UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

517 lines (516 loc) • 20.6 kB
import { createHash } from "node:crypto"; import { statSync } from "node:fs"; import { readFileSync, readdirSync, unlinkSync } from "./descriptor-seat.js"; import { join } from "node:path"; import { ageCutoff, refuseRetentionPolicy } from "../../core/retention-policy.js"; import { readRetentionDeclaration } from "../../core/retention.js"; import { assertSafeToolResultRef, assertToolResultProvenanceMatch, normalizeToolResultProvenance, rekeyToolResultOwner, ToolResultRefConflictError, toolResultRefRefusal, } from "../../core/tool-result-store.js"; import { oneStepRekeyAnswerOf, readIdentityRekeyInput } from "../../core/identity-rekey.js"; import { atomicWriteFile, ensureDir, 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 { HolderLatch } from "../../core/holder-latch.js"; const FILE_TOOL_RESULT_STORE_OPTION_KEYS = optionKeys()({ onCorruptRead: 0, retention: 0 }); export class FileToolResultStore { retention; dir; discloseCorrupt; latch = new HolderLatch(this); constructor(root, options) { const opts = receiveOptions(options, "FileToolResultStore", FILE_TOOL_RESULT_STORE_OPTION_KEYS); this.retention = readRetentionDeclaration("FileToolResultStore.retention", opts.retention); assertAdoptionBootGate(root, "FileToolResultStore"); this.dir = join(root, "tool-results"); this.discloseCorrupt = guardCorruptSink(opts?.onCorruptRead); ensureDir(this.dir); } disclose(path, reason) { this.discloseCorrupt?.({ kind: "file", path, reason }); } locate(ref) { assertSafeToolResultRef(ref); const encoded = encodeRefFilename(ref); return { dir: encoded.folded ? join(this.dir, FOLDED_SUBDIR) : this.dir, stem: sanitizePathComponent(encoded.stem), }; } pathFor(ref, kind = "text") { const { dir, stem } = this.locate(ref); return join(dir, `${stem}${CONTENT_SUFFIX[kind]}`); } refuseOtherKind(ref, incoming, provenance) { const other = incoming === "text" ? "bytes" : "text"; if (modifiedAt(this.pathFor(ref, other)) === undefined) return; throw new ToolResultRefConflictError(ref, this.readOwnerFile(ref, { loud: false }), provenance, { stored: other, incoming }); } ownerPathFor(ref) { const { dir, stem } = this.locate(ref); return join(dir, `${stem}${OWNER_SUFFIX}`); } put(ref, content, provenance) { this.latch.refuse("FileToolResultStore.put"); this.publish(ref, "text", content, provenance, undefined); } putBytes(ref, bytes, provenance, mediaType) { this.latch.refuse("FileToolResultStore.putBytes"); if (!(bytes instanceof Uint8Array)) throw new TypeError(`FileToolResultStore.putBytes: bytes must be a Uint8Array (got ${typeof bytes})`); this.publish(ref, "bytes", bytes, provenance, typeof mediaType === "string" ? mediaType : undefined); } publish(ref, kind, content, provenance, mediaType) { assertSafeToolResultRef(ref); this.refuseOtherKind(ref, kind, provenance); let won; try { writeThenLink(this.pathFor(ref, kind), content); won = true; } catch (err) { if (err.code !== "EEXIST") throw err; won = false; } if (!won) { const stored = this.readOwnerFile(ref, { loud: true }); assertToolResultProvenanceMatch(ref, stored, provenance); return; } if (provenance === undefined) return; try { this.writeOwnerFile(ref, provenance, mediaType); } catch (err) { if (err instanceof ToolResultRefConflictError) unlinkIfAbsentOk(this.pathFor(ref, kind)); throw err; } } ownerOf(ref) { return this.readOwnerFile(ref, { loud: false }); } readOwnerFile(ref, opts) { const ownerPath = (() => { try { return this.ownerPathFor(ref); } catch { return undefined; } })(); if (ownerPath === undefined) return undefined; let raw; try { raw = readFileSync(ownerPath, "utf8"); } catch (err) { if (err.code === "ENOENT") return undefined; if (opts.loud) throw err; this.disclose(ownerPath, `unreadable owner sidecar (${err.code ?? "unknown"}) — read as unowned`); return undefined; } const parsed = parseOwnerRecord(raw); if (parsed !== undefined) return parsed; if (opts.loud) { throw new Error(`tool-result store: owner record for ref ${JSON.stringify(ref)} is present but unreadable — refusing to write over it`); } this.disclose(ownerPath, "not-an-object: owner sidecar is present but is not an owner record — read as unowned"); return undefined; } writeOwnerFile(ref, provenance, mediaType) { try { writeThenLink(this.ownerPathFor(ref), JSON.stringify({ ...normalizeToolResultProvenance(provenance), ref, ...(mediaType !== undefined ? { mediaType } : {}) })); } catch (err) { if (err.code !== "EEXIST") throw err; assertToolResultProvenanceMatch(ref, this.readOwnerFile(ref, { loud: true }), provenance); } } get(ref, opts) { if (toolResultRefRefusal(ref) !== undefined) return undefined; const path = this.pathFor(ref); let full; try { full = readFileSync(path, "utf8"); } catch (err) { if (err.code === "ENOENT") return undefined; throw err; } const offset = Math.min(full.length, Math.max(0, intOr(opts?.offset, 0))); const limit = opts?.limit != null ? Math.max(0, intOr(opts.limit, 0)) : undefined; const content = limit != null ? full.slice(offset, offset + limit) : full.slice(offset); return { content, offset, totalChars: full.length }; } bytesOf(ref) { let path; try { path = this.pathFor(ref, "bytes"); } catch { return undefined; } let size; try { size = statSync(path).size; } catch (err) { if (err.code === "ENOENT") return undefined; throw err; } const record = readOwnerFileAt(this.ownerPathFor(ref)); const mediaType = typeof record === "string" ? undefined : record.mediaType; return { byteLength: size, ...(mediaType !== undefined ? { mediaType } : {}), bytes: () => new Uint8Array(readFileSync(path)) }; } deleteBySession(sessionId) { this.latch.refuse("FileToolResultStore.deleteBySession"); let deleted = 0; let unattributable = 0; for (const dir of [this.dir, join(this.dir, FOLDED_SUBDIR)]) { let names; try { names = readdirSync(dir); } catch (err) { if (err.code === "ENOENT") continue; throw err; } const folded = dir !== this.dir; const listed = new Set(names); for (const name of names) { const part = entryPartOf(name, folded); if (part?.part !== "owner") continue; const owner = readOwnerAt(join(dir, name)); if (owner === "gone") continue; if (owner === "damaged") { unattributable++; continue; } if (owner.sessionId !== sessionId) continue; const { stem } = part; const sidecarPath = join(dir, name); unlinkContentOf(dir, stem); unlinkIfAbsentOk(sidecarPath); const republished = readOwnerAt(sidecarPath); if (republished === "gone") { unlinkContentOf(dir, stem); } else if (republished === "damaged") { unattributable++; } else if (republished.sessionId === sessionId) { unlinkContentOf(dir, stem); unlinkIfAbsentOk(sidecarPath); } deleted++; } for (const name of names) { const part = entryPartOf(name, folded); if (part?.part !== "content") continue; if (listed.has(`${part.stem}${OWNER_SUFFIX}`)) continue; unattributable++; } } return { deleted, unattributable }; } reap(now, opts) { this.latch.refuse("FileToolResultStore.reap"); const cutoff = ageCutoff("FileToolResultStore.reap", now, opts); if (cutoff === undefined) return 0; let removed = 0; for (const [dir, folded] of [[this.dir, false], [join(this.dir, FOLDED_SUBDIR), true]]) { let names; try { names = readdirSync(dir); } catch (err) { if (err.code === "ENOENT") continue; throw err; } const listed = new Set(names); for (const name of names) { const part = entryPartOf(name, folded); if (part === undefined) continue; if (part.part === "owner" && hasContentListed(listed, part.stem)) continue; const path = join(dir, name); const modified = modifiedAt(path); if (modified === undefined || modified >= cutoff) continue; unlinkIfAbsentOk(path); if (part.part === "content") { unlinkIfAbsentOk(join(dir, `${part.stem}${OWNER_SUFFIX}`)); removed++; } } } return removed; } deleteUnattributable(cutoffMs) { this.latch.refuse("FileToolResultStore.deleteUnattributable"); if (typeof cutoffMs !== "number" || !Number.isFinite(cutoffMs)) { refuseRetentionPolicy("FileToolResultStore.deleteUnattributable", "cutoffMs", cutoffMs, "a finite number of milliseconds since the epoch"); } let removed = 0; for (const [dir, folded] of [[this.dir, false], [join(this.dir, FOLDED_SUBDIR), true]]) { let names; try { names = readdirSync(dir); } catch (err) { if (err.code === "ENOENT") continue; throw err; } const listed = new Set(names); for (const name of names) { const part = entryPartOf(name, folded); if (part === undefined || part.part === "owner") continue; if (part.part === "content" && listed.has(`${part.stem}${OWNER_SUFFIX}`)) continue; const path = join(dir, name); const modified = modifiedAt(path); if (modified === undefined || modified >= cutoffMs) continue; if (part.part === "staging") { unlinkIfAbsentOk(path); continue; } if (readOwnerAt(join(dir, `${part.stem}${OWNER_SUFFIX}`)) !== "gone") continue; unlinkIfAbsentOk(path); removed++; } } return removed; } listBySession(sessionId) { const entries = []; let unattributable = 0; let unaddressable = 0; for (const dir of [this.dir, join(this.dir, FOLDED_SUBDIR)]) { let names; try { names = readdirSync(dir); } catch (err) { if (err.code === "ENOENT") continue; throw err; } const folded = dir !== this.dir; const listed = new Set(names); for (const name of names) { const part = entryPartOf(name, folded); if (part?.part !== "owner") continue; const owner = readOwnerFileAt(join(dir, name)); if (owner === "gone") continue; if (owner === "damaged") { unattributable++; continue; } if (owner.provenance.sessionId !== sessionId) continue; const ref = this.refOfEntry(dir, part.stem, owner.ref); if (ref === undefined) unaddressable++; else entries.push({ ref, provenance: owner.provenance }); } for (const name of names) { const part = entryPartOf(name, folded); if (part?.part !== "content" || listed.has(`${part.stem}${OWNER_SUFFIX}`)) continue; unattributable++; } } return { entries, unattributable, unaddressable }; } async rekeyIdentity(input) { this.latch.refuse("FileToolResultStore.rekeyIdentity"); return rekeyToolResultDirectory(this.dir, input); } refOfEntry(dir, stem, stated) { const lies = (ref) => { try { const at = this.locate(ref); return at.dir === dir && at.stem === stem; } catch { return false; } }; if (stated !== undefined) return lies(stated) ? stated : undefined; return dir === this.dir && lies(stem) ? stem : undefined; } } export function rekeyToolResultDirectory(storeDir, input, onUnrekeyable) { const { mode, ...map } = readIdentityRekeyInput("ToolResultStore.rekeyIdentity", input); return refileToolResultDirectory(storeDir, mode, (owner) => rekeyToolResultOwner(owner, map), onUnrekeyable); } export function refileToolResultDirectory(storeDir, mode, judge, onUnrekeyable) { const verdicts = []; for (const [dir, folded] of [[storeDir, false], [join(storeDir, FOLDED_SUBDIR), true]]) { let names; try { names = readdirSync(dir); } catch (err) { if (err.code === "ENOENT") continue; throw err; } for (const name of names) { if (entryPartOf(name, folded)?.part !== "owner") continue; const path = join(dir, name); let raw; try { raw = readFileSync(path, "utf8"); } catch (err) { const code = err.code; if (code === "ENOENT") continue; throw new Error(`tool-result store re-key: the owner record ${path} could not be read (${code ?? err.name}) — refusing rather than leave an entry this move cannot judge; repair it, then run the step again`, { cause: err }); } const owner = parseOwnerFile(raw); if (owner === undefined) continue; const verdict = judge(owner.provenance); if (verdict.kind === "unrekeyable") onUnrekeyable?.(owner.ref ?? name); if (mode === "leave" && verdict.kind === "rekeyed") { const record = { ...owner.members }; delete record.principal; delete record.isolationScope; const { principal, isolationScope } = verdict.owner; atomicWriteFile(dir, path, JSON.stringify({ ...record, ...(principal !== undefined ? { principal } : {}), ...(isolationScope !== undefined ? { isolationScope } : {}) })); } verdicts.push(verdict); } } return oneStepRekeyAnswerOf(mode, verdicts); } const CONTENT_SUFFIX = { text: ".txt", bytes: ".bin" }; const CONTENT_KINDS = Object.keys(CONTENT_SUFFIX); const OWNER_SUFFIX = ".owner.json"; const STAGING_NAME = /^(.+)\.\d+\.[0-9a-f]{12}\.tmp$/; export function entryPartOf(name, folded) { const staged = STAGING_NAME.exec(name); const published = staged !== null ? staged[1] : name; const read = (() => { if (published.endsWith(OWNER_SUFFIX)) return { stem: published.slice(0, -OWNER_SUFFIX.length) }; const kind = CONTENT_KINDS.find((k) => published.endsWith(CONTENT_SUFFIX[k])); return kind === undefined ? undefined : { stem: published.slice(0, -CONTENT_SUFFIX[kind].length), kind }; })(); if (read === undefined || !isEncodedStem(read.stem, folded)) return undefined; if (staged !== null) return { stem: read.stem, part: "staging" }; return read.kind !== undefined ? { stem: read.stem, part: "content", kind: read.kind } : { stem: read.stem, part: "owner" }; } function hasContentListed(listed, stem) { return CONTENT_KINDS.some((k) => listed.has(`${stem}${CONTENT_SUFFIX[k]}`)); } function unlinkContentOf(dir, stem) { for (const k of CONTENT_KINDS) unlinkIfAbsentOk(join(dir, `${stem}${CONTENT_SUFFIX[k]}`)); } function parseOwnerRecord(raw) { return parseOwnerFile(raw)?.provenance; } function parseOwnerFile(raw) { const parsed = (() => { try { return JSON.parse(raw); } catch { return undefined; } })(); if (typeof parsed === "object" && parsed !== null) { const { sessionId, taskId, principal, isolationScope, ref, mediaType } = parsed; const principalOk = principal === undefined || principal === null || (typeof principal === "string" && principal !== ""); const scopeOk = isolationScope === undefined || (typeof isolationScope === "string" && isolationScope !== ""); if (typeof sessionId === "string" && (taskId === undefined || typeof taskId === "string") && principalOk && scopeOk) { const provenance = normalizeToolResultProvenance({ sessionId, taskId, principal: principal, isolationScope: isolationScope }); return { provenance, ...(typeof ref === "string" ? { ref } : {}), ...(typeof mediaType === "string" ? { mediaType } : {}), members: Object.fromEntries(Object.entries(parsed)) }; } } return undefined; } function readOwnerFileAt(path) { let raw; try { raw = readFileSync(path, "utf8"); } catch (err) { return err.code === "ENOENT" ? "gone" : "damaged"; } return parseOwnerFile(raw) ?? "damaged"; } function readOwnerAt(path) { const read = readOwnerFileAt(path); return typeof read === "string" ? read : read.provenance; } function modifiedAt(path) { try { return statSync(path).mtimeMs; } catch (err) { if (err.code === "ENOENT") return undefined; throw err; } } function unlinkIfAbsentOk(path) { try { unlinkSync(path); } catch (err) { if (err.code !== "ENOENT") throw err; } } const NATIVE_FILENAME_CHARSET = /^[A-Za-z0-9_.-]+$/; const FOLDED_SUBDIR = "folded-v2"; const MAX_FILENAME_CHARS = 180; function encodeRefFilename(ref) { if (ref.length <= MAX_FILENAME_CHARS && NATIVE_FILENAME_CHARSET.test(ref)) return { folded: false, stem: ref }; const base = ref.replace(/[^A-Za-z0-9_.-]/g, "-").slice(0, 64); return { folded: true, stem: `${base || "ref"}-${createHash("sha256").update(Buffer.from(ref, "utf16le")).digest("hex")}` }; } const FOLDED_STEM = /^[A-Za-z0-9_.-]{1,64}-[0-9a-f]{64}$/; function isEncodedStem(stem, folded) { return folded ? FOLDED_STEM.test(stem) : stem.length <= MAX_FILENAME_CHARS && NATIVE_FILENAME_CHARSET.test(stem); } function intOr(x, fallback) { return Number.isFinite(x) ? Math.floor(x) : fallback; }