/** * Streaming utilities for filtering and extracting streamable content. * * This module provides implementations of {@link IStreamExtractor}: * - PassthroughExtractor - Simple passthrough (no filtering) * - StructuredFieldStreamExtractor - Extract top-level structured fields safely * * For the interface definition, see types/streaming.ts. * Implementations can use these or create their own extractors. * * Reasoning-tag filtering compares fixed-length prefixes and accumulates * visible runs without copying the remaining stream suffix at every index. */ import type { StreamingContext } from "../streaming-context.js"; import type { StreamChunkCallback } from "../types/components.js"; import type { ResponseSkeleton, StructuredStreamGate } from "../types/model.js"; import type { SchemaRow, StreamEvent } from "../types/state.js"; import type { IStreamExtractor, IStreamingRetryState, StructuredFieldEventCallbacks } from "../types/streaming.js"; /** Error codes for streaming operations */ export type StreamErrorCode = "CHUNK_TOO_LARGE" | "BUFFER_OVERFLOW" | "PARSE_ERROR" | "TIMEOUT" | "ABORTED"; /** * Standardized error class for streaming operations. * Provides structured error codes for easier handling. */ export declare class StreamError extends Error { readonly code: StreamErrorCode; readonly details?: Record; constructor(code: StreamErrorCode, message: string, details?: Record); /** Check if an error is a StreamError */ static isStreamError(error: unknown): error is StreamError; } /** * Streams all content as-is without any filtering. * Use when LLM output is already in the desired format (e.g., plain text responses). */ export declare class PassthroughExtractor implements IStreamExtractor { get done(): boolean; push(chunk: string): string; flush(): string; reset(): void; } /** Passes through streaming text while allowing the owning structured extractor to mark completion for retry and fallback handling. */ export declare class MarkableExtractor implements IStreamExtractor { private _done; get done(): boolean; push(chunk: string): string; flush(): string; reset(): void; /** * Mark the extractor as complete. * WHY: Called by the outer code when the underlying operation completes * successfully. This allows isComplete() to return true for retry/fallback logic. */ markComplete(): void; } /** * Extractor state machine for validation-aware streaming. */ export type ExtractorState = "streaming" | "validating" | "retrying" | "complete" | "failed"; /** * Per-field state tracking for progressive validation. */ export type FieldState = "pending" | "partial" | "complete" | "invalid"; /** * Configuration for StructuredFieldStreamExtractor. */ export interface StructuredFieldStreamExtractorConfig extends StructuredFieldEventCallbacks { /** Validation level (0-3). Level 2+ buffers until flush. */ level: 0 | 1 | 2 | 3; /** Schema rows with field definitions */ schema: SchemaRow[]; /** Which top-level structured fields to stream to the consumer */ streamFields: string[]; /** * Callback for streaming chunks. * WHY accumulated: consumers (voice detection, client-side merge) need the * full field text to avoid re-deriving it from deltas. */ onChunk: (chunk: string, field?: string, accumulated?: string, streamRevision?: number) => void; /** Rich event callback for sophisticated consumers */ onEvent?: (event: StreamEvent) => void; /** Abort signal for cancellation */ abortSignal?: AbortSignal; } /** * Diagnosis result for error analysis. */ export interface ValidationDiagnosis { /** Fields that were never started */ missingFields: string[]; /** Fields with wrong validation codes */ invalidFields: string[]; /** Fields that started but didn't complete */ incompleteFields: string[]; } /** * Extracts configured top-level scalar fields from line-oriented text without streaming * surrounding control fields such as thought/actions/providers. * * This intentionally avoids decoding partial structured documents. It processes * complete lines, tracks top-level field boundaries, and only emits values for * fields explicitly listed in `streamFields`. */ export declare class StructuredFieldStreamExtractor implements IStreamExtractor { private readonly config; private lineBuffer; private currentField; private fieldContents; private emittedContent; private validatedFields; private fieldStates; private state; private streamRevision; private readonly streamFieldSet; /** * The top-level field whose value bytes are currently arriving — tracked for * ALL fields (not just streamed ones) so per-field start/done events have a * correct decoded value. `currentField` (above) is the narrower "currently * streamed to onChunk" pointer. */ private currentTrackedField; /** Fields for which `onFieldStart` has already fired (dedupe). */ private startedFields; /** Fields for which `onFieldDone` has already fired (dedupe). */ private doneFields; constructor(config: StructuredFieldStreamExtractorConfig); get done(): boolean; push(chunk: string): string; flush(): string; reset(): void; signalRetry(retryCount: number): { validatedFields: string[]; }; signalError(message: string): void; getValidatedFields(): Map; diagnose(): ValidationDiagnosis; getState(): ExtractorState; private processAvailableLines; private processLine; private completeCurrentField; private emitFieldStart; private closeCurrentTrackedField; private appendFieldContent; private parseInlineValue; private normalizeContinuationLine; private baseStructuredFieldName; private emitFieldContent; private emitEvent; } /** * Extracts selected free-string fields from a streamed JSON response skeleton. * * Stage-1 response-handler output is a compact JSON envelope, not the line-based * `field: value` format handled by `StructuredFieldStreamExtractor`. This * extractor follows the producer's `ResponseSkeleton` spans and emits only * configured user-visible string fields such as `replyText`, so voice/TTS can * start without exposing the control envelope. */ export declare class ResponseSkeletonStreamExtractor implements IStreamExtractor { private readonly config; private buffer; private spanIndex; private activeStringField; private pendingEscape; private fieldContents; private emittedContent; private reasoningFilters; private state; private formatDecided; private passthrough; private passthroughEmitted; private streamRevision; private readonly streamFieldSet; /** `[field, JSON-encoded key]` for each streamed field, in declaration order. */ private readonly streamFieldKeys; private readonly maxKeyPatternLength; /** Everything pushed this attempt, kept only until the gate decides. */ private gateHead; private gateDecided; /** A denied gate or an unstreamable shape: nothing more emits this attempt. */ private held; /** Field whose parts array is being walked, with the walker's position. */ private partsField; private partsState; private partKind; constructor(config: { skeleton: ResponseSkeleton; streamFields: string[]; onChunk: (chunk: string, field?: string, accumulated?: string, streamRevision?: number) => void; onEvent?: (event: StreamEvent) => void; abortSignal?: AbortSignal; unordered?: boolean; /** * Fields whose value may be an ordered `[{kind, value}]` parts array * instead of a string, mapped to the part kinds whose `value` streams. * The first part of any other kind (or any other shape) ends this * attempt's stream; the caller's final result stays authoritative. */ streamParts?: Readonly>; /** * Decides once per attempt, when the first stream field starts, whether * it may stream. Receives the complete top-level envelope fields that * precede it, or `null` for unstructured prose. A denied (or * undecidable) attempt emits nothing; an allowed one streams only * that top-level value. Requires `unordered`. */ gate?: StructuredStreamGate; }); get done(): boolean; push(chunk: string): string; flush(): string; reset(): void; /** Ends this attempt's stream without emitting anything further. */ private hold; /** * Runs the caller's gate once per attempt. `head` is the raw text pushed * before the first stream field's key: a JSON object prefix whose complete * top-level members are decoded for the gate. Anything that is not such a * prefix (a nested key, an array or XML envelope) is undecidable and holds. */ private passesGate; /** * On the first non-whitespace token, decide whether the stream is the * structured envelope this extractor parses (JSON/array/XML — opens with * `{`, `[`, or `<`) or plain prose. A local model that was not grammar- * constrained (e.g. the FFI backend, which cannot apply GBNF) may emit the * reply as raw prose with no envelope; the structured drain would then match * no spans and emit nothing, collapsing the whole reply into a single * trailing chunk. Detecting prose lets us stream it straight through as the * reply. Envelope-shaped output is unaffected, so the control fields * (thought/actions) are never leaked. */ private decideFormat; /** * Stream buffered prose straight through as reply text (passthrough mode). * Until end-of-stream, a trailing high surrogate stays buffered so it can * rejoin its low half from the next push; emitted text is well-formed. */ private drainPassthrough; signalRetry(retryCount: number): { validatedFields: string[]; }; signalError(message: string): void; getValidatedFields(): Map; diagnose(): ValidationDiagnosis; private drain; private drainUnordered; /** * Walks one `[{kind, value}, ...]` parts array, streaming the `value` of * each part whose `kind` (which must come first) is streamable. Returns * false when more input is needed. Any other shape holds the attempt. */ private drainParts; private findNextStreamFieldStart; private consumeLiteral; private consumeOpeningQuote; private processActiveString; private appendAndEmit; private appendVisibleAndEmit; /** * At end-of-stream, emit a high surrogate `appendVisibleAndEmit` held back * whose low half never arrived, as U+FFFD. */ private flushPendingSurrogate; private filterReasoningTags; private flushReasoningFilter; private emitEvent; } /** * Creates a streaming retry state from an extractor. */ export declare function createStreamingRetryState(extractor: IStreamExtractor): IStreamingRetryState & { appendText: (text: string) => void; }; /** * Creates a complete streaming context with retry state management. */ export declare function createStreamingContext(extractor: IStreamExtractor, onStreamChunk: StreamChunkCallback, messageId?: string): StreamingContext & IStreamingRetryState;