@opentiny/next-sdk 0.1.5 → 0.1.6
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/WebMcpClient.ts +15 -3
- package/agent/AgentModelProvider.ts +10 -1
- package/agent/type.ts +1 -1
- package/dist/WebMcpClient.d.ts +1 -1
- package/dist/WebMcpClient.js +12 -2
- package/dist/agent/AgentModelProvider.d.ts +2 -0
- package/dist/agent/AgentModelProvider.js +8 -1
- package/dist/agent/type.d.ts +1 -1
- package/dist/index.es.dev.js +714 -655
- package/dist/index.es.js +5819 -5782
- package/dist/index.umd.dev.js +714 -655
- package/dist/index.umd.js +29 -29
- package/dist/mcpsdk@1.17.0.dev.js +866 -830
- package/dist/mcpsdk@1.17.0.es.dev.js +868 -832
- package/dist/mcpsdk@1.17.0.es.js +6417 -6437
- package/dist/mcpsdk@1.17.0.js +16 -16
- package/dist/webagent.dev.js +8 -1
- package/dist/webagent.es.dev.js +8 -1
- package/dist/webagent.es.js +4 -4
- package/dist/webagent.js +1 -1
- package/dist/webmcp-full.dev.js +693 -641
- package/dist/webmcp-full.es.dev.js +693 -641
- package/dist/webmcp-full.es.js +3270 -3233
- package/dist/webmcp-full.js +8 -8
- package/dist/webmcp.dev.js +630 -631
- package/dist/webmcp.es.dev.js +629 -629
- package/dist/webmcp.es.js +560 -568
- package/dist/webmcp.js +1 -1
- package/package.json +2 -2
package/dist/webagent.dev.js
CHANGED
|
@@ -24674,6 +24674,9 @@ ${user}:`]
|
|
|
24674
24674
|
}
|
|
24675
24675
|
return await createMCPClient({ transport });
|
|
24676
24676
|
} catch (error) {
|
|
24677
|
+
if (this.onError) {
|
|
24678
|
+
this.onError(`Failed to create MCP client`, error);
|
|
24679
|
+
}
|
|
24677
24680
|
console.error(`Failed to create MCP client`, serverConfig, error);
|
|
24678
24681
|
return null;
|
|
24679
24682
|
}
|
|
@@ -24694,6 +24697,10 @@ ${user}:`]
|
|
|
24694
24697
|
try {
|
|
24695
24698
|
return client ? await ((_a16 = client == null ? void 0 : client.tools) == null ? void 0 : _a16.call(client)) : null;
|
|
24696
24699
|
} catch (error) {
|
|
24700
|
+
if (this.onError) {
|
|
24701
|
+
this.onError(`Failed to query tools`, error);
|
|
24702
|
+
}
|
|
24703
|
+
console.error(`Failed to query tools`, error);
|
|
24697
24704
|
return null;
|
|
24698
24705
|
}
|
|
24699
24706
|
})
|
|
@@ -24721,7 +24728,7 @@ ${user}:`]
|
|
|
24721
24728
|
}
|
|
24722
24729
|
async insertMcpServer(mcpServer) {
|
|
24723
24730
|
var _a16;
|
|
24724
|
-
const find = this.mcpServers.find((item) => item.url === mcpServer.url);
|
|
24731
|
+
const find = this.mcpServers.find((item) => "url" in item && "url" in mcpServer && item.url === mcpServer.url);
|
|
24725
24732
|
if (!find) {
|
|
24726
24733
|
this.mcpServers = [...this.mcpServers, mcpServer];
|
|
24727
24734
|
const client = await this._createOneClient(mcpServer);
|
package/dist/webagent.es.dev.js
CHANGED
|
@@ -24280,6 +24280,9 @@ class AgentModelProvider {
|
|
|
24280
24280
|
}
|
|
24281
24281
|
return await createMCPClient({ transport });
|
|
24282
24282
|
} catch (error) {
|
|
24283
|
+
if (this.onError) {
|
|
24284
|
+
this.onError(`Failed to create MCP client`, error);
|
|
24285
|
+
}
|
|
24283
24286
|
console.error(`Failed to create MCP client`, serverConfig, error);
|
|
24284
24287
|
return null;
|
|
24285
24288
|
}
|
|
@@ -24300,6 +24303,10 @@ class AgentModelProvider {
|
|
|
24300
24303
|
try {
|
|
24301
24304
|
return client ? await ((_a16 = client == null ? void 0 : client.tools) == null ? void 0 : _a16.call(client)) : null;
|
|
24302
24305
|
} catch (error) {
|
|
24306
|
+
if (this.onError) {
|
|
24307
|
+
this.onError(`Failed to query tools`, error);
|
|
24308
|
+
}
|
|
24309
|
+
console.error(`Failed to query tools`, error);
|
|
24303
24310
|
return null;
|
|
24304
24311
|
}
|
|
24305
24312
|
})
|
|
@@ -24327,7 +24334,7 @@ class AgentModelProvider {
|
|
|
24327
24334
|
}
|
|
24328
24335
|
async insertMcpServer(mcpServer) {
|
|
24329
24336
|
var _a16;
|
|
24330
|
-
const find = this.mcpServers.find((item) => item.url === mcpServer.url);
|
|
24337
|
+
const find = this.mcpServers.find((item) => "url" in item && "url" in mcpServer && item.url === mcpServer.url);
|
|
24331
24338
|
if (!find) {
|
|
24332
24339
|
this.mcpServers = [...this.mcpServers, mcpServer];
|
|
24333
24340
|
const client = await this._createOneClient(mcpServer);
|
package/dist/webagent.es.js
CHANGED
|
@@ -19219,7 +19219,7 @@ class uT {
|
|
|
19219
19219
|
let n;
|
|
19220
19220
|
return "type" in t && t.type.toLocaleLowerCase() === "streamablehttp" ? n = new $b(new URL(t.url)) : n = t, await Ww({ transport: n });
|
|
19221
19221
|
} catch (n) {
|
|
19222
|
-
return console.error("Failed to create MCP client", t, n), null;
|
|
19222
|
+
return this.onError && this.onError("Failed to create MCP client", n), console.error("Failed to create MCP client", t, n), null;
|
|
19223
19223
|
}
|
|
19224
19224
|
}
|
|
19225
19225
|
/** 创建 ai-sdk的 mcpClient, 失败则保存为null */
|
|
@@ -19235,8 +19235,8 @@ class uT {
|
|
|
19235
19235
|
var n;
|
|
19236
19236
|
try {
|
|
19237
19237
|
return t ? await ((n = t == null ? void 0 : t.tools) == null ? void 0 : n.call(t)) : null;
|
|
19238
|
-
} catch {
|
|
19239
|
-
return null;
|
|
19238
|
+
} catch (r) {
|
|
19239
|
+
return this.onError && this.onError("Failed to query tools", r), console.error("Failed to query tools", r), null;
|
|
19240
19240
|
}
|
|
19241
19241
|
})
|
|
19242
19242
|
);
|
|
@@ -19260,7 +19260,7 @@ class uT {
|
|
|
19260
19260
|
}
|
|
19261
19261
|
async insertMcpServer(t) {
|
|
19262
19262
|
var r;
|
|
19263
|
-
if (!this.mcpServers.find((o) => o.url === t.url)) {
|
|
19263
|
+
if (!this.mcpServers.find((o) => "url" in o && "url" in t && o.url === t.url)) {
|
|
19264
19264
|
this.mcpServers = [...this.mcpServers, t];
|
|
19265
19265
|
const o = await this._createOneClient(t);
|
|
19266
19266
|
return this.mcpClients.push(o), this.mcpTools.push(await ((r = o == null ? void 0 : o.tools) == null ? void 0 : r.call(o))), !0;
|
package/dist/webagent.js
CHANGED
|
@@ -73,7 +73,7 @@ ${a}
|
|
|
73
73
|
|
|
74
74
|
`;break}case"tool":throw new at({functionality:"tool messages"});default:{const a=o;throw new Error(`Unsupported role: ${a}`)}}return r+=`${n}:
|
|
75
75
|
`,{prompt:r,stopSequences:[`
|
|
76
|
-
${t}:`]}}function sd({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}function ad(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 id=x({echo:re().optional(),logitBias:We(h(),R()).optional(),suffix:h().optional(),user:h().optional(),logprobs:ee([re(),R()]).optional()}),Xx=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:o,frequencyPenalty:s,presencePenalty:a,stopSequences:i,responseFormat:l,tools:u,toolChoice:c,seed:w,providerOptions:_}){const d=[],f={...await kt({provider:"openai",providerOptions:_,schema:id}),...await kt({provider:this.providerOptionsName,providerOptions:_,schema:id})};o!=null&&d.push({type:"unsupported-setting",setting:"topK"}),u!=null&&u.length&&d.push({type:"unsupported-setting",setting:"tools"}),c!=null&&d.push({type:"unsupported-setting",setting:"toolChoice"}),l!=null&&l.type!=="text"&&d.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:y,stopSequences:v}=Yx({prompt:e}),p=[...v??[],...i??[]];return{args:{model:this.modelId,echo:f.echo,logit_bias:f.logitBias,logprobs:(f==null?void 0:f.logprobs)===!0?0:(f==null?void 0:f.logprobs)===!1||f==null?void 0:f.logprobs,suffix:f.suffix,user:f.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:s,presence_penalty:a,seed:w,prompt:y,stop:p.length>0?p:void 0},warnings:d}}async doGenerate(e){var t,n,r;const{args:o,warnings:s}=await this.getArgs(e),{responseHeaders:a,value:i,rawValue:l}=await mt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),body:o,failedResponseHandler:Tt,successfulResponseHandler:on(Qx),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=i.choices[0],c={openai:{}};return u.logprobs!=null&&(c.openai.logprobs=u.logprobs),{content:[{type:"text",text:u.text}],usage:{inputTokens:(t=i.usage)==null?void 0:t.prompt_tokens,outputTokens:(n=i.usage)==null?void 0:n.completion_tokens,totalTokens:(r=i.usage)==null?void 0:r.total_tokens},finishReason:ad(u.finish_reason),request:{body:o},response:{...sd(i),headers:a,body:l},providerMetadata:c,warnings:s}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:s}=await mt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),body:r,failedResponseHandler:Tt,successfulResponseHandler:io(ek),abortSignal:e.abortSignal,fetch:this.config.fetch});let a="unknown";const i={openai:{}},l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let u=!0;return{stream:s.pipeThrough(new TransformStream({start(c){c.enqueue({type:"stream-start",warnings:n})},transform(c,w){if(e.includeRawChunks&&w.enqueue({type:"raw",rawValue:c.rawValue}),!c.success){a="error",w.enqueue({type:"error",error:c.error});return}const _=c.value;if("error"in _){a="error",w.enqueue({type:"error",error:_.error});return}u&&(u=!1,w.enqueue({type:"response-metadata",...sd(_)}),w.enqueue({type:"text-start",id:"0"})),_.usage!=null&&(l.inputTokens=_.usage.prompt_tokens,l.outputTokens=_.usage.completion_tokens,l.totalTokens=_.usage.total_tokens);const d=_.choices[0];(d==null?void 0:d.finish_reason)!=null&&(a=ad(d.finish_reason)),(d==null?void 0:d.logprobs)!=null&&(i.openai.logprobs=d.logprobs),(d==null?void 0:d.text)!=null&&d.text.length>0&&w.enqueue({type:"text-delta",id:"0",delta:d.text})},flush(c){u||c.enqueue({type:"text-end",id:"0"}),c.enqueue({type:"finish",finishReason:a,providerMetadata:i,usage:l})}})),request:{body:r},response:{headers:o}}}},ld=x({prompt_tokens:R(),completion_tokens:R(),total_tokens:R()}),Qx=x({id:h().nullish(),created:R().nullish(),model:h().nullish(),choices:Z(x({text:h(),finish_reason:h(),logprobs:x({tokens:Z(h()),token_logprobs:Z(R()),top_logprobs:Z(We(h(),R())).nullish()}).nullish()})),usage:ld.nullish()}),ek=ee([x({id:h().nullish(),created:R().nullish(),model:h().nullish(),choices:Z(x({text:h(),finish_reason:h().nullish(),index:R(),logprobs:x({tokens:Z(h()),token_logprobs:Z(R()),top_logprobs:Z(We(h(),R())).nullish()}).nullish()})),usage:ld.nullish()}),Ks]),tk=x({dimensions:R().optional(),user:h().optional()}),nk=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 o;if(e.length>this.maxEmbeddingsPerCall)throw new dp({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const s=(o=await kt({provider:"openai",providerOptions:r,schema:tk}))!=null?o:{},{responseHeaders:a,value:i,rawValue:l}=await mt({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:dt(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:Tt,successfulResponseHandler:on(rk),abortSignal:n,fetch:this.config.fetch});return{embeddings:i.data.map(u=>u.embedding),usage:i.usage?{tokens:i.usage.prompt_tokens}:void 0,response:{headers:a,body:l}}}},rk=x({data:Z(x({embedding:Z(R())})),usage:x({prompt_tokens:R()}).nullish()}),ok={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},sk=new Set(["gpt-image-1"]),ak=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get maxImagesPerCall(){var e;return(e=ok[this.modelId])!=null?e:1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:o,providerOptions:s,headers:a,abortSignal:i}){var l,u,c,w;const _=[];r!=null&&_.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),o!=null&&_.push({type:"unsupported-setting",setting:"seed"});const d=(c=(u=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:u.call(l))!=null?c:new Date,{value:f,responseHeaders:y}=await mt({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:dt(this.config.headers(),a),body:{model:this.modelId,prompt:e,n:t,size:n,...(w=s.openai)!=null?w:{},...sk.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Tt,successfulResponseHandler:on(ik),abortSignal:i,fetch:this.config.fetch});return{images:f.data.map(v=>v.b64_json),warnings:_,response:{timestamp:d,modelId:this.modelId,headers:y},providerMetadata:{openai:{images:f.data.map(v=>v.revised_prompt?{revisedPrompt:v.revised_prompt}:null)}}}}},ik=x({data:Z(x({b64_json:h(),revised_prompt:h().optional()}))}),lk=x({container:ee([h(),x({fileIds:Z(h()).optional()})]).optional()}),uk=Ws({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:x({})}),ck={codeInterpreter:uk,fileSearch:Lx,webSearchPreview:qx};function ud(e,t){return t?t.some(n=>e.startsWith(n)):!1}async function dk({prompt:e,systemMessageMode:t,fileIdPrefixes:n}){var r,o,s,a,i,l;const u=[],c=[];for(const{role:w,content:_}of e)switch(w){case"system":{switch(t){case"system":{u.push({role:"system",content:_});break}case"developer":{u.push({role:"developer",content:_});break}case"remove":{c.push({type:"other",message:"system messages are removed for this model"});break}default:{const d=t;throw new Error(`Unsupported system message mode: ${d}`)}}break}case"user":{u.push({role:"user",content:_.map((d,f)=>{var y,v,p;switch(d.type){case"text":return{type:"input_text",text:d.text};case"file":if(d.mediaType.startsWith("image/")){const b=d.mediaType==="image/*"?"image/jpeg":d.mediaType;return{type:"input_image",...d.data instanceof URL?{image_url:d.data.toString()}:typeof d.data=="string"&&ud(d.data,n)?{file_id:d.data}:{image_url:`data:${b};base64,${sn(d.data)}`},detail:(v=(y=d.providerOptions)==null?void 0:y.openai)==null?void 0:v.imageDetail}}else if(d.mediaType==="application/pdf"){if(d.data instanceof URL)throw new at({functionality:"PDF file parts with URLs"});return{type:"input_file",...typeof d.data=="string"&&ud(d.data,n)?{file_id:d.data}:{filename:(p=d.filename)!=null?p:`part-${f}.pdf`,file_data:`data:application/pdf;base64,${sn(d.data)}`}}}else throw new at({functionality:`file part media type ${d.mediaType}`})}})});break}case"assistant":{const d={};for(const f of _)switch(f.type){case"text":{u.push({role:"assistant",content:[{type:"output_text",text:f.text}],id:(s=(o=(r=f.providerOptions)==null?void 0:r.openai)==null?void 0:o.itemId)!=null?s:void 0});break}case"tool-call":{if(f.providerExecuted)break;u.push({type:"function_call",call_id:f.toolCallId,name:f.toolName,arguments:JSON.stringify(f.input),id:(l=(i=(a=f.providerOptions)==null?void 0:a.openai)==null?void 0:i.itemId)!=null?l:void 0});break}case"tool-result":{c.push({type:"other",message:"tool result parts in assistant messages are not supported for OpenAI responses"});break}case"reasoning":{const y=await kt({provider:"openai",providerOptions:f.providerOptions,schema:pk}),v=y==null?void 0:y.itemId;if(v!=null){const p=d[v],b=[];f.text.length>0?b.push({type:"summary_text",text:f.text}):p!==void 0&&c.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(f)}.`}),p===void 0?(d[v]={type:"reasoning",id:v,encrypted_content:y==null?void 0:y.reasoningEncryptedContent,summary:b},u.push(d[v])):p.summary.push(...b)}else c.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(f)}.`});break}}break}case"tool":{for(const d of _){const f=d.output;let y;switch(f.type){case"text":case"error-text":y=f.value;break;case"content":case"json":case"error-json":y=JSON.stringify(f.value);break}u.push({type:"function_call_output",call_id:d.toolCallId,output:y})}break}default:{const d=w;throw new Error(`Unsupported role: ${d}`)}}return{messages:u,warnings:c}}var pk=x({itemId:h().nullish(),reasoningEncryptedContent:h().nullish()});function cd({finishReason:e,hasToolCalls: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 hk({tools:e,toolChoice:t,strictJsonSchema:n}){e=e!=null&&e.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const o=[];for(const a of e)switch(a.type){case"function":o.push({type:"function",name:a.name,description:a.description,parameters:a.inputSchema,strict:n});break;case"provider-defined":{switch(a.id){case"openai.file_search":{const i=td.parse(a.args);o.push({type:"file_search",vector_store_ids:i.vectorStoreIds,max_num_results:i.maxNumResults,ranking_options:i.ranking?{ranker:i.ranking.ranker}:void 0,filters:i.filters});break}case"openai.web_search_preview":{const i=nd.parse(a.args);o.push({type:"web_search_preview",search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.code_interpreter":{const i=lk.parse(a.args);o.push({type:"code_interpreter",container:i.container==null?{type:"auto",file_ids:void 0}:typeof i.container=="string"?i.container:{type:"auto",file_ids:i.container.fileIds}});break}default:{r.push({type:"unsupported-tool",tool:a});break}}break}default:r.push({type:"unsupported-tool",tool:a});break}if(t==null)return{tools:o,toolChoice:void 0,toolWarnings:r};const s=t.type;switch(s){case"auto":case"none":case"required":return{tools:o,toolChoice:s,toolWarnings:r};case"tool":return{tools:o,toolChoice:t.toolName==="code_interpreter"||t.toolName==="file_search"||t.toolName==="web_search_preview"?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:r};default:{const a=s;throw new at({functionality:`tool choice type: ${a}`})}}}var dd=20,pd=Z(x({token:h(),logprob:R(),top_logprobs:Z(x({token:h(),logprob:R()}))})),fk=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({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:o,presencePenalty:s,frequencyPenalty:a,seed:i,prompt:l,providerOptions:u,tools:c,toolChoice:w,responseFormat:_}){var d,f;const y=[],v=zk(this.modelId);o!=null&&y.push({type:"unsupported-setting",setting:"topK"}),i!=null&&y.push({type:"unsupported-setting",setting:"seed"}),s!=null&&y.push({type:"unsupported-setting",setting:"presencePenalty"}),a!=null&&y.push({type:"unsupported-setting",setting:"frequencyPenalty"}),n!=null&&y.push({type:"unsupported-setting",setting:"stopSequences"});const{messages:p,warnings:b}=await dk({prompt:l,systemMessageMode:v.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes});y.push(...b);const g=await kt({provider:"openai",providerOptions:u,schema:jk}),m=(d=g==null?void 0:g.strictJsonSchema)!=null?d:!1,E=typeof(g==null?void 0:g.logprobs)=="number"?g==null?void 0:g.logprobs:(g==null?void 0:g.logprobs)===!0?dd:void 0,S=E?Array.isArray(g==null?void 0:g.include)?[...g==null?void 0:g.include,"message.output_text.logprobs"]:["message.output_text.logprobs"]:g==null?void 0:g.include,T={model:this.modelId,input:p,temperature:t,top_p:r,max_output_tokens:e,...((_==null?void 0:_.type)==="json"||(g==null?void 0:g.textVerbosity))&&{text:{...(_==null?void 0:_.type)==="json"&&{format:_.schema!=null?{type:"json_schema",strict:m,name:(f=_.name)!=null?f:"response",description:_.description,schema:_.schema}:{type:"json_object"}},...(g==null?void 0:g.textVerbosity)&&{verbosity:g.textVerbosity}}},metadata:g==null?void 0:g.metadata,parallel_tool_calls:g==null?void 0:g.parallelToolCalls,previous_response_id:g==null?void 0:g.previousResponseId,store:g==null?void 0:g.store,user:g==null?void 0:g.user,instructions:g==null?void 0:g.instructions,service_tier:g==null?void 0:g.serviceTier,include:S,prompt_cache_key:g==null?void 0:g.promptCacheKey,safety_identifier:g==null?void 0:g.safetyIdentifier,top_logprobs:E,...v.isReasoningModel&&((g==null?void 0:g.reasoningEffort)!=null||(g==null?void 0:g.reasoningSummary)!=null)&&{reasoning:{...(g==null?void 0:g.reasoningEffort)!=null&&{effort:g.reasoningEffort},...(g==null?void 0:g.reasoningSummary)!=null&&{summary:g.reasoningSummary}}},...v.requiredAutoTruncation&&{truncation:"auto"}};v.isReasoningModel?(T.temperature!=null&&(T.temperature=void 0,y.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),T.top_p!=null&&(T.top_p=void 0,y.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):((g==null?void 0:g.reasoningEffort)!=null&&y.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),(g==null?void 0:g.reasoningSummary)!=null&&y.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),(g==null?void 0:g.serviceTier)==="flex"&&!v.supportsFlexProcessing&&(y.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete T.service_tier),(g==null?void 0:g.serviceTier)==="priority"&&!v.supportsPriorityProcessing&&(y.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);const{tools:P,toolChoice:V,toolWarnings:H}=hk({tools:c,toolChoice:w,strictJsonSchema:m});return{args:{...T,tools:P,tool_choice:V},warnings:[...y,...H]}}async doGenerate(e){var t,n,r,o,s,a,i,l,u,c,w,_,d,f,y,v,p;const{args:b,warnings:g}=await this.getArgs(e),m=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:E,value:S,rawValue:T}=await mt({url:m,headers:dt(this.config.headers(),e.headers),body:b,failedResponseHandler:Tt,successfulResponseHandler:on(x({id:h(),created_at:R(),error:x({code:h(),message:h()}).nullish(),model:h(),output:Z(cn("type",[x({type:A("message"),role:A("assistant"),id:h(),content:Z(x({type:A("output_text"),text:h(),logprobs:pd.nullish(),annotations:Z(cn("type",[x({type:A("url_citation"),start_index:R(),end_index:R(),url:h(),title:h()}),x({type:A("file_citation"),start_index:R(),end_index:R(),file_id:h(),quote:h()})]))}))}),x({type:A("function_call"),call_id:h(),name:h(),arguments:h(),id:h()}),x({type:A("web_search_call"),id:h(),status:h().optional(),action:x({type:A("search"),query:h().optional()}).nullish()}),x({type:A("computer_call"),id:h(),status:h().optional()}),x({type:A("file_search_call"),id:h(),status:h().optional(),queries:Z(h()).nullish(),results:Z(x({attributes:x({file_id:h(),filename:h(),score:R(),text:h()})})).nullish()}),x({type:A("reasoning"),id:h(),encrypted_content:h().nullish(),summary:Z(x({type:A("summary_text"),text:h()}))})])),incomplete_details:x({reason:h()}).nullable(),usage:hd})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(S.error)throw new pe({message:S.error.message,url:m,requestBodyValues:b,statusCode:400,responseHeaders:E,responseBody:T,isRetryable:!1});const P=[],V=[];for(const B of S.output)switch(B.type){case"reasoning":{B.summary.length===0&&B.summary.push({type:"summary_text",text:""});for(const oe of B.summary)P.push({type:"reasoning",text:oe.text,providerMetadata:{openai:{itemId:B.id,reasoningEncryptedContent:(t=B.encrypted_content)!=null?t:null}}});break}case"message":{for(const oe of B.content){(r=(n=e.providerOptions)==null?void 0:n.openai)!=null&&r.logprobs&&oe.logprobs&&V.push(oe.logprobs),P.push({type:"text",text:oe.text,providerMetadata:{openai:{itemId:B.id}}});for(const F of oe.annotations)F.type==="url_citation"?P.push({type:"source",sourceType:"url",id:(a=(s=(o=this.config).generateId)==null?void 0:s.call(o))!=null?a:tt(),url:F.url,title:F.title}):F.type==="file_citation"&&P.push({type:"source",sourceType:"document",id:(u=(l=(i=this.config).generateId)==null?void 0:l.call(i))!=null?u:tt(),mediaType:"text/plain",title:F.quote,filename:F.file_id})}break}case"function_call":{P.push({type:"tool-call",toolCallId:B.call_id,toolName:B.name,input:B.arguments,providerMetadata:{openai:{itemId:B.id}}});break}case"web_search_call":{P.push({type:"tool-call",toolCallId:B.id,toolName:"web_search_preview",input:(w=(c=B.action)==null?void 0:c.query)!=null?w:"",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:B.id,toolName:"web_search_preview",result:{status:B.status||"completed",...((_=B.action)==null?void 0:_.query)&&{query:B.action.query}},providerExecuted:!0});break}case"computer_call":{P.push({type:"tool-call",toolCallId:B.id,toolName:"computer_use",input:"",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:B.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:B.status||"completed"},providerExecuted:!0});break}case"file_search_call":{P.push({type:"tool-call",toolCallId:B.id,toolName:"file_search",input:"",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:B.id,toolName:"file_search",result:{type:"file_search_tool_result",status:B.status||"completed",...B.queries&&{queries:B.queries},...B.results&&{results:B.results}},providerExecuted:!0});break}}const H={openai:{responseId:S.id}};return V.length>0&&(H.openai.logprobs=V),{content:P,finishReason:cd({finishReason:(d=S.incomplete_details)==null?void 0:d.reason,hasToolCalls:P.some(B=>B.type==="tool-call")}),usage:{inputTokens:S.usage.input_tokens,outputTokens:S.usage.output_tokens,totalTokens:S.usage.input_tokens+S.usage.output_tokens,reasoningTokens:(y=(f=S.usage.output_tokens_details)==null?void 0:f.reasoning_tokens)!=null?y:void 0,cachedInputTokens:(p=(v=S.usage.input_tokens_details)==null?void 0:v.cached_tokens)!=null?p:void 0},request:{body:b},response:{id:S.id,timestamp:new Date(S.created_at*1e3),modelId:S.model,headers:E,body:T},providerMetadata:H,warnings:g}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:o}=await mt({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Tt,successfulResponseHandler:io(Sk),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=this;let a="unknown";const i={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=[];let u=null;const c={};let w=!1;const _={};return{stream:o.pipeThrough(new TransformStream({start(d){d.enqueue({type:"stream-start",warnings:n})},transform(d,f){var y,v,p,b,g,m,E,S,T,P,V,H,B,oe,F,be,Ee,Ne,Xe;if(e.includeRawChunks&&f.enqueue({type:"raw",rawValue:d.rawValue}),!d.success){a="error",f.enqueue({type:"error",error:d.error});return}const I=d.value;if(md(I))I.item.type==="function_call"?(c[I.output_index]={toolName:I.item.name,toolCallId:I.item.call_id},f.enqueue({type:"tool-input-start",id:I.item.call_id,toolName:I.item.name})):I.item.type==="web_search_call"?(c[I.output_index]={toolName:"web_search_preview",toolCallId:I.item.id},f.enqueue({type:"tool-input-start",id:I.item.id,toolName:"web_search_preview"})):I.item.type==="computer_call"?(c[I.output_index]={toolName:"computer_use",toolCallId:I.item.id},f.enqueue({type:"tool-input-start",id:I.item.id,toolName:"computer_use"})):I.item.type==="file_search_call"?(c[I.output_index]={toolName:"file_search",toolCallId:I.item.id},f.enqueue({type:"tool-input-start",id:I.item.id,toolName:"file_search"})):I.item.type==="message"?f.enqueue({type:"text-start",id:I.item.id,providerMetadata:{openai:{itemId:I.item.id}}}):Ok(I)&&(_[I.item.id]={encryptedContent:I.item.encrypted_content,summaryParts:[0]},f.enqueue({type:"reasoning-start",id:`${I.item.id}:0`,providerMetadata:{openai:{itemId:I.item.id,reasoningEncryptedContent:(y=I.item.encrypted_content)!=null?y:null}}}));else if(fd(I)){if(I.item.type==="function_call")c[I.output_index]=void 0,w=!0,f.enqueue({type:"tool-input-end",id:I.item.call_id}),f.enqueue({type:"tool-call",toolCallId:I.item.call_id,toolName:I.item.name,input:I.item.arguments,providerMetadata:{openai:{itemId:I.item.id}}});else if(I.item.type==="web_search_call")c[I.output_index]=void 0,w=!0,f.enqueue({type:"tool-input-end",id:I.item.id}),f.enqueue({type:"tool-call",toolCallId:I.item.id,toolName:"web_search_preview",input:(p=(v=I.item.action)==null?void 0:v.query)!=null?p:"",providerExecuted:!0}),f.enqueue({type:"tool-result",toolCallId:I.item.id,toolName:"web_search_preview",result:{type:"web_search_tool_result",status:I.item.status||"completed",...((b=I.item.action)==null?void 0:b.query)&&{query:I.item.action.query}},providerExecuted:!0});else if(I.item.type==="computer_call")c[I.output_index]=void 0,w=!0,f.enqueue({type:"tool-input-end",id:I.item.id}),f.enqueue({type:"tool-call",toolCallId:I.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),f.enqueue({type:"tool-result",toolCallId:I.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:I.item.status||"completed"},providerExecuted:!0});else if(I.item.type==="file_search_call")c[I.output_index]=void 0,w=!0,f.enqueue({type:"tool-input-end",id:I.item.id}),f.enqueue({type:"tool-call",toolCallId:I.item.id,toolName:"file_search",input:"",providerExecuted:!0}),f.enqueue({type:"tool-result",toolCallId:I.item.id,toolName:"file_search",result:{type:"file_search_tool_result",status:I.item.status||"completed",...I.item.queries&&{queries:I.item.queries},...I.item.results&&{results:I.item.results}},providerExecuted:!0});else if(I.item.type==="message")f.enqueue({type:"text-end",id:I.item.id});else if(Ck(I)){const ie=_[I.item.id];for(const me of ie.summaryParts)f.enqueue({type:"reasoning-end",id:`${I.item.id}:${me}`,providerMetadata:{openai:{itemId:I.item.id,reasoningEncryptedContent:(g=I.item.encrypted_content)!=null?g:null}}});delete _[I.item.id]}}else if(Ak(I)){const ie=c[I.output_index];ie!=null&&f.enqueue({type:"tool-input-delta",id:ie.toolCallId,delta:I.delta})}else Rk(I)?(u=I.response.id,f.enqueue({type:"response-metadata",id:I.response.id,timestamp:new Date(I.response.created_at*1e3),modelId:I.response.model})):Ik(I)?(f.enqueue({type:"text-delta",id:I.item_id,delta:I.delta}),I.logprobs&&l.push(I.logprobs)):Mk(I)?I.summary_index>0&&((m=_[I.item_id])==null||m.summaryParts.push(I.summary_index),f.enqueue({type:"reasoning-start",id:`${I.item_id}:${I.summary_index}`,providerMetadata:{openai:{itemId:I.item_id,reasoningEncryptedContent:(S=(E=_[I.item_id])==null?void 0:E.encryptedContent)!=null?S:null}}})):Pk(I)?f.enqueue({type:"reasoning-delta",id:`${I.item_id}:${I.summary_index}`,delta:I.delta,providerMetadata:{openai:{itemId:I.item_id}}}):Ek(I)?(a=cd({finishReason:(T=I.response.incomplete_details)==null?void 0:T.reason,hasToolCalls:w}),i.inputTokens=I.response.usage.input_tokens,i.outputTokens=I.response.usage.output_tokens,i.totalTokens=I.response.usage.input_tokens+I.response.usage.output_tokens,i.reasoningTokens=(V=(P=I.response.usage.output_tokens_details)==null?void 0:P.reasoning_tokens)!=null?V:void 0,i.cachedInputTokens=(B=(H=I.response.usage.input_tokens_details)==null?void 0:H.cached_tokens)!=null?B:void 0):Nk(I)?I.annotation.type==="url_citation"?f.enqueue({type:"source",sourceType:"url",id:(be=(F=(oe=s.config).generateId)==null?void 0:F.call(oe))!=null?be:tt(),url:I.annotation.url,title:I.annotation.title}):I.annotation.type==="file_citation"&&f.enqueue({type:"source",sourceType:"document",id:(Xe=(Ne=(Ee=s.config).generateId)==null?void 0:Ne.call(Ee))!=null?Xe:tt(),mediaType:"text/plain",title:I.annotation.quote,filename:I.annotation.file_id}):$k(I)&&f.enqueue({type:"error",error:I})},flush(d){const f={openai:{responseId:u}};l.length>0&&(f.openai.logprobs=l),d.enqueue({type:"finish",finishReason:a,usage:i,providerMetadata:f})}})),request:{body:t},response:{headers:r}}}},hd=x({input_tokens:R(),input_tokens_details:x({cached_tokens:R().nullish()}).nullish(),output_tokens:R(),output_tokens_details:x({reasoning_tokens:R().nullish()}).nullish()}),mk=x({type:A("response.output_text.delta"),item_id:h(),delta:h(),logprobs:pd.nullish()}),gk=x({type:A("error"),code:h(),message:h(),param:h().nullish(),sequence_number:R()}),yk=x({type:qe(["response.completed","response.incomplete"]),response:x({incomplete_details:x({reason:h()}).nullish(),usage:hd})}),vk=x({type:A("response.created"),response:x({id:h(),created_at:R(),model:h()})}),_k=x({type:A("response.output_item.added"),output_index:R(),item:cn("type",[x({type:A("message"),id:h()}),x({type:A("reasoning"),id:h(),encrypted_content:h().nullish()}),x({type:A("function_call"),id:h(),call_id:h(),name:h(),arguments:h()}),x({type:A("web_search_call"),id:h(),status:h(),action:x({type:A("search"),query:h().optional()}).nullish()}),x({type:A("computer_call"),id:h(),status:h()}),x({type:A("file_search_call"),id:h(),status:h(),queries:Z(h()).nullish(),results:Z(x({attributes:x({file_id:h(),filename:h(),score:R(),text:h()})})).optional()})])}),wk=x({type:A("response.output_item.done"),output_index:R(),item:cn("type",[x({type:A("message"),id:h()}),x({type:A("reasoning"),id:h(),encrypted_content:h().nullish()}),x({type:A("function_call"),id:h(),call_id:h(),name:h(),arguments:h(),status:A("completed")}),x({type:A("web_search_call"),id:h(),status:A("completed"),action:x({type:A("search"),query:h().optional()}).nullish()}),x({type:A("computer_call"),id:h(),status:A("completed")}),x({type:A("file_search_call"),id:h(),status:A("completed"),queries:Z(h()).nullish(),results:Z(x({attributes:x({file_id:h(),filename:h(),score:R(),text:h()})})).nullish()})])}),bk=x({type:A("response.function_call_arguments.delta"),item_id:h(),output_index:R(),delta:h()}),xk=x({type:A("response.output_text.annotation.added"),annotation:cn("type",[x({type:A("url_citation"),url:h(),title:h()}),x({type:A("file_citation"),file_id:h(),quote:h()})])}),kk=x({type:A("response.reasoning_summary_part.added"),item_id:h(),summary_index:R()}),Tk=x({type:A("response.reasoning_summary_text.delta"),item_id:h(),summary_index:R(),delta:h()}),Sk=ee([mk,yk,vk,_k,wk,bk,xk,kk,Tk,gk,x({type:h()}).loose()]);function Ik(e){return e.type==="response.output_text.delta"}function fd(e){return e.type==="response.output_item.done"}function Ck(e){return fd(e)&&e.item.type==="reasoning"}function Ek(e){return e.type==="response.completed"||e.type==="response.incomplete"}function Rk(e){return e.type==="response.created"}function Ak(e){return e.type==="response.function_call_arguments.delta"}function md(e){return e.type==="response.output_item.added"}function Ok(e){return md(e)&&e.item.type==="reasoning"}function Nk(e){return e.type==="response.output_text.annotation.added"}function Mk(e){return e.type==="response.reasoning_summary_part.added"}function Pk(e){return e.type==="response.reasoning_summary_text.delta"}function $k(e){return e.type==="error"}function zk(e){const 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 jk=x({metadata:pt().nullish(),parallelToolCalls:re().nullish(),previousResponseId:h().nullish(),store:re().nullish(),user:h().nullish(),reasoningEffort:h().nullish(),strictJsonSchema:re().nullish(),instructions:h().nullish(),reasoningSummary:h().nullish(),serviceTier:qe(["auto","flex","priority"]).nullish(),include:Z(qe(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),textVerbosity:qe(["low","medium","high"]).nullish(),promptCacheKey:h().nullish(),safetyIdentifier:h().nullish(),logprobs:ee([re(),R().min(1).max(dd)]).optional()}),Dk=x({instructions:h().nullish(),speed:R().min(.25).max(4).default(1).nullish()}),Zk=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:o,language:s,providerOptions:a}){const i=[],l=await kt({provider:"openai",providerOptions:a,schema:Dk}),u={model:this.modelId,input:e,voice:t,response_format:"mp3",speed:r,instructions:o};if(n&&(["mp3","opus","aac","flac","wav","pcm"].includes(n)?u.response_format=n:i.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${n}. Using mp3 instead.`})),l){const c={};for(const w in c){const _=c[w];_!==void 0&&(u[w]=_)}}return s&&i.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${s}" was ignored.`}),{requestBody:u,warnings:i}}async doGenerate(e){var t,n,r;const o=(r=(n=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:n.call(t))!=null?r:new Date,{requestBody:s,warnings:a}=await this.getArgs(e),{value:i,responseHeaders:l,rawValue:u}=await mt({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),body:s,failedResponseHandler:Tt,successfulResponseHandler:Mx(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:i,warnings:a,request:{body:JSON.stringify(s)},response:{timestamp:o,modelId:this.modelId,headers:l,body:u}}}},Uk=x({include:Z(h()).optional(),language:h().optional(),prompt:h().optional(),temperature:R().min(0).max(1).default(0).optional(),timestampGranularities:Z(qe(["word","segment"])).default(["segment"]).optional()}),gd={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"},Lk=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}){const r=[],o=await kt({provider:"openai",providerOptions:n,schema:Uk}),s=new FormData,a=e instanceof Uint8Array?new Blob([e]):new Blob([zx(e)]);if(s.append("model",this.modelId),s.append("file",new File([a],"audio",{type:t})),o){const i={include:o.include,language:o.language,prompt:o.prompt,response_format:"verbose_json",temperature:o.temperature,timestamp_granularities:o.timestampGranularities};for(const[l,u]of Object.entries(i))u!=null&&s.append(l,String(u))}return{formData:s,warnings:r}}async doGenerate(e){var t,n,r,o,s,a,i,l;const u=(r=(n=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:n.call(t))!=null?r:new Date,{formData:c,warnings:w}=await this.getArgs(e),{value:_,responseHeaders:d,rawValue:f}=await Nx({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),formData:c,failedResponseHandler:Tt,successfulResponseHandler:on(qk),abortSignal:e.abortSignal,fetch:this.config.fetch}),y=_.language!=null&&_.language in gd?gd[_.language]:void 0;return{text:_.text,segments:(i=(a=(o=_.segments)==null?void 0:o.map(v=>({text:v.text,startSecond:v.start,endSecond:v.end})))!=null?a:(s=_.words)==null?void 0:s.map(v=>({text:v.word,startSecond:v.start,endSecond:v.end})))!=null?i:[],language:y,durationInSeconds:(l=_.duration)!=null?l:void 0,warnings:w,response:{timestamp:u,modelId:this.modelId,headers:d,body:f}}}},qk=x({text:h(),language:h().nullish(),duration:R().nullish(),words:Z(x({word:h(),start:R(),end:R()})).nullish(),segments:Z(x({id:R(),seek:R(),start:R(),end:R(),text:h(),tokens:Z(R()),temperature:R(),avg_logprob:R(),compression_ratio:R(),no_speech_prob:R()})).nullish()});function yd(e={}){var t,n;const r=(t=Kc(e.baseURL))!=null?t:"https://api.openai.com/v1",o=(n=e.name)!=null?n:"openai",s=()=>({Authorization:`Bearer ${Hc({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers}),a=y=>new Vx(y,{provider:`${o}.chat`,url:({path:v})=>`${r}${v}`,headers:s,fetch:e.fetch}),i=y=>new Xx(y,{provider:`${o}.completion`,url:({path:v})=>`${r}${v}`,headers:s,fetch:e.fetch}),l=y=>new nk(y,{provider:`${o}.embedding`,url:({path:v})=>`${r}${v}`,headers:s,fetch:e.fetch}),u=y=>new ak(y,{provider:`${o}.image`,url:({path:v})=>`${r}${v}`,headers:s,fetch:e.fetch}),c=y=>new Lk(y,{provider:`${o}.transcription`,url:({path:v})=>`${r}${v}`,headers:s,fetch:e.fetch}),w=y=>new Zk(y,{provider:`${o}.speech`,url:({path:v})=>`${r}${v}`,headers:s,fetch:e.fetch}),_=y=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return d(y)},d=y=>new fk(y,{provider:`${o}.responses`,url:({path:v})=>`${r}${v}`,headers:s,fetch:e.fetch,fileIdPrefixes:["file-"]}),f=function(y){return _(y)};return f.languageModel=_,f.chat=a,f.completion=i,f.responses=d,f.embedding=l,f.textEmbedding=l,f.textEmbeddingModel=l,f.image=u,f.imageModel=u,f.transcription=c,f.transcriptionModel=c,f.speech=w,f.speechModel=w,f.tools=ck,f}yd();function sr(e){var t,n;return(n=(t=e==null?void 0:e.providerOptions)==null?void 0:t.openaiCompatible)!=null?n:{}}function Bk(e){const t=[];for(const{role:n,content:r,...o}of e){const s=sr({...o});switch(n){case"system":{t.push({role:"system",content:r,...s});break}case"user":{if(r.length===1&&r[0].type==="text"){t.push({role:"user",content:r[0].text,...sr(r[0])});break}t.push({role:"user",content:r.map(a=>{const i=sr(a);switch(a.type){case"text":return{type:"text",text:a.text,...i};case"file":if(a.mediaType.startsWith("image/")){const l=a.mediaType==="image/*"?"image/jpeg":a.mediaType;return{type:"image_url",image_url:{url:a.data instanceof URL?a.data.toString():`data:${l};base64,${sn(a.data)}`},...i}}else throw new at({functionality:`file part media type ${a.mediaType}`})}}),...s});break}case"assistant":{let a="";const i=[];for(const l of r){const u=sr(l);switch(l.type){case"text":{a+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)},...u});break}}}t.push({role:"assistant",content:a,tool_calls:i.length>0?i:void 0,...s});break}case"tool":{for(const a of r){const i=a.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}const u=sr(a);t.push({role:"tool",tool_call_id:a.toolCallId,content:l,...u})}break}default:{const a=n;throw new Error(`Unsupported role: ${a}`)}}}return t}function vd({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}function _d(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 wd=x({user:h().optional(),reasoningEffort:h().optional()}),Vk=x({error:x({message:h(),type:h().nullish(),param:pt().nullish(),code:ee([h(),R()]).nullish()})}),Fk={errorSchema:Vk,errorToMessage:e=>e.error.message};function Hk({tools:e,toolChoice:t}){e=e!=null&&e.length?e:void 0;const n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const r=[];for(const s of e)s.type==="provider-defined"?n.push({type:"unsupported-tool",tool:s}):r.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema}});if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:r,toolChoice:o,toolWarnings:n};case"tool":return{tools:r,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:n};default:{const s=o;throw new at({functionality:`tool choice type: ${s}`})}}}var Jk=class{constructor(e,t){this.specificationVersion="v2";var n,r;this.modelId=e,this.config=t;const o=(n=t.errorStructure)!=null?n:Fk;this.chunkSchema=Wk(o.errorSchema),this.failedResponseHandler=Wc(o),this.supportsStructuredOutputs=(r=t.supportsStructuredOutputs)!=null?r:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var e,t,n;return(n=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?n:{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:s,presencePenalty:a,providerOptions:i,stopSequences:l,responseFormat:u,seed:c,toolChoice:w,tools:_}){var d,f,y;const v=[],p=Object.assign((d=await kt({provider:"openai-compatible",providerOptions:i,schema:wd}))!=null?d:{},(f=await kt({provider:this.providerOptionsName,providerOptions:i,schema:wd}))!=null?f:{});o!=null&&v.push({type:"unsupported-setting",setting:"topK"}),(u==null?void 0:u.type)==="json"&&u.schema!=null&&!this.supportsStructuredOutputs&&v.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:b,toolChoice:g,toolWarnings:m}=Hk({tools:_,toolChoice:w});return{args:{model:this.modelId,user:p.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:s,presence_penalty:a,response_format:(u==null?void 0:u.type)==="json"?this.supportsStructuredOutputs===!0&&u.schema!=null?{type:"json_schema",json_schema:{schema:u.schema,name:(y=u.name)!=null?y:"response",description:u.description}}:{type:"json_object"}:void 0,stop:l,seed:c,...i==null?void 0:i[this.providerOptionsName],reasoning_effort:p.reasoningEffort,messages:Bk(e),tools:b,tool_choice:g},warnings:[...v,...m]}}async doGenerate(e){var t,n,r,o,s,a,i,l,u,c,w,_,d,f,y,v,p;const{args:b,warnings:g}=await this.getArgs({...e}),m=JSON.stringify(b),{responseHeaders:E,value:S,rawValue:T}=await mt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),body:b,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:on(Gk),abortSignal:e.abortSignal,fetch:this.config.fetch}),P=S.choices[0],V=[],H=P.message.content;H!=null&&H.length>0&&V.push({type:"text",text:H});const B=(t=P.message.reasoning_content)!=null?t:P.message.reasoning;if(B!=null&&B.length>0&&V.push({type:"reasoning",text:B}),P.message.tool_calls!=null)for(const be of P.message.tool_calls)V.push({type:"tool-call",toolCallId:(n=be.id)!=null?n:tt(),toolName:be.function.name,input:be.function.arguments});const oe={[this.providerOptionsName]:{},...await((o=(r=this.config.metadataExtractor)==null?void 0:r.extractMetadata)==null?void 0:o.call(r,{parsedBody:T}))},F=(s=S.usage)==null?void 0:s.completion_tokens_details;return(F==null?void 0:F.accepted_prediction_tokens)!=null&&(oe[this.providerOptionsName].acceptedPredictionTokens=F==null?void 0:F.accepted_prediction_tokens),(F==null?void 0:F.rejected_prediction_tokens)!=null&&(oe[this.providerOptionsName].rejectedPredictionTokens=F==null?void 0:F.rejected_prediction_tokens),{content:V,finishReason:_d(P.finish_reason),usage:{inputTokens:(i=(a=S.usage)==null?void 0:a.prompt_tokens)!=null?i:void 0,outputTokens:(u=(l=S.usage)==null?void 0:l.completion_tokens)!=null?u:void 0,totalTokens:(w=(c=S.usage)==null?void 0:c.total_tokens)!=null?w:void 0,reasoningTokens:(f=(d=(_=S.usage)==null?void 0:_.completion_tokens_details)==null?void 0:d.reasoning_tokens)!=null?f:void 0,cachedInputTokens:(p=(v=(y=S.usage)==null?void 0:y.prompt_tokens_details)==null?void 0:v.cached_tokens)!=null?p:void 0},providerMetadata:oe,request:{body:m},response:{...vd(S),headers:E,body:T},warnings:g}}async doStream(e){var t;const{args:n,warnings:r}=await this.getArgs({...e}),o={...n,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},s=(t=this.config.metadataExtractor)==null?void 0:t.createStreamExtractor(),{responseHeaders:a,value:i}=await mt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:io(this.chunkSchema),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=[];let u="unknown";const c={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let w=!0;const _=this.providerOptionsName;let d=!1,f=!1;return{stream:i.pipeThrough(new TransformStream({start(y){y.enqueue({type:"stream-start",warnings:r})},transform(y,v){var p,b,g,m,E,S,T,P,V,H,B,oe,F;if(e.includeRawChunks&&v.enqueue({type:"raw",rawValue:y.rawValue}),!y.success){u="error",v.enqueue({type:"error",error:y.error});return}const be=y.value;if(s==null||s.processChunk(y.rawValue),"error"in be){u="error",v.enqueue({type:"error",error:be.error.message});return}if(w&&(w=!1,v.enqueue({type:"response-metadata",...vd(be)})),be.usage!=null){const{prompt_tokens:I,completion_tokens:ie,total_tokens:me,prompt_tokens_details:de,completion_tokens_details:Q}=be.usage;c.promptTokens=I??void 0,c.completionTokens=ie??void 0,c.totalTokens=me??void 0,(Q==null?void 0:Q.reasoning_tokens)!=null&&(c.completionTokensDetails.reasoningTokens=Q==null?void 0:Q.reasoning_tokens),(Q==null?void 0:Q.accepted_prediction_tokens)!=null&&(c.completionTokensDetails.acceptedPredictionTokens=Q==null?void 0:Q.accepted_prediction_tokens),(Q==null?void 0:Q.rejected_prediction_tokens)!=null&&(c.completionTokensDetails.rejectedPredictionTokens=Q==null?void 0:Q.rejected_prediction_tokens),(de==null?void 0:de.cached_tokens)!=null&&(c.promptTokensDetails.cachedTokens=de==null?void 0:de.cached_tokens)}const Ee=be.choices[0];if((Ee==null?void 0:Ee.finish_reason)!=null&&(u=_d(Ee.finish_reason)),(Ee==null?void 0:Ee.delta)==null)return;const Ne=Ee.delta,Xe=(p=Ne.reasoning_content)!=null?p:Ne.reasoning;if(Xe&&(d||(v.enqueue({type:"reasoning-start",id:"reasoning-0"}),d=!0),v.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:Xe})),Ne.content&&(f||(v.enqueue({type:"text-start",id:"txt-0"}),f=!0),v.enqueue({type:"text-delta",id:"txt-0",delta:Ne.content})),Ne.tool_calls!=null)for(const I of Ne.tool_calls){const ie=I.index;if(l[ie]==null){if(I.id==null)throw new In({data:I,message:"Expected 'id' to be a string."});if(((b=I.function)==null?void 0:b.name)==null)throw new In({data:I,message:"Expected 'function.name' to be a string."});v.enqueue({type:"tool-input-start",id:I.id,toolName:I.function.name}),l[ie]={id:I.id,type:"function",function:{name:I.function.name,arguments:(g=I.function.arguments)!=null?g:""},hasFinished:!1};const de=l[ie];((m=de.function)==null?void 0:m.name)!=null&&((E=de.function)==null?void 0:E.arguments)!=null&&(de.function.arguments.length>0&&v.enqueue({type:"tool-input-start",id:de.id,toolName:de.function.name}),ao(de.function.arguments)&&(v.enqueue({type:"tool-input-end",id:de.id}),v.enqueue({type:"tool-call",toolCallId:(S=de.id)!=null?S:tt(),toolName:de.function.name,input:de.function.arguments}),de.hasFinished=!0));continue}const me=l[ie];me.hasFinished||(((T=I.function)==null?void 0:T.arguments)!=null&&(me.function.arguments+=(V=(P=I.function)==null?void 0:P.arguments)!=null?V:""),v.enqueue({type:"tool-input-delta",id:me.id,delta:(H=I.function.arguments)!=null?H:""}),((B=me.function)==null?void 0:B.name)!=null&&((oe=me.function)==null?void 0:oe.arguments)!=null&&ao(me.function.arguments)&&(v.enqueue({type:"tool-input-end",id:me.id}),v.enqueue({type:"tool-call",toolCallId:(F=me.id)!=null?F:tt(),toolName:me.function.name,input:me.function.arguments}),me.hasFinished=!0))}},flush(y){var v,p,b,g,m,E;d&&y.enqueue({type:"reasoning-end",id:"reasoning-0"}),f&&y.enqueue({type:"text-end",id:"txt-0"});for(const T of l.filter(P=>!P.hasFinished))y.enqueue({type:"tool-input-end",id:T.id}),y.enqueue({type:"tool-call",toolCallId:(v=T.id)!=null?v:tt(),toolName:T.function.name,input:T.function.arguments});const S={[_]:{},...s==null?void 0:s.buildMetadata()};c.completionTokensDetails.acceptedPredictionTokens!=null&&(S[_].acceptedPredictionTokens=c.completionTokensDetails.acceptedPredictionTokens),c.completionTokensDetails.rejectedPredictionTokens!=null&&(S[_].rejectedPredictionTokens=c.completionTokensDetails.rejectedPredictionTokens),y.enqueue({type:"finish",finishReason:u,usage:{inputTokens:(p=c.promptTokens)!=null?p:void 0,outputTokens:(b=c.completionTokens)!=null?b:void 0,totalTokens:(g=c.totalTokens)!=null?g:void 0,reasoningTokens:(m=c.completionTokensDetails.reasoningTokens)!=null?m:void 0,cachedInputTokens:(E=c.promptTokensDetails.cachedTokens)!=null?E:void 0},providerMetadata:S})}})),request:{body:o},response:{headers:a}}}},bd=x({prompt_tokens:R().nullish(),completion_tokens:R().nullish(),total_tokens:R().nullish(),prompt_tokens_details:x({cached_tokens:R().nullish()}).nullish(),completion_tokens_details:x({reasoning_tokens:R().nullish(),accepted_prediction_tokens:R().nullish(),rejected_prediction_tokens:R().nullish()}).nullish()}).nullish(),Gk=x({id:h().nullish(),created:R().nullish(),model:h().nullish(),choices:Z(x({message:x({role:A("assistant").nullish(),content:h().nullish(),reasoning_content:h().nullish(),reasoning:h().nullish(),tool_calls:Z(x({id:h().nullish(),function:x({name:h(),arguments:h()})})).nullish()}),finish_reason:h().nullish()})),usage:bd}),Wk=e=>ee([x({id:h().nullish(),created:R().nullish(),model:h().nullish(),choices:Z(x({delta:x({role:qe(["assistant"]).nullish(),content:h().nullish(),reasoning_content:h().nullish(),reasoning:h().nullish(),tool_calls:Z(x({index:R(),id:h().nullish(),function:x({name:h().nullish(),arguments:h().nullish()})})).nullish()}).nullish(),finish_reason:h().nullish()})),usage:bd}),e]);x({echo:re().optional(),logitBias:We(h(),R()).optional(),suffix:h().optional(),user:h().optional()});var Kk=x({prompt_tokens:R(),completion_tokens:R(),total_tokens:R()});x({id:h().nullish(),created:R().nullish(),model:h().nullish(),choices:Z(x({text:h(),finish_reason:h()})),usage:Kk.nullish()}),x({dimensions:R().optional(),user:h().optional()}),x({data:Z(x({embedding:Z(R())})),usage:x({prompt_tokens:R()}).nullish(),providerMetadata:We(h(),We(h(),pt())).optional()}),x({data:Z(x({b64_json:h()}))});var xd=e=>{var t,n;return e==null?void 0:{deepseek:{promptCacheHitTokens:(t=e.prompt_cache_hit_tokens)!=null?t:NaN,promptCacheMissTokens:(n=e.prompt_cache_miss_tokens)!=null?n:NaN}}},Yk={extractMetadata:async({parsedBody:e})=>{const t=await or({value:e,schema:Xk});return!t.success||t.value.usage==null?void 0:xd(t.value.usage)},createStreamExtractor:()=>{let e;return{processChunk:async t=>{var n,r;const o=await or({value:t,schema:Qk});o.success&&((r=(n=o.value.choices)==null?void 0:n[0])==null?void 0:r.finish_reason)==="stop"&&o.value.usage&&(e=o.value.usage)},buildMetadata:()=>xd(e)}}},kd=x({prompt_cache_hit_tokens:R().nullish(),prompt_cache_miss_tokens:R().nullish()}),Xk=x({usage:kd.nullish()}),Qk=x({choices:Z(x({finish_reason:h().nullish()})).nullish(),usage:kd.nullish()});function Td(e={}){var t;const n=Kc((t=e.baseURL)!=null?t:"https://api.deepseek.com/v1"),r=()=>({Authorization:`Bearer ${Hc({apiKey:e.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...e.headers}),o=a=>new Jk(a,{provider:"deepseek.chat",url:({path:i})=>`${n}${i}`,headers:r,fetch:e.fetch,metadataExtractor:Yk}),s=a=>o(a);return s.languageModel=o,s.chat=o,s.textEmbeddingModel=a=>{throw new wo({modelId:a,modelType:"textEmbeddingModel"})},s.imageModel=a=>{throw new wo({modelId:a,modelType:"imageModel"})},s}Td();const eT={openai:yd,deepseek:Td};class tT{constructor({llmConfig:t,mcpServers:n,llm:r}){if(this.mcpServers=[],this.mcpClients=[],this.mcpTools=[],this.ignoreToolnames=[],this.autoUpdateTools=!0,this.mcpServers=n||[],r)this.llm=r;else if(t){let o;typeof t.providerType=="string"?o=eT[t.providerType]:o=t.providerType,this.llm=o({apiKey:t.apiKey,baseURL:t.baseURL})}else throw new Error("Either llmConfig or llm must be provided")}async _createOneClient(t){try{let n;return"type"in t&&t.type.toLocaleLowerCase()==="streamablehttp"?n=new mx(new URL(t.url)):n=t,await O0({transport:n})}catch(n){return console.error("Failed to create MCP client",t,n),null}}async _createMpcClients(){this.mcpClients=await Promise.all(this.mcpServers.map(async t=>this._createOneClient(t)))}async _createMpcTools(){this.mcpTools=await Promise.all(this.mcpClients.map(async t=>{var n;try{return t?await((n=t==null?void 0:t.tools)==null?void 0:n.call(t)):null}catch{return null}}))}async closeAll(){await Promise.all(this.mcpClients.map(async t=>{try{t.close()}catch{}}))}async initClientsAndTools(){await this._createMpcClients(),await this._createMpcTools()}async updateMcpServers(t){await this.closeAll(),this.mcpServers=t,await this.initClientsAndTools()}async insertMcpServer(t){var r;if(!this.mcpServers.find(o=>o.url===t.url)){this.mcpServers=[...this.mcpServers,t];const o=await this._createOneClient(t);return this.mcpClients.push(o),this.mcpTools.push(await((r=o==null?void 0:o.tools)==null?void 0:r.call(o))),!0}return!1}removeMcpServer(t){const n=this.mcpServers.findIndex(s=>s===t);this.mcpServers.splice(n,1);const r=this.mcpClients[n];this.mcpClients.splice(n,1);try{r==null||r.close()}catch{}const o=this.mcpTools[n];this.mcpTools.splice(n,1),o&&Object.keys(o).forEach(s=>{this.ignoreToolnames=this.ignoreToolnames.filter(a=>a!==s)})}tempMergeTools(t={}){const n=this.mcpTools.reduce((r,o)=>({...r,...o}),{});return Object.assign(n,t),this.ignoreToolnames.forEach(r=>{delete n[r]}),n}async _chat(t,{model:n,maxSteps:r=5,...o}){var s;if(!this.llm)throw new Error("LLM is not initialized");return this.autoUpdateTools&&(await this._createMpcTools(),(s=this.onUpdatedTools)==null||s.call(this)),t({model:this.llm(n),stopWhen:vs(r),...o,tools:this.tempMergeTools(o.tools)})}async chat(t){return this._chat(zw,t)}async chatStream(t){return this._chat(n0,t)}}var vn={},nT=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then},Sd={},nt={};let Ys;const rT=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];nt.getSymbolSize=function(t){if(!t)throw new Error('"version" cannot be null or undefined');if(t<1||t>40)throw new Error('"version" should be in range from 1 to 40');return t*4+17},nt.getSymbolTotalCodewords=function(t){return rT[t]},nt.getBCHDigit=function(e){let t=0;for(;e!==0;)t++,e>>>=1;return t},nt.setToSJISFunction=function(t){if(typeof t!="function")throw new Error('"toSJISFunc" is not a valid function.');Ys=t},nt.isKanjiModeEnabled=function(){return typeof Ys<"u"},nt.toSJIS=function(t){return Ys(t)};var lo={};(function(e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+n)}}e.isValid=function(r){return r&&typeof r.bit<"u"&&r.bit>=0&&r.bit<4},e.from=function(r,o){if(e.isValid(r))return r;try{return t(r)}catch{return o}}})(lo);function Id(){this.buffer=[],this.length=0}Id.prototype={get:function(e){const t=Math.floor(e/8);return(this.buffer[t]>>>7-e%8&1)===1},put:function(e,t){for(let n=0;n<t;n++)this.putBit((e>>>t-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){const t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}};var oT=Id;function ar(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}ar.prototype.set=function(e,t,n,r){const o=e*this.size+t;this.data[o]=n,r&&(this.reservedBit[o]=!0)},ar.prototype.get=function(e,t){return this.data[e*this.size+t]},ar.prototype.xor=function(e,t,n){this.data[e*this.size+t]^=n},ar.prototype.isReserved=function(e,t){return this.reservedBit[e*this.size+t]};var sT=ar,Cd={};(function(e){const t=nt.getSymbolSize;e.getRowColCoords=function(r){if(r===1)return[];const o=Math.floor(r/7)+2,s=t(r),a=s===145?26:Math.ceil((s-13)/(2*o-2))*2,i=[s-7];for(let l=1;l<o-1;l++)i[l]=i[l-1]-a;return i.push(6),i.reverse()},e.getPositions=function(r){const o=[],s=e.getRowColCoords(r),a=s.length;for(let i=0;i<a;i++)for(let l=0;l<a;l++)i===0&&l===0||i===0&&l===a-1||i===a-1&&l===0||o.push([s[i],s[l]]);return o}})(Cd);var Ed={};const aT=nt.getSymbolSize,Rd=7;Ed.getPositions=function(t){const n=aT(t);return[[0,0],[n-Rd,0],[0,n-Rd]]};var Ad={};(function(e){e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(o){return o!=null&&o!==""&&!isNaN(o)&&o>=0&&o<=7},e.from=function(o){return e.isValid(o)?parseInt(o,10):void 0},e.getPenaltyN1=function(o){const s=o.size;let a=0,i=0,l=0,u=null,c=null;for(let w=0;w<s;w++){i=l=0,u=c=null;for(let _=0;_<s;_++){let d=o.get(w,_);d===u?i++:(i>=5&&(a+=t.N1+(i-5)),u=d,i=1),d=o.get(_,w),d===c?l++:(l>=5&&(a+=t.N1+(l-5)),c=d,l=1)}i>=5&&(a+=t.N1+(i-5)),l>=5&&(a+=t.N1+(l-5))}return a},e.getPenaltyN2=function(o){const s=o.size;let a=0;for(let i=0;i<s-1;i++)for(let l=0;l<s-1;l++){const u=o.get(i,l)+o.get(i,l+1)+o.get(i+1,l)+o.get(i+1,l+1);(u===4||u===0)&&a++}return a*t.N2},e.getPenaltyN3=function(o){const s=o.size;let a=0,i=0,l=0;for(let u=0;u<s;u++){i=l=0;for(let c=0;c<s;c++)i=i<<1&2047|o.get(u,c),c>=10&&(i===1488||i===93)&&a++,l=l<<1&2047|o.get(c,u),c>=10&&(l===1488||l===93)&&a++}return a*t.N3},e.getPenaltyN4=function(o){let s=0;const a=o.data.length;for(let l=0;l<a;l++)s+=o.data[l];return Math.abs(Math.ceil(s*100/a/5)-10)*t.N4};function n(r,o,s){switch(r){case e.Patterns.PATTERN000:return(o+s)%2===0;case e.Patterns.PATTERN001:return o%2===0;case e.Patterns.PATTERN010:return s%3===0;case e.Patterns.PATTERN011:return(o+s)%3===0;case e.Patterns.PATTERN100:return(Math.floor(o/2)+Math.floor(s/3))%2===0;case e.Patterns.PATTERN101:return o*s%2+o*s%3===0;case e.Patterns.PATTERN110:return(o*s%2+o*s%3)%2===0;case e.Patterns.PATTERN111:return(o*s%3+(o+s)%2)%2===0;default:throw new Error("bad maskPattern:"+r)}}e.applyMask=function(o,s){const a=s.size;for(let i=0;i<a;i++)for(let l=0;l<a;l++)s.isReserved(l,i)||s.xor(l,i,n(o,l,i))},e.getBestMask=function(o,s){const a=Object.keys(e.Patterns).length;let i=0,l=1/0;for(let u=0;u<a;u++){s(u),e.applyMask(u,o);const c=e.getPenaltyN1(o)+e.getPenaltyN2(o)+e.getPenaltyN3(o)+e.getPenaltyN4(o);e.applyMask(u,o),c<l&&(l=c,i=u)}return i}})(Ad);var uo={};const Lt=lo,co=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],po=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];uo.getBlocksCount=function(t,n){switch(n){case Lt.L:return co[(t-1)*4+0];case Lt.M:return co[(t-1)*4+1];case Lt.Q:return co[(t-1)*4+2];case Lt.H:return co[(t-1)*4+3];default:return}},uo.getTotalCodewordsCount=function(t,n){switch(n){case Lt.L:return po[(t-1)*4+0];case Lt.M:return po[(t-1)*4+1];case Lt.Q:return po[(t-1)*4+2];case Lt.H:return po[(t-1)*4+3];default:return}};var Od={},ho={};const ir=new Uint8Array(512),fo=new Uint8Array(256);(function(){let t=1;for(let n=0;n<255;n++)ir[n]=t,fo[t]=n,t<<=1,t&256&&(t^=285);for(let n=255;n<512;n++)ir[n]=ir[n-255]})(),ho.log=function(t){if(t<1)throw new Error("log("+t+")");return fo[t]},ho.exp=function(t){return ir[t]},ho.mul=function(t,n){return t===0||n===0?0:ir[fo[t]+fo[n]]},function(e){const t=ho;e.mul=function(r,o){const s=new Uint8Array(r.length+o.length-1);for(let a=0;a<r.length;a++)for(let i=0;i<o.length;i++)s[a+i]^=t.mul(r[a],o[i]);return s},e.mod=function(r,o){let s=new Uint8Array(r);for(;s.length-o.length>=0;){const a=s[0];for(let l=0;l<o.length;l++)s[l]^=t.mul(o[l],a);let i=0;for(;i<s.length&&s[i]===0;)i++;s=s.slice(i)}return s},e.generateECPolynomial=function(r){let o=new Uint8Array([1]);for(let s=0;s<r;s++)o=e.mul(o,new Uint8Array([1,t.exp(s)]));return o}}(Od);const Nd=Od;function Xs(e){this.genPoly=void 0,this.degree=e,this.degree&&this.initialize(this.degree)}Xs.prototype.initialize=function(t){this.degree=t,this.genPoly=Nd.generateECPolynomial(this.degree)},Xs.prototype.encode=function(t){if(!this.genPoly)throw new Error("Encoder not initialized");const n=new Uint8Array(t.length+this.degree);n.set(t);const r=Nd.mod(n,this.genPoly),o=this.degree-r.length;if(o>0){const s=new Uint8Array(this.degree);return s.set(r,o),s}return r};var iT=Xs,Md={},qt={},Qs={};Qs.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40};var St={};const Pd="[0-9]+",lT="[A-Z $%*+\\-./:]+";let lr="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";lr=lr.replace(/u/g,"\\u");const uT="(?:(?![A-Z0-9 $%*+\\-./:]|"+lr+`)(?:.|[\r
|
|
76
|
+
${t}:`]}}function sd({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}function ad(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 id=x({echo:re().optional(),logitBias:We(h(),R()).optional(),suffix:h().optional(),user:h().optional(),logprobs:ee([re(),R()]).optional()}),Xx=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:o,frequencyPenalty:s,presencePenalty:a,stopSequences:i,responseFormat:l,tools:u,toolChoice:c,seed:w,providerOptions:_}){const d=[],f={...await kt({provider:"openai",providerOptions:_,schema:id}),...await kt({provider:this.providerOptionsName,providerOptions:_,schema:id})};o!=null&&d.push({type:"unsupported-setting",setting:"topK"}),u!=null&&u.length&&d.push({type:"unsupported-setting",setting:"tools"}),c!=null&&d.push({type:"unsupported-setting",setting:"toolChoice"}),l!=null&&l.type!=="text"&&d.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:y,stopSequences:v}=Yx({prompt:e}),p=[...v??[],...i??[]];return{args:{model:this.modelId,echo:f.echo,logit_bias:f.logitBias,logprobs:(f==null?void 0:f.logprobs)===!0?0:(f==null?void 0:f.logprobs)===!1||f==null?void 0:f.logprobs,suffix:f.suffix,user:f.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:s,presence_penalty:a,seed:w,prompt:y,stop:p.length>0?p:void 0},warnings:d}}async doGenerate(e){var t,n,r;const{args:o,warnings:s}=await this.getArgs(e),{responseHeaders:a,value:i,rawValue:l}=await mt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),body:o,failedResponseHandler:Tt,successfulResponseHandler:on(Qx),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=i.choices[0],c={openai:{}};return u.logprobs!=null&&(c.openai.logprobs=u.logprobs),{content:[{type:"text",text:u.text}],usage:{inputTokens:(t=i.usage)==null?void 0:t.prompt_tokens,outputTokens:(n=i.usage)==null?void 0:n.completion_tokens,totalTokens:(r=i.usage)==null?void 0:r.total_tokens},finishReason:ad(u.finish_reason),request:{body:o},response:{...sd(i),headers:a,body:l},providerMetadata:c,warnings:s}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:s}=await mt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),body:r,failedResponseHandler:Tt,successfulResponseHandler:io(ek),abortSignal:e.abortSignal,fetch:this.config.fetch});let a="unknown";const i={openai:{}},l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let u=!0;return{stream:s.pipeThrough(new TransformStream({start(c){c.enqueue({type:"stream-start",warnings:n})},transform(c,w){if(e.includeRawChunks&&w.enqueue({type:"raw",rawValue:c.rawValue}),!c.success){a="error",w.enqueue({type:"error",error:c.error});return}const _=c.value;if("error"in _){a="error",w.enqueue({type:"error",error:_.error});return}u&&(u=!1,w.enqueue({type:"response-metadata",...sd(_)}),w.enqueue({type:"text-start",id:"0"})),_.usage!=null&&(l.inputTokens=_.usage.prompt_tokens,l.outputTokens=_.usage.completion_tokens,l.totalTokens=_.usage.total_tokens);const d=_.choices[0];(d==null?void 0:d.finish_reason)!=null&&(a=ad(d.finish_reason)),(d==null?void 0:d.logprobs)!=null&&(i.openai.logprobs=d.logprobs),(d==null?void 0:d.text)!=null&&d.text.length>0&&w.enqueue({type:"text-delta",id:"0",delta:d.text})},flush(c){u||c.enqueue({type:"text-end",id:"0"}),c.enqueue({type:"finish",finishReason:a,providerMetadata:i,usage:l})}})),request:{body:r},response:{headers:o}}}},ld=x({prompt_tokens:R(),completion_tokens:R(),total_tokens:R()}),Qx=x({id:h().nullish(),created:R().nullish(),model:h().nullish(),choices:Z(x({text:h(),finish_reason:h(),logprobs:x({tokens:Z(h()),token_logprobs:Z(R()),top_logprobs:Z(We(h(),R())).nullish()}).nullish()})),usage:ld.nullish()}),ek=ee([x({id:h().nullish(),created:R().nullish(),model:h().nullish(),choices:Z(x({text:h(),finish_reason:h().nullish(),index:R(),logprobs:x({tokens:Z(h()),token_logprobs:Z(R()),top_logprobs:Z(We(h(),R())).nullish()}).nullish()})),usage:ld.nullish()}),Ks]),tk=x({dimensions:R().optional(),user:h().optional()}),nk=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 o;if(e.length>this.maxEmbeddingsPerCall)throw new dp({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const s=(o=await kt({provider:"openai",providerOptions:r,schema:tk}))!=null?o:{},{responseHeaders:a,value:i,rawValue:l}=await mt({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:dt(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:Tt,successfulResponseHandler:on(rk),abortSignal:n,fetch:this.config.fetch});return{embeddings:i.data.map(u=>u.embedding),usage:i.usage?{tokens:i.usage.prompt_tokens}:void 0,response:{headers:a,body:l}}}},rk=x({data:Z(x({embedding:Z(R())})),usage:x({prompt_tokens:R()}).nullish()}),ok={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},sk=new Set(["gpt-image-1"]),ak=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get maxImagesPerCall(){var e;return(e=ok[this.modelId])!=null?e:1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:o,providerOptions:s,headers:a,abortSignal:i}){var l,u,c,w;const _=[];r!=null&&_.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),o!=null&&_.push({type:"unsupported-setting",setting:"seed"});const d=(c=(u=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:u.call(l))!=null?c:new Date,{value:f,responseHeaders:y}=await mt({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:dt(this.config.headers(),a),body:{model:this.modelId,prompt:e,n:t,size:n,...(w=s.openai)!=null?w:{},...sk.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Tt,successfulResponseHandler:on(ik),abortSignal:i,fetch:this.config.fetch});return{images:f.data.map(v=>v.b64_json),warnings:_,response:{timestamp:d,modelId:this.modelId,headers:y},providerMetadata:{openai:{images:f.data.map(v=>v.revised_prompt?{revisedPrompt:v.revised_prompt}:null)}}}}},ik=x({data:Z(x({b64_json:h(),revised_prompt:h().optional()}))}),lk=x({container:ee([h(),x({fileIds:Z(h()).optional()})]).optional()}),uk=Ws({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:x({})}),ck={codeInterpreter:uk,fileSearch:Lx,webSearchPreview:qx};function ud(e,t){return t?t.some(n=>e.startsWith(n)):!1}async function dk({prompt:e,systemMessageMode:t,fileIdPrefixes:n}){var r,o,s,a,i,l;const u=[],c=[];for(const{role:w,content:_}of e)switch(w){case"system":{switch(t){case"system":{u.push({role:"system",content:_});break}case"developer":{u.push({role:"developer",content:_});break}case"remove":{c.push({type:"other",message:"system messages are removed for this model"});break}default:{const d=t;throw new Error(`Unsupported system message mode: ${d}`)}}break}case"user":{u.push({role:"user",content:_.map((d,f)=>{var y,v,p;switch(d.type){case"text":return{type:"input_text",text:d.text};case"file":if(d.mediaType.startsWith("image/")){const b=d.mediaType==="image/*"?"image/jpeg":d.mediaType;return{type:"input_image",...d.data instanceof URL?{image_url:d.data.toString()}:typeof d.data=="string"&&ud(d.data,n)?{file_id:d.data}:{image_url:`data:${b};base64,${sn(d.data)}`},detail:(v=(y=d.providerOptions)==null?void 0:y.openai)==null?void 0:v.imageDetail}}else if(d.mediaType==="application/pdf"){if(d.data instanceof URL)throw new at({functionality:"PDF file parts with URLs"});return{type:"input_file",...typeof d.data=="string"&&ud(d.data,n)?{file_id:d.data}:{filename:(p=d.filename)!=null?p:`part-${f}.pdf`,file_data:`data:application/pdf;base64,${sn(d.data)}`}}}else throw new at({functionality:`file part media type ${d.mediaType}`})}})});break}case"assistant":{const d={};for(const f of _)switch(f.type){case"text":{u.push({role:"assistant",content:[{type:"output_text",text:f.text}],id:(s=(o=(r=f.providerOptions)==null?void 0:r.openai)==null?void 0:o.itemId)!=null?s:void 0});break}case"tool-call":{if(f.providerExecuted)break;u.push({type:"function_call",call_id:f.toolCallId,name:f.toolName,arguments:JSON.stringify(f.input),id:(l=(i=(a=f.providerOptions)==null?void 0:a.openai)==null?void 0:i.itemId)!=null?l:void 0});break}case"tool-result":{c.push({type:"other",message:"tool result parts in assistant messages are not supported for OpenAI responses"});break}case"reasoning":{const y=await kt({provider:"openai",providerOptions:f.providerOptions,schema:pk}),v=y==null?void 0:y.itemId;if(v!=null){const p=d[v],b=[];f.text.length>0?b.push({type:"summary_text",text:f.text}):p!==void 0&&c.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(f)}.`}),p===void 0?(d[v]={type:"reasoning",id:v,encrypted_content:y==null?void 0:y.reasoningEncryptedContent,summary:b},u.push(d[v])):p.summary.push(...b)}else c.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(f)}.`});break}}break}case"tool":{for(const d of _){const f=d.output;let y;switch(f.type){case"text":case"error-text":y=f.value;break;case"content":case"json":case"error-json":y=JSON.stringify(f.value);break}u.push({type:"function_call_output",call_id:d.toolCallId,output:y})}break}default:{const d=w;throw new Error(`Unsupported role: ${d}`)}}return{messages:u,warnings:c}}var pk=x({itemId:h().nullish(),reasoningEncryptedContent:h().nullish()});function cd({finishReason:e,hasToolCalls: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 hk({tools:e,toolChoice:t,strictJsonSchema:n}){e=e!=null&&e.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const o=[];for(const a of e)switch(a.type){case"function":o.push({type:"function",name:a.name,description:a.description,parameters:a.inputSchema,strict:n});break;case"provider-defined":{switch(a.id){case"openai.file_search":{const i=td.parse(a.args);o.push({type:"file_search",vector_store_ids:i.vectorStoreIds,max_num_results:i.maxNumResults,ranking_options:i.ranking?{ranker:i.ranking.ranker}:void 0,filters:i.filters});break}case"openai.web_search_preview":{const i=nd.parse(a.args);o.push({type:"web_search_preview",search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.code_interpreter":{const i=lk.parse(a.args);o.push({type:"code_interpreter",container:i.container==null?{type:"auto",file_ids:void 0}:typeof i.container=="string"?i.container:{type:"auto",file_ids:i.container.fileIds}});break}default:{r.push({type:"unsupported-tool",tool:a});break}}break}default:r.push({type:"unsupported-tool",tool:a});break}if(t==null)return{tools:o,toolChoice:void 0,toolWarnings:r};const s=t.type;switch(s){case"auto":case"none":case"required":return{tools:o,toolChoice:s,toolWarnings:r};case"tool":return{tools:o,toolChoice:t.toolName==="code_interpreter"||t.toolName==="file_search"||t.toolName==="web_search_preview"?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:r};default:{const a=s;throw new at({functionality:`tool choice type: ${a}`})}}}var dd=20,pd=Z(x({token:h(),logprob:R(),top_logprobs:Z(x({token:h(),logprob:R()}))})),fk=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({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:o,presencePenalty:s,frequencyPenalty:a,seed:i,prompt:l,providerOptions:u,tools:c,toolChoice:w,responseFormat:_}){var d,f;const y=[],v=zk(this.modelId);o!=null&&y.push({type:"unsupported-setting",setting:"topK"}),i!=null&&y.push({type:"unsupported-setting",setting:"seed"}),s!=null&&y.push({type:"unsupported-setting",setting:"presencePenalty"}),a!=null&&y.push({type:"unsupported-setting",setting:"frequencyPenalty"}),n!=null&&y.push({type:"unsupported-setting",setting:"stopSequences"});const{messages:p,warnings:b}=await dk({prompt:l,systemMessageMode:v.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes});y.push(...b);const g=await kt({provider:"openai",providerOptions:u,schema:jk}),m=(d=g==null?void 0:g.strictJsonSchema)!=null?d:!1,E=typeof(g==null?void 0:g.logprobs)=="number"?g==null?void 0:g.logprobs:(g==null?void 0:g.logprobs)===!0?dd:void 0,S=E?Array.isArray(g==null?void 0:g.include)?[...g==null?void 0:g.include,"message.output_text.logprobs"]:["message.output_text.logprobs"]:g==null?void 0:g.include,T={model:this.modelId,input:p,temperature:t,top_p:r,max_output_tokens:e,...((_==null?void 0:_.type)==="json"||(g==null?void 0:g.textVerbosity))&&{text:{...(_==null?void 0:_.type)==="json"&&{format:_.schema!=null?{type:"json_schema",strict:m,name:(f=_.name)!=null?f:"response",description:_.description,schema:_.schema}:{type:"json_object"}},...(g==null?void 0:g.textVerbosity)&&{verbosity:g.textVerbosity}}},metadata:g==null?void 0:g.metadata,parallel_tool_calls:g==null?void 0:g.parallelToolCalls,previous_response_id:g==null?void 0:g.previousResponseId,store:g==null?void 0:g.store,user:g==null?void 0:g.user,instructions:g==null?void 0:g.instructions,service_tier:g==null?void 0:g.serviceTier,include:S,prompt_cache_key:g==null?void 0:g.promptCacheKey,safety_identifier:g==null?void 0:g.safetyIdentifier,top_logprobs:E,...v.isReasoningModel&&((g==null?void 0:g.reasoningEffort)!=null||(g==null?void 0:g.reasoningSummary)!=null)&&{reasoning:{...(g==null?void 0:g.reasoningEffort)!=null&&{effort:g.reasoningEffort},...(g==null?void 0:g.reasoningSummary)!=null&&{summary:g.reasoningSummary}}},...v.requiredAutoTruncation&&{truncation:"auto"}};v.isReasoningModel?(T.temperature!=null&&(T.temperature=void 0,y.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),T.top_p!=null&&(T.top_p=void 0,y.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):((g==null?void 0:g.reasoningEffort)!=null&&y.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),(g==null?void 0:g.reasoningSummary)!=null&&y.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),(g==null?void 0:g.serviceTier)==="flex"&&!v.supportsFlexProcessing&&(y.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete T.service_tier),(g==null?void 0:g.serviceTier)==="priority"&&!v.supportsPriorityProcessing&&(y.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);const{tools:P,toolChoice:V,toolWarnings:H}=hk({tools:c,toolChoice:w,strictJsonSchema:m});return{args:{...T,tools:P,tool_choice:V},warnings:[...y,...H]}}async doGenerate(e){var t,n,r,o,s,a,i,l,u,c,w,_,d,f,y,v,p;const{args:b,warnings:g}=await this.getArgs(e),m=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:E,value:S,rawValue:T}=await mt({url:m,headers:dt(this.config.headers(),e.headers),body:b,failedResponseHandler:Tt,successfulResponseHandler:on(x({id:h(),created_at:R(),error:x({code:h(),message:h()}).nullish(),model:h(),output:Z(cn("type",[x({type:A("message"),role:A("assistant"),id:h(),content:Z(x({type:A("output_text"),text:h(),logprobs:pd.nullish(),annotations:Z(cn("type",[x({type:A("url_citation"),start_index:R(),end_index:R(),url:h(),title:h()}),x({type:A("file_citation"),start_index:R(),end_index:R(),file_id:h(),quote:h()})]))}))}),x({type:A("function_call"),call_id:h(),name:h(),arguments:h(),id:h()}),x({type:A("web_search_call"),id:h(),status:h().optional(),action:x({type:A("search"),query:h().optional()}).nullish()}),x({type:A("computer_call"),id:h(),status:h().optional()}),x({type:A("file_search_call"),id:h(),status:h().optional(),queries:Z(h()).nullish(),results:Z(x({attributes:x({file_id:h(),filename:h(),score:R(),text:h()})})).nullish()}),x({type:A("reasoning"),id:h(),encrypted_content:h().nullish(),summary:Z(x({type:A("summary_text"),text:h()}))})])),incomplete_details:x({reason:h()}).nullable(),usage:hd})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(S.error)throw new pe({message:S.error.message,url:m,requestBodyValues:b,statusCode:400,responseHeaders:E,responseBody:T,isRetryable:!1});const P=[],V=[];for(const B of S.output)switch(B.type){case"reasoning":{B.summary.length===0&&B.summary.push({type:"summary_text",text:""});for(const oe of B.summary)P.push({type:"reasoning",text:oe.text,providerMetadata:{openai:{itemId:B.id,reasoningEncryptedContent:(t=B.encrypted_content)!=null?t:null}}});break}case"message":{for(const oe of B.content){(r=(n=e.providerOptions)==null?void 0:n.openai)!=null&&r.logprobs&&oe.logprobs&&V.push(oe.logprobs),P.push({type:"text",text:oe.text,providerMetadata:{openai:{itemId:B.id}}});for(const F of oe.annotations)F.type==="url_citation"?P.push({type:"source",sourceType:"url",id:(a=(s=(o=this.config).generateId)==null?void 0:s.call(o))!=null?a:tt(),url:F.url,title:F.title}):F.type==="file_citation"&&P.push({type:"source",sourceType:"document",id:(u=(l=(i=this.config).generateId)==null?void 0:l.call(i))!=null?u:tt(),mediaType:"text/plain",title:F.quote,filename:F.file_id})}break}case"function_call":{P.push({type:"tool-call",toolCallId:B.call_id,toolName:B.name,input:B.arguments,providerMetadata:{openai:{itemId:B.id}}});break}case"web_search_call":{P.push({type:"tool-call",toolCallId:B.id,toolName:"web_search_preview",input:(w=(c=B.action)==null?void 0:c.query)!=null?w:"",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:B.id,toolName:"web_search_preview",result:{status:B.status||"completed",...((_=B.action)==null?void 0:_.query)&&{query:B.action.query}},providerExecuted:!0});break}case"computer_call":{P.push({type:"tool-call",toolCallId:B.id,toolName:"computer_use",input:"",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:B.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:B.status||"completed"},providerExecuted:!0});break}case"file_search_call":{P.push({type:"tool-call",toolCallId:B.id,toolName:"file_search",input:"",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:B.id,toolName:"file_search",result:{type:"file_search_tool_result",status:B.status||"completed",...B.queries&&{queries:B.queries},...B.results&&{results:B.results}},providerExecuted:!0});break}}const H={openai:{responseId:S.id}};return V.length>0&&(H.openai.logprobs=V),{content:P,finishReason:cd({finishReason:(d=S.incomplete_details)==null?void 0:d.reason,hasToolCalls:P.some(B=>B.type==="tool-call")}),usage:{inputTokens:S.usage.input_tokens,outputTokens:S.usage.output_tokens,totalTokens:S.usage.input_tokens+S.usage.output_tokens,reasoningTokens:(y=(f=S.usage.output_tokens_details)==null?void 0:f.reasoning_tokens)!=null?y:void 0,cachedInputTokens:(p=(v=S.usage.input_tokens_details)==null?void 0:v.cached_tokens)!=null?p:void 0},request:{body:b},response:{id:S.id,timestamp:new Date(S.created_at*1e3),modelId:S.model,headers:E,body:T},providerMetadata:H,warnings:g}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:o}=await mt({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Tt,successfulResponseHandler:io(Sk),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=this;let a="unknown";const i={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=[];let u=null;const c={};let w=!1;const _={};return{stream:o.pipeThrough(new TransformStream({start(d){d.enqueue({type:"stream-start",warnings:n})},transform(d,f){var y,v,p,b,g,m,E,S,T,P,V,H,B,oe,F,be,Ee,Ne,Xe;if(e.includeRawChunks&&f.enqueue({type:"raw",rawValue:d.rawValue}),!d.success){a="error",f.enqueue({type:"error",error:d.error});return}const I=d.value;if(md(I))I.item.type==="function_call"?(c[I.output_index]={toolName:I.item.name,toolCallId:I.item.call_id},f.enqueue({type:"tool-input-start",id:I.item.call_id,toolName:I.item.name})):I.item.type==="web_search_call"?(c[I.output_index]={toolName:"web_search_preview",toolCallId:I.item.id},f.enqueue({type:"tool-input-start",id:I.item.id,toolName:"web_search_preview"})):I.item.type==="computer_call"?(c[I.output_index]={toolName:"computer_use",toolCallId:I.item.id},f.enqueue({type:"tool-input-start",id:I.item.id,toolName:"computer_use"})):I.item.type==="file_search_call"?(c[I.output_index]={toolName:"file_search",toolCallId:I.item.id},f.enqueue({type:"tool-input-start",id:I.item.id,toolName:"file_search"})):I.item.type==="message"?f.enqueue({type:"text-start",id:I.item.id,providerMetadata:{openai:{itemId:I.item.id}}}):Ok(I)&&(_[I.item.id]={encryptedContent:I.item.encrypted_content,summaryParts:[0]},f.enqueue({type:"reasoning-start",id:`${I.item.id}:0`,providerMetadata:{openai:{itemId:I.item.id,reasoningEncryptedContent:(y=I.item.encrypted_content)!=null?y:null}}}));else if(fd(I)){if(I.item.type==="function_call")c[I.output_index]=void 0,w=!0,f.enqueue({type:"tool-input-end",id:I.item.call_id}),f.enqueue({type:"tool-call",toolCallId:I.item.call_id,toolName:I.item.name,input:I.item.arguments,providerMetadata:{openai:{itemId:I.item.id}}});else if(I.item.type==="web_search_call")c[I.output_index]=void 0,w=!0,f.enqueue({type:"tool-input-end",id:I.item.id}),f.enqueue({type:"tool-call",toolCallId:I.item.id,toolName:"web_search_preview",input:(p=(v=I.item.action)==null?void 0:v.query)!=null?p:"",providerExecuted:!0}),f.enqueue({type:"tool-result",toolCallId:I.item.id,toolName:"web_search_preview",result:{type:"web_search_tool_result",status:I.item.status||"completed",...((b=I.item.action)==null?void 0:b.query)&&{query:I.item.action.query}},providerExecuted:!0});else if(I.item.type==="computer_call")c[I.output_index]=void 0,w=!0,f.enqueue({type:"tool-input-end",id:I.item.id}),f.enqueue({type:"tool-call",toolCallId:I.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),f.enqueue({type:"tool-result",toolCallId:I.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:I.item.status||"completed"},providerExecuted:!0});else if(I.item.type==="file_search_call")c[I.output_index]=void 0,w=!0,f.enqueue({type:"tool-input-end",id:I.item.id}),f.enqueue({type:"tool-call",toolCallId:I.item.id,toolName:"file_search",input:"",providerExecuted:!0}),f.enqueue({type:"tool-result",toolCallId:I.item.id,toolName:"file_search",result:{type:"file_search_tool_result",status:I.item.status||"completed",...I.item.queries&&{queries:I.item.queries},...I.item.results&&{results:I.item.results}},providerExecuted:!0});else if(I.item.type==="message")f.enqueue({type:"text-end",id:I.item.id});else if(Ck(I)){const ie=_[I.item.id];for(const me of ie.summaryParts)f.enqueue({type:"reasoning-end",id:`${I.item.id}:${me}`,providerMetadata:{openai:{itemId:I.item.id,reasoningEncryptedContent:(g=I.item.encrypted_content)!=null?g:null}}});delete _[I.item.id]}}else if(Ak(I)){const ie=c[I.output_index];ie!=null&&f.enqueue({type:"tool-input-delta",id:ie.toolCallId,delta:I.delta})}else Rk(I)?(u=I.response.id,f.enqueue({type:"response-metadata",id:I.response.id,timestamp:new Date(I.response.created_at*1e3),modelId:I.response.model})):Ik(I)?(f.enqueue({type:"text-delta",id:I.item_id,delta:I.delta}),I.logprobs&&l.push(I.logprobs)):Mk(I)?I.summary_index>0&&((m=_[I.item_id])==null||m.summaryParts.push(I.summary_index),f.enqueue({type:"reasoning-start",id:`${I.item_id}:${I.summary_index}`,providerMetadata:{openai:{itemId:I.item_id,reasoningEncryptedContent:(S=(E=_[I.item_id])==null?void 0:E.encryptedContent)!=null?S:null}}})):Pk(I)?f.enqueue({type:"reasoning-delta",id:`${I.item_id}:${I.summary_index}`,delta:I.delta,providerMetadata:{openai:{itemId:I.item_id}}}):Ek(I)?(a=cd({finishReason:(T=I.response.incomplete_details)==null?void 0:T.reason,hasToolCalls:w}),i.inputTokens=I.response.usage.input_tokens,i.outputTokens=I.response.usage.output_tokens,i.totalTokens=I.response.usage.input_tokens+I.response.usage.output_tokens,i.reasoningTokens=(V=(P=I.response.usage.output_tokens_details)==null?void 0:P.reasoning_tokens)!=null?V:void 0,i.cachedInputTokens=(B=(H=I.response.usage.input_tokens_details)==null?void 0:H.cached_tokens)!=null?B:void 0):Nk(I)?I.annotation.type==="url_citation"?f.enqueue({type:"source",sourceType:"url",id:(be=(F=(oe=s.config).generateId)==null?void 0:F.call(oe))!=null?be:tt(),url:I.annotation.url,title:I.annotation.title}):I.annotation.type==="file_citation"&&f.enqueue({type:"source",sourceType:"document",id:(Xe=(Ne=(Ee=s.config).generateId)==null?void 0:Ne.call(Ee))!=null?Xe:tt(),mediaType:"text/plain",title:I.annotation.quote,filename:I.annotation.file_id}):$k(I)&&f.enqueue({type:"error",error:I})},flush(d){const f={openai:{responseId:u}};l.length>0&&(f.openai.logprobs=l),d.enqueue({type:"finish",finishReason:a,usage:i,providerMetadata:f})}})),request:{body:t},response:{headers:r}}}},hd=x({input_tokens:R(),input_tokens_details:x({cached_tokens:R().nullish()}).nullish(),output_tokens:R(),output_tokens_details:x({reasoning_tokens:R().nullish()}).nullish()}),mk=x({type:A("response.output_text.delta"),item_id:h(),delta:h(),logprobs:pd.nullish()}),gk=x({type:A("error"),code:h(),message:h(),param:h().nullish(),sequence_number:R()}),yk=x({type:qe(["response.completed","response.incomplete"]),response:x({incomplete_details:x({reason:h()}).nullish(),usage:hd})}),vk=x({type:A("response.created"),response:x({id:h(),created_at:R(),model:h()})}),_k=x({type:A("response.output_item.added"),output_index:R(),item:cn("type",[x({type:A("message"),id:h()}),x({type:A("reasoning"),id:h(),encrypted_content:h().nullish()}),x({type:A("function_call"),id:h(),call_id:h(),name:h(),arguments:h()}),x({type:A("web_search_call"),id:h(),status:h(),action:x({type:A("search"),query:h().optional()}).nullish()}),x({type:A("computer_call"),id:h(),status:h()}),x({type:A("file_search_call"),id:h(),status:h(),queries:Z(h()).nullish(),results:Z(x({attributes:x({file_id:h(),filename:h(),score:R(),text:h()})})).optional()})])}),wk=x({type:A("response.output_item.done"),output_index:R(),item:cn("type",[x({type:A("message"),id:h()}),x({type:A("reasoning"),id:h(),encrypted_content:h().nullish()}),x({type:A("function_call"),id:h(),call_id:h(),name:h(),arguments:h(),status:A("completed")}),x({type:A("web_search_call"),id:h(),status:A("completed"),action:x({type:A("search"),query:h().optional()}).nullish()}),x({type:A("computer_call"),id:h(),status:A("completed")}),x({type:A("file_search_call"),id:h(),status:A("completed"),queries:Z(h()).nullish(),results:Z(x({attributes:x({file_id:h(),filename:h(),score:R(),text:h()})})).nullish()})])}),bk=x({type:A("response.function_call_arguments.delta"),item_id:h(),output_index:R(),delta:h()}),xk=x({type:A("response.output_text.annotation.added"),annotation:cn("type",[x({type:A("url_citation"),url:h(),title:h()}),x({type:A("file_citation"),file_id:h(),quote:h()})])}),kk=x({type:A("response.reasoning_summary_part.added"),item_id:h(),summary_index:R()}),Tk=x({type:A("response.reasoning_summary_text.delta"),item_id:h(),summary_index:R(),delta:h()}),Sk=ee([mk,yk,vk,_k,wk,bk,xk,kk,Tk,gk,x({type:h()}).loose()]);function Ik(e){return e.type==="response.output_text.delta"}function fd(e){return e.type==="response.output_item.done"}function Ck(e){return fd(e)&&e.item.type==="reasoning"}function Ek(e){return e.type==="response.completed"||e.type==="response.incomplete"}function Rk(e){return e.type==="response.created"}function Ak(e){return e.type==="response.function_call_arguments.delta"}function md(e){return e.type==="response.output_item.added"}function Ok(e){return md(e)&&e.item.type==="reasoning"}function Nk(e){return e.type==="response.output_text.annotation.added"}function Mk(e){return e.type==="response.reasoning_summary_part.added"}function Pk(e){return e.type==="response.reasoning_summary_text.delta"}function $k(e){return e.type==="error"}function zk(e){const 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 jk=x({metadata:pt().nullish(),parallelToolCalls:re().nullish(),previousResponseId:h().nullish(),store:re().nullish(),user:h().nullish(),reasoningEffort:h().nullish(),strictJsonSchema:re().nullish(),instructions:h().nullish(),reasoningSummary:h().nullish(),serviceTier:qe(["auto","flex","priority"]).nullish(),include:Z(qe(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),textVerbosity:qe(["low","medium","high"]).nullish(),promptCacheKey:h().nullish(),safetyIdentifier:h().nullish(),logprobs:ee([re(),R().min(1).max(dd)]).optional()}),Dk=x({instructions:h().nullish(),speed:R().min(.25).max(4).default(1).nullish()}),Zk=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:o,language:s,providerOptions:a}){const i=[],l=await kt({provider:"openai",providerOptions:a,schema:Dk}),u={model:this.modelId,input:e,voice:t,response_format:"mp3",speed:r,instructions:o};if(n&&(["mp3","opus","aac","flac","wav","pcm"].includes(n)?u.response_format=n:i.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${n}. Using mp3 instead.`})),l){const c={};for(const w in c){const _=c[w];_!==void 0&&(u[w]=_)}}return s&&i.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${s}" was ignored.`}),{requestBody:u,warnings:i}}async doGenerate(e){var t,n,r;const o=(r=(n=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:n.call(t))!=null?r:new Date,{requestBody:s,warnings:a}=await this.getArgs(e),{value:i,responseHeaders:l,rawValue:u}=await mt({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),body:s,failedResponseHandler:Tt,successfulResponseHandler:Mx(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:i,warnings:a,request:{body:JSON.stringify(s)},response:{timestamp:o,modelId:this.modelId,headers:l,body:u}}}},Uk=x({include:Z(h()).optional(),language:h().optional(),prompt:h().optional(),temperature:R().min(0).max(1).default(0).optional(),timestampGranularities:Z(qe(["word","segment"])).default(["segment"]).optional()}),gd={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"},Lk=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}){const r=[],o=await kt({provider:"openai",providerOptions:n,schema:Uk}),s=new FormData,a=e instanceof Uint8Array?new Blob([e]):new Blob([zx(e)]);if(s.append("model",this.modelId),s.append("file",new File([a],"audio",{type:t})),o){const i={include:o.include,language:o.language,prompt:o.prompt,response_format:"verbose_json",temperature:o.temperature,timestamp_granularities:o.timestampGranularities};for(const[l,u]of Object.entries(i))u!=null&&s.append(l,String(u))}return{formData:s,warnings:r}}async doGenerate(e){var t,n,r,o,s,a,i,l;const u=(r=(n=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:n.call(t))!=null?r:new Date,{formData:c,warnings:w}=await this.getArgs(e),{value:_,responseHeaders:d,rawValue:f}=await Nx({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),formData:c,failedResponseHandler:Tt,successfulResponseHandler:on(qk),abortSignal:e.abortSignal,fetch:this.config.fetch}),y=_.language!=null&&_.language in gd?gd[_.language]:void 0;return{text:_.text,segments:(i=(a=(o=_.segments)==null?void 0:o.map(v=>({text:v.text,startSecond:v.start,endSecond:v.end})))!=null?a:(s=_.words)==null?void 0:s.map(v=>({text:v.word,startSecond:v.start,endSecond:v.end})))!=null?i:[],language:y,durationInSeconds:(l=_.duration)!=null?l:void 0,warnings:w,response:{timestamp:u,modelId:this.modelId,headers:d,body:f}}}},qk=x({text:h(),language:h().nullish(),duration:R().nullish(),words:Z(x({word:h(),start:R(),end:R()})).nullish(),segments:Z(x({id:R(),seek:R(),start:R(),end:R(),text:h(),tokens:Z(R()),temperature:R(),avg_logprob:R(),compression_ratio:R(),no_speech_prob:R()})).nullish()});function yd(e={}){var t,n;const r=(t=Kc(e.baseURL))!=null?t:"https://api.openai.com/v1",o=(n=e.name)!=null?n:"openai",s=()=>({Authorization:`Bearer ${Hc({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers}),a=y=>new Vx(y,{provider:`${o}.chat`,url:({path:v})=>`${r}${v}`,headers:s,fetch:e.fetch}),i=y=>new Xx(y,{provider:`${o}.completion`,url:({path:v})=>`${r}${v}`,headers:s,fetch:e.fetch}),l=y=>new nk(y,{provider:`${o}.embedding`,url:({path:v})=>`${r}${v}`,headers:s,fetch:e.fetch}),u=y=>new ak(y,{provider:`${o}.image`,url:({path:v})=>`${r}${v}`,headers:s,fetch:e.fetch}),c=y=>new Lk(y,{provider:`${o}.transcription`,url:({path:v})=>`${r}${v}`,headers:s,fetch:e.fetch}),w=y=>new Zk(y,{provider:`${o}.speech`,url:({path:v})=>`${r}${v}`,headers:s,fetch:e.fetch}),_=y=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return d(y)},d=y=>new fk(y,{provider:`${o}.responses`,url:({path:v})=>`${r}${v}`,headers:s,fetch:e.fetch,fileIdPrefixes:["file-"]}),f=function(y){return _(y)};return f.languageModel=_,f.chat=a,f.completion=i,f.responses=d,f.embedding=l,f.textEmbedding=l,f.textEmbeddingModel=l,f.image=u,f.imageModel=u,f.transcription=c,f.transcriptionModel=c,f.speech=w,f.speechModel=w,f.tools=ck,f}yd();function sr(e){var t,n;return(n=(t=e==null?void 0:e.providerOptions)==null?void 0:t.openaiCompatible)!=null?n:{}}function Bk(e){const t=[];for(const{role:n,content:r,...o}of e){const s=sr({...o});switch(n){case"system":{t.push({role:"system",content:r,...s});break}case"user":{if(r.length===1&&r[0].type==="text"){t.push({role:"user",content:r[0].text,...sr(r[0])});break}t.push({role:"user",content:r.map(a=>{const i=sr(a);switch(a.type){case"text":return{type:"text",text:a.text,...i};case"file":if(a.mediaType.startsWith("image/")){const l=a.mediaType==="image/*"?"image/jpeg":a.mediaType;return{type:"image_url",image_url:{url:a.data instanceof URL?a.data.toString():`data:${l};base64,${sn(a.data)}`},...i}}else throw new at({functionality:`file part media type ${a.mediaType}`})}}),...s});break}case"assistant":{let a="";const i=[];for(const l of r){const u=sr(l);switch(l.type){case"text":{a+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)},...u});break}}}t.push({role:"assistant",content:a,tool_calls:i.length>0?i:void 0,...s});break}case"tool":{for(const a of r){const i=a.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}const u=sr(a);t.push({role:"tool",tool_call_id:a.toolCallId,content:l,...u})}break}default:{const a=n;throw new Error(`Unsupported role: ${a}`)}}}return t}function vd({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}function _d(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 wd=x({user:h().optional(),reasoningEffort:h().optional()}),Vk=x({error:x({message:h(),type:h().nullish(),param:pt().nullish(),code:ee([h(),R()]).nullish()})}),Fk={errorSchema:Vk,errorToMessage:e=>e.error.message};function Hk({tools:e,toolChoice:t}){e=e!=null&&e.length?e:void 0;const n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const r=[];for(const s of e)s.type==="provider-defined"?n.push({type:"unsupported-tool",tool:s}):r.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema}});if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:r,toolChoice:o,toolWarnings:n};case"tool":return{tools:r,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:n};default:{const s=o;throw new at({functionality:`tool choice type: ${s}`})}}}var Jk=class{constructor(e,t){this.specificationVersion="v2";var n,r;this.modelId=e,this.config=t;const o=(n=t.errorStructure)!=null?n:Fk;this.chunkSchema=Wk(o.errorSchema),this.failedResponseHandler=Wc(o),this.supportsStructuredOutputs=(r=t.supportsStructuredOutputs)!=null?r:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var e,t,n;return(n=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?n:{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:s,presencePenalty:a,providerOptions:i,stopSequences:l,responseFormat:u,seed:c,toolChoice:w,tools:_}){var d,f,y;const v=[],p=Object.assign((d=await kt({provider:"openai-compatible",providerOptions:i,schema:wd}))!=null?d:{},(f=await kt({provider:this.providerOptionsName,providerOptions:i,schema:wd}))!=null?f:{});o!=null&&v.push({type:"unsupported-setting",setting:"topK"}),(u==null?void 0:u.type)==="json"&&u.schema!=null&&!this.supportsStructuredOutputs&&v.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:b,toolChoice:g,toolWarnings:m}=Hk({tools:_,toolChoice:w});return{args:{model:this.modelId,user:p.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:s,presence_penalty:a,response_format:(u==null?void 0:u.type)==="json"?this.supportsStructuredOutputs===!0&&u.schema!=null?{type:"json_schema",json_schema:{schema:u.schema,name:(y=u.name)!=null?y:"response",description:u.description}}:{type:"json_object"}:void 0,stop:l,seed:c,...i==null?void 0:i[this.providerOptionsName],reasoning_effort:p.reasoningEffort,messages:Bk(e),tools:b,tool_choice:g},warnings:[...v,...m]}}async doGenerate(e){var t,n,r,o,s,a,i,l,u,c,w,_,d,f,y,v,p;const{args:b,warnings:g}=await this.getArgs({...e}),m=JSON.stringify(b),{responseHeaders:E,value:S,rawValue:T}=await mt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),body:b,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:on(Gk),abortSignal:e.abortSignal,fetch:this.config.fetch}),P=S.choices[0],V=[],H=P.message.content;H!=null&&H.length>0&&V.push({type:"text",text:H});const B=(t=P.message.reasoning_content)!=null?t:P.message.reasoning;if(B!=null&&B.length>0&&V.push({type:"reasoning",text:B}),P.message.tool_calls!=null)for(const be of P.message.tool_calls)V.push({type:"tool-call",toolCallId:(n=be.id)!=null?n:tt(),toolName:be.function.name,input:be.function.arguments});const oe={[this.providerOptionsName]:{},...await((o=(r=this.config.metadataExtractor)==null?void 0:r.extractMetadata)==null?void 0:o.call(r,{parsedBody:T}))},F=(s=S.usage)==null?void 0:s.completion_tokens_details;return(F==null?void 0:F.accepted_prediction_tokens)!=null&&(oe[this.providerOptionsName].acceptedPredictionTokens=F==null?void 0:F.accepted_prediction_tokens),(F==null?void 0:F.rejected_prediction_tokens)!=null&&(oe[this.providerOptionsName].rejectedPredictionTokens=F==null?void 0:F.rejected_prediction_tokens),{content:V,finishReason:_d(P.finish_reason),usage:{inputTokens:(i=(a=S.usage)==null?void 0:a.prompt_tokens)!=null?i:void 0,outputTokens:(u=(l=S.usage)==null?void 0:l.completion_tokens)!=null?u:void 0,totalTokens:(w=(c=S.usage)==null?void 0:c.total_tokens)!=null?w:void 0,reasoningTokens:(f=(d=(_=S.usage)==null?void 0:_.completion_tokens_details)==null?void 0:d.reasoning_tokens)!=null?f:void 0,cachedInputTokens:(p=(v=(y=S.usage)==null?void 0:y.prompt_tokens_details)==null?void 0:v.cached_tokens)!=null?p:void 0},providerMetadata:oe,request:{body:m},response:{...vd(S),headers:E,body:T},warnings:g}}async doStream(e){var t;const{args:n,warnings:r}=await this.getArgs({...e}),o={...n,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},s=(t=this.config.metadataExtractor)==null?void 0:t.createStreamExtractor(),{responseHeaders:a,value:i}=await mt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:io(this.chunkSchema),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=[];let u="unknown";const c={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let w=!0;const _=this.providerOptionsName;let d=!1,f=!1;return{stream:i.pipeThrough(new TransformStream({start(y){y.enqueue({type:"stream-start",warnings:r})},transform(y,v){var p,b,g,m,E,S,T,P,V,H,B,oe,F;if(e.includeRawChunks&&v.enqueue({type:"raw",rawValue:y.rawValue}),!y.success){u="error",v.enqueue({type:"error",error:y.error});return}const be=y.value;if(s==null||s.processChunk(y.rawValue),"error"in be){u="error",v.enqueue({type:"error",error:be.error.message});return}if(w&&(w=!1,v.enqueue({type:"response-metadata",...vd(be)})),be.usage!=null){const{prompt_tokens:I,completion_tokens:ie,total_tokens:me,prompt_tokens_details:de,completion_tokens_details:Q}=be.usage;c.promptTokens=I??void 0,c.completionTokens=ie??void 0,c.totalTokens=me??void 0,(Q==null?void 0:Q.reasoning_tokens)!=null&&(c.completionTokensDetails.reasoningTokens=Q==null?void 0:Q.reasoning_tokens),(Q==null?void 0:Q.accepted_prediction_tokens)!=null&&(c.completionTokensDetails.acceptedPredictionTokens=Q==null?void 0:Q.accepted_prediction_tokens),(Q==null?void 0:Q.rejected_prediction_tokens)!=null&&(c.completionTokensDetails.rejectedPredictionTokens=Q==null?void 0:Q.rejected_prediction_tokens),(de==null?void 0:de.cached_tokens)!=null&&(c.promptTokensDetails.cachedTokens=de==null?void 0:de.cached_tokens)}const Ee=be.choices[0];if((Ee==null?void 0:Ee.finish_reason)!=null&&(u=_d(Ee.finish_reason)),(Ee==null?void 0:Ee.delta)==null)return;const Ne=Ee.delta,Xe=(p=Ne.reasoning_content)!=null?p:Ne.reasoning;if(Xe&&(d||(v.enqueue({type:"reasoning-start",id:"reasoning-0"}),d=!0),v.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:Xe})),Ne.content&&(f||(v.enqueue({type:"text-start",id:"txt-0"}),f=!0),v.enqueue({type:"text-delta",id:"txt-0",delta:Ne.content})),Ne.tool_calls!=null)for(const I of Ne.tool_calls){const ie=I.index;if(l[ie]==null){if(I.id==null)throw new In({data:I,message:"Expected 'id' to be a string."});if(((b=I.function)==null?void 0:b.name)==null)throw new In({data:I,message:"Expected 'function.name' to be a string."});v.enqueue({type:"tool-input-start",id:I.id,toolName:I.function.name}),l[ie]={id:I.id,type:"function",function:{name:I.function.name,arguments:(g=I.function.arguments)!=null?g:""},hasFinished:!1};const de=l[ie];((m=de.function)==null?void 0:m.name)!=null&&((E=de.function)==null?void 0:E.arguments)!=null&&(de.function.arguments.length>0&&v.enqueue({type:"tool-input-start",id:de.id,toolName:de.function.name}),ao(de.function.arguments)&&(v.enqueue({type:"tool-input-end",id:de.id}),v.enqueue({type:"tool-call",toolCallId:(S=de.id)!=null?S:tt(),toolName:de.function.name,input:de.function.arguments}),de.hasFinished=!0));continue}const me=l[ie];me.hasFinished||(((T=I.function)==null?void 0:T.arguments)!=null&&(me.function.arguments+=(V=(P=I.function)==null?void 0:P.arguments)!=null?V:""),v.enqueue({type:"tool-input-delta",id:me.id,delta:(H=I.function.arguments)!=null?H:""}),((B=me.function)==null?void 0:B.name)!=null&&((oe=me.function)==null?void 0:oe.arguments)!=null&&ao(me.function.arguments)&&(v.enqueue({type:"tool-input-end",id:me.id}),v.enqueue({type:"tool-call",toolCallId:(F=me.id)!=null?F:tt(),toolName:me.function.name,input:me.function.arguments}),me.hasFinished=!0))}},flush(y){var v,p,b,g,m,E;d&&y.enqueue({type:"reasoning-end",id:"reasoning-0"}),f&&y.enqueue({type:"text-end",id:"txt-0"});for(const T of l.filter(P=>!P.hasFinished))y.enqueue({type:"tool-input-end",id:T.id}),y.enqueue({type:"tool-call",toolCallId:(v=T.id)!=null?v:tt(),toolName:T.function.name,input:T.function.arguments});const S={[_]:{},...s==null?void 0:s.buildMetadata()};c.completionTokensDetails.acceptedPredictionTokens!=null&&(S[_].acceptedPredictionTokens=c.completionTokensDetails.acceptedPredictionTokens),c.completionTokensDetails.rejectedPredictionTokens!=null&&(S[_].rejectedPredictionTokens=c.completionTokensDetails.rejectedPredictionTokens),y.enqueue({type:"finish",finishReason:u,usage:{inputTokens:(p=c.promptTokens)!=null?p:void 0,outputTokens:(b=c.completionTokens)!=null?b:void 0,totalTokens:(g=c.totalTokens)!=null?g:void 0,reasoningTokens:(m=c.completionTokensDetails.reasoningTokens)!=null?m:void 0,cachedInputTokens:(E=c.promptTokensDetails.cachedTokens)!=null?E:void 0},providerMetadata:S})}})),request:{body:o},response:{headers:a}}}},bd=x({prompt_tokens:R().nullish(),completion_tokens:R().nullish(),total_tokens:R().nullish(),prompt_tokens_details:x({cached_tokens:R().nullish()}).nullish(),completion_tokens_details:x({reasoning_tokens:R().nullish(),accepted_prediction_tokens:R().nullish(),rejected_prediction_tokens:R().nullish()}).nullish()}).nullish(),Gk=x({id:h().nullish(),created:R().nullish(),model:h().nullish(),choices:Z(x({message:x({role:A("assistant").nullish(),content:h().nullish(),reasoning_content:h().nullish(),reasoning:h().nullish(),tool_calls:Z(x({id:h().nullish(),function:x({name:h(),arguments:h()})})).nullish()}),finish_reason:h().nullish()})),usage:bd}),Wk=e=>ee([x({id:h().nullish(),created:R().nullish(),model:h().nullish(),choices:Z(x({delta:x({role:qe(["assistant"]).nullish(),content:h().nullish(),reasoning_content:h().nullish(),reasoning:h().nullish(),tool_calls:Z(x({index:R(),id:h().nullish(),function:x({name:h().nullish(),arguments:h().nullish()})})).nullish()}).nullish(),finish_reason:h().nullish()})),usage:bd}),e]);x({echo:re().optional(),logitBias:We(h(),R()).optional(),suffix:h().optional(),user:h().optional()});var Kk=x({prompt_tokens:R(),completion_tokens:R(),total_tokens:R()});x({id:h().nullish(),created:R().nullish(),model:h().nullish(),choices:Z(x({text:h(),finish_reason:h()})),usage:Kk.nullish()}),x({dimensions:R().optional(),user:h().optional()}),x({data:Z(x({embedding:Z(R())})),usage:x({prompt_tokens:R()}).nullish(),providerMetadata:We(h(),We(h(),pt())).optional()}),x({data:Z(x({b64_json:h()}))});var xd=e=>{var t,n;return e==null?void 0:{deepseek:{promptCacheHitTokens:(t=e.prompt_cache_hit_tokens)!=null?t:NaN,promptCacheMissTokens:(n=e.prompt_cache_miss_tokens)!=null?n:NaN}}},Yk={extractMetadata:async({parsedBody:e})=>{const t=await or({value:e,schema:Xk});return!t.success||t.value.usage==null?void 0:xd(t.value.usage)},createStreamExtractor:()=>{let e;return{processChunk:async t=>{var n,r;const o=await or({value:t,schema:Qk});o.success&&((r=(n=o.value.choices)==null?void 0:n[0])==null?void 0:r.finish_reason)==="stop"&&o.value.usage&&(e=o.value.usage)},buildMetadata:()=>xd(e)}}},kd=x({prompt_cache_hit_tokens:R().nullish(),prompt_cache_miss_tokens:R().nullish()}),Xk=x({usage:kd.nullish()}),Qk=x({choices:Z(x({finish_reason:h().nullish()})).nullish(),usage:kd.nullish()});function Td(e={}){var t;const n=Kc((t=e.baseURL)!=null?t:"https://api.deepseek.com/v1"),r=()=>({Authorization:`Bearer ${Hc({apiKey:e.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...e.headers}),o=a=>new Jk(a,{provider:"deepseek.chat",url:({path:i})=>`${n}${i}`,headers:r,fetch:e.fetch,metadataExtractor:Yk}),s=a=>o(a);return s.languageModel=o,s.chat=o,s.textEmbeddingModel=a=>{throw new wo({modelId:a,modelType:"textEmbeddingModel"})},s.imageModel=a=>{throw new wo({modelId:a,modelType:"imageModel"})},s}Td();const eT={openai:yd,deepseek:Td};class tT{constructor({llmConfig:t,mcpServers:n,llm:r}){if(this.mcpServers=[],this.mcpClients=[],this.mcpTools=[],this.ignoreToolnames=[],this.autoUpdateTools=!0,this.mcpServers=n||[],r)this.llm=r;else if(t){let o;typeof t.providerType=="string"?o=eT[t.providerType]:o=t.providerType,this.llm=o({apiKey:t.apiKey,baseURL:t.baseURL})}else throw new Error("Either llmConfig or llm must be provided")}async _createOneClient(t){try{let n;return"type"in t&&t.type.toLocaleLowerCase()==="streamablehttp"?n=new mx(new URL(t.url)):n=t,await O0({transport:n})}catch(n){return this.onError&&this.onError("Failed to create MCP client",n),console.error("Failed to create MCP client",t,n),null}}async _createMpcClients(){this.mcpClients=await Promise.all(this.mcpServers.map(async t=>this._createOneClient(t)))}async _createMpcTools(){this.mcpTools=await Promise.all(this.mcpClients.map(async t=>{var n;try{return t?await((n=t==null?void 0:t.tools)==null?void 0:n.call(t)):null}catch(r){return this.onError&&this.onError("Failed to query tools",r),console.error("Failed to query tools",r),null}}))}async closeAll(){await Promise.all(this.mcpClients.map(async t=>{try{t.close()}catch{}}))}async initClientsAndTools(){await this._createMpcClients(),await this._createMpcTools()}async updateMcpServers(t){await this.closeAll(),this.mcpServers=t,await this.initClientsAndTools()}async insertMcpServer(t){var r;if(!this.mcpServers.find(o=>"url"in o&&"url"in t&&o.url===t.url)){this.mcpServers=[...this.mcpServers,t];const o=await this._createOneClient(t);return this.mcpClients.push(o),this.mcpTools.push(await((r=o==null?void 0:o.tools)==null?void 0:r.call(o))),!0}return!1}removeMcpServer(t){const n=this.mcpServers.findIndex(s=>s===t);this.mcpServers.splice(n,1);const r=this.mcpClients[n];this.mcpClients.splice(n,1);try{r==null||r.close()}catch{}const o=this.mcpTools[n];this.mcpTools.splice(n,1),o&&Object.keys(o).forEach(s=>{this.ignoreToolnames=this.ignoreToolnames.filter(a=>a!==s)})}tempMergeTools(t={}){const n=this.mcpTools.reduce((r,o)=>({...r,...o}),{});return Object.assign(n,t),this.ignoreToolnames.forEach(r=>{delete n[r]}),n}async _chat(t,{model:n,maxSteps:r=5,...o}){var s;if(!this.llm)throw new Error("LLM is not initialized");return this.autoUpdateTools&&(await this._createMpcTools(),(s=this.onUpdatedTools)==null||s.call(this)),t({model:this.llm(n),stopWhen:vs(r),...o,tools:this.tempMergeTools(o.tools)})}async chat(t){return this._chat(zw,t)}async chatStream(t){return this._chat(n0,t)}}var vn={},nT=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then},Sd={},nt={};let Ys;const rT=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];nt.getSymbolSize=function(t){if(!t)throw new Error('"version" cannot be null or undefined');if(t<1||t>40)throw new Error('"version" should be in range from 1 to 40');return t*4+17},nt.getSymbolTotalCodewords=function(t){return rT[t]},nt.getBCHDigit=function(e){let t=0;for(;e!==0;)t++,e>>>=1;return t},nt.setToSJISFunction=function(t){if(typeof t!="function")throw new Error('"toSJISFunc" is not a valid function.');Ys=t},nt.isKanjiModeEnabled=function(){return typeof Ys<"u"},nt.toSJIS=function(t){return Ys(t)};var lo={};(function(e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+n)}}e.isValid=function(r){return r&&typeof r.bit<"u"&&r.bit>=0&&r.bit<4},e.from=function(r,o){if(e.isValid(r))return r;try{return t(r)}catch{return o}}})(lo);function Id(){this.buffer=[],this.length=0}Id.prototype={get:function(e){const t=Math.floor(e/8);return(this.buffer[t]>>>7-e%8&1)===1},put:function(e,t){for(let n=0;n<t;n++)this.putBit((e>>>t-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){const t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}};var oT=Id;function ar(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}ar.prototype.set=function(e,t,n,r){const o=e*this.size+t;this.data[o]=n,r&&(this.reservedBit[o]=!0)},ar.prototype.get=function(e,t){return this.data[e*this.size+t]},ar.prototype.xor=function(e,t,n){this.data[e*this.size+t]^=n},ar.prototype.isReserved=function(e,t){return this.reservedBit[e*this.size+t]};var sT=ar,Cd={};(function(e){const t=nt.getSymbolSize;e.getRowColCoords=function(r){if(r===1)return[];const o=Math.floor(r/7)+2,s=t(r),a=s===145?26:Math.ceil((s-13)/(2*o-2))*2,i=[s-7];for(let l=1;l<o-1;l++)i[l]=i[l-1]-a;return i.push(6),i.reverse()},e.getPositions=function(r){const o=[],s=e.getRowColCoords(r),a=s.length;for(let i=0;i<a;i++)for(let l=0;l<a;l++)i===0&&l===0||i===0&&l===a-1||i===a-1&&l===0||o.push([s[i],s[l]]);return o}})(Cd);var Ed={};const aT=nt.getSymbolSize,Rd=7;Ed.getPositions=function(t){const n=aT(t);return[[0,0],[n-Rd,0],[0,n-Rd]]};var Ad={};(function(e){e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(o){return o!=null&&o!==""&&!isNaN(o)&&o>=0&&o<=7},e.from=function(o){return e.isValid(o)?parseInt(o,10):void 0},e.getPenaltyN1=function(o){const s=o.size;let a=0,i=0,l=0,u=null,c=null;for(let w=0;w<s;w++){i=l=0,u=c=null;for(let _=0;_<s;_++){let d=o.get(w,_);d===u?i++:(i>=5&&(a+=t.N1+(i-5)),u=d,i=1),d=o.get(_,w),d===c?l++:(l>=5&&(a+=t.N1+(l-5)),c=d,l=1)}i>=5&&(a+=t.N1+(i-5)),l>=5&&(a+=t.N1+(l-5))}return a},e.getPenaltyN2=function(o){const s=o.size;let a=0;for(let i=0;i<s-1;i++)for(let l=0;l<s-1;l++){const u=o.get(i,l)+o.get(i,l+1)+o.get(i+1,l)+o.get(i+1,l+1);(u===4||u===0)&&a++}return a*t.N2},e.getPenaltyN3=function(o){const s=o.size;let a=0,i=0,l=0;for(let u=0;u<s;u++){i=l=0;for(let c=0;c<s;c++)i=i<<1&2047|o.get(u,c),c>=10&&(i===1488||i===93)&&a++,l=l<<1&2047|o.get(c,u),c>=10&&(l===1488||l===93)&&a++}return a*t.N3},e.getPenaltyN4=function(o){let s=0;const a=o.data.length;for(let l=0;l<a;l++)s+=o.data[l];return Math.abs(Math.ceil(s*100/a/5)-10)*t.N4};function n(r,o,s){switch(r){case e.Patterns.PATTERN000:return(o+s)%2===0;case e.Patterns.PATTERN001:return o%2===0;case e.Patterns.PATTERN010:return s%3===0;case e.Patterns.PATTERN011:return(o+s)%3===0;case e.Patterns.PATTERN100:return(Math.floor(o/2)+Math.floor(s/3))%2===0;case e.Patterns.PATTERN101:return o*s%2+o*s%3===0;case e.Patterns.PATTERN110:return(o*s%2+o*s%3)%2===0;case e.Patterns.PATTERN111:return(o*s%3+(o+s)%2)%2===0;default:throw new Error("bad maskPattern:"+r)}}e.applyMask=function(o,s){const a=s.size;for(let i=0;i<a;i++)for(let l=0;l<a;l++)s.isReserved(l,i)||s.xor(l,i,n(o,l,i))},e.getBestMask=function(o,s){const a=Object.keys(e.Patterns).length;let i=0,l=1/0;for(let u=0;u<a;u++){s(u),e.applyMask(u,o);const c=e.getPenaltyN1(o)+e.getPenaltyN2(o)+e.getPenaltyN3(o)+e.getPenaltyN4(o);e.applyMask(u,o),c<l&&(l=c,i=u)}return i}})(Ad);var uo={};const Lt=lo,co=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],po=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];uo.getBlocksCount=function(t,n){switch(n){case Lt.L:return co[(t-1)*4+0];case Lt.M:return co[(t-1)*4+1];case Lt.Q:return co[(t-1)*4+2];case Lt.H:return co[(t-1)*4+3];default:return}},uo.getTotalCodewordsCount=function(t,n){switch(n){case Lt.L:return po[(t-1)*4+0];case Lt.M:return po[(t-1)*4+1];case Lt.Q:return po[(t-1)*4+2];case Lt.H:return po[(t-1)*4+3];default:return}};var Od={},ho={};const ir=new Uint8Array(512),fo=new Uint8Array(256);(function(){let t=1;for(let n=0;n<255;n++)ir[n]=t,fo[t]=n,t<<=1,t&256&&(t^=285);for(let n=255;n<512;n++)ir[n]=ir[n-255]})(),ho.log=function(t){if(t<1)throw new Error("log("+t+")");return fo[t]},ho.exp=function(t){return ir[t]},ho.mul=function(t,n){return t===0||n===0?0:ir[fo[t]+fo[n]]},function(e){const t=ho;e.mul=function(r,o){const s=new Uint8Array(r.length+o.length-1);for(let a=0;a<r.length;a++)for(let i=0;i<o.length;i++)s[a+i]^=t.mul(r[a],o[i]);return s},e.mod=function(r,o){let s=new Uint8Array(r);for(;s.length-o.length>=0;){const a=s[0];for(let l=0;l<o.length;l++)s[l]^=t.mul(o[l],a);let i=0;for(;i<s.length&&s[i]===0;)i++;s=s.slice(i)}return s},e.generateECPolynomial=function(r){let o=new Uint8Array([1]);for(let s=0;s<r;s++)o=e.mul(o,new Uint8Array([1,t.exp(s)]));return o}}(Od);const Nd=Od;function Xs(e){this.genPoly=void 0,this.degree=e,this.degree&&this.initialize(this.degree)}Xs.prototype.initialize=function(t){this.degree=t,this.genPoly=Nd.generateECPolynomial(this.degree)},Xs.prototype.encode=function(t){if(!this.genPoly)throw new Error("Encoder not initialized");const n=new Uint8Array(t.length+this.degree);n.set(t);const r=Nd.mod(n,this.genPoly),o=this.degree-r.length;if(o>0){const s=new Uint8Array(this.degree);return s.set(r,o),s}return r};var iT=Xs,Md={},qt={},Qs={};Qs.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40};var St={};const Pd="[0-9]+",lT="[A-Z $%*+\\-./:]+";let lr="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";lr=lr.replace(/u/g,"\\u");const uT="(?:(?![A-Z0-9 $%*+\\-./:]|"+lr+`)(?:.|[\r
|
|
77
77
|
]))+`;St.KANJI=new RegExp(lr,"g"),St.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),St.BYTE=new RegExp(uT,"g"),St.NUMERIC=new RegExp(Pd,"g"),St.ALPHANUMERIC=new RegExp(lT,"g");const cT=new RegExp("^"+lr+"$"),dT=new RegExp("^"+Pd+"$"),pT=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");St.testKanji=function(t){return cT.test(t)},St.testNumeric=function(t){return dT.test(t)},St.testAlphanumeric=function(t){return pT.test(t)},function(e){const t=Qs,n=St;e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(s,a){if(!s.ccBits)throw new Error("Invalid mode: "+s);if(!t.isValid(a))throw new Error("Invalid version: "+a);return a>=1&&a<10?s.ccBits[0]:a<27?s.ccBits[1]:s.ccBits[2]},e.getBestModeForData=function(s){return n.testNumeric(s)?e.NUMERIC:n.testAlphanumeric(s)?e.ALPHANUMERIC:n.testKanji(s)?e.KANJI:e.BYTE},e.toString=function(s){if(s&&s.id)return s.id;throw new Error("Invalid mode")},e.isValid=function(s){return s&&s.bit&&s.ccBits};function r(o){if(typeof o!="string")throw new Error("Param is not a string");switch(o.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+o)}}e.from=function(s,a){if(e.isValid(s))return s;try{return r(s)}catch{return a}}}(qt),function(e){const t=nt,n=uo,r=lo,o=qt,s=Qs,a=7973,i=t.getBCHDigit(a);function l(_,d,f){for(let y=1;y<=40;y++)if(d<=e.getCapacity(y,f,_))return y}function u(_,d){return o.getCharCountIndicator(_,d)+4}function c(_,d){let f=0;return _.forEach(function(y){const v=u(y.mode,d);f+=v+y.getBitsLength()}),f}function w(_,d){for(let f=1;f<=40;f++)if(c(_,f)<=e.getCapacity(f,d,o.MIXED))return f}e.from=function(d,f){return s.isValid(d)?parseInt(d,10):f},e.getCapacity=function(d,f,y){if(!s.isValid(d))throw new Error("Invalid QR Code version");typeof y>"u"&&(y=o.BYTE);const v=t.getSymbolTotalCodewords(d),p=n.getTotalCodewordsCount(d,f),b=(v-p)*8;if(y===o.MIXED)return b;const g=b-u(y,d);switch(y){case o.NUMERIC:return Math.floor(g/10*3);case o.ALPHANUMERIC:return Math.floor(g/11*2);case o.KANJI:return Math.floor(g/13);case o.BYTE:default:return Math.floor(g/8)}},e.getBestVersionForData=function(d,f){let y;const v=r.from(f,r.M);if(Array.isArray(d)){if(d.length>1)return w(d,v);if(d.length===0)return 1;y=d[0]}else y=d;return l(y.mode,y.getLength(),v)},e.getEncodedBits=function(d){if(!s.isValid(d)||d<7)throw new Error("Invalid QR Code version");let f=d<<12;for(;t.getBCHDigit(f)-i>=0;)f^=a<<t.getBCHDigit(f)-i;return d<<12|f}}(Md);var $d={};const ea=nt,zd=1335,hT=21522,jd=ea.getBCHDigit(zd);$d.getEncodedBits=function(t,n){const r=t.bit<<3|n;let o=r<<10;for(;ea.getBCHDigit(o)-jd>=0;)o^=zd<<ea.getBCHDigit(o)-jd;return(r<<10|o)^hT};var Dd={};const fT=qt;function _n(e){this.mode=fT.NUMERIC,this.data=e.toString()}_n.getBitsLength=function(t){return 10*Math.floor(t/3)+(t%3?t%3*3+1:0)},_n.prototype.getLength=function(){return this.data.length},_n.prototype.getBitsLength=function(){return _n.getBitsLength(this.data.length)},_n.prototype.write=function(t){let n,r,o;for(n=0;n+3<=this.data.length;n+=3)r=this.data.substr(n,3),o=parseInt(r,10),t.put(o,10);const s=this.data.length-n;s>0&&(r=this.data.substr(n),o=parseInt(r,10),t.put(o,s*3+1))};var mT=_n;const gT=qt,ta=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function wn(e){this.mode=gT.ALPHANUMERIC,this.data=e}wn.getBitsLength=function(t){return 11*Math.floor(t/2)+6*(t%2)},wn.prototype.getLength=function(){return this.data.length},wn.prototype.getBitsLength=function(){return wn.getBitsLength(this.data.length)},wn.prototype.write=function(t){let n;for(n=0;n+2<=this.data.length;n+=2){let r=ta.indexOf(this.data[n])*45;r+=ta.indexOf(this.data[n+1]),t.put(r,11)}this.data.length%2&&t.put(ta.indexOf(this.data[n]),6)};var yT=wn;const vT=qt;function bn(e){this.mode=vT.BYTE,typeof e=="string"?this.data=new TextEncoder().encode(e):this.data=new Uint8Array(e)}bn.getBitsLength=function(t){return t*8},bn.prototype.getLength=function(){return this.data.length},bn.prototype.getBitsLength=function(){return bn.getBitsLength(this.data.length)},bn.prototype.write=function(e){for(let t=0,n=this.data.length;t<n;t++)e.put(this.data[t],8)};var _T=bn;const wT=qt,bT=nt;function xn(e){this.mode=wT.KANJI,this.data=e}xn.getBitsLength=function(t){return t*13},xn.prototype.getLength=function(){return this.data.length},xn.prototype.getBitsLength=function(){return xn.getBitsLength(this.data.length)},xn.prototype.write=function(e){let t;for(t=0;t<this.data.length;t++){let n=bT.toSJIS(this.data[t]);if(n>=33088&&n<=40956)n-=33088;else if(n>=57408&&n<=60351)n-=49472;else throw new Error("Invalid SJIS character: "+this.data[t]+`
|
|
78
78
|
Make sure your charset is UTF-8`);n=(n>>>8&255)*192+(n&255),e.put(n,13)}};var xT=xn,Zd={exports:{}};(function(e){var t={single_source_shortest_paths:function(n,r,o){var s={},a={};a[r]=0;var i=t.PriorityQueue.make();i.push(r,0);for(var l,u,c,w,_,d,f,y,v;!i.empty();){l=i.pop(),u=l.value,w=l.cost,_=n[u]||{};for(c in _)_.hasOwnProperty(c)&&(d=_[c],f=w+d,y=a[c],v=typeof a[c]>"u",(v||y>f)&&(a[c]=f,i.push(c,f),s[c]=u))}if(typeof o<"u"&&typeof a[o]>"u"){var p=["Could not find a path from ",r," to ",o,"."].join("");throw new Error(p)}return s},extract_shortest_path_from_predecessor_list:function(n,r){for(var o=[],s=r;s;)o.push(s),n[s],s=n[s];return o.reverse(),o},find_path:function(n,r,o){var s=t.single_source_shortest_paths(n,r,o);return t.extract_shortest_path_from_predecessor_list(s,o)},PriorityQueue:{make:function(n){var r=t.PriorityQueue,o={},s;n=n||{};for(s in r)r.hasOwnProperty(s)&&(o[s]=r[s]);return o.queue=[],o.sorter=n.sorter||r.default_sorter,o},default_sorter:function(n,r){return n.cost-r.cost},push:function(n,r){var o={value:n,cost:r};this.queue.push(o),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};e.exports=t})(Zd);var kT=Zd.exports;(function(e){const t=qt,n=mT,r=yT,o=_T,s=xT,a=St,i=nt,l=kT;function u(p){return unescape(encodeURIComponent(p)).length}function c(p,b,g){const m=[];let E;for(;(E=p.exec(g))!==null;)m.push({data:E[0],index:E.index,mode:b,length:E[0].length});return m}function w(p){const b=c(a.NUMERIC,t.NUMERIC,p),g=c(a.ALPHANUMERIC,t.ALPHANUMERIC,p);let m,E;return i.isKanjiModeEnabled()?(m=c(a.BYTE,t.BYTE,p),E=c(a.KANJI,t.KANJI,p)):(m=c(a.BYTE_KANJI,t.BYTE,p),E=[]),b.concat(g,m,E).sort(function(T,P){return T.index-P.index}).map(function(T){return{data:T.data,mode:T.mode,length:T.length}})}function _(p,b){switch(b){case t.NUMERIC:return n.getBitsLength(p);case t.ALPHANUMERIC:return r.getBitsLength(p);case t.KANJI:return s.getBitsLength(p);case t.BYTE:return o.getBitsLength(p)}}function d(p){return p.reduce(function(b,g){const m=b.length-1>=0?b[b.length-1]:null;return m&&m.mode===g.mode?(b[b.length-1].data+=g.data,b):(b.push(g),b)},[])}function f(p){const b=[];for(let g=0;g<p.length;g++){const m=p[g];switch(m.mode){case t.NUMERIC:b.push([m,{data:m.data,mode:t.ALPHANUMERIC,length:m.length},{data:m.data,mode:t.BYTE,length:m.length}]);break;case t.ALPHANUMERIC:b.push([m,{data:m.data,mode:t.BYTE,length:m.length}]);break;case t.KANJI:b.push([m,{data:m.data,mode:t.BYTE,length:u(m.data)}]);break;case t.BYTE:b.push([{data:m.data,mode:t.BYTE,length:u(m.data)}])}}return b}function y(p,b){const g={},m={start:{}};let E=["start"];for(let S=0;S<p.length;S++){const T=p[S],P=[];for(let V=0;V<T.length;V++){const H=T[V],B=""+S+V;P.push(B),g[B]={node:H,lastCount:0},m[B]={};for(let oe=0;oe<E.length;oe++){const F=E[oe];g[F]&&g[F].node.mode===H.mode?(m[F][B]=_(g[F].lastCount+H.length,H.mode)-_(g[F].lastCount,H.mode),g[F].lastCount+=H.length):(g[F]&&(g[F].lastCount=H.length),m[F][B]=_(H.length,H.mode)+4+t.getCharCountIndicator(H.mode,b))}}E=P}for(let S=0;S<E.length;S++)m[E[S]].end=0;return{map:m,table:g}}function v(p,b){let g;const m=t.getBestModeForData(p);if(g=t.from(b,m),g!==t.BYTE&&g.bit<m.bit)throw new Error('"'+p+'" cannot be encoded with mode '+t.toString(g)+`.
|
|
79
79
|
Suggested mode is: `+t.toString(m));switch(g===t.KANJI&&!i.isKanjiModeEnabled()&&(g=t.BYTE),g){case t.NUMERIC:return new n(p);case t.ALPHANUMERIC:return new r(p);case t.KANJI:return new s(p);case t.BYTE:return new o(p)}}e.fromArray=function(b){return b.reduce(function(g,m){return typeof m=="string"?g.push(v(m,null)):m.data&&g.push(v(m.data,m.mode)),g},[])},e.fromString=function(b,g){const m=w(b,i.isKanjiModeEnabled()),E=f(m),S=y(E,g),T=l.find_path(S.map,"start","end"),P=[];for(let V=1;V<T.length-1;V++)P.push(S.table[T[V]].node);return e.fromArray(d(P))},e.rawSplit=function(b){return e.fromArray(w(b,i.isKanjiModeEnabled()))}})(Dd);const mo=nt,na=lo,TT=oT,ST=sT,IT=Cd,CT=Ed,ra=Ad,oa=uo,ET=iT,go=Md,RT=$d,AT=qt,sa=Dd;function OT(e,t){const n=e.size,r=CT.getPositions(t);for(let o=0;o<r.length;o++){const s=r[o][0],a=r[o][1];for(let i=-1;i<=7;i++)if(!(s+i<=-1||n<=s+i))for(let l=-1;l<=7;l++)a+l<=-1||n<=a+l||(i>=0&&i<=6&&(l===0||l===6)||l>=0&&l<=6&&(i===0||i===6)||i>=2&&i<=4&&l>=2&&l<=4?e.set(s+i,a+l,!0,!0):e.set(s+i,a+l,!1,!0))}}function NT(e){const t=e.size;for(let n=8;n<t-8;n++){const r=n%2===0;e.set(n,6,r,!0),e.set(6,n,r,!0)}}function MT(e,t){const n=IT.getPositions(t);for(let r=0;r<n.length;r++){const o=n[r][0],s=n[r][1];for(let a=-2;a<=2;a++)for(let i=-2;i<=2;i++)a===-2||a===2||i===-2||i===2||a===0&&i===0?e.set(o+a,s+i,!0,!0):e.set(o+a,s+i,!1,!0)}}function PT(e,t){const n=e.size,r=go.getEncodedBits(t);let o,s,a;for(let i=0;i<18;i++)o=Math.floor(i/3),s=i%3+n-8-3,a=(r>>i&1)===1,e.set(o,s,a,!0),e.set(s,o,a,!0)}function aa(e,t,n){const r=e.size,o=RT.getEncodedBits(t,n);let s,a;for(s=0;s<15;s++)a=(o>>s&1)===1,s<6?e.set(s,8,a,!0):s<8?e.set(s+1,8,a,!0):e.set(r-15+s,8,a,!0),s<8?e.set(8,r-s-1,a,!0):s<9?e.set(8,15-s-1+1,a,!0):e.set(8,15-s-1,a,!0);e.set(r-8,8,1,!0)}function $T(e,t){const n=e.size;let r=-1,o=n-1,s=7,a=0;for(let i=n-1;i>0;i-=2)for(i===6&&i--;;){for(let l=0;l<2;l++)if(!e.isReserved(o,i-l)){let u=!1;a<t.length&&(u=(t[a]>>>s&1)===1),e.set(o,i-l,u),s--,s===-1&&(a++,s=7)}if(o+=r,o<0||n<=o){o-=r,r=-r;break}}}function zT(e,t,n){const r=new TT;n.forEach(function(l){r.put(l.mode.bit,4),r.put(l.getLength(),AT.getCharCountIndicator(l.mode,e)),l.write(r)});const o=mo.getSymbolTotalCodewords(e),s=oa.getTotalCodewordsCount(e,t),a=(o-s)*8;for(r.getLengthInBits()+4<=a&&r.put(0,4);r.getLengthInBits()%8!==0;)r.putBit(0);const i=(a-r.getLengthInBits())/8;for(let l=0;l<i;l++)r.put(l%2?17:236,8);return jT(r,e,t)}function jT(e,t,n){const r=mo.getSymbolTotalCodewords(t),o=oa.getTotalCodewordsCount(t,n),s=r-o,a=oa.getBlocksCount(t,n),i=r%a,l=a-i,u=Math.floor(r/a),c=Math.floor(s/a),w=c+1,_=u-c,d=new ET(_);let f=0;const y=new Array(a),v=new Array(a);let p=0;const b=new Uint8Array(e.buffer);for(let T=0;T<a;T++){const P=T<l?c:w;y[T]=b.slice(f,f+P),v[T]=d.encode(y[T]),f+=P,p=Math.max(p,P)}const g=new Uint8Array(r);let m=0,E,S;for(E=0;E<p;E++)for(S=0;S<a;S++)E<y[S].length&&(g[m++]=y[S][E]);for(E=0;E<_;E++)for(S=0;S<a;S++)g[m++]=v[S][E];return g}function DT(e,t,n,r){let o;if(Array.isArray(e))o=sa.fromArray(e);else if(typeof e=="string"){let u=t;if(!u){const c=sa.rawSplit(e);u=go.getBestVersionForData(c,n)}o=sa.fromString(e,u||40)}else throw new Error("Invalid data");const s=go.getBestVersionForData(o,n);if(!s)throw new Error("The amount of data is too big to be stored in a QR Code");if(!t)t=s;else if(t<s)throw new Error(`
|