import { Schema } from "effect" import { LLM } from "@opencode/schema/llm" import { ContentBlockID, ToolCallID } from "./ids.js" import { AssistantMessage, Message, CompactionPart, ToolCallPart, ToolOutput, ToolResultPart, ToolResultValue, } from "./messages.js" import { ProviderMetadata } from "./options.js" import { Media } from "../media.js" export const FinishReason = LLM.FinishReason export type FinishReason = Schema.Schema.Type /** * Token usage reported by an LLM provider. * * **Inclusive totals** (match AI SDK / OpenAI / LangChain convention — a * reader from any of those ecosystems sees the number they expect): * * - `inputTokens` — total prompt tokens, *including* cached reads/writes. * - `outputTokens` — total output tokens, *including* reasoning. * - `totalTokens` — provider-supplied total, or `inputTokens + outputTokens`. * * **Non-overlapping breakdown** (every field is independently meaningful; * consumers never have to subtract): * * - `nonCachedInputTokens` — the "fresh" portion of the prompt. * - `cacheReadInputTokens` — input tokens served from cache. * - `cacheWriteInputTokens` — input tokens written to cache. * - `reasoningTokens` — subset of `outputTokens` spent on hidden reasoning. * * **Invariant**: `nonCachedInputTokens + cacheReadInputTokens + * cacheWriteInputTokens = inputTokens`, and `reasoningTokens ≤ outputTokens`. * Each protocol mapper computes whichever side it doesn't get natively, * with `Math.max(0, …)` clamping for defense against provider bugs. Because * every breakdown field is stored independently, downstream consumers can * read whatever they need (cost-by-category, context-pressure, AI-SDK-style * inclusive total) without ever subtracting — eliminating the underflow * class of bug where a clamped difference would silently store the wrong * value. * * **Semantics by provider**: * * - OpenAI Chat / Responses / Gemini: provider reports inclusive * `inputTokens` and an inclusive `outputTokens`; mapper subtracts to * derive the breakdown. * - Anthropic and Bedrock report the input breakdown natively: Anthropic's * `input_tokens` and Bedrock's `inputTokens` are non-cached only. Their * mappers sum the breakdown to derive the inclusive `inputTokens`. * Anthropic's `outputTokens` includes extended thinking. Newer responses * expose that subset as `output_tokens_details.thinking_tokens`, which maps * to `reasoningTokens`; older responses leave it undefined. * * `providerMetadata` always carries the provider's raw usage payload — * keyed by provider name (`{ openai: ... }`, `{ anthropic: ... }`, etc.) * — for fields we don't normalize and for billing-level audit trails. * Matches the same escape-hatch field on `LLMEvent`. */ export class Usage extends Schema.Class("AI.Usage")({ /** Effective input size of the final message iteration, when reported; not billed totals. */ contextTokens: Schema.optional(Schema.Number), inputTokens: Schema.optional(Schema.Number), outputTokens: Schema.optional(Schema.Number), nonCachedInputTokens: Schema.optional(Schema.Number), cacheReadInputTokens: Schema.optional(Schema.Number), cacheWriteInputTokens: Schema.optional(Schema.Number), reasoningTokens: Schema.optional(Schema.Number), totalTokens: Schema.optional(Schema.Number), /** * USD the endpoint says it charged for this request, as OpenRouter, LiteLLM and OpenCode Zen report it in * `usage.cost`. `0` is authoritative: the request was free or a subscription covered it. Absent, callers price the * tokens themselves. */ cost: Schema.optional(Schema.Number), providerMetadata: Schema.optional(ProviderMetadata), }) { /** * Non-reasoning output tokens (including compaction summaries) — `outputTokens` minus `reasoningTokens`, clamped * to zero. The one place subtraction happens in this contract; the clamp * means a provider reporting `reasoningTokens > outputTokens` produces a * harmless zero rather than a negative that crashes downstream schemas. */ get visibleOutputTokens() { return Math.max(0, (this.outputTokens ?? 0) - (this.reasoningTokens ?? 0)) } static from(input: UsageInput) { return input instanceof Usage ? input : new Usage(input) } } export type UsageInput = Usage | ConstructorParameters[0] /** * Usage reported by media routes. Providers bill images, video, speech, and transcription in different units, so * each response carries the unit it was actually metered in instead of forcing everything into tokens. */ export const MediaUsage = Schema.Union([ Schema.Struct({ type: Schema.Literal("tokens"), input: Schema.optional(Schema.Number), output: Schema.optional(Schema.Number), total: Schema.optional(Schema.Number), details: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)), }), Schema.Struct({ type: Schema.Literal("seconds"), seconds: Schema.Number }), Schema.Struct({ type: Schema.Literal("characters"), characters: Schema.Number }), Schema.Struct({ type: Schema.Literal("credits"), credits: Schema.Number }), Schema.Struct({ type: Schema.Literal("compute"), seconds: Schema.Number }), ]) .pipe(Schema.toTaggedUnion("type")) .annotate({ identifier: "AI.MediaUsage" }) export type MediaUsage = Schema.Schema.Type /** Token usage from a provider's counts. A usage object without any count is no usage, so it returns undefined. */ export const tokenUsage = (counts: { readonly input?: number readonly output?: number readonly total?: number readonly details?: Record }): MediaUsage | undefined => counts.input === undefined && counts.output === undefined && counts.total === undefined ? undefined : { type: "tokens", ...counts } /** A replacement context window, not an assistant message to append to prior history. */ export class CompactionResponse extends Schema.Class("LLM.CompactionResponse")({ replacement: Schema.Array(Message), usage: Schema.optional(Usage), }) {} /** A checkpoint only; retained history and replacement-window construction belong to the caller. */ export class CompactionCheckpointResponse extends Schema.Class( "LLM.CompactionCheckpointResponse", )({ checkpoint: CompactionPart.pipe( Schema.refine( (part): part is CompactionPart & { readonly encrypted: string; readonly text?: never } => part.encrypted !== undefined && part.encrypted.length > 0, { message: "A checkpoint response requires encrypted compaction content" }, ), ), responseID: Schema.String.check(Schema.isPattern(/\S/)), usage: Schema.optional(Usage), }) {} export const StepStart = Schema.Struct({ type: Schema.tag("step-start"), index: Schema.Number, }).annotate({ identifier: "LLM.Event.StepStart" }) export type StepStart = Schema.Schema.Type export const TextStart = Schema.Struct({ type: Schema.tag("text-start"), id: ContentBlockID, providerMetadata: Schema.optional(ProviderMetadata), }).annotate({ identifier: "LLM.Event.TextStart" }) export type TextStart = Schema.Schema.Type export const TextDelta = Schema.Struct({ type: Schema.tag("text-delta"), id: ContentBlockID, text: Schema.String, providerMetadata: Schema.optional(ProviderMetadata), }).annotate({ identifier: "LLM.Event.TextDelta" }) export type TextDelta = Schema.Schema.Type export const TextEnd = Schema.Struct({ type: Schema.tag("text-end"), id: ContentBlockID, /** Authoritative complete value; replaces accumulated deltas when present. */ text: Schema.optional(Schema.String), providerMetadata: Schema.optional(ProviderMetadata), }).annotate({ identifier: "LLM.Event.TextEnd" }) export type TextEnd = Schema.Schema.Type export const ReasoningStart = Schema.Struct({ type: Schema.tag("reasoning-start"), id: ContentBlockID, providerMetadata: Schema.optional(ProviderMetadata), }).annotate({ identifier: "LLM.Event.ReasoningStart" }) export type ReasoningStart = Schema.Schema.Type export const ReasoningDelta = Schema.Struct({ type: Schema.tag("reasoning-delta"), id: ContentBlockID, text: Schema.String, providerMetadata: Schema.optional(ProviderMetadata), }).annotate({ identifier: "LLM.Event.ReasoningDelta" }) export type ReasoningDelta = Schema.Schema.Type export const ReasoningEnd = Schema.Struct({ type: Schema.tag("reasoning-end"), id: ContentBlockID, /** Authoritative complete value; replaces accumulated deltas when present. */ text: Schema.optional(Schema.String), providerMetadata: Schema.optional(ProviderMetadata), }).annotate({ identifier: "LLM.Event.ReasoningEnd" }) export type ReasoningEnd = Schema.Schema.Type export const ToolInputStart = Schema.Struct({ type: Schema.tag("tool-input-start"), id: ToolCallID, name: Schema.String, namespace: Schema.optional(Schema.String), providerExecuted: Schema.optional(Schema.Boolean), providerMetadata: Schema.optional(ProviderMetadata), }).annotate({ identifier: "LLM.Event.ToolInputStart" }) export type ToolInputStart = Schema.Schema.Type export const ToolInputDelta = Schema.Struct({ type: Schema.tag("tool-input-delta"), id: ToolCallID, name: Schema.String, namespace: Schema.optional(Schema.String), text: Schema.String, /** Best-effort parse of all input fragments received through this delta. */ input: Schema.optional(Schema.Unknown), }).annotate({ identifier: "LLM.Event.ToolInputDelta" }) export type ToolInputDelta = Schema.Schema.Type export const ToolInputEnd = Schema.Struct({ type: Schema.tag("tool-input-end"), id: ToolCallID, name: Schema.String, namespace: Schema.optional(Schema.String), providerMetadata: Schema.optional(ProviderMetadata), }).annotate({ identifier: "LLM.Event.ToolInputEnd" }) export type ToolInputEnd = Schema.Schema.Type /** A local tool call whose final input could not be decoded. */ export const ToolInputError = Schema.Struct({ type: Schema.tag("tool-input-error"), id: ToolCallID, name: Schema.String, namespace: Schema.optional(Schema.String), raw: Schema.String, }).annotate({ identifier: "LLM.Event.ToolInputError" }) export type ToolInputError = Schema.Schema.Type export const ToolCall = Schema.Struct({ type: Schema.tag("tool-call"), id: ToolCallID, name: Schema.String, namespace: Schema.optional(Schema.String), input: Schema.Unknown, providerExecuted: Schema.optional(Schema.Boolean), providerMetadata: Schema.optional(ProviderMetadata), }).annotate({ identifier: "LLM.Event.ToolCall" }) export type ToolCall = Schema.Schema.Type export const ToolResult = Schema.Struct({ type: Schema.tag("tool-result"), id: ToolCallID, name: Schema.String, namespace: Schema.optional(Schema.String), result: ToolResultValue, output: Schema.optional(ToolOutput), providerExecuted: Schema.optional(Schema.Boolean), providerMetadata: Schema.optional(ProviderMetadata), }).annotate({ identifier: "LLM.Event.ToolResult" }) export type ToolResult = Schema.Schema.Type export const FinishReasonDetails = Schema.Struct({ normalized: FinishReason, raw: Schema.optional(Schema.String), /** The provider's policy area for a content-filter finish, such as `cyber`. */ category: Schema.optional(Schema.String), /** The provider's human-readable reason for a content-filter finish. */ explanation: Schema.optional(Schema.String), }).annotate({ identifier: "LLM.FinishReasonDetails" }) export type FinishReasonDetails = Schema.Schema.Type export const StepFinish = Schema.Struct({ type: Schema.tag("step-finish"), index: Schema.Number, reason: FinishReasonDetails, usage: Schema.optional(Usage), providerMetadata: Schema.optional(ProviderMetadata), }).annotate({ identifier: "LLM.Event.StepFinish" }) export type StepFinish = Schema.Schema.Type export const Finish = Schema.Struct({ type: Schema.tag("finish"), reason: FinishReasonDetails, usage: Schema.optional(Usage), /** The final assistant message, set by `ai.stream` and `ai.loop`. */ message: Schema.optional(AssistantMessage), providerMetadata: Schema.optional(ProviderMetadata), }).annotate({ identifier: "LLM.Event.Finish" }) export type Finish = Schema.Schema.Type /** A generated media asset (image, audio, …) emitted by the model as first-class output rather than a tool result. */ export const MediaEvent = Schema.Struct({ type: Schema.tag("media"), media: Media.AssetSchema, providerMetadata: Schema.optional(ProviderMetadata), }).annotate({ identifier: "LLM.Event.Media" }) export type MediaEvent = Schema.Schema.Type /** One provider frame as received, emitted before the events parsed from it when the request sets `includeRaw`. */ export const RawEvent = Schema.Struct({ type: Schema.tag("raw"), data: Schema.Unknown, }).annotate({ identifier: "LLM.Event.Raw" }) export type RawEvent = Schema.Schema.Type const llmEventTagged = Schema.Union([ CompactionPart, StepStart, TextStart, TextDelta, TextEnd, ReasoningStart, ReasoningDelta, ReasoningEnd, ToolInputStart, ToolInputDelta, ToolInputEnd, ToolInputError, ToolCall, ToolResult, MediaEvent, StepFinish, Finish, RawEvent, ]).pipe(Schema.toTaggedUnion("type")) type WithID = Omit & { readonly id: ID | string } type WithUsage = Omit & { readonly usage?: UsageInput } const contentBlockID = (value: ContentBlockID | string) => ContentBlockID.make(value) const toolCallID = (value: ToolCallID | string) => ToolCallID.make(value) /** * camelCase aliases for `LLMEvent.guards` (provided by `Schema.toTaggedUnion`). * Lets consumers write `events.filter(LLMEvent.is.toolCall)` instead of * `events.filter(LLMEvent.guards["tool-call"])`. */ export const LLMEvent = Object.assign(llmEventTagged, { compaction: CompactionPart.make, stepStart: StepStart.make, textStart: (input: WithID) => TextStart.make({ ...input, id: contentBlockID(input.id) }), textDelta: (input: WithID) => TextDelta.make({ ...input, id: contentBlockID(input.id) }), textEnd: (input: WithID) => TextEnd.make({ ...input, id: contentBlockID(input.id) }), reasoningStart: (input: WithID) => ReasoningStart.make({ ...input, id: contentBlockID(input.id) }), reasoningDelta: (input: WithID) => ReasoningDelta.make({ ...input, id: contentBlockID(input.id) }), reasoningEnd: (input: WithID) => ReasoningEnd.make({ ...input, id: contentBlockID(input.id) }), toolInputStart: (input: WithID) => ToolInputStart.make({ ...input, id: toolCallID(input.id) }), toolInputDelta: (input: WithID) => ToolInputDelta.make({ ...input, id: toolCallID(input.id) }), toolInputEnd: (input: WithID) => ToolInputEnd.make({ ...input, id: toolCallID(input.id) }), toolInputError: (input: WithID) => ToolInputError.make({ ...input, id: toolCallID(input.id) }), toolCall: (input: WithID) => ToolCall.make({ ...input, id: toolCallID(input.id) }), toolResult: (input: WithID) => ToolResult.make({ ...input, id: toolCallID(input.id), output: input.output === undefined ? undefined : ToolOutput.make(input.output.structured, input.output.content), }), media: MediaEvent.make, stepFinish: (input: WithUsage) => StepFinish.make({ ...input, usage: input.usage === undefined ? undefined : Usage.from(input.usage), }), finish: (input: WithUsage) => Finish.make({ ...input, usage: input.usage === undefined ? undefined : Usage.from(input.usage), }), raw: RawEvent.make, is: { compaction: llmEventTagged.guards.compaction, stepStart: llmEventTagged.guards["step-start"], textStart: llmEventTagged.guards["text-start"], textDelta: llmEventTagged.guards["text-delta"], textEnd: llmEventTagged.guards["text-end"], reasoningStart: llmEventTagged.guards["reasoning-start"], reasoningDelta: llmEventTagged.guards["reasoning-delta"], reasoningEnd: llmEventTagged.guards["reasoning-end"], toolInputStart: llmEventTagged.guards["tool-input-start"], toolInputDelta: llmEventTagged.guards["tool-input-delta"], toolInputEnd: llmEventTagged.guards["tool-input-end"], toolInputError: llmEventTagged.guards["tool-input-error"], toolCall: llmEventTagged.guards["tool-call"], toolResult: llmEventTagged.guards["tool-result"], media: llmEventTagged.guards.media, stepFinish: llmEventTagged.guards["step-finish"], finish: llmEventTagged.guards.finish, raw: llmEventTagged.guards.raw, }, }) export type LLMEvent = Schema.Schema.Type /** Joins deltas per fragment, letting an authoritative end value replace that fragment's accumulated deltas. */ const joinFragments = ( events: ReadonlyArray, isDelta: (event: LLMEvent) => event is LLMEvent & { id: string; text: string }, isEnd: (event: LLMEvent) => event is LLMEvent & { id: string; text?: string }, ) => { const order: string[] = [] const parts = new Map() for (const event of events) { if (isDelta(event)) { if (!parts.has(event.id)) order.push(event.id) parts.set(event.id, (parts.get(event.id) ?? "") + event.text) } if (isEnd(event) && event.text !== undefined) { if (!parts.has(event.id)) order.push(event.id) parts.set(event.id, event.text) } } return order.map((id) => parts.get(id)).join("") } const responseText = (events: ReadonlyArray) => joinFragments(events, LLMEvent.is.textDelta, LLMEvent.is.textEnd) const responseReasoning = (events: ReadonlyArray) => joinFragments(events, LLMEvent.is.reasoningDelta, LLMEvent.is.reasoningEnd) const responseUsage = (events: ReadonlyArray) => events.reduce( (usage, event) => ("usage" in event && event.usage !== undefined ? event.usage : usage), undefined, ) interface ContentAssembly { readonly contentIndex: number readonly text: string readonly providerMetadata?: ProviderMetadata } interface ToolInputAssembly { readonly name: string readonly namespace?: string readonly text: string readonly providerMetadata?: ProviderMetadata } interface ResponseState { readonly events: LLMEvent[] readonly message: AssistantMessage readonly usage?: Usage readonly finishReason?: FinishReasonDetails readonly textParts: Readonly> readonly reasoningParts: Readonly> readonly toolInputs: Readonly> } const emptyResponseState = (): ResponseState => ({ events: [], message: Message.assistant([]), textParts: {}, reasoningParts: {}, toolInputs: {}, }) const appendEvent = (state: ResponseState, event: LLMEvent): ResponseState => { state.events.push(event) if (LLMEvent.is.finish(event)) { return { ...state, usage: event.usage ?? state.usage, finishReason: event.reason, } } return { ...state, usage: "usage" in event && event.usage !== undefined ? event.usage : state.usage, } } type ContentKind = "text" | "reasoning" type AssistantPart = AssistantMessage["content"][number] const contentPart = (type: ContentKind, text: string, providerMetadata: ProviderMetadata | undefined): AssistantPart => providerMetadata === undefined ? { type, text } : { type, text, providerMetadata } const contentWith = (state: ResponseState, content: ReadonlyArray): ResponseState => ({ ...state, message: Message.assistant(content), }) const appendContent = (state: ResponseState, part: AssistantPart) => contentWith(state, [...state.message.content, part]) const replaceContent = (state: ResponseState, index: number, part: AssistantPart) => contentWith( state, state.message.content.map((item, itemIndex) => (itemIndex === index ? part : item)), ) const contentParts = (state: ResponseState, type: ContentKind) => type === "text" ? state.textParts : state.reasoningParts const withContentParts = ( state: ResponseState, type: ContentKind, parts: Readonly>, ): ResponseState => (type === "text" ? { ...state, textParts: parts } : { ...state, reasoningParts: parts }) const ensureContent = ( state: ResponseState, type: ContentKind, id: string, providerMetadata?: ProviderMetadata, ): ResponseState => { const parts = contentParts(state, type) if (parts[id]) return state return withContentParts(appendContent(state, contentPart(type, "", providerMetadata)), type, { ...parts, [id]: { contentIndex: state.message.content.length, text: "", providerMetadata }, }) } const reduceContentDelta = ( state: ResponseState, type: ContentKind, event: TextDelta | ReasoningDelta, ): ResponseState => { const started = ensureContent(state, type, event.id, event.providerMetadata) const parts = contentParts(started, type) const current = parts[event.id] if (!current) return started const text = current.text + event.text const providerMetadata = event.providerMetadata ?? current.providerMetadata return withContentParts( replaceContent(started, current.contentIndex, contentPart(type, text, providerMetadata)), type, { ...parts, [event.id]: { ...current, text, providerMetadata }, }, ) } const reduceContentEnd = (state: ResponseState, type: ContentKind, event: TextEnd | ReasoningEnd): ResponseState => { const parts = contentParts(state, type) const current = parts[event.id] if (!current) return state const text = event.text ?? current.text const providerMetadata = event.providerMetadata ?? current.providerMetadata return withContentParts( replaceContent(state, current.contentIndex, contentPart(type, text, providerMetadata)), type, { ...parts, [event.id]: { ...current, text, providerMetadata }, }, ) } const reduceToolInputStart = (state: ResponseState, event: ToolInputStart): ResponseState => ({ ...state, toolInputs: { ...state.toolInputs, [event.id]: { name: event.name, namespace: event.namespace, text: "", providerMetadata: event.providerMetadata, }, }, }) const reduceToolInputDelta = (state: ResponseState, event: ToolInputDelta): ResponseState => { const current = state.toolInputs[event.id] ?? { name: event.name, namespace: event.namespace, text: "" } return { ...state, toolInputs: { ...state.toolInputs, [event.id]: { ...current, text: current.text + event.text } }, } } const reduceToolInputEnd = (state: ResponseState, event: ToolInputEnd): ResponseState => { const current = state.toolInputs[event.id] ?? { name: event.name, namespace: event.namespace, text: "" } return { ...state, toolInputs: { ...state.toolInputs, [event.id]: { ...current, name: event.name, namespace: event.namespace, providerMetadata: event.providerMetadata ?? current.providerMetadata, }, }, } } const toolCallContent = (event: ToolCall): AssistantPart => ToolCallPart.make({ id: event.id, name: event.name, namespace: event.namespace, input: event.input, ...(event.providerExecuted === undefined ? {} : { providerExecuted: event.providerExecuted }), ...(event.providerMetadata === undefined ? {} : { providerMetadata: event.providerMetadata }), }) const toolResultContent = (event: ToolResult): AssistantPart => ToolResultPart.make({ id: event.id, name: event.name, namespace: event.namespace, result: event.result, ...(event.providerExecuted === undefined ? {} : { providerExecuted: event.providerExecuted }), ...(event.providerMetadata === undefined ? {} : { providerMetadata: event.providerMetadata }), }) const reduceToolCall = (state: ResponseState, event: ToolCall): ResponseState => { const { [event.id]: _finished, ...toolInputs } = state.toolInputs return { ...appendContent(state, toolCallContent(event)), toolInputs } } const reduceResponseState = (state: ResponseState, event: LLMEvent): ResponseState => { if (event.type === "raw") return state const next = appendEvent(state, event) switch (event.type) { case "compaction": return appendContent(next, event) case "text-start": return ensureContent(next, "text", event.id, event.providerMetadata) case "text-delta": return reduceContentDelta(next, "text", event) case "text-end": return reduceContentEnd(next, "text", event) case "reasoning-start": return ensureContent(next, "reasoning", event.id, event.providerMetadata) case "reasoning-delta": return reduceContentDelta(next, "reasoning", event) case "reasoning-end": return reduceContentEnd(next, "reasoning", event) case "tool-input-start": return reduceToolInputStart(next, event) case "tool-input-delta": return reduceToolInputDelta(next, event) case "tool-input-end": return reduceToolInputEnd(next, event) case "tool-input-error": { const { [event.id]: _finished, ...toolInputs } = next.toolInputs return { ...next, toolInputs } } case "tool-call": return reduceToolCall(next, event) case "tool-result": return appendContent(next, toolResultContent(event)) case "media": return appendContent( next, event.providerMetadata === undefined ? { type: "media", media: event.media } : { type: "media", media: event.media, providerMetadata: event.providerMetadata }, ) default: return next } } export class LLMResponse extends Schema.Class("LLM.Response")({ message: AssistantMessage, events: Schema.Array(LLMEvent), usage: Schema.optional(Usage), finishReason: FinishReasonDetails, }) { /** Concatenated assistant text; each fragment's `text-end` value replaces its accumulated deltas when present. */ get text() { return responseText(this.events) } /** Concatenated reasoning text; each fragment's `reasoning-end` value replaces its accumulated deltas when present. */ get reasoning() { return responseReasoning(this.events) } /** Completed tool calls emitted by the provider. */ get toolCalls() { return this.events.filter(LLMEvent.is.toolCall) } } /** * Internal fold that assembles one provider attempt. Not exported from the package. * A state has a single owner: `reduce` appends to the events buffer in place, so earlier states must not be reused. */ export namespace ResponseFold { export type State = ResponseState /** Initial state with a fresh events buffer. */ export const empty = emptyResponseState /** Fold one provider-neutral event into the state. */ export const reduce = reduceResponseState /** Return a completed response only after the terminal finish. The response gets its own copy of the events. */ export const complete = (state: State): LLMResponse | undefined => state.finishReason === undefined ? undefined : new LLMResponse({ message: state.message, events: [...state.events], usage: state.usage, finishReason: state.finishReason, }) /** Output that arrived before a failure, or `undefined` if only `step-start` did; an unfinished response reports `error`. */ export const partial = (state: State) => state.events.every(LLMEvent.is.stepStart) ? undefined : complete({ ...state, finishReason: state.finishReason ?? { normalized: "error" } }) } export namespace LLMResponse { export type Output = LLMResponse | { readonly events: ReadonlyArray; readonly usage?: Usage } /** Assemble a response from a collected event list, or `undefined` if it has no terminal finish. */ export const fromEvents = (events: ReadonlyArray) => ResponseFold.complete(events.reduce(ResponseFold.reduce, ResponseFold.empty())) /** Concatenate assistant text from a response or collected event list. */ export const text = (response: Output) => responseText(response.events) /** Return response usage, falling back to the latest usage-bearing event. */ export const usage = (response: Output) => response.usage ?? responseUsage(response.events) /** Return completed tool calls from a response or collected event list. */ export const toolCalls = (response: Output) => response.events.filter(LLMEvent.is.toolCall) /** Concatenate reasoning text from a response or collected event list. */ export const reasoning = (response: Output) => responseReasoning(response.events) }