import { R as RetryConfig, a as TimeoutConfig, b as RateLimitConfig, c as ToolCall, P as PerformanceMetrics } from './common.d-iR60eBef.js'; /** * Type utilities for AI Kit * Provides branded types, type guards, and utility types for type-safe development */ /** * Creates a branded type to prevent accidental mixing of similar primitive types */ declare const brand: unique symbol; type Brand = T & { readonly [brand]: TBrand; }; /** * User identifier - branded string to prevent mixing with other IDs */ type UserId = Brand; /** * Session identifier - branded string for session management */ type SessionId = Brand; /** * Message identifier - branded string for message tracking */ type MessageId = Brand; /** * Agent identifier - branded string for agent identification */ type AgentId = Brand; /** * Model identifier - branded string for AI model identification */ type ModelId = Brand; /** * Tool identifier - branded string for tool identification */ type ToolId = Brand; /** * Conversation identifier - branded string for conversation tracking */ type ConversationId = Brand; /** * Timestamp in milliseconds - branded number for time values */ type Timestamp = Brand; /** * Helper function to create branded IDs */ declare function createBrandedId(value: string, _brand?: T): Brand; /** * Makes all properties in T deeply partial */ type DeepPartial = T extends object ? { [P in keyof T]?: DeepPartial; } : T; /** * Makes all properties in T deeply readonly */ type DeepReadonly = T extends object ? { readonly [P in keyof T]: DeepReadonly; } : T; /** * Makes all properties in T deeply required */ type DeepRequired = T extends object ? { [P in keyof T]-?: DeepRequired; } : T; /** * Requires at least one property from Keys to be present */ type RequireAtLeastOne = Pick> & { [K in Keys]-?: Required> & Partial>>; }[Keys]; /** * Requires exactly one property from Keys to be present */ type RequireExactlyOne = Pick> & { [K in Keys]: Required> & Partial, never>>; }[Keys]; /** * Makes specified properties optional */ type PartialBy = Omit & Partial>; /** * Makes specified properties required */ type RequiredBy = Omit & Required>; /** * Extracts keys of T where the value is of type V */ type KeysOfType = { [K in keyof T]: T[K] extends V ? K : never; }[keyof T]; /** * Makes properties K mutable (removes readonly) */ type Mutable = Omit & { -readonly [P in K]: T[P]; }; /** * Creates a union of all possible paths through an object */ type Paths = [D] extends [never] ? never : T extends object ? { [K in keyof T]-?: K extends string | number ? `${K}` | (Paths extends infer R ? `${K}.${R & string}` : never) : never; }[keyof T] : never; type Prev = [never, 0, 1, 2, 3, ...0[]]; /** * Gets the value type at a given path in an object */ type PathValue = P extends `${infer K}.${infer Rest}` ? K extends keyof T ? PathValue : never : P extends keyof T ? T[P] : never; /** * Converts union type to intersection type */ type UnionToIntersection = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never; /** * Gets the last element of a union type */ type LastOf = UnionToIntersection T : never> extends () => infer R ? R : never; /** * Converts a union to a tuple */ type UnionToTuple> = [T] extends [never] ? [] : [...UnionToTuple>, L]; /** * Non-nullable version of T */ type NonNullable = T extends null | undefined ? never : T; /** * Nullable version of T */ type Nullable = T | null; /** * Maybe version of T (nullable or undefined) */ type Maybe = T | null | undefined; /** * Awaited type - extracts the type a Promise resolves to */ type Awaited = T extends PromiseLike ? Awaited : T; /** * JSON-serializable types */ type JsonPrimitive = string | number | boolean | null; type JsonObject = { [key: string]: JsonValue; }; type JsonArray = JsonValue[]; type JsonValue = JsonPrimitive | JsonObject | JsonArray; /** * Ensures a type is JSON-serializable */ type Jsonable = T extends JsonValue ? T : T extends { toJSON(): infer R; } ? R : never; /** * Extracts all string literal types from a type */ type StringLiteral = T extends string ? string extends T ? never : T : never; /** * Extracts all number literal types from a type */ type NumberLiteral = T extends number ? number extends T ? never : T : never; /** * Makes a type writable (removes readonly at all levels) */ type Writable = { -readonly [P in keyof T]: T[P]; }; /** * Ensures a function type */ type Fn = (...args: Args) => R; /** * Ensures an async function type */ type AsyncFn = (...args: Args) => Promise; /** * Extracts the parameters of a function type */ type FunctionParams = T extends (...args: infer P) => unknown ? P : never; /** * Extracts the return type of a function */ type FunctionReturn = T extends (...args: unknown[]) => infer R ? R : never; /** * Creates a type with all properties set to undefined */ type AllUndefined = { [P in keyof T]: undefined; }; /** * Flattens nested Pick types */ type FlatPick = { [P in K]: T[P]; }; /** * Creates a strict version of Omit that ensures keys exist */ type StrictOmit = Pick>; /** * Creates a strict version of Pick that ensures keys exist */ type StrictPick = Pick; /** * Type guard to check if value is defined (not null or undefined) */ declare function isDefined(value: T | null | undefined): value is T; /** * Type guard to check if value is null or undefined */ declare function isNullish(value: unknown): value is null | undefined; /** * Type guard to check if value is a string */ declare function isString(value: unknown): value is string; /** * Type guard to check if value is a number */ declare function isNumber(value: unknown): value is number; /** * Type guard to check if value is a boolean */ declare function isBoolean(value: unknown): value is boolean; /** * Type guard to check if value is an object (excluding null and arrays) */ declare function isObject(value: unknown): value is Record; /** * Type guard to check if value is an array */ declare function isArray(value: unknown): value is T[]; /** * Type guard to check if value is a function */ declare function isFunction(value: unknown): value is Fn; /** * Type guard to check if value is a Promise */ declare function isPromise(value: unknown): value is Promise; /** * Type guard to check if value is an Error */ declare function isError(value: unknown): value is Error; /** * Type guard to check if value has a specific property */ declare function hasProperty(value: unknown, property: K): value is Record; /** * Type guard to check if value is a non-empty string */ declare function isNonEmptyString(value: unknown): value is string; /** * Type guard to check if value is a non-empty array */ declare function isNonEmptyArray(value: unknown): value is [T, ...T[]]; /** * Type guard to check if value is JSON-serializable */ declare function isJsonValue(value: unknown): value is JsonValue; /** * Type predicate to filter null/undefined values from arrays */ declare function notNullish(value: T | null | undefined): value is T; /** * Asserts that a condition is true, throwing an error otherwise */ declare function assert(condition: unknown, message?: string): asserts condition; /** * Asserts that a value is defined (not null or undefined) */ declare function assertDefined(value: T | null | undefined, message?: string): asserts value is T; /** * Asserts that a value is a string */ declare function assertString(value: unknown, message?: string): asserts value is string; /** * Asserts that a value is a number */ declare function assertNumber(value: unknown, message?: string): asserts value is number; /** * Asserts that a value is an object */ declare function assertObject(value: unknown, message?: string): asserts value is Record; /** * Asserts that a value is never reached (useful for exhaustive checks) */ declare function assertNever(value: never, message?: string): never; /** * Creates a nominal type that is distinct from its base type */ type Nominal = T & { readonly __nominal: Name; }; /** * Email address - nominal string type */ type Email = Nominal; /** * URL - nominal string type */ type Url = Nominal; /** * ISO 8601 date string - nominal string type */ type ISODateString = Nominal; /** * UUID - nominal string type */ type UUID = Nominal; /** * Positive integer - nominal number type */ type PositiveInt = Nominal; /** * Non-negative integer - nominal number type */ type NonNegativeInt = Nominal; /** * Helper to create discriminated union types */ type DiscriminatedUnion> = T; /** * Extracts a specific variant from a discriminated union */ type ExtractVariant = Extract>; /** * Gets all possible values of a discriminator field */ type DiscriminatorValues = Union extends Record ? V : never; /** * Success result type */ interface Success { readonly success: true; readonly data: T; } /** * Failure result type */ interface Failure { readonly success: false; readonly error: E; } /** * Result type for operations that can fail */ type Result = Success | Failure; /** * Creates a success result */ declare function success(data: T): Success; /** * Creates a failure result */ declare function failure(error: E): Failure; /** * Type guard for success results */ declare function isSuccess(result: Result): result is Success; /** * Type guard for failure results */ declare function isFailure(result: Result): result is Failure; /** * Some value type */ interface Some { readonly kind: 'some'; readonly value: T; } /** * None value type */ interface None { readonly kind: 'none'; } /** * Option type for values that may not exist */ type Option = Some | None; /** * Creates a Some option */ declare function some(value: T): Some; /** * Creates a None option */ declare function none(): None; /** * Type guard for Some options */ declare function isSome(option: Option): option is Some; /** * Type guard for None options */ declare function isNone(option: Option): option is None; /** * Converts a nullable value to an Option */ declare function fromNullable(value: T | null | undefined): Option; /** * Converts an Option to a nullable value */ declare function toNullable(option: Option): T | null; /** * Streaming type definitions for AI Kit * Comprehensive types for streaming AI responses */ // ============================================================================ // Core Streaming Types // ============================================================================ /** * Message role in a conversation */ type MessageRole = 'user' | 'assistant' | 'system' | 'function' | 'tool'; /** * Message content type */ type MessageContentType = 'text' | 'image' | 'audio' | 'video' | 'file'; /** * Message content */ interface MessageContent { readonly type: MessageContentType; readonly data: string; readonly mimeType?: string; readonly metadata?: Record; } /** * Text message content */ interface TextContent extends MessageContent { readonly type: 'text'; readonly data: string; } /** * Image message content */ interface ImageContent extends MessageContent { readonly type: 'image'; readonly data: string; // Base64 or URL readonly width?: number; readonly height?: number; readonly mimeType: string; } /** * Core message interface */ interface Message { readonly id: MessageId; readonly role: MessageRole; readonly content: string | MessageContent | MessageContent[]; readonly timestamp: Timestamp; readonly sessionId?: SessionId; readonly metadata?: MessageMetadata; readonly name?: string; // For function/tool messages readonly functionCall?: FunctionCall; readonly toolCalls?: ToolCall[]; } /** * Message metadata */ interface MessageMetadata { readonly edited?: boolean; readonly deleted?: boolean; readonly parentId?: MessageId; readonly threadId?: string; readonly tags?: readonly string[]; readonly annotations?: readonly Annotation[]; readonly [key: string]: JsonValue | undefined; } /** * Message annotation (for citations, highlights, etc.) */ interface Annotation { readonly type: string; readonly startIndex: number; readonly endIndex: number; readonly data?: JsonValue; } /** * Function call in a message */ interface FunctionCall { readonly name: string; readonly arguments: string; // JSON string } // ============================================================================ // Usage and Cost Tracking // ============================================================================ /** * Token usage information */ interface Usage { readonly promptTokens: number; readonly completionTokens: number; readonly totalTokens: number; readonly cacheReadTokens?: number; readonly cacheWriteTokens?: number; } /** * Cost information */ interface Cost { readonly amount: number; readonly currency: string; readonly breakdown?: CostBreakdown; } /** * Detailed cost breakdown */ interface CostBreakdown { readonly promptCost: number; readonly completionCost: number; readonly cacheCost?: number; readonly totalCost: number; } /** * Complete usage statistics */ interface UsageStats extends Usage { readonly estimatedCost?: Cost; readonly performance?: PerformanceMetrics; readonly model?: string; readonly cacheHit?: boolean; readonly provider?: string; } // ============================================================================ // Stream Events // ============================================================================ /** * Stream event types */ type StreamEventType = | 'start' | 'token' | 'content' | 'function_call' | 'tool_call' | 'done' | 'error' | 'metadata' | 'usage' | 'abort'; /** * Base stream event */ interface BaseStreamEvent { readonly type: T; readonly timestamp: Timestamp; readonly sessionId?: SessionId; } /** * Stream start event */ interface StreamStartEvent extends BaseStreamEvent<'start'> { readonly messageId: MessageId; readonly model?: string; } /** * Token event (individual token streamed) */ interface TokenEvent extends BaseStreamEvent<'token'> { readonly token: string; readonly messageId: MessageId; } /** * Content event (chunk of content) */ interface ContentEvent extends BaseStreamEvent<'content'> { readonly content: string; readonly messageId: MessageId; readonly delta?: string; // For incremental updates } /** * Function call event */ interface FunctionCallEvent extends BaseStreamEvent<'function_call'> { readonly functionCall: FunctionCall; readonly messageId: MessageId; } /** * Tool call event */ interface ToolCallEvent extends BaseStreamEvent<'tool_call'> { readonly toolCall: ToolCall; readonly messageId: MessageId; } /** * Stream done event */ interface StreamDoneEvent extends BaseStreamEvent<'done'> { readonly messageId: MessageId; readonly message: Message; readonly usage?: UsageStats; } /** * Stream error event */ interface StreamErrorEvent extends BaseStreamEvent<'error'> { readonly error: Error; readonly recoverable: boolean; readonly retryAfter?: number; // milliseconds } /** * Stream metadata event */ interface StreamMetadataEvent extends BaseStreamEvent<'metadata'> { readonly metadata: Record; } /** * Stream usage event */ interface StreamUsageEvent extends BaseStreamEvent<'usage'> { readonly usage: UsageStats; } /** * Stream abort event */ interface StreamAbortEvent extends BaseStreamEvent<'abort'> { readonly reason?: string; } /** * Union of all stream events */ type StreamEvent = | StreamStartEvent | TokenEvent | ContentEvent | FunctionCallEvent | ToolCallEvent | StreamDoneEvent | StreamErrorEvent | StreamMetadataEvent | StreamUsageEvent | StreamAbortEvent; /** * Cache configuration */ interface CacheConfig { readonly enabled: boolean; readonly ttl?: number; // seconds readonly storage?: 'memory' | 'redis' | 'custom'; readonly keyPrefix?: string; readonly maxSize?: number; // max items in cache } /** * Stream transport type */ type StreamTransport = 'sse' | 'websocket' | 'http' | 'grpc'; /** * Stream options */ interface StreamOptions { readonly transport?: StreamTransport; readonly reconnect?: boolean; readonly maxReconnectAttempts?: number; readonly reconnectDelay?: number; // milliseconds readonly heartbeatInterval?: number; // milliseconds readonly bufferSize?: number; } /** * Stream configuration */ interface StreamConfig { readonly endpoint: string; readonly model?: string; readonly systemPrompt?: string; readonly temperature?: number; readonly maxTokens?: number; readonly topP?: number; readonly topK?: number; readonly frequencyPenalty?: number; readonly presencePenalty?: number; readonly stop?: readonly string[]; readonly options?: StreamOptions; readonly retry?: RetryConfig; readonly cache?: boolean | CacheConfig; readonly timeout?: number | TimeoutConfig; readonly rateLimit?: RateLimitConfig; readonly headers?: Record; readonly metadata?: Record; } // ============================================================================ // Stream Callbacks // ============================================================================ /** * Stream event handlers */ interface StreamCallbacks { readonly onStart?: (event: StreamStartEvent) => void | Promise; readonly onToken?: (token: string) => void | Promise; readonly onContent?: (content: string) => void | Promise; readonly onFunctionCall?: (call: FunctionCall) => void | Promise; readonly onToolCall?: (call: ToolCall) => void | Promise; readonly onDone?: (event: StreamDoneEvent) => void | Promise; readonly onError?: (error: Error) => void | Promise; readonly onMetadata?: (metadata: Record) => void | Promise; readonly onUsage?: (usage: UsageStats) => void | Promise; readonly onAbort?: (reason?: string) => void | Promise; readonly onEvent?: (event: StreamEvent) => void | Promise; } // ============================================================================ // Stream Result // ============================================================================ /** * Stream state */ type StreamState = | 'idle' | 'connecting' | 'streaming' | 'paused' | 'done' | 'error' | 'aborted'; /** * Stream result interface */ interface StreamResult { readonly messages: readonly Message[]; readonly state: StreamState; readonly isStreaming: boolean; readonly error: Error | null; readonly usage: UsageStats; // Methods send(content: string): Promise; sendMessage(message: Omit): Promise; reset(): void; retry(): Promise; pause(): void; resume(): void; abort(reason?: string): void; getHistory(): readonly Message[]; } // ============================================================================ // Stream Controller // ============================================================================ /** * Stream controller for managing stream lifecycle */ interface StreamController { readonly signal: AbortSignal; readonly state: StreamState; abort(reason?: string): void; pause(): void; resume(): void; retry(): Promise; isAborted(): boolean; isPaused(): boolean; } // ============================================================================ // Server-Sent Events (SSE) // ============================================================================ /** * SSE message */ interface SSEMessage { readonly id?: string; readonly event?: string; readonly data: string; readonly retry?: number; } /** * SSE stream configuration */ interface SSEConfig extends StreamOptions { readonly transport: 'sse'; readonly withCredentials?: boolean; readonly eventSourceInitDict?: EventSourceInit; } // ============================================================================ // WebSocket // ============================================================================ /** * WebSocket message */ interface WebSocketMessage { readonly type: string; readonly payload: JsonValue; readonly id?: string; } /** * WebSocket stream configuration */ interface WebSocketConfig extends StreamOptions { readonly transport: 'websocket'; readonly protocols?: string | readonly string[]; readonly binaryType?: 'blob' | 'arraybuffer'; } // ============================================================================ // Streaming Functions // ============================================================================ /** * Stream function configuration */ interface StreamFunction { readonly name: string; readonly description?: string; readonly parameters: JsonValue; // JSON Schema readonly handler: (args: JsonValue) => Promise | JsonValue; } /** * Stream tool configuration */ interface StreamTool { readonly type: 'function'; readonly function: Omit; } // ============================================================================ // Advanced Stream Types // ============================================================================ /** * Multimodal stream configuration */ interface MultimodalStreamConfig extends StreamConfig { readonly supportedContentTypes?: readonly MessageContentType[]; readonly maxImageSize?: number; // bytes readonly maxAudioDuration?: number; // seconds } /** * Batch stream configuration for multiple concurrent streams */ interface BatchStreamConfig { readonly streams: readonly StreamConfig[]; readonly concurrent?: number; readonly failFast?: boolean; readonly aggregateResults?: boolean; } /** * Stream middleware function */ type StreamMiddleware = ( event: StreamEvent, next: (event: StreamEvent) => void | Promise ) => void | Promise; /** * Stream with middleware support */ interface StreamWithMiddleware extends StreamResult { use(middleware: StreamMiddleware): void; removeMiddleware(middleware: StreamMiddleware): void; } export { isNullish as $, type AgentId as A, type Brand as B, type ConversationId as C, type DeepPartial as D, type Jsonable as E, type StringLiteral as F, type NumberLiteral as G, type Fn as H, type AsyncFn as I, type JsonValue as J, type KeysOfType as K, type LastOf as L, type Message as M, type NonNullable as N, type FunctionParams as O, type PartialBy as P, type FunctionReturn as Q, type Result as R, type SessionId as S, type Timestamp as T, type UsageStats as U, type AllUndefined as V, type Writable as W, type FlatPick as X, type StrictOmit as Y, type StrictPick as Z, isDefined as _, type MessageId as a, type StreamMetadataEvent as a$, isString as a0, isNumber as a1, isBoolean as a2, isObject as a3, isArray as a4, isFunction as a5, isPromise as a6, isError as a7, hasProperty as a8, isNonEmptyString as a9, type None as aA, type Option as aB, some as aC, none as aD, isSome as aE, isNone as aF, fromNullable as aG, toNullable as aH, type MessageRole as aI, type MessageContentType as aJ, type MessageContent as aK, type TextContent as aL, type ImageContent as aM, type MessageMetadata as aN, type Annotation as aO, type FunctionCall as aP, type Cost as aQ, type CostBreakdown as aR, type StreamEventType as aS, type BaseStreamEvent as aT, type StreamStartEvent as aU, type TokenEvent as aV, type ContentEvent as aW, type FunctionCallEvent as aX, type ToolCallEvent as aY, type StreamDoneEvent as aZ, type StreamErrorEvent as a_, isNonEmptyArray as aa, isJsonValue as ab, notNullish as ac, assert as ad, assertDefined as ae, assertString as af, assertNumber as ag, assertObject as ah, assertNever as ai, type Nominal as aj, type Email as ak, type Url as al, type ISODateString as am, type UUID as an, type PositiveInt as ao, type NonNegativeInt as ap, type DiscriminatedUnion as aq, type ExtractVariant as ar, type DiscriminatorValues as as, type Success as at, type Failure as au, success as av, failure as aw, isSuccess as ax, isFailure as ay, type Some as az, type StreamConfig as b, type StreamUsageEvent as b0, type StreamAbortEvent as b1, type StreamEvent as b2, type CacheConfig as b3, type StreamTransport as b4, type StreamState as b5, type StreamController as b6, type SSEMessage as b7, type SSEConfig as b8, type WebSocketMessage as b9, type WebSocketConfig as ba, type StreamFunction as bb, type StreamTool as bc, type MultimodalStreamConfig as bd, type BatchStreamConfig as be, type StreamMiddleware as bf, type StreamWithMiddleware as bg, type StreamCallbacks as c, type Usage as d, type StreamOptions as e, type ToolId as f, type ModelId as g, type StreamResult as h, type UserId as i, createBrandedId as j, type DeepReadonly as k, type DeepRequired as l, type RequireAtLeastOne as m, type RequireExactlyOne as n, type RequiredBy as o, type Mutable as p, type Paths as q, type PathValue as r, type UnionToIntersection as s, type UnionToTuple as t, type Nullable as u, type Maybe as v, type Awaited as w, type JsonPrimitive as x, type JsonObject as y, type JsonArray as z };