@tanstack/ai-client 0.35.1 → 0.36.1

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.
@@ -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 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"}
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 ToolResultOutcome,\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 /** Set when the user or middleware cancelled or denied the tool call; state remains `error`. */\n outcome?: ToolResultOutcome\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":";;;;;;;;;;;;;;;;AAqsCA,SAAgB,YACd,GAAG,OACA;CACH,OAAO;AACT;;;;;;;;;;;;;;;;;AAkBA,SAAgB,wBAOd,SACkD;CAClD,OAAO;AACT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/ai-client",
3
- "version": "0.35.1",
3
+ "version": "0.36.1",
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.61.0",
60
+ "@tanstack/ai": "^0.64.0",
61
61
  "@tanstack/ai-event-client": "^0.13.0",
62
62
  "@tanstack/ai-utils": "^0.4.1"
63
63
  },
@@ -72,9 +72,9 @@
72
72
  "clean": "premove ./build ./dist",
73
73
  "lint:fix": "oxlint src --type-aware --fix",
74
74
  "test:build": "publint --strict",
75
- "test:coverage": "vitest run --coverage",
76
- "test:coverage:watch": "vitest --coverage --watch",
77
75
  "test:oxlint": "oxlint src --type-aware",
76
+ "test:coverage": "vitest run --coverage --coverage.include='src/**' --coverage.reporter=text-summary --coverage.reporter=json-summary",
77
+ "test:coverage:watch": "vitest --coverage --watch",
78
78
  "test:lib": "vitest",
79
79
  "test:lib:dev": "pnpm test:lib --watch",
80
80
  "test:types": "tsc"
@@ -1,14 +1,15 @@
1
1
  import {
2
2
  EventType,
3
3
  StreamProcessor,
4
+ cloneAndDeepFreezeJson,
4
5
  convertSchemaToJsonSchema,
5
6
  generateMessageId,
6
7
  isStandardSchema,
7
8
  mergeMetadata,
8
9
  normalizeToUIMessage,
9
- parseWithStandardSchema,
10
10
  restoreInboundChunk,
11
11
  tanstackMetadata,
12
+ validateWithStandardSchema,
12
13
  } from '@tanstack/ai/client'
13
14
  import {
14
15
  ByokBlockedError,
@@ -88,6 +89,20 @@ interface InternalQueuedMessage extends QueuedMessage {
88
89
  body?: Record<string, any>
89
90
  }
90
91
 
92
+ const STREAM_PROCESSING_BUDGET_MS = 8
93
+
94
+ type SchedulerWithYield = {
95
+ yield?: () => Promise<void>
96
+ }
97
+
98
+ function yieldToHost(): Promise<void> {
99
+ const { scheduler } = globalThis as typeof globalThis & {
100
+ scheduler?: SchedulerWithYield
101
+ }
102
+ if (scheduler?.yield) return scheduler.yield()
103
+ return new Promise((resolve) => setTimeout(resolve, 0))
104
+ }
105
+
91
106
  function assertUniqueInterruptDefinitions(
92
107
  interrupts:
93
108
  | ReadonlyArray<InterruptDefinition<any, any, any, any>>
@@ -1173,7 +1188,12 @@ export class ChatClient<
1173
1188
  this.processor.setMessages(windowMessages)
1174
1189
  this.rememberServerMessageIds(windowMessages)
1175
1190
  }
1176
- if (result.interrupts && result.interrupts.pending.length > 0) {
1191
+ if (
1192
+ result.interrupts &&
1193
+ result.interrupts.pending.length > 0 &&
1194
+ (!result.activeRun?.runId ||
1195
+ result.activeRun.runId === result.interrupts.runId)
1196
+ ) {
1177
1197
  // Pending interrupt = the thread is paused awaiting a human decision, so
1178
1198
  // there is nothing to tail (no chunks stream until it resolves). Restore
1179
1199
  // the approval/wait from the SERVER — identical to reconstructing it from
@@ -1183,7 +1203,9 @@ export class ChatClient<
1183
1203
  // on the server, so a racing hydrate reports both an `activeRun` cursor
1184
1204
  // AND the pending interrupt. Tailing that "active" run would drop the
1185
1205
  // approval card (and hang on a stream that never comes), so the interrupt
1186
- // always wins.
1206
+ // wins over that same run. A DIFFERENT active run is the continuation
1207
+ // that answered this interrupt: the server commits the answer only when
1208
+ // that run finishes, so join it (see the `else` branch below).
1187
1209
  this.applyResumeSnapshot({
1188
1210
  resumeState: {
1189
1211
  threadId: this.threadId,
@@ -1914,13 +1936,23 @@ export class ChatClient<
1914
1936
  }
1915
1937
 
1916
1938
  /**
1917
- * Consume chunks from the connection subscription.
1939
+ * Consume chunks from the connection subscription. Chunks are processed in
1940
+ * order; the loop yields to the host after each processing budget.
1918
1941
  */
1919
1942
  private async consumeSubscription(signal: AbortSignal): Promise<void> {
1920
1943
  const stream = this.connection.subscribe(signal)
1944
+ let chunkProcessingTime = 0
1921
1945
  for await (const chunk of stream) {
1922
1946
  if (signal.aborted) break
1923
- await this.processIncomingChunk(chunk)
1947
+ const startedAt = performance.now()
1948
+ this.processIncomingChunk(chunk)
1949
+ chunkProcessingTime += performance.now() - startedAt
1950
+ if (chunkProcessingTime < STREAM_PROCESSING_BUDGET_MS) continue
1951
+ chunkProcessingTime = 0
1952
+ // Skip the yield when the page is hidden. Browsers clamp timers there,
1953
+ // and that wait paces stream pull.
1954
+ if (typeof document !== 'undefined' && document.hidden) continue
1955
+ await yieldToHost()
1924
1956
  }
1925
1957
  }
1926
1958
 
@@ -1943,7 +1975,7 @@ export class ChatClient<
1943
1975
  * give up after {@link REJOIN_CONNECT_DEADLINE_MS} if no chunk arrives and
1944
1976
  * clear the dead pointer so it does not retry on the next load.
1945
1977
  *
1946
- * Replay chunks are processed WITHOUT the per-chunk yield the live path uses,
1978
+ * Replay chunks are processed WITHOUT the time-slice yield the live path uses,
1947
1979
  * so the buffered prefix snaps in and only the genuinely-live tail streams at
1948
1980
  * network speed — a reload looks like the run continued, not like it re-typed.
1949
1981
  */
@@ -1984,7 +2016,7 @@ export class ChatClient<
1984
2016
  rebuilt = true
1985
2017
  this.dropTrailingInFlightAssistant()
1986
2018
  }
1987
- await this.processIncomingChunk(chunk, { defer: false })
2019
+ this.processIncomingChunk(chunk)
1988
2020
  }
1989
2021
  // Same contract as `streamResponse`: client tools may finish (and
1990
2022
  // queue a resume) while `isLoading` is still true. Wait for them
@@ -2053,10 +2085,7 @@ export class ChatClient<
2053
2085
  }
2054
2086
  }
2055
2087
 
2056
- private async processIncomingChunk(
2057
- chunk: StreamChunk,
2058
- options?: { defer?: boolean },
2059
- ): Promise<void> {
2088
+ private processIncomingChunk(chunk: StreamChunk): void {
2060
2089
  chunk = restoreInboundChunk(chunk)
2061
2090
  if (
2062
2091
  chunk.type === 'RUN_ERROR' &&
@@ -2099,15 +2128,6 @@ export class ChatClient<
2099
2128
  this.syncSubagentHandles()
2100
2129
  this.updateRunLifecycle(chunk)
2101
2130
  this.observeInterruptState(chunk)
2102
- // Live path: yield a macrotask so the UI can paint. Skip when the page is
2103
- // hidden. Browsers clamp setTimeout there, and that wait paces stream pull.
2104
- // Replay passes defer: false so a backlog applies in one batch.
2105
- if (
2106
- options?.defer !== false &&
2107
- (typeof document === 'undefined' || !document.hidden)
2108
- ) {
2109
- await new Promise((resolve) => setTimeout(resolve, 0))
2110
- }
2111
2131
  this.resolveJoinedRun(chunk)
2112
2132
  }
2113
2133
 
@@ -2870,12 +2890,22 @@ export class ChatClient<
2870
2890
  continuationGeneration: number,
2871
2891
  context?: ChatClientRunEventContext,
2872
2892
  ): Promise<void> {
2873
- if (clientTool && result.state !== 'output-error') {
2893
+ if (result.state !== 'output-error') {
2874
2894
  try {
2875
- result = {
2876
- ...result,
2877
- output: this.validateClientToolOutput(clientTool, result.output),
2895
+ let output =
2896
+ clientTool?.outputSchema && isStandardSchema(clientTool.outputSchema)
2897
+ ? await this.validateClientToolOutput(clientTool, result.output)
2898
+ : result.output
2899
+ // Only an interrupt resume needs JSON output. The legacy continuation
2900
+ // keeps the raw value.
2901
+ if (
2902
+ this.interruptManager
2903
+ .getDescriptors()
2904
+ .some((interrupt) => interrupt.toolCallId === result.toolCallId)
2905
+ ) {
2906
+ output = cloneAndDeepFreezeJson(output)
2878
2907
  }
2908
+ result = { ...result, output }
2879
2909
  } catch (error: any) {
2880
2910
  result = {
2881
2911
  ...result,
@@ -2907,12 +2937,16 @@ export class ChatClient<
2907
2937
  )
2908
2938
  this.devtoolsBridge.emitSnapshot()
2909
2939
 
2910
- const resolvedViaInterrupt = this.interruptManager.resolveClientToolOutput(
2911
- result.toolCallId,
2940
+ const resolvedViaInterrupt =
2912
2941
  result.state === 'output-error'
2913
- ? { error: result.errorText || 'Tool execution failed' }
2914
- : result.output,
2915
- )
2942
+ ? this.interruptManager.resolveClientToolError(
2943
+ result.toolCallId,
2944
+ result.errorText || 'Tool execution failed',
2945
+ )
2946
+ : this.interruptManager.resolveClientToolOutput(
2947
+ result.toolCallId,
2948
+ result.output,
2949
+ )
2916
2950
  if (resolvedViaInterrupt) {
2917
2951
  // Interrupt manager stages/submits the resume batch (deferred until the
2918
2952
  // parent stream settles when still loading). Skip legacy continuation.
@@ -2932,15 +2966,20 @@ export class ChatClient<
2932
2966
  await this.checkForContinuation()
2933
2967
  }
2934
2968
 
2935
- private validateClientToolOutput(
2969
+ private async validateClientToolOutput(
2936
2970
  clientTool: AnyClientTool,
2937
- output: any,
2938
- ): any {
2939
- if (clientTool.outputSchema && isStandardSchema(clientTool.outputSchema)) {
2940
- return parseWithStandardSchema(clientTool.outputSchema, output)
2971
+ output: unknown,
2972
+ ): Promise<unknown> {
2973
+ const validation = await validateWithStandardSchema<unknown>(
2974
+ clientTool.outputSchema,
2975
+ output,
2976
+ )
2977
+ if (!validation.success) {
2978
+ throw new Error(
2979
+ validation.issues.map((issue) => issue.message).join(', '),
2980
+ )
2941
2981
  }
2942
-
2943
- return output
2982
+ return validation.data
2944
2983
  }
2945
2984
 
2946
2985
  /**
@@ -11,6 +11,7 @@ import {
11
11
  isStandardSchema,
12
12
  normalizeApprovalSchema,
13
13
  readInterruptBinding,
14
+ withTanstackMetadata,
14
15
  wrapGenericInterruptContinuation,
15
16
  } from '@tanstack/ai/client'
16
17
  import type {
@@ -124,11 +125,13 @@ function resolutionWithContinuation(
124
125
  const continuation = genericInterruptContinuationFromDescriptor(
125
126
  item.descriptor,
126
127
  )
127
- if (!continuation) return resolution
128
- return {
129
- ...resolution,
130
- metadata: wrapGenericInterruptContinuation(continuation),
128
+ if (continuation) {
129
+ return {
130
+ ...resolution,
131
+ metadata: wrapGenericInterruptContinuation(continuation),
132
+ }
131
133
  }
134
+ return resolution
132
135
  }
133
136
 
134
137
  function isRootResolvableInterrupt<
@@ -684,6 +687,25 @@ export class InterruptManager<
684
687
  }
685
688
 
686
689
  resolveClientToolOutput(toolCallId: string, output: unknown): boolean {
690
+ return this.resolveClientToolResult(toolCallId, {
691
+ state: 'output-available',
692
+ output,
693
+ })
694
+ }
695
+
696
+ resolveClientToolError(toolCallId: string, errorText: string): boolean {
697
+ return this.resolveClientToolResult(toolCallId, {
698
+ state: 'output-error',
699
+ errorText,
700
+ })
701
+ }
702
+
703
+ private resolveClientToolResult(
704
+ toolCallId: string,
705
+ result:
706
+ | { state: 'output-available'; output: unknown }
707
+ | { state: 'output-error'; errorText: string },
708
+ ): boolean {
687
709
  const item = this.items.find(
688
710
  (candidate) =>
689
711
  (candidate.kind === 'client-tool-execution' &&
@@ -695,10 +717,56 @@ export class InterruptManager<
695
717
  isLegacyClientToolMetadata(candidate.descriptor.metadata)),
696
718
  )
697
719
  if (!item) return false
698
- this.resolveItem(item.descriptor.id, output)
720
+ if (item.kind !== 'client-tool-execution') {
721
+ this.resolveItem(
722
+ item.descriptor.id,
723
+ result.state === 'output-error'
724
+ ? { error: result.errorText }
725
+ : result.output,
726
+ )
727
+ return true
728
+ }
729
+ if (result.state === 'output-available') {
730
+ this.resolveItem(item.descriptor.id, result.output)
731
+ return true
732
+ }
733
+ this.stageClientToolError(item, result.errorText)
699
734
  return true
700
735
  }
701
736
 
737
+ private stageClientToolError(
738
+ item: RuntimeInterrupt,
739
+ errorText: string,
740
+ ): void {
741
+ this.assertItemMutable()
742
+ this.invalidateRetry()
743
+ if (!item.canResolve) {
744
+ item.status = 'error'
745
+ item.error = this.itemError(
746
+ item.descriptor.id,
747
+ 'invalid-response-schema',
748
+ 'The interrupt response schema is invalid and cannot be resolved.',
749
+ )
750
+ this.publish()
751
+ return
752
+ }
753
+ item.validationGeneration++
754
+ item.resolution = cloneAndDeepFreezeJson(
755
+ withTanstackMetadata(
756
+ resolutionWithContinuation(item, {
757
+ interruptId: item.descriptor.id,
758
+ status: 'resolved',
759
+ payload: { error: errorText },
760
+ }),
761
+ { state: 'output-error' },
762
+ ),
763
+ )
764
+ item.status = 'staged'
765
+ item.error = undefined
766
+ this.publish()
767
+ this.maybeSubmit()
768
+ }
769
+
702
770
  resolveToolApprovalDecision(interruptId: string, approved: boolean): boolean {
703
771
  const item = this.items.find(
704
772
  (candidate) =>
@@ -1279,11 +1347,28 @@ export class InterruptManager<
1279
1347
  : preserveInput(validation)
1280
1348
  }
1281
1349
  if (item.kind === 'client-tool-execution') {
1282
- return validateWithSchema(
1350
+ const validation = validateWithSchema(
1283
1351
  item.tool?.outputSchema,
1284
1352
  payload,
1285
1353
  'invalid-tool-output',
1286
1354
  )
1355
+ const canonicalize = (result: ValidationResult): ValidationResult => {
1356
+ if (!('valid' in result)) return result
1357
+ try {
1358
+ return {
1359
+ valid: true,
1360
+ payload: cloneAndDeepFreezeJson(result.payload),
1361
+ }
1362
+ } catch (error) {
1363
+ return {
1364
+ code: 'invalid-tool-output',
1365
+ message: error instanceof Error ? error.message : String(error),
1366
+ }
1367
+ }
1368
+ }
1369
+ return isPromiseLike(validation)
1370
+ ? Promise.resolve(validation).then(canonicalize)
1371
+ : canonicalize(validation)
1287
1372
  }
1288
1373
  return this.validateApprovalCandidate(item, payload)
1289
1374
  }
package/src/types.ts CHANGED
@@ -24,6 +24,7 @@ import type {
24
24
  StructuredOutputPart,
25
25
  SubagentHandleData,
26
26
  SubagentStatus,
27
+ ToolResultOutcome,
27
28
  UIResourcePart,
28
29
  VideoPart,
29
30
  } from '@tanstack/ai/client'
@@ -618,6 +619,8 @@ export interface ToolResultPart {
618
619
  toolCallId: string
619
620
  content: string | Array<ContentPart>
620
621
  state: ToolResultState
622
+ /** Set when the user or middleware cancelled or denied the tool call; state remains `error`. */
623
+ outcome?: ToolResultOutcome
621
624
  error?: string // Error message if state is "error"
622
625
  metadata?: Record<string, unknown>
623
626
  createdAt?: Date