@sema-agent/core
Version:
Stateless, task-oriented AI agent core
114 lines (112 loc) • 7.56 kB
JavaScript
import { Type } from "typebox";
import { stripErrorCodePrefix, thrownBrainFailure } from "../../brain/errors.js";
import { ADVISOR_TOOL_NAME, advisorFailureHolds, advisorHoldOf } from "../advisor-verdict.js";
import { runSideQuery } from "../side-query.js";
import { thrownText } from "../thrown-value.js";
import { defineTool } from "../tools.js";
import { mountRuleFace, toolFace } from "../tool-catalog-entries.js";
import { egressText } from "../untrusted-egress.js";
const ADVISOR_MESSAGE_MAX_CHARS = 2_000;
export const ADVISOR_SYSTEM_PROMPT = `You are the advisor: a stronger reviewer model consulted by an agent in the middle of its task. Above is the agent's conversation as it stood in the agent's last request — its task, every tool call it made and every result it saw — ending at the point where it asked for advice.
Reply in plain text only. Do not call tools: any tool call you make is discarded and counts as no answer. Be concrete and short: name the decision the agent is facing, say what you would do and why, point at the specific evidence in the conversation that supports it, and flag anything the agent has assumed without checking. If the agent asked before declaring the task done, review the deliverable against the task as stated and list what is missing or wrong. If something you need is not in the conversation, say what is missing and what the agent should check first — that is still guidance.`;
export const ADVISOR_HANDOFF = "You are the advisor now. Review everything above and reply with your guidance.";
const AGENT_INSTRUCTIONS_HEADER = "# The agent's instructions (context for you; they bind the agent, not you)";
const HOLD_SENTENCE = "The advisor is off for this conversation until it is compacted; do not call it again before then.";
function unavailable(model, failure, message, hold, extra = {}) {
const cause = failure.errorKind ?? failure.code ?? failure.stopReason;
const bounded = message !== undefined && message.trim() !== "" ? egressText("same-principal", message).slice(0, ADVISOR_MESSAGE_MAX_CHARS) : undefined;
const text = [`Advisor unavailable${cause !== undefined ? ` (${cause})` : ""}.`, ...(bounded !== undefined ? [bounded] : []), ...(hold ? [HOLD_SENTENCE] : [])].join(" ");
const card = {
type: "advisor",
outcome: "unavailable",
model: model.id,
...extra,
...(failure.stopReason !== undefined ? { stopReason: failure.stopReason } : {}),
...(failure.code !== undefined ? { code: failure.code } : {}),
...(failure.errorKind !== undefined ? { errorKind: failure.errorKind } : {}),
...(hold ? { hold: true } : {}),
};
return { text, card };
}
function askingTurn(branch, toolCallId) {
for (let i = branch.length - 1; i >= 0; i--) {
const e = branch[i];
if (e.type !== "message" || e.message.role !== "assistant")
continue;
const m = e.message;
if (!m.content.some((c) => c.type === "toolCall" && c.id === toolCallId))
continue;
return { ...m, content: m.content.filter((c) => c.type !== "toolCall" || c.id === toolCallId) };
}
return undefined;
}
function projection(sent, turn, toolCallId) {
const close = { role: "toolResult", toolCallId, toolName: ADVISOR_TOOL_NAME, content: [{ type: "text", text: ADVISOR_HANDOFF }], isError: false };
return [...sent.messages, turn, close];
}
function systemPromptOf(sent) {
const sentSystemText = sent.systemPrompt ?? sent.systemBlocks?.map((b) => b.text).join("") ?? "";
return sentSystemText === "" ? ADVISOR_SYSTEM_PROMPT : `${ADVISOR_SYSTEM_PROMPT}\n\n${AGENT_INSTRUCTIONS_HEADER}\n${sentSystemText}`;
}
function outcomeOf(model, r) {
const served = r.servedModel !== model.id ? { servedModel: r.servedModel } : {};
const base = { type: "advisor", model: model.id, ...served, stopReason: r.stopReason, usage: r.usage };
if ((r.stopReason === "stop" || r.stopReason === "length") && r.text.trim() !== "")
return { text: r.text, card: { ...base, outcome: "reviewed" } };
if (r.stopReason === "error" && r.errorCode === "refusal") {
const reason = r.errorMessage !== undefined ? stripErrorCodePrefix(r.errorMessage).trim() : "";
const bounded = reason !== "" ? egressText("same-principal", reason).slice(0, ADVISOR_MESSAGE_MAX_CHARS) : "";
return { text: `Advisor declined to advise on this request.${bounded !== "" ? ` Reason: ${bounded}` : ""}`, card: { ...base, outcome: "declined" } };
}
const failure = { ...(r.errorCode !== undefined ? { code: r.errorCode } : {}), ...(r.errorKind !== undefined ? { errorKind: r.errorKind } : {}), ...(r.inputTooLongRuledOut === true ? { inputTooLongRuledOut: true } : {}) };
const message = r.stopReason === "toolUse" ? "the advisor model answered with a tool call instead of guidance" : r.stopReason === "error" || r.stopReason === "aborted" ? (r.errorMessage !== undefined ? stripErrorCodePrefix(r.errorMessage) : undefined) : "the advisor model returned no guidance";
return unavailable(model, { ...failure, stopReason: r.stopReason }, message, advisorFailureHolds(failure), { ...served, usage: r.usage });
}
async function consult(seat, toolCallId, signal) {
const model = seat.model;
let branch;
try {
branch = await seat.readBranch();
}
catch {
return unavailable(model, {}, "the advisor's availability for this conversation could not be read; try again later", false);
}
const held = advisorHoldOf(branch);
if (held !== undefined)
return unavailable(model, held, undefined, true);
const sent = seat.lastSentRequest();
if (sent === undefined)
return unavailable(model, {}, "no request has been sent to the model on this resumed run yet; call advisor again", false);
const turn = askingTurn(branch, toolCallId) ?? { role: "assistant", content: [{ type: "toolCall", id: toolCallId, name: ADVISOR_TOOL_NAME, arguments: {} }] };
try {
const r = await runSideQuery({
model,
systemPrompt: systemPromptOf(sent),
messages: projection(sent, turn, toolCallId),
...(sent.tools !== undefined && sent.tools.length > 0 ? { tools: sent.tools.map((t) => ({ name: t.name, description: t.description, parameters: t.parameters })) } : {}),
...(signal !== undefined ? { signal } : {}),
...(seat.getApiKeyAndHeaders !== undefined ? { getApiKeyAndHeaders: seat.getApiKeyAndHeaders } : {}),
...(sent.promptLocale !== undefined ? { promptLocale: sent.promptLocale } : {}),
}, { brain: seat.brain });
return outcomeOf(model, r);
}
catch (e) {
seat.markUsageUnknown();
const failure = thrownBrainFailure(e);
return unavailable(model, { ...failure, stopReason: "error" }, stripErrorCodePrefix(thrownText(e)), advisorFailureHolds(failure));
}
}
export function createAdvisorTool(seat) {
return defineTool({
name: ADVISOR_TOOL_NAME,
...toolFace("advisor"),
ruleFace: mountRuleFace("advisor"),
label: seat.model.id,
description: "Consult the advisor: a stronger reviewer model reads this conversation and returns guidance. Takes no parameters.",
parameters: Type.Object({}),
execute: async (_args, ctx) => {
const { text, card } = await consult(seat, ctx.toolCallId, ctx.signal);
return { content: text, details: card, isError: card.outcome === "unavailable" };
},
});
}