blink 1.1.33 → 1.1.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/control/index.d.cts +12 -4
- package/dist/browser/control/index.d.ts +12 -4
- package/dist/cli/chat-manager-bMAuoSb5.js +21 -0
- package/dist/cli/chat-mj0wnV3_.js +1 -0
- package/dist/cli/compute-server-BFNeHOmk.js +1 -0
- package/dist/cli/{connect-t56RPJRB.js → connect-BnhWpzRI.js} +1 -1
- package/dist/cli/connect-Cd-0O7Uu.js +1 -0
- package/dist/cli/create-github-app-Dld06QIC.js +16 -0
- package/dist/cli/{dev-DTCSw4OQ.js → dev-9EzQCNmd.js} +156 -177
- package/dist/cli/{getMachineId-bsd-BECgXpZb.js → getMachineId-bsd-BfwVPdTh.js} +1 -1
- package/dist/cli/{getMachineId-bsd-BgAyii4H.js → getMachineId-bsd-BmhpEQU_.js} +1 -1
- package/dist/cli/{getMachineId-bsd-Cc73dhdJ.js → getMachineId-bsd-C1eeoY31.js} +1 -1
- package/dist/cli/{getMachineId-bsd-DJn61I3m.js → getMachineId-bsd-CO9ne--Y.js} +1 -1
- package/dist/cli/{getMachineId-bsd-Doah6QJP.js → getMachineId-bsd-D4uBPoNF.js} +1 -1
- package/dist/cli/getMachineId-bsd-DVGtITCk.js +1 -0
- package/dist/cli/getMachineId-bsd-MA4oFaCa.js +1 -0
- package/dist/cli/getMachineId-bsd-dbToLPez.js +1 -0
- package/dist/cli/{getMachineId-darwin-BMnMBte0.js → getMachineId-darwin-C0EZ3sY3.js} +1 -1
- package/dist/cli/{getMachineId-darwin-BP9BSYcd.js → getMachineId-darwin-CSfD7gS4.js} +1 -1
- package/dist/cli/{getMachineId-darwin-Bs3mlKrs.js → getMachineId-darwin-CgQ9n4TU.js} +1 -1
- package/dist/cli/{getMachineId-darwin-DFronuaU.js → getMachineId-darwin-Cpq0Lloc.js} +1 -1
- package/dist/cli/{getMachineId-darwin-D-l4_nyT.js → getMachineId-darwin-CuAzoP7O.js} +1 -1
- package/dist/cli/getMachineId-darwin-D6_tdcZj.js +2 -0
- package/dist/cli/getMachineId-darwin-DkExT2qu.js +2 -0
- package/dist/cli/getMachineId-darwin-xoAzTD7x.js +2 -0
- package/dist/cli/{getMachineId-linux-B2r_HEgX.js → getMachineId-linux-B1XJTHUh.js} +1 -1
- package/dist/cli/{getMachineId-linux-Bj52Hdvy.js → getMachineId-linux-CRUR6LbQ.js} +1 -1
- package/dist/cli/{getMachineId-linux-C9o1dYwI.js → getMachineId-linux-CVQNNGui.js} +1 -1
- package/dist/cli/{getMachineId-linux-CGcBOg7J.js → getMachineId-linux-CtdZRCaX.js} +1 -1
- package/dist/cli/getMachineId-linux-DMILcDJR.js +1 -0
- package/dist/cli/getMachineId-linux-Deja7F2k.js +1 -0
- package/dist/cli/getMachineId-linux-DqOGXYgv.js +1 -0
- package/dist/cli/getMachineId-linux-FRx9q8NV.js +1 -0
- package/dist/cli/{getMachineId-unsupported-BtmyS2eg.js → getMachineId-unsupported-B-xvzil1.js} +1 -1
- package/dist/cli/{getMachineId-unsupported-C8az6JKm.js → getMachineId-unsupported-BA3eQjiV.js} +1 -1
- package/dist/cli/{getMachineId-unsupported-CBS2qXAs.js → getMachineId-unsupported-BZCOxs7n.js} +1 -1
- package/dist/cli/{getMachineId-unsupported-Cu0DvxaU.js → getMachineId-unsupported-BjGFauqb.js} +1 -1
- package/dist/cli/getMachineId-unsupported-CLWxRb7f.js +1 -0
- package/dist/cli/getMachineId-unsupported-CSVFDvWp.js +1 -0
- package/dist/cli/getMachineId-unsupported-Cp_95R-6.js +1 -0
- package/dist/cli/getMachineId-unsupported-Nd0_Z7NT.js +1 -0
- package/dist/cli/{getMachineId-win-BCAO7ld1.js → getMachineId-win-AW-Mv9PG.js} +1 -1
- package/dist/cli/{getMachineId-win-BDQszRKi.js → getMachineId-win-B_2C1cwE.js} +1 -1
- package/dist/cli/{getMachineId-win-BOnF6rL7.js → getMachineId-win-BbYxddZ9.js} +1 -1
- package/dist/cli/{getMachineId-win-BOuIHcz_.js → getMachineId-win-BkozcdSh.js} +1 -1
- package/dist/cli/getMachineId-win-CPhFagnx.js +1 -0
- package/dist/cli/{getMachineId-win-pnMl0wak.js → getMachineId-win-CUeKGXdr.js} +1 -1
- package/dist/cli/getMachineId-win-D3-sMfSu.js +1 -0
- package/dist/cli/getMachineId-win-DFVpvzl3.js +1 -0
- package/dist/cli/index.js +7 -7
- package/dist/cli/init-CByRT25U.js +23 -0
- package/dist/cli/{init-templates-D4lwX_8M.js → init-templates-jGRvqLQ6.js} +614 -1
- package/dist/cli/run-Lp28Ogb_.js +1 -0
- package/dist/cli/setup-github-app-D-K7e6al.js +9 -0
- package/dist/cli/{token-Bk68OrJt.js → token-ClGOahUF.js} +1 -1
- package/dist/cli/token-util-DIx5k-1f.js +1 -0
- package/dist/cli/{token-util-BKLboTb2.js → token-util-h1hcKvQX.js} +1 -1
- package/dist/cli/undici-JD4hDNWZ.js +1 -0
- package/dist/cli/utils-B3iC7vdW.js +1 -0
- package/dist/node/agent/index.node.cjs +1 -1
- package/dist/node/agent/index.node.js +1 -1
- package/dist/node/{index.node-Bvp48I1R.cjs → index.node-Btg8Ii_o.cjs} +2 -2
- package/dist/node/{index.node-ppzOWVGE.js → index.node-xL4mvvNL.js} +2 -2
- package/dist/node/react/index.node.cjs +615 -2
- package/dist/node/react/index.node.js +615 -2
- package/package.json +1 -1
- package/dist/cli/chat-C_rQ9SRr.js +0 -1
- package/dist/cli/chat-manager-bLgTuAnK.js +0 -21
- package/dist/cli/compute-server-CyGc-fpM.js +0 -1
- package/dist/cli/connect-CgLoRyDv.js +0 -1
- package/dist/cli/create-slack-app-CyVPwWsG.js +0 -1
- package/dist/cli/events-DKgZ2LNM.js +0 -1
- package/dist/cli/getMachineId-bsd-aoAkh_W6.js +0 -1
- package/dist/cli/getMachineId-bsd-iPOb0TqF.js +0 -1
- package/dist/cli/getMachineId-bsd-io5tPlFg.js +0 -1
- package/dist/cli/getMachineId-darwin-DJO6fOdc.js +0 -2
- package/dist/cli/getMachineId-darwin-DlRRGl6M.js +0 -2
- package/dist/cli/getMachineId-darwin-Wp0usMIp.js +0 -2
- package/dist/cli/getMachineId-linux-CV2HmJXY.js +0 -1
- package/dist/cli/getMachineId-linux-Cv44Y8ZY.js +0 -1
- package/dist/cli/getMachineId-linux-CzNEh3DJ.js +0 -1
- package/dist/cli/getMachineId-linux-_RiwpX2J.js +0 -1
- package/dist/cli/getMachineId-unsupported-Dni2ujA-.js +0 -1
- package/dist/cli/getMachineId-unsupported-MPNVP8rP.js +0 -1
- package/dist/cli/getMachineId-unsupported-mBJd3oBN.js +0 -1
- package/dist/cli/getMachineId-unsupported-rdNf8ej6.js +0 -1
- package/dist/cli/getMachineId-win-BQ_C7kS3.js +0 -1
- package/dist/cli/getMachineId-win-Bw0-Mlkn.js +0 -1
- package/dist/cli/getMachineId-win-DrJTv2qi.js +0 -1
- package/dist/cli/init-DXBledyD.js +0 -23
- package/dist/cli/run-CRrWbMEw.js +0 -1
- package/dist/cli/setup-slack-app-C9L0iIDZ.js +0 -1
- package/dist/cli/token-util-Dui5nOLw.js +0 -1
- package/dist/cli/undici-mM2IfLwA.js +0 -1
- /package/dist/cli/{devtools-CS3ukAFj.js → devtools-CwQnB6v7.js} +0 -0
- /package/dist/cli/{esm-CYkSi8_o.js → esm-BiWxO8S7.js} +0 -0
- /package/dist/cli/{execAsync-9jtK4I3l.js → execAsync-4IyNgpoN.js} +0 -0
- /package/dist/cli/{execAsync-B4_pEoEJ.js → execAsync-B6xSGvuk.js} +0 -0
- /package/dist/cli/{execAsync-BdK7RB6d.js → execAsync-B8_ZTafx.js} +0 -0
- /package/dist/cli/{execAsync-Bjxs-bO2.js → execAsync-B8nelpRN.js} +0 -0
- /package/dist/cli/{execAsync-CM_C8SBr.js → execAsync-Cj_jF8MF.js} +0 -0
- /package/dist/cli/{execAsync-CNFaXJjR.js → execAsync-Ckbi9Yqe.js} +0 -0
- /package/dist/cli/{execAsync-Dl3hbWiU.js → execAsync-CvOpnFex.js} +0 -0
- /package/dist/cli/{execAsync-qGIZ8XA8.js → execAsync-DDBH3pWg.js} +0 -0
- /package/dist/cli/{token-error-CGIVaIg6.js → token-error-BHDo_48c.js} +0 -0
- /package/dist/cli/{undici-BiTrd9-R.js → undici-B5tM_IT9.js} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const e=require(`../chunk-iXuH7AlR.cjs`),t=require(`../index.node-Bvp48I1R.cjs`);require(`../token-error-BoNG8ooW.cjs`),require(`../esm-0UNjvroT.cjs`);const n=require(`../build-EgdtUZTI.cjs`);let r=require(`zod/v4`);r=e.__toESM(r);let i=require(`zod/v3`);i=e.__toESM(i);let a=require(`node:buffer`);a=e.__toESM(a);let o=require(`node:fs`);o=e.__toESM(o);let s=require(`node:url`);s=e.__toESM(s);let c=require(`node:stream`);c=e.__toESM(c);let l=require(`node:util`);l=e.__toESM(l);let u=require(`node:crypto`);u=e.__toESM(u);let d=require(`http`);d=e.__toESM(d);let f=require(`path`);f=e.__toESM(f);let p=require(`fs`);p=e.__toESM(p);let m=require(`ai`);m=e.__toESM(m);let h=require(`fs/promises`);h=e.__toESM(h);let g=require(`child_process`);g=e.__toESM(g);let _=require(`react`);_=e.__toESM(_);let v=require(`node:module`);v=e.__toESM(v);let y=require(`zod`);y=e.__toESM(y);let b=require(`node:path`);b=e.__toESM(b);let x=require(`node:process`);x=e.__toESM(x);let S=require(`node:os`);S=e.__toESM(S);let C=require(`node:tty`);C=e.__toESM(C);let w=require(`node:readline`);w=e.__toESM(w);let T=require(`node:child_process`);T=e.__toESM(T);let E=require(`node:fs/promises`);E=e.__toESM(E),require(`@blink-sdk/compute-protocol/client`);let D=require(`@blink-sdk/compute-protocol/transport`);D=e.__toESM(D);function O(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function k(e){return Object.fromEntries([...e.headers])}function A(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 j(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function M(e,...t){let n=j(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var N=({prefix:e,size:n=16,alphabet:r=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:i=`-`}={})=>{let a=()=>{let e=r.length,t=Array(n);for(let i=0;i<n;i++)t[i]=r[Math.random()*e|0];return t.join(``)};if(e==null)return a;if(r.includes(i))throw new t.InvalidArgumentError({argument:`separator`,message:`The separator "${i}" must not be part of the alphabet "${r}".`});return()=>`${e}${i}${a()}`},P=N();function F(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var ee=[`fetch failed`,`failed to fetch`];function te({error:e,url:n,requestBodyValues:r}){if(F(e))return e;if(e instanceof TypeError&&ee.includes(e.message.toLowerCase())){let i=e.cause;if(i!=null)return new t.APICallError({message:`Cannot connect to API: ${i.message}`,cause:i,url:n,requestBodyValues:r,isRetryable:!0})}return e}var I=`3.0.10`;function ne({apiKey:e,environmentVariableName:n,apiKeyParameterName:r=`apiKey`,description:i}){if(typeof e==`string`)return e;if(e!=null)throw new t.LoadAPIKeyError({message:`${i} API key must be a string.`});if(typeof process>`u`)throw new t.LoadAPIKeyError({message:`${i} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[n],e==null)throw new t.LoadAPIKeyError({message:`${i} API key is missing. Pass it using the '${r}' parameter or the ${n} environment variable.`});if(typeof e!=`string`)throw new t.LoadAPIKeyError({message:`${i} API key must be a string. The value of the ${n} environment variable is not a string.`});return e}var L=/"__proto__"\s*:/,re=/"constructor"\s*:/;function R(e){let t=JSON.parse(e);return typeof t!=`object`||!t||L.test(e)===!1&&re.test(e)===!1?t:z(t)}function z(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 B(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return R(e)}finally{Error.stackTraceLimit=t}}var ie=Symbol.for(`vercel.ai.validator`);function ae(e){return{[ie]:!0,validate:e}}function oe(e){return typeof e==`object`&&!!e&&ie in e&&e[ie]===!0&&`validate`in e}function se(e){return oe(e)?e:ce(e)}function ce(e){return ae(async n=>{let r=await e[`~standard`].validate(n);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new t.TypeValidationError({value:n,cause:r.issues})}})}async function V({value:e,schema:n}){let r=await le({value:e,schema:n});if(!r.success)throw t.TypeValidationError.wrap({value:e,cause:r.error});return r.value}async function le({value:e,schema:n}){let r=se(n);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};let n=await r.validate(e);return n.success?{success:!0,value:n.value,rawValue:e}:{success:!1,error:t.TypeValidationError.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:t.TypeValidationError.wrap({value:e,cause:n}),rawValue:e}}}async function ue({text:e,schema:n}){try{let t=B(e);return n==null?t:V({value:t,schema:n})}catch(n){throw t.JSONParseError.isInstance(n)||t.TypeValidationError.isInstance(n)?n:new t.JSONParseError({text:e,cause:n})}}async function de({text:e,schema:n}){try{let t=B(e);return n==null?{success:!0,value:t,rawValue:t}:await le({value:t,schema:n})}catch(n){return{success:!1,error:t.JSONParseError.isInstance(n)?n:new t.JSONParseError({text:e,cause:n}),rawValue:void 0}}}function fe({stream:e,schema:n}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new t.EventSourceParserStream).pipeThrough(new TransformStream({async transform({data:e},t){e!==`[DONE]`&&t.enqueue(await de({text:e,schema:n}))}}))}async function pe({provider:e,providerOptions:n,schema:r}){if(n?.[e]==null)return;let i=await le({value:n[e],schema:r});if(!i.success)throw new t.InvalidArgumentError({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:i.error});return i.value}var me=()=>globalThis.fetch,he=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>ge({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),ge=async({url:e,headers:n={},body:r,successfulResponseHandler:i,failedResponseHandler:a,abortSignal:o,fetch:s=me()})=>{try{let c=await s(e,{method:`POST`,headers:M(n,`ai-sdk/provider-utils/${I}`,A()),body:r.content,signal:o}),l=k(c);if(!c.ok){let n;try{n=await a({response:c,url:e,requestBodyValues:r.values})}catch(n){throw F(n)||t.APICallError.isInstance(n)?n:new t.APICallError({message:`Failed to process error response`,cause:n,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw n.value}try{return await i({response:c,url:e,requestBodyValues:r.values})}catch(n){throw n instanceof Error&&(F(n)||t.APICallError.isInstance(n))?n:new t.APICallError({message:`Failed to process successful response`,cause:n,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(t){throw te({error:t,url:e,requestBodyValues:r.values})}};function _e(e){return e}function ve({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>_e({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function ye({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>_e({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:r,execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}async function be(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var H=({errorSchema:e,errorToMessage:n,isRetryable:r})=>async({response:i,url:a,requestBodyValues:o})=>{let s=await i.text(),c=k(i);if(s.trim()===``)return{responseHeaders:c,value:new t.APICallError({message:i.statusText,url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,isRetryable:r?.(i)})};try{let l=await ue({text:s,schema:e});return{responseHeaders:c,value:new t.APICallError({message:n(l),url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,data:l,isRetryable:r?.(i,l)})}}catch{return{responseHeaders:c,value:new t.APICallError({message:i.statusText,url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,isRetryable:r?.(i)})}}},xe=e=>async({response:n})=>{let r=k(n);if(n.body==null)throw new t.EmptyResponseBodyError({});return{responseHeaders:r,value:fe({stream:n.body,schema:e})}},Se=e=>async({response:n,url:r,requestBodyValues:i})=>{let a=await n.text(),o=await de({text:a,schema:e}),s=k(n);if(!o.success)throw new t.APICallError({message:`Invalid JSON response`,cause:o.error,statusCode:n.status,responseHeaders:s,responseBody:a,url:r,requestBodyValues:i});return{responseHeaders:s,value:o.value,rawValue:o.rawValue}},Ce=Symbol(`Let zodToJsonSchema decide on which parser to use`),we=Symbol.for(`vercel.ai.schema`),{btoa:Te,atob:Ee}=globalThis;function De(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return Te(t)}function Oe(e){return e instanceof Uint8Array?De(e):e}function ke(e){return e?.replace(/\/$/,``)}var Ae=`2.0.23`,je=r.z.object({type:r.z.literal(`error`),error:r.z.object({type:r.z.string(),message:r.z.string()})}),Me=H({errorSchema:je,errorToMessage:e=>e.error.message}),U=r.z.object({citations:r.z.object({enabled:r.z.boolean()}).optional(),title:r.z.string().optional(),context:r.z.string().optional()}),Ne=r.z.object({sendReasoning:r.z.boolean().optional(),thinking:r.z.object({type:r.z.union([r.z.literal(`enabled`),r.z.literal(`disabled`)]),budgetTokens:r.z.number().optional()}).optional(),disableParallelToolUse:r.z.boolean().optional(),cacheControl:r.z.object({type:r.z.literal(`ephemeral`),ttl:r.z.union([r.z.literal(`5m`),r.z.literal(`1h`)]).optional()}).optional()});function Pe(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var Fe=r.z.object({maxCharacters:r.z.number().optional()}),Ie=ve({id:`anthropic.text_editor_20250728`,name:`str_replace_based_edit_tool`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),Le=(e={})=>Ie(e),Re=r.z.object({maxUses:r.z.number().optional(),allowedDomains:r.z.array(r.z.string()).optional(),blockedDomains:r.z.array(r.z.string()).optional(),userLocation:r.z.object({type:r.z.literal(`approximate`),city:r.z.string().optional(),region:r.z.string().optional(),country:r.z.string().optional(),timezone:r.z.string().optional()}).optional()}),ze=r.z.array(r.z.object({url:r.z.string(),title:r.z.string(),pageAge:r.z.string().nullable(),encryptedContent:r.z.string(),type:r.z.literal(`web_search_result`)})),Be=ye({id:`anthropic.web_search_20250305`,name:`web_search`,inputSchema:r.z.object({query:r.z.string()}),outputSchema:ze}),Ve=(e={})=>Be(e),He=r.z.object({maxUses:r.z.number().optional(),allowedDomains:r.z.array(r.z.string()).optional(),blockedDomains:r.z.array(r.z.string()).optional(),citations:r.z.object({enabled:r.z.boolean()}).optional(),maxContentTokens:r.z.number().optional()}),Ue=r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.union([r.z.object({type:r.z.literal(`base64`),mediaType:r.z.literal(`application/pdf`),data:r.z.string()}),r.z.object({type:r.z.literal(`text`),mediaType:r.z.literal(`text/plain`),data:r.z.string()})])}),retrievedAt:r.z.string().nullable()}),We=ye({id:`anthropic.web_fetch_20250910`,name:`web_fetch`,inputSchema:r.z.object({url:r.z.string()}),outputSchema:Ue}),Ge=(e={})=>We(e);function Ke({tools:e,toolChoice:n,disableParallelToolUse:r}){e=e?.length?e:void 0;let i=[],a=new Set;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:a};let o=[];for(let t of e)switch(t.type){case`function`:{let e=Pe(t.providerOptions);o.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`:a.add(`code-execution-2025-05-22`),o.push({type:`code_execution_20250522`,name:`code_execution`});break;case`anthropic.computer_20250124`:a.add(`computer-use-2025-01-24`),o.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`:a.add(`computer-use-2024-10-22`),o.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`:a.add(`computer-use-2025-01-24`),o.push({name:`str_replace_editor`,type:`text_editor_20250124`});break;case`anthropic.text_editor_20241022`:a.add(`computer-use-2024-10-22`),o.push({name:`str_replace_editor`,type:`text_editor_20241022`});break;case`anthropic.text_editor_20250429`:a.add(`computer-use-2025-01-24`),o.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`});break;case`anthropic.text_editor_20250728`:{let e=Fe.parse(t.args);o.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250728`,max_characters:e.maxCharacters});break}case`anthropic.bash_20250124`:a.add(`computer-use-2025-01-24`),o.push({name:`bash`,type:`bash_20250124`});break;case`anthropic.bash_20241022`:a.add(`computer-use-2024-10-22`),o.push({name:`bash`,type:`bash_20241022`});break;case`anthropic.web_fetch_20250910`:{a.add(`web-fetch-2025-09-10`);let e=He.parse(t.args);o.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=Re.parse(t.args);o.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:i.push({type:`unsupported-tool`,tool:t});break}break;default:i.push({type:`unsupported-tool`,tool:t});break}if(n==null)return{tools:o,toolChoice:r?{type:`auto`,disable_parallel_tool_use:r}:void 0,toolWarnings:i,betas:a};let s=n.type;switch(s){case`auto`:return{tools:o,toolChoice:{type:`auto`,disable_parallel_tool_use:r},toolWarnings:i,betas:a};case`required`:return{tools:o,toolChoice:{type:`any`,disable_parallel_tool_use:r},toolWarnings:i,betas:a};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:a};case`tool`:return{tools:o,toolChoice:{type:`tool`,name:n.toolName,disable_parallel_tool_use:r},toolWarnings:i,betas:a};default:throw new t.UnsupportedFunctionalityError({functionality:`tool choice type: ${s}`})}}var qe=r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),Je=ye({id:`anthropic.code_execution_20250522`,name:`code_execution`,inputSchema:r.z.object({code:r.z.string()}),outputSchema:qe}),Ye=(e={})=>Je(e);function Xe(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 t.UnsupportedFunctionalityError({functionality:`URL-based text documents are not supported for citations`}):new t.UnsupportedFunctionalityError({functionality:`unsupported data type for text documents: ${typeof e}`})}async function Ze({prompt:e,sendReasoning:n,warnings:r}){let i=new Set,a=Qe(e),o,s=[];async function c(e){return(await pe({provider:`anthropic`,providerOptions:e,schema:U}))?.citations?.enabled??!1}async function l(e){let t=await pe({provider:`anthropic`,providerOptions:e,schema:U});return{title:t?.title,context:t?.context}}for(let e=0;e<a.length;e++){let u=a[e],d=e===a.length-1,f=u.type;switch(f){case`system`:if(o!=null)throw new t.UnsupportedFunctionalityError({functionality:`Multiple system messages that are separated by user/assistant messages`});o=u.messages.map(({content:e,providerOptions:t})=>({type:`text`,text:e,cache_control:Pe(t)}));break;case`user`:{let e=[];for(let n of u.messages){let{role:r,content:a}=n;switch(r){case`user`:for(let r=0;r<a.length;r++){let o=a[r],s=r===a.length-1,u=Pe(o.providerOptions)??(s?Pe(n.providerOptions):void 0);switch(o.type){case`text`:e.push({type:`text`,text:o.text,cache_control:u});break;case`file`:if(o.mediaType.startsWith(`image/`))e.push({type:`image`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`base64`,media_type:o.mediaType===`image/*`?`image/jpeg`:o.mediaType,data:Oe(o.data)},cache_control:u});else if(o.mediaType===`application/pdf`){i.add(`pdfs-2024-09-25`);let t=await c(o.providerOptions),n=await l(o.providerOptions);e.push({type:`document`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`base64`,media_type:`application/pdf`,data:Oe(o.data)},title:n.title??o.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:u})}else if(o.mediaType===`text/plain`){let t=await c(o.providerOptions),n=await l(o.providerOptions);e.push({type:`document`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`text`,media_type:`text/plain`,data:Xe(o.data)},title:n.title??o.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:u})}else throw new t.UnsupportedFunctionalityError({functionality:`media type: ${o.mediaType}`});break}}break;case`tool`:for(let r=0;r<a.length;r++){let i=a[r],o=r===a.length-1,s=Pe(i.providerOptions)??(o?Pe(n.providerOptions):void 0),c=i.output,l;switch(c.type){case`content`:l=c.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 t.UnsupportedFunctionalityError({functionality:`media type: ${e.mediaType}`})}});break;case`text`:case`error-text`:l=c.value;break;case`json`:case`error-json`:default:l=JSON.stringify(c.value);break}e.push({type:`tool_result`,tool_use_id:i.toolCallId,content:l,is_error:c.type===`error-text`||c.type===`error-json`?!0:void 0,cache_control:s})}break;default:{let e=r;throw Error(`Unsupported role: ${e}`)}}}s.push({role:`user`,content:e});break}case`assistant`:{let e=[];for(let t=0;t<u.messages.length;t++){let i=u.messages[t],a=t===u.messages.length-1,{content:o}=i;for(let t=0;t<o.length;t++){let s=o[t],c=t===o.length-1,l=Pe(s.providerOptions)??(c?Pe(i.providerOptions):void 0);switch(s.type){case`text`:e.push({type:`text`,text:d&&a&&c?s.text.trim():s.text,cache_control:l});break;case`reasoning`:if(n){let t=await pe({provider:`anthropic`,providerOptions:s.providerOptions,schema:st});t==null?r.push({type:`other`,message:`unsupported reasoning metadata`}):t.signature==null?t.redactedData==null?r.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 r.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}):r.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`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let n=qe.parse(t.value);e.push({type:`code_execution_tool_result`,tool_use_id:s.toolCallId,content:{type:n.type,stdout:n.stdout,stderr:n.stderr,return_code:n.return_code},cache_control:l});break}if(s.toolName===`web_fetch`){let t=s.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let n=Ue.parse(t.value);e.push({type:`web_fetch_tool_result`,tool_use_id:s.toolCallId,content:{type:`web_fetch_result`,url:n.url,retrieved_at:n.retrievedAt,content:{type:`document`,title:n.content.title,citations:n.content.citations,source:{type:n.content.source.type,media_type:n.content.source.mediaType,data:n.content.source.data}}},cache_control:l});break}if(s.toolName===`web_search`){let t=s.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let n=ze.parse(t.value);e.push({type:`web_search_tool_result`,tool_use_id:s.toolCallId,content:n.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:l});break}r.push({type:`other`,message:`provider executed tool result for tool ${s.toolName} is not supported`});break}}}s.push({role:`assistant`,content:e});break}default:{let e=f;throw Error(`content type: ${e}`)}}}return{prompt:{system:o,messages:s},betas:i}}function Qe(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 $e({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 et={webSearchResult:r.z.object({type:r.z.literal(`web_search_result_location`),cited_text:r.z.string(),url:r.z.string(),title:r.z.string(),encrypted_index:r.z.string()}),pageLocation:r.z.object({type:r.z.literal(`page_location`),cited_text:r.z.string(),document_index:r.z.number(),document_title:r.z.string().nullable(),start_page_number:r.z.number(),end_page_number:r.z.number()}),charLocation:r.z.object({type:r.z.literal(`char_location`),cited_text:r.z.string(),document_index:r.z.number(),document_title:r.z.string().nullable(),start_char_index:r.z.number(),end_char_index:r.z.number()})},tt=r.z.discriminatedUnion(`type`,[et.webSearchResult,et.pageLocation,et.charLocation]);r.z.discriminatedUnion(`type`,[et.pageLocation,et.charLocation]);function nt(e,t,n,r){if(e.type===`page_location`||e.type===`char_location`){let i=rt(e,t,n);i&&r(i)}}function rt(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??P}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:n=4096,temperature:r,topP:i,topK:a,frequencyPenalty:o,presencePenalty:s,stopSequences:c,responseFormat:l,seed:u,tools:d,toolChoice:f,providerOptions:p}){let m=[];o!=null&&m.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),s!=null&&m.push({type:`unsupported-setting`,setting:`presencePenalty`}),u!=null&&m.push({type:`unsupported-setting`,setting:`seed`}),l?.type===`json`&&(l.schema==null?m.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format requires a schema. The response format is ignored.`}):d!=null&&m.push({type:`unsupported-setting`,setting:`tools`,details:`JSON response format does not support tools. The provided tools are ignored.`}));let h=l?.type===`json`&&l.schema!=null?{type:`function`,name:`json`,description:`Respond with a JSON object.`,inputSchema:l.schema}:void 0,g=await pe({provider:`anthropic`,providerOptions:p,schema:Ne}),{prompt:_,betas:v}=await Ze({prompt:e,sendReasoning:g?.sendReasoning??!0,warnings:m}),y=g?.thinking?.type===`enabled`,b=g?.thinking?.budgetTokens,x={model:this.modelId,max_tokens:n,temperature:r,top_k:a,top_p:i,stop_sequences:c,...y&&{thinking:{type:`enabled`,budget_tokens:b}},system:_.system,messages:_.messages};if(y){if(b==null)throw new t.UnsupportedFunctionalityError({functionality:`thinking requires a budget`});x.temperature!=null&&(x.temperature=void 0,m.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported when thinking is enabled`})),a!=null&&(x.top_k=void 0,m.push({type:`unsupported-setting`,setting:`topK`,details:`topK is not supported when thinking is enabled`})),i!=null&&(x.top_p=void 0,m.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported when thinking is enabled`})),x.max_tokens=n+b}let{tools:S,toolChoice:C,toolWarnings:w,betas:T}=Ke(h==null?{tools:d??[],toolChoice:f,disableParallelToolUse:g?.disableParallelToolUse}:{tools:[h],toolChoice:{type:`tool`,toolName:h.name},disableParallelToolUse:!0});return{args:{...x,tools:S,tool_choice:C},warnings:[...m,...w],betas:new Set([...v,...T]),usesJsonResponseTool:h!=null}}async getHeaders({betas:e,headers:t}){return O(await be(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 he({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(t),failedResponseHandler:Me,successfulResponseHandler:Se(at),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)nt(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:$e({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 he({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(o),failedResponseHandler:Me,successfulResponseHandler:xe(ot),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;nt(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=$e({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}}}},at=r.z.object({type:r.z.literal(`message`),id:r.z.string().nullish(),model:r.z.string().nullish(),content:r.z.array(r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`text`),text:r.z.string(),citations:r.z.array(tt).optional()}),r.z.object({type:r.z.literal(`thinking`),thinking:r.z.string(),signature:r.z.string()}),r.z.object({type:r.z.literal(`redacted_thinking`),data:r.z.string()}),r.z.object({type:r.z.literal(`tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.unknown()}),r.z.object({type:r.z.literal(`server_tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.record(r.z.string(),r.z.unknown()).nullish()}),r.z.object({type:r.z.literal(`web_fetch_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),retrieved_at:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string().nullable(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.object({type:r.z.literal(`text`),media_type:r.z.string(),data:r.z.string()})})}),r.z.object({type:r.z.literal(`web_fetch_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`web_search_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.array(r.z.object({type:r.z.literal(`web_search_result`),url:r.z.string(),title:r.z.string(),encrypted_content:r.z.string(),page_age:r.z.string().nullish()})),r.z.object({type:r.z.literal(`web_search_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`code_execution_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),r.z.object({type:r.z.literal(`code_execution_tool_result_error`),error_code:r.z.string()})])})])),stop_reason:r.z.string().nullish(),stop_sequence:r.z.string().nullish(),usage:r.z.looseObject({input_tokens:r.z.number(),output_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish(),cache_read_input_tokens:r.z.number().nullish()})}),ot=r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`message_start`),message:r.z.object({id:r.z.string().nullish(),model:r.z.string().nullish(),usage:r.z.looseObject({input_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish(),cache_read_input_tokens:r.z.number().nullish()})})}),r.z.object({type:r.z.literal(`content_block_start`),index:r.z.number(),content_block:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`text`),text:r.z.string()}),r.z.object({type:r.z.literal(`thinking`),thinking:r.z.string()}),r.z.object({type:r.z.literal(`tool_use`),id:r.z.string(),name:r.z.string()}),r.z.object({type:r.z.literal(`redacted_thinking`),data:r.z.string()}),r.z.object({type:r.z.literal(`server_tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.record(r.z.string(),r.z.unknown()).nullish()}),r.z.object({type:r.z.literal(`web_fetch_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),retrieved_at:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string().nullable(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.object({type:r.z.literal(`text`),media_type:r.z.string(),data:r.z.string()})})}),r.z.object({type:r.z.literal(`web_fetch_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`web_search_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.array(r.z.object({type:r.z.literal(`web_search_result`),url:r.z.string(),title:r.z.string(),encrypted_content:r.z.string(),page_age:r.z.string().nullish()})),r.z.object({type:r.z.literal(`web_search_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`code_execution_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),r.z.object({type:r.z.literal(`code_execution_tool_result_error`),error_code:r.z.string()})])})])}),r.z.object({type:r.z.literal(`content_block_delta`),index:r.z.number(),delta:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`input_json_delta`),partial_json:r.z.string()}),r.z.object({type:r.z.literal(`text_delta`),text:r.z.string()}),r.z.object({type:r.z.literal(`thinking_delta`),thinking:r.z.string()}),r.z.object({type:r.z.literal(`signature_delta`),signature:r.z.string()}),r.z.object({type:r.z.literal(`citations_delta`),citation:tt})])}),r.z.object({type:r.z.literal(`content_block_stop`),index:r.z.number()}),r.z.object({type:r.z.literal(`error`),error:r.z.object({type:r.z.string(),message:r.z.string()})}),r.z.object({type:r.z.literal(`message_delta`),delta:r.z.object({stop_reason:r.z.string().nullish(),stop_sequence:r.z.string().nullish()}),usage:r.z.looseObject({output_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish()})}),r.z.object({type:r.z.literal(`message_stop`)}),r.z.object({type:r.z.literal(`ping`)})]),st=r.z.object({signature:r.z.string().optional(),redactedData:r.z.string().optional()}),ct=ve({id:`anthropic.bash_20241022`,name:`bash`,inputSchema:r.default.object({command:r.default.string(),restart:r.default.boolean().optional()})}),lt=ve({id:`anthropic.bash_20250124`,name:`bash`,inputSchema:r.default.object({command:r.default.string(),restart:r.default.boolean().optional()})}),ut=ve({id:`anthropic.computer_20241022`,name:`computer`,inputSchema:r.z.object({action:r.z.enum([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:r.z.array(r.z.number().int()).optional(),text:r.z.string().optional()})}),dt=ve({id:`anthropic.computer_20250124`,name:`computer`,inputSchema:r.z.object({action:r.z.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:r.z.tuple([r.z.number().int(),r.z.number().int()]).optional(),duration:r.z.number().optional(),scroll_amount:r.z.number().optional(),scroll_direction:r.z.enum([`up`,`down`,`left`,`right`]).optional(),start_coordinate:r.z.tuple([r.z.number().int(),r.z.number().int()]).optional(),text:r.z.string().optional()})}),ft=ve({id:`anthropic.text_editor_20241022`,name:`str_replace_editor`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),pt=ve({id:`anthropic.text_editor_20250124`,name:`str_replace_editor`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),mt=ve({id:`anthropic.text_editor_20250429`,name:`str_replace_based_edit_tool`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),ht={bash_20241022:ct,bash_20250124:lt,codeExecution_20250522:Ye,computer_20241022:ut,computer_20250124:dt,textEditor_20241022:ft,textEditor_20250124:pt,textEditor_20250429:mt,textEditor_20250728:Le,webFetch_20250910:Ge,webSearch_20250305:Ve};function gt(e={}){let n=ke(e.baseURL)??`https://api.anthropic.com/v1`,r=()=>M({"anthropic-version":`2023-06-01`,"x-api-key":ne({apiKey:e.apiKey,environmentVariableName:`ANTHROPIC_API_KEY`,description:`Anthropic`}),...e.headers},`ai-sdk/anthropic/${Ae}`),i=t=>new it(t,{provider:`anthropic.messages`,baseURL:n,headers:r,fetch:e.fetch,generateId:e.generateId??P,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})}),a=function(e){if(new.target)throw Error(`The Anthropic model function cannot be called with the new keyword.`);return i(e)};return a.languageModel=i,a.chat=i,a.messages=i,a.textEmbeddingModel=e=>{throw new t.NoSuchModelError({modelId:e,modelType:`textEmbeddingModel`})},a.imageModel=e=>{throw new t.NoSuchModelError({modelId:e,modelType:`imageModel`})},a.tools=ht,a}var _t=gt();function vt(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function yt(e){return Object.fromEntries([...e.headers])}function bt(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 xt(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function St(e,...t){let n=xt(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var Ct=({prefix:e,size:n=16,alphabet:r=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:i=`-`}={})=>{let a=()=>{let e=r.length,t=Array(n);for(let i=0;i<n;i++)t[i]=r[Math.random()*e|0];return t.join(``)};if(e==null)return a;if(r.includes(i))throw new t.InvalidArgumentError({argument:`separator`,message:`The separator "${i}" must not be part of the alphabet "${r}".`});return()=>`${e}${i}${a()}`},wt=Ct();function Tt(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Et=[`fetch failed`,`failed to fetch`];function Dt({error:e,url:n,requestBodyValues:r}){if(Tt(e))return e;if(e instanceof TypeError&&Et.includes(e.message.toLowerCase())){let i=e.cause;if(i!=null)return new t.APICallError({message:`Cannot connect to API: ${i.message}`,cause:i,url:n,requestBodyValues:r,isRetryable:!0})}return e}var Ot=`3.0.10`;function kt({apiKey:e,environmentVariableName:n,apiKeyParameterName:r=`apiKey`,description:i}){if(typeof e==`string`)return e;if(e!=null)throw new t.LoadAPIKeyError({message:`${i} API key must be a string.`});if(typeof process>`u`)throw new t.LoadAPIKeyError({message:`${i} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[n],e==null)throw new t.LoadAPIKeyError({message:`${i} API key is missing. Pass it using the '${r}' parameter or the ${n} environment variable.`});if(typeof e!=`string`)throw new t.LoadAPIKeyError({message:`${i} API key must be a string. The value of the ${n} environment variable is not a string.`});return e}var At=/"__proto__"\s*:/,jt=/"constructor"\s*:/;function Mt(e){let t=JSON.parse(e);return typeof t!=`object`||!t||At.test(e)===!1&&jt.test(e)===!1?t:Nt(t)}function Nt(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 Pt(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Mt(e)}finally{Error.stackTraceLimit=t}}var Ft=Symbol.for(`vercel.ai.validator`);function It(e){return{[Ft]:!0,validate:e}}function Lt(e){return typeof e==`object`&&!!e&&Ft in e&&e[Ft]===!0&&`validate`in e}function Rt(e){return Lt(e)?e:zt(e)}function zt(e){return It(async n=>{let r=await e[`~standard`].validate(n);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new t.TypeValidationError({value:n,cause:r.issues})}})}async function Bt({value:e,schema:n}){let r=await Vt({value:e,schema:n});if(!r.success)throw t.TypeValidationError.wrap({value:e,cause:r.error});return r.value}async function Vt({value:e,schema:n}){let r=Rt(n);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};let n=await r.validate(e);return n.success?{success:!0,value:n.value,rawValue:e}:{success:!1,error:t.TypeValidationError.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:t.TypeValidationError.wrap({value:e,cause:n}),rawValue:e}}}async function Ht({text:e,schema:n}){try{let t=Pt(e);return n==null?t:Bt({value:t,schema:n})}catch(n){throw t.JSONParseError.isInstance(n)||t.TypeValidationError.isInstance(n)?n:new t.JSONParseError({text:e,cause:n})}}async function Ut({text:e,schema:n}){try{let t=Pt(e);return n==null?{success:!0,value:t,rawValue:t}:await Vt({value:t,schema:n})}catch(n){return{success:!1,error:t.JSONParseError.isInstance(n)?n:new t.JSONParseError({text:e,cause:n}),rawValue:void 0}}}function Wt({stream:e,schema:n}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new t.EventSourceParserStream).pipeThrough(new TransformStream({async transform({data:e},t){e!==`[DONE]`&&t.enqueue(await Ut({text:e,schema:n}))}}))}async function Gt({provider:e,providerOptions:n,schema:r}){if(n?.[e]==null)return;let i=await Vt({value:n[e],schema:r});if(!i.success)throw new t.InvalidArgumentError({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:i.error});return i.value}var Kt=()=>globalThis.fetch,qt=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>Jt({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),Jt=async({url:e,headers:n={},body:r,successfulResponseHandler:i,failedResponseHandler:a,abortSignal:o,fetch:s=Kt()})=>{try{let c=await s(e,{method:`POST`,headers:St(n,`ai-sdk/provider-utils/${Ot}`,bt()),body:r.content,signal:o}),l=yt(c);if(!c.ok){let n;try{n=await a({response:c,url:e,requestBodyValues:r.values})}catch(n){throw Tt(n)||t.APICallError.isInstance(n)?n:new t.APICallError({message:`Failed to process error response`,cause:n,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw n.value}try{return await i({response:c,url:e,requestBodyValues:r.values})}catch(n){throw n instanceof Error&&(Tt(n)||t.APICallError.isInstance(n))?n:new t.APICallError({message:`Failed to process successful response`,cause:n,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(t){throw Dt({error:t,url:e,requestBodyValues:r.values})}};function Yt(e){return e}function Xt({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>Yt({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function Zt({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>Yt({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:r,execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}async function Qt(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var $t=({errorSchema:e,errorToMessage:n,isRetryable:r})=>async({response:i,url:a,requestBodyValues:o})=>{let s=await i.text(),c=yt(i);if(s.trim()===``)return{responseHeaders:c,value:new t.APICallError({message:i.statusText,url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,isRetryable:r?.(i)})};try{let l=await Ht({text:s,schema:e});return{responseHeaders:c,value:new t.APICallError({message:n(l),url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,data:l,isRetryable:r?.(i,l)})}}catch{return{responseHeaders:c,value:new t.APICallError({message:i.statusText,url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,isRetryable:r?.(i)})}}},en=e=>async({response:n})=>{let r=yt(n);if(n.body==null)throw new t.EmptyResponseBodyError({});return{responseHeaders:r,value:Wt({stream:n.body,schema:e})}},tn=e=>async({response:n,url:r,requestBodyValues:i})=>{let a=await n.text(),o=await Ut({text:a,schema:e}),s=yt(n);if(!o.success)throw new t.APICallError({message:`Invalid JSON response`,cause:o.error,statusCode:n.status,responseHeaders:s,responseBody:a,url:r,requestBodyValues:i});return{responseHeaders:s,value:o.value,rawValue:o.rawValue}},nn=Symbol(`Let zodToJsonSchema decide on which parser to use`),rn=Symbol.for(`vercel.ai.schema`),{btoa:an,atob:on}=globalThis;function sn(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return an(t)}function cn(e){return e instanceof Uint8Array?sn(e):e}function ln(e){return e?.replace(/\/$/,``)}var un=`2.0.17`,dn=r.z.object({error:r.z.object({code:r.z.number().nullable(),message:r.z.string(),status:r.z.string()})}),fn=$t({errorSchema:dn,errorToMessage:e=>e.error.message}),pn=r.z.object({outputDimensionality:r.z.number().optional(),taskType:r.z.enum([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional()}),mn=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:n,abortSignal:r,providerOptions:i}){let a=await Gt({provider:`google`,providerOptions:i,schema:pn});if(e.length>this.maxEmbeddingsPerCall)throw new t.TooManyEmbeddingValuesForCallError({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let o=vt(await Qt(this.config.headers),n);if(e.length===1){let{responseHeaders:t,value:n,rawValue:i}=await qt({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:o,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType},failedResponseHandler:fn,successfulResponseHandler:tn(gn),abortSignal:r,fetch:this.config.fetch});return{embeddings:[n.embedding.values],usage:void 0,response:{headers:t,body:i}}}let{responseHeaders:s,value:c,rawValue:l}=await qt({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:o,body:{requests:e.map(e=>({model:`models/${this.modelId}`,content:{role:`user`,parts:[{text:e}]},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType}))},failedResponseHandler:fn,successfulResponseHandler:tn(hn),abortSignal:r,fetch:this.config.fetch});return{embeddings:c.embeddings.map(e=>e.values),usage:void 0,response:{headers:s,body:l}}}},hn=r.z.object({embeddings:r.z.array(r.z.object({values:r.z.array(r.z.number())}))}),gn=r.z.object({embedding:r.z.object({values:r.z.array(r.z.number())})});function _n(e){if(e==null||vn(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]=_n(n),e),{})),a&&(p.items=Array.isArray(a)?a.map(_n):_n(a)),o&&(p.allOf=o.map(_n)),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=_n(e[0]);typeof t==`object`&&(p.nullable=!0,Object.assign(p,t))}else p.anyOf=e.map(_n),p.nullable=!0}else p.anyOf=s.map(_n);return c&&(p.oneOf=c.map(_n)),d!==void 0&&(p.minLength=d),p}function vn(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}function yn(e,n){let r=[],i=[],a=!0,o=n?.isGemmaModel??!1;for(let{role:n,content:o}of e)switch(n){case`system`:if(!a)throw new t.UnsupportedFunctionalityError({functionality:`system messages are only supported at the beginning of the conversation`});r.push({text:o});break;case`user`:{a=!1;let e=[];for(let t of o)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:cn(t.data)}});break}}i.push({role:`user`,parts:e});break}case`assistant`:a=!1,i.push({role:`model`,parts:o.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 t.UnsupportedFunctionalityError({functionality:`Only PNG images are supported in assistant messages`});if(e.data instanceof URL)throw new t.UnsupportedFunctionalityError({functionality:`File data URLs in assistant messages are not supported`});return{inlineData:{mimeType:e.mediaType,data:cn(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`:{a=!1;let e=[];for(let t of o){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}}})}i.push({role:`user`,parts:e});break}}if(o&&r.length>0&&i.length>0&&i[0].role===`user`){let e=r.map(e=>e.text).join(`
|
|
1
|
+
const e=require(`../chunk-iXuH7AlR.cjs`),t=require(`../index.node-Btg8Ii_o.cjs`);require(`../token-error-BoNG8ooW.cjs`),require(`../esm-0UNjvroT.cjs`);const n=require(`../build-EgdtUZTI.cjs`);let r=require(`zod/v4`);r=e.__toESM(r);let i=require(`zod/v3`);i=e.__toESM(i);let a=require(`node:buffer`);a=e.__toESM(a);let o=require(`node:fs`);o=e.__toESM(o);let s=require(`node:url`);s=e.__toESM(s);let c=require(`node:stream`);c=e.__toESM(c);let l=require(`node:util`);l=e.__toESM(l);let u=require(`node:crypto`);u=e.__toESM(u);let d=require(`http`);d=e.__toESM(d);let f=require(`path`);f=e.__toESM(f);let p=require(`fs`);p=e.__toESM(p);let m=require(`ai`);m=e.__toESM(m);let h=require(`fs/promises`);h=e.__toESM(h);let g=require(`child_process`);g=e.__toESM(g);let _=require(`react`);_=e.__toESM(_);let v=require(`node:module`);v=e.__toESM(v);let y=require(`zod`);y=e.__toESM(y);let b=require(`node:path`);b=e.__toESM(b);let x=require(`node:process`);x=e.__toESM(x);let S=require(`node:os`);S=e.__toESM(S);let C=require(`node:tty`);C=e.__toESM(C);let w=require(`node:readline`);w=e.__toESM(w);let T=require(`node:child_process`);T=e.__toESM(T);let E=require(`node:fs/promises`);E=e.__toESM(E),require(`@blink-sdk/compute-protocol/client`);let D=require(`@blink-sdk/compute-protocol/transport`);D=e.__toESM(D);function O(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function k(e){return Object.fromEntries([...e.headers])}function A(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 j(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function M(e,...t){let n=j(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var N=({prefix:e,size:n=16,alphabet:r=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:i=`-`}={})=>{let a=()=>{let e=r.length,t=Array(n);for(let i=0;i<n;i++)t[i]=r[Math.random()*e|0];return t.join(``)};if(e==null)return a;if(r.includes(i))throw new t.InvalidArgumentError({argument:`separator`,message:`The separator "${i}" must not be part of the alphabet "${r}".`});return()=>`${e}${i}${a()}`},P=N();function F(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var ee=[`fetch failed`,`failed to fetch`];function te({error:e,url:n,requestBodyValues:r}){if(F(e))return e;if(e instanceof TypeError&&ee.includes(e.message.toLowerCase())){let i=e.cause;if(i!=null)return new t.APICallError({message:`Cannot connect to API: ${i.message}`,cause:i,url:n,requestBodyValues:r,isRetryable:!0})}return e}var I=`3.0.10`;function ne({apiKey:e,environmentVariableName:n,apiKeyParameterName:r=`apiKey`,description:i}){if(typeof e==`string`)return e;if(e!=null)throw new t.LoadAPIKeyError({message:`${i} API key must be a string.`});if(typeof process>`u`)throw new t.LoadAPIKeyError({message:`${i} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[n],e==null)throw new t.LoadAPIKeyError({message:`${i} API key is missing. Pass it using the '${r}' parameter or the ${n} environment variable.`});if(typeof e!=`string`)throw new t.LoadAPIKeyError({message:`${i} API key must be a string. The value of the ${n} environment variable is not a string.`});return e}var L=/"__proto__"\s*:/,re=/"constructor"\s*:/;function R(e){let t=JSON.parse(e);return typeof t!=`object`||!t||L.test(e)===!1&&re.test(e)===!1?t:z(t)}function z(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 B(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return R(e)}finally{Error.stackTraceLimit=t}}var ie=Symbol.for(`vercel.ai.validator`);function ae(e){return{[ie]:!0,validate:e}}function oe(e){return typeof e==`object`&&!!e&&ie in e&&e[ie]===!0&&`validate`in e}function se(e){return oe(e)?e:ce(e)}function ce(e){return ae(async n=>{let r=await e[`~standard`].validate(n);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new t.TypeValidationError({value:n,cause:r.issues})}})}async function V({value:e,schema:n}){let r=await le({value:e,schema:n});if(!r.success)throw t.TypeValidationError.wrap({value:e,cause:r.error});return r.value}async function le({value:e,schema:n}){let r=se(n);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};let n=await r.validate(e);return n.success?{success:!0,value:n.value,rawValue:e}:{success:!1,error:t.TypeValidationError.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:t.TypeValidationError.wrap({value:e,cause:n}),rawValue:e}}}async function ue({text:e,schema:n}){try{let t=B(e);return n==null?t:V({value:t,schema:n})}catch(n){throw t.JSONParseError.isInstance(n)||t.TypeValidationError.isInstance(n)?n:new t.JSONParseError({text:e,cause:n})}}async function de({text:e,schema:n}){try{let t=B(e);return n==null?{success:!0,value:t,rawValue:t}:await le({value:t,schema:n})}catch(n){return{success:!1,error:t.JSONParseError.isInstance(n)?n:new t.JSONParseError({text:e,cause:n}),rawValue:void 0}}}function fe({stream:e,schema:n}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new t.EventSourceParserStream).pipeThrough(new TransformStream({async transform({data:e},t){e!==`[DONE]`&&t.enqueue(await de({text:e,schema:n}))}}))}async function pe({provider:e,providerOptions:n,schema:r}){if(n?.[e]==null)return;let i=await le({value:n[e],schema:r});if(!i.success)throw new t.InvalidArgumentError({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:i.error});return i.value}var me=()=>globalThis.fetch,he=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>ge({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),ge=async({url:e,headers:n={},body:r,successfulResponseHandler:i,failedResponseHandler:a,abortSignal:o,fetch:s=me()})=>{try{let c=await s(e,{method:`POST`,headers:M(n,`ai-sdk/provider-utils/${I}`,A()),body:r.content,signal:o}),l=k(c);if(!c.ok){let n;try{n=await a({response:c,url:e,requestBodyValues:r.values})}catch(n){throw F(n)||t.APICallError.isInstance(n)?n:new t.APICallError({message:`Failed to process error response`,cause:n,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw n.value}try{return await i({response:c,url:e,requestBodyValues:r.values})}catch(n){throw n instanceof Error&&(F(n)||t.APICallError.isInstance(n))?n:new t.APICallError({message:`Failed to process successful response`,cause:n,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(t){throw te({error:t,url:e,requestBodyValues:r.values})}};function _e(e){return e}function ve({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>_e({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function ye({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>_e({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:r,execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}async function be(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var H=({errorSchema:e,errorToMessage:n,isRetryable:r})=>async({response:i,url:a,requestBodyValues:o})=>{let s=await i.text(),c=k(i);if(s.trim()===``)return{responseHeaders:c,value:new t.APICallError({message:i.statusText,url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,isRetryable:r?.(i)})};try{let l=await ue({text:s,schema:e});return{responseHeaders:c,value:new t.APICallError({message:n(l),url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,data:l,isRetryable:r?.(i,l)})}}catch{return{responseHeaders:c,value:new t.APICallError({message:i.statusText,url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,isRetryable:r?.(i)})}}},xe=e=>async({response:n})=>{let r=k(n);if(n.body==null)throw new t.EmptyResponseBodyError({});return{responseHeaders:r,value:fe({stream:n.body,schema:e})}},Se=e=>async({response:n,url:r,requestBodyValues:i})=>{let a=await n.text(),o=await de({text:a,schema:e}),s=k(n);if(!o.success)throw new t.APICallError({message:`Invalid JSON response`,cause:o.error,statusCode:n.status,responseHeaders:s,responseBody:a,url:r,requestBodyValues:i});return{responseHeaders:s,value:o.value,rawValue:o.rawValue}},Ce=Symbol(`Let zodToJsonSchema decide on which parser to use`),we=Symbol.for(`vercel.ai.schema`),{btoa:Te,atob:Ee}=globalThis;function De(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return Te(t)}function Oe(e){return e instanceof Uint8Array?De(e):e}function ke(e){return e?.replace(/\/$/,``)}var Ae=`2.0.23`,je=r.z.object({type:r.z.literal(`error`),error:r.z.object({type:r.z.string(),message:r.z.string()})}),Me=H({errorSchema:je,errorToMessage:e=>e.error.message}),U=r.z.object({citations:r.z.object({enabled:r.z.boolean()}).optional(),title:r.z.string().optional(),context:r.z.string().optional()}),Ne=r.z.object({sendReasoning:r.z.boolean().optional(),thinking:r.z.object({type:r.z.union([r.z.literal(`enabled`),r.z.literal(`disabled`)]),budgetTokens:r.z.number().optional()}).optional(),disableParallelToolUse:r.z.boolean().optional(),cacheControl:r.z.object({type:r.z.literal(`ephemeral`),ttl:r.z.union([r.z.literal(`5m`),r.z.literal(`1h`)]).optional()}).optional()});function Pe(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var Fe=r.z.object({maxCharacters:r.z.number().optional()}),Ie=ve({id:`anthropic.text_editor_20250728`,name:`str_replace_based_edit_tool`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),Le=(e={})=>Ie(e),Re=r.z.object({maxUses:r.z.number().optional(),allowedDomains:r.z.array(r.z.string()).optional(),blockedDomains:r.z.array(r.z.string()).optional(),userLocation:r.z.object({type:r.z.literal(`approximate`),city:r.z.string().optional(),region:r.z.string().optional(),country:r.z.string().optional(),timezone:r.z.string().optional()}).optional()}),ze=r.z.array(r.z.object({url:r.z.string(),title:r.z.string(),pageAge:r.z.string().nullable(),encryptedContent:r.z.string(),type:r.z.literal(`web_search_result`)})),Be=ye({id:`anthropic.web_search_20250305`,name:`web_search`,inputSchema:r.z.object({query:r.z.string()}),outputSchema:ze}),Ve=(e={})=>Be(e),He=r.z.object({maxUses:r.z.number().optional(),allowedDomains:r.z.array(r.z.string()).optional(),blockedDomains:r.z.array(r.z.string()).optional(),citations:r.z.object({enabled:r.z.boolean()}).optional(),maxContentTokens:r.z.number().optional()}),Ue=r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.union([r.z.object({type:r.z.literal(`base64`),mediaType:r.z.literal(`application/pdf`),data:r.z.string()}),r.z.object({type:r.z.literal(`text`),mediaType:r.z.literal(`text/plain`),data:r.z.string()})])}),retrievedAt:r.z.string().nullable()}),We=ye({id:`anthropic.web_fetch_20250910`,name:`web_fetch`,inputSchema:r.z.object({url:r.z.string()}),outputSchema:Ue}),Ge=(e={})=>We(e);function Ke({tools:e,toolChoice:n,disableParallelToolUse:r}){e=e?.length?e:void 0;let i=[],a=new Set;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:a};let o=[];for(let t of e)switch(t.type){case`function`:{let e=Pe(t.providerOptions);o.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`:a.add(`code-execution-2025-05-22`),o.push({type:`code_execution_20250522`,name:`code_execution`});break;case`anthropic.computer_20250124`:a.add(`computer-use-2025-01-24`),o.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`:a.add(`computer-use-2024-10-22`),o.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`:a.add(`computer-use-2025-01-24`),o.push({name:`str_replace_editor`,type:`text_editor_20250124`});break;case`anthropic.text_editor_20241022`:a.add(`computer-use-2024-10-22`),o.push({name:`str_replace_editor`,type:`text_editor_20241022`});break;case`anthropic.text_editor_20250429`:a.add(`computer-use-2025-01-24`),o.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`});break;case`anthropic.text_editor_20250728`:{let e=Fe.parse(t.args);o.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250728`,max_characters:e.maxCharacters});break}case`anthropic.bash_20250124`:a.add(`computer-use-2025-01-24`),o.push({name:`bash`,type:`bash_20250124`});break;case`anthropic.bash_20241022`:a.add(`computer-use-2024-10-22`),o.push({name:`bash`,type:`bash_20241022`});break;case`anthropic.web_fetch_20250910`:{a.add(`web-fetch-2025-09-10`);let e=He.parse(t.args);o.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=Re.parse(t.args);o.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:i.push({type:`unsupported-tool`,tool:t});break}break;default:i.push({type:`unsupported-tool`,tool:t});break}if(n==null)return{tools:o,toolChoice:r?{type:`auto`,disable_parallel_tool_use:r}:void 0,toolWarnings:i,betas:a};let s=n.type;switch(s){case`auto`:return{tools:o,toolChoice:{type:`auto`,disable_parallel_tool_use:r},toolWarnings:i,betas:a};case`required`:return{tools:o,toolChoice:{type:`any`,disable_parallel_tool_use:r},toolWarnings:i,betas:a};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:a};case`tool`:return{tools:o,toolChoice:{type:`tool`,name:n.toolName,disable_parallel_tool_use:r},toolWarnings:i,betas:a};default:throw new t.UnsupportedFunctionalityError({functionality:`tool choice type: ${s}`})}}var qe=r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),Je=ye({id:`anthropic.code_execution_20250522`,name:`code_execution`,inputSchema:r.z.object({code:r.z.string()}),outputSchema:qe}),Ye=(e={})=>Je(e);function Xe(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 t.UnsupportedFunctionalityError({functionality:`URL-based text documents are not supported for citations`}):new t.UnsupportedFunctionalityError({functionality:`unsupported data type for text documents: ${typeof e}`})}async function Ze({prompt:e,sendReasoning:n,warnings:r}){let i=new Set,a=Qe(e),o,s=[];async function c(e){return(await pe({provider:`anthropic`,providerOptions:e,schema:U}))?.citations?.enabled??!1}async function l(e){let t=await pe({provider:`anthropic`,providerOptions:e,schema:U});return{title:t?.title,context:t?.context}}for(let e=0;e<a.length;e++){let u=a[e],d=e===a.length-1,f=u.type;switch(f){case`system`:if(o!=null)throw new t.UnsupportedFunctionalityError({functionality:`Multiple system messages that are separated by user/assistant messages`});o=u.messages.map(({content:e,providerOptions:t})=>({type:`text`,text:e,cache_control:Pe(t)}));break;case`user`:{let e=[];for(let n of u.messages){let{role:r,content:a}=n;switch(r){case`user`:for(let r=0;r<a.length;r++){let o=a[r],s=r===a.length-1,u=Pe(o.providerOptions)??(s?Pe(n.providerOptions):void 0);switch(o.type){case`text`:e.push({type:`text`,text:o.text,cache_control:u});break;case`file`:if(o.mediaType.startsWith(`image/`))e.push({type:`image`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`base64`,media_type:o.mediaType===`image/*`?`image/jpeg`:o.mediaType,data:Oe(o.data)},cache_control:u});else if(o.mediaType===`application/pdf`){i.add(`pdfs-2024-09-25`);let t=await c(o.providerOptions),n=await l(o.providerOptions);e.push({type:`document`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`base64`,media_type:`application/pdf`,data:Oe(o.data)},title:n.title??o.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:u})}else if(o.mediaType===`text/plain`){let t=await c(o.providerOptions),n=await l(o.providerOptions);e.push({type:`document`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`text`,media_type:`text/plain`,data:Xe(o.data)},title:n.title??o.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:u})}else throw new t.UnsupportedFunctionalityError({functionality:`media type: ${o.mediaType}`});break}}break;case`tool`:for(let r=0;r<a.length;r++){let i=a[r],o=r===a.length-1,s=Pe(i.providerOptions)??(o?Pe(n.providerOptions):void 0),c=i.output,l;switch(c.type){case`content`:l=c.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 t.UnsupportedFunctionalityError({functionality:`media type: ${e.mediaType}`})}});break;case`text`:case`error-text`:l=c.value;break;case`json`:case`error-json`:default:l=JSON.stringify(c.value);break}e.push({type:`tool_result`,tool_use_id:i.toolCallId,content:l,is_error:c.type===`error-text`||c.type===`error-json`?!0:void 0,cache_control:s})}break;default:{let e=r;throw Error(`Unsupported role: ${e}`)}}}s.push({role:`user`,content:e});break}case`assistant`:{let e=[];for(let t=0;t<u.messages.length;t++){let i=u.messages[t],a=t===u.messages.length-1,{content:o}=i;for(let t=0;t<o.length;t++){let s=o[t],c=t===o.length-1,l=Pe(s.providerOptions)??(c?Pe(i.providerOptions):void 0);switch(s.type){case`text`:e.push({type:`text`,text:d&&a&&c?s.text.trim():s.text,cache_control:l});break;case`reasoning`:if(n){let t=await pe({provider:`anthropic`,providerOptions:s.providerOptions,schema:st});t==null?r.push({type:`other`,message:`unsupported reasoning metadata`}):t.signature==null?t.redactedData==null?r.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 r.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}):r.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`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let n=qe.parse(t.value);e.push({type:`code_execution_tool_result`,tool_use_id:s.toolCallId,content:{type:n.type,stdout:n.stdout,stderr:n.stderr,return_code:n.return_code},cache_control:l});break}if(s.toolName===`web_fetch`){let t=s.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let n=Ue.parse(t.value);e.push({type:`web_fetch_tool_result`,tool_use_id:s.toolCallId,content:{type:`web_fetch_result`,url:n.url,retrieved_at:n.retrievedAt,content:{type:`document`,title:n.content.title,citations:n.content.citations,source:{type:n.content.source.type,media_type:n.content.source.mediaType,data:n.content.source.data}}},cache_control:l});break}if(s.toolName===`web_search`){let t=s.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let n=ze.parse(t.value);e.push({type:`web_search_tool_result`,tool_use_id:s.toolCallId,content:n.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:l});break}r.push({type:`other`,message:`provider executed tool result for tool ${s.toolName} is not supported`});break}}}s.push({role:`assistant`,content:e});break}default:{let e=f;throw Error(`content type: ${e}`)}}}return{prompt:{system:o,messages:s},betas:i}}function Qe(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 $e({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 et={webSearchResult:r.z.object({type:r.z.literal(`web_search_result_location`),cited_text:r.z.string(),url:r.z.string(),title:r.z.string(),encrypted_index:r.z.string()}),pageLocation:r.z.object({type:r.z.literal(`page_location`),cited_text:r.z.string(),document_index:r.z.number(),document_title:r.z.string().nullable(),start_page_number:r.z.number(),end_page_number:r.z.number()}),charLocation:r.z.object({type:r.z.literal(`char_location`),cited_text:r.z.string(),document_index:r.z.number(),document_title:r.z.string().nullable(),start_char_index:r.z.number(),end_char_index:r.z.number()})},tt=r.z.discriminatedUnion(`type`,[et.webSearchResult,et.pageLocation,et.charLocation]);r.z.discriminatedUnion(`type`,[et.pageLocation,et.charLocation]);function nt(e,t,n,r){if(e.type===`page_location`||e.type===`char_location`){let i=rt(e,t,n);i&&r(i)}}function rt(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??P}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:n=4096,temperature:r,topP:i,topK:a,frequencyPenalty:o,presencePenalty:s,stopSequences:c,responseFormat:l,seed:u,tools:d,toolChoice:f,providerOptions:p}){let m=[];o!=null&&m.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),s!=null&&m.push({type:`unsupported-setting`,setting:`presencePenalty`}),u!=null&&m.push({type:`unsupported-setting`,setting:`seed`}),l?.type===`json`&&(l.schema==null?m.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format requires a schema. The response format is ignored.`}):d!=null&&m.push({type:`unsupported-setting`,setting:`tools`,details:`JSON response format does not support tools. The provided tools are ignored.`}));let h=l?.type===`json`&&l.schema!=null?{type:`function`,name:`json`,description:`Respond with a JSON object.`,inputSchema:l.schema}:void 0,g=await pe({provider:`anthropic`,providerOptions:p,schema:Ne}),{prompt:_,betas:v}=await Ze({prompt:e,sendReasoning:g?.sendReasoning??!0,warnings:m}),y=g?.thinking?.type===`enabled`,b=g?.thinking?.budgetTokens,x={model:this.modelId,max_tokens:n,temperature:r,top_k:a,top_p:i,stop_sequences:c,...y&&{thinking:{type:`enabled`,budget_tokens:b}},system:_.system,messages:_.messages};if(y){if(b==null)throw new t.UnsupportedFunctionalityError({functionality:`thinking requires a budget`});x.temperature!=null&&(x.temperature=void 0,m.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported when thinking is enabled`})),a!=null&&(x.top_k=void 0,m.push({type:`unsupported-setting`,setting:`topK`,details:`topK is not supported when thinking is enabled`})),i!=null&&(x.top_p=void 0,m.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported when thinking is enabled`})),x.max_tokens=n+b}let{tools:S,toolChoice:C,toolWarnings:w,betas:T}=Ke(h==null?{tools:d??[],toolChoice:f,disableParallelToolUse:g?.disableParallelToolUse}:{tools:[h],toolChoice:{type:`tool`,toolName:h.name},disableParallelToolUse:!0});return{args:{...x,tools:S,tool_choice:C},warnings:[...m,...w],betas:new Set([...v,...T]),usesJsonResponseTool:h!=null}}async getHeaders({betas:e,headers:t}){return O(await be(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 he({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(t),failedResponseHandler:Me,successfulResponseHandler:Se(at),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)nt(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:$e({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 he({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(o),failedResponseHandler:Me,successfulResponseHandler:xe(ot),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;nt(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=$e({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}}}},at=r.z.object({type:r.z.literal(`message`),id:r.z.string().nullish(),model:r.z.string().nullish(),content:r.z.array(r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`text`),text:r.z.string(),citations:r.z.array(tt).optional()}),r.z.object({type:r.z.literal(`thinking`),thinking:r.z.string(),signature:r.z.string()}),r.z.object({type:r.z.literal(`redacted_thinking`),data:r.z.string()}),r.z.object({type:r.z.literal(`tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.unknown()}),r.z.object({type:r.z.literal(`server_tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.record(r.z.string(),r.z.unknown()).nullish()}),r.z.object({type:r.z.literal(`web_fetch_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),retrieved_at:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string().nullable(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.object({type:r.z.literal(`text`),media_type:r.z.string(),data:r.z.string()})})}),r.z.object({type:r.z.literal(`web_fetch_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`web_search_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.array(r.z.object({type:r.z.literal(`web_search_result`),url:r.z.string(),title:r.z.string(),encrypted_content:r.z.string(),page_age:r.z.string().nullish()})),r.z.object({type:r.z.literal(`web_search_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`code_execution_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),r.z.object({type:r.z.literal(`code_execution_tool_result_error`),error_code:r.z.string()})])})])),stop_reason:r.z.string().nullish(),stop_sequence:r.z.string().nullish(),usage:r.z.looseObject({input_tokens:r.z.number(),output_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish(),cache_read_input_tokens:r.z.number().nullish()})}),ot=r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`message_start`),message:r.z.object({id:r.z.string().nullish(),model:r.z.string().nullish(),usage:r.z.looseObject({input_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish(),cache_read_input_tokens:r.z.number().nullish()})})}),r.z.object({type:r.z.literal(`content_block_start`),index:r.z.number(),content_block:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`text`),text:r.z.string()}),r.z.object({type:r.z.literal(`thinking`),thinking:r.z.string()}),r.z.object({type:r.z.literal(`tool_use`),id:r.z.string(),name:r.z.string()}),r.z.object({type:r.z.literal(`redacted_thinking`),data:r.z.string()}),r.z.object({type:r.z.literal(`server_tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.record(r.z.string(),r.z.unknown()).nullish()}),r.z.object({type:r.z.literal(`web_fetch_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),retrieved_at:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string().nullable(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.object({type:r.z.literal(`text`),media_type:r.z.string(),data:r.z.string()})})}),r.z.object({type:r.z.literal(`web_fetch_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`web_search_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.array(r.z.object({type:r.z.literal(`web_search_result`),url:r.z.string(),title:r.z.string(),encrypted_content:r.z.string(),page_age:r.z.string().nullish()})),r.z.object({type:r.z.literal(`web_search_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`code_execution_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),r.z.object({type:r.z.literal(`code_execution_tool_result_error`),error_code:r.z.string()})])})])}),r.z.object({type:r.z.literal(`content_block_delta`),index:r.z.number(),delta:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`input_json_delta`),partial_json:r.z.string()}),r.z.object({type:r.z.literal(`text_delta`),text:r.z.string()}),r.z.object({type:r.z.literal(`thinking_delta`),thinking:r.z.string()}),r.z.object({type:r.z.literal(`signature_delta`),signature:r.z.string()}),r.z.object({type:r.z.literal(`citations_delta`),citation:tt})])}),r.z.object({type:r.z.literal(`content_block_stop`),index:r.z.number()}),r.z.object({type:r.z.literal(`error`),error:r.z.object({type:r.z.string(),message:r.z.string()})}),r.z.object({type:r.z.literal(`message_delta`),delta:r.z.object({stop_reason:r.z.string().nullish(),stop_sequence:r.z.string().nullish()}),usage:r.z.looseObject({output_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish()})}),r.z.object({type:r.z.literal(`message_stop`)}),r.z.object({type:r.z.literal(`ping`)})]),st=r.z.object({signature:r.z.string().optional(),redactedData:r.z.string().optional()}),ct=ve({id:`anthropic.bash_20241022`,name:`bash`,inputSchema:r.default.object({command:r.default.string(),restart:r.default.boolean().optional()})}),lt=ve({id:`anthropic.bash_20250124`,name:`bash`,inputSchema:r.default.object({command:r.default.string(),restart:r.default.boolean().optional()})}),ut=ve({id:`anthropic.computer_20241022`,name:`computer`,inputSchema:r.z.object({action:r.z.enum([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:r.z.array(r.z.number().int()).optional(),text:r.z.string().optional()})}),dt=ve({id:`anthropic.computer_20250124`,name:`computer`,inputSchema:r.z.object({action:r.z.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:r.z.tuple([r.z.number().int(),r.z.number().int()]).optional(),duration:r.z.number().optional(),scroll_amount:r.z.number().optional(),scroll_direction:r.z.enum([`up`,`down`,`left`,`right`]).optional(),start_coordinate:r.z.tuple([r.z.number().int(),r.z.number().int()]).optional(),text:r.z.string().optional()})}),ft=ve({id:`anthropic.text_editor_20241022`,name:`str_replace_editor`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),pt=ve({id:`anthropic.text_editor_20250124`,name:`str_replace_editor`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),mt=ve({id:`anthropic.text_editor_20250429`,name:`str_replace_based_edit_tool`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),ht={bash_20241022:ct,bash_20250124:lt,codeExecution_20250522:Ye,computer_20241022:ut,computer_20250124:dt,textEditor_20241022:ft,textEditor_20250124:pt,textEditor_20250429:mt,textEditor_20250728:Le,webFetch_20250910:Ge,webSearch_20250305:Ve};function gt(e={}){let n=ke(e.baseURL)??`https://api.anthropic.com/v1`,r=()=>M({"anthropic-version":`2023-06-01`,"x-api-key":ne({apiKey:e.apiKey,environmentVariableName:`ANTHROPIC_API_KEY`,description:`Anthropic`}),...e.headers},`ai-sdk/anthropic/${Ae}`),i=t=>new it(t,{provider:`anthropic.messages`,baseURL:n,headers:r,fetch:e.fetch,generateId:e.generateId??P,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})}),a=function(e){if(new.target)throw Error(`The Anthropic model function cannot be called with the new keyword.`);return i(e)};return a.languageModel=i,a.chat=i,a.messages=i,a.textEmbeddingModel=e=>{throw new t.NoSuchModelError({modelId:e,modelType:`textEmbeddingModel`})},a.imageModel=e=>{throw new t.NoSuchModelError({modelId:e,modelType:`imageModel`})},a.tools=ht,a}var _t=gt();function vt(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function yt(e){return Object.fromEntries([...e.headers])}function bt(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 xt(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function St(e,...t){let n=xt(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var Ct=({prefix:e,size:n=16,alphabet:r=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:i=`-`}={})=>{let a=()=>{let e=r.length,t=Array(n);for(let i=0;i<n;i++)t[i]=r[Math.random()*e|0];return t.join(``)};if(e==null)return a;if(r.includes(i))throw new t.InvalidArgumentError({argument:`separator`,message:`The separator "${i}" must not be part of the alphabet "${r}".`});return()=>`${e}${i}${a()}`},wt=Ct();function Tt(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Et=[`fetch failed`,`failed to fetch`];function Dt({error:e,url:n,requestBodyValues:r}){if(Tt(e))return e;if(e instanceof TypeError&&Et.includes(e.message.toLowerCase())){let i=e.cause;if(i!=null)return new t.APICallError({message:`Cannot connect to API: ${i.message}`,cause:i,url:n,requestBodyValues:r,isRetryable:!0})}return e}var Ot=`3.0.10`;function kt({apiKey:e,environmentVariableName:n,apiKeyParameterName:r=`apiKey`,description:i}){if(typeof e==`string`)return e;if(e!=null)throw new t.LoadAPIKeyError({message:`${i} API key must be a string.`});if(typeof process>`u`)throw new t.LoadAPIKeyError({message:`${i} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[n],e==null)throw new t.LoadAPIKeyError({message:`${i} API key is missing. Pass it using the '${r}' parameter or the ${n} environment variable.`});if(typeof e!=`string`)throw new t.LoadAPIKeyError({message:`${i} API key must be a string. The value of the ${n} environment variable is not a string.`});return e}var At=/"__proto__"\s*:/,jt=/"constructor"\s*:/;function Mt(e){let t=JSON.parse(e);return typeof t!=`object`||!t||At.test(e)===!1&&jt.test(e)===!1?t:Nt(t)}function Nt(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 Pt(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Mt(e)}finally{Error.stackTraceLimit=t}}var Ft=Symbol.for(`vercel.ai.validator`);function It(e){return{[Ft]:!0,validate:e}}function Lt(e){return typeof e==`object`&&!!e&&Ft in e&&e[Ft]===!0&&`validate`in e}function Rt(e){return Lt(e)?e:zt(e)}function zt(e){return It(async n=>{let r=await e[`~standard`].validate(n);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new t.TypeValidationError({value:n,cause:r.issues})}})}async function Bt({value:e,schema:n}){let r=await Vt({value:e,schema:n});if(!r.success)throw t.TypeValidationError.wrap({value:e,cause:r.error});return r.value}async function Vt({value:e,schema:n}){let r=Rt(n);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};let n=await r.validate(e);return n.success?{success:!0,value:n.value,rawValue:e}:{success:!1,error:t.TypeValidationError.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:t.TypeValidationError.wrap({value:e,cause:n}),rawValue:e}}}async function Ht({text:e,schema:n}){try{let t=Pt(e);return n==null?t:Bt({value:t,schema:n})}catch(n){throw t.JSONParseError.isInstance(n)||t.TypeValidationError.isInstance(n)?n:new t.JSONParseError({text:e,cause:n})}}async function Ut({text:e,schema:n}){try{let t=Pt(e);return n==null?{success:!0,value:t,rawValue:t}:await Vt({value:t,schema:n})}catch(n){return{success:!1,error:t.JSONParseError.isInstance(n)?n:new t.JSONParseError({text:e,cause:n}),rawValue:void 0}}}function Wt({stream:e,schema:n}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new t.EventSourceParserStream).pipeThrough(new TransformStream({async transform({data:e},t){e!==`[DONE]`&&t.enqueue(await Ut({text:e,schema:n}))}}))}async function Gt({provider:e,providerOptions:n,schema:r}){if(n?.[e]==null)return;let i=await Vt({value:n[e],schema:r});if(!i.success)throw new t.InvalidArgumentError({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:i.error});return i.value}var Kt=()=>globalThis.fetch,qt=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>Jt({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),Jt=async({url:e,headers:n={},body:r,successfulResponseHandler:i,failedResponseHandler:a,abortSignal:o,fetch:s=Kt()})=>{try{let c=await s(e,{method:`POST`,headers:St(n,`ai-sdk/provider-utils/${Ot}`,bt()),body:r.content,signal:o}),l=yt(c);if(!c.ok){let n;try{n=await a({response:c,url:e,requestBodyValues:r.values})}catch(n){throw Tt(n)||t.APICallError.isInstance(n)?n:new t.APICallError({message:`Failed to process error response`,cause:n,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw n.value}try{return await i({response:c,url:e,requestBodyValues:r.values})}catch(n){throw n instanceof Error&&(Tt(n)||t.APICallError.isInstance(n))?n:new t.APICallError({message:`Failed to process successful response`,cause:n,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(t){throw Dt({error:t,url:e,requestBodyValues:r.values})}};function Yt(e){return e}function Xt({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>Yt({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function Zt({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>Yt({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:r,execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}async function Qt(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var $t=({errorSchema:e,errorToMessage:n,isRetryable:r})=>async({response:i,url:a,requestBodyValues:o})=>{let s=await i.text(),c=yt(i);if(s.trim()===``)return{responseHeaders:c,value:new t.APICallError({message:i.statusText,url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,isRetryable:r?.(i)})};try{let l=await Ht({text:s,schema:e});return{responseHeaders:c,value:new t.APICallError({message:n(l),url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,data:l,isRetryable:r?.(i,l)})}}catch{return{responseHeaders:c,value:new t.APICallError({message:i.statusText,url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,isRetryable:r?.(i)})}}},en=e=>async({response:n})=>{let r=yt(n);if(n.body==null)throw new t.EmptyResponseBodyError({});return{responseHeaders:r,value:Wt({stream:n.body,schema:e})}},tn=e=>async({response:n,url:r,requestBodyValues:i})=>{let a=await n.text(),o=await Ut({text:a,schema:e}),s=yt(n);if(!o.success)throw new t.APICallError({message:`Invalid JSON response`,cause:o.error,statusCode:n.status,responseHeaders:s,responseBody:a,url:r,requestBodyValues:i});return{responseHeaders:s,value:o.value,rawValue:o.rawValue}},nn=Symbol(`Let zodToJsonSchema decide on which parser to use`),rn=Symbol.for(`vercel.ai.schema`),{btoa:an,atob:on}=globalThis;function sn(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return an(t)}function cn(e){return e instanceof Uint8Array?sn(e):e}function ln(e){return e?.replace(/\/$/,``)}var un=`2.0.17`,dn=r.z.object({error:r.z.object({code:r.z.number().nullable(),message:r.z.string(),status:r.z.string()})}),fn=$t({errorSchema:dn,errorToMessage:e=>e.error.message}),pn=r.z.object({outputDimensionality:r.z.number().optional(),taskType:r.z.enum([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional()}),mn=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:n,abortSignal:r,providerOptions:i}){let a=await Gt({provider:`google`,providerOptions:i,schema:pn});if(e.length>this.maxEmbeddingsPerCall)throw new t.TooManyEmbeddingValuesForCallError({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let o=vt(await Qt(this.config.headers),n);if(e.length===1){let{responseHeaders:t,value:n,rawValue:i}=await qt({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:o,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType},failedResponseHandler:fn,successfulResponseHandler:tn(gn),abortSignal:r,fetch:this.config.fetch});return{embeddings:[n.embedding.values],usage:void 0,response:{headers:t,body:i}}}let{responseHeaders:s,value:c,rawValue:l}=await qt({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:o,body:{requests:e.map(e=>({model:`models/${this.modelId}`,content:{role:`user`,parts:[{text:e}]},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType}))},failedResponseHandler:fn,successfulResponseHandler:tn(hn),abortSignal:r,fetch:this.config.fetch});return{embeddings:c.embeddings.map(e=>e.values),usage:void 0,response:{headers:s,body:l}}}},hn=r.z.object({embeddings:r.z.array(r.z.object({values:r.z.array(r.z.number())}))}),gn=r.z.object({embedding:r.z.object({values:r.z.array(r.z.number())})});function _n(e){if(e==null||vn(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]=_n(n),e),{})),a&&(p.items=Array.isArray(a)?a.map(_n):_n(a)),o&&(p.allOf=o.map(_n)),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=_n(e[0]);typeof t==`object`&&(p.nullable=!0,Object.assign(p,t))}else p.anyOf=e.map(_n),p.nullable=!0}else p.anyOf=s.map(_n);return c&&(p.oneOf=c.map(_n)),d!==void 0&&(p.minLength=d),p}function vn(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}function yn(e,n){let r=[],i=[],a=!0,o=n?.isGemmaModel??!1;for(let{role:n,content:o}of e)switch(n){case`system`:if(!a)throw new t.UnsupportedFunctionalityError({functionality:`system messages are only supported at the beginning of the conversation`});r.push({text:o});break;case`user`:{a=!1;let e=[];for(let t of o)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:cn(t.data)}});break}}i.push({role:`user`,parts:e});break}case`assistant`:a=!1,i.push({role:`model`,parts:o.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 t.UnsupportedFunctionalityError({functionality:`Only PNG images are supported in assistant messages`});if(e.data instanceof URL)throw new t.UnsupportedFunctionalityError({functionality:`File data URLs in assistant messages are not supported`});return{inlineData:{mimeType:e.mediaType,data:cn(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`:{a=!1;let e=[];for(let t of o){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}}})}i.push({role:`user`,parts:e});break}}if(o&&r.length>0&&i.length>0&&i[0].role===`user`){let e=r.map(e=>e.text).join(`
|
|
2
2
|
|
|
3
3
|
`);i[0].parts.unshift({text:e+`
|
|
4
4
|
|
|
@@ -218,7 +218,620 @@ Use this for:
|
|
|
218
218
|
- Extracting relevant information from verbose output
|
|
219
219
|
- Analyzing build or test results
|
|
220
220
|
|
|
221
|
-
Example: After running tests with \`workspace_bash\`, use this to find all FAIL: lines rather than re-running the test command.`,inputSchema:y.z.object({pid:y.z.number(),pattern:y.z.string(),before_lines:y.z.number(),after_lines:y.z.number()}),execute:async(t,n)=>{let r;try{r=new RegExp(t.pattern)}catch{throw Error(`Invalid regex pattern: ${t.pattern}`)}let{lines:i}=await(await e()).request(`process_read_plain_output`,{pid:t.pid},{signal:n.abortSignal}),a=[];for(let e=0;e<i.length;e++)if(i[e].match(r)){let n=Math.max(0,e-t.before_lines),r=Math.min(i.length-1,e+t.after_lines),o=i.slice(n,r+1);a.push({line_number:e,lines:o})}if(a.length>256)throw Error(`Too many matches. Please refine your search.`);return{matches:a,total_matches:a.length}}}))},b_=async function*({client:e,pid:t,abortSignal:n,timeoutMs:r}){let i=await e,a=[],o=null,s=!1,c=null,l=``,u=i.onNotification(`process_output`,e=>{e.pid===t&&(l+=e.output,a.push({pid:t,ansiOutput:l}),o?.())}),d=i.request(`process_wait`,{pid:t,output_idle_timeout_ms:3e3,timeout_ms:r??25e3},{signal:n}).then(e=>{a.push({pid:e.pid,title:e.title,command:e.command,args:e.args,cwd:e.cwd,env:e.env,ansiOutput:e.ansi_output,plainOutput:{totalLines:e.plain_output.total_lines,lines:e.plain_output.lines},durationMs:e.duration_ms,exitCode:e.exit_code,exitSignal:e.exit_signal,stillRunning:typeof e.exit_code!=`number`&&typeof e.exit_signal!=`number`}),s=!0,o?.()}).catch(e=>{c=e,s=!0,o?.()});try{for(;!s||a.length>0;){if(c)throw c;for(a.length===0&&(await new Promise(e=>{o=e}),o=null);a.length>0;)yield a.shift()}await d}finally{u.dispose()}};y.z.union([y.z.object({pid:y.z.number(),ansiOutput:y.z.string()}),y.z.object({pid:y.z.number(),title:y.z.string().optional(),command:y.z.string(),args:y.z.array(y.z.string()),cwd:y.z.string(),env:y.z.record(y.z.string(),y.z.string()),ansiOutput:y.z.string(),plainOutput:y.z.object({totalLines:y.z.number(),lines:y.z.array(y.z.string())}),durationMs:y.z.number(),exitCode:y.z.number().optional(),exitSignal:y.z.number().optional(),stillRunning:y.z.boolean()})]);const x_=(e,t)=>{if(t.length===0)return 0;let n=0,r=0;for(;(r=e.indexOf(t,r))!==-1;)n++,r+=t.length;return n},S_=(e,t,n)=>t.length===0?e:e.split(t).join(n),C_={
|
|
221
|
+
Example: After running tests with \`workspace_bash\`, use this to find all FAIL: lines rather than re-running the test command.`,inputSchema:y.z.object({pid:y.z.number(),pattern:y.z.string(),before_lines:y.z.number(),after_lines:y.z.number()}),execute:async(t,n)=>{let r;try{r=new RegExp(t.pattern)}catch{throw Error(`Invalid regex pattern: ${t.pattern}`)}let{lines:i}=await(await e()).request(`process_read_plain_output`,{pid:t.pid},{signal:n.abortSignal}),a=[];for(let e=0;e<i.length;e++)if(i[e].match(r)){let n=Math.max(0,e-t.before_lines),r=Math.min(i.length-1,e+t.after_lines),o=i.slice(n,r+1);a.push({line_number:e,lines:o})}if(a.length>256)throw Error(`Too many matches. Please refine your search.`);return{matches:a,total_matches:a.length}}}))},b_=async function*({client:e,pid:t,abortSignal:n,timeoutMs:r}){let i=await e,a=[],o=null,s=!1,c=null,l=``,u=i.onNotification(`process_output`,e=>{e.pid===t&&(l+=e.output,a.push({pid:t,ansiOutput:l}),o?.())}),d=i.request(`process_wait`,{pid:t,output_idle_timeout_ms:3e3,timeout_ms:r??25e3},{signal:n}).then(e=>{a.push({pid:e.pid,title:e.title,command:e.command,args:e.args,cwd:e.cwd,env:e.env,ansiOutput:e.ansi_output,plainOutput:{totalLines:e.plain_output.total_lines,lines:e.plain_output.lines},durationMs:e.duration_ms,exitCode:e.exit_code,exitSignal:e.exit_signal,stillRunning:typeof e.exit_code!=`number`&&typeof e.exit_signal!=`number`}),s=!0,o?.()}).catch(e=>{c=e,s=!0,o?.()});try{for(;!s||a.length>0;){if(c)throw c;for(a.length===0&&(await new Promise(e=>{o=e}),o=null);a.length>0;)yield a.shift()}await d}finally{u.dispose()}};y.z.union([y.z.object({pid:y.z.number(),ansiOutput:y.z.string()}),y.z.object({pid:y.z.number(),title:y.z.string().optional(),command:y.z.string(),args:y.z.array(y.z.string()),cwd:y.z.string(),env:y.z.record(y.z.string(),y.z.string()),ansiOutput:y.z.string(),plainOutput:y.z.object({totalLines:y.z.number(),lines:y.z.array(y.z.string())}),durationMs:y.z.number(),exitCode:y.z.number().optional(),exitSignal:y.z.number().optional(),stillRunning:y.z.boolean()})]);const x_=(e,t)=>{if(t.length===0)return 0;let n=0,r=0;for(;(r=e.indexOf(t,r))!==-1;)n++,r+=t.length;return n},S_=(e,t,n)=>t.length===0?e:e.split(t).join(n),C_={scout:{".env.local.hbs":`# Store local environment variables here.
|
|
222
|
+
# They will be used by blink dev for development.
|
|
223
|
+
{{#each envLocal}}
|
|
224
|
+
{{this.[0]}}={{this.[1]}}
|
|
225
|
+
{{/each}}
|
|
226
|
+
{{#unless (hasAnyEnvVar envLocal "OPENAI_API_KEY" "ANTHROPIC_API_KEY" "AI_GATEWAY_API_KEY")}}
|
|
227
|
+
# OPENAI_API_KEY=
|
|
228
|
+
# ANTHROPIC_API_KEY=
|
|
229
|
+
# AI_GATEWAY_API_KEY=
|
|
230
|
+
{{/unless}}
|
|
231
|
+
|
|
232
|
+
# Web search (optional - get an API key from https://exa.ai)
|
|
233
|
+
# EXA_API_KEY=
|
|
234
|
+
|
|
235
|
+
# Coder credentials (optional - for production compute)
|
|
236
|
+
# CODER_URL=
|
|
237
|
+
# CODER_SESSION_TOKEN=
|
|
238
|
+
# CODER_TEMPLATE=
|
|
239
|
+
# CODER_PRESET_NAME=
|
|
240
|
+
`,".env.production":`# Store production environment variables here.
|
|
241
|
+
# They will be upserted as secrets on blink deploy.
|
|
242
|
+
# OPENAI_API_KEY=
|
|
243
|
+
# ANTHROPIC_API_KEY=
|
|
244
|
+
# AI_GATEWAY_API_KEY=
|
|
245
|
+
|
|
246
|
+
# Slack App credentials
|
|
247
|
+
# SLACK_BOT_TOKEN=
|
|
248
|
+
# SLACK_SIGNING_SECRET=
|
|
249
|
+
|
|
250
|
+
# GitHub App credentials
|
|
251
|
+
# GITHUB_APP_ID=
|
|
252
|
+
# GITHUB_CLIENT_ID=
|
|
253
|
+
# GITHUB_CLIENT_SECRET=
|
|
254
|
+
# GITHUB_WEBHOOK_SECRET=
|
|
255
|
+
# GITHUB_PRIVATE_KEY=
|
|
256
|
+
|
|
257
|
+
# Web search
|
|
258
|
+
# EXA_API_KEY=
|
|
259
|
+
|
|
260
|
+
# Coder credentials (recommended for production)
|
|
261
|
+
# CODER_URL=
|
|
262
|
+
# CODER_SESSION_TOKEN=
|
|
263
|
+
# CODER_TEMPLATE=
|
|
264
|
+
# CODER_PRESET_NAME=
|
|
265
|
+
`,".gitignore":`# dependencies
|
|
266
|
+
node_modules
|
|
267
|
+
|
|
268
|
+
# config and build
|
|
269
|
+
.blink/*
|
|
270
|
+
!.blink/config.json
|
|
271
|
+
|
|
272
|
+
# dotenv environment variables file
|
|
273
|
+
.env
|
|
274
|
+
.env.*
|
|
275
|
+
|
|
276
|
+
# Finder (MacOS) folder config
|
|
277
|
+
.DS_Store
|
|
278
|
+
`,"AGENTS.md":`This project is a Blink agent.
|
|
279
|
+
|
|
280
|
+
You are an expert software engineer, which makes you an expert agent developer. You are highly idiomatic, opinionated, concise, and precise. The user prefers accuracy over speed.
|
|
281
|
+
|
|
282
|
+
<communication>
|
|
283
|
+
1. Be concise, direct, and to the point.
|
|
284
|
+
2. You are communicating via a terminal interface, so avoid verbosity, preambles, postambles, and unnecessary whitespace.
|
|
285
|
+
3. NEVER use emojis unless the user explicitly asks for them.
|
|
286
|
+
4. You must avoid text before/after your response, such as "The answer is" or "Short answer:", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...".
|
|
287
|
+
5. Mimic the style of the user's messages.
|
|
288
|
+
6. Do not remind the user you are happy to help.
|
|
289
|
+
7. Do not act with sycophantic flattery or over-the-top enthusiasm.
|
|
290
|
+
8. Do not regurgitate tool output. e.g. if a command succeeds, acknowledge briefly (e.g. "Done" or "Formatted").
|
|
291
|
+
9. *NEVER* create markdown files for the user - *always* guide the user through your efforts.
|
|
292
|
+
10. *NEVER* create example scripts for the user, or examples scripts for you to run. Leverage your tools to accomplish the user's goals.
|
|
293
|
+
</communication>
|
|
294
|
+
|
|
295
|
+
<goals>
|
|
296
|
+
Your method of assisting the user is by iterating their agent using the context provided by the user in run mode.
|
|
297
|
+
|
|
298
|
+
You can obtain additional context by leveraging web search and compute tools to read files, run commands, and search the web.
|
|
299
|
+
|
|
300
|
+
The user is _extremely happy_ to provide additional context. They prefer this over you guessing, and then potentially getting it wrong.
|
|
301
|
+
|
|
302
|
+
<example>
|
|
303
|
+
user: i want a coding agent
|
|
304
|
+
assistant: Let me take a look at your codebase...
|
|
305
|
+
... tool calls to investigate the codebase...
|
|
306
|
+
assistant: I've created tools for linting, testing, and formatting. Hop back in run mode to use your agent! If you ever encounter undesired behavior from your agent, switch back to edit mode to refine your agent.
|
|
307
|
+
</example>
|
|
308
|
+
|
|
309
|
+
Always investigate the current state of the agent before assisting the user.
|
|
310
|
+
</goals>
|
|
311
|
+
|
|
312
|
+
<agent_development>
|
|
313
|
+
Agents are written in TypeScript, and mostly stored in a single \`agent.ts\` file. Complex agents will have multiple files, like a proper codebase.
|
|
314
|
+
|
|
315
|
+
Environment variables are stored in \`.env.local\` and \`.env.production\`. \`blink dev\` will hot-reload environment variable changes in \`.env.local\`.
|
|
316
|
+
|
|
317
|
+
Changes to the agent are hot-reloaded. As you make edits, the user can immediately try them in run mode.
|
|
318
|
+
|
|
319
|
+
1. _ALWAYS_ use the package manager the user is using (inferred from lock files or \`process.argv\`).
|
|
320
|
+
2. You _MUST_ use \`agent.store\` to persist state. The agent process is designed to be stateless.
|
|
321
|
+
3. Test your changes to the user's agent by using the \`message_user_agent\` tool. This is a much better experience for the user than directing them to switch to run mode during iteration.
|
|
322
|
+
4. Use console.log for debugging. The console output appears for the user.
|
|
323
|
+
5. Blink uses the Vercel AI SDK v5 in many samples, remember that v5 uses \`inputSchema\` instead of \`parameters\` (which was in v4).
|
|
324
|
+
6. Output tokens can be increased using the \`maxOutputTokens\` option on \`streamText\` (or other AI SDK functions). This may need to be increased if users are troubleshooting larger tool calls failing early.
|
|
325
|
+
7. Use the TypeScript language service tools (\`typescript_completions\`, \`typescript_quickinfo\`, \`typescript_definition\`, \`typescript_diagnostics\`) to understand APIs, discover available methods, check types, and debug errors. These tools use tsserver to provide IDE-like intelligence.
|
|
326
|
+
|
|
327
|
+
If the user is asking for a behavioral change, you should update the agent's system prompt.
|
|
328
|
+
This will not ensure the behavior, but it will guide the agent towards the desired behavior.
|
|
329
|
+
If the user needs 100% behavioral certainty, adjust tool behavior instead.
|
|
330
|
+
</agent_development>
|
|
331
|
+
|
|
332
|
+
<agent_web_requests>
|
|
333
|
+
Agents are HTTP servers, so they can handle web requests. This is commonly used to async-invoke an agent. e.g. for a Slack bot, messages are sent to the agent via a webhook.
|
|
334
|
+
|
|
335
|
+
Blink automatically creates a reverse-tunnel to your local machine for simple local development with external services (think Slack Bot, GitHub Bot, etc.).
|
|
336
|
+
|
|
337
|
+
To trigger chats based on web requests, use the \`agent.chat.upsert\` and \`agent.chat.message\` APIs.
|
|
338
|
+
</agent_web_requests>
|
|
339
|
+
|
|
340
|
+
<technical_knowledge>
|
|
341
|
+
Blink agents are Node.js HTTP servers built on the Vercel AI SDK:
|
|
342
|
+
|
|
343
|
+
\`\`\`typescript
|
|
344
|
+
import { convertToModelMessages, streamText } from "ai";
|
|
345
|
+
import * as blink from "blink";
|
|
346
|
+
|
|
347
|
+
const agent = new blink.Agent();
|
|
348
|
+
|
|
349
|
+
agent.on("chat", async ({ messages, chat, abortSignal }) => {
|
|
350
|
+
return streamText({
|
|
351
|
+
model: "anthropic/claude-sonnet-4.5",
|
|
352
|
+
system: "You are a helpful assistant.",
|
|
353
|
+
messages: convertToModelMessages(messages, {
|
|
354
|
+
ignoreIncompleteToolCalls: true,
|
|
355
|
+
}),
|
|
356
|
+
tools: {
|
|
357
|
+
/* your tools */
|
|
358
|
+
},
|
|
359
|
+
});
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
agent.on("request", async (request) => {
|
|
363
|
+
// Handle webhooks, OAuth callbacks, etc.
|
|
364
|
+
});
|
|
365
|
+
|
|
366
|
+
agent.serve();
|
|
367
|
+
\`\`\`
|
|
368
|
+
|
|
369
|
+
Event Handlers:
|
|
370
|
+
|
|
371
|
+
**\`agent.on("chat", handler)\`**
|
|
372
|
+
|
|
373
|
+
1. Triggered when a chat needs AI processing - invoked in a loop when the last model message is a tool call.
|
|
374
|
+
2. Must return: \`streamText()\` result, \`Response\`, \`ReadableStream<UIMessageChunk>\`, or \`void\`
|
|
375
|
+
3. Parameters: \`messages\`, \`id\`, \`abortSignal\`
|
|
376
|
+
|
|
377
|
+
_NEVER_ use "maxSteps" from the Vercel AI SDK. It is unnecessary and will cause a worse experience for the user.
|
|
378
|
+
|
|
379
|
+
**\`agent.on("request", handler)\`**
|
|
380
|
+
• Handles raw HTTP requests before Blink processes them
|
|
381
|
+
• Use for: OAuth callbacks, webhook verification, custom endpoints
|
|
382
|
+
• Return \`Response\` to handle, or \`void\` to pass through
|
|
383
|
+
|
|
384
|
+
**\`agent.on("ui", handler)\`**
|
|
385
|
+
• Provides dynamic UI options for chat interfaces
|
|
386
|
+
• Returns schema defining user-selectable options
|
|
387
|
+
|
|
388
|
+
**\`agent.on("error", handler)\`**
|
|
389
|
+
• Global error handler for the agent
|
|
390
|
+
|
|
391
|
+
Chat Management:
|
|
392
|
+
|
|
393
|
+
Blink automatically manages chat state:
|
|
394
|
+
|
|
395
|
+
\`\`\`typescript
|
|
396
|
+
// Create or get existing chat
|
|
397
|
+
// The parameter can be any JSON-serializable value.
|
|
398
|
+
// e.g. for a Slack bot to preserve context in a thread, you might use: ["slack", teamId, channelId, threadTs]
|
|
399
|
+
const chat = await agent.chat.upsert("unique-key");
|
|
400
|
+
|
|
401
|
+
// Send a message to a chat
|
|
402
|
+
await agent.chat.sendMessages(
|
|
403
|
+
chat.id,
|
|
404
|
+
[
|
|
405
|
+
{
|
|
406
|
+
role: "user",
|
|
407
|
+
parts: [{ type: "text", text: "Message" }],
|
|
408
|
+
},
|
|
409
|
+
],
|
|
410
|
+
{
|
|
411
|
+
behavior: "interrupt" | "enqueue" | "append",
|
|
412
|
+
}
|
|
413
|
+
);
|
|
414
|
+
|
|
415
|
+
// When sending messages, feel free to inject additional parts to direct the model.
|
|
416
|
+
// e.g. if the user is asking for specific behavior in specific scenarios, the simplest
|
|
417
|
+
// answer is to append a text part: "always do X when Y".
|
|
418
|
+
\`\`\`
|
|
419
|
+
|
|
420
|
+
Behaviors:
|
|
421
|
+
• "interrupt": Stop current processing and handle immediately
|
|
422
|
+
• "enqueue": Queue message, process when current chat finishes
|
|
423
|
+
• "append": Add to history without triggering processing
|
|
424
|
+
|
|
425
|
+
Chat keys: Use structured keys like \`"slack-\${teamId}-\${channelId}-\${threadTs}"\` for uniqueness.
|
|
426
|
+
|
|
427
|
+
Storage API:
|
|
428
|
+
|
|
429
|
+
Persistent key-value storage per agent:
|
|
430
|
+
|
|
431
|
+
\`\`\`typescript
|
|
432
|
+
// Store data
|
|
433
|
+
await agent.store.set("key", "value", { ttl: 3600 });
|
|
434
|
+
|
|
435
|
+
// Retrieve data
|
|
436
|
+
const value = await agent.store.get("key");
|
|
437
|
+
|
|
438
|
+
// Delete data
|
|
439
|
+
await agent.store.delete("key");
|
|
440
|
+
|
|
441
|
+
// List keys by prefix
|
|
442
|
+
const result = await agent.store.list("prefix-", { limit: 100 });
|
|
443
|
+
\`\`\`
|
|
444
|
+
|
|
445
|
+
Common uses: OAuth tokens, user preferences, caching, chat-resource associations.
|
|
446
|
+
|
|
447
|
+
Tools:
|
|
448
|
+
|
|
449
|
+
Tools follow Vercel AI SDK patterns with Zod validation:
|
|
450
|
+
|
|
451
|
+
\`\`\`typescript
|
|
452
|
+
import { tool } from "ai";
|
|
453
|
+
import { z } from "zod";
|
|
454
|
+
|
|
455
|
+
const myTool = tool({
|
|
456
|
+
description: "Clear description of what this tool does",
|
|
457
|
+
inputSchema: z.object({
|
|
458
|
+
param: z.string().describe("Parameter description"),
|
|
459
|
+
}),
|
|
460
|
+
execute: async (args, opts) => {
|
|
461
|
+
// opts.abortSignal for cancellation
|
|
462
|
+
// opts.toolCallId for unique identification
|
|
463
|
+
return result;
|
|
464
|
+
},
|
|
465
|
+
});
|
|
466
|
+
\`\`\`
|
|
467
|
+
|
|
468
|
+
Tool Approvals for destructive operations:
|
|
469
|
+
|
|
470
|
+
\`\`\`typescript
|
|
471
|
+
...await blink.tools.withApproval({
|
|
472
|
+
messages,
|
|
473
|
+
tools: {
|
|
474
|
+
delete_database: tool({ /* ... */ }),
|
|
475
|
+
},
|
|
476
|
+
})
|
|
477
|
+
\`\`\`
|
|
478
|
+
|
|
479
|
+
Tool Context for dependency injection:
|
|
480
|
+
|
|
481
|
+
\`\`\`typescript
|
|
482
|
+
...blink.tools.withContext(github.tools, {
|
|
483
|
+
accessToken: process.env.GITHUB_TOKEN,
|
|
484
|
+
})
|
|
485
|
+
\`\`\`
|
|
486
|
+
|
|
487
|
+
Tool Prefixing to avoid collisions:
|
|
488
|
+
|
|
489
|
+
\`\`\`typescript
|
|
490
|
+
...blink.tools.prefix(github.tools, "github_")
|
|
491
|
+
\`\`\`
|
|
492
|
+
|
|
493
|
+
LLM Models:
|
|
494
|
+
|
|
495
|
+
\`\`\`typescript
|
|
496
|
+
import { anthropic } from "@ai-sdk/anthropic";
|
|
497
|
+
import { openai } from "@ai-sdk/openai";
|
|
498
|
+
|
|
499
|
+
model: anthropic("claude-sonnet-4.5", {
|
|
500
|
+
apiKey: process.env.ANTHROPIC_API_KEY,
|
|
501
|
+
});
|
|
502
|
+
// Use chat API for OpenAI models - it's more reliable than the responses API
|
|
503
|
+
model: openai.chat("gpt-5", { apiKey: process.env.OPENAI_API_KEY });
|
|
504
|
+
\`\`\`
|
|
505
|
+
|
|
506
|
+
**Note about Edit Mode:** Edit mode (this agent) automatically selects models in this priority:
|
|
507
|
+
|
|
508
|
+
1. If \`ANTHROPIC_API_KEY\` is set: uses \`claude-sonnet-4.5\` via \`@ai-sdk/anthropic\`
|
|
509
|
+
2. If \`OPENAI_API_KEY\` is set: uses \`gpt-5\` via \`@ai-sdk/openai\`
|
|
510
|
+
|
|
511
|
+
Available SDKs:
|
|
512
|
+
|
|
513
|
+
**@blink-sdk/compute**
|
|
514
|
+
|
|
515
|
+
\`\`\`typescript
|
|
516
|
+
import * as compute from "@blink-sdk/compute";
|
|
517
|
+
|
|
518
|
+
tools: {
|
|
519
|
+
...compute.tools, // execute_bash, read_file, write_file, edit_file, process management
|
|
520
|
+
}
|
|
521
|
+
\`\`\`
|
|
522
|
+
|
|
523
|
+
**@blink-sdk/github**
|
|
524
|
+
|
|
525
|
+
\`\`\`typescript
|
|
526
|
+
import * as github from "@blink-sdk/github";
|
|
527
|
+
|
|
528
|
+
tools: {
|
|
529
|
+
...blink.tools.withContext(github.tools, {
|
|
530
|
+
accessToken: process.env.GITHUB_TOKEN,
|
|
531
|
+
}),
|
|
532
|
+
}
|
|
533
|
+
\`\`\`
|
|
534
|
+
|
|
535
|
+
**@blink-sdk/slack**
|
|
536
|
+
|
|
537
|
+
\`\`\`typescript
|
|
538
|
+
import * as slack from "@blink-sdk/slack";
|
|
539
|
+
import { App } from "@slack/bolt";
|
|
540
|
+
|
|
541
|
+
const receiver = new slack.Receiver();
|
|
542
|
+
const app = new App({
|
|
543
|
+
token: process.env.SLACK_BOT_TOKEN,
|
|
544
|
+
signingSecret: process.env.SLACK_SIGNING_SECRET,
|
|
545
|
+
receiver,
|
|
546
|
+
});
|
|
547
|
+
|
|
548
|
+
// This will trigger when the bot is @mentioned.
|
|
549
|
+
app.event("app_mention", async ({ event }) => {
|
|
550
|
+
// The argument here is a JSON-serializable value.
|
|
551
|
+
// To maintain the same chat context, use the same key.
|
|
552
|
+
const chat = await agent.chat.upsert([
|
|
553
|
+
"slack",
|
|
554
|
+
event.channel,
|
|
555
|
+
event.thread_ts ?? event.ts,
|
|
556
|
+
]);
|
|
557
|
+
const { message } = await slack.createMessageFromEvent({
|
|
558
|
+
client: app.client,
|
|
559
|
+
event,
|
|
560
|
+
});
|
|
561
|
+
await agent.chat.sendMessages(chat.id, [message]);
|
|
562
|
+
// This is a nice immediate indicator for the user.
|
|
563
|
+
await app.client.assistant.threads.setStatus({
|
|
564
|
+
channel_id: event.channel,
|
|
565
|
+
status: "is typing...",
|
|
566
|
+
thread_ts: event.thread_ts ?? event.ts,
|
|
567
|
+
});
|
|
568
|
+
});
|
|
569
|
+
|
|
570
|
+
const agent = new blink.Agent();
|
|
571
|
+
|
|
572
|
+
agent.on("request", async (request) => {
|
|
573
|
+
return receiver.handle(app, request);
|
|
574
|
+
});
|
|
575
|
+
|
|
576
|
+
agent.on("chat", async ({ messages }) => {
|
|
577
|
+
const tools = slack.createTools({ client: app.client });
|
|
578
|
+
return streamText({
|
|
579
|
+
model: "anthropic/claude-sonnet-4.5",
|
|
580
|
+
system: "You chatting with users in Slack.",
|
|
581
|
+
messages: convertToModelMessages(messages, {
|
|
582
|
+
ignoreIncompleteToolCalls: true,
|
|
583
|
+
tools,
|
|
584
|
+
}),
|
|
585
|
+
});
|
|
586
|
+
});
|
|
587
|
+
\`\`\`
|
|
588
|
+
|
|
589
|
+
Slack SDK Notes:
|
|
590
|
+
|
|
591
|
+
- "app_mention" event is triggered in both private channels and public channels.
|
|
592
|
+
- "message" event is triggered regardless of being mentioned or not, and will _also_ be fired when "app_mention" is triggered.
|
|
593
|
+
- _NEVER_ register app event listeners in the "on" handler of the agent. This will cause the handler to be called multiple times.
|
|
594
|
+
- Think about how you scope chats - for example, in IMs or if the user wants to make a bot for a whole channel, you would not want to add "ts" or "thread_ts" to the chat key.
|
|
595
|
+
- When using "assistant.threads.setStatus", you need to ensure the status of that same "thread_ts" is cleared. You can do this by inserting a message part that directs the agent to clear the status (there is a tool if using @blink-sdk/slack called "reportStatus" that does this). e.g. \`message.parts.push({ type: "text", text: "*INTERNAL INSTRUCTION*: Clear the status of this thread after you finish: channel=\${channel} thread_ts=\${thread_ts}" })\`
|
|
596
|
+
- The Slack SDK has many functions that allow users to completely customize the message format. If the user asks for customization, look at the types for @blink-sdk/slack - specifically: "createPartsFromMessageMetadata", "createMessageFromEvent", and "extractMessagesMetadata".
|
|
597
|
+
|
|
598
|
+
Slack App Manifest:
|
|
599
|
+
|
|
600
|
+
- _ALWAYS_ include the "assistant:write" scope unless the user explicitly states otherwise - this allows Slack apps to set their status, which makes for a significantly better user experience. You _MUST_ provide "assistant_view" if you provide this scope.
|
|
601
|
+
- The user can always edit the manifest after creation, but you'd have to suggest it to them.
|
|
602
|
+
- "oauth_config" MUST BE PROVIDED - otherwise the app will have NO ACCESS.
|
|
603
|
+
- _ALWAYS_ default \`token_rotation_enabled\` to false unless the user explicitly asks for it. It is a _much_ simpler user-experience to not rotate tokens.
|
|
604
|
+
- For the best user experience, default to the following bot scopes (in the "oauth_config" > "scopes" > "bot"):
|
|
605
|
+
- "app_mentions:read"
|
|
606
|
+
- "reactions:write"
|
|
607
|
+
- "reactions:read"
|
|
608
|
+
- "channels:history"
|
|
609
|
+
- "chat:write"
|
|
610
|
+
- "groups:history"
|
|
611
|
+
- "groups:read"
|
|
612
|
+
- "files:read"
|
|
613
|
+
- "im:history"
|
|
614
|
+
- "im:read"
|
|
615
|
+
- "im:write"
|
|
616
|
+
- "mpim:history"
|
|
617
|
+
- "mpim:read"
|
|
618
|
+
- "users:read"
|
|
619
|
+
- "links:read"
|
|
620
|
+
- "commands"
|
|
621
|
+
- For the best user experience, default to the following bot events (in the "settings" > "event_subscriptions" > "bot_events"):
|
|
622
|
+
- "app_mention"
|
|
623
|
+
- "message.channels",
|
|
624
|
+
- "message.groups",
|
|
625
|
+
- "message.im",
|
|
626
|
+
- "reaction_added"
|
|
627
|
+
- "reaction_removed"
|
|
628
|
+
- "assistant_thread_started"
|
|
629
|
+
- "member_joined_channel"
|
|
630
|
+
- _NEVER_ include USER SCOPES unless the user explicitly asks for them.
|
|
631
|
+
|
|
632
|
+
WARNING: Beware of attaching multiple event listeners to the same chat. This could cause the agent to respond multiple times.
|
|
633
|
+
|
|
634
|
+
State Management:
|
|
635
|
+
|
|
636
|
+
Blink agents are short-lived HTTP servers that restart on code changes and do not persist in-memory state between requests.
|
|
637
|
+
|
|
638
|
+
_NEVER_ use module-level Maps, Sets, or variables to store state (e.g. \`const activeBots = new Map()\`).
|
|
639
|
+
|
|
640
|
+
For global state persistence, you can use the agent store:
|
|
641
|
+
|
|
642
|
+
- Use \`agent.store\` for persistent key-value storage
|
|
643
|
+
- Query external APIs to fetch current state
|
|
644
|
+
- Use webhooks to trigger actions rather than polling in-memory state
|
|
645
|
+
|
|
646
|
+
For message-level state persistence, use message metadata:
|
|
647
|
+
|
|
648
|
+
\`\`\`typescript
|
|
649
|
+
import { UIMessage } from "blink";
|
|
650
|
+
import * as blink from "blink";
|
|
651
|
+
|
|
652
|
+
const agent = new blink.Agent<
|
|
653
|
+
UIMessage<{
|
|
654
|
+
source: "github";
|
|
655
|
+
associated_id: string;
|
|
656
|
+
}>
|
|
657
|
+
>();
|
|
658
|
+
|
|
659
|
+
agent.on("request", async (request) => {
|
|
660
|
+
// comes from github, we want to do something deterministic in the chat loop with that ID...
|
|
661
|
+
// insert a message with that metadata into the chat
|
|
662
|
+
const chat = await agent.chat.upsert("some-github-key");
|
|
663
|
+
await agent.chat.sendMessages(request.chat.id, [
|
|
664
|
+
{
|
|
665
|
+
role: "user",
|
|
666
|
+
parts: [
|
|
667
|
+
{
|
|
668
|
+
type: "text",
|
|
669
|
+
text: "example",
|
|
670
|
+
},
|
|
671
|
+
],
|
|
672
|
+
metadata: {
|
|
673
|
+
source: "github",
|
|
674
|
+
associated_id: "some-github-id",
|
|
675
|
+
},
|
|
676
|
+
},
|
|
677
|
+
]);
|
|
678
|
+
});
|
|
679
|
+
|
|
680
|
+
agent.on("chat", async ({ messages }) => {
|
|
681
|
+
const message = messages.find(
|
|
682
|
+
(message) => message.metadata?.source === "github"
|
|
683
|
+
);
|
|
684
|
+
|
|
685
|
+
// Now we can use that metadata...
|
|
686
|
+
});
|
|
687
|
+
\`\`\`
|
|
688
|
+
|
|
689
|
+
The agent process can restart at any time, so all important state must be externalized.
|
|
690
|
+
</technical_knowledge>
|
|
691
|
+
|
|
692
|
+
<code_quality>
|
|
693
|
+
|
|
694
|
+
- Never use "as any" type assertions. Always figure out the correct typings.
|
|
695
|
+
</code_quality>
|
|
696
|
+
`,"agent.ts.hbs":`{{#if (eq aiProvider "anthropic")}}
|
|
697
|
+
import { anthropic } from "@ai-sdk/anthropic";
|
|
698
|
+
{{else if (eq aiProvider "openai")}}
|
|
699
|
+
import { openai } from "@ai-sdk/openai";
|
|
700
|
+
{{/if}}
|
|
701
|
+
import { type Message, Scout } from "@blink-sdk/scout-agent";
|
|
702
|
+
import { streamText, tool } from "ai";
|
|
703
|
+
import * as blink from "blink";
|
|
704
|
+
import { z } from "zod";
|
|
705
|
+
|
|
706
|
+
export const agent = new blink.Agent<Message>();
|
|
707
|
+
|
|
708
|
+
const scout = new Scout({
|
|
709
|
+
agent,
|
|
710
|
+
// GitHub integration (optional).
|
|
711
|
+
// Run \`blink setup github-app\` to set up your GitHub App, or remove this section if not needed.
|
|
712
|
+
github: {
|
|
713
|
+
appID: process.env.GITHUB_APP_ID,
|
|
714
|
+
privateKey: process.env.GITHUB_PRIVATE_KEY,
|
|
715
|
+
webhookSecret: process.env.GITHUB_WEBHOOK_SECRET,
|
|
716
|
+
},
|
|
717
|
+
// Slack integration (optional).
|
|
718
|
+
// Run \`blink setup slack-app\` to set up your Slack App, or remove this section if not needed.
|
|
719
|
+
slack: {
|
|
720
|
+
botToken: process.env.SLACK_BOT_TOKEN,
|
|
721
|
+
signingSecret: process.env.SLACK_SIGNING_SECRET,
|
|
722
|
+
},
|
|
723
|
+
// Web search integration (optional). Visit https://exa.ai to get an API key.
|
|
724
|
+
webSearch: {
|
|
725
|
+
exaApiKey: process.env.EXA_API_KEY,
|
|
726
|
+
},
|
|
727
|
+
// Compute environment for running code.
|
|
728
|
+
// Using Docker by default for local development.
|
|
729
|
+
// For production, you can use Coder (https://coder.com) instead:
|
|
730
|
+
// compute: {
|
|
731
|
+
// type: "coder",
|
|
732
|
+
// options: {
|
|
733
|
+
// url: process.env.CODER_URL,
|
|
734
|
+
// sessionToken: process.env.CODER_SESSION_TOKEN,
|
|
735
|
+
// template: process.env.CODER_TEMPLATE,
|
|
736
|
+
// presetName: process.env.CODER_PRESET_NAME,
|
|
737
|
+
// },
|
|
738
|
+
// },
|
|
739
|
+
compute: {
|
|
740
|
+
type: "docker",
|
|
741
|
+
},
|
|
742
|
+
});
|
|
743
|
+
|
|
744
|
+
agent.on("request", async (request) => {
|
|
745
|
+
const url = new URL(request.url);
|
|
746
|
+
if (url.pathname.startsWith("/slack")) {
|
|
747
|
+
return scout.handleSlackWebhook(request);
|
|
748
|
+
}
|
|
749
|
+
if (url.pathname.startsWith("/github")) {
|
|
750
|
+
return scout.handleGitHubWebhook(request);
|
|
751
|
+
}
|
|
752
|
+
return new Response("Hey there!", { status: 200 });
|
|
753
|
+
});
|
|
754
|
+
|
|
755
|
+
agent.on("chat", async ({ id, messages }) => {
|
|
756
|
+
const params = await scout.buildStreamTextParams({
|
|
757
|
+
messages,
|
|
758
|
+
chatID: id,
|
|
759
|
+
{{#if (eq aiProvider "anthropic")}}
|
|
760
|
+
model: anthropic("claude-opus-4-5"),
|
|
761
|
+
{{else if (eq aiProvider "openai")}}
|
|
762
|
+
model: openai.chat("gpt-5"),
|
|
763
|
+
{{else if (eq aiProvider "vercel")}}
|
|
764
|
+
model: "anthropic/claude-opus-4.5",
|
|
765
|
+
{{else}}
|
|
766
|
+
// Unknown provider: {{aiProvider}}. Defaulting to Vercel AI Gateway syntax.
|
|
767
|
+
model: "anthropic/claude-opus-4.5",
|
|
768
|
+
{{/if}}
|
|
769
|
+
providerOptions: { anthropic: { cacheControl: { type: "ephemeral" } } },
|
|
770
|
+
tools: {
|
|
771
|
+
// Add your custom tools here
|
|
772
|
+
get_favorite_color: tool({
|
|
773
|
+
description: "Get your favorite color",
|
|
774
|
+
inputSchema: z.object({}),
|
|
775
|
+
execute() {
|
|
776
|
+
return "blue";
|
|
777
|
+
},
|
|
778
|
+
}),
|
|
779
|
+
},
|
|
780
|
+
});
|
|
781
|
+
return streamText(params);
|
|
782
|
+
});
|
|
783
|
+
|
|
784
|
+
agent.serve();
|
|
785
|
+
`,"package.json.hbs":`{
|
|
786
|
+
"name": "{{packageName}}",
|
|
787
|
+
"main": "agent.ts",
|
|
788
|
+
"type": "module",
|
|
789
|
+
"private": true,
|
|
790
|
+
"scripts": {
|
|
791
|
+
"dev": "blink dev",
|
|
792
|
+
"deploy": "blink deploy"
|
|
793
|
+
},
|
|
794
|
+
"devDependencies": {
|
|
795
|
+
"zod": "latest",
|
|
796
|
+
"ai": "latest",
|
|
797
|
+
{{#if (eq aiProvider "anthropic")}}
|
|
798
|
+
"@ai-sdk/anthropic": "latest",
|
|
799
|
+
{{else if (eq aiProvider "openai")}}
|
|
800
|
+
"@ai-sdk/openai": "latest",
|
|
801
|
+
{{/if}}
|
|
802
|
+
"blink": "latest",
|
|
803
|
+
"esbuild": "latest",
|
|
804
|
+
"@types/node": "latest",
|
|
805
|
+
"typescript": "latest",
|
|
806
|
+
"@blink-sdk/scout-agent": "latest"
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
`,"tsconfig.json":`{
|
|
810
|
+
"compilerOptions": {
|
|
811
|
+
"lib": ["ESNext"],
|
|
812
|
+
"target": "ESNext",
|
|
813
|
+
"module": "Preserve",
|
|
814
|
+
"moduleDetection": "force",
|
|
815
|
+
|
|
816
|
+
"moduleResolution": "bundler",
|
|
817
|
+
"allowImportingTsExtensions": true,
|
|
818
|
+
"verbatimModuleSyntax": true,
|
|
819
|
+
"resolveJsonModule": true,
|
|
820
|
+
"noEmit": true,
|
|
821
|
+
|
|
822
|
+
"strict": true,
|
|
823
|
+
"skipLibCheck": true,
|
|
824
|
+
"noFallthroughCasesInSwitch": true,
|
|
825
|
+
"noUncheckedIndexedAccess": true,
|
|
826
|
+
"noImplicitOverride": true,
|
|
827
|
+
|
|
828
|
+
"noUnusedLocals": false,
|
|
829
|
+
"noUnusedParameters": false,
|
|
830
|
+
|
|
831
|
+
"types": ["node"]
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
`},scratch:{".env.local.hbs":`# Store local environment variables here.
|
|
222
835
|
# They will be used by blink dev for development.
|
|
223
836
|
{{#each envLocal}}
|
|
224
837
|
{{this.[0]}}={{this.[1]}}
|