UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

1,102 lines • 62.9 kB
import { isRequestOnly, } from "../internal/llm.js";
import { BrainError } from "./errors.js";
import { promptCacheKeyDefect } from "./prompt-cache-key.js";
import { cacheRetentionDefect } from "./cache-retention.js";
import { startsWithInputTooLongAnchor } from "./input-too-long.js";
import { DEGENERATE_MESSAGE, trimDegenerateTail } from "./repetition.js";
import { NO_WORD, STREAM_TORN_WARNING, carriesNoContent, createCallLoss, createRepetitionPoll, createStreamEndLedger, droppedCallsEnding, droppedFramesNote, endingInNoWord, 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, reportImagesWithheld, sendableImages } from "./media-degrade.js";
import { ANTHROPIC_RESERVED, OUTPUT_CAP_KEYS, applyExtraBody, declaredRequestValues, effectiveOutputCap, headerBagOnce, headerListEntries, lockHeader, mergeHeaders, takeHeaderSpellings } from "./request-params.js";
import { admitRouteRequest, applyRouteCredentialHeaders, assertServableRequestRoot, brainConfigSnapshot, createBrainRouteJudge, dropBlankCredentialHeaders, joinRequestUrl, keyCarriedBy, resolveRequestRootOf, resolveRouteCredential } from "./route-adjudicator.js";
import { requestRouteOf } from "./request-route.js";
import { authSchemeCredentials, httpTrimmed } from "../core/protocol-http-auth.js";
import { NAMES_AS_WRITTEN, judgeInBandError, resolveProviderDialect, endpointToolNames } from "./provider-dialect.js";
import { applyReasoningToRequest, mergeReasoningHeaders } from "./reasoning-request.js";
import { applyFastModeToRequest, fastModeRouteOf, observeFastMode, requestSpeedOf } from "./fast-mode.js";
import { requestReasoning } from "./reasoning-stamp.js";
import { requestWithheld } from "./model-capability.js";
import { reasoningTokensOf } from "./usage-reasoning.js";
import { usageOfStatement } from "./usage-reading.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 EPHEMERAL = { type: "ephemeral" };
const CACHE_CONTROL_OF_RETENTION = Object.freeze({
    short: EPHEMERAL,
    long: Object.freeze({ type: "ephemeral", ttl: "1h" }),
    none: undefined,
});
function cacheControlFor(cacheBreakpoints, retention) {
    const defect = cacheRetentionDefect(retention, "StreamOptions.cacheRetention");
    if (defect !== undefined)
        throw new BrainError("invalid_request", `config.invalid_argument: ${defect}`);
    return cacheBreakpoints ? CACHE_CONTROL_OF_RETENTION[retention ?? "short"] : undefined;
}
function textOf(content) {
    return typeof content === "string"
        ? content
        : content.filter((c) => c.type === "text" && typeof c.text === "string").map((c) => c.text).join("");
}
function toUserBlocks(content, withhold, requestOnlyWireBlocks) {
    if (typeof content === "string") {
        return content.length > 0 ? [{ type: "text", text: content }] : [];
    }
    const blocks = [];
    let omitted = 0;
    for (const c of content) {
        let wireBlock;
        if (c.type === "text" && typeof c.text === "string" && c.text.length > 0) {
            wireBlock = { type: "text", text: c.text };
        }
        else if (c.type === "image" && c.data && c.mimeType) {
            if (withhold === undefined)
                wireBlock = { type: "image", source: { type: "base64", media_type: c.mimeType, data: c.data } };
            else {
                omitted++;
                wireBlock = { type: "text", text: IMAGE_OMITTED_NO_VISION };
            }
        }
        if (wireBlock !== undefined) {
            blocks.push(wireBlock);
            if (requestOnlyWireBlocks !== undefined && isRequestOnly(c))
                requestOnlyWireBlocks.add(wireBlock);
        }
    }
    if (withhold !== undefined)
        reportImagesWithheld(withhold, omitted);
    return blocks;
}
function toAnthropicMessages(ctx, model, toolNames, requestOnlyWireBlocks) {
    const imageWithhold = imageWithholdOf(model);
    const supportsVision = imageWithhold === undefined;
    const raw = [];
    let pendingDocs = [];
    const flushDocs = () => {
        if (pendingDocs.length === 0)
            return;
        raw.push({ role: "user", content: pendingDocs });
        pendingDocs = [];
    };
    const resultWireId = providerResultIds(ctx.messages);
    for (const m of ctx.messages) {
        if (m.role !== "toolResult")
            flushDocs();
        if (m.role === "user") {
            const ub = toUserBlocks(m.content, imageWithhold, requestOnlyWireBlocks);
            if (ub.length > 0) {
                raw.push({ role: "user", content: ub });
            }
            else {
                const placeholder = { type: "text", text: NO_CONTENT };
                if (requestOnlyWireBlocks !== undefined &&
                    Array.isArray(m.content) &&
                    m.content.length > 0 &&
                    m.content.every((c) => isRequestOnly(c))) {
                    requestOnlyWireBlocks.add(placeholder);
                }
                raw.push({ role: "user", content: [placeholder] });
            }
        }
        else if (m.role === "assistant") {
            const blocks = [];
            for (const c of m.content) {
                if (c.type === "thinking") {
                    const tc = c;
                    const sigRaw = tc.thinkingSignature;
                    const sig = typeof sigRaw === "string" && sigRaw.length > 0 ? sigRaw : undefined;
                    if (tc.redacted) {
                        if (sig)
                            blocks.push({ type: "redacted_thinking", data: sig });
                    }
                    else if (sig) {
                        blocks.push({ type: "thinking", thinking: c.thinking, signature: sig });
                    }
                }
                else if (c.type === "text" && c.text) {
                    blocks.push({ type: "text", text: c.text });
                }
                else if (c.type === "toolCall") {
                    blocks.push({ type: "tool_use", id: providerToolCallId(c), name: toolNames.sent(c.name), input: c.arguments ?? {} });
                }
            }
            raw.push({ role: "assistant", content: blocks.length ? blocks : [{ type: "text", text: NO_CONTENT }] });
        }
        else if (m.role === "toolResult") {
            const parts = Array.isArray(m.content) ? m.content : undefined;
            const docs = parts ? parts.filter((c) => c.type === "document") : [];
            const rest = docs.length > 0 && parts ? parts.filter((c) => c.type !== "document") : m.content;
            const hasImage = !m.isError && Array.isArray(rest) && rest.some((c) => c.type === "image");
            let inner = hasImage ? toUserBlocks(rest, imageWithhold) : textOf(rest);
            if (docs.length > 0 && !m.isError) {
                if (supportsVision) {
                    for (const d of docs) {
                        if (d.data && d.mimeType)
                            pendingDocs.push({ type: "document", source: { type: "base64", media_type: d.mimeType, data: d.data } });
                    }
                    const pointer = "(PDF document attached below)";
                    if (typeof inner === "string")
                        inner = inner ? `${inner}\n${pointer}` : pointer;
                    else
                        inner.push({ type: "text", text: pointer });
                }
                else {
                    emitBrainTelemetry({ kind: "document_placeholder", count: docs.length });
                    const note = DOCUMENT_OMITTED;
                    if (typeof inner === "string")
                        inner = inner ? `${inner}\n${note}` : note;
                    else
                        inner.push({ type: "text", text: note });
                }
            }
            if (m.isError) {
                const note = errorResultMediaNote({ images: sendableImages(Array.isArray(rest) ? rest : []).length, documents: docs.length });
                if (note !== undefined) {
                    if (typeof inner === "string")
                        inner = inner ? `${inner}\n${note}` : note;
                    else
                        inner.push({ type: "text", text: note });
                }
            }
            if (typeof inner === "string" ? inner.length === 0 : inner.length === 0)
                inner = NO_CONTENT;
            raw.push({
                role: "user",
                content: [
                    {
                        type: "tool_result",
                        tool_use_id: resultWireId(m.toolCallId),
                        content: inner,
                        ...(m.isError ? { is_error: true } : {}),
                    },
                ],
            });
        }
    }
    flushDocs();
    const merged = [];
    for (const msg of raw) {
        const prev = merged[merged.length - 1];
        if (prev && prev.role === msg.role) {
            prev.content.push(...msg.content);
        }
        else {
            merged.push({ role: msg.role, content: [...msg.content] });
        }
    }
    return merged;
}
function toAnthropicTools(ctx, cacheControl, toolNames) {
    if (!ctx.tools || ctx.tools.length === 0) {
        return undefined;
    }
    return ctx.tools.map((t, i) => ({
        name: toolNames.sent(t.name),
        description: t.description,
        input_schema: projectToolSchema(t.parameters),
        ...(cacheControl !== undefined && i === ctx.tools.length - 1 ? { cache_control: cacheControl } : {}),
    }));
}
function isBlankWireText(block) {
    return block.type === "text" && (typeof block.text !== "string" || block.text.trim().length === 0);
}
function withHistoryCacheMark(body, requestOnlyWireBlocks, cacheControl) {
    if (body.cache_control != null)
        return body;
    let existing = 0;
    if (Array.isArray(body.system)) {
        for (const block of body.system) {
            if (block !== null && typeof block === "object" && block.cache_control != null) {
                existing++;
            }
        }
    }
    if (Array.isArray(body.tools)) {
        for (const tool of body.tools) {
            if (tool !== null && typeof tool === "object" && tool.cache_control != null) {
                existing++;
            }
        }
    }
    if (existing > 3)
        return body;
    const messages = body.messages;
    if (!Array.isArray(messages))
        return body;
    for (let i = messages.length - 1; i >= 0; i--) {
        const msg = messages[i];
        if (!msg || !Array.isArray(msg.content) || msg.content.length === 0)
            continue;
        let markIdx = -1;
        if (msg.role === "assistant") {
            const lastIdx = msg.content.length - 1;
            const last = msg.content[lastIdx];
            if (last !== null && typeof last === "object" && !requestOnlyWireBlocks.has(last)) {
                const rec = last;
                if (rec.type !== "thinking" && rec.type !== "redacted_thinking" && !isBlankWireText(rec)) {
                    markIdx = lastIdx;
                }
            }
        }
        else if (msg.role === "user") {
            for (let j = msg.content.length - 1; j >= 0; j--) {
                const block = msg.content[j];
                if (block === null || typeof block !== "object")
                    continue;
                if (requestOnlyWireBlocks.has(block))
                    continue;
                const rec = block;
                if (rec.type === "thinking" || rec.type === "redacted_thinking" || isBlankWireText(rec))
                    continue;
                markIdx = j;
                break;
            }
        }
        if (markIdx !== -1) {
            const target = msg.content[markIdx];
            const nextContent = msg.content.slice();
            nextContent[markIdx] = { ...target, cache_control: cacheControl };
            const nextMessages = messages.slice();
            nextMessages[i] = { ...msg, content: nextContent };
            return { ...body, messages: nextMessages };
        }
    }
    return body;
}
const NO_CONTENT = "(no content)";
function mapStopReason(reason, hadToolUse) {
    if (hadToolUse || reason === "tool_use")
        return "toolUse";
    if (reason === "max_tokens")
        return "length";
    return "stop";
}
function anthropicStreamErrorCode(t) {
    switch (t) {
        case "rate_limit_error":
            return "rate_limit";
        case "authentication_error":
        case "permission_error":
            return "auth";
        case "invalid_request_error":
            return "invalid_request";
        case "request_too_large":
            return "invalid_request";
        default:
            return "server";
    }
}
function reasoningOf(u) {
    return reasoningTokensOf(u.output_tokens ?? 0, u.thinking_tokens);
}
function reportedUsageOf(model, u) {
    return usageOfStatement(model, "input-excludes-cached", {
        input: u.input_tokens,
        output: u.output_tokens,
        cacheRead: u.cache_read_input_tokens,
        cacheWrite: u.cache_creation_input_tokens,
        cacheWriteLong: u.ephemeral_1h_input_tokens,
        speed: u.speed,
    }, reasoningOf(u));
}
function closeToolUseBlock(acc, responseIds, closed) {
    if (acc.closedTc)
        return acc.closedTc;
    if (!acc.toolName)
        return undefined;
    const args = parseStreamedToolArgs(acc.toolJson, closed);
    if (args === undefined)
        return undefined;
    const { engineId, wireId } = admitToolCallId(acc.toolId, "toolu_", responseIds);
    acc.closedTc = { type: "toolCall", id: engineId, ...(wireId !== engineId ? { wireId } : {}), name: acc.toolName, arguments: args };
    return acc.closedTc;
}
const DELTA_KIND = Object.freeze({
    text_delta: { member: "text", block: "text" },
    thinking_delta: { member: "thinking", block: "thinking" },
    input_json_delta: { member: "partial_json", block: "tool_use" },
    signature_delta: { member: "signature", block: "thinking" },
});
function readEvent(raw) {
    const frame = memberReader();
    const usageSeat = memberReader();
    const unreadable = (index) => ({
        event: { kind: "unreadable", ...(index !== undefined ? { index } : {}) },
        outOfShape: true,
        usageUnreadable: usageSeat.outOfShape,
    });
    const evt = frame.object(raw);
    if (evt === undefined)
        return frame.outOfShape ? unreadable() : { event: { kind: "other" }, outOfShape: false, usageUnreadable: false };
    const type = frame.word(evt.type);
    if (type === undefined)
        return unreadable();
    const usageOf = (v) => {
        const u = usageSeat.object(v);
        if (u === undefined)
            return undefined;
        return {
            input_tokens: usageSeat.count(u.input_tokens),
            output_tokens: usageSeat.count(u.output_tokens),
            cache_read_input_tokens: usageSeat.count(u.cache_read_input_tokens),
            cache_creation_input_tokens: usageSeat.count(u.cache_creation_input_tokens),
            ephemeral_1h_input_tokens: usageSeat.count(usageSeat.object(u.cache_creation)?.ephemeral_1h_input_tokens),
            thinking_tokens: usageSeat.claimIn(u.output_tokens_details, "thinking_tokens"),
            speed: u.speed ?? undefined,
        };
    };
    const done = (event) => ({ event, outOfShape: frame.outOfShape, usageUnreadable: usageSeat.outOfShape });
    switch (type) {
        case "message_start": {
            const msg = frame.object(evt.message);
            const usage = usageOf(msg?.usage);
            return done({ kind: "message_start", model: msg?.model, ...(usage !== undefined ? { usage } : {}) });
        }
        case "content_block_start":
        case "content_block_delta":
        case "content_block_stop": {
            const index = frame.count(evt.index);
            if (index === undefined)
                return unreadable();
            if (type === "content_block_stop")
                return done({ kind: "content_block_stop", index });
            const body = frame.object(type === "content_block_start" ? evt.content_block : evt.delta);
            const bodyType = frame.word(body?.type);
            if (body === undefined || bodyType === undefined)
                return unreadable(index);
            if (type === "content_block_start") {
                const block = bodyType === "tool_use"
                    ? { type: bodyType, id: frame.word(body.id), name: frame.word(body.name) }
                    : bodyType === "redacted_thinking"
                        ? { type: bodyType, data: frame.word(body.data) }
                        : bodyType === "thinking"
                            ? { type: bodyType, thinking: frame.word(body.thinking), signature: frame.word(body.signature) }
                            : { type: bodyType };
                return done({ kind: "content_block_start", index, block });
            }
            const member = Object.hasOwn(DELTA_KIND, bodyType) ? DELTA_KIND[bodyType]?.member : undefined;
            const delta = member === undefined ? { type: bodyType } : { type: bodyType, [member]: frame.word(body[member]) };
            return done({ kind: "content_block_delta", index, delta });
        }
        case "message_delta": {
            const delta = frame.object(evt.delta);
            const details = frame.object(delta?.stop_details);
            const usage = usageOf(evt.usage);
            return done({
                kind: "message_delta",
                stop: endingWordOf(delta?.stop_reason),
                stopInNoWord: endingInNoWord(delta?.stop_reason),
                ...(details !== undefined ? { stopDetails: { category: frame.word(details.category), explanation: frame.word(details.explanation) } } : {}),
                ...(usage !== undefined ? { usage } : {}),
            });
        }
        case "message_stop":
            return done({ kind: "message_stop" });
        case "error": {
            const e = frame.object(evt.error);
            return done({ kind: "error", ...(e !== undefined ? { error: { type: frame.word(e.type), message: frame.word(e.message) } } : {}) });
        }
        default:
            return done({ kind: "other" });
    }
}
export const ANTHROPIC_DEFAULT_BASE_URL = "https://api.anthropic.com";
const ANTHROPIC_KEY_HEADER = "x-api-key";
const BEARER_CREDENTIAL_BETAS = Object.freeze([Object.freeze({ head: "sk-ant-oat", beta: "oauth-2025-04-20" })]);
const bearerCredentialRowOf = (credential) => BEARER_CREDENTIAL_BETAS.find((row) => credential.startsWith(row.head));
function anthropicKeyHeaderOf(apiKey, headers) {
    const seatTaken = Object.keys(headers).some((name) => name.toLowerCase() === "authorization");
    return !seatTaken && bearerCredentialRowOf(apiKey) !== undefined ? "authorization" : ANTHROPIC_KEY_HEADER;
}
function credentialBetaOf(headers) {
    const carried = Object.entries(headers).filter(([name]) => name.toLowerCase() === "authorization");
    if (carried.length !== 1 || typeof carried[0][1] !== "string")
        return undefined;
    const value = httpTrimmed(carried[0][1]);
    const credentials = authSchemeCredentials(value);
    if (credentials === undefined || value.slice(0, value.length - credentials.length).trim().toLowerCase() !== "bearer")
        return undefined;
    const row = bearerCredentialRowOf(credentials);
    return row === undefined ? undefined : { "anthropic-beta": row.beta };
}
export function anthropicCredentialHeadersOf(input) {
    const rawKey = input.apiKey;
    const rawHeaders = input.headers;
    const given = rawHeaders !== undefined && rawHeaders !== null && typeof rawHeaders === "object" ? Object.entries(rawHeaders) : [];
    const stringValued = Object.create(null);
    for (const [name, value] of given)
        if (typeof value === "string")
            stringValued[name] = value;
    dropBlankCredentialHeaders(stringValued);
    const outgoing = Object.create(null);
    for (const [name, value] of given)
        if (typeof value === "string" ? name in stringValued : true)
            outgoing[name] = value;
    const apiKey = typeof rawKey === "string" ? keyCarriedBy(rawKey) : undefined;
    let key;
    if (apiKey !== undefined) {
        const header = anthropicKeyHeaderOf(apiKey, outgoing);
        const value = header === ANTHROPIC_KEY_HEADER ? apiKey : `Bearer ${apiKey}`;
        key = { header, value };
        lockHeader(outgoing, header, value);
    }
    const beta = credentialBetaOf(outgoing)?.["anthropic-beta"];
    return {
        ...(key !== undefined ? { key } : {}),
        ...(beta !== undefined ? { beta } : {}),
    };
}
export function createAnthropicBrain(given = {}) {
    const config = brainConfigSnapshot(given, "createAnthropicBrain config");
    assertServableRequestRoot(config.baseUrl, "config.baseUrl");
    refuseRetiredTimeoutKnobs(config, "construction", "createAnthropicBrain config");
    const doFetch = resolveFetch(config);
    const cacheBreakpoints = config.cacheBreakpoints !== false;
    const stream = (model, context, options) => {
        let thinkingRequested = false;
        let sentMaxTokens;
        let sentMaxTokensLane = "config-default";
        let sentToolNames = NAMES_AS_WRITTEN;
        return runStreamingBrain({
            model,
            doFetch,
            signal: options?.signal,
            config,
            httpLabel: "anthropic",
            maxRetries: options?.maxRetries,
            stallTimeouts: options?.stallTimeouts,
            fastMode: options?.fastMode,
            buildRequest: (overrides) => {
                const routed = { id: model.id, baseUrl: model.baseUrl };
                const { root, origin: rootOrigin } = resolveRequestRootOf(routed.baseUrl, config.baseUrl, ANTHROPIC_DEFAULT_BASE_URL);
                const url = joinRequestUrl(root, "/v1/messages");
                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: ANTHROPIC_KEY_HEADER,
                });
                const routeAdmission = admitRouteRequest(routed, routeCredential, { baseUrl: config.baseUrl, laneDefault: ANTHROPIC_DEFAULT_BASE_URL, requireCredential: config.requireCredential, ...(options?.plaintextOrigins !== undefined ? { plaintextOrigins: options.plaintextOrigins } : {}) });
                const apiKey = routeCredential.apiKey;
                const nonEmptyBlocks = context.systemBlocks?.filter((b) => b.text.length > 0);
                const cacheControl = cacheControlFor(cacheBreakpoints, options?.cacheRetention);
                const system = nonEmptyBlocks?.length
                    ? nonEmptyBlocks.map((b) => ({
                        type: "text",
                        text: b.text,
                        ...(cacheControl !== undefined && b.cacheControlBoundary ? { cache_control: cacheControl } : {}),
                    }))
                    : context.systemPrompt
                        ? [{ type: "text", text: context.systemPrompt, ...(cacheControl !== undefined ? { cache_control: cacheControl } : {}) }]
                        : undefined;
                const cacheKeyDefect = promptCacheKeyDefect(model);
                if (cacheKeyDefect !== undefined)
                    throw new BrainError("invalid_request", `config.invalid_argument: ${cacheKeyDefect} (model "${model.id}")`);
                const requestOnlyWireBlocks = new Set();
                const body = {
                    model: model.id,
                    max_tokens: overrides?.maxOutputTokens ?? options?.maxTokens ?? model.maxTokens ?? config.defaultMaxTokens ?? 4096,
                    messages: toAnthropicMessages(context, model, builtToolNames, requestOnlyWireBlocks),
                    stream: true,
                };
                if (system)
                    body.system = system;
                const tools = toAnthropicTools(context, cacheControl, builtToolNames);
                if (tools)
                    body.tools = tools;
                const anthCompat = (model.compat ?? {});
                if (options?.temperature !== undefined && anthCompat.supportsTemperature !== false) {
                    body.temperature = options.temperature;
                }
                const hardCap = overrides?.maxOutputTokens !== undefined || options?.maxTokens !== undefined;
                const { body: reasoningBody, headers: reasoningHeaders, carried, } = applyReasoningToRequest({
                    api: "anthropic-messages",
                    model,
                    level: options?.reasoning,
                    body,
                    budget: { capIsHard: hardCap, share: config.thinkingBudgetShare, tokens: config.thinkingBudgetTokens },
                    withheld,
                });
                const { body: fastBody, headers: fastHeaders, fastSpeed } = applyFastModeToRequest({ model, call: options?.fastMode, speed, body: reasoningBody, withoutBeta: overrides?.withoutFastModeBeta === true });
                const headerLayers = [modelHeaders, config.headers, optionsHeaders];
                const headers = mergeHeaders(...headerLayers);
                applyRouteCredentialHeaders(headers, routeCredential);
                const declaredBetas = headerLayers.flatMap((layer) => Object.entries(layer ?? {}).flatMap(([name, value]) => (name.toLowerCase() === "anthropic-beta" ? headerListEntries(value) : [])));
                const declared = declaredRequestValues([...headerLayers, headers], [config.version, ...declaredBetas], apiKey);
                takeHeaderSpellings(headers, "anthropic-beta");
                for (const layer of headerLayers) {
                    for (const [name, value] of Object.entries(layer ?? {}))
                        if (name.toLowerCase() === "anthropic-beta")
                            mergeReasoningHeaders(headers, { [name]: value });
                }
                mergeReasoningHeaders(headers, reasoningHeaders);
                if (fastHeaders !== undefined)
                    mergeReasoningHeaders(headers, fastHeaders);
                lockHeader(headers, "content-type", "application/json");
                lockHeader(headers, "anthropic-version", config.version ?? "2023-06-01");
                if (apiKey !== undefined) {
                    const keyHeader = anthropicKeyHeaderOf(apiKey, headers);
                    lockHeader(headers, keyHeader, keyHeader === ANTHROPIC_KEY_HEADER ? apiKey : `Bearer ${apiKey}`);
                }
                const credentialBeta = credentialBetaOf(headers);
                if (credentialBeta !== undefined)
                    mergeReasoningHeaders(headers, credentialBeta);
                const builtThinkingRequested = reasoningBody.thinking !== undefined;
                const builtMaxTokens = reasoningBody.max_tokens;
                const builtMaxTokensLane = overrides?.maxOutputTokens !== undefined
                    ? "engine"
                    : options?.maxTokens !== undefined
                        ? "options"
                        : model.maxTokens !== undefined
                            ? "model"
                            : "config-default";
                const { body: wireRaw, dropped: extraBodyDropped } = applyExtraBody(fastBody, model, ANTHROPIC_RESERVED);
                const wire = options?.historyCacheMark === true && cacheControl !== undefined
                    ? withHistoryCacheMark(wireRaw, requestOnlyWireBlocks, cacheControl)
                    : wireRaw;
                return {
                    url,
                    headers,
                    declared,
                    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.anthropic),
                    capDerivedPaths: [...OUTPUT_CAP_KEYS.anthropic, "thinking.budget_tokens"],
                    reasoning: requestReasoning(options?.reasoning, carried),
                    ...(withheld !== undefined && withheld.length > 0 ? { withheld } : {}),
                    fastSpeed,
                    onCommitted: () => {
                        routeAdmission();
                        if (fastSpeed)
                            observeFastMode(options?.fastMode, { kind: "sent", route: fastModeRouteOf(model) });
                        thinkingRequested = builtThinkingRequested;
                        sentMaxTokens = builtMaxTokens;
                        sentMaxTokensLane = builtMaxTokensLane;
                        sentToolNames = builtToolNames;
                    },
                };
            },
            makeParser: (ctrl) => {
                const { out, partial } = ctrl;
                const blocks = new Map();
                const responseIds = responseToolCallIds();
                const usageRaw = {};
                let stopReason = null;
                let stopInNoWord = false;
                let stopDetails;
                let nextContentIndex = 0;
                let malformedFrames = 0;
                let malformedSample;
                const dropFrame = (data) => {
                    malformedFrames++;
                    malformedSample ??= ctrl.providerWords(data).slice(0, 160);
                };
                let usageUnreadable = false;
                const loss = createCallLoss();
                let degenerate = false;
                let degenTextBlock;
                const rep = createRepetitionPoll();
                let lastDegenCheck = 0;
                const detectRep = config.detectRepetition !== false;
                let messageStopped = false;
                const afterEnd = createStreamEndLedger(ctrl.providerWords);
                const streamEnded = () => stopReason != null || messageStopped;
                const endedWhole = () => streamEnded() && (messageStopped || ![...blocks.values()].some((b) => b.stopped !== true));
                const mergeDeltaUsage = (u) => {
                    if (!u)
                        return;
                    if (u.output_tokens !== undefined)
                        usageRaw.output_tokens = u.output_tokens;
                    if (u.thinking_tokens !== undefined)
                        usageRaw.thinking_tokens = u.thinking_tokens;
                    if (u.speed !== undefined)
                        usageRaw.speed = u.speed;
                    if (u.input_tokens != null && u.input_tokens > 0)
                        usageRaw.input_tokens = u.input_tokens;
                    if (u.cache_read_input_tokens != null && u.cache_read_input_tokens > 0)
                        usageRaw.cache_read_input_tokens = u.cache_read_input_tokens;
                    if (u.cache_creation_input_tokens != null && u.cache_creation_input_tokens > 0) {
                        usageRaw.cache_creation_input_tokens = u.cache_creation_input_tokens;
                    }
                    if (u.ephemeral_1h_input_tokens != null && u.ephemeral_1h_input_tokens > 0)
                        usageRaw.ephemeral_1h_input_tokens = u.ephemeral_1h_input_tokens;
                };
                const reportedUsage = () => {
                    const reading = reportedUsageOf(model, usageRaw);
                    return { usage: reading.usage, ...(reading.missing || usageUnreadable ? { usageMissing: true } : {}) };
                };
                const wordOf = (v) => (typeof v === "string" && v !== "" ? v : NO_WORD);
                const refuseAfterEnd = ({ event: evt, outOfShape }) => {
                    switch (evt.kind) {
                        case "message_delta":
                            mergeDeltaUsage(evt.usage);
                            if (evt.stop !== null && evt.stop !== stopReason)
                                afterEnd.note("ending", evt.stop);
                            else if (outOfShape)
                                afterEnd.note("content", NO_WORD);
                            return;
                        case "content_block_start":
                            afterEnd.note("content", wordOf(evt.block.type), wordOf(evt.block.type));
                            return;
                        case "content_block_delta":
                            afterEnd.note("content", wordOf(evt.delta.type), wordOf(evt.delta.type));
                            return;
                        case "content_block_stop":
                        case "message_start":
                            afterEnd.note("content", evt.kind);
                            return;
                        case "error":
                            afterEnd.note("error", wordOf(evt.error?.type));
                            return;
                        case "unreadable":
                            afterEnd.note("content", NO_WORD);
                            return;
                        case "message_stop":
                            messageStopped = true;
                            return;
                        default:
                            return;
                    }
                };
                const blockFrameOutOfShape = (index) => {
                    const acc = index === undefined ? undefined : blocks.get(index);
                    if (acc === undefined || acc.type === "tool_use")
                        loss.lose();
                };
                const assembleTurn = (stampOn) => {
                    const finalContent = [];
                    const toolCalls = [];
                    const malformed = [];
                    const withheld = [];
                    const unnamed = [];
                    let anyText = false;
                    let reasoningSeen = false;
                    const endedCut = stopReason === "max_tokens" || stopReason == null;
                    for (const [, acc] of [...blocks.entries()].sort((a, b) => a[0] - b[0])) {
                        if (acc.type === "thinking") {
                            if (acc.text.length > 0 || acc.redacted === true)
                                reasoningSeen = true;
                            const block = { type: "thinking", thinking: acc.text };
                            const sig = acc.signature || acc.startSignature;
                            if (sig)
                                block.thinkingSignature = sig;
                            if (acc.redacted)
                                block.redacted = true;
                            finalContent.push(block);
                        }
                        else if (acc.type === "text") {
                            const text = acc === degenTextBlock && rep.cut !== undefined ? trimDegenerateTail(acc.text, rep.cut) : acc.text;
                            if (text) {
                                finalContent.push({ type: "text", text });
                                if (text.trim())
                                    anyText = true;
                            }
                        }
                        else if (acc.type === "tool_use") {
                            const closed = acc.stopped === true || !endedCut;
                            if (!acc.toolName) {
                                (nameMissingCause(closed) === "truncated" ? malformed : unnamed).push(`id="${ctrl.providerWords(acc.toolId || "?")}"(${ctrl.providerWords(acc.toolJson).slice(0, 200)})`);
                            }
                            else {
                                const held = loss.withholds(acc.closedTc !== undefined);
                                const tc = held ? undefined : closeToolUseBlock(acc, responseIds, closed);
                                if (held) {
                                    withheld.push(`${ctrl.providerWords(acc.toolName)}(${ctrl.providerWords(acc.toolJson).slice(0, 200)})`);
                                }
                                else if (tc) {
                                    toolCalls.push(tc);
                                    finalContent.push(tc);
                                }
                                else {
                                    malformed.push(`${ctrl.providerWords(acc.toolName)}(${ctrl.providerWords(acc.toolJson).slice(0, 200)})`);
                                }
                            }
                        }
                    }
                    const notes = [];
                    const cut = [...malformed, ...withheld];
                    if (cut.length > 0) {
                        notes.push({ cause: "truncated", count: cut.length, text: `\n[note: ${cut.length} tool call(s) were truncated (stop_reason="${stopReason ?? "?"}") 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(stampOn, finalContent, notes, { endWord: stopReason ?? undefined, contextWindow: model.contextWindow, maxTokens: model.maxTokens });
                    return { content: finalContent, toolCalls, malformed, withheld, unnamed, anyText, reasoningSeen };
                };
                const handleEvent = (reading, data) => {
                    const evt = reading.event;
                    if (streamEnded()) {
                        if (reading.usageUnreadable && evt.kind === "message_delta")
                            usageUnreadable = true;
                        refuseAfterEnd(reading);
                        return;
                    }
                    let dropped = false;
                    const drop = () => {
                        if (dropped)
                            return;
                        dropped = true;
                        dropFrame(data);
                    };
                    const unplaced = () => {
                        drop();
                        loss.lose();
                    };
                    if (reading.usageUnreadable)
                        usageUnreadable = true;
                    if (reading.outOfShape) {
                        drop();
                        if (evt.kind === "unreadable")
                            blockFrameOutOfShape(evt.index);
                    }
                    switch (evt.kind) {
                        case "message_start": {
                            noteResponseModel(partial, evt.model, model.id, ctrl.providerWords);
                            const u = evt.usage;
                            if (u) {
                                usageRaw.input_tokens = u.input_tokens;
                                usageRaw.cache_read_input_tokens = u.cache_read_input_tokens;
                                usageRaw.cache_creation_input_tokens = u.cache_creation_input_tokens;
                                usageRaw.ephemeral_1h_input_tokens = u.ephemeral_1h_input_tokens;
                                usageRaw.speed = u.speed;
                            }
                            break;
                        }
                        case "content_block_start": {
                            const idx = evt.index;
                            const cb = evt.block;
                            if (cb.type === "redacted_thinking")
                                ctrl.sawContentToken();
                            else
                                ctrl.sawProgress();
                            const taken = blocks.get(idx);
                            if (taken?.type === "tool_use" && taken.stopped === true) {
                                unplaced();
                                break;
                            }
                            const acc = { type: "text", known: true, text: "", signature: "", toolId: "", toolName: "", toolJson: "" };
                            if (cb.type === "thinking" || cb.type === "redacted_thinking") {
                                acc.type = "thinking";
                                if (cb.type === "redacted_thinking") {
                                    acc.redacted = true;
                                    acc.signature = cb.data ?? "";
                                }
                                else {
                                    if (cb.thinking)
                                        acc.text = cb.thinking;
                                    if (cb.signature)
                                        acc.startSignature = cb.signature;
                                }
                                if (acc.text !== "") {
                                    acc.pb = { type: "thinking", thinking: "" };
                                    partial.content = [acc.pb];
                                    out.push({ type: "thinking_start", contentIndex: idx, partial: { ...partial } });
                                    acc.pb.thinking = acc.text;
                                    out.push({ type: "thinking_delta", contentIndex: idx, delta: acc.text, partial: { ...partial } });
                                }
                            }
                            else if (cb.type === "tool_use") {
                                acc.type = "tool_use";
                                acc.toolId = cb.id ?? "";
                                acc.toolName = sentToolNames.called(cb.name ?? "");
                            }
                            else {
                                acc.type = "text";
                                acc.known = cb.type === "text";
                                acc.pb = { type: "text", text: "" };
                                partial.content = [acc.pb];
                                out.push({ type: "text_start", contentIndex: idx, partial: { ...partial } });
                            }
                            blocks.set(idx, acc);
                            nextContentIndex = Math.max(nextContentIndex, idx + 1);
                            if (reading.outOfShape)
                                blockFrameOutOfShape(idx);
                            break;
                        }
                        case "content_block_delta": {
                            const idx = evt.index;
                            const acc = blocks.get(idx);
                            const d = evt.delta;
                            if (acc !== undefined && ((d.type === "text_delta" && d.text) || (d.type === "thinking_delta" && d.thinking) || (d.type === "input_json_delta" && d.partial_json)))
                                ctrl.sawContentToken();
                            else
                                ctrl.sawProgress();
                            const kind = Object.hasOwn(DELTA_KIND, d.type) ? DELTA_KIND[d.type] : undefined;
                            if (kind !== undefined && (acc === undefined || acc.known)) {
                                const bytes = reading.outOfShape || Boolean(d[kind.member]);
                                const toCall = kind.block === "tool_use";
                                const onCall = acc?.type === "tool_use";
                                if (bytes && (toCall ? !(onCall && acc?.stopped !== true) : onCall)) {
                                    unplaced();
                                    break;
                                }
                                if (toCall && reading.outOfShape) {
                                    loss.lose();
                                    break;
                                }
                                if (bytes && acc === undefined) {
                                    drop();
                                    break;
                                }
                            }
                            if (!acc)
                                break;
                            if (acc.type === "tool_use" && !acc.toolName && d.type === "input_json_delta" && d.partial_json)
                                loss.lose();
                            if (d.type === "text_delta" && d.text) {
                                acc.text += d.text;
                                if (acc.pb && acc.pb.type === "text")
                                    acc.pb.text = acc.text;
                                out.push({ type: "text_delta", contentIndex: idx, delta: d.text, partial: { ...partial } });
                                if (detectRep && !degenerate && acc.text.length - lastDegenCheck >= 64) {
                                    lastDegenCheck = acc.text.length;
                                    if (rep.poll(acc.text)) {
                                        degenerate = true;
                                        degenTextBlock = acc;
                                        ctrl.cancel();
                                    }
                                }
                            }
                            else if (d.type === "thinking_delta" && d.thinking) {
                                acc.startSignature = undefined;
                                if (!acc.pb) {
                                    acc.pb = { type: "thinking", thinking: "" };
                                    partial.content = [acc.pb];
                                    out.push({ type: "thinking_start", contentIndex: idx, partial: { ...partial } });
                                }
                                acc.text += d.thinking;
                                if (acc.pb.type === "thinking")
                                    acc.pb.thinking = acc.text;
                                out.push({ type: "thinking_delta", contentIndex: idx, delta: d.thinking, partial: { ...partial } });
                                if (detectRep && !degenerate && acc.text.length - (acc.lastDegenCheck ?? 0) >= 64) {
                                    acc.lastDegenCheck = acc.text.length;
                                    if (rep.poll(acc.text)) {
                                        degenerate = true;
                                        ctrl.cancel();
                                    }
                                }
                            }
                            else if (d.type === "signature_delta" && d.signature) {
                                acc.signature += d.signature;
                            }
                            else if (d.type === "input_json_delta" && d.partial_json) {
                                acc.toolJson += d.partial_json;
                            }
                            break;
                        }
                        case "content_block_stop": {
                            const idx = evt.index;
                            const acc = blocks.get(idx);
                            if (acc)
                                acc.stopped = true;
                            if (acc?.type === "thinking") {
                                if (acc.pb)
                                    out.push({ type: "thinking_end", contentIndex: idx, content: acc.text, partial: { ...partial } });
                            }
                            else if (acc?.type === "text") {
                                out.push({ type: "text_end", contentIndex: idx, content: acc.text, partial: { ...partial } });
                            }
                            else if (acc?.type === "tool_use") {
                                const tc = loss.lost ? undefined : closeToolUseBlock(acc, responseIds, true);
                                if (tc) {
                                    out.push({ type: "toolcall_end", contentIndex: idx, toolCall: tc, partial: { ...partial } });
                                }
                            }
                            break;
                        }
                        case "message_delta": {
                            if (evt.stop !== null) {
                                stopReason = evt.stop;
                                stopInNoWord = evt.stopInNoWord;
                            }
                            const raw = evt.stopDetails;
                            if (raw !== undefined) {
                                stopDetails = {
                                    ...(raw.category !== undefined ? { category: ctrl.providerWords(raw.category) } : {}),
                                    ...(raw.explanation !== undefined ? { explanation: ctrl.providerWords(raw.explanation) } : {}),
                                };
                            }
                            mergeDeltaUsage(evt.usage);
                            break;
                        }
                        case "message_stop":
                            messageStopped = true;
                            break;
                        case "error": {
                            const e = evt.error;
                            if (e !== undefined)
                                ctrl.inBandFrame(e);
                            const inputTooLong = e?.type === "request_too_large" ||
                                (e?.type === "invalid_request_error" && typeof e.message === "string" && startsWithInputTooLongAnchor(e.message));
                            ctrl.keepOutput({ content: assembleTurn({}).content, ...reportedUsage() });
                            throw new BrainError(anthropicStreamErrorCode(e?.type), `anthropic stream error ${ctrl.providerWords(`(${e?.type ?? "unknown"}): ${e?.message ?? ""}`)}`, undefined, {
                                apiError: true,
                                ...(e === undefined ? {} : inputTooLong ? { inputTooLong: true } : { inputTooLongRuledOut: true }),
                                ...(e !== undefined && judgeInBandError(undefined, e).imageUnprocessable ? { imageUnprocessable: true } : {}),
                            });
                        }
                        default:
                            break;
                    }
                };
                return {
                    snapshot() {
                        const accs = [...blocks.values()];
                        const hasSubstantiveText = accs.some((a) => a.type === "text" && a.text.trim() !== "");
                        const hasCompletedToolCall = accs.some((a) => a.closedTc !== undefined);
                        const hasThinking = accs.some((a) => a.type === "thinking" && (a.text.length > 0 || a.redacted === true));
                        return {
                            hasSubstantiveText,
                            hasCompletedToolCall,
                            hasOnlyThinking: hasThinking && !hasSubstantiveText && !hasCompletedToolCall,
                            terminalFrameSeen: streamEnded(),
                        };
                    },
                    sealForRetry() {
                        for (const [idx, acc] of [...blocks.entries()].sort((a, b) => a[0] - b[0])) {
                            if (acc.type === "thinking" && !acc.stopped && acc.pb) {
                                acc.stopped = true;
                                out.push({ type: "thinking_end", contentIndex: idx, content: acc.text, partial: { ...partial } });
                            }
                        }
                    },
                    onLine(rawLine) {
                        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 (streamEnded()) {
                                afterEnd.note("content", NO_WORD);
                                return;
                            }
                            dropFrame(data);
                            loss.lose();
                            return;
                        }
                        handleEvent(readEvent(parsed), data);
                    },
                    finalize(opts) {
                        const { content: finalContent, toolCalls, malformed, withheld, unnamed, anyText, reasoningSeen } = assembleTurn(partial);
                        const doneReason = mapStopReason(stopReason, toolCalls.length > 0);
                        const noUsableContent = toolCalls.length === 0 && !anyText;
                        const cutCount = malformed.length + withheld.length;
                        const dropEnding = droppedCallsEnding({ dropped: cutCount > 0 || unnamed.length > 0, survivingCalls: toolCalls.length }, options);
                        const toolErrorParts = [];
                        const capFacts = { capStop: stopReason === "max_tokens", outputTokens: usageRaw.output_tokens, capTokens: sentMaxTokens };
                        if (malformed.length > 0) {
                            toolErrorParts.push(`tool call argument(s) not valid JSON (likely truncated, stop_reason="${stopReason ?? "?"}"${truncationCauseClause({ ...capFacts, terminalFrameSeen: streamEnded(), inputTokens: requestInputTokensOf(reportedUsage().usage), contextWindow: model.contextWindow })}): ${malformed.join("; ")}`);
                        }
                        if (withheld.length > 0)
                            toolErrorParts.push(withheldCallsClause(`stop_reason="${stopReason ?? "?"}"`, withheld));
                        if (unnamed.length > 0) {
                            toolErrorParts.push(`tool call(s) arrived with no tool name and cannot be executed (stop_reason="${stopReason ?? "?"}"): ${unnamed.join("; ")}`);
                        }
                        const toolError = toolErrorParts.length > 0 ? toolErrorParts.join(" | ") : undefined;
                        const truncatedEmpty = stopReason === "max_tokens" && noUsableContent && !toolError;
                        const dynamicCut = truncatedEmpty && options?.maxTokensDynamic === true;
                        const staticReasoningCut = truncatedEmpty && !dynamicCut && reasoningSeen && options?.staticReasoningCutDowngrade === true;
                        const safetyCut = stopReason === "refusal";
                        const contextWindowExceeded = stopReason === "model_context_window_exceeded";
                        const emptyNoFinish = noUsableContent && stopReason == null && !degenerate && dropEnding !== "toolUse";
                        const maxTokensNote = `effective max_tokens=${sentMaxTokens ?? "?"} (from ${sentMaxTokensLane === "options"
                            ? "options.maxTokens"
                            : sentMaxTokensLane === "engine"
                                ? "the engine's context-overflow recovery"
                                : sentMaxTokensLane === "model"
                                    ? "model.maxTokens"
                                    : "config default"})`;
                        const errorMessage = degenerate
                            ? DEGENERATE_MESSAGE
                            : safetyCut
                                ? `[refusal] response refused by the model (stop_reason="refusal"${stopDetails?.category ? `, category="${stopDetails.category}"` : ""}) — ${stopDetails?.explanation ?? "the output was withheld for policy and is unreliable"}`
                                : contextWindowExceeded
                                    ? `[invalid_request] model context window exceeded (stop_reason="model_context_window_exceeded") — the conversation no longer fits the model's context window`
                                    : (toolError ??
                                        (truncatedEmpty && !dynamicCut && !staticReasoningCut
                                            ? thinkingRequested
                                                ? `[length_empty] response truncated at max_tokens with no answer text (${maxTokensNote}) — extended thinking likely consumed the entire budget; raise max_tokens or lower thinkingBudgetShare`
                                                : reasoningSeen
                                                    ? `[length_empty] response truncated at max_tokens with no answer text (${maxTokensNote}) — the model emitted reasoning although no thinking was requested (a budget-ignoring gateway?) and it consumed the entire output budget; raise max_tokens`
                                                    : `[length_empty] response truncated at max_tokens with no answer text (${maxTokensNote}); raise max_tokens`
                                            : emptyNoFinish
                                                ? `[stream_torn] model stream ended with no content and no stop_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 ||
                            contextWindowExceeded ||
                            emptyNoFinish ||
                            dropEnding === "failed" ||
                            (truncatedEmpty && !dynamicCut && !staticReasoningCut);
                        const tornWithContent = !errored && opts?.truncated !== true && !endedWhole() && !noUsableContent && !degenerate;
                        const errorMessageOut = tornWithContent ? (errorMessage ? `${errorMessage}\n${STREAM_TORN_WARNING}` : STREAM_TORN_WARNING) : errorMessage;
                        const errorKind = degenerate
                            ? "degenerate"
                            : !safetyCut && contextWindowExceeded
                                ? "input_too_long"
                                : !safetyCut && toolError === undefined && truncatedEmpty && !dynamicCut && !staticReasoningCut
                                    ? "length_empty"
                                    : undefined;
                        const modelOutputInvalid = errored && toolError !== undefined && !degenerate && !safetyCut && !contextWindowExceeded ? modelOutputInvalidOf({ truncated: cutCount, unnamed: unnamed.length }, capFacts) : undefined;
                        const finalMessage = {
                            ...partial,
                            content: finalContent.length > 0 ? finalContent : [{ type: "text", text: "" }],
                            stopReason: errored ? "error" : dropEnding === "toolUse" ? "toolUse" : doneReason,
                            ...reportedUsage(),
                            timestamp: Date.now(),
                            ...(errorMessageOut ? { errorMessage: errorMessageOut } : {}),
                            ...(errorKind ? { errorKind } : {}),
                            ...(modelOutputInvalid !== undefined ? { modelOutputInvalid } : {}),
                            ...(tornWithContent ? { partialFinalized: true } : {}),
                            ...(stopInNoWord ? { finishReasonUnknown: NO_WORD } : {}),
                            ...(rep.cut !== undefined || rep.spared.length > 0
                                ? { repetition: { ...(rep.cut !== undefined ? { cut: rep.cut } : {}), ...(rep.spared.length > 0 ? { spared: rep.spared } : {}) } }
                                : {}),
                            ...(staticReasoningCut ? { staticReasoningCut: true } : {}),
                            ...(afterEnd.ignored !== undefined ? { streamEndIgnored: afterEnd.ignored } : {}),
                            ...(stopDetails
                                ? {
                                    diagnostics: [
                                        ...(partial.diagnostics ?? []),
                                        { type: "stop_details", timestamp: Date.now(), details: { ...stopDetails } },
                                    ],
                                }
                                : {}),
                        };
                        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, laneDefault: ANTHROPIC_DEFAULT_BASE_URL, keyHeader: ANTHROPIC_KEY_HEADER }) };
}