@tanstack/ai 0.53.0 → 0.55.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 +14 -13
- package/dist/esm/activities/chat/index.js +22 -4
- package/dist/esm/activities/chat/index.js.map +1 -1
- package/dist/esm/activities/chat/messages.d.ts +21 -1
- package/dist/esm/activities/chat/messages.js +50 -1
- package/dist/esm/activities/chat/messages.js.map +1 -1
- package/dist/esm/activities/chat/stream/processor.d.ts +17 -0
- package/dist/esm/activities/chat/stream/processor.js +27 -0
- package/dist/esm/activities/chat/stream/processor.js.map +1 -1
- package/dist/esm/activities/generateLiveVideo/adapter.d.ts +69 -0
- package/dist/esm/activities/generateLiveVideo/adapter.js +23 -0
- package/dist/esm/activities/generateLiveVideo/adapter.js.map +1 -0
- package/dist/esm/activities/generateLiveVideo/index.d.ts +99 -0
- package/dist/esm/activities/generateLiveVideo/index.js +162 -0
- package/dist/esm/activities/generateLiveVideo/index.js.map +1 -0
- package/dist/esm/activities/generateVideo/index.js +3 -1
- package/dist/esm/activities/generateVideo/index.js.map +1 -1
- package/dist/esm/activities/generateWorld/adapter.d.ts +69 -0
- package/dist/esm/activities/generateWorld/adapter.js +23 -0
- package/dist/esm/activities/generateWorld/adapter.js.map +1 -0
- package/dist/esm/activities/generateWorld/index.d.ts +99 -0
- package/dist/esm/activities/generateWorld/index.js +162 -0
- package/dist/esm/activities/generateWorld/index.js.map +1 -0
- package/dist/esm/activities/index.d.ts +8 -2
- package/dist/esm/activities/index.js +11 -7
- package/dist/esm/activities/middleware/types.d.ts +1 -1
- package/dist/esm/client.d.ts +4 -2
- package/dist/esm/client.js +3 -1
- package/dist/esm/client.js.map +1 -1
- package/dist/esm/index.d.ts +4 -2
- package/dist/esm/index.js +3 -1
- package/dist/esm/middlewares/otel.js +3 -1
- package/dist/esm/middlewares/otel.js.map +1 -1
- package/dist/esm/types.d.ts +112 -0
- package/package.json +3 -3
- package/skills/ai-core/adapter-configuration/SKILL.md +91 -43
- package/skills/ai-core/adapter-configuration/references/anthropic-adapter.md +39 -21
- package/skills/ai-core/adapter-configuration/references/byteplus-adapter.md +5 -0
- package/skills/ai-core/adapter-configuration/references/gemini-adapter.md +14 -6
- package/skills/ai-core/adapter-configuration/references/grok-adapter.md +33 -25
- package/skills/ai-core/adapter-configuration/references/groq-adapter.md +7 -2
- package/skills/ai-core/adapter-configuration/references/ollama-adapter.md +25 -12
- package/skills/ai-core/adapter-configuration/references/openai-adapter.md +19 -9
- package/skills/ai-core/adapter-configuration/references/openrouter-adapter.md +34 -21
- package/skills/ai-core/ag-ui-protocol/SKILL.md +16 -10
- package/skills/ai-core/chat-experience/SKILL.md +228 -108
- package/skills/ai-core/client-persistence/SKILL.md +21 -9
- package/skills/ai-core/custom-backend-integration/SKILL.md +86 -52
- package/skills/ai-core/debug-logging/SKILL.md +100 -18
- package/skills/ai-core/locks/SKILL.md +35 -7
- package/skills/ai-core/media-generation/SKILL.md +136 -61
- package/skills/ai-core/middleware/SKILL.md +174 -69
- package/skills/ai-core/structured-outputs/SKILL.md +98 -49
- package/skills/ai-core/tool-calling/SKILL.md +245 -158
- package/src/activities/chat/index.ts +29 -7
- package/src/activities/chat/messages.ts +60 -0
- package/src/activities/chat/stream/processor.ts +31 -0
- package/src/activities/generateLiveVideo/adapter.ts +99 -0
- package/src/activities/generateLiveVideo/index.ts +339 -0
- package/src/activities/generateVideo/index.ts +3 -4
- package/src/activities/generateWorld/adapter.ts +96 -0
- package/src/activities/generateWorld/index.ts +339 -0
- package/src/activities/index.ts +44 -0
- package/src/activities/middleware/types.ts +2 -0
- package/src/client.ts +8 -0
- package/src/index.ts +8 -0
- package/src/middlewares/otel.ts +2 -0
- package/src/types.ts +128 -0
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { LiveVideoGenerationOptions, LiveVideoGenerationResult } from '../../types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Configuration for live generation adapter instances.
|
|
4
|
+
*
|
|
5
|
+
* @experimental Live generation is an experimental feature and may change.
|
|
6
|
+
*/
|
|
7
|
+
export interface LiveVideoAdapterConfig {
|
|
8
|
+
apiKey?: string;
|
|
9
|
+
baseUrl?: string;
|
|
10
|
+
timeout?: number;
|
|
11
|
+
maxRetries?: number;
|
|
12
|
+
headers?: Record<string, string>;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Live adapter interface with pre-resolved generics.
|
|
16
|
+
*
|
|
17
|
+
* An adapter is created by a provider function: `provider('model')` → `adapter`.
|
|
18
|
+
* All type resolution happens at the provider call site, not in this interface.
|
|
19
|
+
*
|
|
20
|
+
* Generic parameters:
|
|
21
|
+
* - TModel: The specific model name (e.g. 'helios')
|
|
22
|
+
* - TProviderOptions: Provider-specific options (already resolved)
|
|
23
|
+
*
|
|
24
|
+
* @experimental Live generation is an experimental feature and may change.
|
|
25
|
+
*/
|
|
26
|
+
export interface LiveVideoAdapter<TModel extends string = string, TProviderOptions extends object = Record<string, unknown>> {
|
|
27
|
+
/** Discriminator for adapter kind - used to determine API shape */
|
|
28
|
+
readonly kind: 'liveVideo';
|
|
29
|
+
/** Adapter name identifier */
|
|
30
|
+
readonly name: string;
|
|
31
|
+
/** The model this adapter is configured for */
|
|
32
|
+
readonly model: TModel;
|
|
33
|
+
/**
|
|
34
|
+
* @internal Type-only properties for inference. Not assigned at runtime.
|
|
35
|
+
*/
|
|
36
|
+
'~types': {
|
|
37
|
+
providerOptions: TProviderOptions;
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* Open a live video session from a prompt.
|
|
41
|
+
*
|
|
42
|
+
* Server adapters typically mint a short-lived token and return it with the
|
|
43
|
+
* prompt so a browser can connect, set the prompt, and start streaming.
|
|
44
|
+
*/
|
|
45
|
+
createLiveVideo: (options: LiveVideoGenerationOptions<TProviderOptions>) => Promise<LiveVideoGenerationResult>;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* A LiveVideoAdapter with any/unknown type parameters.
|
|
49
|
+
* Useful as a constraint in generic functions and interfaces.
|
|
50
|
+
*/
|
|
51
|
+
export type AnyLiveVideoAdapter = LiveVideoAdapter<any, any>;
|
|
52
|
+
/**
|
|
53
|
+
* Abstract base class for live generation adapters.
|
|
54
|
+
* Extend this class to implement a live adapter for a specific provider.
|
|
55
|
+
*
|
|
56
|
+
* @experimental Live generation is an experimental feature and may change.
|
|
57
|
+
*/
|
|
58
|
+
export declare abstract class BaseLiveVideoAdapter<TModel extends string = string, TProviderOptions extends object = Record<string, unknown>> implements LiveVideoAdapter<TModel, TProviderOptions> {
|
|
59
|
+
readonly kind: "liveVideo";
|
|
60
|
+
abstract readonly name: string;
|
|
61
|
+
readonly model: TModel;
|
|
62
|
+
'~types': {
|
|
63
|
+
providerOptions: TProviderOptions;
|
|
64
|
+
};
|
|
65
|
+
protected config: LiveVideoAdapterConfig;
|
|
66
|
+
constructor(model: TModel, config?: LiveVideoAdapterConfig);
|
|
67
|
+
abstract createLiveVideo(options: LiveVideoGenerationOptions<TProviderOptions>): Promise<LiveVideoGenerationResult>;
|
|
68
|
+
protected generateId(): string;
|
|
69
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
//#region src/activities/generateLiveVideo/adapter.ts
|
|
2
|
+
/**
|
|
3
|
+
* Abstract base class for live generation adapters.
|
|
4
|
+
* Extend this class to implement a live adapter for a specific provider.
|
|
5
|
+
*
|
|
6
|
+
* @experimental Live generation is an experimental feature and may change.
|
|
7
|
+
*/
|
|
8
|
+
var BaseLiveVideoAdapter = class {
|
|
9
|
+
kind = "liveVideo";
|
|
10
|
+
model;
|
|
11
|
+
config;
|
|
12
|
+
constructor(model, config = {}) {
|
|
13
|
+
this.config = config;
|
|
14
|
+
this.model = model;
|
|
15
|
+
}
|
|
16
|
+
generateId() {
|
|
17
|
+
return `${this.name}-${Date.now()}-${Math.random().toString(36).substring(7)}`;
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
//#endregion
|
|
21
|
+
export { BaseLiveVideoAdapter };
|
|
22
|
+
|
|
23
|
+
//# sourceMappingURL=adapter.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"adapter.js","names":[],"sources":["../../../../src/activities/generateLiveVideo/adapter.ts"],"sourcesContent":["import type {\n LiveVideoGenerationOptions,\n LiveVideoGenerationResult,\n} from '../../types'\n\n/**\n * Configuration for live generation adapter instances.\n *\n * @experimental Live generation is an experimental feature and may change.\n */\nexport interface LiveVideoAdapterConfig {\n apiKey?: string\n baseUrl?: string\n timeout?: number\n maxRetries?: number\n headers?: Record<string, string>\n}\n\n/**\n * Live 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. 'helios')\n * - TProviderOptions: Provider-specific options (already resolved)\n *\n * @experimental Live generation is an experimental feature and may change.\n */\nexport interface LiveVideoAdapter<\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: 'liveVideo'\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 * Open a live video session from a prompt.\n *\n * Server adapters typically mint a short-lived token and return it with the\n * prompt so a browser can connect, set the prompt, and start streaming.\n */\n createLiveVideo: (\n options: LiveVideoGenerationOptions<TProviderOptions>,\n ) => Promise<LiveVideoGenerationResult>\n}\n\n/**\n * A LiveVideoAdapter with any/unknown type parameters.\n * Useful as a constraint in generic functions and interfaces.\n */\nexport type AnyLiveVideoAdapter = LiveVideoAdapter<any, any>\n\n/**\n * Abstract base class for live generation adapters.\n * Extend this class to implement a live adapter for a specific provider.\n *\n * @experimental Live generation is an experimental feature and may change.\n */\nexport abstract class BaseLiveVideoAdapter<\n TModel extends string = string,\n TProviderOptions extends object = Record<string, unknown>,\n> implements LiveVideoAdapter<TModel, TProviderOptions> {\n readonly kind = 'liveVideo' 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: LiveVideoAdapterConfig\n\n constructor(model: TModel, config: LiveVideoAdapterConfig = {}) {\n this.config = config\n this.model = model\n }\n\n abstract createLiveVideo(\n options: LiveVideoGenerationOptions<TProviderOptions>,\n ): Promise<LiveVideoGenerationResult>\n\n protected generateId(): string {\n return `${this.name}-${Date.now()}-${Math.random().toString(36).substring(7)}`\n }\n}\n"],"mappings":";;;;;;;AAuEA,IAAsB,uBAAtB,MAGwD;CACtD,OAAgB;CAEhB;CAOA;CAEA,YAAY,OAAe,SAAiC,CAAC,GAAG;EAC9D,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"}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { DebugOption } from '../../logger/types.js';
|
|
2
|
+
import { GenerationMiddleware } from '../middleware/types.js';
|
|
3
|
+
import { LiveVideoAdapter } from './adapter.js';
|
|
4
|
+
import { StreamChunk, LiveVideoGenerationResult } from '../../types.js';
|
|
5
|
+
/** The adapter kind this activity handles */
|
|
6
|
+
export declare const kind: "liveVideo";
|
|
7
|
+
/**
|
|
8
|
+
* Extract provider options from a LiveVideoAdapter via ~types.
|
|
9
|
+
*/
|
|
10
|
+
export type LiveVideoProviderOptions<TAdapter> = TAdapter extends {
|
|
11
|
+
'~types': {
|
|
12
|
+
providerOptions: infer P extends object;
|
|
13
|
+
};
|
|
14
|
+
} ? P : object;
|
|
15
|
+
/**
|
|
16
|
+
* Options for the live generation activity.
|
|
17
|
+
* The model is extracted from the adapter's model property.
|
|
18
|
+
*
|
|
19
|
+
* @template TAdapter - The live adapter type
|
|
20
|
+
* @template TStream - Whether to stream the output
|
|
21
|
+
*
|
|
22
|
+
* @experimental Live generation is an experimental feature and may change.
|
|
23
|
+
*/
|
|
24
|
+
export interface LiveVideoActivityOptions<TAdapter extends LiveVideoAdapter<string, LiveVideoProviderOptions<TAdapter>>, TStream extends boolean = false> {
|
|
25
|
+
/** The live adapter to use (must be created with a model) */
|
|
26
|
+
adapter: TAdapter & {
|
|
27
|
+
kind: typeof kind;
|
|
28
|
+
};
|
|
29
|
+
/** Natural-language description of the shot or scene */
|
|
30
|
+
prompt: string;
|
|
31
|
+
/** Provider-specific options for live generation */
|
|
32
|
+
modelOptions?: LiveVideoProviderOptions<TAdapter>;
|
|
33
|
+
/**
|
|
34
|
+
* Whether to wrap the token result as StreamChunks for SSE transport.
|
|
35
|
+
* This is not the live video. When false or omitted, returns
|
|
36
|
+
* Promise<LiveVideoGenerationResult>.
|
|
37
|
+
*
|
|
38
|
+
* @default false
|
|
39
|
+
*/
|
|
40
|
+
stream?: TStream;
|
|
41
|
+
/**
|
|
42
|
+
* Enable debug logging. Pass `true` to enable all categories, `false` to
|
|
43
|
+
* silence everything including errors, or a `DebugConfig` object for granular
|
|
44
|
+
* control and/or a custom `Logger`.
|
|
45
|
+
*/
|
|
46
|
+
debug?: DebugOption;
|
|
47
|
+
/**
|
|
48
|
+
* Observe-only middleware notified on start, usage, success, and error. Pass
|
|
49
|
+
* `otelMiddleware()` to emit OpenTelemetry spans, or implement the
|
|
50
|
+
* `GenerationMiddleware` contract for a custom backend.
|
|
51
|
+
*/
|
|
52
|
+
middleware?: Array<GenerationMiddleware>;
|
|
53
|
+
/** Stable conversation/thread id for correlating this run when persisted. */
|
|
54
|
+
threadId?: string;
|
|
55
|
+
/** Stable run id for correlating this run when persisted. */
|
|
56
|
+
runId?: string;
|
|
57
|
+
/**
|
|
58
|
+
* Maximum duration of the token mint in milliseconds.
|
|
59
|
+
* No SDK-wide default. Composed with {@link abortSignal}; the first abort wins.
|
|
60
|
+
*/
|
|
61
|
+
timeout?: number;
|
|
62
|
+
/**
|
|
63
|
+
* Caller cancellation signal (request disconnects, job/runtime cancellation).
|
|
64
|
+
* Composed with {@link timeout} into an effective signal forwarded to the
|
|
65
|
+
* adapter. Request-specific — not stored on global provider client config.
|
|
66
|
+
*/
|
|
67
|
+
abortSignal?: AbortSignal;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Result type for the live generation activity.
|
|
71
|
+
* - If stream is true: AsyncIterable<StreamChunk>
|
|
72
|
+
* - Otherwise: Promise<LiveVideoGenerationResult>
|
|
73
|
+
*/
|
|
74
|
+
export type LiveVideoActivityResult<TStream extends boolean = false> = TStream extends true ? AsyncIterable<StreamChunk> : Promise<LiveVideoGenerationResult>;
|
|
75
|
+
/**
|
|
76
|
+
* Live generation activity - opens a live, prompt-steerable video session.
|
|
77
|
+
*
|
|
78
|
+
* @example Mint a session token on the server
|
|
79
|
+
* ```ts
|
|
80
|
+
* import { generateLiveVideo } from '@tanstack/ai'
|
|
81
|
+
* import { reactorVideo } from '@tanstack/ai-reactor'
|
|
82
|
+
*
|
|
83
|
+
* const live = await generateLiveVideo({
|
|
84
|
+
* adapter: reactorVideo('helios'),
|
|
85
|
+
* prompt: 'A red sports car powerslides a mountain hairpin',
|
|
86
|
+
* })
|
|
87
|
+
*
|
|
88
|
+
* // Hand live.token, live.model, and live.prompt to the browser.
|
|
89
|
+
* ```
|
|
90
|
+
*
|
|
91
|
+
* @experimental Live generation is an experimental feature and may change.
|
|
92
|
+
*/
|
|
93
|
+
export declare function generateLiveVideo<TAdapter extends LiveVideoAdapter<string, LiveVideoProviderOptions<TAdapter>>, TStream extends boolean = false>(options: LiveVideoActivityOptions<TAdapter, TStream>): LiveVideoActivityResult<TStream>;
|
|
94
|
+
/**
|
|
95
|
+
* Create typed options for the generateLiveVideo() function without executing.
|
|
96
|
+
*/
|
|
97
|
+
export declare function createLiveVideoOptions<TAdapter extends LiveVideoAdapter<string, LiveVideoProviderOptions<TAdapter>>, TStream extends boolean = false>(options: LiveVideoActivityOptions<TAdapter, TStream>): LiveVideoActivityOptions<TAdapter, TStream>;
|
|
98
|
+
export type { LiveVideoAdapter, LiveVideoAdapterConfig, AnyLiveVideoAdapter, } from './adapter.js';
|
|
99
|
+
export { BaseLiveVideoAdapter } from './adapter.js';
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { resolveDebugOption } from "../../logger/resolve.js";
|
|
2
|
+
import { streamGenerationResult } from "../stream-generation-result.js";
|
|
3
|
+
import { applyGenerationResultTransforms, createGenerationContext, runGenerationAbort, runGenerationError, runGenerationFinish, runGenerationStart, runGenerationUsage } from "../middleware/run.js";
|
|
4
|
+
import { abortReasonMessage, createActivityAbortControls, isActivityAbortError, raceWithAbort } from "../../utilities/activity-abort.js";
|
|
5
|
+
import "./adapter.js";
|
|
6
|
+
import { aiEventClient } from "@tanstack/ai-event-client";
|
|
7
|
+
//#region src/activities/generateLiveVideo/index.ts
|
|
8
|
+
/**
|
|
9
|
+
* Live Activity (Experimental)
|
|
10
|
+
*
|
|
11
|
+
* Mints a session token for a live, prompt-steerable video session. Unlike
|
|
12
|
+
* generateVideo (a job that finishes with a URL), the browser then connects
|
|
13
|
+
* with the token, sets the prompt, and streams until stop/close.
|
|
14
|
+
*
|
|
15
|
+
* @experimental Live generation is an experimental feature and may change.
|
|
16
|
+
*/
|
|
17
|
+
/** The adapter kind this activity handles */
|
|
18
|
+
var kind = "liveVideo";
|
|
19
|
+
function createId(prefix) {
|
|
20
|
+
return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Live generation activity - opens a live, prompt-steerable video session.
|
|
24
|
+
*
|
|
25
|
+
* @example Mint a session token on the server
|
|
26
|
+
* ```ts
|
|
27
|
+
* import { generateLiveVideo } from '@tanstack/ai'
|
|
28
|
+
* import { reactorVideo } from '@tanstack/ai-reactor'
|
|
29
|
+
*
|
|
30
|
+
* const live = await generateLiveVideo({
|
|
31
|
+
* adapter: reactorVideo('helios'),
|
|
32
|
+
* prompt: 'A red sports car powerslides a mountain hairpin',
|
|
33
|
+
* })
|
|
34
|
+
*
|
|
35
|
+
* // Hand live.token, live.model, and live.prompt to the browser.
|
|
36
|
+
* ```
|
|
37
|
+
*
|
|
38
|
+
* @experimental Live generation is an experimental feature and may change.
|
|
39
|
+
*/
|
|
40
|
+
function generateLiveVideo(options) {
|
|
41
|
+
if (options.stream) return streamGenerationResult((resolved) => runGenerateLiveVideo({
|
|
42
|
+
...options,
|
|
43
|
+
runId: resolved.runId
|
|
44
|
+
}), options);
|
|
45
|
+
return runGenerateLiveVideo(options);
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Run the core live generation logic (non-streaming).
|
|
49
|
+
*/
|
|
50
|
+
async function runGenerateLiveVideo(options) {
|
|
51
|
+
const { adapter, stream: _stream, debug: _debug, middleware, threadId, runId, timeout, abortSignal: callerAbortSignal, ...rest } = options;
|
|
52
|
+
const model = adapter.model;
|
|
53
|
+
const requestId = createId("liveVideo");
|
|
54
|
+
const startTime = Date.now();
|
|
55
|
+
const logger = resolveDebugOption(options.debug);
|
|
56
|
+
const abortControls = createActivityAbortControls({
|
|
57
|
+
timeout,
|
|
58
|
+
abortSignal: callerAbortSignal
|
|
59
|
+
});
|
|
60
|
+
const providerName = adapter.provider ?? adapter.name ?? "unknown";
|
|
61
|
+
const mwCtx = createGenerationContext({
|
|
62
|
+
requestId,
|
|
63
|
+
activity: "liveVideo",
|
|
64
|
+
provider: adapter.name,
|
|
65
|
+
model,
|
|
66
|
+
modelOptions: rest.modelOptions,
|
|
67
|
+
threadId,
|
|
68
|
+
runId,
|
|
69
|
+
artifactInputs: { prompt: rest.prompt },
|
|
70
|
+
createId
|
|
71
|
+
});
|
|
72
|
+
await runGenerationStart(middleware, mwCtx);
|
|
73
|
+
aiEventClient.emit("liveVideo:request:started", {
|
|
74
|
+
requestId,
|
|
75
|
+
provider: adapter.name,
|
|
76
|
+
model,
|
|
77
|
+
prompt: rest.prompt,
|
|
78
|
+
timestamp: startTime,
|
|
79
|
+
...rest.modelOptions !== void 0 && { modelOptions: rest.modelOptions }
|
|
80
|
+
});
|
|
81
|
+
logger.request(`activity=generateLiveVideo provider=${providerName}`, {
|
|
82
|
+
provider: providerName,
|
|
83
|
+
model
|
|
84
|
+
});
|
|
85
|
+
try {
|
|
86
|
+
const rawResult = await raceWithAbort(adapter.createLiveVideo({
|
|
87
|
+
...rest,
|
|
88
|
+
model,
|
|
89
|
+
logger,
|
|
90
|
+
...abortControls.signal ? { abortSignal: abortControls.signal } : {}
|
|
91
|
+
}), abortControls.signal);
|
|
92
|
+
abortControls.clear();
|
|
93
|
+
const result = await applyGenerationResultTransforms(mwCtx, rawResult);
|
|
94
|
+
const elapsedMs = Date.now() - startTime;
|
|
95
|
+
aiEventClient.emit("liveVideo:request:completed", {
|
|
96
|
+
requestId,
|
|
97
|
+
provider: adapter.name,
|
|
98
|
+
model: result.model,
|
|
99
|
+
prompt: result.prompt,
|
|
100
|
+
status: result.status,
|
|
101
|
+
duration: elapsedMs,
|
|
102
|
+
timestamp: Date.now(),
|
|
103
|
+
...rest.modelOptions !== void 0 && { modelOptions: rest.modelOptions }
|
|
104
|
+
});
|
|
105
|
+
if (result.usage) aiEventClient.emit("liveVideo:usage", {
|
|
106
|
+
requestId,
|
|
107
|
+
model: result.model,
|
|
108
|
+
usage: result.usage,
|
|
109
|
+
timestamp: Date.now(),
|
|
110
|
+
...rest.modelOptions !== void 0 && { modelOptions: rest.modelOptions }
|
|
111
|
+
});
|
|
112
|
+
logger.output(`activity=generateLiveVideo provider=${providerName}`, {
|
|
113
|
+
model: result.model,
|
|
114
|
+
status: result.status
|
|
115
|
+
});
|
|
116
|
+
if (result.usage) await runGenerationUsage(middleware, mwCtx, result.usage);
|
|
117
|
+
await runGenerationFinish(middleware, mwCtx, {
|
|
118
|
+
duration: elapsedMs,
|
|
119
|
+
usage: result.usage
|
|
120
|
+
});
|
|
121
|
+
return result;
|
|
122
|
+
} catch (error) {
|
|
123
|
+
abortControls.clear();
|
|
124
|
+
const elapsedMs = Date.now() - startTime;
|
|
125
|
+
const err = error;
|
|
126
|
+
aiEventClient.emit("liveVideo:request:error", {
|
|
127
|
+
requestId,
|
|
128
|
+
provider: adapter.name,
|
|
129
|
+
model,
|
|
130
|
+
error: {
|
|
131
|
+
message: err.message,
|
|
132
|
+
name: err.name
|
|
133
|
+
},
|
|
134
|
+
duration: elapsedMs,
|
|
135
|
+
timestamp: Date.now(),
|
|
136
|
+
...rest.modelOptions !== void 0 && { modelOptions: rest.modelOptions }
|
|
137
|
+
});
|
|
138
|
+
if (isActivityAbortError(error, abortControls.signal)) await runGenerationAbort(middleware, mwCtx, {
|
|
139
|
+
reason: abortReasonMessage(error, abortControls.signal),
|
|
140
|
+
duration: elapsedMs
|
|
141
|
+
});
|
|
142
|
+
else await runGenerationError(middleware, mwCtx, {
|
|
143
|
+
error,
|
|
144
|
+
duration: elapsedMs
|
|
145
|
+
});
|
|
146
|
+
logger.errors("generateLiveVideo activity failed", {
|
|
147
|
+
error,
|
|
148
|
+
source: "generateLiveVideo"
|
|
149
|
+
});
|
|
150
|
+
throw error;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Create typed options for the generateLiveVideo() function without executing.
|
|
155
|
+
*/
|
|
156
|
+
function createLiveVideoOptions(options) {
|
|
157
|
+
return options;
|
|
158
|
+
}
|
|
159
|
+
//#endregion
|
|
160
|
+
export { createLiveVideoOptions, generateLiveVideo, kind };
|
|
161
|
+
|
|
162
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/activities/generateLiveVideo/index.ts"],"sourcesContent":["/**\n * Live Activity (Experimental)\n *\n * Mints a session token for a live, prompt-steerable video session. Unlike\n * generateVideo (a job that finishes with a URL), the browser then connects\n * with the token, sets the prompt, and streams until stop/close.\n *\n * @experimental Live generation is an experimental feature and may change.\n */\n\nimport { aiEventClient } from '@tanstack/ai-event-client'\nimport { streamGenerationResult } from '../stream-generation-result.js'\nimport { resolveDebugOption } from '../../logger/resolve'\nimport {\n applyGenerationResultTransforms,\n createGenerationContext,\n runGenerationAbort,\n runGenerationError,\n runGenerationFinish,\n runGenerationStart,\n runGenerationUsage,\n} from '../middleware/run'\nimport {\n abortReasonMessage,\n createActivityAbortControls,\n isActivityAbortError,\n raceWithAbort,\n} from '../../utilities/activity-abort'\nimport type { InternalLogger } from '../../logger/internal-logger'\nimport type { DebugOption } from '../../logger/types'\nimport type { GenerationMiddleware } from '../middleware/types'\nimport type { LiveVideoAdapter } from './adapter'\nimport type { StreamChunk, LiveVideoGenerationResult } from '../../types'\n\n// ===========================\n// Activity Kind\n// ===========================\n\n/** The adapter kind this activity handles */\nexport const kind = 'liveVideo' as const\n\n// ===========================\n// Type Extraction Helpers\n// ===========================\n\n/**\n * Extract provider options from a LiveVideoAdapter via ~types.\n */\nexport type LiveVideoProviderOptions<TAdapter> = TAdapter extends {\n '~types': { providerOptions: infer P extends object }\n}\n ? P\n : object\n\n// ===========================\n// Activity Options Type\n// ===========================\n\n/**\n * Options for the live generation activity.\n * The model is extracted from the adapter's model property.\n *\n * @template TAdapter - The live adapter type\n * @template TStream - Whether to stream the output\n *\n * @experimental Live generation is an experimental feature and may change.\n */\nexport interface LiveVideoActivityOptions<\n TAdapter extends LiveVideoAdapter<string, LiveVideoProviderOptions<TAdapter>>,\n TStream extends boolean = false,\n> {\n /** The live adapter to use (must be created with a model) */\n adapter: TAdapter & { kind: typeof kind }\n /** Natural-language description of the shot or scene */\n prompt: string\n /** Provider-specific options for live generation */\n modelOptions?: LiveVideoProviderOptions<TAdapter>\n /**\n * Whether to wrap the token result as StreamChunks for SSE transport.\n * This is not the live video. When false or omitted, returns\n * Promise<LiveVideoGenerationResult>.\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 the token mint in milliseconds.\n * No SDK-wide default. Composed with {@link abortSignal}; the first abort wins.\n */\n timeout?: number\n /**\n * Caller cancellation signal (request disconnects, job/runtime cancellation).\n * Composed with {@link timeout} into an effective signal forwarded to the\n * adapter. Request-specific — not stored on global provider client config.\n */\n abortSignal?: AbortSignal\n}\n\n// ===========================\n// Activity Result Type\n// ===========================\n\n/**\n * Result type for the live generation activity.\n * - If stream is true: AsyncIterable<StreamChunk>\n * - Otherwise: Promise<LiveVideoGenerationResult>\n */\nexport type LiveVideoActivityResult<TStream extends boolean = false> =\n TStream extends true\n ? AsyncIterable<StreamChunk>\n : Promise<LiveVideoGenerationResult>\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 * Live generation activity - opens a live, prompt-steerable video session.\n *\n * @example Mint a session token on the server\n * ```ts\n * import { generateLiveVideo } from '@tanstack/ai'\n * import { reactorVideo } from '@tanstack/ai-reactor'\n *\n * const live = await generateLiveVideo({\n * adapter: reactorVideo('helios'),\n * prompt: 'A red sports car powerslides a mountain hairpin',\n * })\n *\n * // Hand live.token, live.model, and live.prompt to the browser.\n * ```\n *\n * @experimental Live generation is an experimental feature and may change.\n */\nexport function generateLiveVideo<\n TAdapter extends LiveVideoAdapter<string, LiveVideoProviderOptions<TAdapter>>,\n TStream extends boolean = false,\n>(\n options: LiveVideoActivityOptions<TAdapter, TStream>,\n): LiveVideoActivityResult<TStream> {\n if (options.stream) {\n return streamGenerationResult(\n (resolved) => runGenerateLiveVideo({ ...options, runId: resolved.runId }),\n options,\n ) as LiveVideoActivityResult<TStream>\n }\n return runGenerateLiveVideo(options) as LiveVideoActivityResult<TStream>\n}\n\n/**\n * Run the core live generation logic (non-streaming).\n */\nasync function runGenerateLiveVideo<\n TAdapter extends LiveVideoAdapter<string, LiveVideoProviderOptions<TAdapter>>,\n>(\n options: LiveVideoActivityOptions<TAdapter, boolean>,\n): Promise<LiveVideoGenerationResult> {\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('liveVideo')\n const startTime = Date.now()\n const logger: InternalLogger = resolveDebugOption(options.debug)\n const abortControls = createActivityAbortControls({\n timeout,\n abortSignal: callerAbortSignal,\n })\n const providerName =\n (adapter as { name?: string; provider?: string }).provider ??\n (adapter as { name?: string }).name ??\n 'unknown'\n\n const mwCtx = createGenerationContext({\n requestId,\n activity: 'liveVideo',\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 aiEventClient.emit('liveVideo:request:started', {\n requestId,\n provider: adapter.name,\n model,\n prompt: rest.prompt,\n timestamp: startTime,\n ...(rest.modelOptions !== undefined && {\n modelOptions: rest.modelOptions as Record<string, unknown>,\n }),\n })\n\n logger.request(`activity=generateLiveVideo provider=${providerName}`, {\n provider: providerName,\n model,\n })\n\n try {\n const rawResult = await raceWithAbort(\n adapter.createLiveVideo({\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 elapsedMs = Date.now() - startTime\n\n aiEventClient.emit('liveVideo:request:completed', {\n requestId,\n provider: adapter.name,\n model: result.model,\n prompt: result.prompt,\n status: result.status,\n duration: elapsedMs,\n timestamp: Date.now(),\n ...(rest.modelOptions !== undefined && {\n modelOptions: rest.modelOptions as Record<string, unknown>,\n }),\n })\n\n if (result.usage) {\n aiEventClient.emit('liveVideo:usage', {\n requestId,\n model: result.model,\n usage: result.usage,\n timestamp: Date.now(),\n ...(rest.modelOptions !== undefined && {\n modelOptions: rest.modelOptions as Record<string, unknown>,\n }),\n })\n }\n\n logger.output(`activity=generateLiveVideo provider=${providerName}`, {\n model: result.model,\n status: result.status,\n })\n\n if (result.usage) await runGenerationUsage(middleware, mwCtx, result.usage)\n await runGenerationFinish(middleware, mwCtx, {\n duration: elapsedMs,\n usage: result.usage,\n })\n\n return result\n } catch (error) {\n abortControls.clear()\n const elapsedMs = Date.now() - startTime\n const err = error as Error\n aiEventClient.emit('liveVideo:request:error', {\n requestId,\n provider: adapter.name,\n model,\n error: { message: err.message, name: err.name },\n duration: elapsedMs,\n timestamp: Date.now(),\n ...(rest.modelOptions !== undefined && {\n modelOptions: rest.modelOptions as Record<string, unknown>,\n }),\n })\n if (isActivityAbortError(error, abortControls.signal)) {\n await runGenerationAbort(middleware, mwCtx, {\n reason: abortReasonMessage(error, abortControls.signal),\n duration: elapsedMs,\n })\n } else {\n await runGenerationError(middleware, mwCtx, {\n error,\n duration: elapsedMs,\n })\n }\n logger.errors('generateLiveVideo activity failed', {\n error,\n source: 'generateLiveVideo',\n })\n throw error\n }\n}\n\n// ===========================\n// Options Factory\n// ===========================\n\n/**\n * Create typed options for the generateLiveVideo() function without executing.\n */\nexport function createLiveVideoOptions<\n TAdapter extends LiveVideoAdapter<string, LiveVideoProviderOptions<TAdapter>>,\n TStream extends boolean = false,\n>(\n options: LiveVideoActivityOptions<TAdapter, TStream>,\n): LiveVideoActivityOptions<TAdapter, TStream> {\n return options\n}\n\n// Re-export adapter types\nexport type {\n LiveVideoAdapter,\n LiveVideoAdapterConfig,\n A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C1C,QAAQ,mBAAmB,OAAO,cAAc,MAAM;GACtD,UAAU;EACZ,CAAC;OAED,MAAM,mBAAmB,YAAY,OAAO;GAC1C;GACA,UAAU;EACZ,CAAC;EAEH,OAAO,OAAO,qCAAqC;GACjD;GACA,QAAQ;EACV,CAAC;EACD,MAAM;CACR;AACF;;;;AASA,SAAgB,uBAId,SAC6C;CAC7C,OAAO;AACT"}
|
|
@@ -9,7 +9,9 @@ import { aiEventClient } from "@tanstack/ai-event-client";
|
|
|
9
9
|
/**
|
|
10
10
|
* Video Activity (Experimental)
|
|
11
11
|
*
|
|
12
|
-
* Generates videos from text prompts
|
|
12
|
+
* Generates videos from text prompts. Adapters use a jobs/polling
|
|
13
|
+
* architecture: create a job, poll for status, then fetch a download URL.
|
|
14
|
+
* For a live, prompt-steerable stream, use generateLiveVideo().
|
|
13
15
|
* This is a self-contained module with implementation, types, and JSDoc.
|
|
14
16
|
*
|
|
15
17
|
* @experimental Video generation is an experimental feature and may change.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/activities/generateVideo/index.ts"],"sourcesContent":["/**\n * Video Activity (Experimental)\n *\n * Generates videos from text prompts using a jobs/polling architecture.\n * This is a self-contained module with implementation, types, and JSDoc.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\n\nimport { aiEventClient } from '@tanstack/ai-event-client'\nimport { toRunErrorPayload } from '../error-payload'\nimport { resolveDebugOption } from '../../logger/resolve'\nimport {\n applyGenerationResultTransforms,\n createGenerationContext,\n runGenerationAbort,\n runGenerationError,\n runGenerationFinish,\n runGenerationStart,\n runGenerationUsage,\n} from '../middleware/run'\nimport {\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 // Transforms see the submission result (no url yet, so nothing to copy into a\n // blob store) purely so the run record captures the jobId and any prompt\n // inputs. No finish hook: the run is still running.\n return await applyGenerationResultTransforms(mwCtx, jobResult)\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (!signal) {\n return new Promise((resolve) => setTimeout(resolve, ms))\n }\n if (signal.aborted) {\n return Promise.reject(toAbortError(signal.reason))\n }\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', onAbort)\n resolve()\n }, ms)\n const onAbort = () => {\n clearTimeout(timer)\n signal.removeEventListener('abort', onAbort)\n reject(toAbortError(signal.reason))\n }\n signal.addEventListener('abort', onAbort, { once: true })\n })\n}\n\n/**\n * Internal streaming implementation for video generation.\n * Handles the full job lifecycle: create job → poll for status → stream updates → yield final result.\n */\nasync function* runStreamingVideoGeneration<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n>(options: VideoCreateOptions<TAdapter, true>): AsyncIterable<StreamChunk> {\n const {\n adapter,\n prompt,\n size,\n duration,\n modelOptions,\n middleware,\n timeout,\n abortSignal: callerAbortSignal,\n } = options\n const model = adapter.model\n const runId = options.runId ?? createId('run')\n const requestId = createId('video')\n const obsStartTime = Date.now()\n const pollingInterval = options.pollingInterval ?? 2000\n const maxDuration = options.maxDuration ?? 600_000\n const logger: InternalLogger = resolveDebugOption(options.debug)\n const abortControls = createActivityAbortControls({\n timeout,\n abortSignal: callerAbortSignal,\n })\n const providerName =\n (adapter as { name?: string; provider?: string }).provider ??\n (adapter as { name?: string }).name ??\n 'unknown'\n\n // The wire needs a thread id on every RUN_* chunk, so one is minted when the\n // caller passes none — matching `streamGenerationResult`, which the other\n // activities stream through.\n const wireThreadId = options.threadId ?? createId('thread')\n\n yield {\n type: 'RUN_STARTED',\n runId,\n threadId: wireThreadId,\n timestamp: Date.now(),\n } as StreamChunk\n\n const mwCtx = createGenerationContext({\n requestId,\n activity: 'video',\n provider: adapter.name,\n model,\n modelOptions,\n // Identity has to reach the middleware, not just the chunks: persistence\n // keys the run record on these, and without them it falls back to the\n // internal `requestId` and records no thread link at all.\n //\n // Deliberately the CALLER's `threadId`, never `wireThreadId`: a minted id is\n // known to nobody, so persisting it would file the run in a slot no client\n // could ever hydrate — worse than recording no link, because it looks like\n // one. This mirrors `generateImage`.\n threadId: options.threadId,\n runId,\n artifactInputs: { prompt },\n createId,\n })\n\n await runGenerationStart(middleware, mwCtx)\n\n logger.request(\n `activity=generateVideo provider=${providerName} stream=true`,\n {\n provider: providerName,\n model,\n },\n )\n\n // Tracks whether a terminal observer event (finish/error/abort) has already\n // fired, so the `finally` below can fire one on abandonment without\n // double-firing.\n let settled = false\n try {\n // Create the video generation job\n const jobResult = await raceWithAbort(\n adapter.createVideoJob({\n model,\n prompt,\n size,\n duration,\n modelOptions,\n logger,\n ...(abortControls.signal ? { abortSignal: abortControls.signal } : {}),\n }),\n abortControls.signal,\n )\n\n yield {\n type: 'CUSTOM',\n name: 'video:job:created',\n value: { jobId: jobResult.jobId },\n timestamp: Date.now(),\n }\n\n // Poll for completion\n const startTime = Date.now()\n while (Date.now() - startTime < maxDuration) {\n await sleep(pollingInterval, abortControls.signal)\n\n const statusResult = await adapter.getVideoStatus(jobResult.jobId)\n\n yield {\n type: 'CUSTOM',\n name: 'video:status',\n value: {\n jobId: jobResult.jobId,\n status: statusResult.status,\n progress: statusResult.progress,\n error: statusResult.error,\n },\n timestamp: Date.now(),\n }\n\n if (statusResult.status === 'completed') {\n const urlResult = await adapter.getVideoUrl(jobResult.jobId)\n\n logger.output(\n `activity=generateVideo jobId=${jobResult.jobId} status=completed`,\n {\n jobId: jobResult.jobId,\n url: urlResult.url,\n },\n )\n\n // Run the result transforms before anything observes the result, the\n // same as every other media activity. This is what lets persistence\n // copy the video into a blob store, attach its artifact refs, and\n // rewrite `url` to a durable app-origin one — so the chunk below and\n // the stored run record carry the SAME urls. Skipping it leaves a\n // result whose only url is the provider's expiring link.\n const rawResult = {\n jobId: jobResult.jobId,\n status: 'completed' as const,\n url: urlResult.url,\n expiresAt: urlResult.expiresAt,\n ...(urlResult.usage ? { usage: urlResult.usage } : {}),\n }\n const result = await applyGenerationResultTransforms(mwCtx, rawResult)\n\n // Fire finish before yielding the terminal chunks: the generation has\n // succeeded, so a consumer that stops reading after `generation:result`\n // (without pulling `RUN_FINISHED`) must not trip the abandonment path in\n // `finally`, which would otherwise report a spurious cancellation.\n if (urlResult.usage)\n await runGenerationUsage(middleware, mwCtx, urlResult.usage)\n await runGenerationFinish(middleware, mwCtx, {\n duration: Date.now() - obsStartTime,\n usage: urlResult.usage,\n })\n settled = true\n abortControls.clear()\n\n yield {\n type: 'CUSTOM',\n name: 'generation:result',\n value: result,\n timestamp: Date.now(),\n }\n\n yield* 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":";;;;;;;;;;;;;;;;;AAqDA,IAAa,OAAO;AA2EpB,SAAS,SAAS,QAAwB;CACxC,OAAO,GAAG,OAAO,GAAG,KAAK,IAAI,EAAE,GAAG,K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AC;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 {\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;CA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