@sema-agent/core
Version:
Stateless, task-oriented AI agent core
239 lines (238 loc) • 10.8 kB
JavaScript
import { types } from "node:util";
import { COMPLETIONS_THINKING_FORMATS, declaredCompletionsFormat, isThinkingLevel, THINKING_LEVELS } from "../brain/reasoning.js";
import { promptCacheKeyDefect } from "../brain/prompt-cache-key.js";
import { describeFault, receive } from "./mods/kernel/receive.js";
import { callerKey } from "./caller-text.js";
import { DECLARATION_RECEIPT_MODE } from "./own-property-receipt.js";
import { assertNoRetiredKeys, RETIRED_MODEL_KEYS } from "./retired-keys.js";
import { modelFallbackRefusal } from "./model-fallbacks.js";
export function modelBindingRefusal(field, reason, message) {
const e = new Error(message);
e.code = "config.unknown_role";
e.detail = { field, reason };
return e;
}
export function isList(value) {
try {
return Array.isArray(value);
}
catch {
return false;
}
}
export function bindingShown(value) {
if (typeof value === "string")
return JSON.stringify(value.length > 80 ? `${value.slice(0, 80)}…` : value);
return value === null ? "null" : isList(value) ? "a list" : `a ${typeof value}`;
}
const MODEL_MEMBER_TABLE = {
id: true,
name: true,
api: true,
provider: true,
baseUrl: true,
reasoning: true,
fastMode: true,
defaultThinking: true,
fallbacks: true,
thinkingLevelMap: true,
input: true,
cost: true,
contextWindow: true,
contextTokens: true,
autoCompactTokens: true,
charsPerToken: true,
mediaItemLimit: true,
maxTokens: true,
params: true,
extraBody: true,
headers: true,
promptTraits: true,
compat: true,
};
const MODEL_MEMBERS = new Set(Object.keys(MODEL_MEMBER_TABLE));
export const MODEL_RECEIPT_MODE = Object.freeze({ ...DECLARATION_RECEIPT_MODE, live: Object.freeze(["headers"]) });
const MINTED = new WeakSet();
const LAST = new WeakMap();
const ORIGIN = new WeakMap();
const ENTRY = new WeakMap();
export function modelEntryOf(model) {
return ENTRY.get(model) ?? model;
}
export function isModelSnapshot(value) {
return typeof value === "object" && value !== null && MINTED.has(value);
}
export function modelOriginOf(model) {
return ORIGIN.get(model)?.origin ?? model;
}
export function sameModelData(a, b) {
if (a === b)
return true;
const ha = ORIGIN.get(a);
const hb = ORIGIN.get(b);
if (ha?.headers !== hb?.headers || (ha?.headers !== undefined && ha.origin !== hb?.origin))
return false;
return sameData(a, b, true);
}
export function forkModelSnapshot(snapshot) {
const fork = Object.freeze(Object.create(Object.getPrototypeOf(snapshot), Object.getOwnPropertyDescriptors(snapshot)));
MINTED.add(fork);
const origin = ORIGIN.get(snapshot);
if (origin !== undefined)
ORIGIN.set(fork, origin);
return fork;
}
export function requestModelOf(snapshot) {
const members = Object.getOwnPropertyDescriptors(snapshot);
let perUse = false;
for (const key of MODEL_RECEIPT_MODE.live ?? []) {
const port = members[key];
if (port?.get === undefined)
continue;
perUse = true;
const get = port.get;
let kept;
members[key] = {
enumerable: true,
get: () => {
if (kept === undefined) {
try {
const value = Reflect.apply(get, snapshot, []);
kept = { value: typeof value === "object" && value !== null ? Object.freeze({ ...value }) : value };
}
catch (threw) {
kept = { threw };
}
}
if ("threw" in kept)
throw kept.threw;
return kept.value;
},
};
}
if (!perUse)
return snapshot;
const request = Object.freeze(Object.create(Object.getPrototypeOf(snapshot), members));
MINTED.add(request);
const origin = ORIGIN.get(snapshot);
if (origin !== undefined)
ORIGIN.set(request, origin);
ENTRY.set(request, snapshot);
return request;
}
function unreadableModelRefusal(seat, what, note, fault) {
const how = fault.path.length > 0
? describeFault(fault)
: fault.kind === "proxy"
? "a Proxy"
: "an object of another prototype (a class instance, an `Object.create(…)` value): a Model is a plain record, its members its own";
return modelBindingRefusal(seat, "not_a_model_ref", `${seat} is ${what} that could not be read as plain data — ${how}.${note}`);
}
export function receiveModel(value, seat, what = "a Model object", note = "", catalogEntry = false) {
if (isModelSnapshot(value))
return value;
const model = receivedModel(value, seat, what, note);
if (!catalogEntry && model.fallbacks !== undefined) {
throw modelFallbackRefusal(seat, `${seat} is ${what} carrying \`fallbacks\`, which only a catalog entry declares — the catalog door (RunnerDeps.models / swapDeps) resolves the words over the catalog it receives. Declare the chain on the catalog entry and name it by its word.${note}`);
}
return model;
}
function receivedModel(value, seat, what, note) {
if (typeof value !== "object" || value === null || isList(value)) {
throw modelBindingRefusal(seat, "not_a_model_ref", `${seat} is ${what} that is ${bindingShown(value)}, not a Model — a Model is a plain record carrying a non-empty string \`id\` and a string \`api\`.${note}`);
}
if (types.isProxy(value))
throw unreadableModelRefusal(seat, what, note, { kind: "proxy", path: [] });
const headersAt = Object.getOwnPropertyDescriptor(value, "headers");
const headers = headersAt !== undefined && !Object.hasOwn(headersAt, "value") ? headersAt.get : undefined;
const received = receive(value, MODEL_RECEIPT_MODE, MINTED);
if (!received.ok)
throw unreadableModelRefusal(seat, what, note, received.fault);
const copy = received.value;
judgeModelCopy(copy, seat, what, note);
const prior = LAST.get(value);
if (prior !== undefined && ORIGIN.get(prior)?.headers === headers && sameData(prior, copy, true))
return prior;
MINTED.add(copy);
LAST.set(value, copy);
ORIGIN.set(copy, { origin: value, headers });
return copy;
}
function judgeModelCopy(copy, seat, what, note) {
assertNoRetiredKeys(copy, RETIRED_MODEL_KEYS, "Model");
const id = copy["id"];
const api = copy["api"];
const [member, got] = typeof id !== "string" || id === "" ? ["id", id] : typeof api !== "string" ? ["api", api] : [undefined, undefined];
if (member !== undefined) {
const shown = got === undefined ? "absent" : bindingShown(got);
throw modelBindingRefusal(seat, "not_a_model_ref", `${seat} is ${what} whose \`${member}\` is ${shown} — a Model carries a non-empty string \`id\` and a string \`api\`.${note}`);
}
for (const key of Object.keys(copy)) {
if (!MODEL_MEMBERS.has(key)) {
throw modelBindingRefusal(seat, "not_a_model_ref", `${seat} is ${what} carrying ${callerKey(key)}, which this engine does not know as a member of Model — if it is a member of a newer engine's Model, upgrade the engine first (moved into \`Model.params\` it would not be read as that member); only a provider's own parameter belongs in \`Model.params\`.${note}`);
}
}
const defaultThinking = copy["defaultThinking"];
if (defaultThinking !== undefined && !isThinkingLevel(defaultThinking)) {
throw modelBindingRefusal(seat, "not_a_model_ref", `${seat} is ${what} whose \`defaultThinking\` is ${bindingShown(defaultThinking)} — a model's default thinking level is one of ${THINKING_LEVELS.join(", ")} ("off" spells thinking off), or absent for no default.${note}`);
}
const compat = copy["compat"];
if (typeof compat === "object" && compat !== null) {
try {
declaredCompletionsFormat(compat);
}
catch (e) {
if (e.code !== "config.invalid_argument")
throw e;
throw modelBindingRefusal(seat, "not_a_model_ref", `${seat} is ${what} whose \`compat.thinkingFormat\` is ${bindingShown(compat.thinkingFormat)} — a chat-completions thinking dialect is one of ${COMPLETIONS_THINKING_FORMATS.join(", ")}, or absent for "openai".${note}`);
}
const cacheKeyDefect = promptCacheKeyDefect({ api: copy["api"], compat });
if (cacheKeyDefect !== undefined)
throw modelBindingRefusal(seat, "not_a_model_ref", `${seat} is ${what} whose ${cacheKeyDefect}.${note}`);
}
const mediaItemLimit = copy["mediaItemLimit"];
if (mediaItemLimit !== undefined && !(Number.isInteger(mediaItemLimit) && mediaItemLimit >= 1)) {
throw modelBindingRefusal(seat, "not_a_model_ref", `${seat} is ${what} whose \`mediaItemLimit\` is ${typeof mediaItemLimit === "number" ? String(mediaItemLimit) : bindingShown(mediaItemLimit)} —the most media blocks one request to the endpoint carries is a whole number of at least 1, or absent for the engine's default.${note}`);
}
const fallbacks = copy["fallbacks"];
if (fallbacks !== undefined && (!isList(fallbacks) || !fallbacks.every((w) => typeof w === "string" && w !== ""))) {
throw modelBindingRefusal(seat, "not_a_model_ref", `${seat} is ${what} whose \`fallbacks\` is ${bindingShown(fallbacks)} — a model's fallbacks are a list of catalog words (non-empty strings), or absent for none.${note}`);
}
}
function sameData(a, b, top = false, compared = new Map()) {
if (Object.is(a, b))
return true;
if (typeof a !== "object" || typeof b !== "object" || a === null || b === null)
return false;
const partners = compared.get(a);
if (partners?.has(b) === true)
return true;
if (partners === undefined)
compared.set(a, new Set([b]));
else
partners.add(b);
if (Array.isArray(a) !== Array.isArray(b) || (Array.isArray(a) && Array.isArray(b) && a.length !== b.length))
return false;
const ka = Object.keys(a);
const kb = Object.keys(b);
if (ka.length !== kb.length)
return false;
for (let i = 0; i < ka.length; i++) {
const k = ka[i];
if (k !== kb[i])
return false;
const da = Object.getOwnPropertyDescriptor(a, k);
const db = Object.getOwnPropertyDescriptor(b, k);
const aData = Object.hasOwn(da, "value");
if (aData !== Object.hasOwn(db, "value"))
return false;
if (!aData) {
if (!top)
return false;
continue;
}
if (!sameData(da.value, db.value, false, compared))
return false;
}
return true;
}