@sema-agent/core
Version:
Stateless, task-oriented AI agent core
806 lines (805 loc) • 47.3 kB
JavaScript
import {} from "../internal/llm.js";
import { repairTextToolCalls } from "./tool-call-repair.js";
import { DEGENERATE_MESSAGE, trimDegenerateTail } from "./repetition.js";
import { NO_WORD, STREAM_TORN_WARNING, carriesNoContent, createCallLoss, createRepetitionPoll, createStreamEndLedger, droppedCallsEnding, droppedFramesNote, echoFoldedWord, endingWordOf, memberReader, modelOutputInvalidOf, noteResponseModel, nameMissingCause, parseStreamedToolArgs, placeTurnNotes, requestInputTokensOf, truncationCauseClause, withheldCallsClause } from "./stream-shared.js";
import { admitToolCallId, providerResultIds, providerToolCallId, responseToolCallIds } from "./tool-call-id.js";
import { emitBrainTelemetry } from "./status-sink.js";
import { DOCUMENT_OMITTED, errorResultMediaNote, IMAGE_OMITTED_NO_VISION, imageWithholdOf, imagesOmittedNoVisionNote, reportImagesWithheld, sendableImages, toolImagesPrefix } from "./media-degrade.js";
import { capabilityHeld, requestWithheld } from "./model-capability.js";
import { OPENAI_RESERVED, OUTPUT_CAP_KEYS, applyExtraBody, declaredRequestValues, effectiveOutputCap, headerBagOnce, lockHeader, mergeHeaders } from "./request-params.js";
import { BrainError, providerErrorWord } from "./errors.js";
import { PROMPT_CACHE_KEY_WIRE, promptCacheKeyDefect, sendsPromptCacheKey } from "./prompt-cache-key.js";
import { NAMES_AS_WRITTEN, inBandProviderError, resolveProviderDialect, endpointToolNames } from "./provider-dialect.js";
import { admitRouteRequest, applyRouteCredentialHeaders, assertServableRequestRoot, brainConfigSnapshot, createBrainRouteJudge, joinRequestUrl, resolveRequestRootOf, resolveRouteCredential } from "./route-adjudicator.js";
import { requestRouteOf } from "./request-route.js";
import { reasoningTokensOf } from "./usage-reasoning.js";
import { usageOfStatement } from "./usage-reading.js";
import { applyReasoningToRequest } from "./reasoning-request.js";
import { applyFastModeToRequest, requestSpeedOf } from "./fast-mode.js";
import { requestReasoning } from "./reasoning-stamp.js";
import { runStreamingBrain } from "./stream-engine.js";
import { refuseRetiredTimeoutKnobs } from "./timeout.js";
import { resolveFetch } from "./transport.js";
import { projectToolSchema } from "./tool-schema-projection.js";
const OPENAI_KEY_HEADER = "authorization";
const OPENAI_CACHE_KEY_RESERVED = new Set([...OPENAI_RESERVED, PROMPT_CACHE_KEY_WIRE]);
function closeToolCallAccum(acc, responseIds, closed) {
if (acc.closedTc)
return acc.closedTc;
if (!acc.name)
return undefined;
const args = parseStreamedToolArgs(acc.args, closed);
if (args === undefined)
return undefined;
const { engineId, wireId } = admitToolCallId(acc.id, "call_", responseIds);
acc.closedTc = { type: "toolCall", id: engineId, ...(wireId !== engineId ? { wireId } : {}), name: acc.name, arguments: args };
return acc.closedTc;
}
function textOf(content) {
if (typeof content === "string") {
return content;
}
return content
.filter((c) => c.type === "text" && typeof c.text === "string")
.map((c) => c.text)
.join("");
}
const NO_CONTENT = "(no content)";
function toUserContent(content, withhold) {
if (typeof content === "string") {
return content;
}
const hasImage = content.some((c) => c.type === "image");
const nDocs = content.filter((c) => c.type === "document").length;
if (nDocs > 0)
emitBrainTelemetry({ kind: "document_placeholder", count: nDocs });
if (!hasImage) {
const base = textOf(content);
if (nDocs === 0)
return base;
return base ? `${base}\n${DOCUMENT_OMITTED}` : DOCUMENT_OMITTED;
}
if (withhold !== undefined) {
const n = content.filter((c) => c.type === "image").length;
reportImagesWithheld(withhold, n);
const base = textOf(content);
const note = imagesOmittedNoVisionNote(n);
const withNote = base ? `${base}\n${note}` : note;
return nDocs > 0 ? `${withNote}\n${DOCUMENT_OMITTED}` : withNote;
}
const parts = [];
for (const c of content) {
if (c.type === "text" && typeof c.text === "string" && c.text.length > 0) {
parts.push({ type: "text", text: c.text });
}
else if (c.type === "image" && c.data && c.mimeType) {
parts.push({
type: "image_url",
image_url: { url: `data:${c.mimeType};base64,${c.data}` },
});
}
else if (c.type === "document") {
parts.push({ type: "text", text: DOCUMENT_OMITTED });
}
}
return parts;
}
function thinkingCompat(model) {
return (model.compat ?? {});
}
function toOpenAIMessages(ctx, replayThinking = true, model, toolNames) {
const imageWithhold = imageWithholdOf(model);
const supportsVision = imageWithhold === undefined;
const out = [];
const needsEmptyReasoningField = model !== undefined && capabilityHeld(model, "reasoning") && thinkingCompat(model).requiresReasoningContentOnAssistantMessages === true;
if (ctx.systemPrompt) {
out.push({ role: "system", content: ctx.systemPrompt });
}
let pendingImages = [];
const flushImages = () => {
if (pendingImages.length === 0)
return;
const ids = [...new Set(pendingImages.map((i) => i.toolCallId))].join(", ");
out.push({
role: "user",
content: [
{ type: "text", text: toolImagesPrefix(pendingImages.length, ids, ctx.promptLocale) },
...pendingImages.map((i) => ({ type: "image_url", image_url: { url: `data:${i.mimeType};base64,${i.data}` } })),
],
});
pendingImages = [];
};
const resultWireId = providerResultIds(ctx.messages);
for (const m of ctx.messages) {
if (m.role !== "toolResult")
flushImages();
if (m.role === "user") {
const uc = toUserContent(m.content, imageWithhold);
const empty = uc === "" || (Array.isArray(uc) && uc.length === 0);
out.push({ role: "user", content: empty ? NO_CONTENT : uc });
}
else if (m.role === "assistant") {
const text = m.content
.filter((c) => c.type === "text")
.map((c) => c.text)
.join("");
const toolCalls = m.content.filter((c) => c.type === "toolCall");
const msg = { role: "assistant", content: text };
const reasoning = m.content
.filter((c) => c.type === "thinking")
.map((c) => c.thinking)
.join("");
if (replayThinking && reasoning && toolCalls.length > 0) {
msg.reasoning_content = reasoning;
}
else if (needsEmptyReasoningField) {
msg.reasoning_content = "";
}
if (toolCalls.length > 0) {
msg.tool_calls = toolCalls.map((tc) => ({
id: providerToolCallId(tc),
type: "function",
function: { name: toolNames.sent(tc.name), arguments: JSON.stringify(tc.arguments ?? {}) },
}));
}
out.push(msg);
}
else if (m.role === "toolResult") {
const mediaImages = sendableImages(Array.isArray(m.content) ? m.content : []);
const rawImages = m.isError ? [] : mediaImages;
const images = supportsVision ? rawImages : [];
if (imageWithhold !== undefined)
reportImagesWithheld(imageWithhold, rawImages.length);
const nDocs = Array.isArray(m.content) ? m.content.filter((c) => c.type === "document").length : 0;
if (nDocs > 0)
emitBrainTelemetry({ kind: "document_placeholder", count: nDocs });
const baseText0 = textOf(m.content);
const baseText = nDocs > 0 ? (baseText0 ? `${baseText0}\n${DOCUMENT_OMITTED}` : DOCUMENT_OMITTED) : baseText0;
const text = !supportsVision && rawImages.length > 0 ? (baseText ? `${baseText}\n${IMAGE_OMITTED_NO_VISION}` : IMAGE_OMITTED_NO_VISION) : baseText;
const errorNote = m.isError ? errorResultMediaNote({ images: mediaImages.length, documents: 0 }) : undefined;
const finalText = errorNote === undefined ? text : text ? `${text}\n${errorNote}` : errorNote;
out.push({
role: "tool",
tool_call_id: resultWireId(m.toolCallId),
content: toolResultText(finalText, images.length > 0, m.content),
});
for (const img of images)
pendingImages.push({ toolCallId: resultWireId(m.toolCallId), data: img.data, mimeType: img.mimeType });
}
}
flushImages();
return out;
}
function toolResultText(text, hasCarriedImages, original) {
if (text !== "")
return text;
if (hasCarriedImages)
return "(image attached below)";
return Array.isArray(original) && original.length > 0 ? "(non-text tool result omitted)" : "";
}
function toOpenAITools(ctx, toolNames) {
if (!ctx.tools || ctx.tools.length === 0) {
return undefined;
}
return ctx.tools.map((t) => ({
type: "function",
function: { name: toolNames.sent(t.name), description: t.description, parameters: projectToolSchema(t.parameters) },
}));
}
const FINISH_REASON_READINGS = Object.freeze({
stop: { kind: "finished" },
length: { kind: "finished" },
tool_calls: { kind: "finished" },
function_call: { kind: "finished" },
content_filter: { kind: "refusal" },
sensitive: { kind: "refusal" },
model_context_window_exceeded: { kind: "input_too_long" },
insufficient_system_resource: { kind: "provider_cut", code: "server" },
aborted: { kind: "provider_cut", code: "server" },
network_error: { kind: "provider_cut", code: "network" },
});
function offeredOf(delta) {
const calls = delta.tool_calls;
if (calls !== undefined && calls !== null && !(Array.isArray(calls) && calls.length === 0))
return "tool_calls";
if (delta.refusal)
return "refusal";
if (delta.content)
return "text";
if (delta.reasoning || delta.reasoning_content)
return "reasoning";
return undefined;
}
const present = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
function readUsage(seat, u) {
const details = seat.object(u.prompt_tokens_details);
const nested = seat.claimIn(u.completion_tokens_details, "reasoning_tokens");
return present({
prompt_tokens: seat.count(u.prompt_tokens),
completion_tokens: seat.count(u.completion_tokens),
total_tokens: seat.count(u.total_tokens),
prompt_tokens_details: details === undefined ? undefined : present({ cached_tokens: seat.count(details.cached_tokens) }),
prompt_cache_hit_tokens: seat.count(u.prompt_cache_hit_tokens),
completion_tokens_details: nested === undefined ? undefined : { reasoning_tokens: nested },
reasoning_tokens: seat.claim(u.reasoning_tokens),
});
}
function readChunk(raw) {
const frame = memberReader();
const callStream = memberReader();
const usageSeat = memberReader();
const chunk = callStream.object(raw);
if (chunk === undefined)
return { model: undefined, usageUnreadable: false, callsUnreadable: callStream.outOfShape, outOfShape: callStream.outOfShape };
const error = frame.object(chunk.error);
const usageObject = usageSeat.object(chunk.usage);
const choices = callStream.array(chunk.choices);
const first = choices === undefined ? undefined : callStream.object(choices[0]);
let choice;
if (first !== undefined) {
const delta = callStream.object(first.delta);
const calls = callStream.array(delta?.tool_calls)?.flatMap((element) => {
const tc = callStream.object(element);
if (tc === undefined)
return [];
const fn = callStream.object(tc.function);
return [present({ index: callStream.count(tc.index), id: callStream.word(tc.id), name: callStream.word(fn?.name), arguments: callStream.word(fn?.arguments) })];
});
choice = present({
finish: endingWordOf(first.finish_reason),
offered: delta === undefined ? undefined : offeredOf(delta),
reasoning: frame.word(delta?.reasoning) || frame.word(delta?.reasoning_content) || undefined,
content: frame.word(delta?.content),
refusal: frame.word(delta?.refusal),
calls,
});
}
return present({
error,
model: chunk.model,
usage: usageObject === undefined ? undefined : readUsage(usageSeat, usageObject),
usageUnreadable: usageSeat.outOfShape,
choice,
callsUnreadable: callStream.outOfShape,
outOfShape: frame.outOfShape || callStream.outOfShape,
});
}
function readFinishReason(reason) {
if (reason == null)
return undefined;
return Object.hasOwn(FINISH_REASON_READINGS, reason) ? FINISH_REASON_READINGS[reason] : { kind: "unrecognized" };
}
function mapFinishReason(reason, hadToolCalls) {
if (hadToolCalls) {
return "toolUse";
}
if (reason === "length") {
return "length";
}
return "stop";
}
function reasoningOf(raw) {
return reasoningTokensOf(raw?.completion_tokens ?? 0, raw?.completion_tokens_details?.reasoning_tokens, raw?.reasoning_tokens);
}
function reportedUsageOf(model, raw) {
return usageOfStatement(model, "input-includes-cached", {
input: raw?.prompt_tokens,
output: raw?.completion_tokens,
cacheRead: raw?.prompt_tokens_details?.cached_tokens ?? raw?.prompt_cache_hit_tokens,
total: raw?.total_tokens,
}, reasoningOf(raw));
}
export function inferMaxTokensField(modelId) {
const id = modelId.toLowerCase();
if (/^gpt-5/.test(id) || /^chatgpt-4o/.test(id) || /^o[134](?:$|[-.])/.test(id))
return "max_completion_tokens";
return "max_tokens";
}
export function createOpenAIBrain(given = {}) {
const config = brainConfigSnapshot(given, "createOpenAIBrain config");
assertServableRequestRoot(config.baseUrl, "config.baseUrl");
refuseRetiredTimeoutKnobs(config, "construction", "createOpenAIBrain config");
const doFetch = resolveFetch(config);
const stream = (model, context, options) => {
let sentMaxTokens;
let sentMaxTokensLane = "unset";
let builtMaxTokens;
let builtMaxTokensLane = "unset";
let sentToolNames = NAMES_AS_WRITTEN;
return runStreamingBrain({
model,
doFetch,
signal: options?.signal,
config,
httpLabel: "gateway",
maxRetries: options?.maxRetries,
stallTimeouts: options?.stallTimeouts,
buildRequest: (overrides) => {
const routed = { id: model.id, baseUrl: model.baseUrl };
const { root, origin: rootOrigin } = resolveRequestRootOf(routed.baseUrl, config.baseUrl);
if (!root) {
throw new Error("createOpenAIBrain: no baseUrl configured (set config.baseUrl or model.baseUrl)");
}
const url = joinRequestUrl(root, "/chat/completions");
const speed = requestSpeedOf({ model, call: options?.fastMode, standardSpeed: overrides?.standardSpeed === true });
const withheld = requestWithheld(model, url, speed, overrides?.withhold, options?.tryUndeclared);
const builtToolNames = endpointToolNames(resolveProviderDialect(url, model.api), model.api, (context.tools ?? []).map((t) => t.name));
const modelHeaders = headerBagOnce(model.headers);
const optionsHeaders = headerBagOnce(options?.headers);
const routeCredential = resolveRouteCredential({
optionsApiKey: options?.apiKey,
optionsHeaders,
optionsCredentialOrigin: options?.credentialOrigin,
optionsCredentialOriginUnsettled: options?.credentialOriginUnsettled === true,
modelHeaders,
configApiKey: config.apiKey,
configHeaders: config.headers,
keyHeader: OPENAI_KEY_HEADER,
});
const routeAdmission = admitRouteRequest(routed, routeCredential, { baseUrl: config.baseUrl, requireCredential: config.requireCredential, ...(options?.plaintextOrigins !== undefined ? { plaintextOrigins: options.plaintextOrigins } : {}) });
const apiKey = routeCredential.apiKey;
const cacheKeyDefect = promptCacheKeyDefect(model);
if (cacheKeyDefect !== undefined)
throw new BrainError("invalid_request", `config.invalid_argument: ${cacheKeyDefect} (model "${model.id}")`);
const sendsKey = sendsPromptCacheKey(model);
const sessionKey = sendsKey && typeof options?.promptCacheKey === "string" && options.promptCacheKey !== "" ? options.promptCacheKey : undefined;
const body = {
model: model.id,
...(sessionKey !== undefined ? { [PROMPT_CACHE_KEY_WIRE]: sessionKey } : {}),
messages: toOpenAIMessages(context, config.replayThinking, model, builtToolNames),
stream: true,
stream_options: { include_usage: true },
};
const tools = toOpenAITools(context, builtToolNames);
if (tools)
body.tools = tools;
if (options?.temperature !== undefined)
body.temperature = options.temperature;
const requestedMaxTokens = overrides?.maxOutputTokens ?? options?.maxTokens ?? model.maxTokens;
const declared = (model.compat ?? {}).maxTokensField;
const mtField = declared ?? inferMaxTokensField(model.id);
if (requestedMaxTokens !== undefined) {
const capped = Math.max(1, requestedMaxTokens);
body[mtField] = capped;
builtMaxTokens = capped;
builtMaxTokensLane =
overrides?.maxOutputTokens !== undefined ? "engine" : options?.maxTokens !== undefined ? "options" : "model";
}
else {
builtMaxTokens = undefined;
builtMaxTokensLane = "unset";
}
if (options?.stop)
body.stop = options.stop;
const { body: reasoningBody, carried } = applyReasoningToRequest({ api: "openai-completions", model, level: options?.reasoning, body, withheld });
const headers = mergeHeaders(modelHeaders, config.headers, optionsHeaders);
applyRouteCredentialHeaders(headers, routeCredential);
const declaredValues = declaredRequestValues([modelHeaders, config.headers, optionsHeaders, headers], [], apiKey);
lockHeader(headers, "content-type", "application/json");
if (apiKey !== undefined)
lockHeader(headers, OPENAI_KEY_HEADER, `Bearer ${apiKey}`);
const fastBody = applyFastModeToRequest({ model, call: options?.fastMode, speed, body: reasoningBody }).body;
const { body: wire, dropped: extraBodyDropped } = sendsKey ? applyExtraBody(fastBody, model, OPENAI_CACHE_KEY_RESERVED) : applyExtraBody(fastBody, model, OPENAI_RESERVED);
return {
url,
headers,
declared: declaredValues,
body: JSON.stringify(wire),
...((context.tools?.length ?? 0) > 0 ? { toolNames: context.tools.map((t) => t.name) } : {}),
extraBodyDropped,
route: requestRouteOf(routeCredential, rootOrigin),
outputCapTokens: effectiveOutputCap(wire, OUTPUT_CAP_KEYS.openai),
capDerivedPaths: [mtField],
reasoning: requestReasoning(options?.reasoning, carried),
...(withheld !== undefined && withheld.length > 0 ? { withheld } : {}),
onCommitted: () => {
routeAdmission();
sentMaxTokens = builtMaxTokens;
sentMaxTokensLane = builtMaxTokensLane;
sentToolNames = builtToolNames;
},
};
},
makeParser: (ctrl) => {
const { out, partial } = ctrl;
let accumText = "";
let accumReasoning = "";
let accumRefusal = "";
let degenerate = false;
let degenFace;
const rep = createRepetitionPoll();
let lastDegenCheck = 0;
let lastDegenCheckReasoning = 0;
const detectRep = config.detectRepetition !== false;
let emittedTextStart = false;
let textIndex = 0;
let nextIndex = 0;
const segments = [];
let segmentOpen = false;
let thinkingIndex = 0;
const toolAccum = new Map();
const responseIds = responseToolCallIds();
let finishReason = null;
let inBandError;
const afterEnd = createStreamEndLedger(ctrl.providerWords);
const terminalFrameSeen = () => finishReason != null || inBandError !== undefined;
let usageRaw;
let usageUnreadable = false;
const loss = createCallLoss();
let malformedFrames = 0;
let malformedSample;
const dropFrame = (data) => {
malformedFrames++;
malformedSample ??= ctrl.providerWords(data).slice(0, 160);
};
const strayBytesHeld = () => [...toolAccum.values()].some((a) => !a.name && a.args !== "");
let thinkingBlock = { type: "thinking", thinking: "" };
const textBlock = { type: "text", text: "" };
const pushReasoningDelta = (delta) => {
if (!delta)
return;
ctrl.sawContentToken();
if (!segmentOpen) {
segmentOpen = true;
thinkingIndex = nextIndex++;
thinkingBlock = { type: "thinking", thinking: "" };
lastDegenCheckReasoning = 0;
partial.content = [thinkingBlock];
out.push({ type: "thinking_start", contentIndex: thinkingIndex, partial: { ...partial } });
}
accumReasoning += delta;
thinkingBlock.thinking += delta;
out.push({ type: "thinking_delta", contentIndex: thinkingIndex, delta, partial: { ...partial } });
if (detectRep && !degenerate && thinkingBlock.thinking.length - lastDegenCheckReasoning >= 64) {
lastDegenCheckReasoning = thinkingBlock.thinking.length;
if (rep.poll(thinkingBlock.thinking)) {
degenerate = true;
degenFace = "reasoning";
ctrl.cancel();
}
}
};
const closeThinking = () => {
if (!segmentOpen)
return false;
segmentOpen = false;
segments.push(thinkingBlock.thinking);
out.push({ type: "thinking_end", contentIndex: thinkingIndex, content: thinkingBlock.thinking, partial: { ...partial } });
return true;
};
const pushTextDelta = (delta) => {
if (!delta)
return;
ctrl.sawContentToken();
const segmentClosed = closeThinking();
if (!emittedTextStart) {
emittedTextStart = true;
textIndex = nextIndex++;
partial.content = [textBlock];
out.push({ type: "text_start", contentIndex: textIndex, partial: { ...partial } });
}
else if (segmentClosed) {
partial.content = [textBlock];
}
accumText += delta;
textBlock.text = accumText;
out.push({ type: "text_delta", contentIndex: textIndex, delta, partial: { ...partial } });
if (detectRep && !degenerate && accumText.length - lastDegenCheck >= 64) {
lastDegenCheck = accumText.length;
if (rep.poll(accumText)) {
degenerate = true;
degenFace = "text";
ctrl.cancel();
}
}
};
return {
snapshot() {
const hasCompletedToolCall = [...toolAccum.values()].some((a) => a.closedTc !== undefined);
const hasSubstantiveText = accumText.trim() !== "" || accumRefusal.trim() !== "";
return {
hasSubstantiveText,
hasCompletedToolCall,
hasOnlyThinking: accumReasoning.length > 0 && !hasSubstantiveText && !hasCompletedToolCall,
terminalFrameSeen: terminalFrameSeen(),
};
},
sealForRetry() {
closeThinking();
},
onLine(rawLine) {
if (inBandError !== undefined)
return;
const line = rawLine.trim();
if (!line.startsWith("data:"))
return;
const data = line.slice(5).trim();
if (carriesNoContent(data))
return;
let parsed;
try {
parsed = JSON.parse(data);
}
catch {
if (terminalFrameSeen()) {
afterEnd.note("content", NO_WORD);
return;
}
dropFrame(data);
loss.lose();
return;
}
const chunk = readChunk(parsed);
if (chunk.error !== undefined) {
if (terminalFrameSeen()) {
afterEnd.note("error", providerErrorWord(chunk.error) ?? "?");
return;
}
ctrl.inBandFrame(chunk.error);
inBandError = inBandProviderError(ctrl.dialect, chunk.error, "gateway", ctrl.providerWords);
ctrl.cancel();
return;
}
if (chunk.usage !== undefined)
usageRaw = chunk.usage;
if (chunk.usageUnreadable)
usageUnreadable = true;
noteResponseModel(partial, chunk.model, model.id, ctrl.providerWords);
const choice = chunk.choice;
if (terminalFrameSeen()) {
if (choice !== undefined && choice.finish !== null && choice.finish !== finishReason)
afterEnd.note("ending", choice.finish, choice.offered);
else if (choice?.offered !== undefined)
afterEnd.note("content", choice.offered, choice.offered);
else if (chunk.outOfShape)
afterEnd.note("content", NO_WORD);
return;
}
if (chunk.outOfShape)
dropFrame(data);
if (chunk.callsUnreadable)
loss.lose();
if (choice === undefined)
return;
if (choice.finish !== null)
finishReason = choice.finish;
if (choice.reasoning !== undefined)
pushReasoningDelta(choice.reasoning);
if (choice.refusal) {
ctrl.sawContentToken();
accumRefusal += choice.refusal;
}
if (choice.content !== undefined)
pushTextDelta(choice.content);
if (choice.calls !== undefined) {
if (choice.calls.some((tc) => Boolean(tc.name) || Boolean(tc.arguments)))
ctrl.sawContentToken();
else
ctrl.sawProgress();
let unplaced = false;
let opened;
const strayBefore = strayBytesHeld();
for (const tc of choice.calls) {
const idx = tc.index ?? (tc.id ? toolAccum.size : Math.max(0, toolAccum.size - 1));
if (!toolAccum.has(idx))
opened = Math.max(opened ?? idx, idx);
const acc = toolAccum.get(idx) ?? { id: "", name: "", args: "" };
if (tc.id)
acc.id = tc.id;
if (tc.name)
acc.name = sentToolNames.called(tc.name);
if (tc.arguments) {
if (acc.closedTc === undefined)
acc.args += tc.arguments;
else {
unplaced = true;
loss.lose();
}
}
toolAccum.set(idx, acc);
}
if (unplaced && !chunk.outOfShape)
dropFrame(data);
if (opened !== undefined && !loss.lost && !strayBefore) {
for (const [prevIdx, prevAcc] of [...toolAccum.entries()].sort((a, b) => a[0] - b[0])) {
if (prevIdx >= opened || prevAcc.closedTc)
continue;
if (prevAcc.args === "")
continue;
const done = closeToolCallAccum(prevAcc, responseIds, false);
if (done) {
out.push({ type: "toolcall_end", contentIndex: prevIdx, toolCall: done, partial: { ...partial } });
}
}
}
}
},
finalize(opts) {
closeThinking();
const textFace = degenerate && degenFace === "text" && rep.cut !== undefined ? trimDegenerateTail(accumText, rep.cut) : accumText;
if (emittedTextStart && ((opts?.truncated !== true && inBandError === undefined) || finishReason != null)) {
out.push({ type: "text_end", contentIndex: textIndex, content: textFace, partial: { ...partial } });
}
const finalContent = [];
const thinkingBlocks = segments.map((thinking) => ({ type: "thinking", thinking }));
finalContent.push(...thinkingBlocks);
if (textFace)
finalContent.push({ type: "text", text: textFace });
const toolCalls = [];
const malformed = [];
const withheld = [];
const unnamed = [];
let emptyPlaceholders = 0;
const endedCut = finishReason === "length" || finishReason == null;
if (strayBytesHeld())
loss.lose();
for (const acc of [...toolAccum.entries()].sort((a, b) => a[0] - b[0]).map((e) => e[1])) {
if (!acc.name) {
if (!acc.id && acc.args === "") {
emptyPlaceholders++;
continue;
}
(nameMissingCause(!endedCut) === "truncated" ? malformed : unnamed).push(`id="${ctrl.providerWords(acc.id || "?")}"(${ctrl.providerWords(acc.args).slice(0, 200)})`);
continue;
}
if (loss.withholds(acc.closedTc !== undefined)) {
withheld.push(`${ctrl.providerWords(acc.name)}(${ctrl.providerWords(acc.args).slice(0, 200)})`);
continue;
}
const tc = closeToolCallAccum(acc, responseIds, !endedCut);
if (tc) {
toolCalls.push(tc);
finalContent.push(tc);
}
else {
malformed.push(`${ctrl.providerWords(acc.name)}(${ctrl.providerWords(acc.args).slice(0, 200)})`);
}
}
if (config.repairTextToolCalls && toolCalls.length === 0 && textFace && context.tools && context.tools.length > 0) {
const names = new Set(context.tools.flatMap((t) => [t.name, sentToolNames.sent(t.name), ...(t.aliases ?? [])]));
const repaired = repairTextToolCalls(textFace, names);
if (repaired.toolCalls.length > 0) {
finalContent.length = 0;
finalContent.push(...thinkingBlocks);
if (repaired.cleanedText)
finalContent.push({ type: "text", text: repaired.cleanedText });
for (const repairedCall of repaired.toolCalls) {
const tc = { ...repairedCall, name: sentToolNames.called(repairedCall.name) };
if (loss.withholds(false)) {
withheld.push(`${ctrl.providerWords(tc.name)}(${ctrl.providerWords(JSON.stringify(tc.arguments)).slice(0, 200)})`);
continue;
}
finalContent.push(tc);
toolCalls.push(tc);
}
}
}
const emptySlots = `<empty slot>${emptyPlaceholders > 1 ? ` ×${emptyPlaceholders}` : ""}`;
const cut = [...malformed, ...withheld];
const sawRealAction = toolCalls.length > 0 || cut.length > 0 || unnamed.length > 0;
const verdictOnly = !sawRealAction && finishReason === "tool_calls";
if (emptyPlaceholders > 0 && sawRealAction) {
unnamed.push(emptySlots);
}
else if (verdictOnly) {
unnamed.push(emptyPlaceholders > 0 ? emptySlots : "<no tool_call delta arrived on the stream>");
}
const toolErrorParts = [];
const capFacts = { capStop: finishReason === "length", outputTokens: usageRaw?.completion_tokens, capTokens: sentMaxTokens };
const usageReading = reportedUsageOf(model, usageRaw);
const usageMissing = usageReading.missing || usageUnreadable;
if (malformed.length > 0) {
toolErrorParts.push(`tool call argument(s) not valid JSON (likely truncated, finish_reason="${finishReason ?? "?"}"${truncationCauseClause({ ...capFacts, terminalFrameSeen: terminalFrameSeen(), inputTokens: requestInputTokensOf(usageReading.usage), contextWindow: model.contextWindow })}): ${malformed.join("; ")}`);
}
if (withheld.length > 0)
toolErrorParts.push(withheldCallsClause(`finish_reason="${finishReason ?? "?"}"`, withheld));
if (unnamed.length > 0) {
toolErrorParts.push(`tool call(s) arrived with no tool name and cannot be executed (finish_reason="${finishReason ?? "?"}"): ${unnamed.join("; ")}`);
}
const toolError = toolErrorParts.length > 0 ? toolErrorParts.join(" | ") : undefined;
const noUsableContent = toolCalls.length === 0 && !accumText.trim();
const dropEnding = droppedCallsEnding({ dropped: verdictOnly ? noUsableContent : cut.length > 0 || unnamed.length > 0, survivingCalls: toolCalls.length }, options);
const notes = [];
if (cut.length > 0) {
notes.push({ cause: "truncated", count: cut.length, text: `\n[note: ${cut.length} tool call(s) were truncated (finish_reason="${finishReason ?? "?"}") and dropped — re-issue them next turn: ${cut.join("; ")}]` });
}
if (unnamed.length > 0) {
notes.push({ cause: "unnamed", count: unnamed.length, text: `\n[note: ${unnamed.length} tool call(s) arrived with no tool name and were dropped — re-issue them next turn with an explicit tool name: ${unnamed.join("; ")}]` });
}
if (malformedFrames > 0) {
notes.push({ cause: "bad_frame", count: malformedFrames, text: droppedFramesNote(malformedFrames, malformedSample) });
}
placeTurnNotes(partial, finalContent, notes, { endWord: finishReason ?? undefined, contextWindow: model.contextWindow, maxTokens: model.maxTokens });
if (inBandError !== undefined) {
ctrl.keepOutput({ content: finalContent, usage: usageReading.usage, ...(usageMissing ? { usageMissing: true } : {}) });
throw inBandError;
}
const truncatedEmpty = finishReason === "length" && noUsableContent && !toolError;
const dynamicCut = truncatedEmpty && options?.maxTokensDynamic === true;
const finishReading = readFinishReason(finishReason);
const safetyCut = finishReading?.kind === "refusal";
const contextWindowExceeded = finishReading?.kind === "input_too_long";
const providerCut = finishReading?.kind === "provider_cut" ? finishReading : undefined;
const finishReasonUnknown = finishReading?.kind === "unrecognized" ? echoFoldedWord(finishReason ?? "", ctrl.providerWords) : undefined;
const finishQuoted = JSON.stringify(ctrl.providerWords(finishReason ?? "").slice(0, 64));
const refused = accumRefusal.trim().length > 0;
const emptyNoFinish = noUsableContent && finishReason == null && !degenerate && dropEnding !== "toolUse";
const maxTokensNote = sentMaxTokens !== undefined
? `effective max_tokens=${sentMaxTokens} (from ${sentMaxTokensLane === "options"
? "options.maxTokens"
: sentMaxTokensLane === "engine"
? "the engine's context-overflow recovery"
: "model.maxTokens"})`
: "max_tokens not set (neither options.maxTokens nor model.maxTokens — the provider's default cap applied)";
const errorMessage = degenerate
? DEGENERATE_MESSAGE
: safetyCut
? `[refusal] response cut by the provider content filter (finish_reason=${finishQuoted}) — the output was censored/truncated for policy and is unreliable`
: refused
? `[refusal] response refused by the model for policy reasons: ${ctrl.providerWords(accumRefusal.trim())}`
: contextWindowExceeded
? `[invalid_request] model context window exceeded (finish_reason=${finishQuoted}) — the conversation no longer fits the model's context window`
: providerCut !== undefined
? `[${providerCut.code}] response cut short by the provider (finish_reason=${finishQuoted}) — the text above may be incomplete`
: (toolError ??
(truncatedEmpty && !dynamicCut
? accumReasoning.trim()
? `[length_empty] response truncated at max_tokens (finish_reason="length", ${maxTokensNote}) with no answer text — the model spent the whole budget on reasoning (${accumReasoning.length} reasoning chars). Raise max_tokens, or disable thinking for this task.`
: `[length_empty] response truncated at max_tokens (finish_reason="length", ${maxTokensNote}) with no answer text — raise max_tokens`
: emptyNoFinish
? `[stream_torn] model stream ended with no content and no finish_reason — the response was lost (a torn stream or an in-band provider error frame)${malformedFrames > 0 ? ` — ${malformedFrames} unparseable data frame(s) were dropped on this stream (first sample: ${JSON.stringify(malformedSample)})` : ""}`
: undefined));
const errored = degenerate ||
safetyCut ||
refused ||
contextWindowExceeded ||
providerCut !== undefined ||
emptyNoFinish ||
dropEnding === "failed" ||
(truncatedEmpty && !dynamicCut);
const tornWithContent = !errored && opts?.truncated !== true && !terminalFrameSeen() && !noUsableContent && !degenerate;
const errorMessageOut = tornWithContent ? (errorMessage ? `${errorMessage}\n${STREAM_TORN_WARNING}` : STREAM_TORN_WARNING) : errorMessage;
const errorKind = degenerate
? "degenerate"
: !safetyCut && !refused && contextWindowExceeded
? "input_too_long"
: !safetyCut && !refused && toolError === undefined && truncatedEmpty && !dynamicCut
? "length_empty"
: undefined;
const modelOutputInvalid = errored && toolError !== undefined && !degenerate && !safetyCut && !refused && !contextWindowExceeded && providerCut === undefined
? modelOutputInvalidOf({ truncated: cut.length, unnamed: unnamed.length }, capFacts)
: undefined;
const finalMessage = {
...partial,
content: finalContent.length > 0 ? finalContent : [{ type: "text", text: "" }],
stopReason: errored ? "error" : dropEnding === "toolUse" ? "toolUse" : mapFinishReason(finishReason, toolCalls.length > 0),
usage: usageReading.usage,
...(usageMissing ? { usageMissing: true } : {}),
timestamp: Date.now(),
...(errorMessageOut ? { errorMessage: errorMessageOut } : {}),
...(errorKind ? { errorKind } : {}),
...(modelOutputInvalid !== undefined ? { modelOutputInvalid } : {}),
...(tornWithContent ? { partialFinalized: true } : {}),
...(finishReasonUnknown !== undefined ? { finishReasonUnknown } : {}),
...(afterEnd.ignored !== undefined ? { streamEndIgnored: afterEnd.ignored } : {}),
...(rep.cut !== undefined || rep.spared.length > 0
? { repetition: { ...(rep.cut !== undefined ? { cut: rep.cut } : {}), ...(rep.spared.length > 0 ? { spared: rep.spared } : {}) } }
: {}),
};
if (errored) {
out.push({ type: "error", reason: "error", error: finalMessage });
}
else {
out.push({
type: "done",
reason: finalMessage.stopReason,
message: finalMessage,
});
}
},
};
},
});
};
return { stream, adjudicateRoute: createBrainRouteJudge({ ...config, keyHeader: OPENAI_KEY_HEADER }) };
}