@tanstack/ai 0.42.0 → 0.43.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 +15 -1
- package/dist/esm/activities/chat/adapter.js +23 -16
- package/dist/esm/activities/chat/adapter.js.map +1 -1
- package/dist/esm/activities/chat/agent-loop-strategies.d.ts +5 -36
- package/dist/esm/activities/chat/agent-loop-strategies.js +75 -21
- package/dist/esm/activities/chat/agent-loop-strategies.js.map +1 -1
- package/dist/esm/activities/chat/cancel.d.ts +40 -0
- package/dist/esm/activities/chat/cancel.js +54 -0
- package/dist/esm/activities/chat/cancel.js.map +1 -0
- package/dist/esm/activities/chat/index.d.ts +28 -21
- package/dist/esm/activities/chat/index.js +2100 -1813
- package/dist/esm/activities/chat/index.js.map +1 -1
- package/dist/esm/activities/chat/mcp/manager.d.ts +2 -2
- package/dist/esm/activities/chat/mcp/manager.js +90 -77
- package/dist/esm/activities/chat/mcp/manager.js.map +1 -1
- package/dist/esm/activities/chat/mcp/types.d.ts +2 -2
- package/dist/esm/activities/chat/messages.js +397 -346
- package/dist/esm/activities/chat/messages.js.map +1 -1
- package/dist/esm/activities/chat/middleware/builder.js +17 -15
- package/dist/esm/activities/chat/middleware/builder.js.map +1 -1
- package/dist/esm/activities/chat/middleware/capabilities.js +78 -43
- package/dist/esm/activities/chat/middleware/capabilities.js.map +1 -1
- package/dist/esm/activities/chat/middleware/compose.d.ts +94 -1
- package/dist/esm/activities/chat/middleware/compose.js +623 -531
- package/dist/esm/activities/chat/middleware/compose.js.map +1 -1
- package/dist/esm/activities/chat/middleware/define.js +12 -5
- package/dist/esm/activities/chat/middleware/define.js.map +1 -1
- package/dist/esm/activities/chat/middleware/index.d.ts +5 -1
- package/dist/esm/activities/chat/middleware/locks.d.ts +50 -0
- package/dist/esm/activities/chat/middleware/locks.js +71 -0
- package/dist/esm/activities/chat/middleware/locks.js.map +1 -0
- package/dist/esm/activities/chat/middleware/pending-turn.d.ts +15 -0
- package/dist/esm/activities/chat/middleware/pending-turn.js +35 -0
- package/dist/esm/activities/chat/middleware/pending-turn.js.map +1 -0
- package/dist/esm/activities/chat/middleware/run-disconnect.d.ts +23 -0
- package/dist/esm/activities/chat/middleware/run-disconnect.js +42 -0
- package/dist/esm/activities/chat/middleware/run-disconnect.js.map +1 -0
- package/dist/esm/activities/chat/middleware/run-store.d.ts +283 -0
- package/dist/esm/activities/chat/middleware/run-store.js +176 -0
- package/dist/esm/activities/chat/middleware/run-store.js.map +1 -0
- package/dist/esm/activities/chat/middleware/sandbox-runtime.js +14 -8
- package/dist/esm/activities/chat/middleware/sandbox-runtime.js.map +1 -1
- package/dist/esm/activities/chat/middleware/tool-cache-middleware.js +79 -70
- package/dist/esm/activities/chat/middleware/tool-cache-middleware.js.map +1 -1
- package/dist/esm/activities/chat/middleware/types.d.ts +59 -2
- package/dist/esm/activities/chat/middleware/validate.js +23 -28
- package/dist/esm/activities/chat/middleware/validate.js.map +1 -1
- package/dist/esm/activities/chat/stream/json-parser.js +39 -25
- package/dist/esm/activities/chat/stream/json-parser.js.map +1 -1
- package/dist/esm/activities/chat/stream/message-updaters.js +275 -234
- package/dist/esm/activities/chat/stream/message-updaters.js.map +1 -1
- package/dist/esm/activities/chat/stream/processor.d.ts +24 -4
- package/dist/esm/activities/chat/stream/processor.js +1341 -1542
- package/dist/esm/activities/chat/stream/processor.js.map +1 -1
- package/dist/esm/activities/chat/stream/strategies.js +69 -53
- package/dist/esm/activities/chat/stream/strategies.js.map +1 -1
- package/dist/esm/activities/chat/tools/approval-schema.d.ts +19 -0
- package/dist/esm/activities/chat/tools/approval-schema.js +117 -0
- package/dist/esm/activities/chat/tools/approval-schema.js.map +1 -0
- package/dist/esm/activities/chat/tools/lazy-tool-manager.js +164 -191
- package/dist/esm/activities/chat/tools/lazy-tool-manager.js.map +1 -1
- package/dist/esm/activities/chat/tools/lazy-tools.js +24 -12
- package/dist/esm/activities/chat/tools/lazy-tools.js.map +1 -1
- package/dist/esm/activities/chat/tools/schema-converter.js +293 -146
- package/dist/esm/activities/chat/tools/schema-converter.js.map +1 -1
- package/dist/esm/activities/chat/tools/tool-calls.d.ts +18 -2
- package/dist/esm/activities/chat/tools/tool-calls.js +522 -531
- package/dist/esm/activities/chat/tools/tool-calls.js.map +1 -1
- package/dist/esm/activities/chat/tools/tool-definition.d.ts +75 -16
- package/dist/esm/activities/chat/tools/tool-definition.js +95 -23
- package/dist/esm/activities/chat/tools/tool-definition.js.map +1 -1
- package/dist/esm/activities/error-payload.js +85 -47
- package/dist/esm/activities/error-payload.js.map +1 -1
- package/dist/esm/activities/generateAudio/adapter.js +22 -15
- package/dist/esm/activities/generateAudio/adapter.js.map +1 -1
- package/dist/esm/activities/generateAudio/index.d.ts +4 -0
- package/dist/esm/activities/generateAudio/index.js +141 -105
- package/dist/esm/activities/generateAudio/index.js.map +1 -1
- package/dist/esm/activities/generateImage/adapter.js +22 -15
- package/dist/esm/activities/generateImage/adapter.js.map +1 -1
- package/dist/esm/activities/generateImage/index.d.ts +4 -0
- package/dist/esm/activities/generateImage/index.js +155 -111
- package/dist/esm/activities/generateImage/index.js.map +1 -1
- package/dist/esm/activities/generateSpeech/adapter.js +22 -15
- package/dist/esm/activities/generateSpeech/adapter.js.map +1 -1
- package/dist/esm/activities/generateSpeech/index.d.ts +4 -0
- package/dist/esm/activities/generateSpeech/index.js +159 -110
- package/dist/esm/activities/generateSpeech/index.js.map +1 -1
- package/dist/esm/activities/generateTranscription/adapter.js +22 -15
- package/dist/esm/activities/generateTranscription/adapter.js.map +1 -1
- package/dist/esm/activities/generateTranscription/index.d.ts +4 -0
- package/dist/esm/activities/generateTranscription/index.js +159 -100
- package/dist/esm/activities/generateTranscription/index.js.map +1 -1
- package/dist/esm/activities/generateVideo/adapter.js +36 -29
- package/dist/esm/activities/generateVideo/adapter.js.map +1 -1
- package/dist/esm/activities/generateVideo/index.d.ts +143 -19
- package/dist/esm/activities/generateVideo/index.js +456 -279
- package/dist/esm/activities/generateVideo/index.js.map +1 -1
- package/dist/esm/activities/generateVideo/snap.js +60 -48
- package/dist/esm/activities/generateVideo/snap.js.map +1 -1
- package/dist/esm/activities/index.js +8 -34
- package/dist/esm/activities/middleware/index.d.ts +1 -1
- package/dist/esm/activities/middleware/run.d.ts +10 -0
- package/dist/esm/activities/middleware/run.js +53 -29
- package/dist/esm/activities/middleware/run.js.map +1 -1
- package/dist/esm/activities/middleware/types.d.ts +44 -6
- package/dist/esm/activities/stream-generation-result.d.ts +4 -1
- package/dist/esm/activities/stream-generation-result.js +79 -44
- package/dist/esm/activities/stream-generation-result.js.map +1 -1
- package/dist/esm/activities/summarize/adapter.js +22 -15
- package/dist/esm/activities/summarize/adapter.js.map +1 -1
- package/dist/esm/activities/summarize/chat-stream-summarize.js +252 -202
- package/dist/esm/activities/summarize/chat-stream-summarize.js.map +1 -1
- package/dist/esm/activities/summarize/index.d.ts +27 -0
- package/dist/esm/activities/summarize/index.js +268 -102
- package/dist/esm/activities/summarize/index.js.map +1 -1
- package/dist/esm/adapter-internals.d.ts +2 -1
- package/dist/esm/adapter-internals.js +4 -11
- package/dist/esm/client.d.ts +25 -3
- package/dist/esm/client.js +131 -64
- package/dist/esm/client.js.map +1 -1
- package/dist/esm/custom-events.d.ts +76 -0
- package/dist/esm/custom-events.js +37 -0
- package/dist/esm/custom-events.js.map +1 -0
- package/dist/esm/delivery-detach.d.ts +50 -0
- package/dist/esm/delivery-detach.js +71 -0
- package/dist/esm/delivery-detach.js.map +1 -0
- package/dist/esm/delivery-disconnect.d.ts +62 -0
- package/dist/esm/delivery-disconnect.js +81 -0
- package/dist/esm/delivery-disconnect.js.map +1 -0
- package/dist/esm/extend-adapter.js +19 -17
- package/dist/esm/extend-adapter.js.map +1 -1
- package/dist/esm/index.d.ts +24 -6
- package/dist/esm/index.js +30 -98
- package/dist/esm/interrupt-resume.d.ts +71 -0
- package/dist/esm/interrupt-resume.js +438 -0
- package/dist/esm/interrupt-resume.js.map +1 -0
- package/dist/esm/interrupt-serialization.d.ts +12 -0
- package/dist/esm/interrupt-serialization.js +178 -0
- package/dist/esm/interrupt-serialization.js.map +1 -0
- package/dist/esm/interrupts.d.ts +84 -0
- package/dist/esm/interrupts.js +31 -0
- package/dist/esm/interrupts.js.map +1 -0
- package/dist/esm/locks.d.ts +10 -0
- package/dist/esm/locks.js +2 -0
- package/dist/esm/logger/console-logger.js +101 -78
- package/dist/esm/logger/console-logger.js.map +1 -1
- package/dist/esm/logger/internal-logger.js +104 -89
- package/dist/esm/logger/internal-logger.js.map +1 -1
- package/dist/esm/logger/resolve.js +54 -49
- package/dist/esm/logger/resolve.js.map +1 -1
- package/dist/esm/logger/types.d.ts +1 -1
- package/dist/esm/middlewares/content-guard.js +142 -148
- package/dist/esm/middlewares/content-guard.js.map +1 -1
- package/dist/esm/middlewares/index.js +2 -6
- package/dist/esm/middlewares/otel.js +598 -732
- package/dist/esm/middlewares/otel.js.map +1 -1
- package/dist/esm/middlewares/usage-attributes.js +47 -40
- package/dist/esm/middlewares/usage-attributes.js.map +1 -1
- package/dist/esm/realtime/event-emitter.js +24 -25
- package/dist/esm/realtime/event-emitter.js.map +1 -1
- package/dist/esm/realtime/index.d.ts +5 -9
- package/dist/esm/realtime/index.js +29 -6
- package/dist/esm/realtime/index.js.map +1 -1
- package/dist/esm/scope.d.ts +47 -0
- package/dist/esm/stream-durability.d.ts +171 -0
- package/dist/esm/stream-durability.js +295 -0
- package/dist/esm/stream-durability.js.map +1 -0
- package/dist/esm/stream-to-response.d.ts +178 -13
- package/dist/esm/stream-to-response.js +663 -115
- package/dist/esm/stream-to-response.js.map +1 -1
- package/dist/esm/strip-to-spec-middleware.js +30 -16
- package/dist/esm/strip-to-spec-middleware.js.map +1 -1
- package/dist/esm/system-prompts.js +27 -21
- package/dist/esm/system-prompts.js.map +1 -1
- package/dist/esm/tool-registry.js +72 -45
- package/dist/esm/tool-registry.js.map +1 -1
- package/dist/esm/tools/provider-tool.js +14 -5
- package/dist/esm/tools/provider-tool.js.map +1 -1
- package/dist/esm/types.d.ts +321 -42
- package/dist/esm/types.js +2 -0
- package/dist/esm/utilities/ag-ui-wire.js +79 -93
- package/dist/esm/utilities/ag-ui-wire.js.map +1 -1
- package/dist/esm/utilities/chat-params.d.ts +26 -4
- package/dist/esm/utilities/chat-params.js +218 -92
- package/dist/esm/utilities/chat-params.js.map +1 -1
- package/dist/esm/utilities/errors.js +28 -18
- package/dist/esm/utilities/errors.js.map +1 -1
- package/dist/esm/utilities/media-prompt.js +46 -41
- package/dist/esm/utilities/media-prompt.js.map +1 -1
- package/dist/esm/utilities/numbers.js +13 -10
- package/dist/esm/utilities/numbers.js.map +1 -1
- package/dist/esm/utilities/provider-executed.js +20 -11
- package/dist/esm/utilities/provider-executed.js.map +1 -1
- package/dist/esm/utilities/sampling-keys.js +31 -19
- package/dist/esm/utilities/sampling-keys.js.map +1 -1
- package/dist/esm/utilities/tool-result.js +42 -30
- package/dist/esm/utilities/tool-result.js.map +1 -1
- package/dist/esm/utilities/usage.js +27 -9
- package/dist/esm/utilities/usage.js.map +1 -1
- package/dist/esm/utils.js +26 -18
- package/dist/esm/utils.js.map +1 -1
- package/package.json +10 -6
- package/skills/ai-core/SKILL.md +69 -18
- package/skills/ai-core/adapter-configuration/SKILL.md +44 -21
- package/skills/ai-core/adapter-configuration/references/anthropic-adapter.md +1 -3
- package/skills/ai-core/adapter-configuration/references/byteplus-adapter.md +148 -0
- package/skills/ai-core/adapter-configuration/references/gemini-adapter.md +2 -6
- package/skills/ai-core/adapter-configuration/references/groq-adapter.md +2 -6
- package/skills/ai-core/adapter-configuration/references/openai-adapter.md +1 -3
- package/skills/ai-core/ag-ui-protocol/SKILL.md +1 -1
- package/skills/ai-core/chat-experience/SKILL.md +98 -11
- package/skills/ai-core/client-persistence/SKILL.md +277 -0
- package/skills/ai-core/custom-backend-integration/SKILL.md +1 -1
- package/skills/ai-core/debug-logging/SKILL.md +1 -1
- package/skills/ai-core/locks/SKILL.md +143 -0
- package/skills/ai-core/media-generation/SKILL.md +144 -12
- package/skills/ai-core/middleware/SKILL.md +258 -33
- package/skills/ai-core/structured-outputs/SKILL.md +1 -1
- package/skills/ai-core/tool-calling/SKILL.md +54 -61
- package/src/activities/chat/agent-loop-strategies.ts +5 -39
- package/src/activities/chat/cancel.ts +81 -0
- package/src/activities/chat/index.ts +1091 -200
- package/src/activities/chat/mcp/manager.ts +4 -4
- package/src/activities/chat/mcp/types.ts +2 -2
- package/src/activities/chat/messages.ts +5 -3
- package/src/activities/chat/middleware/builder.ts +1 -1
- package/src/activities/chat/middleware/compose.ts +186 -9
- package/src/activities/chat/middleware/index.ts +26 -0
- package/src/activities/chat/middleware/locks.ts +102 -0
- package/src/activities/chat/middleware/pending-turn.ts +47 -0
- package/src/activities/chat/middleware/run-disconnect.ts +62 -0
- package/src/activities/chat/middleware/run-store.ts +412 -0
- package/src/activities/chat/middleware/types.ts +62 -1
- package/src/activities/chat/stream/processor.ts +189 -5
- package/src/activities/chat/tools/approval-schema.ts +205 -0
- package/src/activities/chat/tools/tool-calls.ts +106 -13
- package/src/activities/chat/tools/tool-definition.ts +210 -39
- package/src/activities/generateAudio/index.ts +20 -3
- package/src/activities/generateImage/index.ts +20 -3
- package/src/activities/generateSpeech/index.ts +25 -3
- package/src/activities/generateTranscription/index.ts +26 -3
- package/src/activities/generateVideo/index.ts +345 -82
- package/src/activities/middleware/index.ts +2 -0
- package/src/activities/middleware/run.ts +31 -0
- package/src/activities/middleware/types.ts +49 -5
- package/src/activities/stream-generation-result.ts +30 -2
- package/src/activities/summarize/chat-stream-summarize.ts +5 -0
- package/src/activities/summarize/index.ts +200 -10
- package/src/adapter-internals.ts +10 -1
- package/src/client.ts +244 -0
- package/src/custom-events.ts +107 -0
- package/src/delivery-detach.ts +72 -0
- package/src/delivery-disconnect.ts +84 -0
- package/src/index.ts +138 -1
- package/src/interrupt-resume.ts +824 -0
- package/src/interrupt-serialization.ts +183 -0
- package/src/interrupts.ts +146 -0
- package/src/locks.ts +17 -0
- package/src/logger/types.ts +1 -1
- package/src/middlewares/otel.ts +1 -0
- package/src/realtime/index.ts +5 -9
- package/src/scope.ts +47 -0
- package/src/stream-durability.ts +598 -0
- package/src/stream-to-response.ts +1051 -95
- package/src/strip-to-spec-middleware.ts +3 -3
- package/src/types.ts +405 -45
- package/src/utilities/chat-params.ts +245 -55
- package/dist/esm/activities/index.js.map +0 -1
- package/dist/esm/adapter-internals.js.map +0 -1
- package/dist/esm/index.js.map +0 -1
- package/dist/esm/middlewares/index.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","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 createGenerationContext,\n runGenerationAbort,\n runGenerationError,\n runGenerationFinish,\n runGenerationStart,\n runGenerationUsage,\n} from '../middleware/run'\nimport type { InternalLogger } from '../../logger/internal-logger'\nimport type { DebugOption } from '../../logger/types'\nimport type { GenerationMiddleware } from '../middleware/types'\nimport type { VideoAdapter } from './adapter'\nimport type {\n MediaPrompt,\n MediaPromptFor,\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 /** Custom run ID (stream mode only) */\n runId?: 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, or implement the\n * `GenerationMiddleware` contract for a custom backend. In streaming mode the\n * span covers the full create→poll→complete lifecycle; in non-streaming mode\n * it covers job submission. An abandoned stream fires `onAbort`.\n */\n middleware?: Array<GenerationMiddleware>\n} & ({} extends VideoProviderOptions<TAdapter>\n ? {\n /** Provider-specific options for video generation */ modelOptions?: VideoProviderOptions<TAdapter>\n }\n : {\n /** Provider-specific options for video generation */ modelOptions: VideoProviderOptions<TAdapter>\n })\n\n/**\n * Options for polling the status of a video generation job.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport interface VideoStatusOptions<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n> extends VideoActivityBaseOptions<TAdapter> {\n /** Request type - get job status */\n request: 'status'\n /** The job ID to check status for */\n jobId: string\n}\n\n/**\n * Options for getting the URL of a completed video.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport interface VideoUrlOptions<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n> extends VideoActivityBaseOptions<TAdapter> {\n /** Request type - get video URL */\n request: 'url'\n /** The job ID to get URL for */\n jobId: string\n}\n\n/**\n * Union type for all video activity options.\n * Discriminated by the `request` field.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport type VideoActivityOptions<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n TRequest extends 'create' | 'status' | 'url' = 'create',\n TStream extends boolean = false,\n> = TRequest extends 'status'\n ? VideoStatusOptions<TAdapter>\n : TRequest extends 'url'\n ? VideoUrlOptions<TAdapter>\n : VideoCreateOptions<TAdapter, TStream>\n\n// ===========================\n// Activity Result Types\n// ===========================\n\n/**\n * Result type for the video activity, based on request type and streaming.\n * - If stream is true (create request): AsyncIterable<StreamChunk>\n * - Otherwise: Promise<VideoJobResult | VideoStatusResult | VideoUrlResult>\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport type VideoActivityResult<\n TRequest extends 'create' | 'status' | 'url' = 'create',\n TStream extends boolean = false,\n> = TRequest extends 'status'\n ? Promise<VideoStatusResult>\n : TRequest extends 'url'\n ? Promise<VideoUrlResult>\n : TStream extends true\n ? AsyncIterable<StreamChunk>\n : Promise<VideoJobResult>\n\n// ===========================\n// Activity Implementation\n// ===========================\n\n/**\n * Generate video - creates a video generation job from a text prompt.\n *\n * Uses AI video generation models to create videos based on natural language descriptions.\n * Unlike image generation, video generation is asynchronous and requires polling for completion.\n *\n * When `stream: true` is passed, handles the full job lifecycle automatically:\n * create job → poll for status → stream updates → yield final result.\n *\n * @experimental Video generation is an experimental feature and may change.\n *\n * @example Create a video generation job\n * ```ts\n * import { generateVideo } 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 *\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 * Internal implementation of non-streaming video job creation.\n */\nasync function runCreateVideoJob<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n>(options: VideoCreateOptions<TAdapter, boolean>): Promise<VideoJobResult> {\n const { adapter, prompt, size, duration, modelOptions, middleware } = options\n const model = adapter.model\n const requestId = createId('video')\n const startTime = Date.now()\n const logger: InternalLogger = resolveDebugOption(options.debug)\n const providerName =\n (adapter as { name?: string; provider?: string }).provider ??\n (adapter as { name?: string }).name ??\n 'unknown'\n\n const mwCtx = createGenerationContext({\n requestId,\n activity: 'video',\n provider: adapter.name,\n model,\n modelOptions,\n createId,\n })\n\n await runGenerationStart(middleware, mwCtx)\n\n logger.request(`activity=generateVideo provider=${providerName}`, {\n provider: providerName,\n model,\n })\n\n try {\n const result = await adapter.createVideoJob({\n model,\n prompt,\n size,\n duration,\n modelOptions,\n logger,\n })\n logger.output(`activity=generateVideo jobId=${result.jobId}`, {\n jobId: result.jobId,\n model: result.model,\n })\n // Non-streaming create only submits the job; usage isn't known until the\n // job completes via polling, so the span covers submission only.\n await runGenerationFinish(middleware, mwCtx, {\n duration: Date.now() - startTime,\n })\n return result\n } catch (error) {\n await runGenerationError(middleware, mwCtx, {\n error,\n duration: Date.now() - startTime,\n })\n logger.errors('generateVideo activity failed', {\n error,\n source: 'generateVideo',\n })\n throw error\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n/**\n * Internal streaming implementation for video generation.\n * Handles the full job lifecycle: create job → poll for status → stream updates → yield final result.\n */\nasync function* runStreamingVideoGeneration<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n>(options: VideoCreateOptions<TAdapter, true>): AsyncIterable<StreamChunk> {\n const { adapter, prompt, size, duration, modelOptions, middleware } = options\n const model = adapter.model\n const runId = options.runId ?? createId('run')\n const requestId = createId('video')\n const obsStartTime = Date.now()\n const pollingInterval = options.pollingInterval ?? 2000\n const maxDuration = options.maxDuration ?? 600_000\n const logger: InternalLogger = resolveDebugOption(options.debug)\n const providerName =\n (adapter as { name?: string; provider?: string }).provider ??\n (adapter as { name?: string }).name ??\n 'unknown'\n\n const threadId = createId('thread')\n\n yield {\n type: 'RUN_STARTED',\n runId,\n threadId,\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 createId,\n })\n\n await runGenerationStart(middleware, mwCtx)\n\n logger.request(\n `activity=generateVideo provider=${providerName} stream=true`,\n {\n provider: providerName,\n model,\n },\n )\n\n // Tracks whether a terminal observer event (finish/error) has already fired,\n // so the `finally` below can fire one on abandonment without double-firing.\n let settled = false\n try {\n // Create the video generation job\n const jobResult = await adapter.createVideoJob({\n model,\n prompt,\n size,\n duration,\n modelOptions,\n logger,\n })\n\n yield {\n type: 'CUSTOM',\n name: 'video:job:created',\n value: { jobId: jobResult.jobId },\n timestamp: Date.now(),\n } as StreamChunk\n\n // Poll for completion\n const startTime = Date.now()\n while (Date.now() - startTime < maxDuration) {\n await sleep(pollingInterval)\n\n const statusResult = await adapter.getVideoStatus(jobResult.jobId)\n\n yield {\n type: 'CUSTOM',\n name: 'video:status',\n value: {\n jobId: jobResult.jobId,\n status: statusResult.status,\n progress: statusResult.progress,\n error: statusResult.error,\n },\n timestamp: Date.now(),\n } as StreamChunk\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 // Fire finish before yielding the terminal chunks: the generation has\n // succeeded, so a consumer that stops reading after `generation:result`\n // (without pulling `RUN_FINISHED`) must not trip the abandonment path in\n // `finally`, which would otherwise report a spurious cancellation.\n if (urlResult.usage)\n await runGenerationUsage(middleware, mwCtx, urlResult.usage)\n await runGenerationFinish(middleware, mwCtx, {\n duration: Date.now() - obsStartTime,\n usage: urlResult.usage,\n })\n settled = true\n\n yield {\n type: 'CUSTOM',\n name: 'generation:result',\n value: {\n jobId: jobResult.jobId,\n status: 'completed',\n url: urlResult.url,\n expiresAt: urlResult.expiresAt,\n ...(urlResult.usage ? { usage: urlResult.usage } : {}),\n },\n timestamp: Date.now(),\n } as StreamChunk\n\n yield {\n type: 'RUN_FINISHED',\n runId,\n threadId,\n finishReason: 'stop',\n timestamp: Date.now(),\n } as StreamChunk\n return\n }\n\n if (statusResult.status === 'failed') {\n throw new Error(statusResult.error || 'Video generation failed')\n }\n }\n\n throw new Error('Video generation timed out')\n } catch (error: unknown) {\n const payload = toRunErrorPayload(error, 'Video generation failed')\n // Mark settled before firing onError: if a user error-hook throws, the\n // `finally` below must still not double-fire onAbort over the same op\n // (which would mask the original error and end the span twice).\n settled = true\n await runGenerationError(middleware, mwCtx, {\n error,\n duration: Date.now() - obsStartTime,\n })\n logger.errors('generateVideo activity failed', {\n message: payload.message,\n code: payload.code,\n source: 'generateVideo',\n })\n yield {\n type: 'RUN_ERROR',\n runId,\n threadId,\n message: payload.message,\n code: payload.code,\n error: payload,\n timestamp: Date.now(),\n } as StreamChunk\n } finally {\n if (!settled) {\n // The consumer abandoned the stream (broke the `for await` loop or\n // disconnected) before completion, so the generator is being unwound at\n // a `yield` without reaching finish/error. Fire `onAbort` — a cancel, not\n // an error — so otelMiddleware ends its span instead of leaking it.\n await runGenerationAbort(middleware, mwCtx, {\n reason: 'Video generation stream abandoned before completion',\n duration: Date.now() - obsStartTime,\n })\n }\n }\n}\n\n/**\n * 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 * @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 */\nexport async function getVideoJobStatus<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n>(options: {\n adapter: TAdapter & { kind: typeof kind }\n jobId: string\n}): Promise<{\n status: 'pending' | 'processing' | 'completed' | 'failed'\n progress?: number\n url?: string\n error?: string\n usage?: TokenUsage\n}> {\n const { adapter, jobId } = options\n const requestId = createId('video-status')\n const startTime = Date.now()\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 try {\n const urlResult = await adapter.getVideoUrl(jobId)\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 return {\n status: statusResult.status,\n progress: statusResult.progress,\n url: urlResult.url,\n ...(urlResult.usage ? { usage: urlResult.usage } : {}),\n }\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 return {\n status: 'failed' as const,\n progress: statusResult.progress,\n error: errorMessage,\n }\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 error: statusResult.error,\n duration: Date.now() - startTime,\n timestamp: Date.now(),\n })\n\n // Return status for non-completed jobs\n return {\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"],"names":[],"mappings":";;;;AAuCO,MAAM,OAAO;AA2EpB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AO,aAAa;AAAA,EAAA;AAExB;AASO,SAAS,mBAId,SACuC;AACvC,SAAO;AACT;"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/activities/generateVideo/index.ts"],"sourcesContent":["/**\n * Video Activity (Experimental)\n *\n * Generates videos from text prompts using a jobs/polling architecture.\n * This is a self-contained module with implementation, types, and JSDoc.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\n\nimport { aiEventClient } from '@tanstack/ai-event-client'\nimport { toRunErrorPayload } from '../error-payload'\nimport { resolveDebugOption } from '../../logger/resolve'\nimport {\n applyGenerationResultTransforms,\n createGenerationContext,\n runGenerationAbort,\n runGenerationError,\n runGenerationFinish,\n runGenerationStart,\n runGenerationUsage,\n} from '../middleware/run'\nimport type { InternalLogger } from '../../logger/internal-logger'\nimport type { DebugOption } from '../../logger/types'\nimport type {\n GenerationMiddleware,\n GenerationMiddlewareContext,\n} from '../middleware/types'\nimport type { VideoAdapter } from './adapter'\nimport type {\n MediaPrompt,\n MediaPromptFor,\n PersistedArtifactRef,\n StreamChunk,\n TokenUsage,\n VideoJobResult,\n VideoStatusResult,\n VideoUrlResult,\n} from '../../types'\n\n// ===========================\n// Activity Kind\n// ===========================\n\n/** The adapter kind this activity handles */\nexport const kind = 'video' as const\n\n// ===========================\n// Type Extraction Helpers\n// ===========================\n\n/**\n * Extract provider options from a VideoAdapter via ~types.\n */\nexport type VideoProviderOptions<TAdapter> =\n TAdapter extends VideoAdapter<any, any, any, any, any, any>\n ? TAdapter['~types']['providerOptions']\n : object\n\n/**\n * Extract the size type for a VideoAdapter's model via ~types.\n */\nexport type VideoSizeForAdapter<TAdapter> =\n TAdapter extends VideoAdapter<\n infer TModel,\n any,\n any,\n infer TSizeMap,\n any,\n any\n >\n ? TModel extends keyof TSizeMap\n ? TSizeMap[TModel]\n : string\n : string\n\n/**\n * Extract the prompt type a model accepts from a VideoAdapter via ~types.\n * Mirrors `ImagePromptForModel`: models in the adapter's input-modality map\n * get a `prompt` narrowed to text + their supported part types; adapters\n * without a map fall back to the full MediaPrompt.\n */\nexport type VideoPromptForAdapter<TAdapter> =\n TAdapter extends VideoAdapter<\n infer TModel,\n any,\n any,\n any,\n infer ModsByName,\n any\n >\n ? string extends keyof ModsByName\n ? MediaPrompt\n : TModel extends keyof ModsByName\n ? MediaPromptFor<ModsByName[TModel][number]>\n : MediaPrompt\n : MediaPrompt\n\n/**\n * Extract the duration type for a VideoAdapter's model via ~types.\n * Mirrors `VideoSizeForAdapter`. Falls back to `number` for adapters that\n * haven't declared per-model duration constraints.\n */\nexport type VideoDurationForAdapter<TAdapter> =\n TAdapter extends VideoAdapter<\n infer TModel,\n any,\n any,\n any,\n any,\n infer TDurationMap\n >\n ? TModel extends keyof TDurationMap\n ? TDurationMap[TModel]\n : number\n : number\n\n// ===========================\n// Activity Options Types\n\nfunction createId(prefix: string): string {\n return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`\n}\n// ===========================\n\n/**\n * Base options shared by all video activity operations.\n * The model is extracted from the adapter's model property.\n */\ninterface VideoActivityBaseOptions<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n> {\n /** The video adapter to use (must be created with a model) */\n adapter: TAdapter & { kind: typeof kind }\n}\n\n/**\n * Options for creating a new video generation job.\n * The model is extracted from the adapter's model property.\n *\n * @template TAdapter - The video adapter type\n * @template TStream - Whether to stream the output\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport type VideoCreateOptions<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n TStream extends boolean = false,\n> = VideoActivityBaseOptions<TAdapter> & {\n /** Request type - create a new job (default if not specified) */\n request?: 'create'\n /**\n * Description of the desired video. Either a plain string, or — for models\n * that support image-conditioned generation — an ordered array of content\n * parts interleaving text with image inputs. Image parts may carry\n * `metadata.role` (`'start_frame' | 'end_frame' | 'reference' |\n * 'character'`) to disambiguate intent; positional fallback otherwise. The\n * accepted part types are narrowed per model via the adapter's\n * input-modality map.\n */\n prompt: VideoPromptForAdapter<TAdapter>\n /** Video size — format depends on the provider (e.g., \"16:9\", \"1280x720\") */\n size?: VideoSizeForAdapter<TAdapter>\n /**\n * Video duration in seconds. Adapters that declare a per-model duration\n * map narrow this to the model's valid union (e.g. `4 | 6 | 8` for Veo 3).\n * Pass `adapter.snapDuration(seconds)` to coerce raw seconds to a valid\n * value.\n */\n duration?: VideoDurationForAdapter<TAdapter>\n /**\n * Whether to stream the video generation lifecycle.\n * When true, returns an AsyncIterable<StreamChunk> that handles the full\n * job lifecycle: create job, poll for status, yield updates, and yield final result.\n * When false or not provided, returns a Promise<VideoJobResult>.\n *\n * @default false\n */\n stream?: TStream\n /** Polling interval in milliseconds (stream mode only). @default 2000 */\n pollingInterval?: number\n /** Maximum time to wait before timing out in milliseconds (stream mode only). @default 600000 */\n maxDuration?: number\n /**\n * Custom run id (stream mode only) — the id stamped on the emitted\n * `RUN_STARTED` / `RUN_FINISHED` chunks.\n *\n * IGNORED by a non-streaming submit. That run spans two calls, and its id is\n * derived from the provider's job instead, so {@link getVideoJobStatus} can\n * recompute it from the `jobId` you already have to poll with. Honoring a\n * custom id here would reintroduce the failure this avoids: a caller who set\n * it on the submit and forgot it on the poll would silently open a second\n * record while the first sat unfinished forever.\n */\n runId?: string\n /**\n * Stable conversation/thread id for correlating this run when persisted.\n *\n * Also the `threadId` stamped on the emitted `RUN_STARTED` / `RUN_FINISHED`\n * chunks; when omitted a throwaway id is minted for those chunks only, and\n * the persisted run record carries NO thread link rather than a fabricated\n * one. Pass it whenever persistence is on — it is the slot a reloading client\n * hydrates by, so a run stored without it can only be fetched by run id.\n */\n threadId?: string\n /**\n * Enable debug logging. Pass `true` to enable all categories, `false` to\n * silence everything including errors, or a `DebugConfig` object for granular\n * control and/or a custom `Logger`.\n */\n debug?: DebugOption\n /**\n * Observe-only middleware notified on start, usage, success, and error. Pass\n * `otelMiddleware()` to emit OpenTelemetry spans, `withGenerationPersistence()`\n * to persist the run, or implement the `GenerationMiddleware` contract for a\n * custom backend.\n *\n * In streaming mode one run covers the full create→poll→complete lifecycle:\n * `onStart` at submission, a terminal `onFinish`/`onError` when the job\n * settles, and `onAbort` if the consumer abandons the stream.\n *\n * In NON-streaming mode the call only SUBMITS the job, so it only opens the\n * run: no terminal hook fires here, because the video does not exist yet.\n * Pass the same `middleware` and `threadId` to {@link getVideoJobStatus}; the\n * poll that observes a terminal job state finishes the run and is where the\n * result and its artifacts are recorded. Nothing else has to be threaded\n * through — both calls derive the run id from the provider's `jobId`, the one\n * id a poller cannot be missing.\n *\n * Because the job id only exists once the provider accepts the job, `onStart`\n * fires AFTER the submit request rather than before it — an observer's span\n * therefore covers the run from acceptance onward, not the submit round-trip.\n * A submission that FAILS has no job to key on, so it opens and immediately\n * fails a run under this call's `requestId`: the thread's latest run reports\n * the failure (a client hydrating the slot sees it) even though there is no\n * job to resume.\n */\n middleware?: Array<GenerationMiddleware>\n} & ({} extends VideoProviderOptions<TAdapter>\n ? {\n /** Provider-specific options for video generation */ modelOptions?: VideoProviderOptions<TAdapter>\n }\n : {\n /** Provider-specific options for video generation */ modelOptions: VideoProviderOptions<TAdapter>\n })\n\n/**\n * Options for polling the status of a video generation job.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport interface VideoStatusOptions<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n> extends VideoActivityBaseOptions<TAdapter> {\n /** Request type - get job status */\n request: 'status'\n /** The job ID to check status for */\n jobId: string\n}\n\n/**\n * Options for getting the URL of a completed video.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport interface VideoUrlOptions<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n> extends VideoActivityBaseOptions<TAdapter> {\n /** Request type - get video URL */\n request: 'url'\n /** The job ID to get URL for */\n jobId: string\n}\n\n/**\n * Union type for all video activity options.\n * Discriminated by the `request` field.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport type VideoActivityOptions<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n TRequest extends 'create' | 'status' | 'url' = 'create',\n TStream extends boolean = false,\n> = TRequest extends 'status'\n ? VideoStatusOptions<TAdapter>\n : TRequest extends 'url'\n ? VideoUrlOptions<TAdapter>\n : VideoCreateOptions<TAdapter, TStream>\n\n// ===========================\n// Activity Result Types\n// ===========================\n\n/**\n * Result type for the video activity, based on request type and streaming.\n * - If stream is true (create request): AsyncIterable<StreamChunk>\n * - Otherwise: Promise<VideoJobResult | VideoStatusResult | VideoUrlResult>\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport type VideoActivityResult<\n TRequest extends 'create' | 'status' | 'url' = 'create',\n TStream extends boolean = false,\n> = TRequest extends 'status'\n ? Promise<VideoStatusResult>\n : TRequest extends 'url'\n ? Promise<VideoUrlResult>\n : TStream extends true\n ? AsyncIterable<StreamChunk>\n : Promise<VideoJobResult>\n\n// ===========================\n// Activity Implementation\n// ===========================\n\n/**\n * Generate video - creates a video generation job from a text prompt.\n *\n * Uses AI video generation models to create videos based on natural language descriptions.\n * Unlike image generation, video generation is asynchronous and requires polling for completion.\n *\n * When `stream: true` is passed, handles the full job lifecycle automatically:\n * create job → poll for status → stream updates → yield final result.\n *\n * @experimental Video generation is an experimental feature and may change.\n *\n * @example Create a video generation job\n * ```ts\n * import { generateVideo, getVideoJobStatus } from '@tanstack/ai'\n * import { openaiVideo } from '@tanstack/ai-openai'\n *\n * // Start a video generation job\n * const { jobId } = await generateVideo({\n * adapter: openaiVideo('sora-2'),\n * prompt: 'A cat chasing a dog in a sunny park'\n * })\n *\n * console.log('Job started:', jobId)\n *\n * // The submission only OPENS the run; the poll that sees a terminal state is\n * // what completes it. The `jobId` is the whole correlation — pass the same\n * // `middleware` and `threadId` when you use them.\n * const status = await getVideoJobStatus({\n * adapter: openaiVideo('sora-2'),\n * jobId,\n * })\n * ```\n *\n * @example Stream the full video generation lifecycle\n * ```ts\n * import { generateVideo, toServerSentEventsResponse } from '@tanstack/ai'\n * import { openaiVideo } from '@tanstack/ai-openai'\n *\n * const stream = generateVideo({\n * adapter: openaiVideo('sora-2'),\n * prompt: 'A cat chasing a dog in a sunny park',\n * stream: true,\n * pollingInterval: 3000,\n * })\n *\n * return toServerSentEventsResponse(stream)\n * ```\n */\nexport function generateVideo<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n TStream extends boolean = false,\n>(\n options: VideoCreateOptions<TAdapter, TStream>,\n): VideoActivityResult<'create', TStream> {\n if (options.stream) {\n return runStreamingVideoGeneration(\n options as VideoCreateOptions<TAdapter, true>,\n ) as VideoActivityResult<'create', TStream>\n }\n\n return runCreateVideoJob(options) as VideoActivityResult<'create', TStream>\n}\n\n/**\n * The run id a non-streaming video job is filed under, derived from the\n * provider job itself.\n *\n * A submit-and-poll run spans two calls in two different requests, so the two\n * halves need to agree on an id. Deriving it from the `jobId` — the one id a\n * poller structurally cannot be missing, because it cannot poll without it —\n * means no correlation state has to survive the boundary and there is no\n * \"forgot to pass the run id\" failure to document. The provider is part of the\n * key so two providers' job-id spaces cannot collide, and both halves are\n * percent-encoded so the joined string stays unambiguous (and url-safe, since\n * run ids end up in storage keys and query strings).\n */\nfunction videoRunIdForJob(provider: string, jobId: string): string {\n return `video:${encodeURIComponent(provider)}:${encodeURIComponent(jobId)}`\n}\n\n/**\n * Internal implementation of non-streaming video job creation.\n *\n * Submitting a job OPENS a run, it does not complete one: the video does not\n * exist yet, and the bytes only appear on a later poll. So this fires `onStart`\n * and runs the result transforms over the submission result — the jobId lands\n * on the run record, which is what lets a later request resume polling — but\n * fires NO terminal hook. {@link getVideoJobStatus} finishes the run when the\n * job settles, keyed on the same derived id.\n *\n * `onStart` therefore runs AFTER the submit request: the run's id comes from\n * the job, which does not exist until the provider accepts it. A submission\n * that fails has no job, so it opens and immediately fails a run under this\n * call's `requestId` — terminal and unresumable by construction, but it puts\n * the failure where a client hydrating the thread will see it instead of\n * showing nothing.\n */\nasync function runCreateVideoJob<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n>(options: VideoCreateOptions<TAdapter, boolean>): Promise<VideoJobResult> {\n const { adapter, prompt, size, duration, modelOptions, middleware } = options\n const model = adapter.model\n const requestId = createId('video')\n const startTime = Date.now()\n const logger: InternalLogger = resolveDebugOption(options.debug)\n const providerName =\n (adapter as { name?: string; provider?: string }).provider ??\n (adapter as { name?: string }).name ??\n 'unknown'\n\n // `runId` is resolved per outcome (from the job, or absent on failure), so the\n // context is built once the outcome is known. `options.runId` is deliberately\n // not consulted: in non-streaming mode the run id is always the derived one,\n // the single rule that keeps the two calls in agreement.\n const contextFor = (runId?: string): GenerationMiddlewareContext =>\n createGenerationContext({\n requestId,\n activity: 'video',\n provider: adapter.name,\n model,\n modelOptions,\n // Deliberately the CALLER's `threadId` — no minted fallback. A thread id\n // nobody else knows would file the run in a slot no client could hydrate,\n // which is worse than no link because it looks like one. Mirrors the\n // streaming path.\n threadId: options.threadId,\n runId,\n artifactInputs: { prompt },\n createId,\n })\n\n logger.request(`activity=generateVideo provider=${providerName}`, {\n provider: providerName,\n model,\n })\n\n let jobResult: VideoJobResult\n try {\n jobResult = await adapter.createVideoJob({\n model,\n prompt,\n size,\n duration,\n modelOptions,\n logger,\n })\n } catch (error) {\n // No jobId exists, so this run can only be keyed on the request. Start it\n // just to fail it: `generationRuns.update` on an unknown run id is a no-op\n // by contract, so without the `onStart` the failure would persist nowhere.\n const failedCtx = contextFor()\n await runGenerationStart(middleware, failedCtx)\n await runGenerationError(middleware, failedCtx, {\n error,\n duration: Date.now() - startTime,\n })\n logger.errors('generateVideo activity failed', {\n error,\n source: 'generateVideo',\n })\n throw error\n }\n\n logger.output(`activity=generateVideo jobId=${jobResult.jobId}`, {\n jobId: jobResult.jobId,\n model: jobResult.model,\n })\n\n const mwCtx = contextFor(videoRunIdForJob(adapter.name, jobResult.jobId))\n await runGenerationStart(middleware, mwCtx)\n // Transforms see the submission result (no url yet, so nothing to copy into a\n // blob store) purely so the run record captures the jobId and any prompt\n // inputs. No finish hook: the run is still running.\n return await applyGenerationResultTransforms(mwCtx, jobResult)\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n/**\n * Internal streaming implementation for video generation.\n * Handles the full job lifecycle: create job → poll for status → stream updates → yield final result.\n */\nasync function* runStreamingVideoGeneration<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n>(options: VideoCreateOptions<TAdapter, true>): AsyncIterable<StreamChunk> {\n const { adapter, prompt, size, duration, modelOptions, middleware } = options\n const model = adapter.model\n const runId = options.runId ?? createId('run')\n const requestId = createId('video')\n const obsStartTime = Date.now()\n const pollingInterval = options.pollingInterval ?? 2000\n const maxDuration = options.maxDuration ?? 600_000\n const logger: InternalLogger = resolveDebugOption(options.debug)\n const providerName =\n (adapter as { name?: string; provider?: string }).provider ??\n (adapter as { name?: string }).name ??\n 'unknown'\n\n // The wire needs a thread id on every RUN_* chunk, so one is minted when the\n // caller passes none — matching `streamGenerationResult`, which the other\n // activities stream through.\n const wireThreadId = options.threadId ?? createId('thread')\n\n yield {\n type: 'RUN_STARTED',\n runId,\n threadId: wireThreadId,\n timestamp: Date.now(),\n } as StreamChunk\n\n const mwCtx = createGenerationContext({\n requestId,\n activity: 'video',\n provider: adapter.name,\n model,\n modelOptions,\n // Identity has to reach the middleware, not just the chunks: persistence\n // keys the run record on these, and without them it falls back to the\n // internal `requestId` and records no thread link at all.\n //\n // Deliberately the CALLER's `threadId`, never `wireThreadId`: a minted id is\n // known to nobody, so persisting it would file the run in a slot no client\n // could ever hydrate — worse than recording no link, because it looks like\n // one. This mirrors `generateImage`.\n threadId: options.threadId,\n runId,\n artifactInputs: { prompt },\n createId,\n })\n\n await runGenerationStart(middleware, mwCtx)\n\n logger.request(\n `activity=generateVideo provider=${providerName} stream=true`,\n {\n provider: providerName,\n model,\n },\n )\n\n // Tracks whether a terminal observer event (finish/error) has already fired,\n // so the `finally` below can fire one on abandonment without double-firing.\n let settled = false\n try {\n // Create the video generation job\n const jobResult = await adapter.createVideoJob({\n model,\n prompt,\n size,\n duration,\n modelOptions,\n logger,\n })\n\n yield {\n type: 'CUSTOM',\n name: 'video:job:created',\n value: { jobId: jobResult.jobId },\n timestamp: Date.now(),\n }\n\n // Poll for completion\n const startTime = Date.now()\n while (Date.now() - startTime < maxDuration) {\n await sleep(pollingInterval)\n\n const statusResult = await adapter.getVideoStatus(jobResult.jobId)\n\n yield {\n type: 'CUSTOM',\n name: 'video:status',\n value: {\n jobId: jobResult.jobId,\n status: statusResult.status,\n progress: statusResult.progress,\n error: statusResult.error,\n },\n timestamp: Date.now(),\n }\n\n if (statusResult.status === 'completed') {\n const urlResult = await adapter.getVideoUrl(jobResult.jobId)\n\n logger.output(\n `activity=generateVideo jobId=${jobResult.jobId} status=completed`,\n {\n jobId: jobResult.jobId,\n url: urlResult.url,\n },\n )\n\n // Run the result transforms before anything observes the result, the\n // same as every other media activity. This is what lets persistence\n // copy the video into a blob store, attach its artifact refs, and\n // rewrite `url` to a durable app-origin one — so the chunk below and\n // the stored run record carry the SAME urls. Skipping it leaves a\n // result whose only url is the provider's expiring link.\n const rawResult = {\n jobId: jobResult.jobId,\n status: 'completed' as const,\n url: urlResult.url,\n expiresAt: urlResult.expiresAt,\n ...(urlResult.usage ? { usage: urlResult.usage } : {}),\n }\n const result = await applyGenerationResultTransforms(mwCtx, rawResult)\n\n // Fire finish before yielding the terminal chunks: the generation has\n // succeeded, so a consumer that stops reading after `generation:result`\n // (without pulling `RUN_FINISHED`) must not trip the abandonment path in\n // `finally`, which would otherwise report a spurious cancellation.\n if (urlResult.usage)\n await runGenerationUsage(middleware, mwCtx, urlResult.usage)\n await runGenerationFinish(middleware, mwCtx, {\n duration: Date.now() - obsStartTime,\n usage: urlResult.usage,\n })\n settled = true\n\n yield {\n type: 'CUSTOM',\n name: 'generation:result',\n value: result,\n timestamp: Date.now(),\n }\n\n yield {\n type: 'RUN_FINISHED',\n runId,\n threadId: wireThreadId,\n finishReason: 'stop',\n timestamp: Date.now(),\n } as StreamChunk\n return\n }\n\n if (statusResult.status === 'failed') {\n throw new Error(statusResult.error || 'Video generation failed')\n }\n }\n\n throw new Error('Video generation timed out')\n } catch (error: unknown) {\n const payload = toRunErrorPayload(error, 'Video generation failed')\n // Mark settled before firing onError: if a user error-hook throws, the\n // `finally` below must still not double-fire onAbort over the same op\n // (which would mask the original error and end the span twice).\n settled = true\n await runGenerationError(middleware, mwCtx, {\n error,\n duration: Date.now() - obsStartTime,\n })\n logger.errors('generateVideo activity failed', {\n message: payload.message,\n code: payload.code,\n source: 'generateVideo',\n })\n yield {\n type: 'RUN_ERROR',\n runId,\n threadId: wireThreadId,\n message: payload.message,\n code: payload.code,\n error: payload,\n timestamp: Date.now(),\n } as StreamChunk\n } finally {\n if (!settled) {\n // The consumer abandoned the stream (broke the `for await` loop or\n // disconnected) before completion, so the generator is being unwound at\n // a `yield` without reaching finish/error. Fire `onAbort` — a cancel, not\n // an error — so otelMiddleware ends its span instead of leaking it.\n await runGenerationAbort(middleware, mwCtx, {\n reason: 'Video generation stream abandoned before completion',\n duration: Date.now() - obsStartTime,\n })\n }\n }\n}\n\n/**\n * Options for {@link getVideoJobStatus}.\n *\n * The run this poll finishes is identified by `adapter` + `jobId` alone — the\n * same pair the submitting `generateVideo()` call derived it from — so there is\n * no run id to thread through. Pass the submission's `threadId` and the same\n * `middleware`.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport interface VideoJobStatusOptions<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n> {\n /** The video adapter to use (must be created with a model) */\n adapter: TAdapter & { kind: typeof kind }\n /** The job ID to check status for */\n jobId: string\n /**\n * The scope the run is filed under. Must match the submission's `threadId` —\n * generation persistence REFUSES a run without a scope (a run filed under\n * none can never be hydrated by one), so omitting it throws rather than\n * quietly filing the finished video somewhere unreachable.\n */\n threadId?: string\n /**\n * Observe-only middleware. Hooks fire ONLY on the poll that observes a\n * terminal job state: `onStart` (resuming the submission's run), then the\n * result transforms — which is where persistence copies the video into a blob\n * store and rewrites `url` to a durable one, so the returned result carries\n * the same urls as the stored record — then `onFinish`, or `onError` when the\n * job failed. Intermediate polls invoke nothing, so a middleware is not\n * charged for the wait.\n */\n middleware?: Array<GenerationMiddleware>\n}\n\n/**\n * The status of a video job, plus the video itself once the job completed.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport interface VideoJobStatusResult {\n /** Job identifier */\n jobId: string\n status: 'pending' | 'processing' | 'completed' | 'failed'\n progress?: number\n url?: string\n /** When the provider url expires, if it reported one. */\n expiresAt?: Date\n error?: string\n usage?: TokenUsage\n /** Durable artifact references, when generation persistence is wired. */\n artifacts?: Array<PersistedArtifactRef>\n}\n\n/**\n * Get video job status - returns the current status, progress, and URL if available.\n *\n * This function combines status checking and URL retrieval. If the job is completed,\n * it will automatically fetch and include the video URL.\n *\n * It is also where a non-streaming `generateVideo()` run ENDS: pass the same\n * `middleware` and `threadId`, and the poll that first sees a terminal job state\n * finishes the run (recording the result and its artifacts) or fails it. The run\n * is identified by `adapter` + `jobId`, exactly what the submission derived it\n * from, so there is nothing else to carry between the two calls.\n *\n * @experimental Video generation is an experimental feature and may change.\n *\n * @example Check job status\n * ```ts\n * import { getVideoJobStatus } from '@tanstack/ai'\n * import { openaiVideo } from '@tanstack/ai-openai'\n *\n * const result = await getVideoJobStatus({\n * adapter: openaiVideo('sora-2'),\n * jobId: 'job-123'\n * })\n *\n * console.log('Status:', result.status)\n * console.log('Progress:', result.progress)\n * if (result.url) {\n * console.log('Video URL:', result.url)\n * }\n * ```\n *\n * @example Submit and poll one persisted run\n * ```ts\n * import { generateVideo, getVideoJobStatus } from '@tanstack/ai'\n * import { withGenerationPersistence } from '@tanstack/ai-persistence'\n * import { openaiVideo } from '@tanstack/ai-openai'\n *\n * const adapter = openaiVideo('sora-2')\n * const middleware = [withGenerationPersistence(persistence)]\n *\n * // Opens the run (status `running`, jobId recorded). Its run id is derived\n * // from the provider job, so nothing has to be stored to resume it.\n * const { jobId } = await generateVideo({\n * adapter,\n * prompt: 'A cat chasing a dog in a sunny park',\n * threadId,\n * middleware,\n * })\n *\n * // Completes the SAME run once the job settles — this is what writes the\n * // video, its artifacts, and the terminal status. Works from a different\n * // request or process: the jobId is the only correlation.\n * const status = await getVideoJobStatus({\n * adapter,\n * jobId,\n * threadId,\n * middleware,\n * })\n * ```\n */\nexport async function getVideoJobStatus<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n>(options: VideoJobStatusOptions<TAdapter>): Promise<VideoJobStatusResult> {\n const { adapter, jobId, middleware } = options\n const requestId = createId('video-status')\n const startTime = Date.now()\n\n // Built per call but only USED on a terminal poll — `onStart` is what\n // registers the result transforms, so it has to run in the same call that\n // applies them.\n const terminalContext = (): GenerationMiddlewareContext =>\n createGenerationContext({\n requestId,\n activity: 'video',\n provider: adapter.name,\n model: adapter.model,\n threadId: options.threadId,\n // Recomputed, never passed in: the submitting call derived the same id\n // from the same provider + job, so the two halves agree without the\n // caller carrying anything but the jobId they must already have.\n runId: videoRunIdForJob(adapter.name, jobId),\n // Deliberately no `artifactInputs`: the submission already persisted any\n // prompt inputs under this run, and passing them again would store a\n // second copy of every input image.\n createId,\n })\n\n aiEventClient.emit('video:request:started', {\n requestId,\n provider: adapter.name,\n model: adapter.model,\n requestType: 'status',\n jobId,\n timestamp: startTime,\n })\n\n // Get status first\n const statusResult = await adapter.getVideoStatus(jobId)\n\n // If completed, also get the URL\n if (statusResult.status === 'completed') {\n let urlResult: VideoUrlResult\n // Scoped tightly to the provider call: a middleware hook that throws must\n // surface as itself, not be relabelled \"failed to get video URL\" and then\n // re-reported to the very middleware that threw.\n try {\n urlResult = await adapter.getVideoUrl(jobId)\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : 'Failed to get video URL'\n aiEventClient.emit('video:request:completed', {\n requestId,\n provider: adapter.name,\n model: adapter.model,\n requestType: 'status',\n jobId,\n status: 'failed',\n progress: statusResult.progress,\n error: errorMessage,\n duration: Date.now() - startTime,\n timestamp: Date.now(),\n })\n // Provider reported completed but result fetch failed — treat as failed,\n // and fail the run with it: the job is terminal, so nothing later will.\n await runGenerationError(middleware, terminalContext(), {\n error,\n duration: Date.now() - startTime,\n })\n return {\n jobId,\n status: 'failed' as const,\n progress: statusResult.progress,\n error: errorMessage,\n }\n }\n\n aiEventClient.emit('video:request:completed', {\n requestId,\n provider: adapter.name,\n model: adapter.model,\n requestType: 'status',\n jobId,\n status: statusResult.status,\n progress: statusResult.progress,\n url: urlResult.url,\n duration: Date.now() - startTime,\n timestamp: Date.now(),\n })\n if (urlResult.usage) {\n aiEventClient.emit('video:usage', {\n requestId,\n model: adapter.model,\n usage: urlResult.usage,\n timestamp: Date.now(),\n })\n }\n\n const mwCtx = terminalContext()\n await runGenerationStart(middleware, mwCtx)\n const result = await applyGenerationResultTransforms<VideoJobStatusResult>(\n mwCtx,\n {\n jobId,\n status: 'completed',\n ...(statusResult.progress !== undefined\n ? { progress: statusResult.progress }\n : {}),\n url: urlResult.url,\n ...(urlResult.expiresAt ? { expiresAt: urlResult.expiresAt } : {}),\n ...(urlResult.usage ? { usage: urlResult.usage } : {}),\n },\n )\n if (urlResult.usage)\n await runGenerationUsage(middleware, mwCtx, urlResult.usage)\n await runGenerationFinish(middleware, mwCtx, {\n duration: Date.now() - startTime,\n usage: urlResult.usage,\n })\n return result\n }\n\n aiEventClient.emit('video:request:completed', {\n requestId,\n provider: adapter.name,\n model: adapter.model,\n requestType: 'status',\n jobId,\n status: statusResult.status,\n progress: statusResult.progress,\n error: statusResult.error,\n duration: Date.now() - startTime,\n timestamp: Date.now(),\n })\n\n // A failed job is terminal for the run too: without this the record would sit\n // at `running` forever, indistinguishable from a job still being worked on.\n if (statusResult.status === 'failed') {\n await runGenerationError(middleware, terminalContext(), {\n error: new Error(statusResult.error || 'Video generation failed'),\n duration: Date.now() - startTime,\n })\n }\n\n // Return status for non-completed jobs\n return {\n jobId,\n status: statusResult.status,\n progress: statusResult.progress,\n error: statusResult.error,\n }\n}\n\n// ===========================\n// Options Factory\n// ===========================\n\n/**\n * Create typed options for the generateVideo() function without executing.\n */\nexport function createVideoOptions<\n TAdapter extends VideoAdapter<string, any, any, any, any, any>,\n TStream extends boolean = false,\n>(\n options: VideoCreateOptions<TAdapter, TStream>,\n): VideoCreateOptions<TAdapter, TStream> {\n return options\n}\n\n// Re-export adapter types\nexport type {\n VideoAdapter,\n VideoAdapterConfig,\n AnyVideoAdapter,\n} from './adapter'\nexport { BaseVideoAdapter } from './adapter'\n"],"mappings":";;;;;;;;;;;;;;;AA4CA,IAAa,OAAO;AA2EpB,SAAS,SAAS,QAAwB;CACxC,OAAO,GAAG,OAAO,GAAG,KAAK,IAAI,EAAE,GAAG,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC;AACzE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkPA,SAAgB,cAId,SACwC;CACxC,IAAI,QAAQ,QACV,OAAO,4BACL,OACF;CAGF,OAAO,kBAAkB,OAAO;AAClC;;;;;;;;;;;;;;AAeA,SAAS,iBAAiB,UAAkB,OAAuB;CACjE,OAAO,SAAS,mBAAmB,QAAQ,EAAE,GAAG,mBAAmB,KAAK;AAC1E;;;;;;;;;;;;;;;;;;AAmBA,eAAe,kBAEb,SAAyE;CACzE,MAAM,EAAE,SAAS,QAAQ,MAAM,UAAU,cAAc,eAAe;CACtE,MAAM,QAAQ,QAAQ;CACtB,MAAM,YAAY,SAAS,OAAO;CAClC,MAAM,YAAY,KAAK,IAAI;CAC3B,MAAM,SAAyB,mBAAmB,QAAQ,KAAK;CAC/D,MAAM,eACH,QAAiD,YACjD,QAA8B,QAC/B;CAMF,MAAM,cAAc,UAClB,wBAAwB;EACtB;EACA,UAAU;EACV,UAAU,QAAQ;EAClB;EACA;EAKA,UAAU,QAAQ;EAClB;EACA,gBAAgB,EAAE,OAAO;EACzB;CACF,CAAC;CAEH,OAAO,QAAQ,mCAAmC,gBAAgB;EAChE,UAAU;EACV;CACF,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C,UAAU,KAAK,IAAI,IAAI;GACvB,OAAO,UAAU;EACnB,CAAC;EACD,OAAO;CACT;CAEA,cAAc,KAAK,2BAA2B;EAC5C;EACA,UAAU,QAAQ;EAClB,OAAO,QAAQ;EACf,aAAa;EACb;EACA,QAAQ,aAAa;EACrB,UAAU,aAAa;EACvB,OAAO,aAAa;EACpB,UAAU,KAAK,IAAI,IAAI;EACvB,WAAW,KAAK,IAAI;CACtB,CAAC;CAID,IAAI,aAAa,WAAW,UAC1B,MAAM,mBAAmB,YAAY,gBAAgB,GAAG;EACtD,OAAO,IAAI,MAAM,aAAa,SAAS,yBAAyB;EAChE,UAAU,KAAK,IAAI,IAAI;CACzB,CAAC;CAIH,OAAO;EACL;EACA,QAAQ,aAAa;EACrB,UAAU,aAAa;EACvB,OAAO,aAAa;CACtB;AACF;;;;AASA,SAAgB,mBAId,SACuC;CACvC,OAAO;AACT"}
|
|
@@ -1,54 +1,66 @@
|
|
|
1
|
+
//#region src/activities/generateVideo/snap.ts
|
|
2
|
+
/**
|
|
3
|
+
* Extract a numeric seconds value from a `DurationOptions` entry. Returns
|
|
4
|
+
* `null` for entries that don't parse as a number — e.g. `'auto'`.
|
|
5
|
+
*
|
|
6
|
+
* Handles the keyword-with-unit form FAL uses for Luma/Veo (`'8s'`, `'9s'`)
|
|
7
|
+
* by stripping a trailing `s`. Pure-numeric strings (`'5'`, `'10'`) parse via
|
|
8
|
+
* Number(). Numbers pass through.
|
|
9
|
+
*/
|
|
1
10
|
function entryToSeconds(entry) {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
const parsed = Number(stripped);
|
|
7
|
-
return Number.isFinite(parsed) ? parsed : null;
|
|
11
|
+
if (typeof entry === "number") return Number.isFinite(entry) ? entry : null;
|
|
12
|
+
const stripped = entry.endsWith("s") ? entry.slice(0, -1) : entry;
|
|
13
|
+
const parsed = Number(stripped);
|
|
14
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
8
15
|
}
|
|
16
|
+
/**
|
|
17
|
+
* Snap a raw seconds value to the closest valid duration for a model's
|
|
18
|
+
* `DurationOptions`.
|
|
19
|
+
*
|
|
20
|
+
* - `none` → `undefined`
|
|
21
|
+
* - `discrete` → closest numeric-parseable entry; if none parse,
|
|
22
|
+
* returns `values[0]` (keyword-only models like 'auto')
|
|
23
|
+
* - `range` → clamped to [min, max] and rounded to `step` (default 1)
|
|
24
|
+
* - `mixed` → closest of (discrete numerics ∪ range values)
|
|
25
|
+
*
|
|
26
|
+
* @experimental Video generation is an experimental feature and may change.
|
|
27
|
+
*/
|
|
9
28
|
function snapToDurationOption(seconds, options) {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
max,
|
|
29
|
-
Math.max(min, Math.round((clamped - min) / step) * step + min)
|
|
30
|
-
);
|
|
31
|
-
const discreteSeconds = typeof discreteCandidate === "number" ? discreteCandidate : discreteCandidate !== void 0 ? entryToSeconds(discreteCandidate) ?? Infinity : Infinity;
|
|
32
|
-
return Math.abs(discreteSeconds - seconds) <= Math.abs(rangeValue - seconds) ? discreteCandidate : rangeValue;
|
|
33
|
-
}
|
|
34
|
-
}
|
|
29
|
+
switch (options.kind) {
|
|
30
|
+
case "none": return;
|
|
31
|
+
case "discrete": return pickClosestDiscrete(seconds, options.values);
|
|
32
|
+
case "range": {
|
|
33
|
+
const step = options.step ?? 1;
|
|
34
|
+
const clamped = Math.min(options.max, Math.max(options.min, seconds));
|
|
35
|
+
const snapped = Math.round((clamped - options.min) / step) * step + options.min;
|
|
36
|
+
return Math.min(options.max, Math.max(options.min, snapped));
|
|
37
|
+
}
|
|
38
|
+
case "mixed": {
|
|
39
|
+
const discreteCandidate = pickClosestDiscrete(seconds, options.values);
|
|
40
|
+
if (!options.range) return discreteCandidate;
|
|
41
|
+
const { min, max, step = 1 } = options.range;
|
|
42
|
+
const rangeValue = Math.min(max, Math.max(min, Math.round((Math.min(max, Math.max(min, seconds)) - min) / step) * step + min));
|
|
43
|
+
const discreteSeconds = typeof discreteCandidate === "number" ? discreteCandidate : discreteCandidate !== void 0 ? entryToSeconds(discreteCandidate) ?? Infinity : Infinity;
|
|
44
|
+
return Math.abs(discreteSeconds - seconds) <= Math.abs(rangeValue - seconds) ? discreteCandidate : rangeValue;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
35
47
|
}
|
|
36
48
|
function pickClosestDiscrete(seconds, values) {
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
49
|
+
if (values.length === 0) return void 0;
|
|
50
|
+
let best;
|
|
51
|
+
let bestDistance = Infinity;
|
|
52
|
+
for (const value of values) {
|
|
53
|
+
const v = entryToSeconds(value);
|
|
54
|
+
if (v === null) continue;
|
|
55
|
+
const distance = Math.abs(v - seconds);
|
|
56
|
+
if (distance < bestDistance) {
|
|
57
|
+
bestDistance = distance;
|
|
58
|
+
best = value;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return best ?? values[0];
|
|
50
62
|
}
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
//# sourceMappingURL=snap.js.map
|
|
63
|
+
//#endregion
|
|
64
|
+
export { snapToDurationOption };
|
|
65
|
+
|
|
66
|
+
//# sourceMappingURL=snap.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"snap.js","sources":["../../../../src/activities/generateVideo/snap.ts"],"sourcesContent":["import type { DurationOptions } from './adapter'\n\n/**\n * Extract a numeric seconds value from a `DurationOptions` entry. Returns\n * `null` for entries that don't parse as a number — e.g. `'auto'`.\n *\n * Handles the keyword-with-unit form FAL uses for Luma/Veo (`'8s'`, `'9s'`)\n * by stripping a trailing `s`. Pure-numeric strings (`'5'`, `'10'`) parse via\n * Number(). Numbers pass through.\n */\nfunction entryToSeconds(entry: string | number): number | null {\n if (typeof entry === 'number') {\n return Number.isFinite(entry) ? entry : null\n }\n const stripped = entry.endsWith('s') ? entry.slice(0, -1) : entry\n const parsed = Number(stripped)\n return Number.isFinite(parsed) ? parsed : null\n}\n\n/**\n * Snap a raw seconds value to the closest valid duration for a model's\n * `DurationOptions`.\n *\n * - `none` → `undefined`\n * - `discrete` → closest numeric-parseable entry; if none parse,\n * returns `values[0]` (keyword-only models like 'auto')\n * - `range` → clamped to [min, max] and rounded to `step` (default 1)\n * - `mixed` → closest of (discrete numerics ∪ range values)\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport function snapToDurationOption<T extends string | number | undefined>(\n seconds: number,\n options: DurationOptions<T>,\n): T | undefined {\n switch (options.kind) {\n case 'none':\n return undefined\n\n case 'discrete': {\n return pickClosestDiscrete(seconds, options.values)\n }\n\n case 'range': {\n const step = options.step ?? 1\n const clamped = Math.min(options.max, Math.max(options.min, seconds))\n const snapped =\n Math.round((clamped - options.min) / step) * step + options.min\n return Math.min(options.max, Math.max(options.min, snapped)) as T\n }\n\n case 'mixed': {\n const discreteCandidate = pickClosestDiscrete(seconds, options.values)\n if (!options.range) return discreteCandidate\n\n const { min, max, step = 1 } = options.range\n const clamped = Math.min(max, Math.max(min, seconds))\n const rangeValue = Math.min(\n max,\n Math.max(min, Math.round((clamped - min) / step) * step + min),\n )\n\n // Compare distance; range value is numeric, discrete may have non-numeric\n // first-entry fallback (return distance Infinity for non-numerics).\n const discreteSeconds =\n typeof discreteCandidate === 'number'\n ? discreteCandidate\n : discreteCandidate !== undefined\n ? (entryToSeconds(discreteCandidate) ?? Infinity)\n : Infinity\n\n return Math.abs(discreteSeconds - seconds) <=\n Math.abs(rangeValue - seconds)\n ? discreteCandidate\n : (rangeValue as T)\n }\n }\n}\n\nfunction pickClosestDiscrete<T extends string | number>(\n seconds: number,\n values: ReadonlyArray<T>,\n): T | undefined {\n if (values.length === 0) return undefined\n\n let best: T | undefined\n let bestDistance = Infinity\n for (const value of values) {\n const v = entryToSeconds(value)\n if (v === null) continue\n const distance = Math.abs(v - seconds)\n if (distance < bestDistance) {\n bestDistance = distance\n best = value\n }\n }\n\n // Keyword-only set (no numeric-parseable entries) — fall back to first entry.\n return best ?? values[0]\n}\n"],"
|
|
1
|
+
{"version":3,"file":"snap.js","names":[],"sources":["../../../../src/activities/generateVideo/snap.ts"],"sourcesContent":["import type { DurationOptions } from './adapter'\n\n/**\n * Extract a numeric seconds value from a `DurationOptions` entry. Returns\n * `null` for entries that don't parse as a number — e.g. `'auto'`.\n *\n * Handles the keyword-with-unit form FAL uses for Luma/Veo (`'8s'`, `'9s'`)\n * by stripping a trailing `s`. Pure-numeric strings (`'5'`, `'10'`) parse via\n * Number(). Numbers pass through.\n */\nfunction entryToSeconds(entry: string | number): number | null {\n if (typeof entry === 'number') {\n return Number.isFinite(entry) ? entry : null\n }\n const stripped = entry.endsWith('s') ? entry.slice(0, -1) : entry\n const parsed = Number(stripped)\n return Number.isFinite(parsed) ? parsed : null\n}\n\n/**\n * Snap a raw seconds value to the closest valid duration for a model's\n * `DurationOptions`.\n *\n * - `none` → `undefined`\n * - `discrete` → closest numeric-parseable entry; if none parse,\n * returns `values[0]` (keyword-only models like 'auto')\n * - `range` → clamped to [min, max] and rounded to `step` (default 1)\n * - `mixed` → closest of (discrete numerics ∪ range values)\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport function snapToDurationOption<T extends string | number | undefined>(\n seconds: number,\n options: DurationOptions<T>,\n): T | undefined {\n switch (options.kind) {\n case 'none':\n return undefined\n\n case 'discrete': {\n return pickClosestDiscrete(seconds, options.values)\n }\n\n case 'range': {\n const step = options.step ?? 1\n const clamped = Math.min(options.max, Math.max(options.min, seconds))\n const snapped =\n Math.round((clamped - options.min) / step) * step + options.min\n return Math.min(options.max, Math.max(options.min, snapped)) as T\n }\n\n case 'mixed': {\n const discreteCandidate = pickClosestDiscrete(seconds, options.values)\n if (!options.range) return discreteCandidate\n\n const { min, max, step = 1 } = options.range\n const clamped = Math.min(max, Math.max(min, seconds))\n const rangeValue = Math.min(\n max,\n Math.max(min, Math.round((clamped - min) / step) * step + min),\n )\n\n // Compare distance; range value is numeric, discrete may have non-numeric\n // first-entry fallback (return distance Infinity for non-numerics).\n const discreteSeconds =\n typeof discreteCandidate === 'number'\n ? discreteCandidate\n : discreteCandidate !== undefined\n ? (entryToSeconds(discreteCandidate) ?? Infinity)\n : Infinity\n\n return Math.abs(discreteSeconds - seconds) <=\n Math.abs(rangeValue - seconds)\n ? discreteCandidate\n : (rangeValue as T)\n }\n }\n}\n\nfunction pickClosestDiscrete<T extends string | number>(\n seconds: number,\n values: ReadonlyArray<T>,\n): T | undefined {\n if (values.length === 0) return undefined\n\n let best: T | undefined\n let bestDistance = Infinity\n for (const value of values) {\n const v = entryToSeconds(value)\n if (v === null) continue\n const distance = Math.abs(v - seconds)\n if (distance < bestDistance) {\n bestDistance = distance\n best = value\n }\n }\n\n // Keyword-only set (no numeric-parseable entries) — fall back to first entry.\n return best ?? values[0]\n}\n"],"mappings":";;;;;;;;;AAUA,SAAS,eAAe,OAAuC;CAC7D,IAAI,OAAO,UAAU,UACnB,OAAO,OAAO,SAAS,KAAK,IAAI,QAAQ;CAE1C,MAAM,WAAW,MAAM,SAAS,GAAG,IAAI,MAAM,MAAM,GAAG,EAAE,IAAI;CAC5D,MAAM,SAAS,OAAO,QAAQ;CAC9B,OAAO,OAAO,SAAS,MAAM,IAAI,SAAS;AAC5C;;;;;;;;;;;;;AAcA,SAAgB,qBACd,SACA,SACe;CACf,QAAQ,QAAQ,MAAhB;EACE,KAAK,QACH;EAEF,KAAK,YACH,OAAO,oBAAoB,SAAS,QAAQ,MAAM;EAGpD,KAAK,SA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at, kind as kind$3 } from "./chat/index.js";
|
|
4
3
|
import { BaseSummarizeAdapter } from "./summarize/adapter.js";
|
|
5
4
|
import { ChatStreamSummarizeAdapter } from "./summarize/chat-stream-summarize.js";
|
|
6
|
-
import {
|
|
5
|
+
import { kind as kind$2, summarize } from "./summarize/index.js";
|
|
7
6
|
import { BaseImageAdapter } from "./generateImage/adapter.js";
|
|
8
|
-
import { kind as
|
|
7
|
+
import { generateImage, kind as kind$1 } from "./generateImage/index.js";
|
|
9
8
|
import { BaseAudioAdapter } from "./generateAudio/adapter.js";
|
|
10
|
-
import {
|
|
9
|
+
import { generateAudio, kind } from "./generateAudio/index.js";
|
|
11
10
|
import { BaseVideoAdapter } from "./generateVideo/adapter.js";
|
|
11
|
+
import { generateVideo, getVideoJobStatus, kind as kind$6 } from "./generateVideo/index.js";
|
|
12
12
|
import { snapToDurationOption } from "./generateVideo/snap.js";
|
|
13
|
-
import { generateSpeech, kind as kind6 } from "./generateSpeech/index.js";
|
|
14
13
|
import { BaseTTSAdapter } from "./generateSpeech/adapter.js";
|
|
15
|
-
import {
|
|
14
|
+
import { generateSpeech, kind as kind$5 } from "./generateSpeech/index.js";
|
|
16
15
|
import { BaseTranscriptionAdapter } from "./generateTranscription/adapter.js";
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
BaseImageAdapter,
|
|
20
|
-
BaseSummarizeAdapter,
|
|
21
|
-
BaseTTSAdapter,
|
|
22
|
-
BaseTextAdapter,
|
|
23
|
-
BaseTranscriptionAdapter,
|
|
24
|
-
BaseVideoAdapter,
|
|
25
|
-
ChatStreamSummarizeAdapter,
|
|
26
|
-
kind4 as audioKind,
|
|
27
|
-
chat,
|
|
28
|
-
generateAudio,
|
|
29
|
-
generateImage,
|
|
30
|
-
generateSpeech,
|
|
31
|
-
generateTranscription,
|
|
32
|
-
generateVideo,
|
|
33
|
-
getVideoJobStatus,
|
|
34
|
-
kind3 as imageKind,
|
|
35
|
-
snapToDurationOption,
|
|
36
|
-
summarize,
|
|
37
|
-
kind2 as summarizeKind,
|
|
38
|
-
kind as textKind,
|
|
39
|
-
kind7 as transcriptionKind,
|
|
40
|
-
kind6 as ttsKind,
|
|
41
|
-
kind5 as videoKind
|
|
42
|
-
};
|
|
43
|
-
//# sourceMappingURL=index.js.map
|
|
16
|
+
import { generateTranscription, kind as kind$4 } from "./generateTranscription/index.js";
|
|
17
|
+
export { BaseAudioAdapter, BaseImageAdapter, BaseSummarizeAdapter, BaseTTSAdapter, BaseTextAdapter, BaseTranscriptionAdapter, BaseVideoAdapter, ChatStreamSummarizeAdapter, kind as audioKind, chat, generateAudio, generateImage, generateSpeech, generateTranscription, generateVideo, getVideoJobStatus, kind$1 as imageKind, snapToDurationOption, summarize, kind$2 as summarizeKind, kind$3 as textKind, kind$4 as transcriptionKind, kind$5 as ttsKind, kind$6 as videoKind };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export type { GenerationActivity, GenerationMiddleware, GenerationMiddlewareContext, GenerationUsageInfo, GenerationFinishInfo, GenerationAbortInfo, GenerationErrorInfo, AnyGenerationMiddleware, } from './types.js';
|
|
1
|
+
export type { GenerationActivity, GenerationMiddleware, GenerationMiddlewareContext, GenerationUsageInfo, GenerationFinishInfo, GenerationAbortInfo, GenerationErrorInfo, AnyGenerationMiddleware, GenerationResultTransform, GenerationResultTransformContext, } from './types.js';
|
|
2
2
|
export { createGenerationContext, runGenerationStart, runGenerationUsage, runGenerationFinish, runGenerationAbort, runGenerationError, } from './run.js';
|
|
@@ -11,6 +11,9 @@ export declare function createGenerationContext(args: {
|
|
|
11
11
|
provider: string;
|
|
12
12
|
model: string;
|
|
13
13
|
modelOptions?: unknown;
|
|
14
|
+
threadId?: string;
|
|
15
|
+
runId?: string;
|
|
16
|
+
artifactInputs?: unknown;
|
|
14
17
|
createId: (prefix: string) => string;
|
|
15
18
|
}): GenerationMiddlewareContext;
|
|
16
19
|
export declare function runGenerationStart(middleware: ReadonlyArray<GenerationMiddleware> | undefined, ctx: GenerationMiddlewareContext): Promise<void>;
|
|
@@ -18,3 +21,10 @@ export declare function runGenerationUsage(middleware: ReadonlyArray<GenerationM
|
|
|
18
21
|
export declare function runGenerationFinish(middleware: ReadonlyArray<GenerationMiddleware> | undefined, ctx: GenerationMiddlewareContext, info: GenerationFinishInfo): Promise<void>;
|
|
19
22
|
export declare function runGenerationAbort(middleware: ReadonlyArray<GenerationMiddleware> | undefined, ctx: GenerationMiddlewareContext, info: GenerationAbortInfo): Promise<void>;
|
|
20
23
|
export declare function runGenerationError(middleware: ReadonlyArray<GenerationMiddleware> | undefined, ctx: GenerationMiddlewareContext, info: GenerationErrorInfo): Promise<void>;
|
|
24
|
+
/**
|
|
25
|
+
* Apply the result transforms middleware registered on the context, in order,
|
|
26
|
+
* to the raw adapter result. Each transform may return a replacement result or
|
|
27
|
+
* `undefined` to leave it unchanged. Runs after the adapter result exists and
|
|
28
|
+
* before the final result is returned or streamed.
|
|
29
|
+
*/
|
|
30
|
+
export declare function applyGenerationResultTransforms<TResult>(ctx: GenerationMiddlewareContext, result: TResult): Promise<TResult>;
|
|
@@ -1,42 +1,66 @@
|
|
|
1
|
+
//#region src/activities/middleware/run.ts
|
|
2
|
+
/**
|
|
3
|
+
* Build the stable context for a single media-activity call.
|
|
4
|
+
*
|
|
5
|
+
* Media activities are always server-side and carry no user runtime context,
|
|
6
|
+
* so `source` is fixed to `'server'` and `context` to `undefined`.
|
|
7
|
+
*/
|
|
1
8
|
function createGenerationContext(args) {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
9
|
+
return {
|
|
10
|
+
requestId: args.requestId,
|
|
11
|
+
activity: args.activity,
|
|
12
|
+
provider: args.provider,
|
|
13
|
+
model: args.model,
|
|
14
|
+
modelOptions: args.modelOptions,
|
|
15
|
+
threadId: args.threadId,
|
|
16
|
+
runId: args.runId,
|
|
17
|
+
source: "server",
|
|
18
|
+
createId: args.createId,
|
|
19
|
+
context: void 0,
|
|
20
|
+
resultTransforms: [],
|
|
21
|
+
artifactInputs: args.artifactInputs
|
|
22
|
+
};
|
|
12
23
|
}
|
|
24
|
+
/**
|
|
25
|
+
* Run a single lifecycle hook across each middleware in registration order,
|
|
26
|
+
* awaiting each. Exceptions PROPAGATE (matching `chat()` middleware) — a
|
|
27
|
+
* broken middleware fails the activity rather than being silently swallowed.
|
|
28
|
+
*/
|
|
13
29
|
async function run(middleware, invoke) {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
await invoke(mw);
|
|
17
|
-
}
|
|
30
|
+
if (!middleware || middleware.length === 0) return;
|
|
31
|
+
for (const mw of middleware) await invoke(mw);
|
|
18
32
|
}
|
|
19
33
|
function runGenerationStart(middleware, ctx) {
|
|
20
|
-
|
|
34
|
+
return run(middleware, (mw) => mw.onStart?.(ctx));
|
|
21
35
|
}
|
|
22
36
|
function runGenerationUsage(middleware, ctx, usage) {
|
|
23
|
-
|
|
37
|
+
return run(middleware, (mw) => mw.onUsage?.(ctx, usage));
|
|
24
38
|
}
|
|
25
39
|
function runGenerationFinish(middleware, ctx, info) {
|
|
26
|
-
|
|
40
|
+
return run(middleware, (mw) => mw.onFinish?.(ctx, info));
|
|
27
41
|
}
|
|
28
42
|
function runGenerationAbort(middleware, ctx, info) {
|
|
29
|
-
|
|
43
|
+
return run(middleware, (mw) => mw.onAbort?.(ctx, info));
|
|
30
44
|
}
|
|
31
45
|
function runGenerationError(middleware, ctx, info) {
|
|
32
|
-
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
46
|
+
return run(middleware, (mw) => mw.onError?.(ctx, info));
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Apply the result transforms middleware registered on the context, in order,
|
|
50
|
+
* to the raw adapter result. Each transform may return a replacement result or
|
|
51
|
+
* `undefined` to leave it unchanged. Runs after the adapter result exists and
|
|
52
|
+
* before the final result is returned or streamed.
|
|
53
|
+
*/
|
|
54
|
+
async function applyGenerationResultTransforms(ctx, result) {
|
|
55
|
+
let current = result;
|
|
56
|
+
const transformCtx = { middleware: ctx };
|
|
57
|
+
for (const transform of ctx.resultTransforms ?? []) {
|
|
58
|
+
const transformed = await transform(current, transformCtx);
|
|
59
|
+
if (transformed !== void 0) current = transformed;
|
|
60
|
+
}
|
|
61
|
+
return current;
|
|
62
|
+
}
|
|
63
|
+
//#endregion
|
|
64
|
+
export { applyGenerationResultTransforms, createGenerationContext, runGenerationAbort, runGenerationError, runGenerationFinish, runGenerationStart, runGenerationUsage };
|
|
65
|
+
|
|
66
|
+
//# sourceMappingURL=run.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run.js","sources":["../../../../src/activities/middleware/run.ts"],"sourcesContent":["import type {\n GenerationAbortInfo,\n GenerationErrorInfo,\n GenerationFinishInfo,\n GenerationMiddleware,\n GenerationMiddlewareContext,\n GenerationUsageInfo,\n} from './types'\n\n/**\n * Build the stable context for a single media-activity call.\n *\n * Media activities are always server-side and carry no user runtime context,\n * so `source` is fixed to `'server'` and `context` to `undefined`.\n */\nexport function createGenerationContext(args: {\n requestId: string\n activity: GenerationMiddlewareContext['activity']\n provider: string\n model: string\n modelOptions?: unknown\n createId: (prefix: string) => string\n}): GenerationMiddlewareContext {\n return {\n requestId: args.requestId,\n activity: args.activity,\n provider: args.provider,\n model: args.model,\n modelOptions: args.modelOptions,\n source: 'server',\n createId: args.createId,\n context: undefined,\n }\n}\n\n/**\n * Run a single lifecycle hook across each middleware in registration order,\n * awaiting each. Exceptions PROPAGATE (matching `chat()` middleware) — a\n * broken middleware fails the activity rather than being silently swallowed.\n */\nasync function run(\n middleware: ReadonlyArray<GenerationMiddleware> | undefined,\n invoke: (mw: GenerationMiddleware) => void | Promise<void>,\n): Promise<void> {\n if (!middleware || middleware.length === 0) return\n for (const mw of middleware) {\n await invoke(mw)\n }\n}\n\nexport function runGenerationStart(\n middleware: ReadonlyArray<GenerationMiddleware> | undefined,\n ctx: GenerationMiddlewareContext,\n): Promise<void> {\n return run(middleware, (mw) => mw.onStart?.(ctx))\n}\n\nexport function runGenerationUsage(\n middleware: ReadonlyArray<GenerationMiddleware> | undefined,\n ctx: GenerationMiddlewareContext,\n usage: GenerationUsageInfo,\n): Promise<void> {\n return run(middleware, (mw) => mw.onUsage?.(ctx, usage))\n}\n\nexport function runGenerationFinish(\n middleware: ReadonlyArray<GenerationMiddleware> | undefined,\n ctx: GenerationMiddlewareContext,\n info: GenerationFinishInfo,\n): Promise<void> {\n return run(middleware, (mw) => mw.onFinish?.(ctx, info))\n}\n\nexport function runGenerationAbort(\n middleware: ReadonlyArray<GenerationMiddleware> | undefined,\n ctx: GenerationMiddlewareContext,\n info: GenerationAbortInfo,\n): Promise<void> {\n return run(middleware, (mw) => mw.onAbort?.(ctx, info))\n}\n\nexport function runGenerationError(\n middleware: ReadonlyArray<GenerationMiddleware> | undefined,\n ctx: GenerationMiddlewareContext,\n info: GenerationErrorInfo,\n): Promise<void> {\n return run(middleware, (mw) => mw.onError?.(ctx, info))\n}\n
|
|
1
|
+
{"version":3,"file":"run.js","names":[],"sources":["../../../../src/activities/middleware/run.ts"],"sourcesContent":["import type {\n GenerationAbortInfo,\n GenerationErrorInfo,\n GenerationFinishInfo,\n GenerationMiddleware,\n GenerationMiddlewareContext,\n GenerationResultTransformContext,\n GenerationUsageInfo,\n} from './types'\n\n/**\n * Build the stable context for a single media-activity call.\n *\n * Media activities are always server-side and carry no user runtime context,\n * so `source` is fixed to `'server'` and `context` to `undefined`.\n */\nexport function createGenerationContext(args: {\n requestId: string\n activity: GenerationMiddlewareContext['activity']\n provider: string\n model: string\n modelOptions?: unknown\n threadId?: string\n runId?: string\n artifactInputs?: unknown\n createId: (prefix: string) => string\n}): GenerationMiddlewareContext {\n return {\n requestId: args.requestId,\n activity: args.activity,\n provider: args.provider,\n model: args.model,\n modelOptions: args.modelOptions,\n threadId: args.threadId,\n runId: args.runId,\n source: 'server',\n createId: args.createId,\n context: undefined,\n resultTransforms: [],\n artifactInputs: args.artifactInputs,\n }\n}\n\n/**\n * Run a single lifecycle hook across each middleware in registration order,\n * awaiting each. Exceptions PROPAGATE (matching `chat()` middleware) — a\n * broken middleware fails the activity rather than being silently swallowed.\n */\nasync function run(\n middleware: ReadonlyArray<GenerationMiddleware> | undefined,\n invoke: (mw: GenerationMiddleware) => void | Promise<void>,\n): Promise<void> {\n if (!middleware || middleware.length === 0) return\n for (const mw of middleware) {\n await invoke(mw)\n }\n}\n\nexport function runGenerationStart(\n middleware: ReadonlyArray<GenerationMiddleware> | undefined,\n ctx: GenerationMiddlewareContext,\n): Promise<void> {\n return run(middleware, (mw) => mw.onStart?.(ctx))\n}\n\nexport function runGenerationUsage(\n middleware: ReadonlyArray<GenerationMiddleware> | undefined,\n ctx: GenerationMiddlewareContext,\n usage: GenerationUsageInfo,\n): Promise<void> {\n return run(middleware, (mw) => mw.onUsage?.(ctx, usage))\n}\n\nexport function runGenerationFinish(\n middleware: ReadonlyArray<GenerationMiddleware> | undefined,\n ctx: GenerationMiddlewareContext,\n info: GenerationFinishInfo,\n): Promise<void> {\n return run(middleware, (mw) => mw.onFinish?.(ctx, info))\n}\n\nexport function runGenerationAbort(\n middleware: ReadonlyArray<GenerationMiddleware> | undefined,\n ctx: GenerationMiddlewareContext,\n info: GenerationAbortInfo,\n): Promise<void> {\n return run(middleware, (mw) => mw.onAbort?.(ctx, info))\n}\n\nexport function runGenerationError(\n middleware: ReadonlyArray<GenerationMiddleware> | undefined,\n ctx: GenerationMiddlewareContext,\n info: GenerationErrorInfo,\n): Promise<void> {\n return run(middleware, (mw) => mw.onError?.(ctx, info))\n}\n\n/**\n * Apply the result transforms middleware registered on the context, in order,\n * to the raw adapter result. Each transform may return a replacement result or\n * `undefined` to leave it unchanged. Runs after the adapter result exists and\n * before the final result is returned or streamed.\n */\nexport async function applyGenerationResultTransforms<TResult>(\n ctx: GenerationMiddlewareContext,\n result: TResult,\n): Promise<TResult> {\n let current = result\n const transformCtx: GenerationResultTransformContext = { middleware: ctx }\n\n for (const transform of ctx.resultTransforms ?? []) {\n const transformed = await transform(current, transformCtx)\n if (transformed !== undefined) {\n current = transformed as TResult\n }\n }\n\n return current\n}\n"],"mappings":";;;;;;;AAgBA,SAAgB,wBAAwB,MAUR;CAC9B,OAAO;EACL,WAAW,KAAK;EAChB,UAAU,KAAK;EACf,UAAU,KAAK;EACf,OAAO,KAAK;EACZ,cAAc,KAAK;EACnB,UAAU,KAAK;EACf,OAAO,KAAK;EACZ,QAAQ;EACR,UAAU,KAAK;EACf,SAAS,KAAA;EACT,kBAAkB,CAAC;EACnB,gBAAgB,KAAK;CACvB;AACF;;;;;;AAOA,eAAe,IACb,YACA,QACe;CACf,IAAI,CAAC,cAAc,WAAW,WAAW,GAAG;CAC5C,KAAK,MAAM,MAAM,YACf,MAAM,OAAO,EAAE;AAEnB;AAEA,SAAgB,mBACd,YACA,KACe;CACf,OAAO,IAAI,aAAa,OAAO,GAAG,UAAU,GAAG,CAAC;AAClD;AAEA,SAAgB,mBACd,YACA,KACA,OACe;CACf,OAAO,IAAI,aAAa,OAAO,GAAG,UAAU,KAAK,KAAK,CAAC;AACzD;AAEA,SAAgB,oBACd,YACA,KACA,MACe;CACf,OAAO,IAAI,aAAa,OAAO,GAAG,WAAW,KAAK,IAAI,CAAC;AACzD;AAEA,SAAgB,mBACd,YACA,KACA,MACe;CACf,OAAO,IAAI,aAAa,OAAO,GAAG,UAAU,KAAK,IAAI,CAAC;AACxD;AAEA,SAAgB,mBACd,YACA,KACA,MACe;CACf,OAAO,IAAI,aAAa,OAAO,GAAG,UAAU,KAAK,IAAI,CAAC;AACxD;;;;;;;AAQA,eAAsB,gCACpB,KACA,QACkB;CAClB,IAAI,UAAU;CACd,MAAM,eAAiD,EAAE,YAAY,IAAI;CAEzE,KAAK,MAAM,aAAa,IAAI,oBAAoB,CAAC,GAAG;EAClD,MAAM,cAAc,MAAM,UAAU,SAAS,YAAY;EACzD,IAAI,gBAAgB,KAAA,GAClB,UAAU;CAEd;CAEA,OAAO;AACT"}
|
|
@@ -2,13 +2,16 @@ import { TokenUsage } from '../../types.js';
|
|
|
2
2
|
/**
|
|
3
3
|
* The activity an observability event describes.
|
|
4
4
|
*
|
|
5
|
-
* Mirrors the public surface a caller reaches for: `'chat'` for `chat()`,
|
|
6
|
-
* the media kinds for the `generate*`
|
|
7
|
-
* adapter's kind (the public
|
|
8
|
-
* `'speech'`/`'text'` vocabulary).
|
|
9
|
-
* `gen_ai.operation.name`.
|
|
5
|
+
* Mirrors the public surface a caller reaches for: `'chat'` for `chat()`,
|
|
6
|
+
* `'summarize'` for `summarize()`, and the media kinds for the `generate*`
|
|
7
|
+
* activities. `'tts'` matches the speech adapter's kind (the public
|
|
8
|
+
* discriminator avoids inventing a parallel `'speech'`/`'text'` vocabulary).
|
|
9
|
+
* `otelMiddleware` maps each to its `gen_ai.operation.name`.
|
|
10
|
+
*
|
|
11
|
+
* `'summarize'` produces text, not media, so it has no artifacts — a
|
|
12
|
+
* persistence middleware stores its run record and result and nothing else.
|
|
10
13
|
*/
|
|
11
|
-
export type GenerationActivity = 'chat' | 'image' | 'video' | 'audio' | 'tts' | 'transcription';
|
|
14
|
+
export type GenerationActivity = 'chat' | 'image' | 'video' | 'audio' | 'tts' | 'transcription' | 'summarize';
|
|
12
15
|
/**
|
|
13
16
|
* Stable context passed to every {@link GenerationMiddleware} hook. Created
|
|
14
17
|
* once per activity call and shared across the hooks of that call.
|
|
@@ -30,6 +33,10 @@ export interface GenerationMiddlewareContext<TContext = unknown> {
|
|
|
30
33
|
provider: string;
|
|
31
34
|
/** Model id. Emitted as `gen_ai.request.model`. */
|
|
32
35
|
model: string;
|
|
36
|
+
/** Stable conversation/thread id, when supplied by the caller. */
|
|
37
|
+
threadId?: string;
|
|
38
|
+
/** Stable run id, when supplied by the caller. */
|
|
39
|
+
runId?: string;
|
|
33
40
|
/**
|
|
34
41
|
* Provider-specific options passed to the activity, if any. Typed `unknown`
|
|
35
42
|
* because each activity's options are strongly typed per model; a supertype
|
|
@@ -42,7 +49,38 @@ export interface GenerationMiddlewareContext<TContext = unknown> {
|
|
|
42
49
|
createId: (prefix: string) => string;
|
|
43
50
|
/** Runtime context provided by the activity options, if any. */
|
|
44
51
|
context: TContext;
|
|
52
|
+
/**
|
|
53
|
+
* Result transforms registered by middleware during this activity call.
|
|
54
|
+
* Transforms run after the raw adapter result exists and before the final
|
|
55
|
+
* result is returned or streamed. Push multiple transforms to run them in
|
|
56
|
+
* registration order.
|
|
57
|
+
*
|
|
58
|
+
* REQUIRED (always an array, empty when nothing registered): middleware
|
|
59
|
+
* registers by pushing onto it, so an optional array would let a host that
|
|
60
|
+
* builds its own context omit it and silently no-op every registration —
|
|
61
|
+
* generation persistence would then mark a run completed with neither its
|
|
62
|
+
* result nor its artifacts written, with nothing to observe but the missing
|
|
63
|
+
* data. Every context the library builds comes from
|
|
64
|
+
* `createGenerationContext`, which always sets `[]`.
|
|
65
|
+
*/
|
|
66
|
+
resultTransforms: Array<GenerationResultTransform<any, TContext>>;
|
|
67
|
+
/**
|
|
68
|
+
* Activity inputs captured for middleware that needs to transform or persist
|
|
69
|
+
* the result together with reconstructable request metadata.
|
|
70
|
+
*/
|
|
71
|
+
artifactInputs?: unknown;
|
|
72
|
+
}
|
|
73
|
+
/** Stable context handed to each {@link GenerationResultTransform}. */
|
|
74
|
+
export interface GenerationResultTransformContext<TContext = unknown> {
|
|
75
|
+
/** The activity call being transformed. */
|
|
76
|
+
middleware: GenerationMiddlewareContext<TContext>;
|
|
45
77
|
}
|
|
78
|
+
/**
|
|
79
|
+
* A transform middleware registers on `ctx.resultTransforms` to rewrite the raw
|
|
80
|
+
* adapter result before it is returned or streamed. Return a new result to
|
|
81
|
+
* replace it, or `undefined` to leave it unchanged.
|
|
82
|
+
*/
|
|
83
|
+
export type GenerationResultTransform<TResult = unknown, TContext = unknown> = (result: TResult, ctx: GenerationResultTransformContext<TContext>) => TResult | undefined | Promise<TResult | undefined>;
|
|
46
84
|
/**
|
|
47
85
|
* Token usage passed to {@link GenerationMiddleware.onUsage}. Kept as an
|
|
48
86
|
* interface extending `TokenUsage` to preserve declaration merging for this
|
|
@@ -9,7 +9,10 @@ import { StreamChunk } from '../types.js';
|
|
|
9
9
|
* @param options - Optional configuration (runId, threadId)
|
|
10
10
|
* @returns An AsyncIterable of StreamChunks with RUN_STARTED, CUSTOM(generation:result), and RUN_FINISHED events on success, or RUN_STARTED and RUN_ERROR on failure
|
|
11
11
|
*/
|
|
12
|
-
export declare function streamGenerationResult<TResult>(generator: (
|
|
12
|
+
export declare function streamGenerationResult<TResult>(generator: (resolved: {
|
|
13
|
+
runId: string;
|
|
14
|
+
threadId: string;
|
|
15
|
+
}) => Promise<TResult>, options?: {
|
|
13
16
|
runId?: string;
|
|
14
17
|
threadId?: string;
|
|
15
18
|
}): AsyncIterable<StreamChunk>;
|