@sema-agent/core
Version:
Stateless, task-oriented AI agent core
150 lines (149 loc) • 8.73 kB
JavaScript
import { modPackageDigest } from "./digest.js";
import { expandModPattern, expandOnSide, MOD_EVENT_TABLE } from "./events.js";
import { modsInvalid } from "./registration.js";
export const MOD_PACKAGE_FILES = Object.freeze({ plugin: ".claude-plugin/plugin.json", hooks: "hooks/hooks.json" });
const SOURCE_MEMBERS = ["plugin", "hooks", "readModule", "side", "expectDigest"];
const SHA256_HEX = /^[0-9a-f]{64}$/;
const HOST_FACT = "which is the host's to give (the seat, tier, provenance, options and budget are never read from a package)";
const HOST_FACTS = Object.freeze({ tier: HOST_FACT, provenance: HOST_FACT, seat: HOST_FACT, options: HOST_FACT, budgetMs: HOST_FACT });
const PLUGIN_SHAPE = Object.freeze({ file: MOD_PACKAGE_FILES.plugin, takes: Object.freeze(["name", "version", "description", "author"]), refuses: HOST_FACTS });
const HOOKS_SHAPE = Object.freeze({
file: MOD_PACKAGE_FILES.hooks,
takes: Object.freeze(["modules", "contract", "uses", "description"]),
refuses: Object.freeze({ ...HOST_FACTS, surface: "which names a surface module: a surface module is mounted by the client that renders it, never through hooks.json" }),
});
const USES_SHAPE = Object.freeze({ file: MOD_PACKAGE_FILES.hooks, takes: Object.freeze(["events", "calls"]), refuses: Object.freeze({}) });
const MODULE_MEMBER = `${MOD_PACKAGE_FILES.hooks}: modules[0]`;
const PATH_RULE = 'a hooks module is named by one path relative to hooks.json: "/"-separated, an optional leading "./", no empty, "." or ".." segment, no "\\" or ":", ending ".mjs"';
export async function readModPackage(source) {
const { plugin, hooks, readModule, side, expectDigest } = sourceOf(source);
const unread = [];
const pluginJson = jsonRecord(plugin, PLUGIN_SHAPE, unread);
const hooksJson = jsonRecord(hooks, HOOKS_SHAPE, unread);
const modulePath = modulePathOf(own(hooksJson, "modules"));
const uses = usesOn(own(hooksJson, "uses"), side, unread);
const answered = await readModule(modulePath);
if (!isBytes(answered))
throw modsInvalid(`${MODULE_MEMBER}: the host's readModule answered ${kind(answered)}; it answers the module's bytes`);
const module = new Uint8Array(answered);
const digest = modPackageDigest(plugin, hooks, module);
if (expectDigest !== undefined && digest !== expectDigest) {
throw Object.assign(modsInvalid(`its bytes are not the ones the host expected (digest ${digest}, expected ${expectDigest}); nothing of it is handed on`), {
detail: Object.freeze({ digest: Object.freeze({ expected: expectDigest, actual: digest }) }),
});
}
return Object.freeze({
name: own(pluginJson, "name"),
uses,
contract: own(hooksJson, "contract"),
unread: Object.freeze(unread.map((u) => Object.freeze(u))),
modulePath,
module,
digest,
});
}
function sourceOf(source) {
const form = `it is { ${SOURCE_MEMBERS.join(", ")} }`;
if (typeof source !== "object" || source === null || Array.isArray(source))
throw modsInvalid(`the package reader's argument is ${kind(source)}; ${form}`);
for (const k of Reflect.ownKeys(source)) {
if (typeof k === "symbol" || !SOURCE_MEMBERS.includes(k)) {
throw modsInvalid(`the package reader's argument carries ${typeof k === "symbol" ? "a symbol-keyed member" : JSON.stringify(k).slice(0, 66)}, a member it does not take; ${form}`);
}
}
const plugin = Reflect.get(source, "plugin");
const hooks = Reflect.get(source, "hooks");
const readModule = Reflect.get(source, "readModule");
const side = Reflect.get(source, "side");
if (!isBytes(plugin) || !isBytes(hooks))
throw modsInvalid(`the package reader's plugin and hooks are the two manifests' bytes (a Uint8Array each)`);
if (typeof readModule !== "function")
throw modsInvalid(`the package reader's readModule is ${kind(readModule)}; it is a function that reads the hooks module`);
if (side !== "engine" && side !== "surface")
throw modsInvalid(`the package reader's side is ${kind(side)}; it is the bus the host reads the package for, "engine" or "surface"`);
const expectDigest = Reflect.get(source, "expectDigest");
if (expectDigest !== undefined && (typeof expectDigest !== "string" || !SHA256_HEX.test(expectDigest))) {
throw modsInvalid(`the package reader's expectDigest is ${typeof expectDigest === "string" ? `a string of ${expectDigest.length} characters` : kind(expectDigest)}; it is a package digest, a sha256 in lowercase hex (64 characters)`);
}
return { plugin: new Uint8Array(plugin), hooks: new Uint8Array(hooks), readModule: readModule, side, expectDigest };
}
function isBytes(v) {
return ArrayBuffer.isView(v) && Object.prototype.toString.call(v) === "[object Uint8Array]";
}
function own(record, key) {
return Object.hasOwn(record, key) ? record[key] : undefined;
}
function jsonRecord(bytes, shape, unread) {
const { file, takes, refuses } = shape;
let parsed;
try {
parsed = JSON.parse(new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes));
}
catch {
throw modsInvalid(`${file}: is not JSON`);
}
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
throw modsInvalid(`${file}: is ${kind(parsed)}; it is a JSON object`);
unreadOf(parsed, { file, takes, refuses }, "", unread);
return parsed;
}
function unreadOf(record, shape, prefix, unread) {
const { file, takes, refuses } = shape;
for (const k of Object.keys(record)) {
if (takes.includes(k))
continue;
const why = Object.hasOwn(refuses, k) ? refuses[k] : undefined;
if (why !== undefined)
throw modsInvalid(`${file}${prefix === "" ? "" : ` ${prefix.slice(0, -1)}`}: carries "${k}", ${why}`);
unread.push({ file, name: `${prefix}${k}` });
}
}
function modulePathOf(modules) {
if (!Array.isArray(modules) || modules.length !== 1 || typeof modules[0] !== "string")
throw modsInvalid(`${MOD_PACKAGE_FILES.hooks}: modules is ${kind(modules)}; it lists exactly one path, relative to hooks.json`);
const given = modules[0];
const rest = given.startsWith("./") ? given.slice(2) : given;
const fits = rest.endsWith(".mjs") && rest.split("/").every((s) => s !== "" && s !== "." && s !== ".." && !s.includes("\\") && !s.includes(":"));
if (!fits)
throw modsInvalid(`${MODULE_MEMBER} is not a path this reader takes; ${PATH_RULE}`);
return `hooks/${rest}`;
}
function usesOn(uses, side, unread) {
const at = `${MOD_PACKAGE_FILES.hooks}: uses`;
if (typeof uses !== "object" || uses === null || Array.isArray(uses))
throw modsInvalid(`${at} is ${kind(uses)}; it declares { events, calls }, each a list of event names`);
unreadOf(uses, USES_SHAPE, "uses.", unread);
let ownSide = false;
const lists = { events: [], calls: [] };
for (const field of ["events", "calls"]) {
const list = Object.hasOwn(uses, field) ? Reflect.get(uses, field) : undefined;
if (!Array.isArray(list))
throw modsInvalid(`${at}.${field} is ${kind(list)}; it is a list of event names`);
list.forEach((item, i) => {
const where = `${at}.${field}[${i}]`;
if (typeof item !== "string")
throw modsInvalid(`${where} is ${kind(item)}; it is an event name or a "<prefix>.*" pattern`);
const selected = expandOnSide(item, side);
if ("refusal" in selected) {
throw modsInvalid("refusal" in expandModPattern(item)
? `${where} is not an event name, or a "<prefix>.*" pattern, that selects a name the kernel knows`
: `${where} selects only the ${side === "engine" ? "surface" : "engine"} side's names, and the host reads this package for the ${side} bus`);
}
if (selected.names.some((n) => MOD_EVENT_TABLE[n].side === side))
ownSide = true;
lists[field].push(item);
});
}
if (!ownSide)
throw modsInvalid(`${at} selects no name of the ${side} side's own — only names both buses read, or none — so it does not say it is a package for the ${side} bus; a package declares one ${side} event or method at least`);
return Object.freeze({ events: Object.freeze(lists.events), calls: Object.freeze(lists.calls) });
}
export function kind(v) {
if (v === undefined)
return "absent";
if (v === null)
return "null";
if (Array.isArray(v))
return `a list of ${v.length}`;
return typeof v === "number" || typeof v === "boolean" ? String(v) : `a ${typeof v}`;
}