UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

381 lines (380 loc) • 19.6 kB
import { posix } from "node:path"; import { types } from "node:util"; import { expandOnSide, MOD_PACKAGE_FILES, stationOn, } from "./kernel/index.js"; import { kind } from "./kernel/package-reader.js"; import { modsInvalid } from "./kernel/registration.js"; import { matcherViolation, MODS_VALUE_DEPTH } from "./kernel/site-rules.js"; import { describeThrown } from "../tool-policy.js"; export const REFERENCE_MODULE_MAX_BYTES = 1024 * 1024; const PLUGIN = MOD_PACKAGE_FILES.plugin; const HOOKS = MOD_PACKAGE_FILES.hooks; const MODULE_MEMBER = `${HOOKS}: modules[0]`; const row = (n) => `(compatibility row ${n})`; const MODULE_SUFFIXES = Object.freeze([".js", ".mjs", ".cjs"]); const TYPESCRIPT_SUFFIXES = Object.freeze([".ts", ".tsx", ".mts", ".cts", ".jsx"]); const isEmptyList = (v) => Array.isArray(v) && v.length === 0; const isEmptyRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v) && Object.keys(v).length === 0; const namesNothing = (v) => v === null || v === "" || isEmptyList(v) || isEmptyRecord(v); const never = () => false; const COMPONENT_WHY = "which names a component (commands, agents, skills, styles, themes, workflows, servers, monitors, channels, settings) — phase one loads a reference-form package's hooks module alone"; const component = (key) => Object.freeze({ key, row: "16", reads: namesNothing, why: COMPONENT_WHY }); const PLUGIN_ROWS = Object.freeze([ Object.freeze({ key: "hooks", row: "13", reads: never, why: "which names hooks of the manifest's own — phase one loads a reference-form package's hooks module alone" }), Object.freeze({ key: "userConfig", row: "14", reads: never, why: "which asks the person for values — phase one has no seat that asks them" }), Object.freeze({ key: "dependencies", row: "15b", reads: isEmptyList, why: "which names other plugins it needs — phase one loads one package by itself (an empty list is read)" }), ...["commands", "agents", "skills", "outputStyles", "themes", "workflows", "mcpServers", "lspServers", "monitors", "channels", "settings"].map(component), ]); const HOOKS_ROWS = Object.freeze([ Object.freeze({ key: "hooks", row: "12", reads: isEmptyRecord, why: "which holds command hooks — phase one loads the hooks module alone (an empty {} is read)" }), Object.freeze({ key: "surface", row: "19", reads: never, why: "which names a surface module: a surface module is mounted by the client that renders it, never through hooks.json" }), ]); const PLUGIN_TAKES = Object.freeze(["name", "version", "description", "author", "$schema", "defaultEnabled", ...PLUGIN_ROWS.map((r) => r.key)]); const HOOKS_TAKES = Object.freeze(["modules", "description", "$schema", ...HOOKS_ROWS.map((r) => r.key)]); export const REFERENCE_COMPONENT_FOLDERS = Object.freeze(["commands", "agents", "skills", "output-styles", "themes", "monitors", "workflows"]); export const REFERENCE_COMPONENT_FILES = Object.freeze([".mcp.json", ".lsp.json", "settings.json"]); export function readReferenceManifests(plugin, hooksJson) { const pluginJson = jsonObject(plugin, PLUGIN); judgeRows(pluginJson, PLUGIN, PLUGIN_ROWS); judgeRows(hooksJson, HOOKS, HOOKS_ROWS); const name = own(pluginJson, "name"); if (typeof name !== "string") throw modsInvalid(`${PLUGIN}: name is ${kind(name)}; it names the plugin`); const modulePath = referenceModulePath(own(hooksJson, "modules")); const unread = [...unreadOf(pluginJson, PLUGIN, PLUGIN_TAKES), ...unreadOf(hooksJson, HOOKS, HOOKS_TAKES)]; return Object.freeze({ name, modulePath, unread: Object.freeze(unread) }); } export function componentFolderRefusal(folder) { return modsInvalid(`${folder}/: holds a component the reference loads from that folder by default — phase one loads a reference-form package's hooks module alone ${row("16")}`); } export function judgeComponentFile(file, bytes) { const text = new TextDecoder("utf-8").decode(bytes); if (text.trim() === "") return; let parsed; try { parsed = JSON.parse(text); } catch { parsed = undefined; } if (isEmptyRecord(parsed)) return; throw modsInvalid(`${file}: configures a component the reference reads from that file by default (or cannot be read as JSON) — phase one loads a reference-form package's hooks module alone ${row("16")}`); } export function judgeReferenceModule(bytes) { if (bytes.byteLength > REFERENCE_MODULE_MAX_BYTES) { throw modsInvalid(`${MODULE_MEMBER}: is ${bytes.byteLength} bytes; a hooks module is at most ${REFERENCE_MODULE_MAX_BYTES} bytes (1 MiB) ${row("57")}`); } } function referenceModulePath(modules) { if (!Array.isArray(modules) || modules.length !== 1) throw modsInvalid(`${HOOKS}: modules is ${kind(modules)}; it lists the package's one hooks module ${row("18")}`); const given = modules[0]; if (typeof given !== "string" || given === "" || given.startsWith("/") || given.includes("\\") || given.includes(":")) { throw modsInvalid(`${MODULE_MEMBER} is not a path this reader takes; a hooks module is named by one "/"-separated path relative to hooks.json, with no "\\" or ":"`); } const path = posix.join(posix.dirname(HOOKS), given); if (path === "." || path === ".." || path.startsWith("../")) throw modsInvalid(`${MODULE_MEMBER}: resolves outside the package`); const suffix = posix.extname(path); if (TYPESCRIPT_SUFFIXES.includes(suffix)) throw modsInvalid(`${MODULE_MEMBER}: is TypeScript-family source, which phase one does not compile; name a module of plain JavaScript ${row("3")}`); if (!MODULE_SUFFIXES.includes(suffix)) throw modsInvalid(`${MODULE_MEMBER}: is not named like code; a hooks module ends ${MODULE_SUFFIXES.join(", ")} and is read as an ES module ${row("2")}`); return path; } function jsonObject(bytes, file) { 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`); return parsed; } function judgeRows(record, file, rows) { for (const r of rows) { if (Object.hasOwn(record, r.key) && !r.reads(record[r.key])) throw modsInvalid(`${file}: carries "${r.key}", ${r.why} ${row(r.row)}`); } } function unreadOf(record, file, takes) { const names = new Set(Object.keys(record)); for (const k of takes) names.delete(k); return [...names].map((name) => Object.freeze({ file, name })); } export const REFERENCE_LOAD_MS = 10_000; export function referenceOptions(options) { if (options === undefined) return Object.freeze({}); return dataCopy(options, new Set(), 0); } function dataCopy(v, path, depth) { if (v === null || v === undefined || typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "bigint") return v; if (typeof v !== "object") throw optionsRefusal(`hold ${typeof v === "function" ? "a function" : `a ${typeof v}`}`); if (types.isProxy(v)) throw optionsRefusal("hold a Proxy"); if (path.has(v)) throw optionsRefusal("hold a cycle"); if (depth >= MODS_VALUE_DEPTH) throw optionsRefusal(`nest deeper than ${MODS_VALUE_DEPTH} levels`); const proto = Object.getPrototypeOf(v); const list = Array.isArray(v); if (list ? proto !== Array.prototype : proto !== Object.prototype && proto !== null) throw optionsRefusal("hold an object that is not a plain record or list"); if (Object.getOwnPropertySymbols(v).length > 0) throw optionsRefusal("hold a symbol-keyed member"); const names = Object.getOwnPropertyNames(v); if (list && names.length !== v.length + 1) throw optionsRefusal("hold a list with a hole or a member beside its items"); path.add(v); const out = list ? [] : proto === null ? Object.create(null) : {}; for (const name of list ? names.slice(0, -1) : names) { const d = Object.getOwnPropertyDescriptor(v, name); if (d === undefined || d.get !== undefined || d.set !== undefined) throw optionsRefusal("hold an accessor"); Object.defineProperty(out, name, { value: dataCopy(d.value, path, depth + 1), enumerable: d.enumerable === true, writable: true, configurable: true }); } path.delete(v); return Object.freeze(out); } function optionsRefusal(what) { return modsInvalid(`the host's options ${what}; a reference-form package's options are data, copied and frozen before its code runs ${row("56")}`); } export function referenceImportRefusal(err, said) { const specifier = unresolvedSpecifier(err); if (specifier !== undefined) { const relative = specifier.startsWith("./") || specifier.startsWith("../") || specifier.startsWith("/"); return modsInvalid(relative ? `${MODULE_MEMBER}: imports another file of the package; a hooks module is imported from its own bytes, so phase one takes one self-contained file ${row("4")}` : `${MODULE_MEMBER}: imports a package by name (claude-code or another); a hooks module is imported from its own bytes, with nothing to resolve a package from ${row("5")}`); } return modsInvalid(`${MODULE_MEMBER}: could not be imported (${said}); a hooks module is imported from its own bytes, so it is one self-contained file`); } function unresolvedSpecifier(err) { if (!(err instanceof Error) || types.isProxy(err)) return undefined; const code = Object.getOwnPropertyDescriptor(err, "code")?.value; const message = Object.getOwnPropertyDescriptor(err, "message")?.value; if (code !== "ERR_UNSUPPORTED_RESOLVE_REQUEST" || typeof message !== "string") return undefined; return /specifier "([^"]*)"/.exec(message)?.[1]; } export async function recordReferencePackage(load) { const name = load.manifests.name; const recorder = referenceRecorder(name); const startedAt = performance.now(); let ranOut = false; const outOfTime = () => ranOut || performance.now() - startedAt >= REFERENCE_LOAD_MS; let clock; const expired = new Promise((settle) => { clock = setTimeout(() => { ranOut = true; recorder.seal(); settle("expired"); }, REFERENCE_LOAD_MS); }); const run = (async () => { const ns = await load.importModule(); if (outOfTime()) return "expired"; const register = typeof ns === "object" && ns !== null ? Reflect.get(ns, "register") : undefined; if (typeof register !== "function") throw modsInvalid(`${name}: the hooks module exports no register function; a hooks module exports register(on, options)`); try { await Reflect.apply(register, undefined, [recorder.on, load.options]); } catch (err) { throw recorder.problem() ?? modsInvalid(`${name}: register() threw: ${describeThrown(err)}`); } finally { recorder.seal(); } return outOfTime() ? "expired" : "settled"; })(); run.catch(() => undefined); let ended; try { ended = await Promise.race([run, expired]); } finally { clearTimeout(clock); recorder.seal(); } const problem = recorder.problem(); if (problem !== undefined) throw problem; if (ended === "expired") throw modsInvalid(`${name}: not loaded within ${REFERENCE_LOAD_MS}ms`); return Object.freeze({ form: "reference", name, root: load.root, digest: load.digest, options: load.options, hooks: recorder.hooks(), uses: Object.freeze({ events: Object.freeze([...new Set(recorder.hooks().map((h) => h.pattern))]), calls: Object.freeze([]) }), unread: load.manifests.unread, }); } function spelled(pattern) { return typeof pattern === "string" && /^[A-Za-z0-9._:*!-]{1,80}$/.test(pattern) ? `"${pattern}"` : typeof pattern === "string" ? "a pattern" : kind(pattern); } const isGeneratorFunction = (fn) => { const tag = Object.prototype.toString.call(fn); return tag === "[object AsyncGeneratorFunction]" || tag === "[object GeneratorFunction]"; }; function patternRefusal(pattern) { if (typeof pattern !== "string") return `takes an event name or a "<prefix>.*" pattern, not ${kind(pattern)}`; if (pattern === "*" || pattern.startsWith("!")) return `selects every event or negates a pattern, which phase one does not take; name the events ${row("27")}`; if (pattern === "ui.*" || pattern.startsWith("ui.")) return `is a ui hook, which phase one does not take: the engine renders no surface ${row("32")}`; const selected = expandOnSide(pattern, "engine"); if ("refusal" in selected) return selected.refusal; if (!selected.names.some((n) => stationOn(n, "engine") !== undefined)) return `selects no event the engine raises in this version ${row("30")}`; return undefined; } function referenceRecorder(name) { let sealed = false; let problem; let frozen; const recorded = []; const once = new Set(); const fail = (why) => { const err = modsInvalid(`${name}: ${why}`); problem ??= err; throw err; }; const afterSettled = (what) => modsInvalid(`${name}: ${what} was called after register() settled`); const on = (...args) => { if (sealed) throw afterSettled("on()"); const [pattern, a, b] = args; const withMatcher = typeof a !== "function"; const hook = withMatcher ? b : a; const said = `on(${spelled(pattern)})`; if (typeof hook !== "function" || args.length !== (withMatcher ? 3 : 2)) fail(`${said} takes (pattern, hook) or (pattern, matcher, hook); the hook is a function`); if (isGeneratorFunction(hook)) fail(`${said}: the hook is a generator function, a streaming hook phase one does not take ${row("28")}`); const why = patternRefusal(pattern); if (why !== undefined) fail(`${said} ${why}`); const p = pattern; let matcher; if (withMatcher) { const copy = typeof a === "object" && a !== null && !Array.isArray(a) ? Object.freeze(Object.fromEntries(Object.entries(a))) : a; const bad = matcherViolation(copy); if (bad !== undefined) fail(`${said}: ${bad} ${row("38")}`); matcher = copy; } if (matcher === undefined || p.endsWith(".*")) { if (once.has(p)) fail(`${said} registered twice`); once.add(p); } const entry = { pattern: p, matcher, hook: hook, caught: undefined }; recorded.push(entry); return Object.freeze({ catch: (fn) => { if (sealed) throw afterSettled(`${said}.catch()`); if (typeof fn !== "function") fail(`${said}.catch() takes a function`); if (isGeneratorFunction(fn)) fail(`${said}.catch(): a generator function is a streaming hook phase one does not take ${row("28")}`); if (entry.caught !== undefined) fail(`${said}.catch() was called a second time; a hook takes one .catch`); entry.caught = fn; }, }); }; return { on, seal: () => { sealed = true; }, problem: () => problem, hooks: () => (frozen ??= Object.freeze(recorded.map((r) => Object.freeze({ pattern: r.pattern, ...(r.matcher !== undefined ? { matcher: r.matcher } : {}), hook: r.hook, ...(r.caught !== undefined ? { catch: r.caught } : {}) })))), }; } export function referenceReplay(record) { const mounts = referenceMounts(record); return (on, options) => { if (!Object.is(options, record.options)) { throw modsInvalid(`${record.name}: register() was handed options other than the ones its package was recorded with — a reference-form package's register ran once, at its load, with those`); } if (typeof on !== "function") throw modsInvalid(`${record.name}: register() was handed no on() function`); for (const m of mounts) { const opts = m.onCatch !== undefined ? [{ catch: m.onCatch }] : []; Reflect.apply(on, undefined, m.matcher !== undefined ? [m.pattern, m.matcher, m.fn, ...opts] : [m.pattern, m.fn, ...opts]); } }; } function referenceMounts(record) { const dollar = referenceDollar(record); const out = []; for (const h of record.hooks) { const hook = h.hook; const pkgCatch = h.catch; const fn = (_$, e, next) => hook(dollar, e, onceNext(record.name, next)); const onCatch = pkgCatch === undefined ? undefined : (_$, e, next) => { const failed = next.error; const projected = failed === undefined ? undefined : Object.freeze({ kind: failed.kind === "timeout" ? "timeout" : "throw", ...(failed.message !== undefined ? { message: failed.message } : {}), budget: failed.budget }); return pkgCatch(dollar, e, onceNext(record.name, next, projected === undefined ? undefined : { error: projected, called: next.called === true })); }; const selected = expandOnSide(h.pattern, "engine"); const names = !h.pattern.endsWith(".*") ? [h.pattern] : "names" in selected ? selected.names.filter((n) => stationOn(n, "engine") !== undefined) : []; for (const pattern of names) out.push(Object.freeze({ pattern, ...(h.matcher !== undefined ? { matcher: h.matcher } : {}), fn, ...(onCatch !== undefined ? { onCatch } : {}) })); } return Object.freeze(out); } function onceNext(name, next, caught) { let started = false; const take = (start) => { if (started) return Promise.reject(new Error(`${name}: next() was already called — a hook's next goes below once, and its first answer stands`)); started = true; return start(); }; const projected = (e) => take(() => next(e)); Object.defineProperties(projected, { to: { value: (e, tier) => take(() => next.to(e, tier)), enumerable: true }, signal: { get: () => next.signal, enumerable: true }, origin: { get: () => next.origin, enumerable: true }, trace: { get: () => next.trace, enumerable: true }, budget: { get: () => next.budget, enumerable: true }, ...(caught !== undefined ? { error: { value: caught.error, enumerable: true }, called: { value: caught.called, enumerable: true } } : {}), }); return Object.freeze(projected); } function referenceDollar(record) { const plugin = Object.freeze({ name: record.name, root: record.root }); return new Proxy(Object.freeze({ plugin }), { get: (target, prop) => { if (prop === "plugin") return target.plugin; if (typeof prop === "symbol" || prop === "then") return undefined; throw new Error(`${record.name}: $.${prop.slice(0, 60)}: phase one gives a reference-form package no $ calls ${row("7")}`); }, }); } function own(record, key) { return Object.hasOwn(record, key) ? record[key] : undefined; }