@sema-agent/core
Version:
Stateless, task-oriented AI agent core
169 lines (168 loc) • 9.35 kB
JavaScript
import { askPerModelAuth } from "../../brain/route-adjudicator.js";
import { describeRejectedValue } from "../tool-search-setting.js";
import { brainToRuntime } from "../runtime.js";
import { modelLaneBrainOf } from "./model-lane-seat.js";
import { plaintextOriginsOf } from "../plaintext-origins-seat.js";
import { catalogOfDeps, receiveRoleMap, resolveTaskModel, roleModelIfSet, unheldChainRefusal } from "../roles.js";
import { isAliasModelId, openAiCompatChatSeat } from "../memory-engine/distiller.js";
import { runMemoryConsolidationDriver } from "../memory-engine/consolidation-driver.js";
import { bareChatRefusal, consolidationSeatRefusal, explicitModelId } from "./consolidation-seat-door.js";
import { recommendationUnconsumed } from "../memory-engine/consolidation.js";
import { deliverWriteRefusal } from "./memory-consolidation-write-judge.js";
import { asThrownError } from "../thrown-value.js";
const CONSOLIDATION_CHAIN = ["consolidate", "summarize"];
function consolidationRoleModel(models, roles) {
return roleModelIfSet(CONSOLIDATION_CHAIN[0], {}, { models, roles }) ?? roleModelIfSet(CONSOLIDATION_CHAIN[1], {}, { models, roles });
}
const seatRefusal = consolidationSeatRefusal;
function readConsolidationSeat(deps) {
const seat = deps.memoryConsolidationDriver;
const chat = seat?.chat;
if (typeof chat === "function") {
const model = seat.model;
return explicitModelId(model) ? { kind: "function", seat: seat, chat, model } : { kind: "refused", arm: "unusable", refusal: bareChatRefusal(model) };
}
if (chat !== undefined)
return { kind: "endpoint", seat: seat, chat };
const models = catalogOfDeps(deps);
const roles = receiveRoleMap(deps.roles, "RunnerDeps.roles");
if (consolidationRoleModel(models, roles) === undefined)
return { kind: "refused", arm: "no_seat", refusal: unheldChainRefusal(CONSOLIDATION_CHAIN, models, roles) };
const hop = resolveTaskModel({ modelRole: CONSOLIDATION_CHAIN[0] }, { models, roles });
if (isAliasModelId(hop.model.id)) {
return { kind: "refused", arm: "unusable", refusal: seatRefusal(`the resolved consolidation model id ${JSON.stringify(hop.model.id)} is an alias spelling — an alias can be re-pointed upstream and would move the run with no trace in the archive; bind an explicit id.`) };
}
return { kind: "roles", seat, hop };
}
const NO_SEAT_SENTENCE = 'memory consolidation has no model seat: configure RunnerDeps.memoryConsolidationDriver.chat (an endpoint triple or a chat function), or declare roles.consolidate / roles.summarize (a tier-expanded catalog\'s "flash" binding also satisfies the summarize hop). The chain deliberately does NOT fall back to the default main model — a whole-library distillation must not silently ride the most expensive seat.';
export function resolveMemoryConsolidationDriver(deps) {
const reading = readConsolidationSeat(deps);
if (reading.kind === "refused")
throw reading.refusal ?? seatRefusal(NO_SEAT_SENTENCE);
const seat = reading.seat;
let chat;
let model;
if (reading.kind === "function") {
model = reading.model;
chat = reading.chat;
}
else if (reading.kind === "endpoint") {
chat = openAiCompatChatSeat(reading.chat, plaintextOriginsOf(deps));
model = reading.chat.model;
}
else {
const { model: resolved, thinking } = reading.hop;
model = resolved.id;
const runtime = brainToRuntime(modelLaneBrainOf(deps));
chat = async (req) => {
const auth = await askPerModelAuth(deps.getApiKeyAndHeaders, resolved, deps);
const message = await runtime.completeSimple(resolved, { systemPrompt: req.system, messages: [{ role: "user", content: req.user, timestamp: Date.now() }] }, { temperature: req.temperature, maxTokens: req.maxTokens, reasoning: thinking, apiKey: auth?.apiKey, headers: auth?.headers, ...(auth?.credentialOrigin !== undefined ? { credentialOrigin: auth.credentialOrigin } : {}), ...(auth?.credentialOriginUnsettled === true ? { credentialOriginUnsettled: true } : {}) });
if (message.stopReason === "error" || message.stopReason === "aborted") {
throw new Error(message.errorMessage ?? `model completion ${message.stopReason}`);
}
return {
content: message.content
.filter((c) => c.type === "text")
.map((c) => c.text)
.join(""),
finishReason: message.stopReason,
usage: { promptTokens: message.usage.input, completionTokens: message.usage.output },
model: resolved.id,
};
};
}
return {
chat,
model,
...(seat?.contract !== undefined ? { contract: seat.contract } : {}),
...(seat?.maxCycles !== undefined ? { maxCycles: seat.maxCycles } : {}),
...(seat?.mintRepairBudget !== undefined ? { mintRepairBudget: seat.mintRepairBudget } : {}),
...(deps.memoryConsolidation !== undefined ? { consolidation: deps.memoryConsolidation } : {}),
};
}
export function consolidationSeatResolvable(deps) {
const reading = readConsolidationSeat(deps);
return !(reading.kind === "refused" && reading.arm === "no_seat");
}
export function autoRunConsolidationFromRecommendation(args) {
const { deps, engine, scope, sessionId, writeJudge, compliance, onNotice, onError } = args;
return (async () => {
try {
await runMemoryConsolidationDriver(engine, scope, { ...resolveMemoryConsolidationDriver(deps), writeJudge, compliance, onNotice });
}
catch (err) {
if (deliverWriteRefusal(err, scope, onNotice))
return;
try {
onError?.(asThrownError(err), { phase: "memory", sessionId });
}
catch {
}
}
})();
}
export const AUTO_RUN_ON_RECOMMENDATION_DEFAULT = true;
export function autoRunOnRecommendationEffective(deps) {
const raw = deps.autoRunOnRecommendation;
if (raw === true)
return true;
if (raw !== undefined)
return false;
return AUTO_RUN_ON_RECOMMENDATION_DEFAULT && deps.memoryConsolidation !== undefined && consolidationSeatResolvable(deps);
}
export async function scopeHasUnconsumedRecommendation(engine, scope) {
const row = await engine.readConsolidationGate(scope);
return row !== undefined && recommendationUnconsumed(row);
}
function autoRunRefusal(message) {
const e = new Error(message);
e.code = "config.auto_consolidation";
return e;
}
export function assertAutoConsolidationWirable(deps) {
const armed = armingLevel(deps);
if (armed !== undefined && armed.level === 0)
throw armed.refusal;
}
export function assertSwapKeepsAutoConsolidationWirable(before, after) {
let roles;
let from;
try {
roles = receiveRoleMap(before.roles, "RunnerDeps.roles");
from = armingLevel({ ...before, roles });
}
catch (err) {
const code = typeof err?.code === "string" ? err.code : "uncoded";
const told = Object.assign(new Error(`swapDeps: the deps in force could not be read for automatic consolidation (${code}), so the swap was judged with no level to keep`), { code });
try {
before.onError?.(told, { phase: "config", sessionId: "", classification: "swap-arming-unjudged" });
}
catch {
}
return;
}
if (from === undefined)
return;
const to = armingLevel({ ...after, roles });
if (to !== undefined && to.level < from.level)
throw to.refusal;
}
function armingLevel(deps) {
const raw = deps.autoRunOnRecommendation;
if (raw === undefined)
return undefined;
if (typeof raw !== "boolean") {
return { level: 0, refusal: autoRunRefusal(`RunnerDeps.autoRunOnRecommendation must be a boolean when present (got ${describeRejectedValue(raw)}) — a non-boolean would silently read as off, arming or disarming whole-library egress by accident.`) };
}
if (raw !== true)
return undefined;
if (deps.memoryConsolidation === undefined) {
return { level: 0, refusal: autoRunRefusal("RunnerDeps.autoRunOnRecommendation is true but RunnerDeps.memoryConsolidation is absent — the recommendation that would trigger a run is never minted (consolidation is OFF) and the engine's verbs refuse coded, so the trigger can never fire. An armed-but-unrunnable trigger is refused, never folded to off: wire memoryConsolidation, or leave autoRunOnRecommendation unset.") };
}
const reading = readConsolidationSeat(deps);
if (reading.kind !== "refused")
return { level: 2 };
if (reading.arm === "unusable")
return { level: 1, refusal: reading.refusal ?? seatRefusal(NO_SEAT_SENTENCE) };
return { level: 0, refusal: reading.refusal ?? autoRunRefusal("RunnerDeps.autoRunOnRecommendation is true but no consolidation model seat resolves — configure RunnerDeps.memoryConsolidationDriver.chat (an endpoint triple or a chat function), or declare roles.consolidate / roles.summarize. Arming auto-run with no model to run it is refused, never folded to off (a whole-library distillation must not silently ride the default main model).") };
}