stacks-ai 0.2.8 → 0.2.9

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.
@@ -1,15 +0,0 @@
1
- import{_ as oo,Z as no,w as je,l as Ot,a as pe,b as Ge,p as me,c as Et,d as ge,r as Se,e as fe,A as Mt,f as Ve,o as t,h as be,i as Oe,v as ce,j as P,k as qt,m as Ie,U as _e,n as Y,q as ne,t as x,u as ae,x as n,y as e,z as a,B as Q,C as Be,D,N as ot,E as ve,F as Ue,G as we,H as ue,I as ye,J as Le,K as Ee,L as At,M as ao,O as qe,P as nt,T as $t,Q as Pt,R as io,S as Dt,V as We,W as lo,X as so,Y as ro}from"./index-Bu15JuLn.js";function uo(o){return oo(no,o)}var po="3.0.9",co=P(()=>D(t({type:n("error"),error:t({type:e(),message:e()})}))),at=Be({errorSchema:co,errorToMessage:o=>o.error.message}),_o=P(()=>D(t({type:n("message"),id:e().nullish(),model:e().nullish(),content:x(ae("type",[t({type:n("text"),text:e(),citations:x(ae("type",[t({type:n("web_search_result_location"),cited_text:e(),url:e(),title:e(),encrypted_index:e()}),t({type:n("page_location"),cited_text:e(),document_index:a(),document_title:e().nullable(),start_page_number:a(),end_page_number:a()}),t({type:n("char_location"),cited_text:e(),document_index:a(),document_title:e().nullable(),start_char_index:a(),end_char_index:a()})])).optional()}),t({type:n("thinking"),thinking:e(),signature:e()}),t({type:n("redacted_thinking"),data:e()}),t({type:n("tool_use"),id:e(),name:e(),input:we(),caller:Q([t({type:n("code_execution_20250825"),tool_id:e()}),t({type:n("direct")})]).optional()}),t({type:n("server_tool_use"),id:e(),name:e(),input:ue(e(),we()).nullish()}),t({type:n("mcp_tool_use"),id:e(),name:e(),input:we(),server_name:e()}),t({type:n("mcp_tool_result"),tool_use_id:e(),is_error:ne(),content:x(Q([e(),t({type:n("text"),text:e()})]))}),t({type:n("web_fetch_tool_result"),tool_use_id:e(),content:Q([t({type:n("web_fetch_result"),url:e(),retrieved_at:e(),content:t({type:n("document"),title:e().nullable(),citations:t({enabled:ne()}).optional(),source:Q([t({type:n("base64"),media_type:n("application/pdf"),data:e()}),t({type:n("text"),media_type:n("text/plain"),data:e()})])})}),t({type:n("web_fetch_tool_result_error"),error_code:e()})])}),t({type:n("web_search_tool_result"),tool_use_id:e(),content:Q([x(t({type:n("web_search_result"),url:e(),title:e(),encrypted_content:e(),page_age:e().nullish()})),t({type:n("web_search_tool_result_error"),error_code:e()})])}),t({type:n("code_execution_tool_result"),tool_use_id:e(),content:Q([t({type:n("code_execution_result"),stdout:e(),stderr:e(),return_code:a(),content:x(t({type:n("code_execution_output"),file_id:e()})).optional().default([])}),t({type:n("code_execution_tool_result_error"),error_code:e()})])}),t({type:n("bash_code_execution_tool_result"),tool_use_id:e(),content:ae("type",[t({type:n("bash_code_execution_result"),content:x(t({type:n("bash_code_execution_output"),file_id:e()})),stdout:e(),stderr:e(),return_code:a()}),t({type:n("bash_code_execution_tool_result_error"),error_code:e()})])}),t({type:n("text_editor_code_execution_tool_result"),tool_use_id:e(),content:ae("type",[t({type:n("text_editor_code_execution_tool_result_error"),error_code:e()}),t({type:n("text_editor_code_execution_view_result"),content:e(),file_type:e(),num_lines:a().nullable(),start_line:a().nullable(),total_lines:a().nullable()}),t({type:n("text_editor_code_execution_create_result"),is_file_update:ne()}),t({type:n("text_editor_code_execution_str_replace_result"),lines:x(e()).nullable(),new_lines:a().nullable(),new_start:a().nullable(),old_lines:a().nullable(),old_start:a().nullable()})])}),t({type:n("tool_search_tool_result"),tool_use_id:e(),content:Q([t({type:n("tool_search_tool_search_result"),tool_references:x(t({type:n("tool_reference"),tool_name:e()}))}),t({type:n("tool_search_tool_result_error"),error_code:e()})])})])),stop_reason:e().nullish(),stop_sequence:e().nullish(),usage:Ue({input_tokens:a(),output_tokens:a(),cache_creation_input_tokens:a().nullish(),cache_read_input_tokens:a().nullish()}),container:t({expires_at:e(),id:e(),skills:x(t({type:Q([n("anthropic"),n("custom")]),skill_id:e(),version:e()})).nullish()}).nullish(),context_management:t({applied_edits:x(Q([t({type:n("clear_tool_uses_20250919"),cleared_tool_uses:a(),cleared_input_tokens:a()}),t({type:n("clear_thinking_20251015"),cleared_thinking_turns:a(),cleared_input_tokens:a()})]))}).nullish()}))),mo=P(()=>D(ae("type",[t({type:n("message_start"),message:t({id:e().nullish(),model:e().nullish(),role:e().nullish(),usage:Ue({input_tokens:a(),cache_creation_input_tokens:a().nullish(),cache_read_input_tokens:a().nullish()}),content:x(ae("type",[t({type:n("tool_use"),id:e(),name:e(),input:we(),caller:Q([t({type:n("code_execution_20250825"),tool_id:e()}),t({type:n("direct")})]).optional()})])).nullish(),stop_reason:e().nullish(),container:t({expires_at:e(),id:e()}).nullish()})}),t({type:n("content_block_start"),index:a(),content_block:ae("type",[t({type:n("text"),text:e()}),t({type:n("thinking"),thinking:e()}),t({type:n("tool_use"),id:e(),name:e(),input:ue(e(),we()).optional(),caller:Q([t({type:n("code_execution_20250825"),tool_id:e()}),t({type:n("direct")})]).optional()}),t({type:n("redacted_thinking"),data:e()}),t({type:n("server_tool_use"),id:e(),name:e(),input:ue(e(),we()).nullish()}),t({type:n("mcp_tool_use"),id:e(),name:e(),input:we(),server_name:e()}),t({type:n("mcp_tool_result"),tool_use_id:e(),is_error:ne(),content:x(Q([e(),t({type:n("text"),text:e()})]))}),t({type:n("web_fetch_tool_result"),tool_use_id:e(),content:Q([t({type:n("web_fetch_result"),url:e(),retrieved_at:e(),content:t({type:n("document"),title:e().nullable(),citations:t({enabled:ne()}).optional(),source:Q([t({type:n("base64"),media_type:n("application/pdf"),data:e()}),t({type:n("text"),media_type:n("text/plain"),data:e()})])})}),t({type:n("web_fetch_tool_result_error"),error_code:e()})])}),t({type:n("web_search_tool_result"),tool_use_id:e(),content:Q([x(t({type:n("web_search_result"),url:e(),title:e(),encrypted_content:e(),page_age:e().nullish()})),t({type:n("web_search_tool_result_error"),error_code:e()})])}),t({type:n("code_execution_tool_result"),tool_use_id:e(),content:Q([t({type:n("code_execution_result"),stdout:e(),stderr:e(),return_code:a(),content:x(t({type:n("code_execution_output"),file_id:e()})).optional().default([])}),t({type:n("code_execution_tool_result_error"),error_code:e()})])}),t({type:n("bash_code_execution_tool_result"),tool_use_id:e(),content:ae("type",[t({type:n("bash_code_execution_result"),content:x(t({type:n("bash_code_execution_output"),file_id:e()})),stdout:e(),stderr:e(),return_code:a()}),t({type:n("bash_code_execution_tool_result_error"),error_code:e()})])}),t({type:n("text_editor_code_execution_tool_result"),tool_use_id:e(),content:ae("type",[t({type:n("text_editor_code_execution_tool_result_error"),error_code:e()}),t({type:n("text_editor_code_execution_view_result"),content:e(),file_type:e(),num_lines:a().nullable(),start_line:a().nullable(),total_lines:a().nullable()}),t({type:n("text_editor_code_execution_create_result"),is_file_update:ne()}),t({type:n("text_editor_code_execution_str_replace_result"),lines:x(e()).nullable(),new_lines:a().nullable(),new_start:a().nullable(),old_lines:a().nullable(),old_start:a().nullable()})])}),t({type:n("tool_search_tool_result"),tool_use_id:e(),content:Q([t({type:n("tool_search_tool_search_result"),tool_references:x(t({type:n("tool_reference"),tool_name:e()}))}),t({type:n("tool_search_tool_result_error"),error_code:e()})])})])}),t({type:n("content_block_delta"),index:a(),delta:ae("type",[t({type:n("input_json_delta"),partial_json:e()}),t({type:n("text_delta"),text:e()}),t({type:n("thinking_delta"),thinking:e()}),t({type:n("signature_delta"),signature:e()}),t({type:n("citations_delta"),citation:ae("type",[t({type:n("web_search_result_location"),cited_text:e(),url:e(),title:e(),encrypted_index:e()}),t({type:n("page_location"),cited_text:e(),document_index:a(),document_title:e().nullable(),start_page_number:a(),end_page_number:a()}),t({type:n("char_location"),cited_text:e(),document_index:a(),document_title:e().nullable(),start_char_index:a(),end_char_index:a()})])})])}),t({type:n("content_block_stop"),index:a()}),t({type:n("error"),error:t({type:e(),message:e()})}),t({type:n("message_delta"),delta:t({stop_reason:e().nullish(),stop_sequence:e().nullish(),container:t({expires_at:e(),id:e(),skills:x(t({type:Q([n("anthropic"),n("custom")]),skill_id:e(),version:e()})).nullish()}).nullish(),context_management:t({applied_edits:x(Q([t({type:n("clear_tool_uses_20250919"),cleared_tool_uses:a(),cleared_input_tokens:a()}),t({type:n("clear_thinking_20251015"),cleared_thinking_turns:a(),cleared_input_tokens:a()})]))}).nullish()}),usage:Ue({output_tokens:a(),cache_creation_input_tokens:a().nullish()})}),t({type:n("message_stop")}),t({type:n("ping")})]))),ho=P(()=>D(t({signature:e().optional(),redactedData:e().optional()}))),it=t({citations:t({enabled:ne()}).optional(),title:e().optional(),context:e().optional()}),go=t({sendReasoning:ne().optional(),structuredOutputMode:Y(["outputFormat","jsonTool","auto"]).optional(),thinking:t({type:Q([n("enabled"),n("disabled")]),budgetTokens:a().optional()}).optional(),disableParallelToolUse:ne().optional(),cacheControl:t({type:n("ephemeral"),ttl:Q([n("5m"),n("1h")]).optional()}).optional(),mcpServers:x(t({type:n("url"),name:e(),url:e(),authorizationToken:e().nullish(),toolConfiguration:t({enabled:ne().nullish(),allowedTools:x(e()).nullish()}).nullish()})).optional(),container:t({id:e().optional(),skills:x(t({type:Q([n("anthropic"),n("custom")]),skillId:e(),version:e().optional()})).optional()}).optional(),toolStreaming:ne().optional(),effort:Y(["low","medium","high"]).optional(),contextManagement:t({edits:x(ae("type",[t({type:n("clear_tool_uses_20250919"),trigger:ae("type",[t({type:n("input_tokens"),value:a()}),t({type:n("tool_uses"),value:a()})]).optional(),keep:t({type:n("tool_uses"),value:a()}).optional(),clearAtLeast:t({type:n("input_tokens"),value:a()}).optional(),clearToolInputs:ne().optional(),excludeTools:x(e()).optional()}),t({type:n("clear_thinking_20251015"),keep:Q([n("all"),t({type:n("thinking_turns"),value:a()})]).optional()})]))}).optional()}),lt=4;function fo(o){var l;const s=o==null?void 0:o.anthropic;return(l=s==null?void 0:s.cacheControl)!=null?l:s==null?void 0:s.cache_control}var Fe=class{constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl(o,l){const s=fo(o);if(s){if(!l.canCache){this.warnings.push({type:"unsupported",feature:"cache_control on non-cacheable context",details:`cache_control cannot be set on ${l.type}. It will be ignored.`});return}if(this.breakpointCount++,this.breakpointCount>lt){this.warnings.push({type:"unsupported",feature:"cacheControl breakpoint limit",details:`Maximum ${lt} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return s}}getWarnings(){return this.warnings}},yo=P(()=>D(t({maxCharacters:a().optional()}))),vo=P(()=>D(t({command:Y(["view","create","str_replace","insert"]),path:e(),file_text:e().optional(),insert_line:a().int().optional(),new_str:e().optional(),old_str:e().optional(),view_range:x(a().int()).optional()}))),bo=ve({id:"anthropic.text_editor_20250728",inputSchema:vo}),xo=(o={})=>bo(o),wo=P(()=>D(t({maxUses:a().optional(),allowedDomains:x(e()).optional(),blockedDomains:x(e()).optional(),userLocation:t({type:n("approximate"),city:e().optional(),region:e().optional(),country:e().optional(),timezone:e().optional()}).optional()}))),Ut=P(()=>D(x(t({url:e(),title:e().nullable(),pageAge:e().nullable(),encryptedContent:e(),type:n("web_search_result")})))),ko=P(()=>D(t({query:e()}))),Co=ye({id:"anthropic.web_search_20250305",inputSchema:ko,outputSchema:Ut,supportsDeferredResults:!0}),Io=(o={})=>Co(o),To=P(()=>D(t({maxUses:a().optional(),allowedDomains:x(e()).optional(),blockedDomains:x(e()).optional(),citations:t({enabled:ne()}).optional(),maxContentTokens:a().optional()}))),Lt=P(()=>D(t({type:n("web_fetch_result"),url:e(),content:t({type:n("document"),title:e().nullable(),citations:t({enabled:ne()}).optional(),source:Q([t({type:n("base64"),mediaType:n("application/pdf"),data:e()}),t({type:n("text"),mediaType:n("text/plain"),data:e()})])}),retrievedAt:e().nullable()}))),So=P(()=>D(t({url:e()}))),No=ye({id:"anthropic.web_fetch_20250910",inputSchema:So,outputSchema:Lt,supportsDeferredResults:!0}),Ro=(o={})=>No(o);async function Oo({tools:o,toolChoice:l,disableParallelToolUse:s,cacheControlValidator:p,supportsStructuredOutput:c}){var m;o=o!=null&&o.length?o:void 0;const u=[],d=new Set,b=p||new Fe;if(o==null)return{tools:void 0,toolChoice:void 0,toolWarnings:u,betas:d};const _=[];for(const w of o)switch(w.type){case"function":{const y=b.getCacheControl(w.providerOptions,{type:"tool definition",canCache:!0}),g=(m=w.providerOptions)==null?void 0:m.anthropic,k=g==null?void 0:g.deferLoading,C=g==null?void 0:g.allowedCallers;_.push({name:w.name,description:w.description,input_schema:w.inputSchema,cache_control:y,...c===!0&&w.strict!=null?{strict:w.strict}:{},...k!=null?{defer_loading:k}:{},...C!=null?{allowed_callers:C}:{},...w.inputExamples!=null?{input_examples:w.inputExamples.map(f=>f.input)}:{}}),c===!0&&d.add("structured-outputs-2025-11-13"),(w.inputExamples!=null||C!=null)&&d.add("advanced-tool-use-2025-11-20");break}case"provider":{switch(w.id){case"anthropic.code_execution_20250522":{d.add("code-execution-2025-05-22"),_.push({type:"code_execution_20250522",name:"code_execution",cache_control:void 0});break}case"anthropic.code_execution_20250825":{d.add("code-execution-2025-08-25"),_.push({type:"code_execution_20250825",name:"code_execution"});break}case"anthropic.computer_20250124":{d.add("computer-use-2025-01-24"),_.push({name:"computer",type:"computer_20250124",display_width_px:w.args.displayWidthPx,display_height_px:w.args.displayHeightPx,display_number:w.args.displayNumber,cache_control:void 0});break}case"anthropic.computer_20241022":{d.add("computer-use-2024-10-22"),_.push({name:"computer",type:"computer_20241022",display_width_px:w.args.displayWidthPx,display_height_px:w.args.displayHeightPx,display_number:w.args.displayNumber,cache_control:void 0});break}case"anthropic.text_editor_20250124":{d.add("computer-use-2025-01-24"),_.push({name:"str_replace_editor",type:"text_editor_20250124",cache_control:void 0});break}case"anthropic.text_editor_20241022":{d.add("computer-use-2024-10-22"),_.push({name:"str_replace_editor",type:"text_editor_20241022",cache_control:void 0});break}case"anthropic.text_editor_20250429":{d.add("computer-use-2025-01-24"),_.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429",cache_control:void 0});break}case"anthropic.text_editor_20250728":{const y=await ce({value:w.args,schema:yo});_.push({name:"str_replace_based_edit_tool",type:"text_editor_20250728",max_characters:y.maxCharacters,cache_control:void 0});break}case"anthropic.bash_20250124":{d.add("computer-use-2025-01-24"),_.push({name:"bash",type:"bash_20250124",cache_control:void 0});break}case"anthropic.bash_20241022":{d.add("computer-use-2024-10-22"),_.push({name:"bash",type:"bash_20241022",cache_control:void 0});break}case"anthropic.memory_20250818":{d.add("context-management-2025-06-27"),_.push({name:"memory",type:"memory_20250818"});break}case"anthropic.web_fetch_20250910":{d.add("web-fetch-2025-09-10");const y=await ce({value:w.args,schema:To});_.push({type:"web_fetch_20250910",name:"web_fetch",max_uses:y.maxUses,allowed_domains:y.allowedDomains,blocked_domains:y.blockedDomains,citations:y.citations,max_content_tokens:y.maxContentTokens,cache_control:void 0});break}case"anthropic.web_search_20250305":{const y=await ce({value:w.args,schema:wo});_.push({type:"web_search_20250305",name:"web_search",max_uses:y.maxUses,allowed_domains:y.allowedDomains,blocked_domains:y.blockedDomains,user_location:y.userLocation,cache_control:void 0});break}case"anthropic.tool_search_regex_20251119":{d.add("advanced-tool-use-2025-11-20"),_.push({type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"});break}case"anthropic.tool_search_bm25_20251119":{d.add("advanced-tool-use-2025-11-20"),_.push({type:"tool_search_tool_bm25_20251119",name:"tool_search_tool_bm25"});break}default:{u.push({type:"unsupported",feature:`provider-defined tool ${w.id}`});break}}break}default:{u.push({type:"unsupported",feature:`tool ${w}`});break}}if(l==null)return{tools:_,toolChoice:s?{type:"auto",disable_parallel_tool_use:s}:void 0,toolWarnings:u,betas:d};const T=l.type;switch(T){case"auto":return{tools:_,toolChoice:{type:"auto",disable_parallel_tool_use:s},toolWarnings:u,betas:d};case"required":return{tools:_,toolChoice:{type:"any",disable_parallel_tool_use:s},toolWarnings:u,betas:d};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:u,betas:d};case"tool":return{tools:_,toolChoice:{type:"tool",name:l.toolName,disable_parallel_tool_use:s},toolWarnings:u,betas:d};default:{const w=T;throw new _e({functionality:`tool choice type: ${w}`})}}}function st(o){var l,s;const p=o.input_tokens,c=o.output_tokens,m=(l=o.cache_creation_input_tokens)!=null?l:0,u=(s=o.cache_read_input_tokens)!=null?s:0;return{inputTokens:{total:p+m+u,noCache:p,cacheRead:u,cacheWrite:m},outputTokens:{total:c,text:void 0,reasoning:void 0},raw:o}}var Ht=P(()=>D(t({type:n("code_execution_result"),stdout:e(),stderr:e(),return_code:a(),content:x(t({type:n("code_execution_output"),file_id:e()})).optional().default([])}))),Eo=P(()=>D(t({code:e()}))),Mo=ye({id:"anthropic.code_execution_20250522",inputSchema:Eo,outputSchema:Ht}),qo=(o={})=>Mo(o),jt=P(()=>D(ae("type",[t({type:n("code_execution_result"),stdout:e(),stderr:e(),return_code:a(),content:x(t({type:n("code_execution_output"),file_id:e()})).optional().default([])}),t({type:n("bash_code_execution_result"),content:x(t({type:n("bash_code_execution_output"),file_id:e()})),stdout:e(),stderr:e(),return_code:a()}),t({type:n("bash_code_execution_tool_result_error"),error_code:e()}),t({type:n("text_editor_code_execution_tool_result_error"),error_code:e()}),t({type:n("text_editor_code_execution_view_result"),content:e(),file_type:e(),num_lines:a().nullable(),start_line:a().nullable(),total_lines:a().nullable()}),t({type:n("text_editor_code_execution_create_result"),is_file_update:ne()}),t({type:n("text_editor_code_execution_str_replace_result"),lines:x(e()).nullable(),new_lines:a().nullable(),new_start:a().nullable(),old_lines:a().nullable(),old_start:a().nullable()})]))),Ao=P(()=>D(ae("type",[t({type:n("programmatic-tool-call"),code:e()}),t({type:n("bash_code_execution"),command:e()}),ae("command",[t({type:n("text_editor_code_execution"),command:n("view"),path:e()}),t({type:n("text_editor_code_execution"),command:n("create"),path:e(),file_text:e().nullish()}),t({type:n("text_editor_code_execution"),command:n("str_replace"),path:e(),old_str:e(),new_str:e()})])]))),$o=ye({id:"anthropic.code_execution_20250825",inputSchema:Ao,outputSchema:jt,supportsDeferredResults:!0}),Po=(o={})=>$o(o),Gt=P(()=>D(x(t({type:n("tool_reference"),toolName:e()})))),Do=P(()=>D(t({pattern:e(),limit:a().optional()}))),Uo=ye({id:"anthropic.tool_search_regex_20251119",inputSchema:Do,outputSchema:Gt}),Lo=(o={})=>Uo(o);function Ho(o){if(typeof o=="string")return Buffer.from(o,"base64").toString("utf-8");if(o instanceof Uint8Array)return new TextDecoder().decode(o);throw o instanceof URL?new _e({functionality:"URL-based text documents are not supported for citations"}):new _e({functionality:`unsupported data type for text documents: ${typeof o}`})}function Ae(o){return o instanceof URL||jo(o)}function jo(o){return typeof o=="string"&&/^https?:\/\//i.test(o)}function $e(o){return o instanceof URL?o.toString():o}async function Go({prompt:o,sendReasoning:l,warnings:s,cacheControlValidator:p,toolNameMapping:c}){var m,u,d,b,_,T,w,y,g,k,C,f,L,$,M;const X=new Set,q=Vo(o),i=p||new Fe;let A;const ie=[];async function h(N){var S,G;const E=await me({provider:"anthropic",providerOptions:N,schema:it});return(G=(S=E==null?void 0:E.citations)==null?void 0:S.enabled)!=null?G:!1}async function K(N){const S=await me({provider:"anthropic",providerOptions:N,schema:it});return{title:S==null?void 0:S.title,context:S==null?void 0:S.context}}for(let N=0;N<q.length;N++){const S=q[N],G=N===q.length-1,E=S.type;switch(E){case"system":{if(A!=null)throw new _e({functionality:"Multiple system messages that are separated by user/assistant messages"});A=S.messages.map(({content:I,providerOptions:F})=>({type:"text",text:I,cache_control:i.getCacheControl(F,{type:"system message",canCache:!0})}));break}case"user":{const I=[];for(const F of S.messages){const{role:V,content:W}=F;switch(V){case"user":{for(let ee=0;ee<W.length;ee++){const H=W[ee],le=ee===W.length-1,R=(m=i.getCacheControl(H.providerOptions,{type:"user message part",canCache:!0}))!=null?m:le?i.getCacheControl(F.providerOptions,{type:"user message",canCache:!0}):void 0;switch(H.type){case"text":{I.push({type:"text",text:H.text,cache_control:R});break}case"file":{if(H.mediaType.startsWith("image/"))I.push({type:"image",source:Ae(H.data)?{type:"url",url:$e(H.data)}:{type:"base64",media_type:H.mediaType==="image/*"?"image/jpeg":H.mediaType,data:Ie(H.data)},cache_control:R});else if(H.mediaType==="application/pdf"){X.add("pdfs-2024-09-25");const re=await h(H.providerOptions),z=await K(H.providerOptions);I.push({type:"document",source:Ae(H.data)?{type:"url",url:$e(H.data)}:{type:"base64",media_type:"application/pdf",data:Ie(H.data)},title:(u=z.title)!=null?u:H.filename,...z.context&&{context:z.context},...re&&{citations:{enabled:!0}},cache_control:R})}else if(H.mediaType==="text/plain"){const re=await h(H.providerOptions),z=await K(H.providerOptions);I.push({type:"document",source:Ae(H.data)?{type:"url",url:$e(H.data)}:{type:"text",media_type:"text/plain",data:Ho(H.data)},title:(d=z.title)!=null?d:H.filename,...z.context&&{context:z.context},...re&&{citations:{enabled:!0}},cache_control:R})}else throw new _e({functionality:`media type: ${H.mediaType}`});break}}}break}case"tool":{for(let ee=0;ee<W.length;ee++){const H=W[ee];if(H.type==="tool-approval-response")continue;const le=ee===W.length-1,R=(b=i.getCacheControl(H.providerOptions,{type:"tool result part",canCache:!0}))!=null?b:le?i.getCacheControl(F.providerOptions,{type:"tool result message",canCache:!0}):void 0,re=H.output;let z;switch(re.type){case"content":z=re.value.map(te=>{switch(te.type){case"text":return{type:"text",text:te.text};case"image-data":return{type:"image",source:{type:"base64",media_type:te.mediaType,data:te.data}};case"image-url":return{type:"image",source:{type:"url",url:te.url}};case"file-url":return{type:"document",source:{type:"url",url:te.url}};case"file-data":{if(te.mediaType==="application/pdf")return X.add("pdfs-2024-09-25"),{type:"document",source:{type:"base64",media_type:te.mediaType,data:te.data}};s.push({type:"other",message:`unsupported tool content part type: ${te.type} with media type: ${te.mediaType}`});return}default:{s.push({type:"other",message:`unsupported tool content part type: ${te.type}`});return}}}).filter(qt);break;case"text":case"error-text":z=re.value;break;case"execution-denied":z=(_=re.reason)!=null?_:"Tool execution denied.";break;case"json":case"error-json":default:z=JSON.stringify(re.value);break}I.push({type:"tool_result",tool_use_id:H.toolCallId,content:z,is_error:re.type==="error-text"||re.type==="error-json"?!0:void 0,cache_control:R})}break}default:{const ee=V;throw new Error(`Unsupported role: ${ee}`)}}}ie.push({role:"user",content:I});break}case"assistant":{const I=[],F=new Set;for(let V=0;V<S.messages.length;V++){const W=S.messages[V],ee=V===S.messages.length-1,{content:H}=W;for(let le=0;le<H.length;le++){const R=H[le],re=le===H.length-1,z=(T=i.getCacheControl(R.providerOptions,{type:"assistant message part",canCache:!0}))!=null?T:re?i.getCacheControl(W.providerOptions,{type:"assistant message",canCache:!0}):void 0;switch(R.type){case"text":{I.push({type:"text",text:G&&ee&&re?R.text.trim():R.text,cache_control:z});break}case"reasoning":{if(l){const te=await me({provider:"anthropic",providerOptions:R.providerOptions,schema:ho});te!=null?te.signature!=null?(i.getCacheControl(R.providerOptions,{type:"thinking block",canCache:!1}),I.push({type:"thinking",thinking:R.text,signature:te.signature})):te.redactedData!=null?(i.getCacheControl(R.providerOptions,{type:"redacted thinking block",canCache:!1}),I.push({type:"redacted_thinking",data:te.redactedData})):s.push({type:"other",message:"unsupported reasoning metadata"}):s.push({type:"other",message:"unsupported reasoning metadata"})}else s.push({type:"other",message:"sending reasoning content is disabled for this model"});break}case"tool-call":{if(R.providerExecuted){const J=c.toProviderToolName(R.toolName);if(((y=(w=R.providerOptions)==null?void 0:w.anthropic)==null?void 0:y.type)==="mcp-tool-use"){F.add(R.toolCallId);const v=(k=(g=R.providerOptions)==null?void 0:g.anthropic)==null?void 0:k.serverName;if(v==null||typeof v!="string"){s.push({type:"other",message:"mcp tool use server name is required and must be a string"});break}I.push({type:"mcp_tool_use",id:R.toolCallId,name:R.toolName,input:R.input,server_name:v,cache_control:z})}else if(J==="code_execution"&&R.input!=null&&typeof R.input=="object"&&"type"in R.input&&typeof R.input.type=="string"&&(R.input.type==="bash_code_execution"||R.input.type==="text_editor_code_execution"))I.push({type:"server_tool_use",id:R.toolCallId,name:R.input.type,input:R.input,cache_control:z});else if(J==="code_execution"&&R.input!=null&&typeof R.input=="object"&&"type"in R.input&&R.input.type==="programmatic-tool-call"){const{type:v,...oe}=R.input;I.push({type:"server_tool_use",id:R.toolCallId,name:"code_execution",input:oe,cache_control:z})}else J==="code_execution"||J==="web_fetch"||J==="web_search"?I.push({type:"server_tool_use",id:R.toolCallId,name:J,input:R.input,cache_control:z}):J==="tool_search_tool_regex"||J==="tool_search_tool_bm25"?I.push({type:"server_tool_use",id:R.toolCallId,name:J,input:R.input,cache_control:z}):s.push({type:"other",message:`provider executed tool call for tool ${R.toolName} is not supported`});break}const te=(C=R.providerOptions)==null?void 0:C.anthropic,j=te!=null&&te.caller?te.caller.type==="code_execution_20250825"&&te.caller.toolId?{type:"code_execution_20250825",tool_id:te.caller.toolId}:te.caller.type==="direct"?{type:"direct"}:void 0:void 0;I.push({type:"tool_use",id:R.toolCallId,name:R.toolName,input:R.input,...j&&{caller:j},cache_control:z});break}case"tool-result":{const te=c.toProviderToolName(R.toolName);if(F.has(R.toolCallId)){const j=R.output;if(j.type!=="json"&&j.type!=="error-json"){s.push({type:"other",message:`provider executed tool result output type ${j.type} for tool ${R.toolName} is not supported`});break}I.push({type:"mcp_tool_result",tool_use_id:R.toolCallId,is_error:j.type==="error-json",content:j.value,cache_control:z})}else if(te==="code_execution"){const j=R.output;if(j.type==="error-text"||j.type==="error-json"){let J={};try{typeof j.value=="string"?J=JSON.parse(j.value):typeof j.value=="object"&&j.value!==null&&(J=j.value)}catch{}J.type==="code_execution_tool_result_error"?I.push({type:"code_execution_tool_result",tool_use_id:R.toolCallId,content:{type:"code_execution_tool_result_error",error_code:(f=J.errorCode)!=null?f:"unknown"},cache_control:z}):I.push({type:"bash_code_execution_tool_result",tool_use_id:R.toolCallId,cache_control:z,content:{type:"bash_code_execution_tool_result_error",error_code:(L=J.errorCode)!=null?L:"unknown"}});break}if(j.type!=="json"){s.push({type:"other",message:`provider executed tool result output type ${j.type} for tool ${R.toolName} is not supported`});break}if(j.value==null||typeof j.value!="object"||!("type"in j.value)||typeof j.value.type!="string"){s.push({type:"other",message:`provider executed tool result output value is not a valid code execution result for tool ${R.toolName}`});break}if(j.value.type==="code_execution_result"){const J=await ce({value:j.value,schema:Ht});I.push({type:"code_execution_tool_result",tool_use_id:R.toolCallId,content:{type:J.type,stdout:J.stdout,stderr:J.stderr,return_code:J.return_code,content:($=J.content)!=null?$:[]},cache_control:z})}else{const J=await ce({value:j.value,schema:jt});J.type==="code_execution_result"?I.push({type:"code_execution_tool_result",tool_use_id:R.toolCallId,content:{type:J.type,stdout:J.stdout,stderr:J.stderr,return_code:J.return_code,content:(M=J.content)!=null?M:[]},cache_control:z}):J.type==="bash_code_execution_result"||J.type==="bash_code_execution_tool_result_error"?I.push({type:"bash_code_execution_tool_result",tool_use_id:R.toolCallId,cache_control:z,content:J}):I.push({type:"text_editor_code_execution_tool_result",tool_use_id:R.toolCallId,cache_control:z,content:J})}break}if(te==="web_fetch"){const j=R.output;if(j.type==="error-json"){const U=JSON.parse(j.value);I.push({type:"web_fetch_tool_result",tool_use_id:R.toolCallId,content:{type:"web_fetch_tool_result_error",error_code:U.errorCode},cache_control:z});break}if(j.type!=="json"){s.push({type:"other",message:`provider executed tool result output type ${j.type} for tool ${R.toolName} is not supported`});break}const J=await ce({value:j.value,schema:Lt});I.push({type:"web_fetch_tool_result",tool_use_id:R.toolCallId,content:{type:"web_fetch_result",url:J.url,retrieved_at:J.retrievedAt,content:{type:"document",title:J.content.title,citations:J.content.citations,source:{type:J.content.source.type,media_type:J.content.source.mediaType,data:J.content.source.data}}},cache_control:z});break}if(te==="web_search"){const j=R.output;if(j.type!=="json"){s.push({type:"other",message:`provider executed tool result output type ${j.type} for tool ${R.toolName} is not supported`});break}const J=await ce({value:j.value,schema:Ut});I.push({type:"web_search_tool_result",tool_use_id:R.toolCallId,content:J.map(U=>({url:U.url,title:U.title,page_age:U.pageAge,encrypted_content:U.encryptedContent,type:U.type})),cache_control:z});break}if(te==="tool_search_tool_regex"||te==="tool_search_tool_bm25"){const j=R.output;if(j.type!=="json"){s.push({type:"other",message:`provider executed tool result output type ${j.type} for tool ${R.toolName} is not supported`});break}const U=(await ce({value:j.value,schema:Gt})).map(v=>({type:"tool_reference",tool_name:v.toolName}));I.push({type:"tool_search_tool_result",tool_use_id:R.toolCallId,content:{type:"tool_search_tool_search_result",tool_references:U},cache_control:z});break}s.push({type:"other",message:`provider executed tool result for tool ${R.toolName} is not supported`});break}}}}ie.push({role:"assistant",content:I});break}default:{const I=E;throw new Error(`content type: ${I}`)}}}return{prompt:{system:A,messages:ie},betas:X}}function Vo(o){const l=[];let s;for(const p of o){const{role:c}=p;switch(c){case"system":{(s==null?void 0:s.type)!=="system"&&(s={type:"system",messages:[]},l.push(s)),s.messages.push(p);break}case"assistant":{(s==null?void 0:s.type)!=="assistant"&&(s={type:"assistant",messages:[]},l.push(s)),s.messages.push(p);break}case"user":{(s==null?void 0:s.type)!=="user"&&(s={type:"user",messages:[]},l.push(s)),s.messages.push(p);break}case"tool":{(s==null?void 0:s.type)!=="user"&&(s={type:"user",messages:[]},l.push(s)),s.messages.push(p);break}default:{const m=c;throw new Error(`Unsupported role: ${m}`)}}}return l}function Pe({finishReason:o,isJsonResponseFromTool:l}){switch(o){case"pause_turn":case"end_turn":case"stop_sequence":return"stop";case"refusal":return"content-filter";case"tool_use":return l?"stop":"tool-calls";case"max_tokens":case"model_context_window_exceeded":return"length";default:return"other"}}function rt(o,l,s){var p;if(o.type!=="page_location"&&o.type!=="char_location")return;const c=l[o.document_index];if(c)return{type:"source",sourceType:"document",id:s(),mediaType:c.mediaType,title:(p=o.document_title)!=null?p:c.title,filename:c.filename,providerMetadata:{anthropic:o.type==="page_location"?{citedText:o.cited_text,startPageNumber:o.start_page_number,endPageNumber:o.end_page_number}:{citedText:o.cited_text,startCharIndex:o.start_char_index,endCharIndex:o.end_char_index}}}}var Bo=class{constructor(o,l){this.specificationVersion="v3";var s;this.modelId=o,this.config=l,this.generateId=(s=l.generateId)!=null?s:pe}supportsUrl(o){return o.protocol==="https:"}get provider(){return this.config.provider}get supportedUrls(){var o,l,s;return(s=(l=(o=this.config).supportedUrls)==null?void 0:l.call(o))!=null?s:{}}async getArgs({userSuppliedBetas:o,prompt:l,maxOutputTokens:s,temperature:p,topP:c,topK:m,frequencyPenalty:u,presencePenalty:d,stopSequences:b,responseFormat:_,seed:T,tools:w,toolChoice:y,providerOptions:g,stream:k}){var C,f,L,$,M,X;const q=[];u!=null&&q.push({type:"unsupported",feature:"frequencyPenalty"}),d!=null&&q.push({type:"unsupported",feature:"presencePenalty"}),T!=null&&q.push({type:"unsupported",feature:"seed"}),p!=null&&p>1?(q.push({type:"unsupported",feature:"temperature",details:`${p} exceeds anthropic maximum of 1.0. clamped to 1.0`}),p=1):p!=null&&p<0&&(q.push({type:"unsupported",feature:"temperature",details:`${p} is below anthropic minimum of 0. clamped to 0`}),p=0),(_==null?void 0:_.type)==="json"&&_.schema==null&&q.push({type:"unsupported",feature:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."});const i=await me({provider:"anthropic",providerOptions:g,schema:go}),{maxOutputTokens:A,supportsStructuredOutput:ie,isKnownModel:h}=Wo(this.modelId),K=((C=this.config.supportsNativeStructuredOutput)!=null?C:!0)&&ie,N=(f=i==null?void 0:i.structuredOutputMode)!=null?f:"auto",S=N==="outputFormat"||N==="auto"&&K,G=(_==null?void 0:_.type)==="json"&&_.schema!=null&&!S?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:_.schema}:void 0,E=i==null?void 0:i.contextManagement,I=new Fe,F=Et({tools:w,providerToolNames:{"anthropic.code_execution_20250522":"code_execution","anthropic.code_execution_20250825":"code_execution","anthropic.computer_20241022":"computer","anthropic.computer_20250124":"computer","anthropic.text_editor_20241022":"str_replace_editor","anthropic.text_editor_20250124":"str_replace_editor","anthropic.text_editor_20250429":"str_replace_based_edit_tool","anthropic.text_editor_20250728":"str_replace_based_edit_tool","anthropic.bash_20241022":"bash","anthropic.bash_20250124":"bash","anthropic.memory_20250818":"memory","anthropic.web_search_20250305":"web_search","anthropic.web_fetch_20250910":"web_fetch","anthropic.tool_search_regex_20251119":"tool_search_tool_regex","anthropic.tool_search_bm25_20251119":"tool_search_tool_bm25"}}),{prompt:V,betas:W}=await Go({prompt:l,sendReasoning:(L=i==null?void 0:i.sendReasoning)!=null?L:!0,warnings:q,cacheControlValidator:I,toolNameMapping:F}),ee=(($=i==null?void 0:i.thinking)==null?void 0:$.type)==="enabled";let H=(M=i==null?void 0:i.thinking)==null?void 0:M.budgetTokens;const le=s??A,R={model:this.modelId,max_tokens:le,temperature:p,top_k:m,top_p:c,stop_sequences:b,...ee&&{thinking:{type:"enabled",budget_tokens:H}},...(i==null?void 0:i.effort)&&{output_config:{effort:i.effort}},...S&&(_==null?void 0:_.type)==="json"&&_.schema!=null&&{output_format:{type:"json_schema",schema:_.schema}},...(i==null?void 0:i.mcpServers)&&i.mcpServers.length>0&&{mcp_servers:i.mcpServers.map(v=>({type:v.type,name:v.name,url:v.url,authorization_token:v.authorizationToken,tool_configuration:v.toolConfiguration?{allowed_tools:v.toolConfiguration.allowedTools,enabled:v.toolConfiguration.enabled}:void 0}))},...(i==null?void 0:i.container)&&{container:i.container.skills&&i.container.skills.length>0?{id:i.container.id,skills:i.container.skills.map(v=>({type:v.type,skill_id:v.skillId,version:v.version}))}:i.container.id},system:V.system,messages:V.messages,...E&&{context_management:{edits:E.edits.map(v=>{const oe=v.type;switch(oe){case"clear_tool_uses_20250919":return{type:v.type,...v.trigger!==void 0&&{trigger:v.trigger},...v.keep!==void 0&&{keep:v.keep},...v.clearAtLeast!==void 0&&{clear_at_least:v.clearAtLeast},...v.clearToolInputs!==void 0&&{clear_tool_inputs:v.clearToolInputs},...v.excludeTools!==void 0&&{exclude_tools:v.excludeTools}};case"clear_thinking_20251015":return{type:v.type,...v.keep!==void 0&&{keep:v.keep}};default:q.push({type:"other",message:`Unknown context management strategy: ${oe}`});return}}).filter(v=>v!==void 0)}}};ee?(H==null&&(q.push({type:"compatibility",feature:"extended thinking",details:"thinking budget is required when thinking is enabled. using default budget of 1024 tokens."}),R.thinking={type:"enabled",budget_tokens:1024},H=1024),R.temperature!=null&&(R.temperature=void 0,q.push({type:"unsupported",feature:"temperature",details:"temperature is not supported when thinking is enabled"})),m!=null&&(R.top_k=void 0,q.push({type:"unsupported",feature:"topK",details:"topK is not supported when thinking is enabled"})),c!=null&&(R.top_p=void 0,q.push({type:"unsupported",feature:"topP",details:"topP is not supported when thinking is enabled"})),R.max_tokens=le+(H??0)):c!=null&&p!=null&&(q.push({type:"unsupported",feature:"topP",details:"topP is not supported when temperature is set. topP is ignored."}),R.top_p=void 0),h&&R.max_tokens>A&&(s!=null&&q.push({type:"unsupported",feature:"maxOutputTokens",details:`${R.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${A} max output tokens. The max output tokens have been limited to ${A}.`}),R.max_tokens=A),i!=null&&i.mcpServers&&i.mcpServers.length>0&&W.add("mcp-client-2025-04-04"),E&&W.add("context-management-2025-06-27"),i!=null&&i.container&&i.container.skills&&i.container.skills.length>0&&(W.add("code-execution-2025-08-25"),W.add("skills-2025-10-02"),W.add("files-api-2025-04-14"),w!=null&&w.some(v=>v.type==="provider"&&v.id==="anthropic.code_execution_20250825")||q.push({type:"other",message:"code execution tool is required when using skills"})),i!=null&&i.effort&&W.add("effort-2025-11-24"),k&&((X=i==null?void 0:i.toolStreaming)==null||X)&&W.add("fine-grained-tool-streaming-2025-05-14"),S&&(_==null?void 0:_.type)==="json"&&_.schema!=null&&W.add("structured-outputs-2025-11-13");const{tools:z,toolChoice:te,toolWarnings:j,betas:J}=await Oo(G!=null?{tools:[...w??[],G],toolChoice:{type:"required"},disableParallelToolUse:!0,cacheControlValidator:I,supportsStructuredOutput:K}:{tools:w??[],toolChoice:y,disableParallelToolUse:i==null?void 0:i.disableParallelToolUse,cacheControlValidator:I,supportsStructuredOutput:K}),U=I.getWarnings();return{args:{...R,tools:z,tool_choice:te,stream:k===!0?!0:void 0},warnings:[...q,...j,...U],betas:new Set([...W,...J,...o]),usesJsonResponseTool:G!=null,toolNameMapping:F}}async getHeaders({betas:o,headers:l}){return ge(await Se(this.config.headers),l,o.size>0?{"anthropic-beta":Array.from(o).join(",")}:{})}async getBetasFromHeaders(o){var l,s;const c=(l=(await Se(this.config.headers))["anthropic-beta"])!=null?l:"",m=(s=o==null?void 0:o["anthropic-beta"])!=null?s:"";return new Set([...c.toLowerCase().split(","),...m.toLowerCase().split(",")].map(u=>u.trim()).filter(u=>u!==""))}buildRequestUrl(o){var l,s,p;return(p=(s=(l=this.config).buildRequestUrl)==null?void 0:s.call(l,this.config.baseURL,o))!=null?p:`${this.config.baseURL}/messages`}transformRequestBody(o){var l,s,p;return(p=(s=(l=this.config).transformRequestBody)==null?void 0:s.call(l,o))!=null?p:o}extractCitationDocuments(o){const l=s=>{var p,c;if(s.type!=="file"||s.mediaType!=="application/pdf"&&s.mediaType!=="text/plain")return!1;const m=(p=s.providerOptions)==null?void 0:p.anthropic,u=m==null?void 0:m.citations;return(c=u==null?void 0:u.enabled)!=null?c:!1};return o.filter(s=>s.role==="user").flatMap(s=>s.content).filter(l).map(s=>{var p;const c=s;return{title:(p=c.filename)!=null?p:"Untitled Document",filename:c.filename,mediaType:c.mediaType}})}async doGenerate(o){var l,s,p,c,m,u,d,b,_,T,w;const{args:y,warnings:g,betas:k,usesJsonResponseTool:C,toolNameMapping:f}=await this.getArgs({...o,stream:!1,userSuppliedBetas:await this.getBetasFromHeaders(o.headers)}),L=this.extractCitationDocuments(o.prompt),{responseHeaders:$,value:M,rawValue:X}=await fe({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:k,headers:o.headers}),body:this.transformRequestBody(y),failedResponseHandler:at,successfulResponseHandler:be(_o),abortSignal:o.abortSignal,fetch:this.config.fetch}),q=[],i={},A={};let ie=!1;for(const h of M.content)switch(h.type){case"text":{if(!C&&(q.push({type:"text",text:h.text}),h.citations))for(const K of h.citations){const N=rt(K,L,this.generateId);N&&q.push(N)}break}case"thinking":{q.push({type:"reasoning",text:h.thinking,providerMetadata:{anthropic:{signature:h.signature}}});break}case"redacted_thinking":{q.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:h.data}}});break}case"tool_use":{if(C&&h.name==="json")ie=!0,q.push({type:"text",text:JSON.stringify(h.input)});else{const N=h.caller,S=N?{type:N.type,toolId:"tool_id"in N?N.tool_id:void 0}:void 0;q.push({type:"tool-call",toolCallId:h.id,toolName:h.name,input:JSON.stringify(h.input),...S&&{providerMetadata:{anthropic:{caller:S}}}})}break}case"server_tool_use":{if(h.name==="text_editor_code_execution"||h.name==="bash_code_execution")q.push({type:"tool-call",toolCallId:h.id,toolName:f.toCustomToolName("code_execution"),input:JSON.stringify({type:h.name,...h.input}),providerExecuted:!0});else if(h.name==="web_search"||h.name==="code_execution"||h.name==="web_fetch"){const K=h.name==="code_execution"&&h.input!=null&&typeof h.input=="object"&&"code"in h.input&&!("type"in h.input)?{type:"programmatic-tool-call",...h.input}:h.input;q.push({type:"tool-call",toolCallId:h.id,toolName:f.toCustomToolName(h.name),input:JSON.stringify(K),providerExecuted:!0})}else(h.name==="tool_search_tool_regex"||h.name==="tool_search_tool_bm25")&&(A[h.id]=h.name,q.push({type:"tool-call",toolCallId:h.id,toolName:f.toCustomToolName(h.name),input:JSON.stringify(h.input),providerExecuted:!0}));break}case"mcp_tool_use":{i[h.id]={type:"tool-call",toolCallId:h.id,toolName:h.name,input:JSON.stringify(h.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:h.server_name}}},q.push(i[h.id]);break}case"mcp_tool_result":{q.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:i[h.tool_use_id].toolName,isError:h.is_error,result:h.content,dynamic:!0,providerMetadata:i[h.tool_use_id].providerMetadata});break}case"web_fetch_tool_result":{h.content.type==="web_fetch_result"?q.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:f.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:h.content.url,retrievedAt:h.content.retrieved_at,content:{type:h.content.content.type,title:h.content.content.title,citations:h.content.content.citations,source:{type:h.content.content.source.type,mediaType:h.content.content.source.media_type,data:h.content.content.source.data}}}}):h.content.type==="web_fetch_tool_result_error"&&q.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:f.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:h.content.error_code}});break}case"web_search_tool_result":{if(Array.isArray(h.content)){q.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:f.toCustomToolName("web_search"),result:h.content.map(K=>{var N;return{url:K.url,title:K.title,pageAge:(N=K.page_age)!=null?N:null,encryptedContent:K.encrypted_content,type:K.type}})});for(const K of h.content)q.push({type:"source",sourceType:"url",id:this.generateId(),url:K.url,title:K.title,providerMetadata:{anthropic:{pageAge:(l=K.page_age)!=null?l:null}}})}else q.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:f.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:h.content.error_code}});break}case"code_execution_tool_result":{h.content.type==="code_execution_result"?q.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:f.toCustomToolName("code_execution"),result:{type:h.content.type,stdout:h.content.stdout,stderr:h.content.stderr,return_code:h.content.return_code,content:(s=h.content.content)!=null?s:[]}}):h.content.type==="code_execution_tool_result_error"&&q.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:f.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:h.content.error_code}});break}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{q.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:f.toCustomToolName("code_execution"),result:h.content});break}case"tool_search_tool_result":{const K=(p=A[h.tool_use_id])!=null?p:"tool_search_tool_regex";h.content.type==="tool_search_tool_search_result"?q.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:f.toCustomToolName(K),result:h.content.tool_references.map(N=>({type:N.type,toolName:N.tool_name}))}):q.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:f.toCustomToolName(K),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:h.content.error_code}});break}}return{content:q,finishReason:{unified:Pe({finishReason:M.stop_reason,isJsonResponseFromTool:ie}),raw:(c=M.stop_reason)!=null?c:void 0},usage:st(M.usage),request:{body:y},response:{id:(m=M.id)!=null?m:void 0,modelId:(u=M.model)!=null?u:void 0,headers:$,body:X},warnings:g,providerMetadata:{anthropic:{usage:M.usage,cacheCreationInputTokens:(d=M.usage.cache_creation_input_tokens)!=null?d:null,stopSequence:(b=M.stop_sequence)!=null?b:null,container:M.container?{expiresAt:M.container.expires_at,id:M.container.id,skills:(T=(_=M.container.skills)==null?void 0:_.map(h=>({type:h.type,skillId:h.skill_id,version:h.version})))!=null?T:null}:null,contextManagement:(w=ut(M.context_management))!=null?w:null}}}}async doStream(o){var l,s;const{args:p,warnings:c,betas:m,usesJsonResponseTool:u,toolNameMapping:d}=await this.getArgs({...o,stream:!0,userSuppliedBetas:await this.getBetasFromHeaders(o.headers)}),b=this.extractCitationDocuments(o.prompt),_=this.buildRequestUrl(!0),{responseHeaders:T,value:w}=await fe({url:_,headers:await this.getHeaders({betas:m,headers:o.headers}),body:this.transformRequestBody(p),failedResponseHandler:at,successfulResponseHandler:Oe(mo),abortSignal:o.abortSignal,fetch:this.config.fetch});let y={unified:"other",raw:void 0};const g={input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0},k={},C={},f={};let L=null,$,M=null,X=null,q=null,i=!1,A;const ie=this.generateId,h=w.pipeThrough(new TransformStream({start(G){G.enqueue({type:"stream-start",warnings:c})},transform(G,E){var I,F,V,W,ee,H,le,R,re,z,te,j,J;if(o.includeRawChunks&&E.enqueue({type:"raw",rawValue:G.rawValue}),!G.success){E.enqueue({type:"error",error:G.error});return}const U=G.value;switch(U.type){case"ping":return;case"content_block_start":{const v=U.content_block,oe=v.type;switch(A=oe,oe){case"text":{if(u)return;k[U.index]={type:"text"},E.enqueue({type:"text-start",id:String(U.index)});return}case"thinking":{k[U.index]={type:"reasoning"},E.enqueue({type:"reasoning-start",id:String(U.index)});return}case"redacted_thinking":{k[U.index]={type:"reasoning"},E.enqueue({type:"reasoning-start",id:String(U.index),providerMetadata:{anthropic:{redactedData:v.data}}});return}case"tool_use":{if(u&&v.name==="json")i=!0,k[U.index]={type:"text"},E.enqueue({type:"text-start",id:String(U.index)});else{const Z=v.caller,he=Z?{type:Z.type,toolId:"tool_id"in Z?Z.tool_id:void 0}:void 0,Ne=v.input&&Object.keys(v.input).length>0?JSON.stringify(v.input):"";k[U.index]={type:"tool-call",toolCallId:v.id,toolName:v.name,input:Ne,firstDelta:Ne.length===0,...he&&{caller:he}},E.enqueue({type:"tool-input-start",id:v.id,toolName:v.name})}return}case"server_tool_use":{if(["web_fetch","web_search","code_execution","text_editor_code_execution","bash_code_execution"].includes(v.name)){const O=v.name==="text_editor_code_execution"||v.name==="bash_code_execution"?"code_execution":v.name,Z=d.toCustomToolName(O);k[U.index]={type:"tool-call",toolCallId:v.id,toolName:Z,input:"",providerExecuted:!0,firstDelta:!0,providerToolName:v.name},E.enqueue({type:"tool-input-start",id:v.id,toolName:Z,providerExecuted:!0})}else if(v.name==="tool_search_tool_regex"||v.name==="tool_search_tool_bm25"){f[v.id]=v.name;const O=d.toCustomToolName(v.name);k[U.index]={type:"tool-call",toolCallId:v.id,toolName:O,input:"",providerExecuted:!0,firstDelta:!0,providerToolName:v.name},E.enqueue({type:"tool-input-start",id:v.id,toolName:O,providerExecuted:!0})}return}case"web_fetch_tool_result":{v.content.type==="web_fetch_result"?E.enqueue({type:"tool-result",toolCallId:v.tool_use_id,toolName:d.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:v.content.url,retrievedAt:v.content.retrieved_at,content:{type:v.content.content.type,title:v.content.content.title,citations:v.content.content.citations,source:{type:v.content.content.source.type,mediaType:v.content.content.source.media_type,data:v.content.content.source.data}}}}):v.content.type==="web_fetch_tool_result_error"&&E.enqueue({type:"tool-result",toolCallId:v.tool_use_id,toolName:d.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:v.content.error_code}});return}case"web_search_tool_result":{if(Array.isArray(v.content)){E.enqueue({type:"tool-result",toolCallId:v.tool_use_id,toolName:d.toCustomToolName("web_search"),result:v.content.map(O=>{var Z;return{url:O.url,title:O.title,pageAge:(Z=O.page_age)!=null?Z:null,encryptedContent:O.encrypted_content,type:O.type}})});for(const O of v.content)E.enqueue({type:"source",sourceType:"url",id:ie(),url:O.url,title:O.title,providerMetadata:{anthropic:{pageAge:(I=O.page_age)!=null?I:null}}})}else E.enqueue({type:"tool-result",toolCallId:v.tool_use_id,toolName:d.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:v.content.error_code}});return}case"code_execution_tool_result":{v.content.type==="code_execution_result"?E.enqueue({type:"tool-result",toolCallId:v.tool_use_id,toolName:d.toCustomToolName("code_execution"),result:{type:v.content.type,stdout:v.content.stdout,stderr:v.content.stderr,return_code:v.content.return_code,content:(F=v.content.content)!=null?F:[]}}):v.content.type==="code_execution_tool_result_error"&&E.enqueue({type:"tool-result",toolCallId:v.tool_use_id,toolName:d.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:v.content.error_code}});return}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{E.enqueue({type:"tool-result",toolCallId:v.tool_use_id,toolName:d.toCustomToolName("code_execution"),result:v.content});return}case"tool_search_tool_result":{const O=(V=f[v.tool_use_id])!=null?V:"tool_search_tool_regex";v.content.type==="tool_search_tool_search_result"?E.enqueue({type:"tool-result",toolCallId:v.tool_use_id,toolName:d.toCustomToolName(O),result:v.content.tool_references.map(Z=>({type:Z.type,toolName:Z.tool_name}))}):E.enqueue({type:"tool-result",toolCallId:v.tool_use_id,toolName:d.toCustomToolName(O),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:v.content.error_code}});return}case"mcp_tool_use":{C[v.id]={type:"tool-call",toolCallId:v.id,toolName:v.name,input:JSON.stringify(v.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:v.server_name}}},E.enqueue(C[v.id]);return}case"mcp_tool_result":{E.enqueue({type:"tool-result",toolCallId:v.tool_use_id,toolName:C[v.tool_use_id].toolName,isError:v.is_error,result:v.content,dynamic:!0,providerMetadata:C[v.tool_use_id].providerMetadata});return}default:{const O=oe;throw new Error(`Unsupported content block type: ${O}`)}}}case"content_block_stop":{if(k[U.index]!=null){const v=k[U.index];switch(v.type){case"text":{E.enqueue({type:"text-end",id:String(U.index)});break}case"reasoning":{E.enqueue({type:"reasoning-end",id:String(U.index)});break}case"tool-call":if(!(u&&v.toolName==="json")){E.enqueue({type:"tool-input-end",id:v.toolCallId});let O=v.input===""?"{}":v.input;if(v.providerToolName==="code_execution")try{const Z=JSON.parse(O);Z!=null&&typeof Z=="object"&&"code"in Z&&!("type"in Z)&&(O=JSON.stringify({type:"programmatic-tool-call",...Z}))}catch{}E.enqueue({type:"tool-call",toolCallId:v.toolCallId,toolName:v.toolName,input:O,providerExecuted:v.providerExecuted,...v.caller&&{providerMetadata:{anthropic:{caller:v.caller}}}})}break}delete k[U.index]}A=void 0;return}case"content_block_delta":{const v=U.delta.type;switch(v){case"text_delta":{if(u)return;E.enqueue({type:"text-delta",id:String(U.index),delta:U.delta.text});return}case"thinking_delta":{E.enqueue({type:"reasoning-delta",id:String(U.index),delta:U.delta.thinking});return}case"signature_delta":{A==="thinking"&&E.enqueue({type:"reasoning-delta",id:String(U.index),delta:"",providerMetadata:{anthropic:{signature:U.delta.signature}}});return}case"input_json_delta":{const oe=k[U.index];let O=U.delta.partial_json;if(O.length===0)return;if(i){if((oe==null?void 0:oe.type)!=="text")return;E.enqueue({type:"text-delta",id:String(U.index),delta:O})}else{if((oe==null?void 0:oe.type)!=="tool-call")return;oe.firstDelta&&(oe.providerToolName==="bash_code_execution"||oe.providerToolName==="text_editor_code_execution")&&(O=`{"type": "${oe.providerToolName}",${O.substring(1)}`),E.enqueue({type:"tool-input-delta",id:oe.toolCallId,delta:O}),oe.input+=O,oe.firstDelta=!1}return}case"citations_delta":{const oe=U.delta.citation,O=rt(oe,b,ie);O&&E.enqueue(O);return}default:{const oe=v;throw new Error(`Unsupported delta type: ${oe}`)}}}case"message_start":{if(g.input_tokens=U.message.usage.input_tokens,g.cache_read_input_tokens=(W=U.message.usage.cache_read_input_tokens)!=null?W:0,g.cache_creation_input_tokens=(ee=U.message.usage.cache_creation_input_tokens)!=null?ee:0,$={...U.message.usage},M=(H=U.message.usage.cache_creation_input_tokens)!=null?H:null,U.message.container!=null&&(q={expiresAt:U.message.container.expires_at,id:U.message.container.id,skills:null}),U.message.stop_reason!=null&&(y={unified:Pe({finishReason:U.message.stop_reason,isJsonResponseFromTool:i}),raw:U.message.stop_reason}),E.enqueue({type:"response-metadata",id:(le=U.message.id)!=null?le:void 0,modelId:(R=U.message.model)!=null?R:void 0}),U.message.content!=null)for(let v=0;v<U.message.content.length;v++){const oe=U.message.content[v];if(oe.type==="tool_use"){const O=oe.caller,Z=O?{type:O.type,toolId:"tool_id"in O?O.tool_id:void 0}:void 0;E.enqueue({type:"tool-input-start",id:oe.id,toolName:oe.name});const he=JSON.stringify((re=oe.input)!=null?re:{});E.enqueue({type:"tool-input-delta",id:oe.id,delta:he}),E.enqueue({type:"tool-input-end",id:oe.id}),E.enqueue({type:"tool-call",toolCallId:oe.id,toolName:oe.name,input:he,...Z&&{providerMetadata:{anthropic:{caller:Z}}}})}}return}case"message_delta":{g.output_tokens=U.usage.output_tokens,y={unified:Pe({finishReason:U.delta.stop_reason,isJsonResponseFromTool:i}),raw:(z=U.delta.stop_reason)!=null?z:void 0},X=(te=U.delta.stop_sequence)!=null?te:null,q=U.delta.container!=null?{expiresAt:U.delta.container.expires_at,id:U.delta.container.id,skills:(J=(j=U.delta.container.skills)==null?void 0:j.map(v=>({type:v.type,skillId:v.skill_id,version:v.version})))!=null?J:null}:null,U.delta.context_management&&(L=ut(U.delta.context_management)),$={...$,...U.usage};return}case"message_stop":{E.enqueue({type:"finish",finishReason:y,usage:st(g),providerMetadata:{anthropic:{usage:$??null,cacheCreationInputTokens:M,stopSequence:X,container:q,contextManagement:L}}});return}case"error":{E.enqueue({type:"error",error:U.error});return}default:{const v=U;throw new Error(`Unsupported chunk type: ${v}`)}}}})),[K,N]=h.tee(),S=K.getReader();try{await S.read();let G=await S.read();if(((l=G.value)==null?void 0:l.type)==="raw"&&(G=await S.read()),((s=G.value)==null?void 0:s.type)==="error"){const E=G.value.error;throw new Mt({message:E.message,url:_,requestBodyValues:p,statusCode:E.type==="overloaded_error"?529:500,responseHeaders:T,responseBody:JSON.stringify(E),isRetryable:E.type==="overloaded_error"})}}finally{S.cancel().catch(()=>{}),S.releaseLock()}return{stream:N,request:{body:p},response:{headers:T}}}};function Wo(o){return o.includes("claude-sonnet-4-5")||o.includes("claude-opus-4-5")||o.includes("claude-haiku-4-5")?{maxOutputTokens:64e3,supportsStructuredOutput:!0,isKnownModel:!0}:o.includes("claude-opus-4-1")?{maxOutputTokens:32e3,supportsStructuredOutput:!0,isKnownModel:!0}:o.includes("claude-sonnet-4-")||o.includes("claude-3-7-sonnet")?{maxOutputTokens:64e3,supportsStructuredOutput:!1,isKnownModel:!0}:o.includes("claude-opus-4-")?{maxOutputTokens:32e3,supportsStructuredOutput:!1,isKnownModel:!0}:o.includes("claude-3-5-haiku")?{maxOutputTokens:8192,supportsStructuredOutput:!1,isKnownModel:!0}:o.includes("claude-3-haiku")?{maxOutputTokens:4096,supportsStructuredOutput:!1,isKnownModel:!0}:{maxOutputTokens:4096,supportsStructuredOutput:!1,isKnownModel:!1}}function ut(o){return o?{appliedEdits:o.applied_edits.map(l=>{switch(l.type){case"clear_tool_uses_20250919":return{type:l.type,clearedToolUses:l.cleared_tool_uses,clearedInputTokens:l.cleared_input_tokens};case"clear_thinking_20251015":return{type:l.type,clearedThinkingTurns:l.cleared_thinking_turns,clearedInputTokens:l.cleared_input_tokens}}}).filter(l=>l!==void 0)}:null}var Fo=P(()=>D(t({command:e(),restart:ne().optional()}))),Jo=ve({id:"anthropic.bash_20241022",inputSchema:Fo}),Ko=P(()=>D(t({command:e(),restart:ne().optional()}))),zo=ve({id:"anthropic.bash_20250124",inputSchema:Ko}),Yo=P(()=>D(t({action:Y(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:x(a().int()).optional(),text:e().optional()}))),Xo=ve({id:"anthropic.computer_20241022",inputSchema:Yo}),Qo=P(()=>D(t({action:Y(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:Le([a().int(),a().int()]).optional(),duration:a().optional(),scroll_amount:a().optional(),scroll_direction:Y(["up","down","left","right"]).optional(),start_coordinate:Le([a().int(),a().int()]).optional(),text:e().optional()}))),Zo=ve({id:"anthropic.computer_20250124",inputSchema:Qo}),en=P(()=>D(ae("command",[t({command:n("view"),path:e(),view_range:Le([a(),a()]).optional()}),t({command:n("create"),path:e(),file_text:e()}),t({command:n("str_replace"),path:e(),old_str:e(),new_str:e()}),t({command:n("insert"),path:e(),insert_line:a(),insert_text:e()}),t({command:n("delete"),path:e()}),t({command:n("rename"),old_path:e(),new_path:e()})]))),tn=ve({id:"anthropic.memory_20250818",inputSchema:en}),on=P(()=>D(t({command:Y(["view","create","str_replace","insert","undo_edit"]),path:e(),file_text:e().optional(),insert_line:a().int().optional(),new_str:e().optional(),old_str:e().optional(),view_range:x(a().int()).optional()}))),nn=ve({id:"anthropic.text_editor_20241022",inputSchema:on}),an=P(()=>D(t({command:Y(["view","create","str_replace","insert","undo_edit"]),path:e(),file_text:e().optional(),insert_line:a().int().optional(),new_str:e().optional(),old_str:e().optional(),view_range:x(a().int()).optional()}))),ln=ve({id:"anthropic.text_editor_20250124",inputSchema:an}),sn=P(()=>D(t({command:Y(["view","create","str_replace","insert"]),path:e(),file_text:e().optional(),insert_line:a().int().optional(),new_str:e().optional(),old_str:e().optional(),view_range:x(a().int()).optional()}))),rn=ve({id:"anthropic.text_editor_20250429",inputSchema:sn}),un=P(()=>D(x(t({type:n("tool_reference"),toolName:e()})))),pn=P(()=>D(t({query:e(),limit:a().optional()}))),cn=ye({id:"anthropic.tool_search_bm25_20251119",inputSchema:pn,outputSchema:un}),dn=(o={})=>cn(o),_n={bash_20241022:Jo,bash_20250124:zo,codeExecution_20250522:qo,codeExecution_20250825:Po,computer_20241022:Xo,computer_20250124:Zo,memory_20250818:tn,textEditor_20241022:nn,textEditor_20250124:ln,textEditor_20250429:rn,textEditor_20250728:xo,webFetch_20250910:Ro,webSearch_20250305:Io,toolSearchRegex_20251119:Lo,toolSearchBm25_20251119:dn};function mn(o={}){var l,s;const p=(l=je(Ot({settingValue:o.baseURL,environmentVariableName:"ANTHROPIC_BASE_URL"})))!=null?l:"https://api.anthropic.com/v1",c=(s=o.name)!=null?s:"anthropic.messages",m=()=>Ge({"anthropic-version":"2023-06-01","x-api-key":Ve({apiKey:o.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"}),...o.headers},`ai-sdk/anthropic/${po}`),u=b=>{var _;return new Bo(b,{provider:c,baseURL:p,headers:m,fetch:o.fetch,generateId:(_=o.generateId)!=null?_:pe,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})})},d=function(b){if(new.target)throw new Error("The Anthropic model function cannot be called with the new keyword.");return u(b)};return d.specificationVersion="v3",d.languageModel=u,d.chat=u,d.messages=u,d.embeddingModel=b=>{throw new ot({modelId:b,modelType:"embeddingModel"})},d.textEmbeddingModel=d.embeddingModel,d.imageModel=b=>{throw new ot({modelId:b,modelType:"imageModel"})},d.tools=_n,d}var ci=mn(),Je=t({error:t({message:e(),type:e().nullish(),param:Ee().nullish(),code:Q([e(),a()]).nullish()})}),ke=Be({errorSchema:Je,errorToMessage:o=>o.error.message});function Vt(o){const l=o.startsWith("o3")||o.startsWith("o4-mini")||o.startsWith("gpt-5")&&!o.startsWith("gpt-5-chat"),s=o.startsWith("gpt-4")||o.startsWith("gpt-5-mini")||o.startsWith("gpt-5")&&!o.startsWith("gpt-5-nano")&&!o.startsWith("gpt-5-chat")||o.startsWith("o3")||o.startsWith("o4-mini"),p=o.startsWith("o1")||o.startsWith("o3")||o.startsWith("o4-mini")||o.startsWith("codex-mini")||o.startsWith("computer-use-preview")||o.startsWith("gpt-5")&&!o.startsWith("gpt-5-chat"),c=o.startsWith("gpt-5.1")||o.startsWith("gpt-5.2");return{supportsFlexProcessing:l,supportsPriorityProcessing:s,isReasoningModel:p,systemMessageMode:p?"developer":"system",supportsNonReasoningParameters:c}}function pt(o){var l,s,p,c,m,u;if(o==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const d=(l=o.prompt_tokens)!=null?l:0,b=(s=o.completion_tokens)!=null?s:0,_=(c=(p=o.prompt_tokens_details)==null?void 0:p.cached_tokens)!=null?c:0,T=(u=(m=o.completion_tokens_details)==null?void 0:m.reasoning_tokens)!=null?u:0;return{inputTokens:{total:d,noCache:d-_,cacheRead:_,cacheWrite:void 0},outputTokens:{total:b,text:b-T,reasoning:T},raw:o}}function hn({prompt:o,systemMessageMode:l="system"}){var s;const p=[],c=[];for(const{role:m,content:u}of o)switch(m){case"system":{switch(l){case"system":{p.push({role:"system",content:u});break}case"developer":{p.push({role:"developer",content:u});break}case"remove":{c.push({type:"other",message:"system messages are removed for this model"});break}default:{const d=l;throw new Error(`Unsupported system message mode: ${d}`)}}break}case"user":{if(u.length===1&&u[0].type==="text"){p.push({role:"user",content:u[0].text});break}p.push({role:"user",content:u.map((d,b)=>{var _,T,w;switch(d.type){case"text":return{type:"text",text:d.text};case"file":if(d.mediaType.startsWith("image/")){const y=d.mediaType==="image/*"?"image/jpeg":d.mediaType;return{type:"image_url",image_url:{url:d.data instanceof URL?d.data.toString():`data:${y};base64,${Ie(d.data)}`,detail:(T=(_=d.providerOptions)==null?void 0:_.openai)==null?void 0:T.imageDetail}}}else if(d.mediaType.startsWith("audio/")){if(d.data instanceof URL)throw new _e({functionality:"audio file parts with URLs"});switch(d.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:Ie(d.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:Ie(d.data),format:"mp3"}};default:throw new _e({functionality:`audio content parts with media type ${d.mediaType}`})}}else if(d.mediaType==="application/pdf"){if(d.data instanceof URL)throw new _e({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof d.data=="string"&&d.data.startsWith("file-")?{file_id:d.data}:{filename:(w=d.filename)!=null?w:`part-${b}.pdf`,file_data:`data:application/pdf;base64,${Ie(d.data)}`}}}else throw new _e({functionality:`file part media type ${d.mediaType}`})}})});break}case"assistant":{let d="";const b=[];for(const _ of u)switch(_.type){case"text":{d+=_.text;break}case"tool-call":{b.push({id:_.toolCallId,type:"function",function:{name:_.toolName,arguments:JSON.stringify(_.input)}});break}}p.push({role:"assistant",content:d,tool_calls:b.length>0?b:void 0});break}case"tool":{for(const d of u){if(d.type==="tool-approval-response")continue;const b=d.output;let _;switch(b.type){case"text":case"error-text":_=b.value;break;case"execution-denied":_=(s=b.reason)!=null?s:"Tool execution denied.";break;case"content":case"json":case"error-json":_=JSON.stringify(b.value);break}p.push({role:"tool",tool_call_id:d.toolCallId,content:_})}break}default:{const d=m;throw new Error(`Unsupported role: ${d}`)}}return{messages:p,warnings:c}}function De({id:o,model:l,created:s}){return{id:o??void 0,modelId:l??void 0,timestamp:s?new Date(s*1e3):void 0}}function ct(o){switch(o){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"other"}}var gn=P(()=>D(t({id:e().nullish(),created:a().nullish(),model:e().nullish(),choices:x(t({message:t({role:n("assistant").nullish(),content:e().nullish(),tool_calls:x(t({id:e().nullish(),type:n("function"),function:t({name:e(),arguments:e()})})).nullish(),annotations:x(t({type:n("url_citation"),url_citation:t({start_index:a(),end_index:a(),url:e(),title:e()})})).nullish()}),index:a(),logprobs:t({content:x(t({token:e(),logprob:a(),top_logprobs:x(t({token:e(),logprob:a()}))})).nullish()}).nullish(),finish_reason:e().nullish()})),usage:t({prompt_tokens:a().nullish(),completion_tokens:a().nullish(),total_tokens:a().nullish(),prompt_tokens_details:t({cached_tokens:a().nullish()}).nullish(),completion_tokens_details:t({reasoning_tokens:a().nullish(),accepted_prediction_tokens:a().nullish(),rejected_prediction_tokens:a().nullish()}).nullish()}).nullish()}))),fn=P(()=>D(Q([t({id:e().nullish(),created:a().nullish(),model:e().nullish(),choices:x(t({delta:t({role:Y(["assistant"]).nullish(),content:e().nullish(),tool_calls:x(t({index:a(),id:e().nullish(),type:n("function").nullish(),function:t({name:e().nullish(),arguments:e().nullish()})})).nullish(),annotations:x(t({type:n("url_citation"),url_citation:t({start_index:a(),end_index:a(),url:e(),title:e()})})).nullish()}).nullish(),logprobs:t({content:x(t({token:e(),logprob:a(),top_logprobs:x(t({token:e(),logprob:a()}))})).nullish()}).nullish(),finish_reason:e().nullish(),index:a()})),usage:t({prompt_tokens:a().nullish(),completion_tokens:a().nullish(),total_tokens:a().nullish(),prompt_tokens_details:t({cached_tokens:a().nullish()}).nullish(),completion_tokens_details:t({reasoning_tokens:a().nullish(),accepted_prediction_tokens:a().nullish(),rejected_prediction_tokens:a().nullish()}).nullish()}).nullish()}),Je]))),yn=P(()=>D(t({logitBias:ue(uo(),a()).optional(),logprobs:Q([ne(),a()]).optional(),parallelToolCalls:ne().optional(),user:e().optional(),reasoningEffort:Y(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:a().optional(),store:ne().optional(),metadata:ue(e().max(64),e().max(512)).optional(),prediction:ue(e(),Ee()).optional(),serviceTier:Y(["auto","flex","priority","default"]).optional(),strictJsonSchema:ne().optional(),textVerbosity:Y(["low","medium","high"]).optional(),promptCacheKey:e().optional(),promptCacheRetention:Y(["in_memory","24h"]).optional(),safetyIdentifier:e().optional(),systemMessageMode:Y(["system","developer","remove"]).optional(),forceReasoning:ne().optional()})));function vn({tools:o,toolChoice:l}){o=o!=null&&o.length?o:void 0;const s=[];if(o==null)return{tools:void 0,toolChoice:void 0,toolWarnings:s};const p=[];for(const m of o)switch(m.type){case"function":p.push({type:"function",function:{name:m.name,description:m.description,parameters:m.inputSchema,...m.strict!=null?{strict:m.strict}:{}}});break;default:s.push({type:"unsupported",feature:`tool type: ${m.type}`});break}if(l==null)return{tools:p,toolChoice:void 0,toolWarnings:s};const c=l.type;switch(c){case"auto":case"none":case"required":return{tools:p,toolChoice:c,toolWarnings:s};case"tool":return{tools:p,toolChoice:{type:"function",function:{name:l.toolName}},toolWarnings:s};default:{const m=c;throw new _e({functionality:`tool choice type: ${m}`})}}}var bn=class{constructor(o,l){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=o,this.config=l}get provider(){return this.config.provider}async getArgs({prompt:o,maxOutputTokens:l,temperature:s,topP:p,topK:c,frequencyPenalty:m,presencePenalty:u,stopSequences:d,responseFormat:b,seed:_,tools:T,toolChoice:w,providerOptions:y}){var g,k,C,f,L;const $=[],M=(g=await me({provider:"openai",providerOptions:y,schema:yn}))!=null?g:{},X=Vt(this.modelId),q=(k=M.forceReasoning)!=null?k:X.isReasoningModel;c!=null&&$.push({type:"unsupported",feature:"topK"});const{messages:i,warnings:A}=hn({prompt:o,systemMessageMode:(C=M.systemMessageMode)!=null?C:q?"developer":X.systemMessageMode});$.push(...A);const ie=(f=M.strictJsonSchema)!=null?f:!0,h={model:this.modelId,logit_bias:M.logitBias,logprobs:M.logprobs===!0||typeof M.logprobs=="number"?!0:void 0,top_logprobs:typeof M.logprobs=="number"?M.logprobs:typeof M.logprobs=="boolean"&&M.logprobs?0:void 0,user:M.user,parallel_tool_calls:M.parallelToolCalls,max_tokens:l,temperature:s,top_p:p,frequency_penalty:m,presence_penalty:u,response_format:(b==null?void 0:b.type)==="json"?b.schema!=null?{type:"json_schema",json_schema:{schema:b.schema,strict:ie,name:(L=b.name)!=null?L:"response",description:b.description}}:{type:"json_object"}:void 0,stop:d,seed:_,verbosity:M.textVerbosity,max_completion_tokens:M.maxCompletionTokens,store:M.store,metadata:M.metadata,prediction:M.prediction,reasoning_effort:M.reasoningEffort,service_tier:M.serviceTier,prompt_cache_key:M.promptCacheKey,prompt_cache_retention:M.promptCacheRetention,safety_identifier:M.safetyIdentifier,messages:i};q?((M.reasoningEffort!=="none"||!X.supportsNonReasoningParameters)&&(h.temperature!=null&&(h.temperature=void 0,$.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),h.top_p!=null&&(h.top_p=void 0,$.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),h.logprobs!=null&&(h.logprobs=void 0,$.push({type:"other",message:"logprobs is not supported for reasoning models"}))),h.frequency_penalty!=null&&(h.frequency_penalty=void 0,$.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),h.presence_penalty!=null&&(h.presence_penalty=void 0,$.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),h.logit_bias!=null&&(h.logit_bias=void 0,$.push({type:"other",message:"logitBias is not supported for reasoning models"})),h.top_logprobs!=null&&(h.top_logprobs=void 0,$.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),h.max_tokens!=null&&(h.max_completion_tokens==null&&(h.max_completion_tokens=h.max_tokens),h.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&h.temperature!=null&&(h.temperature=void 0,$.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),M.serviceTier==="flex"&&!X.supportsFlexProcessing&&($.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),h.service_tier=void 0),M.serviceTier==="priority"&&!X.supportsPriorityProcessing&&($.push({type:"unsupported",feature:"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"}),h.service_tier=void 0);const{tools:K,toolChoice:N,toolWarnings:S}=vn({tools:T,toolChoice:w});return{args:{...h,tools:K,tool_choice:N},warnings:[...$,...S]}}async doGenerate(o){var l,s,p,c,m,u,d;const{args:b,warnings:_}=await this.getArgs(o),{responseHeaders:T,value:w,rawValue:y}=await fe({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:ge(this.config.headers(),o.headers),body:b,failedResponseHandler:ke,successfulResponseHandler:be(gn),abortSignal:o.abortSignal,fetch:this.config.fetch}),g=w.choices[0],k=[],C=g.message.content;C!=null&&C.length>0&&k.push({type:"text",text:C});for(const $ of(l=g.message.tool_calls)!=null?l:[])k.push({type:"tool-call",toolCallId:(s=$.id)!=null?s:pe(),toolName:$.function.name,input:$.function.arguments});for(const $ of(p=g.message.annotations)!=null?p:[])k.push({type:"source",sourceType:"url",id:pe(),url:$.url_citation.url,title:$.url_citation.title});const f=(c=w.usage)==null?void 0:c.completion_tokens_details;(m=w.usage)==null||m.prompt_tokens_details;const L={openai:{}};return(f==null?void 0:f.accepted_prediction_tokens)!=null&&(L.openai.acceptedPredictionTokens=f==null?void 0:f.accepted_prediction_tokens),(f==null?void 0:f.rejected_prediction_tokens)!=null&&(L.openai.rejectedPredictionTokens=f==null?void 0:f.rejected_prediction_tokens),((u=g.logprobs)==null?void 0:u.content)!=null&&(L.openai.logprobs=g.logprobs.content),{content:k,finishReason:{unified:ct(g.finish_reason),raw:(d=g.finish_reason)!=null?d:void 0},usage:pt(w.usage),request:{body:b},response:{...De(w),headers:T,body:y},warnings:_,providerMetadata:L}}async doStream(o){const{args:l,warnings:s}=await this.getArgs(o),p={...l,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:c,value:m}=await fe({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:ge(this.config.headers(),o.headers),body:p,failedResponseHandler:ke,successfulResponseHandler:Oe(fn),abortSignal:o.abortSignal,fetch:this.config.fetch}),u=[];let d={unified:"other",raw:void 0},b,_=!1,T=!1;const w={openai:{}};return{stream:m.pipeThrough(new TransformStream({start(y){y.enqueue({type:"stream-start",warnings:s})},transform(y,g){var k,C,f,L,$,M,X,q,i,A,ie,h,K,N,S,G,E;if(o.includeRawChunks&&g.enqueue({type:"raw",rawValue:y.rawValue}),!y.success){d={unified:"error",raw:void 0},g.enqueue({type:"error",error:y.error});return}const I=y.value;if("error"in I){d={unified:"error",raw:void 0},g.enqueue({type:"error",error:I.error});return}if(!_){const W=De(I);Object.values(W).some(Boolean)&&(_=!0,g.enqueue({type:"response-metadata",...De(I)}))}I.usage!=null&&(b=I.usage,((k=I.usage.completion_tokens_details)==null?void 0:k.accepted_prediction_tokens)!=null&&(w.openai.acceptedPredictionTokens=(C=I.usage.completion_tokens_details)==null?void 0:C.accepted_prediction_tokens),((f=I.usage.completion_tokens_details)==null?void 0:f.rejected_prediction_tokens)!=null&&(w.openai.rejectedPredictionTokens=(L=I.usage.completion_tokens_details)==null?void 0:L.rejected_prediction_tokens));const F=I.choices[0];if((F==null?void 0:F.finish_reason)!=null&&(d={unified:ct(F.finish_reason),raw:F.finish_reason}),(($=F==null?void 0:F.logprobs)==null?void 0:$.content)!=null&&(w.openai.logprobs=F.logprobs.content),(F==null?void 0:F.delta)==null)return;const V=F.delta;if(V.content!=null&&(T||(g.enqueue({type:"text-start",id:"0"}),T=!0),g.enqueue({type:"text-delta",id:"0",delta:V.content})),V.tool_calls!=null)for(const W of V.tool_calls){const ee=W.index;if(u[ee]==null){if(W.type!=="function")throw new qe({data:W,message:"Expected 'function' type."});if(W.id==null)throw new qe({data:W,message:"Expected 'id' to be a string."});if(((M=W.function)==null?void 0:M.name)==null)throw new qe({data:W,message:"Expected 'function.name' to be a string."});g.enqueue({type:"tool-input-start",id:W.id,toolName:W.function.name}),u[ee]={id:W.id,type:"function",function:{name:W.function.name,arguments:(X=W.function.arguments)!=null?X:""},hasFinished:!1};const le=u[ee];((q=le.function)==null?void 0:q.name)!=null&&((i=le.function)==null?void 0:i.arguments)!=null&&(le.function.arguments.length>0&&g.enqueue({type:"tool-input-delta",id:le.id,delta:le.function.arguments}),nt(le.function.arguments)&&(g.enqueue({type:"tool-input-end",id:le.id}),g.enqueue({type:"tool-call",toolCallId:(A=le.id)!=null?A:pe(),toolName:le.function.name,input:le.function.arguments}),le.hasFinished=!0));continue}const H=u[ee];H.hasFinished||(((ie=W.function)==null?void 0:ie.arguments)!=null&&(H.function.arguments+=(K=(h=W.function)==null?void 0:h.arguments)!=null?K:""),g.enqueue({type:"tool-input-delta",id:H.id,delta:(N=W.function.arguments)!=null?N:""}),((S=H.function)==null?void 0:S.name)!=null&&((G=H.function)==null?void 0:G.arguments)!=null&&nt(H.function.arguments)&&(g.enqueue({type:"tool-input-end",id:H.id}),g.enqueue({type:"tool-call",toolCallId:(E=H.id)!=null?E:pe(),toolName:H.function.name,input:H.function.arguments}),H.hasFinished=!0))}if(V.annotations!=null)for(const W of V.annotations)g.enqueue({type:"source",sourceType:"url",id:pe(),url:W.url_citation.url,title:W.url_citation.title})},flush(y){T&&y.enqueue({type:"text-end",id:"0"}),y.enqueue({type:"finish",finishReason:d,usage:pt(b),...w!=null?{providerMetadata:w}:{}})}})),request:{body:p},response:{headers:c}}}};function dt(o){var l,s,p,c;if(o==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const m=(l=o.prompt_tokens)!=null?l:0,u=(s=o.completion_tokens)!=null?s:0;return{inputTokens:{total:(p=o.prompt_tokens)!=null?p:void 0,noCache:m,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:(c=o.completion_tokens)!=null?c:void 0,text:u,reasoning:void 0},raw:o}}function xn({prompt:o,user:l="user",assistant:s="assistant"}){let p="";o[0].role==="system"&&(p+=`${o[0].content}
2
-
3
- `,o=o.slice(1));for(const{role:c,content:m}of o)switch(c){case"system":throw new ro({message:"Unexpected system message in prompt: ${content}",prompt:o});case"user":{const u=m.map(d=>{switch(d.type){case"text":return d.text}}).filter(Boolean).join("");p+=`${l}:
4
- ${u}
5
-
6
- `;break}case"assistant":{const u=m.map(d=>{switch(d.type){case"text":return d.text;case"tool-call":throw new _e({functionality:"tool-call messages"})}}).join("");p+=`${s}:
7
- ${u}
8
-
9
- `;break}case"tool":throw new _e({functionality:"tool messages"});default:{const u=c;throw new Error(`Unsupported role: ${u}`)}}return p+=`${s}:
10
- `,{prompt:p,stopSequences:[`
11
- ${l}:`]}}function _t({id:o,model:l,created:s}){return{id:o??void 0,modelId:l??void 0,timestamp:s!=null?new Date(s*1e3):void 0}}function mt(o){switch(o){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"other"}}var wn=P(()=>D(t({id:e().nullish(),created:a().nullish(),model:e().nullish(),choices:x(t({text:e(),finish_reason:e(),logprobs:t({tokens:x(e()),token_logprobs:x(a()),top_logprobs:x(ue(e(),a())).nullish()}).nullish()})),usage:t({prompt_tokens:a(),completion_tokens:a(),total_tokens:a()}).nullish()}))),kn=P(()=>D(Q([t({id:e().nullish(),created:a().nullish(),model:e().nullish(),choices:x(t({text:e(),finish_reason:e().nullish(),index:a(),logprobs:t({tokens:x(e()),token_logprobs:x(a()),top_logprobs:x(ue(e(),a())).nullish()}).nullish()})),usage:t({prompt_tokens:a(),completion_tokens:a(),total_tokens:a()}).nullish()}),Je]))),ht=P(()=>D(t({echo:ne().optional(),logitBias:ue(e(),a()).optional(),suffix:e().optional(),user:e().optional(),logprobs:Q([ne(),a()]).optional()}))),Cn=class{constructor(o,l){this.specificationVersion="v3",this.supportedUrls={},this.modelId=o,this.config=l}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:o,maxOutputTokens:l,temperature:s,topP:p,topK:c,frequencyPenalty:m,presencePenalty:u,stopSequences:d,responseFormat:b,tools:_,toolChoice:T,seed:w,providerOptions:y}){const g=[],k={...await me({provider:"openai",providerOptions:y,schema:ht}),...await me({provider:this.providerOptionsName,providerOptions:y,schema:ht})};c!=null&&g.push({type:"unsupported",feature:"topK"}),_!=null&&_.length&&g.push({type:"unsupported",feature:"tools"}),T!=null&&g.push({type:"unsupported",feature:"toolChoice"}),b!=null&&b.type!=="text"&&g.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:C,stopSequences:f}=xn({prompt:o}),L=[...f??[],...d??[]];return{args:{model:this.modelId,echo:k.echo,logit_bias:k.logitBias,logprobs:(k==null?void 0:k.logprobs)===!0?0:(k==null?void 0:k.logprobs)===!1||k==null?void 0:k.logprobs,suffix:k.suffix,user:k.user,max_tokens:l,temperature:s,top_p:p,frequency_penalty:m,presence_penalty:u,seed:w,prompt:C,stop:L.length>0?L:void 0},warnings:g}}async doGenerate(o){var l;const{args:s,warnings:p}=await this.getArgs(o),{responseHeaders:c,value:m,rawValue:u}=await fe({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:ge(this.config.headers(),o.headers),body:s,failedResponseHandler:ke,successfulResponseHandler:be(wn),abortSignal:o.abortSignal,fetch:this.config.fetch}),d=m.choices[0],b={openai:{}};return d.logprobs!=null&&(b.openai.logprobs=d.logprobs),{content:[{type:"text",text:d.text}],usage:dt(m.usage),finishReason:{unified:mt(d.finish_reason),raw:(l=d.finish_reason)!=null?l:void 0},request:{body:s},response:{..._t(m),headers:c,body:u},providerMetadata:b,warnings:p}}async doStream(o){const{args:l,warnings:s}=await this.getArgs(o),p={...l,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:c,value:m}=await fe({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:ge(this.config.headers(),o.headers),body:p,failedResponseHandler:ke,successfulResponseHandler:Oe(kn),abortSignal:o.abortSignal,fetch:this.config.fetch});let u={unified:"other",raw:void 0};const d={openai:{}};let b,_=!0;return{stream:m.pipeThrough(new TransformStream({start(T){T.enqueue({type:"stream-start",warnings:s})},transform(T,w){if(o.includeRawChunks&&w.enqueue({type:"raw",rawValue:T.rawValue}),!T.success){u={unified:"error",raw:void 0},w.enqueue({type:"error",error:T.error});return}const y=T.value;if("error"in y){u={unified:"error",raw:void 0},w.enqueue({type:"error",error:y.error});return}_&&(_=!1,w.enqueue({type:"response-metadata",..._t(y)}),w.enqueue({type:"text-start",id:"0"})),y.usage!=null&&(b=y.usage);const g=y.choices[0];(g==null?void 0:g.finish_reason)!=null&&(u={unified:mt(g.finish_reason),raw:g.finish_reason}),(g==null?void 0:g.logprobs)!=null&&(d.openai.logprobs=g.logprobs),(g==null?void 0:g.text)!=null&&g.text.length>0&&w.enqueue({type:"text-delta",id:"0",delta:g.text})},flush(T){_||T.enqueue({type:"text-end",id:"0"}),T.enqueue({type:"finish",finishReason:u,providerMetadata:d,usage:dt(b)})}})),request:{body:p},response:{headers:c}}}},In=P(()=>D(t({dimensions:a().optional(),user:e().optional()}))),Tn=P(()=>D(t({data:x(t({embedding:x(a())})),usage:t({prompt_tokens:a()}).nullish()}))),Sn=class{constructor(o,l){this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=o,this.config=l}get provider(){return this.config.provider}async doEmbed({values:o,headers:l,abortSignal:s,providerOptions:p}){var c;if(o.length>this.maxEmbeddingsPerCall)throw new $t({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:o});const m=(c=await me({provider:"openai",providerOptions:p,schema:In}))!=null?c:{},{responseHeaders:u,value:d,rawValue:b}=await fe({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:ge(this.config.headers(),l),body:{model:this.modelId,input:o,encoding_format:"float",dimensions:m.dimensions,user:m.user},failedResponseHandler:ke,successfulResponseHandler:be(Tn),abortSignal:s,fetch:this.config.fetch});return{warnings:[],embeddings:d.data.map(_=>_.embedding),usage:d.usage?{tokens:d.usage.prompt_tokens}:void 0,response:{headers:u,body:b}}}},gt=P(()=>D(t({created:a().nullish(),data:x(t({b64_json:e(),revised_prompt:e().nullish()})),background:e().nullish(),output_format:e().nullish(),size:e().nullish(),quality:e().nullish(),usage:t({input_tokens:a().nullish(),output_tokens:a().nullish(),total_tokens:a().nullish(),input_tokens_details:t({image_tokens:a().nullish(),text_tokens:a().nullish()}).nullish()}).nullish()}))),Nn={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10},Rn=["gpt-image-1-mini","gpt-image-1.5","gpt-image-1"];function On(o){return Rn.some(l=>o.startsWith(l))}var En=class{constructor(o,l){this.modelId=o,this.config=l,this.specificationVersion="v3"}get maxImagesPerCall(){var o;return(o=Nn[this.modelId])!=null?o:1}get provider(){return this.config.provider}async doGenerate({prompt:o,files:l,mask:s,n:p,size:c,aspectRatio:m,seed:u,providerOptions:d,headers:b,abortSignal:_}){var T,w,y,g,k,C,f,L,$,M,X;const q=[];m!=null&&q.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),u!=null&&q.push({type:"unsupported",feature:"seed"});const i=(y=(w=(T=this.config._internal)==null?void 0:T.currentDate)==null?void 0:w.call(T))!=null?y:new Date;if(l!=null){const{value:h,responseHeaders:K}=await Pt({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:ge(this.config.headers(),b),formData:io({model:this.modelId,prompt:o,image:await Promise.all(l.map(N=>N.type==="file"?new Blob([N.data instanceof Uint8Array?new Blob([N.data],{type:N.mediaType}):new Blob([We(N.data)],{type:N.mediaType})],{type:N.mediaType}):Dt(N.url))),mask:s!=null?await Mn(s):void 0,n:p,size:c,...(g=d.openai)!=null?g:{}}),failedResponseHandler:ke,successfulResponseHandler:be(gt),abortSignal:_,fetch:this.config.fetch});return{images:h.data.map(N=>N.b64_json),warnings:q,usage:h.usage!=null?{inputTokens:(k=h.usage.input_tokens)!=null?k:void 0,outputTokens:(C=h.usage.output_tokens)!=null?C:void 0,totalTokens:(f=h.usage.total_tokens)!=null?f:void 0}:void 0,response:{timestamp:i,modelId:this.modelId,headers:K},providerMetadata:{openai:{images:h.data.map(N=>{var S,G,E,I,F;return{...N.revised_prompt?{revisedPrompt:N.revised_prompt}:{},created:(S=h.created)!=null?S:void 0,size:(G=h.size)!=null?G:void 0,quality:(E=h.quality)!=null?E:void 0,background:(I=h.background)!=null?I:void 0,outputFormat:(F=h.output_format)!=null?F:void 0}})}}}}const{value:A,responseHeaders:ie}=await fe({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:ge(this.config.headers(),b),body:{model:this.modelId,prompt:o,n:p,size:c,...(L=d.openai)!=null?L:{},...On(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:ke,successfulResponseHandler:be(gt),abortSignal:_,fetch:this.config.fetch});return{images:A.data.map(h=>h.b64_json),warnings:q,usage:A.usage!=null?{inputTokens:($=A.usage.input_tokens)!=null?$:void 0,outputTokens:(M=A.usage.output_tokens)!=null?M:void 0,totalTokens:(X=A.usage.total_tokens)!=null?X:void 0}:void 0,response:{timestamp:i,modelId:this.modelId,headers:ie},providerMetadata:{openai:{images:A.data.map(h=>{var K,N,S,G,E;return{...h.revised_prompt?{revisedPrompt:h.revised_prompt}:{},created:(K=A.created)!=null?K:void 0,size:(N=A.size)!=null?N:void 0,quality:(S=A.quality)!=null?S:void 0,background:(G=A.background)!=null?G:void 0,outputFormat:(E=A.output_format)!=null?E:void 0}})}}}}};async function Mn(o){if(!o)return;if(o.type==="url")return Dt(o.url);const l=o.data instanceof Uint8Array?o.data:We(o.data);return new Blob([l],{type:o.mediaType})}var qn=P(()=>D(t({callId:e(),operation:ae("type",[t({type:n("create_file"),path:e(),diff:e()}),t({type:n("delete_file"),path:e()}),t({type:n("update_file"),path:e(),diff:e()})])}))),Bt=P(()=>D(t({status:Y(["completed","failed"]),output:e().optional()}))),An=ye({id:"openai.apply_patch",inputSchema:qn,outputSchema:Bt}),$n=An,Pn=P(()=>D(t({code:e().nullish(),containerId:e()}))),Dn=P(()=>D(t({outputs:x(ae("type",[t({type:n("logs"),logs:e()}),t({type:n("image"),url:e()})])).nullish()}))),Un=P(()=>D(t({container:Q([e(),t({fileIds:x(e()).optional()})]).optional()}))),Ln=ye({id:"openai.code_interpreter",inputSchema:Pn,outputSchema:Dn}),Hn=(o={})=>Ln(o),Wt=t({key:e(),type:Y(["eq","ne","gt","gte","lt","lte","in","nin"]),value:Q([e(),a(),ne(),x(e())])}),Ft=t({type:Y(["and","or"]),filters:x(Q([Wt,At(()=>Ft)]))}),jn=P(()=>D(t({vectorStoreIds:x(e()),maxNumResults:a().optional(),ranking:t({ranker:e().optional(),scoreThreshold:a().optional()}).optional(),filters:Q([Wt,Ft]).optional()}))),Gn=P(()=>D(t({queries:x(e()),results:x(t({attributes:ue(e(),we()),fileId:e(),filename:e(),score:a(),text:e()})).nullable()}))),Vn=ye({id:"openai.file_search",inputSchema:t({}),outputSchema:Gn}),Bn=P(()=>D(t({background:Y(["auto","opaque","transparent"]).optional(),inputFidelity:Y(["low","high"]).optional(),inputImageMask:t({fileId:e().optional(),imageUrl:e().optional()}).optional(),model:e().optional(),moderation:Y(["auto"]).optional(),outputCompression:a().int().min(0).max(100).optional(),outputFormat:Y(["png","jpeg","webp"]).optional(),partialImages:a().int().min(0).max(3).optional(),quality:Y(["auto","low","medium","high"]).optional(),size:Y(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),Wn=P(()=>D(t({}))),Fn=P(()=>D(t({result:e()}))),Jn=ye({id:"openai.image_generation",inputSchema:Wn,outputSchema:Fn}),Kn=(o={})=>Jn(o),Jt=P(()=>D(t({action:t({type:n("exec"),command:x(e()),timeoutMs:a().optional(),user:e().optional(),workingDirectory:e().optional(),env:ue(e(),e()).optional()})}))),Kt=P(()=>D(t({output:e()}))),zn=ye({id:"openai.local_shell",inputSchema:Jt,outputSchema:Kt}),zt=P(()=>D(t({action:t({commands:x(e()),timeoutMs:a().optional(),maxOutputLength:a().optional()})}))),Yt=P(()=>D(t({output:x(t({stdout:e(),stderr:e(),outcome:ae("type",[t({type:n("timeout")}),t({type:n("exit"),exitCode:a()})])}))}))),Yn=ye({id:"openai.shell",inputSchema:zt,outputSchema:Yt}),Xn=P(()=>D(t({externalWebAccess:ne().optional(),filters:t({allowedDomains:x(e()).optional()}).optional(),searchContextSize:Y(["low","medium","high"]).optional(),userLocation:t({type:n("approximate"),country:e().optional(),city:e().optional(),region:e().optional(),timezone:e().optional()}).optional()}))),Qn=P(()=>D(t({}))),Zn=P(()=>D(t({action:ae("type",[t({type:n("search"),query:e().optional()}),t({type:n("openPage"),url:e().nullish()}),t({type:n("findInPage"),url:e().nullish(),pattern:e().nullish()})]),sources:x(ae("type",[t({type:n("url"),url:e()}),t({type:n("api"),name:e()})])).optional()}))),ea=ye({id:"openai.web_search",inputSchema:Qn,outputSchema:Zn}),ta=(o={})=>ea(o),oa=P(()=>D(t({searchContextSize:Y(["low","medium","high"]).optional(),userLocation:t({type:n("approximate"),country:e().optional(),city:e().optional(),region:e().optional(),timezone:e().optional()}).optional()}))),na=P(()=>D(t({}))),aa=P(()=>D(t({action:ae("type",[t({type:n("search"),query:e().optional()}),t({type:n("openPage"),url:e().nullish()}),t({type:n("findInPage"),url:e().nullish(),pattern:e().nullish()})])}))),ia=ye({id:"openai.web_search_preview",inputSchema:na,outputSchema:aa}),He=At(()=>Q([e(),a(),ne(),ao(),x(He),ue(e(),He)])),la=P(()=>D(t({serverLabel:e(),allowedTools:Q([x(e()),t({readOnly:ne().optional(),toolNames:x(e()).optional()})]).optional(),authorization:e().optional(),connectorId:e().optional(),headers:ue(e(),e()).optional(),requireApproval:Q([Y(["always","never"]),t({never:t({toolNames:x(e()).optional()}).optional()})]).optional(),serverDescription:e().optional(),serverUrl:e().optional()}).refine(o=>o.serverUrl!=null||o.connectorId!=null,"One of serverUrl or connectorId must be provided."))),sa=P(()=>D(t({}))),ra=P(()=>D(t({type:n("call"),serverLabel:e(),name:e(),arguments:e(),output:e().nullish(),error:Q([e(),He]).optional()}))),ua=ye({id:"openai.mcp",inputSchema:sa,outputSchema:ra}),pa=o=>ua(o),ca={applyPatch:$n,codeInterpreter:Hn,fileSearch:Vn,imageGeneration:Kn,localShell:zn,shell:Yn,webSearchPreview:ia,webSearch:ta,mcp:pa};function ft(o){var l,s,p,c;if(o==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const m=o.input_tokens,u=o.output_tokens,d=(s=(l=o.input_tokens_details)==null?void 0:l.cached_tokens)!=null?s:0,b=(c=(p=o.output_tokens_details)==null?void 0:p.reasoning_tokens)!=null?c:0;return{inputTokens:{total:m,noCache:m-d,cacheRead:d,cacheWrite:void 0},outputTokens:{total:u,text:u-b,reasoning:b},raw:o}}function yt(o,l){return l?l.some(s=>o.startsWith(s)):!1}async function da({prompt:o,toolNameMapping:l,systemMessageMode:s,providerOptionsName:p,fileIdPrefixes:c,store:m,hasLocalShellTool:u=!1,hasShellTool:d=!1,hasApplyPatchTool:b=!1}){var _,T,w,y,g,k,C,f,L,$,M,X,q;const i=[],A=[],ie=new Set;for(const{role:h,content:K}of o)switch(h){case"system":{switch(s){case"system":{i.push({role:"system",content:K});break}case"developer":{i.push({role:"developer",content:K});break}case"remove":{A.push({type:"other",message:"system messages are removed for this model"});break}default:{const N=s;throw new Error(`Unsupported system message mode: ${N}`)}}break}case"user":{i.push({role:"user",content:K.map((N,S)=>{var G,E,I;switch(N.type){case"text":return{type:"input_text",text:N.text};case"file":if(N.mediaType.startsWith("image/")){const F=N.mediaType==="image/*"?"image/jpeg":N.mediaType;return{type:"input_image",...N.data instanceof URL?{image_url:N.data.toString()}:typeof N.data=="string"&&yt(N.data,c)?{file_id:N.data}:{image_url:`data:${F};base64,${Ie(N.data)}`},detail:(E=(G=N.providerOptions)==null?void 0:G[p])==null?void 0:E.imageDetail}}else{if(N.mediaType==="application/pdf")return N.data instanceof URL?{type:"input_file",file_url:N.data.toString()}:{type:"input_file",...typeof N.data=="string"&&yt(N.data,c)?{file_id:N.data}:{filename:(I=N.filename)!=null?I:`part-${S}.pdf`,file_data:`data:application/pdf;base64,${Ie(N.data)}`}};throw new _e({functionality:`file part media type ${N.mediaType}`})}}})});break}case"assistant":{const N={};for(const S of K)switch(S.type){case"text":{const G=(T=(_=S.providerOptions)==null?void 0:_[p])==null?void 0:T.itemId;if(m&&G!=null){i.push({type:"item_reference",id:G});break}i.push({role:"assistant",content:[{type:"output_text",text:S.text}],id:G});break}case"tool-call":{const G=(C=(y=(w=S.providerOptions)==null?void 0:w[p])==null?void 0:y.itemId)!=null?C:(k=(g=S.providerMetadata)==null?void 0:g[p])==null?void 0:k.itemId;if(S.providerExecuted){m&&G!=null&&i.push({type:"item_reference",id:G});break}if(m&&G!=null){i.push({type:"item_reference",id:G});break}const E=l.toProviderToolName(S.toolName);if(u&&E==="local_shell"){const I=await ce({value:S.input,schema:Jt});i.push({type:"local_shell_call",call_id:S.toolCallId,id:G,action:{type:"exec",command:I.action.command,timeout_ms:I.action.timeoutMs,user:I.action.user,working_directory:I.action.workingDirectory,env:I.action.env}});break}if(d&&E==="shell"){const I=await ce({value:S.input,schema:zt});i.push({type:"shell_call",call_id:S.toolCallId,id:G,status:"completed",action:{commands:I.action.commands,timeout_ms:I.action.timeoutMs,max_output_length:I.action.maxOutputLength}});break}i.push({type:"function_call",call_id:S.toolCallId,name:E,arguments:JSON.stringify(S.input),id:G});break}case"tool-result":{if(S.output.type==="execution-denied"||S.output.type==="json"&&typeof S.output.value=="object"&&S.output.value!=null&&"type"in S.output.value&&S.output.value.type==="execution-denied")break;if(m){const G=($=(L=(f=S.providerMetadata)==null?void 0:f[p])==null?void 0:L.itemId)!=null?$:S.toolCallId;i.push({type:"item_reference",id:G})}else A.push({type:"other",message:`Results for OpenAI tool ${S.toolName} are not sent to the API when store is false`});break}case"reasoning":{const G=await me({provider:p,providerOptions:S.providerOptions,schema:_a}),E=G==null?void 0:G.itemId;if(E!=null){const I=N[E];if(m)I===void 0&&(i.push({type:"item_reference",id:E}),N[E]={type:"reasoning",id:E,summary:[]});else{const F=[];S.text.length>0?F.push({type:"summary_text",text:S.text}):I!==void 0&&A.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(S)}.`}),I===void 0?(N[E]={type:"reasoning",id:E,encrypted_content:G==null?void 0:G.reasoningEncryptedContent,summary:F},i.push(N[E])):(I.summary.push(...F),(G==null?void 0:G.reasoningEncryptedContent)!=null&&(I.encrypted_content=G.reasoningEncryptedContent))}}else A.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(S)}.`});break}}break}case"tool":{for(const N of K){if(N.type==="tool-approval-response"){const I=N;if(ie.has(I.approvalId))continue;ie.add(I.approvalId),m&&i.push({type:"item_reference",id:I.approvalId}),i.push({type:"mcp_approval_response",approval_request_id:I.approvalId,approve:I.approved});continue}const S=N.output;if(S.type==="execution-denied"&&((X=(M=S.providerOptions)==null?void 0:M.openai)==null?void 0:X.approvalId))continue;const G=l.toProviderToolName(N.toolName);if(u&&G==="local_shell"&&S.type==="json"){const I=await ce({value:S.value,schema:Kt});i.push({type:"local_shell_call_output",call_id:N.toolCallId,output:I.output});continue}if(d&&G==="shell"&&S.type==="json"){const I=await ce({value:S.value,schema:Yt});i.push({type:"shell_call_output",call_id:N.toolCallId,output:I.output.map(F=>({stdout:F.stdout,stderr:F.stderr,outcome:F.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:F.outcome.exitCode}}))});continue}if(b&&N.toolName==="apply_patch"&&S.type==="json"){const I=await ce({value:S.value,schema:Bt});i.push({type:"apply_patch_call_output",call_id:N.toolCallId,status:I.status,output:I.output});continue}let E;switch(S.type){case"text":case"error-text":E=S.value;break;case"execution-denied":E=(q=S.reason)!=null?q:"Tool execution denied.";break;case"json":case"error-json":E=JSON.stringify(S.value);break;case"content":E=S.value.map(I=>{var F;switch(I.type){case"text":return{type:"input_text",text:I.text};case"image-data":return{type:"input_image",image_url:`data:${I.mediaType};base64,${I.data}`};case"image-url":return{type:"input_image",image_url:I.url};case"file-data":return{type:"input_file",filename:(F=I.filename)!=null?F:"data",file_data:`data:${I.mediaType};base64,${I.data}`};default:{A.push({type:"other",message:`unsupported tool content part type: ${I.type}`});return}}}).filter(qt);break}i.push({type:"function_call_output",call_id:N.toolCallId,output:E})}break}default:{const N=h;throw new Error(`Unsupported role: ${N}`)}}return{input:i,warnings:A}}var _a=t({itemId:e().nullish(),reasoningEncryptedContent:e().nullish()});function vt({finishReason:o,hasFunctionCall:l}){switch(o){case void 0:case null:return l?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return l?"tool-calls":"other"}}var ma=P(()=>D(Q([t({type:n("response.output_text.delta"),item_id:e(),delta:e(),logprobs:x(t({token:e(),logprob:a(),top_logprobs:x(t({token:e(),logprob:a()}))})).nullish()}),t({type:Y(["response.completed","response.incomplete"]),response:t({incomplete_details:t({reason:e()}).nullish(),usage:t({input_tokens:a(),input_tokens_details:t({cached_tokens:a().nullish()}).nullish(),output_tokens:a(),output_tokens_details:t({reasoning_tokens:a().nullish()}).nullish()}),service_tier:e().nullish()})}),t({type:n("response.created"),response:t({id:e(),created_at:a(),model:e(),service_tier:e().nullish()})}),t({type:n("response.output_item.added"),output_index:a(),item:ae("type",[t({type:n("message"),id:e()}),t({type:n("reasoning"),id:e(),encrypted_content:e().nullish()}),t({type:n("function_call"),id:e(),call_id:e(),name:e(),arguments:e()}),t({type:n("web_search_call"),id:e(),status:e()}),t({type:n("computer_call"),id:e(),status:e()}),t({type:n("file_search_call"),id:e()}),t({type:n("image_generation_call"),id:e()}),t({type:n("code_interpreter_call"),id:e(),container_id:e(),code:e().nullable(),outputs:x(ae("type",[t({type:n("logs"),logs:e()}),t({type:n("image"),url:e()})])).nullable(),status:e()}),t({type:n("mcp_call"),id:e(),status:e(),approval_request_id:e().nullish()}),t({type:n("mcp_list_tools"),id:e()}),t({type:n("mcp_approval_request"),id:e()}),t({type:n("apply_patch_call"),id:e(),call_id:e(),status:Y(["in_progress","completed"]),operation:ae("type",[t({type:n("create_file"),path:e(),diff:e()}),t({type:n("delete_file"),path:e()}),t({type:n("update_file"),path:e(),diff:e()})])}),t({type:n("shell_call"),id:e(),call_id:e(),status:Y(["in_progress","completed","incomplete"]),action:t({commands:x(e())})})])}),t({type:n("response.output_item.done"),output_index:a(),item:ae("type",[t({type:n("message"),id:e()}),t({type:n("reasoning"),id:e(),encrypted_content:e().nullish()}),t({type:n("function_call"),id:e(),call_id:e(),name:e(),arguments:e(),status:n("completed")}),t({type:n("code_interpreter_call"),id:e(),code:e().nullable(),container_id:e(),outputs:x(ae("type",[t({type:n("logs"),logs:e()}),t({type:n("image"),url:e()})])).nullable()}),t({type:n("image_generation_call"),id:e(),result:e()}),t({type:n("web_search_call"),id:e(),status:e(),action:ae("type",[t({type:n("search"),query:e().nullish(),sources:x(ae("type",[t({type:n("url"),url:e()}),t({type:n("api"),name:e()})])).nullish()}),t({type:n("open_page"),url:e().nullish()}),t({type:n("find_in_page"),url:e().nullish(),pattern:e().nullish()})])}),t({type:n("file_search_call"),id:e(),queries:x(e()),results:x(t({attributes:ue(e(),Q([e(),a(),ne()])),file_id:e(),filename:e(),score:a(),text:e()})).nullish()}),t({type:n("local_shell_call"),id:e(),call_id:e(),action:t({type:n("exec"),command:x(e()),timeout_ms:a().optional(),user:e().optional(),working_directory:e().optional(),env:ue(e(),e()).optional()})}),t({type:n("computer_call"),id:e(),status:n("completed")}),t({type:n("mcp_call"),id:e(),status:e(),arguments:e(),name:e(),server_label:e(),output:e().nullish(),error:Q([e(),t({type:e().optional(),code:Q([a(),e()]).optional(),message:e().optional()}).loose()]).nullish(),approval_request_id:e().nullish()}),t({type:n("mcp_list_tools"),id:e(),server_label:e(),tools:x(t({name:e(),description:e().optional(),input_schema:Ee(),annotations:ue(e(),we()).optional()})),error:Q([e(),t({type:e().optional(),code:Q([a(),e()]).optional(),message:e().optional()}).loose()]).optional()}),t({type:n("mcp_approval_request"),id:e(),server_label:e(),name:e(),arguments:e(),approval_request_id:e().optional()}),t({type:n("apply_patch_call"),id:e(),call_id:e(),status:Y(["in_progress","completed"]),operation:ae("type",[t({type:n("create_file"),path:e(),diff:e()}),t({type:n("delete_file"),path:e()}),t({type:n("update_file"),path:e(),diff:e()})])}),t({type:n("shell_call"),id:e(),call_id:e(),status:Y(["in_progress","completed","incomplete"]),action:t({commands:x(e())})})])}),t({type:n("response.function_call_arguments.delta"),item_id:e(),output_index:a(),delta:e()}),t({type:n("response.image_generation_call.partial_image"),item_id:e(),output_index:a(),partial_image_b64:e()}),t({type:n("response.code_interpreter_call_code.delta"),item_id:e(),output_index:a(),delta:e()}),t({type:n("response.code_interpreter_call_code.done"),item_id:e(),output_index:a(),code:e()}),t({type:n("response.output_text.annotation.added"),annotation:ae("type",[t({type:n("url_citation"),start_index:a(),end_index:a(),url:e(),title:e()}),t({type:n("file_citation"),file_id:e(),filename:e().nullish(),index:a().nullish(),start_index:a().nullish(),end_index:a().nullish(),quote:e().nullish()}),t({type:n("container_file_citation"),container_id:e(),file_id:e(),filename:e().nullish(),start_index:a().nullish(),end_index:a().nullish(),index:a().nullish()}),t({type:n("file_path"),file_id:e(),index:a().nullish()})])}),t({type:n("response.reasoning_summary_part.added"),item_id:e(),summary_index:a()}),t({type:n("response.reasoning_summary_text.delta"),item_id:e(),summary_index:a(),delta:e()}),t({type:n("response.reasoning_summary_part.done"),item_id:e(),summary_index:a()}),t({type:n("response.apply_patch_call_operation_diff.delta"),item_id:e(),output_index:a(),delta:e(),obfuscation:e().nullish()}),t({type:n("response.apply_patch_call_operation_diff.done"),item_id:e(),output_index:a(),diff:e()}),t({type:n("error"),sequence_number:a(),error:t({type:e(),code:e(),message:e(),param:e().nullish()})}),t({type:e()}).loose().transform(o=>({type:"unknown_chunk",message:o.type}))]))),ha=P(()=>D(t({id:e().optional(),created_at:a().optional(),error:t({message:e(),type:e(),param:e().nullish(),code:e()}).nullish(),model:e().optional(),output:x(ae("type",[t({type:n("message"),role:n("assistant"),id:e(),content:x(t({type:n("output_text"),text:e(),logprobs:x(t({token:e(),logprob:a(),top_logprobs:x(t({token:e(),logprob:a()}))})).nullish(),annotations:x(ae("type",[t({type:n("url_citation"),start_index:a(),end_index:a(),url:e(),title:e()}),t({type:n("file_citation"),file_id:e(),filename:e().nullish(),index:a().nullish(),start_index:a().nullish(),end_index:a().nullish(),quote:e().nullish()}),t({type:n("container_file_citation"),container_id:e(),file_id:e(),filename:e().nullish(),start_index:a().nullish(),end_index:a().nullish(),index:a().nullish()}),t({type:n("file_path"),file_id:e(),index:a().nullish()})]))}))}),t({type:n("web_search_call"),id:e(),status:e(),action:ae("type",[t({type:n("search"),query:e().nullish(),sources:x(ae("type",[t({type:n("url"),url:e()}),t({type:n("api"),name:e()})])).nullish()}),t({type:n("open_page"),url:e().nullish()}),t({type:n("find_in_page"),url:e().nullish(),pattern:e().nullish()})])}),t({type:n("file_search_call"),id:e(),queries:x(e()),results:x(t({attributes:ue(e(),Q([e(),a(),ne()])),file_id:e(),filename:e(),score:a(),text:e()})).nullish()}),t({type:n("code_interpreter_call"),id:e(),code:e().nullable(),container_id:e(),outputs:x(ae("type",[t({type:n("logs"),logs:e()}),t({type:n("image"),url:e()})])).nullable()}),t({type:n("image_generation_call"),id:e(),result:e()}),t({type:n("local_shell_call"),id:e(),call_id:e(),action:t({type:n("exec"),command:x(e()),timeout_ms:a().optional(),user:e().optional(),working_directory:e().optional(),env:ue(e(),e()).optional()})}),t({type:n("function_call"),call_id:e(),name:e(),arguments:e(),id:e()}),t({type:n("computer_call"),id:e(),status:e().optional()}),t({type:n("reasoning"),id:e(),encrypted_content:e().nullish(),summary:x(t({type:n("summary_text"),text:e()}))}),t({type:n("mcp_call"),id:e(),status:e(),arguments:e(),name:e(),server_label:e(),output:e().nullish(),error:Q([e(),t({type:e().optional(),code:Q([a(),e()]).optional(),message:e().optional()}).loose()]).nullish(),approval_request_id:e().nullish()}),t({type:n("mcp_list_tools"),id:e(),server_label:e(),tools:x(t({name:e(),description:e().optional(),input_schema:Ee(),annotations:ue(e(),we()).optional()})),error:Q([e(),t({type:e().optional(),code:Q([a(),e()]).optional(),message:e().optional()}).loose()]).optional()}),t({type:n("mcp_approval_request"),id:e(),server_label:e(),name:e(),arguments:e(),approval_request_id:e().optional()}),t({type:n("apply_patch_call"),id:e(),call_id:e(),status:Y(["in_progress","completed"]),operation:ae("type",[t({type:n("create_file"),path:e(),diff:e()}),t({type:n("delete_file"),path:e()}),t({type:n("update_file"),path:e(),diff:e()})])}),t({type:n("shell_call"),id:e(),call_id:e(),status:Y(["in_progress","completed","incomplete"]),action:t({commands:x(e())})})])).optional(),service_tier:e().nullish(),incomplete_details:t({reason:e()}).nullish(),usage:t({input_tokens:a(),input_tokens_details:t({cached_tokens:a().nullish()}).nullish(),output_tokens:a(),output_tokens_details:t({reasoning_tokens:a().nullish()}).nullish()}).optional()}))),Xt=20,bt=P(()=>D(t({conversation:e().nullish(),include:x(Y(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:e().nullish(),logprobs:Q([ne(),a().min(1).max(Xt)]).optional(),maxToolCalls:a().nullish(),metadata:Ee().nullish(),parallelToolCalls:ne().nullish(),previousResponseId:e().nullish(),promptCacheKey:e().nullish(),promptCacheRetention:Y(["in_memory","24h"]).nullish(),reasoningEffort:e().nullish(),reasoningSummary:e().nullish(),safetyIdentifier:e().nullish(),serviceTier:Y(["auto","flex","priority","default"]).nullish(),store:ne().nullish(),strictJsonSchema:ne().nullish(),textVerbosity:Y(["low","medium","high"]).nullish(),truncation:Y(["auto","disabled"]).nullish(),user:e().nullish(),systemMessageMode:Y(["system","developer","remove"]).optional(),forceReasoning:ne().optional()})));async function ga({tools:o,toolChoice:l}){o=o!=null&&o.length?o:void 0;const s=[];if(o==null)return{tools:void 0,toolChoice:void 0,toolWarnings:s};const p=[];for(const m of o)switch(m.type){case"function":p.push({type:"function",name:m.name,description:m.description,parameters:m.inputSchema,...m.strict!=null?{strict:m.strict}:{}});break;case"provider":{switch(m.id){case"openai.file_search":{const u=await ce({value:m.args,schema:jn});p.push({type:"file_search",vector_store_ids:u.vectorStoreIds,max_num_results:u.maxNumResults,ranking_options:u.ranking?{ranker:u.ranking.ranker,score_threshold:u.ranking.scoreThreshold}:void 0,filters:u.filters});break}case"openai.local_shell":{p.push({type:"local_shell"});break}case"openai.shell":{p.push({type:"shell"});break}case"openai.apply_patch":{p.push({type:"apply_patch"});break}case"openai.web_search_preview":{const u=await ce({value:m.args,schema:oa});p.push({type:"web_search_preview",search_context_size:u.searchContextSize,user_location:u.userLocation});break}case"openai.web_search":{const u=await ce({value:m.args,schema:Xn});p.push({type:"web_search",filters:u.filters!=null?{allowed_domains:u.filters.allowedDomains}:void 0,external_web_access:u.externalWebAccess,search_context_size:u.searchContextSize,user_location:u.userLocation});break}case"openai.code_interpreter":{const u=await ce({value:m.args,schema:Un});p.push({type:"code_interpreter",container:u.container==null?{type:"auto",file_ids:void 0}:typeof u.container=="string"?u.container:{type:"auto",file_ids:u.container.fileIds}});break}case"openai.image_generation":{const u=await ce({value:m.args,schema:Bn});p.push({type:"image_generation",background:u.background,input_fidelity:u.inputFidelity,input_image_mask:u.inputImageMask?{file_id:u.inputImageMask.fileId,image_url:u.inputImageMask.imageUrl}:void 0,model:u.model,moderation:u.moderation,partial_images:u.partialImages,quality:u.quality,output_compression:u.outputCompression,output_format:u.outputFormat,size:u.size});break}case"openai.mcp":{const u=await ce({value:m.args,schema:la}),d=T=>({tool_names:T.toolNames}),b=u.requireApproval,_=b==null?void 0:typeof b=="string"?b:b.never!=null?{never:d(b.never)}:void 0;p.push({type:"mcp",server_label:u.serverLabel,allowed_tools:Array.isArray(u.allowedTools)?u.allowedTools:u.allowedTools?{read_only:u.allowedTools.readOnly,tool_names:u.allowedTools.toolNames}:void 0,authorization:u.authorization,connector_id:u.connectorId,headers:u.headers,require_approval:_??"never",server_description:u.serverDescription,server_url:u.serverUrl});break}}break}default:s.push({type:"unsupported",feature:`function tool ${m}`});break}if(l==null)return{tools:p,toolChoice:void 0,toolWarnings:s};const c=l.type;switch(c){case"auto":case"none":case"required":return{tools:p,toolChoice:c,toolWarnings:s};case"tool":return{tools:p,toolChoice:l.toolName==="code_interpreter"||l.toolName==="file_search"||l.toolName==="image_generation"||l.toolName==="web_search_preview"||l.toolName==="web_search"||l.toolName==="mcp"||l.toolName==="apply_patch"?{type:l.toolName}:{type:"function",name:l.toolName},toolWarnings:s};default:{const m=c;throw new _e({functionality:`tool choice type: ${m}`})}}}function xt(o){var l,s;const p={};for(const c of o)if(c.role==="assistant")for(const m of c.content){if(m.type!=="tool-call")continue;const u=(s=(l=m.providerOptions)==null?void 0:l.openai)==null?void 0:s.approvalRequestId;u!=null&&(p[u]=m.toolCallId)}return p}var fa=class{constructor(o,l){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=o,this.config=l}get provider(){return this.config.provider}async getArgs({maxOutputTokens:o,temperature:l,stopSequences:s,topP:p,topK:c,presencePenalty:m,frequencyPenalty:u,seed:d,prompt:b,providerOptions:_,tools:T,toolChoice:w,responseFormat:y}){var g,k,C,f,L,$;const M=[],X=Vt(this.modelId);c!=null&&M.push({type:"unsupported",feature:"topK"}),d!=null&&M.push({type:"unsupported",feature:"seed"}),m!=null&&M.push({type:"unsupported",feature:"presencePenalty"}),u!=null&&M.push({type:"unsupported",feature:"frequencyPenalty"}),s!=null&&M.push({type:"unsupported",feature:"stopSequences"});const q=this.config.provider.includes("azure")?"azure":"openai";let i=await me({provider:q,providerOptions:_,schema:bt});i==null&&q!=="openai"&&(i=await me({provider:"openai",providerOptions:_,schema:bt}));const A=(g=i==null?void 0:i.forceReasoning)!=null?g:X.isReasoningModel;i!=null&&i.conversation&&(i!=null&&i.previousResponseId)&&M.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const ie=Et({tools:T,providerToolNames:{"openai.code_interpreter":"code_interpreter","openai.file_search":"file_search","openai.image_generation":"image_generation","openai.local_shell":"local_shell","openai.shell":"shell","openai.web_search":"web_search","openai.web_search_preview":"web_search_preview","openai.mcp":"mcp","openai.apply_patch":"apply_patch"}}),{input:h,warnings:K}=await da({prompt:b,toolNameMapping:ie,systemMessageMode:(k=i==null?void 0:i.systemMessageMode)!=null?k:A?"developer":X.systemMessageMode,providerOptionsName:q,fileIdPrefixes:this.config.fileIdPrefixes,store:(C=i==null?void 0:i.store)!=null?C:!0,hasLocalShellTool:E("openai.local_shell"),hasShellTool:E("openai.shell"),hasApplyPatchTool:E("openai.apply_patch")});M.push(...K);const N=(f=i==null?void 0:i.strictJsonSchema)!=null?f:!0;let S=i==null?void 0:i.include;function G(R){S==null?S=[R]:S.includes(R)||(S=[...S,R])}function E(R){return(T==null?void 0:T.find(re=>re.type==="provider"&&re.id===R))!=null}const I=typeof(i==null?void 0:i.logprobs)=="number"?i==null?void 0:i.logprobs:(i==null?void 0:i.logprobs)===!0?Xt:void 0;I&&G("message.output_text.logprobs");const F=(L=T==null?void 0:T.find(R=>R.type==="provider"&&(R.id==="openai.web_search"||R.id==="openai.web_search_preview")))==null?void 0:L.name;F&&G("web_search_call.action.sources"),E("openai.code_interpreter")&&G("code_interpreter_call.outputs");const V=i==null?void 0:i.store;V===!1&&A&&G("reasoning.encrypted_content");const W={model:this.modelId,input:h,temperature:l,top_p:p,max_output_tokens:o,...((y==null?void 0:y.type)==="json"||(i==null?void 0:i.textVerbosity))&&{text:{...(y==null?void 0:y.type)==="json"&&{format:y.schema!=null?{type:"json_schema",strict:N,name:($=y.name)!=null?$:"response",description:y.description,schema:y.schema}:{type:"json_object"}},...(i==null?void 0:i.textVerbosity)&&{verbosity:i.textVerbosity}}},conversation:i==null?void 0:i.conversation,max_tool_calls:i==null?void 0:i.maxToolCalls,metadata:i==null?void 0:i.metadata,parallel_tool_calls:i==null?void 0:i.parallelToolCalls,previous_response_id:i==null?void 0:i.previousResponseId,store:V,user:i==null?void 0:i.user,instructions:i==null?void 0:i.instructions,service_tier:i==null?void 0:i.serviceTier,include:S,prompt_cache_key:i==null?void 0:i.promptCacheKey,prompt_cache_retention:i==null?void 0:i.promptCacheRetention,safety_identifier:i==null?void 0:i.safetyIdentifier,top_logprobs:I,truncation:i==null?void 0:i.truncation,...A&&((i==null?void 0:i.reasoningEffort)!=null||(i==null?void 0:i.reasoningSummary)!=null)&&{reasoning:{...(i==null?void 0:i.reasoningEffort)!=null&&{effort:i.reasoningEffort},...(i==null?void 0:i.reasoningSummary)!=null&&{summary:i.reasoningSummary}}}};A?(i==null?void 0:i.reasoningEffort)==="none"&&X.supportsNonReasoningParameters||(W.temperature!=null&&(W.temperature=void 0,M.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),W.top_p!=null&&(W.top_p=void 0,M.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):((i==null?void 0:i.reasoningEffort)!=null&&M.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),(i==null?void 0:i.reasoningSummary)!=null&&M.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),(i==null?void 0:i.serviceTier)==="flex"&&!X.supportsFlexProcessing&&(M.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete W.service_tier),(i==null?void 0:i.serviceTier)==="priority"&&!X.supportsPriorityProcessing&&(M.push({type:"unsupported",feature:"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 W.service_tier);const{tools:ee,toolChoice:H,toolWarnings:le}=await ga({tools:T,toolChoice:w});return{webSearchToolName:F,args:{...W,tools:ee,tool_choice:H},warnings:[...M,...le],store:V,toolNameMapping:ie,providerOptionsName:q}}async doGenerate(o){var l,s,p,c,m,u,d,b,_,T,w,y,g,k,C,f,L,$,M,X,q,i,A,ie,h,K,N,S,G,E,I;const{args:F,warnings:V,webSearchToolName:W,toolNameMapping:ee,providerOptionsName:H}=await this.getArgs(o),le=this.config.url({path:"/responses",modelId:this.modelId}),R=xt(o.prompt),{responseHeaders:re,value:z,rawValue:te}=await fe({url:le,headers:ge(this.config.headers(),o.headers),body:F,failedResponseHandler:ke,successfulResponseHandler:be(ha),abortSignal:o.abortSignal,fetch:this.config.fetch});if(z.error)throw new Mt({message:z.error.message,url:le,requestBodyValues:F,statusCode:400,responseHeaders:re,responseBody:te,isRetryable:!1});const j=[],J=[];let U=!1;for(const O of z.output)switch(O.type){case"reasoning":{O.summary.length===0&&O.summary.push({type:"summary_text",text:""});for(const Z of O.summary)j.push({type:"reasoning",text:Z.text,providerMetadata:{[H]:{itemId:O.id,reasoningEncryptedContent:(l=O.encrypted_content)!=null?l:null}}});break}case"image_generation_call":{j.push({type:"tool-call",toolCallId:O.id,toolName:ee.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),j.push({type:"tool-result",toolCallId:O.id,toolName:ee.toCustomToolName("image_generation"),result:{result:O.result}});break}case"local_shell_call":{j.push({type:"tool-call",toolCallId:O.call_id,toolName:ee.toCustomToolName("local_shell"),input:JSON.stringify({action:O.action}),providerMetadata:{[H]:{itemId:O.id}}});break}case"shell_call":{j.push({type:"tool-call",toolCallId:O.call_id,toolName:ee.toCustomToolName("shell"),input:JSON.stringify({action:{commands:O.action.commands}}),providerMetadata:{[H]:{itemId:O.id}}});break}case"message":{for(const Z of O.content){(p=(s=o.providerOptions)==null?void 0:s[H])!=null&&p.logprobs&&Z.logprobs&&J.push(Z.logprobs);const he={itemId:O.id,...Z.annotations.length>0&&{annotations:Z.annotations}};j.push({type:"text",text:Z.text,providerMetadata:{[H]:he}});for(const se of Z.annotations)se.type==="url_citation"?j.push({type:"source",sourceType:"url",id:(u=(m=(c=this.config).generateId)==null?void 0:m.call(c))!=null?u:pe(),url:se.url,title:se.title}):se.type==="file_citation"?j.push({type:"source",sourceType:"document",id:(_=(b=(d=this.config).generateId)==null?void 0:b.call(d))!=null?_:pe(),mediaType:"text/plain",title:(w=(T=se.quote)!=null?T:se.filename)!=null?w:"Document",filename:(y=se.filename)!=null?y:se.file_id,...se.file_id?{providerMetadata:{[H]:{fileId:se.file_id}}}:{}}):se.type==="container_file_citation"?j.push({type:"source",sourceType:"document",id:(C=(k=(g=this.config).generateId)==null?void 0:k.call(g))!=null?C:pe(),mediaType:"text/plain",title:(L=(f=se.filename)!=null?f:se.file_id)!=null?L:"Document",filename:($=se.filename)!=null?$:se.file_id,providerMetadata:{[H]:{fileId:se.file_id,containerId:se.container_id,...se.index!=null?{index:se.index}:{}}}}):se.type==="file_path"&&j.push({type:"source",sourceType:"document",id:(q=(X=(M=this.config).generateId)==null?void 0:X.call(M))!=null?q:pe(),mediaType:"application/octet-stream",title:se.file_id,filename:se.file_id,providerMetadata:{[H]:{fileId:se.file_id,...se.index!=null?{index:se.index}:{}}}})}break}case"function_call":{U=!0,j.push({type:"tool-call",toolCallId:O.call_id,toolName:O.name,input:O.arguments,providerMetadata:{[H]:{itemId:O.id}}});break}case"web_search_call":{j.push({type:"tool-call",toolCallId:O.id,toolName:ee.toCustomToolName(W??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),j.push({type:"tool-result",toolCallId:O.id,toolName:ee.toCustomToolName(W??"web_search"),result:kt(O.action)});break}case"mcp_call":{const Z=O.approval_request_id!=null&&(i=R[O.approval_request_id])!=null?i:O.id,he=`mcp.${O.name}`;j.push({type:"tool-call",toolCallId:Z,toolName:he,input:O.arguments,providerExecuted:!0,dynamic:!0}),j.push({type:"tool-result",toolCallId:Z,toolName:he,result:{type:"call",serverLabel:O.server_label,name:O.name,arguments:O.arguments,...O.output!=null?{output:O.output}:{},...O.error!=null?{error:O.error}:{}},providerMetadata:{[H]:{itemId:O.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const Z=(A=O.approval_request_id)!=null?A:O.id,he=(K=(h=(ie=this.config).generateId)==null?void 0:h.call(ie))!=null?K:pe(),se=`mcp.${O.name}`;j.push({type:"tool-call",toolCallId:he,toolName:se,input:O.arguments,providerExecuted:!0,dynamic:!0}),j.push({type:"tool-approval-request",approvalId:Z,toolCallId:he});break}case"computer_call":{j.push({type:"tool-call",toolCallId:O.id,toolName:ee.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),j.push({type:"tool-result",toolCallId:O.id,toolName:ee.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:O.status||"completed"}});break}case"file_search_call":{j.push({type:"tool-call",toolCallId:O.id,toolName:ee.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),j.push({type:"tool-result",toolCallId:O.id,toolName:ee.toCustomToolName("file_search"),result:{queries:O.queries,results:(S=(N=O.results)==null?void 0:N.map(Z=>({attributes:Z.attributes,fileId:Z.file_id,filename:Z.filename,score:Z.score,text:Z.text})))!=null?S:null}});break}case"code_interpreter_call":{j.push({type:"tool-call",toolCallId:O.id,toolName:ee.toCustomToolName("code_interpreter"),input:JSON.stringify({code:O.code,containerId:O.container_id}),providerExecuted:!0}),j.push({type:"tool-result",toolCallId:O.id,toolName:ee.toCustomToolName("code_interpreter"),result:{outputs:O.outputs}});break}case"apply_patch_call":{j.push({type:"tool-call",toolCallId:O.call_id,toolName:ee.toCustomToolName("apply_patch"),input:JSON.stringify({callId:O.call_id,operation:O.operation}),providerMetadata:{[H]:{itemId:O.id}}});break}}const v={[H]:{responseId:z.id}};J.length>0&&(v[H].logprobs=J),typeof z.service_tier=="string"&&(v[H].serviceTier=z.service_tier);const oe=z.usage;return{content:j,finishReason:{unified:vt({finishReason:(G=z.incomplete_details)==null?void 0:G.reason,hasFunctionCall:U}),raw:(I=(E=z.incomplete_details)==null?void 0:E.reason)!=null?I:void 0},usage:ft(oe),request:{body:F},response:{id:z.id,timestamp:new Date(z.created_at*1e3),modelId:z.model,headers:re,body:te},providerMetadata:v,warnings:V}}async doStream(o){const{args:l,warnings:s,webSearchToolName:p,toolNameMapping:c,store:m,providerOptionsName:u}=await this.getArgs(o),{responseHeaders:d,value:b}=await fe({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:ge(this.config.headers(),o.headers),body:{...l,stream:!0},failedResponseHandler:ke,successfulResponseHandler:Oe(ma),abortSignal:o.abortSignal,fetch:this.config.fetch}),_=this,T=xt(o.prompt),w=new Map;let y={unified:"other",raw:void 0},g;const k=[];let C=null;const f={},L=[];let $=!1;const M={};let X;return{stream:b.pipeThrough(new TransformStream({start(q){q.enqueue({type:"stream-start",warnings:s})},transform(q,i){var A,ie,h,K,N,S,G,E,I,F,V,W,ee,H,le,R,re,z,te,j,J,U,v,oe,O,Z,he,se,Ne,Ke,ze,Ye,Xe,Qe,Ze,et;if(o.includeRawChunks&&i.enqueue({type:"raw",rawValue:q.rawValue}),!q.success){y={unified:"error",raw:void 0},i.enqueue({type:"error",error:q.error});return}const r=q.value;if(wt(r)){if(r.item.type==="function_call")f[r.output_index]={toolName:r.item.name,toolCallId:r.item.call_id},i.enqueue({type:"tool-input-start",id:r.item.call_id,toolName:r.item.name});else if(r.item.type==="web_search_call")f[r.output_index]={toolName:c.toCustomToolName(p??"web_search"),toolCallId:r.item.id},i.enqueue({type:"tool-input-start",id:r.item.id,toolName:c.toCustomToolName(p??"web_search"),providerExecuted:!0}),i.enqueue({type:"tool-input-end",id:r.item.id}),i.enqueue({type:"tool-call",toolCallId:r.item.id,toolName:c.toCustomToolName(p??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(r.item.type==="computer_call")f[r.output_index]={toolName:c.toCustomToolName("computer_use"),toolCallId:r.item.id},i.enqueue({type:"tool-input-start",id:r.item.id,toolName:c.toCustomToolName("computer_use"),providerExecuted:!0});else if(r.item.type==="code_interpreter_call")f[r.output_index]={toolName:c.toCustomToolName("code_interpreter"),toolCallId:r.item.id,codeInterpreter:{containerId:r.item.container_id}},i.enqueue({type:"tool-input-start",id:r.item.id,toolName:c.toCustomToolName("code_interpreter"),providerExecuted:!0}),i.enqueue({type:"tool-input-delta",id:r.item.id,delta:`{"containerId":"${r.item.container_id}","code":"`});else if(r.item.type==="file_search_call")i.enqueue({type:"tool-call",toolCallId:r.item.id,toolName:c.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(r.item.type==="image_generation_call")i.enqueue({type:"tool-call",toolCallId:r.item.id,toolName:c.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(!(r.item.type==="mcp_call"||r.item.type==="mcp_list_tools"||r.item.type==="mcp_approval_request"))if(r.item.type==="apply_patch_call"){const{call_id:B,operation:de}=r.item;if(f[r.output_index]={toolName:c.toCustomToolName("apply_patch"),toolCallId:B,applyPatch:{hasDiff:de.type==="delete_file",endEmitted:de.type==="delete_file"}},i.enqueue({type:"tool-input-start",id:B,toolName:c.toCustomToolName("apply_patch")}),de.type==="delete_file"){const xe=JSON.stringify({callId:B,operation:de});i.enqueue({type:"tool-input-delta",id:B,delta:xe}),i.enqueue({type:"tool-input-end",id:B})}else i.enqueue({type:"tool-input-delta",id:B,delta:`{"callId":"${Te(B)}","operation":{"type":"${Te(de.type)}","path":"${Te(de.path)}","diff":"`})}else r.item.type==="shell_call"?f[r.output_index]={toolName:c.toCustomToolName("shell"),toolCallId:r.item.call_id}:r.item.type==="message"?(L.splice(0,L.length),i.enqueue({type:"text-start",id:r.item.id,providerMetadata:{[u]:{itemId:r.item.id}}})):wt(r)&&r.item.type==="reasoning"&&(M[r.item.id]={encryptedContent:r.item.encrypted_content,summaryParts:{0:"active"}},i.enqueue({type:"reasoning-start",id:`${r.item.id}:0`,providerMetadata:{[u]:{itemId:r.item.id,reasoningEncryptedContent:(A=r.item.encrypted_content)!=null?A:null}}}))}else if(va(r)){if(r.item.type==="message")i.enqueue({type:"text-end",id:r.item.id,providerMetadata:{[u]:{itemId:r.item.id,...L.length>0&&{annotations:L}}}});else if(r.item.type==="function_call")f[r.output_index]=void 0,$=!0,i.enqueue({type:"tool-input-end",id:r.item.call_id}),i.enqueue({type:"tool-call",toolCallId:r.item.call_id,toolName:r.item.name,input:r.item.arguments,providerMetadata:{[u]:{itemId:r.item.id}}});else if(r.item.type==="web_search_call")f[r.output_index]=void 0,i.enqueue({type:"tool-result",toolCallId:r.item.id,toolName:c.toCustomToolName(p??"web_search"),result:kt(r.item.action)});else if(r.item.type==="computer_call")f[r.output_index]=void 0,i.enqueue({type:"tool-input-end",id:r.item.id}),i.enqueue({type:"tool-call",toolCallId:r.item.id,toolName:c.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),i.enqueue({type:"tool-result",toolCallId:r.item.id,toolName:c.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:r.item.status||"completed"}});else if(r.item.type==="file_search_call")f[r.output_index]=void 0,i.enqueue({type:"tool-result",toolCallId:r.item.id,toolName:c.toCustomToolName("file_search"),result:{queries:r.item.queries,results:(h=(ie=r.item.results)==null?void 0:ie.map(B=>({attributes:B.attributes,fileId:B.file_id,filename:B.filename,score:B.score,text:B.text})))!=null?h:null}});else if(r.item.type==="code_interpreter_call")f[r.output_index]=void 0,i.enqueue({type:"tool-result",toolCallId:r.item.id,toolName:c.toCustomToolName("code_interpreter"),result:{outputs:r.item.outputs}});else if(r.item.type==="image_generation_call")i.enqueue({type:"tool-result",toolCallId:r.item.id,toolName:c.toCustomToolName("image_generation"),result:{result:r.item.result}});else if(r.item.type==="mcp_call"){f[r.output_index]=void 0;const B=(K=r.item.approval_request_id)!=null?K:void 0,de=B!=null&&(S=(N=w.get(B))!=null?N:T[B])!=null?S:r.item.id,xe=`mcp.${r.item.name}`;i.enqueue({type:"tool-call",toolCallId:de,toolName:xe,input:r.item.arguments,providerExecuted:!0,dynamic:!0}),i.enqueue({type:"tool-result",toolCallId:de,toolName:xe,result:{type:"call",serverLabel:r.item.server_label,name:r.item.name,arguments:r.item.arguments,...r.item.output!=null?{output:r.item.output}:{},...r.item.error!=null?{error:r.item.error}:{}},providerMetadata:{[u]:{itemId:r.item.id}}})}else if(r.item.type==="mcp_list_tools")f[r.output_index]=void 0;else if(r.item.type==="apply_patch_call"){const B=f[r.output_index];B!=null&&B.applyPatch&&!B.applyPatch.endEmitted&&r.item.operation.type!=="delete_file"&&(B.applyPatch.hasDiff||i.enqueue({type:"tool-input-delta",id:B.toolCallId,delta:Te(r.item.operation.diff)}),i.enqueue({type:"tool-input-delta",id:B.toolCallId,delta:'"}}'}),i.enqueue({type:"tool-input-end",id:B.toolCallId}),B.applyPatch.endEmitted=!0),B&&r.item.status==="completed"&&i.enqueue({type:"tool-call",toolCallId:B.toolCallId,toolName:c.toCustomToolName("apply_patch"),input:JSON.stringify({callId:r.item.call_id,operation:r.item.operation}),providerMetadata:{[u]:{itemId:r.item.id}}}),f[r.output_index]=void 0}else if(r.item.type==="mcp_approval_request"){f[r.output_index]=void 0;const B=(I=(E=(G=_.config).generateId)==null?void 0:E.call(G))!=null?I:pe(),de=(F=r.item.approval_request_id)!=null?F:r.item.id;w.set(de,B);const xe=`mcp.${r.item.name}`;i.enqueue({type:"tool-call",toolCallId:B,toolName:xe,input:r.item.arguments,providerExecuted:!0,dynamic:!0}),i.enqueue({type:"tool-approval-request",approvalId:de,toolCallId:B})}else if(r.item.type==="local_shell_call")f[r.output_index]=void 0,i.enqueue({type:"tool-call",toolCallId:r.item.call_id,toolName:c.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:r.item.action.command,timeoutMs:r.item.action.timeout_ms,user:r.item.action.user,workingDirectory:r.item.action.working_directory,env:r.item.action.env}}),providerMetadata:{[u]:{itemId:r.item.id}}});else if(r.item.type==="shell_call")f[r.output_index]=void 0,i.enqueue({type:"tool-call",toolCallId:r.item.call_id,toolName:c.toCustomToolName("shell"),input:JSON.stringify({action:{commands:r.item.action.commands}}),providerMetadata:{[u]:{itemId:r.item.id}}});else if(r.item.type==="reasoning"){const B=M[r.item.id],de=Object.entries(B.summaryParts).filter(([xe,tt])=>tt==="active"||tt==="can-conclude").map(([xe])=>xe);for(const xe of de)i.enqueue({type:"reasoning-end",id:`${r.item.id}:${xe}`,providerMetadata:{[u]:{itemId:r.item.id,reasoningEncryptedContent:(V=r.item.encrypted_content)!=null?V:null}}});delete M[r.item.id]}}else if(wa(r)){const B=f[r.output_index];B!=null&&i.enqueue({type:"tool-input-delta",id:B.toolCallId,delta:r.delta})}else if(Ta(r)){const B=f[r.output_index];B!=null&&B.applyPatch&&(i.enqueue({type:"tool-input-delta",id:B.toolCallId,delta:Te(r.delta)}),B.applyPatch.hasDiff=!0)}else if(Sa(r)){const B=f[r.output_index];B!=null&&B.applyPatch&&!B.applyPatch.endEmitted&&(B.applyPatch.hasDiff||(i.enqueue({type:"tool-input-delta",id:B.toolCallId,delta:Te(r.diff)}),B.applyPatch.hasDiff=!0),i.enqueue({type:"tool-input-delta",id:B.toolCallId,delta:'"}}'}),i.enqueue({type:"tool-input-end",id:B.toolCallId}),B.applyPatch.endEmitted=!0)}else if(ka(r))i.enqueue({type:"tool-result",toolCallId:r.item_id,toolName:c.toCustomToolName("image_generation"),result:{result:r.partial_image_b64},preliminary:!0});else if(Ca(r)){const B=f[r.output_index];B!=null&&i.enqueue({type:"tool-input-delta",id:B.toolCallId,delta:Te(r.delta)})}else if(Ia(r)){const B=f[r.output_index];B!=null&&(i.enqueue({type:"tool-input-delta",id:B.toolCallId,delta:'"}'}),i.enqueue({type:"tool-input-end",id:B.toolCallId}),i.enqueue({type:"tool-call",toolCallId:B.toolCallId,toolName:c.toCustomToolName("code_interpreter"),input:JSON.stringify({code:r.code,containerId:B.codeInterpreter.containerId}),providerExecuted:!0}))}else if(xa(r))C=r.response.id,i.enqueue({type:"response-metadata",id:r.response.id,timestamp:new Date(r.response.created_at*1e3),modelId:r.response.model});else if(ya(r))i.enqueue({type:"text-delta",id:r.item_id,delta:r.delta}),(ee=(W=o.providerOptions)==null?void 0:W[u])!=null&&ee.logprobs&&r.logprobs&&k.push(r.logprobs);else if(r.type==="response.reasoning_summary_part.added"){if(r.summary_index>0){const B=M[r.item_id];B.summaryParts[r.summary_index]="active";for(const de of Object.keys(B.summaryParts))B.summaryParts[de]==="can-conclude"&&(i.enqueue({type:"reasoning-end",id:`${r.item_id}:${de}`,providerMetadata:{[u]:{itemId:r.item_id}}}),B.summaryParts[de]="concluded");i.enqueue({type:"reasoning-start",id:`${r.item_id}:${r.summary_index}`,providerMetadata:{[u]:{itemId:r.item_id,reasoningEncryptedContent:(le=(H=M[r.item_id])==null?void 0:H.encryptedContent)!=null?le:null}}})}}else r.type==="response.reasoning_summary_text.delta"?i.enqueue({type:"reasoning-delta",id:`${r.item_id}:${r.summary_index}`,delta:r.delta,providerMetadata:{[u]:{itemId:r.item_id}}}):r.type==="response.reasoning_summary_part.done"?m?(i.enqueue({type:"reasoning-end",id:`${r.item_id}:${r.summary_index}`,providerMetadata:{[u]:{itemId:r.item_id}}}),M[r.item_id].summaryParts[r.summary_index]="concluded"):M[r.item_id].summaryParts[r.summary_index]="can-conclude":ba(r)?(y={unified:vt({finishReason:(R=r.response.incomplete_details)==null?void 0:R.reason,hasFunctionCall:$}),raw:(z=(re=r.response.incomplete_details)==null?void 0:re.reason)!=null?z:void 0},g=r.response.usage,typeof r.response.service_tier=="string"&&(X=r.response.service_tier)):Na(r)?(L.push(r.annotation),r.annotation.type==="url_citation"?i.enqueue({type:"source",sourceType:"url",id:(J=(j=(te=_.config).generateId)==null?void 0:j.call(te))!=null?J:pe(),url:r.annotation.url,title:r.annotation.title}):r.annotation.type==="file_citation"?i.enqueue({type:"source",sourceType:"document",id:(oe=(v=(U=_.config).generateId)==null?void 0:v.call(U))!=null?oe:pe(),mediaType:"text/plain",title:(Z=(O=r.annotation.quote)!=null?O:r.annotation.filename)!=null?Z:"Document",filename:(he=r.annotation.filename)!=null?he:r.annotation.file_id,...r.annotation.file_id?{providerMetadata:{[u]:{fileId:r.annotation.file_id}}}:{}}):r.annotation.type==="container_file_citation"?i.enqueue({type:"source",sourceType:"document",id:(Ke=(Ne=(se=_.config).generateId)==null?void 0:Ne.call(se))!=null?Ke:pe(),mediaType:"text/plain",title:(Ye=(ze=r.annotation.filename)!=null?ze:r.annotation.file_id)!=null?Ye:"Document",filename:(Xe=r.annotation.filename)!=null?Xe:r.annotation.file_id,providerMetadata:{[u]:{fileId:r.annotation.file_id,containerId:r.annotation.container_id,...r.annotation.index!=null?{index:r.annotation.index}:{}}}}):r.annotation.type==="file_path"&&i.enqueue({type:"source",sourceType:"document",id:(et=(Ze=(Qe=_.config).generateId)==null?void 0:Ze.call(Qe))!=null?et:pe(),mediaType:"application/octet-stream",title:r.annotation.file_id,filename:r.annotation.file_id,providerMetadata:{[u]:{fileId:r.annotation.file_id,...r.annotation.index!=null?{index:r.annotation.index}:{}}}})):Ra(r)&&i.enqueue({type:"error",error:r})},flush(q){const i={[u]:{responseId:C}};k.length>0&&(i[u].logprobs=k),X!==void 0&&(i[u].serviceTier=X),q.enqueue({type:"finish",finishReason:y,usage:ft(g),providerMetadata:i})}})),request:{body:l},response:{headers:d}}}};function ya(o){return o.type==="response.output_text.delta"}function va(o){return o.type==="response.output_item.done"}function ba(o){return o.type==="response.completed"||o.type==="response.incomplete"}function xa(o){return o.type==="response.created"}function wa(o){return o.type==="response.function_call_arguments.delta"}function ka(o){return o.type==="response.image_generation_call.partial_image"}function Ca(o){return o.type==="response.code_interpreter_call_code.delta"}function Ia(o){return o.type==="response.code_interpreter_call_code.done"}function Ta(o){return o.type==="response.apply_patch_call_operation_diff.delta"}function Sa(o){return o.type==="response.apply_patch_call_operation_diff.done"}function wt(o){return o.type==="response.output_item.added"}function Na(o){return o.type==="response.output_text.annotation.added"}function Ra(o){return o.type==="error"}function kt(o){var l;switch(o.type){case"search":return{action:{type:"search",query:(l=o.query)!=null?l:void 0},...o.sources!=null&&{sources:o.sources}};case"open_page":return{action:{type:"openPage",url:o.url}};case"find_in_page":return{action:{type:"findInPage",url:o.url,pattern:o.pattern}}}}function Te(o){return JSON.stringify(o).slice(1,-1)}var Oa=P(()=>D(t({instructions:e().nullish(),speed:a().min(.25).max(4).default(1).nullish()}))),Ea=class{constructor(o,l){this.modelId=o,this.config=l,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({text:o,voice:l="alloy",outputFormat:s="mp3",speed:p,instructions:c,language:m,providerOptions:u}){const d=[],b=await me({provider:"openai",providerOptions:u,schema:Oa}),_={model:this.modelId,input:o,voice:l,response_format:"mp3",speed:p,instructions:c};if(s&&(["mp3","opus","aac","flac","wav","pcm"].includes(s)?_.response_format=s:d.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${s}. Using mp3 instead.`})),b){const T={};for(const w in T){const y=T[w];y!==void 0&&(_[w]=y)}}return m&&d.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${m}" was ignored.`}),{requestBody:_,warnings:d}}async doGenerate(o){var l,s,p;const c=(p=(s=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:s.call(l))!=null?p:new Date,{requestBody:m,warnings:u}=await this.getArgs(o),{value:d,responseHeaders:b,rawValue:_}=await fe({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:ge(this.config.headers(),o.headers),body:m,failedResponseHandler:ke,successfulResponseHandler:so(),abortSignal:o.abortSignal,fetch:this.config.fetch});return{audio:d,warnings:u,request:{body:JSON.stringify(m)},response:{timestamp:c,modelId:this.modelId,headers:b,body:_}}}},Ma=P(()=>D(t({text:e(),language:e().nullish(),duration:a().nullish(),words:x(t({word:e(),start:a(),end:a()})).nullish(),segments:x(t({id:a(),seek:a(),start:a(),end:a(),text:e(),tokens:x(a()),temperature:a(),avg_logprob:a(),compression_ratio:a(),no_speech_prob:a()})).nullish()}))),qa=P(()=>D(t({include:x(e()).optional(),language:e().optional(),prompt:e().optional(),temperature:a().min(0).max(1).default(0).optional(),timestampGranularities:x(Y(["word","segment"])).default(["segment"]).optional()}))),Ct={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"},Aa=class{constructor(o,l){this.modelId=o,this.config=l,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({audio:o,mediaType:l,providerOptions:s}){const p=[],c=await me({provider:"openai",providerOptions:s,schema:qa}),m=new FormData,u=o instanceof Uint8Array?new Blob([o]):new Blob([We(o)]);m.append("model",this.modelId);const d=lo(l);if(m.append("file",new File([u],"audio",{type:l}),`audio.${d}`),c){const b={include:c.include,language:c.language,prompt:c.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:c.temperature,timestamp_granularities:c.timestampGranularities};for(const[_,T]of Object.entries(b))if(T!=null)if(Array.isArray(T))for(const w of T)m.append(`${_}[]`,String(w));else m.append(_,String(T))}return{formData:m,warnings:p}}async doGenerate(o){var l,s,p,c,m,u,d,b;const _=(p=(s=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:s.call(l))!=null?p:new Date,{formData:T,warnings:w}=await this.getArgs(o),{value:y,responseHeaders:g,rawValue:k}=await Pt({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:ge(this.config.headers(),o.headers),formData:T,failedResponseHandler:ke,successfulResponseHandler:be(Ma),abortSignal:o.abortSignal,fetch:this.config.fetch}),C=y.language!=null&&y.language in Ct?Ct[y.language]:void 0;return{text:y.text,segments:(d=(u=(c=y.segments)==null?void 0:c.map(f=>({text:f.text,startSecond:f.start,endSecond:f.end})))!=null?u:(m=y.words)==null?void 0:m.map(f=>({text:f.word,startSecond:f.start,endSecond:f.end})))!=null?d:[],language:C,durationInSeconds:(b=y.duration)!=null?b:void 0,warnings:w,response:{timestamp:_,modelId:this.modelId,headers:g,body:k}}}},$a="3.0.7";function Pa(o={}){var l,s;const p=(l=je(Ot({settingValue:o.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?l:"https://api.openai.com/v1",c=(s=o.name)!=null?s:"openai",m=()=>Ge({Authorization:`Bearer ${Ve({apiKey:o.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":o.organization,"OpenAI-Project":o.project,...o.headers},`ai-sdk/openai/${$a}`),u=C=>new bn(C,{provider:`${c}.chat`,url:({path:f})=>`${p}${f}`,headers:m,fetch:o.fetch}),d=C=>new Cn(C,{provider:`${c}.completion`,url:({path:f})=>`${p}${f}`,headers:m,fetch:o.fetch}),b=C=>new Sn(C,{provider:`${c}.embedding`,url:({path:f})=>`${p}${f}`,headers:m,fetch:o.fetch}),_=C=>new En(C,{provider:`${c}.image`,url:({path:f})=>`${p}${f}`,headers:m,fetch:o.fetch}),T=C=>new Aa(C,{provider:`${c}.transcription`,url:({path:f})=>`${p}${f}`,headers:m,fetch:o.fetch}),w=C=>new Ea(C,{provider:`${c}.speech`,url:({path:f})=>`${p}${f}`,headers:m,fetch:o.fetch}),y=C=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return g(C)},g=C=>new fa(C,{provider:`${c}.responses`,url:({path:f})=>`${p}${f}`,headers:m,fetch:o.fetch,fileIdPrefixes:["file-"]}),k=function(C){return y(C)};return k.specificationVersion="v3",k.languageModel=y,k.chat=u,k.completion=d,k.responses=g,k.embedding=b,k.embeddingModel=b,k.textEmbedding=b,k.textEmbeddingModel=b,k.image=_,k.imageModel=_,k.transcription=T,k.transcriptionModel=T,k.speech=w,k.speechModel=w,k.tools=ca,k}var di=Pa(),Da="3.0.6",Ua=P(()=>D(t({error:t({code:a().nullable(),message:e(),status:e()})}))),Re=Be({errorSchema:Ua,errorToMessage:o=>o.error.message}),La=P(()=>D(t({outputDimensionality:a().optional(),taskType:Y(["SEMANTIC_SIMILARITY","CLASSIFICATION","CLUSTERING","RETRIEVAL_DOCUMENT","RETRIEVAL_QUERY","QUESTION_ANSWERING","FACT_VERIFICATION","CODE_RETRIEVAL_QUERY"]).optional()}))),Ha=class{constructor(o,l){this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=o,this.config=l}get provider(){return this.config.provider}async doEmbed({values:o,headers:l,abortSignal:s,providerOptions:p}){const c=await me({provider:"google",providerOptions:p,schema:La});if(o.length>this.maxEmbeddingsPerCall)throw new $t({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:o});const m=ge(await Se(this.config.headers),l);if(o.length===1){const{responseHeaders:_,value:T,rawValue:w}=await fe({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:m,body:{model:`models/${this.modelId}`,content:{parts:[{text:o[0]}]},outputDimensionality:c==null?void 0:c.outputDimensionality,taskType:c==null?void 0:c.taskType},failedResponseHandler:Re,successfulResponseHandler:be(Ga),abortSignal:s,fetch:this.config.fetch});return{warnings:[],embeddings:[T.embedding.values],usage:void 0,response:{headers:_,body:w}}}const{responseHeaders:u,value:d,rawValue:b}=await fe({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:m,body:{requests:o.map(_=>({model:`models/${this.modelId}`,content:{role:"user",parts:[{text:_}]},outputDimensionality:c==null?void 0:c.outputDimensionality,taskType:c==null?void 0:c.taskType}))},failedResponseHandler:Re,successfulResponseHandler:be(ja),abortSignal:s,fetch:this.config.fetch});return{warnings:[],embeddings:d.embeddings.map(_=>_.values),usage:void 0,response:{headers:u,body:b}}}},ja=P(()=>D(t({embeddings:x(t({values:x(a())}))}))),Ga=P(()=>D(t({embedding:t({values:x(a())})})));function It(o){var l,s,p,c;if(o==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const m=(l=o.promptTokenCount)!=null?l:0,u=(s=o.candidatesTokenCount)!=null?s:0,d=(p=o.cachedContentTokenCount)!=null?p:0,b=(c=o.thoughtsTokenCount)!=null?c:0;return{inputTokens:{total:m,noCache:m-d,cacheRead:d,cacheWrite:void 0},outputTokens:{total:u+b,text:u,reasoning:b},raw:o}}function Ce(o,l=!0){if(o==null)return;if(Va(o))return l?void 0:typeof o=="object"&&o.description?{type:"object",description:o.description}:{type:"object"};if(typeof o=="boolean")return{type:"boolean",properties:{}};const{type:s,description:p,required:c,properties:m,items:u,allOf:d,anyOf:b,oneOf:_,format:T,const:w,minLength:y,enum:g}=o,k={};if(p&&(k.description=p),c&&(k.required=c),T&&(k.format=T),w!==void 0&&(k.enum=[w]),s)if(Array.isArray(s)){const C=s.includes("null"),f=s.filter(L=>L!=="null");f.length===0?k.type="null":(k.anyOf=f.map(L=>({type:L})),C&&(k.nullable=!0))}else k.type=s;if(g!==void 0&&(k.enum=g),m!=null&&(k.properties=Object.entries(m).reduce((C,[f,L])=>(C[f]=Ce(L,!1),C),{})),u&&(k.items=Array.isArray(u)?u.map(C=>Ce(C,!1)):Ce(u,!1)),d&&(k.allOf=d.map(C=>Ce(C,!1))),b)if(b.some(C=>typeof C=="object"&&(C==null?void 0:C.type)==="null")){const C=b.filter(f=>!(typeof f=="object"&&(f==null?void 0:f.type)==="null"));if(C.length===1){const f=Ce(C[0],!1);typeof f=="object"&&(k.nullable=!0,Object.assign(k,f))}else k.anyOf=C.map(f=>Ce(f,!1)),k.nullable=!0}else k.anyOf=b.map(C=>Ce(C,!1));return _&&(k.oneOf=_.map(C=>Ce(C,!1))),y!==void 0&&(k.minLength=y),k}function Va(o){return o!=null&&typeof o=="object"&&o.type==="object"&&(o.properties==null||Object.keys(o.properties).length===0)&&!o.additionalProperties}function Ba(o,l){var s,p,c;const m=[],u=[];let d=!0;const b=(s=l==null?void 0:l.isGemmaModel)!=null?s:!1,_=(p=l==null?void 0:l.providerOptionsName)!=null?p:"google";for(const{role:T,content:w}of o)switch(T){case"system":{if(!d)throw new _e({functionality:"system messages are only supported at the beginning of the conversation"});m.push({text:w});break}case"user":{d=!1;const y=[];for(const g of w)switch(g.type){case"text":{y.push({text:g.text});break}case"file":{const k=g.mediaType==="image/*"?"image/jpeg":g.mediaType;y.push(g.data instanceof URL?{fileData:{mimeType:k,fileUri:g.data.toString()}}:{inlineData:{mimeType:k,data:Ie(g.data)}});break}}u.push({role:"user",parts:y});break}case"assistant":{d=!1,u.push({role:"model",parts:w.map(y=>{var g;const k=(g=y.providerOptions)==null?void 0:g[_],C=(k==null?void 0:k.thoughtSignature)!=null?String(k.thoughtSignature):void 0;switch(y.type){case"text":return y.text.length===0?void 0:{text:y.text,thoughtSignature:C};case"reasoning":return y.text.length===0?void 0:{text:y.text,thought:!0,thoughtSignature:C};case"file":{if(y.data instanceof URL)throw new _e({functionality:"File data URLs in assistant messages are not supported"});return{inlineData:{mimeType:y.mediaType,data:Ie(y.data)},thoughtSignature:C}}case"tool-call":return{functionCall:{name:y.toolName,args:y.input},thoughtSignature:C}}}).filter(y=>y!==void 0)});break}case"tool":{d=!1;const y=[];for(const g of w){if(g.type==="tool-approval-response")continue;const k=g.output;if(k.type==="content")for(const C of k.value)switch(C.type){case"text":y.push({functionResponse:{name:g.toolName,response:{name:g.toolName,content:C.text}}});break;case"image-data":y.push({inlineData:{mimeType:C.mediaType,data:C.data}},{text:"Tool executed successfully and returned this image as a response"});break;default:y.push({text:JSON.stringify(C)});break}else y.push({functionResponse:{name:g.toolName,response:{name:g.toolName,content:k.type==="execution-denied"?(c=k.reason)!=null?c:"Tool execution denied.":k.value}}})}u.push({role:"user",parts:y});break}}if(b&&m.length>0&&u.length>0&&u[0].role==="user"){const T=m.map(w=>w.text).join(`
12
-
13
- `);u[0].parts.unshift({text:T+`
14
-
15
- `})}return{systemInstruction:m.length>0&&!b?{parts:m}:void 0,contents:u}}function Tt(o){return o.includes("/")?o:`models/${o}`}var St=P(()=>D(t({responseModalities:x(Y(["TEXT","IMAGE"])).optional(),thinkingConfig:t({thinkingBudget:a().optional(),includeThoughts:ne().optional(),thinkingLevel:Y(["minimal","low","medium","high"]).optional()}).optional(),cachedContent:e().optional(),structuredOutputs:ne().optional(),safetySettings:x(t({category:Y(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:Y(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])})).optional(),threshold:Y(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]).optional(),audioTimestamp:ne().optional(),labels:ue(e(),e()).optional(),mediaResolution:Y(["MEDIA_RESOLUTION_UNSPECIFIED","MEDIA_RESOLUTION_LOW","MEDIA_RESOLUTION_MEDIUM","MEDIA_RESOLUTION_HIGH"]).optional(),imageConfig:t({aspectRatio:Y(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9"]).optional(),imageSize:Y(["1K","2K","4K"]).optional()}).optional(),retrievalConfig:t({latLng:t({latitude:a(),longitude:a()}).optional()}).optional()})));function Wa({tools:o,toolChoice:l,modelId:s}){var p;o=o!=null&&o.length?o:void 0;const c=[],m=["gemini-flash-latest","gemini-flash-lite-latest","gemini-pro-latest"].some(g=>g===s),u=s.includes("gemini-2")||s.includes("gemini-3")||m,d=s.includes("gemini-1.5-flash")&&!s.includes("-8b"),b=s.includes("gemini-2.5")||s.includes("gemini-3");if(o==null)return{tools:void 0,toolConfig:void 0,toolWarnings:c};const _=o.some(g=>g.type==="function"),T=o.some(g=>g.type==="provider");if(_&&T&&c.push({type:"unsupported",feature:"combination of function and provider-defined tools"}),T){const g=[];return o.filter(C=>C.type==="provider").forEach(C=>{switch(C.id){case"google.google_search":u?g.push({googleSearch:{}}):d?g.push({googleSearchRetrieval:{dynamicRetrievalConfig:{mode:C.args.mode,dynamicThreshold:C.args.dynamicThreshold}}}):g.push({googleSearchRetrieval:{}});break;case"google.enterprise_web_search":u?g.push({enterpriseWebSearch:{}}):c.push({type:"unsupported",feature:`provider-defined tool ${C.id}`,details:"Enterprise Web Search requires Gemini 2.0 or newer."});break;case"google.url_context":u?g.push({urlContext:{}}):c.push({type:"unsupported",feature:`provider-defined tool ${C.id}`,details:"The URL context tool is not supported with other Gemini models than Gemini 2."});break;case"google.code_execution":u?g.push({codeExecution:{}}):c.push({type:"unsupported",feature:`provider-defined tool ${C.id}`,details:"The code execution tools is not supported with other Gemini models than Gemini 2."});break;case"google.file_search":b?g.push({fileSearch:{...C.args}}):c.push({type:"unsupported",feature:`provider-defined tool ${C.id}`,details:"The file search tool is only supported with Gemini 2.5 models and Gemini 3 models."});break;case"google.vertex_rag_store":u?g.push({retrieval:{vertex_rag_store:{rag_resources:{rag_corpus:C.args.ragCorpus},similarity_top_k:C.args.topK}}}):c.push({type:"unsupported",feature:`provider-defined tool ${C.id}`,details:"The RAG store tool is not supported with other Gemini models than Gemini 2."});break;case"google.google_maps":u?g.push({googleMaps:{}}):c.push({type:"unsupported",feature:`provider-defined tool ${C.id}`,details:"The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer."});break;default:c.push({type:"unsupported",feature:`provider-defined tool ${C.id}`});break}}),{tools:g.length>0?g:void 0,toolConfig:void 0,toolWarnings:c}}const w=[];for(const g of o)switch(g.type){case"function":w.push({name:g.name,description:(p=g.description)!=null?p:"",parameters:Ce(g.inputSchema)});break;default:c.push({type:"unsupported",feature:`function tool ${g.name}`});break}if(l==null)return{tools:[{functionDeclarations:w}],toolConfig:void 0,toolWarnings:c};const y=l.type;switch(y){case"auto":return{tools:[{functionDeclarations:w}],toolConfig:{functionCallingConfig:{mode:"AUTO"}},toolWarnings:c};case"none":return{tools:[{functionDeclarations:w}],toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:c};case"required":return{tools:[{functionDeclarations:w}],toolConfig:{functionCallingConfig:{mode:"ANY"}},toolWarnings:c};case"tool":return{tools:[{functionDeclarations:w}],toolConfig:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[l.toolName]}},toolWarnings:c};default:{const g=y;throw new _e({functionality:`tool choice type: ${g}`})}}}function Nt({finishReason:o,hasToolCalls:l}){switch(o){case"STOP":return l?"tool-calls":"stop";case"MAX_TOKENS":return"length";case"IMAGE_SAFETY":case"RECITATION":case"SAFETY":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":return"content-filter";case"MALFORMED_FUNCTION_CALL":return"error";case"FINISH_REASON_UNSPECIFIED":case"OTHER":default:return"other"}}var Fa=class{constructor(o,l){this.specificationVersion="v3";var s;this.modelId=o,this.config=l,this.generateId=(s=l.generateId)!=null?s:pe}get provider(){return this.config.provider}get supportedUrls(){var o,l,s;return(s=(l=(o=this.config).supportedUrls)==null?void 0:l.call(o))!=null?s:{}}async getArgs({prompt:o,maxOutputTokens:l,temperature:s,topP:p,topK:c,frequencyPenalty:m,presencePenalty:u,stopSequences:d,responseFormat:b,seed:_,tools:T,toolChoice:w,providerOptions:y}){var g;const k=[],C=this.config.provider.includes("vertex")?"vertex":"google";let f=await me({provider:C,providerOptions:y,schema:St});f==null&&C!=="google"&&(f=await me({provider:"google",providerOptions:y,schema:St})),T!=null&&T.some(A=>A.type==="provider"&&A.id==="google.vertex_rag_store")&&!this.config.provider.startsWith("google.vertex.")&&k.push({type:"other",message:`The 'vertex_rag_store' tool is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`});const L=this.modelId.toLowerCase().startsWith("gemma-"),{contents:$,systemInstruction:M}=Ba(o,{isGemmaModel:L,providerOptionsName:C}),{tools:X,toolConfig:q,toolWarnings:i}=Wa({tools:T,toolChoice:w,modelId:this.modelId});return{args:{generationConfig:{maxOutputTokens:l,temperature:s,topK:c,topP:p,frequencyPenalty:m,presencePenalty:u,stopSequences:d,seed:_,responseMimeType:(b==null?void 0:b.type)==="json"?"application/json":void 0,responseSchema:(b==null?void 0:b.type)==="json"&&b.schema!=null&&((g=f==null?void 0:f.structuredOutputs)==null||g)?Ce(b.schema):void 0,...(f==null?void 0:f.audioTimestamp)&&{audioTimestamp:f.audioTimestamp},responseModalities:f==null?void 0:f.responseModalities,thinkingConfig:f==null?void 0:f.thinkingConfig,...(f==null?void 0:f.mediaResolution)&&{mediaResolution:f.mediaResolution},...(f==null?void 0:f.imageConfig)&&{imageConfig:f.imageConfig}},contents:$,systemInstruction:L?void 0:M,safetySettings:f==null?void 0:f.safetySettings,tools:X,toolConfig:f!=null&&f.retrievalConfig?{...q,retrievalConfig:f.retrievalConfig}:q,cachedContent:f==null?void 0:f.cachedContent,labels:f==null?void 0:f.labels},warnings:[...k,...i],providerOptionsName:C}}async doGenerate(o){var l,s,p,c,m,u,d,b,_;const{args:T,warnings:w,providerOptionsName:y}=await this.getArgs(o),g=ge(await Se(this.config.headers),o.headers),{responseHeaders:k,value:C,rawValue:f}=await fe({url:`${this.config.baseURL}/${Tt(this.modelId)}:generateContent`,headers:g,body:T,failedResponseHandler:Re,successfulResponseHandler:be(Ka),abortSignal:o.abortSignal,fetch:this.config.fetch}),L=C.candidates[0],$=[],M=(s=(l=L.content)==null?void 0:l.parts)!=null?s:[],X=C.usageMetadata;let q;for(const A of M)if("executableCode"in A&&((p=A.executableCode)!=null&&p.code)){const ie=this.config.generateId();q=ie,$.push({type:"tool-call",toolCallId:ie,toolName:"code_execution",input:JSON.stringify(A.executableCode),providerExecuted:!0})}else"codeExecutionResult"in A&&A.codeExecutionResult?($.push({type:"tool-result",toolCallId:q,toolName:"code_execution",result:{outcome:A.codeExecutionResult.outcome,output:A.codeExecutionResult.output}}),q=void 0):"text"in A&&A.text!=null&&A.text.length>0?$.push({type:A.thought===!0?"reasoning":"text",text:A.text,providerMetadata:A.thoughtSignature?{[y]:{thoughtSignature:A.thoughtSignature}}:void 0}):"functionCall"in A?$.push({type:"tool-call",toolCallId:this.config.generateId(),toolName:A.functionCall.name,input:JSON.stringify(A.functionCall.args),providerMetadata:A.thoughtSignature?{[y]:{thoughtSignature:A.thoughtSignature}}:void 0}):"inlineData"in A&&$.push({type:"file",data:A.inlineData.data,mediaType:A.inlineData.mimeType,providerMetadata:A.thoughtSignature?{[y]:{thoughtSignature:A.thoughtSignature}}:void 0});const i=(c=Rt({groundingMetadata:L.groundingMetadata,generateId:this.config.generateId}))!=null?c:[];for(const A of i)$.push(A);return{content:$,finishReason:{unified:Nt({finishReason:L.finishReason,hasToolCalls:$.some(A=>A.type==="tool-call"&&!A.providerExecuted)}),raw:(m=L.finishReason)!=null?m:void 0},usage:It(X),warnings:w,providerMetadata:{[y]:{promptFeedback:(u=C.promptFeedback)!=null?u:null,groundingMetadata:(d=L.groundingMetadata)!=null?d:null,urlContextMetadata:(b=L.urlContextMetadata)!=null?b:null,safetyRatings:(_=L.safetyRatings)!=null?_:null,usageMetadata:X??null}},request:{body:T},response:{headers:k,body:f}}}async doStream(o){const{args:l,warnings:s,providerOptionsName:p}=await this.getArgs(o),c=ge(await Se(this.config.headers),o.headers),{responseHeaders:m,value:u}=await fe({url:`${this.config.baseURL}/${Tt(this.modelId)}:streamGenerateContent?alt=sse`,headers:c,body:l,failedResponseHandler:Re,successfulResponseHandler:Oe(za),abortSignal:o.abortSignal,fetch:this.config.fetch});let d={unified:"other",raw:void 0},b,_;const T=this.config.generateId;let w=!1,y=null,g=null,k=0;const C=new Set;let f;return{stream:u.pipeThrough(new TransformStream({start(L){L.enqueue({type:"stream-start",warnings:s})},transform(L,$){var M,X,q,i,A,ie,h;if(o.includeRawChunks&&$.enqueue({type:"raw",rawValue:L.rawValue}),!L.success){$.enqueue({type:"error",error:L.error});return}const K=L.value,N=K.usageMetadata;N!=null&&(b=N);const S=(M=K.candidates)==null?void 0:M[0];if(S==null)return;const G=S.content,E=Rt({groundingMetadata:S.groundingMetadata,generateId:T});if(E!=null)for(const I of E)I.sourceType==="url"&&!C.has(I.url)&&(C.add(I.url),$.enqueue(I));if(G!=null){const I=(X=G.parts)!=null?X:[];for(const V of I)if("executableCode"in V&&((q=V.executableCode)!=null&&q.code)){const W=T();f=W,$.enqueue({type:"tool-call",toolCallId:W,toolName:"code_execution",input:JSON.stringify(V.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in V&&V.codeExecutionResult){const W=f;W&&($.enqueue({type:"tool-result",toolCallId:W,toolName:"code_execution",result:{outcome:V.codeExecutionResult.outcome,output:V.codeExecutionResult.output}}),f=void 0)}else"text"in V&&V.text!=null&&V.text.length>0?V.thought===!0?(y!==null&&($.enqueue({type:"text-end",id:y}),y=null),g===null&&(g=String(k++),$.enqueue({type:"reasoning-start",id:g,providerMetadata:V.thoughtSignature?{[p]:{thoughtSignature:V.thoughtSignature}}:void 0})),$.enqueue({type:"reasoning-delta",id:g,delta:V.text,providerMetadata:V.thoughtSignature?{[p]:{thoughtSignature:V.thoughtSignature}}:void 0})):(g!==null&&($.enqueue({type:"reasoning-end",id:g}),g=null),y===null&&(y=String(k++),$.enqueue({type:"text-start",id:y,providerMetadata:V.thoughtSignature?{[p]:{thoughtSignature:V.thoughtSignature}}:void 0})),$.enqueue({type:"text-delta",id:y,delta:V.text,providerMetadata:V.thoughtSignature?{[p]:{thoughtSignature:V.thoughtSignature}}:void 0})):"inlineData"in V&&$.enqueue({type:"file",mediaType:V.inlineData.mimeType,data:V.inlineData.data});const F=Ja({parts:G.parts,generateId:T,providerOptionsName:p});if(F!=null)for(const V of F)$.enqueue({type:"tool-input-start",id:V.toolCallId,toolName:V.toolName,providerMetadata:V.providerMetadata}),$.enqueue({type:"tool-input-delta",id:V.toolCallId,delta:V.args,providerMetadata:V.providerMetadata}),$.enqueue({type:"tool-input-end",id:V.toolCallId,providerMetadata:V.providerMetadata}),$.enqueue({type:"tool-call",toolCallId:V.toolCallId,toolName:V.toolName,input:V.args,providerMetadata:V.providerMetadata}),w=!0}S.finishReason!=null&&(d={unified:Nt({finishReason:S.finishReason,hasToolCalls:w}),raw:S.finishReason},_={[p]:{promptFeedback:(i=K.promptFeedback)!=null?i:null,groundingMetadata:(A=S.groundingMetadata)!=null?A:null,urlContextMetadata:(ie=S.urlContextMetadata)!=null?ie:null,safetyRatings:(h=S.safetyRatings)!=null?h:null}},N!=null&&(_[p].usageMetadata=N))},flush(L){y!==null&&L.enqueue({type:"text-end",id:y}),g!==null&&L.enqueue({type:"reasoning-end",id:g}),L.enqueue({type:"finish",finishReason:d,usage:It(b),providerMetadata:_})}})),response:{headers:m},request:{body:l}}}};function Ja({parts:o,generateId:l,providerOptionsName:s}){const p=o==null?void 0:o.filter(c=>"functionCall"in c);return p==null||p.length===0?void 0:p.map(c=>({type:"tool-call",toolCallId:l(),toolName:c.functionCall.name,args:JSON.stringify(c.functionCall.args),providerMetadata:c.thoughtSignature?{[s]:{thoughtSignature:c.thoughtSignature}}:void 0}))}function Rt({groundingMetadata:o,generateId:l}){var s,p,c,m,u;if(!(o!=null&&o.groundingChunks))return;const d=[];for(const b of o.groundingChunks)if(b.web!=null)d.push({type:"source",sourceType:"url",id:l(),url:b.web.uri,title:(s=b.web.title)!=null?s:void 0});else if(b.retrievedContext!=null){const _=b.retrievedContext.uri,T=b.retrievedContext.fileSearchStore;if(_&&(_.startsWith("http://")||_.startsWith("https://")))d.push({type:"source",sourceType:"url",id:l(),url:_,title:(p=b.retrievedContext.title)!=null?p:void 0});else if(_){const w=(c=b.retrievedContext.title)!=null?c:"Unknown Document";let y="application/octet-stream",g;_.endsWith(".pdf")?(y="application/pdf",g=_.split("/").pop()):_.endsWith(".txt")?(y="text/plain",g=_.split("/").pop()):_.endsWith(".docx")?(y="application/vnd.openxmlformats-officedocument.wordprocessingml.document",g=_.split("/").pop()):_.endsWith(".doc")?(y="application/msword",g=_.split("/").pop()):(_.match(/\.(md|markdown)$/)&&(y="text/markdown"),g=_.split("/").pop()),d.push({type:"source",sourceType:"document",id:l(),mediaType:y,title:w,filename:g})}else if(T){const w=(m=b.retrievedContext.title)!=null?m:"Unknown Document";d.push({type:"source",sourceType:"document",id:l(),mediaType:"application/octet-stream",title:w,filename:T.split("/").pop()})}}else b.maps!=null&&b.maps.uri&&d.push({type:"source",sourceType:"url",id:l(),url:b.maps.uri,title:(u=b.maps.title)!=null?u:void 0});return d.length>0?d:void 0}var Qt=()=>t({webSearchQueries:x(e()).nullish(),retrievalQueries:x(e()).nullish(),searchEntryPoint:t({renderedContent:e()}).nullish(),groundingChunks:x(t({web:t({uri:e(),title:e().nullish()}).nullish(),retrievedContext:t({uri:e().nullish(),title:e().nullish(),text:e().nullish(),fileSearchStore:e().nullish()}).nullish(),maps:t({uri:e().nullish(),title:e().nullish(),text:e().nullish(),placeId:e().nullish()}).nullish()})).nullish(),groundingSupports:x(t({segment:t({startIndex:a().nullish(),endIndex:a().nullish(),text:e().nullish()}),segment_text:e().nullish(),groundingChunkIndices:x(a()).nullish(),supportChunkIndices:x(a()).nullish(),confidenceScores:x(a()).nullish(),confidenceScore:x(a()).nullish()})).nullish(),retrievalMetadata:Q([t({webDynamicRetrievalScore:a()}),t({})]).nullish()}),Zt=()=>t({parts:x(Q([t({functionCall:t({name:e(),args:we()}),thoughtSignature:e().nullish()}),t({inlineData:t({mimeType:e(),data:e()}),thoughtSignature:e().nullish()}),t({executableCode:t({language:e(),code:e()}).nullish(),codeExecutionResult:t({outcome:e(),output:e()}).nullish(),text:e().nullish(),thought:ne().nullish(),thoughtSignature:e().nullish()})])).nullish()}),Me=()=>t({category:e().nullish(),probability:e().nullish(),probabilityScore:a().nullish(),severity:e().nullish(),severityScore:a().nullish(),blocked:ne().nullish()}),eo=t({cachedContentTokenCount:a().nullish(),thoughtsTokenCount:a().nullish(),promptTokenCount:a().nullish(),candidatesTokenCount:a().nullish(),totalTokenCount:a().nullish(),trafficType:e().nullish()}),to=()=>t({urlMetadata:x(t({retrievedUrl:e(),urlRetrievalStatus:e()}))}),Ka=P(()=>D(t({candidates:x(t({content:Zt().nullish().or(t({}).strict()),finishReason:e().nullish(),safetyRatings:x(Me()).nullish(),groundingMetadata:Qt().nullish(),urlContextMetadata:to().nullish()})),usageMetadata:eo.nullish(),promptFeedback:t({blockReason:e().nullish(),safetyRatings:x(Me()).nullish()}).nullish()}))),za=P(()=>D(t({candidates:x(t({content:Zt().nullish(),finishReason:e().nullish(),safetyRatings:x(Me()).nullish(),groundingMetadata:Qt().nullish(),urlContextMetadata:to().nullish()})).nullish(),usageMetadata:eo.nullish(),promptFeedback:t({blockReason:e().nullish(),safetyRatings:x(Me()).nullish()}).nullish()}))),Ya=ye({id:"google.code_execution",inputSchema:t({language:e().describe("The programming language of the code."),code:e().describe("The code to be executed.")}),outputSchema:t({outcome:e().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),output:e().describe("The output from the code execution.")})}),Xa=ve({id:"google.enterprise_web_search",inputSchema:P(()=>D(t({})))}),Qa=t({fileSearchStoreNames:x(e()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),topK:a().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(),metadataFilter:e().describe("Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression.").optional()}).passthrough(),Za=P(()=>D(Qa)),ei=ve({id:"google.file_search",inputSchema:Za}),ti=ve({id:"google.google_maps",inputSchema:P(()=>D(t({})))}),oi=ve({id:"google.google_search",inputSchema:P(()=>D(t({mode:Y(["MODE_DYNAMIC","MODE_UNSPECIFIED"]).default("MODE_UNSPECIFIED"),dynamicThreshold:a().default(1)})))}),ni=ve({id:"google.url_context",inputSchema:P(()=>D(t({})))}),ai=ve({id:"google.vertex_rag_store",inputSchema:t({ragCorpus:e(),topK:a().optional()})}),ii={googleSearch:oi,enterpriseWebSearch:Xa,googleMaps:ti,urlContext:ni,fileSearch:ei,codeExecution:Ya,vertexRagStore:ai},li=class{constructor(o,l,s){this.modelId=o,this.settings=l,this.config=s,this.specificationVersion="v3"}get maxImagesPerCall(){var o;return(o=this.settings.maxImagesPerCall)!=null?o:4}get provider(){return this.config.provider}async doGenerate(o){var l,s,p;const{prompt:c,n:m=1,size:u,aspectRatio:d="1:1",seed:b,providerOptions:_,headers:T,abortSignal:w,files:y,mask:g}=o,k=[];if(y!=null&&y.length>0)throw new Error("Google Generative AI does not support image editing. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities.");if(g!=null)throw new Error("Google Generative AI does not support image editing with masks. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities.");u!=null&&k.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."}),b!=null&&k.push({type:"unsupported",feature:"seed",details:"This model does not support the `seed` option through this provider."});const C=await me({provider:"google",providerOptions:_,schema:ri}),f=(p=(s=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:s.call(l))!=null?p:new Date,L={sampleCount:m};d!=null&&(L.aspectRatio=d),C&&Object.assign(L,C);const $={instances:[{prompt:c}],parameters:L},{responseHeaders:M,value:X}=await fe({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:ge(await Se(this.config.headers),T),body:$,failedResponseHandler:Re,successfulResponseHandler:be(si),abortSignal:w,fetch:this.config.fetch});return{images:X.predictions.map(q=>q.bytesBase64Encoded),warnings:k??[],providerMetadata:{google:{images:X.predictions.map(q=>({}))}},response:{timestamp:f,modelId:this.modelId,headers:M}}}},si=P(()=>D(t({predictions:x(t({bytesBase64Encoded:e()})).default([])}))),ri=P(()=>D(t({personGeneration:Y(["dont_allow","allow_adult","allow_all"]).nullish(),aspectRatio:Y(["1:1","3:4","4:3","9:16","16:9"]).nullish()})));function ui(o={}){var l,s;const p=(l=je(o.baseURL))!=null?l:"https://generativelanguage.googleapis.com/v1beta",c=(s=o.name)!=null?s:"google.generative-ai",m=()=>Ge({"x-goog-api-key":Ve({apiKey:o.apiKey,environmentVariableName:"GOOGLE_GENERATIVE_AI_API_KEY",description:"Google Generative AI"}),...o.headers},`ai-sdk/google/${Da}`),u=T=>{var w;return new Fa(T,{provider:c,baseURL:p,headers:m,generateId:(w=o.generateId)!=null?w:pe,supportedUrls:()=>({"*":[new RegExp(`^${p}/files/.*$`),new RegExp("^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$"),new RegExp("^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$")]}),fetch:o.fetch})},d=T=>new Ha(T,{provider:c,baseURL:p,headers:m,fetch:o.fetch}),b=(T,w={})=>new li(T,w,{provider:c,baseURL:p,headers:m,fetch:o.fetch}),_=function(T){if(new.target)throw new Error("The Google Generative AI model function cannot be called with the new keyword.");return u(T)};return _.specificationVersion="v3",_.languageModel=u,_.chat=u,_.generativeAI=u,_.embedding=d,_.embeddingModel=d,_.textEmbedding=d,_.textEmbeddingModel=d,_.image=b,_.imageModel=b,_.tools=ii,_}ui();export{ci as a,ui as c,di as o};