@sema-agent/core
Version:
Stateless, task-oriented AI agent core
82 lines (81 loc) • 4.66 kB
JavaScript
import { closeSync, writeFileSync } from "node:fs";
import { link, unlink } from "node:fs/promises";
import { join } from "node:path";
import { openExclusiveTemp } from "../exclusive-temp.js";
import { MEMORY_INDEX_FILENAME } from "./entry-scan.js";
import { parseEntryFile, serializeEntryFile } from "./frontmatter.js";
import { isStatedDate, readV2HeaderHints, STATED_HEADER_FIELDS } from "./header-hints.js";
import { MEMORY_FILENAME_SEGMENT_RE } from "./scan.js";
export function memoryEntryPortOf(session) {
return async (draft) => {
const s = session();
return s === undefined ? { kind: "unavailable", reason: "this leg mounted no engine memory" } : s.createEntry(draft);
};
}
const refused = (code, reason) => ({ kind: "refused", code, reason: reason.slice(0, 2000) });
const refusedStated = (spec) => refused("invalid_header", `\`${spec.field}\` must be ${spec.type}. Nothing was written.`);
const LONE_SURROGATE_RE = /[\uD800-\uDFFF]/u;
export async function createMemoryEntry(o) {
const { name, description, type, body } = o.draft;
if (typeof name !== "string" || !MEMORY_FILENAME_SEGMENT_RE.test(name) || name.startsWith(".") || `${name}.md`.toLowerCase() === MEMORY_INDEX_FILENAME.toLowerCase()) {
return refused("invalid_name", `"${String(name).slice(0, 80)}" is not an entry name: use one short kebab-case word group (letters, digits, '.', '_' and '-' only, not starting with '.', and not MEMORY). Nothing was written.`);
}
if (typeof description !== "string" || typeof type !== "string" || typeof body !== "string")
return refused("invalid_header", "`description`, `type` and `body` must be text. Nothing was written.");
const stated = [];
for (const spec of STATED_HEADER_FIELDS) {
const raw = o.draft[spec.field];
if (raw === undefined)
continue;
if (typeof raw !== "string" || LONE_SURROGATE_RE.test(raw))
return refusedStated(spec);
stated.push({ field: spec, value: raw.trim() });
}
const extra = stated.map((s) => `${s.field.line}: ${s.value}`);
const header = { name, description: description.trim(), type: type.trim(), ...(extra.length > 0 ? { extra } : {}) };
const target = join(o.home ?? o.domain, `${name}.md`);
const content = serializeEntryFile({ frontmatter: header, body });
const read = parseEntryFile(content).frontmatter;
for (const field of ["description", "type"]) {
if (header[field] === "" || read[field] !== header[field])
return refused("invalid_header", `\`${field}\` must be one non-empty line of plain text that the entry's header holds as written. Nothing was written.`);
}
const hints = readV2HeaderHints(read.extra);
for (const s of stated) {
if (hints[s.field.field] !== s.value || (s.field.field === "lastConfirmedAt" && !isStatedDate(s.value)))
return refusedStated(s.field);
}
const verdict = await o.gate({ key: target, content });
if (verdict !== undefined && verdict.ok === false)
return refused(verdict.code.slice(0, 40), `the memory write gate refused it: ${verdict.reason.slice(0, 1500)}`);
if (o.home === null)
return refused("read_only_layering", "this session has no memory write home. Nothing was written.");
if (o.boundAtMount?.(target) === true)
return refused("exists", `an entry named "${name.slice(0, 80)}" already exists in this session's memory (it stood there when the session began, and keeps the name even if it was renamed or removed since); entries are only created here, never changed. Choose another name. Nothing was written.`);
let staged;
try {
staged = openExclusiveTemp(target);
}
catch (err) {
return refused("write_failed", `the entry file could not be written (${(err.code ?? "an unexpected error").slice(0, 40)}). Nothing was written.`);
}
try {
try {
writeFileSync(staged.fd, content);
}
finally {
closeSync(staged.fd);
}
await link(staged.path, target);
}
catch (err) {
const code = err.code;
if (code === "EEXIST")
return refused("exists", `an entry named "${name.slice(0, 80)}" already exists in this session's memory; entries are only created here, never changed. Choose another name. Nothing was written.`);
return refused("write_failed", `the entry file could not be written (${(code ?? "an unexpected error").slice(0, 40)}). Nothing was written.`);
}
finally {
await unlink(staged.path).catch(() => undefined);
}
return { kind: "created", path: target };
}