@sema-agent/core
Version:
Stateless, task-oriented AI agent core
1,868 lines • 83.5 kB
JavaScript
import { findToolByName, relayedTextOf, toolNameIndex, validateToolArguments } from "../llm/index.js";
import { truncateError } from "../../core/tool-errors.js";
import { judgeToolNameMiss, mountedToolNames } from "../../core/tool-name-aliases.js";
import { userRowSourceOf } from "../../core/user-row-origin.js";
import { engineTextFor } from "../../prompt-assembly/engine-text.js";
import { emitBrainStatus } from "../../brain/status-sink.js";
import { outputCapLoweredDetail } from "../../brain/context-overflow.js";
import { INTERRUPTED_BY_USER_FOR_TOOL_USE_MARKER, INTERRUPTED_BY_USER_MARKER, } from "../../core/session-reconcile.js";
import { resolveAgentCoreStreamFn } from "./runtime-deps.js";
import { isErrorLike, readMember, readOwnMembers, thrownMarksOf } from "../../core/thrown-value.js";
import { egressThrownText, egressValue } from "../../core/untrusted-egress.js";
import { remoteWords } from "../../core/protocol-http-auth.js";
import { types } from "node:util";
import { admitToolResultMediaBlocks, firstUnprocessedOverTarget, toolResultMediaBlocks } from "../../core/image-admission.js";
import { resolveImageProcessor } from "../../core/image-downsample.js";
import { runWithCommandSandboxPlan } from "../../core/command-sandbox-dispatch.js";
import { toolResultBytesKeeper } from "../../core/tool-result-store.js";
import { IMAGE_REFUSAL_KIND, imageRefusalRemoves, MEDIA_ITEMS_REFUSAL_KIND, toolSchemaRefusalReplaces, withoutRefusedToolSchemas } from "../llm/rejected-images.js";
const IMAGE_REFUSAL_RETRIES = 3;
function appendTextDeltaToAssistantMessage(message, contentIndex, delta) {
const content = [...message.content];
const currentContent = content[contentIndex];
content[contentIndex] =
currentContent?.type === "text"
? { ...currentContent, text: currentContent.text + delta }
: { type: "text", text: delta };
return { ...message, content };
}
function resolveAssistantMessageUpdate(event, currentMessage) {
if ("partial" in event && event.partial) {
return event.partial;
}
if (event.type === "text_delta") {
return appendTextDeltaToAssistantMessage(currentMessage, event.contentIndex, event.delta);
}
return currentMessage;
}
export function findUnansweredToolBatch(messages) {
for (let i = messages.length - 1; i >= 0; i--) {
const m = messages[i];
if (m.role !== "assistant")
continue;
return unansweredToolCallsOf(m, messages.slice(i + 1)).length > 0 ? m : undefined;
}
return undefined;
}
function unansweredToolCallsOf(assistantMessage, after) {
const answered = new Set(after.filter((m) => m.role === "toolResult").map((m) => m.toolCallId));
const seen = new Set();
const unanswered = [];
for (const c of assistantMessage.content) {
if (c.type !== "toolCall" || answered.has(c.id) || seen.has(c.id))
continue;
seen.add(c.id);
unanswered.push(c);
}
return unanswered;
}
export async function settleUnansweredToolCalls(context, assistantMessage, config, signal, emit, halt) {
const at = context.messages.lastIndexOf(assistantMessage);
const toolCalls = unansweredToolCallsOf(assistantMessage, at >= 0 ? context.messages.slice(at + 1) : context.messages);
if (toolCalls.length === 0)
return { messages: [], terminate: false, ran: false };
if (halt !== undefined) {
const messages = [];
for (const toolCall of toolCalls) {
if (signal?.aborted)
break;
messages.push((await settleHaltedToolCall(toolCall, halt, emit)).message);
}
return { messages, terminate: true, ran: false };
}
return config.toolExecution === "sequential"
? executeToolCallsSequential(context, assistantMessage, toolCalls, config, signal, emit)
: executeToolCallsPartitioned(context, assistantMessage, toolCalls, config, signal, emit);
}
export async function runAgentLoop(prompts, context, config, emit, signal, streamFn, runtime, trace, seams) {
const state = await createLoopState({ ...context, messages: [...context.messages] }, config, []);
await emit({ type: "agent_start" });
await openTurn(state, emit);
if (seams?.settle !== undefined && (await settleTrailingBatchTurn(state, signal, emit, seams.settle)) === "ended") {
return state.newMessages;
}
const delivered = typeof prompts === "function" ? await prompts() : prompts;
if (delivered.some((m) => m !== seams?.ridingPrompt)) {
state.hasMoreToolCalls = seams?.endsAwaitingUser !== true;
if (state.hasMoreToolCalls && seams?.givenAnswer !== undefined)
state.givenAnswer = seams.givenAnswer;
}
else if (state.newMessages.length === 0) {
state.hasMoreToolCalls = false;
}
state.context.messages.push(...delivered);
state.newMessages.push(...delivered);
for (const prompt of delivered) {
await emit({ type: "message_start", message: prompt });
await emit({ type: "message_end", message: prompt });
}
try {
await runLoop(state, signal, emit, streamFn, runtime, trace);
}
finally {
closeOpenContinuation(state, signal);
}
return state.newMessages;
}
async function settleTrailingBatchTurn(state, signal, emit, settle) {
const tail = findUnansweredToolBatch(state.context.messages);
if (tail === undefined)
return "continue";
const turnController = new AbortController();
const onRunAbort = () => turnController.abort();
if (signal !== undefined) {
if (signal.aborted)
turnController.abort();
else
signal.addEventListener("abort", onRunAbort, { once: true });
}
state.config.noteTurnOpened?.(state.newMessages.length);
state.config.publishTurnInterruptSeat?.(turnController);
let batch;
try {
batch = await settleUnansweredToolCalls(state.context, tail, state.config, turnController.signal, emit, settle.halt);
}
finally {
state.config.publishTurnInterruptSeat?.(undefined);
signal?.removeEventListener("abort", onRunAbort);
}
state.context.messages.push(...batch.messages);
state.newMessages.push(...batch.messages);
let ended = signal?.aborted === true;
let terminalEmitted = false;
if (!ended && turnController.signal.aborted) {
const cut = state.config.noteTurnCutConsumed?.(turnController);
const pendingBeforeSettlement = state.pendingMessages;
const outcome = await settleInterruptedTurn(state, tail, batch.messages, signal, emit, cut);
ended = outcome.kind === "terminal";
if (!ended)
state.pendingMessages.unshift(...pendingBeforeSettlement);
terminalEmitted = ended;
}
else if (!ended) {
state.hasMoreToolCalls = !batch.terminate;
const boundary = { message: tail, toolResults: batch.messages, context: state.context, newMessages: state.newMessages };
adoptNextTurnSnapshot(state, await state.config.prepareNextTurn?.({ ...boundary, continues: state.hasMoreToolCalls }));
ended = (await state.config.shouldStopAfterTurn?.(boundary)) === true || signal?.aborted === true;
if (!ended)
state.pendingMessages.push(...((await state.config.getSteeringMessages?.(state.hasMoreToolCalls)) || []));
}
settle.report({ assistantMessage: tail, settled: batch.messages.length, aborted: ended });
if (ended && !terminalEmitted)
await emit({ type: "agent_end", messages: state.newMessages });
return ended ? "ended" : "continue";
}
function openTurn(state, emit) {
state.turnOpen = true;
return emit({ type: "turn_start" });
}
function endTurn(state, emit, message, toolResults) {
state.turnOpen = false;
return emit({ type: "turn_end", message, toolResults });
}
const PROMPT_TOO_LONG_RE = /context.{0,3}length|context_length|context window (?:limit|exceeded)|reached its context window|prompt is too long|too many tokens|maximum context|exceeds? .{0,30}(?:context|token)|input is too long|\b413\b/i;
function isBlankFailureContent(message) {
return message.content.every((c) => c.type === "text" ? c.text.trim() === "" : c.type === "thinking" ? c.thinking.trim() === "" : false);
}
function defaultDetectPromptTooLong(message) {
if (message.stopReason !== "error")
return false;
if (message.errorKind === "input_too_long")
return true;
if (message.inputTooLongRuledOut === true)
return false;
if (message.errorBodyIncomplete === true)
return false;
return PROMPT_TOO_LONG_RE.test(message.errorMessage ?? "");
}
function createPtlWithholdBuffer(emit, detect) {
const held = [];
let liveStartEmitted = false;
const isCandidate = (message) => message.role === "assistant" &&
message.stopReason === "error" &&
detect(message) &&
isBlankFailureContent(message);
return {
sink: async (event) => {
if (event.type === "message_start" && isCandidate(event.message)) {
held.push(event);
return;
}
if (event.type === "message_end" && !liveStartEmitted && isCandidate(event.message)) {
held.push(event);
return;
}
if (event.type === "message_start")
liveStartEmitted = true;
await emit(event);
},
async flush() {
for (const event of held.splice(0))
await emit(event);
},
discard() {
held.length = 0;
},
};
}
function createMalformedToolUseNudge() {
return {
role: "custom",
customType: "loop:malformed-tool-use-retry",
provenance: "engine-note",
content: "Your previous response indicated tool use but contained no valid tool call. Re-issue the tool call(s) now, with complete and valid JSON arguments — provide exactly one JSON value per parameter, and do not truncate. If an argument is long, split the work into several smaller calls.",
display: false,
timestamp: Date.now(),
};
}
const LOOP_TOOL_MISSES = new WeakSet();
function sameToolMissKey(calls, results, nextTools) {
if (calls.length === 0 || results.length !== calls.length)
return undefined;
if (!results.every((r) => typeof r.details === "object" && r.details !== null && LOOP_TOOL_MISSES.has(r.details)))
return undefined;
const next = toolNameIndex(nextTools);
if (calls.some((c) => next(c.name) !== undefined))
return undefined;
return JSON.stringify([...new Set(calls.map((c) => c.name))].sort());
}
function createThinkingOnlyNudge() {
return {
role: "custom",
customType: "loop:thinking-only-retry",
provenance: "engine-note",
content: "Your previous response had no visible output — it contained only internal reasoning. Respond now with your answer as visible text (or make the required tool calls); do not end the turn with reasoning alone.",
display: false,
timestamp: Date.now(),
};
}
const MIDSTREAM_CONTINUE_BUDGET = 3;
function settleContinuation(state, cutTurnsBefore, turnMessage) {
if (state.midstreamPartialContinues > cutTurnsBefore) {
state.continuationDue = true;
return;
}
if (!state.continuationOpen || turnMessage === undefined || turnMessage.role !== "assistant")
return;
state.continuationOpen = false;
if (turnMessage.stopReason === "aborted")
return;
const answered = turnMessage.stopReason !== "error" && (turnMessage.partialFinalized !== true || turnMessage.stopReason === "toolUse");
const say = continuationText(state);
emitBrainStatus(answered ? { phase: "recovered", detail: say("core/engine.continuation-recovered") } : { phase: "gave_up", detail: say("core/engine.continuation-gave-up") });
}
function openContinuation(state) {
if (!state.continuationDue)
return;
state.continuationDue = false;
state.continuationOpen = true;
emitBrainStatus({ phase: "continuing", detail: continuationText(state)("core/engine.continuation-continuing"), attempt: state.midstreamPartialContinues, maxRetries: MIDSTREAM_CONTINUE_BUDGET });
}
function closeOpenContinuation(state, signal) {
const { continuationOpen: open, continuationDue: due } = state;
state.continuationOpen = false;
state.continuationDue = false;
if (!open || (!due && signal?.aborted === true))
return;
emitBrainStatus({ phase: "gave_up", detail: continuationText(state)("core/engine.continuation-gave-up") });
}
function continuationText(state) {
return engineTextFor(state.context.promptLocale);
}
function createMidstreamPartialContinueNudge() {
return {
role: "custom",
customType: "loop:midstream-partial-continue",
provenance: "engine-note",
content: "Your previous response was cut off mid-stream by a connection failure — the content above may be incomplete. Continue EXACTLY where you left off; do not repeat any content you already produced, do not re-introduce or summarize.",
display: false,
timestamp: Date.now(),
};
}
function createDegenerateRecoveryNudge(locale) {
return {
role: "custom",
customType: "loop:degenerate-output-recovery",
provenance: "engine-note",
content: engineTextFor(locale)("core/engine.degenerate-recovery"),
display: false,
timestamp: Date.now(),
};
}
function createReasoningCutContinueNudge() {
return {
role: "custom",
customType: "loop:truncated-output-continue",
provenance: "engine-note",
content: "Your previous response hit the output-token limit before producing any visible text (the budget went to internal reasoning). " +
"Do NOT restart the long reasoning: state your current best answer or next concrete action directly as visible text (or make the required tool call) now.",
display: false,
timestamp: Date.now(),
};
}
function createContinueNudge() {
return {
role: "custom",
customType: "loop:truncated-output-continue",
provenance: "engine-note",
content: "Your previous response was cut off because it hit the output-token limit. Continue EXACTLY where you left off — do not repeat any content you already produced, do not re-introduce or summarize.",
display: false,
timestamp: Date.now(),
};
}
async function createLoopState(context, config, newMessages) {
return {
context,
config,
newMessages,
turnOpen: false,
pendingMessages: (await config.getSteeringMessages?.(true)) || [],
hasMoreToolCalls: true,
truncatedOutputContinues: 0,
staticReasoningCutRecoveries: context.messages.filter((m) => m.role === "assistant" && m.staticReasoningCut === true).length,
degenerateContinues: 0,
malformedToolUseRetries: 0,
missedToolRetries: 0,
thinkingOnlyRetries: 0,
midstreamPartialContinues: 0,
continuationOpen: false,
continuationDue: false,
};
}
async function runLoop(state, signal, emit, streamFn, runtime, trace) {
while (true) {
if (!state.hasMoreToolCalls && state.pendingMessages.length === 0) {
const followUpMessages = (await state.config.getFollowUpMessages?.()) || [];
if (followUpMessages.length === 0) {
if ((state.config.pendingInjectionCount?.() ?? 0) > 0) {
state.pendingMessages = (await state.config.getSteeringMessages?.(false)) || [];
if (state.pendingMessages.length > 0) {
trace?.({ kind: "continue", reason: "steer_injected" });
}
continue;
}
trace?.({ kind: "terminal", reason: "completed" });
break;
}
const answer = followUpMessages.length === 1 ? state.config.answerOf?.(followUpMessages[0]) : undefined;
if (answer !== undefined)
state.givenAnswer = { text: answer.text, by: answer.by, input: followUpMessages[0] };
else
state.pendingMessages = followUpMessages;
trace?.({ kind: "continue", reason: "follow_up_injected" });
}
const cutTurnsBefore = state.midstreamPartialContinues;
const messagesBefore = state.newMessages.length;
const outcome = await runSingleTurn(state, signal, emit, streamFn, runtime, trace);
settleContinuation(state, cutTurnsBefore, state.newMessages.slice(messagesBefore).findLast((m) => m.role === "assistant"));
if (outcome.kind === "terminal") {
trace?.({ kind: "terminal", reason: outcome.reason });
return;
}
if (outcome.recovered) {
trace?.({ kind: "continue", reason: outcome.recovered });
}
else if (state.pendingMessages.length > 0) {
trace?.({ kind: "continue", reason: "steer_injected" });
}
else if (state.hasMoreToolCalls) {
trace?.({ kind: "continue", reason: "next_turn" });
}
}
await emit({ type: "agent_end", messages: state.newMessages });
}
const MAX_STATIC_REASONING_CUT_RECOVERIES = 2;
function isPersonsInput(message) {
return userRowSourceOf(message)?.origin === "human_input";
}
function clearCountsOnPersonsInput(state, inputs) {
if (!inputs.some(isPersonsInput))
return;
state.malformedToolUseRetries = 0;
state.missedToolRetries = 0;
}
function underMalformedBudget(state, count) {
const malformed = state.config.recovery?.malformedToolUse;
return malformed !== undefined && count < (malformed.maxRetries ?? 2);
}
function countReask(state) {
state.malformedToolUseRetries++;
state.config.recovery?.malformedToolUse?.onReask?.();
}
function malformedRetryLeft(state) {
return underMalformedBudget(state, state.malformedToolUseRetries);
}
function callGrantsOf(state) {
return {
...(state.config.recovery?.truncatedOutput !== undefined && state.staticReasoningCutRecoveries < MAX_STATIC_REASONING_CUT_RECOVERIES ? { staticReasoningCutDowngrade: true } : {}),
...(malformedRetryLeft(state) ? { reissueDroppedCalls: true } : {}),
};
}
async function runSingleTurn(state, signal, emit, streamFn, runtime, trace) {
if (signal?.aborted) {
await emit({ type: "agent_end", messages: state.newMessages });
return { kind: "terminal", reason: "aborted_before_stream" };
}
if (state.config.shouldHaltBeforeTurn?.() === true) {
await emit({ type: "agent_end", messages: state.newMessages });
return { kind: "terminal", reason: "stop_requested" };
}
if (!state.turnOpen) {
await openTurn(state, emit);
if (state.config.shouldHaltBeforeTurn?.() === true) {
await emit({ type: "agent_end", messages: state.newMessages });
return { kind: "terminal", reason: "stop_requested" };
}
}
const turnController = new AbortController();
const onRunAbort = () => turnController.abort();
if (signal !== undefined) {
if (signal.aborted)
turnController.abort();
else
signal.addEventListener("abort", onRunAbort, { once: true });
}
let seatLive = false;
const publishSeat = () => {
seatLive = true;
state.config.publishTurnInterruptSeat?.(turnController);
};
const retractSeat = () => {
if (!seatLive)
return;
seatLive = false;
state.config.publishTurnInterruptSeat?.(undefined);
};
try {
return await runTurnPhases(state, signal, turnController, publishSeat, retractSeat, emit, streamFn, runtime, trace);
}
finally {
retractSeat();
signal?.removeEventListener("abort", onRunAbort);
}
}
async function runTurnPhases(state, signal, turnController, publishSeat, retractSeat, emit, streamFn, runtime, trace) {
const given = state.givenAnswer;
state.givenAnswer = undefined;
const carried = given !== undefined ? state.pendingMessages : [];
state.config.noteTurnOpened?.(state.newMessages.length);
if (given === undefined)
publishSeat();
if (given === undefined && state.config.recheckImmediateInjections) {
state.pendingMessages = await state.config.recheckImmediateInjections(state.pendingMessages);
}
const injected = given === undefined ? state.pendingMessages : given.input !== undefined ? [given.input] : [];
if (injected.length > 0) {
for (const message of injected) {
await emit({ type: "message_start", message });
await emit({ type: "message_end", message });
state.context.messages.push(message);
state.newMessages.push(message);
}
}
clearCountsOnPersonsInput(state, injected);
const retractWhenNothingInFlight = (final) => {
if (final.stopReason === "aborted" || final.stopReason === "error")
return;
if (final.content.every((b) => b.type !== "toolCall"))
retractSeat();
};
const grants = callGrantsOf(state);
const ptl = state.config.recovery?.promptTooLong;
const ptlDetect = ptl?.detect ?? defaultDetectPromptTooLong;
const withholdEnabled = ptl !== undefined && (ptl.withholdErrorEvents ?? true);
let withhold = withholdEnabled ? createPtlWithholdBuffer(emit, ptlDetect) : undefined;
let message;
let cutAtFinalSettle = false;
const announceDispatch = () => openContinuation(state);
let sent;
({ message, cutAtSettle: cutAtFinalSettle, request: sent } =
given !== undefined
? await deliverGivenAnswer(state.context, state.config, given, emit)
: await streamAssistantResponse(state.context, state.config, turnController.signal, withhold?.sink ?? emit, streamFn, runtime, grants, retractWhenNothingInFlight, announceDispatch));
let interruptedInRecovery = false;
let imageRetries = 0;
let mediaItemsLowered = false;
const refusalChangesRequest = () => {
if (message.errorKind === IMAGE_REFUSAL_KIND)
return imageRetries < IMAGE_REFUSAL_RETRIES && imageRefusalRemoves(state.context.messages, message);
if (message.errorKind === MEDIA_ITEMS_REFUSAL_KIND) {
if (state.config.mediaItemLimit?.lower() !== true)
return false;
mediaItemsLowered = true;
return true;
}
return toolSchemaRefusalReplaces(state.context.messages, message, state.context.tools);
};
const resendWithoutRefusedParts = async () => {
while (message.stopReason === "error" &&
!signal?.aborted &&
!turnController.signal.aborted &&
isBlankFailureContent(message) &&
state.context.messages[state.context.messages.length - 1] === message &&
refusalChangesRequest()) {
if (message.errorKind === IMAGE_REFUSAL_KIND)
imageRetries++;
else if (message.refusedTool !== undefined) {
try {
state.config.onToolSchemaRefused?.({ tool: message.refusedTool, refusalAt: message.timestamp });
}
catch {
}
}
trace?.({ kind: "continue", reason: message.errorKind === IMAGE_REFUSAL_KIND ? "image_refusal_retry" : message.errorKind === MEDIA_ITEMS_REFUSAL_KIND ? "media_items_refusal_retry" : "tool_schema_refusal_retry" });
({ message, cutAtSettle: cutAtFinalSettle, request: sent } = await streamAssistantResponse(state.context, state.config, turnController.signal, withhold?.sink ?? emit, streamFn, runtime, grants, retractWhenNothingInFlight, announceDispatch));
}
};
await resendWithoutRefusedParts();
{
if (ptl) {
const detect = ptlDetect;
const maxRetries = ptl.maxRetries ?? 2;
let attempt = 0;
while (message.stopReason === "error" &&
!signal?.aborted &&
detect(message) &&
isBlankFailureContent(message) &&
attempt < maxRetries) {
attempt++;
if (state.context.messages[state.context.messages.length - 1] === message) {
state.context.messages.pop();
}
let replaced;
try {
replaced = await ptl.recover(state.context.messages, attempt, turnController.signal, message);
}
catch {
replaced = undefined;
}
const lowered = replaced === undefined || Array.isArray(replaced) ? undefined : replaced.outputCap;
const refusedRequest = sent;
if (lowered !== undefined && (refusedRequest === undefined || (refusedRequest.maxTokens !== undefined && lowered.to >= refusedRequest.maxTokens)))
replaced = undefined;
if (!replaced) {
state.context.messages.push(message);
interruptedInRecovery = turnController.signal.aborted && !signal?.aborted;
break;
}
withhold?.discard();
withhold = withholdEnabled ? createPtlWithholdBuffer(emit, ptlDetect) : undefined;
if (Array.isArray(replaced)) {
state.context.messages = replaced;
}
else {
adoptRebuiltContext(state.context, replaced);
}
if (turnController.signal.aborted && !signal?.aborted) {
state.context.messages.push(message);
interruptedInRecovery = true;
break;
}
trace?.({ kind: "continue", reason: "reactive_compact_retry" });
const resend = lowered !== undefined && refusedRequest !== undefined ? { request: refusedRequest, maxTokens: lowered.to } : undefined;
const errorStatus = message.apiErrorStatus;
const from = Math.min(lowered?.from ?? Infinity, refusedRequest?.maxTokens ?? Infinity);
let announced = false;
const dispatched = resend === undefined ? announceDispatch : () => {
announceDispatch();
announced = true;
emitBrainStatus({ phase: "retrying", detail: outputCapLoweredDetail(from, resend.maxTokens), attempt, maxRetries, errClass: "output_cap", ...(errorStatus !== undefined ? { errorStatus } : {}) });
};
try {
({ message, cutAtSettle: cutAtFinalSettle, request: sent } = await streamAssistantResponse(state.context, state.config, turnController.signal, withhold?.sink ?? emit, streamFn, runtime, grants, retractWhenNothingInFlight, dispatched, resend));
}
finally {
if (announced) {
const failed = message.stopReason === "error" || message.stopReason === "aborted";
emitBrainStatus(failed ? { phase: "gave_up", detail: "the response ended in an error" } : { phase: "recovered", detail: "recovered after retrying" });
}
}
}
}
}
await resendWithoutRefusedParts();
const unrecoveredPtlFailureUnderInterrupt = ptl !== undefined &&
message.stopReason === "error" &&
ptlDetect(message) &&
isBlankFailureContent(message);
const cutAtPtlLaneExit = turnController.signal.aborted;
const interruptOwnsTurn = ((message.stopReason === "aborted" && cutAtFinalSettle) || (unrecoveredPtlFailureUnderInterrupt && cutAtPtlLaneExit) || interruptedInRecovery) &&
!signal?.aborted;
const cut = interruptOwnsTurn ? state.config.noteTurnCutConsumed?.(turnController) : undefined;
if (interruptOwnsTurn && message.stopReason === "error")
withhold?.discard();
await withhold?.flush();
state.newMessages.push(message);
const toolCalls = message.content.filter((c) => c.type === "toolCall");
const streakBefore = { retries: state.missedToolRetries, missed: state.streakMissedNames };
if (toolCalls.length > 0) {
state.missedToolRetries = 0;
state.streakMissedNames = undefined;
}
if (message.staticReasoningCut === true)
state.staticReasoningCutRecoveries++;
if (interruptOwnsTurn) {
retractSeat();
return await settleInterruptedTurn(state, message, [], signal, emit, cut);
}
{
const degen = state.config.recovery?.degenerateOutput;
if (degen &&
message.stopReason === "error" &&
!signal?.aborted &&
degen.detect(message) &&
message.content.every((b) => b.type !== "toolCall") &&
state.degenerateContinues < (degen.maxContinues ?? 2)) {
retractSeat();
state.degenerateContinues++;
await endTurn(state, emit, message, []);
const drained = (await state.config.getSteeringMessages?.(false)) || [];
state.pendingMessages = drained.length > 0 ? drained : [createDegenerateRecoveryNudge(state.context.promptLocale)];
return { kind: "ran", recovered: "degenerate_output_recovery" };
}
if (message.stopReason !== "error")
state.degenerateContinues = 0;
}
const lostEveryCall = message.stopReason === "error" && toolCalls.length === 0 && message.modelOutputInvalid !== undefined && state.config.recovery?.malformedToolUse !== undefined && signal?.aborted !== true;
const carriedOn = lostEveryCall && (state.config.pendingInjectionCount?.() ?? 1) > 0;
if ((message.stopReason === "error" || message.stopReason === "aborted") && !carriedOn) {
retractSeat();
await endTurn(state, emit, message, []);
await emit({ type: "agent_end", messages: state.newMessages });
return { kind: "terminal", reason: "assistant_error" };
}
const toolResults = [];
state.hasMoreToolCalls = false;
if (toolCalls.length > 0) {
const executedToolBatch = await executeToolCalls(state.context, message, state.config, turnController.signal, emit);
toolResults.push(...executedToolBatch.messages);
state.hasMoreToolCalls = !executedToolBatch.terminate;
if (executedToolBatch.ran)
state.malformedToolUseRetries = 0;
for (const result of toolResults) {
state.context.messages.push(result);
state.newMessages.push(result);
}
}
const cutAtBatchSettle = turnController.signal.aborted;
retractSeat();
if (toolCalls.length > 0 && cutAtBatchSettle && !signal?.aborted) {
const batchCut = state.config.noteTurnCutConsumed?.(turnController);
return await settleInterruptedTurn(state, message, toolResults, signal, emit, batchCut);
}
if (mediaItemsLowered && message.stopReason !== "error" && !signal?.aborted)
await state.config.mediaItemLimit?.answered({ provider: message.provider, model: message.model });
await endTurn(state, emit, message, toolResults);
const nextTurnContext = {
message,
toolResults,
context: state.context,
newMessages: state.newMessages,
};
const nextTurnSnapshot = await state.config.prepareNextTurn?.({ ...nextTurnContext, continues: state.hasMoreToolCalls });
adoptNextTurnSnapshot(state, nextTurnSnapshot);
if (await state.config.shouldStopAfterTurn?.({
message,
toolResults,
context: state.context,
newMessages: state.newMessages,
})) {
await emit({ type: "agent_end", messages: state.newMessages });
return { kind: "terminal", reason: "stop_requested" };
}
state.pendingMessages = [...carried, ...((await state.config.getSteeringMessages?.(state.hasMoreToolCalls)) || [])];
const truncated = state.config.recovery?.truncatedOutput;
if (message.stopReason === "length") {
if (truncated && toolCalls.length === 0 && state.pendingMessages.length === 0) {
if (state.truncatedOutputContinues < (truncated.maxContinues ?? 3)) {
state.truncatedOutputContinues++;
state.midstreamPartialContinues = 0;
const noVisibleText = !message.content.some((c) => c.type === "text" && c.text.trim() !== "");
state.pendingMessages = [...state.pendingMessages, noVisibleText ? createReasoningCutContinueNudge() : createContinueNudge()];
return { kind: "ran", recovered: "max_output_tokens_recovery" };
}
await emit({ type: "agent_end", messages: state.newMessages });
return { kind: "terminal", reason: "truncated_output_exhausted" };
}
}
else {
state.truncatedOutputContinues = 0;
}
if (message.stopReason === "stop" && message.partialFinalized === true) {
if (toolCalls.length === 0 &&
state.pendingMessages.length === 0 &&
state.midstreamPartialContinues < MIDSTREAM_CONTINUE_BUDGET) {
state.midstreamPartialContinues++;
state.pendingMessages = [createMidstreamPartialContinueNudge()];
return { kind: "ran", recovered: "midstream_partial_recovery" };
}
}
else {
state.midstreamPartialContinues = 0;
}
const malformed = state.config.recovery?.malformedToolUse;
const noParseableCall = message.stopReason === "toolUse" && toolCalls.length === 0;
const missedKey = sameToolMissKey(toolCalls, toolResults, state.context.tools);
if (missedKey !== undefined) {
if (missedKey === streakBefore.missed)
state.missedToolRetries = streakBefore.retries;
state.streakMissedNames = missedKey;
}
clearCountsOnPersonsInput(state, state.pendingMessages);
if (carriedOn) {
if (state.pendingMessages.some(isPersonsInput) && malformedRetryLeft(state)) {
countReask(state);
return { kind: "ran" };
}
await emit({ type: "agent_end", messages: state.newMessages });
return { kind: "terminal", reason: "assistant_error" };
}
if (malformed && (noParseableCall || missedKey !== undefined)) {
if (noParseableCall ? malformedRetryLeft(state) : underMalformedBudget(state, state.missedToolRetries)) {
if (noParseableCall) {
countReask(state);
if (state.pendingMessages.length > 0)
return { kind: "ran" };
state.pendingMessages = [createMalformedToolUseNudge()];
return { kind: "ran", recovered: "malformed_tool_use_retry" };
}
state.missedToolRetries++;
}
else {
await emit({ type: "agent_end", messages: state.newMessages });
return { kind: "terminal", reason: "malformed_tool_use_exhausted" };
}
}
const thinkingOnly = state.config.recovery?.thinkingOnly;
if (thinkingOnly &&
message.stopReason === "stop" &&
toolCalls.length === 0 &&
state.pendingMessages.length === 0 &&
state.thinkingOnlyRetries < (thinkingOnly.maxRetries ?? 1) &&
message.content.some((c) => c.type === "thinking") &&
!message.content.some((c) => c.type === "text" && c.text.trim() !== "")) {
state.thinkingOnlyRetries++;
state.pendingMessages = [createThinkingOnlyNudge()];
return { kind: "ran", recovered: "thinking_only_retry" };
}
return { kind: "ran" };
}
function adoptRebuiltContext(context, adopted) {
context.messages = adopted.messages;
if (adopted.systemPrompt === undefined)
return;
context.systemPrompt = adopted.systemPrompt;
if (adopted.systemBlocks !== undefined) {
context.systemBlocks = adopted.systemBlocks;
}
else {
delete context.systemBlocks;
}
}
function adoptNextTurnSnapshot(state, nextTurnSnapshot) {
if (!nextTurnSnapshot)
return;
state.context = nextTurnSnapshot.context ?? state.context;
state.config = Object.assign({}, state.config, {
model: nextTurnSnapshot.model ?? state.config.model,
reasoning: nextTurnSnapshot.thinkingLevel === undefined
? state.config.reasoning
: nextTurnSnapshot.thinkingLevel,
});
}
export const TURN_INTERRUPTED_TOOL_TEXT = "[INTERRUPTED] The user interrupted this turn before this tool call started. It was never executed and " +
"had no side effects. Address the user's interjection first; re-issue the call afterwards if it is still needed.";
export const TURN_ENDED_TOOL_TEXT = "[Tool call did not complete: the turn was ended to deliver the message that follows. Nothing refused it; re-run it if still needed.]";
export const INTERRUPT_TURN_CUT_SETTLEMENT = Object.freeze({ neverStartedText: TURN_INTERRUPTED_TOOL_TEXT, marker: true, movesArmedCommandAside: false });
async function settleInterruptedTurn(state, message, committedResults, signal, emit, cut = INTERRUPT_TURN_CUT_SETTLEMENT) {
const toolResults = [...committedResults];
const turnCalls = message.content.filter((c) => c.type === "toolCall");
const priorResults = state.context.messages.slice(state.context.messages.lastIndexOf(message) + 1).filter((m) => m.role === "toolResult");
const answered = new Set([...priorResults, ...toolResults].map((r) => r.toolCallId));
for (const call of turnCalls) {
if (answered.has(call.id))
continue;
await emit({
type: "tool_execution_start",
toolCallId: call.id,
toolName: call.name,
args: call.arguments,
});
const finalized = {
toolCall: call,
result: {
content: [{ type: "text", text: cut.neverStartedText }],
details: { errorKind: "interrupted_never_started" },
},
isError: true,
};
await emit({
type: "tool_execution_end",
toolCallId: call.id,
toolName: call.name,
result: finalized.result,
isError: true,
notExecuted: true,
});
const toolResultMessage = createToolResultMessage(finalized);
await emitToolResultMessage(toolResultMessage, emit);
state.context.messages.push(toolResultMessage);
state.newMessages.push(toolResultMessage);
toolResults.push(toolResultMessage);
}
if (turnCalls.length === 0 &&
isBlankFailureContent(message) &&
state.context.messages[state.context.messages.length - 1] === message) {
state.context.messages.pop();
if (state.newMessages[state.newMessages.length - 1] === message)
state.newMessages.pop();
}
if (cut.marker) {
const marker = {
role: "user",
content: [
{
type: "text",
text: turnCalls.length > 0 ? INTERRUPTED_BY_USER_FOR_TOOL_USE_MARKER : INTERRUPTED_BY_USER_MARKER,
},
],
provenance: "engine-note",
origin: "interruption_marker",
timestamp: Date.now(),
};
await emit({ type: "message_start", message: marker });
await emit({ type: "message_end", message: marker });
state.context.messages.push(marker);
state.newMessages.push(marker);
}
state.hasMoreToolCalls = false;
await endTurn(state, emit, message, toolResults);
if (signal?.aborted) {
await emit({ type: "agent_end", messages: state.newMessages });
return { kind: "terminal", reason: "aborted_before_stream" };
}
const nextTurnSnapshot = await state.config.prepareNextTurn?.({
message,
toolResults,
context: state.context,
newMessages: state.newMessages,
continues: state.hasMoreToolCalls,
});
adoptNextTurnSnapshot(state, nextTurnSnapshot);
if (await state.config.shouldStopAfterTurn?.({
message,
toolResults,
context: state.context,
newMessages: state.newMessages,
})) {
await emit({ type: "agent_end", messages: state.newMessages });
return { kind: "terminal", reason: "stop_requested" };
}
state.pendingMessages = (await state.config.getSteeringMessages?.(state.hasMoreToolCalls)) || [];
return { kind: "ran" };
}
export function llmRequestContext(context, llmMessages) {
return {
systemPrompt: context.systemPrompt,
...(context.systemBlocks ? { systemBlocks: context.systemBlocks } : {}),
messages: llmMessages,
tools: withoutRefusedToolSchemas(context.tools, context.messages),
...(context.promptLocale !== undefined ? { promptLocale: context.promptLocale } : {}),
};
}
export function loopRequestControls(config) {
const maxTokens = config.maxTokensPerCall?.() ?? config.maxTokens;
return { ...(config.reasoning !== undefined ? { reasoning: config.reasoning } : {}), ...(maxTokens !== undefined ? { maxTokens } : {}), tryUndeclared: true };
}
async function streamAssistantResponse(context, config, signal, emit, streamFn, runtime, grants = {}, onObtained, onDispatch, resend) {
let llmContext;
let trimmedRequestTokens;
if (resend !== undefined) {
({ context: llmContext, trimmedRequestTokens } = resend.request);
}
else {
let messages = context.messages;
if (config.transformContext) {
const transformed = await config.transformContext(messages, signal);
if (Array.isArray(transformed)) {
messages = transformed;
}
else {
if (transformed.adoptedContext !== undefined) {
adoptRebuiltContext(context, transformed.adoptedContext);
}
messages = transformed.messages;
trimmedRequestTokens = transformed.trimmedRequestTokens;
}
}
const llmMessages = await config.convertToLlm(messages);
if (llmMessages[llmMessages.length - 1]?.role === "assistant") {
throw new Error("a model request must not end on the assistant's own row: the context to send is hand-built or its transcript is corrupt");
}
llmContext = llmRequestContext(context, llmMessages);
}
const streamFunction = resolveAgentCoreStreamFn(runtime, streamFn);
const resolvedApiKey = (config.getApiKey ? await config.getApiKey(config.model.provider) : undefined) || config.apiKey;
const perCallMaxTokens = config.maxTokensPerCall?.();
const maxTokens = resend?.maxTokens ?? perCallMaxTokens ?? config.maxTokens;
const perCallStallTimeouts = config.stallTimeoutsPerCall?.();
const perCallFastMode = config.fastModePerCall?.();
if (signal?.aborted) {
const abortedBeforeDispatch = engineAbortedFinal(config.model);
context.messages.push(abortedBeforeDispatch);
await emit({ type: "message_start", message: { ...abortedBeforeDispatch } });
await emit({ type: "message_end", message: abortedBeforeDispatch });
return { message: abortedBeforeDispatch, cutAtSettle: true };
}
onDispatch?.();
const request = { context: llmContext, trimmedRequestTokens, maxTokens: maxTokens ?? config.model.maxTokens };
const { staticReasoningCutDowngrade: _configStatic, reissueDroppedCalls: _configReissue, ...callConfig } = config;
const response = cutByTurnSignal(() => streamFunction(config.model, llmContext, {
...callConfig,
...(perCallMaxTokens !== undefined ? { maxTokens: perCallMaxTokens, maxTokensDynamic: true } : {}),
...(resend !== undefined ? { maxTokens: resend.maxTokens } : {}),
...(perCallStallTimeouts !== undefined ? { stallTimeouts: perCallStallTimeouts } : {}),
...(perCallFastMode !== undefined ? { fastMode: perCallFastMode } : {}),
...(grants.staticReasoningCutDowngrade === true ? { staticReasoningCutDowngrade: true } : {}),
...(grants.reissueDroppedCalls === true ? { reissueDroppedCalls: true } : {}),
tryUndeclared: true,
apiKey: resolvedApiKey,
signal,
}), signal, config.model);
let partialMessage = null;
let addedPartial = false;
let said = "";
for await (const event of response) {
switch (event.type) {
case "start": {
const message = event.partial;
partialMessage = message;
context.messages.push(message);
addedPartial = true;
await emit({ type: "message_start", message: { ...message } });
break;
}
case "text_start":
case "text_delta":
case "text_end":
case "thinking_start":
case "thinking_delta":
case "thinking_end":
case "toolcall_start":
case "toolcall_delta":
case "toolcall_end":
if (partialMessage) {
const message = resolveAssistantMessageUpdate(event, partialMessage);
partialMessage = message;
said += relayedTextOf(event) ?? "";
context.messages[context.messages.length - 1] = message;
await emit({
type: "message_update",
assistantMessageEvent: event,
message: { ...message },
});
}
break;
case "done":
case "error": {
const finalMessage = answeringRequest(withSaidText(receivedFinal(await response.result()), said), trimmedRequestTokens);
const cutAtSettle = signal?.aborted === true;
onObtained?.(finalMessage);
if (addedPartial) {
context.messages[context.messages.length - 1] = finalMessage;
}
else {
context.messages.push(finalMessage);
}
if (!addedPartial) {
await emit({ type: "message_start", message: { ...finalMessage } });
}
await emit({ type: "message_end", message: finalMessage });
return { message: finalMessage, cutAtSettle, request };
}
}
}
const finalMessage = answeringRequest(withSaidText(receivedFinal(await response.result()), said), trimmedRequestTokens);
const cutAtSettle = signal?.aborted === true;
onObtained?.(finalMessage);
if (addedPartial) {
context.messages[context.messages.length - 1] = finalMessage;
}
else {
context.messages.push(finalMessage);
await emit({ type: "message_start", message: { ...finalMessage } });
}
await emit({ type: "message_end", message: finalMessage });
return { message: finalMessage, cutAtSettle, request };
}
async function deliverGivenAnswer(context, config, given, emit) {
const message = {
role: "assistant",
content: [{ type: "text", text: given.text }],
api: config.model.api,
provider: config.model.provider,
model: config.model.id,
stopReason: "stop",
timestamp: Date.now(),
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
answeredBy: given.by,
};
const opened = { ...message, content: [{ type: "text", text: "" }] };
context.messages.push(message);
await emit({ type: "message_start", message: { ...opened, content: [] } });
await emit({ type: "message_update", assistantMessageEvent: { type: "text_start", contentIndex: 0, partial: opened }, message: opened });
await emit({ type: "message_update", assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta: given.text, partial: message }, message: { ...message } });
await emit({ type: "message_update", assistantMessageEvent: { type: "text_end", contentIndex: 0, content: given.text, partial: message }, message: { ...message } });
await emit({ type: "message_end", message });
return { message, cutAtSettle: false };
}
function engineAbortedFinal(model) {
return {
role: "assistant",
content: [{ type: "text", text: "" }],
api: model.api,
provider: model.provider,
model: model.id,
stopReason: "aborted",
timestamp: Date.now(),
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
usageMissing: true,
};
}
function withSaidText(final, said) {
if (final.stopReason !== "aborted" || !isBlankFailureContent(final) || said.trim() === "")
return final;
return { ...final, content: [{ type: "text", text: said }] };
}
const ANSWERED_FINALS = new WeakSet();
function answeringRequest(final, trimmedRequestTokens) {
const stated = Object.prototype.hasOwnProperty.call(final, "trimmedRequestTokens");
const earlier = ANSWERED_FINALS.has(final);
ANSWERED_FINALS.add(final);
if (trimmedRequestTokens === undefined && !stated)
return final;
if (!stated && !earlier && !types.isProxy(final) && Reflect.defineProperty(final, "trimmedRequestTokens", { value: trimmedRequestTokens, enumerable: true, writable: true, configurable: true }))
return final;
return copyWithMember(final, "trimmedRequestTokens", trimmedRequestTokens);
}
function copyWithMember(message, key, value) {
const copy = {};
for (const [k, v] of Object.entries(readOwnMembers(message) ?? {}))
if (k !== key)
Object.defineProperty(copy, k, { value: v, enumerable: true, writable: true, configurable: true });
if (value !== undefined)
copy[key] = value;
return copy;
}
function cutByTurnSignal(open, signal, model) {
const steps = [];
let wake;
let answered = false;
let settled = false;
let resolveFinal;
let rejectFinal;
const final = new Promise((resolve, reject) => ((resolveFinal = resolve), (rejectFinal = reject)));
final.catch(() => undefined);
const deliver = (step) => {
steps.push(step);
wake?.();
};
let iterator;
let letGo = false;
const release = () => {
letGo = true;
const it = iterator;
iterator = undefined;
if (it?.return !== undefined)
void Promise.resolve(it).then((held) => held.return?.()).catch(() => undefined);
};
const settle = (outcome) => {
if (settled)
return;
settled = true;
signal?.removeEventListener("abort", onAbort);
if ("message" in outcome)
resolveFinal(outcome.message);
else
rejectFinal(outcome.error);
};
const onAbort = () => void setImmediate(() => {
if (settled)
return;
const shell = engineAbortedFinal(model);
if (!answered) {
answered = true;
deliver({ event: { type: "error", reason: "aborted", error: shell } });
deliver("end");
}
settle({ message: shell });
release();
});
if (signal?.aborted)
onAbort();
else
signal?.addEventListener("abort", onAbort, { once: true });
void (async () => {
try {
const inner = await open();
const it = (iterator = inner[Symbol.asyncIterator]());
if (letGo)
return release();
for (;;) {
const step = await it.next();
if (letGo)
return;
if (step.done === true)
break;
const event = step.value;
deliver({ event });
if (event.type !== "done" && event.type !== "error")
continue;
answered = true;
settle({ message: await inner.result() });
return release();
}
iterator = undefined;
if (!answered) {
answered = true;
deliver("end");
settle({ message: await inner.result() });
}
}
catch (error) {
if (!answered) {
iterator = undefined;
answered = true;
deliver({ error });
}
else
release();
settle({ error });
}
finally {
deliver("end");
}
})();
return {
async *[Symbol.asyncIterator]() {
let readToEnd = false;
try {
for (;;) {
const step = steps.shift();
if (step === undefined) {
await new Promise((resolve) => (wake = resolve));
wake = undefined;
continue;
}
if (step === "end")
return void (readToEnd = true);
if ("error" in step)
throw step.error;
yield step.event;
}
}
finally {
if (!readToEnd) {
signal?.removeEventListener("abort", onAbort);
release();
}
}
},
result: () => final,
};
}
function callAsRun(call, tools, config) {
if (config.retiredCallName === undefined || findToolByName(tools, call.name) !== undefined)
return call;
const current = config.retiredCallName(call.name);
return current !== undefined && findToolByName(tools, current) !== undefined ? { ...call, name: current } : call;
}
async function executeToolCalls(currentContext, assistantMessage, config, signal, emit) {
const toolCalls = assistantMessage.content.filter((c) => c.type === "toolCall").map((c) => callAsRun(c, currentContext.tools, config));
if (config.toolExecution === "sequential") {
return executeToolCallsSequential(currentContext, assistantMessage, toolCalls, config, signal, emit);
}
return executeToolCallsPartitioned(currentContext, assistantMessage, toolCalls, config, signal, emit);
}
async function executeToolCallsSequential(currentContext, assistantMessage, toolCalls, config, signal, emit) {
const finalizedCalls = [];
const messages = [];
let ran = false;
for (let i = 0; i < toolCalls.length; i++) {
const toolCall = toolCalls[i];
const { finalized, halt, ran: thisRan } = await runToolCall(currentContext, assistantMessage, toolCall, config, signal, emit);
ran ||= thisRan;
const toolResultMessage = createToolResultMessage(finalized);
await emitToolResultMessage(toolResultMessage, emit);
finalizedCalls.push(finalized);
messages.push(toolResultMessage);
if (halt !== undefined) {
for (const remaining of toolCalls.slice(i + 1)) {
if (signal?.aborted)
break;
const settled = await settleHaltedToolCall(remaining, halt, emit);
finalizedCalls.push(settled.finalized);
messages.push(settled.message);
}
return { messages, terminate: true, ran };
}
if (signal?.aborted) {
break;
}
}
return {
messages,
terminate: shouldTerminateToolBatch(finalizedCalls),
ran,
};
}
export async function runToolCall(currentContext, assistantMessage, toolCall, config, signal, emit) {
await emit({ type: "tool_execution_start", toolCallId: toolCall.id, toolName: toolCall.name, args: toolCall.arguments });
const preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);
const finalized = preparation.kind === "immediate"
? { toolCall, result: preparation.result, isError: preparation.isError, ...(preparation.notExecuted === true ? { notExecuted: true } : {}) }
: await executePreparedWithDisclosure(currentContext, assistantMessage, preparation, config, signal, emit);
await emitToolExecutionEnd(finalized, emit);
return { finalized, ran: ranOf(preparation, finalized), ...(preparation.kind === "immediate" && preparation.halt !== undefined ? { halt: preparation.halt } : {}) };
}
function ranOf(preparation, finalized) {
return preparation.kind === "prepared" && finalized.notExecuted !== true;
}
async function settleHaltedToolCall(toolCall, halt, emit) {
await emit({
type: "tool_execution_start",
toolCallId: toolCall.id,
toolName: toolCall.name,
args: toolCall.arguments,
});
const finalized = {
toolCall,
result: {
content: [{ type: "text", text: truncateError(halt.reason) }],
details: halt.details !== undefined ? { ...halt.details } : {},
},
isError: true,
};
await emit({
type: "tool_execution_end",
toolCallId: finalized.toolCall.id,
toolName: finalized.toolCall.name,
result: finalized.result,
isError: true,
notExecuted: true,
});
const message = createToolResultMessage(finalized);
await emitToolResultMessage(message, emit);
return { finalized, message };
}
function isCallConcurrencySafe(tool, args) {
if (!tool)
return false;
if (tool.executionMode === "parallel")
return true;
if (!tool.isConcurrencySafe)
return false;
try {
return tool.isConcurrencySafe(args) === true;
}
catch {
return false;
}
}
export function isBatchSafeToolCall(tool, toolCall) {
if (!tool)
return false;
let args;
try {
args = validateToolArguments(tool, prepareToolCallArguments(tool, toolCall));
}
catch {
return false;
}
return isCallConcurrencySafe(tool, args);
}
function partitionToolCalls(toolCalls, tools) {
const batches = [];
for (const tc of toolCalls) {
const safe = isBatchSafeToolCall(findToolByName(tools, tc.name), tc);
const last = batches[batches.length - 1];
if (safe && last?.safe) {
last.calls.push(tc);
}
else {
batches.push({ safe, calls: [tc] });
}
}
return batches;
}
function resolveToolConcurrency(configured) {
if (configured === undefined)
return 10;
return Number.isFinite(configured) ? Math.max(1, Math.floor(configured)) : 1;
}
async function runCapped(thunks, limit) {
const results = new Array(thunks.length);
const failures = new Array(thunks.length);
let next = 0;
const width = Number.isFinite(limit) ? Math.max(1, Math.min(limit, thunks.length)) : 1;
const workers = Array.from({ length: width }, async () => {
while (next < thunks.length) {
const i = next++;
try {
results[i] = await thunks[i]();
}
catch (error) {
failures[i] = { error };
}
}
});
await Promise.all(workers);
const firstFailure = failures.find((failure) => failure !== undefined);
if (firstFailure !== undefined) {
throw firstFailure.error;
}
return results;
}
async function executeToolCallsPartitioned(currentContext, assistantMessage, toolCalls, config, signal, emit) {
const cap = resolveToolConcurrency(config.maxToolConcurrency);
const allFinalized = [];
const messages = [];
let ran = false;
let halt;
const batches = partitionToolCalls(toolCalls, currentContext.tools);
outer: for (const batch of batches) {
if (signal?.aborted)
break;
const entries = [];
for (const toolCall of batch.calls) {
await emit({
type: "tool_execution_start",
toolCallId: toolCall.id,
toolName: toolCall.name,
args: toolCall.arguments,
});
const preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);
if (preparation.kind === "immediate") {
const finalized = { toolCall, result: preparation.result, isError: preparation.isError, ...(preparation.notExecuted === true ? { notExecuted: true } : {}) };
await emitToolExecutionEnd(finalized, emit);
entries.push({ finalized, toolCall });
if (preparation.halt !== undefined) {
halt = preparation.halt;
break;
}
}
else {
entries.push({ prepared: preparation, toolCall });
}
if (signal?.aborted) {
await settleBatch(entries, true);
break outer;
}
}
await settleBatch(entries, batch.safe);
if (halt !== undefined)
break;
}
if (halt !== undefined && !signal?.aborted) {
const settledIds = new Set(messages.map((m) => m.toolCallId));
for (const toolCall of toolCalls) {
if (settledIds.has(toolCall.id))
continue;
if (signal?.aborted)
break;
const settled = await settleHaltedToolCall(toolCall, halt, emit);
allFinalized.push(settled.finalized);
messages.push(settled.message);
}
return { messages, terminate: true, ran };
}
return { messages, terminate: shouldTerminateToolBatch(allFinalized), ran };
async function settleBatch(entries, concurrent) {
const runOne = (entry) => async () => {
const prepared = entry.prepared;
if (!prepared) {
throw new Error(`tool call ${entry.toolCall.id} reached execution without a preparation`);
}
const finalized = await executePreparedWithDisclosure(currentContext, assistantMessage, prepared, config, signal, emit);
if (ranOf(prepared, finalized))
ran = true;
await emitToolExecutionEnd(finalized, emit);
return finalized;
};
const preparedEntries = entries.filter((e) => e.prepared);
let executedResults;
if (concurrent && preparedEntries.length > 1) {
executedResults = await runCapped(preparedEntries.map((e) => runOne(e)), cap);
}
else {
executedResults = [];
for (const e of preparedEntries) {
executedResults.push(await runOne(e)());
}
}
let idx = 0;
for (const e of entries) {
const finalized = e.finalized ?? executedResults[idx++];
if (!finalized)
continue;
allFinalized.push(finalized);
const toolResultMessage = createToolResultMessage(finalized);
await emitToolResultMessage(toolResultMessage, emit);
messages.push(toolResultMessage);
}
}
}
function receivedFinal(message) {
const words = readMember(message, "errorMessage");
const minted = typeof words === "string" ? remoteWords(words, []) : undefined;
if (minted === words && readsTheSame(message, "errorMessage", words))
return message;
return copyWithMember(message, "errorMessage", minted);
}
function readsTheSame(o, key, value) {
if (types.isProxy(o))
return false;
const d = Reflect.getOwnPropertyDescriptor(o, key);
if (d === undefined)
return value === undefined && !(key in o);
return "value" in d && d.value === value;
}
function shouldTerminateToolBatch(finalizedCalls) {
return (finalizedCalls.length > 0 &&
finalizedCalls.every((finalized) => finalized.result.terminate === true));
}
function prepareToolCallArguments(tool, toolCall) {
if (!tool.prepareArguments) {
return toolCall;
}
const preparedArguments = tool.prepareArguments(toolCall.arguments);
if (preparedArguments === toolCall.arguments) {
return toolCall;
}
return {
...toolCall,
arguments: preparedArguments,
};
}
export function readToolCallArguments(tool, toolCall, args) {
const prepared = prepareToolCallArguments(tool, { ...toolCall, arguments: structuredClone(args) });
try {
return validateToolArguments(tool, prepared);
}
catch {
return args;
}
}
export const ROSTER_LISTING_MAX = 25;
export const ROSTER_SEARCH_HINT_NAME = "ToolSearch";
function formatRosterRecovery(availableTools, text) {
if (availableTools.length === 0)
return "";
const shown = availableTools.slice(0, ROSTER_LISTING_MAX);
const withheld = availableTools.length - shown.length;
const listing = withheld > 0 ? text("core/engine.roster-listing-withheld", { shown: shown.join(", "), withheld: String(withheld) }) : shown.join(", ");
return ` ${availableTools.includes(ROSTER_SEARCH_HINT_NAME) ? text("core/engine.roster-recovery-search", { listing, search: ROSTER_SEARCH_HINT_NAME }) : text("core/engine.roster-recovery", { listing })}`;
}
export const TOOL_VALIDATION_REFUSED_CODE = "tool.validation_refused";
export const TOOL_INPUT_VALIDATION_TIMEOUT_MS = 10_000;
async function runInputValidation(tool, args, toolCallId, signal, onFault) {
if (tool.validateInput === undefined)
return undefined;
try {
const verdict = await boundedValidatorCall(() => tool.validateInput(args, signal !== undefined ? { toolCallId, signal } : { toolCallId }), signal);
if (verdict !== null && typeof verdict === "object" && verdict.ok === false && typeof verdict.message === "string") {
return typeof verdict.code === "string" ? { message: verdict.message, code: verdict.code } : { message: verdict.message };
}
return undefined;
}
catch (error) {
if (signal?.aborted === true)
return undefined;
try {
const ret = onFault?.({ toolName: tool.name, toolCallId, error });
if (ret !== null && typeof ret === "object" && typeof ret.then === "function") {
ret.then(undefined, () => undefined);
}
}
catch {
}
return undefined;
}
}
function boundedValidatorCall(call, signal) {
return new Promise((resolve, reject) => {
let settled = false;
const finish = (fn) => {
if (settled)
return;
settled = true;
clearTimeout(timer);
signal?.removeEventListener("abort", onAbort);
fn();
};
const onAbort = () => finish(() => reject(Object.assign(new Error("tool input pre-validation aborted"), { name: "AbortError" })));
const timer = setTimeout(() => finish(() => reject(new Error(`tool input pre-validation did not answer within ${TOOL_INPUT_VALIDATION_TIMEOUT_MS}ms`))), TOOL_INPUT_VALIDATION_TIMEOUT_MS);
if (signal?.aborted === true) {
onAbort();
return;
}
signal?.addEventListener("abort", onAbort, { once: true });
let out;
try {
out = call();
}
catch (err) {
finish(() => reject(err));
return;
}
Promise.resolve(out).then((v) => finish(() => resolve(v)), (err) => finish(() => reject(err)));
});
}
function sameToolArgs(a, b) {
if (a === b)
return true;
const canon = (v) => JSON.stringify(v, (_k, x) => (x !== null && typeof x === "object" && !Array.isArray(x) ? Object.fromEntries(Object.keys(x).sort().map((k) => [k, x[k]])) : x));
return canon(a) === canon(b);
}
function validationRefusedOutcome(tool, refusal) {
return {
kind: "immediate",
result: createErrorToolResult(refusal.message, {
details: { code: TOOL_VALIDATION_REFUSED_CODE, toolName: tool.name, ...(refusal.code !== undefined ? { reason: refusal.code } : {}) },
}),
isError: true,
};
}
function neverStartedIf(neverStarted, outcome) {
return neverStarted ? { ...outcome, notExecuted: true } : outcome;
}
async function prepareToolCall(currentContext, assistantMessage, toolCall, config, signal) {
const tool = findToolByName(currentContext.tools, toolCall.name);
if (!tool) {
const tools = currentContext.tools ?? [];
const availableTools = tools.map((t) => t.name);
const text = engineTextFor(currentContext.promptLocale);
const reason = config.absentToolReason?.(toolCall.name, text);
const miss = reason !== undefined ? { kind: "expected-absent", detail: reason } : judgeToolNameMiss(toolCall.name, mountedToolNames(tools));
const missSentence = reason !== undefined
? text("core/engine.tool-not-found-unmounted", { name: toolCall.name, detail: reason })
: miss.kind === "expected-absent"
? text("core/engine.tool-not-found-retired", { name: toolCall.name, detail: miss.detail })
: text("core/engine.tool-not-found", { name: toolCall.name });
const result = createErrorToolResult(`${missSentence}${formatRosterRecovery(availableTools, text)}`, {
details: {
code: "tool.not_found",
toolName: toolCall.name,
availableTools,
absence: miss.kind,
...(miss.kind === "expected-absent" ? { detail: miss.detail, ...(miss.successor !== undefined ? { successor: miss.successor } : {}) } : {}),
},
});
if (typeof result.details === "object" && result.details !== null)
LOOP_TOOL_MISSES.add(result.details);
return { kind: "immediate", result, isError: true };
}
let gateLetGo = false;
try {
const preparedToolCall = prepareToolCallArguments(tool, toolCall);
let finalArgs = validateToolArguments(tool, preparedToolCall);
const refusal = await runInputValidation(tool, finalArgs, toolCall.id, signal, config.onToolInputValidationFault);
if (refusal !== undefined)
return validationRefusedOutcome(tool, refusal);
const validatedArgs = finalArgs;
let sandboxPlan;
if (config.beforeToolCall) {
const beforeResult = await config.beforeToolCall({
assistantMessage,
toolCall,
args: finalArgs,
context: currentContext,
readArguments: (args) => readToolCallArguments(tool, toolCall, args),
}, signal);
if (signal?.aborted) {
const held = config.heldCallResult?.(toolCall.id);
if (held !== undefined)
return { kind: "immediate", result: held, isError: false, notExecuted: true };
return {
kind: "immediate",
result: createErrorToolResult("Operation aborted", { details: safeAbortDetails(config.abortResultDetails) }),
isError: true,
};
}
if (beforeResult?.block) {
const blocked = createErrorToolResult(beforeResult.reason || "Tool execution was blocked", beforeResult.details !== undefined ? { details: beforeResult.details } : undefined);
if (beforeResult.haltRemaining !== undefined) {
return { kind: "immediate", result: blocked, isError: true, halt: beforeResult.haltRemaining };
}
return { kind: "immediate", result: blocked, isError: true };
}
gateLetGo = true;
sandboxPlan = beforeResult?.sandboxPlan;
const rewritten = beforeResult?.updatedInput;
if (rewritten !== undefined) {
const judged = structuredClone(rewritten);
finalArgs = validateToolArguments(tool, prepareToolCallArguments(tool, { ...preparedToolCall, arguments: structuredClone(judged) }));
if (!sameToolArgs(finalArgs, judged)) {
throw new Error(`the arguments cleared for "${tool.name}" are not the ones it would run: its reading of them (argument preparation, schema coercions) changes them, and that form was never judged — not executed`);
}
if (!sameToolArgs(validatedArgs, finalArgs)) {
const rewrittenRefusal = await runInputValidation(tool, finalArgs, toolCall.id, signal, config.onToolInputValidationFault);
if (rewrittenRefusal !== undefined)
return neverStartedIf(true, validationRefusedOutcome(tool, rewrittenRefusal));
}
}
}
if (signal?.aborted) {
return neverStartedIf(gateLetGo, {
kind: "immediate",
result: createErrorToolResult("Operation aborted"),
isError: true,
});
}
return {
kind: "prepared",
toolCall,
tool,
args: finalArgs,
...(sandboxPlan !== undefined ? { sandboxPlan } : {}),
};
}
catch (error) {
return neverStartedIf(gateLetGo, {
kind: "immediate",
result: thrownErrorToolResult(error),
isError: true,
});
}
}
async function executePreparedToolCall(prepared, signal, emit, executeTool, abortResultDetails) {
const updateEvents = [];
let acceptingUpdates = true;
if (signal?.aborted) {
return { result: createErrorToolResult("operation aborted before execution", { details: safeAbortDetails(abortResultDetails) }), isError: true, notExecuted: true };
}
const work = (async () => {
let outcome;
let bodyStarted = false, bodyClosed = false;
try {
const body = () => runWithCommandSandboxPlan(prepared.sandboxPlan, () => prepared.tool.execute(prepared.toolCall.id, prepared.args, signal, (partialResult) => {
if (!acceptingUpdates) {
return;
}
let delivery;
try {
delivery = Promise.resolve(emit({
type: "tool_execution_update",
toolCallId: prepared.toolCall.id,
toolName: prepared.toolCall.name,
args: prepared.toolCall.arguments,
partialResult,
}));
}
catch (error) {
delivery = Promise.reject(error);
}
void delivery.catch(() => undefined);
updateEvents.push(delivery);
}));
const startBody = () => (bodyClosed ? Promise.resolve(Object.assign(createErrorToolResult("operation not executed: the execution station had already settled this call without running its body"), { isError: true })) : ((bodyStarted = true), body()));
const result = executeTool !== undefined ? await executeTool({ toolCall: prepared.toolCall, tool: prepared.tool, args: prepared.args }, startBody, signal) : await body();
bodyClosed = !bodyStarted;
outcome = neverStartedIf(executeTool !== undefined && !bodyStarted, { result, isError: result.isError === true });
}
catch (error) {
bodyClosed = !bodyStarted;
outcome = neverStartedIf(executeTool !== undefined && !bodyStarted, {
result: thrownErrorToolResult(error),
isError: true,
});
}
acceptingUpdates = false;
const deliveryFailure = await settleUpdateDeliveries(updateEvents);
if (!deliveryFailure)
return outcome;
const reason = deliveryFailure.reason;
const details = annotateDeliveryFailure(outcome.result, {
message: egressThrownText("same-principal", reason),
});
return details === UNANNOTATED ? outcome : { ...outcome, result: { ...outcome.result, details } };
})();
return work;
}
const TOOL_PROGRESS_DELIVERY_FAILED = "toolProgressDeliveryFailed";
const UNANNOTATED = Symbol("unannotated");
function annotateDeliveryFailure(result, mark) {
try {
const raw = result.details;
const prior = raw === undefined ? {} : raw;
const proto = prior === null || typeof prior !== "object" ? undefined : Object.getPrototypeOf(prior);
if (proto !== Object.prototype && proto !== null)
return UNANNOTATED;
const details = { ...prior };
if (TOOL_PROGRESS_DELIVERY_FAILED in details)
return UNANNOTATED;
details[TOOL_PROGRESS_DELIVERY_FAILED] = mark;
return details;
}
catch {
return UNANNOTATED;
}
}
function readDeliveryFailureMark(details) {
try {
if (details === null || typeof details !== "object")
return undefined;
const mark = details[TOOL_PROGRESS_DELIVERY_FAILED];
return mark;
}
catch {
return undefined;
}
}
async function settleUpdateDeliveries(updateEvents) {
if (updateEvents.length === 0)
return undefined;
let reportFailure;
const firstFailure = new Promise((resolve) => {
reportFailure = resolve;
});
for (const delivery of updateEvents) {
void delivery.catch((reason) => reportFailure({ reason }));
}
const allSettled = Promise.allSettled(updateEvents).then((entries) => {
for (const entry of entries) {
if (entry.status === "rejected")
return { reason: entry.reason };
}
return undefined;
});
const failure = await Promise.race([firstFailure, allSettled]);
if (failure && isAbortSemanticsError(failure.reason))
throw failure.reason;
return failure;
}
async function executePreparedWithDisclosure(currentContext, assistantMessage, prepared, config, signal, emit) {
let executed;
try {
executed = await executePreparedToolCall(prepared, signal, emit, config.executeTool, config.abortResultDetails);
}
catch (error) {
if (isAbortSemanticsError(error))
throw error;
executed = {
result: thrownErrorToolResult(error, (words) => `[tool execution harness failed: ${words}]`),
isError: true,
};
}
return finalizeExecutedToolCall(currentContext, assistantMessage, prepared, executed, config, signal);
}
function finalizeExecutedToolCall(currentContext, assistantMessage, prepared, executed, config, signal) {
return finalizeToolOutcome(prepared.toolCall, executed, config.afterToolCall === undefined
? undefined
: (result, isError) => config.afterToolCall({ assistantMessage, toolCall: prepared.toolCall, args: prepared.args, result, isError, context: currentContext }, signal), config);
}
export async function finalizeToolOutcome(toolCall, executed, after, media) {
let result = executed.result;
let isError = executed.isError;
const deliveryMark = readDeliveryFailureMark(executed.result.details);
if (after) {
try {
const afterResult = await after(result, isError);
if (afterResult) {
result = {
content: afterResult.content ?? result.content,
details: afterResult.details ?? result.details,
terminate: afterResult.terminate ?? result.terminate,
};
isError = afterResult.isError ?? isError;
}
}
catch (error) {
const note = truncateError(`[post-tool processing failed (the tool already executed): ${egressThrownText("same-principal", error)}]`);
result = { ...result, content: [...result.content, { type: "text", text: note }] };
}
if (deliveryMark !== undefined && readDeliveryFailureMark(result.details) === undefined) {
const details = annotateDeliveryFailure(result, deliveryMark);
if (details !== UNANNOTATED)
result = { ...result, details };
}
}
const mediaBlocks = toolResultMediaBlocks(result.content);
if (mediaBlocks !== undefined) {
const processor = await resolveImageProcessor(media?.imageProcessor);
const admitted = await admitToolResultMediaBlocks(mediaBlocks, toolCall.name, processor, toolResultBytesKeeper(media?.toolResultBytes, toolCall.id));
result = { ...result, content: admitted.content };
const unprocessed = firstUnprocessedOverTarget(admitted.content, processor);
if (admitted.refused.length > 0) {
try {
media?.onToolMediaRefused?.({ toolName: toolCall.name, toolCallId: toolCall.id, refused: admitted.refused });
}
catch {
}
}
if (unprocessed !== undefined) {
try {
media?.onImageUnprocessed?.(unprocessed);
}
catch {
}
}
}
return { toolCall, result, isError, ...(executed.notExecuted === true ? { notExecuted: true } : {}) };
}
function safeAbortDetails(fn) {
try {
return fn?.();
}
catch {
return undefined;
}
}
function isAbortSemanticsError(error) {
let cursor = error;
for (let depth = 0; depth < 8 && isErrorLike(cursor); depth++) {
if (readMember(cursor, "name") === "AbortError")
return true;
const next = readMember(cursor, "cause");
if (next === cursor)
break;
cursor = next;
}
return false;
}
function createErrorToolResult(message, source) {
const details = thrownMarksOf(source) ?? {};
return {
content: [{ type: "text", text: truncateError(message) }],
details,
};
}
function thrownErrorToolResult(error, frame = (words) => words) {
return createErrorToolResult(frame(egressThrownText("same-principal", error)), { details: egressValue("same-principal", thrownMarksOf(error)) });
}
async function emitToolExecutionEnd(finalized, emit) {
await emit({
type: "tool_execution_end",
toolCallId: finalized.toolCall.id,
toolName: finalized.toolCall.name,
result: finalized.result,
isError: finalized.isError,
...(finalized.notExecuted === true ? { notExecuted: true } : {}),
});
}
function createToolResultMessage(finalized) {
return {
role: "toolResult",
toolCallId: finalized.toolCall.id,
toolName: finalized.toolCall.name,
content: finalized.result.content,
details: finalized.result.details,
isError: finalized.isError,
timestamp: Date.now(),
};
}
async function emitToolResultMessage(toolResultMessage, emit) {
await emit({ type: "message_start", message: toolResultMessage });
await emit({ type: "message_end", message: toolResultMessage });
}