@sema-agent/core
Version:
Stateless, task-oriented AI agent core
194 lines (193 loc) • 11.3 kB
JavaScript
import { createHash } from "node:crypto";
import { types } from "node:util";
import { seatAskMarker } from "../brain/route-adjudicator.js";
import { modelOriginOf, sameModelData } from "./model-receipt.js";
import { assertContainmentFaceValue } from "../tools/fs/containment-face.js";
import { assertContextSettingsValue } from "./context-settings.js";
import { READ_DENY_DEPLOYMENT_SEATS, screenReadDenySeat } from "./read-face-seats.js";
import { deliverEngineNotice } from "./engine-notice.js";
import { uuidv7 } from "../internal/harness.js";
import { callerKey } from "./caller-text.js";
import { receiveOwnProperties } from "./own-property-receipt.js";
import { holdConsolidationSeatKey } from "./runner/construction-doors.js";
import { eraseSentCredentials } from "./protocol-http-auth.js";
import { receiveConsolidationDriverSeat, screenConsolidationDriverSeat } from "./runner/consolidation-seat-door.js";
export const SWAPPABLE_DEP_SEATS = Object.freeze(["models", "tiers", "readFace", "writeFace", "contextSettings", "readDenyPatterns", "readDenyBuiltinTiers", "readDenyBuiltinExclude", "readDenyFloorRequired", "readDenyBuiltinRequestExcludable", "memoryConsolidationDriver"]);
const SWAPPABLE_DEP_SEAT_SET = new Set(SWAPPABLE_DEP_SEATS);
export function isSwappableDepSeat(k) {
return SWAPPABLE_DEP_SEAT_SET.has(k);
}
export const SWAP_SEAT_NOTICE = {
models: "config.models_swapped",
tiers: "config.models_swapped",
readFace: "config.read_face_swapped",
writeFace: "config.write_face_swapped",
contextSettings: "config.context_settings_swapped",
readDenyPatterns: "config.read_deny_swapped",
readDenyBuiltinTiers: "config.read_deny_swapped",
readDenyBuiltinExclude: "config.read_deny_swapped",
readDenyFloorRequired: "config.read_deny_swapped",
readDenyBuiltinRequestExcludable: "config.read_deny_swapped",
memoryConsolidationDriver: "config.memory_consolidation_driver_swapped",
};
const SEAT_BIRTH = Symbol("sema.core.seatBirth");
let catalogSwaps = 0;
export function noteCatalogSwap() {
catalogSwaps += 1;
}
export function takeSeat(seat, liveCatalog) {
if (typeof seat !== "function" || Object.hasOwn(seat, SEAT_BIRTH))
return seat;
const host = seat;
const record = { birth: liveCatalog(), swaps: catalogSwaps, live: liveCatalog, legs: new Set(), walked: new WeakSet() };
const taken = function (...args) {
const mark = seatAskMarker();
const answer = Reflect.apply(host, this, args);
if (mark === undefined)
return answer;
const judge = () => {
if (record.swaps !== catalogSwaps && !entrySettled(args[0], record))
mark();
};
if (typeof answer?.then === "function")
return Promise.resolve(answer).then((a) => (judge(), a));
judge();
return answer;
};
Object.defineProperty(taken, SEAT_BIRTH, { value: record });
return taken;
}
export function withSeatTaken(spec, liveCatalog) {
const seat = Reflect.get(spec, "getApiKeyAndHeaders");
const taken = takeSeat(seat, liveCatalog);
return taken === seat ? spec : { ...spec, getApiKeyAndHeaders: taken };
}
export function seatLegPrepares(seat, catalog) {
if (typeof seat !== "function" || catalog === undefined)
return;
const record = Reflect.get(seat, SEAT_BIRTH);
if (record === undefined || catalog === record.birth || record.walked.has(catalog))
return;
for (const entry of Object.values(catalog))
if (entry !== undefined)
record.legs.add(modelOriginOf(entry));
if (entriesFixed(catalog))
record.walked.add(catalog);
}
function entriesFixed(catalog) {
return !types.isProxy(catalog) && Object.isFrozen(catalog) && Object.values(Object.getOwnPropertyDescriptors(catalog)).every((member) => Object.hasOwn(member, "value"));
}
function entrySettled(model, seat) {
const live = seat.live();
const held = modelOriginOf(model);
const found = seat.legs.has(held) || [seat.birth, live].some((catalog) => catalog !== undefined && Object.values(catalog).some((entry) => entry !== undefined && (entry === model || modelOriginOf(entry) === held)));
if (!found)
return true;
const holds = (catalog) => catalog !== undefined && Object.values(catalog).some((entry) => entry !== undefined && (entry === model || (entry.id === model.id && entry.baseUrl === model.baseUrl && sameModelData(entry, model))));
return holds(seat.birth) && holds(live);
}
export function screenSwappableDeps(next) {
return screenCandidate(next, undefined, undefined);
}
export function receiveSwappableDeps(next, onNotice, plaintextOrigins) {
return screenCandidate(next, (driver) => holdConsolidationSeatKey(driver, onNotice, "at swapDeps"), plaintextOrigins);
}
function screenCandidate(next, takeKeyIn, plaintextOrigins) {
if (next === null || typeof next !== "object" || Array.isArray(next)) {
throw new Error(`swapDeps: the candidate must be a plain object naming the seats to swap (got ${next === null ? "null" : Array.isArray(next) ? "array" : typeof next}) — the current deps stay in force`);
}
const keys = Object.keys(next);
const unknown = keys.filter((k) => !isSwappableDepSeat(k));
if (unknown.length > 0) {
throw new Error(`swapDeps: ${unknown.map((k) => callerKey(k)).join(", ")} is not a hot-swappable seat (the closed set is ${SWAPPABLE_DEP_SEATS.join(" | ")}) — the current deps stay in force`);
}
const present = SWAPPABLE_DEP_SEATS.filter((seat) => Object.hasOwn(next, seat));
if (present.length === 0) {
throw new Error(`swapDeps: the candidate names no seat (an empty swap is a caller defect, not a no-op) — the current deps stay in force`);
}
const raw = next;
const candidate = {};
for (const seat of present) {
const v = raw[seat];
switch (seat) {
case "models":
if (v === null || typeof v !== "object" || Array.isArray(v)) {
throw new Error(`swapDeps: models must be a plain Record<string, Model> (got ${v === null ? "null" : Array.isArray(v) ? "array" : typeof v}) — the current generation stays in force`);
}
candidate.models = receiveOwnProperties(v, { subject: "swapDeps.models", unit: "entry", moment: "at swapDeps" });
break;
case "tiers":
if (!present.includes("models")) {
throw new Error(`swapDeps: tiers is a binding over models — pass the catalog it binds in the same swap (\`{ models, tiers }\`); the current generation stays in force`);
}
if (v !== undefined && (v === null || typeof v !== "object" || Array.isArray(v))) {
throw new Error(`swapDeps: tiers must be a plain Record<string, ModelRef> or undefined (got ${v === null ? "null" : Array.isArray(v) ? "array" : typeof v}) — the current generation stays in force`);
}
candidate.tiers = v === undefined ? undefined : receiveOwnProperties(v, { subject: "swapDeps.tiers", unit: "binding", moment: "at swapDeps" });
break;
case "readFace":
candidate.readFace = assertContainmentFaceValue(v, "read", "deps");
break;
case "writeFace":
candidate.writeFace = assertContainmentFaceValue(v, "write", "deps");
break;
case "contextSettings":
candidate.contextSettings = assertContextSettingsValue(v, "swapDeps");
break;
case "readDenyPatterns":
case "readDenyBuiltinTiers":
case "readDenyBuiltinExclude":
case "readDenyFloorRequired":
case "readDenyBuiltinRequestExcludable":
candidate[seat] = screenReadDenySeat(seat, v);
break;
case "memoryConsolidationDriver": {
const driver = receiveConsolidationDriverSeat(v, "swapDeps.memoryConsolidationDriver", "at swapDeps");
takeKeyIn?.(driver);
screenConsolidationDriverSeat(driver, "swapDeps.memoryConsolidationDriver", plaintextOrigins);
candidate.memoryConsolidationDriver = driver;
break;
}
default: {
const _exhaustive = seat;
throw new Error(`swapDeps: unhandled seat ${String(_exhaustive)}`);
}
}
}
return { seats: present, candidate: candidate };
}
export function catalogGenerationOf(models, tiers) {
const names = Object.keys(models).sort();
const bindings = tiers === undefined ? [] : Object.keys(tiers).sort().map((tier) => [tier, typeof tiers[tier] === "string" ? tiers[tier] : null]);
return `cgv1:${createHash("sha256").update(JSON.stringify([names, bindings])).digest("hex")}`;
}
export function announceReadDenySwap(onNotice, seats, inForce) {
const named = READ_DENY_DEPLOYMENT_SEATS.filter((s) => seats.includes(s));
if (named.length === 0)
return;
const patterns = inForce.readDenyPatterns?.length ?? null;
const tiers = inForce.readDenyBuiltinTiers !== undefined ? [...inForce.readDenyBuiltinTiers] : null;
const exclude = inForce.readDenyBuiltinExclude?.length ?? null;
const floorRequired = inForce.readDenyFloorRequired ?? null;
const releasable = inForce.readDenyBuiltinRequestExcludable ?? [];
deliverEngineNotice(onNotice, {
code: "config.read_deny_swapped",
message: `deployment read-deny declaration swapped (${named.join(", ")}): ${patterns ?? "no"} addition(s), built-in tiers ${tiers === null ? "(default)" : `[${tiers.join(", ")}]`}, ${exclude ?? "no"} built-in row removal(s), byte floor ${floorRequired === true ? "required" : "not required"}, request-releasable rows ${releasable.length === 0 ? "none" : `[${releasable.join(", ")}]`}; in-flight legs keep the deny face they prepared under, new legs compile against the new declaration`,
detail: { seats: named, patterns, tiers, exclude, floorRequired, occurrenceId: uuidv7() },
});
}
export function announceConsolidationDriverSwap(onNotice, seats, written) {
if (!seats.includes("memoryConsolidationDriver"))
return;
const seat = written.memoryConsolidationDriver;
const chat = seat?.chat;
const shape = seat === undefined ? "cleared" : typeof chat === "function" ? "function" : chat !== undefined ? "endpoint" : "roles";
const named = shape === "endpoint" ? chat.model : shape === "function" ? (seat?.model ?? null) : null;
const key = shape === "endpoint" ? chat.apiKey : undefined;
const model = named !== null && typeof key === "string" && key !== "" ? eraseSentCredentials(named, [key]) : named;
deliverEngineNotice(onNotice, {
code: "config.memory_consolidation_driver_swapped",
message: `memory consolidation seat swapped (${shape}${model !== null ? `, model ${JSON.stringify(model)}` : ""}): it takes effect from the next consolidation that starts; a consolidation already running finishes on the seat it started with, and its provider still receives the rest of that run's requests`,
detail: { shape, model, occurrenceId: uuidv7() },
});
}