@neta-art/generation 0.1.5 → 0.1.7
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 +24 -0
- package/dist/builtins-C-_aGhT8.d.ts.map +1 -1
- package/dist/{builtins-WOyUMLOY.js → builtins-NAtI9FFU.js} +91 -1
- package/dist/builtins-NAtI9FFU.js.map +1 -0
- package/dist/builtins.js +1 -1
- package/dist/cli/index.js +2 -2
- package/dist/{export-config-1c3HS6eX.js → export-config-DvBXBq-8.js} +80 -9
- package/dist/export-config-DvBXBq-8.js.map +1 -0
- package/dist/index.d.ts +4 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -3
- package/models/qwen-image-edit.yaml +44 -0
- package/models/z-image-turbo.yaml +34 -0
- package/package.json +1 -1
- package/dist/builtins-WOyUMLOY.js.map +0 -1
- package/dist/export-config-1c3HS6eX.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"builtins-WOyUMLOY.js","names":["parameters: GenerationModelDeclaration[\"parameters\"]","input: GenerationModelDeclaration[\"content\"][\"input\"]","builtinGenerationModels: GenerationModelDeclaration[]"],"sources":["../src/types.ts","../src/utils.ts","../src/builtins.ts"],"sourcesContent":["export const MODEL_SCHEMA = \"neta.generation.model.v1\" as const;\n\nexport type GenerationSource = { type: \"url\"; url: string } | { type: \"base64\"; mediaType: string; data: string };\n\nexport type GenerationContentBlockMeta = Record<string, unknown>;\n\nexport type GenerationContentBlock =\n | { type: \"text\"; text: string; meta?: GenerationContentBlockMeta }\n | { type: \"image\"; source: GenerationSource; meta?: GenerationContentBlockMeta }\n | { type: \"video\"; source: GenerationSource; meta?: GenerationContentBlockMeta }\n | { type: \"audio\"; source: GenerationSource; meta?: GenerationContentBlockMeta };\n\nexport type GenerationContentSpec = {\n type: \"text\" | \"image\" | \"video\" | \"audio\";\n required?: boolean;\n min?: number;\n max?: number;\n sources?: Array<GenerationSource[\"type\"]>;\n merge?: \"newline\" | \"space\" | \"concat\";\n meta?: Record<string, unknown>;\n description?: string;\n};\n\nexport type GenerationParameterSpec =\n | {\n type: \"string\";\n optional?: boolean;\n default?: string;\n enum?: string[];\n description?: string;\n examples?: string[];\n }\n | {\n type: \"number\";\n optional?: boolean;\n default?: number;\n min?: number;\n max?: number;\n description?: string;\n examples?: number[];\n }\n | {\n type: \"integer\";\n optional?: boolean;\n default?: number;\n min?: number;\n max?: number;\n description?: string;\n examples?: number[];\n }\n | {\n type: \"boolean\";\n optional?: boolean;\n default?: boolean;\n description?: string;\n examples?: boolean[];\n };\n\nexport type GenerationMetaFieldSpec =\n | GenerationParameterSpec\n | { type: \"object\"; optional?: boolean; description?: string };\n\nexport type GenerationMetaTaskVariantSpec = {\n description?: string;\n required?: string[];\n requiredContent?: Array<GenerationContentSpec[\"type\"]>;\n sendTask?: boolean;\n};\n\nexport type GenerationMetaSpec = {\n fields?: Record<string, GenerationMetaFieldSpec>;\n taskField?: string;\n taskVariants?: Record<string, GenerationMetaTaskVariantSpec>;\n};\n\nexport type GenerationModelDeclaration = {\n schema: typeof MODEL_SCHEMA;\n model: string;\n title?: string;\n description?: string;\n allowUnknownParameters?: boolean;\n adapter: {\n type: string;\n } & Record<string, unknown>;\n content: {\n input: GenerationContentSpec[];\n };\n parameters?: Record<string, GenerationParameterSpec>;\n meta?: GenerationMetaSpec;\n examples?: Array<{\n title?: string;\n request: GenerateRequest;\n }>;\n};\n\nexport type GenerateRequest = {\n model: string;\n content: GenerationContentBlock[];\n parameters?: Record<string, unknown>;\n meta?: Record<string, unknown>;\n /** @deprecated Use meta. */\n metadata?: Record<string, unknown>;\n apiKey?: string;\n baseUrl?: string;\n};\n\nexport type ResolvedGenerationRequest = {\n declaration: GenerationModelDeclaration;\n request: GenerateRequest;\n parameters: Record<string, unknown>;\n meta: Record<string, unknown>;\n};\n\nexport type GenerationSourceResolver = (source: GenerationSource) => Promise<string> | string;\n\nexport type GenerationDebugEvent =\n | {\n type: \"request\";\n url: string;\n method: string;\n headers: Record<string, string>;\n body?: unknown;\n }\n | {\n type: \"response\";\n url: string;\n status: number;\n statusText: string;\n headers: Record<string, string>;\n trace: Record<string, string>;\n elapsedMs: number;\n body?: unknown;\n };\n\nexport type GenerationDebugLogger = (event: GenerationDebugEvent) => void;\n\nexport type GenerationDebugOptions = {\n enabled?: boolean;\n includeSensitive?: boolean;\n includeResponseBody?: boolean;\n logger?: GenerationDebugLogger;\n};\n\nexport type GenerationDebugConfig = GenerationDebugOptions & {\n enabled: boolean;\n includeSensitive: boolean;\n includeResponseBody: boolean;\n logger: GenerationDebugLogger;\n};\n\nexport type GenerationAdapterContext = {\n apiKey: string;\n baseUrl: string;\n fetch: typeof fetch;\n resolveSource: GenerationSourceResolver;\n};\n\nexport type GenerationAdapterInput = ResolvedGenerationRequest & {\n context: GenerationAdapterContext;\n};\n\nexport type GenerationAdapter = (input: GenerationAdapterInput) => Promise<GenerationContentBlock[]>;\n\nexport type CreateGenerationClientOptions = {\n apiKey?: string;\n baseUrl?: string;\n models?: GenerationModelDeclaration[];\n includeBuiltinModels?: boolean;\n fetch?: typeof fetch;\n sourceResolver?: GenerationSourceResolver;\n adapters?: Record<string, GenerationAdapter>;\n debug?: boolean | GenerationDebugOptions;\n};\n\nexport type GenerationClient = {\n generate(request: GenerateRequest): Promise<GenerationContentBlock[]>;\n validate(request: GenerateRequest): ResolvedGenerationRequest;\n listModels(): GenerationModelDeclaration[];\n getModel(model: string): GenerationModelDeclaration | null;\n stringifyModelConfig(model: string, options?: { format?: \"yaml\" | \"json\" }): string;\n exportModelConfig(model: string, filePath: string): Promise<void>;\n exportModelConfigs(directory: string): Promise<void>;\n};\n","import type { GenerationContentBlock } from \"./types.js\";\n\nexport function cloneJson<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\nexport function slugifyFileName(value: string): string {\n return (\n value\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\") || \"model\"\n );\n}\n\nexport function getBlockMeta(block: GenerationContentBlock): Record<string, unknown> | undefined {\n return \"meta\" in block ? block.meta : undefined;\n}\n\nexport function compactArray<T>(values: T[]): T[] | undefined {\n return values.length > 0 ? values : undefined;\n}\n\nexport function compactObject<T extends Record<string, unknown>>(value: T): T {\n for (const key of Object.keys(value)) if (value[key] === undefined) delete value[key];\n return value;\n}\n","import type { GenerationModelDeclaration } from \"./types.js\";\nimport { MODEL_SCHEMA } from \"./types.js\";\nimport { cloneJson } from \"./utils.js\";\n\nconst imageSizeParameters = {\n size: {\n type: \"string\",\n optional: true,\n default: \"1024x1024\",\n description: \"Output image size.\",\n examples: [\"auto\", \"1024x1024\", \"1536x1024\", \"1024x1536\", \"2048x2048\", \"2048x1152\", \"3840x2160\", \"2160x3840\"],\n },\n quality: {\n type: \"string\",\n optional: true,\n default: \"auto\",\n enum: [\"auto\", \"low\", \"medium\", \"high\"],\n description: \"Image quality.\",\n },\n} satisfies GenerationModelDeclaration[\"parameters\"];\n\nconst noobxlImageParameters = {\n size: {\n type: \"string\",\n optional: true,\n default: \"1024x1024\",\n description: \"Output image size as WIDTHxHEIGHT.\",\n examples: [\"1024x1024\", \"768x1024\", \"1024x768\"],\n },\n negative_prompt: {\n type: \"string\",\n optional: true,\n description: \"Content to avoid in generated images.\",\n },\n seed: {\n type: \"integer\",\n optional: true,\n min: 0,\n description: \"Random seed for reproducibility.\",\n },\n} satisfies GenerationModelDeclaration[\"parameters\"];\n\nconst noobxlImageToImageParameters = {\n ...noobxlImageParameters,\n controlnet_weight: {\n type: \"number\",\n optional: true,\n min: 0,\n max: 2,\n description: \"ControlNet tile weight. The provider default is 0.8.\",\n },\n ipadapter_face_image_ref: {\n type: \"string\",\n optional: true,\n description: \"Optional face reference image URL for IP-Adapter.\",\n },\n ipadapter_face_weight: {\n type: \"number\",\n optional: true,\n min: 0,\n max: 2,\n description: \"IP-Adapter face weight. The provider default is 0.6 when a face reference is supplied.\",\n },\n} satisfies GenerationModelDeclaration[\"parameters\"];\n\nfunction videoParameters(defaults: { resolution: string; maxWait: number }) {\n return {\n duration: {\n type: \"integer\",\n optional: true,\n default: 5,\n min: 4,\n max: 15,\n description: \"Video duration in seconds.\",\n },\n resolution: {\n type: \"string\",\n optional: true,\n default: defaults.resolution,\n enum: [\"480p\", \"720p\", \"1080p\", \"2K\"],\n description: \"Output video resolution.\",\n },\n aspect_ratio: {\n type: \"string\",\n optional: true,\n default: \"16:9\",\n enum: [\"16:9\", \"9:16\", \"1:1\", \"4:3\", \"3:2\", \"2:3\", \"3:4\", \"21:9\", \"adaptive\"],\n description: \"Output aspect ratio. Use adaptive to let the model choose.\",\n },\n fps: { type: \"integer\", optional: true, default: 30, min: 1, max: 60, description: \"Frames per second.\" },\n seed: { type: \"integer\", optional: true, description: \"Random seed for reproducibility.\" },\n generate_audio: { type: \"boolean\", optional: true, default: true, description: \"Generate synchronized audio.\" },\n return_last_frame: {\n type: \"boolean\",\n optional: true,\n default: true,\n description: \"Return the last frame as an image for chaining video segments.\",\n },\n camera_fixed: {\n type: \"boolean\",\n optional: true,\n default: false,\n description: \"Fix camera position when supported.\",\n },\n watermark: { type: \"boolean\", optional: true, default: false, description: \"Add AI Generated watermark.\" },\n poll_interval: {\n type: \"integer\",\n optional: true,\n default: 2,\n min: 1,\n max: 30,\n description: \"Seconds between task status checks.\",\n },\n max_wait: {\n type: \"integer\",\n optional: true,\n default: defaults.maxWait,\n min: 30,\n max: 1800,\n description: \"Maximum seconds to wait for task completion.\",\n },\n } satisfies GenerationModelDeclaration[\"parameters\"];\n}\n\nfunction klingVideoParameters(options: {\n maxDuration: number;\n negativePrompt?: boolean;\n seed?: boolean;\n sound?: boolean;\n}) {\n const parameters: GenerationModelDeclaration[\"parameters\"] = {\n duration: {\n type: \"integer\",\n optional: true,\n default: 5,\n min: 5,\n max: options.maxDuration,\n description: \"Video duration in seconds.\",\n },\n aspect_ratio: {\n type: \"string\",\n optional: true,\n default: \"16:9\",\n enum: [\"16:9\", \"9:16\", \"1:1\"],\n description: \"Output aspect ratio.\",\n },\n mode: {\n type: \"string\",\n optional: true,\n default: \"std\",\n enum: [\"std\", \"pro\"],\n description: \"Kling generation mode.\",\n },\n cfg_scale: {\n type: \"number\",\n optional: true,\n default: 0.5,\n min: 0,\n max: 1,\n description: \"Prompt adherence scale.\",\n },\n poll_interval: {\n type: \"integer\",\n optional: true,\n default: 5,\n min: 1,\n max: 30,\n description: \"Seconds between task status checks.\",\n },\n max_wait: {\n type: \"integer\",\n optional: true,\n default: 900,\n min: 30,\n max: 1800,\n description: \"Maximum seconds to wait for task completion.\",\n },\n };\n if (options.negativePrompt) {\n parameters.negative_prompt = {\n type: \"string\",\n optional: true,\n description: \"Negative prompt.\",\n };\n }\n if (options.seed) {\n parameters.seed = {\n type: \"integer\",\n optional: true,\n description: \"Random seed for reproducibility.\",\n };\n }\n if (options.sound) {\n parameters.sound = {\n type: \"string\",\n optional: true,\n enum: [\"on\", \"off\"],\n description: \"Enable or disable generated sound when supported.\",\n };\n }\n return parameters;\n}\n\nconst sunoTaskParameters = {\n poll_interval: {\n type: \"integer\",\n optional: true,\n default: 5,\n min: 1,\n max: 60,\n description: \"Seconds between task status checks.\",\n },\n max_wait: {\n type: \"integer\",\n optional: true,\n default: 600,\n min: 30,\n max: 3600,\n description: \"Maximum seconds to wait for task completion.\",\n },\n} satisfies GenerationModelDeclaration[\"parameters\"];\n\nconst sunoCommonMetaFields = {\n title: { type: \"string\", optional: true, description: \"Suno song title.\" },\n tags: { type: \"string\", optional: true, description: \"Comma-separated Suno music style tags.\" },\n gpt_description_prompt: { type: \"string\", optional: true, description: \"Suno inspiration-mode prompt.\" },\n negative_tags: { type: \"string\", optional: true, description: \"Styles to avoid.\" },\n generation_type: { type: \"string\", optional: true, description: \"Suno generation type.\" },\n make_instrumental: { type: \"boolean\", optional: true, default: false, description: \"Generate instrumental music.\" },\n metadata: { type: \"object\", optional: true, description: \"Suno provider metadata payload.\" },\n metadata_params: {\n type: \"object\",\n optional: true,\n description: \"Suno task-specific metadata payload.\",\n },\n} satisfies NonNullable<GenerationModelDeclaration[\"meta\"]>[\"fields\"];\n\nconst sunoTaskVariants = {\n extend: { required: [\"continue_clip_id\"] },\n upload_extend: { required: [\"continue_clip_id\"] },\n infill: { required: [\"continue_clip_id\", \"metadata_params\"] },\n fixed_infill: { required: [\"continue_clip_id\", \"metadata_params\"] },\n infill_intro: { required: [\"continue_clip_id\", \"metadata_params\"] },\n infill_outro: { required: [\"continue_clip_id\", \"metadata_params\"] },\n cover_infill: { required: [\"continue_clip_id\", \"metadata_params\"] },\n cover_extend: { required: [\"continue_clip_id\"] },\n artist_infill: { required: [\"continue_clip_id\", \"metadata_params\"] },\n artist_consistency: { required: [\"persona_id\", \"artist_clip_id\"] },\n cover: { required: [\"task_id\", \"continue_clip_id\"] },\n image_to_song: { requiredContent: [\"image\"], required: [\"metadata_params\"] },\n video_to_song: { requiredContent: [\"video\"], required: [\"metadata_params\"] },\n concat: { required: [\"clip_id\"] },\n sound: { required: [\"metadata_params\"] },\n underpainting: { required: [\"metadata_params\"] },\n overpainting: { required: [\"metadata_params\"] },\n remaster: { required: [\"metadata_params\"] },\n vox: { required: [\"artist_clip_id\"] },\n chop_sample_condition: { required: [\"metadata_params\"] },\n mashup_condition: { required: [\"metadata_params\"] },\n playlist_condition: { required: [\"metadata_params\"] },\n} satisfies NonNullable<GenerationModelDeclaration[\"meta\"]>[\"taskVariants\"];\n\nfunction sunoContentInput(\n options: { text?: \"required\" | \"optional\" | \"none\"; audio?: boolean; image?: boolean; video?: boolean } = {},\n): GenerationModelDeclaration[\"content\"][\"input\"] {\n const input: GenerationModelDeclaration[\"content\"][\"input\"] = [];\n if (options.text !== \"none\") {\n input.push({\n type: \"text\",\n required: options.text === \"required\",\n max: 16,\n merge: \"newline\",\n description:\n \"Prompt text. The adapter maps merged text to the operation's text field when that field is not provided.\",\n });\n }\n if (options.audio) {\n input.push({\n type: \"audio\",\n required: true,\n max: 1,\n sources: [\"url\", \"base64\"],\n description: \"Reference audio.\",\n });\n }\n if (options.image) {\n input.push({\n type: \"image\",\n required: true,\n max: 1,\n sources: [\"url\", \"base64\"],\n description: \"Reference image.\",\n });\n }\n if (options.video) {\n input.push({\n type: \"video\",\n required: true,\n max: 1,\n sources: [\"url\", \"base64\"],\n description: \"Reference video.\",\n });\n }\n return input;\n}\n\nconst sunoVersions = [\n { model: \"suno_music_chirp_fenix\", title: \"Suno Music Chirp Fenix v5.5\", mv: \"chirp-fenix\" },\n] as const;\n\nconst sunoMusicExample = {\n title: \"Music generation\",\n request: {\n model: \"suno_music_chirp_fenix\",\n content: [{ type: \"text\", text: \"uplifting cinematic pop with warm piano and clear chorus\" }],\n meta: {\n title: \"Warm Horizon\",\n tags: \"cinematic pop, warm piano\",\n make_instrumental: false,\n },\n },\n} satisfies NonNullable<GenerationModelDeclaration[\"examples\"]>[number];\n\nfunction sunoVersionModel(version: (typeof sunoVersions)[number]): GenerationModelDeclaration {\n return {\n schema: MODEL_SCHEMA,\n model: version.model,\n title: version.title,\n description: \"Suno text-to-music model with a fixed Suno model version.\",\n adapter: { type: \"suno.tasks\", operation: \"music\", payload: { mv: version.mv } },\n content: {\n input: sunoContentInput({ text: \"required\" }),\n },\n parameters: sunoTaskParameters,\n meta: {\n fields: sunoCommonMetaFields,\n },\n ...(version.model === \"suno_music_chirp_fenix\" ? { examples: [sunoMusicExample] } : {}),\n };\n}\n\nfunction sunoTaskModel(options: {\n model: string;\n title: string;\n description: string;\n task: string;\n mv?: string;\n content?: Parameters<typeof sunoContentInput>[0];\n fields?: NonNullable<GenerationModelDeclaration[\"meta\"]>[\"fields\"];\n examples?: GenerationModelDeclaration[\"examples\"];\n}): GenerationModelDeclaration {\n return {\n schema: MODEL_SCHEMA,\n model: options.model,\n title: options.title,\n description: options.description,\n adapter: {\n type: \"suno.tasks\",\n operation: \"music\",\n task: options.task,\n payload: { mv: options.mv ?? \"chirp-v5\" },\n },\n content: {\n input: sunoContentInput(options.content ?? { text: \"optional\" }),\n },\n parameters: sunoTaskParameters,\n meta: {\n fields: {\n ...sunoCommonMetaFields,\n ...options.fields,\n },\n taskVariants: sunoTaskVariants,\n },\n ...(options.examples ? { examples: options.examples } : {}),\n };\n}\n\nconst sunoModels = [\n ...sunoVersions.map(sunoVersionModel),\n {\n schema: MODEL_SCHEMA,\n model: \"suno_style_tags\",\n title: \"Suno Style Tags\",\n description: \"Suno style tag upsampling model.\",\n adapter: { type: \"suno.tasks\", operation: \"upsample_tags\" },\n content: {\n input: sunoContentInput({ text: \"required\" }),\n },\n },\n {\n schema: MODEL_SCHEMA,\n model: \"suno_upload_audio\",\n title: \"Suno Upload Audio\",\n description: \"Suno reference-audio upload model.\",\n adapter: { type: \"suno.tasks\", operation: \"upload_audio\", defaults: { name: \"reference-audio\", timeout: 120 } },\n content: {\n input: sunoContentInput({ text: \"none\", audio: true }),\n },\n parameters: sunoTaskParameters,\n meta: {\n fields: {\n name: { type: \"string\", optional: true, description: \"Upload name.\" },\n timeout: { type: \"integer\", optional: true, description: \"Upload timeout in seconds.\" },\n },\n },\n },\n sunoTaskModel({\n model: \"suno_image_to_song_chirp_v5\",\n title: \"Suno Image to Song Chirp v5.0\",\n description: \"Suno image-to-song task with a fixed chirp-v5 engine.\",\n task: \"image_to_song\",\n content: { text: \"optional\", image: true },\n fields: {\n metadata_params: { type: \"object\", description: \"Image-to-song metadata payload.\" },\n },\n }),\n sunoTaskModel({\n model: \"suno_video_to_song_chirp_v5\",\n title: \"Suno Video to Song Chirp v5.0\",\n description: \"Suno video-to-song task with a fixed chirp-v5 engine.\",\n task: \"video_to_song\",\n content: { text: \"optional\", video: true },\n fields: {\n metadata_params: { type: \"object\", description: \"Video-to-song metadata payload.\" },\n },\n }),\n sunoTaskModel({\n model: \"suno_sound_chirp_v5\",\n title: \"Suno Sound Chirp v5.0\",\n description: \"Suno sound-effect generation task with a fixed chirp-v5 engine.\",\n task: \"sound\",\n content: { text: \"optional\" },\n fields: {\n metadata_params: { type: \"object\", description: \"Sound task metadata payload.\" },\n },\n }),\n sunoTaskModel({\n model: \"suno_cover_chirp_v5\",\n title: \"Suno Cover Chirp v5.0\",\n description: \"Suno cover task with a fixed chirp-v5 engine.\",\n task: \"cover\",\n content: { text: \"optional\" },\n fields: {\n cover_clip_id: { type: \"string\", description: \"Clip id to cover.\" },\n task_id: { type: \"string\", description: \"Source Suno task id used for cover routing.\" },\n continue_clip_id: { type: \"string\", description: \"Source clip id used for cover generation.\" },\n continue_at: { type: \"number\", optional: true, description: \"Source clip continuation position in seconds.\" },\n },\n }),\n sunoTaskModel({\n model: \"suno_infill_chirp_v5\",\n title: \"Suno Infill Chirp v5.0\",\n description: \"Suno local edit task with a fixed chirp-v5 engine.\",\n task: \"infill\",\n content: { text: \"optional\" },\n fields: {\n continue_clip_id: { type: \"string\", description: \"Clip id to edit.\" },\n metadata_params: { type: \"object\", description: \"Infill timing and replacement metadata.\" },\n },\n }),\n sunoTaskModel({\n model: \"suno_vox_chirp_v5\",\n title: \"Suno Vox Chirp v5.0\",\n description: \"Suno hum-to-song task with a fixed chirp-v5 engine.\",\n task: \"vox\",\n content: { text: \"optional\" },\n fields: {\n artist_clip_id: { type: \"string\", description: \"Reference hum or vocal clip id.\" },\n },\n }),\n] satisfies GenerationModelDeclaration[];\n\nconst builtinModels = [\n {\n schema: MODEL_SCHEMA,\n model: \"gpt-image-2\",\n title: \"GPT Image 2\",\n description:\n \"Image generation model with optional reference images. Good for photorealistic scenes, detailed images, and image editing with references.\",\n adapter: { type: \"openai.images\" },\n content: {\n input: [\n { type: \"text\", required: true, min: 1, max: 16, merge: \"newline\", description: \"Prompt text.\" },\n {\n type: \"image\",\n required: false,\n max: 16,\n sources: [\"url\", \"base64\"],\n description: \"Optional reference images.\",\n },\n ],\n },\n parameters: imageSizeParameters,\n examples: [\n {\n title: \"Basic image\",\n request: {\n model: \"gpt-image-2\",\n content: [{ type: \"text\", text: \"a cyberpunk cat in neon rain\" }],\n parameters: { size: \"1024x1024\", quality: \"auto\" },\n },\n },\n ],\n },\n {\n schema: MODEL_SCHEMA,\n model: \"gemini-3.1-flash-image-preview\",\n title: \"Gemini 3.1 Flash Image Preview\",\n description:\n \"Gemini image generation and editing model. Good for text rendering, infographics, style transfer, and iterative image editing with references.\",\n adapter: { type: \"gemini.generateContent\" },\n content: {\n input: [\n { type: \"text\", required: true, min: 1, max: 16, merge: \"newline\", description: \"Prompt text.\" },\n {\n type: \"image\",\n required: false,\n max: 14,\n sources: [\"url\", \"base64\"],\n description: \"Optional reference images.\",\n },\n ],\n },\n parameters: {\n aspect_ratio: {\n type: \"string\",\n optional: true,\n default: \"1:1\",\n enum: [\"1:1\", \"16:9\", \"4:3\", \"3:2\", \"3:4\", \"2:3\", \"9:16\", \"5:4\", \"4:5\", \"21:9\", \"1:4\", \"4:1\", \"1:8\", \"8:1\"],\n description: \"Output aspect ratio.\",\n },\n image_size: {\n type: \"string\",\n optional: true,\n default: \"2K\",\n enum: [\"512\", \"1K\", \"2K\", \"4K\"],\n description: \"Output image resolution.\",\n },\n },\n examples: [\n {\n title: \"Basic image\",\n request: {\n model: \"gemini-3.1-flash-image-preview\",\n content: [\n { type: \"text\", text: \"a vibrant infographic explaining photosynthesis with clear readable labels\" },\n ],\n parameters: { aspect_ratio: \"16:9\", image_size: \"1K\" },\n },\n },\n ],\n },\n {\n schema: MODEL_SCHEMA,\n model: \"kling-text-to-video\",\n title: \"Kling Text To Video\",\n description: \"Kling latest text-to-video generation through Neta Router.\",\n adapter: { type: \"kling.videoGenerations\" },\n content: {\n input: [{ type: \"text\", required: true, min: 1, max: 16, merge: \"newline\", description: \"Video prompt.\" }],\n },\n parameters: klingVideoParameters({ maxDuration: 10, negativePrompt: true, seed: true }),\n examples: [\n {\n title: \"Text to video\",\n request: {\n model: \"kling-text-to-video\",\n content: [{ type: \"text\", text: \"a small paper boat floating on calm water, cinematic motion\" }],\n parameters: { duration: 5, aspect_ratio: \"16:9\", mode: \"std\" },\n },\n },\n ],\n },\n {\n schema: MODEL_SCHEMA,\n model: \"kling-image-to-video\",\n title: \"Kling Image To Video\",\n description: \"Kling latest image-to-video generation through Neta Router.\",\n adapter: { type: \"kling.videoGenerations\" },\n content: {\n input: [\n { type: \"text\", required: true, min: 1, max: 16, merge: \"newline\", description: \"Video prompt.\" },\n {\n type: \"image\",\n required: false,\n max: 2,\n sources: [\"url\", \"base64\"],\n description:\n \"First frame and optional tail frame image input. Provider-native image input may be passed in meta.\",\n },\n ],\n },\n parameters: klingVideoParameters({ maxDuration: 10, negativePrompt: true, seed: true }),\n examples: [\n {\n title: \"Image to video\",\n request: {\n model: \"kling-image-to-video\",\n content: [\n { type: \"text\", text: \"gently turn toward the camera with soft natural motion\" },\n { type: \"image\", source: { type: \"url\", url: \"https://example.com/input.png\" } },\n ],\n parameters: { duration: 5, aspect_ratio: \"16:9\" },\n },\n },\n ],\n },\n {\n schema: MODEL_SCHEMA,\n model: \"kling-omni-video\",\n title: \"Kling Omni Video\",\n description: \"Kling latest Omni-Video generation through Neta Router.\",\n adapter: { type: \"kling.videoGenerations\" },\n content: {\n input: [\n {\n type: \"text\",\n required: false,\n max: 16,\n merge: \"newline\",\n description: \"Optional video prompt. Use Kling Omni placeholders such as <<<image_1>>> with image_list.\",\n },\n {\n type: \"image\",\n required: false,\n max: 2,\n sources: [\"url\", \"base64\"],\n description: \"Optional simple image input. Provider-native Omni media arrays belong in request meta.\",\n },\n ],\n },\n parameters: klingVideoParameters({ maxDuration: 15, sound: true }),\n meta: {\n fields: {\n multi_shot: {\n type: \"boolean\",\n optional: true,\n description: \"Enable Kling Omni multi-shot mode.\",\n },\n shot_type: {\n type: \"string\",\n optional: true,\n description: \"Kling Omni shot type.\",\n },\n },\n },\n examples: [\n {\n title: \"Omni text to video\",\n request: {\n model: \"kling-omni-video\",\n content: [{ type: \"text\", text: \"a small paper boat floating on calm water, cinematic motion\" }],\n parameters: { duration: 5, aspect_ratio: \"16:9\", mode: \"std\" },\n },\n },\n {\n title: \"Omni image to video\",\n request: {\n model: \"kling-omni-video\",\n content: [{ type: \"text\", text: \"<<<image_1>>> gently turns toward the camera with soft natural motion\" }],\n parameters: { duration: 5, aspect_ratio: \"16:9\" },\n meta: {\n image_list: [{ image_url: \"https://example.com/input.png\", type: \"first_frame\" }],\n },\n },\n },\n ],\n },\n {\n schema: MODEL_SCHEMA,\n model: \"kling-multi-image-to-video\",\n title: \"Kling Multi-Image Reference To Video\",\n description: \"Kling latest multi-image reference video generation through Neta Router.\",\n adapter: { type: \"kling.videoGenerations\" },\n content: {\n input: [\n { type: \"text\", required: true, min: 1, max: 16, merge: \"newline\", description: \"Video prompt.\" },\n {\n type: \"image\",\n required: false,\n max: 4,\n sources: [\"url\", \"base64\"],\n description: \"Reference image inputs. Provider-native image_list input may be passed in meta.\",\n },\n ],\n },\n parameters: klingVideoParameters({ maxDuration: 10, negativePrompt: true, seed: true }),\n examples: [\n {\n title: \"Multi-image reference to video\",\n request: {\n model: \"kling-multi-image-to-video\",\n content: [\n { type: \"text\", text: \"combine the references into one cinematic shot\" },\n { type: \"image\", source: { type: \"url\", url: \"https://example.com/reference-1.png\" } },\n { type: \"image\", source: { type: \"url\", url: \"https://example.com/reference-2.png\" } },\n ],\n parameters: { duration: 5, aspect_ratio: \"16:9\" },\n },\n },\n ],\n },\n {\n schema: MODEL_SCHEMA,\n model: \"noobxl-t2i-onediff\",\n title: \"NoobXL T2I OneDiff\",\n description: \"NoobXL text-to-image model.\",\n allowUnknownParameters: true,\n adapter: { type: \"openai.images\" },\n content: {\n input: [{ type: \"text\", required: true, min: 1, max: 16, merge: \"newline\", description: \"Prompt text.\" }],\n },\n parameters: noobxlImageParameters,\n examples: [\n {\n title: \"Text to image\",\n request: {\n model: \"noobxl-t2i-onediff\",\n content: [{ type: \"text\", text: \"anime key visual, luminous city at night, crisp linework\" }],\n parameters: { size: \"1024x1024\", negative_prompt: \"low quality, blurry\" },\n },\n },\n ],\n },\n {\n schema: MODEL_SCHEMA,\n model: \"noobxl-i2i-ipa-onediff\",\n title: \"NoobXL I2I IPA OneDiff\",\n description: \"NoobXL image-to-image model with optional face reference controls.\",\n allowUnknownParameters: true,\n adapter: { type: \"openai.images\" },\n content: {\n input: [\n { type: \"text\", required: true, min: 1, max: 16, merge: \"newline\", description: \"Prompt text.\" },\n {\n type: \"image\",\n required: true,\n min: 1,\n max: 1,\n sources: [\"url\", \"base64\"],\n description: \"Single source image.\",\n },\n ],\n },\n parameters: noobxlImageToImageParameters,\n examples: [\n {\n title: \"Image to image\",\n request: {\n model: \"noobxl-i2i-ipa-onediff\",\n content: [\n { type: \"text\", text: \"keep the character identity, redraw as a polished anime illustration\" },\n { type: \"image\", source: { type: \"url\", url: \"https://example.com/reference.png\" } },\n ],\n parameters: { size: \"1024x1024\", controlnet_weight: 0.8 },\n },\n },\n ],\n },\n {\n schema: MODEL_SCHEMA,\n model: \"birefnet-general\",\n title: \"BiRefNet General\",\n description: \"BiRefNet single-image segmentation and background removal model.\",\n adapter: { type: \"openai.images\" },\n content: {\n input: [\n {\n type: \"image\",\n required: true,\n min: 1,\n max: 1,\n sources: [\"url\", \"base64\"],\n description: \"Single source image.\",\n },\n ],\n },\n examples: [\n {\n title: \"Remove background\",\n request: {\n model: \"birefnet-general\",\n content: [{ type: \"image\", source: { type: \"url\", url: \"https://example.com/portrait.png\" } }],\n },\n },\n ],\n },\n {\n schema: MODEL_SCHEMA,\n model: \"seedance-2-0\",\n title: \"Seedance 2.0\",\n description: \"Higher quality Ark video generation model for final production outputs.\",\n adapter: { type: \"ark.videoGenerations\" },\n content: {\n input: [\n { type: \"text\", required: true, min: 1, max: 16, merge: \"newline\", description: \"Video prompt.\" },\n {\n type: \"image\",\n required: false,\n max: 9,\n sources: [\"url\", \"base64\"],\n description: \"Optional image input. Use meta.role as first_frame, last_frame, or reference_image.\",\n },\n ],\n },\n parameters: videoParameters({ resolution: \"1080p\", maxWait: 900 }),\n examples: [\n {\n title: \"Text to video\",\n request: {\n model: \"seedance-2-0\",\n content: [\n {\n type: \"text\",\n text: \"a cat playing piano in a cozy jazz club, cinematic lighting, smooth camera movement\",\n },\n ],\n parameters: { duration: 5, resolution: \"1080p\", aspect_ratio: \"16:9\" },\n },\n },\n ],\n },\n {\n schema: MODEL_SCHEMA,\n model: \"seedance-2-0-fast\",\n title: \"Seedance 2.0 Fast\",\n description:\n \"Fast Ark video generation model for drafts, rapid iteration, text-to-video, image-to-video, and reference-guided video generation.\",\n adapter: { type: \"ark.videoGenerations\" },\n content: {\n input: [\n { type: \"text\", required: true, min: 1, max: 16, merge: \"newline\", description: \"Video prompt.\" },\n {\n type: \"image\",\n required: false,\n max: 9,\n sources: [\"url\", \"base64\"],\n description: \"Optional image input. Use meta.role as first_frame, last_frame, or reference_image.\",\n },\n ],\n },\n parameters: videoParameters({ resolution: \"720p\", maxWait: 600 }),\n examples: [\n {\n title: \"Text to video\",\n request: {\n model: \"seedance-2-0-fast\",\n content: [\n {\n type: \"text\",\n text: \"a cat playing piano in a cozy jazz club, cinematic lighting, smooth camera movement\",\n },\n ],\n parameters: { duration: 5, resolution: \"720p\", aspect_ratio: \"16:9\" },\n },\n },\n ],\n },\n ...sunoModels,\n] satisfies GenerationModelDeclaration[];\n\nexport const builtinGenerationModels: GenerationModelDeclaration[] = cloneJson(builtinModels);\n\nexport function getBuiltinGenerationModel(model: string): GenerationModelDeclaration | null {\n return cloneJson(builtinModels.find((declaration) => declaration.model === model) ?? null);\n}\n\nexport function listBuiltinGenerationModels(): GenerationModelDeclaration[] {\n return cloneJson(builtinModels);\n}\n"],"mappings":";AAAA,MAAa,eAAe;;;;ACE5B,SAAgB,UAAa,OAAa;AACxC,QAAO,KAAK,MAAM,KAAK,UAAU,MAAM,CAAC;;AAG1C,SAAgB,gBAAgB,OAAuB;AACrD,QACE,MACG,MAAM,CACN,aAAa,CACb,QAAQ,kBAAkB,IAAI,CAC9B,QAAQ,YAAY,GAAG,IAAI;;AAIlC,SAAgB,aAAa,OAAoE;AAC/F,QAAO,UAAU,QAAQ,MAAM,O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AO;EACP,OAAO;EACP,aACE;EACF,SAAS,EAAE,MAAM,wBAAwB;EACzC,SAAS,EACP,OAAO,CACL;GAAE,MAAM;GAAQ,UAAU;GAAM,KAAK;GAAG,KAAK;GAAI,OAAO;GAAW,aAAa;GAAiB,EACjG;GACE,MAAM;GACN,UAAU;GACV,KAAK;GACL,SAAS,CAAC,OAAO,SAAS;GAC1B,aAAa;GACd,CACF,EACF;EACD,YAAY,gBAAgB;GAAE,YAAY;GAAQ,SAAS;GAAK,CAAC;EACjE,UAAU,CACR;GACE,OAAO;GACP,SAAS;IACP,OAAO;IACP,SAAS,CACP;KACE,MAAM;KACN,MAAM;KACP,CACF;IACD,YAAY;KAAE,UAAU;KAAG,YAAY;KAAQ,cAAc;KAAQ;IACtE;GACF,CACF;EACF;CACD,GAAG;CACJ;AAED,MAAaC,0BAAwD,UAAU,cAAc;AAE7F,SAAgB,0BAA0B,OAAkD;AAC1F,QAAO,UAAU,cAAc,MAAM,gBAAgB,YAAY,UAAU,MAAM,IAAI,KAAK;;AAG5F,SAAgB,8BAA4D;AAC1E,QAAO,UAAU,cAAc"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"export-config-1c3HS6eX.js","names":["output: Record<string, string>","resolved: Record<string, unknown>","merged: Record<string, unknown>","REQUEST_TIMEOUT_MS","DEFAULT_POLL_INTERVAL_SEC","DEFAULT_MAX_WAIT_SEC","RESOLUTION_SHORT_EDGE: Record<string, number>","ASPECT_RATIOS: Record<string, [number, number] | null>","sleep","asString","asNumber","normalizeStatus","getImageRole","content: Array<Record<string, unknown>>","extractTaskId","metadata: Record<string, unknown>","requestJson","payload: Record<string, unknown>","output: GenerationContentBlock[]","REQUEST_TIMEOUT_MS","generationConfig: Record<string, unknown>","image: Record<string, string>","output: GenerationContentBlock[]","REQUEST_TIMEOUT_MS","DEFAULT_POLL_INTERVAL_SEC","DEFAULT_MAX_WAIT_SEC","KLING_MODELS: Record<\n string,\n {\n submitPath: string;\n defaultModelName: string;\n imageMode: KlingImageMode;\n allowPromptlessOmni?: boolean;\n }\n>","sleep","asString","asInteger","isRecord","normalizeStatus","buildPayload","payload: Record<string, unknown>","extractTaskId","requestJson","parsed: unknown","REQUEST_TIMEOUT_MS","payload: Record<string, unknown>","output: GenerationContentBlock[]","OPERATION_PATHS: Record<\n string,\n { path: string; poll: boolean; defaultMusicVersion?: boolean; textField?: string; requireText?: boolean }\n>","isRecord","payload: Record<string, unknown>","imageUrl: string | undefined","videoUrl: string | undefined","parsed: TaskResponse","output: GenerationContentBlock[]","raw: TaskResponse","builtinGenerationAdapters: Record<string, GenerationAdapter>","parseYaml","stringifyYaml","defaultGenerationSourceResolver: GenerationSourceResolver","output: Record<string, unknown>"],"sources":["../src/errors.ts","../src/http.ts","../src/validation.ts","../src/adapters/ark-video-generations.ts","../src/adapters/gemini-generate-content.ts","../src/adapters/kling-video-generations.ts","../src/adapters/openai-images.ts","../src/adapters/suno-tasks.ts","../src/adapters/index.ts","../src/config.ts","../src/source.ts","../src/client.ts","../src/export-config.ts"],"sourcesContent":["export class GenerationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"GenerationError\";\n }\n}\n\nexport class GenerationConfigError extends GenerationError {\n constructor(message: string) {\n super(message);\n this.name = \"GenerationConfigError\";\n }\n}\n\nexport class GenerationValidationError extends GenerationError {\n constructor(message: string) {\n super(message);\n this.name = \"GenerationValidationError\";\n }\n}\n\nexport class GenerationUnsupportedAdapterError extends GenerationError {\n constructor(adapterType: string) {\n super(`Unsupported generation adapter: ${adapterType}`);\n this.name = \"GenerationUnsupportedAdapterError\";\n }\n}\n\nexport class GenerationProviderError extends GenerationError {\n readonly status: number | undefined;\n readonly body: string | undefined;\n readonly details: Record<string, unknown> | undefined;\n\n constructor(\n message = \"Generation provider request failed\",\n options?: { status?: number; body?: string; details?: Record<string, unknown> },\n ) {\n super(message);\n this.name = \"GenerationProviderError\";\n this.status = options?.status;\n this.body = options?.body;\n this.details = options?.details;\n }\n}\n\nexport class GenerationTimeoutError extends GenerationProviderError {\n constructor(message = \"Generation request timed out\", details?: Record<string, unknown>) {\n super(message, details ? { details } : undefined);\n this.name = \"GenerationTimeoutError\";\n }\n}\n","import { GenerationTimeoutError } from \"./errors.js\";\nimport type { GenerationDebugConfig } from \"./types.js\";\n\nfunction headersToRecord(headers: HeadersInit | undefined): Record<string, string> {\n if (!headers) return {};\n if (headers instanceof Headers) {\n const output: Record<string, string> = {};\n headers.forEach((value, key) => {\n output[key] = value;\n });\n return output;\n }\n if (Array.isArray(headers)) return Object.fromEntries(headers.map(([key, value]) => [key, value]));\n return { ...headers };\n}\n\nfunction parseJsonBody(body: string): unknown {\n try {\n return JSON.parse(body);\n } catch {\n return body;\n }\n}\n\nfunction parseDebugBody(body: BodyInit | null | undefined): unknown {\n if (typeof body !== \"string\") return body ? \"[non-string body]\" : undefined;\n return parseJsonBody(body);\n}\n\nconst TRACE_HEADER_PATTERN =\n /(^|[-_])(request|trace|span|correlation|cf-ray|x-tt-logid)([-_]|$)|^(x-request-id|x-trace-id|x-correlation-id|traceparent|tracestate|cf-ray|server-timing)$/i;\n\nfunction pickTraceHeaders(headers: Record<string, string>): Record<string, string> {\n const output: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n if (TRACE_HEADER_PATTERN.test(key)) output[key] = value;\n }\n return output;\n}\n\nfunction emitDebugRequest(debug: GenerationDebugConfig, url: string, init: RequestInit): number {\n debug.logger({\n type: \"request\",\n url,\n method: init.method ?? \"GET\",\n headers: headersToRecord(init.headers),\n body: parseDebugBody(init.body),\n });\n return Date.now();\n}\n\nasync function readDebugResponseBody(response: Response): Promise<unknown> {\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (contentType.includes(\"application/json\") || contentType.includes(\"+json\")) {\n return parseJsonBody(await response.clone().text());\n }\n if (contentType.startsWith(\"text/\")) return response.clone().text();\n return \"[non-text body]\";\n}\n\nasync function emitDebugResponse(\n debug: GenerationDebugConfig,\n url: string,\n response: Response,\n startedAt: number,\n): Promise<void> {\n const headers = headersToRecord(response.headers);\n debug.logger({\n type: \"response\",\n url,\n status: response.status,\n statusText: response.statusText,\n headers,\n trace: pickTraceHeaders(headers),\n elapsedMs: Date.now() - startedAt,\n ...(debug.includeResponseBody ? { body: await readDebugResponseBody(response) } : {}),\n });\n}\n\nexport function createDebugFetch(fetchFn: typeof fetch, debug: GenerationDebugConfig): typeof fetch {\n return (async (input: string | URL | Request, init?: RequestInit) => {\n const url = String(input instanceof Request ? input.url : input);\n const requestInit = init ?? (input instanceof Request ? input : {});\n const startedAt = emitDebugRequest(debug, url, requestInit);\n const response = await fetchFn(input, init);\n await emitDebugResponse(debug, url, response, startedAt);\n return response;\n }) as typeof fetch;\n}\n\nexport async function fetchWithTimeout(\n fetchFn: typeof fetch,\n url: string,\n init: RequestInit,\n timeoutMs: number,\n): Promise<Response> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), timeoutMs);\n try {\n return await fetchFn(url, { ...init, signal: controller.signal });\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") throw new GenerationTimeoutError();\n throw error;\n } finally {\n clearTimeout(timeout);\n }\n}\n\nexport function joinUrl(baseUrl: string, path: string): string {\n return `${baseUrl.replace(/\\/+$/, \"\")}/${path.replace(/^\\/+/, \"\")}`;\n}\n","import { GenerationValidationError } from \"./errors.js\";\nimport type {\n GenerationContentBlock,\n GenerationContentSpec,\n GenerationMetaFieldSpec,\n GenerationModelDeclaration,\n GenerationParameterSpec,\n} from \"./types.js\";\n\nfunction specsByType(specs: GenerationContentSpec[]) {\n const map = new Map<GenerationContentSpec[\"type\"], GenerationContentSpec>();\n for (const spec of specs) map.set(spec.type, spec);\n return map;\n}\n\nexport function validateGenerationContent(\n declaration: GenerationModelDeclaration,\n content: GenerationContentBlock[],\n): void {\n const inputSpecs = specsByType(declaration.content.input);\n const counts = new Map<GenerationContentSpec[\"type\"], number>();\n\n for (const block of content) {\n const spec = inputSpecs.get(block.type);\n if (!spec)\n throw new GenerationValidationError(`Content block type is not supported by ${declaration.model}: ${block.type}`);\n counts.set(block.type, (counts.get(block.type) ?? 0) + 1);\n\n if (\"source\" in block && spec.sources && !spec.sources.includes(block.source.type)) {\n throw new GenerationValidationError(\n `${block.type} source is not supported by ${declaration.model}: ${block.source.type}`,\n );\n }\n }\n\n for (const spec of declaration.content.input) {\n const count = counts.get(spec.type) ?? 0;\n if (spec.required && count === 0)\n throw new GenerationValidationError(`Missing required ${spec.type} content block`);\n if (spec.min !== undefined && count < spec.min)\n throw new GenerationValidationError(`Expected at least ${spec.min} ${spec.type} content block(s)`);\n if (spec.max !== undefined && count > spec.max)\n throw new GenerationValidationError(`Expected at most ${spec.max} ${spec.type} content block(s)`);\n }\n}\n\nexport function resolveGenerationParameters(\n declaration: GenerationModelDeclaration,\n parameters: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n const specs = declaration.parameters ?? {};\n const resolved: Record<string, unknown> = {};\n const allowUnknownParameters = declaration.allowUnknownParameters ?? false;\n\n for (const key of Object.keys(parameters ?? {})) {\n if (!specs[key]) {\n if (!allowUnknownParameters) throw new GenerationValidationError(`Unknown parameter: ${key}`);\n const value = parameters?.[key];\n if (value !== undefined) resolved[key] = value;\n }\n }\n\n for (const [key, spec] of Object.entries(specs)) {\n const value = parameters?.[key];\n if (value === undefined) {\n if (spec.default !== undefined) resolved[key] = spec.default;\n else if (!spec.optional) throw new GenerationValidationError(`Missing required parameter: ${key}`);\n continue;\n }\n\n validateSpecValue(`Parameter ${key}`, spec, value);\n resolved[key] = value;\n }\n\n return resolved;\n}\n\nexport function mergeGenerationMeta(\n requestMeta: Record<string, unknown> | undefined,\n content: GenerationContentBlock[],\n): Record<string, unknown> {\n const merged: Record<string, unknown> = {};\n mergeMetaFields(merged, requestMeta);\n for (const block of content) {\n mergeMetaFields(merged, block.meta);\n }\n return merged;\n}\n\nfunction normalizeMetaKey(key: string): string {\n return key === \"metadataParams\" ? \"metadata_params\" : key;\n}\n\nfunction mergeMetaFields(target: Record<string, unknown>, meta: Record<string, unknown> | undefined): void {\n for (const [key, value] of Object.entries(meta ?? {})) {\n const normalizedKey = normalizeMetaKey(key);\n if (value !== undefined && target[normalizedKey] === undefined) target[normalizedKey] = value;\n }\n}\n\nfunction validateSpecValue(\n label: string,\n spec: GenerationParameterSpec | GenerationMetaFieldSpec,\n value: unknown,\n): void {\n switch (spec.type) {\n case \"string\":\n if (typeof value !== \"string\") throw new GenerationValidationError(`${label} must be a string`);\n if (spec.enum && !spec.enum.includes(value))\n throw new GenerationValidationError(`${label} must be one of: ${spec.enum.join(\", \")}`);\n break;\n case \"number\":\n if (typeof value !== \"number\" || !Number.isFinite(value))\n throw new GenerationValidationError(`${label} must be a number`);\n if (spec.min !== undefined && value < spec.min)\n throw new GenerationValidationError(`${label} must be >= ${spec.min}`);\n if (spec.max !== undefined && value > spec.max)\n throw new GenerationValidationError(`${label} must be <= ${spec.max}`);\n break;\n case \"integer\":\n if (typeof value !== \"number\" || !Number.isInteger(value))\n throw new GenerationValidationError(`${label} must be an integer`);\n if (spec.min !== undefined && value < spec.min)\n throw new GenerationValidationError(`${label} must be >= ${spec.min}`);\n if (spec.max !== undefined && value > spec.max)\n throw new GenerationValidationError(`${label} must be <= ${spec.max}`);\n break;\n case \"boolean\":\n if (typeof value !== \"boolean\") throw new GenerationValidationError(`${label} must be a boolean`);\n break;\n case \"object\":\n if (!value || typeof value !== \"object\" || Array.isArray(value))\n throw new GenerationValidationError(`${label} must be an object`);\n break;\n }\n}\n\nexport function resolveGenerationMeta(\n declaration: GenerationModelDeclaration,\n meta: Record<string, unknown> | undefined,\n content: GenerationContentBlock[],\n): Record<string, unknown> {\n const specs = declaration.meta?.fields ?? {};\n const resolved: Record<string, unknown> = {};\n\n for (const key of Object.keys(meta ?? {})) {\n if (!specs[key]) {\n const value = meta?.[key];\n if (value !== undefined) resolved[key] = value;\n }\n }\n\n for (const [key, spec] of Object.entries(specs)) {\n const value = meta?.[key];\n if (value === undefined) {\n if (!spec.optional) throw new GenerationValidationError(`Missing required meta: ${key}`);\n continue;\n }\n validateSpecValue(`meta.${key}`, spec, value);\n resolved[key] = value;\n }\n\n const taskField = declaration.meta?.taskField;\n const task = taskField && typeof resolved[taskField] === \"string\" ? resolved[taskField] : undefined;\n if (!task) return resolved;\n\n const variant = declaration.meta?.taskVariants?.[task];\n if (!variant) throw new GenerationValidationError(`Unsupported meta.${taskField}: ${task}`);\n\n for (const key of variant.required ?? []) {\n if (resolved[key] === undefined || resolved[key] === null || resolved[key] === \"\") {\n throw new GenerationValidationError(`meta.${taskField} ${task} requires meta.${key}`);\n }\n }\n\n for (const type of variant.requiredContent ?? []) {\n if (!content.some((block) => block.type === type)) {\n throw new GenerationValidationError(`meta.${taskField} ${task} requires ${type} content`);\n }\n }\n\n return resolved;\n}\n\nexport function mergeTextBlocks(declaration: GenerationModelDeclaration, content: GenerationContentBlock[]): string {\n const textSpec = declaration.content.input.find((spec) => spec.type === \"text\");\n const separator = textSpec?.merge === \"space\" ? \" \" : textSpec?.merge === \"concat\" ? \"\" : \"\\n\";\n return content\n .filter((block): block is Extract<GenerationContentBlock, { type: \"text\" }> => block.type === \"text\")\n .map((block) => block.text)\n .join(separator)\n .trim();\n}\n","import { GenerationProviderError, GenerationTimeoutError, GenerationValidationError } from \"../errors.js\";\nimport { fetchWithTimeout, joinUrl } from \"../http.js\";\nimport type { GenerationAdapterInput, GenerationContentBlock } from \"../types.js\";\nimport { compactObject, getBlockMeta } from \"../utils.js\";\nimport { mergeTextBlocks } from \"../validation.js\";\n\nconst REQUEST_TIMEOUT_MS = 60_000;\nconst DEFAULT_POLL_INTERVAL_SEC = 2;\nconst DEFAULT_MAX_WAIT_SEC = 600;\n\nconst RESOLUTION_SHORT_EDGE: Record<string, number> = {\n \"480p\": 480,\n \"720p\": 720,\n \"1080p\": 1080,\n \"2K\": 1440,\n};\n\nconst ASPECT_RATIOS: Record<string, [number, number] | null> = {\n \"16:9\": [16, 9],\n \"9:16\": [9, 16],\n \"1:1\": [1, 1],\n \"4:3\": [4, 3],\n \"3:2\": [3, 2],\n \"2:3\": [2, 3],\n \"3:4\": [3, 4],\n \"21:9\": [21, 9],\n adaptive: null,\n};\n\ntype ArkCreateTaskResponse = { id?: unknown; task_id?: unknown; status?: unknown };\n\ntype ArkTaskStatusResponse = {\n data?: {\n status?: unknown;\n result_url?: unknown;\n progress?: unknown;\n first_frame?: unknown;\n data?: {\n status?: unknown;\n content?: { video_url?: unknown; first_frame?: unknown };\n resolution?: unknown;\n ratio?: unknown;\n duration?: unknown;\n framespersecond?: unknown;\n seed?: unknown;\n generate_audio?: unknown;\n model?: unknown;\n usage?: unknown;\n };\n };\n};\n\ntype ImageMode = \"image\" | \"frame\" | \"reference\";\ntype ResolvedImage = { url: string; role: string | undefined };\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction asString(value: unknown): string | undefined {\n return typeof value === \"string\" && value ? value : undefined;\n}\n\nfunction asNumber(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\nfunction asBoolean(value: unknown): boolean | undefined {\n return typeof value === \"boolean\" ? value : undefined;\n}\n\nfunction normalizeStatus(value: string): string {\n const status = value.toLowerCase();\n return status === \"success\" ? \"succeeded\" : status;\n}\n\nfunction getIntegerParameter(parameters: Record<string, unknown>, key: string, fallback: number): number {\n const value = parameters[key];\n return typeof value === \"number\" && Number.isInteger(value) ? value : fallback;\n}\n\nfunction resolveSize(resolution: string, aspectRatio: string): { width: number; height: number } | null {\n const ratio = ASPECT_RATIOS[aspectRatio];\n if (!ratio) return null;\n\n const shortEdge = RESOLUTION_SHORT_EDGE[resolution];\n if (!shortEdge) throw new GenerationValidationError(`Unsupported resolution: ${resolution}`);\n\n const [wRatio, hRatio] = ratio;\n const width = wRatio >= hRatio ? Math.round((shortEdge * wRatio) / hRatio) : shortEdge;\n const height = wRatio >= hRatio ? shortEdge : Math.round((shortEdge * hRatio) / wRatio);\n return { width: width % 2 === 0 ? width : width + 1, height: height % 2 === 0 ? height : height + 1 };\n}\n\nfunction getImageRole(block: Extract<GenerationContentBlock, { type: \"image\" }>): string | undefined {\n const role = getBlockMeta(block)?.role;\n return typeof role === \"string\" && role ? role : undefined;\n}\n\nfunction classifyImages(images: ResolvedImage[]): ImageMode | null {\n if (images.length === 0) return null;\n const hasFirstOrLast = images.some((image) => image.role === \"first_frame\" || image.role === \"last_frame\");\n const hasReference = images.some((image) => image.role === \"reference_image\");\n const hasPlain = images.some((image) => !image.role);\n const modes = [hasPlain, hasFirstOrLast, hasReference].filter(Boolean).length;\n if (modes > 1)\n throw new GenerationValidationError(\n \"Cannot mix video image modes: use only plain image, first_frame/last_frame, or reference_image\",\n );\n if (hasReference) return \"reference\";\n if (hasFirstOrLast) return \"frame\";\n return \"image\";\n}\n\nfunction buildMetadataContent(prompt: string, images: ResolvedImage[], mode: Exclude<ImageMode, \"image\">) {\n const content: Array<Record<string, unknown>> = [{ type: \"text\", text: prompt }];\n for (const image of images) {\n if (mode === \"frame\" && image.role !== \"first_frame\" && image.role !== \"last_frame\") {\n throw new GenerationValidationError(\"Frame mode images must use meta.role first_frame or last_frame\");\n }\n if (mode === \"reference\" && image.role !== \"reference_image\") {\n throw new GenerationValidationError(\"Reference mode images must use meta.role reference_image\");\n }\n content.push({ type: \"image_url\", image_url: { url: image.url }, role: image.role });\n }\n return content;\n}\n\nfunction extractTaskId(response: ArkCreateTaskResponse): string {\n const taskId = asString(response.task_id) ?? asString(response.id);\n if (!taskId) {\n throw new GenerationProviderError(\"Video generation provider did not return a task id\", {\n details: { response },\n });\n }\n return taskId;\n}\n\nfunction normalizeTaskStatus(response: ArkTaskStatusResponse) {\n if (response.data) {\n const wrapper = response.data;\n const native = wrapper.data;\n const status = normalizeStatus(asString(native?.status) ?? asString(wrapper.status) ?? \"unknown\");\n const videoUrl = asString(wrapper.result_url) ?? asString(native?.content?.video_url);\n const lastFrameUrl = asString(wrapper.first_frame) ?? asString(native?.content?.first_frame);\n const metadata: Record<string, unknown> = {\n progress: wrapper.progress,\n resolution: native?.resolution,\n ratio: native?.ratio,\n duration: native?.duration,\n framespersecond: native?.framespersecond,\n seed: native?.seed,\n generate_audio: native?.generate_audio,\n model: native?.model,\n usage: native?.usage,\n };\n for (const key of Object.keys(metadata)) if (metadata[key] === undefined) delete metadata[key];\n return { status, videoUrl, lastFrameUrl, metadata };\n }\n return { status: \"unknown\", videoUrl: undefined, lastFrameUrl: undefined, metadata: {} };\n}\n\nasync function requestJson(input: GenerationAdapterInput, path: string, init: RequestInit): Promise<unknown> {\n const response = await fetchWithTimeout(\n input.context.fetch,\n joinUrl(input.context.baseUrl, path),\n {\n ...init,\n headers: {\n Authorization: `Bearer ${input.context.apiKey}`,\n \"Content-Type\": \"application/json\",\n ...init.headers,\n },\n },\n REQUEST_TIMEOUT_MS,\n );\n\n if (!response.ok) {\n const body = await response.text().catch(() => response.statusText);\n throw new GenerationProviderError(\"Video generation provider request failed\", { status: response.status, body });\n }\n return response.json();\n}\n\nexport async function arkVideoGenerationsAdapter(input: GenerationAdapterInput): Promise<GenerationContentBlock[]> {\n const prompt = mergeTextBlocks(input.declaration, input.request.content);\n if (!prompt) throw new GenerationValidationError(\"Prompt text is required\");\n\n const imageBlocks = input.request.content.filter(\n (block): block is Extract<GenerationContentBlock, { type: \"image\" }> => block.type === \"image\",\n );\n const images = await Promise.all(\n imageBlocks.map(async (block) => ({\n url: await input.context.resolveSource(block.source),\n role: getImageRole(block),\n })),\n );\n\n const mode = classifyImages(images);\n const resolution = asString(input.parameters.resolution) ?? \"720p\";\n const aspectRatio = asString(input.parameters.aspect_ratio) ?? \"16:9\";\n const duration = getIntegerParameter(input.parameters, \"duration\", 5);\n const fps = getIntegerParameter(input.parameters, \"fps\", 30);\n const pollIntervalSec = getIntegerParameter(input.parameters, \"poll_interval\", DEFAULT_POLL_INTERVAL_SEC);\n const maxWaitSec = getIntegerParameter(input.parameters, \"max_wait\", DEFAULT_MAX_WAIT_SEC);\n const generateAudio = asBoolean(input.parameters.generate_audio) ?? true;\n const returnLastFrame = asBoolean(input.parameters.return_last_frame) ?? true;\n const cameraFixed = asBoolean(input.parameters.camera_fixed) ?? false;\n const watermark = asBoolean(input.parameters.watermark) ?? false;\n const seed = asNumber(input.parameters.seed);\n\n const payload: Record<string, unknown> = { model: input.declaration.model, prompt };\n const metadata: Record<string, unknown> = { duration, fps, generate_audio: generateAudio };\n if (seed !== undefined) metadata.seed = seed;\n if (returnLastFrame) metadata.return_last_frame = true;\n if (cameraFixed) metadata.camera_fixed = true;\n if (watermark) metadata.watermark = true;\n\n if (mode === \"frame\" || mode === \"reference\") {\n metadata.content = buildMetadataContent(prompt, images, mode);\n metadata.resolution = resolution;\n metadata.ratio = aspectRatio;\n } else {\n const size = resolveSize(resolution, aspectRatio);\n if (size) {\n payload.width = size.width;\n payload.height = size.height;\n }\n if (images[0]) payload.image = images[0].url;\n }\n payload.metadata = metadata;\n\n const task = (await requestJson(input, \"/v1/video/generations\", {\n method: \"POST\",\n body: JSON.stringify(payload),\n })) as ArkCreateTaskResponse;\n const taskId = extractTaskId(task);\n const startedAt = Date.now();\n\n while (Date.now() - startedAt <= maxWaitSec * 1000) {\n await sleep(pollIntervalSec * 1000);\n const rawStatus = (await requestJson(input, `/v1/video/generations/${encodeURIComponent(taskId)}`, {\n method: \"GET\",\n })) as ArkTaskStatusResponse;\n const status = normalizeTaskStatus(rawStatus);\n\n if (status.status === \"succeeded\") {\n if (!status.videoUrl) {\n throw new GenerationProviderError(\"Video generation succeeded but returned no video URL\", {\n details: compactObject({ taskId, rawStatus, metadata: status.metadata }),\n });\n }\n const output: GenerationContentBlock[] = [\n {\n type: \"video\",\n source: { type: \"url\", url: status.videoUrl },\n meta: { task_id: taskId, status: status.status, ...status.metadata },\n },\n ];\n if (status.lastFrameUrl)\n output.push({\n type: \"image\",\n source: { type: \"url\", url: status.lastFrameUrl },\n meta: { role: \"last_frame\", task_id: taskId },\n });\n return output;\n }\n\n if ([\"failed\", \"expired\", \"cancelled\"].includes(status.status)) {\n throw new GenerationProviderError(`Video generation ${status.status}`, { details: { taskId, rawStatus } });\n }\n }\n\n throw new GenerationTimeoutError(\"Timed out waiting for video generation\", { taskId });\n}\n","import { GenerationProviderError, GenerationValidationError } from \"../errors.js\";\nimport { fetchWithTimeout, joinUrl } from \"../http.js\";\nimport type { GenerationAdapterInput, GenerationContentBlock } from \"../types.js\";\nimport { compactArray, compactObject } from \"../utils.js\";\nimport { mergeTextBlocks } from \"../validation.js\";\n\nconst REQUEST_TIMEOUT_MS = 300_000;\nconst IMAGE_FETCH_TIMEOUT_MS = 60_000;\nconst MAX_REFERENCE_IMAGE_BYTES = 10 * 1024 * 1024;\n\nconst DATA_URI_PATTERN = /^data:([^;]+);base64,(.+)$/s;\nconst MARKDOWN_IMAGE_DATA_URI_PATTERN = /!\\[[^\\]]*\\]\\(data:([^;]+);base64,([^)]+)\\)/;\n\ntype GeminiPart = { text: string } | { inlineData: { mimeType: string; data: string } };\n\ntype GeminiResponsePart = {\n text?: unknown;\n inlineData?: { mimeType?: unknown; data?: unknown };\n fileData?: { mimeType?: unknown; fileUri?: unknown };\n};\n\ntype GeminiCandidate = {\n content?: { role?: unknown; parts?: GeminiResponsePart[] };\n finishReason?: unknown;\n finishMessage?: unknown;\n safetyRatings?: unknown;\n citationMetadata?: unknown;\n groundingMetadata?: unknown;\n avgLogprobs?: unknown;\n index?: unknown;\n};\n\ntype GeminiGenerateContentResponse = {\n candidates?: GeminiCandidate[];\n promptFeedback?: unknown;\n usageMetadata?: unknown;\n modelVersion?: unknown;\n responseId?: unknown;\n};\n\nfunction dataUriToInlineData(value: string): GeminiPart | null {\n const match = DATA_URI_PATTERN.exec(value);\n if (!match) return null;\n const [, mimeType, data] = match;\n if (!mimeType || !data) return null;\n return { inlineData: { mimeType, data } };\n}\n\nasync function urlToInlineData(fetchFn: typeof fetch, url: string): Promise<GeminiPart> {\n const response = await fetchWithTimeout(\n fetchFn,\n url,\n { method: \"GET\", headers: { \"User-Agent\": \"NetaGeneration/1.0\" } },\n IMAGE_FETCH_TIMEOUT_MS,\n );\n if (!response.ok) throw new GenerationProviderError(\"Failed to fetch reference image\", { status: response.status });\n\n const contentLength = response.headers.get(\"content-length\");\n if (contentLength && Number(contentLength) > MAX_REFERENCE_IMAGE_BYTES) {\n throw new GenerationValidationError(\"Reference image is too large\");\n }\n\n const bytes = Buffer.from(await response.arrayBuffer());\n if (bytes.byteLength > MAX_REFERENCE_IMAGE_BYTES) throw new GenerationValidationError(\"Reference image is too large\");\n\n const contentType = response.headers.get(\"content-type\")?.split(\";\")[0]?.trim();\n const mimeType = contentType?.startsWith(\"image/\") ? contentType : \"image/png\";\n return { inlineData: { mimeType, data: bytes.toString(\"base64\") } };\n}\n\nasync function sourceToInlineData(input: GenerationAdapterInput, value: string): Promise<GeminiPart> {\n const inline = dataUriToInlineData(value);\n if (inline) return inline;\n if (value.startsWith(\"http://\") || value.startsWith(\"https://\")) return urlToInlineData(input.context.fetch, value);\n throw new GenerationValidationError(\"Unsupported image source for Gemini image generation\");\n}\n\nfunction extractMarkdownDataUriImage(text: string): GenerationContentBlock | null {\n const match = MARKDOWN_IMAGE_DATA_URI_PATTERN.exec(text);\n if (!match) return null;\n const [, mediaType, data] = match;\n if (!mediaType || !data) return null;\n return { type: \"image\", source: { type: \"base64\", mediaType, data } };\n}\n\nfunction collectGeminiNoOutputDetails(raw: GeminiGenerateContentResponse): Record<string, unknown> {\n const candidates = raw.candidates ?? [];\n return compactObject({\n finishReasons: compactArray(\n candidates.map((candidate) => candidate.finishReason).filter((value) => value !== undefined),\n ),\n finishMessages: compactArray(\n candidates.map((candidate) => candidate.finishMessage).filter((value) => value !== undefined),\n ),\n safetyRatings: compactArray(candidates.flatMap((candidate) => candidate.safetyRatings ?? [])),\n promptFeedback: raw.promptFeedback,\n usageMetadata: raw.usageMetadata,\n modelVersion: raw.modelVersion,\n responseId: raw.responseId,\n candidateCount: candidates.length,\n candidates: compactArray(\n candidates.map((candidate) =>\n compactObject({\n index: candidate.index,\n finishReason: candidate.finishReason,\n finishMessage: candidate.finishMessage,\n safetyRatings: candidate.safetyRatings,\n citationMetadata: candidate.citationMetadata,\n groundingMetadata: candidate.groundingMetadata,\n avgLogprobs: candidate.avgLogprobs,\n contentRole: candidate.content?.role,\n partCount: candidate.content?.parts?.length,\n }),\n ),\n ),\n });\n}\n\nfunction appendGeminiFileDataOutput(\n output: GenerationContentBlock[],\n fileData: GeminiResponsePart[\"fileData\"],\n): boolean {\n if (typeof fileData?.fileUri !== \"string\" || !fileData.fileUri) return false;\n const mediaType = typeof fileData.mimeType === \"string\" ? fileData.mimeType : \"image/png\";\n output.push({ type: \"image\", source: { type: \"url\", url: fileData.fileUri }, meta: { mediaType } });\n return true;\n}\n\nfunction appendGeminiPartOutput(output: GenerationContentBlock[], part: GeminiResponsePart): void {\n if (typeof part.text === \"string\" && part.text.trim()) {\n const image = extractMarkdownDataUriImage(part.text);\n if (image) {\n output.push(image);\n return;\n }\n output.push({ type: \"text\", text: part.text });\n return;\n }\n\n if (part.inlineData && typeof part.inlineData.data === \"string\" && part.inlineData.data) {\n output.push({\n type: \"image\",\n source: {\n type: \"base64\",\n mediaType: typeof part.inlineData.mimeType === \"string\" ? part.inlineData.mimeType : \"image/png\",\n data: part.inlineData.data,\n },\n });\n return;\n }\n\n appendGeminiFileDataOutput(output, part.fileData);\n}\n\nexport async function geminiGenerateContentAdapter(input: GenerationAdapterInput): Promise<GenerationContentBlock[]> {\n const prompt = mergeTextBlocks(input.declaration, input.request.content);\n if (!prompt) throw new GenerationValidationError(\"Prompt text is required\");\n\n const imageParts = await Promise.all(\n input.request.content\n .filter((block): block is Extract<GenerationContentBlock, { type: \"image\" }> => block.type === \"image\")\n .map(async (block) => sourceToInlineData(input, await input.context.resolveSource(block.source))),\n );\n\n const generationConfig: Record<string, unknown> = { responseModalities: [\"IMAGE\"] };\n const aspectRatio = input.parameters.aspect_ratio;\n const imageSize = input.parameters.image_size;\n if (typeof aspectRatio === \"string\" || typeof imageSize === \"string\") {\n const image: Record<string, string> = {};\n if (typeof aspectRatio === \"string\") image.aspectRatio = aspectRatio;\n if (typeof imageSize === \"string\") image.imageSize = imageSize;\n generationConfig.responseFormat = { image };\n }\n\n const payload = {\n contents: [{ parts: [{ text: prompt }, ...imageParts] satisfies GeminiPart[] }],\n generationConfig,\n };\n\n const response = await fetchWithTimeout(\n input.context.fetch,\n joinUrl(input.context.baseUrl, `/v1beta/models/${encodeURIComponent(input.declaration.model)}:generateContent`),\n {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${input.context.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n },\n REQUEST_TIMEOUT_MS,\n );\n\n if (!response.ok) {\n const body = await response.text().catch(() => response.statusText);\n throw new GenerationProviderError(\"Gemini generation provider request failed\", { status: response.status, body });\n }\n\n const raw = (await response.json()) as GeminiGenerateContentResponse;\n const output: GenerationContentBlock[] = [];\n for (const candidate of raw.candidates ?? []) {\n for (const part of candidate.content?.parts ?? []) appendGeminiPartOutput(output, part);\n }\n if (output.length === 0) {\n throw new GenerationProviderError(\"Gemini generation returned no output\", {\n details: collectGeminiNoOutputDetails(raw),\n });\n }\n return output;\n}\n","import { GenerationProviderError, GenerationTimeoutError, GenerationValidationError } from \"../errors.js\";\nimport { fetchWithTimeout, joinUrl } from \"../http.js\";\nimport type { GenerationAdapterInput, GenerationContentBlock, GenerationSource } from \"../types.js\";\nimport { compactObject, getBlockMeta } from \"../utils.js\";\nimport { mergeTextBlocks } from \"../validation.js\";\n\nconst REQUEST_TIMEOUT_MS = 60_000;\nconst DEFAULT_POLL_INTERVAL_SEC = 5;\nconst DEFAULT_MAX_WAIT_SEC = 900;\n\ntype KlingImageMode = \"none\" | \"single\" | \"omni\" | \"multi\";\n\nconst KLING_MODELS: Record<\n string,\n {\n submitPath: string;\n defaultModelName: string;\n imageMode: KlingImageMode;\n allowPromptlessOmni?: boolean;\n }\n> = {\n \"kling-text-to-video\": {\n submitPath: \"/kling/v1/videos/text2video\",\n defaultModelName: \"kling-v3\",\n imageMode: \"none\",\n },\n \"kling-image-to-video\": {\n submitPath: \"/kling/v1/videos/image2video\",\n defaultModelName: \"kling-v3\",\n imageMode: \"single\",\n },\n \"kling-omni-video\": {\n submitPath: \"/kling/v1/videos/omni-video\",\n defaultModelName: \"kling-v3-omni\",\n imageMode: \"omni\",\n allowPromptlessOmni: true,\n },\n \"kling-multi-image-to-video\": {\n submitPath: \"/kling/v1/videos/multi-image2video\",\n defaultModelName: \"kling-v1-6\",\n imageMode: \"multi\",\n },\n};\n\ntype CreateTaskResponse = {\n id?: unknown;\n task_id?: unknown;\n status?: unknown;\n data?: {\n id?: unknown;\n task_id?: unknown;\n status?: unknown;\n task_status?: unknown;\n };\n};\n\ntype TaskStatusResponse = {\n code?: unknown;\n message?: unknown;\n status?: unknown;\n task_status?: unknown;\n video_url?: unknown;\n result_url?: unknown;\n url?: unknown;\n progress?: unknown;\n error?: {\n message?: unknown;\n };\n metadata?: {\n url?: unknown;\n };\n data?: {\n status?: unknown;\n task_status?: unknown;\n task_status_msg?: unknown;\n result_url?: unknown;\n video_url?: unknown;\n url?: unknown;\n progress?: unknown;\n task_result?: {\n videos?: Array<{ url?: unknown; duration?: unknown }>;\n };\n data?: {\n status?: unknown;\n content?: { video_url?: unknown; first_frame?: unknown };\n progress?: unknown;\n task_result?: {\n videos?: Array<{ url?: unknown; duration?: unknown }>;\n };\n };\n };\n};\n\ntype ResolvedImage = {\n url: string;\n role?: string;\n};\n\ntype OmniImageReference = {\n image_url: string;\n type?: string;\n};\n\ntype MultiImageReference = {\n image: string;\n};\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction asString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n}\n\nfunction asInteger(value: unknown, fallback: number): number {\n return typeof value === \"number\" && Number.isInteger(value) ? value : fallback;\n}\n\nfunction asNumber(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction providerMeta(input: Record<string, unknown>): Record<string, unknown> {\n const rest = { ...input };\n delete rest.cohub;\n delete rest.role;\n return rest;\n}\n\nfunction normalizeStatus(value: unknown): string {\n const status = String(value ?? \"\")\n .trim()\n .toLowerCase();\n if (status === \"success\" || status === \"succeed\" || status === \"succeeded\" || status === \"completed\") {\n return \"succeeded\";\n }\n if (\n status === \"queued\" ||\n status === \"processing\" ||\n status === \"in_progress\" ||\n status === \"not_start\" ||\n status === \"submitted\"\n ) {\n return \"processing\";\n }\n if (status === \"failure\" || status === \"failed\" || status === \"error\") return \"failed\";\n if (status === \"cancelled\" || status === \"canceled\") return \"cancelled\";\n return status || \"unknown\";\n}\n\nfunction getImageRole(block: Extract<GenerationContentBlock, { type: \"image\" }>): string | undefined {\n const role = getBlockMeta(block)?.role;\n return typeof role === \"string\" && role.trim() ? role.trim() : undefined;\n}\n\nasync function resolveKlingImageSource(input: GenerationAdapterInput, source: GenerationSource): Promise<string> {\n if (source.type === \"base64\") return source.data;\n return input.context.resolveSource(source);\n}\n\nasync function resolveImages(input: GenerationAdapterInput): Promise<ResolvedImage[]> {\n const imageBlocks = input.request.content.filter(\n (block): block is Extract<GenerationContentBlock, { type: \"image\" }> => block.type === \"image\",\n );\n return Promise.all(\n imageBlocks.map(async (block) => {\n const role = getImageRole(block);\n const url = await resolveKlingImageSource(input, block.source);\n return role ? { url, role } : { url };\n }),\n );\n}\n\nfunction hasOfficialOmniMedia(meta: Record<string, unknown>): boolean {\n return [\"image_list\", \"element_list\", \"video_list\"].some((key) => {\n const value = meta[key];\n return Array.isArray(value) ? value.length > 0 : value !== undefined;\n });\n}\n\nfunction hasPlainImagePayload(meta: Record<string, unknown>): boolean {\n return typeof meta.image === \"string\" && meta.image.trim().length > 0;\n}\n\nfunction hasMultiImagePayload(meta: Record<string, unknown>): boolean {\n return Array.isArray(meta.image_list) && meta.image_list.length > 0;\n}\n\nfunction hasPromptlessOmniPayload(meta: Record<string, unknown>, images: ResolvedImage[]): boolean {\n return images.length > 0 || hasOfficialOmniMedia(meta) || hasPlainImagePayload(meta);\n}\n\nfunction omniImageType(image: ResolvedImage, index: number): string | undefined {\n if (image.role === \"first_frame\" || image.role === \"end_frame\") return image.role;\n if (image.role === \"last_frame\") return \"end_frame\";\n if (!image.role) return index === 0 ? \"first_frame\" : \"end_frame\";\n return undefined;\n}\n\nfunction buildOmniImageList(images: ResolvedImage[]): OmniImageReference[] {\n return images.map((image, index) => {\n const type = omniImageType(image, index);\n return type ? { image_url: image.url, type } : { image_url: image.url };\n });\n}\n\nfunction buildMultiImageList(images: ResolvedImage[]): MultiImageReference[] {\n return images.map((image) => ({ image: image.url }));\n}\n\nfunction resolveKlingModel(input: GenerationAdapterInput) {\n const model = KLING_MODELS[input.declaration.model];\n if (!model) throw new GenerationValidationError(`Unsupported Kling generation model: ${input.declaration.model}`);\n return model;\n}\n\nfunction buildPayload(\n input: GenerationAdapterInput,\n model: (typeof KLING_MODELS)[string],\n prompt: string,\n images: ResolvedImage[],\n): Record<string, unknown> {\n const payload: Record<string, unknown> = {\n ...providerMeta(input.meta),\n model_name: model.defaultModelName,\n };\n\n if (prompt) payload.prompt = prompt;\n if (!payload.duration) payload.duration = String(asInteger(input.parameters.duration, 5));\n if (!payload.mode) payload.mode = asString(input.parameters.mode) ?? \"std\";\n if (payload.cfg_scale === undefined) payload.cfg_scale = asNumber(input.parameters.cfg_scale) ?? 0.5;\n if (!payload.aspect_ratio) payload.aspect_ratio = asString(input.parameters.aspect_ratio) ?? \"16:9\";\n if (payload.negative_prompt === undefined && asString(input.parameters.negative_prompt)) {\n payload.negative_prompt = input.parameters.negative_prompt;\n }\n if (payload.sound === undefined && asString(input.parameters.sound)) payload.sound = input.parameters.sound;\n if (model.imageMode === \"single\" && images[0] && !hasPlainImagePayload(payload)) {\n payload.image = images[0].url;\n if (images[1] && payload.image_tail === undefined) payload.image_tail = images[1].url;\n }\n if (\n model.imageMode === \"omni\" &&\n images.length > 0 &&\n !hasOfficialOmniMedia(payload) &&\n !hasPlainImagePayload(payload)\n ) {\n payload.image_list = buildOmniImageList(images);\n }\n if (model.imageMode === \"multi\" && images.length > 0 && !hasMultiImagePayload(payload)) {\n payload.image_list = buildMultiImageList(images);\n }\n if (payload.seed === undefined && input.parameters.seed !== undefined) payload.seed = input.parameters.seed;\n\n return payload;\n}\n\nfunction extractTaskId(response: CreateTaskResponse): string {\n const taskId =\n asString(response.task_id) ??\n asString(response.id) ??\n asString(response.data?.task_id) ??\n asString(response.data?.id);\n if (!taskId) {\n throw new GenerationProviderError(\"Kling video provider did not return a task id\", { details: { response } });\n }\n return taskId;\n}\n\nfunction extractStatus(response: TaskStatusResponse) {\n const wrapper = response.data;\n const native = wrapper?.data;\n const status = normalizeStatus(\n native?.status ?? wrapper?.task_status ?? wrapper?.status ?? response.task_status ?? response.status,\n );\n const firstVideo = wrapper?.task_result?.videos?.[0] ?? native?.task_result?.videos?.[0];\n const videoUrl =\n asString(firstVideo?.url) ??\n asString(wrapper?.result_url) ??\n asString(wrapper?.video_url) ??\n asString(wrapper?.url) ??\n asString(native?.content?.video_url) ??\n asString(response.metadata?.url) ??\n asString(response.result_url) ??\n asString(response.video_url) ??\n asString(response.url);\n const message = asString(wrapper?.task_status_msg) ?? asString(response.error?.message) ?? asString(response.message);\n return {\n status,\n videoUrl,\n message,\n metadata: compactObject({\n progress: wrapper?.progress ?? native?.progress ?? response.progress,\n duration: firstVideo?.duration,\n task_status_msg: message,\n code: response.code,\n }),\n };\n}\n\nasync function requestJson(input: GenerationAdapterInput, path: string, init: RequestInit): Promise<unknown> {\n const response = await fetchWithTimeout(\n input.context.fetch,\n joinUrl(input.context.baseUrl, path),\n {\n ...init,\n headers: {\n Authorization: `Bearer ${input.context.apiKey}`,\n \"Content-Type\": \"application/json\",\n ...init.headers,\n },\n },\n REQUEST_TIMEOUT_MS,\n );\n const body = await response.text();\n let parsed: unknown = {};\n try {\n parsed = body ? JSON.parse(body) : {};\n } catch {\n throw new GenerationProviderError(\"Kling video provider returned invalid JSON\", { status: response.status, body });\n }\n if (!response.ok) {\n const details = isRecord(parsed) ? { details: parsed } : {};\n throw new GenerationProviderError(\"Kling video provider request failed\", {\n status: response.status,\n body,\n ...details,\n });\n }\n return parsed;\n}\n\nexport async function klingVideoGenerationsAdapter(input: GenerationAdapterInput): Promise<GenerationContentBlock[]> {\n const model = resolveKlingModel(input);\n const prompt = mergeTextBlocks(input.declaration, input.request.content);\n const images = await resolveImages(input);\n const meta = providerMeta(input.meta);\n\n if (!prompt && !model.allowPromptlessOmni) throw new GenerationValidationError(\"Prompt text is required\");\n if (!prompt && model.allowPromptlessOmni && !hasPromptlessOmniPayload(meta, images)) {\n throw new GenerationValidationError(\"Prompt text or Omni media input is required\");\n }\n if (model.imageMode === \"single\" && images.length === 0 && !hasPlainImagePayload(meta)) {\n throw new GenerationValidationError(\"Image input is required\");\n }\n if (model.imageMode === \"multi\" && images.length === 0 && !hasMultiImagePayload(meta)) {\n throw new GenerationValidationError(\"Multi-image input is required\");\n }\n\n const task = (await requestJson(input, model.submitPath, {\n method: \"POST\",\n body: JSON.stringify(buildPayload(input, model, prompt, images)),\n })) as CreateTaskResponse;\n const taskId = extractTaskId(task);\n const pollIntervalSec = asInteger(input.parameters.poll_interval, DEFAULT_POLL_INTERVAL_SEC);\n const maxWaitSec = asInteger(input.parameters.max_wait, DEFAULT_MAX_WAIT_SEC);\n const startedAt = Date.now();\n\n while (Date.now() - startedAt <= maxWaitSec * 1000) {\n await sleep(pollIntervalSec * 1000);\n const rawStatus = (await requestJson(input, `${model.submitPath}/${encodeURIComponent(taskId)}`, {\n method: \"GET\",\n })) as TaskStatusResponse;\n const status = extractStatus(rawStatus);\n\n if (status.status === \"succeeded\") {\n if (!status.videoUrl) {\n throw new GenerationProviderError(\"Kling video generation succeeded but returned no video URL\", {\n details: compactObject({ taskId, rawStatus, metadata: status.metadata }),\n });\n }\n return [\n {\n type: \"video\",\n source: { type: \"url\", url: status.videoUrl },\n meta: { task_id: taskId, status: status.status, ...status.metadata },\n },\n ];\n }\n if (status.status === \"failed\" || status.status === \"cancelled\" || status.status === \"expired\") {\n throw new GenerationProviderError(`Kling video generation ${status.status}`, {\n details: compactObject({ taskId, message: status.message, rawStatus }),\n });\n }\n }\n\n throw new GenerationTimeoutError(\"Timed out waiting for Kling video generation\", { taskId });\n}\n","import { GenerationProviderError, GenerationValidationError } from \"../errors.js\";\nimport { fetchWithTimeout, joinUrl } from \"../http.js\";\nimport type { GenerationAdapterInput, GenerationContentBlock } from \"../types.js\";\nimport { compactArray, compactObject } from \"../utils.js\";\nimport { mergeTextBlocks } from \"../validation.js\";\n\nconst REQUEST_TIMEOUT_MS = 300_000;\n\ntype OpenAiImagesResponse = {\n data?: Array<{\n url?: unknown;\n b64_json?: unknown;\n revised_prompt?: unknown;\n }>;\n created?: unknown;\n usage?: unknown;\n background?: unknown;\n output_format?: unknown;\n quality?: unknown;\n size?: unknown;\n};\n\nfunction collectOpenAiImagesNoOutputDetails(raw: OpenAiImagesResponse): Record<string, unknown> {\n const data = raw.data ?? [];\n return compactObject({\n created: raw.created,\n usage: raw.usage,\n background: raw.background,\n outputFormat: raw.output_format,\n quality: raw.quality,\n size: raw.size,\n dataCount: data.length,\n data: compactArray(\n data.map((item) =>\n compactObject({\n hasUrl: typeof item.url === \"string\" && item.url.length > 0,\n hasBase64Json: typeof item.b64_json === \"string\" && item.b64_json.length > 0,\n revisedPrompt: item.revised_prompt,\n }),\n ),\n ),\n });\n}\n\nfunction requiresPrompt(input: GenerationAdapterInput): boolean {\n const textSpec = input.declaration.content.input.find((spec) => spec.type === \"text\");\n return !!textSpec && (textSpec.required === true || (textSpec.min ?? 0) > 0);\n}\n\nexport async function openAiImagesAdapter(input: GenerationAdapterInput): Promise<GenerationContentBlock[]> {\n const prompt = mergeTextBlocks(input.declaration, input.request.content);\n if (!prompt && requiresPrompt(input)) throw new GenerationValidationError(\"Prompt text is required\");\n\n const images = await Promise.all(\n input.request.content\n .filter((block): block is Extract<GenerationContentBlock, { type: \"image\" }> => block.type === \"image\")\n .map((block) => input.context.resolveSource(block.source)),\n );\n\n const payload: Record<string, unknown> = {\n model: input.declaration.model,\n prompt,\n ...input.parameters,\n };\n if (images.length > 0) payload.image = images;\n\n const response = await fetchWithTimeout(\n input.context.fetch,\n joinUrl(input.context.baseUrl, \"/v1/images/generations\"),\n {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${input.context.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n },\n REQUEST_TIMEOUT_MS,\n );\n\n if (!response.ok) {\n const body = await response.text().catch(() => response.statusText);\n throw new GenerationProviderError(\"Image generation provider request failed\", { status: response.status, body });\n }\n\n const raw = (await response.json()) as OpenAiImagesResponse;\n const output: GenerationContentBlock[] = [];\n for (const item of raw.data ?? []) {\n if (typeof item.url === \"string\" && item.url) {\n output.push({ type: \"image\", source: { type: \"url\", url: item.url } });\n }\n if (typeof item.b64_json === \"string\" && item.b64_json) {\n output.push({ type: \"image\", source: { type: \"base64\", mediaType: \"image/png\", data: item.b64_json } });\n }\n if (typeof item.revised_prompt === \"string\" && item.revised_prompt.trim()) {\n output.push({ type: \"text\", text: item.revised_prompt, meta: { role: \"revised_prompt\" } });\n }\n }\n if (output.length === 0) {\n throw new GenerationProviderError(\"Image generation returned no output\", {\n details: collectOpenAiImagesNoOutputDetails(raw),\n });\n }\n return output;\n}\n","import { GenerationProviderError, GenerationTimeoutError, GenerationValidationError } from \"../errors.js\";\nimport { fetchWithTimeout, joinUrl } from \"../http.js\";\nimport type {\n GenerationAdapterInput,\n GenerationContentBlock,\n GenerationContentSpec,\n GenerationSource,\n} from \"../types.js\";\nimport { compactObject } from \"../utils.js\";\nimport { mergeTextBlocks } from \"../validation.js\";\n\nconst REQUEST_TIMEOUT_MS = 60_000;\nconst DEFAULT_POLL_INTERVAL_SEC = 5;\nconst DEFAULT_MAX_WAIT_SEC = 600;\nconst DEFAULT_MUSIC_VERSION = \"chirp-v5\";\n\nconst OPERATION_PATHS: Record<\n string,\n { path: string; poll: boolean; defaultMusicVersion?: boolean; textField?: string; requireText?: boolean }\n> = {\n music: { path: \"/suno/submit/music\", poll: true, defaultMusicVersion: true, textField: \"prompt\" },\n lyrics: { path: \"/suno/submit/lyrics\", poll: true, textField: \"prompt\", requireText: true },\n concat: { path: \"/suno/submit/concat\", poll: true },\n upsample_tags: { path: \"/suno/submit/upsample-tags\", poll: false, textField: \"original_tags\", requireText: true },\n upload_audio: { path: \"/suno/uploads/audio\", poll: true },\n};\n\nconst FINAL_SUCCESS_STATUSES = new Set([\"success\", \"succeeded\", \"completed\"]);\nconst FINAL_FAILURE_STATUSES = new Set([\"failure\", \"failed\", \"error\", \"cancelled\", \"canceled\", \"expired\"]);\n\ntype TaskResponse<T = unknown> = {\n code?: unknown;\n message?: unknown;\n data?: T;\n};\n\ntype SunoTaskDto = {\n task_id?: unknown;\n taskBatchId?: unknown;\n task_batch_id?: unknown;\n action?: unknown;\n status?: unknown;\n taskStatus?: unknown;\n task_status?: unknown;\n fail_reason?: unknown;\n failReason?: unknown;\n result_url?: unknown;\n progress?: unknown;\n submit_time?: unknown;\n start_time?: unknown;\n finish_time?: unknown;\n data?: unknown;\n};\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction asString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n}\n\nfunction asInteger(value: unknown, fallback: number): number {\n return typeof value === \"number\" && Number.isInteger(value) ? value : fallback;\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n return isRecord(value) ? value : {};\n}\n\nfunction successCode(value: unknown): boolean {\n const code = String(value ?? \"\")\n .trim()\n .toLowerCase();\n return code === \"success\" || code === \"200\" || code === \"0\";\n}\n\nfunction requireSuccess<T>(response: TaskResponse<T>, fallbackMessage: string): T {\n if (!successCode(response.code)) {\n throw new GenerationProviderError(fallbackMessage, {\n details: {\n code: response.code,\n message: response.message,\n data: response.data,\n },\n });\n }\n return response.data as T;\n}\n\nfunction extractTaskId(value: unknown): string | undefined {\n if (typeof value === \"string\" && value.trim()) return value.trim();\n if (!isRecord(value)) return undefined;\n for (const key of [\"task_id\", \"id\", \"taskBatchId\"]) {\n const taskId = asString(value[key]);\n if (taskId) return taskId;\n }\n return undefined;\n}\n\nfunction normalizeStatus(value: unknown): string {\n const status = String(value ?? \"\")\n .trim()\n .toLowerCase();\n if (status === \"finished\") return \"success\";\n if (status === \"fail\" || status === \"rejected\") return \"failed\";\n return status;\n}\n\nfunction normalizeTask(operation: string, data: unknown): SunoTaskDto | null {\n if (Array.isArray(data)) return data.length > 0 ? normalizeTask(operation, data[0]) : null;\n if (!isRecord(data)) return null;\n if (\"status\" in data || \"taskStatus\" in data || \"task_status\" in data || \"task_id\" in data || \"taskBatchId\" in data) {\n const hasProviderEnvelope =\n \"taskStatus\" in data || \"task_status\" in data || \"taskBatchId\" in data || \"task_batch_id\" in data;\n return {\n ...data,\n task_id: data.task_id ?? data.taskBatchId ?? data.task_batch_id,\n status: data.status ?? data.taskStatus ?? data.task_status,\n fail_reason: data.fail_reason ?? data.failReason,\n data: data.data ?? (hasProviderEnvelope ? data : undefined),\n } as SunoTaskDto;\n }\n if (Array.isArray(data.data) && data.data.length > 0) return normalizeTask(operation, data.data[0]);\n return { action: operation, status: \"SUCCESS\", data };\n}\n\nfunction getOperation(input: GenerationAdapterInput): string {\n const fixedOperation = asString(input.declaration.adapter.operation);\n const requestedOperation = asString(input.parameters.operation);\n if (fixedOperation && requestedOperation && fixedOperation !== requestedOperation) {\n throw new GenerationValidationError(\n `${input.declaration.model} uses Suno operation ${fixedOperation}; parameters.operation cannot override it`,\n );\n }\n const operation = fixedOperation ?? requestedOperation ?? \"music\";\n if (!OPERATION_PATHS[operation]) throw new GenerationValidationError(`Unsupported Suno operation: ${operation}`);\n return operation;\n}\n\nasync function buildPayload(input: GenerationAdapterInput, operation: string): Promise<Record<string, unknown>> {\n const payload: Record<string, unknown> = {\n ...asRecord(input.declaration.adapter.defaults),\n ...input.meta,\n };\n const config = OPERATION_PATHS[operation];\n\n const prompt = mergeTextBlocks(input.declaration, input.request.content);\n if (prompt && config?.textField && payload[config.textField] === undefined) payload[config.textField] = prompt;\n const audioBlock = input.request.content.find(\n (block): block is Extract<GenerationContentBlock, { type: \"audio\" }> => block.type === \"audio\",\n );\n if (audioBlock && payload.url === undefined) payload.url = await input.context.resolveSource(audioBlock.source);\n\n const imageBlock = input.request.content.find(\n (block): block is Extract<GenerationContentBlock, { type: \"image\" }> => block.type === \"image\",\n );\n let imageUrl: string | undefined;\n if (imageBlock) {\n imageUrl = await input.context.resolveSource(imageBlock.source);\n if (payload.image_url === undefined) payload.image_url = imageUrl;\n }\n\n const videoBlock = input.request.content.find(\n (block): block is Extract<GenerationContentBlock, { type: \"video\" }> => block.type === \"video\",\n );\n let videoUrl: string | undefined;\n if (videoBlock) {\n videoUrl = await input.context.resolveSource(videoBlock.source);\n if (payload.video_url === undefined) payload.video_url = videoUrl;\n }\n\n applyFixedPayload(input, payload, asRecord(input.declaration.adapter.payload));\n const fixedTask = asString(input.declaration.adapter.task);\n if (fixedTask) applyFixedPayload(input, payload, { task: fixedTask });\n\n const task = asString(payload.task);\n if (task === \"image_to_song\" && imageUrl) setMetadataParam(payload, \"image_url\", imageUrl);\n if (task === \"video_to_song\" && videoUrl) setMetadataParam(payload, \"video_url\", videoUrl);\n if (task === \"cover\" && payload.clip_id === undefined) {\n const coverClipId = asString(payload.cover_clip_id);\n if (coverClipId) payload.clip_id = coverClipId;\n }\n\n normalizeMusicTaskPayload(input, operation, payload);\n\n if (config?.defaultMusicVersion && payload.mv === undefined && payload.model_name === undefined) {\n payload.mv = DEFAULT_MUSIC_VERSION;\n }\n\n validateSunoPayload(operation, payload);\n return payload;\n}\n\nfunction applyFixedPayload(\n input: GenerationAdapterInput,\n payload: Record<string, unknown>,\n fixed: Record<string, unknown>,\n): void {\n for (const [key, value] of Object.entries(fixed)) {\n if (value === undefined) continue;\n if (payload[key] !== undefined && payload[key] !== value) {\n throw new GenerationValidationError(\n `${input.declaration.model} fixes Suno ${key}; meta.${key} cannot override it`,\n );\n }\n payload[key] = value;\n }\n}\n\nfunction setMetadataParam(payload: Record<string, unknown>, key: string, value: string): void {\n const metadataParams = isRecord(payload.metadata_params) ? payload.metadata_params : {};\n if (metadataParams[key] === undefined) metadataParams[key] = value;\n payload.metadata_params = metadataParams;\n}\n\nfunction contentCount(content: GenerationContentBlock[], type: GenerationContentSpec[\"type\"]): number {\n return content.filter((block) => block.type === type).length;\n}\n\nfunction normalizeMusicTaskPayload(\n input: GenerationAdapterInput,\n operation: string,\n payload: Record<string, unknown>,\n): void {\n if (operation !== \"music\") return;\n const taskField = input.declaration.meta?.taskField ?? \"task\";\n const task = asString(payload[taskField]);\n if (!task) return;\n const taskVariant = input.declaration.meta?.taskVariants?.[task];\n if (!taskVariant) throw new GenerationValidationError(`Unsupported Suno music task: ${task}`);\n for (const key of taskVariant.required ?? []) {\n if (payload[key] === undefined || payload[key] === null || payload[key] === \"\") {\n throw new GenerationValidationError(`Suno task ${task} requires meta.${key}`);\n }\n }\n for (const type of taskVariant.requiredContent ?? []) {\n if (contentCount(input.request.content, type) === 0) {\n throw new GenerationValidationError(`Suno task ${task} requires ${type} content`);\n }\n }\n if (taskVariant.sendTask === false) delete payload[taskField];\n}\n\nfunction validateSunoPayload(operation: string, payload: Record<string, unknown>): void {\n const config = OPERATION_PATHS[operation];\n const task = asString(payload.task);\n if (operation === \"music\" && task) {\n if (task === \"lyrics\") throw new GenerationValidationError(\"Use operation=lyrics instead of task=lyrics\");\n }\n if (config?.requireText && !asString(payload[config.textField ?? \"prompt\"])) {\n throw new GenerationValidationError(`${config.textField ?? \"prompt\"} text is required`);\n }\n if (operation === \"upload_audio\" && !asString(payload.url)) {\n throw new GenerationValidationError(\"Audio url is required for Suno upload_audio\");\n }\n if (operation === \"concat\" && !asString(payload.clip_id)) {\n throw new GenerationValidationError(\"clip_id is required for Suno concat\");\n }\n}\n\nasync function requestJson(input: GenerationAdapterInput, path: string, init: RequestInit): Promise<TaskResponse> {\n const response = await fetchWithTimeout(\n input.context.fetch,\n joinUrl(input.context.baseUrl, path),\n {\n ...init,\n headers: {\n Authorization: `Bearer ${input.context.apiKey}`,\n \"Content-Type\": \"application/json\",\n ...init.headers,\n },\n },\n REQUEST_TIMEOUT_MS,\n );\n const body = await response.text();\n let parsed: TaskResponse;\n try {\n parsed = body ? (JSON.parse(body) as TaskResponse) : {};\n } catch {\n throw new GenerationProviderError(\"Suno provider returned invalid JSON\", { status: response.status, body });\n }\n if (!response.ok) {\n throw new GenerationProviderError(\"Suno provider request failed\", {\n status: response.status,\n details: { body: parsed },\n });\n }\n return parsed;\n}\n\nfunction appendUrlBlock(\n output: GenerationContentBlock[],\n type: \"audio\" | \"video\" | \"image\",\n url: unknown,\n meta: Record<string, unknown>,\n): void {\n const value = asString(url);\n if (!value) return;\n output.push({ type, source: { type: \"url\", url: value } as GenerationSource, meta: compactObject(meta) });\n}\n\nfunction appendSunoContent(output: GenerationContentBlock[], value: unknown, meta: Record<string, unknown> = {}): void {\n if (Array.isArray(value)) {\n for (const item of value) appendSunoContent(output, item, meta);\n return;\n }\n if (!isRecord(value)) return;\n\n if (isRecord(value.clips)) {\n for (const clip of Object.values(value.clips)) appendSunoContent(output, clip, meta);\n }\n if (Array.isArray(value.items)) {\n for (const item of value.items) appendSunoContent(output, item, meta);\n }\n\n const itemMeta = compactObject({\n ...meta,\n id: value.id,\n clip_id: value.clipId ?? value.clip_id ?? meta.clip_id,\n task_id: value.task_id ?? value.taskId ?? meta.task_id,\n title: value.title,\n status: value.status ?? meta.status,\n model: value.model_name ?? value.modelName,\n duration: value.duration ?? (isRecord(value.metadata) ? value.metadata.duration : undefined),\n tags: value.tags ?? (isRecord(value.metadata) ? value.metadata.tags : undefined),\n prompt: value.prompt ?? (isRecord(value.metadata) ? value.metadata.prompt : undefined),\n progress: value.progress ?? meta.progress,\n progress_message: value.progressMsg ?? value.progress_msg,\n task_batch_id: value.taskBatchId ?? value.task_batch_id,\n continue_clip_id: value.continueClipId ?? value.continue_clip_id,\n input_type: value.inputType ?? value.input_type,\n make_instrumental: value.makeInstrumental ?? value.make_instrumental,\n created_at: value.createTime ?? value.created_at,\n });\n\n appendUrlBlock(\n output,\n \"audio\",\n value.audio_url ?? value.audioUrl ?? value.cld2AudioUrl ?? value.cld2_audio_url,\n itemMeta,\n );\n appendUrlBlock(output, \"audio\", value.vocal_audio_url ?? value.vocalAudioUrl, itemMeta);\n appendUrlBlock(output, \"audio\", value.instrumental_audio_url ?? value.instrumentalAudioUrl, itemMeta);\n appendUrlBlock(output, \"audio\", value.source_audio_url ?? value.sourceAudioUrl, itemMeta);\n appendUrlBlock(\n output,\n \"video\",\n value.video_url ?? value.videoUrl ?? value.cld2VideoUrl ?? value.cld2_video_url,\n itemMeta,\n );\n appendUrlBlock(\n output,\n \"image\",\n value.image_large_url ?? value.image_url ?? value.imageUrl ?? value.cld2ImageUrl ?? value.cld2_image_url,\n itemMeta,\n );\n\n const text = asString(value.upsampled_tags) ?? asString(value.text) ?? asString(value.lyrics);\n if (text) output.push({ type: \"text\", text, meta: itemMeta });\n\n if (isRecord(value.data)) appendSunoContent(output, value.data, itemMeta);\n}\n\nfunction buildImmediateResult(operation: string, data: unknown, raw: unknown): GenerationContentBlock[] {\n const output: GenerationContentBlock[] = [];\n const metadata = compactObject({ operation, raw });\n appendSunoContent(output, data, metadata);\n if (output.length > 0) return output;\n\n const value = extractTaskId(data) ?? asString(data);\n if (value) output.push({ type: \"text\", text: value, meta: metadata });\n return requireSunoOutput(output, \"Suno provider returned no output\", { operation, raw });\n}\n\nfunction requireSunoOutput(\n output: GenerationContentBlock[],\n message: string,\n details: Record<string, unknown>,\n): GenerationContentBlock[] {\n if (output.length === 0) throw new GenerationProviderError(message, { details });\n return output;\n}\n\nfunction buildResult(operation: string, task: SunoTaskDto, raw: unknown): GenerationContentBlock[] {\n const output: GenerationContentBlock[] = [];\n const metadata = compactObject({\n operation,\n task_id: task.task_id,\n action: task.action,\n status: task.status,\n fail_reason: task.fail_reason,\n progress: task.progress,\n submit_time: task.submit_time,\n start_time: task.start_time,\n finish_time: task.finish_time,\n raw,\n });\n appendSunoContent(output, task.data, metadata);\n appendUrlBlock(output, \"audio\", task.result_url, metadata);\n return requireSunoOutput(output, \"Suno task succeeded but returned no output\", { operation, task, raw });\n}\n\nasync function pollSunoTask(\n input: GenerationAdapterInput,\n operation: string,\n taskId: string,\n pollIntervalSec: number,\n maxWaitSec: number,\n): Promise<GenerationContentBlock[]> {\n const startedAt = Date.now();\n while (Date.now() - startedAt <= maxWaitSec * 1000) {\n await sleep(pollIntervalSec * 1000);\n let raw: TaskResponse;\n try {\n raw = await requestJson(input, `/suno/fetch/${encodeURIComponent(taskId)}`, { method: \"GET\" });\n } catch (error) {\n if (error instanceof GenerationProviderError) throw error;\n continue;\n }\n const data = requireSuccess(raw, \"Suno task fetch failed\");\n const task = normalizeTask(operation, data);\n if (!task) throw new GenerationProviderError(\"Suno task fetch returned invalid task data\", { details: { data } });\n\n const status = normalizeStatus(task.status);\n if (FINAL_SUCCESS_STATUSES.has(status)) return buildResult(operation, task, data);\n if (FINAL_FAILURE_STATUSES.has(status)) {\n throw new GenerationProviderError(\"Suno task failed\", {\n details: {\n task_id: taskId,\n status: task.status,\n fail_reason: task.fail_reason,\n },\n });\n }\n }\n throw new GenerationTimeoutError(\"Timed out waiting for Suno task\", { task_id: taskId, operation });\n}\n\nexport async function sunoTasksAdapter(input: GenerationAdapterInput): Promise<GenerationContentBlock[]> {\n const operation = getOperation(input);\n const payload = await buildPayload(input, operation);\n const config = OPERATION_PATHS[operation];\n if (!config) throw new GenerationValidationError(`Unsupported Suno operation: ${operation}`);\n const raw = await requestJson(input, config.path, {\n method: \"POST\",\n body: JSON.stringify(payload),\n });\n const data = requireSuccess(raw, \"Suno task submit failed\");\n\n if (!config.poll) return buildImmediateResult(operation, data, raw);\n\n const taskId = extractTaskId(data);\n if (!taskId) return buildImmediateResult(operation, data, raw);\n\n const pollIntervalSec = asInteger(input.parameters.poll_interval, DEFAULT_POLL_INTERVAL_SEC);\n const maxWaitSec = asInteger(input.parameters.max_wait, DEFAULT_MAX_WAIT_SEC);\n return pollSunoTask(input, operation, taskId, pollIntervalSec, maxWaitSec);\n}\n","import { GenerationUnsupportedAdapterError } from \"../errors.js\";\nimport type { GenerationAdapter } from \"../types.js\";\nimport { arkVideoGenerationsAdapter } from \"./ark-video-generations.js\";\nimport { geminiGenerateContentAdapter } from \"./gemini-generate-content.js\";\nimport { klingVideoGenerationsAdapter } from \"./kling-video-generations.js\";\nimport { openAiImagesAdapter } from \"./openai-images.js\";\nimport { sunoTasksAdapter } from \"./suno-tasks.js\";\n\nexport const builtinGenerationAdapters: Record<string, GenerationAdapter> = {\n \"ark.videoGenerations\": arkVideoGenerationsAdapter,\n \"gemini.generateContent\": geminiGenerateContentAdapter,\n \"kling.videoGenerations\": klingVideoGenerationsAdapter,\n \"openai.images\": openAiImagesAdapter,\n \"suno.tasks\": sunoTasksAdapter,\n};\n\nexport function getGenerationAdapter(\n type: string,\n adapters: Record<string, GenerationAdapter> = {},\n): GenerationAdapter {\n const adapter = adapters[type] ?? builtinGenerationAdapters[type];\n if (!adapter) throw new GenerationUnsupportedAdapterError(type);\n return adapter;\n}\n\nexport * from \"./ark-video-generations.js\";\nexport * from \"./gemini-generate-content.js\";\nexport * from \"./kling-video-generations.js\";\nexport * from \"./openai-images.js\";\nexport * from \"./suno-tasks.js\";\n","import { mkdir, readdir, readFile, writeFile } from \"node:fs/promises\";\nimport { extname, join } from \"node:path\";\nimport { parse as parseYaml, stringify as stringifyYaml } from \"yaml\";\nimport { GenerationConfigError } from \"./errors.js\";\nimport { type GenerationModelDeclaration, MODEL_SCHEMA } from \"./types.js\";\nimport { cloneJson, slugifyFileName } from \"./utils.js\";\n\nconst DECLARATION_EXTENSIONS = new Set([\".yaml\", \".yml\", \".json\"]);\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction isParameterSpec(value: unknown): boolean {\n if (!isRecord(value)) return false;\n return [\"string\", \"number\", \"integer\", \"boolean\"].includes(String(value.type));\n}\n\nfunction isMetaFieldSpec(value: unknown): boolean {\n if (!isRecord(value)) return false;\n return isParameterSpec(value) || String(value.type) === \"object\";\n}\n\nfunction isMetaTaskVariantSpec(value: unknown): boolean {\n if (!isRecord(value)) return false;\n return (\n (value.description === undefined || typeof value.description === \"string\") &&\n (value.required === undefined ||\n (Array.isArray(value.required) && value.required.every((item) => typeof item === \"string\"))) &&\n (value.requiredContent === undefined ||\n (Array.isArray(value.requiredContent) && value.requiredContent.every((item) => typeof item === \"string\"))) &&\n (value.sendTask === undefined || typeof value.sendTask === \"boolean\")\n );\n}\n\nfunction isMetaSpec(value: unknown): boolean {\n if (!isRecord(value)) return false;\n return (\n (value.fields === undefined ||\n (isRecord(value.fields) && Object.values(value.fields).every((field) => isMetaFieldSpec(field)))) &&\n (value.taskField === undefined || typeof value.taskField === \"string\") &&\n (value.taskVariants === undefined ||\n (isRecord(value.taskVariants) &&\n Object.values(value.taskVariants).every((variant) => isMetaTaskVariantSpec(variant))))\n );\n}\n\nexport function isGenerationModelDeclaration(value: unknown): value is GenerationModelDeclaration {\n if (!isRecord(value)) return false;\n const adapter = value.adapter;\n const content = value.content;\n const parameters = value.parameters;\n const meta = value.meta;\n const examples = value.examples;\n return (\n value.schema === MODEL_SCHEMA &&\n typeof value.model === \"string\" &&\n value.model.trim().length > 0 &&\n (value.allowUnknownParameters === undefined || typeof value.allowUnknownParameters === \"boolean\") &&\n isRecord(adapter) &&\n typeof adapter.type === \"string\" &&\n isRecord(content) &&\n Array.isArray(content.input) &&\n (parameters === undefined || (isRecord(parameters) && Object.values(parameters).every(isParameterSpec))) &&\n (meta === undefined || isMetaSpec(meta)) &&\n (examples === undefined || Array.isArray(examples))\n );\n}\n\nexport function parseGenerationModelDeclaration(rawText: string, filePath = \"model.yaml\"): GenerationModelDeclaration {\n const parsed = extname(filePath) === \".json\" ? JSON.parse(rawText) : parseYaml(rawText);\n if (!isGenerationModelDeclaration(parsed)) throw new GenerationConfigError(`Invalid model declaration: ${filePath}`);\n return parsed;\n}\n\nexport function stringifyGenerationModelDeclaration(\n declaration: GenerationModelDeclaration,\n options: { format?: \"yaml\" | \"json\" } = {},\n): string {\n const value = cloneJson(declaration);\n if (options.format === \"json\") return `${JSON.stringify(value, null, 2)}\\n`;\n return stringifyYaml(value, { lineWidth: 120 });\n}\n\nexport async function readGenerationModelDeclaration(filePath: string): Promise<GenerationModelDeclaration> {\n return parseGenerationModelDeclaration(await readFile(filePath, \"utf-8\"), filePath);\n}\n\nexport async function readGenerationModelDeclarationsFromFiles(\n filePaths: string[],\n): Promise<GenerationModelDeclaration[]> {\n const declarations = await Promise.all(filePaths.map((filePath) => readGenerationModelDeclaration(filePath)));\n return mergeGenerationModelDeclarations(declarations);\n}\n\nexport async function readGenerationModelDeclarationsFromDirectory(\n directory: string,\n): Promise<GenerationModelDeclaration[]> {\n const entries = await readdir(directory);\n const files = entries\n .filter((entry) => DECLARATION_EXTENSIONS.has(extname(entry)))\n .sort()\n .map((entry) => join(directory, entry));\n return readGenerationModelDeclarationsFromFiles(files);\n}\n\nexport function mergeGenerationModelDeclarations(\n declarations: GenerationModelDeclaration[],\n): GenerationModelDeclaration[] {\n const byModel = new Map<string, GenerationModelDeclaration>();\n for (const declaration of declarations) byModel.set(declaration.model, declaration);\n return [...byModel.values()].sort((a, b) => a.model.localeCompare(b.model));\n}\n\nexport async function writeGenerationModelDeclaration(\n declaration: GenerationModelDeclaration,\n filePath: string,\n options: { format?: \"yaml\" | \"json\" } = {},\n): Promise<void> {\n await writeFile(filePath, stringifyGenerationModelDeclaration(declaration, options));\n}\n\nexport async function writeGenerationModelDeclarations(\n declarations: GenerationModelDeclaration[],\n directory: string,\n options: { format?: \"yaml\" | \"json\" } = {},\n): Promise<void> {\n await mkdir(directory, { recursive: true });\n const ext = options.format === \"json\" ? \"json\" : \"yaml\";\n await Promise.all(\n declarations.map((declaration) =>\n writeGenerationModelDeclaration(\n declaration,\n join(directory, `${slugifyFileName(declaration.model)}.${ext}`),\n options,\n ),\n ),\n );\n}\n","import type { GenerationSource, GenerationSourceResolver } from \"./types.js\";\n\nexport const defaultGenerationSourceResolver: GenerationSourceResolver = (source: GenerationSource) => {\n switch (source.type) {\n case \"url\":\n return source.url;\n case \"base64\":\n return `data:${source.mediaType};base64,${source.data}`;\n }\n};\n","import { getGenerationAdapter } from \"./adapters/index.js\";\nimport { builtinGenerationModels } from \"./builtins.js\";\nimport {\n readGenerationModelDeclarationsFromDirectory,\n readGenerationModelDeclarationsFromFiles,\n stringifyGenerationModelDeclaration,\n writeGenerationModelDeclaration,\n writeGenerationModelDeclarations,\n} from \"./config.js\";\nimport { GenerationConfigError } from \"./errors.js\";\nimport { createDebugFetch } from \"./http.js\";\nimport { defaultGenerationSourceResolver } from \"./source.js\";\nimport type {\n CreateGenerationClientOptions,\n GenerateRequest,\n GenerationClient,\n GenerationDebugConfig,\n GenerationModelDeclaration,\n} from \"./types.js\";\nimport { cloneJson } from \"./utils.js\";\nimport {\n mergeGenerationMeta,\n resolveGenerationMeta,\n resolveGenerationParameters,\n validateGenerationContent,\n} from \"./validation.js\";\n\nconst DEFAULT_BASE_URL = \"https://router.neta.art\";\nconst REDACTED = \"[REDACTED]\";\nconst SECRET_DEBUG_KEY_PATTERN = /^(authorization|api[-_]?key|token|thoughtSignature)$/i;\nconst BASE64_DEBUG_KEY_PATTERN = /^(b64_json|data)$/i;\nconst MEDIA_PAYLOAD_KEYS = new Set([\n \"audio\",\n \"audio_url\",\n \"image\",\n \"image_tail\",\n \"image_url\",\n \"first_frame\",\n \"mask\",\n \"result_url\",\n \"static_mask\",\n \"url\",\n \"video\",\n \"video_url\",\n \"watermark_url\",\n]);\n\nfunction isUrlLike(value: string): boolean {\n return /^(https?:|s3:|gs:|file:|blob:)\\/\\//i.test(value.trim());\n}\n\nfunction isBase64Like(value: string): boolean {\n const compact = value.trim().replace(/\\s/g, \"\");\n if (compact.length < 256 || compact.length % 4 === 1) return false;\n return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(compact);\n}\n\nfunction shouldRedactString(key: string | undefined, value: string): boolean {\n const trimmed = value.trim();\n if (!trimmed) return false;\n if (/^data:/i.test(trimmed)) return true;\n if (isBase64Like(trimmed)) return true;\n return !!key && MEDIA_PAYLOAD_KEYS.has(key.toLowerCase()) && !isUrlLike(trimmed);\n}\n\nfunction redactDebugEvent<T>(value: T, options: { redactSecrets: boolean }, key?: string): T {\n if (typeof value === \"string\") return (shouldRedactString(key, value) ? REDACTED : value) as T;\n if (Array.isArray(value)) return value.map((item) => redactDebugEvent(item, options, key)) as T;\n if (!value || typeof value !== \"object\") return value;\n\n const output: Record<string, unknown> = {};\n for (const [childKey, child] of Object.entries(value)) {\n if (BASE64_DEBUG_KEY_PATTERN.test(childKey) || (options.redactSecrets && SECRET_DEBUG_KEY_PATTERN.test(childKey))) {\n output[childKey] = REDACTED;\n } else {\n output[childKey] = redactDebugEvent(child, options, childKey);\n }\n }\n return output as T;\n}\n\nfunction defaultDebugLogger(event: unknown): void {\n console.error(JSON.stringify(event, null, 2));\n}\n\nfunction resolveDebugConfig(debug: CreateGenerationClientOptions[\"debug\"]): GenerationDebugConfig | undefined {\n if (!debug) return undefined;\n if (debug === true) {\n return {\n enabled: true,\n includeSensitive: false,\n includeResponseBody: true,\n logger: (event) => defaultDebugLogger(redactDebugEvent(event, { redactSecrets: true })),\n };\n }\n if (!debug.enabled) return undefined;\n const includeSensitive = debug.includeSensitive ?? false;\n const logger = debug.logger ?? defaultDebugLogger;\n return {\n enabled: true,\n includeSensitive,\n includeResponseBody: debug.includeResponseBody ?? true,\n logger: (event) => logger(redactDebugEvent(event, { redactSecrets: !includeSensitive })),\n };\n}\n\nfunction resolveModels(options: CreateGenerationClientOptions): GenerationModelDeclaration[] {\n const includeBuiltinModels = options.includeBuiltinModels ?? !options.models;\n const models = [...(includeBuiltinModels ? builtinGenerationModels : []), ...(options.models ?? [])];\n const byModel = new Map<string, GenerationModelDeclaration>();\n for (const model of models) byModel.set(model.model, cloneJson(model));\n return [...byModel.values()].sort((a, b) => a.model.localeCompare(b.model));\n}\n\nexport function createGenerationClient(options: CreateGenerationClientOptions = {}): GenerationClient {\n const models = resolveModels(options);\n const byModel = new Map(models.map((declaration) => [declaration.model, declaration]));\n const fetchFn = options.fetch ?? globalThis.fetch;\n if (!fetchFn) throw new GenerationConfigError(\"A fetch implementation is required\");\n const debug = resolveDebugConfig(options.debug);\n const adapterFetch = debug ? createDebugFetch(fetchFn, debug) : fetchFn;\n\n function requireModel(model: string): GenerationModelDeclaration {\n const declaration = byModel.get(model);\n if (!declaration) throw new GenerationConfigError(`Generation model is unavailable: ${model}`);\n return declaration;\n }\n\n return {\n validate(request: GenerateRequest) {\n const declaration = requireModel(request.model);\n validateGenerationContent(declaration, request.content);\n const parameters = resolveGenerationParameters(declaration, request.parameters);\n const meta = resolveGenerationMeta(\n declaration,\n mergeGenerationMeta({ ...(request.metadata ?? {}), ...(request.meta ?? {}) }, request.content),\n request.content,\n );\n return { declaration: cloneJson(declaration), request: cloneJson(request), parameters, meta };\n },\n\n async generate(request: GenerateRequest) {\n const resolved = this.validate(request);\n const apiKey = request.apiKey ?? options.apiKey;\n if (!apiKey) throw new GenerationConfigError(\"apiKey is required\");\n const adapter = getGenerationAdapter(resolved.declaration.adapter.type, options.adapters);\n return adapter({\n ...resolved,\n context: {\n apiKey,\n baseUrl: request.baseUrl ?? options.baseUrl ?? DEFAULT_BASE_URL,\n fetch: adapterFetch,\n resolveSource: options.sourceResolver ?? defaultGenerationSourceResolver,\n },\n });\n },\n\n listModels() {\n return cloneJson(models);\n },\n\n getModel(model: string) {\n const declaration = byModel.get(model);\n return declaration ? cloneJson(declaration) : null;\n },\n\n stringifyModelConfig(model: string, stringifyOptions = {}) {\n return stringifyGenerationModelDeclaration(requireModel(model), stringifyOptions);\n },\n\n exportModelConfig(model: string, filePath: string) {\n return writeGenerationModelDeclaration(requireModel(model), filePath);\n },\n\n exportModelConfigs(directory: string) {\n return writeGenerationModelDeclarations(models, directory);\n },\n };\n}\n\nexport async function createGenerationClientFromFiles(\n filePaths: string[],\n options: Omit<CreateGenerationClientOptions, \"models\"> = {},\n): Promise<GenerationClient> {\n const models = await readGenerationModelDeclarationsFromFiles(filePaths);\n return createGenerationClient({ ...options, models, includeBuiltinModels: options.includeBuiltinModels ?? true });\n}\n\nexport async function createGenerationClientFromDirectory(\n directory: string,\n options: Omit<CreateGenerationClientOptions, \"models\"> = {},\n): Promise<GenerationClient> {\n const models = await readGenerationModelDeclarationsFromDirectory(directory);\n return createGenerationClient({ ...options, models, includeBuiltinModels: options.includeBuiltinModels ?? true });\n}\n\nexport async function createGenerationClientFromFile(\n filePath: string,\n options: Omit<CreateGenerationClientOptions, \"models\"> = {},\n): Promise<GenerationClient> {\n return createGenerationClientFromFiles([filePath], options);\n}\n","import { getBuiltinGenerationModel, listBuiltinGenerationModels } from \"./builtins.js\";\nimport {\n stringifyGenerationModelDeclaration,\n writeGenerationModelDeclaration,\n writeGenerationModelDeclarations,\n} from \"./config.js\";\nimport { GenerationConfigError } from \"./errors.js\";\n\nexport function stringifyBuiltinModelConfig(model: string, options: { format?: \"yaml\" | \"json\" } = {}): string {\n const declaration = getBuiltinGenerationModel(model);\n if (!declaration) throw new GenerationConfigError(`Built-in model is unavailable: ${model}`);\n return stringifyGenerationModelDeclaration(declaration, options);\n}\n\nexport async function exportBuiltinModelConfig(model: string, filePath: string): Promise<void> {\n const declaration = getBuiltinGenerationModel(model);\n if (!declaration) throw new GenerationConfigError(`Built-in model is unavailable: ${model}`);\n await writeGenerationModelDeclaration(declaration, filePath);\n}\n\nexport async function exportBuiltinModelConfigs(directory: string): Promise<void> {\n await writeGenerationModelDeclarations(listBuiltinGenerationModels(), directory);\n}\n"],"mappings":";;;;;;AAAA,IAAa,kBAAb,cAAqC,MAAM;CACzC,YAAY,SAAiB;AAC3B,QAAM,QAAQ;AACd,OAAK,OAAO;;;AAIhB,IAAa,wBAAb,cAA2C,gBAAgB;CACzD,YAAY,SAAiB;AAC3B,QAAM,QAAQ;AACd,OAAK,OAAO;;;AAIhB,IAAa,4BAAb,cAA+C,gBAAgB;CAC7D,YAAY,SAAiB;AAC3B,QAAM,QAAQ;AACd,OAAK,OAAO;;;AAIhB,IAAa,oCAAb,cAAuD,gBAAgB;CACrE,YAAY,aAAqB;AAC/B,QAAM,mCAAmC,cAAc;AACvD,OAAK,OAAO;;;AAIhB,IAAa,0BAAb,cAA6C,gBAAgB;CAC3D,AAAS;CACT,AAAS;CACT,AAAS;CAET,YACE,UAAU,sCACV,SACA;AACA,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,OAAK,SAAS,SAAS;AACvB,OAAK,OAAO,SAAS;AACrB,OAAK,UAAU,SAAS;;;AAI5B,IAAa,yBAAb,cAA4C,wBAAwB;CAClE,YAAY,UAAU,gCAAgC,SAAmC;AACvF,QAAM,SAAS,UAAU,EAAE,SAAS,GAAG,OAAU;AACjD,OAAK,OAAO;;;;;;AC7ChB,SAAS,gBAAgB,SAA0D;AACjF,KAAI,CAAC,QAAS,QAAO,EAAE;AACvB,KAAI,mBAAmB,SAAS;EAC9B,MAAMA,SAAiC,EAAE;AACzC,UAAQ,SAAS,OAAO,QAAQ;AAC9B,UAAO,OAAO;IACd;AACF,SAAO;;AAET,KAAI,MAAM,QAAQ,QAAQ,CAAE,QAAO,OAAO,YAAY,QAAQ,KAAK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