@sema-agent/core
Version:
Stateless, task-oriented AI agent core
86 lines (85 loc) • 5.54 kB
JavaScript
import { ADVISOR_TOOL_NAME, advisorAttachVerdict, advisorHoldOf, advisorNotAttachedNotice, advisorReasonTold } from "../advisor-verdict.js";
import { deliverEngineNotice } from "../types.js";
import { advisorInstructionFrame } from "./advisor-instructions.js";
import { createAdvisorTool } from "./advisor-tool.js";
import { announceDigest } from "./announce-once-ledger.js";
import { conversationSegmentOf } from "./conversation-segment.js";
import { derivedRouteFallsBack } from "./derived-route-fallback.js";
import { derivedLegBrain } from "./side-call-account.js";
import { withBrainCallGuardrail } from "../../brain/timeout.js";
import { modelLaneBrainOf } from "./model-lane-seat.js";
import { refusalAbout } from "../config-refusal-input.js";
import { observingBrain } from "./prefix-ledger.js";
export async function prepareAdvisor(input) {
const { spec, deps, model, onceLedger, sessionId, runId } = input;
const told = onceLedger.arms().advisor;
if (spec.advisorModel === undefined && told === undefined)
return { manifest: undefined, instruction: undefined };
const requested = spec.advisorModel === undefined || input.advisorTool === "disabled" ? undefined : typeof spec.advisorModel === "string" ? spec.advisorModel : spec.advisorModel.id;
const fact = (f) => ({ ...(requested !== undefined ? { requested } : {}), main: model.id, ...f });
const notAttached = (reason, extra = {}) => {
input.roster.mounts.know({ "advisor.route": false });
if (input.rootLeg && requested !== undefined && advisorReasonTold(reason)) {
onceLedger.oncePerSession(announceDigest("advisor.not_attached", `${reason}\n${requested}\n${model.id}`), () => deliverEngineNotice(deps.onNotice, advisorNotAttachedNotice({ reason, advisorModel: requested, mainModel: model.id, sessionId, ...(runId !== undefined ? { runId } : {}) })));
}
return fact({ state: "not_attached", reason, ...extra });
};
let branch;
const readBranch = async () => (branch ??= await input.session.getBranch().catch(() => undefined));
let mounted = false;
const mount = async (advisor) => {
if ((spec.tools ?? []).some((t) => t.name === ADVISOR_TOOL_NAME)) {
const e = new Error(`Tool name "${ADVISOR_TOOL_NAME}" is reserved when TaskSpec.advisorModel attaches the advisor tool.`);
e.code = "config.reserved_tool_name";
throw refusalAbout("taskConfig", e);
}
if (!input.roster.mounts.holdsIf("advisor", { "advisor.route": true }))
return fact({ state: "not_attached", reason: "excluded" });
const entries = await readBranch();
if (entries === undefined)
return notAttached("hold_unknown");
const held = advisorHoldOf(entries);
if (held !== undefined) {
input.roster.mounts.know({ "advisor.route": false });
return fact({ state: "held", model: advisor.id, hold: held });
}
const route = await derivedRouteFallsBack({ seat: "advisor", derived: advisor, primary: model, brain: modelLaneBrainOf(deps), getApiKeyAndHeaders: spec.getApiKeyAndHeaders, onNotice: deps.onNotice, sessionId, ...(runId !== undefined ? { runId } : {}), onBrokenPairing: "detach" });
if (route.action === "detach")
return notAttached("route_refused", route.cause !== undefined ? { routeCode: route.cause } : {});
input.roster.mounts.know({ "advisor.route": true });
if (!input.roster.mounts.judge("advisor"))
return fact({ state: "not_attached", reason: "excluded" });
input.roster.mount(createAdvisorTool(advisorSeat(input, advisor)), { source: "builtin", mountedBy: "optional" });
mounted = true;
return fact({ state: "on", model: advisor.id });
};
let manifest;
if (spec.advisorModel !== undefined) {
const verdict = advisorAttachVerdict({ deps: { ...deps, ...(input.advisorTool !== undefined ? { advisorTool: input.advisorTool } : {}) }, main: model, advisor: spec.advisorModel });
manifest = verdict.state === "on" ? await mount(verdict.model) : notAttached(verdict.reason);
}
const entries = told !== undefined || mounted ? await readBranch() : undefined;
if (entries === undefined)
return { manifest, instruction: undefined };
const segment = conversationSegmentOf(entries);
const owed = advisorInstructionFrame(told !== undefined && told.segment === segment ? told.state : undefined, mounted, input.say);
return { manifest, instruction: { ...(owed !== undefined ? { owed } : {}), segment, mounted } };
}
function advisorSeat(input, model) {
const book = (lane, m, reply) => {
const door = input.sideCallBookRef.book;
if (door === undefined)
throw new Error("the advisor was consulted before the run body bound the leg's usage account, which it does before any tool call");
door(lane, m, reply);
};
const ms = input.brainCallGuardrailMs;
const guarded = (b) => (ms === undefined ? b : { ...b, stream: withBrainCallGuardrail((m, c, o) => b.stream(m, c, o), ms, {}) });
return {
model,
brain: derivedLegBrain(() => observingBrain(guarded(modelLaneBrainOf(input.deps)), input.observeSideRequest), "advisor", book),
lastSentRequest: input.lastSentRequest,
readBranch: () => input.session.getBranch(),
getApiKeyAndHeaders: input.spec.getApiKeyAndHeaders,
markUsageUnknown: () => book("advisor", model, undefined),
};
}