UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3 lines • 15.5 kB
import{l as normalizeOptionalString,o as normalizeLowercaseStringOrEmpty}from"./string-coerce-CpTFcSwY.mjs";import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{i as fetchWithSsrFGuard}from"./fetch-guard-B_7-F5Lc.mjs";import{f as readProviderBinaryResponse,h as readProviderJsonResponse,n as assertOkOrThrowHttpError,r as assertOkOrThrowProviderError}from"./provider-http-errors-CWZQ78Qm.mjs";import"./string-coerce-runtime-BYDH9Quw.mjs";import"./ssrf-runtime-Dx9DKr_m.mjs";import{_ as resolveProviderOperationTimeoutMs,r as createProviderOperationDeadline}from"./shared-BGvdIfYO.mjs";import{r as resolveGeneratedImageDownloadMaxBytes}from"./configured-max-bytes-D7sE4PVV.mjs";import"./media-generation-runtime-BFOVKJoy.mjs";import{d as toImageDataUrl,i as imageFileExtensionForMimeType}from"./image-assets-PunGVmB-.mjs";import{n as isProviderApiKeyConfiguredAsync}from"./provider-auth-availability-BcdrxLsU.mjs";import"./provider-http-D0sVd8r_.mjs";import"./image-generation-C9u55YgW.mjs";import"./provider-auth-Czspvb3-.mjs";import{t as resolveFalHttpRequestConfig}from"./http-config-CWVp-9kA.mjs"; //!extensions/fal/image-generation-provider.ts const DEFAULT_FAL_IMAGE_MODEL=`fal-ai/flux/dev`;const DEFAULT_FAL_EDIT_SUBPATH=`image-to-image`;const FAL_KREA_2_MODEL_PREFIX=`krea/v2/`;const FAL_KREA_2_MEDIUM_MODEL=`krea/v2/medium/text-to-image`;const FAL_KREA_2_LARGE_MODEL=`krea/v2/large/text-to-image`;const FAL_NANO_BANANA_MODEL=`fal-ai/nano-banana`;const FAL_NANO_BANANA_2_LITE_MODEL=`google/nano-banana-2-lite`;const FAL_GROK_IMAGINE_MODEL=`xai/grok-imagine-image`;const FAL_GPT_IMAGE_25_MODELS=[`openai/gpt-image-2.5/flare/text-to-image`,`openai/gpt-image-2.5/flare/edit`,`openai/gpt-image-2.5/sunburst/text-to-image`,`openai/gpt-image-2.5/sunburst/edit`];const GPT_IMAGE_25_EDIT_MAX_INPUT_IMAGES=16;const GPT_IMAGE_25_QUALITIES=[`low`,`medium`,`high`,`xhigh`,`max`,`auto`];const GPT_IMAGE_25_OUTPUT_FORMATS=[`png`,`jpeg`,`webp`];const GPT_IMAGE_25_BACKGROUNDS=[`transparent`,`opaque`,`auto`];const DEFAULT_OUTPUT_FORMAT=`png`;const GPT_IMAGE_EDIT_MAX_INPUT_IMAGES=10;const NANO_BANANA_LEGACY_EDIT_MAX_INPUT_IMAGES=3;const NANO_BANANA_EDIT_MAX_INPUT_IMAGES=14;const GROK_IMAGINE_EDIT_MAX_INPUT_IMAGES=3;const KREA_STYLE_REFERENCE_MAX_INPUT_IMAGES=10;const FAL_OUTPUT_FORMATS=[`png`,`jpeg`];const FAL_SUPPORTED_SIZES=[`1024x1024`,`1024x1536`,`1536x1024`,`1024x1792`,`1792x1024`];const FAL_SUPPORTED_ASPECT_RATIOS=[`1:1`,`2:3`,`3:2`,`2.35:1`,`3:4`,`4:3`,`4:5`,`5:4`,`9:16`,`16:9`,`21:9`,`4:1`,`1:4`,`8:1`,`1:8`];const KREA_SUPPORTED_ASPECT_RATIOS=[`1:1`,`4:3`,`3:2`,`16:9`,`2.35:1`,`4:5`,`2:3`,`9:16`];const NANO_BANANA_LEGACY_SUPPORTED_ASPECT_RATIOS=[`21:9`,`16:9`,`3:2`,`4:3`,`5:4`,`1:1`,`4:5`,`3:4`,`2:3`,`9:16`];const NANO_BANANA_SUPPORTED_ASPECT_RATIOS=[...NANO_BANANA_LEGACY_SUPPORTED_ASPECT_RATIOS,`4:1`,`1:4`,`8:1`,`1:8`];const GROK_IMAGINE_SUPPORTED_ASPECT_RATIOS=[`2:1`,`20:9`,`19.5:9`,`16:9`,`4:3`,`3:2`,`1:1`,`2:3`,`3:4`,`9:16`,`9:19.5`,`9:20`,`1:2`];const GROK_IMAGINE_SUPPORTED_RESOLUTIONS=[`1K`,`2K`];const KREA_CREATIVITY_LEVELS=[`raw`,`low`,`medium`,`high`];const FAL_IMAGE_MALFORMED_RESPONSE=`fal image generation response malformed`;const DEFAULT_HTTP_TIMEOUT_MS=3e4;function parseFalImageGenerationResponse(e){if(!isRecord(e))throw new Error(FAL_IMAGE_MALFORMED_RESPONSE);const t=e.images??[];if(!Array.isArray(t)||!t.every(isRecord))throw new Error(FAL_IMAGE_MALFORMED_RESPONSE);return{images:t,prompt:normalizeOptionalString(e.prompt)}}function ensureFalModelPath(e,t,n){if(!t||n.appendEditPath===false)return e;if(isFalGptImage25Model(e))return e.replace(/\/text-to-image$/,`/edit`);return e.includes(`/image-to-image/`)||[n.appendEditPath,`edit`,DEFAULT_FAL_EDIT_SUBPATH].some(t=>e.endsWith(`/${t}`))?e:`${e}/${n.appendEditPath}`}function isFalGptImage25Model(e){return FAL_GPT_IMAGE_25_MODELS.some(t=>t===e)}function resolveFalImageModelSchema(e){const t={referenceImages:`image_urls`,referenceLimitNoun:`reference image`,appendEditPath:`edit`,supportsCount:true,supportsOutputFormat:true};if(isFalGptImage25Model(e))return{...t,geometry:`image_size`,maxInputImages:GPT_IMAGE_25_EDIT_MAX_INPUT_IMAGES,referenceLimitLabel:`fal GPT Image 2.5 edit`};if(e.startsWith(FAL_KREA_2_MODEL_PREFIX))return{geometry:`native_aspect_ratio`,aspectRatios:KREA_SUPPORTED_ASPECT_RATIOS,referenceImages:`image_style_references`,maxInputImages:KREA_STYLE_REFERENCE_MAX_INPUT_IMAGES,referenceLimitLabel:`fal Krea 2`,referenceLimitNoun:`style reference`,appendEditPath:false,supportsCount:false,supportsOutputFormat:false};if(e===FAL_NANO_BANANA_MODEL||e.startsWith(`${FAL_NANO_BANANA_MODEL}/`))return{...t,geometry:`native_aspect_ratio`,aspectRatios:NANO_BANANA_LEGACY_SUPPORTED_ASPECT_RATIOS,resolutions:[],maxInputImages:NANO_BANANA_LEGACY_EDIT_MAX_INPUT_IMAGES,referenceLimitLabel:`fal Nano Banana`};if(e.startsWith(`openai/gpt-image-`)||e.startsWith(`${FAL_NANO_BANANA_MODEL}-`)){const n=e.startsWith(`${FAL_NANO_BANANA_MODEL}-`);return{...t,geometry:n?`native_aspect_ratio`:`image_size`,...n?{aspectRatios:NANO_BANANA_SUPPORTED_ASPECT_RATIOS}:{},maxInputImages:n?NANO_BANANA_EDIT_MAX_INPUT_IMAGES:GPT_IMAGE_EDIT_MAX_INPUT_IMAGES,referenceLimitLabel:n?`fal Nano Banana 2`:`fal GPT Image edit`}}if(e.startsWith(FAL_NANO_BANANA_2_LITE_MODEL))return{...t,geometry:`native_aspect_ratio`,aspectRatios:NANO_BANANA_SUPPORTED_ASPECT_RATIOS,resolutions:[],maxInputImages:NANO_BANANA_EDIT_MAX_INPUT_IMAGES,referenceLimitLabel:`fal Nano Banana 2 Lite`};if(e.startsWith(FAL_GROK_IMAGINE_MODEL))return{...t,geometry:`native_aspect_ratio`,aspectRatios:GROK_IMAGINE_SUPPORTED_ASPECT_RATIOS,resolutions:GROK_IMAGINE_SUPPORTED_RESOLUTIONS,resolutionCase:`lower`,maxInputImages:GROK_IMAGINE_EDIT_MAX_INPUT_IMAGES,referenceLimitLabel:`fal Grok Imagine`};return{geometry:`image_size`,referenceImages:`image_url`,maxInputImages:1,referenceLimitLabel:`fal flux image generation currently`,referenceLimitNoun:`reference image`,appendEditPath:`image-to-image`,supportsCount:true,supportsOutputFormat:true}}function parseSize(e){const t=e?.trim();if(!t)return null;const n=/^(\d{2,5})x(\d{2,5})$/iu.exec(t);if(!n)return null;const r=Number.parseInt(n[1]??``,10);const i=Number.parseInt(n[2]??``,10);if(r<=0||i<=0)return null;return{width:r,height:i}}const FAL_ASPECT_RATIO_SIZES=/* @__PURE__ */ new Map([[`1:1`,`square_hd`],[`4:3`,`landscape_4_3`],[`3:4`,`portrait_4_3`],[`16:9`,`landscape_16_9`],[`9:16`,`portrait_16_9`]]);function parseAspectRatioParts(e){const t=/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/u.exec(e.trim());if(!t)throw new Error(`Invalid fal aspect ratio: ${e}`);const n=Number.parseFloat(t[1]??``);const r=Number.parseFloat(t[2]??``);if(!Number.isFinite(n)||!Number.isFinite(r)||n<=0||r<=0)throw new Error(`Invalid fal aspect ratio: ${e}`);return{widthRatio:n,heightRatio:r}}function aspectRatioToDimensions(e,t){const{widthRatio:n,heightRatio:r}=parseAspectRatioParts(e);if(n>=r)return{width:t,height:Math.max(1,Math.round(t*r/n))};return{width:Math.max(1,Math.round(t*n/r)),height:t}}function resolveFalImageSize(e,t){const n=parseSize(e.size);if(n)return n;const r=e.aspectRatio?.trim();const i=e.resolution?e.resolution===`4K`?4096:e.resolution===`2K`?2048:1024:void 0;if(r){if(i&&!t)return aspectRatioToDimensions(r,i);return FAL_ASPECT_RATIO_SIZES.get(r)??aspectRatioToDimensions(r,1024)}return i?{width:i,height:i}:void 0}function validateFalGptImage25Size(e){if(e===void 0||typeof e===`string`)return;const{width:t,height:n}=e;const r=t*n;if(t%16!==0||n%16!==0||Math.max(t,n)>3840||r<655360||r>8294400||t>n*3||n>t*3)throw new Error(`fal GPT Image 2.5 requires size dimensions divisible by 16, edges up to 3840, 655360-8294400 pixels, and aspect ratio between 1:3 and 3:1. Use size 1024x1024, 1536x1024, 1024x1536, or auto instead of incompatible geometry hints.`)}function aspectRatioScore(e,t){const{widthRatio:n,heightRatio:r}=parseAspectRatioParts(e);return Math.abs(Math.log(n/r)-Math.log(t))}function mapGptImage25Models(e){return Object.fromEntries(FAL_GPT_IMAGE_25_MODELS.map(t=>[t,e()]))}function buildFalImageGenerationProvider(){return{id:`fal`,label:`fal`,defaultModel:DEFAULT_FAL_IMAGE_MODEL,models:[DEFAULT_FAL_IMAGE_MODEL,`${DEFAULT_FAL_IMAGE_MODEL}/${DEFAULT_FAL_EDIT_SUBPATH}`,FAL_KREA_2_MEDIUM_MODEL,FAL_KREA_2_LARGE_MODEL,...FAL_GPT_IMAGE_25_MODELS],isConfiguredAsync:e=>isProviderApiKeyConfiguredAsync({provider:`fal`,...e}),capabilities:{generate:{maxCount:4,supportsSize:true,supportsAspectRatio:true,supportsResolution:true},edit:{enabled:true,maxCount:4,maxInputImages:1,maxInputImagesByModel:{...mapGptImage25Models(()=>GPT_IMAGE_25_EDIT_MAX_INPUT_IMAGES),[FAL_NANO_BANANA_MODEL]:NANO_BANANA_LEGACY_EDIT_MAX_INPUT_IMAGES,[`${FAL_NANO_BANANA_MODEL}/edit`]:NANO_BANANA_LEGACY_EDIT_MAX_INPUT_IMAGES},maxInputImagesByModelPrefix:{"openai/gpt-image-":GPT_IMAGE_EDIT_MAX_INPUT_IMAGES,[FAL_KREA_2_MODEL_PREFIX]:KREA_STYLE_REFERENCE_MAX_INPUT_IMAGES,[`${FAL_NANO_BANANA_MODEL}-`]:NANO_BANANA_EDIT_MAX_INPUT_IMAGES,[FAL_NANO_BANANA_2_LITE_MODEL]:NANO_BANANA_EDIT_MAX_INPUT_IMAGES,[FAL_GROK_IMAGINE_MODEL]:GROK_IMAGINE_EDIT_MAX_INPUT_IMAGES},supportsSize:true,supportsAspectRatio:true,supportsResolution:true},geometry:{sizes:[...FAL_SUPPORTED_SIZES],sizesByModel:{...mapGptImage25Models(()=>[]),[FAL_KREA_2_MEDIUM_MODEL]:[],[FAL_KREA_2_LARGE_MODEL]:[]},aspectRatios:[...FAL_SUPPORTED_ASPECT_RATIOS],aspectRatiosByModel:Object.fromEntries([FAL_NANO_BANANA_MODEL,`${FAL_NANO_BANANA_MODEL}/edit`,FAL_NANO_BANANA_2_LITE_MODEL,`${FAL_NANO_BANANA_2_LITE_MODEL}/edit`,FAL_GROK_IMAGINE_MODEL,`${FAL_GROK_IMAGINE_MODEL}/edit`,`${FAL_GROK_IMAGINE_MODEL}/quality`,`${FAL_GROK_IMAGINE_MODEL}/quality/edit`,FAL_KREA_2_MEDIUM_MODEL,FAL_KREA_2_LARGE_MODEL,`${FAL_NANO_BANANA_MODEL}-2`,`${FAL_NANO_BANANA_MODEL}-2/edit`].flatMap(e=>{const t=resolveFalImageModelSchema(e).aspectRatios;return t?[[e,[...t]]]:[]})),resolutions:[`1K`,`2K`,`4K`],resolutionsByModel:{...mapGptImage25Models(()=>[]),[FAL_KREA_2_MEDIUM_MODEL]:[],[FAL_KREA_2_LARGE_MODEL]:[],[FAL_NANO_BANANA_MODEL]:[],[`${FAL_NANO_BANANA_MODEL}/edit`]:[],[FAL_NANO_BANANA_2_LITE_MODEL]:[],[`${FAL_NANO_BANANA_2_LITE_MODEL}/edit`]:[],[FAL_GROK_IMAGINE_MODEL]:[...GROK_IMAGINE_SUPPORTED_RESOLUTIONS],[`${FAL_GROK_IMAGINE_MODEL}/edit`]:[...GROK_IMAGINE_SUPPORTED_RESOLUTIONS],[`${FAL_GROK_IMAGINE_MODEL}/quality`]:[...GROK_IMAGINE_SUPPORTED_RESOLUTIONS],[`${FAL_GROK_IMAGINE_MODEL}/quality/edit`]:[...GROK_IMAGINE_SUPPORTED_RESOLUTIONS]}},output:{formats:[...FAL_OUTPUT_FORMATS],formatsByModel:mapGptImage25Models(()=>[...GPT_IMAGE_25_OUTPUT_FORMATS]),qualitiesByModel:mapGptImage25Models(()=>[...GPT_IMAGE_25_QUALITIES]),backgroundsByModel:mapGptImage25Models(()=>[...GPT_IMAGE_25_BACKGROUNDS])}},async generateImage(e){const t=createProviderOperationDeadline({timeoutMs:e.timeoutMs,label:`fal image generation`});const n=e.inputImages?.length??0;const r=n>0;const i=e.model?.trim()||DEFAULT_FAL_IMAGE_MODEL;const a=resolveFalImageModelSchema(i);const o=isFalGptImage25Model(i);if(o&&e.resolution)throw new Error(`fal GPT Image 2.5 does not support resolution overrides; use size instead`);if(o&&e.size&&e.size!==`auto`&&!parseSize(e.size))throw new Error(`fal GPT Image 2.5 size must be WIDTHxHEIGHT or auto`);let s;if(o&&e.size===`auto`)s=`auto`;else if(o&&e.aspectRatio&&!e.size){const{width:t,height:n}=aspectRatioToDimensions(e.aspectRatio,1536);s={width:Math.round(t/16)*16,height:Math.round(n/16)*16}}else s=resolveFalImageSize(e,r);if(o)validateFalGptImage25Size(s);const c=ensureFalModelPath(i,r,a);if(r&&n>a.maxInputImages){const e=a.maxInputImages===1?`one`:String(a.maxInputImages);const t=a.maxInputImages===1?a.referenceLimitNoun:`${a.referenceLimitNoun}s`;throw new Error(`${a.referenceLimitLabel} supports at most ${e} ${t} (requested ${n})`)}if(r&&a.referenceImages===`image_url`&&e.aspectRatio)throw new Error(`fal flux image edit endpoint does not support aspectRatio overrides`);if(!a.supportsCount&&(e.count??1)>1)throw new Error(`fal ${i} supports one output image per request`);if(!a.supportsOutputFormat&&e.outputFormat)throw new Error(`fal ${i} does not support outputFormat overrides`);const{baseUrl:l,headers:u,dispatcherPolicy:d}=await resolveFalHttpRequestConfig({req:e,capability:`image`});const f=resolveGeneratedImageDownloadMaxBytes(e.cfg);const p={prompt:e.prompt,...a.supportsCount?{num_images:e.count??1}:{},...a.supportsOutputFormat?{output_format:e.outputFormat??DEFAULT_OUTPUT_FORMAT}:{},...o&&e.quality?{quality:e.quality}:{},...o&&e.background?{background:e.background}:{}};if(a.referenceImages===`image_style_references`){const t=isRecord(e.providerOptions?.fal)?e.providerOptions.fal:void 0;const n=normalizeLowercaseStringOrEmpty(t?.creativity);p.creativity=KREA_CREATIVITY_LEVELS.some(e=>e===n)?n:`medium`}if(a.geometry===`native_aspect_ratio`){if(e.resolution&&a.referenceImages===`image_style_references`)throw new Error(`fal Krea 2 supports aspectRatio but not resolution overrides`);let t=e.aspectRatio?.trim();const n=a.aspectRatios;const r=e.size?s:void 0;if(t){if(n&&!n.includes(t))throw new Error(`${a.referenceLimitLabel} supports aspectRatio values: ${n.join(`, `)}`)}else if(n&&r&&typeof r!==`string`){const e=r.width/r.height;t=n.reduce((t,n)=>{if(!t)return n;return aspectRatioScore(n,e)<aspectRatioScore(t,e)?n:t},void 0)}if(t)p.aspect_ratio=t;if(e.resolution&&a.referenceImages===`image_urls`){const t=a.resolutions;if(t===void 0)p.resolution=e.resolution;else if(t.length===0)throw new Error(`${a.referenceLimitLabel} does not support resolution overrides`);else if(!t.includes(e.resolution))throw new Error(`${a.referenceLimitLabel} supports resolution values: ${t.join(`, `)}`);else p.resolution=a.resolutionCase===`lower`?e.resolution.toLowerCase():e.resolution}}else if(s!==void 0)p.image_size=s;if(r){const t=(e.inputImages??[]).map(toImageDataUrl);if(a.referenceImages===`image_urls`)p.image_urls=t;else if(a.referenceImages===`image_style_references`)p.image_style_references=t.map(e=>({image_url:e}));else p.image_url=t[0]}const{response:m,release:h}=await fetchWithSsrFGuard({url:`${l}/${c}`,signal:e.signal,init:{method:`POST`,headers:u,body:JSON.stringify(p)},timeoutMs:t.timeoutMs===void 0?void 0:resolveProviderOperationTimeoutMs({deadline:t,defaultTimeoutMs:t.timeoutMs}),dispatcherPolicy:d,auditContext:`fal-image-generate`});try{await assertOkOrThrowHttpError(m,`fal image generation failed`);const n=parseFalImageGenerationResponse(await readProviderJsonResponse(m,`fal.image-generation`));const r=[];for(const i of n.images){const n=normalizeOptionalString(i.url);if(!n)throw new Error(FAL_IMAGE_MALFORMED_RESPONSE);const{response:a,release:o}=await fetchWithSsrFGuard({url:n,signal:e.signal,timeoutMs:resolveProviderOperationTimeoutMs({deadline:t,defaultTimeoutMs:t.timeoutMs??DEFAULT_HTTP_TIMEOUT_MS}),auditContext:`fal-image-download`});try{await assertOkOrThrowProviderError(a,`fal image download failed`);const e=a.headers.get(`content-type`)?.trim()||`image/png`;const t=await readProviderBinaryResponse(a,`fal generated image download`,`image`,{maxBytes:f,chunkTimeoutMs:0,onOverflow:({maxBytes:e})=>/* @__PURE__ */ new Error(`fal generated image download exceeds ${e} bytes`)});r.push({buffer:t,mimeType:e,fileName:`image-${r.length+1}.${imageFileExtensionForMimeType(e)}`})}finally{await o()}}if(r.length===0)throw new Error(`fal image generation response missing image data`);return{images:r,model:c,metadata:n.prompt?{prompt:n.prompt}:void 0}}finally{await h()}}}}export{buildFalImageGenerationProvider as t};