@tanstack/ai-client 0.25.2 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +2 -1
  2. package/dist/esm/byok/client.d.ts +52 -0
  3. package/dist/esm/byok/client.js +300 -0
  4. package/dist/esm/byok/client.js.map +1 -0
  5. package/dist/esm/byok/passkey.d.ts +43 -0
  6. package/dist/esm/byok/passkey.js +251 -0
  7. package/dist/esm/byok/passkey.js.map +1 -0
  8. package/dist/esm/byok/resolve.d.ts +8 -0
  9. package/dist/esm/byok/resolve.js +20 -0
  10. package/dist/esm/byok/resolve.js.map +1 -0
  11. package/dist/esm/byok/storage.d.ts +15 -0
  12. package/dist/esm/byok/storage.js +16 -0
  13. package/dist/esm/byok/storage.js.map +1 -0
  14. package/dist/esm/byok.d.ts +8 -0
  15. package/dist/esm/byok.js +5 -0
  16. package/dist/esm/chat-client.d.ts +18 -5
  17. package/dist/esm/chat-client.js +96 -59
  18. package/dist/esm/chat-client.js.map +1 -1
  19. package/dist/esm/connection-adapters.d.ts +2 -0
  20. package/dist/esm/connection-adapters.js +70 -30
  21. package/dist/esm/connection-adapters.js.map +1 -1
  22. package/dist/esm/generation-client.d.ts +3 -1
  23. package/dist/esm/generation-client.js +27 -6
  24. package/dist/esm/generation-client.js.map +1 -1
  25. package/dist/esm/generation-types.d.ts +14 -0
  26. package/dist/esm/generation-types.js +4 -2
  27. package/dist/esm/generation-types.js.map +1 -1
  28. package/dist/esm/interrupt-manager.d.ts +1 -0
  29. package/dist/esm/interrupt-manager.js +15 -6
  30. package/dist/esm/interrupt-manager.js.map +1 -1
  31. package/dist/esm/sse-parser.js +8 -1
  32. package/dist/esm/sse-parser.js.map +1 -1
  33. package/dist/esm/types.d.ts +46 -3
  34. package/dist/esm/types.js.map +1 -1
  35. package/dist/esm/video-generation-client.d.ts +3 -1
  36. package/dist/esm/video-generation-client.js +29 -8
  37. package/dist/esm/video-generation-client.js.map +1 -1
  38. package/package.json +7 -3
  39. package/src/byok/client.ts +360 -0
  40. package/src/byok/passkey.ts +399 -0
  41. package/src/byok/resolve.ts +30 -0
  42. package/src/byok/storage.ts +29 -0
  43. package/src/byok.ts +20 -0
  44. package/src/chat-client.ts +138 -77
  45. package/src/connection-adapters.ts +108 -53
  46. package/src/generation-client.ts +53 -9
  47. package/src/generation-types.ts +24 -2
  48. package/src/interrupt-manager.ts +20 -6
  49. package/src/sse-parser.ts +10 -0
  50. package/src/types.ts +48 -3
  51. package/src/video-generation-client.ts +50 -9
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","names":[],"sources":["../../src/types.ts"],"sourcesContent":["import type {\n AnyClientTool,\n ApprovalCapabilityOf,\n ApprovalSchemaOf,\n AudioPart,\n BatchInterruptError,\n ChunkStrategy,\n ContentPart,\n DocumentPart,\n ImagePart,\n InferSchemaType,\n InterruptDefinition,\n InferToolInput,\n InferToolOutput,\n InputSchemaOf,\n Interrupt,\n InterruptBinding,\n ItemInterruptError,\n ModelMessage,\n NoSchema,\n RunAgentResumeItem,\n SchemaInput,\n StreamChunk,\n StructuredOutputPart,\n UIResourcePart,\n VideoPart,\n} from '@tanstack/ai/client'\nimport type { 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}\n\n/**\n * Direct function that performs a chat request. Mirrors\n * `GenerationFetcher`. Returns either a `Response` (SSE body parsed by the\n * chat client) or an `AsyncIterable<StreamChunk>` (yielded directly). May\n * return the value synchronously, as a `Promise`, or as an async generator\n * (`async function*`) — the chat client awaits whichever shape is returned.\n *\n * @example\n * ```ts\n * useChat({\n * fetcher: ({ messages }, { signal }) =>\n * chatFn({ data: { messages }, signal }),\n * })\n * ```\n */\nexport type ChatFetcher = (\n input: ChatFetcherInput,\n options: ChatFetcherOptions,\n) =>\n | Response\n | AsyncIterable<StreamChunk>\n | Promise<Response | AsyncIterable<StreamChunk>>\n\n/**\n * Distributive `Omit` — applies `Omit<O, K>` per branch of a union so\n * discriminated unions survive omission. Plain `Omit` collapses unions\n * into a single object shape, which would erase the `ChatTransport` XOR\n * when framework hooks omit React-managed callbacks from\n * `ChatClientOptions`.\n */\nexport type DistributedOmit<\n TObject,\n TKeys extends keyof any,\n> = TObject extends unknown ? Omit<TObject, TKeys> : never\n\n/**\n * Discriminated union enforcing that exactly one of `connection` or\n * `fetcher` is provided. Mirrors `GenerationTransport`.\n */\nexport type ChatTransport =\n | { connection: ConnectionAdapter; fetcher?: never }\n | { fetcher: ChatFetcher; connection?: never }\n\n/**\n * Tool call states - track the lifecycle of a tool call\n */\nexport type ToolCallState =\n | 'awaiting-input' // Received start but no arguments yet\n | 'input-streaming' // Partial arguments received\n | 'input-complete' // All arguments received\n | 'approval-requested' // Waiting for user approval\n | 'approval-responded' // User has approved/denied\n | 'complete' // Result is complete\n | 'error' // Tool execution failed (terminal)\n\n/**\n * Tool result states - track the lifecycle of a tool result\n */\nexport type ToolResultState =\n | 'streaming' // Placeholder for future streamed output\n | 'complete' // Result is complete\n | 'error' // Error occurred\n\n/**\n * ChatClient state - track the lifecycle of a chat\n */\nexport type ChatClientState = 'ready' | 'submitted' | 'streaming' | 'error'\n\n/**\n * Connection lifecycle state for the subscription loop.\n */\nexport type ConnectionStatus =\n | 'disconnected'\n | 'connecting'\n | 'connected'\n | 'error'\n\n/**\n * Multimodal content input for sending messages with rich media.\n * Allows sending text, images, audio, video, and documents to the LLM.\n *\n * @example\n * ```ts\n * // Send an image with a question\n * client.sendMessage({\n * content: [\n * { type: 'text', content: 'What is in this image?' },\n * { type: 'image', source: { type: 'url', value: 'https://example.com/photo.jpg' } }\n * ],\n * id: 'custom-message-id' // optional\n * })\n * ```\n */\nexport interface MultimodalContent {\n /**\n * The content of the message.\n * Can be a simple string or an array of content parts for multimodal messages.\n */\n content: string | Array<ContentPart>\n /**\n * Optional custom ID for the message.\n * If not provided, a unique ID will be generated.\n */\n id?: string\n}\n\n/**\n * Action taken when `sendMessage` is called while the client is busy\n * (streaming, claiming a send, or draining the queue).\n * - `queue`: hold the message; it auto-sends when the current run settles\n * **successfully**.\n * - `drop`: ignore the send (promise still resolves; does not throw).\n * - `interrupt`: abort the current stream and send immediately. Unlike\n * `stop()`, does **not** flush already-queued messages — they still drain\n * after the interrupting send settles successfully.\n */\nexport type WhenBusy = 'queue' | 'drop' | 'interrupt'\n\n/**\n * Why the client is busy when a {@link QueueStrategy} runs.\n * - `streaming` — an LLM stream is active (`isLoading`).\n * - `sendInFlight` — a send has claimed the client but is not yet loading.\n * - `draining` — the queue drain loop is delivering pending messages.\n */\nexport type QueueBusyReason = 'streaming' | 'sendInFlight' | 'draining'\n\n/**\n * A user message held in the send queue while a stream is active.\n * Rendered separately from `messages`; cancellable via `cancelQueued(id)`\n * until it drains.\n */\nexport interface QueuedMessage {\n id: string\n content: string | MultimodalContent\n createdAt: number\n}\n\n/**\n * Declarative queue policy.\n */\nexport interface QueueConfig {\n /**\n * Action when the client is busy (streaming, claiming a send, or draining).\n * Default `'queue'`.\n */\n whenBusy?: WhenBusy\n /**\n * How queued items leave the queue.\n * - `'fifo'`: one at a time, in order (default).\n * - `'batch'`: merge all queued items into one send when the run settles\n * successfully.\n */\n drain?: 'fifo' | 'batch'\n /** Max queued items. Unlimited when omitted. `0` means never queue. */\n maxSize?: number\n /**\n * Behavior when `maxSize` is reached. Default `'reject'`.\n * `'reject'` silently discards the new send (does not throw);\n * `'drop-oldest'` evicts the oldest queued item to make room.\n * Only meaningful when `maxSize` is set.\n */\n onOverflow?: 'reject' | 'drop-oldest'\n}\n\n/**\n * Escape hatch: decide the action for a single send. Drain stays FIFO for the\n * function form (no `batch` via function). Per-call `sendOptions.whenBusy`\n * overrides the strategy for that send.\n *\n * Actions match {@link WhenBusy}: `'queue' | 'drop' | 'interrupt'`. Concurrent\n * streams are not supported. `pending.id` is the id that will be stored if the\n * action is `'queue'` (safe to pass to `cancelQueued`).\n */\nexport type QueueStrategy = (ctx: {\n pending: QueuedMessage\n busyReason: QueueBusyReason\n queued: ReadonlyArray<QueuedMessage>\n}) => { action: WhenBusy }\n\n/** A `WhenBusy` shorthand, a full config, or a strategy function. */\nexport type QueueOption = WhenBusy | QueueConfig | QueueStrategy\n\n/** Per-call overrides for `sendMessage`. */\nexport interface SendMessageOptions {\n /** Overrides the configured `whenBusy` for this one send. */\n whenBusy?: WhenBusy\n}\n\n/**\n * Message parts - building blocks of UIMessage\n */\nexport interface TextPart {\n type: 'text'\n content: string\n}\n\n/**\n * Helper type that creates a tool-call part for a specific tool.\n * This is a conditional type to enable proper distribution over union types,\n * creating a discriminated union where `name` is the discriminant.\n */\ntype ToolCallPartForTool<T> = T extends AnyClientTool\n ? {\n type: 'tool-call'\n id: string\n name: T['name']\n arguments: string // JSON string (may be incomplete)\n /** Parsed tool input (typed from inputSchema) */\n input?: InferToolInput<T>\n state: ToolCallState\n /** Tool execution output (for client tools or after approval) */\n output?: InferToolOutput<T>\n } & (NonNullable<T['needsApproval']> extends true\n ? {\n /**\n * Approval metadata — present only on tools defined with\n * `needsApproval: true`. Populated once the call reaches\n * `state: 'approval-requested'`. `needsApproval` is an optional\n * property on the tool, so we index into it (rather than\n * `T extends { needsApproval: true }`, which an optional property\n * never satisfies) and strip `undefined` before comparing to `true`.\n */\n approval?: {\n id: string // Unique approval ID\n needsApproval: boolean // Always true if present\n approved?: boolean // User's decision (undefined until responded)\n }\n }\n : // Tools without `needsApproval: true` never carry an approval field.\n // `& unknown` is a no-op intersection (adds nothing).\n unknown)\n : never\n\n/**\n * Fallback tool-call part type when tools are not typed\n */\ntype UntypedToolCallPart = {\n type: 'tool-call'\n id: string\n name: string\n arguments: string\n input?: any\n state: ToolCallState\n approval?: {\n id: string\n needsApproval: boolean\n approved?: boolean\n }\n output?: any\n}\n\n/**\n * Tool call part that creates a proper discriminated union.\n * When TTools is typed, checking `part.name === 'toolName'` will narrow\n * `part.output` to the correct type for that tool.\n *\n * The discriminant is `name`, so code like:\n * ```ts\n * if (part.name === 'recommendGuitar') {\n * // part.output is now typed to the recommendGuitar tool's output\n * }\n * ```\n */\nexport type ToolCallPart<TTools extends ReadonlyArray<AnyClientTool> = any> =\n // Check if we have a concrete tools array (not 'any' or 'never')\n [TTools] extends [never]\n ? UntypedToolCallPart\n : unknown extends TTools\n ? UntypedToolCallPart\n : TTools extends ReadonlyArray<infer Tool>\n ? Tool extends AnyClientTool\n ? ToolCallPartForTool<Tool>\n : UntypedToolCallPart\n : UntypedToolCallPart\n\nexport interface ToolResultPart {\n type: 'tool-result'\n toolCallId: string\n content: string | Array<ContentPart>\n state: ToolResultState\n error?: string // Error message if state is \"error\"\n}\n\nexport interface ThinkingPart {\n type: 'thinking'\n content: string\n}\n\nexport type MessagePart<\n TTools extends ReadonlyArray<AnyClientTool> = any,\n TData = unknown,\n> =\n | TextPart\n | ImagePart\n | AudioPart\n | VideoPart\n | DocumentPart\n | ToolCallPart<TTools>\n | ToolResultPart\n | ThinkingPart\n | StructuredOutputPart<TData>\n | UIResourcePart\n\n/**\n * UIMessage - Domain-specific message format optimized for building chat UIs\n * Contains parts that can be text, tool calls, or tool results.\n *\n * `TTools` narrows the tool-call/result part types based on the registered\n * tools. `TData` is the schema-inferred type for any `structured-output` part\n * on the message — defaulted to `unknown` so untyped consumers (the core\n * stream processor, the wire converter) don't need to thread a schema generic\n * everywhere; the hook layer (`useChat({ outputSchema })`) substitutes it on\n * the public return so `m.parts.find(p => p.type === 'structured-output').data`\n * is typed without manual casts.\n */\nexport interface UIMessage<\n TTools extends ReadonlyArray<AnyClientTool> = any,\n TData = unknown,\n> {\n id: string\n role: 'system' | 'user' | 'assistant'\n parts: Array<MessagePart<TTools, TData>>\n createdAt?: Date\n}\n\n/**\n * A generic key/value storage adapter. `getItem` may be sync or async; the\n * chat persistence layer treats every call as best-effort. The provided\n * `localStoragePersistence` / `sessionStoragePersistence` / `indexedDBPersistence`\n * factories return one of these, and `ChatStorageAdapter<ChatPersistedState>`\n * is assignable to {@link ChatClientPersistence}.\n */\nexport interface ChatStorageAdapter<TValue> {\n getItem: (\n id: string,\n ) => TValue | null | undefined | Promise<TValue | null | undefined>\n setItem: (id: string, value: TValue) => void | Promise<void>\n removeItem: (id: string) => void | Promise<void>\n}\n\n/**\n * The single record a `ChatClientPersistence` adapter stores per chat. It folds\n * the two things that must survive a full page reload into one blob under one\n * key: the message transcript and the optional resume snapshot (which run to\n * rejoin / which interrupts to rehydrate). One adapter, one key — see\n * {@link ChatClientPersistence}.\n */\nexport interface ChatPersistedState<\n TTools extends ReadonlyArray<AnyClientTool> = any,\n> {\n messages: Array<UIMessage<TTools>>\n /** Present while a run is in flight or paused on an interrupt; absent otherwise. */\n resume?: ChatResumeSnapshot\n}\n\n/**\n * Storage adapter for durable chat state. A single adapter persists both the\n * message transcript and the resume snapshot as one {@link ChatPersistedState}\n * record, so a full page reload restores the conversation AND can rejoin an\n * in-flight run / rehydrate pending interrupts.\n *\n * For backward compatibility `getItem` may also return a bare `UIMessage[]`\n * (the legacy messages-only format); the client normalizes it to\n * `{ messages }`. `setItem` always writes the combined record.\n */\nexport interface ChatClientPersistence<\n TTools extends ReadonlyArray<AnyClientTool> = any,\n> {\n getItem: (\n id: string,\n ) =>\n | ChatPersistedState<TTools>\n | Array<UIMessage<TTools>>\n | null\n | undefined\n | Promise<\n ChatPersistedState<TTools> | Array<UIMessage<TTools>> | null | undefined\n >\n setItem: (\n id: string,\n state: ChatPersistedState<TTools>,\n ) => void | Promise<void>\n removeItem: (id: string) => void | Promise<void>\n}\n\n/**\n * The `persistence` option for a chat.\n *\n * - `false` (default): ephemeral. Messages live in memory only; a reload starts\n * from empty.\n * - `true`: server-authoritative. Nothing is cached in the browser. On mount the\n * client hydrates the thread from the server by its `threadId` (paints the\n * stored transcript and tails any run still generating), so a reload or the\n * same thread opened on another device both just resume. Requires a connection\n * with a `hydrate` handler.\n * - a {@link ChatClientPersistence} adapter: client-authoritative. The combined\n * {@link ChatPersistedState} record (transcript plus resume pointer) is cached\n * in the browser and restored on reload with no network.\n */\nexport type ChatPersistenceOption<\n TTools extends ReadonlyArray<AnyClientTool> = any,\n> = boolean | ChatClientPersistence<TTools>\n\n/**\n * The `persistence` / `threadId` pairing for `ChatClient` and the chat hooks.\n *\n * Persistence that is on (`true` or a storage adapter) requires a `threadId`.\n * A minted id changes every reload, so nothing would restore. The compiler\n * asks for the conversation id instead.\n *\n * Omit `persistence`, or set it to `false`, and `threadId` stays optional.\n * The client then mints one after mount for the wire and DevTools.\n *\n * Intersect this onto `ChatClientOptions`. Do not apply a later plain `Omit`\n * to that type: it collapses the union and the requirement disappears. Use\n * {@link DistributedOmit}.\n */\nexport type ChatPersistenceOptions<\n TTools extends ReadonlyArray<AnyClientTool> = any,\n> =\n | {\n persistence: true\n threadId: string\n }\n | {\n persistence: ChatClientPersistence<TTools>\n threadId: string\n }\n | {\n persistence?: false | undefined\n threadId?: string\n }\n\ntype IsUnknown<T> = unknown extends T\n ? [T] extends [unknown]\n ? true\n : false\n : false\n\ntype KnownContext<T> = IsUnknown<T> extends true ? never : T\n\ntype MergeContext<TLeft, TRight> = [TLeft] extends [never]\n ? TRight\n : [TRight] extends [never]\n ? TLeft\n : TLeft & TRight\n\ntype UnionToIntersection<T> = [T] extends [never]\n ? never\n : (T extends unknown ? (value: T) => void : never) extends (\n value: infer TIntersection,\n ) => void\n ? TIntersection\n : never\n\ntype DefinedContext<T> = Exclude<T, undefined>\n\ntype ContextFromExecute<T> = T extends (...args: any) => any\n ? NonNullable<Parameters<T>[1]> extends { context: infer TContext }\n ? KnownContext<TContext>\n : never\n : never\n\ntype ContextFromClientTool<T> = T extends AnyClientTool\n ? T extends { execute?: infer TExecute }\n ? ContextFromExecute<TExecute>\n : never\n : never\n\ntype RequiredContextFromClientToolUnion<T> = T extends unknown\n ? undefined extends ContextFromClientTool<T>\n ? never\n : ContextFromClientTool<T>\n : never\n\ntype ContextFromClientToolUnion<T> = [\n UnionToIntersection<DefinedContext<ContextFromClientTool<T>>>,\n] extends [never]\n ? never\n : [RequiredContextFromClientToolUnion<T>] extends [never]\n ? UnionToIntersection<DefinedContext<ContextFromClientTool<T>>> | undefined\n : UnionToIntersection<DefinedContext<ContextFromClientTool<T>>>\n\ntype ContextFromClientTools<TTools> =\n IsUnknown<TTools> extends true\n ? never\n : TTools extends readonly [infer THead, ...infer TTail]\n ? MergeContext<\n ContextFromClientTool<THead>,\n ContextFromClientTools<TTail>\n >\n : TTools extends ReadonlyArray<infer TItem>\n ? ContextFromClientToolUnion<TItem>\n : never\n\nexport type InferredClientContext<TTools> = [\n ContextFromClientTools<TTools>,\n] extends [never]\n ? unknown\n : ContextFromClientTools<TTools>\n\nexport type ClientContextOptionFromTools<TTools, TContext> = [\n ContextFromClientTools<TTools>,\n] extends [never]\n ? { context?: TContext }\n : undefined extends ContextFromClientTools<TTools>\n ? { context?: TContext & ContextFromClientTools<TTools> }\n : { context: TContext & ContextFromClientTools<TTools> }\n\n/**\n * Base options for `ChatClient`, excluding the transport (`connection` or\n * `fetcher`) which is supplied separately via `ChatTransport` so the XOR\n * is preserved when composing the final `ChatClientOptions` type.\n */\nexport interface ChatClientBaseOptions<\n TTools extends ReadonlyArray<AnyClientTool> = any,\n TContext = unknown,\n 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 * 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":";;;;;;;;;;;;;;;;AAmhCA,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 UIResourcePart,\n VideoPart,\n} from '@tanstack/ai/client'\nimport type { ByokClient } from './byok'\nimport type { ConnectionAdapter } from './connection-adapters'\nimport type { AIDevtoolsClientMetadata } from './devtools'\nimport type { ChatDevtoolsBridgeFactory } from './devtools-noop'\n\nexport type { StructuredOutputPart }\n\nexport interface ChatResumeState {\n threadId: string\n runId: string\n}\n\nexport type ChatPendingInterrupt = Interrupt\n\n/**\n * The durable pointer a chat keeps for the run it may need to rejoin, plus any\n * interrupt that run is waiting on.\n *\n * @internal\n */\nexport interface ChatResumeSnapshot {\n resumeState: ChatResumeState\n pendingInterrupts?: Array<ChatPendingInterrupt>\n}\n\nexport type InterruptItemStatus =\n | 'pending'\n | 'validating'\n | 'staged'\n | 'submitting'\n | 'error'\n\nexport interface BoundInterruptBase {\n readonly id: string\n readonly interruptId: string\n readonly reason: string\n readonly message?: string\n readonly responseSchema?: Readonly<Record<string, unknown>>\n readonly expiresAt?: string\n readonly metadata?: Readonly<Record<string, unknown>>\n readonly threadId: string\n readonly interruptedRunId: string\n readonly generation: number\n readonly status: InterruptItemStatus\n readonly errors: ReadonlyArray<ItemInterruptError>\n /** @deprecated Use `errors[0]`. */\n readonly error?: ItemInterruptError\n /**\n * Whether the binding/schema allows resolution at hydrate time.\n * Does not flip on submit/expiry — gate UI on `status`, `resuming`, and\n * `errors` for those lifecycle states.\n */\n readonly canResolve: boolean\n cancel: () => void\n clearResolution: () => void\n}\n\nexport interface GenericAGUIInterrupt extends BoundInterruptBase {\n readonly kind: 'generic'\n readonly binding: Readonly<Extract<InterruptBinding, { kind: 'generic' }>>\n resolveInterrupt: (payload: unknown) => void\n}\n\ntype InterruptResponseInput<TDefinition> =\n TDefinition extends InterruptDefinition<any, any, infer TResponseSchema, any>\n ? InferSchemaType<TResponseSchema>\n : never\n\ntype RegisteredGenericInterruptFor<\n TDefinition extends InterruptDefinition<any, any, any, any>,\n> =\n TDefinition extends InterruptDefinition<\n infer TDefinitionId,\n any,\n any,\n infer TPayload\n >\n ? BoundInterruptBase & {\n readonly kind: 'generic'\n readonly definitionId: TDefinitionId\n readonly key: string\n readonly payload: TPayload | undefined\n readonly binding: Readonly<\n Extract<InterruptBinding, { kind: 'generic' }> & {\n definitionId: TDefinitionId\n key: string\n batchIndex: number\n }\n >\n resolveInterrupt: (\n response: InterruptResponseInput<TDefinition>,\n ) => void\n }\n : never\n\nexport type RegisteredGenericInterrupt<\n TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>>,\n> = TInterrupts[number] extends infer TDefinition\n ? TDefinition extends InterruptDefinition<any, any, any, any>\n ? RegisteredGenericInterruptFor<TDefinition>\n : never\n : never\n\n/** A bound generic interrupt for one `defineInterrupt()` definition. */\nexport type GenericInterrupt<\n TDefinition extends InterruptDefinition<any, any, any, any>,\n> = RegisteredGenericInterruptFor<TDefinition>\n\n/**\n * An interrupt that arrived on the stream carrying no resume binding this\n * client understands — no `tanstack:interruptBinding`, or one written at a\n * protocol version we don't recognise.\n *\n * These are surfaced rather than hidden so a UI can show that the run is\n * paused, but they are never resolvable here: something else owns them. A\n * workflow engine's durable approval projected into the same AG-UI stream\n * lands in this bucket, and resolving it through the chat resume path would\n * send an answer no one is waiting for. Render it, or route it to whatever\n * actually owns the pause.\n */\nexport interface UnboundInterrupt extends Omit<\n BoundInterruptBase,\n 'cancel' | 'clearResolution'\n> {\n readonly kind: 'unbound'\n readonly binding?: undefined\n readonly canResolve: false\n}\n\ntype ApprovalBranchSchema<TTool, TBranch extends 'approve' | 'reject'> =\n ApprovalSchemaOf<TTool> extends infer TApproval\n ? TApproval extends { approve?: SchemaInput; reject?: SchemaInput }\n ? Exclude<TApproval[TBranch], undefined>\n : TApproval extends SchemaInput\n ? TApproval\n : never\n : never\n\ntype ApprovalEdits<TTool> =\n InputSchemaOf<TTool> extends NoSchema\n ? { editedArgs?: never }\n : { editedArgs?: InferToolInput<TTool> }\n\ntype ApprovalPayload<TSchema> = [TSchema] extends [never]\n ? { payload?: never }\n : TSchema extends SchemaInput\n ? { payload: InferSchemaType<TSchema> }\n : { payload?: never }\n\ntype ApproveArguments<TTool> = [\n ApprovalBranchSchema<TTool, 'approve'>,\n] extends [never]\n ? InputSchemaOf<TTool> extends NoSchema\n ? [options?: never]\n : [options?: ApprovalEdits<TTool> & { payload?: never }]\n : [\n options: ApprovalEdits<TTool> &\n ApprovalPayload<ApprovalBranchSchema<TTool, 'approve'>>,\n ]\n\ntype RejectArguments<TTool> = [ApprovalBranchSchema<TTool, 'reject'>] extends [\n never,\n]\n ? [options?: never]\n : [\n options: { editedArgs?: never } & ApprovalPayload<\n ApprovalBranchSchema<TTool, 'reject'>\n >,\n ]\n\nexport type ToolApprovalInterrupt<TTool extends AnyClientTool = AnyClientTool> =\n TTool extends AnyClientTool\n ? BoundInterruptBase & {\n readonly kind: 'tool-approval'\n readonly binding: Readonly<\n Extract<InterruptBinding, { kind: 'tool-approval' }>\n >\n readonly toolName: TTool['name']\n readonly toolCallId: string\n readonly originalArgs: InferToolInput<TTool>\n // A single generic call signature — not two overloads. Overloads break\n // editor autocomplete: a half-typed options literal (e.g.\n // `resolveInterrupt(true, { payload: {` ) satisfies neither overload,\n // so TS resolves no signature and offers no contextual completions.\n // Making `approved` a generic discriminant lets TS infer it from the\n // first argument and pick the matching branch for the rest params, so\n // `payload` / `editedArgs` / the correct schema's fields complete\n // per-branch (a plain union-of-tuples would offer both branches'\n // fields) while still enforcing the right shape.\n resolveInterrupt: <TApproved extends boolean>(\n approved: TApproved,\n ...args: TApproved extends true\n ? ApproveArguments<TTool>\n : RejectArguments<TTool>\n ) => void\n }\n : never\n\ntype ApprovalInterrupts<TTools extends ReadonlyArray<AnyClientTool>> =\n TTools[number] extends infer TTool\n ? TTool extends AnyClientTool\n ? ApprovalCapabilityOf<TTool> extends true\n ? ToolApprovalInterrupt<TTool>\n : never\n : never\n : never\n\n// Client tools resolve through their `.client()` implementation (auto-run) or\n// `addToolResult` — never as a bound interrupt. The `client-tool-execution`\n// pause is handled internally and is intentionally absent from this public\n// union.\nexport type ChatInterrupt<\n TTools extends ReadonlyArray<AnyClientTool> = ReadonlyArray<AnyClientTool>,\n TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> =\n readonly [],\n> =\n | GenericAGUIInterrupt\n | RegisteredGenericInterrupt<TInterrupts>\n | UnboundInterrupt\n | ApprovalInterrupts<TTools>\n\nexport type ResolvableChatInterrupt<\n TTools extends ReadonlyArray<AnyClientTool> = ReadonlyArray<AnyClientTool>,\n TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> =\n readonly [],\n> =\n | GenericAGUIInterrupt\n | RegisteredGenericInterrupt<TInterrupts>\n | ApprovalInterrupts<TTools>\n\nexport type BoundInterrupts<\n TTools extends ReadonlyArray<AnyClientTool> = ReadonlyArray<AnyClientTool>,\n TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> =\n readonly [],\n> = ReadonlyArray<ChatInterrupt<TTools, TInterrupts>>\n\nexport interface ChatInterruptState<\n TTools extends ReadonlyArray<AnyClientTool> = ReadonlyArray<AnyClientTool>,\n TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> =\n readonly [],\n> {\n readonly interrupts: BoundInterrupts<TTools, TInterrupts>\n /** @deprecated Use `interrupts`. Same snapshot today. */\n readonly pendingInterrupts: BoundInterrupts<TTools, TInterrupts>\n readonly interruptErrors: ReadonlyArray<BatchInterruptError>\n readonly resuming: boolean\n}\n\n/**\n * `messages` is the full UIMessage history (not a delta). `data` is the\n * merged body — `ChatClientOptions.body` plus any per-call data passed to\n * `sendMessage(...)`. `threadId` / `runId` are the AG-UI correlation ids\n * the chat client uses to track this turn — forward them to your server\n * if it needs to correlate requests.\n */\nexport interface ChatFetcherInput {\n messages: Array<UIMessage>\n data?: Record<string, unknown>\n threadId: string\n runId: string\n parentRunId?: string\n resume?: Array<RunAgentResumeItem>\n}\n\nexport interface ChatFetcherOptions {\n /** Fires when `stop()` is called or the request is superseded. */\n signal: AbortSignal\n /** Extra request headers for this run (e.g. BYOK keys). */\n headers?: Record<string, string>\n}\n\n/**\n * Direct function that performs a chat request. Mirrors\n * `GenerationFetcher`. Returns either a `Response` (SSE body parsed by the\n * chat client) or an `AsyncIterable<StreamChunk>` (yielded directly). May\n * return the value synchronously, as a `Promise`, or as an async generator\n * (`async function*`) — the chat client awaits whichever shape is returned.\n *\n * @example\n * ```ts\n * useChat({\n * fetcher: ({ messages }, { signal }) =>\n * chatFn({ data: { messages }, signal }),\n * })\n * ```\n */\nexport type ChatFetcher = (\n input: ChatFetcherInput,\n options: ChatFetcherOptions,\n) =>\n | Response\n | AsyncIterable<StreamChunk>\n | Promise<Response | AsyncIterable<StreamChunk>>\n\n/**\n * Distributive `Omit` — applies `Omit<O, K>` per branch of a union so\n * discriminated unions survive omission. Plain `Omit` collapses unions\n * into a single object shape, which would erase the `ChatTransport` XOR\n * when framework hooks omit React-managed callbacks from\n * `ChatClientOptions`.\n */\nexport type DistributedOmit<\n TObject,\n TKeys extends keyof any,\n> = TObject extends unknown ? Omit<TObject, TKeys> : never\n\n/**\n * Discriminated union enforcing that exactly one of `connection` or\n * `fetcher` is provided. Mirrors `GenerationTransport`.\n */\nexport type ChatTransport =\n | { connection: ConnectionAdapter; fetcher?: never }\n | { fetcher: ChatFetcher; connection?: never }\n\n/**\n * Tool call states - track the lifecycle of a tool call\n */\nexport type ToolCallState =\n | 'awaiting-input' // Received start but no arguments yet\n | 'input-streaming' // Partial arguments received\n | 'input-complete' // All arguments received\n | 'approval-requested' // Waiting for user approval\n | 'approval-responded' // User has approved/denied\n | 'complete' // Result is complete\n | 'error' // Tool execution failed (terminal)\n\n/**\n * Tool result states - track the lifecycle of a tool result\n */\nexport type ToolResultState =\n | 'streaming' // Placeholder for future streamed output\n | 'complete' // Result is complete\n | 'error' // Error occurred\n\n/**\n * ChatClient state - track the lifecycle of a chat\n */\nexport type ChatClientState = 'ready' | 'submitted' | 'streaming' | 'error'\n\n/**\n * Connection lifecycle state for the subscription loop.\n */\nexport type ConnectionStatus =\n | 'disconnected'\n | 'connecting'\n | 'connected'\n | 'error'\n\n/**\n * Multimodal content input for sending messages with rich media.\n * Allows sending text, images, audio, video, and documents to the LLM.\n *\n * @example\n * ```ts\n * // Send an image with a question\n * client.sendMessage({\n * content: [\n * { type: 'text', content: 'What is in this image?' },\n * { type: 'image', source: { type: 'url', value: 'https://example.com/photo.jpg' } }\n * ],\n * id: 'custom-message-id' // optional\n * })\n * ```\n */\nexport interface MultimodalContent {\n /**\n * The content of the message.\n * Can be a simple string or an array of content parts for multimodal messages.\n */\n content: string | Array<ContentPart>\n /**\n * Optional custom ID for the message.\n * If not provided, a unique ID will be generated.\n */\n id?: string\n /**\n * Optional AG-UI metadata bag copied onto the resulting UIMessage.\n *\n * @example\n * ```ts\n * await client.sendMessage({\n * content: 'Show me failed logins',\n * metadata: { author: { id: 'user-42', name: 'Dana' } },\n * })\n * ```\n */\n metadata?: Record<string, any>\n}\n\n/**\n * Action taken when `sendMessage` is called while the client is busy\n * (streaming, claiming a send, or draining the queue).\n * - `queue`: hold the message; it auto-sends when the current run settles\n * **successfully**.\n * - `drop`: ignore the send (promise still resolves; does not throw).\n * - `interrupt`: abort the current stream and send immediately. Unlike\n * `stop()`, does **not** flush already-queued messages — they still drain\n * after the interrupting send settles successfully.\n */\nexport type WhenBusy = 'queue' | 'drop' | 'interrupt'\n\n/**\n * Why the client is busy when a {@link QueueStrategy} runs.\n * - `streaming` — an LLM stream is active (`isLoading`).\n * - `sendInFlight` — a send has claimed the client but is not yet loading.\n * - `draining` — the queue drain loop is delivering pending messages.\n */\nexport type QueueBusyReason = 'streaming' | 'sendInFlight' | 'draining'\n\n/**\n * A user message held in the send queue while a stream is active.\n * Rendered separately from `messages`; cancellable via `cancelQueued(id)`\n * until it drains.\n */\nexport interface QueuedMessage {\n id: string\n content: string | MultimodalContent\n createdAt: number\n}\n\n/**\n * Declarative queue policy.\n */\nexport interface QueueConfig {\n /**\n * Action when the client is busy (streaming, claiming a send, or draining).\n * Default `'queue'`.\n */\n whenBusy?: WhenBusy\n /**\n * How queued items leave the queue.\n * - `'fifo'`: one at a time, in order (default).\n * - `'batch'`: merge all queued items into one send when the run settles\n * successfully.\n */\n drain?: 'fifo' | 'batch'\n /** Max queued items. Unlimited when omitted. `0` means never queue. */\n maxSize?: number\n /**\n * Behavior when `maxSize` is reached. Default `'reject'`.\n * `'reject'` silently discards the new send (does not throw);\n * `'drop-oldest'` evicts the oldest queued item to make room.\n * Only meaningful when `maxSize` is set.\n */\n onOverflow?: 'reject' | 'drop-oldest'\n}\n\n/**\n * Escape hatch: decide the action for a single send. Drain stays FIFO for the\n * function form (no `batch` via function). Per-call `sendOptions.whenBusy`\n * overrides the strategy for that send.\n *\n * Actions match {@link WhenBusy}. Concurrent streams are not supported.\n * `pending.id` is the id that will be stored if the action is `'queue'`\n * (safe to pass to `cancelQueued`).\n */\nexport type QueueStrategy = (ctx: {\n pending: QueuedMessage\n busyReason: QueueBusyReason\n queued: ReadonlyArray<QueuedMessage>\n}) => { action: WhenBusy }\n\n/** A `WhenBusy` shorthand, a full config, or a strategy function. */\nexport type QueueOption = WhenBusy | QueueConfig | QueueStrategy\n\n/** Per-call overrides for `sendMessage`. */\nexport interface SendMessageOptions {\n /** Overrides the configured `whenBusy` for this one send. */\n whenBusy?: WhenBusy\n /**\n * Extra JSON merged into this request's wire `forwardedProps`.\n * Shallow merge: `{ ...chatBody, ...positionalBody, ...body }`.\n * This field wins on key collisions.\n *\n * Framework hooks (`useChat`, `injectChat`, `createChat`) expose\n * `sendMessage(content, options)` with no positional body, so this field\n * is the per-call body channel on those surfaces.\n */\n body?: Record<string, any>\n}\n\n/**\n * Message parts - building blocks of UIMessage\n */\nexport interface TextPart {\n type: 'text'\n content: string\n}\n\n/**\n * Helper type that creates a tool-call part for a specific tool.\n * This is a conditional type to enable proper distribution over union types,\n * creating a discriminated union where `name` is the discriminant.\n */\ntype ToolCallPartForTool<T> = T extends AnyClientTool\n ? {\n type: 'tool-call'\n id: string\n name: T['name']\n arguments: string // JSON string (may be incomplete)\n /** Parsed tool input (typed from inputSchema) */\n input?: InferToolInput<T>\n state: ToolCallState\n /** Tool execution output (for client tools or after approval) */\n output?: InferToolOutput<T>\n } & (NonNullable<T['needsApproval']> extends true\n ? {\n /**\n * Approval metadata — present only on tools defined with\n * `needsApproval: true`. Populated once the call reaches\n * `state: 'approval-requested'`. `needsApproval` is an optional\n * property on the tool, so we index into it (rather than\n * `T extends { needsApproval: true }`, which an optional property\n * never satisfies) and strip `undefined` before comparing to `true`.\n */\n approval?: {\n id: string // Unique approval ID\n needsApproval: boolean // Always true if present\n approved?: boolean // User's decision (undefined until responded)\n }\n }\n : // Tools without `needsApproval: true` never carry an approval field.\n // `& unknown` is a no-op intersection (adds nothing).\n unknown)\n : never\n\n/**\n * Fallback tool-call part type when tools are not typed\n */\ntype UntypedToolCallPart = {\n type: 'tool-call'\n id: string\n name: string\n arguments: string\n input?: any\n state: ToolCallState\n approval?: {\n id: string\n needsApproval: boolean\n approved?: boolean\n }\n output?: any\n}\n\n/**\n * Tool call part that creates a proper discriminated union.\n * When TTools is typed, checking `part.name === 'toolName'` will narrow\n * `part.output` to the correct type for that tool.\n *\n * The discriminant is `name`, so code like:\n * ```ts\n * if (part.name === 'recommendGuitar') {\n * // part.output is now typed to the recommendGuitar tool's output\n * }\n * ```\n */\nexport type ToolCallPart<TTools extends ReadonlyArray<AnyClientTool> = any> =\n // Check if we have a concrete tools array (not 'any' or 'never')\n [TTools] extends [never]\n ? UntypedToolCallPart\n : unknown extends TTools\n ? UntypedToolCallPart\n : TTools extends ReadonlyArray<infer Tool>\n ? Tool extends AnyClientTool\n ? ToolCallPartForTool<Tool>\n : UntypedToolCallPart\n : UntypedToolCallPart\n\nexport interface ToolResultPart {\n type: 'tool-result'\n toolCallId: string\n content: string | Array<ContentPart>\n state: ToolResultState\n error?: string // Error message if state is \"error\"\n}\n\nexport interface ThinkingPart {\n type: 'thinking'\n content: string\n}\n\nexport type MessagePart<\n TTools extends ReadonlyArray<AnyClientTool> = any,\n TData = unknown,\n> =\n | TextPart\n | ImagePart\n | AudioPart\n | VideoPart\n | DocumentPart\n | ToolCallPart<TTools>\n | ToolResultPart\n | ThinkingPart\n | StructuredOutputPart<TData>\n | UIResourcePart\n\n/**\n * UIMessage - Domain-specific message format optimized for building chat UIs\n * Contains parts that can be text, tool calls, or tool results.\n *\n * `TTools` narrows the tool-call/result part types based on the registered\n * tools. `TData` is the schema-inferred type for any `structured-output` part\n * on the message — defaulted to `unknown` so untyped consumers (the core\n * stream processor, the wire converter) don't need to thread a schema generic\n * everywhere; the hook layer (`useChat({ outputSchema })`) substitutes it on\n * the public return so `m.parts.find(p => p.type === 'structured-output').data`\n * is typed without manual casts.\n */\nexport interface UIMessage<\n TTools extends ReadonlyArray<AnyClientTool> = any,\n TData = unknown,\n> {\n id: string\n role: 'system' | 'user' | 'assistant'\n parts: Array<MessagePart<TTools, TData>>\n createdAt?: Date\n /**\n * 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 | {\n persistence: ChatClientPersistence<TTools>\n threadId: string\n }\n | {\n persistence?: false | undefined\n threadId?: string\n }\n\ntype IsUnknown<T> = unknown extends T\n ? [T] extends [unknown]\n ? true\n : false\n : false\n\ntype KnownContext<T> = IsUnknown<T> extends true ? never : T\n\ntype MergeContext<TLeft, TRight> = [TLeft] extends [never]\n ? TRight\n : [TRight] extends [never]\n ? TLeft\n : TLeft & TRight\n\ntype UnionToIntersection<T> = [T] extends [never]\n ? never\n : (T extends unknown ? (value: T) => void : never) extends (\n value: infer TIntersection,\n ) => void\n ? TIntersection\n : never\n\ntype DefinedContext<T> = Exclude<T, undefined>\n\ntype ContextFromExecute<T> = T extends (...args: any) => any\n ? NonNullable<Parameters<T>[1]> extends { context: infer TContext }\n ? KnownContext<TContext>\n : never\n : never\n\ntype ContextFromClientTool<T> = T extends AnyClientTool\n ? T extends { execute?: infer TExecute }\n ? ContextFromExecute<TExecute>\n : never\n : never\n\ntype RequiredContextFromClientToolUnion<T> = T extends unknown\n ? undefined extends ContextFromClientTool<T>\n ? never\n : ContextFromClientTool<T>\n : never\n\ntype ContextFromClientToolUnion<T> = [\n UnionToIntersection<DefinedContext<ContextFromClientTool<T>>>,\n] extends [never]\n ? never\n : [RequiredContextFromClientToolUnion<T>] extends [never]\n ? UnionToIntersection<DefinedContext<ContextFromClientTool<T>>> | undefined\n : UnionToIntersection<DefinedContext<ContextFromClientTool<T>>>\n\ntype ContextFromClientTools<TTools> =\n IsUnknown<TTools> extends true\n ? never\n : TTools extends readonly [infer THead, ...infer TTail]\n ? MergeContext<\n ContextFromClientTool<THead>,\n ContextFromClientTools<TTail>\n >\n : TTools extends ReadonlyArray<infer TItem>\n ? ContextFromClientToolUnion<TItem>\n : never\n\nexport type InferredClientContext<TTools> = [\n ContextFromClientTools<TTools>,\n] extends [never]\n ? unknown\n : ContextFromClientTools<TTools>\n\nexport type ClientContextOptionFromTools<TTools, TContext> = [\n ContextFromClientTools<TTools>,\n] extends [never]\n ? { context?: TContext }\n : undefined extends ContextFromClientTools<TTools>\n ? { context?: TContext & ContextFromClientTools<TTools> }\n : { context: TContext & ContextFromClientTools<TTools> }\n\n/**\n * Base options for `ChatClient`, excluding the transport (`connection` or\n * `fetcher`) which is supplied separately via `ChatTransport` so the XOR\n * is preserved when composing the final `ChatClientOptions` type.\n */\nexport interface ChatClientBaseOptions<\n TTools extends ReadonlyArray<AnyClientTool> = any,\n TContext = unknown,\n TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> =\n readonly [],\n> {\n /**\n * Initial messages to populate the chat\n */\n initialMessages?: Array<UIMessage<TTools>>\n\n /**\n * Initial resumable run state, useful when rehydrating a persisted client\n * after a full page reload. This restores the client-side interrupt\n * descriptors needed to send AG-UI resume entries.\n */\n initialResumeSnapshot?: ChatResumeSnapshot\n\n /**\n * Arbitrary client-controlled JSON forwarded to the server in the\n * AG-UI `RunAgentInput.forwardedProps` field. Use this for per-session\n * options like provider/model selection or feature flags that the\n * server endpoint should read.\n *\n * Replaces the legacy `body` option. If both are provided,\n * `forwardedProps` wins on key collision.\n */\n forwardedProps?: Record<string, any>\n\n /**\n * @deprecated Use `forwardedProps` instead. `body` continues to work\n * unchanged — its values are merged into the AG-UI\n * `RunAgentInput.forwardedProps` field on the wire and are also\n * mirrored under the legacy `data` field for servers that have not\n * migrated yet. Will be removed in a future major release.\n */\n body?: Record<string, any>\n\n /**\n * Optional BYOK keyring. On each send the client prepares the resolved\n * provider and stamps `x-byok-*` request headers. Keys never go in the body.\n */\n byok?: ByokClient\n\n /**\n * Optional provider id for this chat. If it returns a provider slug,\n * only that key is prepared and sent. Otherwise the merged `provider`\n * from `forwardedProps`, `body`, and per-call `sendMessage` `body` is\n * used. Later sources win. If no slug resolves, the send throws\n * instead of attaching every stored key.\n */\n byokProvider?: () => string | undefined\n\n /**\n * Client-local runtime context passed to client tool implementations.\n *\n * This value is not serialized to the server. Use `forwardedProps` for\n * explicit client-to-server handoff of serializable values.\n */\n context?: TContext\n\n /**\n * Callback when a response is received\n */\n onResponse?: (response?: Response) => void | Promise<void>\n\n /**\n * Callback when a stream chunk is received\n */\n onChunk?: (chunk: StreamChunk) => void\n\n /**\n * Callback when the response is finished\n */\n onFinish?: (message: UIMessage<TTools>) => void\n\n /**\n * Callback when an error occurs\n */\n onError?: (error: Error) => void\n\n /**\n * Callback when messages change\n */\n onMessagesChange?: (messages: Array<UIMessage<TTools>>) => void\n\n /**\n * Callback when loading state changes\n */\n onLoadingChange?: (isLoading: boolean) => void\n\n /**\n * Callback when error state changes\n */\n onErrorChange?: (error: Error | undefined) => void\n\n /**\n * Callback when chat status changes\n */\n onStatusChange?: (status: ChatClientState) => void\n\n /**\n * Callback when subscription lifecycle changes.\n * This is independent from request lifecycle (`isLoading`, `status`).\n */\n onSubscriptionChange?: (isSubscribed: boolean) => void\n\n /**\n * Callback when connection lifecycle changes.\n */\n onConnectionStatusChange?: (status: ConnectionStatus) => void\n\n /**\n * Callback when session generation activity changes.\n * Derived from stream run events (RUN_STARTED / RUN_FINISHED / RUN_ERROR).\n * Unlike `onLoadingChange` (request-local), this reflects shared generation\n * activity visible to all subscribers (e.g. across tabs/devices).\n */\n onSessionGeneratingChange?: (isGenerating: boolean) => void\n\n /**\n * Policy for messages sent while the client is busy (streaming, claiming\n * a send, or draining the queue). Accepts a `WhenBusy` string, a\n * `QueueConfig`, or a `QueueStrategy` function.\n * Default: `{ whenBusy: 'queue', drain: 'fifo' }`.\n * Queued items auto-send only after a **successful** settle; they are\n * discarded on error/abort, `stop()`, `clear()`, `unsubscribe()`, and\n * `reload()`.\n */\n queue?: QueueOption\n\n /**\n * Callback when the pending send queue changes (enqueue, cancel, drain,\n * or flush).\n */\n onQueueChange?: (queue: Array<QueuedMessage>) => void\n\n /**\n * Callback when resumable run state or pending interrupts change.\n */\n onResumeStateChange?: (\n resumeState: ChatResumeState | null,\n pendingInterrupts: BoundInterrupts<TTools, TInterrupts>,\n ) => void\n\n /**\n * Callback when the id of the run this client has in flight changes: the new\n * id when a run starts (a send, or a `joinRun` rejoin), `null` when it settles.\n */\n onRunIdChange?: (runId: string | null) => void\n\n /**\n * Callback when the immutable interrupt state snapshot changes.\n * Snapshot restoration passes `{ source: 'hydrate' }`; streamed and\n * client-initiated updates pass `{ source: 'live' }`.\n */\n onInterruptStateChange?: (\n state: ChatInterruptState<TTools, TInterrupts>,\n context: { source: 'hydrate' | 'live' },\n ) => void\n\n /**\n * Callback when a custom event is received from a server-side tool.\n * Custom events are emitted by tools using `context.emitCustomEvent()` during execution.\n *\n * @param eventType - The name of the custom event\n * @param data - The event payload data\n * @param context - Additional context including the toolCallId that emitted the event\n */\n onCustomEvent?: (\n eventType: string,\n data: unknown,\n context: { toolCallId?: string },\n ) => void\n\n /**\n * Client-side tools with execution logic\n * When provided, tools with execute functions will be called automatically\n */\n tools?: TTools\n\n /** First-party generic interrupts this client can type and resolve. */\n interrupts?: TInterrupts\n\n /**\n * Devtools hook metadata for this client instance.\n */\n devtools?: Partial<AIDevtoolsClientMetadata>\n\n /**\n * Factory that constructs the devtools bridge. Default is a no-op\n * factory, which keeps `@tanstack/ai-client/devtools` (the heavy\n * bridge implementation) out of the main entry's bundle. Frameworks\n * that need live devtools should pass the real factory from\n * `@tanstack/ai-client/devtools`.\n */\n devtoolsBridgeFactory?: ChatDevtoolsBridgeFactory\n\n /**\n * Stream processing options (optional)\n * Configure chunking strategy\n */\n streamProcessor?: {\n /**\n * Strategy for when to emit text updates\n * Defaults to ImmediateStrategy (every chunk)\n */\n chunkStrategy?: ChunkStrategy\n }\n}\n\n/**\n * Options for `ChatClient`. Exactly one of `connection` or `fetcher` must be\n * provided — the type-level XOR is enforced via `ChatTransport`. Persistence\n * that is on requires a `threadId` via {@link ChatPersistenceOptions}.\n */\nexport type ChatClientOptions<\n TTools extends ReadonlyArray<AnyClientTool> = any,\n TContext = InferredClientContext<TTools>,\n TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> =\n readonly [],\n> = DistributedOmit<\n ChatClientBaseOptions<TTools, TContext, TInterrupts>,\n 'context'\n> &\n ClientContextOptionFromTools<TTools, TContext> &\n ChatTransport &\n ChatPersistenceOptions<TTools>\n\nexport interface ChatRequestBody {\n messages: Array<ModelMessage>\n data?: Record<string, any>\n}\n\n/**\n * Create a typed array of client tools with proper type inference.\n * This eliminates the need for `as const` when defining tool arrays.\n *\n * @example\n * ```ts\n * const tools = clientTools(\n * myTool1.client(() => result1),\n * myTool2.client(() => result2),\n * )\n *\n * // tools is now properly typed as a tuple with literal tool names\n * // This enables type narrowing when checking part.name === 'toolName'\n * ```\n */\nexport function clientTools<const T extends Array<AnyClientTool>>(\n ...tools: T\n): T {\n return tools\n}\n\n/**\n * Helper to create typed chat client options\n * Use this to get proper type inference for messages\n *\n * @example\n * ```ts\n * const tools = clientTools(myTool1, myTool2)\n *\n * const chatOptions = createChatClientOptions({\n * connection: fetchServerSentEvents('/api/chat'),\n * tools,\n * })\n *\n * type MyMessages = InferChatMessages<typeof chatOptions>\n * ```\n */\nexport function createChatClientOptions<\n const TTools extends ReadonlyArray<AnyClientTool>,\n TContext = InferredClientContext<TTools>,\n const TInterrupts extends ReadonlyArray<\n InterruptDefinition<any, any, any, any>\n > = readonly [],\n>(\n options: ChatClientOptions<TTools, TContext, TInterrupts>,\n): ChatClientOptions<TTools, TContext, TInterrupts> {\n return options\n}\n\n/**\n * Extract the message type from chat options\n *\n * @example\n * ```ts\n * const chatOptions = createChatClientOptions({\n * connection: fetchServerSentEvents('/api/chat'),\n * tools: [myTool1, myTool2],\n * })\n *\n * type MyMessages = InferChatMessages<typeof chatOptions>\n * // MyMessages is now Array<UIMessage<[typeof myTool1, typeof myTool2]>>\n * ```\n */\nexport type InferChatMessages<T> =\n T extends ChatClientOptions<infer TTools, any>\n ? Array<UIMessage<TTools>>\n : never\n"],"mappings":";;;;;;;;;;;;;;;;AAgkCA,SAAgB,YACd,GAAG,OACA;CACH,OAAO;AACT;;;;;;;;;;;;;;;;;AAkBA,SAAgB,wBAOd,SACkD;CAClD,OAAO;AACT"}
@@ -45,6 +45,8 @@ export declare class VideoGenerationClient<TOutput = VideoGenerateResult> {
45
45
  private threadId;
46
46
  private readonly serverDriven;
47
47
  private body;
48
+ private byok;
49
+ private byokProvider;
48
50
  private result;
49
51
  private input;
50
52
  private progress;
@@ -96,7 +98,7 @@ export declare class VideoGenerationClient<TOutput = VideoGenerateResult> {
96
98
  /**
97
99
  * Update options without recreating the client.
98
100
  */
99
- updateOptions(options: Partial<Pick<VideoGenerationClientOptions<TOutput>, 'body' | 'onResult' | 'onError' | 'onProgress' | 'onChunk' | 'onJobCreated' | 'onStatusUpdate'>>): void;
101
+ updateOptions(options: Partial<Pick<VideoGenerationClientOptions<TOutput>, 'body' | 'byok' | 'byokProvider' | 'onResult' | 'onError' | 'onProgress' | 'onChunk' | 'onJobCreated' | 'onStatusUpdate'>>): void;
100
102
  dispose(): void;
101
103
  getResult(): TOutput | null;
102
104
  getJobId(): string | null;
@@ -1,6 +1,9 @@
1
+ import { prepareResolvedByokHeaders, resolveByokProviderId } from "./byok/resolve.js";
1
2
  import { createNoOpVideoDevtoolsBridge } from "./devtools-noop.js";
2
3
  import { GENERATION_EVENTS, GENERATION_STREAM_TRUNCATED_MESSAGE, GENERATION_UNRESTORABLE_RESULT_MESSAGE, clientStateFromResumeStatus, createGenerationHydrationError, createGenerationResultSnapshot, parseGenerationResumeSnapshot, updateGenerationResumeSnapshot } from "./generation-types.js";
3
4
  import { parseSSEResponse } from "./sse-parser.js";
5
+ import { restoreInboundChunk } from "@tanstack/ai/client";
6
+ import { ByokBlockedError, ByokMissingError } from "@tanstack/ai/byok";
4
7
  //#region src/video-generation-client.ts
5
8
  /**
6
9
  * A specialized client for job-based video generation.
@@ -48,6 +51,8 @@ var VideoGenerationClient = class {
48
51
  threadId;
49
52
  serverDriven = false;
50
53
  body;
54
+ byok;
55
+ byokProvider;
51
56
  result = null;
52
57
  input = null;
53
58
  progress = null;
@@ -71,6 +76,8 @@ var VideoGenerationClient = class {
71
76
  this.hydrateGenerationHandler = options.hydrateGeneration;
72
77
  this.joinRunHandler = options.joinRun;
73
78
  this.body = options.body ?? {};
79
+ this.byok = options.byok;
80
+ this.byokProvider = options.byokProvider;
74
81
  this.serverDriven = options.persistence === true;
75
82
  this.callbacksRef = {
76
83
  onResult: options.onResult,
@@ -146,19 +153,26 @@ var VideoGenerationClient = class {
146
153
  this.abortController = abortController;
147
154
  const { signal } = abortController;
148
155
  try {
149
- if (this.fetcher) await this.generateWithFetcher(input, signal, runId);
156
+ let headers;
157
+ if (this.byok) {
158
+ const provider = resolveByokProviderId(this.byokProvider, this.body.provider);
159
+ headers = await prepareResolvedByokHeaders(this.byok, provider);
160
+ }
161
+ if (this.fetcher) await this.generateWithFetcher(input, signal, runId, headers);
150
162
  else if (this.connection) {
151
163
  const mergedData = {
152
164
  ...this.body,
153
165
  ...input
154
166
  };
155
- const stream = this.connection.connect([], mergedData, signal, this.createRunContext(runId));
167
+ const stream = this.connection.connect([], mergedData, signal, this.createRunContext(runId, headers));
156
168
  await this.processStream(stream, runId, signal);
157
169
  } else throw new Error("VideoGenerationClient requires either a connection or fetcher option");
158
170
  if (!signal.aborted && this.status === "success") this.devtoolsBridge.finishRun(this.devtoolsBridge.getActiveRunId() ?? runId, "run:completed", "completed");
159
171
  } catch (err) {
160
172
  if (signal.aborted) return;
161
173
  const error = err instanceof Error ? err : new Error(String(err));
174
+ if (error instanceof ByokMissingError) this.byok?.request(error.provider, "missing");
175
+ if (error instanceof ByokBlockedError && error.reason === "locked") this.byok?.request(error.provider, "locked");
162
176
  this.setError(error);
163
177
  this.setStatus("error");
164
178
  this.recordResumeSnapshotError(error);
@@ -174,9 +188,12 @@ var VideoGenerationClient = class {
174
188
  /**
175
189
  * Direct fetcher mode: call fetcher and set result.
176
190
  */
177
- async generateWithFetcher(input, signal, runId) {
191
+ async generateWithFetcher(input, signal, runId, headers) {
178
192
  if (!this.fetcher) return;
179
- const result = await this.fetcher(input, { signal });
193
+ const result = await this.fetcher(input, headers === void 0 ? { signal } : {
194
+ signal,
195
+ headers
196
+ });
180
197
  if (signal.aborted) return;
181
198
  if (result instanceof Response) await this.processStream(parseSSEResponse(result, signal), runId, signal);
182
199
  else {
@@ -198,8 +215,9 @@ var VideoGenerationClient = class {
198
215
  async processStream(source, fallbackRunId, signal) {
199
216
  let streamRunId;
200
217
  let sawTerminalChunk = false;
201
- for await (const chunk of source) {
218
+ for await (const raw of source) {
202
219
  if (signal.aborted) break;
220
+ const chunk = restoreInboundChunk(raw);
203
221
  this.callbacksRef.onChunk?.(chunk);
204
222
  this.observeResumeSnapshot(chunk);
205
223
  const chunkRunId = "runId" in chunk && typeof chunk.runId === "string" ? chunk.runId : void 0;
@@ -233,7 +251,7 @@ var VideoGenerationClient = class {
233
251
  break;
234
252
  case "RUN_ERROR": {
235
253
  this.devtoolsBridge.ensureRunStarted(chunkRunId ?? streamRunId ?? fallbackRunId);
236
- const msg = chunk.message || chunk.error?.message || "An error occurred";
254
+ const msg = chunk.message || "An error occurred";
237
255
  throw new Error(msg);
238
256
  }
239
257
  }
@@ -287,6 +305,8 @@ var VideoGenerationClient = class {
287
305
  */
288
306
  updateOptions(options) {
289
307
  if (options.body !== void 0) this.body = options.body ?? {};
308
+ if (options.byok !== void 0) this.byok = options.byok;
309
+ if (options.byokProvider !== void 0) this.byokProvider = options.byokProvider;
290
310
  if (options.onResult !== void 0) this.callbacksRef.onResult = options.onResult;
291
311
  if (options.onError !== void 0) this.callbacksRef.onError = options.onError;
292
312
  if (options.onProgress !== void 0) this.callbacksRef.onProgress = options.onProgress;
@@ -422,10 +442,11 @@ var VideoGenerationClient = class {
422
442
  generateUniqueId(prefix) {
423
443
  return `${prefix}-${Date.now()}-${Math.random().toString(36).substring(7)}`;
424
444
  }
425
- createRunContext(runId) {
445
+ createRunContext(runId, headers) {
426
446
  return {
427
447
  threadId: this.threadId,
428
- runId
448
+ runId,
449
+ ...headers ? { headers } : {}
429
450
  };
430
451
  }
431
452
  observeResumeSnapshot(chunk) {
@@ -1 +1 @@
1
- {"version":3,"file":"video-generation-client.js","names":[],"sources":["../../src/video-generation-client.ts"],"sourcesContent":["import {\n GENERATION_EVENTS,\n GENERATION_STREAM_TRUNCATED_MESSAGE,\n GENERATION_UNRESTORABLE_RESULT_MESSAGE,\n clientStateFromResumeStatus,\n createGenerationHydrationError,\n createGenerationResultSnapshot,\n parseGenerationResumeSnapshot,\n updateGenerationResumeSnapshot,\n} from './generation-types'\nimport { createNoOpVideoDevtoolsBridge } from './devtools-noop'\nimport { parseSSEResponse } from './sse-parser'\nimport type { StreamChunk } from '@tanstack/ai/client'\nimport type {\n ConnectConnectionAdapter,\n GenerationHydrationResult,\n RunAgentInputContext,\n} from './connection-adapters'\nimport type {\n AIDevtoolsClientMetadata,\n AIDevtoolsGenerationProgress,\n VideoDevtoolsBridge,\n VideoDevtoolsBridgeOptions,\n} from './devtools'\nimport type {\n GenerationClientState,\n GenerationFetcher,\n GenerationPersistenceOptions,\n GenerationResumeSnapshot,\n GenerationResumeState,\n GenerationTransport,\n VideoGenerateInput,\n VideoGenerateResult,\n VideoGenerationClientOptions,\n VideoStatusInfo,\n} from './generation-types'\n\n/**\n * Callbacks stored in a ref so hooks can update them without recreating the client.\n */\n// All optional fields explicitly allow `| undefined` so callers can spread\n// option bags (where each callback may be `undefined`) into the callbacks\n// ref under `exactOptionalPropertyTypes`.\ninterface VideoCallbacks<TOutput> {\n onResult?:\n | ((result: VideoGenerateResult) => TOutput | null | void)\n | undefined\n onError?: ((error: Error) => void) | undefined\n onProgress?: ((progress: number, message?: string) => void) | undefined\n onChunk?: ((chunk: StreamChunk) => void) | undefined\n onJobCreated?: ((jobId: string) => void) | undefined\n onStatusUpdate?: ((status: VideoStatusInfo) => void) | undefined\n onResultChange?: ((result: TOutput | null) => void) | undefined\n onLoadingChange?: ((isLoading: boolean) => void) | undefined\n onErrorChange?: ((error: Error | undefined) => void) | undefined\n onStatusChange?: ((status: GenerationClientState) => void) | undefined\n onJobIdChange?: ((jobId: string | null) => void) | undefined\n onVideoStatusChange?: ((status: VideoStatusInfo | null) => void) | undefined\n onResumeSnapshotChange?:\n | ((snapshot: GenerationResumeSnapshot | undefined) => void)\n | undefined\n onResumeStateChange?:\n | ((resumeState: GenerationResumeState | null) => void)\n | undefined\n}\n\n/**\n * A specialized client for job-based video generation.\n *\n * Video generation is asynchronous: a job is created, then polled for status\n * until completion. This client handles the full lifecycle.\n *\n * Supports two transport modes:\n * - **ConnectConnectionAdapter** — Server handles the polling loop internally and\n * streams status updates via CUSTOM events.\n * - **Fetcher** — Direct async function that returns a completed\n * `VideoGenerateResult`.\n *\n * @example\n * ```typescript\n * // With streaming connection adapter (server-driven polling)\n * const client = new VideoGenerationClient({\n * connection: fetchServerSentEvents('/api/generate/video'),\n * onResultChange: setResult,\n * onVideoStatusChange: setVideoStatus,\n * })\n *\n * // With fetcher (direct result)\n * const client = new VideoGenerationClient({\n * fetcher: async (input) => {\n * const res = await fetch('/api/video/generate', {\n * method: 'POST',\n * body: JSON.stringify(input),\n * })\n * return res.json() // { jobId, status: 'completed', url, expiresAt }\n * },\n * })\n *\n * await client.generate({ prompt: 'A flying car over a city' })\n * ```\n */\nexport class VideoGenerationClient<TOutput = VideoGenerateResult> {\n private readonly connection: ConnectConnectionAdapter | undefined\n // Persistence handlers supplied as options (e.g. alongside a `fetcher`), used\n // when the connection doesn't carry its own — the connection's handlers take\n // precedence when both exist.\n private readonly hydrateGenerationHandler:\n | ConnectConnectionAdapter['hydrateGeneration']\n | undefined\n private readonly joinRunHandler:\n | ConnectConnectionAdapter['joinRun']\n | undefined\n private readonly fetcher:\n | GenerationFetcher<VideoGenerateInput, VideoGenerateResult>\n | undefined\n private uniqueId: string\n private readonly devtoolsMetadata: AIDevtoolsClientMetadata\n private readonly devtoolsBridge: VideoDevtoolsBridge<TOutput>\n private threadId: string\n // Server-driven mode (`persistence: true`): no local snapshot store; on mount\n // the client hydrates the last generation for `threadId` from the server.\n private readonly serverDriven: boolean = false\n private body: Record<string, any>\n\n private result: TOutput | null = null\n private input: VideoGenerateInput | null = null\n private progress: AIDevtoolsGenerationProgress | null = null\n private jobId: string | null = null\n private videoStatus: VideoStatusInfo | null = null\n private isLoading = false\n private error: Error | undefined = undefined\n private status: GenerationClientState = 'idle'\n private resumeSnapshot: GenerationResumeSnapshot | undefined\n private abortController: AbortController | null = null\n private rejoinedRunId: string | undefined\n private readonly callbacksRef: VideoCallbacks<TOutput>\n private devtoolsMounted = false\n private disposed = false\n private serverHydrationStarted = false\n\n constructor(\n options: Omit<\n VideoGenerationClientOptions<TOutput>,\n 'persistence' | 'threadId'\n > &\n GenerationPersistenceOptions &\n GenerationTransport<VideoGenerateInput, VideoGenerateResult>,\n ) {\n // `threadId` is the only identity. Do not mint a random id during\n // construct: hooks build this client during render.\n this.threadId = options.threadId ?? ''\n this.uniqueId = this.threadId\n this.connection = options.connection\n this.fetcher = options.fetcher\n this.hydrateGenerationHandler = options.hydrateGeneration\n this.joinRunHandler = options.joinRun\n this.body = options.body ?? {}\n // `persistence` is `false`/omitted (ephemeral) or `true` (server-driven:\n // hydrate the last generation for `threadId` from the server on mount).\n this.serverDriven = options.persistence === true\n this.callbacksRef = {\n onResult: options.onResult,\n onError: options.onError,\n onProgress: options.onProgress,\n onChunk: options.onChunk,\n onJobCreated: options.onJobCreated,\n onStatusUpdate: options.onStatusUpdate,\n onResultChange: options.onResultChange,\n onLoadingChange: options.onLoadingChange,\n onErrorChange: options.onErrorChange,\n onStatusChange: options.onStatusChange,\n onJobIdChange: options.onJobIdChange,\n onVideoStatusChange: options.onVideoStatusChange,\n onResumeSnapshotChange: options.onResumeSnapshotChange,\n onResumeStateChange: options.onResumeStateChange,\n }\n\n this.devtoolsMetadata = this.createDevtoolsMetadata(options.devtools)\n this.devtoolsBridge = (\n options.devtoolsBridgeFactory ?? createNoOpVideoDevtoolsBridge\n )<TOutput>(this.buildDevtoolsBridgeOptions())\n\n // Mount hydration (`maybeHydrateFromServer`) is deliberately NOT run here. The framework\n // hooks build this client inside `useMemo`, so the constructor executes in\n // React's render phase; hydrating here would re-fire the hydrate GET on\n // every discarded/speculative render, flooding the connection pool when\n // several clients mount together. It is kicked off once from\n // `mountDevtools`, which the hooks call from a commit-phase mount effect.\n }\n\n private buildDevtoolsBridgeOptions(): VideoDevtoolsBridgeOptions<TOutput> {\n const client = this\n return {\n get hookId() {\n return client.uniqueId\n },\n get clientId() {\n return client.uniqueId\n },\n get threadId() {\n return client.threadId\n },\n metadata: this.devtoolsMetadata,\n getCoreState: () => ({\n input: this.input,\n result: this.result,\n progress: this.progress,\n status: this.status,\n isLoading: this.isLoading,\n jobId: this.jobId,\n videoStatus: this.videoStatus,\n ...(this.error ? { error: this.error.message } : {}),\n }),\n }\n }\n\n mountDevtools(): void {\n this.ensureThreadId()\n // Mounting revives a disposed client. Framework hooks call this from\n // their mount effect, so a dispose → remount cycle (e.g. React\n // StrictMode's mount → cleanup → mount replay against the same memoized\n // client) leaves the client usable again.\n this.disposed = false\n this.maybeHydrateFromServer()\n // Re-attach to an already-loaded `running` snapshot (remount case); see the\n // note in GenerationClient.mountDevtools. Guarded by rejoinInFlight.\n this.maybeResumeInFlight()\n if (this.devtoolsMounted) {\n return\n }\n\n this.devtoolsMounted = true\n this.devtoolsBridge.emitRegistered()\n this.devtoolsBridge.emitSnapshot()\n }\n\n /**\n * Trigger video generation.\n * Only one generation can be in-flight at a time.\n */\n async generate(input: VideoGenerateInput): Promise<void> {\n if (this.disposed) return\n if (this.isLoading) return\n this.mountDevtools()\n\n this.input = input\n this.progress = null\n const runId = this.devtoolsBridge.beginRun(input)\n this.setIsLoading(true)\n this.setStatus('generating')\n this.setError(undefined)\n this.setJobId(null)\n this.setVideoStatus(null)\n\n const abortController = new AbortController()\n this.abortController = abortController\n const { signal } = abortController\n\n try {\n if (this.fetcher) {\n await this.generateWithFetcher(input, signal, runId)\n } else if (this.connection) {\n const mergedData = { ...this.body, ...input }\n const stream = this.connection.connect(\n [],\n mergedData,\n signal,\n this.createRunContext(runId),\n )\n await this.processStream(stream, runId, signal)\n } else {\n throw new Error(\n 'VideoGenerationClient requires either a connection or fetcher option',\n )\n }\n if (!signal.aborted && this.status === 'success') {\n this.devtoolsBridge.finishRun(\n this.devtoolsBridge.getActiveRunId() ?? runId,\n 'run:completed',\n 'completed',\n )\n }\n } catch (err: unknown) {\n if (signal.aborted) return\n const error = err instanceof Error ? err : new Error(String(err))\n this.setError(error)\n this.setStatus('error')\n this.recordResumeSnapshotError(error)\n this.devtoolsBridge.finishRun(\n this.devtoolsBridge.getActiveRunId() ?? runId,\n 'run:errored',\n 'errored',\n error.message,\n )\n this.callbacksRef.onError?.(error)\n } finally {\n if (this.abortController === abortController) {\n this.abortController = null\n this.setIsLoading(false)\n }\n }\n }\n\n /**\n * Direct fetcher mode: call fetcher and set result.\n */\n private async generateWithFetcher(\n input: VideoGenerateInput,\n signal: AbortSignal,\n runId: string,\n ): Promise<void> {\n if (!this.fetcher) return\n\n // Fetcher returns a completed result directly, or a Response with SSE body\n const result = await this.fetcher(input, { signal })\n if (signal.aborted) return\n\n if (result instanceof Response) {\n // Server function returned SSE Response — parse stream\n await this.processStream(parseSSEResponse(result, signal), runId, signal)\n } else {\n this.devtoolsBridge.ensureRunStarted(runId)\n this.setResult(result)\n this.setStatus('success')\n this.completePlainFetcherResumeSnapshot(result)\n }\n }\n\n /**\n * Process a stream of AG-UI events from the streaming connection adapter.\n * The server handles the polling loop and streams status updates.\n *\n * Throws {@link GENERATION_STREAM_TRUNCATED_MESSAGE} when the iteration ends\n * without a terminal chunk — see the note on\n * `GenerationClient.processStream`. Video runs are long enough that a proxy\n * idle timeout mid-poll is the likeliest way to hit it.\n */\n private async processStream(\n source: AsyncIterable<StreamChunk>,\n fallbackRunId: string,\n signal: AbortSignal,\n ): Promise<void> {\n let streamRunId: string | undefined\n let sawTerminalChunk = false\n\n for await (const chunk of source) {\n if (signal.aborted) break\n\n this.callbacksRef.onChunk?.(chunk)\n this.observeResumeSnapshot(chunk)\n const chunkRunId =\n 'runId' in chunk && typeof chunk.runId === 'string'\n ? chunk.runId\n : undefined\n\n // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check -- AG-UI EventType has ~22 variants; this consumer only handles the subset relevant to video generation lifecycle.\n switch (chunk.type) {\n case 'RUN_STARTED': {\n streamRunId = chunk.runId\n this.devtoolsBridge.ensureRunStarted(chunk.runId)\n break\n }\n case 'CUSTOM': {\n this.devtoolsBridge.ensureRunStarted(streamRunId ?? fallbackRunId)\n if (chunk.name === GENERATION_EVENTS.VIDEO_JOB_CREATED) {\n const { jobId } = chunk.value as { jobId: string }\n this.setJobId(jobId)\n this.callbacksRef.onJobCreated?.(jobId)\n } else if (chunk.name === GENERATION_EVENTS.VIDEO_STATUS) {\n const statusInfo = chunk.value as VideoStatusInfo\n this.setVideoStatus(statusInfo)\n this.callbacksRef.onStatusUpdate?.(statusInfo)\n if (statusInfo.progress !== undefined) {\n this.setProgress(statusInfo.progress)\n }\n } else if (chunk.name === GENERATION_EVENTS.RESULT) {\n this.setResult(chunk.value as VideoGenerateResult)\n } else if (chunk.name === GENERATION_EVENTS.PROGRESS) {\n const { progress, message } = chunk.value as {\n progress: number\n message?: string\n }\n this.setProgress(progress, message)\n }\n break\n }\n case 'RUN_FINISHED': {\n streamRunId = chunk.runId\n sawTerminalChunk = true\n this.devtoolsBridge.ensureRunStarted(chunk.runId)\n this.setStatus('success')\n break\n }\n case 'RUN_ERROR': {\n this.devtoolsBridge.ensureRunStarted(\n chunkRunId ?? streamRunId ?? fallbackRunId,\n )\n // Prefer spec `message`; fall back to deprecated `error.message`\n const msg =\n (chunk.message as string | undefined) ||\n chunk.error?.message ||\n 'An error occurred'\n throw new Error(msg)\n }\n default:\n break\n }\n }\n\n // An aborted read is a deliberate stop/dispose, not a truncation.\n if (!sawTerminalChunk && !signal.aborted) {\n throw new Error(GENERATION_STREAM_TRUNCATED_MESSAGE)\n }\n }\n\n /**\n * Abort any in-flight generation or polling.\n */\n stop(): void {\n const runId = this.devtoolsBridge.getActiveRunId()\n if (this.abortController) {\n this.abortController.abort()\n this.abortController = null\n }\n this.setIsLoading(false)\n if (this.status === 'generating') {\n this.setStatus('idle')\n if (runId) {\n this.devtoolsBridge.finishRun(runId, 'run:cancelled', 'cancelled')\n }\n }\n // A stopped run is no longer resumable. Without this the in-memory\n // snapshot stays `running`, and a remount's `maybeResumeInFlight` would\n // rejoin a run the user just cancelled.\n if (this.resumeSnapshot && this.resumeSnapshot.status === 'running') {\n this.resumeSnapshot = {\n ...this.resumeSnapshot,\n resumeState: null,\n status: 'idle',\n }\n this.notifyResumeSnapshotChanged()\n }\n }\n\n /**\n * Clear all state and return to idle. Also drops the client's in-memory\n * resume snapshot, so a remount restores nothing. The server-side record is\n * untouched — this client no longer writes one — so a full page reload under\n * `persistence: true` re-hydrates the last generation again.\n */\n reset(): void {\n this.stop()\n this.setResult(null)\n this.input = null\n this.progress = null\n this.devtoolsBridge.resetRuns()\n this.setJobId(null)\n this.setVideoStatus(null)\n this.setError(undefined)\n this.setStatus('idle')\n this.clearResumeSnapshot()\n this.devtoolsBridge.emitState()\n }\n\n /**\n * Update options without recreating the client.\n */\n updateOptions(\n options: Partial<\n Pick<\n VideoGenerationClientOptions<TOutput>,\n | 'body'\n | 'onResult'\n | 'onError'\n | 'onProgress'\n | 'onChunk'\n | 'onJobCreated'\n | 'onStatusUpdate'\n >\n >,\n ): void {\n if (options.body !== undefined) {\n this.body = options.body ?? {}\n }\n if (options.onResult !== undefined) {\n this.callbacksRef.onResult = options.onResult\n }\n if (options.onError !== undefined) {\n this.callbacksRef.onError = options.onError\n }\n if (options.onProgress !== undefined) {\n this.callbacksRef.onProgress = options.onProgress\n }\n if (options.onChunk !== undefined) {\n this.callbacksRef.onChunk = options.onChunk\n }\n if (options.onJobCreated !== undefined) {\n this.callbacksRef.onJobCreated = options.onJobCreated\n }\n if (options.onStatusUpdate !== undefined) {\n this.callbacksRef.onStatusUpdate = options.onStatusUpdate\n }\n }\n\n dispose(): void {\n this.disposed = true\n // Teardown, NOT a user cancel (see GenerationClient.dispose): abort in-flight\n // delivery but keep the `running` snapshot resumable so a remount rejoins.\n if (this.abortController) {\n this.abortController.abort()\n this.abortController = null\n }\n this.setIsLoading(false)\n this.devtoolsBridge.dispose()\n this.devtoolsMounted = false\n this.serverHydrationStarted = false\n this.rejoinedRunId = undefined\n }\n\n // ===========================\n // Getters\n // ===========================\n\n getResult(): TOutput | null {\n return this.result\n }\n\n getJobId(): string | null {\n return this.jobId\n }\n\n getVideoStatus(): VideoStatusInfo | null {\n return this.videoStatus\n }\n\n getIsLoading(): boolean {\n return this.isLoading\n }\n\n getError(): Error | undefined {\n return this.error\n }\n\n getStatus(): GenerationClientState {\n return this.status\n }\n\n getResumeSnapshot(): GenerationResumeSnapshot | undefined {\n return this.resumeSnapshot\n ? {\n ...this.resumeSnapshot,\n ...(this.resumeSnapshot.pendingArtifacts\n ? { pendingArtifacts: [...this.resumeSnapshot.pendingArtifacts] }\n : {}),\n ...(this.resumeSnapshot.result\n ? {\n result: {\n ...this.resumeSnapshot.result,\n ...(this.resumeSnapshot.result.artifacts\n ? { artifacts: [...this.resumeSnapshot.result.artifacts] }\n : {}),\n },\n }\n : {}),\n ...(this.resumeSnapshot.error\n ? { error: { ...this.resumeSnapshot.error } }\n : {}),\n ...(this.resumeSnapshot.lastEvent\n ? { lastEvent: { ...this.resumeSnapshot.lastEvent } }\n : {}),\n }\n : undefined\n }\n\n // ===========================\n // Private state setters\n // ===========================\n\n private setResult(rawResult: VideoGenerateResult | null): void {\n if (rawResult === null) {\n this.result = null\n this.callbacksRef.onResultChange?.(null)\n this.devtoolsBridge.recordResultChange()\n return\n }\n\n const completedStatus = this.createCompletedVideoStatus(rawResult)\n if (this.progress?.value !== 100) {\n this.setProgress(100, this.progress?.message)\n }\n this.setJobId(rawResult.jobId)\n this.setVideoStatus(completedStatus)\n\n if (this.callbacksRef.onResult) {\n const transformed = this.callbacksRef.onResult(rawResult)\n if (transformed === null) {\n // null return → keep previous result unchanged, just re-emit\n this.devtoolsBridge.emitState()\n return\n }\n if (transformed !== undefined) {\n // Non-null, non-undefined → use transformed value\n this.result = transformed\n this.callbacksRef.onResultChange?.(this.result)\n this.devtoolsBridge.recordResultChange()\n return\n }\n }\n\n // No onResult callback, or callback returned void → use raw value as\n // TOutput. When the caller did not supply an onResult transform,\n // `TOutput` defaults to `VideoGenerateResult`, so the runtime cast is\n // sound.\n // oxlint-disable-next-line eslint-js/no-restricted-syntax -- TOutput defaults to VideoGenerateResult when no onResult transform is supplied\n this.result = rawResult as unknown as TOutput\n this.callbacksRef.onResultChange?.(this.result)\n this.devtoolsBridge.recordResultChange()\n }\n\n private setJobId(jobId: string | null): void {\n this.jobId = jobId\n this.callbacksRef.onJobIdChange?.(jobId)\n this.devtoolsBridge.recordJobIdChange()\n }\n\n private setVideoStatus(status: VideoStatusInfo | null): void {\n this.videoStatus = status\n this.callbacksRef.onVideoStatusChange?.(status)\n this.devtoolsBridge.recordVideoStatusChange()\n }\n\n private setIsLoading(isLoading: boolean): void {\n this.isLoading = isLoading\n this.callbacksRef.onLoadingChange?.(isLoading)\n this.devtoolsBridge.recordLoadingChange()\n }\n\n private setError(error: Error | undefined): void {\n this.error = error\n this.callbacksRef.onErrorChange?.(error)\n this.devtoolsBridge.recordErrorChange(error)\n }\n\n private setStatus(status: GenerationClientState): void {\n this.status = status\n this.callbacksRef.onStatusChange?.(status)\n this.devtoolsBridge.recordStatusChange(status)\n }\n\n private setProgress(value: number, message?: string): void {\n this.progress = {\n value,\n ...(message ? { message } : {}),\n }\n if (message === undefined) {\n this.callbacksRef.onProgress?.(value)\n } else {\n this.callbacksRef.onProgress?.(value, message)\n }\n this.devtoolsBridge.recordProgressChange()\n }\n\n private createCompletedVideoStatus(\n result: VideoGenerateResult,\n ): VideoStatusInfo {\n return {\n jobId: result.jobId,\n status: result.status,\n progress: 100,\n url: result.url,\n }\n }\n\n private createDevtoolsMetadata(\n metadata?: Partial<AIDevtoolsClientMetadata>,\n ): AIDevtoolsClientMetadata {\n return {\n hookName: metadata?.hookName ?? 'useGenerateVideo',\n outputKind: metadata?.outputKind ?? 'video',\n ...(metadata?.framework ? { framework: metadata.framework } : {}),\n ...(metadata?.name ? { name: metadata.name } : {}),\n }\n }\n\n private ensureThreadId(): string {\n if (!this.threadId) {\n this.threadId = this.generateUniqueId('video')\n }\n this.uniqueId = this.threadId\n return this.threadId\n }\n\n private generateUniqueId(prefix: string): string {\n return `${prefix}-${Date.now()}-${Math.random().toString(36).substring(7)}`\n }\n\n private createRunContext(runId: string): RunAgentInputContext {\n return {\n threadId: this.threadId,\n runId,\n }\n }\n\n private observeResumeSnapshot(chunk: StreamChunk): void {\n this.resumeSnapshot = updateGenerationResumeSnapshot(\n this.resumeSnapshot,\n chunk,\n )\n this.notifyResumeSnapshotChanged()\n }\n\n /** Notify the internal snapshot listener AND emit the public resume state. */\n private notifyResumeSnapshotChanged(): void {\n this.callbacksRef.onResumeSnapshotChange?.(this.resumeSnapshot)\n this.emitResumeState()\n }\n\n /** Derive the public `resumeState` from the internal snapshot. */\n private emitResumeState(): void {\n const snapshot = this.resumeSnapshot\n const state = snapshot?.resumeState\n const resumeState: GenerationResumeState | null = state\n ? {\n ...state,\n ...(snapshot?.pendingArtifacts && snapshot.pendingArtifacts.length > 0\n ? { pendingArtifacts: [...snapshot.pendingArtifacts] }\n : {}),\n }\n : null\n this.callbacksRef.onResumeStateChange?.(resumeState)\n }\n\n /**\n * Repaint the normal fields from a restored snapshot so a reload presents the\n * video in `result` / `status` / `error` / `jobId`, never a snapshot object.\n * `isLoading` stays false (no auto-tail). Not re-persisted (it came from\n * storage / the server).\n *\n * A `complete` snapshot with no durable video artifact cannot be rebuilt, so\n * it repaints as an error rather than a `success` with a `null` result — see\n * the note on `GenerationClient.repaintFromSnapshot`.\n */\n private repaintFromSnapshot(snapshot: GenerationResumeSnapshot): void {\n this.resumeSnapshot = snapshot\n this.notifyResumeSnapshotChanged()\n this.setStatus(clientStateFromResumeStatus(snapshot.status))\n this.setError(\n snapshot.error\n ? Object.assign(\n new Error(snapshot.error.message),\n snapshot.error.code ? { code: snapshot.error.code } : {},\n )\n : undefined,\n )\n if (snapshot.result?.providerJobId)\n this.setJobId(snapshot.result.providerJobId)\n const restored = this.reconstructVideoResult(snapshot)\n if (restored !== null) {\n this.setResult(restored)\n } else if (snapshot.status === 'complete') {\n this.reportUnrestorableResult()\n }\n }\n\n /**\n * Report a `complete` snapshot with no durable video artifact to rebuild\n * from. Runs after the status/error repaint above, so it wins over the\n * snapshot's own `complete` status.\n */\n private reportUnrestorableResult(): void {\n const error = new Error(GENERATION_UNRESTORABLE_RESULT_MESSAGE)\n this.setStatus('error')\n this.setError(error)\n this.callbacksRef.onError?.(error)\n }\n\n /**\n * Repaint a restored snapshot (client store or server hydrate) and, when it\n * reports a run still in flight, tail that run to completion via `joinRun`\n * (from the connection, or the `joinRun` option when the transport can't\n * carry one).\n *\n * A `running` snapshot that no `joinRun` handler can tail is repainted as an\n * interrupted error instead of a `generating` status that would never\n * settle: an interrupted generation cannot be resumed, only re-run.\n */\n private repaintRestoredSnapshot(\n snapshot: GenerationResumeSnapshot,\n activeRunId?: string,\n ): void {\n if (snapshot.status !== 'running') {\n this.repaintFromSnapshot(snapshot)\n return\n }\n const joinRun = this.connection?.joinRun ?? this.joinRunHandler\n const runId = activeRunId ?? snapshot.resumeState?.runId\n if (runId && joinRun) {\n this.repaintFromSnapshot(snapshot)\n this.rejoinInFlight(runId)\n return\n }\n this.repaintFromSnapshot({\n ...snapshot,\n resumeState: null,\n status: 'error',\n error: {\n message:\n 'The previous generation was interrupted before it finished and cannot be resumed — generate again to retry.',\n },\n })\n }\n\n /**\n * Rebuild a `VideoGenerateResult` from a restored snapshot: the video's bytes\n * are served from the durable artifact URL, so the restored result renders\n * from your own origin. Returns `null` when there is no durable video artifact.\n */\n private reconstructVideoResult(\n snapshot: GenerationResumeSnapshot,\n ): VideoGenerateResult | null {\n const result = snapshot.result\n const artifacts = result?.artifacts ?? []\n const output = artifacts.find(\n (a) =>\n a.role === 'output' && a.source.mediaType === 'video' && a.url != null,\n )\n if (!output?.url) return null\n return {\n jobId: result?.providerJobId ?? '',\n status: 'completed',\n url: output.url,\n ...(result?.expiresAt ? { expiresAt: new Date(result.expiresAt) } : {}),\n artifacts,\n }\n }\n\n /**\n * The plain (non-Response) fetcher path never observes stream chunks, so\n * the terminal snapshot is built here from the fetcher's own result. A\n * stale `error` from a previous run is intentionally dropped — this run\n * succeeded.\n */\n private completePlainFetcherResumeSnapshot(rawResult: unknown): void {\n const previous = this.resumeSnapshot\n const result = createGenerationResultSnapshot(rawResult)\n this.resumeSnapshot = {\n schemaVersion: 1,\n resumeState: null,\n status: 'complete',\n ...(previous?.activity ? { activity: previous.activity } : {}),\n ...(previous?.pendingArtifacts && previous.pendingArtifacts.length > 0\n ? { pendingArtifacts: [...previous.pendingArtifacts] }\n : {}),\n ...(result\n ? { result }\n : previous?.result\n ? { result: { ...previous.result } }\n : {}),\n }\n this.notifyResumeSnapshotChanged()\n }\n\n /**\n * Records a transport-level failure (network drop, throwing callback) in\n * the snapshot. Without this, only a server-emitted RUN_ERROR chunk would\n * mark the snapshot `error`, leaving a persisted record that claims the\n * run is still in flight.\n */\n private recordResumeSnapshotError(error: Error): void {\n // Surface the failure on the observable fields FIRST, unconditionally (see\n // the note in GenerationClient.recordResumeSnapshotError): a RUN_ERROR\n // already flipped the snapshot to `error`, so the early-return would else\n // skip this and leave `status` stuck on `generating`. The guard avoids a\n // duplicate `error` emission on the live `generate()` path.\n if (this.status !== 'error') this.setStatus('error')\n this.setError(error)\n if (this.resumeSnapshot?.status === 'error') return\n if (!this.resumeSnapshot && !this.serverDriven) return\n const previous = this.resumeSnapshot\n this.resumeSnapshot = {\n schemaVersion: 1,\n resumeState: null,\n status: 'error',\n ...(previous?.activity ? { activity: previous.activity } : {}),\n ...(previous?.pendingArtifacts && previous.pendingArtifacts.length > 0\n ? { pendingArtifacts: [...previous.pendingArtifacts] }\n : {}),\n ...(previous?.result ? { result: { ...previous.result } } : {}),\n error: { message: error.message },\n }\n this.notifyResumeSnapshotChanged()\n }\n\n /**\n * Drop the client's in-memory snapshot and re-emit. Purely local — this\n * client writes no storage, so nothing persisted is removed.\n */\n private clearResumeSnapshot(): void {\n this.resumeSnapshot = undefined\n this.notifyResumeSnapshotChanged()\n }\n\n /**\n * Server-driven mount hydration entry point (`persistence: true`). Runs at\n * most once, from the commit-phase mount path (`mountDevtools`) — never the\n * constructor / render phase — so remounts and speculative renders can't\n * re-fire the hydrate GET.\n */\n private maybeHydrateFromServer(): void {\n if (!this.serverDriven || this.serverHydrationStarted) return\n this.serverHydrationStarted = true\n if (this.connection?.hydrateGeneration ?? this.hydrateGenerationHandler) {\n this.hydrateFromServer()\n } else {\n // `persistence: true` without any hydrate source can never restore\n // anything — warn rather than silently no-op.\n console.warn(\n '[TanStack AI] `persistence: true` (server-driven) needs a `hydrateGeneration` handler — either a connection that implements one (e.g. `fetchServerSentEvents` / `fetchHttpStream`, or `stream()` / `rpcStream()` with persistence handlers) or the `hydrateGeneration` option. Without one, nothing is persisted or restored.',\n )\n }\n }\n\n /**\n * Server-driven mount hydration (`persistence: true`). The client holds no\n * local snapshot; on mount it asks the server — keyed by the stable threadId —\n * for the last generation's resume snapshot, validates it, and repaints it. It\n * never auto-starts a run, and never blocks: a `generate()` that starts first\n * owns the client and hydration backs off, mirroring the chat client.\n *\n * A genuine **miss** (no record for the thread) is silent; a genuine\n * **failure** (transport error, authorize rejection, malformed body, a record\n * the validator rejects) surfaces through `status` / `error` / `onError` — see\n * the note on `GenerationClient.hydrateFromServer`.\n */\n private hydrateFromServer(): void {\n const hydrate =\n this.connection?.hydrateGeneration ?? this.hydrateGenerationHandler\n if (!hydrate) return\n // A send that already started owns the client; don't stomp it.\n if (this.resumeSnapshot || this.isLoading || this.status !== 'idle') return\n void (async () => {\n let res: GenerationHydrationResult\n try {\n res = await hydrate(this.threadId)\n } catch (cause) {\n this.failHydration(\n createGenerationHydrationError(\n 'the request to the server did not succeed',\n cause,\n ),\n )\n return\n }\n // No record for this thread — a fresh thread, not a failure.\n if (!res.resumeSnapshot) return\n const snapshot = parseGenerationResumeSnapshot(res.resumeSnapshot)\n if (!snapshot) {\n this.failHydration(\n createGenerationHydrationError(\n 'the server returned a record this client cannot read (unknown schema version, or a missing/invalid `status` or `resumeState`)',\n ),\n )\n return\n }\n // Re-check: a send may have started while the fetch was in flight.\n if (this.resumeSnapshot || this.isLoading || this.status !== 'idle')\n return\n // A run still generating on the server: re-attach and finish it in place.\n this.repaintRestoredSnapshot(snapshot, res.activeRun?.runId)\n })()\n }\n\n /**\n * Surface a hydration failure on the observable fields. Skipped when a\n * `generate()` took ownership while the hydrate GET was in flight.\n */\n private failHydration(error: Error): void {\n if (this.resumeSnapshot || this.isLoading || this.status !== 'idle') return\n this.setStatus('error')\n this.setError(error)\n this.callbacksRef.onError?.(error)\n }\n\n /**\n * Re-attach to an already-loaded `running` snapshot (remount case); see the\n * note in GenerationClient.maybeResumeInFlight. Guarded by `rejoinInFlight`.\n */\n private maybeResumeInFlight(): void {\n if (this.resumeSnapshot?.status !== 'running') return\n const runId = this.resumeSnapshot.resumeState?.runId\n if (runId) this.rejoinInFlight(runId)\n }\n\n /**\n * Re-attach to a video run still generating and stream it to completion,\n * mirroring the chat client's mount-time rejoin. Reuses `processStream`, so\n * the job status and result repaint from the replayed chunks. A live\n * `generate()` owns the client and is never stomped; a run is rejoined once.\n */\n private rejoinInFlight(runId: string): void {\n const joinRun = this.connection?.joinRun ?? this.joinRunHandler\n if (!joinRun) return\n if (this.rejoinedRunId === runId) return\n if (this.isLoading || this.abortController) return\n this.rejoinedRunId = runId\n const controller = new AbortController()\n this.abortController = controller\n this.setIsLoading(true)\n this.setStatus('generating')\n void (async () => {\n try {\n await this.processStream(\n joinRun(runId, controller.signal),\n runId,\n controller.signal,\n )\n } catch (error) {\n if (!controller.signal.aborted) {\n const failure =\n error instanceof Error ? error : new Error(String(error))\n // Settles `status`/`error` AND rewrites the snapshot to a terminal\n // `error` with a null `resumeState`, so the next mount does not\n // rejoin this run again.\n this.recordResumeSnapshotError(failure)\n this.callbacksRef.onError?.(failure)\n }\n } finally {\n // Only reset if this rejoin still owns the client: a `stop()` +\n // fresh `generate()` may have replaced the controller while the tail\n // was settling, and that live run owns `isLoading` now.\n if (this.abortController === controller) {\n this.abortController = null\n this.setIsLoading(false)\n }\n }\n })()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqGA,IAAa,wBAAb,MAAkE;CAChE;CAIA;CAGA;CAGA;CAGA;CACA;CACA;CACA;CAGA,eAAyC;CACzC;CAEA,SAAiC;CACjC,QAA2C;CAC3C,WAAwD;CACxD,QAA+B;CAC/B,cAA8C;CAC9C,YAAoB;CACpB,QAAmC,KAAA;CACnC,SAAwC;CACxC;CACA,kBAAkD;CAClD;CACA;CACA,kBAA0B;CAC1B,WAAmB;CACnB,yBAAiC;CAEjC,YACE,SAMA;EAGA,KAAK,WAAW,QAAQ,YAAY;EACpC,KAAK,WAAW,KAAK;EACrB,KAAK,aAAa,QAAQ;EAC1B,KAAK,UAAU,QAAQ;EAC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;EAClC,IAAI,KAAK,aAAa,KAAK,iBAAiB;EAC5C,KAAK,gBAAgB;EACrB,MAAM,aAAa,IAAI,gBAAgB;EACvC,KAAK,kBAAkB;EACvB,KAAK,aAAa,IAAI;EACtB,KAAK,UAAU,YAAY;EAC3B,CAAM,YAAY;GAChB,IAAI;IACF,MAAM,KAAK,cACT,QAAQ,OAAO,WAAW,MAAM,GAChC,OACA,WAAW,MACb;GACF,SAAS,OAAO;IACd,IAAI,CAAC,WAAW,OAAO,SAAS;KAC9B,MAAM,UACJ,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;KAI1D,KAAK,0BAA0B,OAAO;KACtC,KAAK,aAAa,UAAU,OAAO;IACrC;GACF,UAAU;IAIR,IAAI,KAAK,oBAAoB,YAAY;KACvC,KAAK,kBAAkB;KACvB,KAAK,aAAa,KAAK;IACzB;GACF;EACF,EAAA,CAAG;CACL;AACF"}
1
+ {"version":3,"file":"video-generation-client.js","names":[],"sources":["../../src/video-generation-client.ts"],"sourcesContent":["import { ByokBlockedError, ByokMissingError } from '@tanstack/ai/byok'\nimport {\n prepareResolvedByokHeaders,\n resolveByokProviderId,\n} from './byok/resolve'\nimport {\n GENERATION_EVENTS,\n GENERATION_STREAM_TRUNCATED_MESSAGE,\n GENERATION_UNRESTORABLE_RESULT_MESSAGE,\n clientStateFromResumeStatus,\n createGenerationHydrationError,\n createGenerationResultSnapshot,\n parseGenerationResumeSnapshot,\n updateGenerationResumeSnapshot,\n} from './generation-types'\nimport { createNoOpVideoDevtoolsBridge } from './devtools-noop'\nimport { parseSSEResponse } from './sse-parser'\nimport { restoreInboundChunk } from '@tanstack/ai/client'\nimport type { StreamChunk } from '@tanstack/ai/client'\nimport type { ByokClient } from './byok'\nimport type {\n ConnectConnectionAdapter,\n GenerationHydrationResult,\n RunAgentInputContext,\n} from './connection-adapters'\nimport type {\n AIDevtoolsClientMetadata,\n AIDevtoolsGenerationProgress,\n VideoDevtoolsBridge,\n VideoDevtoolsBridgeOptions,\n} from './devtools'\nimport type {\n GenerationClientState,\n GenerationFetcher,\n GenerationPersistenceOptions,\n GenerationResumeSnapshot,\n GenerationResumeState,\n GenerationTransport,\n VideoGenerateInput,\n VideoGenerateResult,\n VideoGenerationClientOptions,\n VideoStatusInfo,\n} from './generation-types'\n\n/**\n * Callbacks stored in a ref so hooks can update them without recreating the client.\n */\n// All optional fields explicitly allow `| undefined` so callers can spread\n// option bags (where each callback may be `undefined`) into the callbacks\n// ref under `exactOptionalPropertyTypes`.\ninterface VideoCallbacks<TOutput> {\n onResult?:\n | ((result: VideoGenerateResult) => TOutput | null | void)\n | undefined\n onError?: ((error: Error) => void) | undefined\n onProgress?: ((progress: number, message?: string) => void) | undefined\n onChunk?: ((chunk: StreamChunk) => void) | undefined\n onJobCreated?: ((jobId: string) => void) | undefined\n onStatusUpdate?: ((status: VideoStatusInfo) => void) | undefined\n onResultChange?: ((result: TOutput | null) => void) | undefined\n onLoadingChange?: ((isLoading: boolean) => void) | undefined\n onErrorChange?: ((error: Error | undefined) => void) | undefined\n onStatusChange?: ((status: GenerationClientState) => void) | undefined\n onJobIdChange?: ((jobId: string | null) => void) | undefined\n onVideoStatusChange?: ((status: VideoStatusInfo | null) => void) | undefined\n onResumeSnapshotChange?:\n | ((snapshot: GenerationResumeSnapshot | undefined) => void)\n | undefined\n onResumeStateChange?:\n | ((resumeState: GenerationResumeState | null) => void)\n | undefined\n}\n\n/**\n * A specialized client for job-based video generation.\n *\n * Video generation is asynchronous: a job is created, then polled for status\n * until completion. This client handles the full lifecycle.\n *\n * Supports two transport modes:\n * - **ConnectConnectionAdapter** — Server handles the polling loop internally and\n * streams status updates via CUSTOM events.\n * - **Fetcher** — Direct async function that returns a completed\n * `VideoGenerateResult`.\n *\n * @example\n * ```typescript\n * // With streaming connection adapter (server-driven polling)\n * const client = new VideoGenerationClient({\n * connection: fetchServerSentEvents('/api/generate/video'),\n * onResultChange: setResult,\n * onVideoStatusChange: setVideoStatus,\n * })\n *\n * // With fetcher (direct result)\n * const client = new VideoGenerationClient({\n * fetcher: async (input) => {\n * const res = await fetch('/api/video/generate', {\n * method: 'POST',\n * body: JSON.stringify(input),\n * })\n * return res.json() // { jobId, status: 'completed', url, expiresAt }\n * },\n * })\n *\n * await client.generate({ prompt: 'A flying car over a city' })\n * ```\n */\nexport class VideoGenerationClient<TOutput = VideoGenerateResult> {\n private readonly connection: ConnectConnectionAdapter | undefined\n // Persistence handlers supplied as options (e.g. alongside a `fetcher`), used\n // when the connection doesn't carry its own — the connection's handlers take\n // precedence when both exist.\n private readonly hydrateGenerationHandler:\n | ConnectConnectionAdapter['hydrateGeneration']\n | undefined\n private readonly joinRunHandler:\n | ConnectConnectionAdapter['joinRun']\n | undefined\n private readonly fetcher:\n | GenerationFetcher<VideoGenerateInput, VideoGenerateResult>\n | undefined\n private uniqueId: string\n private readonly devtoolsMetadata: AIDevtoolsClientMetadata\n private readonly devtoolsBridge: VideoDevtoolsBridge<TOutput>\n private threadId: string\n // Server-driven mode (`persistence: true`): no local snapshot store; on mount\n // the client hydrates the last generation for `threadId` from the server.\n private readonly serverDriven: boolean = false\n private body: Record<string, any>\n private byok: ByokClient | undefined\n private byokProvider: (() => string | undefined) | undefined\n\n private result: TOutput | null = null\n private input: VideoGenerateInput | null = null\n private progress: AIDevtoolsGenerationProgress | null = null\n private jobId: string | null = null\n private videoStatus: VideoStatusInfo | null = null\n private isLoading = false\n private error: Error | undefined = undefined\n private status: GenerationClientState = 'idle'\n private resumeSnapshot: GenerationResumeSnapshot | undefined\n private abortController: AbortController | null = null\n private rejoinedRunId: string | undefined\n private readonly callbacksRef: VideoCallbacks<TOutput>\n private devtoolsMounted = false\n private disposed = false\n private serverHydrationStarted = false\n\n constructor(\n options: Omit<\n VideoGenerationClientOptions<TOutput>,\n 'persistence' | 'threadId'\n > &\n GenerationPersistenceOptions &\n GenerationTransport<VideoGenerateInput, VideoGenerateResult>,\n ) {\n // `threadId` is the only identity. Do not mint a random id during\n // construct: hooks build this client during render.\n this.threadId = options.threadId ?? ''\n this.uniqueId = this.threadId\n this.connection = options.connection\n this.fetcher = options.fetcher\n this.hydrateGenerationHandler = options.hydrateGeneration\n this.joinRunHandler = options.joinRun\n this.body = options.body ?? {}\n this.byok = options.byok\n this.byokProvider = options.byokProvider\n // `persistence` is `false`/omitted (ephemeral) or `true` (server-driven:\n // hydrate the last generation for `threadId` from the server on mount).\n this.serverDriven = options.persistence === true\n this.callbacksRef = {\n onResult: options.onResult,\n onError: options.onError,\n onProgress: options.onProgress,\n onChunk: options.onChunk,\n onJobCreated: options.onJobCreated,\n onStatusUpdate: options.onStatusUpdate,\n onResultChange: options.onResultChange,\n onLoadingChange: options.onLoadingChange,\n onErrorChange: options.onErrorChange,\n onStatusChange: options.onStatusChange,\n onJobIdChange: options.onJobIdChange,\n onVideoStatusChange: options.onVideoStatusChange,\n onResumeSnapshotChange: options.onResumeSnapshotChange,\n onResumeStateChange: options.onResumeStateChange,\n }\n\n this.devtoolsMetadata = this.createDevtoolsMetadata(options.devtools)\n this.devtoolsBridge = (\n options.devtoolsBridgeFactory ?? createNoOpVideoDevtoolsBridge\n )<TOutput>(this.buildDevtoolsBridgeOptions())\n\n // Mount hydration (`maybeHydrateFromServer`) is deliberately NOT run here. The framework\n // hooks build this client inside `useMemo`, so the constructor executes in\n // React's render phase; hydrating here would re-fire the hydrate GET on\n // every discarded/speculative render, flooding the connection pool when\n // several clients mount together. It is kicked off once from\n // `mountDevtools`, which the hooks call from a commit-phase mount effect.\n }\n\n private buildDevtoolsBridgeOptions(): VideoDevtoolsBridgeOptions<TOutput> {\n const client = this\n return {\n get hookId() {\n return client.uniqueId\n },\n get clientId() {\n return client.uniqueId\n },\n get threadId() {\n return client.threadId\n },\n metadata: this.devtoolsMetadata,\n getCoreState: () => ({\n input: this.input,\n result: this.result,\n progress: this.progress,\n status: this.status,\n isLoading: this.isLoading,\n jobId: this.jobId,\n videoStatus: this.videoStatus,\n ...(this.error ? { error: this.error.message } : {}),\n }),\n }\n }\n\n mountDevtools(): void {\n this.ensureThreadId()\n // Mounting revives a disposed client. Framework hooks call this from\n // their mount effect, so a dispose → remount cycle (e.g. React\n // StrictMode's mount → cleanup → mount replay against the same memoized\n // client) leaves the client usable again.\n this.disposed = false\n this.maybeHydrateFromServer()\n // Re-attach to an already-loaded `running` snapshot (remount case); see the\n // note in GenerationClient.mountDevtools. Guarded by rejoinInFlight.\n this.maybeResumeInFlight()\n if (this.devtoolsMounted) {\n return\n }\n\n this.devtoolsMounted = true\n this.devtoolsBridge.emitRegistered()\n this.devtoolsBridge.emitSnapshot()\n }\n\n /**\n * Trigger video generation.\n * Only one generation can be in-flight at a time.\n */\n async generate(input: VideoGenerateInput): Promise<void> {\n if (this.disposed) return\n if (this.isLoading) return\n this.mountDevtools()\n\n this.input = input\n this.progress = null\n const runId = this.devtoolsBridge.beginRun(input)\n this.setIsLoading(true)\n this.setStatus('generating')\n this.setError(undefined)\n this.setJobId(null)\n this.setVideoStatus(null)\n\n const abortController = new AbortController()\n this.abortController = abortController\n const { signal } = abortController\n\n try {\n let headers: Record<string, string> | undefined\n if (this.byok) {\n const provider = resolveByokProviderId(\n this.byokProvider,\n this.body.provider,\n )\n headers = await prepareResolvedByokHeaders(this.byok, provider)\n }\n\n if (this.fetcher) {\n await this.generateWithFetcher(input, signal, runId, headers)\n } else if (this.connection) {\n const mergedData = { ...this.body, ...input }\n const stream = this.connection.connect(\n [],\n mergedData,\n signal,\n this.createRunContext(runId, headers),\n )\n await this.processStream(stream, runId, signal)\n } else {\n throw new Error(\n 'VideoGenerationClient requires either a connection or fetcher option',\n )\n }\n if (!signal.aborted && this.status === 'success') {\n this.devtoolsBridge.finishRun(\n this.devtoolsBridge.getActiveRunId() ?? runId,\n 'run:completed',\n 'completed',\n )\n }\n } catch (err: unknown) {\n if (signal.aborted) return\n const error = err instanceof Error ? err : new Error(String(err))\n if (error instanceof ByokMissingError) {\n this.byok?.request(error.provider, 'missing')\n }\n if (error instanceof ByokBlockedError && error.reason === 'locked') {\n this.byok?.request(error.provider, 'locked')\n }\n this.setError(error)\n this.setStatus('error')\n this.recordResumeSnapshotError(error)\n this.devtoolsBridge.finishRun(\n this.devtoolsBridge.getActiveRunId() ?? runId,\n 'run:errored',\n 'errored',\n error.message,\n )\n this.callbacksRef.onError?.(error)\n } finally {\n if (this.abortController === abortController) {\n this.abortController = null\n this.setIsLoading(false)\n }\n }\n }\n\n /**\n * Direct fetcher mode: call fetcher and set result.\n */\n private async generateWithFetcher(\n input: VideoGenerateInput,\n signal: AbortSignal,\n runId: string,\n headers?: Record<string, string>,\n ): Promise<void> {\n if (!this.fetcher) return\n\n // Fetcher returns a completed result directly, or a Response with SSE body\n const result = await this.fetcher(\n input,\n headers === undefined ? { signal } : { signal, headers },\n )\n if (signal.aborted) return\n\n if (result instanceof Response) {\n // Server function returned SSE Response — parse stream\n await this.processStream(parseSSEResponse(result, signal), runId, signal)\n } else {\n this.devtoolsBridge.ensureRunStarted(runId)\n this.setResult(result)\n this.setStatus('success')\n this.completePlainFetcherResumeSnapshot(result)\n }\n }\n\n /**\n * Process a stream of AG-UI events from the streaming connection adapter.\n * The server handles the polling loop and streams status updates.\n *\n * Throws {@link GENERATION_STREAM_TRUNCATED_MESSAGE} when the iteration ends\n * without a terminal chunk — see the note on\n * `GenerationClient.processStream`. Video runs are long enough that a proxy\n * idle timeout mid-poll is the likeliest way to hit it.\n */\n private async processStream(\n source: AsyncIterable<StreamChunk>,\n fallbackRunId: string,\n signal: AbortSignal,\n ): Promise<void> {\n let streamRunId: string | undefined\n let sawTerminalChunk = false\n\n for await (const raw of source) {\n if (signal.aborted) break\n\n const chunk = restoreInboundChunk(raw)\n this.callbacksRef.onChunk?.(chunk)\n this.observeResumeSnapshot(chunk)\n const chunkRunId =\n 'runId' in chunk && typeof chunk.runId === 'string'\n ? chunk.runId\n : undefined\n\n // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check -- AG-UI EventType has ~22 variants; this consumer only handles the subset relevant to video generation lifecycle.\n switch (chunk.type) {\n case 'RUN_STARTED': {\n streamRunId = chunk.runId\n this.devtoolsBridge.ensureRunStarted(chunk.runId)\n break\n }\n case 'CUSTOM': {\n this.devtoolsBridge.ensureRunStarted(streamRunId ?? fallbackRunId)\n if (chunk.name === GENERATION_EVENTS.VIDEO_JOB_CREATED) {\n const { jobId } = chunk.value as { jobId: string }\n this.setJobId(jobId)\n this.callbacksRef.onJobCreated?.(jobId)\n } else if (chunk.name === GENERATION_EVENTS.VIDEO_STATUS) {\n const statusInfo = chunk.value as VideoStatusInfo\n this.setVideoStatus(statusInfo)\n this.callbacksRef.onStatusUpdate?.(statusInfo)\n if (statusInfo.progress !== undefined) {\n this.setProgress(statusInfo.progress)\n }\n } else if (chunk.name === GENERATION_EVENTS.RESULT) {\n this.setResult(chunk.value as VideoGenerateResult)\n } else if (chunk.name === GENERATION_EVENTS.PROGRESS) {\n const { progress, message } = chunk.value as {\n progress: number\n message?: string\n }\n this.setProgress(progress, message)\n }\n break\n }\n case 'RUN_FINISHED': {\n streamRunId = chunk.runId\n sawTerminalChunk = true\n this.devtoolsBridge.ensureRunStarted(chunk.runId)\n this.setStatus('success')\n break\n }\n case 'RUN_ERROR': {\n this.devtoolsBridge.ensureRunStarted(\n chunkRunId ?? streamRunId ?? fallbackRunId,\n )\n // Spec RUN_ERROR message. Missing message uses this fallback.\n const msg =\n (chunk.message as string | undefined) || 'An error occurred'\n throw new Error(msg)\n }\n default:\n break\n }\n }\n\n // An aborted read is a deliberate stop/dispose, not a truncation.\n if (!sawTerminalChunk && !signal.aborted) {\n throw new Error(GENERATION_STREAM_TRUNCATED_MESSAGE)\n }\n }\n\n /**\n * Abort any in-flight generation or polling.\n */\n stop(): void {\n const runId = this.devtoolsBridge.getActiveRunId()\n if (this.abortController) {\n this.abortController.abort()\n this.abortController = null\n }\n this.setIsLoading(false)\n if (this.status === 'generating') {\n this.setStatus('idle')\n if (runId) {\n this.devtoolsBridge.finishRun(runId, 'run:cancelled', 'cancelled')\n }\n }\n // A stopped run is no longer resumable. Without this the in-memory\n // snapshot stays `running`, and a remount's `maybeResumeInFlight` would\n // rejoin a run the user just cancelled.\n if (this.resumeSnapshot && this.resumeSnapshot.status === 'running') {\n this.resumeSnapshot = {\n ...this.resumeSnapshot,\n resumeState: null,\n status: 'idle',\n }\n this.notifyResumeSnapshotChanged()\n }\n }\n\n /**\n * Clear all state and return to idle. Also drops the client's in-memory\n * resume snapshot, so a remount restores nothing. The server-side record is\n * untouched — this client no longer writes one — so a full page reload under\n * `persistence: true` re-hydrates the last generation again.\n */\n reset(): void {\n this.stop()\n this.setResult(null)\n this.input = null\n this.progress = null\n this.devtoolsBridge.resetRuns()\n this.setJobId(null)\n this.setVideoStatus(null)\n this.setError(undefined)\n this.setStatus('idle')\n this.clearResumeSnapshot()\n this.devtoolsBridge.emitState()\n }\n\n /**\n * Update options without recreating the client.\n */\n updateOptions(\n options: Partial<\n Pick<\n VideoGenerationClientOptions<TOutput>,\n | 'body'\n | 'byok'\n | 'byokProvider'\n | 'onResult'\n | 'onError'\n | 'onProgress'\n | 'onChunk'\n | 'onJobCreated'\n | 'onStatusUpdate'\n >\n >,\n ): void {\n if (options.body !== undefined) {\n this.body = options.body ?? {}\n }\n if (options.byok !== undefined) {\n this.byok = options.byok\n }\n if (options.byokProvider !== undefined) {\n this.byokProvider = options.byokProvider\n }\n if (options.onResult !== undefined) {\n this.callbacksRef.onResult = options.onResult\n }\n if (options.onError !== undefined) {\n this.callbacksRef.onError = options.onError\n }\n if (options.onProgress !== undefined) {\n this.callbacksRef.onProgress = options.onProgress\n }\n if (options.onChunk !== undefined) {\n this.callbacksRef.onChunk = options.onChunk\n }\n if (options.onJobCreated !== undefined) {\n this.callbacksRef.onJobCreated = options.onJobCreated\n }\n if (options.onStatusUpdate !== undefined) {\n this.callbacksRef.onStatusUpdate = options.onStatusUpdate\n }\n }\n\n dispose(): void {\n this.disposed = true\n // Teardown, NOT a user cancel (see GenerationClient.dispose): abort in-flight\n // delivery but keep the `running` snapshot resumable so a remount rejoins.\n if (this.abortController) {\n this.abortController.abort()\n this.abortController = null\n }\n this.setIsLoading(false)\n this.devtoolsBridge.dispose()\n this.devtoolsMounted = false\n this.serverHydrationStarted = false\n this.rejoinedRunId = undefined\n }\n\n // ===========================\n // Getters\n // ===========================\n\n getResult(): TOutput | null {\n return this.result\n }\n\n getJobId(): string | null {\n return this.jobId\n }\n\n getVideoStatus(): VideoStatusInfo | null {\n return this.videoStatus\n }\n\n getIsLoading(): boolean {\n return this.isLoading\n }\n\n getError(): Error | undefined {\n return this.error\n }\n\n getStatus(): GenerationClientState {\n return this.status\n }\n\n getResumeSnapshot(): GenerationResumeSnapshot | undefined {\n return this.resumeSnapshot\n ? {\n ...this.resumeSnapshot,\n ...(this.resumeSnapshot.pendingArtifacts\n ? { pendingArtifacts: [...this.resumeSnapshot.pendingArtifacts] }\n : {}),\n ...(this.resumeSnapshot.result\n ? {\n result: {\n ...this.resumeSnapshot.result,\n ...(this.resumeSnapshot.result.artifacts\n ? { artifacts: [...this.resumeSnapshot.result.artifacts] }\n : {}),\n },\n }\n : {}),\n ...(this.resumeSnapshot.error\n ? { error: { ...this.resumeSnapshot.error } }\n : {}),\n ...(this.resumeSnapshot.lastEvent\n ? { lastEvent: { ...this.resumeSnapshot.lastEvent } }\n : {}),\n }\n : undefined\n }\n\n // ===========================\n // Private state setters\n // ===========================\n\n private setResult(rawResult: VideoGenerateResult | null): void {\n if (rawResult === null) {\n this.result = null\n this.callbacksRef.onResultChange?.(null)\n this.devtoolsBridge.recordResultChange()\n return\n }\n\n const completedStatus = this.createCompletedVideoStatus(rawResult)\n if (this.progress?.value !== 100) {\n this.setProgress(100, this.progress?.message)\n }\n this.setJobId(rawResult.jobId)\n this.setVideoStatus(completedStatus)\n\n if (this.callbacksRef.onResult) {\n const transformed = this.callbacksRef.onResult(rawResult)\n if (transformed === null) {\n // null return → keep previous result unchanged, just re-emit\n this.devtoolsBridge.emitState()\n return\n }\n if (transformed !== undefined) {\n // Non-null, non-undefined → use transformed value\n this.result = transformed\n this.callbacksRef.onResultChange?.(this.result)\n this.devtoolsBridge.recordResultChange()\n return\n }\n }\n\n // No onResult callback, or callback returned void → use raw value as\n // TOutput. When the caller did not supply an onResult transform,\n // `TOutput` defaults to `VideoGenerateResult`, so the runtime cast is\n // sound.\n // oxlint-disable-next-line eslint-js/no-restricted-syntax -- TOutput defaults to VideoGenerateResult when no onResult transform is supplied\n this.result = rawResult as unknown as TOutput\n this.callbacksRef.onResultChange?.(this.result)\n this.devtoolsBridge.recordResultChange()\n }\n\n private setJobId(jobId: string | null): void {\n this.jobId = jobId\n this.callbacksRef.onJobIdChange?.(jobId)\n this.devtoolsBridge.recordJobIdChange()\n }\n\n private setVideoStatus(status: VideoStatusInfo | null): void {\n this.videoStatus = status\n this.callbacksRef.onVideoStatusChange?.(status)\n this.devtoolsBridge.recordVideoStatusChange()\n }\n\n private setIsLoading(isLoading: boolean): void {\n this.isLoading = isLoading\n this.callbacksRef.onLoadingChange?.(isLoading)\n this.devtoolsBridge.recordLoadingChange()\n }\n\n private setError(error: Error | undefined): void {\n this.error = error\n this.callbacksRef.onErrorChange?.(error)\n this.devtoolsBridge.recordErrorChange(error)\n }\n\n private setStatus(status: GenerationClientState): void {\n this.status = status\n this.callbacksRef.onStatusChange?.(status)\n this.devtoolsBridge.recordStatusChange(status)\n }\n\n private setProgress(value: number, message?: string): void {\n this.progress = {\n value,\n ...(message ? { message } : {}),\n }\n if (message === undefined) {\n this.callbacksRef.onProgress?.(value)\n } else {\n this.callbacksRef.onProgress?.(value, message)\n }\n this.devtoolsBridge.recordProgressChange()\n }\n\n private createCompletedVideoStatus(\n result: VideoGenerateResult,\n ): VideoStatusInfo {\n return {\n jobId: result.jobId,\n status: result.status,\n progress: 100,\n url: result.url,\n }\n }\n\n private createDevtoolsMetadata(\n metadata?: Partial<AIDevtoolsClientMetadata>,\n ): AIDevtoolsClientMetadata {\n return {\n hookName: metadata?.hookName ?? 'useGenerateVideo',\n outputKind: metadata?.outputKind ?? 'video',\n ...(metadata?.framework ? { framework: metadata.framework } : {}),\n ...(metadata?.name ? { name: metadata.name } : {}),\n }\n }\n\n private ensureThreadId(): string {\n if (!this.threadId) {\n this.threadId = this.generateUniqueId('video')\n }\n this.uniqueId = this.threadId\n return this.threadId\n }\n\n private generateUniqueId(prefix: string): string {\n return `${prefix}-${Date.now()}-${Math.random().toString(36).substring(7)}`\n }\n\n private createRunContext(\n runId: string,\n headers?: Record<string, string>,\n ): RunAgentInputContext {\n return {\n threadId: this.threadId,\n runId,\n ...(headers ? { headers } : {}),\n }\n }\n\n private observeResumeSnapshot(chunk: StreamChunk): void {\n this.resumeSnapshot = updateGenerationResumeSnapshot(\n this.resumeSnapshot,\n chunk,\n )\n this.notifyResumeSnapshotChanged()\n }\n\n /** Notify the internal snapshot listener AND emit the public resume state. */\n private notifyResumeSnapshotChanged(): void {\n this.callbacksRef.onResumeSnapshotChange?.(this.resumeSnapshot)\n this.emitResumeState()\n }\n\n /** Derive the public `resumeState` from the internal snapshot. */\n private emitResumeState(): void {\n const snapshot = this.resumeSnapshot\n const state = snapshot?.resumeState\n const resumeState: GenerationResumeState | null = state\n ? {\n ...state,\n ...(snapshot?.pendingArtifacts && snapshot.pendingArtifacts.length > 0\n ? { pendingArtifacts: [...snapshot.pendingArtifacts] }\n : {}),\n }\n : null\n this.callbacksRef.onResumeStateChange?.(resumeState)\n }\n\n /**\n * Repaint the normal fields from a restored snapshot so a reload presents the\n * video in `result` / `status` / `error` / `jobId`, never a snapshot object.\n * `isLoading` stays false (no auto-tail). Not re-persisted (it came from\n * storage / the server).\n *\n * A `complete` snapshot with no durable video artifact cannot be rebuilt, so\n * it repaints as an error rather than a `success` with a `null` result — see\n * the note on `GenerationClient.repaintFromSnapshot`.\n */\n private repaintFromSnapshot(snapshot: GenerationResumeSnapshot): void {\n this.resumeSnapshot = snapshot\n this.notifyResumeSnapshotChanged()\n this.setStatus(clientStateFromResumeStatus(snapshot.status))\n this.setError(\n snapshot.error\n ? Object.assign(\n new Error(snapshot.error.message),\n snapshot.error.code ? { code: snapshot.error.code } : {},\n )\n : undefined,\n )\n if (snapshot.result?.providerJobId)\n this.setJobId(snapshot.result.providerJobId)\n const restored = this.reconstructVideoResult(snapshot)\n if (restored !== null) {\n this.setResult(restored)\n } else if (snapshot.status === 'complete') {\n this.reportUnrestorableResult()\n }\n }\n\n /**\n * Report a `complete` snapshot with no durable video artifact to rebuild\n * from. Runs after the status/error repaint above, so it wins over the\n * snapshot's own `complete` status.\n */\n private reportUnrestorableResult(): void {\n const error = new Error(GENERATION_UNRESTORABLE_RESULT_MESSAGE)\n this.setStatus('error')\n this.setError(error)\n this.callbacksRef.onError?.(error)\n }\n\n /**\n * Repaint a restored snapshot (client store or server hydrate) and, when it\n * reports a run still in flight, tail that run to completion via `joinRun`\n * (from the connection, or the `joinRun` option when the transport can't\n * carry one).\n *\n * A `running` snapshot that no `joinRun` handler can tail is repainted as an\n * interrupted error instead of a `generating` status that would never\n * settle: an interrupted generation cannot be resumed, only re-run.\n */\n private repaintRestoredSnapshot(\n snapshot: GenerationResumeSnapshot,\n activeRunId?: string,\n ): void {\n if (snapshot.status !== 'running') {\n this.repaintFromSnapshot(snapshot)\n return\n }\n const joinRun = this.connection?.joinRun ?? this.joinRunHandler\n const runId = activeRunId ?? snapshot.resumeState?.runId\n if (runId && joinRun) {\n this.repaintFromSnapshot(snapshot)\n this.rejoinInFlight(runId)\n return\n }\n this.repaintFromSnapshot({\n ...snapshot,\n resumeState: null,\n status: 'error',\n error: {\n message:\n 'The previous generation was interrupted before it finished and cannot be resumed — generate again to retry.',\n },\n })\n }\n\n /**\n * Rebuild a `VideoGenerateResult` from a restored snapshot: the video's bytes\n * are served from the durable artifact URL, so the restored result renders\n * from your own origin. Returns `null` when there is no durable video artifact.\n */\n private reconstructVideoResult(\n snapshot: GenerationResumeSnapshot,\n ): VideoGenerateResult | null {\n const result = snapshot.result\n const artifacts = result?.artifacts ?? []\n const output = artifacts.find(\n (a) =>\n a.role === 'output' && a.source.mediaType === 'video' && a.url != null,\n )\n if (!output?.url) return null\n return {\n jobId: result?.providerJobId ?? '',\n status: 'completed',\n url: output.url,\n ...(result?.expiresAt ? { expiresAt: new Date(result.expiresAt) } : {}),\n artifacts,\n }\n }\n\n /**\n * The plain (non-Response) fetcher path never observes stream chunks, so\n * the terminal snapshot is built here from the fetcher's own result. A\n * stale `error` from a previous run is intentionally dropped — this run\n * succeeded.\n */\n private completePlainFetcherResumeSnapshot(rawResult: unknown): void {\n const previous = this.resumeSnapshot\n const result = createGenerationResultSnapshot(rawResult)\n this.resumeSnapshot = {\n schemaVersion: 1,\n resumeState: null,\n status: 'complete',\n ...(previous?.activity ? { activity: previous.activity } : {}),\n ...(previous?.pendingArtifacts && previous.pendingArtifacts.length > 0\n ? { pendingArtifacts: [...previous.pendingArtifacts] }\n : {}),\n ...(result\n ? { result }\n : previous?.result\n ? { result: { ...previous.result } }\n : {}),\n }\n this.notifyResumeSnapshotChanged()\n }\n\n /**\n * Records a transport-level failure (network drop, throwing callback) in\n * the snapshot. Without this, only a server-emitted RUN_ERROR chunk would\n * mark the snapshot `error`, leaving a persisted record that claims the\n * run is still in flight.\n */\n private recordResumeSnapshotError(error: Error): void {\n // Surface the failure on the observable fields FIRST, unconditionally (see\n // the note in GenerationClient.recordResumeSnapshotError): a RUN_ERROR\n // already flipped the snapshot to `error`, so the early-return would else\n // skip this and leave `status` stuck on `generating`. The guard avoids a\n // duplicate `error` emission on the live `generate()` path.\n if (this.status !== 'error') this.setStatus('error')\n this.setError(error)\n if (this.resumeSnapshot?.status === 'error') return\n if (!this.resumeSnapshot && !this.serverDriven) return\n const previous = this.resumeSnapshot\n this.resumeSnapshot = {\n schemaVersion: 1,\n resumeState: null,\n status: 'error',\n ...(previous?.activity ? { activity: previous.activity } : {}),\n ...(previous?.pendingArtifacts && previous.pendingArtifacts.length > 0\n ? { pendingArtifacts: [...previous.pendingArtifacts] }\n : {}),\n ...(previous?.result ? { result: { ...previous.result } } : {}),\n error: { message: error.message },\n }\n this.notifyResumeSnapshotChanged()\n }\n\n /**\n * Drop the client's in-memory snapshot and re-emit. Purely local — this\n * client writes no storage, so nothing persisted is removed.\n */\n private clearResumeSnapshot(): void {\n this.resumeSnapshot = undefined\n this.notifyResumeSnapshotChanged()\n }\n\n /**\n * Server-driven mount hydration entry point (`persistence: true`). Runs at\n * most once, from the commit-phase mount path (`mountDevtools`) — never the\n * constructor / render phase — so remounts and speculative renders can't\n * re-fire the hydrate GET.\n */\n private maybeHydrateFromServer(): void {\n if (!this.serverDriven || this.serverHydrationStarted) return\n this.serverHydrationStarted = true\n if (this.connection?.hydrateGeneration ?? this.hydrateGenerationHandler) {\n this.hydrateFromServer()\n } else {\n // `persistence: true` without any hydrate source can never restore\n // anything — warn rather than silently no-op.\n console.warn(\n '[TanStack AI] `persistence: true` (server-driven) needs a `hydrateGeneration` handler — either a connection that implements one (e.g. `fetchServerSentEvents` / `fetchHttpStream`, or `stream()` / `rpcStream()` with persistence handlers) or the `hydrateGeneration` option. Without one, nothing is persisted or restored.',\n )\n }\n }\n\n /**\n * Server-driven mount hydration (`persistence: true`). The client holds no\n * local snapshot; on mount it asks the server — keyed by the stable threadId —\n * for the last generation's resume snapshot, validates it, and repaints it. It\n * never auto-starts a run, and never blocks: a `generate()` that starts first\n * owns the client and hydration backs off, mirroring the chat client.\n *\n * A genuine **miss** (no record for the thread) is silent; a genuine\n * **failure** (transport error, authorize rejection, malformed body, a record\n * the validator rejects) surfaces through `status` / `error` / `onError` — see\n * the note on `GenerationClient.hydrateFromServer`.\n */\n private hydrateFromServer(): void {\n const hydrate =\n this.connection?.hydrateGeneration ?? this.hydrateGenerationHandler\n if (!hydrate) return\n // A send that already started owns the client; don't stomp it.\n if (this.resumeSnapshot || this.isLoading || this.status !== 'idle') return\n void (async () => {\n let res: GenerationHydrationResult\n try {\n res = await hydrate(this.threadId)\n } catch (cause) {\n this.failHydration(\n createGenerationHydrationError(\n 'the request to the server did not succeed',\n cause,\n ),\n )\n return\n }\n // No record for this thread — a fresh thread, not a failure.\n if (!res.resumeSnapshot) return\n const snapshot = parseGenerationResumeSnapshot(res.resumeSnapshot)\n if (!snapshot) {\n this.failHydration(\n createGenerationHydrationError(\n 'the server returned a record this client cannot read (unknown schema version, or a missing/invalid `status` or `resumeState`)',\n ),\n )\n return\n }\n // Re-check: a send may have started while the fetch was in flight.\n if (this.resumeSnapshot || this.isLoading || this.status !== 'idle')\n return\n // A run still generating on the server: re-attach and finish it in place.\n this.repaintRestoredSnapshot(snapshot, res.activeRun?.runId)\n })()\n }\n\n /**\n * Surface a hydration failure on the observable fields. Skipped when a\n * `generate()` took ownership while the hydrate GET was in flight.\n */\n private failHydration(error: Error): void {\n if (this.resumeSnapshot || this.isLoading || this.status !== 'idle') return\n this.setStatus('error')\n this.setError(error)\n this.callbacksRef.onError?.(error)\n }\n\n /**\n * Re-attach to an already-loaded `running` snapshot (remount case); see the\n * note in GenerationClient.maybeResumeInFlight. Guarded by `rejoinInFlight`.\n */\n private maybeResumeInFlight(): void {\n if (this.resumeSnapshot?.status !== 'running') return\n const runId = this.resumeSnapshot.resumeState?.runId\n if (runId) this.rejoinInFlight(runId)\n }\n\n /**\n * Re-attach to a video run still generating and stream it to completion,\n * mirroring the chat client's mount-time rejoin. Reuses `processStream`, so\n * the job status and result repaint from the replayed chunks. A live\n * `generate()` owns the client and is never stomped; a run is rejoined once.\n */\n private rejoinInFlight(runId: string): void {\n const joinRun = this.connection?.joinRun ?? this.joinRunHandler\n if (!joinRun) return\n if (this.rejoinedRunId === runId) return\n if (this.isLoading || this.abortController) return\n this.rejoinedRunId = runId\n const controller = new AbortController()\n this.abortController = controller\n this.setIsLoading(true)\n this.setStatus('generating')\n void (async () => {\n try {\n await this.processStream(\n joinRun(runId, controller.signal),\n runId,\n controller.signal,\n )\n } catch (error) {\n if (!controller.signal.aborted) {\n const failure =\n error instanceof Error ? error : new Error(String(error))\n // Settles `status`/`error` AND rewrites the snapshot to a terminal\n // `error` with a null `resumeState`, so the next mount does not\n // rejoin this run again.\n this.recordResumeSnapshotError(failure)\n this.callbacksRef.onError?.(failure)\n }\n } finally {\n // Only reset if this rejoin still owns the client: a `stop()` +\n // fresh `generate()` may have replaced the controller while the tail\n // was settling, and that live run owns `isLoading` now.\n if (this.abortController === controller) {\n this.abortController = null\n this.setIsLoading(false)\n }\n }\n })()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4GA,IAAa,wBAAb,MAAkE;CAChE;CAIA;CAGA;CAGA;CAGA;CACA;CACA;CACA;CAGA,eAAyC;CACzC;CACA;CACA;CAEA,SAAiC;CACjC,QAA2C;CAC3C,WAAwD;CACxD,QAA+B;CAC/B,cAA8C;CAC9C,YAAoB;CACpB,QAAmC,KAAA;CACnC,SAAwC;CACxC;CACA,kBAAkD;CAClD;CACA;CACA,kBAA0B;CAC1B,WAAmB;CACnB,yBAAiC;CAEjC,YACE,SAMA;EAGA,KAAK,WAAW,QAAQ,YAAY;EACpC,KAAK,WAAW,KAAK;EACrB,KAAK,aAAa,QAAQ;EAC1B,KAAK,UAAU,QAAQ;EACvB,KAAK,2BAA2B,QAAQ;EACxC,KAAK,iBAAiB,QAAQ;EAC9B,KAAK,OAAO,QAAQ,QAAQ,CAAC;EAC7B,KAAK,OAAO,QAAQ;EACpB,KAAK,eAAe,QAAQ;EAG5B,KAAK,eAAe,QAAQ,gBAAgB;EAC5C,KAAK,eAAe;GAClB,UAAU,QAAQ;GAClB,SAAS,QAAQ;GACjB,YAAY,QAAQ;GACpB,SAAS,QAAQ;GACjB,cAAc,QAAQ;GACtB,gBAAgB,QAAQ;GACxB,gBAAgB,QAAQ;GACxB,iBAAiB,QAAQ;GACzB,eAAe,QAAQ;GACvB,gBAAgB,QAAQ;GACxB,eAAe,QAAQ;GACvB,qBAAqB,QAAQ;GAC7B,wBAAwB,QAAQ;GAChC,qBAAqB,QAAQ;EAC/B;EAE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AM,UAAU,KAAK,YAAY,WAAW,KAAK;EACjD,IAAI,CAAC,SAAS;EACd,IAAI,KAAK,kBAAkB,OAAO;EAClC,IAAI,KAAK,aAAa,KAAK,iBAAiB;EAC5C,KAAK,gBAAgB;EACrB,MAAM,aAAa,IAAI,gBAAgB;EACvC,KAAK,kBAAkB;EACvB,KAAK,aAAa,IAAI;EACtB,KAAK,UAAU,YAAY;EAC3B,CAAM,YAAY;GAChB,IAAI;IACF,MAAM,KAAK,cACT,QAAQ,OAAO,WAAW,MAAM,GAChC,OACA,WAAW,MACb;GACF,SAAS,OAAO;IACd,IAAI,CAAC,WAAW,OAAO,SAAS;KAC9B,MAAM,UACJ,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;KAI1D,KAAK,0BAA0B,OAAO;KACtC,KAAK,aAAa,UAAU,OAAO;IACrC;GACF,UAAU;IAIR,IAAI,KAAK,oBAAoB,YAAY;KACvC,KAAK,kBAAkB;KACvB,KAAK,aAAa,KAAK;IACzB;GACF;EACF,EAAA,CAAG;CACL;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/ai-client",
3
- "version": "0.25.2",
3
+ "version": "0.28.0",
4
4
  "description": "Framework-agnostic headless client for TanStack AI chat, realtime sessions, streaming transports, and media generations.",
5
5
  "author": "Tanner Linsley",
6
6
  "license": "MIT",
@@ -42,6 +42,10 @@
42
42
  "./devtools": {
43
43
  "types": "./dist/esm/devtools.d.ts",
44
44
  "import": "./dist/esm/devtools.js"
45
+ },
46
+ "./byok": {
47
+ "types": "./dist/esm/byok.d.ts",
48
+ "import": "./dist/esm/byok.js"
45
49
  }
46
50
  },
47
51
  "files": [
@@ -49,8 +53,8 @@
49
53
  "src"
50
54
  ],
51
55
  "dependencies": {
52
- "@tanstack/ai": "^0.47.3",
53
- "@tanstack/ai-event-client": "^0.9.0",
56
+ "@tanstack/ai": "^0.49.1",
57
+ "@tanstack/ai-event-client": "^0.10.0",
54
58
  "@tanstack/ai-utils": "^0.4.0"
55
59
  },
56
60
  "devDependencies": {