@tanstack/ai-client 0.33.2 → 0.34.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.
@@ -10,7 +10,7 @@ export type { RegisterWebMCPToolsOptions, WebMCPToolAnnotations, WebMCPToolOptio
10
10
  export { RealtimeClient } from './realtime-client.js';
11
11
  export { GenerationClient } from './generation-client.js';
12
12
  export { VideoGenerationClient } from './video-generation-client.js';
13
- export type { UIMessage, MessagePart, TextPart, ToolCallPart, ToolResultPart, ThinkingPart, StructuredOutputPart, ChatClientPersistence, ChatPersistedState, ChatPersistenceOption, ChatPersistenceOptions, ChatStorageAdapter, ChatClientOptions, ChatPendingInterrupt, BoundInterruptBase, BoundInterrupts, ChatInterrupt, ChatInterruptState, GenericAGUIInterrupt, GenericInterrupt, RegisteredGenericInterrupt, ResolvableChatInterrupt, 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';
13
+ export type { UIMessage, MessagePart, TextPart, ToolCallPart, ToolResultPart, ThinkingPart, StructuredOutputPart, SubagentPart, SubagentPartOf, SubagentHandle, SubagentHandleOf, SubagentHandles, SubagentClientAgent, SubagentStatus, ChatClientPersistence, ChatPersistedState, ChatPersistenceOption, ChatPersistenceOptions, ChatStorageAdapter, ChatClientOptions, ChatPendingInterrupt, BoundInterruptBase, BoundInterrupts, ChatInterrupt, ChatInterruptState, GenericAGUIInterrupt, GenericInterrupt, RegisteredGenericInterrupt, ResolvableChatInterrupt, 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';
14
14
  export type { InferGenerationOutput, InferGenerationOutputFromReturn, GenerationClientState, GenerationPersistenceOptions, GenerationClientOptions, GenerationFetcher, GenerationFetcherOptions, GenerationTransport, VideoGenerationClientOptions, VideoStatusInfo, VideoGenerateResult, ImageGenerateInput, AudioGenerateInput, SpeechGenerateInput, TranscriptionGenerateInput, SummarizeGenerateInput, VideoGenerateInput, GenerationRestoredResult, } from './generation-types.js';
15
15
  export { GENERATION_EVENTS } from './generation-types.js';
16
16
  export { reconstructImageResult, reconstructAudioResult, reconstructSpeechResult, reconstructTranscriptionResult, reconstructSummarizeResult, } from './generation-reconstruct.js';
@@ -1,4 +1,4 @@
1
- import { AnyClientTool, ApprovalCapabilityOf, ApprovalSchemaOf, AudioPart, BatchInterruptError, ChunkStrategy, ContentPart, DocumentPart, ImagePart, InferSchemaType, InterruptDefinition, InferToolInput, InferToolOutput, InputSchemaOf, Interrupt, InterruptBinding, ItemInterruptError, ModelMessage, NoSchema, RunAgentResumeItem, SchemaInput, StreamChunk, StructuredOutputPart, UIResourcePart, VideoPart } from '@tanstack/ai/client';
1
+ import { AnyClientTool, ApprovalCapabilityOf, ApprovalSchemaOf, AudioPart, BatchInterruptError, ChunkStrategy, ContentPart, DocumentPart, ImagePart, InferSchemaType, InterruptDefinition, InferToolInput, InferToolOutput, InputSchemaOf, Interrupt, InterruptBinding, ItemInterruptError, ModelMessage, NoSchema, RunAgentResumeItem, SchemaInput, StreamChunk, StructuredOutputPart, SubagentHandleData, SubagentStatus, UIResourcePart, VideoPart } from '@tanstack/ai/client';
2
2
  import { ByokClient } from './byok.js';
3
3
  import { ConnectionAdapter } from './connection-adapters.js';
4
4
  import { AIDevtoolsClientMetadata } from './devtools.js';
@@ -343,6 +343,21 @@ export interface TextPart {
343
343
  type: 'text';
344
344
  content: string;
345
345
  }
346
+ /**
347
+ * Tool-call part for a bare `{ name }` tool, such as a server tool
348
+ * definition a subagent carries. No `approval` field.
349
+ */
350
+ type ToolCallPartForNamedTool<T extends {
351
+ name: string;
352
+ }> = {
353
+ type: 'tool-call';
354
+ id: string;
355
+ name: T['name'];
356
+ arguments: string;
357
+ input?: InferToolInput<T>;
358
+ state: ToolCallState;
359
+ output?: InferToolOutput<T>;
360
+ };
346
361
  /**
347
362
  * Helper type that creates a tool-call part for a specific tool.
348
363
  * This is a conditional type to enable proper distribution over union types,
@@ -372,7 +387,9 @@ type ToolCallPartForTool<T> = T extends AnyClientTool ? {
372
387
  needsApproval: boolean;
373
388
  approved?: boolean;
374
389
  };
375
- } : unknown) : never;
390
+ } : unknown) : T extends {
391
+ name: string;
392
+ } ? ToolCallPartForNamedTool<T> : never;
376
393
  /**
377
394
  * Fallback tool-call part type when tools are not typed
378
395
  */
@@ -402,9 +419,13 @@ type UntypedToolCallPart = {
402
419
  * }
403
420
  * ```
404
421
  */
405
- export type ToolCallPart<TTools extends ReadonlyArray<AnyClientTool> = any> = [
422
+ export type ToolCallPart<TTools extends ReadonlyArray<{
423
+ name: string;
424
+ }> = any> = [
406
425
  TTools
407
- ] extends [never] ? UntypedToolCallPart : unknown extends TTools ? UntypedToolCallPart : TTools extends ReadonlyArray<infer Tool> ? Tool extends AnyClientTool ? ToolCallPartForTool<Tool> : UntypedToolCallPart : UntypedToolCallPart;
426
+ ] extends [never] ? UntypedToolCallPart : unknown extends TTools ? UntypedToolCallPart : TTools extends ReadonlyArray<infer Tool> ? Tool extends {
427
+ name: string;
428
+ } ? ToolCallPartForTool<Tool> : UntypedToolCallPart : UntypedToolCallPart;
408
429
  export interface ToolResultPart {
409
430
  type: 'tool-result';
410
431
  id?: string;
@@ -420,7 +441,54 @@ export interface ThinkingPart {
420
441
  type: 'thinking';
421
442
  content: string;
422
443
  }
423
- export type MessagePart<TTools extends ReadonlyArray<AnyClientTool> = any, TData = unknown> = TextPart | ImagePart | AudioPart | VideoPart | DocumentPart | ToolCallPart<TTools> | ToolResultPart | ThinkingPart | StructuredOutputPart<TData> | UIResourcePart;
444
+ export type { SubagentStatus };
445
+ export interface SubagentHandle extends SubagentHandleData {
446
+ /**
447
+ * Set by ChatClient on every card it holds, streamed, restored, or initial,
448
+ * nested cards included. Calling it marks the card `error` (`Stopped`),
449
+ * ignores that child's later chunks until the same child starts again, and
450
+ * aborts the local request, parent stream included. A durable server run
451
+ * keeps going.
452
+ */
453
+ stop?: () => void;
454
+ }
455
+ export interface SubagentPart {
456
+ type: 'subagent';
457
+ subagent: SubagentHandle;
458
+ }
459
+ /**
460
+ * The slice of a server `defineAgent` result that the client reads for types.
461
+ * The client does not call `run`. Put tool definitions (from
462
+ * `toolDefinition`) in `tools` to type the child's tool calls and approvals.
463
+ */
464
+ export type SubagentClientAgent = {
465
+ name: string;
466
+ description?: string;
467
+ tools?: ReadonlyArray<{
468
+ name: string;
469
+ }>;
470
+ interrupts?: ReadonlyArray<InterruptDefinition<any, any, any, any>>;
471
+ outputSchema?: SchemaInput;
472
+ };
473
+ type AgentToolList<TAgent> = TAgent extends {
474
+ tools?: infer TTools;
475
+ } ? [undefined] extends [TTools] ? [TTools] extends [undefined] ? any : Exclude<TTools, undefined> extends ReadonlyArray<infer TTool> ? [TTool] extends [never] ? any : Exclude<TTools, undefined> : any : TTools extends ReadonlyArray<infer TTool> ? [TTool] extends [never] ? any : TTools : any : any;
476
+ type AgentOutputData<TAgent> = TAgent extends {
477
+ outputSchema?: infer TSchema;
478
+ } ? Exclude<TSchema, undefined> extends SchemaInput ? [Exclude<TSchema, undefined>] extends [never] ? unknown : InferSchemaType<Exclude<TSchema, undefined>> : unknown : unknown;
479
+ /** One child handle. `name` is the discriminant. */
480
+ export type SubagentHandleOf<TAgent extends SubagentClientAgent> = Omit<SubagentHandle, 'name' | 'messages'> & {
481
+ name: TAgent['name'];
482
+ messages: Array<UIMessage<AgentToolList<TAgent>, AgentOutputData<TAgent>>>;
483
+ };
484
+ export type SubagentHandles<TAgents extends ReadonlyArray<SubagentClientAgent> | undefined> = [TAgents] extends [undefined] ? SubagentHandle : unknown extends TAgents ? SubagentHandle : TAgents extends ReadonlyArray<infer TAgent> ? TAgent extends SubagentClientAgent ? SubagentHandleOf<TAgent> : SubagentHandle : SubagentHandle;
485
+ export type SubagentPartOf<TAgents extends ReadonlyArray<SubagentClientAgent> | undefined> = [TAgents] extends [undefined] ? SubagentPart : unknown extends TAgents ? SubagentPart : {
486
+ type: 'subagent';
487
+ subagent: SubagentHandles<TAgents>;
488
+ };
489
+ export type MessagePart<TTools extends ReadonlyArray<{
490
+ name: string;
491
+ }> = any, TData = unknown, TSubagents extends ReadonlyArray<SubagentClientAgent> | undefined = undefined> = TextPart | ImagePart | AudioPart | VideoPart | DocumentPart | ToolCallPart<TTools> | ToolResultPart | ThinkingPart | StructuredOutputPart<TData> | UIResourcePart | SubagentPartOf<TSubagents>;
424
492
  /**
425
493
  * UIMessage - Domain-specific message format optimized for building chat UIs
426
494
  * Contains parts that can be text, tool calls, or tool results.
@@ -433,11 +501,13 @@ export type MessagePart<TTools extends ReadonlyArray<AnyClientTool> = any, TData
433
501
  * the public return so `m.parts.find(p => p.type === 'structured-output').data`
434
502
  * is typed without manual casts.
435
503
  */
436
- export interface UIMessage<TTools extends ReadonlyArray<AnyClientTool> = any, TData = unknown> {
504
+ export interface UIMessage<TTools extends ReadonlyArray<{
505
+ name: string;
506
+ }> = any, TData = unknown, TSubagents extends ReadonlyArray<SubagentClientAgent> | undefined = undefined> {
437
507
  id: string;
438
508
  role: 'system' | 'user' | 'assistant';
439
509
  name?: string;
440
- parts: Array<MessagePart<TTools, TData>>;
510
+ parts: Array<MessagePart<TTools, TData, TSubagents>>;
441
511
  createdAt?: Date;
442
512
  /**
443
513
  * Optional AG-UI metadata bag. TanStack writes the `tanstack` key.
@@ -599,6 +669,13 @@ export interface ChatClientBaseOptions<TTools extends ReadonlyArray<AnyClientToo
599
669
  * provider and stamps `x-byok-*` request headers. Keys never go in the body.
600
670
  */
601
671
  byok?: ByokClient;
672
+ /**
673
+ * The agents you pass to `chat({ subagents: { agents } })`, for types only.
674
+ * The client does not call `run`. `createChatHook` from
675
+ * `@tanstack/ai-react/ui` requires a `subagentsComponents` entry for every
676
+ * agent name.
677
+ */
678
+ subagents?: ReadonlyArray<SubagentClientAgent>;
602
679
  /**
603
680
  * Optional provider id for this chat. If it returns a provider slug,
604
681
  * only that key is prepared and sent. Otherwise the merged `provider`
@@ -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 InterruptDefinition,\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 { ByokClient } from './byok'\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\ntype InterruptResponseInput<TDefinition> =\n TDefinition extends InterruptDefinition<any, any, infer TResponseSchema, any>\n ? InferSchemaType<TResponseSchema>\n : never\n\ntype RegisteredGenericInterruptFor<\n TDefinition extends InterruptDefinition<any, any, any, any>,\n> =\n TDefinition extends InterruptDefinition<\n infer TDefinitionId,\n any,\n any,\n infer TPayload\n >\n ? BoundInterruptBase & {\n readonly kind: 'generic'\n readonly definitionId: TDefinitionId\n readonly key: string\n readonly payload: TPayload | undefined\n readonly binding: Readonly<\n Extract<InterruptBinding, { kind: 'generic' }> & {\n definitionId: TDefinitionId\n key: string\n batchIndex: number\n }\n >\n resolveInterrupt: (\n response: InterruptResponseInput<TDefinition>,\n ) => void\n }\n : never\n\nexport type RegisteredGenericInterrupt<\n TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>>,\n> = TInterrupts[number] extends infer TDefinition\n ? TDefinition extends InterruptDefinition<any, any, any, any>\n ? RegisteredGenericInterruptFor<TDefinition>\n : never\n : never\n\n/** A bound generic interrupt for one `defineInterrupt()` definition. */\nexport type GenericInterrupt<\n TDefinition extends InterruptDefinition<any, any, any, any>,\n> = RegisteredGenericInterruptFor<TDefinition>\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 Omit<\n BoundInterruptBase,\n 'cancel' | 'clearResolution'\n> {\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 TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> =\n readonly [],\n> =\n | GenericAGUIInterrupt\n | RegisteredGenericInterrupt<TInterrupts>\n | UnboundInterrupt\n | ApprovalInterrupts<TTools>\n\nexport type ResolvableChatInterrupt<\n TTools extends ReadonlyArray<AnyClientTool> = ReadonlyArray<AnyClientTool>,\n TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> =\n readonly [],\n> =\n | GenericAGUIInterrupt\n | RegisteredGenericInterrupt<TInterrupts>\n | ApprovalInterrupts<TTools>\n\nexport type BoundInterrupts<\n TTools extends ReadonlyArray<AnyClientTool> = ReadonlyArray<AnyClientTool>,\n TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> =\n readonly [],\n> = ReadonlyArray<ChatInterrupt<TTools, TInterrupts>>\n\nexport interface ChatInterruptState<\n TTools extends ReadonlyArray<AnyClientTool> = ReadonlyArray<AnyClientTool>,\n TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> =\n readonly [],\n> {\n readonly interrupts: BoundInterrupts<TTools, TInterrupts>\n /** @deprecated Use `interrupts`. Same snapshot today. */\n readonly pendingInterrupts: BoundInterrupts<TTools, TInterrupts>\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 /** Extra request headers for this run (e.g. BYOK keys). */\n headers?: Record<string, string>\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 * Optional AG-UI metadata bag copied onto the resulting UIMessage.\n *\n * @example\n * ```ts\n * await client.sendMessage({\n * content: 'Show me failed logins',\n * metadata: { author: { id: 'user-42', name: 'Dana' } },\n * })\n * ```\n */\n metadata?: Record<string, any>\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}. Concurrent streams are not supported.\n * `pending.id` is the id that will be stored if the action is `'queue'`\n * (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 * Extra JSON merged into this request's wire `forwardedProps`.\n * Shallow merge: `{ ...chatBody, ...positionalBody, ...body }`.\n * This field wins on key collisions.\n *\n * Framework hooks (`useChat`, `injectChat`, `createChat`) expose\n * `sendMessage(content, options)` with no positional body, so this field\n * is the per-call body channel on those surfaces.\n */\n body?: Record<string, any>\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 id?: string\n name?: string\n toolCallId: string\n content: string | Array<ContentPart>\n state: ToolResultState\n error?: string // Error message if state is \"error\"\n metadata?: Record<string, unknown>\n createdAt?: Date\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 name?: string\n parts: Array<MessagePart<TTools, TData>>\n createdAt?: Date\n /**\n * Optional AG-UI metadata bag. TanStack writes the `tanstack` key.\n * User keys stay at the top.\n */\n metadata?: Record<string, any>\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 * Newest-window size for server hydrate. Only with `persistence: true`.\n * Without this, hydrate still loads the full thread.\n */\n history?: {\n pageSize: number\n }\n }\n | {\n persistence: ChatClientPersistence<TTools>\n threadId: string\n history?: never\n }\n | {\n persistence?: false | undefined\n threadId?: string\n history?: never\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 TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> =\n readonly [],\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 * Optional BYOK keyring. On each send the client prepares the resolved\n * provider and stamps `x-byok-*` request headers. Keys never go in the body.\n */\n byok?: ByokClient\n\n /**\n * Optional provider id for this chat. If it returns a provider slug,\n * only that key is prepared and sent. Otherwise the merged `provider`\n * from `forwardedProps`, `body`, and per-call `sendMessage` `body` is\n * used. Later sources win. If no slug resolves, the send throws\n * instead of attaching every stored key.\n */\n byokProvider?: () => string | undefined\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, TInterrupts>,\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 /**\n * Callback when the immutable interrupt state snapshot changes.\n * Snapshot restoration passes `{ source: 'hydrate' }`; streamed and\n * client-initiated updates pass `{ source: 'live' }`.\n */\n onInterruptStateChange?: (\n state: ChatInterruptState<TTools, TInterrupts>,\n context: { source: 'hydrate' | 'live' },\n ) => 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 /** First-party generic interrupts this client can type and resolve. */\n interrupts?: TInterrupts\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 TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> =\n readonly [],\n> = DistributedOmit<\n ChatClientBaseOptions<TTools, TContext, TInterrupts>,\n 'context'\n> &\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 const TInterrupts extends ReadonlyArray<\n InterruptDefinition<any, any, any, any>\n > = readonly [],\n>(\n options: ChatClientOptions<TTools, TContext, TInterrupts>,\n): ChatClientOptions<TTools, TContext, TInterrupts> {\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":";;;;;;;;;;;;;;;;AA8kCA,SAAgB,YACd,GAAG,OACA;CACH,OAAO;AACT;;;;;;;;;;;;;;;;;AAkBA,SAAgB,wBAOd,SACkD;CAClD,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 InterruptDefinition,\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 SubagentHandleData,\n SubagentStatus,\n UIResourcePart,\n VideoPart,\n} from '@tanstack/ai/client'\nimport type { ByokClient } from './byok'\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\ntype InterruptResponseInput<TDefinition> =\n TDefinition extends InterruptDefinition<any, any, infer TResponseSchema, any>\n ? InferSchemaType<TResponseSchema>\n : never\n\ntype RegisteredGenericInterruptFor<\n TDefinition extends InterruptDefinition<any, any, any, any>,\n> =\n TDefinition extends InterruptDefinition<\n infer TDefinitionId,\n any,\n any,\n infer TPayload\n >\n ? BoundInterruptBase & {\n readonly kind: 'generic'\n readonly definitionId: TDefinitionId\n readonly key: string\n readonly payload: TPayload | undefined\n readonly binding: Readonly<\n Extract<InterruptBinding, { kind: 'generic' }> & {\n definitionId: TDefinitionId\n key: string\n batchIndex: number\n }\n >\n resolveInterrupt: (\n response: InterruptResponseInput<TDefinition>,\n ) => void\n }\n : never\n\nexport type RegisteredGenericInterrupt<\n TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>>,\n> = TInterrupts[number] extends infer TDefinition\n ? TDefinition extends InterruptDefinition<any, any, any, any>\n ? RegisteredGenericInterruptFor<TDefinition>\n : never\n : never\n\n/** A bound generic interrupt for one `defineInterrupt()` definition. */\nexport type GenericInterrupt<\n TDefinition extends InterruptDefinition<any, any, any, any>,\n> = RegisteredGenericInterruptFor<TDefinition>\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 Omit<\n BoundInterruptBase,\n 'cancel' | 'clearResolution'\n> {\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 TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> =\n readonly [],\n> =\n | GenericAGUIInterrupt\n | RegisteredGenericInterrupt<TInterrupts>\n | UnboundInterrupt\n | ApprovalInterrupts<TTools>\n\nexport type ResolvableChatInterrupt<\n TTools extends ReadonlyArray<AnyClientTool> = ReadonlyArray<AnyClientTool>,\n TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> =\n readonly [],\n> =\n | GenericAGUIInterrupt\n | RegisteredGenericInterrupt<TInterrupts>\n | ApprovalInterrupts<TTools>\n\nexport type BoundInterrupts<\n TTools extends ReadonlyArray<AnyClientTool> = ReadonlyArray<AnyClientTool>,\n TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> =\n readonly [],\n> = ReadonlyArray<ChatInterrupt<TTools, TInterrupts>>\n\nexport interface ChatInterruptState<\n TTools extends ReadonlyArray<AnyClientTool> = ReadonlyArray<AnyClientTool>,\n TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> =\n readonly [],\n> {\n readonly interrupts: BoundInterrupts<TTools, TInterrupts>\n /** @deprecated Use `interrupts`. Same snapshot today. */\n readonly pendingInterrupts: BoundInterrupts<TTools, TInterrupts>\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 /** Extra request headers for this run (e.g. BYOK keys). */\n headers?: Record<string, string>\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 * Optional AG-UI metadata bag copied onto the resulting UIMessage.\n *\n * @example\n * ```ts\n * await client.sendMessage({\n * content: 'Show me failed logins',\n * metadata: { author: { id: 'user-42', name: 'Dana' } },\n * })\n * ```\n */\n metadata?: Record<string, any>\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}. Concurrent streams are not supported.\n * `pending.id` is the id that will be stored if the action is `'queue'`\n * (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 * Extra JSON merged into this request's wire `forwardedProps`.\n * Shallow merge: `{ ...chatBody, ...positionalBody, ...body }`.\n * This field wins on key collisions.\n *\n * Framework hooks (`useChat`, `injectChat`, `createChat`) expose\n * `sendMessage(content, options)` with no positional body, so this field\n * is the per-call body channel on those surfaces.\n */\n body?: Record<string, any>\n}\n\n/**\n * Message parts - building blocks of UIMessage\n */\nexport interface TextPart {\n type: 'text'\n content: string\n}\n\n/**\n * Tool-call part for a bare `{ name }` tool, such as a server tool\n * definition a subagent carries. No `approval` field.\n */\ntype ToolCallPartForNamedTool<T extends { name: string }> = {\n type: 'tool-call'\n id: string\n name: T['name']\n arguments: string\n input?: InferToolInput<T>\n state: ToolCallState\n output?: InferToolOutput<T>\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 : T extends { name: string }\n ? ToolCallPartForNamedTool<T>\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<{ name: string }> = 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 { name: string }\n ? ToolCallPartForTool<Tool>\n : UntypedToolCallPart\n : UntypedToolCallPart\n\nexport interface ToolResultPart {\n type: 'tool-result'\n id?: string\n name?: string\n toolCallId: string\n content: string | Array<ContentPart>\n state: ToolResultState\n error?: string // Error message if state is \"error\"\n metadata?: Record<string, unknown>\n createdAt?: Date\n}\n\nexport interface ThinkingPart {\n type: 'thinking'\n content: string\n}\n\nexport type { SubagentStatus }\n\nexport interface SubagentHandle extends SubagentHandleData {\n /**\n * Set by ChatClient on every card it holds, streamed, restored, or initial,\n * nested cards included. Calling it marks the card `error` (`Stopped`),\n * ignores that child's later chunks until the same child starts again, and\n * aborts the local request, parent stream included. A durable server run\n * keeps going.\n */\n stop?: () => void\n}\n\nexport interface SubagentPart {\n type: 'subagent'\n subagent: SubagentHandle\n}\n\n/**\n * The slice of a server `defineAgent` result that the client reads for types.\n * The client does not call `run`. Put tool definitions (from\n * `toolDefinition`) in `tools` to type the child's tool calls and approvals.\n */\nexport type SubagentClientAgent = {\n name: string\n description?: string\n tools?: ReadonlyArray<{ name: string }>\n interrupts?: ReadonlyArray<InterruptDefinition<any, any, any, any>>\n outputSchema?: SchemaInput\n}\n\ntype AgentToolList<TAgent> = TAgent extends { tools?: infer TTools }\n ? [undefined] extends [TTools]\n ? [TTools] extends [undefined]\n ? any\n : Exclude<TTools, undefined> extends ReadonlyArray<infer TTool>\n ? [TTool] extends [never]\n ? any\n : Exclude<TTools, undefined>\n : any\n : TTools extends ReadonlyArray<infer TTool>\n ? [TTool] extends [never]\n ? any\n : TTools\n : any\n : any\n\ntype AgentOutputData<TAgent> = TAgent extends { outputSchema?: infer TSchema }\n ? Exclude<TSchema, undefined> extends SchemaInput\n ? [Exclude<TSchema, undefined>] extends [never]\n ? unknown\n : InferSchemaType<Exclude<TSchema, undefined>>\n : unknown\n : unknown\n\n/** One child handle. `name` is the discriminant. */\nexport type SubagentHandleOf<TAgent extends SubagentClientAgent> = Omit<\n SubagentHandle,\n 'name' | 'messages'\n> & {\n name: TAgent['name']\n messages: Array<UIMessage<AgentToolList<TAgent>, AgentOutputData<TAgent>>>\n}\n\nexport type SubagentHandles<\n TAgents extends ReadonlyArray<SubagentClientAgent> | undefined,\n> = [TAgents] extends [undefined]\n ? SubagentHandle\n : unknown extends TAgents\n ? SubagentHandle\n : TAgents extends ReadonlyArray<infer TAgent>\n ? TAgent extends SubagentClientAgent\n ? SubagentHandleOf<TAgent>\n : SubagentHandle\n : SubagentHandle\n\nexport type SubagentPartOf<\n TAgents extends ReadonlyArray<SubagentClientAgent> | undefined,\n> = [TAgents] extends [undefined]\n ? SubagentPart\n : unknown extends TAgents\n ? SubagentPart\n : {\n type: 'subagent'\n subagent: SubagentHandles<TAgents>\n }\n\nexport type MessagePart<\n TTools extends ReadonlyArray<{ name: string }> = any,\n TData = unknown,\n TSubagents extends ReadonlyArray<SubagentClientAgent> | undefined = undefined,\n> =\n | TextPart\n | ImagePart\n | AudioPart\n | VideoPart\n | DocumentPart\n | ToolCallPart<TTools>\n | ToolResultPart\n | ThinkingPart\n | StructuredOutputPart<TData>\n | UIResourcePart\n | SubagentPartOf<TSubagents>\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<{ name: string }> = any,\n TData = unknown,\n TSubagents extends ReadonlyArray<SubagentClientAgent> | undefined = undefined,\n> {\n id: string\n role: 'system' | 'user' | 'assistant'\n name?: string\n parts: Array<MessagePart<TTools, TData, TSubagents>>\n createdAt?: Date\n /**\n * Optional AG-UI metadata bag. TanStack writes the `tanstack` key.\n * User keys stay at the top.\n */\n metadata?: Record<string, any>\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 * Newest-window size for server hydrate. Only with `persistence: true`.\n * Without this, hydrate still loads the full thread.\n */\n history?: {\n pageSize: number\n }\n }\n | {\n persistence: ChatClientPersistence<TTools>\n threadId: string\n history?: never\n }\n | {\n persistence?: false | undefined\n threadId?: string\n history?: never\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 TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> =\n readonly [],\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 * Optional BYOK keyring. On each send the client prepares the resolved\n * provider and stamps `x-byok-*` request headers. Keys never go in the body.\n */\n byok?: ByokClient\n\n /**\n * The agents you pass to `chat({ subagents: { agents } })`, for types only.\n * The client does not call `run`. `createChatHook` from\n * `@tanstack/ai-react/ui` requires a `subagentsComponents` entry for every\n * agent name.\n */\n subagents?: ReadonlyArray<SubagentClientAgent>\n\n /**\n * Optional provider id for this chat. If it returns a provider slug,\n * only that key is prepared and sent. Otherwise the merged `provider`\n * from `forwardedProps`, `body`, and per-call `sendMessage` `body` is\n * used. Later sources win. If no slug resolves, the send throws\n * instead of attaching every stored key.\n */\n byokProvider?: () => string | undefined\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, TInterrupts>,\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 /**\n * Callback when the immutable interrupt state snapshot changes.\n * Snapshot restoration passes `{ source: 'hydrate' }`; streamed and\n * client-initiated updates pass `{ source: 'live' }`.\n */\n onInterruptStateChange?: (\n state: ChatInterruptState<TTools, TInterrupts>,\n context: { source: 'hydrate' | 'live' },\n ) => 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 /** First-party generic interrupts this client can type and resolve. */\n interrupts?: TInterrupts\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 TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> =\n readonly [],\n> = DistributedOmit<\n ChatClientBaseOptions<TTools, TContext, TInterrupts>,\n 'context'\n> &\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 const TInterrupts extends ReadonlyArray<\n InterruptDefinition<any, any, any, any>\n > = readonly [],\n>(\n options: ChatClientOptions<TTools, TContext, TInterrupts>,\n): ChatClientOptions<TTools, TContext, TInterrupts> {\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":";;;;;;;;;;;;;;;;AAksCA,SAAgB,YACd,GAAG,OACA;CACH,OAAO;AACT;;;;;;;;;;;;;;;;;AAkBA,SAAgB,wBAOd,SACkD;CAClD,OAAO;AACT"}
@@ -9,7 +9,8 @@ var PART_KEY_BY_TYPE = {
9
9
  "tool-call": "toolCall",
10
10
  "tool-result": "toolResult",
11
11
  "structured-output": "structuredOutput",
12
- "ui-resource": "uiResource"
12
+ "ui-resource": "uiResource",
13
+ subagent: "subagent"
13
14
  };
14
15
  function partTypeToKey(type) {
15
16
  const mapped = PART_KEY_BY_TYPE[type];
@@ -1 +1 @@
1
- {"version":3,"file":"selectors.js","names":[],"sources":["../../../src/ui/selectors.ts"],"sourcesContent":["import type {\n MessagePart,\n ToolApprovalInterrupt,\n ToolCallPart,\n ToolResultPart,\n UIMessage,\n} from '../types'\nimport type {\n ChatUIInterrupt,\n ChatUIPartKey,\n ChatUISelectInput,\n ChatUISelectedMessage,\n ChatUISelectedPart,\n ChatUISelection,\n} from './types'\n\nconst PART_KEY_BY_TYPE: Record<string, ChatUIPartKey> = {\n text: 'text',\n image: 'image',\n audio: 'audio',\n video: 'video',\n document: 'document',\n thinking: 'thinking',\n 'tool-call': 'toolCall',\n 'tool-result': 'toolResult',\n 'structured-output': 'structuredOutput',\n 'ui-resource': 'uiResource',\n}\n\nexport function partTypeToKey(type: string): ChatUIPartKey | string {\n const mapped = PART_KEY_BY_TYPE[type]\n if (mapped) return mapped\n return type.replace(/-([a-z])/g, (_, letter: string) => letter.toUpperCase())\n}\n\nexport function collectInlineToolNames(\n toolInterrupts?: Record<string, unknown>,\n mappedToolNames?: ReadonlyArray<string>,\n): Array<string> {\n const listPlaced = new Set(Object.keys(toolInterrupts ?? {}))\n return (mappedToolNames ?? []).filter((name) => !listPlaced.has(name))\n}\n\nexport function resolveInterruptComponent(\n interrupt: ChatUIInterrupt,\n interruptsMap:\n | {\n tools?: Record<string, unknown>\n generic?: Record<string, unknown>\n }\n | undefined,\n): unknown {\n if (!interruptsMap) return undefined\n if (interrupt.kind === 'tool-approval') {\n return interruptsMap.tools?.[interrupt.toolName]\n }\n const generic = interruptsMap.generic\n if (!generic) return undefined\n const definitionId =\n 'definitionId' in interrupt && typeof interrupt.definitionId === 'string'\n ? interrupt.definitionId\n : undefined\n if (definitionId && definitionId !== 'fallback') {\n const registered = generic[definitionId]\n if (registered) return registered\n }\n return generic.fallback\n}\n\nfunction isToolCallPart(part: MessagePart): part is ToolCallPart {\n return part.type === 'tool-call'\n}\n\nfunction isToolResultPart(part: MessagePart): part is ToolResultPart {\n return part.type === 'tool-result'\n}\n\nfunction isToolApproval(\n interrupt: ChatUIInterrupt,\n): interrupt is ToolApprovalInterrupt {\n return interrupt.kind === 'tool-approval'\n}\n\nexport function selectChatUI(input: ChatUISelectInput): ChatUISelection {\n const messages = input.messages\n const interrupts = input.interrupts ?? []\n const inlineToolNames = new Set(input.inlineToolNames ?? [])\n\n const resultsByCallId = new Map<string, ToolResultPart>()\n const callIds = new Set<string>()\n for (const message of messages) {\n for (const part of message.parts) {\n if (isToolCallPart(part)) callIds.add(part.id)\n if (isToolResultPart(part)) resultsByCallId.set(part.toolCallId, part)\n }\n }\n\n const approvalByCallId = new Map<string, ToolApprovalInterrupt>()\n for (const interrupt of interrupts) {\n if (isToolApproval(interrupt)) {\n approvalByCallId.set(interrupt.toolCallId, interrupt)\n }\n }\n\n const selectedMessages: Array<ChatUISelectedMessage> = messages.map(\n (message) => ({\n message,\n parts: message.parts.map((part) =>\n toSelectedPart(part, resultsByCallId, approvalByCallId, callIds),\n ),\n }),\n )\n\n return {\n messages: selectedMessages,\n interrupts: interrupts.filter((interrupt) => {\n if (!isToolApproval(interrupt)) return true\n if (!inlineToolNames.has(interrupt.toolName)) return true\n return !callIds.has(interrupt.toolCallId)\n }),\n }\n}\n\nfunction toSelectedPart(\n part: MessagePart,\n resultsByCallId: Map<string, ToolResultPart>,\n approvalByCallId: Map<string, ToolApprovalInterrupt>,\n callIds: Set<string>,\n): ChatUISelectedPart {\n if (isToolCallPart(part)) {\n const result = resultsByCallId.get(part.id)\n const interrupt = approvalByCallId.get(part.id)\n return {\n key: 'toolCall',\n part,\n ...(result ? { result } : {}),\n ...(interrupt ? { interrupt } : {}),\n input: part.input,\n output: part.output,\n }\n }\n\n if (isToolResultPart(part)) {\n return {\n key: 'toolResult',\n part,\n matched: callIds.has(part.toolCallId),\n }\n }\n\n return {\n key: partTypeToKey(part.type) as Exclude<\n ChatUIPartKey,\n 'toolCall' | 'toolResult'\n >,\n part,\n }\n}\n\nexport function automaticPartsForMessage(\n selected: ChatUISelectedMessage,\n): Array<ChatUISelectedPart> {\n return selected.parts.filter(\n (part) => !(part.key === 'toolResult' && part.matched),\n )\n}\n\nexport function selectMessageUI(\n message: UIMessage,\n input: Omit<ChatUISelectInput, 'messages'>,\n): ChatUISelectedMessage {\n return (\n selectChatUI({ ...input, messages: [message] }).messages[0] ?? {\n message,\n parts: [],\n }\n )\n}\n"],"mappings":";AAgBA,IAAM,mBAAkD;CACtD,MAAM;CACN,OAAO;CACP,OAAO;CACP,OAAO;CACP,UAAU;CACV,UAAU;CACV,aAAa;CACb,eAAe;CACf,qBAAqB;CACrB,eAAe;AACjB;AAEA,SAAgB,cAAc,MAAsC;CAClE,MAAM,SAAS,iBAAiB;CAChC,IAAI,QAAQ,OAAO;CACnB,OAAO,KAAK,QAAQ,cAAc,GAAG,WAAmB,OAAO,YAAY,CAAC;AAC9E;AAEA,SAAgB,uBACd,gBACA,iBACe;CACf,MAAM,aAAa,IAAI,IAAI,OAAO,KAAK,kBAAkB,CAAC,CAAC,CAAC;CAC5D,QAAQ,mBAAmB,CAAC,EAAA,CAAG,QAAQ,SAAS,CAAC,WAAW,IAAI,IAAI,CAAC;AACvE;AAEA,SAAgB,0BACd,WACA,eAMS;CACT,IAAI,CAAC,eAAe,OAAO,KAAA;CAC3B,IAAI,UAAU,SAAS,iBACrB,OAAO,cAAc,QAAQ,UAAU;CAEzC,MAAM,UAAU,cAAc;CAC9B,IAAI,CAAC,SAAS,OAAO,KAAA;CACrB,MAAM,eACJ,kBAAkB,aAAa,OAAO,UAAU,iBAAiB,WAC7D,UAAU,eACV,KAAA;CACN,IAAI,gBAAgB,iBAAiB,YAAY;EAC/C,MAAM,aAAa,QAAQ;EAC3B,IAAI,YAAY,OAAO;CACzB;CACA,OAAO,QAAQ;AACjB;AAEA,SAAS,eAAe,MAAyC;CAC/D,OAAO,KAAK,SAAS;AACvB;AAEA,SAAS,iBAAiB,MAA2C;CACnE,OAAO,KAAK,SAAS;AACvB;AAEA,SAAS,eACP,WACoC;CACpC,OAAO,UAAU,SAAS;AAC5B;AAEA,SAAgB,aAAa,OAA2C;CACtE,MAAM,WAAW,MAAM;CACvB,MAAM,aAAa,MAAM,cAAc,CAAC;CACxC,MAAM,kBAAkB,IAAI,IAAI,MAAM,mBAAmB,CAAC,CAAC;CAE3D,MAAM,kCAAkB,IAAI,IAA4B;CACxD,MAAM,0BAAU,IAAI,IAAY;CAChC,KAAK,MAAM,WAAW,UACpB,KAAK,MAAM,QAAQ,QAAQ,OAAO;EAChC,IAAI,eAAe,IAAI,GAAG,QAAQ,IAAI,KAAK,EAAE;EAC7C,IAAI,iBAAiB,IAAI,GAAG,gBAAgB,IAAI,KAAK,YAAY,IAAI;CACvE;CAGF,MAAM,mCAAmB,IAAI,IAAmC;CAChE,KAAK,MAAM,aAAa,YACtB,IAAI,eAAe,SAAS,GAC1B,iBAAiB,IAAI,UAAU,YAAY,SAAS;CAaxD,OAAO;EACL,UAVqD,SAAS,KAC7D,aAAa;GACZ;GACA,OAAO,QAAQ,MAAM,KAAK,SACxB,eAAe,MAAM,iBAAiB,kBAAkB,OAAO,CACjE;EACF,EAIU;EACV,YAAY,WAAW,QAAQ,cAAc;GAC3C,IAAI,CAAC,eAAe,SAAS,GAAG,OAAO;GACvC,IAAI,CAAC,gBAAgB,IAAI,UAAU,QAAQ,GAAG,OAAO;GACrD,OAAO,CAAC,QAAQ,IAAI,UAAU,UAAU;EAC1C,CAAC;CACH;AACF;AAEA,SAAS,eACP,MACA,iBACA,kBACA,SACoB;CACpB,IAAI,eAAe,IAAI,GAAG;EACxB,MAAM,SAAS,gBAAgB,IAAI,KAAK,EAAE;EAC1C,MAAM,YAAY,iBAAiB,IAAI,KAAK,EAAE;EAC9C,OAAO;GACL,KAAK;GACL;GACA,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;GAC3B,GAAI,YAAY,EAAE,UAAU,IAAI,CAAC;GACjC,OAAO,KAAK;GACZ,QAAQ,KAAK;EACf;CACF;CAEA,IAAI,iBAAiB,IAAI,GACvB,OAAO;EACL,KAAK;EACL;EACA,SAAS,QAAQ,IAAI,KAAK,UAAU;CACtC;CAGF,OAAO;EACL,KAAK,cAAc,KAAK,IAAI;EAI5B;CACF;AACF;AAEA,SAAgB,yBACd,UAC2B;CAC3B,OAAO,SAAS,MAAM,QACnB,SAAS,EAAE,KAAK,QAAQ,gBAAgB,KAAK,QAChD;AACF;AAEA,SAAgB,gBACd,SACA,OACuB;CACvB,OACE,aAAa;EAAE,GAAG;EAAO,UAAU,CAAC,OAAO;CAAE,CAAC,CAAC,CAAC,SAAS,MAAM;EAC7D;EACA,OAAO,CAAC;CACV;AAEJ"}
1
+ {"version":3,"file":"selectors.js","names":[],"sources":["../../../src/ui/selectors.ts"],"sourcesContent":["import type {\n MessagePart,\n ToolApprovalInterrupt,\n ToolCallPart,\n ToolResultPart,\n UIMessage,\n} from '../types'\nimport type {\n ChatUIInterrupt,\n ChatUIPartKey,\n ChatUISelectInput,\n ChatUISelectedMessage,\n ChatUISelectedPart,\n ChatUISelection,\n} from './types'\n\nconst PART_KEY_BY_TYPE: Record<string, ChatUIPartKey> = {\n text: 'text',\n image: 'image',\n audio: 'audio',\n video: 'video',\n document: 'document',\n thinking: 'thinking',\n 'tool-call': 'toolCall',\n 'tool-result': 'toolResult',\n 'structured-output': 'structuredOutput',\n 'ui-resource': 'uiResource',\n subagent: 'subagent',\n}\n\nexport function partTypeToKey(type: string): ChatUIPartKey | string {\n const mapped = PART_KEY_BY_TYPE[type]\n if (mapped) return mapped\n return type.replace(/-([a-z])/g, (_, letter: string) => letter.toUpperCase())\n}\n\nexport function collectInlineToolNames(\n toolInterrupts?: Record<string, unknown>,\n mappedToolNames?: ReadonlyArray<string>,\n): Array<string> {\n const listPlaced = new Set(Object.keys(toolInterrupts ?? {}))\n return (mappedToolNames ?? []).filter((name) => !listPlaced.has(name))\n}\n\nexport function resolveInterruptComponent(\n interrupt: ChatUIInterrupt,\n interruptsMap:\n | {\n tools?: Record<string, unknown>\n generic?: Record<string, unknown>\n }\n | undefined,\n): unknown {\n if (!interruptsMap) return undefined\n if (interrupt.kind === 'tool-approval') {\n return interruptsMap.tools?.[interrupt.toolName]\n }\n const generic = interruptsMap.generic\n if (!generic) return undefined\n const definitionId =\n 'definitionId' in interrupt && typeof interrupt.definitionId === 'string'\n ? interrupt.definitionId\n : undefined\n if (definitionId && definitionId !== 'fallback') {\n const registered = generic[definitionId]\n if (registered) return registered\n }\n return generic.fallback\n}\n\nfunction isToolCallPart(part: MessagePart): part is ToolCallPart {\n return part.type === 'tool-call'\n}\n\nfunction isToolResultPart(part: MessagePart): part is ToolResultPart {\n return part.type === 'tool-result'\n}\n\nfunction isToolApproval(\n interrupt: ChatUIInterrupt,\n): interrupt is ToolApprovalInterrupt {\n return interrupt.kind === 'tool-approval'\n}\n\nexport function selectChatUI(input: ChatUISelectInput): ChatUISelection {\n const messages = input.messages\n const interrupts = input.interrupts ?? []\n const inlineToolNames = new Set(input.inlineToolNames ?? [])\n\n const resultsByCallId = new Map<string, ToolResultPart>()\n const callIds = new Set<string>()\n for (const message of messages) {\n for (const part of message.parts) {\n if (isToolCallPart(part)) callIds.add(part.id)\n if (isToolResultPart(part)) resultsByCallId.set(part.toolCallId, part)\n }\n }\n\n const approvalByCallId = new Map<string, ToolApprovalInterrupt>()\n for (const interrupt of interrupts) {\n if (isToolApproval(interrupt)) {\n approvalByCallId.set(interrupt.toolCallId, interrupt)\n }\n }\n\n const selectedMessages: Array<ChatUISelectedMessage> = messages.map(\n (message) => ({\n message,\n parts: message.parts.map((part) =>\n toSelectedPart(part, resultsByCallId, approvalByCallId, callIds),\n ),\n }),\n )\n\n return {\n messages: selectedMessages,\n interrupts: interrupts.filter((interrupt) => {\n if (!isToolApproval(interrupt)) return true\n if (!inlineToolNames.has(interrupt.toolName)) return true\n return !callIds.has(interrupt.toolCallId)\n }),\n }\n}\n\nfunction toSelectedPart(\n part: MessagePart,\n resultsByCallId: Map<string, ToolResultPart>,\n approvalByCallId: Map<string, ToolApprovalInterrupt>,\n callIds: Set<string>,\n): ChatUISelectedPart {\n if (isToolCallPart(part)) {\n const result = resultsByCallId.get(part.id)\n const interrupt = approvalByCallId.get(part.id)\n return {\n key: 'toolCall',\n part,\n ...(result ? { result } : {}),\n ...(interrupt ? { interrupt } : {}),\n input: part.input,\n output: part.output,\n }\n }\n\n if (isToolResultPart(part)) {\n return {\n key: 'toolResult',\n part,\n matched: callIds.has(part.toolCallId),\n }\n }\n\n return {\n key: partTypeToKey(part.type) as Exclude<\n ChatUIPartKey,\n 'toolCall' | 'toolResult'\n >,\n part,\n }\n}\n\nexport function automaticPartsForMessage(\n selected: ChatUISelectedMessage,\n): Array<ChatUISelectedPart> {\n return selected.parts.filter(\n (part) => !(part.key === 'toolResult' && part.matched),\n )\n}\n\nexport function selectMessageUI(\n message: UIMessage,\n input: Omit<ChatUISelectInput, 'messages'>,\n): ChatUISelectedMessage {\n return (\n selectChatUI({ ...input, messages: [message] }).messages[0] ?? {\n message,\n parts: [],\n }\n )\n}\n"],"mappings":";AAgBA,IAAM,mBAAkD;CACtD,MAAM;CACN,OAAO;CACP,OAAO;CACP,OAAO;CACP,UAAU;CACV,UAAU;CACV,aAAa;CACb,eAAe;CACf,qBAAqB;CACrB,eAAe;CACf,UAAU;AACZ;AAEA,SAAgB,cAAc,MAAsC;CAClE,MAAM,SAAS,iBAAiB;CAChC,IAAI,QAAQ,OAAO;CACnB,OAAO,KAAK,QAAQ,cAAc,GAAG,WAAmB,OAAO,YAAY,CAAC;AAC9E;AAEA,SAAgB,uBACd,gBACA,iBACe;CACf,MAAM,aAAa,IAAI,IAAI,OAAO,KAAK,kBAAkB,CAAC,CAAC,CAAC;CAC5D,QAAQ,mBAAmB,CAAC,EAAA,CAAG,QAAQ,SAAS,CAAC,WAAW,IAAI,IAAI,CAAC;AACvE;AAEA,SAAgB,0BACd,WACA,eAMS;CACT,IAAI,CAAC,eAAe,OAAO,KAAA;CAC3B,IAAI,UAAU,SAAS,iBACrB,OAAO,cAAc,QAAQ,UAAU;CAEzC,MAAM,UAAU,cAAc;CAC9B,IAAI,CAAC,SAAS,OAAO,KAAA;CACrB,MAAM,eACJ,kBAAkB,aAAa,OAAO,UAAU,iBAAiB,WAC7D,UAAU,eACV,KAAA;CACN,IAAI,gBAAgB,iBAAiB,YAAY;EAC/C,MAAM,aAAa,QAAQ;EAC3B,IAAI,YAAY,OAAO;CACzB;CACA,OAAO,QAAQ;AACjB;AAEA,SAAS,eAAe,MAAyC;CAC/D,OAAO,KAAK,SAAS;AACvB;AAEA,SAAS,iBAAiB,MAA2C;CACnE,OAAO,KAAK,SAAS;AACvB;AAEA,SAAS,eACP,WACoC;CACpC,OAAO,UAAU,SAAS;AAC5B;AAEA,SAAgB,aAAa,OAA2C;CACtE,MAAM,WAAW,MAAM;CACvB,MAAM,aAAa,MAAM,cAAc,CAAC;CACxC,MAAM,kBAAkB,IAAI,IAAI,MAAM,mBAAmB,CAAC,CAAC;CAE3D,MAAM,kCAAkB,IAAI,IAA4B;CACxD,MAAM,0BAAU,IAAI,IAAY;CAChC,KAAK,MAAM,WAAW,UACpB,KAAK,MAAM,QAAQ,QAAQ,OAAO;EAChC,IAAI,eAAe,IAAI,GAAG,QAAQ,IAAI,KAAK,EAAE;EAC7C,IAAI,iBAAiB,IAAI,GAAG,gBAAgB,IAAI,KAAK,YAAY,IAAI;CACvE;CAGF,MAAM,mCAAmB,IAAI,IAAmC;CAChE,KAAK,MAAM,aAAa,YACtB,IAAI,eAAe,SAAS,GAC1B,iBAAiB,IAAI,UAAU,YAAY,SAAS;CAaxD,OAAO;EACL,UAVqD,SAAS,KAC7D,aAAa;GACZ;GACA,OAAO,QAAQ,MAAM,KAAK,SACxB,eAAe,MAAM,iBAAiB,kBAAkB,OAAO,CACjE;EACF,EAIU;EACV,YAAY,WAAW,QAAQ,cAAc;GAC3C,IAAI,CAAC,eAAe,SAAS,GAAG,OAAO;GACvC,IAAI,CAAC,gBAAgB,IAAI,UAAU,QAAQ,GAAG,OAAO;GACrD,OAAO,CAAC,QAAQ,IAAI,UAAU,UAAU;EAC1C,CAAC;CACH;AACF;AAEA,SAAS,eACP,MACA,iBACA,kBACA,SACoB;CACpB,IAAI,eAAe,IAAI,GAAG;EACxB,MAAM,SAAS,gBAAgB,IAAI,KAAK,EAAE;EAC1C,MAAM,YAAY,iBAAiB,IAAI,KAAK,EAAE;EAC9C,OAAO;GACL,KAAK;GACL;GACA,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;GAC3B,GAAI,YAAY,EAAE,UAAU,IAAI,CAAC;GACjC,OAAO,KAAK;GACZ,QAAQ,KAAK;EACf;CACF;CAEA,IAAI,iBAAiB,IAAI,GACvB,OAAO;EACL,KAAK;EACL;EACA,SAAS,QAAQ,IAAI,KAAK,UAAU;CACtC;CAGF,OAAO;EACL,KAAK,cAAc,KAAK,IAAI;EAI5B;CACF;AACF;AAEA,SAAgB,yBACd,UAC2B;CAC3B,OAAO,SAAS,MAAM,QACnB,SAAS,EAAE,KAAK,QAAQ,gBAAgB,KAAK,QAChD;AACF;AAEA,SAAgB,gBACd,SACA,OACuB;CACvB,OACE,aAAa;EAAE,GAAG;EAAO,UAAU,CAAC,OAAO;CAAE,CAAC,CAAC,CAAC,SAAS,MAAM;EAC7D;EACA,OAAO,CAAC;CACV;AAEJ"}
@@ -1,6 +1,6 @@
1
1
  import { AnyClientTool, InferSchemaType, InferToolInput, InferToolOutput, InterruptDefinition, SchemaInput } from '@tanstack/ai/client';
2
- import { ChatInterrupt, MessagePart, RegisteredGenericInterrupt, StructuredOutputPart, ToolApprovalInterrupt, ToolCallPart, ToolResultPart, UIMessage } from '../types.js';
3
- export type ChatUIPartKey = 'text' | 'image' | 'audio' | 'video' | 'document' | 'thinking' | 'toolCall' | 'toolResult' | 'structuredOutput' | 'uiResource';
2
+ import { ChatInterrupt, MessagePart, RegisteredGenericInterrupt, SubagentClientAgent, StructuredOutputPart, ToolApprovalInterrupt, ToolCallPart, ToolResultPart, UIMessage } from '../types.js';
3
+ export type ChatUIPartKey = 'text' | 'image' | 'audio' | 'video' | 'document' | 'thinking' | 'toolCall' | 'toolResult' | 'structuredOutput' | 'uiResource' | 'subagent';
4
4
  export type ChatUIPartTypeByKey = {
5
5
  text: 'text';
6
6
  image: 'image';
@@ -12,6 +12,7 @@ export type ChatUIPartTypeByKey = {
12
12
  toolResult: 'tool-result';
13
13
  structuredOutput: 'structured-output';
14
14
  uiResource: 'ui-resource';
15
+ subagent: 'subagent';
15
16
  };
16
17
  export type ChatUIPartOf<TOptions, TKey extends ChatUIPartKey = ChatUIPartKey> = TKey extends ChatUIPartKey ? Extract<MessagePart<ChatUIToolsOf<TOptions>, ChatUIData<TOptions>>, {
17
18
  type: ChatUIPartTypeByKey[TKey];
@@ -19,9 +20,14 @@ export type ChatUIPartOf<TOptions, TKey extends ChatUIPartKey = ChatUIPartKey> =
19
20
  export type ChatUIToolsOf<TOptions> = TOptions extends {
20
21
  tools: infer TTools;
21
22
  } ? TTools extends ReadonlyArray<AnyClientTool> ? TTools : any : any;
22
- export type ChatUIInterruptsOf<TOptions> = TOptions extends {
23
+ type RootInterruptsOf<TOptions> = TOptions extends {
23
24
  interrupts: infer TInterrupts;
24
25
  } ? TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> ? TInterrupts : readonly [] : readonly [];
26
+ type AgentInterrupts<TOptions> = ConcreteItems<AgentField<ChatUISubagentsOf<TOptions>[number], 'interrupts', readonly []>>;
27
+ /** The root `interrupts` plus every child agent's `interrupts`. */
28
+ export type ChatUIInterruptsOf<TOptions> = [AgentInterrupts<TOptions>] extends [
29
+ never
30
+ ] ? RootInterruptsOf<TOptions> : ReadonlyArray<RootInterruptsOf<TOptions>[number] | Extract<AgentInterrupts<TOptions>, InterruptDefinition<any, any, any, any>>>;
25
31
  export type ChatUISchemaOf<TOptions> = TOptions extends {
26
32
  outputSchema: infer TSchema;
27
33
  } ? TSchema extends SchemaInput ? TSchema : undefined : undefined;
@@ -36,13 +42,53 @@ export type ChatUIHasNamedTools<TOptions> = [ChatUIToolName<TOptions>] extends [
36
42
  export type ChatUIHasNamedInterrupts<TOptions> = [
37
43
  ChatUIRegisteredInterruptId<TOptions>
38
44
  ] extends [never] ? false : [string] extends [ChatUIRegisteredInterruptId<TOptions>] ? false : true;
45
+ /** The agents in `options.subagents`, or an empty list. */
46
+ export type ChatUISubagentsOf<TOptions> = TOptions extends {
47
+ subagents?: infer TAgents;
48
+ } ? Exclude<TAgents, undefined> extends ReadonlyArray<SubagentClientAgent> ? Exclude<TAgents, undefined> : readonly [] : readonly [];
49
+ export type ChatUISubagentName<TOptions> = ChatUISubagentsOf<TOptions>[number]['name'];
50
+ /** The agent in `options.subagents` with this name. */
51
+ export type ChatUISubagentOf<TOptions, TName> = Extract<ChatUISubagentsOf<TOptions>[number], {
52
+ name: TName;
53
+ }>;
54
+ type AgentField<TAgent, TKey extends string, TFallback> = TAgent extends {
55
+ [K in TKey]?: infer TValue;
56
+ } ? [Exclude<TValue, undefined>] extends [never] ? TFallback : Exclude<TValue, undefined> : TFallback;
57
+ /**
58
+ * One child agent seen as chat options, so the part, tool, and interrupt
59
+ * types read that agent's `tools`, `interrupts`, and `outputSchema`. An
60
+ * unknown name gives untyped options.
61
+ */
62
+ export type ChatUISubagentOptions<TOptions, TName> = [
63
+ ChatUISubagentOf<TOptions, TName>
64
+ ] extends [never] ? {} : ChatUISubagentOf<TOptions, TName> extends infer TAgent ? {
65
+ tools: AgentField<TAgent, 'tools', readonly []>;
66
+ interrupts: AgentField<TAgent, 'interrupts', readonly []>;
67
+ outputSchema: AgentField<TAgent, 'outputSchema', undefined>;
68
+ } : {};
69
+ type ConcreteItems<TList> = unknown extends TList ? never : TList extends ReadonlyArray<infer TItem> ? TItem : never;
70
+ type AgentTools<TOptions> = ConcreteItems<AgentField<ChatUISubagentsOf<TOptions>[number], 'tools', readonly []>>;
71
+ /**
72
+ * The tools whose approvals can reach this chat: the root `tools` plus every
73
+ * child agent's `tools`.
74
+ */
75
+ export type ChatUIApprovalToolsOf<TOptions> = [
76
+ ConcreteItems<ChatUIToolsOf<TOptions>> | AgentTools<TOptions>
77
+ ] extends [never] ? ChatUIToolsOf<TOptions> : ReadonlyArray<Extract<ConcreteItems<ChatUIToolsOf<TOptions>> | AgentTools<TOptions>, AnyClientTool>>;
78
+ export type ChatUIApprovalToolName<TOptions> = ChatUIApprovalToolsOf<TOptions>[number] extends infer TTool ? TTool extends AnyClientTool ? TTool['name'] : string : string;
79
+ export type ChatUIHasNamedSubagents<TOptions> = [
80
+ ChatUISubagentName<TOptions>
81
+ ] extends [never] ? false : [string] extends [ChatUISubagentName<TOptions>] ? false : true;
39
82
  export type ChatUINamedInterruptId<TOptions> = Exclude<ChatUIRegisteredInterruptId<TOptions>, 'fallback'>;
40
- export type ChatUIInterruptName<TOptions> = (ChatUIHasNamedTools<TOptions> extends true ? ChatUIToolName<TOptions> : never) | (ChatUIHasNamedInterrupts<TOptions> extends true ? ChatUINamedInterruptId<TOptions> : never);
83
+ type ChatUIHasNamedApprovalTools<TOptions> = [
84
+ ChatUIApprovalToolName<TOptions>
85
+ ] extends [never] ? false : [string] extends [ChatUIApprovalToolName<TOptions>] ? false : true;
86
+ export type ChatUIInterruptName<TOptions> = (ChatUIHasNamedApprovalTools<TOptions> extends true ? ChatUIApprovalToolName<TOptions> : never) | (ChatUIHasNamedInterrupts<TOptions> extends true ? ChatUINamedInterruptId<TOptions> : never);
41
87
  type ToolByName<TOptions, TName> = Extract<ChatUIToolsOf<TOptions> extends ReadonlyArray<infer TTool> ? TTool : never, {
42
88
  name: TName;
43
89
  }>;
44
90
  export type ChatUIInterrupt = ChatInterrupt | ToolApprovalInterrupt;
45
- export type ChatUIToolApproval<TOptions, TName extends ChatUIToolName<TOptions> = ChatUIToolName<TOptions>> = Extract<ChatInterrupt<ChatUIToolsOf<TOptions>, ChatUIInterruptsOf<TOptions>>, {
91
+ export type ChatUIToolApproval<TOptions, TName extends string = ChatUIApprovalToolName<TOptions>> = Extract<ChatInterrupt<ChatUIApprovalToolsOf<TOptions>, ChatUIInterruptsOf<TOptions>>, {
46
92
  kind: 'tool-approval';
47
93
  toolName: TName;
48
94
  }>;
@@ -52,17 +98,14 @@ export type ChatUIToolPart<TOptions, TName extends ChatUIToolName<TOptions> = Ch
52
98
  name: TName;
53
99
  }>;
54
100
  result?: ToolResultPart;
55
- interrupt?: Extract<ChatInterrupt<ChatUIToolsOf<TOptions>, ChatUIInterruptsOf<TOptions>>, {
56
- kind: 'tool-approval';
57
- toolName: TName;
58
- }>;
101
+ interrupt?: ChatUIToolApproval<TOptions, TName>;
59
102
  input?: InferToolInput<ToolByName<TOptions, TName>>;
60
103
  output?: InferToolOutput<ToolByName<TOptions, TName>>;
61
104
  };
62
105
  export type RegisteredUIInterrupt<TOptions, TId extends ChatUIRegisteredInterruptId<TOptions> = ChatUIRegisteredInterruptId<TOptions>> = Extract<RegisteredGenericInterrupt<ChatUIInterruptsOf<TOptions>>, {
63
106
  definitionId: TId;
64
107
  }>;
65
- export type ChatUIInterruptOf<TOptions, TName extends ChatUIInterruptName<TOptions> = never> = [TName] extends [never] ? ChatUIInterrupt : TName extends (ChatUIHasNamedTools<TOptions> extends true ? ChatUIToolName<TOptions> : never) ? ChatUIToolApproval<TOptions, TName> : TName extends ChatUINamedInterruptId<TOptions> ? RegisteredUIInterrupt<TOptions, TName> : ChatUIInterrupt;
108
+ export type ChatUIInterruptOf<TOptions, TName extends ChatUIInterruptName<TOptions> = never> = [TName] extends [never] ? ChatUIInterrupt : TName extends (ChatUIHasNamedApprovalTools<TOptions> extends true ? ChatUIApprovalToolName<TOptions> : never) ? ChatUIToolApproval<TOptions, TName> : TName extends ChatUINamedInterruptId<TOptions> ? RegisteredUIInterrupt<TOptions, TName> : ChatUIInterrupt;
66
109
  export type ChatUISelectedToolPart = {
67
110
  key: 'toolCall';
68
111
  part: ToolCallPart;
package/dist/esm/ui.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  export { partTypeToKey, selectChatUI } from './ui/selectors.js';
2
2
  export { automaticPartsForMessage, collectInlineToolNames, resolveInterruptComponent, selectMessageUI, } from './ui/selectors.js';
3
- export type { ChatUIData, ChatUIHasNamedInterrupts, ChatUIHasNamedTools, ChatUIInterrupt, ChatUIInterruptName, ChatUIInterruptOf, ChatUIInterruptsOf, ChatUINamedInterruptId, ChatUIMessages, ChatUIPartKey, ChatUIPartOf, ChatUIPartTypeByKey, ChatUIRegisteredInterruptId, ChatUISchemaOf, ChatUISelectInput, ChatUISelectedGenericPart, ChatUISelectedMessage, ChatUISelectedPart, ChatUISelectedPartOf, ChatUISelectedResultPart, ChatUISelectedToolPart, ChatUISelection, ChatUIStructuredPart, ChatUIToolApproval, ChatUIToolName, ChatUIToolPart, ChatUIToolsOf, RegisteredUIInterrupt, } from './ui/types.js';
3
+ export type { ChatUIApprovalToolName, ChatUIApprovalToolsOf, ChatUIData, ChatUIHasNamedInterrupts, ChatUIHasNamedSubagents, ChatUIHasNamedTools, ChatUIInterrupt, ChatUIInterruptName, ChatUIInterruptOf, ChatUIInterruptsOf, ChatUINamedInterruptId, ChatUIMessages, ChatUIPartKey, ChatUIPartOf, ChatUIPartTypeByKey, ChatUIRegisteredInterruptId, ChatUISchemaOf, ChatUISelectInput, ChatUISelectedGenericPart, ChatUISelectedMessage, ChatUISelectedPart, ChatUISelectedPartOf, ChatUISelectedResultPart, ChatUISelectedToolPart, ChatUISelection, ChatUISubagentName, ChatUISubagentOf, ChatUISubagentOptions, ChatUISubagentsOf, ChatUIStructuredPart, ChatUIToolApproval, ChatUIToolName, ChatUIToolPart, ChatUIToolsOf, RegisteredUIInterrupt, } from './ui/types.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/ai-client",
3
- "version": "0.33.2",
3
+ "version": "0.34.0",
4
4
  "description": "Framework-agnostic headless client for TanStack AI chat, realtime sessions, streaming transports, and media generations.",
5
5
  "author": "Tanner Linsley",
6
6
  "license": "MIT",
@@ -57,7 +57,7 @@
57
57
  "src"
58
58
  ],
59
59
  "dependencies": {
60
- "@tanstack/ai": "^0.58.0",
60
+ "@tanstack/ai": "^0.59.0",
61
61
  "@tanstack/ai-event-client": "^0.12.1",
62
62
  "@tanstack/ai-utils": "^0.4.1"
63
63
  },