@tanstack/ai-angular 1.1.0 → 1.2.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.
package/README.md CHANGED
@@ -128,16 +128,17 @@ export async function POST(request: Request) {
128
128
 
129
129
  ## Available Functions
130
130
 
131
- | Function | Description |
132
- | ---------------------- | ---------------------------------------------------------------- |
133
- | `injectChat` | Streaming chat with messages, tool calls, and structured outputs |
134
- | `injectGeneration` | Generic generation client (streaming or one-shot) |
135
- | `injectGenerateImage` | Image generation |
136
- | `injectGenerateAudio` | Audio generation |
137
- | `injectGenerateVideo` | Video generation |
138
- | `injectGenerateSpeech` | Text-to-speech |
139
- | `injectSummarize` | Summarization |
140
- | `injectTranscription` | Audio transcription |
131
+ | Function | Description |
132
+ | ----------------------- | ---------------------------------------------------------------- |
133
+ | `injectChat` | Streaming chat with messages, tool calls, and structured outputs |
134
+ | `injectGeneration` | Generic generation client (streaming or one-shot) |
135
+ | `injectGenerateImage` | Image generation |
136
+ | `injectGenerateAudio` | Audio generation |
137
+ | `injectGenerateVideo` | Video generation |
138
+ | `injectGenerate3DModel` | 3D model generation (experimental) |
139
+ | `injectGenerateSpeech` | Text-to-speech |
140
+ | `injectSummarize` | Summarization |
141
+ | `injectTranscription` | Audio transcription |
141
142
 
142
143
  All generation functions return signals (`result`, `isLoading`, `error`, `status`) and methods (`generate`, `stop`, `reset`).
143
144
 
package/dist/README.md CHANGED
@@ -128,16 +128,17 @@ export async function POST(request: Request) {
128
128
 
129
129
  ## Available Functions
130
130
 
131
- | Function | Description |
132
- | ---------------------- | ---------------------------------------------------------------- |
133
- | `injectChat` | Streaming chat with messages, tool calls, and structured outputs |
134
- | `injectGeneration` | Generic generation client (streaming or one-shot) |
135
- | `injectGenerateImage` | Image generation |
136
- | `injectGenerateAudio` | Audio generation |
137
- | `injectGenerateVideo` | Video generation |
138
- | `injectGenerateSpeech` | Text-to-speech |
139
- | `injectSummarize` | Summarization |
140
- | `injectTranscription` | Audio transcription |
131
+ | Function | Description |
132
+ | ----------------------- | ---------------------------------------------------------------- |
133
+ | `injectChat` | Streaming chat with messages, tool calls, and structured outputs |
134
+ | `injectGeneration` | Generic generation client (streaming or one-shot) |
135
+ | `injectGenerateImage` | Image generation |
136
+ | `injectGenerateAudio` | Audio generation |
137
+ | `injectGenerateVideo` | Video generation |
138
+ | `injectGenerate3DModel` | 3D model generation (experimental) |
139
+ | `injectGenerateSpeech` | Text-to-speech |
140
+ | `injectSummarize` | Summarization |
141
+ | `injectTranscription` | Audio transcription |
141
142
 
142
143
  All generation functions return signals (`result`, `isLoading`, `error`, `status`) and methods (`generate`, `stop`, `reset`).
143
144
 
@@ -1,2 +1 @@
1
- import { ByokClient, EMPTY_BYOK_SNAPSHOT, decryptKeyring, defaultByokStorage, defineByok, defineByokProvider, deriveAesKey, encryptKeyring, isPasskeyStorageSupported, memoryStorage, passkeyStorage } from "@tanstack/ai-client/byok";
2
- export { ByokClient, EMPTY_BYOK_SNAPSHOT, decryptKeyring, defaultByokStorage, defineByok, defineByokProvider, deriveAesKey, encryptKeyring, isPasskeyStorageSupported, memoryStorage, passkeyStorage };
1
+ export { ByokClient, EMPTY_BYOK_SNAPSHOT, decryptKeyring, defaultByokStorage, defineByok, defineByokProvider, deriveAesKey, encryptKeyring, isPasskeyStorageSupported, memoryStorage, passkeyStorage } from "@tanstack/ai-client/byok";
@@ -291,6 +291,18 @@ function injectGenerateImage(options) {
291
291
  reconstructResult: reconstructImageResult$1
292
292
  });
293
293
  }
294
+ function injectGenerate3DModel(options) {
295
+ const devtools = {
296
+ ...options.devtools,
297
+ framework: "angular",
298
+ hookName: "injectGenerate3DModel"
299
+ };
300
+ return injectGeneration({
301
+ ...options,
302
+ devtools,
303
+ persistence: false
304
+ });
305
+ }
294
306
  function injectGenerateAudio(options) {
295
307
  const devtools = {
296
308
  ...options.devtools,
@@ -467,6 +479,6 @@ function injectGenerateVideo(options) {
467
479
  runId: runId.asReadonly()
468
480
  };
469
481
  }
470
- export { AudioRecorder, BatchStrategy, ChatClient, CompositeStrategy, DurableStreamIncompleteError, GENERATION_EVENTS, GenerationClient, ImmediateStrategy, InterruptManager, PartialJSONParser, PunctuationStrategy, RealtimeClient, StorageUnavailableError, StreamProcessor, StreamReconnectLimitError, StreamTruncatedError, UnsupportedResponseStreamError, VideoGenerationClient, WordBoundaryStrategy, clientTools, convertMessagesToModelMessages, createAIDevtoolsGenerationPreview, createChatClientOptions, createMcpAppBridge, defaultJSONParser, fetchHttpStream, fetchJson, fetchServerSentEvents, generateMessageId, getWebMCPTools, indexedDBPersistence, injectAudioRecorder, injectByok, injectChat, injectGenerateAudio, injectGenerateImage, injectGenerateSpeech, injectGenerateVideo, injectGeneration, injectPageWebMCPTools, injectRegisterWebMCPTools, injectSummarize, injectTranscription, localStoragePersistence, modelMessageToUIMessage, modelMessagesToUIMessages, normalizeToUIMessage, parsePartialJSON, reconstructAudioResult, reconstructImageResult, reconstructSpeechResult, reconstructSummarizeResult, reconstructTranscriptionResult, registerWebMCPTools, rpcStream, sessionStoragePersistence, stream, subscribeWebMCPTools, uiMessageToModelMessages, webSocket, xhrHttpStream, xhrServerSentEvents };
482
+ export { AudioRecorder, BatchStrategy, ChatClient, CompositeStrategy, DurableStreamIncompleteError, GENERATION_EVENTS, GenerationClient, ImmediateStrategy, InterruptManager, PartialJSONParser, PunctuationStrategy, RealtimeClient, StorageUnavailableError, StreamProcessor, StreamReconnectLimitError, StreamTruncatedError, UnsupportedResponseStreamError, VideoGenerationClient, WordBoundaryStrategy, clientTools, convertMessagesToModelMessages, createAIDevtoolsGenerationPreview, createChatClientOptions, createMcpAppBridge, defaultJSONParser, fetchHttpStream, fetchJson, fetchServerSentEvents, generateMessageId, getWebMCPTools, indexedDBPersistence, injectAudioRecorder, injectByok, injectChat, injectGenerate3DModel, injectGenerateAudio, injectGenerateImage, injectGenerateSpeech, injectGenerateVideo, injectGeneration, injectPageWebMCPTools, injectRegisterWebMCPTools, injectSummarize, injectTranscription, localStoragePersistence, modelMessageToUIMessage, modelMessagesToUIMessages, normalizeToUIMessage, parsePartialJSON, reconstructAudioResult, reconstructImageResult, reconstructSpeechResult, reconstructSummarizeResult, reconstructTranscriptionResult, registerWebMCPTools, rpcStream, sessionStoragePersistence, stream, subscribeWebMCPTools, uiMessageToModelMessages, webSocket, xhrHttpStream, xhrServerSentEvents };
471
483
 
472
484
  //# sourceMappingURL=tanstack-ai-angular.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"tanstack-ai-angular.mjs","names":[],"sources":["../../src/internal/to-reactive.ts","../../src/inject-chat.ts","../../src/inject-byok.ts","../../src/inject-web-mcp-tools.ts","../../src/inject-generation.ts","../../src/inject-generate-image.ts","../../src/inject-generate-audio.ts","../../src/inject-generate-speech.ts","../../src/inject-transcription.ts","../../src/inject-audio-recorder.ts","../../src/inject-summarize.ts","../../src/inject-generate-video.ts"],"sourcesContent":["import { computed, isSignal } from '@angular/core'\nimport type { Signal } from '@angular/core'\n\n/**\n * A value that may be supplied to `injectChat` either as a static value, an\n * Angular `Signal`, or a zero-arg getter. The getter form lets callers read\n * other signals so the option stays reactive.\n */\nexport type ReactiveOption<T> = T | Signal<T> | (() => T)\n\n/**\n * Normalize a {@link ReactiveOption} into a `Signal`-like getter `() => T`.\n *\n * - A `Signal` is returned as-is (already a getter that tracks reads).\n * - A zero-arg function is wrapped in `computed` so reads inside it are tracked.\n * - A plain value becomes a constant non-reactive fn (never re-fires).\n */\nexport function toReactive<T>(value: ReactiveOption<T>): () => T {\n if (isSignal(value)) {\n return value\n }\n if (typeof value === 'function') {\n return computed(value as () => T)\n }\n return () => value\n}\n","import { ChatClient } from '@tanstack/ai-client'\nimport { createChatDevtoolsBridge } from '@tanstack/ai-client/devtools'\nimport {\n DestroyRef,\n Injector,\n afterNextRender,\n assertInInjectionContext,\n computed,\n effect,\n inject,\n signal,\n} from '@angular/core'\nimport { toReactive } from './internal/to-reactive'\nimport type {\n AnyClientTool,\n InterruptDefinition,\n InferSchemaType,\n ModelMessage,\n RunAgentResumeItem,\n SchemaInput,\n StreamChunk,\n} from '@tanstack/ai'\nimport type {\n ResolvableChatInterrupt,\n ChatResumeState,\n InferredClientContext,\n SendMessageOptions,\n StructuredOutputPart,\n} from '@tanstack/ai-client'\nimport type {\n DeepPartial,\n InjectChatOptions,\n InjectChatResult,\n MultimodalContent,\n UIMessage,\n} from './types'\n\nexport function injectChat<\n const TTools extends ReadonlyArray<AnyClientTool> = any,\n TSchema extends SchemaInput | undefined = undefined,\n TContext = InferredClientContext<TTools>,\n const TInterrupts extends ReadonlyArray<\n InterruptDefinition<any, any, any, any>\n > = readonly [],\n>(\n options: InjectChatOptions<TTools, TSchema, TContext, TInterrupts>,\n): InjectChatResult<TTools, TSchema, TInterrupts> {\n assertInInjectionContext(injectChat)\n\n type Partial = DeepPartial<InferSchemaType<NonNullable<TSchema>>>\n type Final = InferSchemaType<NonNullable<TSchema>>\n\n const destroyRef = inject(DestroyRef)\n const injector = inject(Injector)\n\n // Reactive option sources. Plain values become constant computeds.\n const forwardedPropsSource =\n options.forwardedProps !== undefined\n ? toReactive(options.forwardedProps)\n : undefined\n const contextSource =\n options.context !== undefined ? toReactive(options.context) : undefined\n const liveSource =\n options.live !== undefined ? toReactive(options.live) : undefined\n const toolsSource =\n options.tools !== undefined ? toReactive(options.tools) : undefined\n\n const transport = options.connection\n ? { connection: options.connection }\n : { fetcher: options.fetcher }\n\n const client = new ChatClient<TTools, TContext, TInterrupts>({\n devtoolsBridgeFactory: createChatDevtoolsBridge,\n ...transport,\n ...(options.initialMessages !== undefined && {\n initialMessages: options.initialMessages,\n }),\n threadId: options.threadId,\n ...(options.persistence === true\n ? {\n persistence: true,\n ...(options.history !== undefined && {\n history: options.history,\n }),\n }\n : { persistence: options.persistence }),\n ...(options.initialResumeSnapshot !== undefined && {\n initialResumeSnapshot: options.initialResumeSnapshot,\n }),\n ...(forwardedPropsSource !== undefined && {\n forwardedProps: forwardedPropsSource(),\n }),\n ...(options.byok !== undefined && { byok: options.byok }),\n byokProvider: () => options.byokProvider?.(),\n ...(contextSource !== undefined && { context: contextSource() }),\n devtools: {\n ...options.devtools,\n framework: 'angular',\n hookName: 'injectChat',\n outputKind: options.outputSchema ? 'structured' : 'chat',\n },\n onResponse: (response) => options.onResponse?.(response),\n onChunk: (chunk: StreamChunk) => options.onChunk?.(chunk),\n onFinish: (message) => options.onFinish?.(message),\n onError: (err) => options.onError?.(err),\n onInterruptStateChange: (nextInterruptState, context) => {\n options.onInterruptStateChange?.(nextInterruptState, context)\n },\n tools: toolsSource?.(),\n ...(options.interrupts !== undefined && {\n interrupts: options.interrupts,\n }),\n onCustomEvent: (eventType, data, context) =>\n options.onCustomEvent?.(eventType, data, context),\n ...(options.streamProcessor !== undefined && {\n streamProcessor: options.streamProcessor,\n }),\n ...(options.queue !== undefined && { queue: options.queue }),\n })\n\n const snapshot = signal(client.getSnapshot())\n const messages = computed(() => snapshot().messages)\n const interruptState = computed(() => snapshot().interruptState)\n const unsubscribeSnapshot = client.subscribeSnapshot(() =>\n snapshot.set(client.getSnapshot()),\n )\n\n // START TAILING HERE, not in the constructor. A client is idle until something\n // attaches it, so a client that gets built and thrown away never opens a\n // connection — an unreachable stream would hold one of the browser's ~6\n // connections per origin until the page reloaded. `inject*` runs in an injection\n // context tied to the consumer's lifetime, and `destroyRef.onDestroy` below is the\n // matching `detach`.\n client.attach()\n\n // Sync reactive forwardedProps / context to the client.\n if (forwardedPropsSource || contextSource) {\n effect(\n () => {\n const newForwardedProps = forwardedPropsSource?.()\n const newContext = contextSource?.()\n client.updateOptions({\n ...(newForwardedProps !== undefined && {\n forwardedProps: newForwardedProps,\n }),\n ...(newContext !== undefined && { context: newContext }),\n })\n },\n { injector },\n )\n }\n\n // Sync reactive tools to the client.\n if (toolsSource) {\n effect(() => client.updateOptions({ tools: toolsSource() }), { injector })\n }\n\n // Subscribe / unsubscribe based on reactive `live`.\n if (liveSource) {\n effect(\n () => {\n if (liveSource()) {\n client.subscribe()\n } else {\n client.unsubscribe()\n }\n },\n { injector },\n )\n }\n\n afterNextRender(\n () => {\n client.mountDevtools()\n // Delivery-durability resume is transparent: the resumable SSE\n // connection adapter reattaches via the browser's native Last-Event-ID\n // on reconnect. No client-side auto-resume wiring is needed.\n },\n { injector },\n )\n\n destroyRef.onDestroy(() => {\n unsubscribeSnapshot()\n // Release the connection first: the counterpart of the `attach` above.\n client.detach()\n if (liveSource?.()) {\n client.unsubscribe()\n } else {\n client.stop()\n }\n client.dispose()\n })\n\n // Active structured-output part = the one on the assistant message after the\n // latest user message. Ported from ai-vue/src/use-chat.ts.\n const activeStructuredPart = computed<StructuredOutputPart | null>(() => {\n const list = messages()\n let lastUserIndex = -1\n for (let i = list.length - 1; i >= 0; i--) {\n if (list[i]?.role === 'user') {\n lastUserIndex = i\n break\n }\n }\n if (lastUserIndex === -1) return null\n for (let i = list.length - 1; i > lastUserIndex; i--) {\n const m = list[i]\n if (m?.role !== 'assistant') continue\n const part = m.parts.find(\n (p): p is StructuredOutputPart => p.type === 'structured-output',\n )\n if (part) return part\n }\n return null\n })\n\n const partial = computed<Partial>(() => {\n const part = activeStructuredPart()\n if (!part) return {} as Partial\n const v = part.partial ?? part.data\n return (v ?? {}) as Partial\n })\n\n const final = computed<Final | null>(() => {\n const part = activeStructuredPart()\n if (!part || part.status !== 'complete') return null\n return part.data as Final\n })\n\n const sendMessage = async (\n content: string | MultimodalContent,\n sendOptions?: SendMessageOptions,\n ) => {\n await client.sendMessage(content, undefined, sendOptions)\n }\n const cancelQueued = (id: string) => client.cancelQueued(id)\n const append = async (message: ModelMessage | UIMessage<TTools>) => {\n await client.append(message)\n }\n const reload = async () => {\n await client.reload()\n }\n const loadOlderMessages = async () => {\n await client.loadOlderMessages()\n }\n const stop = () => client.stop()\n const clear = () => client.clear()\n const setMessages = (m: ReadonlyArray<UIMessage<TTools>>) =>\n client.setMessagesManually(m)\n const addToolResult = async (result: {\n toolCallId: string\n tool: string\n output: any\n state?: 'output-available' | 'output-error'\n errorText?: string\n }) => {\n await client.addToolResult(result)\n }\n const interrupts = computed(() => interruptState().interrupts)\n const interruptErrors = computed(() => interruptState().interruptErrors)\n const resuming = computed(() => interruptState().resuming)\n const resolveInterrupts = (\n resolution:\n | boolean\n | ((\n interrupt: ResolvableChatInterrupt<TTools, TInterrupts>,\n ) => undefined),\n ) => {\n if (typeof resolution === 'boolean') {\n client.resolveInterrupts(resolution)\n } else {\n client.resolveInterrupts(resolution)\n }\n }\n const cancelInterrupts = () => client.cancelInterrupts()\n const retryInterrupts = () => client.retryInterrupts()\n const resumeInterruptsUnsafe = (\n resumeItems: Array<RunAgentResumeItem>,\n state?: ChatResumeState,\n ) => client.resumeInterruptsUnsafe(resumeItems, state)\n\n // oxlint-disable-next-line eslint-js/no-restricted-syntax -- return shape diverges from conditional InjectChatResult<TTools, TSchema>; TS can't structurally narrow the TSchema-gated partial/final signals\n return {\n messages,\n sendMessage,\n queue: computed(() => snapshot().queue),\n cancelQueued,\n append,\n reload,\n stop,\n isLoading: computed(() => snapshot().isLoading),\n hasOlderMessages: computed(() => snapshot().hasOlderMessages),\n loadOlderMessages,\n error: computed(() => snapshot().error),\n status: computed(() => snapshot().status),\n isSubscribed: computed(() => snapshot().isSubscribed),\n connectionStatus: computed(() => snapshot().connectionStatus),\n sessionGenerating: computed(() => snapshot().sessionGenerating),\n isHydrating: computed(() => snapshot().isHydrating),\n setMessages,\n clear,\n addToolResult,\n runId: computed(() => snapshot().runId),\n interrupts,\n interruptErrors,\n resuming,\n resolveInterrupts,\n cancelInterrupts,\n retryInterrupts,\n resumeInterruptsUnsafe,\n partial,\n final,\n } as unknown as InjectChatResult<TTools, TSchema, TInterrupts>\n}\n","import {\n DestroyRef,\n assertInInjectionContext,\n inject,\n signal,\n} from '@angular/core'\nimport type { Signal } from '@angular/core'\nimport type { ByokClient, ByokSnapshot } from '@tanstack/ai-client/byok'\n\nexport function injectByok(client: ByokClient): Signal<ByokSnapshot> {\n assertInInjectionContext(injectByok)\n const destroyRef = inject(DestroyRef)\n const snapshot = signal(client.getSnapshot())\n const unsubscribe = client.subscribe(() => {\n snapshot.set(client.getSnapshot())\n })\n destroyRef.onDestroy(unsubscribe)\n return snapshot.asReadonly()\n}\n","import {\n DestroyRef,\n assertInInjectionContext,\n inject,\n signal,\n} from '@angular/core'\nimport { registerWebMCPTools, subscribeWebMCPTools } from '@tanstack/ai-client'\nimport type { Signal } from '@angular/core'\nimport type {\n AnyClientTool,\n InferredClientContext,\n RegisterWebMCPToolsOptions,\n SubscribeWebMCPToolsOptions,\n} from '@tanstack/ai-client'\n\n/**\n * Options for {@link injectRegisterWebMCPTools}.\n *\n * Context is required when a client tool declares a required runtime context.\n */\nexport type InjectRegisterWebMCPToolsOptions<\n TTools extends ReadonlyArray<AnyClientTool>,\n TContext = InferredClientContext<TTools>,\n> = Omit<RegisterWebMCPToolsOptions<TTools, TContext>, 'signal'> & {\n /** Receives asynchronous WebMCP registration errors. */\n onError?: (error: unknown) => void\n}\n\n/**\n * Registers executable client tools with WebMCP for the current Angular owner.\n *\n * Angular removes the registrations when it destroys the injection owner. Call\n * this function in an injection context, such as a component field initializer.\n *\n * @param tools - The executable client tools to expose through WebMCP.\n * @param options - Runtime context, per-tool options, and error handling.\n *\n * @example\n * ```ts\n * registration = injectRegisterWebMCPTools([statusTool], {\n * onError: (error) => console.error(error),\n * })\n * ```\n */\nexport function injectRegisterWebMCPTools<\n const TTools extends ReadonlyArray<AnyClientTool>,\n TContext = InferredClientContext<TTools>,\n>(\n tools: TTools,\n ...[options]: {} extends InjectRegisterWebMCPToolsOptions<TTools, TContext>\n ? [options?: InjectRegisterWebMCPToolsOptions<TTools, TContext>]\n : [options: InjectRegisterWebMCPToolsOptions<TTools, TContext>]\n) {\n assertInInjectionContext(injectRegisterWebMCPTools)\n const destroyRef = inject(DestroyRef)\n const registrationController = new AbortController()\n const { onError, ...registrationOptions } = options ?? {}\n\n destroyRef.onDestroy(() => registrationController.abort())\n\n void registerWebMCPTools(tools, {\n ...registrationOptions,\n signal: registrationController.signal,\n }).catch((error) => {\n if (!registrationController.signal.aborted) {\n onError?.(error)\n }\n })\n}\n\n/** Options for {@link injectPageWebMCPTools}. */\nexport type InjectPageWebMCPToolsOptions = Omit<\n SubscribeWebMCPToolsOptions,\n 'signal'\n>\n\n/**\n * Returns the WebMCP tools on the page as client tools for `injectChat`.\n *\n * The signal starts empty and updates when the page registers or removes a\n * tool. Angular stops the updates when it destroys the injection owner. Call\n * this function in an injection context.\n *\n * @param options - A filter that skips tools, and an error callback.\n *\n * @example\n * ```ts\n * pageTools = injectPageWebMCPTools({\n * filter: (tool) => tool.origin === location.origin,\n * })\n * chat = injectChat({ threadId: 'support-1', connection, tools: this.pageTools })\n * ```\n */\nexport function injectPageWebMCPTools(\n options?: InjectPageWebMCPToolsOptions,\n): Signal<Array<AnyClientTool>> {\n assertInInjectionContext(injectPageWebMCPTools)\n const destroyRef = inject(DestroyRef)\n const tools = signal<Array<AnyClientTool>>([])\n const controller = new AbortController()\n\n destroyRef.onDestroy(() => controller.abort())\n\n subscribeWebMCPTools((nextTools) => tools.set(nextTools), {\n signal: controller.signal,\n filter: (tool) => options?.filter?.(tool) ?? true,\n onError: (error) => options?.onError?.(error),\n })\n\n return tools.asReadonly()\n}\n","import { GenerationClient } from '@tanstack/ai-client'\nimport { createGenerationDevtoolsBridge } from '@tanstack/ai-client/devtools'\nimport {\n DestroyRef,\n Injector,\n afterNextRender,\n assertInInjectionContext,\n effect,\n inject,\n signal,\n} from '@angular/core'\nimport { toReactive } from './internal/to-reactive'\nimport type { Signal } from '@angular/core'\nimport type { StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientOptions,\n GenerationClientState,\n GenerationFetcher,\n GenerationRestoredResult,\n InferGenerationOutputFromReturn,\n} from '@tanstack/ai-client'\nimport type { ByokClient } from '@tanstack/ai-client/byok'\nimport type { ProviderId } from '@tanstack/ai/byok'\nimport type { ReactiveOption } from './internal/to-reactive'\n\nexport interface InjectGenerationOptions<TInput, TResult, TOutput = TResult> {\n /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */\n connection?: ConnectConnectionAdapter\n /** Direct async function for one-shot generation (no streaming protocol needed) */\n fetcher?: GenerationFetcher<TInput, TResult>\n /** Additional request body params. Reactive. */\n body?: ReactiveOption<Record<string, any>>\n /** Optional BYOK keyring. Keys go in `x-byok-*` headers, never the body. */\n byok?: ByokClient\n /** Optional provider id. If it returns a slug, only that key is sent. If no slug resolves (`byokProvider`, then `body.provider`), generate throws. */\n byokProvider?: () => ProviderId | undefined\n /** Display options for TanStack AI Devtools. */\n devtools?: AIDevtoolsDisplayOptions\n /**\n * How this generation persists across reloads.\n * - Omit / `false`: ephemeral, in-memory only.\n * - `true`: server-driven — on mount the client hydrates the last generation\n * for its `threadId` from the server (needs a connection with a\n * `hydrateGeneration` handler) and repaints it; it never auto-starts a run.\n */\n persistence?: boolean\n /**\n * The **scope** this generation belongs to: a stable, app-chosen name for the\n * slot successive runs fill — not a link to a chat conversation.\n *\n * The hook starts empty and produces many runs over its life; each gets its\n * own `runId`, but all belong to one scope. Persistence keys on this, so\n * derive it from your own domain and keep it identical across reloads (e.g.\n * `` `video-${videoId}-start-frame` ``). It is also sent as the AG-UI thread\n * id on the wire, which the protocol requires.\n *\n * Required. A generated id would change on every reload, so persistence\n * would restore nothing.\n */\n threadId: string\n /**\n * Server-driven hydration handler for `persistence: true` when the\n * connection doesn't carry one (e.g. alongside `fetcher`, or a `stream()` /\n * `rpcStream()` adapter built without handlers) — typically a one-line\n * server-function call. The connection's own handler takes precedence.\n */\n hydrateGeneration?: ConnectConnectionAdapter['hydrateGeneration']\n /**\n * Re-attach handler that replays a run still generating to completion on\n * mount, when the connection doesn't carry one. Without it, a restored\n * `running` snapshot surfaces as an (interrupted) error. The connection's\n * own handler takes precedence.\n */\n joinRun?: ConnectConnectionAdapter['joinRun']\n /**\n * Callback when a result is received. Can optionally return a transformed value.\n *\n * - Return a non-null value to transform and store it as the result\n * - Return `null` to keep the previous result unchanged\n * - Return nothing (`void`) to store the raw result as-is\n */\n onResult?: (result: TResult) => TOutput | null | void\n /** Callback when an error occurs */\n onError?: (error: Error) => void\n /** Callback when progress is reported (0-100) */\n onProgress?: (progress: number, message?: string) => void\n /** Callback for each stream chunk (connect-based adapter mode only) */\n onChunk?: (chunk: StreamChunk) => void\n /**\n * @internal Rebuild a typed result from a restored snapshot, injected by each\n * specialized injectable (image / speech / audio / transcription / summarize).\n * Forwarded to the client so a server-hydrate restore repaints `result`.\n */\n reconstructResult?: (restored: GenerationRestoredResult) => TResult | null\n}\n\n/**\n * Return type for the injectGeneration function.\n *\n * @template TOutput - The output type (after optional transform)\n * @template TInput - The input type accepted by `generate` (defaults to any object)\n */\nexport interface InjectGenerationResult<\n TOutput,\n TInput extends Record<string, any> = Record<string, any>,\n> {\n /** Trigger a generation request */\n generate: (input: TInput) => Promise<void>\n /** The generation result, or null if not yet generated */\n result: Signal<TOutput | null>\n /** Whether a generation is currently in progress */\n isLoading: Signal<boolean>\n /** Current error, if any */\n error: Signal<Error | undefined>\n /** Current state of the generation client */\n status: Signal<GenerationClientState>\n /** Abort the current generation */\n stop: () => void\n /** Clear result, error, and return to idle */\n reset: () => void\n /** Identity of the in-flight run while one is streaming, or null after it ends */\n /**\n * The id of the generation job currently running, or `null` when nothing is in\n * flight. Each call to `generate` is one job with its own id. Pass it to your\n * own endpoint to cancel or poll the provider job — `stop()` only aborts the\n * local stream, it does not stop work already running on the provider.\n */\n runId: Signal<string | null>\n}\n\n// `TTransformed` infers from the `onResult` return position (a covariant\n// inference site that works even for an optional nested property), which types\n// the callback parameter as `TResult` and narrows `result`. Inferring the\n// whole callback as a defaulted type parameter instead collapses to the\n// default, leaving the parameter `any` — a hard error under `strict`. See\n// issue #848.\nexport function injectGeneration<\n TInput extends Record<string, any>,\n TResult,\n TTransformed = void,\n>(\n options: Omit<InjectGenerationOptions<TInput, TResult>, 'onResult'> & {\n onResult?: (result: TResult) => TTransformed\n },\n): InjectGenerationResult<\n InferGenerationOutputFromReturn<TResult, TTransformed>,\n TInput\n> {\n assertInInjectionContext(injectGeneration)\n\n type TOutput = InferGenerationOutputFromReturn<TResult, TTransformed>\n\n const destroyRef = inject(DestroyRef)\n const injector = inject(Injector)\n\n const result = signal<TOutput | null>(null)\n const isLoading = signal(false)\n const error = signal<Error | undefined>(undefined)\n const status = signal<GenerationClientState>('idle')\n const runId = signal<string | null>(null)\n let disposed = false\n\n const bodySource =\n options.body !== undefined ? toReactive(options.body) : undefined\n\n const clientOptions: GenerationClientOptions<TInput, TResult, TOutput> = {\n persistence: options.persistence,\n threadId: options.threadId,\n ...(bodySource !== undefined && { body: bodySource() }),\n ...(options.hydrateGeneration !== undefined && {\n hydrateGeneration: options.hydrateGeneration,\n }),\n ...(options.joinRun !== undefined && { joinRun: options.joinRun }),\n ...(options.byok !== undefined && { byok: options.byok }),\n byokProvider: () => options.byokProvider?.(),\n ...(options.reconstructResult\n ? { reconstructResult: options.reconstructResult }\n : {}),\n devtoolsBridgeFactory: createGenerationDevtoolsBridge,\n devtools: {\n ...options.devtools,\n framework: 'angular',\n hookName: 'injectGeneration',\n },\n // The transform's raw return type (`TTransformed`) and the stored output\n // (`TOutput`, with null/void/undefined stripped) are identical at runtime;\n // the cast bridges the relationship that the conditional type hides.\n onResult: ((r: TResult) => options.onResult?.(r)) as (\n result: TResult,\n ) => TOutput | null | void,\n onError: (e: Error) => {\n if (!disposed) options.onError?.(e)\n },\n onProgress: (p: number, m?: string) => {\n if (!disposed) options.onProgress?.(p, m)\n },\n onChunk: (c: StreamChunk) => {\n if (!disposed) options.onChunk?.(c)\n },\n }\n\n let client: GenerationClient<TInput, TResult, TOutput>\n if (options.connection) {\n client = new GenerationClient({\n ...clientOptions,\n connection: options.connection,\n })\n } else if (options.fetcher) {\n client = new GenerationClient({\n ...clientOptions,\n fetcher: options.fetcher,\n })\n } else {\n throw new Error(\n 'injectGeneration requires either a connection or fetcher option',\n )\n }\n\n const applySnapshot = () => {\n const next = client.getSnapshot()\n result.set(next.result)\n isLoading.set(next.isLoading)\n error.set(next.error)\n status.set(next.status)\n runId.set(next.runId)\n }\n applySnapshot()\n const unsubscribeSnapshot = client.subscribe(applySnapshot)\n\n if (bodySource) {\n effect(\n () => {\n client.updateOptions({\n body: bodySource(),\n })\n },\n { injector },\n )\n }\n\n // Mount devtools only. Generation runs are never auto-started after render —\n // persisted state is read-only for display.\n afterNextRender(\n () => {\n client.mountDevtools()\n },\n { injector },\n )\n destroyRef.onDestroy(() => {\n disposed = true\n unsubscribeSnapshot()\n client.dispose()\n })\n\n return {\n generate: (input: TInput) => client.generate(input),\n result: result.asReadonly(),\n isLoading: isLoading.asReadonly(),\n error: error.asReadonly(),\n status: status.asReadonly(),\n stop: () => client.stop(),\n reset: () => client.reset(),\n runId: runId.asReadonly(),\n }\n}\n","import { injectGeneration } from './inject-generation'\nimport { reconstructImageResult } from '@tanstack/ai-client'\nimport type { Signal } from '@angular/core'\nimport type { ImageGenerationResult } from '@tanstack/ai'\nimport type {\n GenerationClientState,\n ImageGenerateInput,\n InferGenerationOutputFromReturn,\n} from '@tanstack/ai-client'\nimport type {\n InjectGenerationOptions,\n InjectGenerationResult,\n} from './inject-generation'\n\nexport type InjectGenerateImageOptions<TOutput = ImageGenerationResult> = Omit<\n InjectGenerationOptions<ImageGenerateInput, ImageGenerationResult, TOutput>,\n 'onResult' | 'reconstructResult'\n> & {\n onResult?: (result: ImageGenerationResult) => TOutput | null | void\n}\n\nexport interface InjectGenerateImageResult<\n TOutput = ImageGenerationResult,\n> extends Omit<InjectGenerationResult<TOutput>, 'generate'> {\n generate: (input: ImageGenerateInput) => Promise<void>\n result: Signal<TOutput | null>\n isLoading: Signal<boolean>\n error: Signal<Error | undefined>\n status: Signal<GenerationClientState>\n}\n\nexport function injectGenerateImage<TTransformed = void>(\n options: Omit<InjectGenerateImageOptions, 'onResult'> & {\n onResult?: (result: ImageGenerationResult) => TTransformed\n },\n): InjectGenerateImageResult<\n InferGenerationOutputFromReturn<ImageGenerationResult, TTransformed>\n> {\n const devtools = {\n ...options.devtools,\n framework: 'angular' as const,\n hookName: 'injectGenerateImage',\n outputKind: 'image' as const,\n }\n const generation = injectGeneration<\n ImageGenerateInput,\n ImageGenerationResult,\n TTransformed\n >({\n ...options,\n devtools,\n reconstructResult: reconstructImageResult,\n })\n return generation\n}\n","import { injectGeneration } from './inject-generation'\nimport { reconstructAudioResult } from '@tanstack/ai-client'\nimport type { AudioGenerationResult, StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n AudioGenerateInput,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n InferGenerationOutputFromReturn,\n} from '@tanstack/ai-client'\nimport type { Signal } from '@angular/core'\nimport type { ReactiveOption } from './internal/to-reactive'\nimport type {\n InjectGenerationOptions,\n InjectGenerationResult,\n} from './inject-generation'\n\n/**\n * Options for the injectGenerateAudio injectable.\n *\n * @template TOutput - The output type after optional transform (defaults to AudioGenerationResult)\n */\nexport interface InjectGenerateAudioOptions<\n TOutput = AudioGenerationResult,\n> extends Pick<\n InjectGenerationOptions<AudioGenerateInput, AudioGenerationResult, TOutput>,\n | 'persistence'\n | 'threadId'\n | 'hydrateGeneration'\n | 'joinRun'\n | 'byok'\n | 'byokProvider'\n> {\n /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */\n connection?: ConnectConnectionAdapter\n /** Direct async function for audio generation */\n fetcher?: GenerationFetcher<AudioGenerateInput, AudioGenerationResult>\n /** Additional body parameters to send with connect-based adapter requests. Reactive. */\n body?: ReactiveOption<Record<string, any>>\n /** Display options for TanStack AI Devtools. */\n devtools?: AIDevtoolsDisplayOptions\n /**\n * Callback when audio is generated. Can optionally return a transformed value.\n *\n * - Return a non-null value to transform and store it as the result\n * - Return `null` to keep the previous result unchanged\n * - Return nothing (`void`) to store the raw result as-is\n */\n onResult?: (result: AudioGenerationResult) => TOutput | null | void\n /** Callback when an error occurs */\n onError?: (error: Error) => void\n /** Callback when progress is reported (0-100) */\n onProgress?: (progress: number, message?: string) => void\n /** Callback for each stream chunk (connect-based adapter mode only) */\n onChunk?: (chunk: StreamChunk) => void\n}\n\n/**\n * Return type for the injectGenerateAudio injectable.\n *\n * @template TOutput - The output type (after optional transform)\n */\nexport interface InjectGenerateAudioResult<\n TOutput = AudioGenerationResult,\n> extends Omit<InjectGenerationResult<TOutput>, 'generate'> {\n /** Trigger audio generation */\n generate: (input: AudioGenerateInput) => Promise<void>\n /** The generation result containing audio, or null */\n result: Signal<TOutput | null>\n /** Whether generation is in progress */\n isLoading: Signal<boolean>\n /** Current error, if any */\n error: Signal<Error | undefined>\n /** Current state of the generation */\n status: Signal<GenerationClientState>\n}\n\n/**\n * Angular injectable for generating audio (music, sound effects) using AI models.\n *\n * @example\n * ```typescript\n * import { Component } from '@angular/core'\n * import { injectGenerateAudio } from '@tanstack/ai-angular'\n * import { fetchServerSentEvents } from '@tanstack/ai-client'\n *\n * @Component({\n * selector: 'app-audio',\n * template: `\n * <button (click)=\"generate({ prompt: 'An upbeat electronic track', duration: 10 })\">\n * Generate\n * </button>\n * @if (result()) {\n * <audio [src]=\"result()!.audio.url\" controls></audio>\n * }\n * `,\n * })\n * export class AudioComponent {\n * private gen = injectGenerateAudio({\n * threadId: 'theme-audio',\n * connection: fetchServerSentEvents('/api/generate/audio'),\n * })\n *\n * generate = this.gen.generate\n * result = this.gen.result\n * isLoading = this.gen.isLoading\n * }\n * ```\n */\nexport function injectGenerateAudio<TTransformed = void>(\n options: Omit<InjectGenerateAudioOptions, 'onResult'> & {\n onResult?: (result: AudioGenerationResult) => TTransformed\n },\n): InjectGenerateAudioResult<\n InferGenerationOutputFromReturn<AudioGenerationResult, TTransformed>\n> {\n const devtools = {\n ...options.devtools,\n framework: 'angular',\n hookName: 'injectGenerateAudio',\n outputKind: 'audio' as const,\n }\n const generation = injectGeneration<\n AudioGenerateInput,\n AudioGenerationResult,\n TTransformed\n >({\n ...options,\n devtools,\n reconstructResult: reconstructAudioResult,\n })\n\n return generation\n}\n","import { injectGeneration } from './inject-generation'\nimport { reconstructSpeechResult } from '@tanstack/ai-client'\nimport type { Signal } from '@angular/core'\nimport type { TTSResult } from '@tanstack/ai'\nimport type {\n GenerationClientState,\n InferGenerationOutputFromReturn,\n SpeechGenerateInput,\n} from '@tanstack/ai-client'\nimport type {\n InjectGenerationOptions,\n InjectGenerationResult,\n} from './inject-generation'\n\nexport type InjectGenerateSpeechOptions<TOutput = TTSResult> = Omit<\n InjectGenerationOptions<SpeechGenerateInput, TTSResult, TOutput>,\n 'onResult' | 'reconstructResult'\n> & {\n onResult?: (result: TTSResult) => TOutput | null | void\n}\n\nexport interface InjectGenerateSpeechResult<TOutput = TTSResult> extends Omit<\n InjectGenerationResult<TOutput>,\n 'generate'\n> {\n generate: (input: SpeechGenerateInput) => Promise<void>\n result: Signal<TOutput | null>\n isLoading: Signal<boolean>\n error: Signal<Error | undefined>\n status: Signal<GenerationClientState>\n}\n\nexport function injectGenerateSpeech<TTransformed = void>(\n options: Omit<InjectGenerateSpeechOptions, 'onResult'> & {\n onResult?: (result: TTSResult) => TTransformed\n },\n): InjectGenerateSpeechResult<\n InferGenerationOutputFromReturn<TTSResult, TTransformed>\n> {\n const devtools = {\n ...options.devtools,\n framework: 'angular' as const,\n hookName: 'injectGenerateSpeech',\n outputKind: 'audio' as const,\n }\n const generation = injectGeneration<\n SpeechGenerateInput,\n TTSResult,\n TTransformed\n >({\n ...options,\n devtools,\n reconstructResult: reconstructSpeechResult,\n })\n return generation\n}\n","import { injectGeneration } from './inject-generation'\nimport { reconstructTranscriptionResult } from '@tanstack/ai-client'\nimport type { Signal } from '@angular/core'\nimport type { TranscriptionResult } from '@tanstack/ai'\nimport type {\n GenerationClientState,\n InferGenerationOutputFromReturn,\n TranscriptionGenerateInput,\n} from '@tanstack/ai-client'\nimport type {\n InjectGenerationOptions,\n InjectGenerationResult,\n} from './inject-generation'\n\nexport type InjectTranscriptionOptions<TOutput = TranscriptionResult> = Omit<\n InjectGenerationOptions<\n TranscriptionGenerateInput,\n TranscriptionResult,\n TOutput\n >,\n 'onResult' | 'reconstructResult'\n> & {\n onResult?: (result: TranscriptionResult) => TOutput | null | void\n}\n\nexport interface InjectTranscriptionResult<\n TOutput = TranscriptionResult,\n> extends Omit<InjectGenerationResult<TOutput>, 'generate'> {\n generate: (input: TranscriptionGenerateInput) => Promise<void>\n result: Signal<TOutput | null>\n isLoading: Signal<boolean>\n error: Signal<Error | undefined>\n status: Signal<GenerationClientState>\n}\n\nexport function injectTranscription<TTransformed = void>(\n options: Omit<InjectTranscriptionOptions, 'onResult'> & {\n onResult?: (result: TranscriptionResult) => TTransformed\n },\n): InjectTranscriptionResult<\n InferGenerationOutputFromReturn<TranscriptionResult, TTransformed>\n> {\n const devtools = {\n ...options.devtools,\n framework: 'angular' as const,\n hookName: 'injectTranscription',\n outputKind: 'text' as const,\n }\n const generation = injectGeneration<\n TranscriptionGenerateInput,\n TranscriptionResult,\n TTransformed\n >({\n ...options,\n devtools,\n reconstructResult: reconstructTranscriptionResult,\n })\n return generation\n}\n","import {\n DestroyRef,\n assertInInjectionContext,\n inject,\n signal,\n} from '@angular/core'\nimport { AudioRecorder } from '@tanstack/ai-client'\nimport type { Signal } from '@angular/core'\nimport type {\n AudioRecorderOptions,\n AudioRecording,\n InferAudioRecordingOutput,\n} from '@tanstack/ai-client'\n\nexport type InjectAudioRecorderOptions<TOnComplete> = AudioRecorderOptions & {\n /**\n * Optional transform applied to the recording when `stop()` resolves. Its\n * (awaited) return value becomes `recording` and the resolved value of\n * `stop()`. Return nothing to keep the raw `AudioRecording`.\n */\n onComplete?: TOnComplete\n}\n\nexport interface InjectAudioRecorderResult<TOutput> {\n /** Reactive: latest recording (transformed if `onComplete` provided), or null. */\n recording: Signal<TOutput | null>\n /** Reactive: true while actively capturing audio. */\n isRecording: Signal<boolean>\n /** Whether the browser supports recording. */\n isSupported: boolean\n start: () => Promise<void>\n /** Stop and resolve with the completed recording (transformed if `onComplete` provided). */\n stop: () => Promise<TOutput>\n /** Discard the in-progress recording and release the mic. */\n cancel: () => void\n}\n\n/**\n * Angular injectable for recording an audio message. The resolved recording\n * carries `.part` (for `injectChat`'s `sendMessage`) and `.base64` (for the\n * generation injectables). Must be called in an injection context.\n *\n * Errors are delivered via `onError`. `start()` and `stop()` also reject on\n * failure (and `stop()` rejects with `Recording cancelled` if `cancel()` runs\n * while a stop is in flight, e.g. on destroy) — handle one channel, not both.\n */\n// The transforming overload requires `onComplete`. Without that constraint an\n// options object carrying only unrelated keys (`injectAudioRecorder({ onError })`)\n// still matches it, `TOnComplete` infers as `unknown`, and `recording`/`stop()`\n// collapse to `unknown` — so passing any option would silently cost you the\n// `AudioRecording` type. Requiring it here sends those calls to the second\n// overload instead (issue #1001).\nexport function injectAudioRecorder<\n TOnComplete extends (recording: AudioRecording) => unknown,\n>(\n options: InjectAudioRecorderOptions<TOnComplete> & {\n onComplete: TOnComplete\n },\n): InjectAudioRecorderResult<InferAudioRecordingOutput<TOnComplete>>\nexport function injectAudioRecorder(\n options?: InjectAudioRecorderOptions<undefined>,\n): InjectAudioRecorderResult<AudioRecording>\nexport function injectAudioRecorder(\n options: InjectAudioRecorderOptions<\n (recording: AudioRecording) => unknown\n > = {},\n): InjectAudioRecorderResult<unknown> {\n assertInInjectionContext(injectAudioRecorder)\n const destroyRef = inject(DestroyRef)\n const recorder = new AudioRecorder({\n ...(options.audio !== undefined && { audio: options.audio }),\n ...(options.mimeType !== undefined && { mimeType: options.mimeType }),\n ...(options.onError !== undefined && { onError: options.onError }),\n })\n const isRecording = signal(false)\n const recording = signal<unknown>(null)\n\n const unsubscribe = recorder.subscribe((state) => {\n isRecording.set(state === 'recording')\n })\n destroyRef.onDestroy(() => {\n unsubscribe()\n recorder.cancel()\n })\n\n const stop = async (): Promise<unknown> => {\n const rawRecording = await recorder.stop()\n const transformed = await options.onComplete?.(rawRecording)\n // Only `undefined` (returning nothing) keeps the raw recording; a returned\n // null is a real value, matching the inferred output type.\n const output = transformed === undefined ? rawRecording : transformed\n recording.set(output)\n return output\n }\n\n return {\n recording: recording.asReadonly(),\n isRecording: isRecording.asReadonly(),\n isSupported: AudioRecorder.isSupported(),\n start: () => recorder.start(),\n stop,\n cancel: () => recorder.cancel(),\n }\n}\n","import { injectGeneration } from './inject-generation'\nimport { reconstructSummarizeResult } from '@tanstack/ai-client'\nimport type { Signal } from '@angular/core'\nimport type { SummarizationResult } from '@tanstack/ai'\nimport type {\n GenerationClientState,\n InferGenerationOutputFromReturn,\n SummarizeGenerateInput,\n} from '@tanstack/ai-client'\nimport type {\n InjectGenerationOptions,\n InjectGenerationResult,\n} from './inject-generation'\n\nexport type InjectSummarizeOptions<TOutput = SummarizationResult> = Omit<\n InjectGenerationOptions<SummarizeGenerateInput, SummarizationResult, TOutput>,\n 'onResult' | 'reconstructResult'\n> & {\n onResult?: (result: SummarizationResult) => TOutput | null | void\n}\n\nexport interface InjectSummarizeResult<\n TOutput = SummarizationResult,\n> extends Omit<InjectGenerationResult<TOutput>, 'generate'> {\n generate: (input: SummarizeGenerateInput) => Promise<void>\n result: Signal<TOutput | null>\n isLoading: Signal<boolean>\n error: Signal<Error | undefined>\n status: Signal<GenerationClientState>\n}\n\nexport function injectSummarize<TTransformed = void>(\n options: Omit<InjectSummarizeOptions, 'onResult'> & {\n onResult?: (result: SummarizationResult) => TTransformed\n },\n): InjectSummarizeResult<\n InferGenerationOutputFromReturn<SummarizationResult, TTransformed>\n> {\n const devtools = {\n ...options.devtools,\n framework: 'angular' as const,\n hookName: 'injectSummarize',\n outputKind: 'text' as const,\n }\n const generation = injectGeneration<\n SummarizeGenerateInput,\n SummarizationResult,\n TTransformed\n >({\n ...options,\n devtools,\n reconstructResult: reconstructSummarizeResult,\n })\n return generation\n}\n","import { VideoGenerationClient } from '@tanstack/ai-client'\nimport { createVideoDevtoolsBridge } from '@tanstack/ai-client/devtools'\nimport {\n DestroyRef,\n Injector,\n afterNextRender,\n assertInInjectionContext,\n effect,\n inject,\n signal,\n} from '@angular/core'\nimport { toReactive } from './internal/to-reactive'\nimport type { Signal } from '@angular/core'\nimport type { ReactiveOption } from './internal/to-reactive'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n InferGenerationOutputFromReturn,\n VideoGenerateInput,\n VideoGenerateResult,\n VideoStatusInfo,\n} from '@tanstack/ai-client'\nimport type { ByokClient } from '@tanstack/ai-client/byok'\nimport type { ProviderId } from '@tanstack/ai/byok'\nimport type { StreamChunk } from '@tanstack/ai'\n\nexport interface InjectGenerateVideoOptions<TOutput = VideoGenerateResult> {\n connection?: ConnectConnectionAdapter\n fetcher?: GenerationFetcher<VideoGenerateInput, VideoGenerateResult>\n body?: ReactiveOption<Record<string, any>>\n /** Optional BYOK keyring. Keys go in `x-byok-*` headers, never the body. */\n byok?: ByokClient\n /** Optional provider id. If it returns a slug, only that key is sent. If no slug resolves (`byokProvider`, then `body.provider`), generate throws. */\n byokProvider?: () => ProviderId | undefined\n devtools?: AIDevtoolsDisplayOptions\n /**\n * How this generation persists across reloads.\n * - Omit / `false`: ephemeral, in-memory only.\n * - `true`: server-driven — on mount the client hydrates the last generation\n * for its `threadId` from the server (needs a connection with a\n * `hydrateGeneration` handler) and repaints it; it never auto-starts a run.\n */\n persistence?: boolean\n /**\n * The **scope** this generation belongs to: a stable, app-chosen name for the\n * slot successive runs fill — not a link to a chat conversation.\n *\n * The hook starts empty and produces many runs over its life; each gets its\n * own `runId`, but all belong to one scope. Persistence keys on this, so\n * derive it from your own domain and keep it identical across reloads (e.g.\n * `` `video-${videoId}-start-frame` ``). It is also sent as the AG-UI thread\n * id on the wire, which the protocol requires.\n *\n * Required. A generated id would change on every reload, so persistence\n * would restore nothing.\n */\n threadId: string\n /**\n * Server-driven hydration handler for `persistence: true` when the\n * connection doesn't carry one (e.g. alongside `fetcher`, or a `stream()` /\n * `rpcStream()` adapter built without handlers) — typically a one-line\n * server-function call. The connection's own handler takes precedence.\n */\n hydrateGeneration?: ConnectConnectionAdapter['hydrateGeneration']\n /**\n * Re-attach handler that replays a run still generating to completion on\n * mount, when the connection doesn't carry one. Without it, a restored\n * `running` snapshot surfaces as an (interrupted) error. The connection's\n * own handler takes precedence.\n */\n joinRun?: ConnectConnectionAdapter['joinRun']\n onResult?: (result: VideoGenerateResult) => TOutput | null | void\n onError?: (error: Error) => void\n onProgress?: (progress: number, message?: string) => void\n onJobCreated?: (jobId: string) => void\n onStatusUpdate?: (status: VideoStatusInfo) => void\n onChunk?: (chunk: StreamChunk) => void\n}\n\nexport interface InjectGenerateVideoResult<TOutput = VideoGenerateResult> {\n generate: (input: VideoGenerateInput) => Promise<void>\n result: Signal<TOutput | null>\n jobId: Signal<string | null>\n videoStatus: Signal<VideoStatusInfo | null>\n isLoading: Signal<boolean>\n error: Signal<Error | undefined>\n status: Signal<GenerationClientState>\n stop: () => void\n reset: () => void\n /**\n * The id of the generation job currently running, or `null` when nothing is in\n * flight. Each call to `generate` is one job with its own id. Pass it to your\n * own endpoint to cancel or poll the provider job — `stop()` only aborts the\n * local stream, it does not stop work already running on the provider.\n */\n runId: Signal<string | null>\n}\n\n// `TTransformed` infers from the `onResult` return position so the callback\n// parameter is typed as `VideoGenerateResult` and `result` narrows to the\n// transform's return. See issue #848.\nexport function injectGenerateVideo<TTransformed = void>(\n options: Omit<InjectGenerateVideoOptions, 'onResult'> & {\n onResult?: (result: VideoGenerateResult) => TTransformed\n },\n): InjectGenerateVideoResult<\n InferGenerationOutputFromReturn<VideoGenerateResult, TTransformed>\n> {\n assertInInjectionContext(injectGenerateVideo)\n\n type TOutput = InferGenerationOutputFromReturn<\n VideoGenerateResult,\n TTransformed\n >\n\n const destroyRef = inject(DestroyRef)\n const injector = inject(Injector)\n\n const result = signal<TOutput | null>(null)\n const jobId = signal<string | null>(null)\n const videoStatus = signal<VideoStatusInfo | null>(null)\n const isLoading = signal(false)\n const error = signal<Error | undefined>(undefined)\n const status = signal<GenerationClientState>('idle')\n const runId = signal<string | null>(null)\n let disposed = false\n\n const bodySource =\n options.body !== undefined ? toReactive(options.body) : undefined\n\n const baseOptions = {\n ...(bodySource !== undefined && { body: bodySource() }),\n persistence: options.persistence,\n threadId: options.threadId,\n ...(options.hydrateGeneration !== undefined && {\n hydrateGeneration: options.hydrateGeneration,\n }),\n ...(options.joinRun !== undefined && { joinRun: options.joinRun }),\n ...(options.byok !== undefined && { byok: options.byok }),\n byokProvider: () => options.byokProvider?.(),\n devtoolsBridgeFactory: createVideoDevtoolsBridge,\n devtools: {\n ...options.devtools,\n framework: 'angular',\n hookName: 'injectGenerateVideo',\n outputKind: 'video' as const,\n },\n // The transform's raw return type (`TTransformed`) and the stored output\n // (`TOutput`, with null/void/undefined stripped) are identical at runtime;\n // the cast bridges the relationship that the conditional type hides.\n onResult: ((r: VideoGenerateResult) => options.onResult?.(r)) as (\n result: VideoGenerateResult,\n ) => TOutput | null | void,\n onError: (e: Error) => {\n if (!disposed) options.onError?.(e)\n },\n onProgress: (p: number, m?: string) => {\n if (!disposed) options.onProgress?.(p, m)\n },\n onChunk: (c: StreamChunk) => {\n if (!disposed) options.onChunk?.(c)\n },\n onJobCreated: (id: string) => {\n if (!disposed) options.onJobCreated?.(id)\n },\n onStatusUpdate: (s: VideoStatusInfo) => {\n if (!disposed) options.onStatusUpdate?.(s)\n },\n }\n\n let client: VideoGenerationClient<TOutput>\n if (options.connection) {\n client = new VideoGenerationClient({\n ...baseOptions,\n connection: options.connection,\n })\n } else if (options.fetcher) {\n client = new VideoGenerationClient({\n ...baseOptions,\n fetcher: options.fetcher,\n })\n } else {\n throw new Error(\n 'injectGenerateVideo requires either a connection or fetcher option',\n )\n }\n\n const applySnapshot = () => {\n const next = client.getSnapshot()\n result.set(next.result)\n isLoading.set(next.isLoading)\n error.set(next.error)\n status.set(next.status)\n runId.set(next.runId)\n jobId.set(next.jobId)\n videoStatus.set(next.videoStatus)\n }\n applySnapshot()\n const unsubscribeSnapshot = client.subscribe(applySnapshot)\n\n if (bodySource) {\n effect(\n () => {\n client.updateOptions({\n body: bodySource(),\n })\n },\n { injector },\n )\n }\n\n // Mount devtools only. Generation runs are never auto-started after render —\n // persisted state is read-only for display.\n afterNextRender(\n () => {\n client.mountDevtools()\n },\n { injector },\n )\n destroyRef.onDestroy(() => {\n disposed = true\n unsubscribeSnapshot()\n client.dispose()\n })\n\n return {\n generate: (input: VideoGenerateInput) => client.generate(input),\n result: result.asReadonly(),\n jobId: jobId.asReadonly(),\n videoStatus: videoStatus.asReadonly(),\n isLoading: isLoading.asReadonly(),\n error: error.asReadonly(),\n status: status.asReadonly(),\n stop: () => client.stop(),\n reset: () => client.reset(),\n runId: runId.asReadonly(),\n }\n}\n"],"mappings":";;;AAiBA,SAAgB,WAAc,OAAwB;CACpD,IAAI,SAAS,KAAK,GAChB,OAAO;CAET,IAAI,OAAO,UAAU,YACnB,OAAO,SAAS,KAAgB;CAElC,aAAa;AACf;ACYA,SAAgB,WAQd,SAAkE;CAElE,yBAAyB,UAAU;CAKnC,MAAM,aAAa,OAAO,UAAU;CACpC,MAAM,WAAW,OAAO,QAAQ;CAGhC,MAAM,uBACJ,QAAQ,mBAAmB,SACvB,WAAW,QAAQ,cAAc,IACjC;CACN,MAAM,gBACJ,QAAQ,YAAY,SAAY,WAAW,QAAQ,OAAO,IAAI;CAChE,MAAM,aACJ,QAAQ,SAAS,SAAY,WAAW,QAAQ,IAAI,IAAI;CAC1D,MAAM,cACJ,QAAQ,UAAU,SAAY,WAAW,QAAQ,KAAK,IAAI;CAE5D,MAAM,YAAY,QAAQ,aACtB,EAAE,YAAY,QAAQ,WAAU,IAChC,EAAE,SAAS,QAAQ,QAAO;CAE9B,MAAM,SAAS,IAAI,aAA0C;EAC3D,uBAAuB;EACvB,GAAG;EACH,GAAI,QAAQ,oBAAoB,UAAa,EAC3C,iBAAiB,QAAQ,gBAC1B;EACD,UAAU,QAAQ;EAClB,GAAI,QAAQ,gBAAgB,OAC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U;EAC/B,OAAO,MAAM,WAAU;EACvB,QAAQ,OAAO,WAAU;EACzB,YAAY,OAAO,KAAI;EACvB,aAAa,OAAO,MAAK;EACzB,OAAO,MAAM,WAAU;CACxB;AACH"}
1
+ {"version":3,"file":"tanstack-ai-angular.mjs","names":["ChatClient","registerWebMCPTools","GenerationClient","reconstructImageResult","reconstructAudioResult","reconstructSpeechResult","reconstructTranscriptionResult","AudioRecorder","reconstructSummarizeResult","VideoGenerationClient"],"sources":["../../src/internal/to-reactive.ts","../../src/inject-chat.ts","../../src/inject-byok.ts","../../src/inject-web-mcp-tools.ts","../../src/inject-generation.ts","../../src/inject-generate-image.ts","../../src/inject-generate-3d-model.ts","../../src/inject-generate-audio.ts","../../src/inject-generate-speech.ts","../../src/inject-transcription.ts","../../src/inject-audio-recorder.ts","../../src/inject-summarize.ts","../../src/inject-generate-video.ts"],"sourcesContent":["import { computed, isSignal } from '@angular/core'\nimport type { Signal } from '@angular/core'\n\n/**\n * A value that may be supplied to `injectChat` either as a static value, an\n * Angular `Signal`, or a zero-arg getter. The getter form lets callers read\n * other signals so the option stays reactive.\n */\nexport type ReactiveOption<T> = T | Signal<T> | (() => T)\n\n/**\n * Normalize a {@link ReactiveOption} into a `Signal`-like getter `() => T`.\n *\n * - A `Signal` is returned as-is (already a getter that tracks reads).\n * - A zero-arg function is wrapped in `computed` so reads inside it are tracked.\n * - A plain value becomes a constant non-reactive fn (never re-fires).\n */\nexport function toReactive<T>(value: ReactiveOption<T>): () => T {\n if (isSignal(value)) {\n return value\n }\n if (typeof value === 'function') {\n return computed(value as () => T)\n }\n return () => value\n}\n","import { ChatClient } from '@tanstack/ai-client'\nimport { createChatDevtoolsBridge } from '@tanstack/ai-client/devtools'\nimport {\n DestroyRef,\n Injector,\n afterNextRender,\n assertInInjectionContext,\n computed,\n effect,\n inject,\n signal,\n} from '@angular/core'\nimport { toReactive } from './internal/to-reactive'\nimport type {\n AnyClientTool,\n InterruptDefinition,\n InferSchemaType,\n ModelMessage,\n RunAgentResumeItem,\n SchemaInput,\n StreamChunk,\n} from '@tanstack/ai'\nimport type {\n ResolvableChatInterrupt,\n ChatResumeState,\n InferredClientContext,\n SendMessageOptions,\n StructuredOutputPart,\n} from '@tanstack/ai-client'\nimport type {\n DeepPartial,\n InjectChatOptions,\n InjectChatResult,\n MultimodalContent,\n UIMessage,\n} from './types'\n\nexport function injectChat<\n const TTools extends ReadonlyArray<AnyClientTool> = any,\n TSchema extends SchemaInput | undefined = undefined,\n TContext = InferredClientContext<TTools>,\n const TInterrupts extends ReadonlyArray<\n InterruptDefinition<any, any, any, any>\n > = readonly [],\n>(\n options: InjectChatOptions<TTools, TSchema, TContext, TInterrupts>,\n): InjectChatResult<TTools, TSchema, TInterrupts> {\n assertInInjectionContext(injectChat)\n\n type Partial = DeepPartial<InferSchemaType<NonNullable<TSchema>>>\n type Final = InferSchemaType<NonNullable<TSchema>>\n\n const destroyRef = inject(DestroyRef)\n const injector = inject(Injector)\n\n // Reactive option sources. Plain values become constant computeds.\n const forwardedPropsSource =\n options.forwardedProps !== undefined\n ? toReactive(options.forwardedProps)\n : undefined\n const contextSource =\n options.context !== undefined ? toReactive(options.context) : undefined\n const liveSource =\n options.live !== undefined ? toReactive(options.live) : undefined\n const toolsSource =\n options.tools !== undefined ? toReactive(options.tools) : undefined\n\n const transport = options.connection\n ? { connection: options.connection }\n : { fetcher: options.fetcher }\n\n const client = new ChatClient<TTools, TContext, TInterrupts>({\n devtoolsBridgeFactory: createChatDevtoolsBridge,\n ...transport,\n ...(options.initialMessages !== undefined && {\n initialMessages: options.initialMessages,\n }),\n threadId: options.threadId,\n ...(options.persistence === true\n ? {\n persistence: true,\n ...(options.history !== undefined && {\n history: options.history,\n }),\n }\n : { persistence: options.persistence }),\n ...(options.initialResumeSnapshot !== undefined && {\n initialResumeSnapshot: options.initialResumeSnapshot,\n }),\n ...(forwardedPropsSource !== undefined && {\n forwardedProps: forwardedPropsSource(),\n }),\n ...(options.byok !== undefined && { byok: options.byok }),\n byokProvider: () => options.byokProvider?.(),\n ...(contextSource !== undefined && { context: contextSource() }),\n devtools: {\n ...options.devtools,\n framework: 'angular',\n hookName: 'injectChat',\n outputKind: options.outputSchema ? 'structured' : 'chat',\n },\n onResponse: (response) => options.onResponse?.(response),\n onChunk: (chunk: StreamChunk) => options.onChunk?.(chunk),\n onFinish: (message) => options.onFinish?.(message),\n onError: (err) => options.onError?.(err),\n onInterruptStateChange: (nextInterruptState, context) => {\n options.onInterruptStateChange?.(nextInterruptState, context)\n },\n tools: toolsSource?.(),\n ...(options.interrupts !== undefined && {\n interrupts: options.interrupts,\n }),\n onCustomEvent: (eventType, data, context) =>\n options.onCustomEvent?.(eventType, data, context),\n ...(options.streamProcessor !== undefined && {\n streamProcessor: options.streamProcessor,\n }),\n ...(options.queue !== undefined && { queue: options.queue }),\n })\n\n const snapshot = signal(client.getSnapshot())\n const messages = computed(() => snapshot().messages)\n const interruptState = computed(() => snapshot().interruptState)\n const unsubscribeSnapshot = client.subscribeSnapshot(() =>\n snapshot.set(client.getSnapshot()),\n )\n\n // START TAILING HERE, not in the constructor. A client is idle until something\n // attaches it, so a client that gets built and thrown away never opens a\n // connection — an unreachable stream would hold one of the browser's ~6\n // connections per origin until the page reloaded. `inject*` runs in an injection\n // context tied to the consumer's lifetime, and `destroyRef.onDestroy` below is the\n // matching `detach`.\n client.attach()\n\n // Sync reactive forwardedProps / context to the client.\n if (forwardedPropsSource || contextSource) {\n effect(\n () => {\n const newForwardedProps = forwardedPropsSource?.()\n const newContext = contextSource?.()\n client.updateOptions({\n ...(newForwardedProps !== undefined && {\n forwardedProps: newForwardedProps,\n }),\n ...(newContext !== undefined && { context: newContext }),\n })\n },\n { injector },\n )\n }\n\n // Sync reactive tools to the client.\n if (toolsSource) {\n effect(() => client.updateOptions({ tools: toolsSource() }), { injector })\n }\n\n // Subscribe / unsubscribe based on reactive `live`.\n if (liveSource) {\n effect(\n () => {\n if (liveSource()) {\n client.subscribe()\n } else {\n client.unsubscribe()\n }\n },\n { injector },\n )\n }\n\n afterNextRender(\n () => {\n client.mountDevtools()\n // Delivery-durability resume is transparent: the resumable SSE\n // connection adapter reattaches via the browser's native Last-Event-ID\n // on reconnect. No client-side auto-resume wiring is needed.\n },\n { injector },\n )\n\n destroyRef.onDestroy(() => {\n unsubscribeSnapshot()\n // Release the connection first: the counterpart of the `attach` above.\n client.detach()\n if (liveSource?.()) {\n client.unsubscribe()\n } else {\n client.stop()\n }\n client.dispose()\n })\n\n // Active structured-output part = the one on the assistant message after the\n // latest user message. Ported from ai-vue/src/use-chat.ts.\n const activeStructuredPart = computed<StructuredOutputPart | null>(() => {\n const list = messages()\n let lastUserIndex = -1\n for (let i = list.length - 1; i >= 0; i--) {\n if (list[i]?.role === 'user') {\n lastUserIndex = i\n break\n }\n }\n if (lastUserIndex === -1) return null\n for (let i = list.length - 1; i > lastUserIndex; i--) {\n const m = list[i]\n if (m?.role !== 'assistant') continue\n const part = m.parts.find(\n (p): p is StructuredOutputPart => p.type === 'structured-output',\n )\n if (part) return part\n }\n return null\n })\n\n const partial = computed<Partial>(() => {\n const part = activeStructuredPart()\n if (!part) return {} as Partial\n const v = part.partial ?? part.data\n return (v ?? {}) as Partial\n })\n\n const final = computed<Final | null>(() => {\n const part = activeStructuredPart()\n if (!part || part.status !== 'complete') return null\n return part.data as Final\n })\n\n const sendMessage = async (\n content: string | MultimodalContent,\n sendOptions?: SendMessageOptions,\n ) => {\n await client.sendMessage(content, undefined, sendOptions)\n }\n const cancelQueued = (id: string) => client.cancelQueued(id)\n const append = async (message: ModelMessage | UIMessage<TTools>) => {\n await client.append(message)\n }\n const reload = async () => {\n await client.reload()\n }\n const loadOlderMessages = async () => {\n await client.loadOlderMessages()\n }\n const stop = () => client.stop()\n const clear = () => client.clear()\n const setMessages = (m: ReadonlyArray<UIMessage<TTools>>) =>\n client.setMessagesManually(m)\n const addToolResult = async (result: {\n toolCallId: string\n tool: string\n output: any\n state?: 'output-available' | 'output-error'\n errorText?: string\n }) => {\n await client.addToolResult(result)\n }\n const interrupts = computed(() => interruptState().interrupts)\n const interruptErrors = computed(() => interruptState().interruptErrors)\n const resuming = computed(() => interruptState().resuming)\n const resolveInterrupts = (\n resolution:\n | boolean\n | ((\n interrupt: ResolvableChatInterrupt<TTools, TInterrupts>,\n ) => undefined),\n ) => {\n if (typeof resolution === 'boolean') {\n client.resolveInterrupts(resolution)\n } else {\n client.resolveInterrupts(resolution)\n }\n }\n const cancelInterrupts = () => client.cancelInterrupts()\n const retryInterrupts = () => client.retryInterrupts()\n const resumeInterruptsUnsafe = (\n resumeItems: Array<RunAgentResumeItem>,\n state?: ChatResumeState,\n ) => client.resumeInterruptsUnsafe(resumeItems, state)\n\n // oxlint-disable-next-line eslint-js/no-restricted-syntax -- return shape diverges from conditional InjectChatResult<TTools, TSchema>; TS can't structurally narrow the TSchema-gated partial/final signals\n return {\n messages,\n sendMessage,\n queue: computed(() => snapshot().queue),\n cancelQueued,\n append,\n reload,\n stop,\n isLoading: computed(() => snapshot().isLoading),\n hasOlderMessages: computed(() => snapshot().hasOlderMessages),\n loadOlderMessages,\n error: computed(() => snapshot().error),\n status: computed(() => snapshot().status),\n isSubscribed: computed(() => snapshot().isSubscribed),\n connectionStatus: computed(() => snapshot().connectionStatus),\n sessionGenerating: computed(() => snapshot().sessionGenerating),\n isHydrating: computed(() => snapshot().isHydrating),\n setMessages,\n clear,\n addToolResult,\n runId: computed(() => snapshot().runId),\n interrupts,\n interruptErrors,\n resuming,\n resolveInterrupts,\n cancelInterrupts,\n retryInterrupts,\n resumeInterruptsUnsafe,\n partial,\n final,\n } as unknown as InjectChatResult<TTools, TSchema, TInterrupts>\n}\n","import {\n DestroyRef,\n assertInInjectionContext,\n inject,\n signal,\n} from '@angular/core'\nimport type { Signal } from '@angular/core'\nimport type { ByokClient, ByokSnapshot } from '@tanstack/ai-client/byok'\n\nexport function injectByok(client: ByokClient): Signal<ByokSnapshot> {\n assertInInjectionContext(injectByok)\n const destroyRef = inject(DestroyRef)\n const snapshot = signal(client.getSnapshot())\n const unsubscribe = client.subscribe(() => {\n snapshot.set(client.getSnapshot())\n })\n destroyRef.onDestroy(unsubscribe)\n return snapshot.asReadonly()\n}\n","import {\n DestroyRef,\n assertInInjectionContext,\n inject,\n signal,\n} from '@angular/core'\nimport { registerWebMCPTools, subscribeWebMCPTools } from '@tanstack/ai-client'\nimport type { Signal } from '@angular/core'\nimport type {\n AnyClientTool,\n InferredClientContext,\n RegisterWebMCPToolsOptions,\n SubscribeWebMCPToolsOptions,\n} from '@tanstack/ai-client'\n\n/**\n * Options for {@link injectRegisterWebMCPTools}.\n *\n * Context is required when a client tool declares a required runtime context.\n */\nexport type InjectRegisterWebMCPToolsOptions<\n TTools extends ReadonlyArray<AnyClientTool>,\n TContext = InferredClientContext<TTools>,\n> = Omit<RegisterWebMCPToolsOptions<TTools, TContext>, 'signal'> & {\n /** Receives asynchronous WebMCP registration errors. */\n onError?: (error: unknown) => void\n}\n\n/**\n * Registers executable client tools with WebMCP for the current Angular owner.\n *\n * Angular removes the registrations when it destroys the injection owner. Call\n * this function in an injection context, such as a component field initializer.\n *\n * @param tools - The executable client tools to expose through WebMCP.\n * @param options - Runtime context, per-tool options, and error handling.\n *\n * @example\n * ```ts\n * registration = injectRegisterWebMCPTools([statusTool], {\n * onError: (error) => console.error(error),\n * })\n * ```\n */\nexport function injectRegisterWebMCPTools<\n const TTools extends ReadonlyArray<AnyClientTool>,\n TContext = InferredClientContext<TTools>,\n>(\n tools: TTools,\n ...[options]: {} extends InjectRegisterWebMCPToolsOptions<TTools, TContext>\n ? [options?: InjectRegisterWebMCPToolsOptions<TTools, TContext>]\n : [options: InjectRegisterWebMCPToolsOptions<TTools, TContext>]\n) {\n assertInInjectionContext(injectRegisterWebMCPTools)\n const destroyRef = inject(DestroyRef)\n const registrationController = new AbortController()\n const { onError, ...registrationOptions } = options ?? {}\n\n destroyRef.onDestroy(() => registrationController.abort())\n\n void registerWebMCPTools(tools, {\n ...registrationOptions,\n signal: registrationController.signal,\n }).catch((error) => {\n if (!registrationController.signal.aborted) {\n onError?.(error)\n }\n })\n}\n\n/** Options for {@link injectPageWebMCPTools}. */\nexport type InjectPageWebMCPToolsOptions = Omit<\n SubscribeWebMCPToolsOptions,\n 'signal'\n>\n\n/**\n * Returns the WebMCP tools on the page as client tools for `injectChat`.\n *\n * The signal starts empty and updates when the page registers or removes a\n * tool. Angular stops the updates when it destroys the injection owner. Call\n * this function in an injection context.\n *\n * @param options - A filter that skips tools, and an error callback.\n *\n * @example\n * ```ts\n * pageTools = injectPageWebMCPTools({\n * filter: (tool) => tool.origin === location.origin,\n * })\n * chat = injectChat({ threadId: 'support-1', connection, tools: this.pageTools })\n * ```\n */\nexport function injectPageWebMCPTools(\n options?: InjectPageWebMCPToolsOptions,\n): Signal<Array<AnyClientTool>> {\n assertInInjectionContext(injectPageWebMCPTools)\n const destroyRef = inject(DestroyRef)\n const tools = signal<Array<AnyClientTool>>([])\n const controller = new AbortController()\n\n destroyRef.onDestroy(() => controller.abort())\n\n subscribeWebMCPTools((nextTools) => tools.set(nextTools), {\n signal: controller.signal,\n filter: (tool) => options?.filter?.(tool) ?? true,\n onError: (error) => options?.onError?.(error),\n })\n\n return tools.asReadonly()\n}\n","import { GenerationClient } from '@tanstack/ai-client'\nimport { createGenerationDevtoolsBridge } from '@tanstack/ai-client/devtools'\nimport {\n DestroyRef,\n Injector,\n afterNextRender,\n assertInInjectionContext,\n effect,\n inject,\n signal,\n} from '@angular/core'\nimport { toReactive } from './internal/to-reactive'\nimport type { Signal } from '@angular/core'\nimport type { StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientOptions,\n GenerationClientState,\n GenerationFetcher,\n GenerationRestoredResult,\n InferGenerationOutputFromReturn,\n} from '@tanstack/ai-client'\nimport type { ByokClient } from '@tanstack/ai-client/byok'\nimport type { ProviderId } from '@tanstack/ai/byok'\nimport type { ReactiveOption } from './internal/to-reactive'\n\nexport interface InjectGenerationOptions<TInput, TResult, TOutput = TResult> {\n /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */\n connection?: ConnectConnectionAdapter\n /** Direct async function for one-shot generation (no streaming protocol needed) */\n fetcher?: GenerationFetcher<TInput, TResult>\n /** Additional request body params. Reactive. */\n body?: ReactiveOption<Record<string, any>>\n /** Optional BYOK keyring. Keys go in `x-byok-*` headers, never the body. */\n byok?: ByokClient\n /** Optional provider id. If it returns a slug, only that key is sent. If no slug resolves (`byokProvider`, then `body.provider`), generate throws. */\n byokProvider?: () => ProviderId | undefined\n /** Display options for TanStack AI Devtools. */\n devtools?: AIDevtoolsDisplayOptions\n /**\n * How this generation persists across reloads.\n * - Omit / `false`: ephemeral, in-memory only.\n * - `true`: server-driven — on mount the client hydrates the last generation\n * for its `threadId` from the server (needs a connection with a\n * `hydrateGeneration` handler) and repaints it; it never auto-starts a run.\n */\n persistence?: boolean\n /**\n * The **scope** this generation belongs to: a stable, app-chosen name for the\n * slot successive runs fill — not a link to a chat conversation.\n *\n * The hook starts empty and produces many runs over its life; each gets its\n * own `runId`, but all belong to one scope. Persistence keys on this, so\n * derive it from your own domain and keep it identical across reloads (e.g.\n * `` `video-${videoId}-start-frame` ``). It is also sent as the AG-UI thread\n * id on the wire, which the protocol requires.\n *\n * Required. A generated id would change on every reload, so persistence\n * would restore nothing.\n */\n threadId: string\n /**\n * Server-driven hydration handler for `persistence: true` when the\n * connection doesn't carry one (e.g. alongside `fetcher`, or a `stream()` /\n * `rpcStream()` adapter built without handlers) — typically a one-line\n * server-function call. The connection's own handler takes precedence.\n */\n hydrateGeneration?: ConnectConnectionAdapter['hydrateGeneration']\n /**\n * Re-attach handler that replays a run still generating to completion on\n * mount, when the connection doesn't carry one. Without it, a restored\n * `running` snapshot surfaces as an (interrupted) error. The connection's\n * own handler takes precedence.\n */\n joinRun?: ConnectConnectionAdapter['joinRun']\n /**\n * Callback when a result is received. Can optionally return a transformed value.\n *\n * - Return a non-null value to transform and store it as the result\n * - Return `null` to keep the previous result unchanged\n * - Return nothing (`void`) to store the raw result as-is\n */\n onResult?: (result: TResult) => TOutput | null | void\n /** Callback when an error occurs */\n onError?: (error: Error) => void\n /** Callback when progress is reported (0-100) */\n onProgress?: (progress: number, message?: string) => void\n /** Callback for each stream chunk (connect-based adapter mode only) */\n onChunk?: (chunk: StreamChunk) => void\n /**\n * @internal Rebuild a typed result from a restored snapshot, injected by each\n * specialized injectable (image / speech / audio / transcription / summarize).\n * Forwarded to the client so a server-hydrate restore repaints `result`.\n */\n reconstructResult?: (restored: GenerationRestoredResult) => TResult | null\n}\n\n/**\n * Return type for the injectGeneration function.\n *\n * @template TOutput - The output type (after optional transform)\n * @template TInput - The input type accepted by `generate` (defaults to any object)\n */\nexport interface InjectGenerationResult<\n TOutput,\n TInput extends Record<string, any> = Record<string, any>,\n> {\n /** Trigger a generation request */\n generate: (input: TInput) => Promise<void>\n /** The generation result, or null if not yet generated */\n result: Signal<TOutput | null>\n /** Whether a generation is currently in progress */\n isLoading: Signal<boolean>\n /** Current error, if any */\n error: Signal<Error | undefined>\n /** Current state of the generation client */\n status: Signal<GenerationClientState>\n /** Abort the current generation */\n stop: () => void\n /** Clear result, error, and return to idle */\n reset: () => void\n /** Identity of the in-flight run while one is streaming, or null after it ends */\n /**\n * The id of the generation job currently running, or `null` when nothing is in\n * flight. Each call to `generate` is one job with its own id. Pass it to your\n * own endpoint to cancel or poll the provider job — `stop()` only aborts the\n * local stream, it does not stop work already running on the provider.\n */\n runId: Signal<string | null>\n}\n\n// `TTransformed` infers from the `onResult` return position (a covariant\n// inference site that works even for an optional nested property), which types\n// the callback parameter as `TResult` and narrows `result`. Inferring the\n// whole callback as a defaulted type parameter instead collapses to the\n// default, leaving the parameter `any` — a hard error under `strict`. See\n// issue #848.\nexport function injectGeneration<\n TInput extends Record<string, any>,\n TResult,\n TTransformed = void,\n>(\n options: Omit<InjectGenerationOptions<TInput, TResult>, 'onResult'> & {\n onResult?: (result: TResult) => TTransformed\n },\n): InjectGenerationResult<\n InferGenerationOutputFromReturn<TResult, TTransformed>,\n TInput\n> {\n assertInInjectionContext(injectGeneration)\n\n type TOutput = InferGenerationOutputFromReturn<TResult, TTransformed>\n\n const destroyRef = inject(DestroyRef)\n const injector = inject(Injector)\n\n const result = signal<TOutput | null>(null)\n const isLoading = signal(false)\n const error = signal<Error | undefined>(undefined)\n const status = signal<GenerationClientState>('idle')\n const runId = signal<string | null>(null)\n let disposed = false\n\n const bodySource =\n options.body !== undefined ? toReactive(options.body) : undefined\n\n const clientOptions: GenerationClientOptions<TInput, TResult, TOutput> = {\n persistence: options.persistence,\n threadId: options.threadId,\n ...(bodySource !== undefined && { body: bodySource() }),\n ...(options.hydrateGeneration !== undefined && {\n hydrateGeneration: options.hydrateGeneration,\n }),\n ...(options.joinRun !== undefined && { joinRun: options.joinRun }),\n ...(options.byok !== undefined && { byok: options.byok }),\n byokProvider: () => options.byokProvider?.(),\n ...(options.reconstructResult\n ? { reconstructResult: options.reconstructResult }\n : {}),\n devtoolsBridgeFactory: createGenerationDevtoolsBridge,\n devtools: {\n ...options.devtools,\n framework: 'angular',\n hookName: 'injectGeneration',\n },\n // The transform's raw return type (`TTransformed`) and the stored output\n // (`TOutput`, with null/void/undefined stripped) are identical at runtime;\n // the cast bridges the relationship that the conditional type hides.\n onResult: ((r: TResult) => options.onResult?.(r)) as (\n result: TResult,\n ) => TOutput | null | void,\n onError: (e: Error) => {\n if (!disposed) options.onError?.(e)\n },\n onProgress: (p: number, m?: string) => {\n if (!disposed) options.onProgress?.(p, m)\n },\n onChunk: (c: StreamChunk) => {\n if (!disposed) options.onChunk?.(c)\n },\n }\n\n let client: GenerationClient<TInput, TResult, TOutput>\n if (options.connection) {\n client = new GenerationClient({\n ...clientOptions,\n connection: options.connection,\n })\n } else if (options.fetcher) {\n client = new GenerationClient({\n ...clientOptions,\n fetcher: options.fetcher,\n })\n } else {\n throw new Error(\n 'injectGeneration requires either a connection or fetcher option',\n )\n }\n\n const applySnapshot = () => {\n const next = client.getSnapshot()\n result.set(next.result)\n isLoading.set(next.isLoading)\n error.set(next.error)\n status.set(next.status)\n runId.set(next.runId)\n }\n applySnapshot()\n const unsubscribeSnapshot = client.subscribe(applySnapshot)\n\n if (bodySource) {\n effect(\n () => {\n client.updateOptions({\n body: bodySource(),\n })\n },\n { injector },\n )\n }\n\n // Mount devtools only. Generation runs are never auto-started after render —\n // persisted state is read-only for display.\n afterNextRender(\n () => {\n client.mountDevtools()\n },\n { injector },\n )\n destroyRef.onDestroy(() => {\n disposed = true\n unsubscribeSnapshot()\n client.dispose()\n })\n\n return {\n generate: (input: TInput) => client.generate(input),\n result: result.asReadonly(),\n isLoading: isLoading.asReadonly(),\n error: error.asReadonly(),\n status: status.asReadonly(),\n stop: () => client.stop(),\n reset: () => client.reset(),\n runId: runId.asReadonly(),\n }\n}\n","import { injectGeneration } from './inject-generation'\nimport { reconstructImageResult } from '@tanstack/ai-client'\nimport type { Signal } from '@angular/core'\nimport type { ImageGenerationResult } from '@tanstack/ai'\nimport type {\n GenerationClientState,\n ImageGenerateInput,\n InferGenerationOutputFromReturn,\n} from '@tanstack/ai-client'\nimport type {\n InjectGenerationOptions,\n InjectGenerationResult,\n} from './inject-generation'\n\nexport type InjectGenerateImageOptions<TOutput = ImageGenerationResult> = Omit<\n InjectGenerationOptions<ImageGenerateInput, ImageGenerationResult, TOutput>,\n 'onResult' | 'reconstructResult'\n> & {\n onResult?: (result: ImageGenerationResult) => TOutput | null | void\n}\n\nexport interface InjectGenerateImageResult<\n TOutput = ImageGenerationResult,\n> extends Omit<InjectGenerationResult<TOutput>, 'generate'> {\n generate: (input: ImageGenerateInput) => Promise<void>\n result: Signal<TOutput | null>\n isLoading: Signal<boolean>\n error: Signal<Error | undefined>\n status: Signal<GenerationClientState>\n}\n\nexport function injectGenerateImage<TTransformed = void>(\n options: Omit<InjectGenerateImageOptions, 'onResult'> & {\n onResult?: (result: ImageGenerationResult) => TTransformed\n },\n): InjectGenerateImageResult<\n InferGenerationOutputFromReturn<ImageGenerationResult, TTransformed>\n> {\n const devtools = {\n ...options.devtools,\n framework: 'angular' as const,\n hookName: 'injectGenerateImage',\n outputKind: 'image' as const,\n }\n const generation = injectGeneration<\n ImageGenerateInput,\n ImageGenerationResult,\n TTransformed\n >({\n ...options,\n devtools,\n reconstructResult: reconstructImageResult,\n })\n return generation\n}\n","import { injectGeneration } from './inject-generation'\nimport type { Signal } from '@angular/core'\nimport type { Model3DResult } from '@tanstack/ai'\nimport type {\n GenerationClientState,\n InferGenerationOutputFromReturn,\n Model3DGenerateInput,\n} from '@tanstack/ai-client'\nimport type {\n InjectGenerationOptions,\n InjectGenerationResult,\n} from './inject-generation'\n\n/**\n * Options for {@link injectGenerate3DModel}.\n *\n * @experimental 3D model generation is experimental. The shape can change in\n * a minor release.\n */\nexport type InjectGenerate3DModelOptions<TOutput = Model3DResult> = Omit<\n InjectGenerationOptions<Model3DGenerateInput, Model3DResult, TOutput>,\n | 'onResult'\n | 'reconstructResult'\n | 'persistence'\n | 'hydrateGeneration'\n | 'joinRun'\n> & {\n onResult?: (result: Model3DResult) => TOutput | null | void\n}\n\n/**\n * Return type of {@link injectGenerate3DModel}.\n *\n * @experimental 3D model generation is experimental. The shape can change in\n * a minor release.\n */\nexport interface InjectGenerate3DModelResult<\n TOutput = Model3DResult,\n> extends Omit<InjectGenerationResult<TOutput>, 'generate'> {\n generate: (input: Model3DGenerateInput) => Promise<void>\n result: Signal<TOutput | null>\n isLoading: Signal<boolean>\n error: Signal<Error | undefined>\n status: Signal<GenerationClientState>\n}\n\n/**\n * Generates a 3D model from a text or image prompt, with Angular signals.\n *\n * The server route runs `generate3DModel()` and streams the response. The\n * stream sends `generation:progress` events while the provider job runs, then\n * one `generation:result` event with the `Model3DResult`. Call it in an\n * injection context (a component field initializer, the constructor, or\n * `runInInjectionContext`).\n *\n * @param options - A `connection` (streaming) or a `fetcher` (one request),\n * a `threadId`, and optional callbacks (`onResult`, `onProgress`, `onError`).\n * If `onResult` returns a value, `result` holds that value.\n *\n * @example\n * ```ts\n * model = injectGenerate3DModel({\n * threadId: 'product-model',\n * connection: fetchServerSentEvents('/api/generate/3d-model'),\n * })\n *\n * this.model.generate({ prompt: 'A low-poly wooden chair' })\n * // this.model.result()?.url is the GLB file\n * ```\n *\n * @experimental 3D model generation is experimental. The shape can change in\n * a minor release.\n */\nexport function injectGenerate3DModel<TTransformed = void>(\n options: Omit<InjectGenerate3DModelOptions, 'onResult'> & {\n onResult?: (result: Model3DResult) => TTransformed\n },\n): InjectGenerate3DModelResult<\n InferGenerationOutputFromReturn<Model3DResult, TTransformed>\n> {\n const devtools = {\n ...options.devtools,\n framework: 'angular' as const,\n hookName: 'injectGenerate3DModel',\n }\n return injectGeneration<Model3DGenerateInput, Model3DResult, TTransformed>({\n ...options,\n devtools,\n // 3D results are never persisted, even if an untyped caller sets it.\n persistence: false,\n })\n}\n","import { injectGeneration } from './inject-generation'\nimport { reconstructAudioResult } from '@tanstack/ai-client'\nimport type { AudioGenerationResult, StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n AudioGenerateInput,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n InferGenerationOutputFromReturn,\n} from '@tanstack/ai-client'\nimport type { Signal } from '@angular/core'\nimport type { ReactiveOption } from './internal/to-reactive'\nimport type {\n InjectGenerationOptions,\n InjectGenerationResult,\n} from './inject-generation'\n\n/**\n * Options for the injectGenerateAudio injectable.\n *\n * @template TOutput - The output type after optional transform (defaults to AudioGenerationResult)\n */\nexport interface InjectGenerateAudioOptions<\n TOutput = AudioGenerationResult,\n> extends Pick<\n InjectGenerationOptions<AudioGenerateInput, AudioGenerationResult, TOutput>,\n | 'persistence'\n | 'threadId'\n | 'hydrateGeneration'\n | 'joinRun'\n | 'byok'\n | 'byokProvider'\n> {\n /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */\n connection?: ConnectConnectionAdapter\n /** Direct async function for audio generation */\n fetcher?: GenerationFetcher<AudioGenerateInput, AudioGenerationResult>\n /** Additional body parameters to send with connect-based adapter requests. Reactive. */\n body?: ReactiveOption<Record<string, any>>\n /** Display options for TanStack AI Devtools. */\n devtools?: AIDevtoolsDisplayOptions\n /**\n * Callback when audio is generated. Can optionally return a transformed value.\n *\n * - Return a non-null value to transform and store it as the result\n * - Return `null` to keep the previous result unchanged\n * - Return nothing (`void`) to store the raw result as-is\n */\n onResult?: (result: AudioGenerationResult) => TOutput | null | void\n /** Callback when an error occurs */\n onError?: (error: Error) => void\n /** Callback when progress is reported (0-100) */\n onProgress?: (progress: number, message?: string) => void\n /** Callback for each stream chunk (connect-based adapter mode only) */\n onChunk?: (chunk: StreamChunk) => void\n}\n\n/**\n * Return type for the injectGenerateAudio injectable.\n *\n * @template TOutput - The output type (after optional transform)\n */\nexport interface InjectGenerateAudioResult<\n TOutput = AudioGenerationResult,\n> extends Omit<InjectGenerationResult<TOutput>, 'generate'> {\n /** Trigger audio generation */\n generate: (input: AudioGenerateInput) => Promise<void>\n /** The generation result containing audio, or null */\n result: Signal<TOutput | null>\n /** Whether generation is in progress */\n isLoading: Signal<boolean>\n /** Current error, if any */\n error: Signal<Error | undefined>\n /** Current state of the generation */\n status: Signal<GenerationClientState>\n}\n\n/**\n * Angular injectable for generating audio (music, sound effects) using AI models.\n *\n * @example\n * ```typescript\n * import { Component } from '@angular/core'\n * import { injectGenerateAudio } from '@tanstack/ai-angular'\n * import { fetchServerSentEvents } from '@tanstack/ai-client'\n *\n * @Component({\n * selector: 'app-audio',\n * template: `\n * <button (click)=\"generate({ prompt: 'An upbeat electronic track', duration: 10 })\">\n * Generate\n * </button>\n * @if (result()) {\n * <audio [src]=\"result()!.audio.url\" controls></audio>\n * }\n * `,\n * })\n * export class AudioComponent {\n * private gen = injectGenerateAudio({\n * threadId: 'theme-audio',\n * connection: fetchServerSentEvents('/api/generate/audio'),\n * })\n *\n * generate = this.gen.generate\n * result = this.gen.result\n * isLoading = this.gen.isLoading\n * }\n * ```\n */\nexport function injectGenerateAudio<TTransformed = void>(\n options: Omit<InjectGenerateAudioOptions, 'onResult'> & {\n onResult?: (result: AudioGenerationResult) => TTransformed\n },\n): InjectGenerateAudioResult<\n InferGenerationOutputFromReturn<AudioGenerationResult, TTransformed>\n> {\n const devtools = {\n ...options.devtools,\n framework: 'angular',\n hookName: 'injectGenerateAudio',\n outputKind: 'audio' as const,\n }\n const generation = injectGeneration<\n AudioGenerateInput,\n AudioGenerationResult,\n TTransformed\n >({\n ...options,\n devtools,\n reconstructResult: reconstructAudioResult,\n })\n\n return generation\n}\n","import { injectGeneration } from './inject-generation'\nimport { reconstructSpeechResult } from '@tanstack/ai-client'\nimport type { Signal } from '@angular/core'\nimport type { TTSResult } from '@tanstack/ai'\nimport type {\n GenerationClientState,\n InferGenerationOutputFromReturn,\n SpeechGenerateInput,\n} from '@tanstack/ai-client'\nimport type {\n InjectGenerationOptions,\n InjectGenerationResult,\n} from './inject-generation'\n\nexport type InjectGenerateSpeechOptions<TOutput = TTSResult> = Omit<\n InjectGenerationOptions<SpeechGenerateInput, TTSResult, TOutput>,\n 'onResult' | 'reconstructResult'\n> & {\n onResult?: (result: TTSResult) => TOutput | null | void\n}\n\nexport interface InjectGenerateSpeechResult<TOutput = TTSResult> extends Omit<\n InjectGenerationResult<TOutput>,\n 'generate'\n> {\n generate: (input: SpeechGenerateInput) => Promise<void>\n result: Signal<TOutput | null>\n isLoading: Signal<boolean>\n error: Signal<Error | undefined>\n status: Signal<GenerationClientState>\n}\n\nexport function injectGenerateSpeech<TTransformed = void>(\n options: Omit<InjectGenerateSpeechOptions, 'onResult'> & {\n onResult?: (result: TTSResult) => TTransformed\n },\n): InjectGenerateSpeechResult<\n InferGenerationOutputFromReturn<TTSResult, TTransformed>\n> {\n const devtools = {\n ...options.devtools,\n framework: 'angular' as const,\n hookName: 'injectGenerateSpeech',\n outputKind: 'audio' as const,\n }\n const generation = injectGeneration<\n SpeechGenerateInput,\n TTSResult,\n TTransformed\n >({\n ...options,\n devtools,\n reconstructResult: reconstructSpeechResult,\n })\n return generation\n}\n","import { injectGeneration } from './inject-generation'\nimport { reconstructTranscriptionResult } from '@tanstack/ai-client'\nimport type { Signal } from '@angular/core'\nimport type { TranscriptionResult } from '@tanstack/ai'\nimport type {\n GenerationClientState,\n InferGenerationOutputFromReturn,\n TranscriptionGenerateInput,\n} from '@tanstack/ai-client'\nimport type {\n InjectGenerationOptions,\n InjectGenerationResult,\n} from './inject-generation'\n\nexport type InjectTranscriptionOptions<TOutput = TranscriptionResult> = Omit<\n InjectGenerationOptions<\n TranscriptionGenerateInput,\n TranscriptionResult,\n TOutput\n >,\n 'onResult' | 'reconstructResult'\n> & {\n onResult?: (result: TranscriptionResult) => TOutput | null | void\n}\n\nexport interface InjectTranscriptionResult<\n TOutput = TranscriptionResult,\n> extends Omit<InjectGenerationResult<TOutput>, 'generate'> {\n generate: (input: TranscriptionGenerateInput) => Promise<void>\n result: Signal<TOutput | null>\n isLoading: Signal<boolean>\n error: Signal<Error | undefined>\n status: Signal<GenerationClientState>\n}\n\nexport function injectTranscription<TTransformed = void>(\n options: Omit<InjectTranscriptionOptions, 'onResult'> & {\n onResult?: (result: TranscriptionResult) => TTransformed\n },\n): InjectTranscriptionResult<\n InferGenerationOutputFromReturn<TranscriptionResult, TTransformed>\n> {\n const devtools = {\n ...options.devtools,\n framework: 'angular' as const,\n hookName: 'injectTranscription',\n outputKind: 'text' as const,\n }\n const generation = injectGeneration<\n TranscriptionGenerateInput,\n TranscriptionResult,\n TTransformed\n >({\n ...options,\n devtools,\n reconstructResult: reconstructTranscriptionResult,\n })\n return generation\n}\n","import {\n DestroyRef,\n assertInInjectionContext,\n inject,\n signal,\n} from '@angular/core'\nimport { AudioRecorder } from '@tanstack/ai-client'\nimport type { Signal } from '@angular/core'\nimport type {\n AudioRecorderOptions,\n AudioRecording,\n InferAudioRecordingOutput,\n} from '@tanstack/ai-client'\n\nexport type InjectAudioRecorderOptions<TOnComplete> = AudioRecorderOptions & {\n /**\n * Optional transform applied to the recording when `stop()` resolves. Its\n * (awaited) return value becomes `recording` and the resolved value of\n * `stop()`. Return nothing to keep the raw `AudioRecording`.\n */\n onComplete?: TOnComplete\n}\n\nexport interface InjectAudioRecorderResult<TOutput> {\n /** Reactive: latest recording (transformed if `onComplete` provided), or null. */\n recording: Signal<TOutput | null>\n /** Reactive: true while actively capturing audio. */\n isRecording: Signal<boolean>\n /** Whether the browser supports recording. */\n isSupported: boolean\n start: () => Promise<void>\n /** Stop and resolve with the completed recording (transformed if `onComplete` provided). */\n stop: () => Promise<TOutput>\n /** Discard the in-progress recording and release the mic. */\n cancel: () => void\n}\n\n/**\n * Angular injectable for recording an audio message. The resolved recording\n * carries `.part` (for `injectChat`'s `sendMessage`) and `.base64` (for the\n * generation injectables). Must be called in an injection context.\n *\n * Errors are delivered via `onError`. `start()` and `stop()` also reject on\n * failure (and `stop()` rejects with `Recording cancelled` if `cancel()` runs\n * while a stop is in flight, e.g. on destroy) — handle one channel, not both.\n */\n// The transforming overload requires `onComplete`. Without that constraint an\n// options object carrying only unrelated keys (`injectAudioRecorder({ onError })`)\n// still matches it, `TOnComplete` infers as `unknown`, and `recording`/`stop()`\n// collapse to `unknown` — so passing any option would silently cost you the\n// `AudioRecording` type. Requiring it here sends those calls to the second\n// overload instead (issue #1001).\nexport function injectAudioRecorder<\n TOnComplete extends (recording: AudioRecording) => unknown,\n>(\n options: InjectAudioRecorderOptions<TOnComplete> & {\n onComplete: TOnComplete\n },\n): InjectAudioRecorderResult<InferAudioRecordingOutput<TOnComplete>>\nexport function injectAudioRecorder(\n options?: InjectAudioRecorderOptions<undefined>,\n): InjectAudioRecorderResult<AudioRecording>\nexport function injectAudioRecorder(\n options: InjectAudioRecorderOptions<\n (recording: AudioRecording) => unknown\n > = {},\n): InjectAudioRecorderResult<unknown> {\n assertInInjectionContext(injectAudioRecorder)\n const destroyRef = inject(DestroyRef)\n const recorder = new AudioRecorder({\n ...(options.audio !== undefined && { audio: options.audio }),\n ...(options.mimeType !== undefined && { mimeType: options.mimeType }),\n ...(options.onError !== undefined && { onError: options.onError }),\n })\n const isRecording = signal(false)\n const recording = signal<unknown>(null)\n\n const unsubscribe = recorder.subscribe((state) => {\n isRecording.set(state === 'recording')\n })\n destroyRef.onDestroy(() => {\n unsubscribe()\n recorder.cancel()\n })\n\n const stop = async (): Promise<unknown> => {\n const rawRecording = await recorder.stop()\n const transformed = await options.onComplete?.(rawRecording)\n // Only `undefined` (returning nothing) keeps the raw recording; a returned\n // null is a real value, matching the inferred output type.\n const output = transformed === undefined ? rawRecording : transformed\n recording.set(output)\n return output\n }\n\n return {\n recording: recording.asReadonly(),\n isRecording: isRecording.asReadonly(),\n isSupported: AudioRecorder.isSupported(),\n start: () => recorder.start(),\n stop,\n cancel: () => recorder.cancel(),\n }\n}\n","import { injectGeneration } from './inject-generation'\nimport { reconstructSummarizeResult } from '@tanstack/ai-client'\nimport type { Signal } from '@angular/core'\nimport type { SummarizationResult } from '@tanstack/ai'\nimport type {\n GenerationClientState,\n InferGenerationOutputFromReturn,\n SummarizeGenerateInput,\n} from '@tanstack/ai-client'\nimport type {\n InjectGenerationOptions,\n InjectGenerationResult,\n} from './inject-generation'\n\nexport type InjectSummarizeOptions<TOutput = SummarizationResult> = Omit<\n InjectGenerationOptions<SummarizeGenerateInput, SummarizationResult, TOutput>,\n 'onResult' | 'reconstructResult'\n> & {\n onResult?: (result: SummarizationResult) => TOutput | null | void\n}\n\nexport interface InjectSummarizeResult<\n TOutput = SummarizationResult,\n> extends Omit<InjectGenerationResult<TOutput>, 'generate'> {\n generate: (input: SummarizeGenerateInput) => Promise<void>\n result: Signal<TOutput | null>\n isLoading: Signal<boolean>\n error: Signal<Error | undefined>\n status: Signal<GenerationClientState>\n}\n\nexport function injectSummarize<TTransformed = void>(\n options: Omit<InjectSummarizeOptions, 'onResult'> & {\n onResult?: (result: SummarizationResult) => TTransformed\n },\n): InjectSummarizeResult<\n InferGenerationOutputFromReturn<SummarizationResult, TTransformed>\n> {\n const devtools = {\n ...options.devtools,\n framework: 'angular' as const,\n hookName: 'injectSummarize',\n outputKind: 'text' as const,\n }\n const generation = injectGeneration<\n SummarizeGenerateInput,\n SummarizationResult,\n TTransformed\n >({\n ...options,\n devtools,\n reconstructResult: reconstructSummarizeResult,\n })\n return generation\n}\n","import { VideoGenerationClient } from '@tanstack/ai-client'\nimport { createVideoDevtoolsBridge } from '@tanstack/ai-client/devtools'\nimport {\n DestroyRef,\n Injector,\n afterNextRender,\n assertInInjectionContext,\n effect,\n inject,\n signal,\n} from '@angular/core'\nimport { toReactive } from './internal/to-reactive'\nimport type { Signal } from '@angular/core'\nimport type { ReactiveOption } from './internal/to-reactive'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n InferGenerationOutputFromReturn,\n VideoGenerateInput,\n VideoGenerateResult,\n VideoStatusInfo,\n} from '@tanstack/ai-client'\nimport type { ByokClient } from '@tanstack/ai-client/byok'\nimport type { ProviderId } from '@tanstack/ai/byok'\nimport type { StreamChunk } from '@tanstack/ai'\n\nexport interface InjectGenerateVideoOptions<TOutput = VideoGenerateResult> {\n connection?: ConnectConnectionAdapter\n fetcher?: GenerationFetcher<VideoGenerateInput, VideoGenerateResult>\n body?: ReactiveOption<Record<string, any>>\n /** Optional BYOK keyring. Keys go in `x-byok-*` headers, never the body. */\n byok?: ByokClient\n /** Optional provider id. If it returns a slug, only that key is sent. If no slug resolves (`byokProvider`, then `body.provider`), generate throws. */\n byokProvider?: () => ProviderId | undefined\n devtools?: AIDevtoolsDisplayOptions\n /**\n * How this generation persists across reloads.\n * - Omit / `false`: ephemeral, in-memory only.\n * - `true`: server-driven — on mount the client hydrates the last generation\n * for its `threadId` from the server (needs a connection with a\n * `hydrateGeneration` handler) and repaints it; it never auto-starts a run.\n */\n persistence?: boolean\n /**\n * The **scope** this generation belongs to: a stable, app-chosen name for the\n * slot successive runs fill — not a link to a chat conversation.\n *\n * The hook starts empty and produces many runs over its life; each gets its\n * own `runId`, but all belong to one scope. Persistence keys on this, so\n * derive it from your own domain and keep it identical across reloads (e.g.\n * `` `video-${videoId}-start-frame` ``). It is also sent as the AG-UI thread\n * id on the wire, which the protocol requires.\n *\n * Required. A generated id would change on every reload, so persistence\n * would restore nothing.\n */\n threadId: string\n /**\n * Server-driven hydration handler for `persistence: true` when the\n * connection doesn't carry one (e.g. alongside `fetcher`, or a `stream()` /\n * `rpcStream()` adapter built without handlers) — typically a one-line\n * server-function call. The connection's own handler takes precedence.\n */\n hydrateGeneration?: ConnectConnectionAdapter['hydrateGeneration']\n /**\n * Re-attach handler that replays a run still generating to completion on\n * mount, when the connection doesn't carry one. Without it, a restored\n * `running` snapshot surfaces as an (interrupted) error. The connection's\n * own handler takes precedence.\n */\n joinRun?: ConnectConnectionAdapter['joinRun']\n onResult?: (result: VideoGenerateResult) => TOutput | null | void\n onError?: (error: Error) => void\n onProgress?: (progress: number, message?: string) => void\n onJobCreated?: (jobId: string) => void\n onStatusUpdate?: (status: VideoStatusInfo) => void\n onChunk?: (chunk: StreamChunk) => void\n}\n\nexport interface InjectGenerateVideoResult<TOutput = VideoGenerateResult> {\n generate: (input: VideoGenerateInput) => Promise<void>\n result: Signal<TOutput | null>\n jobId: Signal<string | null>\n videoStatus: Signal<VideoStatusInfo | null>\n isLoading: Signal<boolean>\n error: Signal<Error | undefined>\n status: Signal<GenerationClientState>\n stop: () => void\n reset: () => void\n /**\n * The id of the generation job currently running, or `null` when nothing is in\n * flight. Each call to `generate` is one job with its own id. Pass it to your\n * own endpoint to cancel or poll the provider job — `stop()` only aborts the\n * local stream, it does not stop work already running on the provider.\n */\n runId: Signal<string | null>\n}\n\n// `TTransformed` infers from the `onResult` return position so the callback\n// parameter is typed as `VideoGenerateResult` and `result` narrows to the\n// transform's return. See issue #848.\nexport function injectGenerateVideo<TTransformed = void>(\n options: Omit<InjectGenerateVideoOptions, 'onResult'> & {\n onResult?: (result: VideoGenerateResult) => TTransformed\n },\n): InjectGenerateVideoResult<\n InferGenerationOutputFromReturn<VideoGenerateResult, TTransformed>\n> {\n assertInInjectionContext(injectGenerateVideo)\n\n type TOutput = InferGenerationOutputFromReturn<\n VideoGenerateResult,\n TTransformed\n >\n\n const destroyRef = inject(DestroyRef)\n const injector = inject(Injector)\n\n const result = signal<TOutput | null>(null)\n const jobId = signal<string | null>(null)\n const videoStatus = signal<VideoStatusInfo | null>(null)\n const isLoading = signal(false)\n const error = signal<Error | undefined>(undefined)\n const status = signal<GenerationClientState>('idle')\n const runId = signal<string | null>(null)\n let disposed = false\n\n const bodySource =\n options.body !== undefined ? toReactive(options.body) : undefined\n\n const baseOptions = {\n ...(bodySource !== undefined && { body: bodySource() }),\n persistence: options.persistence,\n threadId: options.threadId,\n ...(options.hydrateGeneration !== undefined && {\n hydrateGeneration: options.hydrateGeneration,\n }),\n ...(options.joinRun !== undefined && { joinRun: options.joinRun }),\n ...(options.byok !== undefined && { byok: options.byok }),\n byokProvider: () => options.byokProvider?.(),\n devtoolsBridgeFactory: createVideoDevtoolsBridge,\n devtools: {\n ...options.devtools,\n framework: 'angular',\n hookName: 'injectGenerateVideo',\n outputKind: 'video' as const,\n },\n // The transform's raw return type (`TTransformed`) and the stored output\n // (`TOutput`, with null/void/undefined stripped) are identical at runtime;\n // the cast bridges the relationship that the conditional type hides.\n onResult: ((r: VideoGenerateResult) => options.onResult?.(r)) as (\n result: VideoGenerateResult,\n ) => TOutput | null | void,\n onError: (e: Error) => {\n if (!disposed) options.onError?.(e)\n },\n onProgress: (p: number, m?: string) => {\n if (!disposed) options.onProgress?.(p, m)\n },\n onChunk: (c: StreamChunk) => {\n if (!disposed) options.onChunk?.(c)\n },\n onJobCreated: (id: string) => {\n if (!disposed) options.onJobCreated?.(id)\n },\n onStatusUpdate: (s: VideoStatusInfo) => {\n if (!disposed) options.onStatusUpdate?.(s)\n },\n }\n\n let client: VideoGenerationClient<TOutput>\n if (options.connection) {\n client = new VideoGenerationClient({\n ...baseOptions,\n connection: options.connection,\n })\n } else if (options.fetcher) {\n client = new VideoGenerationClient({\n ...baseOptions,\n fetcher: options.fetcher,\n })\n } else {\n throw new Error(\n 'injectGenerateVideo requires either a connection or fetcher option',\n )\n }\n\n const applySnapshot = () => {\n const next = client.getSnapshot()\n result.set(next.result)\n isLoading.set(next.isLoading)\n error.set(next.error)\n status.set(next.status)\n runId.set(next.runId)\n jobId.set(next.jobId)\n videoStatus.set(next.videoStatus)\n }\n applySnapshot()\n const unsubscribeSnapshot = client.subscribe(applySnapshot)\n\n if (bodySource) {\n effect(\n () => {\n client.updateOptions({\n body: bodySource(),\n })\n },\n { injector },\n )\n }\n\n // Mount devtools only. Generation runs are never auto-started after render —\n // persisted state is read-only for display.\n afterNextRender(\n () => {\n client.mountDevtools()\n },\n { injector },\n )\n destroyRef.onDestroy(() => {\n disposed = true\n unsubscribeSnapshot()\n client.dispose()\n })\n\n return {\n generate: (input: VideoGenerateInput) => client.generate(input),\n result: result.asReadonly(),\n jobId: jobId.asReadonly(),\n videoStatus: videoStatus.asReadonly(),\n isLoading: isLoading.asReadonly(),\n error: error.asReadonly(),\n status: status.asReadonly(),\n stop: () => client.stop(),\n reset: () => client.reset(),\n runId: runId.asReadonly(),\n }\n}\n"],"mappings":";;;AAiBA,SAAgB,WAAc,OAAwB;CACpD,IAAI,SAAS,KAAK,GAChB,OAAO;CAET,IAAI,OAAO,UAAU,YACnB,OAAO,SAAS,KAAgB;CAElC,aAAa;AACf;ACYA,SAAgB,WAQd,SAAkE;CAElE,yBAAyB,UAAU;CAKnC,MAAM,aAAa,OAAO,UAAU;CACpC,MAAM,WAAW,OAAO,QAAQ;CAGhC,MAAM,uBACJ,QAAQ,mBAAmB,SACvB,WAAW,QAAQ,cAAc,IACjC;CACN,MAAM,gBACJ,QAAQ,YAAY,SAAY,WAAW,QAAQ,OAAO,IAAI;CAChE,MAAM,aACJ,QAAQ,SAAS,SAAY,WAAW,QAAQ,IAAI,IAAI;CAC1D,MAAM,c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AAI,KAAK,KAAK;EACpB,YAAY,IAAI,KAAK,WAAW;CAClC;CACA,cAAa;CACb,MAAM,sBAAsB,OAAO,UAAU,aAAa;CAE1D,IAAI,YACF,aACO;EACH,OAAO,cAAc,EACnB,MAAM,WAAU,EACjB,CAAA;CACH,GACA,EAAE,SAAQ,CAAE;CAMhB,sBACO;EACH,OAAO,cAAa;CACtB,GACA,EAAE,SAAQ,CAAE;CAEd,WAAW,gBAAe;EACxB,WAAW;EACX,oBAAmB;EACnB,OAAO,QAAO;CAChB,CAAC;CAED,OAAO;EACL,WAAW,UAA8B,OAAO,SAAS,KAAK;EAC9D,QAAQ,OAAO,WAAU;EACzB,OAAO,MAAM,WAAU;EACvB,aAAa,YAAY,WAAU;EACnC,WAAW,UAAU,WAAU;EAC/B,OAAO,MAAM,WAAU;EACvB,QAAQ,OAAO,WAAU;EACzB,YAAY,OAAO,KAAI;EACvB,aAAa,OAAO,MAAK;EACzB,OAAO,MAAM,WAAU;CACxB;AACH"}
@@ -1,5 +1,5 @@
1
- import { AnyClientTool, AudioGenerationResult, ImageGenerationResult, InferSchemaType, InterruptDefinition, ModelMessage, RunAgentResumeItem, SchemaInput, StreamChunk, SummarizationResult, TTSResult, TranscriptionResult } from "@tanstack/ai";
2
- import { AIDevtoolsDisplayOptions, AnyClientTool as AnyClientTool$1, AudioGenerateInput, AudioGenerateInput as AudioGenerateInput$1, AudioRecorder, AudioRecorderOptions, AudioRecording, BatchStrategy, BoundInterrupts, ChatClient, ChatClientOptions, ChatClientPersistence, ChatClientState, ChatInterruptState, ChatPersistedState, ChatPersistenceOption, ChatRequestBody, ChatResumeState, ChatStorageAdapter, ClientContextOptionFromTools, CompositeStrategy, ConnectConnectionAdapter, ConnectConnectionAdapter as ConnectConnectionAdapter$1, ConnectionAdapter, ConnectionStatus, CreateMcpAppBridgeOptions, DistributedOmit, DurableStreamIncompleteError, FetchConnectionOptions, FetchJsonOptions, GENERATION_EVENTS, GenerationClient, GenerationClientState, GenerationClientState as GenerationClientState$1, GenerationFetcher, GenerationRestoredResult, GetWebMCPToolsOptions, ImageGenerateInput, ImageGenerateInput as ImageGenerateInput$1, ImmediateStrategy, IndexedDBPersistenceOptions, InferAudioRecordingOutput, InferChatMessages, InferGenerationOutputFromReturn, InferredClientContext, InterruptManager, McpAppBridge, MultimodalContent, PartialJSONParser, PunctuationStrategy, QueueConfig, QueueOption, QueueStrategy, QueuedMessage, RealtimeClient, RegisterWebMCPToolsOptions, ResolvableChatInterrupt, RunAgentInputContext, SendMessageOptions, SpeechGenerateInput, SpeechGenerateInput as SpeechGenerateInput$1, StorageUnavailableError, StreamProcessor, StreamReconnectLimitError, StreamTruncatedError, SubscribeConnectionAdapter, SubscribeWebMCPToolsOptions, SubscribeWebMCPToolsOptions as SubscribeWebMCPToolsOptions$1, SummarizeGenerateInput, SummarizeGenerateInput as SummarizeGenerateInput$1, TranscriptionGenerateInput, TranscriptionGenerateInput as TranscriptionGenerateInput$1, UIMessage, UnsupportedResponseStreamError, VideoGenerateInput, VideoGenerateInput as VideoGenerateInput$1, VideoGenerateResult, VideoGenerateResult as VideoGenerateResult$1, VideoGenerationClient, VideoStatusInfo, VideoStatusInfo as VideoStatusInfo$1, WebMCPPageTool, WebSocketConnectionOptions, WebStoragePersistenceOptions, WhenBusy, WordBoundaryStrategy, XhrConnectionOptions, clientTools, convertMessagesToModelMessages, createAIDevtoolsGenerationPreview, createChatClientOptions, createMcpAppBridge, defaultJSONParser, fetchHttpStream, fetchJson, fetchServerSentEvents, generateMessageId, getWebMCPTools, indexedDBPersistence, localStoragePersistence, modelMessageToUIMessage, modelMessagesToUIMessages, normalizeToUIMessage, parsePartialJSON, reconstructAudioResult, reconstructImageResult, reconstructSpeechResult, reconstructSummarizeResult, reconstructTranscriptionResult, registerWebMCPTools, rpcStream, sessionStoragePersistence, stream, subscribeWebMCPTools, uiMessageToModelMessages, webSocket, xhrHttpStream, xhrServerSentEvents } from "@tanstack/ai-client";
1
+ import { AnyClientTool, AudioGenerationResult, ImageGenerationResult, InferSchemaType, InterruptDefinition, Model3DResult, ModelMessage, RunAgentResumeItem, SchemaInput, StreamChunk, SummarizationResult, TTSResult, TranscriptionResult } from "@tanstack/ai";
2
+ import { AIDevtoolsDisplayOptions, AnyClientTool as AnyClientTool$1, AudioGenerateInput, AudioGenerateInput as AudioGenerateInput$1, AudioRecorder, AudioRecorderOptions, AudioRecording, BatchStrategy, BoundInterrupts, ChatClient, ChatClientOptions, ChatClientPersistence, ChatClientState, ChatInterruptState, ChatPersistedState, ChatPersistenceOption, ChatRequestBody, ChatResumeState, ChatStorageAdapter, ClientContextOptionFromTools, CompositeStrategy, ConnectConnectionAdapter, ConnectConnectionAdapter as ConnectConnectionAdapter$1, ConnectionAdapter, ConnectionStatus, CreateMcpAppBridgeOptions, DistributedOmit, DurableStreamIncompleteError, FetchConnectionOptions, FetchJsonOptions, GENERATION_EVENTS, GenerationClient, GenerationClientState, GenerationClientState as GenerationClientState$1, GenerationFetcher, GenerationRestoredResult, GetWebMCPToolsOptions, ImageGenerateInput, ImageGenerateInput as ImageGenerateInput$1, ImmediateStrategy, IndexedDBPersistenceOptions, InferAudioRecordingOutput, InferChatMessages, InferGenerationOutputFromReturn, InferredClientContext, InterruptManager, McpAppBridge, Model3DGenerateInput, Model3DGenerateInput as Model3DGenerateInput$1, MultimodalContent, PartialJSONParser, PunctuationStrategy, QueueConfig, QueueOption, QueueStrategy, QueuedMessage, RealtimeClient, RegisterWebMCPToolsOptions, ResolvableChatInterrupt, RunAgentInputContext, SendMessageOptions, SpeechGenerateInput, SpeechGenerateInput as SpeechGenerateInput$1, StorageUnavailableError, StreamProcessor, StreamReconnectLimitError, StreamTruncatedError, SubscribeConnectionAdapter, SubscribeWebMCPToolsOptions, SubscribeWebMCPToolsOptions as SubscribeWebMCPToolsOptions$1, SummarizeGenerateInput, SummarizeGenerateInput as SummarizeGenerateInput$1, TranscriptionGenerateInput, TranscriptionGenerateInput as TranscriptionGenerateInput$1, UIMessage, UnsupportedResponseStreamError, VideoGenerateInput, VideoGenerateInput as VideoGenerateInput$1, VideoGenerateResult, VideoGenerateResult as VideoGenerateResult$1, VideoGenerationClient, VideoStatusInfo, VideoStatusInfo as VideoStatusInfo$1, WebMCPPageTool, WebSocketConnectionOptions, WebStoragePersistenceOptions, WhenBusy, WordBoundaryStrategy, XhrConnectionOptions, clientTools, convertMessagesToModelMessages, createAIDevtoolsGenerationPreview, createChatClientOptions, createMcpAppBridge, defaultJSONParser, fetchHttpStream, fetchJson, fetchServerSentEvents, generateMessageId, getWebMCPTools, indexedDBPersistence, localStoragePersistence, modelMessageToUIMessage, modelMessagesToUIMessages, normalizeToUIMessage, parsePartialJSON, reconstructAudioResult, reconstructImageResult, reconstructSpeechResult, reconstructSummarizeResult, reconstructTranscriptionResult, registerWebMCPTools, rpcStream, sessionStoragePersistence, stream, subscribeWebMCPTools, uiMessageToModelMessages, webSocket, xhrHttpStream, xhrServerSentEvents } from "@tanstack/ai-client";
3
3
  import { Signal } from "@angular/core";
4
4
  import { ByokClient, ByokSnapshot } from "@tanstack/ai-client/byok";
5
5
  import { ProviderId } from "@tanstack/ai/byok";
@@ -291,6 +291,58 @@ interface InjectGenerateImageResult<TOutput = ImageGenerationResult> extends Omi
291
291
  export declare function injectGenerateImage<TTransformed = void>(options: Omit<InjectGenerateImageOptions, 'onResult'> & {
292
292
  onResult?: (result: ImageGenerationResult) => TTransformed;
293
293
  }): InjectGenerateImageResult<InferGenerationOutputFromReturn<ImageGenerationResult, TTransformed>>;
294
+ /**
295
+ * Options for {@link injectGenerate3DModel}.
296
+ *
297
+ * @experimental 3D model generation is experimental. The shape can change in
298
+ * a minor release.
299
+ */
300
+ type InjectGenerate3DModelOptions<TOutput = Model3DResult> = Omit<InjectGenerationOptions<Model3DGenerateInput$1, Model3DResult, TOutput>, 'onResult' | 'reconstructResult' | 'persistence' | 'hydrateGeneration' | 'joinRun'> & {
301
+ onResult?: (result: Model3DResult) => TOutput | null | void;
302
+ };
303
+ /**
304
+ * Return type of {@link injectGenerate3DModel}.
305
+ *
306
+ * @experimental 3D model generation is experimental. The shape can change in
307
+ * a minor release.
308
+ */
309
+ interface InjectGenerate3DModelResult<TOutput = Model3DResult> extends Omit<InjectGenerationResult<TOutput>, 'generate'> {
310
+ generate: (input: Model3DGenerateInput$1) => Promise<void>;
311
+ result: Signal<TOutput | null>;
312
+ isLoading: Signal<boolean>;
313
+ error: Signal<Error | undefined>;
314
+ status: Signal<GenerationClientState$1>;
315
+ }
316
+ /**
317
+ * Generates a 3D model from a text or image prompt, with Angular signals.
318
+ *
319
+ * The server route runs `generate3DModel()` and streams the response. The
320
+ * stream sends `generation:progress` events while the provider job runs, then
321
+ * one `generation:result` event with the `Model3DResult`. Call it in an
322
+ * injection context (a component field initializer, the constructor, or
323
+ * `runInInjectionContext`).
324
+ *
325
+ * @param options - A `connection` (streaming) or a `fetcher` (one request),
326
+ * a `threadId`, and optional callbacks (`onResult`, `onProgress`, `onError`).
327
+ * If `onResult` returns a value, `result` holds that value.
328
+ *
329
+ * @example
330
+ * ```ts
331
+ * model = injectGenerate3DModel({
332
+ * threadId: 'product-model',
333
+ * connection: fetchServerSentEvents('/api/generate/3d-model'),
334
+ * })
335
+ *
336
+ * this.model.generate({ prompt: 'A low-poly wooden chair' })
337
+ * // this.model.result()?.url is the GLB file
338
+ * ```
339
+ *
340
+ * @experimental 3D model generation is experimental. The shape can change in
341
+ * a minor release.
342
+ */
343
+ export declare function injectGenerate3DModel<TTransformed = void>(options: Omit<InjectGenerate3DModelOptions, 'onResult'> & {
344
+ onResult?: (result: Model3DResult) => TTransformed;
345
+ }): InjectGenerate3DModelResult<InferGenerationOutputFromReturn<Model3DResult, TTransformed>>;
294
346
  /**
295
347
  * Options for the injectGenerateAudio injectable.
296
348
  *
@@ -518,4 +570,4 @@ interface InjectGenerateVideoResult<TOutput = VideoGenerateResult$1> {
518
570
  export declare function injectGenerateVideo<TTransformed = void>(options: Omit<InjectGenerateVideoOptions, 'onResult'> & {
519
571
  onResult?: (result: VideoGenerateResult$1) => TTransformed;
520
572
  }): InjectGenerateVideoResult<InferGenerationOutputFromReturn<VideoGenerateResult$1, TTransformed>>;
521
- export { type AudioGenerateInput, AudioRecorder, BatchStrategy, ChatClient, type ChatClientPersistence, type ChatPersistedState, type ChatPersistenceOption, type ChatRequestBody, type ChatStorageAdapter, CompositeStrategy, type ConnectConnectionAdapter, type ConnectionAdapter, type CreateMcpAppBridgeOptions, type DeepPartial, DurableStreamIncompleteError, type FetchConnectionOptions, type FetchJsonOptions, GENERATION_EVENTS, GenerationClient, type GenerationClientState, type GetWebMCPToolsOptions, type ImageGenerateInput, ImmediateStrategy, type IndexedDBPersistenceOptions, type InferChatMessages, type InjectAudioRecorderOptions, type InjectAudioRecorderResult, type InjectChatOptions, type InjectChatResult, type InjectGenerateAudioOptions, type InjectGenerateAudioResult, type InjectGenerateImageOptions, type InjectGenerateImageResult, type InjectGenerateSpeechOptions, type InjectGenerateSpeechResult, type InjectGenerateVideoOptions, type InjectGenerateVideoResult, type InjectGenerationOptions, type InjectGenerationResult, type InjectPageWebMCPToolsOptions, type InjectRegisterWebMCPToolsOptions, type InjectSummarizeOptions, type InjectSummarizeResult, type InjectTranscriptionOptions, type InjectTranscriptionResult, InterruptManager, type McpAppBridge, type MultimodalContent, PartialJSONParser, PunctuationStrategy, type QueueConfig, type QueueOption, type QueueStrategy, type QueuedMessage, type ReactiveOption, RealtimeClient, type RunAgentInputContext, type SendMessageOptions, type SpeechGenerateInput, StorageUnavailableError, StreamProcessor, StreamReconnectLimitError, StreamTruncatedError, type SubscribeConnectionAdapter, type SubscribeWebMCPToolsOptions, type SummarizeGenerateInput, type TranscriptionGenerateInput, type UIMessage, UnsupportedResponseStreamError, type VideoGenerateInput, type VideoGenerateResult, VideoGenerationClient, type VideoStatusInfo, type WebMCPPageTool, type WebSocketConnectionOptions, type WebStoragePersistenceOptions, type WhenBusy, WordBoundaryStrategy, type XhrConnectionOptions, clientTools, convertMessagesToModelMessages, createAIDevtoolsGenerationPreview, createChatClientOptions, createMcpAppBridge, defaultJSONParser, fetchHttpStream, fetchJson, fetchServerSentEvents, generateMessageId, getWebMCPTools, indexedDBPersistence, localStoragePersistence, modelMessageToUIMessage, modelMessagesToUIMessages, normalizeToUIMessage, parsePartialJSON, reconstructAudioResult, reconstructImageResult, reconstructSpeechResult, reconstructSummarizeResult, reconstructTranscriptionResult, registerWebMCPTools, rpcStream, sessionStoragePersistence, stream, subscribeWebMCPTools, uiMessageToModelMessages, webSocket, xhrHttpStream, xhrServerSentEvents };
573
+ export { type AudioGenerateInput, AudioRecorder, BatchStrategy, ChatClient, type ChatClientPersistence, type ChatPersistedState, type ChatPersistenceOption, type ChatRequestBody, type ChatStorageAdapter, CompositeStrategy, type ConnectConnectionAdapter, type ConnectionAdapter, type CreateMcpAppBridgeOptions, type DeepPartial, DurableStreamIncompleteError, type FetchConnectionOptions, type FetchJsonOptions, GENERATION_EVENTS, GenerationClient, type GenerationClientState, type GetWebMCPToolsOptions, type ImageGenerateInput, ImmediateStrategy, type IndexedDBPersistenceOptions, type InferChatMessages, type InjectAudioRecorderOptions, type InjectAudioRecorderResult, type InjectChatOptions, type InjectChatResult, type InjectGenerate3DModelOptions, type InjectGenerate3DModelResult, type InjectGenerateAudioOptions, type InjectGenerateAudioResult, type InjectGenerateImageOptions, type InjectGenerateImageResult, type InjectGenerateSpeechOptions, type InjectGenerateSpeechResult, type InjectGenerateVideoOptions, type InjectGenerateVideoResult, type InjectGenerationOptions, type InjectGenerationResult, type InjectPageWebMCPToolsOptions, type InjectRegisterWebMCPToolsOptions, type InjectSummarizeOptions, type InjectSummarizeResult, type InjectTranscriptionOptions, type InjectTranscriptionResult, InterruptManager, type McpAppBridge, type Model3DGenerateInput, type MultimodalContent, PartialJSONParser, PunctuationStrategy, type QueueConfig, type QueueOption, type QueueStrategy, type QueuedMessage, type ReactiveOption, RealtimeClient, type RunAgentInputContext, type SendMessageOptions, type SpeechGenerateInput, StorageUnavailableError, StreamProcessor, StreamReconnectLimitError, StreamTruncatedError, type SubscribeConnectionAdapter, type SubscribeWebMCPToolsOptions, type SummarizeGenerateInput, type TranscriptionGenerateInput, type UIMessage, UnsupportedResponseStreamError, type VideoGenerateInput, type VideoGenerateResult, VideoGenerationClient, type VideoStatusInfo, type WebMCPPageTool, type WebSocketConnectionOptions, type WebStoragePersistenceOptions, type WhenBusy, WordBoundaryStrategy, type XhrConnectionOptions, clientTools, convertMessagesToModelMessages, createAIDevtoolsGenerationPreview, createChatClientOptions, createMcpAppBridge, defaultJSONParser, fetchHttpStream, fetchJson, fetchServerSentEvents, generateMessageId, getWebMCPTools, indexedDBPersistence, localStoragePersistence, modelMessageToUIMessage, modelMessagesToUIMessages, normalizeToUIMessage, parsePartialJSON, reconstructAudioResult, reconstructImageResult, reconstructSpeechResult, reconstructSummarizeResult, reconstructTranscriptionResult, registerWebMCPTools, rpcStream, sessionStoragePersistence, stream, subscribeWebMCPTools, uiMessageToModelMessages, webSocket, xhrHttpStream, xhrServerSentEvents };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/ai-angular",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "Angular signals integration for TanStack AI streaming chat, structured outputs, and media generation.",
5
5
  "author": "",
6
6
  "license": "MIT",
@@ -54,12 +54,12 @@
54
54
  ],
55
55
  "dependencies": {
56
56
  "tslib": "^2.8.1",
57
- "@tanstack/ai-client": "^1.1.0"
57
+ "@tanstack/ai-client": "^1.2.0"
58
58
  },
59
59
  "peerDependencies": {
60
60
  "@angular/common": ">=22.0.0 <23",
61
61
  "@angular/core": ">=22.0.0 <23",
62
- "@tanstack/ai": "^1.2.0"
62
+ "@tanstack/ai": "^1.7.0"
63
63
  },
64
64
  "devDependencies": {
65
65
  "@analogjs/vite-plugin-angular": "^2.9.6",
@@ -74,10 +74,10 @@
74
74
  "jsdom": "^27.4.0",
75
75
  "ng-packagr": "^22.2.1",
76
76
  "typescript": "6.0.2",
77
- "vitest": "^4.1.10",
77
+ "vitest": "^4.1.12",
78
78
  "zod": "^4.2.0",
79
79
  "zone.js": "^0.15.0",
80
- "@tanstack/ai": "1.2.0"
80
+ "@tanstack/ai": "1.7.0"
81
81
  },
82
82
  "scripts": {
83
83
  "clean": "premove ./build ./dist",
package/src/index.ts CHANGED
@@ -26,6 +26,13 @@ export type {
26
26
  InjectGenerateImageResult,
27
27
  } from './inject-generate-image'
28
28
 
29
+ // Generate 3D Model (experimental)
30
+ export { injectGenerate3DModel } from './inject-generate-3d-model'
31
+ export type {
32
+ InjectGenerate3DModelOptions,
33
+ InjectGenerate3DModelResult,
34
+ } from './inject-generate-3d-model'
35
+
29
36
  // Generate Audio
30
37
  export { injectGenerateAudio } from './inject-generate-audio'
31
38
  export type {
@@ -166,4 +173,5 @@ export {
166
173
  type VideoGenerateInput,
167
174
  type VideoGenerateResult,
168
175
  type VideoStatusInfo,
176
+ type Model3DGenerateInput,
169
177
  } from '@tanstack/ai-client'
@@ -0,0 +1,92 @@
1
+ import { injectGeneration } from './inject-generation'
2
+ import type { Signal } from '@angular/core'
3
+ import type { Model3DResult } from '@tanstack/ai'
4
+ import type {
5
+ GenerationClientState,
6
+ InferGenerationOutputFromReturn,
7
+ Model3DGenerateInput,
8
+ } from '@tanstack/ai-client'
9
+ import type {
10
+ InjectGenerationOptions,
11
+ InjectGenerationResult,
12
+ } from './inject-generation'
13
+
14
+ /**
15
+ * Options for {@link injectGenerate3DModel}.
16
+ *
17
+ * @experimental 3D model generation is experimental. The shape can change in
18
+ * a minor release.
19
+ */
20
+ export type InjectGenerate3DModelOptions<TOutput = Model3DResult> = Omit<
21
+ InjectGenerationOptions<Model3DGenerateInput, Model3DResult, TOutput>,
22
+ | 'onResult'
23
+ | 'reconstructResult'
24
+ | 'persistence'
25
+ | 'hydrateGeneration'
26
+ | 'joinRun'
27
+ > & {
28
+ onResult?: (result: Model3DResult) => TOutput | null | void
29
+ }
30
+
31
+ /**
32
+ * Return type of {@link injectGenerate3DModel}.
33
+ *
34
+ * @experimental 3D model generation is experimental. The shape can change in
35
+ * a minor release.
36
+ */
37
+ export interface InjectGenerate3DModelResult<
38
+ TOutput = Model3DResult,
39
+ > extends Omit<InjectGenerationResult<TOutput>, 'generate'> {
40
+ generate: (input: Model3DGenerateInput) => Promise<void>
41
+ result: Signal<TOutput | null>
42
+ isLoading: Signal<boolean>
43
+ error: Signal<Error | undefined>
44
+ status: Signal<GenerationClientState>
45
+ }
46
+
47
+ /**
48
+ * Generates a 3D model from a text or image prompt, with Angular signals.
49
+ *
50
+ * The server route runs `generate3DModel()` and streams the response. The
51
+ * stream sends `generation:progress` events while the provider job runs, then
52
+ * one `generation:result` event with the `Model3DResult`. Call it in an
53
+ * injection context (a component field initializer, the constructor, or
54
+ * `runInInjectionContext`).
55
+ *
56
+ * @param options - A `connection` (streaming) or a `fetcher` (one request),
57
+ * a `threadId`, and optional callbacks (`onResult`, `onProgress`, `onError`).
58
+ * If `onResult` returns a value, `result` holds that value.
59
+ *
60
+ * @example
61
+ * ```ts
62
+ * model = injectGenerate3DModel({
63
+ * threadId: 'product-model',
64
+ * connection: fetchServerSentEvents('/api/generate/3d-model'),
65
+ * })
66
+ *
67
+ * this.model.generate({ prompt: 'A low-poly wooden chair' })
68
+ * // this.model.result()?.url is the GLB file
69
+ * ```
70
+ *
71
+ * @experimental 3D model generation is experimental. The shape can change in
72
+ * a minor release.
73
+ */
74
+ export function injectGenerate3DModel<TTransformed = void>(
75
+ options: Omit<InjectGenerate3DModelOptions, 'onResult'> & {
76
+ onResult?: (result: Model3DResult) => TTransformed
77
+ },
78
+ ): InjectGenerate3DModelResult<
79
+ InferGenerationOutputFromReturn<Model3DResult, TTransformed>
80
+ > {
81
+ const devtools = {
82
+ ...options.devtools,
83
+ framework: 'angular' as const,
84
+ hookName: 'injectGenerate3DModel',
85
+ }
86
+ return injectGeneration<Model3DGenerateInput, Model3DResult, TTransformed>({
87
+ ...options,
88
+ devtools,
89
+ // 3D results are never persisted, even if an untyped caller sets it.
90
+ persistence: false,
91
+ })
92
+ }