@ax-llm/ax 25.4.3 → 25.4.4

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/index.cjs CHANGED
@@ -861,7 +861,7 @@ UPDATE an existing bullet if one already covers this failure mode.`}}async funct
861
861
  `)),a?i=e:r.push({role:`user`,content:e})}else if(n.role===`assistant`){let e=n.content||``;r.push({role:`assistant`,content:e})}else if(n.role===`function`){let e=n.content?.length?n.content.map(e=>e.type===`text`?e.text:e.type===`image`?e.altText??`[Image: ${e.mimeType}]`:e.type===`audio`?e.transcription??`[Audio: ${e.mimeType??`application/octet-stream`}]`:e.type===`url`?e.cachedContent??[e.title,e.description,e.url].filter(Boolean).join(`
862
862
  `):e.extractedText??`[File: ${e.filename??`file`} (${e.mimeType})]`).join(`
863
863
  `):typeof n.result==`string`?n.result:JSON.stringify(n.result);r.push({role:`assistant`,content:e})}}!i&&e.chatPrompt.length>0&&e.chatPrompt[e.chatPrompt.length-1].role!==`user`&&(i=``);let a;if(e.responseFormat?.schema){if(typeof e.responseFormat.schema==`string`)try{a=JSON.parse(e.responseFormat.schema)}catch{}else typeof e.responseFormat.schema==`object`&&e.responseFormat.schema!==null&&(a=e.responseFormat.schema.schema||e.responseFormat.schema)}return[{name:`/prompt`,localCall:async(e,n)=>{let r=e,i=nT(this.suppliedLanguageModel);if(typeof i.availability==`function`){let e=await i.availability();if(e===`unavailable`||e===`no`)throw Error(`Chrome built-in AI model is not available on this device.`)}else if(typeof i.capabilities==`function`){let e=await i.capabilities();if(e.available===`no`||e.available===`unavailable`)throw Error(`Chrome built-in AI model is not available on this device.`)}let{temperature:a,topK:o}=r;if(a===void 0!=(o===void 0)){let e=i.params?await i.params():await i.capabilities?.();if(a??=e?.defaultTemperature,o??=e?.defaultTopK,a===void 0||o===void 0)throw Error(`Chrome AI sampling requires both temperature and topK, or neither. Supply both values or use a Chrome extension with LanguageModel.params().`)}let s=await i.create({...r.initialPrompts.length>0?{initialPrompts:r.initialPrompts}:{},...a===void 0?{}:{temperature:a},...o===void 0?{}:{topK:o},signal:t?.abortSignal}),c=!1;try{let e={...r.responseConstraint?{responseConstraint:r.responseConstraint}:{},...t?.abortSignal?{signal:t.abortSignal}:{}},i=Object.keys(e).length>0;if(n){let t=this.handleStreaming(s,r.prompt,i?e:void 0);return c=!0,t}let a=await s.prompt(r.prompt,i?e:void 0);return{id:`chrome-ai-${Date.now()}`,content:a,finishReason:`stop`}}finally{c||rT(s)}}},{model:n,initialPrompts:r,prompt:i,...a?{responseConstraint:a}:{},...e.modelConfig?.temperature===void 0?this.config.temperature===void 0?{}:{temperature:this.config.temperature}:{temperature:e.modelConfig.temperature},...e.modelConfig?.topK===void 0?this.config.topK===void 0?{}:{topK:this.config.topK}:{topK:e.modelConfig.topK},stream:e.modelConfig?.stream??this.config.stream}]}handleStreaming(e,t,n){let r=`chrome-ai-${Date.now()}`,i=e.promptStreaming(t,n),a=!1,o=()=>{a||(a=!0,rT(e))};if(i&&typeof i.getReader==`function`){let e=i.getReader();return new ReadableStream({async pull(t){try{let{done:n,value:i}=await e.read();if(n){o(),t.close();return}let a={id:r,content:i??``,done:!1};t.enqueue(a)}catch(e){o(),t.error(e)}},cancel(){o()}})}if(i&&typeof i[Symbol.asyncIterator]==`function`){let e=i[Symbol.asyncIterator]();return new ReadableStream({async pull(t){try{let{done:n,value:i}=await e.next();if(n){o(),t.close();return}let a={id:r,content:i??``,done:!1};t.enqueue(a)}catch(e){o(),t.error(e)}},cancel(){o()}})}throw Error(`Chrome AI promptStreaming did not return a valid stream`)}createEmbedReq=e=>{throw Error(`Chrome AI does not support embeddings`)};createChatResp=e=>({results:[{index:0,id:e.id,content:e.content,finishReason:e.finishReason}],remoteId:e.id});createChatStreamResp=(e,t)=>{let n=e.done?`stop`:void 0;return{results:[{index:0,id:e.id,content:e.content,finishReason:n}],remoteId:e.id}};createEmbedResp(e){throw Error(`Chrome AI does not support embeddings`)}},aT=class extends Sy{constructor({languageModel:e,config:t,options:n,models:r}={}){let i={...eT(),...t},a=new iT(i,e);super(a,{name:`ChromeAI`,apiURL:void 0,headers:async()=>({}),modelInfo:ox,defaults:{model:i.model},supportFor:e=>({functions:!1,streaming:!0,structuredOutputs:!0,structuredOutputModes:[`native`],hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:`none`},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}),options:n,models:r})}};const oT=e=>e.includes(`gemini-3`),sT=e=>e===`gemini-3.8-flash`||e===`gemini-3.7-flash`||e===`gemini-3.6-flash`||e===`gemini-3.5-flash-lite`,cT=e=>e===`gemini-3.8-flash`||e===`gemini-3.7-flash`||e===`gemini-3.6-flash`,lT=e=>[`gemini-3.8-flash`,`gemini-3.7-flash`,`gemini-3.6-flash`,`gemini-3.5-flash`,`gemini-3.5-flash-lite`,`gemini-3.1-pro-preview`,`gemini-3.1-flash-lite`,`gemini-2.5-flash`,`gemini-2.5-pro`].includes(e),uT=({model:e,modelConfig:t,config:n,isVertex:r,explicit:i})=>{let a=sT(e),o=cT(e),s=!r&&lT(e),c={};if(!a){let r=t?.temperature??n.temperature;oT(e)&&(r===void 0||r<1)&&(r!==void 0&&i.has(`temperature`)&&vy(`${e}\u0000temperature-raised`,`Ax raised temperature ${r} to 1 for ${e}: Google recommends 1.0 for Gemini 3 models.`),r=1),c.temperature=r,t?.topP!==void 0&&(c.topP=t.topP),c.topK=t?.topK}t?.presencePenalty!==void 0&&yy(e,`presencePenalty`,s?`the model does not accept it`:`Ax does not send it to Gemini`);let l=t?.frequencyPenalty??n.frequencyPenalty;l!==void 0&&(o||s?yy(e,`frequencyPenalty`,`the model does not accept it`):c.frequencyPenalty=l);let u=t?.n??n.n,d=o||!r&&oT(e);return u!==void 0&&u>1&&d&&yy(e,`n`,`the model returns one candidate`),o||(c.candidateCount=d?1:u??1),c},dT=/* @__PURE__ */ new Set([`none`,`minimal`,`low`,`medium`,`high`,`highest`]),fT=e=>{let t=e.toLowerCase();if(oT(t))return t===`gemini-3.8-live`?`unsupported`:t.includes(`-image`)?`image`:t.includes(`gemini-3-pro`)?`legacy-pro`:t.includes(`gemini-3.8-flash`)||t.includes(`gemini-3.7-flash`)||t.includes(`gemini-3.1-pro`)||t.includes(`gemini-3.8-live-extended-thinking`)?`no-minimal`:`full`},pT=(e,t)=>{switch(fT(e)){case`image`:return t===`minimal`||t===`low`?`minimal`:`high`;case`legacy-pro`:return t===`minimal`||t===`low`?`low`:`high`;case`no-minimal`:return t===`minimal`?`low`:t;case`full`:case`unsupported`:case void 0:return t}},mT=e=>e.toLowerCase()===`gemini-3.8-live-extended-thinking`,hT=({model:e,direct:t,logicalLevel:n,showThoughts:r,thinkingLevelMapping:i,thinkingTokenBudgetLevels:a})=>{let o={},s=fT(e);if(s===`unsupported`)return o;if(t?.thinkingTokenBudget!==void 0){if(s)throw Error(`Gemini 3 models (${e}) do not support numeric thinkingTokenBudget. Use a logical thinkingTokenBudget level or thinkingLevel instead.`);o.thinkingBudget=e.includes(`gemini-2.5-pro`)&&t.thinkingTokenBudget===0?a?.minimal??200:t.thinkingTokenBudget}if(t?.thinkingLevel!==void 0&&s&&(o.thinkingLevel=pT(e,t.thinkingLevel)),t?.includeThoughts!==void 0&&(o.includeThoughts=t.includeThoughts),n!==void 0){if(typeof n==`number`){if(s)throw Error(`Gemini 3 models (${e}) do not support numeric thinkingTokenBudget. Use a logical thinkingTokenBudget level instead.`);o.thinkingBudget=e.includes(`gemini-2.5-pro`)&&n===0?a?.minimal??200:n,delete o.thinkingLevel}else{if(!dT.has(n))throw Error(`Unsupported Gemini thinkingTokenBudget level '${String(n)}'`);if(s){let t=n===`none`?`minimal`:n,r=t===`highest`?`high`:t,a=i?.[t]??r;o.thinkingLevel=pT(e,a),delete o.thinkingBudget}else{let t=a?.minimal??200;o.thinkingBudget={none:e.includes(`gemini-2.5-pro`)?t:0,minimal:t,low:a?.low??800,medium:a?.medium??5e3,high:a?.high??1e4,highest:a?.highest??24500}[n],delete o.thinkingLevel}}}return r!==void 0&&(o.includeThoughts=r),n===`none`&&(o.includeThoughts=!1),o.thinkingLevel===void 0&&mT(e)&&(o.thinkingLevel=`medium`),o.thinkingLevel!==void 0&&delete o.thinkingBudget,o},gT=(e,t)=>t?`v1beta1`:`v1`,_T=/* @__PURE__ */ new Set([`gemini-embedding-2`]),vT=e=>`embedding`in e,yT=e=>{if(!e||typeof e!=`object`)return e;let t={...e},n=Array.isArray(t.type)&&t.type.length===2&&t.type.includes(`null`);return delete t.default,delete t.optional,delete t.oneOf,delete t.anyOf,Array.isArray(t.type)&&!n&&(t.type=t.type.includes(`object`)?`object`:t.type[0]??`string`),t.properties&&typeof t.properties==`object`&&(t.properties=Object.fromEntries(Object.entries(t.properties).map(([e,t])=>[e,yT(t)]))),t.items&&=yT(t.items),t},bT=(e,t,n)=>{for(let r=t-1;r>=0;r--){let t=e[r];if(t?.role!==`assistant`||!t.functionCalls)continue;let i=t.functionCalls.find(e=>e.id===n);if(i?.function?.name)return i.function.name}return n},xT=(e,t,n)=>{let r=n.protocolResult?.value,i=[{functionResponse:{id:n.functionId,name:bT(e,t,n.functionId),response:{result:n.result,...r?.structuredContent?{structuredContent:r.structuredContent}:{}}}}];for(let e of n.content??[])e.type===`text`?i.push({text:e.text}):e.type===`image`?i.push({inlineData:{mimeType:e.mimeType,data:e.image}}):e.type===`audio`?i.push({inlineData:{mimeType:e.mimeType??`application/octet-stream`,data:e.data}}):e.type===`file`?i.push({inlineData:{mimeType:e.mimeType,data:e.data}}):i.push({text:e.cachedContent??[e.title,e.description,e.url].filter(Boolean).join(`
864
- `)});return i},ST=[{category:`HARM_CATEGORY_HARASSMENT`,threshold:`BLOCK_NONE`},{category:`HARM_CATEGORY_HATE_SPEECH`,threshold:`BLOCK_NONE`},{category:`HARM_CATEGORY_SEXUALLY_EXPLICIT`,threshold:`BLOCK_NONE`},{category:`HARM_CATEGORY_DANGEROUS_CONTENT`,threshold:`BLOCK_NONE`}],CT=()=>structuredClone({model:`gemini-3.6-flash`,embedModel:`text-embedding-005`,safetySettings:ST,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},thinkingLevelMapping:{minimal:`minimal`,low:`low`,medium:`medium`,high:`high`,highest:`high`},...hy()}),wT=()=>structuredClone({model:`gemini-3.6-flash`,embedModel:`text-embedding-005`,safetySettings:ST,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},thinkingLevelMapping:{minimal:`minimal`,low:`low`,medium:`medium`,high:`high`,highest:`high`},...by()});var TT=class{config;vertexConfig;endpointId;apiKey;credentialProvider;options;vertexApiURLForModel;tokensUsed;models;serviceTierSupportFor;constructor(e,t,n,r,i,a,o){if(this.config=e,this.vertexConfig=t,this.endpointId=n,this.apiKey=r,this.credentialProvider=i,this.options=a,this.vertexApiURLForModel=o,!this.isVertex&&this.config.autoTruncate)throw Error(`Auto truncate is not supported for GoogleGemini`);hT({model:this.config.model,direct:this.config.thinking,thinkingLevelMapping:this.config.thinkingLevelMapping,thinkingTokenBudgetLevels:this.config.thinkingTokenBudgetLevels})}setModels(e){this.models=e}setServiceTierSupportFor(e){this.serviceTierSupportFor=e}resolveServiceTier(e,t,n=!1){let r=t.serviceTier??this.options?.serviceTier??this.config.serviceTier,i=JS(r),a=n||this.isVertex;if(a&&i&&i!==`auto`)throw Error(`Gemini inference service tiers are not supported by ${n?`the Live API`:`Vertex AI`}`);return XS({requested:r,supported:a?[]:this.serviceTierSupportFor?.(e)??[`standard`,`flex`,`priority`],mapping:{auto:null,standard:`standard`,flex:`flex`,priority:`priority`},provider:`Google Gemini`,model:e})}getEffectiveMappings(e){let t=this.models?.find(t=>t.model===e);return{thinkingLevelMapping:{...this.config.thinkingLevelMapping,...t?.thinkingLevelMapping??{}},thinkingTokenBudgetLevels:{...this.config.thinkingTokenBudgetLevels,...t?.thinkingTokenBudgetLevels??{}}}}getTokenUsage(){return this.tokensUsed}get isVertex(){return this.vertexConfig!==void 0}getVertexApiURL(e,t){return this.isVertex?this.vertexApiURLForModel?.(e,t):void 0}async transcribe(e,t){let n=e.model??`gemini-3.5-transcribe`,r=typeof this.apiKey==`function`?await this.apiKey():this.apiKey,i=this.isVertex?`${this.getVertexApiURL(n,t?.beta)}/models/${n}:generateContent`:`https://generativelanguage.googleapis.com/v1beta/models/${n}:generateContent`,a={contents:[{role:`user`,parts:[{inlineData:{mimeType:e.audio.mimeType??fb(e.audio.format,e.audio.sampleRate),data:e.audio.data}},{text:e.prompt??`Generate a transcript of the speech in this audio.`}]}]},o={"Content-Type":`application/json`,...this.isVertex&&r?{Authorization:`Bearer ${r}`}:!this.isVertex&&r?{"x-goog-api-key":r}:{}},s=await(t?.fetch??globalThis.fetch)(i,{method:`POST`,headers:this.credentialProvider?{...o,...await this.credentialProvider({profile:`google-gemini`,operation:`transcribe`,method:`POST`,url:i})}:o,body:JSON.stringify(a),signal:t?.abortSignal});if(!s.ok)throw Error(`Gemini transcription failed: ${s.status} ${s.statusText}`);return{text:(await s.json()).candidates?.[0]?.content?.parts?.map(e=>`audioTranscription`in e?e.audioTranscription.text:`text`in e&&!e.thought?e.text:``).join(``).trim()??``}}async speak(e,t){let n=e.model??`gemini-3.8-flash-tts`,r=typeof this.apiKey==`function`?await this.apiKey():this.apiKey,i=this.isVertex?`${this.getVertexApiURL(n,t?.beta)}/models/${n}:generateContent`:`https://generativelanguage.googleapis.com/v1beta/models/${n}:generateContent`,a=typeof e.voice==`object`?e.voice.id:e.voice??`Kore`;return await kb({url:i,headers:{...this.isVertex&&r?{Authorization:`Bearer ${r}`}:!this.isVertex&&r?{"x-goog-api-key":r}:{},...this.credentialProvider?await this.credentialProvider({profile:`google-gemini`,operation:`speak`,method:`POST`,url:i}):{}},body:{contents:[{role:`user`,parts:[{text:e.text}]}],generationConfig:{responseModalities:[`AUDIO`],speechConfig:{voiceConfig:{prebuiltVoiceConfig:{voiceName:a}}}}},transcript:e.text,fetch:t?.fetch,abortSignal:t?.abortSignal})}getVertexCacheContext(){if(!this.vertexConfig)return;let{projectId:e,region:t}=this.vertexConfig,n=`https://${Dy(t)}/v1`,r=`projects/${e}/locations/${t}`;return{baseUrl:n,parent:r,modelResource:e=>`${r}/publishers/google/models/${e}`}}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,stream:e.stream,n:e.n}}hasProviderDeclaredTools(){return!!(this.options?.codeExecution||this.options?.googleSearchRetrieval||this.options?.googleSearch||this.options?.googleMaps||this.options?.urlContext)}buildToolState(e,t){let n=[];if(e.functions&&e.functions.length>0){let t=e.functions.map(e=>{let t={type:`object`,properties:{dummy:{type:`string`,description:`An optional dummy parameter, do not use`}},required:[]},n=e.parameters?yT(e.parameters):void 0;return n===void 0||n&&typeof n==`object`&&Object.keys(n).length===0?n={...t}:n&&typeof n==`object`&&n.type===`object`&&(!(`properties`in n)||!n.properties||Object.keys(n.properties).length===0)&&(n={...n,properties:{dummy:{type:`string`,description:`An optional dummy parameter, do not use`}},required:[]}),{name:e.name,description:e.description,parametersJsonSchema:n}});n.push({function_declarations:t})}if(this.options?.codeExecution&&n.push({code_execution:{}}),this.options?.googleSearchRetrieval&&n.push({google_search_retrieval:{dynamic_retrieval_config:this.options.googleSearchRetrieval}}),this.options?.googleSearch&&n.push({google_search:{}}),this.options?.googleMaps){let e=this.options.googleMaps,t=e?.enableWidget===void 0?{}:{enableWidget:e.enableWidget};n.push({google_maps:t})}this.options?.urlContext&&n.push({url_context:{}}),n.length===0&&(n=void 0);let r,i=Array.isArray(n)?n.some(e=>e&&Array.isArray(e.function_declarations)&&e.function_declarations.length>0):!1;if(e.functionCall){if(e.functionCall===`none`)r={function_calling_config:{mode:`NONE`}};else if(e.functionCall===`auto`)r={function_calling_config:{mode:`AUTO`}};else if(e.functionCall===`required`)r={function_calling_config:{mode:`ANY`}};else{let t=e.functionCall.function?.name;r={function_calling_config:{mode:`ANY`,...t?{allowed_function_names:[t]}:{}}}}}else i&&(r={function_calling_config:{mode:`AUTO`}});this.options?.retrievalConfig&&(r={...r??{},retrievalConfig:{...this.options.retrievalConfig.latLng?{latLng:this.options.retrievalConfig.latLng}:{}}});let a=e.functions?.some(e=>e.cache)??!1,o=!!(n&&n.length>0)||!!r,s=!!t?.contextCache&&o;return{tools:n,toolConfig:r,cacheableTools:a||s}}createChatReq=async(e,t)=>{let n=e.model,r=e.modelConfig?.stream??this.config.stream,i=Cx(this.config.audio,e.modelConfig?.audio),a=wx(n,this.config.audio,e.modelConfig?.audio),o=this.resolveServiceTier(n,t,a);if(!e.chatPrompt||e.chatPrompt.length===0)throw Error(`Chat prompt is empty`);let s;if(a){if(this.isVertex)throw Error(`Gemini Live audio currently supports Google AI API-key WebSocket sessions only`);s={name:`gemini-live-audio`}}else s=this.endpointId?{name:r?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:{name:r?`/models/${n}:streamGenerateContent?alt=sse`:`/models/${n}:generateContent`};!a&&this.isVertex&&(s.url=this.getVertexApiURL(n,t?.beta));let c=e.chatPrompt.filter(e=>e.role===`system`).map(e=>e.content),l=c.length>0?{role:`user`,parts:[{text:c.join(` `)}]}:void 0,u=[],d=e.chatPrompt.filter(e=>e.role!==`system`);for(let e=0;e<d.length;e++){let t=d[e];switch(t.role){case`user`:{let e=Array.isArray(t.content)?t.content.map((e,t)=>{switch(e.type){case`text`:return{text:e.text};case`image`:return{inlineData:{mimeType:e.mimeType,data:e.image}};case`audio`:return{inlineData:{mimeType:e.mimeType??fb(e.format,e.sampleRate),data:e.data}};case`file`:return`fileUri`in e?{fileData:{mimeType:e.mimeType,fileUri:e.fileUri}}:{inlineData:{mimeType:e.mimeType,data:e.data}};default:throw Error(`Chat prompt content type not supported (index: ${t})`)}}):[{text:t.content}];u.push({role:`user`,parts:e});break}case`assistant`:{let e=[],n=t.thoughtBlocks,r=t.functionCalls&&t.functionCalls.length>0,i=n?.[0],a=n?.map(e=>e.data).join(``)??``,o=i?.signature;if(a&&e.push({...r?{}:{thought:!0},text:a,...o&&!r?{thought_signature:o}:{}}),t.functionCalls){let n=t.functionCalls.map((e,t)=>{let n;if(typeof e.function.params==`string`){let t=e.function.params;if(t.trim().length===0)n={};else try{n=JSON.parse(t)}catch{throw Error(`Failed to parse function params JSON: ${t}`)}}else n=e.function.params;let r={functionCall:{...e.id?{id:e.id}:{},name:e.function.name,args:n}};return o&&t===0&&(r.thought_signature=o),r});e.push(...n)}let s=t.audio?.transcript;if((t.content||s)&&e.push({text:t.content??s??``}),e.length===0)throw Error(`Assistant content is empty`);u.push({role:`model`,parts:e});break}case`function`:{let n=[],r=t,i=e;for(;;){if(!(`functionId`in r))throw Error(`Chat prompt functionId is empty (index: ${i})`);if(n.push(...xT(d,i,r)),i+1<d.length&&d[i+1].role===`function`)i++,r=d[i];else break}e=i,u.push({role:`user`,parts:n});break}default:throw Error(`Invalid role: ${JSON.stringify(t)} (index: ${e})`)}}let{tools:f,toolConfig:p}=this.buildToolState(e,t),m=this.getEffectiveMappings(n),h=hT({model:n,direct:this.config.thinking,logicalLevel:t?.thinkingTokenBudget,showThoughts:t?.showThoughts,...m}),g=e.modelConfig?.maxTokens??this.config.maxTokens;if(h.thinkingLevel&&g!==void 0)throw Error(`Cannot set maxTokens when using thinkingLevel with Gemini models. When thinking is enabled, the model manages output tokens automatically. Remove the maxTokens setting or disable thinking.`);let _={maxOutputTokens:e.modelConfig?.maxTokens??this.config.maxTokens,...uT({model:n,modelConfig:e.modelConfig,config:this.config,isVertex:this.isVertex,explicit:new Set(e.explicitSamplingKeys??[])}),stopSequences:e.modelConfig?.stopSequences??this.config.stopSequences,responseMimeType:`text/plain`,...Object.keys(h).length>0?{thinkingConfig:h}:{}};if(a&&(e.responseFormat||this.config.responseFormat))throw Error(`Gemini Live audio models do not support structured response formats with audio output`);if(e.responseFormat){if(e.responseFormat.type===`json_schema`&&e.responseFormat.schema){let t=e.responseFormat.schema.schema||e.responseFormat.schema;_.responseMimeType=`application/json`,_.responseJsonSchema=yT(t)}else _.responseMimeType=`application/json`}else this.config.responseFormat&&this.config.responseFormat===`json_object`&&(_.responseMimeType=`application/json`);let v={contents:u,tools:f,toolConfig:p,systemInstruction:l,generationConfig:_,safetySettings:this.config.safetySettings,...o?{service_tier:o}:{}};if(a){let e=typeof this.apiKey==`function`?await this.apiKey():this.apiKey;if(!e)throw Error(`GoogleGemini AI API key not set`);s=Dx({model:n,request:v,apiKey:e,audio:i})}return[s,v]};createEmbedReq=async(e,t)=>{let n=e.embedModel;if(!n)throw Error(`Embed model not set`);if(!e.texts||e.texts.length===0)throw Error(`Embed texts is empty`);let r,i;if(this.vertexConfig&&!this.endpointId&&_T.has(n)){if(e.texts.length!==1)throw Error(`${n} on Vertex embeds one text per request; call embed() once per text`);let a=Dy(`global`),o=gT(n,t?.beta);r={name:`/models/${n}:embedContent`,url:`https://${a}/${o}/projects/${this.vertexConfig.projectId}/locations/global/publishers/google`},i={content:{parts:[{text:e.texts[0]}]},autoTruncate:this.config.autoTruncate,outputDimensionality:this.config.dimensions}}else this.isVertex?(r=this.endpointId?{name:`/${this.endpointId}:predict`}:{name:`/models/${n}:predict`},r.url=this.getVertexApiURL(n,t?.beta),i={instances:e.texts.map(e=>({content:e,...this.config.embedType&&{task_type:this.config.embedType}})),parameters:{autoTruncate:this.config.autoTruncate,outputDimensionality:this.config.dimensions}}):(r={name:`/models/${n}:batchEmbedContents`},i={requests:e.texts.map(e=>({model:`models/${n}`,content:{parts:[{text:e}]},outputDimensionality:this.config.dimensions,...this.config.embedType&&{taskType:this.config.embedType}}))});return[r,i]};createChatResp=e=>{let t,n=e.candidates?.map(e=>{let n={index:0};switch(e.finishReason){case`MAX_TOKENS`:n.finishReason=`length`;break;case`STOP`:n.finishReason=`stop`;break;case`SAFETY`:throw new Go(`Content was blocked due to safety settings`,void 0,void 0);case`RECITATION`:throw new Go(`Content was blocked due to recitation policy`,void 0,void 0);case`MALFORMED_FUNCTION_CALL`:throw new Go(`Function call was malformed and blocked`,void 0,void 0);case`UNEXPECTED_TOOL_CALL`:throw new Go(`Unexpected tool call`,void 0,void 0);case`FINISH_REASON_UNSPECIFIED`:throw new Go(`Finish reason unspecified`,void 0,void 0);case`BLOCKLIST`:throw new Go(`Content was blocked due to blocklist`,void 0,void 0);case`PROHIBITED_CONTENT`:throw new Go(`Content was blocked due to prohibited content`,void 0,void 0);case`SPII`:throw new Go(`Content was blocked due to SPII`,void 0,void 0);case`OTHER`:throw new Go(`Other finish reason`,void 0,void 0)}if(!e.content||!e.content.parts)return n;for(let t of e.content.parts){if(`text`in t){if(`thought`in t&&t.thought||t.thought===!0){n.thought=t.text;let e=t.thoughtSignature||t.thought_signature;n.thoughtBlocks||=[],n.thoughtBlocks.push({data:t.text,encrypted:!1,...e?{signature:e}:{}})}else n.content=t.text;continue}if(`functionCall`in t){let e=t.thoughtSignature||t.thought_signature;if(e){if(!n.thoughtBlocks||n.thoughtBlocks.length===0)n.thoughtBlocks=[{data:``,encrypted:!1,signature:e}];else{let t=n.thoughtBlocks[n.thoughtBlocks.length-1];t&&!t.signature&&(t.signature=e)}}n.functionCalls=[...n.functionCalls??[],{id:t.functionCall.id??c(),type:`function`,function:{name:t.functionCall.name,params:t.functionCall.args}}]}let e=Ex(t);e&&(n.audio=e)}let r=e.citationMetadata?.citations;if(Array.isArray(r)&&r.length){let e=e=>e?`${e.year}-${String(e.month).padStart(2,`0`)}-${String(e.day).padStart(2,`0`)}`:void 0;n.citations=r.filter(e=>typeof e?.uri==`string`).map(t=>({url:t.uri,title:t.title,license:t.license,publicationDate:e(t.publicationDate)}))}let i=e.groundingMetadata;if(i){if(Array.isArray(i.groundingChunks)){let e=i.groundingChunks.map(e=>e?.maps).filter(e=>e&&typeof e.uri==`string`).map(e=>({url:e.uri,title:e.title}));e.length&&(n.citations=[...n.citations??[],...e]);let t=i.groundingChunks.map(e=>e?.retrievedContext).filter(e=>e&&(typeof e.uri==`string`||typeof e.media_id==`string`)).map(e=>({url:e.uri??``,title:e.title,...typeof e.media_id==`string`?{mediaId:e.media_id}:{},...Array.isArray(e.page_numbers)?{pageNumbers:e.page_numbers}:{}}));t.length&&(n.citations=[...n.citations??[],...t])}typeof i.googleMapsWidgetContextToken==`string`&&(t=i.googleMapsWidgetContextToken)}return n});if(e.usageMetadata){let t=e.usageMetadata.cachedContentTokenCount??0,n=e.usageMetadata.serviceTier===`unspecified`?`standard`:e.usageMetadata.serviceTier;this.tokensUsed={totalTokens:e.usageMetadata.totalTokenCount,promptTokens:e.usageMetadata.promptTokenCount-t,completionTokens:e.usageMetadata.candidatesTokenCount,thoughtsTokens:e.usageMetadata.thoughtsTokenCount,...t>0?{cacheReadTokens:t}:{},...n?{serviceTier:n}:{}}}let r={results:n,...e.responseId?{remoteId:e.responseId}:{},...e.modelVersion?{providerMetadata:{google:{modelVersion:e.modelVersion}}}:{}};return t&&(r.providerMetadata={...r.providerMetadata,google:{...r.providerMetadata?.google??{},mapsWidgetContextToken:t}}),r};createChatStreamResp=e=>this.createChatResp(e);createEmbedResp=e=>{if(this.tokensUsed=void 0,vT(e)){if(e.usageMetadata){let t=e.usageMetadata.promptTokenCount??0;this.tokensUsed={promptTokens:t,completionTokens:0,totalTokens:e.usageMetadata.totalTokenCount??t}}return{embeddings:[e.embedding.values]}}let t;return t=this.isVertex?e.predictions.map(e=>e.embeddings.values):e.embeddings.map(e=>e.values),{embeddings:t}};supportsContextCache=e=>{let t=e;return _x.some(e=>t.includes(e)||e.includes(t))};buildCacheCreateOp=(e,t)=>{let n=e.model,r=t.contextCache?.ttlSeconds??3600,{tools:i,toolConfig:a,cacheableTools:o}=this.buildToolState(e,t),{systemInstruction:s,contents:c}=this.extractCacheableContent(e.chatPrompt);if(!s&&(!c||c.length===0)&&!o)return;let l=this.getVertexCacheContext(),u={model:l?l.modelResource(n):`models/${n}`,ttl:`${r}s`,displayName:`ax-cache-${Date.now()}`};s&&(u.systemInstruction=s),c&&c.length>0&&(u.contents=c),o&&(i&&i.length>0&&(u.tools=i),a&&(u.toolConfig=a));let d;return d=l?`/${l.parent}/cachedContents`:`/cachedContents`,{type:`create`,apiConfig:{name:d,...l?{url:l.baseUrl}:{}},request:u,parseResponse:e=>{let t=e;if(t?.name)return{name:t.name,expiresAt:t.expireTime,tokenCount:t.usageMetadata?.totalTokenCount}}}};getContextCacheToolState=(e,t)=>{let{tools:n,toolConfig:r,cacheableTools:i}=this.buildToolState(e,t);if(!i)return;let a=e.functions?.map(({cache:e,...t})=>t);if(a&&a.length>0||e.functionCall)return{functions:a,functionCall:e.functionCall};if(n||r)return{functions:[{name:`__gemini_tool_state__`,description:JSON.stringify({tools:n,toolConfig:r})}]}};buildCacheUpdateTTLOp=(e,t)=>{let n={ttl:`${t}s`},r=`/${e}?${new URLSearchParams({updateMask:`ttl`}).toString()}`,i=this.getVertexCacheContext();return{type:`update`,apiConfig:{name:r,method:`PATCH`,headers:{"Content-Type":`application/json`},...i?{url:i.baseUrl}:{}},request:n,parseResponse:e=>{let t=e;if(t?.name)return{name:t.name,expiresAt:t.expireTime,tokenCount:t.usageMetadata?.totalTokenCount}}}};buildCacheDeleteOp=e=>{let t=`/${e}`,n=this.getVertexCacheContext();return{type:`delete`,apiConfig:{name:t,headers:{"Content-Type":`application/json`},...n?{url:n.baseUrl}:{}},request:{},parseResponse:()=>void 0}};prepareCachedChatReq=async(e,t,n)=>{let r=e.model,i=this.resolveServiceTier(r,t),a=e.modelConfig?.stream??this.config.stream,{tools:o,toolConfig:s,cacheableTools:c}=this.buildToolState(e,t),{dynamicContents:l,dynamicSystemInstruction:u}=this.extractDynamicContent(e.chatPrompt),d;d=this.endpointId?{name:a?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:{name:a?`/models/${r}:streamGenerateContent?alt=sse`:`/models/${r}:generateContent`};let f=this.getEffectiveMappings(r),p=hT({model:r,direct:this.config.thinking,logicalLevel:t.thinkingTokenBudget,showThoughts:t.showThoughts,...f}),m={contents:l,cachedContent:n,generationConfig:{maxOutputTokens:e.modelConfig?.maxTokens??this.config.maxTokens,...uT({model:r,modelConfig:e.modelConfig,config:this.config,isVertex:this.isVertex,explicit:new Set(e.explicitSamplingKeys??[])}),stopSequences:e.modelConfig?.stopSequences??this.config.stopSequences,responseMimeType:`text/plain`,...Object.keys(p).length>0?{thinkingConfig:p}:{}},safetySettings:this.config.safetySettings,...i?{service_tier:i}:{}};return c||(o&&o.length>0&&(m.tools=o),s&&(m.toolConfig=s)),u&&(m.systemInstruction=u),{apiConfig:d,request:m}};extractCacheableContent(e){let t,n=[],r=-1;for(let t=e.length-1;t>=0;t--){let n=e[t];if(`cache`in n&&n.cache){r=t;break}}for(let i=0;i<e.length;i++){let a=e[i];if(a.role===`system`){t={role:`user`,parts:[{text:a.content}]};continue}if(r>=0&&i<=r){if(a.role===`user`){let e=[];if(typeof a.content==`string`)e.push({text:a.content});else if(Array.isArray(a.content))for(let t of a.content)switch(t.type){case`text`:e.push({text:t.text});break;case`image`:e.push({inlineData:{mimeType:t.mimeType,data:t.image}});break;case`audio`:e.push({inlineData:{mimeType:t.mimeType??fb(t.format,t.sampleRate),data:t.data}});break;case`file`:`fileUri`in t?e.push({fileData:{mimeType:t.mimeType,fileUri:t.fileUri}}):e.push({inlineData:{mimeType:t.mimeType,data:t.data}})}e.length>0&&n.push({role:`user`,parts:e})}else if(a.role===`assistant`){let e=[],t=a.thoughtBlocks,r=a.functionCalls&&a.functionCalls.length>0,i=t?.[0]?.signature,o=t?.map(e=>e.data).join(``)??``;if(o&&e.push({...r?{}:{thought:!0},text:o,...i&&!r?{thought_signature:i}:{}}),a.functionCalls)for(let[t,n]of a.functionCalls.entries()){let r;if(typeof n.function.params==`string`)try{r=JSON.parse(n.function.params)}catch{r={}}else r=n.function.params??{};let a={functionCall:{...n.id?{id:n.id}:{},name:n.function.name,args:r}};i&&t===0&&(a.thought_signature=i),e.push(a)}a.content&&e.push({text:a.content}),e.length>0&&n.push({role:`model`,parts:e})}else a.role===`function`&&n.push({role:`user`,parts:xT(e,i,a)})}}return{systemInstruction:t,contents:n}}extractDynamicContent(e){let t=[],n=-1;for(let t=e.length-1;t>=0;t--){let r=e[t];if(`cache`in r&&r.cache){n=t;break}}for(let r=0;r<e.length;r++){let i=e[r];if(i.role!==`system`&&!(n>=0&&r<=n)){if(i.role===`user`){let e=[];if(typeof i.content==`string`)e.push({text:i.content});else if(Array.isArray(i.content)){for(let t of i.content)if(!(`cache`in t&&t.cache))switch(t.type){case`text`:e.push({text:t.text});break;case`image`:e.push({inlineData:{mimeType:t.mimeType,data:t.image}});break;case`audio`:e.push({inlineData:{mimeType:t.mimeType??fb(t.format,t.sampleRate),data:t.data}});break;case`file`:`fileUri`in t?e.push({fileData:{mimeType:t.mimeType,fileUri:t.fileUri}}):e.push({inlineData:{mimeType:t.mimeType,data:t.data}})}}e.length>0&&t.push({role:`user`,parts:e})}else if(i.role===`assistant`){let e=[],n=i.thoughtBlocks,r=i.functionCalls&&i.functionCalls.length>0,a=n?.[0]?.signature,o=n?.map(e=>e.data).join(``)??``;if(o&&e.push({...r?{}:{thought:!0},text:o,...a&&!r?{thought_signature:a}:{}}),i.functionCalls)for(let[t,n]of i.functionCalls.entries()){let r;if(typeof n.function.params==`string`)try{r=JSON.parse(n.function.params)}catch{r={}}else r=n.function.params??{};let i={functionCall:{...n.id?{id:n.id}:{},name:n.function.name,args:r}};a&&t===0&&(i.thought_signature=a),e.push(i)}i.content&&e.push({text:i.content}),e.length>0&&t.push({role:`model`,parts:e})}else i.role===`function`&&t.push({role:`user`,parts:xT(e,r,i)})}}return{dynamicContents:t,dynamicSystemInstruction:void 0}}},ET=class e extends Sy{static create(t){return new e(t)}constructor({apiKey:e,credentialProvider:t,projectId:n,region:r,endpointId:i,config:a,options:o,models:s,modelInfo:c}){let l=n!==void 0&&r!==void 0?{projectId:n,region:r}:void 0,u={...CT(),...a};if(l&&u.serviceTier&&u.serviceTier!==`auto`)throw Error(`Gemini inference service tiers are not supported by Vertex AI`);let d,f,p;if(l){let{projectId:n,region:r}=l;if(!e&&!t)throw Error(`GoogleGemini Vertex API key or credential provider not set`);if(e&&typeof e!=`function`)throw Error(`GoogleGemini Vertex API key must be a function for token-based authentication`);let a;a=i?`endpoints`:`publishers/google`;let o=Dy(r);p=(e,t)=>`https://${o}/${gT(e,t)}/projects/${n}/locations/${r}/${a}`,d=p(u.model),f=async()=>({...e?{Authorization:`Bearer ${typeof e==`function`?await e():e}`}:{}})}else{if(!e&&!t)throw Error(`GoogleGemini AI API key or credential provider not set`);d=`https://generativelanguage.googleapis.com/v1beta`,f=async()=>({...e?{"x-goog-api-key":typeof e==`function`?await e():e}:{}})}let m=new TT(u,l,i,e,t,o,p);c=[...vx,...c??[]];let h=e=>{let t=wx(e,{output:{enabled:!0}}),n=Rv({model:e,modelInfo:c,models:s}),r=n?.supported?.structuredOutputs??!0,i=n?.supported?.structuredOutputModes??(r?[`native`,`function`]:[`function`]);return{functions:!0,streaming:!0,hasThinkingBudget:n?.supported?.thinkingBudget??!1,hasShowThoughts:n?.supported?.showThoughts??!1,structuredOutputs:i.includes(`native`),structuredOutputModes:i,media:{images:{supported:!0,formats:[`image/jpeg`,`image/png`,`image/gif`,`image/webp`],maxSize:20971520,detailLevels:[`high`,`low`,`auto`]},audio:{supported:!0,formats:t?[`pcm16`,`pcm`]:[`wav`,`mp3`,`aac`,`ogg`],maxDuration:570,output:{supported:t,formats:[`pcm16`],sampleRate:24e3,voices:[`Kore`]}},files:{supported:!0,formats:[`application/pdf`,`text/plain`,`text/csv`,`text/html`,`text/xml`],maxSize:2147483648,uploadMethod:`cloud`},urls:{supported:!0,webSearch:!0,contextFetching:!0}},caching:{supported:m.supportsContextCache(e),types:[`persistent`]},thinking:n?.supported?.thinkingBudget??!1,multiTurn:!0,serviceTiers:n?.supported?.serviceTiers??(l||t?[]:[`standard`,`flex`,`priority`])}},g=s?.map(e=>{let t=e,n=t?.config;if(!n)return e;let r={};n.maxTokens!==void 0&&(r.maxTokens=n.maxTokens),n.temperature!==void 0&&(r.temperature=n.temperature),n.topP!==void 0&&(r.topP=n.topP),n.topK!==void 0&&(r.topK=n.topK),n.presencePenalty!==void 0&&(r.presencePenalty=n.presencePenalty),n.frequencyPenalty!==void 0&&(r.frequencyPenalty=n.frequencyPenalty),n.stopSequences!==void 0&&(r.stopSequences=n.stopSequences),n.endSequences!==void 0&&(r.endSequences=n.endSequences),n.stream!==void 0&&(r.stream=n.stream),n.n!==void 0&&(r.n=n.n);let i={...t};Object.keys(r).length>0&&(i.modelConfig={...t.modelConfig??{},...r});let a=n.thinking?.thinkingTokenBudget;if(typeof a==`number`){let e=String(t.model??u.model);if(oT(e))throw Error(`Gemini 3 models (${e}) do not support numeric thinkingTokenBudget. Use a logical thinkingTokenBudget level instead.`);let n=u.thinkingTokenBudgetLevels,r=[[`minimal`,n?.minimal??200],[`low`,n?.low??800],[`medium`,n?.medium??5e3],[`high`,n?.high??1e4],[`highest`,n?.highest??24500]],o=`minimal`,s=1/0;for(let[e,t]of r){let n=Math.abs(a-t);n<s&&(s=n,o=e)}i.thinkingTokenBudget=o}return n.thinking?.includeThoughts!==void 0&&(i.showThoughts=!!n.thinking.includeThoughts),n.serviceTier!==void 0&&(i.serviceTier=n.serviceTier),n.thinkingLevelMapping&&(i.thinkingLevelMapping=n.thinkingLevelMapping),n.thinkingTokenBudgetLevels&&(i.thinkingTokenBudgetLevels=n.thinkingTokenBudgetLevels),i});g?m.setModels(g):s&&m.setModels(s),m.setServiceTierSupportFor(e=>h(e).serviceTiers??[]),super(m,{name:`GoogleGeminiAI`,apiURL:d,headers:f,modelInfo:c,defaults:{model:u.model,embedModel:u.embedModel},options:o,credentialProvider:t,profile:`google-gemini`,supportFor:h,models:g??s}),this.setExplicitModelConfigKeys(a)}},DT=class{config;metrics={latency:{chat:{mean:0,p95:0,p99:0,samples:[]},embed:{mean:0,p95:0,p99:0,samples:[]}},errors:{chat:{count:0,rate:0,total:0},embed:{count:0,rate:0,total:0}}};constructor(e={}){this.config=e,this.config.id=this.config.id??c()}getLastUsedChatModel(){return this.config.modelInfo?.name??`mock-model`}getLastUsedEmbedModel(){return this.config.embedModelInfo?.name??`mock-embed-model`}getLastUsedModelConfig(){return this.config.modelInfo?{maxTokens:this.config.modelInfo.maxTokens,temperature:.7,stream:this.config.features?.streaming??!1}:void 0}getName(){return this.config.name??`mock-ai-service`}getId(){return this.config.id??`mock-ai-service-id`}getFeatures(e){let t=this.config.features?.media;return{functions:this.config.features?.functions??!1,streaming:this.config.features?.streaming??!1,structuredOutputs:this.config.features?.structuredOutputs,...this.config.features?.structuredOutputModes?{structuredOutputModes:this.config.features.structuredOutputModes}:{},...this.config.features?.serviceTiers?{serviceTiers:this.config.features.serviceTiers}:{},media:{images:{supported:t?.images?.supported??!1,formats:t?.images?.formats??[]},audio:{supported:t?.audio?.supported??!1,formats:t?.audio?.formats??[]},files:{supported:t?.files?.supported??!1,formats:t?.files?.formats??[],uploadMethod:t?.files?.uploadMethod??`none`},urls:{supported:t?.urls?.supported??!1,webSearch:t?.urls?.webSearch??!1,contextFetching:t?.urls?.contextFetching??!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}getModelList(){return this.config.models}getMetrics(){return this.metrics}getEstimatedCost(){return 0}async chat(e,t){if(this.config.latencyMs&&await new Promise(e=>setTimeout(e,this.config.latencyMs)),this.config.shouldError)throw Error(this.config.errorMessage??`Mock chat error`);return this.updateMetrics(`chat`),typeof this.config.chatResponse==`function`?await this.config.chatResponse(e,t):this.config.chatResponse??{results:[{index:0,content:`Mock response`,finishReason:`stop`}],modelUsage:{ai:this.getName(),model:`mock-model`,tokens:{promptTokens:10,completionTokens:5,totalTokens:15}}}}async embed(e,t){if(this.config.latencyMs&&await new Promise(e=>setTimeout(e,this.config.latencyMs)),this.config.shouldError)throw Error(this.config.errorMessage??`Mock embed error`);return this.updateMetrics(`embed`),typeof this.config.embedResponse==`function`?this.config.embedResponse(e):this.config.embedResponse??{embeddings:[[.1,.2,.3]],modelUsage:{ai:this.getName(),model:`mock-model`,tokens:{promptTokens:5,completionTokens:0,totalTokens:5}}}}async transcribe(e,t){if(this.config.shouldError)throw Error(this.config.errorMessage??`Mock transcribe error`);return typeof this.config.transcribeResponse==`function`?this.config.transcribeResponse(e):this.config.transcribeResponse??{text:`Mock transcription`}}async speak(e,t){if(this.config.shouldError)throw Error(this.config.errorMessage??`Mock speech error`);return typeof this.config.speechResponse==`function`?this.config.speechResponse(e):this.config.speechResponse??{data:`bW9jay1hdWRpbw==`,format:`mp3`,mimeType:`audio/mpeg`,transcript:e.text}}setOptions(e){this.config.options=e}getOptions(){return this.config.options??{}}getLogger(){return this.config.options?.logger??(e=>{console.log(e)})}updateMetrics(e){let t=this.config.latencyMs??0;this.metrics.latency[e].samples.push(t);let n=this.metrics.latency[e].samples;if(this.metrics.latency[e].mean=n.reduce((e,t)=>e+t,0)/n.length,n.length>0){let r=[...n].sort((e,t)=>e-t),i=Math.max(0,Math.floor(r.length*.95)-1);this.metrics.latency[e].p95=r[i]??t;let a=Math.max(0,Math.floor(r.length*.99)-1);this.metrics.latency[e].p99=r[a]??t}if(this.config.shouldError){this.metrics.errors[e].count++,this.metrics.errors[e].total++;let t=this.metrics.latency[e].samples.length;this.metrics.errors[e].rate=t>0?this.metrics.errors[e].count/t:0}}},OT=class e{options;lastUsedService;services=/* @__PURE__ */ new Map;constructor(e){if(e.length===0)throw Error(`No AI services provided.`);for(let[t,n]of e.entries())if(`key`in n){if(this.services.has(n.key))throw Error(`Duplicate model key: ${n.key}`);let{service:e,description:t,isInternal:r}=n;this.services.set(n.key,{service:e,description:t,isInternal:r})}else{let e=n.getModelList();if(!e)throw Error(`Service ${t} \`${n.getName()}\` has no model list.`);for(let r of e){if(this.services.has(r.key)){let e=this.services.get(r.key)?.service;throw Error(`Service ${t} \`${n.getName()}\` has duplicate model key: ${r.key} as service ${e?.getName()}`)}if(`model`in r&&typeof r.model)this.services.set(r.key,{description:r.description,service:n,model:r.model});else if(`embedModel`in r&&r.embedModel)this.services.set(r.key,{description:r.description,service:n,embedModel:r.embedModel});else throw Error(`Key ${r.key} in model list for service ${t} \`${n.getName()}\` is missing a model or embedModel property.`)}}}static create(t){return new e(t)}getLastUsedChatModel(){return this.lastUsedService?.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.lastUsedService?.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.lastUsedService?.getLastUsedModelConfig()}async resolveChatService(e){let t=e.model?this.services.get(e.model):void 0;if(!t)throw Error(`No service found for model key: ${String(e.model)}`);return this.lastUsedService=t.service,{service:t.service,model:t.model?e.model:void 0}}async openChatSession(e,t){let n=e.model?this.services.get(e.model):void 0;if(!n)throw Error(`No service found for model key: ${String(e.model)}`);if(!n.service.openChatSession)throw Error(`Selected service does not support chat sessions`);this.lastUsedService=n.service;let{model:r,...i}=e;return await n.service.openChatSession(n.model?e:i,t)}async chat(e,t){let n=e.model;if(!n)throw Error(`Model key must be specified for multi-service`);let r=this.services.get(n);if(!r)throw Error(`No service found for model key: ${n}`);if(this.lastUsedService=r.service,!r.model){let{model:n,...i}=e;return await r.service.chat(i,t)}return await r.service.chat({model:n,...e},t)}async embed(e,t){let n=e.embedModel;if(!n)throw Error(`Embed model key must be specified for multi-service`);let r=this.services.get(n);if(!r)throw Error(`No service found for embed model key: ${n}`);if(this.lastUsedService=r.service,!r.model&&!r.embedModel){let{embedModel:n,...i}=e;return await r.service.embed(i,t)}return await r.service.embed({embedModel:n,...e},t)}async transcribe(e,t){let n=e.model;if(!n){let n=Array.from(this.services.values())[0]?.service;if(!n)throw Error(`No AI services provided.`);return this.lastUsedService=n,await n.transcribe(e,t)}let r=this.services.get(n);if(!r)throw Error(`No service found for transcription model key: ${n}`);return this.lastUsedService=r.service,await r.service.transcribe(e,t)}async speak(e,t){let n=e.model;if(!n){let n=Array.from(this.services.values())[0]?.service;if(!n)throw Error(`No AI services provided.`);return this.lastUsedService=n,await n.speak(e,t)}let r=this.services.get(n);if(!r)throw Error(`No service found for speech model key: ${n}`);return this.lastUsedService=r.service,await r.service.speak(e,t)}getId(){return`MultiServiceRouter:${Array.from(this.services.values()).map(e=>e.service.getId()).join(`,`)}`}getName(){return`MultiServiceRouter`}getModelList(){return Array.from(this.services).filter(([,e])=>!e.isInternal).map(([e,t])=>{if(t.model)return{key:e,description:t.description,model:t.model};if(t.embedModel)return{key:e,description:t.description,embedModel:t.embedModel};throw Error(`Service ${e} has no model or embedModel`)})}getFeatures(e){if(e){let t=this.services.get(e);if(t)return t.service.getFeatures(t.model?e:void 0)}return{functions:!1,streaming:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:`none`},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}getMetrics(){let e=this.lastUsedService;if(!e){let t=this.services.values().next().value;t&&(e=`service`in t?t.service:t)}if(!e)throw Error(`No service available to get metrics.`);return e.getMetrics()}getEstimatedCost(e){return this.lastUsedService?.getEstimatedCost(e)??0}setOptions(e){for(let t of this.services.values())t.service.setOptions(e);this.options=e}getOptions(){return this.options??{}}getLogger(){let e=this.lastUsedService;if(!e){let t=this.services.values().next().value;t&&(e=t.service)}if(!e)throw Error(`No service available to get logger.`);return e.getLogger()}setServiceEntry(e,t){this.services.set(e,t)}};function kT(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`OpenAI Decisions: invalid ${t}`);return e}function AT(e,t){if(typeof e!=`string`)throw Error(`OpenAI Decisions: invalid ${t}`)}function jT(e,t){if(typeof e!=`string`||!e.trim())throw Error(`OpenAI Decisions: invalid ${t}`)}function MT(e,t){if(typeof e!=`number`||!Number.isFinite(e)||e<0||e>1)throw Error(`OpenAI Decisions: invalid probability for ${t}`);return e}function NT(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(`OpenAI Decisions: invalid ${t}`)}function PT(e){jT(e.model,`model`),e.safety_identifier!=null&&AT(e.safety_identifier,`safety_identifier`);let t=0;if(typeof e.input!=`string`){if(!Array.isArray(e.input)||!e.input.length)throw Error(`OpenAI Decisions: input must be text or user messages`);for(let n of e.input){let e=kT(n,`input message`);if(e.role!==`user`||e.type!==void 0&&e.type!==`message`)throw Error(`OpenAI Decisions: only user messages are supported`);if(typeof e.content!=`string`){if(!Array.isArray(e.content)||!e.content.length)throw Error(`OpenAI Decisions: invalid input content`);for(let n of e.content){let e=kT(n,`input part`);if(e.type!==`input_text`||typeof e.text!=`string`){if(e.type!==`input_image`||typeof e.image_url!=`string`||!/^data:image\/[a-zA-Z0-9.+-]+;base64,[A-Za-z0-9+/]+={0,2}$/.test(e.image_url))throw Error(`OpenAI Decisions: images require inline base64 data URLs; files, audio, and hosted URLs are unsupported`);if(e.detail!=null&&![`low`,`high`,`auto`,`original`].includes(String(e.detail)))throw Error(`OpenAI Decisions: invalid image detail`);t++}}}}}if(t>128)throw Error(`OpenAI Decisions: at most 128 images are supported`);if(!Array.isArray(e.questions)||!e.questions.length)throw Error(`OpenAI Decisions: at least one question is required`);let n=/* @__PURE__ */ new Set;for(let t of e.questions){let e=kT(t,`question`);if(AT(e.instructions,`question instructions`),e.name!==void 0){if(AT(e.name,`question name`),n.has(e.name))throw Error(`OpenAI Decisions: duplicate question name`);n.add(e.name)}if(e.type===`predicate`)continue;let r=e.type===`choice`?e.choices:e.type===`score`?e.levels:void 0;if(!Array.isArray(r))throw Error(`OpenAI Decisions: invalid question type or options`);let i=e.type===`score`?10:255;if(r.length<2||r.length>i)throw Error(`OpenAI Decisions: ${e.type} requires 2–${i} options`);let a=/* @__PURE__ */ new Set;for(let t of r){let n=kT(t,`question option`),r=e.type===`choice`?n.value:n.label;if((e.type===`score`||typeof r!=`boolean`)&&AT(r,`option value`),a.has(r))throw Error(`OpenAI Decisions: duplicate option value`);if(a.add(r),n.description!==void 0&&typeof n.description!=`string`)throw Error(`OpenAI Decisions: invalid option description`)}}}function FT(e,t){let n=kT(e,`response`);if(jT(n.model,`response model`),!Array.isArray(n.answers)||n.answers.length!==t.length)throw Error(`OpenAI Decisions: incomplete answers`);for(let[e,r]of t.entries()){let t=kT(n.answers[e],`answer ${e}`);if(t.name!==(r.name??null))throw Error(`OpenAI Decisions: incorrect answer name or order`);if(t.type===`refusal`)continue;if(t.type!==r.type)throw Error(`OpenAI Decisions: incorrect answer type`);if(r.type===`predicate`){MT(t.probability,`predicate`);continue}MT(t.confidence,`confidence`);let i=r.type===`choice`?r.choices.map(e=>e.value):r.levels.map((e,t)=>t);if(!Array.isArray(t.probabilities)||t.probabilities.length!==i.length)throw Error(`OpenAI Decisions: incomplete probabilities`);let a=/* @__PURE__ */ new Set,o=0;for(let e of t.probabilities){let t=kT(e,`probability`);if(!i.some(e=>e===t.value)||a.has(t.value))throw Error(`OpenAI Decisions: unknown or duplicate probability value`);if(a.add(t.value),o+=MT(t.probability,`distribution`),r.type===`score`&&t.label!==r.levels[t.value]?.label)throw Error(`OpenAI Decisions: incorrect score label`)}if(Math.abs(o-1)>.01+2**-52*i.length)throw Error(`OpenAI Decisions: invalid probability distribution`);if(r.type===`choice`&&!i.some(e=>e===t.choice))throw Error(`OpenAI Decisions: unknown choice`);if(r.type===`score`&&(typeof t.score!=`number`||!Number.isFinite(t.score)||t.score<0||t.score>i.length-1))throw Error(`OpenAI Decisions: invalid score`)}let r=kT(n.usage,`usage`);for(let e of[`input_tokens`,`output_tokens`,`total_tokens`])NT(r[e],e);let i=kT(r.input_tokens_details,`input token details`);return NT(i.cached_tokens,`cached tokens`),NT(i.cache_write_tokens,`cache write tokens`),NT(kT(r.output_tokens_details,`output token details`).reasoning_tokens,`reasoning tokens`),e}var IT=class{args;threshold;constructor(e){this.args=e,this.threshold=MT(e.trueThreshold??.5,`trueThreshold`)}getModelConfig(){return{stream:!1}}getTokenUsage(){}validateChatReq(e){this.payload(e)}plan(e){if(e.responseFormat?.type!==`json_schema`)throw Error(`OpenAI Decisions requires an output schema. Use ax() with required boolean, class or rubric score outputs`);let t=kT(kT(e.responseFormat.schema,`responseFormat.schema`).schema,`output schema`);if(t.type!==`object`||t.anyOf||t.oneOf||t.allOf||t.$ref)throw Error(`OpenAI Decisions requires a flat object output schema`);let n=kT(t.properties,`output properties`),r=t.required;if(!Object.keys(n).length)throw Error(`OpenAI Decisions requires at least one output field`);return Object.entries(n).map(([t,n])=>{let i=kT(n,`field ${t}`),a=e.responseFormat?.decisionFields?.[t];if(a?.type===`box`)throw Error(`OpenAI Decisions does not support box outputs; use Typesafe or a generative vision provider`);if(a?.isArray||a?.isOptional)throw Error(`Decision providers require flat, required scalar outputs`);let o=a?{...i,type:a.type===`class`?`string`:a.type,enum:a.type===`class`?a.options:void 0,anyOf:void 0}:i,s=()=>/* @__PURE__ */ Error(`OpenAI Decisions cannot evaluate output "${t}". Use required boolean, class or rubric score fields, or a generative provider for other outputs`);if(!Array.isArray(r)||!r.includes(t)||o.anyOf||o.oneOf||o.allOf||o.$ref||o.const!==void 0)throw s();let c=e.responseFormat?.fieldDescriptions?.[t];if(c){if(kT(c,`field description ${t}`),kT(c.valueDescriptions,`value descriptions for ${t}`),c.description!==void 0&&typeof c.description!=`string`)throw Error(`OpenAI Decisions: description for ${t} must be a string`);ct(o.type===`string`&&Array.isArray(o.enum)?`class`:String(o.type),c.valueDescriptions,o.enum,t)}let l=c?c.description:o.description,u=typeof l==`string`&&l?`${t}: ${l}`:`Evaluate the output field ${t}.`;if(a?.type===`score`)return{name:t,question:{type:`score`,instructions:u,levels:a.options.map(e=>({label:e}))}};if(o.type===`boolean`&&!o.enum)return{name:t,question:{type:`predicate`,instructions:c?[u,...Object.entries(c.valueDescriptions).map(([e,t])=>`${e}: ${t}`)].join(`
864
+ `)});return i},ST=[{category:`HARM_CATEGORY_HARASSMENT`,threshold:`BLOCK_NONE`},{category:`HARM_CATEGORY_HATE_SPEECH`,threshold:`BLOCK_NONE`},{category:`HARM_CATEGORY_SEXUALLY_EXPLICIT`,threshold:`BLOCK_NONE`},{category:`HARM_CATEGORY_DANGEROUS_CONTENT`,threshold:`BLOCK_NONE`}],CT=()=>structuredClone({model:`gemini-3.6-flash`,embedModel:`text-embedding-005`,safetySettings:ST,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},thinkingLevelMapping:{minimal:`minimal`,low:`low`,medium:`medium`,high:`high`,highest:`high`},...hy()}),wT=()=>structuredClone({model:`gemini-3.6-flash`,embedModel:`text-embedding-005`,safetySettings:ST,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},thinkingLevelMapping:{minimal:`minimal`,low:`low`,medium:`medium`,high:`high`,highest:`high`},...by()});var TT=class{config;vertexConfig;endpointId;apiKey;credentialProvider;options;vertexApiURLForModel;tokensUsed;models;serviceTierSupportFor;constructor(e,t,n,r,i,a,o){if(this.config=e,this.vertexConfig=t,this.endpointId=n,this.apiKey=r,this.credentialProvider=i,this.options=a,this.vertexApiURLForModel=o,!this.isVertex&&this.config.autoTruncate)throw Error(`Auto truncate is not supported for GoogleGemini`);hT({model:this.config.model,direct:this.config.thinking,thinkingLevelMapping:this.config.thinkingLevelMapping,thinkingTokenBudgetLevels:this.config.thinkingTokenBudgetLevels})}setModels(e){this.models=e}setServiceTierSupportFor(e){this.serviceTierSupportFor=e}resolveServiceTier(e,t,n=!1){let r=t.serviceTier??this.options?.serviceTier??this.config.serviceTier,i=JS(r),a=n||this.isVertex;if(a&&i&&i!==`auto`)throw Error(`Gemini inference service tiers are not supported by ${n?`the Live API`:`Vertex AI`}`);return XS({requested:r,supported:a?[]:this.serviceTierSupportFor?.(e)??[`standard`,`flex`,`priority`],mapping:{auto:null,standard:`standard`,flex:`flex`,priority:`priority`},provider:`Google Gemini`,model:e})}getEffectiveMappings(e){let t=this.models?.find(t=>t.model===e);return{thinkingLevelMapping:{...this.config.thinkingLevelMapping,...t?.thinkingLevelMapping??{}},thinkingTokenBudgetLevels:{...this.config.thinkingTokenBudgetLevels,...t?.thinkingTokenBudgetLevels??{}}}}getTokenUsage(){return this.tokensUsed}get isVertex(){return this.vertexConfig!==void 0}getVertexApiURL(e,t){return this.isVertex?this.vertexApiURLForModel?.(e,t):void 0}async transcribe(e,t){let n=e.model??`gemini-3.5-transcribe`,r=typeof this.apiKey==`function`?await this.apiKey():this.apiKey,i=this.isVertex?`${this.getVertexApiURL(n,t?.beta)}/models/${n}:generateContent`:`https://generativelanguage.googleapis.com/v1beta/models/${n}:generateContent`,a={contents:[{role:`user`,parts:[{inlineData:{mimeType:e.audio.mimeType??fb(e.audio.format,e.audio.sampleRate),data:e.audio.data}},{text:e.prompt??`Generate a transcript of the speech in this audio.`}]}]},o={"Content-Type":`application/json`,...this.isVertex&&r?{Authorization:`Bearer ${r}`}:!this.isVertex&&r?{"x-goog-api-key":r}:{}},s=await(t?.fetch??globalThis.fetch)(i,{method:`POST`,headers:this.credentialProvider?{...o,...await this.credentialProvider({profile:`google-gemini`,operation:`transcribe`,method:`POST`,url:i})}:o,body:JSON.stringify(a),signal:t?.abortSignal});if(!s.ok)throw Error(`Gemini transcription failed: ${s.status} ${s.statusText}`);return{text:(await s.json()).candidates?.[0]?.content?.parts?.map(e=>`audioTranscription`in e?e.audioTranscription.text:`text`in e&&!e.thought?e.text:``).join(``).trim()??``}}async speak(e,t){let n=e.model??`gemini-3.8-flash-tts`,r=typeof this.apiKey==`function`?await this.apiKey():this.apiKey,i=this.isVertex?`${this.getVertexApiURL(n,t?.beta)}/models/${n}:generateContent`:`https://generativelanguage.googleapis.com/v1beta/models/${n}:generateContent`,a=typeof e.voice==`object`?e.voice.id:e.voice??`Kore`;return await kb({url:i,headers:{...this.isVertex&&r?{Authorization:`Bearer ${r}`}:!this.isVertex&&r?{"x-goog-api-key":r}:{},...this.credentialProvider?await this.credentialProvider({profile:`google-gemini`,operation:`speak`,method:`POST`,url:i}):{}},body:{contents:[{role:`user`,parts:[{text:e.text}]}],generationConfig:{responseModalities:[`AUDIO`],speechConfig:{voiceConfig:{prebuiltVoiceConfig:{voiceName:a}}}}},transcript:e.text,fetch:t?.fetch,abortSignal:t?.abortSignal})}getVertexCacheContext(){if(!this.vertexConfig)return;let{projectId:e,region:t}=this.vertexConfig,n=`https://${Dy(t)}/v1`,r=`projects/${e}/locations/${t}`;return{baseUrl:n,parent:r,modelResource:e=>`${r}/publishers/google/models/${e}`}}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,stream:e.stream,n:e.n}}hasProviderDeclaredTools(){return!!(this.options?.codeExecution||this.options?.googleSearchRetrieval||this.options?.googleSearch||this.options?.googleMaps||this.options?.urlContext)}buildToolState(e,t){let n=[];if(e.functions&&e.functions.length>0){let t=e.functions.map(e=>{let t={type:`object`,properties:{dummy:{type:`string`,description:`An optional dummy parameter, do not use`}},required:[]},n=e.parameters?yT(e.parameters):void 0;return n===void 0||n&&typeof n==`object`&&Object.keys(n).length===0?n={...t}:n&&typeof n==`object`&&n.type===`object`&&(!(`properties`in n)||!n.properties||Object.keys(n.properties).length===0)&&(n={...n,properties:{dummy:{type:`string`,description:`An optional dummy parameter, do not use`}},required:[]}),{name:e.name,description:e.description,parametersJsonSchema:n}});n.push({function_declarations:t})}if(this.options?.codeExecution&&n.push({code_execution:{}}),this.options?.googleSearchRetrieval&&n.push({google_search_retrieval:{dynamic_retrieval_config:this.options.googleSearchRetrieval}}),this.options?.googleSearch&&n.push({google_search:{}}),this.options?.googleMaps){let e=this.options.googleMaps,t=e?.enableWidget===void 0?{}:{enableWidget:e.enableWidget};n.push({google_maps:t})}this.options?.urlContext&&n.push({url_context:{}}),n.length===0&&(n=void 0);let r,i=Array.isArray(n)?n.some(e=>e&&Array.isArray(e.function_declarations)&&e.function_declarations.length>0):!1;if(e.functionCall){if(e.functionCall===`none`)r={function_calling_config:{mode:`NONE`}};else if(e.functionCall===`auto`)r={function_calling_config:{mode:`AUTO`}};else if(e.functionCall===`required`)r={function_calling_config:{mode:`ANY`}};else{let t=e.functionCall.function?.name;r={function_calling_config:{mode:`ANY`,...t?{allowed_function_names:[t]}:{}}}}}else i&&(r={function_calling_config:{mode:`AUTO`}});this.options?.retrievalConfig&&(r={...r??{},retrievalConfig:{...this.options.retrievalConfig.latLng?{latLng:this.options.retrievalConfig.latLng}:{}}});let a=e.functions?.some(e=>e.cache)??!1,o=!!(n&&n.length>0)||!!r,s=!!t?.contextCache&&o;return{tools:n,toolConfig:r,cacheableTools:a||s}}createChatReq=async(e,t)=>{let n=e.model,r=e.modelConfig?.stream??this.config.stream,i=Cx(this.config.audio,e.modelConfig?.audio),a=wx(n,this.config.audio,e.modelConfig?.audio),o=this.resolveServiceTier(n,t,a);if(!e.chatPrompt||e.chatPrompt.length===0)throw Error(`Chat prompt is empty`);let s;if(a){if(this.isVertex)throw Error(`Gemini Live audio currently supports Google AI API-key WebSocket sessions only`);s={name:`gemini-live-audio`}}else s=this.endpointId?{name:r?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:{name:r?`/models/${n}:streamGenerateContent?alt=sse`:`/models/${n}:generateContent`};!a&&this.isVertex&&(s.url=this.getVertexApiURL(n,t?.beta));let c=e.chatPrompt.filter(e=>e.role===`system`).map(e=>e.content),l=c.length>0?{role:`user`,parts:[{text:c.join(` `)}]}:void 0,u=[],d=e.chatPrompt.filter(e=>e.role!==`system`);for(let e=0;e<d.length;e++){let t=d[e];switch(t.role){case`user`:{let e=Array.isArray(t.content)?t.content.map((e,t)=>{switch(e.type){case`text`:return{text:e.text};case`image`:return{inlineData:{mimeType:e.mimeType,data:e.image}};case`audio`:return{inlineData:{mimeType:e.mimeType??fb(e.format,e.sampleRate),data:e.data}};case`file`:return`fileUri`in e?{fileData:{mimeType:e.mimeType,fileUri:e.fileUri}}:{inlineData:{mimeType:e.mimeType,data:e.data}};default:throw Error(`Chat prompt content type not supported (index: ${t})`)}}):[{text:t.content}];u.push({role:`user`,parts:e});break}case`assistant`:{let e=[],n=t.thoughtBlocks,r=t.functionCalls&&t.functionCalls.length>0,i=n?.[0],a=n?.map(e=>e.data).join(``)??``,o=i?.signature;if(a&&e.push({...r?{}:{thought:!0},text:a,...o&&!r?{thought_signature:o}:{}}),t.functionCalls){let n=t.functionCalls.map((e,t)=>{let n;if(typeof e.function.params==`string`){let t=e.function.params;if(t.trim().length===0)n={};else try{n=JSON.parse(t)}catch{throw Error(`Failed to parse function params JSON: ${t}`)}}else n=e.function.params;let r={functionCall:{...e.id?{id:e.id}:{},name:e.function.name,args:n}};return o&&t===0&&(r.thought_signature=o),r});e.push(...n)}let s=t.audio?.transcript;if((t.content||s)&&e.push({text:t.content??s??``}),e.length===0)throw Error(`Assistant content is empty`);u.push({role:`model`,parts:e});break}case`function`:{let n=[],r=t,i=e;for(;;){if(!(`functionId`in r))throw Error(`Chat prompt functionId is empty (index: ${i})`);if(n.push(...xT(d,i,r)),i+1<d.length&&d[i+1].role===`function`)i++,r=d[i];else break}e=i,u.push({role:`user`,parts:n});break}default:throw Error(`Invalid role: ${JSON.stringify(t)} (index: ${e})`)}}let{tools:f,toolConfig:p}=this.buildToolState(e,t),m=this.getEffectiveMappings(n),h=hT({model:n,direct:this.config.thinking,logicalLevel:t?.thinkingTokenBudget,showThoughts:t?.showThoughts,...m}),g=e.modelConfig?.maxTokens??this.config.maxTokens;if(h.thinkingLevel&&g!==void 0)throw Error(`Cannot set maxTokens when using thinkingLevel with Gemini models. When thinking is enabled, the model manages output tokens automatically. Remove the maxTokens setting or disable thinking.`);let _={maxOutputTokens:e.modelConfig?.maxTokens??this.config.maxTokens,...uT({model:n,modelConfig:e.modelConfig,config:this.config,isVertex:this.isVertex,explicit:new Set(e.explicitSamplingKeys??[])}),stopSequences:e.modelConfig?.stopSequences??this.config.stopSequences,responseMimeType:`text/plain`,...Object.keys(h).length>0?{thinkingConfig:h}:{}};if(a&&(e.responseFormat||this.config.responseFormat))throw Error(`Gemini Live audio models do not support structured response formats with audio output`);if(e.responseFormat){if(e.responseFormat.type===`json_schema`&&e.responseFormat.schema){let t=e.responseFormat.schema.schema||e.responseFormat.schema;_.responseMimeType=`application/json`,_.responseJsonSchema=yT(t)}else _.responseMimeType=`application/json`}else this.config.responseFormat&&this.config.responseFormat===`json_object`&&(_.responseMimeType=`application/json`);let v={contents:u,tools:f,toolConfig:p,systemInstruction:l,generationConfig:_,safetySettings:this.config.safetySettings,...o?{service_tier:o}:{}};if(a){let e=typeof this.apiKey==`function`?await this.apiKey():this.apiKey;if(!e)throw Error(`GoogleGemini AI API key not set`);s=Dx({model:n,request:v,apiKey:e,audio:i})}return[s,v]};createEmbedReq=async(e,t)=>{let n=e.embedModel;if(!n)throw Error(`Embed model not set`);if(!e.texts||e.texts.length===0)throw Error(`Embed texts is empty`);let r,i;if(this.vertexConfig&&!this.endpointId&&_T.has(n)){if(e.texts.length!==1)throw Error(`${n} on Vertex embeds one text per request; call embed() once per text`);let a=Dy(`global`),o=gT(n,t?.beta);r={name:`/models/${n}:embedContent`,url:`https://${a}/${o}/projects/${this.vertexConfig.projectId}/locations/global/publishers/google`},i={content:{parts:[{text:e.texts[0]}]},autoTruncate:this.config.autoTruncate,outputDimensionality:this.config.dimensions}}else this.isVertex?(r=this.endpointId?{name:`/${this.endpointId}:predict`}:{name:`/models/${n}:predict`},r.url=this.getVertexApiURL(n,t?.beta),i={instances:e.texts.map(e=>({content:e,...this.config.embedType&&{task_type:this.config.embedType}})),parameters:{autoTruncate:this.config.autoTruncate,outputDimensionality:this.config.dimensions}}):(r={name:`/models/${n}:batchEmbedContents`},i={requests:e.texts.map(e=>({model:`models/${n}`,content:{parts:[{text:e}]},outputDimensionality:this.config.dimensions,...this.config.embedType&&{taskType:this.config.embedType}}))});return[r,i]};createChatResp=e=>{let t,n=e.candidates?.map(e=>{let n={index:0};switch(e.finishReason){case`MAX_TOKENS`:n.finishReason=`length`;break;case`STOP`:n.finishReason=`stop`;break;case`SAFETY`:throw new Go(`Content was blocked due to safety settings`,void 0,void 0);case`RECITATION`:throw new Go(`Content was blocked due to recitation policy`,void 0,void 0);case`MALFORMED_FUNCTION_CALL`:throw new Go(`Function call was malformed and blocked`,void 0,void 0);case`UNEXPECTED_TOOL_CALL`:throw new Go(`Unexpected tool call`,void 0,void 0);case`FINISH_REASON_UNSPECIFIED`:throw new Go(`Finish reason unspecified`,void 0,void 0);case`BLOCKLIST`:throw new Go(`Content was blocked due to blocklist`,void 0,void 0);case`PROHIBITED_CONTENT`:throw new Go(`Content was blocked due to prohibited content`,void 0,void 0);case`SPII`:throw new Go(`Content was blocked due to SPII`,void 0,void 0);case`OTHER`:throw new Go(`Other finish reason`,void 0,void 0)}if(!e.content||!e.content.parts)return n;for(let t of e.content.parts){if(`text`in t){if(`thought`in t&&t.thought||t.thought===!0){n.thought=t.text;let e=t.thoughtSignature||t.thought_signature;n.thoughtBlocks||=[],n.thoughtBlocks.push({data:t.text,encrypted:!1,...e?{signature:e}:{}})}else n.content=t.text;continue}if(`functionCall`in t){let e=t.thoughtSignature||t.thought_signature;if(e){if(!n.thoughtBlocks||n.thoughtBlocks.length===0)n.thoughtBlocks=[{data:``,encrypted:!1,signature:e}];else{let t=n.thoughtBlocks[n.thoughtBlocks.length-1];t&&!t.signature&&(t.signature=e)}}n.functionCalls=[...n.functionCalls??[],{id:t.functionCall.id??c(),type:`function`,function:{name:t.functionCall.name,params:t.functionCall.args}}]}let e=Ex(t);e&&(n.audio=e)}let r=e.citationMetadata?.citations;if(Array.isArray(r)&&r.length){let e=e=>e?`${e.year}-${String(e.month).padStart(2,`0`)}-${String(e.day).padStart(2,`0`)}`:void 0;n.citations=r.filter(e=>typeof e?.uri==`string`).map(t=>({url:t.uri,title:t.title,license:t.license,publicationDate:e(t.publicationDate)}))}let i=e.groundingMetadata;if(i){if(Array.isArray(i.groundingChunks)){let e=i.groundingChunks.map(e=>e?.maps).filter(e=>e&&typeof e.uri==`string`).map(e=>({url:e.uri,title:e.title}));e.length&&(n.citations=[...n.citations??[],...e]);let t=i.groundingChunks.map(e=>e?.retrievedContext).filter(e=>e&&(typeof e.uri==`string`||typeof e.media_id==`string`)).map(e=>({url:e.uri??``,title:e.title,...typeof e.media_id==`string`?{mediaId:e.media_id}:{},...Array.isArray(e.page_numbers)?{pageNumbers:e.page_numbers}:{}}));t.length&&(n.citations=[...n.citations??[],...t])}typeof i.googleMapsWidgetContextToken==`string`&&(t=i.googleMapsWidgetContextToken)}return n});if(e.usageMetadata){let t=e.usageMetadata.cachedContentTokenCount??0,n=e.usageMetadata.serviceTier===`unspecified`?`standard`:e.usageMetadata.serviceTier;this.tokensUsed={totalTokens:e.usageMetadata.totalTokenCount,promptTokens:e.usageMetadata.promptTokenCount-t,completionTokens:e.usageMetadata.candidatesTokenCount,thoughtsTokens:e.usageMetadata.thoughtsTokenCount,...t>0?{cacheReadTokens:t}:{},...n?{serviceTier:n}:{}}}let r={results:n,...e.responseId?{remoteId:e.responseId}:{},...e.modelVersion?{providerMetadata:{google:{modelVersion:e.modelVersion}}}:{}};return t&&(r.providerMetadata={...r.providerMetadata,google:{...r.providerMetadata?.google??{},mapsWidgetContextToken:t}}),r};createChatStreamResp=e=>this.createChatResp(e);createEmbedResp=e=>{if(this.tokensUsed=void 0,vT(e)){if(e.usageMetadata){let t=e.usageMetadata.promptTokenCount??0;this.tokensUsed={promptTokens:t,completionTokens:0,totalTokens:e.usageMetadata.totalTokenCount??t}}return{embeddings:[e.embedding.values]}}let t;return t=this.isVertex?e.predictions.map(e=>e.embeddings.values):e.embeddings.map(e=>e.values),{embeddings:t}};supportsContextCache=e=>{let t=e;return _x.some(e=>t.includes(e)||e.includes(t))};buildCacheCreateOp=(e,t)=>{let n=e.model,r=t.contextCache?.ttlSeconds??3600,{tools:i,toolConfig:a,cacheableTools:o}=this.buildToolState(e,t),{systemInstruction:s,contents:c}=this.extractCacheableContent(e.chatPrompt);if(!s&&(!c||c.length===0)&&!o)return;let l=this.getVertexCacheContext(),u={model:l?l.modelResource(n):`models/${n}`,ttl:`${r}s`,displayName:`ax-cache-${Date.now()}`};s&&(u.systemInstruction=s),c&&c.length>0&&(u.contents=c),o&&(i&&i.length>0&&(u.tools=i),a&&(u.toolConfig=a));let d;return d=l?`/${l.parent}/cachedContents`:`/cachedContents`,{type:`create`,apiConfig:{name:d,...l?{url:l.baseUrl}:{}},request:u,parseResponse:e=>{let t=e;if(t?.name)return{name:t.name,expiresAt:t.expireTime,tokenCount:t.usageMetadata?.totalTokenCount}}}};getContextCacheToolState=(e,t)=>{let{tools:n,toolConfig:r,cacheableTools:i}=this.buildToolState(e,t);if(!i)return;let a=e.functions?.map(({cache:e,...t})=>t);if(a&&a.length>0||e.functionCall)return{functions:a,functionCall:e.functionCall};if(n||r)return{functions:[{name:`__gemini_tool_state__`,description:JSON.stringify({tools:n,toolConfig:r})}]}};buildCacheUpdateTTLOp=(e,t)=>{let n={ttl:`${t}s`},r=`/${e}?${new URLSearchParams({updateMask:`ttl`}).toString()}`,i=this.getVertexCacheContext();return{type:`update`,apiConfig:{name:r,method:`PATCH`,headers:{"Content-Type":`application/json`},...i?{url:i.baseUrl}:{}},request:n,parseResponse:e=>{let t=e;if(t?.name)return{name:t.name,expiresAt:t.expireTime,tokenCount:t.usageMetadata?.totalTokenCount}}}};buildCacheDeleteOp=e=>{let t=`/${e}`,n=this.getVertexCacheContext();return{type:`delete`,apiConfig:{name:t,headers:{"Content-Type":`application/json`},...n?{url:n.baseUrl}:{}},request:{},parseResponse:()=>void 0}};prepareCachedChatReq=async(e,t,n)=>{let r=e.model,i=this.resolveServiceTier(r,t),a=e.modelConfig?.stream??this.config.stream,{tools:o,toolConfig:s,cacheableTools:c}=this.buildToolState(e,t),{dynamicContents:l,dynamicSystemInstruction:u}=this.extractDynamicContent(e.chatPrompt),d;d=this.endpointId?{name:a?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:{name:a?`/models/${r}:streamGenerateContent?alt=sse`:`/models/${r}:generateContent`};let f=this.getEffectiveMappings(r),p=hT({model:r,direct:this.config.thinking,logicalLevel:t.thinkingTokenBudget,showThoughts:t.showThoughts,...f}),m={contents:l,cachedContent:n,generationConfig:{maxOutputTokens:e.modelConfig?.maxTokens??this.config.maxTokens,...uT({model:r,modelConfig:e.modelConfig,config:this.config,isVertex:this.isVertex,explicit:new Set(e.explicitSamplingKeys??[])}),stopSequences:e.modelConfig?.stopSequences??this.config.stopSequences,responseMimeType:`text/plain`,...Object.keys(p).length>0?{thinkingConfig:p}:{}},safetySettings:this.config.safetySettings,...i?{service_tier:i}:{}};return c||(o&&o.length>0&&(m.tools=o),s&&(m.toolConfig=s)),u&&(m.systemInstruction=u),{apiConfig:d,request:m}};extractCacheableContent(e){let t=[],n=[],r=-1;for(let t=e.length-1;t>=0;t--){let n=e[t];if(`cache`in n&&n.cache){r=t;break}}for(let i=0;i<e.length;i++){let a=e[i];if(a.role===`system`){t.push(a.content);continue}if(r>=0&&i<=r){if(a.role===`user`){let e=[];if(typeof a.content==`string`)e.push({text:a.content});else if(Array.isArray(a.content))for(let t of a.content)switch(t.type){case`text`:e.push({text:t.text});break;case`image`:e.push({inlineData:{mimeType:t.mimeType,data:t.image}});break;case`audio`:e.push({inlineData:{mimeType:t.mimeType??fb(t.format,t.sampleRate),data:t.data}});break;case`file`:`fileUri`in t?e.push({fileData:{mimeType:t.mimeType,fileUri:t.fileUri}}):e.push({inlineData:{mimeType:t.mimeType,data:t.data}})}e.length>0&&n.push({role:`user`,parts:e})}else if(a.role===`assistant`){let e=[],t=a.thoughtBlocks,r=a.functionCalls&&a.functionCalls.length>0,i=t?.[0]?.signature,o=t?.map(e=>e.data).join(``)??``;if(o&&e.push({...r?{}:{thought:!0},text:o,...i&&!r?{thought_signature:i}:{}}),a.functionCalls)for(let[t,n]of a.functionCalls.entries()){let r;if(typeof n.function.params==`string`)try{r=JSON.parse(n.function.params)}catch{r={}}else r=n.function.params??{};let a={functionCall:{...n.id?{id:n.id}:{},name:n.function.name,args:r}};i&&t===0&&(a.thought_signature=i),e.push(a)}a.content&&e.push({text:a.content}),e.length>0&&n.push({role:`model`,parts:e})}else a.role===`function`&&n.push({role:`user`,parts:xT(e,i,a)})}}return{systemInstruction:t.length>0?{role:`user`,parts:[{text:t.join(` `)}]}:void 0,contents:n}}extractDynamicContent(e){let t=[],n=-1;for(let t=e.length-1;t>=0;t--){let r=e[t];if(`cache`in r&&r.cache){n=t;break}}for(let r=0;r<e.length;r++){let i=e[r];if(i.role!==`system`&&!(n>=0&&r<=n)){if(i.role===`user`){let e=[];if(typeof i.content==`string`)e.push({text:i.content});else if(Array.isArray(i.content)){for(let t of i.content)if(!(`cache`in t&&t.cache))switch(t.type){case`text`:e.push({text:t.text});break;case`image`:e.push({inlineData:{mimeType:t.mimeType,data:t.image}});break;case`audio`:e.push({inlineData:{mimeType:t.mimeType??fb(t.format,t.sampleRate),data:t.data}});break;case`file`:`fileUri`in t?e.push({fileData:{mimeType:t.mimeType,fileUri:t.fileUri}}):e.push({inlineData:{mimeType:t.mimeType,data:t.data}})}}e.length>0&&t.push({role:`user`,parts:e})}else if(i.role===`assistant`){let e=[],n=i.thoughtBlocks,r=i.functionCalls&&i.functionCalls.length>0,a=n?.[0]?.signature,o=n?.map(e=>e.data).join(``)??``;if(o&&e.push({...r?{}:{thought:!0},text:o,...a&&!r?{thought_signature:a}:{}}),i.functionCalls)for(let[t,n]of i.functionCalls.entries()){let r;if(typeof n.function.params==`string`)try{r=JSON.parse(n.function.params)}catch{r={}}else r=n.function.params??{};let i={functionCall:{...n.id?{id:n.id}:{},name:n.function.name,args:r}};a&&t===0&&(i.thought_signature=a),e.push(i)}i.content&&e.push({text:i.content}),e.length>0&&t.push({role:`model`,parts:e})}else i.role===`function`&&t.push({role:`user`,parts:xT(e,r,i)})}}return{dynamicContents:t,dynamicSystemInstruction:void 0}}},ET=class e extends Sy{static create(t){return new e(t)}constructor({apiKey:e,credentialProvider:t,projectId:n,region:r,endpointId:i,config:a,options:o,models:s,modelInfo:c}){let l=n!==void 0&&r!==void 0?{projectId:n,region:r}:void 0,u={...CT(),...a};if(l&&u.serviceTier&&u.serviceTier!==`auto`)throw Error(`Gemini inference service tiers are not supported by Vertex AI`);let d,f,p;if(l){let{projectId:n,region:r}=l;if(!e&&!t)throw Error(`GoogleGemini Vertex API key or credential provider not set`);if(e&&typeof e!=`function`)throw Error(`GoogleGemini Vertex API key must be a function for token-based authentication`);let a;a=i?`endpoints`:`publishers/google`;let o=Dy(r);p=(e,t)=>`https://${o}/${gT(e,t)}/projects/${n}/locations/${r}/${a}`,d=p(u.model),f=async()=>({...e?{Authorization:`Bearer ${typeof e==`function`?await e():e}`}:{}})}else{if(!e&&!t)throw Error(`GoogleGemini AI API key or credential provider not set`);d=`https://generativelanguage.googleapis.com/v1beta`,f=async()=>({...e?{"x-goog-api-key":typeof e==`function`?await e():e}:{}})}let m=new TT(u,l,i,e,t,o,p);c=[...vx,...c??[]];let h=e=>{let t=wx(e,{output:{enabled:!0}}),n=Rv({model:e,modelInfo:c,models:s}),r=n?.supported?.structuredOutputs??!0,i=n?.supported?.structuredOutputModes??(r?[`native`,`function`]:[`function`]);return{functions:!0,streaming:!0,hasThinkingBudget:n?.supported?.thinkingBudget??!1,hasShowThoughts:n?.supported?.showThoughts??!1,structuredOutputs:i.includes(`native`),structuredOutputModes:i,media:{images:{supported:!0,formats:[`image/jpeg`,`image/png`,`image/gif`,`image/webp`],maxSize:20971520,detailLevels:[`high`,`low`,`auto`]},audio:{supported:!0,formats:t?[`pcm16`,`pcm`]:[`wav`,`mp3`,`aac`,`ogg`],maxDuration:570,output:{supported:t,formats:[`pcm16`],sampleRate:24e3,voices:[`Kore`]}},files:{supported:!0,formats:[`application/pdf`,`text/plain`,`text/csv`,`text/html`,`text/xml`],maxSize:2147483648,uploadMethod:`cloud`},urls:{supported:!0,webSearch:!0,contextFetching:!0}},caching:{supported:m.supportsContextCache(e),types:[`persistent`]},thinking:n?.supported?.thinkingBudget??!1,multiTurn:!0,serviceTiers:n?.supported?.serviceTiers??(l||t?[]:[`standard`,`flex`,`priority`])}},g=s?.map(e=>{let t=e,n=t?.config;if(!n)return e;let r={};n.maxTokens!==void 0&&(r.maxTokens=n.maxTokens),n.temperature!==void 0&&(r.temperature=n.temperature),n.topP!==void 0&&(r.topP=n.topP),n.topK!==void 0&&(r.topK=n.topK),n.presencePenalty!==void 0&&(r.presencePenalty=n.presencePenalty),n.frequencyPenalty!==void 0&&(r.frequencyPenalty=n.frequencyPenalty),n.stopSequences!==void 0&&(r.stopSequences=n.stopSequences),n.endSequences!==void 0&&(r.endSequences=n.endSequences),n.stream!==void 0&&(r.stream=n.stream),n.n!==void 0&&(r.n=n.n);let i={...t};Object.keys(r).length>0&&(i.modelConfig={...t.modelConfig??{},...r});let a=n.thinking?.thinkingTokenBudget;if(typeof a==`number`){let e=String(t.model??u.model);if(oT(e))throw Error(`Gemini 3 models (${e}) do not support numeric thinkingTokenBudget. Use a logical thinkingTokenBudget level instead.`);let n=u.thinkingTokenBudgetLevels,r=[[`minimal`,n?.minimal??200],[`low`,n?.low??800],[`medium`,n?.medium??5e3],[`high`,n?.high??1e4],[`highest`,n?.highest??24500]],o=`minimal`,s=1/0;for(let[e,t]of r){let n=Math.abs(a-t);n<s&&(s=n,o=e)}i.thinkingTokenBudget=o}return n.thinking?.includeThoughts!==void 0&&(i.showThoughts=!!n.thinking.includeThoughts),n.serviceTier!==void 0&&(i.serviceTier=n.serviceTier),n.thinkingLevelMapping&&(i.thinkingLevelMapping=n.thinkingLevelMapping),n.thinkingTokenBudgetLevels&&(i.thinkingTokenBudgetLevels=n.thinkingTokenBudgetLevels),i});g?m.setModels(g):s&&m.setModels(s),m.setServiceTierSupportFor(e=>h(e).serviceTiers??[]),super(m,{name:`GoogleGeminiAI`,apiURL:d,headers:f,modelInfo:c,defaults:{model:u.model,embedModel:u.embedModel},options:o,credentialProvider:t,profile:`google-gemini`,supportFor:h,models:g??s}),this.setExplicitModelConfigKeys(a)}},DT=class{config;metrics={latency:{chat:{mean:0,p95:0,p99:0,samples:[]},embed:{mean:0,p95:0,p99:0,samples:[]}},errors:{chat:{count:0,rate:0,total:0},embed:{count:0,rate:0,total:0}}};constructor(e={}){this.config=e,this.config.id=this.config.id??c()}getLastUsedChatModel(){return this.config.modelInfo?.name??`mock-model`}getLastUsedEmbedModel(){return this.config.embedModelInfo?.name??`mock-embed-model`}getLastUsedModelConfig(){return this.config.modelInfo?{maxTokens:this.config.modelInfo.maxTokens,temperature:.7,stream:this.config.features?.streaming??!1}:void 0}getName(){return this.config.name??`mock-ai-service`}getId(){return this.config.id??`mock-ai-service-id`}getFeatures(e){let t=this.config.features?.media;return{functions:this.config.features?.functions??!1,streaming:this.config.features?.streaming??!1,structuredOutputs:this.config.features?.structuredOutputs,...this.config.features?.structuredOutputModes?{structuredOutputModes:this.config.features.structuredOutputModes}:{},...this.config.features?.serviceTiers?{serviceTiers:this.config.features.serviceTiers}:{},media:{images:{supported:t?.images?.supported??!1,formats:t?.images?.formats??[]},audio:{supported:t?.audio?.supported??!1,formats:t?.audio?.formats??[]},files:{supported:t?.files?.supported??!1,formats:t?.files?.formats??[],uploadMethod:t?.files?.uploadMethod??`none`},urls:{supported:t?.urls?.supported??!1,webSearch:t?.urls?.webSearch??!1,contextFetching:t?.urls?.contextFetching??!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}getModelList(){return this.config.models}getMetrics(){return this.metrics}getEstimatedCost(){return 0}async chat(e,t){if(this.config.latencyMs&&await new Promise(e=>setTimeout(e,this.config.latencyMs)),this.config.shouldError)throw Error(this.config.errorMessage??`Mock chat error`);return this.updateMetrics(`chat`),typeof this.config.chatResponse==`function`?await this.config.chatResponse(e,t):this.config.chatResponse??{results:[{index:0,content:`Mock response`,finishReason:`stop`}],modelUsage:{ai:this.getName(),model:`mock-model`,tokens:{promptTokens:10,completionTokens:5,totalTokens:15}}}}async embed(e,t){if(this.config.latencyMs&&await new Promise(e=>setTimeout(e,this.config.latencyMs)),this.config.shouldError)throw Error(this.config.errorMessage??`Mock embed error`);return this.updateMetrics(`embed`),typeof this.config.embedResponse==`function`?this.config.embedResponse(e):this.config.embedResponse??{embeddings:[[.1,.2,.3]],modelUsage:{ai:this.getName(),model:`mock-model`,tokens:{promptTokens:5,completionTokens:0,totalTokens:5}}}}async transcribe(e,t){if(this.config.shouldError)throw Error(this.config.errorMessage??`Mock transcribe error`);return typeof this.config.transcribeResponse==`function`?this.config.transcribeResponse(e):this.config.transcribeResponse??{text:`Mock transcription`}}async speak(e,t){if(this.config.shouldError)throw Error(this.config.errorMessage??`Mock speech error`);return typeof this.config.speechResponse==`function`?this.config.speechResponse(e):this.config.speechResponse??{data:`bW9jay1hdWRpbw==`,format:`mp3`,mimeType:`audio/mpeg`,transcript:e.text}}setOptions(e){this.config.options=e}getOptions(){return this.config.options??{}}getLogger(){return this.config.options?.logger??(e=>{console.log(e)})}updateMetrics(e){let t=this.config.latencyMs??0;this.metrics.latency[e].samples.push(t);let n=this.metrics.latency[e].samples;if(this.metrics.latency[e].mean=n.reduce((e,t)=>e+t,0)/n.length,n.length>0){let r=[...n].sort((e,t)=>e-t),i=Math.max(0,Math.floor(r.length*.95)-1);this.metrics.latency[e].p95=r[i]??t;let a=Math.max(0,Math.floor(r.length*.99)-1);this.metrics.latency[e].p99=r[a]??t}if(this.config.shouldError){this.metrics.errors[e].count++,this.metrics.errors[e].total++;let t=this.metrics.latency[e].samples.length;this.metrics.errors[e].rate=t>0?this.metrics.errors[e].count/t:0}}},OT=class e{options;lastUsedService;services=/* @__PURE__ */ new Map;constructor(e){if(e.length===0)throw Error(`No AI services provided.`);for(let[t,n]of e.entries())if(`key`in n){if(this.services.has(n.key))throw Error(`Duplicate model key: ${n.key}`);let{service:e,description:t,isInternal:r}=n;this.services.set(n.key,{service:e,description:t,isInternal:r})}else{let e=n.getModelList();if(!e)throw Error(`Service ${t} \`${n.getName()}\` has no model list.`);for(let r of e){if(this.services.has(r.key)){let e=this.services.get(r.key)?.service;throw Error(`Service ${t} \`${n.getName()}\` has duplicate model key: ${r.key} as service ${e?.getName()}`)}if(`model`in r&&typeof r.model)this.services.set(r.key,{description:r.description,service:n,model:r.model});else if(`embedModel`in r&&r.embedModel)this.services.set(r.key,{description:r.description,service:n,embedModel:r.embedModel});else throw Error(`Key ${r.key} in model list for service ${t} \`${n.getName()}\` is missing a model or embedModel property.`)}}}static create(t){return new e(t)}getLastUsedChatModel(){return this.lastUsedService?.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.lastUsedService?.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.lastUsedService?.getLastUsedModelConfig()}async resolveChatService(e){let t=e.model?this.services.get(e.model):void 0;if(!t)throw Error(`No service found for model key: ${String(e.model)}`);return this.lastUsedService=t.service,{service:t.service,model:t.model?e.model:void 0}}async openChatSession(e,t){let n=e.model?this.services.get(e.model):void 0;if(!n)throw Error(`No service found for model key: ${String(e.model)}`);if(!n.service.openChatSession)throw Error(`Selected service does not support chat sessions`);this.lastUsedService=n.service;let{model:r,...i}=e;return await n.service.openChatSession(n.model?e:i,t)}async chat(e,t){let n=e.model;if(!n)throw Error(`Model key must be specified for multi-service`);let r=this.services.get(n);if(!r)throw Error(`No service found for model key: ${n}`);if(this.lastUsedService=r.service,!r.model){let{model:n,...i}=e;return await r.service.chat(i,t)}return await r.service.chat({model:n,...e},t)}async embed(e,t){let n=e.embedModel;if(!n)throw Error(`Embed model key must be specified for multi-service`);let r=this.services.get(n);if(!r)throw Error(`No service found for embed model key: ${n}`);if(this.lastUsedService=r.service,!r.model&&!r.embedModel){let{embedModel:n,...i}=e;return await r.service.embed(i,t)}return await r.service.embed({embedModel:n,...e},t)}async transcribe(e,t){let n=e.model;if(!n){let n=Array.from(this.services.values())[0]?.service;if(!n)throw Error(`No AI services provided.`);return this.lastUsedService=n,await n.transcribe(e,t)}let r=this.services.get(n);if(!r)throw Error(`No service found for transcription model key: ${n}`);return this.lastUsedService=r.service,await r.service.transcribe(e,t)}async speak(e,t){let n=e.model;if(!n){let n=Array.from(this.services.values())[0]?.service;if(!n)throw Error(`No AI services provided.`);return this.lastUsedService=n,await n.speak(e,t)}let r=this.services.get(n);if(!r)throw Error(`No service found for speech model key: ${n}`);return this.lastUsedService=r.service,await r.service.speak(e,t)}getId(){return`MultiServiceRouter:${Array.from(this.services.values()).map(e=>e.service.getId()).join(`,`)}`}getName(){return`MultiServiceRouter`}getModelList(){return Array.from(this.services).filter(([,e])=>!e.isInternal).map(([e,t])=>{if(t.model)return{key:e,description:t.description,model:t.model};if(t.embedModel)return{key:e,description:t.description,embedModel:t.embedModel};throw Error(`Service ${e} has no model or embedModel`)})}getFeatures(e){if(e){let t=this.services.get(e);if(t)return t.service.getFeatures(t.model?e:void 0)}return{functions:!1,streaming:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:`none`},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}getMetrics(){let e=this.lastUsedService;if(!e){let t=this.services.values().next().value;t&&(e=`service`in t?t.service:t)}if(!e)throw Error(`No service available to get metrics.`);return e.getMetrics()}getEstimatedCost(e){return this.lastUsedService?.getEstimatedCost(e)??0}setOptions(e){for(let t of this.services.values())t.service.setOptions(e);this.options=e}getOptions(){return this.options??{}}getLogger(){let e=this.lastUsedService;if(!e){let t=this.services.values().next().value;t&&(e=t.service)}if(!e)throw Error(`No service available to get logger.`);return e.getLogger()}setServiceEntry(e,t){this.services.set(e,t)}};function kT(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`OpenAI Decisions: invalid ${t}`);return e}function AT(e,t){if(typeof e!=`string`)throw Error(`OpenAI Decisions: invalid ${t}`)}function jT(e,t){if(typeof e!=`string`||!e.trim())throw Error(`OpenAI Decisions: invalid ${t}`)}function MT(e,t){if(typeof e!=`number`||!Number.isFinite(e)||e<0||e>1)throw Error(`OpenAI Decisions: invalid probability for ${t}`);return e}function NT(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(`OpenAI Decisions: invalid ${t}`)}function PT(e){jT(e.model,`model`),e.safety_identifier!=null&&AT(e.safety_identifier,`safety_identifier`);let t=0;if(typeof e.input!=`string`){if(!Array.isArray(e.input)||!e.input.length)throw Error(`OpenAI Decisions: input must be text or user messages`);for(let n of e.input){let e=kT(n,`input message`);if(e.role!==`user`||e.type!==void 0&&e.type!==`message`)throw Error(`OpenAI Decisions: only user messages are supported`);if(typeof e.content!=`string`){if(!Array.isArray(e.content)||!e.content.length)throw Error(`OpenAI Decisions: invalid input content`);for(let n of e.content){let e=kT(n,`input part`);if(e.type!==`input_text`||typeof e.text!=`string`){if(e.type!==`input_image`||typeof e.image_url!=`string`||!/^data:image\/[a-zA-Z0-9.+-]+;base64,[A-Za-z0-9+/]+={0,2}$/.test(e.image_url))throw Error(`OpenAI Decisions: images require inline base64 data URLs; files, audio, and hosted URLs are unsupported`);if(e.detail!=null&&![`low`,`high`,`auto`,`original`].includes(String(e.detail)))throw Error(`OpenAI Decisions: invalid image detail`);t++}}}}}if(t>128)throw Error(`OpenAI Decisions: at most 128 images are supported`);if(!Array.isArray(e.questions)||!e.questions.length)throw Error(`OpenAI Decisions: at least one question is required`);let n=/* @__PURE__ */ new Set;for(let t of e.questions){let e=kT(t,`question`);if(AT(e.instructions,`question instructions`),e.name!==void 0){if(AT(e.name,`question name`),n.has(e.name))throw Error(`OpenAI Decisions: duplicate question name`);n.add(e.name)}if(e.type===`predicate`)continue;let r=e.type===`choice`?e.choices:e.type===`score`?e.levels:void 0;if(!Array.isArray(r))throw Error(`OpenAI Decisions: invalid question type or options`);let i=e.type===`score`?10:255;if(r.length<2||r.length>i)throw Error(`OpenAI Decisions: ${e.type} requires 2–${i} options`);let a=/* @__PURE__ */ new Set;for(let t of r){let n=kT(t,`question option`),r=e.type===`choice`?n.value:n.label;if((e.type===`score`||typeof r!=`boolean`)&&AT(r,`option value`),a.has(r))throw Error(`OpenAI Decisions: duplicate option value`);if(a.add(r),n.description!==void 0&&typeof n.description!=`string`)throw Error(`OpenAI Decisions: invalid option description`)}}}function FT(e,t){let n=kT(e,`response`);if(jT(n.model,`response model`),!Array.isArray(n.answers)||n.answers.length!==t.length)throw Error(`OpenAI Decisions: incomplete answers`);for(let[e,r]of t.entries()){let t=kT(n.answers[e],`answer ${e}`);if(t.name!==(r.name??null))throw Error(`OpenAI Decisions: incorrect answer name or order`);if(t.type===`refusal`)continue;if(t.type!==r.type)throw Error(`OpenAI Decisions: incorrect answer type`);if(r.type===`predicate`){MT(t.probability,`predicate`);continue}MT(t.confidence,`confidence`);let i=r.type===`choice`?r.choices.map(e=>e.value):r.levels.map((e,t)=>t);if(!Array.isArray(t.probabilities)||t.probabilities.length!==i.length)throw Error(`OpenAI Decisions: incomplete probabilities`);let a=/* @__PURE__ */ new Set,o=0;for(let e of t.probabilities){let t=kT(e,`probability`);if(!i.some(e=>e===t.value)||a.has(t.value))throw Error(`OpenAI Decisions: unknown or duplicate probability value`);if(a.add(t.value),o+=MT(t.probability,`distribution`),r.type===`score`&&t.label!==r.levels[t.value]?.label)throw Error(`OpenAI Decisions: incorrect score label`)}if(Math.abs(o-1)>.01+2**-52*i.length)throw Error(`OpenAI Decisions: invalid probability distribution`);if(r.type===`choice`&&!i.some(e=>e===t.choice))throw Error(`OpenAI Decisions: unknown choice`);if(r.type===`score`&&(typeof t.score!=`number`||!Number.isFinite(t.score)||t.score<0||t.score>i.length-1))throw Error(`OpenAI Decisions: invalid score`)}let r=kT(n.usage,`usage`);for(let e of[`input_tokens`,`output_tokens`,`total_tokens`])NT(r[e],e);let i=kT(r.input_tokens_details,`input token details`);return NT(i.cached_tokens,`cached tokens`),NT(i.cache_write_tokens,`cache write tokens`),NT(kT(r.output_tokens_details,`output token details`).reasoning_tokens,`reasoning tokens`),e}var IT=class{args;threshold;constructor(e){this.args=e,this.threshold=MT(e.trueThreshold??.5,`trueThreshold`)}getModelConfig(){return{stream:!1}}getTokenUsage(){}validateChatReq(e){this.payload(e)}plan(e){if(e.responseFormat?.type!==`json_schema`)throw Error(`OpenAI Decisions requires an output schema. Use ax() with required boolean, class or rubric score outputs`);let t=kT(kT(e.responseFormat.schema,`responseFormat.schema`).schema,`output schema`);if(t.type!==`object`||t.anyOf||t.oneOf||t.allOf||t.$ref)throw Error(`OpenAI Decisions requires a flat object output schema`);let n=kT(t.properties,`output properties`),r=t.required;if(!Object.keys(n).length)throw Error(`OpenAI Decisions requires at least one output field`);return Object.entries(n).map(([t,n])=>{let i=kT(n,`field ${t}`),a=e.responseFormat?.decisionFields?.[t];if(a?.type===`box`)throw Error(`OpenAI Decisions does not support box outputs; use Typesafe or a generative vision provider`);if(a?.isArray||a?.isOptional)throw Error(`Decision providers require flat, required scalar outputs`);let o=a?{...i,type:a.type===`class`?`string`:a.type,enum:a.type===`class`?a.options:void 0,anyOf:void 0}:i,s=()=>/* @__PURE__ */ Error(`OpenAI Decisions cannot evaluate output "${t}". Use required boolean, class or rubric score fields, or a generative provider for other outputs`);if(!Array.isArray(r)||!r.includes(t)||o.anyOf||o.oneOf||o.allOf||o.$ref||o.const!==void 0)throw s();let c=e.responseFormat?.fieldDescriptions?.[t];if(c){if(kT(c,`field description ${t}`),kT(c.valueDescriptions,`value descriptions for ${t}`),c.description!==void 0&&typeof c.description!=`string`)throw Error(`OpenAI Decisions: description for ${t} must be a string`);ct(o.type===`string`&&Array.isArray(o.enum)?`class`:String(o.type),c.valueDescriptions,o.enum,t)}let l=c?c.description:o.description,u=typeof l==`string`&&l?`${t}: ${l}`:`Evaluate the output field ${t}.`;if(a?.type===`score`)return{name:t,question:{type:`score`,instructions:u,levels:a.options.map(e=>({label:e}))}};if(o.type===`boolean`&&!o.enum)return{name:t,question:{type:`predicate`,instructions:c?[u,...Object.entries(c.valueDescriptions).map(([e,t])=>`${e}: ${t}`)].join(`
865
865
  `):u}};if(o.type===`string`&&Array.isArray(o.enum)&&o.enum.length>0&&o.enum.every(e=>typeof e==`string`)&&new Set(o.enum).size===o.enum.length)return{name:t,question:{type:`choice`,instructions:u,choices:o.enum.map(e=>({value:e,...c&&Object.hasOwn(c.valueDescriptions,e)?{description:c.valueDescriptions[e]}:{}}))}};throw s()})}payload(e){if(e.functions?.length||e.functionCall&&e.functionCall!==`none`)throw Error(`OpenAI Decisions does not support tools`);for(let[t,n]of Object.entries(e.modelConfig??{}))if(n!==void 0&&t!==`stream`&&(t!==`n`||n!==1))throw Error(`OpenAI Decisions does not support generation control "${t}"`);let t=[];for(let n of e.chatPrompt){if(n.role===`function`||n.role===`assistant`&&(n.functionCalls?.length||n.audio||n.images?.length))throw Error(`OpenAI Decisions does not support tool or media history`);if(t.push({type:`input_text`,text:`${n.role}:`}),typeof n.content==`string`)t.push({type:`input_text`,text:n.content});else if(n.role===`user`)for(let e of n.content)if(e.type===`text`)t.push({type:`input_text`,text:e.text});else if(e.type===`image`)t.push({type:`input_image`,image_url:e.image.startsWith(`data:`)?e.image:`data:${e.mimeType};base64,${e.image}`,...e.details?{detail:e.details}:{}});else throw Error(`OpenAI Decisions supports text and inline images only`)}let n={model:e.model,input:[{role:`user`,content:t}],questions:this.plan(e).map(({name:e,question:t})=>({...t,name:e})),...this.args.safetyIdentifier?{safety_identifier:this.args.safetyIdentifier}:{}};return PT(n),n}createChatReq(e){return[{name:`/decisions`},this.payload(e)]}createChatResp(e,t){if(!t)throw Error(`OpenAI Decisions response decoding requires its request`);let n=FT(e,this.plan(t).map(({name:e,question:t})=>({...t,name:e}))),r={},i=n.answers.map(e=>{let n=e.name;if(t.responseFormat?.decisionFields?.[n])return e.type===`refusal`?(r[n]={refused:!0},[n,{status:`refused`}]):e.type===`predicate`?(r[n]={},[n,{probability:e.probability}]):e.type===`score`?(r[n]={value:e.score,confidence:e.confidence},[n,{probabilities:[...e.probabilities].sort((e,t)=>Number(e.value)-Number(t.value)).map(e=>e.probability)}]):(r[n]={value:e.choice,confidence:e.confidence},[n,{probabilities:Object.fromEntries(e.probabilities.map(e=>[e.value,e.probability]))}]);if(e.type===`refusal`)throw Error(`OpenAI Decisions refused question "${n}"`);return[n,e.type===`predicate`?e.probability>=this.threshold:e.type===`choice`?e.choice:e.score]});return{results:[{index:0,...Object.keys(r).length?{decisionContext:{provenance:{source:`native`,provider:`OpenAI Decisions`,model:n.model},native:r}}:{},content:JSON.stringify(Object.fromEntries(i)),finishReason:`stop`}],modelUsage:{ai:`OpenAI Decisions`,model:n.model,tokens:bC(n.usage)},providerMetadata:{openaiDecisions:{answers:n.answers}}}}},LT=class extends Sy{constructor(e){if(!e.apiKey?.trim()&&!e.credentialProvider)throw Error(`OpenAI Decisions requires apiKey or credentialProvider`);let t=uw(`openai-decisions`),n=e.config?.model??t.defaultModel;super(new IT(e),{name:`OpenAI Decisions`,profile:`openai-decisions`,apiURL:e.apiURL??t.baseURL,headers:async()=>e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{},credentialProvider:e.credentialProvider,modelInfo:e.modelInfo??FS,defaults:{model:n},options:e.options,models:e.models,supportFor:()=>gw(`openai-decisions`,n)})}};jo();var RT=class{args;constructor(e){if(!e.apiKey?.trim()&&!e.credentialProvider)throw Error(`OpenAI Decisions requires apiKey or credentialProvider`);this.args={...e,headers:{...e.headers},options:{...e.options}}}async create(e,t){let n={...e,model:e.model??this.args.model??`gpt-6-luna`};PT(n);let r=structuredClone(n);return FT(await this.request(`/decisions`,`POST`,r,t),r.questions)}async request(e,t,n,r){let i=Object.fromEntries(Object.entries(r??{}).filter(([,e])=>e!==void 0));return await ns({...this.args.options,...i,abortSignal:Y(this.args.options?.abortSignal,r?.abortSignal),name:e,url:this.args.apiURL??`https://api.openai.com/v1`,method:t,resolveHeaders:async({method:e,url:t})=>Gv(this.args.apiKey?{Authorization:`Bearer ${this.args.apiKey}`}:void 0,this.args.headers,await this.args.credentialProvider?.({profile:`openai-decisions`,operation:`chat`,method:e,url:t}))},n)}};function zT(e){return new RT(e)}async function BT(e,t,n={}){if(typeof e==`string`)return[{type:`text`,text:e}];if(!Array.isArray(e))return[{type:`text`,text:String(e)}];let r=t.getFeatures(),i=[];for(let a of e)try{switch(a.type){case`text`:i.push({type:`text`,text:a.text});break;case`image`:if(r.media.images.supported)i.push(a);else if(a.altText)i.push({type:`text`,text:a.altText});else if(n.imageToText)try{let e=await n.imageToText(a.image);i.push({type:`text`,text:e})}catch(e){throw new qo(e,`image`,`vision analysis`)}else switch(n.fallbackBehavior){case`error`:throw new Ko(`Images`,t.getName(),!1);case`skip`:continue;default:i.push({type:`text`,text:`[Image content not supported by this provider]`})}break;case`audio`:if(r.media.audio.supported)a.transcription?i.push({type:`text`,text:a.transcription}):i.push({type:`text`,text:`[Audio content]`});else if(a.transcription)i.push({type:`text`,text:a.transcription});else if(n.audioToText)try{let e=await n.audioToText(a.data,a.format);i.push({type:`text`,text:e})}catch(e){throw new qo(e,`audio`,`transcription`)}else switch(n.fallbackBehavior){case`error`:throw new Ko(`Audio`,t.getName(),!1);case`skip`:continue;case`degrade`:i.push({type:`text`,text:`[Audio content not supported by this provider]`})}break;case`file`:if(r.media.files.supported)i.push(a);else if(a.extractedText)i.push({type:`text`,text:a.extractedText});else if(n.fileToText)try{let e=await n.fileToText(a.data,a.mimeType);i.push({type:`text`,text:e})}catch(e){throw new qo(e,`file`,`text extraction`)}else switch(n.fallbackBehavior){case`error`:throw new Ko(`Files`,t.getName(),!1);case`skip`:continue;default:i.push({type:`text`,text:`[File: ${a.filename} - content not accessible by this provider]`})}break;case`url`:if(r.media.urls.supported)a.cachedContent?i.push({type:`text`,text:a.cachedContent}):i.push({type:`text`,text:`[Link: ${a.url}${a.title?` - ${a.title}`:``}]`});else if(a.cachedContent)i.push({type:`text`,text:a.cachedContent});else if(n.urlToText)try{let e=await n.urlToText(a.url);i.push({type:`text`,text:e})}catch(e){throw new qo(e,`url`,`content fetching`)}else switch(n.fallbackBehavior){case`error`:throw new Ko(`URLs`,t.getName(),!1);case`skip`:continue;case`degrade`:i.push({type:`text`,text:`[Link: ${a.url}${a.title?` - ${a.title}`:``}]`})}break;default:typeof a==`object`&&a.text?i.push({type:`text`,text:a.text}):i.push({type:`text`,text:String(a)})}}catch(e){throw e instanceof Ko||e instanceof qo?e:new qo(e,a.type||`unknown`,`content processing`)}return i}function VT(e){let t=!1,n=!1,r=!1,i=!1;for(let a of e)if(a.role===`user`&&Array.isArray(a.content))for(let e of a.content)switch(e.type){case`image`:t=!0;break;case`audio`:n=!0;break;case`file`:r=!0;break;case`url`:i=!0}return{hasImages:t,hasAudio:n,hasFiles:r,hasUrls:i}}var HT=class{providers;processingServices;config;constructor(e){this.providers=[e.providers.primary,...e.providers.alternatives],this.processingServices=e.processing,this.config=e.routing}async openChatSession(e,t={}){let n=await this.selectProviderWithDegradation(e,{},t.serviceTier,t);if(!n.provider.openChatSession)throw Error(`Selected provider does not support chat sessions`);let r=await this.preprocessRequest(e,n.provider);return await n.provider.openChatSession(r,t)}async chat(e,t={}){let n=await this.selectProviderWithDegradation(e,t.routingOptions||{},t.serviceTier,t),r=await this.preprocessRequest(e,n.provider,t.processingOptions);try{return n.provider.validateChatRequest?.(r,t),{response:await n.provider.chat(r,t),routing:n}}catch(n){if(n instanceof Ko&&t.fallbackProviders?.length)return await this.tryFallbackProviders(e,t.fallbackProviders,t);throw n}}async preprocessRequest(e,t,n){let r={...n,fallbackBehavior:n?.fallbackBehavior||`degrade`,imageToText:n?.imageToText||this.processingServices.imageToText,audioToText:n?.audioToText||this.processingServices.audioToText,fileToText:n?.fileToText||this.processingServices.fileToText,urlToText:n?.urlToText||this.processingServices.urlToText},i=[];for(let n of e.chatPrompt)if(n.role===`user`&&Array.isArray(n.content)){let e=await BT(n.content,t,r);e.every(e=>e.type===`text`)&&e.length===1?i.push({...n,content:e[0].text}):i.push({...n,content:e.map(e=>e.type===`text`?{type:`text`,text:e.text}:e)})}else i.push(n);return{...e,chatPrompt:i}}async selectProviderWithDegradation(e,t,n,r){let i=Kb(e),a=[],o=[],s=[];try{let c=n&&n!==`auto`?this.providers.filter(t=>t.getFeatures(e.model).serviceTiers?.includes(n)):this.providers;if(c.length===0)throw Error(`No provider supports service tier ${n}`);let l=Yb(e,c,{requireExactMatch:t.requireExactMatch??this.config.capability.requireExactMatch,allowDegradation:t.allowDegradation??this.config.capability.allowDegradation},r),u=l.getFeatures();return i.hasImages&&!u.media.images.supported&&(o.push(`Images will be converted to text descriptions`),a.push(`Image-to-text conversion`)),i.hasAudio&&!u.media.audio.supported&&(o.push(`Audio will be transcribed to text`),a.push(`Audio-to-text transcription`)),i.hasFiles&&!u.media.files.supported&&(o.push(`File content will be extracted to text`),a.push(`File-to-text extraction`)),i.hasUrls&&!u.media.urls.supported&&(o.push(`URL content will be pre-fetched`),a.push(`URL content fetching`)),i.requiresStreaming&&!u.streaming&&s.push(`Streaming not supported - will use non-streaming mode`),i.requiresCaching&&!u.caching.supported&&s.push(`Content caching not supported`),{provider:l,processingApplied:a,degradations:o,warnings:s}}catch(e){throw Error(`Provider selection failed: ${e instanceof Error?e.message:`Unknown error`}`)}}async tryFallbackProviders(e,t,n){for(let r of t)if(!n.serviceTier||n.serviceTier===`auto`||r.getFeatures(e.model).serviceTiers?.includes(n.serviceTier))try{r.validateChatRequest?.(e,n);let t={provider:r,processingApplied:[`Fallback provider selection`],degradations:[`Using fallback provider due to primary provider failure`],warnings:[]},i=await this.preprocessRequest(e,r,{fallbackBehavior:`degrade`});return r.validateChatRequest?.(i,n),{response:await r.chat(i,n),routing:t}}catch{}throw Error(`All fallback providers failed`)}async getRoutingRecommendation(e){return await this.selectProviderWithDegradation(e,{})}async validateRequest(e){let t=Kb(e),n=[],r=[];try{let i=await this.selectProviderWithDegradation(e,{});return i.degradations.length>0&&(n.push(...i.degradations),r.push(`Consider using a provider that natively supports all media types`)),i.warnings.length>0&&n.push(...i.warnings),t.hasImages&&this.processingServices.imageToText===void 0&&(this.providers.some(e=>e.getFeatures().media.images.supported)||(n.push(`No image processing service available and no providers support images`),r.push(`Add imageToText processing service or use image-capable provider`))),t.hasAudio&&this.processingServices.audioToText===void 0&&(this.providers.some(e=>e.getFeatures().media.audio.supported)||(n.push(`No audio processing service available and no providers support audio`),r.push(`Add audioToText processing service or use audio-capable provider`))),{canHandle:n.length===0||i.degradations.length>0,issues:n,recommendations:r}}catch(e){return{canHandle:!1,issues:[`Cannot route request: ${e instanceof Error?e.message:`Unknown error`}`],recommendations:[`Add more providers or processing services to handle this request`]}}}getRoutingStats(){let e={};for(let t of this.providers){let n=t.getFeatures(),r=t.getName();n.functions&&(e.Functions=e.Functions||[],e.Functions.push(r)),n.streaming&&(e.Streaming=e.Streaming||[],e.Streaming.push(r)),n.media.images.supported&&(e.Images=e.Images||[],e.Images.push(r)),n.media.audio.supported&&(e.Audio=e.Audio||[],e.Audio.push(r)),n.media.files.supported&&(e.Files=e.Files||[],e.Files.push(r)),n.media.urls.supported&&(e.URLs=e.URLs||[],e.URLs.push(r)),n.caching.supported&&(e.Caching=e.Caching||[],e.Caching.push(r))}return{totalProviders:this.providers.length,capabilityMatrix:e,recommendedProvider:this.providers[0]?.getName()||`None`}}};function UT(e){return Object.keys(e.assets??{}).length||Object.values(e.questions).some(e=>e.type===`box`)?{"TypeSafe-Danger-Zone-Images":`true`}:{}}function WT(e){let t={};return{state:{messages:e.chatPrompt.map(e=>({role:e.role,content:e.role===`function`?e.result:typeof e.content==`string`?e.content:e.role===`user`?e.content.map(e=>{if(e.type===`text`)return e.text;if(e.type!==`image`)throw Error(`Typesafe supports text and inline PNG/JPEG images only`);let n={"image/png":`png`,"image/jpeg":`jpeg`,"image/jpg":`jpg`}[e.mimeType??``];if(!n)throw Error(`Typesafe images must be PNG or JPEG`);let r=e.image;if(r.startsWith(`data:`)){let t=/^data:(image\/(?:png|jpeg|jpg));base64,(.*)$/.exec(r);if(!t||t[1]!==e.mimeType)throw Error(`Typesafe image data URL must match its MIME type`);r=t[2]}let i=c();return t[i]={type:`image`,format:n,data_base64:r},i}).join(`
866
866
  `):``}))},...Object.keys(t).length?{assets:t}:{}}}function GT(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Typesafe: ${t} must be an object`);return e}function KT(e,t){if(typeof e!=`number`||!Number.isFinite(e)||e<0||e>1)throw Error(`Typesafe: invalid probability for ${t}`);return e}function qT(e,t,n=/* @__PURE__ */ new Set){if(e!==null&&typeof e!=`string`&&typeof e!=`boolean`&&!(typeof e==`number`&&Number.isFinite(e))){if(typeof e!=`object`||!e||n.has(e))throw Error(`Typesafe: ${t} must contain finite, non-circular JSON values`);if(!Array.isArray(e)&&![Object.prototype,null].includes(Object.getPrototypeOf(e)))throw Error(`Typesafe: ${t} must contain plain JSON objects`);n.add(e);for(let r of Array.isArray(e)?e:Object.values(e))qT(r,t,n);n.delete(e)}}function JT(e,t){if(e!==null&&typeof e!=`string`&&typeof e!=`object`)throw Error(`Typesafe: ${t} must be text, an object, an array, or null`);qT(e,t)}function YT(e){if(typeof e.model!=`string`||!e.model.trim())throw Error(`Typesafe: model must be a nonempty string`);JT(e.state,`state`);let t=GT(e.questions,`questions`);if(ZT(e),!Object.keys(t).length)throw Error(`Typesafe: questions must not be empty`);for(let[n,r]of Object.entries(t)){let t=GT(r,`question ${n}`);if(t.instructions!==void 0&&JT(t.instructions,`${n}.instructions`),t.type===`box`){if(t.instructions===void 0||t.instructions===null||typeof t.instructions==`string`&&!t.instructions.trim())throw Error(`Typesafe: Box ${n} requires instructions`);if(t.criteria!==void 0)throw Error(`Typesafe: Box ${n} does not accept criteria`);if(!Object.keys(e.assets??{}).length)throw Error(`Typesafe: Box ${n} requires an image asset`)}else if(t.type===`noul`){if(t.criteria!==void 0&&t.criteria!==null){let e=GT(t.criteria,`${n}.criteria`);for(let[t,r]of Object.entries(e)){if(t!==`true`&&t!==`false`)throw Error(`Typesafe: invalid Noul criterion ${n}.${t}`);JT(r,`${n}.criteria.${t}`)}}}else if(t.type===`choice`){let e=GT(t.criteria,`${n}.criteria`),r=Object.values(e);if(r.length<1||r.length>255)throw Error(`Typesafe: Choice ${n} requires 1–255 options`);for(let e of r)JT(e,`${n}.criteria`)}else if(t.type===`score`){if(!Array.isArray(t.criteria)||t.criteria.length<2||t.criteria.length>10)throw Error(`Typesafe: Score ${n} requires 2–10 levels`);for(let e of t.criteria)JT(e,`${n}.criteria`)}else throw Error(`Typesafe: unknown question type for ${n}`)}}function XT(e,t){let n=GT(e,`response`),r=GT(n.answers,`answers`);for(let[e,n]of Object.entries(t)){if(!Object.hasOwn(r,e))throw Error(`Typesafe: missing answer for ${e}`);let t=GT(r[e],`answer ${e}`);if(t.type!==n.type)throw Error(`Typesafe: incorrect answer type for ${e}`);if(n.type===`noul`){KT(t.noul,e);continue}if(KT(t.confidence,`${e}.confidence`),n.type===`box`){qe(t.box,e);continue}let i=GT(t.probabilities,`${e}.probabilities`),a=n.type===`choice`?Object.keys(n.criteria):n.criteria.map((e,t)=>String(t));if(Object.keys(i).length!==a.length||a.some(e=>!Object.hasOwn(i,e)))throw Error(`Typesafe: incomplete probability distribution for ${e}`);let o=a.reduce((t,n)=>t+KT(i[n],`${e}.${n}`),0),s=2**-52*a.length;if(Math.abs(o-1)>.01+s)throw Error(`Typesafe: invalid probability distribution for ${e}`);if(n.type===`choice`){if(typeof t.choice!=`string`||!Object.hasOwn(n.criteria,t.choice))throw Error(`Typesafe: unknown choice for ${e}`)}else{if(typeof t.score!=`number`||!Number.isFinite(t.score)||t.score<0||t.score>a.length-1)throw Error(`Typesafe: invalid score for ${e}`);let n=GT(t.legend,`${e}.legend`);if(Object.keys(n).length!==a.length||a.some(e=>!Object.hasOwn(n,e)))throw Error(`Typesafe: incomplete legend for ${e}`);for(let t of Object.values(n))JT(t,`${e}.legend`)}}let i=GT(n.usage,`usage`);for(let e of[i.input_tokens,i.output_tokens])if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(`Typesafe: invalid token usage`);if(typeof n.model!=`string`||!n.model.trim())throw Error(`Typesafe: missing response model`);return e}function ZT(e){if(e.assets===void 0)return;let t=GT(e.assets,`assets`),n=[],r=e=>{if(typeof e==`string`)n.push(e);else if(e&&typeof e==`object`)for(let t of Object.values(e))r(t)};qT(e.questions,`questions`),r(e.state);for(let t of Object.values(e.questions))r(t.instructions),`criteria`in t&&r(t.criteria);let i=0;for(let[e,r]of Object.entries(t)){let t=new TextEncoder().encode(e).length;if(i+=t,!e.trim()||t>1024||i>65536)throw Error(`Typesafe: invalid image reference length`);if(!n.some(t=>t.includes(e)))throw Error(`Typesafe: image asset ${e} is not referenced`);let a=GT(r,`asset ${e}`);if(a.type!==void 0&&a.type!==`image`)throw Error(`Typesafe: assets must be images`);if(a.part!==void 0)throw Error(`Typesafe: multipart assets are not supported; use data_base64`);if(![`png`,`jpg`,`jpeg`].includes(String(a.format)))throw Error(`Typesafe: images must be PNG or JPEG`);let o=a.data_base64;if(typeof o!=`string`||!o.length||o.length%4!=0||!/^[A-Za-z0-9+/]+={0,2}$/.test(o))throw Error(`Typesafe: image data_base64 must be padded base64 without a data URL prefix`);if(o.length/4*3-(o.endsWith(`==`)?2:+!!o.endsWith(`=`))>16777216)throw Error(`Typesafe: image exceeds 16 MiB`)}if(new TextEncoder().encode(JSON.stringify(e)).length>33554432)throw Error(`Typesafe: image request exceeds 32 MiB`)}var QT=class{threshold;constructor(e){this.threshold=KT(e.trueThreshold??.5,`trueThreshold`)}getModelConfig(){return{stream:!1}}getTokenUsage(){}validateChatReq(e){if(e.functions?.length||e.functionCall&&e.functionCall!==`none`)throw Error(`Typesafe does not support tools; use a generative provider for tool execution`);if(e.modelConfig?.n!==void 0&&e.modelConfig.n!==1)throw Error(`Typesafe does not support multiple completion samples`);if(e.modelConfig?.audio)throw Error(`Typesafe supports text and inline PNG/JPEG images only`);for(let t of e.chatPrompt){if(t.role===`function`||t.role===`assistant`&&(t.functionCalls?.length||t.audio||t.images?.length))throw Error(`Typesafe does not support tool or media history`);if(t.role===`user`&&Array.isArray(t.content)&&t.content.some(e=>e.type!==`text`&&e.type!==`image`))throw Error(`Typesafe supports text and inline PNG/JPEG images only`)}for(let[t,n]of Object.entries(e.modelConfig??{}))if(n!==void 0&&t!==`stream`&&t!==`n`)throw Error(`Typesafe does not support generation control "${t}"`);let t=this.plan(e);YT({model:e.model,...WT(e),questions:Object.fromEntries(t.map(({name:e,question:t})=>[e,t]))})}plan(e){if(e.responseFormat?.type!==`json_schema`)throw Error(`Typesafe requires an output schema. Use ax() with required boolean, class, rubric score or box outputs`);let t=GT(GT(e.responseFormat.schema,`responseFormat.schema`).schema,`output schema`);if(t.type!==`object`||t.anyOf||t.oneOf||t.allOf||t.$ref)throw Error(`Typesafe requires a flat object output schema`);let n=GT(t.properties,`output properties`),r=t.required;if(!Object.keys(n).length)throw Error(`Typesafe requires at least one output field`);return Object.entries(n).map(([t,n])=>{let i=GT(n,`field ${t}`),a=e.responseFormat?.decisionFields?.[t];if(a?.isArray||a?.isOptional)throw Error(`Decision providers require flat, required scalar outputs`);let o=a?{...i,type:a.type===`class`?`string`:a.type,enum:a.type===`class`?a.options:void 0,anyOf:void 0}:i,s=()=>/* @__PURE__ */ Error(`Typesafe cannot evaluate output "${t}". Use required boolean, class, rubric score or box fields, or a generative provider for other outputs`);if(!Array.isArray(r)||!r.includes(t)||o.anyOf||o.oneOf||o.allOf||o.$ref||o.const!==void 0)throw s();let c=e.responseFormat?.fieldDescriptions?.[t];if(c){if(GT(c,`field description ${t}`),GT(c.valueDescriptions,`value descriptions for ${t}`),c.description!==void 0&&typeof c.description!=`string`)throw Error(`Typesafe: description for ${t} must be a string`);ct(o.type===`string`&&Array.isArray(o.enum)?`class`:String(o.type),c.valueDescriptions,o.enum,t)}let l=c?c.description:o.description,u=typeof l==`string`&&l?`${t}: ${l}`:`Evaluate the output field ${t}.`;if(a?.type===`box`)return{name:t,question:{type:`box`,instructions:u}};if(a?.type===`score`)return{name:t,question:{type:`score`,instructions:u,criteria:a.options}};if(o.type===`boolean`&&!o.enum)return{name:t,question:{type:`noul`,instructions:u,...c?{criteria:{...c.valueDescriptions}}:{}}};if(o.type===`string`&&Array.isArray(o.enum)&&o.enum.length>0&&o.enum.every(e=>typeof e==`string`)&&new Set(o.enum).size===o.enum.length)return{name:t,question:{type:`choice`,instructions:u,criteria:Object.fromEntries(o.enum.map(e=>[e,c&&Object.hasOwn(c.valueDescriptions,e)?c.valueDescriptions[e]:null]))}};throw s()})}createChatReq(e){this.validateChatReq(e);let t=this.plan(e),n={model:e.model,...WT(e),questions:Object.fromEntries(t.map(({name:e,question:t})=>[e,t]))};return[{name:`/v1/systemone`,headers:UT(n)},n]}createChatResp(e,t){if(!t)throw Error(`Typesafe response decoding requires its request`);let n=this.plan(t),r=XT(e,Object.fromEntries(n.map(({name:e,question:t})=>[e,t]))),i={},a=n.map(({name:e})=>{let n=r.answers[e];return n.type===`box`?(i[e]={confidence:n.confidence},[e,t.responseFormat?.decisionFields?.[e]?.evidence?{box:n.box}:n.box]):t.responseFormat?.decisionFields?.[e]?n.type===`noul`?(i[e]={},[e,{probability:n.noul}]):n.type===`score`?(i[e]={value:n.score,confidence:n.confidence},[e,{probabilities:Object.keys(n.probabilities).sort((e,t)=>Number(e)-Number(t)).map(e=>n.probabilities[e])}]):(i[e]={value:n.choice,confidence:n.confidence},[e,{probabilities:n.probabilities}]):[e,n.type===`noul`?n.noul>=this.threshold:n.type===`choice`?n.choice:n.score]});return{results:[{index:0,...Object.keys(i).length?{decisionContext:{provenance:{source:`native`,provider:`Typesafe`,model:r.model},native:i}}:{},content:JSON.stringify(Object.fromEntries(a)),finishReason:`stop`}],modelUsage:{ai:`Typesafe`,model:r.model,tokens:{promptTokens:r.usage.input_tokens,completionTokens:r.usage.output_tokens,totalTokens:r.usage.input_tokens+r.usage.output_tokens}},providerMetadata:{typesafe:{answers:r.answers}}}}},$T=class extends Sy{constructor(e){if(!e.apiKey?.trim()&&!e.credentialProvider)throw Error(`Typesafe requires apiKey or credentialProvider`);let t=uw(`typesafe`),n=e.config?.model??t.defaultModel;super(new QT(e),{name:`Typesafe`,profile:`typesafe`,apiURL:e.apiURL??t.baseURL,headers:async()=>e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{},credentialProvider:e.credentialProvider,modelInfo:e.modelInfo??[],defaults:{model:n},options:e.options,models:e.models,supportFor:()=>{let e=gw(`typesafe`,n);return{...e,media:{...e.media,images:{supported:!0,formats:[`image/png`,`image/jpeg`,`image/jpg`]}}}}})}};jo();var eE=class{args;constructor(e){if(!e.apiKey?.trim()&&!e.credentialProvider)throw Error(`Typesafe requires apiKey or credentialProvider`);this.args={...e,headers:{...e.headers},options:{...e.options}}}async systemOne(e,t){let n={...e,model:e.model??this.args.model??`jev-latest`};YT(n);let r=structuredClone(n);return XT(await this.request(`/v1/systemone`,`POST`,r,t),r.questions)}async listModels(e){let t=GT(await this.request(`/v1/models`,`GET`,void 0,e),`model catalog`).models;if(!Array.isArray(t))throw Error(`Typesafe: model catalog must be an array`);for(let e of t){let t=GT(e,`model card`);if(typeof t.name!=`string`||!t.name.trim()||typeof t.description!=`string`||typeof t.release_date!=`string`)throw Error(`Typesafe: invalid model card`)}return t}async request(e,t,n,r){let i=Object.fromEntries(Object.entries(r??{}).filter(([,e])=>e!==void 0));return await ns({...this.args.options,...i,abortSignal:Y(this.args.options?.abortSignal,r?.abortSignal),name:e,url:this.args.apiURL??`https://api.typesafe.ai`,method:t,resolveHeaders:async({method:e,url:t})=>({...this.args.apiKey?{Authorization:`Bearer ${this.args.apiKey}`}:{},...e===`POST`?UT(n):{},...this.args.headers,...await this.args.credentialProvider?.({profile:`typesafe`,operation:e===`GET`?`models`:`chat`,method:e,url:t})})},n)}};function tE(e){return new eE(e)}const nE=()=>structuredClone({model:`Llama-3.2-3B-Instruct-q4f32_1-MLC`,...hy()}),rE=()=>structuredClone({model:`Llama-3.2-3B-Instruct-q4f32_1-MLC`,...by()});var iE=class{config;tokensUsed;engine;constructor(e,t){this.config=e,this.engine=t}getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,stream:e.stream,n:e.n}}createChatReq(e){let t=e.model,n=this.config.supportsFunctions??!1,r=e.chatPrompt.map(e=>{if(e.role===`function`){let t=e.content?.length?e.content.map(e=>e.type===`text`?e.text:e.type===`image`?e.altText??`[MCP image result: ${e.mimeType}]`:e.type===`audio`?e.transcription??`[MCP audio result: ${e.mimeType??`application/octet-stream`}]`:e.type===`url`?e.cachedContent??[e.title,e.description,e.url].filter(Boolean).join(`
867
867
  `):e.extractedText??`[MCP file result: ${e.filename??`file`} (${e.mimeType})]`).join(`