UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

227 lines (226 loc) • 12.3 kB
import { constants } from "node:fs"; import { lstat, open, readdir, stat } from "node:fs/promises"; import { isAbsolute, relative, resolve, sep } from "node:path"; import { KERNEL_CONTRACT_VERSION, MOD_PACKAGE_FILES, MODS_INVALID_CODE, readModPackage } from "./kernel/index.js"; import { modPackageDigest } from "./kernel/digest.js"; import { kind } from "./kernel/package-reader.js"; import { modsInvalid } from "./kernel/registration.js"; import { componentFolderRefusal, judgeComponentFile, judgeReferenceModule, readReferenceManifests, recordReferencePackage, REFERENCE_COMPONENT_FILES, REFERENCE_COMPONENT_FOLDERS, referenceImportRefusal, referenceOptions, referenceReplay, } from "./reference-package.js"; import { physicalPathOfAsync } from "../physical-path.js"; import { describeThrown } from "../tool-policy.js"; import { foreignLine } from "../protocol-http-auth.js"; import { deliverEngineNotice } from "../engine-notice.js"; import { callerKey } from "../caller-text.js"; import { refuseStrayMembers } from "../own-property-receipt.js"; const KEY_SPELLING_MAX = 60; const ROOT_SPELLING_MAX = 1024; const MODULE_MEMBER = `${MOD_PACKAGE_FILES.hooks}: modules[0]`; const MODULE_URL_HEAD = "data:text/javascript;base64,"; const MODULE_URL_TEXT = /data:text\/javascript;base64,[A-Za-z0-9+/=]*/g; export async function loadModPackage(dir, host = {}) { return (await loadPackage(dir, host, "registration")); } export async function readReferencePackageRecord(dir, host = {}) { return (await loadPackage(dir, host, "record")); } async function loadPackage(dir, host, wants) { const single = closedHost(dir, host); const root = await realRoot(dir); try { const plugin = await packageFile(root, MOD_PACKAGE_FILES.plugin, MOD_PACKAGE_FILES.plugin); const hooks = await packageFile(root, MOD_PACKAGE_FILES.hooks, MOD_PACKAGE_FILES.hooks); const reference = referenceFormOf(hooks); if (reference === undefined) { if (wants === "record") throw modsInvalid(`${MOD_PACKAGE_FILES.hooks}: states a contract, so the package is of this engine's own form, which has no reference-form record`); return await loadFrom(root, host, plugin, hooks); } admitReferenceForm(single, reference); const read = await readReferenceForm(root, host, plugin, hooks, reference); const options = referenceOptions(host.options); const record = await recordReferencePackage({ root, manifests: read.manifests, digest: read.digest, options, importModule: () => importModuleBytes(read.module, referenceImportRefusal) }); if (wants === "record") return record; return referenceRegistration(record, host); } catch (err) { if (typeof err === "object" && err !== null && Reflect.get(err, "code") === MODS_INVALID_CODE) { const detail = Reflect.get(err, "detail"); throw Object.assign(modsInvalid(`mod package ${root}: ${err.message}`), detail !== undefined ? { detail } : {}); } throw err; } } function referenceRegistration(record, host) { const unread = record.unread.map((u) => ({ file: u.file, key: foreignLine(u.name, KEY_SPELLING_MAX), name: u.name })); const registration = Object.freeze({ name: record.name, uses: record.uses, ...(host.tier !== undefined ? { tier: host.tier } : {}), ...(host.provenance !== undefined ? { provenance: host.provenance } : {}), options: record.options, register: referenceReplay(record), failure: "skip", digest: record.digest, ...(unread.length > 0 ? { unread: Object.freeze(unread.map((u) => Object.freeze({ file: u.file, key: u.key }))) } : {}), form: "reference", }); tellUnread(record.root, unread); return registration; } function tellUnread(root, unread) { const shownRoot = foreignLine(root, ROOT_SPELLING_MAX); for (const u of unread) { deliverEngineNotice(undefined, { code: "mods.package_key_unread", message: `mod package ${shownRoot}: ${u.file} carries the member ${callerKey(u.name)}, which this engine's mod package reader does not read; the package is loaded without it`, detail: { package: root, file: u.file, key: u.key }, }); } } function referenceFormOf(hooks) { let parsed; try { parsed = JSON.parse(new TextDecoder("utf-8", { ignoreBOM: true }).decode(hooks)); } catch { return undefined; } if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed) || Object.hasOwn(parsed, "contract")) return undefined; return parsed; } function admitReferenceForm(single, hooksJson) { const noContract = { detail: Object.freeze({ contract: Object.freeze({ stated: null, kernel: KERNEL_CONTRACT_VERSION }) }) }; if (Object.hasOwn(hooksJson, "uses")) { throw Object.assign(modsInvalid(`${MOD_PACKAGE_FILES.hooks}: contract is absent, yet it declares uses; a package of this engine's form states the contract it was written against — this engine's mods kernel is contract ${KERNEL_CONTRACT_VERSION} — and a reference-form package declares no uses`), noContract); } if (single !== true) { throw Object.assign(modsInvalid(`${MOD_PACKAGE_FILES.hooks}: states no contract, so the package is of the reference plugin form, which loads only in a process whose host declares it serves one principal (singlePrincipal: true); this host's singlePrincipal is ${single === false ? "false" : "absent"}`), noContract); } } async function readReferenceForm(root, host, plugin, hooks, hooksJson) { const manifests = readReferenceManifests(plugin, hooksJson); for (const folder of REFERENCE_COMPONENT_FOLDERS) { let entries = []; try { const at = resolve(root, folder); const real = (await lstat(at)).isSymbolicLink() ? await physicalPathOfAsync(at) : at; if (!insidePackage(root, real)) throw modsInvalid(`${folder}/: resolves outside the package`); if ((await stat(real)).isDirectory()) entries = await readdir(real); } catch (err) { if (typeof err === "object" && err !== null && Reflect.get(err, "code") === MODS_INVALID_CODE) throw err; if (!isAbsent(err)) throw modsInvalid(`${folder}/: could not be checked for a component (${codeOf(err)})`); } if (entries.length > 0) throw componentFolderRefusal(folder); } for (const file of REFERENCE_COMPONENT_FILES) { const present = await lstat(resolve(root, file)).then(() => true, (err) => !isAbsent(err)); if (present) judgeComponentFile(file, await packageFile(root, file, file)); } const module = await packageFile(root, manifests.modulePath, MODULE_MEMBER); judgeReferenceModule(module); const digest = modPackageDigest(plugin, hooks, module); const expectDigest = host.expectDigest; 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 imported`), { detail: Object.freeze({ digest: Object.freeze({ expected: expectDigest, actual: digest }) }), }); } return { manifests, module, digest }; } async function importModuleBytes(module, refusal) { try { return await import(`${MODULE_URL_HEAD}${Buffer.from(module.buffer, module.byteOffset, module.byteLength).toString("base64")}`); } catch (err) { throw refusal(err, describeThrown(err).replace(MODULE_URL_TEXT, MODULE_MEMBER)); } } function insidePackage(root, real) { const inside = relative(root, real); return !(inside === "" || inside === ".." || inside.startsWith(`..${sep}`) || isAbsolute(inside)); } function codeOf(err) { const code = typeof err === "object" && err !== null ? Reflect.get(err, "code") : undefined; return typeof code === "string" ? code : describeThrown(err); } const isAbsent = (err) => ["ENOENT", "ENOTDIR"].includes(codeOf(err)); async function loadFrom(root, host, plugin, hooks) { const expectDigest = host.expectDigest; const read = await readModPackage({ plugin, hooks, readModule: (path) => packageFile(root, path, MODULE_MEMBER), side: "engine", ...(expectDigest !== undefined ? { expectDigest } : {}) }); if (read.contract !== KERNEL_CONTRACT_VERSION) { const stated = typeof read.contract === "number" ? read.contract : null; throw Object.assign(modsInvalid(`${MOD_PACKAGE_FILES.hooks}: contract is ${kind(read.contract)}; this engine's mods kernel is contract ${KERNEL_CONTRACT_VERSION}, and a package loads only under the contract it was written against`), { detail: Object.freeze({ contract: Object.freeze({ stated, kernel: KERNEL_CONTRACT_VERSION }) }) }); } const ns = await importModuleBytes(read.module, (_err, said) => modsInvalid(`${MODULE_MEMBER}: could not be imported (${said}); a hooks module is imported from its own bytes, so it is one self-contained file: a relative or package import has nothing to resolve from`)); const unread = read.unread.map((u) => ({ file: u.file, key: foreignLine(u.name, KEY_SPELLING_MAX), name: u.name })); const registration = Object.freeze({ name: read.name, uses: read.uses, ...(host.tier !== undefined ? { tier: host.tier } : {}), ...(host.provenance !== undefined ? { provenance: host.provenance } : {}), ...(host.options !== undefined ? { options: host.options } : {}), register: (typeof ns === "object" && ns !== null ? Reflect.get(ns, "register") : undefined), digest: read.digest, ...(unread.length > 0 ? { unread: Object.freeze(unread.map((u) => Object.freeze({ file: u.file, key: u.key }))) } : {}), }); tellUnread(root, unread); return registration; } const HOST_MEMBERS = ["tier", "provenance", "options", "expectDigest", "singlePrincipal"]; function closedHost(dir, host) { if (typeof host !== "object" || host === null || Array.isArray(host)) { throw modsInvalid(`mod package ${dir}: the host's argument is ${kind(host)}; it is { ${HOST_MEMBERS.map((k) => `${k}?`).join(", ")} }`); } refuseStrayMembers(host, { subject: "the host's argument", unit: "member", moment: "at loadModPackage" }, HOST_MEMBERS, (sentence) => modsInvalid(`mod package ${dir}: ${sentence}`)); const d = Object.getOwnPropertyDescriptor(host, "singlePrincipal"); if (d === undefined) return "absent"; if (d.get !== undefined || d.set !== undefined || typeof d.value !== "boolean") { throw modsInvalid(`mod package ${dir}: the host's singlePrincipal is ${d.get !== undefined || d.set !== undefined ? "an accessor" : kind(d.value)}; it is an own boolean data member, true where the host declares this process serves one principal`); } return d.value; } async function realRoot(dir) { try { const root = await physicalPathOfAsync(dir); if ((await stat(root)).isDirectory()) return root; } catch { } throw modsInvalid(`mod package ${dir}: not a directory`); } async function packageFile(root, path, said) { let real; try { real = await physicalPathOfAsync(resolve(root, ...path.split("/"))); } catch { throw modsInvalid(`${said}: is not in the package; a mod package carries it`); } if (!insidePackage(root, real)) throw modsInvalid(`${said}: resolves outside the package`); let handle; try { handle = await open(real, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); if (!(await handle.stat()).isFile()) throw Object.assign(new Error("not a regular file"), { code: "not a regular file" }); return await handle.readFile(); } catch (err) { const code = typeof err === "object" && err !== null ? Reflect.get(err, "code") : undefined; throw modsInvalid(`${said}: could not be read as a regular file of the package (${typeof code === "string" ? code : describeThrown(err)})`); } finally { await handle?.close(); } }