blink 0.1.61 → 0.1.63

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.
@@ -18,4 +18,4 @@ ${e}
18
18
 
19
19
  `;break}case`tool`:throw new L({functionality:`tool messages`});default:{let e=i;throw Error(`Unsupported role: ${e}`)}}return r+=`${n}:
20
20
  `,{prompt:r,stopSequences:[`
21
- ${t}:`]}}function or({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function sr(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`content_filter`:return`content-filter`;case`function_call`:case`tool_calls`:return`tool-calls`;default:return`unknown`}}var cr=t.z.object({echo:t.z.boolean().optional(),logitBias:t.z.record(t.z.string(),t.z.number()).optional(),suffix:t.z.string().optional(),user:t.z.string().optional(),logprobs:t.z.union([t.z.boolean(),t.z.number()]).optional()}),lr=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(`.`)[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,tools:l,toolChoice:u,seed:d,providerOptions:f}){let p=[],m={...await V({provider:`openai`,providerOptions:f,schema:cr}),...await V({provider:this.providerOptionsName,providerOptions:f,schema:cr})};i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),l?.length&&p.push({type:`unsupported-setting`,setting:`tools`}),u!=null&&p.push({type:`unsupported-setting`,setting:`toolChoice`}),c!=null&&c.type!==`text`&&p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format is not supported.`});let{prompt:h,stopSequences:g}=ar({prompt:e}),_=[...g??[],...s??[]];return{args:{model:this.modelId,echo:m.echo,logit_bias:m.logitBias,logprobs:m?.logprobs===!0?0:m?.logprobs===!1?void 0:m?.logprobs,suffix:m.suffix,user:m.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:a,presence_penalty:o,seed:d,prompt:h,stop:_.length>0?_:void 0},warnings:p}}async doGenerate(e){var t,n,r;let{args:i,warnings:a}=await this.getArgs(e),{responseHeaders:o,value:s,rawValue:c}=await H({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:R(this.config.headers(),e.headers),body:i,failedResponseHandler:$,successfulResponseHandler:q(dr),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=s.choices[0],u={openai:{}};return l.logprobs!=null&&(u.openai.logprobs=l.logprobs),{content:[{type:`text`,text:l.text}],usage:{inputTokens:(t=s.usage)?.prompt_tokens,outputTokens:(n=s.usage)?.completion_tokens,totalTokens:(r=s.usage)?.total_tokens},finishReason:sr(l.finish_reason),request:{body:i},response:{...or(s),headers:o,body:c},providerMetadata:u,warnings:a}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:a}=await H({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:R(this.config.headers(),e.headers),body:r,failedResponseHandler:$,successfulResponseHandler:K(fr),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=`unknown`,s={openai:{}},c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=!0;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){o=`error`,n.enqueue({type:`error`,error:t.error});return}let r=t.value;if(`error`in r){o=`error`,n.enqueue({type:`error`,error:r.error});return}l&&(l=!1,n.enqueue({type:`response-metadata`,...or(r)}),n.enqueue({type:`text-start`,id:`0`})),r.usage!=null&&(c.inputTokens=r.usage.prompt_tokens,c.outputTokens=r.usage.completion_tokens,c.totalTokens=r.usage.total_tokens);let i=r.choices[0];i?.finish_reason!=null&&(o=sr(i.finish_reason)),i?.logprobs!=null&&(s.openai.logprobs=i.logprobs),i?.text!=null&&i.text.length>0&&n.enqueue({type:`text-delta`,id:`0`,delta:i.text})},flush(e){l||e.enqueue({type:`text-end`,id:`0`}),e.enqueue({type:`finish`,finishReason:o,providerMetadata:s,usage:c})}})),request:{body:r},response:{headers:i}}}},ur=t.z.object({prompt_tokens:t.z.number(),completion_tokens:t.z.number(),total_tokens:t.z.number()}),dr=t.z.object({id:t.z.string().nullish(),created:t.z.number().nullish(),model:t.z.string().nullish(),choices:t.z.array(t.z.object({text:t.z.string(),finish_reason:t.z.string(),logprobs:t.z.object({tokens:t.z.array(t.z.string()),token_logprobs:t.z.array(t.z.number()),top_logprobs:t.z.array(t.z.record(t.z.string(),t.z.number())).nullish()}).nullish()})),usage:ur.nullish()}),fr=t.z.union([t.z.object({id:t.z.string().nullish(),created:t.z.number().nullish(),model:t.z.string().nullish(),choices:t.z.array(t.z.object({text:t.z.string(),finish_reason:t.z.string().nullish(),index:t.z.number(),logprobs:t.z.object({tokens:t.z.array(t.z.string()),token_logprobs:t.z.array(t.z.number()),top_logprobs:t.z.array(t.z.record(t.z.string(),t.z.number())).nullish()}).nullish()})),usage:ur.nullish()}),Ln]),pr=t.z.object({dimensions:t.z.number().optional(),user:t.z.string().optional()}),mr=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){var i;if(e.length>this.maxEmbeddingsPerCall)throw new Te({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let a=(i=await V({provider:`openai`,providerOptions:r,schema:pr}))??{},{responseHeaders:o,value:s,rawValue:c}=await H({url:this.config.url({path:`/embeddings`,modelId:this.modelId}),headers:R(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:`float`,dimensions:a.dimensions,user:a.user},failedResponseHandler:$,successfulResponseHandler:q(hr),abortSignal:n,fetch:this.config.fetch});return{embeddings:s.data.map(e=>e.embedding),usage:s.usage?{tokens:s.usage.prompt_tokens}:void 0,response:{headers:o,body:c}}}},hr=t.z.object({data:t.z.array(t.z.object({embedding:t.z.array(t.z.number())})),usage:t.z.object({prompt_tokens:t.z.number()}).nullish()}),gr={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},_r=new Set([`gpt-image-1`]),vr=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get maxImagesPerCall(){var e;return(e=gr[this.modelId])??1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:a,headers:o,abortSignal:s}){var c,l,u,d;let f=[];r!=null&&f.push({type:`unsupported-setting`,setting:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&f.push({type:`unsupported-setting`,setting:`seed`});let p=(u=(l=(c=this.config._internal)?.currentDate)?.call(c))??new Date,{value:m,responseHeaders:h}=await H({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:R(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...(d=a.openai)??{},..._r.has(this.modelId)?{}:{response_format:`b64_json`}},failedResponseHandler:$,successfulResponseHandler:q(yr),abortSignal:s,fetch:this.config.fetch});return{images:m.data.map(e=>e.b64_json),warnings:f,response:{timestamp:p,modelId:this.modelId,headers:h},providerMetadata:{openai:{images:m.data.map(e=>e.revised_prompt?{revisedPrompt:e.revised_prompt}:null)}}}}},yr=t.z.object({data:t.z.array(t.z.object({b64_json:t.z.string(),revised_prompt:t.z.string().optional()}))}),br=t.z.object({container:t.z.union([t.z.string(),t.z.object({fileIds:t.z.array(t.z.string()).optional()})]).optional()}),xr=U({id:`openai.code_interpreter`,name:`code_interpreter`,inputSchema:t.z.object({})}),Sr=(e={})=>xr(e),Cr=t.z.object({filters:t.z.object({allowedDomains:t.z.array(t.z.string()).optional()}).optional(),searchContextSize:t.z.enum([`low`,`medium`,`high`]).optional(),userLocation:t.z.object({type:t.z.literal(`approximate`),country:t.z.string().optional(),city:t.z.string().optional(),region:t.z.string().optional(),timezone:t.z.string().optional()}).optional()}),wr=U({id:`openai.web_search`,name:`web_search`,inputSchema:t.z.object({action:t.z.discriminatedUnion(`type`,[t.z.object({type:t.z.literal(`search`),query:t.z.string().nullish()}),t.z.object({type:t.z.literal(`open_page`),url:t.z.string()}),t.z.object({type:t.z.literal(`find`),url:t.z.string(),pattern:t.z.string()})]).nullish()})}),Tr=(e={})=>wr(e),Er={codeInterpreter:Sr,fileSearch:Kn,webSearchPreview:Jn,webSearch:Tr};function Dr(e,t){return t?t.some(t=>e.startsWith(t)):!1}async function Or({prompt:e,systemMessageMode:t,fileIdPrefixes:n}){var r,i,a,o,s,c;let l=[],u=[];for(let{role:d,content:f}of e)switch(d){case`system`:switch(t){case`system`:l.push({role:`system`,content:f});break;case`developer`:l.push({role:`developer`,content:f});break;case`remove`:u.push({type:`other`,message:`system messages are removed for this model`});break;default:{let e=t;throw Error(`Unsupported system message mode: ${e}`)}}break;case`user`:l.push({role:`user`,content:f.map((e,t)=>{var r,i,a;switch(e.type){case`text`:return{type:`input_text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`input_image`,...e.data instanceof URL?{image_url:e.data.toString()}:typeof e.data==`string`&&Dr(e.data,n)?{file_id:e.data}:{image_url:`data:${t};base64,${J(e.data)}`},detail:(i=(r=e.providerOptions)?.openai)?.imageDetail}}else if(e.mediaType===`application/pdf`)return e.data instanceof URL?{type:`input_file`,file_url:e.data.toString()}:{type:`input_file`,...typeof e.data==`string`&&Dr(e.data,n)?{file_id:e.data}:{filename:(a=e.filename)??`part-${t}.pdf`,file_data:`data:application/pdf;base64,${J(e.data)}`}};else throw new L({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e={};for(let t of f)switch(t.type){case`text`:l.push({role:`assistant`,content:[{type:`output_text`,text:t.text}],id:(a=(i=(r=t.providerOptions)?.openai)?.itemId)??void 0});break;case`tool-call`:if(t.providerExecuted)break;l.push({type:`function_call`,call_id:t.toolCallId,name:t.toolName,arguments:JSON.stringify(t.input),id:(c=(s=(o=t.providerOptions)?.openai)?.itemId)??void 0});break;case`tool-result`:u.push({type:`other`,message:`tool result parts in assistant messages are not supported for OpenAI responses`});break;case`reasoning`:{let n=await V({provider:`openai`,providerOptions:t.providerOptions,schema:kr}),r=n?.itemId;if(r!=null){let i=e[r],a=[];t.text.length>0?a.push({type:`summary_text`,text:t.text}):i!==void 0&&u.push({type:`other`,message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(t)}.`}),i===void 0?(e[r]={type:`reasoning`,id:r,encrypted_content:n?.reasoningEncryptedContent,summary:a},l.push(e[r])):i.summary.push(...a)}else u.push({type:`other`,message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(t)}.`});break}}break}case`tool`:for(let e of f){let t=e.output,n;switch(t.type){case`text`:case`error-text`:n=t.value;break;case`content`:case`json`:case`error-json`:n=JSON.stringify(t.value);break}l.push({type:`function_call_output`,call_id:e.toolCallId,output:n})}break;default:{let e=d;throw Error(`Unsupported role: ${e}`)}}return{messages:l,warnings:u}}var kr=t.z.object({itemId:t.z.string().nullish(),reasoningEncryptedContent:t.z.string().nullish()});function Ar({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?`tool-calls`:`stop`;case`max_output_tokens`:return`length`;case`content_filter`:return`content-filter`;default:return t?`tool-calls`:`unknown`}}function jr({tools:e,toolChoice:t,strictJsonSchema:n}){e=e?.length?e:void 0;let r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};let i=[];for(let t of e)switch(t.type){case`function`:i.push({type:`function`,name:t.name,description:t.description,parameters:t.inputSchema,strict:n});break;case`provider-defined`:switch(t.id){case`openai.file_search`:{let e=Gn.parse(t.args);i.push({type:`file_search`,vector_store_ids:e.vectorStoreIds,max_num_results:e.maxNumResults,ranking_options:e.ranking?{ranker:e.ranking.ranker}:void 0,filters:e.filters});break}case`openai.web_search_preview`:{let e=qn.parse(t.args);i.push({type:`web_search_preview`,search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.web_search`:{let e=Cr.parse(t.args);i.push({type:`web_search`,filters:e.filters==null?void 0:{allowed_domains:e.filters.allowedDomains},search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.code_interpreter`:{let e=br.parse(t.args);i.push({type:`code_interpreter`,container:e.container==null?{type:`auto`,file_ids:void 0}:typeof e.container==`string`?e.container:{type:`auto`,file_ids:e.container.fileIds}});break}default:r.push({type:`unsupported-tool`,tool:t});break}break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:i,toolChoice:void 0,toolWarnings:r};let a=t.type;switch(a){case`auto`:case`none`:case`required`:return{tools:i,toolChoice:a,toolWarnings:r};case`tool`:return{tools:i,toolChoice:t.toolName===`code_interpreter`||t.toolName===`file_search`||t.toolName===`web_search_preview`||t.toolName===`web_search`?{type:t.toolName}:{type:`function`,name:t.toolName},toolWarnings:r};default:{let e=a;throw new L({functionality:`tool choice type: ${e}`})}}}var Mr=t.z.object({type:t.z.literal(`web_search_call`),id:t.z.string(),status:t.z.string(),action:t.z.discriminatedUnion(`type`,[t.z.object({type:t.z.literal(`search`),query:t.z.string().nullish()}),t.z.object({type:t.z.literal(`open_page`),url:t.z.string()}),t.z.object({type:t.z.literal(`find`),url:t.z.string(),pattern:t.z.string()})]).nullish()}),Nr=20,Pr=t.z.array(t.z.object({token:t.z.string(),logprob:t.z.number(),top_logprobs:t.z.array(t.z.object({token:t.z.string(),logprob:t.z.number()}))})),Fr=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:i,presencePenalty:a,frequencyPenalty:o,seed:s,prompt:c,providerOptions:l,tools:u,toolChoice:d,responseFormat:f}){var p,m,h;let g=[],_=oi(this.modelId);i!=null&&g.push({type:`unsupported-setting`,setting:`topK`}),s!=null&&g.push({type:`unsupported-setting`,setting:`seed`}),a!=null&&g.push({type:`unsupported-setting`,setting:`presencePenalty`}),o!=null&&g.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),n!=null&&g.push({type:`unsupported-setting`,setting:`stopSequences`});let{messages:v,warnings:y}=await Or({prompt:c,systemMessageMode:_.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes});g.push(...y);let b=await V({provider:`openai`,providerOptions:l,schema:si}),x=(p=b?.strictJsonSchema)??!1,S=b?.include,C=typeof b?.logprobs==`number`?b?.logprobs:b?.logprobs===!0?Nr:void 0;S=C?Array.isArray(S)?[...S,`message.output_text.logprobs`]:[`message.output_text.logprobs`]:S;let w=(m=u?.find(e=>e.type===`provider-defined`&&(e.id===`openai.web_search`||e.id===`openai.web_search_preview`)))?.name;S=w?Array.isArray(S)?[...S,`web_search_call.action.sources`]:[`web_search_call.action.sources`]:S;let T={model:this.modelId,input:v,temperature:t,top_p:r,max_output_tokens:e,...(f?.type===`json`||b?.textVerbosity)&&{text:{...f?.type===`json`&&{format:f.schema==null?{type:`json_object`}:{type:`json_schema`,strict:x,name:(h=f.name)??`response`,description:f.description,schema:f.schema}},...b?.textVerbosity&&{verbosity:b.textVerbosity}}},metadata:b?.metadata,parallel_tool_calls:b?.parallelToolCalls,previous_response_id:b?.previousResponseId,store:b?.store,user:b?.user,instructions:b?.instructions,service_tier:b?.serviceTier,include:S,prompt_cache_key:b?.promptCacheKey,safety_identifier:b?.safetyIdentifier,top_logprobs:C,..._.isReasoningModel&&(b?.reasoningEffort!=null||b?.reasoningSummary!=null)&&{reasoning:{...b?.reasoningEffort!=null&&{effort:b.reasoningEffort},...b?.reasoningSummary!=null&&{summary:b.reasoningSummary}}},..._.requiredAutoTruncation&&{truncation:`auto`}};_.isReasoningModel?(T.temperature!=null&&(T.temperature=void 0,g.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for reasoning models`})),T.top_p!=null&&(T.top_p=void 0,g.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported for reasoning models`}))):(b?.reasoningEffort!=null&&g.push({type:`unsupported-setting`,setting:`reasoningEffort`,details:`reasoningEffort is not supported for non-reasoning models`}),b?.reasoningSummary!=null&&g.push({type:`unsupported-setting`,setting:`reasoningSummary`,details:`reasoningSummary is not supported for non-reasoning models`})),b?.serviceTier===`flex`&&!_.supportsFlexProcessing&&(g.push({type:`unsupported-setting`,setting:`serviceTier`,details:`flex processing is only available for o3, o4-mini, and gpt-5 models`}),delete T.service_tier),b?.serviceTier===`priority`&&!_.supportsPriorityProcessing&&(g.push({type:`unsupported-setting`,setting:`serviceTier`,details:`priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported`}),delete T.service_tier);let{tools:E,toolChoice:D,toolWarnings:O}=jr({tools:u,toolChoice:d,strictJsonSchema:x});return{webSearchToolName:w,args:{...T,tools:E,tool_choice:D},warnings:[...g,...O]}}async doGenerate(e){var n,r,i,a,o,s,c,l,u,d,p,m,h,g,_,v,y;let{args:b,warnings:x,webSearchToolName:S}=await this.getArgs(e),C=this.config.url({path:`/responses`,modelId:this.modelId}),{responseHeaders:w,value:T,rawValue:E}=await H({url:C,headers:R(this.config.headers(),e.headers),body:b,failedResponseHandler:$,successfulResponseHandler:q(t.z.object({id:t.z.string(),created_at:t.z.number(),error:t.z.object({code:t.z.string(),message:t.z.string()}).nullish(),model:t.z.string(),output:t.z.array(t.z.discriminatedUnion(`type`,[t.z.object({type:t.z.literal(`message`),role:t.z.literal(`assistant`),id:t.z.string(),content:t.z.array(t.z.object({type:t.z.literal(`output_text`),text:t.z.string(),logprobs:Pr.nullish(),annotations:t.z.array(t.z.discriminatedUnion(`type`,[t.z.object({type:t.z.literal(`url_citation`),start_index:t.z.number(),end_index:t.z.number(),url:t.z.string(),title:t.z.string()}),t.z.object({type:t.z.literal(`file_citation`),file_id:t.z.string(),filename:t.z.string().nullish(),index:t.z.number().nullish(),start_index:t.z.number().nullish(),end_index:t.z.number().nullish(),quote:t.z.string().nullish()}),t.z.object({type:t.z.literal(`container_file_citation`)})]))}))}),t.z.object({type:t.z.literal(`code_interpreter_call`)}),t.z.object({type:t.z.literal(`function_call`),call_id:t.z.string(),name:t.z.string(),arguments:t.z.string(),id:t.z.string()}),Mr,t.z.object({type:t.z.literal(`computer_call`),id:t.z.string(),status:t.z.string().optional()}),t.z.object({type:t.z.literal(`file_search_call`),id:t.z.string(),status:t.z.string().optional(),queries:t.z.array(t.z.string()).nullish(),results:t.z.array(t.z.object({attributes:t.z.object({file_id:t.z.string(),filename:t.z.string(),score:t.z.number(),text:t.z.string()})})).nullish()}),t.z.object({type:t.z.literal(`reasoning`),id:t.z.string(),encrypted_content:t.z.string().nullish(),summary:t.z.array(t.z.object({type:t.z.literal(`summary_text`),text:t.z.string()}))})])),service_tier:t.z.string().nullish(),incomplete_details:t.z.object({reason:t.z.string()}).nullable(),usage:Ir})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(T.error)throw new f({message:T.error.message,url:C,requestBodyValues:b,statusCode:400,responseHeaders:w,responseBody:E,isRetryable:!1});let D=[],O=[],k=!1;for(let t of T.output)switch(t.type){case`reasoning`:t.summary.length===0&&t.summary.push({type:`summary_text`,text:``});for(let e of t.summary)D.push({type:`reasoning`,text:e.text,providerMetadata:{openai:{itemId:t.id,reasoningEncryptedContent:(n=t.encrypted_content)??null}}});break;case`message`:for(let n of t.content){(i=(r=e.providerOptions)?.openai)?.logprobs&&n.logprobs&&O.push(n.logprobs),D.push({type:`text`,text:n.text,providerMetadata:{openai:{itemId:t.id}}});for(let e of n.annotations)e.type===`url_citation`?D.push({type:`source`,sourceType:`url`,id:(s=(o=(a=this.config).generateId)?.call(a))??B(),url:e.url,title:e.title}):e.type===`file_citation`&&D.push({type:`source`,sourceType:`document`,id:(u=(l=(c=this.config).generateId)?.call(c))??B(),mediaType:`text/plain`,title:(p=(d=e.quote)??e.filename)??`Document`,filename:(m=e.filename)??e.file_id})}break;case`function_call`:k=!0,D.push({type:`tool-call`,toolCallId:t.call_id,toolName:t.name,input:t.arguments,providerMetadata:{openai:{itemId:t.id}}});break;case`web_search_call`:D.push({type:`tool-call`,toolCallId:t.id,toolName:S??`web_search`,input:JSON.stringify({action:t.action}),providerExecuted:!0}),D.push({type:`tool-result`,toolCallId:t.id,toolName:S??`web_search`,result:{status:t.status},providerExecuted:!0});break;case`computer_call`:D.push({type:`tool-call`,toolCallId:t.id,toolName:`computer_use`,input:``,providerExecuted:!0}),D.push({type:`tool-result`,toolCallId:t.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:t.status||`completed`},providerExecuted:!0});break;case`file_search_call`:D.push({type:`tool-call`,toolCallId:t.id,toolName:`file_search`,input:``,providerExecuted:!0}),D.push({type:`tool-result`,toolCallId:t.id,toolName:`file_search`,result:{type:`file_search_tool_result`,status:t.status||`completed`,...t.queries&&{queries:t.queries},...t.results&&{results:t.results}},providerExecuted:!0});break}let A={openai:{responseId:T.id}};return O.length>0&&(A.openai.logprobs=O),typeof T.service_tier==`string`&&(A.openai.serviceTier=T.service_tier),{content:D,finishReason:Ar({finishReason:(h=T.incomplete_details)?.reason,hasFunctionCall:k}),usage:{inputTokens:T.usage.input_tokens,outputTokens:T.usage.output_tokens,totalTokens:T.usage.input_tokens+T.usage.output_tokens,reasoningTokens:(_=(g=T.usage.output_tokens_details)?.reasoning_tokens)??void 0,cachedInputTokens:(y=(v=T.usage.input_tokens_details)?.cached_tokens)??void 0},request:{body:b},response:{id:T.id,timestamp:new Date(T.created_at*1e3),modelId:T.model,headers:w,body:E},providerMetadata:A,warnings:x}}async doStream(e){let{args:t,warnings:n,webSearchToolName:r}=await this.getArgs(e),{responseHeaders:i,value:a}=await H({url:this.config.url({path:`/responses`,modelId:this.modelId}),headers:R(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:$,successfulResponseHandler:K(qr),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=this,s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=[],u=null,d={},f=!1,p={},m;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){var i,a,h,g,_,v,y,b,x,S,C,w,T,E,D,O,k,A,ee,te,j;if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){s=`error`,n.enqueue({type:`error`,error:t.error});return}let M=t.value;if(ei(M))M.item.type===`function_call`?(d[M.output_index]={toolName:M.item.name,toolCallId:M.item.call_id},n.enqueue({type:`tool-input-start`,id:M.item.call_id,toolName:M.item.name})):M.item.type===`web_search_call`?(d[M.output_index]={toolName:r??`web_search`,toolCallId:M.item.id},n.enqueue({type:`tool-input-start`,id:M.item.id,toolName:r??`web_search`})):M.item.type===`computer_call`?(d[M.output_index]={toolName:`computer_use`,toolCallId:M.item.id},n.enqueue({type:`tool-input-start`,id:M.item.id,toolName:`computer_use`})):M.item.type===`file_search_call`?(d[M.output_index]={toolName:`file_search`,toolCallId:M.item.id},n.enqueue({type:`tool-input-start`,id:M.item.id,toolName:`file_search`})):M.item.type===`message`?n.enqueue({type:`text-start`,id:M.item.id,providerMetadata:{openai:{itemId:M.item.id}}}):ti(M)&&(p[M.item.id]={encryptedContent:M.item.encrypted_content,summaryParts:[0]},n.enqueue({type:`reasoning-start`,id:`${M.item.id}:0`,providerMetadata:{openai:{itemId:M.item.id,reasoningEncryptedContent:(i=M.item.encrypted_content)??null}}}));else if(Yr(M)){if(M.item.type===`function_call`)d[M.output_index]=void 0,f=!0,n.enqueue({type:`tool-input-end`,id:M.item.call_id}),n.enqueue({type:`tool-call`,toolCallId:M.item.call_id,toolName:M.item.name,input:M.item.arguments,providerMetadata:{openai:{itemId:M.item.id}}});else if(M.item.type===`web_search_call`)d[M.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:M.item.id}),n.enqueue({type:`tool-call`,toolCallId:M.item.id,toolName:`web_search`,input:JSON.stringify({action:M.item.action}),providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:M.item.id,toolName:`web_search`,result:{status:M.item.status},providerExecuted:!0});else if(M.item.type===`computer_call`)d[M.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:M.item.id}),n.enqueue({type:`tool-call`,toolCallId:M.item.id,toolName:`computer_use`,input:``,providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:M.item.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:M.item.status||`completed`},providerExecuted:!0});else if(M.item.type===`file_search_call`)d[M.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:M.item.id}),n.enqueue({type:`tool-call`,toolCallId:M.item.id,toolName:`file_search`,input:``,providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:M.item.id,toolName:`file_search`,result:{type:`file_search_tool_result`,status:M.item.status||`completed`,...M.item.queries&&{queries:M.item.queries},...M.item.results&&{results:M.item.results}},providerExecuted:!0});else if(M.item.type===`message`)n.enqueue({type:`text-end`,id:M.item.id});else if(Xr(M)){let e=p[M.item.id];for(let t of e.summaryParts)n.enqueue({type:`reasoning-end`,id:`${M.item.id}:${t}`,providerMetadata:{openai:{itemId:M.item.id,reasoningEncryptedContent:(a=M.item.encrypted_content)??null}}});delete p[M.item.id]}}else if($r(M)){let e=d[M.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:M.delta})}else Qr(M)?(u=M.response.id,n.enqueue({type:`response-metadata`,id:M.response.id,timestamp:new Date(M.response.created_at*1e3),modelId:M.response.model})):Jr(M)?(n.enqueue({type:`text-delta`,id:M.item_id,delta:M.delta}),(g=(h=e.providerOptions)?.openai)?.logprobs&&M.logprobs&&l.push(M.logprobs)):ri(M)?M.summary_index>0&&((_=p[M.item_id])==null||_.summaryParts.push(M.summary_index),n.enqueue({type:`reasoning-start`,id:`${M.item_id}:${M.summary_index}`,providerMetadata:{openai:{itemId:M.item_id,reasoningEncryptedContent:(y=(v=p[M.item_id])?.encryptedContent)??null}}})):ii(M)?n.enqueue({type:`reasoning-delta`,id:`${M.item_id}:${M.summary_index}`,delta:M.delta,providerMetadata:{openai:{itemId:M.item_id}}}):Zr(M)?(s=Ar({finishReason:(b=M.response.incomplete_details)?.reason,hasFunctionCall:f}),c.inputTokens=M.response.usage.input_tokens,c.outputTokens=M.response.usage.output_tokens,c.totalTokens=M.response.usage.input_tokens+M.response.usage.output_tokens,c.reasoningTokens=(S=(x=M.response.usage.output_tokens_details)?.reasoning_tokens)??void 0,c.cachedInputTokens=(w=(C=M.response.usage.input_tokens_details)?.cached_tokens)??void 0,typeof M.response.service_tier==`string`&&(m=M.response.service_tier)):ni(M)?M.annotation.type===`url_citation`?n.enqueue({type:`source`,sourceType:`url`,id:(D=(E=(T=o.config).generateId)?.call(T))??B(),url:M.annotation.url,title:M.annotation.title}):M.annotation.type===`file_citation`&&n.enqueue({type:`source`,sourceType:`document`,id:(A=(k=(O=o.config).generateId)?.call(O))??B(),mediaType:`text/plain`,title:(te=(ee=M.annotation.quote)??M.annotation.filename)??`Document`,filename:(j=M.annotation.filename)??M.annotation.file_id}):ai(M)&&n.enqueue({type:`error`,error:M})},flush(e){let t={openai:{responseId:u}};l.length>0&&(t.openai.logprobs=l),m!==void 0&&(t.openai.serviceTier=m),e.enqueue({type:`finish`,finishReason:s,usage:c,providerMetadata:t})}})),request:{body:t},response:{headers:i}}}},Ir=t.z.object({input_tokens:t.z.number(),input_tokens_details:t.z.object({cached_tokens:t.z.number().nullish()}).nullish(),output_tokens:t.z.number(),output_tokens_details:t.z.object({reasoning_tokens:t.z.number().nullish()}).nullish()}),Lr=t.z.object({type:t.z.literal(`response.output_text.delta`),item_id:t.z.string(),delta:t.z.string(),logprobs:Pr.nullish()}),Rr=t.z.object({type:t.z.literal(`error`),code:t.z.string(),message:t.z.string(),param:t.z.string().nullish(),sequence_number:t.z.number()}),zr=t.z.object({type:t.z.enum([`response.completed`,`response.incomplete`]),response:t.z.object({incomplete_details:t.z.object({reason:t.z.string()}).nullish(),usage:Ir,service_tier:t.z.string().nullish()})}),Br=t.z.object({type:t.z.literal(`response.created`),response:t.z.object({id:t.z.string(),created_at:t.z.number(),model:t.z.string(),service_tier:t.z.string().nullish()})}),Vr=t.z.object({type:t.z.literal(`response.output_item.added`),output_index:t.z.number(),item:t.z.discriminatedUnion(`type`,[t.z.object({type:t.z.literal(`message`),id:t.z.string()}),t.z.object({type:t.z.literal(`reasoning`),id:t.z.string(),encrypted_content:t.z.string().nullish()}),t.z.object({type:t.z.literal(`function_call`),id:t.z.string(),call_id:t.z.string(),name:t.z.string(),arguments:t.z.string()}),t.z.object({type:t.z.literal(`web_search_call`),id:t.z.string(),status:t.z.string(),action:t.z.object({type:t.z.literal(`search`),query:t.z.string().optional()}).nullish()}),t.z.object({type:t.z.literal(`computer_call`),id:t.z.string(),status:t.z.string()}),t.z.object({type:t.z.literal(`file_search_call`),id:t.z.string(),status:t.z.string(),queries:t.z.array(t.z.string()).nullish(),results:t.z.array(t.z.object({attributes:t.z.object({file_id:t.z.string(),filename:t.z.string(),score:t.z.number(),text:t.z.string()})})).optional()})])}),Hr=t.z.object({type:t.z.literal(`response.output_item.done`),output_index:t.z.number(),item:t.z.discriminatedUnion(`type`,[t.z.object({type:t.z.literal(`message`),id:t.z.string()}),t.z.object({type:t.z.literal(`reasoning`),id:t.z.string(),encrypted_content:t.z.string().nullish()}),t.z.object({type:t.z.literal(`function_call`),id:t.z.string(),call_id:t.z.string(),name:t.z.string(),arguments:t.z.string(),status:t.z.literal(`completed`)}),Mr,t.z.object({type:t.z.literal(`computer_call`),id:t.z.string(),status:t.z.literal(`completed`)}),t.z.object({type:t.z.literal(`file_search_call`),id:t.z.string(),status:t.z.literal(`completed`),queries:t.z.array(t.z.string()).nullish(),results:t.z.array(t.z.object({attributes:t.z.object({file_id:t.z.string(),filename:t.z.string(),score:t.z.number(),text:t.z.string()})})).nullish()})])}),Ur=t.z.object({type:t.z.literal(`response.function_call_arguments.delta`),item_id:t.z.string(),output_index:t.z.number(),delta:t.z.string()}),Wr=t.z.object({type:t.z.literal(`response.output_text.annotation.added`),annotation:t.z.discriminatedUnion(`type`,[t.z.object({type:t.z.literal(`url_citation`),url:t.z.string(),title:t.z.string()}),t.z.object({type:t.z.literal(`file_citation`),file_id:t.z.string(),filename:t.z.string().nullish(),index:t.z.number().nullish(),start_index:t.z.number().nullish(),end_index:t.z.number().nullish(),quote:t.z.string().nullish()})])}),Gr=t.z.object({type:t.z.literal(`response.reasoning_summary_part.added`),item_id:t.z.string(),summary_index:t.z.number()}),Kr=t.z.object({type:t.z.literal(`response.reasoning_summary_text.delta`),item_id:t.z.string(),summary_index:t.z.number(),delta:t.z.string()}),qr=t.z.union([Lr,zr,Br,Vr,Hr,Ur,Wr,Gr,Kr,Rr,t.z.object({type:t.z.string()}).loose()]);function Jr(e){return e.type===`response.output_text.delta`}function Yr(e){return e.type===`response.output_item.done`}function Xr(e){return Yr(e)&&e.item.type===`reasoning`}function Zr(e){return e.type===`response.completed`||e.type===`response.incomplete`}function Qr(e){return e.type===`response.created`}function $r(e){return e.type===`response.function_call_arguments.delta`}function ei(e){return e.type===`response.output_item.added`}function ti(e){return ei(e)&&e.item.type===`reasoning`}function ni(e){return e.type===`response.output_text.annotation.added`}function ri(e){return e.type===`response.reasoning_summary_part.added`}function ii(e){return e.type===`response.reasoning_summary_text.delta`}function ai(e){return e.type===`error`}function oi(e){let t=e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`),n=e.startsWith(`gpt-4`)||e.startsWith(`gpt-5-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-nano`)&&!e.startsWith(`gpt-5-chat`)||e.startsWith(`o3`)||e.startsWith(`o4-mini`),r={requiredAutoTruncation:!1,systemMessageMode:`system`,supportsFlexProcessing:t,supportsPriorityProcessing:n};return e.startsWith(`gpt-5-chat`)?{...r,isReasoningModel:!1}:e.startsWith(`o`)||e.startsWith(`gpt-5`)||e.startsWith(`codex-`)||e.startsWith(`computer-use`)?e.startsWith(`o1-mini`)||e.startsWith(`o1-preview`)?{...r,isReasoningModel:!0,systemMessageMode:`remove`}:{...r,isReasoningModel:!0,systemMessageMode:`developer`}:{...r,isReasoningModel:!1}}var si=t.z.object({metadata:t.z.any().nullish(),parallelToolCalls:t.z.boolean().nullish(),previousResponseId:t.z.string().nullish(),store:t.z.boolean().nullish(),user:t.z.string().nullish(),reasoningEffort:t.z.string().nullish(),strictJsonSchema:t.z.boolean().nullish(),instructions:t.z.string().nullish(),reasoningSummary:t.z.string().nullish(),serviceTier:t.z.enum([`auto`,`flex`,`priority`]).nullish(),include:t.z.array(t.z.enum([`reasoning.encrypted_content`,`file_search_call.results`,`message.output_text.logprobs`])).nullish(),textVerbosity:t.z.enum([`low`,`medium`,`high`]).nullish(),promptCacheKey:t.z.string().nullish(),safetyIdentifier:t.z.string().nullish(),logprobs:t.z.union([t.z.boolean(),t.z.number().min(1).max(Nr)]).optional()}),ci=t.z.object({instructions:t.z.string().nullish(),speed:t.z.number().min(.25).max(4).default(1).nullish()}),li=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get provider(){return this.config.provider}async getArgs({text:e,voice:t=`alloy`,outputFormat:n=`mp3`,speed:r,instructions:i,language:a,providerOptions:o}){let s=[],c=await V({provider:`openai`,providerOptions:o,schema:ci}),l={model:this.modelId,input:e,voice:t,response_format:`mp3`,speed:r,instructions:i};if(n&&([`mp3`,`opus`,`aac`,`flac`,`wav`,`pcm`].includes(n)?l.response_format=n:s.push({type:`unsupported-setting`,setting:`outputFormat`,details:`Unsupported output format: ${n}. Using mp3 instead.`})),c){let e={};for(let t in e){let n=e[t];n!==void 0&&(l[t]=n)}}return a&&s.push({type:`unsupported-setting`,setting:`language`,details:`OpenAI speech models do not support language selection. Language parameter "${a}" was ignored.`}),{requestBody:l,warnings:s}}async doGenerate(e){var t,n,r;let i=(r=(n=(t=this.config._internal)?.currentDate)?.call(t))??new Date,{requestBody:a,warnings:o}=await this.getArgs(e),{value:s,responseHeaders:c,rawValue:l}=await H({url:this.config.url({path:`/audio/speech`,modelId:this.modelId}),headers:R(this.config.headers(),e.headers),body:a,failedResponseHandler:$,successfulResponseHandler:ht(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:s,warnings:o,request:{body:JSON.stringify(a)},response:{timestamp:i,modelId:this.modelId,headers:c,body:l}}}},ui=t.z.object({include:t.z.array(t.z.string()).optional(),language:t.z.string().optional(),prompt:t.z.string().optional(),temperature:t.z.number().min(0).max(1).default(0).optional(),timestampGranularities:t.z.array(t.z.enum([`word`,`segment`])).default([`segment`]).optional()}),di={afrikaans:`af`,arabic:`ar`,armenian:`hy`,azerbaijani:`az`,belarusian:`be`,bosnian:`bs`,bulgarian:`bg`,catalan:`ca`,chinese:`zh`,croatian:`hr`,czech:`cs`,danish:`da`,dutch:`nl`,english:`en`,estonian:`et`,finnish:`fi`,french:`fr`,galician:`gl`,german:`de`,greek:`el`,hebrew:`he`,hindi:`hi`,hungarian:`hu`,icelandic:`is`,indonesian:`id`,italian:`it`,japanese:`ja`,kannada:`kn`,kazakh:`kk`,korean:`ko`,latvian:`lv`,lithuanian:`lt`,macedonian:`mk`,malay:`ms`,marathi:`mr`,maori:`mi`,nepali:`ne`,norwegian:`no`,persian:`fa`,polish:`pl`,portuguese:`pt`,romanian:`ro`,russian:`ru`,serbian:`sr`,slovak:`sk`,slovenian:`sl`,spanish:`es`,swahili:`sw`,swedish:`sv`,tagalog:`tl`,tamil:`ta`,thai:`th`,turkish:`tr`,ukrainian:`uk`,urdu:`ur`,vietnamese:`vi`,welsh:`cy`},fi=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:n}){let r=[],i=await V({provider:`openai`,providerOptions:n,schema:ui}),a=new FormData,o=e instanceof Uint8Array?new Blob([e]):new Blob([bt(e)]);a.append(`model`,this.modelId);let s=qe(t);if(a.append(`file`,new File([o],`audio`,{type:t}),`audio.${s}`),i){let e={include:i.include,language:i.language,prompt:i.prompt,response_format:[`gpt-4o-transcribe`,`gpt-4o-mini-transcribe`].includes(this.modelId)?`json`:`verbose_json`,temperature:i.temperature,timestamp_granularities:i.timestampGranularities};for(let[t,n]of Object.entries(e))if(n!=null)if(Array.isArray(n))for(let e of n)a.append(`${t}[]`,String(e));else a.append(t,String(n))}return{formData:a,warnings:r}}async doGenerate(e){var t,n,r,i,a,o,s,c;let l=(r=(n=(t=this.config._internal)?.currentDate)?.call(t))??new Date,{formData:u,warnings:d}=await this.getArgs(e),{value:f,responseHeaders:p,rawValue:m}=await dt({url:this.config.url({path:`/audio/transcriptions`,modelId:this.modelId}),headers:R(this.config.headers(),e.headers),formData:u,failedResponseHandler:$,successfulResponseHandler:q(pi),abortSignal:e.abortSignal,fetch:this.config.fetch}),h=f.language!=null&&f.language in di?di[f.language]:void 0;return{text:f.text,segments:(s=(o=(i=f.segments)?.map(e=>({text:e.text,startSecond:e.start,endSecond:e.end})))??(a=f.words)?.map(e=>({text:e.word,startSecond:e.start,endSecond:e.end})))??[],language:h,durationInSeconds:(c=f.duration)??void 0,warnings:d,response:{timestamp:l,modelId:this.modelId,headers:p,body:m}}}},pi=t.z.object({text:t.z.string(),language:t.z.string().nullish(),duration:t.z.number().nullish(),words:t.z.array(t.z.object({word:t.z.string(),start:t.z.number(),end:t.z.number()})).nullish(),segments:t.z.array(t.z.object({id:t.z.number(),seek:t.z.number(),start:t.z.number(),end:t.z.number(),text:t.z.string(),tokens:t.z.array(t.z.number()),temperature:t.z.number(),avg_logprob:t.z.number(),compression_ratio:t.z.number(),no_speech_prob:t.z.number()})).nullish()});function mi(e={}){var t,n;let r=(t=St(e.baseURL))??`https://api.openai.com/v1`,i=(n=e.name)??`openai`,a=()=>({Authorization:`Bearer ${Ke({apiKey:e.apiKey,environmentVariableName:`OPENAI_API_KEY`,description:`OpenAI`})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers}),o=t=>new Xn(t,{provider:`${i}.chat`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),s=t=>new lr(t,{provider:`${i}.completion`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),c=t=>new mr(t,{provider:`${i}.embedding`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),l=t=>new vr(t,{provider:`${i}.image`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),u=t=>new fi(t,{provider:`${i}.transcription`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),d=t=>new li(t,{provider:`${i}.speech`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),f=e=>{if(new.target)throw Error(`The OpenAI model function cannot be called with the new keyword.`);return p(e)},p=t=>new Fr(t,{provider:`${i}.responses`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch,fileIdPrefixes:[`file-`]}),m=function(e){return f(e)};return m.languageModel=f,m.chat=o,m.completion=s,m.responses=p,m.embedding=c,m.textEmbedding=c,m.textEmbeddingModel=c,m.image=l,m.imageModel=l,m.transcription=u,m.transcriptionModel=u,m.speech=d,m.speechModel=d,m.tools=Er,m}var hi=mi(),gi=t.z.object({user:t.z.string().optional(),reasoningEffort:t.z.string().optional()}),_i=t.z.object({error:t.z.object({message:t.z.string(),type:t.z.string().nullish(),param:t.z.any().nullish(),code:t.z.union([t.z.string(),t.z.number()]).nullish()})}),vi={errorSchema:_i,errorToMessage:e=>e.error.message},yi=t.z.object({prompt_tokens:t.z.number().nullish(),completion_tokens:t.z.number().nullish(),total_tokens:t.z.number().nullish(),prompt_tokens_details:t.z.object({cached_tokens:t.z.number().nullish()}).nullish(),completion_tokens_details:t.z.object({reasoning_tokens:t.z.number().nullish(),accepted_prediction_tokens:t.z.number().nullish(),rejected_prediction_tokens:t.z.number().nullish()}).nullish()}).nullish(),bi=t.z.object({id:t.z.string().nullish(),created:t.z.number().nullish(),model:t.z.string().nullish(),choices:t.z.array(t.z.object({message:t.z.object({role:t.z.literal(`assistant`).nullish(),content:t.z.string().nullish(),reasoning_content:t.z.string().nullish(),reasoning:t.z.string().nullish(),tool_calls:t.z.array(t.z.object({id:t.z.string().nullish(),function:t.z.object({name:t.z.string(),arguments:t.z.string()})})).nullish()}),finish_reason:t.z.string().nullish()})),usage:yi}),xi=t.z.object({echo:t.z.boolean().optional(),logitBias:t.z.record(t.z.string(),t.z.number()).optional(),suffix:t.z.string().optional(),user:t.z.string().optional()}),Si=t.z.object({prompt_tokens:t.z.number(),completion_tokens:t.z.number(),total_tokens:t.z.number()}),Ci=t.z.object({id:t.z.string().nullish(),created:t.z.number().nullish(),model:t.z.string().nullish(),choices:t.z.array(t.z.object({text:t.z.string(),finish_reason:t.z.string()})),usage:Si.nullish()}),wi=t.z.object({dimensions:t.z.number().optional(),user:t.z.string().optional()}),Ti=t.z.object({data:t.z.array(t.z.object({embedding:t.z.array(t.z.number())})),usage:t.z.object({prompt_tokens:t.z.number()}).nullish(),providerMetadata:t.z.record(t.z.string(),t.z.record(t.z.string(),t.z.any())).optional()}),Ei=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`,this.maxImagesPerCall=10}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:a,headers:o,abortSignal:s}){var c,l,u,d,f;let p=[];r!=null&&p.push({type:`unsupported-setting`,setting:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&p.push({type:`unsupported-setting`,setting:`seed`});let m=(u=(l=(c=this.config._internal)?.currentDate)?.call(c))??new Date,{value:h,responseHeaders:g}=await H({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:R(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...(d=a.openai)??{},response_format:`b64_json`},failedResponseHandler:G((f=this.config.errorStructure)??vi),successfulResponseHandler:q(Di),abortSignal:s,fetch:this.config.fetch});return{images:h.data.map(e=>e.b64_json),warnings:p,response:{timestamp:m,modelId:this.modelId,headers:g}}}},Di=t.z.object({data:t.z.array(t.z.object({b64_json:t.z.string()}))});function Oi(e){let t=[],n=[];for(let{role:n,content:r}of e)switch(n){case`system`:t.push({role:`system`,content:r});break;case`user`:if(r.length===1&&r[0].type===`text`){t.push({role:`user`,content:r[0].text});break}t.push({role:`user`,content:r.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`image_url`,image_url:{url:e.data instanceof URL?e.data.toString():`data:${t};base64,${J(e.data)}`}}}else throw new L({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e=``,n=[];for(let t of r)switch(t.type){case`text`:e+=t.text;break;case`tool-call`:n.push({id:t.toolCallId,type:`function`,function:{name:t.toolName,arguments:JSON.stringify(t.input)}});break}t.push({role:`assistant`,content:e,tool_calls:n.length>0?n:void 0});break}case`tool`:for(let e of r){let n=e.output,r;switch(n.type){case`text`:case`error-text`:r=n.value;break;case`content`:case`json`:case`error-json`:r=JSON.stringify(n.value);break}t.push({role:`tool`,tool_call_id:e.toolCallId,content:r})}break;default:{let e=n;throw Error(`Unsupported role: ${e}`)}}return{messages:t,warnings:n}}function ki({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function Ai(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`tool_calls`:case`function_call`:return`tool-calls`;case`content_filter`:return`content-filter`;default:return`unknown`}}var ji=t.z.object({type:t.z.literal(`web`),country:t.z.string().length(2).optional(),excludedWebsites:t.z.array(t.z.string()).max(5).optional(),allowedWebsites:t.z.array(t.z.string()).max(5).optional(),safeSearch:t.z.boolean().optional()}),Mi=t.z.object({type:t.z.literal(`x`),xHandles:t.z.array(t.z.string()).optional()}),Ni=t.z.object({type:t.z.literal(`news`),country:t.z.string().length(2).optional(),excludedWebsites:t.z.array(t.z.string()).max(5).optional(),safeSearch:t.z.boolean().optional()}),Pi=t.z.object({type:t.z.literal(`rss`),links:t.z.array(t.z.string().url()).max(1)}),Fi=t.z.discriminatedUnion(`type`,[ji,Mi,Ni,Pi]),Ii=t.z.object({reasoningEffort:t.z.enum([`low`,`high`]).optional(),searchParameters:t.z.object({mode:t.z.enum([`off`,`auto`,`on`]),returnCitations:t.z.boolean().optional(),fromDate:t.z.string().optional(),toDate:t.z.string().optional(),maxSearchResults:t.z.number().min(1).max(50).optional(),sources:t.z.array(Fi).optional()}).optional()}),Li=t.z.object({error:t.z.object({message:t.z.string(),type:t.z.string().nullish(),param:t.z.any().nullish(),code:t.z.union([t.z.string(),t.z.number()]).nullish()})}),Ri=G({errorSchema:Li,errorToMessage:e=>e.error.message});function zi({tools:e,toolChoice:t}){e=e?.length?e:void 0;let n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};let r=[];for(let t of e)t.type===`provider-defined`?n.push({type:`unsupported-tool`,tool:t}):r.push({type:`function`,function:{name:t.name,description:t.description,parameters:t.inputSchema}});if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};let i=t.type;switch(i){case`auto`:case`none`:return{tools:r,toolChoice:i,toolWarnings:n};case`required`:return{tools:r,toolChoice:`required`,toolWarnings:n};case`tool`:return{tools:r,toolChoice:{type:`function`,function:{name:t.toolName}},toolWarnings:n};default:{let e=i;throw new L({functionality:`tool choice type: ${e}`})}}}var Bi=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,seed:c,responseFormat:l,providerOptions:u,tools:d,toolChoice:f}){var p,m,h;let g=[],_=(p=await V({provider:`xai`,providerOptions:u,schema:Ii}))??{};i!=null&&g.push({type:`unsupported-setting`,setting:`topK`}),a!=null&&g.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),o!=null&&g.push({type:`unsupported-setting`,setting:`presencePenalty`}),s!=null&&g.push({type:`unsupported-setting`,setting:`stopSequences`}),l!=null&&l.type===`json`&&l.schema!=null&&g.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format schema is not supported`});let{messages:v,warnings:y}=Oi(e);g.push(...y);let{tools:b,toolChoice:x,toolWarnings:S}=zi({tools:d,toolChoice:f});g.push(...S);let C={model:this.modelId,max_tokens:t,temperature:n,top_p:r,seed:c,reasoning_effort:_.reasoningEffort,response_format:l?.type===`json`?l.schema==null?{type:`json_object`}:{type:`json_schema`,json_schema:{name:(m=l.name)??`response`,schema:l.schema,strict:!0}}:void 0,search_parameters:_.searchParameters?{mode:_.searchParameters.mode,return_citations:_.searchParameters.returnCitations,from_date:_.searchParameters.fromDate,to_date:_.searchParameters.toDate,max_search_results:_.searchParameters.maxSearchResults,sources:(h=_.searchParameters.sources)?.map(e=>({type:e.type,...e.type===`web`&&{country:e.country,excluded_websites:e.excludedWebsites,allowed_websites:e.allowedWebsites,safe_search:e.safeSearch},...e.type===`x`&&{x_handles:e.xHandles},...e.type===`news`&&{country:e.country,excluded_websites:e.excludedWebsites,safe_search:e.safeSearch},...e.type===`rss`&&{links:e.links}}))}:void 0,messages:v,tools:b,tool_choice:x};return{args:C,warnings:g}}async doGenerate(e){var t,n,r;let{args:i,warnings:a}=await this.getArgs(e),{responseHeaders:o,value:s,rawValue:c}=await H({url:`${(t=this.config.baseURL)??`https://api.x.ai/v1`}/chat/completions`,headers:R(this.config.headers(),e.headers),body:i,failedResponseHandler:Ri,successfulResponseHandler:q(Hi),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=s.choices[0],u=[];if(l.message.content!=null&&l.message.content.length>0){let e=l.message.content,t=i.messages[i.messages.length-1];t?.role===`assistant`&&e===t.content&&(e=``),e.length>0&&u.push({type:`text`,text:e})}if(l.message.reasoning_content!=null&&l.message.reasoning_content.length>0&&u.push({type:`reasoning`,text:l.message.reasoning_content}),l.message.tool_calls!=null)for(let e of l.message.tool_calls)u.push({type:`tool-call`,toolCallId:e.id,toolName:e.function.name,input:e.function.arguments});if(s.citations!=null)for(let e of s.citations)u.push({type:`source`,sourceType:`url`,id:this.config.generateId(),url:e});return{content:u,finishReason:Ai(l.finish_reason),usage:{inputTokens:s.usage.prompt_tokens,outputTokens:s.usage.completion_tokens,totalTokens:s.usage.total_tokens,reasoningTokens:(r=(n=s.usage.completion_tokens_details)?.reasoning_tokens)??void 0},request:{body:i},response:{...ki(s),headers:o,body:c},warnings:a}}async doStream(e){var t;let{args:n,warnings:r}=await this.getArgs(e),i={...n,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:a,value:o}=await H({url:`${(t=this.config.baseURL)??`https://api.x.ai/v1`}/chat/completions`,headers:R(this.config.headers(),e.headers),body:i,failedResponseHandler:Ri,successfulResponseHandler:K(Ui),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l={},u={},d=this;return{stream:o.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:r})},transform(t,n){var r,a;if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let o=t.value;if(n.enqueue({type:`response-metadata`,...ki(o)}),o.citations!=null)for(let e of o.citations)n.enqueue({type:`source`,sourceType:`url`,id:d.config.generateId(),url:e});o.usage!=null&&(c.inputTokens=o.usage.prompt_tokens,c.outputTokens=o.usage.completion_tokens,c.totalTokens=o.usage.total_tokens,c.reasoningTokens=(a=(r=o.usage.completion_tokens_details)?.reasoning_tokens)??void 0);let f=o.choices[0];if(f?.finish_reason!=null&&(s=Ai(f.finish_reason)),f?.delta==null)return;let p=f.delta,m=f.index;if(p.content!=null&&p.content.length>0){let e=p.content,t=i.messages[i.messages.length-1];if(t?.role===`assistant`&&e===t.content)return;let r=`text-${o.id||m}`;l[r]??(l[r]={type:`text`},n.enqueue({type:`text-start`,id:r})),n.enqueue({type:`text-delta`,id:r,delta:e})}if(p.reasoning_content!=null&&p.reasoning_content.length>0){let e=`reasoning-${o.id||m}`;if(u[e]===p.reasoning_content)return;u[e]=p.reasoning_content,l[e]??(l[e]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:e})),n.enqueue({type:`reasoning-delta`,id:e,delta:p.reasoning_content})}if(p.tool_calls!=null)for(let e of p.tool_calls){let t=e.id;n.enqueue({type:`tool-input-start`,id:t,toolName:e.function.name}),n.enqueue({type:`tool-input-delta`,id:t,delta:e.function.arguments}),n.enqueue({type:`tool-input-end`,id:t}),n.enqueue({type:`tool-call`,toolCallId:t,toolName:e.function.name,input:e.function.arguments})}},flush(e){for(let[t,n]of Object.entries(l))e.enqueue({type:n.type===`text`?`text-end`:`reasoning-end`,id:t});e.enqueue({type:`finish`,finishReason:s,usage:c})}})),request:{body:i},response:{headers:a}}}},Vi=t.z.object({prompt_tokens:t.z.number(),completion_tokens:t.z.number(),total_tokens:t.z.number(),completion_tokens_details:t.z.object({reasoning_tokens:t.z.number().nullish()}).nullish()}),Hi=t.z.object({id:t.z.string().nullish(),created:t.z.number().nullish(),model:t.z.string().nullish(),choices:t.z.array(t.z.object({message:t.z.object({role:t.z.literal(`assistant`),content:t.z.string().nullish(),reasoning_content:t.z.string().nullish(),tool_calls:t.z.array(t.z.object({id:t.z.string(),type:t.z.literal(`function`),function:t.z.object({name:t.z.string(),arguments:t.z.string()})})).nullish()}),index:t.z.number(),finish_reason:t.z.string().nullish()})),object:t.z.literal(`chat.completion`),usage:Vi,citations:t.z.array(t.z.string().url()).nullish()}),Ui=t.z.object({id:t.z.string().nullish(),created:t.z.number().nullish(),model:t.z.string().nullish(),choices:t.z.array(t.z.object({delta:t.z.object({role:t.z.enum([`assistant`]).optional(),content:t.z.string().nullish(),reasoning_content:t.z.string().nullish(),tool_calls:t.z.array(t.z.object({id:t.z.string(),type:t.z.literal(`function`),function:t.z.object({name:t.z.string(),arguments:t.z.string()})})).nullish()}),finish_reason:t.z.string().nullish(),index:t.z.number()})),usage:Vi.nullish(),citations:t.z.array(t.z.string().url()).nullish()}),Wi={errorSchema:Li,errorToMessage:e=>e.error.message};function Gi(e={}){var t;let n=St((t=e.baseURL)??`https://api.x.ai/v1`),r=()=>({Authorization:`Bearer ${Ke({apiKey:e.apiKey,environmentVariableName:`XAI_API_KEY`,description:`xAI API key`})}`,...e.headers}),i=t=>new Bi(t,{provider:`xai.chat`,baseURL:n,headers:r,generateId:B,fetch:e.fetch}),a=t=>new Ei(t,{provider:`xai.image`,url:({path:e})=>`${n}${e}`,headers:r,fetch:e.fetch,errorStructure:Wi}),o=e=>i(e);return o.languageModel=i,o.chat=i,o.textEmbeddingModel=e=>{throw new be({modelId:e,modelType:`textEmbeddingModel`})},o.imageModel=a,o.image=a,o}var Ki=Gi();function qi(e){if(!e.body)throw Error(`Response body is required`);let t=e.headers.get(la);if(!t||t===`ui-message`)return e.body.pipeThrough(new TextDecoderStream).pipeThrough(new ze).pipeThrough(new TransformStream({async transform(e,t){if(e.data===`[DONE]`)return;let n=await st({text:e.data});n.success?t.enqueue(n.value):t.error(n.error)}}));let r=e=>(0,n.streamText)({model:e,prompt:[{role:`user`,content:[{type:`text`,text:`Hello, world!`}]}]}).toUIMessageStream();switch(t){case`openai-chat`:return r(mi({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`openai-response`:return r(mi({apiKey:`ignored`,fetch:(t,n)=>e}).responses(`fake-model`));case`anthropic`:return r(tn({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`google`:return r(Fn({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`xai`:return r(Gi({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));default:throw Error(`Unsupported response format: ${t}`)}}var Ji=(e,t,n={})=>{let r=`${e}=${t}`;if(e.startsWith(`__Secure-`)&&!n.secure)throw Error(`__Secure- Cookie must have Secure attributes`);if(e.startsWith(`__Host-`)){if(!n.secure)throw Error(`__Host- Cookie must have Secure attributes`);if(n.path!==`/`)throw Error(`__Host- Cookie must have Path attributes with "/"`);if(n.domain)throw Error(`__Host- Cookie must not have Domain attributes`)}if(n&&typeof n.maxAge==`number`&&n.maxAge>=0){if(n.maxAge>3456e4)throw Error(`Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.`);r+=`; Max-Age=${n.maxAge|0}`}if(n.domain&&n.prefix!==`host`&&(r+=`; Domain=${n.domain}`),n.path&&(r+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw Error(`Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.`);r+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly&&(r+=`; HttpOnly`),n.secure&&(r+=`; Secure`),n.sameSite&&(r+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.priority&&(r+=`; Priority=${n.priority.charAt(0).toUpperCase()+n.priority.slice(1)}`),n.partitioned){if(!n.secure)throw Error(`Partitioned Cookie must have Secure attributes`);r+=`; Partitioned`}return r},Yi=(e,t,n)=>(t=encodeURIComponent(t),Ji(e,t,n)),Xi=(e,t)=>(e=e.replace(/\/+$/,``),e+=`/`,t=t.replace(/^\/+/,``),e+t),Zi=(e,t)=>{for(let[n,r]of Object.entries(t)){let t=RegExp(`/:`+n+`(?:{[^/]+})?\\??`);e=e.replace(t,r?`/${r}`:``)}return e},Qi=e=>{let t=new URLSearchParams;for(let[n,r]of Object.entries(e)){if(r===void 0)continue;if(Array.isArray(r))for(let e of r)t.append(n,e);else t.set(n,r)}return t},$i=(e,t)=>{switch(t){case`ws`:return e.replace(/^http/,`ws`);case`http`:return e.replace(/^ws/,`http`)}},ea=e=>/^https?:\/\/[^\/]+?\/index(?=\?|$)/.test(e)?e.replace(/\/index(?=\?|$)/,`/`):e.replace(/\/index(?=\?|$)/,``);function ta(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function na(e,t){if(!ta(e)&&!ta(t))return t;let n={...e};for(let e in t){let r=t[e];ta(n[e])&&ta(r)?n[e]=na(n[e],r):n[e]=r}return n}var ra=(e,t)=>{let n=new Proxy(()=>{},{get(n,r){if(!(typeof r!=`string`||r===`then`))return ra(e,[...t,r])},apply(n,r,i){return e({path:t,args:i})}});return n},ia=class{url;method;queryParams=void 0;pathParams={};rBody;cType=void 0;constructor(e,t){this.url=e,this.method=t}fetch=async(e,t)=>{if(e){if(e.query&&(this.queryParams=Qi(e.query)),e.form){let t=new FormData;for(let[n,r]of Object.entries(e.form))if(Array.isArray(r))for(let e of r)t.append(n,e);else t.append(n,r);this.rBody=t}e.json&&(this.rBody=JSON.stringify(e.json),this.cType=`application/json`),e.param&&(this.pathParams=e.param)}let n=this.method.toUpperCase(),r={...e?.header,...typeof t?.headers==`function`?await t.headers():t?.headers};if(e?.cookie){let t=[];for(let[n,r]of Object.entries(e.cookie))t.push(Yi(n,r,{path:`/`}));r.Cookie=t.join(`,`)}this.cType&&(r[`Content-Type`]=this.cType);let i=new Headers(r??void 0),a=this.url;a=ea(a),a=Zi(a,this.pathParams),this.queryParams&&(a=a+`?`+this.queryParams.toString()),n=this.method.toUpperCase();let o=!(n===`GET`||n===`HEAD`);return(t?.fetch||fetch)(a,{body:o?this.rBody:void 0,method:n,headers:i,...t?.init})}},aa=(e,t)=>ra(function n(r){let i=[...r.path],a=i.slice(-3).reverse();if(a[0]===`toString`)return a[1]===`name`?a[2]||``:n.toString();if(a[0]===`valueOf`)return a[1]===`name`?a[2]||``:n;let o=``;if(/^\$/.test(a[0])){let e=i.pop();e&&(o=e.replace(/^\$/,``))}let s=i.join(`/`),c=Xi(e,s);if(o===`url`){let e=c;return r.args[0]&&(r.args[0].param&&(e=Zi(c,r.args[0].param)),r.args[0].query&&(e=e+`?`+Qi(r.args[0].query).toString())),e=ea(e),new URL(e)}if(o===`ws`){let e=$i(r.args[0]&&r.args[0].param?Zi(c,r.args[0].param):c,`ws`),n=new URL(e),i=r.args[0]?.query;i&&Object.entries(i).forEach(([e,t])=>{Array.isArray(t)?t.forEach(t=>n.searchParams.append(e,t)):n.searchParams.set(e,t)});let a=(...e)=>t?.webSocket!==void 0&&typeof t.webSocket==`function`?t.webSocket(...e):new WebSocket(...e);return a(n.toString())}let l=new ia(c,o);if(o){t??={};let e=na(t,{...r.args[1]});return l.fetch(r.args[0],e)}return l},[]);const oa=`BLINK_API_SERVER_URL`,sa=process.env[oa],ca=aa(sa??``,{fetch:sa?void 0:async()=>{throw console.warn(`Your code is attempting to use the Blink API server, but no API server is configured for this Blink agent.`),Error(`No API server is configured for this Blink agent. External APIs are not available.`)}}),la=`x-blink-stream-response-format`;var ua=class{options;constructor(e){this.options=e}get baseUrl(){return this.options.baseUrl}async sendMessages(e,t){let n=await fetch(`${this.options.baseUrl}/_agent/send-messages`,{method:`POST`,body:JSON.stringify(e),headers:this.options.headers,signal:t?.signal});return n.ok||await this.handleError(n),qi(n)}async experimental_provideCompletions(e){let t=await fetch(`${this.options.baseUrl}/_agent/completions`,{method:`POST`,body:JSON.stringify(e),headers:this.options.headers});if(t.ok||await this.handleError(t),t.headers.get(`content-type`)?.includes(`application/json`)){let e=await t.json();return new ReadableStream({start(t){t.enqueue(e),t.close()}})}if(!t.body)throw Error(`Failed to provide completions (${t.status}): ${t.statusText}`);return da(t)}async capabilities(){let e=await fetch(`${this.options.baseUrl}/_agent/capabilities`,{headers:this.options.headers});e.ok||await this.handleError(e);let t=await e.json();return t}async health(){let e=await fetch(`${this.options.baseUrl}/_agent/health`,{headers:this.options.headers});e.ok||await this.handleError(e)}async handleError(e){let t;try{t=await e.text()}catch{}if(t){let n;try{n=JSON.parse(t)}catch{}throw n?Error(n.error):Error(`Failed to send messages (${e.status}): ${t}`)}throw Error(`Failed to send messages (${e.status}): ${e.statusText}`)}};const da=e=>{let t=new ze;if(!e.body)throw Error(`The stream endpoint did not return a body!`);return e.body.pipeThrough(new TextDecoderStream).pipeTo(t.writable).catch(e=>{}),fa(t.readable)},fa=e=>{let t=e.pipeThrough(new TransformStream({async transform(e,t){let n=await st({text:e.data});if(!n.success){t.error(n.error);return}t.enqueue(n.value)}}));return t};Object.defineProperty(exports,`APICallError`,{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,`APIServerURLEnvironmentVariable`,{enumerable:!0,get:function(){return oa}}),Object.defineProperty(exports,`Client`,{enumerable:!0,get:function(){return ua}}),Object.defineProperty(exports,`EmptyResponseBodyError`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,`EventSourceParserStream`,{enumerable:!0,get:function(){return ze}}),Object.defineProperty(exports,`InvalidArgumentError`,{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,`InvalidPromptError`,{enumerable:!0,get:function(){return O}}),Object.defineProperty(exports,`InvalidResponseDataError`,{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,`JSONParseError`,{enumerable:!0,get:function(){return F}}),Object.defineProperty(exports,`StreamResponseFormatHeader`,{enumerable:!0,get:function(){return la}}),Object.defineProperty(exports,`TooManyEmbeddingValuesForCallError`,{enumerable:!0,get:function(){return Te}}),Object.defineProperty(exports,`TypeValidationError`,{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,`UnsupportedFunctionalityError`,{enumerable:!0,get:function(){return L}}),Object.defineProperty(exports,`client`,{enumerable:!0,get:function(){return ca}}),Object.defineProperty(exports,`convertResponseToUIMessageStream`,{enumerable:!0,get:function(){return qi}}),Object.defineProperty(exports,`createAsyncIterableStream`,{enumerable:!0,get:function(){return Be}}),Object.defineProperty(exports,`streamSSE`,{enumerable:!0,get:function(){return da}});
21
+ ${t}:`]}}function or({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function sr(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`content_filter`:return`content-filter`;case`function_call`:case`tool_calls`:return`tool-calls`;default:return`unknown`}}var cr=t.z.object({echo:t.z.boolean().optional(),logitBias:t.z.record(t.z.string(),t.z.number()).optional(),suffix:t.z.string().optional(),user:t.z.string().optional(),logprobs:t.z.union([t.z.boolean(),t.z.number()]).optional()}),lr=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(`.`)[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,tools:l,toolChoice:u,seed:d,providerOptions:f}){let p=[],m={...await V({provider:`openai`,providerOptions:f,schema:cr}),...await V({provider:this.providerOptionsName,providerOptions:f,schema:cr})};i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),l?.length&&p.push({type:`unsupported-setting`,setting:`tools`}),u!=null&&p.push({type:`unsupported-setting`,setting:`toolChoice`}),c!=null&&c.type!==`text`&&p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format is not supported.`});let{prompt:h,stopSequences:g}=ar({prompt:e}),_=[...g??[],...s??[]];return{args:{model:this.modelId,echo:m.echo,logit_bias:m.logitBias,logprobs:m?.logprobs===!0?0:m?.logprobs===!1?void 0:m?.logprobs,suffix:m.suffix,user:m.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:a,presence_penalty:o,seed:d,prompt:h,stop:_.length>0?_:void 0},warnings:p}}async doGenerate(e){var t,n,r;let{args:i,warnings:a}=await this.getArgs(e),{responseHeaders:o,value:s,rawValue:c}=await H({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:R(this.config.headers(),e.headers),body:i,failedResponseHandler:$,successfulResponseHandler:q(dr),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=s.choices[0],u={openai:{}};return l.logprobs!=null&&(u.openai.logprobs=l.logprobs),{content:[{type:`text`,text:l.text}],usage:{inputTokens:(t=s.usage)?.prompt_tokens,outputTokens:(n=s.usage)?.completion_tokens,totalTokens:(r=s.usage)?.total_tokens},finishReason:sr(l.finish_reason),request:{body:i},response:{...or(s),headers:o,body:c},providerMetadata:u,warnings:a}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:a}=await H({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:R(this.config.headers(),e.headers),body:r,failedResponseHandler:$,successfulResponseHandler:K(fr),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=`unknown`,s={openai:{}},c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=!0;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){o=`error`,n.enqueue({type:`error`,error:t.error});return}let r=t.value;if(`error`in r){o=`error`,n.enqueue({type:`error`,error:r.error});return}l&&(l=!1,n.enqueue({type:`response-metadata`,...or(r)}),n.enqueue({type:`text-start`,id:`0`})),r.usage!=null&&(c.inputTokens=r.usage.prompt_tokens,c.outputTokens=r.usage.completion_tokens,c.totalTokens=r.usage.total_tokens);let i=r.choices[0];i?.finish_reason!=null&&(o=sr(i.finish_reason)),i?.logprobs!=null&&(s.openai.logprobs=i.logprobs),i?.text!=null&&i.text.length>0&&n.enqueue({type:`text-delta`,id:`0`,delta:i.text})},flush(e){l||e.enqueue({type:`text-end`,id:`0`}),e.enqueue({type:`finish`,finishReason:o,providerMetadata:s,usage:c})}})),request:{body:r},response:{headers:i}}}},ur=t.z.object({prompt_tokens:t.z.number(),completion_tokens:t.z.number(),total_tokens:t.z.number()}),dr=t.z.object({id:t.z.string().nullish(),created:t.z.number().nullish(),model:t.z.string().nullish(),choices:t.z.array(t.z.object({text:t.z.string(),finish_reason:t.z.string(),logprobs:t.z.object({tokens:t.z.array(t.z.string()),token_logprobs:t.z.array(t.z.number()),top_logprobs:t.z.array(t.z.record(t.z.string(),t.z.number())).nullish()}).nullish()})),usage:ur.nullish()}),fr=t.z.union([t.z.object({id:t.z.string().nullish(),created:t.z.number().nullish(),model:t.z.string().nullish(),choices:t.z.array(t.z.object({text:t.z.string(),finish_reason:t.z.string().nullish(),index:t.z.number(),logprobs:t.z.object({tokens:t.z.array(t.z.string()),token_logprobs:t.z.array(t.z.number()),top_logprobs:t.z.array(t.z.record(t.z.string(),t.z.number())).nullish()}).nullish()})),usage:ur.nullish()}),Ln]),pr=t.z.object({dimensions:t.z.number().optional(),user:t.z.string().optional()}),mr=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){var i;if(e.length>this.maxEmbeddingsPerCall)throw new Te({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let a=(i=await V({provider:`openai`,providerOptions:r,schema:pr}))??{},{responseHeaders:o,value:s,rawValue:c}=await H({url:this.config.url({path:`/embeddings`,modelId:this.modelId}),headers:R(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:`float`,dimensions:a.dimensions,user:a.user},failedResponseHandler:$,successfulResponseHandler:q(hr),abortSignal:n,fetch:this.config.fetch});return{embeddings:s.data.map(e=>e.embedding),usage:s.usage?{tokens:s.usage.prompt_tokens}:void 0,response:{headers:o,body:c}}}},hr=t.z.object({data:t.z.array(t.z.object({embedding:t.z.array(t.z.number())})),usage:t.z.object({prompt_tokens:t.z.number()}).nullish()}),gr={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},_r=new Set([`gpt-image-1`]),vr=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get maxImagesPerCall(){var e;return(e=gr[this.modelId])??1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:a,headers:o,abortSignal:s}){var c,l,u,d;let f=[];r!=null&&f.push({type:`unsupported-setting`,setting:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&f.push({type:`unsupported-setting`,setting:`seed`});let p=(u=(l=(c=this.config._internal)?.currentDate)?.call(c))??new Date,{value:m,responseHeaders:h}=await H({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:R(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...(d=a.openai)??{},..._r.has(this.modelId)?{}:{response_format:`b64_json`}},failedResponseHandler:$,successfulResponseHandler:q(yr),abortSignal:s,fetch:this.config.fetch});return{images:m.data.map(e=>e.b64_json),warnings:f,response:{timestamp:p,modelId:this.modelId,headers:h},providerMetadata:{openai:{images:m.data.map(e=>e.revised_prompt?{revisedPrompt:e.revised_prompt}:null)}}}}},yr=t.z.object({data:t.z.array(t.z.object({b64_json:t.z.string(),revised_prompt:t.z.string().optional()}))}),br=t.z.object({container:t.z.union([t.z.string(),t.z.object({fileIds:t.z.array(t.z.string()).optional()})]).optional()}),xr=U({id:`openai.code_interpreter`,name:`code_interpreter`,inputSchema:t.z.object({})}),Sr=(e={})=>xr(e),Cr=t.z.object({filters:t.z.object({allowedDomains:t.z.array(t.z.string()).optional()}).optional(),searchContextSize:t.z.enum([`low`,`medium`,`high`]).optional(),userLocation:t.z.object({type:t.z.literal(`approximate`),country:t.z.string().optional(),city:t.z.string().optional(),region:t.z.string().optional(),timezone:t.z.string().optional()}).optional()}),wr=U({id:`openai.web_search`,name:`web_search`,inputSchema:t.z.object({action:t.z.discriminatedUnion(`type`,[t.z.object({type:t.z.literal(`search`),query:t.z.string().nullish()}),t.z.object({type:t.z.literal(`open_page`),url:t.z.string()}),t.z.object({type:t.z.literal(`find`),url:t.z.string(),pattern:t.z.string()})]).nullish()})}),Tr=(e={})=>wr(e),Er={codeInterpreter:Sr,fileSearch:Kn,webSearchPreview:Jn,webSearch:Tr};function Dr(e,t){return t?t.some(t=>e.startsWith(t)):!1}async function Or({prompt:e,systemMessageMode:t,fileIdPrefixes:n}){var r,i,a,o,s,c;let l=[],u=[];for(let{role:d,content:f}of e)switch(d){case`system`:switch(t){case`system`:l.push({role:`system`,content:f});break;case`developer`:l.push({role:`developer`,content:f});break;case`remove`:u.push({type:`other`,message:`system messages are removed for this model`});break;default:{let e=t;throw Error(`Unsupported system message mode: ${e}`)}}break;case`user`:l.push({role:`user`,content:f.map((e,t)=>{var r,i,a;switch(e.type){case`text`:return{type:`input_text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`input_image`,...e.data instanceof URL?{image_url:e.data.toString()}:typeof e.data==`string`&&Dr(e.data,n)?{file_id:e.data}:{image_url:`data:${t};base64,${J(e.data)}`},detail:(i=(r=e.providerOptions)?.openai)?.imageDetail}}else if(e.mediaType===`application/pdf`)return e.data instanceof URL?{type:`input_file`,file_url:e.data.toString()}:{type:`input_file`,...typeof e.data==`string`&&Dr(e.data,n)?{file_id:e.data}:{filename:(a=e.filename)??`part-${t}.pdf`,file_data:`data:application/pdf;base64,${J(e.data)}`}};else throw new L({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e={};for(let t of f)switch(t.type){case`text`:l.push({role:`assistant`,content:[{type:`output_text`,text:t.text}],id:(a=(i=(r=t.providerOptions)?.openai)?.itemId)??void 0});break;case`tool-call`:if(t.providerExecuted)break;l.push({type:`function_call`,call_id:t.toolCallId,name:t.toolName,arguments:JSON.stringify(t.input),id:(c=(s=(o=t.providerOptions)?.openai)?.itemId)??void 0});break;case`tool-result`:u.push({type:`other`,message:`tool result parts in assistant messages are not supported for OpenAI responses`});break;case`reasoning`:{let n=await V({provider:`openai`,providerOptions:t.providerOptions,schema:kr}),r=n?.itemId;if(r!=null){let i=e[r],a=[];t.text.length>0?a.push({type:`summary_text`,text:t.text}):i!==void 0&&u.push({type:`other`,message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(t)}.`}),i===void 0?(e[r]={type:`reasoning`,id:r,encrypted_content:n?.reasoningEncryptedContent,summary:a},l.push(e[r])):i.summary.push(...a)}else u.push({type:`other`,message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(t)}.`});break}}break}case`tool`:for(let e of f){let t=e.output,n;switch(t.type){case`text`:case`error-text`:n=t.value;break;case`content`:case`json`:case`error-json`:n=JSON.stringify(t.value);break}l.push({type:`function_call_output`,call_id:e.toolCallId,output:n})}break;default:{let e=d;throw Error(`Unsupported role: ${e}`)}}return{messages:l,warnings:u}}var kr=t.z.object({itemId:t.z.string().nullish(),reasoningEncryptedContent:t.z.string().nullish()});function Ar({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?`tool-calls`:`stop`;case`max_output_tokens`:return`length`;case`content_filter`:return`content-filter`;default:return t?`tool-calls`:`unknown`}}function jr({tools:e,toolChoice:t,strictJsonSchema:n}){e=e?.length?e:void 0;let r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};let i=[];for(let t of e)switch(t.type){case`function`:i.push({type:`function`,name:t.name,description:t.description,parameters:t.inputSchema,strict:n});break;case`provider-defined`:switch(t.id){case`openai.file_search`:{let e=Gn.parse(t.args);i.push({type:`file_search`,vector_store_ids:e.vectorStoreIds,max_num_results:e.maxNumResults,ranking_options:e.ranking?{ranker:e.ranking.ranker}:void 0,filters:e.filters});break}case`openai.web_search_preview`:{let e=qn.parse(t.args);i.push({type:`web_search_preview`,search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.web_search`:{let e=Cr.parse(t.args);i.push({type:`web_search`,filters:e.filters==null?void 0:{allowed_domains:e.filters.allowedDomains},search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.code_interpreter`:{let e=br.parse(t.args);i.push({type:`code_interpreter`,container:e.container==null?{type:`auto`,file_ids:void 0}:typeof e.container==`string`?e.container:{type:`auto`,file_ids:e.container.fileIds}});break}default:r.push({type:`unsupported-tool`,tool:t});break}break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:i,toolChoice:void 0,toolWarnings:r};let a=t.type;switch(a){case`auto`:case`none`:case`required`:return{tools:i,toolChoice:a,toolWarnings:r};case`tool`:return{tools:i,toolChoice:t.toolName===`code_interpreter`||t.toolName===`file_search`||t.toolName===`web_search_preview`||t.toolName===`web_search`?{type:t.toolName}:{type:`function`,name:t.toolName},toolWarnings:r};default:{let e=a;throw new L({functionality:`tool choice type: ${e}`})}}}var Mr=t.z.object({type:t.z.literal(`web_search_call`),id:t.z.string(),status:t.z.string(),action:t.z.discriminatedUnion(`type`,[t.z.object({type:t.z.literal(`search`),query:t.z.string().nullish()}),t.z.object({type:t.z.literal(`open_page`),url:t.z.string()}),t.z.object({type:t.z.literal(`find`),url:t.z.string(),pattern:t.z.string()})]).nullish()}),Nr=20,Pr=t.z.array(t.z.object({token:t.z.string(),logprob:t.z.number(),top_logprobs:t.z.array(t.z.object({token:t.z.string(),logprob:t.z.number()}))})),Fr=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:i,presencePenalty:a,frequencyPenalty:o,seed:s,prompt:c,providerOptions:l,tools:u,toolChoice:d,responseFormat:f}){var p,m,h;let g=[],_=oi(this.modelId);i!=null&&g.push({type:`unsupported-setting`,setting:`topK`}),s!=null&&g.push({type:`unsupported-setting`,setting:`seed`}),a!=null&&g.push({type:`unsupported-setting`,setting:`presencePenalty`}),o!=null&&g.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),n!=null&&g.push({type:`unsupported-setting`,setting:`stopSequences`});let{messages:v,warnings:y}=await Or({prompt:c,systemMessageMode:_.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes});g.push(...y);let b=await V({provider:`openai`,providerOptions:l,schema:si}),x=(p=b?.strictJsonSchema)??!1,S=b?.include,C=typeof b?.logprobs==`number`?b?.logprobs:b?.logprobs===!0?Nr:void 0;S=C?Array.isArray(S)?[...S,`message.output_text.logprobs`]:[`message.output_text.logprobs`]:S;let w=(m=u?.find(e=>e.type===`provider-defined`&&(e.id===`openai.web_search`||e.id===`openai.web_search_preview`)))?.name;S=w?Array.isArray(S)?[...S,`web_search_call.action.sources`]:[`web_search_call.action.sources`]:S;let T={model:this.modelId,input:v,temperature:t,top_p:r,max_output_tokens:e,...(f?.type===`json`||b?.textVerbosity)&&{text:{...f?.type===`json`&&{format:f.schema==null?{type:`json_object`}:{type:`json_schema`,strict:x,name:(h=f.name)??`response`,description:f.description,schema:f.schema}},...b?.textVerbosity&&{verbosity:b.textVerbosity}}},metadata:b?.metadata,parallel_tool_calls:b?.parallelToolCalls,previous_response_id:b?.previousResponseId,store:b?.store,user:b?.user,instructions:b?.instructions,service_tier:b?.serviceTier,include:S,prompt_cache_key:b?.promptCacheKey,safety_identifier:b?.safetyIdentifier,top_logprobs:C,..._.isReasoningModel&&(b?.reasoningEffort!=null||b?.reasoningSummary!=null)&&{reasoning:{...b?.reasoningEffort!=null&&{effort:b.reasoningEffort},...b?.reasoningSummary!=null&&{summary:b.reasoningSummary}}},..._.requiredAutoTruncation&&{truncation:`auto`}};_.isReasoningModel?(T.temperature!=null&&(T.temperature=void 0,g.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for reasoning models`})),T.top_p!=null&&(T.top_p=void 0,g.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported for reasoning models`}))):(b?.reasoningEffort!=null&&g.push({type:`unsupported-setting`,setting:`reasoningEffort`,details:`reasoningEffort is not supported for non-reasoning models`}),b?.reasoningSummary!=null&&g.push({type:`unsupported-setting`,setting:`reasoningSummary`,details:`reasoningSummary is not supported for non-reasoning models`})),b?.serviceTier===`flex`&&!_.supportsFlexProcessing&&(g.push({type:`unsupported-setting`,setting:`serviceTier`,details:`flex processing is only available for o3, o4-mini, and gpt-5 models`}),delete T.service_tier),b?.serviceTier===`priority`&&!_.supportsPriorityProcessing&&(g.push({type:`unsupported-setting`,setting:`serviceTier`,details:`priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported`}),delete T.service_tier);let{tools:E,toolChoice:D,toolWarnings:O}=jr({tools:u,toolChoice:d,strictJsonSchema:x});return{webSearchToolName:w,args:{...T,tools:E,tool_choice:D},warnings:[...g,...O]}}async doGenerate(e){var n,r,i,a,o,s,c,l,u,d,p,m,h,g,_,v,y;let{args:b,warnings:x,webSearchToolName:S}=await this.getArgs(e),C=this.config.url({path:`/responses`,modelId:this.modelId}),{responseHeaders:w,value:T,rawValue:E}=await H({url:C,headers:R(this.config.headers(),e.headers),body:b,failedResponseHandler:$,successfulResponseHandler:q(t.z.object({id:t.z.string(),created_at:t.z.number(),error:t.z.object({code:t.z.string(),message:t.z.string()}).nullish(),model:t.z.string(),output:t.z.array(t.z.discriminatedUnion(`type`,[t.z.object({type:t.z.literal(`message`),role:t.z.literal(`assistant`),id:t.z.string(),content:t.z.array(t.z.object({type:t.z.literal(`output_text`),text:t.z.string(),logprobs:Pr.nullish(),annotations:t.z.array(t.z.discriminatedUnion(`type`,[t.z.object({type:t.z.literal(`url_citation`),start_index:t.z.number(),end_index:t.z.number(),url:t.z.string(),title:t.z.string()}),t.z.object({type:t.z.literal(`file_citation`),file_id:t.z.string(),filename:t.z.string().nullish(),index:t.z.number().nullish(),start_index:t.z.number().nullish(),end_index:t.z.number().nullish(),quote:t.z.string().nullish()}),t.z.object({type:t.z.literal(`container_file_citation`)})]))}))}),t.z.object({type:t.z.literal(`code_interpreter_call`)}),t.z.object({type:t.z.literal(`function_call`),call_id:t.z.string(),name:t.z.string(),arguments:t.z.string(),id:t.z.string()}),Mr,t.z.object({type:t.z.literal(`computer_call`),id:t.z.string(),status:t.z.string().optional()}),t.z.object({type:t.z.literal(`file_search_call`),id:t.z.string(),status:t.z.string().optional(),queries:t.z.array(t.z.string()).nullish(),results:t.z.array(t.z.object({attributes:t.z.object({file_id:t.z.string(),filename:t.z.string(),score:t.z.number(),text:t.z.string()})})).nullish()}),t.z.object({type:t.z.literal(`reasoning`),id:t.z.string(),encrypted_content:t.z.string().nullish(),summary:t.z.array(t.z.object({type:t.z.literal(`summary_text`),text:t.z.string()}))})])),service_tier:t.z.string().nullish(),incomplete_details:t.z.object({reason:t.z.string()}).nullable(),usage:Ir})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(T.error)throw new f({message:T.error.message,url:C,requestBodyValues:b,statusCode:400,responseHeaders:w,responseBody:E,isRetryable:!1});let D=[],O=[],k=!1;for(let t of T.output)switch(t.type){case`reasoning`:t.summary.length===0&&t.summary.push({type:`summary_text`,text:``});for(let e of t.summary)D.push({type:`reasoning`,text:e.text,providerMetadata:{openai:{itemId:t.id,reasoningEncryptedContent:(n=t.encrypted_content)??null}}});break;case`message`:for(let n of t.content){(i=(r=e.providerOptions)?.openai)?.logprobs&&n.logprobs&&O.push(n.logprobs),D.push({type:`text`,text:n.text,providerMetadata:{openai:{itemId:t.id}}});for(let e of n.annotations)e.type===`url_citation`?D.push({type:`source`,sourceType:`url`,id:(s=(o=(a=this.config).generateId)?.call(a))??B(),url:e.url,title:e.title}):e.type===`file_citation`&&D.push({type:`source`,sourceType:`document`,id:(u=(l=(c=this.config).generateId)?.call(c))??B(),mediaType:`text/plain`,title:(p=(d=e.quote)??e.filename)??`Document`,filename:(m=e.filename)??e.file_id})}break;case`function_call`:k=!0,D.push({type:`tool-call`,toolCallId:t.call_id,toolName:t.name,input:t.arguments,providerMetadata:{openai:{itemId:t.id}}});break;case`web_search_call`:D.push({type:`tool-call`,toolCallId:t.id,toolName:S??`web_search`,input:JSON.stringify({action:t.action}),providerExecuted:!0}),D.push({type:`tool-result`,toolCallId:t.id,toolName:S??`web_search`,result:{status:t.status},providerExecuted:!0});break;case`computer_call`:D.push({type:`tool-call`,toolCallId:t.id,toolName:`computer_use`,input:``,providerExecuted:!0}),D.push({type:`tool-result`,toolCallId:t.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:t.status||`completed`},providerExecuted:!0});break;case`file_search_call`:D.push({type:`tool-call`,toolCallId:t.id,toolName:`file_search`,input:``,providerExecuted:!0}),D.push({type:`tool-result`,toolCallId:t.id,toolName:`file_search`,result:{type:`file_search_tool_result`,status:t.status||`completed`,...t.queries&&{queries:t.queries},...t.results&&{results:t.results}},providerExecuted:!0});break}let A={openai:{responseId:T.id}};return O.length>0&&(A.openai.logprobs=O),typeof T.service_tier==`string`&&(A.openai.serviceTier=T.service_tier),{content:D,finishReason:Ar({finishReason:(h=T.incomplete_details)?.reason,hasFunctionCall:k}),usage:{inputTokens:T.usage.input_tokens,outputTokens:T.usage.output_tokens,totalTokens:T.usage.input_tokens+T.usage.output_tokens,reasoningTokens:(_=(g=T.usage.output_tokens_details)?.reasoning_tokens)??void 0,cachedInputTokens:(y=(v=T.usage.input_tokens_details)?.cached_tokens)??void 0},request:{body:b},response:{id:T.id,timestamp:new Date(T.created_at*1e3),modelId:T.model,headers:w,body:E},providerMetadata:A,warnings:x}}async doStream(e){let{args:t,warnings:n,webSearchToolName:r}=await this.getArgs(e),{responseHeaders:i,value:a}=await H({url:this.config.url({path:`/responses`,modelId:this.modelId}),headers:R(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:$,successfulResponseHandler:K(qr),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=this,s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=[],u=null,d={},f=!1,p={},m;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){var i,a,h,g,_,v,y,b,x,S,C,w,T,E,D,O,k,A,ee,te,j;if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){s=`error`,n.enqueue({type:`error`,error:t.error});return}let M=t.value;if(ei(M))M.item.type===`function_call`?(d[M.output_index]={toolName:M.item.name,toolCallId:M.item.call_id},n.enqueue({type:`tool-input-start`,id:M.item.call_id,toolName:M.item.name})):M.item.type===`web_search_call`?(d[M.output_index]={toolName:r??`web_search`,toolCallId:M.item.id},n.enqueue({type:`tool-input-start`,id:M.item.id,toolName:r??`web_search`})):M.item.type===`computer_call`?(d[M.output_index]={toolName:`computer_use`,toolCallId:M.item.id},n.enqueue({type:`tool-input-start`,id:M.item.id,toolName:`computer_use`})):M.item.type===`file_search_call`?(d[M.output_index]={toolName:`file_search`,toolCallId:M.item.id},n.enqueue({type:`tool-input-start`,id:M.item.id,toolName:`file_search`})):M.item.type===`message`?n.enqueue({type:`text-start`,id:M.item.id,providerMetadata:{openai:{itemId:M.item.id}}}):ti(M)&&(p[M.item.id]={encryptedContent:M.item.encrypted_content,summaryParts:[0]},n.enqueue({type:`reasoning-start`,id:`${M.item.id}:0`,providerMetadata:{openai:{itemId:M.item.id,reasoningEncryptedContent:(i=M.item.encrypted_content)??null}}}));else if(Yr(M)){if(M.item.type===`function_call`)d[M.output_index]=void 0,f=!0,n.enqueue({type:`tool-input-end`,id:M.item.call_id}),n.enqueue({type:`tool-call`,toolCallId:M.item.call_id,toolName:M.item.name,input:M.item.arguments,providerMetadata:{openai:{itemId:M.item.id}}});else if(M.item.type===`web_search_call`)d[M.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:M.item.id}),n.enqueue({type:`tool-call`,toolCallId:M.item.id,toolName:`web_search`,input:JSON.stringify({action:M.item.action}),providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:M.item.id,toolName:`web_search`,result:{status:M.item.status},providerExecuted:!0});else if(M.item.type===`computer_call`)d[M.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:M.item.id}),n.enqueue({type:`tool-call`,toolCallId:M.item.id,toolName:`computer_use`,input:``,providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:M.item.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:M.item.status||`completed`},providerExecuted:!0});else if(M.item.type===`file_search_call`)d[M.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:M.item.id}),n.enqueue({type:`tool-call`,toolCallId:M.item.id,toolName:`file_search`,input:``,providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:M.item.id,toolName:`file_search`,result:{type:`file_search_tool_result`,status:M.item.status||`completed`,...M.item.queries&&{queries:M.item.queries},...M.item.results&&{results:M.item.results}},providerExecuted:!0});else if(M.item.type===`message`)n.enqueue({type:`text-end`,id:M.item.id});else if(Xr(M)){let e=p[M.item.id];for(let t of e.summaryParts)n.enqueue({type:`reasoning-end`,id:`${M.item.id}:${t}`,providerMetadata:{openai:{itemId:M.item.id,reasoningEncryptedContent:(a=M.item.encrypted_content)??null}}});delete p[M.item.id]}}else if($r(M)){let e=d[M.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:M.delta})}else Qr(M)?(u=M.response.id,n.enqueue({type:`response-metadata`,id:M.response.id,timestamp:new Date(M.response.created_at*1e3),modelId:M.response.model})):Jr(M)?(n.enqueue({type:`text-delta`,id:M.item_id,delta:M.delta}),(g=(h=e.providerOptions)?.openai)?.logprobs&&M.logprobs&&l.push(M.logprobs)):ri(M)?M.summary_index>0&&((_=p[M.item_id])==null||_.summaryParts.push(M.summary_index),n.enqueue({type:`reasoning-start`,id:`${M.item_id}:${M.summary_index}`,providerMetadata:{openai:{itemId:M.item_id,reasoningEncryptedContent:(y=(v=p[M.item_id])?.encryptedContent)??null}}})):ii(M)?n.enqueue({type:`reasoning-delta`,id:`${M.item_id}:${M.summary_index}`,delta:M.delta,providerMetadata:{openai:{itemId:M.item_id}}}):Zr(M)?(s=Ar({finishReason:(b=M.response.incomplete_details)?.reason,hasFunctionCall:f}),c.inputTokens=M.response.usage.input_tokens,c.outputTokens=M.response.usage.output_tokens,c.totalTokens=M.response.usage.input_tokens+M.response.usage.output_tokens,c.reasoningTokens=(S=(x=M.response.usage.output_tokens_details)?.reasoning_tokens)??void 0,c.cachedInputTokens=(w=(C=M.response.usage.input_tokens_details)?.cached_tokens)??void 0,typeof M.response.service_tier==`string`&&(m=M.response.service_tier)):ni(M)?M.annotation.type===`url_citation`?n.enqueue({type:`source`,sourceType:`url`,id:(D=(E=(T=o.config).generateId)?.call(T))??B(),url:M.annotation.url,title:M.annotation.title}):M.annotation.type===`file_citation`&&n.enqueue({type:`source`,sourceType:`document`,id:(A=(k=(O=o.config).generateId)?.call(O))??B(),mediaType:`text/plain`,title:(te=(ee=M.annotation.quote)??M.annotation.filename)??`Document`,filename:(j=M.annotation.filename)??M.annotation.file_id}):ai(M)&&n.enqueue({type:`error`,error:M})},flush(e){let t={openai:{responseId:u}};l.length>0&&(t.openai.logprobs=l),m!==void 0&&(t.openai.serviceTier=m),e.enqueue({type:`finish`,finishReason:s,usage:c,providerMetadata:t})}})),request:{body:t},response:{headers:i}}}},Ir=t.z.object({input_tokens:t.z.number(),input_tokens_details:t.z.object({cached_tokens:t.z.number().nullish()}).nullish(),output_tokens:t.z.number(),output_tokens_details:t.z.object({reasoning_tokens:t.z.number().nullish()}).nullish()}),Lr=t.z.object({type:t.z.literal(`response.output_text.delta`),item_id:t.z.string(),delta:t.z.string(),logprobs:Pr.nullish()}),Rr=t.z.object({type:t.z.literal(`error`),code:t.z.string(),message:t.z.string(),param:t.z.string().nullish(),sequence_number:t.z.number()}),zr=t.z.object({type:t.z.enum([`response.completed`,`response.incomplete`]),response:t.z.object({incomplete_details:t.z.object({reason:t.z.string()}).nullish(),usage:Ir,service_tier:t.z.string().nullish()})}),Br=t.z.object({type:t.z.literal(`response.created`),response:t.z.object({id:t.z.string(),created_at:t.z.number(),model:t.z.string(),service_tier:t.z.string().nullish()})}),Vr=t.z.object({type:t.z.literal(`response.output_item.added`),output_index:t.z.number(),item:t.z.discriminatedUnion(`type`,[t.z.object({type:t.z.literal(`message`),id:t.z.string()}),t.z.object({type:t.z.literal(`reasoning`),id:t.z.string(),encrypted_content:t.z.string().nullish()}),t.z.object({type:t.z.literal(`function_call`),id:t.z.string(),call_id:t.z.string(),name:t.z.string(),arguments:t.z.string()}),t.z.object({type:t.z.literal(`web_search_call`),id:t.z.string(),status:t.z.string(),action:t.z.object({type:t.z.literal(`search`),query:t.z.string().optional()}).nullish()}),t.z.object({type:t.z.literal(`computer_call`),id:t.z.string(),status:t.z.string()}),t.z.object({type:t.z.literal(`file_search_call`),id:t.z.string(),status:t.z.string(),queries:t.z.array(t.z.string()).nullish(),results:t.z.array(t.z.object({attributes:t.z.object({file_id:t.z.string(),filename:t.z.string(),score:t.z.number(),text:t.z.string()})})).optional()})])}),Hr=t.z.object({type:t.z.literal(`response.output_item.done`),output_index:t.z.number(),item:t.z.discriminatedUnion(`type`,[t.z.object({type:t.z.literal(`message`),id:t.z.string()}),t.z.object({type:t.z.literal(`reasoning`),id:t.z.string(),encrypted_content:t.z.string().nullish()}),t.z.object({type:t.z.literal(`function_call`),id:t.z.string(),call_id:t.z.string(),name:t.z.string(),arguments:t.z.string(),status:t.z.literal(`completed`)}),Mr,t.z.object({type:t.z.literal(`computer_call`),id:t.z.string(),status:t.z.literal(`completed`)}),t.z.object({type:t.z.literal(`file_search_call`),id:t.z.string(),status:t.z.literal(`completed`),queries:t.z.array(t.z.string()).nullish(),results:t.z.array(t.z.object({attributes:t.z.object({file_id:t.z.string(),filename:t.z.string(),score:t.z.number(),text:t.z.string()})})).nullish()})])}),Ur=t.z.object({type:t.z.literal(`response.function_call_arguments.delta`),item_id:t.z.string(),output_index:t.z.number(),delta:t.z.string()}),Wr=t.z.object({type:t.z.literal(`response.output_text.annotation.added`),annotation:t.z.discriminatedUnion(`type`,[t.z.object({type:t.z.literal(`url_citation`),url:t.z.string(),title:t.z.string()}),t.z.object({type:t.z.literal(`file_citation`),file_id:t.z.string(),filename:t.z.string().nullish(),index:t.z.number().nullish(),start_index:t.z.number().nullish(),end_index:t.z.number().nullish(),quote:t.z.string().nullish()})])}),Gr=t.z.object({type:t.z.literal(`response.reasoning_summary_part.added`),item_id:t.z.string(),summary_index:t.z.number()}),Kr=t.z.object({type:t.z.literal(`response.reasoning_summary_text.delta`),item_id:t.z.string(),summary_index:t.z.number(),delta:t.z.string()}),qr=t.z.union([Lr,zr,Br,Vr,Hr,Ur,Wr,Gr,Kr,Rr,t.z.object({type:t.z.string()}).loose()]);function Jr(e){return e.type===`response.output_text.delta`}function Yr(e){return e.type===`response.output_item.done`}function Xr(e){return Yr(e)&&e.item.type===`reasoning`}function Zr(e){return e.type===`response.completed`||e.type===`response.incomplete`}function Qr(e){return e.type===`response.created`}function $r(e){return e.type===`response.function_call_arguments.delta`}function ei(e){return e.type===`response.output_item.added`}function ti(e){return ei(e)&&e.item.type===`reasoning`}function ni(e){return e.type===`response.output_text.annotation.added`}function ri(e){return e.type===`response.reasoning_summary_part.added`}function ii(e){return e.type===`response.reasoning_summary_text.delta`}function ai(e){return e.type===`error`}function oi(e){let t=e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`),n=e.startsWith(`gpt-4`)||e.startsWith(`gpt-5-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-nano`)&&!e.startsWith(`gpt-5-chat`)||e.startsWith(`o3`)||e.startsWith(`o4-mini`),r={requiredAutoTruncation:!1,systemMessageMode:`system`,supportsFlexProcessing:t,supportsPriorityProcessing:n};return e.startsWith(`gpt-5-chat`)?{...r,isReasoningModel:!1}:e.startsWith(`o`)||e.startsWith(`gpt-5`)||e.startsWith(`codex-`)||e.startsWith(`computer-use`)?e.startsWith(`o1-mini`)||e.startsWith(`o1-preview`)?{...r,isReasoningModel:!0,systemMessageMode:`remove`}:{...r,isReasoningModel:!0,systemMessageMode:`developer`}:{...r,isReasoningModel:!1}}var si=t.z.object({metadata:t.z.any().nullish(),parallelToolCalls:t.z.boolean().nullish(),previousResponseId:t.z.string().nullish(),store:t.z.boolean().nullish(),user:t.z.string().nullish(),reasoningEffort:t.z.string().nullish(),strictJsonSchema:t.z.boolean().nullish(),instructions:t.z.string().nullish(),reasoningSummary:t.z.string().nullish(),serviceTier:t.z.enum([`auto`,`flex`,`priority`]).nullish(),include:t.z.array(t.z.enum([`reasoning.encrypted_content`,`file_search_call.results`,`message.output_text.logprobs`])).nullish(),textVerbosity:t.z.enum([`low`,`medium`,`high`]).nullish(),promptCacheKey:t.z.string().nullish(),safetyIdentifier:t.z.string().nullish(),logprobs:t.z.union([t.z.boolean(),t.z.number().min(1).max(Nr)]).optional()}),ci=t.z.object({instructions:t.z.string().nullish(),speed:t.z.number().min(.25).max(4).default(1).nullish()}),li=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get provider(){return this.config.provider}async getArgs({text:e,voice:t=`alloy`,outputFormat:n=`mp3`,speed:r,instructions:i,language:a,providerOptions:o}){let s=[],c=await V({provider:`openai`,providerOptions:o,schema:ci}),l={model:this.modelId,input:e,voice:t,response_format:`mp3`,speed:r,instructions:i};if(n&&([`mp3`,`opus`,`aac`,`flac`,`wav`,`pcm`].includes(n)?l.response_format=n:s.push({type:`unsupported-setting`,setting:`outputFormat`,details:`Unsupported output format: ${n}. Using mp3 instead.`})),c){let e={};for(let t in e){let n=e[t];n!==void 0&&(l[t]=n)}}return a&&s.push({type:`unsupported-setting`,setting:`language`,details:`OpenAI speech models do not support language selection. Language parameter "${a}" was ignored.`}),{requestBody:l,warnings:s}}async doGenerate(e){var t,n,r;let i=(r=(n=(t=this.config._internal)?.currentDate)?.call(t))??new Date,{requestBody:a,warnings:o}=await this.getArgs(e),{value:s,responseHeaders:c,rawValue:l}=await H({url:this.config.url({path:`/audio/speech`,modelId:this.modelId}),headers:R(this.config.headers(),e.headers),body:a,failedResponseHandler:$,successfulResponseHandler:ht(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:s,warnings:o,request:{body:JSON.stringify(a)},response:{timestamp:i,modelId:this.modelId,headers:c,body:l}}}},ui=t.z.object({include:t.z.array(t.z.string()).optional(),language:t.z.string().optional(),prompt:t.z.string().optional(),temperature:t.z.number().min(0).max(1).default(0).optional(),timestampGranularities:t.z.array(t.z.enum([`word`,`segment`])).default([`segment`]).optional()}),di={afrikaans:`af`,arabic:`ar`,armenian:`hy`,azerbaijani:`az`,belarusian:`be`,bosnian:`bs`,bulgarian:`bg`,catalan:`ca`,chinese:`zh`,croatian:`hr`,czech:`cs`,danish:`da`,dutch:`nl`,english:`en`,estonian:`et`,finnish:`fi`,french:`fr`,galician:`gl`,german:`de`,greek:`el`,hebrew:`he`,hindi:`hi`,hungarian:`hu`,icelandic:`is`,indonesian:`id`,italian:`it`,japanese:`ja`,kannada:`kn`,kazakh:`kk`,korean:`ko`,latvian:`lv`,lithuanian:`lt`,macedonian:`mk`,malay:`ms`,marathi:`mr`,maori:`mi`,nepali:`ne`,norwegian:`no`,persian:`fa`,polish:`pl`,portuguese:`pt`,romanian:`ro`,russian:`ru`,serbian:`sr`,slovak:`sk`,slovenian:`sl`,spanish:`es`,swahili:`sw`,swedish:`sv`,tagalog:`tl`,tamil:`ta`,thai:`th`,turkish:`tr`,ukrainian:`uk`,urdu:`ur`,vietnamese:`vi`,welsh:`cy`},fi=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:n}){let r=[],i=await V({provider:`openai`,providerOptions:n,schema:ui}),a=new FormData,o=e instanceof Uint8Array?new Blob([e]):new Blob([bt(e)]);a.append(`model`,this.modelId);let s=qe(t);if(a.append(`file`,new File([o],`audio`,{type:t}),`audio.${s}`),i){let e={include:i.include,language:i.language,prompt:i.prompt,response_format:[`gpt-4o-transcribe`,`gpt-4o-mini-transcribe`].includes(this.modelId)?`json`:`verbose_json`,temperature:i.temperature,timestamp_granularities:i.timestampGranularities};for(let[t,n]of Object.entries(e))if(n!=null)if(Array.isArray(n))for(let e of n)a.append(`${t}[]`,String(e));else a.append(t,String(n))}return{formData:a,warnings:r}}async doGenerate(e){var t,n,r,i,a,o,s,c;let l=(r=(n=(t=this.config._internal)?.currentDate)?.call(t))??new Date,{formData:u,warnings:d}=await this.getArgs(e),{value:f,responseHeaders:p,rawValue:m}=await dt({url:this.config.url({path:`/audio/transcriptions`,modelId:this.modelId}),headers:R(this.config.headers(),e.headers),formData:u,failedResponseHandler:$,successfulResponseHandler:q(pi),abortSignal:e.abortSignal,fetch:this.config.fetch}),h=f.language!=null&&f.language in di?di[f.language]:void 0;return{text:f.text,segments:(s=(o=(i=f.segments)?.map(e=>({text:e.text,startSecond:e.start,endSecond:e.end})))??(a=f.words)?.map(e=>({text:e.word,startSecond:e.start,endSecond:e.end})))??[],language:h,durationInSeconds:(c=f.duration)??void 0,warnings:d,response:{timestamp:l,modelId:this.modelId,headers:p,body:m}}}},pi=t.z.object({text:t.z.string(),language:t.z.string().nullish(),duration:t.z.number().nullish(),words:t.z.array(t.z.object({word:t.z.string(),start:t.z.number(),end:t.z.number()})).nullish(),segments:t.z.array(t.z.object({id:t.z.number(),seek:t.z.number(),start:t.z.number(),end:t.z.number(),text:t.z.string(),tokens:t.z.array(t.z.number()),temperature:t.z.number(),avg_logprob:t.z.number(),compression_ratio:t.z.number(),no_speech_prob:t.z.number()})).nullish()});function mi(e={}){var t,n;let r=(t=St(e.baseURL))??`https://api.openai.com/v1`,i=(n=e.name)??`openai`,a=()=>({Authorization:`Bearer ${Ke({apiKey:e.apiKey,environmentVariableName:`OPENAI_API_KEY`,description:`OpenAI`})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers}),o=t=>new Xn(t,{provider:`${i}.chat`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),s=t=>new lr(t,{provider:`${i}.completion`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),c=t=>new mr(t,{provider:`${i}.embedding`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),l=t=>new vr(t,{provider:`${i}.image`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),u=t=>new fi(t,{provider:`${i}.transcription`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),d=t=>new li(t,{provider:`${i}.speech`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),f=e=>{if(new.target)throw Error(`The OpenAI model function cannot be called with the new keyword.`);return p(e)},p=t=>new Fr(t,{provider:`${i}.responses`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch,fileIdPrefixes:[`file-`]}),m=function(e){return f(e)};return m.languageModel=f,m.chat=o,m.completion=s,m.responses=p,m.embedding=c,m.textEmbedding=c,m.textEmbeddingModel=c,m.image=l,m.imageModel=l,m.transcription=u,m.transcriptionModel=u,m.speech=d,m.speechModel=d,m.tools=Er,m}var hi=mi(),gi=t.z.object({user:t.z.string().optional(),reasoningEffort:t.z.string().optional()}),_i=t.z.object({error:t.z.object({message:t.z.string(),type:t.z.string().nullish(),param:t.z.any().nullish(),code:t.z.union([t.z.string(),t.z.number()]).nullish()})}),vi={errorSchema:_i,errorToMessage:e=>e.error.message},yi=t.z.object({prompt_tokens:t.z.number().nullish(),completion_tokens:t.z.number().nullish(),total_tokens:t.z.number().nullish(),prompt_tokens_details:t.z.object({cached_tokens:t.z.number().nullish()}).nullish(),completion_tokens_details:t.z.object({reasoning_tokens:t.z.number().nullish(),accepted_prediction_tokens:t.z.number().nullish(),rejected_prediction_tokens:t.z.number().nullish()}).nullish()}).nullish(),bi=t.z.object({id:t.z.string().nullish(),created:t.z.number().nullish(),model:t.z.string().nullish(),choices:t.z.array(t.z.object({message:t.z.object({role:t.z.literal(`assistant`).nullish(),content:t.z.string().nullish(),reasoning_content:t.z.string().nullish(),reasoning:t.z.string().nullish(),tool_calls:t.z.array(t.z.object({id:t.z.string().nullish(),function:t.z.object({name:t.z.string(),arguments:t.z.string()})})).nullish()}),finish_reason:t.z.string().nullish()})),usage:yi}),xi=t.z.object({echo:t.z.boolean().optional(),logitBias:t.z.record(t.z.string(),t.z.number()).optional(),suffix:t.z.string().optional(),user:t.z.string().optional()}),Si=t.z.object({prompt_tokens:t.z.number(),completion_tokens:t.z.number(),total_tokens:t.z.number()}),Ci=t.z.object({id:t.z.string().nullish(),created:t.z.number().nullish(),model:t.z.string().nullish(),choices:t.z.array(t.z.object({text:t.z.string(),finish_reason:t.z.string()})),usage:Si.nullish()}),wi=t.z.object({dimensions:t.z.number().optional(),user:t.z.string().optional()}),Ti=t.z.object({data:t.z.array(t.z.object({embedding:t.z.array(t.z.number())})),usage:t.z.object({prompt_tokens:t.z.number()}).nullish(),providerMetadata:t.z.record(t.z.string(),t.z.record(t.z.string(),t.z.any())).optional()}),Ei=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`,this.maxImagesPerCall=10}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:a,headers:o,abortSignal:s}){var c,l,u,d,f;let p=[];r!=null&&p.push({type:`unsupported-setting`,setting:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&p.push({type:`unsupported-setting`,setting:`seed`});let m=(u=(l=(c=this.config._internal)?.currentDate)?.call(c))??new Date,{value:h,responseHeaders:g}=await H({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:R(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...(d=a.openai)??{},response_format:`b64_json`},failedResponseHandler:G((f=this.config.errorStructure)??vi),successfulResponseHandler:q(Di),abortSignal:s,fetch:this.config.fetch});return{images:h.data.map(e=>e.b64_json),warnings:p,response:{timestamp:m,modelId:this.modelId,headers:g}}}},Di=t.z.object({data:t.z.array(t.z.object({b64_json:t.z.string()}))});function Oi(e){let t=[],n=[];for(let{role:n,content:r}of e)switch(n){case`system`:t.push({role:`system`,content:r});break;case`user`:if(r.length===1&&r[0].type===`text`){t.push({role:`user`,content:r[0].text});break}t.push({role:`user`,content:r.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`image_url`,image_url:{url:e.data instanceof URL?e.data.toString():`data:${t};base64,${J(e.data)}`}}}else throw new L({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e=``,n=[];for(let t of r)switch(t.type){case`text`:e+=t.text;break;case`tool-call`:n.push({id:t.toolCallId,type:`function`,function:{name:t.toolName,arguments:JSON.stringify(t.input)}});break}t.push({role:`assistant`,content:e,tool_calls:n.length>0?n:void 0});break}case`tool`:for(let e of r){let n=e.output,r;switch(n.type){case`text`:case`error-text`:r=n.value;break;case`content`:case`json`:case`error-json`:r=JSON.stringify(n.value);break}t.push({role:`tool`,tool_call_id:e.toolCallId,content:r})}break;default:{let e=n;throw Error(`Unsupported role: ${e}`)}}return{messages:t,warnings:n}}function ki({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function Ai(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`tool_calls`:case`function_call`:return`tool-calls`;case`content_filter`:return`content-filter`;default:return`unknown`}}var ji=t.z.object({type:t.z.literal(`web`),country:t.z.string().length(2).optional(),excludedWebsites:t.z.array(t.z.string()).max(5).optional(),allowedWebsites:t.z.array(t.z.string()).max(5).optional(),safeSearch:t.z.boolean().optional()}),Mi=t.z.object({type:t.z.literal(`x`),xHandles:t.z.array(t.z.string()).optional()}),Ni=t.z.object({type:t.z.literal(`news`),country:t.z.string().length(2).optional(),excludedWebsites:t.z.array(t.z.string()).max(5).optional(),safeSearch:t.z.boolean().optional()}),Pi=t.z.object({type:t.z.literal(`rss`),links:t.z.array(t.z.string().url()).max(1)}),Fi=t.z.discriminatedUnion(`type`,[ji,Mi,Ni,Pi]),Ii=t.z.object({reasoningEffort:t.z.enum([`low`,`high`]).optional(),searchParameters:t.z.object({mode:t.z.enum([`off`,`auto`,`on`]),returnCitations:t.z.boolean().optional(),fromDate:t.z.string().optional(),toDate:t.z.string().optional(),maxSearchResults:t.z.number().min(1).max(50).optional(),sources:t.z.array(Fi).optional()}).optional()}),Li=t.z.object({error:t.z.object({message:t.z.string(),type:t.z.string().nullish(),param:t.z.any().nullish(),code:t.z.union([t.z.string(),t.z.number()]).nullish()})}),Ri=G({errorSchema:Li,errorToMessage:e=>e.error.message});function zi({tools:e,toolChoice:t}){e=e?.length?e:void 0;let n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};let r=[];for(let t of e)t.type===`provider-defined`?n.push({type:`unsupported-tool`,tool:t}):r.push({type:`function`,function:{name:t.name,description:t.description,parameters:t.inputSchema}});if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};let i=t.type;switch(i){case`auto`:case`none`:return{tools:r,toolChoice:i,toolWarnings:n};case`required`:return{tools:r,toolChoice:`required`,toolWarnings:n};case`tool`:return{tools:r,toolChoice:{type:`function`,function:{name:t.toolName}},toolWarnings:n};default:{let e=i;throw new L({functionality:`tool choice type: ${e}`})}}}var Bi=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,seed:c,responseFormat:l,providerOptions:u,tools:d,toolChoice:f}){var p,m,h;let g=[],_=(p=await V({provider:`xai`,providerOptions:u,schema:Ii}))??{};i!=null&&g.push({type:`unsupported-setting`,setting:`topK`}),a!=null&&g.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),o!=null&&g.push({type:`unsupported-setting`,setting:`presencePenalty`}),s!=null&&g.push({type:`unsupported-setting`,setting:`stopSequences`}),l!=null&&l.type===`json`&&l.schema!=null&&g.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format schema is not supported`});let{messages:v,warnings:y}=Oi(e);g.push(...y);let{tools:b,toolChoice:x,toolWarnings:S}=zi({tools:d,toolChoice:f});g.push(...S);let C={model:this.modelId,max_tokens:t,temperature:n,top_p:r,seed:c,reasoning_effort:_.reasoningEffort,response_format:l?.type===`json`?l.schema==null?{type:`json_object`}:{type:`json_schema`,json_schema:{name:(m=l.name)??`response`,schema:l.schema,strict:!0}}:void 0,search_parameters:_.searchParameters?{mode:_.searchParameters.mode,return_citations:_.searchParameters.returnCitations,from_date:_.searchParameters.fromDate,to_date:_.searchParameters.toDate,max_search_results:_.searchParameters.maxSearchResults,sources:(h=_.searchParameters.sources)?.map(e=>({type:e.type,...e.type===`web`&&{country:e.country,excluded_websites:e.excludedWebsites,allowed_websites:e.allowedWebsites,safe_search:e.safeSearch},...e.type===`x`&&{x_handles:e.xHandles},...e.type===`news`&&{country:e.country,excluded_websites:e.excludedWebsites,safe_search:e.safeSearch},...e.type===`rss`&&{links:e.links}}))}:void 0,messages:v,tools:b,tool_choice:x};return{args:C,warnings:g}}async doGenerate(e){var t,n,r;let{args:i,warnings:a}=await this.getArgs(e),{responseHeaders:o,value:s,rawValue:c}=await H({url:`${(t=this.config.baseURL)??`https://api.x.ai/v1`}/chat/completions`,headers:R(this.config.headers(),e.headers),body:i,failedResponseHandler:Ri,successfulResponseHandler:q(Hi),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=s.choices[0],u=[];if(l.message.content!=null&&l.message.content.length>0){let e=l.message.content,t=i.messages[i.messages.length-1];t?.role===`assistant`&&e===t.content&&(e=``),e.length>0&&u.push({type:`text`,text:e})}if(l.message.reasoning_content!=null&&l.message.reasoning_content.length>0&&u.push({type:`reasoning`,text:l.message.reasoning_content}),l.message.tool_calls!=null)for(let e of l.message.tool_calls)u.push({type:`tool-call`,toolCallId:e.id,toolName:e.function.name,input:e.function.arguments});if(s.citations!=null)for(let e of s.citations)u.push({type:`source`,sourceType:`url`,id:this.config.generateId(),url:e});return{content:u,finishReason:Ai(l.finish_reason),usage:{inputTokens:s.usage.prompt_tokens,outputTokens:s.usage.completion_tokens,totalTokens:s.usage.total_tokens,reasoningTokens:(r=(n=s.usage.completion_tokens_details)?.reasoning_tokens)??void 0},request:{body:i},response:{...ki(s),headers:o,body:c},warnings:a}}async doStream(e){var t;let{args:n,warnings:r}=await this.getArgs(e),i={...n,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:a,value:o}=await H({url:`${(t=this.config.baseURL)??`https://api.x.ai/v1`}/chat/completions`,headers:R(this.config.headers(),e.headers),body:i,failedResponseHandler:Ri,successfulResponseHandler:K(Ui),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l={},u={},d=this;return{stream:o.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:r})},transform(t,n){var r,a;if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let o=t.value;if(n.enqueue({type:`response-metadata`,...ki(o)}),o.citations!=null)for(let e of o.citations)n.enqueue({type:`source`,sourceType:`url`,id:d.config.generateId(),url:e});o.usage!=null&&(c.inputTokens=o.usage.prompt_tokens,c.outputTokens=o.usage.completion_tokens,c.totalTokens=o.usage.total_tokens,c.reasoningTokens=(a=(r=o.usage.completion_tokens_details)?.reasoning_tokens)??void 0);let f=o.choices[0];if(f?.finish_reason!=null&&(s=Ai(f.finish_reason)),f?.delta==null)return;let p=f.delta,m=f.index;if(p.content!=null&&p.content.length>0){let e=p.content,t=i.messages[i.messages.length-1];if(t?.role===`assistant`&&e===t.content)return;let r=`text-${o.id||m}`;l[r]??(l[r]={type:`text`},n.enqueue({type:`text-start`,id:r})),n.enqueue({type:`text-delta`,id:r,delta:e})}if(p.reasoning_content!=null&&p.reasoning_content.length>0){let e=`reasoning-${o.id||m}`;if(u[e]===p.reasoning_content)return;u[e]=p.reasoning_content,l[e]??(l[e]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:e})),n.enqueue({type:`reasoning-delta`,id:e,delta:p.reasoning_content})}if(p.tool_calls!=null)for(let e of p.tool_calls){let t=e.id;n.enqueue({type:`tool-input-start`,id:t,toolName:e.function.name}),n.enqueue({type:`tool-input-delta`,id:t,delta:e.function.arguments}),n.enqueue({type:`tool-input-end`,id:t}),n.enqueue({type:`tool-call`,toolCallId:t,toolName:e.function.name,input:e.function.arguments})}},flush(e){for(let[t,n]of Object.entries(l))e.enqueue({type:n.type===`text`?`text-end`:`reasoning-end`,id:t});e.enqueue({type:`finish`,finishReason:s,usage:c})}})),request:{body:i},response:{headers:a}}}},Vi=t.z.object({prompt_tokens:t.z.number(),completion_tokens:t.z.number(),total_tokens:t.z.number(),completion_tokens_details:t.z.object({reasoning_tokens:t.z.number().nullish()}).nullish()}),Hi=t.z.object({id:t.z.string().nullish(),created:t.z.number().nullish(),model:t.z.string().nullish(),choices:t.z.array(t.z.object({message:t.z.object({role:t.z.literal(`assistant`),content:t.z.string().nullish(),reasoning_content:t.z.string().nullish(),tool_calls:t.z.array(t.z.object({id:t.z.string(),type:t.z.literal(`function`),function:t.z.object({name:t.z.string(),arguments:t.z.string()})})).nullish()}),index:t.z.number(),finish_reason:t.z.string().nullish()})),object:t.z.literal(`chat.completion`),usage:Vi,citations:t.z.array(t.z.string().url()).nullish()}),Ui=t.z.object({id:t.z.string().nullish(),created:t.z.number().nullish(),model:t.z.string().nullish(),choices:t.z.array(t.z.object({delta:t.z.object({role:t.z.enum([`assistant`]).optional(),content:t.z.string().nullish(),reasoning_content:t.z.string().nullish(),tool_calls:t.z.array(t.z.object({id:t.z.string(),type:t.z.literal(`function`),function:t.z.object({name:t.z.string(),arguments:t.z.string()})})).nullish()}),finish_reason:t.z.string().nullish(),index:t.z.number()})),usage:Vi.nullish(),citations:t.z.array(t.z.string().url()).nullish()}),Wi={errorSchema:Li,errorToMessage:e=>e.error.message};function Gi(e={}){var t;let n=St((t=e.baseURL)??`https://api.x.ai/v1`),r=()=>({Authorization:`Bearer ${Ke({apiKey:e.apiKey,environmentVariableName:`XAI_API_KEY`,description:`xAI API key`})}`,...e.headers}),i=t=>new Bi(t,{provider:`xai.chat`,baseURL:n,headers:r,generateId:B,fetch:e.fetch}),a=t=>new Ei(t,{provider:`xai.image`,url:({path:e})=>`${n}${e}`,headers:r,fetch:e.fetch,errorStructure:Wi}),o=e=>i(e);return o.languageModel=i,o.chat=i,o.textEmbeddingModel=e=>{throw new be({modelId:e,modelType:`textEmbeddingModel`})},o.imageModel=a,o.image=a,o}var Ki=Gi();function qi(e){if(!e.body)throw Error(`Response body is required`);let t=e.headers.get(la);if(!t||t===`ui-message`)return e.body.pipeThrough(new TextDecoderStream).pipeThrough(new ze).pipeThrough(new TransformStream({async transform(e,t){if(e.data===`[DONE]`)return;let n=await st({text:e.data});n.success?t.enqueue(n.value):t.error(n.error)}}));let r=e=>(0,n.streamText)({model:e,prompt:[{role:`user`,content:[{type:`text`,text:`Hello, world!`}]}]}).toUIMessageStream();switch(t){case`openai-chat`:return r(mi({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`openai-response`:return r(mi({apiKey:`ignored`,fetch:(t,n)=>e}).responses(`fake-model`));case`anthropic`:return r(tn({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`google`:return r(Fn({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`xai`:return r(Gi({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));default:throw Error(`Unsupported response format: ${t}`)}}var Ji=(e,t,n={})=>{let r=`${e}=${t}`;if(e.startsWith(`__Secure-`)&&!n.secure)throw Error(`__Secure- Cookie must have Secure attributes`);if(e.startsWith(`__Host-`)){if(!n.secure)throw Error(`__Host- Cookie must have Secure attributes`);if(n.path!==`/`)throw Error(`__Host- Cookie must have Path attributes with "/"`);if(n.domain)throw Error(`__Host- Cookie must not have Domain attributes`)}if(n&&typeof n.maxAge==`number`&&n.maxAge>=0){if(n.maxAge>3456e4)throw Error(`Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.`);r+=`; Max-Age=${n.maxAge|0}`}if(n.domain&&n.prefix!==`host`&&(r+=`; Domain=${n.domain}`),n.path&&(r+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw Error(`Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.`);r+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly&&(r+=`; HttpOnly`),n.secure&&(r+=`; Secure`),n.sameSite&&(r+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.priority&&(r+=`; Priority=${n.priority.charAt(0).toUpperCase()+n.priority.slice(1)}`),n.partitioned){if(!n.secure)throw Error(`Partitioned Cookie must have Secure attributes`);r+=`; Partitioned`}return r},Yi=(e,t,n)=>(t=encodeURIComponent(t),Ji(e,t,n)),Xi=(e,t)=>(e=e.replace(/\/+$/,``),e+=`/`,t=t.replace(/^\/+/,``),e+t),Zi=(e,t)=>{for(let[n,r]of Object.entries(t)){let t=RegExp(`/:`+n+`(?:{[^/]+})?\\??`);e=e.replace(t,r?`/${r}`:``)}return e},Qi=e=>{let t=new URLSearchParams;for(let[n,r]of Object.entries(e)){if(r===void 0)continue;if(Array.isArray(r))for(let e of r)t.append(n,e);else t.set(n,r)}return t},$i=(e,t)=>{switch(t){case`ws`:return e.replace(/^http/,`ws`);case`http`:return e.replace(/^ws/,`http`)}},ea=e=>/^https?:\/\/[^\/]+?\/index(?=\?|$)/.test(e)?e.replace(/\/index(?=\?|$)/,`/`):e.replace(/\/index(?=\?|$)/,``);function ta(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function na(e,t){if(!ta(e)&&!ta(t))return t;let n={...e};for(let e in t){let r=t[e];ta(n[e])&&ta(r)?n[e]=na(n[e],r):n[e]=r}return n}var ra=(e,t)=>{let n=new Proxy(()=>{},{get(n,r){if(!(typeof r!=`string`||r===`then`))return ra(e,[...t,r])},apply(n,r,i){return e({path:t,args:i})}});return n},ia=class{url;method;queryParams=void 0;pathParams={};rBody;cType=void 0;constructor(e,t){this.url=e,this.method=t}fetch=async(e,t)=>{if(e){if(e.query&&(this.queryParams=Qi(e.query)),e.form){let t=new FormData;for(let[n,r]of Object.entries(e.form))if(Array.isArray(r))for(let e of r)t.append(n,e);else t.append(n,r);this.rBody=t}e.json&&(this.rBody=JSON.stringify(e.json),this.cType=`application/json`),e.param&&(this.pathParams=e.param)}let n=this.method.toUpperCase(),r={...e?.header,...typeof t?.headers==`function`?await t.headers():t?.headers};if(e?.cookie){let t=[];for(let[n,r]of Object.entries(e.cookie))t.push(Yi(n,r,{path:`/`}));r.Cookie=t.join(`,`)}this.cType&&(r[`Content-Type`]=this.cType);let i=new Headers(r??void 0),a=this.url;a=ea(a),a=Zi(a,this.pathParams),this.queryParams&&(a=a+`?`+this.queryParams.toString()),n=this.method.toUpperCase();let o=!(n===`GET`||n===`HEAD`);return(t?.fetch||fetch)(a,{body:o?this.rBody:void 0,method:n,headers:i,...t?.init})}},aa=(e,t)=>ra(function n(r){let i=[...r.path],a=i.slice(-3).reverse();if(a[0]===`toString`)return a[1]===`name`?a[2]||``:n.toString();if(a[0]===`valueOf`)return a[1]===`name`?a[2]||``:n;let o=``;if(/^\$/.test(a[0])){let e=i.pop();e&&(o=e.replace(/^\$/,``))}let s=i.join(`/`),c=Xi(e,s);if(o===`url`){let e=c;return r.args[0]&&(r.args[0].param&&(e=Zi(c,r.args[0].param)),r.args[0].query&&(e=e+`?`+Qi(r.args[0].query).toString())),e=ea(e),new URL(e)}if(o===`ws`){let e=$i(r.args[0]&&r.args[0].param?Zi(c,r.args[0].param):c,`ws`),n=new URL(e),i=r.args[0]?.query;i&&Object.entries(i).forEach(([e,t])=>{Array.isArray(t)?t.forEach(t=>n.searchParams.append(e,t)):n.searchParams.set(e,t)});let a=(...e)=>t?.webSocket!==void 0&&typeof t.webSocket==`function`?t.webSocket(...e):new WebSocket(...e);return a(n.toString())}let l=new ia(c,o);if(o){t??={};let e=na(t,{...r.args[1]});return l.fetch(r.args[0],e)}return l},[]);const oa=`BLINK_API_SERVER_URL`,sa=process.env[oa],ca=aa(sa??``,{fetch:sa?void 0:async()=>{throw console.warn(`Your code is attempting to use the Blink API server, but no API server is configured for this Blink agent.`),Error(`No API server is configured for this Blink agent. External APIs are not available.`)}}),la=`x-blink-stream-response-format`;var ua=class{options;constructor(e){this.options=e}get baseUrl(){return this.options.baseUrl}async sendMessages(e,t){let n=await fetch(`${this.options.baseUrl}/_agent/send-messages`,{method:`POST`,body:JSON.stringify(e),headers:this.options.headers,signal:t?.signal});return n.ok||await this.handleError(n),qi(n)}async experimental_provideCompletions(e){let t=await fetch(`${this.options.baseUrl}/_agent/completions`,{method:`POST`,body:JSON.stringify(e),headers:this.options.headers});if(t.ok||await this.handleError(t),t.headers.get(`content-type`)?.includes(`application/json`)){let e=await t.json();return new ReadableStream({start(t){t.enqueue(e),t.close()}})}if(!t.body)throw Error(`Failed to provide completions (${t.status}): ${t.statusText}`);return da(t)}async capabilities(){let e=await fetch(`${this.options.baseUrl}/_agent/capabilities`,{headers:this.options.headers});e.ok||await this.handleError(e);let t=await e.json();return t}async provideUIOptions(e,t){let n=await fetch(`${this.options.baseUrl}/_agent/options`,{method:`POST`,body:JSON.stringify(e),headers:this.options.headers,signal:t?.signal});n.ok||await this.handleError(n);let r=await n.json();return r}async health(){let e=await fetch(`${this.options.baseUrl}/_agent/health`,{headers:this.options.headers});e.ok||await this.handleError(e)}async handleError(e){let t;try{t=await e.text()}catch{}if(t){let n;try{n=JSON.parse(t)}catch{}throw n?Error(n.error):Error(`Failed to send messages (${e.status}): ${t}`)}throw Error(`Failed to send messages (${e.status}): ${e.statusText}`)}};const da=e=>{let t=new ze;if(!e.body)throw Error(`The stream endpoint did not return a body!`);return e.body.pipeThrough(new TextDecoderStream).pipeTo(t.writable).catch(e=>{}),fa(t.readable)},fa=e=>{let t=e.pipeThrough(new TransformStream({async transform(e,t){let n=await st({text:e.data});if(!n.success){t.error(n.error);return}t.enqueue(n.value)}}));return t};Object.defineProperty(exports,`APICallError`,{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,`APIServerURLEnvironmentVariable`,{enumerable:!0,get:function(){return oa}}),Object.defineProperty(exports,`Client`,{enumerable:!0,get:function(){return ua}}),Object.defineProperty(exports,`EmptyResponseBodyError`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,`EventSourceParserStream`,{enumerable:!0,get:function(){return ze}}),Object.defineProperty(exports,`InvalidArgumentError`,{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,`InvalidPromptError`,{enumerable:!0,get:function(){return O}}),Object.defineProperty(exports,`InvalidResponseDataError`,{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,`JSONParseError`,{enumerable:!0,get:function(){return F}}),Object.defineProperty(exports,`StreamResponseFormatHeader`,{enumerable:!0,get:function(){return la}}),Object.defineProperty(exports,`TooManyEmbeddingValuesForCallError`,{enumerable:!0,get:function(){return Te}}),Object.defineProperty(exports,`TypeValidationError`,{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,`UnsupportedFunctionalityError`,{enumerable:!0,get:function(){return L}}),Object.defineProperty(exports,`client`,{enumerable:!0,get:function(){return ca}}),Object.defineProperty(exports,`convertResponseToUIMessageStream`,{enumerable:!0,get:function(){return qi}}),Object.defineProperty(exports,`createAsyncIterableStream`,{enumerable:!0,get:function(){return Be}}),Object.defineProperty(exports,`streamSSE`,{enumerable:!0,get:function(){return da}});
@@ -1,7 +1,7 @@
1
- import http from "http";
2
- import * as ai0 from "ai";
3
- import { AsyncIterableStream, InferUIMessageChunk, Tool, ToolSet, UIDataTypes, UIMessage, UIMessagePart, UITools } from "ai";
4
1
  import * as _ai_sdk_provider0 from "@ai-sdk/provider";
2
+ import * as ai0 from "ai";
3
+ import { AsyncIterableStream, InferToolInput, InferToolOutput, InferUIMessageChunk, Tool, ToolSet, UIDataTypes, UIMessage, UIMessagePart, UITools } from "ai";
4
+ import http from "http";
5
5
 
6
6
  //#region src/api/chat.d.ts
7
7
  interface Chat {
@@ -39,6 +39,31 @@ declare const chat: Readonly<{
39
39
  type ToolWithContext<CONTEXT, TOOL extends Tool> = TOOL & {
40
40
  withContext(context: CONTEXT): TOOL;
41
41
  };
42
+ /**
43
+ * ToolWithApproval is a tool that supports the "autoApprove" method.
44
+ *
45
+ * @param TOOL The tool type.
46
+ * @returns The tool with the given approval.
47
+ */
48
+ type ToolWithApproval<INPUT, OUTPUT> = Tool<INPUT, OUTPUT> & {
49
+ /**
50
+ * autoApprove is a function that can be used to automatically approve
51
+ * an approval tool call based on the input.
52
+ *
53
+ * @param input The input to the tool.
54
+ * @returns Whether the tool call should be approved.
55
+ */
56
+ autoApprove?: (input: INPUT) => Promise<boolean> | boolean;
57
+ };
58
+ type ToolSetWithApproval<TOOLS extends ToolSet> = { [K in keyof TOOLS]: ToolWithApproval<InferToolInput<TOOLS[K]>, InferToolOutput<TOOLS[K]>> };
59
+ /**
60
+ * toolWithApproval is a helper for inferring the execute and autoApprove
61
+ * arguments of a tool.
62
+ *
63
+ * @param tool The tool to wrap.
64
+ * @returns The wrapped tool.
65
+ */
66
+ declare function toolWithApproval<INPUT, OUTPUT>(tool: ToolWithApproval<INPUT, OUTPUT>): ToolWithApproval<INPUT, OUTPUT>;
42
67
  /**
43
68
  * Tools are helpers for managing tools.
44
69
  */
@@ -67,7 +92,7 @@ declare const tools: {
67
92
  *
68
93
  * @returns Tools that should be sent in `streamText`.
69
94
  */
70
- withApproval<TOOLS extends ToolSet, MESSAGE extends UIMessage>(options: {
95
+ withApproval<TOOLSET extends ToolSet, TOOLS extends ToolSetWithApproval<TOOLSET>, MESSAGE extends UIMessage>(options: {
71
96
  messages: MESSAGE[];
72
97
  tools: TOOLS;
73
98
  abortSignal?: AbortSignal;
@@ -169,6 +194,45 @@ type ExperimentalCompletion = {
169
194
  replace?: [number, number];
170
195
  };
171
196
  type ExperimentalProvideCompletionsResponse = ReadableStream<ExperimentalCompletion> | Promise<ReadableStream<ExperimentalCompletion>> | Promise<ExperimentalCompletion> | ExperimentalCompletion;
197
+ type ProvideOptionsRequest<MESSAGE extends UIMessage = UIMessage> = {
198
+ /**
199
+ * Options that are actively selected by the user.
200
+ *
201
+ * Use this to provide custom options based on previous selections.
202
+ */
203
+ readonly selectedOptions?: ExtractUIOptions<MESSAGE>;
204
+ };
205
+ type OptionSelectValue<ID extends string = string> = {
206
+ readonly id: ID;
207
+ readonly label: string;
208
+ };
209
+ type OptionSelect<Values extends readonly OptionSelectValue[] = readonly OptionSelectValue[]> = {
210
+ readonly type: "select";
211
+ readonly label: string;
212
+ readonly values: Values;
213
+ readonly defaultValue: Values[number]["id"];
214
+ };
215
+ type Options = Record<string, string>;
216
+ type WithUIOptions<OPTIONS extends Options, MESSAGE extends UIMessage = UIMessage> = MESSAGE & {
217
+ readonly role: "user";
218
+ readonly metadata: MESSAGE["metadata"] & {
219
+ readonly options: OPTIONS;
220
+ };
221
+ };
222
+ type ExtractUIOptions<M> = M extends WithUIOptions<infer O> ? O : never;
223
+ type OptionsSchema<OPTIONS extends Options> = { [K in keyof OPTIONS]: OptionSelect<Array<{
224
+ id: OPTIONS[K];
225
+ label: string;
226
+ }>> };
227
+ /**
228
+ * lastUIOptions finds the last user message with options.
229
+ * Options are stored in message metadata to preserve the history
230
+ * of changing options.
231
+ *
232
+ * @param messages - The messages to search.
233
+ * @returns The last user message with options, or undefined if no such message exists.
234
+ */
235
+ declare function lastUIOptions<MESSAGE extends UIMessage>(messages: MESSAGE[]): ExtractUIOptions<MESSAGE> | undefined;
172
236
  interface AgentOptions<MESSAGE extends UIMessage = UIMessage> {
173
237
  /**
174
238
  * sendMessages is called when the agent is streaming chat messages.
@@ -196,14 +260,24 @@ interface AgentOptions<MESSAGE extends UIMessage = UIMessage> {
196
260
  * @returns A stream of completions, or a single completion.
197
261
  */
198
262
  experimental_provideCompletions?(options: ExperimentalProvideCompletionsOptions<MESSAGE>): ExperimentalProvideCompletionsResponse;
263
+ /**
264
+ * provideUIOptions is called when the agent is asked to provide
265
+ * user-selectable options.
266
+ *
267
+ * To provide options, use:
268
+ * @example
269
+ * ```ts
270
+ * blink.agent<blink.WithUIOptions<{
271
+ * model: "gpt-5" | "sonnet"
272
+ * }>>({
273
+ * // ...
274
+ * })
275
+ * ```
276
+ *
277
+ * @returns A schema for the options.
278
+ */
279
+ provideUIOptions?(options: ProvideOptionsRequest<MESSAGE>): Promise<OptionsSchema<ExtractUIOptions<MESSAGE>>> | OptionsSchema<ExtractUIOptions<MESSAGE>>;
199
280
  }
200
- /**
201
- * A Blink agent is simply an HTTP handler with a reserved
202
- * "/_agent/" path used for agent-specific requests.
203
- *
204
- * The environment variable "BLINK_API_SERVER_URL" is used
205
- * to serve responses to the `blink.*` API. (e.g. blink.chat.upsert).
206
- */
207
281
  interface Agent {
208
282
  /**
209
283
  * fetch is the HTTP handler for the agent.
@@ -221,9 +295,6 @@ interface Agent {
221
295
  */
222
296
  serve(options?: ServeOptions): http.Server;
223
297
  }
224
- /**
225
- * ServeOptions is the options for the `.serve()` method.
226
- */
227
298
  type ServeOptions = {
228
299
  readonly host?: string;
229
300
  readonly port?: number;
@@ -274,7 +345,7 @@ declare const _default: {
274
345
  withContext(context: unknown): ai0.Tool;
275
346
  };
276
347
  }>(tools: TOOLS, context: ContextFromTools<TOOLS>): { [K in keyof TOOLS]: ai0.Tool };
277
- withApproval<TOOLS extends ai0.ToolSet, MESSAGE extends UIMessage>(options: {
348
+ withApproval<TOOLSET extends ai0.ToolSet, TOOLS extends ToolSetWithApproval<TOOLSET>, MESSAGE extends UIMessage>(options: {
278
349
  messages: MESSAGE[];
279
350
  tools: TOOLS;
280
351
  abortSignal?: AbortSignal;
@@ -283,4 +354,4 @@ declare const _default: {
283
354
  };
284
355
  };
285
356
  //#endregion
286
- export { Agent, AgentOptions, Chat, ChatBehavior, ContextFromTools, ExperimentalCompletion, ExperimentalProvideCompletionsOptions, ExperimentalProvideCompletionsResponse, Message, MessageOptions, SendMessagesOptions, SendMessagesResponse, ServeOptions, StreamResponseFormat, ToolApprovalOutput, ToolWithContext, _default, agent, chat, isToolApprovalOutput, model, storage, tools, withResponseFormat };
357
+ export { Agent, AgentOptions, Chat, ChatBehavior, ContextFromTools, ExperimentalCompletion, ExperimentalProvideCompletionsOptions, ExperimentalProvideCompletionsResponse, ExtractUIOptions, Message, MessageOptions, OptionSelect, OptionSelectValue, Options, OptionsSchema, ProvideOptionsRequest, SendMessagesOptions, SendMessagesResponse, ServeOptions, StreamResponseFormat, ToolApprovalOutput, ToolSetWithApproval, ToolWithApproval, ToolWithContext, WithUIOptions, _default, agent, chat, isToolApprovalOutput, lastUIOptions, model, storage, toolWithApproval, tools, withResponseFormat };
@@ -1,4 +1,4 @@
1
- import { Chat, ExperimentalCompletion } from "./index-CIUoZVwP.js";
1
+ import { Chat, ExperimentalCompletion, OptionsSchema, ProvideOptionsRequest, WithUIOptions } from "./index-BdS2C_9A.cjs";
2
2
  import { UIMessage, UIMessageChunk } from "ai";
3
3
 
4
4
  //#region src/http/async-iterable-stream.d.ts
@@ -60,6 +60,7 @@ interface ExperimentalProvideCompletionsRequest {
60
60
  interface CapabilitiesResponse {
61
61
  readonly requests: boolean;
62
62
  readonly completions: boolean;
63
+ readonly options: boolean;
63
64
  }
64
65
  interface ClientOptions {
65
66
  readonly baseUrl: string;
@@ -90,6 +91,12 @@ declare class Client {
90
91
  * This is used to check if the agent supports requests and completions.
91
92
  */
92
93
  capabilities(): Promise<CapabilitiesResponse>;
94
+ /**
95
+ * provideUIOptions provides selectable options to the user.
96
+ */
97
+ provideUIOptions(request: ProvideOptionsRequest<WithUIOptions<Record<string, any>>>, options?: {
98
+ signal?: AbortSignal;
99
+ }): Promise<OptionsSchema<any>>;
93
100
  /**
94
101
  * health simply returns a 200 response.
95
102
  * This is used to check if the agent is running.
@@ -1,7 +1,7 @@
1
- import * as _ai_sdk_provider0 from "@ai-sdk/provider";
2
- import * as ai0 from "ai";
3
- import { AsyncIterableStream, InferUIMessageChunk, Tool, ToolSet, UIDataTypes, UIMessage, UIMessagePart, UITools } from "ai";
4
1
  import http from "http";
2
+ import * as ai0 from "ai";
3
+ import { AsyncIterableStream, InferToolInput, InferToolOutput, InferUIMessageChunk, Tool, ToolSet, UIDataTypes, UIMessage, UIMessagePart, UITools } from "ai";
4
+ import * as _ai_sdk_provider0 from "@ai-sdk/provider";
5
5
 
6
6
  //#region src/api/chat.d.ts
7
7
  interface Chat {
@@ -39,6 +39,31 @@ declare const chat: Readonly<{
39
39
  type ToolWithContext<CONTEXT, TOOL extends Tool> = TOOL & {
40
40
  withContext(context: CONTEXT): TOOL;
41
41
  };
42
+ /**
43
+ * ToolWithApproval is a tool that supports the "autoApprove" method.
44
+ *
45
+ * @param TOOL The tool type.
46
+ * @returns The tool with the given approval.
47
+ */
48
+ type ToolWithApproval<INPUT, OUTPUT> = Tool<INPUT, OUTPUT> & {
49
+ /**
50
+ * autoApprove is a function that can be used to automatically approve
51
+ * an approval tool call based on the input.
52
+ *
53
+ * @param input The input to the tool.
54
+ * @returns Whether the tool call should be approved.
55
+ */
56
+ autoApprove?: (input: INPUT) => Promise<boolean> | boolean;
57
+ };
58
+ type ToolSetWithApproval<TOOLS extends ToolSet> = { [K in keyof TOOLS]: ToolWithApproval<InferToolInput<TOOLS[K]>, InferToolOutput<TOOLS[K]>> };
59
+ /**
60
+ * toolWithApproval is a helper for inferring the execute and autoApprove
61
+ * arguments of a tool.
62
+ *
63
+ * @param tool The tool to wrap.
64
+ * @returns The wrapped tool.
65
+ */
66
+ declare function toolWithApproval<INPUT, OUTPUT>(tool: ToolWithApproval<INPUT, OUTPUT>): ToolWithApproval<INPUT, OUTPUT>;
42
67
  /**
43
68
  * Tools are helpers for managing tools.
44
69
  */
@@ -67,7 +92,7 @@ declare const tools: {
67
92
  *
68
93
  * @returns Tools that should be sent in `streamText`.
69
94
  */
70
- withApproval<TOOLS extends ToolSet, MESSAGE extends UIMessage>(options: {
95
+ withApproval<TOOLSET extends ToolSet, TOOLS extends ToolSetWithApproval<TOOLSET>, MESSAGE extends UIMessage>(options: {
71
96
  messages: MESSAGE[];
72
97
  tools: TOOLS;
73
98
  abortSignal?: AbortSignal;
@@ -169,6 +194,45 @@ type ExperimentalCompletion = {
169
194
  replace?: [number, number];
170
195
  };
171
196
  type ExperimentalProvideCompletionsResponse = ReadableStream<ExperimentalCompletion> | Promise<ReadableStream<ExperimentalCompletion>> | Promise<ExperimentalCompletion> | ExperimentalCompletion;
197
+ type ProvideOptionsRequest<MESSAGE extends UIMessage = UIMessage> = {
198
+ /**
199
+ * Options that are actively selected by the user.
200
+ *
201
+ * Use this to provide custom options based on previous selections.
202
+ */
203
+ readonly selectedOptions?: ExtractUIOptions<MESSAGE>;
204
+ };
205
+ type OptionSelectValue<ID extends string = string> = {
206
+ readonly id: ID;
207
+ readonly label: string;
208
+ };
209
+ type OptionSelect<Values extends readonly OptionSelectValue[] = readonly OptionSelectValue[]> = {
210
+ readonly type: "select";
211
+ readonly label: string;
212
+ readonly values: Values;
213
+ readonly defaultValue: Values[number]["id"];
214
+ };
215
+ type Options = Record<string, string>;
216
+ type WithUIOptions<OPTIONS extends Options, MESSAGE extends UIMessage = UIMessage> = MESSAGE & {
217
+ readonly role: "user";
218
+ readonly metadata: MESSAGE["metadata"] & {
219
+ readonly options: OPTIONS;
220
+ };
221
+ };
222
+ type ExtractUIOptions<M> = M extends WithUIOptions<infer O> ? O : never;
223
+ type OptionsSchema<OPTIONS extends Options> = { [K in keyof OPTIONS]: OptionSelect<Array<{
224
+ id: OPTIONS[K];
225
+ label: string;
226
+ }>> };
227
+ /**
228
+ * lastUIOptions finds the last user message with options.
229
+ * Options are stored in message metadata to preserve the history
230
+ * of changing options.
231
+ *
232
+ * @param messages - The messages to search.
233
+ * @returns The last user message with options, or undefined if no such message exists.
234
+ */
235
+ declare function lastUIOptions<MESSAGE extends UIMessage>(messages: MESSAGE[]): ExtractUIOptions<MESSAGE> | undefined;
172
236
  interface AgentOptions<MESSAGE extends UIMessage = UIMessage> {
173
237
  /**
174
238
  * sendMessages is called when the agent is streaming chat messages.
@@ -196,14 +260,24 @@ interface AgentOptions<MESSAGE extends UIMessage = UIMessage> {
196
260
  * @returns A stream of completions, or a single completion.
197
261
  */
198
262
  experimental_provideCompletions?(options: ExperimentalProvideCompletionsOptions<MESSAGE>): ExperimentalProvideCompletionsResponse;
263
+ /**
264
+ * provideUIOptions is called when the agent is asked to provide
265
+ * user-selectable options.
266
+ *
267
+ * To provide options, use:
268
+ * @example
269
+ * ```ts
270
+ * blink.agent<blink.WithUIOptions<{
271
+ * model: "gpt-5" | "sonnet"
272
+ * }>>({
273
+ * // ...
274
+ * })
275
+ * ```
276
+ *
277
+ * @returns A schema for the options.
278
+ */
279
+ provideUIOptions?(options: ProvideOptionsRequest<MESSAGE>): Promise<OptionsSchema<ExtractUIOptions<MESSAGE>>> | OptionsSchema<ExtractUIOptions<MESSAGE>>;
199
280
  }
200
- /**
201
- * A Blink agent is simply an HTTP handler with a reserved
202
- * "/_agent/" path used for agent-specific requests.
203
- *
204
- * The environment variable "BLINK_API_SERVER_URL" is used
205
- * to serve responses to the `blink.*` API. (e.g. blink.chat.upsert).
206
- */
207
281
  interface Agent {
208
282
  /**
209
283
  * fetch is the HTTP handler for the agent.
@@ -221,9 +295,6 @@ interface Agent {
221
295
  */
222
296
  serve(options?: ServeOptions): http.Server;
223
297
  }
224
- /**
225
- * ServeOptions is the options for the `.serve()` method.
226
- */
227
298
  type ServeOptions = {
228
299
  readonly host?: string;
229
300
  readonly port?: number;
@@ -274,7 +345,7 @@ declare const _default: {
274
345
  withContext(context: unknown): ai0.Tool;
275
346
  };
276
347
  }>(tools: TOOLS, context: ContextFromTools<TOOLS>): { [K in keyof TOOLS]: ai0.Tool };
277
- withApproval<TOOLS extends ai0.ToolSet, MESSAGE extends UIMessage>(options: {
348
+ withApproval<TOOLSET extends ai0.ToolSet, TOOLS extends ToolSetWithApproval<TOOLSET>, MESSAGE extends UIMessage>(options: {
278
349
  messages: MESSAGE[];
279
350
  tools: TOOLS;
280
351
  abortSignal?: AbortSignal;
@@ -283,4 +354,4 @@ declare const _default: {
283
354
  };
284
355
  };
285
356
  //#endregion
286
- export { Agent, AgentOptions, Chat, ChatBehavior, ContextFromTools, ExperimentalCompletion, ExperimentalProvideCompletionsOptions, ExperimentalProvideCompletionsResponse, Message, MessageOptions, SendMessagesOptions, SendMessagesResponse, ServeOptions, StreamResponseFormat, ToolApprovalOutput, ToolWithContext, _default, agent, chat, isToolApprovalOutput, model, storage, tools, withResponseFormat };
357
+ export { Agent, AgentOptions, Chat, ChatBehavior, ContextFromTools, ExperimentalCompletion, ExperimentalProvideCompletionsOptions, ExperimentalProvideCompletionsResponse, ExtractUIOptions, Message, MessageOptions, OptionSelect, OptionSelectValue, Options, OptionsSchema, ProvideOptionsRequest, SendMessagesOptions, SendMessagesResponse, ServeOptions, StreamResponseFormat, ToolApprovalOutput, ToolSetWithApproval, ToolWithApproval, ToolWithContext, WithUIOptions, _default, agent, chat, isToolApprovalOutput, lastUIOptions, model, storage, toolWithApproval, tools, withResponseFormat };