@sema-agent/core
Version:
Stateless, task-oriented AI agent core
716 lines (715 loc) • 37.7 kB
JavaScript
import { isPlainRecord } from "../mods/kernel/receive.js";
import { needsAuthorizationArm } from "../mcp-failure.js";
import { ATTACHMENT_SOURCES } from "../attachment-source.js";
import { delimitUntrustedWithClip, inlineUntrusted, sanitizeUntrustedText, SHELLED_BODY_ENVELOPE_TAGS } from "../untrusted-text.js";
import { protocolOf } from "@sema-agent/primitives";
import { renderBackgroundTaskTable } from "../task-notification.js";
import { renderSkillLinesWithin, renderSkillsBlock } from "./synthetic-tools.js";
import { SKILL_LISTING_DEFAULT_BUDGET } from "../skill-listing-budget.js";
import { foldListingWithin, foldRemovalArmWithin, removalArmFloor } from "./listing-fold.js";
import { EVENT_PROMPT_REGISTRY, eventDefaultOn, eventMaxBytes } from "../../prompt-assembly/event-registry.js";
import { engineTextFor } from "../../prompt-assembly/engine-text.js";
import { TOOL_SEARCH_NAME as TOOL_SEARCH_TOOL_NAME } from "./tool-disclosure.js";
import { elapsedTimeSlots, silentTurnReminderDue } from "./boundary-reminders.js";
export const TODO_REMINDER_CONFIG = {
TURNS_SINCE_WRITE: 10,
TURNS_BETWEEN_REMINDERS: 10,
};
export const TOOL_SEARCH_REMINDER_CONFIG = {
EVERY_N_TURNS: 15,
MAX_NAMES: 10,
};
export const TOTAL_TOKENS_REMINDER_MODES = Object.freeze(["off", "infinite", "fixed", "countdown", "padded-countdown"]);
export const TOTAL_TOKENS_REMINDER_DEFAULT_MODE = "padded-countdown";
export const TOTAL_TOKENS_FIXED_ARM_VALUE = 5_000_000;
export const CHANGED_FILES_MAX = 20;
export const CHANGED_FILES_MTIME_EPS_MS = 2000;
export const ATTACHMENT_BYTE_CAP = 8 * 1024;
const PROJECTION_ITEMS_MAX = 50;
const PROJECTION_SCAN_MAX = 10_000;
const PROJECTION_CONTENT_MAX = 80;
const LISTING_FRAME_FLOOR_BYTES = 768;
export const WORKFLOW_CONTINUATION_MAX_BYTES = eventMaxBytes("workflow_continuation");
function readingOf({ engineText = engineTextFor() }) {
return engineText;
}
const INPUT_BOUNDS = {
tools_delta: (inp) => toolsDeltaBound(inp),
mcp_unavailable: () => MCP_UNAVAILABLE_MAX_BYTES,
agent_listing: (inp) => listingFrameBound(inp.listingBudget) + (inp.agentModels !== undefined ? Buffer.byteLength(modelsAvailableLine(inp.agentModels, readingOf(inp)), "utf8") : 0),
skills_listing: (inp) => listingFrameBound(inp.listingBudget),
mcp_instructions: (inp) => mcpInstructionsBound(inp),
mcp_dropped_tools: (inp) => mcpDroppedToolsBound(inp),
};
function deliveryClassOf(source) {
const row = EVENT_PROMPT_REGISTRY.get(source);
if (row?.dedupe === undefined)
throw new Error(`attachment source "${source}" has no event registry row that says how the bundle treats it (dedupe)`);
if (row.dedupe === "repeat")
return Object.freeze({ class: "clippable" });
const bound = INPUT_BOUNDS[source];
if (bound !== undefined)
return Object.freeze({ class: "intact", bound });
const ceiling = eventMaxBytes(source);
return Object.freeze({ class: "intact", bound: () => ceiling });
}
export const ATTACHMENT_DELIVERY_CLASS = Object.freeze(Object.fromEntries(ATTACHMENT_SOURCES.map((s) => [s, deliveryClassOf(s)])));
export function isIntactSource(source) {
return ATTACHMENT_DELIVERY_CLASS[source].class === "intact";
}
function listingFrameBound(budget) {
return Math.max((budget ?? SKILL_LISTING_DEFAULT_BUDGET).blockMaxBytes, LISTING_FRAME_FLOOR_BYTES);
}
const ATTACHMENT_TAGS_DEFAULT = [...SHELLED_BODY_ENVELOPE_TAGS];
const ATTACHMENT_TAGS_OWNED = {
skills_listing: SHELLED_BODY_ENVELOPE_TAGS.filter((t) => t !== "skills"),
total_tokens_reminder: SHELLED_BODY_ENVELOPE_TAGS.filter((t) => t !== "total_tokens"),
};
export function attachmentEnvelopeTags(source) {
return ATTACHMENT_TAGS_OWNED[source] ?? ATTACHMENT_TAGS_DEFAULT;
}
export function createAttachmentState() {
return {
lastTodoReminderTurn: 0,
lastTaskReminderTurn: 0,
lastToolSearchReminderTurn: 0,
postCompactPending: false,
};
}
function listOf(value) {
if (!Array.isArray(value) || Object.getPrototypeOf(value) !== Array.prototype)
return undefined;
const items = [];
for (let i = 0; i < Math.min(value.length, PROJECTION_SCAN_MAX); i++)
if (Object.hasOwn(value, i))
items.push(value[i]);
return items;
}
function readTaskEntry(raw) {
if (!isPlainRecord(raw) || typeof raw.id !== "string")
return undefined;
const { id, subject, status } = raw;
return { id, item: { content: typeof subject === "string" ? subject.slice(0, PROJECTION_CONTENT_MAX) : "", status: typeof status === "string" ? status : "pending" } };
}
export function reduceToolEnd(state, details) {
if (!isPlainRecord(details))
return;
const type = details.type;
if (type === "todo") {
const newTodos = listOf(details.newTodos);
if (newTodos === undefined)
return;
const shaped = [];
for (const item of newTodos) {
if (!isPlainRecord(item))
continue;
const { content, status } = item;
if (typeof content === "string" && typeof status === "string")
shaped.push({ content: content.slice(0, PROJECTION_CONTENT_MAX), status });
}
const allDone = shaped.length > 0 && shaped.every((t) => t.status === "completed");
state.todo = allDone ? { items: [] } : { items: shaped.slice(0, PROJECTION_ITEMS_MAX) };
}
else if (type === "task") {
const map = state.taskItems ?? (state.taskItems = new Map());
const deleted = details.deleted;
if (typeof deleted === "string")
map.delete(deleted);
const entry = readTaskEntry(details.task);
if (entry !== undefined)
map.set(entry.id, entry.item);
}
else if (type === "task-list") {
const tasks = listOf(details.tasks);
if (tasks === undefined)
return;
const map = new Map();
for (const raw of tasks) {
const entry = readTaskEntry(raw);
if (entry !== undefined)
map.set(entry.id, entry.item);
}
state.taskItems = map;
}
}
export function stampWriteAnchor(state, family, clock) {
if (family === "task")
state.taskLastWriteTurn = clock;
else if (family === "tool_search")
state.toolSearchLastUseTurn = clock;
else
state.todoLastWriteTurn = clock;
}
export function advanceCadenceClock(state, clock, content, writeFamilyOf) {
if (!Array.isArray(content))
return clock + 1;
for (const b of content) {
const t = b?.type;
if (t === "thinking" || t === "redacted_thinking")
continue;
clock += 1;
if (t === "toolCall") {
const name = b.name;
const family = typeof name === "string" ? writeFamilyOf(name) : undefined;
if (family !== undefined)
stampWriteAnchor(state, family, clock);
}
}
return clock;
}
export function rebaseCadenceWindows(state, clock) {
state.taskLastWriteTurn = clock;
state.todoLastWriteTurn = clock;
state.lastTaskReminderTurn = clock;
state.lastTodoReminderTurn = clock;
state.toolSearchLastUseTurn = clock;
state.lastToolSearchReminderTurn = clock;
}
const EMPTY = Object.freeze([]);
export function collectDueAttachments(state, inp) {
let out;
const say = readingOf(inp);
if (inp.config.todoReminderMode !== "off" && inp.config.todoReminder && (inp.todoMounted || inp.taskListMounted)) {
const cadenceNow = inp.cadenceTurn ?? inp.turn;
if (inp.taskListMounted) {
const lastWrite = state.taskLastWriteTurn ?? 0;
if (cadenceNow - lastWrite >= TODO_REMINDER_CONFIG.TURNS_SINCE_WRITE &&
cadenceNow - state.lastTaskReminderTurn >= TODO_REMINDER_CONFIG.TURNS_BETWEEN_REMINDERS) {
(out ??= []).push({ source: "task_reminder", body: renderTaskReminder(state, say), commit: () => void (state.lastTaskReminderTurn = cadenceNow) });
}
}
else {
const lastWrite = state.todoLastWriteTurn ?? 0;
if (cadenceNow - lastWrite >= TODO_REMINDER_CONFIG.TURNS_SINCE_WRITE &&
cadenceNow - state.lastTodoReminderTurn >= TODO_REMINDER_CONFIG.TURNS_BETWEEN_REMINDERS) {
(out ??= []).push({ source: "todo_reminder", body: renderTodoReminder(state, say), commit: () => void (state.lastTodoReminderTurn = cadenceNow) });
}
}
}
if (inp.config.toolSearchReminder &&
inp.undiscoveredTools !== undefined &&
inp.undiscoveredTools.length > 0 &&
!(out ?? []).some((a) => a.source === "todo_reminder" || a.source === "task_reminder")) {
const cadenceNow = inp.cadenceTurn ?? inp.turn;
const sinceUse = state.toolSearchLastUseTurn === undefined ? Number.POSITIVE_INFINITY : cadenceNow - state.toolSearchLastUseTurn;
if (sinceUse >= TOOL_SEARCH_REMINDER_CONFIG.EVERY_N_TURNS && cadenceNow - state.lastToolSearchReminderTurn >= TOOL_SEARCH_REMINDER_CONFIG.EVERY_N_TURNS) {
(out ??= []).push({ source: "tool_search_usage_reminder", body: renderToolSearchUsageReminder(inp.undiscoveredTools, inp.deferDirectCall !== false, say), commit: () => void (state.lastToolSearchReminderTurn = cadenceNow) });
}
}
if (inp.outputStyle !== undefined)
(out ??= []).push({ source: "output_style", body: inp.outputStyle });
const silentArm = inp.config.silentTurnReminder;
if (silentArm !== undefined && silentArm !== "off" && inp.silentTurn !== undefined && silentTurnReminderDue(inp.silentTurn.stretch, silentArm, inp.silentTurn.now)) {
(out ??= []).push({ source: "silent_turn_reminder", body: renderSilentTurnReminder(say) });
}
if (inp.config.elapsedTimeReminder === true && inp.elapsedMs !== undefined) {
(out ??= []).push({ source: "elapsed_time_reminder", body: renderElapsedTime(inp.elapsedMs, say) });
}
if (inp.config.budgetUsd && inp.budgetUsd !== undefined) {
(out ??= []).push({ source: "budget_usd", body: renderBudgetUsd(inp.budgetUsd.used, inp.budgetUsd.total, say) });
}
if (inp.config.totalTokensReminder === true) {
const mode = inp.config.totalTokensReminderMode ?? TOTAL_TOKENS_REMINDER_DEFAULT_MODE;
if (mode === "infinite" || mode === "fixed") {
(out ??= []).push({ source: "total_tokens_reminder", body: renderTotalTokensReminder(mode, 0, say) });
}
else if ((mode === "countdown" || mode === "padded-countdown") && inp.totalTokens !== undefined) {
const { used, total } = inp.totalTokens;
if (Number.isFinite(used) && Number.isFinite(total) && used >= 0 && total >= 0) {
const effectiveUsed = mode === "padded-countdown" ? (state.totalTokensFloor = Math.max(state.totalTokensFloor ?? 0, used)) : used;
(out ??= []).push({ source: "total_tokens_reminder", body: renderTotalTokensReminder(mode, total - effectiveUsed, say) });
}
}
}
if (inp.config.backgroundTasks && state.postCompactPending) {
if (inp.backgroundTasks !== undefined && inp.backgroundTasks.length > 0) {
(out ??= []).push({ source: "background_tasks", body: renderBackgroundTasks(inp.backgroundTasks, say), echoBound: ATTACHMENT_BYTE_CAP, commit: () => void (state.postCompactPending = false) });
}
else {
state.postCompactPending = false;
}
}
if (inp.config.toolsDelta) {
const body = renderToolsDelta({
...(inp.newTools !== undefined ? { added: inp.newTools } : {}),
...(inp.newToolsStaticFace === true ? { staticFace: true } : {}),
...(inp.newToolsSwappedUnderStatic !== undefined && inp.newToolsSwappedUnderStatic.length > 0
? { swappedUnderStatic: inp.newToolsSwappedUnderStatic }
: {}),
...(inp.readdedToolsSwappedUnderStatic !== undefined && inp.readdedToolsSwappedUnderStatic.length > 0
? { readdedSwappedUnderStatic: inp.readdedToolsSwappedUnderStatic }
: {}),
...(inp.mcpToolsDelta ?? {}),
}, say);
if (body !== undefined)
(out ??= []).push({ source: "tools_delta", body });
}
const agentListingBody = inp.config.agentListing && inp.agentListing !== undefined
? renderAgentListingDelta(state, inp.agentListing, inp.agentToolName ?? "Agent", inp.agentModels, inp.listingBudget, say)
: undefined;
if (agentListingBody !== undefined)
(out ??= []).push({ source: "agent_listing", body: agentListingBody });
const skillsListingBody = inp.config.skillsListing && inp.skillsListing !== undefined
? renderSkillsListingDelta(state, inp.skillsListing, inp.listingBudget, say)
: undefined;
if (skillsListingBody !== undefined)
(out ??= []).push({ source: "skills_listing", body: skillsListingBody });
if (inp.config.mcpInstructions && inp.mcpInstructions !== undefined) {
const body = renderMcpInstructionsDelta(inp.mcpInstructions.added, inp.mcpInstructions.removed, say);
if (body !== undefined)
(out ??= []).push({ source: "mcp_instructions", body });
}
if (inp.config.mcpInstructions && inp.mcpDroppedTools !== undefined && inp.mcpDroppedTools.length > 0) {
(out ??= []).push({ source: "mcp_dropped_tools", body: renderMcpDroppedTools(inp.mcpDroppedTools, say) });
}
if (inp.config.changedFiles && inp.changedFiles !== undefined) {
const frame = collectChangedFilesAttachment(inp.changedFiles, say);
if (frame !== undefined)
(out ??= []).push(frame);
}
if (out === undefined)
return EMPTY;
return capAttachments(out);
}
export function collectChangedFilesAttachment(changed, say = engineTextFor()) {
if (changed.length === 0)
return undefined;
return { source: "changed_files", body: renderChangedFiles(changed.map((c) => c.path), say), noticed: changed.map((c) => ({ path: c.path, mtimeMs: c.mtimeMs })) };
}
export function collectChangedFilesFirstRequestFrame(changed, say = engineTextFor()) {
const frame = collectChangedFilesAttachment(changed, say);
if (frame === undefined)
return undefined;
const [capped] = capAttachments([frame]);
return capped === undefined ? undefined : { ...frame, body: capped.body };
}
export function changedFilesNoticeIn(text, block, frame) {
const at = text.indexOf(block);
if (at < 0 || frame.noticed === undefined)
return undefined;
const tags = attachmentEnvelopeTags("changed_files");
const files = [];
let cursor = 0;
for (const f of frame.noticed) {
const line = `\n${sanitizeUntrustedText(`- ${f.path}`, tags)}`;
let found = -1;
for (let i = block.indexOf(line, cursor); i >= 0; i = block.indexOf(line, i + 1)) {
if (block[i + line.length] === "\n") {
found = i;
break;
}
}
if (found < 0)
break;
files.push({ path: f.path, mtimeMs: f.mtimeMs, start: at + found, end: at + found + line.length });
cursor = found + line.length;
}
return files.length === 0 ? undefined : { start: at, end: at + block.length, files };
}
function renderTodoReminder(state, say) {
const items = state.todo?.items ?? [];
let message = `${say("core/event.todo-reminder")}\n`;
if (items.length > 0) {
const todoItems = items.map((t, i) => `${i + 1}. [${t.status}] ${t.content}`).join("\n");
message += `\n\n${say("core/event.todo-reminder.list", { items: todoItems })}`;
}
return message;
}
function renderTaskReminder(state, say) {
const entries = [...(state.taskItems ?? new Map())]
.sort((a, b) => Number(a[0]) - Number(b[0]))
.slice(0, PROJECTION_ITEMS_MAX);
let message = `${say("core/event.task-reminder")}\n`;
if (entries.length > 0) {
const taskItems = entries.map(([id, t]) => `#${id}. [${t.status}] ${t.content}`).join("\n");
message += `\n\n${say("core/event.task-reminder.list", { items: taskItems })}`;
}
return message;
}
export function renderToolSearchUsageReminder(undiscovered, directCallEnabled = true, say = engineTextFor()) {
const shown = undiscovered.slice(0, TOOL_SEARCH_REMINDER_CONFIG.MAX_NAMES);
const more = undiscovered.length - shown.length;
const names = more > 0 ? say("core/event.tool-search-usage-reminder.more", { names: shown.join(", "), count: String(more) }) : shown.join(", ");
return say(directCallEnabled ? "core/event.tool-search-usage-reminder" : "core/event.tool-search-usage-reminder.no-direct-call", { names, search: TOOL_SEARCH_TOOL_NAME });
}
export function renderDateChange(newDate, say) {
return say("core/event.date-change", { date: newDate });
}
export function collectDateChange(state, today, say) {
if (today === state.announcedDate)
return undefined;
return { source: "date_change", body: renderDateChange(today, say) };
}
export function renderSilentTurnReminder(say) {
return say("core/event.silent-turn-reminder");
}
export function renderElapsedTime(ms, say) {
return say("core/event.elapsed-time", elapsedTimeSlots(ms));
}
export function renderBudgetUsd(used, total, say = engineTextFor()) {
return say("core/event.budget-usd", { used: String(used), total: String(total), remaining: String(total - used) });
}
export function renderTotalTokensReminder(mode, remaining, say = engineTextFor()) {
const shown = mode === "infinite" ? say("core/event.total-tokens.infinite") : String(mode === "fixed" ? TOTAL_TOKENS_FIXED_ARM_VALUE : Math.max(0, remaining));
return say("core/event.total-tokens", { count: shown });
}
export function renderOrphanedBackgroundTasks(tasks, say) {
const safe = (t) => sanitizeUntrustedText(t, SHELLED_BODY_ENVELOPE_TAGS);
const lines = tasks.map((t) => `- ${say("core/event.orphaned-background-tasks.line", { description: safe(t.description || say("core/event.orphaned-background-tasks.no-description")), id: safe(t.id) })}`);
return say("core/event.orphaned-background-tasks", { list: lines.join("\n") });
}
function renderChangedFiles(paths, say) {
return say("core/event.changed-files", { paths: paths.map((p) => `- ${p}`).join("\n") });
}
function renderBackgroundTasks(tasks, say) {
return say("core/event.background-tasks", { table: renderBackgroundTaskTable(tasks) });
}
export const TOOLS_DELTA_LIST_MAX = 30;
function groupByMcpServer(names) {
const counts = new Map();
for (const n of names) {
const key = protocolOf(n)?.displayGroupKey(n) ?? n;
counts.set(key, (counts.get(key) ?? 0) + 1);
}
return [...counts.entries()]
.sort(([a], [b]) => a.localeCompare(b))
.map(([k, c]) => (c > 1 ? `${k} (${c})` : k))
.join(", ");
}
export function renderMcpUnavailable(entries, say = engineTextFor()) {
const failed = entries.filter((f) => f.authorization === undefined && f.connecting !== true);
const connecting = entries.filter((f) => f.connecting === true);
const stillConnecting = connecting.length === 0
? undefined
: `${say("core/event.mcp-unavailable.still-connecting", { servers: `${connecting.slice(0, TOOLS_DELTA_LIST_MAX).map((f) => f.name).join("\n")}${connecting.length > TOOLS_DELTA_LIST_MAX ? `\n${say("core/event.mcp-unavailable.more", { count: String(connecting.length - TOOLS_DELTA_LIST_MAX) })}` : ""}` })}${connecting[0].waitTool !== undefined ? ` ${say("core/event.mcp-unavailable.still-connecting-wait", { tool: connecting[0].waitTool })}` : ""}`;
const listed = (group, header) => {
if (group.length === 0)
return undefined;
const head = group.slice(0, TOOLS_DELTA_LIST_MAX).map((f) => `${f.name}${f.error === undefined ? "" : f.classLine === true ? ` ${f.error}` : `: "${f.error}"`}`).join("\n");
const more = group.length > TOOLS_DELTA_LIST_MAX ? `\n${say("core/event.mcp-unavailable.more", { count: String(group.length - TOOLS_DELTA_LIST_MAX) })}` : "";
return say(header, { servers: `${head}${more}` });
};
const forNow = listed(failed.filter((f) => f.remembered !== true), "core/event.mcp-unavailable.for-now");
const lists = [listed(failed.filter((f) => f.remembered === true), "core/event.mcp-unavailable.for-this-session"), forNow].filter((l) => l !== undefined);
const arms = [
stillConnecting,
needsAuthorizationArm(entries, TOOLS_DELTA_LIST_MAX, say),
lists.length === 0
? undefined
: `${lists.join("\n\n")}\n\n${forNow !== undefined ? `${say("core/event.mcp-unavailable.retried")} ` : ""}${say("core/event.mcp-unavailable.connection-failure")}`,
].filter((arm) => arm !== undefined);
return arms.length > 0 ? arms.join("\n\n") : undefined;
}
export function mcpUnavailableOn(cfg) {
return attachmentSwitchOn(cfg, "mcpUnavailable", "mcp_unavailable");
}
export function attachmentSwitchOn(cfg, key, kind) {
const declared = cfg?.[key];
if (declared === undefined)
return eventDefaultOn(kind);
if (typeof declared !== "boolean") {
const field = `TaskSpec.attachments.${key}`;
const e = new Error(`${field} must be a boolean when present (got ${declared === null ? "null" : Array.isArray(declared) ? "an array" : typeof declared}) — refused rather than read as on or off; omit the key for the default.`);
e.code = "config.invalid_argument";
e.detail = { field };
throw e;
}
return declared;
}
export function owedMcpUnavailable(prepared, cfg) {
const entries = mcpUnavailableOn(cfg) ? [...(prepared.mcpUnavailable?.pending ?? [])] : [];
const body = renderMcpUnavailable(entries, prepared.engineText);
return body === undefined ? undefined : { body, entries };
}
export function renderToolsDelta(input, say = engineTextFor()) {
const blocks = [];
const added = input.added ?? [];
if (added.length > 0) {
const swapped = input.staticFace === true ? (input.swappedUnderStatic ?? []).filter((n) => added.includes(n)) : [];
const grouped = added.length > TOOLS_DELTA_LIST_MAX;
const exception = swapped.length > 0
? `\n${grouped ? say("core/event.tools-delta.exception-grouped", { count: String(swapped.length) }) : say("core/event.tools-delta.exception", { names: swapped.join(", ") })}`
: "";
const lead = grouped
? say(input.staticFace === true ? "core/event.tools-delta.added-static-grouped" : "core/event.tools-delta.added-grouped", { count: String(added.length), groups: groupByMcpServer(added) })
: say(input.staticFace === true ? "core/event.tools-delta.added-static" : "core/event.tools-delta.added", { list: added.map((n) => `- ${n}`).join("\n") });
blocks.push(lead + exception);
}
const readded = input.readded ?? [];
if (readded.length > 0) {
const swappedBack = input.staticFace === true ? (input.readdedSwappedUnderStatic ?? []).filter((n) => readded.includes(n)) : [];
const lead = say(readded.length === 1 ? "core/event.tools-delta.readded-one" : "core/event.tools-delta.readded", { count: String(readded.length), groups: groupByMcpServer(readded) });
const steer = input.staticFace === true
? say("core/event.tools-delta.readded-static") + (swappedBack.length > 0 ? ` ${say("core/event.tools-delta.exception", { names: swappedBack.join(", ") })}` : "")
: say("core/event.tools-delta.readded-loaded");
blocks.push(`${lead} ${steer}`);
}
const removed = input.removed ?? [];
if (removed.length > 0) {
blocks.push(removed.length > TOOLS_DELTA_LIST_MAX
? say("core/event.tools-delta.removed-grouped", { count: String(removed.length), groups: groupByMcpServer(removed), search: TOOL_SEARCH_TOOL_NAME })
: say("core/event.tools-delta.removed", { search: TOOL_SEARCH_TOOL_NAME, names: removed.join("\n") }));
blocks.push(say("core/event.ambient-context"));
}
return blocks.length > 0 ? blocks.join("\n\n") : undefined;
}
export function agentListingInitialHeader(toolName, say = engineTextFor()) {
return say("core/event.agent-listing", { tool: sanitizeUntrustedText(toolName, SHELLED_BODY_ENVELOPE_TAGS) });
}
function listingIdentity(name) {
return sanitizeUntrustedText(name, SHELLED_BODY_ENVELOPE_TAGS);
}
export function agentListingDeltaHeader(toolName, say = engineTextFor()) {
return say("core/event.agent-listing.added", { tool: sanitizeUntrustedText(toolName, SHELLED_BODY_ENVELOPE_TAGS) });
}
export function agentListingRemovedHeader(say = engineTextFor()) {
return say("core/event.agent-listing.removed");
}
export function agentListingHeaders(toolName, say = engineTextFor()) {
return { initial: agentListingInitialHeader(toolName, say), delta: agentListingDeltaHeader(toolName, say), removed: agentListingRemovedHeader(say) };
}
export function renderAgentListingFrame(state, entries, toolName, models, budget = SKILL_LISTING_DEFAULT_BUDGET, say = engineTextFor()) {
const safe = (t) => sanitizeUntrustedText(t, SHELLED_BODY_ENVELOPE_TAGS);
const line = (e) => {
const base = e.description ? `- ${safe(e.name)}: ${safe(e.description)}` : `- ${safe(e.name)}`;
return `${base} ${say("core/event.agent-listing.tools", { tools: safe(e.tools ?? say("core/event.agent-listing.all-tools")) })}`;
};
const bytes = (s) => Buffer.byteLength(s, "utf8");
const joiner = bytes(AGENT_DELTA_BLOCK_JOINER);
const moreRemoved = (n) => say("core/event.listing.more-removed", { count: String(n) });
const fold = (items, header, maxBytes) => foldListingWithin(items, {
blockMaxBytes: maxBytes,
full: line,
nameOnly: (e) => `- ${safe(e.name)}`,
nameOf: (e) => e.name,
capMarker: say("core/event.agent-listing.capped"),
overflowLine: (n) => say("core/event.agent-listing.more", { count: String(n) }),
frame: (lines) => [header, ...lines].join("\n"),
});
const announced = state.announcedAgentTypes;
if (announced === undefined) {
if (entries.length === 0)
return undefined;
const tail = [];
if (entries.length > 1)
tail.push(say("core/event.agent-listing.concurrency"));
if (models !== undefined && models.length > 0)
tail.push(modelsAvailableLine(models, say));
const tailCost = tail.reduce((acc, t) => acc + joiner + bytes(t), 0);
const roster = fold(entries, agentListingInitialHeader(toolName, say), budget.blockMaxBytes - tailCost);
return { text: [roster.text, ...tail].join(AGENT_DELTA_BLOCK_JOINER), nameOnly: roster.nameOnly, dropped: roster.dropped, listed: entries.length };
}
const announcedIds = new Set([...announced.keys()].map(listingIdentity));
const entryIds = new Set(entries.map((e) => listingIdentity(e.name)));
const added = entries.filter((e) => !announcedIds.has(listingIdentity(e.name))).toSorted((a, b) => a.name.localeCompare(b.name));
const removed = [...announced.keys()].filter((n) => !entryIds.has(listingIdentity(n))).sort();
const modelsDrifted = state.announcedModels !== undefined &&
models !== undefined &&
(state.announcedModels.length !== models.length ||
state.announcedModels.some((m, i) => listingIdentity(m) !== listingIdentity(models[i])));
if (added.length === 0 && removed.length === 0 && !modelsDrifted)
return undefined;
const modelsLine = modelsDrifted ? modelsAvailableLine(models, say) : undefined;
const modelsCost = modelsLine !== undefined ? joiner + bytes(modelsLine) : 0;
const ambient = say("core/event.ambient-context");
const removedHeader = agentListingRemovedHeader(say);
const ambientCost = removed.length > 0 ? joiner + bytes(ambient) : 0;
const removalReserve = removed.length > 0 ? joiner + bytes(removalArmFloor(removedHeader, removed.length, moreRemoved)) : 0;
const addArm = added.length > 0 ? fold(added, agentListingDeltaHeader(toolName, say), budget.blockMaxBytes - modelsCost - ambientCost - removalReserve) : undefined;
const addCost = addArm === undefined ? 0 : bytes(addArm.text) + joiner;
const blocks = addArm === undefined ? [] : [addArm.text];
if (removed.length > 0) {
blocks.push(foldRemovalArmWithin(removed, removedHeader, budget.blockMaxBytes - modelsCost - ambientCost - addCost, moreRemoved));
blocks.push(ambient);
}
if (modelsLine !== undefined)
blocks.push(modelsLine);
return { text: blocks.join(AGENT_DELTA_BLOCK_JOINER), nameOnly: addArm?.nameOnly ?? [], dropped: addArm?.dropped ?? [], listed: added.length };
}
export function renderAgentListingDelta(state, entries, toolName, models, budget, say) {
return renderAgentListingFrame(state, entries, toolName, models, budget, say)?.text;
}
const AGENT_DELTA_BLOCK_JOINER = "\n\n";
export function modelsPrefix(say) {
return `${say("core/event.agent-listing.models")} `;
}
function modelsAvailableLine(models, say) {
const named = models.map((m) => sanitizeUntrustedText(m, SHELLED_BODY_ENVELOPE_TAGS));
return `${modelsPrefix(say)}${named.length > 0 ? named.join(", ") : say("core/event.agent-listing.models-none")}`;
}
export function commitAgentListing(state, entries, models) {
state.announcedAgentTypes = new Map(entries.map((e) => [e.name, e.description]));
if (models !== undefined)
state.announcedModels = [...models];
}
export function skillsListingHeaders(say = engineTextFor()) {
return { initial: say("core/event.skills-listing"), delta: say("core/event.skills-listing.added"), removed: say("core/event.skills-listing.removed") };
}
const SKILLS_DELTA_BLOCK_JOINER = "\n\n";
export function renderSkillsListingFrame(state, entries, budget = SKILL_LISTING_DEFAULT_BUDGET, say = engineTextFor()) {
const announced = state.announcedSkills;
if (announced === undefined) {
if (entries.length === 0)
return undefined;
const block = renderSkillsBlock(entries, budget, say);
return block === undefined ? undefined : { ...block, listed: entries.length };
}
const announcedIds = new Set([...announced.keys()].map(listingIdentity));
const entryIds = new Set(entries.map((e) => listingIdentity(e.name)));
const added = entries.filter((e) => !announcedIds.has(listingIdentity(e.name)));
const removed = [...announced.keys()].filter((n) => !entryIds.has(listingIdentity(n)));
if (added.length === 0 && removed.length === 0)
return undefined;
const bytes = (s) => Buffer.byteLength(s, "utf8");
const joiner = bytes(SKILLS_DELTA_BLOCK_JOINER);
const frameMaxBytes = budget.blockMaxBytes;
const headers = skillsListingHeaders(say);
const ambient = say("core/event.ambient-context");
const moreRemoved = (n) => say("core/event.listing.more-removed", { count: String(n) });
const ambientCost = removed.length > 0 ? joiner + bytes(ambient) : 0;
const removalReserve = removed.length > 0 ? joiner + bytes(removalArmFloor(headers.removed, removed.length, moreRemoved)) : 0;
const addArm = added.length > 0
? renderSkillLinesWithin(added, {
blockMaxBytes: frameMaxBytes - ambientCost - removalReserve,
descMaxChars: budget.descMaxChars,
frame: (lines) => [headers.delta, ...lines].join("\n"),
say,
})
: undefined;
const addCost = addArm === undefined ? 0 : bytes(addArm.text) + (removed.length > 0 ? joiner : 0);
const blocks = addArm === undefined ? [] : [addArm.text];
if (removed.length > 0) {
blocks.push(foldRemovalArmWithin(removed, headers.removed, frameMaxBytes - ambientCost - addCost, moreRemoved), ambient);
}
return {
text: blocks.join(SKILLS_DELTA_BLOCK_JOINER),
nameOnly: addArm?.nameOnly ?? [],
dropped: addArm?.dropped ?? [],
listed: added.length,
};
}
export function renderSkillsListingDelta(state, entries, budget, say) {
return renderSkillsListingFrame(state, entries, budget, say)?.text;
}
export function commitSkillsListing(state, entries) {
state.announcedSkills = new Map(entries.map((e) => [e.name, e.description]));
}
export const MCP_INSTRUCTIONS_MAX_CHARS = 4096;
export function fenceMcpServerInstructions(server, text, say = engineTextFor()) {
const fence = delimitUntrustedWithClip(say("core/engine.mcp-fence-label", { server }), text, MCP_INSTRUCTIONS_MAX_CHARS);
return fence.clipped ? `${fence.text}\n${mcpInstructionsTruncationNote(say)}` : fence.text;
}
function mcpInstructionsTruncationNote(say) {
return say("core/engine.mcp-entry-truncated", { max: String(MCP_INSTRUCTIONS_MAX_CHARS) });
}
export function renderMcpInstructionsEntry(entry, say = engineTextFor()) {
if (entry.author !== "host")
return fenceMcpServerInstructions(entry.server, entry.text, say);
const cps = [...entry.text];
const body = cps.length > MCP_INSTRUCTIONS_MAX_CHARS ? `${cps.slice(0, MCP_INSTRUCTIONS_MAX_CHARS - 1).join("")}…\n${mcpInstructionsTruncationNote(say)}` : entry.text;
return `## ${inlineUntrusted(entry.server, 160)}\n${body}`;
}
export function renderMcpInstructionsDelta(added, removed, say = engineTextFor()) {
const blocks = [];
if (added.length > 0) {
blocks.push(`${say("core/engine.mcp-header")}\n\n${say("core/engine.mcp-intro")}\n\n${added.map((entry) => renderMcpInstructionsEntry(entry, say)).join("\n\n")}`);
}
if (removed.length > 0) {
blocks.push(`${say("core/engine.mcp-disconnected")}\n${removed.join("\n")}`);
blocks.push(say("core/event.ambient-context"));
}
return blocks.length > 0 ? blocks.join("\n\n") : undefined;
}
export function renderMcpDroppedTools(entries, say = engineTextFor()) {
const lines = entries.map((e) => say("core/event.mcp-dropped-tools.entry", { tool: e.tool, server: e.server, reason: e.reason })).join("\n");
return `${say("core/event.mcp-dropped-tools", { entries: lines })}\n\n${say("core/event.ambient-context")}`;
}
export const MCP_DROPPED_BATCH_MAX_BYTES = eventMaxBytes("mcp_dropped_tools");
export function selectMcpDroppedBatch(entries, say = engineTextFor()) {
const out = [];
for (const e of entries) {
out.push(e);
if (out.length > 1 && Buffer.byteLength(renderMcpDroppedTools(out, say), "utf8") > MCP_DROPPED_BATCH_MAX_BYTES) {
out.pop();
break;
}
}
return out;
}
const TOOLS_DELTA_FIXED_MAX_BYTES = 2048;
function toolsDeltaBound(inp) {
const bytes = (s) => Buffer.byteLength(s, "utf8");
const list = (names) => (names.length > TOOLS_DELTA_LIST_MAX ? bytes(groupByMcpServer(names)) : names.reduce((acc, n) => acc + bytes(n) + 3, 0));
const swapped = (names) => names.reduce((acc, n) => acc + bytes(n) + 2, 0);
const mcp = inp.mcpToolsDelta;
return (TOOLS_DELTA_FIXED_MAX_BYTES +
list(inp.newTools ?? []) +
swapped(inp.newToolsSwappedUnderStatic ?? []) +
bytes(groupByMcpServer(mcp?.readded ?? [])) +
swapped(inp.readdedToolsSwappedUnderStatic ?? []) +
list(mcp?.removed ?? []));
}
const MCP_UNAVAILABLE_MAX_BYTES = 2048 + TOOLS_DELTA_LIST_MAX * ((160 + 240) * 4 + 8);
const MCP_INSTRUCTIONS_FENCE_MAX_BYTES = 512;
function mcpInstructionsBound(inp) {
const bytes = (s) => Buffer.byteLength(s, "utf8");
const m = inp.mcpInstructions;
if (m === undefined)
return 0;
return (512 +
m.added.reduce((acc, a) => acc + MCP_INSTRUCTIONS_MAX_CHARS * 4 + bytes(a.server) + MCP_INSTRUCTIONS_FENCE_MAX_BYTES, 0) +
m.removed.reduce((acc, n) => acc + bytes(n) + 1, 0));
}
const MCP_DROPPED_FIXED_MAX_BYTES = 1024;
function mcpDroppedToolsBound(inp) {
const bytes = (s) => Buffer.byteLength(s, "utf8");
const first = inp.mcpDroppedTools?.[0];
const single = first === undefined ? 0 : MCP_DROPPED_FIXED_MAX_BYTES + bytes(first.tool) + bytes(first.server) + bytes(first.reason) + 32;
return Math.max(MCP_DROPPED_BATCH_MAX_BYTES, single);
}
const TRUNCATION_MARKER = "\n…[truncated]";
const MIN_KEEP_BYTES = 160;
function capAttachments(atts) {
let total = 0;
for (const a of atts)
if (!isIntactSource(a.source))
total += Buffer.byteLength(a.body, "utf8");
if (total <= ATTACHMENT_BYTE_CAP)
return atts;
let budget = ATTACHMENT_BYTE_CAP;
const out = [];
for (const a of atts) {
if (isIntactSource(a.source)) {
out.push(a);
continue;
}
const len = Buffer.byteLength(a.body, "utf8");
if (len <= budget) {
out.push(a);
budget -= len;
}
else if (budget >= MIN_KEEP_BYTES) {
const clipped = clipToBytes(a.body, budget - Buffer.byteLength(TRUNCATION_MARKER, "utf8"));
out.push({ ...a, body: clipped + TRUNCATION_MARKER });
budget = 0;
}
else {
budget = 0;
}
}
return out;
}
export function clipToBytes(s, maxBytes) {
if (Buffer.byteLength(s, "utf8") <= maxBytes)
return s;
let lo = 0;
let hi = s.length;
while (lo < hi) {
const mid = (lo + hi + 1) >> 1;
if (Buffer.byteLength(s.slice(0, mid), "utf8") <= maxBytes)
lo = mid;
else
hi = mid - 1;
}
return s.slice(0, lo);
}