@tanstack/ai-client 0.23.2 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,7 +8,7 @@ export type { McpAppBridge, CreateMcpAppBridgeOptions } from './mcp-app-bridge.j
8
8
  export { RealtimeClient } from './realtime-client.js';
9
9
  export { GenerationClient } from './generation-client.js';
10
10
  export { VideoGenerationClient } from './video-generation-client.js';
11
- export type { UIMessage, MessagePart, TextPart, ToolCallPart, ToolResultPart, ThinkingPart, StructuredOutputPart, ChatClientPersistence, ChatPersistedState, ChatPersistenceOption, ChatStorageAdapter, ChatClientOptions, ChatPendingInterrupt, BoundInterruptBase, BoundInterrupts, ChatInterrupt, ChatInterruptState, GenericAGUIInterrupt, UnboundInterrupt, InterruptItemStatus, ToolApprovalInterrupt, ClientContextOptionFromTools, ChatResumeState, ChatRequestBody, InferChatMessages, InferredClientContext, ChatClientState, ConnectionStatus, ChatFetcher, ChatFetcherInput, ChatFetcherOptions, ChatTransport, DistributedOmit, MultimodalContent, QueuedMessage, WhenBusy, QueueBusyReason, QueueConfig, QueueStrategy, QueueOption, SendMessageOptions, } from './types.js';
11
+ export type { UIMessage, MessagePart, TextPart, ToolCallPart, ToolResultPart, ThinkingPart, StructuredOutputPart, ChatClientPersistence, ChatPersistedState, ChatPersistenceOption, ChatPersistenceOptions, ChatStorageAdapter, ChatClientOptions, ChatPendingInterrupt, BoundInterruptBase, BoundInterrupts, ChatInterrupt, ChatInterruptState, GenericAGUIInterrupt, UnboundInterrupt, InterruptItemStatus, ToolApprovalInterrupt, ClientContextOptionFromTools, ChatResumeState, ChatRequestBody, InferChatMessages, InferredClientContext, ChatClientState, ConnectionStatus, ChatFetcher, ChatFetcherInput, ChatFetcherOptions, ChatTransport, DistributedOmit, MultimodalContent, QueuedMessage, WhenBusy, QueueBusyReason, QueueConfig, QueueStrategy, QueueOption, SendMessageOptions, } from './types.js';
12
12
  export type { InferGenerationOutput, InferGenerationOutputFromReturn, GenerationClientState, GenerationPersistenceOptions, GenerationClientOptions, GenerationFetcher, GenerationFetcherOptions, GenerationTransport, VideoGenerationClientOptions, VideoStatusInfo, VideoGenerateResult, ImageGenerateInput, AudioGenerateInput, SpeechGenerateInput, TranscriptionGenerateInput, SummarizeGenerateInput, VideoGenerateInput, GenerationRestoredResult, } from './generation-types.js';
13
13
  export { GENERATION_EVENTS } from './generation-types.js';
14
14
  export { reconstructImageResult, reconstructAudioResult, reconstructSpeechResult, reconstructTranscriptionResult, reconstructSummarizeResult, } from './generation-reconstruct.js';
@@ -20,6 +20,6 @@ export { createAIDevtoolsGenerationPreview, type AIDevtoolsClientMetadata, type
20
20
  export type { ExtractToolNames, ExtractToolInput, ExtractToolOutput, } from './tool-types.js';
21
21
  export type { AnyClientTool, Interrupt, PersistedArtifactActivity, PersistedArtifactRef, PersistedArtifactRole, RunAgentResumeItem, RunFinishedOutcome, } from '@tanstack/ai/client';
22
22
  export type { RealtimeAdapter, RealtimeConnection, RealtimeClientOptions, RealtimeClientState, RealtimeStateChangeCallback, } from './realtime-types.js';
23
- export { fetchServerSentEvents, fetchHttpStream, xhrServerSentEvents, xhrHttpStream, stream, rpcStream, StreamTruncatedError, DurableStreamIncompleteError, StreamReconnectLimitError, type ConnectConnectionAdapter, type ConnectionAdapter, type GenerationHydrationResult, type FetchConnectionOptions, type ReconnectOptions, type ResumableConnectConnectionAdapter, type RunAgentInputContext, type StreamConnectionHandlers, type SubscribeConnectionAdapter, type XhrConnectionOptions, } from './connection-adapters.js';
23
+ export { fetchServerSentEvents, fetchHttpStream, xhrServerSentEvents, xhrHttpStream, stream, rpcStream, webSocket, StreamTruncatedError, DurableStreamIncompleteError, StreamReconnectLimitError, type ConnectConnectionAdapter, type ConnectionAdapter, type GenerationHydrationResult, type FetchConnectionOptions, type ReconnectOptions, type ResumableConnectConnectionAdapter, type RunAgentInputContext, type StreamConnectionHandlers, type SubscribeConnectionAdapter, type WebSocketConnectionOptions, type XhrConnectionOptions, } from './connection-adapters.js';
24
24
  export { uiMessageToModelMessages, modelMessageToUIMessage, modelMessagesToUIMessages, convertMessagesToModelMessages, normalizeToUIMessage, generateMessageId, } from '@tanstack/ai/client';
25
25
  export { StreamProcessor, ImmediateStrategy, PunctuationStrategy, BatchStrategy, WordBoundaryStrategy, CompositeStrategy, parsePartialJSON, PartialJSONParser, defaultJSONParser, type ChunkStrategy, type StreamProcessorOptions, type StreamProcessorEvents, type InternalToolCallState, type ToolCallState, type ToolResultState, type JSONParser, type ChunkRecording, type ProcessorResult, type ProcessorState, } from '@tanstack/ai/client';
package/dist/esm/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { AudioRecorder } from "./audio-recorder.js";
2
2
  import { UnsupportedResponseStreamError } from "./response-stream.js";
3
- import { DurableStreamIncompleteError, StreamReconnectLimitError, StreamTruncatedError, fetchHttpStream, fetchServerSentEvents, rpcStream, stream, xhrHttpStream, xhrServerSentEvents } from "./connection-adapters.js";
3
+ import { DurableStreamIncompleteError, StreamReconnectLimitError, StreamTruncatedError, fetchHttpStream, fetchServerSentEvents, rpcStream, stream, webSocket, xhrHttpStream, xhrServerSentEvents } from "./connection-adapters.js";
4
4
  import { InterruptManager } from "./interrupt-manager.js";
5
5
  import { ChatClient } from "./chat-client.js";
6
6
  import { createMcpAppBridge } from "./mcp-app-bridge.js";
@@ -13,4 +13,4 @@ import { clientTools, createChatClientOptions } from "./types.js";
13
13
  import { StorageUnavailableError, indexedDBPersistence, localStoragePersistence, sessionStoragePersistence } from "./storage-adapters.js";
14
14
  import { createAIDevtoolsGenerationPreview } from "./devtools.js";
15
15
  import { BatchStrategy, CompositeStrategy, ImmediateStrategy, PartialJSONParser, PunctuationStrategy, StreamProcessor, WordBoundaryStrategy, convertMessagesToModelMessages, defaultJSONParser, generateMessageId, modelMessageToUIMessage, modelMessagesToUIMessages, normalizeToUIMessage, parsePartialJSON, uiMessageToModelMessages } from "@tanstack/ai/client";
16
- export { AudioRecorder, BatchStrategy, ChatClient, CompositeStrategy, DurableStreamIncompleteError, GENERATION_EVENTS, GenerationClient, ImmediateStrategy, InterruptManager, PartialJSONParser, PunctuationStrategy, RealtimeClient, StorageUnavailableError, StreamProcessor, StreamReconnectLimitError, StreamTruncatedError, UnsupportedResponseStreamError, VideoGenerationClient, WordBoundaryStrategy, clientTools, convertMessagesToModelMessages, createAIDevtoolsGenerationPreview, createChatClientOptions, createMcpAppBridge, defaultJSONParser, fetchHttpStream, fetchServerSentEvents, generateMessageId, indexedDBPersistence, localStoragePersistence, modelMessageToUIMessage, modelMessagesToUIMessages, normalizeToUIMessage, parsePartialJSON, reconstructAudioResult, reconstructImageResult, reconstructSpeechResult, reconstructSummarizeResult, reconstructTranscriptionResult, rpcStream, sessionStoragePersistence, stream, uiMessageToModelMessages, xhrHttpStream, xhrServerSentEvents };
16
+ export { AudioRecorder, BatchStrategy, ChatClient, CompositeStrategy, DurableStreamIncompleteError, GENERATION_EVENTS, GenerationClient, ImmediateStrategy, InterruptManager, PartialJSONParser, PunctuationStrategy, RealtimeClient, StorageUnavailableError, StreamProcessor, StreamReconnectLimitError, StreamTruncatedError, UnsupportedResponseStreamError, VideoGenerationClient, WordBoundaryStrategy, clientTools, convertMessagesToModelMessages, createAIDevtoolsGenerationPreview, createChatClientOptions, createMcpAppBridge, defaultJSONParser, fetchHttpStream, fetchServerSentEvents, generateMessageId, indexedDBPersistence, localStoragePersistence, modelMessageToUIMessage, modelMessagesToUIMessages, normalizeToUIMessage, parsePartialJSON, reconstructAudioResult, reconstructImageResult, reconstructSpeechResult, reconstructSummarizeResult, reconstructTranscriptionResult, rpcStream, sessionStoragePersistence, stream, uiMessageToModelMessages, webSocket, xhrHttpStream, xhrServerSentEvents };
@@ -445,6 +445,30 @@ export interface ChatClientPersistence<TTools extends ReadonlyArray<AnyClientToo
445
445
  * in the browser and restored on reload with no network.
446
446
  */
447
447
  export type ChatPersistenceOption<TTools extends ReadonlyArray<AnyClientTool> = any> = boolean | ChatClientPersistence<TTools>;
448
+ /**
449
+ * The `persistence` / `threadId` pairing for `ChatClient` and the chat hooks.
450
+ *
451
+ * Persistence that is on (`true` or a storage adapter) requires a `threadId`.
452
+ * A minted id changes every reload, so nothing would restore. The compiler
453
+ * asks for the conversation id instead.
454
+ *
455
+ * Omit `persistence`, or set it to `false`, and `threadId` stays optional.
456
+ * The client then mints one after mount for the wire and DevTools.
457
+ *
458
+ * Intersect this onto `ChatClientOptions`. Do not apply a later plain `Omit`
459
+ * to that type: it collapses the union and the requirement disappears. Use
460
+ * {@link DistributedOmit}.
461
+ */
462
+ export type ChatPersistenceOptions<TTools extends ReadonlyArray<AnyClientTool> = any> = {
463
+ persistence: true;
464
+ threadId: string;
465
+ } | {
466
+ persistence: ChatClientPersistence<TTools>;
467
+ threadId: string;
468
+ } | {
469
+ persistence?: false | undefined;
470
+ threadId?: string;
471
+ };
448
472
  type IsUnknown<T> = unknown extends T ? [T] extends [unknown] ? true : false : false;
449
473
  type KnownContext<T> = IsUnknown<T> extends true ? never : T;
450
474
  type MergeContext<TLeft, TRight> = [TLeft] extends [never] ? TRight : [TRight] extends [never] ? TLeft : TLeft & TRight;
@@ -483,40 +507,6 @@ export interface ChatClientBaseOptions<TTools extends ReadonlyArray<AnyClientToo
483
507
  * Initial messages to populate the chat
484
508
  */
485
509
  initialMessages?: Array<UIMessage<TTools>>;
486
- /**
487
- * How this chat persists across reloads. See {@link ChatPersistenceOption}.
488
- *
489
- * - Omit or `false`: ephemeral, in-memory only.
490
- * - `true`: server-authoritative. The client caches nothing and hydrates the
491
- * thread from the server by its `threadId` on mount (needs a connection with
492
- * a `hydrate` handler). Big transcripts never touch the browser, and the same
493
- * thread opens the same way on another device.
494
- * - a {@link ChatClientPersistence} adapter: client-authoritative. The combined
495
- * {@link ChatPersistedState} record (transcript plus resume pointer) is cached
496
- * in the browser, restoring the transcript, pending interrupts, and an
497
- * in-flight run on reload.
498
- *
499
- * Use `initialResumeSnapshot` for a host-supplied in-memory rehydrate instead.
500
- */
501
- persistence?: ChatPersistenceOption<TTools>;
502
- /**
503
- * Optional storage-key override for this chat instance, and the devtools
504
- * instance id. Persistence keys on `threadId` by default; set `id` only when
505
- * you need the persisted record keyed separately from the wire thread.
506
- * Prefer a stable `threadId` for the common case.
507
- *
508
- * The framework hooks (`useChat` / `createChat`) do NOT expose `id`: a hook's
509
- * identity is its `threadId`. This lower-level escape hatch exists only for
510
- * direct `ChatClient` construction.
511
- */
512
- id?: string;
513
- /**
514
- * The conversation id for this chat, stable across sends and reloads. It is
515
- * the AG-UI thread key on the wire AND the key client persistence stores the
516
- * conversation under, so set a stable `threadId` to have a reload restore the
517
- * same conversation. If omitted, a unique thread id is generated per session.
518
- */
519
- threadId?: string;
520
510
  /**
521
511
  * Initial resumable run state, useful when rehydrating a persisted client
522
512
  * after a full page reload. This restores the client-side interrupt
@@ -664,9 +654,10 @@ export interface ChatClientBaseOptions<TTools extends ReadonlyArray<AnyClientToo
664
654
  }
665
655
  /**
666
656
  * Options for `ChatClient`. Exactly one of `connection` or `fetcher` must be
667
- * provided — the type-level XOR is enforced via `ChatTransport`.
657
+ * provided — the type-level XOR is enforced via `ChatTransport`. Persistence
658
+ * that is on requires a `threadId` via {@link ChatPersistenceOptions}.
668
659
  */
669
- export type ChatClientOptions<TTools extends ReadonlyArray<AnyClientTool> = any, TContext = InferredClientContext<TTools>> = DistributedOmit<ChatClientBaseOptions<TTools, TContext>, 'context'> & ClientContextOptionFromTools<TTools, TContext> & ChatTransport;
660
+ export type ChatClientOptions<TTools extends ReadonlyArray<AnyClientTool> = any, TContext = InferredClientContext<TTools>> = DistributedOmit<ChatClientBaseOptions<TTools, TContext>, 'context'> & ClientContextOptionFromTools<TTools, TContext> & ChatTransport & ChatPersistenceOptions<TTools>;
670
661
  export interface ChatRequestBody {
671
662
  messages: Array<ModelMessage>;
672
663
  data?: Record<string, any>;
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","names":[],"sources":["../../src/types.ts"],"sourcesContent":["import type {\n AnyClientTool,\n ApprovalCapabilityOf,\n ApprovalSchemaOf,\n AudioPart,\n BatchInterruptError,\n ChunkStrategy,\n ContentPart,\n DocumentPart,\n ImagePart,\n InferSchemaType,\n InferToolInput,\n InferToolOutput,\n InputSchemaOf,\n Interrupt,\n InterruptBinding,\n ItemInterruptError,\n ModelMessage,\n NoSchema,\n RunAgentResumeItem,\n SchemaInput,\n StreamChunk,\n StructuredOutputPart,\n UIResourcePart,\n VideoPart,\n} from '@tanstack/ai/client'\nimport type { ConnectionAdapter } from './connection-adapters'\nimport type { AIDevtoolsClientMetadata } from './devtools'\nimport type { ChatDevtoolsBridgeFactory } from './devtools-noop'\n\nexport type { StructuredOutputPart }\n\nexport interface ChatResumeState {\n threadId: string\n runId: string\n}\n\nexport type ChatPendingInterrupt = Interrupt\n\n/**\n * The durable pointer a chat keeps for the run it may need to rejoin, plus any\n * interrupt that run is waiting on.\n *\n * @internal\n */\nexport interface ChatResumeSnapshot {\n resumeState: ChatResumeState\n pendingInterrupts?: Array<ChatPendingInterrupt>\n}\n\nexport type InterruptItemStatus =\n | 'pending'\n | 'validating'\n | 'staged'\n | 'submitting'\n | 'error'\n\nexport interface BoundInterruptBase {\n readonly id: string\n readonly interruptId: string\n readonly reason: string\n readonly message?: string\n readonly responseSchema?: Readonly<Record<string, unknown>>\n readonly expiresAt?: string\n readonly metadata?: Readonly<Record<string, unknown>>\n readonly threadId: string\n readonly interruptedRunId: string\n readonly generation: number\n readonly status: InterruptItemStatus\n readonly errors: ReadonlyArray<ItemInterruptError>\n /** @deprecated Use `errors[0]`. */\n readonly error?: ItemInterruptError\n /**\n * Whether the binding/schema allows resolution at hydrate time.\n * Does not flip on submit/expiry — gate UI on `status`, `resuming`, and\n * `errors` for those lifecycle states.\n */\n readonly canResolve: boolean\n cancel: () => void\n clearResolution: () => void\n}\n\nexport interface GenericAGUIInterrupt extends BoundInterruptBase {\n readonly kind: 'generic'\n readonly binding: Readonly<Extract<InterruptBinding, { kind: 'generic' }>>\n resolveInterrupt: (payload: unknown) => void\n}\n\n/**\n * An interrupt that arrived on the stream carrying no resume binding this\n * client understands — no `tanstack:interruptBinding`, or one written at a\n * protocol version we don't recognise.\n *\n * These are surfaced rather than hidden so a UI can show that the run is\n * paused, but they are never resolvable here: something else owns them. A\n * workflow engine's durable approval projected into the same AG-UI stream\n * lands in this bucket, and resolving it through the chat resume path would\n * send an answer no one is waiting for. Render it, or route it to whatever\n * actually owns the pause.\n */\nexport interface UnboundInterrupt extends BoundInterruptBase {\n readonly kind: 'unbound'\n readonly binding?: undefined\n readonly canResolve: false\n}\n\ntype ApprovalBranchSchema<TTool, TBranch extends 'approve' | 'reject'> =\n ApprovalSchemaOf<TTool> extends infer TApproval\n ? TApproval extends { approve?: SchemaInput; reject?: SchemaInput }\n ? Exclude<TApproval[TBranch], undefined>\n : TApproval extends SchemaInput\n ? TApproval\n : never\n : never\n\ntype ApprovalEdits<TTool> =\n InputSchemaOf<TTool> extends NoSchema\n ? { editedArgs?: never }\n : { editedArgs?: InferToolInput<TTool> }\n\ntype ApprovalPayload<TSchema> = [TSchema] extends [never]\n ? { payload?: never }\n : TSchema extends SchemaInput\n ? { payload: InferSchemaType<TSchema> }\n : { payload?: never }\n\ntype ApproveArguments<TTool> = [\n ApprovalBranchSchema<TTool, 'approve'>,\n] extends [never]\n ? InputSchemaOf<TTool> extends NoSchema\n ? [options?: never]\n : [options?: ApprovalEdits<TTool> & { payload?: never }]\n : [\n options: ApprovalEdits<TTool> &\n ApprovalPayload<ApprovalBranchSchema<TTool, 'approve'>>,\n ]\n\ntype RejectArguments<TTool> = [ApprovalBranchSchema<TTool, 'reject'>] extends [\n never,\n]\n ? [options?: never]\n : [\n options: { editedArgs?: never } & ApprovalPayload<\n ApprovalBranchSchema<TTool, 'reject'>\n >,\n ]\n\nexport type ToolApprovalInterrupt<TTool extends AnyClientTool = AnyClientTool> =\n TTool extends AnyClientTool\n ? BoundInterruptBase & {\n readonly kind: 'tool-approval'\n readonly binding: Readonly<\n Extract<InterruptBinding, { kind: 'tool-approval' }>\n >\n readonly toolName: TTool['name']\n readonly toolCallId: string\n readonly originalArgs: InferToolInput<TTool>\n // A single generic call signature — not two overloads. Overloads break\n // editor autocomplete: a half-typed options literal (e.g.\n // `resolveInterrupt(true, { payload: {` ) satisfies neither overload,\n // so TS resolves no signature and offers no contextual completions.\n // Making `approved` a generic discriminant lets TS infer it from the\n // first argument and pick the matching branch for the rest params, so\n // `payload` / `editedArgs` / the correct schema's fields complete\n // per-branch (a plain union-of-tuples would offer both branches'\n // fields) while still enforcing the right shape.\n resolveInterrupt: <TApproved extends boolean>(\n approved: TApproved,\n ...args: TApproved extends true\n ? ApproveArguments<TTool>\n : RejectArguments<TTool>\n ) => void\n }\n : never\n\ntype ApprovalInterrupts<TTools extends ReadonlyArray<AnyClientTool>> =\n TTools[number] extends infer TTool\n ? TTool extends AnyClientTool\n ? ApprovalCapabilityOf<TTool> extends true\n ? ToolApprovalInterrupt<TTool>\n : never\n : never\n : never\n\n// Client tools resolve through their `.client()` implementation (auto-run) or\n// `addToolResult` — never as a bound interrupt. The `client-tool-execution`\n// pause is handled internally and is intentionally absent from this public\n// union.\nexport type ChatInterrupt<\n TTools extends ReadonlyArray<AnyClientTool> = ReadonlyArray<AnyClientTool>,\n> = GenericAGUIInterrupt | UnboundInterrupt | ApprovalInterrupts<TTools>\n\nexport type BoundInterrupts<\n TTools extends ReadonlyArray<AnyClientTool> = ReadonlyArray<AnyClientTool>,\n> = ReadonlyArray<ChatInterrupt<TTools>>\n\nexport interface ChatInterruptState<\n TTools extends ReadonlyArray<AnyClientTool> = ReadonlyArray<AnyClientTool>,\n> {\n readonly interrupts: BoundInterrupts<TTools>\n /** @deprecated Use `interrupts`. Same snapshot today. */\n readonly pendingInterrupts: BoundInterrupts<TTools>\n readonly interruptErrors: ReadonlyArray<BatchInterruptError>\n readonly resuming: boolean\n}\n\n/**\n * `messages` is the full UIMessage history (not a delta). `data` is the\n * merged body — `ChatClientOptions.body` plus any per-call data passed to\n * `sendMessage(...)`. `threadId` / `runId` are the AG-UI correlation ids\n * the chat client uses to track this turn — forward them to your server\n * if it needs to correlate requests.\n */\nexport interface ChatFetcherInput {\n messages: Array<UIMessage>\n data?: Record<string, unknown>\n threadId: string\n runId: string\n parentRunId?: string\n resume?: Array<RunAgentResumeItem>\n}\n\nexport interface ChatFetcherOptions {\n /** Fires when `stop()` is called or the request is superseded. */\n signal: AbortSignal\n}\n\n/**\n * Direct function that performs a chat request. Mirrors\n * `GenerationFetcher`. Returns either a `Response` (SSE body parsed by the\n * chat client) or an `AsyncIterable<StreamChunk>` (yielded directly). May\n * return the value synchronously, as a `Promise`, or as an async generator\n * (`async function*`) — the chat client awaits whichever shape is returned.\n *\n * @example\n * ```ts\n * useChat({\n * fetcher: ({ messages }, { signal }) =>\n * chatFn({ data: { messages }, signal }),\n * })\n * ```\n */\nexport type ChatFetcher = (\n input: ChatFetcherInput,\n options: ChatFetcherOptions,\n) =>\n | Response\n | AsyncIterable<StreamChunk>\n | Promise<Response | AsyncIterable<StreamChunk>>\n\n/**\n * Distributive `Omit` — applies `Omit<O, K>` per branch of a union so\n * discriminated unions survive omission. Plain `Omit` collapses unions\n * into a single object shape, which would erase the `ChatTransport` XOR\n * when framework hooks omit React-managed callbacks from\n * `ChatClientOptions`.\n */\nexport type DistributedOmit<\n TObject,\n TKeys extends keyof any,\n> = TObject extends unknown ? Omit<TObject, TKeys> : never\n\n/**\n * Discriminated union enforcing that exactly one of `connection` or\n * `fetcher` is provided. Mirrors `GenerationTransport`.\n */\nexport type ChatTransport =\n | { connection: ConnectionAdapter; fetcher?: never }\n | { fetcher: ChatFetcher; connection?: never }\n\n/**\n * Tool call states - track the lifecycle of a tool call\n */\nexport type ToolCallState =\n | 'awaiting-input' // Received start but no arguments yet\n | 'input-streaming' // Partial arguments received\n | 'input-complete' // All arguments received\n | 'approval-requested' // Waiting for user approval\n | 'approval-responded' // User has approved/denied\n | 'complete' // Result is complete\n | 'error' // Tool execution failed (terminal)\n\n/**\n * Tool result states - track the lifecycle of a tool result\n */\nexport type ToolResultState =\n | 'streaming' // Placeholder for future streamed output\n | 'complete' // Result is complete\n | 'error' // Error occurred\n\n/**\n * ChatClient state - track the lifecycle of a chat\n */\nexport type ChatClientState = 'ready' | 'submitted' | 'streaming' | 'error'\n\n/**\n * Connection lifecycle state for the subscription loop.\n */\nexport type ConnectionStatus =\n | 'disconnected'\n | 'connecting'\n | 'connected'\n | 'error'\n\n/**\n * Multimodal content input for sending messages with rich media.\n * Allows sending text, images, audio, video, and documents to the LLM.\n *\n * @example\n * ```ts\n * // Send an image with a question\n * client.sendMessage({\n * content: [\n * { type: 'text', content: 'What is in this image?' },\n * { type: 'image', source: { type: 'url', value: 'https://example.com/photo.jpg' } }\n * ],\n * id: 'custom-message-id' // optional\n * })\n * ```\n */\nexport interface MultimodalContent {\n /**\n * The content of the message.\n * Can be a simple string or an array of content parts for multimodal messages.\n */\n content: string | Array<ContentPart>\n /**\n * Optional custom ID for the message.\n * If not provided, a unique ID will be generated.\n */\n id?: string\n}\n\n/**\n * Action taken when `sendMessage` is called while the client is busy\n * (streaming, claiming a send, or draining the queue).\n * - `queue`: hold the message; it auto-sends when the current run settles\n * **successfully**.\n * - `drop`: ignore the send (promise still resolves; does not throw).\n * - `interrupt`: abort the current stream and send immediately. Unlike\n * `stop()`, does **not** flush already-queued messages — they still drain\n * after the interrupting send settles successfully.\n */\nexport type WhenBusy = 'queue' | 'drop' | 'interrupt'\n\n/**\n * Why the client is busy when a {@link QueueStrategy} runs.\n * - `streaming` — an LLM stream is active (`isLoading`).\n * - `sendInFlight` — a send has claimed the client but is not yet loading.\n * - `draining` — the queue drain loop is delivering pending messages.\n */\nexport type QueueBusyReason = 'streaming' | 'sendInFlight' | 'draining'\n\n/**\n * A user message held in the send queue while a stream is active.\n * Rendered separately from `messages`; cancellable via `cancelQueued(id)`\n * until it drains.\n */\nexport interface QueuedMessage {\n id: string\n content: string | MultimodalContent\n createdAt: number\n}\n\n/**\n * Declarative queue policy.\n */\nexport interface QueueConfig {\n /**\n * Action when the client is busy (streaming, claiming a send, or draining).\n * Default `'queue'`.\n */\n whenBusy?: WhenBusy\n /**\n * How queued items leave the queue.\n * - `'fifo'`: one at a time, in order (default).\n * - `'batch'`: merge all queued items into one send when the run settles\n * successfully.\n */\n drain?: 'fifo' | 'batch'\n /** Max queued items. Unlimited when omitted. `0` means never queue. */\n maxSize?: number\n /**\n * Behavior when `maxSize` is reached. Default `'reject'`.\n * `'reject'` silently discards the new send (does not throw);\n * `'drop-oldest'` evicts the oldest queued item to make room.\n * Only meaningful when `maxSize` is set.\n */\n onOverflow?: 'reject' | 'drop-oldest'\n}\n\n/**\n * Escape hatch: decide the action for a single send. Drain stays FIFO for the\n * function form (no `batch` via function). Per-call `sendOptions.whenBusy`\n * overrides the strategy for that send.\n *\n * Actions match {@link WhenBusy}: `'queue' | 'drop' | 'interrupt'`. Concurrent\n * streams are not supported. `pending.id` is the id that will be stored if the\n * action is `'queue'` (safe to pass to `cancelQueued`).\n */\nexport type QueueStrategy = (ctx: {\n pending: QueuedMessage\n busyReason: QueueBusyReason\n queued: ReadonlyArray<QueuedMessage>\n}) => { action: WhenBusy }\n\n/** A `WhenBusy` shorthand, a full config, or a strategy function. */\nexport type QueueOption = WhenBusy | QueueConfig | QueueStrategy\n\n/** Per-call overrides for `sendMessage`. */\nexport interface SendMessageOptions {\n /** Overrides the configured `whenBusy` for this one send. */\n whenBusy?: WhenBusy\n}\n\n/**\n * Message parts - building blocks of UIMessage\n */\nexport interface TextPart {\n type: 'text'\n content: string\n}\n\n/**\n * Helper type that creates a tool-call part for a specific tool.\n * This is a conditional type to enable proper distribution over union types,\n * creating a discriminated union where `name` is the discriminant.\n */\ntype ToolCallPartForTool<T> = T extends AnyClientTool\n ? {\n type: 'tool-call'\n id: string\n name: T['name']\n arguments: string // JSON string (may be incomplete)\n /** Parsed tool input (typed from inputSchema) */\n input?: InferToolInput<T>\n state: ToolCallState\n /** Tool execution output (for client tools or after approval) */\n output?: InferToolOutput<T>\n } & (NonNullable<T['needsApproval']> extends true\n ? {\n /**\n * Approval metadata — present only on tools defined with\n * `needsApproval: true`. Populated once the call reaches\n * `state: 'approval-requested'`. `needsApproval` is an optional\n * property on the tool, so we index into it (rather than\n * `T extends { needsApproval: true }`, which an optional property\n * never satisfies) and strip `undefined` before comparing to `true`.\n */\n approval?: {\n id: string // Unique approval ID\n needsApproval: boolean // Always true if present\n approved?: boolean // User's decision (undefined until responded)\n }\n }\n : // Tools without `needsApproval: true` never carry an approval field.\n // `& unknown` is a no-op intersection (adds nothing).\n unknown)\n : never\n\n/**\n * Fallback tool-call part type when tools are not typed\n */\ntype UntypedToolCallPart = {\n type: 'tool-call'\n id: string\n name: string\n arguments: string\n input?: any\n state: ToolCallState\n approval?: {\n id: string\n needsApproval: boolean\n approved?: boolean\n }\n output?: any\n}\n\n/**\n * Tool call part that creates a proper discriminated union.\n * When TTools is typed, checking `part.name === 'toolName'` will narrow\n * `part.output` to the correct type for that tool.\n *\n * The discriminant is `name`, so code like:\n * ```ts\n * if (part.name === 'recommendGuitar') {\n * // part.output is now typed to the recommendGuitar tool's output\n * }\n * ```\n */\nexport type ToolCallPart<TTools extends ReadonlyArray<AnyClientTool> = any> =\n // Check if we have a concrete tools array (not 'any' or 'never')\n [TTools] extends [never]\n ? UntypedToolCallPart\n : unknown extends TTools\n ? UntypedToolCallPart\n : TTools extends ReadonlyArray<infer Tool>\n ? Tool extends AnyClientTool\n ? ToolCallPartForTool<Tool>\n : UntypedToolCallPart\n : UntypedToolCallPart\n\nexport interface ToolResultPart {\n type: 'tool-result'\n toolCallId: string\n content: string | Array<ContentPart>\n state: ToolResultState\n error?: string // Error message if state is \"error\"\n}\n\nexport interface ThinkingPart {\n type: 'thinking'\n content: string\n}\n\nexport type MessagePart<\n TTools extends ReadonlyArray<AnyClientTool> = any,\n TData = unknown,\n> =\n | TextPart\n | ImagePart\n | AudioPart\n | VideoPart\n | DocumentPart\n | ToolCallPart<TTools>\n | ToolResultPart\n | ThinkingPart\n | StructuredOutputPart<TData>\n | UIResourcePart\n\n/**\n * UIMessage - Domain-specific message format optimized for building chat UIs\n * Contains parts that can be text, tool calls, or tool results.\n *\n * `TTools` narrows the tool-call/result part types based on the registered\n * tools. `TData` is the schema-inferred type for any `structured-output` part\n * on the message — defaulted to `unknown` so untyped consumers (the core\n * stream processor, the wire converter) don't need to thread a schema generic\n * everywhere; the hook layer (`useChat({ outputSchema })`) substitutes it on\n * the public return so `m.parts.find(p => p.type === 'structured-output').data`\n * is typed without manual casts.\n */\nexport interface UIMessage<\n TTools extends ReadonlyArray<AnyClientTool> = any,\n TData = unknown,\n> {\n id: string\n role: 'system' | 'user' | 'assistant'\n parts: Array<MessagePart<TTools, TData>>\n createdAt?: Date\n}\n\n/**\n * A generic key/value storage adapter. `getItem` may be sync or async; the\n * chat persistence layer treats every call as best-effort. The provided\n * `localStoragePersistence` / `sessionStoragePersistence` / `indexedDBPersistence`\n * factories return one of these, and `ChatStorageAdapter<ChatPersistedState>`\n * is assignable to {@link ChatClientPersistence}.\n */\nexport interface ChatStorageAdapter<TValue> {\n getItem: (\n id: string,\n ) => TValue | null | undefined | Promise<TValue | null | undefined>\n setItem: (id: string, value: TValue) => void | Promise<void>\n removeItem: (id: string) => void | Promise<void>\n}\n\n/**\n * The single record a `ChatClientPersistence` adapter stores per chat. It folds\n * the two things that must survive a full page reload into one blob under one\n * key: the message transcript and the optional resume snapshot (which run to\n * rejoin / which interrupts to rehydrate). One adapter, one key — see\n * {@link ChatClientPersistence}.\n */\nexport interface ChatPersistedState<\n TTools extends ReadonlyArray<AnyClientTool> = any,\n> {\n messages: Array<UIMessage<TTools>>\n /** Present while a run is in flight or paused on an interrupt; absent otherwise. */\n resume?: ChatResumeSnapshot\n}\n\n/**\n * Storage adapter for durable chat state. A single adapter persists both the\n * message transcript and the resume snapshot as one {@link ChatPersistedState}\n * record, so a full page reload restores the conversation AND can rejoin an\n * in-flight run / rehydrate pending interrupts.\n *\n * For backward compatibility `getItem` may also return a bare `UIMessage[]`\n * (the legacy messages-only format); the client normalizes it to\n * `{ messages }`. `setItem` always writes the combined record.\n */\nexport interface ChatClientPersistence<\n TTools extends ReadonlyArray<AnyClientTool> = any,\n> {\n getItem: (\n id: string,\n ) =>\n | ChatPersistedState<TTools>\n | Array<UIMessage<TTools>>\n | null\n | undefined\n | Promise<\n ChatPersistedState<TTools> | Array<UIMessage<TTools>> | null | undefined\n >\n setItem: (\n id: string,\n state: ChatPersistedState<TTools>,\n ) => void | Promise<void>\n removeItem: (id: string) => void | Promise<void>\n}\n\n/**\n * The `persistence` option for a chat.\n *\n * - `false` (default): ephemeral. Messages live in memory only; a reload starts\n * from empty.\n * - `true`: server-authoritative. Nothing is cached in the browser. On mount the\n * client hydrates the thread from the server by its `threadId` (paints the\n * stored transcript and tails any run still generating), so a reload or the\n * same thread opened on another device both just resume. Requires a connection\n * with a `hydrate` handler.\n * - a {@link ChatClientPersistence} adapter: client-authoritative. The combined\n * {@link ChatPersistedState} record (transcript plus resume pointer) is cached\n * in the browser and restored on reload with no network.\n */\nexport type ChatPersistenceOption<\n TTools extends ReadonlyArray<AnyClientTool> = any,\n> = boolean | ChatClientPersistence<TTools>\n\ntype IsUnknown<T> = unknown extends T\n ? [T] extends [unknown]\n ? true\n : false\n : false\n\ntype KnownContext<T> = IsUnknown<T> extends true ? never : T\n\ntype MergeContext<TLeft, TRight> = [TLeft] extends [never]\n ? TRight\n : [TRight] extends [never]\n ? TLeft\n : TLeft & TRight\n\ntype UnionToIntersection<T> = [T] extends [never]\n ? never\n : (T extends unknown ? (value: T) => void : never) extends (\n value: infer TIntersection,\n ) => void\n ? TIntersection\n : never\n\ntype DefinedContext<T> = Exclude<T, undefined>\n\ntype ContextFromExecute<T> = T extends (...args: any) => any\n ? NonNullable<Parameters<T>[1]> extends { context: infer TContext }\n ? KnownContext<TContext>\n : never\n : never\n\ntype ContextFromClientTool<T> = T extends AnyClientTool\n ? T extends { execute?: infer TExecute }\n ? ContextFromExecute<TExecute>\n : never\n : never\n\ntype RequiredContextFromClientToolUnion<T> = T extends unknown\n ? undefined extends ContextFromClientTool<T>\n ? never\n : ContextFromClientTool<T>\n : never\n\ntype ContextFromClientToolUnion<T> = [\n UnionToIntersection<DefinedContext<ContextFromClientTool<T>>>,\n] extends [never]\n ? never\n : [RequiredContextFromClientToolUnion<T>] extends [never]\n ? UnionToIntersection<DefinedContext<ContextFromClientTool<T>>> | undefined\n : UnionToIntersection<DefinedContext<ContextFromClientTool<T>>>\n\ntype ContextFromClientTools<TTools> =\n IsUnknown<TTools> extends true\n ? never\n : TTools extends readonly [infer THead, ...infer TTail]\n ? MergeContext<\n ContextFromClientTool<THead>,\n ContextFromClientTools<TTail>\n >\n : TTools extends ReadonlyArray<infer TItem>\n ? ContextFromClientToolUnion<TItem>\n : never\n\nexport type InferredClientContext<TTools> = [\n ContextFromClientTools<TTools>,\n] extends [never]\n ? unknown\n : ContextFromClientTools<TTools>\n\nexport type ClientContextOptionFromTools<TTools, TContext> = [\n ContextFromClientTools<TTools>,\n] extends [never]\n ? { context?: TContext }\n : undefined extends ContextFromClientTools<TTools>\n ? { context?: TContext & ContextFromClientTools<TTools> }\n : { context: TContext & ContextFromClientTools<TTools> }\n\n/**\n * Base options for `ChatClient`, excluding the transport (`connection` or\n * `fetcher`) which is supplied separately via `ChatTransport` so the XOR\n * is preserved when composing the final `ChatClientOptions` type.\n */\nexport interface ChatClientBaseOptions<\n TTools extends ReadonlyArray<AnyClientTool> = any,\n TContext = unknown,\n> {\n /**\n * Initial messages to populate the chat\n */\n initialMessages?: Array<UIMessage<TTools>>\n\n /**\n * How this chat persists across reloads. See {@link ChatPersistenceOption}.\n *\n * - Omit or `false`: ephemeral, in-memory only.\n * - `true`: server-authoritative. The client caches nothing and hydrates the\n * thread from the server by its `threadId` on mount (needs a connection with\n * a `hydrate` handler). Big transcripts never touch the browser, and the same\n * thread opens the same way on another device.\n * - a {@link ChatClientPersistence} adapter: client-authoritative. The combined\n * {@link ChatPersistedState} record (transcript plus resume pointer) is cached\n * in the browser, restoring the transcript, pending interrupts, and an\n * in-flight run on reload.\n *\n * Use `initialResumeSnapshot` for a host-supplied in-memory rehydrate instead.\n */\n persistence?: ChatPersistenceOption<TTools>\n\n /**\n * Optional storage-key override for this chat instance, and the devtools\n * instance id. Persistence keys on `threadId` by default; set `id` only when\n * you need the persisted record keyed separately from the wire thread.\n * Prefer a stable `threadId` for the common case.\n *\n * The framework hooks (`useChat` / `createChat`) do NOT expose `id`: a hook's\n * identity is its `threadId`. This lower-level escape hatch exists only for\n * direct `ChatClient` construction.\n */\n id?: string\n\n /**\n * The conversation id for this chat, stable across sends and reloads. It is\n * the AG-UI thread key on the wire AND the key client persistence stores the\n * conversation under, so set a stable `threadId` to have a reload restore the\n * same conversation. If omitted, a unique thread id is generated per session.\n */\n threadId?: string\n\n /**\n * Initial resumable run state, useful when rehydrating a persisted client\n * after a full page reload. This restores the client-side interrupt\n * descriptors needed to send AG-UI resume entries.\n */\n initialResumeSnapshot?: ChatResumeSnapshot\n\n /**\n * Arbitrary client-controlled JSON forwarded to the server in the\n * AG-UI `RunAgentInput.forwardedProps` field. Use this for per-session\n * options like provider/model selection or feature flags that the\n * server endpoint should read.\n *\n * Replaces the legacy `body` option. If both are provided,\n * `forwardedProps` wins on key collision.\n */\n forwardedProps?: Record<string, any>\n\n /**\n * @deprecated Use `forwardedProps` instead. `body` continues to work\n * unchanged — its values are merged into the AG-UI\n * `RunAgentInput.forwardedProps` field on the wire and are also\n * mirrored under the legacy `data` field for servers that have not\n * migrated yet. Will be removed in a future major release.\n */\n body?: Record<string, any>\n\n /**\n * Client-local runtime context passed to client tool implementations.\n *\n * This value is not serialized to the server. Use `forwardedProps` for\n * explicit client-to-server handoff of serializable values.\n */\n context?: TContext\n\n /**\n * Callback when a response is received\n */\n onResponse?: (response?: Response) => void | Promise<void>\n\n /**\n * Callback when a stream chunk is received\n */\n onChunk?: (chunk: StreamChunk) => void\n\n /**\n * Callback when the response is finished\n */\n onFinish?: (message: UIMessage<TTools>) => void\n\n /**\n * Callback when an error occurs\n */\n onError?: (error: Error) => void\n\n /**\n * Callback when messages change\n */\n onMessagesChange?: (messages: Array<UIMessage<TTools>>) => void\n\n /**\n * Callback when loading state changes\n */\n onLoadingChange?: (isLoading: boolean) => void\n\n /**\n * Callback when error state changes\n */\n onErrorChange?: (error: Error | undefined) => void\n\n /**\n * Callback when chat status changes\n */\n onStatusChange?: (status: ChatClientState) => void\n\n /**\n * Callback when subscription lifecycle changes.\n * This is independent from request lifecycle (`isLoading`, `status`).\n */\n onSubscriptionChange?: (isSubscribed: boolean) => void\n\n /**\n * Callback when connection lifecycle changes.\n */\n onConnectionStatusChange?: (status: ConnectionStatus) => void\n\n /**\n * Callback when session generation activity changes.\n * Derived from stream run events (RUN_STARTED / RUN_FINISHED / RUN_ERROR).\n * Unlike `onLoadingChange` (request-local), this reflects shared generation\n * activity visible to all subscribers (e.g. across tabs/devices).\n */\n onSessionGeneratingChange?: (isGenerating: boolean) => void\n\n /**\n * Policy for messages sent while the client is busy (streaming, claiming\n * a send, or draining the queue). Accepts a `WhenBusy` string, a\n * `QueueConfig`, or a `QueueStrategy` function.\n * Default: `{ whenBusy: 'queue', drain: 'fifo' }`.\n * Queued items auto-send only after a **successful** settle; they are\n * discarded on error/abort, `stop()`, `clear()`, `unsubscribe()`, and\n * `reload()`.\n */\n queue?: QueueOption\n\n /**\n * Callback when the pending send queue changes (enqueue, cancel, drain,\n * or flush).\n */\n onQueueChange?: (queue: Array<QueuedMessage>) => void\n\n /**\n * Callback when resumable run state or pending interrupts change.\n */\n onResumeStateChange?: (\n resumeState: ChatResumeState | null,\n pendingInterrupts: BoundInterrupts<TTools>,\n ) => void\n\n /**\n * Callback when the id of the run this client has in flight changes: the new\n * id when a run starts (a send, or a `joinRun` rejoin), `null` when it settles.\n */\n onRunIdChange?: (runId: string | null) => void\n\n /** Callback when the immutable interrupt state snapshot changes. */\n onInterruptStateChange?: (state: ChatInterruptState<TTools>) => void\n\n /**\n * Callback when a custom event is received from a server-side tool.\n * Custom events are emitted by tools using `context.emitCustomEvent()` during execution.\n *\n * @param eventType - The name of the custom event\n * @param data - The event payload data\n * @param context - Additional context including the toolCallId that emitted the event\n */\n onCustomEvent?: (\n eventType: string,\n data: unknown,\n context: { toolCallId?: string },\n ) => void\n\n /**\n * Client-side tools with execution logic\n * When provided, tools with execute functions will be called automatically\n */\n tools?: TTools\n\n /**\n * Devtools hook metadata for this client instance.\n */\n devtools?: Partial<AIDevtoolsClientMetadata>\n\n /**\n * Factory that constructs the devtools bridge. Default is a no-op\n * factory, which keeps `@tanstack/ai-client/devtools` (the heavy\n * bridge implementation) out of the main entry's bundle. Frameworks\n * that need live devtools should pass the real factory from\n * `@tanstack/ai-client/devtools`.\n */\n devtoolsBridgeFactory?: ChatDevtoolsBridgeFactory\n\n /**\n * Stream processing options (optional)\n * Configure chunking strategy\n */\n streamProcessor?: {\n /**\n * Strategy for when to emit text updates\n * Defaults to ImmediateStrategy (every chunk)\n */\n chunkStrategy?: ChunkStrategy\n }\n}\n\n/**\n * Options for `ChatClient`. Exactly one of `connection` or `fetcher` must be\n * provided — the type-level XOR is enforced via `ChatTransport`.\n */\nexport type ChatClientOptions<\n TTools extends ReadonlyArray<AnyClientTool> = any,\n TContext = InferredClientContext<TTools>,\n> = DistributedOmit<ChatClientBaseOptions<TTools, TContext>, 'context'> &\n ClientContextOptionFromTools<TTools, TContext> &\n ChatTransport\n\nexport interface ChatRequestBody {\n messages: Array<ModelMessage>\n data?: Record<string, any>\n}\n\n/**\n * Create a typed array of client tools with proper type inference.\n * This eliminates the need for `as const` when defining tool arrays.\n *\n * @example\n * ```ts\n * const tools = clientTools(\n * myTool1.client(() => result1),\n * myTool2.client(() => result2),\n * )\n *\n * // tools is now properly typed as a tuple with literal tool names\n * // This enables type narrowing when checking part.name === 'toolName'\n * ```\n */\nexport function clientTools<const T extends Array<AnyClientTool>>(\n ...tools: T\n): T {\n return tools\n}\n\n/**\n * Helper to create typed chat client options\n * Use this to get proper type inference for messages\n *\n * @example\n * ```ts\n * const tools = clientTools(myTool1, myTool2)\n *\n * const chatOptions = createChatClientOptions({\n * connection: fetchServerSentEvents('/api/chat'),\n * tools,\n * })\n *\n * type MyMessages = InferChatMessages<typeof chatOptions>\n * ```\n */\nexport function createChatClientOptions<\n const TTools extends ReadonlyArray<AnyClientTool>,\n TContext = InferredClientContext<TTools>,\n>(\n options: ChatClientOptions<TTools, TContext>,\n): ChatClientOptions<TTools, TContext> {\n return options\n}\n\n/**\n * Extract the message type from chat options\n *\n * @example\n * ```ts\n * const chatOptions = createChatClientOptions({\n * connection: fetchServerSentEvents('/api/chat'),\n * tools: [myTool1, myTool2],\n * })\n *\n * type MyMessages = InferChatMessages<typeof chatOptions>\n * // MyMessages is now Array<UIMessage<[typeof myTool1, typeof myTool2]>>\n * ```\n */\nexport type InferChatMessages<T> =\n T extends ChatClientOptions<infer TTools, any>\n ? Array<UIMessage<TTools>>\n : never\n"],"mappings":";;;;;;;;;;;;;;;;AAm8BA,SAAgB,YACd,GAAG,OACA;CACH,OAAO;AACT;;;;;;;;;;;;;;;;;AAkBA,SAAgB,wBAId,SACqC;CACrC,OAAO;AACT"}
1
+ {"version":3,"file":"types.js","names":[],"sources":["../../src/types.ts"],"sourcesContent":["import type {\n AnyClientTool,\n ApprovalCapabilityOf,\n ApprovalSchemaOf,\n AudioPart,\n BatchInterruptError,\n ChunkStrategy,\n ContentPart,\n DocumentPart,\n ImagePart,\n InferSchemaType,\n InferToolInput,\n InferToolOutput,\n InputSchemaOf,\n Interrupt,\n InterruptBinding,\n ItemInterruptError,\n ModelMessage,\n NoSchema,\n RunAgentResumeItem,\n SchemaInput,\n StreamChunk,\n StructuredOutputPart,\n UIResourcePart,\n VideoPart,\n} from '@tanstack/ai/client'\nimport type { ConnectionAdapter } from './connection-adapters'\nimport type { AIDevtoolsClientMetadata } from './devtools'\nimport type { ChatDevtoolsBridgeFactory } from './devtools-noop'\n\nexport type { StructuredOutputPart }\n\nexport interface ChatResumeState {\n threadId: string\n runId: string\n}\n\nexport type ChatPendingInterrupt = Interrupt\n\n/**\n * The durable pointer a chat keeps for the run it may need to rejoin, plus any\n * interrupt that run is waiting on.\n *\n * @internal\n */\nexport interface ChatResumeSnapshot {\n resumeState: ChatResumeState\n pendingInterrupts?: Array<ChatPendingInterrupt>\n}\n\nexport type InterruptItemStatus =\n | 'pending'\n | 'validating'\n | 'staged'\n | 'submitting'\n | 'error'\n\nexport interface BoundInterruptBase {\n readonly id: string\n readonly interruptId: string\n readonly reason: string\n readonly message?: string\n readonly responseSchema?: Readonly<Record<string, unknown>>\n readonly expiresAt?: string\n readonly metadata?: Readonly<Record<string, unknown>>\n readonly threadId: string\n readonly interruptedRunId: string\n readonly generation: number\n readonly status: InterruptItemStatus\n readonly errors: ReadonlyArray<ItemInterruptError>\n /** @deprecated Use `errors[0]`. */\n readonly error?: ItemInterruptError\n /**\n * Whether the binding/schema allows resolution at hydrate time.\n * Does not flip on submit/expiry — gate UI on `status`, `resuming`, and\n * `errors` for those lifecycle states.\n */\n readonly canResolve: boolean\n cancel: () => void\n clearResolution: () => void\n}\n\nexport interface GenericAGUIInterrupt extends BoundInterruptBase {\n readonly kind: 'generic'\n readonly binding: Readonly<Extract<InterruptBinding, { kind: 'generic' }>>\n resolveInterrupt: (payload: unknown) => void\n}\n\n/**\n * An interrupt that arrived on the stream carrying no resume binding this\n * client understands — no `tanstack:interruptBinding`, or one written at a\n * protocol version we don't recognise.\n *\n * These are surfaced rather than hidden so a UI can show that the run is\n * paused, but they are never resolvable here: something else owns them. A\n * workflow engine's durable approval projected into the same AG-UI stream\n * lands in this bucket, and resolving it through the chat resume path would\n * send an answer no one is waiting for. Render it, or route it to whatever\n * actually owns the pause.\n */\nexport interface UnboundInterrupt extends BoundInterruptBase {\n readonly kind: 'unbound'\n readonly binding?: undefined\n readonly canResolve: false\n}\n\ntype ApprovalBranchSchema<TTool, TBranch extends 'approve' | 'reject'> =\n ApprovalSchemaOf<TTool> extends infer TApproval\n ? TApproval extends { approve?: SchemaInput; reject?: SchemaInput }\n ? Exclude<TApproval[TBranch], undefined>\n : TApproval extends SchemaInput\n ? TApproval\n : never\n : never\n\ntype ApprovalEdits<TTool> =\n InputSchemaOf<TTool> extends NoSchema\n ? { editedArgs?: never }\n : { editedArgs?: InferToolInput<TTool> }\n\ntype ApprovalPayload<TSchema> = [TSchema] extends [never]\n ? { payload?: never }\n : TSchema extends SchemaInput\n ? { payload: InferSchemaType<TSchema> }\n : { payload?: never }\n\ntype ApproveArguments<TTool> = [\n ApprovalBranchSchema<TTool, 'approve'>,\n] extends [never]\n ? InputSchemaOf<TTool> extends NoSchema\n ? [options?: never]\n : [options?: ApprovalEdits<TTool> & { payload?: never }]\n : [\n options: ApprovalEdits<TTool> &\n ApprovalPayload<ApprovalBranchSchema<TTool, 'approve'>>,\n ]\n\ntype RejectArguments<TTool> = [ApprovalBranchSchema<TTool, 'reject'>] extends [\n never,\n]\n ? [options?: never]\n : [\n options: { editedArgs?: never } & ApprovalPayload<\n ApprovalBranchSchema<TTool, 'reject'>\n >,\n ]\n\nexport type ToolApprovalInterrupt<TTool extends AnyClientTool = AnyClientTool> =\n TTool extends AnyClientTool\n ? BoundInterruptBase & {\n readonly kind: 'tool-approval'\n readonly binding: Readonly<\n Extract<InterruptBinding, { kind: 'tool-approval' }>\n >\n readonly toolName: TTool['name']\n readonly toolCallId: string\n readonly originalArgs: InferToolInput<TTool>\n // A single generic call signature — not two overloads. Overloads break\n // editor autocomplete: a half-typed options literal (e.g.\n // `resolveInterrupt(true, { payload: {` ) satisfies neither overload,\n // so TS resolves no signature and offers no contextual completions.\n // Making `approved` a generic discriminant lets TS infer it from the\n // first argument and pick the matching branch for the rest params, so\n // `payload` / `editedArgs` / the correct schema's fields complete\n // per-branch (a plain union-of-tuples would offer both branches'\n // fields) while still enforcing the right shape.\n resolveInterrupt: <TApproved extends boolean>(\n approved: TApproved,\n ...args: TApproved extends true\n ? ApproveArguments<TTool>\n : RejectArguments<TTool>\n ) => void\n }\n : never\n\ntype ApprovalInterrupts<TTools extends ReadonlyArray<AnyClientTool>> =\n TTools[number] extends infer TTool\n ? TTool extends AnyClientTool\n ? ApprovalCapabilityOf<TTool> extends true\n ? ToolApprovalInterrupt<TTool>\n : never\n : never\n : never\n\n// Client tools resolve through their `.client()` implementation (auto-run) or\n// `addToolResult` — never as a bound interrupt. The `client-tool-execution`\n// pause is handled internally and is intentionally absent from this public\n// union.\nexport type ChatInterrupt<\n TTools extends ReadonlyArray<AnyClientTool> = ReadonlyArray<AnyClientTool>,\n> = GenericAGUIInterrupt | UnboundInterrupt | ApprovalInterrupts<TTools>\n\nexport type BoundInterrupts<\n TTools extends ReadonlyArray<AnyClientTool> = ReadonlyArray<AnyClientTool>,\n> = ReadonlyArray<ChatInterrupt<TTools>>\n\nexport interface ChatInterruptState<\n TTools extends ReadonlyArray<AnyClientTool> = ReadonlyArray<AnyClientTool>,\n> {\n readonly interrupts: BoundInterrupts<TTools>\n /** @deprecated Use `interrupts`. Same snapshot today. */\n readonly pendingInterrupts: BoundInterrupts<TTools>\n readonly interruptErrors: ReadonlyArray<BatchInterruptError>\n readonly resuming: boolean\n}\n\n/**\n * `messages` is the full UIMessage history (not a delta). `data` is the\n * merged body — `ChatClientOptions.body` plus any per-call data passed to\n * `sendMessage(...)`. `threadId` / `runId` are the AG-UI correlation ids\n * the chat client uses to track this turn — forward them to your server\n * if it needs to correlate requests.\n */\nexport interface ChatFetcherInput {\n messages: Array<UIMessage>\n data?: Record<string, unknown>\n threadId: string\n runId: string\n parentRunId?: string\n resume?: Array<RunAgentResumeItem>\n}\n\nexport interface ChatFetcherOptions {\n /** Fires when `stop()` is called or the request is superseded. */\n signal: AbortSignal\n}\n\n/**\n * Direct function that performs a chat request. Mirrors\n * `GenerationFetcher`. Returns either a `Response` (SSE body parsed by the\n * chat client) or an `AsyncIterable<StreamChunk>` (yielded directly). May\n * return the value synchronously, as a `Promise`, or as an async generator\n * (`async function*`) — the chat client awaits whichever shape is returned.\n *\n * @example\n * ```ts\n * useChat({\n * fetcher: ({ messages }, { signal }) =>\n * chatFn({ data: { messages }, signal }),\n * })\n * ```\n */\nexport type ChatFetcher = (\n input: ChatFetcherInput,\n options: ChatFetcherOptions,\n) =>\n | Response\n | AsyncIterable<StreamChunk>\n | Promise<Response | AsyncIterable<StreamChunk>>\n\n/**\n * Distributive `Omit` — applies `Omit<O, K>` per branch of a union so\n * discriminated unions survive omission. Plain `Omit` collapses unions\n * into a single object shape, which would erase the `ChatTransport` XOR\n * when framework hooks omit React-managed callbacks from\n * `ChatClientOptions`.\n */\nexport type DistributedOmit<\n TObject,\n TKeys extends keyof any,\n> = TObject extends unknown ? Omit<TObject, TKeys> : never\n\n/**\n * Discriminated union enforcing that exactly one of `connection` or\n * `fetcher` is provided. Mirrors `GenerationTransport`.\n */\nexport type ChatTransport =\n | { connection: ConnectionAdapter; fetcher?: never }\n | { fetcher: ChatFetcher; connection?: never }\n\n/**\n * Tool call states - track the lifecycle of a tool call\n */\nexport type ToolCallState =\n | 'awaiting-input' // Received start but no arguments yet\n | 'input-streaming' // Partial arguments received\n | 'input-complete' // All arguments received\n | 'approval-requested' // Waiting for user approval\n | 'approval-responded' // User has approved/denied\n | 'complete' // Result is complete\n | 'error' // Tool execution failed (terminal)\n\n/**\n * Tool result states - track the lifecycle of a tool result\n */\nexport type ToolResultState =\n | 'streaming' // Placeholder for future streamed output\n | 'complete' // Result is complete\n | 'error' // Error occurred\n\n/**\n * ChatClient state - track the lifecycle of a chat\n */\nexport type ChatClientState = 'ready' | 'submitted' | 'streaming' | 'error'\n\n/**\n * Connection lifecycle state for the subscription loop.\n */\nexport type ConnectionStatus =\n | 'disconnected'\n | 'connecting'\n | 'connected'\n | 'error'\n\n/**\n * Multimodal content input for sending messages with rich media.\n * Allows sending text, images, audio, video, and documents to the LLM.\n *\n * @example\n * ```ts\n * // Send an image with a question\n * client.sendMessage({\n * content: [\n * { type: 'text', content: 'What is in this image?' },\n * { type: 'image', source: { type: 'url', value: 'https://example.com/photo.jpg' } }\n * ],\n * id: 'custom-message-id' // optional\n * })\n * ```\n */\nexport interface MultimodalContent {\n /**\n * The content of the message.\n * Can be a simple string or an array of content parts for multimodal messages.\n */\n content: string | Array<ContentPart>\n /**\n * Optional custom ID for the message.\n * If not provided, a unique ID will be generated.\n */\n id?: string\n}\n\n/**\n * Action taken when `sendMessage` is called while the client is busy\n * (streaming, claiming a send, or draining the queue).\n * - `queue`: hold the message; it auto-sends when the current run settles\n * **successfully**.\n * - `drop`: ignore the send (promise still resolves; does not throw).\n * - `interrupt`: abort the current stream and send immediately. Unlike\n * `stop()`, does **not** flush already-queued messages — they still drain\n * after the interrupting send settles successfully.\n */\nexport type WhenBusy = 'queue' | 'drop' | 'interrupt'\n\n/**\n * Why the client is busy when a {@link QueueStrategy} runs.\n * - `streaming` — an LLM stream is active (`isLoading`).\n * - `sendInFlight` — a send has claimed the client but is not yet loading.\n * - `draining` — the queue drain loop is delivering pending messages.\n */\nexport type QueueBusyReason = 'streaming' | 'sendInFlight' | 'draining'\n\n/**\n * A user message held in the send queue while a stream is active.\n * Rendered separately from `messages`; cancellable via `cancelQueued(id)`\n * until it drains.\n */\nexport interface QueuedMessage {\n id: string\n content: string | MultimodalContent\n createdAt: number\n}\n\n/**\n * Declarative queue policy.\n */\nexport interface QueueConfig {\n /**\n * Action when the client is busy (streaming, claiming a send, or draining).\n * Default `'queue'`.\n */\n whenBusy?: WhenBusy\n /**\n * How queued items leave the queue.\n * - `'fifo'`: one at a time, in order (default).\n * - `'batch'`: merge all queued items into one send when the run settles\n * successfully.\n */\n drain?: 'fifo' | 'batch'\n /** Max queued items. Unlimited when omitted. `0` means never queue. */\n maxSize?: number\n /**\n * Behavior when `maxSize` is reached. Default `'reject'`.\n * `'reject'` silently discards the new send (does not throw);\n * `'drop-oldest'` evicts the oldest queued item to make room.\n * Only meaningful when `maxSize` is set.\n */\n onOverflow?: 'reject' | 'drop-oldest'\n}\n\n/**\n * Escape hatch: decide the action for a single send. Drain stays FIFO for the\n * function form (no `batch` via function). Per-call `sendOptions.whenBusy`\n * overrides the strategy for that send.\n *\n * Actions match {@link WhenBusy}: `'queue' | 'drop' | 'interrupt'`. Concurrent\n * streams are not supported. `pending.id` is the id that will be stored if the\n * action is `'queue'` (safe to pass to `cancelQueued`).\n */\nexport type QueueStrategy = (ctx: {\n pending: QueuedMessage\n busyReason: QueueBusyReason\n queued: ReadonlyArray<QueuedMessage>\n}) => { action: WhenBusy }\n\n/** A `WhenBusy` shorthand, a full config, or a strategy function. */\nexport type QueueOption = WhenBusy | QueueConfig | QueueStrategy\n\n/** Per-call overrides for `sendMessage`. */\nexport interface SendMessageOptions {\n /** Overrides the configured `whenBusy` for this one send. */\n whenBusy?: WhenBusy\n}\n\n/**\n * Message parts - building blocks of UIMessage\n */\nexport interface TextPart {\n type: 'text'\n content: string\n}\n\n/**\n * Helper type that creates a tool-call part for a specific tool.\n * This is a conditional type to enable proper distribution over union types,\n * creating a discriminated union where `name` is the discriminant.\n */\ntype ToolCallPartForTool<T> = T extends AnyClientTool\n ? {\n type: 'tool-call'\n id: string\n name: T['name']\n arguments: string // JSON string (may be incomplete)\n /** Parsed tool input (typed from inputSchema) */\n input?: InferToolInput<T>\n state: ToolCallState\n /** Tool execution output (for client tools or after approval) */\n output?: InferToolOutput<T>\n } & (NonNullable<T['needsApproval']> extends true\n ? {\n /**\n * Approval metadata — present only on tools defined with\n * `needsApproval: true`. Populated once the call reaches\n * `state: 'approval-requested'`. `needsApproval` is an optional\n * property on the tool, so we index into it (rather than\n * `T extends { needsApproval: true }`, which an optional property\n * never satisfies) and strip `undefined` before comparing to `true`.\n */\n approval?: {\n id: string // Unique approval ID\n needsApproval: boolean // Always true if present\n approved?: boolean // User's decision (undefined until responded)\n }\n }\n : // Tools without `needsApproval: true` never carry an approval field.\n // `& unknown` is a no-op intersection (adds nothing).\n unknown)\n : never\n\n/**\n * Fallback tool-call part type when tools are not typed\n */\ntype UntypedToolCallPart = {\n type: 'tool-call'\n id: string\n name: string\n arguments: string\n input?: any\n state: ToolCallState\n approval?: {\n id: string\n needsApproval: boolean\n approved?: boolean\n }\n output?: any\n}\n\n/**\n * Tool call part that creates a proper discriminated union.\n * When TTools is typed, checking `part.name === 'toolName'` will narrow\n * `part.output` to the correct type for that tool.\n *\n * The discriminant is `name`, so code like:\n * ```ts\n * if (part.name === 'recommendGuitar') {\n * // part.output is now typed to the recommendGuitar tool's output\n * }\n * ```\n */\nexport type ToolCallPart<TTools extends ReadonlyArray<AnyClientTool> = any> =\n // Check if we have a concrete tools array (not 'any' or 'never')\n [TTools] extends [never]\n ? UntypedToolCallPart\n : unknown extends TTools\n ? UntypedToolCallPart\n : TTools extends ReadonlyArray<infer Tool>\n ? Tool extends AnyClientTool\n ? ToolCallPartForTool<Tool>\n : UntypedToolCallPart\n : UntypedToolCallPart\n\nexport interface ToolResultPart {\n type: 'tool-result'\n toolCallId: string\n content: string | Array<ContentPart>\n state: ToolResultState\n error?: string // Error message if state is \"error\"\n}\n\nexport interface ThinkingPart {\n type: 'thinking'\n content: string\n}\n\nexport type MessagePart<\n TTools extends ReadonlyArray<AnyClientTool> = any,\n TData = unknown,\n> =\n | TextPart\n | ImagePart\n | AudioPart\n | VideoPart\n | DocumentPart\n | ToolCallPart<TTools>\n | ToolResultPart\n | ThinkingPart\n | StructuredOutputPart<TData>\n | UIResourcePart\n\n/**\n * UIMessage - Domain-specific message format optimized for building chat UIs\n * Contains parts that can be text, tool calls, or tool results.\n *\n * `TTools` narrows the tool-call/result part types based on the registered\n * tools. `TData` is the schema-inferred type for any `structured-output` part\n * on the message — defaulted to `unknown` so untyped consumers (the core\n * stream processor, the wire converter) don't need to thread a schema generic\n * everywhere; the hook layer (`useChat({ outputSchema })`) substitutes it on\n * the public return so `m.parts.find(p => p.type === 'structured-output').data`\n * is typed without manual casts.\n */\nexport interface UIMessage<\n TTools extends ReadonlyArray<AnyClientTool> = any,\n TData = unknown,\n> {\n id: string\n role: 'system' | 'user' | 'assistant'\n parts: Array<MessagePart<TTools, TData>>\n createdAt?: Date\n}\n\n/**\n * A generic key/value storage adapter. `getItem` may be sync or async; the\n * chat persistence layer treats every call as best-effort. The provided\n * `localStoragePersistence` / `sessionStoragePersistence` / `indexedDBPersistence`\n * factories return one of these, and `ChatStorageAdapter<ChatPersistedState>`\n * is assignable to {@link ChatClientPersistence}.\n */\nexport interface ChatStorageAdapter<TValue> {\n getItem: (\n id: string,\n ) => TValue | null | undefined | Promise<TValue | null | undefined>\n setItem: (id: string, value: TValue) => void | Promise<void>\n removeItem: (id: string) => void | Promise<void>\n}\n\n/**\n * The single record a `ChatClientPersistence` adapter stores per chat. It folds\n * the two things that must survive a full page reload into one blob under one\n * key: the message transcript and the optional resume snapshot (which run to\n * rejoin / which interrupts to rehydrate). One adapter, one key — see\n * {@link ChatClientPersistence}.\n */\nexport interface ChatPersistedState<\n TTools extends ReadonlyArray<AnyClientTool> = any,\n> {\n messages: Array<UIMessage<TTools>>\n /** Present while a run is in flight or paused on an interrupt; absent otherwise. */\n resume?: ChatResumeSnapshot\n}\n\n/**\n * Storage adapter for durable chat state. A single adapter persists both the\n * message transcript and the resume snapshot as one {@link ChatPersistedState}\n * record, so a full page reload restores the conversation AND can rejoin an\n * in-flight run / rehydrate pending interrupts.\n *\n * For backward compatibility `getItem` may also return a bare `UIMessage[]`\n * (the legacy messages-only format); the client normalizes it to\n * `{ messages }`. `setItem` always writes the combined record.\n */\nexport interface ChatClientPersistence<\n TTools extends ReadonlyArray<AnyClientTool> = any,\n> {\n getItem: (\n id: string,\n ) =>\n | ChatPersistedState<TTools>\n | Array<UIMessage<TTools>>\n | null\n | undefined\n | Promise<\n ChatPersistedState<TTools> | Array<UIMessage<TTools>> | null | undefined\n >\n setItem: (\n id: string,\n state: ChatPersistedState<TTools>,\n ) => void | Promise<void>\n removeItem: (id: string) => void | Promise<void>\n}\n\n/**\n * The `persistence` option for a chat.\n *\n * - `false` (default): ephemeral. Messages live in memory only; a reload starts\n * from empty.\n * - `true`: server-authoritative. Nothing is cached in the browser. On mount the\n * client hydrates the thread from the server by its `threadId` (paints the\n * stored transcript and tails any run still generating), so a reload or the\n * same thread opened on another device both just resume. Requires a connection\n * with a `hydrate` handler.\n * - a {@link ChatClientPersistence} adapter: client-authoritative. The combined\n * {@link ChatPersistedState} record (transcript plus resume pointer) is cached\n * in the browser and restored on reload with no network.\n */\nexport type ChatPersistenceOption<\n TTools extends ReadonlyArray<AnyClientTool> = any,\n> = boolean | ChatClientPersistence<TTools>\n\n/**\n * The `persistence` / `threadId` pairing for `ChatClient` and the chat hooks.\n *\n * Persistence that is on (`true` or a storage adapter) requires a `threadId`.\n * A minted id changes every reload, so nothing would restore. The compiler\n * asks for the conversation id instead.\n *\n * Omit `persistence`, or set it to `false`, and `threadId` stays optional.\n * The client then mints one after mount for the wire and DevTools.\n *\n * Intersect this onto `ChatClientOptions`. Do not apply a later plain `Omit`\n * to that type: it collapses the union and the requirement disappears. Use\n * {@link DistributedOmit}.\n */\nexport type ChatPersistenceOptions<\n TTools extends ReadonlyArray<AnyClientTool> = any,\n> =\n | {\n persistence: true\n threadId: string\n }\n | {\n persistence: ChatClientPersistence<TTools>\n threadId: string\n }\n | {\n persistence?: false | undefined\n threadId?: string\n }\n\ntype IsUnknown<T> = unknown extends T\n ? [T] extends [unknown]\n ? true\n : false\n : false\n\ntype KnownContext<T> = IsUnknown<T> extends true ? never : T\n\ntype MergeContext<TLeft, TRight> = [TLeft] extends [never]\n ? TRight\n : [TRight] extends [never]\n ? TLeft\n : TLeft & TRight\n\ntype UnionToIntersection<T> = [T] extends [never]\n ? never\n : (T extends unknown ? (value: T) => void : never) extends (\n value: infer TIntersection,\n ) => void\n ? TIntersection\n : never\n\ntype DefinedContext<T> = Exclude<T, undefined>\n\ntype ContextFromExecute<T> = T extends (...args: any) => any\n ? NonNullable<Parameters<T>[1]> extends { context: infer TContext }\n ? KnownContext<TContext>\n : never\n : never\n\ntype ContextFromClientTool<T> = T extends AnyClientTool\n ? T extends { execute?: infer TExecute }\n ? ContextFromExecute<TExecute>\n : never\n : never\n\ntype RequiredContextFromClientToolUnion<T> = T extends unknown\n ? undefined extends ContextFromClientTool<T>\n ? never\n : ContextFromClientTool<T>\n : never\n\ntype ContextFromClientToolUnion<T> = [\n UnionToIntersection<DefinedContext<ContextFromClientTool<T>>>,\n] extends [never]\n ? never\n : [RequiredContextFromClientToolUnion<T>] extends [never]\n ? UnionToIntersection<DefinedContext<ContextFromClientTool<T>>> | undefined\n : UnionToIntersection<DefinedContext<ContextFromClientTool<T>>>\n\ntype ContextFromClientTools<TTools> =\n IsUnknown<TTools> extends true\n ? never\n : TTools extends readonly [infer THead, ...infer TTail]\n ? MergeContext<\n ContextFromClientTool<THead>,\n ContextFromClientTools<TTail>\n >\n : TTools extends ReadonlyArray<infer TItem>\n ? ContextFromClientToolUnion<TItem>\n : never\n\nexport type InferredClientContext<TTools> = [\n ContextFromClientTools<TTools>,\n] extends [never]\n ? unknown\n : ContextFromClientTools<TTools>\n\nexport type ClientContextOptionFromTools<TTools, TContext> = [\n ContextFromClientTools<TTools>,\n] extends [never]\n ? { context?: TContext }\n : undefined extends ContextFromClientTools<TTools>\n ? { context?: TContext & ContextFromClientTools<TTools> }\n : { context: TContext & ContextFromClientTools<TTools> }\n\n/**\n * Base options for `ChatClient`, excluding the transport (`connection` or\n * `fetcher`) which is supplied separately via `ChatTransport` so the XOR\n * is preserved when composing the final `ChatClientOptions` type.\n */\nexport interface ChatClientBaseOptions<\n TTools extends ReadonlyArray<AnyClientTool> = any,\n TContext = unknown,\n> {\n /**\n * Initial messages to populate the chat\n */\n initialMessages?: Array<UIMessage<TTools>>\n\n /**\n * Initial resumable run state, useful when rehydrating a persisted client\n * after a full page reload. This restores the client-side interrupt\n * descriptors needed to send AG-UI resume entries.\n */\n initialResumeSnapshot?: ChatResumeSnapshot\n\n /**\n * Arbitrary client-controlled JSON forwarded to the server in the\n * AG-UI `RunAgentInput.forwardedProps` field. Use this for per-session\n * options like provider/model selection or feature flags that the\n * server endpoint should read.\n *\n * Replaces the legacy `body` option. If both are provided,\n * `forwardedProps` wins on key collision.\n */\n forwardedProps?: Record<string, any>\n\n /**\n * @deprecated Use `forwardedProps` instead. `body` continues to work\n * unchanged — its values are merged into the AG-UI\n * `RunAgentInput.forwardedProps` field on the wire and are also\n * mirrored under the legacy `data` field for servers that have not\n * migrated yet. Will be removed in a future major release.\n */\n body?: Record<string, any>\n\n /**\n * Client-local runtime context passed to client tool implementations.\n *\n * This value is not serialized to the server. Use `forwardedProps` for\n * explicit client-to-server handoff of serializable values.\n */\n context?: TContext\n\n /**\n * Callback when a response is received\n */\n onResponse?: (response?: Response) => void | Promise<void>\n\n /**\n * Callback when a stream chunk is received\n */\n onChunk?: (chunk: StreamChunk) => void\n\n /**\n * Callback when the response is finished\n */\n onFinish?: (message: UIMessage<TTools>) => void\n\n /**\n * Callback when an error occurs\n */\n onError?: (error: Error) => void\n\n /**\n * Callback when messages change\n */\n onMessagesChange?: (messages: Array<UIMessage<TTools>>) => void\n\n /**\n * Callback when loading state changes\n */\n onLoadingChange?: (isLoading: boolean) => void\n\n /**\n * Callback when error state changes\n */\n onErrorChange?: (error: Error | undefined) => void\n\n /**\n * Callback when chat status changes\n */\n onStatusChange?: (status: ChatClientState) => void\n\n /**\n * Callback when subscription lifecycle changes.\n * This is independent from request lifecycle (`isLoading`, `status`).\n */\n onSubscriptionChange?: (isSubscribed: boolean) => void\n\n /**\n * Callback when connection lifecycle changes.\n */\n onConnectionStatusChange?: (status: ConnectionStatus) => void\n\n /**\n * Callback when session generation activity changes.\n * Derived from stream run events (RUN_STARTED / RUN_FINISHED / RUN_ERROR).\n * Unlike `onLoadingChange` (request-local), this reflects shared generation\n * activity visible to all subscribers (e.g. across tabs/devices).\n */\n onSessionGeneratingChange?: (isGenerating: boolean) => void\n\n /**\n * Policy for messages sent while the client is busy (streaming, claiming\n * a send, or draining the queue). Accepts a `WhenBusy` string, a\n * `QueueConfig`, or a `QueueStrategy` function.\n * Default: `{ whenBusy: 'queue', drain: 'fifo' }`.\n * Queued items auto-send only after a **successful** settle; they are\n * discarded on error/abort, `stop()`, `clear()`, `unsubscribe()`, and\n * `reload()`.\n */\n queue?: QueueOption\n\n /**\n * Callback when the pending send queue changes (enqueue, cancel, drain,\n * or flush).\n */\n onQueueChange?: (queue: Array<QueuedMessage>) => void\n\n /**\n * Callback when resumable run state or pending interrupts change.\n */\n onResumeStateChange?: (\n resumeState: ChatResumeState | null,\n pendingInterrupts: BoundInterrupts<TTools>,\n ) => void\n\n /**\n * Callback when the id of the run this client has in flight changes: the new\n * id when a run starts (a send, or a `joinRun` rejoin), `null` when it settles.\n */\n onRunIdChange?: (runId: string | null) => void\n\n /** Callback when the immutable interrupt state snapshot changes. */\n onInterruptStateChange?: (state: ChatInterruptState<TTools>) => void\n\n /**\n * Callback when a custom event is received from a server-side tool.\n * Custom events are emitted by tools using `context.emitCustomEvent()` during execution.\n *\n * @param eventType - The name of the custom event\n * @param data - The event payload data\n * @param context - Additional context including the toolCallId that emitted the event\n */\n onCustomEvent?: (\n eventType: string,\n data: unknown,\n context: { toolCallId?: string },\n ) => void\n\n /**\n * Client-side tools with execution logic\n * When provided, tools with execute functions will be called automatically\n */\n tools?: TTools\n\n /**\n * Devtools hook metadata for this client instance.\n */\n devtools?: Partial<AIDevtoolsClientMetadata>\n\n /**\n * Factory that constructs the devtools bridge. Default is a no-op\n * factory, which keeps `@tanstack/ai-client/devtools` (the heavy\n * bridge implementation) out of the main entry's bundle. Frameworks\n * that need live devtools should pass the real factory from\n * `@tanstack/ai-client/devtools`.\n */\n devtoolsBridgeFactory?: ChatDevtoolsBridgeFactory\n\n /**\n * Stream processing options (optional)\n * Configure chunking strategy\n */\n streamProcessor?: {\n /**\n * Strategy for when to emit text updates\n * Defaults to ImmediateStrategy (every chunk)\n */\n chunkStrategy?: ChunkStrategy\n }\n}\n\n/**\n * Options for `ChatClient`. Exactly one of `connection` or `fetcher` must be\n * provided — the type-level XOR is enforced via `ChatTransport`. Persistence\n * that is on requires a `threadId` via {@link ChatPersistenceOptions}.\n */\nexport type ChatClientOptions<\n TTools extends ReadonlyArray<AnyClientTool> = any,\n TContext = InferredClientContext<TTools>,\n> = DistributedOmit<ChatClientBaseOptions<TTools, TContext>, 'context'> &\n ClientContextOptionFromTools<TTools, TContext> &\n ChatTransport &\n ChatPersistenceOptions<TTools>\n\nexport interface ChatRequestBody {\n messages: Array<ModelMessage>\n data?: Record<string, any>\n}\n\n/**\n * Create a typed array of client tools with proper type inference.\n * This eliminates the need for `as const` when defining tool arrays.\n *\n * @example\n * ```ts\n * const tools = clientTools(\n * myTool1.client(() => result1),\n * myTool2.client(() => result2),\n * )\n *\n * // tools is now properly typed as a tuple with literal tool names\n * // This enables type narrowing when checking part.name === 'toolName'\n * ```\n */\nexport function clientTools<const T extends Array<AnyClientTool>>(\n ...tools: T\n): T {\n return tools\n}\n\n/**\n * Helper to create typed chat client options\n * Use this to get proper type inference for messages\n *\n * @example\n * ```ts\n * const tools = clientTools(myTool1, myTool2)\n *\n * const chatOptions = createChatClientOptions({\n * connection: fetchServerSentEvents('/api/chat'),\n * tools,\n * })\n *\n * type MyMessages = InferChatMessages<typeof chatOptions>\n * ```\n */\nexport function createChatClientOptions<\n const TTools extends ReadonlyArray<AnyClientTool>,\n TContext = InferredClientContext<TTools>,\n>(\n options: ChatClientOptions<TTools, TContext>,\n): ChatClientOptions<TTools, TContext> {\n return options\n}\n\n/**\n * Extract the message type from chat options\n *\n * @example\n * ```ts\n * const chatOptions = createChatClientOptions({\n * connection: fetchServerSentEvents('/api/chat'),\n * tools: [myTool1, myTool2],\n * })\n *\n * type MyMessages = InferChatMessages<typeof chatOptions>\n * // MyMessages is now Array<UIMessage<[typeof myTool1, typeof myTool2]>>\n * ```\n */\nexport type InferChatMessages<T> =\n T extends ChatClientOptions<infer TTools, any>\n ? Array<UIMessage<TTools>>\n : never\n"],"mappings":";;;;;;;;;;;;;;;;AA87BA,SAAgB,YACd,GAAG,OACA;CACH,OAAO;AACT;;;;;;;;;;;;;;;;;AAkBA,SAAgB,wBAId,SACqC;CACrC,OAAO;AACT"}
@@ -1,5 +1,4 @@
1
- import { ConnectConnectionAdapter } from './connection-adapters.js';
2
- import { GenerationClientState, GenerationFetcher, GenerationResumeSnapshot, VideoGenerateInput, VideoGenerateResult, VideoGenerationClientOptions, VideoStatusInfo } from './generation-types.js';
1
+ import { GenerationClientState, GenerationPersistenceOptions, GenerationResumeSnapshot, GenerationTransport, VideoGenerateInput, VideoGenerateResult, VideoGenerationClientOptions, VideoStatusInfo } from './generation-types.js';
3
2
  /**
4
3
  * A specialized client for job-based video generation.
5
4
  *
@@ -40,10 +39,10 @@ export declare class VideoGenerationClient<TOutput = VideoGenerateResult> {
40
39
  private readonly hydrateGenerationHandler;
41
40
  private readonly joinRunHandler;
42
41
  private readonly fetcher;
43
- private readonly uniqueId;
42
+ private uniqueId;
44
43
  private readonly devtoolsMetadata;
45
44
  private readonly devtoolsBridge;
46
- private readonly threadId;
45
+ private threadId;
47
46
  private readonly serverDriven;
48
47
  private body;
49
48
  private result;
@@ -61,13 +60,7 @@ export declare class VideoGenerationClient<TOutput = VideoGenerateResult> {
61
60
  private devtoolsMounted;
62
61
  private disposed;
63
62
  private serverHydrationStarted;
64
- constructor(options: VideoGenerationClientOptions<TOutput> & ({
65
- connection: ConnectConnectionAdapter;
66
- fetcher?: never;
67
- } | {
68
- fetcher: GenerationFetcher<VideoGenerateInput, VideoGenerateResult>;
69
- connection?: never;
70
- }));
63
+ constructor(options: Omit<VideoGenerationClientOptions<TOutput>, 'persistence' | 'threadId'> & GenerationPersistenceOptions & GenerationTransport<VideoGenerateInput, VideoGenerateResult>);
71
64
  private buildDevtoolsBridgeOptions;
72
65
  mountDevtools(): void;
73
66
  /**
@@ -121,6 +114,7 @@ export declare class VideoGenerationClient<TOutput = VideoGenerateResult> {
121
114
  private setProgress;
122
115
  private createCompletedVideoStatus;
123
116
  private createDevtoolsMetadata;
117
+ private ensureThreadId;
124
118
  private generateUniqueId;
125
119
  private createRunContext;
126
120
  private observeResumeSnapshot;
@@ -64,8 +64,8 @@ var VideoGenerationClient = class {
64
64
  disposed = false;
65
65
  serverHydrationStarted = false;
66
66
  constructor(options) {
67
- this.uniqueId = options.threadId ?? options.id ?? this.generateUniqueId("video");
68
- this.threadId = options.threadId ?? this.uniqueId;
67
+ this.threadId = options.threadId ?? "";
68
+ this.uniqueId = this.threadId;
69
69
  this.connection = options.connection;
70
70
  this.fetcher = options.fetcher;
71
71
  this.hydrateGenerationHandler = options.hydrateGeneration;
@@ -92,10 +92,17 @@ var VideoGenerationClient = class {
92
92
  this.devtoolsBridge = (options.devtoolsBridgeFactory ?? createNoOpVideoDevtoolsBridge)(this.buildDevtoolsBridgeOptions());
93
93
  }
94
94
  buildDevtoolsBridgeOptions() {
95
+ const client = this;
95
96
  return {
96
- hookId: this.uniqueId,
97
- clientId: this.uniqueId,
98
- threadId: this.threadId,
97
+ get hookId() {
98
+ return client.uniqueId;
99
+ },
100
+ get clientId() {
101
+ return client.uniqueId;
102
+ },
103
+ get threadId() {
104
+ return client.threadId;
105
+ },
99
106
  metadata: this.devtoolsMetadata,
100
107
  getCoreState: () => ({
101
108
  input: this.input,
@@ -110,6 +117,7 @@ var VideoGenerationClient = class {
110
117
  };
111
118
  }
112
119
  mountDevtools() {
120
+ this.ensureThreadId();
113
121
  this.disposed = false;
114
122
  this.maybeHydrateFromServer();
115
123
  this.maybeResumeInFlight();
@@ -228,7 +236,6 @@ var VideoGenerationClient = class {
228
236
  const msg = chunk.message || chunk.error?.message || "An error occurred";
229
237
  throw new Error(msg);
230
238
  }
231
- default: break;
232
239
  }
233
240
  }
234
241
  if (!sawTerminalChunk && !signal.aborted) throw new Error(GENERATION_STREAM_TRUNCATED_MESSAGE);
@@ -407,6 +414,11 @@ var VideoGenerationClient = class {
407
414
  ...metadata?.name ? { name: metadata.name } : {}
408
415
  };
409
416
  }
417
+ ensureThreadId() {
418
+ if (!this.threadId) this.threadId = this.generateUniqueId("video");
419
+ this.uniqueId = this.threadId;
420
+ return this.threadId;
421
+ }
410
422
  generateUniqueId(prefix) {
411
423
  return `${prefix}-${Date.now()}-${Math.random().toString(36).substring(7)}`;
412
424
  }