@sema-agent/core
Version:
Stateless, task-oriented AI agent core
43 lines (42 loc) • 2.19 kB
JavaScript
import { catalogMessage, SEMA_DEFAULT_CATALOG } from "./catalog/index.js";
import { ENGINE_MESSAGES } from "./catalog/engine.js";
import { ENVIRONMENT_MESSAGES } from "./catalog/environment.js";
import { EVENT_MESSAGES } from "./catalog/events.js";
import { PROMPT_LOCALES } from "./catalog/schema.js";
import { renderingOf } from "./select.js";
import { fillSlots, slotNames } from "./slots.js";
const READABLE = new Set([...ENVIRONMENT_MESSAGES, ...ENGINE_MESSAGES, ...EVENT_MESSAGES].map((m) => m.id));
for (const id of READABLE) {
const m = catalogMessage(id);
if (m.variants.length !== 1 || Object.keys(m.variants[0].when).length > 0)
throw new Error(`engine text "${id}": a message the engine mints has one unconditional variant`);
}
const quoted = (names) => [...names].map((n) => `"${n}"`).join(", ");
const readingIn = (locale, replaced) => (id, slots = {}) => {
if (!READABLE.has(id))
throw new Error(`engine text: "${id}" is not a message the engine mints`);
const over = replaced?.current.get(id);
const text = over ?? renderingOf(SEMA_DEFAULT_CATALOG, id, catalogMessage(id).variants[0], locale);
if (over === undefined) {
const carried = new Set(slotNames(text));
const unknown = Object.keys(slots).filter((name) => !carried.has(name));
if (unknown.length > 0)
throw new Error(`engine text "${id}": no slot ${quoted(unknown)} (it carries ${carried.size > 0 ? quoted(carried) : "none"})`);
}
const filled = fillSlots(text, (name) => (Object.prototype.hasOwnProperty.call(slots, name) ? slots[name] : undefined));
if (filled.missing.length > 0)
throw new Error(`engine text "${id}": slot ${quoted(new Set(filled.missing))} has no value`);
return filled.text;
};
const READINGS = new Map();
export function engineTextFor(locale = "canonical", replaced) {
if (replaced !== undefined)
return readingIn(locale, replaced);
let reading = READINGS.get(locale);
if (reading === undefined)
READINGS.set(locale, (reading = readingIn(locale)));
return reading;
}
export function shippedReadings() {
return PROMPT_LOCALES.map((l) => engineTextFor(l));
}