@tanstack/ai-react 0.15.14 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/esm/index.d.ts +23 -0
  2. package/dist/esm/index.js +34 -0
  3. package/dist/esm/index.js.map +1 -0
  4. package/dist/esm/mcp-apps.d.ts +20 -0
  5. package/dist/esm/mcp-apps.js +52 -0
  6. package/dist/esm/mcp-apps.js.map +1 -0
  7. package/dist/esm/realtime-types.d.ts +109 -0
  8. package/dist/esm/types.d.ts +150 -0
  9. package/dist/esm/use-audio-recorder.d.ts +43 -0
  10. package/dist/esm/use-audio-recorder.js +49 -0
  11. package/dist/esm/use-audio-recorder.js.map +1 -0
  12. package/dist/esm/use-chat.d.ts +4 -0
  13. package/dist/esm/use-chat.js +258 -0
  14. package/dist/esm/use-chat.js.map +1 -0
  15. package/dist/esm/use-generate-audio.d.ts +87 -0
  16. package/dist/esm/use-generate-audio.js +26 -0
  17. package/dist/esm/use-generate-audio.js.map +1 -0
  18. package/dist/esm/use-generate-image.d.ts +89 -0
  19. package/dist/esm/use-generate-image.js +26 -0
  20. package/dist/esm/use-generate-image.js.map +1 -0
  21. package/dist/esm/use-generate-speech.d.ts +83 -0
  22. package/dist/esm/use-generate-speech.js +26 -0
  23. package/dist/esm/use-generate-speech.js.map +1 -0
  24. package/dist/esm/use-generate-video.d.ts +94 -0
  25. package/dist/esm/use-generate-video.js +107 -0
  26. package/dist/esm/use-generate-video.js.map +1 -0
  27. package/dist/esm/use-generation.d.ts +80 -0
  28. package/dist/esm/use-generation.js +94 -0
  29. package/dist/esm/use-generation.js.map +1 -0
  30. package/dist/esm/use-mcp-app-bridge.d.ts +25 -0
  31. package/dist/esm/use-mcp-app-bridge.js +26 -0
  32. package/dist/esm/use-mcp-app-bridge.js.map +1 -0
  33. package/dist/esm/use-realtime-chat.d.ts +42 -0
  34. package/dist/esm/use-realtime-chat.js +189 -0
  35. package/dist/esm/use-realtime-chat.js.map +1 -0
  36. package/dist/esm/use-summarize.d.ts +86 -0
  37. package/dist/esm/use-summarize.js +26 -0
  38. package/dist/esm/use-summarize.js.map +1 -0
  39. package/dist/esm/use-transcription.d.ts +91 -0
  40. package/dist/esm/use-transcription.js +23 -0
  41. package/dist/esm/use-transcription.js.map +1 -0
  42. package/package.json +15 -4
  43. package/src/index.ts +11 -0
  44. package/src/mcp-apps.tsx +88 -0
  45. package/src/use-audio-recorder.ts +112 -0
  46. package/src/use-generate-audio.ts +5 -8
  47. package/src/use-generate-image.ts +5 -8
  48. package/src/use-generate-speech.ts +7 -7
  49. package/src/use-generate-video.ts +18 -9
  50. package/src/use-generation.ts +17 -6
  51. package/src/use-mcp-app-bridge.ts +60 -0
  52. package/src/use-summarize.ts +7 -8
  53. package/src/use-transcription.ts +9 -11
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-generate-speech.js","sources":["../../src/use-generate-speech.ts"],"sourcesContent":["import { useGeneration } from './use-generation'\nimport type { StreamChunk, TTSResult } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n InferGenerationOutputFromReturn,\n SpeechGenerateInput,\n} from '@tanstack/ai-client'\n\n/**\n * Options for the useGenerateSpeech hook.\n *\n * @template TOutput - The output type after optional transform (defaults to TTSResult)\n */\nexport interface UseGenerateSpeechOptions<TOutput = TTSResult> {\n /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */\n connection?: ConnectConnectionAdapter\n /** Direct async function for speech generation */\n fetcher?: GenerationFetcher<SpeechGenerateInput, TTSResult>\n /** Unique identifier for this generation instance */\n id?: string\n /** Additional body parameters to send with connect-based adapter requests */\n body?: Record<string, any>\n /** Display options for TanStack AI Devtools. */\n devtools?: AIDevtoolsDisplayOptions\n /**\n * Callback when speech 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: TTSResult) => 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 useGenerateSpeech hook.\n *\n * @template TOutput - The output type (after optional transform)\n */\nexport interface UseGenerateSpeechReturn<TOutput = TTSResult> {\n /** Trigger speech generation */\n generate: (input: SpeechGenerateInput) => Promise<void>\n /** The TTS result containing audio data, or null */\n result: TOutput | null\n /** Whether generation is in progress */\n isLoading: boolean\n /** Current error, if any */\n error: Error | undefined\n /** Current state of the generation */\n status: GenerationClientState\n /** Abort the current generation */\n stop: () => void\n /** Clear result, error, and return to idle */\n reset: () => void\n}\n\n/**\n * React hook for generating speech (text-to-speech) using AI models.\n *\n * @example\n * ```tsx\n * import { useGenerateSpeech } from '@tanstack/ai-react'\n * import { fetchServerSentEvents } from '@tanstack/ai-client'\n *\n * function SpeechGenerator() {\n * const { generate, result, isLoading } = useGenerateSpeech({\n * connection: fetchServerSentEvents('/api/generate/speech'),\n * })\n *\n * return (\n * <div>\n * <button onClick={() => generate({ text: 'Hello world', voice: 'alloy' })}>\n * Generate Speech\n * </button>\n * {result && (\n * <audio src={`data:audio/${result.format};base64,${result.audio}`} controls />\n * )}\n * </div>\n * )\n * }\n * ```\n */\nexport function useGenerateSpeech<TTransformed = void>(\n options: Omit<UseGenerateSpeechOptions, 'onResult'> & {\n onResult?: (result: TTSResult) => TTransformed\n },\n): UseGenerateSpeechReturn<\n InferGenerationOutputFromReturn<TTSResult, TTransformed>\n> {\n const devtools = {\n ...options.devtools,\n framework: 'react',\n hookName: 'useGenerateSpeech',\n outputKind: 'audio' as const,\n }\n const { generate, result, isLoading, error, status, stop, reset } =\n useGeneration<SpeechGenerateInput, TTSResult, TTransformed>({\n ...options,\n devtools,\n })\n\n return {\n generate: generate as (input: SpeechGenerateInput) => Promise<void>,\n result,\n isLoading,\n error,\n status,\n stop,\n reset,\n }\n}\n"],"names":[],"mappings":";AA2FO,SAAS,kBACd,SAKA;AACA,QAAM,WAAW;AAAA,IACf,GAAG,QAAQ;AAAA,IACX,WAAW;AAAA,IACX,UAAU;AAAA,IACV,YAAY;AAAA,EAAA;AAEd,QAAM,EAAE,UAAU,QAAQ,WAAW,OAAO,QAAQ,MAAM,MAAA,IACxD,cAA4D;AAAA,IAC1D,GAAG;AAAA,IACH;AAAA,EAAA,CACD;AAEH,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAEJ;"}
@@ -0,0 +1,94 @@
1
+ import { StreamChunk } from '@tanstack/ai';
2
+ import { AIDevtoolsDisplayOptions, ConnectConnectionAdapter, GenerationClientState, GenerationFetcher, InferGenerationOutputFromReturn, VideoGenerateInput, VideoGenerateResult, VideoStatusInfo } from '@tanstack/ai-client';
3
+ /**
4
+ * Options for the useGenerateVideo hook.
5
+ */
6
+ export interface UseGenerateVideoOptions<TOutput = VideoGenerateResult> {
7
+ /** Connect-based adapter for streaming transport (server handles polling) */
8
+ connection?: ConnectConnectionAdapter;
9
+ /** Direct async function that returns a completed video result */
10
+ fetcher?: GenerationFetcher<VideoGenerateInput, VideoGenerateResult>;
11
+ /** Unique identifier for this generation instance */
12
+ id?: string;
13
+ /** Additional body parameters to send with connect-based adapter requests */
14
+ body?: Record<string, any>;
15
+ /** Display options for TanStack AI Devtools. */
16
+ devtools?: AIDevtoolsDisplayOptions;
17
+ /**
18
+ * Callback when video generation completes. Can optionally return a transformed value.
19
+ *
20
+ * - Return a non-null value to transform and store it as the result
21
+ * - Return `null` to keep the previous result unchanged
22
+ * - Return nothing (`void`) to store the raw result as-is
23
+ */
24
+ onResult?: (result: VideoGenerateResult) => TOutput | null | void;
25
+ /** Callback when an error occurs */
26
+ onError?: (error: Error) => void;
27
+ /** Callback when progress is reported (0-100) */
28
+ onProgress?: (progress: number, message?: string) => void;
29
+ /** Callback when a video job is created */
30
+ onJobCreated?: (jobId: string) => void;
31
+ /** Callback on each status update */
32
+ onStatusUpdate?: (status: VideoStatusInfo) => void;
33
+ /** Callback for each stream chunk (connect-based adapter mode only) */
34
+ onChunk?: (chunk: StreamChunk) => void;
35
+ }
36
+ /**
37
+ * Return type for the useGenerateVideo hook.
38
+ *
39
+ * @template TOutput - The output type (after optional transform)
40
+ */
41
+ export interface UseGenerateVideoReturn<TOutput = VideoGenerateResult> {
42
+ /** Trigger video generation */
43
+ generate: (input: VideoGenerateInput) => Promise<void>;
44
+ /** The final video result (with URL), or null */
45
+ result: TOutput | null;
46
+ /** The current job ID, or null */
47
+ jobId: string | null;
48
+ /** Current video generation status info, or null */
49
+ videoStatus: VideoStatusInfo | null;
50
+ /** Whether generation/polling is in progress */
51
+ isLoading: boolean;
52
+ /** Current error, if any */
53
+ error: Error | undefined;
54
+ /** Current state of the generation */
55
+ status: GenerationClientState;
56
+ /** Abort the current generation/polling */
57
+ stop: () => void;
58
+ /** Clear all state and return to idle */
59
+ reset: () => void;
60
+ }
61
+ /**
62
+ * React hook for generating videos using AI models.
63
+ *
64
+ * Video generation is asynchronous: a job is created, then polled for status
65
+ * until completion. This hook handles the full lifecycle.
66
+ *
67
+ * @example
68
+ * ```tsx
69
+ * import { useGenerateVideo } from '@tanstack/ai-react'
70
+ * import { fetchServerSentEvents } from '@tanstack/ai-client'
71
+ *
72
+ * function VideoGenerator() {
73
+ * const { generate, result, videoStatus, isLoading } = useGenerateVideo({
74
+ * connection: fetchServerSentEvents('/api/generate/video'),
75
+ * onStatusUpdate: (status) => console.log(`Progress: ${status.progress}%`),
76
+ * })
77
+ *
78
+ * return (
79
+ * <div>
80
+ * <button onClick={() => generate({ prompt: 'A flying car over a city' })}>
81
+ * Generate Video
82
+ * </button>
83
+ * {isLoading && videoStatus && (
84
+ * <p>Status: {videoStatus.status} ({videoStatus.progress}%)</p>
85
+ * )}
86
+ * {result && <video src={result.url} controls />}
87
+ * </div>
88
+ * )
89
+ * }
90
+ * ```
91
+ */
92
+ export declare function useGenerateVideo<TTransformed = void>(options: Omit<UseGenerateVideoOptions, 'onResult'> & {
93
+ onResult?: (result: VideoGenerateResult) => TTransformed;
94
+ }): UseGenerateVideoReturn<InferGenerationOutputFromReturn<VideoGenerateResult, TTransformed>>;
@@ -0,0 +1,107 @@
1
+ import { VideoGenerationClient } from "@tanstack/ai-client";
2
+ import { createVideoDevtoolsBridge } from "@tanstack/ai-client/devtools";
3
+ import { useId, useState, useRef, useMemo, useEffect, useCallback } from "react";
4
+ function useGenerateVideo(options) {
5
+ const hookId = useId();
6
+ const clientId = options.id || hookId;
7
+ const [result, setResult] = useState(null);
8
+ const [jobId, setJobId] = useState(null);
9
+ const [videoStatus, setVideoStatus] = useState(null);
10
+ const [isLoading, setIsLoading] = useState(false);
11
+ const [error, setError] = useState(void 0);
12
+ const [status, setStatus] = useState("idle");
13
+ const optionsRef = useRef(options);
14
+ optionsRef.current = options;
15
+ const client = useMemo(() => {
16
+ const opts = optionsRef.current;
17
+ const baseOptions = {
18
+ id: clientId,
19
+ body: opts.body,
20
+ devtoolsBridgeFactory: createVideoDevtoolsBridge,
21
+ devtools: {
22
+ ...opts.devtools,
23
+ framework: "react",
24
+ hookName: "useGenerateVideo",
25
+ outputKind: "video"
26
+ },
27
+ // The transform's raw return type (`TTransformed`) and the stored output
28
+ // (`TOutput`, with null/void/undefined stripped) are identical at runtime;
29
+ // the cast bridges the relationship that the conditional type hides.
30
+ onResult: ((r) => optionsRef.current.onResult?.(r)),
31
+ onError: (e) => {
32
+ optionsRef.current.onError?.(e);
33
+ },
34
+ onProgress: (p, m) => {
35
+ optionsRef.current.onProgress?.(p, m);
36
+ },
37
+ onChunk: (c) => {
38
+ optionsRef.current.onChunk?.(c);
39
+ },
40
+ onJobCreated: (id) => {
41
+ optionsRef.current.onJobCreated?.(id);
42
+ },
43
+ onStatusUpdate: (s) => {
44
+ optionsRef.current.onStatusUpdate?.(s);
45
+ },
46
+ onResultChange: setResult,
47
+ onLoadingChange: setIsLoading,
48
+ onErrorChange: setError,
49
+ onStatusChange: setStatus,
50
+ onJobIdChange: setJobId,
51
+ onVideoStatusChange: setVideoStatus
52
+ };
53
+ if (opts.connection) {
54
+ return new VideoGenerationClient({
55
+ ...baseOptions,
56
+ connection: opts.connection
57
+ });
58
+ }
59
+ if (opts.fetcher) {
60
+ return new VideoGenerationClient({
61
+ ...baseOptions,
62
+ fetcher: opts.fetcher
63
+ });
64
+ }
65
+ throw new Error(
66
+ "useGenerateVideo requires either a connection or fetcher option"
67
+ );
68
+ }, [clientId]);
69
+ useEffect(() => {
70
+ client.updateOptions({
71
+ ...options.body !== void 0 && { body: options.body }
72
+ });
73
+ }, [client, options.body]);
74
+ useEffect(() => {
75
+ client.mountDevtools();
76
+ return () => {
77
+ client.dispose();
78
+ };
79
+ }, [client]);
80
+ const generate = useCallback(
81
+ async (input) => {
82
+ await client.generate(input);
83
+ },
84
+ [client]
85
+ );
86
+ const stop = useCallback(() => {
87
+ client.stop();
88
+ }, [client]);
89
+ const reset = useCallback(() => {
90
+ client.reset();
91
+ }, [client]);
92
+ return {
93
+ generate,
94
+ result,
95
+ jobId,
96
+ videoStatus,
97
+ isLoading,
98
+ error,
99
+ status,
100
+ stop,
101
+ reset
102
+ };
103
+ }
104
+ export {
105
+ useGenerateVideo
106
+ };
107
+ //# sourceMappingURL=use-generate-video.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-generate-video.js","sources":["../../src/use-generate-video.ts"],"sourcesContent":["import { VideoGenerationClient } from '@tanstack/ai-client'\nimport { createVideoDevtoolsBridge } from '@tanstack/ai-client/devtools'\nimport { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'\nimport type { StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n InferGenerationOutputFromReturn,\n VideoGenerateInput,\n VideoGenerateResult,\n VideoStatusInfo,\n} from '@tanstack/ai-client'\n\n/**\n * Options for the useGenerateVideo hook.\n */\nexport interface UseGenerateVideoOptions<TOutput = VideoGenerateResult> {\n /** Connect-based adapter for streaming transport (server handles polling) */\n connection?: ConnectConnectionAdapter\n /** Direct async function that returns a completed video result */\n fetcher?: GenerationFetcher<VideoGenerateInput, VideoGenerateResult>\n /** Unique identifier for this generation instance */\n id?: string\n /** Additional body parameters to send with connect-based adapter requests */\n body?: Record<string, any>\n /** Display options for TanStack AI Devtools. */\n devtools?: AIDevtoolsDisplayOptions\n /**\n * Callback when video generation completes. 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: VideoGenerateResult) => 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 when a video job is created */\n onJobCreated?: (jobId: string) => void\n /** Callback on each status update */\n onStatusUpdate?: (status: VideoStatusInfo) => 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 useGenerateVideo hook.\n *\n * @template TOutput - The output type (after optional transform)\n */\nexport interface UseGenerateVideoReturn<TOutput = VideoGenerateResult> {\n /** Trigger video generation */\n generate: (input: VideoGenerateInput) => Promise<void>\n /** The final video result (with URL), or null */\n result: TOutput | null\n /** The current job ID, or null */\n jobId: string | null\n /** Current video generation status info, or null */\n videoStatus: VideoStatusInfo | null\n /** Whether generation/polling is in progress */\n isLoading: boolean\n /** Current error, if any */\n error: Error | undefined\n /** Current state of the generation */\n status: GenerationClientState\n /** Abort the current generation/polling */\n stop: () => void\n /** Clear all state and return to idle */\n reset: () => void\n}\n\n/**\n * React hook for generating videos using AI models.\n *\n * Video generation is asynchronous: a job is created, then polled for status\n * until completion. This hook handles the full lifecycle.\n *\n * @example\n * ```tsx\n * import { useGenerateVideo } from '@tanstack/ai-react'\n * import { fetchServerSentEvents } from '@tanstack/ai-client'\n *\n * function VideoGenerator() {\n * const { generate, result, videoStatus, isLoading } = useGenerateVideo({\n * connection: fetchServerSentEvents('/api/generate/video'),\n * onStatusUpdate: (status) => console.log(`Progress: ${status.progress}%`),\n * })\n *\n * return (\n * <div>\n * <button onClick={() => generate({ prompt: 'A flying car over a city' })}>\n * Generate Video\n * </button>\n * {isLoading && videoStatus && (\n * <p>Status: {videoStatus.status} ({videoStatus.progress}%)</p>\n * )}\n * {result && <video src={result.url} controls />}\n * </div>\n * )\n * }\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 useGenerateVideo<TTransformed = void>(\n options: Omit<UseGenerateVideoOptions, 'onResult'> & {\n onResult?: (result: VideoGenerateResult) => TTransformed\n },\n): UseGenerateVideoReturn<\n InferGenerationOutputFromReturn<VideoGenerateResult, TTransformed>\n> {\n type TOutput = InferGenerationOutputFromReturn<\n VideoGenerateResult,\n TTransformed\n >\n const hookId = useId()\n const clientId = options.id || hookId\n\n const [result, setResult] = useState<TOutput | null>(null)\n const [jobId, setJobId] = useState<string | null>(null)\n const [videoStatus, setVideoStatus] = useState<VideoStatusInfo | null>(null)\n const [isLoading, setIsLoading] = useState(false)\n const [error, setError] = useState<Error | undefined>(undefined)\n const [status, setStatus] = useState<GenerationClientState>('idle')\n\n const optionsRef = useRef(options)\n optionsRef.current = options\n\n const client = useMemo(() => {\n const opts = optionsRef.current\n\n // Conditional spread for `body` (strict-optional in target).\n // Optional callbacks are wrapped in non-returning bodies so\n // `?.()`'s implicit `undefined` doesn't widen the function\n // return type (which `exactOptionalPropertyTypes` rejects\n // against the strict-optional target).\n const baseOptions = {\n id: clientId,\n body: opts.body,\n devtoolsBridgeFactory: createVideoDevtoolsBridge,\n devtools: {\n ...opts.devtools,\n framework: 'react',\n hookName: 'useGenerateVideo',\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) =>\n optionsRef.current.onResult?.(r)) as (\n result: VideoGenerateResult,\n ) => TOutput | null | void,\n onError: (e: Error) => {\n optionsRef.current.onError?.(e)\n },\n onProgress: (p: number, m?: string) => {\n optionsRef.current.onProgress?.(p, m)\n },\n onChunk: (c: StreamChunk) => {\n optionsRef.current.onChunk?.(c)\n },\n onJobCreated: (id: string) => {\n optionsRef.current.onJobCreated?.(id)\n },\n onStatusUpdate: (s: VideoStatusInfo) => {\n optionsRef.current.onStatusUpdate?.(s)\n },\n onResultChange: setResult,\n onLoadingChange: setIsLoading,\n onErrorChange: setError,\n onStatusChange: setStatus,\n onJobIdChange: setJobId,\n onVideoStatusChange: setVideoStatus,\n }\n\n if (opts.connection) {\n return new VideoGenerationClient<TOutput>({\n ...baseOptions,\n connection: opts.connection,\n })\n }\n\n if (opts.fetcher) {\n return new VideoGenerationClient<TOutput>({\n ...baseOptions,\n fetcher: opts.fetcher,\n })\n }\n\n throw new Error(\n 'useGenerateVideo requires either a connection or fetcher option',\n )\n }, [clientId])\n\n // Sync body changes without recreating client\n useEffect(() => {\n // Conditional spread: target uses strict-optional `body?: T`.\n client.updateOptions({\n ...(options.body !== undefined && { body: options.body }),\n })\n }, [client, options.body])\n\n // Cleanup on unmount\n useEffect(() => {\n client.mountDevtools()\n\n return () => {\n client.dispose()\n }\n }, [client])\n\n const generate = useCallback(\n async (input: VideoGenerateInput) => {\n await client.generate(input)\n },\n [client],\n )\n\n const stop = useCallback(() => {\n client.stop()\n }, [client])\n\n const reset = useCallback(() => {\n client.reset()\n }, [client])\n\n return {\n generate,\n result,\n jobId,\n videoStatus,\n isLoading,\n error,\n status,\n stop,\n reset,\n }\n}\n"],"names":[],"mappings":";;;AA6GO,SAAS,iBACd,SAKA;AAKA,QAAM,SAAS,MAAA;AACf,QAAM,WAAW,QAAQ,MAAM;AAE/B,QAAM,CAAC,QAAQ,SAAS,IAAI,SAAyB,IAAI;AACzD,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAwB,IAAI;AACtD,QAAM,CAAC,aAAa,cAAc,IAAI,SAAiC,IAAI;AAC3E,QAAM,CAAC,WAAW,YAAY,IAAI,SAAS,KAAK;AAChD,QAAM,CAAC,OAAO,QAAQ,IAAI,SAA4B,MAAS;AAC/D,QAAM,CAAC,QAAQ,SAAS,IAAI,SAAgC,MAAM;AAElE,QAAM,aAAa,OAAO,OAAO;AACjC,aAAW,UAAU;AAErB,QAAM,SAAS,QAAQ,MAAM;AAC3B,UAAM,OAAO,WAAW;AAOxB,UAAM,cAAc;AAAA,MAClB,IAAI;AAAA,MACJ,MAAM,KAAK;AAAA,MACX,uBAAuB;AAAA,MACvB,UAAU;AAAA,QACR,GAAG,KAAK;AAAA,QACR,WAAW;AAAA,QACX,UAAU;AAAA,QACV,YAAY;AAAA,MAAA;AAAA;AAAA;AAAA;AAAA,MAKd,WAAW,CAAC,MACV,WAAW,QAAQ,WAAW,CAAC;AAAA,MAGjC,SAAS,CAAC,MAAa;AACrB,mBAAW,QAAQ,UAAU,CAAC;AAAA,MAChC;AAAA,MACA,YAAY,CAAC,GAAW,MAAe;AACrC,mBAAW,QAAQ,aAAa,GAAG,CAAC;AAAA,MACtC;AAAA,MACA,SAAS,CAAC,MAAmB;AAC3B,mBAAW,QAAQ,UAAU,CAAC;AAAA,MAChC;AAAA,MACA,cAAc,CAAC,OAAe;AAC5B,mBAAW,QAAQ,eAAe,EAAE;AAAA,MACtC;AAAA,MACA,gBAAgB,CAAC,MAAuB;AACtC,mBAAW,QAAQ,iBAAiB,CAAC;AAAA,MACvC;AAAA,MACA,gBAAgB;AAAA,MAChB,iBAAiB;AAAA,MACjB,eAAe;AAAA,MACf,gBAAgB;AAAA,MAChB,eAAe;AAAA,MACf,qBAAqB;AAAA,IAAA;AAGvB,QAAI,KAAK,YAAY;AACnB,aAAO,IAAI,sBAA+B;AAAA,QACxC,GAAG;AAAA,QACH,YAAY,KAAK;AAAA,MAAA,CAClB;AAAA,IACH;AAEA,QAAI,KAAK,SAAS;AAChB,aAAO,IAAI,sBAA+B;AAAA,QACxC,GAAG;AAAA,QACH,SAAS,KAAK;AAAA,MAAA,CACf;AAAA,IACH;AAEA,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAAA,EAEJ,GAAG,CAAC,QAAQ,CAAC;AAGb,YAAU,MAAM;AAEd,WAAO,cAAc;AAAA,MACnB,GAAI,QAAQ,SAAS,UAAa,EAAE,MAAM,QAAQ,KAAA;AAAA,IAAK,CACxD;AAAA,EACH,GAAG,CAAC,QAAQ,QAAQ,IAAI,CAAC;AAGzB,YAAU,MAAM;AACd,WAAO,cAAA;AAEP,WAAO,MAAM;AACX,aAAO,QAAA;AAAA,IACT;AAAA,EACF,GAAG,CAAC,MAAM,CAAC;AAEX,QAAM,WAAW;AAAA,IACf,OAAO,UAA8B;AACnC,YAAM,OAAO,SAAS,KAAK;AAAA,IAC7B;AAAA,IACA,CAAC,MAAM;AAAA,EAAA;AAGT,QAAM,OAAO,YAAY,MAAM;AAC7B,WAAO,KAAA;AAAA,EACT,GAAG,CAAC,MAAM,CAAC;AAEX,QAAM,QAAQ,YAAY,MAAM;AAC9B,WAAO,MAAA;AAAA,EACT,GAAG,CAAC,MAAM,CAAC;AAEX,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAEJ;"}
@@ -0,0 +1,80 @@
1
+ import { StreamChunk } from '@tanstack/ai';
2
+ import { AIDevtoolsDisplayOptions, ConnectConnectionAdapter, GenerationClientState, GenerationFetcher, InferGenerationOutputFromReturn } from '@tanstack/ai-client';
3
+ /**
4
+ * Options for the useGeneration hook.
5
+ *
6
+ * Accepts either a `connection` (streaming transport) or a `fetcher` (direct async call).
7
+ *
8
+ * @template TInput - The input type for the generation request
9
+ * @template TResult - The result type returned by the generation
10
+ * @template TOutput - The output type after optional transform (defaults to TResult)
11
+ */
12
+ export interface UseGenerationOptions<TInput, TResult, TOutput = TResult> {
13
+ /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */
14
+ connection?: ConnectConnectionAdapter;
15
+ /** Direct async function for one-shot generation (no streaming protocol needed) */
16
+ fetcher?: GenerationFetcher<TInput, TResult>;
17
+ /** Unique identifier for this generation instance */
18
+ id?: string;
19
+ /** Additional body parameters to send with connect-based adapter requests */
20
+ body?: Record<string, any>;
21
+ /** Display options for TanStack AI Devtools. */
22
+ devtools?: AIDevtoolsDisplayOptions;
23
+ /**
24
+ * Callback when a result is received. Can optionally return a transformed value.
25
+ *
26
+ * - Return a non-null value to transform and store it as the result
27
+ * - Return `null` to keep the previous result unchanged
28
+ * - Return nothing (`void`) to store the raw result as-is
29
+ */
30
+ onResult?: (result: TResult) => TOutput | null | void;
31
+ /** Callback when an error occurs */
32
+ onError?: (error: Error) => void;
33
+ /** Callback when progress is reported (0-100) */
34
+ onProgress?: (progress: number, message?: string) => void;
35
+ /** Callback for each stream chunk (connect-based adapter mode only) */
36
+ onChunk?: (chunk: StreamChunk) => void;
37
+ }
38
+ /**
39
+ * Return type for the useGeneration hook.
40
+ *
41
+ * @template TOutput - The output type (after optional transform)
42
+ */
43
+ export interface UseGenerationReturn<TOutput> {
44
+ /** Trigger a generation request */
45
+ generate: (input: Record<string, any>) => Promise<void>;
46
+ /** The generation result, or null if not yet generated */
47
+ result: TOutput | null;
48
+ /** Whether a generation is currently in progress */
49
+ isLoading: boolean;
50
+ /** Current error, if any */
51
+ error: Error | undefined;
52
+ /** Current state of the generation client */
53
+ status: GenerationClientState;
54
+ /** Abort the current generation */
55
+ stop: () => void;
56
+ /** Clear result, error, and return to idle */
57
+ reset: () => void;
58
+ }
59
+ /**
60
+ * Generic React hook for one-shot generation tasks.
61
+ *
62
+ * This is the base hook used by `useGenerateImage`, `useGenerateSpeech`,
63
+ * `useTranscription`, and `useSummarize`. You can also use it directly
64
+ * for custom generation types.
65
+ *
66
+ * @template TInput - The input type for the generation request
67
+ * @template TResult - The result type returned by the generation
68
+ *
69
+ * @example
70
+ * ```tsx
71
+ * const { generate, result, isLoading } = useGeneration<MyInput, MyResult>({
72
+ * connection: fetchServerSentEvents('/api/generate/custom'),
73
+ * })
74
+ *
75
+ * await generate({ prompt: 'Hello' })
76
+ * ```
77
+ */
78
+ export declare function useGeneration<TInput extends Record<string, any>, TResult, TTransformed = void>(options: Omit<UseGenerationOptions<TInput, TResult>, 'onResult'> & {
79
+ onResult?: (result: TResult) => TTransformed;
80
+ }): UseGenerationReturn<InferGenerationOutputFromReturn<TResult, TTransformed>>;
@@ -0,0 +1,94 @@
1
+ import { GenerationClient } from "@tanstack/ai-client";
2
+ import { createGenerationDevtoolsBridge } from "@tanstack/ai-client/devtools";
3
+ import { useId, useState, useRef, useMemo, useEffect, useCallback } from "react";
4
+ function useGeneration(options) {
5
+ const hookId = useId();
6
+ const clientId = options.id || hookId;
7
+ const [result, setResult] = useState(null);
8
+ const [isLoading, setIsLoading] = useState(false);
9
+ const [error, setError] = useState(void 0);
10
+ const [status, setStatus] = useState("idle");
11
+ const optionsRef = useRef(options);
12
+ optionsRef.current = options;
13
+ const client = useMemo(() => {
14
+ const opts = optionsRef.current;
15
+ const clientOptions = {
16
+ id: clientId,
17
+ body: opts.body,
18
+ devtoolsBridgeFactory: createGenerationDevtoolsBridge,
19
+ devtools: {
20
+ hookName: "useGeneration",
21
+ framework: "react",
22
+ ...opts.devtools
23
+ },
24
+ // The transform's raw return type (`TTransformed`) and the stored output
25
+ // (`TOutput`, with null/void/undefined stripped) are identical at runtime;
26
+ // the cast bridges the relationship that the conditional type hides.
27
+ onResult: ((r) => optionsRef.current.onResult?.(r)),
28
+ onError: (e) => {
29
+ optionsRef.current.onError?.(e);
30
+ },
31
+ onProgress: (p, m) => {
32
+ optionsRef.current.onProgress?.(p, m);
33
+ },
34
+ onChunk: (c) => {
35
+ optionsRef.current.onChunk?.(c);
36
+ },
37
+ onResultChange: setResult,
38
+ onLoadingChange: setIsLoading,
39
+ onErrorChange: setError,
40
+ onStatusChange: setStatus
41
+ };
42
+ if (opts.connection) {
43
+ return new GenerationClient({
44
+ ...clientOptions,
45
+ connection: opts.connection
46
+ });
47
+ }
48
+ if (opts.fetcher) {
49
+ return new GenerationClient({
50
+ ...clientOptions,
51
+ fetcher: opts.fetcher
52
+ });
53
+ }
54
+ throw new Error(
55
+ "useGeneration requires either a connection or fetcher option"
56
+ );
57
+ }, [clientId]);
58
+ useEffect(() => {
59
+ client.updateOptions({
60
+ ...options.body !== void 0 && { body: options.body }
61
+ });
62
+ }, [client, options.body]);
63
+ useEffect(() => {
64
+ client.mountDevtools();
65
+ return () => {
66
+ client.dispose();
67
+ };
68
+ }, [client]);
69
+ const generate = useCallback(
70
+ async (input) => {
71
+ await client.generate(input);
72
+ },
73
+ [client]
74
+ );
75
+ const stop = useCallback(() => {
76
+ client.stop();
77
+ }, [client]);
78
+ const reset = useCallback(() => {
79
+ client.reset();
80
+ }, [client]);
81
+ return {
82
+ generate,
83
+ result,
84
+ isLoading,
85
+ error,
86
+ status,
87
+ stop,
88
+ reset
89
+ };
90
+ }
91
+ export {
92
+ useGeneration
93
+ };
94
+ //# sourceMappingURL=use-generation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-generation.js","sources":["../../src/use-generation.ts"],"sourcesContent":["import { GenerationClient } from '@tanstack/ai-client'\nimport { createGenerationDevtoolsBridge } from '@tanstack/ai-client/devtools'\nimport { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'\nimport type { StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientOptions,\n GenerationClientState,\n GenerationFetcher,\n InferGenerationOutputFromReturn,\n} from '@tanstack/ai-client'\n\n/**\n * Options for the useGeneration hook.\n *\n * Accepts either a `connection` (streaming transport) or a `fetcher` (direct async call).\n *\n * @template TInput - The input type for the generation request\n * @template TResult - The result type returned by the generation\n * @template TOutput - The output type after optional transform (defaults to TResult)\n */\nexport interface UseGenerationOptions<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 /** Unique identifier for this generation instance */\n id?: string\n /** Additional body parameters to send with connect-based adapter requests */\n body?: Record<string, any>\n /** Display options for TanStack AI Devtools. */\n devtools?: AIDevtoolsDisplayOptions\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\n/**\n * Return type for the useGeneration hook.\n *\n * @template TOutput - The output type (after optional transform)\n */\nexport interface UseGenerationReturn<TOutput> {\n /** Trigger a generation request */\n generate: (input: Record<string, any>) => Promise<void>\n /** The generation result, or null if not yet generated */\n result: TOutput | null\n /** Whether a generation is currently in progress */\n isLoading: boolean\n /** Current error, if any */\n error: Error | undefined\n /** Current state of the generation client */\n status: GenerationClientState\n /** Abort the current generation */\n stop: () => void\n /** Clear result, error, and return to idle */\n reset: () => void\n}\n\n/**\n * Generic React hook for one-shot generation tasks.\n *\n * This is the base hook used by `useGenerateImage`, `useGenerateSpeech`,\n * `useTranscription`, and `useSummarize`. You can also use it directly\n * for custom generation types.\n *\n * @template TInput - The input type for the generation request\n * @template TResult - The result type returned by the generation\n *\n * @example\n * ```tsx\n * const { generate, result, isLoading } = useGeneration<MyInput, MyResult>({\n * connection: fetchServerSentEvents('/api/generate/custom'),\n * })\n *\n * await generate({ prompt: 'Hello' })\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 useGeneration<\n TInput extends Record<string, any>,\n TResult,\n TTransformed = void,\n>(\n options: Omit<UseGenerationOptions<TInput, TResult>, 'onResult'> & {\n onResult?: (result: TResult) => TTransformed\n },\n): UseGenerationReturn<InferGenerationOutputFromReturn<TResult, TTransformed>> {\n type TOutput = InferGenerationOutputFromReturn<TResult, TTransformed>\n const hookId = useId()\n const clientId = options.id || hookId\n\n const [result, setResult] = useState<TOutput | null>(null)\n const [isLoading, setIsLoading] = useState(false)\n const [error, setError] = useState<Error | undefined>(undefined)\n const [status, setStatus] = useState<GenerationClientState>('idle')\n\n const optionsRef = useRef(options)\n optionsRef.current = options\n\n const client = useMemo(() => {\n const opts = optionsRef.current\n\n // Conditional spread for `body` (strict-optional in target;\n // local source is `Record<string, any> | undefined`). Callbacks\n // wrap optional ones in non-returning bodies so `?.()`'s\n // implicit `undefined` doesn't pollute the function return type.\n const clientOptions: GenerationClientOptions<TInput, TResult, TOutput> = {\n id: clientId,\n body: opts.body,\n devtoolsBridgeFactory: createGenerationDevtoolsBridge,\n devtools: {\n hookName: 'useGeneration',\n framework: 'react',\n ...opts.devtools,\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) => optionsRef.current.onResult?.(r)) as (\n result: TResult,\n ) => TOutput | null | void,\n onError: (e: Error) => {\n optionsRef.current.onError?.(e)\n },\n onProgress: (p: number, m?: string) => {\n optionsRef.current.onProgress?.(p, m)\n },\n onChunk: (c: StreamChunk) => {\n optionsRef.current.onChunk?.(c)\n },\n onResultChange: setResult,\n onLoadingChange: setIsLoading,\n onErrorChange: setError,\n onStatusChange: setStatus,\n }\n\n if (opts.connection) {\n return new GenerationClient<TInput, TResult, TOutput>({\n ...clientOptions,\n connection: opts.connection,\n })\n }\n\n if (opts.fetcher) {\n return new GenerationClient<TInput, TResult, TOutput>({\n ...clientOptions,\n fetcher: opts.fetcher,\n })\n }\n\n throw new Error(\n 'useGeneration requires either a connection or fetcher option',\n )\n }, [clientId])\n\n // Sync body changes without recreating client\n useEffect(() => {\n // Conditional spread: target uses strict-optional `body?: T`.\n client.updateOptions({\n ...(options.body !== undefined && { body: options.body }),\n })\n }, [client, options.body])\n\n // Cleanup on unmount\n useEffect(() => {\n client.mountDevtools()\n\n return () => {\n client.dispose()\n }\n }, [client])\n\n const generate = useCallback(\n async (input: TInput) => {\n await client.generate(input)\n },\n [client],\n )\n\n const stop = useCallback(() => {\n client.stop()\n }, [client])\n\n const reset = useCallback(() => {\n client.reset()\n }, [client])\n\n return {\n generate: generate as (input: Record<string, any>) => Promise<void>,\n result,\n isLoading,\n error,\n status,\n stop,\n reset,\n }\n}\n"],"names":[],"mappings":";;;AAgGO,SAAS,cAKd,SAG6E;AAE7E,QAAM,SAAS,MAAA;AACf,QAAM,WAAW,QAAQ,MAAM;AAE/B,QAAM,CAAC,QAAQ,SAAS,IAAI,SAAyB,IAAI;AACzD,QAAM,CAAC,WAAW,YAAY,IAAI,SAAS,KAAK;AAChD,QAAM,CAAC,OAAO,QAAQ,IAAI,SAA4B,MAAS;AAC/D,QAAM,CAAC,QAAQ,SAAS,IAAI,SAAgC,MAAM;AAElE,QAAM,aAAa,OAAO,OAAO;AACjC,aAAW,UAAU;AAErB,QAAM,SAAS,QAAQ,MAAM;AAC3B,UAAM,OAAO,WAAW;AAMxB,UAAM,gBAAmE;AAAA,MACvE,IAAI;AAAA,MACJ,MAAM,KAAK;AAAA,MACX,uBAAuB;AAAA,MACvB,UAAU;AAAA,QACR,UAAU;AAAA,QACV,WAAW;AAAA,QACX,GAAG,KAAK;AAAA,MAAA;AAAA;AAAA;AAAA;AAAA,MAKV,WAAW,CAAC,MAAe,WAAW,QAAQ,WAAW,CAAC;AAAA,MAG1D,SAAS,CAAC,MAAa;AACrB,mBAAW,QAAQ,UAAU,CAAC;AAAA,MAChC;AAAA,MACA,YAAY,CAAC,GAAW,MAAe;AACrC,mBAAW,QAAQ,aAAa,GAAG,CAAC;AAAA,MACtC;AAAA,MACA,SAAS,CAAC,MAAmB;AAC3B,mBAAW,QAAQ,UAAU,CAAC;AAAA,MAChC;AAAA,MACA,gBAAgB;AAAA,MAChB,iBAAiB;AAAA,MACjB,eAAe;AAAA,MACf,gBAAgB;AAAA,IAAA;AAGlB,QAAI,KAAK,YAAY;AACnB,aAAO,IAAI,iBAA2C;AAAA,QACpD,GAAG;AAAA,QACH,YAAY,KAAK;AAAA,MAAA,CAClB;AAAA,IACH;AAEA,QAAI,KAAK,SAAS;AAChB,aAAO,IAAI,iBAA2C;AAAA,QACpD,GAAG;AAAA,QACH,SAAS,KAAK;AAAA,MAAA,CACf;AAAA,IACH;AAEA,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAAA,EAEJ,GAAG,CAAC,QAAQ,CAAC;AAGb,YAAU,MAAM;AAEd,WAAO,cAAc;AAAA,MACnB,GAAI,QAAQ,SAAS,UAAa,EAAE,MAAM,QAAQ,KAAA;AAAA,IAAK,CACxD;AAAA,EACH,GAAG,CAAC,QAAQ,QAAQ,IAAI,CAAC;AAGzB,YAAU,MAAM;AACd,WAAO,cAAA;AAEP,WAAO,MAAM;AACX,aAAO,QAAA;AAAA,IACT;AAAA,EACF,GAAG,CAAC,MAAM,CAAC;AAEX,QAAM,WAAW;AAAA,IACf,OAAO,UAAkB;AACvB,YAAM,OAAO,SAAS,KAAK;AAAA,IAC7B;AAAA,IACA,CAAC,MAAM;AAAA,EAAA;AAGT,QAAM,OAAO,YAAY,MAAM;AAC7B,WAAO,KAAA;AAAA,EACT,GAAG,CAAC,MAAM,CAAC;AAEX,QAAM,QAAQ,YAAY,MAAM;AAC9B,WAAO,MAAA;AAAA,EACT,GAAG,CAAC,MAAM,CAAC;AAEX,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAEJ;"}
@@ -0,0 +1,25 @@
1
+ import { CreateMcpAppBridgeOptions, McpAppBridge } from '@tanstack/ai-client';
2
+ export type UseMcpAppBridgeOptions = CreateMcpAppBridgeOptions;
3
+ /**
4
+ * React wrapper around `createMcpAppBridge` that returns a **stable** bridge for
5
+ * the given `threadId`/`callEndpoint`, while always invoking the latest
6
+ * `chat.sendMessage` and `onLink` (kept in refs). This avoids both recreating
7
+ * the bridge on every render and the stale-closure / `exhaustive-deps` dance
8
+ * you'd otherwise write by hand:
9
+ *
10
+ * ```tsx
11
+ * const { sendMessage } = useChat({ threadId, connection })
12
+ * const bridge = useMcpAppBridge({
13
+ * threadId,
14
+ * callEndpoint: '/api/mcp-apps-call',
15
+ * chat: { sendMessage: async (content) => void sendMessage(content) },
16
+ * onLink: (url) => window.open(url, '_blank', 'noopener,noreferrer'),
17
+ * })
18
+ * // pass `bridge` to <MCPAppResource bridge={bridge} … />
19
+ * ```
20
+ *
21
+ * The bridge is recreated only when `threadId`, `callEndpoint`, `fetchImpl`, or
22
+ * the *presence* of `onLink` changes — passing a new inline `onLink`/`sendMessage`
23
+ * each render does not churn it.
24
+ */
25
+ export declare function useMcpAppBridge(options: UseMcpAppBridgeOptions): McpAppBridge;
@@ -0,0 +1,26 @@
1
+ import { useRef, useMemo } from "react";
2
+ import { createMcpAppBridge } from "@tanstack/ai-client";
3
+ function useMcpAppBridge(options) {
4
+ const { threadId, callEndpoint, chat, fetchImpl, onLink } = options;
5
+ const chatRef = useRef(chat);
6
+ chatRef.current = chat;
7
+ const onLinkRef = useRef(onLink);
8
+ onLinkRef.current = onLink;
9
+ const hasOnLink = onLink != null;
10
+ return useMemo(
11
+ () => createMcpAppBridge({
12
+ threadId,
13
+ callEndpoint,
14
+ fetchImpl,
15
+ chat: {
16
+ sendMessage: (content, body) => chatRef.current.sendMessage(content, body)
17
+ },
18
+ onLink: hasOnLink ? (url) => onLinkRef.current?.(url) : void 0
19
+ }),
20
+ [threadId, callEndpoint, fetchImpl, hasOnLink]
21
+ );
22
+ }
23
+ export {
24
+ useMcpAppBridge
25
+ };
26
+ //# sourceMappingURL=use-mcp-app-bridge.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-mcp-app-bridge.js","sources":["../../src/use-mcp-app-bridge.ts"],"sourcesContent":["import { useMemo, useRef } from 'react'\nimport { createMcpAppBridge } from '@tanstack/ai-client'\nimport type {\n CreateMcpAppBridgeOptions,\n McpAppBridge,\n} from '@tanstack/ai-client'\n\nexport type UseMcpAppBridgeOptions = CreateMcpAppBridgeOptions\n\n/**\n * React wrapper around `createMcpAppBridge` that returns a **stable** bridge for\n * the given `threadId`/`callEndpoint`, while always invoking the latest\n * `chat.sendMessage` and `onLink` (kept in refs). This avoids both recreating\n * the bridge on every render and the stale-closure / `exhaustive-deps` dance\n * you'd otherwise write by hand:\n *\n * ```tsx\n * const { sendMessage } = useChat({ threadId, connection })\n * const bridge = useMcpAppBridge({\n * threadId,\n * callEndpoint: '/api/mcp-apps-call',\n * chat: { sendMessage: async (content) => void sendMessage(content) },\n * onLink: (url) => window.open(url, '_blank', 'noopener,noreferrer'),\n * })\n * // pass `bridge` to <MCPAppResource bridge={bridge} … />\n * ```\n *\n * The bridge is recreated only when `threadId`, `callEndpoint`, `fetchImpl`, or\n * the *presence* of `onLink` changes — passing a new inline `onLink`/`sendMessage`\n * each render does not churn it.\n */\nexport function useMcpAppBridge(options: UseMcpAppBridgeOptions): McpAppBridge {\n const { threadId, callEndpoint, chat, fetchImpl, onLink } = options\n\n // Latest-value refs so the bridge identity stays stable but its callbacks are\n // never stale (the bridge calls `.current` at invocation time, not creation).\n const chatRef = useRef(chat)\n chatRef.current = chat\n const onLinkRef = useRef(onLink)\n onLinkRef.current = onLink\n\n // Whether a link handler was supplied governs the bridge's link behavior\n // (forward vs. display-only warn), so it's part of the bridge's identity.\n const hasOnLink = onLink != null\n\n return useMemo(\n () =>\n createMcpAppBridge({\n threadId,\n callEndpoint,\n fetchImpl,\n chat: {\n sendMessage: (content, body) =>\n chatRef.current.sendMessage(content, body),\n },\n onLink: hasOnLink ? (url) => onLinkRef.current?.(url) : undefined,\n }),\n [threadId, callEndpoint, fetchImpl, hasOnLink],\n )\n}\n"],"names":[],"mappings":";;AA+BO,SAAS,gBAAgB,SAA+C;AAC7E,QAAM,EAAE,UAAU,cAAc,MAAM,WAAW,WAAW;AAI5D,QAAM,UAAU,OAAO,IAAI;AAC3B,UAAQ,UAAU;AAClB,QAAM,YAAY,OAAO,MAAM;AAC/B,YAAU,UAAU;AAIpB,QAAM,YAAY,UAAU;AAE5B,SAAO;AAAA,IACL,MACE,mBAAmB;AAAA,MACjB;AAAA,MACA;AAAA,MACA;AAAA,MACA,MAAM;AAAA,QACJ,aAAa,CAAC,SAAS,SACrB,QAAQ,QAAQ,YAAY,SAAS,IAAI;AAAA,MAAA;AAAA,MAE7C,QAAQ,YAAY,CAAC,QAAQ,UAAU,UAAU,GAAG,IAAI;AAAA,IAAA,CACzD;AAAA,IACH,CAAC,UAAU,cAAc,WAAW,SAAS;AAAA,EAAA;AAEjD;"}
@@ -0,0 +1,42 @@
1
+ import { UseRealtimeChatOptions, UseRealtimeChatReturn } from './realtime-types.js';
2
+ /**
3
+ * React hook for realtime voice conversations.
4
+ *
5
+ * Provides a simple interface for voice-to-voice AI interactions
6
+ * with support for multiple providers (OpenAI, ElevenLabs, etc.).
7
+ *
8
+ * @param options - Configuration options including adapter and callbacks
9
+ * @returns Hook return value with state and control methods
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * import { useRealtimeChat } from '@tanstack/ai-react'
14
+ * import { openaiRealtime } from '@tanstack/ai-openai'
15
+ *
16
+ * function VoiceChat() {
17
+ * const {
18
+ * status,
19
+ * mode,
20
+ * messages,
21
+ * connect,
22
+ * disconnect,
23
+ * inputLevel,
24
+ * outputLevel,
25
+ * } = useRealtimeChat({
26
+ * getToken: () => fetch('/api/realtime-token').then(r => r.json()),
27
+ * adapter: openaiRealtime(),
28
+ * })
29
+ *
30
+ * return (
31
+ * <div>
32
+ * <p>Status: {status}</p>
33
+ * <p>Mode: {mode}</p>
34
+ * <button onClick={status === 'idle' ? connect : disconnect}>
35
+ * {status === 'idle' ? 'Start' : 'Stop'}
36
+ * </button>
37
+ * </div>
38
+ * )
39
+ * }
40
+ * ```
41
+ */
42
+ export declare function useRealtimeChat(options: UseRealtimeChatOptions): UseRealtimeChatReturn;