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