@tanstack/ai 0.59.0 → 0.63.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/esm/activities/chat/adapter.d.ts +9 -0
- package/dist/esm/activities/chat/adapter.js +1 -0
- package/dist/esm/activities/chat/adapter.js.map +1 -1
- package/dist/esm/activities/chat/agents/define-agent.d.ts +17 -5
- package/dist/esm/activities/chat/agents/define-agent.js.map +1 -1
- package/dist/esm/activities/chat/agents/spawn.d.ts +2 -0
- package/dist/esm/activities/chat/agents/spawn.js +8 -5
- package/dist/esm/activities/chat/agents/spawn.js.map +1 -1
- package/dist/esm/activities/chat/index.js +289 -78
- package/dist/esm/activities/chat/index.js.map +1 -1
- package/dist/esm/activities/chat/messages.js +35 -19
- package/dist/esm/activities/chat/messages.js.map +1 -1
- package/dist/esm/activities/chat/middleware/types.d.ts +1 -0
- package/dist/esm/activities/chat/middleware/types.js.map +1 -1
- package/dist/esm/activities/chat/stream/message-updaters.d.ts +2 -2
- package/dist/esm/activities/chat/stream/message-updaters.js +11 -3
- package/dist/esm/activities/chat/stream/message-updaters.js.map +1 -1
- package/dist/esm/activities/chat/stream/processor.d.ts +11 -10
- package/dist/esm/activities/chat/stream/processor.js +51 -28
- package/dist/esm/activities/chat/stream/processor.js.map +1 -1
- package/dist/esm/activities/chat/tools/tool-calls.d.ts +16 -2
- package/dist/esm/activities/chat/tools/tool-calls.js +57 -16
- package/dist/esm/activities/chat/tools/tool-calls.js.map +1 -1
- package/dist/esm/activities/chat/tools/tool-definition.d.ts +4 -0
- package/dist/esm/activities/chat/tools/tool-definition.js +4 -0
- package/dist/esm/activities/chat/tools/tool-definition.js.map +1 -1
- package/dist/esm/activities/embed/adapter.d.ts +7 -0
- package/dist/esm/activities/embed/adapter.js +1 -0
- package/dist/esm/activities/embed/adapter.js.map +1 -1
- package/dist/esm/activities/embed/index.js +2 -0
- package/dist/esm/activities/embed/index.js.map +1 -1
- package/dist/esm/activities/evaluate/adapter.d.ts +4 -0
- package/dist/esm/activities/evaluate/adapter.js.map +1 -1
- package/dist/esm/activities/evaluate/index.d.ts +4 -0
- package/dist/esm/activities/evaluate/index.js +3 -1
- package/dist/esm/activities/evaluate/index.js.map +1 -1
- package/dist/esm/activities/files/adapter.d.ts +97 -0
- package/dist/esm/activities/files/adapter.js +45 -0
- package/dist/esm/activities/files/adapter.js.map +1 -0
- package/dist/esm/activities/files/index.d.ts +66 -0
- package/dist/esm/activities/files/index.js +78 -0
- package/dist/esm/activities/files/index.js.map +1 -0
- package/dist/esm/activities/generateImage/adapter.d.ts +8 -0
- package/dist/esm/activities/generateImage/adapter.js +1 -0
- package/dist/esm/activities/generateImage/adapter.js.map +1 -1
- package/dist/esm/activities/generateImage/index.js +2 -0
- package/dist/esm/activities/generateImage/index.js.map +1 -1
- package/dist/esm/activities/generateVideo/adapter.d.ts +8 -0
- package/dist/esm/activities/generateVideo/adapter.js +1 -0
- package/dist/esm/activities/generateVideo/adapter.js.map +1 -1
- package/dist/esm/activities/generateVideo/index.js +3 -0
- package/dist/esm/activities/generateVideo/index.js.map +1 -1
- package/dist/esm/activities/generateWorld/adapter.d.ts +4 -2
- package/dist/esm/activities/generateWorld/adapter.js.map +1 -1
- package/dist/esm/activities/generateWorld/index.d.ts +4 -3
- package/dist/esm/activities/generateWorld/index.js +5 -4
- package/dist/esm/activities/generateWorld/index.js.map +1 -1
- package/dist/esm/activities/index.d.ts +6 -3
- package/dist/esm/activities/index.js +13 -11
- package/dist/esm/activities/summarize/chat-stream-summarize.d.ts +2 -0
- package/dist/esm/activities/summarize/chat-stream-summarize.js +8 -8
- package/dist/esm/activities/summarize/chat-stream-summarize.js.map +1 -1
- package/dist/esm/client.d.ts +3 -1
- package/dist/esm/client.js +2 -1
- package/dist/esm/client.js.map +1 -1
- package/dist/esm/index.d.ts +4 -3
- package/dist/esm/index.js +5 -3
- package/dist/esm/interrupt-resume.js +29 -4
- package/dist/esm/interrupt-resume.js.map +1 -1
- package/dist/esm/middlewares/otel.d.ts +5 -2
- package/dist/esm/middlewares/otel.js +114 -0
- package/dist/esm/middlewares/otel.js.map +1 -1
- package/dist/esm/types.d.ts +114 -14
- package/dist/esm/utilities/ag-ui-wire.js +39 -16
- package/dist/esm/utilities/ag-ui-wire.js.map +1 -1
- package/dist/esm/utilities/content-source.d.ts +60 -0
- package/dist/esm/utilities/content-source.js +85 -0
- package/dist/esm/utilities/content-source.js.map +1 -0
- package/dist/esm/utilities/provider-executed.d.ts +7 -0
- package/dist/esm/utilities/provider-executed.js +10 -1
- package/dist/esm/utilities/provider-executed.js.map +1 -1
- package/dist/esm/utilities/tool-result.d.ts +14 -3
- package/dist/esm/utilities/tool-result.js +26 -3
- package/dist/esm/utilities/tool-result.js.map +1 -1
- package/package.json +4 -4
- package/skills/ai-core/adapter-configuration/SKILL.md +62 -0
- package/skills/ai-core/chat-experience/SKILL.md +134 -0
- package/skills/ai-core/media-generation/SKILL.md +8 -0
- package/skills/ai-core/tool-calling/SKILL.md +103 -0
- package/src/activities/chat/adapter.ts +10 -0
- package/src/activities/chat/agents/define-agent.ts +20 -3
- package/src/activities/chat/agents/spawn.ts +20 -12
- package/src/activities/chat/index.ts +458 -99
- package/src/activities/chat/messages.ts +52 -6
- package/src/activities/chat/middleware/types.ts +1 -0
- package/src/activities/chat/stream/message-updaters.ts +27 -2
- package/src/activities/chat/stream/processor.ts +81 -49
- package/src/activities/chat/tools/tool-calls.ts +104 -9
- package/src/activities/chat/tools/tool-definition.ts +8 -0
- package/src/activities/embed/adapter.ts +7 -0
- package/src/activities/embed/index.ts +5 -0
- package/src/activities/evaluate/adapter.ts +4 -0
- package/src/activities/evaluate/index.ts +6 -0
- package/src/activities/files/adapter.ts +120 -0
- package/src/activities/files/index.ts +113 -0
- package/src/activities/generateImage/adapter.ts +8 -0
- package/src/activities/generateImage/index.ts +4 -0
- package/src/activities/generateVideo/adapter.ts +8 -0
- package/src/activities/generateVideo/index.ts +7 -0
- package/src/activities/generateWorld/adapter.ts +4 -2
- package/src/activities/generateWorld/index.ts +7 -6
- package/src/activities/index.ts +25 -1
- package/src/activities/summarize/chat-stream-summarize.ts +22 -12
- package/src/client.ts +8 -0
- package/src/index.ts +17 -0
- package/src/interrupt-resume.ts +55 -4
- package/src/middlewares/otel.ts +161 -3
- package/src/types.ts +114 -14
- package/src/utilities/ag-ui-wire.ts +72 -17
- package/src/utilities/content-source.ts +138 -0
- package/src/utilities/provider-executed.ts +13 -0
- package/src/utilities/tool-result.ts +45 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/activities/files/index.ts"],"sourcesContent":["/**\n * Files Activity\n *\n * Dispatch functions for provider Files APIs. Each takes `{ adapter, ... }` and\n * calls the adapter method directly (mirrors the other activity dispatchers).\n * `get`/`delete` are optional on the adapter; the dispatchers throw a clear\n * error when the selected provider has no lifecycle API.\n */\n\nimport type { ContentPartFileSource } from '../../types'\nimport type { FileHandle, FileUploadInput, FilesAdapter } from './adapter'\n\n/** The adapter kind this activity handles */\nexport const kind = 'files' as const\n\n/**\n * Upload a file to a provider's Files API and return its handle. The handle\n * carries the provider name as a literal type, so passing it to another\n * provider's lifecycle call is a compile error.\n *\n * @example\n * ```ts\n * const files = openaiFiles()\n * const handle = await uploadFile({ adapter: files, input: { data, mimeType: 'image/png' } })\n * ```\n */\nexport async function uploadFile<TName extends string>(options: {\n adapter: FilesAdapter<TName> & { kind: typeof kind }\n input: FileUploadInput\n}): Promise<FileHandle<TName>> {\n return options.adapter.upload(options.input)\n}\n\n/**\n * Resolve a lifecycle id from either a raw id string or a {@link FileHandle}\n * (whose `id` — not its `uri`/wire value — is the lifecycle currency).\n */\nfunction toLifecycleId(id: string | FileHandle): string {\n return typeof id === 'string' ? id : id.id\n}\n\n/**\n * Fetch metadata for a previously uploaded file. Accepts the handle itself\n * (preferred — the provider-literal type rejects a foreign provider's handle\n * at compile time) or its raw lifecycle id.\n *\n * @throws if the provider's files adapter has no `get` (e.g. fal storage).\n */\nexport async function getFile<TName extends string>(options: {\n adapter: FilesAdapter<TName> & { kind: typeof kind }\n // `NoInfer` so `TName` comes from the adapter only. Otherwise a foreign\n // handle widens it to a union and the call compiles.\n id: string | FileHandle<NoInfer<TName>>\n}): Promise<FileHandle<TName>> {\n const { adapter } = options\n if (!adapter.get) {\n throw new Error(\n `${adapter.name}: files adapter does not support get() — this provider ` +\n `has no file-retrieval API.`,\n )\n }\n return adapter.get(toLifecycleId(options.id))\n}\n\n/**\n * Delete a previously uploaded file. Accepts the handle itself (preferred —\n * the provider-literal type rejects a foreign provider's handle at compile\n * time) or its raw lifecycle id.\n *\n * @throws if the provider's files adapter has no `delete` (e.g. fal storage).\n */\nexport async function deleteFile<TName extends string>(options: {\n adapter: FilesAdapter<TName> & { kind: typeof kind }\n id: string | FileHandle<NoInfer<TName>>\n}): Promise<void> {\n const { adapter } = options\n if (!adapter.delete) {\n throw new Error(\n `${adapter.name}: files adapter does not support delete() — this ` +\n `provider has no file-deletion API.`,\n )\n }\n return adapter.delete(toLifecycleId(options.id))\n}\n\n/**\n * Build a `{ type: 'file' }` content source from an uploaded\n * {@link FileHandle}, for use in a chat message (image/audio/document part\n * `source`).\n *\n * The source's `value` is the handle's wire form: the handle URL when the\n * provider exposes one (Gemini, fal, Grok), otherwise the opaque id (OpenAI,\n * Anthropic). `provider` records the issuer, so an adapter for a different\n * provider rejects the source rather than sending a handle it cannot resolve.\n *\n * @example\n * ```ts\n * const handle = await uploadFile({ adapter: openaiFiles(), input })\n * messages.push({ role: 'user', content: [\n * { type: 'image', source: fileSourceFromHandle(handle) },\n * ] })\n * ```\n */\nexport function fileSourceFromHandle<TProvider extends string>(\n handle: FileHandle<TProvider>,\n): ContentPartFileSource<TProvider> {\n return {\n type: 'file',\n value: handle.uri ?? handle.id,\n provider: handle.provider,\n ...(handle.mimeType ? { mimeType: handle.mimeType } : {}),\n }\n}\n"],"mappings":";;AAaA,IAAa,OAAO;;;;;;;;;;;;AAapB,eAAsB,WAAiC,SAGxB;CAC7B,OAAO,QAAQ,QAAQ,OAAO,QAAQ,KAAK;AAC7C;;;;;AAMA,SAAS,cAAc,IAAiC;CACtD,OAAO,OAAO,OAAO,WAAW,KAAK,GAAG;AAC1C;;;;;;;;AASA,eAAsB,QAA8B,SAKrB;CAC7B,MAAM,EAAE,YAAY;CACpB,IAAI,CAAC,QAAQ,KACX,MAAM,IAAI,MACR,GAAG,QAAQ,KAAK,kFAElB;CAEF,OAAO,QAAQ,IAAI,cAAc,QAAQ,EAAE,CAAC;AAC9C;;;;;;;;AASA,eAAsB,WAAiC,SAGrC;CAChB,MAAM,EAAE,YAAY;CACpB,IAAI,CAAC,QAAQ,QACX,MAAM,IAAI,MACR,GAAG,QAAQ,KAAK,oFAElB;CAEF,OAAO,QAAQ,OAAO,cAAc,QAAQ,EAAE,CAAC;AACjD;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,qBACd,QACkC;CAClC,OAAO;EACL,MAAM;EACN,OAAO,OAAO,OAAO,OAAO;EAC5B,UAAU,OAAO;EACjB,GAAI,OAAO,WAAW,EAAE,UAAU,OAAO,SAAS,IAAI,CAAC;CACzD;AACF"}
|
|
@@ -34,6 +34,13 @@ export interface ImageAdapter<TModel extends string = string, TProviderOptions e
|
|
|
34
34
|
readonly kind: 'image';
|
|
35
35
|
/** Adapter name identifier */
|
|
36
36
|
readonly name: string;
|
|
37
|
+
/**
|
|
38
|
+
* Declares that this adapter can consume `{ type: 'file' }` content
|
|
39
|
+
* sources (provider Files API references). The activity dispatcher rejects
|
|
40
|
+
* file sources in preflight for adapters that don't declare this, so
|
|
41
|
+
* adapters written before the file arm existed fail closed.
|
|
42
|
+
*/
|
|
43
|
+
readonly supportsFileSources?: boolean;
|
|
37
44
|
/** The model this adapter is configured for */
|
|
38
45
|
readonly model: TModel;
|
|
39
46
|
/**
|
|
@@ -64,6 +71,7 @@ export type AnyImageAdapter = ImageAdapter<any, any, any, any, any>;
|
|
|
64
71
|
export declare abstract class BaseImageAdapter<TModel extends string = string, TProviderOptions extends object = Record<string, unknown>, TModelProviderOptionsByName extends Record<string, any> = Record<string, any>, TModelSizeByName extends Record<string, string | undefined> = Record<string, string>, TModelInputModalitiesByName extends ModelInputModalitiesByName = ModelInputModalitiesByName> implements ImageAdapter<TModel, TProviderOptions, TModelProviderOptionsByName, TModelSizeByName, TModelInputModalitiesByName> {
|
|
65
72
|
readonly kind: "image";
|
|
66
73
|
abstract readonly name: string;
|
|
74
|
+
readonly supportsFileSources: boolean;
|
|
67
75
|
readonly model: TModel;
|
|
68
76
|
'~types': {
|
|
69
77
|
providerOptions: TProviderOptions;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adapter.js","names":[],"sources":["../../../../src/activities/generateImage/adapter.ts"],"sourcesContent":["import type {\n ImageGenerationOptions,\n ImageGenerationResult,\n ModelInputModalitiesByName,\n} from '../../types'\n\n/**\n * Resolve the size type for a model from the model-size map.\n * If the map has an index signature (i.e. no explicit keys), falls back to string.\n * If the model is an explicit key, uses its mapped size type.\n * Otherwise falls back to string.\n */\n\n/**\n * Configuration for image adapter instances\n */\nexport interface ImageAdapterConfig {\n apiKey?: string\n baseUrl?: string\n timeout?: number\n maxRetries?: number\n headers?: Record<string, string>\n}\n\n/**\n * Image adapter interface with pre-resolved generics.\n *\n * An adapter is created by a provider function: `provider('model')` → `adapter`\n * All type resolution happens at the provider call site, not in this interface.\n *\n * Generic parameters:\n * - TModel: The specific model name (e.g., 'dall-e-3')\n * - TProviderOptions: Base provider-specific options (already resolved)\n * - TModelProviderOptionsByName: Map from model name to its specific provider options\n * - TModelSizeByName: Map from model name to its supported sizes\n * - TModelInputModalitiesByName: Map from model name to the non-text prompt\n * modalities it accepts (constrains the `prompt` part types at compile time)\n */\nexport interface ImageAdapter<\n TModel extends string = string,\n TProviderOptions extends object = Record<string, unknown>,\n TModelProviderOptionsByName extends Record<string, any> = Record<string, any>,\n TModelSizeByName extends Record<string, string | undefined> = Record<\n string,\n string\n >,\n TModelInputModalitiesByName extends ModelInputModalitiesByName =\n ModelInputModalitiesByName,\n> {\n /** Discriminator for adapter kind - used by generate() to determine API shape */\n readonly kind: 'image'\n /** Adapter name identifier */\n readonly name: string\n /** The model this adapter is configured for */\n readonly model: TModel\n\n /**\n * @internal Type-only properties for inference. Not assigned at runtime.\n */\n '~types': {\n providerOptions: TProviderOptions\n modelProviderOptionsByName: TModelProviderOptionsByName\n modelSizeByName: TModelSizeByName\n modelInputModalitiesByName: TModelInputModalitiesByName\n }\n\n /**\n * Generate images from a prompt\n */\n generateImages: (\n options: ImageGenerationOptions<TProviderOptions, TModelSizeByName[TModel]>,\n ) => Promise<ImageGenerationResult>\n}\n\n/**\n * An ImageAdapter with any/unknown type parameters.\n * Useful as a constraint in generic functions and interfaces.\n */\nexport type AnyImageAdapter = ImageAdapter<any, any, any, any, any>\n\n/**\n * Abstract base class for image generation adapters.\n * Extend this class to implement an image adapter for a specific provider.\n *\n * Generic parameters match ImageAdapter - all pre-resolved by the provider function.\n */\nexport abstract class BaseImageAdapter<\n TModel extends string = string,\n TProviderOptions extends object = Record<string, unknown>,\n TModelProviderOptionsByName extends Record<string, any> = Record<string, any>,\n TModelSizeByName extends Record<string, string | undefined> = Record<\n string,\n string\n >,\n TModelInputModalitiesByName extends ModelInputModalitiesByName =\n ModelInputModalitiesByName,\n> implements ImageAdapter<\n TModel,\n TProviderOptions,\n TModelProviderOptionsByName,\n TModelSizeByName,\n TModelInputModalitiesByName\n> {\n readonly kind = 'image' as const\n abstract readonly name: string\n readonly model: TModel\n\n // Type-only property - never assigned at runtime\n declare '~types': {\n providerOptions: TProviderOptions\n modelProviderOptionsByName: TModelProviderOptionsByName\n modelSizeByName: TModelSizeByName\n modelInputModalitiesByName: TModelInputModalitiesByName\n }\n\n protected config: ImageAdapterConfig\n\n constructor(model: TModel, config: ImageAdapterConfig = {}) {\n this.config = config\n this.model = model\n }\n\n abstract generateImages(\n options: ImageGenerationOptions<TProviderOptions, TModelSizeByName[TModel]>,\n ): Promise<ImageGenerationResult>\n\n protected generateId(): string {\n return `${this.name}-${Date.now()}-${Math.random().toString(36).substring(7)}`\n }\n}\n"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"adapter.js","names":[],"sources":["../../../../src/activities/generateImage/adapter.ts"],"sourcesContent":["import type {\n ImageGenerationOptions,\n ImageGenerationResult,\n ModelInputModalitiesByName,\n} from '../../types'\n\n/**\n * Resolve the size type for a model from the model-size map.\n * If the map has an index signature (i.e. no explicit keys), falls back to string.\n * If the model is an explicit key, uses its mapped size type.\n * Otherwise falls back to string.\n */\n\n/**\n * Configuration for image adapter instances\n */\nexport interface ImageAdapterConfig {\n apiKey?: string\n baseUrl?: string\n timeout?: number\n maxRetries?: number\n headers?: Record<string, string>\n}\n\n/**\n * Image adapter interface with pre-resolved generics.\n *\n * An adapter is created by a provider function: `provider('model')` → `adapter`\n * All type resolution happens at the provider call site, not in this interface.\n *\n * Generic parameters:\n * - TModel: The specific model name (e.g., 'dall-e-3')\n * - TProviderOptions: Base provider-specific options (already resolved)\n * - TModelProviderOptionsByName: Map from model name to its specific provider options\n * - TModelSizeByName: Map from model name to its supported sizes\n * - TModelInputModalitiesByName: Map from model name to the non-text prompt\n * modalities it accepts (constrains the `prompt` part types at compile time)\n */\nexport interface ImageAdapter<\n TModel extends string = string,\n TProviderOptions extends object = Record<string, unknown>,\n TModelProviderOptionsByName extends Record<string, any> = Record<string, any>,\n TModelSizeByName extends Record<string, string | undefined> = Record<\n string,\n string\n >,\n TModelInputModalitiesByName extends ModelInputModalitiesByName =\n ModelInputModalitiesByName,\n> {\n /** Discriminator for adapter kind - used by generate() to determine API shape */\n readonly kind: 'image'\n /** Adapter name identifier */\n readonly name: string\n /**\n * Declares that this adapter can consume `{ type: 'file' }` content\n * sources (provider Files API references). The activity dispatcher rejects\n * file sources in preflight for adapters that don't declare this, so\n * adapters written before the file arm existed fail closed.\n */\n readonly supportsFileSources?: boolean\n /** The model this adapter is configured for */\n readonly model: TModel\n\n /**\n * @internal Type-only properties for inference. Not assigned at runtime.\n */\n '~types': {\n providerOptions: TProviderOptions\n modelProviderOptionsByName: TModelProviderOptionsByName\n modelSizeByName: TModelSizeByName\n modelInputModalitiesByName: TModelInputModalitiesByName\n }\n\n /**\n * Generate images from a prompt\n */\n generateImages: (\n options: ImageGenerationOptions<TProviderOptions, TModelSizeByName[TModel]>,\n ) => Promise<ImageGenerationResult>\n}\n\n/**\n * An ImageAdapter with any/unknown type parameters.\n * Useful as a constraint in generic functions and interfaces.\n */\nexport type AnyImageAdapter = ImageAdapter<any, any, any, any, any>\n\n/**\n * Abstract base class for image generation adapters.\n * Extend this class to implement an image adapter for a specific provider.\n *\n * Generic parameters match ImageAdapter - all pre-resolved by the provider function.\n */\nexport abstract class BaseImageAdapter<\n TModel extends string = string,\n TProviderOptions extends object = Record<string, unknown>,\n TModelProviderOptionsByName extends Record<string, any> = Record<string, any>,\n TModelSizeByName extends Record<string, string | undefined> = Record<\n string,\n string\n >,\n TModelInputModalitiesByName extends ModelInputModalitiesByName =\n ModelInputModalitiesByName,\n> implements ImageAdapter<\n TModel,\n TProviderOptions,\n TModelProviderOptionsByName,\n TModelSizeByName,\n TModelInputModalitiesByName\n> {\n readonly kind = 'image' as const\n abstract readonly name: string\n readonly supportsFileSources: boolean = false\n readonly model: TModel\n\n // Type-only property - never assigned at runtime\n declare '~types': {\n providerOptions: TProviderOptions\n modelProviderOptionsByName: TModelProviderOptionsByName\n modelSizeByName: TModelSizeByName\n modelInputModalitiesByName: TModelInputModalitiesByName\n }\n\n protected config: ImageAdapterConfig\n\n constructor(model: TModel, config: ImageAdapterConfig = {}) {\n this.config = config\n this.model = model\n }\n\n abstract generateImages(\n options: ImageGenerationOptions<TProviderOptions, TModelSizeByName[TModel]>,\n ): Promise<ImageGenerationResult>\n\n protected generateId(): string {\n return `${this.name}-${Date.now()}-${Math.random().toString(36).substring(7)}`\n }\n}\n"],"mappings":";;;;;;;AA6FA,IAAsB,mBAAtB,MAgBE;CACA,OAAgB;CAEhB,sBAAwC;CACxC;CAUA;CAEA,YAAY,OAAe,SAA6B,CAAC,GAAG;EAC1D,KAAK,SAAS;EACd,KAAK,QAAQ;CACf;CAMA,aAA+B;EAC7B,OAAO,GAAG,KAAK,KAAK,GAAG,KAAK,IAAI,EAAE,GAAG,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,UAAU,CAAC;CAC7E;AACF"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { resolveDebugOption } from "../../logger/resolve.js";
|
|
2
|
+
import { assertPromptFileSourceSupport } from "../../utilities/content-source.js";
|
|
2
3
|
import { applyGenerationResultTransforms, createGenerationContext, runGenerationAbort, runGenerationError, runGenerationFinish, runGenerationStart, runGenerationUsage } from "../middleware/run.js";
|
|
3
4
|
import { streamGenerationResult } from "../stream-generation-result.js";
|
|
4
5
|
import { abortReasonMessage, createActivityAbortControls, isActivityAbortError, raceWithAbort } from "../../utilities/activity-abort.js";
|
|
@@ -63,6 +64,7 @@ function createId(prefix) {
|
|
|
63
64
|
* ```
|
|
64
65
|
*/
|
|
65
66
|
function generateImage(options) {
|
|
67
|
+
assertPromptFileSourceSupport(options.adapter, options.prompt);
|
|
66
68
|
if (options.stream) return streamGenerationResult((resolved) => runGenerateImage({
|
|
67
69
|
...options,
|
|
68
70
|
runId: resolved.runId
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/activities/generateImage/index.ts"],"sourcesContent":["/**\n * Image Activity\n *\n * Generates images from text prompts.\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 { resolveMediaPrompt } from '../../utilities/media-prompt'\nimport type { InternalLogger } from '../../logger/internal-logger'\nimport type { DebugOption } from '../../logger/types'\nimport type { GenerationMiddleware } from '../middleware/types'\nimport type { ImageAdapter } from './adapter'\nimport type {\n ImageGenerationResult,\n MediaPrompt,\n MediaPromptFor,\n StreamChunk,\n} from '../../types'\n\n// ===========================\n// Activity Kind\n// ===========================\n\n/** The adapter kind this activity handles */\nexport const kind = 'image' as const\n\n// ===========================\n// Type Extraction Helpers\n// ===========================\n\n/**\n * Extract model-specific provider options from an ImageAdapter via ~types.\n * If the model has specific options defined in ModelProviderOptions (and not just via index signature),\n * use those; otherwise fall back to base provider options.\n */\nexport type ImageProviderOptionsForModel<TAdapter, TModel extends string> =\n TAdapter extends ImageAdapter<any, infer BaseOptions, infer ModelOptions, any>\n ? string extends keyof ModelOptions\n ? // ModelOptions is Record<string, unknown> or has index signature - use BaseOptions\n BaseOptions\n : // ModelOptions has explicit keys - check if TModel is one of them\n TModel extends keyof ModelOptions\n ? ModelOptions[TModel]\n : BaseOptions\n : object\n\n/**\n * Extract model-specific size options from an ImageAdapter via ~types.\n * If the model has specific sizes defined, use those; otherwise fall back to string.\n */\nexport type ImageSizeForModel<TAdapter, TModel extends string> =\n TAdapter extends ImageAdapter<any, any, any, infer SizeByName>\n ? string extends keyof SizeByName\n ? // SizeByName has index signature - fall back to string\n string\n : // SizeByName has explicit keys - check if TModel is one of them\n TModel extends keyof SizeByName\n ? SizeByName[TModel]\n : string\n : string\n\n/**\n * Extract the prompt type a model accepts from an ImageAdapter via ~types.\n * Adapters declare a per-model input-modality map; models in the map get a\n * `prompt` narrowed to text + their supported part types (text-only models\n * accept `string | Array<TextPart>`), so unsupported media parts fail at\n * compile time. Adapters without a map fall back to the full MediaPrompt.\n */\nexport type ImagePromptForModel<TAdapter, TModel extends string> =\n TAdapter extends ImageAdapter<any, any, any, any, infer ModsByName>\n ? string extends keyof ModsByName\n ? // No explicit map - accept the full union\n MediaPrompt\n : TModel extends keyof ModsByName\n ? MediaPromptFor<ModsByName[TModel][number]>\n : MediaPrompt\n : MediaPrompt\n\n// ===========================\n// Activity Options Type\n// ===========================\n\n/**\n * Options for the image activity.\n * The model is extracted from the adapter's model property.\n *\n * @template TAdapter - The image adapter type\n * @template TStream - Whether to stream the output\n */\nexport type ImageActivityOptions<\n TAdapter extends ImageAdapter<string, any, any, any>,\n TStream extends boolean = false,\n> = {\n /** The image adapter to use (must be created with a model) */\n adapter: TAdapter & { kind: typeof kind }\n /**\n * Description of the desired image(s). Either a plain string, or — for\n * models that support image-conditioned generation — an ordered array of\n * content parts interleaving text with image inputs (image-to-image,\n * reference-guided, edit, multi-reference). Media parts may carry\n * `metadata.role` (`'reference' | 'mask' | 'control' | 'character'`) to\n * disambiguate intent. The accepted part types are narrowed per model via\n * the adapter's input-modality map.\n */\n prompt: ImagePromptForModel<TAdapter, TAdapter['model']>\n /** Number of images to generate (default: 1) */\n numberOfImages?: number\n /** Image size in WIDTHxHEIGHT format (e.g., \"1024x1024\") */\n size?: ImageSizeForModel<TAdapter, TAdapter['model']>\n /**\n * Whether to stream the image generation result.\n * When true, returns an AsyncIterable<StreamChunk> for streaming transport.\n * When false or not provided, returns a Promise<ImageGenerationResult>.\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} & ({} extends ImageProviderOptionsForModel<TAdapter, TAdapter['model']>\n ? {\n /** Provider-specific options for image generation */ modelOptions?: ImageProviderOptionsForModel<\n TAdapter,\n TAdapter['model']\n >\n }\n : {\n /** Provider-specific options for image generation */ modelOptions: ImageProviderOptionsForModel<\n TAdapter,\n TAdapter['model']\n >\n })\n\n// ===========================\n// Activity Result Type\n// ===========================\n\n/**\n * Result type for the image activity.\n * - If stream is true: AsyncIterable<StreamChunk>\n * - Otherwise: Promise<ImageGenerationResult>\n */\nexport type ImageActivityResult<TStream extends boolean = false> =\n TStream extends true\n ? AsyncIterable<StreamChunk>\n : Promise<ImageGenerationResult>\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 * Image activity - generates images from text prompts.\n *\n * Uses AI image generation models to create images based on natural language descriptions.\n *\n * @example Generate a single image\n * ```ts\n * import { generateImage } from '@tanstack/ai'\n * import { openaiImage } from '@tanstack/ai-openai'\n *\n * const result = await generateImage({\n * adapter: openaiImage('dall-e-3'),\n * prompt: 'A serene mountain landscape at sunset'\n * })\n *\n * console.log(result.images[0].url)\n * ```\n *\n * @example Generate multiple images\n * ```ts\n * const result = await generateImage({\n * adapter: openaiImage('dall-e-2'),\n * prompt: 'A cute robot mascot',\n * numberOfImages: 4,\n * size: '512x512'\n * })\n *\n * result.images.forEach((image, i) => {\n * console.log(`Image ${i + 1}: ${image.url}`)\n * })\n * ```\n *\n * @example With provider-specific options\n * ```ts\n * const result = await generateImage({\n * adapter: openaiImage('dall-e-3'),\n * prompt: 'A professional headshot photo',\n * size: '1024x1024',\n * modelOptions: {\n * quality: 'hd',\n * style: 'natural'\n * }\n * })\n * ```\n */\nexport function generateImage<\n TAdapter extends ImageAdapter<string, any, any, any>,\n TStream extends boolean = false,\n>(\n options: ImageActivityOptions<TAdapter, TStream>,\n): ImageActivityResult<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) => runGenerateImage({ ...options, runId: resolved.runId }),\n options,\n ) as ImageActivityResult<TStream>\n }\n\n return runGenerateImage(options) as ImageActivityResult<TStream>\n}\n\n/**\n * Internal implementation of image generation (always non-streaming).\n * Contains all devtools event emission logic.\n */\nasync function runGenerateImage<\n TAdapter extends ImageAdapter<string, any, any, any>,\n>(\n options: ImageActivityOptions<TAdapter, boolean>,\n): Promise<ImageGenerationResult> {\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('image')\n const startTime = Date.now()\n const logger: InternalLogger = resolveDebugOption(options.debug)\n const abortControls = createActivityAbortControls({\n timeout,\n abortSignal: callerAbortSignal,\n })\n\n const mwCtx = createGenerationContext({\n requestId,\n activity: 'image',\n provider: adapter.name,\n model,\n modelOptions: rest.modelOptions,\n threadId,\n runId,\n artifactInputs: { prompt: rest.prompt },\n createId,\n })\n\n await runGenerationStart(middleware, mwCtx)\n\n // Devtools events carry the flattened prompt text plus media-part counts —\n // the wire payload stays `prompt: string` regardless of the prompt shape.\n const resolved = resolveMediaPrompt(rest.prompt)\n\n aiEventClient.emit('image:request:started', {\n requestId,\n provider: adapter.name,\n model,\n prompt: resolved.text,\n numberOfImages: rest.numberOfImages,\n size: rest.size,\n ...(resolved.images.length > 0 && {\n imageInputCount: resolved.images.length,\n }),\n ...(resolved.videos.length > 0 && {\n videoInputCount: resolved.videos.length,\n }),\n ...(resolved.audios.length > 0 && {\n audioInputCount: resolved.audios.length,\n }),\n modelOptions: rest.modelOptions,\n timestamp: startTime,\n })\n\n logger.request(`activity=generateImage provider=${adapter.name}`, {\n provider: adapter.name,\n model,\n })\n\n try {\n const rawResult = await raceWithAbort(\n adapter.generateImages({\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('image:request:completed', {\n requestId,\n provider: adapter.name,\n model,\n // GeneratedImage is a discriminated `{ url } | { b64Json }` union, but the\n // wire shape on the devtools event is a plain optional pair. Use\n // conditional spreads so the emitted record only sets the field actually\n // present — `exactOptionalPropertyTypes` rejects `field: undefined`\n // against `field?: string` targets.\n images: result.images.map((image) => ({\n url: image.url,\n b64Json: image.b64Json,\n })),\n duration,\n modelOptions: rest.modelOptions,\n timestamp: Date.now(),\n })\n\n if (result.usage) {\n aiEventClient.emit('image:usage', {\n requestId,\n model,\n usage: result.usage,\n modelOptions: rest.modelOptions,\n timestamp: Date.now(),\n })\n }\n\n logger.output(`activity=generateImage count=${result.images.length}`, {\n count: result.images.length,\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 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('generateImage activity failed', {\n error,\n source: 'generateImage',\n })\n throw error\n }\n}\n\n// ===========================\n// Options Factory\n// ===========================\n\n/**\n * Create typed options for the generateImage() function without executing.\n */\nexport function createImageOptions<\n TAdapter extends ImageAdapter<string, any, any, any>,\n TStream extends boolean = false,\n>(\n options: ImageActivityOptions<TAdapter, TStream>,\n): ImageActivityOptions<TAdapter, TStream> {\n return options\n}\n\n// Re-export adapter types\nexport type {\n ImageAdapter,\n ImageAdapterConfig,\n AnyImageAdapter,\n} from './adapter'\nexport { BaseImageAdapter } from './adapter'\n"],"mappings":";;;;;;;;;;;;;;;AA0CA,IAAa,OAAO;AAqJpB,SAAS,SAAS,QAAwB;CACxC,OAAO,GAAG,OAAO,GAAG,KAAK,IAAI,EAAE,GAAG,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC;AACzE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,SAAgB,cAId,SAC8B;CAC9B,IAAI,QAAQ,QACV,OAAO,wBAMJ,aAAa,iBAAiB;EAAE,GAAG;EAAS,OAAO,SAAS;CAAM,CAAC,GACpE,OACF;CAGF,OAAO,iBAAiB,OAAO;AACjC;;;;;AAMA,eAAe,iBAGb,SACgC;CAChC,MAAM,EACJ,SACA,QAAQ,SACR,OAAO,QACP,YACA,UACA,OACA,SACA,aAAa,mBACb,GAAG,SACD;CACJ,MAAM,QAAQ,QAAQ;CACtB,MAAM,YAAY,SAAS,OAAO;CAClC,MAAM,YAAY,KAAK,IAAI;CAC3B,MAAM,SAAyB,mBAAmB,QAAQ,KAAK;CAC/D,MAAM,gBAAgB,4BAA4B;EAChD;EACA,aAAa;CACf,CAAC;CAED,MAAM,QAAQ,wBAAwB;EACpC;EACA,UAAU;EACV,UAAU,QAAQ;EAClB;EACA,cAAc,KAAK;EACnB;EACA;EACA,gBAAgB,EAAE,QAAQ,KAAK,OAAO;EACtC;CACF,CAAC;CAED,MAAM,mBAAmB,YAAY,KAAK;CAI1C,MAAM,WAAW,mBAAmB,KAAK,MAAM;CAE/C,cAAc,KAAK,yBAAyB;EAC1C;EACA,UAAU,QAAQ;E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AW,KAAK,IAAI,IAAI;EAC9B,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,iCAAiC;GAC7C;GACA,QAAQ;EACV,CAAC;EACD,MAAM;CACR;AACF;;;;AASA,SAAgB,mBAId,SACyC;CACzC,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/activities/generateImage/index.ts"],"sourcesContent":["/**\n * Image Activity\n *\n * Generates images from text prompts.\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 { resolveMediaPrompt } from '../../utilities/media-prompt'\nimport { assertPromptFileSourceSupport } from '../../utilities/content-source'\nimport type { InternalLogger } from '../../logger/internal-logger'\nimport type { DebugOption } from '../../logger/types'\nimport type { GenerationMiddleware } from '../middleware/types'\nimport type { ImageAdapter } from './adapter'\nimport type {\n ImageGenerationResult,\n MediaPrompt,\n MediaPromptFor,\n StreamChunk,\n} from '../../types'\n\n// ===========================\n// Activity Kind\n// ===========================\n\n/** The adapter kind this activity handles */\nexport const kind = 'image' as const\n\n// ===========================\n// Type Extraction Helpers\n// ===========================\n\n/**\n * Extract model-specific provider options from an ImageAdapter via ~types.\n * If the model has specific options defined in ModelProviderOptions (and not just via index signature),\n * use those; otherwise fall back to base provider options.\n */\nexport type ImageProviderOptionsForModel<TAdapter, TModel extends string> =\n TAdapter extends ImageAdapter<any, infer BaseOptions, infer ModelOptions, any>\n ? string extends keyof ModelOptions\n ? // ModelOptions is Record<string, unknown> or has index signature - use BaseOptions\n BaseOptions\n : // ModelOptions has explicit keys - check if TModel is one of them\n TModel extends keyof ModelOptions\n ? ModelOptions[TModel]\n : BaseOptions\n : object\n\n/**\n * Extract model-specific size options from an ImageAdapter via ~types.\n * If the model has specific sizes defined, use those; otherwise fall back to string.\n */\nexport type ImageSizeForModel<TAdapter, TModel extends string> =\n TAdapter extends ImageAdapter<any, any, any, infer SizeByName>\n ? string extends keyof SizeByName\n ? // SizeByName has index signature - fall back to string\n string\n : // SizeByName has explicit keys - check if TModel is one of them\n TModel extends keyof SizeByName\n ? SizeByName[TModel]\n : string\n : string\n\n/**\n * Extract the prompt type a model accepts from an ImageAdapter via ~types.\n * Adapters declare a per-model input-modality map; models in the map get a\n * `prompt` narrowed to text + their supported part types (text-only models\n * accept `string | Array<TextPart>`), so unsupported media parts fail at\n * compile time. Adapters without a map fall back to the full MediaPrompt.\n */\nexport type ImagePromptForModel<TAdapter, TModel extends string> =\n TAdapter extends ImageAdapter<any, any, any, any, infer ModsByName>\n ? string extends keyof ModsByName\n ? // No explicit map - accept the full union\n MediaPrompt\n : TModel extends keyof ModsByName\n ? MediaPromptFor<ModsByName[TModel][number]>\n : MediaPrompt\n : MediaPrompt\n\n// ===========================\n// Activity Options Type\n// ===========================\n\n/**\n * Options for the image activity.\n * The model is extracted from the adapter's model property.\n *\n * @template TAdapter - The image adapter type\n * @template TStream - Whether to stream the output\n */\nexport type ImageActivityOptions<\n TAdapter extends ImageAdapter<string, any, any, any>,\n TStream extends boolean = false,\n> = {\n /** The image adapter to use (must be created with a model) */\n adapter: TAdapter & { kind: typeof kind }\n /**\n * Description of the desired image(s). Either a plain string, or — for\n * models that support image-conditioned generation — an ordered array of\n * content parts interleaving text with image inputs (image-to-image,\n * reference-guided, edit, multi-reference). Media parts may carry\n * `metadata.role` (`'reference' | 'mask' | 'control' | 'character'`) to\n * disambiguate intent. The accepted part types are narrowed per model via\n * the adapter's input-modality map.\n */\n prompt: ImagePromptForModel<TAdapter, TAdapter['model']>\n /** Number of images to generate (default: 1) */\n numberOfImages?: number\n /** Image size in WIDTHxHEIGHT format (e.g., \"1024x1024\") */\n size?: ImageSizeForModel<TAdapter, TAdapter['model']>\n /**\n * Whether to stream the image generation result.\n * When true, returns an AsyncIterable<StreamChunk> for streaming transport.\n * When false or not provided, returns a Promise<ImageGenerationResult>.\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} & ({} extends ImageProviderOptionsForModel<TAdapter, TAdapter['model']>\n ? {\n /** Provider-specific options for image generation */ modelOptions?: ImageProviderOptionsForModel<\n TAdapter,\n TAdapter['model']\n >\n }\n : {\n /** Provider-specific options for image generation */ modelOptions: ImageProviderOptionsForModel<\n TAdapter,\n TAdapter['model']\n >\n })\n\n// ===========================\n// Activity Result Type\n// ===========================\n\n/**\n * Result type for the image activity.\n * - If stream is true: AsyncIterable<StreamChunk>\n * - Otherwise: Promise<ImageGenerationResult>\n */\nexport type ImageActivityResult<TStream extends boolean = false> =\n TStream extends true\n ? AsyncIterable<StreamChunk>\n : Promise<ImageGenerationResult>\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 * Image activity - generates images from text prompts.\n *\n * Uses AI image generation models to create images based on natural language descriptions.\n *\n * @example Generate a single image\n * ```ts\n * import { generateImage } from '@tanstack/ai'\n * import { openaiImage } from '@tanstack/ai-openai'\n *\n * const result = await generateImage({\n * adapter: openaiImage('dall-e-3'),\n * prompt: 'A serene mountain landscape at sunset'\n * })\n *\n * console.log(result.images[0].url)\n * ```\n *\n * @example Generate multiple images\n * ```ts\n * const result = await generateImage({\n * adapter: openaiImage('dall-e-2'),\n * prompt: 'A cute robot mascot',\n * numberOfImages: 4,\n * size: '512x512'\n * })\n *\n * result.images.forEach((image, i) => {\n * console.log(`Image ${i + 1}: ${image.url}`)\n * })\n * ```\n *\n * @example With provider-specific options\n * ```ts\n * const result = await generateImage({\n * adapter: openaiImage('dall-e-3'),\n * prompt: 'A professional headshot photo',\n * size: '1024x1024',\n * modelOptions: {\n * quality: 'hd',\n * style: 'natural'\n * }\n * })\n * ```\n */\nexport function generateImage<\n TAdapter extends ImageAdapter<string, any, any, any>,\n TStream extends boolean = false,\n>(\n options: ImageActivityOptions<TAdapter, TStream>,\n): ImageActivityResult<TStream> {\n // Fail closed before middleware start and before `stream: true` emits\n // RUN_STARTED, so an unsupported file source never opens a run.\n assertPromptFileSourceSupport(options.adapter, options.prompt)\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) => runGenerateImage({ ...options, runId: resolved.runId }),\n options,\n ) as ImageActivityResult<TStream>\n }\n\n return runGenerateImage(options) as ImageActivityResult<TStream>\n}\n\n/**\n * Internal implementation of image generation (always non-streaming).\n * Contains all devtools event emission logic.\n */\nasync function runGenerateImage<\n TAdapter extends ImageAdapter<string, any, any, any>,\n>(\n options: ImageActivityOptions<TAdapter, boolean>,\n): Promise<ImageGenerationResult> {\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('image')\n const startTime = Date.now()\n const logger: InternalLogger = resolveDebugOption(options.debug)\n const abortControls = createActivityAbortControls({\n timeout,\n abortSignal: callerAbortSignal,\n })\n\n const mwCtx = createGenerationContext({\n requestId,\n activity: 'image',\n provider: adapter.name,\n model,\n modelOptions: rest.modelOptions,\n threadId,\n runId,\n artifactInputs: { prompt: rest.prompt },\n createId,\n })\n\n await runGenerationStart(middleware, mwCtx)\n\n // Devtools events carry the flattened prompt text plus media-part counts —\n // the wire payload stays `prompt: string` regardless of the prompt shape.\n const resolved = resolveMediaPrompt(rest.prompt)\n\n aiEventClient.emit('image:request:started', {\n requestId,\n provider: adapter.name,\n model,\n prompt: resolved.text,\n numberOfImages: rest.numberOfImages,\n size: rest.size,\n ...(resolved.images.length > 0 && {\n imageInputCount: resolved.images.length,\n }),\n ...(resolved.videos.length > 0 && {\n videoInputCount: resolved.videos.length,\n }),\n ...(resolved.audios.length > 0 && {\n audioInputCount: resolved.audios.length,\n }),\n modelOptions: rest.modelOptions,\n timestamp: startTime,\n })\n\n logger.request(`activity=generateImage provider=${adapter.name}`, {\n provider: adapter.name,\n model,\n })\n\n try {\n const rawResult = await raceWithAbort(\n adapter.generateImages({\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('image:request:completed', {\n requestId,\n provider: adapter.name,\n model,\n // GeneratedImage is a discriminated `{ url } | { b64Json }` union, but the\n // wire shape on the devtools event is a plain optional pair. Use\n // conditional spreads so the emitted record only sets the field actually\n // present — `exactOptionalPropertyTypes` rejects `field: undefined`\n // against `field?: string` targets.\n images: result.images.map((image) => ({\n url: image.url,\n b64Json: image.b64Json,\n })),\n duration,\n modelOptions: rest.modelOptions,\n timestamp: Date.now(),\n })\n\n if (result.usage) {\n aiEventClient.emit('image:usage', {\n requestId,\n model,\n usage: result.usage,\n modelOptions: rest.modelOptions,\n timestamp: Date.now(),\n })\n }\n\n logger.output(`activity=generateImage count=${result.images.length}`, {\n count: result.images.length,\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 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('generateImage activity failed', {\n error,\n source: 'generateImage',\n })\n throw error\n }\n}\n\n// ===========================\n// Options Factory\n// ===========================\n\n/**\n * Create typed options for the generateImage() function without executing.\n */\nexport function createImageOptions<\n TAdapter extends ImageAdapter<string, any, any, any>,\n TStream extends boolean = false,\n>(\n options: ImageActivityOptions<TAdapter, TStream>,\n): ImageActivityOptions<TAdapter, TStream> {\n return options\n}\n\n// Re-export adapter types\nexport type {\n ImageAdapter,\n ImageAdapterConfig,\n AnyImageAdapter,\n} from './adapter'\nexport { BaseImageAdapter } from './adapter'\n"],"mappings":";;;;;;;;;;;;;;;;AA2CA,IAAa,OAAO;AAqJpB,SAAS,SAAS,QAAwB;CACxC,OAAO,GAAG,OAAO,GAAG,KAAK,IAAI,EAAE,GAAG,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC;AAC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AAI;EACF,MAAM,YAAY,MAAM,cACtB,QAAQ,eAAe;GACrB,GAAG;GACH;GACA;GACA,GAAI,cAAc,SAAS,EAAE,aAAa,cAAc,OAAO,IAAI,CAAC;EACtE,CAAC,GACD,cAAc,MAChB;EACA,cAAc,MAAM;EACpB,MAAM,SAAS,MAAM,gCAAgC,OAAO,SAAS;EACrE,MAAM,WAAW,KAAK,IAAI,IAAI;EAE9B,cAAc,KAAK,2BAA2B;GAC5C;GACA,UAAU,QAAQ;GAClB;GAMA,QAAQ,OAAO,OAAO,KAAK,WAAW;IACpC,KAAK,MAAM;IACX,SAAS,MAAM;GACjB,EAAE;GACF;GACA,cAAc,KAAK;GACnB,WAAW,KAAK,IAAI;EACtB,CAAC;EAED,IAAI,OAAO,OACT,cAAc,KAAK,eAAe;GAChC;GACA;GACA,OAAO,OAAO;GACd,cAAc,KAAK;GACnB,WAAW,KAAK,IAAI;EACtB,CAAC;EAGH,OAAO,OAAO,gCAAgC,OAAO,OAAO,UAAU,EACpE,OAAO,OAAO,OAAO,OACvB,CAAC;EAED,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,cAAc,MAAM;EACpB,MAAM,WAAW,KAAK,IAAI,IAAI;EAC9B,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,iCAAiC;GAC7C;GACA,QAAQ;EACV,CAAC;EACD,MAAM;CACR;AACF;;;;AASA,SAAgB,mBAId,SACyC;CACzC,OAAO;AACT"}
|
|
@@ -64,6 +64,13 @@ export interface VideoAdapter<TModel extends string = string, TProviderOptions e
|
|
|
64
64
|
readonly kind: 'video';
|
|
65
65
|
/** Adapter name identifier */
|
|
66
66
|
readonly name: string;
|
|
67
|
+
/**
|
|
68
|
+
* Declares that this adapter can consume `{ type: 'file' }` content
|
|
69
|
+
* sources (provider Files API references). The activity dispatcher rejects
|
|
70
|
+
* file sources in preflight for adapters that don't declare this, so
|
|
71
|
+
* adapters written before the file arm existed fail closed.
|
|
72
|
+
*/
|
|
73
|
+
readonly supportsFileSources?: boolean;
|
|
67
74
|
/** The model this adapter is configured for */
|
|
68
75
|
readonly model: TModel;
|
|
69
76
|
/**
|
|
@@ -118,6 +125,7 @@ export type AnyVideoAdapter = VideoAdapter<any, any, any, any, any, any>;
|
|
|
118
125
|
export declare abstract class BaseVideoAdapter<TModel extends string = string, TProviderOptions extends object = Record<string, unknown>, TModelProviderOptionsByName extends Record<string, any> = Record<string, any>, TModelSizeByName extends Record<string, string | undefined> = Record<string, string>, TModelInputModalitiesByName extends ModelInputModalitiesByName = ModelInputModalitiesByName, TModelDurationByName extends Record<string, string | number | undefined> = Record<string, number>> implements VideoAdapter<TModel, TProviderOptions, TModelProviderOptionsByName, TModelSizeByName, TModelInputModalitiesByName, TModelDurationByName> {
|
|
119
126
|
readonly kind: "video";
|
|
120
127
|
abstract readonly name: string;
|
|
128
|
+
readonly supportsFileSources: boolean;
|
|
121
129
|
readonly model: TModel;
|
|
122
130
|
'~types': {
|
|
123
131
|
providerOptions: TProviderOptions;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adapter.js","names":[],"sources":["../../../../src/activities/generateVideo/adapter.ts"],"sourcesContent":["import type {\n ModelInputModalitiesByName,\n VideoGenerationOptions,\n VideoJobResult,\n VideoStatusResult,\n VideoUrlResult,\n} from '../../types'\n\n/**\n * Structured description of the durations a video model accepts.\n *\n * Tagged union so the same shape can express discrete enums (OpenAI Sora,\n * Veo), continuous ranges, mixed shapes, and models with no duration field.\n * Consumed by `VideoAdapter.availableDurations()`.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport type DurationOptions<T extends string | number | undefined> =\n | { kind: 'discrete'; values: ReadonlyArray<NonNullable<T>> }\n | { kind: 'range'; min: number; max: number; step?: number; unit: 'seconds' }\n | {\n kind: 'mixed'\n values: ReadonlyArray<NonNullable<T>>\n range?: { min: number; max: number; step?: number }\n }\n | { kind: 'none' }\n\n/**\n * Configuration for video adapter instances\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport interface VideoAdapterConfig {\n apiKey?: string\n baseUrl?: string\n timeout?: number\n maxRetries?: number\n headers?: Record<string, string>\n}\n\n/**\n * Video adapter interface with pre-resolved generics.\n *\n * An adapter is created by a provider function: `provider('model')` → `adapter`\n * All type resolution happens at the provider call site, not in this interface.\n *\n * @experimental Video generation is an experimental feature and may change.\n *\n * Generic parameters:\n * - TModel: The specific model name (e.g., 'sora-2')\n * - TProviderOptions: Provider-specific options (already resolved)\n * - TModelProviderOptionsByName: Map from model name to its specific provider options\n * - TModelSizeByName: Map from model name to its supported sizes\n * - TModelInputModalitiesByName: Map from model name to the non-text prompt\n * modalities it accepts (constrains the `prompt` part types at compile time)\n * - TModelDurationByName: Map from model name to its supported duration\n * union. Defaults to `Record<string, number>` so adapters that haven't\n * declared a map keep today's `duration?: number` typing.\n */\nexport interface VideoAdapter<\n TModel extends string = string,\n TProviderOptions extends object = Record<string, unknown>,\n TModelProviderOptionsByName extends Record<string, any> = Record<string, any>,\n TModelSizeByName extends Record<string, string | undefined> = Record<\n string,\n string\n >,\n TModelInputModalitiesByName extends ModelInputModalitiesByName =\n ModelInputModalitiesByName,\n TModelDurationByName extends Record<string, string | number | undefined> =\n Record<string, number>,\n> {\n /** Discriminator for adapter kind - used to determine API shape */\n readonly kind: 'video'\n /** Adapter name identifier */\n readonly name: string\n /** The model this adapter is configured for */\n readonly model: TModel\n\n /**\n * @internal Type-only properties for inference. Not assigned at runtime.\n */\n '~types': {\n providerOptions: TProviderOptions\n modelProviderOptionsByName: TModelProviderOptionsByName\n modelSizeByName: TModelSizeByName\n modelInputModalitiesByName: TModelInputModalitiesByName\n modelDurationByName: TModelDurationByName\n }\n\n /**\n * Create a new video generation job.\n * Returns a job ID that can be used to poll for status and retrieve the video.\n */\n createVideoJob: (\n options: VideoGenerationOptions<\n TProviderOptions,\n TModelSizeByName[TModel],\n TModelDurationByName[TModel]\n >,\n ) => Promise<VideoJobResult>\n\n /**\n * Get the current status of a video generation job.\n */\n getVideoStatus: (jobId: string) => Promise<VideoStatusResult>\n\n /**\n * Get the URL to download/view the generated video.\n * Should only be called after status is 'completed'.\n */\n getVideoUrl: (jobId: string) => Promise<VideoUrlResult>\n\n /**\n * Describe the durations this adapter's model accepts. Returns a tagged\n * union so consumers can render UI / coerce input without provider-specific\n * knowledge.\n */\n availableDurations: () => DurationOptions<TModelDurationByName[TModel]>\n\n /**\n * Coerce a raw seconds value to the closest valid duration for this model.\n * Returns `undefined` for models with no duration field.\n */\n snapDuration: (seconds: number) => TModelDurationByName[TModel] | undefined\n}\n\n/**\n * A VideoAdapter with any/unknown type parameters.\n * Useful as a constraint in generic functions and interfaces.\n */\nexport type AnyVideoAdapter = VideoAdapter<any, any, any, any, any, any>\n\n/**\n * Abstract base class for video generation adapters.\n * Extend this class to implement a video adapter for a specific provider.\n *\n * @experimental Video generation is an experimental feature and may change.\n *\n * Generic parameters match VideoAdapter - all pre-resolved by the provider function.\n */\nexport abstract class BaseVideoAdapter<\n TModel extends string = string,\n TProviderOptions extends object = Record<string, unknown>,\n TModelProviderOptionsByName extends Record<string, any> = Record<string, any>,\n TModelSizeByName extends Record<string, string | undefined> = Record<\n string,\n string\n >,\n TModelInputModalitiesByName extends ModelInputModalitiesByName =\n ModelInputModalitiesByName,\n TModelDurationByName extends Record<string, string | number | undefined> =\n Record<string, number>,\n> implements VideoAdapter<\n TModel,\n TProviderOptions,\n TModelProviderOptionsByName,\n TModelSizeByName,\n TModelInputModalitiesByName,\n TModelDurationByName\n> {\n readonly kind = 'video' as const\n abstract readonly name: string\n readonly model: TModel\n\n // Type-only property - never assigned at runtime\n declare '~types': {\n providerOptions: TProviderOptions\n modelProviderOptionsByName: TModelProviderOptionsByName\n modelSizeByName: TModelSizeByName\n modelInputModalitiesByName: TModelInputModalitiesByName\n modelDurationByName: TModelDurationByName\n }\n\n protected config: VideoAdapterConfig\n\n constructor(config: VideoAdapterConfig = {}, model: TModel) {\n this.config = config\n this.model = model\n }\n\n abstract createVideoJob(\n options: VideoGenerationOptions<\n TProviderOptions,\n TModelSizeByName[TModel],\n TModelDurationByName[TModel]\n >,\n ): Promise<VideoJobResult>\n\n abstract getVideoStatus(jobId: string): Promise<VideoStatusResult>\n\n abstract getVideoUrl(jobId: string): Promise<VideoUrlResult>\n\n /**\n * Default implementation returns `{ kind: 'none' }`. Adapters that have\n * declared their per-model duration map should override this.\n */\n availableDurations(): DurationOptions<TModelDurationByName[TModel]> {\n return { kind: 'none' }\n }\n\n /**\n * Default implementation returns `undefined`. Adapters that have declared\n * their per-model duration map should override.\n */\n snapDuration(_seconds: number): TModelDurationByName[TModel] | undefined {\n return undefined\n }\n\n protected generateId(): string {\n return `${this.name}-${Date.now()}-${Math.random().toString(36).substring(7)}`\n }\n}\n"],"mappings":";;;;;;;;;
|
|
1
|
+
{"version":3,"file":"adapter.js","names":[],"sources":["../../../../src/activities/generateVideo/adapter.ts"],"sourcesContent":["import type {\n ModelInputModalitiesByName,\n VideoGenerationOptions,\n VideoJobResult,\n VideoStatusResult,\n VideoUrlResult,\n} from '../../types'\n\n/**\n * Structured description of the durations a video model accepts.\n *\n * Tagged union so the same shape can express discrete enums (OpenAI Sora,\n * Veo), continuous ranges, mixed shapes, and models with no duration field.\n * Consumed by `VideoAdapter.availableDurations()`.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport type DurationOptions<T extends string | number | undefined> =\n | { kind: 'discrete'; values: ReadonlyArray<NonNullable<T>> }\n | { kind: 'range'; min: number; max: number; step?: number; unit: 'seconds' }\n | {\n kind: 'mixed'\n values: ReadonlyArray<NonNullable<T>>\n range?: { min: number; max: number; step?: number }\n }\n | { kind: 'none' }\n\n/**\n * Configuration for video adapter instances\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport interface VideoAdapterConfig {\n apiKey?: string\n baseUrl?: string\n timeout?: number\n maxRetries?: number\n headers?: Record<string, string>\n}\n\n/**\n * Video adapter interface with pre-resolved generics.\n *\n * An adapter is created by a provider function: `provider('model')` → `adapter`\n * All type resolution happens at the provider call site, not in this interface.\n *\n * @experimental Video generation is an experimental feature and may change.\n *\n * Generic parameters:\n * - TModel: The specific model name (e.g., 'sora-2')\n * - TProviderOptions: Provider-specific options (already resolved)\n * - TModelProviderOptionsByName: Map from model name to its specific provider options\n * - TModelSizeByName: Map from model name to its supported sizes\n * - TModelInputModalitiesByName: Map from model name to the non-text prompt\n * modalities it accepts (constrains the `prompt` part types at compile time)\n * - TModelDurationByName: Map from model name to its supported duration\n * union. Defaults to `Record<string, number>` so adapters that haven't\n * declared a map keep today's `duration?: number` typing.\n */\nexport interface VideoAdapter<\n TModel extends string = string,\n TProviderOptions extends object = Record<string, unknown>,\n TModelProviderOptionsByName extends Record<string, any> = Record<string, any>,\n TModelSizeByName extends Record<string, string | undefined> = Record<\n string,\n string\n >,\n TModelInputModalitiesByName extends ModelInputModalitiesByName =\n ModelInputModalitiesByName,\n TModelDurationByName extends Record<string, string | number | undefined> =\n Record<string, number>,\n> {\n /** Discriminator for adapter kind - used to determine API shape */\n readonly kind: 'video'\n /** Adapter name identifier */\n readonly name: string\n /**\n * Declares that this adapter can consume `{ type: 'file' }` content\n * sources (provider Files API references). The activity dispatcher rejects\n * file sources in preflight for adapters that don't declare this, so\n * adapters written before the file arm existed fail closed.\n */\n readonly supportsFileSources?: boolean\n /** The model this adapter is configured for */\n readonly model: TModel\n\n /**\n * @internal Type-only properties for inference. Not assigned at runtime.\n */\n '~types': {\n providerOptions: TProviderOptions\n modelProviderOptionsByName: TModelProviderOptionsByName\n modelSizeByName: TModelSizeByName\n modelInputModalitiesByName: TModelInputModalitiesByName\n modelDurationByName: TModelDurationByName\n }\n\n /**\n * Create a new video generation job.\n * Returns a job ID that can be used to poll for status and retrieve the video.\n */\n createVideoJob: (\n options: VideoGenerationOptions<\n TProviderOptions,\n TModelSizeByName[TModel],\n TModelDurationByName[TModel]\n >,\n ) => Promise<VideoJobResult>\n\n /**\n * Get the current status of a video generation job.\n */\n getVideoStatus: (jobId: string) => Promise<VideoStatusResult>\n\n /**\n * Get the URL to download/view the generated video.\n * Should only be called after status is 'completed'.\n */\n getVideoUrl: (jobId: string) => Promise<VideoUrlResult>\n\n /**\n * Describe the durations this adapter's model accepts. Returns a tagged\n * union so consumers can render UI / coerce input without provider-specific\n * knowledge.\n */\n availableDurations: () => DurationOptions<TModelDurationByName[TModel]>\n\n /**\n * Coerce a raw seconds value to the closest valid duration for this model.\n * Returns `undefined` for models with no duration field.\n */\n snapDuration: (seconds: number) => TModelDurationByName[TModel] | undefined\n}\n\n/**\n * A VideoAdapter with any/unknown type parameters.\n * Useful as a constraint in generic functions and interfaces.\n */\nexport type AnyVideoAdapter = VideoAdapter<any, any, any, any, any, any>\n\n/**\n * Abstract base class for video generation adapters.\n * Extend this class to implement a video adapter for a specific provider.\n *\n * @experimental Video generation is an experimental feature and may change.\n *\n * Generic parameters match VideoAdapter - all pre-resolved by the provider function.\n */\nexport abstract class BaseVideoAdapter<\n TModel extends string = string,\n TProviderOptions extends object = Record<string, unknown>,\n TModelProviderOptionsByName extends Record<string, any> = Record<string, any>,\n TModelSizeByName extends Record<string, string | undefined> = Record<\n string,\n string\n >,\n TModelInputModalitiesByName extends ModelInputModalitiesByName =\n ModelInputModalitiesByName,\n TModelDurationByName extends Record<string, string | number | undefined> =\n Record<string, number>,\n> implements VideoAdapter<\n TModel,\n TProviderOptions,\n TModelProviderOptionsByName,\n TModelSizeByName,\n TModelInputModalitiesByName,\n TModelDurationByName\n> {\n readonly kind = 'video' as const\n abstract readonly name: string\n readonly supportsFileSources: boolean = false\n readonly model: TModel\n\n // Type-only property - never assigned at runtime\n declare '~types': {\n providerOptions: TProviderOptions\n modelProviderOptionsByName: TModelProviderOptionsByName\n modelSizeByName: TModelSizeByName\n modelInputModalitiesByName: TModelInputModalitiesByName\n modelDurationByName: TModelDurationByName\n }\n\n protected config: VideoAdapterConfig\n\n constructor(config: VideoAdapterConfig = {}, model: TModel) {\n this.config = config\n this.model = model\n }\n\n abstract createVideoJob(\n options: VideoGenerationOptions<\n TProviderOptions,\n TModelSizeByName[TModel],\n TModelDurationByName[TModel]\n >,\n ): Promise<VideoJobResult>\n\n abstract getVideoStatus(jobId: string): Promise<VideoStatusResult>\n\n abstract getVideoUrl(jobId: string): Promise<VideoUrlResult>\n\n /**\n * Default implementation returns `{ kind: 'none' }`. Adapters that have\n * declared their per-model duration map should override this.\n */\n availableDurations(): DurationOptions<TModelDurationByName[TModel]> {\n return { kind: 'none' }\n }\n\n /**\n * Default implementation returns `undefined`. Adapters that have declared\n * their per-model duration map should override.\n */\n snapDuration(_seconds: number): TModelDurationByName[TModel] | undefined {\n return undefined\n }\n\n protected generateId(): string {\n return `${this.name}-${Date.now()}-${Math.random().toString(36).substring(7)}`\n }\n}\n"],"mappings":";;;;;;;;;AAoJA,IAAsB,mBAAtB,MAmBE;CACA,OAAgB;CAEhB,sBAAwC;CACxC;CAWA;CAEA,YAAY,SAA6B,CAAC,GAAG,OAAe;EAC1D,KAAK,SAAS;EACd,KAAK,QAAQ;CACf;;;;;CAkBA,qBAAoE;EAClE,OAAO,EAAE,MAAM,OAAO;CACxB;;;;;CAMA,aAAa,UAA4D,CAEzE;CAEA,aAA+B;EAC7B,OAAO,GAAG,KAAK,KAAK,GAAG,KAAK,IAAI,EAAE,GAAG,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,UAAU,CAAC;CAC7E;AACF"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { toRunErrorPayload } from "../error-payload.js";
|
|
2
2
|
import { normalizeStreamChunk } from "../../utilities/normalize-stream-chunk.js";
|
|
3
3
|
import { resolveDebugOption } from "../../logger/resolve.js";
|
|
4
|
+
import { assertPromptFileSourceSupport } from "../../utilities/content-source.js";
|
|
4
5
|
import { applyGenerationResultTransforms, createGenerationContext, runGenerationAbort, runGenerationError, runGenerationFinish, runGenerationStart, runGenerationUsage } from "../middleware/run.js";
|
|
5
6
|
import { abortReasonMessage, createActivityAbortControls, isActivityAbortError, raceWithAbort, toAbortError } from "../../utilities/activity-abort.js";
|
|
6
7
|
import "./adapter.js";
|
|
@@ -108,6 +109,7 @@ function videoRunIdForJob(provider, jobId) {
|
|
|
108
109
|
*/
|
|
109
110
|
async function runCreateVideoJob(options) {
|
|
110
111
|
const { adapter, prompt, size, duration, modelOptions, middleware, timeout, abortSignal: callerAbortSignal } = options;
|
|
112
|
+
assertPromptFileSourceSupport(adapter, prompt);
|
|
111
113
|
const model = adapter.model;
|
|
112
114
|
const requestId = createId("video");
|
|
113
115
|
const startTime = Date.now();
|
|
@@ -193,6 +195,7 @@ function sleep(ms, signal) {
|
|
|
193
195
|
*/
|
|
194
196
|
async function* runStreamingVideoGeneration(options) {
|
|
195
197
|
const { adapter, prompt, size, duration, modelOptions, middleware, timeout, abortSignal: callerAbortSignal } = options;
|
|
198
|
+
assertPromptFileSourceSupport(adapter, prompt);
|
|
196
199
|
const model = adapter.model;
|
|
197
200
|
const runId = options.runId ?? createId("run");
|
|
198
201
|
const requestId = createId("video");
|
|
@@ -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. Adapters use a jobs/polling\n * architecture: create a job, poll for status, then fetch a download URL.\n * For a live, prompt-steerable stream, use generateLiveVideo().\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 { normalizeStreamChunk } from '../../utilities/normalize-stream-chunk'\nimport type { AdapterYieldChunk } from '../../utilities/adapter-yield-chunk'\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 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* normalizeStreamChunk({\n type: 'RUN_FINISHED',\n runId,\n threadId: wireThreadId,\n finishReason: 'stop',\n timestamp: Date.now(),\n } as AdapterYieldChunk)\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* normalizeStreamChunk({\n type: 'RUN_ERROR',\n runId,\n threadId: wireThreadId,\n message: payload.message,\n ...(payload.code !== undefined ? { code: payload.code } : {}),\n timestamp: Date.now(),\n } as AdapterYieldChunk)\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":";;;;;;;;;;;;;;;;;;;AAuDA,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;;;;;;;;;;;;;;;;;;AAmBA,eAAe,kBAEb,SAAyE;CACzE,MAAM,EACJ,SACA,QACA,MACA,UACA,cACA,YACA,SACA,aAAa,sBACX;CACJ,MAAM,QAAQ,QAAQ;CACtB,MAAM,YAAY,SAAS,OAAO;CAClC,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;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,cAChB,QAAQ,eAAe;GACrB;GACA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ACA,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. Adapters use a jobs/polling\n * architecture: create a job, poll for status, then fetch a download URL.\n * For a live, prompt-steerable stream, use generateLiveVideo().\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 { assertPromptFileSourceSupport } from '../../utilities/content-source'\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 { normalizeStreamChunk } from '../../utilities/normalize-stream-chunk'\nimport type { AdapterYieldChunk } from '../../utilities/adapter-yield-chunk'\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 // Fail closed on `{ type: 'file' }` sources for adapters that haven't\n // declared support (see assertPromptFileSourceSupport).\n assertPromptFileSourceSupport(adapter, prompt)\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 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 // Fail closed on `{ type: 'file' }` sources for adapters that haven't\n // declared support (see assertPromptFileSourceSupport).\n assertPromptFileSourceSupport(adapter, prompt)\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* normalizeStreamChunk({\n type: 'RUN_FINISHED',\n runId,\n threadId: wireThreadId,\n finishReason: 'stop',\n timestamp: Date.now(),\n } as AdapterYieldChunk)\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* normalizeStreamChunk({\n type: 'RUN_ERROR',\n runId,\n threadId: wireThreadId,\n message: payload.message,\n ...(payload.code !== undefined ? { code: payload.code } : {}),\n timestamp: Date.now(),\n } as AdapterYieldChunk)\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":";;;;;;;;;;;;;;;;;;;;AAwDA,IAAa,OAAO;AA2EpB,SAAS,SAAS,QAAwB;CACxC,OAAO,GAAG,OAAO,GAAG,KAAK,IAAI,EAAE,GAAG,KAAK,OAAO,CAAC,CAAC,SAAS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AU,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"}
|
|
@@ -37,10 +37,12 @@ export interface WorldAdapter<TModel extends string = string, TProviderOptions e
|
|
|
37
37
|
providerOptions: TProviderOptions;
|
|
38
38
|
};
|
|
39
39
|
/**
|
|
40
|
-
*
|
|
40
|
+
* Create a world from a prompt.
|
|
41
41
|
*
|
|
42
|
-
*
|
|
42
|
+
* Live session adapters mint a short-lived token and return it with the
|
|
43
43
|
* prompt so a browser can connect, set the prompt, and start streaming.
|
|
44
|
+
* Job adapters start generation and return a world URL (or an operation
|
|
45
|
+
* id while the job is still running).
|
|
44
46
|
*/
|
|
45
47
|
createWorld: (options: WorldGenerationOptions<TProviderOptions>) => Promise<WorldGenerationResult>;
|
|
46
48
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adapter.js","names":[],"sources":["../../../../src/activities/generateWorld/adapter.ts"],"sourcesContent":["import type { WorldGenerationOptions, WorldGenerationResult } from '../../types'\n\n/**\n * Configuration for world generation adapter instances.\n *\n * @experimental World generation is an experimental feature and may change.\n */\nexport interface WorldAdapterConfig {\n apiKey?: string\n baseUrl?: string\n timeout?: number\n maxRetries?: number\n headers?: Record<string, string>\n}\n\n/**\n * World adapter interface with pre-resolved generics.\n *\n * An adapter is created by a provider function: `provider('model')` → `adapter`.\n * All type resolution happens at the provider call site, not in this interface.\n *\n * Generic parameters:\n * - TModel: The specific model name (e.g. 'visko-orbis-stable')\n * - TProviderOptions: Provider-specific options (already resolved)\n *\n * @experimental World generation is an experimental feature and may change.\n */\nexport interface WorldAdapter<\n TModel extends string = string,\n TProviderOptions extends object = Record<string, unknown>,\n> {\n /** Discriminator for adapter kind - used to determine API shape */\n readonly kind: 'world'\n /** Adapter name identifier */\n readonly name: string\n /** The model this adapter is configured for */\n readonly model: TModel\n\n /**\n * @internal Type-only properties for inference. Not assigned at runtime.\n */\n '~types': {\n providerOptions: TProviderOptions\n }\n\n /**\n *
|
|
1
|
+
{"version":3,"file":"adapter.js","names":[],"sources":["../../../../src/activities/generateWorld/adapter.ts"],"sourcesContent":["import type { WorldGenerationOptions, WorldGenerationResult } from '../../types'\n\n/**\n * Configuration for world generation adapter instances.\n *\n * @experimental World generation is an experimental feature and may change.\n */\nexport interface WorldAdapterConfig {\n apiKey?: string\n baseUrl?: string\n timeout?: number\n maxRetries?: number\n headers?: Record<string, string>\n}\n\n/**\n * World adapter interface with pre-resolved generics.\n *\n * An adapter is created by a provider function: `provider('model')` → `adapter`.\n * All type resolution happens at the provider call site, not in this interface.\n *\n * Generic parameters:\n * - TModel: The specific model name (e.g. 'visko-orbis-stable')\n * - TProviderOptions: Provider-specific options (already resolved)\n *\n * @experimental World generation is an experimental feature and may change.\n */\nexport interface WorldAdapter<\n TModel extends string = string,\n TProviderOptions extends object = Record<string, unknown>,\n> {\n /** Discriminator for adapter kind - used to determine API shape */\n readonly kind: 'world'\n /** Adapter name identifier */\n readonly name: string\n /** The model this adapter is configured for */\n readonly model: TModel\n\n /**\n * @internal Type-only properties for inference. Not assigned at runtime.\n */\n '~types': {\n providerOptions: TProviderOptions\n }\n\n /**\n * Create a world from a prompt.\n *\n * Live session adapters mint a short-lived token and return it with the\n * prompt so a browser can connect, set the prompt, and start streaming.\n * Job adapters start generation and return a world URL (or an operation\n * id while the job is still running).\n */\n createWorld: (\n options: WorldGenerationOptions<TProviderOptions>,\n ) => Promise<WorldGenerationResult>\n}\n\n/**\n * A WorldAdapter with any/unknown type parameters.\n * Useful as a constraint in generic functions and interfaces.\n */\nexport type AnyWorldAdapter = WorldAdapter<any, any>\n\n/**\n * Abstract base class for world generation adapters.\n * Extend this class to implement a world adapter for a specific provider.\n *\n * @experimental World generation is an experimental feature and may change.\n */\nexport abstract class BaseWorldAdapter<\n TModel extends string = string,\n TProviderOptions extends object = Record<string, unknown>,\n> implements WorldAdapter<TModel, TProviderOptions> {\n readonly kind = 'world' as const\n abstract readonly name: string\n readonly model: TModel\n\n // Type-only property - never assigned at runtime\n declare '~types': {\n providerOptions: TProviderOptions\n }\n\n protected config: WorldAdapterConfig\n\n constructor(model: TModel, config: WorldAdapterConfig = {}) {\n this.config = config\n this.model = model\n }\n\n abstract createWorld(\n options: WorldGenerationOptions<TProviderOptions>,\n ): Promise<WorldGenerationResult>\n\n protected generateId(): string {\n return `${this.name}-${Date.now()}-${Math.random().toString(36).substring(7)}`\n }\n}\n"],"mappings":";;;;;;;AAsEA,IAAsB,mBAAtB,MAGoD;CAClD,OAAgB;CAEhB;CAOA;CAEA,YAAY,OAAe,SAA6B,CAAC,GAAG;EAC1D,KAAK,SAAS;EACd,KAAK,QAAQ;CACf;CAMA,aAA+B;EAC7B,OAAO,GAAG,KAAK,KAAK,GAAG,KAAK,IAAI,EAAE,GAAG,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,UAAU,CAAC;CAC7E;AACF"}
|
|
@@ -31,7 +31,7 @@ export interface WorldActivityOptions<TAdapter extends WorldAdapter<string, Worl
|
|
|
31
31
|
/** Provider-specific options for world generation */
|
|
32
32
|
modelOptions?: WorldProviderOptions<TAdapter>;
|
|
33
33
|
/**
|
|
34
|
-
* Whether to wrap the
|
|
34
|
+
* Whether to wrap the result as StreamChunks for SSE transport.
|
|
35
35
|
* This is not the live video. When false or omitted, returns
|
|
36
36
|
* Promise<WorldGenerationResult>.
|
|
37
37
|
*
|
|
@@ -55,7 +55,7 @@ export interface WorldActivityOptions<TAdapter extends WorldAdapter<string, Worl
|
|
|
55
55
|
/** Stable run id for correlating this run when persisted. */
|
|
56
56
|
runId?: string;
|
|
57
57
|
/**
|
|
58
|
-
* Maximum
|
|
58
|
+
* Maximum wait for the mint or job poll, in milliseconds.
|
|
59
59
|
* No SDK-wide default. Composed with {@link abortSignal}; the first abort wins.
|
|
60
60
|
*/
|
|
61
61
|
timeout?: number;
|
|
@@ -73,7 +73,8 @@ export interface WorldActivityOptions<TAdapter extends WorldAdapter<string, Worl
|
|
|
73
73
|
*/
|
|
74
74
|
export type WorldActivityResult<TStream extends boolean = false> = TStream extends true ? AsyncIterable<StreamChunk> : Promise<WorldGenerationResult>;
|
|
75
75
|
/**
|
|
76
|
-
* World generation activity
|
|
76
|
+
* World generation activity. Live adapters mint a session token. Job
|
|
77
|
+
* adapters return a viewer URL or an in-progress operation id.
|
|
77
78
|
*
|
|
78
79
|
* @example Mint a session token on the server
|
|
79
80
|
* ```ts
|
|
@@ -8,9 +8,9 @@ import { aiEventClient } from "@tanstack/ai-event-client";
|
|
|
8
8
|
/**
|
|
9
9
|
* World Activity (Experimental)
|
|
10
10
|
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
11
|
+
* Live adapters mint a session token for a prompt-steerable world. Job
|
|
12
|
+
* adapters start generation and return a viewer URL, or an operation id
|
|
13
|
+
* while the job is still running.
|
|
14
14
|
*
|
|
15
15
|
* @experimental World generation is an experimental feature and may change.
|
|
16
16
|
*/
|
|
@@ -20,7 +20,8 @@ function createId(prefix) {
|
|
|
20
20
|
return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
|
|
21
21
|
}
|
|
22
22
|
/**
|
|
23
|
-
* World generation activity
|
|
23
|
+
* World generation activity. Live adapters mint a session token. Job
|
|
24
|
+
* adapters return a viewer URL or an in-progress operation id.
|
|
24
25
|
*
|
|
25
26
|
* @example Mint a session token on the server
|
|
26
27
|
* ```ts
|