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.
Files changed (106) hide show
  1. package/dist/browser/control/index.d.cts +12 -4
  2. package/dist/browser/control/index.d.ts +12 -4
  3. package/dist/cli/chat-manager-bMAuoSb5.js +21 -0
  4. package/dist/cli/chat-mj0wnV3_.js +1 -0
  5. package/dist/cli/compute-server-BFNeHOmk.js +1 -0
  6. package/dist/cli/{connect-t56RPJRB.js → connect-BnhWpzRI.js} +1 -1
  7. package/dist/cli/connect-Cd-0O7Uu.js +1 -0
  8. package/dist/cli/create-github-app-Dld06QIC.js +16 -0
  9. package/dist/cli/{dev-DTCSw4OQ.js → dev-9EzQCNmd.js} +156 -177
  10. package/dist/cli/{getMachineId-bsd-BECgXpZb.js → getMachineId-bsd-BfwVPdTh.js} +1 -1
  11. package/dist/cli/{getMachineId-bsd-BgAyii4H.js → getMachineId-bsd-BmhpEQU_.js} +1 -1
  12. package/dist/cli/{getMachineId-bsd-Cc73dhdJ.js → getMachineId-bsd-C1eeoY31.js} +1 -1
  13. package/dist/cli/{getMachineId-bsd-DJn61I3m.js → getMachineId-bsd-CO9ne--Y.js} +1 -1
  14. package/dist/cli/{getMachineId-bsd-Doah6QJP.js → getMachineId-bsd-D4uBPoNF.js} +1 -1
  15. package/dist/cli/getMachineId-bsd-DVGtITCk.js +1 -0
  16. package/dist/cli/getMachineId-bsd-MA4oFaCa.js +1 -0
  17. package/dist/cli/getMachineId-bsd-dbToLPez.js +1 -0
  18. package/dist/cli/{getMachineId-darwin-BMnMBte0.js → getMachineId-darwin-C0EZ3sY3.js} +1 -1
  19. package/dist/cli/{getMachineId-darwin-BP9BSYcd.js → getMachineId-darwin-CSfD7gS4.js} +1 -1
  20. package/dist/cli/{getMachineId-darwin-Bs3mlKrs.js → getMachineId-darwin-CgQ9n4TU.js} +1 -1
  21. package/dist/cli/{getMachineId-darwin-DFronuaU.js → getMachineId-darwin-Cpq0Lloc.js} +1 -1
  22. package/dist/cli/{getMachineId-darwin-D-l4_nyT.js → getMachineId-darwin-CuAzoP7O.js} +1 -1
  23. package/dist/cli/getMachineId-darwin-D6_tdcZj.js +2 -0
  24. package/dist/cli/getMachineId-darwin-DkExT2qu.js +2 -0
  25. package/dist/cli/getMachineId-darwin-xoAzTD7x.js +2 -0
  26. package/dist/cli/{getMachineId-linux-B2r_HEgX.js → getMachineId-linux-B1XJTHUh.js} +1 -1
  27. package/dist/cli/{getMachineId-linux-Bj52Hdvy.js → getMachineId-linux-CRUR6LbQ.js} +1 -1
  28. package/dist/cli/{getMachineId-linux-C9o1dYwI.js → getMachineId-linux-CVQNNGui.js} +1 -1
  29. package/dist/cli/{getMachineId-linux-CGcBOg7J.js → getMachineId-linux-CtdZRCaX.js} +1 -1
  30. package/dist/cli/getMachineId-linux-DMILcDJR.js +1 -0
  31. package/dist/cli/getMachineId-linux-Deja7F2k.js +1 -0
  32. package/dist/cli/getMachineId-linux-DqOGXYgv.js +1 -0
  33. package/dist/cli/getMachineId-linux-FRx9q8NV.js +1 -0
  34. package/dist/cli/{getMachineId-unsupported-BtmyS2eg.js → getMachineId-unsupported-B-xvzil1.js} +1 -1
  35. package/dist/cli/{getMachineId-unsupported-C8az6JKm.js → getMachineId-unsupported-BA3eQjiV.js} +1 -1
  36. package/dist/cli/{getMachineId-unsupported-CBS2qXAs.js → getMachineId-unsupported-BZCOxs7n.js} +1 -1
  37. package/dist/cli/{getMachineId-unsupported-Cu0DvxaU.js → getMachineId-unsupported-BjGFauqb.js} +1 -1
  38. package/dist/cli/getMachineId-unsupported-CLWxRb7f.js +1 -0
  39. package/dist/cli/getMachineId-unsupported-CSVFDvWp.js +1 -0
  40. package/dist/cli/getMachineId-unsupported-Cp_95R-6.js +1 -0
  41. package/dist/cli/getMachineId-unsupported-Nd0_Z7NT.js +1 -0
  42. package/dist/cli/{getMachineId-win-BCAO7ld1.js → getMachineId-win-AW-Mv9PG.js} +1 -1
  43. package/dist/cli/{getMachineId-win-BDQszRKi.js → getMachineId-win-B_2C1cwE.js} +1 -1
  44. package/dist/cli/{getMachineId-win-BOnF6rL7.js → getMachineId-win-BbYxddZ9.js} +1 -1
  45. package/dist/cli/{getMachineId-win-BOuIHcz_.js → getMachineId-win-BkozcdSh.js} +1 -1
  46. package/dist/cli/getMachineId-win-CPhFagnx.js +1 -0
  47. package/dist/cli/{getMachineId-win-pnMl0wak.js → getMachineId-win-CUeKGXdr.js} +1 -1
  48. package/dist/cli/getMachineId-win-D3-sMfSu.js +1 -0
  49. package/dist/cli/getMachineId-win-DFVpvzl3.js +1 -0
  50. package/dist/cli/index.js +7 -7
  51. package/dist/cli/init-CByRT25U.js +23 -0
  52. package/dist/cli/{init-templates-D4lwX_8M.js → init-templates-jGRvqLQ6.js} +614 -1
  53. package/dist/cli/run-Lp28Ogb_.js +1 -0
  54. package/dist/cli/setup-github-app-D-K7e6al.js +9 -0
  55. package/dist/cli/{token-Bk68OrJt.js → token-ClGOahUF.js} +1 -1
  56. package/dist/cli/token-util-DIx5k-1f.js +1 -0
  57. package/dist/cli/{token-util-BKLboTb2.js → token-util-h1hcKvQX.js} +1 -1
  58. package/dist/cli/undici-JD4hDNWZ.js +1 -0
  59. package/dist/cli/utils-B3iC7vdW.js +1 -0
  60. package/dist/node/agent/index.node.cjs +1 -1
  61. package/dist/node/agent/index.node.js +1 -1
  62. package/dist/node/{index.node-Bvp48I1R.cjs → index.node-Btg8Ii_o.cjs} +2 -2
  63. package/dist/node/{index.node-ppzOWVGE.js → index.node-xL4mvvNL.js} +2 -2
  64. package/dist/node/react/index.node.cjs +615 -2
  65. package/dist/node/react/index.node.js +615 -2
  66. package/package.json +1 -1
  67. package/dist/cli/chat-C_rQ9SRr.js +0 -1
  68. package/dist/cli/chat-manager-bLgTuAnK.js +0 -21
  69. package/dist/cli/compute-server-CyGc-fpM.js +0 -1
  70. package/dist/cli/connect-CgLoRyDv.js +0 -1
  71. package/dist/cli/create-slack-app-CyVPwWsG.js +0 -1
  72. package/dist/cli/events-DKgZ2LNM.js +0 -1
  73. package/dist/cli/getMachineId-bsd-aoAkh_W6.js +0 -1
  74. package/dist/cli/getMachineId-bsd-iPOb0TqF.js +0 -1
  75. package/dist/cli/getMachineId-bsd-io5tPlFg.js +0 -1
  76. package/dist/cli/getMachineId-darwin-DJO6fOdc.js +0 -2
  77. package/dist/cli/getMachineId-darwin-DlRRGl6M.js +0 -2
  78. package/dist/cli/getMachineId-darwin-Wp0usMIp.js +0 -2
  79. package/dist/cli/getMachineId-linux-CV2HmJXY.js +0 -1
  80. package/dist/cli/getMachineId-linux-Cv44Y8ZY.js +0 -1
  81. package/dist/cli/getMachineId-linux-CzNEh3DJ.js +0 -1
  82. package/dist/cli/getMachineId-linux-_RiwpX2J.js +0 -1
  83. package/dist/cli/getMachineId-unsupported-Dni2ujA-.js +0 -1
  84. package/dist/cli/getMachineId-unsupported-MPNVP8rP.js +0 -1
  85. package/dist/cli/getMachineId-unsupported-mBJd3oBN.js +0 -1
  86. package/dist/cli/getMachineId-unsupported-rdNf8ej6.js +0 -1
  87. package/dist/cli/getMachineId-win-BQ_C7kS3.js +0 -1
  88. package/dist/cli/getMachineId-win-Bw0-Mlkn.js +0 -1
  89. package/dist/cli/getMachineId-win-DrJTv2qi.js +0 -1
  90. package/dist/cli/init-DXBledyD.js +0 -23
  91. package/dist/cli/run-CRrWbMEw.js +0 -1
  92. package/dist/cli/setup-slack-app-C9L0iIDZ.js +0 -1
  93. package/dist/cli/token-util-Dui5nOLw.js +0 -1
  94. package/dist/cli/undici-mM2IfLwA.js +0 -1
  95. /package/dist/cli/{devtools-CS3ukAFj.js → devtools-CwQnB6v7.js} +0 -0
  96. /package/dist/cli/{esm-CYkSi8_o.js → esm-BiWxO8S7.js} +0 -0
  97. /package/dist/cli/{execAsync-9jtK4I3l.js → execAsync-4IyNgpoN.js} +0 -0
  98. /package/dist/cli/{execAsync-B4_pEoEJ.js → execAsync-B6xSGvuk.js} +0 -0
  99. /package/dist/cli/{execAsync-BdK7RB6d.js → execAsync-B8_ZTafx.js} +0 -0
  100. /package/dist/cli/{execAsync-Bjxs-bO2.js → execAsync-B8nelpRN.js} +0 -0
  101. /package/dist/cli/{execAsync-CM_C8SBr.js → execAsync-Cj_jF8MF.js} +0 -0
  102. /package/dist/cli/{execAsync-CNFaXJjR.js → execAsync-Ckbi9Yqe.js} +0 -0
  103. /package/dist/cli/{execAsync-Dl3hbWiU.js → execAsync-CvOpnFex.js} +0 -0
  104. /package/dist/cli/{execAsync-qGIZ8XA8.js → execAsync-DDBH3pWg.js} +0 -0
  105. /package/dist/cli/{token-error-CGIVaIg6.js → token-error-BHDo_48c.js} +0 -0
  106. /package/dist/cli/{undici-BiTrd9-R.js → undici-B5tM_IT9.js} +0 -0
@@ -1,4 +1,4 @@
1
- import{__commonJSMin as e,__esmMin as t,__export as n,__reExport as r,__require as i,__toCommonJS as a,__toESM as o}from"../chunk-D9KrCrVq.js";import{APICallError as s,APIServerURLEnvironmentVariable as c,Agent as l,EmptyResponseBodyError as u,EventSourceParserStream as d,Hono as f,InvalidArgumentError as p,InvalidPromptError as m,InvalidResponseDataError as h,JSONParseError as g,LoadAPIKeyError as _,NoSuchModelError as v,StreamResponseFormatHeader as y,TooManyEmbeddingValuesForCallError as b,TypeValidationError as x,UnsupportedFunctionalityError as S,createGatewayProvider as C,createServerAdapter as w,hc as T,isToolApprovalOutput as E,lastUIOptions as D,tools as O,validator as k}from"../index.node-ppzOWVGE.js";import"../token-error-488npYdU.js";import"../esm-CbZfjZBn.js";import{resolveConfig as A}from"../build-DYI55eX2.js";import{createRequire as j}from"node:module";import M,{z as N}from"zod/v4";import{ZodFirstPartyTypeKind as ee}from"zod/v3";import{Buffer as te}from"node:buffer";import*as P from"node:fs";import F,{existsSync as I,mkdirSync as ne,readFileSync as L,unlinkSync as re,writeFileSync as R}from"node:fs";import{fileURLToPath as ie}from"node:url";import{Writable as z}from"node:stream";import{promisify as ae,stripVTControlCharacters as oe}from"node:util";import{createHash as se}from"node:crypto";import ce,{createServer as le}from"http";import{dirname as B,join as ue}from"path";import{existsSync as de,mkdirSync as fe,readFileSync as pe,watch as me,writeFileSync as he}from"fs";import{convertToModelMessages as ge,isToolOrDynamicToolUIPart as _e,readUIMessageStream as ve,streamText as ye,tool as be}from"ai";import{readFile as xe,stat as V,writeFile as Se}from"fs/promises";import{spawn as Ce}from"child_process";import{createContext as we,useCallback as H,useEffect as U,useMemo as Te,useRef as W,useState as G}from"react";import K,{z as q}from"zod";import*as Ee from"node:path";import De,{dirname as Oe,join as ke}from"node:path";import J,{stdin as Ae,stdout as je}from"node:process";import Me from"node:os";import Ne from"node:tty";import*as Pe from"node:readline";import Fe from"node:readline";import Ie,{execFile as Le}from"node:child_process";import Re,{constants as ze}from"node:fs/promises";import"@blink-sdk/compute-protocol/client";import{createInMemoryClientServer as Be}from"@blink-sdk/compute-protocol/transport";function Ve(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function He(e){return Object.fromEntries([...e.headers])}function Ue(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 We(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function Ge(e,...t){let n=We(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var Ke=(({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new p({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();function qe(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Je=[`fetch failed`,`failed to fetch`];function Ye({error:e,url:t,requestBodyValues:n}){if(qe(e))return e;if(e instanceof TypeError&&Je.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new s({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}var Xe=`3.0.10`;function Ze({apiKey:e,environmentVariableName:t,apiKeyParameterName:n=`apiKey`,description:r}){if(typeof e==`string`)return e;if(e!=null)throw new _({message:`${r} API key must be a string.`});if(typeof process>`u`)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!=`string`)throw new _({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var Qe=/"__proto__"\s*:/,$e=/"constructor"\s*:/;function et(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Qe.test(e)===!1&&$e.test(e)===!1?t:tt(t)}function tt(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 nt(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return et(e)}finally{Error.stackTraceLimit=t}}var rt=Symbol.for(`vercel.ai.validator`);function it(e){return{[rt]:!0,validate:e}}function at(e){return typeof e==`object`&&!!e&&rt in e&&e[rt]===!0&&`validate`in e}function ot(e){return at(e)?e:st(e)}function st(e){return it(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new x({value:t,cause:n.issues})}})}async function ct({value:e,schema:t}){let n=await lt({value:e,schema:t});if(!n.success)throw x.wrap({value:e,cause:n.error});return n.value}async function lt({value:e,schema:t}){let n=ot(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:x.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:x.wrap({value:e,cause:t}),rawValue:e}}}async function ut({text:e,schema:t}){try{let n=nt(e);return t==null?n:ct({value:n,schema:t})}catch(t){throw g.isInstance(t)||x.isInstance(t)?t:new g({text:e,cause:t})}}async function dt({text:e,schema:t}){try{let n=nt(e);return t==null?{success:!0,value:n,rawValue:n}:await lt({value:n,schema:t})}catch(t){return{success:!1,error:g.isInstance(t)?t:new g({text:e,cause:t}),rawValue:void 0}}}function ft({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new d).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await dt({text:e,schema:t}))}}))}async function pt({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;let r=await lt({value:t[e],schema:n});if(!r.success)throw new p({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:r.error});return r.value}var mt=()=>globalThis.fetch,ht=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>gt({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),gt=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=mt()})=>{try{let c=await o(e,{method:`POST`,headers:Ge(t,`ai-sdk/provider-utils/${Xe}`,Ue()),body:n.content,signal:a}),l=He(c);if(!c.ok){let t;try{t=await i({response:c,url:e,requestBodyValues:n.values})}catch(t){throw qe(t)||s.isInstance(t)?t:new s({message:`Failed to process error response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw t.value}try{return await r({response:c,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(qe(t)||s.isInstance(t))?t:new s({message:`Failed to process successful response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(t){throw Ye({error:t,url:e,requestBodyValues:n.values})}};function _t(e){return e}function vt({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>_t({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function yt({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>_t({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 bt(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var xt=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),c=He(r);if(o.trim()===``)return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})};try{let l=await ut({text:o,schema:e});return{responseHeaders:c,value:new s({message:t(l),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})}}},St=e=>async({response:t})=>{let n=He(t);if(t.body==null)throw new u({});return{responseHeaders:n,value:ft({stream:t.body,schema:e})}},Ct=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await dt({text:i,schema:e}),o=He(t);if(!a.success)throw new s({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},{btoa:wt,atob:Tt}=globalThis;function Et(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return wt(t)}function Dt(e){return e instanceof Uint8Array?Et(e):e}function Ot(e){return e?.replace(/\/$/,``)}var kt=`2.0.23`,At=N.object({type:N.literal(`error`),error:N.object({type:N.string(),message:N.string()})}),jt=xt({errorSchema:At,errorToMessage:e=>e.error.message}),Mt=N.object({citations:N.object({enabled:N.boolean()}).optional(),title:N.string().optional(),context:N.string().optional()}),Nt=N.object({sendReasoning:N.boolean().optional(),thinking:N.object({type:N.union([N.literal(`enabled`),N.literal(`disabled`)]),budgetTokens:N.number().optional()}).optional(),disableParallelToolUse:N.boolean().optional(),cacheControl:N.object({type:N.literal(`ephemeral`),ttl:N.union([N.literal(`5m`),N.literal(`1h`)]).optional()}).optional()});function Pt(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var Ft=N.object({maxCharacters:N.number().optional()}),It=vt({id:`anthropic.text_editor_20250728`,name:`str_replace_based_edit_tool`,inputSchema:N.object({command:N.enum([`view`,`create`,`str_replace`,`insert`]),path:N.string(),file_text:N.string().optional(),insert_line:N.number().int().optional(),new_str:N.string().optional(),old_str:N.string().optional(),view_range:N.array(N.number().int()).optional()})}),Lt=(e={})=>It(e),Rt=N.object({maxUses:N.number().optional(),allowedDomains:N.array(N.string()).optional(),blockedDomains:N.array(N.string()).optional(),userLocation:N.object({type:N.literal(`approximate`),city:N.string().optional(),region:N.string().optional(),country:N.string().optional(),timezone:N.string().optional()}).optional()}),zt=N.array(N.object({url:N.string(),title:N.string(),pageAge:N.string().nullable(),encryptedContent:N.string(),type:N.literal(`web_search_result`)})),Bt=yt({id:`anthropic.web_search_20250305`,name:`web_search`,inputSchema:N.object({query:N.string()}),outputSchema:zt}),Vt=(e={})=>Bt(e),Ht=N.object({maxUses:N.number().optional(),allowedDomains:N.array(N.string()).optional(),blockedDomains:N.array(N.string()).optional(),citations:N.object({enabled:N.boolean()}).optional(),maxContentTokens:N.number().optional()}),Ut=N.object({type:N.literal(`web_fetch_result`),url:N.string(),content:N.object({type:N.literal(`document`),title:N.string(),citations:N.object({enabled:N.boolean()}).optional(),source:N.union([N.object({type:N.literal(`base64`),mediaType:N.literal(`application/pdf`),data:N.string()}),N.object({type:N.literal(`text`),mediaType:N.literal(`text/plain`),data:N.string()})])}),retrievedAt:N.string().nullable()}),Wt=yt({id:`anthropic.web_fetch_20250910`,name:`web_fetch`,inputSchema:N.object({url:N.string()}),outputSchema:Ut}),Gt=(e={})=>Wt(e);function Kt({tools:e,toolChoice:t,disableParallelToolUse:n}){e=e?.length?e:void 0;let r=[],i=new Set;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};let a=[];for(let t of e)switch(t.type){case`function`:{let e=Pt(t.providerOptions);a.push({name:t.name,description:t.description,input_schema:t.inputSchema,cache_control:e});break}case`provider-defined`:switch(t.id){case`anthropic.code_execution_20250522`:i.add(`code-execution-2025-05-22`),a.push({type:`code_execution_20250522`,name:`code_execution`});break;case`anthropic.computer_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`computer`,type:`computer_20250124`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.computer_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`computer`,type:`computer_20241022`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.text_editor_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_editor`,type:`text_editor_20250124`});break;case`anthropic.text_editor_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`str_replace_editor`,type:`text_editor_20241022`});break;case`anthropic.text_editor_20250429`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`});break;case`anthropic.text_editor_20250728`:{let e=Ft.parse(t.args);a.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250728`,max_characters:e.maxCharacters});break}case`anthropic.bash_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`bash`,type:`bash_20250124`});break;case`anthropic.bash_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`bash`,type:`bash_20241022`});break;case`anthropic.web_fetch_20250910`:{i.add(`web-fetch-2025-09-10`);let e=Ht.parse(t.args);a.push({type:`web_fetch_20250910`,name:`web_fetch`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens});break}case`anthropic.web_search_20250305`:{let e=Rt.parse(t.args);a.push({type:`web_search_20250305`,name:`web_search`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation});break}default:r.push({type:`unsupported-tool`,tool:t});break}break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:a,toolChoice:n?{type:`auto`,disable_parallel_tool_use:n}:void 0,toolWarnings:r,betas:i};let o=t.type;switch(o){case`auto`:return{tools:a,toolChoice:{type:`auto`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`required`:return{tools:a,toolChoice:{type:`any`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};case`tool`:return{tools:a,toolChoice:{type:`tool`,name:t.toolName,disable_parallel_tool_use:n},toolWarnings:r,betas:i};default:throw new S({functionality:`tool choice type: ${o}`})}}var qt=N.object({type:N.literal(`code_execution_result`),stdout:N.string(),stderr:N.string(),return_code:N.number()}),Jt=yt({id:`anthropic.code_execution_20250522`,name:`code_execution`,inputSchema:N.object({code:N.string()}),outputSchema:qt}),Yt=(e={})=>Jt(e);function Xt(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 S({functionality:`URL-based text documents are not supported for citations`}):new S({functionality:`unsupported data type for text documents: ${typeof e}`})}async function Zt({prompt:e,sendReasoning:t,warnings:n}){let r=new Set,i=Qt(e),a,o=[];async function s(e){return(await pt({provider:`anthropic`,providerOptions:e,schema:Mt}))?.citations?.enabled??!1}async function c(e){let t=await pt({provider:`anthropic`,providerOptions:e,schema:Mt});return{title:t?.title,context:t?.context}}for(let e=0;e<i.length;e++){let l=i[e],u=e===i.length-1,d=l.type;switch(d){case`system`:if(a!=null)throw new S({functionality:`Multiple system messages that are separated by user/assistant messages`});a=l.messages.map(({content:e,providerOptions:t})=>({type:`text`,text:e,cache_control:Pt(t)}));break;case`user`:{let e=[];for(let t of l.messages){let{role:n,content:i}=t;switch(n){case`user`:for(let n=0;n<i.length;n++){let a=i[n],o=n===i.length-1,l=Pt(a.providerOptions)??(o?Pt(t.providerOptions):void 0);switch(a.type){case`text`:e.push({type:`text`,text:a.text,cache_control:l});break;case`file`:if(a.mediaType.startsWith(`image/`))e.push({type:`image`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`base64`,media_type:a.mediaType===`image/*`?`image/jpeg`:a.mediaType,data:Dt(a.data)},cache_control:l});else if(a.mediaType===`application/pdf`){r.add(`pdfs-2024-09-25`);let t=await s(a.providerOptions),n=await c(a.providerOptions);e.push({type:`document`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`base64`,media_type:`application/pdf`,data:Dt(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else if(a.mediaType===`text/plain`){let t=await s(a.providerOptions),n=await c(a.providerOptions);e.push({type:`document`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`text`,media_type:`text/plain`,data:Xt(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else throw new S({functionality:`media type: ${a.mediaType}`});break}}break;case`tool`:for(let n=0;n<i.length;n++){let r=i[n],a=n===i.length-1,o=Pt(r.providerOptions)??(a?Pt(t.providerOptions):void 0),s=r.output,c;switch(s.type){case`content`:c=s.value.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text,cache_control:void 0};case`media`:if(e.mediaType.startsWith(`image/`))return{type:`image`,source:{type:`base64`,media_type:e.mediaType,data:e.data},cache_control:void 0};throw new S({functionality:`media type: ${e.mediaType}`})}});break;case`text`:case`error-text`:c=s.value;break;case`json`:case`error-json`:default:c=JSON.stringify(s.value);break}e.push({type:`tool_result`,tool_use_id:r.toolCallId,content:c,is_error:s.type===`error-text`||s.type===`error-json`?!0:void 0,cache_control:o})}break;default:{let e=n;throw Error(`Unsupported role: ${e}`)}}}o.push({role:`user`,content:e});break}case`assistant`:{let e=[];for(let r=0;r<l.messages.length;r++){let i=l.messages[r],a=r===l.messages.length-1,{content:o}=i;for(let r=0;r<o.length;r++){let s=o[r],c=r===o.length-1,l=Pt(s.providerOptions)??(c?Pt(i.providerOptions):void 0);switch(s.type){case`text`:e.push({type:`text`,text:u&&a&&c?s.text.trim():s.text,cache_control:l});break;case`reasoning`:if(t){let t=await pt({provider:`anthropic`,providerOptions:s.providerOptions,schema:cn});t==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):t.signature==null?t.redactedData==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):e.push({type:`redacted_thinking`,data:t.redactedData,cache_control:l}):e.push({type:`thinking`,thinking:s.text,signature:t.signature,cache_control:l})}else n.push({type:`other`,message:`sending reasoning content is disabled for this model`});break;case`tool-call`:if(s.providerExecuted){s.toolName===`code_execution`||s.toolName===`web_fetch`||s.toolName===`web_search`?e.push({type:`server_tool_use`,id:s.toolCallId,name:s.toolName,input:s.input,cache_control:l}):n.push({type:`other`,message:`provider executed tool call for tool ${s.toolName} is not supported`});break}e.push({type:`tool_use`,id:s.toolCallId,name:s.toolName,input:s.input,cache_control:l});break;case`tool-result`:if(s.toolName===`code_execution`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=qt.parse(t.value);e.push({type:`code_execution_tool_result`,tool_use_id:s.toolCallId,content:{type:r.type,stdout:r.stdout,stderr:r.stderr,return_code:r.return_code},cache_control:l});break}if(s.toolName===`web_fetch`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=Ut.parse(t.value);e.push({type:`web_fetch_tool_result`,tool_use_id:s.toolCallId,content:{type:`web_fetch_result`,url:r.url,retrieved_at:r.retrievedAt,content:{type:`document`,title:r.content.title,citations:r.content.citations,source:{type:r.content.source.type,media_type:r.content.source.mediaType,data:r.content.source.data}}},cache_control:l});break}if(s.toolName===`web_search`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=zt.parse(t.value);e.push({type:`web_search_tool_result`,tool_use_id:s.toolCallId,content:r.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:l});break}n.push({type:`other`,message:`provider executed tool result for tool ${s.toolName} is not supported`});break}}}o.push({role:`assistant`,content:e});break}default:{let e=d;throw Error(`content type: ${e}`)}}}return{prompt:{system:a,messages:o},betas:r}}function Qt(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 $t({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 en={webSearchResult:N.object({type:N.literal(`web_search_result_location`),cited_text:N.string(),url:N.string(),title:N.string(),encrypted_index:N.string()}),pageLocation:N.object({type:N.literal(`page_location`),cited_text:N.string(),document_index:N.number(),document_title:N.string().nullable(),start_page_number:N.number(),end_page_number:N.number()}),charLocation:N.object({type:N.literal(`char_location`),cited_text:N.string(),document_index:N.number(),document_title:N.string().nullable(),start_char_index:N.number(),end_char_index:N.number()})},tn=N.discriminatedUnion(`type`,[en.webSearchResult,en.pageLocation,en.charLocation]);N.discriminatedUnion(`type`,[en.pageLocation,en.charLocation]);function nn(e,t,n,r){if(e.type===`page_location`||e.type===`char_location`){let i=rn(e,t,n);i&&r(i)}}function rn(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 an=class{constructor(e,t){this.specificationVersion=`v2`,this.modelId=e,this.config=t,this.generateId=t.generateId??Ke}supportsUrl(e){return e.protocol===`https:`}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:t=4096,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){let p=[];a!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),l!=null&&p.push({type:`unsupported-setting`,setting:`seed`}),c?.type===`json`&&(c.schema==null?p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format requires a schema. The response format is ignored.`}):u!=null&&p.push({type:`unsupported-setting`,setting:`tools`,details:`JSON response format does not support tools. The provided tools are ignored.`}));let m=c?.type===`json`&&c.schema!=null?{type:`function`,name:`json`,description:`Respond with a JSON object.`,inputSchema:c.schema}:void 0,h=await pt({provider:`anthropic`,providerOptions:f,schema:Nt}),{prompt:g,betas:_}=await Zt({prompt:e,sendReasoning:h?.sendReasoning??!0,warnings:p}),v=h?.thinking?.type===`enabled`,y=h?.thinking?.budgetTokens,b={model:this.modelId,max_tokens:t,temperature:n,top_k:i,top_p:r,stop_sequences:s,...v&&{thinking:{type:`enabled`,budget_tokens:y}},system:g.system,messages:g.messages};if(v){if(y==null)throw new S({functionality:`thinking requires a budget`});b.temperature!=null&&(b.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported when thinking is enabled`})),i!=null&&(b.top_k=void 0,p.push({type:`unsupported-setting`,setting:`topK`,details:`topK is not supported when thinking is enabled`})),r!=null&&(b.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported when thinking is enabled`})),b.max_tokens=t+y}let{tools:x,toolChoice:C,toolWarnings:w,betas:T}=Kt(m==null?{tools:u??[],toolChoice:d,disableParallelToolUse:h?.disableParallelToolUse}:{tools:[m],toolChoice:{type:`tool`,toolName:m.name},disableParallelToolUse:!0});return{args:{...b,tools:x,tool_choice:C},warnings:[...p,...w],betas:new Set([..._,...T]),usesJsonResponseTool:m!=null}}async getHeaders({betas:e,headers:t}){return Ve(await bt(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 ht({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(t),failedResponseHandler:jt,successfulResponseHandler:Ct(on),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)nn(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:$t({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 ht({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(o),failedResponseHandler:jt,successfulResponseHandler:St(sn),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;nn(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=$t({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}}}},on=N.object({type:N.literal(`message`),id:N.string().nullish(),model:N.string().nullish(),content:N.array(N.discriminatedUnion(`type`,[N.object({type:N.literal(`text`),text:N.string(),citations:N.array(tn).optional()}),N.object({type:N.literal(`thinking`),thinking:N.string(),signature:N.string()}),N.object({type:N.literal(`redacted_thinking`),data:N.string()}),N.object({type:N.literal(`tool_use`),id:N.string(),name:N.string(),input:N.unknown()}),N.object({type:N.literal(`server_tool_use`),id:N.string(),name:N.string(),input:N.record(N.string(),N.unknown()).nullish()}),N.object({type:N.literal(`web_fetch_tool_result`),tool_use_id:N.string(),content:N.union([N.object({type:N.literal(`web_fetch_result`),url:N.string(),retrieved_at:N.string(),content:N.object({type:N.literal(`document`),title:N.string().nullable(),citations:N.object({enabled:N.boolean()}).optional(),source:N.object({type:N.literal(`text`),media_type:N.string(),data:N.string()})})}),N.object({type:N.literal(`web_fetch_tool_result_error`),error_code:N.string()})])}),N.object({type:N.literal(`web_search_tool_result`),tool_use_id:N.string(),content:N.union([N.array(N.object({type:N.literal(`web_search_result`),url:N.string(),title:N.string(),encrypted_content:N.string(),page_age:N.string().nullish()})),N.object({type:N.literal(`web_search_tool_result_error`),error_code:N.string()})])}),N.object({type:N.literal(`code_execution_tool_result`),tool_use_id:N.string(),content:N.union([N.object({type:N.literal(`code_execution_result`),stdout:N.string(),stderr:N.string(),return_code:N.number()}),N.object({type:N.literal(`code_execution_tool_result_error`),error_code:N.string()})])})])),stop_reason:N.string().nullish(),stop_sequence:N.string().nullish(),usage:N.looseObject({input_tokens:N.number(),output_tokens:N.number(),cache_creation_input_tokens:N.number().nullish(),cache_read_input_tokens:N.number().nullish()})}),sn=N.discriminatedUnion(`type`,[N.object({type:N.literal(`message_start`),message:N.object({id:N.string().nullish(),model:N.string().nullish(),usage:N.looseObject({input_tokens:N.number(),cache_creation_input_tokens:N.number().nullish(),cache_read_input_tokens:N.number().nullish()})})}),N.object({type:N.literal(`content_block_start`),index:N.number(),content_block:N.discriminatedUnion(`type`,[N.object({type:N.literal(`text`),text:N.string()}),N.object({type:N.literal(`thinking`),thinking:N.string()}),N.object({type:N.literal(`tool_use`),id:N.string(),name:N.string()}),N.object({type:N.literal(`redacted_thinking`),data:N.string()}),N.object({type:N.literal(`server_tool_use`),id:N.string(),name:N.string(),input:N.record(N.string(),N.unknown()).nullish()}),N.object({type:N.literal(`web_fetch_tool_result`),tool_use_id:N.string(),content:N.union([N.object({type:N.literal(`web_fetch_result`),url:N.string(),retrieved_at:N.string(),content:N.object({type:N.literal(`document`),title:N.string().nullable(),citations:N.object({enabled:N.boolean()}).optional(),source:N.object({type:N.literal(`text`),media_type:N.string(),data:N.string()})})}),N.object({type:N.literal(`web_fetch_tool_result_error`),error_code:N.string()})])}),N.object({type:N.literal(`web_search_tool_result`),tool_use_id:N.string(),content:N.union([N.array(N.object({type:N.literal(`web_search_result`),url:N.string(),title:N.string(),encrypted_content:N.string(),page_age:N.string().nullish()})),N.object({type:N.literal(`web_search_tool_result_error`),error_code:N.string()})])}),N.object({type:N.literal(`code_execution_tool_result`),tool_use_id:N.string(),content:N.union([N.object({type:N.literal(`code_execution_result`),stdout:N.string(),stderr:N.string(),return_code:N.number()}),N.object({type:N.literal(`code_execution_tool_result_error`),error_code:N.string()})])})])}),N.object({type:N.literal(`content_block_delta`),index:N.number(),delta:N.discriminatedUnion(`type`,[N.object({type:N.literal(`input_json_delta`),partial_json:N.string()}),N.object({type:N.literal(`text_delta`),text:N.string()}),N.object({type:N.literal(`thinking_delta`),thinking:N.string()}),N.object({type:N.literal(`signature_delta`),signature:N.string()}),N.object({type:N.literal(`citations_delta`),citation:tn})])}),N.object({type:N.literal(`content_block_stop`),index:N.number()}),N.object({type:N.literal(`error`),error:N.object({type:N.string(),message:N.string()})}),N.object({type:N.literal(`message_delta`),delta:N.object({stop_reason:N.string().nullish(),stop_sequence:N.string().nullish()}),usage:N.looseObject({output_tokens:N.number(),cache_creation_input_tokens:N.number().nullish()})}),N.object({type:N.literal(`message_stop`)}),N.object({type:N.literal(`ping`)})]),cn=N.object({signature:N.string().optional(),redactedData:N.string().optional()}),ln=vt({id:`anthropic.bash_20241022`,name:`bash`,inputSchema:M.object({command:M.string(),restart:M.boolean().optional()})}),un=vt({id:`anthropic.bash_20250124`,name:`bash`,inputSchema:M.object({command:M.string(),restart:M.boolean().optional()})}),dn=vt({id:`anthropic.computer_20241022`,name:`computer`,inputSchema:N.object({action:N.enum([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:N.array(N.number().int()).optional(),text:N.string().optional()})}),fn=vt({id:`anthropic.computer_20250124`,name:`computer`,inputSchema:N.object({action:N.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:N.tuple([N.number().int(),N.number().int()]).optional(),duration:N.number().optional(),scroll_amount:N.number().optional(),scroll_direction:N.enum([`up`,`down`,`left`,`right`]).optional(),start_coordinate:N.tuple([N.number().int(),N.number().int()]).optional(),text:N.string().optional()})}),pn=vt({id:`anthropic.text_editor_20241022`,name:`str_replace_editor`,inputSchema:N.object({command:N.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:N.string(),file_text:N.string().optional(),insert_line:N.number().int().optional(),new_str:N.string().optional(),old_str:N.string().optional(),view_range:N.array(N.number().int()).optional()})}),mn=vt({id:`anthropic.text_editor_20250124`,name:`str_replace_editor`,inputSchema:N.object({command:N.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:N.string(),file_text:N.string().optional(),insert_line:N.number().int().optional(),new_str:N.string().optional(),old_str:N.string().optional(),view_range:N.array(N.number().int()).optional()})}),hn=vt({id:`anthropic.text_editor_20250429`,name:`str_replace_based_edit_tool`,inputSchema:N.object({command:N.enum([`view`,`create`,`str_replace`,`insert`]),path:N.string(),file_text:N.string().optional(),insert_line:N.number().int().optional(),new_str:N.string().optional(),old_str:N.string().optional(),view_range:N.array(N.number().int()).optional()})}),gn={bash_20241022:ln,bash_20250124:un,codeExecution_20250522:Yt,computer_20241022:dn,computer_20250124:fn,textEditor_20241022:pn,textEditor_20250124:mn,textEditor_20250429:hn,textEditor_20250728:Lt,webFetch_20250910:Gt,webSearch_20250305:Vt};function _n(e={}){let t=Ot(e.baseURL)??`https://api.anthropic.com/v1`,n=()=>Ge({"anthropic-version":`2023-06-01`,"x-api-key":Ze({apiKey:e.apiKey,environmentVariableName:`ANTHROPIC_API_KEY`,description:`Anthropic`}),...e.headers},`ai-sdk/anthropic/${kt}`),r=r=>new an(r,{provider:`anthropic.messages`,baseURL:t,headers:n,fetch:e.fetch,generateId:e.generateId??Ke,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})}),i=function(e){if(new.target)throw Error(`The Anthropic model function cannot be called with the new keyword.`);return r(e)};return i.languageModel=r,i.chat=r,i.messages=r,i.textEmbeddingModel=e=>{throw new v({modelId:e,modelType:`textEmbeddingModel`})},i.imageModel=e=>{throw new v({modelId:e,modelType:`imageModel`})},i.tools=gn,i}_n();function vn(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function yn(e){return Object.fromEntries([...e.headers])}function bn(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 xn(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function Sn(e,...t){let n=xn(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var Cn=(({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new p({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();function wn(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Tn=[`fetch failed`,`failed to fetch`];function En({error:e,url:t,requestBodyValues:n}){if(wn(e))return e;if(e instanceof TypeError&&Tn.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new s({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}var Dn=`3.0.10`;function On({apiKey:e,environmentVariableName:t,apiKeyParameterName:n=`apiKey`,description:r}){if(typeof e==`string`)return e;if(e!=null)throw new _({message:`${r} API key must be a string.`});if(typeof process>`u`)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!=`string`)throw new _({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var kn=/"__proto__"\s*:/,An=/"constructor"\s*:/;function jn(e){let t=JSON.parse(e);return typeof t!=`object`||!t||kn.test(e)===!1&&An.test(e)===!1?t:Mn(t)}function Mn(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 Nn(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return jn(e)}finally{Error.stackTraceLimit=t}}var Pn=Symbol.for(`vercel.ai.validator`);function Fn(e){return{[Pn]:!0,validate:e}}function In(e){return typeof e==`object`&&!!e&&Pn in e&&e[Pn]===!0&&`validate`in e}function Ln(e){return In(e)?e:Rn(e)}function Rn(e){return Fn(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new x({value:t,cause:n.issues})}})}async function zn({value:e,schema:t}){let n=await Bn({value:e,schema:t});if(!n.success)throw x.wrap({value:e,cause:n.error});return n.value}async function Bn({value:e,schema:t}){let n=Ln(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:x.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:x.wrap({value:e,cause:t}),rawValue:e}}}async function Vn({text:e,schema:t}){try{let n=Nn(e);return t==null?n:zn({value:n,schema:t})}catch(t){throw g.isInstance(t)||x.isInstance(t)?t:new g({text:e,cause:t})}}async function Hn({text:e,schema:t}){try{let n=Nn(e);return t==null?{success:!0,value:n,rawValue:n}:await Bn({value:n,schema:t})}catch(t){return{success:!1,error:g.isInstance(t)?t:new g({text:e,cause:t}),rawValue:void 0}}}function Un({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new d).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await Hn({text:e,schema:t}))}}))}async function Wn({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;let r=await Bn({value:t[e],schema:n});if(!r.success)throw new p({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:r.error});return r.value}var Gn=()=>globalThis.fetch,Kn=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>qn({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),qn=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=Gn()})=>{try{let c=await o(e,{method:`POST`,headers:Sn(t,`ai-sdk/provider-utils/${Dn}`,bn()),body:n.content,signal:a}),l=yn(c);if(!c.ok){let t;try{t=await i({response:c,url:e,requestBodyValues:n.values})}catch(t){throw wn(t)||s.isInstance(t)?t:new s({message:`Failed to process error response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw t.value}try{return await r({response:c,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(wn(t)||s.isInstance(t))?t:new s({message:`Failed to process successful response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(t){throw En({error:t,url:e,requestBodyValues:n.values})}};function Jn(e){return e}function Yn({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>Jn({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function Xn({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>Jn({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 Zn(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var Qn=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),c=yn(r);if(o.trim()===``)return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})};try{let l=await Vn({text:o,schema:e});return{responseHeaders:c,value:new s({message:t(l),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})}}},$n=e=>async({response:t})=>{let n=yn(t);if(t.body==null)throw new u({});return{responseHeaders:n,value:Un({stream:t.body,schema:e})}},er=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await Hn({text:i,schema:e}),o=yn(t);if(!a.success)throw new s({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},{btoa:tr,atob:nr}=globalThis;function rr(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return tr(t)}function ir(e){return e instanceof Uint8Array?rr(e):e}function ar(e){return e?.replace(/\/$/,``)}var or=`2.0.17`,sr=N.object({error:N.object({code:N.number().nullable(),message:N.string(),status:N.string()})}),cr=Qn({errorSchema:sr,errorToMessage:e=>e.error.message}),lr=N.object({outputDimensionality:N.number().optional(),taskType:N.enum([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional()}),ur=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){let i=await Wn({provider:`google`,providerOptions:r,schema:lr});if(e.length>this.maxEmbeddingsPerCall)throw new b({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let a=vn(await Zn(this.config.headers),t);if(e.length===1){let{responseHeaders:t,value:r,rawValue:o}=await Kn({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:a,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType},failedResponseHandler:cr,successfulResponseHandler:er(fr),abortSignal:n,fetch:this.config.fetch});return{embeddings:[r.embedding.values],usage:void 0,response:{headers:t,body:o}}}let{responseHeaders:o,value:s,rawValue:c}=await Kn({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:a,body:{requests:e.map(e=>({model:`models/${this.modelId}`,content:{role:`user`,parts:[{text:e}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType}))},failedResponseHandler:cr,successfulResponseHandler:er(dr),abortSignal:n,fetch:this.config.fetch});return{embeddings:s.embeddings.map(e=>e.values),usage:void 0,response:{headers:o,body:c}}}},dr=N.object({embeddings:N.array(N.object({values:N.array(N.number())}))}),fr=N.object({embedding:N.object({values:N.array(N.number())})});function pr(e){if(e==null||mr(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]=pr(n),e),{})),a&&(p.items=Array.isArray(a)?a.map(pr):pr(a)),o&&(p.allOf=o.map(pr)),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=pr(e[0]);typeof t==`object`&&(p.nullable=!0,Object.assign(p,t))}else p.anyOf=e.map(pr),p.nullable=!0}else p.anyOf=s.map(pr);return c&&(p.oneOf=c.map(pr)),d!==void 0&&(p.minLength=d),p}function mr(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}function hr(e,t){let n=[],r=[],i=!0,a=t?.isGemmaModel??!1;for(let{role:t,content:a}of e)switch(t){case`system`:if(!i)throw new S({functionality:`system messages are only supported at the beginning of the conversation`});n.push({text:a});break;case`user`:{i=!1;let e=[];for(let t of a)switch(t.type){case`text`:e.push({text:t.text});break;case`file`:{let n=t.mediaType===`image/*`?`image/jpeg`:t.mediaType;e.push(t.data instanceof URL?{fileData:{mimeType:n,fileUri:t.data.toString()}}:{inlineData:{mimeType:n,data:ir(t.data)}});break}}r.push({role:`user`,parts:e});break}case`assistant`:i=!1,r.push({role:`model`,parts:a.map(e=>{switch(e.type){case`text`:return e.text.length===0?void 0:{text:e.text,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`reasoning`:return e.text.length===0?void 0:{text:e.text,thought:!0,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`file`:if(e.mediaType!==`image/png`)throw new S({functionality:`Only PNG images are supported in assistant messages`});if(e.data instanceof URL)throw new S({functionality:`File data URLs in assistant messages are not supported`});return{inlineData:{mimeType:e.mediaType,data:ir(e.data)}};case`tool-call`:return{functionCall:{name:e.toolName,args:e.input},thoughtSignature:e.providerOptions?.google?.thoughtSignature}}}).filter(e=>e!==void 0)});break;case`tool`:{i=!1;let e=[];for(let t of a){let n=t.output;if(n.type===`content`)for(let r of n.value)switch(r.type){case`text`:e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:r.text}}});break;case`media`:e.push({inlineData:{mimeType:r.mediaType,data:r.data}},{text:`Tool executed successfully and returned this image as a response`});break;default:e.push({text:JSON.stringify(r)});break}else e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:n.value}}})}r.push({role:`user`,parts:e});break}}if(a&&n.length>0&&r.length>0&&r[0].role===`user`){let e=n.map(e=>e.text).join(`
1
+ import{__commonJSMin as e,__esmMin as t,__export as n,__reExport as r,__require as i,__toCommonJS as a,__toESM as o}from"../chunk-D9KrCrVq.js";import{APICallError as s,APIServerURLEnvironmentVariable as c,Agent as l,EmptyResponseBodyError as u,EventSourceParserStream as d,Hono as f,InvalidArgumentError as p,InvalidPromptError as m,InvalidResponseDataError as h,JSONParseError as g,LoadAPIKeyError as _,NoSuchModelError as v,StreamResponseFormatHeader as y,TooManyEmbeddingValuesForCallError as b,TypeValidationError as x,UnsupportedFunctionalityError as S,createGatewayProvider as C,createServerAdapter as w,hc as T,isToolApprovalOutput as E,lastUIOptions as D,tools as O,validator as k}from"../index.node-xL4mvvNL.js";import"../token-error-488npYdU.js";import"../esm-CbZfjZBn.js";import{resolveConfig as A}from"../build-DYI55eX2.js";import{createRequire as j}from"node:module";import M,{z as N}from"zod/v4";import{ZodFirstPartyTypeKind as ee}from"zod/v3";import{Buffer as te}from"node:buffer";import*as P from"node:fs";import F,{existsSync as I,mkdirSync as ne,readFileSync as L,unlinkSync as re,writeFileSync as R}from"node:fs";import{fileURLToPath as ie}from"node:url";import{Writable as z}from"node:stream";import{promisify as ae,stripVTControlCharacters as oe}from"node:util";import{createHash as se}from"node:crypto";import ce,{createServer as le}from"http";import{dirname as B,join as ue}from"path";import{existsSync as de,mkdirSync as fe,readFileSync as pe,watch as me,writeFileSync as he}from"fs";import{convertToModelMessages as ge,isToolOrDynamicToolUIPart as _e,readUIMessageStream as ve,streamText as ye,tool as be}from"ai";import{readFile as xe,stat as V,writeFile as Se}from"fs/promises";import{spawn as Ce}from"child_process";import{createContext as we,useCallback as H,useEffect as U,useMemo as Te,useRef as W,useState as G}from"react";import K,{z as q}from"zod";import*as Ee from"node:path";import De,{dirname as Oe,join as ke}from"node:path";import J,{stdin as Ae,stdout as je}from"node:process";import Me from"node:os";import Ne from"node:tty";import*as Pe from"node:readline";import Fe from"node:readline";import Ie,{execFile as Le}from"node:child_process";import Re,{constants as ze}from"node:fs/promises";import"@blink-sdk/compute-protocol/client";import{createInMemoryClientServer as Be}from"@blink-sdk/compute-protocol/transport";function Ve(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function He(e){return Object.fromEntries([...e.headers])}function Ue(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 We(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function Ge(e,...t){let n=We(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var Ke=(({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new p({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();function qe(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Je=[`fetch failed`,`failed to fetch`];function Ye({error:e,url:t,requestBodyValues:n}){if(qe(e))return e;if(e instanceof TypeError&&Je.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new s({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}var Xe=`3.0.10`;function Ze({apiKey:e,environmentVariableName:t,apiKeyParameterName:n=`apiKey`,description:r}){if(typeof e==`string`)return e;if(e!=null)throw new _({message:`${r} API key must be a string.`});if(typeof process>`u`)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!=`string`)throw new _({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var Qe=/"__proto__"\s*:/,$e=/"constructor"\s*:/;function et(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Qe.test(e)===!1&&$e.test(e)===!1?t:tt(t)}function tt(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 nt(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return et(e)}finally{Error.stackTraceLimit=t}}var rt=Symbol.for(`vercel.ai.validator`);function it(e){return{[rt]:!0,validate:e}}function at(e){return typeof e==`object`&&!!e&&rt in e&&e[rt]===!0&&`validate`in e}function ot(e){return at(e)?e:st(e)}function st(e){return it(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new x({value:t,cause:n.issues})}})}async function ct({value:e,schema:t}){let n=await lt({value:e,schema:t});if(!n.success)throw x.wrap({value:e,cause:n.error});return n.value}async function lt({value:e,schema:t}){let n=ot(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:x.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:x.wrap({value:e,cause:t}),rawValue:e}}}async function ut({text:e,schema:t}){try{let n=nt(e);return t==null?n:ct({value:n,schema:t})}catch(t){throw g.isInstance(t)||x.isInstance(t)?t:new g({text:e,cause:t})}}async function dt({text:e,schema:t}){try{let n=nt(e);return t==null?{success:!0,value:n,rawValue:n}:await lt({value:n,schema:t})}catch(t){return{success:!1,error:g.isInstance(t)?t:new g({text:e,cause:t}),rawValue:void 0}}}function ft({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new d).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await dt({text:e,schema:t}))}}))}async function pt({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;let r=await lt({value:t[e],schema:n});if(!r.success)throw new p({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:r.error});return r.value}var mt=()=>globalThis.fetch,ht=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>gt({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),gt=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=mt()})=>{try{let c=await o(e,{method:`POST`,headers:Ge(t,`ai-sdk/provider-utils/${Xe}`,Ue()),body:n.content,signal:a}),l=He(c);if(!c.ok){let t;try{t=await i({response:c,url:e,requestBodyValues:n.values})}catch(t){throw qe(t)||s.isInstance(t)?t:new s({message:`Failed to process error response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw t.value}try{return await r({response:c,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(qe(t)||s.isInstance(t))?t:new s({message:`Failed to process successful response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(t){throw Ye({error:t,url:e,requestBodyValues:n.values})}};function _t(e){return e}function vt({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>_t({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function yt({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>_t({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 bt(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var xt=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),c=He(r);if(o.trim()===``)return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})};try{let l=await ut({text:o,schema:e});return{responseHeaders:c,value:new s({message:t(l),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})}}},St=e=>async({response:t})=>{let n=He(t);if(t.body==null)throw new u({});return{responseHeaders:n,value:ft({stream:t.body,schema:e})}},Ct=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await dt({text:i,schema:e}),o=He(t);if(!a.success)throw new s({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},{btoa:wt,atob:Tt}=globalThis;function Et(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return wt(t)}function Dt(e){return e instanceof Uint8Array?Et(e):e}function Ot(e){return e?.replace(/\/$/,``)}var kt=`2.0.23`,At=N.object({type:N.literal(`error`),error:N.object({type:N.string(),message:N.string()})}),jt=xt({errorSchema:At,errorToMessage:e=>e.error.message}),Mt=N.object({citations:N.object({enabled:N.boolean()}).optional(),title:N.string().optional(),context:N.string().optional()}),Nt=N.object({sendReasoning:N.boolean().optional(),thinking:N.object({type:N.union([N.literal(`enabled`),N.literal(`disabled`)]),budgetTokens:N.number().optional()}).optional(),disableParallelToolUse:N.boolean().optional(),cacheControl:N.object({type:N.literal(`ephemeral`),ttl:N.union([N.literal(`5m`),N.literal(`1h`)]).optional()}).optional()});function Pt(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var Ft=N.object({maxCharacters:N.number().optional()}),It=vt({id:`anthropic.text_editor_20250728`,name:`str_replace_based_edit_tool`,inputSchema:N.object({command:N.enum([`view`,`create`,`str_replace`,`insert`]),path:N.string(),file_text:N.string().optional(),insert_line:N.number().int().optional(),new_str:N.string().optional(),old_str:N.string().optional(),view_range:N.array(N.number().int()).optional()})}),Lt=(e={})=>It(e),Rt=N.object({maxUses:N.number().optional(),allowedDomains:N.array(N.string()).optional(),blockedDomains:N.array(N.string()).optional(),userLocation:N.object({type:N.literal(`approximate`),city:N.string().optional(),region:N.string().optional(),country:N.string().optional(),timezone:N.string().optional()}).optional()}),zt=N.array(N.object({url:N.string(),title:N.string(),pageAge:N.string().nullable(),encryptedContent:N.string(),type:N.literal(`web_search_result`)})),Bt=yt({id:`anthropic.web_search_20250305`,name:`web_search`,inputSchema:N.object({query:N.string()}),outputSchema:zt}),Vt=(e={})=>Bt(e),Ht=N.object({maxUses:N.number().optional(),allowedDomains:N.array(N.string()).optional(),blockedDomains:N.array(N.string()).optional(),citations:N.object({enabled:N.boolean()}).optional(),maxContentTokens:N.number().optional()}),Ut=N.object({type:N.literal(`web_fetch_result`),url:N.string(),content:N.object({type:N.literal(`document`),title:N.string(),citations:N.object({enabled:N.boolean()}).optional(),source:N.union([N.object({type:N.literal(`base64`),mediaType:N.literal(`application/pdf`),data:N.string()}),N.object({type:N.literal(`text`),mediaType:N.literal(`text/plain`),data:N.string()})])}),retrievedAt:N.string().nullable()}),Wt=yt({id:`anthropic.web_fetch_20250910`,name:`web_fetch`,inputSchema:N.object({url:N.string()}),outputSchema:Ut}),Gt=(e={})=>Wt(e);function Kt({tools:e,toolChoice:t,disableParallelToolUse:n}){e=e?.length?e:void 0;let r=[],i=new Set;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};let a=[];for(let t of e)switch(t.type){case`function`:{let e=Pt(t.providerOptions);a.push({name:t.name,description:t.description,input_schema:t.inputSchema,cache_control:e});break}case`provider-defined`:switch(t.id){case`anthropic.code_execution_20250522`:i.add(`code-execution-2025-05-22`),a.push({type:`code_execution_20250522`,name:`code_execution`});break;case`anthropic.computer_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`computer`,type:`computer_20250124`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.computer_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`computer`,type:`computer_20241022`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.text_editor_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_editor`,type:`text_editor_20250124`});break;case`anthropic.text_editor_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`str_replace_editor`,type:`text_editor_20241022`});break;case`anthropic.text_editor_20250429`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`});break;case`anthropic.text_editor_20250728`:{let e=Ft.parse(t.args);a.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250728`,max_characters:e.maxCharacters});break}case`anthropic.bash_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`bash`,type:`bash_20250124`});break;case`anthropic.bash_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`bash`,type:`bash_20241022`});break;case`anthropic.web_fetch_20250910`:{i.add(`web-fetch-2025-09-10`);let e=Ht.parse(t.args);a.push({type:`web_fetch_20250910`,name:`web_fetch`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens});break}case`anthropic.web_search_20250305`:{let e=Rt.parse(t.args);a.push({type:`web_search_20250305`,name:`web_search`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation});break}default:r.push({type:`unsupported-tool`,tool:t});break}break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:a,toolChoice:n?{type:`auto`,disable_parallel_tool_use:n}:void 0,toolWarnings:r,betas:i};let o=t.type;switch(o){case`auto`:return{tools:a,toolChoice:{type:`auto`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`required`:return{tools:a,toolChoice:{type:`any`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};case`tool`:return{tools:a,toolChoice:{type:`tool`,name:t.toolName,disable_parallel_tool_use:n},toolWarnings:r,betas:i};default:throw new S({functionality:`tool choice type: ${o}`})}}var qt=N.object({type:N.literal(`code_execution_result`),stdout:N.string(),stderr:N.string(),return_code:N.number()}),Jt=yt({id:`anthropic.code_execution_20250522`,name:`code_execution`,inputSchema:N.object({code:N.string()}),outputSchema:qt}),Yt=(e={})=>Jt(e);function Xt(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 S({functionality:`URL-based text documents are not supported for citations`}):new S({functionality:`unsupported data type for text documents: ${typeof e}`})}async function Zt({prompt:e,sendReasoning:t,warnings:n}){let r=new Set,i=Qt(e),a,o=[];async function s(e){return(await pt({provider:`anthropic`,providerOptions:e,schema:Mt}))?.citations?.enabled??!1}async function c(e){let t=await pt({provider:`anthropic`,providerOptions:e,schema:Mt});return{title:t?.title,context:t?.context}}for(let e=0;e<i.length;e++){let l=i[e],u=e===i.length-1,d=l.type;switch(d){case`system`:if(a!=null)throw new S({functionality:`Multiple system messages that are separated by user/assistant messages`});a=l.messages.map(({content:e,providerOptions:t})=>({type:`text`,text:e,cache_control:Pt(t)}));break;case`user`:{let e=[];for(let t of l.messages){let{role:n,content:i}=t;switch(n){case`user`:for(let n=0;n<i.length;n++){let a=i[n],o=n===i.length-1,l=Pt(a.providerOptions)??(o?Pt(t.providerOptions):void 0);switch(a.type){case`text`:e.push({type:`text`,text:a.text,cache_control:l});break;case`file`:if(a.mediaType.startsWith(`image/`))e.push({type:`image`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`base64`,media_type:a.mediaType===`image/*`?`image/jpeg`:a.mediaType,data:Dt(a.data)},cache_control:l});else if(a.mediaType===`application/pdf`){r.add(`pdfs-2024-09-25`);let t=await s(a.providerOptions),n=await c(a.providerOptions);e.push({type:`document`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`base64`,media_type:`application/pdf`,data:Dt(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else if(a.mediaType===`text/plain`){let t=await s(a.providerOptions),n=await c(a.providerOptions);e.push({type:`document`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`text`,media_type:`text/plain`,data:Xt(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else throw new S({functionality:`media type: ${a.mediaType}`});break}}break;case`tool`:for(let n=0;n<i.length;n++){let r=i[n],a=n===i.length-1,o=Pt(r.providerOptions)??(a?Pt(t.providerOptions):void 0),s=r.output,c;switch(s.type){case`content`:c=s.value.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text,cache_control:void 0};case`media`:if(e.mediaType.startsWith(`image/`))return{type:`image`,source:{type:`base64`,media_type:e.mediaType,data:e.data},cache_control:void 0};throw new S({functionality:`media type: ${e.mediaType}`})}});break;case`text`:case`error-text`:c=s.value;break;case`json`:case`error-json`:default:c=JSON.stringify(s.value);break}e.push({type:`tool_result`,tool_use_id:r.toolCallId,content:c,is_error:s.type===`error-text`||s.type===`error-json`?!0:void 0,cache_control:o})}break;default:{let e=n;throw Error(`Unsupported role: ${e}`)}}}o.push({role:`user`,content:e});break}case`assistant`:{let e=[];for(let r=0;r<l.messages.length;r++){let i=l.messages[r],a=r===l.messages.length-1,{content:o}=i;for(let r=0;r<o.length;r++){let s=o[r],c=r===o.length-1,l=Pt(s.providerOptions)??(c?Pt(i.providerOptions):void 0);switch(s.type){case`text`:e.push({type:`text`,text:u&&a&&c?s.text.trim():s.text,cache_control:l});break;case`reasoning`:if(t){let t=await pt({provider:`anthropic`,providerOptions:s.providerOptions,schema:cn});t==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):t.signature==null?t.redactedData==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):e.push({type:`redacted_thinking`,data:t.redactedData,cache_control:l}):e.push({type:`thinking`,thinking:s.text,signature:t.signature,cache_control:l})}else n.push({type:`other`,message:`sending reasoning content is disabled for this model`});break;case`tool-call`:if(s.providerExecuted){s.toolName===`code_execution`||s.toolName===`web_fetch`||s.toolName===`web_search`?e.push({type:`server_tool_use`,id:s.toolCallId,name:s.toolName,input:s.input,cache_control:l}):n.push({type:`other`,message:`provider executed tool call for tool ${s.toolName} is not supported`});break}e.push({type:`tool_use`,id:s.toolCallId,name:s.toolName,input:s.input,cache_control:l});break;case`tool-result`:if(s.toolName===`code_execution`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=qt.parse(t.value);e.push({type:`code_execution_tool_result`,tool_use_id:s.toolCallId,content:{type:r.type,stdout:r.stdout,stderr:r.stderr,return_code:r.return_code},cache_control:l});break}if(s.toolName===`web_fetch`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=Ut.parse(t.value);e.push({type:`web_fetch_tool_result`,tool_use_id:s.toolCallId,content:{type:`web_fetch_result`,url:r.url,retrieved_at:r.retrievedAt,content:{type:`document`,title:r.content.title,citations:r.content.citations,source:{type:r.content.source.type,media_type:r.content.source.mediaType,data:r.content.source.data}}},cache_control:l});break}if(s.toolName===`web_search`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=zt.parse(t.value);e.push({type:`web_search_tool_result`,tool_use_id:s.toolCallId,content:r.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:l});break}n.push({type:`other`,message:`provider executed tool result for tool ${s.toolName} is not supported`});break}}}o.push({role:`assistant`,content:e});break}default:{let e=d;throw Error(`content type: ${e}`)}}}return{prompt:{system:a,messages:o},betas:r}}function Qt(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 $t({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 en={webSearchResult:N.object({type:N.literal(`web_search_result_location`),cited_text:N.string(),url:N.string(),title:N.string(),encrypted_index:N.string()}),pageLocation:N.object({type:N.literal(`page_location`),cited_text:N.string(),document_index:N.number(),document_title:N.string().nullable(),start_page_number:N.number(),end_page_number:N.number()}),charLocation:N.object({type:N.literal(`char_location`),cited_text:N.string(),document_index:N.number(),document_title:N.string().nullable(),start_char_index:N.number(),end_char_index:N.number()})},tn=N.discriminatedUnion(`type`,[en.webSearchResult,en.pageLocation,en.charLocation]);N.discriminatedUnion(`type`,[en.pageLocation,en.charLocation]);function nn(e,t,n,r){if(e.type===`page_location`||e.type===`char_location`){let i=rn(e,t,n);i&&r(i)}}function rn(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 an=class{constructor(e,t){this.specificationVersion=`v2`,this.modelId=e,this.config=t,this.generateId=t.generateId??Ke}supportsUrl(e){return e.protocol===`https:`}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:t=4096,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){let p=[];a!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),l!=null&&p.push({type:`unsupported-setting`,setting:`seed`}),c?.type===`json`&&(c.schema==null?p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format requires a schema. The response format is ignored.`}):u!=null&&p.push({type:`unsupported-setting`,setting:`tools`,details:`JSON response format does not support tools. The provided tools are ignored.`}));let m=c?.type===`json`&&c.schema!=null?{type:`function`,name:`json`,description:`Respond with a JSON object.`,inputSchema:c.schema}:void 0,h=await pt({provider:`anthropic`,providerOptions:f,schema:Nt}),{prompt:g,betas:_}=await Zt({prompt:e,sendReasoning:h?.sendReasoning??!0,warnings:p}),v=h?.thinking?.type===`enabled`,y=h?.thinking?.budgetTokens,b={model:this.modelId,max_tokens:t,temperature:n,top_k:i,top_p:r,stop_sequences:s,...v&&{thinking:{type:`enabled`,budget_tokens:y}},system:g.system,messages:g.messages};if(v){if(y==null)throw new S({functionality:`thinking requires a budget`});b.temperature!=null&&(b.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported when thinking is enabled`})),i!=null&&(b.top_k=void 0,p.push({type:`unsupported-setting`,setting:`topK`,details:`topK is not supported when thinking is enabled`})),r!=null&&(b.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported when thinking is enabled`})),b.max_tokens=t+y}let{tools:x,toolChoice:C,toolWarnings:w,betas:T}=Kt(m==null?{tools:u??[],toolChoice:d,disableParallelToolUse:h?.disableParallelToolUse}:{tools:[m],toolChoice:{type:`tool`,toolName:m.name},disableParallelToolUse:!0});return{args:{...b,tools:x,tool_choice:C},warnings:[...p,...w],betas:new Set([..._,...T]),usesJsonResponseTool:m!=null}}async getHeaders({betas:e,headers:t}){return Ve(await bt(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 ht({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(t),failedResponseHandler:jt,successfulResponseHandler:Ct(on),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)nn(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:$t({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 ht({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(o),failedResponseHandler:jt,successfulResponseHandler:St(sn),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;nn(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=$t({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}}}},on=N.object({type:N.literal(`message`),id:N.string().nullish(),model:N.string().nullish(),content:N.array(N.discriminatedUnion(`type`,[N.object({type:N.literal(`text`),text:N.string(),citations:N.array(tn).optional()}),N.object({type:N.literal(`thinking`),thinking:N.string(),signature:N.string()}),N.object({type:N.literal(`redacted_thinking`),data:N.string()}),N.object({type:N.literal(`tool_use`),id:N.string(),name:N.string(),input:N.unknown()}),N.object({type:N.literal(`server_tool_use`),id:N.string(),name:N.string(),input:N.record(N.string(),N.unknown()).nullish()}),N.object({type:N.literal(`web_fetch_tool_result`),tool_use_id:N.string(),content:N.union([N.object({type:N.literal(`web_fetch_result`),url:N.string(),retrieved_at:N.string(),content:N.object({type:N.literal(`document`),title:N.string().nullable(),citations:N.object({enabled:N.boolean()}).optional(),source:N.object({type:N.literal(`text`),media_type:N.string(),data:N.string()})})}),N.object({type:N.literal(`web_fetch_tool_result_error`),error_code:N.string()})])}),N.object({type:N.literal(`web_search_tool_result`),tool_use_id:N.string(),content:N.union([N.array(N.object({type:N.literal(`web_search_result`),url:N.string(),title:N.string(),encrypted_content:N.string(),page_age:N.string().nullish()})),N.object({type:N.literal(`web_search_tool_result_error`),error_code:N.string()})])}),N.object({type:N.literal(`code_execution_tool_result`),tool_use_id:N.string(),content:N.union([N.object({type:N.literal(`code_execution_result`),stdout:N.string(),stderr:N.string(),return_code:N.number()}),N.object({type:N.literal(`code_execution_tool_result_error`),error_code:N.string()})])})])),stop_reason:N.string().nullish(),stop_sequence:N.string().nullish(),usage:N.looseObject({input_tokens:N.number(),output_tokens:N.number(),cache_creation_input_tokens:N.number().nullish(),cache_read_input_tokens:N.number().nullish()})}),sn=N.discriminatedUnion(`type`,[N.object({type:N.literal(`message_start`),message:N.object({id:N.string().nullish(),model:N.string().nullish(),usage:N.looseObject({input_tokens:N.number(),cache_creation_input_tokens:N.number().nullish(),cache_read_input_tokens:N.number().nullish()})})}),N.object({type:N.literal(`content_block_start`),index:N.number(),content_block:N.discriminatedUnion(`type`,[N.object({type:N.literal(`text`),text:N.string()}),N.object({type:N.literal(`thinking`),thinking:N.string()}),N.object({type:N.literal(`tool_use`),id:N.string(),name:N.string()}),N.object({type:N.literal(`redacted_thinking`),data:N.string()}),N.object({type:N.literal(`server_tool_use`),id:N.string(),name:N.string(),input:N.record(N.string(),N.unknown()).nullish()}),N.object({type:N.literal(`web_fetch_tool_result`),tool_use_id:N.string(),content:N.union([N.object({type:N.literal(`web_fetch_result`),url:N.string(),retrieved_at:N.string(),content:N.object({type:N.literal(`document`),title:N.string().nullable(),citations:N.object({enabled:N.boolean()}).optional(),source:N.object({type:N.literal(`text`),media_type:N.string(),data:N.string()})})}),N.object({type:N.literal(`web_fetch_tool_result_error`),error_code:N.string()})])}),N.object({type:N.literal(`web_search_tool_result`),tool_use_id:N.string(),content:N.union([N.array(N.object({type:N.literal(`web_search_result`),url:N.string(),title:N.string(),encrypted_content:N.string(),page_age:N.string().nullish()})),N.object({type:N.literal(`web_search_tool_result_error`),error_code:N.string()})])}),N.object({type:N.literal(`code_execution_tool_result`),tool_use_id:N.string(),content:N.union([N.object({type:N.literal(`code_execution_result`),stdout:N.string(),stderr:N.string(),return_code:N.number()}),N.object({type:N.literal(`code_execution_tool_result_error`),error_code:N.string()})])})])}),N.object({type:N.literal(`content_block_delta`),index:N.number(),delta:N.discriminatedUnion(`type`,[N.object({type:N.literal(`input_json_delta`),partial_json:N.string()}),N.object({type:N.literal(`text_delta`),text:N.string()}),N.object({type:N.literal(`thinking_delta`),thinking:N.string()}),N.object({type:N.literal(`signature_delta`),signature:N.string()}),N.object({type:N.literal(`citations_delta`),citation:tn})])}),N.object({type:N.literal(`content_block_stop`),index:N.number()}),N.object({type:N.literal(`error`),error:N.object({type:N.string(),message:N.string()})}),N.object({type:N.literal(`message_delta`),delta:N.object({stop_reason:N.string().nullish(),stop_sequence:N.string().nullish()}),usage:N.looseObject({output_tokens:N.number(),cache_creation_input_tokens:N.number().nullish()})}),N.object({type:N.literal(`message_stop`)}),N.object({type:N.literal(`ping`)})]),cn=N.object({signature:N.string().optional(),redactedData:N.string().optional()}),ln=vt({id:`anthropic.bash_20241022`,name:`bash`,inputSchema:M.object({command:M.string(),restart:M.boolean().optional()})}),un=vt({id:`anthropic.bash_20250124`,name:`bash`,inputSchema:M.object({command:M.string(),restart:M.boolean().optional()})}),dn=vt({id:`anthropic.computer_20241022`,name:`computer`,inputSchema:N.object({action:N.enum([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:N.array(N.number().int()).optional(),text:N.string().optional()})}),fn=vt({id:`anthropic.computer_20250124`,name:`computer`,inputSchema:N.object({action:N.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:N.tuple([N.number().int(),N.number().int()]).optional(),duration:N.number().optional(),scroll_amount:N.number().optional(),scroll_direction:N.enum([`up`,`down`,`left`,`right`]).optional(),start_coordinate:N.tuple([N.number().int(),N.number().int()]).optional(),text:N.string().optional()})}),pn=vt({id:`anthropic.text_editor_20241022`,name:`str_replace_editor`,inputSchema:N.object({command:N.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:N.string(),file_text:N.string().optional(),insert_line:N.number().int().optional(),new_str:N.string().optional(),old_str:N.string().optional(),view_range:N.array(N.number().int()).optional()})}),mn=vt({id:`anthropic.text_editor_20250124`,name:`str_replace_editor`,inputSchema:N.object({command:N.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:N.string(),file_text:N.string().optional(),insert_line:N.number().int().optional(),new_str:N.string().optional(),old_str:N.string().optional(),view_range:N.array(N.number().int()).optional()})}),hn=vt({id:`anthropic.text_editor_20250429`,name:`str_replace_based_edit_tool`,inputSchema:N.object({command:N.enum([`view`,`create`,`str_replace`,`insert`]),path:N.string(),file_text:N.string().optional(),insert_line:N.number().int().optional(),new_str:N.string().optional(),old_str:N.string().optional(),view_range:N.array(N.number().int()).optional()})}),gn={bash_20241022:ln,bash_20250124:un,codeExecution_20250522:Yt,computer_20241022:dn,computer_20250124:fn,textEditor_20241022:pn,textEditor_20250124:mn,textEditor_20250429:hn,textEditor_20250728:Lt,webFetch_20250910:Gt,webSearch_20250305:Vt};function _n(e={}){let t=Ot(e.baseURL)??`https://api.anthropic.com/v1`,n=()=>Ge({"anthropic-version":`2023-06-01`,"x-api-key":Ze({apiKey:e.apiKey,environmentVariableName:`ANTHROPIC_API_KEY`,description:`Anthropic`}),...e.headers},`ai-sdk/anthropic/${kt}`),r=r=>new an(r,{provider:`anthropic.messages`,baseURL:t,headers:n,fetch:e.fetch,generateId:e.generateId??Ke,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})}),i=function(e){if(new.target)throw Error(`The Anthropic model function cannot be called with the new keyword.`);return r(e)};return i.languageModel=r,i.chat=r,i.messages=r,i.textEmbeddingModel=e=>{throw new v({modelId:e,modelType:`textEmbeddingModel`})},i.imageModel=e=>{throw new v({modelId:e,modelType:`imageModel`})},i.tools=gn,i}_n();function vn(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function yn(e){return Object.fromEntries([...e.headers])}function bn(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 xn(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function Sn(e,...t){let n=xn(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var Cn=(({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new p({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();function wn(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Tn=[`fetch failed`,`failed to fetch`];function En({error:e,url:t,requestBodyValues:n}){if(wn(e))return e;if(e instanceof TypeError&&Tn.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new s({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}var Dn=`3.0.10`;function On({apiKey:e,environmentVariableName:t,apiKeyParameterName:n=`apiKey`,description:r}){if(typeof e==`string`)return e;if(e!=null)throw new _({message:`${r} API key must be a string.`});if(typeof process>`u`)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!=`string`)throw new _({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var kn=/"__proto__"\s*:/,An=/"constructor"\s*:/;function jn(e){let t=JSON.parse(e);return typeof t!=`object`||!t||kn.test(e)===!1&&An.test(e)===!1?t:Mn(t)}function Mn(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 Nn(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return jn(e)}finally{Error.stackTraceLimit=t}}var Pn=Symbol.for(`vercel.ai.validator`);function Fn(e){return{[Pn]:!0,validate:e}}function In(e){return typeof e==`object`&&!!e&&Pn in e&&e[Pn]===!0&&`validate`in e}function Ln(e){return In(e)?e:Rn(e)}function Rn(e){return Fn(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new x({value:t,cause:n.issues})}})}async function zn({value:e,schema:t}){let n=await Bn({value:e,schema:t});if(!n.success)throw x.wrap({value:e,cause:n.error});return n.value}async function Bn({value:e,schema:t}){let n=Ln(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:x.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:x.wrap({value:e,cause:t}),rawValue:e}}}async function Vn({text:e,schema:t}){try{let n=Nn(e);return t==null?n:zn({value:n,schema:t})}catch(t){throw g.isInstance(t)||x.isInstance(t)?t:new g({text:e,cause:t})}}async function Hn({text:e,schema:t}){try{let n=Nn(e);return t==null?{success:!0,value:n,rawValue:n}:await Bn({value:n,schema:t})}catch(t){return{success:!1,error:g.isInstance(t)?t:new g({text:e,cause:t}),rawValue:void 0}}}function Un({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new d).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await Hn({text:e,schema:t}))}}))}async function Wn({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;let r=await Bn({value:t[e],schema:n});if(!r.success)throw new p({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:r.error});return r.value}var Gn=()=>globalThis.fetch,Kn=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>qn({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),qn=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=Gn()})=>{try{let c=await o(e,{method:`POST`,headers:Sn(t,`ai-sdk/provider-utils/${Dn}`,bn()),body:n.content,signal:a}),l=yn(c);if(!c.ok){let t;try{t=await i({response:c,url:e,requestBodyValues:n.values})}catch(t){throw wn(t)||s.isInstance(t)?t:new s({message:`Failed to process error response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw t.value}try{return await r({response:c,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(wn(t)||s.isInstance(t))?t:new s({message:`Failed to process successful response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(t){throw En({error:t,url:e,requestBodyValues:n.values})}};function Jn(e){return e}function Yn({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>Jn({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function Xn({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>Jn({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 Zn(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var Qn=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),c=yn(r);if(o.trim()===``)return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})};try{let l=await Vn({text:o,schema:e});return{responseHeaders:c,value:new s({message:t(l),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})}}},$n=e=>async({response:t})=>{let n=yn(t);if(t.body==null)throw new u({});return{responseHeaders:n,value:Un({stream:t.body,schema:e})}},er=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await Hn({text:i,schema:e}),o=yn(t);if(!a.success)throw new s({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},{btoa:tr,atob:nr}=globalThis;function rr(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return tr(t)}function ir(e){return e instanceof Uint8Array?rr(e):e}function ar(e){return e?.replace(/\/$/,``)}var or=`2.0.17`,sr=N.object({error:N.object({code:N.number().nullable(),message:N.string(),status:N.string()})}),cr=Qn({errorSchema:sr,errorToMessage:e=>e.error.message}),lr=N.object({outputDimensionality:N.number().optional(),taskType:N.enum([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional()}),ur=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){let i=await Wn({provider:`google`,providerOptions:r,schema:lr});if(e.length>this.maxEmbeddingsPerCall)throw new b({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let a=vn(await Zn(this.config.headers),t);if(e.length===1){let{responseHeaders:t,value:r,rawValue:o}=await Kn({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:a,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType},failedResponseHandler:cr,successfulResponseHandler:er(fr),abortSignal:n,fetch:this.config.fetch});return{embeddings:[r.embedding.values],usage:void 0,response:{headers:t,body:o}}}let{responseHeaders:o,value:s,rawValue:c}=await Kn({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:a,body:{requests:e.map(e=>({model:`models/${this.modelId}`,content:{role:`user`,parts:[{text:e}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType}))},failedResponseHandler:cr,successfulResponseHandler:er(dr),abortSignal:n,fetch:this.config.fetch});return{embeddings:s.embeddings.map(e=>e.values),usage:void 0,response:{headers:o,body:c}}}},dr=N.object({embeddings:N.array(N.object({values:N.array(N.number())}))}),fr=N.object({embedding:N.object({values:N.array(N.number())})});function pr(e){if(e==null||mr(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]=pr(n),e),{})),a&&(p.items=Array.isArray(a)?a.map(pr):pr(a)),o&&(p.allOf=o.map(pr)),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=pr(e[0]);typeof t==`object`&&(p.nullable=!0,Object.assign(p,t))}else p.anyOf=e.map(pr),p.nullable=!0}else p.anyOf=s.map(pr);return c&&(p.oneOf=c.map(pr)),d!==void 0&&(p.minLength=d),p}function mr(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}function hr(e,t){let n=[],r=[],i=!0,a=t?.isGemmaModel??!1;for(let{role:t,content:a}of e)switch(t){case`system`:if(!i)throw new S({functionality:`system messages are only supported at the beginning of the conversation`});n.push({text:a});break;case`user`:{i=!1;let e=[];for(let t of a)switch(t.type){case`text`:e.push({text:t.text});break;case`file`:{let n=t.mediaType===`image/*`?`image/jpeg`:t.mediaType;e.push(t.data instanceof URL?{fileData:{mimeType:n,fileUri:t.data.toString()}}:{inlineData:{mimeType:n,data:ir(t.data)}});break}}r.push({role:`user`,parts:e});break}case`assistant`:i=!1,r.push({role:`model`,parts:a.map(e=>{switch(e.type){case`text`:return e.text.length===0?void 0:{text:e.text,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`reasoning`:return e.text.length===0?void 0:{text:e.text,thought:!0,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`file`:if(e.mediaType!==`image/png`)throw new S({functionality:`Only PNG images are supported in assistant messages`});if(e.data instanceof URL)throw new S({functionality:`File data URLs in assistant messages are not supported`});return{inlineData:{mimeType:e.mediaType,data:ir(e.data)}};case`tool-call`:return{functionCall:{name:e.toolName,args:e.input},thoughtSignature:e.providerOptions?.google?.thoughtSignature}}}).filter(e=>e!==void 0)});break;case`tool`:{i=!1;let e=[];for(let t of a){let n=t.output;if(n.type===`content`)for(let r of n.value)switch(r.type){case`text`:e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:r.text}}});break;case`media`:e.push({inlineData:{mimeType:r.mediaType,data:r.data}},{text:`Tool executed successfully and returned this image as a response`});break;default:e.push({text:JSON.stringify(r)});break}else e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:n.value}}})}r.push({role:`user`,parts:e});break}}if(a&&n.length>0&&r.length>0&&r[0].role===`user`){let e=n.map(e=>e.text).join(`
2
2
 
3
3
  `);r[0].parts.unshift({text:e+`
4
4
 
@@ -129,7 +129,620 @@ Use this for:
129
129
  - Extracting relevant information from verbose output
130
130
  - Analyzing build or test results
131
131
 
132
- Example: After running tests with \`workspace_bash\`, use this to find all FAIL: lines rather than re-running the test command.`,inputSchema:q.object({pid:q.number(),pattern:q.string(),before_lines:q.number(),after_lines:q.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}}}))},ph=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()}};q.union([q.object({pid:q.number(),ansiOutput:q.string()}),q.object({pid:q.number(),title:q.string().optional(),command:q.string(),args:q.array(q.string()),cwd:q.string(),env:q.record(q.string(),q.string()),ansiOutput:q.string(),plainOutput:q.object({totalLines:q.number(),lines:q.array(q.string())}),durationMs:q.number(),exitCode:q.number().optional(),exitSignal:q.number().optional(),stillRunning:q.boolean()})]);const mh=(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},hh=(e,t,n)=>t.length===0?e:e.split(t).join(n),gh={scratch:{".env.local.hbs":`# Store local environment variables here.
132
+ Example: After running tests with \`workspace_bash\`, use this to find all FAIL: lines rather than re-running the test command.`,inputSchema:q.object({pid:q.number(),pattern:q.string(),before_lines:q.number(),after_lines:q.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}}}))},ph=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()}};q.union([q.object({pid:q.number(),ansiOutput:q.string()}),q.object({pid:q.number(),title:q.string().optional(),command:q.string(),args:q.array(q.string()),cwd:q.string(),env:q.record(q.string(),q.string()),ansiOutput:q.string(),plainOutput:q.object({totalLines:q.number(),lines:q.array(q.string())}),durationMs:q.number(),exitCode:q.number().optional(),exitSignal:q.number().optional(),stillRunning:q.boolean()})]);const mh=(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},hh=(e,t,n)=>t.length===0?e:e.split(t).join(n),gh={scout:{".env.local.hbs":`# Store local environment variables here.
133
+ # They will be used by blink dev for development.
134
+ {{#each envLocal}}
135
+ {{this.[0]}}={{this.[1]}}
136
+ {{/each}}
137
+ {{#unless (hasAnyEnvVar envLocal "OPENAI_API_KEY" "ANTHROPIC_API_KEY" "AI_GATEWAY_API_KEY")}}
138
+ # OPENAI_API_KEY=
139
+ # ANTHROPIC_API_KEY=
140
+ # AI_GATEWAY_API_KEY=
141
+ {{/unless}}
142
+
143
+ # Web search (optional - get an API key from https://exa.ai)
144
+ # EXA_API_KEY=
145
+
146
+ # Coder credentials (optional - for production compute)
147
+ # CODER_URL=
148
+ # CODER_SESSION_TOKEN=
149
+ # CODER_TEMPLATE=
150
+ # CODER_PRESET_NAME=
151
+ `,".env.production":`# Store production environment variables here.
152
+ # They will be upserted as secrets on blink deploy.
153
+ # OPENAI_API_KEY=
154
+ # ANTHROPIC_API_KEY=
155
+ # AI_GATEWAY_API_KEY=
156
+
157
+ # Slack App credentials
158
+ # SLACK_BOT_TOKEN=
159
+ # SLACK_SIGNING_SECRET=
160
+
161
+ # GitHub App credentials
162
+ # GITHUB_APP_ID=
163
+ # GITHUB_CLIENT_ID=
164
+ # GITHUB_CLIENT_SECRET=
165
+ # GITHUB_WEBHOOK_SECRET=
166
+ # GITHUB_PRIVATE_KEY=
167
+
168
+ # Web search
169
+ # EXA_API_KEY=
170
+
171
+ # Coder credentials (recommended for production)
172
+ # CODER_URL=
173
+ # CODER_SESSION_TOKEN=
174
+ # CODER_TEMPLATE=
175
+ # CODER_PRESET_NAME=
176
+ `,".gitignore":`# dependencies
177
+ node_modules
178
+
179
+ # config and build
180
+ .blink/*
181
+ !.blink/config.json
182
+
183
+ # dotenv environment variables file
184
+ .env
185
+ .env.*
186
+
187
+ # Finder (MacOS) folder config
188
+ .DS_Store
189
+ `,"AGENTS.md":`This project is a Blink agent.
190
+
191
+ 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.
192
+
193
+ <communication>
194
+ 1. Be concise, direct, and to the point.
195
+ 2. You are communicating via a terminal interface, so avoid verbosity, preambles, postambles, and unnecessary whitespace.
196
+ 3. NEVER use emojis unless the user explicitly asks for them.
197
+ 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...".
198
+ 5. Mimic the style of the user's messages.
199
+ 6. Do not remind the user you are happy to help.
200
+ 7. Do not act with sycophantic flattery or over-the-top enthusiasm.
201
+ 8. Do not regurgitate tool output. e.g. if a command succeeds, acknowledge briefly (e.g. "Done" or "Formatted").
202
+ 9. *NEVER* create markdown files for the user - *always* guide the user through your efforts.
203
+ 10. *NEVER* create example scripts for the user, or examples scripts for you to run. Leverage your tools to accomplish the user's goals.
204
+ </communication>
205
+
206
+ <goals>
207
+ Your method of assisting the user is by iterating their agent using the context provided by the user in run mode.
208
+
209
+ You can obtain additional context by leveraging web search and compute tools to read files, run commands, and search the web.
210
+
211
+ The user is _extremely happy_ to provide additional context. They prefer this over you guessing, and then potentially getting it wrong.
212
+
213
+ <example>
214
+ user: i want a coding agent
215
+ assistant: Let me take a look at your codebase...
216
+ ... tool calls to investigate the codebase...
217
+ 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.
218
+ </example>
219
+
220
+ Always investigate the current state of the agent before assisting the user.
221
+ </goals>
222
+
223
+ <agent_development>
224
+ Agents are written in TypeScript, and mostly stored in a single \`agent.ts\` file. Complex agents will have multiple files, like a proper codebase.
225
+
226
+ Environment variables are stored in \`.env.local\` and \`.env.production\`. \`blink dev\` will hot-reload environment variable changes in \`.env.local\`.
227
+
228
+ Changes to the agent are hot-reloaded. As you make edits, the user can immediately try them in run mode.
229
+
230
+ 1. _ALWAYS_ use the package manager the user is using (inferred from lock files or \`process.argv\`).
231
+ 2. You _MUST_ use \`agent.store\` to persist state. The agent process is designed to be stateless.
232
+ 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.
233
+ 4. Use console.log for debugging. The console output appears for the user.
234
+ 5. Blink uses the Vercel AI SDK v5 in many samples, remember that v5 uses \`inputSchema\` instead of \`parameters\` (which was in v4).
235
+ 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.
236
+ 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.
237
+
238
+ If the user is asking for a behavioral change, you should update the agent's system prompt.
239
+ This will not ensure the behavior, but it will guide the agent towards the desired behavior.
240
+ If the user needs 100% behavioral certainty, adjust tool behavior instead.
241
+ </agent_development>
242
+
243
+ <agent_web_requests>
244
+ 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.
245
+
246
+ Blink automatically creates a reverse-tunnel to your local machine for simple local development with external services (think Slack Bot, GitHub Bot, etc.).
247
+
248
+ To trigger chats based on web requests, use the \`agent.chat.upsert\` and \`agent.chat.message\` APIs.
249
+ </agent_web_requests>
250
+
251
+ <technical_knowledge>
252
+ Blink agents are Node.js HTTP servers built on the Vercel AI SDK:
253
+
254
+ \`\`\`typescript
255
+ import { convertToModelMessages, streamText } from "ai";
256
+ import * as blink from "blink";
257
+
258
+ const agent = new blink.Agent();
259
+
260
+ agent.on("chat", async ({ messages, chat, abortSignal }) => {
261
+ return streamText({
262
+ model: "anthropic/claude-sonnet-4.5",
263
+ system: "You are a helpful assistant.",
264
+ messages: convertToModelMessages(messages, {
265
+ ignoreIncompleteToolCalls: true,
266
+ }),
267
+ tools: {
268
+ /* your tools */
269
+ },
270
+ });
271
+ });
272
+
273
+ agent.on("request", async (request) => {
274
+ // Handle webhooks, OAuth callbacks, etc.
275
+ });
276
+
277
+ agent.serve();
278
+ \`\`\`
279
+
280
+ Event Handlers:
281
+
282
+ **\`agent.on("chat", handler)\`**
283
+
284
+ 1. Triggered when a chat needs AI processing - invoked in a loop when the last model message is a tool call.
285
+ 2. Must return: \`streamText()\` result, \`Response\`, \`ReadableStream<UIMessageChunk>\`, or \`void\`
286
+ 3. Parameters: \`messages\`, \`id\`, \`abortSignal\`
287
+
288
+ _NEVER_ use "maxSteps" from the Vercel AI SDK. It is unnecessary and will cause a worse experience for the user.
289
+
290
+ **\`agent.on("request", handler)\`**
291
+ • Handles raw HTTP requests before Blink processes them
292
+ • Use for: OAuth callbacks, webhook verification, custom endpoints
293
+ • Return \`Response\` to handle, or \`void\` to pass through
294
+
295
+ **\`agent.on("ui", handler)\`**
296
+ • Provides dynamic UI options for chat interfaces
297
+ • Returns schema defining user-selectable options
298
+
299
+ **\`agent.on("error", handler)\`**
300
+ • Global error handler for the agent
301
+
302
+ Chat Management:
303
+
304
+ Blink automatically manages chat state:
305
+
306
+ \`\`\`typescript
307
+ // Create or get existing chat
308
+ // The parameter can be any JSON-serializable value.
309
+ // e.g. for a Slack bot to preserve context in a thread, you might use: ["slack", teamId, channelId, threadTs]
310
+ const chat = await agent.chat.upsert("unique-key");
311
+
312
+ // Send a message to a chat
313
+ await agent.chat.sendMessages(
314
+ chat.id,
315
+ [
316
+ {
317
+ role: "user",
318
+ parts: [{ type: "text", text: "Message" }],
319
+ },
320
+ ],
321
+ {
322
+ behavior: "interrupt" | "enqueue" | "append",
323
+ }
324
+ );
325
+
326
+ // When sending messages, feel free to inject additional parts to direct the model.
327
+ // e.g. if the user is asking for specific behavior in specific scenarios, the simplest
328
+ // answer is to append a text part: "always do X when Y".
329
+ \`\`\`
330
+
331
+ Behaviors:
332
+ • "interrupt": Stop current processing and handle immediately
333
+ • "enqueue": Queue message, process when current chat finishes
334
+ • "append": Add to history without triggering processing
335
+
336
+ Chat keys: Use structured keys like \`"slack-\${teamId}-\${channelId}-\${threadTs}"\` for uniqueness.
337
+
338
+ Storage API:
339
+
340
+ Persistent key-value storage per agent:
341
+
342
+ \`\`\`typescript
343
+ // Store data
344
+ await agent.store.set("key", "value", { ttl: 3600 });
345
+
346
+ // Retrieve data
347
+ const value = await agent.store.get("key");
348
+
349
+ // Delete data
350
+ await agent.store.delete("key");
351
+
352
+ // List keys by prefix
353
+ const result = await agent.store.list("prefix-", { limit: 100 });
354
+ \`\`\`
355
+
356
+ Common uses: OAuth tokens, user preferences, caching, chat-resource associations.
357
+
358
+ Tools:
359
+
360
+ Tools follow Vercel AI SDK patterns with Zod validation:
361
+
362
+ \`\`\`typescript
363
+ import { tool } from "ai";
364
+ import { z } from "zod";
365
+
366
+ const myTool = tool({
367
+ description: "Clear description of what this tool does",
368
+ inputSchema: z.object({
369
+ param: z.string().describe("Parameter description"),
370
+ }),
371
+ execute: async (args, opts) => {
372
+ // opts.abortSignal for cancellation
373
+ // opts.toolCallId for unique identification
374
+ return result;
375
+ },
376
+ });
377
+ \`\`\`
378
+
379
+ Tool Approvals for destructive operations:
380
+
381
+ \`\`\`typescript
382
+ ...await blink.tools.withApproval({
383
+ messages,
384
+ tools: {
385
+ delete_database: tool({ /* ... */ }),
386
+ },
387
+ })
388
+ \`\`\`
389
+
390
+ Tool Context for dependency injection:
391
+
392
+ \`\`\`typescript
393
+ ...blink.tools.withContext(github.tools, {
394
+ accessToken: process.env.GITHUB_TOKEN,
395
+ })
396
+ \`\`\`
397
+
398
+ Tool Prefixing to avoid collisions:
399
+
400
+ \`\`\`typescript
401
+ ...blink.tools.prefix(github.tools, "github_")
402
+ \`\`\`
403
+
404
+ LLM Models:
405
+
406
+ \`\`\`typescript
407
+ import { anthropic } from "@ai-sdk/anthropic";
408
+ import { openai } from "@ai-sdk/openai";
409
+
410
+ model: anthropic("claude-sonnet-4.5", {
411
+ apiKey: process.env.ANTHROPIC_API_KEY,
412
+ });
413
+ // Use chat API for OpenAI models - it's more reliable than the responses API
414
+ model: openai.chat("gpt-5", { apiKey: process.env.OPENAI_API_KEY });
415
+ \`\`\`
416
+
417
+ **Note about Edit Mode:** Edit mode (this agent) automatically selects models in this priority:
418
+
419
+ 1. If \`ANTHROPIC_API_KEY\` is set: uses \`claude-sonnet-4.5\` via \`@ai-sdk/anthropic\`
420
+ 2. If \`OPENAI_API_KEY\` is set: uses \`gpt-5\` via \`@ai-sdk/openai\`
421
+
422
+ Available SDKs:
423
+
424
+ **@blink-sdk/compute**
425
+
426
+ \`\`\`typescript
427
+ import * as compute from "@blink-sdk/compute";
428
+
429
+ tools: {
430
+ ...compute.tools, // execute_bash, read_file, write_file, edit_file, process management
431
+ }
432
+ \`\`\`
433
+
434
+ **@blink-sdk/github**
435
+
436
+ \`\`\`typescript
437
+ import * as github from "@blink-sdk/github";
438
+
439
+ tools: {
440
+ ...blink.tools.withContext(github.tools, {
441
+ accessToken: process.env.GITHUB_TOKEN,
442
+ }),
443
+ }
444
+ \`\`\`
445
+
446
+ **@blink-sdk/slack**
447
+
448
+ \`\`\`typescript
449
+ import * as slack from "@blink-sdk/slack";
450
+ import { App } from "@slack/bolt";
451
+
452
+ const receiver = new slack.Receiver();
453
+ const app = new App({
454
+ token: process.env.SLACK_BOT_TOKEN,
455
+ signingSecret: process.env.SLACK_SIGNING_SECRET,
456
+ receiver,
457
+ });
458
+
459
+ // This will trigger when the bot is @mentioned.
460
+ app.event("app_mention", async ({ event }) => {
461
+ // The argument here is a JSON-serializable value.
462
+ // To maintain the same chat context, use the same key.
463
+ const chat = await agent.chat.upsert([
464
+ "slack",
465
+ event.channel,
466
+ event.thread_ts ?? event.ts,
467
+ ]);
468
+ const { message } = await slack.createMessageFromEvent({
469
+ client: app.client,
470
+ event,
471
+ });
472
+ await agent.chat.sendMessages(chat.id, [message]);
473
+ // This is a nice immediate indicator for the user.
474
+ await app.client.assistant.threads.setStatus({
475
+ channel_id: event.channel,
476
+ status: "is typing...",
477
+ thread_ts: event.thread_ts ?? event.ts,
478
+ });
479
+ });
480
+
481
+ const agent = new blink.Agent();
482
+
483
+ agent.on("request", async (request) => {
484
+ return receiver.handle(app, request);
485
+ });
486
+
487
+ agent.on("chat", async ({ messages }) => {
488
+ const tools = slack.createTools({ client: app.client });
489
+ return streamText({
490
+ model: "anthropic/claude-sonnet-4.5",
491
+ system: "You chatting with users in Slack.",
492
+ messages: convertToModelMessages(messages, {
493
+ ignoreIncompleteToolCalls: true,
494
+ tools,
495
+ }),
496
+ });
497
+ });
498
+ \`\`\`
499
+
500
+ Slack SDK Notes:
501
+
502
+ - "app_mention" event is triggered in both private channels and public channels.
503
+ - "message" event is triggered regardless of being mentioned or not, and will _also_ be fired when "app_mention" is triggered.
504
+ - _NEVER_ register app event listeners in the "on" handler of the agent. This will cause the handler to be called multiple times.
505
+ - 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.
506
+ - 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}" })\`
507
+ - 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".
508
+
509
+ Slack App Manifest:
510
+
511
+ - _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.
512
+ - The user can always edit the manifest after creation, but you'd have to suggest it to them.
513
+ - "oauth_config" MUST BE PROVIDED - otherwise the app will have NO ACCESS.
514
+ - _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.
515
+ - For the best user experience, default to the following bot scopes (in the "oauth_config" > "scopes" > "bot"):
516
+ - "app_mentions:read"
517
+ - "reactions:write"
518
+ - "reactions:read"
519
+ - "channels:history"
520
+ - "chat:write"
521
+ - "groups:history"
522
+ - "groups:read"
523
+ - "files:read"
524
+ - "im:history"
525
+ - "im:read"
526
+ - "im:write"
527
+ - "mpim:history"
528
+ - "mpim:read"
529
+ - "users:read"
530
+ - "links:read"
531
+ - "commands"
532
+ - For the best user experience, default to the following bot events (in the "settings" > "event_subscriptions" > "bot_events"):
533
+ - "app_mention"
534
+ - "message.channels",
535
+ - "message.groups",
536
+ - "message.im",
537
+ - "reaction_added"
538
+ - "reaction_removed"
539
+ - "assistant_thread_started"
540
+ - "member_joined_channel"
541
+ - _NEVER_ include USER SCOPES unless the user explicitly asks for them.
542
+
543
+ WARNING: Beware of attaching multiple event listeners to the same chat. This could cause the agent to respond multiple times.
544
+
545
+ State Management:
546
+
547
+ Blink agents are short-lived HTTP servers that restart on code changes and do not persist in-memory state between requests.
548
+
549
+ _NEVER_ use module-level Maps, Sets, or variables to store state (e.g. \`const activeBots = new Map()\`).
550
+
551
+ For global state persistence, you can use the agent store:
552
+
553
+ - Use \`agent.store\` for persistent key-value storage
554
+ - Query external APIs to fetch current state
555
+ - Use webhooks to trigger actions rather than polling in-memory state
556
+
557
+ For message-level state persistence, use message metadata:
558
+
559
+ \`\`\`typescript
560
+ import { UIMessage } from "blink";
561
+ import * as blink from "blink";
562
+
563
+ const agent = new blink.Agent<
564
+ UIMessage<{
565
+ source: "github";
566
+ associated_id: string;
567
+ }>
568
+ >();
569
+
570
+ agent.on("request", async (request) => {
571
+ // comes from github, we want to do something deterministic in the chat loop with that ID...
572
+ // insert a message with that metadata into the chat
573
+ const chat = await agent.chat.upsert("some-github-key");
574
+ await agent.chat.sendMessages(request.chat.id, [
575
+ {
576
+ role: "user",
577
+ parts: [
578
+ {
579
+ type: "text",
580
+ text: "example",
581
+ },
582
+ ],
583
+ metadata: {
584
+ source: "github",
585
+ associated_id: "some-github-id",
586
+ },
587
+ },
588
+ ]);
589
+ });
590
+
591
+ agent.on("chat", async ({ messages }) => {
592
+ const message = messages.find(
593
+ (message) => message.metadata?.source === "github"
594
+ );
595
+
596
+ // Now we can use that metadata...
597
+ });
598
+ \`\`\`
599
+
600
+ The agent process can restart at any time, so all important state must be externalized.
601
+ </technical_knowledge>
602
+
603
+ <code_quality>
604
+
605
+ - Never use "as any" type assertions. Always figure out the correct typings.
606
+ </code_quality>
607
+ `,"agent.ts.hbs":`{{#if (eq aiProvider "anthropic")}}
608
+ import { anthropic } from "@ai-sdk/anthropic";
609
+ {{else if (eq aiProvider "openai")}}
610
+ import { openai } from "@ai-sdk/openai";
611
+ {{/if}}
612
+ import { type Message, Scout } from "@blink-sdk/scout-agent";
613
+ import { streamText, tool } from "ai";
614
+ import * as blink from "blink";
615
+ import { z } from "zod";
616
+
617
+ export const agent = new blink.Agent<Message>();
618
+
619
+ const scout = new Scout({
620
+ agent,
621
+ // GitHub integration (optional).
622
+ // Run \`blink setup github-app\` to set up your GitHub App, or remove this section if not needed.
623
+ github: {
624
+ appID: process.env.GITHUB_APP_ID,
625
+ privateKey: process.env.GITHUB_PRIVATE_KEY,
626
+ webhookSecret: process.env.GITHUB_WEBHOOK_SECRET,
627
+ },
628
+ // Slack integration (optional).
629
+ // Run \`blink setup slack-app\` to set up your Slack App, or remove this section if not needed.
630
+ slack: {
631
+ botToken: process.env.SLACK_BOT_TOKEN,
632
+ signingSecret: process.env.SLACK_SIGNING_SECRET,
633
+ },
634
+ // Web search integration (optional). Visit https://exa.ai to get an API key.
635
+ webSearch: {
636
+ exaApiKey: process.env.EXA_API_KEY,
637
+ },
638
+ // Compute environment for running code.
639
+ // Using Docker by default for local development.
640
+ // For production, you can use Coder (https://coder.com) instead:
641
+ // compute: {
642
+ // type: "coder",
643
+ // options: {
644
+ // url: process.env.CODER_URL,
645
+ // sessionToken: process.env.CODER_SESSION_TOKEN,
646
+ // template: process.env.CODER_TEMPLATE,
647
+ // presetName: process.env.CODER_PRESET_NAME,
648
+ // },
649
+ // },
650
+ compute: {
651
+ type: "docker",
652
+ },
653
+ });
654
+
655
+ agent.on("request", async (request) => {
656
+ const url = new URL(request.url);
657
+ if (url.pathname.startsWith("/slack")) {
658
+ return scout.handleSlackWebhook(request);
659
+ }
660
+ if (url.pathname.startsWith("/github")) {
661
+ return scout.handleGitHubWebhook(request);
662
+ }
663
+ return new Response("Hey there!", { status: 200 });
664
+ });
665
+
666
+ agent.on("chat", async ({ id, messages }) => {
667
+ const params = await scout.buildStreamTextParams({
668
+ messages,
669
+ chatID: id,
670
+ {{#if (eq aiProvider "anthropic")}}
671
+ model: anthropic("claude-opus-4-5"),
672
+ {{else if (eq aiProvider "openai")}}
673
+ model: openai.chat("gpt-5"),
674
+ {{else if (eq aiProvider "vercel")}}
675
+ model: "anthropic/claude-opus-4.5",
676
+ {{else}}
677
+ // Unknown provider: {{aiProvider}}. Defaulting to Vercel AI Gateway syntax.
678
+ model: "anthropic/claude-opus-4.5",
679
+ {{/if}}
680
+ providerOptions: { anthropic: { cacheControl: { type: "ephemeral" } } },
681
+ tools: {
682
+ // Add your custom tools here
683
+ get_favorite_color: tool({
684
+ description: "Get your favorite color",
685
+ inputSchema: z.object({}),
686
+ execute() {
687
+ return "blue";
688
+ },
689
+ }),
690
+ },
691
+ });
692
+ return streamText(params);
693
+ });
694
+
695
+ agent.serve();
696
+ `,"package.json.hbs":`{
697
+ "name": "{{packageName}}",
698
+ "main": "agent.ts",
699
+ "type": "module",
700
+ "private": true,
701
+ "scripts": {
702
+ "dev": "blink dev",
703
+ "deploy": "blink deploy"
704
+ },
705
+ "devDependencies": {
706
+ "zod": "latest",
707
+ "ai": "latest",
708
+ {{#if (eq aiProvider "anthropic")}}
709
+ "@ai-sdk/anthropic": "latest",
710
+ {{else if (eq aiProvider "openai")}}
711
+ "@ai-sdk/openai": "latest",
712
+ {{/if}}
713
+ "blink": "latest",
714
+ "esbuild": "latest",
715
+ "@types/node": "latest",
716
+ "typescript": "latest",
717
+ "@blink-sdk/scout-agent": "latest"
718
+ }
719
+ }
720
+ `,"tsconfig.json":`{
721
+ "compilerOptions": {
722
+ "lib": ["ESNext"],
723
+ "target": "ESNext",
724
+ "module": "Preserve",
725
+ "moduleDetection": "force",
726
+
727
+ "moduleResolution": "bundler",
728
+ "allowImportingTsExtensions": true,
729
+ "verbatimModuleSyntax": true,
730
+ "resolveJsonModule": true,
731
+ "noEmit": true,
732
+
733
+ "strict": true,
734
+ "skipLibCheck": true,
735
+ "noFallthroughCasesInSwitch": true,
736
+ "noUncheckedIndexedAccess": true,
737
+ "noImplicitOverride": true,
738
+
739
+ "noUnusedLocals": false,
740
+ "noUnusedParameters": false,
741
+
742
+ "types": ["node"]
743
+ }
744
+ }
745
+ `},scratch:{".env.local.hbs":`# Store local environment variables here.
133
746
  # They will be used by blink dev for development.
134
747
  {{#each envLocal}}
135
748
  {{this.[0]}}={{this.[1]}}