@tanstack/ai 0.43.0 → 0.44.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/dist/esm/activities/chat/messages.js +21 -8
- package/dist/esm/activities/chat/messages.js.map +1 -1
- package/dist/esm/activities/embed/adapter.d.ts +69 -0
- package/dist/esm/activities/embed/adapter.js +23 -0
- package/dist/esm/activities/embed/adapter.js.map +1 -0
- package/dist/esm/activities/embed/index.d.ts +117 -0
- package/dist/esm/activities/embed/index.js +166 -0
- package/dist/esm/activities/embed/index.js.map +1 -0
- package/dist/esm/activities/error-payload.d.ts +8 -0
- package/dist/esm/activities/error-payload.js +29 -17
- package/dist/esm/activities/error-payload.js.map +1 -1
- package/dist/esm/activities/generateAudio/index.d.ts +12 -0
- package/dist/esm/activities/generateAudio/index.js +19 -6
- package/dist/esm/activities/generateAudio/index.js.map +1 -1
- package/dist/esm/activities/generateImage/index.d.ts +12 -0
- package/dist/esm/activities/generateImage/index.js +21 -7
- package/dist/esm/activities/generateImage/index.js.map +1 -1
- package/dist/esm/activities/generateSpeech/index.d.ts +17 -1
- package/dist/esm/activities/generateSpeech/index.js +19 -6
- package/dist/esm/activities/generateSpeech/index.js.map +1 -1
- package/dist/esm/activities/generateTranscription/index.d.ts +17 -1
- package/dist/esm/activities/generateTranscription/index.js +19 -6
- package/dist/esm/activities/generateTranscription/index.js.map +1 -1
- package/dist/esm/activities/generateVideo/index.d.ts +18 -0
- package/dist/esm/activities/generateVideo/index.js +54 -15
- package/dist/esm/activities/generateVideo/index.js.map +1 -1
- package/dist/esm/activities/index.d.ts +8 -2
- package/dist/esm/activities/index.js +11 -7
- package/dist/esm/activities/middleware/types.d.ts +1 -1
- package/dist/esm/activities/rerank/adapter.d.ts +63 -0
- package/dist/esm/activities/rerank/adapter.js +23 -0
- package/dist/esm/activities/rerank/adapter.js.map +1 -0
- package/dist/esm/activities/rerank/index.d.ts +92 -0
- package/dist/esm/activities/rerank/index.js +163 -0
- package/dist/esm/activities/rerank/index.js.map +1 -0
- package/dist/esm/activities/summarize/index.d.ts +17 -1
- package/dist/esm/activities/summarize/index.js +19 -5
- package/dist/esm/activities/summarize/index.js.map +1 -1
- package/dist/esm/index.d.ts +7 -2
- package/dist/esm/index.js +5 -1
- package/dist/esm/middlewares/otel.d.ts +3 -1
- package/dist/esm/middlewares/otel.js +25 -6
- package/dist/esm/middlewares/otel.js.map +1 -1
- package/dist/esm/types.d.ts +195 -0
- package/dist/esm/utilities/activity-abort.d.ts +53 -0
- package/dist/esm/utilities/activity-abort.js +150 -0
- package/dist/esm/utilities/activity-abort.js.map +1 -0
- package/dist/esm/utilities/embedding-input.d.ts +32 -0
- package/dist/esm/utilities/embedding-input.js +61 -0
- package/dist/esm/utilities/embedding-input.js.map +1 -0
- package/package.json +3 -3
- package/src/activities/chat/messages.ts +30 -1
- package/src/activities/embed/adapter.ts +112 -0
- package/src/activities/embed/index.ts +318 -0
- package/src/activities/error-payload.ts +41 -9
- package/src/activities/generateAudio/index.ts +47 -5
- package/src/activities/generateImage/index.ts +48 -5
- package/src/activities/generateSpeech/index.ts +52 -9
- package/src/activities/generateTranscription/index.ts +52 -9
- package/src/activities/generateVideo/index.ts +131 -33
- package/src/activities/index.ts +44 -0
- package/src/activities/middleware/types.ts +2 -0
- package/src/activities/rerank/adapter.ts +90 -0
- package/src/activities/rerank/index.ts +302 -0
- package/src/activities/summarize/index.ts +59 -19
- package/src/index.ts +19 -0
- package/src/middlewares/otel.ts +60 -8
- package/src/types.ts +219 -0
- package/src/utilities/activity-abort.ts +197 -0
- package/src/utilities/embedding-input.ts +83 -0
|
@@ -7,7 +7,11 @@ export declare const kind: "transcription";
|
|
|
7
7
|
/**
|
|
8
8
|
* Extract provider options from a TranscriptionAdapter via ~types.
|
|
9
9
|
*/
|
|
10
|
-
export type TranscriptionProviderOptions<TAdapter> = TAdapter extends
|
|
10
|
+
export type TranscriptionProviderOptions<TAdapter> = TAdapter extends {
|
|
11
|
+
'~types': {
|
|
12
|
+
providerOptions: infer P extends object;
|
|
13
|
+
};
|
|
14
|
+
} ? P : object;
|
|
11
15
|
/**
|
|
12
16
|
* Options for the transcription activity.
|
|
13
17
|
* The model is extracted from the adapter's model property.
|
|
@@ -54,6 +58,18 @@ export interface TranscriptionActivityOptions<TAdapter extends TranscriptionAdap
|
|
|
54
58
|
threadId?: string;
|
|
55
59
|
/** Stable run id for correlating this run when persisted. */
|
|
56
60
|
runId?: string;
|
|
61
|
+
/**
|
|
62
|
+
* Maximum duration of this activity invocation in milliseconds.
|
|
63
|
+
* No SDK-wide default — choose a value suitable for the provider and job.
|
|
64
|
+
* Composed with {@link abortSignal}; the first abort wins.
|
|
65
|
+
*/
|
|
66
|
+
timeout?: number;
|
|
67
|
+
/**
|
|
68
|
+
* Caller cancellation signal (request disconnects, job/runtime cancellation).
|
|
69
|
+
* Composed with {@link timeout} into an effective signal forwarded to the
|
|
70
|
+
* adapter. Request-specific — not stored on global provider client config.
|
|
71
|
+
*/
|
|
72
|
+
abortSignal?: AbortSignal;
|
|
57
73
|
}
|
|
58
74
|
/**
|
|
59
75
|
* Result type for the transcription activity.
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { resolveDebugOption } from "../../logger/resolve.js";
|
|
2
2
|
import { streamGenerationResult } from "../stream-generation-result.js";
|
|
3
|
-
import { applyGenerationResultTransforms, createGenerationContext, runGenerationError, runGenerationFinish, runGenerationStart, runGenerationUsage } from "../middleware/run.js";
|
|
3
|
+
import { applyGenerationResultTransforms, createGenerationContext, runGenerationAbort, runGenerationError, runGenerationFinish, runGenerationStart, runGenerationUsage } from "../middleware/run.js";
|
|
4
|
+
import { abortReasonMessage, createActivityAbortControls, isActivityAbortError, raceWithAbort } from "../../utilities/activity-abort.js";
|
|
4
5
|
import "./adapter.js";
|
|
5
6
|
import { aiEventClient } from "@tanstack/ai-event-client";
|
|
6
7
|
//#region src/activities/generateTranscription/index.ts
|
|
@@ -69,11 +70,15 @@ function generateTranscription(options) {
|
|
|
69
70
|
* Run non-streaming transcription
|
|
70
71
|
*/
|
|
71
72
|
async function runGenerateTranscription(options) {
|
|
72
|
-
const { adapter, stream: _stream, debug: _debug, middleware, threadId, runId, ...rest } = options;
|
|
73
|
+
const { adapter, stream: _stream, debug: _debug, middleware, threadId, runId, timeout, abortSignal: callerAbortSignal, ...rest } = options;
|
|
73
74
|
const model = adapter.model;
|
|
74
75
|
const requestId = createId("transcription");
|
|
75
76
|
const startTime = Date.now();
|
|
76
77
|
const logger = resolveDebugOption(options.debug);
|
|
78
|
+
const abortControls = createActivityAbortControls({
|
|
79
|
+
timeout,
|
|
80
|
+
abortSignal: callerAbortSignal
|
|
81
|
+
});
|
|
77
82
|
const providerName = adapter.provider ?? adapter.name ?? "unknown";
|
|
78
83
|
const mwCtx = createGenerationContext({
|
|
79
84
|
requestId,
|
|
@@ -107,11 +112,14 @@ async function runGenerateTranscription(options) {
|
|
|
107
112
|
model
|
|
108
113
|
});
|
|
109
114
|
try {
|
|
110
|
-
const
|
|
115
|
+
const rawResult = await raceWithAbort(adapter.transcribe({
|
|
111
116
|
...rest,
|
|
112
117
|
model,
|
|
113
|
-
logger
|
|
114
|
-
|
|
118
|
+
logger,
|
|
119
|
+
...abortControls.signal ? { abortSignal: abortControls.signal } : {}
|
|
120
|
+
}), abortControls.signal);
|
|
121
|
+
abortControls.clear();
|
|
122
|
+
const result = await applyGenerationResultTransforms(mwCtx, rawResult);
|
|
115
123
|
const duration = Date.now() - startTime;
|
|
116
124
|
aiEventClient.emit("transcription:request:completed", {
|
|
117
125
|
requestId,
|
|
@@ -131,6 +139,7 @@ async function runGenerateTranscription(options) {
|
|
|
131
139
|
});
|
|
132
140
|
return result;
|
|
133
141
|
} catch (error) {
|
|
142
|
+
abortControls.clear();
|
|
134
143
|
const duration = Date.now() - startTime;
|
|
135
144
|
const err = error;
|
|
136
145
|
aiEventClient.emit("transcription:request:error", {
|
|
@@ -145,7 +154,11 @@ async function runGenerateTranscription(options) {
|
|
|
145
154
|
modelOptions: rest.modelOptions,
|
|
146
155
|
timestamp: Date.now()
|
|
147
156
|
});
|
|
148
|
-
await
|
|
157
|
+
if (isActivityAbortError(error, abortControls.signal)) await runGenerationAbort(middleware, mwCtx, {
|
|
158
|
+
reason: abortReasonMessage(error, abortControls.signal),
|
|
159
|
+
duration
|
|
160
|
+
});
|
|
161
|
+
else await runGenerationError(middleware, mwCtx, {
|
|
149
162
|
error,
|
|
150
163
|
duration
|
|
151
164
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/activities/generateTranscription/index.ts"],"sourcesContent":["/**\n * Transcription Activity\n *\n * Transcribes audio to text using speech-to-text models.\n * This is a self-contained module with implementation, types, and JSDoc.\n */\n\nimport { aiEventClient } from '@tanstack/ai-event-client'\nimport { streamGenerationResult } from '../stream-generation-result.js'\nimport { resolveDebugOption } from '../../logger/resolve'\nimport {\n applyGenerationResultTransforms,\n createGenerationContext,\n runGenerationError,\n runGenerationFinish,\n runGenerationStart,\n runGenerationUsage,\n} from '../middleware/run'\nimport type { InternalLogger } from '../../logger/internal-logger'\nimport type { DebugOption } from '../../logger/types'\nimport type { GenerationMiddleware } from '../middleware/types'\nimport type { TranscriptionAdapter } from './adapter'\nimport type {\n StreamChunk,\n TranscriptionResponseFormat,\n TranscriptionResult,\n} from '../../types'\n\n// ===========================\n// Activity Kind\n// ===========================\n\n/** The adapter kind this activity handles */\nexport const kind = 'transcription' as const\n\n// ===========================\n// Type Extraction Helpers\n// ===========================\n\n/**\n * Extract provider options from a TranscriptionAdapter via ~types.\n */\nexport type TranscriptionProviderOptions<TAdapter> =\n TAdapter extends TranscriptionAdapter<any, any>\n ? TAdapter['~types']['providerOptions']\n : object\n\n// ===========================\n// Activity Options Type\n// ===========================\n\n/**\n * Options for the transcription activity.\n * The model is extracted from the adapter's model property.\n *\n * @template TAdapter - The transcription adapter type\n * @template TStream - Whether to stream the output\n */\nexport interface TranscriptionActivityOptions<\n TAdapter extends TranscriptionAdapter<\n string,\n TranscriptionProviderOptions<TAdapter>\n >,\n TStream extends boolean = false,\n> {\n /** The transcription adapter to use (must be created with a model) */\n adapter: TAdapter & { kind: typeof kind }\n /** The audio data to transcribe - can be base64 string, File, Blob, or Buffer */\n audio: string | File | Blob | ArrayBuffer\n /** The language of the audio in ISO-639-1 format (e.g., 'en') */\n language?: string\n /** An optional prompt to guide the transcription */\n prompt?: string\n /** The format of the transcription output */\n responseFormat?: TranscriptionResponseFormat\n /** Provider-specific options for transcription */\n modelOptions?: TranscriptionProviderOptions<TAdapter>\n /**\n * Whether to stream the transcription result.\n * When true, returns an AsyncIterable<StreamChunk> for streaming transport.\n * When false or not provided, returns a Promise<TranscriptionResult>.\n *\n * @default false\n */\n stream?: TStream\n /**\n * Enable debug logging. Pass `true` to enable all categories, `false` to\n * silence everything including errors, or a `DebugConfig` object for granular\n * control and/or a custom `Logger`.\n */\n debug?: DebugOption\n /**\n * Observe-only middleware notified on start, usage, success, and error. Pass\n * `otelMiddleware()` to emit OpenTelemetry spans, or implement the\n * `GenerationMiddleware` contract for a custom backend.\n */\n middleware?: Array<GenerationMiddleware>\n /** Stable conversation/thread id for correlating this run when persisted. */\n threadId?: string\n /** Stable run id for correlating this run when persisted. */\n runId?: string\n}\n\n// ===========================\n// Activity Result Type\n// ===========================\n\n/**\n * Result type for the transcription activity.\n * - If stream is true: AsyncIterable<StreamChunk>\n * - Otherwise: Promise<TranscriptionResult>\n */\nexport type TranscriptionActivityResult<TStream extends boolean = false> =\n TStream extends true\n ? AsyncIterable<StreamChunk>\n : Promise<TranscriptionResult>\n\nfunction createId(prefix: string): string {\n return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`\n}\n\n// ===========================\n// Activity Implementation\n// ===========================\n\n/**\n * Transcription activity - converts audio to text.\n *\n * Uses AI speech-to-text models to transcribe audio content.\n *\n * @example Transcribe an audio file\n * ```ts\n * import { generateTranscription } from '@tanstack/ai'\n * import { openaiTranscription } from '@tanstack/ai-openai'\n *\n * const result = await generateTranscription({\n * adapter: openaiTranscription('whisper-1'),\n * audio: audioFile, // File, Blob, or base64 string\n * language: 'en'\n * })\n *\n * console.log(result.text)\n * ```\n *\n * @example With verbose output for timestamps\n * ```ts\n * const result = await generateTranscription({\n * adapter: openaiTranscription('whisper-1'),\n * audio: audioFile,\n * responseFormat: 'verbose_json'\n * })\n *\n * result.segments?.forEach(segment => {\n * console.log(`[${segment.start}s - ${segment.end}s]: ${segment.text}`)\n * })\n * ```\n *\n * @example Streaming transcription result\n * ```ts\n * for await (const chunk of generateTranscription({\n * adapter: openaiTranscription('whisper-1'),\n * audio: audioFile,\n * stream: true\n * })) {\n * console.log(chunk)\n * }\n * ```\n */\nexport function generateTranscription<\n TAdapter extends TranscriptionAdapter<\n string,\n TranscriptionProviderOptions<TAdapter>\n >,\n TStream extends boolean = false,\n>(\n options: TranscriptionActivityOptions<TAdapter, TStream>,\n): TranscriptionActivityResult<TStream> {\n if (options.stream) {\n return streamGenerationResult(\n // Only `runId` is taken from the resolved wire identity. `threadId` stays\n // the CALLER's: `streamGenerationResult` mints one for the RUN_* chunks\n // when none was passed, and spreading that over the options would hand\n // middleware a thread id known to nobody, which persistence would then\n // file the run under. Matches `generateVideo`.\n (resolved) =>\n runGenerateTranscription({ ...options, runId: resolved.runId }),\n options,\n ) as TranscriptionActivityResult<TStream>\n }\n\n return runGenerateTranscription(\n options,\n ) as TranscriptionActivityResult<TStream>\n}\n\n/**\n * Run non-streaming transcription\n */\nasync function runGenerateTranscription<\n TAdapter extends TranscriptionAdapter<\n string,\n TranscriptionProviderOptions<TAdapter>\n >,\n>(\n options: TranscriptionActivityOptions<TAdapter, boolean>,\n): Promise<TranscriptionResult> {\n const {\n adapter,\n stream: _stream,\n debug: _debug,\n middleware,\n threadId,\n runId,\n ...rest\n } = options\n const model = adapter.model\n const requestId = createId('transcription')\n const startTime = Date.now()\n const logger: InternalLogger = resolveDebugOption(options.debug)\n const providerName =\n (adapter as { name?: string; provider?: string }).provider ??\n (adapter as { name?: string }).name ??\n 'unknown'\n\n const mwCtx = createGenerationContext({\n requestId,\n activity: 'transcription',\n provider: adapter.name,\n model,\n modelOptions: rest.modelOptions,\n artifactInputs: {\n audio: rest.audio,\n language: rest.language,\n prompt: rest.prompt,\n responseFormat: rest.responseFormat,\n },\n threadId,\n runId,\n createId,\n })\n\n await runGenerationStart(middleware, mwCtx)\n\n aiEventClient.emit('transcription:request:started', {\n requestId,\n provider: adapter.name,\n model,\n language: rest.language,\n prompt: rest.prompt,\n responseFormat: rest.responseFormat,\n modelOptions: rest.modelOptions as Record<string, unknown> | undefined,\n timestamp: startTime,\n })\n\n logger.request(`activity=generateTranscription provider=${providerName}`, {\n provider: providerName,\n model,\n })\n\n try {\n const rawResult = await adapter.transcribe({ ...rest, model, logger })\n const result = await applyGenerationResultTransforms(mwCtx, rawResult)\n const duration = Date.now() - startTime\n\n aiEventClient.emit('transcription:request:completed', {\n requestId,\n provider: adapter.name,\n model,\n text: result.text,\n language: result.language,\n duration,\n modelOptions: rest.modelOptions as Record<string, unknown> | undefined,\n timestamp: Date.now(),\n })\n\n logger.output(\n `activity=generateTranscription length=${result.text.length}`,\n { hasText: !!result.text },\n )\n\n if (result.usage) await runGenerationUsage(middleware, mwCtx, result.usage)\n await runGenerationFinish(middleware, mwCtx, {\n duration,\n usage: result.usage,\n })\n\n return result\n } catch (error) {\n const duration = Date.now() - startTime\n const err = error as Error\n aiEventClient.emit('transcription:request:error', {\n requestId,\n provider: adapter.name,\n model,\n error: { message: err.message, name: err.name },\n duration,\n modelOptions: rest.modelOptions as Record<string, unknown> | undefined,\n timestamp: Date.now(),\n })\n await runGenerationError(middleware, mwCtx, {\n error,\n duration,\n })\n logger.errors('generateTranscription activity failed', {\n error,\n source: 'generateTranscription',\n })\n throw error\n }\n}\n\n// ===========================\n// Options Factory\n// ===========================\n\n/**\n * Create typed options for the generateTranscription() function without executing.\n */\nexport function createTranscriptionOptions<\n TAdapter extends TranscriptionAdapter<\n string,\n TranscriptionProviderOptions<TAdapter>\n >,\n TStream extends boolean = false,\n>(\n options: TranscriptionActivityOptions<TAdapter, TStream>,\n): TranscriptionActivityOptions<TAdapter, TStream> {\n return options\n}\n\n// Re-export adapter types\nexport type {\n TranscriptionAdapter,\n TranscriptionAdapterConfig,\n AnyTranscriptionAdapter,\n} from './adapter'\nexport { BaseTranscriptionAdapter } from './adapter'\n"],"mappings":";;;;;;;;;;;;;AAiCA,IAAa,OAAO;AAoFpB,SAAS,SAAS,QAAwB;CACxC,OAAO,GAAG,OAAO,GAAG,KAAK,IAAI,EAAE,GAAG,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC;AACzE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,SAAgB,sBAOd,SACsC;CACtC,IAAI,QAAQ,QACV,OAAO,wBAMJ,aACC,yBAAyB;EAAE,GAAG;EAAS,OAAO,SAAS;CAAM,CAAC,GAChE,OACF;CAGF,OAAO,yBACL,OACF;AACF;;;;AAKA,eAAe,yBAMb,SAC8B;CAC9B,MAAM,EACJ,SACA,QAAQ,SACR,OAAO,QACP,YACA,UACA,OACA,GAAG,SACD;CACJ,MAAM,QAAQ,QAAQ;CACtB,MAAM,YAAY,SAAS,eAAe;CAC1C,MAAM,YAAY,KAAK,IAAI;CAC3B,MAAM,SAAyB,mBAAmB,QAAQ,KAAK;CAC/D,MAAM,eACH,QAAiD,YACjD,QAA8B,QAC/B;CAEF,MAAM,QAAQ,wBAAwB;EACpC;EACA,UAAU;EACV,UAAU,QAAQ;EAClB;EACA,cAAc,KAAK;EACnB,gBAAgB;GACd,OAAO,KAAK;GACZ,UAAU,KAAK;GACf,QAAQ,KAAK;GACb,gBAAgB,KAAK;EACvB;EACA;EACA;EACA;CACF,CAAC;CAED,MAAM,mBAAmB,YAAY,KAAK;CAE1C,cAAc,KAAK,iCAAiC;EAClD;EACA,UAAU,QAAQ;EAClB;EACA,UAAU,KAAK;EACf,QAAQ,KAAK;EACb,gBAAgB,KAAK;EACrB,cAAc,KAAK;EACnB,WAAW;CACb,CAAC;CAED,OAAO,QAAQ,2CAA2C,gBAAgB;EACxE,UAAU;EACV;CACF,CAAC;CAED,IAAI;EAEF,MAAM,SAAS,MAAM,gCAAgC,OAAO,MADpC,QAAQ,WAAW;GAAE,GAAG;GAAM;GAAO;EAAO,CAAC,CACA;EACrE,MAAM,WAAW,KAAK,IAAI,IAAI;EAE9B,cAAc,KAAK,mCAAmC;GACpD;GACA,UAAU,QAAQ;GAClB;GACA,MAAM,OAAO;GACb,UAAU,OAAO;GACjB;GACA,cAAc,KAAK;GACnB,WAAW,KAAK,IAAI;EACtB,CAAC;EAED,OAAO,OACL,yCAAyC,OAAO,KAAK,UACrD,EAAE,SAAS,CAAC,CAAC,OAAO,KAAK,CAC3B;EAEA,IAAI,OAAO,OAAO,MAAM,mBAAmB,YAAY,OAAO,OAAO,KAAK;EAC1E,MAAM,oBAAoB,YAAY,OAAO;GAC3C;GACA,OAAO,OAAO;EAChB,CAAC;EAED,OAAO;CACT,SAAS,OAAO;EACd,MAAM,WAAW,KAAK,IAAI,IAAI;EAC9B,MAAM,MAAM;EACZ,cAAc,KAAK,+BAA+B;GAChD;GACA,UAAU,QAAQ;GAClB;GACA,OAAO;IAAE,SAAS,IAAI;IAAS,MAAM,IAAI;GAAK;GAC9C;GACA,cAAc,KAAK;GACnB,WAAW,KAAK,IAAI;EACtB,CAAC;EACD,MAAM,mBAAmB,YAAY,OAAO;GAC1C;GACA;EACF,CAAC;EACD,OAAO,OAAO,yCAAyC;GACrD;GACA,QAAQ;EACV,CAAC;EACD,MAAM;CACR;AACF;;;;AASA,SAAgB,2BAOd,SACiD;CACjD,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/activities/generateTranscription/index.ts"],"sourcesContent":["/**\n * Transcription Activity\n *\n * Transcribes audio to text using speech-to-text models.\n * This is a self-contained module with implementation, types, and JSDoc.\n */\n\nimport { aiEventClient } from '@tanstack/ai-event-client'\nimport { streamGenerationResult } from '../stream-generation-result.js'\nimport { resolveDebugOption } from '../../logger/resolve'\nimport {\n applyGenerationResultTransforms,\n createGenerationContext,\n runGenerationAbort,\n runGenerationError,\n runGenerationFinish,\n runGenerationStart,\n runGenerationUsage,\n} from '../middleware/run'\nimport {\n abortReasonMessage,\n createActivityAbortControls,\n isActivityAbortError,\n raceWithAbort,\n} from '../../utilities/activity-abort'\nimport type { InternalLogger } from '../../logger/internal-logger'\nimport type { DebugOption } from '../../logger/types'\nimport type { GenerationMiddleware } from '../middleware/types'\nimport type { TranscriptionAdapter } from './adapter'\nimport type {\n StreamChunk,\n TranscriptionResponseFormat,\n TranscriptionResult,\n} from '../../types'\n\n// ===========================\n// Activity Kind\n// ===========================\n\n/** The adapter kind this activity handles */\nexport const kind = 'transcription' as const\n\n// ===========================\n// Type Extraction Helpers\n// ===========================\n\n/**\n * Extract provider options from a TranscriptionAdapter via ~types.\n */\nexport type TranscriptionProviderOptions<TAdapter> = TAdapter extends {\n '~types': { providerOptions: infer P extends object }\n}\n ? P\n : object\n\n// ===========================\n// Activity Options Type\n// ===========================\n\n/**\n * Options for the transcription activity.\n * The model is extracted from the adapter's model property.\n *\n * @template TAdapter - The transcription adapter type\n * @template TStream - Whether to stream the output\n */\nexport interface TranscriptionActivityOptions<\n TAdapter extends TranscriptionAdapter<\n string,\n TranscriptionProviderOptions<TAdapter>\n >,\n TStream extends boolean = false,\n> {\n /** The transcription adapter to use (must be created with a model) */\n adapter: TAdapter & { kind: typeof kind }\n /** The audio data to transcribe - can be base64 string, File, Blob, or Buffer */\n audio: string | File | Blob | ArrayBuffer\n /** The language of the audio in ISO-639-1 format (e.g., 'en') */\n language?: string\n /** An optional prompt to guide the transcription */\n prompt?: string\n /** The format of the transcription output */\n responseFormat?: TranscriptionResponseFormat\n /** Provider-specific options for transcription */\n modelOptions?: TranscriptionProviderOptions<TAdapter>\n /**\n * Whether to stream the transcription result.\n * When true, returns an AsyncIterable<StreamChunk> for streaming transport.\n * When false or not provided, returns a Promise<TranscriptionResult>.\n *\n * @default false\n */\n stream?: TStream\n /**\n * Enable debug logging. Pass `true` to enable all categories, `false` to\n * silence everything including errors, or a `DebugConfig` object for granular\n * control and/or a custom `Logger`.\n */\n debug?: DebugOption\n /**\n * Observe-only middleware notified on start, usage, success, and error. Pass\n * `otelMiddleware()` to emit OpenTelemetry spans, or implement the\n * `GenerationMiddleware` contract for a custom backend.\n */\n middleware?: Array<GenerationMiddleware>\n /** Stable conversation/thread id for correlating this run when persisted. */\n threadId?: string\n /** Stable run id for correlating this run when persisted. */\n runId?: string\n /**\n * Maximum duration of this activity invocation in milliseconds.\n * No SDK-wide default — choose a value suitable for the provider and job.\n * Composed with {@link abortSignal}; the first abort wins.\n */\n timeout?: number\n /**\n * Caller cancellation signal (request disconnects, job/runtime cancellation).\n * Composed with {@link timeout} into an effective signal forwarded to the\n * adapter. Request-specific — not stored on global provider client config.\n */\n abortSignal?: AbortSignal\n}\n\n// ===========================\n// Activity Result Type\n// ===========================\n\n/**\n * Result type for the transcription activity.\n * - If stream is true: AsyncIterable<StreamChunk>\n * - Otherwise: Promise<TranscriptionResult>\n */\nexport type TranscriptionActivityResult<TStream extends boolean = false> =\n TStream extends true\n ? AsyncIterable<StreamChunk>\n : Promise<TranscriptionResult>\n\nfunction createId(prefix: string): string {\n return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`\n}\n\n// ===========================\n// Activity Implementation\n// ===========================\n\n/**\n * Transcription activity - converts audio to text.\n *\n * Uses AI speech-to-text models to transcribe audio content.\n *\n * @example Transcribe an audio file\n * ```ts\n * import { generateTranscription } from '@tanstack/ai'\n * import { openaiTranscription } from '@tanstack/ai-openai'\n *\n * const result = await generateTranscription({\n * adapter: openaiTranscription('whisper-1'),\n * audio: audioFile, // File, Blob, or base64 string\n * language: 'en'\n * })\n *\n * console.log(result.text)\n * ```\n *\n * @example With verbose output for timestamps\n * ```ts\n * const result = await generateTranscription({\n * adapter: openaiTranscription('whisper-1'),\n * audio: audioFile,\n * responseFormat: 'verbose_json'\n * })\n *\n * result.segments?.forEach(segment => {\n * console.log(`[${segment.start}s - ${segment.end}s]: ${segment.text}`)\n * })\n * ```\n *\n * @example Streaming transcription result\n * ```ts\n * for await (const chunk of generateTranscription({\n * adapter: openaiTranscription('whisper-1'),\n * audio: audioFile,\n * stream: true\n * })) {\n * console.log(chunk)\n * }\n * ```\n */\nexport function generateTranscription<\n TAdapter extends TranscriptionAdapter<\n string,\n TranscriptionProviderOptions<TAdapter>\n >,\n TStream extends boolean = false,\n>(\n options: TranscriptionActivityOptions<TAdapter, TStream>,\n): TranscriptionActivityResult<TStream> {\n if (options.stream) {\n return streamGenerationResult(\n // Only `runId` is taken from the resolved wire identity. `threadId` stays\n // the CALLER's: `streamGenerationResult` mints one for the RUN_* chunks\n // when none was passed, and spreading that over the options would hand\n // middleware a thread id known to nobody, which persistence would then\n // file the run under. Matches `generateVideo`.\n (resolved) =>\n runGenerateTranscription({ ...options, runId: resolved.runId }),\n options,\n ) as TranscriptionActivityResult<TStream>\n }\n\n return runGenerateTranscription(\n options,\n ) as TranscriptionActivityResult<TStream>\n}\n\n/**\n * Run non-streaming transcription\n */\nasync function runGenerateTranscription<\n TAdapter extends TranscriptionAdapter<\n string,\n TranscriptionProviderOptions<TAdapter>\n >,\n>(\n options: TranscriptionActivityOptions<TAdapter, boolean>,\n): Promise<TranscriptionResult> {\n const {\n adapter,\n stream: _stream,\n debug: _debug,\n middleware,\n threadId,\n runId,\n timeout,\n abortSignal: callerAbortSignal,\n ...rest\n } = options\n const model = adapter.model\n const requestId = createId('transcription')\n const startTime = Date.now()\n const logger: InternalLogger = resolveDebugOption(options.debug)\n const abortControls = createActivityAbortControls({\n timeout,\n abortSignal: callerAbortSignal,\n })\n const providerName =\n (adapter as { name?: string; provider?: string }).provider ??\n (adapter as { name?: string }).name ??\n 'unknown'\n\n const mwCtx = createGenerationContext({\n requestId,\n activity: 'transcription',\n provider: adapter.name,\n model,\n modelOptions: rest.modelOptions,\n artifactInputs: {\n audio: rest.audio,\n language: rest.language,\n prompt: rest.prompt,\n responseFormat: rest.responseFormat,\n },\n threadId,\n runId,\n createId,\n })\n\n await runGenerationStart(middleware, mwCtx)\n\n aiEventClient.emit('transcription:request:started', {\n requestId,\n provider: adapter.name,\n model,\n language: rest.language,\n prompt: rest.prompt,\n responseFormat: rest.responseFormat,\n modelOptions: rest.modelOptions as Record<string, unknown> | undefined,\n timestamp: startTime,\n })\n\n logger.request(`activity=generateTranscription provider=${providerName}`, {\n provider: providerName,\n model,\n })\n\n try {\n const rawResult = await raceWithAbort(\n adapter.transcribe({\n ...rest,\n model,\n logger,\n ...(abortControls.signal ? { abortSignal: abortControls.signal } : {}),\n }),\n abortControls.signal,\n )\n abortControls.clear()\n const result = await applyGenerationResultTransforms(mwCtx, rawResult)\n const duration = Date.now() - startTime\n\n aiEventClient.emit('transcription:request:completed', {\n requestId,\n provider: adapter.name,\n model,\n text: result.text,\n language: result.language,\n duration,\n modelOptions: rest.modelOptions as Record<string, unknown> | undefined,\n timestamp: Date.now(),\n })\n\n logger.output(\n `activity=generateTranscription length=${result.text.length}`,\n { hasText: !!result.text },\n )\n\n if (result.usage) await runGenerationUsage(middleware, mwCtx, result.usage)\n await runGenerationFinish(middleware, mwCtx, {\n duration,\n usage: result.usage,\n })\n\n return result\n } catch (error) {\n abortControls.clear()\n const duration = Date.now() - startTime\n const err = error as Error\n aiEventClient.emit('transcription:request:error', {\n requestId,\n provider: adapter.name,\n model,\n error: { message: err.message, name: err.name },\n duration,\n modelOptions: rest.modelOptions as Record<string, unknown> | undefined,\n timestamp: Date.now(),\n })\n if (isActivityAbortError(error, abortControls.signal)) {\n await runGenerationAbort(middleware, mwCtx, {\n reason: abortReasonMessage(error, abortControls.signal),\n duration,\n })\n } else {\n await runGenerationError(middleware, mwCtx, {\n error,\n duration,\n })\n }\n logger.errors('generateTranscription activity failed', {\n error,\n source: 'generateTranscription',\n })\n throw error\n }\n}\n\n// ===========================\n// Options Factory\n// ===========================\n\n/**\n * Create typed options for the generateTranscription() function without executing.\n */\nexport function createTranscriptionOptions<\n TAdapter extends TranscriptionAdapter<\n string,\n TranscriptionProviderOptions<TAdapter>\n >,\n TStream extends boolean = false,\n>(\n options: TranscriptionActivityOptions<TAdapter, TStream>,\n): TranscriptionActivityOptions<TAdapter, TStream> {\n return options\n}\n\n// Re-export adapter types\nexport type {\n TranscriptionAdapter,\n TranscriptionAdapterConfig,\n AnyTranscriptionAdapter,\n} from './adapter'\nexport { BaseTranscriptionAdapter } from './adapter'\n"],"mappings":";;;;;;;;;;;;;;AAwCA,IAAa,OAAO;AAiGpB,SAAS,SAAS,QAAwB;CACxC,OAAO,GAAG,OAAO,GAAG,KAAK,IAAI,EAAE,GAAG,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC;AACzE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,SAAgB,sBAOd,SACsC;CACtC,IAAI,QAAQ,QACV,OAAO,wBAMJ,aACC,yBAAyB;EAAE,GAAG;EAAS,OAAO,SAAS;CAAM,CAAC,GAChE,OACF;CAGF,OAAO,yBACL,OACF;AACF;;;;AAKA,eAAe,yBAMb,SAC8B;CAC9B,MAAM,EACJ,SACA,QAAQ,SACR,OAAO,QACP,YACA,UACA,OACA,SACA,aAAa,mBACb,GAAG,SACD;CACJ,MAAM,QAAQ,QAAQ;CACtB,MAAM,YAAY,SAAS,eAAe;CAC1C,MAAM,YAAY,KAAK,IAAI;CAC3B,MAAM,SAAyB,mBAAmB,QAAQ,KAAK;CAC/D,MAAM,gBAAgB,4BAA4B;EAChD;EACA,aAAa;CACf,CAAC;CACD,MAAM,eACH,QAAiD,YACjD,QAA8B,QAC/B;CAEF,MAAM,QAAQ,wBAAwB;EACpC;EACA,UAAU;EACV,UAAU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;GAC9C;GACA,cAAc,KAAK;GACnB,WAAW,KAAK,IAAI;EACtB,CAAC;EACD,IAAI,qBAAqB,OAAO,cAAc,MAAM,GAClD,MAAM,mBAAmB,YAAY,OAAO;GAC1C,QAAQ,mBAAmB,OAAO,cAAc,MAAM;GACtD;EACF,CAAC;OAED,MAAM,mBAAmB,YAAY,OAAO;GAC1C;GACA;EACF,CAAC;EAEH,OAAO,OAAO,yCAAyC;GACrD;GACA,QAAQ;EACV,CAAC;EACD,MAAM;CACR;AACF;;;;AASA,SAAgB,2BAOd,SACiD;CACjD,OAAO;AACT"}
|
|
@@ -134,6 +134,24 @@ export type VideoCreateOptions<TAdapter extends VideoAdapter<string, any, any, a
|
|
|
134
134
|
* job to resume.
|
|
135
135
|
*/
|
|
136
136
|
middleware?: Array<GenerationMiddleware>;
|
|
137
|
+
/**
|
|
138
|
+
* Maximum duration of this activity invocation in milliseconds.
|
|
139
|
+
* No SDK-wide default — choose a value suitable for the provider and job.
|
|
140
|
+
* Composed with {@link abortSignal}; the first abort wins.
|
|
141
|
+
*
|
|
142
|
+
* In stream mode this bounds the full create→poll→complete lifecycle and
|
|
143
|
+
* complements {@link maxDuration} (which defaults to 10 minutes). When both
|
|
144
|
+
* are set, the shorter limit wins via signal composition against the
|
|
145
|
+
* polling deadline.
|
|
146
|
+
*/
|
|
147
|
+
timeout?: number;
|
|
148
|
+
/**
|
|
149
|
+
* Caller cancellation signal (request disconnects, job/runtime cancellation).
|
|
150
|
+
* Composed with {@link timeout} into an effective signal forwarded to the
|
|
151
|
+
* adapter on job submission. Request-specific — not stored on global
|
|
152
|
+
* provider client config.
|
|
153
|
+
*/
|
|
154
|
+
abortSignal?: AbortSignal;
|
|
137
155
|
} & ({} extends VideoProviderOptions<TAdapter> ? {
|
|
138
156
|
/** Provider-specific options for video generation */ modelOptions?: VideoProviderOptions<TAdapter>;
|
|
139
157
|
} : {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { toRunErrorPayload } from "../error-payload.js";
|
|
2
2
|
import { resolveDebugOption } from "../../logger/resolve.js";
|
|
3
3
|
import { applyGenerationResultTransforms, createGenerationContext, runGenerationAbort, runGenerationError, runGenerationFinish, runGenerationStart, runGenerationUsage } from "../middleware/run.js";
|
|
4
|
+
import { abortReasonMessage, createActivityAbortControls, isActivityAbortError, raceWithAbort, toAbortError } from "../../utilities/activity-abort.js";
|
|
4
5
|
import "./adapter.js";
|
|
5
6
|
import { aiEventClient } from "@tanstack/ai-event-client";
|
|
6
7
|
//#region src/activities/generateVideo/index.ts
|
|
@@ -103,11 +104,15 @@ function videoRunIdForJob(provider, jobId) {
|
|
|
103
104
|
* showing nothing.
|
|
104
105
|
*/
|
|
105
106
|
async function runCreateVideoJob(options) {
|
|
106
|
-
const { adapter, prompt, size, duration, modelOptions, middleware } = options;
|
|
107
|
+
const { adapter, prompt, size, duration, modelOptions, middleware, timeout, abortSignal: callerAbortSignal } = options;
|
|
107
108
|
const model = adapter.model;
|
|
108
109
|
const requestId = createId("video");
|
|
109
110
|
const startTime = Date.now();
|
|
110
111
|
const logger = resolveDebugOption(options.debug);
|
|
112
|
+
const abortControls = createActivityAbortControls({
|
|
113
|
+
timeout,
|
|
114
|
+
abortSignal: callerAbortSignal
|
|
115
|
+
});
|
|
111
116
|
const providerName = adapter.provider ?? adapter.name ?? "unknown";
|
|
112
117
|
const contextFor = (runId) => createGenerationContext({
|
|
113
118
|
requestId,
|
|
@@ -126,20 +131,28 @@ async function runCreateVideoJob(options) {
|
|
|
126
131
|
});
|
|
127
132
|
let jobResult;
|
|
128
133
|
try {
|
|
129
|
-
jobResult = await adapter.createVideoJob({
|
|
134
|
+
jobResult = await raceWithAbort(adapter.createVideoJob({
|
|
130
135
|
model,
|
|
131
136
|
prompt,
|
|
132
137
|
size,
|
|
133
138
|
duration,
|
|
134
139
|
modelOptions,
|
|
135
|
-
logger
|
|
136
|
-
|
|
140
|
+
logger,
|
|
141
|
+
...abortControls.signal ? { abortSignal: abortControls.signal } : {}
|
|
142
|
+
}), abortControls.signal);
|
|
143
|
+
abortControls.clear();
|
|
137
144
|
} catch (error) {
|
|
145
|
+
abortControls.clear();
|
|
138
146
|
const failedCtx = contextFor();
|
|
139
147
|
await runGenerationStart(middleware, failedCtx);
|
|
140
|
-
|
|
148
|
+
const elapsed = Date.now() - startTime;
|
|
149
|
+
if (isActivityAbortError(error, abortControls.signal)) await runGenerationAbort(middleware, failedCtx, {
|
|
150
|
+
reason: abortReasonMessage(error, abortControls.signal),
|
|
151
|
+
duration: elapsed
|
|
152
|
+
});
|
|
153
|
+
else await runGenerationError(middleware, failedCtx, {
|
|
141
154
|
error,
|
|
142
|
-
duration:
|
|
155
|
+
duration: elapsed
|
|
143
156
|
});
|
|
144
157
|
logger.errors("generateVideo activity failed", {
|
|
145
158
|
error,
|
|
@@ -155,15 +168,28 @@ async function runCreateVideoJob(options) {
|
|
|
155
168
|
await runGenerationStart(middleware, mwCtx);
|
|
156
169
|
return await applyGenerationResultTransforms(mwCtx, jobResult);
|
|
157
170
|
}
|
|
158
|
-
function sleep(ms) {
|
|
159
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
171
|
+
function sleep(ms, signal) {
|
|
172
|
+
if (!signal) return new Promise((resolve) => setTimeout(resolve, ms));
|
|
173
|
+
if (signal.aborted) return Promise.reject(toAbortError(signal.reason));
|
|
174
|
+
return new Promise((resolve, reject) => {
|
|
175
|
+
const timer = setTimeout(() => {
|
|
176
|
+
signal.removeEventListener("abort", onAbort);
|
|
177
|
+
resolve();
|
|
178
|
+
}, ms);
|
|
179
|
+
const onAbort = () => {
|
|
180
|
+
clearTimeout(timer);
|
|
181
|
+
signal.removeEventListener("abort", onAbort);
|
|
182
|
+
reject(toAbortError(signal.reason));
|
|
183
|
+
};
|
|
184
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
185
|
+
});
|
|
160
186
|
}
|
|
161
187
|
/**
|
|
162
188
|
* Internal streaming implementation for video generation.
|
|
163
189
|
* Handles the full job lifecycle: create job → poll for status → stream updates → yield final result.
|
|
164
190
|
*/
|
|
165
191
|
async function* runStreamingVideoGeneration(options) {
|
|
166
|
-
const { adapter, prompt, size, duration, modelOptions, middleware } = options;
|
|
192
|
+
const { adapter, prompt, size, duration, modelOptions, middleware, timeout, abortSignal: callerAbortSignal } = options;
|
|
167
193
|
const model = adapter.model;
|
|
168
194
|
const runId = options.runId ?? createId("run");
|
|
169
195
|
const requestId = createId("video");
|
|
@@ -171,6 +197,10 @@ async function* runStreamingVideoGeneration(options) {
|
|
|
171
197
|
const pollingInterval = options.pollingInterval ?? 2e3;
|
|
172
198
|
const maxDuration = options.maxDuration ?? 6e5;
|
|
173
199
|
const logger = resolveDebugOption(options.debug);
|
|
200
|
+
const abortControls = createActivityAbortControls({
|
|
201
|
+
timeout,
|
|
202
|
+
abortSignal: callerAbortSignal
|
|
203
|
+
});
|
|
174
204
|
const providerName = adapter.provider ?? adapter.name ?? "unknown";
|
|
175
205
|
const wireThreadId = options.threadId ?? createId("thread");
|
|
176
206
|
yield {
|
|
@@ -197,14 +227,15 @@ async function* runStreamingVideoGeneration(options) {
|
|
|
197
227
|
});
|
|
198
228
|
let settled = false;
|
|
199
229
|
try {
|
|
200
|
-
const jobResult = await adapter.createVideoJob({
|
|
230
|
+
const jobResult = await raceWithAbort(adapter.createVideoJob({
|
|
201
231
|
model,
|
|
202
232
|
prompt,
|
|
203
233
|
size,
|
|
204
234
|
duration,
|
|
205
235
|
modelOptions,
|
|
206
|
-
logger
|
|
207
|
-
|
|
236
|
+
logger,
|
|
237
|
+
...abortControls.signal ? { abortSignal: abortControls.signal } : {}
|
|
238
|
+
}), abortControls.signal);
|
|
208
239
|
yield {
|
|
209
240
|
type: "CUSTOM",
|
|
210
241
|
name: "video:job:created",
|
|
@@ -213,7 +244,7 @@ async function* runStreamingVideoGeneration(options) {
|
|
|
213
244
|
};
|
|
214
245
|
const startTime = Date.now();
|
|
215
246
|
while (Date.now() - startTime < maxDuration) {
|
|
216
|
-
await sleep(pollingInterval);
|
|
247
|
+
await sleep(pollingInterval, abortControls.signal);
|
|
217
248
|
const statusResult = await adapter.getVideoStatus(jobResult.jobId);
|
|
218
249
|
yield {
|
|
219
250
|
type: "CUSTOM",
|
|
@@ -245,6 +276,7 @@ async function* runStreamingVideoGeneration(options) {
|
|
|
245
276
|
usage: urlResult.usage
|
|
246
277
|
});
|
|
247
278
|
settled = true;
|
|
279
|
+
abortControls.clear();
|
|
248
280
|
yield {
|
|
249
281
|
type: "CUSTOM",
|
|
250
282
|
name: "generation:result",
|
|
@@ -264,11 +296,17 @@ async function* runStreamingVideoGeneration(options) {
|
|
|
264
296
|
}
|
|
265
297
|
throw new Error("Video generation timed out");
|
|
266
298
|
} catch (error) {
|
|
299
|
+
abortControls.clear();
|
|
267
300
|
const payload = toRunErrorPayload(error, "Video generation failed");
|
|
268
301
|
settled = true;
|
|
269
|
-
|
|
302
|
+
const elapsed = Date.now() - obsStartTime;
|
|
303
|
+
if (isActivityAbortError(error, abortControls.signal)) await runGenerationAbort(middleware, mwCtx, {
|
|
304
|
+
reason: abortReasonMessage(error, abortControls.signal),
|
|
305
|
+
duration: elapsed
|
|
306
|
+
});
|
|
307
|
+
else await runGenerationError(middleware, mwCtx, {
|
|
270
308
|
error,
|
|
271
|
-
duration:
|
|
309
|
+
duration: elapsed
|
|
272
310
|
});
|
|
273
311
|
logger.errors("generateVideo activity failed", {
|
|
274
312
|
message: payload.message,
|
|
@@ -285,6 +323,7 @@ async function* runStreamingVideoGeneration(options) {
|
|
|
285
323
|
timestamp: Date.now()
|
|
286
324
|
};
|
|
287
325
|
} finally {
|
|
326
|
+
abortControls.clear();
|
|
288
327
|
if (!settled) await runGenerationAbort(middleware, mwCtx, {
|
|
289
328
|
reason: "Video generation stream abandoned before completion",
|
|
290
329
|
duration: Date.now() - obsStartTime
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/activities/generateVideo/index.ts"],"sourcesContent":["/**\n * Video Activity (Experimental)\n *\n * Generates videos from text prompts using a jobs/polling architecture.\n * This is a self-contained module with implementation, types, and JSDoc.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\n\nimport { aiEventClient } from '@tanstack/ai-event-client'\nimport { toRunErrorPayload } from '../error-payload'\nimport { resolveDebugOption } from '../../logger/resolve'\nimport {\n applyGenerationResultTransforms,\n createGenerationContext,\n runGenerationAbort,\n runGenerationError,\n runGenerationFinish,\n runGenerationStart,\n runGenerationUsage,\n} from '../middleware/run'\nimport type { InternalLogger } from '../../logger/internal-logger'\nimport type { DebugOption } from '../../logger/types'\nimport type {\n GenerationMiddleware,\n GenerationMiddlewareContext,\n} from '../middleware/types'\nimport type { VideoAdapter } from './adapter'\nimport type {\n MediaPrompt,\n MediaPromptFor,\n PersistedArtifactRef,\n StreamChunk,\n TokenUsage,\n VideoJobResult,\n VideoStatusResult,\n VideoUrlResult,\n} from '../../types'\n\n// ===========================\n// Activity Kind\n// ===========================\n\n/** The adapter kind this activity handles */\nexport const kind = 'video' as const\n\n// ===========================\n// Type Extraction Helpers\n// ===========================\n\n/**\n * Extract provider options from a VideoAdapter via ~types.\n */\nexport type VideoProviderOptions<TAdapter> =\n TAdapter extends VideoAdapter<any, any, any, any, any, any>\n ? TAdapter['~types']['providerOptions']\n : object\n\n/**\n * Extract the size type for a VideoAdapter's model via ~types.\n */\nexport type VideoSizeForAdapter<TAdapter> =\n TAdapter extends VideoAdapter<\n infer TModel,\n any,\n any,\n infer TSizeMap,\n any,\n any\n >\n ? TModel extends keyof TSizeMap\n ? TSizeMap[TModel]\n : string\n : string\n\n/**\n * Extract the prompt type a model accepts from a VideoAdapter via ~types.\n * Mirrors `ImagePromptForModel`: models in the adapter's input-modality map\n * get a `prompt` narrowed to text + their supported part types; adapters\n * without a map fall back to the full MediaPrompt.\n */\nexport type VideoPromptForAdapter<TAdapter> =\n TAdapter extends VideoAdapter<\n infer TModel,\n any,\n any,\n any,\n infer ModsByName,\n any\n >\n ? string extends keyof ModsByName\n ? MediaPrompt\n : TModel extends keyof ModsByName\n ? MediaPromptFor<ModsByName[TModel][number]>\n : MediaPrompt\n : MediaPrompt\n\n/**\n * Extract the duration type for a VideoAdapter's model via ~types.\n * Mirrors `VideoSizeForAdapter`. Falls back to `number` for adapters that\n * haven't declared per-model duration constraints.\n */\nexport type VideoDurationForAdapter<TAdapter> =\n TAdapter extends VideoAdapter<\n infer TModel,\n any,\n any,\n any,\n any,\n infer TDurationMap\n >\n ? TModel extends keyof TDurationMap\n ? TDurationMap[TModel]\n : number\n : number\n\n// ===========================\n// Activity Options Types\n\nfunction createId(prefix: string): string {\n return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`\n}\n// ===========================\n\n/**\n * Base options shared by all video activity operations.\n * The model is extracted from the adapter's model property.\n */\ninterface VideoActivityBaseOptions<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n> {\n /** The video adapter to use (must be created with a model) */\n adapter: TAdapter & { kind: typeof kind }\n}\n\n/**\n * Options for creating a new video generation job.\n * The model is extracted from the adapter's model property.\n *\n * @template TAdapter - The video adapter type\n * @template TStream - Whether to stream the output\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport type VideoCreateOptions<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n TStream extends boolean = false,\n> = VideoActivityBaseOptions<TAdapter> & {\n /** Request type - create a new job (default if not specified) */\n request?: 'create'\n /**\n * Description of the desired video. Either a plain string, or — for models\n * that support image-conditioned generation — an ordered array of content\n * parts interleaving text with image inputs. Image parts may carry\n * `metadata.role` (`'start_frame' | 'end_frame' | 'reference' |\n * 'character'`) to disambiguate intent; positional fallback otherwise. The\n * accepted part types are narrowed per model via the adapter's\n * input-modality map.\n */\n prompt: VideoPromptForAdapter<TAdapter>\n /** Video size — format depends on the provider (e.g., \"16:9\", \"1280x720\") */\n size?: VideoSizeForAdapter<TAdapter>\n /**\n * Video duration in seconds. Adapters that declare a per-model duration\n * map narrow this to the model's valid union (e.g. `4 | 6 | 8` for Veo 3).\n * Pass `adapter.snapDuration(seconds)` to coerce raw seconds to a valid\n * value.\n */\n duration?: VideoDurationForAdapter<TAdapter>\n /**\n * Whether to stream the video generation lifecycle.\n * When true, returns an AsyncIterable<StreamChunk> that handles the full\n * job lifecycle: create job, poll for status, yield updates, and yield final result.\n * When false or not provided, returns a Promise<VideoJobResult>.\n *\n * @default false\n */\n stream?: TStream\n /** Polling interval in milliseconds (stream mode only). @default 2000 */\n pollingInterval?: number\n /** Maximum time to wait before timing out in milliseconds (stream mode only). @default 600000 */\n maxDuration?: number\n /**\n * Custom run id (stream mode only) — the id stamped on the emitted\n * `RUN_STARTED` / `RUN_FINISHED` chunks.\n *\n * IGNORED by a non-streaming submit. That run spans two calls, and its id is\n * derived from the provider's job instead, so {@link getVideoJobStatus} can\n * recompute it from the `jobId` you already have to poll with. Honoring a\n * custom id here would reintroduce the failure this avoids: a caller who set\n * it on the submit and forgot it on the poll would silently open a second\n * record while the first sat unfinished forever.\n */\n runId?: string\n /**\n * Stable conversation/thread id for correlating this run when persisted.\n *\n * Also the `threadId` stamped on the emitted `RUN_STARTED` / `RUN_FINISHED`\n * chunks; when omitted a throwaway id is minted for those chunks only, and\n * the persisted run record carries NO thread link rather than a fabricated\n * one. Pass it whenever persistence is on — it is the slot a reloading client\n * hydrates by, so a run stored without it can only be fetched by run id.\n */\n threadId?: string\n /**\n * Enable debug logging. Pass `true` to enable all categories, `false` to\n * silence everything including errors, or a `DebugConfig` object for granular\n * control and/or a custom `Logger`.\n */\n debug?: DebugOption\n /**\n * Observe-only middleware notified on start, usage, success, and error. Pass\n * `otelMiddleware()` to emit OpenTelemetry spans, `withGenerationPersistence()`\n * to persist the run, or implement the `GenerationMiddleware` contract for a\n * custom backend.\n *\n * In streaming mode one run covers the full create→poll→complete lifecycle:\n * `onStart` at submission, a terminal `onFinish`/`onError` when the job\n * settles, and `onAbort` if the consumer abandons the stream.\n *\n * In NON-streaming mode the call only SUBMITS the job, so it only opens the\n * run: no terminal hook fires here, because the video does not exist yet.\n * Pass the same `middleware` and `threadId` to {@link getVideoJobStatus}; the\n * poll that observes a terminal job state finishes the run and is where the\n * result and its artifacts are recorded. Nothing else has to be threaded\n * through — both calls derive the run id from the provider's `jobId`, the one\n * id a poller cannot be missing.\n *\n * Because the job id only exists once the provider accepts the job, `onStart`\n * fires AFTER the submit request rather than before it — an observer's span\n * therefore covers the run from acceptance onward, not the submit round-trip.\n * A submission that FAILS has no job to key on, so it opens and immediately\n * fails a run under this call's `requestId`: the thread's latest run reports\n * the failure (a client hydrating the slot sees it) even though there is no\n * job to resume.\n */\n middleware?: Array<GenerationMiddleware>\n} & ({} extends VideoProviderOptions<TAdapter>\n ? {\n /** Provider-specific options for video generation */ modelOptions?: VideoProviderOptions<TAdapter>\n }\n : {\n /** Provider-specific options for video generation */ modelOptions: VideoProviderOptions<TAdapter>\n })\n\n/**\n * Options for polling the status of a video generation job.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport interface VideoStatusOptions<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n> extends VideoActivityBaseOptions<TAdapter> {\n /** Request type - get job status */\n request: 'status'\n /** The job ID to check status for */\n jobId: string\n}\n\n/**\n * Options for getting the URL of a completed video.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport interface VideoUrlOptions<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n> extends VideoActivityBaseOptions<TAdapter> {\n /** Request type - get video URL */\n request: 'url'\n /** The job ID to get URL for */\n jobId: string\n}\n\n/**\n * Union type for all video activity options.\n * Discriminated by the `request` field.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport type VideoActivityOptions<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n TRequest extends 'create' | 'status' | 'url' = 'create',\n TStream extends boolean = false,\n> = TRequest extends 'status'\n ? VideoStatusOptions<TAdapter>\n : TRequest extends 'url'\n ? VideoUrlOptions<TAdapter>\n : VideoCreateOptions<TAdapter, TStream>\n\n// ===========================\n// Activity Result Types\n// ===========================\n\n/**\n * Result type for the video activity, based on request type and streaming.\n * - If stream is true (create request): AsyncIterable<StreamChunk>\n * - Otherwise: Promise<VideoJobResult | VideoStatusResult | VideoUrlResult>\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport type VideoActivityResult<\n TRequest extends 'create' | 'status' | 'url' = 'create',\n TStream extends boolean = false,\n> = TRequest extends 'status'\n ? Promise<VideoStatusResult>\n : TRequest extends 'url'\n ? Promise<VideoUrlResult>\n : TStream extends true\n ? AsyncIterable<StreamChunk>\n : Promise<VideoJobResult>\n\n// ===========================\n// Activity Implementation\n// ===========================\n\n/**\n * Generate video - creates a video generation job from a text prompt.\n *\n * Uses AI video generation models to create videos based on natural language descriptions.\n * Unlike image generation, video generation is asynchronous and requires polling for completion.\n *\n * When `stream: true` is passed, handles the full job lifecycle automatically:\n * create job → poll for status → stream updates → yield final result.\n *\n * @experimental Video generation is an experimental feature and may change.\n *\n * @example Create a video generation job\n * ```ts\n * import { generateVideo, getVideoJobStatus } from '@tanstack/ai'\n * import { openaiVideo } from '@tanstack/ai-openai'\n *\n * // Start a video generation job\n * const { jobId } = await generateVideo({\n * adapter: openaiVideo('sora-2'),\n * prompt: 'A cat chasing a dog in a sunny park'\n * })\n *\n * console.log('Job started:', jobId)\n *\n * // The submission only OPENS the run; the poll that sees a terminal state is\n * // what completes it. The `jobId` is the whole correlation — pass the same\n * // `middleware` and `threadId` when you use them.\n * const status = await getVideoJobStatus({\n * adapter: openaiVideo('sora-2'),\n * jobId,\n * })\n * ```\n *\n * @example Stream the full video generation lifecycle\n * ```ts\n * import { generateVideo, toServerSentEventsResponse } from '@tanstack/ai'\n * import { openaiVideo } from '@tanstack/ai-openai'\n *\n * const stream = generateVideo({\n * adapter: openaiVideo('sora-2'),\n * prompt: 'A cat chasing a dog in a sunny park',\n * stream: true,\n * pollingInterval: 3000,\n * })\n *\n * return toServerSentEventsResponse(stream)\n * ```\n */\nexport function generateVideo<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n TStream extends boolean = false,\n>(\n options: VideoCreateOptions<TAdapter, TStream>,\n): VideoActivityResult<'create', TStream> {\n if (options.stream) {\n return runStreamingVideoGeneration(\n options as VideoCreateOptions<TAdapter, true>,\n ) as VideoActivityResult<'create', TStream>\n }\n\n return runCreateVideoJob(options) as VideoActivityResult<'create', TStream>\n}\n\n/**\n * The run id a non-streaming video job is filed under, derived from the\n * provider job itself.\n *\n * A submit-and-poll run spans two calls in two different requests, so the two\n * halves need to agree on an id. Deriving it from the `jobId` — the one id a\n * poller structurally cannot be missing, because it cannot poll without it —\n * means no correlation state has to survive the boundary and there is no\n * \"forgot to pass the run id\" failure to document. The provider is part of the\n * key so two providers' job-id spaces cannot collide, and both halves are\n * percent-encoded so the joined string stays unambiguous (and url-safe, since\n * run ids end up in storage keys and query strings).\n */\nfunction videoRunIdForJob(provider: string, jobId: string): string {\n return `video:${encodeURIComponent(provider)}:${encodeURIComponent(jobId)}`\n}\n\n/**\n * Internal implementation of non-streaming video job creation.\n *\n * Submitting a job OPENS a run, it does not complete one: the video does not\n * exist yet, and the bytes only appear on a later poll. So this fires `onStart`\n * and runs the result transforms over the submission result — the jobId lands\n * on the run record, which is what lets a later request resume polling — but\n * fires NO terminal hook. {@link getVideoJobStatus} finishes the run when the\n * job settles, keyed on the same derived id.\n *\n * `onStart` therefore runs AFTER the submit request: the run's id comes from\n * the job, which does not exist until the provider accepts it. A submission\n * that fails has no job, so it opens and immediately fails a run under this\n * call's `requestId` — terminal and unresumable by construction, but it puts\n * the failure where a client hydrating the thread will see it instead of\n * showing nothing.\n */\nasync function runCreateVideoJob<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n>(options: VideoCreateOptions<TAdapter, boolean>): Promise<VideoJobResult> {\n const { adapter, prompt, size, duration, modelOptions, middleware } = options\n const model = adapter.model\n const requestId = createId('video')\n const startTime = Date.now()\n const logger: InternalLogger = resolveDebugOption(options.debug)\n const providerName =\n (adapter as { name?: string; provider?: string }).provider ??\n (adapter as { name?: string }).name ??\n 'unknown'\n\n // `runId` is resolved per outcome (from the job, or absent on failure), so the\n // context is built once the outcome is known. `options.runId` is deliberately\n // not consulted: in non-streaming mode the run id is always the derived one,\n // the single rule that keeps the two calls in agreement.\n const contextFor = (runId?: string): GenerationMiddlewareContext =>\n createGenerationContext({\n requestId,\n activity: 'video',\n provider: adapter.name,\n model,\n modelOptions,\n // Deliberately the CALLER's `threadId` — no minted fallback. A thread id\n // nobody else knows would file the run in a slot no client could hydrate,\n // which is worse than no link because it looks like one. Mirrors the\n // streaming path.\n threadId: options.threadId,\n runId,\n artifactInputs: { prompt },\n createId,\n })\n\n logger.request(`activity=generateVideo provider=${providerName}`, {\n provider: providerName,\n model,\n })\n\n let jobResult: VideoJobResult\n try {\n jobResult = await adapter.createVideoJob({\n model,\n prompt,\n size,\n duration,\n modelOptions,\n logger,\n })\n } catch (error) {\n // No jobId exists, so this run can only be keyed on the request. Start it\n // just to fail it: `generationRuns.update` on an unknown run id is a no-op\n // by contract, so without the `onStart` the failure would persist nowhere.\n const failedCtx = contextFor()\n await runGenerationStart(middleware, failedCtx)\n await runGenerationError(middleware, failedCtx, {\n error,\n duration: Date.now() - startTime,\n })\n logger.errors('generateVideo activity failed', {\n error,\n source: 'generateVideo',\n })\n throw error\n }\n\n logger.output(`activity=generateVideo jobId=${jobResult.jobId}`, {\n jobId: jobResult.jobId,\n model: jobResult.model,\n })\n\n const mwCtx = contextFor(videoRunIdForJob(adapter.name, jobResult.jobId))\n await runGenerationStart(middleware, mwCtx)\n // Transforms see the submission result (no url yet, so nothing to copy into a\n // blob store) purely so the run record captures the jobId and any prompt\n // inputs. No finish hook: the run is still running.\n return await applyGenerationResultTransforms(mwCtx, jobResult)\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n/**\n * Internal streaming implementation for video generation.\n * Handles the full job lifecycle: create job → poll for status → stream updates → yield final result.\n */\nasync function* runStreamingVideoGeneration<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n>(options: VideoCreateOptions<TAdapter, true>): AsyncIterable<StreamChunk> {\n const { adapter, prompt, size, duration, modelOptions, middleware } = options\n const model = adapter.model\n const runId = options.runId ?? createId('run')\n const requestId = createId('video')\n const obsStartTime = Date.now()\n const pollingInterval = options.pollingInterval ?? 2000\n const maxDuration = options.maxDuration ?? 600_000\n const logger: InternalLogger = resolveDebugOption(options.debug)\n const providerName =\n (adapter as { name?: string; provider?: string }).provider ??\n (adapter as { name?: string }).name ??\n 'unknown'\n\n // The wire needs a thread id on every RUN_* chunk, so one is minted when the\n // caller passes none — matching `streamGenerationResult`, which the other\n // activities stream through.\n const wireThreadId = options.threadId ?? createId('thread')\n\n yield {\n type: 'RUN_STARTED',\n runId,\n threadId: wireThreadId,\n timestamp: Date.now(),\n } as StreamChunk\n\n const mwCtx = createGenerationContext({\n requestId,\n activity: 'video',\n provider: adapter.name,\n model,\n modelOptions,\n // Identity has to reach the middleware, not just the chunks: persistence\n // keys the run record on these, and without them it falls back to the\n // internal `requestId` and records no thread link at all.\n //\n // Deliberately the CALLER's `threadId`, never `wireThreadId`: a minted id is\n // known to nobody, so persisting it would file the run in a slot no client\n // could ever hydrate — worse than recording no link, because it looks like\n // one. This mirrors `generateImage`.\n threadId: options.threadId,\n runId,\n artifactInputs: { prompt },\n createId,\n })\n\n await runGenerationStart(middleware, mwCtx)\n\n logger.request(\n `activity=generateVideo provider=${providerName} stream=true`,\n {\n provider: providerName,\n model,\n },\n )\n\n // Tracks whether a terminal observer event (finish/error) has already fired,\n // so the `finally` below can fire one on abandonment without double-firing.\n let settled = false\n try {\n // Create the video generation job\n const jobResult = await adapter.createVideoJob({\n model,\n prompt,\n size,\n duration,\n modelOptions,\n logger,\n })\n\n yield {\n type: 'CUSTOM',\n name: 'video:job:created',\n value: { jobId: jobResult.jobId },\n timestamp: Date.now(),\n }\n\n // Poll for completion\n const startTime = Date.now()\n while (Date.now() - startTime < maxDuration) {\n await sleep(pollingInterval)\n\n const statusResult = await adapter.getVideoStatus(jobResult.jobId)\n\n yield {\n type: 'CUSTOM',\n name: 'video:status',\n value: {\n jobId: jobResult.jobId,\n status: statusResult.status,\n progress: statusResult.progress,\n error: statusResult.error,\n },\n timestamp: Date.now(),\n }\n\n if (statusResult.status === 'completed') {\n const urlResult = await adapter.getVideoUrl(jobResult.jobId)\n\n logger.output(\n `activity=generateVideo jobId=${jobResult.jobId} status=completed`,\n {\n jobId: jobResult.jobId,\n url: urlResult.url,\n },\n )\n\n // Run the result transforms before anything observes the result, the\n // same as every other media activity. This is what lets persistence\n // copy the video into a blob store, attach its artifact refs, and\n // rewrite `url` to a durable app-origin one — so the chunk below and\n // the stored run record carry the SAME urls. Skipping it leaves a\n // result whose only url is the provider's expiring link.\n const rawResult = {\n jobId: jobResult.jobId,\n status: 'completed' as const,\n url: urlResult.url,\n expiresAt: urlResult.expiresAt,\n ...(urlResult.usage ? { usage: urlResult.usage } : {}),\n }\n const result = await applyGenerationResultTransforms(mwCtx, rawResult)\n\n // Fire finish before yielding the terminal chunks: the generation has\n // succeeded, so a consumer that stops reading after `generation:result`\n // (without pulling `RUN_FINISHED`) must not trip the abandonment path in\n // `finally`, which would otherwise report a spurious cancellation.\n if (urlResult.usage)\n await runGenerationUsage(middleware, mwCtx, urlResult.usage)\n await runGenerationFinish(middleware, mwCtx, {\n duration: Date.now() - obsStartTime,\n usage: urlResult.usage,\n })\n settled = true\n\n yield {\n type: 'CUSTOM',\n name: 'generation:result',\n value: result,\n timestamp: Date.now(),\n }\n\n yield {\n type: 'RUN_FINISHED',\n runId,\n threadId: wireThreadId,\n finishReason: 'stop',\n timestamp: Date.now(),\n } as StreamChunk\n return\n }\n\n if (statusResult.status === 'failed') {\n throw new Error(statusResult.error || 'Video generation failed')\n }\n }\n\n throw new Error('Video generation timed out')\n } catch (error: unknown) {\n const payload = toRunErrorPayload(error, 'Video generation failed')\n // Mark settled before firing onError: if a user error-hook throws, the\n // `finally` below must still not double-fire onAbort over the same op\n // (which would mask the original error and end the span twice).\n settled = true\n await runGenerationError(middleware, mwCtx, {\n error,\n duration: Date.now() - obsStartTime,\n })\n logger.errors('generateVideo activity failed', {\n message: payload.message,\n code: payload.code,\n source: 'generateVideo',\n })\n yield {\n type: 'RUN_ERROR',\n runId,\n threadId: wireThreadId,\n message: payload.message,\n code: payload.code,\n error: payload,\n timestamp: Date.now(),\n } as StreamChunk\n } finally {\n if (!settled) {\n // The consumer abandoned the stream (broke the `for await` loop or\n // disconnected) before completion, so the generator is being unwound at\n // a `yield` without reaching finish/error. Fire `onAbort` — a cancel, not\n // an error — so otelMiddleware ends its span instead of leaking it.\n await runGenerationAbort(middleware, mwCtx, {\n reason: 'Video generation stream abandoned before completion',\n duration: Date.now() - obsStartTime,\n })\n }\n }\n}\n\n/**\n * Options for {@link getVideoJobStatus}.\n *\n * The run this poll finishes is identified by `adapter` + `jobId` alone — the\n * same pair the submitting `generateVideo()` call derived it from — so there is\n * no run id to thread through. Pass the submission's `threadId` and the same\n * `middleware`.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport interface VideoJobStatusOptions<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n> {\n /** The video adapter to use (must be created with a model) */\n adapter: TAdapter & { kind: typeof kind }\n /** The job ID to check status for */\n jobId: string\n /**\n * The scope the run is filed under. Must match the submission's `threadId` —\n * generation persistence REFUSES a run without a scope (a run filed under\n * none can never be hydrated by one), so omitting it throws rather than\n * quietly filing the finished video somewhere unreachable.\n */\n threadId?: string\n /**\n * Observe-only middleware. Hooks fire ONLY on the poll that observes a\n * terminal job state: `onStart` (resuming the submission's run), then the\n * result transforms — which is where persistence copies the video into a blob\n * store and rewrites `url` to a durable one, so the returned result carries\n * the same urls as the stored record — then `onFinish`, or `onError` when the\n * job failed. Intermediate polls invoke nothing, so a middleware is not\n * charged for the wait.\n */\n middleware?: Array<GenerationMiddleware>\n}\n\n/**\n * The status of a video job, plus the video itself once the job completed.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport interface VideoJobStatusResult {\n /** Job identifier */\n jobId: string\n status: 'pending' | 'processing' | 'completed' | 'failed'\n progress?: number\n url?: string\n /** When the provider url expires, if it reported one. */\n expiresAt?: Date\n error?: string\n usage?: TokenUsage\n /** Durable artifact references, when generation persistence is wired. */\n artifacts?: Array<PersistedArtifactRef>\n}\n\n/**\n * Get video job status - returns the current status, progress, and URL if available.\n *\n * This function combines status checking and URL retrieval. If the job is completed,\n * it will automatically fetch and include the video URL.\n *\n * It is also where a non-streaming `generateVideo()` run ENDS: pass the same\n * `middleware` and `threadId`, and the poll that first sees a terminal job state\n * finishes the run (recording the result and its artifacts) or fails it. The run\n * is identified by `adapter` + `jobId`, exactly what the submission derived it\n * from, so there is nothing else to carry between the two calls.\n *\n * @experimental Video generation is an experimental feature and may change.\n *\n * @example Check job status\n * ```ts\n * import { getVideoJobStatus } from '@tanstack/ai'\n * import { openaiVideo } from '@tanstack/ai-openai'\n *\n * const result = await getVideoJobStatus({\n * adapter: openaiVideo('sora-2'),\n * jobId: 'job-123'\n * })\n *\n * console.log('Status:', result.status)\n * console.log('Progress:', result.progress)\n * if (result.url) {\n * console.log('Video URL:', result.url)\n * }\n * ```\n *\n * @example Submit and poll one persisted run\n * ```ts\n * import { generateVideo, getVideoJobStatus } from '@tanstack/ai'\n * import { withGenerationPersistence } from '@tanstack/ai-persistence'\n * import { openaiVideo } from '@tanstack/ai-openai'\n *\n * const adapter = openaiVideo('sora-2')\n * const middleware = [withGenerationPersistence(persistence)]\n *\n * // Opens the run (status `running`, jobId recorded). Its run id is derived\n * // from the provider job, so nothing has to be stored to resume it.\n * const { jobId } = await generateVideo({\n * adapter,\n * prompt: 'A cat chasing a dog in a sunny park',\n * threadId,\n * middleware,\n * })\n *\n * // Completes the SAME run once the job settles — this is what writes the\n * // video, its artifacts, and the terminal status. Works from a different\n * // request or process: the jobId is the only correlation.\n * const status = await getVideoJobStatus({\n * adapter,\n * jobId,\n * threadId,\n * middleware,\n * })\n * ```\n */\nexport async function getVideoJobStatus<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n>(options: VideoJobStatusOptions<TAdapter>): Promise<VideoJobStatusResult> {\n const { adapter, jobId, middleware } = options\n const requestId = createId('video-status')\n const startTime = Date.now()\n\n // Built per call but only USED on a terminal poll — `onStart` is what\n // registers the result transforms, so it has to run in the same call that\n // applies them.\n const terminalContext = (): GenerationMiddlewareContext =>\n createGenerationContext({\n requestId,\n activity: 'video',\n provider: adapter.name,\n model: adapter.model,\n threadId: options.threadId,\n // Recomputed, never passed in: the submitting call derived the same id\n // from the same provider + job, so the two halves agree without the\n // caller carrying anything but the jobId they must already have.\n runId: videoRunIdForJob(adapter.name, jobId),\n // Deliberately no `artifactInputs`: the submission already persisted any\n // prompt inputs under this run, and passing them again would store a\n // second copy of every input image.\n createId,\n })\n\n aiEventClient.emit('video:request:started', {\n requestId,\n provider: adapter.name,\n model: adapter.model,\n requestType: 'status',\n jobId,\n timestamp: startTime,\n })\n\n // Get status first\n const statusResult = await adapter.getVideoStatus(jobId)\n\n // If completed, also get the URL\n if (statusResult.status === 'completed') {\n let urlResult: VideoUrlResult\n // Scoped tightly to the provider call: a middleware hook that throws must\n // surface as itself, not be relabelled \"failed to get video URL\" and then\n // re-reported to the very middleware that threw.\n try {\n urlResult = await adapter.getVideoUrl(jobId)\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : 'Failed to get video URL'\n aiEventClient.emit('video:request:completed', {\n requestId,\n provider: adapter.name,\n model: adapter.model,\n requestType: 'status',\n jobId,\n status: 'failed',\n progress: statusResult.progress,\n error: errorMessage,\n duration: Date.now() - startTime,\n timestamp: Date.now(),\n })\n // Provider reported completed but result fetch failed — treat as failed,\n // and fail the run with it: the job is terminal, so nothing later will.\n await runGenerationError(middleware, terminalContext(), {\n error,\n duration: Date.now() - startTime,\n })\n return {\n jobId,\n status: 'failed' as const,\n progress: statusResult.progress,\n error: errorMessage,\n }\n }\n\n aiEventClient.emit('video:request:completed', {\n requestId,\n provider: adapter.name,\n model: adapter.model,\n requestType: 'status',\n jobId,\n status: statusResult.status,\n progress: statusResult.progress,\n url: urlResult.url,\n duration: Date.now() - startTime,\n timestamp: Date.now(),\n })\n if (urlResult.usage) {\n aiEventClient.emit('video:usage', {\n requestId,\n model: adapter.model,\n usage: urlResult.usage,\n timestamp: Date.now(),\n })\n }\n\n const mwCtx = terminalContext()\n await runGenerationStart(middleware, mwCtx)\n const result = await applyGenerationResultTransforms<VideoJobStatusResult>(\n mwCtx,\n {\n jobId,\n status: 'completed',\n ...(statusResult.progress !== undefined\n ? { progress: statusResult.progress }\n : {}),\n url: urlResult.url,\n ...(urlResult.expiresAt ? { expiresAt: urlResult.expiresAt } : {}),\n ...(urlResult.usage ? { usage: urlResult.usage } : {}),\n },\n )\n if (urlResult.usage)\n await runGenerationUsage(middleware, mwCtx, urlResult.usage)\n await runGenerationFinish(middleware, mwCtx, {\n duration: Date.now() - startTime,\n usage: urlResult.usage,\n })\n return result\n }\n\n aiEventClient.emit('video:request:completed', {\n requestId,\n provider: adapter.name,\n model: adapter.model,\n requestType: 'status',\n jobId,\n status: statusResult.status,\n progress: statusResult.progress,\n error: statusResult.error,\n duration: Date.now() - startTime,\n timestamp: Date.now(),\n })\n\n // A failed job is terminal for the run too: without this the record would sit\n // at `running` forever, indistinguishable from a job still being worked on.\n if (statusResult.status === 'failed') {\n await runGenerationError(middleware, terminalContext(), {\n error: new Error(statusResult.error || 'Video generation failed'),\n duration: Date.now() - startTime,\n })\n }\n\n // Return status for non-completed jobs\n return {\n jobId,\n status: statusResult.status,\n progress: statusResult.progress,\n error: statusResult.error,\n }\n}\n\n// ===========================\n// Options Factory\n// ===========================\n\n/**\n * Create typed options for the generateVideo() function without executing.\n */\nexport function createVideoOptions<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n TStream extends boolean = false,\n>(\n options: VideoCreateOptions<TAdapter, TStream>,\n): VideoCreateOptions<TAdapter, TStream> {\n return options\n}\n\n// Re-export adapter types\nexport type {\n VideoAdapter,\n VideoAdapterConfig,\n AnyVideoAdapter,\n} from './adapter'\nexport { BaseVideoAdapter } from './adapter'\n"],"mappings":";;;;;;;;;;;;;;;AA4CA,IAAa,OAAO;AA2EpB,SAAS,SAAS,QAAwB;CACxC,OAAO,GAAG,OAAO,GAAG,KAAK,IAAI,EAAE,GAAG,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC;AACzE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkPA,SAAgB,cAId,SACwC;CACxC,IAAI,QAAQ,QACV,OAAO,4BACL,OACF;CAGF,OAAO,kBAAkB,OAAO;AAClC;;;;;;;;;;;;;;AAeA,SAAS,iBAAiB,UAAkB,OAAuB;CACjE,OAAO,SAAS,mBAAmB,QAAQ,EAAE,GAAG,mBAAmB,KAAK;AAC1E;;;;;;;;;;;;;;;;;;AAmBA,eAAe,kBAEb,SAAyE;CACzE,MAAM,EAAE,SAAS,QAAQ,MAAM,UAAU,cAAc,eAAe;CACtE,MAAM,QAAQ,QAAQ;CACtB,MAAM,YAAY,SAAS,OAAO;CAClC,MAAM,YAAY,KAAK,IAAI;CAC3B,MAAM,SAAyB,mBAAmB,QAAQ,KAAK;CAC/D,MAAM,eACH,QAAiD,YACjD,QAA8B,QAC/B;CAMF,MAAM,cAAc,UAClB,wBAAwB;EACtB;EACA,UAAU;EACV,UAAU,QAAQ;EAClB;EACA;EAKA,UAAU,QAAQ;EAClB;EACA,gBAAgB,EAAE,OAAO;EACzB;CACF,CAAC;CAEH,OAAO,QAAQ,mCAAmC,gBAAgB;EAChE,UAAU;EACV;CACF,CAAC;CAED,IAAI;CACJ,IAAI;EACF,YAAY,MAAM,QAAQ,eAAe;GACvC;GACA;GACA;GACA;GACA;GACA;EACF,CAAC;CACH,SAAS,OAAO;EAId,MAAM,YAAY,WAAW;EAC7B,MAAM,m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EACb;EACA,QAAQ,aAAa;EACrB,UAAU,aAAa;EACvB,OAAO,aAAa;EACpB,UAAU,KAAK,IAAI,IAAI;EACvB,WAAW,KAAK,IAAI;CACtB,CAAC;CAID,IAAI,aAAa,WAAW,UAC1B,MAAM,mBAAmB,YAAY,gBAAgB,GAAG;EACtD,OAAO,IAAI,MAAM,aAAa,SAAS,yBAAyB;EAChE,UAAU,KAAK,IAAI,IAAI;CACzB,CAAC;CAIH,OAAO;EACL;EACA,QAAQ,aAAa;EACrB,UAAU,aAAa;EACvB,OAAO,aAAa;CACtB;AACF;;;;AASA,SAAgB,mBAId,SACuC;CACvC,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/activities/generateVideo/index.ts"],"sourcesContent":["/**\n * Video Activity (Experimental)\n *\n * Generates videos from text prompts using a jobs/polling architecture.\n * This is a self-contained module with implementation, types, and JSDoc.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\n\nimport { aiEventClient } from '@tanstack/ai-event-client'\nimport { toRunErrorPayload } from '../error-payload'\nimport { resolveDebugOption } from '../../logger/resolve'\nimport {\n applyGenerationResultTransforms,\n createGenerationContext,\n runGenerationAbort,\n runGenerationError,\n runGenerationFinish,\n runGenerationStart,\n runGenerationUsage,\n} from '../middleware/run'\nimport {\n abortReasonMessage,\n createActivityAbortControls,\n isActivityAbortError,\n raceWithAbort,\n toAbortError,\n} from '../../utilities/activity-abort'\nimport type { InternalLogger } from '../../logger/internal-logger'\nimport type { DebugOption } from '../../logger/types'\nimport type {\n GenerationMiddleware,\n GenerationMiddlewareContext,\n} from '../middleware/types'\nimport type { VideoAdapter } from './adapter'\nimport type {\n MediaPrompt,\n MediaPromptFor,\n PersistedArtifactRef,\n StreamChunk,\n TokenUsage,\n VideoJobResult,\n VideoStatusResult,\n VideoUrlResult,\n} from '../../types'\n\n// ===========================\n// Activity Kind\n// ===========================\n\n/** The adapter kind this activity handles */\nexport const kind = 'video' as const\n\n// ===========================\n// Type Extraction Helpers\n// ===========================\n\n/**\n * Extract provider options from a VideoAdapter via ~types.\n */\nexport type VideoProviderOptions<TAdapter> =\n TAdapter extends VideoAdapter<any, any, any, any, any, any>\n ? TAdapter['~types']['providerOptions']\n : object\n\n/**\n * Extract the size type for a VideoAdapter's model via ~types.\n */\nexport type VideoSizeForAdapter<TAdapter> =\n TAdapter extends VideoAdapter<\n infer TModel,\n any,\n any,\n infer TSizeMap,\n any,\n any\n >\n ? TModel extends keyof TSizeMap\n ? TSizeMap[TModel]\n : string\n : string\n\n/**\n * Extract the prompt type a model accepts from a VideoAdapter via ~types.\n * Mirrors `ImagePromptForModel`: models in the adapter's input-modality map\n * get a `prompt` narrowed to text + their supported part types; adapters\n * without a map fall back to the full MediaPrompt.\n */\nexport type VideoPromptForAdapter<TAdapter> =\n TAdapter extends VideoAdapter<\n infer TModel,\n any,\n any,\n any,\n infer ModsByName,\n any\n >\n ? string extends keyof ModsByName\n ? MediaPrompt\n : TModel extends keyof ModsByName\n ? MediaPromptFor<ModsByName[TModel][number]>\n : MediaPrompt\n : MediaPrompt\n\n/**\n * Extract the duration type for a VideoAdapter's model via ~types.\n * Mirrors `VideoSizeForAdapter`. Falls back to `number` for adapters that\n * haven't declared per-model duration constraints.\n */\nexport type VideoDurationForAdapter<TAdapter> =\n TAdapter extends VideoAdapter<\n infer TModel,\n any,\n any,\n any,\n any,\n infer TDurationMap\n >\n ? TModel extends keyof TDurationMap\n ? TDurationMap[TModel]\n : number\n : number\n\n// ===========================\n// Activity Options Types\n\nfunction createId(prefix: string): string {\n return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`\n}\n// ===========================\n\n/**\n * Base options shared by all video activity operations.\n * The model is extracted from the adapter's model property.\n */\ninterface VideoActivityBaseOptions<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n> {\n /** The video adapter to use (must be created with a model) */\n adapter: TAdapter & { kind: typeof kind }\n}\n\n/**\n * Options for creating a new video generation job.\n * The model is extracted from the adapter's model property.\n *\n * @template TAdapter - The video adapter type\n * @template TStream - Whether to stream the output\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport type VideoCreateOptions<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n TStream extends boolean = false,\n> = VideoActivityBaseOptions<TAdapter> & {\n /** Request type - create a new job (default if not specified) */\n request?: 'create'\n /**\n * Description of the desired video. Either a plain string, or — for models\n * that support image-conditioned generation — an ordered array of content\n * parts interleaving text with image inputs. Image parts may carry\n * `metadata.role` (`'start_frame' | 'end_frame' | 'reference' |\n * 'character'`) to disambiguate intent; positional fallback otherwise. The\n * accepted part types are narrowed per model via the adapter's\n * input-modality map.\n */\n prompt: VideoPromptForAdapter<TAdapter>\n /** Video size — format depends on the provider (e.g., \"16:9\", \"1280x720\") */\n size?: VideoSizeForAdapter<TAdapter>\n /**\n * Video duration in seconds. Adapters that declare a per-model duration\n * map narrow this to the model's valid union (e.g. `4 | 6 | 8` for Veo 3).\n * Pass `adapter.snapDuration(seconds)` to coerce raw seconds to a valid\n * value.\n */\n duration?: VideoDurationForAdapter<TAdapter>\n /**\n * Whether to stream the video generation lifecycle.\n * When true, returns an AsyncIterable<StreamChunk> that handles the full\n * job lifecycle: create job, poll for status, yield updates, and yield final result.\n * When false or not provided, returns a Promise<VideoJobResult>.\n *\n * @default false\n */\n stream?: TStream\n /** Polling interval in milliseconds (stream mode only). @default 2000 */\n pollingInterval?: number\n /** Maximum time to wait before timing out in milliseconds (stream mode only). @default 600000 */\n maxDuration?: number\n /**\n * Custom run id (stream mode only) — the id stamped on the emitted\n * `RUN_STARTED` / `RUN_FINISHED` chunks.\n *\n * IGNORED by a non-streaming submit. That run spans two calls, and its id is\n * derived from the provider's job instead, so {@link getVideoJobStatus} can\n * recompute it from the `jobId` you already have to poll with. Honoring a\n * custom id here would reintroduce the failure this avoids: a caller who set\n * it on the submit and forgot it on the poll would silently open a second\n * record while the first sat unfinished forever.\n */\n runId?: string\n /**\n * Stable conversation/thread id for correlating this run when persisted.\n *\n * Also the `threadId` stamped on the emitted `RUN_STARTED` / `RUN_FINISHED`\n * chunks; when omitted a throwaway id is minted for those chunks only, and\n * the persisted run record carries NO thread link rather than a fabricated\n * one. Pass it whenever persistence is on — it is the slot a reloading client\n * hydrates by, so a run stored without it can only be fetched by run id.\n */\n threadId?: string\n /**\n * Enable debug logging. Pass `true` to enable all categories, `false` to\n * silence everything including errors, or a `DebugConfig` object for granular\n * control and/or a custom `Logger`.\n */\n debug?: DebugOption\n /**\n * Observe-only middleware notified on start, usage, success, and error. Pass\n * `otelMiddleware()` to emit OpenTelemetry spans, `withGenerationPersistence()`\n * to persist the run, or implement the `GenerationMiddleware` contract for a\n * custom backend.\n *\n * In streaming mode one run covers the full create→poll→complete lifecycle:\n * `onStart` at submission, a terminal `onFinish`/`onError` when the job\n * settles, and `onAbort` if the consumer abandons the stream.\n *\n * In NON-streaming mode the call only SUBMITS the job, so it only opens the\n * run: no terminal hook fires here, because the video does not exist yet.\n * Pass the same `middleware` and `threadId` to {@link getVideoJobStatus}; the\n * poll that observes a terminal job state finishes the run and is where the\n * result and its artifacts are recorded. Nothing else has to be threaded\n * through — both calls derive the run id from the provider's `jobId`, the one\n * id a poller cannot be missing.\n *\n * Because the job id only exists once the provider accepts the job, `onStart`\n * fires AFTER the submit request rather than before it — an observer's span\n * therefore covers the run from acceptance onward, not the submit round-trip.\n * A submission that FAILS has no job to key on, so it opens and immediately\n * fails a run under this call's `requestId`: the thread's latest run reports\n * the failure (a client hydrating the slot sees it) even though there is no\n * job to resume.\n */\n middleware?: Array<GenerationMiddleware>\n /**\n * Maximum duration of this activity invocation in milliseconds.\n * No SDK-wide default — choose a value suitable for the provider and job.\n * Composed with {@link abortSignal}; the first abort wins.\n *\n * In stream mode this bounds the full create→poll→complete lifecycle and\n * complements {@link maxDuration} (which defaults to 10 minutes). When both\n * are set, the shorter limit wins via signal composition against the\n * polling deadline.\n */\n timeout?: number\n /**\n * Caller cancellation signal (request disconnects, job/runtime cancellation).\n * Composed with {@link timeout} into an effective signal forwarded to the\n * adapter on job submission. Request-specific — not stored on global\n * provider client config.\n */\n abortSignal?: AbortSignal\n} & ({} extends VideoProviderOptions<TAdapter>\n ? {\n /** Provider-specific options for video generation */ modelOptions?: VideoProviderOptions<TAdapter>\n }\n : {\n /** Provider-specific options for video generation */ modelOptions: VideoProviderOptions<TAdapter>\n })\n\n/**\n * Options for polling the status of a video generation job.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport interface VideoStatusOptions<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n> extends VideoActivityBaseOptions<TAdapter> {\n /** Request type - get job status */\n request: 'status'\n /** The job ID to check status for */\n jobId: string\n}\n\n/**\n * Options for getting the URL of a completed video.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport interface VideoUrlOptions<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n> extends VideoActivityBaseOptions<TAdapter> {\n /** Request type - get video URL */\n request: 'url'\n /** The job ID to get URL for */\n jobId: string\n}\n\n/**\n * Union type for all video activity options.\n * Discriminated by the `request` field.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport type VideoActivityOptions<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n TRequest extends 'create' | 'status' | 'url' = 'create',\n TStream extends boolean = false,\n> = TRequest extends 'status'\n ? VideoStatusOptions<TAdapter>\n : TRequest extends 'url'\n ? VideoUrlOptions<TAdapter>\n : VideoCreateOptions<TAdapter, TStream>\n\n// ===========================\n// Activity Result Types\n// ===========================\n\n/**\n * Result type for the video activity, based on request type and streaming.\n * - If stream is true (create request): AsyncIterable<StreamChunk>\n * - Otherwise: Promise<VideoJobResult | VideoStatusResult | VideoUrlResult>\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport type VideoActivityResult<\n TRequest extends 'create' | 'status' | 'url' = 'create',\n TStream extends boolean = false,\n> = TRequest extends 'status'\n ? Promise<VideoStatusResult>\n : TRequest extends 'url'\n ? Promise<VideoUrlResult>\n : TStream extends true\n ? AsyncIterable<StreamChunk>\n : Promise<VideoJobResult>\n\n// ===========================\n// Activity Implementation\n// ===========================\n\n/**\n * Generate video - creates a video generation job from a text prompt.\n *\n * Uses AI video generation models to create videos based on natural language descriptions.\n * Unlike image generation, video generation is asynchronous and requires polling for completion.\n *\n * When `stream: true` is passed, handles the full job lifecycle automatically:\n * create job → poll for status → stream updates → yield final result.\n *\n * @experimental Video generation is an experimental feature and may change.\n *\n * @example Create a video generation job\n * ```ts\n * import { generateVideo, getVideoJobStatus } from '@tanstack/ai'\n * import { openaiVideo } from '@tanstack/ai-openai'\n *\n * // Start a video generation job\n * const { jobId } = await generateVideo({\n * adapter: openaiVideo('sora-2'),\n * prompt: 'A cat chasing a dog in a sunny park'\n * })\n *\n * console.log('Job started:', jobId)\n *\n * // The submission only OPENS the run; the poll that sees a terminal state is\n * // what completes it. The `jobId` is the whole correlation — pass the same\n * // `middleware` and `threadId` when you use them.\n * const status = await getVideoJobStatus({\n * adapter: openaiVideo('sora-2'),\n * jobId,\n * })\n * ```\n *\n * @example Stream the full video generation lifecycle\n * ```ts\n * import { generateVideo, toServerSentEventsResponse } from '@tanstack/ai'\n * import { openaiVideo } from '@tanstack/ai-openai'\n *\n * const stream = generateVideo({\n * adapter: openaiVideo('sora-2'),\n * prompt: 'A cat chasing a dog in a sunny park',\n * stream: true,\n * pollingInterval: 3000,\n * })\n *\n * return toServerSentEventsResponse(stream)\n * ```\n */\nexport function generateVideo<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n TStream extends boolean = false,\n>(\n options: VideoCreateOptions<TAdapter, TStream>,\n): VideoActivityResult<'create', TStream> {\n if (options.stream) {\n return runStreamingVideoGeneration(\n options as VideoCreateOptions<TAdapter, true>,\n ) as VideoActivityResult<'create', TStream>\n }\n\n return runCreateVideoJob(options) as VideoActivityResult<'create', TStream>\n}\n\n/**\n * The run id a non-streaming video job is filed under, derived from the\n * provider job itself.\n *\n * A submit-and-poll run spans two calls in two different requests, so the two\n * halves need to agree on an id. Deriving it from the `jobId` — the one id a\n * poller structurally cannot be missing, because it cannot poll without it —\n * means no correlation state has to survive the boundary and there is no\n * \"forgot to pass the run id\" failure to document. The provider is part of the\n * key so two providers' job-id spaces cannot collide, and both halves are\n * percent-encoded so the joined string stays unambiguous (and url-safe, since\n * run ids end up in storage keys and query strings).\n */\nfunction videoRunIdForJob(provider: string, jobId: string): string {\n return `video:${encodeURIComponent(provider)}:${encodeURIComponent(jobId)}`\n}\n\n/**\n * Internal implementation of non-streaming video job creation.\n *\n * Submitting a job OPENS a run, it does not complete one: the video does not\n * exist yet, and the bytes only appear on a later poll. So this fires `onStart`\n * and runs the result transforms over the submission result — the jobId lands\n * on the run record, which is what lets a later request resume polling — but\n * fires NO terminal hook. {@link getVideoJobStatus} finishes the run when the\n * job settles, keyed on the same derived id.\n *\n * `onStart` therefore runs AFTER the submit request: the run's id comes from\n * the job, which does not exist until the provider accepts it. A submission\n * that fails has no job, so it opens and immediately fails a run under this\n * call's `requestId` — terminal and unresumable by construction, but it puts\n * the failure where a client hydrating the thread will see it instead of\n * showing nothing.\n */\nasync function runCreateVideoJob<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n>(options: VideoCreateOptions<TAdapter, boolean>): Promise<VideoJobResult> {\n const {\n adapter,\n prompt,\n size,\n duration,\n modelOptions,\n middleware,\n timeout,\n abortSignal: callerAbortSignal,\n } = options\n const model = adapter.model\n const requestId = createId('video')\n const startTime = Date.now()\n const logger: InternalLogger = resolveDebugOption(options.debug)\n const abortControls = createActivityAbortControls({\n timeout,\n abortSignal: callerAbortSignal,\n })\n const providerName =\n (adapter as { name?: string; provider?: string }).provider ??\n (adapter as { name?: string }).name ??\n 'unknown'\n\n // `runId` is resolved per outcome (from the job, or absent on failure), so the\n // context is built once the outcome is known. `options.runId` is deliberately\n // not consulted: in non-streaming mode the run id is always the derived one,\n // the single rule that keeps the two calls in agreement.\n const contextFor = (runId?: string): GenerationMiddlewareContext =>\n createGenerationContext({\n requestId,\n activity: 'video',\n provider: adapter.name,\n model,\n modelOptions,\n // Deliberately the CALLER's `threadId` — no minted fallback. A thread id\n // nobody else knows would file the run in a slot no client could hydrate,\n // which is worse than no link because it looks like one. Mirrors the\n // streaming path.\n threadId: options.threadId,\n runId,\n artifactInputs: { prompt },\n createId,\n })\n\n logger.request(`activity=generateVideo provider=${providerName}`, {\n provider: providerName,\n model,\n })\n\n let jobResult: VideoJobResult\n try {\n jobResult = await raceWithAbort(\n adapter.createVideoJob({\n model,\n prompt,\n size,\n duration,\n modelOptions,\n logger,\n ...(abortControls.signal ? { abortSignal: abortControls.signal } : {}),\n }),\n abortControls.signal,\n )\n abortControls.clear()\n } catch (error) {\n abortControls.clear()\n // No jobId exists, so this run can only be keyed on the request. Start it\n // just to fail it: `generationRuns.update` on an unknown run id is a no-op\n // by contract, so without the `onStart` the failure would persist nowhere.\n const failedCtx = contextFor()\n await runGenerationStart(middleware, failedCtx)\n const elapsed = Date.now() - startTime\n if (isActivityAbortError(error, abortControls.signal)) {\n await runGenerationAbort(middleware, failedCtx, {\n reason: abortReasonMessage(error, abortControls.signal),\n duration: elapsed,\n })\n } else {\n await runGenerationError(middleware, failedCtx, {\n error,\n duration: elapsed,\n })\n }\n logger.errors('generateVideo activity failed', {\n error,\n source: 'generateVideo',\n })\n throw error\n }\n\n logger.output(`activity=generateVideo jobId=${jobResult.jobId}`, {\n jobId: jobResult.jobId,\n model: jobResult.model,\n })\n\n const mwCtx = contextFor(videoRunIdForJob(adapter.name, jobResult.jobId))\n await runGenerationStart(middleware, mwCtx)\n // Transforms see the submission result (no url yet, so nothing to copy into a\n // blob store) purely so the run record captures the jobId and any prompt\n // inputs. No finish hook: the run is still running.\n return await applyGenerationResultTransforms(mwCtx, jobResult)\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (!signal) {\n return new Promise((resolve) => setTimeout(resolve, ms))\n }\n if (signal.aborted) {\n return Promise.reject(toAbortError(signal.reason))\n }\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', onAbort)\n resolve()\n }, ms)\n const onAbort = () => {\n clearTimeout(timer)\n signal.removeEventListener('abort', onAbort)\n reject(toAbortError(signal.reason))\n }\n signal.addEventListener('abort', onAbort, { once: true })\n })\n}\n\n/**\n * Internal streaming implementation for video generation.\n * Handles the full job lifecycle: create job → poll for status → stream updates → yield final result.\n */\nasync function* runStreamingVideoGeneration<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n>(options: VideoCreateOptions<TAdapter, true>): AsyncIterable<StreamChunk> {\n const {\n adapter,\n prompt,\n size,\n duration,\n modelOptions,\n middleware,\n timeout,\n abortSignal: callerAbortSignal,\n } = options\n const model = adapter.model\n const runId = options.runId ?? createId('run')\n const requestId = createId('video')\n const obsStartTime = Date.now()\n const pollingInterval = options.pollingInterval ?? 2000\n const maxDuration = options.maxDuration ?? 600_000\n const logger: InternalLogger = resolveDebugOption(options.debug)\n const abortControls = createActivityAbortControls({\n timeout,\n abortSignal: callerAbortSignal,\n })\n const providerName =\n (adapter as { name?: string; provider?: string }).provider ??\n (adapter as { name?: string }).name ??\n 'unknown'\n\n // The wire needs a thread id on every RUN_* chunk, so one is minted when the\n // caller passes none — matching `streamGenerationResult`, which the other\n // activities stream through.\n const wireThreadId = options.threadId ?? createId('thread')\n\n yield {\n type: 'RUN_STARTED',\n runId,\n threadId: wireThreadId,\n timestamp: Date.now(),\n } as StreamChunk\n\n const mwCtx = createGenerationContext({\n requestId,\n activity: 'video',\n provider: adapter.name,\n model,\n modelOptions,\n // Identity has to reach the middleware, not just the chunks: persistence\n // keys the run record on these, and without them it falls back to the\n // internal `requestId` and records no thread link at all.\n //\n // Deliberately the CALLER's `threadId`, never `wireThreadId`: a minted id is\n // known to nobody, so persisting it would file the run in a slot no client\n // could ever hydrate — worse than recording no link, because it looks like\n // one. This mirrors `generateImage`.\n threadId: options.threadId,\n runId,\n artifactInputs: { prompt },\n createId,\n })\n\n await runGenerationStart(middleware, mwCtx)\n\n logger.request(\n `activity=generateVideo provider=${providerName} stream=true`,\n {\n provider: providerName,\n model,\n },\n )\n\n // Tracks whether a terminal observer event (finish/error/abort) has already\n // fired, so the `finally` below can fire one on abandonment without\n // double-firing.\n let settled = false\n try {\n // Create the video generation job\n const jobResult = await raceWithAbort(\n adapter.createVideoJob({\n model,\n prompt,\n size,\n duration,\n modelOptions,\n logger,\n ...(abortControls.signal ? { abortSignal: abortControls.signal } : {}),\n }),\n abortControls.signal,\n )\n\n yield {\n type: 'CUSTOM',\n name: 'video:job:created',\n value: { jobId: jobResult.jobId },\n timestamp: Date.now(),\n }\n\n // Poll for completion\n const startTime = Date.now()\n while (Date.now() - startTime < maxDuration) {\n await sleep(pollingInterval, abortControls.signal)\n\n const statusResult = await adapter.getVideoStatus(jobResult.jobId)\n\n yield {\n type: 'CUSTOM',\n name: 'video:status',\n value: {\n jobId: jobResult.jobId,\n status: statusResult.status,\n progress: statusResult.progress,\n error: statusResult.error,\n },\n timestamp: Date.now(),\n }\n\n if (statusResult.status === 'completed') {\n const urlResult = await adapter.getVideoUrl(jobResult.jobId)\n\n logger.output(\n `activity=generateVideo jobId=${jobResult.jobId} status=completed`,\n {\n jobId: jobResult.jobId,\n url: urlResult.url,\n },\n )\n\n // Run the result transforms before anything observes the result, the\n // same as every other media activity. This is what lets persistence\n // copy the video into a blob store, attach its artifact refs, and\n // rewrite `url` to a durable app-origin one — so the chunk below and\n // the stored run record carry the SAME urls. Skipping it leaves a\n // result whose only url is the provider's expiring link.\n const rawResult = {\n jobId: jobResult.jobId,\n status: 'completed' as const,\n url: urlResult.url,\n expiresAt: urlResult.expiresAt,\n ...(urlResult.usage ? { usage: urlResult.usage } : {}),\n }\n const result = await applyGenerationResultTransforms(mwCtx, rawResult)\n\n // Fire finish before yielding the terminal chunks: the generation has\n // succeeded, so a consumer that stops reading after `generation:result`\n // (without pulling `RUN_FINISHED`) must not trip the abandonment path in\n // `finally`, which would otherwise report a spurious cancellation.\n if (urlResult.usage)\n await runGenerationUsage(middleware, mwCtx, urlResult.usage)\n await runGenerationFinish(middleware, mwCtx, {\n duration: Date.now() - obsStartTime,\n usage: urlResult.usage,\n })\n settled = true\n abortControls.clear()\n\n yield {\n type: 'CUSTOM',\n name: 'generation:result',\n value: result,\n timestamp: Date.now(),\n }\n\n yield {\n type: 'RUN_FINISHED',\n runId,\n threadId: wireThreadId,\n finishReason: 'stop',\n timestamp: Date.now(),\n } as StreamChunk\n return\n }\n\n if (statusResult.status === 'failed') {\n throw new Error(statusResult.error || 'Video generation failed')\n }\n }\n\n throw new Error('Video generation timed out')\n } catch (error: unknown) {\n abortControls.clear()\n const payload = toRunErrorPayload(error, 'Video generation failed')\n // Mark settled before firing terminal hooks: if a user error-hook throws,\n // the `finally` below must still not double-fire onAbort over the same op\n // (which would mask the original error and end the span twice).\n settled = true\n const elapsed = Date.now() - obsStartTime\n if (isActivityAbortError(error, abortControls.signal)) {\n await runGenerationAbort(middleware, mwCtx, {\n reason: abortReasonMessage(error, abortControls.signal),\n duration: elapsed,\n })\n } else {\n await runGenerationError(middleware, mwCtx, {\n error,\n duration: elapsed,\n })\n }\n logger.errors('generateVideo activity failed', {\n message: payload.message,\n code: payload.code,\n source: 'generateVideo',\n })\n yield {\n type: 'RUN_ERROR',\n runId,\n threadId: wireThreadId,\n message: payload.message,\n code: payload.code,\n error: payload,\n timestamp: Date.now(),\n } as StreamChunk\n } finally {\n abortControls.clear()\n if (!settled) {\n // The consumer abandoned the stream (broke the `for await` loop or\n // disconnected) before completion, so the generator is being unwound at\n // a `yield` without reaching finish/error. Fire `onAbort` — a cancel, not\n // an error — so otelMiddleware ends its span instead of leaking it.\n await runGenerationAbort(middleware, mwCtx, {\n reason: 'Video generation stream abandoned before completion',\n duration: Date.now() - obsStartTime,\n })\n }\n }\n}\n\n/**\n * Options for {@link getVideoJobStatus}.\n *\n * The run this poll finishes is identified by `adapter` + `jobId` alone — the\n * same pair the submitting `generateVideo()` call derived it from — so there is\n * no run id to thread through. Pass the submission's `threadId` and the same\n * `middleware`.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport interface VideoJobStatusOptions<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n> {\n /** The video adapter to use (must be created with a model) */\n adapter: TAdapter & { kind: typeof kind }\n /** The job ID to check status for */\n jobId: string\n /**\n * The scope the run is filed under. Must match the submission's `threadId` —\n * generation persistence REFUSES a run without a scope (a run filed under\n * none can never be hydrated by one), so omitting it throws rather than\n * quietly filing the finished video somewhere unreachable.\n */\n threadId?: string\n /**\n * Observe-only middleware. Hooks fire ONLY on the poll that observes a\n * terminal job state: `onStart` (resuming the submission's run), then the\n * result transforms — which is where persistence copies the video into a blob\n * store and rewrites `url` to a durable one, so the returned result carries\n * the same urls as the stored record — then `onFinish`, or `onError` when the\n * job failed. Intermediate polls invoke nothing, so a middleware is not\n * charged for the wait.\n */\n middleware?: Array<GenerationMiddleware>\n}\n\n/**\n * The status of a video job, plus the video itself once the job completed.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport interface VideoJobStatusResult {\n /** Job identifier */\n jobId: string\n status: 'pending' | 'processing' | 'completed' | 'failed'\n progress?: number\n url?: string\n /** When the provider url expires, if it reported one. */\n expiresAt?: Date\n error?: string\n usage?: TokenUsage\n /** Durable artifact references, when generation persistence is wired. */\n artifacts?: Array<PersistedArtifactRef>\n}\n\n/**\n * Get video job status - returns the current status, progress, and URL if available.\n *\n * This function combines status checking and URL retrieval. If the job is completed,\n * it will automatically fetch and include the video URL.\n *\n * It is also where a non-streaming `generateVideo()` run ENDS: pass the same\n * `middleware` and `threadId`, and the poll that first sees a terminal job state\n * finishes the run (recording the result and its artifacts) or fails it. The run\n * is identified by `adapter` + `jobId`, exactly what the submission derived it\n * from, so there is nothing else to carry between the two calls.\n *\n * @experimental Video generation is an experimental feature and may change.\n *\n * @example Check job status\n * ```ts\n * import { getVideoJobStatus } from '@tanstack/ai'\n * import { openaiVideo } from '@tanstack/ai-openai'\n *\n * const result = await getVideoJobStatus({\n * adapter: openaiVideo('sora-2'),\n * jobId: 'job-123'\n * })\n *\n * console.log('Status:', result.status)\n * console.log('Progress:', result.progress)\n * if (result.url) {\n * console.log('Video URL:', result.url)\n * }\n * ```\n *\n * @example Submit and poll one persisted run\n * ```ts\n * import { generateVideo, getVideoJobStatus } from '@tanstack/ai'\n * import { withGenerationPersistence } from '@tanstack/ai-persistence'\n * import { openaiVideo } from '@tanstack/ai-openai'\n *\n * const adapter = openaiVideo('sora-2')\n * const middleware = [withGenerationPersistence(persistence)]\n *\n * // Opens the run (status `running`, jobId recorded). Its run id is derived\n * // from the provider job, so nothing has to be stored to resume it.\n * const { jobId } = await generateVideo({\n * adapter,\n * prompt: 'A cat chasing a dog in a sunny park',\n * threadId,\n * middleware,\n * })\n *\n * // Completes the SAME run once the job settles — this is what writes the\n * // video, its artifacts, and the terminal status. Works from a different\n * // request or process: the jobId is the only correlation.\n * const status = await getVideoJobStatus({\n * adapter,\n * jobId,\n * threadId,\n * middleware,\n * })\n * ```\n */\nexport async function getVideoJobStatus<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n>(options: VideoJobStatusOptions<TAdapter>): Promise<VideoJobStatusResult> {\n const { adapter, jobId, middleware } = options\n const requestId = createId('video-status')\n const startTime = Date.now()\n\n // Built per call but only USED on a terminal poll — `onStart` is what\n // registers the result transforms, so it has to run in the same call that\n // applies them.\n const terminalContext = (): GenerationMiddlewareContext =>\n createGenerationContext({\n requestId,\n activity: 'video',\n provider: adapter.name,\n model: adapter.model,\n threadId: options.threadId,\n // Recomputed, never passed in: the submitting call derived the same id\n // from the same provider + job, so the two halves agree without the\n // caller carrying anything but the jobId they must already have.\n runId: videoRunIdForJob(adapter.name, jobId),\n // Deliberately no `artifactInputs`: the submission already persisted any\n // prompt inputs under this run, and passing them again would store a\n // second copy of every input image.\n createId,\n })\n\n aiEventClient.emit('video:request:started', {\n requestId,\n provider: adapter.name,\n model: adapter.model,\n requestType: 'status',\n jobId,\n timestamp: startTime,\n })\n\n // Get status first\n const statusResult = await adapter.getVideoStatus(jobId)\n\n // If completed, also get the URL\n if (statusResult.status === 'completed') {\n let urlResult: VideoUrlResult\n // Scoped tightly to the provider call: a middleware hook that throws must\n // surface as itself, not be relabelled \"failed to get video URL\" and then\n // re-reported to the very middleware that threw.\n try {\n urlResult = await adapter.getVideoUrl(jobId)\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : 'Failed to get video URL'\n aiEventClient.emit('video:request:completed', {\n requestId,\n provider: adapter.name,\n model: adapter.model,\n requestType: 'status',\n jobId,\n status: 'failed',\n progress: statusResult.progress,\n error: errorMessage,\n duration: Date.now() - startTime,\n timestamp: Date.now(),\n })\n // Provider reported completed but result fetch failed — treat as failed,\n // and fail the run with it: the job is terminal, so nothing later will.\n await runGenerationError(middleware, terminalContext(), {\n error,\n duration: Date.now() - startTime,\n })\n return {\n jobId,\n status: 'failed' as const,\n progress: statusResult.progress,\n error: errorMessage,\n }\n }\n\n aiEventClient.emit('video:request:completed', {\n requestId,\n provider: adapter.name,\n model: adapter.model,\n requestType: 'status',\n jobId,\n status: statusResult.status,\n progress: statusResult.progress,\n url: urlResult.url,\n duration: Date.now() - startTime,\n timestamp: Date.now(),\n })\n if (urlResult.usage) {\n aiEventClient.emit('video:usage', {\n requestId,\n model: adapter.model,\n usage: urlResult.usage,\n timestamp: Date.now(),\n })\n }\n\n const mwCtx = terminalContext()\n await runGenerationStart(middleware, mwCtx)\n const result = await applyGenerationResultTransforms<VideoJobStatusResult>(\n mwCtx,\n {\n jobId,\n status: 'completed',\n ...(statusResult.progress !== undefined\n ? { progress: statusResult.progress }\n : {}),\n url: urlResult.url,\n ...(urlResult.expiresAt ? { expiresAt: urlResult.expiresAt } : {}),\n ...(urlResult.usage ? { usage: urlResult.usage } : {}),\n },\n )\n if (urlResult.usage)\n await runGenerationUsage(middleware, mwCtx, urlResult.usage)\n await runGenerationFinish(middleware, mwCtx, {\n duration: Date.now() - startTime,\n usage: urlResult.usage,\n })\n return result\n }\n\n aiEventClient.emit('video:request:completed', {\n requestId,\n provider: adapter.name,\n model: adapter.model,\n requestType: 'status',\n jobId,\n status: statusResult.status,\n progress: statusResult.progress,\n error: statusResult.error,\n duration: Date.now() - startTime,\n timestamp: Date.now(),\n })\n\n // A failed job is terminal for the run too: without this the record would sit\n // at `running` forever, indistinguishable from a job still being worked on.\n if (statusResult.status === 'failed') {\n await runGenerationError(middleware, terminalContext(), {\n error: new Error(statusResult.error || 'Video generation failed'),\n duration: Date.now() - startTime,\n })\n }\n\n // Return status for non-completed jobs\n return {\n jobId,\n status: statusResult.status,\n progress: statusResult.progress,\n error: statusResult.error,\n }\n}\n\n// ===========================\n// Options Factory\n// ===========================\n\n/**\n * Create typed options for the generateVideo() function without executing.\n */\nexport function createVideoOptions<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n TStream extends boolean = false,\n>(\n options: VideoCreateOptions<TAdapter, TStream>,\n): VideoCreateOptions<TAdapter, TStream> {\n return options\n}\n\n// Re-export adapter types\nexport type {\n VideoAdapter,\n VideoAdapterConfig,\n AnyVideoAdapter,\n} from './adapter'\nexport { BaseVideoAdapter } from './adapter'\n"],"mappings":";;;;;;;;;;;;;;;;AAmDA,IAAa,OAAO;AA2EpB,SAAS,SAAS,QAAwB;CACxC,OAAO,GAAG,OAAO,GAAG,KAAK,IAAI,EAAE,GAAG,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC;AACzE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoQA,SAAgB,cAId,SACwC;CACxC,IAAI,QAAQ,QACV,OAAO,4BACL,OACF;CAGF,OAAO,kBAAkB,OAAO;AAClC;;;;;;;;;;;;;;AAeA,SAAS,iBAAiB,UAAkB,OAAuB;CACjE,OAAO,SAAS,mBAAmB,QAAQ,EAAE,GAAG,mBAAmB,KAAK;AAC1E;;;;;;;;;;;;;;;;;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OACA;GACE;GACA,QAAQ;GACR,GAAI,aAAa,aAAa,KAAA,IAC1B,EAAE,UAAU,aAAa,SAAS,IAClC,CAAC;GACL,KAAK,UAAU;GACf,GAAI,UAAU,YAAY,EAAE,WAAW,UAAU,UAAU,IAAI,CAAC;GAChE,GAAI,UAAU,QAAQ,EAAE,OAAO,UAAU,MAAM,IAAI,CAAC;EACtD,CACF;EACA,IAAI,UAAU,OACZ,MAAM,mBAAmB,YAAY,OAAO,UAAU,KAAK;EAC7D,MAAM,oBAAoB,YAAY,OAAO;GAC3C,UAAU,KAAK,IAAI,IAAI;GACvB,OAAO,UAAU;EACnB,CAAC;EACD,OAAO;CACT;CAEA,cAAc,KAAK,2BAA2B;EAC5C;EACA,UAAU,QAAQ;EAClB,OAAO,QAAQ;EACf,aAAa;EACb;EACA,QAAQ,aAAa;EACrB,UAAU,aAAa;EACvB,OAAO,aAAa;EACpB,UAAU,KAAK,IAAI,IAAI;EACvB,WAAW,KAAK,IAAI;CACtB,CAAC;CAID,IAAI,aAAa,WAAW,UAC1B,MAAM,mBAAmB,YAAY,gBAAgB,GAAG;EACtD,OAAO,IAAI,MAAM,aAAa,SAAS,yBAAyB;EAChE,UAAU,KAAK,IAAI,IAAI;CACzB,CAAC;CAIH,OAAO;EACL;EACA,QAAQ,aAAa;EACrB,UAAU,aAAa;EACvB,OAAO,aAAa;CACtB;AACF;;;;AASA,SAAgB,mBAId,SACuC;CACvC,OAAO;AACT"}
|
|
@@ -5,11 +5,15 @@ import { AnyAudioAdapter } from './generateAudio/adapter.js';
|
|
|
5
5
|
import { AnyVideoAdapter } from './generateVideo/adapter.js';
|
|
6
6
|
import { AnyTTSAdapter } from './generateSpeech/adapter.js';
|
|
7
7
|
import { AnyTranscriptionAdapter } from './generateTranscription/adapter.js';
|
|
8
|
+
import { AnyEmbeddingAdapter } from './embed/adapter.js';
|
|
9
|
+
import { AnyRerankAdapter } from './rerank/adapter.js';
|
|
8
10
|
export { kind as textKind, chat, type TextActivityOptions, type TextActivityResult, } from './chat/index.js';
|
|
9
11
|
export { BaseTextAdapter, type AnyTextAdapter, type TextAdapter, type TextAdapterConfig, type StructuredOutputOptions, type StructuredOutputResult, } from './chat/adapter.js';
|
|
10
12
|
export { kind as summarizeKind, summarize, type SummarizeActivityOptions, type SummarizeActivityResult, type SummarizeProviderOptions, } from './summarize/index.js';
|
|
11
13
|
export { BaseSummarizeAdapter, type SummarizeAdapter, type SummarizeAdapterConfig, type AnySummarizeAdapter, } from './summarize/adapter.js';
|
|
12
14
|
export { ChatStreamSummarizeAdapter, type ChatStreamCapable, type InferTextProviderOptions, } from './summarize/chat-stream-summarize.js';
|
|
15
|
+
export { kind as rerankKind, rerank, createRerankOptions, type RerankActivityOptions, type RerankProviderOptions, } from './rerank/index.js';
|
|
16
|
+
export { BaseRerankAdapter, type RerankAdapter, type RerankAdapterConfig, type AnyRerankAdapter, } from './rerank/adapter.js';
|
|
13
17
|
export { kind as imageKind, generateImage, type ImageActivityOptions, type ImageActivityResult, type ImageProviderOptionsForModel, type ImageSizeForModel, } from './generateImage/index.js';
|
|
14
18
|
export { BaseImageAdapter, type ImageAdapter, type ImageAdapterConfig, type AnyImageAdapter, } from './generateImage/adapter.js';
|
|
15
19
|
export { kind as audioKind, generateAudio, type AudioActivityOptions, type AudioActivityResult, type AudioProviderOptions, } from './generateAudio/index.js';
|
|
@@ -21,7 +25,9 @@ export { kind as ttsKind, generateSpeech, type TTSActivityOptions, type TTSActiv
|
|
|
21
25
|
export { BaseTTSAdapter, type TTSAdapter, type TTSAdapterConfig, type AnyTTSAdapter, } from './generateSpeech/adapter.js';
|
|
22
26
|
export { kind as transcriptionKind, generateTranscription, type TranscriptionActivityOptions, type TranscriptionActivityResult, type TranscriptionProviderOptions, } from './generateTranscription/index.js';
|
|
23
27
|
export { BaseTranscriptionAdapter, type TranscriptionAdapter, type TranscriptionAdapterConfig, type AnyTranscriptionAdapter, } from './generateTranscription/adapter.js';
|
|
28
|
+
export { kind as embeddingKind, embed, type EmbedOptions, type EmbedProviderOptionsForModel, type EmbeddingInputForModel, } from './embed/index.js';
|
|
29
|
+
export { BaseEmbeddingAdapter, type EmbeddingAdapter, type EmbeddingAdapterConfig, type AnyEmbeddingAdapter, } from './embed/adapter.js';
|
|
24
30
|
/** Union of all adapter types that can be passed to chat() */
|
|
25
|
-
export type AIAdapter = AnyTextAdapter | AnySummarizeAdapter | AnyImageAdapter | AnyAudioAdapter | AnyVideoAdapter | AnyTTSAdapter | AnyTranscriptionAdapter;
|
|
31
|
+
export type AIAdapter = AnyTextAdapter | AnySummarizeAdapter | AnyImageAdapter | AnyAudioAdapter | AnyVideoAdapter | AnyTTSAdapter | AnyTranscriptionAdapter | AnyEmbeddingAdapter | AnyRerankAdapter;
|
|
26
32
|
/** Union type of all adapter kinds */
|
|
27
|
-
export type AdapterKind = 'text' | 'summarize' | 'image' | 'audio' | 'video' | 'tts' | 'transcription';
|
|
33
|
+
export type AdapterKind = 'text' | 'summarize' | 'image' | 'audio' | 'video' | 'tts' | 'transcription' | 'embedding' | 'rerank';
|