blink 1.1.16 → 1.1.17
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/cli/{auth-DCUw-BJE.js → auth-Db3lxkv2.js} +2 -2
- package/dist/cli/{chat-ebiRKqit.js → chat-BtLHnRou.js} +1 -1
- package/dist/cli/{dev-Bz1veOUF.js → dev-VE6iNqe3.js} +104 -104
- package/dist/cli/index.js +3 -3
- package/dist/cli/init-BmUPyFWc.js +25 -0
- package/dist/cli/{init-templates-C_keoZ45.js → init-templates-3vtw2MZQ.js} +178 -143
- package/dist/cli/login-D1muj139.js +1 -0
- package/dist/cli/{run-DT3wRuFc.js → run-BlY6czRh.js} +1 -1
- package/dist/cli/{setup-slack-app-Bo1yEsSq.js → setup-slack-app-BeKQIOnA.js} +1 -1
- package/dist/cli/{util-DBfnc6lD.js → util-x4GqZFrj.js} +1 -1
- package/dist/node/agent/index.node.cjs +1 -1
- package/dist/node/agent/index.node.js +1 -1
- package/dist/node/{index.node-sb6fILn2.cjs → index.node-CijG75ex.cjs} +1 -1
- package/dist/node/{index.node-CERnwYbK.js → index.node-CvZqlsJo.js} +1 -1
- package/dist/node/react/index.node.cjs +209 -174
- package/dist/node/react/index.node.d.cts +3 -1
- package/dist/node/react/index.node.d.ts +3 -1
- package/dist/node/react/index.node.js +184 -149
- package/package.json +6 -4
- package/dist/cli/init-DYcep43s.js +0 -3
- package/dist/cli/login-P-KIKeEv.js +0 -1
- /package/dist/cli/{dist-AXHevRdg.js → dist-DxkSGwUH.js} +0 -0
- /package/dist/cli/{open-DCYivxgo.js → open-S_jcQ0nw.js} +0 -0
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{__commonJSMin as e,__esmMin as t,__export as n,__reExport as r,__require as i,__toCommonJS as a,__toESM as o}from"../chunk-D9KrCrVq.js";import{APICallError as s,APIServerURLEnvironmentVariable as c,Agent as l,EventSourceParserStream as u,Hono as d,InvalidArgumentError as f,InvalidPromptError as p,InvalidResponseDataError as m,JSONParseError as h,NoSuchModelError as g,StreamResponseFormatHeader as _,TooManyEmbeddingValuesForCallError as v,TypeValidationError as y,UnsupportedFunctionalityError as b,combineHeaders as x,convertBase64ToUint8Array as S,convertToBase64 as C,createBinaryResponseHandler as w,createEventSourceResponseHandler as T,createJsonErrorResponseHandler as E,createJsonResponseHandler as D,createProviderDefinedToolFactory as O,createProviderDefinedToolFactoryWithOutputSchema as k,createServerAdapter as A,generateId as j,hc as M,isParsableJson as N,isToolApprovalOutput as P,lastUIOptions as ee,loadApiKey as te,loadOptionalSetting as ne,mediaTypeToExtension as F,model as I,parseProviderOptions as L,postFormDataToApi as R,postJsonToApi as z,require_has_flag as re,resolve as B,tools as ie,validator as V,withUserAgentSuffix as ae,withoutTrailingSlash as oe}from"../index.node-CERnwYbK.js";import"../token-error-488npYdU.js";import"../esm-CbZfjZBn.js";import{resolveConfig as se}from"../build-D_L0gFGa.js";import{createRequire as H}from"node:module";import ce,{z as U}from"zod/v4";import"zod/v3";import{Buffer as le}from"node:buffer";import*as W from"node:fs";import ue,{createReadStream as de,existsSync as fe,mkdirSync as pe,readFileSync as me,unlinkSync as he,writeFileSync as ge}from"node:fs";import{fileURLToPath as _e}from"node:url";import{Writable as ve}from"node:stream";import{promisify as ye,stripVTControlCharacters as be}from"node:util";import{createHash as xe}from"node:crypto";import Se,{createServer as Ce}from"http";import{dirname as we,join as Te}from"path";import{createRequire as Ee}from"module";import{existsSync as De,mkdirSync as Oe,readFileSync as ke,watch as Ae,writeFileSync as je}from"fs";import{convertToModelMessages as Me,isToolOrDynamicToolUIPart as Ne,readUIMessageStream as Pe,streamText as Fe,tool as Ie}from"ai";import*as Le from"fs/promises";import{readFile as Re,stat as ze,writeFile as Be}from"fs/promises";import{spawn as Ve}from"child_process";import{useCallback as He,useEffect as G,useMemo as Ue,useRef as We,useState as K}from"react";import q,{ZodFirstPartyTypeKind as J,ZodType as Ge,z as Y}from"zod";import*as Ke from"node:path";import qe,{dirname as Je,join as Ye}from"node:path";import Xe,{stdin as Ze,stdout as Qe}from"node:process";import*as $e from"node:readline";import et from"node:readline";import tt,{execFile as nt}from"node:child_process";import*as rt from"node:fs/promises";import it,{constants as at}from"node:fs/promises";import ot from"node:os";var st=`2.0.23`,ct=U.object({type:U.literal(`error`),error:U.object({type:U.string(),message:U.string()})}),lt=E({errorSchema:ct,errorToMessage:e=>e.error.message}),ut=U.object({citations:U.object({enabled:U.boolean()}).optional(),title:U.string().optional(),context:U.string().optional()}),dt=U.object({sendReasoning:U.boolean().optional(),thinking:U.object({type:U.union([U.literal(`enabled`),U.literal(`disabled`)]),budgetTokens:U.number().optional()}).optional(),disableParallelToolUse:U.boolean().optional(),cacheControl:U.object({type:U.literal(`ephemeral`),ttl:U.union([U.literal(`5m`),U.literal(`1h`)]).optional()}).optional()});function ft(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var pt=U.object({maxCharacters:U.number().optional()}),mt=O({id:`anthropic.text_editor_20250728`,name:`str_replace_based_edit_tool`,inputSchema:U.object({command:U.enum([`view`,`create`,`str_replace`,`insert`]),path:U.string(),file_text:U.string().optional(),insert_line:U.number().int().optional(),new_str:U.string().optional(),old_str:U.string().optional(),view_range:U.array(U.number().int()).optional()})}),ht=(e={})=>mt(e),gt=U.object({maxUses:U.number().optional(),allowedDomains:U.array(U.string()).optional(),blockedDomains:U.array(U.string()).optional(),userLocation:U.object({type:U.literal(`approximate`),city:U.string().optional(),region:U.string().optional(),country:U.string().optional(),timezone:U.string().optional()}).optional()}),_t=U.array(U.object({url:U.string(),title:U.string(),pageAge:U.string().nullable(),encryptedContent:U.string(),type:U.literal(`web_search_result`)})),vt=k({id:`anthropic.web_search_20250305`,name:`web_search`,inputSchema:U.object({query:U.string()}),outputSchema:_t}),yt=(e={})=>vt(e),bt=U.object({maxUses:U.number().optional(),allowedDomains:U.array(U.string()).optional(),blockedDomains:U.array(U.string()).optional(),citations:U.object({enabled:U.boolean()}).optional(),maxContentTokens:U.number().optional()}),xt=U.object({type:U.literal(`web_fetch_result`),url:U.string(),content:U.object({type:U.literal(`document`),title:U.string(),citations:U.object({enabled:U.boolean()}).optional(),source:U.union([U.object({type:U.literal(`base64`),mediaType:U.literal(`application/pdf`),data:U.string()}),U.object({type:U.literal(`text`),mediaType:U.literal(`text/plain`),data:U.string()})])}),retrievedAt:U.string().nullable()}),St=k({id:`anthropic.web_fetch_20250910`,name:`web_fetch`,inputSchema:U.object({url:U.string()}),outputSchema:xt}),Ct=(e={})=>St(e);function wt({tools:e,toolChoice:t,disableParallelToolUse:n}){e=e?.length?e:void 0;let r=[],i=new Set;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};let a=[];for(let t of e)switch(t.type){case`function`:{let e=ft(t.providerOptions);a.push({name:t.name,description:t.description,input_schema:t.inputSchema,cache_control:e});break}case`provider-defined`:switch(t.id){case`anthropic.code_execution_20250522`:i.add(`code-execution-2025-05-22`),a.push({type:`code_execution_20250522`,name:`code_execution`});break;case`anthropic.computer_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`computer`,type:`computer_20250124`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.computer_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`computer`,type:`computer_20241022`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.text_editor_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_editor`,type:`text_editor_20250124`});break;case`anthropic.text_editor_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`str_replace_editor`,type:`text_editor_20241022`});break;case`anthropic.text_editor_20250429`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`});break;case`anthropic.text_editor_20250728`:{let e=pt.parse(t.args);a.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250728`,max_characters:e.maxCharacters});break}case`anthropic.bash_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`bash`,type:`bash_20250124`});break;case`anthropic.bash_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`bash`,type:`bash_20241022`});break;case`anthropic.web_fetch_20250910`:{i.add(`web-fetch-2025-09-10`);let e=bt.parse(t.args);a.push({type:`web_fetch_20250910`,name:`web_fetch`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens});break}case`anthropic.web_search_20250305`:{let e=gt.parse(t.args);a.push({type:`web_search_20250305`,name:`web_search`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation});break}default:r.push({type:`unsupported-tool`,tool:t});break}break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:a,toolChoice:n?{type:`auto`,disable_parallel_tool_use:n}:void 0,toolWarnings:r,betas:i};let o=t.type;switch(o){case`auto`:return{tools:a,toolChoice:{type:`auto`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`required`:return{tools:a,toolChoice:{type:`any`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};case`tool`:return{tools:a,toolChoice:{type:`tool`,name:t.toolName,disable_parallel_tool_use:n},toolWarnings:r,betas:i};default:throw new b({functionality:`tool choice type: ${o}`})}}var Tt=U.object({type:U.literal(`code_execution_result`),stdout:U.string(),stderr:U.string(),return_code:U.number()}),Et=k({id:`anthropic.code_execution_20250522`,name:`code_execution`,inputSchema:U.object({code:U.string()}),outputSchema:Tt}),Dt=(e={})=>Et(e);function Ot(e){if(typeof e==`string`)return Buffer.from(e,`base64`).toString(`utf-8`);if(e instanceof Uint8Array)return new TextDecoder().decode(e);throw e instanceof URL?new b({functionality:`URL-based text documents are not supported for citations`}):new b({functionality:`unsupported data type for text documents: ${typeof e}`})}async function kt({prompt:e,sendReasoning:t,warnings:n}){let r=new Set,i=At(e),a,o=[];async function s(e){return(await L({provider:`anthropic`,providerOptions:e,schema:ut}))?.citations?.enabled??!1}async function c(e){let t=await L({provider:`anthropic`,providerOptions:e,schema:ut});return{title:t?.title,context:t?.context}}for(let e=0;e<i.length;e++){let l=i[e],u=e===i.length-1,d=l.type;switch(d){case`system`:if(a!=null)throw new b({functionality:`Multiple system messages that are separated by user/assistant messages`});a=l.messages.map(({content:e,providerOptions:t})=>({type:`text`,text:e,cache_control:ft(t)}));break;case`user`:{let e=[];for(let t of l.messages){let{role:n,content:i}=t;switch(n){case`user`:for(let n=0;n<i.length;n++){let a=i[n],o=n===i.length-1,l=ft(a.providerOptions)??(o?ft(t.providerOptions):void 0);switch(a.type){case`text`:e.push({type:`text`,text:a.text,cache_control:l});break;case`file`:if(a.mediaType.startsWith(`image/`))e.push({type:`image`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`base64`,media_type:a.mediaType===`image/*`?`image/jpeg`:a.mediaType,data:C(a.data)},cache_control:l});else if(a.mediaType===`application/pdf`){r.add(`pdfs-2024-09-25`);let t=await s(a.providerOptions),n=await c(a.providerOptions);e.push({type:`document`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`base64`,media_type:`application/pdf`,data:C(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else if(a.mediaType===`text/plain`){let t=await s(a.providerOptions),n=await c(a.providerOptions);e.push({type:`document`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`text`,media_type:`text/plain`,data:Ot(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else throw new b({functionality:`media type: ${a.mediaType}`});break}}break;case`tool`:for(let n=0;n<i.length;n++){let r=i[n],a=n===i.length-1,o=ft(r.providerOptions)??(a?ft(t.providerOptions):void 0),s=r.output,c;switch(s.type){case`content`:c=s.value.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text,cache_control:void 0};case`media`:if(e.mediaType.startsWith(`image/`))return{type:`image`,source:{type:`base64`,media_type:e.mediaType,data:e.data},cache_control:void 0};throw new b({functionality:`media type: ${e.mediaType}`})}});break;case`text`:case`error-text`:c=s.value;break;case`json`:case`error-json`:default:c=JSON.stringify(s.value);break}e.push({type:`tool_result`,tool_use_id:r.toolCallId,content:c,is_error:s.type===`error-text`||s.type===`error-json`?!0:void 0,cache_control:o})}break;default:{let e=n;throw Error(`Unsupported role: ${e}`)}}}o.push({role:`user`,content:e});break}case`assistant`:{let e=[];for(let r=0;r<l.messages.length;r++){let i=l.messages[r],a=r===l.messages.length-1,{content:o}=i;for(let r=0;r<o.length;r++){let s=o[r],c=r===o.length-1,l=ft(s.providerOptions)??(c?ft(i.providerOptions):void 0);switch(s.type){case`text`:e.push({type:`text`,text:u&&a&&c?s.text.trim():s.text,cache_control:l});break;case`reasoning`:if(t){let t=await L({provider:`anthropic`,providerOptions:s.providerOptions,schema:zt});t==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):t.signature==null?t.redactedData==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):e.push({type:`redacted_thinking`,data:t.redactedData,cache_control:l}):e.push({type:`thinking`,thinking:s.text,signature:t.signature,cache_control:l})}else n.push({type:`other`,message:`sending reasoning content is disabled for this model`});break;case`tool-call`:if(s.providerExecuted){s.toolName===`code_execution`||s.toolName===`web_fetch`||s.toolName===`web_search`?e.push({type:`server_tool_use`,id:s.toolCallId,name:s.toolName,input:s.input,cache_control:l}):n.push({type:`other`,message:`provider executed tool call for tool ${s.toolName} is not supported`});break}e.push({type:`tool_use`,id:s.toolCallId,name:s.toolName,input:s.input,cache_control:l});break;case`tool-result`:if(s.toolName===`code_execution`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=Tt.parse(t.value);e.push({type:`code_execution_tool_result`,tool_use_id:s.toolCallId,content:{type:r.type,stdout:r.stdout,stderr:r.stderr,return_code:r.return_code},cache_control:l});break}if(s.toolName===`web_fetch`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=xt.parse(t.value);e.push({type:`web_fetch_tool_result`,tool_use_id:s.toolCallId,content:{type:`web_fetch_result`,url:r.url,retrieved_at:r.retrievedAt,content:{type:`document`,title:r.content.title,citations:r.content.citations,source:{type:r.content.source.type,media_type:r.content.source.mediaType,data:r.content.source.data}}},cache_control:l});break}if(s.toolName===`web_search`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=_t.parse(t.value);e.push({type:`web_search_tool_result`,tool_use_id:s.toolCallId,content:r.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:l});break}n.push({type:`other`,message:`provider executed tool result for tool ${s.toolName} is not supported`});break}}}o.push({role:`assistant`,content:e});break}default:{let e=d;throw Error(`content type: ${e}`)}}}return{prompt:{system:a,messages:o},betas:r}}function At(e){let t=[],n;for(let r of e){let{role:e}=r;switch(e){case`system`:n?.type!==`system`&&(n={type:`system`,messages:[]},t.push(n)),n.messages.push(r);break;case`assistant`:n?.type!==`assistant`&&(n={type:`assistant`,messages:[]},t.push(n)),n.messages.push(r);break;case`user`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;case`tool`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;default:{let t=e;throw Error(`Unsupported role: ${t}`)}}}return t}function jt({finishReason:e,isJsonResponseFromTool:t}){switch(e){case`pause_turn`:case`end_turn`:case`stop_sequence`:return`stop`;case`refusal`:return`content-filter`;case`tool_use`:return t?`stop`:`tool-calls`;case`max_tokens`:return`length`;default:return`unknown`}}var Mt={webSearchResult:U.object({type:U.literal(`web_search_result_location`),cited_text:U.string(),url:U.string(),title:U.string(),encrypted_index:U.string()}),pageLocation:U.object({type:U.literal(`page_location`),cited_text:U.string(),document_index:U.number(),document_title:U.string().nullable(),start_page_number:U.number(),end_page_number:U.number()}),charLocation:U.object({type:U.literal(`char_location`),cited_text:U.string(),document_index:U.number(),document_title:U.string().nullable(),start_char_index:U.number(),end_char_index:U.number()})},Nt=U.discriminatedUnion(`type`,[Mt.webSearchResult,Mt.pageLocation,Mt.charLocation]);U.discriminatedUnion(`type`,[Mt.pageLocation,Mt.charLocation]);function Pt(e,t,n,r){if(e.type===`page_location`||e.type===`char_location`){let i=Ft(e,t,n);i&&r(i)}}function Ft(e,t,n){let r=t[e.document_index];if(!r)return null;let i=e.type===`page_location`?{citedText:e.cited_text,startPageNumber:e.start_page_number,endPageNumber:e.end_page_number}:{citedText:e.cited_text,startCharIndex:e.start_char_index,endCharIndex:e.end_char_index};return{type:`source`,sourceType:`document`,id:n(),mediaType:r.mediaType,title:e.document_title??r.title,filename:r.filename,providerMetadata:{anthropic:i}}}var It=class{constructor(e,t){this.specificationVersion=`v2`,this.modelId=e,this.config=t,this.generateId=t.generateId??j}supportsUrl(e){return e.protocol===`https:`}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:t=4096,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){let p=[];a!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),l!=null&&p.push({type:`unsupported-setting`,setting:`seed`}),c?.type===`json`&&(c.schema==null?p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format requires a schema. The response format is ignored.`}):u!=null&&p.push({type:`unsupported-setting`,setting:`tools`,details:`JSON response format does not support tools. The provided tools are ignored.`}));let m=c?.type===`json`&&c.schema!=null?{type:`function`,name:`json`,description:`Respond with a JSON object.`,inputSchema:c.schema}:void 0,h=await L({provider:`anthropic`,providerOptions:f,schema:dt}),{prompt:g,betas:_}=await kt({prompt:e,sendReasoning:h?.sendReasoning??!0,warnings:p}),v=h?.thinking?.type===`enabled`,y=h?.thinking?.budgetTokens,x={model:this.modelId,max_tokens:t,temperature:n,top_k:i,top_p:r,stop_sequences:s,...v&&{thinking:{type:`enabled`,budget_tokens:y}},system:g.system,messages:g.messages};if(v){if(y==null)throw new b({functionality:`thinking requires a budget`});x.temperature!=null&&(x.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported when thinking is enabled`})),i!=null&&(x.top_k=void 0,p.push({type:`unsupported-setting`,setting:`topK`,details:`topK is not supported when thinking is enabled`})),r!=null&&(x.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported when thinking is enabled`})),x.max_tokens=t+y}let{tools:S,toolChoice:C,toolWarnings:w,betas:T}=wt(m==null?{tools:u??[],toolChoice:d,disableParallelToolUse:h?.disableParallelToolUse}:{tools:[m],toolChoice:{type:`tool`,toolName:m.name},disableParallelToolUse:!0});return{args:{...x,tools:S,tool_choice:C},warnings:[...p,...w],betas:new Set([..._,...T]),usesJsonResponseTool:m!=null}}async getHeaders({betas:e,headers:t}){return x(await B(this.config.headers),e.size>0?{"anthropic-beta":Array.from(e).join(`,`)}:{},t)}buildRequestUrl(e){var t;return(t=this.config).buildRequestUrl?.call(t,this.config.baseURL,e)??`${this.config.baseURL}/messages`}transformRequestBody(e){var t;return(t=this.config).transformRequestBody?.call(t,e)??e}extractCitationDocuments(e){return e.filter(e=>e.role===`user`).flatMap(e=>e.content).filter(e=>e.type!==`file`||e.mediaType!==`application/pdf`&&e.mediaType!==`text/plain`?!1:e.providerOptions?.anthropic?.citations?.enabled??!1).map(e=>{let t=e;return{title:t.filename??`Untitled Document`,filename:t.filename,mediaType:t.mediaType}})}async doGenerate(e){let{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),a=this.extractCitationDocuments(e.prompt),{responseHeaders:o,value:s,rawValue:c}=await z({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(t),failedResponseHandler:lt,successfulResponseHandler:D(Lt),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=[];for(let e of s.content)switch(e.type){case`text`:if(!i&&(l.push({type:`text`,text:e.text}),e.citations))for(let t of e.citations)Pt(t,a,this.generateId,e=>l.push(e));break;case`thinking`:l.push({type:`reasoning`,text:e.thinking,providerMetadata:{anthropic:{signature:e.signature}}});break;case`redacted_thinking`:l.push({type:`reasoning`,text:``,providerMetadata:{anthropic:{redactedData:e.data}}});break;case`tool_use`:l.push(i?{type:`text`,text:JSON.stringify(e.input)}:{type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input)});break;case`server_tool_use`:(e.name===`web_search`||e.name===`code_execution`||e.name===`web_fetch`)&&l.push({type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input),providerExecuted:!0});break;case`web_fetch_tool_result`:e.content.type===`web_fetch_result`?l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,result:{type:`web_fetch_result`,url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}},providerExecuted:!0}):e.content.type===`web_fetch_tool_result_error`&&l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,isError:!0,result:{type:`web_fetch_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break;case`web_search_tool_result`:if(Array.isArray(e.content)){l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type})),providerExecuted:!0});for(let t of e.content)l.push({type:`source`,sourceType:`url`,id:this.generateId(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break;case`code_execution_tool_result`:e.content.type===`code_execution_result`?l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break}return{content:l,finishReason:jt({finishReason:s.stop_reason,isJsonResponseFromTool:i}),usage:{inputTokens:s.usage.input_tokens,outputTokens:s.usage.output_tokens,totalTokens:s.usage.input_tokens+s.usage.output_tokens,cachedInputTokens:s.usage.cache_read_input_tokens??void 0},request:{body:t},response:{id:s.id??void 0,modelId:s.model??void 0,headers:o,body:c},warnings:n,providerMetadata:{anthropic:{usage:s.usage,cacheCreationInputTokens:s.usage.cache_creation_input_tokens??null,stopSequence:s.stop_sequence??null}}}}async doStream(e){let{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),a=this.extractCitationDocuments(e.prompt),o={...t,stream:!0},{responseHeaders:s,value:c}=await z({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(o),failedResponseHandler:lt,successfulResponseHandler:T(Rt),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=`unknown`,u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},d={},f,p=null,m=null,h,g=this.generateId;return{stream:c.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let r=t.value;switch(r.type){case`ping`:return;case`content_block_start`:{let e=r.content_block.type;switch(h=e,e){case`text`:d[r.index]={type:`text`},n.enqueue({type:`text-start`,id:String(r.index)});return;case`thinking`:d[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index)});return;case`redacted_thinking`:d[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index),providerMetadata:{anthropic:{redactedData:r.content_block.data}}});return;case`tool_use`:d[r.index]=i?{type:`text`}:{type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``},n.enqueue(i?{type:`text-start`,id:String(r.index)}:{type:`tool-input-start`,id:r.content_block.id,toolName:r.content_block.name});return;case`server_tool_use`:(r.content_block.name===`web_fetch`||r.content_block.name===`web_search`||r.content_block.name===`code_execution`)&&(d[r.index]={type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``,providerExecuted:!0},n.enqueue({type:`tool-input-start`,id:r.content_block.id,toolName:r.content_block.name,providerExecuted:!0}));return;case`web_fetch_tool_result`:{let e=r.content_block;e.content.type===`web_fetch_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,result:{type:`web_fetch_result`,url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}}}):e.content.type===`web_fetch_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,isError:!0,result:{type:`web_fetch_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}case`web_search_tool_result`:{let e=r.content_block;if(Array.isArray(e.content)){n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type})),providerExecuted:!0});for(let t of e.content)n.enqueue({type:`source`,sourceType:`url`,id:g(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}case`code_execution_tool_result`:{let e=r.content_block;e.content.type===`code_execution_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}default:{let t=e;throw Error(`Unsupported content block type: ${t}`)}}}case`content_block_stop`:if(d[r.index]!=null){let e=d[r.index];switch(e.type){case`text`:n.enqueue({type:`text-end`,id:String(r.index)});break;case`reasoning`:n.enqueue({type:`reasoning-end`,id:String(r.index)});break;case`tool-call`:i||(n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue(e));break}delete d[r.index]}h=void 0;return;case`content_block_delta`:{let e=r.delta.type;switch(e){case`text_delta`:if(i)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:r.delta.text});return;case`thinking_delta`:n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:r.delta.thinking});return;case`signature_delta`:h===`thinking`&&n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:``,providerMetadata:{anthropic:{signature:r.delta.signature}}});return;case`input_json_delta`:{let e=d[r.index],t=r.delta.partial_json;if(i){if(e?.type!==`text`)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:t})}else{if(e?.type!==`tool-call`)return;n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:t}),e.input+=t}return}case`citations_delta`:{let e=r.delta.citation;Pt(e,a,g,e=>n.enqueue(e));return}default:{let t=e;throw Error(`Unsupported delta type: ${t}`)}}}case`message_start`:u.inputTokens=r.message.usage.input_tokens,u.cachedInputTokens=r.message.usage.cache_read_input_tokens??void 0,f={...r.message.usage},p=r.message.usage.cache_creation_input_tokens??null,n.enqueue({type:`response-metadata`,id:r.message.id??void 0,modelId:r.message.model??void 0});return;case`message_delta`:u.outputTokens=r.usage.output_tokens,u.totalTokens=(u.inputTokens??0)+(r.usage.output_tokens??0),l=jt({finishReason:r.delta.stop_reason,isJsonResponseFromTool:i}),m=r.delta.stop_sequence??null,f={...f,...r.usage};return;case`message_stop`:n.enqueue({type:`finish`,finishReason:l,usage:u,providerMetadata:{anthropic:{usage:f??null,cacheCreationInputTokens:p,stopSequence:m}}});return;case`error`:n.enqueue({type:`error`,error:r.error});return;default:{let e=r;throw Error(`Unsupported chunk type: ${e}`)}}}})),request:{body:o},response:{headers:s}}}},Lt=U.object({type:U.literal(`message`),id:U.string().nullish(),model:U.string().nullish(),content:U.array(U.discriminatedUnion(`type`,[U.object({type:U.literal(`text`),text:U.string(),citations:U.array(Nt).optional()}),U.object({type:U.literal(`thinking`),thinking:U.string(),signature:U.string()}),U.object({type:U.literal(`redacted_thinking`),data:U.string()}),U.object({type:U.literal(`tool_use`),id:U.string(),name:U.string(),input:U.unknown()}),U.object({type:U.literal(`server_tool_use`),id:U.string(),name:U.string(),input:U.record(U.string(),U.unknown()).nullish()}),U.object({type:U.literal(`web_fetch_tool_result`),tool_use_id:U.string(),content:U.union([U.object({type:U.literal(`web_fetch_result`),url:U.string(),retrieved_at:U.string(),content:U.object({type:U.literal(`document`),title:U.string().nullable(),citations:U.object({enabled:U.boolean()}).optional(),source:U.object({type:U.literal(`text`),media_type:U.string(),data:U.string()})})}),U.object({type:U.literal(`web_fetch_tool_result_error`),error_code:U.string()})])}),U.object({type:U.literal(`web_search_tool_result`),tool_use_id:U.string(),content:U.union([U.array(U.object({type:U.literal(`web_search_result`),url:U.string(),title:U.string(),encrypted_content:U.string(),page_age:U.string().nullish()})),U.object({type:U.literal(`web_search_tool_result_error`),error_code:U.string()})])}),U.object({type:U.literal(`code_execution_tool_result`),tool_use_id:U.string(),content:U.union([U.object({type:U.literal(`code_execution_result`),stdout:U.string(),stderr:U.string(),return_code:U.number()}),U.object({type:U.literal(`code_execution_tool_result_error`),error_code:U.string()})])})])),stop_reason:U.string().nullish(),stop_sequence:U.string().nullish(),usage:U.looseObject({input_tokens:U.number(),output_tokens:U.number(),cache_creation_input_tokens:U.number().nullish(),cache_read_input_tokens:U.number().nullish()})}),Rt=U.discriminatedUnion(`type`,[U.object({type:U.literal(`message_start`),message:U.object({id:U.string().nullish(),model:U.string().nullish(),usage:U.looseObject({input_tokens:U.number(),cache_creation_input_tokens:U.number().nullish(),cache_read_input_tokens:U.number().nullish()})})}),U.object({type:U.literal(`content_block_start`),index:U.number(),content_block:U.discriminatedUnion(`type`,[U.object({type:U.literal(`text`),text:U.string()}),U.object({type:U.literal(`thinking`),thinking:U.string()}),U.object({type:U.literal(`tool_use`),id:U.string(),name:U.string()}),U.object({type:U.literal(`redacted_thinking`),data:U.string()}),U.object({type:U.literal(`server_tool_use`),id:U.string(),name:U.string(),input:U.record(U.string(),U.unknown()).nullish()}),U.object({type:U.literal(`web_fetch_tool_result`),tool_use_id:U.string(),content:U.union([U.object({type:U.literal(`web_fetch_result`),url:U.string(),retrieved_at:U.string(),content:U.object({type:U.literal(`document`),title:U.string().nullable(),citations:U.object({enabled:U.boolean()}).optional(),source:U.object({type:U.literal(`text`),media_type:U.string(),data:U.string()})})}),U.object({type:U.literal(`web_fetch_tool_result_error`),error_code:U.string()})])}),U.object({type:U.literal(`web_search_tool_result`),tool_use_id:U.string(),content:U.union([U.array(U.object({type:U.literal(`web_search_result`),url:U.string(),title:U.string(),encrypted_content:U.string(),page_age:U.string().nullish()})),U.object({type:U.literal(`web_search_tool_result_error`),error_code:U.string()})])}),U.object({type:U.literal(`code_execution_tool_result`),tool_use_id:U.string(),content:U.union([U.object({type:U.literal(`code_execution_result`),stdout:U.string(),stderr:U.string(),return_code:U.number()}),U.object({type:U.literal(`code_execution_tool_result_error`),error_code:U.string()})])})])}),U.object({type:U.literal(`content_block_delta`),index:U.number(),delta:U.discriminatedUnion(`type`,[U.object({type:U.literal(`input_json_delta`),partial_json:U.string()}),U.object({type:U.literal(`text_delta`),text:U.string()}),U.object({type:U.literal(`thinking_delta`),thinking:U.string()}),U.object({type:U.literal(`signature_delta`),signature:U.string()}),U.object({type:U.literal(`citations_delta`),citation:Nt})])}),U.object({type:U.literal(`content_block_stop`),index:U.number()}),U.object({type:U.literal(`error`),error:U.object({type:U.string(),message:U.string()})}),U.object({type:U.literal(`message_delta`),delta:U.object({stop_reason:U.string().nullish(),stop_sequence:U.string().nullish()}),usage:U.looseObject({output_tokens:U.number(),cache_creation_input_tokens:U.number().nullish()})}),U.object({type:U.literal(`message_stop`)}),U.object({type:U.literal(`ping`)})]),zt=U.object({signature:U.string().optional(),redactedData:U.string().optional()}),Bt=O({id:`anthropic.bash_20241022`,name:`bash`,inputSchema:ce.object({command:ce.string(),restart:ce.boolean().optional()})}),Vt=O({id:`anthropic.bash_20250124`,name:`bash`,inputSchema:ce.object({command:ce.string(),restart:ce.boolean().optional()})}),Ht=O({id:`anthropic.computer_20241022`,name:`computer`,inputSchema:U.object({action:U.enum([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:U.array(U.number().int()).optional(),text:U.string().optional()})}),Ut=O({id:`anthropic.computer_20250124`,name:`computer`,inputSchema:U.object({action:U.enum([`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:U.tuple([U.number().int(),U.number().int()]).optional(),duration:U.number().optional(),scroll_amount:U.number().optional(),scroll_direction:U.enum([`up`,`down`,`left`,`right`]).optional(),start_coordinate:U.tuple([U.number().int(),U.number().int()]).optional(),text:U.string().optional()})}),Wt=O({id:`anthropic.text_editor_20241022`,name:`str_replace_editor`,inputSchema:U.object({command:U.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:U.string(),file_text:U.string().optional(),insert_line:U.number().int().optional(),new_str:U.string().optional(),old_str:U.string().optional(),view_range:U.array(U.number().int()).optional()})}),Gt=O({id:`anthropic.text_editor_20250124`,name:`str_replace_editor`,inputSchema:U.object({command:U.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:U.string(),file_text:U.string().optional(),insert_line:U.number().int().optional(),new_str:U.string().optional(),old_str:U.string().optional(),view_range:U.array(U.number().int()).optional()})}),Kt=O({id:`anthropic.text_editor_20250429`,name:`str_replace_based_edit_tool`,inputSchema:U.object({command:U.enum([`view`,`create`,`str_replace`,`insert`]),path:U.string(),file_text:U.string().optional(),insert_line:U.number().int().optional(),new_str:U.string().optional(),old_str:U.string().optional(),view_range:U.array(U.number().int()).optional()})}),qt={bash_20241022:Bt,bash_20250124:Vt,codeExecution_20250522:Dt,computer_20241022:Ht,computer_20250124:Ut,textEditor_20241022:Wt,textEditor_20250124:Gt,textEditor_20250429:Kt,textEditor_20250728:ht,webFetch_20250910:Ct,webSearch_20250305:yt};function Jt(e={}){let t=oe(e.baseURL)??`https://api.anthropic.com/v1`,n=()=>ae({"anthropic-version":`2023-06-01`,"x-api-key":te({apiKey:e.apiKey,environmentVariableName:`ANTHROPIC_API_KEY`,description:`Anthropic`}),...e.headers},`ai-sdk/anthropic/${st}`),r=r=>new It(r,{provider:`anthropic.messages`,baseURL:t,headers:n,fetch:e.fetch,generateId:e.generateId??j,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})}),i=function(e){if(new.target)throw Error(`The Anthropic model function cannot be called with the new keyword.`);return r(e)};return i.languageModel=r,i.chat=r,i.messages=r,i.textEmbeddingModel=e=>{throw new g({modelId:e,modelType:`textEmbeddingModel`})},i.imageModel=e=>{throw new g({modelId:e,modelType:`imageModel`})},i.tools=qt,i}Jt();var Yt=`2.0.17`,Xt=U.object({error:U.object({code:U.number().nullable(),message:U.string(),status:U.string()})}),Zt=E({errorSchema:Xt,errorToMessage:e=>e.error.message}),Qt=U.object({outputDimensionality:U.number().optional(),taskType:U.enum([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional()}),$t=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){let i=await L({provider:`google`,providerOptions:r,schema:Qt});if(e.length>this.maxEmbeddingsPerCall)throw new v({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let a=x(await B(this.config.headers),t);if(e.length===1){let{responseHeaders:t,value:r,rawValue:o}=await z({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:a,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType},failedResponseHandler:Zt,successfulResponseHandler:D(tn),abortSignal:n,fetch:this.config.fetch});return{embeddings:[r.embedding.values],usage:void 0,response:{headers:t,body:o}}}let{responseHeaders:o,value:s,rawValue:c}=await z({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:a,body:{requests:e.map(e=>({model:`models/${this.modelId}`,content:{role:`user`,parts:[{text:e}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType}))},failedResponseHandler:Zt,successfulResponseHandler:D(en),abortSignal:n,fetch:this.config.fetch});return{embeddings:s.embeddings.map(e=>e.values),usage:void 0,response:{headers:o,body:c}}}},en=U.object({embeddings:U.array(U.object({values:U.array(U.number())}))}),tn=U.object({embedding:U.object({values:U.array(U.number())})});function nn(e){if(e==null||rn(e))return;if(typeof e==`boolean`)return{type:`boolean`,properties:{}};let{type:t,description:n,required:r,properties:i,items:a,allOf:o,anyOf:s,oneOf:c,format:l,const:u,minLength:d,enum:f}=e,p={};if(n&&(p.description=n),r&&(p.required=r),l&&(p.format=l),u!==void 0&&(p.enum=[u]),t&&(Array.isArray(t)?t.includes(`null`)?(p.type=t.filter(e=>e!==`null`)[0],p.nullable=!0):p.type=t:t===`null`?p.type=`null`:p.type=t),f!==void 0&&(p.enum=f),i!=null&&(p.properties=Object.entries(i).reduce((e,[t,n])=>(e[t]=nn(n),e),{})),a&&(p.items=Array.isArray(a)?a.map(nn):nn(a)),o&&(p.allOf=o.map(nn)),s)if(s.some(e=>typeof e==`object`&&e?.type===`null`)){let e=s.filter(e=>!(typeof e==`object`&&e?.type===`null`));if(e.length===1){let t=nn(e[0]);typeof t==`object`&&(p.nullable=!0,Object.assign(p,t))}else p.anyOf=e.map(nn),p.nullable=!0}else p.anyOf=s.map(nn);return c&&(p.oneOf=c.map(nn)),d!==void 0&&(p.minLength=d),p}function rn(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}function an(e,t){let n=[],r=[],i=!0,a=t?.isGemmaModel??!1;for(let{role:t,content:a}of e)switch(t){case`system`:if(!i)throw new b({functionality:`system messages are only supported at the beginning of the conversation`});n.push({text:a});break;case`user`:{i=!1;let e=[];for(let t of a)switch(t.type){case`text`:e.push({text:t.text});break;case`file`:{let n=t.mediaType===`image/*`?`image/jpeg`:t.mediaType;e.push(t.data instanceof URL?{fileData:{mimeType:n,fileUri:t.data.toString()}}:{inlineData:{mimeType:n,data:C(t.data)}});break}}r.push({role:`user`,parts:e});break}case`assistant`:i=!1,r.push({role:`model`,parts:a.map(e=>{switch(e.type){case`text`:return e.text.length===0?void 0:{text:e.text,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`reasoning`:return e.text.length===0?void 0:{text:e.text,thought:!0,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`file`:if(e.mediaType!==`image/png`)throw new b({functionality:`Only PNG images are supported in assistant messages`});if(e.data instanceof URL)throw new b({functionality:`File data URLs in assistant messages are not supported`});return{inlineData:{mimeType:e.mediaType,data:C(e.data)}};case`tool-call`:return{functionCall:{name:e.toolName,args:e.input},thoughtSignature:e.providerOptions?.google?.thoughtSignature}}}).filter(e=>e!==void 0)});break;case`tool`:{i=!1;let e=[];for(let t of a){let n=t.output;if(n.type===`content`)for(let r of n.value)switch(r.type){case`text`:e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:r.text}}});break;case`media`:e.push({inlineData:{mimeType:r.mediaType,data:r.data}},{text:`Tool executed successfully and returned this image as a response`});break;default:e.push({text:JSON.stringify(r)});break}else e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:n.value}}})}r.push({role:`user`,parts:e});break}}if(a&&n.length>0&&r.length>0&&r[0].role===`user`){let e=n.map(e=>e.text).join(`
|
|
1
|
+
import{__commonJSMin as e,__esmMin as t,__export as n,__reExport as r,__require as i,__toCommonJS as a,__toESM as o}from"../chunk-D9KrCrVq.js";import{APICallError as s,APIServerURLEnvironmentVariable as c,Agent as l,EventSourceParserStream as u,Hono as d,InvalidArgumentError as f,InvalidPromptError as p,InvalidResponseDataError as m,JSONParseError as h,NoSuchModelError as g,StreamResponseFormatHeader as _,TooManyEmbeddingValuesForCallError as v,TypeValidationError as y,UnsupportedFunctionalityError as b,combineHeaders as x,convertBase64ToUint8Array as S,convertToBase64 as C,createBinaryResponseHandler as w,createEventSourceResponseHandler as T,createGatewayProvider as E,createJsonErrorResponseHandler as D,createJsonResponseHandler as O,createProviderDefinedToolFactory as k,createProviderDefinedToolFactoryWithOutputSchema as A,createServerAdapter as j,generateId as M,hc as N,isParsableJson as P,isToolApprovalOutput as ee,lastUIOptions as te,loadApiKey as ne,loadOptionalSetting as F,mediaTypeToExtension as I,parseProviderOptions as L,postFormDataToApi as R,postJsonToApi as z,require_has_flag as re,resolve as B,tools as ie,validator as V,withUserAgentSuffix as ae,withoutTrailingSlash as oe}from"../index.node-CvZqlsJo.js";import"../token-error-488npYdU.js";import"../esm-CbZfjZBn.js";import{resolveConfig as se}from"../build-D_L0gFGa.js";import{createRequire as H}from"node:module";import ce,{z as U}from"zod/v4";import"zod/v3";import{Buffer as le}from"node:buffer";import*as W from"node:fs";import ue,{createReadStream as de,existsSync as fe,mkdirSync as pe,readFileSync as me,unlinkSync as he,writeFileSync as ge}from"node:fs";import{fileURLToPath as _e}from"node:url";import{Writable as ve}from"node:stream";import{promisify as ye,stripVTControlCharacters as be}from"node:util";import{createHash as xe}from"node:crypto";import Se,{createServer as Ce}from"http";import{dirname as we,join as Te}from"path";import{createRequire as Ee}from"module";import{existsSync as De,mkdirSync as Oe,readFileSync as ke,watch as Ae,writeFileSync as je}from"fs";import{convertToModelMessages as Me,isToolOrDynamicToolUIPart as Ne,readUIMessageStream as Pe,streamText as Fe,tool as Ie}from"ai";import*as Le from"fs/promises";import{readFile as Re,stat as ze,writeFile as Be}from"fs/promises";import{spawn as Ve}from"child_process";import{useCallback as He,useEffect as G,useMemo as Ue,useRef as We,useState as K}from"react";import q,{ZodFirstPartyTypeKind as J,ZodType as Ge,z as Y}from"zod";import*as Ke from"node:path";import qe,{dirname as Je,join as Ye}from"node:path";import Xe,{stdin as Ze,stdout as Qe}from"node:process";import*as $e from"node:readline";import et from"node:readline";import tt,{execFile as nt}from"node:child_process";import*as rt from"node:fs/promises";import it,{constants as at}from"node:fs/promises";import ot from"node:os";var st=`2.0.23`,ct=U.object({type:U.literal(`error`),error:U.object({type:U.string(),message:U.string()})}),lt=D({errorSchema:ct,errorToMessage:e=>e.error.message}),ut=U.object({citations:U.object({enabled:U.boolean()}).optional(),title:U.string().optional(),context:U.string().optional()}),dt=U.object({sendReasoning:U.boolean().optional(),thinking:U.object({type:U.union([U.literal(`enabled`),U.literal(`disabled`)]),budgetTokens:U.number().optional()}).optional(),disableParallelToolUse:U.boolean().optional(),cacheControl:U.object({type:U.literal(`ephemeral`),ttl:U.union([U.literal(`5m`),U.literal(`1h`)]).optional()}).optional()});function ft(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var pt=U.object({maxCharacters:U.number().optional()}),mt=k({id:`anthropic.text_editor_20250728`,name:`str_replace_based_edit_tool`,inputSchema:U.object({command:U.enum([`view`,`create`,`str_replace`,`insert`]),path:U.string(),file_text:U.string().optional(),insert_line:U.number().int().optional(),new_str:U.string().optional(),old_str:U.string().optional(),view_range:U.array(U.number().int()).optional()})}),ht=(e={})=>mt(e),gt=U.object({maxUses:U.number().optional(),allowedDomains:U.array(U.string()).optional(),blockedDomains:U.array(U.string()).optional(),userLocation:U.object({type:U.literal(`approximate`),city:U.string().optional(),region:U.string().optional(),country:U.string().optional(),timezone:U.string().optional()}).optional()}),_t=U.array(U.object({url:U.string(),title:U.string(),pageAge:U.string().nullable(),encryptedContent:U.string(),type:U.literal(`web_search_result`)})),vt=A({id:`anthropic.web_search_20250305`,name:`web_search`,inputSchema:U.object({query:U.string()}),outputSchema:_t}),yt=(e={})=>vt(e),bt=U.object({maxUses:U.number().optional(),allowedDomains:U.array(U.string()).optional(),blockedDomains:U.array(U.string()).optional(),citations:U.object({enabled:U.boolean()}).optional(),maxContentTokens:U.number().optional()}),xt=U.object({type:U.literal(`web_fetch_result`),url:U.string(),content:U.object({type:U.literal(`document`),title:U.string(),citations:U.object({enabled:U.boolean()}).optional(),source:U.union([U.object({type:U.literal(`base64`),mediaType:U.literal(`application/pdf`),data:U.string()}),U.object({type:U.literal(`text`),mediaType:U.literal(`text/plain`),data:U.string()})])}),retrievedAt:U.string().nullable()}),St=A({id:`anthropic.web_fetch_20250910`,name:`web_fetch`,inputSchema:U.object({url:U.string()}),outputSchema:xt}),Ct=(e={})=>St(e);function wt({tools:e,toolChoice:t,disableParallelToolUse:n}){e=e?.length?e:void 0;let r=[],i=new Set;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};let a=[];for(let t of e)switch(t.type){case`function`:{let e=ft(t.providerOptions);a.push({name:t.name,description:t.description,input_schema:t.inputSchema,cache_control:e});break}case`provider-defined`:switch(t.id){case`anthropic.code_execution_20250522`:i.add(`code-execution-2025-05-22`),a.push({type:`code_execution_20250522`,name:`code_execution`});break;case`anthropic.computer_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`computer`,type:`computer_20250124`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.computer_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`computer`,type:`computer_20241022`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.text_editor_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_editor`,type:`text_editor_20250124`});break;case`anthropic.text_editor_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`str_replace_editor`,type:`text_editor_20241022`});break;case`anthropic.text_editor_20250429`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`});break;case`anthropic.text_editor_20250728`:{let e=pt.parse(t.args);a.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250728`,max_characters:e.maxCharacters});break}case`anthropic.bash_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`bash`,type:`bash_20250124`});break;case`anthropic.bash_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`bash`,type:`bash_20241022`});break;case`anthropic.web_fetch_20250910`:{i.add(`web-fetch-2025-09-10`);let e=bt.parse(t.args);a.push({type:`web_fetch_20250910`,name:`web_fetch`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens});break}case`anthropic.web_search_20250305`:{let e=gt.parse(t.args);a.push({type:`web_search_20250305`,name:`web_search`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation});break}default:r.push({type:`unsupported-tool`,tool:t});break}break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:a,toolChoice:n?{type:`auto`,disable_parallel_tool_use:n}:void 0,toolWarnings:r,betas:i};let o=t.type;switch(o){case`auto`:return{tools:a,toolChoice:{type:`auto`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`required`:return{tools:a,toolChoice:{type:`any`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};case`tool`:return{tools:a,toolChoice:{type:`tool`,name:t.toolName,disable_parallel_tool_use:n},toolWarnings:r,betas:i};default:throw new b({functionality:`tool choice type: ${o}`})}}var Tt=U.object({type:U.literal(`code_execution_result`),stdout:U.string(),stderr:U.string(),return_code:U.number()}),Et=A({id:`anthropic.code_execution_20250522`,name:`code_execution`,inputSchema:U.object({code:U.string()}),outputSchema:Tt}),Dt=(e={})=>Et(e);function Ot(e){if(typeof e==`string`)return Buffer.from(e,`base64`).toString(`utf-8`);if(e instanceof Uint8Array)return new TextDecoder().decode(e);throw e instanceof URL?new b({functionality:`URL-based text documents are not supported for citations`}):new b({functionality:`unsupported data type for text documents: ${typeof e}`})}async function kt({prompt:e,sendReasoning:t,warnings:n}){let r=new Set,i=At(e),a,o=[];async function s(e){return(await L({provider:`anthropic`,providerOptions:e,schema:ut}))?.citations?.enabled??!1}async function c(e){let t=await L({provider:`anthropic`,providerOptions:e,schema:ut});return{title:t?.title,context:t?.context}}for(let e=0;e<i.length;e++){let l=i[e],u=e===i.length-1,d=l.type;switch(d){case`system`:if(a!=null)throw new b({functionality:`Multiple system messages that are separated by user/assistant messages`});a=l.messages.map(({content:e,providerOptions:t})=>({type:`text`,text:e,cache_control:ft(t)}));break;case`user`:{let e=[];for(let t of l.messages){let{role:n,content:i}=t;switch(n){case`user`:for(let n=0;n<i.length;n++){let a=i[n],o=n===i.length-1,l=ft(a.providerOptions)??(o?ft(t.providerOptions):void 0);switch(a.type){case`text`:e.push({type:`text`,text:a.text,cache_control:l});break;case`file`:if(a.mediaType.startsWith(`image/`))e.push({type:`image`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`base64`,media_type:a.mediaType===`image/*`?`image/jpeg`:a.mediaType,data:C(a.data)},cache_control:l});else if(a.mediaType===`application/pdf`){r.add(`pdfs-2024-09-25`);let t=await s(a.providerOptions),n=await c(a.providerOptions);e.push({type:`document`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`base64`,media_type:`application/pdf`,data:C(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else if(a.mediaType===`text/plain`){let t=await s(a.providerOptions),n=await c(a.providerOptions);e.push({type:`document`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`text`,media_type:`text/plain`,data:Ot(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else throw new b({functionality:`media type: ${a.mediaType}`});break}}break;case`tool`:for(let n=0;n<i.length;n++){let r=i[n],a=n===i.length-1,o=ft(r.providerOptions)??(a?ft(t.providerOptions):void 0),s=r.output,c;switch(s.type){case`content`:c=s.value.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text,cache_control:void 0};case`media`:if(e.mediaType.startsWith(`image/`))return{type:`image`,source:{type:`base64`,media_type:e.mediaType,data:e.data},cache_control:void 0};throw new b({functionality:`media type: ${e.mediaType}`})}});break;case`text`:case`error-text`:c=s.value;break;case`json`:case`error-json`:default:c=JSON.stringify(s.value);break}e.push({type:`tool_result`,tool_use_id:r.toolCallId,content:c,is_error:s.type===`error-text`||s.type===`error-json`?!0:void 0,cache_control:o})}break;default:{let e=n;throw Error(`Unsupported role: ${e}`)}}}o.push({role:`user`,content:e});break}case`assistant`:{let e=[];for(let r=0;r<l.messages.length;r++){let i=l.messages[r],a=r===l.messages.length-1,{content:o}=i;for(let r=0;r<o.length;r++){let s=o[r],c=r===o.length-1,l=ft(s.providerOptions)??(c?ft(i.providerOptions):void 0);switch(s.type){case`text`:e.push({type:`text`,text:u&&a&&c?s.text.trim():s.text,cache_control:l});break;case`reasoning`:if(t){let t=await L({provider:`anthropic`,providerOptions:s.providerOptions,schema:zt});t==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):t.signature==null?t.redactedData==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):e.push({type:`redacted_thinking`,data:t.redactedData,cache_control:l}):e.push({type:`thinking`,thinking:s.text,signature:t.signature,cache_control:l})}else n.push({type:`other`,message:`sending reasoning content is disabled for this model`});break;case`tool-call`:if(s.providerExecuted){s.toolName===`code_execution`||s.toolName===`web_fetch`||s.toolName===`web_search`?e.push({type:`server_tool_use`,id:s.toolCallId,name:s.toolName,input:s.input,cache_control:l}):n.push({type:`other`,message:`provider executed tool call for tool ${s.toolName} is not supported`});break}e.push({type:`tool_use`,id:s.toolCallId,name:s.toolName,input:s.input,cache_control:l});break;case`tool-result`:if(s.toolName===`code_execution`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=Tt.parse(t.value);e.push({type:`code_execution_tool_result`,tool_use_id:s.toolCallId,content:{type:r.type,stdout:r.stdout,stderr:r.stderr,return_code:r.return_code},cache_control:l});break}if(s.toolName===`web_fetch`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=xt.parse(t.value);e.push({type:`web_fetch_tool_result`,tool_use_id:s.toolCallId,content:{type:`web_fetch_result`,url:r.url,retrieved_at:r.retrievedAt,content:{type:`document`,title:r.content.title,citations:r.content.citations,source:{type:r.content.source.type,media_type:r.content.source.mediaType,data:r.content.source.data}}},cache_control:l});break}if(s.toolName===`web_search`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=_t.parse(t.value);e.push({type:`web_search_tool_result`,tool_use_id:s.toolCallId,content:r.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:l});break}n.push({type:`other`,message:`provider executed tool result for tool ${s.toolName} is not supported`});break}}}o.push({role:`assistant`,content:e});break}default:{let e=d;throw Error(`content type: ${e}`)}}}return{prompt:{system:a,messages:o},betas:r}}function At(e){let t=[],n;for(let r of e){let{role:e}=r;switch(e){case`system`:n?.type!==`system`&&(n={type:`system`,messages:[]},t.push(n)),n.messages.push(r);break;case`assistant`:n?.type!==`assistant`&&(n={type:`assistant`,messages:[]},t.push(n)),n.messages.push(r);break;case`user`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;case`tool`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;default:{let t=e;throw Error(`Unsupported role: ${t}`)}}}return t}function jt({finishReason:e,isJsonResponseFromTool:t}){switch(e){case`pause_turn`:case`end_turn`:case`stop_sequence`:return`stop`;case`refusal`:return`content-filter`;case`tool_use`:return t?`stop`:`tool-calls`;case`max_tokens`:return`length`;default:return`unknown`}}var Mt={webSearchResult:U.object({type:U.literal(`web_search_result_location`),cited_text:U.string(),url:U.string(),title:U.string(),encrypted_index:U.string()}),pageLocation:U.object({type:U.literal(`page_location`),cited_text:U.string(),document_index:U.number(),document_title:U.string().nullable(),start_page_number:U.number(),end_page_number:U.number()}),charLocation:U.object({type:U.literal(`char_location`),cited_text:U.string(),document_index:U.number(),document_title:U.string().nullable(),start_char_index:U.number(),end_char_index:U.number()})},Nt=U.discriminatedUnion(`type`,[Mt.webSearchResult,Mt.pageLocation,Mt.charLocation]);U.discriminatedUnion(`type`,[Mt.pageLocation,Mt.charLocation]);function Pt(e,t,n,r){if(e.type===`page_location`||e.type===`char_location`){let i=Ft(e,t,n);i&&r(i)}}function Ft(e,t,n){let r=t[e.document_index];if(!r)return null;let i=e.type===`page_location`?{citedText:e.cited_text,startPageNumber:e.start_page_number,endPageNumber:e.end_page_number}:{citedText:e.cited_text,startCharIndex:e.start_char_index,endCharIndex:e.end_char_index};return{type:`source`,sourceType:`document`,id:n(),mediaType:r.mediaType,title:e.document_title??r.title,filename:r.filename,providerMetadata:{anthropic:i}}}var It=class{constructor(e,t){this.specificationVersion=`v2`,this.modelId=e,this.config=t,this.generateId=t.generateId??M}supportsUrl(e){return e.protocol===`https:`}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:t=4096,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){let p=[];a!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),l!=null&&p.push({type:`unsupported-setting`,setting:`seed`}),c?.type===`json`&&(c.schema==null?p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format requires a schema. The response format is ignored.`}):u!=null&&p.push({type:`unsupported-setting`,setting:`tools`,details:`JSON response format does not support tools. The provided tools are ignored.`}));let m=c?.type===`json`&&c.schema!=null?{type:`function`,name:`json`,description:`Respond with a JSON object.`,inputSchema:c.schema}:void 0,h=await L({provider:`anthropic`,providerOptions:f,schema:dt}),{prompt:g,betas:_}=await kt({prompt:e,sendReasoning:h?.sendReasoning??!0,warnings:p}),v=h?.thinking?.type===`enabled`,y=h?.thinking?.budgetTokens,x={model:this.modelId,max_tokens:t,temperature:n,top_k:i,top_p:r,stop_sequences:s,...v&&{thinking:{type:`enabled`,budget_tokens:y}},system:g.system,messages:g.messages};if(v){if(y==null)throw new b({functionality:`thinking requires a budget`});x.temperature!=null&&(x.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported when thinking is enabled`})),i!=null&&(x.top_k=void 0,p.push({type:`unsupported-setting`,setting:`topK`,details:`topK is not supported when thinking is enabled`})),r!=null&&(x.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported when thinking is enabled`})),x.max_tokens=t+y}let{tools:S,toolChoice:C,toolWarnings:w,betas:T}=wt(m==null?{tools:u??[],toolChoice:d,disableParallelToolUse:h?.disableParallelToolUse}:{tools:[m],toolChoice:{type:`tool`,toolName:m.name},disableParallelToolUse:!0});return{args:{...x,tools:S,tool_choice:C},warnings:[...p,...w],betas:new Set([..._,...T]),usesJsonResponseTool:m!=null}}async getHeaders({betas:e,headers:t}){return x(await B(this.config.headers),e.size>0?{"anthropic-beta":Array.from(e).join(`,`)}:{},t)}buildRequestUrl(e){var t;return(t=this.config).buildRequestUrl?.call(t,this.config.baseURL,e)??`${this.config.baseURL}/messages`}transformRequestBody(e){var t;return(t=this.config).transformRequestBody?.call(t,e)??e}extractCitationDocuments(e){return e.filter(e=>e.role===`user`).flatMap(e=>e.content).filter(e=>e.type!==`file`||e.mediaType!==`application/pdf`&&e.mediaType!==`text/plain`?!1:e.providerOptions?.anthropic?.citations?.enabled??!1).map(e=>{let t=e;return{title:t.filename??`Untitled Document`,filename:t.filename,mediaType:t.mediaType}})}async doGenerate(e){let{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),a=this.extractCitationDocuments(e.prompt),{responseHeaders:o,value:s,rawValue:c}=await z({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(t),failedResponseHandler:lt,successfulResponseHandler:O(Lt),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=[];for(let e of s.content)switch(e.type){case`text`:if(!i&&(l.push({type:`text`,text:e.text}),e.citations))for(let t of e.citations)Pt(t,a,this.generateId,e=>l.push(e));break;case`thinking`:l.push({type:`reasoning`,text:e.thinking,providerMetadata:{anthropic:{signature:e.signature}}});break;case`redacted_thinking`:l.push({type:`reasoning`,text:``,providerMetadata:{anthropic:{redactedData:e.data}}});break;case`tool_use`:l.push(i?{type:`text`,text:JSON.stringify(e.input)}:{type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input)});break;case`server_tool_use`:(e.name===`web_search`||e.name===`code_execution`||e.name===`web_fetch`)&&l.push({type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input),providerExecuted:!0});break;case`web_fetch_tool_result`:e.content.type===`web_fetch_result`?l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,result:{type:`web_fetch_result`,url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}},providerExecuted:!0}):e.content.type===`web_fetch_tool_result_error`&&l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,isError:!0,result:{type:`web_fetch_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break;case`web_search_tool_result`:if(Array.isArray(e.content)){l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type})),providerExecuted:!0});for(let t of e.content)l.push({type:`source`,sourceType:`url`,id:this.generateId(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break;case`code_execution_tool_result`:e.content.type===`code_execution_result`?l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break}return{content:l,finishReason:jt({finishReason:s.stop_reason,isJsonResponseFromTool:i}),usage:{inputTokens:s.usage.input_tokens,outputTokens:s.usage.output_tokens,totalTokens:s.usage.input_tokens+s.usage.output_tokens,cachedInputTokens:s.usage.cache_read_input_tokens??void 0},request:{body:t},response:{id:s.id??void 0,modelId:s.model??void 0,headers:o,body:c},warnings:n,providerMetadata:{anthropic:{usage:s.usage,cacheCreationInputTokens:s.usage.cache_creation_input_tokens??null,stopSequence:s.stop_sequence??null}}}}async doStream(e){let{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),a=this.extractCitationDocuments(e.prompt),o={...t,stream:!0},{responseHeaders:s,value:c}=await z({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(o),failedResponseHandler:lt,successfulResponseHandler:T(Rt),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=`unknown`,u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},d={},f,p=null,m=null,h,g=this.generateId;return{stream:c.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let r=t.value;switch(r.type){case`ping`:return;case`content_block_start`:{let e=r.content_block.type;switch(h=e,e){case`text`:d[r.index]={type:`text`},n.enqueue({type:`text-start`,id:String(r.index)});return;case`thinking`:d[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index)});return;case`redacted_thinking`:d[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index),providerMetadata:{anthropic:{redactedData:r.content_block.data}}});return;case`tool_use`:d[r.index]=i?{type:`text`}:{type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``},n.enqueue(i?{type:`text-start`,id:String(r.index)}:{type:`tool-input-start`,id:r.content_block.id,toolName:r.content_block.name});return;case`server_tool_use`:(r.content_block.name===`web_fetch`||r.content_block.name===`web_search`||r.content_block.name===`code_execution`)&&(d[r.index]={type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``,providerExecuted:!0},n.enqueue({type:`tool-input-start`,id:r.content_block.id,toolName:r.content_block.name,providerExecuted:!0}));return;case`web_fetch_tool_result`:{let e=r.content_block;e.content.type===`web_fetch_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,result:{type:`web_fetch_result`,url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}}}):e.content.type===`web_fetch_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,isError:!0,result:{type:`web_fetch_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}case`web_search_tool_result`:{let e=r.content_block;if(Array.isArray(e.content)){n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type})),providerExecuted:!0});for(let t of e.content)n.enqueue({type:`source`,sourceType:`url`,id:g(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}case`code_execution_tool_result`:{let e=r.content_block;e.content.type===`code_execution_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}default:{let t=e;throw Error(`Unsupported content block type: ${t}`)}}}case`content_block_stop`:if(d[r.index]!=null){let e=d[r.index];switch(e.type){case`text`:n.enqueue({type:`text-end`,id:String(r.index)});break;case`reasoning`:n.enqueue({type:`reasoning-end`,id:String(r.index)});break;case`tool-call`:i||(n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue(e));break}delete d[r.index]}h=void 0;return;case`content_block_delta`:{let e=r.delta.type;switch(e){case`text_delta`:if(i)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:r.delta.text});return;case`thinking_delta`:n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:r.delta.thinking});return;case`signature_delta`:h===`thinking`&&n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:``,providerMetadata:{anthropic:{signature:r.delta.signature}}});return;case`input_json_delta`:{let e=d[r.index],t=r.delta.partial_json;if(i){if(e?.type!==`text`)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:t})}else{if(e?.type!==`tool-call`)return;n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:t}),e.input+=t}return}case`citations_delta`:{let e=r.delta.citation;Pt(e,a,g,e=>n.enqueue(e));return}default:{let t=e;throw Error(`Unsupported delta type: ${t}`)}}}case`message_start`:u.inputTokens=r.message.usage.input_tokens,u.cachedInputTokens=r.message.usage.cache_read_input_tokens??void 0,f={...r.message.usage},p=r.message.usage.cache_creation_input_tokens??null,n.enqueue({type:`response-metadata`,id:r.message.id??void 0,modelId:r.message.model??void 0});return;case`message_delta`:u.outputTokens=r.usage.output_tokens,u.totalTokens=(u.inputTokens??0)+(r.usage.output_tokens??0),l=jt({finishReason:r.delta.stop_reason,isJsonResponseFromTool:i}),m=r.delta.stop_sequence??null,f={...f,...r.usage};return;case`message_stop`:n.enqueue({type:`finish`,finishReason:l,usage:u,providerMetadata:{anthropic:{usage:f??null,cacheCreationInputTokens:p,stopSequence:m}}});return;case`error`:n.enqueue({type:`error`,error:r.error});return;default:{let e=r;throw Error(`Unsupported chunk type: ${e}`)}}}})),request:{body:o},response:{headers:s}}}},Lt=U.object({type:U.literal(`message`),id:U.string().nullish(),model:U.string().nullish(),content:U.array(U.discriminatedUnion(`type`,[U.object({type:U.literal(`text`),text:U.string(),citations:U.array(Nt).optional()}),U.object({type:U.literal(`thinking`),thinking:U.string(),signature:U.string()}),U.object({type:U.literal(`redacted_thinking`),data:U.string()}),U.object({type:U.literal(`tool_use`),id:U.string(),name:U.string(),input:U.unknown()}),U.object({type:U.literal(`server_tool_use`),id:U.string(),name:U.string(),input:U.record(U.string(),U.unknown()).nullish()}),U.object({type:U.literal(`web_fetch_tool_result`),tool_use_id:U.string(),content:U.union([U.object({type:U.literal(`web_fetch_result`),url:U.string(),retrieved_at:U.string(),content:U.object({type:U.literal(`document`),title:U.string().nullable(),citations:U.object({enabled:U.boolean()}).optional(),source:U.object({type:U.literal(`text`),media_type:U.string(),data:U.string()})})}),U.object({type:U.literal(`web_fetch_tool_result_error`),error_code:U.string()})])}),U.object({type:U.literal(`web_search_tool_result`),tool_use_id:U.string(),content:U.union([U.array(U.object({type:U.literal(`web_search_result`),url:U.string(),title:U.string(),encrypted_content:U.string(),page_age:U.string().nullish()})),U.object({type:U.literal(`web_search_tool_result_error`),error_code:U.string()})])}),U.object({type:U.literal(`code_execution_tool_result`),tool_use_id:U.string(),content:U.union([U.object({type:U.literal(`code_execution_result`),stdout:U.string(),stderr:U.string(),return_code:U.number()}),U.object({type:U.literal(`code_execution_tool_result_error`),error_code:U.string()})])})])),stop_reason:U.string().nullish(),stop_sequence:U.string().nullish(),usage:U.looseObject({input_tokens:U.number(),output_tokens:U.number(),cache_creation_input_tokens:U.number().nullish(),cache_read_input_tokens:U.number().nullish()})}),Rt=U.discriminatedUnion(`type`,[U.object({type:U.literal(`message_start`),message:U.object({id:U.string().nullish(),model:U.string().nullish(),usage:U.looseObject({input_tokens:U.number(),cache_creation_input_tokens:U.number().nullish(),cache_read_input_tokens:U.number().nullish()})})}),U.object({type:U.literal(`content_block_start`),index:U.number(),content_block:U.discriminatedUnion(`type`,[U.object({type:U.literal(`text`),text:U.string()}),U.object({type:U.literal(`thinking`),thinking:U.string()}),U.object({type:U.literal(`tool_use`),id:U.string(),name:U.string()}),U.object({type:U.literal(`redacted_thinking`),data:U.string()}),U.object({type:U.literal(`server_tool_use`),id:U.string(),name:U.string(),input:U.record(U.string(),U.unknown()).nullish()}),U.object({type:U.literal(`web_fetch_tool_result`),tool_use_id:U.string(),content:U.union([U.object({type:U.literal(`web_fetch_result`),url:U.string(),retrieved_at:U.string(),content:U.object({type:U.literal(`document`),title:U.string().nullable(),citations:U.object({enabled:U.boolean()}).optional(),source:U.object({type:U.literal(`text`),media_type:U.string(),data:U.string()})})}),U.object({type:U.literal(`web_fetch_tool_result_error`),error_code:U.string()})])}),U.object({type:U.literal(`web_search_tool_result`),tool_use_id:U.string(),content:U.union([U.array(U.object({type:U.literal(`web_search_result`),url:U.string(),title:U.string(),encrypted_content:U.string(),page_age:U.string().nullish()})),U.object({type:U.literal(`web_search_tool_result_error`),error_code:U.string()})])}),U.object({type:U.literal(`code_execution_tool_result`),tool_use_id:U.string(),content:U.union([U.object({type:U.literal(`code_execution_result`),stdout:U.string(),stderr:U.string(),return_code:U.number()}),U.object({type:U.literal(`code_execution_tool_result_error`),error_code:U.string()})])})])}),U.object({type:U.literal(`content_block_delta`),index:U.number(),delta:U.discriminatedUnion(`type`,[U.object({type:U.literal(`input_json_delta`),partial_json:U.string()}),U.object({type:U.literal(`text_delta`),text:U.string()}),U.object({type:U.literal(`thinking_delta`),thinking:U.string()}),U.object({type:U.literal(`signature_delta`),signature:U.string()}),U.object({type:U.literal(`citations_delta`),citation:Nt})])}),U.object({type:U.literal(`content_block_stop`),index:U.number()}),U.object({type:U.literal(`error`),error:U.object({type:U.string(),message:U.string()})}),U.object({type:U.literal(`message_delta`),delta:U.object({stop_reason:U.string().nullish(),stop_sequence:U.string().nullish()}),usage:U.looseObject({output_tokens:U.number(),cache_creation_input_tokens:U.number().nullish()})}),U.object({type:U.literal(`message_stop`)}),U.object({type:U.literal(`ping`)})]),zt=U.object({signature:U.string().optional(),redactedData:U.string().optional()}),Bt=k({id:`anthropic.bash_20241022`,name:`bash`,inputSchema:ce.object({command:ce.string(),restart:ce.boolean().optional()})}),Vt=k({id:`anthropic.bash_20250124`,name:`bash`,inputSchema:ce.object({command:ce.string(),restart:ce.boolean().optional()})}),Ht=k({id:`anthropic.computer_20241022`,name:`computer`,inputSchema:U.object({action:U.enum([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:U.array(U.number().int()).optional(),text:U.string().optional()})}),Ut=k({id:`anthropic.computer_20250124`,name:`computer`,inputSchema:U.object({action:U.enum([`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:U.tuple([U.number().int(),U.number().int()]).optional(),duration:U.number().optional(),scroll_amount:U.number().optional(),scroll_direction:U.enum([`up`,`down`,`left`,`right`]).optional(),start_coordinate:U.tuple([U.number().int(),U.number().int()]).optional(),text:U.string().optional()})}),Wt=k({id:`anthropic.text_editor_20241022`,name:`str_replace_editor`,inputSchema:U.object({command:U.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:U.string(),file_text:U.string().optional(),insert_line:U.number().int().optional(),new_str:U.string().optional(),old_str:U.string().optional(),view_range:U.array(U.number().int()).optional()})}),Gt=k({id:`anthropic.text_editor_20250124`,name:`str_replace_editor`,inputSchema:U.object({command:U.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:U.string(),file_text:U.string().optional(),insert_line:U.number().int().optional(),new_str:U.string().optional(),old_str:U.string().optional(),view_range:U.array(U.number().int()).optional()})}),Kt=k({id:`anthropic.text_editor_20250429`,name:`str_replace_based_edit_tool`,inputSchema:U.object({command:U.enum([`view`,`create`,`str_replace`,`insert`]),path:U.string(),file_text:U.string().optional(),insert_line:U.number().int().optional(),new_str:U.string().optional(),old_str:U.string().optional(),view_range:U.array(U.number().int()).optional()})}),qt={bash_20241022:Bt,bash_20250124:Vt,codeExecution_20250522:Dt,computer_20241022:Ht,computer_20250124:Ut,textEditor_20241022:Wt,textEditor_20250124:Gt,textEditor_20250429:Kt,textEditor_20250728:ht,webFetch_20250910:Ct,webSearch_20250305:yt};function Jt(e={}){let t=oe(e.baseURL)??`https://api.anthropic.com/v1`,n=()=>ae({"anthropic-version":`2023-06-01`,"x-api-key":ne({apiKey:e.apiKey,environmentVariableName:`ANTHROPIC_API_KEY`,description:`Anthropic`}),...e.headers},`ai-sdk/anthropic/${st}`),r=r=>new It(r,{provider:`anthropic.messages`,baseURL:t,headers:n,fetch:e.fetch,generateId:e.generateId??M,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})}),i=function(e){if(new.target)throw Error(`The Anthropic model function cannot be called with the new keyword.`);return r(e)};return i.languageModel=r,i.chat=r,i.messages=r,i.textEmbeddingModel=e=>{throw new g({modelId:e,modelType:`textEmbeddingModel`})},i.imageModel=e=>{throw new g({modelId:e,modelType:`imageModel`})},i.tools=qt,i}Jt();var Yt=`2.0.17`,Xt=U.object({error:U.object({code:U.number().nullable(),message:U.string(),status:U.string()})}),Zt=D({errorSchema:Xt,errorToMessage:e=>e.error.message}),Qt=U.object({outputDimensionality:U.number().optional(),taskType:U.enum([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional()}),$t=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){let i=await L({provider:`google`,providerOptions:r,schema:Qt});if(e.length>this.maxEmbeddingsPerCall)throw new v({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let a=x(await B(this.config.headers),t);if(e.length===1){let{responseHeaders:t,value:r,rawValue:o}=await z({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:a,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType},failedResponseHandler:Zt,successfulResponseHandler:O(tn),abortSignal:n,fetch:this.config.fetch});return{embeddings:[r.embedding.values],usage:void 0,response:{headers:t,body:o}}}let{responseHeaders:o,value:s,rawValue:c}=await z({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:a,body:{requests:e.map(e=>({model:`models/${this.modelId}`,content:{role:`user`,parts:[{text:e}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType}))},failedResponseHandler:Zt,successfulResponseHandler:O(en),abortSignal:n,fetch:this.config.fetch});return{embeddings:s.embeddings.map(e=>e.values),usage:void 0,response:{headers:o,body:c}}}},en=U.object({embeddings:U.array(U.object({values:U.array(U.number())}))}),tn=U.object({embedding:U.object({values:U.array(U.number())})});function nn(e){if(e==null||rn(e))return;if(typeof e==`boolean`)return{type:`boolean`,properties:{}};let{type:t,description:n,required:r,properties:i,items:a,allOf:o,anyOf:s,oneOf:c,format:l,const:u,minLength:d,enum:f}=e,p={};if(n&&(p.description=n),r&&(p.required=r),l&&(p.format=l),u!==void 0&&(p.enum=[u]),t&&(Array.isArray(t)?t.includes(`null`)?(p.type=t.filter(e=>e!==`null`)[0],p.nullable=!0):p.type=t:t===`null`?p.type=`null`:p.type=t),f!==void 0&&(p.enum=f),i!=null&&(p.properties=Object.entries(i).reduce((e,[t,n])=>(e[t]=nn(n),e),{})),a&&(p.items=Array.isArray(a)?a.map(nn):nn(a)),o&&(p.allOf=o.map(nn)),s)if(s.some(e=>typeof e==`object`&&e?.type===`null`)){let e=s.filter(e=>!(typeof e==`object`&&e?.type===`null`));if(e.length===1){let t=nn(e[0]);typeof t==`object`&&(p.nullable=!0,Object.assign(p,t))}else p.anyOf=e.map(nn),p.nullable=!0}else p.anyOf=s.map(nn);return c&&(p.oneOf=c.map(nn)),d!==void 0&&(p.minLength=d),p}function rn(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}function an(e,t){let n=[],r=[],i=!0,a=t?.isGemmaModel??!1;for(let{role:t,content:a}of e)switch(t){case`system`:if(!i)throw new b({functionality:`system messages are only supported at the beginning of the conversation`});n.push({text:a});break;case`user`:{i=!1;let e=[];for(let t of a)switch(t.type){case`text`:e.push({text:t.text});break;case`file`:{let n=t.mediaType===`image/*`?`image/jpeg`:t.mediaType;e.push(t.data instanceof URL?{fileData:{mimeType:n,fileUri:t.data.toString()}}:{inlineData:{mimeType:n,data:C(t.data)}});break}}r.push({role:`user`,parts:e});break}case`assistant`:i=!1,r.push({role:`model`,parts:a.map(e=>{switch(e.type){case`text`:return e.text.length===0?void 0:{text:e.text,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`reasoning`:return e.text.length===0?void 0:{text:e.text,thought:!0,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`file`:if(e.mediaType!==`image/png`)throw new b({functionality:`Only PNG images are supported in assistant messages`});if(e.data instanceof URL)throw new b({functionality:`File data URLs in assistant messages are not supported`});return{inlineData:{mimeType:e.mediaType,data:C(e.data)}};case`tool-call`:return{functionCall:{name:e.toolName,args:e.input},thoughtSignature:e.providerOptions?.google?.thoughtSignature}}}).filter(e=>e!==void 0)});break;case`tool`:{i=!1;let e=[];for(let t of a){let n=t.output;if(n.type===`content`)for(let r of n.value)switch(r.type){case`text`:e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:r.text}}});break;case`media`:e.push({inlineData:{mimeType:r.mediaType,data:r.data}},{text:`Tool executed successfully and returned this image as a response`});break;default:e.push({text:JSON.stringify(r)});break}else e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:n.value}}})}r.push({role:`user`,parts:e});break}}if(a&&n.length>0&&r.length>0&&r[0].role===`user`){let e=n.map(e=>e.text).join(`
|
|
2
2
|
|
|
3
3
|
`);r[0].parts.unshift({text:e+`
|
|
4
4
|
|
|
5
|
-
`})}return{systemInstruction:n.length>0&&!a?{parts:n}:void 0,contents:r}}function on(e){return e.includes(`/`)?e:`models/${e}`}var sn=U.object({responseModalities:U.array(U.enum([`TEXT`,`IMAGE`])).optional(),thinkingConfig:U.object({thinkingBudget:U.number().optional(),includeThoughts:U.boolean().optional()}).optional(),cachedContent:U.string().optional(),structuredOutputs:U.boolean().optional(),safetySettings:U.array(U.object({category:U.enum([`HARM_CATEGORY_UNSPECIFIED`,`HARM_CATEGORY_HATE_SPEECH`,`HARM_CATEGORY_DANGEROUS_CONTENT`,`HARM_CATEGORY_HARASSMENT`,`HARM_CATEGORY_SEXUALLY_EXPLICIT`,`HARM_CATEGORY_CIVIC_INTEGRITY`]),threshold:U.enum([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`])})).optional(),threshold:U.enum([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`]).optional(),audioTimestamp:U.boolean().optional(),labels:U.record(U.string(),U.string()).optional()});function cn({tools:e,toolChoice:t,modelId:n}){e=e?.length?e:void 0;let r=[],i=n.includes(`gemini-2`),a=n.includes(`gemini-1.5-flash`)&&!n.includes(`-8b`);if(e==null)return{tools:void 0,toolConfig:void 0,toolWarnings:r};let o=e.some(e=>e.type===`function`),s=e.some(e=>e.type===`provider-defined`);if(o&&s&&r.push({type:`unsupported-tool`,tool:e.find(e=>e.type===`function`),details:`Cannot mix function tools with provider-defined tools in the same request. Please use either function tools or provider-defined tools, but not both.`}),s){let t={};return e.filter(e=>e.type===`provider-defined`).forEach(e=>{switch(e.id){case`google.google_search`:i?t.googleSearch={}:a?t.googleSearchRetrieval={dynamicRetrievalConfig:{mode:e.args.mode,dynamicThreshold:e.args.dynamicThreshold}}:t.googleSearchRetrieval={};break;case`google.url_context`:i?t.urlContext={}:r.push({type:`unsupported-tool`,tool:e,details:`The URL context tool is not supported with other Gemini models than Gemini 2.`});break;case`google.code_execution`:i?t.codeExecution={}:r.push({type:`unsupported-tool`,tool:e,details:`The code execution tools is not supported with other Gemini models than Gemini 2.`});break;default:r.push({type:`unsupported-tool`,tool:e});break}}),{tools:Object.keys(t).length>0?t:void 0,toolConfig:void 0,toolWarnings:r}}let c=[];for(let t of e)switch(t.type){case`function`:c.push({name:t.name,description:t.description??``,parameters:nn(t.inputSchema)});break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:{functionDeclarations:c},toolConfig:void 0,toolWarnings:r};let l=t.type;switch(l){case`auto`:return{tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:`AUTO`}},toolWarnings:r};case`none`:return{tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:`NONE`}},toolWarnings:r};case`required`:return{tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:`ANY`}},toolWarnings:r};case`tool`:return{tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:`ANY`,allowedFunctionNames:[t.toolName]}},toolWarnings:r};default:throw new b({functionality:`tool choice type: ${l}`})}}function ln({finishReason:e,hasToolCalls:t}){switch(e){case`STOP`:return t?`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`FINISH_REASON_UNSPECIFIED`:case`OTHER`:return`other`;case`MALFORMED_FUNCTION_CALL`:return`error`;default:return`unknown`}}var un=U.object({web:U.object({uri:U.string(),title:U.string()}).nullish(),retrievedContext:U.object({uri:U.string(),title:U.string()}).nullish()}),dn=U.object({webSearchQueries:U.array(U.string()).nullish(),retrievalQueries:U.array(U.string()).nullish(),searchEntryPoint:U.object({renderedContent:U.string()}).nullish(),groundingChunks:U.array(un).nullish(),groundingSupports:U.array(U.object({segment:U.object({startIndex:U.number().nullish(),endIndex:U.number().nullish(),text:U.string().nullish()}),segment_text:U.string().nullish(),groundingChunkIndices:U.array(U.number()).nullish(),supportChunkIndices:U.array(U.number()).nullish(),confidenceScores:U.array(U.number()).nullish(),confidenceScore:U.array(U.number()).nullish()})).nullish(),retrievalMetadata:U.union([U.object({webDynamicRetrievalScore:U.number()}),U.object({})]).nullish()}),fn=O({id:`google.google_search`,name:`google_search`,inputSchema:U.object({mode:U.enum([`MODE_DYNAMIC`,`MODE_UNSPECIFIED`]).default(`MODE_UNSPECIFIED`),dynamicThreshold:U.number().default(1)})}),pn=U.object({retrievedUrl:U.string(),urlRetrievalStatus:U.string()}),mn=U.object({urlMetadata:U.array(pn)}),hn=O({id:`google.url_context`,name:`url_context`,inputSchema:U.object({})}),gn=class{constructor(e,t){this.specificationVersion=`v2`,this.modelId=e,this.config=t,this.generateId=t.generateId??j}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){let p=[],m=await L({provider:`google`,providerOptions:f,schema:sn});m?.thinkingConfig?.includeThoughts===!0&&!this.config.provider.startsWith(`google.vertex.`)&&p.push({type:`other`,message:`The 'includeThoughts' option 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}).`});let h=this.modelId.toLowerCase().startsWith(`gemma-`),{contents:g,systemInstruction:_}=an(e,{isGemmaModel:h}),{tools:v,toolConfig:y,toolWarnings:b}=cn({tools:u,toolChoice:d,modelId:this.modelId});return{args:{generationConfig:{maxOutputTokens:t,temperature:n,topK:i,topP:r,frequencyPenalty:a,presencePenalty:o,stopSequences:s,seed:l,responseMimeType:c?.type===`json`?`application/json`:void 0,responseSchema:c?.type===`json`&&c.schema!=null&&(m?.structuredOutputs??!0)?nn(c.schema):void 0,...m?.audioTimestamp&&{audioTimestamp:m.audioTimestamp},responseModalities:m?.responseModalities,thinkingConfig:m?.thinkingConfig},contents:g,systemInstruction:h?void 0:_,safetySettings:m?.safetySettings,tools:v,toolConfig:y,cachedContent:m?.cachedContent,labels:m?.labels},warnings:[...p,...b]}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),r=JSON.stringify(t),i=x(await B(this.config.headers),e.headers),{responseHeaders:a,value:o,rawValue:s}=await z({url:`${this.config.baseURL}/${on(this.modelId)}:generateContent`,headers:i,body:t,failedResponseHandler:Zt,successfulResponseHandler:D(Cn),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=o.candidates[0],l=[],u=c.content?.parts??[],d=o.usageMetadata,f;for(let e of u)if(`executableCode`in e&&e.executableCode?.code){let t=this.config.generateId();f=t,l.push({type:`tool-call`,toolCallId:t,toolName:`code_execution`,input:JSON.stringify(e.executableCode),providerExecuted:!0})}else `codeExecutionResult`in e&&e.codeExecutionResult?(l.push({type:`tool-result`,toolCallId:f,toolName:`code_execution`,result:{outcome:e.codeExecutionResult.outcome,output:e.codeExecutionResult.output},providerExecuted:!0}),f=void 0):`text`in e&&e.text!=null&&e.text.length>0?l.push({type:e.thought===!0?`reasoning`:`text`,text:e.text,providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0}):`functionCall`in e?l.push({type:`tool-call`,toolCallId:this.config.generateId(),toolName:e.functionCall.name,input:JSON.stringify(e.functionCall.args),providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0}):`inlineData`in e&&l.push({type:`file`,data:e.inlineData.data,mediaType:e.inlineData.mimeType});let p=yn({groundingMetadata:c.groundingMetadata,generateId:this.config.generateId})??[];for(let e of p)l.push(e);return{content:l,finishReason:ln({finishReason:c.finishReason,hasToolCalls:l.some(e=>e.type===`tool-call`)}),usage:{inputTokens:d?.promptTokenCount??void 0,outputTokens:d?.candidatesTokenCount??void 0,totalTokens:d?.totalTokenCount??void 0,reasoningTokens:d?.thoughtsTokenCount??void 0,cachedInputTokens:d?.cachedContentTokenCount??void 0},warnings:n,providerMetadata:{google:{promptFeedback:o.promptFeedback??null,groundingMetadata:c.groundingMetadata??null,urlContextMetadata:c.urlContextMetadata??null,safetyRatings:c.safetyRatings??null,usageMetadata:d??null}},request:{body:r},response:{headers:a,body:s}}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r=JSON.stringify(t),i=x(await B(this.config.headers),e.headers),{responseHeaders:a,value:o}=await z({url:`${this.config.baseURL}/${on(this.modelId)}:streamGenerateContent?alt=sse`,headers:i,body:t,failedResponseHandler:Zt,successfulResponseHandler:T(wn),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l,u=this.config.generateId,d=!1,f=null,p=null,m=0,h=new Set,g;return{stream:o.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let r=t.value,i=r.usageMetadata;i!=null&&(c.inputTokens=i.promptTokenCount??void 0,c.outputTokens=i.candidatesTokenCount??void 0,c.totalTokens=i.totalTokenCount??void 0,c.reasoningTokens=i.thoughtsTokenCount??void 0,c.cachedInputTokens=i.cachedContentTokenCount??void 0);let a=r.candidates?.[0];if(a==null)return;let o=a.content,_=yn({groundingMetadata:a.groundingMetadata,generateId:u});if(_!=null)for(let e of _)e.sourceType===`url`&&!h.has(e.url)&&(h.add(e.url),n.enqueue(e));if(o!=null){let e=o.parts??[];for(let t of e)if(`executableCode`in t&&t.executableCode?.code){let e=u();g=e,n.enqueue({type:`tool-call`,toolCallId:e,toolName:`code_execution`,input:JSON.stringify(t.executableCode),providerExecuted:!0}),d=!0}else if(`codeExecutionResult`in t&&t.codeExecutionResult){let e=g;e&&(n.enqueue({type:`tool-result`,toolCallId:e,toolName:`code_execution`,result:{outcome:t.codeExecutionResult.outcome,output:t.codeExecutionResult.output},providerExecuted:!0}),g=void 0)}else `text`in t&&t.text!=null&&t.text.length>0&&(t.thought===!0?(f!==null&&(n.enqueue({type:`text-end`,id:f}),f=null),p===null&&(p=String(m++),n.enqueue({type:`reasoning-start`,id:p,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})),n.enqueue({type:`reasoning-delta`,id:p,delta:t.text,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})):(p!==null&&(n.enqueue({type:`reasoning-end`,id:p}),p=null),f===null&&(f=String(m++),n.enqueue({type:`text-start`,id:f,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})),n.enqueue({type:`text-delta`,id:f,delta:t.text,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})));let t=vn(o.parts);if(t!=null)for(let e of t)n.enqueue({type:`file`,mediaType:e.inlineData.mimeType,data:e.inlineData.data});let r=_n({parts:o.parts,generateId:u});if(r!=null)for(let e of r)n.enqueue({type:`tool-input-start`,id:e.toolCallId,toolName:e.toolName,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:e.args,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-input-end`,id:e.toolCallId,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.args,providerMetadata:e.providerMetadata}),d=!0}a.finishReason!=null&&(s=ln({finishReason:a.finishReason,hasToolCalls:d}),l={google:{promptFeedback:r.promptFeedback??null,groundingMetadata:a.groundingMetadata??null,urlContextMetadata:a.urlContextMetadata??null,safetyRatings:a.safetyRatings??null}},i!=null&&(l.google.usageMetadata=i))},flush(e){f!==null&&e.enqueue({type:`text-end`,id:f}),p!==null&&e.enqueue({type:`reasoning-end`,id:p}),e.enqueue({type:`finish`,finishReason:s,usage:c,providerMetadata:l})}})),response:{headers:a},request:{body:r}}}};function _n({parts:e,generateId:t}){let n=e?.filter(e=>`functionCall`in e);return n==null||n.length===0?void 0:n.map(e=>({type:`tool-call`,toolCallId:t(),toolName:e.functionCall.name,args:JSON.stringify(e.functionCall.args),providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0}))}function vn(e){return e?.filter(e=>`inlineData`in e)}function yn({groundingMetadata:e,generateId:t}){return(e?.groundingChunks)?.filter(e=>e.web!=null).map(e=>({type:`source`,sourceType:`url`,id:t(),url:e.web.uri,title:e.web.title}))}var bn=U.object({parts:U.array(U.union([U.object({functionCall:U.object({name:U.string(),args:U.unknown()}),thoughtSignature:U.string().nullish()}),U.object({inlineData:U.object({mimeType:U.string(),data:U.string()})}),U.object({executableCode:U.object({language:U.string(),code:U.string()}).nullish(),codeExecutionResult:U.object({outcome:U.string(),output:U.string()}).nullish(),text:U.string().nullish(),thought:U.boolean().nullish(),thoughtSignature:U.string().nullish()})])).nullish()}),xn=U.object({category:U.string().nullish(),probability:U.string().nullish(),probabilityScore:U.number().nullish(),severity:U.string().nullish(),severityScore:U.number().nullish(),blocked:U.boolean().nullish()}),Sn=U.object({cachedContentTokenCount:U.number().nullish(),thoughtsTokenCount:U.number().nullish(),promptTokenCount:U.number().nullish(),candidatesTokenCount:U.number().nullish(),totalTokenCount:U.number().nullish()}),Cn=U.object({candidates:U.array(U.object({content:bn.nullish().or(U.object({}).strict()),finishReason:U.string().nullish(),safetyRatings:U.array(xn).nullish(),groundingMetadata:dn.nullish(),urlContextMetadata:mn.nullish()})),usageMetadata:Sn.nullish(),promptFeedback:U.object({blockReason:U.string().nullish(),safetyRatings:U.array(xn).nullish()}).nullish()}),wn=U.object({candidates:U.array(U.object({content:bn.nullish(),finishReason:U.string().nullish(),safetyRatings:U.array(xn).nullish(),groundingMetadata:dn.nullish(),urlContextMetadata:mn.nullish()})).nullish(),usageMetadata:Sn.nullish(),promptFeedback:U.object({blockReason:U.string().nullish(),safetyRatings:U.array(xn).nullish()}).nullish()}),Tn=k({id:`google.code_execution`,name:`code_execution`,inputSchema:U.object({language:U.string().describe(`The programming language of the code.`),code:U.string().describe(`The code to be executed.`)}),outputSchema:U.object({outcome:U.string().describe(`The outcome of the execution (e.g., "OUTCOME_OK").`),output:U.string().describe(`The output from the code execution.`)})}),En={googleSearch:fn,urlContext:hn,codeExecution:Tn},Dn=class{constructor(e,t,n){this.modelId=e,this.settings=t,this.config=n,this.specificationVersion=`v2`}get maxImagesPerCall(){return this.settings.maxImagesPerCall??4}get provider(){return this.config.provider}async doGenerate(e){var t;let{prompt:n,n:r=1,size:i=`1024x1024`,aspectRatio:a=`1:1`,seed:o,providerOptions:s,headers:c,abortSignal:l}=e,u=[];i!=null&&u.push({type:`unsupported-setting`,setting:`size`,details:"This model does not support the `size` option. Use `aspectRatio` instead."}),o!=null&&u.push({type:`unsupported-setting`,setting:`seed`,details:"This model does not support the `seed` option through this provider."});let d=await L({provider:`google`,providerOptions:s,schema:kn}),f=((t=this.config._internal)?.currentDate)?.call(t)??new Date,p={sampleCount:r};a!=null&&(p.aspectRatio=a),d&&Object.assign(p,d);let m={instances:[{prompt:n}],parameters:p},{responseHeaders:h,value:g}=await z({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:x(await B(this.config.headers),c),body:m,failedResponseHandler:Zt,successfulResponseHandler:D(On),abortSignal:l,fetch:this.config.fetch});return{images:g.predictions.map(e=>e.bytesBase64Encoded),warnings:u??[],providerMetadata:{google:{images:g.predictions.map(e=>({}))}},response:{timestamp:f,modelId:this.modelId,headers:h}}}},On=U.object({predictions:U.array(U.object({bytesBase64Encoded:U.string()})).default([])}),kn=U.object({personGeneration:U.enum([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),aspectRatio:U.enum([`1:1`,`3:4`,`4:3`,`9:16`,`16:9`]).nullish()});function An(e={}){let t=oe(e.baseURL)??`https://generativelanguage.googleapis.com/v1beta`,n=()=>ae({"x-goog-api-key":te({apiKey:e.apiKey,environmentVariableName:`GOOGLE_GENERATIVE_AI_API_KEY`,description:`Google Generative AI`}),...e.headers},`ai-sdk/google/${Yt}`),r=r=>new gn(r,{provider:`google.generative-ai`,baseURL:t,headers:n,generateId:e.generateId??j,supportedUrls:()=>({"*":[RegExp(`^${t}/files/.*$`),RegExp(`^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$`),RegExp(`^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$`)]}),fetch:e.fetch}),i=r=>new $t(r,{provider:`google.generative-ai`,baseURL:t,headers:n,fetch:e.fetch}),a=(r,i={})=>new Dn(r,i,{provider:`google.generative-ai`,baseURL:t,headers:n,fetch:e.fetch}),o=function(e){if(new.target)throw Error(`The Google Generative AI model function cannot be called with the new keyword.`);return r(e)};return o.languageModel=r,o.chat=r,o.generativeAI=r,o.embedding=i,o.textEmbedding=i,o.textEmbeddingModel=i,o.image=a,o.imageModel=a,o.tools=En,o}An();var jn=U.object({error:U.object({message:U.string(),type:U.string().nullish(),param:U.any().nullish(),code:U.union([U.string(),U.number()]).nullish()})}),Mn=E({errorSchema:jn,errorToMessage:e=>e.error.message});function Nn({prompt:e,systemMessageMode:t=`system`}){let n=[],r=[];for(let{role:i,content:a}of e)switch(i){case`system`:switch(t){case`system`:n.push({role:`system`,content:a});break;case`developer`:n.push({role:`developer`,content:a});break;case`remove`:r.push({type:`other`,message:`system messages are removed for this model`});break;default:{let e=t;throw Error(`Unsupported system message mode: ${e}`)}}break;case`user`:if(a.length===1&&a[0].type===`text`){n.push({role:`user`,content:a[0].text});break}n.push({role:`user`,content:a.map((e,t)=>{switch(e.type){case`text`:return{type:`text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`image_url`,image_url:{url:e.data instanceof URL?e.data.toString():`data:${t};base64,${C(e.data)}`,detail:e.providerOptions?.openai?.imageDetail}}}else if(e.mediaType.startsWith(`audio/`)){if(e.data instanceof URL)throw new b({functionality:`audio file parts with URLs`});switch(e.mediaType){case`audio/wav`:return{type:`input_audio`,input_audio:{data:C(e.data),format:`wav`}};case`audio/mp3`:case`audio/mpeg`:return{type:`input_audio`,input_audio:{data:C(e.data),format:`mp3`}};default:throw new b({functionality:`audio content parts with media type ${e.mediaType}`})}}else if(e.mediaType===`application/pdf`){if(e.data instanceof URL)throw new b({functionality:`PDF file parts with URLs`});return{type:`file`,file:typeof e.data==`string`&&e.data.startsWith(`file-`)?{file_id:e.data}:{filename:e.filename??`part-${t}.pdf`,file_data:`data:application/pdf;base64,${C(e.data)}`}}}else throw new b({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e=``,t=[];for(let n of a)switch(n.type){case`text`:e+=n.text;break;case`tool-call`:t.push({id:n.toolCallId,type:`function`,function:{name:n.toolName,arguments:JSON.stringify(n.input)}});break}n.push({role:`assistant`,content:e,tool_calls:t.length>0?t:void 0});break}case`tool`:for(let e of a){let t=e.output,r;switch(t.type){case`text`:case`error-text`:r=t.value;break;case`content`:case`json`:case`error-json`:r=JSON.stringify(t.value);break}n.push({role:`tool`,tool_call_id:e.toolCallId,content:r})}break;default:{let e=i;throw Error(`Unsupported role: ${e}`)}}return{messages:n,warnings:r}}function Pn({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function Fn(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`content_filter`:return`content-filter`;case`function_call`:case`tool_calls`:return`tool-calls`;default:return`unknown`}}var In=U.object({logitBias:U.record(U.coerce.number(),U.number()).optional(),logprobs:U.union([U.boolean(),U.number()]).optional(),parallelToolCalls:U.boolean().optional(),user:U.string().optional(),reasoningEffort:U.enum([`minimal`,`low`,`medium`,`high`]).optional(),maxCompletionTokens:U.number().optional(),store:U.boolean().optional(),metadata:U.record(U.string().max(64),U.string().max(512)).optional(),prediction:U.record(U.string(),U.any()).optional(),structuredOutputs:U.boolean().optional(),serviceTier:U.enum([`auto`,`flex`,`priority`]).optional(),strictJsonSchema:U.boolean().optional(),textVerbosity:U.enum([`low`,`medium`,`high`]).optional(),promptCacheKey:U.string().optional(),safetyIdentifier:U.string().optional()});function Ln({tools:e,toolChoice:t,structuredOutputs:n,strictJsonSchema:r}){e=e?.length?e:void 0;let i=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i};let a=[];for(let t of e)switch(t.type){case`function`:a.push({type:`function`,function:{name:t.name,description:t.description,parameters:t.inputSchema,strict:n?r:void 0}});break;default:i.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:a,toolChoice:void 0,toolWarnings:i};let o=t.type;switch(o){case`auto`:case`none`:case`required`:return{tools:a,toolChoice:o,toolWarnings:i};case`tool`:return{tools:a,toolChoice:{type:`function`,function:{name:t.toolName}},toolWarnings:i};default:throw new b({functionality:`tool choice type: ${o}`})}}var Rn=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){let p=[],m=await L({provider:`openai`,providerOptions:f,schema:In})??{},h=m.structuredOutputs??!0;i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),c?.type===`json`&&c.schema!=null&&!h&&p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format schema is only supported with structuredOutputs`});let{messages:g,warnings:_}=Nn({prompt:e,systemMessageMode:Gn(this.modelId)});p.push(..._);let v=m.strictJsonSchema??!1,y={model:this.modelId,logit_bias:m.logitBias,logprobs:m.logprobs===!0||typeof m.logprobs==`number`?!0:void 0,top_logprobs:typeof m.logprobs==`number`?m.logprobs:typeof m.logprobs==`boolean`&&m.logprobs?0:void 0,user:m.user,parallel_tool_calls:m.parallelToolCalls,max_tokens:t,temperature:n,top_p:r,frequency_penalty:a,presence_penalty:o,response_format:c?.type===`json`?h&&c.schema!=null?{type:`json_schema`,json_schema:{schema:c.schema,strict:v,name:c.name??`response`,description:c.description}}:{type:`json_object`}:void 0,stop:s,seed:l,verbosity:m.textVerbosity,max_completion_tokens:m.maxCompletionTokens,store:m.store,metadata:m.metadata,prediction:m.prediction,reasoning_effort:m.reasoningEffort,service_tier:m.serviceTier,prompt_cache_key:m.promptCacheKey,safety_identifier:m.safetyIdentifier,messages:g};Hn(this.modelId)?(y.temperature!=null&&(y.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for reasoning models`})),y.top_p!=null&&(y.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported for reasoning models`})),y.frequency_penalty!=null&&(y.frequency_penalty=void 0,p.push({type:`unsupported-setting`,setting:`frequencyPenalty`,details:`frequencyPenalty is not supported for reasoning models`})),y.presence_penalty!=null&&(y.presence_penalty=void 0,p.push({type:`unsupported-setting`,setting:`presencePenalty`,details:`presencePenalty is not supported for reasoning models`})),y.logit_bias!=null&&(y.logit_bias=void 0,p.push({type:`other`,message:`logitBias is not supported for reasoning models`})),y.logprobs!=null&&(y.logprobs=void 0,p.push({type:`other`,message:`logprobs is not supported for reasoning models`})),y.top_logprobs!=null&&(y.top_logprobs=void 0,p.push({type:`other`,message:`topLogprobs is not supported for reasoning models`})),y.max_tokens!=null&&(y.max_completion_tokens??=y.max_tokens,y.max_tokens=void 0)):(this.modelId.startsWith(`gpt-4o-search-preview`)||this.modelId.startsWith(`gpt-4o-mini-search-preview`))&&y.temperature!=null&&(y.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for the search preview models and has been removed.`})),m.serviceTier===`flex`&&!Un(this.modelId)&&(p.push({type:`unsupported-setting`,setting:`serviceTier`,details:`flex processing is only available for o3, o4-mini, and gpt-5 models`}),y.service_tier=void 0),m.serviceTier===`priority`&&!Wn(this.modelId)&&(p.push({type:`unsupported-setting`,setting:`serviceTier`,details:`priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported`}),y.service_tier=void 0);let{tools:b,toolChoice:x,toolWarnings:S}=Ln({tools:u,toolChoice:d,structuredOutputs:h,strictJsonSchema:v});return{args:{...y,tools:b,tool_choice:x},warnings:[...p,...S]}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:i,rawValue:a}=await z({url:this.config.url({path:`/chat/completions`,modelId:this.modelId}),headers:x(this.config.headers(),e.headers),body:t,failedResponseHandler:Mn,successfulResponseHandler:D(Bn),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=i.choices[0],s=[],c=o.message.content;c!=null&&c.length>0&&s.push({type:`text`,text:c});for(let e of o.message.tool_calls??[])s.push({type:`tool-call`,toolCallId:e.id??j(),toolName:e.function.name,input:e.function.arguments});for(let e of o.message.annotations??[])s.push({type:`source`,sourceType:`url`,id:j(),url:e.url,title:e.title});let l=i.usage?.completion_tokens_details,u=i.usage?.prompt_tokens_details,d={openai:{}};return l?.accepted_prediction_tokens!=null&&(d.openai.acceptedPredictionTokens=l?.accepted_prediction_tokens),l?.rejected_prediction_tokens!=null&&(d.openai.rejectedPredictionTokens=l?.rejected_prediction_tokens),o.logprobs?.content!=null&&(d.openai.logprobs=o.logprobs.content),{content:s,finishReason:Fn(o.finish_reason),usage:{inputTokens:i.usage?.prompt_tokens??void 0,outputTokens:i.usage?.completion_tokens??void 0,totalTokens:i.usage?.total_tokens??void 0,reasoningTokens:l?.reasoning_tokens??void 0,cachedInputTokens:u?.cached_tokens??void 0},request:{body:t},response:{...Pn(i),headers:r,body:a},warnings:n,providerMetadata:d}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:a}=await z({url:this.config.url({path:`/chat/completions`,modelId:this.modelId}),headers:x(this.config.headers(),e.headers),body:r,failedResponseHandler:Mn,successfulResponseHandler:T(Vn),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=[],s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=!0,u=!1,d={openai:{}};return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){s=`error`,n.enqueue({type:`error`,error:t.error});return}let r=t.value;if(`error`in r){s=`error`,n.enqueue({type:`error`,error:r.error});return}l&&(l=!1,n.enqueue({type:`response-metadata`,...Pn(r)})),r.usage!=null&&(c.inputTokens=r.usage.prompt_tokens??void 0,c.outputTokens=r.usage.completion_tokens??void 0,c.totalTokens=r.usage.total_tokens??void 0,c.reasoningTokens=r.usage.completion_tokens_details?.reasoning_tokens??void 0,c.cachedInputTokens=r.usage.prompt_tokens_details?.cached_tokens??void 0,r.usage.completion_tokens_details?.accepted_prediction_tokens!=null&&(d.openai.acceptedPredictionTokens=r.usage.completion_tokens_details?.accepted_prediction_tokens),r.usage.completion_tokens_details?.rejected_prediction_tokens!=null&&(d.openai.rejectedPredictionTokens=r.usage.completion_tokens_details?.rejected_prediction_tokens));let i=r.choices[0];if(i?.finish_reason!=null&&(s=Fn(i.finish_reason)),i?.logprobs?.content!=null&&(d.openai.logprobs=i.logprobs.content),i?.delta==null)return;let a=i.delta;if(a.content!=null&&(u||=(n.enqueue({type:`text-start`,id:`0`}),!0),n.enqueue({type:`text-delta`,id:`0`,delta:a.content})),a.tool_calls!=null)for(let e of a.tool_calls){let t=e.index;if(o[t]==null){if(e.type!==`function`)throw new m({data:e,message:`Expected 'function' type.`});if(e.id==null)throw new m({data:e,message:`Expected 'id' to be a string.`});if(e.function?.name==null)throw new m({data:e,message:`Expected 'function.name' to be a string.`});n.enqueue({type:`tool-input-start`,id:e.id,toolName:e.function.name}),o[t]={id:e.id,type:`function`,function:{name:e.function.name,arguments:e.function.arguments??``},hasFinished:!1};let r=o[t];r.function?.name!=null&&r.function?.arguments!=null&&(r.function.arguments.length>0&&n.enqueue({type:`tool-input-delta`,id:r.id,delta:r.function.arguments}),N(r.function.arguments)&&(n.enqueue({type:`tool-input-end`,id:r.id}),n.enqueue({type:`tool-call`,toolCallId:r.id??j(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0));continue}let r=o[t];r.hasFinished||(e.function?.arguments!=null&&(r.function.arguments+=e.function?.arguments??``),n.enqueue({type:`tool-input-delta`,id:r.id,delta:e.function.arguments??``}),r.function?.name!=null&&r.function?.arguments!=null&&N(r.function.arguments)&&(n.enqueue({type:`tool-input-end`,id:r.id}),n.enqueue({type:`tool-call`,toolCallId:r.id??j(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0))}if(a.annotations!=null)for(let e of a.annotations)n.enqueue({type:`source`,sourceType:`url`,id:j(),url:e.url,title:e.title})},flush(e){u&&e.enqueue({type:`text-end`,id:`0`}),e.enqueue({type:`finish`,finishReason:s,usage:c,...d==null?{}:{providerMetadata:d}})}})),request:{body:r},response:{headers:i}}}},zn=U.object({prompt_tokens:U.number().nullish(),completion_tokens:U.number().nullish(),total_tokens:U.number().nullish(),prompt_tokens_details:U.object({cached_tokens:U.number().nullish()}).nullish(),completion_tokens_details:U.object({reasoning_tokens:U.number().nullish(),accepted_prediction_tokens:U.number().nullish(),rejected_prediction_tokens:U.number().nullish()}).nullish()}).nullish(),Bn=U.object({id:U.string().nullish(),created:U.number().nullish(),model:U.string().nullish(),choices:U.array(U.object({message:U.object({role:U.literal(`assistant`).nullish(),content:U.string().nullish(),tool_calls:U.array(U.object({id:U.string().nullish(),type:U.literal(`function`),function:U.object({name:U.string(),arguments:U.string()})})).nullish(),annotations:U.array(U.object({type:U.literal(`url_citation`),start_index:U.number(),end_index:U.number(),url:U.string(),title:U.string()})).nullish()}),index:U.number(),logprobs:U.object({content:U.array(U.object({token:U.string(),logprob:U.number(),top_logprobs:U.array(U.object({token:U.string(),logprob:U.number()}))})).nullish()}).nullish(),finish_reason:U.string().nullish()})),usage:zn}),Vn=U.union([U.object({id:U.string().nullish(),created:U.number().nullish(),model:U.string().nullish(),choices:U.array(U.object({delta:U.object({role:U.enum([`assistant`]).nullish(),content:U.string().nullish(),tool_calls:U.array(U.object({index:U.number(),id:U.string().nullish(),type:U.literal(`function`).nullish(),function:U.object({name:U.string().nullish(),arguments:U.string().nullish()})})).nullish(),annotations:U.array(U.object({type:U.literal(`url_citation`),start_index:U.number(),end_index:U.number(),url:U.string(),title:U.string()})).nullish()}).nullish(),logprobs:U.object({content:U.array(U.object({token:U.string(),logprob:U.number(),top_logprobs:U.array(U.object({token:U.string(),logprob:U.number()}))})).nullish()}).nullish(),finish_reason:U.string().nullish(),index:U.number()})),usage:zn}),jn]);function Hn(e){return(e.startsWith(`o`)||e.startsWith(`gpt-5`))&&!e.startsWith(`gpt-5-chat`)}function Un(e){return e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`)}function Wn(e){return e.startsWith(`gpt-4`)||e.startsWith(`gpt-5-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-nano`)&&!e.startsWith(`gpt-5-chat`)||e.startsWith(`o3`)||e.startsWith(`o4-mini`)}function Gn(e){return Hn(e)?Kn[e]?.systemMessageMode??`developer`:`system`}var Kn={"o1-mini":{systemMessageMode:`remove`},"o1-mini-2024-09-12":{systemMessageMode:`remove`},"o1-preview":{systemMessageMode:`remove`},"o1-preview-2024-09-12":{systemMessageMode:`remove`},o3:{systemMessageMode:`developer`},"o3-2025-04-16":{systemMessageMode:`developer`},"o3-mini":{systemMessageMode:`developer`},"o3-mini-2025-01-31":{systemMessageMode:`developer`},"o4-mini":{systemMessageMode:`developer`},"o4-mini-2025-04-16":{systemMessageMode:`developer`}};function qn({prompt:e,user:t=`user`,assistant:n=`assistant`}){let r=``;e[0].role===`system`&&(r+=`${e[0].content}
|
|
5
|
+
`})}return{systemInstruction:n.length>0&&!a?{parts:n}:void 0,contents:r}}function on(e){return e.includes(`/`)?e:`models/${e}`}var sn=U.object({responseModalities:U.array(U.enum([`TEXT`,`IMAGE`])).optional(),thinkingConfig:U.object({thinkingBudget:U.number().optional(),includeThoughts:U.boolean().optional()}).optional(),cachedContent:U.string().optional(),structuredOutputs:U.boolean().optional(),safetySettings:U.array(U.object({category:U.enum([`HARM_CATEGORY_UNSPECIFIED`,`HARM_CATEGORY_HATE_SPEECH`,`HARM_CATEGORY_DANGEROUS_CONTENT`,`HARM_CATEGORY_HARASSMENT`,`HARM_CATEGORY_SEXUALLY_EXPLICIT`,`HARM_CATEGORY_CIVIC_INTEGRITY`]),threshold:U.enum([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`])})).optional(),threshold:U.enum([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`]).optional(),audioTimestamp:U.boolean().optional(),labels:U.record(U.string(),U.string()).optional()});function cn({tools:e,toolChoice:t,modelId:n}){e=e?.length?e:void 0;let r=[],i=n.includes(`gemini-2`),a=n.includes(`gemini-1.5-flash`)&&!n.includes(`-8b`);if(e==null)return{tools:void 0,toolConfig:void 0,toolWarnings:r};let o=e.some(e=>e.type===`function`),s=e.some(e=>e.type===`provider-defined`);if(o&&s&&r.push({type:`unsupported-tool`,tool:e.find(e=>e.type===`function`),details:`Cannot mix function tools with provider-defined tools in the same request. Please use either function tools or provider-defined tools, but not both.`}),s){let t={};return e.filter(e=>e.type===`provider-defined`).forEach(e=>{switch(e.id){case`google.google_search`:i?t.googleSearch={}:a?t.googleSearchRetrieval={dynamicRetrievalConfig:{mode:e.args.mode,dynamicThreshold:e.args.dynamicThreshold}}:t.googleSearchRetrieval={};break;case`google.url_context`:i?t.urlContext={}:r.push({type:`unsupported-tool`,tool:e,details:`The URL context tool is not supported with other Gemini models than Gemini 2.`});break;case`google.code_execution`:i?t.codeExecution={}:r.push({type:`unsupported-tool`,tool:e,details:`The code execution tools is not supported with other Gemini models than Gemini 2.`});break;default:r.push({type:`unsupported-tool`,tool:e});break}}),{tools:Object.keys(t).length>0?t:void 0,toolConfig:void 0,toolWarnings:r}}let c=[];for(let t of e)switch(t.type){case`function`:c.push({name:t.name,description:t.description??``,parameters:nn(t.inputSchema)});break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:{functionDeclarations:c},toolConfig:void 0,toolWarnings:r};let l=t.type;switch(l){case`auto`:return{tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:`AUTO`}},toolWarnings:r};case`none`:return{tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:`NONE`}},toolWarnings:r};case`required`:return{tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:`ANY`}},toolWarnings:r};case`tool`:return{tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:`ANY`,allowedFunctionNames:[t.toolName]}},toolWarnings:r};default:throw new b({functionality:`tool choice type: ${l}`})}}function ln({finishReason:e,hasToolCalls:t}){switch(e){case`STOP`:return t?`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`FINISH_REASON_UNSPECIFIED`:case`OTHER`:return`other`;case`MALFORMED_FUNCTION_CALL`:return`error`;default:return`unknown`}}var un=U.object({web:U.object({uri:U.string(),title:U.string()}).nullish(),retrievedContext:U.object({uri:U.string(),title:U.string()}).nullish()}),dn=U.object({webSearchQueries:U.array(U.string()).nullish(),retrievalQueries:U.array(U.string()).nullish(),searchEntryPoint:U.object({renderedContent:U.string()}).nullish(),groundingChunks:U.array(un).nullish(),groundingSupports:U.array(U.object({segment:U.object({startIndex:U.number().nullish(),endIndex:U.number().nullish(),text:U.string().nullish()}),segment_text:U.string().nullish(),groundingChunkIndices:U.array(U.number()).nullish(),supportChunkIndices:U.array(U.number()).nullish(),confidenceScores:U.array(U.number()).nullish(),confidenceScore:U.array(U.number()).nullish()})).nullish(),retrievalMetadata:U.union([U.object({webDynamicRetrievalScore:U.number()}),U.object({})]).nullish()}),fn=k({id:`google.google_search`,name:`google_search`,inputSchema:U.object({mode:U.enum([`MODE_DYNAMIC`,`MODE_UNSPECIFIED`]).default(`MODE_UNSPECIFIED`),dynamicThreshold:U.number().default(1)})}),pn=U.object({retrievedUrl:U.string(),urlRetrievalStatus:U.string()}),mn=U.object({urlMetadata:U.array(pn)}),hn=k({id:`google.url_context`,name:`url_context`,inputSchema:U.object({})}),gn=class{constructor(e,t){this.specificationVersion=`v2`,this.modelId=e,this.config=t,this.generateId=t.generateId??M}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){let p=[],m=await L({provider:`google`,providerOptions:f,schema:sn});m?.thinkingConfig?.includeThoughts===!0&&!this.config.provider.startsWith(`google.vertex.`)&&p.push({type:`other`,message:`The 'includeThoughts' option 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}).`});let h=this.modelId.toLowerCase().startsWith(`gemma-`),{contents:g,systemInstruction:_}=an(e,{isGemmaModel:h}),{tools:v,toolConfig:y,toolWarnings:b}=cn({tools:u,toolChoice:d,modelId:this.modelId});return{args:{generationConfig:{maxOutputTokens:t,temperature:n,topK:i,topP:r,frequencyPenalty:a,presencePenalty:o,stopSequences:s,seed:l,responseMimeType:c?.type===`json`?`application/json`:void 0,responseSchema:c?.type===`json`&&c.schema!=null&&(m?.structuredOutputs??!0)?nn(c.schema):void 0,...m?.audioTimestamp&&{audioTimestamp:m.audioTimestamp},responseModalities:m?.responseModalities,thinkingConfig:m?.thinkingConfig},contents:g,systemInstruction:h?void 0:_,safetySettings:m?.safetySettings,tools:v,toolConfig:y,cachedContent:m?.cachedContent,labels:m?.labels},warnings:[...p,...b]}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),r=JSON.stringify(t),i=x(await B(this.config.headers),e.headers),{responseHeaders:a,value:o,rawValue:s}=await z({url:`${this.config.baseURL}/${on(this.modelId)}:generateContent`,headers:i,body:t,failedResponseHandler:Zt,successfulResponseHandler:O(Cn),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=o.candidates[0],l=[],u=c.content?.parts??[],d=o.usageMetadata,f;for(let e of u)if(`executableCode`in e&&e.executableCode?.code){let t=this.config.generateId();f=t,l.push({type:`tool-call`,toolCallId:t,toolName:`code_execution`,input:JSON.stringify(e.executableCode),providerExecuted:!0})}else `codeExecutionResult`in e&&e.codeExecutionResult?(l.push({type:`tool-result`,toolCallId:f,toolName:`code_execution`,result:{outcome:e.codeExecutionResult.outcome,output:e.codeExecutionResult.output},providerExecuted:!0}),f=void 0):`text`in e&&e.text!=null&&e.text.length>0?l.push({type:e.thought===!0?`reasoning`:`text`,text:e.text,providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0}):`functionCall`in e?l.push({type:`tool-call`,toolCallId:this.config.generateId(),toolName:e.functionCall.name,input:JSON.stringify(e.functionCall.args),providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0}):`inlineData`in e&&l.push({type:`file`,data:e.inlineData.data,mediaType:e.inlineData.mimeType});let p=yn({groundingMetadata:c.groundingMetadata,generateId:this.config.generateId})??[];for(let e of p)l.push(e);return{content:l,finishReason:ln({finishReason:c.finishReason,hasToolCalls:l.some(e=>e.type===`tool-call`)}),usage:{inputTokens:d?.promptTokenCount??void 0,outputTokens:d?.candidatesTokenCount??void 0,totalTokens:d?.totalTokenCount??void 0,reasoningTokens:d?.thoughtsTokenCount??void 0,cachedInputTokens:d?.cachedContentTokenCount??void 0},warnings:n,providerMetadata:{google:{promptFeedback:o.promptFeedback??null,groundingMetadata:c.groundingMetadata??null,urlContextMetadata:c.urlContextMetadata??null,safetyRatings:c.safetyRatings??null,usageMetadata:d??null}},request:{body:r},response:{headers:a,body:s}}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r=JSON.stringify(t),i=x(await B(this.config.headers),e.headers),{responseHeaders:a,value:o}=await z({url:`${this.config.baseURL}/${on(this.modelId)}:streamGenerateContent?alt=sse`,headers:i,body:t,failedResponseHandler:Zt,successfulResponseHandler:T(wn),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l,u=this.config.generateId,d=!1,f=null,p=null,m=0,h=new Set,g;return{stream:o.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let r=t.value,i=r.usageMetadata;i!=null&&(c.inputTokens=i.promptTokenCount??void 0,c.outputTokens=i.candidatesTokenCount??void 0,c.totalTokens=i.totalTokenCount??void 0,c.reasoningTokens=i.thoughtsTokenCount??void 0,c.cachedInputTokens=i.cachedContentTokenCount??void 0);let a=r.candidates?.[0];if(a==null)return;let o=a.content,_=yn({groundingMetadata:a.groundingMetadata,generateId:u});if(_!=null)for(let e of _)e.sourceType===`url`&&!h.has(e.url)&&(h.add(e.url),n.enqueue(e));if(o!=null){let e=o.parts??[];for(let t of e)if(`executableCode`in t&&t.executableCode?.code){let e=u();g=e,n.enqueue({type:`tool-call`,toolCallId:e,toolName:`code_execution`,input:JSON.stringify(t.executableCode),providerExecuted:!0}),d=!0}else if(`codeExecutionResult`in t&&t.codeExecutionResult){let e=g;e&&(n.enqueue({type:`tool-result`,toolCallId:e,toolName:`code_execution`,result:{outcome:t.codeExecutionResult.outcome,output:t.codeExecutionResult.output},providerExecuted:!0}),g=void 0)}else `text`in t&&t.text!=null&&t.text.length>0&&(t.thought===!0?(f!==null&&(n.enqueue({type:`text-end`,id:f}),f=null),p===null&&(p=String(m++),n.enqueue({type:`reasoning-start`,id:p,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})),n.enqueue({type:`reasoning-delta`,id:p,delta:t.text,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})):(p!==null&&(n.enqueue({type:`reasoning-end`,id:p}),p=null),f===null&&(f=String(m++),n.enqueue({type:`text-start`,id:f,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})),n.enqueue({type:`text-delta`,id:f,delta:t.text,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})));let t=vn(o.parts);if(t!=null)for(let e of t)n.enqueue({type:`file`,mediaType:e.inlineData.mimeType,data:e.inlineData.data});let r=_n({parts:o.parts,generateId:u});if(r!=null)for(let e of r)n.enqueue({type:`tool-input-start`,id:e.toolCallId,toolName:e.toolName,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:e.args,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-input-end`,id:e.toolCallId,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.args,providerMetadata:e.providerMetadata}),d=!0}a.finishReason!=null&&(s=ln({finishReason:a.finishReason,hasToolCalls:d}),l={google:{promptFeedback:r.promptFeedback??null,groundingMetadata:a.groundingMetadata??null,urlContextMetadata:a.urlContextMetadata??null,safetyRatings:a.safetyRatings??null}},i!=null&&(l.google.usageMetadata=i))},flush(e){f!==null&&e.enqueue({type:`text-end`,id:f}),p!==null&&e.enqueue({type:`reasoning-end`,id:p}),e.enqueue({type:`finish`,finishReason:s,usage:c,providerMetadata:l})}})),response:{headers:a},request:{body:r}}}};function _n({parts:e,generateId:t}){let n=e?.filter(e=>`functionCall`in e);return n==null||n.length===0?void 0:n.map(e=>({type:`tool-call`,toolCallId:t(),toolName:e.functionCall.name,args:JSON.stringify(e.functionCall.args),providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0}))}function vn(e){return e?.filter(e=>`inlineData`in e)}function yn({groundingMetadata:e,generateId:t}){return(e?.groundingChunks)?.filter(e=>e.web!=null).map(e=>({type:`source`,sourceType:`url`,id:t(),url:e.web.uri,title:e.web.title}))}var bn=U.object({parts:U.array(U.union([U.object({functionCall:U.object({name:U.string(),args:U.unknown()}),thoughtSignature:U.string().nullish()}),U.object({inlineData:U.object({mimeType:U.string(),data:U.string()})}),U.object({executableCode:U.object({language:U.string(),code:U.string()}).nullish(),codeExecutionResult:U.object({outcome:U.string(),output:U.string()}).nullish(),text:U.string().nullish(),thought:U.boolean().nullish(),thoughtSignature:U.string().nullish()})])).nullish()}),xn=U.object({category:U.string().nullish(),probability:U.string().nullish(),probabilityScore:U.number().nullish(),severity:U.string().nullish(),severityScore:U.number().nullish(),blocked:U.boolean().nullish()}),Sn=U.object({cachedContentTokenCount:U.number().nullish(),thoughtsTokenCount:U.number().nullish(),promptTokenCount:U.number().nullish(),candidatesTokenCount:U.number().nullish(),totalTokenCount:U.number().nullish()}),Cn=U.object({candidates:U.array(U.object({content:bn.nullish().or(U.object({}).strict()),finishReason:U.string().nullish(),safetyRatings:U.array(xn).nullish(),groundingMetadata:dn.nullish(),urlContextMetadata:mn.nullish()})),usageMetadata:Sn.nullish(),promptFeedback:U.object({blockReason:U.string().nullish(),safetyRatings:U.array(xn).nullish()}).nullish()}),wn=U.object({candidates:U.array(U.object({content:bn.nullish(),finishReason:U.string().nullish(),safetyRatings:U.array(xn).nullish(),groundingMetadata:dn.nullish(),urlContextMetadata:mn.nullish()})).nullish(),usageMetadata:Sn.nullish(),promptFeedback:U.object({blockReason:U.string().nullish(),safetyRatings:U.array(xn).nullish()}).nullish()}),Tn=A({id:`google.code_execution`,name:`code_execution`,inputSchema:U.object({language:U.string().describe(`The programming language of the code.`),code:U.string().describe(`The code to be executed.`)}),outputSchema:U.object({outcome:U.string().describe(`The outcome of the execution (e.g., "OUTCOME_OK").`),output:U.string().describe(`The output from the code execution.`)})}),En={googleSearch:fn,urlContext:hn,codeExecution:Tn},Dn=class{constructor(e,t,n){this.modelId=e,this.settings=t,this.config=n,this.specificationVersion=`v2`}get maxImagesPerCall(){return this.settings.maxImagesPerCall??4}get provider(){return this.config.provider}async doGenerate(e){var t;let{prompt:n,n:r=1,size:i=`1024x1024`,aspectRatio:a=`1:1`,seed:o,providerOptions:s,headers:c,abortSignal:l}=e,u=[];i!=null&&u.push({type:`unsupported-setting`,setting:`size`,details:"This model does not support the `size` option. Use `aspectRatio` instead."}),o!=null&&u.push({type:`unsupported-setting`,setting:`seed`,details:"This model does not support the `seed` option through this provider."});let d=await L({provider:`google`,providerOptions:s,schema:kn}),f=((t=this.config._internal)?.currentDate)?.call(t)??new Date,p={sampleCount:r};a!=null&&(p.aspectRatio=a),d&&Object.assign(p,d);let m={instances:[{prompt:n}],parameters:p},{responseHeaders:h,value:g}=await z({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:x(await B(this.config.headers),c),body:m,failedResponseHandler:Zt,successfulResponseHandler:O(On),abortSignal:l,fetch:this.config.fetch});return{images:g.predictions.map(e=>e.bytesBase64Encoded),warnings:u??[],providerMetadata:{google:{images:g.predictions.map(e=>({}))}},response:{timestamp:f,modelId:this.modelId,headers:h}}}},On=U.object({predictions:U.array(U.object({bytesBase64Encoded:U.string()})).default([])}),kn=U.object({personGeneration:U.enum([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),aspectRatio:U.enum([`1:1`,`3:4`,`4:3`,`9:16`,`16:9`]).nullish()});function An(e={}){let t=oe(e.baseURL)??`https://generativelanguage.googleapis.com/v1beta`,n=()=>ae({"x-goog-api-key":ne({apiKey:e.apiKey,environmentVariableName:`GOOGLE_GENERATIVE_AI_API_KEY`,description:`Google Generative AI`}),...e.headers},`ai-sdk/google/${Yt}`),r=r=>new gn(r,{provider:`google.generative-ai`,baseURL:t,headers:n,generateId:e.generateId??M,supportedUrls:()=>({"*":[RegExp(`^${t}/files/.*$`),RegExp(`^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$`),RegExp(`^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$`)]}),fetch:e.fetch}),i=r=>new $t(r,{provider:`google.generative-ai`,baseURL:t,headers:n,fetch:e.fetch}),a=(r,i={})=>new Dn(r,i,{provider:`google.generative-ai`,baseURL:t,headers:n,fetch:e.fetch}),o=function(e){if(new.target)throw Error(`The Google Generative AI model function cannot be called with the new keyword.`);return r(e)};return o.languageModel=r,o.chat=r,o.generativeAI=r,o.embedding=i,o.textEmbedding=i,o.textEmbeddingModel=i,o.image=a,o.imageModel=a,o.tools=En,o}An();var jn=U.object({error:U.object({message:U.string(),type:U.string().nullish(),param:U.any().nullish(),code:U.union([U.string(),U.number()]).nullish()})}),Mn=D({errorSchema:jn,errorToMessage:e=>e.error.message});function Nn({prompt:e,systemMessageMode:t=`system`}){let n=[],r=[];for(let{role:i,content:a}of e)switch(i){case`system`:switch(t){case`system`:n.push({role:`system`,content:a});break;case`developer`:n.push({role:`developer`,content:a});break;case`remove`:r.push({type:`other`,message:`system messages are removed for this model`});break;default:{let e=t;throw Error(`Unsupported system message mode: ${e}`)}}break;case`user`:if(a.length===1&&a[0].type===`text`){n.push({role:`user`,content:a[0].text});break}n.push({role:`user`,content:a.map((e,t)=>{switch(e.type){case`text`:return{type:`text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`image_url`,image_url:{url:e.data instanceof URL?e.data.toString():`data:${t};base64,${C(e.data)}`,detail:e.providerOptions?.openai?.imageDetail}}}else if(e.mediaType.startsWith(`audio/`)){if(e.data instanceof URL)throw new b({functionality:`audio file parts with URLs`});switch(e.mediaType){case`audio/wav`:return{type:`input_audio`,input_audio:{data:C(e.data),format:`wav`}};case`audio/mp3`:case`audio/mpeg`:return{type:`input_audio`,input_audio:{data:C(e.data),format:`mp3`}};default:throw new b({functionality:`audio content parts with media type ${e.mediaType}`})}}else if(e.mediaType===`application/pdf`){if(e.data instanceof URL)throw new b({functionality:`PDF file parts with URLs`});return{type:`file`,file:typeof e.data==`string`&&e.data.startsWith(`file-`)?{file_id:e.data}:{filename:e.filename??`part-${t}.pdf`,file_data:`data:application/pdf;base64,${C(e.data)}`}}}else throw new b({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e=``,t=[];for(let n of a)switch(n.type){case`text`:e+=n.text;break;case`tool-call`:t.push({id:n.toolCallId,type:`function`,function:{name:n.toolName,arguments:JSON.stringify(n.input)}});break}n.push({role:`assistant`,content:e,tool_calls:t.length>0?t:void 0});break}case`tool`:for(let e of a){let t=e.output,r;switch(t.type){case`text`:case`error-text`:r=t.value;break;case`content`:case`json`:case`error-json`:r=JSON.stringify(t.value);break}n.push({role:`tool`,tool_call_id:e.toolCallId,content:r})}break;default:{let e=i;throw Error(`Unsupported role: ${e}`)}}return{messages:n,warnings:r}}function Pn({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function Fn(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`content_filter`:return`content-filter`;case`function_call`:case`tool_calls`:return`tool-calls`;default:return`unknown`}}var In=U.object({logitBias:U.record(U.coerce.number(),U.number()).optional(),logprobs:U.union([U.boolean(),U.number()]).optional(),parallelToolCalls:U.boolean().optional(),user:U.string().optional(),reasoningEffort:U.enum([`minimal`,`low`,`medium`,`high`]).optional(),maxCompletionTokens:U.number().optional(),store:U.boolean().optional(),metadata:U.record(U.string().max(64),U.string().max(512)).optional(),prediction:U.record(U.string(),U.any()).optional(),structuredOutputs:U.boolean().optional(),serviceTier:U.enum([`auto`,`flex`,`priority`]).optional(),strictJsonSchema:U.boolean().optional(),textVerbosity:U.enum([`low`,`medium`,`high`]).optional(),promptCacheKey:U.string().optional(),safetyIdentifier:U.string().optional()});function Ln({tools:e,toolChoice:t,structuredOutputs:n,strictJsonSchema:r}){e=e?.length?e:void 0;let i=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i};let a=[];for(let t of e)switch(t.type){case`function`:a.push({type:`function`,function:{name:t.name,description:t.description,parameters:t.inputSchema,strict:n?r:void 0}});break;default:i.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:a,toolChoice:void 0,toolWarnings:i};let o=t.type;switch(o){case`auto`:case`none`:case`required`:return{tools:a,toolChoice:o,toolWarnings:i};case`tool`:return{tools:a,toolChoice:{type:`function`,function:{name:t.toolName}},toolWarnings:i};default:throw new b({functionality:`tool choice type: ${o}`})}}var Rn=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){let p=[],m=await L({provider:`openai`,providerOptions:f,schema:In})??{},h=m.structuredOutputs??!0;i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),c?.type===`json`&&c.schema!=null&&!h&&p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format schema is only supported with structuredOutputs`});let{messages:g,warnings:_}=Nn({prompt:e,systemMessageMode:Gn(this.modelId)});p.push(..._);let v=m.strictJsonSchema??!1,y={model:this.modelId,logit_bias:m.logitBias,logprobs:m.logprobs===!0||typeof m.logprobs==`number`?!0:void 0,top_logprobs:typeof m.logprobs==`number`?m.logprobs:typeof m.logprobs==`boolean`&&m.logprobs?0:void 0,user:m.user,parallel_tool_calls:m.parallelToolCalls,max_tokens:t,temperature:n,top_p:r,frequency_penalty:a,presence_penalty:o,response_format:c?.type===`json`?h&&c.schema!=null?{type:`json_schema`,json_schema:{schema:c.schema,strict:v,name:c.name??`response`,description:c.description}}:{type:`json_object`}:void 0,stop:s,seed:l,verbosity:m.textVerbosity,max_completion_tokens:m.maxCompletionTokens,store:m.store,metadata:m.metadata,prediction:m.prediction,reasoning_effort:m.reasoningEffort,service_tier:m.serviceTier,prompt_cache_key:m.promptCacheKey,safety_identifier:m.safetyIdentifier,messages:g};Hn(this.modelId)?(y.temperature!=null&&(y.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for reasoning models`})),y.top_p!=null&&(y.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported for reasoning models`})),y.frequency_penalty!=null&&(y.frequency_penalty=void 0,p.push({type:`unsupported-setting`,setting:`frequencyPenalty`,details:`frequencyPenalty is not supported for reasoning models`})),y.presence_penalty!=null&&(y.presence_penalty=void 0,p.push({type:`unsupported-setting`,setting:`presencePenalty`,details:`presencePenalty is not supported for reasoning models`})),y.logit_bias!=null&&(y.logit_bias=void 0,p.push({type:`other`,message:`logitBias is not supported for reasoning models`})),y.logprobs!=null&&(y.logprobs=void 0,p.push({type:`other`,message:`logprobs is not supported for reasoning models`})),y.top_logprobs!=null&&(y.top_logprobs=void 0,p.push({type:`other`,message:`topLogprobs is not supported for reasoning models`})),y.max_tokens!=null&&(y.max_completion_tokens??=y.max_tokens,y.max_tokens=void 0)):(this.modelId.startsWith(`gpt-4o-search-preview`)||this.modelId.startsWith(`gpt-4o-mini-search-preview`))&&y.temperature!=null&&(y.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for the search preview models and has been removed.`})),m.serviceTier===`flex`&&!Un(this.modelId)&&(p.push({type:`unsupported-setting`,setting:`serviceTier`,details:`flex processing is only available for o3, o4-mini, and gpt-5 models`}),y.service_tier=void 0),m.serviceTier===`priority`&&!Wn(this.modelId)&&(p.push({type:`unsupported-setting`,setting:`serviceTier`,details:`priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported`}),y.service_tier=void 0);let{tools:b,toolChoice:x,toolWarnings:S}=Ln({tools:u,toolChoice:d,structuredOutputs:h,strictJsonSchema:v});return{args:{...y,tools:b,tool_choice:x},warnings:[...p,...S]}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:i,rawValue:a}=await z({url:this.config.url({path:`/chat/completions`,modelId:this.modelId}),headers:x(this.config.headers(),e.headers),body:t,failedResponseHandler:Mn,successfulResponseHandler:O(Bn),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=i.choices[0],s=[],c=o.message.content;c!=null&&c.length>0&&s.push({type:`text`,text:c});for(let e of o.message.tool_calls??[])s.push({type:`tool-call`,toolCallId:e.id??M(),toolName:e.function.name,input:e.function.arguments});for(let e of o.message.annotations??[])s.push({type:`source`,sourceType:`url`,id:M(),url:e.url,title:e.title});let l=i.usage?.completion_tokens_details,u=i.usage?.prompt_tokens_details,d={openai:{}};return l?.accepted_prediction_tokens!=null&&(d.openai.acceptedPredictionTokens=l?.accepted_prediction_tokens),l?.rejected_prediction_tokens!=null&&(d.openai.rejectedPredictionTokens=l?.rejected_prediction_tokens),o.logprobs?.content!=null&&(d.openai.logprobs=o.logprobs.content),{content:s,finishReason:Fn(o.finish_reason),usage:{inputTokens:i.usage?.prompt_tokens??void 0,outputTokens:i.usage?.completion_tokens??void 0,totalTokens:i.usage?.total_tokens??void 0,reasoningTokens:l?.reasoning_tokens??void 0,cachedInputTokens:u?.cached_tokens??void 0},request:{body:t},response:{...Pn(i),headers:r,body:a},warnings:n,providerMetadata:d}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:a}=await z({url:this.config.url({path:`/chat/completions`,modelId:this.modelId}),headers:x(this.config.headers(),e.headers),body:r,failedResponseHandler:Mn,successfulResponseHandler:T(Vn),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=[],s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=!0,u=!1,d={openai:{}};return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){s=`error`,n.enqueue({type:`error`,error:t.error});return}let r=t.value;if(`error`in r){s=`error`,n.enqueue({type:`error`,error:r.error});return}l&&(l=!1,n.enqueue({type:`response-metadata`,...Pn(r)})),r.usage!=null&&(c.inputTokens=r.usage.prompt_tokens??void 0,c.outputTokens=r.usage.completion_tokens??void 0,c.totalTokens=r.usage.total_tokens??void 0,c.reasoningTokens=r.usage.completion_tokens_details?.reasoning_tokens??void 0,c.cachedInputTokens=r.usage.prompt_tokens_details?.cached_tokens??void 0,r.usage.completion_tokens_details?.accepted_prediction_tokens!=null&&(d.openai.acceptedPredictionTokens=r.usage.completion_tokens_details?.accepted_prediction_tokens),r.usage.completion_tokens_details?.rejected_prediction_tokens!=null&&(d.openai.rejectedPredictionTokens=r.usage.completion_tokens_details?.rejected_prediction_tokens));let i=r.choices[0];if(i?.finish_reason!=null&&(s=Fn(i.finish_reason)),i?.logprobs?.content!=null&&(d.openai.logprobs=i.logprobs.content),i?.delta==null)return;let a=i.delta;if(a.content!=null&&(u||=(n.enqueue({type:`text-start`,id:`0`}),!0),n.enqueue({type:`text-delta`,id:`0`,delta:a.content})),a.tool_calls!=null)for(let e of a.tool_calls){let t=e.index;if(o[t]==null){if(e.type!==`function`)throw new m({data:e,message:`Expected 'function' type.`});if(e.id==null)throw new m({data:e,message:`Expected 'id' to be a string.`});if(e.function?.name==null)throw new m({data:e,message:`Expected 'function.name' to be a string.`});n.enqueue({type:`tool-input-start`,id:e.id,toolName:e.function.name}),o[t]={id:e.id,type:`function`,function:{name:e.function.name,arguments:e.function.arguments??``},hasFinished:!1};let r=o[t];r.function?.name!=null&&r.function?.arguments!=null&&(r.function.arguments.length>0&&n.enqueue({type:`tool-input-delta`,id:r.id,delta:r.function.arguments}),P(r.function.arguments)&&(n.enqueue({type:`tool-input-end`,id:r.id}),n.enqueue({type:`tool-call`,toolCallId:r.id??M(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0));continue}let r=o[t];r.hasFinished||(e.function?.arguments!=null&&(r.function.arguments+=e.function?.arguments??``),n.enqueue({type:`tool-input-delta`,id:r.id,delta:e.function.arguments??``}),r.function?.name!=null&&r.function?.arguments!=null&&P(r.function.arguments)&&(n.enqueue({type:`tool-input-end`,id:r.id}),n.enqueue({type:`tool-call`,toolCallId:r.id??M(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0))}if(a.annotations!=null)for(let e of a.annotations)n.enqueue({type:`source`,sourceType:`url`,id:M(),url:e.url,title:e.title})},flush(e){u&&e.enqueue({type:`text-end`,id:`0`}),e.enqueue({type:`finish`,finishReason:s,usage:c,...d==null?{}:{providerMetadata:d}})}})),request:{body:r},response:{headers:i}}}},zn=U.object({prompt_tokens:U.number().nullish(),completion_tokens:U.number().nullish(),total_tokens:U.number().nullish(),prompt_tokens_details:U.object({cached_tokens:U.number().nullish()}).nullish(),completion_tokens_details:U.object({reasoning_tokens:U.number().nullish(),accepted_prediction_tokens:U.number().nullish(),rejected_prediction_tokens:U.number().nullish()}).nullish()}).nullish(),Bn=U.object({id:U.string().nullish(),created:U.number().nullish(),model:U.string().nullish(),choices:U.array(U.object({message:U.object({role:U.literal(`assistant`).nullish(),content:U.string().nullish(),tool_calls:U.array(U.object({id:U.string().nullish(),type:U.literal(`function`),function:U.object({name:U.string(),arguments:U.string()})})).nullish(),annotations:U.array(U.object({type:U.literal(`url_citation`),start_index:U.number(),end_index:U.number(),url:U.string(),title:U.string()})).nullish()}),index:U.number(),logprobs:U.object({content:U.array(U.object({token:U.string(),logprob:U.number(),top_logprobs:U.array(U.object({token:U.string(),logprob:U.number()}))})).nullish()}).nullish(),finish_reason:U.string().nullish()})),usage:zn}),Vn=U.union([U.object({id:U.string().nullish(),created:U.number().nullish(),model:U.string().nullish(),choices:U.array(U.object({delta:U.object({role:U.enum([`assistant`]).nullish(),content:U.string().nullish(),tool_calls:U.array(U.object({index:U.number(),id:U.string().nullish(),type:U.literal(`function`).nullish(),function:U.object({name:U.string().nullish(),arguments:U.string().nullish()})})).nullish(),annotations:U.array(U.object({type:U.literal(`url_citation`),start_index:U.number(),end_index:U.number(),url:U.string(),title:U.string()})).nullish()}).nullish(),logprobs:U.object({content:U.array(U.object({token:U.string(),logprob:U.number(),top_logprobs:U.array(U.object({token:U.string(),logprob:U.number()}))})).nullish()}).nullish(),finish_reason:U.string().nullish(),index:U.number()})),usage:zn}),jn]);function Hn(e){return(e.startsWith(`o`)||e.startsWith(`gpt-5`))&&!e.startsWith(`gpt-5-chat`)}function Un(e){return e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`)}function Wn(e){return e.startsWith(`gpt-4`)||e.startsWith(`gpt-5-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-nano`)&&!e.startsWith(`gpt-5-chat`)||e.startsWith(`o3`)||e.startsWith(`o4-mini`)}function Gn(e){return Hn(e)?Kn[e]?.systemMessageMode??`developer`:`system`}var Kn={"o1-mini":{systemMessageMode:`remove`},"o1-mini-2024-09-12":{systemMessageMode:`remove`},"o1-preview":{systemMessageMode:`remove`},"o1-preview-2024-09-12":{systemMessageMode:`remove`},o3:{systemMessageMode:`developer`},"o3-2025-04-16":{systemMessageMode:`developer`},"o3-mini":{systemMessageMode:`developer`},"o3-mini-2025-01-31":{systemMessageMode:`developer`},"o4-mini":{systemMessageMode:`developer`},"o4-mini-2025-04-16":{systemMessageMode:`developer`}};function qn({prompt:e,user:t=`user`,assistant:n=`assistant`}){let r=``;e[0].role===`system`&&(r+=`${e[0].content}
|
|
6
6
|
|
|
7
7
|
`,e=e.slice(1));for(let{role:i,content:a}of e)switch(i){case`system`:throw new p({message:"Unexpected system message in prompt: ${content}",prompt:e});case`user`:{let e=a.map(e=>{switch(e.type){case`text`:return e.text}}).filter(Boolean).join(``);r+=`${t}:
|
|
8
8
|
${e}
|
|
@@ -12,7 +12,7 @@ ${e}
|
|
|
12
12
|
|
|
13
13
|
`;break}case`tool`:throw new b({functionality:`tool messages`});default:{let e=i;throw Error(`Unsupported role: ${e}`)}}return r+=`${n}:
|
|
14
14
|
`,{prompt:r,stopSequences:[`
|
|
15
|
-
${t}:`]}}function Jn({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function Yn(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`content_filter`:return`content-filter`;case`function_call`:case`tool_calls`:return`tool-calls`;default:return`unknown`}}var Xn=U.object({echo:U.boolean().optional(),logitBias:U.record(U.string(),U.number()).optional(),suffix:U.string().optional(),user:U.string().optional(),logprobs:U.union([U.boolean(),U.number()]).optional()}),Zn=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(`.`)[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,tools:l,toolChoice:u,seed:d,providerOptions:f}){let p=[],m={...await L({provider:`openai`,providerOptions:f,schema:Xn}),...await L({provider:this.providerOptionsName,providerOptions:f,schema:Xn})};i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),l?.length&&p.push({type:`unsupported-setting`,setting:`tools`}),u!=null&&p.push({type:`unsupported-setting`,setting:`toolChoice`}),c!=null&&c.type!==`text`&&p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format is not supported.`});let{prompt:h,stopSequences:g}=qn({prompt:e}),_=[...g??[],...s??[]];return{args:{model:this.modelId,echo:m.echo,logit_bias:m.logitBias,logprobs:m?.logprobs===!0?0:m?.logprobs===!1?void 0:m?.logprobs,suffix:m.suffix,user:m.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:a,presence_penalty:o,seed:d,prompt:h,stop:_.length>0?_:void 0},warnings:p}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:i,rawValue:a}=await z({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:x(this.config.headers(),e.headers),body:t,failedResponseHandler:Mn,successfulResponseHandler:D($n),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=i.choices[0],s={openai:{}};return o.logprobs!=null&&(s.openai.logprobs=o.logprobs),{content:[{type:`text`,text:o.text}],usage:{inputTokens:i.usage?.prompt_tokens,outputTokens:i.usage?.completion_tokens,totalTokens:i.usage?.total_tokens},finishReason:Yn(o.finish_reason),request:{body:t},response:{...Jn(i),headers:r,body:a},providerMetadata:s,warnings:n}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:a}=await z({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:x(this.config.headers(),e.headers),body:r,failedResponseHandler:Mn,successfulResponseHandler:T(er),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=`unknown`,s={openai:{}},c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=!0;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){o=`error`,n.enqueue({type:`error`,error:t.error});return}let r=t.value;if(`error`in r){o=`error`,n.enqueue({type:`error`,error:r.error});return}l&&(l=!1,n.enqueue({type:`response-metadata`,...Jn(r)}),n.enqueue({type:`text-start`,id:`0`})),r.usage!=null&&(c.inputTokens=r.usage.prompt_tokens,c.outputTokens=r.usage.completion_tokens,c.totalTokens=r.usage.total_tokens);let i=r.choices[0];i?.finish_reason!=null&&(o=Yn(i.finish_reason)),i?.logprobs!=null&&(s.openai.logprobs=i.logprobs),i?.text!=null&&i.text.length>0&&n.enqueue({type:`text-delta`,id:`0`,delta:i.text})},flush(e){l||e.enqueue({type:`text-end`,id:`0`}),e.enqueue({type:`finish`,finishReason:o,providerMetadata:s,usage:c})}})),request:{body:r},response:{headers:i}}}},Qn=U.object({prompt_tokens:U.number(),completion_tokens:U.number(),total_tokens:U.number()}),$n=U.object({id:U.string().nullish(),created:U.number().nullish(),model:U.string().nullish(),choices:U.array(U.object({text:U.string(),finish_reason:U.string(),logprobs:U.object({tokens:U.array(U.string()),token_logprobs:U.array(U.number()),top_logprobs:U.array(U.record(U.string(),U.number())).nullish()}).nullish()})),usage:Qn.nullish()}),er=U.union([U.object({id:U.string().nullish(),created:U.number().nullish(),model:U.string().nullish(),choices:U.array(U.object({text:U.string(),finish_reason:U.string().nullish(),index:U.number(),logprobs:U.object({tokens:U.array(U.string()),token_logprobs:U.array(U.number()),top_logprobs:U.array(U.record(U.string(),U.number())).nullish()}).nullish()})),usage:Qn.nullish()}),jn]),tr=U.object({dimensions:U.number().optional(),user:U.string().optional()}),nr=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){if(e.length>this.maxEmbeddingsPerCall)throw new v({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let i=await L({provider:`openai`,providerOptions:r,schema:tr})??{},{responseHeaders:a,value:o,rawValue:s}=await z({url:this.config.url({path:`/embeddings`,modelId:this.modelId}),headers:x(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:`float`,dimensions:i.dimensions,user:i.user},failedResponseHandler:Mn,successfulResponseHandler:D(rr),abortSignal:n,fetch:this.config.fetch});return{embeddings:o.data.map(e=>e.embedding),usage:o.usage?{tokens:o.usage.prompt_tokens}:void 0,response:{headers:a,body:s}}}},rr=U.object({data:U.array(U.object({embedding:U.array(U.number())})),usage:U.object({prompt_tokens:U.number()}).nullish()}),ir={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},ar=new Set([`gpt-image-1`]),or=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get maxImagesPerCall(){return ir[this.modelId]??1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:a,headers:o,abortSignal:s}){var c;let l=[];r!=null&&l.push({type:`unsupported-setting`,setting:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&l.push({type:`unsupported-setting`,setting:`seed`});let u=((c=this.config._internal)?.currentDate)?.call(c)??new Date,{value:d,responseHeaders:f}=await z({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:x(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...a.openai??{},...ar.has(this.modelId)?{}:{response_format:`b64_json`}},failedResponseHandler:Mn,successfulResponseHandler:D(sr),abortSignal:s,fetch:this.config.fetch});return{images:d.data.map(e=>e.b64_json),warnings:l,response:{timestamp:u,modelId:this.modelId,headers:f},providerMetadata:{openai:{images:d.data.map(e=>e.revised_prompt?{revisedPrompt:e.revised_prompt}:null)}}}}},sr=U.object({data:U.array(U.object({b64_json:U.string(),revised_prompt:U.string().optional()}))}),cr=U.object({code:U.string().nullish(),containerId:U.string()}),lr=U.object({outputs:U.array(U.discriminatedUnion(`type`,[U.object({type:U.literal(`logs`),logs:U.string()}),U.object({type:U.literal(`image`),url:U.string()})])).nullish()}),ur=U.object({container:U.union([U.string(),U.object({fileIds:U.array(U.string()).optional()})]).optional()}),dr=k({id:`openai.code_interpreter`,name:`code_interpreter`,inputSchema:cr,outputSchema:lr}),fr=(e={})=>dr(e),pr=U.object({key:U.string(),type:U.enum([`eq`,`ne`,`gt`,`gte`,`lt`,`lte`]),value:U.union([U.string(),U.number(),U.boolean()])}),mr=U.object({type:U.enum([`and`,`or`]),filters:U.array(U.union([pr,U.lazy(()=>mr)]))}),hr=U.object({vectorStoreIds:U.array(U.string()),maxNumResults:U.number().optional(),ranking:U.object({ranker:U.string().optional(),scoreThreshold:U.number().optional()}).optional(),filters:U.union([pr,mr]).optional()}),gr=U.object({queries:U.array(U.string()),results:U.array(U.object({attributes:U.record(U.string(),U.unknown()),fileId:U.string(),filename:U.string(),score:U.number(),text:U.string()})).nullable()}),_r=k({id:`openai.file_search`,name:`file_search`,inputSchema:U.object({}),outputSchema:gr}),vr=U.object({background:U.enum([`auto`,`opaque`,`transparent`]).optional(),inputFidelity:U.enum([`low`,`high`]).optional(),inputImageMask:U.object({fileId:U.string().optional(),imageUrl:U.string().optional()}).optional(),model:U.string().optional(),moderation:U.enum([`auto`]).optional(),outputCompression:U.number().int().min(0).max(100).optional(),outputFormat:U.enum([`png`,`jpeg`,`webp`]).optional(),quality:U.enum([`auto`,`low`,`medium`,`high`]).optional(),size:U.enum([`1024x1024`,`1024x1536`,`1536x1024`,`auto`]).optional()}).strict(),yr=U.object({result:U.string()}),br=k({id:`openai.image_generation`,name:`image_generation`,inputSchema:U.object({}),outputSchema:yr}),xr=(e={})=>br(e),Sr=U.object({action:U.object({type:U.literal(`exec`),command:U.array(U.string()),timeoutMs:U.number().optional(),user:U.string().optional(),workingDirectory:U.string().optional(),env:U.record(U.string(),U.string()).optional()})}),Cr=U.object({output:U.string()}),wr=k({id:`openai.local_shell`,name:`local_shell`,inputSchema:Sr,outputSchema:Cr}),Tr=U.object({filters:U.object({allowedDomains:U.array(U.string()).optional()}).optional(),searchContextSize:U.enum([`low`,`medium`,`high`]).optional(),userLocation:U.object({type:U.literal(`approximate`),country:U.string().optional(),city:U.string().optional(),region:U.string().optional(),timezone:U.string().optional()}).optional()}),Er=O({id:`openai.web_search`,name:`web_search`,inputSchema:U.object({action:U.discriminatedUnion(`type`,[U.object({type:U.literal(`search`),query:U.string().nullish()}),U.object({type:U.literal(`open_page`),url:U.string()}),U.object({type:U.literal(`find`),url:U.string(),pattern:U.string()})]).nullish()})}),Dr=(e={})=>Er(e),Or=U.object({searchContextSize:U.enum([`low`,`medium`,`high`]).optional(),userLocation:U.object({type:U.literal(`approximate`),country:U.string().optional(),city:U.string().optional(),region:U.string().optional(),timezone:U.string().optional()}).optional()}),kr=O({id:`openai.web_search_preview`,name:`web_search_preview`,inputSchema:U.object({action:U.discriminatedUnion(`type`,[U.object({type:U.literal(`search`),query:U.string().nullish()}),U.object({type:U.literal(`open_page`),url:U.string()}),U.object({type:U.literal(`find`),url:U.string(),pattern:U.string()})]).nullish()})}),Ar={codeInterpreter:fr,fileSearch:_r,imageGeneration:xr,localShell:wr,webSearchPreview:kr,webSearch:Dr};function jr(e,t){return t?t.some(t=>e.startsWith(t)):!1}async function Mr({prompt:e,systemMessageMode:t,fileIdPrefixes:n,store:r,hasLocalShellTool:i=!1}){let a=[],o=[];for(let{role:s,content:c}of e)switch(s){case`system`:switch(t){case`system`:a.push({role:`system`,content:c});break;case`developer`:a.push({role:`developer`,content:c});break;case`remove`:o.push({type:`other`,message:`system messages are removed for this model`});break;default:{let e=t;throw Error(`Unsupported system message mode: ${e}`)}}break;case`user`:a.push({role:`user`,content:c.map((e,t)=>{switch(e.type){case`text`:return{type:`input_text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`input_image`,...e.data instanceof URL?{image_url:e.data.toString()}:typeof e.data==`string`&&jr(e.data,n)?{file_id:e.data}:{image_url:`data:${t};base64,${C(e.data)}`},detail:e.providerOptions?.openai?.imageDetail}}else if(e.mediaType===`application/pdf`)return e.data instanceof URL?{type:`input_file`,file_url:e.data.toString()}:{type:`input_file`,...typeof e.data==`string`&&jr(e.data,n)?{file_id:e.data}:{filename:e.filename??`part-${t}.pdf`,file_data:`data:application/pdf;base64,${C(e.data)}`}};else throw new b({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e={},t={};for(let n of c)switch(n.type){case`text`:a.push({role:`assistant`,content:[{type:`output_text`,text:n.text}],id:n.providerOptions?.openai?.itemId??void 0});break;case`tool-call`:if(t[n.toolCallId]=n,n.providerExecuted)break;if(i&&n.toolName===`local_shell`){let e=Sr.parse(n.input);a.push({type:`local_shell_call`,call_id:n.toolCallId,id:n.providerOptions?.openai?.itemId??void 0,action:{type:`exec`,command:e.action.command,timeout_ms:e.action.timeoutMs,user:e.action.user,working_directory:e.action.workingDirectory,env:e.action.env}});break}a.push({type:`function_call`,call_id:n.toolCallId,name:n.toolName,arguments:JSON.stringify(n.input),id:n.providerOptions?.openai?.itemId??void 0});break;case`tool-result`:r?a.push({type:`item_reference`,id:n.toolCallId}):o.push({type:`other`,message:`Results for OpenAI tool ${n.toolName} are not sent to the API when store is false`});break;case`reasoning`:{let t=await L({provider:`openai`,providerOptions:n.providerOptions,schema:Nr}),i=t?.itemId;if(i!=null){let s=e[i];if(r)s===void 0&&(a.push({type:`item_reference`,id:i}),e[i]={type:`reasoning`,id:i,summary:[]});else{let r=[];n.text.length>0?r.push({type:`summary_text`,text:n.text}):s!==void 0&&o.push({type:`other`,message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(n)}.`}),s===void 0?(e[i]={type:`reasoning`,id:i,encrypted_content:t?.reasoningEncryptedContent,summary:r},a.push(e[i])):s.summary.push(...r)}}else o.push({type:`other`,message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(n)}.`});break}}break}case`tool`:for(let e of c){let t=e.output;if(i&&e.toolName===`local_shell`&&t.type===`json`){a.push({type:`local_shell_call_output`,call_id:e.toolCallId,output:Cr.parse(t.value).output});break}let n;switch(t.type){case`text`:case`error-text`:n=t.value;break;case`content`:case`json`:case`error-json`:n=JSON.stringify(t.value);break}a.push({type:`function_call_output`,call_id:e.toolCallId,output:n})}break;default:{let e=s;throw Error(`Unsupported role: ${e}`)}}return{input:a,warnings:o}}var Nr=U.object({itemId:U.string().nullish(),reasoningEncryptedContent:U.string().nullish()});function Pr({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?`tool-calls`:`stop`;case`max_output_tokens`:return`length`;case`content_filter`:return`content-filter`;default:return t?`tool-calls`:`unknown`}}function Fr({tools:e,toolChoice:t,strictJsonSchema:n}){e=e?.length?e:void 0;let r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};let i=[];for(let t of e)switch(t.type){case`function`:i.push({type:`function`,name:t.name,description:t.description,parameters:t.inputSchema,strict:n});break;case`provider-defined`:switch(t.id){case`openai.file_search`:{let e=hr.parse(t.args);i.push({type:`file_search`,vector_store_ids:e.vectorStoreIds,max_num_results:e.maxNumResults,ranking_options:e.ranking?{ranker:e.ranking.ranker,score_threshold:e.ranking.scoreThreshold}:void 0,filters:e.filters});break}case`openai.local_shell`:i.push({type:`local_shell`});break;case`openai.web_search_preview`:{let e=Or.parse(t.args);i.push({type:`web_search_preview`,search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.web_search`:{let e=Tr.parse(t.args);i.push({type:`web_search`,filters:e.filters==null?void 0:{allowed_domains:e.filters.allowedDomains},search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.code_interpreter`:{let e=ur.parse(t.args);i.push({type:`code_interpreter`,container:e.container==null?{type:`auto`,file_ids:void 0}:typeof e.container==`string`?e.container:{type:`auto`,file_ids:e.container.fileIds}});break}case`openai.image_generation`:{let e=vr.parse(t.args);i.push({type:`image_generation`,background:e.background,input_fidelity:e.inputFidelity,input_image_mask:e.inputImageMask?{file_id:e.inputImageMask.fileId,image_url:e.inputImageMask.imageUrl}:void 0,model:e.model,size:e.size,quality:e.quality,moderation:e.moderation,output_format:e.outputFormat,output_compression:e.outputCompression});break}}break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:i,toolChoice:void 0,toolWarnings:r};let a=t.type;switch(a){case`auto`:case`none`:case`required`:return{tools:i,toolChoice:a,toolWarnings:r};case`tool`:return{tools:i,toolChoice:t.toolName===`code_interpreter`||t.toolName===`file_search`||t.toolName===`image_generation`||t.toolName===`web_search_preview`||t.toolName===`web_search`?{type:t.toolName}:{type:`function`,name:t.toolName},toolWarnings:r};default:throw new b({functionality:`tool choice type: ${a}`})}}var Ir=U.object({type:U.literal(`web_search_call`),id:U.string(),status:U.string(),action:U.discriminatedUnion(`type`,[U.object({type:U.literal(`search`),query:U.string().nullish()}),U.object({type:U.literal(`open_page`),url:U.string()}),U.object({type:U.literal(`find`),url:U.string(),pattern:U.string()})]).nullish()}),Lr=U.object({type:U.literal(`file_search_call`),id:U.string(),queries:U.array(U.string()),results:U.array(U.object({attributes:U.record(U.string(),U.unknown()),file_id:U.string(),filename:U.string(),score:U.number(),text:U.string()})).nullish()}),Rr=U.object({type:U.literal(`code_interpreter_call`),id:U.string(),code:U.string().nullable(),container_id:U.string(),outputs:U.array(U.discriminatedUnion(`type`,[U.object({type:U.literal(`logs`),logs:U.string()}),U.object({type:U.literal(`image`),url:U.string()})])).nullable()}),zr=U.object({type:U.literal(`local_shell_call`),id:U.string(),call_id:U.string(),action:U.object({type:U.literal(`exec`),command:U.array(U.string()),timeout_ms:U.number().optional(),user:U.string().optional(),working_directory:U.string().optional(),env:U.record(U.string(),U.string()).optional()})}),Br=U.object({type:U.literal(`image_generation_call`),id:U.string(),result:U.string()}),Vr=20,Hr=U.array(U.object({token:U.string(),logprob:U.number(),top_logprobs:U.array(U.object({token:U.string(),logprob:U.number()}))})),Ur=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:i,presencePenalty:a,frequencyPenalty:o,seed:s,prompt:c,providerOptions:l,tools:u,toolChoice:d,responseFormat:f}){let p=[],m=vi(this.modelId);i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),s!=null&&p.push({type:`unsupported-setting`,setting:`seed`}),a!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),n!=null&&p.push({type:`unsupported-setting`,setting:`stopSequences`});let h=await L({provider:`openai`,providerOptions:l,schema:yi}),{input:g,warnings:_}=await Mr({prompt:c,systemMessageMode:m.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:h?.store??!0,hasLocalShellTool:x(`openai.local_shell`)});p.push(..._);let v=h?.strictJsonSchema??!1,y=h?.include;function b(e){y=y==null?[e]:[...y,e]}function x(e){return u?.find(t=>t.type===`provider-defined`&&t.id===e)!=null}let S=typeof h?.logprobs==`number`?h?.logprobs:h?.logprobs===!0?Vr:void 0;S&&b(`message.output_text.logprobs`);let C=u?.find(e=>e.type===`provider-defined`&&(e.id===`openai.web_search`||e.id===`openai.web_search_preview`))?.name;C&&b(`web_search_call.action.sources`),x(`openai.code_interpreter`)&&b(`code_interpreter_call.outputs`);let w={model:this.modelId,input:g,temperature:t,top_p:r,max_output_tokens:e,...(f?.type===`json`||h?.textVerbosity)&&{text:{...f?.type===`json`&&{format:f.schema==null?{type:`json_object`}:{type:`json_schema`,strict:v,name:f.name??`response`,description:f.description,schema:f.schema}},...h?.textVerbosity&&{verbosity:h.textVerbosity}}},max_tool_calls:h?.maxToolCalls,metadata:h?.metadata,parallel_tool_calls:h?.parallelToolCalls,previous_response_id:h?.previousResponseId,store:h?.store,user:h?.user,instructions:h?.instructions,service_tier:h?.serviceTier,include:y,prompt_cache_key:h?.promptCacheKey,safety_identifier:h?.safetyIdentifier,top_logprobs:S,...m.isReasoningModel&&(h?.reasoningEffort!=null||h?.reasoningSummary!=null)&&{reasoning:{...h?.reasoningEffort!=null&&{effort:h.reasoningEffort},...h?.reasoningSummary!=null&&{summary:h.reasoningSummary}}},...m.requiredAutoTruncation&&{truncation:`auto`}};m.isReasoningModel?(w.temperature!=null&&(w.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for reasoning models`})),w.top_p!=null&&(w.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported for reasoning models`}))):(h?.reasoningEffort!=null&&p.push({type:`unsupported-setting`,setting:`reasoningEffort`,details:`reasoningEffort is not supported for non-reasoning models`}),h?.reasoningSummary!=null&&p.push({type:`unsupported-setting`,setting:`reasoningSummary`,details:`reasoningSummary is not supported for non-reasoning models`})),h?.serviceTier===`flex`&&!m.supportsFlexProcessing&&(p.push({type:`unsupported-setting`,setting:`serviceTier`,details:`flex processing is only available for o3, o4-mini, and gpt-5 models`}),delete w.service_tier),h?.serviceTier===`priority`&&!m.supportsPriorityProcessing&&(p.push({type:`unsupported-setting`,setting:`serviceTier`,details:`priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported`}),delete w.service_tier);let{tools:T,toolChoice:E,toolWarnings:D}=Fr({tools:u,toolChoice:d,strictJsonSchema:v});return{webSearchToolName:C,args:{...w,tools:T,tool_choice:E},warnings:[...p,...D]}}async doGenerate(e){var t,n;let{args:r,warnings:i,webSearchToolName:a}=await this.getArgs(e),o=this.config.url({path:`/responses`,modelId:this.modelId}),{responseHeaders:c,value:l,rawValue:u}=await z({url:o,headers:x(this.config.headers(),e.headers),body:r,failedResponseHandler:Mn,successfulResponseHandler:D(U.object({id:U.string(),created_at:U.number(),error:U.object({code:U.string(),message:U.string()}).nullish(),model:U.string(),output:U.array(U.discriminatedUnion(`type`,[U.object({type:U.literal(`message`),role:U.literal(`assistant`),id:U.string(),content:U.array(U.object({type:U.literal(`output_text`),text:U.string(),logprobs:Hr.nullish(),annotations:U.array(U.discriminatedUnion(`type`,[U.object({type:U.literal(`url_citation`),start_index:U.number(),end_index:U.number(),url:U.string(),title:U.string()}),U.object({type:U.literal(`file_citation`),file_id:U.string(),filename:U.string().nullish(),index:U.number().nullish(),start_index:U.number().nullish(),end_index:U.number().nullish(),quote:U.string().nullish()}),U.object({type:U.literal(`container_file_citation`)})]))}))}),Ir,Lr,Rr,Br,zr,U.object({type:U.literal(`function_call`),call_id:U.string(),name:U.string(),arguments:U.string(),id:U.string()}),U.object({type:U.literal(`computer_call`),id:U.string(),status:U.string().optional()}),U.object({type:U.literal(`reasoning`),id:U.string(),encrypted_content:U.string().nullish(),summary:U.array(U.object({type:U.literal(`summary_text`),text:U.string()}))})])),service_tier:U.string().nullish(),incomplete_details:U.object({reason:U.string()}).nullish(),usage:Wr})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(l.error)throw new s({message:l.error.message,url:o,requestBodyValues:r,statusCode:400,responseHeaders:c,responseBody:u,isRetryable:!1});let d=[],f=[],p=!1;for(let r of l.output)switch(r.type){case`reasoning`:r.summary.length===0&&r.summary.push({type:`summary_text`,text:``});for(let e of r.summary)d.push({type:`reasoning`,text:e.text,providerMetadata:{openai:{itemId:r.id,reasoningEncryptedContent:r.encrypted_content??null}}});break;case`image_generation_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`image_generation`,input:`{}`,providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`image_generation`,result:{result:r.result},providerExecuted:!0});break;case`local_shell_call`:d.push({type:`tool-call`,toolCallId:r.call_id,toolName:`local_shell`,input:JSON.stringify({action:r.action}),providerMetadata:{openai:{itemId:r.id}}});break;case`message`:for(let i of r.content){e.providerOptions?.openai?.logprobs&&i.logprobs&&f.push(i.logprobs),d.push({type:`text`,text:i.text,providerMetadata:{openai:{itemId:r.id}}});for(let e of i.annotations)e.type===`url_citation`?d.push({type:`source`,sourceType:`url`,id:(t=this.config).generateId?.call(t)??j(),url:e.url,title:e.title}):e.type===`file_citation`&&d.push({type:`source`,sourceType:`document`,id:(n=this.config).generateId?.call(n)??j(),mediaType:`text/plain`,title:e.quote??e.filename??`Document`,filename:e.filename??e.file_id})}break;case`function_call`:p=!0,d.push({type:`tool-call`,toolCallId:r.call_id,toolName:r.name,input:r.arguments,providerMetadata:{openai:{itemId:r.id}}});break;case`web_search_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:a??`web_search`,input:JSON.stringify({action:r.action}),providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:a??`web_search`,result:{status:r.status},providerExecuted:!0});break;case`computer_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`computer_use`,input:``,providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:r.status||`completed`},providerExecuted:!0});break;case`file_search_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`file_search`,input:`{}`,providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`file_search`,result:{queries:r.queries,results:r.results?.map(e=>({attributes:e.attributes,fileId:e.file_id,filename:e.filename,score:e.score,text:e.text}))??null},providerExecuted:!0});break;case`code_interpreter_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`code_interpreter`,input:JSON.stringify({code:r.code,containerId:r.container_id}),providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`code_interpreter`,result:{outputs:r.outputs},providerExecuted:!0});break}let m={openai:{responseId:l.id}};return f.length>0&&(m.openai.logprobs=f),typeof l.service_tier==`string`&&(m.openai.serviceTier=l.service_tier),{content:d,finishReason:Pr({finishReason:l.incomplete_details?.reason,hasFunctionCall:p}),usage:{inputTokens:l.usage.input_tokens,outputTokens:l.usage.output_tokens,totalTokens:l.usage.input_tokens+l.usage.output_tokens,reasoningTokens:l.usage.output_tokens_details?.reasoning_tokens??void 0,cachedInputTokens:l.usage.input_tokens_details?.cached_tokens??void 0},request:{body:r},response:{id:l.id,timestamp:new Date(l.created_at*1e3),modelId:l.model,headers:c,body:u},providerMetadata:m,warnings:i}}async doStream(e){let{args:t,warnings:n,webSearchToolName:r}=await this.getArgs(e),{responseHeaders:i,value:a}=await z({url:this.config.url({path:`/responses`,modelId:this.modelId}),headers:x(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Mn,successfulResponseHandler:T(ri),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=this,s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=[],u=null,d={},f=!1,p={},m;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){var i,a,h;if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){s=`error`,n.enqueue({type:`error`,error:t.error});return}let g=t.value;if(fi(g))g.item.type===`function_call`?(d[g.output_index]={toolName:g.item.name,toolCallId:g.item.call_id},n.enqueue({type:`tool-input-start`,id:g.item.call_id,toolName:g.item.name})):g.item.type===`web_search_call`?(d[g.output_index]={toolName:r??`web_search`,toolCallId:g.item.id},n.enqueue({type:`tool-input-start`,id:g.item.id,toolName:r??`web_search`})):g.item.type===`computer_call`?(d[g.output_index]={toolName:`computer_use`,toolCallId:g.item.id},n.enqueue({type:`tool-input-start`,id:g.item.id,toolName:`computer_use`})):g.item.type===`code_interpreter_call`?(d[g.output_index]={toolName:`code_interpreter`,toolCallId:g.item.id,codeInterpreter:{containerId:g.item.container_id}},n.enqueue({type:`tool-input-start`,id:g.item.id,toolName:`code_interpreter`}),n.enqueue({type:`tool-input-delta`,id:g.item.id,delta:`{"containerId":"${g.item.container_id}","code":"`})):g.item.type===`file_search_call`?n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`file_search`,input:`{}`,providerExecuted:!0}):g.item.type===`image_generation_call`?n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`image_generation`,input:`{}`,providerExecuted:!0}):g.item.type===`message`?n.enqueue({type:`text-start`,id:g.item.id,providerMetadata:{openai:{itemId:g.item.id}}}):pi(g)&&(p[g.item.id]={encryptedContent:g.item.encrypted_content,summaryParts:[0]},n.enqueue({type:`reasoning-start`,id:`${g.item.id}:0`,providerMetadata:{openai:{itemId:g.item.id,reasoningEncryptedContent:g.item.encrypted_content??null}}}));else if(ai(g)){if(g.item.type===`function_call`)d[g.output_index]=void 0,f=!0,n.enqueue({type:`tool-input-end`,id:g.item.call_id}),n.enqueue({type:`tool-call`,toolCallId:g.item.call_id,toolName:g.item.name,input:g.item.arguments,providerMetadata:{openai:{itemId:g.item.id}}});else if(g.item.type===`web_search_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:g.item.id}),n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`web_search`,input:JSON.stringify({action:g.item.action}),providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`web_search`,result:{status:g.item.status},providerExecuted:!0});else if(g.item.type===`computer_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:g.item.id}),n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`computer_use`,input:``,providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:g.item.status||`completed`},providerExecuted:!0});else if(g.item.type===`file_search_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`file_search`,result:{queries:g.item.queries,results:g.item.results?.map(e=>({attributes:e.attributes,fileId:e.file_id,filename:e.filename,score:e.score,text:e.text}))??null},providerExecuted:!0});else if(g.item.type===`code_interpreter_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`code_interpreter`,result:{outputs:g.item.outputs},providerExecuted:!0});else if(g.item.type===`image_generation_call`)n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`image_generation`,result:{result:g.item.result},providerExecuted:!0});else if(g.item.type===`local_shell_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-call`,toolCallId:g.item.call_id,toolName:`local_shell`,input:JSON.stringify({action:{type:`exec`,command:g.item.action.command,timeoutMs:g.item.action.timeout_ms,user:g.item.action.user,workingDirectory:g.item.action.working_directory,env:g.item.action.env}}),providerMetadata:{openai:{itemId:g.item.id}}});else if(g.item.type===`message`)n.enqueue({type:`text-end`,id:g.item.id});else if(oi(g)){let e=p[g.item.id];for(let t of e.summaryParts)n.enqueue({type:`reasoning-end`,id:`${g.item.id}:${t}`,providerMetadata:{openai:{itemId:g.item.id,reasoningEncryptedContent:g.item.encrypted_content??null}}});delete p[g.item.id]}}else if(li(g)){let e=d[g.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:g.delta})}else if(ui(g)){let e=d[g.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:JSON.stringify(g.delta).slice(1,-1)})}else if(di(g)){let e=d[g.output_index];e!=null&&(n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:`"}`}),n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:`code_interpreter`,input:JSON.stringify({code:g.code,containerId:e.codeInterpreter.containerId}),providerExecuted:!0}))}else ci(g)?(u=g.response.id,n.enqueue({type:`response-metadata`,id:g.response.id,timestamp:new Date(g.response.created_at*1e3),modelId:g.response.model})):ii(g)?(n.enqueue({type:`text-delta`,id:g.item_id,delta:g.delta}),e.providerOptions?.openai?.logprobs&&g.logprobs&&l.push(g.logprobs)):hi(g)?g.summary_index>0&&((i=p[g.item_id])==null||i.summaryParts.push(g.summary_index),n.enqueue({type:`reasoning-start`,id:`${g.item_id}:${g.summary_index}`,providerMetadata:{openai:{itemId:g.item_id,reasoningEncryptedContent:p[g.item_id]?.encryptedContent??null}}})):gi(g)?n.enqueue({type:`reasoning-delta`,id:`${g.item_id}:${g.summary_index}`,delta:g.delta,providerMetadata:{openai:{itemId:g.item_id}}}):si(g)?(s=Pr({finishReason:g.response.incomplete_details?.reason,hasFunctionCall:f}),c.inputTokens=g.response.usage.input_tokens,c.outputTokens=g.response.usage.output_tokens,c.totalTokens=g.response.usage.input_tokens+g.response.usage.output_tokens,c.reasoningTokens=g.response.usage.output_tokens_details?.reasoning_tokens??void 0,c.cachedInputTokens=g.response.usage.input_tokens_details?.cached_tokens??void 0,typeof g.response.service_tier==`string`&&(m=g.response.service_tier)):mi(g)?g.annotation.type===`url_citation`?n.enqueue({type:`source`,sourceType:`url`,id:(a=o.config).generateId?.call(a)??j(),url:g.annotation.url,title:g.annotation.title}):g.annotation.type===`file_citation`&&n.enqueue({type:`source`,sourceType:`document`,id:(h=o.config).generateId?.call(h)??j(),mediaType:`text/plain`,title:g.annotation.quote??g.annotation.filename??`Document`,filename:g.annotation.filename??g.annotation.file_id}):_i(g)&&n.enqueue({type:`error`,error:g})},flush(e){let t={openai:{responseId:u}};l.length>0&&(t.openai.logprobs=l),m!==void 0&&(t.openai.serviceTier=m),e.enqueue({type:`finish`,finishReason:s,usage:c,providerMetadata:t})}})),request:{body:t},response:{headers:i}}}},Wr=U.object({input_tokens:U.number(),input_tokens_details:U.object({cached_tokens:U.number().nullish()}).nullish(),output_tokens:U.number(),output_tokens_details:U.object({reasoning_tokens:U.number().nullish()}).nullish()}),Gr=U.object({type:U.literal(`response.output_text.delta`),item_id:U.string(),delta:U.string(),logprobs:Hr.nullish()}),Kr=U.object({type:U.literal(`error`),code:U.string(),message:U.string(),param:U.string().nullish(),sequence_number:U.number()}),qr=U.object({type:U.enum([`response.completed`,`response.incomplete`]),response:U.object({incomplete_details:U.object({reason:U.string()}).nullish(),usage:Wr,service_tier:U.string().nullish()})}),Jr=U.object({type:U.literal(`response.created`),response:U.object({id:U.string(),created_at:U.number(),model:U.string(),service_tier:U.string().nullish()})}),Yr=U.object({type:U.literal(`response.output_item.added`),output_index:U.number(),item:U.discriminatedUnion(`type`,[U.object({type:U.literal(`message`),id:U.string()}),U.object({type:U.literal(`reasoning`),id:U.string(),encrypted_content:U.string().nullish()}),U.object({type:U.literal(`function_call`),id:U.string(),call_id:U.string(),name:U.string(),arguments:U.string()}),U.object({type:U.literal(`web_search_call`),id:U.string(),status:U.string(),action:U.object({type:U.literal(`search`),query:U.string().optional()}).nullish()}),U.object({type:U.literal(`computer_call`),id:U.string(),status:U.string()}),U.object({type:U.literal(`file_search_call`),id:U.string()}),U.object({type:U.literal(`image_generation_call`),id:U.string()}),U.object({type:U.literal(`code_interpreter_call`),id:U.string(),container_id:U.string(),code:U.string().nullable(),outputs:U.array(U.discriminatedUnion(`type`,[U.object({type:U.literal(`logs`),logs:U.string()}),U.object({type:U.literal(`image`),url:U.string()})])).nullable(),status:U.string()})])}),Xr=U.object({type:U.literal(`response.output_item.done`),output_index:U.number(),item:U.discriminatedUnion(`type`,[U.object({type:U.literal(`message`),id:U.string()}),U.object({type:U.literal(`reasoning`),id:U.string(),encrypted_content:U.string().nullish()}),U.object({type:U.literal(`function_call`),id:U.string(),call_id:U.string(),name:U.string(),arguments:U.string(),status:U.literal(`completed`)}),Rr,Br,Ir,Lr,zr,U.object({type:U.literal(`computer_call`),id:U.string(),status:U.literal(`completed`)})])}),Zr=U.object({type:U.literal(`response.function_call_arguments.delta`),item_id:U.string(),output_index:U.number(),delta:U.string()}),Qr=U.object({type:U.literal(`response.code_interpreter_call_code.delta`),item_id:U.string(),output_index:U.number(),delta:U.string()}),$r=U.object({type:U.literal(`response.code_interpreter_call_code.done`),item_id:U.string(),output_index:U.number(),code:U.string()}),ei=U.object({type:U.literal(`response.output_text.annotation.added`),annotation:U.discriminatedUnion(`type`,[U.object({type:U.literal(`url_citation`),url:U.string(),title:U.string()}),U.object({type:U.literal(`file_citation`),file_id:U.string(),filename:U.string().nullish(),index:U.number().nullish(),start_index:U.number().nullish(),end_index:U.number().nullish(),quote:U.string().nullish()})])}),ti=U.object({type:U.literal(`response.reasoning_summary_part.added`),item_id:U.string(),summary_index:U.number()}),ni=U.object({type:U.literal(`response.reasoning_summary_text.delta`),item_id:U.string(),summary_index:U.number(),delta:U.string()}),ri=U.union([Gr,qr,Jr,Yr,Xr,Zr,Qr,$r,ei,ti,ni,Kr,U.object({type:U.string()}).loose()]);function ii(e){return e.type===`response.output_text.delta`}function ai(e){return e.type===`response.output_item.done`}function oi(e){return ai(e)&&e.item.type===`reasoning`}function si(e){return e.type===`response.completed`||e.type===`response.incomplete`}function ci(e){return e.type===`response.created`}function li(e){return e.type===`response.function_call_arguments.delta`}function ui(e){return e.type===`response.code_interpreter_call_code.delta`}function di(e){return e.type===`response.code_interpreter_call_code.done`}function fi(e){return e.type===`response.output_item.added`}function pi(e){return fi(e)&&e.item.type===`reasoning`}function mi(e){return e.type===`response.output_text.annotation.added`}function hi(e){return e.type===`response.reasoning_summary_part.added`}function gi(e){return e.type===`response.reasoning_summary_text.delta`}function _i(e){return e.type===`error`}function vi(e){let t=e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`),n=e.startsWith(`gpt-4`)||e.startsWith(`gpt-5-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-nano`)&&!e.startsWith(`gpt-5-chat`)||e.startsWith(`o3`)||e.startsWith(`o4-mini`),r={requiredAutoTruncation:!1,systemMessageMode:`system`,supportsFlexProcessing:t,supportsPriorityProcessing:n};return e.startsWith(`gpt-5-chat`)?{...r,isReasoningModel:!1}:e.startsWith(`o`)||e.startsWith(`gpt-5`)||e.startsWith(`codex-`)||e.startsWith(`computer-use`)?e.startsWith(`o1-mini`)||e.startsWith(`o1-preview`)?{...r,isReasoningModel:!0,systemMessageMode:`remove`}:{...r,isReasoningModel:!0,systemMessageMode:`developer`}:{...r,isReasoningModel:!1}}var yi=U.object({include:U.array(U.enum([`reasoning.encrypted_content`,`file_search_call.results`,`message.output_text.logprobs`])).nullish(),instructions:U.string().nullish(),logprobs:U.union([U.boolean(),U.number().min(1).max(Vr)]).optional(),maxToolCalls:U.number().nullish(),metadata:U.any().nullish(),parallelToolCalls:U.boolean().nullish(),previousResponseId:U.string().nullish(),promptCacheKey:U.string().nullish(),reasoningEffort:U.string().nullish(),reasoningSummary:U.string().nullish(),safetyIdentifier:U.string().nullish(),serviceTier:U.enum([`auto`,`flex`,`priority`]).nullish(),store:U.boolean().nullish(),strictJsonSchema:U.boolean().nullish(),textVerbosity:U.enum([`low`,`medium`,`high`]).nullish(),user:U.string().nullish()}),bi=U.object({instructions:U.string().nullish(),speed:U.number().min(.25).max(4).default(1).nullish()}),xi=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get provider(){return this.config.provider}async getArgs({text:e,voice:t=`alloy`,outputFormat:n=`mp3`,speed:r,instructions:i,language:a,providerOptions:o}){let s=[],c=await L({provider:`openai`,providerOptions:o,schema:bi}),l={model:this.modelId,input:e,voice:t,response_format:`mp3`,speed:r,instructions:i};if(n&&([`mp3`,`opus`,`aac`,`flac`,`wav`,`pcm`].includes(n)?l.response_format=n:s.push({type:`unsupported-setting`,setting:`outputFormat`,details:`Unsupported output format: ${n}. Using mp3 instead.`})),c){let e={};for(let t in e){let n=e[t];n!==void 0&&(l[t]=n)}}return a&&s.push({type:`unsupported-setting`,setting:`language`,details:`OpenAI speech models do not support language selection. Language parameter "${a}" was ignored.`}),{requestBody:l,warnings:s}}async doGenerate(e){var t;let n=((t=this.config._internal)?.currentDate)?.call(t)??new Date,{requestBody:r,warnings:i}=await this.getArgs(e),{value:a,responseHeaders:o,rawValue:s}=await z({url:this.config.url({path:`/audio/speech`,modelId:this.modelId}),headers:x(this.config.headers(),e.headers),body:r,failedResponseHandler:Mn,successfulResponseHandler:w(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:a,warnings:i,request:{body:JSON.stringify(r)},response:{timestamp:n,modelId:this.modelId,headers:o,body:s}}}},Si=U.object({include:U.array(U.string()).optional(),language:U.string().optional(),prompt:U.string().optional(),temperature:U.number().min(0).max(1).default(0).optional(),timestampGranularities:U.array(U.enum([`word`,`segment`])).default([`segment`]).optional()}),Ci={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`},wi=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:n}){let r=[],i=await L({provider:`openai`,providerOptions:n,schema:Si}),a=new FormData,o=e instanceof Uint8Array?new Blob([e]):new Blob([S(e)]);a.append(`model`,this.modelId);let s=F(t);if(a.append(`file`,new File([o],`audio`,{type:t}),`audio.${s}`),i){let e={include:i.include,language:i.language,prompt:i.prompt,response_format:[`gpt-4o-transcribe`,`gpt-4o-mini-transcribe`].includes(this.modelId)?`json`:`verbose_json`,temperature:i.temperature,timestamp_granularities:i.timestampGranularities};for(let[t,n]of Object.entries(e))if(n!=null)if(Array.isArray(n))for(let e of n)a.append(`${t}[]`,String(e));else a.append(t,String(n))}return{formData:a,warnings:r}}async doGenerate(e){var t;let n=((t=this.config._internal)?.currentDate)?.call(t)??new Date,{formData:r,warnings:i}=await this.getArgs(e),{value:a,responseHeaders:o,rawValue:s}=await R({url:this.config.url({path:`/audio/transcriptions`,modelId:this.modelId}),headers:x(this.config.headers(),e.headers),formData:r,failedResponseHandler:Mn,successfulResponseHandler:D(Ti),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=a.language!=null&&a.language in Ci?Ci[a.language]:void 0;return{text:a.text,segments:a.segments?.map(e=>({text:e.text,startSecond:e.start,endSecond:e.end}))??a.words?.map(e=>({text:e.word,startSecond:e.start,endSecond:e.end}))??[],language:c,durationInSeconds:a.duration??void 0,warnings:i,response:{timestamp:n,modelId:this.modelId,headers:o,body:s}}}},Ti=U.object({text:U.string(),language:U.string().nullish(),duration:U.number().nullish(),words:U.array(U.object({word:U.string(),start:U.number(),end:U.number()})).nullish(),segments:U.array(U.object({id:U.number(),seek:U.number(),start:U.number(),end:U.number(),text:U.string(),tokens:U.array(U.number()),temperature:U.number(),avg_logprob:U.number(),compression_ratio:U.number(),no_speech_prob:U.number()})).nullish()}),Ei=`2.0.42`;function Di(e={}){let t=oe(ne({settingValue:e.baseURL,environmentVariableName:`OPENAI_BASE_URL`}))??`https://api.openai.com/v1`,n=e.name??`openai`,r=()=>ae({Authorization:`Bearer ${te({apiKey:e.apiKey,environmentVariableName:`OPENAI_API_KEY`,description:`OpenAI`})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${Ei}`),i=i=>new Rn(i,{provider:`${n}.chat`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),a=i=>new Zn(i,{provider:`${n}.completion`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),o=i=>new nr(i,{provider:`${n}.embedding`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),s=i=>new or(i,{provider:`${n}.image`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),c=i=>new wi(i,{provider:`${n}.transcription`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),l=i=>new xi(i,{provider:`${n}.speech`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),u=e=>{if(new.target)throw Error(`The OpenAI model function cannot be called with the new keyword.`);return d(e)},d=i=>new Ur(i,{provider:`${n}.responses`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch,fileIdPrefixes:[`file-`]}),f=function(e){return u(e)};return f.languageModel=u,f.chat=i,f.completion=a,f.responses=d,f.embedding=o,f.textEmbedding=o,f.textEmbeddingModel=o,f.image=s,f.imageModel=s,f.transcription=c,f.transcriptionModel=c,f.speech=l,f.speechModel=l,f.tools=Ar,f}Di();function Oi(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function ki(e){return Object.fromEntries([...e.headers])}function Ai(e=globalThis){return e.window?`runtime/browser`:e.navigator?.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:e.process?.versions?.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?`runtime/vercel-edge`:`runtime/unknown`}function ji(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function Mi(e,...t){let n=ji(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}(({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new f({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();function Ni(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Pi=[`fetch failed`,`failed to fetch`];function Fi({error:e,url:t,requestBodyValues:n}){if(Ni(e))return e;if(e instanceof TypeError&&Pi.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new s({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}var Ii=`3.0.10`,Li=/"__proto__"\s*:/,Ri=/"constructor"\s*:/;function zi(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Li.test(e)===!1&&Ri.test(e)===!1?t:Bi(t)}function Bi(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function Vi(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return zi(e)}finally{Error.stackTraceLimit=t}}var Hi=Symbol.for(`vercel.ai.validator`);function Ui(e){return{[Hi]:!0,validate:e}}function Wi(e){return typeof e==`object`&&!!e&&Hi in e&&e[Hi]===!0&&`validate`in e}function Gi(e){return Wi(e)?e:Ki(e)}function Ki(e){return Ui(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new y({value:t,cause:n.issues})}})}async function qi({value:e,schema:t}){let n=await Ji({value:e,schema:t});if(!n.success)throw y.wrap({value:e,cause:n.error});return n.value}async function Ji({value:e,schema:t}){let n=Gi(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:y.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:y.wrap({value:e,cause:t}),rawValue:e}}}async function Yi({text:e,schema:t}){try{let n=Vi(e);return t==null?n:qi({value:n,schema:t})}catch(t){throw h.isInstance(t)||y.isInstance(t)?t:new h({text:e,cause:t})}}async function Xi({text:e,schema:t}){try{let n=Vi(e);return t==null?{success:!0,value:n,rawValue:n}:await Ji({value:n,schema:t})}catch(t){return{success:!1,error:h.isInstance(t)?t:new h({text:e,cause:t}),rawValue:void 0}}}var Zi=()=>globalThis.fetch,Qi=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>$i({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),$i=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=Zi()})=>{try{let c=await o(e,{method:`POST`,headers:Mi(t,`ai-sdk/provider-utils/${Ii}`,Ai()),body:n.content,signal:a}),l=ki(c);if(!c.ok){let t;try{t=await i({response:c,url:e,requestBodyValues:n.values})}catch(t){throw Ni(t)||s.isInstance(t)?t:new s({message:`Failed to process error response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw t.value}try{return await r({response:c,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(Ni(t)||s.isInstance(t))?t:new s({message:`Failed to process successful response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(t){throw Fi({error:t,url:e,requestBodyValues:n.values})}},ea=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),c=ki(r);if(o.trim()===``)return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})};try{let l=await Yi({text:o,schema:e});return{responseHeaders:c,value:new s({message:t(l),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})}}},ta=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await Xi({text:i,schema:e}),o=ki(t);if(!a.success)throw new s({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},{btoa:na,atob:ra}=globalThis;U.object({user:U.string().optional(),reasoningEffort:U.string().optional()});var ia={errorSchema:U.object({error:U.object({message:U.string(),type:U.string().nullish(),param:U.any().nullish(),code:U.union([U.string(),U.number()]).nullish()})}),errorToMessage:e=>e.error.message},aa=U.object({prompt_tokens:U.number().nullish(),completion_tokens:U.number().nullish(),total_tokens:U.number().nullish(),prompt_tokens_details:U.object({cached_tokens:U.number().nullish()}).nullish(),completion_tokens_details:U.object({reasoning_tokens:U.number().nullish(),accepted_prediction_tokens:U.number().nullish(),rejected_prediction_tokens:U.number().nullish()}).nullish()}).nullish();U.object({id:U.string().nullish(),created:U.number().nullish(),model:U.string().nullish(),choices:U.array(U.object({message:U.object({role:U.literal(`assistant`).nullish(),content:U.string().nullish(),reasoning_content:U.string().nullish(),reasoning:U.string().nullish(),tool_calls:U.array(U.object({id:U.string().nullish(),function:U.object({name:U.string(),arguments:U.string()})})).nullish()}),finish_reason:U.string().nullish()})),usage:aa}),U.object({echo:U.boolean().optional(),logitBias:U.record(U.string(),U.number()).optional(),suffix:U.string().optional(),user:U.string().optional()});var oa=U.object({prompt_tokens:U.number(),completion_tokens:U.number(),total_tokens:U.number()});U.object({id:U.string().nullish(),created:U.number().nullish(),model:U.string().nullish(),choices:U.array(U.object({text:U.string(),finish_reason:U.string()})),usage:oa.nullish()}),U.object({dimensions:U.number().optional(),user:U.string().optional()}),U.object({data:U.array(U.object({embedding:U.array(U.number())})),usage:U.object({prompt_tokens:U.number()}).nullish(),providerMetadata:U.record(U.string(),U.record(U.string(),U.any())).optional()});var sa=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`,this.maxImagesPerCall=10}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:a,headers:o,abortSignal:s}){var c;let l=[];r!=null&&l.push({type:`unsupported-setting`,setting:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&l.push({type:`unsupported-setting`,setting:`seed`});let u=((c=this.config._internal)?.currentDate)?.call(c)??new Date,{value:d,responseHeaders:f}=await Qi({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:Oi(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...a.openai??{},response_format:`b64_json`},failedResponseHandler:ea(this.config.errorStructure??ia),successfulResponseHandler:ta(ca),abortSignal:s,fetch:this.config.fetch});return{images:d.data.map(e=>e.b64_json),warnings:l,response:{timestamp:u,modelId:this.modelId,headers:f}}}},ca=U.object({data:U.array(U.object({b64_json:U.string()}))});function la(e){let t=[],n=[];for(let{role:n,content:r}of e)switch(n){case`system`:t.push({role:`system`,content:r});break;case`user`:if(r.length===1&&r[0].type===`text`){t.push({role:`user`,content:r[0].text});break}t.push({role:`user`,content:r.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`image_url`,image_url:{url:e.data instanceof URL?e.data.toString():`data:${t};base64,${C(e.data)}`}}}else throw new b({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e=``,n=[];for(let t of r)switch(t.type){case`text`:e+=t.text;break;case`tool-call`:n.push({id:t.toolCallId,type:`function`,function:{name:t.toolName,arguments:JSON.stringify(t.input)}});break}t.push({role:`assistant`,content:e,tool_calls:n.length>0?n:void 0});break}case`tool`:for(let e of r){let n=e.output,r;switch(n.type){case`text`:case`error-text`:r=n.value;break;case`content`:case`json`:case`error-json`:r=JSON.stringify(n.value);break}t.push({role:`tool`,tool_call_id:e.toolCallId,content:r})}break;default:{let e=n;throw Error(`Unsupported role: ${e}`)}}return{messages:t,warnings:n}}function ua({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function da(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`tool_calls`:case`function_call`:return`tool-calls`;case`content_filter`:return`content-filter`;default:return`unknown`}}var fa=U.object({type:U.literal(`web`),country:U.string().length(2).optional(),excludedWebsites:U.array(U.string()).max(5).optional(),allowedWebsites:U.array(U.string()).max(5).optional(),safeSearch:U.boolean().optional()}),pa=U.object({type:U.literal(`x`),excludedXHandles:U.array(U.string()).optional(),includedXHandles:U.array(U.string()).optional(),postFavoriteCount:U.number().int().optional(),postViewCount:U.number().int().optional(),xHandles:U.array(U.string()).optional()}),ma=U.object({type:U.literal(`news`),country:U.string().length(2).optional(),excludedWebsites:U.array(U.string()).max(5).optional(),safeSearch:U.boolean().optional()}),ha=U.object({type:U.literal(`rss`),links:U.array(U.string().url()).max(1)}),ga=U.discriminatedUnion(`type`,[fa,pa,ma,ha]),_a=U.object({reasoningEffort:U.enum([`low`,`high`]).optional(),searchParameters:U.object({mode:U.enum([`off`,`auto`,`on`]),returnCitations:U.boolean().optional(),fromDate:U.string().optional(),toDate:U.string().optional(),maxSearchResults:U.number().min(1).max(50).optional(),sources:U.array(ga).optional()}).optional()}),va=U.object({error:U.object({message:U.string(),type:U.string().nullish(),param:U.any().nullish(),code:U.union([U.string(),U.number()]).nullish()})}),ya=E({errorSchema:va,errorToMessage:e=>e.error.message});function ba({tools:e,toolChoice:t}){e=e?.length?e:void 0;let n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};let r=[];for(let t of e)t.type===`provider-defined`?n.push({type:`unsupported-tool`,tool:t}):r.push({type:`function`,function:{name:t.name,description:t.description,parameters:t.inputSchema}});if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};let i=t.type;switch(i){case`auto`:case`none`:return{tools:r,toolChoice:i,toolWarnings:n};case`required`:return{tools:r,toolChoice:`required`,toolWarnings:n};case`tool`:return{tools:r,toolChoice:{type:`function`,function:{name:t.toolName}},toolWarnings:n};default:throw new b({functionality:`tool choice type: ${i}`})}}var xa=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,seed:c,responseFormat:l,providerOptions:u,tools:d,toolChoice:f}){let p=[],m=await L({provider:`xai`,providerOptions:u,schema:_a})??{};i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),a!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),s!=null&&p.push({type:`unsupported-setting`,setting:`stopSequences`}),l!=null&&l.type===`json`&&l.schema!=null&&p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format schema is not supported`});let{messages:h,warnings:g}=la(e);p.push(...g);let{tools:_,toolChoice:v,toolWarnings:y}=ba({tools:d,toolChoice:f});return p.push(...y),{args:{model:this.modelId,max_tokens:t,temperature:n,top_p:r,seed:c,reasoning_effort:m.reasoningEffort,response_format:l?.type===`json`?l.schema==null?{type:`json_object`}:{type:`json_schema`,json_schema:{name:l.name??`response`,schema:l.schema,strict:!0}}:void 0,search_parameters:m.searchParameters?{mode:m.searchParameters.mode,return_citations:m.searchParameters.returnCitations,from_date:m.searchParameters.fromDate,to_date:m.searchParameters.toDate,max_search_results:m.searchParameters.maxSearchResults,sources:m.searchParameters.sources?.map(e=>({type:e.type,...e.type===`web`&&{country:e.country,excluded_websites:e.excludedWebsites,allowed_websites:e.allowedWebsites,safe_search:e.safeSearch},...e.type===`x`&&{excluded_x_handles:e.excludedXHandles,included_x_handles:e.includedXHandles??e.xHandles,post_favorite_count:e.postFavoriteCount,post_view_count:e.postViewCount},...e.type===`news`&&{country:e.country,excluded_websites:e.excludedWebsites,safe_search:e.safeSearch},...e.type===`rss`&&{links:e.links}}))}:void 0,messages:h,tools:_,tool_choice:v},warnings:p}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:i,rawValue:a}=await z({url:`${this.config.baseURL??`https://api.x.ai/v1`}/chat/completions`,headers:x(this.config.headers(),e.headers),body:t,failedResponseHandler:ya,successfulResponseHandler:D(Ca),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=i.choices[0],s=[];if(o.message.content!=null&&o.message.content.length>0){let e=o.message.content,n=t.messages[t.messages.length-1];n?.role===`assistant`&&e===n.content&&(e=``),e.length>0&&s.push({type:`text`,text:e})}if(o.message.reasoning_content!=null&&o.message.reasoning_content.length>0&&s.push({type:`reasoning`,text:o.message.reasoning_content}),o.message.tool_calls!=null)for(let e of o.message.tool_calls)s.push({type:`tool-call`,toolCallId:e.id,toolName:e.function.name,input:e.function.arguments});if(i.citations!=null)for(let e of i.citations)s.push({type:`source`,sourceType:`url`,id:this.config.generateId(),url:e});return{content:s,finishReason:da(o.finish_reason),usage:{inputTokens:i.usage.prompt_tokens,outputTokens:i.usage.completion_tokens,totalTokens:i.usage.total_tokens,reasoningTokens:i.usage.completion_tokens_details?.reasoning_tokens??void 0},request:{body:t},response:{...ua(i),headers:r,body:a},warnings:n}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:a}=await z({url:`${this.config.baseURL??`https://api.x.ai/v1`}/chat/completions`,headers:x(this.config.headers(),e.headers),body:r,failedResponseHandler:ya,successfulResponseHandler:T(wa),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=`unknown`,s={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},c=!0,l={},u={},d=this;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let i=t.value;if(c&&=(n.enqueue({type:`response-metadata`,...ua(i)}),!1),i.citations!=null)for(let e of i.citations)n.enqueue({type:`source`,sourceType:`url`,id:d.config.generateId(),url:e});i.usage!=null&&(s.inputTokens=i.usage.prompt_tokens,s.outputTokens=i.usage.completion_tokens,s.totalTokens=i.usage.total_tokens,s.reasoningTokens=i.usage.completion_tokens_details?.reasoning_tokens??void 0);let a=i.choices[0];if(a?.finish_reason!=null&&(o=da(a.finish_reason)),a?.delta==null)return;let f=a.delta,p=a.index;if(f.content!=null&&f.content.length>0){let e=f.content,t=r.messages[r.messages.length-1];if(t?.role===`assistant`&&e===t.content)return;let a=`text-${i.id||p}`;l[a]??(l[a]={type:`text`},n.enqueue({type:`text-start`,id:a})),n.enqueue({type:`text-delta`,id:a,delta:e})}if(f.reasoning_content!=null&&f.reasoning_content.length>0){let e=`reasoning-${i.id||p}`;if(u[e]===f.reasoning_content)return;u[e]=f.reasoning_content,l[e]??(l[e]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:e})),n.enqueue({type:`reasoning-delta`,id:e,delta:f.reasoning_content})}if(f.tool_calls!=null)for(let e of f.tool_calls){let t=e.id;n.enqueue({type:`tool-input-start`,id:t,toolName:e.function.name}),n.enqueue({type:`tool-input-delta`,id:t,delta:e.function.arguments}),n.enqueue({type:`tool-input-end`,id:t}),n.enqueue({type:`tool-call`,toolCallId:t,toolName:e.function.name,input:e.function.arguments})}},flush(e){for(let[t,n]of Object.entries(l))e.enqueue({type:n.type===`text`?`text-end`:`reasoning-end`,id:t});e.enqueue({type:`finish`,finishReason:o,usage:s})}})),request:{body:r},response:{headers:i}}}},Sa=U.object({prompt_tokens:U.number(),completion_tokens:U.number(),total_tokens:U.number(),completion_tokens_details:U.object({reasoning_tokens:U.number().nullish()}).nullish()}),Ca=U.object({id:U.string().nullish(),created:U.number().nullish(),model:U.string().nullish(),choices:U.array(U.object({message:U.object({role:U.literal(`assistant`),content:U.string().nullish(),reasoning_content:U.string().nullish(),tool_calls:U.array(U.object({id:U.string(),type:U.literal(`function`),function:U.object({name:U.string(),arguments:U.string()})})).nullish()}),index:U.number(),finish_reason:U.string().nullish()})),object:U.literal(`chat.completion`),usage:Sa,citations:U.array(U.string().url()).nullish()}),wa=U.object({id:U.string().nullish(),created:U.number().nullish(),model:U.string().nullish(),choices:U.array(U.object({delta:U.object({role:U.enum([`assistant`]).optional(),content:U.string().nullish(),reasoning_content:U.string().nullish(),tool_calls:U.array(U.object({id:U.string(),type:U.literal(`function`),function:U.object({name:U.string(),arguments:U.string()})})).nullish()}),finish_reason:U.string().nullish(),index:U.number()})),usage:Sa.nullish(),citations:U.array(U.string().url()).nullish()}),Ta=`2.0.23`,Ea={errorSchema:va,errorToMessage:e=>e.error.message};function Da(e={}){let t=oe(e.baseURL??`https://api.x.ai/v1`),n=()=>ae({Authorization:`Bearer ${te({apiKey:e.apiKey,environmentVariableName:`XAI_API_KEY`,description:`xAI API key`})}`,...e.headers},`ai-sdk/xai/${Ta}`),r=r=>new xa(r,{provider:`xai.chat`,baseURL:t,headers:n,generateId:j,fetch:e.fetch}),i=r=>new sa(r,{provider:`xai.image`,url:({path:e})=>`${t}${e}`,headers:n,fetch:e.fetch,errorStructure:Ea}),a=e=>r(e);return a.languageModel=r,a.chat=r,a.textEmbeddingModel=e=>{throw new g({modelId:e,modelType:`textEmbeddingModel`})},a.imageModel=i,a.image=i,a}Da();function Oa(e){if(!e.body)throw Error(`Response body is required`);let t=e.headers.get(_);if(!t||t===`ui-message`)return e.body.pipeThrough(new TextDecoderStream).pipeThrough(new u).pipeThrough(new TransformStream({async transform(e,t){if(e.data!==`[DONE]`)try{let n=JSON.parse(e.data);t.enqueue(n)}catch(e){t.error(e);return}}}));let n=e=>Fe({model:e,prompt:[{role:`user`,content:[{type:`text`,text:`Hello, world!`}]}]}).toUIMessageStream();switch(t){case`openai-chat`:return n(Di({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`openai-response`:return n(Di({apiKey:`ignored`,fetch:(t,n)=>e}).responses(`fake-model`));case`anthropic`:return n(Jt({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`google`:return n(An({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`xai`:return n(Da({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));default:throw Error(`Unsupported response format: ${t}`)}}var ka=class{baseUrl;client;constructor(e){this.client=M(e.baseUrl),this.baseUrl=e.baseUrl}async chat(e,t){let n=await this.client._agent.chat.$post({json:e},{headers:t?.headers,init:{signal:t?.signal}});return n.ok||await this.handleError(n),Oa(n)}async capabilities(){let e=await this.client._agent.capabilities.$get();return e.ok||await this.handleError(e),e.json()}async ui(e,t){let n=await this.client._agent.ui.$get({query:e.selectedOptions?{selected_options:JSON.stringify(e.selectedOptions)}:{}},{init:{signal:t?.signal}});if(!n.ok||n.status!==200){if(n.status===404)return;await this.handleError(n)}return n.json()}async health(){let e=await this.client._agent.health.$get();e.ok||await this.handleError(e)}async handleError(e){let t;try{t=await e.text()}catch{}if(t){let n;try{n=JSON.parse(t)}catch{}throw n?Error(n.error):Error(`Failed (${e.status}): ${t}`)}throw Error(`Failed (${e.status}): ${e.statusText}`)}};function Aa(e){let[t,n]=K(void 0),[r,i]=K([]),[a,o]=K(void 0),[s,l]=K(e.buildResult),[u,d]=K(e.env),[f,p]=K(e.apiServerUrl),[m,h]=K(void 0);return G(()=>{d(e.env),l(e.buildResult),p(e.apiServerUrl)},[e.env,e.buildResult,e.apiServerUrl]),G(()=>{if(!s||`error`in s){n(void 0),i([]),o(void 0),h(void 0);return}let e=new AbortController,t=!1;return o(void 0),n(void 0),h(void 0),(async()=>{let t=await ja(),r=Ve(`node`,[`--no-deprecation`,s.entry],{stdio:`pipe`,env:{...process.env,...u,[c]:f,PORT:t.toString(),HOST:`127.0.0.1`}});e.signal.addEventListener(`abort`,()=>{try{r.kill()}catch{}});let a=!1;r.stdout.on(`data`,e=>{let t=Buffer.from(e).toString(`utf-8`).trim();!a&&t.startsWith(`Agent server listening on`)||(a||console.log(`stdout: ${t}`),t.length&&i(e=>[...e,{level:`log`,message:t}]))}),r.stderr.on(`data`,e=>{a||console.error(`stderr: ${Buffer.from(e).toString(`utf-8`).trim()}`);let t=Buffer.from(e).toString(`utf-8`).trim();t.length&&i(e=>[...e,{level:`error`,message:t}])}),r.on(`error`,t=>{e.abort(t)}),r.on(`exit`,(t,n)=>{e.abort(`Agent exited with code ${t??`unknown`} and signal ${n??`unknown`}. Be sure to call "blink.agent(...).serve()".`)});let o=new ka({baseUrl:`http://127.0.0.1:${t}`});for(;!e.signal.aborted;){try{await o.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(e.signal.aborted)throw e.signal.reason;a=!0;let l=await o.capabilities();h(l),n(o)})().catch(e=>{t||o(e instanceof Error?e:Error(String(e)))}),()=>{t=!0,e.abort()}},[s,u,f]),Ue(()=>({agent:t,logs:r,error:a,capabilities:m}),[t,r,a,m])}async function ja(){let e=Ce();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}var Ma=Object.getOwnPropertyNames,Na=(e,t)=>function(){return t||(0,e[Ma(e)[0]])((t={exports:{}}).exports,t),t.exports},X=H(import.meta.url);Y.object({email:Y.string().email(),password:Y.string().min(8)}),Y.object({email:Y.string().email(),code:Y.string()}),Y.object({email:Y.string().email(),password:Y.string().min(8)});var Pa=class{constructor(e,t){this.client=e,this.baseURL=t}async token(e,t={timeout:12e4}){return new Promise((n,r)=>{let i=crypto.randomUUID(),a=this.client.websocket(`/api/auth/token?id=${i}`),o=new URL(`/auth?id=${i}`,this.baseURL),s=setTimeout(()=>{r(Error(`Timeout waiting for the user to authenticate`))},t.timeout);a.onerror=e=>{clearTimeout(s),console.log(`error`,e),r(Error(`Failed to connect to server`))},a.onopen=()=>{e(o.toString(),i)},a.onmessage=e=>{typeof e.data==`string`&&(clearTimeout(s),n(e.data))}})}},Fa=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function Ia(e){}function La(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=Ia,onError:n=Ia,onRetry:r=Ia,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=Ra(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1,i=e.slice(t+r);f(n,i,e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t}
|
|
15
|
+
${t}:`]}}function Jn({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function Yn(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`content_filter`:return`content-filter`;case`function_call`:case`tool_calls`:return`tool-calls`;default:return`unknown`}}var Xn=U.object({echo:U.boolean().optional(),logitBias:U.record(U.string(),U.number()).optional(),suffix:U.string().optional(),user:U.string().optional(),logprobs:U.union([U.boolean(),U.number()]).optional()}),Zn=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(`.`)[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,tools:l,toolChoice:u,seed:d,providerOptions:f}){let p=[],m={...await L({provider:`openai`,providerOptions:f,schema:Xn}),...await L({provider:this.providerOptionsName,providerOptions:f,schema:Xn})};i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),l?.length&&p.push({type:`unsupported-setting`,setting:`tools`}),u!=null&&p.push({type:`unsupported-setting`,setting:`toolChoice`}),c!=null&&c.type!==`text`&&p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format is not supported.`});let{prompt:h,stopSequences:g}=qn({prompt:e}),_=[...g??[],...s??[]];return{args:{model:this.modelId,echo:m.echo,logit_bias:m.logitBias,logprobs:m?.logprobs===!0?0:m?.logprobs===!1?void 0:m?.logprobs,suffix:m.suffix,user:m.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:a,presence_penalty:o,seed:d,prompt:h,stop:_.length>0?_:void 0},warnings:p}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:i,rawValue:a}=await z({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:x(this.config.headers(),e.headers),body:t,failedResponseHandler:Mn,successfulResponseHandler:O($n),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=i.choices[0],s={openai:{}};return o.logprobs!=null&&(s.openai.logprobs=o.logprobs),{content:[{type:`text`,text:o.text}],usage:{inputTokens:i.usage?.prompt_tokens,outputTokens:i.usage?.completion_tokens,totalTokens:i.usage?.total_tokens},finishReason:Yn(o.finish_reason),request:{body:t},response:{...Jn(i),headers:r,body:a},providerMetadata:s,warnings:n}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:a}=await z({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:x(this.config.headers(),e.headers),body:r,failedResponseHandler:Mn,successfulResponseHandler:T(er),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=`unknown`,s={openai:{}},c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=!0;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){o=`error`,n.enqueue({type:`error`,error:t.error});return}let r=t.value;if(`error`in r){o=`error`,n.enqueue({type:`error`,error:r.error});return}l&&(l=!1,n.enqueue({type:`response-metadata`,...Jn(r)}),n.enqueue({type:`text-start`,id:`0`})),r.usage!=null&&(c.inputTokens=r.usage.prompt_tokens,c.outputTokens=r.usage.completion_tokens,c.totalTokens=r.usage.total_tokens);let i=r.choices[0];i?.finish_reason!=null&&(o=Yn(i.finish_reason)),i?.logprobs!=null&&(s.openai.logprobs=i.logprobs),i?.text!=null&&i.text.length>0&&n.enqueue({type:`text-delta`,id:`0`,delta:i.text})},flush(e){l||e.enqueue({type:`text-end`,id:`0`}),e.enqueue({type:`finish`,finishReason:o,providerMetadata:s,usage:c})}})),request:{body:r},response:{headers:i}}}},Qn=U.object({prompt_tokens:U.number(),completion_tokens:U.number(),total_tokens:U.number()}),$n=U.object({id:U.string().nullish(),created:U.number().nullish(),model:U.string().nullish(),choices:U.array(U.object({text:U.string(),finish_reason:U.string(),logprobs:U.object({tokens:U.array(U.string()),token_logprobs:U.array(U.number()),top_logprobs:U.array(U.record(U.string(),U.number())).nullish()}).nullish()})),usage:Qn.nullish()}),er=U.union([U.object({id:U.string().nullish(),created:U.number().nullish(),model:U.string().nullish(),choices:U.array(U.object({text:U.string(),finish_reason:U.string().nullish(),index:U.number(),logprobs:U.object({tokens:U.array(U.string()),token_logprobs:U.array(U.number()),top_logprobs:U.array(U.record(U.string(),U.number())).nullish()}).nullish()})),usage:Qn.nullish()}),jn]),tr=U.object({dimensions:U.number().optional(),user:U.string().optional()}),nr=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){if(e.length>this.maxEmbeddingsPerCall)throw new v({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let i=await L({provider:`openai`,providerOptions:r,schema:tr})??{},{responseHeaders:a,value:o,rawValue:s}=await z({url:this.config.url({path:`/embeddings`,modelId:this.modelId}),headers:x(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:`float`,dimensions:i.dimensions,user:i.user},failedResponseHandler:Mn,successfulResponseHandler:O(rr),abortSignal:n,fetch:this.config.fetch});return{embeddings:o.data.map(e=>e.embedding),usage:o.usage?{tokens:o.usage.prompt_tokens}:void 0,response:{headers:a,body:s}}}},rr=U.object({data:U.array(U.object({embedding:U.array(U.number())})),usage:U.object({prompt_tokens:U.number()}).nullish()}),ir={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},ar=new Set([`gpt-image-1`]),or=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get maxImagesPerCall(){return ir[this.modelId]??1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:a,headers:o,abortSignal:s}){var c;let l=[];r!=null&&l.push({type:`unsupported-setting`,setting:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&l.push({type:`unsupported-setting`,setting:`seed`});let u=((c=this.config._internal)?.currentDate)?.call(c)??new Date,{value:d,responseHeaders:f}=await z({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:x(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...a.openai??{},...ar.has(this.modelId)?{}:{response_format:`b64_json`}},failedResponseHandler:Mn,successfulResponseHandler:O(sr),abortSignal:s,fetch:this.config.fetch});return{images:d.data.map(e=>e.b64_json),warnings:l,response:{timestamp:u,modelId:this.modelId,headers:f},providerMetadata:{openai:{images:d.data.map(e=>e.revised_prompt?{revisedPrompt:e.revised_prompt}:null)}}}}},sr=U.object({data:U.array(U.object({b64_json:U.string(),revised_prompt:U.string().optional()}))}),cr=U.object({code:U.string().nullish(),containerId:U.string()}),lr=U.object({outputs:U.array(U.discriminatedUnion(`type`,[U.object({type:U.literal(`logs`),logs:U.string()}),U.object({type:U.literal(`image`),url:U.string()})])).nullish()}),ur=U.object({container:U.union([U.string(),U.object({fileIds:U.array(U.string()).optional()})]).optional()}),dr=A({id:`openai.code_interpreter`,name:`code_interpreter`,inputSchema:cr,outputSchema:lr}),fr=(e={})=>dr(e),pr=U.object({key:U.string(),type:U.enum([`eq`,`ne`,`gt`,`gte`,`lt`,`lte`]),value:U.union([U.string(),U.number(),U.boolean()])}),mr=U.object({type:U.enum([`and`,`or`]),filters:U.array(U.union([pr,U.lazy(()=>mr)]))}),hr=U.object({vectorStoreIds:U.array(U.string()),maxNumResults:U.number().optional(),ranking:U.object({ranker:U.string().optional(),scoreThreshold:U.number().optional()}).optional(),filters:U.union([pr,mr]).optional()}),gr=U.object({queries:U.array(U.string()),results:U.array(U.object({attributes:U.record(U.string(),U.unknown()),fileId:U.string(),filename:U.string(),score:U.number(),text:U.string()})).nullable()}),_r=A({id:`openai.file_search`,name:`file_search`,inputSchema:U.object({}),outputSchema:gr}),vr=U.object({background:U.enum([`auto`,`opaque`,`transparent`]).optional(),inputFidelity:U.enum([`low`,`high`]).optional(),inputImageMask:U.object({fileId:U.string().optional(),imageUrl:U.string().optional()}).optional(),model:U.string().optional(),moderation:U.enum([`auto`]).optional(),outputCompression:U.number().int().min(0).max(100).optional(),outputFormat:U.enum([`png`,`jpeg`,`webp`]).optional(),quality:U.enum([`auto`,`low`,`medium`,`high`]).optional(),size:U.enum([`1024x1024`,`1024x1536`,`1536x1024`,`auto`]).optional()}).strict(),yr=U.object({result:U.string()}),br=A({id:`openai.image_generation`,name:`image_generation`,inputSchema:U.object({}),outputSchema:yr}),xr=(e={})=>br(e),Sr=U.object({action:U.object({type:U.literal(`exec`),command:U.array(U.string()),timeoutMs:U.number().optional(),user:U.string().optional(),workingDirectory:U.string().optional(),env:U.record(U.string(),U.string()).optional()})}),Cr=U.object({output:U.string()}),wr=A({id:`openai.local_shell`,name:`local_shell`,inputSchema:Sr,outputSchema:Cr}),Tr=U.object({filters:U.object({allowedDomains:U.array(U.string()).optional()}).optional(),searchContextSize:U.enum([`low`,`medium`,`high`]).optional(),userLocation:U.object({type:U.literal(`approximate`),country:U.string().optional(),city:U.string().optional(),region:U.string().optional(),timezone:U.string().optional()}).optional()}),Er=k({id:`openai.web_search`,name:`web_search`,inputSchema:U.object({action:U.discriminatedUnion(`type`,[U.object({type:U.literal(`search`),query:U.string().nullish()}),U.object({type:U.literal(`open_page`),url:U.string()}),U.object({type:U.literal(`find`),url:U.string(),pattern:U.string()})]).nullish()})}),Dr=(e={})=>Er(e),Or=U.object({searchContextSize:U.enum([`low`,`medium`,`high`]).optional(),userLocation:U.object({type:U.literal(`approximate`),country:U.string().optional(),city:U.string().optional(),region:U.string().optional(),timezone:U.string().optional()}).optional()}),kr=k({id:`openai.web_search_preview`,name:`web_search_preview`,inputSchema:U.object({action:U.discriminatedUnion(`type`,[U.object({type:U.literal(`search`),query:U.string().nullish()}),U.object({type:U.literal(`open_page`),url:U.string()}),U.object({type:U.literal(`find`),url:U.string(),pattern:U.string()})]).nullish()})}),Ar={codeInterpreter:fr,fileSearch:_r,imageGeneration:xr,localShell:wr,webSearchPreview:kr,webSearch:Dr};function jr(e,t){return t?t.some(t=>e.startsWith(t)):!1}async function Mr({prompt:e,systemMessageMode:t,fileIdPrefixes:n,store:r,hasLocalShellTool:i=!1}){let a=[],o=[];for(let{role:s,content:c}of e)switch(s){case`system`:switch(t){case`system`:a.push({role:`system`,content:c});break;case`developer`:a.push({role:`developer`,content:c});break;case`remove`:o.push({type:`other`,message:`system messages are removed for this model`});break;default:{let e=t;throw Error(`Unsupported system message mode: ${e}`)}}break;case`user`:a.push({role:`user`,content:c.map((e,t)=>{switch(e.type){case`text`:return{type:`input_text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`input_image`,...e.data instanceof URL?{image_url:e.data.toString()}:typeof e.data==`string`&&jr(e.data,n)?{file_id:e.data}:{image_url:`data:${t};base64,${C(e.data)}`},detail:e.providerOptions?.openai?.imageDetail}}else if(e.mediaType===`application/pdf`)return e.data instanceof URL?{type:`input_file`,file_url:e.data.toString()}:{type:`input_file`,...typeof e.data==`string`&&jr(e.data,n)?{file_id:e.data}:{filename:e.filename??`part-${t}.pdf`,file_data:`data:application/pdf;base64,${C(e.data)}`}};else throw new b({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e={},t={};for(let n of c)switch(n.type){case`text`:a.push({role:`assistant`,content:[{type:`output_text`,text:n.text}],id:n.providerOptions?.openai?.itemId??void 0});break;case`tool-call`:if(t[n.toolCallId]=n,n.providerExecuted)break;if(i&&n.toolName===`local_shell`){let e=Sr.parse(n.input);a.push({type:`local_shell_call`,call_id:n.toolCallId,id:n.providerOptions?.openai?.itemId??void 0,action:{type:`exec`,command:e.action.command,timeout_ms:e.action.timeoutMs,user:e.action.user,working_directory:e.action.workingDirectory,env:e.action.env}});break}a.push({type:`function_call`,call_id:n.toolCallId,name:n.toolName,arguments:JSON.stringify(n.input),id:n.providerOptions?.openai?.itemId??void 0});break;case`tool-result`:r?a.push({type:`item_reference`,id:n.toolCallId}):o.push({type:`other`,message:`Results for OpenAI tool ${n.toolName} are not sent to the API when store is false`});break;case`reasoning`:{let t=await L({provider:`openai`,providerOptions:n.providerOptions,schema:Nr}),i=t?.itemId;if(i!=null){let s=e[i];if(r)s===void 0&&(a.push({type:`item_reference`,id:i}),e[i]={type:`reasoning`,id:i,summary:[]});else{let r=[];n.text.length>0?r.push({type:`summary_text`,text:n.text}):s!==void 0&&o.push({type:`other`,message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(n)}.`}),s===void 0?(e[i]={type:`reasoning`,id:i,encrypted_content:t?.reasoningEncryptedContent,summary:r},a.push(e[i])):s.summary.push(...r)}}else o.push({type:`other`,message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(n)}.`});break}}break}case`tool`:for(let e of c){let t=e.output;if(i&&e.toolName===`local_shell`&&t.type===`json`){a.push({type:`local_shell_call_output`,call_id:e.toolCallId,output:Cr.parse(t.value).output});break}let n;switch(t.type){case`text`:case`error-text`:n=t.value;break;case`content`:case`json`:case`error-json`:n=JSON.stringify(t.value);break}a.push({type:`function_call_output`,call_id:e.toolCallId,output:n})}break;default:{let e=s;throw Error(`Unsupported role: ${e}`)}}return{input:a,warnings:o}}var Nr=U.object({itemId:U.string().nullish(),reasoningEncryptedContent:U.string().nullish()});function Pr({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?`tool-calls`:`stop`;case`max_output_tokens`:return`length`;case`content_filter`:return`content-filter`;default:return t?`tool-calls`:`unknown`}}function Fr({tools:e,toolChoice:t,strictJsonSchema:n}){e=e?.length?e:void 0;let r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};let i=[];for(let t of e)switch(t.type){case`function`:i.push({type:`function`,name:t.name,description:t.description,parameters:t.inputSchema,strict:n});break;case`provider-defined`:switch(t.id){case`openai.file_search`:{let e=hr.parse(t.args);i.push({type:`file_search`,vector_store_ids:e.vectorStoreIds,max_num_results:e.maxNumResults,ranking_options:e.ranking?{ranker:e.ranking.ranker,score_threshold:e.ranking.scoreThreshold}:void 0,filters:e.filters});break}case`openai.local_shell`:i.push({type:`local_shell`});break;case`openai.web_search_preview`:{let e=Or.parse(t.args);i.push({type:`web_search_preview`,search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.web_search`:{let e=Tr.parse(t.args);i.push({type:`web_search`,filters:e.filters==null?void 0:{allowed_domains:e.filters.allowedDomains},search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.code_interpreter`:{let e=ur.parse(t.args);i.push({type:`code_interpreter`,container:e.container==null?{type:`auto`,file_ids:void 0}:typeof e.container==`string`?e.container:{type:`auto`,file_ids:e.container.fileIds}});break}case`openai.image_generation`:{let e=vr.parse(t.args);i.push({type:`image_generation`,background:e.background,input_fidelity:e.inputFidelity,input_image_mask:e.inputImageMask?{file_id:e.inputImageMask.fileId,image_url:e.inputImageMask.imageUrl}:void 0,model:e.model,size:e.size,quality:e.quality,moderation:e.moderation,output_format:e.outputFormat,output_compression:e.outputCompression});break}}break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:i,toolChoice:void 0,toolWarnings:r};let a=t.type;switch(a){case`auto`:case`none`:case`required`:return{tools:i,toolChoice:a,toolWarnings:r};case`tool`:return{tools:i,toolChoice:t.toolName===`code_interpreter`||t.toolName===`file_search`||t.toolName===`image_generation`||t.toolName===`web_search_preview`||t.toolName===`web_search`?{type:t.toolName}:{type:`function`,name:t.toolName},toolWarnings:r};default:throw new b({functionality:`tool choice type: ${a}`})}}var Ir=U.object({type:U.literal(`web_search_call`),id:U.string(),status:U.string(),action:U.discriminatedUnion(`type`,[U.object({type:U.literal(`search`),query:U.string().nullish()}),U.object({type:U.literal(`open_page`),url:U.string()}),U.object({type:U.literal(`find`),url:U.string(),pattern:U.string()})]).nullish()}),Lr=U.object({type:U.literal(`file_search_call`),id:U.string(),queries:U.array(U.string()),results:U.array(U.object({attributes:U.record(U.string(),U.unknown()),file_id:U.string(),filename:U.string(),score:U.number(),text:U.string()})).nullish()}),Rr=U.object({type:U.literal(`code_interpreter_call`),id:U.string(),code:U.string().nullable(),container_id:U.string(),outputs:U.array(U.discriminatedUnion(`type`,[U.object({type:U.literal(`logs`),logs:U.string()}),U.object({type:U.literal(`image`),url:U.string()})])).nullable()}),zr=U.object({type:U.literal(`local_shell_call`),id:U.string(),call_id:U.string(),action:U.object({type:U.literal(`exec`),command:U.array(U.string()),timeout_ms:U.number().optional(),user:U.string().optional(),working_directory:U.string().optional(),env:U.record(U.string(),U.string()).optional()})}),Br=U.object({type:U.literal(`image_generation_call`),id:U.string(),result:U.string()}),Vr=20,Hr=U.array(U.object({token:U.string(),logprob:U.number(),top_logprobs:U.array(U.object({token:U.string(),logprob:U.number()}))})),Ur=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:i,presencePenalty:a,frequencyPenalty:o,seed:s,prompt:c,providerOptions:l,tools:u,toolChoice:d,responseFormat:f}){let p=[],m=vi(this.modelId);i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),s!=null&&p.push({type:`unsupported-setting`,setting:`seed`}),a!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),n!=null&&p.push({type:`unsupported-setting`,setting:`stopSequences`});let h=await L({provider:`openai`,providerOptions:l,schema:yi}),{input:g,warnings:_}=await Mr({prompt:c,systemMessageMode:m.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:h?.store??!0,hasLocalShellTool:x(`openai.local_shell`)});p.push(..._);let v=h?.strictJsonSchema??!1,y=h?.include;function b(e){y=y==null?[e]:[...y,e]}function x(e){return u?.find(t=>t.type===`provider-defined`&&t.id===e)!=null}let S=typeof h?.logprobs==`number`?h?.logprobs:h?.logprobs===!0?Vr:void 0;S&&b(`message.output_text.logprobs`);let C=u?.find(e=>e.type===`provider-defined`&&(e.id===`openai.web_search`||e.id===`openai.web_search_preview`))?.name;C&&b(`web_search_call.action.sources`),x(`openai.code_interpreter`)&&b(`code_interpreter_call.outputs`);let w={model:this.modelId,input:g,temperature:t,top_p:r,max_output_tokens:e,...(f?.type===`json`||h?.textVerbosity)&&{text:{...f?.type===`json`&&{format:f.schema==null?{type:`json_object`}:{type:`json_schema`,strict:v,name:f.name??`response`,description:f.description,schema:f.schema}},...h?.textVerbosity&&{verbosity:h.textVerbosity}}},max_tool_calls:h?.maxToolCalls,metadata:h?.metadata,parallel_tool_calls:h?.parallelToolCalls,previous_response_id:h?.previousResponseId,store:h?.store,user:h?.user,instructions:h?.instructions,service_tier:h?.serviceTier,include:y,prompt_cache_key:h?.promptCacheKey,safety_identifier:h?.safetyIdentifier,top_logprobs:S,...m.isReasoningModel&&(h?.reasoningEffort!=null||h?.reasoningSummary!=null)&&{reasoning:{...h?.reasoningEffort!=null&&{effort:h.reasoningEffort},...h?.reasoningSummary!=null&&{summary:h.reasoningSummary}}},...m.requiredAutoTruncation&&{truncation:`auto`}};m.isReasoningModel?(w.temperature!=null&&(w.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for reasoning models`})),w.top_p!=null&&(w.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported for reasoning models`}))):(h?.reasoningEffort!=null&&p.push({type:`unsupported-setting`,setting:`reasoningEffort`,details:`reasoningEffort is not supported for non-reasoning models`}),h?.reasoningSummary!=null&&p.push({type:`unsupported-setting`,setting:`reasoningSummary`,details:`reasoningSummary is not supported for non-reasoning models`})),h?.serviceTier===`flex`&&!m.supportsFlexProcessing&&(p.push({type:`unsupported-setting`,setting:`serviceTier`,details:`flex processing is only available for o3, o4-mini, and gpt-5 models`}),delete w.service_tier),h?.serviceTier===`priority`&&!m.supportsPriorityProcessing&&(p.push({type:`unsupported-setting`,setting:`serviceTier`,details:`priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported`}),delete w.service_tier);let{tools:T,toolChoice:E,toolWarnings:D}=Fr({tools:u,toolChoice:d,strictJsonSchema:v});return{webSearchToolName:C,args:{...w,tools:T,tool_choice:E},warnings:[...p,...D]}}async doGenerate(e){var t,n;let{args:r,warnings:i,webSearchToolName:a}=await this.getArgs(e),o=this.config.url({path:`/responses`,modelId:this.modelId}),{responseHeaders:c,value:l,rawValue:u}=await z({url:o,headers:x(this.config.headers(),e.headers),body:r,failedResponseHandler:Mn,successfulResponseHandler:O(U.object({id:U.string(),created_at:U.number(),error:U.object({code:U.string(),message:U.string()}).nullish(),model:U.string(),output:U.array(U.discriminatedUnion(`type`,[U.object({type:U.literal(`message`),role:U.literal(`assistant`),id:U.string(),content:U.array(U.object({type:U.literal(`output_text`),text:U.string(),logprobs:Hr.nullish(),annotations:U.array(U.discriminatedUnion(`type`,[U.object({type:U.literal(`url_citation`),start_index:U.number(),end_index:U.number(),url:U.string(),title:U.string()}),U.object({type:U.literal(`file_citation`),file_id:U.string(),filename:U.string().nullish(),index:U.number().nullish(),start_index:U.number().nullish(),end_index:U.number().nullish(),quote:U.string().nullish()}),U.object({type:U.literal(`container_file_citation`)})]))}))}),Ir,Lr,Rr,Br,zr,U.object({type:U.literal(`function_call`),call_id:U.string(),name:U.string(),arguments:U.string(),id:U.string()}),U.object({type:U.literal(`computer_call`),id:U.string(),status:U.string().optional()}),U.object({type:U.literal(`reasoning`),id:U.string(),encrypted_content:U.string().nullish(),summary:U.array(U.object({type:U.literal(`summary_text`),text:U.string()}))})])),service_tier:U.string().nullish(),incomplete_details:U.object({reason:U.string()}).nullish(),usage:Wr})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(l.error)throw new s({message:l.error.message,url:o,requestBodyValues:r,statusCode:400,responseHeaders:c,responseBody:u,isRetryable:!1});let d=[],f=[],p=!1;for(let r of l.output)switch(r.type){case`reasoning`:r.summary.length===0&&r.summary.push({type:`summary_text`,text:``});for(let e of r.summary)d.push({type:`reasoning`,text:e.text,providerMetadata:{openai:{itemId:r.id,reasoningEncryptedContent:r.encrypted_content??null}}});break;case`image_generation_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`image_generation`,input:`{}`,providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`image_generation`,result:{result:r.result},providerExecuted:!0});break;case`local_shell_call`:d.push({type:`tool-call`,toolCallId:r.call_id,toolName:`local_shell`,input:JSON.stringify({action:r.action}),providerMetadata:{openai:{itemId:r.id}}});break;case`message`:for(let i of r.content){e.providerOptions?.openai?.logprobs&&i.logprobs&&f.push(i.logprobs),d.push({type:`text`,text:i.text,providerMetadata:{openai:{itemId:r.id}}});for(let e of i.annotations)e.type===`url_citation`?d.push({type:`source`,sourceType:`url`,id:(t=this.config).generateId?.call(t)??M(),url:e.url,title:e.title}):e.type===`file_citation`&&d.push({type:`source`,sourceType:`document`,id:(n=this.config).generateId?.call(n)??M(),mediaType:`text/plain`,title:e.quote??e.filename??`Document`,filename:e.filename??e.file_id})}break;case`function_call`:p=!0,d.push({type:`tool-call`,toolCallId:r.call_id,toolName:r.name,input:r.arguments,providerMetadata:{openai:{itemId:r.id}}});break;case`web_search_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:a??`web_search`,input:JSON.stringify({action:r.action}),providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:a??`web_search`,result:{status:r.status},providerExecuted:!0});break;case`computer_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`computer_use`,input:``,providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:r.status||`completed`},providerExecuted:!0});break;case`file_search_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`file_search`,input:`{}`,providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`file_search`,result:{queries:r.queries,results:r.results?.map(e=>({attributes:e.attributes,fileId:e.file_id,filename:e.filename,score:e.score,text:e.text}))??null},providerExecuted:!0});break;case`code_interpreter_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`code_interpreter`,input:JSON.stringify({code:r.code,containerId:r.container_id}),providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`code_interpreter`,result:{outputs:r.outputs},providerExecuted:!0});break}let m={openai:{responseId:l.id}};return f.length>0&&(m.openai.logprobs=f),typeof l.service_tier==`string`&&(m.openai.serviceTier=l.service_tier),{content:d,finishReason:Pr({finishReason:l.incomplete_details?.reason,hasFunctionCall:p}),usage:{inputTokens:l.usage.input_tokens,outputTokens:l.usage.output_tokens,totalTokens:l.usage.input_tokens+l.usage.output_tokens,reasoningTokens:l.usage.output_tokens_details?.reasoning_tokens??void 0,cachedInputTokens:l.usage.input_tokens_details?.cached_tokens??void 0},request:{body:r},response:{id:l.id,timestamp:new Date(l.created_at*1e3),modelId:l.model,headers:c,body:u},providerMetadata:m,warnings:i}}async doStream(e){let{args:t,warnings:n,webSearchToolName:r}=await this.getArgs(e),{responseHeaders:i,value:a}=await z({url:this.config.url({path:`/responses`,modelId:this.modelId}),headers:x(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Mn,successfulResponseHandler:T(ri),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=this,s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=[],u=null,d={},f=!1,p={},m;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){var i,a,h;if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){s=`error`,n.enqueue({type:`error`,error:t.error});return}let g=t.value;if(fi(g))g.item.type===`function_call`?(d[g.output_index]={toolName:g.item.name,toolCallId:g.item.call_id},n.enqueue({type:`tool-input-start`,id:g.item.call_id,toolName:g.item.name})):g.item.type===`web_search_call`?(d[g.output_index]={toolName:r??`web_search`,toolCallId:g.item.id},n.enqueue({type:`tool-input-start`,id:g.item.id,toolName:r??`web_search`})):g.item.type===`computer_call`?(d[g.output_index]={toolName:`computer_use`,toolCallId:g.item.id},n.enqueue({type:`tool-input-start`,id:g.item.id,toolName:`computer_use`})):g.item.type===`code_interpreter_call`?(d[g.output_index]={toolName:`code_interpreter`,toolCallId:g.item.id,codeInterpreter:{containerId:g.item.container_id}},n.enqueue({type:`tool-input-start`,id:g.item.id,toolName:`code_interpreter`}),n.enqueue({type:`tool-input-delta`,id:g.item.id,delta:`{"containerId":"${g.item.container_id}","code":"`})):g.item.type===`file_search_call`?n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`file_search`,input:`{}`,providerExecuted:!0}):g.item.type===`image_generation_call`?n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`image_generation`,input:`{}`,providerExecuted:!0}):g.item.type===`message`?n.enqueue({type:`text-start`,id:g.item.id,providerMetadata:{openai:{itemId:g.item.id}}}):pi(g)&&(p[g.item.id]={encryptedContent:g.item.encrypted_content,summaryParts:[0]},n.enqueue({type:`reasoning-start`,id:`${g.item.id}:0`,providerMetadata:{openai:{itemId:g.item.id,reasoningEncryptedContent:g.item.encrypted_content??null}}}));else if(ai(g)){if(g.item.type===`function_call`)d[g.output_index]=void 0,f=!0,n.enqueue({type:`tool-input-end`,id:g.item.call_id}),n.enqueue({type:`tool-call`,toolCallId:g.item.call_id,toolName:g.item.name,input:g.item.arguments,providerMetadata:{openai:{itemId:g.item.id}}});else if(g.item.type===`web_search_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:g.item.id}),n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`web_search`,input:JSON.stringify({action:g.item.action}),providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`web_search`,result:{status:g.item.status},providerExecuted:!0});else if(g.item.type===`computer_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:g.item.id}),n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`computer_use`,input:``,providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:g.item.status||`completed`},providerExecuted:!0});else if(g.item.type===`file_search_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`file_search`,result:{queries:g.item.queries,results:g.item.results?.map(e=>({attributes:e.attributes,fileId:e.file_id,filename:e.filename,score:e.score,text:e.text}))??null},providerExecuted:!0});else if(g.item.type===`code_interpreter_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`code_interpreter`,result:{outputs:g.item.outputs},providerExecuted:!0});else if(g.item.type===`image_generation_call`)n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`image_generation`,result:{result:g.item.result},providerExecuted:!0});else if(g.item.type===`local_shell_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-call`,toolCallId:g.item.call_id,toolName:`local_shell`,input:JSON.stringify({action:{type:`exec`,command:g.item.action.command,timeoutMs:g.item.action.timeout_ms,user:g.item.action.user,workingDirectory:g.item.action.working_directory,env:g.item.action.env}}),providerMetadata:{openai:{itemId:g.item.id}}});else if(g.item.type===`message`)n.enqueue({type:`text-end`,id:g.item.id});else if(oi(g)){let e=p[g.item.id];for(let t of e.summaryParts)n.enqueue({type:`reasoning-end`,id:`${g.item.id}:${t}`,providerMetadata:{openai:{itemId:g.item.id,reasoningEncryptedContent:g.item.encrypted_content??null}}});delete p[g.item.id]}}else if(li(g)){let e=d[g.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:g.delta})}else if(ui(g)){let e=d[g.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:JSON.stringify(g.delta).slice(1,-1)})}else if(di(g)){let e=d[g.output_index];e!=null&&(n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:`"}`}),n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:`code_interpreter`,input:JSON.stringify({code:g.code,containerId:e.codeInterpreter.containerId}),providerExecuted:!0}))}else ci(g)?(u=g.response.id,n.enqueue({type:`response-metadata`,id:g.response.id,timestamp:new Date(g.response.created_at*1e3),modelId:g.response.model})):ii(g)?(n.enqueue({type:`text-delta`,id:g.item_id,delta:g.delta}),e.providerOptions?.openai?.logprobs&&g.logprobs&&l.push(g.logprobs)):hi(g)?g.summary_index>0&&((i=p[g.item_id])==null||i.summaryParts.push(g.summary_index),n.enqueue({type:`reasoning-start`,id:`${g.item_id}:${g.summary_index}`,providerMetadata:{openai:{itemId:g.item_id,reasoningEncryptedContent:p[g.item_id]?.encryptedContent??null}}})):gi(g)?n.enqueue({type:`reasoning-delta`,id:`${g.item_id}:${g.summary_index}`,delta:g.delta,providerMetadata:{openai:{itemId:g.item_id}}}):si(g)?(s=Pr({finishReason:g.response.incomplete_details?.reason,hasFunctionCall:f}),c.inputTokens=g.response.usage.input_tokens,c.outputTokens=g.response.usage.output_tokens,c.totalTokens=g.response.usage.input_tokens+g.response.usage.output_tokens,c.reasoningTokens=g.response.usage.output_tokens_details?.reasoning_tokens??void 0,c.cachedInputTokens=g.response.usage.input_tokens_details?.cached_tokens??void 0,typeof g.response.service_tier==`string`&&(m=g.response.service_tier)):mi(g)?g.annotation.type===`url_citation`?n.enqueue({type:`source`,sourceType:`url`,id:(a=o.config).generateId?.call(a)??M(),url:g.annotation.url,title:g.annotation.title}):g.annotation.type===`file_citation`&&n.enqueue({type:`source`,sourceType:`document`,id:(h=o.config).generateId?.call(h)??M(),mediaType:`text/plain`,title:g.annotation.quote??g.annotation.filename??`Document`,filename:g.annotation.filename??g.annotation.file_id}):_i(g)&&n.enqueue({type:`error`,error:g})},flush(e){let t={openai:{responseId:u}};l.length>0&&(t.openai.logprobs=l),m!==void 0&&(t.openai.serviceTier=m),e.enqueue({type:`finish`,finishReason:s,usage:c,providerMetadata:t})}})),request:{body:t},response:{headers:i}}}},Wr=U.object({input_tokens:U.number(),input_tokens_details:U.object({cached_tokens:U.number().nullish()}).nullish(),output_tokens:U.number(),output_tokens_details:U.object({reasoning_tokens:U.number().nullish()}).nullish()}),Gr=U.object({type:U.literal(`response.output_text.delta`),item_id:U.string(),delta:U.string(),logprobs:Hr.nullish()}),Kr=U.object({type:U.literal(`error`),code:U.string(),message:U.string(),param:U.string().nullish(),sequence_number:U.number()}),qr=U.object({type:U.enum([`response.completed`,`response.incomplete`]),response:U.object({incomplete_details:U.object({reason:U.string()}).nullish(),usage:Wr,service_tier:U.string().nullish()})}),Jr=U.object({type:U.literal(`response.created`),response:U.object({id:U.string(),created_at:U.number(),model:U.string(),service_tier:U.string().nullish()})}),Yr=U.object({type:U.literal(`response.output_item.added`),output_index:U.number(),item:U.discriminatedUnion(`type`,[U.object({type:U.literal(`message`),id:U.string()}),U.object({type:U.literal(`reasoning`),id:U.string(),encrypted_content:U.string().nullish()}),U.object({type:U.literal(`function_call`),id:U.string(),call_id:U.string(),name:U.string(),arguments:U.string()}),U.object({type:U.literal(`web_search_call`),id:U.string(),status:U.string(),action:U.object({type:U.literal(`search`),query:U.string().optional()}).nullish()}),U.object({type:U.literal(`computer_call`),id:U.string(),status:U.string()}),U.object({type:U.literal(`file_search_call`),id:U.string()}),U.object({type:U.literal(`image_generation_call`),id:U.string()}),U.object({type:U.literal(`code_interpreter_call`),id:U.string(),container_id:U.string(),code:U.string().nullable(),outputs:U.array(U.discriminatedUnion(`type`,[U.object({type:U.literal(`logs`),logs:U.string()}),U.object({type:U.literal(`image`),url:U.string()})])).nullable(),status:U.string()})])}),Xr=U.object({type:U.literal(`response.output_item.done`),output_index:U.number(),item:U.discriminatedUnion(`type`,[U.object({type:U.literal(`message`),id:U.string()}),U.object({type:U.literal(`reasoning`),id:U.string(),encrypted_content:U.string().nullish()}),U.object({type:U.literal(`function_call`),id:U.string(),call_id:U.string(),name:U.string(),arguments:U.string(),status:U.literal(`completed`)}),Rr,Br,Ir,Lr,zr,U.object({type:U.literal(`computer_call`),id:U.string(),status:U.literal(`completed`)})])}),Zr=U.object({type:U.literal(`response.function_call_arguments.delta`),item_id:U.string(),output_index:U.number(),delta:U.string()}),Qr=U.object({type:U.literal(`response.code_interpreter_call_code.delta`),item_id:U.string(),output_index:U.number(),delta:U.string()}),$r=U.object({type:U.literal(`response.code_interpreter_call_code.done`),item_id:U.string(),output_index:U.number(),code:U.string()}),ei=U.object({type:U.literal(`response.output_text.annotation.added`),annotation:U.discriminatedUnion(`type`,[U.object({type:U.literal(`url_citation`),url:U.string(),title:U.string()}),U.object({type:U.literal(`file_citation`),file_id:U.string(),filename:U.string().nullish(),index:U.number().nullish(),start_index:U.number().nullish(),end_index:U.number().nullish(),quote:U.string().nullish()})])}),ti=U.object({type:U.literal(`response.reasoning_summary_part.added`),item_id:U.string(),summary_index:U.number()}),ni=U.object({type:U.literal(`response.reasoning_summary_text.delta`),item_id:U.string(),summary_index:U.number(),delta:U.string()}),ri=U.union([Gr,qr,Jr,Yr,Xr,Zr,Qr,$r,ei,ti,ni,Kr,U.object({type:U.string()}).loose()]);function ii(e){return e.type===`response.output_text.delta`}function ai(e){return e.type===`response.output_item.done`}function oi(e){return ai(e)&&e.item.type===`reasoning`}function si(e){return e.type===`response.completed`||e.type===`response.incomplete`}function ci(e){return e.type===`response.created`}function li(e){return e.type===`response.function_call_arguments.delta`}function ui(e){return e.type===`response.code_interpreter_call_code.delta`}function di(e){return e.type===`response.code_interpreter_call_code.done`}function fi(e){return e.type===`response.output_item.added`}function pi(e){return fi(e)&&e.item.type===`reasoning`}function mi(e){return e.type===`response.output_text.annotation.added`}function hi(e){return e.type===`response.reasoning_summary_part.added`}function gi(e){return e.type===`response.reasoning_summary_text.delta`}function _i(e){return e.type===`error`}function vi(e){let t=e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`),n=e.startsWith(`gpt-4`)||e.startsWith(`gpt-5-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-nano`)&&!e.startsWith(`gpt-5-chat`)||e.startsWith(`o3`)||e.startsWith(`o4-mini`),r={requiredAutoTruncation:!1,systemMessageMode:`system`,supportsFlexProcessing:t,supportsPriorityProcessing:n};return e.startsWith(`gpt-5-chat`)?{...r,isReasoningModel:!1}:e.startsWith(`o`)||e.startsWith(`gpt-5`)||e.startsWith(`codex-`)||e.startsWith(`computer-use`)?e.startsWith(`o1-mini`)||e.startsWith(`o1-preview`)?{...r,isReasoningModel:!0,systemMessageMode:`remove`}:{...r,isReasoningModel:!0,systemMessageMode:`developer`}:{...r,isReasoningModel:!1}}var yi=U.object({include:U.array(U.enum([`reasoning.encrypted_content`,`file_search_call.results`,`message.output_text.logprobs`])).nullish(),instructions:U.string().nullish(),logprobs:U.union([U.boolean(),U.number().min(1).max(Vr)]).optional(),maxToolCalls:U.number().nullish(),metadata:U.any().nullish(),parallelToolCalls:U.boolean().nullish(),previousResponseId:U.string().nullish(),promptCacheKey:U.string().nullish(),reasoningEffort:U.string().nullish(),reasoningSummary:U.string().nullish(),safetyIdentifier:U.string().nullish(),serviceTier:U.enum([`auto`,`flex`,`priority`]).nullish(),store:U.boolean().nullish(),strictJsonSchema:U.boolean().nullish(),textVerbosity:U.enum([`low`,`medium`,`high`]).nullish(),user:U.string().nullish()}),bi=U.object({instructions:U.string().nullish(),speed:U.number().min(.25).max(4).default(1).nullish()}),xi=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get provider(){return this.config.provider}async getArgs({text:e,voice:t=`alloy`,outputFormat:n=`mp3`,speed:r,instructions:i,language:a,providerOptions:o}){let s=[],c=await L({provider:`openai`,providerOptions:o,schema:bi}),l={model:this.modelId,input:e,voice:t,response_format:`mp3`,speed:r,instructions:i};if(n&&([`mp3`,`opus`,`aac`,`flac`,`wav`,`pcm`].includes(n)?l.response_format=n:s.push({type:`unsupported-setting`,setting:`outputFormat`,details:`Unsupported output format: ${n}. Using mp3 instead.`})),c){let e={};for(let t in e){let n=e[t];n!==void 0&&(l[t]=n)}}return a&&s.push({type:`unsupported-setting`,setting:`language`,details:`OpenAI speech models do not support language selection. Language parameter "${a}" was ignored.`}),{requestBody:l,warnings:s}}async doGenerate(e){var t;let n=((t=this.config._internal)?.currentDate)?.call(t)??new Date,{requestBody:r,warnings:i}=await this.getArgs(e),{value:a,responseHeaders:o,rawValue:s}=await z({url:this.config.url({path:`/audio/speech`,modelId:this.modelId}),headers:x(this.config.headers(),e.headers),body:r,failedResponseHandler:Mn,successfulResponseHandler:w(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:a,warnings:i,request:{body:JSON.stringify(r)},response:{timestamp:n,modelId:this.modelId,headers:o,body:s}}}},Si=U.object({include:U.array(U.string()).optional(),language:U.string().optional(),prompt:U.string().optional(),temperature:U.number().min(0).max(1).default(0).optional(),timestampGranularities:U.array(U.enum([`word`,`segment`])).default([`segment`]).optional()}),Ci={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`},wi=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:n}){let r=[],i=await L({provider:`openai`,providerOptions:n,schema:Si}),a=new FormData,o=e instanceof Uint8Array?new Blob([e]):new Blob([S(e)]);a.append(`model`,this.modelId);let s=I(t);if(a.append(`file`,new File([o],`audio`,{type:t}),`audio.${s}`),i){let e={include:i.include,language:i.language,prompt:i.prompt,response_format:[`gpt-4o-transcribe`,`gpt-4o-mini-transcribe`].includes(this.modelId)?`json`:`verbose_json`,temperature:i.temperature,timestamp_granularities:i.timestampGranularities};for(let[t,n]of Object.entries(e))if(n!=null)if(Array.isArray(n))for(let e of n)a.append(`${t}[]`,String(e));else a.append(t,String(n))}return{formData:a,warnings:r}}async doGenerate(e){var t;let n=((t=this.config._internal)?.currentDate)?.call(t)??new Date,{formData:r,warnings:i}=await this.getArgs(e),{value:a,responseHeaders:o,rawValue:s}=await R({url:this.config.url({path:`/audio/transcriptions`,modelId:this.modelId}),headers:x(this.config.headers(),e.headers),formData:r,failedResponseHandler:Mn,successfulResponseHandler:O(Ti),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=a.language!=null&&a.language in Ci?Ci[a.language]:void 0;return{text:a.text,segments:a.segments?.map(e=>({text:e.text,startSecond:e.start,endSecond:e.end}))??a.words?.map(e=>({text:e.word,startSecond:e.start,endSecond:e.end}))??[],language:c,durationInSeconds:a.duration??void 0,warnings:i,response:{timestamp:n,modelId:this.modelId,headers:o,body:s}}}},Ti=U.object({text:U.string(),language:U.string().nullish(),duration:U.number().nullish(),words:U.array(U.object({word:U.string(),start:U.number(),end:U.number()})).nullish(),segments:U.array(U.object({id:U.number(),seek:U.number(),start:U.number(),end:U.number(),text:U.string(),tokens:U.array(U.number()),temperature:U.number(),avg_logprob:U.number(),compression_ratio:U.number(),no_speech_prob:U.number()})).nullish()}),Ei=`2.0.42`;function Di(e={}){let t=oe(F({settingValue:e.baseURL,environmentVariableName:`OPENAI_BASE_URL`}))??`https://api.openai.com/v1`,n=e.name??`openai`,r=()=>ae({Authorization:`Bearer ${ne({apiKey:e.apiKey,environmentVariableName:`OPENAI_API_KEY`,description:`OpenAI`})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${Ei}`),i=i=>new Rn(i,{provider:`${n}.chat`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),a=i=>new Zn(i,{provider:`${n}.completion`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),o=i=>new nr(i,{provider:`${n}.embedding`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),s=i=>new or(i,{provider:`${n}.image`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),c=i=>new wi(i,{provider:`${n}.transcription`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),l=i=>new xi(i,{provider:`${n}.speech`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),u=e=>{if(new.target)throw Error(`The OpenAI model function cannot be called with the new keyword.`);return d(e)},d=i=>new Ur(i,{provider:`${n}.responses`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch,fileIdPrefixes:[`file-`]}),f=function(e){return u(e)};return f.languageModel=u,f.chat=i,f.completion=a,f.responses=d,f.embedding=o,f.textEmbedding=o,f.textEmbeddingModel=o,f.image=s,f.imageModel=s,f.transcription=c,f.transcriptionModel=c,f.speech=l,f.speechModel=l,f.tools=Ar,f}Di();function Oi(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function ki(e){return Object.fromEntries([...e.headers])}function Ai(e=globalThis){return e.window?`runtime/browser`:e.navigator?.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:e.process?.versions?.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?`runtime/vercel-edge`:`runtime/unknown`}function ji(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function Mi(e,...t){let n=ji(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}(({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new f({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();function Ni(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Pi=[`fetch failed`,`failed to fetch`];function Fi({error:e,url:t,requestBodyValues:n}){if(Ni(e))return e;if(e instanceof TypeError&&Pi.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new s({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}var Ii=`3.0.10`,Li=/"__proto__"\s*:/,Ri=/"constructor"\s*:/;function zi(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Li.test(e)===!1&&Ri.test(e)===!1?t:Bi(t)}function Bi(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function Vi(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return zi(e)}finally{Error.stackTraceLimit=t}}var Hi=Symbol.for(`vercel.ai.validator`);function Ui(e){return{[Hi]:!0,validate:e}}function Wi(e){return typeof e==`object`&&!!e&&Hi in e&&e[Hi]===!0&&`validate`in e}function Gi(e){return Wi(e)?e:Ki(e)}function Ki(e){return Ui(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new y({value:t,cause:n.issues})}})}async function qi({value:e,schema:t}){let n=await Ji({value:e,schema:t});if(!n.success)throw y.wrap({value:e,cause:n.error});return n.value}async function Ji({value:e,schema:t}){let n=Gi(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:y.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:y.wrap({value:e,cause:t}),rawValue:e}}}async function Yi({text:e,schema:t}){try{let n=Vi(e);return t==null?n:qi({value:n,schema:t})}catch(t){throw h.isInstance(t)||y.isInstance(t)?t:new h({text:e,cause:t})}}async function Xi({text:e,schema:t}){try{let n=Vi(e);return t==null?{success:!0,value:n,rawValue:n}:await Ji({value:n,schema:t})}catch(t){return{success:!1,error:h.isInstance(t)?t:new h({text:e,cause:t}),rawValue:void 0}}}var Zi=()=>globalThis.fetch,Qi=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>$i({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),$i=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=Zi()})=>{try{let c=await o(e,{method:`POST`,headers:Mi(t,`ai-sdk/provider-utils/${Ii}`,Ai()),body:n.content,signal:a}),l=ki(c);if(!c.ok){let t;try{t=await i({response:c,url:e,requestBodyValues:n.values})}catch(t){throw Ni(t)||s.isInstance(t)?t:new s({message:`Failed to process error response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw t.value}try{return await r({response:c,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(Ni(t)||s.isInstance(t))?t:new s({message:`Failed to process successful response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(t){throw Fi({error:t,url:e,requestBodyValues:n.values})}},ea=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),c=ki(r);if(o.trim()===``)return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})};try{let l=await Yi({text:o,schema:e});return{responseHeaders:c,value:new s({message:t(l),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})}}},ta=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await Xi({text:i,schema:e}),o=ki(t);if(!a.success)throw new s({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},{btoa:na,atob:ra}=globalThis;U.object({user:U.string().optional(),reasoningEffort:U.string().optional()});var ia={errorSchema:U.object({error:U.object({message:U.string(),type:U.string().nullish(),param:U.any().nullish(),code:U.union([U.string(),U.number()]).nullish()})}),errorToMessage:e=>e.error.message},aa=U.object({prompt_tokens:U.number().nullish(),completion_tokens:U.number().nullish(),total_tokens:U.number().nullish(),prompt_tokens_details:U.object({cached_tokens:U.number().nullish()}).nullish(),completion_tokens_details:U.object({reasoning_tokens:U.number().nullish(),accepted_prediction_tokens:U.number().nullish(),rejected_prediction_tokens:U.number().nullish()}).nullish()}).nullish();U.object({id:U.string().nullish(),created:U.number().nullish(),model:U.string().nullish(),choices:U.array(U.object({message:U.object({role:U.literal(`assistant`).nullish(),content:U.string().nullish(),reasoning_content:U.string().nullish(),reasoning:U.string().nullish(),tool_calls:U.array(U.object({id:U.string().nullish(),function:U.object({name:U.string(),arguments:U.string()})})).nullish()}),finish_reason:U.string().nullish()})),usage:aa}),U.object({echo:U.boolean().optional(),logitBias:U.record(U.string(),U.number()).optional(),suffix:U.string().optional(),user:U.string().optional()});var oa=U.object({prompt_tokens:U.number(),completion_tokens:U.number(),total_tokens:U.number()});U.object({id:U.string().nullish(),created:U.number().nullish(),model:U.string().nullish(),choices:U.array(U.object({text:U.string(),finish_reason:U.string()})),usage:oa.nullish()}),U.object({dimensions:U.number().optional(),user:U.string().optional()}),U.object({data:U.array(U.object({embedding:U.array(U.number())})),usage:U.object({prompt_tokens:U.number()}).nullish(),providerMetadata:U.record(U.string(),U.record(U.string(),U.any())).optional()});var sa=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`,this.maxImagesPerCall=10}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:a,headers:o,abortSignal:s}){var c;let l=[];r!=null&&l.push({type:`unsupported-setting`,setting:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&l.push({type:`unsupported-setting`,setting:`seed`});let u=((c=this.config._internal)?.currentDate)?.call(c)??new Date,{value:d,responseHeaders:f}=await Qi({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:Oi(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...a.openai??{},response_format:`b64_json`},failedResponseHandler:ea(this.config.errorStructure??ia),successfulResponseHandler:ta(ca),abortSignal:s,fetch:this.config.fetch});return{images:d.data.map(e=>e.b64_json),warnings:l,response:{timestamp:u,modelId:this.modelId,headers:f}}}},ca=U.object({data:U.array(U.object({b64_json:U.string()}))});function la(e){let t=[],n=[];for(let{role:n,content:r}of e)switch(n){case`system`:t.push({role:`system`,content:r});break;case`user`:if(r.length===1&&r[0].type===`text`){t.push({role:`user`,content:r[0].text});break}t.push({role:`user`,content:r.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`image_url`,image_url:{url:e.data instanceof URL?e.data.toString():`data:${t};base64,${C(e.data)}`}}}else throw new b({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e=``,n=[];for(let t of r)switch(t.type){case`text`:e+=t.text;break;case`tool-call`:n.push({id:t.toolCallId,type:`function`,function:{name:t.toolName,arguments:JSON.stringify(t.input)}});break}t.push({role:`assistant`,content:e,tool_calls:n.length>0?n:void 0});break}case`tool`:for(let e of r){let n=e.output,r;switch(n.type){case`text`:case`error-text`:r=n.value;break;case`content`:case`json`:case`error-json`:r=JSON.stringify(n.value);break}t.push({role:`tool`,tool_call_id:e.toolCallId,content:r})}break;default:{let e=n;throw Error(`Unsupported role: ${e}`)}}return{messages:t,warnings:n}}function ua({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function da(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`tool_calls`:case`function_call`:return`tool-calls`;case`content_filter`:return`content-filter`;default:return`unknown`}}var fa=U.object({type:U.literal(`web`),country:U.string().length(2).optional(),excludedWebsites:U.array(U.string()).max(5).optional(),allowedWebsites:U.array(U.string()).max(5).optional(),safeSearch:U.boolean().optional()}),pa=U.object({type:U.literal(`x`),excludedXHandles:U.array(U.string()).optional(),includedXHandles:U.array(U.string()).optional(),postFavoriteCount:U.number().int().optional(),postViewCount:U.number().int().optional(),xHandles:U.array(U.string()).optional()}),ma=U.object({type:U.literal(`news`),country:U.string().length(2).optional(),excludedWebsites:U.array(U.string()).max(5).optional(),safeSearch:U.boolean().optional()}),ha=U.object({type:U.literal(`rss`),links:U.array(U.string().url()).max(1)}),ga=U.discriminatedUnion(`type`,[fa,pa,ma,ha]),_a=U.object({reasoningEffort:U.enum([`low`,`high`]).optional(),searchParameters:U.object({mode:U.enum([`off`,`auto`,`on`]),returnCitations:U.boolean().optional(),fromDate:U.string().optional(),toDate:U.string().optional(),maxSearchResults:U.number().min(1).max(50).optional(),sources:U.array(ga).optional()}).optional()}),va=U.object({error:U.object({message:U.string(),type:U.string().nullish(),param:U.any().nullish(),code:U.union([U.string(),U.number()]).nullish()})}),ya=D({errorSchema:va,errorToMessage:e=>e.error.message});function ba({tools:e,toolChoice:t}){e=e?.length?e:void 0;let n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};let r=[];for(let t of e)t.type===`provider-defined`?n.push({type:`unsupported-tool`,tool:t}):r.push({type:`function`,function:{name:t.name,description:t.description,parameters:t.inputSchema}});if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};let i=t.type;switch(i){case`auto`:case`none`:return{tools:r,toolChoice:i,toolWarnings:n};case`required`:return{tools:r,toolChoice:`required`,toolWarnings:n};case`tool`:return{tools:r,toolChoice:{type:`function`,function:{name:t.toolName}},toolWarnings:n};default:throw new b({functionality:`tool choice type: ${i}`})}}var xa=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,seed:c,responseFormat:l,providerOptions:u,tools:d,toolChoice:f}){let p=[],m=await L({provider:`xai`,providerOptions:u,schema:_a})??{};i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),a!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),s!=null&&p.push({type:`unsupported-setting`,setting:`stopSequences`}),l!=null&&l.type===`json`&&l.schema!=null&&p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format schema is not supported`});let{messages:h,warnings:g}=la(e);p.push(...g);let{tools:_,toolChoice:v,toolWarnings:y}=ba({tools:d,toolChoice:f});return p.push(...y),{args:{model:this.modelId,max_tokens:t,temperature:n,top_p:r,seed:c,reasoning_effort:m.reasoningEffort,response_format:l?.type===`json`?l.schema==null?{type:`json_object`}:{type:`json_schema`,json_schema:{name:l.name??`response`,schema:l.schema,strict:!0}}:void 0,search_parameters:m.searchParameters?{mode:m.searchParameters.mode,return_citations:m.searchParameters.returnCitations,from_date:m.searchParameters.fromDate,to_date:m.searchParameters.toDate,max_search_results:m.searchParameters.maxSearchResults,sources:m.searchParameters.sources?.map(e=>({type:e.type,...e.type===`web`&&{country:e.country,excluded_websites:e.excludedWebsites,allowed_websites:e.allowedWebsites,safe_search:e.safeSearch},...e.type===`x`&&{excluded_x_handles:e.excludedXHandles,included_x_handles:e.includedXHandles??e.xHandles,post_favorite_count:e.postFavoriteCount,post_view_count:e.postViewCount},...e.type===`news`&&{country:e.country,excluded_websites:e.excludedWebsites,safe_search:e.safeSearch},...e.type===`rss`&&{links:e.links}}))}:void 0,messages:h,tools:_,tool_choice:v},warnings:p}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:i,rawValue:a}=await z({url:`${this.config.baseURL??`https://api.x.ai/v1`}/chat/completions`,headers:x(this.config.headers(),e.headers),body:t,failedResponseHandler:ya,successfulResponseHandler:O(Ca),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=i.choices[0],s=[];if(o.message.content!=null&&o.message.content.length>0){let e=o.message.content,n=t.messages[t.messages.length-1];n?.role===`assistant`&&e===n.content&&(e=``),e.length>0&&s.push({type:`text`,text:e})}if(o.message.reasoning_content!=null&&o.message.reasoning_content.length>0&&s.push({type:`reasoning`,text:o.message.reasoning_content}),o.message.tool_calls!=null)for(let e of o.message.tool_calls)s.push({type:`tool-call`,toolCallId:e.id,toolName:e.function.name,input:e.function.arguments});if(i.citations!=null)for(let e of i.citations)s.push({type:`source`,sourceType:`url`,id:this.config.generateId(),url:e});return{content:s,finishReason:da(o.finish_reason),usage:{inputTokens:i.usage.prompt_tokens,outputTokens:i.usage.completion_tokens,totalTokens:i.usage.total_tokens,reasoningTokens:i.usage.completion_tokens_details?.reasoning_tokens??void 0},request:{body:t},response:{...ua(i),headers:r,body:a},warnings:n}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:a}=await z({url:`${this.config.baseURL??`https://api.x.ai/v1`}/chat/completions`,headers:x(this.config.headers(),e.headers),body:r,failedResponseHandler:ya,successfulResponseHandler:T(wa),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=`unknown`,s={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},c=!0,l={},u={},d=this;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let i=t.value;if(c&&=(n.enqueue({type:`response-metadata`,...ua(i)}),!1),i.citations!=null)for(let e of i.citations)n.enqueue({type:`source`,sourceType:`url`,id:d.config.generateId(),url:e});i.usage!=null&&(s.inputTokens=i.usage.prompt_tokens,s.outputTokens=i.usage.completion_tokens,s.totalTokens=i.usage.total_tokens,s.reasoningTokens=i.usage.completion_tokens_details?.reasoning_tokens??void 0);let a=i.choices[0];if(a?.finish_reason!=null&&(o=da(a.finish_reason)),a?.delta==null)return;let f=a.delta,p=a.index;if(f.content!=null&&f.content.length>0){let e=f.content,t=r.messages[r.messages.length-1];if(t?.role===`assistant`&&e===t.content)return;let a=`text-${i.id||p}`;l[a]??(l[a]={type:`text`},n.enqueue({type:`text-start`,id:a})),n.enqueue({type:`text-delta`,id:a,delta:e})}if(f.reasoning_content!=null&&f.reasoning_content.length>0){let e=`reasoning-${i.id||p}`;if(u[e]===f.reasoning_content)return;u[e]=f.reasoning_content,l[e]??(l[e]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:e})),n.enqueue({type:`reasoning-delta`,id:e,delta:f.reasoning_content})}if(f.tool_calls!=null)for(let e of f.tool_calls){let t=e.id;n.enqueue({type:`tool-input-start`,id:t,toolName:e.function.name}),n.enqueue({type:`tool-input-delta`,id:t,delta:e.function.arguments}),n.enqueue({type:`tool-input-end`,id:t}),n.enqueue({type:`tool-call`,toolCallId:t,toolName:e.function.name,input:e.function.arguments})}},flush(e){for(let[t,n]of Object.entries(l))e.enqueue({type:n.type===`text`?`text-end`:`reasoning-end`,id:t});e.enqueue({type:`finish`,finishReason:o,usage:s})}})),request:{body:r},response:{headers:i}}}},Sa=U.object({prompt_tokens:U.number(),completion_tokens:U.number(),total_tokens:U.number(),completion_tokens_details:U.object({reasoning_tokens:U.number().nullish()}).nullish()}),Ca=U.object({id:U.string().nullish(),created:U.number().nullish(),model:U.string().nullish(),choices:U.array(U.object({message:U.object({role:U.literal(`assistant`),content:U.string().nullish(),reasoning_content:U.string().nullish(),tool_calls:U.array(U.object({id:U.string(),type:U.literal(`function`),function:U.object({name:U.string(),arguments:U.string()})})).nullish()}),index:U.number(),finish_reason:U.string().nullish()})),object:U.literal(`chat.completion`),usage:Sa,citations:U.array(U.string().url()).nullish()}),wa=U.object({id:U.string().nullish(),created:U.number().nullish(),model:U.string().nullish(),choices:U.array(U.object({delta:U.object({role:U.enum([`assistant`]).optional(),content:U.string().nullish(),reasoning_content:U.string().nullish(),tool_calls:U.array(U.object({id:U.string(),type:U.literal(`function`),function:U.object({name:U.string(),arguments:U.string()})})).nullish()}),finish_reason:U.string().nullish(),index:U.number()})),usage:Sa.nullish(),citations:U.array(U.string().url()).nullish()}),Ta=`2.0.23`,Ea={errorSchema:va,errorToMessage:e=>e.error.message};function Da(e={}){let t=oe(e.baseURL??`https://api.x.ai/v1`),n=()=>ae({Authorization:`Bearer ${ne({apiKey:e.apiKey,environmentVariableName:`XAI_API_KEY`,description:`xAI API key`})}`,...e.headers},`ai-sdk/xai/${Ta}`),r=r=>new xa(r,{provider:`xai.chat`,baseURL:t,headers:n,generateId:M,fetch:e.fetch}),i=r=>new sa(r,{provider:`xai.image`,url:({path:e})=>`${t}${e}`,headers:n,fetch:e.fetch,errorStructure:Ea}),a=e=>r(e);return a.languageModel=r,a.chat=r,a.textEmbeddingModel=e=>{throw new g({modelId:e,modelType:`textEmbeddingModel`})},a.imageModel=i,a.image=i,a}Da();function Oa(e){if(!e.body)throw Error(`Response body is required`);let t=e.headers.get(_);if(!t||t===`ui-message`)return e.body.pipeThrough(new TextDecoderStream).pipeThrough(new u).pipeThrough(new TransformStream({async transform(e,t){if(e.data!==`[DONE]`)try{let n=JSON.parse(e.data);t.enqueue(n)}catch(e){t.error(e);return}}}));let n=e=>Fe({model:e,prompt:[{role:`user`,content:[{type:`text`,text:`Hello, world!`}]}]}).toUIMessageStream();switch(t){case`openai-chat`:return n(Di({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`openai-response`:return n(Di({apiKey:`ignored`,fetch:(t,n)=>e}).responses(`fake-model`));case`anthropic`:return n(Jt({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`google`:return n(An({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`xai`:return n(Da({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));default:throw Error(`Unsupported response format: ${t}`)}}var ka=class{baseUrl;client;constructor(e){this.client=N(e.baseUrl),this.baseUrl=e.baseUrl}async chat(e,t){let n=await this.client._agent.chat.$post({json:e},{headers:t?.headers,init:{signal:t?.signal}});return n.ok||await this.handleError(n),Oa(n)}async capabilities(){let e=await this.client._agent.capabilities.$get();return e.ok||await this.handleError(e),e.json()}async ui(e,t){let n=await this.client._agent.ui.$get({query:e.selectedOptions?{selected_options:JSON.stringify(e.selectedOptions)}:{}},{init:{signal:t?.signal}});if(!n.ok||n.status!==200){if(n.status===404)return;await this.handleError(n)}return n.json()}async health(){let e=await this.client._agent.health.$get();e.ok||await this.handleError(e)}async handleError(e){let t;try{t=await e.text()}catch{}if(t){let n;try{n=JSON.parse(t)}catch{}throw n?Error(n.error):Error(`Failed (${e.status}): ${t}`)}throw Error(`Failed (${e.status}): ${e.statusText}`)}};function Aa(e){let[t,n]=K(void 0),[r,i]=K([]),[a,o]=K(void 0),[s,l]=K(e.buildResult),[u,d]=K(e.env),[f,p]=K(e.apiServerUrl),[m,h]=K(void 0);return G(()=>{d(e.env),l(e.buildResult),p(e.apiServerUrl)},[e.env,e.buildResult,e.apiServerUrl]),G(()=>{if(!s||`error`in s){n(void 0),i([]),o(void 0),h(void 0);return}let e=new AbortController,t=!1;return o(void 0),n(void 0),h(void 0),(async()=>{let t=await ja(),r=Ve(`node`,[`--no-deprecation`,s.entry],{stdio:`pipe`,env:{...process.env,...u,[c]:f,PORT:t.toString(),HOST:`127.0.0.1`}});e.signal.addEventListener(`abort`,()=>{try{r.kill()}catch{}});let a=!1;r.stdout.on(`data`,e=>{let t=Buffer.from(e).toString(`utf-8`).trim();!a&&t.startsWith(`Agent server listening on`)||(a||console.log(`stdout: ${t}`),t.length&&i(e=>[...e,{level:`log`,message:t}]))}),r.stderr.on(`data`,e=>{a||console.error(`stderr: ${Buffer.from(e).toString(`utf-8`).trim()}`);let t=Buffer.from(e).toString(`utf-8`).trim();t.length&&i(e=>[...e,{level:`error`,message:t}])}),r.on(`error`,t=>{e.abort(t)}),r.on(`exit`,(t,n)=>{e.abort(`Agent exited with code ${t??`unknown`} and signal ${n??`unknown`}. Be sure to call "blink.agent(...).serve()".`)});let o=new ka({baseUrl:`http://127.0.0.1:${t}`});for(;!e.signal.aborted;){try{await o.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(e.signal.aborted)throw e.signal.reason;a=!0;let l=await o.capabilities();h(l),n(o)})().catch(e=>{t||o(e instanceof Error?e:Error(String(e)))}),()=>{t=!0,e.abort()}},[s,u,f]),Ue(()=>({agent:t,logs:r,error:a,capabilities:m}),[t,r,a,m])}async function ja(){let e=Ce();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}var Ma=Object.getOwnPropertyNames,Na=(e,t)=>function(){return t||(0,e[Ma(e)[0]])((t={exports:{}}).exports,t),t.exports},X=H(import.meta.url);Y.object({email:Y.string().email(),password:Y.string().min(8)}),Y.object({email:Y.string().email(),code:Y.string()}),Y.object({email:Y.string().email(),password:Y.string().min(8)});var Pa=class{constructor(e,t){this.client=e,this.baseURL=t}async token(e,t={timeout:12e4}){return new Promise((n,r)=>{let i=crypto.randomUUID(),a=this.client.websocket(`/api/auth/token?id=${i}`),o=new URL(`/auth?id=${i}`,this.baseURL),s=setTimeout(()=>{r(Error(`Timeout waiting for the user to authenticate`))},t.timeout);a.onerror=e=>{clearTimeout(s),console.log(`error`,e),r(Error(`Failed to connect to server`))},a.onopen=()=>{e(o.toString(),i)},a.onmessage=e=>{typeof e.data==`string`&&(clearTimeout(s),n(e.data))}})}},Fa=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function Ia(e){}function La(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=Ia,onError:n=Ia,onRetry:r=Ia,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=Ra(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1,i=e.slice(t+r);f(n,i,e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t}
|
|
16
16
|
`;break;case`id`:s=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new Fa(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new Fa(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}));break}}function p(){c.length>0&&t({id:s,event:l||void 0,data:c.endsWith(`
|
|
17
17
|
`)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function Ra(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
|
|
18
18
|
`,r),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i===-1?a!==-1&&(o=a):o=i===e.length-1?-1:i,o===-1){n=e.slice(r);break}else{let n=e.slice(r,o);t.push(n),r=o+1,e[r-1]===`\r`&&e[r]===`
|
|
@@ -50,7 +50,7 @@ ${ml}`),t.includes(`
|
|
|
50
50
|
`)&&(n=3+be(t.slice(t.lastIndexOf(`
|
|
51
51
|
`))).length);let e=be(t).length;n+e<process.stdout.columns?(n+=e,process.stdout.write(t)):(process.stdout.write(`
|
|
52
52
|
${ml}${t.trimStart()}`),n=3+be(t.trimStart()).length)}process.stdout.write(`
|
|
53
|
-
`)},info:e=>hl.message(e,{symbol:rl.default.blue(ll)}),success:e=>hl.message(e,{symbol:rl.default.green(ul)}),step:e=>hl.message(e,{symbol:rl.default.green(sl)}),warn:e=>hl.message(e,{symbol:rl.default.yellow(dl)}),warning:e=>hl.warn(e),error:e=>hl.message(e,{symbol:rl.default.red(fl)})};let gl;function _l(){try{return ue.statSync(`/.dockerenv`),!0}catch{return!1}}function vl(){try{return ue.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function yl(){return gl===void 0&&(gl=_l()||vl()),gl}let bl;const xl=()=>{try{return ue.statSync(`/run/.containerenv`),!0}catch{return!1}};function Sl(){return bl===void 0&&(bl=xl()||yl()),bl}const Cl=()=>{if(Xe.platform!==`linux`)return!1;if(ot.release().toLowerCase().includes(`microsoft`))return!Sl();try{return ue.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!Sl():!1}catch{return!1}};var wl=Xe.env.__IS_WSL_TEST__?Cl:Cl();const Tl=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await it.access(n,at.F_OK),r=!0}catch{}if(!r)return e;let i=await it.readFile(n,{encoding:`utf8`}),a=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(i);return a?(t=a.groups.mountPoint.trim(),t=t.endsWith(`/`)?t:`${t}/`,t):e}})(),El=async()=>`${await Tl()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Dl=async()=>wl?El():`${Xe.env.SYSTEMROOT||Xe.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function Ol(e,t,n){let r=n=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0});return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){let e=n();return r(e),e},set(e){r(e)}}),e}const kl=ye(nt);async function Al(){if(Xe.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await kl(`defaults`,[`read`,`com.apple.LaunchServices/com.apple.launchservices.secure`,`LSHandlers`]);return/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??`com.apple.Safari`}const jl=ye(nt);async function Ml(e,{humanReadableOutput:t=!0,signal:n}={}){if(Xe.platform!==`darwin`)throw Error(`macOS only`);let r=t?[]:[`-ss`],i={};n&&(i.signal=n);let{stdout:a}=await jl(`osascript`,[`-e`,e,r],i);return a.trim()}async function Nl(e){return Ml(`tell application "Finder" to set app_path to application file id "${e}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}const Pl=ye(nt),Fl={AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:`Edge`,id:`com.microsoft.edge.old`},MSEdgeDHTML:{name:`Edge`,id:`com.microsoft.edge`},MSEdgeHTM:{name:`Edge`,id:`com.microsoft.edge`},"IE.HTTP":{name:`Internet Explorer`,id:`com.microsoft.ie`},FirefoxURL:{name:`Firefox`,id:`org.mozilla.firefox`},ChromeHTML:{name:`Chrome`,id:`com.google.chrome`},BraveHTML:{name:`Brave`,id:`com.brave.Browser`},BraveBHTML:{name:`Brave Beta`,id:`com.brave.Browser.beta`},BraveSSHTM:{name:`Brave Nightly`,id:`com.brave.Browser.nightly`}};var Il=class extends Error{};async function Ll(e=Pl){let{stdout:t}=await e(`reg`,[`QUERY`,` HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice`,`/v`,`ProgId`]),n=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(t);if(!n)throw new Il(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=Fl[r];if(!i)throw new Il(`Unknown browser ID: ${r}`);return i}const Rl=ye(nt),zl=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function Bl(){if(Xe.platform===`darwin`){let e=await Al();return{name:await Nl(e),id:e}}if(Xe.platform===`linux`){let{stdout:e}=await Rl(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:zl(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(Xe.platform===`win32`)return Ll();throw Error(`Only macOS, Linux, and Windows are supported`)}const Vl=ye(tt.execFile),Hl=qe.dirname(_e(import.meta.url)),Ul=qe.join(Hl,`xdg-open`),{platform:Wl,arch:Gl}=Xe;async function Kl(){let e=await Dl(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=le.from(t,`utf16le`).toString(`base64`),{stdout:r}=await Vl(e,[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,n],{encoding:`utf8`}),i=r.trim(),a={ChromeHTML:`com.google.chrome`,BraveHTML:`com.brave.Browser`,MSEdgeHTM:`com.microsoft.edge`,FirefoxURL:`org.mozilla.firefox`};return a[i]?{id:a[i]}:{}}const ql=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},Jl=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return ql(e.app,t=>Jl({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return ql(t,t=>Jl({...e,app:{name:t,arguments:n}}));if(t===`browser`||t===`browserPrivate`){let r={"com.google.chrome":`chrome`,"google-chrome.desktop":`chrome`,"com.brave.Browser":`brave`,"org.mozilla.firefox":`firefox`,"firefox.desktop":`firefox`,"com.microsoft.msedge":`edge`,"com.microsoft.edge":`edge`,"com.microsoft.edgemac":`edge`,"microsoft-edge.desktop":`edge`},i={chrome:`--incognito`,brave:`--incognito`,firefox:`--private-window`,edge:`--inPrivate`},a=wl?await Kl():await Bl();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),Jl({...e,app:{name:Ql[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,i=[],a={};if(Wl===`darwin`)r=`open`,e.wait&&i.push(`--wait-apps`),e.background&&i.push(`--background`),e.newInstance&&i.push(`--new`),t&&i.push(`-a`,t);else if(Wl===`win32`||wl&&!Sl()&&!t){r=await Dl(),i.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),wl||(a.windowsVerbatimArguments=!0);let o=[`Start`];e.wait&&o.push(`-Wait`),t?(o.push(`"\`"${t}\`""`),e.target&&n.push(e.target)):e.target&&o.push(`"${e.target}"`),n.length>0&&(n=n.map(e=>`"\`"${e}\`""`),o.push(`-ArgumentList`,n.join(`,`))),e.target=le.from(o.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!Hl||Hl===`/`,t=!1;try{await it.access(Ul,at.X_OK),t=!0}catch{}r=Xe.versions.electron??(Wl===`android`||e||!t)?`xdg-open`:Ul}n.length>0&&i.push(...n),e.wait||(a.stdio=`ignore`,a.detached=!0)}Wl===`darwin`&&n.length>0&&i.push(`--args`,...n),e.target&&i.push(e.target);let o=tt.spawn(r,i,a);return e.wait?new Promise((t,n)=>{o.once(`error`,n),o.once(`close`,r=>{if(!e.allowNonzeroExitCode&&r>0){n(Error(`Exited with code ${r}`));return}t(o)})}):(o.unref(),o)},Yl=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return Jl({...t,target:e})};function Xl(e){if(typeof e==`string`||Array.isArray(e))return e;let{[Gl]:t}=e;if(!t)throw Error(`${Gl} is not supported`);return t}function Zl({[Wl]:e},{wsl:t}){if(t&&wl)return Xl(t);if(!e)throw Error(`${Wl} is not supported`);return Xl(e)}const Ql={};Ol(Ql,`chrome`,()=>Zl({darwin:`google chrome`,win32:`chrome`,linux:[`google-chrome`,`google-chrome-stable`,`chromium`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`,x64:[`/mnt/c/Program Files/Google/Chrome/Application/chrome.exe`,`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`]}})),Ol(Ql,`brave`,()=>Zl({darwin:`brave browser`,win32:`brave`,linux:[`brave-browser`,`brave`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`,x64:[`/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe`,`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`]}})),Ol(Ql,`firefox`,()=>Zl({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),Ol(Ql,`edge`,()=>Zl({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),Ol(Ql,`browser`,()=>`browser`),Ol(Ql,`browserPrivate`,()=>`browserPrivate`);var $l=Yl;function eu(e){let t=e||ru();if(fe(t)){let e=me(t,`utf8`);return JSON.parse(e).token}}function tu(e,t){let n=t||ru();fe(Je(n))||pe(Je(n),{recursive:!0}),ge(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function nu(e){let t=e||ru();fe(t)&&he(t)}function ru(){let e=Mc(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return Ye(e[0],`auth.json`)}function iu(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=K(),[s,c]=K(()=>eu(i)),[l,u]=K(),d=We(n),f=We(r);G(()=>{d.current=n,f.current=r},[n,r]);let p=He(async()=>{u(void 0);try{let e=eu(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new mc({baseURL:`https://blink.so`});t.authToken=e;let n={email:(await t.users.me()).email};o(n),d.current?.(n)}catch(e){o(void 0),u(e instanceof Error?e.message:String(e)),d.current?.(void 0)}},[i]),m=He(async()=>{u(void 0);try{let e=new mc,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();tu(t,i),c(t);let r={email:n.email};return o(r),d.current?.(r),r}catch(e){let t=e instanceof Error?e.message:String(e);throw u(t),e}},[i]),h=He(()=>{nu(i),c(void 0),o(void 0),u(void 0),d.current?.(void 0)},[i]);return G(()=>{t&&p()},[t,p]),{user:a,token:s,error:l,login:m,logout:h}}function au(e){let{directory:t,onBuildStart:n,onBuildSuccess:r,onBuildError:i}=typeof e==`string`?{directory:e}:e,a=Ue(()=>se(t),[t]),[o,s]=K(void 0),[c,l]=K(void 0),[u,d]=K(`building`),f=We(n),p=We(r),m=We(i);return G(()=>{f.current=n,p.current=r,m.current=i},[n,r,i]),G(()=>{let e=new AbortController;return a.build({cwd:t,entry:a.entry,outdir:a.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{d(`building`),s(void 0),l(void 0),f.current?.()},onResult:e=>{`error`in e?(s(e.error),d(`error`),m.current?.(e.error)):(l(e),d(`success`),p.current?.(e))}}).catch(e=>{console.log(`error`,e),d(`error`),s(e),m.current?.(e)}),()=>{e.abort()}},[t]),Ue(()=>({error:o,status:u,result:c,entry:a.entry,outdir:a.outdir}),[o,u,c,a.entry,a.outdir])}function ou(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function su(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const cu=/^\.+(\\|\/)|^\.+$/,lu=/[. ]+$/,uu=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,du=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,fu=e=>e===``,pu=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,mu=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let hu;function gu(){return hu??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),hu}function _u(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(ou().test(n)||[...n].some(e=>du.test(e)&&!fu(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(mu,` `),n.length>0&&(e=e.replaceAll(pu,`$1`)),e=e.replace(lu,``),e=e.replace(cu,n),e=e.replace(ou(),n),e=e.replaceAll(uu,e=>fu(e)?e:n),e.length===0&&(e=n),e=su().test(e)?e+n:e;let r=typeof t.maxLength==`number`?t.maxLength:100;if(e.length>r){let t=e.lastIndexOf(`.`);if(t===-1)e=vu(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=vu(n,a)+i}}return e}function vu(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of gu().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function yu(e){return`${e}.lock`}function bu(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function xu(e,t={}){let n=yu(e),r=process.pid.toString();try{return W.writeFileSync(n,r,{flag:`wx`}),!0}catch(r){if(r.code!==`EEXIST`)throw r;if(t.stale===0)return!1;let i;try{i=parseInt(W.readFileSync(n,`utf8`),10)}catch{return W.unlinkSync(n),xu(e,{...t,stale:0})}if(!bu(i))try{return W.unlinkSync(n),xu(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return xu(e,{...t,stale:0});throw n}return!1}}async function Su(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=Ke.resolve(e),i=0;for(;i<=n.retries;){if(xu(r,n))return()=>Cu(r);i<n.retries&&await new Promise(e=>setTimeout(e,n.retryInterval)),i++}let a=Error(`Lock file is already being held`);throw a.code=`ELOCKED`,a.file=r,a}function Cu(e){let t=Ke.resolve(e),n=yu(t);try{if(parseInt(W.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}W.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function wu(e){let t=Ke.resolve(e),n=yu(t);try{if(!W.existsSync(n))return{locked:!1};let e=W.readFileSync(n,`utf8`),t=parseInt(e,10);return bu(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const Tu=e=>{W.mkdirSync(e,{recursive:!0})},Eu=e=>{try{W.fdatasyncSync(e)}catch{}try{W.closeSync(e)}catch{}},Du=e=>{try{let t=W.openSync(e,`r`);try{W.fsyncSync(t)}finally{W.closeSync(t)}}catch{}},Ou=(e,t)=>{let n=Ke.dirname(e);Tu(n);let r=Ke.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=W.openSync(r,`w`),W.writeFileSync(i,t,`utf-8`),Eu(i),i=void 0,W.renameSync(r,e),Du(e),Du(n)}catch(e){if(i!==void 0)try{W.closeSync(i)}catch{}try{W.rmSync(r,{force:!0})}catch{}throw e}},ku=(e,t)=>{let n=new Map,r,i=e=>{if(W.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(W.readFileSync(e,`utf-8`))},a=(e,t)=>{Ou(e,JSON.stringify(t,null,2))},o=async()=>{if(r)throw Error(`Index is already locked`);let t=Ke.join(e,`index.json`);Tu(e),W.existsSync(t)||W.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await Su(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},s=async()=>{let t=Ke.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},c=async t=>{let n=Ke.join(e,`index.json`);a(n,t)},l=async t=>{let n=(await s()).ids[t];if(n)return Ke.join(e,n)},u=async t=>{let n=(await s()).ids[t];if(!n)return;let r=Ke.join(e,n);if(W.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(W.readFileSync(r,`utf-8`))},d=async n=>{let r=n[t],i=String(r),l=_u(i,{replacement:`_`})+`.json`,u=await o();try{let t=await s();t.ids[i]=l,t.current=i;let r=Ke.join(e,l);a(r,n),await c(t)}finally{await u()}};return{async get(e){return await u(e)},async list(){if(!W.statSync(e,{throwIfNoEntry:!1}))return[];let t=await s(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=Ke.join(e,i),a=W.statSync(t,{throwIfNoEntry:!1});if(!a)continue;let o=wu(t);n.push({key:r,locked:o.locked,pid:o.pid,mtime:a.mtimeMs})}return n.sort((e,t)=>t.mtime-e.mtime),n},async lock(r,i){if(n.has(r))throw Error(`Key "${r}" is already locked in this process`);let a=await l(r);if(!a){let t=_u(r,{replacement:`_`})+`.json`,n=await o();try{let n=await s();n.ids[r]=t;let i=Ke.join(e,t);Tu(e),W.writeFileSync(i,JSON.stringify({}),`utf-8`),await c(n),a=i}finally{await n()}}if(i?.force){let e=wu(a);if(e.locked&&e.pid&&e.pid!==process.pid)try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,100))}catch(t){t.code!==`ESRCH`&&console.warn(`Failed to kill process ${e.pid}:`,t.message)}}let f=await Su(a,{stale:!0,retries:i?.force?10:5,retryInterval:(i?.force,100)});return n.set(r,()=>Promise.resolve(f())),{async get(){let e=await u(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await d(e)},async update(e){let n=await u(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await d({...n,...e})},async delete(){let t=await o();try{let t=await s(),n=t.ids[r];if(n){delete t.ids[r],t.current===r&&(t.current=void 0),await c(t);let i=Ke.join(e,n);try{W.rmSync(i,{force:!0}),Du(e)}catch{}}}finally{await t()}},async release(){try{f()}finally{n.delete(r)}}}},dispose(){n.clear()}}},Au=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,a,o,s=new Map,c=new Map,l=Ke.join(e,`index.json`),u=()=>{try{if(!W.statSync(l,{throwIfNoEntry:!1}))return{ids:{}};let e=W.readFileSync(l,`utf-8`);return{ids:JSON.parse(e).ids??{}}}catch{return{ids:{}}}},d=(e,t,n,r)=>{for(let a of i)try{a({key:e,value:t,locked:n,pid:r})}catch(e){console.error(`Error in onChange callback:`,e)}},f=(t,n,r=!1)=>{let i=Ke.join(e,n);try{let e=W.statSync(i,{throwIfNoEntry:!1}),a=c.get(n);if(!e){a&&(c.delete(n),d(t,void 0,!1));return}let o=e.mtimeMs,s=a?{locked:a.locked,pid:a.pid}:{locked:!1,pid:void 0};if((r||!a)&&(s=wu(i)),!a||a.mtime!==o||a.locked!==s.locked||a.pid!==s.pid){let e;e=!a||a.mtime!==o?JSON.parse(W.readFileSync(i,`utf-8`)):a.cachedValue,c.set(n,{mtime:o,key:t,locked:s.locked,pid:s.pid,cachedValue:e}),d(t,e,s.locked,s.pid)}}catch{}},p=()=>{try{let e=u(),t=new Set(Object.keys(e.ids));for(let[t,n]of Object.entries(e.ids))f(t,n,!0);for(let[e,n]of c.entries())t.has(n.key)||(c.delete(e),d(n.key,void 0,!1))}catch{}},m=(e,t,n=!1)=>{let i=s.get(e);i&&clearTimeout(i),s.set(e,setTimeout(()=>{s.delete(e),f(e,t,n)},r))},h=()=>{if(a)return;try{W.mkdirSync(e,{recursive:!0})}catch{}a=W.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){p();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=u(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&f(r,e,!0);return}let n=u(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&m(r,t,!1)});let t=()=>{p(),o=setTimeout(t,n)};p(),o=setTimeout(t,n)};return{onChange(e){return i.size===0&&h(),i.add(e),()=>{if(i.delete(e),i.size===0){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),c.clear()}}},dispose(){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),i.clear(),c.clear()}}};async function ju({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=Mu}){n=[...n];let a=new TransformStream,o=a.writable.getWriter(),s=async()=>{let a;try{let c=await t.chat({messages:n,id:e},{signal:r}),l=Pe({message:{id:crypto.randomUUID(),role:`assistant`,parts:[],metadata:{}},stream:c,onError:e=>{e instanceof Error&&e.name===`AbortError`||o.abort(e)}});for await(let e of l)o.write(e),a=e;if(a&&i(a)){n.push(a),await s();return}await o.close()}catch(e){if(e?.name===`AbortError`||r?.aborted)return;await o.abort(e)}finally{await o.close()}};return s().catch(e=>{o.abort(e)}),a.readable}const Mu=e=>{if(e.role!==`assistant`)return!1;let t=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),n=e.parts.slice(t+1).filter(Ne);return n.length===0||n.some(e=>P(e.output)&&e.output.outcome===`pending`)?!1:n.every(e=>e.state.startsWith(`output-`))},Nu=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function Pu(e){return typeof e==`object`&&e?.__blink_internal!==void 0}var Fu=class{chatId;agent;chatStore;serializeMessage;filterMessages;chat;loading=!1;streamingMessage;status=`idle`;queue=[];abortController;isProcessingQueue=!1;listeners=new Set;watcher;disposed=!1;constructor(e){this.chatId=e.chatId??`00000000-0000-0000-0000-000000000000`,this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.loading=!0,this.chatStore=ku(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.watcher=Au(e.chatsDirectory,{pollInterval:1e3,debounce:50}),this.watcher.onChange(e=>{if(e.key!==this.chatId||this.isProcessingQueue)return;if(!e.value){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.status=`idle`,this.streamingMessage=void 0,this.notifyListeners();return}if(this.chat.updated_at===e.value?.updated_at)return;let t=e.value,n=e.value?.error?`error`:`idle`;e.locked&&(n=`streaming`);let r=this.chat.updated_at!==t?.updated_at||this.status!==n;this.chat={...t,error:void 0},this.streamingMessage=void 0,this.status=n,r&&this.notifyListeners()}),this.chatStore.get(this.chatId).then(e=>{this.disposed||e&&(this.chat={...e,error:void 0})}).catch(e=>{this.chat.error=e instanceof Error?e.message:String(e)}).finally(()=>{this.loading=!1,this.notifyListeners()})}setAgent(e){this.agent=e}getState(){return{id:this.chatId,key:this.chat?.key,messages:(this.chat?.messages??[]).filter(e=>!Pu(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,error:this.chat?.error,loading:this.loading,queuedMessages:this.queue}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async upsertMessages(e,t){let n=!1,r;t?r=t:(r=await this.chatStore.lock(this.chatId),n=!0);try{let t=await r.get();(!t.id||!Array.isArray(t.messages))&&(t={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]});let n=[...t.messages];for(let t of e){let e;if(this.serializeMessage){let n=this.serializeMessage(t);if(n===void 0)return;e=n}else e={...t,created_at:new Date().toISOString(),mode:`run`,metadata:t.metadata,id:t.id??crypto.randomUUID()};let r=n.findIndex(t=>t.id===e.id);r===-1?n.push(e):n.splice(r,1,e)}this.chat={...t,updated_at:new Date().toISOString(),messages:n},await r.set(this.chat),this.notifyListeners()}finally{n&&await r.release()}}async deleteMessages(e){let t;try{t=await this.chatStore.lock(this.chatId);let n=await t.get();this.chat.messages=n.messages.filter(t=>!e.includes(t.id)),this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),this.notifyListeners()}finally{t&&await t.release()}}async sendMessages(e){if(this.chat.error){let e=await this.chatStore.lock(this.chatId);try{this.chat={...await e.get(),error:void 0,updated_at:new Date().toISOString()},await e.set(this.chat)}finally{await e.release()}}if(this.status=`idle`,this.notifyListeners(),this.isProcessingQueue){this.queue.push(...e),this.notifyListeners();return}this.queue=e,this.processQueueOrRun()}async start(){this.chat.error=void 0,this.status=`idle`,this.notifyListeners(),this.processQueueOrRun()}async stop(){this.status=`idle`,this.abortController?.abort(),this.notifyListeners()}async processQueueOrRun(){if(!this.agent){this.chat.error=`The agent is not available. Please wait for the build to succeed.`,this.status=`error`,this.queue=[],this.notifyListeners();return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0,this.chat.error=void 0;let e;try{e=await this.chatStore.lock(this.chatId);let t=!0;for(;this.queue.length>0||t;){t=!1;let n=new AbortController;this.abortController=n;let r=[...this.queue];this.queue=[],this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),r.length>0&&await this.upsertMessages(r,e);let i=this.chat.messages;this.filterMessages&&(i=i.filter(this.filterMessages)),i=i.map(e=>({...e,parts:e.parts.map(e=>!Ne(e)||e.input!==``?e:{...e,input:{}})}));let a=performance.now(),o=await ju({agent:this.agent,id:this.chatId,signal:n.signal,messages:i}),s=async t=>{let n=t;if(this.serializeMessage){let e=this.serializeMessage(t);if(e===void 0)return;n=e}this.chat.updated_at=new Date().toISOString(),this.chat.messages.push(n),this.streamingMessage=void 0,await e?.set(this.chat)},c=o.getReader();n.signal.addEventListener(`abort`,()=>{c.cancel().catch(()=>{})},{once:!0});let l;try{for(;;){let{done:e,value:t}=await c.read();if(e||n.signal.aborted)break;l||=performance.now()-a,this.streamingMessage&&t.id!==this.streamingMessage.id&&await s(this.streamingMessage);let r={...t,metadata:{...typeof t.metadata==`object`&&t.metadata!==null?t.metadata:{},ttft:l}};this.streamingMessage=this.serializeMessage?this.serializeMessage(r):r,this.notifyListeners()}}finally{c.releaseLock()}this.streamingMessage&&await s(this.streamingMessage)}}catch(e){this.chat.error=e instanceof Error?e.message:String(e)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,this.chat.error?this.status=`error`:this.status=`idle`,e&&(this.chat.updated_at=new Date().toISOString(),await e.set(this.chat),await e.release(),this.notifyListeners())}}stopStreaming(){this.abortController?.abort()}clearQueue(){this.queue=[],this.notifyListeners()}async resetChat(){this.abortController?.abort(),this.resetChatState(),this.notifyListeners();let e;try{e=await this.chatStore.lock(this.chatId),await e.delete()}catch{}finally{if(e)try{await e.release()}catch{}}}dispose(){this.disposed=!0,this.watcher.dispose(),this.listeners.clear(),this.abortController?.abort()}resetChatState(){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.streamingMessage=void 0,this.status=`idle`,this.queue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};function Iu(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a}=e,o=We(null),[s,c]=K({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[]});G(()=>{o.current&&o.current.dispose();let e=new Fu({chatId:t,chatsDirectory:r,serializeMessage:i,filterMessages:a}),n=e.subscribe(e=>{c(e)});return c(e.getState()),o.current=e,()=>{n(),e.dispose(),o.current=null}},[t,r]),G(()=>{o.current&&o.current.setAgent(n)},[n]);let l=He(async e=>{o.current&&await o.current.sendMessages([e])},[]),u=He(async e=>{o.current&&await o.current.upsertMessages([e])},[]),d=He(()=>{o.current&&o.current.stopStreaming()},[]),f=He(async()=>{o.current&&await o.current.resetChat()},[]),p=He(()=>{o.current&&o.current.clearQueue()},[]),m=He(async e=>{o.current&&await o.current.deleteMessages([e])},[]),h=He(async()=>{o.current&&await o.current.start()},[]);return{...s,sendMessage:l,upsertMessage:u,stopStreaming:d,resetChat:f,clearQueue:p,deleteMessage:m,start:h}}function Lu(e){return Te(e,`data`,`devhook.txt`)}function Ru(e){return De(Lu(e))}function zu(e){let t=Lu(e);if(De(t))return ke(t,`utf-8`).trim()}function Bu(e){let t=Lu(e);if(Oe(we(t),{recursive:!0}),De(t))return ke(t,`utf-8`);let n=crypto.randomUUID();return je(t,n),n}const Vu=(e,t)=>e.json({error:t},400),Hu=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}},Uu=()=>new d,Wu=Uu().get(`/:key`,async e=>{let{key:t,err:n}=Hu(e);if(n)return Vu(e,n);let r=await e.env.store.get(t);return e.json({value:r},200)}).post(`/:key`,V(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?Vu(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:Vu(t,`Value must be a string`):Vu(t,`Value is required`)}),async e=>{let{key:t,err:n}=Hu(e);if(n)return Vu(e,n);let{value:r}=e.req.valid(`json`);return await e.env.store.set(t,r),e.body(null,204)}).delete(`/:key`,async e=>{let{key:t,err:n}=Hu(e);return n?Vu(e,n):(await e.env.store.delete(t),e.body(null,204))}).get(`/`,async e=>{let{cursor:t,limit:n,prefix:r}=e.req.query(),{entries:i,cursor:a}=await e.env.store.list(r,{cursor:t?String(t):void 0,limit:n?Number(n):100});return e.json({entries:i,cursor:a})}),Gu=e=>{let t=e.req.param(`key`);return t?t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}:{key:t,err:`Key is required`}},Ku=V(`param`,e=>({id:e.id})),qu=Uu().post(`/:key`,async e=>{let{key:t,err:n}=Gu(e);return n?Vu(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,Ku,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,Ku,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.getMessages(t),200)}).post(`/:id/sendMessages`,V(`json`,e=>({id:e.id,messages:e.messages,options:e.options})),async e=>{let{id:t,messages:n,options:r}=e.req.valid(`json`);return t?(await e.env.chat.sendMessages(t,n,r),e.body(null,204)):Vu(e,`ID is required`)}).delete(`/:id/messages`,Ku,V(`query`,e=>(typeof e.message==`string`&&(e.message=[e.message]),{messages:e.message})),async e=>{let{id:t}=e.req.valid(`param`),{messages:n}=e.req.valid(`query`);return await e.env.chat.deleteMessages(t,n),e.body(null,204)}).post(`/:id/start`,Ku,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,Ku,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,Ku,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),Ju=Uu().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),Yu=new d().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,Wu).route(`/chat`,qu).route(`/otlp`,Ju);var Xu=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function Zu(e){return typeof e==`string`&&Xu.test(e)}var Qu=Zu;function $u(e){if(!Qu(e))throw TypeError(`Invalid UUID`);let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,t&255,(t=parseInt(e.slice(9,13),16))>>>8,t&255,(t=parseInt(e.slice(14,18),16))>>>8,t&255,(t=parseInt(e.slice(19,23),16))>>>8,t&255,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255)}var ed=$u;const td=[];for(let e=0;e<256;++e)td.push((e+256).toString(16).slice(1));function nd(e,t=0){return(td[e[t+0]]+td[e[t+1]]+td[e[t+2]]+td[e[t+3]]+`-`+td[e[t+4]]+td[e[t+5]]+`-`+td[e[t+6]]+td[e[t+7]]+`-`+td[e[t+8]]+td[e[t+9]]+`-`+td[e[t+10]]+td[e[t+11]]+td[e[t+12]]+td[e[t+13]]+td[e[t+14]]+td[e[t+15]]).toLowerCase()}function rd(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t}function id(e,t,n,r,i,a){let o=typeof n==`string`?rd(n):n,s=typeof r==`string`?ed(r):r;if(typeof r==`string`&&(r=ed(r)),r?.length!==16)throw TypeError(`Namespace must be array-like (16 iterable integer values, 0-255)`);let c=new Uint8Array(16+o.length);if(c.set(s),c.set(o,s.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,i){a||=0;for(let e=0;e<16;++e)i[a+e]=c[e];return i}return nd(c)}function ad(e){return Array.isArray(e)?e=Buffer.from(e):typeof e==`string`&&(e=Buffer.from(e,`utf8`)),xe(`sha1`).update(e).digest()}var od=ad;function sd(e,t,n,r){return id(80,od,e,t,n,r)}sd.DNS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,sd.URL=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;var cd=sd;function ld(e){let t=Ye(e.dataDirectory,`chats`),n={},r=Ye(e.dataDirectory,`storage.json`);W.existsSync(r)&&(n=JSON.parse(W.readFileSync(r,`utf-8`)));let i=new Map,a=n=>{let r=i.get(n);return r||(r=new Fu({chatId:n,chatsDirectory:t}),i.set(n,r)),r.setAgent(e.getAgent()),r},o={async upsert(e){let t=cd(JSON.stringify(e),cd.URL),n=a(t).getState(),r=n.messages.length===0&&!n.created_at;return{id:n.id,created:r,createdAt:n.created_at??new Date().toISOString(),key:e}},async get(e){let t=a(e).getState();return{id:t.id,createdAt:t.created_at??new Date().toISOString()}},async getMessages(e){return a(e).getState().messages},async sendMessages(e,t,n){let r=a(e),i=t.map(e=>Nu(e,`run`));if(n?.behavior===`append`){await r.upsertMessages(i);return}if(n?.behavior===`interrupt`){await r.sendMessages(i);return}await r.sendMessages(i)},async deleteMessages(e,t){await a(e).deleteMessages(t)},async start(e){await a(e).start()},async stop(e){await a(e).stop()},async delete(e){await a(e).resetChat()}},s={get(e){return Promise.resolve(n[e])},set(e,t){return n[e]=t,W.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},delete(e){return delete n[e],W.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},list(e,t){let r=Math.min(t?.limit??100,1e3),i=t?.cursor,a=Object.keys(n).filter(t=>t.startsWith(e??``)).sort(),o=0;if(i){let e=a.indexOf(i);e!==-1&&(o=e+1)}let s=a.slice(o,o+r),c=o+r<a.length?s[s.length-1]:void 0;return Promise.resolve({entries:s.map(e=>({key:e})),cursor:c})}},c=Ce(A(e=>Yu.fetch(e,{chat:o,store:s})));c.listen(e.port??0);let l=ku(t,`id`);return{url:`http://127.0.0.1:${c.address().port}`,chatsDirectory:t,getChatManager:a,listChats:()=>l.list(),dispose:()=>{for(let e of i.values())e.dispose();i.clear(),l.dispose(),c.close()}}}function ud({agent:e,capabilities:t,messages:n}){let[r,i]=K(void 0),[a,o]=K(!0),[s,c]=K(void 0),l=We(s);G(()=>{l.current=s},[s]);let[u,d]=K(()=>ee(n));G(()=>{d(e=>{let t=ee(n);return JSON.stringify(t)===JSON.stringify(e)?e:t})},[n]);let[f,p]=K(void 0),m=He((e,t)=>{if(!l.current)return!1;let n=l.current[e];return n?n.values.some(e=>e.id===t):!1},[]),h=He(e=>{p(t=>{let n={...u,...t,...e};for(let[e,t]of Object.entries(n))m(e,t)||delete n[e];for(let[e,t]of Object.entries(l.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[u,m]);G(()=>{if(!u&&!s){p(void 0);return}h()},[u,s,h]);let g=We(void 0),_=We(void 0);G(()=>{e!==_.current&&(_.current=e,c(void 0),p(void 0),i(void 0),o(!0),g.current=void 0)},[e]),G(()=>{if(t&&!t.ui||!e){c(void 0),p(void 0),i(void 0),g.current=void 0;return}let n=f?JSON.stringify(f):``;if(g.current===n){o(!1),i(void 0);return}let r=new AbortController;return o(!0),i(void 0),e.ui(f?{selectedOptions:f}:{},{signal:r.signal}).then(e=>{if(!e){c(void 0);return}r.signal.aborted||(c(t=>JSON.stringify(t)===JSON.stringify(e)?t:e),g.current=n)}).catch(e=>{r.signal.aborted||i(e instanceof Error?e:Error(String(e)))}).finally(()=>{o(!1)}),()=>{r.abort()}},[e,t,f]);let v=He((e,t)=>{h({[e]:t})},[h]);return{schema:s,options:f,setOption:v,loading:a,error:r}}var dd=o(Vc());function fd(e){let t=We(e.onRequest);G(()=>{t.current=e.onRequest},[e.onRequest]);let[n,r]=K(`disconnected`);return G(()=>{if(e.disabled||!e.id){r(`disconnected`);return}let n=!1,i,a,o=!1,s,c=Ye(e.directory,`data`,`devhook`);return(async()=>{try{s=await Su(c,{stale:!0,retries:0})}catch(e){if(e&&typeof e==`object`&&`code`in e&&e.code===`ELOCKED`){let e=``;try{let t=wu(c);t.locked&&t.pid&&(e=` (PID: ${t.pid})`)}catch{}console.error(dd.default.red(`\nError: Another ${dd.default.bold(`blink dev`)} process is already running in this directory${e}.`)),console.error(dd.default.red(`Please stop the other process and try again.
|
|
53
|
+
`)},info:e=>hl.message(e,{symbol:rl.default.blue(ll)}),success:e=>hl.message(e,{symbol:rl.default.green(ul)}),step:e=>hl.message(e,{symbol:rl.default.green(sl)}),warn:e=>hl.message(e,{symbol:rl.default.yellow(dl)}),warning:e=>hl.warn(e),error:e=>hl.message(e,{symbol:rl.default.red(fl)})};let gl;function _l(){try{return ue.statSync(`/.dockerenv`),!0}catch{return!1}}function vl(){try{return ue.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function yl(){return gl===void 0&&(gl=_l()||vl()),gl}let bl;const xl=()=>{try{return ue.statSync(`/run/.containerenv`),!0}catch{return!1}};function Sl(){return bl===void 0&&(bl=xl()||yl()),bl}const Cl=()=>{if(Xe.platform!==`linux`)return!1;if(ot.release().toLowerCase().includes(`microsoft`))return!Sl();try{return ue.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!Sl():!1}catch{return!1}};var wl=Xe.env.__IS_WSL_TEST__?Cl:Cl();const Tl=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await it.access(n,at.F_OK),r=!0}catch{}if(!r)return e;let i=await it.readFile(n,{encoding:`utf8`}),a=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(i);return a?(t=a.groups.mountPoint.trim(),t=t.endsWith(`/`)?t:`${t}/`,t):e}})(),El=async()=>`${await Tl()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Dl=async()=>wl?El():`${Xe.env.SYSTEMROOT||Xe.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function Ol(e,t,n){let r=n=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0});return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){let e=n();return r(e),e},set(e){r(e)}}),e}const kl=ye(nt);async function Al(){if(Xe.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await kl(`defaults`,[`read`,`com.apple.LaunchServices/com.apple.launchservices.secure`,`LSHandlers`]);return/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??`com.apple.Safari`}const jl=ye(nt);async function Ml(e,{humanReadableOutput:t=!0,signal:n}={}){if(Xe.platform!==`darwin`)throw Error(`macOS only`);let r=t?[]:[`-ss`],i={};n&&(i.signal=n);let{stdout:a}=await jl(`osascript`,[`-e`,e,r],i);return a.trim()}async function Nl(e){return Ml(`tell application "Finder" to set app_path to application file id "${e}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}const Pl=ye(nt),Fl={AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:`Edge`,id:`com.microsoft.edge.old`},MSEdgeDHTML:{name:`Edge`,id:`com.microsoft.edge`},MSEdgeHTM:{name:`Edge`,id:`com.microsoft.edge`},"IE.HTTP":{name:`Internet Explorer`,id:`com.microsoft.ie`},FirefoxURL:{name:`Firefox`,id:`org.mozilla.firefox`},ChromeHTML:{name:`Chrome`,id:`com.google.chrome`},BraveHTML:{name:`Brave`,id:`com.brave.Browser`},BraveBHTML:{name:`Brave Beta`,id:`com.brave.Browser.beta`},BraveSSHTM:{name:`Brave Nightly`,id:`com.brave.Browser.nightly`}};var Il=class extends Error{};async function Ll(e=Pl){let{stdout:t}=await e(`reg`,[`QUERY`,` HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice`,`/v`,`ProgId`]),n=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(t);if(!n)throw new Il(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=Fl[r];if(!i)throw new Il(`Unknown browser ID: ${r}`);return i}const Rl=ye(nt),zl=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function Bl(){if(Xe.platform===`darwin`){let e=await Al();return{name:await Nl(e),id:e}}if(Xe.platform===`linux`){let{stdout:e}=await Rl(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:zl(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(Xe.platform===`win32`)return Ll();throw Error(`Only macOS, Linux, and Windows are supported`)}const Vl=ye(tt.execFile),Hl=qe.dirname(_e(import.meta.url)),Ul=qe.join(Hl,`xdg-open`),{platform:Wl,arch:Gl}=Xe;async function Kl(){let e=await Dl(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=le.from(t,`utf16le`).toString(`base64`),{stdout:r}=await Vl(e,[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,n],{encoding:`utf8`}),i=r.trim(),a={ChromeHTML:`com.google.chrome`,BraveHTML:`com.brave.Browser`,MSEdgeHTM:`com.microsoft.edge`,FirefoxURL:`org.mozilla.firefox`};return a[i]?{id:a[i]}:{}}const ql=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},Jl=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return ql(e.app,t=>Jl({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return ql(t,t=>Jl({...e,app:{name:t,arguments:n}}));if(t===`browser`||t===`browserPrivate`){let r={"com.google.chrome":`chrome`,"google-chrome.desktop":`chrome`,"com.brave.Browser":`brave`,"org.mozilla.firefox":`firefox`,"firefox.desktop":`firefox`,"com.microsoft.msedge":`edge`,"com.microsoft.edge":`edge`,"com.microsoft.edgemac":`edge`,"microsoft-edge.desktop":`edge`},i={chrome:`--incognito`,brave:`--incognito`,firefox:`--private-window`,edge:`--inPrivate`},a=wl?await Kl():await Bl();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),Jl({...e,app:{name:Ql[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,i=[],a={};if(Wl===`darwin`)r=`open`,e.wait&&i.push(`--wait-apps`),e.background&&i.push(`--background`),e.newInstance&&i.push(`--new`),t&&i.push(`-a`,t);else if(Wl===`win32`||wl&&!Sl()&&!t){r=await Dl(),i.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),wl||(a.windowsVerbatimArguments=!0);let o=[`Start`];e.wait&&o.push(`-Wait`),t?(o.push(`"\`"${t}\`""`),e.target&&n.push(e.target)):e.target&&o.push(`"${e.target}"`),n.length>0&&(n=n.map(e=>`"\`"${e}\`""`),o.push(`-ArgumentList`,n.join(`,`))),e.target=le.from(o.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!Hl||Hl===`/`,t=!1;try{await it.access(Ul,at.X_OK),t=!0}catch{}r=Xe.versions.electron??(Wl===`android`||e||!t)?`xdg-open`:Ul}n.length>0&&i.push(...n),e.wait||(a.stdio=`ignore`,a.detached=!0)}Wl===`darwin`&&n.length>0&&i.push(`--args`,...n),e.target&&i.push(e.target);let o=tt.spawn(r,i,a);return e.wait?new Promise((t,n)=>{o.once(`error`,n),o.once(`close`,r=>{if(!e.allowNonzeroExitCode&&r>0){n(Error(`Exited with code ${r}`));return}t(o)})}):(o.unref(),o)},Yl=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return Jl({...t,target:e})};function Xl(e){if(typeof e==`string`||Array.isArray(e))return e;let{[Gl]:t}=e;if(!t)throw Error(`${Gl} is not supported`);return t}function Zl({[Wl]:e},{wsl:t}){if(t&&wl)return Xl(t);if(!e)throw Error(`${Wl} is not supported`);return Xl(e)}const Ql={};Ol(Ql,`chrome`,()=>Zl({darwin:`google chrome`,win32:`chrome`,linux:[`google-chrome`,`google-chrome-stable`,`chromium`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`,x64:[`/mnt/c/Program Files/Google/Chrome/Application/chrome.exe`,`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`]}})),Ol(Ql,`brave`,()=>Zl({darwin:`brave browser`,win32:`brave`,linux:[`brave-browser`,`brave`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`,x64:[`/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe`,`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`]}})),Ol(Ql,`firefox`,()=>Zl({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),Ol(Ql,`edge`,()=>Zl({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),Ol(Ql,`browser`,()=>`browser`),Ol(Ql,`browserPrivate`,()=>`browserPrivate`);var $l=Yl;function eu(e){let t=e||ru();if(fe(t)){let e=me(t,`utf8`);return JSON.parse(e).token}}function tu(e,t){let n=t||ru();fe(Je(n))||pe(Je(n),{recursive:!0}),ge(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function nu(e){let t=e||ru();fe(t)&&he(t)}function ru(){let e=Mc(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return Ye(e[0],`auth.json`)}function iu(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=K(),[s,c]=K(()=>eu(i)),[l,u]=K(),d=We(n),f=We(r);G(()=>{d.current=n,f.current=r},[n,r]);let p=He(async()=>{u(void 0);try{let e=eu(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new mc({baseURL:`https://blink.so`});t.authToken=e;let n={email:(await t.users.me()).email};o(n),d.current?.(n)}catch(e){o(void 0),u(e instanceof Error?e.message:String(e)),d.current?.(void 0)}},[i]),m=He(async()=>{u(void 0);try{let e=new mc,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();tu(t,i),c(t);let r={email:n.email};return o(r),d.current?.(r),r}catch(e){let t=e instanceof Error?e.message:String(e);throw u(t),e}},[i]),h=He(()=>{nu(i),c(void 0),o(void 0),u(void 0),d.current?.(void 0)},[i]);return G(()=>{t&&p()},[t,p]),{user:a,token:s,error:l,login:m,logout:h}}function au(e){let{directory:t,onBuildStart:n,onBuildSuccess:r,onBuildError:i}=typeof e==`string`?{directory:e}:e,a=Ue(()=>se(t),[t]),[o,s]=K(void 0),[c,l]=K(void 0),[u,d]=K(`building`),f=We(n),p=We(r),m=We(i);return G(()=>{f.current=n,p.current=r,m.current=i},[n,r,i]),G(()=>{let e=new AbortController;return a.build({cwd:t,entry:a.entry,outdir:a.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{d(`building`),s(void 0),l(void 0),f.current?.()},onResult:e=>{`error`in e?(s(e.error),d(`error`),m.current?.(e.error)):(l(e),d(`success`),p.current?.(e))}}).catch(e=>{console.log(`error`,e),d(`error`),s(e),m.current?.(e)}),()=>{e.abort()}},[t]),Ue(()=>({error:o,status:u,result:c,entry:a.entry,outdir:a.outdir}),[o,u,c,a.entry,a.outdir])}function ou(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function su(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const cu=/^\.+(\\|\/)|^\.+$/,lu=/[. ]+$/,uu=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,du=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,fu=e=>e===``,pu=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,mu=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let hu;function gu(){return hu??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),hu}function _u(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(ou().test(n)||[...n].some(e=>du.test(e)&&!fu(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(mu,` `),n.length>0&&(e=e.replaceAll(pu,`$1`)),e=e.replace(lu,``),e=e.replace(cu,n),e=e.replace(ou(),n),e=e.replaceAll(uu,e=>fu(e)?e:n),e.length===0&&(e=n),e=su().test(e)?e+n:e;let r=typeof t.maxLength==`number`?t.maxLength:100;if(e.length>r){let t=e.lastIndexOf(`.`);if(t===-1)e=vu(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=vu(n,a)+i}}return e}function vu(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of gu().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function yu(e){return`${e}.lock`}function bu(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function xu(e,t={}){let n=yu(e),r=process.pid.toString();try{return W.writeFileSync(n,r,{flag:`wx`}),!0}catch(r){if(r.code!==`EEXIST`)throw r;if(t.stale===0)return!1;let i;try{i=parseInt(W.readFileSync(n,`utf8`),10)}catch{return W.unlinkSync(n),xu(e,{...t,stale:0})}if(!bu(i))try{return W.unlinkSync(n),xu(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return xu(e,{...t,stale:0});throw n}return!1}}async function Su(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=Ke.resolve(e),i=0;for(;i<=n.retries;){if(xu(r,n))return()=>Cu(r);i<n.retries&&await new Promise(e=>setTimeout(e,n.retryInterval)),i++}let a=Error(`Lock file is already being held`);throw a.code=`ELOCKED`,a.file=r,a}function Cu(e){let t=Ke.resolve(e),n=yu(t);try{if(parseInt(W.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}W.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function wu(e){let t=Ke.resolve(e),n=yu(t);try{if(!W.existsSync(n))return{locked:!1};let e=W.readFileSync(n,`utf8`),t=parseInt(e,10);return bu(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const Tu=e=>{W.mkdirSync(e,{recursive:!0})},Eu=e=>{try{W.fdatasyncSync(e)}catch{}try{W.closeSync(e)}catch{}},Du=e=>{try{let t=W.openSync(e,`r`);try{W.fsyncSync(t)}finally{W.closeSync(t)}}catch{}},Ou=(e,t)=>{let n=Ke.dirname(e);Tu(n);let r=Ke.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=W.openSync(r,`w`),W.writeFileSync(i,t,`utf-8`),Eu(i),i=void 0,W.renameSync(r,e),Du(e),Du(n)}catch(e){if(i!==void 0)try{W.closeSync(i)}catch{}try{W.rmSync(r,{force:!0})}catch{}throw e}},ku=(e,t)=>{let n=new Map,r,i=e=>{if(W.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(W.readFileSync(e,`utf-8`))},a=(e,t)=>{Ou(e,JSON.stringify(t,null,2))},o=async()=>{if(r)throw Error(`Index is already locked`);let t=Ke.join(e,`index.json`);Tu(e),W.existsSync(t)||W.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await Su(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},s=async()=>{let t=Ke.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},c=async t=>{let n=Ke.join(e,`index.json`);a(n,t)},l=async t=>{let n=(await s()).ids[t];if(n)return Ke.join(e,n)},u=async t=>{let n=(await s()).ids[t];if(!n)return;let r=Ke.join(e,n);if(W.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(W.readFileSync(r,`utf-8`))},d=async n=>{let r=n[t],i=String(r),l=_u(i,{replacement:`_`})+`.json`,u=await o();try{let t=await s();t.ids[i]=l,t.current=i;let r=Ke.join(e,l);a(r,n),await c(t)}finally{await u()}};return{async get(e){return await u(e)},async list(){if(!W.statSync(e,{throwIfNoEntry:!1}))return[];let t=await s(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=Ke.join(e,i),a=W.statSync(t,{throwIfNoEntry:!1});if(!a)continue;let o=wu(t);n.push({key:r,locked:o.locked,pid:o.pid,mtime:a.mtimeMs})}return n.sort((e,t)=>t.mtime-e.mtime),n},async lock(r,i){if(n.has(r))throw Error(`Key "${r}" is already locked in this process`);let a=await l(r);if(!a){let t=_u(r,{replacement:`_`})+`.json`,n=await o();try{let n=await s();n.ids[r]=t;let i=Ke.join(e,t);Tu(e),W.writeFileSync(i,JSON.stringify({}),`utf-8`),await c(n),a=i}finally{await n()}}if(i?.force){let e=wu(a);if(e.locked&&e.pid&&e.pid!==process.pid)try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,100))}catch(t){t.code!==`ESRCH`&&console.warn(`Failed to kill process ${e.pid}:`,t.message)}}let f=await Su(a,{stale:!0,retries:i?.force?10:5,retryInterval:(i?.force,100)});return n.set(r,()=>Promise.resolve(f())),{async get(){let e=await u(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await d(e)},async update(e){let n=await u(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await d({...n,...e})},async delete(){let t=await o();try{let t=await s(),n=t.ids[r];if(n){delete t.ids[r],t.current===r&&(t.current=void 0),await c(t);let i=Ke.join(e,n);try{W.rmSync(i,{force:!0}),Du(e)}catch{}}}finally{await t()}},async release(){try{f()}finally{n.delete(r)}}}},dispose(){n.clear()}}},Au=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,a,o,s=new Map,c=new Map,l=Ke.join(e,`index.json`),u=()=>{try{if(!W.statSync(l,{throwIfNoEntry:!1}))return{ids:{}};let e=W.readFileSync(l,`utf-8`);return{ids:JSON.parse(e).ids??{}}}catch{return{ids:{}}}},d=(e,t,n,r)=>{for(let a of i)try{a({key:e,value:t,locked:n,pid:r})}catch(e){console.error(`Error in onChange callback:`,e)}},f=(t,n,r=!1)=>{let i=Ke.join(e,n);try{let e=W.statSync(i,{throwIfNoEntry:!1}),a=c.get(n);if(!e){a&&(c.delete(n),d(t,void 0,!1));return}let o=e.mtimeMs,s=a?{locked:a.locked,pid:a.pid}:{locked:!1,pid:void 0};if((r||!a)&&(s=wu(i)),!a||a.mtime!==o||a.locked!==s.locked||a.pid!==s.pid){let e;e=!a||a.mtime!==o?JSON.parse(W.readFileSync(i,`utf-8`)):a.cachedValue,c.set(n,{mtime:o,key:t,locked:s.locked,pid:s.pid,cachedValue:e}),d(t,e,s.locked,s.pid)}}catch{}},p=()=>{try{let e=u(),t=new Set(Object.keys(e.ids));for(let[t,n]of Object.entries(e.ids))f(t,n,!0);for(let[e,n]of c.entries())t.has(n.key)||(c.delete(e),d(n.key,void 0,!1))}catch{}},m=(e,t,n=!1)=>{let i=s.get(e);i&&clearTimeout(i),s.set(e,setTimeout(()=>{s.delete(e),f(e,t,n)},r))},h=()=>{if(a)return;try{W.mkdirSync(e,{recursive:!0})}catch{}a=W.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){p();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=u(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&f(r,e,!0);return}let n=u(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&m(r,t,!1)});let t=()=>{p(),o=setTimeout(t,n)};p(),o=setTimeout(t,n)};return{onChange(e){return i.size===0&&h(),i.add(e),()=>{if(i.delete(e),i.size===0){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),c.clear()}}},dispose(){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),i.clear(),c.clear()}}};async function ju({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=Mu}){n=[...n];let a=new TransformStream,o=a.writable.getWriter(),s=async()=>{let a;try{let c=await t.chat({messages:n,id:e},{signal:r}),l=Pe({message:{id:crypto.randomUUID(),role:`assistant`,parts:[],metadata:{}},stream:c,onError:e=>{e instanceof Error&&e.name===`AbortError`||o.abort(e)}});for await(let e of l)o.write(e),a=e;if(a&&i(a)){n.push(a),await s();return}await o.close()}catch(e){if(e?.name===`AbortError`||r?.aborted)return;await o.abort(e)}finally{await o.close()}};return s().catch(e=>{o.abort(e)}),a.readable}const Mu=e=>{if(e.role!==`assistant`)return!1;let t=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),n=e.parts.slice(t+1).filter(Ne);return n.length===0||n.some(e=>ee(e.output)&&e.output.outcome===`pending`)?!1:n.every(e=>e.state.startsWith(`output-`))},Nu=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function Pu(e){return typeof e==`object`&&e?.__blink_internal!==void 0}var Fu=class{chatId;agent;chatStore;serializeMessage;filterMessages;chat;loading=!1;streamingMessage;status=`idle`;queue=[];abortController;isProcessingQueue=!1;listeners=new Set;watcher;disposed=!1;constructor(e){this.chatId=e.chatId??`00000000-0000-0000-0000-000000000000`,this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.loading=!0,this.chatStore=ku(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.watcher=Au(e.chatsDirectory,{pollInterval:1e3,debounce:50}),this.watcher.onChange(e=>{if(e.key!==this.chatId||this.isProcessingQueue)return;if(!e.value){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.status=`idle`,this.streamingMessage=void 0,this.notifyListeners();return}if(this.chat.updated_at===e.value?.updated_at)return;let t=e.value,n=e.value?.error?`error`:`idle`;e.locked&&(n=`streaming`);let r=this.chat.updated_at!==t?.updated_at||this.status!==n;this.chat={...t,error:void 0},this.streamingMessage=void 0,this.status=n,r&&this.notifyListeners()}),this.chatStore.get(this.chatId).then(e=>{this.disposed||e&&(this.chat={...e,error:void 0})}).catch(e=>{this.chat.error=e instanceof Error?e.message:String(e)}).finally(()=>{this.loading=!1,this.notifyListeners()})}setAgent(e){this.agent=e}getState(){return{id:this.chatId,key:this.chat?.key,messages:(this.chat?.messages??[]).filter(e=>!Pu(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,error:this.chat?.error,loading:this.loading,queuedMessages:this.queue}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async upsertMessages(e,t){let n=!1,r;t?r=t:(r=await this.chatStore.lock(this.chatId),n=!0);try{let t=await r.get();(!t.id||!Array.isArray(t.messages))&&(t={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]});let n=[...t.messages];for(let t of e){let e;if(this.serializeMessage){let n=this.serializeMessage(t);if(n===void 0)return;e=n}else e={...t,created_at:new Date().toISOString(),mode:`run`,metadata:t.metadata,id:t.id??crypto.randomUUID()};let r=n.findIndex(t=>t.id===e.id);r===-1?n.push(e):n.splice(r,1,e)}this.chat={...t,updated_at:new Date().toISOString(),messages:n},await r.set(this.chat),this.notifyListeners()}finally{n&&await r.release()}}async deleteMessages(e){let t;try{t=await this.chatStore.lock(this.chatId);let n=await t.get();this.chat.messages=n.messages.filter(t=>!e.includes(t.id)),this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),this.notifyListeners()}finally{t&&await t.release()}}async sendMessages(e){if(this.chat.error){let e=await this.chatStore.lock(this.chatId);try{this.chat={...await e.get(),error:void 0,updated_at:new Date().toISOString()},await e.set(this.chat)}finally{await e.release()}}if(this.status=`idle`,this.notifyListeners(),this.isProcessingQueue){this.queue.push(...e),this.notifyListeners();return}this.queue=e,this.processQueueOrRun()}async start(){this.chat.error=void 0,this.status=`idle`,this.notifyListeners(),this.processQueueOrRun()}async stop(){this.status=`idle`,this.abortController?.abort(),this.notifyListeners()}async processQueueOrRun(){if(!this.agent){this.chat.error=`The agent is not available. Please wait for the build to succeed.`,this.status=`error`,this.queue=[],this.notifyListeners();return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0,this.chat.error=void 0;let e;try{e=await this.chatStore.lock(this.chatId);let t=!0;for(;this.queue.length>0||t;){t=!1;let n=new AbortController;this.abortController=n;let r=[...this.queue];this.queue=[],this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),r.length>0&&await this.upsertMessages(r,e);let i=this.chat.messages;this.filterMessages&&(i=i.filter(this.filterMessages)),i=i.map(e=>({...e,parts:e.parts.map(e=>!Ne(e)||e.input!==``?e:{...e,input:{}})}));let a=performance.now(),o=await ju({agent:this.agent,id:this.chatId,signal:n.signal,messages:i}),s=async t=>{let n=t;if(this.serializeMessage){let e=this.serializeMessage(t);if(e===void 0)return;n=e}this.chat.updated_at=new Date().toISOString(),this.chat.messages.push(n),this.streamingMessage=void 0,await e?.set(this.chat)},c=o.getReader();n.signal.addEventListener(`abort`,()=>{c.cancel().catch(()=>{})},{once:!0});let l;try{for(;;){let{done:e,value:t}=await c.read();if(e||n.signal.aborted)break;l||=performance.now()-a,this.streamingMessage&&t.id!==this.streamingMessage.id&&await s(this.streamingMessage);let r={...t,metadata:{...typeof t.metadata==`object`&&t.metadata!==null?t.metadata:{},ttft:l}};this.streamingMessage=this.serializeMessage?this.serializeMessage(r):r,this.notifyListeners()}}finally{c.releaseLock()}this.streamingMessage&&await s(this.streamingMessage)}}catch(e){this.chat.error=e instanceof Error?e.message:String(e)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,this.chat.error?this.status=`error`:this.status=`idle`,e&&(this.chat.updated_at=new Date().toISOString(),await e.set(this.chat),await e.release(),this.notifyListeners())}}stopStreaming(){this.abortController?.abort()}clearQueue(){this.queue=[],this.notifyListeners()}async resetChat(){this.abortController?.abort(),this.resetChatState(),this.notifyListeners();let e;try{e=await this.chatStore.lock(this.chatId),await e.delete()}catch{}finally{if(e)try{await e.release()}catch{}}}dispose(){this.disposed=!0,this.watcher.dispose(),this.listeners.clear(),this.abortController?.abort()}resetChatState(){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.streamingMessage=void 0,this.status=`idle`,this.queue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};function Iu(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a}=e,o=We(null),[s,c]=K({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[]});G(()=>{o.current&&o.current.dispose();let e=new Fu({chatId:t,chatsDirectory:r,serializeMessage:i,filterMessages:a}),n=e.subscribe(e=>{c(e)});return c(e.getState()),o.current=e,()=>{n(),e.dispose(),o.current=null}},[t,r]),G(()=>{o.current&&o.current.setAgent(n)},[n]);let l=He(async e=>{o.current&&await o.current.sendMessages([e])},[]),u=He(async e=>{o.current&&await o.current.upsertMessages([e])},[]),d=He(()=>{o.current&&o.current.stopStreaming()},[]),f=He(async()=>{o.current&&await o.current.resetChat()},[]),p=He(()=>{o.current&&o.current.clearQueue()},[]),m=He(async e=>{o.current&&await o.current.deleteMessages([e])},[]),h=He(async()=>{o.current&&await o.current.start()},[]);return{...s,sendMessage:l,upsertMessage:u,stopStreaming:d,resetChat:f,clearQueue:p,deleteMessage:m,start:h}}function Lu(e){return Te(e,`data`,`devhook.txt`)}function Ru(e){return De(Lu(e))}function zu(e){let t=Lu(e);if(De(t))return ke(t,`utf-8`).trim()}function Bu(e){let t=Lu(e);if(Oe(we(t),{recursive:!0}),De(t))return ke(t,`utf-8`);let n=crypto.randomUUID();return je(t,n),n}const Vu=(e,t)=>e.json({error:t},400),Hu=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}},Uu=()=>new d,Wu=Uu().get(`/:key`,async e=>{let{key:t,err:n}=Hu(e);if(n)return Vu(e,n);let r=await e.env.store.get(t);return e.json({value:r},200)}).post(`/:key`,V(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?Vu(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:Vu(t,`Value must be a string`):Vu(t,`Value is required`)}),async e=>{let{key:t,err:n}=Hu(e);if(n)return Vu(e,n);let{value:r}=e.req.valid(`json`);return await e.env.store.set(t,r),e.body(null,204)}).delete(`/:key`,async e=>{let{key:t,err:n}=Hu(e);return n?Vu(e,n):(await e.env.store.delete(t),e.body(null,204))}).get(`/`,async e=>{let{cursor:t,limit:n,prefix:r}=e.req.query(),{entries:i,cursor:a}=await e.env.store.list(r,{cursor:t?String(t):void 0,limit:n?Number(n):100});return e.json({entries:i,cursor:a})}),Gu=e=>{let t=e.req.param(`key`);return t?t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}:{key:t,err:`Key is required`}},Ku=V(`param`,e=>({id:e.id})),qu=Uu().post(`/:key`,async e=>{let{key:t,err:n}=Gu(e);return n?Vu(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,Ku,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,Ku,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.getMessages(t),200)}).post(`/:id/sendMessages`,V(`json`,e=>({id:e.id,messages:e.messages,options:e.options})),async e=>{let{id:t,messages:n,options:r}=e.req.valid(`json`);return t?(await e.env.chat.sendMessages(t,n,r),e.body(null,204)):Vu(e,`ID is required`)}).delete(`/:id/messages`,Ku,V(`query`,e=>(typeof e.message==`string`&&(e.message=[e.message]),{messages:e.message})),async e=>{let{id:t}=e.req.valid(`param`),{messages:n}=e.req.valid(`query`);return await e.env.chat.deleteMessages(t,n),e.body(null,204)}).post(`/:id/start`,Ku,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,Ku,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,Ku,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),Ju=Uu().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),Yu=new d().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,Wu).route(`/chat`,qu).route(`/otlp`,Ju);var Xu=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function Zu(e){return typeof e==`string`&&Xu.test(e)}var Qu=Zu;function $u(e){if(!Qu(e))throw TypeError(`Invalid UUID`);let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,t&255,(t=parseInt(e.slice(9,13),16))>>>8,t&255,(t=parseInt(e.slice(14,18),16))>>>8,t&255,(t=parseInt(e.slice(19,23),16))>>>8,t&255,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255)}var ed=$u;const td=[];for(let e=0;e<256;++e)td.push((e+256).toString(16).slice(1));function nd(e,t=0){return(td[e[t+0]]+td[e[t+1]]+td[e[t+2]]+td[e[t+3]]+`-`+td[e[t+4]]+td[e[t+5]]+`-`+td[e[t+6]]+td[e[t+7]]+`-`+td[e[t+8]]+td[e[t+9]]+`-`+td[e[t+10]]+td[e[t+11]]+td[e[t+12]]+td[e[t+13]]+td[e[t+14]]+td[e[t+15]]).toLowerCase()}function rd(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t}function id(e,t,n,r,i,a){let o=typeof n==`string`?rd(n):n,s=typeof r==`string`?ed(r):r;if(typeof r==`string`&&(r=ed(r)),r?.length!==16)throw TypeError(`Namespace must be array-like (16 iterable integer values, 0-255)`);let c=new Uint8Array(16+o.length);if(c.set(s),c.set(o,s.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,i){a||=0;for(let e=0;e<16;++e)i[a+e]=c[e];return i}return nd(c)}function ad(e){return Array.isArray(e)?e=Buffer.from(e):typeof e==`string`&&(e=Buffer.from(e,`utf8`)),xe(`sha1`).update(e).digest()}var od=ad;function sd(e,t,n,r){return id(80,od,e,t,n,r)}sd.DNS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,sd.URL=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;var cd=sd;function ld(e){let t=Ye(e.dataDirectory,`chats`),n={},r=Ye(e.dataDirectory,`storage.json`);W.existsSync(r)&&(n=JSON.parse(W.readFileSync(r,`utf-8`)));let i=new Map,a=n=>{let r=i.get(n);return r||(r=new Fu({chatId:n,chatsDirectory:t}),i.set(n,r)),r.setAgent(e.getAgent()),r},o={async upsert(e){let t=cd(JSON.stringify(e),cd.URL),n=a(t).getState(),r=n.messages.length===0&&!n.created_at;return{id:n.id,created:r,createdAt:n.created_at??new Date().toISOString(),key:e}},async get(e){let t=a(e).getState();return{id:t.id,createdAt:t.created_at??new Date().toISOString()}},async getMessages(e){return a(e).getState().messages},async sendMessages(e,t,n){let r=a(e),i=t.map(e=>Nu(e,`run`));if(n?.behavior===`append`){await r.upsertMessages(i);return}if(n?.behavior===`interrupt`){await r.sendMessages(i);return}await r.sendMessages(i)},async deleteMessages(e,t){await a(e).deleteMessages(t)},async start(e){await a(e).start()},async stop(e){await a(e).stop()},async delete(e){await a(e).resetChat()}},s={get(e){return Promise.resolve(n[e])},set(e,t){return n[e]=t,W.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},delete(e){return delete n[e],W.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},list(e,t){let r=Math.min(t?.limit??100,1e3),i=t?.cursor,a=Object.keys(n).filter(t=>t.startsWith(e??``)).sort(),o=0;if(i){let e=a.indexOf(i);e!==-1&&(o=e+1)}let s=a.slice(o,o+r),c=o+r<a.length?s[s.length-1]:void 0;return Promise.resolve({entries:s.map(e=>({key:e})),cursor:c})}},c=Ce(j(e=>Yu.fetch(e,{chat:o,store:s})));c.listen(e.port??0);let l=ku(t,`id`);return{url:`http://127.0.0.1:${c.address().port}`,chatsDirectory:t,getChatManager:a,listChats:()=>l.list(),dispose:()=>{for(let e of i.values())e.dispose();i.clear(),l.dispose(),c.close()}}}function ud({agent:e,capabilities:t,messages:n}){let[r,i]=K(void 0),[a,o]=K(!0),[s,c]=K(void 0),l=We(s);G(()=>{l.current=s},[s]);let[u,d]=K(()=>te(n));G(()=>{d(e=>{let t=te(n);return JSON.stringify(t)===JSON.stringify(e)?e:t})},[n]);let[f,p]=K(void 0),m=He((e,t)=>{if(!l.current)return!1;let n=l.current[e];return n?n.values.some(e=>e.id===t):!1},[]),h=He(e=>{p(t=>{let n={...u,...t,...e};for(let[e,t]of Object.entries(n))m(e,t)||delete n[e];for(let[e,t]of Object.entries(l.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[u,m]);G(()=>{if(!u&&!s){p(void 0);return}h()},[u,s,h]);let g=We(void 0),_=We(void 0);G(()=>{e!==_.current&&(_.current=e,c(void 0),p(void 0),i(void 0),o(!0),g.current=void 0)},[e]),G(()=>{if(t&&!t.ui||!e){c(void 0),p(void 0),i(void 0),g.current=void 0;return}let n=f?JSON.stringify(f):``;if(g.current===n){o(!1),i(void 0);return}let r=new AbortController;return o(!0),i(void 0),e.ui(f?{selectedOptions:f}:{},{signal:r.signal}).then(e=>{if(!e){c(void 0);return}r.signal.aborted||(c(t=>JSON.stringify(t)===JSON.stringify(e)?t:e),g.current=n)}).catch(e=>{r.signal.aborted||i(e instanceof Error?e:Error(String(e)))}).finally(()=>{o(!1)}),()=>{r.abort()}},[e,t,f]);let v=He((e,t)=>{h({[e]:t})},[h]);return{schema:s,options:f,setOption:v,loading:a,error:r}}var dd=o(Vc());function fd(e){let t=We(e.onRequest);G(()=>{t.current=e.onRequest},[e.onRequest]);let[n,r]=K(`disconnected`);return G(()=>{if(e.disabled||!e.id){r(`disconnected`);return}let n=!1,i,a,o=!1,s,c=Ye(e.directory,`data`,`devhook`);return(async()=>{try{s=await Su(c,{stale:!0,retries:0})}catch(e){if(e&&typeof e==`object`&&`code`in e&&e.code===`ELOCKED`){let e=``;try{let t=wu(c);t.locked&&t.pid&&(e=` (PID: ${t.pid})`)}catch{}console.error(dd.default.red(`\nError: Another ${dd.default.bold(`blink dev`)} process is already running in this directory${e}.`)),console.error(dd.default.red(`Please stop the other process and try again.
|
|
54
54
|
`)),process.exit(1)}let t=e&&typeof e==`object`&&`message`in e?String(e.message):String(e);console.warn(dd.default.yellow(`\nWarning: Failed to acquire devhook lock: ${t}`)),console.warn(dd.default.yellow(`Continuing without lock. Multiple ${dd.default.bold(`blink dev`)} processes may conflict with each other.\n`))}let l=()=>{if(!(n||o)){if(o=!0,i){try{i.dispose()}catch{}i=void 0}i=new mc({baseURL:`https://blink.so`}).devhook.listen({id:e.id,onRequest:async e=>t.current(e),onConnect:()=>{o=!1,r(`connected`)},onDisconnect:()=>{o=!1,r(`disconnected`),!n&&!a&&(a=setTimeout(()=>{a=void 0,l()},2e3))},onError:e=>{o=!1,r(`error`),!n&&!a&&(a=setTimeout(()=>{a=void 0,l()},2e3))}})}};l()})(),()=>{if(n=!0,a&&=(clearTimeout(a),void 0),i){try{i.dispose()}catch{}i=void 0}if(s)try{s()}catch(e){console.warn(`Failed to release devhook lock:`,e)}}},[e.disabled,e.directory]),{id:e.id,url:e.id?`https://${e.id}.blink.host`:void 0,status:n}}var pd=e(((e,t)=>{t.exports={name:`dotenv`,version:`17.2.3`,description:`Loads environment variables from .env file`,main:`lib/main.js`,types:`lib/main.d.ts`,exports:{".":{types:`./lib/main.d.ts`,require:`./lib/main.js`,default:`./lib/main.js`},"./config":`./config.js`,"./config.js":`./config.js`,"./lib/env-options":`./lib/env-options.js`,"./lib/env-options.js":`./lib/env-options.js`,"./lib/cli-options":`./lib/cli-options.js`,"./lib/cli-options.js":`./lib/cli-options.js`,"./package.json":`./package.json`},scripts:{"dts-check":`tsc --project tests/types/tsconfig.json`,lint:`standard`,pretest:`npm run lint && npm run dts-check`,test:`tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000`,"test:coverage":`tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov`,prerelease:`npm test`,release:`standard-version`},repository:{type:`git`,url:`git://github.com/motdotla/dotenv.git`},homepage:`https://github.com/motdotla/dotenv#readme`,funding:`https://dotenvx.com`,keywords:[`dotenv`,`env`,`.env`,`environment`,`variables`,`config`,`settings`],readmeFilename:`README.md`,license:`BSD-2-Clause`,devDependencies:{"@types/node":`^18.11.3`,decache:`^4.6.2`,sinon:`^14.0.1`,standard:`^17.0.0`,"standard-version":`^9.5.0`,tap:`^19.2.0`,typescript:`^4.8.4`},engines:{node:`>=12`},browser:{fs:!1}}})),md=o(e(((e,t)=>{let n=i(`fs`),r=i(`path`),a=i(`os`),o=i(`crypto`),s=pd().version,c=[`🔐 encrypt with Dotenvx: https://dotenvx.com`,`🔐 prevent committing .env to code: https://dotenvx.com/precommit`,`🔐 prevent building .env in docker: https://dotenvx.com/prebuild`,`📡 add observability to secrets: https://dotenvx.com/ops`,`👥 sync secrets across teammates & machines: https://dotenvx.com/ops`,`🗂️ backup and recover secrets: https://dotenvx.com/ops`,`✅ audit secrets and track compliance: https://dotenvx.com/ops`,`🔄 add secrets lifecycle management: https://dotenvx.com/ops`,`🔑 add access controls to secrets: https://dotenvx.com/ops`,"🛠️ run anywhere with `dotenvx run -- yourcommand`",`⚙️ specify custom .env file path with { path: '/custom/path/.env' }`,`⚙️ enable debug logging with { debug: true }`,`⚙️ override existing env vars with { override: true }`,`⚙️ suppress all logs with { quiet: true }`,`⚙️ write to custom object with { processEnv: myObject }`,`⚙️ load multiple .env files with { path: ['.env.local', '.env'] }`];function l(){return c[Math.floor(Math.random()*c.length)]}function u(e){return typeof e==`string`?![`false`,`0`,`no`,`off`,``].includes(e.toLowerCase()):!!e}function d(){return process.stdout.isTTY}function f(e){return d()?`\x1b[2m${e}\x1b[0m`:e}let p=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function m(e){let t={},n=e.toString();n=n.replace(/\r\n?/gm,`
|
|
55
55
|
`);let r;for(;(r=p.exec(n))!=null;){let e=r[1],n=r[2]||``;n=n.trim();let i=n[0];n=n.replace(/^(['"`])([\s\S]*)\1$/gm,`$2`),i===`"`&&(n=n.replace(/\\n/g,`
|
|
56
56
|
`),n=n.replace(/\\r/g,`\r`)),t[e]=n}return t}function h(e){e||={};let t=x(e);e.path=t;let n=O.configDotenv(e);if(!n.parsed){let e=Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code=`MISSING_DATA`,e}let r=y(e).split(`,`),i=r.length,a;for(let e=0;e<i;e++)try{let t=r[e].trim(),i=b(n,t);a=O.decrypt(i.ciphertext,i.key);break}catch(t){if(e+1>=i)throw t}return O.parse(a)}function g(e){console.error(`[dotenv@${s}][WARN] ${e}`)}function _(e){console.log(`[dotenv@${s}][DEBUG] ${e}`)}function v(e){console.log(`[dotenv@${s}] ${e}`)}function y(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:``}function b(e,t){let n;try{n=new URL(t)}catch(e){if(e.code===`ERR_INVALID_URL`){let e=Error(`INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development`);throw e.code=`INVALID_DOTENV_KEY`,e}throw e}let r=n.password;if(!r){let e=Error(`INVALID_DOTENV_KEY: Missing key part`);throw e.code=`INVALID_DOTENV_KEY`,e}let i=n.searchParams.get(`environment`);if(!i){let e=Error(`INVALID_DOTENV_KEY: Missing environment part`);throw e.code=`INVALID_DOTENV_KEY`,e}let a=`DOTENV_VAULT_${i.toUpperCase()}`,o=e.parsed[a];if(!o){let e=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${a} in your .env.vault file.`);throw e.code=`NOT_FOUND_DOTENV_ENVIRONMENT`,e}return{ciphertext:o,key:r}}function x(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let r of e.path)n.existsSync(r)&&(t=r.endsWith(`.vault`)?r:`${r}.vault`);else t=e.path.endsWith(`.vault`)?e.path:`${e.path}.vault`;else t=r.resolve(process.cwd(),`.env.vault`);return n.existsSync(t)?t:null}function S(e){return e[0]===`~`?r.join(a.homedir(),e.slice(1)):e}function C(e){let t=u(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=u(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(t||!n)&&v(`Loading env from encrypted .env.vault`);let r=O._parseVault(e),i=process.env;return e&&e.processEnv!=null&&(i=e.processEnv),O.populate(i,r,e),{parsed:r}}function w(e){let t=r.resolve(process.cwd(),`.env`),i=`utf8`,a=process.env;e&&e.processEnv!=null&&(a=e.processEnv);let o=u(a.DOTENV_CONFIG_DEBUG||e&&e.debug),s=u(a.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?i=e.encoding:o&&_(`No encoding is specified. UTF-8 is used by default`);let c=[t];if(e&&e.path)if(!Array.isArray(e.path))c=[S(e.path)];else{c=[];for(let t of e.path)c.push(S(t))}let d,p={};for(let t of c)try{let r=O.parse(n.readFileSync(t,{encoding:i}));O.populate(p,r,e)}catch(e){o&&_(`Failed to load ${t} ${e.message}`),d=e}let m=O.populate(a,p,e);if(o=u(a.DOTENV_CONFIG_DEBUG||o),s=u(a.DOTENV_CONFIG_QUIET||s),o||!s){let e=Object.keys(m).length,t=[];for(let e of c)try{let n=r.relative(process.cwd(),e);t.push(n)}catch(t){o&&_(`Failed to load ${e} ${t.message}`),d=t}v(`injecting env (${e}) from ${t.join(`,`)} ${f(`-- tip: ${l()}`)}`)}return d?{parsed:p,error:d}:{parsed:p}}function T(e){if(y(e).length===0)return O.configDotenv(e);let t=x(e);return t?O._configVault(e):(g(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),O.configDotenv(e))}function E(e,t){let n=Buffer.from(t.slice(-64),`hex`),r=Buffer.from(e,`base64`),i=r.subarray(0,12),a=r.subarray(-16);r=r.subarray(12,-16);try{let e=o.createDecipheriv(`aes-256-gcm`,n,i);return e.setAuthTag(a),`${e.update(r)}${e.final()}`}catch(e){let t=e instanceof RangeError,n=e.message===`Invalid key length`,r=e.message===`Unsupported state or unable to authenticate data`;if(t||n){let e=Error(`INVALID_DOTENV_KEY: It must be 64 characters long (or more)`);throw e.code=`INVALID_DOTENV_KEY`,e}else if(r){let e=Error(`DECRYPTION_FAILED: Please check your DOTENV_KEY`);throw e.code=`DECRYPTION_FAILED`,e}else throw e}}function D(e,t,n={}){let r=!!(n&&n.debug),i=!!(n&&n.override),a={};if(typeof t!=`object`){let e=Error(`OBJECT_REQUIRED: Please check the processEnv argument being passed to populate`);throw e.code=`OBJECT_REQUIRED`,e}for(let n of Object.keys(t))Object.prototype.hasOwnProperty.call(e,n)?(i===!0&&(e[n]=t[n],a[n]=t[n]),r&&_(i===!0?`"${n}" is already defined and WAS overwritten`:`"${n}" is already defined and was NOT overwritten`)):(e[n]=t[n],a[n]=t[n]);return a}let O={configDotenv:w,_configVault:C,_parseVault:h,config:T,decrypt:E,parse:m,populate:D};t.exports.configDotenv=O.configDotenv,t.exports._configVault=O._configVault,t.exports._parseVault=O._parseVault,t.exports.config=O.config,t.exports.decrypt=O.decrypt,t.exports.parse=O.parse,t.exports.populate=O.populate,t.exports=O}))());async function hd(e,t){let n=e;for(;n!==we(n);){let e=Te(n,t);try{return await ze(e),e}catch{}n=we(n)}}function gd(e,t=`.env.local`){let[n,r]=K({});return G(()=>{let n,i=e=>{try{let t=ke(e,`utf-8`),n=(0,md.parse)(t);r(n)}catch(e){console.error(`Error reading ${t}:`,e),r({})}};return hd(e,t).then(e=>{if(!e){r({});return}i(e),n=Ae(e,{persistent:!1},()=>{i(e)})}),()=>{n&&n.close()}},[e,t]),n}const _d=(e,t)=>{let n=typeof e==`string`;typeof e==`string`&&(e=t.encode(e));let r=new Uint8Array(1+e.byteLength);return r[0]=n?0:1,r.set(new Uint8Array(e),1),r},vd=(e,t)=>e[0]===0?t.decode(e.subarray(1)):new Uint8Array(e.subarray(1));let yd=function(e){return e[e.REQUEST=0]=`REQUEST`,e[e.PROXY_INIT=1]=`PROXY_INIT`,e[e.PROXY_BODY=2]=`PROXY_BODY`,e[e.PROXY_WEBSOCKET_MESSAGE=3]=`PROXY_WEBSOCKET_MESSAGE`,e[e.PROXY_WEBSOCKET_CLOSE=4]=`PROXY_WEBSOCKET_CLOSE`,e}({}),bd=function(e){return e[e.RESPONSE=0]=`RESPONSE`,e[e.NOTIFICATION=1]=`NOTIFICATION`,e[e.PROXY_INIT=2]=`PROXY_INIT`,e[e.PROXY_DATA=3]=`PROXY_DATA`,e[e.PROXY_WEBSOCKET_MESSAGE=4]=`PROXY_WEBSOCKET_MESSAGE`,e[e.PROXY_WEBSOCKET_CLOSE=5]=`PROXY_WEBSOCKET_CLOSE`,e}({});const xd={[yd.REQUEST]:Y.string(),[yd.PROXY_INIT]:Y.object({method:Y.string(),headers:Y.record(Y.string(),Y.string()),url:Y.string()}),[yd.PROXY_BODY]:Y.instanceof(Uint8Array),[yd.PROXY_WEBSOCKET_MESSAGE]:Y.object({type:Y.enum([`text`,`binary`]),data:Y.instanceof(Uint8Array)}),[yd.PROXY_WEBSOCKET_CLOSE]:Y.object({code:Y.number().optional(),reason:Y.string().optional()})};bd.RESPONSE,Y.string(),bd.NOTIFICATION,Y.string(),bd.PROXY_INIT,Y.object({status_code:Y.number(),status_message:Y.string(),headers:Y.record(Y.string(),Y.string())}),bd.PROXY_DATA,Y.instanceof(Uint8Array),bd.PROXY_WEBSOCKET_MESSAGE,Y.instanceof(Uint8Array),bd.PROXY_WEBSOCKET_CLOSE,Y.object({code:Y.number(),reason:Y.string()}),yd.PROXY_INIT,Y.string(),Y.record(Y.string(),Y.string()),Y.string();const Sd={process_execute:Y.object({command:Y.string(),args:Y.array(Y.string()),env_file:Y.string().optional(),env:Y.record(Y.string(),Y.string()).optional(),cwd:Y.string().optional()}),process_send_input:Y.object({pid:Y.number(),data:Y.string()}),process_wait:Y.object({pid:Y.number(),output_idle_timeout_ms:Y.number().optional(),timeout_ms:Y.number().optional()}),process_list:Y.object({include_dead:Y.boolean().optional()}),process_read_plain_output:Y.object({pid:Y.number(),start_line:Y.number().optional(),end_line:Y.number().optional()}),process_kill:Y.object({pid:Y.number(),signal:Y.string().optional()}),set_env:Y.object({env:Y.record(Y.string(),Y.string())}),read_file:Y.object({path:Y.string(),line_start:Y.number().optional(),line_end:Y.number().optional()}),write_file:Y.object({path:Y.string(),content:Y.string(),base64:Y.boolean().optional(),mode:Y.number().optional()}),read_directory:Y.object({path:Y.string()}),watch_directory:Y.object({path:Y.string()}),deploy_static_files:Y.object({path:Y.string()})},Cd=Y.object({pid:Y.number(),command:Y.string(),args:Y.array(Y.string()),title:Y.string().optional(),cwd:Y.string(),env:Y.record(Y.string(),Y.string()),exit_code:Y.number().optional(),exit_signal:Y.number().optional(),duration_ms:Y.number().optional(),output_total_lines:Y.number()});Cd.extend({ansi_output:Y.string(),plain_output:Y.object({lines:Y.array(Y.string()),total_lines:Y.number()})}),Y.object({pid:Y.number()}),Y.object({}),Y.object({processes:Y.array(Cd)}),Y.object({lines:Y.array(Y.string()),total_lines:Y.number(),duration_ms:Y.number(),exit_code:Y.number().optional(),exit_signal:Y.number().optional()}),Y.object({}),Y.object({}),Y.object({total_lines:Y.number(),lines_read:Y.number(),start_line:Y.number(),content:Y.string(),mime_type:Y.string()}),Y.object({}),Y.object({entries:Y.array(Y.object({name:Y.string(),type:Y.enum([`file`,`directory`,`symlink`])}))}),Y.object({}),Y.object({deployment_id:Y.string()});const wd=Y.object({type:Y.enum([`create`,`update`,`delete`]),path:Y.string()}),Td=Y.object({type:Y.enum([`context`,`added`,`deleted`]),content:Y.string(),oldLineNumber:Y.number().optional(),newLineNumber:Y.number().optional()}),Ed=Y.object({oldStart:Y.number(),oldLines:Y.number(),newStart:Y.number(),newLines:Y.number(),lines:Y.array(Td)}),Dd=Y.object({path:Y.string(),status:Y.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),oldPath:Y.string().optional(),insertions:Y.number(),deletions:Y.number(),chunks:Y.array(Ed)}),Od=Y.object({totalFiles:Y.number(),totalInsertions:Y.number(),totalDeletions:Y.number(),netChange:Y.number(),startHash:Y.string().optional(),currentHash:Y.string().optional(),timespan:Y.number(),files:Y.array(Dd)}),kd=Y.object({path:Y.string(),status:Y.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),staged:Y.boolean()}),Ad=Y.object({hash:Y.string(),shortHash:Y.string(),message:Y.string(),author:Y.string(),email:Y.string(),date:Y.date(),timestamp:Y.date(),filesChanged:Y.number(),insertions:Y.number(),deletions:Y.number(),commitDiff:Y.array(Dd).optional()});Y.object({files:Y.array(kd),branch:Y.string(),ahead:Y.number(),behind:Y.number(),timestamp:Y.date(),sessionDiff:Od.optional(),workingDirectoryDiff:Od.optional(),newCommits:Y.array(Ad),currentCommit:Y.object({hash:Y.string(),shortHash:Y.string(),message:Y.string(),author:Y.string(),date:Y.date()}).optional(),diffSkipped:Y.boolean().optional(),payloadTruncated:Y.boolean().optional(),estimatedSizeKB:Y.number().optional()}),Y.object({debounceDelay:Y.number().optional(),gitStatusInterval:Y.number().optional(),ignoreDotfiles:Y.boolean().optional(),ignored:Y.array(Y.string()).optional(),watchGit:Y.boolean().optional(),includeDiffs:Y.boolean().optional(),maxDiffFiles:Y.number().optional(),maxPayloadSizeKB:Y.number().optional(),truncateLargeDiffs:Y.boolean().optional()}),Y.object({status:Cd}),Y.object({pid:Y.number(),output:Y.string()}),Y.object({changes:Y.array(wd)});var jd=class{notificationCallbacks=new Map;disposables=[];requestHandlers=new Map;send;jwt;requestTimeoutMS;constructor({send:e,jwt:t,requestTimeoutMS:n}){this.send=e,this.jwt=t,this.requestTimeoutMS=n}handleMessage(e){if(typeof e!=`string`)return;let t=JSON.parse(e);if(`id`in t){let e=this.requestHandlers.get(t.id);if(!e)return;e(t.payload,t.error)}else if(`type`in t)this.notificationCallbacks.get(t.type)?.forEach(e=>{e(t.payload)});else return}dispose(e){this.disposables.forEach(t=>t.dispose(e))}async request(e,t,n){let r=crypto.randomUUID(),i,a,o=new Promise((e,t)=>{i=e,a=t}),s={dispose:e=>{l();let t=`Client was disposed!`;e&&(t+=` Reason: ${e}`),a(Error(t))}};this.disposables.push(s);let c;this.requestTimeoutMS&&(c=setTimeout(()=>{a(Error(`Request timed out`))},this.requestTimeoutMS));let l=()=>{this.disposables.splice(this.disposables.indexOf(s),1),this.requestHandlers.delete(r),c&&clearTimeout(c)};n?.signal&&n.signal.addEventListener(`abort`,()=>{l(),a(n.signal?.reason)}),this.requestHandlers.set(r,(e,t)=>{if(l(),t)return a(Error(t));i(e)});let u={id:r,type:e,payload:t,jwt:this.jwt};return this.send(JSON.stringify(u)),o}onNotification(e,t){let n=this.notificationCallbacks.get(e)??[];return n.push(t),this.notificationCallbacks.set(e,n),{dispose:()=>{let n=this.notificationCallbacks.get(e)??[],r=n.indexOf(t);r!==-1&&n.splice(r,1)}}}},Md=e(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),Nd=e(((e,t)=>{let{EMPTY_BUFFER:n}=Md(),r=Buffer[Symbol.species];function a(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function o(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function s(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function c(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function l(e){if(l.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),l.readOnly=!1),t}if(t.exports={concat:a,mask:o,toArrayBuffer:c,toBuffer:l,unmask:s},!process.env.WS_NO_BUFFER_UTIL)try{let e=i(`bufferutil`);t.exports.mask=function(t,n,r,i,a){a<48?o(t,n,r,i,a):e.mask(t,n,r,i,a)},t.exports.unmask=function(t,n){t.length<32?s(t,n):e.unmask(t,n)}}catch{}})),Pd=e(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),Fd=e(((e,t)=>{let n=i(`zlib`),r=Nd(),a=Pd(),{kStatusCode:o}=Md(),s=Buffer[Symbol.species],c=Buffer.from([0,0,255,255]),l=Symbol(`permessage-deflate`),u=Symbol(`total-length`),d=Symbol(`callback`),f=Symbol(`buffers`),p=Symbol(`error`),m;t.exports=class{constructor(e,t,n){if(this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!m){let e=this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit;m=new a(e)}}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[d];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){m.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){m.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[l]=this,this._inflate[u]=0,this._inflate[f]=[],this._inflate.on(`error`,_),this._inflate.on(`data`,g)}this._inflate[d]=i,this._inflate.write(e),t&&this._inflate.write(c),this._inflate.flush(()=>{let e=this._inflate[p];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[f],this._inflate[u]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[u]=0,this._inflate[f]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[u]=0,this._deflate[f]=[],this._deflate.on(`data`,h)}this._deflate[d]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[f],this._deflate[u]);t&&(e=new s(e.buffer,e.byteOffset,e.length-4)),this._deflate[d]=null,this._deflate[u]=0,this._deflate[f]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function h(e){this[f].push(e),this[u]+=e.length}function g(e){if(this[u]+=e.length,this[l]._maxPayload<1||this[u]<=this[l]._maxPayload){this[f].push(e);return}this[p]=RangeError(`Max payload size exceeded`),this[p].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[p][o]=1009,this.removeListener(`data`,g),this.reset()}function _(e){if(this[l]._inflate=null,this[p]){this[d](this[p]);return}e[o]=1007,this[d](e)}})),Id=e(((e,t)=>{let{isUtf8:n}=i(`buffer`),{hasBlob:r}=Md(),a=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function o(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function s(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function c(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:c,isValidStatusCode:o,isValidUTF8:s,tokenChars:a},n)t.exports.isValidUTF8=function(e){return e.length<24?s(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=i(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?s(t):e(t)}}catch{}})),Ld=e(((e,t)=>{let{Writable:n}=i(`stream`),r=Fd(),{BINARY_TYPES:a,EMPTY_BUFFER:o,kStatusCode:s,kWebSocket:c}=Md(),{concat:l,toArrayBuffer:u,unmask:d}=Nd(),{isValidStatusCode:f,isValidUTF8:p}=Id(),m=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||a[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[c]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new m(t.buffer,t.byteOffset+e,t.length-e),new m(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new m(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){let t=this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`);e(t);return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(!this._fragmented){let t=this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let t=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let t=this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`);e(t);return}if(n){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let t=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`);e(t);return}}else{let t=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){let t=this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`);e(t);return}}else if(this._masked){let t=this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`);e(t);return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){let t=this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`);e(t);return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`);e(t);return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=o;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&d(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let e=this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`);t(e);return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?l(n,t):this._binaryType===`arraybuffer`?u(l(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=l(n,t);if(!this._skipUTF8Validation&&!p(r)){let t=this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`);e(t);return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,o),this.end();else{let n=e.readUInt16BE(0);if(!f(n)){let e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`);t(e);return}let r=new m(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!p(r)){let e=this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`);t(e);return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[s]=r,a}}})),Rd=e(((e,t)=>{let{Duplex:n}=i(`stream`),{randomFillSync:r}=i(`crypto`),a=Fd(),{EMPTY_BUFFER:o,kWebSocket:s,NOOP:c}=Md(),{isBlob:l,isValidStatusCode:u}=Id(),{mask:d,toBuffer:f}=Nd(),p=Symbol(`kByteLength`),m=Buffer.alloc(4),h=8*1024,g,_=h;t.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=c,this[s]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||m,t.generateMask?t.generateMask(n):(_===h&&(g===void 0&&(g=Buffer.alloc(h)),r(g,0,h),_=0),n[0]=g[_++],n[1]=g[_++],n[2]=g[_++],n[3]=g[_++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[p]!==void 0?s=t[p]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(d(e,n,l,a,s),[l]):(d(e,n,e,0,s),[l,e])}close(t,n,r,i){let a;if(t===void 0)a=o;else if(typeof t!=`number`||!u(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)a=Buffer.allocUnsafe(2),a.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);a=Buffer.allocUnsafe(2+e),a.writeUInt16BE(t,0),typeof n==`string`?a.write(n,2):a.set(n,2)}let s={[p]:a.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(a,s),i):this.enqueue([this.dispatch,a,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):l(t)?(i=t.size,a=!1):(t=f(t),i=t.length,a=f.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[p]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};l(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):l(t)?(i=t.size,a=!1):(t=f(t),i=t.length,a=f.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[p]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};l(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[a.extensionName],i=t.binary?2:1,o=t.compress,s,c;typeof e==`string`?(s=Buffer.byteLength(e),c=!1):l(e)?(s=e.size,c=!1):(e=f(e),s=e.length,c=f.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0);let u={[p]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};l(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[p],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(v,this,e,i);return}this._bufferedBytes-=r[p];let a=f(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(y,this,e,i)})}dispatch(t,n,r,i){if(!n){this.sendFrame(e.frame(t,r),i);return}let o=this._extensions[a.extensionName];this._bufferedBytes+=r[p],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){v(this,Error(`The socket was closed while data was being compressed`),i);return}this._bufferedBytes-=r[p],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),i),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][p],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][p],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function v(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function y(e,t,n){v(e,t,n),e.onerror(t)}})),zd=e(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=Md(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,`target`,{enumerable:!0}),Object.defineProperty(f.prototype,`type`,{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,`code`,{enumerable:!0}),Object.defineProperty(p.prototype,`reason`,{enumerable:!0}),Object.defineProperty(p.prototype,`wasClean`,{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,`error`,{enumerable:!0}),Object.defineProperty(m.prototype,`message`,{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),Bd=e(((e,t)=>{let{tokenChars:n}=Id();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),Vd=e(((e,t)=>{let n=i(`events`),r=i(`https`),a=i(`http`),o=i(`net`),s=i(`tls`),{randomBytes:c,createHash:l}=i(`crypto`),{Duplex:u,Readable:d}=i(`stream`),{URL:f}=i(`url`),p=Fd(),m=Ld(),h=Rd(),{isBlob:g}=Id(),{BINARY_TYPES:_,EMPTY_BUFFER:v,GUID:y,kForOnEventAttribute:b,kListener:x,kStatusCode:S,kWebSocket:C,NOOP:w}=Md(),{EventTarget:{addEventListener:T,removeEventListener:E}}=zd(),{format:D,parse:O}=Bd(),{toBuffer:k}=Nd(),A=Symbol(`kAborted`),j=[8,13],M=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],N=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var P=class e extends n{constructor(t,n,r){super(),this._binaryType=_[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=v,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),ee(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){_.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new m({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new h(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[C]=this,a[C]=this,t[C]=this,i.on(`conclude`,R),i.on(`drain`,z),i.on(`error`,re),i.on(`message`,ie),i.on(`ping`,V),i.on(`pong`,ae),a.onerror=se,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,ce),t.on(`data`,U),t.on(`end`,le),t.on(`error`,W),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[p.extensionName]&&this._extensions[p.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){I(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),H(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){L(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||v,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){L(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||v,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){L(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[p.extensionName]||(i.compress=!1),this._sender.send(t||v,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){I(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(P,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(P.prototype,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(P,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(P.prototype,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(P,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(P.prototype,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(P,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),Object.defineProperty(P.prototype,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(P.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(P.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[b])return t[x];return null},set(t){for(let t of this.listeners(e))if(t[b]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[b]:!0})}})}),P.prototype.addEventListener=T,P.prototype.removeEventListener=E,t.exports=P;function ee(e,t,n,i){let o={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:j[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,!j.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${j.join(`, `)})`);let s;if(t instanceof f)s=t;else try{s=new f(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}s.protocol===`http:`?s.protocol=`ws:`:s.protocol===`https:`&&(s.protocol=`wss:`),e._url=s.href;let u=s.protocol===`wss:`,d=s.protocol===`ws+unix:`,m;if(s.protocol!==`ws:`&&!u&&!d?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:d&&!s.pathname?m=`The URL's pathname is empty`:s.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;te(e,t);return}let h=u?443:80,g=c(16).toString(`base64`),_=u?r.request:a.request,v=new Set,b;if(o.createConnection=o.createConnection||(u?F:ne),o.defaultPort=o.defaultPort||h,o.port=s.port||h,o.host=s.hostname.startsWith(`[`)?s.hostname.slice(1,-1):s.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=s.pathname+s.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(b=new p(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=D({[p.extensionName]:b.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!N.test(e)||v.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);v.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(s.username||s.password)&&(o.auth=`${s.username}:${s.password}`),d){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let x;if(o.followRedirects){if(e._redirects===0){e._originalIpc=d,e._originalSecure=u,e._originalHostOrSocketPath=d?o.socketPath:s.host;let t=i&&i.headers;if(i={...i,headers:{}},t)for(let[e,n]of Object.entries(t))i.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=d?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:s.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!i.headers.authorization&&(i.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),x=e._req=_(o),e._redirects&&e.emit(`redirect`,e.url,x)}else x=e._req=_(o);o.timeout&&x.on(`timeout`,()=>{I(e,x,`Opening handshake has timed out`)}),x.on(`error`,t=>{x===null||x[A]||(x=e._req=null,te(e,t))}),x.on(`response`,r=>{let a=r.headers.location,s=r.statusCode;if(a&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){I(e,x,`Maximum redirects exceeded`);return}x.abort();let r;try{r=new f(a,t)}catch{let t=SyntaxError(`Invalid URL: ${a}`);te(e,t);return}ee(e,r,n,i)}else e.emit(`unexpected-response`,x,r)||I(e,x,`Unexpected server response: ${r.statusCode}`)}),x.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==P.CONNECTING)return;x=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){I(e,n,`Invalid Upgrade header`);return}let a=l(`sha1`).update(g+y).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){I(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],c;if(s===void 0?v.size&&(c=`Server sent no subprotocol`):v.size?v.has(s)||(c=`Server sent an invalid subprotocol`):c=`Server sent a subprotocol but none was requested`,c){I(e,n,c);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!b){I(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=O(u)}catch{I(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==p.extensionName){I(e,n,`Server indicated an extension that was not requested`);return}try{b.accept(t[p.extensionName])}catch{I(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[p.extensionName]=b}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(x,e):x.end()}function te(e,t){e._readyState=P.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function ne(e){return e.path=e.socketPath,o.connect(e)}function F(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=o.isIP(e.host)?``:e.host),s.connect(e)}function I(e,t,n){e._readyState=P.CLOSING;let r=Error(n);Error.captureStackTrace(r,I),t.setHeader?(t[A]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(te,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function L(e,t,n){if(t){let n=g(t)?t.size:k(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${M[e.readyState]})`);process.nextTick(n,t)}}function R(e,t){let n=this[C];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[C]!==void 0&&(n._socket.removeListener(`data`,U),process.nextTick(oe,n._socket),e===1005?n.close():n.close(e,t))}function z(){let e=this[C];e.isPaused||e._socket.resume()}function re(e){let t=this[C];t._socket[C]!==void 0&&(t._socket.removeListener(`data`,U),process.nextTick(oe,t._socket),t.close(e[S])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function B(){this[C].emitClose()}function ie(e,t){this[C].emit(`message`,e,t)}function V(e){let t=this[C];t._autoPong&&t.pong(e,!this._isServer,w),t.emit(`ping`,e)}function ae(e){this[C].emit(`pong`,e)}function oe(e){e.resume()}function se(e){let t=this[C];t.readyState!==P.CLOSED&&(t.readyState===P.OPEN&&(t._readyState=P.CLOSING,H(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function H(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),3e4)}function ce(){let e=this[C];this.removeListener(`close`,ce),this.removeListener(`data`,U),this.removeListener(`end`,le),e._readyState=P.CLOSING;let t;!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&(t=e._socket.read())!==null&&e._receiver.write(t),e._receiver.end(),this[C]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,B),e._receiver.on(`finish`,B))}function U(e){this[C]._receiver.write(e)||this.pause()}function le(){let e=this[C];e._readyState=P.CLOSING,e._receiver.end(),this.end()}function W(){let e=this[C];this.removeListener(`error`,W),this.on(`error`,w),e&&(e._readyState=P.CLOSING,this.destroy())}})),Hd=e(((e,t)=>{Vd();let{Duplex:n}=i(`stream`);function r(e){e.emit(`close`)}function a(){!this.destroyed&&this._writableState.finished&&this.destroy()}function o(e){this.removeListener(`error`,o),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function s(e,t){let i=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(i=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let a=!1;e.once(`error`,function(e){a=!0,n(e)}),e.once(`close`,function(){a||n(t),process.nextTick(r,s)}),i&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,a),s.on(`error`,o),s}t.exports=s})),Ud=e(((e,t)=>{let{tokenChars:n}=Id();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),Wd=e(((e,t)=>{let n=i(`events`),r=i(`http`),{Duplex:a}=i(`stream`),{createHash:o}=i(`crypto`),s=Bd(),c=Fd(),l=Ud(),u=Vd(),{GUID:d,kWebSocket:f}=Md(),p=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:u,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=m(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(h,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(h,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{h(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,g);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,o=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){v(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){v(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!p.test(i)){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(o!==13&&o!==8){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){_(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=l.parse(u)}catch{v(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&f!==void 0){let n=new c(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=s.parse(f);e[c.extensionName]&&(n.accept(e[c.extensionName]),m[c.extensionName]=n)}catch{v(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${o===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return _(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return _(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,a,l){if(!i.readable||!i.writable)return i.destroy();if(i[f])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return _(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${o(`sha1`).update(t+d).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[c.extensionName]){let t=e[c.extensionName].params,n=s.format({[c.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
|
|
@@ -163,53 +163,7 @@ for await (const chunk of exa.streamAnswer(query)) {
|
|
|
163
163
|
// Handle chunks
|
|
164
164
|
}`,400);let n=t?.outputSchema;n&&Lg(n)&&(n=Rg(n));let r={query:e,stream:!1,text:t?.text??!1,model:t?.model??`exa`,systemPrompt:t?.systemPrompt,outputSchema:n,userLocation:t?.userLocation};return await this.request(`/answer`,`POST`,r)}async*streamAnswer(e,t){let n=t?.outputSchema;n&&Lg(n)&&(n=Rg(n));let r={query:e,text:t?.text??!1,stream:!0,model:t?.model??`exa`,systemPrompt:t?.systemPrompt,outputSchema:n},i=await Zg(this.baseURL+`/answer`,{method:`POST`,headers:this.headers,body:JSON.stringify(r)});if(!i.ok){let e=await i.text();throw new Ig(e,i.status,new Date().toISOString())}let a=i.body?.getReader();if(!a)throw new Ig(`No response body available for streaming.`,500,new Date().toISOString());let o=new TextDecoder,s=``;try{for(;;){let{done:e,value:t}=await a.read();if(e)break;s+=o.decode(t,{stream:!0});let n=s.split(`
|
|
165
165
|
`);s=n.pop()||``;for(let e of n){if(!e.startsWith(`data: `))continue;let t=e.replace(/^data:\s*/,``).trim();if(!t||t===`[DONE]`)continue;let n;try{n=JSON.parse(t)}catch{continue}let r=this.processChunk(n);(r.content||r.citations)&&(yield r)}}if(s.startsWith(`data: `)){let e=s.replace(/^data:\s*/,``).trim();if(e&&e!==`[DONE]`)try{let t=JSON.parse(e),n=this.processChunk(t);(n.content||n.citations)&&(yield n)}catch{}}}finally{a.releaseLock()}}processChunk(e){let t,n;return e.choices&&e.choices[0]&&e.choices[0].delta&&(t=e.choices[0].delta.content),e.citations&&e.citations!==`null`&&(n=e.citations.map(e=>({id:e.id,url:e.url,title:e.title,publishedDate:e.publishedDate,author:e.author,text:e.text}))),{content:t,citations:n}}async parseSSEStream(e){let t=e.body?.getReader();if(!t)throw new Ig(`No response body available for streaming.`,500,new Date().toISOString());let n=new TextDecoder,r=``;return new Promise(async(e,i)=>{try{for(;;){let{done:a,value:o}=await t.read();if(a)break;r+=n.decode(o,{stream:!0});let s=r.split(`
|
|
166
|
-
`);r=s.pop()||``;for(let n of s){if(!n.startsWith(`data: `))continue;let r=n.replace(/^data:\s*/,``).trim();if(!r||r===`[DONE]`)continue;let a;try{a=JSON.parse(r)}catch{continue}switch(a.tag){case`complete`:t.releaseLock(),e(a.data);return;case`error`:{let e=a.error?.message||`Unknown error`;t.releaseLock(),i(new Ig(e,500,new Date().toISOString()));return}default:break}}}i(new Ig(`Stream ended without a completion event.`,500,new Date().toISOString()))}catch(e){i(e)}finally{try{t.releaseLock()}catch{}}})}};const e_=()=>{let e;if(process.env.EXA_API_KEY)e=new $g(process.env.EXA_API_KEY);else if(process.env.BLINK_INVOCATION_AUTH_TOKEN)e=new $g(process.env.BLINK_INVOCATION_AUTH_TOKEN,`https://blink.so/api/tools/exa`);else if(process.env.BLINK_TOKEN)e=new $g(process.env.BLINK_TOKEN,`https://blink.so/api/tools/exa`);else throw console.warn(`You must set the EXA_API_KEY environment variable or be authenticated with Blink to use the web search SDK.`),Error(`The EXA_API_KEY environment variable or a Blink token must be set to use the web search SDK.`);return e},t_={web_search:Sh({description:`Perform a search query on the web, and retrieve the most relevant URLs/web data.`,inputSchema:Y.object({query:Y.string()}),execute:async({query:e})=>await e_().searchAndContents(e,{numResults:5,type:`auto`,text:{maxCharacters:3e3},livecrawl:`preferred`})})},n_={scratch:{"
|
|
167
|
-
import * as blink from "blink";
|
|
168
|
-
import { z } from "zod";
|
|
169
|
-
|
|
170
|
-
const agent = blink.agent();
|
|
171
|
-
|
|
172
|
-
agent.on("chat", async ({ messages }) => {
|
|
173
|
-
return streamText({
|
|
174
|
-
model: blink.model("anthropic/claude-sonnet-4.5"),
|
|
175
|
-
system: \`You are a basic agent the user will customize.
|
|
176
|
-
|
|
177
|
-
Suggest the user enters edit mode with Ctrl+T or /edit to customize the agent.
|
|
178
|
-
Demonstrate your capabilities with the IP tool.\`,
|
|
179
|
-
messages: convertToModelMessages(messages),
|
|
180
|
-
tools: {
|
|
181
|
-
get_ip_info: tool({
|
|
182
|
-
description: "Get IP address information of the computer.",
|
|
183
|
-
inputSchema: z.object({}),
|
|
184
|
-
execute: async () => {
|
|
185
|
-
const response = await fetch("https://ipinfo.io/json");
|
|
186
|
-
return response.json();
|
|
187
|
-
},
|
|
188
|
-
}),
|
|
189
|
-
},
|
|
190
|
-
});
|
|
191
|
-
});
|
|
192
|
-
|
|
193
|
-
agent.serve();
|
|
194
|
-
`,"package.json":`{
|
|
195
|
-
"name": "{{name}}",
|
|
196
|
-
"main": "agent.ts",
|
|
197
|
-
"type": "module",
|
|
198
|
-
"private": true,
|
|
199
|
-
"scripts": {
|
|
200
|
-
"dev": "blink dev",
|
|
201
|
-
"deploy": "blink deploy"
|
|
202
|
-
},
|
|
203
|
-
"devDependencies": {
|
|
204
|
-
"zod": "latest",
|
|
205
|
-
"ai": "latest",
|
|
206
|
-
"blink": "latest",
|
|
207
|
-
"esbuild": "latest",
|
|
208
|
-
"@types/node": "latest",
|
|
209
|
-
"typescript": "latest"
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
`,".gitignore":`# dependencies
|
|
166
|
+
`);r=s.pop()||``;for(let n of s){if(!n.startsWith(`data: `))continue;let r=n.replace(/^data:\s*/,``).trim();if(!r||r===`[DONE]`)continue;let a;try{a=JSON.parse(r)}catch{continue}switch(a.tag){case`complete`:t.releaseLock(),e(a.data);return;case`error`:{let e=a.error?.message||`Unknown error`;t.releaseLock(),i(new Ig(e,500,new Date().toISOString()));return}default:break}}}i(new Ig(`Stream ended without a completion event.`,500,new Date().toISOString()))}catch(e){i(e)}finally{try{t.releaseLock()}catch{}}})}};const e_=()=>{let e;if(process.env.EXA_API_KEY)e=new $g(process.env.EXA_API_KEY);else if(process.env.BLINK_INVOCATION_AUTH_TOKEN)e=new $g(process.env.BLINK_INVOCATION_AUTH_TOKEN,`https://blink.so/api/tools/exa`);else if(process.env.BLINK_TOKEN)e=new $g(process.env.BLINK_TOKEN,`https://blink.so/api/tools/exa`);else throw console.warn(`You must set the EXA_API_KEY environment variable or be authenticated with Blink to use the web search SDK.`),Error(`The EXA_API_KEY environment variable or a Blink token must be set to use the web search SDK.`);return e},t_={web_search:Sh({description:`Perform a search query on the web, and retrieve the most relevant URLs/web data.`,inputSchema:Y.object({query:Y.string()}),execute:async({query:e})=>await e_().searchAndContents(e,{numResults:5,type:`auto`,text:{maxCharacters:3e3},livecrawl:`preferred`})})},n_={scratch:{".gitignore":`# dependencies
|
|
213
167
|
node_modules
|
|
214
168
|
|
|
215
169
|
# config and build
|
|
@@ -689,106 +643,53 @@ The agent process can restart at any time, so all important state must be extern
|
|
|
689
643
|
# Store local environment variables here.
|
|
690
644
|
# They will be used by blink dev for development.
|
|
691
645
|
# EXTERNAL_SERVICE_API_KEY=
|
|
692
|
-
`,".env.production"
|
|
693
|
-
# Store production environment variables here.
|
|
646
|
+
`,".env.production":`# Store production environment variables here.
|
|
694
647
|
# They will be upserted as secrets on blink deploy.
|
|
695
648
|
# EXTERNAL_SERVICE_API_KEY=
|
|
696
|
-
|
|
649
|
+
`,"agent.ts.hbs":`import { convertToModelMessages, streamText, tool } from "ai";
|
|
697
650
|
import * as blink from "blink";
|
|
698
|
-
import
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
signingSecret: process.env.SLACK_SIGNING_SECRET,
|
|
705
|
-
receiver,
|
|
706
|
-
});
|
|
707
|
-
|
|
708
|
-
// Handle messages in channels (only when @mentioned)
|
|
709
|
-
app.event("app_mention", async ({ event }) => {
|
|
710
|
-
const chat = await agent.chat.upsert([
|
|
711
|
-
"slack",
|
|
712
|
-
event.channel,
|
|
713
|
-
event.thread_ts ?? event.ts,
|
|
714
|
-
]);
|
|
715
|
-
const { message } = await slack.createMessageFromEvent({
|
|
716
|
-
client: app.client,
|
|
717
|
-
event,
|
|
718
|
-
});
|
|
719
|
-
await agent.chat.sendMessages(chat.id, [message]);
|
|
720
|
-
await app.client.assistant.threads.setStatus({
|
|
721
|
-
channel_id: event.channel,
|
|
722
|
-
status: "is typing...",
|
|
723
|
-
thread_ts: event.thread_ts ?? event.ts,
|
|
724
|
-
});
|
|
725
|
-
});
|
|
651
|
+
import { z } from "zod";
|
|
652
|
+
{{#if (eq aiProvider "anthropic")}}
|
|
653
|
+
import { anthropic } from "@ai-sdk/anthropic";
|
|
654
|
+
{{else if (eq aiProvider "openai")}}
|
|
655
|
+
import { openai } from "@ai-sdk/openai";
|
|
656
|
+
{{/if}}
|
|
726
657
|
|
|
727
|
-
// Handle direct messages (always respond)
|
|
728
|
-
app.event("message", async ({ event }) => {
|
|
729
|
-
// Ignore bot messages and message changes
|
|
730
|
-
if (event.subtype || event.bot_id) {
|
|
731
|
-
return;
|
|
732
|
-
}
|
|
733
|
-
// Only handle DMs (channel type is 'im')
|
|
734
|
-
const channelInfo = await app.client.conversations.info({
|
|
735
|
-
channel: event.channel,
|
|
736
|
-
});
|
|
737
|
-
if (!channelInfo.channel?.is_im) {
|
|
738
|
-
return;
|
|
739
|
-
}
|
|
740
|
-
const chat = await agent.chat.upsert(["slack", event.channel]);
|
|
741
|
-
const { message } = await slack.createMessageFromEvent({
|
|
742
|
-
client: app.client,
|
|
743
|
-
event,
|
|
744
|
-
});
|
|
745
|
-
await agent.chat.sendMessages(chat.id, [message]);
|
|
746
|
-
await app.client.assistant.threads.setStatus({
|
|
747
|
-
channel_id: event.channel,
|
|
748
|
-
status: "is typing...",
|
|
749
|
-
thread_ts: event.thread_ts ?? event.ts,
|
|
750
|
-
});
|
|
751
|
-
});
|
|
752
658
|
const agent = new blink.Agent();
|
|
753
659
|
|
|
754
|
-
agent.on("request", async (request) => {
|
|
755
|
-
return receiver.handle(app, request);
|
|
756
|
-
});
|
|
757
|
-
|
|
758
660
|
agent.on("chat", async ({ messages }) => {
|
|
759
|
-
const tools = slack.createTools({ client: app.client });
|
|
760
|
-
const lastMessage = messages[messages.length - 1];
|
|
761
|
-
const threadInfo = lastMessage?.metadata as
|
|
762
|
-
| { channel?: string; thread_ts?: string }
|
|
763
|
-
| undefined;
|
|
764
|
-
|
|
765
|
-
// Add instruction to clear status after completion
|
|
766
|
-
if (threadInfo?.channel && threadInfo?.thread_ts) {
|
|
767
|
-
const clonedMessages = structuredClone(messages);
|
|
768
|
-
const lastClonedMessage = clonedMessages[clonedMessages.length - 1];
|
|
769
|
-
if (lastClonedMessage) {
|
|
770
|
-
lastClonedMessage.parts.push({
|
|
771
|
-
type: "text",
|
|
772
|
-
text: \`*INTERNAL INSTRUCTION*: Clear the status of this thread after you finish: channel=\${threadInfo.channel} thread_ts=\${threadInfo.thread_ts}\`,
|
|
773
|
-
});
|
|
774
|
-
}
|
|
775
|
-
messages = clonedMessages;
|
|
776
|
-
}
|
|
777
|
-
|
|
778
661
|
return streamText({
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
662
|
+
{{#if (eq aiProvider "anthropic")}}
|
|
663
|
+
model: anthropic("claude-sonnet-4-5"),
|
|
664
|
+
{{else if (eq aiProvider "openai")}}
|
|
665
|
+
model: openai("gpt-5-chat-latest"),
|
|
666
|
+
{{else if (eq aiProvider "vercel")}}
|
|
667
|
+
model: "anthropic/claude-sonnet-4.5",
|
|
668
|
+
{{else}}
|
|
669
|
+
// Unknown provider: {{aiProvider}}. Defaulting to Vercel AI Gateway syntax.
|
|
670
|
+
model: "anthropic/claude-sonnet-4.5",
|
|
671
|
+
{{/if}}
|
|
672
|
+
system: \`You are a basic agent the user will customize.
|
|
673
|
+
|
|
674
|
+
Suggest the user enters edit mode with Ctrl+T or /edit to customize the agent.
|
|
675
|
+
Demonstrate your capabilities with the IP tool.\`,
|
|
676
|
+
messages: convertToModelMessages(messages),
|
|
677
|
+
tools: {
|
|
678
|
+
get_ip_info: tool({
|
|
679
|
+
description: "Get IP address information of the computer.",
|
|
680
|
+
inputSchema: z.object({}),
|
|
681
|
+
execute: async () => {
|
|
682
|
+
const response = await fetch("https://ipinfo.io/json");
|
|
683
|
+
return response.json();
|
|
684
|
+
},
|
|
685
|
+
}),
|
|
686
|
+
},
|
|
786
687
|
});
|
|
787
688
|
});
|
|
788
689
|
|
|
789
690
|
agent.serve();
|
|
790
|
-
`,"package.json":`{
|
|
791
|
-
"name": "{{
|
|
691
|
+
`,"package.json.hbs":`{
|
|
692
|
+
"name": "{{packageName}}",
|
|
792
693
|
"main": "agent.ts",
|
|
793
694
|
"type": "module",
|
|
794
695
|
"private": true,
|
|
@@ -799,15 +700,18 @@ agent.serve();
|
|
|
799
700
|
"devDependencies": {
|
|
800
701
|
"zod": "latest",
|
|
801
702
|
"ai": "latest",
|
|
703
|
+
{{#if (eq aiProvider "anthropic")}}
|
|
704
|
+
"@ai-sdk/anthropic": "latest",
|
|
705
|
+
{{else if (eq aiProvider "openai")}}
|
|
706
|
+
"@ai-sdk/openai": "latest",
|
|
707
|
+
{{/if}}
|
|
802
708
|
"blink": "latest",
|
|
803
709
|
"esbuild": "latest",
|
|
804
710
|
"@types/node": "latest",
|
|
805
|
-
"typescript": "latest"
|
|
806
|
-
"@slack/bolt": "latest",
|
|
807
|
-
"@blink-sdk/slack": "latest"
|
|
711
|
+
"typescript": "latest"
|
|
808
712
|
}
|
|
809
713
|
}
|
|
810
|
-
|
|
714
|
+
`},"slack-bot":{".gitignore":`# dependencies
|
|
811
715
|
node_modules
|
|
812
716
|
|
|
813
717
|
# config and build
|
|
@@ -1288,12 +1192,143 @@ The agent process can restart at any time, so all important state must be extern
|
|
|
1288
1192
|
# They will be used by blink dev for development.
|
|
1289
1193
|
SLACK_BOT_TOKEN=xoxb-your-token-here
|
|
1290
1194
|
SLACK_SIGNING_SECRET=your-signing-secret-here
|
|
1291
|
-
`,".env.production"
|
|
1292
|
-
# Store production environment variables here.
|
|
1195
|
+
`,".env.production":`# Store production environment variables here.
|
|
1293
1196
|
# They will be upserted as secrets on blink deploy.
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1197
|
+
# EXTERNAL_SERVICE_API_KEY=
|
|
1198
|
+
`,"agent.ts.hbs":`import { convertToModelMessages, streamText } from "ai";
|
|
1199
|
+
import * as blink from "blink";
|
|
1200
|
+
import * as slack from "@blink-sdk/slack";
|
|
1201
|
+
import { App } from "@slack/bolt";
|
|
1202
|
+
{{#if (eq aiProvider "anthropic")}}
|
|
1203
|
+
import { anthropic } from "@ai-sdk/anthropic";
|
|
1204
|
+
{{else if (eq aiProvider "openai")}}
|
|
1205
|
+
import { openai } from "@ai-sdk/openai";
|
|
1206
|
+
{{/if}}
|
|
1207
|
+
|
|
1208
|
+
const receiver = new slack.Receiver();
|
|
1209
|
+
const app = new App({
|
|
1210
|
+
token: process.env.SLACK_BOT_TOKEN,
|
|
1211
|
+
signingSecret: process.env.SLACK_SIGNING_SECRET,
|
|
1212
|
+
receiver,
|
|
1213
|
+
});
|
|
1214
|
+
|
|
1215
|
+
// Handle messages in channels (only when @mentioned)
|
|
1216
|
+
app.event("app_mention", async ({ event }) => {
|
|
1217
|
+
const chat = await agent.chat.upsert([
|
|
1218
|
+
"slack",
|
|
1219
|
+
event.channel,
|
|
1220
|
+
event.thread_ts ?? event.ts,
|
|
1221
|
+
]);
|
|
1222
|
+
const { message } = await slack.createMessageFromEvent({
|
|
1223
|
+
client: app.client,
|
|
1224
|
+
event,
|
|
1225
|
+
});
|
|
1226
|
+
await agent.chat.sendMessages(chat.id, [message]);
|
|
1227
|
+
await app.client.assistant.threads.setStatus({
|
|
1228
|
+
channel_id: event.channel,
|
|
1229
|
+
status: "is typing...",
|
|
1230
|
+
thread_ts: event.thread_ts ?? event.ts,
|
|
1231
|
+
});
|
|
1232
|
+
});
|
|
1233
|
+
|
|
1234
|
+
// Handle direct messages (always respond)
|
|
1235
|
+
app.event("message", async ({ event }) => {
|
|
1236
|
+
// Ignore bot messages and message changes
|
|
1237
|
+
if (event.subtype || event.bot_id) {
|
|
1238
|
+
return;
|
|
1239
|
+
}
|
|
1240
|
+
// Only handle DMs (channel type is 'im')
|
|
1241
|
+
const channelInfo = await app.client.conversations.info({
|
|
1242
|
+
channel: event.channel,
|
|
1243
|
+
});
|
|
1244
|
+
if (!channelInfo.channel?.is_im) {
|
|
1245
|
+
return;
|
|
1246
|
+
}
|
|
1247
|
+
const chat = await agent.chat.upsert(["slack", event.channel]);
|
|
1248
|
+
const { message } = await slack.createMessageFromEvent({
|
|
1249
|
+
client: app.client,
|
|
1250
|
+
event,
|
|
1251
|
+
});
|
|
1252
|
+
await agent.chat.sendMessages(chat.id, [message]);
|
|
1253
|
+
await app.client.assistant.threads.setStatus({
|
|
1254
|
+
channel_id: event.channel,
|
|
1255
|
+
status: "is typing...",
|
|
1256
|
+
thread_ts: event.thread_ts ?? event.ts,
|
|
1257
|
+
});
|
|
1258
|
+
});
|
|
1259
|
+
|
|
1260
|
+
const agent = new blink.Agent();
|
|
1261
|
+
|
|
1262
|
+
agent.on("request", async (request) => {
|
|
1263
|
+
return receiver.handle(app, request);
|
|
1264
|
+
});
|
|
1265
|
+
|
|
1266
|
+
agent.on("chat", async ({ messages }) => {
|
|
1267
|
+
const tools = slack.createTools({ client: app.client });
|
|
1268
|
+
const lastMessage = messages[messages.length - 1];
|
|
1269
|
+
const threadInfo = lastMessage?.metadata as
|
|
1270
|
+
| { channel?: string; thread_ts?: string }
|
|
1271
|
+
| undefined;
|
|
1272
|
+
|
|
1273
|
+
// Add instruction to clear status after completion
|
|
1274
|
+
if (threadInfo?.channel && threadInfo?.thread_ts) {
|
|
1275
|
+
const clonedMessages = structuredClone(messages);
|
|
1276
|
+
const lastClonedMessage = clonedMessages[clonedMessages.length - 1];
|
|
1277
|
+
if (lastClonedMessage) {
|
|
1278
|
+
lastClonedMessage.parts.push({
|
|
1279
|
+
type: "text",
|
|
1280
|
+
text: \`*INTERNAL INSTRUCTION*: Clear the status of this thread after you finish: channel=\${threadInfo.channel} thread_ts=\${threadInfo.thread_ts}\`,
|
|
1281
|
+
});
|
|
1282
|
+
}
|
|
1283
|
+
messages = clonedMessages;
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
return streamText({
|
|
1287
|
+
{{#if (eq aiProvider "anthropic")}}
|
|
1288
|
+
model: anthropic("claude-sonnet-4-5"),
|
|
1289
|
+
{{else if (eq aiProvider "openai")}}
|
|
1290
|
+
model: openai("gpt-5-chat-latest"),
|
|
1291
|
+
{{else if (eq aiProvider "vercel")}}
|
|
1292
|
+
model: "anthropic/claude-sonnet-4.5",
|
|
1293
|
+
{{else}}
|
|
1294
|
+
// Unknown provider: {{aiProvider}}. Defaulting to Vercel AI Gateway syntax.
|
|
1295
|
+
model: "anthropic/claude-sonnet-4.5",
|
|
1296
|
+
{{/if}}
|
|
1297
|
+
system: "You are a helpful Slack bot assistant.",
|
|
1298
|
+
messages: convertToModelMessages(messages, {
|
|
1299
|
+
ignoreIncompleteToolCalls: true,
|
|
1300
|
+
tools,
|
|
1301
|
+
}),
|
|
1302
|
+
tools,
|
|
1303
|
+
});
|
|
1304
|
+
});
|
|
1305
|
+
|
|
1306
|
+
agent.serve();`,"package.json.hbs":`{
|
|
1307
|
+
"name": "{{packageName}}",
|
|
1308
|
+
"main": "agent.ts",
|
|
1309
|
+
"type": "module",
|
|
1310
|
+
"private": true,
|
|
1311
|
+
"scripts": {
|
|
1312
|
+
"dev": "blink dev",
|
|
1313
|
+
"deploy": "blink deploy"
|
|
1314
|
+
},
|
|
1315
|
+
"devDependencies": {
|
|
1316
|
+
"zod": "latest",
|
|
1317
|
+
"ai": "latest",
|
|
1318
|
+
{{#if (eq aiProvider "anthropic")}}
|
|
1319
|
+
"@ai-sdk/anthropic": "latest",
|
|
1320
|
+
{{else if (eq aiProvider "openai")}}
|
|
1321
|
+
"@ai-sdk/openai": "latest",
|
|
1322
|
+
{{/if}}
|
|
1323
|
+
"blink": "latest",
|
|
1324
|
+
"esbuild": "latest",
|
|
1325
|
+
"@types/node": "latest",
|
|
1326
|
+
"typescript": "latest",
|
|
1327
|
+
"@slack/bolt": "latest",
|
|
1328
|
+
"@blink-sdk/slack": "latest"
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
`}};function r_(e,t,n){let r,i=Se.createServer(j(async a=>{let o=new URL(a.url,r);if(o.pathname!==`/`)return new Response(`Not found`,{status:404});let s=o.searchParams.get(`code`);if(s)try{let e=await fetch(`https://api.github.com/app-manifests/${s}/conversions`,{method:`POST`,headers:{Accept:`application/vnd.github+json`,"User-Agent":`blink.so`,"X-GitHub-Api-Version":`2022-11-28`}});if(!e.ok){let t=await e.text();throw Error(`GitHub API error: ${e.status} ${e.statusText}${t?` - ${t}`:``}`)}let t=await e.json();return await n?.(null,t),new Response(`GitHub App created successfully! Return to your terminal to continue.`,{headers:{"Content-Type":`text/plain`}})}catch(e){let t=e instanceof Error?e:Error(String(e));try{await n?.(t,null)}catch(e){t=e instanceof Error?e:Error(String(e))}let r=t.message;return new Response(`Error: ${r}\n\nReturn to your terminal for more details.`,{status:500,headers:{"Content-Type":`text/plain`}})}finally{i.close()}let c={...e,redirect_url:r},l=`<!DOCTYPE html>
|
|
1297
1332
|
<html>
|
|
1298
1333
|
<body>
|
|
1299
1334
|
<form id="f" method="POST" action="${t?`https://github.com/organizations/${t}/settings/apps/new`:`https://github.com/settings/apps/new`}">
|
|
@@ -1394,4 +1429,4 @@ Slack:
|
|
|
1394
1429
|
1. *ALWAYS* use the \`typecheck_agent\` tool to check for type errors before making changes. NEVER invoke \`tsc\` directly.
|
|
1395
1430
|
2. Use the \`message_user_agent\` tool to test the agent after you make changes.
|
|
1396
1431
|
</agent_development>
|
|
1397
|
-
`});let p=n_.scratch[`AGENTS.md`];try{p=await Re(Te(e.directory,`AGENTS.md`),`utf-8`)}catch{}return f.unshift({role:`system`,content:p}),Fe({model:
|
|
1432
|
+
`});let p=n_.scratch[`AGENTS.md`];try{p=await Re(Te(e.directory,`AGENTS.md`),`utf-8`)}catch{}return f.unshift({role:`system`,content:p}),Fe({model:m_(e.env),messages:f,maxOutputTokens:64e3,tools:d,abortSignal:a,experimental_repairToolCall:({tools:e,toolCall:t})=>{throw Object.keys(e).includes(t.toolName)?Error(`You have this tool, but you used an invalid input.`):Error(`Invalid tool call. Tool "${t.toolName}" is not available to the EDIT AGENT.`)}})}),{agent:t,setUserAgentUrl:e=>{n=e},cleanup:()=>{r&&=(r.close(),void 0)}}}function p_(e){if(e.ANTHROPIC_API_KEY)return Jt({apiKey:e.ANTHROPIC_API_KEY}).chat(`claude-sonnet-4-5`);if(e.OPENAI_API_KEY)return Di({apiKey:e.OPENAI_API_KEY}).responses(`gpt-5`);if(e.AI_GATEWAY_API_KEY)return E({apiKey:e.AI_GATEWAY_API_KEY})(`anthropic/claude-sonnet-4-5`)}function m_(e){let t=p_(e);if(!t)throw Error(`No API key available for edit mode`);return t}function h_(e){let[t,n]=K(void 0),[r,i]=K(void 0),[a,o]=K(!1),s=We(void 0);return G(()=>{let t=new AbortController,r=!1;if(i(void 0),n(void 0),!p_(e.env)){o(!0);return}return o(!1),(async()=>{s.current=f_({directory:e.directory,env:e.env,getDevhookUrl:e.getDevhookUrl});let r=await g_(),i=s.current.agent.serve({port:r,host:`127.0.0.1`,apiUrl:e.apiServerUrl});t.signal.addEventListener(`abort`,()=>{try{i.close()}catch{}s.current?.cleanup()});let a=new ka({baseUrl:`http://127.0.0.1:${r}`});for(;!t.signal.aborted;){try{await a.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(t.signal.aborted)throw t.signal.reason;n(a)})().catch(e=>{r||i(e instanceof Error?e:Error(String(e)))}),()=>{r=!0,t.abort()}},[e.directory,e.apiServerUrl,e.env,e.getDevhookUrl]),Ue(()=>({client:t,error:r,missingApiKey:a,setUserAgentUrl:e=>{s.current?.setUserAgentUrl(e)}}),[t,r,a])}async function g_(){let e=Ce();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function __(e){let{directory:t}=e,[n,r]=K(),[i,a]=K(!1),[o,s]=K(`run`),c=We(`run`);G(()=>{c.current=o},[o]);let l=He(t=>{s(t),e.onModeChange?.(t),r(void 0)},[e.onModeChange]),u=He(()=>{l(o===`run`?`edit`:`run`)},[o,l]),{error:d,status:f,result:p,entry:m}=au({directory:t,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),h=iu({autoCheck:!0,onAuthChange:e.onAuthChange,onLoginUrl:e.onLoginUrl}),g=gd(t),_=Ue(()=>{let e=h.token;return e?{...g,BLINK_TOKEN:e}:g},[g,h.token]),v=We(void 0);G(()=>{let t=Object.keys(_);if(t.length===v.current||v.current===void 0){v.current=t.length;return}v.current=t.length,e.onEnvLoaded?.(t)},[_,e.onEnvLoaded]);let y=We(void 0),b=Ue(()=>ld({port:0,dataDirectory:Te(t,`data`),getAgent:()=>y.current}),[t]),{agent:x,logs:S,error:C,capabilities:w}=Aa({buildResult:p,env:_,apiServerUrl:b.url}),{client:T,error:E,missingApiKey:D,setUserAgentUrl:O}=h_({directory:t,apiServerUrl:b.url,env:_,getDevhookUrl:He(()=>{let e=zu(t)??Bu(t);return F(e),`https://${e}.blink.host`},[t])}),[k,A]=K(`00000000-0000-0000-0000-000000000000`);G(()=>{y.current=x},[x]),G(()=>{x&&O(x.baseUrl),(o===`run`&&!x||o===`edit`&&!T)&&b.getChatManager(k)?.stopStreaming()},[x,T,o,k,b,O]);let j=We(void 0),M=Iu({chatId:k,agent:o===`run`?x:T,chatsDirectory:b.chatsDirectory,serializeMessage:e=>{let t=e.role===`user`&&j.current?{...typeof e.metadata==`object`&&e.metadata!==null?e.metadata:{},options:j.current}:e.metadata;return typeof t==`object`&&t&&(t.__blink_mode=c.current),{id:e.id??crypto.randomUUID(),created_at:new Date().toISOString(),role:e.role,parts:e.parts,mode:c.current,metadata:t}},filterMessages:e=>c.current===`edit`?!0:!(Pu(e.metadata)||e.mode===`edit`)}),N=We(0);G(()=>{if(S.length===N.current)return;let t=N.current;for(let n of S.slice(t))e.onAgentLog?.(n);N.current=S.length},[S,e.onAgentLog,M.upsertMessage]);let[P,te]=K([]);G(()=>{b.listChats().then(e=>{te(e.map(e=>e.key))})},[b]),G(()=>{k&&!P.includes(k)&&te(e=>[...e,k])},[k,P]);let[ne,F]=K(()=>Ru(t)?zu(t):Bu(t)),I=fd({id:ne,directory:t,disabled:!w?.request,onRequest:async t=>{if(!x)throw Error(`No agent`);let n=new URL(t.url),r=new URL(x.baseUrl);r.pathname=n.pathname,r.search=n.search;try{let i=await fetch(r.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:`manual`,signal:t.signal,duplex:`half`});return e.onDevhookRequest?.({method:t.method,path:n.pathname,status:i.status}),i}catch(e){return console.error(`Error sending request to user's agent:`,e),new Response(`Internal server error`,{status:500})}}});G(()=>{I.status!==`connected`||!I.url||e.onDevhookConnected?.(I.url)},[I.status,I.url]);let{schema:L,options:R,error:z,setOption:re}=ud({agent:o===`run`?x:T,capabilities:w,messages:M.messages});G(()=>{j.current=R},[R]);let B=Ue(()=>{let e=new Map;return C&&o===`run`&&e.set(`agent`,C.message),E&&o===`edit`&&e.set(`editAgent`,`Edit agent error: ${E.message}`),M.error&&f!==`building`&&e.set(`chat`,`Chat error: ${M.error}`),z&&e.set(`options`,`Options error: ${z.message}`),e},[C,E,M.error,z,o,f]),ie=We(new Map);G(()=>{let t=ie.current,n=B;for(let[r,i]of n.entries())t.get(r)!==i&&e.onError?.(i);for(let e of t.keys())n.has(e);ie.current=new Map(n)},[B,e.onError]);let V=Ue(()=>{let e=[...M.messages].reverse().find(e=>!(e.role!==`assistant`||e.metadata&&e.metadata.ephemeral));if(!e||n===e.id)return;let t=e.parts.filter(Ne);if(t.length!==0&&t.some(e=>ee(e.output)&&e.output.outcome===`pending`))return e},[M.messages,n]),ae=He(async(e,t)=>{if(!V)return;t&&e&&a(!0),r(V.id);let n=M.messages;if(n.length===0)return;let i=n[n.length-1];if(!i||i.role!==`assistant`||!Array.isArray(i.parts))return;let o=i.parts.map(t=>t.output&&ee(t.output)&&t.output.outcome===`pending`?{...t,output:{...t.output,outcome:e?`approved`:`rejected`}}:t);await M.upsertMessage({...i,parts:o}),await M.start()},[V,M]);G(()=>{i&&V&&ae(!0)},[i,V,ae]);let oe=He(()=>{let e=crypto.randomUUID();A(e),te(t=>[...t,e]),r(void 0)},[]),se=He(e=>{A(e),r(void 0)},[]),H=Ue(()=>{if(V)return{message:V,approve:e=>ae(!0,e),reject:()=>ae(!1),autoApproveEnabled:i}},[V,ae,i]),ce=Ue(()=>{let e=M.messages;if(e.length!==0)for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n||n.role!==`assistant`||!n.metadata||typeof n.metadata!=`object`||!(`totalUsage`in n.metadata))continue;let r=n.metadata.totalUsage;if(!(!r||typeof r!=`object`)&&!(!(`inputTokens`in r)||!(`outputTokens`in r)||!(`totalTokens`in r)))return{inputTokens:r.inputTokens,outputTokens:r.outputTokens,totalTokens:r.totalTokens,cachedInputTokens:r.cachedInputTokens}}},[M.messages]),U=Ue(()=>{if(M.status!==`streaming`)return!1;if(!M.streamingMessage)return!0;let e=M.streamingMessage.parts.filter(Ne);return e.length>0&&e.every(e=>e.state.startsWith(`output-`))},[M.status,M.streamingMessage]);return{mode:o,setMode:l,toggleMode:u,chat:M,chats:P,switchChat:se,newChat:oe,build:{status:f,error:d,entrypoint:m},devhook:{connected:I.status===`connected`,url:I.status===`connected`?I.url:void 0},capabilities:w,options:{schema:L,selected:R,error:z,setOption:re},approval:H,tokenUsage:ce,auth:h,server:b,showWaitingPlaceholder:U,editModeMissingApiKey:D}}export{Aa as useAgent,iu as useAuth,au as useBundler,Iu as useChat,__ as useDevMode,fd as useDevhook,gd as useDotenv,h_ as useEditAgent,ud as useOptions};
|