blink 0.1.66 → 0.1.67
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/api/index.browser.cjs +1 -1
- package/dist/browser/api/index.browser.js +1 -1
- package/dist/browser/{client-DsiYP47H.js → client-BbZudkEc.js} +1 -1
- package/dist/browser/{client-C9uh5T54.cjs → client-DFaZjb1-.cjs} +1 -1
- package/dist/browser/http/index.cjs +1 -1
- package/dist/browser/http/index.d.cts +148 -1
- package/dist/browser/http/index.d.ts +148 -1
- package/dist/browser/http/index.js +1 -1
- package/dist/browser/{index.browser-CFap1r_Y.cjs → index.browser-BwGhLjB7.cjs} +1 -1
- package/dist/browser/{index.browser-CeE1x4lk.js → index.browser-Dj8kjB6X.js} +1 -1
- package/dist/browser/react/index.cjs +1 -1
- package/dist/browser/react/index.js +1 -1
- package/dist/cli/{auth-Dw-wJ1IM.js → auth-BUNIOupD.js} +1 -1
- package/dist/cli/{chat-CvTLq5E0.js → chat-L0VBV1Zr.js} +1 -1
- package/dist/cli/{dev-Cp22zef8.js → dev-BAQJ4XqP.js} +96 -113
- package/dist/cli/index.js +6 -6
- package/dist/cli/{init-LfebhEg-.js → init-BEvNUWUD.js} +1 -1
- package/dist/cli/login-DKW_KVCA.js +1 -0
- package/package.json +8 -2
- package/dist/cli/login-KHDcJ0iZ.js +0 -1
- /package/dist/cli/{dist-CN69Y-yA.js → dist-NqrnQGst.js} +0 -0
- /package/dist/cli/{open-Cr8lEmcs.js → open-CSMQaj0E.js} +0 -0
|
@@ -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 fr({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 pr(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 mr=c.z.object({echo:c.z.boolean().optional(),logitBias:c.z.record(c.z.string(),c.z.number()).optional(),suffix:c.z.string().optional(),user:c.z.string().optional(),logprobs:c.z.union([c.z.boolean(),c.z.number()]).optional()}),hr=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:mr}),...await V({provider:this.providerOptionsName,providerOptions:f,schema:mr})};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}=dr({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(_r),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:pr(l.finish_reason),request:{body:i},response:{...fr(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(vr),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`,...fr(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=pr(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}}}},gr=c.z.object({prompt_tokens:c.z.number(),completion_tokens:c.z.number(),total_tokens:c.z.number()}),_r=c.z.object({id:c.z.string().nullish(),created:c.z.number().nullish(),model:c.z.string().nullish(),choices:c.z.array(c.z.object({text:c.z.string(),finish_reason:c.z.string(),logprobs:c.z.object({tokens:c.z.array(c.z.string()),token_logprobs:c.z.array(c.z.number()),top_logprobs:c.z.array(c.z.record(c.z.string(),c.z.number())).nullish()}).nullish()})),usage:gr.nullish()}),vr=c.z.union([c.z.object({id:c.z.string().nullish(),created:c.z.number().nullish(),model:c.z.string().nullish(),choices:c.z.array(c.z.object({text:c.z.string(),finish_reason:c.z.string().nullish(),index:c.z.number(),logprobs:c.z.object({tokens:c.z.array(c.z.string()),token_logprobs:c.z.array(c.z.number()),top_logprobs:c.z.array(c.z.record(c.z.string(),c.z.number())).nullish()}).nullish()})),usage:gr.nullish()}),Un]),yr=c.z.object({dimensions:c.z.number().optional(),user:c.z.string().optional()}),br=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 Le({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let a=(i=await V({provider:`openai`,providerOptions:r,schema:yr}))??{},{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(xr),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}}}},xr=c.z.object({data:c.z.array(c.z.object({embedding:c.z.array(c.z.number())})),usage:c.z.object({prompt_tokens:c.z.number()}).nullish()}),Sr={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},Cr=new Set([`gpt-image-1`]),wr=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get maxImagesPerCall(){var e;return(e=Sr[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)??{},...Cr.has(this.modelId)?{}:{response_format:`b64_json`}},failedResponseHandler:$,successfulResponseHandler:q(Tr),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)}}}}},Tr=c.z.object({data:c.z.array(c.z.object({b64_json:c.z.string(),revised_prompt:c.z.string().optional()}))}),Er=c.z.object({container:c.z.union([c.z.string(),c.z.object({fileIds:c.z.array(c.z.string()).optional()})]).optional()}),Dr=U({id:`openai.code_interpreter`,name:`code_interpreter`,inputSchema:c.z.object({})}),Or=(e={})=>Dr(e),kr=c.z.object({filters:c.z.object({allowedDomains:c.z.array(c.z.string()).optional()}).optional(),searchContextSize:c.z.enum([`low`,`medium`,`high`]).optional(),userLocation:c.z.object({type:c.z.literal(`approximate`),country:c.z.string().optional(),city:c.z.string().optional(),region:c.z.string().optional(),timezone:c.z.string().optional()}).optional()}),Ar=U({id:`openai.web_search`,name:`web_search`,inputSchema:c.z.object({action:c.z.discriminatedUnion(`type`,[c.z.object({type:c.z.literal(`search`),query:c.z.string().nullish()}),c.z.object({type:c.z.literal(`open_page`),url:c.z.string()}),c.z.object({type:c.z.literal(`find`),url:c.z.string(),pattern:c.z.string()})]).nullish()})}),jr=(e={})=>Ar(e),Mr={codeInterpreter:Or,fileSearch:Qn,webSearchPreview:er,webSearch:jr};function Nr(e,t){return t?t.some(t=>e.startsWith(t)):!1}async function Pr({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`&&Nr(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`&&Nr(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:Fr}),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 Fr=c.z.object({itemId:c.z.string().nullish(),reasoningEncryptedContent:c.z.string().nullish()});function Ir({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 Lr({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=Zn.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=$n.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=kr.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=Er.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 Rr=c.z.object({type:c.z.literal(`web_search_call`),id:c.z.string(),status:c.z.string(),action:c.z.discriminatedUnion(`type`,[c.z.object({type:c.z.literal(`search`),query:c.z.string().nullish()}),c.z.object({type:c.z.literal(`open_page`),url:c.z.string()}),c.z.object({type:c.z.literal(`find`),url:c.z.string(),pattern:c.z.string()})]).nullish()}),zr=20,Br=c.z.array(c.z.object({token:c.z.string(),logprob:c.z.number(),top_logprobs:c.z.array(c.z.object({token:c.z.string(),logprob:c.z.number()}))})),Vr=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=[],_=fi(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 Pr({prompt:c,systemMessageMode:_.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes});g.push(...y);let b=await V({provider:`openai`,providerOptions:l,schema:pi}),x=(p=b?.strictJsonSchema)??!1,S=b?.include,C=typeof b?.logprobs==`number`?b?.logprobs:b?.logprobs===!0?zr: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}=Lr({tools:u,toolChoice:d,strictJsonSchema:x});return{webSearchToolName:w,args:{...T,tools:E,tool_choice:D},warnings:[...g,...O]}}async doGenerate(e){var t,n,r,i,a,o,s,l,u,d,f,p,m,h,g,_,v;let{args:y,warnings:b,webSearchToolName:x}=await this.getArgs(e),S=this.config.url({path:`/responses`,modelId:this.modelId}),{responseHeaders:C,value:T,rawValue:E}=await H({url:S,headers:R(this.config.headers(),e.headers),body:y,failedResponseHandler:$,successfulResponseHandler:q(c.z.object({id:c.z.string(),created_at:c.z.number(),error:c.z.object({code:c.z.string(),message:c.z.string()}).nullish(),model:c.z.string(),output:c.z.array(c.z.discriminatedUnion(`type`,[c.z.object({type:c.z.literal(`message`),role:c.z.literal(`assistant`),id:c.z.string(),content:c.z.array(c.z.object({type:c.z.literal(`output_text`),text:c.z.string(),logprobs:Br.nullish(),annotations:c.z.array(c.z.discriminatedUnion(`type`,[c.z.object({type:c.z.literal(`url_citation`),start_index:c.z.number(),end_index:c.z.number(),url:c.z.string(),title:c.z.string()}),c.z.object({type:c.z.literal(`file_citation`),file_id:c.z.string(),filename:c.z.string().nullish(),index:c.z.number().nullish(),start_index:c.z.number().nullish(),end_index:c.z.number().nullish(),quote:c.z.string().nullish()}),c.z.object({type:c.z.literal(`container_file_citation`)})]))}))}),c.z.object({type:c.z.literal(`code_interpreter_call`)}),c.z.object({type:c.z.literal(`function_call`),call_id:c.z.string(),name:c.z.string(),arguments:c.z.string(),id:c.z.string()}),Rr,c.z.object({type:c.z.literal(`computer_call`),id:c.z.string(),status:c.z.string().optional()}),c.z.object({type:c.z.literal(`file_search_call`),id:c.z.string(),status:c.z.string().optional(),queries:c.z.array(c.z.string()).nullish(),results:c.z.array(c.z.object({attributes:c.z.object({file_id:c.z.string(),filename:c.z.string(),score:c.z.number(),text:c.z.string()})})).nullish()}),c.z.object({type:c.z.literal(`reasoning`),id:c.z.string(),encrypted_content:c.z.string().nullish(),summary:c.z.array(c.z.object({type:c.z.literal(`summary_text`),text:c.z.string()}))})])),service_tier:c.z.string().nullish(),incomplete_details:c.z.object({reason:c.z.string()}).nullable(),usage:Hr})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(T.error)throw new w({message:T.error.message,url:S,requestBodyValues:y,statusCode:400,responseHeaders:C,responseBody:E,isRetryable:!1});let D=[],O=[],k=!1;for(let c of T.output)switch(c.type){case`reasoning`:c.summary.length===0&&c.summary.push({type:`summary_text`,text:``});for(let e of c.summary)D.push({type:`reasoning`,text:e.text,providerMetadata:{openai:{itemId:c.id,reasoningEncryptedContent:(t=c.encrypted_content)??null}}});break;case`message`:for(let t of c.content){(r=(n=e.providerOptions)?.openai)?.logprobs&&t.logprobs&&O.push(t.logprobs),D.push({type:`text`,text:t.text,providerMetadata:{openai:{itemId:c.id}}});for(let e of t.annotations)e.type===`url_citation`?D.push({type:`source`,sourceType:`url`,id:(o=(a=(i=this.config).generateId)?.call(i))??B(),url:e.url,title:e.title}):e.type===`file_citation`&&D.push({type:`source`,sourceType:`document`,id:(u=(l=(s=this.config).generateId)?.call(s))??B(),mediaType:`text/plain`,title:(f=(d=e.quote)??e.filename)??`Document`,filename:(p=e.filename)??e.file_id})}break;case`function_call`:k=!0,D.push({type:`tool-call`,toolCallId:c.call_id,toolName:c.name,input:c.arguments,providerMetadata:{openai:{itemId:c.id}}});break;case`web_search_call`:D.push({type:`tool-call`,toolCallId:c.id,toolName:x??`web_search`,input:JSON.stringify({action:c.action}),providerExecuted:!0}),D.push({type:`tool-result`,toolCallId:c.id,toolName:x??`web_search`,result:{status:c.status},providerExecuted:!0});break;case`computer_call`:D.push({type:`tool-call`,toolCallId:c.id,toolName:`computer_use`,input:``,providerExecuted:!0}),D.push({type:`tool-result`,toolCallId:c.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:c.status||`completed`},providerExecuted:!0});break;case`file_search_call`:D.push({type:`tool-call`,toolCallId:c.id,toolName:`file_search`,input:``,providerExecuted:!0}),D.push({type:`tool-result`,toolCallId:c.id,toolName:`file_search`,result:{type:`file_search_tool_result`,status:c.status||`completed`,...c.queries&&{queries:c.queries},...c.results&&{results:c.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:Ir({finishReason:(m=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=(h=T.usage.output_tokens_details)?.reasoning_tokens)??void 0,cachedInputTokens:(v=(_=T.usage.input_tokens_details)?.cached_tokens)??void 0},request:{body:y},response:{id:T.id,timestamp:new Date(T.created_at*1e3),modelId:T.model,headers:C,body:E},providerMetadata:A,warnings:b}}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($r),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,j,ee,M;if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){s=`error`,n.enqueue({type:`error`,error:t.error});return}let N=t.value;if(oi(N))N.item.type===`function_call`?(d[N.output_index]={toolName:N.item.name,toolCallId:N.item.call_id},n.enqueue({type:`tool-input-start`,id:N.item.call_id,toolName:N.item.name})):N.item.type===`web_search_call`?(d[N.output_index]={toolName:r??`web_search`,toolCallId:N.item.id},n.enqueue({type:`tool-input-start`,id:N.item.id,toolName:r??`web_search`})):N.item.type===`computer_call`?(d[N.output_index]={toolName:`computer_use`,toolCallId:N.item.id},n.enqueue({type:`tool-input-start`,id:N.item.id,toolName:`computer_use`})):N.item.type===`file_search_call`?(d[N.output_index]={toolName:`file_search`,toolCallId:N.item.id},n.enqueue({type:`tool-input-start`,id:N.item.id,toolName:`file_search`})):N.item.type===`message`?n.enqueue({type:`text-start`,id:N.item.id,providerMetadata:{openai:{itemId:N.item.id}}}):si(N)&&(p[N.item.id]={encryptedContent:N.item.encrypted_content,summaryParts:[0]},n.enqueue({type:`reasoning-start`,id:`${N.item.id}:0`,providerMetadata:{openai:{itemId:N.item.id,reasoningEncryptedContent:(i=N.item.encrypted_content)??null}}}));else if(ti(N)){if(N.item.type===`function_call`)d[N.output_index]=void 0,f=!0,n.enqueue({type:`tool-input-end`,id:N.item.call_id}),n.enqueue({type:`tool-call`,toolCallId:N.item.call_id,toolName:N.item.name,input:N.item.arguments,providerMetadata:{openai:{itemId:N.item.id}}});else if(N.item.type===`web_search_call`)d[N.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:N.item.id}),n.enqueue({type:`tool-call`,toolCallId:N.item.id,toolName:`web_search`,input:JSON.stringify({action:N.item.action}),providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:N.item.id,toolName:`web_search`,result:{status:N.item.status},providerExecuted:!0});else if(N.item.type===`computer_call`)d[N.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:N.item.id}),n.enqueue({type:`tool-call`,toolCallId:N.item.id,toolName:`computer_use`,input:``,providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:N.item.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:N.item.status||`completed`},providerExecuted:!0});else if(N.item.type===`file_search_call`)d[N.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:N.item.id}),n.enqueue({type:`tool-call`,toolCallId:N.item.id,toolName:`file_search`,input:``,providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:N.item.id,toolName:`file_search`,result:{type:`file_search_tool_result`,status:N.item.status||`completed`,...N.item.queries&&{queries:N.item.queries},...N.item.results&&{results:N.item.results}},providerExecuted:!0});else if(N.item.type===`message`)n.enqueue({type:`text-end`,id:N.item.id});else if(ni(N)){let e=p[N.item.id];for(let t of e.summaryParts)n.enqueue({type:`reasoning-end`,id:`${N.item.id}:${t}`,providerMetadata:{openai:{itemId:N.item.id,reasoningEncryptedContent:(a=N.item.encrypted_content)??null}}});delete p[N.item.id]}}else if(ai(N)){let e=d[N.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:N.delta})}else ii(N)?(u=N.response.id,n.enqueue({type:`response-metadata`,id:N.response.id,timestamp:new Date(N.response.created_at*1e3),modelId:N.response.model})):ei(N)?(n.enqueue({type:`text-delta`,id:N.item_id,delta:N.delta}),(g=(h=e.providerOptions)?.openai)?.logprobs&&N.logprobs&&l.push(N.logprobs)):li(N)?N.summary_index>0&&((_=p[N.item_id])==null||_.summaryParts.push(N.summary_index),n.enqueue({type:`reasoning-start`,id:`${N.item_id}:${N.summary_index}`,providerMetadata:{openai:{itemId:N.item_id,reasoningEncryptedContent:(y=(v=p[N.item_id])?.encryptedContent)??null}}})):ui(N)?n.enqueue({type:`reasoning-delta`,id:`${N.item_id}:${N.summary_index}`,delta:N.delta,providerMetadata:{openai:{itemId:N.item_id}}}):ri(N)?(s=Ir({finishReason:(b=N.response.incomplete_details)?.reason,hasFunctionCall:f}),c.inputTokens=N.response.usage.input_tokens,c.outputTokens=N.response.usage.output_tokens,c.totalTokens=N.response.usage.input_tokens+N.response.usage.output_tokens,c.reasoningTokens=(S=(x=N.response.usage.output_tokens_details)?.reasoning_tokens)??void 0,c.cachedInputTokens=(w=(C=N.response.usage.input_tokens_details)?.cached_tokens)??void 0,typeof N.response.service_tier==`string`&&(m=N.response.service_tier)):ci(N)?N.annotation.type===`url_citation`?n.enqueue({type:`source`,sourceType:`url`,id:(D=(E=(T=o.config).generateId)?.call(T))??B(),url:N.annotation.url,title:N.annotation.title}):N.annotation.type===`file_citation`&&n.enqueue({type:`source`,sourceType:`document`,id:(A=(k=(O=o.config).generateId)?.call(O))??B(),mediaType:`text/plain`,title:(ee=(j=N.annotation.quote)??N.annotation.filename)??`Document`,filename:(M=N.annotation.filename)??N.annotation.file_id}):di(N)&&n.enqueue({type:`error`,error:N})},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}}}},Hr=c.z.object({input_tokens:c.z.number(),input_tokens_details:c.z.object({cached_tokens:c.z.number().nullish()}).nullish(),output_tokens:c.z.number(),output_tokens_details:c.z.object({reasoning_tokens:c.z.number().nullish()}).nullish()}),Ur=c.z.object({type:c.z.literal(`response.output_text.delta`),item_id:c.z.string(),delta:c.z.string(),logprobs:Br.nullish()}),Wr=c.z.object({type:c.z.literal(`error`),code:c.z.string(),message:c.z.string(),param:c.z.string().nullish(),sequence_number:c.z.number()}),Gr=c.z.object({type:c.z.enum([`response.completed`,`response.incomplete`]),response:c.z.object({incomplete_details:c.z.object({reason:c.z.string()}).nullish(),usage:Hr,service_tier:c.z.string().nullish()})}),Kr=c.z.object({type:c.z.literal(`response.created`),response:c.z.object({id:c.z.string(),created_at:c.z.number(),model:c.z.string(),service_tier:c.z.string().nullish()})}),qr=c.z.object({type:c.z.literal(`response.output_item.added`),output_index:c.z.number(),item:c.z.discriminatedUnion(`type`,[c.z.object({type:c.z.literal(`message`),id:c.z.string()}),c.z.object({type:c.z.literal(`reasoning`),id:c.z.string(),encrypted_content:c.z.string().nullish()}),c.z.object({type:c.z.literal(`function_call`),id:c.z.string(),call_id:c.z.string(),name:c.z.string(),arguments:c.z.string()}),c.z.object({type:c.z.literal(`web_search_call`),id:c.z.string(),status:c.z.string(),action:c.z.object({type:c.z.literal(`search`),query:c.z.string().optional()}).nullish()}),c.z.object({type:c.z.literal(`computer_call`),id:c.z.string(),status:c.z.string()}),c.z.object({type:c.z.literal(`file_search_call`),id:c.z.string(),status:c.z.string(),queries:c.z.array(c.z.string()).nullish(),results:c.z.array(c.z.object({attributes:c.z.object({file_id:c.z.string(),filename:c.z.string(),score:c.z.number(),text:c.z.string()})})).optional()})])}),Jr=c.z.object({type:c.z.literal(`response.output_item.done`),output_index:c.z.number(),item:c.z.discriminatedUnion(`type`,[c.z.object({type:c.z.literal(`message`),id:c.z.string()}),c.z.object({type:c.z.literal(`reasoning`),id:c.z.string(),encrypted_content:c.z.string().nullish()}),c.z.object({type:c.z.literal(`function_call`),id:c.z.string(),call_id:c.z.string(),name:c.z.string(),arguments:c.z.string(),status:c.z.literal(`completed`)}),Rr,c.z.object({type:c.z.literal(`computer_call`),id:c.z.string(),status:c.z.literal(`completed`)}),c.z.object({type:c.z.literal(`file_search_call`),id:c.z.string(),status:c.z.literal(`completed`),queries:c.z.array(c.z.string()).nullish(),results:c.z.array(c.z.object({attributes:c.z.object({file_id:c.z.string(),filename:c.z.string(),score:c.z.number(),text:c.z.string()})})).nullish()})])}),Yr=c.z.object({type:c.z.literal(`response.function_call_arguments.delta`),item_id:c.z.string(),output_index:c.z.number(),delta:c.z.string()}),Xr=c.z.object({type:c.z.literal(`response.output_text.annotation.added`),annotation:c.z.discriminatedUnion(`type`,[c.z.object({type:c.z.literal(`url_citation`),url:c.z.string(),title:c.z.string()}),c.z.object({type:c.z.literal(`file_citation`),file_id:c.z.string(),filename:c.z.string().nullish(),index:c.z.number().nullish(),start_index:c.z.number().nullish(),end_index:c.z.number().nullish(),quote:c.z.string().nullish()})])}),Zr=c.z.object({type:c.z.literal(`response.reasoning_summary_part.added`),item_id:c.z.string(),summary_index:c.z.number()}),Qr=c.z.object({type:c.z.literal(`response.reasoning_summary_text.delta`),item_id:c.z.string(),summary_index:c.z.number(),delta:c.z.string()}),$r=c.z.union([Ur,Gr,Kr,qr,Jr,Yr,Xr,Zr,Qr,Wr,c.z.object({type:c.z.string()}).loose()]);function ei(e){return e.type===`response.output_text.delta`}function ti(e){return e.type===`response.output_item.done`}function ni(e){return ti(e)&&e.item.type===`reasoning`}function ri(e){return e.type===`response.completed`||e.type===`response.incomplete`}function ii(e){return e.type===`response.created`}function ai(e){return e.type===`response.function_call_arguments.delta`}function oi(e){return e.type===`response.output_item.added`}function si(e){return oi(e)&&e.item.type===`reasoning`}function ci(e){return e.type===`response.output_text.annotation.added`}function li(e){return e.type===`response.reasoning_summary_part.added`}function ui(e){return e.type===`response.reasoning_summary_text.delta`}function di(e){return e.type===`error`}function fi(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 pi=c.z.object({metadata:c.z.any().nullish(),parallelToolCalls:c.z.boolean().nullish(),previousResponseId:c.z.string().nullish(),store:c.z.boolean().nullish(),user:c.z.string().nullish(),reasoningEffort:c.z.string().nullish(),strictJsonSchema:c.z.boolean().nullish(),instructions:c.z.string().nullish(),reasoningSummary:c.z.string().nullish(),serviceTier:c.z.enum([`auto`,`flex`,`priority`]).nullish(),include:c.z.array(c.z.enum([`reasoning.encrypted_content`,`file_search_call.results`,`message.output_text.logprobs`])).nullish(),textVerbosity:c.z.enum([`low`,`medium`,`high`]).nullish(),promptCacheKey:c.z.string().nullish(),safetyIdentifier:c.z.string().nullish(),logprobs:c.z.union([c.z.boolean(),c.z.number().min(1).max(zr)]).optional()}),mi=c.z.object({instructions:c.z.string().nullish(),speed:c.z.number().min(.25).max(4).default(1).nullish()}),hi=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:mi}),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:xt(),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}}}},gi=c.z.object({include:c.z.array(c.z.string()).optional(),language:c.z.string().optional(),prompt:c.z.string().optional(),temperature:c.z.number().min(0).max(1).default(0).optional(),timestampGranularities:c.z.array(c.z.enum([`word`,`segment`])).default([`segment`]).optional()}),_i={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`},vi=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:gi}),a=new FormData,o=e instanceof Uint8Array?new Blob([e]):new Blob([Et(e)]);a.append(`model`,this.modelId);let s=$e(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 _t({url:this.config.url({path:`/audio/transcriptions`,modelId:this.modelId}),headers:R(this.config.headers(),e.headers),formData:u,failedResponseHandler:$,successfulResponseHandler:q(yi),abortSignal:e.abortSignal,fetch:this.config.fetch}),h=f.language!=null&&f.language in _i?_i[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}}}},yi=c.z.object({text:c.z.string(),language:c.z.string().nullish(),duration:c.z.number().nullish(),words:c.z.array(c.z.object({word:c.z.string(),start:c.z.number(),end:c.z.number()})).nullish(),segments:c.z.array(c.z.object({id:c.z.number(),seek:c.z.number(),start:c.z.number(),end:c.z.number(),text:c.z.string(),tokens:c.z.array(c.z.number()),temperature:c.z.number(),avg_logprob:c.z.number(),compression_ratio:c.z.number(),no_speech_prob:c.z.number()})).nullish()});function bi(e={}){var t,n;let r=(t=Ot(e.baseURL))??`https://api.openai.com/v1`,i=(n=e.name)??`openai`,a=()=>({Authorization:`Bearer ${Qe({apiKey:e.apiKey,environmentVariableName:`OPENAI_API_KEY`,description:`OpenAI`})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers}),o=t=>new nr(t,{provider:`${i}.chat`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),s=t=>new hr(t,{provider:`${i}.completion`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),c=t=>new br(t,{provider:`${i}.embedding`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),l=t=>new wr(t,{provider:`${i}.image`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),u=t=>new vi(t,{provider:`${i}.transcription`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),d=t=>new hi(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 Vr(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=Mr,m}var xi=bi(),Si=c.z.object({user:c.z.string().optional(),reasoningEffort:c.z.string().optional()}),Ci=c.z.object({error:c.z.object({message:c.z.string(),type:c.z.string().nullish(),param:c.z.any().nullish(),code:c.z.union([c.z.string(),c.z.number()]).nullish()})}),wi={errorSchema:Ci,errorToMessage:e=>e.error.message},Ti=c.z.object({prompt_tokens:c.z.number().nullish(),completion_tokens:c.z.number().nullish(),total_tokens:c.z.number().nullish(),prompt_tokens_details:c.z.object({cached_tokens:c.z.number().nullish()}).nullish(),completion_tokens_details:c.z.object({reasoning_tokens:c.z.number().nullish(),accepted_prediction_tokens:c.z.number().nullish(),rejected_prediction_tokens:c.z.number().nullish()}).nullish()}).nullish(),Ei=c.z.object({id:c.z.string().nullish(),created:c.z.number().nullish(),model:c.z.string().nullish(),choices:c.z.array(c.z.object({message:c.z.object({role:c.z.literal(`assistant`).nullish(),content:c.z.string().nullish(),reasoning_content:c.z.string().nullish(),reasoning:c.z.string().nullish(),tool_calls:c.z.array(c.z.object({id:c.z.string().nullish(),function:c.z.object({name:c.z.string(),arguments:c.z.string()})})).nullish()}),finish_reason:c.z.string().nullish()})),usage:Ti}),Di=c.z.object({echo:c.z.boolean().optional(),logitBias:c.z.record(c.z.string(),c.z.number()).optional(),suffix:c.z.string().optional(),user:c.z.string().optional()}),Oi=c.z.object({prompt_tokens:c.z.number(),completion_tokens:c.z.number(),total_tokens:c.z.number()}),ki=c.z.object({id:c.z.string().nullish(),created:c.z.number().nullish(),model:c.z.string().nullish(),choices:c.z.array(c.z.object({text:c.z.string(),finish_reason:c.z.string()})),usage:Oi.nullish()}),Ai=c.z.object({dimensions:c.z.number().optional(),user:c.z.string().optional()}),ji=c.z.object({data:c.z.array(c.z.object({embedding:c.z.array(c.z.number())})),usage:c.z.object({prompt_tokens:c.z.number()}).nullish(),providerMetadata:c.z.record(c.z.string(),c.z.record(c.z.string(),c.z.any())).optional()}),Mi=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)??wi),successfulResponseHandler:q(Ni),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}}}},Ni=c.z.object({data:c.z.array(c.z.object({b64_json:c.z.string()}))});function Pi(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 Fi({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 Ii(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 Li=c.z.object({type:c.z.literal(`web`),country:c.z.string().length(2).optional(),excludedWebsites:c.z.array(c.z.string()).max(5).optional(),allowedWebsites:c.z.array(c.z.string()).max(5).optional(),safeSearch:c.z.boolean().optional()}),Ri=c.z.object({type:c.z.literal(`x`),xHandles:c.z.array(c.z.string()).optional()}),zi=c.z.object({type:c.z.literal(`news`),country:c.z.string().length(2).optional(),excludedWebsites:c.z.array(c.z.string()).max(5).optional(),safeSearch:c.z.boolean().optional()}),Bi=c.z.object({type:c.z.literal(`rss`),links:c.z.array(c.z.string().url()).max(1)}),Vi=c.z.discriminatedUnion(`type`,[Li,Ri,zi,Bi]),Hi=c.z.object({reasoningEffort:c.z.enum([`low`,`high`]).optional(),searchParameters:c.z.object({mode:c.z.enum([`off`,`auto`,`on`]),returnCitations:c.z.boolean().optional(),fromDate:c.z.string().optional(),toDate:c.z.string().optional(),maxSearchResults:c.z.number().min(1).max(50).optional(),sources:c.z.array(Vi).optional()}).optional()}),Ui=c.z.object({error:c.z.object({message:c.z.string(),type:c.z.string().nullish(),param:c.z.any().nullish(),code:c.z.union([c.z.string(),c.z.number()]).nullish()})}),Wi=G({errorSchema:Ui,errorToMessage:e=>e.error.message});function Gi({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 Ki=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:Hi}))??{};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}=Pi(e);g.push(...y);let{tools:b,toolChoice:x,toolWarnings:S}=Gi({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:Wi,successfulResponseHandler:q(Ji),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:Ii(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:{...Fi(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:Wi,successfulResponseHandler:K(Yi),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`,...Fi(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=Ii(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}}}},qi=c.z.object({prompt_tokens:c.z.number(),completion_tokens:c.z.number(),total_tokens:c.z.number(),completion_tokens_details:c.z.object({reasoning_tokens:c.z.number().nullish()}).nullish()}),Ji=c.z.object({id:c.z.string().nullish(),created:c.z.number().nullish(),model:c.z.string().nullish(),choices:c.z.array(c.z.object({message:c.z.object({role:c.z.literal(`assistant`),content:c.z.string().nullish(),reasoning_content:c.z.string().nullish(),tool_calls:c.z.array(c.z.object({id:c.z.string(),type:c.z.literal(`function`),function:c.z.object({name:c.z.string(),arguments:c.z.string()})})).nullish()}),index:c.z.number(),finish_reason:c.z.string().nullish()})),object:c.z.literal(`chat.completion`),usage:qi,citations:c.z.array(c.z.string().url()).nullish()}),Yi=c.z.object({id:c.z.string().nullish(),created:c.z.number().nullish(),model:c.z.string().nullish(),choices:c.z.array(c.z.object({delta:c.z.object({role:c.z.enum([`assistant`]).optional(),content:c.z.string().nullish(),reasoning_content:c.z.string().nullish(),tool_calls:c.z.array(c.z.object({id:c.z.string(),type:c.z.literal(`function`),function:c.z.object({name:c.z.string(),arguments:c.z.string()})})).nullish()}),finish_reason:c.z.string().nullish(),index:c.z.number()})),usage:qi.nullish(),citations:c.z.array(c.z.string().url()).nullish()}),Xi={errorSchema:Ui,errorToMessage:e=>e.error.message};function Zi(e={}){var t;let n=Ot((t=e.baseURL)??`https://api.x.ai/v1`),r=()=>({Authorization:`Bearer ${Qe({apiKey:e.apiKey,environmentVariableName:`XAI_API_KEY`,description:`xAI API key`})}`,...e.headers}),i=t=>new Ki(t,{provider:`xai.chat`,baseURL:n,headers:r,generateId:B,fetch:e.fetch}),a=t=>new Mi(t,{provider:`xai.image`,url:({path:e})=>`${n}${e}`,headers:r,fetch:e.fetch,errorStructure:Xi}),o=e=>i(e);return o.languageModel=i,o.chat=i,o.textEmbeddingModel=e=>{throw new Me({modelId:e,modelType:`textEmbeddingModel`})},o.imageModel=a,o.image=a,o}var Qi=Zi();function $i(e){if(!e.body)throw Error(`Response body is required`);let t=e.headers.get(Fa);if(!t||t===`ui-message`)return e.body.pipeThrough(new TextDecoderStream).pipeThrough(new m).pipeThrough(new TransformStream({async transform(e,t){if(e.data!==`[DONE]`)try{let n=JSON.parse(e.data);t.enqueue(n)}catch(e){t.error(e);return}}}));let n=e=>(0,l.streamText)({model:e,prompt:[{role:`user`,content:[{type:`text`,text:`Hello, world!`}]}]}).toUIMessageStream();switch(t){case`openai-chat`:return n(bi({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`openai-response`:return n(bi({apiKey:`ignored`,fetch:(t,n)=>e}).responses(`fake-model`));case`anthropic`:return n(cn({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`google`:return n(Vn({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`xai`:return n(Zi({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));default:throw Error(`Unsupported response format: ${t}`)}}var ea=e=>{let t=e.split(`/`);return t[0]===``&&t.shift(),t},ta=e=>{let{groups:t,path:n}=na(e),r=ea(n);return ra(r,t)},na=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(e,n)=>{let r=`@${n}`;return t.push([r,e]),r}),{groups:t,path:e}},ra=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[r]=t[n];for(let i=e.length-1;i>=0;i--)if(e[i].includes(r)){e[i]=e[i].replace(r,t[n][1]);break}}return e},ia={},aa=(e,t)=>{if(e===`*`)return`*`;let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return ia[r]||(n[2]?ia[r]=t&&t[0]!==`:`&&t[0]!==`*`?[r,n[1],RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],RegExp(`^${n[2]}$`)]:ia[r]=[e,n[1],!0]),ia[r]}return null},oa=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},sa=e=>oa(e,decodeURI),ca=e=>{let t=e.url,n=t.indexOf(`/`,t.indexOf(`:`)+4),r=n;for(;r<t.length;r++){let e=t.charCodeAt(r);if(e===37){let e=t.indexOf(`?`,r),i=t.slice(n,e===-1?void 0:e);return sa(i.includes(`%25`)?i.replace(/%25/g,`%2525`):i)}else if(e===63)break}return t.slice(n,r)},la=e=>{let t=ca(e);return t.length>1&&t.at(-1)===`/`?t.slice(0,-1):t},ua=(e,t,...n)=>(n.length&&(t=ua(t,...n)),`${e?.[0]===`/`?``:`/`}${e}${t===`/`?``:`${e?.at(-1)===`/`?``:`/`}${t?.[0]===`/`?t.slice(1):t}`}`),da=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(`:`))return null;let t=e.split(`/`),n=[],r=``;return t.forEach(e=>{if(e!==``&&!/\:/.test(e))r+=`/`+e;else if(/\:/.test(e))if(/\?/.test(e)){n.length===0&&r===``?n.push(`/`):n.push(r);let t=e.replace(`?`,``);r+=`/`+t,n.push(r)}else r+=`/`+e}),n.filter((e,t,n)=>n.indexOf(e)===t)},fa=e=>/[%+]/.test(e)?(e.indexOf(`+`)!==-1&&(e=e.replace(/\+/g,` `)),e.indexOf(`%`)===-1?e:oa(e,ga)):e,pa=(e,t,n)=>{let r;if(!n&&t&&!/[%+]/.test(t)){let n=e.indexOf(`?${t}`,8);for(n===-1&&(n=e.indexOf(`&${t}`,8));n!==-1;){let r=e.charCodeAt(n+t.length+1);if(r===61){let r=n+t.length+2,i=e.indexOf(`&`,r);return fa(e.slice(r,i===-1?void 0:i))}else if(r==38||isNaN(r))return``;n=e.indexOf(`&${t}`,n+1)}if(r=/[%+]/.test(e),!r)return}let i={};r??=/[%+]/.test(e);let a=e.indexOf(`?`,8);for(;a!==-1;){let t=e.indexOf(`&`,a+1),o=e.indexOf(`=`,a);o>t&&t!==-1&&(o=-1);let s=e.slice(a+1,o===-1?t===-1?void 0:t:o);if(r&&(s=fa(s)),a=t,s===``)continue;let c;o===-1?c=``:(c=e.slice(o+1,t===-1?void 0:t),r&&(c=fa(c))),n?(i[s]&&Array.isArray(i[s])||(i[s]=[]),i[s].push(c)):i[s]??=c}return t?i[t]:i},ma=pa,ha=(e,t)=>pa(e,t,!0),ga=decodeURIComponent,_a=/^[\w!#$%&'*.^`|~+-]+$/,va=/^[ !#-:<-[\]-~]*$/,ya=(e,t)=>{if(t&&e.indexOf(t)===-1)return{};let n=e.trim().split(`;`),r={};for(let e of n){e=e.trim();let n=e.indexOf(`=`);if(n===-1)continue;let i=e.substring(0,n).trim();if(t&&t!==i||!_a.test(i))continue;let a=e.substring(n+1).trim();if(a.startsWith(`"`)&&a.endsWith(`"`)&&(a=a.slice(1,-1)),va.test(a)&&(r[i]=a.indexOf(`%`)===-1?a:oa(a,ga),t))break}return r},ba=(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},xa=(e,t,n)=>(t=encodeURIComponent(t),ba(e,t,n)),Sa=(e,t)=>(e=e.replace(/\/+$/,``),e+=`/`,t=t.replace(/^\/+/,``),e+t),Ca=(e,t)=>{for(let[n,r]of Object.entries(t)){let t=RegExp(`/:`+n+`(?:{[^/]+})?\\??`);e=e.replace(t,r?`/${r}`:``)}return e},wa=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},Ta=(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 Da(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Oa(e,t){if(!Da(e)&&!Da(t))return t;let n={...e};for(let e in t){let r=t[e];Da(n[e])&&Da(r)?n[e]=Oa(n[e],r):n[e]=r}return n}var ka=(e,t)=>{let n=new Proxy(()=>{},{get(n,r){if(!(typeof r!=`string`||r===`then`))return ka(e,[...t,r])},apply(n,r,i){return e({path:t,args:i})}});return n},Aa=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=wa(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(xa(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=Ca(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})}},ja=(e,t)=>ka(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=Sa(e,s);if(o===`url`){let e=c;return r.args[0]&&(r.args[0].param&&(e=Ca(c,r.args[0].param)),r.args[0].query&&(e=e+`?`+wa(r.args[0].query).toString())),e=Ea(e),new URL(e)}if(o===`ws`){let e=Ta(r.args[0]&&r.args[0].param?Ca(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 Aa(c,o);if(o){t??={};let e=Oa(t,{...r.args[1]});return l.fetch(r.args[0],e)}return l},[]);const Ma=`BLINK_API_SERVER_URL`,Na=process.env[Ma],Pa=ja(Na??``,{fetch:Na?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.`)}}),Fa=`x-blink-stream-response-format`;var Ia=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),$i(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 La(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 La=e=>{let t=new m;if(!e.body)throw Error(`The stream endpoint did not return a body!`);return e.body.pipeThrough(new TextDecoderStream).pipeTo(t.writable).catch(e=>{}),Ra(t.readable)},Ra=e=>{let t=e.pipeThrough(new TransformStream({async transform(e,t){try{let n=JSON.parse(e.data);t.enqueue(n)}catch(e){t.error(e);return}}}));return t};Object.defineProperty(exports,`APIServerURLEnvironmentVariable`,{enumerable:!0,get:function(){return Ma}}),Object.defineProperty(exports,`Client`,{enumerable:!0,get:function(){return Ia}}),Object.defineProperty(exports,`StreamResponseFormatHeader`,{enumerable:!0,get:function(){return Fa}}),Object.defineProperty(exports,`__toESM`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`checkOptionalParameter`,{enumerable:!0,get:function(){return da}}),Object.defineProperty(exports,`client`,{enumerable:!0,get:function(){return Pa}}),Object.defineProperty(exports,`convertResponseToUIMessageStream`,{enumerable:!0,get:function(){return $i}}),Object.defineProperty(exports,`decodeURIComponent_`,{enumerable:!0,get:function(){return ga}}),Object.defineProperty(exports,`getPath`,{enumerable:!0,get:function(){return ca}}),Object.defineProperty(exports,`getPathNoStrict`,{enumerable:!0,get:function(){return la}}),Object.defineProperty(exports,`getPattern`,{enumerable:!0,get:function(){return aa}}),Object.defineProperty(exports,`getQueryParam`,{enumerable:!0,get:function(){return ma}}),Object.defineProperty(exports,`getQueryParams`,{enumerable:!0,get:function(){return ha}}),Object.defineProperty(exports,`mergePath`,{enumerable:!0,get:function(){return ua}}),Object.defineProperty(exports,`parse`,{enumerable:!0,get:function(){return ya}}),Object.defineProperty(exports,`splitPath`,{enumerable:!0,get:function(){return ea}}),Object.defineProperty(exports,`splitRoutingPath`,{enumerable:!0,get:function(){return ta}}),Object.defineProperty(exports,`streamSSE`,{enumerable:!0,get:function(){return La}}),Object.defineProperty(exports,`tryDecode`,{enumerable:!0,get:function(){return oa}});
|
|
21
|
+
${t}:`]}}function fr({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 pr(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 mr=c.z.object({echo:c.z.boolean().optional(),logitBias:c.z.record(c.z.string(),c.z.number()).optional(),suffix:c.z.string().optional(),user:c.z.string().optional(),logprobs:c.z.union([c.z.boolean(),c.z.number()]).optional()}),hr=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:mr}),...await V({provider:this.providerOptionsName,providerOptions:f,schema:mr})};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}=dr({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(_r),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:pr(l.finish_reason),request:{body:i},response:{...fr(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(vr),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`,...fr(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=pr(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}}}},gr=c.z.object({prompt_tokens:c.z.number(),completion_tokens:c.z.number(),total_tokens:c.z.number()}),_r=c.z.object({id:c.z.string().nullish(),created:c.z.number().nullish(),model:c.z.string().nullish(),choices:c.z.array(c.z.object({text:c.z.string(),finish_reason:c.z.string(),logprobs:c.z.object({tokens:c.z.array(c.z.string()),token_logprobs:c.z.array(c.z.number()),top_logprobs:c.z.array(c.z.record(c.z.string(),c.z.number())).nullish()}).nullish()})),usage:gr.nullish()}),vr=c.z.union([c.z.object({id:c.z.string().nullish(),created:c.z.number().nullish(),model:c.z.string().nullish(),choices:c.z.array(c.z.object({text:c.z.string(),finish_reason:c.z.string().nullish(),index:c.z.number(),logprobs:c.z.object({tokens:c.z.array(c.z.string()),token_logprobs:c.z.array(c.z.number()),top_logprobs:c.z.array(c.z.record(c.z.string(),c.z.number())).nullish()}).nullish()})),usage:gr.nullish()}),Un]),yr=c.z.object({dimensions:c.z.number().optional(),user:c.z.string().optional()}),br=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 Le({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let a=(i=await V({provider:`openai`,providerOptions:r,schema:yr}))??{},{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(xr),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}}}},xr=c.z.object({data:c.z.array(c.z.object({embedding:c.z.array(c.z.number())})),usage:c.z.object({prompt_tokens:c.z.number()}).nullish()}),Sr={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},Cr=new Set([`gpt-image-1`]),wr=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get maxImagesPerCall(){var e;return(e=Sr[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)??{},...Cr.has(this.modelId)?{}:{response_format:`b64_json`}},failedResponseHandler:$,successfulResponseHandler:q(Tr),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)}}}}},Tr=c.z.object({data:c.z.array(c.z.object({b64_json:c.z.string(),revised_prompt:c.z.string().optional()}))}),Er=c.z.object({container:c.z.union([c.z.string(),c.z.object({fileIds:c.z.array(c.z.string()).optional()})]).optional()}),Dr=U({id:`openai.code_interpreter`,name:`code_interpreter`,inputSchema:c.z.object({})}),Or=(e={})=>Dr(e),kr=c.z.object({filters:c.z.object({allowedDomains:c.z.array(c.z.string()).optional()}).optional(),searchContextSize:c.z.enum([`low`,`medium`,`high`]).optional(),userLocation:c.z.object({type:c.z.literal(`approximate`),country:c.z.string().optional(),city:c.z.string().optional(),region:c.z.string().optional(),timezone:c.z.string().optional()}).optional()}),Ar=U({id:`openai.web_search`,name:`web_search`,inputSchema:c.z.object({action:c.z.discriminatedUnion(`type`,[c.z.object({type:c.z.literal(`search`),query:c.z.string().nullish()}),c.z.object({type:c.z.literal(`open_page`),url:c.z.string()}),c.z.object({type:c.z.literal(`find`),url:c.z.string(),pattern:c.z.string()})]).nullish()})}),jr=(e={})=>Ar(e),Mr={codeInterpreter:Or,fileSearch:Qn,webSearchPreview:er,webSearch:jr};function Nr(e,t){return t?t.some(t=>e.startsWith(t)):!1}async function Pr({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`&&Nr(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`&&Nr(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:Fr}),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 Fr=c.z.object({itemId:c.z.string().nullish(),reasoningEncryptedContent:c.z.string().nullish()});function Ir({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 Lr({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=Zn.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=$n.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=kr.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=Er.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 Rr=c.z.object({type:c.z.literal(`web_search_call`),id:c.z.string(),status:c.z.string(),action:c.z.discriminatedUnion(`type`,[c.z.object({type:c.z.literal(`search`),query:c.z.string().nullish()}),c.z.object({type:c.z.literal(`open_page`),url:c.z.string()}),c.z.object({type:c.z.literal(`find`),url:c.z.string(),pattern:c.z.string()})]).nullish()}),zr=20,Br=c.z.array(c.z.object({token:c.z.string(),logprob:c.z.number(),top_logprobs:c.z.array(c.z.object({token:c.z.string(),logprob:c.z.number()}))})),Vr=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=[],_=fi(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 Pr({prompt:c,systemMessageMode:_.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes});g.push(...y);let b=await V({provider:`openai`,providerOptions:l,schema:pi}),x=(p=b?.strictJsonSchema)??!1,S=b?.include,C=typeof b?.logprobs==`number`?b?.logprobs:b?.logprobs===!0?zr: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}=Lr({tools:u,toolChoice:d,strictJsonSchema:x});return{webSearchToolName:w,args:{...T,tools:E,tool_choice:D},warnings:[...g,...O]}}async doGenerate(e){var t,n,r,i,a,o,s,l,u,d,f,p,m,h,g,_,v;let{args:y,warnings:b,webSearchToolName:x}=await this.getArgs(e),S=this.config.url({path:`/responses`,modelId:this.modelId}),{responseHeaders:C,value:T,rawValue:E}=await H({url:S,headers:R(this.config.headers(),e.headers),body:y,failedResponseHandler:$,successfulResponseHandler:q(c.z.object({id:c.z.string(),created_at:c.z.number(),error:c.z.object({code:c.z.string(),message:c.z.string()}).nullish(),model:c.z.string(),output:c.z.array(c.z.discriminatedUnion(`type`,[c.z.object({type:c.z.literal(`message`),role:c.z.literal(`assistant`),id:c.z.string(),content:c.z.array(c.z.object({type:c.z.literal(`output_text`),text:c.z.string(),logprobs:Br.nullish(),annotations:c.z.array(c.z.discriminatedUnion(`type`,[c.z.object({type:c.z.literal(`url_citation`),start_index:c.z.number(),end_index:c.z.number(),url:c.z.string(),title:c.z.string()}),c.z.object({type:c.z.literal(`file_citation`),file_id:c.z.string(),filename:c.z.string().nullish(),index:c.z.number().nullish(),start_index:c.z.number().nullish(),end_index:c.z.number().nullish(),quote:c.z.string().nullish()}),c.z.object({type:c.z.literal(`container_file_citation`)})]))}))}),c.z.object({type:c.z.literal(`code_interpreter_call`)}),c.z.object({type:c.z.literal(`function_call`),call_id:c.z.string(),name:c.z.string(),arguments:c.z.string(),id:c.z.string()}),Rr,c.z.object({type:c.z.literal(`computer_call`),id:c.z.string(),status:c.z.string().optional()}),c.z.object({type:c.z.literal(`file_search_call`),id:c.z.string(),status:c.z.string().optional(),queries:c.z.array(c.z.string()).nullish(),results:c.z.array(c.z.object({attributes:c.z.object({file_id:c.z.string(),filename:c.z.string(),score:c.z.number(),text:c.z.string()})})).nullish()}),c.z.object({type:c.z.literal(`reasoning`),id:c.z.string(),encrypted_content:c.z.string().nullish(),summary:c.z.array(c.z.object({type:c.z.literal(`summary_text`),text:c.z.string()}))})])),service_tier:c.z.string().nullish(),incomplete_details:c.z.object({reason:c.z.string()}).nullable(),usage:Hr})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(T.error)throw new w({message:T.error.message,url:S,requestBodyValues:y,statusCode:400,responseHeaders:C,responseBody:E,isRetryable:!1});let D=[],O=[],k=!1;for(let c of T.output)switch(c.type){case`reasoning`:c.summary.length===0&&c.summary.push({type:`summary_text`,text:``});for(let e of c.summary)D.push({type:`reasoning`,text:e.text,providerMetadata:{openai:{itemId:c.id,reasoningEncryptedContent:(t=c.encrypted_content)??null}}});break;case`message`:for(let t of c.content){(r=(n=e.providerOptions)?.openai)?.logprobs&&t.logprobs&&O.push(t.logprobs),D.push({type:`text`,text:t.text,providerMetadata:{openai:{itemId:c.id}}});for(let e of t.annotations)e.type===`url_citation`?D.push({type:`source`,sourceType:`url`,id:(o=(a=(i=this.config).generateId)?.call(i))??B(),url:e.url,title:e.title}):e.type===`file_citation`&&D.push({type:`source`,sourceType:`document`,id:(u=(l=(s=this.config).generateId)?.call(s))??B(),mediaType:`text/plain`,title:(f=(d=e.quote)??e.filename)??`Document`,filename:(p=e.filename)??e.file_id})}break;case`function_call`:k=!0,D.push({type:`tool-call`,toolCallId:c.call_id,toolName:c.name,input:c.arguments,providerMetadata:{openai:{itemId:c.id}}});break;case`web_search_call`:D.push({type:`tool-call`,toolCallId:c.id,toolName:x??`web_search`,input:JSON.stringify({action:c.action}),providerExecuted:!0}),D.push({type:`tool-result`,toolCallId:c.id,toolName:x??`web_search`,result:{status:c.status},providerExecuted:!0});break;case`computer_call`:D.push({type:`tool-call`,toolCallId:c.id,toolName:`computer_use`,input:``,providerExecuted:!0}),D.push({type:`tool-result`,toolCallId:c.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:c.status||`completed`},providerExecuted:!0});break;case`file_search_call`:D.push({type:`tool-call`,toolCallId:c.id,toolName:`file_search`,input:``,providerExecuted:!0}),D.push({type:`tool-result`,toolCallId:c.id,toolName:`file_search`,result:{type:`file_search_tool_result`,status:c.status||`completed`,...c.queries&&{queries:c.queries},...c.results&&{results:c.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:Ir({finishReason:(m=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=(h=T.usage.output_tokens_details)?.reasoning_tokens)??void 0,cachedInputTokens:(v=(_=T.usage.input_tokens_details)?.cached_tokens)??void 0},request:{body:y},response:{id:T.id,timestamp:new Date(T.created_at*1e3),modelId:T.model,headers:C,body:E},providerMetadata:A,warnings:b}}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($r),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,j,ee,M;if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){s=`error`,n.enqueue({type:`error`,error:t.error});return}let N=t.value;if(oi(N))N.item.type===`function_call`?(d[N.output_index]={toolName:N.item.name,toolCallId:N.item.call_id},n.enqueue({type:`tool-input-start`,id:N.item.call_id,toolName:N.item.name})):N.item.type===`web_search_call`?(d[N.output_index]={toolName:r??`web_search`,toolCallId:N.item.id},n.enqueue({type:`tool-input-start`,id:N.item.id,toolName:r??`web_search`})):N.item.type===`computer_call`?(d[N.output_index]={toolName:`computer_use`,toolCallId:N.item.id},n.enqueue({type:`tool-input-start`,id:N.item.id,toolName:`computer_use`})):N.item.type===`file_search_call`?(d[N.output_index]={toolName:`file_search`,toolCallId:N.item.id},n.enqueue({type:`tool-input-start`,id:N.item.id,toolName:`file_search`})):N.item.type===`message`?n.enqueue({type:`text-start`,id:N.item.id,providerMetadata:{openai:{itemId:N.item.id}}}):si(N)&&(p[N.item.id]={encryptedContent:N.item.encrypted_content,summaryParts:[0]},n.enqueue({type:`reasoning-start`,id:`${N.item.id}:0`,providerMetadata:{openai:{itemId:N.item.id,reasoningEncryptedContent:(i=N.item.encrypted_content)??null}}}));else if(ti(N)){if(N.item.type===`function_call`)d[N.output_index]=void 0,f=!0,n.enqueue({type:`tool-input-end`,id:N.item.call_id}),n.enqueue({type:`tool-call`,toolCallId:N.item.call_id,toolName:N.item.name,input:N.item.arguments,providerMetadata:{openai:{itemId:N.item.id}}});else if(N.item.type===`web_search_call`)d[N.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:N.item.id}),n.enqueue({type:`tool-call`,toolCallId:N.item.id,toolName:`web_search`,input:JSON.stringify({action:N.item.action}),providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:N.item.id,toolName:`web_search`,result:{status:N.item.status},providerExecuted:!0});else if(N.item.type===`computer_call`)d[N.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:N.item.id}),n.enqueue({type:`tool-call`,toolCallId:N.item.id,toolName:`computer_use`,input:``,providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:N.item.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:N.item.status||`completed`},providerExecuted:!0});else if(N.item.type===`file_search_call`)d[N.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:N.item.id}),n.enqueue({type:`tool-call`,toolCallId:N.item.id,toolName:`file_search`,input:``,providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:N.item.id,toolName:`file_search`,result:{type:`file_search_tool_result`,status:N.item.status||`completed`,...N.item.queries&&{queries:N.item.queries},...N.item.results&&{results:N.item.results}},providerExecuted:!0});else if(N.item.type===`message`)n.enqueue({type:`text-end`,id:N.item.id});else if(ni(N)){let e=p[N.item.id];for(let t of e.summaryParts)n.enqueue({type:`reasoning-end`,id:`${N.item.id}:${t}`,providerMetadata:{openai:{itemId:N.item.id,reasoningEncryptedContent:(a=N.item.encrypted_content)??null}}});delete p[N.item.id]}}else if(ai(N)){let e=d[N.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:N.delta})}else ii(N)?(u=N.response.id,n.enqueue({type:`response-metadata`,id:N.response.id,timestamp:new Date(N.response.created_at*1e3),modelId:N.response.model})):ei(N)?(n.enqueue({type:`text-delta`,id:N.item_id,delta:N.delta}),(g=(h=e.providerOptions)?.openai)?.logprobs&&N.logprobs&&l.push(N.logprobs)):li(N)?N.summary_index>0&&((_=p[N.item_id])==null||_.summaryParts.push(N.summary_index),n.enqueue({type:`reasoning-start`,id:`${N.item_id}:${N.summary_index}`,providerMetadata:{openai:{itemId:N.item_id,reasoningEncryptedContent:(y=(v=p[N.item_id])?.encryptedContent)??null}}})):ui(N)?n.enqueue({type:`reasoning-delta`,id:`${N.item_id}:${N.summary_index}`,delta:N.delta,providerMetadata:{openai:{itemId:N.item_id}}}):ri(N)?(s=Ir({finishReason:(b=N.response.incomplete_details)?.reason,hasFunctionCall:f}),c.inputTokens=N.response.usage.input_tokens,c.outputTokens=N.response.usage.output_tokens,c.totalTokens=N.response.usage.input_tokens+N.response.usage.output_tokens,c.reasoningTokens=(S=(x=N.response.usage.output_tokens_details)?.reasoning_tokens)??void 0,c.cachedInputTokens=(w=(C=N.response.usage.input_tokens_details)?.cached_tokens)??void 0,typeof N.response.service_tier==`string`&&(m=N.response.service_tier)):ci(N)?N.annotation.type===`url_citation`?n.enqueue({type:`source`,sourceType:`url`,id:(D=(E=(T=o.config).generateId)?.call(T))??B(),url:N.annotation.url,title:N.annotation.title}):N.annotation.type===`file_citation`&&n.enqueue({type:`source`,sourceType:`document`,id:(A=(k=(O=o.config).generateId)?.call(O))??B(),mediaType:`text/plain`,title:(ee=(j=N.annotation.quote)??N.annotation.filename)??`Document`,filename:(M=N.annotation.filename)??N.annotation.file_id}):di(N)&&n.enqueue({type:`error`,error:N})},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}}}},Hr=c.z.object({input_tokens:c.z.number(),input_tokens_details:c.z.object({cached_tokens:c.z.number().nullish()}).nullish(),output_tokens:c.z.number(),output_tokens_details:c.z.object({reasoning_tokens:c.z.number().nullish()}).nullish()}),Ur=c.z.object({type:c.z.literal(`response.output_text.delta`),item_id:c.z.string(),delta:c.z.string(),logprobs:Br.nullish()}),Wr=c.z.object({type:c.z.literal(`error`),code:c.z.string(),message:c.z.string(),param:c.z.string().nullish(),sequence_number:c.z.number()}),Gr=c.z.object({type:c.z.enum([`response.completed`,`response.incomplete`]),response:c.z.object({incomplete_details:c.z.object({reason:c.z.string()}).nullish(),usage:Hr,service_tier:c.z.string().nullish()})}),Kr=c.z.object({type:c.z.literal(`response.created`),response:c.z.object({id:c.z.string(),created_at:c.z.number(),model:c.z.string(),service_tier:c.z.string().nullish()})}),qr=c.z.object({type:c.z.literal(`response.output_item.added`),output_index:c.z.number(),item:c.z.discriminatedUnion(`type`,[c.z.object({type:c.z.literal(`message`),id:c.z.string()}),c.z.object({type:c.z.literal(`reasoning`),id:c.z.string(),encrypted_content:c.z.string().nullish()}),c.z.object({type:c.z.literal(`function_call`),id:c.z.string(),call_id:c.z.string(),name:c.z.string(),arguments:c.z.string()}),c.z.object({type:c.z.literal(`web_search_call`),id:c.z.string(),status:c.z.string(),action:c.z.object({type:c.z.literal(`search`),query:c.z.string().optional()}).nullish()}),c.z.object({type:c.z.literal(`computer_call`),id:c.z.string(),status:c.z.string()}),c.z.object({type:c.z.literal(`file_search_call`),id:c.z.string(),status:c.z.string(),queries:c.z.array(c.z.string()).nullish(),results:c.z.array(c.z.object({attributes:c.z.object({file_id:c.z.string(),filename:c.z.string(),score:c.z.number(),text:c.z.string()})})).optional()})])}),Jr=c.z.object({type:c.z.literal(`response.output_item.done`),output_index:c.z.number(),item:c.z.discriminatedUnion(`type`,[c.z.object({type:c.z.literal(`message`),id:c.z.string()}),c.z.object({type:c.z.literal(`reasoning`),id:c.z.string(),encrypted_content:c.z.string().nullish()}),c.z.object({type:c.z.literal(`function_call`),id:c.z.string(),call_id:c.z.string(),name:c.z.string(),arguments:c.z.string(),status:c.z.literal(`completed`)}),Rr,c.z.object({type:c.z.literal(`computer_call`),id:c.z.string(),status:c.z.literal(`completed`)}),c.z.object({type:c.z.literal(`file_search_call`),id:c.z.string(),status:c.z.literal(`completed`),queries:c.z.array(c.z.string()).nullish(),results:c.z.array(c.z.object({attributes:c.z.object({file_id:c.z.string(),filename:c.z.string(),score:c.z.number(),text:c.z.string()})})).nullish()})])}),Yr=c.z.object({type:c.z.literal(`response.function_call_arguments.delta`),item_id:c.z.string(),output_index:c.z.number(),delta:c.z.string()}),Xr=c.z.object({type:c.z.literal(`response.output_text.annotation.added`),annotation:c.z.discriminatedUnion(`type`,[c.z.object({type:c.z.literal(`url_citation`),url:c.z.string(),title:c.z.string()}),c.z.object({type:c.z.literal(`file_citation`),file_id:c.z.string(),filename:c.z.string().nullish(),index:c.z.number().nullish(),start_index:c.z.number().nullish(),end_index:c.z.number().nullish(),quote:c.z.string().nullish()})])}),Zr=c.z.object({type:c.z.literal(`response.reasoning_summary_part.added`),item_id:c.z.string(),summary_index:c.z.number()}),Qr=c.z.object({type:c.z.literal(`response.reasoning_summary_text.delta`),item_id:c.z.string(),summary_index:c.z.number(),delta:c.z.string()}),$r=c.z.union([Ur,Gr,Kr,qr,Jr,Yr,Xr,Zr,Qr,Wr,c.z.object({type:c.z.string()}).loose()]);function ei(e){return e.type===`response.output_text.delta`}function ti(e){return e.type===`response.output_item.done`}function ni(e){return ti(e)&&e.item.type===`reasoning`}function ri(e){return e.type===`response.completed`||e.type===`response.incomplete`}function ii(e){return e.type===`response.created`}function ai(e){return e.type===`response.function_call_arguments.delta`}function oi(e){return e.type===`response.output_item.added`}function si(e){return oi(e)&&e.item.type===`reasoning`}function ci(e){return e.type===`response.output_text.annotation.added`}function li(e){return e.type===`response.reasoning_summary_part.added`}function ui(e){return e.type===`response.reasoning_summary_text.delta`}function di(e){return e.type===`error`}function fi(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 pi=c.z.object({metadata:c.z.any().nullish(),parallelToolCalls:c.z.boolean().nullish(),previousResponseId:c.z.string().nullish(),store:c.z.boolean().nullish(),user:c.z.string().nullish(),reasoningEffort:c.z.string().nullish(),strictJsonSchema:c.z.boolean().nullish(),instructions:c.z.string().nullish(),reasoningSummary:c.z.string().nullish(),serviceTier:c.z.enum([`auto`,`flex`,`priority`]).nullish(),include:c.z.array(c.z.enum([`reasoning.encrypted_content`,`file_search_call.results`,`message.output_text.logprobs`])).nullish(),textVerbosity:c.z.enum([`low`,`medium`,`high`]).nullish(),promptCacheKey:c.z.string().nullish(),safetyIdentifier:c.z.string().nullish(),logprobs:c.z.union([c.z.boolean(),c.z.number().min(1).max(zr)]).optional()}),mi=c.z.object({instructions:c.z.string().nullish(),speed:c.z.number().min(.25).max(4).default(1).nullish()}),hi=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:mi}),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:xt(),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}}}},gi=c.z.object({include:c.z.array(c.z.string()).optional(),language:c.z.string().optional(),prompt:c.z.string().optional(),temperature:c.z.number().min(0).max(1).default(0).optional(),timestampGranularities:c.z.array(c.z.enum([`word`,`segment`])).default([`segment`]).optional()}),_i={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`},vi=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:gi}),a=new FormData,o=e instanceof Uint8Array?new Blob([e]):new Blob([Et(e)]);a.append(`model`,this.modelId);let s=$e(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 _t({url:this.config.url({path:`/audio/transcriptions`,modelId:this.modelId}),headers:R(this.config.headers(),e.headers),formData:u,failedResponseHandler:$,successfulResponseHandler:q(yi),abortSignal:e.abortSignal,fetch:this.config.fetch}),h=f.language!=null&&f.language in _i?_i[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}}}},yi=c.z.object({text:c.z.string(),language:c.z.string().nullish(),duration:c.z.number().nullish(),words:c.z.array(c.z.object({word:c.z.string(),start:c.z.number(),end:c.z.number()})).nullish(),segments:c.z.array(c.z.object({id:c.z.number(),seek:c.z.number(),start:c.z.number(),end:c.z.number(),text:c.z.string(),tokens:c.z.array(c.z.number()),temperature:c.z.number(),avg_logprob:c.z.number(),compression_ratio:c.z.number(),no_speech_prob:c.z.number()})).nullish()});function bi(e={}){var t,n;let r=(t=Ot(e.baseURL))??`https://api.openai.com/v1`,i=(n=e.name)??`openai`,a=()=>({Authorization:`Bearer ${Qe({apiKey:e.apiKey,environmentVariableName:`OPENAI_API_KEY`,description:`OpenAI`})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers}),o=t=>new nr(t,{provider:`${i}.chat`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),s=t=>new hr(t,{provider:`${i}.completion`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),c=t=>new br(t,{provider:`${i}.embedding`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),l=t=>new wr(t,{provider:`${i}.image`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),u=t=>new vi(t,{provider:`${i}.transcription`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),d=t=>new hi(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 Vr(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=Mr,m}var xi=bi(),Si=c.z.object({user:c.z.string().optional(),reasoningEffort:c.z.string().optional()}),Ci=c.z.object({error:c.z.object({message:c.z.string(),type:c.z.string().nullish(),param:c.z.any().nullish(),code:c.z.union([c.z.string(),c.z.number()]).nullish()})}),wi={errorSchema:Ci,errorToMessage:e=>e.error.message},Ti=c.z.object({prompt_tokens:c.z.number().nullish(),completion_tokens:c.z.number().nullish(),total_tokens:c.z.number().nullish(),prompt_tokens_details:c.z.object({cached_tokens:c.z.number().nullish()}).nullish(),completion_tokens_details:c.z.object({reasoning_tokens:c.z.number().nullish(),accepted_prediction_tokens:c.z.number().nullish(),rejected_prediction_tokens:c.z.number().nullish()}).nullish()}).nullish(),Ei=c.z.object({id:c.z.string().nullish(),created:c.z.number().nullish(),model:c.z.string().nullish(),choices:c.z.array(c.z.object({message:c.z.object({role:c.z.literal(`assistant`).nullish(),content:c.z.string().nullish(),reasoning_content:c.z.string().nullish(),reasoning:c.z.string().nullish(),tool_calls:c.z.array(c.z.object({id:c.z.string().nullish(),function:c.z.object({name:c.z.string(),arguments:c.z.string()})})).nullish()}),finish_reason:c.z.string().nullish()})),usage:Ti}),Di=c.z.object({echo:c.z.boolean().optional(),logitBias:c.z.record(c.z.string(),c.z.number()).optional(),suffix:c.z.string().optional(),user:c.z.string().optional()}),Oi=c.z.object({prompt_tokens:c.z.number(),completion_tokens:c.z.number(),total_tokens:c.z.number()}),ki=c.z.object({id:c.z.string().nullish(),created:c.z.number().nullish(),model:c.z.string().nullish(),choices:c.z.array(c.z.object({text:c.z.string(),finish_reason:c.z.string()})),usage:Oi.nullish()}),Ai=c.z.object({dimensions:c.z.number().optional(),user:c.z.string().optional()}),ji=c.z.object({data:c.z.array(c.z.object({embedding:c.z.array(c.z.number())})),usage:c.z.object({prompt_tokens:c.z.number()}).nullish(),providerMetadata:c.z.record(c.z.string(),c.z.record(c.z.string(),c.z.any())).optional()}),Mi=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)??wi),successfulResponseHandler:q(Ni),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}}}},Ni=c.z.object({data:c.z.array(c.z.object({b64_json:c.z.string()}))});function Pi(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 Fi({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 Ii(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 Li=c.z.object({type:c.z.literal(`web`),country:c.z.string().length(2).optional(),excludedWebsites:c.z.array(c.z.string()).max(5).optional(),allowedWebsites:c.z.array(c.z.string()).max(5).optional(),safeSearch:c.z.boolean().optional()}),Ri=c.z.object({type:c.z.literal(`x`),xHandles:c.z.array(c.z.string()).optional()}),zi=c.z.object({type:c.z.literal(`news`),country:c.z.string().length(2).optional(),excludedWebsites:c.z.array(c.z.string()).max(5).optional(),safeSearch:c.z.boolean().optional()}),Bi=c.z.object({type:c.z.literal(`rss`),links:c.z.array(c.z.string().url()).max(1)}),Vi=c.z.discriminatedUnion(`type`,[Li,Ri,zi,Bi]),Hi=c.z.object({reasoningEffort:c.z.enum([`low`,`high`]).optional(),searchParameters:c.z.object({mode:c.z.enum([`off`,`auto`,`on`]),returnCitations:c.z.boolean().optional(),fromDate:c.z.string().optional(),toDate:c.z.string().optional(),maxSearchResults:c.z.number().min(1).max(50).optional(),sources:c.z.array(Vi).optional()}).optional()}),Ui=c.z.object({error:c.z.object({message:c.z.string(),type:c.z.string().nullish(),param:c.z.any().nullish(),code:c.z.union([c.z.string(),c.z.number()]).nullish()})}),Wi=G({errorSchema:Ui,errorToMessage:e=>e.error.message});function Gi({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 Ki=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:Hi}))??{};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}=Pi(e);g.push(...y);let{tools:b,toolChoice:x,toolWarnings:S}=Gi({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:Wi,successfulResponseHandler:q(Ji),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:Ii(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:{...Fi(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:Wi,successfulResponseHandler:K(Yi),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`,...Fi(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=Ii(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}}}},qi=c.z.object({prompt_tokens:c.z.number(),completion_tokens:c.z.number(),total_tokens:c.z.number(),completion_tokens_details:c.z.object({reasoning_tokens:c.z.number().nullish()}).nullish()}),Ji=c.z.object({id:c.z.string().nullish(),created:c.z.number().nullish(),model:c.z.string().nullish(),choices:c.z.array(c.z.object({message:c.z.object({role:c.z.literal(`assistant`),content:c.z.string().nullish(),reasoning_content:c.z.string().nullish(),tool_calls:c.z.array(c.z.object({id:c.z.string(),type:c.z.literal(`function`),function:c.z.object({name:c.z.string(),arguments:c.z.string()})})).nullish()}),index:c.z.number(),finish_reason:c.z.string().nullish()})),object:c.z.literal(`chat.completion`),usage:qi,citations:c.z.array(c.z.string().url()).nullish()}),Yi=c.z.object({id:c.z.string().nullish(),created:c.z.number().nullish(),model:c.z.string().nullish(),choices:c.z.array(c.z.object({delta:c.z.object({role:c.z.enum([`assistant`]).optional(),content:c.z.string().nullish(),reasoning_content:c.z.string().nullish(),tool_calls:c.z.array(c.z.object({id:c.z.string(),type:c.z.literal(`function`),function:c.z.object({name:c.z.string(),arguments:c.z.string()})})).nullish()}),finish_reason:c.z.string().nullish(),index:c.z.number()})),usage:qi.nullish(),citations:c.z.array(c.z.string().url()).nullish()}),Xi={errorSchema:Ui,errorToMessage:e=>e.error.message};function Zi(e={}){var t;let n=Ot((t=e.baseURL)??`https://api.x.ai/v1`),r=()=>({Authorization:`Bearer ${Qe({apiKey:e.apiKey,environmentVariableName:`XAI_API_KEY`,description:`xAI API key`})}`,...e.headers}),i=t=>new Ki(t,{provider:`xai.chat`,baseURL:n,headers:r,generateId:B,fetch:e.fetch}),a=t=>new Mi(t,{provider:`xai.image`,url:({path:e})=>`${n}${e}`,headers:r,fetch:e.fetch,errorStructure:Xi}),o=e=>i(e);return o.languageModel=i,o.chat=i,o.textEmbeddingModel=e=>{throw new Me({modelId:e,modelType:`textEmbeddingModel`})},o.imageModel=a,o.image=a,o}var Qi=Zi();function $i(e){if(!e.body)throw Error(`Response body is required`);let t=e.headers.get(Fa);if(!t||t===`ui-message`)return e.body.pipeThrough(new TextDecoderStream).pipeThrough(new m).pipeThrough(new TransformStream({async transform(e,t){if(e.data!==`[DONE]`)try{let n=JSON.parse(e.data);t.enqueue(n)}catch(e){t.error(e);return}}}));let n=e=>(0,l.streamText)({model:e,prompt:[{role:`user`,content:[{type:`text`,text:`Hello, world!`}]}]}).toUIMessageStream();switch(t){case`openai-chat`:return n(bi({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`openai-response`:return n(bi({apiKey:`ignored`,fetch:(t,n)=>e}).responses(`fake-model`));case`anthropic`:return n(cn({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`google`:return n(Vn({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`xai`:return n(Zi({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));default:throw Error(`Unsupported response format: ${t}`)}}var ea=e=>{let t=e.split(`/`);return t[0]===``&&t.shift(),t},ta=e=>{let{groups:t,path:n}=na(e),r=ea(n);return ra(r,t)},na=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(e,n)=>{let r=`@${n}`;return t.push([r,e]),r}),{groups:t,path:e}},ra=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[r]=t[n];for(let i=e.length-1;i>=0;i--)if(e[i].includes(r)){e[i]=e[i].replace(r,t[n][1]);break}}return e},ia={},aa=(e,t)=>{if(e===`*`)return`*`;let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return ia[r]||(n[2]?ia[r]=t&&t[0]!==`:`&&t[0]!==`*`?[r,n[1],RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],RegExp(`^${n[2]}$`)]:ia[r]=[e,n[1],!0]),ia[r]}return null},oa=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},sa=e=>oa(e,decodeURI),ca=e=>{let t=e.url,n=t.indexOf(`/`,t.indexOf(`:`)+4),r=n;for(;r<t.length;r++){let e=t.charCodeAt(r);if(e===37){let e=t.indexOf(`?`,r),i=t.slice(n,e===-1?void 0:e);return sa(i.includes(`%25`)?i.replace(/%25/g,`%2525`):i)}else if(e===63)break}return t.slice(n,r)},la=e=>{let t=ca(e);return t.length>1&&t.at(-1)===`/`?t.slice(0,-1):t},ua=(e,t,...n)=>(n.length&&(t=ua(t,...n)),`${e?.[0]===`/`?``:`/`}${e}${t===`/`?``:`${e?.at(-1)===`/`?``:`/`}${t?.[0]===`/`?t.slice(1):t}`}`),da=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(`:`))return null;let t=e.split(`/`),n=[],r=``;return t.forEach(e=>{if(e!==``&&!/\:/.test(e))r+=`/`+e;else if(/\:/.test(e))if(/\?/.test(e)){n.length===0&&r===``?n.push(`/`):n.push(r);let t=e.replace(`?`,``);r+=`/`+t,n.push(r)}else r+=`/`+e}),n.filter((e,t,n)=>n.indexOf(e)===t)},fa=e=>/[%+]/.test(e)?(e.indexOf(`+`)!==-1&&(e=e.replace(/\+/g,` `)),e.indexOf(`%`)===-1?e:oa(e,ga)):e,pa=(e,t,n)=>{let r;if(!n&&t&&!/[%+]/.test(t)){let n=e.indexOf(`?${t}`,8);for(n===-1&&(n=e.indexOf(`&${t}`,8));n!==-1;){let r=e.charCodeAt(n+t.length+1);if(r===61){let r=n+t.length+2,i=e.indexOf(`&`,r);return fa(e.slice(r,i===-1?void 0:i))}else if(r==38||isNaN(r))return``;n=e.indexOf(`&${t}`,n+1)}if(r=/[%+]/.test(e),!r)return}let i={};r??=/[%+]/.test(e);let a=e.indexOf(`?`,8);for(;a!==-1;){let t=e.indexOf(`&`,a+1),o=e.indexOf(`=`,a);o>t&&t!==-1&&(o=-1);let s=e.slice(a+1,o===-1?t===-1?void 0:t:o);if(r&&(s=fa(s)),a=t,s===``)continue;let c;o===-1?c=``:(c=e.slice(o+1,t===-1?void 0:t),r&&(c=fa(c))),n?(i[s]&&Array.isArray(i[s])||(i[s]=[]),i[s].push(c)):i[s]??=c}return t?i[t]:i},ma=pa,ha=(e,t)=>pa(e,t,!0),ga=decodeURIComponent,_a=/^[\w!#$%&'*.^`|~+-]+$/,va=/^[ !#-:<-[\]-~]*$/,ya=(e,t)=>{if(t&&e.indexOf(t)===-1)return{};let n=e.trim().split(`;`),r={};for(let e of n){e=e.trim();let n=e.indexOf(`=`);if(n===-1)continue;let i=e.substring(0,n).trim();if(t&&t!==i||!_a.test(i))continue;let a=e.substring(n+1).trim();if(a.startsWith(`"`)&&a.endsWith(`"`)&&(a=a.slice(1,-1)),va.test(a)&&(r[i]=a.indexOf(`%`)===-1?a:oa(a,ga),t))break}return r},ba=(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},xa=(e,t,n)=>(t=encodeURIComponent(t),ba(e,t,n)),Sa=(e,t)=>(e=e.replace(/\/+$/,``),e+=`/`,t=t.replace(/^\/+/,``),e+t),Ca=(e,t)=>{for(let[n,r]of Object.entries(t)){let t=RegExp(`/:`+n+`(?:{[^/]+})?\\??`);e=e.replace(t,r?`/${r}`:``)}return e},wa=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},Ta=(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 Da(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Oa(e,t){if(!Da(e)&&!Da(t))return t;let n={...e};for(let e in t){let r=t[e];Da(n[e])&&Da(r)?n[e]=Oa(n[e],r):n[e]=r}return n}var ka=(e,t)=>{let n=new Proxy(()=>{},{get(n,r){if(!(typeof r!=`string`||r===`then`))return ka(e,[...t,r])},apply(n,r,i){return e({path:t,args:i})}});return n},Aa=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=wa(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(xa(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=Ca(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})}},ja=(e,t)=>ka(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=Sa(e,s);if(o===`url`){let e=c;return r.args[0]&&(r.args[0].param&&(e=Ca(c,r.args[0].param)),r.args[0].query&&(e=e+`?`+wa(r.args[0].query).toString())),e=Ea(e),new URL(e)}if(o===`ws`){let e=Ta(r.args[0]&&r.args[0].param?Ca(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 Aa(c,o);if(o){t??={};let e=Oa(t,{...r.args[1]});return l.fetch(r.args[0],e)}return l},[]);const Ma=`BLINK_API_SERVER_URL`,Na=process.env[Ma],Pa=ja(Na??``,{fetch:Na?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.`)}}),Fa=`x-blink-stream-response-format`;var Ia=class{options;constructor(e){this.options=e}get baseUrl(){return this.options.baseUrl}async sendMessages(e,t){let n=new URL(`/_agent/send-messages`,this.options.baseUrl),r=await fetch(n.toString(),{method:`POST`,body:JSON.stringify(e),headers:this.options.headers,signal:t?.signal});return r.ok||await this.handleError(r),$i(r)}async experimental_provideCompletions(e){let t=new URL(`/_agent/completions`,this.options.baseUrl),n=await fetch(t.toString(),{method:`POST`,body:JSON.stringify(e),headers:this.options.headers});if(n.ok||await this.handleError(n),n.headers.get(`content-type`)?.includes(`application/json`)){let e=await n.json();return new ReadableStream({start(t){t.enqueue(e),t.close()}})}if(!n.body)throw Error(`Failed to provide completions (${n.status}): ${n.statusText}`);return La(n)}async capabilities(){let e=new URL(`/_agent/capabilities`,this.options.baseUrl),t=await fetch(e.toString(),{headers:this.options.headers});t.ok||await this.handleError(t);let n=await t.json();return n}async provideUIOptions(e,t){let n=new URL(`/_agent/options`,this.options.baseUrl),r=await fetch(n.toString(),{method:`POST`,body:JSON.stringify(e),headers:this.options.headers,signal:t?.signal});r.ok||await this.handleError(r);let i=await r.json();return i}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 La=e=>{let t=new m;if(!e.body)throw Error(`The stream endpoint did not return a body!`);return e.body.pipeThrough(new TextDecoderStream).pipeTo(t.writable).catch(e=>{}),Ra(t.readable)},Ra=e=>{let t=e.pipeThrough(new TransformStream({async transform(e,t){try{let n=JSON.parse(e.data);t.enqueue(n)}catch(e){t.error(e);return}}}));return t};Object.defineProperty(exports,`APIServerURLEnvironmentVariable`,{enumerable:!0,get:function(){return Ma}}),Object.defineProperty(exports,`Client`,{enumerable:!0,get:function(){return Ia}}),Object.defineProperty(exports,`StreamResponseFormatHeader`,{enumerable:!0,get:function(){return Fa}}),Object.defineProperty(exports,`__toESM`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`checkOptionalParameter`,{enumerable:!0,get:function(){return da}}),Object.defineProperty(exports,`client`,{enumerable:!0,get:function(){return Pa}}),Object.defineProperty(exports,`convertResponseToUIMessageStream`,{enumerable:!0,get:function(){return $i}}),Object.defineProperty(exports,`decodeURIComponent_`,{enumerable:!0,get:function(){return ga}}),Object.defineProperty(exports,`getPath`,{enumerable:!0,get:function(){return ca}}),Object.defineProperty(exports,`getPathNoStrict`,{enumerable:!0,get:function(){return la}}),Object.defineProperty(exports,`getPattern`,{enumerable:!0,get:function(){return aa}}),Object.defineProperty(exports,`getQueryParam`,{enumerable:!0,get:function(){return ma}}),Object.defineProperty(exports,`getQueryParams`,{enumerable:!0,get:function(){return ha}}),Object.defineProperty(exports,`mergePath`,{enumerable:!0,get:function(){return ua}}),Object.defineProperty(exports,`parse`,{enumerable:!0,get:function(){return ya}}),Object.defineProperty(exports,`splitPath`,{enumerable:!0,get:function(){return ea}}),Object.defineProperty(exports,`splitRoutingPath`,{enumerable:!0,get:function(){return ta}}),Object.defineProperty(exports,`streamSSE`,{enumerable:!0,get:function(){return La}}),Object.defineProperty(exports,`tryDecode`,{enumerable:!0,get:function(){return oa}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const e=require(`../client-C9uh5T54.cjs`);function t(e){let t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){let e=this.getReader(),t=!1;async function n(n){t=!0;try{n&&await e.cancel?.()}finally{try{e.releaseLock()}catch{}}}return{async next(){if(t)return{done:!0,value:void 0};let{done:r,value:i}=await e.read();return r?(await n(!0),{done:!0,value:void 0}):{done:!1,value:i}},async return(){return await n(!0),{done:!0,value:void 0}},async throw(e){throw await n(!0),e}}},t}var n=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},r=Symbol(),i=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=e instanceof u?e.raw.headers:e.headers,o=i.get(`Content-Type`);return o?.startsWith(`multipart/form-data`)||o?.startsWith(`application/x-www-form-urlencoded`)?a(e,{all:n,dot:r}):{}};async function a(e,t){let n=await e.formData();return n?o(n,t):{}}function o(e,t){let n=Object.create(null);return e.forEach((e,r)=>{let i=t.all||r.endsWith(`[]`);i?s(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{let r=e.includes(`.`);r&&(c(n,e,t),delete n[e])}),n}var s=(e,t,n)=>{e[t]===void 0?t.endsWith(`[]`)?e[t]=[n]:e[t]=n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},c=(e,t,n)=>{let r=e,i=t.split(`.`);i.forEach((e,t)=>{t===i.length-1?r[e]=n:((!r[e]||typeof r[e]!=`object`||Array.isArray(r[e])||r[e]instanceof File)&&(r[e]=Object.create(null)),r=r[e])})},l=t=>e.tryDecode(t,e.decodeURIComponent_),u=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#matchResult=n,this.#validatedData={}}param(e){return e?this.#getDecodedParam(e):this.#getAllDecodedParams()}#getDecodedParam(e){let t=this.#matchResult[0][this.routeIndex][1][e],n=this.#getParamValue(t);return n&&/\%/.test(n)?l(n):n}#getAllDecodedParams(){let e={},t=Object.keys(this.#matchResult[0][this.routeIndex][1]);for(let n of t){let t=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?l(t):t)}return e}#getParamValue(e){return this.#matchResult[1]?this.#matchResult[1][e]:e}query(t){return e.getQueryParam(this.url,t)}queries(t){return e.getQueryParams(this.url,t)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return this.bodyCache.parsedBody??=await i(this,e)}#cachedBody=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let i=Object.keys(t)[0];return i?t[i].then(t=>(i===`json`&&(t=JSON.stringify(t)),new Response(t)[e]())):t[e]=n[e]()};json(){return this.#cachedBody(`text`).then(e=>JSON.parse(e))}text(){return this.#cachedBody(`text`)}arrayBuffer(){return this.#cachedBody(`arrayBuffer`)}blob(){return this.#cachedBody(`blob`)}formData(){return this.#cachedBody(`formData`)}addValidatedData(e,t){this.#validatedData[e]=t}valid(e){return this.#validatedData[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[r](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},d={Stringify:1,BeforeStream:2,Stream:3},f=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},p=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>p(e,t,!1,r,i))).then(()=>i[0]));return n?f(await o,a):o},m=`text/plain; charset=UTF-8`,h=(e,t)=>({"Content-Type":e,...t}),g=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(e,t){this.#rawRequest=e,t&&(this.#executionCtx=t.executionCtx,this.env=t.env,this.#notFoundHandler=t.notFoundHandler,this.#path=t.path,this.#matchResult=t.matchResult)}get req(){return this.#req??=new u(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&`respondWith`in this.#executionCtx)return this.#executionCtx;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error(`This context has no ExecutionContext`)}get res(){return this.#res||=new Response(null,{headers:this.#preparedHeaders??=new Headers})}set res(e){if(this.#res&&e){e=new Response(e.body,e);for(let[t,n]of this.#res.headers.entries()){if(t===`content-type`)continue;if(t===`set-cookie`){let t=this.#res.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}}this.#res=e,this.finalized=!0}render=(...e)=>(this.#renderer??=e=>this.html(e),this.#renderer(...e));setLayout=e=>this.#layout=e;getLayout=()=>this.#layout;setRenderer=e=>{this.#renderer=e};header=(e,t,n)=>{this.finalized&&(this.#res=new Response(this.#res.body,this.#res));let r=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#status=e};set=(e,t)=>{this.#var??=new Map,this.#var.set(e,t)};get=e=>this.#var?this.#var.get(e):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(e,t,n){let r=this.#res?new Headers(this.#res.headers):this.#preparedHeaders??new Headers;if(typeof t==`object`&&`headers`in t){let e=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[t,n]of e)t.toLowerCase()===`set-cookie`?r.append(t,n):r.set(t,n)}if(n)for(let[e,t]of Object.entries(n))if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}let i=typeof t==`number`?t:t?.status??this.#status;return new Response(e,{status:i,headers:r})}newResponse=(...e)=>this.#newResponse(...e);body=(e,t,n)=>this.#newResponse(e,t,n);text=(e,t,n)=>!this.#preparedHeaders&&!this.#status&&!t&&!n&&!this.finalized?new Response(e):this.#newResponse(e,t,h(m,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,h(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,h(`text/html; charset=UTF-8`,n));return typeof e==`object`?p(e,d.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#notFoundHandler??=()=>new Response,this.#notFoundHandler(this))},_=`ALL`,ee=`all`,v=[`get`,`post`,`put`,`delete`,`options`,`patch`],y=`Can not add a route since the matcher is already built.`,b=class extends Error{},te=`__COMPOSED_HANDLER`,x=e=>e.text(`404 Not Found`,404),S=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},C=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(t={}){let n=[...v,ee];n.forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#path=t:this.#addRoute(e,this.#path,t),n.forEach(t=>{this.#addRoute(e,this.#path,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#path=r;for(let t of[e].flat())n.map(e=>{this.#addRoute(t.toUpperCase(),this.#path,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#path=e:(this.#path=`*`,t.unshift(e)),t.forEach(e=>{this.#addRoute(_,this.#path,e)}),this);let{strict:r,...i}=t;Object.assign(this,i),this.getPath=r??!0?t.getPath??e.getPath:e.getPathNoStrict}#clone(){let e=new C({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=x;errorHandler=S;route(e,t){let r=this.basePath(e);return t.routes.map(e=>{let i;t.errorHandler===S?i=e.handler:(i=async(r,i)=>(await n([],t.errorHandler)(r,()=>e.handler(r,i))).res,i[te]=e.handler),r.#addRoute(e.method,e.path,i)}),this}basePath(t){let n=this.#clone();return n._basePath=e.mergePath(this._basePath,t),n}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#notFoundHandler=e,this);mount(t,n,r){let i,a;r&&(typeof r==`function`?a=r:(a=r.optionHandler,i=r.replaceRequest===!1?e=>e:r.replaceRequest));let o=a?e=>{let t=a(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};i||=(()=>{let n=e.mergePath(this._basePath,t),r=n===`/`?0:n.length;return e=>{let t=new URL(e.url);return t.pathname=t.pathname.slice(r)||`/`,new Request(t,e)}})();let s=async(e,t)=>{let r=await n(i(e.req.raw),...o(e));if(r)return r;await t()};return this.#addRoute(_,e.mergePath(t,`*`),s),this}#addRoute(t,n,r){t=t.toUpperCase(),n=e.mergePath(this._basePath,n);let i={basePath:this._basePath,path:n,method:t,handler:r};this.router.add(t,n,[r,i]),this.routes.push(i)}#handleError(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#dispatch(e,t,r,i){if(i===`HEAD`)return(async()=>new Response(null,await this.#dispatch(e,t,r,`GET`)))();let a=this.getPath(e,{env:r}),o=this.router.match(i,a),s=new g(e,{path:a,matchResult:o,env:r,executionCtx:t,notFoundHandler:this.#notFoundHandler});if(o[0].length===1){let e;try{e=o[0][0][0][0](s,async()=>{s.res=await this.#notFoundHandler(s)})}catch(e){return this.#handleError(e,s)}return e instanceof Promise?e.then(e=>e||(s.finalized?s.res:this.#notFoundHandler(s))).catch(e=>this.#handleError(e,s)):e??this.#notFoundHandler(s)}let c=n(o[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let e=await c(s);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#handleError(e,s)}})()}fetch=(e,...t)=>this.#dispatch(e,t[1],t[0],e.method);request=(t,n,r,i)=>t instanceof Request?this.fetch(n?new Request(t,n):t,r,i):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${e.mergePath(`/`,t)}`,n),r,i));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#dispatch(e.request,e,void 0,e.request.method))})}},w=`[^/]+`,T=`.*`,E=`(?:|/.*)`,D=Symbol(),O=new Set(`.\\+*[^]$()`);function k(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===T||e===E?1:t===T||t===E?-1:e===w?1:t===w?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var A=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw D;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,T]:[``,``,w]:a===`/*`?[``,``,E]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||w;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw D;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==T&&e!==E))throw D;if(i)return;c=this.#children[t]=new A,e!==``&&(c.#varIndex=r.varIndex++)}!i&&e!==``&&n.push([e,c.#varIndex])}else if(c=this.#children[a],!c){if(Object.keys(this.#children).some(e=>e.length>1&&e!==T&&e!==E))throw D;if(i)return;c=this.#children[a]=new A}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(k),t=e.map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:O.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#index==`number`&&t.unshift(`#${this.#index}`),t.length===0?``:t.length===1?t[0]:`(?:`+t.join(`|`)+`)`}},j=class{#context={varIndex:0};#root=new A;insert(e,t,n){let r=[],i=[];for(let t=0;;){let n=!1;if(e=e.replace(/\{[^}]+\}/g,e=>{let r=`@\\${t}`;return i[t]=[r,e],t++,n=!0,r}),!n)break}let a=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=i.length-1;e>=0;e--){let[t]=i[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,i[e][1]);break}}return this.#root.insert(a,t,r,this.#context,n),r}buildRegExp(){let e=this.#root.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},M=[],N=[/^$/,[],Object.create(null)],P=Object.create(null);function F(e){return P[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function I(){P=Object.create(null)}function ne(e){let t=new j,n=[];if(e.length===0)return N;let r=e.map(e=>[!/\*|\/:/.test(e[0]),...e]).sort(([e,t],[n,r])=>e?1:n?-1:t.length-r.length),i=Object.create(null);for(let e=0,a=-1,o=r.length;e<o;e++){let[o,s,c]=r[e];o?i[s]=[c.map(([e])=>[e,Object.create(null)]),M]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===D?new b(s):e}o||(n[a]=c.map(([e,t])=>{let n=Object.create(null);for(--t;t>=0;t--){let[e,r]=l[t];n[e]=r}return[e,n]}))}let[a,o,s]=t.buildRegExp();for(let e=0,t=n.length;e<t;e++)for(let t=0,r=n[e].length;t<r;t++){let r=n[e][t]?.[1];if(!r)continue;let i=Object.keys(r);for(let e=0,t=i.length;e<t;e++)r[i[e]]=s[r[i[e]]]}let c=[];for(let e in o)c[e]=n[o[e]];return[a,c,i]}function L(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(F(n).test(t))return[...e[n]]}}var re=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[_]:Object.create(null)},this.#routes={[_]:Object.create(null)}}add(t,n,r){let i=this.#middleware,a=this.#routes;if(!i||!a)throw Error(y);i[t]||[i,a].forEach(e=>{e[t]=Object.create(null),Object.keys(e[_]).forEach(n=>{e[t][n]=[...e[_][n]]})}),n===`/*`&&(n=`*`);let o=(n.match(/\/:/g)||[]).length;if(/\*$/.test(n)){let e=F(n);t===_?Object.keys(i).forEach(e=>{i[e][n]||=L(i[e],n)||L(i[_],n)||[]}):i[t][n]||=L(i[t],n)||L(i[_],n)||[],Object.keys(i).forEach(n=>{(t===_||t===n)&&Object.keys(i[n]).forEach(t=>{e.test(t)&&i[n][t].push([r,o])})}),Object.keys(a).forEach(n=>{(t===_||t===n)&&Object.keys(a[n]).forEach(t=>e.test(t)&&a[n][t].push([r,o]))});return}let s=e.checkOptionalParameter(n)||[n];for(let e=0,n=s.length;e<n;e++){let c=s[e];Object.keys(a).forEach(s=>{(t===_||t===s)&&(a[s][c]||=[...L(i[s],c)||L(i[_],c)||[]],a[s][c].push([r,o-n+e+1]))})}}match(e,t){I();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[_],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],M];let o=a.indexOf(``,1);return[r[1][o],a]},this.match(e,t)}#buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach(t=>{e[t]||=this.#buildMatcher(t)}),this.#middleware=this.#routes=void 0,e}#buildMatcher(e){let t=[],n=e===_;return[this.#middleware,this.#routes].forEach(r=>{let i=r[e]?Object.keys(r[e]).map(t=>[t,r[e][t]]):[];i.length===0?e!==_&&t.push(...Object.keys(r[_]).map(e=>[e,r[_][e]])):(n||=!0,t.push(...i))}),n?ne(t):null}},R=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(y);this.#routes.push([e,t,n])}match(e,t){if(!this.#routes)throw Error(`Fatal error`);let n=this.#routers,r=this.#routes,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof b)continue;throw e}this.match=i.match.bind(i),this.#routers=[i],this.#routes=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw Error(`No active router has been determined yet.`);return this.#routers[0]}},z=Object.create(null),B=class{#methods;#children;#patterns;#order=0;#params=z;constructor(e,t,n){if(this.#children=n||Object.create(null),this.#methods=[],e&&t){let n=Object.create(null);n[e]={handler:t,possibleKeys:[],score:0},this.#methods=[n]}this.#patterns=[]}insert(t,n,r){this.#order=++this.#order;let i=this,a=e.splitRoutingPath(n),o=[];for(let t=0,n=a.length;t<n;t++){let n=a[t],r=a[t+1],s=e.getPattern(n,r),c=Array.isArray(s)?s[0]:n;if(c in i.#children){i=i.#children[c],s&&o.push(s[1]);continue}i.#children[c]=new B,s&&(i.#patterns.push(s),o.push(s[1])),i=i.#children[c]}return i.#methods.push({[t]:{handler:r,possibleKeys:o.filter((e,t,n)=>n.indexOf(e)===t),score:this.#order}}),i}#getHandlerSets(e,t,n,r){let i=[];for(let a=0,o=e.#methods.length;a<o;a++){let o=e.#methods[a],s=o[t]||o[_],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==z||r&&r!==z))for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e],i=c[s.score];s.params[t]=r?.[t]&&!i?r[t]:n[t]??r?.[t],c[s.score]=!0}}return i}search(t,n){let r=[];this.#params=z;let i=this,a=[i],o=e.splitPath(n),s=[];for(let e=0,n=o.length;e<n;e++){let i=o[e],c=e===n-1,l=[];for(let n=0,u=a.length;n<u;n++){let u=a[n],d=u.#children[i];d&&(d.#params=u.#params,c?(d.#children[`*`]&&r.push(...this.#getHandlerSets(d.#children[`*`],t,u.#params)),r.push(...this.#getHandlerSets(d,t,u.#params))):l.push(d));for(let n=0,a=u.#patterns.length;n<a;n++){let a=u.#patterns[n],d=u.#params===z?{}:{...u.#params};if(a===`*`){let e=u.#children[`*`];e&&(r.push(...this.#getHandlerSets(e,t,u.#params)),e.#params=d,l.push(e));continue}let[f,p,m]=a;if(!i&&!(m instanceof RegExp))continue;let h=u.#children[f],g=o.slice(e).join(`/`);if(m instanceof RegExp){let e=m.exec(g);if(e){if(d[p]=e[0],r.push(...this.#getHandlerSets(h,t,u.#params,d)),Object.keys(h.#children).length){h.#params=d;let t=e[0].match(/\//)?.length??0,n=s[t]||=[];n.push(h)}continue}}(m===!0||m.test(i))&&(d[p]=i,c?(r.push(...this.#getHandlerSets(h,t,d,u.#params)),h.#children[`*`]&&r.push(...this.#getHandlerSets(h.#children[`*`],t,d,u.#params))):(h.#params=d,l.push(h)))}}a=l.concat(s.shift()??[])}return r.length>1&&r.sort((e,t)=>e.score-t.score),[r.map(({handler:e,params:t})=>[e,t])]}},V=class{name=`TrieRouter`;#node;constructor(){this.#node=new B}add(t,n,r){let i=e.checkOptionalParameter(n);if(i){for(let e=0,n=i.length;e<n;e++)this.#node.insert(t,i[e],r);return}this.#node.insert(t,n,r)}match(e,t){return this.#node.search(e,t)}},H=class extends C{constructor(e={}){super(e),this.router=e.router??new R({routers:[new re,new V]})}},U=(t,n,r)=>{let i=t.req.raw.headers.get(`Cookie`);if(typeof n==`string`){if(!i)return;let t=n;r===`secure`?t=`__Secure-`+n:r===`host`&&(t=`__Host-`+n);let a=e.parse(i,t);return a[t]}if(!i)return{};let a=e.parse(i);return a},W=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){if(this.res){let e=new Response(this.res.body,{status:this.status,headers:this.res.headers});return e}return new Response(this.message,{status:this.status})}},G=(e,t)=>{let n=new Response(e,{headers:{"Content-Type":t}});return n.formData()},K=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,q=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,J=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,Y=(e,t)=>async(n,r)=>{let i={},a=n.req.header(`Content-Type`);switch(e){case`json`:if(!a||!K.test(a))break;try{i=await n.req.json()}catch{throw new W(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(q.test(a)||J.test(a)))break;let e;if(n.req.bodyCache.formData)e=await n.req.bodyCache.formData;else try{let t=await n.req.arrayBuffer();e=await G(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new W(400,{message:t})}let t={};e.forEach((e,n)=>{n.endsWith(`[]`)?(t[n]??=[]).push(e):Array.isArray(t[n])?t[n].push(e):n in t?t[n]=[t[n],e]:t[n]=e}),i=t;break}case`query`:i=Object.fromEntries(Object.entries(n.req.queries()).map(([e,t])=>t.length===1?[e,t[0]]:[e,t]));break;case`param`:i=n.req.param();break;case`header`:i=n.req.header();break;case`cookie`:i=U(n);break}let o=await t(i,n);if(o instanceof Response)return o;n.req.addValidatedData(e,o),await r()};const X=(e,t)=>e.json({error:t},400),Z=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>128?{key:t,err:`Key is too long. Max length is 128 characters.`}:{key:t}},Q=()=>new H,ie=Q().get(`/kv/:key`,async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let r=await e.env.storage.kv.get(t);return e.json({value:r},200)}).post(`/kv/:key`,Y(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>1024?X(t,`Value is too long. Max length is 1024 characters.`):{value:n}:X(t,`Value must be a string`):X(t,`Value is required`)}),async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let{value:r}=e.req.valid(`json`);return await e.env.storage.kv.set(t,r),e.body(null,204)}).delete(`/kv/:key`,async e=>{let{key:t,err:n}=Z(e);return n?X(e,n):(await e.env.storage.kv.del(t),e.body(null,204))}),$=e=>{let t=e.req.param(`id`);return t?t.length>128?{id:t,err:`ID is too long. Max length is 128 characters.`}:{id:t}:{id:t,err:`ID is required`}},ae=Q().basePath(`/:id`).post(`/`,async e=>{let{id:t,err:n}=$(e);if(n)return X(e,n);let r=await e.env.chat.upsert(t);return e.json({id:r.id},200)}).post(`/sendMessages`,Y(`json`,(e,t)=>{let n=e.messages;if(!n)return X(t,`Messages are required`);if(!Array.isArray(n))return X(t,`Messages must be an array`);if(n.length===0)return X(t,`Messages must not be empty`);let r=e.behavior;return r!==`enqueue`&&r!==`interrupt`&&r!==`append`?X(t,`Invalid behavior`):{messages:n,behavior:r}}),async e=>{let{id:t,err:n}=$(e);if(n)return X(e,n);let{messages:r,behavior:i}=e.req.valid(`json`);try{await e.env.chat.sendMessages(t,{messages:r,behavior:i})}catch(t){return X(e,t instanceof Error?t.message:`Unknown error`)}return e.body(null,204)}),oe=new H().route(`/storage`,ie).route(`/chat`,ae);exports.APIServerURLEnvironmentVariable=e.APIServerURLEnvironmentVariable,exports.Client=e.Client,exports.StreamResponseFormatHeader=e.StreamResponseFormatHeader,exports.convertResponseToUIMessageStream=e.convertResponseToUIMessageStream,exports.createAsyncIterableStream=t,exports.streamSSE=e.streamSSE;
|
|
1
|
+
const e=require(`../client-DFaZjb1-.cjs`);function t(e){let t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){let e=this.getReader(),t=!1;async function n(n){t=!0;try{n&&await e.cancel?.()}finally{try{e.releaseLock()}catch{}}}return{async next(){if(t)return{done:!0,value:void 0};let{done:r,value:i}=await e.read();return r?(await n(!0),{done:!0,value:void 0}):{done:!1,value:i}},async return(){return await n(!0),{done:!0,value:void 0}},async throw(e){throw await n(!0),e}}},t}var n=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},r=Symbol(),i=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=e instanceof u?e.raw.headers:e.headers,o=i.get(`Content-Type`);return o?.startsWith(`multipart/form-data`)||o?.startsWith(`application/x-www-form-urlencoded`)?a(e,{all:n,dot:r}):{}};async function a(e,t){let n=await e.formData();return n?o(n,t):{}}function o(e,t){let n=Object.create(null);return e.forEach((e,r)=>{let i=t.all||r.endsWith(`[]`);i?s(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{let r=e.includes(`.`);r&&(c(n,e,t),delete n[e])}),n}var s=(e,t,n)=>{e[t]===void 0?t.endsWith(`[]`)?e[t]=[n]:e[t]=n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},c=(e,t,n)=>{let r=e,i=t.split(`.`);i.forEach((e,t)=>{t===i.length-1?r[e]=n:((!r[e]||typeof r[e]!=`object`||Array.isArray(r[e])||r[e]instanceof File)&&(r[e]=Object.create(null)),r=r[e])})},l=t=>e.tryDecode(t,e.decodeURIComponent_),u=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#matchResult=n,this.#validatedData={}}param(e){return e?this.#getDecodedParam(e):this.#getAllDecodedParams()}#getDecodedParam(e){let t=this.#matchResult[0][this.routeIndex][1][e],n=this.#getParamValue(t);return n&&/\%/.test(n)?l(n):n}#getAllDecodedParams(){let e={},t=Object.keys(this.#matchResult[0][this.routeIndex][1]);for(let n of t){let t=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?l(t):t)}return e}#getParamValue(e){return this.#matchResult[1]?this.#matchResult[1][e]:e}query(t){return e.getQueryParam(this.url,t)}queries(t){return e.getQueryParams(this.url,t)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return this.bodyCache.parsedBody??=await i(this,e)}#cachedBody=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let i=Object.keys(t)[0];return i?t[i].then(t=>(i===`json`&&(t=JSON.stringify(t)),new Response(t)[e]())):t[e]=n[e]()};json(){return this.#cachedBody(`text`).then(e=>JSON.parse(e))}text(){return this.#cachedBody(`text`)}arrayBuffer(){return this.#cachedBody(`arrayBuffer`)}blob(){return this.#cachedBody(`blob`)}formData(){return this.#cachedBody(`formData`)}addValidatedData(e,t){this.#validatedData[e]=t}valid(e){return this.#validatedData[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[r](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},d={Stringify:1,BeforeStream:2,Stream:3},f=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},p=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>p(e,t,!1,r,i))).then(()=>i[0]));return n?f(await o,a):o},m=`text/plain; charset=UTF-8`,h=(e,t)=>({"Content-Type":e,...t}),g=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(e,t){this.#rawRequest=e,t&&(this.#executionCtx=t.executionCtx,this.env=t.env,this.#notFoundHandler=t.notFoundHandler,this.#path=t.path,this.#matchResult=t.matchResult)}get req(){return this.#req??=new u(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&`respondWith`in this.#executionCtx)return this.#executionCtx;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error(`This context has no ExecutionContext`)}get res(){return this.#res||=new Response(null,{headers:this.#preparedHeaders??=new Headers})}set res(e){if(this.#res&&e){e=new Response(e.body,e);for(let[t,n]of this.#res.headers.entries()){if(t===`content-type`)continue;if(t===`set-cookie`){let t=this.#res.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}}this.#res=e,this.finalized=!0}render=(...e)=>(this.#renderer??=e=>this.html(e),this.#renderer(...e));setLayout=e=>this.#layout=e;getLayout=()=>this.#layout;setRenderer=e=>{this.#renderer=e};header=(e,t,n)=>{this.finalized&&(this.#res=new Response(this.#res.body,this.#res));let r=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#status=e};set=(e,t)=>{this.#var??=new Map,this.#var.set(e,t)};get=e=>this.#var?this.#var.get(e):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(e,t,n){let r=this.#res?new Headers(this.#res.headers):this.#preparedHeaders??new Headers;if(typeof t==`object`&&`headers`in t){let e=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[t,n]of e)t.toLowerCase()===`set-cookie`?r.append(t,n):r.set(t,n)}if(n)for(let[e,t]of Object.entries(n))if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}let i=typeof t==`number`?t:t?.status??this.#status;return new Response(e,{status:i,headers:r})}newResponse=(...e)=>this.#newResponse(...e);body=(e,t,n)=>this.#newResponse(e,t,n);text=(e,t,n)=>!this.#preparedHeaders&&!this.#status&&!t&&!n&&!this.finalized?new Response(e):this.#newResponse(e,t,h(m,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,h(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,h(`text/html; charset=UTF-8`,n));return typeof e==`object`?p(e,d.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#notFoundHandler??=()=>new Response,this.#notFoundHandler(this))},_=`ALL`,ee=`all`,v=[`get`,`post`,`put`,`delete`,`options`,`patch`],y=`Can not add a route since the matcher is already built.`,b=class extends Error{},te=`__COMPOSED_HANDLER`,x=e=>e.text(`404 Not Found`,404),S=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},C=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(t={}){let n=[...v,ee];n.forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#path=t:this.#addRoute(e,this.#path,t),n.forEach(t=>{this.#addRoute(e,this.#path,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#path=r;for(let t of[e].flat())n.map(e=>{this.#addRoute(t.toUpperCase(),this.#path,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#path=e:(this.#path=`*`,t.unshift(e)),t.forEach(e=>{this.#addRoute(_,this.#path,e)}),this);let{strict:r,...i}=t;Object.assign(this,i),this.getPath=r??!0?t.getPath??e.getPath:e.getPathNoStrict}#clone(){let e=new C({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=x;errorHandler=S;route(e,t){let r=this.basePath(e);return t.routes.map(e=>{let i;t.errorHandler===S?i=e.handler:(i=async(r,i)=>(await n([],t.errorHandler)(r,()=>e.handler(r,i))).res,i[te]=e.handler),r.#addRoute(e.method,e.path,i)}),this}basePath(t){let n=this.#clone();return n._basePath=e.mergePath(this._basePath,t),n}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#notFoundHandler=e,this);mount(t,n,r){let i,a;r&&(typeof r==`function`?a=r:(a=r.optionHandler,i=r.replaceRequest===!1?e=>e:r.replaceRequest));let o=a?e=>{let t=a(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};i||=(()=>{let n=e.mergePath(this._basePath,t),r=n===`/`?0:n.length;return e=>{let t=new URL(e.url);return t.pathname=t.pathname.slice(r)||`/`,new Request(t,e)}})();let s=async(e,t)=>{let r=await n(i(e.req.raw),...o(e));if(r)return r;await t()};return this.#addRoute(_,e.mergePath(t,`*`),s),this}#addRoute(t,n,r){t=t.toUpperCase(),n=e.mergePath(this._basePath,n);let i={basePath:this._basePath,path:n,method:t,handler:r};this.router.add(t,n,[r,i]),this.routes.push(i)}#handleError(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#dispatch(e,t,r,i){if(i===`HEAD`)return(async()=>new Response(null,await this.#dispatch(e,t,r,`GET`)))();let a=this.getPath(e,{env:r}),o=this.router.match(i,a),s=new g(e,{path:a,matchResult:o,env:r,executionCtx:t,notFoundHandler:this.#notFoundHandler});if(o[0].length===1){let e;try{e=o[0][0][0][0](s,async()=>{s.res=await this.#notFoundHandler(s)})}catch(e){return this.#handleError(e,s)}return e instanceof Promise?e.then(e=>e||(s.finalized?s.res:this.#notFoundHandler(s))).catch(e=>this.#handleError(e,s)):e??this.#notFoundHandler(s)}let c=n(o[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let e=await c(s);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#handleError(e,s)}})()}fetch=(e,...t)=>this.#dispatch(e,t[1],t[0],e.method);request=(t,n,r,i)=>t instanceof Request?this.fetch(n?new Request(t,n):t,r,i):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${e.mergePath(`/`,t)}`,n),r,i));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#dispatch(e.request,e,void 0,e.request.method))})}},w=`[^/]+`,T=`.*`,E=`(?:|/.*)`,D=Symbol(),O=new Set(`.\\+*[^]$()`);function k(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===T||e===E?1:t===T||t===E?-1:e===w?1:t===w?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var A=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw D;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,T]:[``,``,w]:a===`/*`?[``,``,E]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||w;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw D;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==T&&e!==E))throw D;if(i)return;c=this.#children[t]=new A,e!==``&&(c.#varIndex=r.varIndex++)}!i&&e!==``&&n.push([e,c.#varIndex])}else if(c=this.#children[a],!c){if(Object.keys(this.#children).some(e=>e.length>1&&e!==T&&e!==E))throw D;if(i)return;c=this.#children[a]=new A}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(k),t=e.map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:O.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#index==`number`&&t.unshift(`#${this.#index}`),t.length===0?``:t.length===1?t[0]:`(?:`+t.join(`|`)+`)`}},j=class{#context={varIndex:0};#root=new A;insert(e,t,n){let r=[],i=[];for(let t=0;;){let n=!1;if(e=e.replace(/\{[^}]+\}/g,e=>{let r=`@\\${t}`;return i[t]=[r,e],t++,n=!0,r}),!n)break}let a=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=i.length-1;e>=0;e--){let[t]=i[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,i[e][1]);break}}return this.#root.insert(a,t,r,this.#context,n),r}buildRegExp(){let e=this.#root.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},M=[],N=[/^$/,[],Object.create(null)],P=Object.create(null);function F(e){return P[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function I(){P=Object.create(null)}function ne(e){let t=new j,n=[];if(e.length===0)return N;let r=e.map(e=>[!/\*|\/:/.test(e[0]),...e]).sort(([e,t],[n,r])=>e?1:n?-1:t.length-r.length),i=Object.create(null);for(let e=0,a=-1,o=r.length;e<o;e++){let[o,s,c]=r[e];o?i[s]=[c.map(([e])=>[e,Object.create(null)]),M]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===D?new b(s):e}o||(n[a]=c.map(([e,t])=>{let n=Object.create(null);for(--t;t>=0;t--){let[e,r]=l[t];n[e]=r}return[e,n]}))}let[a,o,s]=t.buildRegExp();for(let e=0,t=n.length;e<t;e++)for(let t=0,r=n[e].length;t<r;t++){let r=n[e][t]?.[1];if(!r)continue;let i=Object.keys(r);for(let e=0,t=i.length;e<t;e++)r[i[e]]=s[r[i[e]]]}let c=[];for(let e in o)c[e]=n[o[e]];return[a,c,i]}function L(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(F(n).test(t))return[...e[n]]}}var re=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[_]:Object.create(null)},this.#routes={[_]:Object.create(null)}}add(t,n,r){let i=this.#middleware,a=this.#routes;if(!i||!a)throw Error(y);i[t]||[i,a].forEach(e=>{e[t]=Object.create(null),Object.keys(e[_]).forEach(n=>{e[t][n]=[...e[_][n]]})}),n===`/*`&&(n=`*`);let o=(n.match(/\/:/g)||[]).length;if(/\*$/.test(n)){let e=F(n);t===_?Object.keys(i).forEach(e=>{i[e][n]||=L(i[e],n)||L(i[_],n)||[]}):i[t][n]||=L(i[t],n)||L(i[_],n)||[],Object.keys(i).forEach(n=>{(t===_||t===n)&&Object.keys(i[n]).forEach(t=>{e.test(t)&&i[n][t].push([r,o])})}),Object.keys(a).forEach(n=>{(t===_||t===n)&&Object.keys(a[n]).forEach(t=>e.test(t)&&a[n][t].push([r,o]))});return}let s=e.checkOptionalParameter(n)||[n];for(let e=0,n=s.length;e<n;e++){let c=s[e];Object.keys(a).forEach(s=>{(t===_||t===s)&&(a[s][c]||=[...L(i[s],c)||L(i[_],c)||[]],a[s][c].push([r,o-n+e+1]))})}}match(e,t){I();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[_],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],M];let o=a.indexOf(``,1);return[r[1][o],a]},this.match(e,t)}#buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach(t=>{e[t]||=this.#buildMatcher(t)}),this.#middleware=this.#routes=void 0,e}#buildMatcher(e){let t=[],n=e===_;return[this.#middleware,this.#routes].forEach(r=>{let i=r[e]?Object.keys(r[e]).map(t=>[t,r[e][t]]):[];i.length===0?e!==_&&t.push(...Object.keys(r[_]).map(e=>[e,r[_][e]])):(n||=!0,t.push(...i))}),n?ne(t):null}},R=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(y);this.#routes.push([e,t,n])}match(e,t){if(!this.#routes)throw Error(`Fatal error`);let n=this.#routers,r=this.#routes,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof b)continue;throw e}this.match=i.match.bind(i),this.#routers=[i],this.#routes=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw Error(`No active router has been determined yet.`);return this.#routers[0]}},z=Object.create(null),B=class{#methods;#children;#patterns;#order=0;#params=z;constructor(e,t,n){if(this.#children=n||Object.create(null),this.#methods=[],e&&t){let n=Object.create(null);n[e]={handler:t,possibleKeys:[],score:0},this.#methods=[n]}this.#patterns=[]}insert(t,n,r){this.#order=++this.#order;let i=this,a=e.splitRoutingPath(n),o=[];for(let t=0,n=a.length;t<n;t++){let n=a[t],r=a[t+1],s=e.getPattern(n,r),c=Array.isArray(s)?s[0]:n;if(c in i.#children){i=i.#children[c],s&&o.push(s[1]);continue}i.#children[c]=new B,s&&(i.#patterns.push(s),o.push(s[1])),i=i.#children[c]}return i.#methods.push({[t]:{handler:r,possibleKeys:o.filter((e,t,n)=>n.indexOf(e)===t),score:this.#order}}),i}#getHandlerSets(e,t,n,r){let i=[];for(let a=0,o=e.#methods.length;a<o;a++){let o=e.#methods[a],s=o[t]||o[_],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==z||r&&r!==z))for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e],i=c[s.score];s.params[t]=r?.[t]&&!i?r[t]:n[t]??r?.[t],c[s.score]=!0}}return i}search(t,n){let r=[];this.#params=z;let i=this,a=[i],o=e.splitPath(n),s=[];for(let e=0,n=o.length;e<n;e++){let i=o[e],c=e===n-1,l=[];for(let n=0,u=a.length;n<u;n++){let u=a[n],d=u.#children[i];d&&(d.#params=u.#params,c?(d.#children[`*`]&&r.push(...this.#getHandlerSets(d.#children[`*`],t,u.#params)),r.push(...this.#getHandlerSets(d,t,u.#params))):l.push(d));for(let n=0,a=u.#patterns.length;n<a;n++){let a=u.#patterns[n],d=u.#params===z?{}:{...u.#params};if(a===`*`){let e=u.#children[`*`];e&&(r.push(...this.#getHandlerSets(e,t,u.#params)),e.#params=d,l.push(e));continue}let[f,p,m]=a;if(!i&&!(m instanceof RegExp))continue;let h=u.#children[f],g=o.slice(e).join(`/`);if(m instanceof RegExp){let e=m.exec(g);if(e){if(d[p]=e[0],r.push(...this.#getHandlerSets(h,t,u.#params,d)),Object.keys(h.#children).length){h.#params=d;let t=e[0].match(/\//)?.length??0,n=s[t]||=[];n.push(h)}continue}}(m===!0||m.test(i))&&(d[p]=i,c?(r.push(...this.#getHandlerSets(h,t,d,u.#params)),h.#children[`*`]&&r.push(...this.#getHandlerSets(h.#children[`*`],t,d,u.#params))):(h.#params=d,l.push(h)))}}a=l.concat(s.shift()??[])}return r.length>1&&r.sort((e,t)=>e.score-t.score),[r.map(({handler:e,params:t})=>[e,t])]}},V=class{name=`TrieRouter`;#node;constructor(){this.#node=new B}add(t,n,r){let i=e.checkOptionalParameter(n);if(i){for(let e=0,n=i.length;e<n;e++)this.#node.insert(t,i[e],r);return}this.#node.insert(t,n,r)}match(e,t){return this.#node.search(e,t)}},H=class extends C{constructor(e={}){super(e),this.router=e.router??new R({routers:[new re,new V]})}},U=(t,n,r)=>{let i=t.req.raw.headers.get(`Cookie`);if(typeof n==`string`){if(!i)return;let t=n;r===`secure`?t=`__Secure-`+n:r===`host`&&(t=`__Host-`+n);let a=e.parse(i,t);return a[t]}if(!i)return{};let a=e.parse(i);return a},W=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){if(this.res){let e=new Response(this.res.body,{status:this.status,headers:this.res.headers});return e}return new Response(this.message,{status:this.status})}},G=(e,t)=>{let n=new Response(e,{headers:{"Content-Type":t}});return n.formData()},K=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,q=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,J=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,Y=(e,t)=>async(n,r)=>{let i={},a=n.req.header(`Content-Type`);switch(e){case`json`:if(!a||!K.test(a))break;try{i=await n.req.json()}catch{throw new W(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(q.test(a)||J.test(a)))break;let e;if(n.req.bodyCache.formData)e=await n.req.bodyCache.formData;else try{let t=await n.req.arrayBuffer();e=await G(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new W(400,{message:t})}let t={};e.forEach((e,n)=>{n.endsWith(`[]`)?(t[n]??=[]).push(e):Array.isArray(t[n])?t[n].push(e):n in t?t[n]=[t[n],e]:t[n]=e}),i=t;break}case`query`:i=Object.fromEntries(Object.entries(n.req.queries()).map(([e,t])=>t.length===1?[e,t[0]]:[e,t]));break;case`param`:i=n.req.param();break;case`header`:i=n.req.header();break;case`cookie`:i=U(n);break}let o=await t(i,n);if(o instanceof Response)return o;n.req.addValidatedData(e,o),await r()};const X=(e,t)=>e.json({error:t},400),Z=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>128?{key:t,err:`Key is too long. Max length is 128 characters.`}:{key:t}},Q=()=>new H,ie=Q().get(`/kv/:key`,async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let r=await e.env.storage.kv.get(t);return e.json({value:r},200)}).post(`/kv/:key`,Y(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>1024?X(t,`Value is too long. Max length is 1024 characters.`):{value:n}:X(t,`Value must be a string`):X(t,`Value is required`)}),async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let{value:r}=e.req.valid(`json`);return await e.env.storage.kv.set(t,r),e.body(null,204)}).delete(`/kv/:key`,async e=>{let{key:t,err:n}=Z(e);return n?X(e,n):(await e.env.storage.kv.del(t),e.body(null,204))}),$=e=>{let t=e.req.param(`id`);return t?t.length>128?{id:t,err:`ID is too long. Max length is 128 characters.`}:{id:t}:{id:t,err:`ID is required`}},ae=Q().basePath(`/:id`).post(`/`,async e=>{let{id:t,err:n}=$(e);if(n)return X(e,n);let r=await e.env.chat.upsert(t);return e.json({id:r.id},200)}).post(`/sendMessages`,Y(`json`,(e,t)=>{let n=e.messages;if(!n)return X(t,`Messages are required`);if(!Array.isArray(n))return X(t,`Messages must be an array`);if(n.length===0)return X(t,`Messages must not be empty`);let r=e.behavior;return r!==`enqueue`&&r!==`interrupt`&&r!==`append`?X(t,`Invalid behavior`):{messages:n,behavior:r}}),async e=>{let{id:t,err:n}=$(e);if(n)return X(e,n);let{messages:r,behavior:i}=e.req.valid(`json`);try{await e.env.chat.sendMessages(t,{messages:r,behavior:i})}catch(t){return X(e,t instanceof Error?t.message:`Unknown error`)}return e.body(null,204)}),oe=new H().route(`/storage`,ie).route(`/chat`,ae);exports.APIServerURLEnvironmentVariable=e.APIServerURLEnvironmentVariable,exports.Client=e.Client,exports.StreamResponseFormatHeader=e.StreamResponseFormatHeader,exports.api=oe,exports.convertResponseToUIMessageStream=e.convertResponseToUIMessageStream,exports.createAsyncIterableStream=t,exports.streamSSE=e.streamSSE;
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { Chat, ChatBehavior, Message } from "../index.browser-CHLe3dau.cjs";
|
|
2
2
|
import { APIServerURLEnvironmentVariable, CapabilitiesResponse, Client, ClientOptions, ExperimentalProvideCompletionsRequest, SendMessagesRequest, StreamResponseFormatHeader, streamSSE } from "../client-Co98ZOqj.cjs";
|
|
3
3
|
import { UIMessageChunk } from "ai";
|
|
4
|
+
import * as hono_types0 from "hono/types";
|
|
5
|
+
import * as hono_hono_base0 from "hono/hono-base";
|
|
4
6
|
|
|
5
7
|
//#region src/http/async-iterable-stream.d.ts
|
|
6
8
|
/**
|
|
@@ -52,9 +54,154 @@ type APIBindings = {
|
|
|
52
54
|
* server.listen(options.port);
|
|
53
55
|
* ```
|
|
54
56
|
*/
|
|
57
|
+
declare const api: hono_hono_base0.HonoBase<{
|
|
58
|
+
Bindings: APIBindings;
|
|
59
|
+
}, hono_types0.BlankSchema | hono_types0.MergeSchemaPath<{
|
|
60
|
+
"/kv/:key": {
|
|
61
|
+
$get: {
|
|
62
|
+
input: {
|
|
63
|
+
param: {
|
|
64
|
+
key: string;
|
|
65
|
+
};
|
|
66
|
+
};
|
|
67
|
+
output: {
|
|
68
|
+
error: string;
|
|
69
|
+
};
|
|
70
|
+
outputFormat: "json";
|
|
71
|
+
status: 400;
|
|
72
|
+
} | {
|
|
73
|
+
input: {
|
|
74
|
+
param: {
|
|
75
|
+
key: string;
|
|
76
|
+
};
|
|
77
|
+
};
|
|
78
|
+
output: {
|
|
79
|
+
value: string | undefined;
|
|
80
|
+
};
|
|
81
|
+
outputFormat: "json";
|
|
82
|
+
status: 200;
|
|
83
|
+
};
|
|
84
|
+
};
|
|
85
|
+
} & {
|
|
86
|
+
"/kv/:key": {
|
|
87
|
+
$post: {
|
|
88
|
+
input: {
|
|
89
|
+
json: {
|
|
90
|
+
value: string;
|
|
91
|
+
};
|
|
92
|
+
} & {
|
|
93
|
+
param: {
|
|
94
|
+
key: string;
|
|
95
|
+
};
|
|
96
|
+
};
|
|
97
|
+
output: {
|
|
98
|
+
error: string;
|
|
99
|
+
};
|
|
100
|
+
outputFormat: "json";
|
|
101
|
+
status: 400;
|
|
102
|
+
} | {
|
|
103
|
+
input: {
|
|
104
|
+
json: {
|
|
105
|
+
value: string;
|
|
106
|
+
};
|
|
107
|
+
} & {
|
|
108
|
+
param: {
|
|
109
|
+
key: string;
|
|
110
|
+
};
|
|
111
|
+
};
|
|
112
|
+
output: null;
|
|
113
|
+
outputFormat: "body";
|
|
114
|
+
status: 204;
|
|
115
|
+
};
|
|
116
|
+
};
|
|
117
|
+
} & {
|
|
118
|
+
"/kv/:key": {
|
|
119
|
+
$delete: {
|
|
120
|
+
input: {
|
|
121
|
+
param: {
|
|
122
|
+
key: string;
|
|
123
|
+
};
|
|
124
|
+
};
|
|
125
|
+
output: {
|
|
126
|
+
error: string;
|
|
127
|
+
};
|
|
128
|
+
outputFormat: "json";
|
|
129
|
+
status: 400;
|
|
130
|
+
} | {
|
|
131
|
+
input: {
|
|
132
|
+
param: {
|
|
133
|
+
key: string;
|
|
134
|
+
};
|
|
135
|
+
};
|
|
136
|
+
output: null;
|
|
137
|
+
outputFormat: "body";
|
|
138
|
+
status: 204;
|
|
139
|
+
};
|
|
140
|
+
};
|
|
141
|
+
}, "/storage"> | hono_types0.MergeSchemaPath<{
|
|
142
|
+
"/:id": {
|
|
143
|
+
$post: {
|
|
144
|
+
input: {
|
|
145
|
+
param: {
|
|
146
|
+
id: string;
|
|
147
|
+
};
|
|
148
|
+
};
|
|
149
|
+
output: {
|
|
150
|
+
error: string;
|
|
151
|
+
};
|
|
152
|
+
outputFormat: "json";
|
|
153
|
+
status: 400;
|
|
154
|
+
} | {
|
|
155
|
+
input: {
|
|
156
|
+
param: {
|
|
157
|
+
id: string;
|
|
158
|
+
};
|
|
159
|
+
};
|
|
160
|
+
output: {
|
|
161
|
+
id: string;
|
|
162
|
+
};
|
|
163
|
+
outputFormat: "json";
|
|
164
|
+
status: 200;
|
|
165
|
+
};
|
|
166
|
+
};
|
|
167
|
+
} & {
|
|
168
|
+
"/:id/sendMessages": {
|
|
169
|
+
$post: {
|
|
170
|
+
input: {
|
|
171
|
+
json: {
|
|
172
|
+
messages: Message[];
|
|
173
|
+
behavior: ChatBehavior;
|
|
174
|
+
};
|
|
175
|
+
} & {
|
|
176
|
+
param: {
|
|
177
|
+
id: string;
|
|
178
|
+
};
|
|
179
|
+
};
|
|
180
|
+
output: {
|
|
181
|
+
error: string;
|
|
182
|
+
};
|
|
183
|
+
outputFormat: "json";
|
|
184
|
+
status: 400;
|
|
185
|
+
} | {
|
|
186
|
+
input: {
|
|
187
|
+
json: {
|
|
188
|
+
messages: Message[];
|
|
189
|
+
behavior: ChatBehavior;
|
|
190
|
+
};
|
|
191
|
+
} & {
|
|
192
|
+
param: {
|
|
193
|
+
id: string;
|
|
194
|
+
};
|
|
195
|
+
};
|
|
196
|
+
output: null;
|
|
197
|
+
outputFormat: "body";
|
|
198
|
+
status: 204;
|
|
199
|
+
};
|
|
200
|
+
};
|
|
201
|
+
}, "/chat">, "/">;
|
|
55
202
|
//#endregion
|
|
56
203
|
//#region src/http/convert-response-to-ui-message-stream.d.ts
|
|
57
204
|
type StreamResponseFormat = "ui-message" | "openai-chat" | "openai-response" | "anthropic" | "google" | "xai";
|
|
58
205
|
declare function convertResponseToUIMessageStream(response: Response): ReadableStream<UIMessageChunk>;
|
|
59
206
|
//#endregion
|
|
60
|
-
export { APIBindings, APIServerURLEnvironmentVariable, AsyncIterableStream, CapabilitiesResponse, Client, ClientOptions, ExperimentalProvideCompletionsRequest, SendMessagesRequest, StreamResponseFormat, StreamResponseFormatHeader, convertResponseToUIMessageStream, createAsyncIterableStream, streamSSE };
|
|
207
|
+
export { APIBindings, APIServerURLEnvironmentVariable, AsyncIterableStream, CapabilitiesResponse, Client, ClientOptions, ExperimentalProvideCompletionsRequest, SendMessagesRequest, StreamResponseFormat, StreamResponseFormatHeader, api, convertResponseToUIMessageStream, createAsyncIterableStream, streamSSE };
|