blink 1.1.19 → 1.1.20

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 (30) hide show
  1. package/dist/cli/create-slack-app-CyVPwWsG.js +1 -0
  2. package/dist/cli/{dev-BShY-dVP.js → dev-C5PZ-A_f.js} +5 -5
  3. package/dist/cli/index.js +3 -3
  4. package/dist/cli/{init-DoMgv4kU.js → init-CFrylDAP.js} +1 -1
  5. package/dist/cli/{init-templates-MqyReSD9.js → init-templates-CB4tNZfU.js} +249 -263
  6. package/dist/cli/{run-DFYLWiOa.js → run-bKDX6K46.js} +1 -1
  7. package/dist/cli/{setup-slack-app-DQ3iSM5s.js → setup-slack-app-D_iwQuzr.js} +1 -1
  8. package/dist/cli/{util-BQ3TH_Sv.js → util-DDB5k1Go.js} +4 -4
  9. package/dist/node/agent/index.node.cjs +1 -1
  10. package/dist/node/agent/index.node.d.cts +2 -2
  11. package/dist/node/agent/index.node.d.ts +2 -2
  12. package/dist/node/agent/index.node.js +1 -1
  13. package/dist/node/build/index.cjs +1 -1
  14. package/dist/node/build/index.d.cts +1 -1
  15. package/dist/node/build/index.d.ts +1 -1
  16. package/dist/node/build/index.js +1 -1
  17. package/dist/node/{build-D_L0gFGa.js → build-DYI55eX2.js} +1 -1
  18. package/dist/node/{build-BzoNpizh.cjs → build-EgdtUZTI.cjs} +1 -1
  19. package/dist/node/{index-C28Wm0bG.d.ts → index-CnBfy-54.d.ts} +1 -1
  20. package/dist/node/{index-DlWgNLmT.d.cts → index-DYOqnOdZ.d.cts} +1 -1
  21. package/dist/node/{index.node-TFdiI8lm.js → index.node-B6JXREDl.js} +1 -1
  22. package/dist/node/{index.node-D7Cvmag9.cjs → index.node-BrLfthBj.cjs} +1 -1
  23. package/dist/node/{index.node-B6plkLLA.d.cts → index.node-CFw4ITad.d.cts} +1 -21
  24. package/dist/node/{index.node-qJt_7e9E.d.ts → index.node-Dvc-cHCZ.d.ts} +1 -21
  25. package/dist/node/react/index.node.cjs +252 -266
  26. package/dist/node/react/index.node.d.cts +2 -2
  27. package/dist/node/react/index.node.d.ts +2 -2
  28. package/dist/node/react/index.node.js +252 -266
  29. package/package.json +2 -1
  30. package/dist/cli/create-slack-app-CNDXDwfs.js +0 -1
@@ -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,EventSourceParserStream as u,Hono as d,InvalidPromptError as f,InvalidResponseDataError as p,NoSuchModelError as m,StreamResponseFormatHeader as h,TooManyEmbeddingValuesForCallError as g,UnsupportedFunctionalityError as _,combineHeaders as v,convertBase64ToUint8Array as y,convertToBase64 as b,createBinaryResponseHandler as x,createEventSourceResponseHandler as S,createGatewayProvider as C,createJsonErrorResponseHandler as w,createJsonResponseHandler as T,createProviderDefinedToolFactory as E,createProviderDefinedToolFactoryWithOutputSchema as D,createServerAdapter as O,generateId as k,hc as A,isParsableJson as j,isToolApprovalOutput as ee,lastUIOptions as M,loadApiKey as te,loadOptionalSetting as ne,mediaTypeToExtension as re,parseProviderOptions as N,postFormDataToApi as P,postJsonToApi as F,require_has_flag as I,resolve as L,tools as R,validator as ie,withUserAgentSuffix as z,withoutTrailingSlash as ae}from"../index.node-TFdiI8lm.js";import"../token-error-488npYdU.js";import"../esm-CbZfjZBn.js";import{resolveConfig as oe}from"../build-D_L0gFGa.js";import{createRequire as se}from"node:module";import ce,{z as B}from"zod/v4";import"zod/v3";import{Buffer as V}from"node:buffer";import*as H from"node:fs";import le,{existsSync as ue,mkdirSync as de,readFileSync as fe,unlinkSync as pe,writeFileSync as me}from"node:fs";import{fileURLToPath as he}from"node:url";import{Writable as ge}from"node:stream";import{promisify as _e,stripVTControlCharacters as ve}from"node:util";import{createHash as ye}from"node:crypto";import U,{createServer as be}from"http";import{dirname as xe,join as Se}from"path";import{existsSync as Ce,mkdirSync as we,readFileSync as Te,watch as Ee,writeFileSync as De}from"fs";import{convertToModelMessages as Oe,isToolOrDynamicToolUIPart as ke,readUIMessageStream as Ae,streamText as je,tool as W}from"ai";import{readFile as Me,stat as Ne,writeFile as Pe}from"fs/promises";import{spawn as Fe}from"child_process";import{useCallback as G,useEffect as K,useMemo as Ie,useRef as Le,useState as q}from"react";import J,{z as Y}from"zod";import*as Re from"node:path";import ze,{dirname as Be,join as Ve}from"node:path";import X,{stdin as He,stdout as Ue}from"node:process";import*as We from"node:readline";import Ge from"node:readline";import Ke,{execFile as qe}from"node:child_process";import Je,{constants as Ye}from"node:fs/promises";import Xe from"node:os";import"@blink-sdk/compute-protocol/client";import{createInMemoryClientServer as Ze}from"@blink-sdk/compute-protocol/transport";var Qe=`2.0.23`,$e=B.object({type:B.literal(`error`),error:B.object({type:B.string(),message:B.string()})}),et=w({errorSchema:$e,errorToMessage:e=>e.error.message}),tt=B.object({citations:B.object({enabled:B.boolean()}).optional(),title:B.string().optional(),context:B.string().optional()}),nt=B.object({sendReasoning:B.boolean().optional(),thinking:B.object({type:B.union([B.literal(`enabled`),B.literal(`disabled`)]),budgetTokens:B.number().optional()}).optional(),disableParallelToolUse:B.boolean().optional(),cacheControl:B.object({type:B.literal(`ephemeral`),ttl:B.union([B.literal(`5m`),B.literal(`1h`)]).optional()}).optional()});function rt(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var it=B.object({maxCharacters:B.number().optional()}),at=E({id:`anthropic.text_editor_20250728`,name:`str_replace_based_edit_tool`,inputSchema:B.object({command:B.enum([`view`,`create`,`str_replace`,`insert`]),path:B.string(),file_text:B.string().optional(),insert_line:B.number().int().optional(),new_str:B.string().optional(),old_str:B.string().optional(),view_range:B.array(B.number().int()).optional()})}),ot=(e={})=>at(e),st=B.object({maxUses:B.number().optional(),allowedDomains:B.array(B.string()).optional(),blockedDomains:B.array(B.string()).optional(),userLocation:B.object({type:B.literal(`approximate`),city:B.string().optional(),region:B.string().optional(),country:B.string().optional(),timezone:B.string().optional()}).optional()}),ct=B.array(B.object({url:B.string(),title:B.string(),pageAge:B.string().nullable(),encryptedContent:B.string(),type:B.literal(`web_search_result`)})),lt=D({id:`anthropic.web_search_20250305`,name:`web_search`,inputSchema:B.object({query:B.string()}),outputSchema:ct}),ut=(e={})=>lt(e),dt=B.object({maxUses:B.number().optional(),allowedDomains:B.array(B.string()).optional(),blockedDomains:B.array(B.string()).optional(),citations:B.object({enabled:B.boolean()}).optional(),maxContentTokens:B.number().optional()}),ft=B.object({type:B.literal(`web_fetch_result`),url:B.string(),content:B.object({type:B.literal(`document`),title:B.string(),citations:B.object({enabled:B.boolean()}).optional(),source:B.union([B.object({type:B.literal(`base64`),mediaType:B.literal(`application/pdf`),data:B.string()}),B.object({type:B.literal(`text`),mediaType:B.literal(`text/plain`),data:B.string()})])}),retrievedAt:B.string().nullable()}),pt=D({id:`anthropic.web_fetch_20250910`,name:`web_fetch`,inputSchema:B.object({url:B.string()}),outputSchema:ft}),mt=(e={})=>pt(e);function ht({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=rt(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=it.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=dt.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=st.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 _({functionality:`tool choice type: ${o}`})}}var gt=B.object({type:B.literal(`code_execution_result`),stdout:B.string(),stderr:B.string(),return_code:B.number()}),_t=D({id:`anthropic.code_execution_20250522`,name:`code_execution`,inputSchema:B.object({code:B.string()}),outputSchema:gt}),vt=(e={})=>_t(e);function yt(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 _({functionality:`URL-based text documents are not supported for citations`}):new _({functionality:`unsupported data type for text documents: ${typeof e}`})}async function bt({prompt:e,sendReasoning:t,warnings:n}){let r=new Set,i=xt(e),a,o=[];async function s(e){return(await N({provider:`anthropic`,providerOptions:e,schema:tt}))?.citations?.enabled??!1}async function c(e){let t=await N({provider:`anthropic`,providerOptions:e,schema:tt});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 _({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:rt(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=rt(a.providerOptions)??(o?rt(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:b(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:b(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:yt(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else throw new _({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=rt(r.providerOptions)??(a?rt(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 _({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=rt(s.providerOptions)??(c?rt(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 N({provider:`anthropic`,providerOptions:s.providerOptions,schema:At});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=gt.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=ft.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=ct.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 xt(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 St({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 Ct={webSearchResult:B.object({type:B.literal(`web_search_result_location`),cited_text:B.string(),url:B.string(),title:B.string(),encrypted_index:B.string()}),pageLocation:B.object({type:B.literal(`page_location`),cited_text:B.string(),document_index:B.number(),document_title:B.string().nullable(),start_page_number:B.number(),end_page_number:B.number()}),charLocation:B.object({type:B.literal(`char_location`),cited_text:B.string(),document_index:B.number(),document_title:B.string().nullable(),start_char_index:B.number(),end_char_index:B.number()})},wt=B.discriminatedUnion(`type`,[Ct.webSearchResult,Ct.pageLocation,Ct.charLocation]);B.discriminatedUnion(`type`,[Ct.pageLocation,Ct.charLocation]);function Tt(e,t,n,r){if(e.type===`page_location`||e.type===`char_location`){let i=Et(e,t,n);i&&r(i)}}function Et(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 Dt=class{constructor(e,t){this.specificationVersion=`v2`,this.modelId=e,this.config=t,this.generateId=t.generateId??k}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 N({provider:`anthropic`,providerOptions:f,schema:nt}),{prompt:g,betas:v}=await bt({prompt:e,sendReasoning:h?.sendReasoning??!0,warnings:p}),y=h?.thinking?.type===`enabled`,b=h?.thinking?.budgetTokens,x={model:this.modelId,max_tokens:t,temperature:n,top_k:i,top_p:r,stop_sequences:s,...y&&{thinking:{type:`enabled`,budget_tokens:b}},system:g.system,messages:g.messages};if(y){if(b==null)throw new _({functionality:`thinking requires a budget`});x.temperature!=null&&(x.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported when thinking is enabled`})),i!=null&&(x.top_k=void 0,p.push({type:`unsupported-setting`,setting:`topK`,details:`topK is not supported when thinking is enabled`})),r!=null&&(x.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported when thinking is enabled`})),x.max_tokens=t+b}let{tools:S,toolChoice:C,toolWarnings:w,betas:T}=ht(m==null?{tools:u??[],toolChoice:d,disableParallelToolUse:h?.disableParallelToolUse}:{tools:[m],toolChoice:{type:`tool`,toolName:m.name},disableParallelToolUse:!0});return{args:{...x,tools:S,tool_choice:C},warnings:[...p,...w],betas:new Set([...v,...T]),usesJsonResponseTool:m!=null}}async getHeaders({betas:e,headers:t}){return v(await L(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 F({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(t),failedResponseHandler:et,successfulResponseHandler:T(Ot),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)Tt(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:St({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 F({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(o),failedResponseHandler:et,successfulResponseHandler:S(kt),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;Tt(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=St({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}}}},Ot=B.object({type:B.literal(`message`),id:B.string().nullish(),model:B.string().nullish(),content:B.array(B.discriminatedUnion(`type`,[B.object({type:B.literal(`text`),text:B.string(),citations:B.array(wt).optional()}),B.object({type:B.literal(`thinking`),thinking:B.string(),signature:B.string()}),B.object({type:B.literal(`redacted_thinking`),data:B.string()}),B.object({type:B.literal(`tool_use`),id:B.string(),name:B.string(),input:B.unknown()}),B.object({type:B.literal(`server_tool_use`),id:B.string(),name:B.string(),input:B.record(B.string(),B.unknown()).nullish()}),B.object({type:B.literal(`web_fetch_tool_result`),tool_use_id:B.string(),content:B.union([B.object({type:B.literal(`web_fetch_result`),url:B.string(),retrieved_at:B.string(),content:B.object({type:B.literal(`document`),title:B.string().nullable(),citations:B.object({enabled:B.boolean()}).optional(),source:B.object({type:B.literal(`text`),media_type:B.string(),data:B.string()})})}),B.object({type:B.literal(`web_fetch_tool_result_error`),error_code:B.string()})])}),B.object({type:B.literal(`web_search_tool_result`),tool_use_id:B.string(),content:B.union([B.array(B.object({type:B.literal(`web_search_result`),url:B.string(),title:B.string(),encrypted_content:B.string(),page_age:B.string().nullish()})),B.object({type:B.literal(`web_search_tool_result_error`),error_code:B.string()})])}),B.object({type:B.literal(`code_execution_tool_result`),tool_use_id:B.string(),content:B.union([B.object({type:B.literal(`code_execution_result`),stdout:B.string(),stderr:B.string(),return_code:B.number()}),B.object({type:B.literal(`code_execution_tool_result_error`),error_code:B.string()})])})])),stop_reason:B.string().nullish(),stop_sequence:B.string().nullish(),usage:B.looseObject({input_tokens:B.number(),output_tokens:B.number(),cache_creation_input_tokens:B.number().nullish(),cache_read_input_tokens:B.number().nullish()})}),kt=B.discriminatedUnion(`type`,[B.object({type:B.literal(`message_start`),message:B.object({id:B.string().nullish(),model:B.string().nullish(),usage:B.looseObject({input_tokens:B.number(),cache_creation_input_tokens:B.number().nullish(),cache_read_input_tokens:B.number().nullish()})})}),B.object({type:B.literal(`content_block_start`),index:B.number(),content_block:B.discriminatedUnion(`type`,[B.object({type:B.literal(`text`),text:B.string()}),B.object({type:B.literal(`thinking`),thinking:B.string()}),B.object({type:B.literal(`tool_use`),id:B.string(),name:B.string()}),B.object({type:B.literal(`redacted_thinking`),data:B.string()}),B.object({type:B.literal(`server_tool_use`),id:B.string(),name:B.string(),input:B.record(B.string(),B.unknown()).nullish()}),B.object({type:B.literal(`web_fetch_tool_result`),tool_use_id:B.string(),content:B.union([B.object({type:B.literal(`web_fetch_result`),url:B.string(),retrieved_at:B.string(),content:B.object({type:B.literal(`document`),title:B.string().nullable(),citations:B.object({enabled:B.boolean()}).optional(),source:B.object({type:B.literal(`text`),media_type:B.string(),data:B.string()})})}),B.object({type:B.literal(`web_fetch_tool_result_error`),error_code:B.string()})])}),B.object({type:B.literal(`web_search_tool_result`),tool_use_id:B.string(),content:B.union([B.array(B.object({type:B.literal(`web_search_result`),url:B.string(),title:B.string(),encrypted_content:B.string(),page_age:B.string().nullish()})),B.object({type:B.literal(`web_search_tool_result_error`),error_code:B.string()})])}),B.object({type:B.literal(`code_execution_tool_result`),tool_use_id:B.string(),content:B.union([B.object({type:B.literal(`code_execution_result`),stdout:B.string(),stderr:B.string(),return_code:B.number()}),B.object({type:B.literal(`code_execution_tool_result_error`),error_code:B.string()})])})])}),B.object({type:B.literal(`content_block_delta`),index:B.number(),delta:B.discriminatedUnion(`type`,[B.object({type:B.literal(`input_json_delta`),partial_json:B.string()}),B.object({type:B.literal(`text_delta`),text:B.string()}),B.object({type:B.literal(`thinking_delta`),thinking:B.string()}),B.object({type:B.literal(`signature_delta`),signature:B.string()}),B.object({type:B.literal(`citations_delta`),citation:wt})])}),B.object({type:B.literal(`content_block_stop`),index:B.number()}),B.object({type:B.literal(`error`),error:B.object({type:B.string(),message:B.string()})}),B.object({type:B.literal(`message_delta`),delta:B.object({stop_reason:B.string().nullish(),stop_sequence:B.string().nullish()}),usage:B.looseObject({output_tokens:B.number(),cache_creation_input_tokens:B.number().nullish()})}),B.object({type:B.literal(`message_stop`)}),B.object({type:B.literal(`ping`)})]),At=B.object({signature:B.string().optional(),redactedData:B.string().optional()}),jt=E({id:`anthropic.bash_20241022`,name:`bash`,inputSchema:ce.object({command:ce.string(),restart:ce.boolean().optional()})}),Mt=E({id:`anthropic.bash_20250124`,name:`bash`,inputSchema:ce.object({command:ce.string(),restart:ce.boolean().optional()})}),Nt=E({id:`anthropic.computer_20241022`,name:`computer`,inputSchema:B.object({action:B.enum([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:B.array(B.number().int()).optional(),text:B.string().optional()})}),Pt=E({id:`anthropic.computer_20250124`,name:`computer`,inputSchema:B.object({action:B.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:B.tuple([B.number().int(),B.number().int()]).optional(),duration:B.number().optional(),scroll_amount:B.number().optional(),scroll_direction:B.enum([`up`,`down`,`left`,`right`]).optional(),start_coordinate:B.tuple([B.number().int(),B.number().int()]).optional(),text:B.string().optional()})}),Ft=E({id:`anthropic.text_editor_20241022`,name:`str_replace_editor`,inputSchema:B.object({command:B.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:B.string(),file_text:B.string().optional(),insert_line:B.number().int().optional(),new_str:B.string().optional(),old_str:B.string().optional(),view_range:B.array(B.number().int()).optional()})}),It=E({id:`anthropic.text_editor_20250124`,name:`str_replace_editor`,inputSchema:B.object({command:B.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:B.string(),file_text:B.string().optional(),insert_line:B.number().int().optional(),new_str:B.string().optional(),old_str:B.string().optional(),view_range:B.array(B.number().int()).optional()})}),Lt=E({id:`anthropic.text_editor_20250429`,name:`str_replace_based_edit_tool`,inputSchema:B.object({command:B.enum([`view`,`create`,`str_replace`,`insert`]),path:B.string(),file_text:B.string().optional(),insert_line:B.number().int().optional(),new_str:B.string().optional(),old_str:B.string().optional(),view_range:B.array(B.number().int()).optional()})}),Rt={bash_20241022:jt,bash_20250124:Mt,codeExecution_20250522:vt,computer_20241022:Nt,computer_20250124:Pt,textEditor_20241022:Ft,textEditor_20250124:It,textEditor_20250429:Lt,textEditor_20250728:ot,webFetch_20250910:mt,webSearch_20250305:ut};function zt(e={}){let t=ae(e.baseURL)??`https://api.anthropic.com/v1`,n=()=>z({"anthropic-version":`2023-06-01`,"x-api-key":te({apiKey:e.apiKey,environmentVariableName:`ANTHROPIC_API_KEY`,description:`Anthropic`}),...e.headers},`ai-sdk/anthropic/${Qe}`),r=r=>new Dt(r,{provider:`anthropic.messages`,baseURL:t,headers:n,fetch:e.fetch,generateId:e.generateId??k,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 m({modelId:e,modelType:`textEmbeddingModel`})},i.imageModel=e=>{throw new m({modelId:e,modelType:`imageModel`})},i.tools=Rt,i}zt();var Bt=`2.0.17`,Vt=B.object({error:B.object({code:B.number().nullable(),message:B.string(),status:B.string()})}),Ht=w({errorSchema:Vt,errorToMessage:e=>e.error.message}),Ut=B.object({outputDimensionality:B.number().optional(),taskType:B.enum([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional()}),Wt=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 N({provider:`google`,providerOptions:r,schema:Ut});if(e.length>this.maxEmbeddingsPerCall)throw new g({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let a=v(await L(this.config.headers),t);if(e.length===1){let{responseHeaders:t,value:r,rawValue:o}=await F({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:Ht,successfulResponseHandler:T(Kt),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 F({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:Ht,successfulResponseHandler:T(Gt),abortSignal:n,fetch:this.config.fetch});return{embeddings:s.embeddings.map(e=>e.values),usage:void 0,response:{headers:o,body:c}}}},Gt=B.object({embeddings:B.array(B.object({values:B.array(B.number())}))}),Kt=B.object({embedding:B.object({values:B.array(B.number())})});function qt(e){if(e==null||Jt(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]=qt(n),e),{})),a&&(p.items=Array.isArray(a)?a.map(qt):qt(a)),o&&(p.allOf=o.map(qt)),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=qt(e[0]);typeof t==`object`&&(p.nullable=!0,Object.assign(p,t))}else p.anyOf=e.map(qt),p.nullable=!0}else p.anyOf=s.map(qt);return c&&(p.oneOf=c.map(qt)),d!==void 0&&(p.minLength=d),p}function Jt(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}function Yt(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 _({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:b(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 _({functionality:`Only PNG images are supported in assistant messages`});if(e.data instanceof URL)throw new _({functionality:`File data URLs in assistant messages are not supported`});return{inlineData:{mimeType:e.mediaType,data:b(e.data)}};case`tool-call`:return{functionCall:{name:e.toolName,args:e.input},thoughtSignature:e.providerOptions?.google?.thoughtSignature}}}).filter(e=>e!==void 0)});break;case`tool`:{i=!1;let e=[];for(let t of a){let n=t.output;if(n.type===`content`)for(let r of n.value)switch(r.type){case`text`:e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:r.text}}});break;case`media`:e.push({inlineData:{mimeType:r.mediaType,data:r.data}},{text:`Tool executed successfully and returned this image as a response`});break;default:e.push({text:JSON.stringify(r)});break}else e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:n.value}}})}r.push({role:`user`,parts:e});break}}if(a&&n.length>0&&r.length>0&&r[0].role===`user`){let e=n.map(e=>e.text).join(`
1
+ import{__commonJSMin as e,__esmMin as t,__export as n,__reExport as r,__require as i,__toCommonJS as a,__toESM as o}from"../chunk-D9KrCrVq.js";import{APICallError as s,APIServerURLEnvironmentVariable as c,Agent as l,EventSourceParserStream as u,Hono as d,InvalidPromptError as f,InvalidResponseDataError as p,NoSuchModelError as m,StreamResponseFormatHeader as h,TooManyEmbeddingValuesForCallError as g,UnsupportedFunctionalityError as _,combineHeaders as v,convertBase64ToUint8Array as y,convertToBase64 as b,createBinaryResponseHandler as x,createEventSourceResponseHandler as S,createGatewayProvider as C,createJsonErrorResponseHandler as w,createJsonResponseHandler as T,createProviderDefinedToolFactory as E,createProviderDefinedToolFactoryWithOutputSchema as D,createServerAdapter as O,generateId as k,hc as A,isParsableJson as j,isToolApprovalOutput as ee,lastUIOptions as M,loadApiKey as te,loadOptionalSetting as ne,mediaTypeToExtension as re,parseProviderOptions as N,postFormDataToApi as P,postJsonToApi as F,require_has_flag as I,resolve as L,tools as R,validator as ie,withUserAgentSuffix as z,withoutTrailingSlash as ae}from"../index.node-B6JXREDl.js";import"../token-error-488npYdU.js";import"../esm-CbZfjZBn.js";import{resolveConfig as oe}from"../build-DYI55eX2.js";import{createRequire as se}from"node:module";import ce,{z as B}from"zod/v4";import"zod/v3";import{Buffer as V}from"node:buffer";import*as H from"node:fs";import le,{existsSync as ue,mkdirSync as de,readFileSync as fe,unlinkSync as pe,writeFileSync as me}from"node:fs";import{fileURLToPath as he}from"node:url";import{Writable as ge}from"node:stream";import{promisify as _e,stripVTControlCharacters as ve}from"node:util";import{createHash as ye}from"node:crypto";import U,{createServer as be}from"http";import{dirname as xe,join as Se}from"path";import{existsSync as Ce,mkdirSync as we,readFileSync as Te,watch as Ee,writeFileSync as De}from"fs";import{convertToModelMessages as Oe,isToolOrDynamicToolUIPart as ke,readUIMessageStream as Ae,streamText as je,tool as W}from"ai";import{readFile as Me,stat as Ne,writeFile as Pe}from"fs/promises";import{spawn as Fe}from"child_process";import{useCallback as G,useEffect as K,useMemo as Ie,useRef as Le,useState as q}from"react";import J,{z as Y}from"zod";import*as Re from"node:path";import ze,{dirname as Be,join as Ve}from"node:path";import X,{stdin as He,stdout as Ue}from"node:process";import*as We from"node:readline";import Ge from"node:readline";import Ke,{execFile as qe}from"node:child_process";import Je,{constants as Ye}from"node:fs/promises";import Xe from"node:os";import"@blink-sdk/compute-protocol/client";import{createInMemoryClientServer as Ze}from"@blink-sdk/compute-protocol/transport";var Qe=`2.0.23`,$e=B.object({type:B.literal(`error`),error:B.object({type:B.string(),message:B.string()})}),et=w({errorSchema:$e,errorToMessage:e=>e.error.message}),tt=B.object({citations:B.object({enabled:B.boolean()}).optional(),title:B.string().optional(),context:B.string().optional()}),nt=B.object({sendReasoning:B.boolean().optional(),thinking:B.object({type:B.union([B.literal(`enabled`),B.literal(`disabled`)]),budgetTokens:B.number().optional()}).optional(),disableParallelToolUse:B.boolean().optional(),cacheControl:B.object({type:B.literal(`ephemeral`),ttl:B.union([B.literal(`5m`),B.literal(`1h`)]).optional()}).optional()});function rt(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var it=B.object({maxCharacters:B.number().optional()}),at=E({id:`anthropic.text_editor_20250728`,name:`str_replace_based_edit_tool`,inputSchema:B.object({command:B.enum([`view`,`create`,`str_replace`,`insert`]),path:B.string(),file_text:B.string().optional(),insert_line:B.number().int().optional(),new_str:B.string().optional(),old_str:B.string().optional(),view_range:B.array(B.number().int()).optional()})}),ot=(e={})=>at(e),st=B.object({maxUses:B.number().optional(),allowedDomains:B.array(B.string()).optional(),blockedDomains:B.array(B.string()).optional(),userLocation:B.object({type:B.literal(`approximate`),city:B.string().optional(),region:B.string().optional(),country:B.string().optional(),timezone:B.string().optional()}).optional()}),ct=B.array(B.object({url:B.string(),title:B.string(),pageAge:B.string().nullable(),encryptedContent:B.string(),type:B.literal(`web_search_result`)})),lt=D({id:`anthropic.web_search_20250305`,name:`web_search`,inputSchema:B.object({query:B.string()}),outputSchema:ct}),ut=(e={})=>lt(e),dt=B.object({maxUses:B.number().optional(),allowedDomains:B.array(B.string()).optional(),blockedDomains:B.array(B.string()).optional(),citations:B.object({enabled:B.boolean()}).optional(),maxContentTokens:B.number().optional()}),ft=B.object({type:B.literal(`web_fetch_result`),url:B.string(),content:B.object({type:B.literal(`document`),title:B.string(),citations:B.object({enabled:B.boolean()}).optional(),source:B.union([B.object({type:B.literal(`base64`),mediaType:B.literal(`application/pdf`),data:B.string()}),B.object({type:B.literal(`text`),mediaType:B.literal(`text/plain`),data:B.string()})])}),retrievedAt:B.string().nullable()}),pt=D({id:`anthropic.web_fetch_20250910`,name:`web_fetch`,inputSchema:B.object({url:B.string()}),outputSchema:ft}),mt=(e={})=>pt(e);function ht({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=rt(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=it.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=dt.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=st.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 _({functionality:`tool choice type: ${o}`})}}var gt=B.object({type:B.literal(`code_execution_result`),stdout:B.string(),stderr:B.string(),return_code:B.number()}),_t=D({id:`anthropic.code_execution_20250522`,name:`code_execution`,inputSchema:B.object({code:B.string()}),outputSchema:gt}),vt=(e={})=>_t(e);function yt(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 _({functionality:`URL-based text documents are not supported for citations`}):new _({functionality:`unsupported data type for text documents: ${typeof e}`})}async function bt({prompt:e,sendReasoning:t,warnings:n}){let r=new Set,i=xt(e),a,o=[];async function s(e){return(await N({provider:`anthropic`,providerOptions:e,schema:tt}))?.citations?.enabled??!1}async function c(e){let t=await N({provider:`anthropic`,providerOptions:e,schema:tt});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 _({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:rt(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=rt(a.providerOptions)??(o?rt(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:b(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:b(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:yt(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else throw new _({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=rt(r.providerOptions)??(a?rt(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 _({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=rt(s.providerOptions)??(c?rt(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 N({provider:`anthropic`,providerOptions:s.providerOptions,schema:At});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=gt.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=ft.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=ct.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 xt(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 St({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 Ct={webSearchResult:B.object({type:B.literal(`web_search_result_location`),cited_text:B.string(),url:B.string(),title:B.string(),encrypted_index:B.string()}),pageLocation:B.object({type:B.literal(`page_location`),cited_text:B.string(),document_index:B.number(),document_title:B.string().nullable(),start_page_number:B.number(),end_page_number:B.number()}),charLocation:B.object({type:B.literal(`char_location`),cited_text:B.string(),document_index:B.number(),document_title:B.string().nullable(),start_char_index:B.number(),end_char_index:B.number()})},wt=B.discriminatedUnion(`type`,[Ct.webSearchResult,Ct.pageLocation,Ct.charLocation]);B.discriminatedUnion(`type`,[Ct.pageLocation,Ct.charLocation]);function Tt(e,t,n,r){if(e.type===`page_location`||e.type===`char_location`){let i=Et(e,t,n);i&&r(i)}}function Et(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 Dt=class{constructor(e,t){this.specificationVersion=`v2`,this.modelId=e,this.config=t,this.generateId=t.generateId??k}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 N({provider:`anthropic`,providerOptions:f,schema:nt}),{prompt:g,betas:v}=await bt({prompt:e,sendReasoning:h?.sendReasoning??!0,warnings:p}),y=h?.thinking?.type===`enabled`,b=h?.thinking?.budgetTokens,x={model:this.modelId,max_tokens:t,temperature:n,top_k:i,top_p:r,stop_sequences:s,...y&&{thinking:{type:`enabled`,budget_tokens:b}},system:g.system,messages:g.messages};if(y){if(b==null)throw new _({functionality:`thinking requires a budget`});x.temperature!=null&&(x.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported when thinking is enabled`})),i!=null&&(x.top_k=void 0,p.push({type:`unsupported-setting`,setting:`topK`,details:`topK is not supported when thinking is enabled`})),r!=null&&(x.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported when thinking is enabled`})),x.max_tokens=t+b}let{tools:S,toolChoice:C,toolWarnings:w,betas:T}=ht(m==null?{tools:u??[],toolChoice:d,disableParallelToolUse:h?.disableParallelToolUse}:{tools:[m],toolChoice:{type:`tool`,toolName:m.name},disableParallelToolUse:!0});return{args:{...x,tools:S,tool_choice:C},warnings:[...p,...w],betas:new Set([...v,...T]),usesJsonResponseTool:m!=null}}async getHeaders({betas:e,headers:t}){return v(await L(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 F({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(t),failedResponseHandler:et,successfulResponseHandler:T(Ot),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)Tt(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:St({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 F({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(o),failedResponseHandler:et,successfulResponseHandler:S(kt),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;Tt(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=St({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}}}},Ot=B.object({type:B.literal(`message`),id:B.string().nullish(),model:B.string().nullish(),content:B.array(B.discriminatedUnion(`type`,[B.object({type:B.literal(`text`),text:B.string(),citations:B.array(wt).optional()}),B.object({type:B.literal(`thinking`),thinking:B.string(),signature:B.string()}),B.object({type:B.literal(`redacted_thinking`),data:B.string()}),B.object({type:B.literal(`tool_use`),id:B.string(),name:B.string(),input:B.unknown()}),B.object({type:B.literal(`server_tool_use`),id:B.string(),name:B.string(),input:B.record(B.string(),B.unknown()).nullish()}),B.object({type:B.literal(`web_fetch_tool_result`),tool_use_id:B.string(),content:B.union([B.object({type:B.literal(`web_fetch_result`),url:B.string(),retrieved_at:B.string(),content:B.object({type:B.literal(`document`),title:B.string().nullable(),citations:B.object({enabled:B.boolean()}).optional(),source:B.object({type:B.literal(`text`),media_type:B.string(),data:B.string()})})}),B.object({type:B.literal(`web_fetch_tool_result_error`),error_code:B.string()})])}),B.object({type:B.literal(`web_search_tool_result`),tool_use_id:B.string(),content:B.union([B.array(B.object({type:B.literal(`web_search_result`),url:B.string(),title:B.string(),encrypted_content:B.string(),page_age:B.string().nullish()})),B.object({type:B.literal(`web_search_tool_result_error`),error_code:B.string()})])}),B.object({type:B.literal(`code_execution_tool_result`),tool_use_id:B.string(),content:B.union([B.object({type:B.literal(`code_execution_result`),stdout:B.string(),stderr:B.string(),return_code:B.number()}),B.object({type:B.literal(`code_execution_tool_result_error`),error_code:B.string()})])})])),stop_reason:B.string().nullish(),stop_sequence:B.string().nullish(),usage:B.looseObject({input_tokens:B.number(),output_tokens:B.number(),cache_creation_input_tokens:B.number().nullish(),cache_read_input_tokens:B.number().nullish()})}),kt=B.discriminatedUnion(`type`,[B.object({type:B.literal(`message_start`),message:B.object({id:B.string().nullish(),model:B.string().nullish(),usage:B.looseObject({input_tokens:B.number(),cache_creation_input_tokens:B.number().nullish(),cache_read_input_tokens:B.number().nullish()})})}),B.object({type:B.literal(`content_block_start`),index:B.number(),content_block:B.discriminatedUnion(`type`,[B.object({type:B.literal(`text`),text:B.string()}),B.object({type:B.literal(`thinking`),thinking:B.string()}),B.object({type:B.literal(`tool_use`),id:B.string(),name:B.string()}),B.object({type:B.literal(`redacted_thinking`),data:B.string()}),B.object({type:B.literal(`server_tool_use`),id:B.string(),name:B.string(),input:B.record(B.string(),B.unknown()).nullish()}),B.object({type:B.literal(`web_fetch_tool_result`),tool_use_id:B.string(),content:B.union([B.object({type:B.literal(`web_fetch_result`),url:B.string(),retrieved_at:B.string(),content:B.object({type:B.literal(`document`),title:B.string().nullable(),citations:B.object({enabled:B.boolean()}).optional(),source:B.object({type:B.literal(`text`),media_type:B.string(),data:B.string()})})}),B.object({type:B.literal(`web_fetch_tool_result_error`),error_code:B.string()})])}),B.object({type:B.literal(`web_search_tool_result`),tool_use_id:B.string(),content:B.union([B.array(B.object({type:B.literal(`web_search_result`),url:B.string(),title:B.string(),encrypted_content:B.string(),page_age:B.string().nullish()})),B.object({type:B.literal(`web_search_tool_result_error`),error_code:B.string()})])}),B.object({type:B.literal(`code_execution_tool_result`),tool_use_id:B.string(),content:B.union([B.object({type:B.literal(`code_execution_result`),stdout:B.string(),stderr:B.string(),return_code:B.number()}),B.object({type:B.literal(`code_execution_tool_result_error`),error_code:B.string()})])})])}),B.object({type:B.literal(`content_block_delta`),index:B.number(),delta:B.discriminatedUnion(`type`,[B.object({type:B.literal(`input_json_delta`),partial_json:B.string()}),B.object({type:B.literal(`text_delta`),text:B.string()}),B.object({type:B.literal(`thinking_delta`),thinking:B.string()}),B.object({type:B.literal(`signature_delta`),signature:B.string()}),B.object({type:B.literal(`citations_delta`),citation:wt})])}),B.object({type:B.literal(`content_block_stop`),index:B.number()}),B.object({type:B.literal(`error`),error:B.object({type:B.string(),message:B.string()})}),B.object({type:B.literal(`message_delta`),delta:B.object({stop_reason:B.string().nullish(),stop_sequence:B.string().nullish()}),usage:B.looseObject({output_tokens:B.number(),cache_creation_input_tokens:B.number().nullish()})}),B.object({type:B.literal(`message_stop`)}),B.object({type:B.literal(`ping`)})]),At=B.object({signature:B.string().optional(),redactedData:B.string().optional()}),jt=E({id:`anthropic.bash_20241022`,name:`bash`,inputSchema:ce.object({command:ce.string(),restart:ce.boolean().optional()})}),Mt=E({id:`anthropic.bash_20250124`,name:`bash`,inputSchema:ce.object({command:ce.string(),restart:ce.boolean().optional()})}),Nt=E({id:`anthropic.computer_20241022`,name:`computer`,inputSchema:B.object({action:B.enum([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:B.array(B.number().int()).optional(),text:B.string().optional()})}),Pt=E({id:`anthropic.computer_20250124`,name:`computer`,inputSchema:B.object({action:B.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:B.tuple([B.number().int(),B.number().int()]).optional(),duration:B.number().optional(),scroll_amount:B.number().optional(),scroll_direction:B.enum([`up`,`down`,`left`,`right`]).optional(),start_coordinate:B.tuple([B.number().int(),B.number().int()]).optional(),text:B.string().optional()})}),Ft=E({id:`anthropic.text_editor_20241022`,name:`str_replace_editor`,inputSchema:B.object({command:B.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:B.string(),file_text:B.string().optional(),insert_line:B.number().int().optional(),new_str:B.string().optional(),old_str:B.string().optional(),view_range:B.array(B.number().int()).optional()})}),It=E({id:`anthropic.text_editor_20250124`,name:`str_replace_editor`,inputSchema:B.object({command:B.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:B.string(),file_text:B.string().optional(),insert_line:B.number().int().optional(),new_str:B.string().optional(),old_str:B.string().optional(),view_range:B.array(B.number().int()).optional()})}),Lt=E({id:`anthropic.text_editor_20250429`,name:`str_replace_based_edit_tool`,inputSchema:B.object({command:B.enum([`view`,`create`,`str_replace`,`insert`]),path:B.string(),file_text:B.string().optional(),insert_line:B.number().int().optional(),new_str:B.string().optional(),old_str:B.string().optional(),view_range:B.array(B.number().int()).optional()})}),Rt={bash_20241022:jt,bash_20250124:Mt,codeExecution_20250522:vt,computer_20241022:Nt,computer_20250124:Pt,textEditor_20241022:Ft,textEditor_20250124:It,textEditor_20250429:Lt,textEditor_20250728:ot,webFetch_20250910:mt,webSearch_20250305:ut};function zt(e={}){let t=ae(e.baseURL)??`https://api.anthropic.com/v1`,n=()=>z({"anthropic-version":`2023-06-01`,"x-api-key":te({apiKey:e.apiKey,environmentVariableName:`ANTHROPIC_API_KEY`,description:`Anthropic`}),...e.headers},`ai-sdk/anthropic/${Qe}`),r=r=>new Dt(r,{provider:`anthropic.messages`,baseURL:t,headers:n,fetch:e.fetch,generateId:e.generateId??k,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 m({modelId:e,modelType:`textEmbeddingModel`})},i.imageModel=e=>{throw new m({modelId:e,modelType:`imageModel`})},i.tools=Rt,i}zt();var Bt=`2.0.17`,Vt=B.object({error:B.object({code:B.number().nullable(),message:B.string(),status:B.string()})}),Ht=w({errorSchema:Vt,errorToMessage:e=>e.error.message}),Ut=B.object({outputDimensionality:B.number().optional(),taskType:B.enum([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional()}),Wt=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 N({provider:`google`,providerOptions:r,schema:Ut});if(e.length>this.maxEmbeddingsPerCall)throw new g({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let a=v(await L(this.config.headers),t);if(e.length===1){let{responseHeaders:t,value:r,rawValue:o}=await F({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:Ht,successfulResponseHandler:T(Kt),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 F({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:Ht,successfulResponseHandler:T(Gt),abortSignal:n,fetch:this.config.fetch});return{embeddings:s.embeddings.map(e=>e.values),usage:void 0,response:{headers:o,body:c}}}},Gt=B.object({embeddings:B.array(B.object({values:B.array(B.number())}))}),Kt=B.object({embedding:B.object({values:B.array(B.number())})});function qt(e){if(e==null||Jt(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]=qt(n),e),{})),a&&(p.items=Array.isArray(a)?a.map(qt):qt(a)),o&&(p.allOf=o.map(qt)),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=qt(e[0]);typeof t==`object`&&(p.nullable=!0,Object.assign(p,t))}else p.anyOf=e.map(qt),p.nullable=!0}else p.anyOf=s.map(qt);return c&&(p.oneOf=c.map(qt)),d!==void 0&&(p.minLength=d),p}function Jt(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}function Yt(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 _({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:b(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 _({functionality:`Only PNG images are supported in assistant messages`});if(e.data instanceof URL)throw new _({functionality:`File data URLs in assistant messages are not supported`});return{inlineData:{mimeType:e.mediaType,data:b(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
 
@@ -50,7 +50,7 @@ ${kc}`),t.includes(`
50
50
  `)&&(n=3+ve(t.slice(t.lastIndexOf(`
51
51
  `))).length);let e=ve(t).length;n+e<process.stdout.columns?(n+=e,process.stdout.write(t)):(process.stdout.write(`
52
52
  ${kc}${t.trimStart()}`),n=3+ve(t.trimStart()).length)}process.stdout.write(`
53
- `)},info:e=>Ac.message(e,{symbol:vc.default.blue(wc)}),success:e=>Ac.message(e,{symbol:vc.default.green(Tc)}),step:e=>Ac.message(e,{symbol:vc.default.green(Sc)}),warn:e=>Ac.message(e,{symbol:vc.default.yellow(Ec)}),warning:e=>Ac.warn(e),error:e=>Ac.message(e,{symbol:vc.default.red(Dc)})};let jc;function Mc(){try{return le.statSync(`/.dockerenv`),!0}catch{return!1}}function Nc(){try{return le.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function Pc(){return jc===void 0&&(jc=Mc()||Nc()),jc}let Fc;const Ic=()=>{try{return le.statSync(`/run/.containerenv`),!0}catch{return!1}};function Lc(){return Fc===void 0&&(Fc=Ic()||Pc()),Fc}const Rc=()=>{if(X.platform!==`linux`)return!1;if(Xe.release().toLowerCase().includes(`microsoft`))return!Lc();try{return le.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!Lc():!1}catch{return!1}};var zc=X.env.__IS_WSL_TEST__?Rc:Rc();const Bc=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await Je.access(n,Ye.F_OK),r=!0}catch{}if(!r)return e;let i=await Je.readFile(n,{encoding:`utf8`}),a=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(i);return a?(t=a.groups.mountPoint.trim(),t=t.endsWith(`/`)?t:`${t}/`,t):e}})(),Vc=async()=>`${await Bc()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Hc=async()=>zc?Vc():`${X.env.SYSTEMROOT||X.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function Uc(e,t,n){let r=n=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0});return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){let e=n();return r(e),e},set(e){r(e)}}),e}const Wc=_e(qe);async function Gc(){if(X.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await Wc(`defaults`,[`read`,`com.apple.LaunchServices/com.apple.launchservices.secure`,`LSHandlers`]);return/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??`com.apple.Safari`}const Kc=_e(qe);async function qc(e,{humanReadableOutput:t=!0,signal:n}={}){if(X.platform!==`darwin`)throw Error(`macOS only`);let r=t?[]:[`-ss`],i={};n&&(i.signal=n);let{stdout:a}=await Kc(`osascript`,[`-e`,e,r],i);return a.trim()}async function Jc(e){return qc(`tell application "Finder" to set app_path to application file id "${e}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}const Yc=_e(qe),Xc={AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:`Edge`,id:`com.microsoft.edge.old`},MSEdgeDHTML:{name:`Edge`,id:`com.microsoft.edge`},MSEdgeHTM:{name:`Edge`,id:`com.microsoft.edge`},"IE.HTTP":{name:`Internet Explorer`,id:`com.microsoft.ie`},FirefoxURL:{name:`Firefox`,id:`org.mozilla.firefox`},ChromeHTML:{name:`Chrome`,id:`com.google.chrome`},BraveHTML:{name:`Brave`,id:`com.brave.Browser`},BraveBHTML:{name:`Brave Beta`,id:`com.brave.Browser.beta`},BraveSSHTM:{name:`Brave Nightly`,id:`com.brave.Browser.nightly`}};var Zc=class extends Error{};async function Qc(e=Yc){let{stdout:t}=await e(`reg`,[`QUERY`,` HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice`,`/v`,`ProgId`]),n=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(t);if(!n)throw new Zc(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=Xc[r];if(!i)throw new Zc(`Unknown browser ID: ${r}`);return i}const $c=_e(qe),el=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function tl(){if(X.platform===`darwin`){let e=await Gc();return{name:await Jc(e),id:e}}if(X.platform===`linux`){let{stdout:e}=await $c(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:el(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(X.platform===`win32`)return Qc();throw Error(`Only macOS, Linux, and Windows are supported`)}const nl=_e(Ke.execFile),rl=ze.dirname(he(import.meta.url)),il=ze.join(rl,`xdg-open`),{platform:al,arch:ol}=X;async function sl(){let e=await Hc(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=V.from(t,`utf16le`).toString(`base64`),{stdout:r}=await nl(e,[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,n],{encoding:`utf8`}),i=r.trim(),a={ChromeHTML:`com.google.chrome`,BraveHTML:`com.brave.Browser`,MSEdgeHTM:`com.microsoft.edge`,FirefoxURL:`org.mozilla.firefox`};return a[i]?{id:a[i]}:{}}const cl=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},ll=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return cl(e.app,t=>ll({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return cl(t,t=>ll({...e,app:{name:t,arguments:n}}));if(t===`browser`||t===`browserPrivate`){let r={"com.google.chrome":`chrome`,"google-chrome.desktop":`chrome`,"com.brave.Browser":`brave`,"org.mozilla.firefox":`firefox`,"firefox.desktop":`firefox`,"com.microsoft.msedge":`edge`,"com.microsoft.edge":`edge`,"com.microsoft.edgemac":`edge`,"microsoft-edge.desktop":`edge`},i={chrome:`--incognito`,brave:`--incognito`,firefox:`--private-window`,edge:`--inPrivate`},a=zc?await sl():await tl();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),ll({...e,app:{name:pl[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,i=[],a={};if(al===`darwin`)r=`open`,e.wait&&i.push(`--wait-apps`),e.background&&i.push(`--background`),e.newInstance&&i.push(`--new`),t&&i.push(`-a`,t);else if(al===`win32`||zc&&!Lc()&&!t){r=await Hc(),i.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),zc||(a.windowsVerbatimArguments=!0);let o=[`Start`];e.wait&&o.push(`-Wait`),t?(o.push(`"\`"${t}\`""`),e.target&&n.push(e.target)):e.target&&o.push(`"${e.target}"`),n.length>0&&(n=n.map(e=>`"\`"${e}\`""`),o.push(`-ArgumentList`,n.join(`,`))),e.target=V.from(o.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!rl||rl===`/`,t=!1;try{await Je.access(il,Ye.X_OK),t=!0}catch{}r=X.versions.electron??(al===`android`||e||!t)?`xdg-open`:il}n.length>0&&i.push(...n),e.wait||(a.stdio=`ignore`,a.detached=!0)}al===`darwin`&&n.length>0&&i.push(`--args`,...n),e.target&&i.push(e.target);let o=Ke.spawn(r,i,a);return e.wait?new Promise((t,n)=>{o.once(`error`,n),o.once(`close`,r=>{if(!e.allowNonzeroExitCode&&r>0){n(Error(`Exited with code ${r}`));return}t(o)})}):(o.unref(),o)},ul=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return ll({...t,target:e})};function dl(e){if(typeof e==`string`||Array.isArray(e))return e;let{[ol]:t}=e;if(!t)throw Error(`${ol} is not supported`);return t}function fl({[al]:e},{wsl:t}){if(t&&zc)return dl(t);if(!e)throw Error(`${al} is not supported`);return dl(e)}const pl={};Uc(pl,`chrome`,()=>fl({darwin:`google chrome`,win32:`chrome`,linux:[`google-chrome`,`google-chrome-stable`,`chromium`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`,x64:[`/mnt/c/Program Files/Google/Chrome/Application/chrome.exe`,`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`]}})),Uc(pl,`brave`,()=>fl({darwin:`brave browser`,win32:`brave`,linux:[`brave-browser`,`brave`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`,x64:[`/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe`,`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`]}})),Uc(pl,`firefox`,()=>fl({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),Uc(pl,`edge`,()=>fl({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),Uc(pl,`browser`,()=>`browser`),Uc(pl,`browserPrivate`,()=>`browserPrivate`);var ml=ul;async function hl(e,t=void 0){try{(await ml(e)).once(`error`,n=>{console.log(ac.default.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))})}catch{console.log(ac.default.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))}}nc();function gl(e){let t=e||yl();if(ue(t)){let e=fe(t,`utf8`);return JSON.parse(e).token}}function _l(e,t){let n=t||yl();ue(Be(n))||de(Be(n),{recursive:!0}),me(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function vl(e){let t=e||yl();ue(t)&&pe(t)}function yl(){let e=qs(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return Ve(e[0],`auth.json`)}function bl(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=q(),[s,c]=q(()=>gl(i)),[l,u]=q(),d=Le(n),f=Le(r);K(()=>{d.current=n,f.current=r},[n,r]);let p=G(async()=>{u(void 0);try{let e=gl(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new ks({baseURL:`https://blink.so`});t.authToken=e;let n={email:(await t.users.me()).email};o(n),d.current?.(n)}catch(e){o(void 0),u(e instanceof Error?e.message:String(e)),d.current?.(void 0)}},[i]),m=G(async()=>{u(void 0);try{let e=new ks,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();_l(t,i),c(t);let r={email:n.email};return o(r),d.current?.(r),r}catch(e){let t=e instanceof Error?e.message:String(e);throw u(t),e}},[i]),h=G(()=>{vl(i),c(void 0),o(void 0),u(void 0),d.current?.(void 0)},[i]);return K(()=>{t&&p()},[t,p]),{user:a,token:s,error:l,login:m,logout:h}}function xl(e){let{directory:t,onBuildStart:n,onBuildSuccess:r,onBuildError:i}=typeof e==`string`?{directory:e}:e,a=Ie(()=>oe(t),[t]),[o,s]=q(void 0),[c,l]=q(void 0),[u,d]=q(`building`),f=Le(n),p=Le(r),m=Le(i);return K(()=>{f.current=n,p.current=r,m.current=i},[n,r,i]),K(()=>{let e=new AbortController;return a.build({cwd:t,entry:a.entry,outdir:a.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{d(`building`),s(void 0),l(void 0),f.current?.()},onResult:e=>{`error`in e?(s(e.error),d(`error`),m.current?.(e.error)):(l(e),d(`success`),p.current?.(e))}}).catch(e=>{console.log(`error`,e),d(`error`),s(e),m.current?.(e)}),()=>{e.abort()}},[t]),Ie(()=>({error:o,status:u,result:c,entry:a.entry,outdir:a.outdir}),[o,u,c,a.entry,a.outdir])}function Sl(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function Cl(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const wl=/^\.+(\\|\/)|^\.+$/,Tl=/[. ]+$/,El=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,Dl=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,Ol=e=>e===`‍`,kl=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,Al=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let jl;function Ml(){return jl??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),jl}function Nl(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(Sl().test(n)||[...n].some(e=>Dl.test(e)&&!Ol(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(Al,` `),n.length>0&&(e=e.replaceAll(kl,`$1`)),e=e.replace(Tl,``),e=e.replace(wl,n),e=e.replace(Sl(),n),e=e.replaceAll(El,e=>Ol(e)?e:n),e.length===0&&(e=n),e=Cl().test(e)?e+n:e;let r=typeof t.maxLength==`number`?t.maxLength:100;if(e.length>r){let t=e.lastIndexOf(`.`);if(t===-1)e=Pl(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=Pl(n,a)+i}}return e}function Pl(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of Ml().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function Fl(e){return`${e}.lock`}function Il(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function Ll(e,t={}){let n=Fl(e),r=process.pid.toString();try{return H.writeFileSync(n,r,{flag:`wx`}),!0}catch(r){if(r.code!==`EEXIST`)throw r;if(t.stale===0)return!1;let i;try{i=parseInt(H.readFileSync(n,`utf8`),10)}catch{return H.unlinkSync(n),Ll(e,{...t,stale:0})}if(!Il(i))try{return H.unlinkSync(n),Ll(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return Ll(e,{...t,stale:0});throw n}return!1}}async function Rl(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=Re.resolve(e),i=0;for(;i<=n.retries;){if(Ll(r,n))return()=>zl(r);i<n.retries&&await new Promise(e=>setTimeout(e,n.retryInterval)),i++}let a=Error(`Lock file is already being held`);throw a.code=`ELOCKED`,a.file=r,a}function zl(e){let t=Re.resolve(e),n=Fl(t);try{if(parseInt(H.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}H.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function Bl(e){let t=Re.resolve(e),n=Fl(t);try{if(!H.existsSync(n))return{locked:!1};let e=H.readFileSync(n,`utf8`),t=parseInt(e,10);return Il(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const Vl=e=>{H.mkdirSync(e,{recursive:!0})},Hl=e=>{try{H.fdatasyncSync(e)}catch{}try{H.closeSync(e)}catch{}},Ul=e=>{try{let t=H.openSync(e,`r`);try{H.fsyncSync(t)}finally{H.closeSync(t)}}catch{}},Wl=(e,t)=>{let n=Re.dirname(e);Vl(n);let r=Re.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=H.openSync(r,`w`),H.writeFileSync(i,t,`utf-8`),Hl(i),i=void 0,H.renameSync(r,e),Ul(e),Ul(n)}catch(e){if(i!==void 0)try{H.closeSync(i)}catch{}try{H.rmSync(r,{force:!0})}catch{}throw e}},Gl=(e,t)=>{let n=new Map,r,i=e=>{if(H.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(H.readFileSync(e,`utf-8`))},a=(e,t)=>{Wl(e,JSON.stringify(t,null,2))},o=async()=>{if(r)throw Error(`Index is already locked`);let t=Re.join(e,`index.json`);Vl(e),H.existsSync(t)||H.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await Rl(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},s=async()=>{let t=Re.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},c=async t=>{let n=Re.join(e,`index.json`);a(n,t)},l=async t=>{let n=(await s()).ids[t];if(n)return Re.join(e,n)},u=async t=>{let n=(await s()).ids[t];if(!n)return;let r=Re.join(e,n);if(H.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(H.readFileSync(r,`utf-8`))},d=async n=>{let r=n[t],i=String(r),l=Nl(i,{replacement:`_`})+`.json`,u=await o();try{let t=await s();t.ids[i]=l,t.current=i;let r=Re.join(e,l);a(r,n),await c(t)}finally{await u()}};return{async get(e){return await u(e)},async list(){if(!H.statSync(e,{throwIfNoEntry:!1}))return[];let t=await s(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=Re.join(e,i),a=H.statSync(t,{throwIfNoEntry:!1});if(!a)continue;let o=Bl(t);n.push({key:r,locked:o.locked,pid:o.pid,mtime:a.mtimeMs})}return n.sort((e,t)=>t.mtime-e.mtime),n},async lock(r,i){if(n.has(r))throw Error(`Key "${r}" is already locked in this process`);let a=await l(r);if(!a){let t=Nl(r,{replacement:`_`})+`.json`,n=await o();try{let n=await s();n.ids[r]=t;let i=Re.join(e,t);Vl(e),H.writeFileSync(i,JSON.stringify({}),`utf-8`),await c(n),a=i}finally{await n()}}if(i?.force){let e=Bl(a);if(e.locked&&e.pid&&e.pid!==process.pid)try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,100))}catch(t){t.code!==`ESRCH`&&console.warn(`Failed to kill process ${e.pid}:`,t.message)}}let f=await Rl(a,{stale:!0,retries:i?.force?10:5,retryInterval:(i?.force,100)});return n.set(r,()=>Promise.resolve(f())),{async get(){let e=await u(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await d(e)},async update(e){let n=await u(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await d({...n,...e})},async delete(){let t=await o();try{let t=await s(),n=t.ids[r];if(n){delete t.ids[r],t.current===r&&(t.current=void 0),await c(t);let i=Re.join(e,n);try{H.rmSync(i,{force:!0}),Ul(e)}catch{}}}finally{await t()}},async release(){try{f()}finally{n.delete(r)}}}},dispose(){n.clear()}}},Kl=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,a,o,s=new Map,c=new Map,l=Re.join(e,`index.json`),u=()=>{try{if(!H.statSync(l,{throwIfNoEntry:!1}))return{ids:{}};let e=H.readFileSync(l,`utf-8`);return{ids:JSON.parse(e).ids??{}}}catch{return{ids:{}}}},d=(e,t,n,r)=>{for(let a of i)try{a({key:e,value:t,locked:n,pid:r})}catch(e){console.error(`Error in onChange callback:`,e)}},f=(t,n,r=!1)=>{let i=Re.join(e,n);try{let e=H.statSync(i,{throwIfNoEntry:!1}),a=c.get(n);if(!e){a&&(c.delete(n),d(t,void 0,!1));return}let o=e.mtimeMs,s=a?{locked:a.locked,pid:a.pid}:{locked:!1,pid:void 0};if((r||!a)&&(s=Bl(i)),!a||a.mtime!==o||a.locked!==s.locked||a.pid!==s.pid){let e;e=!a||a.mtime!==o?JSON.parse(H.readFileSync(i,`utf-8`)):a.cachedValue,c.set(n,{mtime:o,key:t,locked:s.locked,pid:s.pid,cachedValue:e}),d(t,e,s.locked,s.pid)}}catch{}},p=()=>{try{let e=u(),t=new Set(Object.keys(e.ids));for(let[t,n]of Object.entries(e.ids))f(t,n,!0);for(let[e,n]of c.entries())t.has(n.key)||(c.delete(e),d(n.key,void 0,!1))}catch{}},m=(e,t,n=!1)=>{let i=s.get(e);i&&clearTimeout(i),s.set(e,setTimeout(()=>{s.delete(e),f(e,t,n)},r))},h=()=>{if(a)return;try{H.mkdirSync(e,{recursive:!0})}catch{}a=H.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){p();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=u(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&f(r,e,!0);return}let n=u(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&m(r,t,!1)});let t=()=>{p(),o=setTimeout(t,n)};p(),o=setTimeout(t,n)};return{onChange(e){return i.size===0&&h(),i.add(e),()=>{if(i.delete(e),i.size===0){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),c.clear()}}},dispose(){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),i.clear(),c.clear()}}};async function ql({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=Jl}){n=[...n];let a=new TransformStream,o=a.writable.getWriter(),s=async()=>{let a;try{let c=await t.chat({messages:n,id:e},{signal:r}),l=Ae({message:{id:crypto.randomUUID(),role:`assistant`,parts:[],metadata:{}},stream:c,onError:e=>{e instanceof Error&&e.name===`AbortError`||o.abort(e)}});for await(let e of l)o.write(e),a=e;if(a&&i(a)){n.push(a),await s();return}await o.close()}catch(e){if(e?.name===`AbortError`||r?.aborted)return;await o.abort(e)}finally{await o.close()}};return s().catch(e=>{o.abort(e)}),a.readable}const Jl=e=>{if(e.role!==`assistant`)return!1;let t=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),n=e.parts.slice(t+1).filter(ke);return n.length===0||n.some(e=>ee(e.output)&&e.output.outcome===`pending`)?!1:n.every(e=>e.state.startsWith(`output-`))},Yl=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function Xl(e){return typeof e==`object`&&e?.__blink_internal!==void 0}var Zl=class{chatId;agent;chatStore;serializeMessage;filterMessages;chat;loading=!1;streamingMessage;status=`idle`;queue=[];abortController;isProcessingQueue=!1;listeners=new Set;watcher;disposed=!1;constructor(e){this.chatId=e.chatId??`00000000-0000-0000-0000-000000000000`,this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.loading=!0,this.chatStore=Gl(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.watcher=Kl(e.chatsDirectory,{pollInterval:1e3,debounce:50}),this.watcher.onChange(e=>{if(e.key!==this.chatId||this.isProcessingQueue)return;if(!e.value){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.status=`idle`,this.streamingMessage=void 0,this.notifyListeners();return}if(this.chat.updated_at===e.value?.updated_at)return;let t=e.value,n=e.value?.error?`error`:`idle`;e.locked&&(n=`streaming`);let r=this.chat.updated_at!==t?.updated_at||this.status!==n;this.chat={...t,error:void 0},this.streamingMessage=void 0,this.status=n,r&&this.notifyListeners()}),this.chatStore.get(this.chatId).then(e=>{this.disposed||e&&(this.chat={...e,error:void 0})}).catch(e=>{this.chat.error=e instanceof Error?e.message:String(e)}).finally(()=>{this.loading=!1,this.notifyListeners()})}setAgent(e){this.agent=e}getState(){return{id:this.chatId,key:this.chat?.key,messages:(this.chat?.messages??[]).filter(e=>!Xl(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,error:this.chat?.error,loading:this.loading,queuedMessages:this.queue}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async upsertMessages(e,t){let n=!1,r;t?r=t:(r=await this.chatStore.lock(this.chatId),n=!0);try{let t=await r.get();(!t.id||!Array.isArray(t.messages))&&(t={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]});let n=[...t.messages];for(let t of e){let e;if(this.serializeMessage){let n=this.serializeMessage(t);if(n===void 0)return;e=n}else e={...t,created_at:new Date().toISOString(),mode:`run`,metadata:t.metadata,id:t.id??crypto.randomUUID()};let r=n.findIndex(t=>t.id===e.id);r===-1?n.push(e):n.splice(r,1,e)}this.chat={...t,updated_at:new Date().toISOString(),messages:n},await r.set(this.chat),this.notifyListeners()}finally{n&&await r.release()}}async deleteMessages(e){let t;try{t=await this.chatStore.lock(this.chatId);let n=await t.get();this.chat.messages=n.messages.filter(t=>!e.includes(t.id)),this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),this.notifyListeners()}finally{t&&await t.release()}}async sendMessages(e){if(this.chat.error){let e=await this.chatStore.lock(this.chatId);try{this.chat={...await e.get(),error:void 0,updated_at:new Date().toISOString()},await e.set(this.chat)}finally{await e.release()}}if(this.status=`idle`,this.notifyListeners(),this.isProcessingQueue){this.queue.push(...e),this.notifyListeners();return}this.queue=e,this.processQueueOrRun()}async start(){this.chat.error=void 0,this.status=`idle`,this.notifyListeners(),this.processQueueOrRun()}async stop(){this.status=`idle`,this.abortController?.abort(),this.notifyListeners()}async processQueueOrRun(){if(!this.agent){this.chat.error=`The agent is not available. Please wait for the build to succeed.`,this.status=`error`,this.queue=[],this.notifyListeners();return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0,this.chat.error=void 0;let e;try{e=await this.chatStore.lock(this.chatId);let t=!0;for(;this.queue.length>0||t;){t=!1;let n=new AbortController;this.abortController=n;let r=[...this.queue];this.queue=[],this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),r.length>0&&await this.upsertMessages(r,e);let i=this.chat.messages;this.filterMessages&&(i=i.filter(this.filterMessages)),i=i.map(e=>({...e,parts:e.parts.map(e=>!ke(e)||e.input!==``?e:{...e,input:{}})}));let a=performance.now(),o=await ql({agent:this.agent,id:this.chatId,signal:n.signal,messages:i}),s=async t=>{let n=t;if(this.serializeMessage){let e=this.serializeMessage(t);if(e===void 0)return;n=e}this.chat.updated_at=new Date().toISOString(),this.chat.messages.push(n),this.streamingMessage=void 0,await e?.set(this.chat)},c=o.getReader();n.signal.addEventListener(`abort`,()=>{c.cancel().catch(()=>{})},{once:!0});let l;try{for(;;){let{done:e,value:t}=await c.read();if(e||n.signal.aborted)break;l||=performance.now()-a,this.streamingMessage&&t.id!==this.streamingMessage.id&&await s(this.streamingMessage);let r={...t,metadata:{...typeof t.metadata==`object`&&t.metadata!==null?t.metadata:{},ttft:l}};this.streamingMessage=this.serializeMessage?this.serializeMessage(r):r,this.notifyListeners()}}finally{c.releaseLock()}this.streamingMessage&&await s(this.streamingMessage)}}catch(e){this.chat.error=e instanceof Error?e.message:String(e)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,this.chat.error?this.status=`error`:this.status=`idle`,e&&(this.chat.updated_at=new Date().toISOString(),await e.set(this.chat),await e.release(),this.notifyListeners())}}stopStreaming(){this.abortController?.abort()}clearQueue(){this.queue=[],this.notifyListeners()}async resetChat(){this.abortController?.abort(),this.resetChatState(),this.notifyListeners();let e;try{e=await this.chatStore.lock(this.chatId),await e.delete()}catch{}finally{if(e)try{await e.release()}catch{}}}dispose(){this.disposed=!0,this.watcher.dispose(),this.listeners.clear(),this.abortController?.abort()}resetChatState(){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.streamingMessage=void 0,this.status=`idle`,this.queue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};function Ql(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a}=e,o=Le(null),[s,c]=q({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[]});K(()=>{o.current&&o.current.dispose();let e=new Zl({chatId:t,chatsDirectory:r,serializeMessage:i,filterMessages:a}),n=e.subscribe(e=>{c(e)});return c(e.getState()),o.current=e,()=>{n(),e.dispose(),o.current=null}},[t,r]),K(()=>{o.current&&o.current.setAgent(n)},[n]);let l=G(async e=>{o.current&&await o.current.sendMessages([e])},[]),u=G(async e=>{o.current&&await o.current.upsertMessages([e])},[]),d=G(()=>{o.current&&o.current.stopStreaming()},[]),f=G(async()=>{o.current&&await o.current.resetChat()},[]),p=G(()=>{o.current&&o.current.clearQueue()},[]),m=G(async e=>{o.current&&await o.current.deleteMessages([e])},[]),h=G(async()=>{o.current&&await o.current.start()},[]);return{...s,sendMessage:l,upsertMessage:u,stopStreaming:d,resetChat:f,clearQueue:p,deleteMessage:m,start:h}}function $l(e){return Se(e,`data`,`devhook.txt`)}function eu(e){return Ce($l(e))}function tu(e){let t=$l(e);if(Ce(t))return Te(t,`utf-8`).trim()}function nu(e){let t=$l(e);if(we(xe(t),{recursive:!0}),Ce(t))return Te(t,`utf-8`);let n=crypto.randomUUID();return De(t,n),n}const ru=(e,t)=>e.json({error:t},400),iu=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}},au=()=>new d,ou=au().get(`/:key`,async e=>{let{key:t,err:n}=iu(e);if(n)return ru(e,n);let r=await e.env.store.get(t);return e.json({value:r},200)}).post(`/:key`,ie(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?ru(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:ru(t,`Value must be a string`):ru(t,`Value is required`)}),async e=>{let{key:t,err:n}=iu(e);if(n)return ru(e,n);let{value:r}=e.req.valid(`json`);return await e.env.store.set(t,r),e.body(null,204)}).delete(`/:key`,async e=>{let{key:t,err:n}=iu(e);return n?ru(e,n):(await e.env.store.delete(t),e.body(null,204))}).get(`/`,async e=>{let{cursor:t,limit:n,prefix:r}=e.req.query(),{entries:i,cursor:a}=await e.env.store.list(r,{cursor:t?String(t):void 0,limit:n?Number(n):100});return e.json({entries:i,cursor:a})}),su=e=>{let t=e.req.param(`key`);return t?t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}:{key:t,err:`Key is required`}},cu=ie(`param`,e=>({id:e.id})),lu=au().post(`/:key`,async e=>{let{key:t,err:n}=su(e);return n?ru(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,cu,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,cu,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.getMessages(t),200)}).post(`/:id/sendMessages`,ie(`json`,e=>({id:e.id,messages:e.messages,options:e.options})),async e=>{let{id:t,messages:n,options:r}=e.req.valid(`json`);return t?(await e.env.chat.sendMessages(t,n,r),e.body(null,204)):ru(e,`ID is required`)}).delete(`/:id/messages`,cu,ie(`query`,e=>(typeof e.message==`string`&&(e.message=[e.message]),{messages:e.message})),async e=>{let{id:t}=e.req.valid(`param`),{messages:n}=e.req.valid(`query`);return await e.env.chat.deleteMessages(t,n),e.body(null,204)}).post(`/:id/start`,cu,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,cu,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,cu,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),uu=au().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),du=new d().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,ou).route(`/chat`,lu).route(`/otlp`,uu);var fu=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function pu(e){return typeof e==`string`&&fu.test(e)}var mu=pu;function hu(e){if(!mu(e))throw TypeError(`Invalid UUID`);let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,t&255,(t=parseInt(e.slice(9,13),16))>>>8,t&255,(t=parseInt(e.slice(14,18),16))>>>8,t&255,(t=parseInt(e.slice(19,23),16))>>>8,t&255,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255)}var gu=hu;const _u=[];for(let e=0;e<256;++e)_u.push((e+256).toString(16).slice(1));function vu(e,t=0){return(_u[e[t+0]]+_u[e[t+1]]+_u[e[t+2]]+_u[e[t+3]]+`-`+_u[e[t+4]]+_u[e[t+5]]+`-`+_u[e[t+6]]+_u[e[t+7]]+`-`+_u[e[t+8]]+_u[e[t+9]]+`-`+_u[e[t+10]]+_u[e[t+11]]+_u[e[t+12]]+_u[e[t+13]]+_u[e[t+14]]+_u[e[t+15]]).toLowerCase()}function yu(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t}function bu(e,t,n,r,i,a){let o=typeof n==`string`?yu(n):n,s=typeof r==`string`?gu(r):r;if(typeof r==`string`&&(r=gu(r)),r?.length!==16)throw TypeError(`Namespace must be array-like (16 iterable integer values, 0-255)`);let c=new Uint8Array(16+o.length);if(c.set(s),c.set(o,s.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,i){a||=0;for(let e=0;e<16;++e)i[a+e]=c[e];return i}return vu(c)}function xu(e){return Array.isArray(e)?e=Buffer.from(e):typeof e==`string`&&(e=Buffer.from(e,`utf8`)),ye(`sha1`).update(e).digest()}var Su=xu;function Cu(e,t,n,r){return bu(80,Su,e,t,n,r)}Cu.DNS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,Cu.URL=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;var wu=Cu;function Tu(e){let t=Ve(e.dataDirectory,`chats`),n={},r=Ve(e.dataDirectory,`storage.json`);H.existsSync(r)&&(n=JSON.parse(H.readFileSync(r,`utf-8`)));let i=new Map,a=n=>{let r=i.get(n);return r||(r=new Zl({chatId:n,chatsDirectory:t}),i.set(n,r)),r.setAgent(e.getAgent()),r},o={async upsert(e){let t=wu(JSON.stringify(e),wu.URL),n=a(t).getState(),r=n.messages.length===0&&!n.created_at;return{id:n.id,created:r,createdAt:n.created_at??new Date().toISOString(),key:e}},async get(e){let t=a(e).getState();return{id:t.id,createdAt:t.created_at??new Date().toISOString()}},async getMessages(e){return a(e).getState().messages},async sendMessages(e,t,n){let r=a(e),i=t.map(e=>Yl(e,`run`));if(n?.behavior===`append`){await r.upsertMessages(i);return}if(n?.behavior===`interrupt`){await r.sendMessages(i);return}await r.sendMessages(i)},async deleteMessages(e,t){await a(e).deleteMessages(t)},async start(e){await a(e).start()},async stop(e){await a(e).stop()},async delete(e){await a(e).resetChat()}},s={get(e){return Promise.resolve(n[e])},set(e,t){return n[e]=t,H.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},delete(e){return delete n[e],H.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},list(e,t){let r=Math.min(t?.limit??100,1e3),i=t?.cursor,a=Object.keys(n).filter(t=>t.startsWith(e??``)).sort(),o=0;if(i){let e=a.indexOf(i);e!==-1&&(o=e+1)}let s=a.slice(o,o+r),c=o+r<a.length?s[s.length-1]:void 0;return Promise.resolve({entries:s.map(e=>({key:e})),cursor:c})}},c=be(O(e=>du.fetch(e,{chat:o,store:s})));c.listen(e.port??0);let l=Gl(t,`id`);return{url:`http://127.0.0.1:${c.address().port}`,chatsDirectory:t,getChatManager:a,listChats:()=>l.list(),dispose:()=>{for(let e of i.values())e.dispose();i.clear(),l.dispose(),c.close()}}}function Eu({agent:e,capabilities:t,messages:n}){let[r,i]=q(void 0),[a,o]=q(!0),[s,c]=q(void 0),l=Le(s);K(()=>{l.current=s},[s]);let[u,d]=q(()=>M(n));K(()=>{d(e=>{let t=M(n);return JSON.stringify(t)===JSON.stringify(e)?e:t})},[n]);let[f,p]=q(void 0),m=G((e,t)=>{if(!l.current)return!1;let n=l.current[e];return n?n.values.some(e=>e.id===t):!1},[]),h=G(e=>{p(t=>{let n={...u,...t,...e};for(let[e,t]of Object.entries(n))m(e,t)||delete n[e];for(let[e,t]of Object.entries(l.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[u,m]);K(()=>{if(!u&&!s){p(void 0);return}h()},[u,s,h]);let g=Le(void 0),_=Le(void 0);K(()=>{e!==_.current&&(_.current=e,c(void 0),p(void 0),i(void 0),o(!0),g.current=void 0)},[e]),K(()=>{if(t&&!t.ui||!e){c(void 0),p(void 0),i(void 0),g.current=void 0;return}let n=f?JSON.stringify(f):``;if(g.current===n){o(!1),i(void 0);return}let r=new AbortController;return o(!0),i(void 0),e.ui(f?{selectedOptions:f}:{},{signal:r.signal}).then(e=>{if(!e){c(void 0);return}r.signal.aborted||(c(t=>JSON.stringify(t)===JSON.stringify(e)?t:e),g.current=n)}).catch(e=>{r.signal.aborted||i(e instanceof Error?e:Error(String(e)))}).finally(()=>{o(!1)}),()=>{r.abort()}},[e,t,f]);let v=G((e,t)=>{h({[e]:t})},[h]);return{schema:s,options:f,setOption:v,loading:a,error:r}}var Du=o(nc());function Ou(e){let t=Le(e.onRequest);K(()=>{t.current=e.onRequest},[e.onRequest]);let[n,r]=q(`disconnected`);return K(()=>{if(e.disabled||!e.id){r(`disconnected`);return}let n=!1,i,a,o=!1,s,c=Ve(e.directory,`data`,`devhook`);return(async()=>{try{s=await Rl(c,{stale:!0,retries:0})}catch(e){if(e&&typeof e==`object`&&`code`in e&&e.code===`ELOCKED`){let e=``;try{let t=Bl(c);t.locked&&t.pid&&(e=` (PID: ${t.pid})`)}catch{}console.error(Du.default.red(`\nError: Another ${Du.default.bold(`blink dev`)} process is already running in this directory${e}.`)),console.error(Du.default.red(`Please stop the other process and try again.
53
+ `)},info:e=>Ac.message(e,{symbol:vc.default.blue(wc)}),success:e=>Ac.message(e,{symbol:vc.default.green(Tc)}),step:e=>Ac.message(e,{symbol:vc.default.green(Sc)}),warn:e=>Ac.message(e,{symbol:vc.default.yellow(Ec)}),warning:e=>Ac.warn(e),error:e=>Ac.message(e,{symbol:vc.default.red(Dc)})};let jc;function Mc(){try{return le.statSync(`/.dockerenv`),!0}catch{return!1}}function Nc(){try{return le.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function Pc(){return jc===void 0&&(jc=Mc()||Nc()),jc}let Fc;const Ic=()=>{try{return le.statSync(`/run/.containerenv`),!0}catch{return!1}};function Lc(){return Fc===void 0&&(Fc=Ic()||Pc()),Fc}const Rc=()=>{if(X.platform!==`linux`)return!1;if(Xe.release().toLowerCase().includes(`microsoft`))return!Lc();try{return le.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!Lc():!1}catch{return!1}};var zc=X.env.__IS_WSL_TEST__?Rc:Rc();const Bc=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await Je.access(n,Ye.F_OK),r=!0}catch{}if(!r)return e;let i=await Je.readFile(n,{encoding:`utf8`}),a=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(i);return a?(t=a.groups.mountPoint.trim(),t=t.endsWith(`/`)?t:`${t}/`,t):e}})(),Vc=async()=>`${await Bc()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Hc=async()=>zc?Vc():`${X.env.SYSTEMROOT||X.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function Uc(e,t,n){let r=n=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0});return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){let e=n();return r(e),e},set(e){r(e)}}),e}const Wc=_e(qe);async function Gc(){if(X.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await Wc(`defaults`,[`read`,`com.apple.LaunchServices/com.apple.launchservices.secure`,`LSHandlers`]);return/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??`com.apple.Safari`}const Kc=_e(qe);async function qc(e,{humanReadableOutput:t=!0,signal:n}={}){if(X.platform!==`darwin`)throw Error(`macOS only`);let r=t?[]:[`-ss`],i={};n&&(i.signal=n);let{stdout:a}=await Kc(`osascript`,[`-e`,e,r],i);return a.trim()}async function Jc(e){return qc(`tell application "Finder" to set app_path to application file id "${e}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}const Yc=_e(qe),Xc={AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:`Edge`,id:`com.microsoft.edge.old`},MSEdgeDHTML:{name:`Edge`,id:`com.microsoft.edge`},MSEdgeHTM:{name:`Edge`,id:`com.microsoft.edge`},"IE.HTTP":{name:`Internet Explorer`,id:`com.microsoft.ie`},FirefoxURL:{name:`Firefox`,id:`org.mozilla.firefox`},ChromeHTML:{name:`Chrome`,id:`com.google.chrome`},BraveHTML:{name:`Brave`,id:`com.brave.Browser`},BraveBHTML:{name:`Brave Beta`,id:`com.brave.Browser.beta`},BraveSSHTM:{name:`Brave Nightly`,id:`com.brave.Browser.nightly`}};var Zc=class extends Error{};async function Qc(e=Yc){let{stdout:t}=await e(`reg`,[`QUERY`,` HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice`,`/v`,`ProgId`]),n=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(t);if(!n)throw new Zc(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=Xc[r];if(!i)throw new Zc(`Unknown browser ID: ${r}`);return i}const $c=_e(qe),el=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function tl(){if(X.platform===`darwin`){let e=await Gc();return{name:await Jc(e),id:e}}if(X.platform===`linux`){let{stdout:e}=await $c(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:el(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(X.platform===`win32`)return Qc();throw Error(`Only macOS, Linux, and Windows are supported`)}const nl=_e(Ke.execFile),rl=ze.dirname(he(import.meta.url)),il=ze.join(rl,`xdg-open`),{platform:al,arch:ol}=X;async function sl(){let e=await Hc(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=V.from(t,`utf16le`).toString(`base64`),{stdout:r}=await nl(e,[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,n],{encoding:`utf8`}),i=r.trim(),a={ChromeHTML:`com.google.chrome`,BraveHTML:`com.brave.Browser`,MSEdgeHTM:`com.microsoft.edge`,FirefoxURL:`org.mozilla.firefox`};return a[i]?{id:a[i]}:{}}const cl=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},ll=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return cl(e.app,t=>ll({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return cl(t,t=>ll({...e,app:{name:t,arguments:n}}));if(t===`browser`||t===`browserPrivate`){let r={"com.google.chrome":`chrome`,"google-chrome.desktop":`chrome`,"com.brave.Browser":`brave`,"org.mozilla.firefox":`firefox`,"firefox.desktop":`firefox`,"com.microsoft.msedge":`edge`,"com.microsoft.edge":`edge`,"com.microsoft.edgemac":`edge`,"microsoft-edge.desktop":`edge`},i={chrome:`--incognito`,brave:`--incognito`,firefox:`--private-window`,edge:`--inPrivate`},a=zc?await sl():await tl();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),ll({...e,app:{name:pl[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,i=[],a={};if(al===`darwin`)r=`open`,e.wait&&i.push(`--wait-apps`),e.background&&i.push(`--background`),e.newInstance&&i.push(`--new`),t&&i.push(`-a`,t);else if(al===`win32`||zc&&!Lc()&&!t){r=await Hc(),i.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),zc||(a.windowsVerbatimArguments=!0);let o=[`Start`];e.wait&&o.push(`-Wait`),t?(o.push(`"\`"${t}\`""`),e.target&&n.push(e.target)):e.target&&o.push(`"${e.target}"`),n.length>0&&(n=n.map(e=>`"\`"${e}\`""`),o.push(`-ArgumentList`,n.join(`,`))),e.target=V.from(o.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!rl||rl===`/`,t=!1;try{await Je.access(il,Ye.X_OK),t=!0}catch{}r=X.versions.electron??(al===`android`||e||!t)?`xdg-open`:il}n.length>0&&i.push(...n),e.wait||(a.stdio=`ignore`,a.detached=!0)}al===`darwin`&&n.length>0&&i.push(`--args`,...n),e.target&&i.push(e.target);let o=Ke.spawn(r,i,a);return e.wait?new Promise((t,n)=>{o.once(`error`,n),o.once(`close`,r=>{if(!e.allowNonzeroExitCode&&r>0){n(Error(`Exited with code ${r}`));return}t(o)})}):(o.unref(),o)},ul=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return ll({...t,target:e})};function dl(e){if(typeof e==`string`||Array.isArray(e))return e;let{[ol]:t}=e;if(!t)throw Error(`${ol} is not supported`);return t}function fl({[al]:e},{wsl:t}){if(t&&zc)return dl(t);if(!e)throw Error(`${al} is not supported`);return dl(e)}const pl={};Uc(pl,`chrome`,()=>fl({darwin:`google chrome`,win32:`chrome`,linux:[`google-chrome`,`google-chrome-stable`,`chromium`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`,x64:[`/mnt/c/Program Files/Google/Chrome/Application/chrome.exe`,`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`]}})),Uc(pl,`brave`,()=>fl({darwin:`brave browser`,win32:`brave`,linux:[`brave-browser`,`brave`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`,x64:[`/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe`,`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`]}})),Uc(pl,`firefox`,()=>fl({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),Uc(pl,`edge`,()=>fl({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),Uc(pl,`browser`,()=>`browser`),Uc(pl,`browserPrivate`,()=>`browserPrivate`);var ml=ul;async function hl(e,t=void 0){try{(await ml(e)).once(`error`,n=>{console.log(ac.default.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))})}catch{console.log(ac.default.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))}}nc();function gl(e){let t=e||yl();if(ue(t)){let e=fe(t,`utf8`);return JSON.parse(e).token}}function _l(e,t){let n=t||yl();ue(Be(n))||de(Be(n),{recursive:!0}),me(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function vl(e){let t=e||yl();ue(t)&&pe(t)}function yl(){let e=qs(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return Ve(e[0],`auth.json`)}function bl(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=q(),[s,c]=q(()=>gl(i)),[l,u]=q(),d=Le(n),f=Le(r);K(()=>{d.current=n,f.current=r},[n,r]);let p=G(async()=>{u(void 0);try{let e=gl(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new ks({baseURL:`https://blink.so`});t.authToken=e;let n={email:(await t.users.me()).email};o(n),d.current?.(n)}catch(e){o(void 0),u(e instanceof Error?e.message:String(e)),d.current?.(void 0)}},[i]),m=G(async()=>{u(void 0);try{let e=new ks,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();_l(t,i),c(t);let r={email:n.email};return o(r),d.current?.(r),r}catch(e){let t=e instanceof Error?e.message:String(e);throw u(t),e}},[i]),h=G(()=>{vl(i),c(void 0),o(void 0),u(void 0),d.current?.(void 0)},[i]);return K(()=>{t&&p()},[t,p]),{user:a,token:s,error:l,login:m,logout:h}}function xl(e){let{directory:t,onBuildStart:n,onBuildSuccess:r,onBuildError:i}=typeof e==`string`?{directory:e}:e,a=Ie(()=>oe(t),[t]),[o,s]=q(void 0),[c,l]=q(void 0),[u,d]=q(`building`),f=Le(n),p=Le(r),m=Le(i);return K(()=>{f.current=n,p.current=r,m.current=i},[n,r,i]),K(()=>{let e=new AbortController;return a.build({cwd:t,entry:a.entry,outdir:a.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{d(`building`),s(void 0),l(void 0),f.current?.()},onResult:e=>{`error`in e?(s(e.error),d(`error`),m.current?.(e.error)):(l(e),d(`success`),p.current?.(e))}}).catch(e=>{console.log(`error`,e),d(`error`),s(e),m.current?.(e)}),()=>{e.abort()}},[t]),Ie(()=>({error:o,status:u,result:c,entry:a.entry,outdir:a.outdir}),[o,u,c,a.entry,a.outdir])}function Sl(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function Cl(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const wl=/^\.+(\\|\/)|^\.+$/,Tl=/[. ]+$/,El=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,Dl=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,Ol=e=>e===`‍`,kl=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,Al=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let jl;function Ml(){return jl??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),jl}function Nl(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(Sl().test(n)||[...n].some(e=>Dl.test(e)&&!Ol(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(Al,` `),n.length>0&&(e=e.replaceAll(kl,`$1`)),e=e.replace(Tl,``),e=e.replace(wl,n),e=e.replace(Sl(),n),e=e.replaceAll(El,e=>Ol(e)?e:n),e.length===0&&(e=n),e=Cl().test(e)?e+n:e;let r=typeof t.maxLength==`number`?t.maxLength:100;if(e.length>r){let t=e.lastIndexOf(`.`);if(t===-1)e=Pl(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=Pl(n,a)+i}}return e}function Pl(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of Ml().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function Fl(e){return`${e}.lock`}function Il(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function Ll(e,t={}){let n=Fl(e),r=process.pid.toString();try{return H.writeFileSync(n,r,{flag:`wx`}),!0}catch(r){if(r.code!==`EEXIST`)throw r;if(t.stale===0)return!1;let i;try{i=parseInt(H.readFileSync(n,`utf8`),10)}catch{return H.unlinkSync(n),Ll(e,{...t,stale:0})}if(!Il(i))try{return H.unlinkSync(n),Ll(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return Ll(e,{...t,stale:0});throw n}return!1}}async function Rl(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=Re.resolve(e),i=0;for(;i<=n.retries;){if(Ll(r,n))return()=>zl(r);i<n.retries&&await new Promise(e=>setTimeout(e,n.retryInterval)),i++}let a=Error(`Lock file is already being held`);throw a.code=`ELOCKED`,a.file=r,a}function zl(e){let t=Re.resolve(e),n=Fl(t);try{if(parseInt(H.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}H.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function Bl(e){let t=Re.resolve(e),n=Fl(t);try{if(!H.existsSync(n))return{locked:!1};let e=H.readFileSync(n,`utf8`),t=parseInt(e,10);return Il(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const Vl=e=>{H.mkdirSync(e,{recursive:!0})},Hl=e=>{try{H.fdatasyncSync(e)}catch{}try{H.closeSync(e)}catch{}},Ul=e=>{try{let t=H.openSync(e,`r`);try{H.fsyncSync(t)}finally{H.closeSync(t)}}catch{}},Wl=(e,t)=>{let n=Re.dirname(e);Vl(n);let r=Re.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=H.openSync(r,`w`),H.writeFileSync(i,t,`utf-8`),Hl(i),i=void 0,H.renameSync(r,e),Ul(e),Ul(n)}catch(e){if(i!==void 0)try{H.closeSync(i)}catch{}try{H.rmSync(r,{force:!0})}catch{}throw e}},Gl=(e,t)=>{let n=new Map,r,i=e=>{if(H.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(H.readFileSync(e,`utf-8`))},a=(e,t)=>{Wl(e,JSON.stringify(t,null,2))},o=async()=>{if(r)throw Error(`Index is already locked`);let t=Re.join(e,`index.json`);Vl(e),H.existsSync(t)||H.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await Rl(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},s=async()=>{let t=Re.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},c=async t=>{let n=Re.join(e,`index.json`);a(n,t)},l=async t=>{let n=(await s()).ids[t];if(n)return Re.join(e,n)},u=async t=>{let n=(await s()).ids[t];if(!n)return;let r=Re.join(e,n);if(H.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(H.readFileSync(r,`utf-8`))},d=async n=>{let r=n[t],i=String(r),l=Nl(i,{replacement:`_`})+`.json`,u=await o();try{let t=await s();t.ids[i]=l,t.current=i;let r=Re.join(e,l);a(r,n),await c(t)}finally{await u()}};return{async get(e){return await u(e)},async list(){if(!H.statSync(e,{throwIfNoEntry:!1}))return[];let t=await s(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=Re.join(e,i),a=H.statSync(t,{throwIfNoEntry:!1});if(!a)continue;let o=Bl(t);n.push({key:r,locked:o.locked,pid:o.pid,mtime:a.mtimeMs})}return n.sort((e,t)=>t.mtime-e.mtime),n},async lock(r,i){if(n.has(r))throw Error(`Key "${r}" is already locked in this process`);let a=await l(r);if(!a){let t=Nl(r,{replacement:`_`})+`.json`,n=await o();try{let n=await s();n.ids[r]=t;let i=Re.join(e,t);Vl(e),H.writeFileSync(i,JSON.stringify({}),`utf-8`),await c(n),a=i}finally{await n()}}if(i?.force){let e=Bl(a);if(e.locked&&e.pid&&e.pid!==process.pid)try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,100))}catch(t){t.code!==`ESRCH`&&console.warn(`Failed to kill process ${e.pid}:`,t.message)}}let f=await Rl(a,{stale:!0,retries:i?.force?10:5,retryInterval:(i?.force,100)});return n.set(r,()=>Promise.resolve(f())),{async get(){let e=await u(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await d(e)},async update(e){let n=await u(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await d({...n,...e})},async delete(){let t=await o();try{let t=await s(),n=t.ids[r];if(n){delete t.ids[r],t.current===r&&(t.current=void 0),await c(t);let i=Re.join(e,n);try{H.rmSync(i,{force:!0}),Ul(e)}catch{}}}finally{await t()}},async release(){try{f()}finally{n.delete(r)}}}},dispose(){n.clear()}}},Kl=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,a,o,s=new Map,c=new Map,l=Re.join(e,`index.json`),u=()=>{try{if(!H.statSync(l,{throwIfNoEntry:!1}))return{ids:{}};let e=H.readFileSync(l,`utf-8`);return{ids:JSON.parse(e).ids??{}}}catch{return{ids:{}}}},d=(e,t,n,r)=>{for(let a of i)try{a({key:e,value:t,locked:n,pid:r})}catch(e){console.error(`Error in onChange callback:`,e)}},f=(t,n,r=!1)=>{let i=Re.join(e,n);try{let e=H.statSync(i,{throwIfNoEntry:!1}),a=c.get(n);if(!e){a&&(c.delete(n),d(t,void 0,!1));return}let o=e.mtimeMs,s=a?{locked:a.locked,pid:a.pid}:{locked:!1,pid:void 0};if((r||!a)&&(s=Bl(i)),!a||a.mtime!==o||a.locked!==s.locked||a.pid!==s.pid){let e;e=!a||a.mtime!==o?JSON.parse(H.readFileSync(i,`utf-8`)):a.cachedValue,c.set(n,{mtime:o,key:t,locked:s.locked,pid:s.pid,cachedValue:e}),d(t,e,s.locked,s.pid)}}catch{}},p=()=>{try{let e=u(),t=new Set(Object.keys(e.ids));for(let[t,n]of Object.entries(e.ids))f(t,n,!0);for(let[e,n]of c.entries())t.has(n.key)||(c.delete(e),d(n.key,void 0,!1))}catch{}},m=(e,t,n=!1)=>{let i=s.get(e);i&&clearTimeout(i),s.set(e,setTimeout(()=>{s.delete(e),f(e,t,n)},r))},h=()=>{if(a)return;try{H.mkdirSync(e,{recursive:!0})}catch{}a=H.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){p();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=u(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&f(r,e,!0);return}let n=u(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&m(r,t,!1)});let t=()=>{p(),o=setTimeout(t,n)};p(),o=setTimeout(t,n)};return{onChange(e){return i.size===0&&h(),i.add(e),()=>{if(i.delete(e),i.size===0){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),c.clear()}}},dispose(){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),i.clear(),c.clear()}}};async function ql({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=Jl}){n=[...n];let a=new TransformStream,o=a.writable.getWriter(),s=async()=>{let a;try{let c=await t.chat({messages:n,id:e},{signal:r}),l=Ae({message:{id:crypto.randomUUID(),role:`assistant`,parts:[],metadata:{}},stream:c,onError:e=>{e instanceof Error&&e.name===`AbortError`||o.abort(e)}});for await(let e of l)o.write(e),a=e;if(a&&i(a)){n.push(a),await s();return}await o.close()}catch(e){if(e?.name===`AbortError`||r?.aborted)return;await o.abort(e)}finally{await o.close()}};return s().catch(e=>{o.abort(e)}),a.readable}const Jl=e=>{if(e.role!==`assistant`)return!1;let t=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),n=e.parts.slice(t+1).filter(ke);return n.length===0||n.some(e=>ee(e.output)&&e.output.outcome===`pending`)?!1:n.every(e=>e.state.startsWith(`output-`))},Yl=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function Xl(e){return typeof e==`object`&&e?.__blink_internal!==void 0}var Zl=class{chatId;agent;chatStore;serializeMessage;filterMessages;chat;loading=!1;streamingMessage;status=`idle`;queue=[];abortController;isProcessingQueue=!1;listeners=new Set;watcher;disposed=!1;constructor(e){this.chatId=e.chatId??`00000000-0000-0000-0000-000000000000`,this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.loading=!0,this.chatStore=Gl(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.watcher=Kl(e.chatsDirectory,{pollInterval:1e3,debounce:50}),this.watcher.onChange(e=>{if(e.key!==this.chatId||this.isProcessingQueue)return;if(!e.value){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.status=`idle`,this.streamingMessage=void 0,this.notifyListeners();return}if(this.chat.updated_at===e.value?.updated_at)return;let t=e.value,n=e.value?.error?`error`:`idle`;e.locked&&(n=`streaming`);let r=this.chat.updated_at!==t?.updated_at||this.status!==n;this.chat={...t,error:void 0},this.streamingMessage=void 0,this.status=n,r&&this.notifyListeners()}),this.chatStore.get(this.chatId).then(e=>{this.disposed||e&&(this.chat={...e,error:void 0})}).catch(e=>{this.chat.error=e instanceof Error?e.message:String(e)}).finally(()=>{this.loading=!1,this.notifyListeners()})}setAgent(e){this.agent=e}getState(){return{id:this.chatId,key:this.chat?.key,messages:(this.chat?.messages??[]).filter(e=>!Xl(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,error:this.chat?.error,loading:this.loading,queuedMessages:this.queue}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async upsertMessages(e,t){let n=!1,r;t?r=t:(r=await this.chatStore.lock(this.chatId),n=!0);try{let t=await r.get();(!t.id||!Array.isArray(t.messages))&&(t={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]});let n=[...t.messages];for(let t of e){let e;if(this.serializeMessage){let n=this.serializeMessage(t);if(n===void 0)return;e=n}else e={...t,created_at:new Date().toISOString(),mode:`run`,metadata:t.metadata,id:t.id??crypto.randomUUID()};let r=n.findIndex(t=>t.id===e.id);r===-1?n.push(e):n.splice(r,1,e)}this.chat={...t,updated_at:new Date().toISOString(),messages:n},await r.set(this.chat),this.notifyListeners()}finally{n&&await r.release()}}async deleteMessages(e){let t;try{t=await this.chatStore.lock(this.chatId);let n=await t.get();this.chat.messages=n.messages.filter(t=>!e.includes(t.id)),this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),this.notifyListeners()}finally{t&&await t.release()}}async sendMessages(e){if(this.chat.error){let e=await this.chatStore.lock(this.chatId);try{this.chat={...await e.get(),error:void 0,updated_at:new Date().toISOString()},await e.set(this.chat)}finally{await e.release()}}if(this.status=`idle`,this.notifyListeners(),this.isProcessingQueue){this.queue.push(...e),this.notifyListeners();return}this.queue=e,this.processQueueOrRun()}async start(){this.chat.error=void 0,this.status=`idle`,this.notifyListeners(),this.processQueueOrRun()}async stop(){this.status=`idle`,this.abortController?.abort(),this.notifyListeners()}async processQueueOrRun(){if(!this.agent){this.chat.error=`The agent is not available. Please wait for the build to succeed.`,this.status=`error`,this.queue=[],this.notifyListeners();return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0,this.chat.error=void 0;let e;try{e=await this.chatStore.lock(this.chatId);let t=!0;for(;this.queue.length>0||t;){t=!1;let n=new AbortController;this.abortController=n;let r=[...this.queue];this.queue=[],this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),r.length>0&&await this.upsertMessages(r,e);let i=this.chat.messages;this.filterMessages&&(i=i.filter(this.filterMessages)),i=i.map(e=>({...e,parts:e.parts.map(e=>!ke(e)||e.input!==``?e:{...e,input:{}})}));let a=performance.now(),o=await ql({agent:this.agent,id:this.chatId,signal:n.signal,messages:i}),s=async t=>{let n=t;if(this.serializeMessage){let e=this.serializeMessage(t);if(e===void 0)return;n=e}this.chat.updated_at=new Date().toISOString(),this.chat.messages.push(n),this.streamingMessage=void 0,await e?.set(this.chat)},c=o.getReader();n.signal.addEventListener(`abort`,()=>{c.cancel().catch(()=>{})},{once:!0});let l;try{for(;;){let{done:e,value:t}=await c.read();if(e||n.signal.aborted)break;l||=performance.now()-a,this.streamingMessage&&t.id!==this.streamingMessage.id&&await s(this.streamingMessage);let r={...t,metadata:{...typeof t.metadata==`object`&&t.metadata!==null?t.metadata:{},ttft:l}};this.streamingMessage=this.serializeMessage?this.serializeMessage(r):r,this.notifyListeners()}}finally{c.releaseLock()}this.streamingMessage&&await s(this.streamingMessage)}}catch(e){this.chat.error=e instanceof Error?e.message:String(e)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,this.chat.error?this.status=`error`:this.status=`idle`,e&&(this.chat.updated_at=new Date().toISOString(),await e.set(this.chat),await e.release(),this.notifyListeners())}}stopStreaming(){this.abortController?.abort()}clearQueue(){this.queue=[],this.notifyListeners()}async resetChat(){this.abortController?.abort(),this.resetChatState(),this.notifyListeners();let e;try{e=await this.chatStore.lock(this.chatId),await e.delete()}catch{}finally{if(e)try{await e.release()}catch{}}}dispose(){this.disposed=!0,this.watcher.dispose(),this.listeners.clear(),this.abortController?.abort()}resetChatState(){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.streamingMessage=void 0,this.status=`idle`,this.queue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};function Ql(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a}=e,o=Le(null),[s,c]=q({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[]});K(()=>{o.current&&o.current.dispose();let e=new Zl({chatId:t,chatsDirectory:r,serializeMessage:i,filterMessages:a}),n=e.subscribe(e=>{c(e)});return c(e.getState()),o.current=e,()=>{n(),e.dispose(),o.current=null}},[t,r]),K(()=>{o.current&&o.current.setAgent(n)},[n]);let l=G(async e=>{o.current&&await o.current.sendMessages([e])},[]),u=G(async e=>{o.current&&await o.current.upsertMessages([e])},[]),d=G(()=>{o.current&&o.current.stopStreaming()},[]),f=G(async()=>{o.current&&await o.current.resetChat()},[]),p=G(()=>{o.current&&o.current.clearQueue()},[]),m=G(async e=>{o.current&&await o.current.deleteMessages([e])},[]),h=G(async()=>{o.current&&await o.current.start()},[]);return{...s,sendMessage:l,upsertMessage:u,stopStreaming:d,resetChat:f,clearQueue:p,deleteMessage:m,start:h}}function $l(e){return Se(e,`.blink`,`devhook.txt`)}function eu(e){return Ce($l(e))}function tu(e){let t=$l(e);if(Ce(t))return Te(t,`utf-8`).trim()}function nu(e){let t=$l(e);if(we(xe(t),{recursive:!0}),Ce(t))return Te(t,`utf-8`);let n=crypto.randomUUID();return De(t,n),n}const ru=(e,t)=>e.json({error:t},400),iu=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}},au=()=>new d,ou=au().get(`/:key`,async e=>{let{key:t,err:n}=iu(e);if(n)return ru(e,n);let r=await e.env.store.get(t);return e.json({value:r},200)}).post(`/:key`,ie(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?ru(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:ru(t,`Value must be a string`):ru(t,`Value is required`)}),async e=>{let{key:t,err:n}=iu(e);if(n)return ru(e,n);let{value:r}=e.req.valid(`json`);return await e.env.store.set(t,r),e.body(null,204)}).delete(`/:key`,async e=>{let{key:t,err:n}=iu(e);return n?ru(e,n):(await e.env.store.delete(t),e.body(null,204))}).get(`/`,async e=>{let{cursor:t,limit:n,prefix:r}=e.req.query(),{entries:i,cursor:a}=await e.env.store.list(r,{cursor:t?String(t):void 0,limit:n?Number(n):100});return e.json({entries:i,cursor:a})}),su=e=>{let t=e.req.param(`key`);return t?t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}:{key:t,err:`Key is required`}},cu=ie(`param`,e=>({id:e.id})),lu=au().post(`/:key`,async e=>{let{key:t,err:n}=su(e);return n?ru(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,cu,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,cu,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.getMessages(t),200)}).post(`/:id/sendMessages`,ie(`json`,e=>({id:e.id,messages:e.messages,options:e.options})),async e=>{let{id:t,messages:n,options:r}=e.req.valid(`json`);return t?(await e.env.chat.sendMessages(t,n,r),e.body(null,204)):ru(e,`ID is required`)}).delete(`/:id/messages`,cu,ie(`query`,e=>(typeof e.message==`string`&&(e.message=[e.message]),{messages:e.message})),async e=>{let{id:t}=e.req.valid(`param`),{messages:n}=e.req.valid(`query`);return await e.env.chat.deleteMessages(t,n),e.body(null,204)}).post(`/:id/start`,cu,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,cu,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,cu,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),uu=au().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),du=new d().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,ou).route(`/chat`,lu).route(`/otlp`,uu);var fu=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function pu(e){return typeof e==`string`&&fu.test(e)}var mu=pu;function hu(e){if(!mu(e))throw TypeError(`Invalid UUID`);let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,t&255,(t=parseInt(e.slice(9,13),16))>>>8,t&255,(t=parseInt(e.slice(14,18),16))>>>8,t&255,(t=parseInt(e.slice(19,23),16))>>>8,t&255,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255)}var gu=hu;const _u=[];for(let e=0;e<256;++e)_u.push((e+256).toString(16).slice(1));function vu(e,t=0){return(_u[e[t+0]]+_u[e[t+1]]+_u[e[t+2]]+_u[e[t+3]]+`-`+_u[e[t+4]]+_u[e[t+5]]+`-`+_u[e[t+6]]+_u[e[t+7]]+`-`+_u[e[t+8]]+_u[e[t+9]]+`-`+_u[e[t+10]]+_u[e[t+11]]+_u[e[t+12]]+_u[e[t+13]]+_u[e[t+14]]+_u[e[t+15]]).toLowerCase()}function yu(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t}function bu(e,t,n,r,i,a){let o=typeof n==`string`?yu(n):n,s=typeof r==`string`?gu(r):r;if(typeof r==`string`&&(r=gu(r)),r?.length!==16)throw TypeError(`Namespace must be array-like (16 iterable integer values, 0-255)`);let c=new Uint8Array(16+o.length);if(c.set(s),c.set(o,s.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,i){a||=0;for(let e=0;e<16;++e)i[a+e]=c[e];return i}return vu(c)}function xu(e){return Array.isArray(e)?e=Buffer.from(e):typeof e==`string`&&(e=Buffer.from(e,`utf8`)),ye(`sha1`).update(e).digest()}var Su=xu;function Cu(e,t,n,r){return bu(80,Su,e,t,n,r)}Cu.DNS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,Cu.URL=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;var wu=Cu;function Tu(e){let t=Ve(e.dataDirectory,`chats`),n={},r=Ve(e.dataDirectory,`storage.json`);H.existsSync(r)&&(n=JSON.parse(H.readFileSync(r,`utf-8`)));let i=new Map,a=n=>{let r=i.get(n);return r||(r=new Zl({chatId:n,chatsDirectory:t}),i.set(n,r)),r.setAgent(e.getAgent()),r},o={async upsert(e){let t=wu(JSON.stringify(e),wu.URL),n=a(t).getState(),r=n.messages.length===0&&!n.created_at;return{id:n.id,created:r,createdAt:n.created_at??new Date().toISOString(),key:e}},async get(e){let t=a(e).getState();return{id:t.id,createdAt:t.created_at??new Date().toISOString()}},async getMessages(e){return a(e).getState().messages},async sendMessages(e,t,n){let r=a(e),i=t.map(e=>Yl(e,`run`));if(n?.behavior===`append`){await r.upsertMessages(i);return}if(n?.behavior===`interrupt`){await r.sendMessages(i);return}await r.sendMessages(i)},async deleteMessages(e,t){await a(e).deleteMessages(t)},async start(e){await a(e).start()},async stop(e){await a(e).stop()},async delete(e){await a(e).resetChat()}},s={get(e){return Promise.resolve(n[e])},set(e,t){return n[e]=t,H.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},delete(e){return delete n[e],H.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},list(e,t){let r=Math.min(t?.limit??100,1e3),i=t?.cursor,a=Object.keys(n).filter(t=>t.startsWith(e??``)).sort(),o=0;if(i){let e=a.indexOf(i);e!==-1&&(o=e+1)}let s=a.slice(o,o+r),c=o+r<a.length?s[s.length-1]:void 0;return Promise.resolve({entries:s.map(e=>({key:e})),cursor:c})}},c=be(O(e=>du.fetch(e,{chat:o,store:s})));c.listen(e.port??0);let l=Gl(t,`id`);return{url:`http://127.0.0.1:${c.address().port}`,chatsDirectory:t,getChatManager:a,listChats:()=>l.list(),dispose:()=>{for(let e of i.values())e.dispose();i.clear(),l.dispose(),c.close()}}}function Eu({agent:e,capabilities:t,messages:n}){let[r,i]=q(void 0),[a,o]=q(!0),[s,c]=q(void 0),l=Le(s);K(()=>{l.current=s},[s]);let[u,d]=q(()=>M(n));K(()=>{d(e=>{let t=M(n);return JSON.stringify(t)===JSON.stringify(e)?e:t})},[n]);let[f,p]=q(void 0),m=G((e,t)=>{if(!l.current)return!1;let n=l.current[e];return n?n.values.some(e=>e.id===t):!1},[]),h=G(e=>{p(t=>{let n={...u,...t,...e};for(let[e,t]of Object.entries(n))m(e,t)||delete n[e];for(let[e,t]of Object.entries(l.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[u,m]);K(()=>{if(!u&&!s){p(void 0);return}h()},[u,s,h]);let g=Le(void 0),_=Le(void 0);K(()=>{e!==_.current&&(_.current=e,c(void 0),p(void 0),i(void 0),o(!0),g.current=void 0)},[e]),K(()=>{if(t&&!t.ui||!e){c(void 0),p(void 0),i(void 0),g.current=void 0;return}let n=f?JSON.stringify(f):``;if(g.current===n){o(!1),i(void 0);return}let r=new AbortController;return o(!0),i(void 0),e.ui(f?{selectedOptions:f}:{},{signal:r.signal}).then(e=>{if(!e){c(void 0);return}r.signal.aborted||(c(t=>JSON.stringify(t)===JSON.stringify(e)?t:e),g.current=n)}).catch(e=>{r.signal.aborted||i(e instanceof Error?e:Error(String(e)))}).finally(()=>{o(!1)}),()=>{r.abort()}},[e,t,f]);let v=G((e,t)=>{h({[e]:t})},[h]);return{schema:s,options:f,setOption:v,loading:a,error:r}}var Du=o(nc());function Ou(e){let t=Le(e.onRequest);K(()=>{t.current=e.onRequest},[e.onRequest]);let[n,r]=q(`disconnected`);return K(()=>{if(e.disabled||!e.id){r(`disconnected`);return}let n=!1,i,a,o=!1,s,c=Ve(e.directory,`.blink`,`devhook`);return(async()=>{try{s=await Rl(c,{stale:!0,retries:0})}catch(e){if(e&&typeof e==`object`&&`code`in e&&e.code===`ELOCKED`){let e=``;try{let t=Bl(c);t.locked&&t.pid&&(e=` (PID: ${t.pid})`)}catch{}console.error(Du.default.red(`\nError: Another ${Du.default.bold(`blink dev`)} process is already running in this directory${e}.`)),console.error(Du.default.red(`Please stop the other process and try again.
54
54
  `)),process.exit(1)}let t=e&&typeof e==`object`&&`message`in e?String(e.message):String(e);console.warn(Du.default.yellow(`\nWarning: Failed to acquire devhook lock: ${t}`)),console.warn(Du.default.yellow(`Continuing without lock. Multiple ${Du.default.bold(`blink dev`)} processes may conflict with each other.\n`))}let l=()=>{if(!(n||o)){if(o=!0,i){try{i.dispose()}catch{}i=void 0}i=new ks({baseURL:`https://blink.so`}).devhook.listen({id:e.id,onRequest:async e=>t.current(e),onConnect:()=>{o=!1,r(`connected`)},onDisconnect:()=>{o=!1,r(`disconnected`),!n&&!a&&(a=setTimeout(()=>{a=void 0,l()},2e3))},onError:e=>{o=!1,r(`error`),!n&&!a&&(a=setTimeout(()=>{a=void 0,l()},2e3))}})}};l()})(),()=>{if(n=!0,a&&=(clearTimeout(a),void 0),i){try{i.dispose()}catch{}i=void 0}if(s)try{s()}catch(e){console.warn(`Failed to release devhook lock:`,e)}}},[e.disabled,e.directory]),{id:e.id,url:e.id?`https://${e.id}.blink.host`:void 0,status:n}}var ku=e(((e,t)=>{t.exports={name:`dotenv`,version:`17.2.3`,description:`Loads environment variables from .env file`,main:`lib/main.js`,types:`lib/main.d.ts`,exports:{".":{types:`./lib/main.d.ts`,require:`./lib/main.js`,default:`./lib/main.js`},"./config":`./config.js`,"./config.js":`./config.js`,"./lib/env-options":`./lib/env-options.js`,"./lib/env-options.js":`./lib/env-options.js`,"./lib/cli-options":`./lib/cli-options.js`,"./lib/cli-options.js":`./lib/cli-options.js`,"./package.json":`./package.json`},scripts:{"dts-check":`tsc --project tests/types/tsconfig.json`,lint:`standard`,pretest:`npm run lint && npm run dts-check`,test:`tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000`,"test:coverage":`tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov`,prerelease:`npm test`,release:`standard-version`},repository:{type:`git`,url:`git://github.com/motdotla/dotenv.git`},homepage:`https://github.com/motdotla/dotenv#readme`,funding:`https://dotenvx.com`,keywords:[`dotenv`,`env`,`.env`,`environment`,`variables`,`config`,`settings`],readmeFilename:`README.md`,license:`BSD-2-Clause`,devDependencies:{"@types/node":`^18.11.3`,decache:`^4.6.2`,sinon:`^14.0.1`,standard:`^17.0.0`,"standard-version":`^9.5.0`,tap:`^19.2.0`,typescript:`^4.8.4`},engines:{node:`>=12`},browser:{fs:!1}}})),Au=o(e(((e,t)=>{let n=i(`fs`),r=i(`path`),a=i(`os`),o=i(`crypto`),s=ku().version,c=[`🔐 encrypt with Dotenvx: https://dotenvx.com`,`🔐 prevent committing .env to code: https://dotenvx.com/precommit`,`🔐 prevent building .env in docker: https://dotenvx.com/prebuild`,`📡 add observability to secrets: https://dotenvx.com/ops`,`👥 sync secrets across teammates & machines: https://dotenvx.com/ops`,`🗂️ backup and recover secrets: https://dotenvx.com/ops`,`✅ audit secrets and track compliance: https://dotenvx.com/ops`,`🔄 add secrets lifecycle management: https://dotenvx.com/ops`,`🔑 add access controls to secrets: https://dotenvx.com/ops`,"🛠️ run anywhere with `dotenvx run -- yourcommand`",`⚙️ specify custom .env file path with { path: '/custom/path/.env' }`,`⚙️ enable debug logging with { debug: true }`,`⚙️ override existing env vars with { override: true }`,`⚙️ suppress all logs with { quiet: true }`,`⚙️ write to custom object with { processEnv: myObject }`,`⚙️ load multiple .env files with { path: ['.env.local', '.env'] }`];function l(){return c[Math.floor(Math.random()*c.length)]}function u(e){return typeof e==`string`?![`false`,`0`,`no`,`off`,``].includes(e.toLowerCase()):!!e}function d(){return process.stdout.isTTY}function f(e){return d()?`\x1b[2m${e}\x1b[0m`:e}let p=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function m(e){let t={},n=e.toString();n=n.replace(/\r\n?/gm,`
55
55
  `);let r;for(;(r=p.exec(n))!=null;){let e=r[1],n=r[2]||``;n=n.trim();let i=n[0];n=n.replace(/^(['"`])([\s\S]*)\1$/gm,`$2`),i===`"`&&(n=n.replace(/\\n/g,`
56
56
  `),n=n.replace(/\\r/g,`\r`)),t[e]=n}return t}function h(e){e||={};let t=x(e);e.path=t;let n=O.configDotenv(e);if(!n.parsed){let e=Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code=`MISSING_DATA`,e}let r=y(e).split(`,`),i=r.length,a;for(let e=0;e<i;e++)try{let t=r[e].trim(),i=b(n,t);a=O.decrypt(i.ciphertext,i.key);break}catch(t){if(e+1>=i)throw t}return O.parse(a)}function g(e){console.error(`[dotenv@${s}][WARN] ${e}`)}function _(e){console.log(`[dotenv@${s}][DEBUG] ${e}`)}function v(e){console.log(`[dotenv@${s}] ${e}`)}function y(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:``}function b(e,t){let n;try{n=new URL(t)}catch(e){if(e.code===`ERR_INVALID_URL`){let e=Error(`INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development`);throw e.code=`INVALID_DOTENV_KEY`,e}throw e}let r=n.password;if(!r){let e=Error(`INVALID_DOTENV_KEY: Missing key part`);throw e.code=`INVALID_DOTENV_KEY`,e}let i=n.searchParams.get(`environment`);if(!i){let e=Error(`INVALID_DOTENV_KEY: Missing environment part`);throw e.code=`INVALID_DOTENV_KEY`,e}let a=`DOTENV_VAULT_${i.toUpperCase()}`,o=e.parsed[a];if(!o){let e=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${a} in your .env.vault file.`);throw e.code=`NOT_FOUND_DOTENV_ENVIRONMENT`,e}return{ciphertext:o,key:r}}function x(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let r of e.path)n.existsSync(r)&&(t=r.endsWith(`.vault`)?r:`${r}.vault`);else t=e.path.endsWith(`.vault`)?e.path:`${e.path}.vault`;else t=r.resolve(process.cwd(),`.env.vault`);return n.existsSync(t)?t:null}function S(e){return e[0]===`~`?r.join(a.homedir(),e.slice(1)):e}function C(e){let t=u(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=u(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(t||!n)&&v(`Loading env from encrypted .env.vault`);let r=O._parseVault(e),i=process.env;return e&&e.processEnv!=null&&(i=e.processEnv),O.populate(i,r,e),{parsed:r}}function w(e){let t=r.resolve(process.cwd(),`.env`),i=`utf8`,a=process.env;e&&e.processEnv!=null&&(a=e.processEnv);let o=u(a.DOTENV_CONFIG_DEBUG||e&&e.debug),s=u(a.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?i=e.encoding:o&&_(`No encoding is specified. UTF-8 is used by default`);let c=[t];if(e&&e.path)if(!Array.isArray(e.path))c=[S(e.path)];else{c=[];for(let t of e.path)c.push(S(t))}let d,p={};for(let t of c)try{let r=O.parse(n.readFileSync(t,{encoding:i}));O.populate(p,r,e)}catch(e){o&&_(`Failed to load ${t} ${e.message}`),d=e}let m=O.populate(a,p,e);if(o=u(a.DOTENV_CONFIG_DEBUG||o),s=u(a.DOTENV_CONFIG_QUIET||s),o||!s){let e=Object.keys(m).length,t=[];for(let e of c)try{let n=r.relative(process.cwd(),e);t.push(n)}catch(t){o&&_(`Failed to load ${e} ${t.message}`),d=t}v(`injecting env (${e}) from ${t.join(`,`)} ${f(`-- tip: ${l()}`)}`)}return d?{parsed:p,error:d}:{parsed:p}}function T(e){if(y(e).length===0)return O.configDotenv(e);let t=x(e);return t?O._configVault(e):(g(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),O.configDotenv(e))}function E(e,t){let n=Buffer.from(t.slice(-64),`hex`),r=Buffer.from(e,`base64`),i=r.subarray(0,12),a=r.subarray(-16);r=r.subarray(12,-16);try{let e=o.createDecipheriv(`aes-256-gcm`,n,i);return e.setAuthTag(a),`${e.update(r)}${e.final()}`}catch(e){let t=e instanceof RangeError,n=e.message===`Invalid key length`,r=e.message===`Unsupported state or unable to authenticate data`;if(t||n){let e=Error(`INVALID_DOTENV_KEY: It must be 64 characters long (or more)`);throw e.code=`INVALID_DOTENV_KEY`,e}else if(r){let e=Error(`DECRYPTION_FAILED: Please check your DOTENV_KEY`);throw e.code=`DECRYPTION_FAILED`,e}else throw e}}function D(e,t,n={}){let r=!!(n&&n.debug),i=!!(n&&n.override),a={};if(typeof t!=`object`){let e=Error(`OBJECT_REQUIRED: Please check the processEnv argument being passed to populate`);throw e.code=`OBJECT_REQUIRED`,e}for(let n of Object.keys(t))Object.prototype.hasOwnProperty.call(e,n)?(i===!0&&(e[n]=t[n],a[n]=t[n]),r&&_(i===!0?`"${n}" is already defined and WAS overwritten`:`"${n}" is already defined and was NOT overwritten`)):(e[n]=t[n],a[n]=t[n]);return a}let O={configDotenv:w,_configVault:C,_parseVault:h,config:T,decrypt:E,parse:m,populate:D};t.exports.configDotenv=O.configDotenv,t.exports._configVault=O._configVault,t.exports._parseVault=O._parseVault,t.exports.config=O.config,t.exports.decrypt=O.decrypt,t.exports.parse=O.parse,t.exports.populate=O.populate,t.exports=O}))());async function ju(e,t){let n=e;for(;n!==xe(n);){let e=Se(n,t);try{return await Ne(e),e}catch{}n=xe(n)}}function Mu(e,t=`.env.local`){let[n,r]=q({});return K(()=>{let n,i=e=>{try{let t=Te(e,`utf-8`),n=(0,Au.parse)(t);r(n)}catch(e){console.error(`Error reading ${t}:`,e),r({})}};return ju(e,t).then(e=>{if(!e){r({});return}i(e),n=Ee(e,{persistent:!1},()=>{i(e)})}),()=>{n&&n.close()}},[e,t]),n}var Nu=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}else return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h){d[r]=void 0;continue}if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}};new class extends Nu{};function Pu(e,t){let n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function Fu(e,t){let n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function Iu(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function Lu(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function Ru(e,t){return Iu(e,t,``)}function zu(e,t){return Lu(e,t,``)}function Bu(e,t){return t.slice(0,Vu(e,t))}function Vu(e,t){let n=0;e.length>t.length&&(n=e.length-t.length);let r=t.length;e.length<t.length&&(r=e.length);let i=Array(r),a=0;i[0]=0;for(let e=1;e<r;e++){for(t[e]==t[a]?i[e]=i[a]:i[e]=a;a>0&&t[e]!=t[a];)a=i[a];t[e]==t[a]&&a++}a=0;for(let r=n;r<e.length;r++){for(;a>0&&e[r]!=t[a];)a=i[a];e[r]==t[a]&&a++}return a}function Hu(e){let t;for(t=e.length-1;t>=0&&e[t].match(/\s/);t--);return e.substring(t+1)}function Uu(e){let t=e.match(/^\s*/);return t?t[0]:``}const Wu=`a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,Gu=RegExp(`[${Wu}]+|\\s+|[^${Wu}]`,`ug`);new class extends Nu{equals(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()}tokenize(e,t={}){let n;if(t.intlSegmenter){let r=t.intlSegmenter;if(r.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=Array.from(r.segment(e),e=>e.segment)}else n=e.match(Gu)||[];let r=[],i=null;return n.forEach(e=>{/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):i!=null&&/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r}join(e){return e.map((e,t)=>t==0?e:e.replace(/^\s+/,``)).join(``)}postProcess(e,t){if(!e||t.oneChangePerToken)return e;let n=null,r=null,i=null;return e.forEach(e=>{e.added?r=e:e.removed?i=e:((r||i)&&Ku(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&Ku(n,i,r,null),e}};function Ku(e,t,n,r){if(t&&n){let i=Uu(t.value),a=Hu(t.value),o=Uu(n.value),s=Hu(n.value);if(e){let r=Pu(i,o);e.value=Lu(e.value,o,r),t.value=Ru(t.value,r),n.value=Ru(n.value,r)}if(r){let e=Fu(a,s);r.value=Iu(r.value,s,e),t.value=zu(t.value,e),n.value=zu(n.value,e)}}else if(n){if(e){let e=Uu(n.value);n.value=n.value.substring(e.length)}if(r){let e=Uu(r.value);r.value=r.value.substring(e.length)}}else if(e&&r){let n=Uu(r.value),i=Uu(t.value),a=Hu(t.value),o=Pu(n,i);t.value=Ru(t.value,o);let s=Fu(Ru(n,o),a);t.value=zu(t.value,s),r.value=Iu(r.value,n,s),e.value=Lu(e.value,n,n.slice(0,n.length-s.length))}else if(r){let e=Uu(r.value),n=Hu(t.value),i=Bu(n,e);t.value=zu(t.value,i)}else if(e){let n=Hu(e.value),r=Uu(t.value),i=Bu(n,r);t.value=Ru(t.value,i)}}new class extends Nu{tokenize(e){let t=RegExp(`(\\r?\\n)|[${Wu}]+|[^\\S\\n\\r]+|[^${Wu}]`,`ug`);return e.match(t)||[]}};const qu=new class extends Nu{constructor(){super(...arguments),this.tokenize=Yu}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
@@ -130,11 +130,18 @@ Use this for:
130
130
  - Extracting relevant information from verbose output
131
131
  - Analyzing build or test results
132
132
 
133
- Example: After running tests with \`workspace_bash\`, use this to find all FAIL: lines rather than re-running the test command.`,inputSchema:Y.object({pid:Y.number(),pattern:Y.string(),before_lines:Y.number(),after_lines:Y.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}}}))},ad=async function*({client:e,pid:t,abortSignal:n,timeoutMs:r}){let i=await e,a=[],o=null,s=!1,c=null,l=``,u=i.onNotification(`process_output`,e=>{e.pid===t&&(l+=e.output,a.push({pid:t,ansiOutput:l}),o?.())}),d=i.request(`process_wait`,{pid:t,output_idle_timeout_ms:3e3,timeout_ms:r??25e3},{signal:n}).then(e=>{a.push({pid:e.pid,title:e.title,command:e.command,args:e.args,cwd:e.cwd,env:e.env,ansiOutput:e.ansi_output,plainOutput:{totalLines:e.plain_output.total_lines,lines:e.plain_output.lines},durationMs:e.duration_ms,exitCode:e.exit_code,exitSignal:e.exit_signal,stillRunning:typeof e.exit_code!=`number`&&typeof e.exit_signal!=`number`}),s=!0,o?.()}).catch(e=>{c=e,s=!0,o?.()});try{for(;!s||a.length>0;){if(c)throw c;for(a.length===0&&(await new Promise(e=>{o=e}),o=null);a.length>0;)yield a.shift()}await d}finally{u.dispose()}};Y.union([Y.object({pid:Y.number(),ansiOutput:Y.string()}),Y.object({pid:Y.number(),title:Y.string().optional(),command:Y.string(),args:Y.array(Y.string()),cwd:Y.string(),env:Y.record(Y.string(),Y.string()),ansiOutput:Y.string(),plainOutput:Y.object({totalLines:Y.number(),lines:Y.array(Y.string())}),durationMs:Y.number(),exitCode:Y.number().optional(),exitSignal:Y.number().optional(),stillRunning:Y.boolean()})]);const od=(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},sd=(e,t,n)=>t.length===0?e:e.split(t).join(n),cd={scratch:{".gitignore":`# dependencies
133
+ Example: After running tests with \`workspace_bash\`, use this to find all FAIL: lines rather than re-running the test command.`,inputSchema:Y.object({pid:Y.number(),pattern:Y.string(),before_lines:Y.number(),after_lines:Y.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}}}))},ad=async function*({client:e,pid:t,abortSignal:n,timeoutMs:r}){let i=await e,a=[],o=null,s=!1,c=null,l=``,u=i.onNotification(`process_output`,e=>{e.pid===t&&(l+=e.output,a.push({pid:t,ansiOutput:l}),o?.())}),d=i.request(`process_wait`,{pid:t,output_idle_timeout_ms:3e3,timeout_ms:r??25e3},{signal:n}).then(e=>{a.push({pid:e.pid,title:e.title,command:e.command,args:e.args,cwd:e.cwd,env:e.env,ansiOutput:e.ansi_output,plainOutput:{totalLines:e.plain_output.total_lines,lines:e.plain_output.lines},durationMs:e.duration_ms,exitCode:e.exit_code,exitSignal:e.exit_signal,stillRunning:typeof e.exit_code!=`number`&&typeof e.exit_signal!=`number`}),s=!0,o?.()}).catch(e=>{c=e,s=!0,o?.()});try{for(;!s||a.length>0;){if(c)throw c;for(a.length===0&&(await new Promise(e=>{o=e}),o=null);a.length>0;)yield a.shift()}await d}finally{u.dispose()}};Y.union([Y.object({pid:Y.number(),ansiOutput:Y.string()}),Y.object({pid:Y.number(),title:Y.string().optional(),command:Y.string(),args:Y.array(Y.string()),cwd:Y.string(),env:Y.record(Y.string(),Y.string()),ansiOutput:Y.string(),plainOutput:Y.object({totalLines:Y.number(),lines:Y.array(Y.string())}),durationMs:Y.number(),exitCode:Y.number().optional(),exitSignal:Y.number().optional(),stillRunning:Y.boolean()})]);const od=(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},sd=(e,t,n)=>t.length===0?e:e.split(t).join(n),cd={scratch:{".env.local":`
134
+ # Store local environment variables here.
135
+ # They will be used by blink dev for development.
136
+ # EXTERNAL_SERVICE_API_KEY=
137
+ `,".env.production":`# Store production environment variables here.
138
+ # They will be upserted as secrets on blink deploy.
139
+ # EXTERNAL_SERVICE_API_KEY=
140
+ `,".gitignore":`# dependencies
134
141
  node_modules
135
142
 
136
143
  # config and build
137
- data
144
+ .blink
138
145
 
139
146
  # dotenv environment variables file
140
147
  .env
@@ -142,103 +149,6 @@ data
142
149
 
143
150
  # Finder (MacOS) folder config
144
151
  .DS_Store
145
- `,"tsconfig.json":`{
146
- "compilerOptions": {
147
- "lib": ["ESNext"],
148
- "target": "ESNext",
149
- "module": "Preserve",
150
- "moduleDetection": "force",
151
-
152
- "moduleResolution": "bundler",
153
- "allowImportingTsExtensions": true,
154
- "verbatimModuleSyntax": true,
155
- "resolveJsonModule": true,
156
- "noEmit": true,
157
-
158
- "strict": true,
159
- "skipLibCheck": true,
160
- "noFallthroughCasesInSwitch": true,
161
- "noUncheckedIndexedAccess": true,
162
- "noImplicitOverride": true,
163
-
164
- "noUnusedLocals": false,
165
- "noUnusedParameters": false,
166
-
167
- "types": ["node"]
168
- }
169
- }
170
- `,".env.local":`
171
- # Store local environment variables here.
172
- # They will be used by blink dev for development.
173
- # EXTERNAL_SERVICE_API_KEY=
174
- `,".env.production":`# Store production environment variables here.
175
- # They will be upserted as secrets on blink deploy.
176
- # EXTERNAL_SERVICE_API_KEY=
177
- `,"agent.ts.hbs":`import { convertToModelMessages, streamText, tool } from "ai";
178
- import * as blink from "blink";
179
- import { z } from "zod";
180
- {{#if (eq aiProvider "anthropic")}}
181
- import { anthropic } from "@ai-sdk/anthropic";
182
- {{else if (eq aiProvider "openai")}}
183
- import { openai } from "@ai-sdk/openai";
184
- {{/if}}
185
-
186
- const agent = new blink.Agent();
187
-
188
- agent.on("chat", async ({ messages }) => {
189
- return streamText({
190
- {{#if (eq aiProvider "anthropic")}}
191
- model: anthropic("claude-sonnet-4-5"),
192
- {{else if (eq aiProvider "openai")}}
193
- model: openai("gpt-5-chat-latest"),
194
- {{else if (eq aiProvider "vercel")}}
195
- model: "anthropic/claude-sonnet-4.5",
196
- {{else}}
197
- // Unknown provider: {{aiProvider}}. Defaulting to Vercel AI Gateway syntax.
198
- model: "anthropic/claude-sonnet-4.5",
199
- {{/if}}
200
- system: \`You are a basic agent the user will customize.
201
-
202
- Suggest the user enters edit mode with Ctrl+T or /edit to customize the agent.
203
- Demonstrate your capabilities with the IP tool.\`,
204
- messages: convertToModelMessages(messages),
205
- tools: {
206
- get_ip_info: tool({
207
- description: "Get IP address information of the computer.",
208
- inputSchema: z.object({}),
209
- execute: async () => {
210
- const response = await fetch("https://ipinfo.io/json");
211
- return response.json();
212
- },
213
- }),
214
- },
215
- });
216
- });
217
-
218
- agent.serve();
219
- `,"package.json.hbs":`{
220
- "name": "{{packageName}}",
221
- "main": "agent.ts",
222
- "type": "module",
223
- "private": true,
224
- "scripts": {
225
- "dev": "blink dev",
226
- "deploy": "blink deploy"
227
- },
228
- "devDependencies": {
229
- "zod": "latest",
230
- "ai": "latest",
231
- {{#if (eq aiProvider "anthropic")}}
232
- "@ai-sdk/anthropic": "latest",
233
- {{else if (eq aiProvider "openai")}}
234
- "@ai-sdk/openai": "latest",
235
- {{/if}}
236
- "blink": "latest",
237
- "esbuild": "latest",
238
- "@types/node": "latest",
239
- "typescript": "latest"
240
- }
241
- }
242
152
  `,"AGENTS.md":`This project is a Blink agent.
243
153
 
244
154
  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.
@@ -312,7 +222,7 @@ const agent = new blink.Agent();
312
222
 
313
223
  agent.on("chat", async ({ messages, chat, abortSignal }) => {
314
224
  return streamText({
315
- model: blink.model("anthropic/claude-sonnet-4.5"),
225
+ model: "anthropic/claude-sonnet-4.5",
316
226
  system: "You are a helpful assistant.",
317
227
  messages: convertToModelMessages(messages, {
318
228
  ignoreIncompleteToolCalls: true,
@@ -456,17 +366,6 @@ Tool Prefixing to avoid collisions:
456
366
 
457
367
  LLM Models:
458
368
 
459
- **Option 1: Blink Gateway** (Quick Start)
460
-
461
- \`\`\`typescript
462
- model: blink.model("anthropic/claude-sonnet-4.5");
463
- model: blink.model("openai/gpt-5");
464
- \`\`\`
465
-
466
- Requires: \`blink login\` or \`BLINK_TOKEN\` env var
467
-
468
- **Option 2: Direct Provider** (Production Recommended)
469
-
470
369
  \`\`\`typescript
471
370
  import { anthropic } from "@ai-sdk/anthropic";
472
371
  import { openai } from "@ai-sdk/openai";
@@ -481,7 +380,6 @@ model: openai("gpt-5", { apiKey: process.env.OPENAI_API_KEY });
481
380
 
482
381
  1. If \`ANTHROPIC_API_KEY\` is set: uses \`claude-sonnet-4.5\` via \`@ai-sdk/anthropic\`
483
382
  2. If \`OPENAI_API_KEY\` is set: uses \`gpt-5\` via \`@ai-sdk/openai\`
484
- 3. Otherwise: falls back to \`blink.model("anthropic/claude-sonnet-4.5")\`
485
383
 
486
384
  Available SDKs:
487
385
 
@@ -551,7 +449,7 @@ agent.on("request", async (request) => {
551
449
  agent.on("chat", async ({ messages }) => {
552
450
  const tools = slack.createTools({ client: app.client });
553
451
  return streamText({
554
- model: blink.model("anthropic/claude-sonnet-4.5"),
452
+ model: "anthropic/claude-sonnet-4.5",
555
453
  system: "You chatting with users in Slack.",
556
454
  messages: convertToModelMessages(messages, {
557
455
  ignoreIncompleteToolCalls: true,
@@ -575,7 +473,7 @@ Slack App Manifest:
575
473
  - _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.
576
474
  - The user can always edit the manifest after creation, but you'd have to suggest it to them.
577
475
  - "oauth_config" MUST BE PROVIDED - otherwise the app will have NO ACCESS.
578
- - _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.
476
+ - _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.
579
477
  - For the best user experience, default to the following bot scopes (in the "oauth_config" > "scopes" > "bot"):
580
478
  - "app_mentions:read"
581
479
  - "reactions:write"
@@ -668,160 +566,54 @@ The agent process can restart at any time, so all important state must be extern
668
566
 
669
567
  - Never use "as any" type assertions. Always figure out the correct typings.
670
568
  </code_quality>
671
- `},"slack-bot":{".gitignore":`# dependencies
672
- node_modules
673
-
674
- # config and build
675
- data
676
-
677
- # dotenv environment variables file
678
- .env
679
- .env.*
680
-
681
- # Finder (MacOS) folder config
682
- .DS_Store
683
- `,"tsconfig.json":`{
684
- "compilerOptions": {
685
- "lib": ["ESNext"],
686
- "target": "ESNext",
687
- "module": "Preserve",
688
- "moduleDetection": "force",
689
-
690
- "moduleResolution": "bundler",
691
- "allowImportingTsExtensions": true,
692
- "verbatimModuleSyntax": true,
693
- "resolveJsonModule": true,
694
- "noEmit": true,
695
-
696
- "strict": true,
697
- "skipLibCheck": true,
698
- "noFallthroughCasesInSwitch": true,
699
- "noUncheckedIndexedAccess": true,
700
- "noImplicitOverride": true,
701
-
702
- "noUnusedLocals": false,
703
- "noUnusedParameters": false,
704
-
705
- "types": ["node"]
706
- }
707
- }
708
- `,".env.local":`
709
- # Store local environment variables here.
710
- # They will be used by blink dev for development.
711
- SLACK_BOT_TOKEN=xoxb-your-token-here
712
- SLACK_SIGNING_SECRET=your-signing-secret-here
713
- `,".env.production":`# Store production environment variables here.
714
- # They will be upserted as secrets on blink deploy.
715
- # EXTERNAL_SERVICE_API_KEY=
716
- `,"agent.ts.hbs":`import { convertToModelMessages, streamText } from "ai";
569
+ `,"agent.ts.hbs":`import { convertToModelMessages, streamText, tool } from "ai";
717
570
  import * as blink from "blink";
718
- import * as slack from "@blink-sdk/slack";
719
- import { App } from "@slack/bolt";
571
+ import { z } from "zod";
720
572
  {{#if (eq aiProvider "anthropic")}}
721
573
  import { anthropic } from "@ai-sdk/anthropic";
722
574
  {{else if (eq aiProvider "openai")}}
723
575
  import { openai } from "@ai-sdk/openai";
724
576
  {{/if}}
725
577
 
726
- const receiver = new slack.Receiver();
727
- const app = new App({
728
- token: process.env.SLACK_BOT_TOKEN,
729
- signingSecret: process.env.SLACK_SIGNING_SECRET,
730
- receiver,
731
- });
732
-
733
- // Handle messages in channels (only when @mentioned)
734
- app.event("app_mention", async ({ event }) => {
735
- const chat = await agent.chat.upsert([
736
- "slack",
737
- event.channel,
738
- event.thread_ts ?? event.ts,
739
- ]);
740
- const { message } = await slack.createMessageFromEvent({
741
- client: app.client,
742
- event,
743
- });
744
- await agent.chat.sendMessages(chat.id, [message]);
745
- await app.client.assistant.threads.setStatus({
746
- channel_id: event.channel,
747
- status: "is typing...",
748
- thread_ts: event.thread_ts ?? event.ts,
749
- });
750
- });
751
-
752
- // Handle direct messages (always respond)
753
- app.event("message", async ({ event }) => {
754
- // Ignore bot messages and message changes
755
- if (event.subtype || event.bot_id) {
756
- return;
757
- }
758
- // Only handle DMs (channel type is 'im')
759
- const channelInfo = await app.client.conversations.info({
760
- channel: event.channel,
761
- });
762
- if (!channelInfo.channel?.is_im) {
763
- return;
764
- }
765
- const chat = await agent.chat.upsert(["slack", event.channel]);
766
- const { message } = await slack.createMessageFromEvent({
767
- client: app.client,
768
- event,
769
- });
770
- await agent.chat.sendMessages(chat.id, [message]);
771
- await app.client.assistant.threads.setStatus({
772
- channel_id: event.channel,
773
- status: "is typing...",
774
- thread_ts: event.thread_ts ?? event.ts,
775
- });
776
- });
777
-
778
578
  const agent = new blink.Agent();
779
579
 
780
- agent.on("request", async (request) => {
781
- return receiver.handle(app, request);
782
- });
783
-
784
580
  agent.on("chat", async ({ messages }) => {
785
- const tools = slack.createTools({ client: app.client });
786
- const lastMessage = messages[messages.length - 1];
787
- const threadInfo = lastMessage?.metadata as
788
- | { channel?: string; thread_ts?: string }
789
- | undefined;
790
-
791
- // Add instruction to clear status after completion
792
- if (threadInfo?.channel && threadInfo?.thread_ts) {
793
- const clonedMessages = structuredClone(messages);
794
- const lastClonedMessage = clonedMessages[clonedMessages.length - 1];
795
- if (lastClonedMessage) {
796
- lastClonedMessage.parts.push({
797
- type: "text",
798
- text: \`*INTERNAL INSTRUCTION*: Clear the status of this thread after you finish: channel=\${threadInfo.channel} thread_ts=\${threadInfo.thread_ts}\`,
799
- });
800
- }
801
- messages = clonedMessages;
802
- }
803
-
804
581
  return streamText({
805
582
  {{#if (eq aiProvider "anthropic")}}
806
583
  model: anthropic("claude-sonnet-4-5"),
807
584
  {{else if (eq aiProvider "openai")}}
808
- model: openai("gpt-5-chat-latest"),
585
+ model: openai("gpt-5-codex"),
586
+ providerOptions: {
587
+ openai: {
588
+ reasoningSummary: "detailed",
589
+ },
590
+ },
809
591
  {{else if (eq aiProvider "vercel")}}
810
592
  model: "anthropic/claude-sonnet-4.5",
811
593
  {{else}}
812
594
  // Unknown provider: {{aiProvider}}. Defaulting to Vercel AI Gateway syntax.
813
595
  model: "anthropic/claude-sonnet-4.5",
814
596
  {{/if}}
815
- system: "You are a helpful Slack bot assistant.",
816
- messages: convertToModelMessages(messages, {
817
- ignoreIncompleteToolCalls: true,
818
- tools,
819
- }),
820
- tools,
597
+ system: \`You are a basic agent the user will customize.
598
+
599
+ Suggest the user enters edit mode with Ctrl+T or /edit to customize the agent.
600
+ Demonstrate your capabilities with the IP tool.\`,
601
+ messages: convertToModelMessages(messages),
602
+ tools: {
603
+ get_ip_info: tool({
604
+ description: "Get IP address information of the computer.",
605
+ inputSchema: z.object({}),
606
+ execute: async () => {
607
+ const response = await fetch("https://ipinfo.io/json");
608
+ return response.json();
609
+ },
610
+ }),
611
+ },
821
612
  });
822
613
  });
823
614
 
824
- agent.serve();`,"package.json.hbs":`{
615
+ agent.serve();
616
+ `,"package.json.hbs":`{
825
617
  "name": "{{packageName}}",
826
618
  "main": "agent.ts",
827
619
  "type": "module",
@@ -841,11 +633,54 @@ agent.serve();`,"package.json.hbs":`{
841
633
  "blink": "latest",
842
634
  "esbuild": "latest",
843
635
  "@types/node": "latest",
844
- "typescript": "latest",
845
- "@slack/bolt": "latest",
846
- "@blink-sdk/slack": "latest"
636
+ "typescript": "latest"
847
637
  }
848
638
  }
639
+ `,"tsconfig.json":`{
640
+ "compilerOptions": {
641
+ "lib": ["ESNext"],
642
+ "target": "ESNext",
643
+ "module": "Preserve",
644
+ "moduleDetection": "force",
645
+
646
+ "moduleResolution": "bundler",
647
+ "allowImportingTsExtensions": true,
648
+ "verbatimModuleSyntax": true,
649
+ "resolveJsonModule": true,
650
+ "noEmit": true,
651
+
652
+ "strict": true,
653
+ "skipLibCheck": true,
654
+ "noFallthroughCasesInSwitch": true,
655
+ "noUncheckedIndexedAccess": true,
656
+ "noImplicitOverride": true,
657
+
658
+ "noUnusedLocals": false,
659
+ "noUnusedParameters": false,
660
+
661
+ "types": ["node"]
662
+ }
663
+ }
664
+ `},"slack-bot":{".env.local":`
665
+ # Store local environment variables here.
666
+ # They will be used by blink dev for development.
667
+ SLACK_BOT_TOKEN=xoxb-your-token-here
668
+ SLACK_SIGNING_SECRET=your-signing-secret-here
669
+ `,".env.production":`# Store production environment variables here.
670
+ # They will be upserted as secrets on blink deploy.
671
+ # EXTERNAL_SERVICE_API_KEY=
672
+ `,".gitignore":`# dependencies
673
+ node_modules
674
+
675
+ # config and build
676
+ .blink
677
+
678
+ # dotenv environment variables file
679
+ .env
680
+ .env.*
681
+
682
+ # Finder (MacOS) folder config
683
+ .DS_Store
849
684
  `,"AGENTS.md":`This project is a Blink agent.
850
685
 
851
686
  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.
@@ -919,7 +754,7 @@ const agent = new blink.Agent();
919
754
 
920
755
  agent.on("chat", async ({ messages, chat, abortSignal }) => {
921
756
  return streamText({
922
- model: blink.model("anthropic/claude-sonnet-4.5"),
757
+ model: "anthropic/claude-sonnet-4.5",
923
758
  system: "You are a helpful assistant.",
924
759
  messages: convertToModelMessages(messages, {
925
760
  ignoreIncompleteToolCalls: true,
@@ -1063,17 +898,6 @@ Tool Prefixing to avoid collisions:
1063
898
 
1064
899
  LLM Models:
1065
900
 
1066
- **Option 1: Blink Gateway** (Quick Start)
1067
-
1068
- \`\`\`typescript
1069
- model: blink.model("anthropic/claude-sonnet-4.5");
1070
- model: blink.model("openai/gpt-5");
1071
- \`\`\`
1072
-
1073
- Requires: \`blink login\` or \`BLINK_TOKEN\` env var
1074
-
1075
- **Option 2: Direct Provider** (Production Recommended)
1076
-
1077
901
  \`\`\`typescript
1078
902
  import { anthropic } from "@ai-sdk/anthropic";
1079
903
  import { openai } from "@ai-sdk/openai";
@@ -1088,7 +912,6 @@ model: openai("gpt-5", { apiKey: process.env.OPENAI_API_KEY });
1088
912
 
1089
913
  1. If \`ANTHROPIC_API_KEY\` is set: uses \`claude-sonnet-4.5\` via \`@ai-sdk/anthropic\`
1090
914
  2. If \`OPENAI_API_KEY\` is set: uses \`gpt-5\` via \`@ai-sdk/openai\`
1091
- 3. Otherwise: falls back to \`blink.model("anthropic/claude-sonnet-4.5")\`
1092
915
 
1093
916
  Available SDKs:
1094
917
 
@@ -1158,7 +981,7 @@ agent.on("request", async (request) => {
1158
981
  agent.on("chat", async ({ messages }) => {
1159
982
  const tools = slack.createTools({ client: app.client });
1160
983
  return streamText({
1161
- model: blink.model("anthropic/claude-sonnet-4.5"),
984
+ model: "anthropic/claude-sonnet-4.5",
1162
985
  system: "You chatting with users in Slack.",
1163
986
  messages: convertToModelMessages(messages, {
1164
987
  ignoreIncompleteToolCalls: true,
@@ -1182,7 +1005,7 @@ Slack App Manifest:
1182
1005
  - _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.
1183
1006
  - The user can always edit the manifest after creation, but you'd have to suggest it to them.
1184
1007
  - "oauth_config" MUST BE PROVIDED - otherwise the app will have NO ACCESS.
1185
- - _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.
1008
+ - _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.
1186
1009
  - For the best user experience, default to the following bot scopes (in the "oauth_config" > "scopes" > "bot"):
1187
1010
  - "app_mentions:read"
1188
1011
  - "reactions:write"
@@ -1275,6 +1098,169 @@ The agent process can restart at any time, so all important state must be extern
1275
1098
 
1276
1099
  - Never use "as any" type assertions. Always figure out the correct typings.
1277
1100
  </code_quality>
1101
+ `,"agent.ts.hbs":`import { convertToModelMessages, streamText } from "ai";
1102
+ import * as blink from "blink";
1103
+ import * as slack from "@blink-sdk/slack";
1104
+ import { App } from "@slack/bolt";
1105
+ {{#if (eq aiProvider "anthropic")}}
1106
+ import { anthropic } from "@ai-sdk/anthropic";
1107
+ {{else if (eq aiProvider "openai")}}
1108
+ import { openai } from "@ai-sdk/openai";
1109
+ {{/if}}
1110
+
1111
+ const receiver = new slack.Receiver();
1112
+ const app = new App({
1113
+ token: process.env.SLACK_BOT_TOKEN,
1114
+ signingSecret: process.env.SLACK_SIGNING_SECRET,
1115
+ receiver,
1116
+ });
1117
+
1118
+ // Handle messages in channels (only when @mentioned)
1119
+ app.event("app_mention", async ({ event }) => {
1120
+ const chat = await agent.chat.upsert([
1121
+ "slack",
1122
+ event.channel,
1123
+ event.thread_ts ?? event.ts,
1124
+ ]);
1125
+ const { message } = await slack.createMessageFromEvent({
1126
+ client: app.client,
1127
+ event,
1128
+ });
1129
+ await agent.chat.sendMessages(chat.id, [message]);
1130
+ await app.client.assistant.threads.setStatus({
1131
+ channel_id: event.channel,
1132
+ status: "is typing...",
1133
+ thread_ts: event.thread_ts ?? event.ts,
1134
+ });
1135
+ });
1136
+
1137
+ // Handle direct messages (always respond)
1138
+ app.event("message", async ({ event }) => {
1139
+ // Ignore bot messages and message changes
1140
+ if (event.subtype || event.bot_id) {
1141
+ return;
1142
+ }
1143
+ // Only handle DMs (channel type is 'im')
1144
+ const channelInfo = await app.client.conversations.info({
1145
+ channel: event.channel,
1146
+ });
1147
+ if (!channelInfo.channel?.is_im) {
1148
+ return;
1149
+ }
1150
+ const chat = await agent.chat.upsert(["slack", event.channel]);
1151
+ const { message } = await slack.createMessageFromEvent({
1152
+ client: app.client,
1153
+ event,
1154
+ });
1155
+ await agent.chat.sendMessages(chat.id, [message]);
1156
+ await app.client.assistant.threads.setStatus({
1157
+ channel_id: event.channel,
1158
+ status: "is typing...",
1159
+ thread_ts: event.thread_ts ?? event.ts,
1160
+ });
1161
+ });
1162
+
1163
+ const agent = new blink.Agent();
1164
+
1165
+ agent.on("request", async (request) => {
1166
+ return receiver.handle(app, request);
1167
+ });
1168
+
1169
+ agent.on("chat", async ({ messages }) => {
1170
+ const tools = slack.createTools({ client: app.client });
1171
+ const lastMessage = messages[messages.length - 1];
1172
+ const threadInfo = lastMessage?.metadata as
1173
+ | { channel?: string; thread_ts?: string }
1174
+ | undefined;
1175
+
1176
+ // Add instruction to clear status after completion
1177
+ if (threadInfo?.channel && threadInfo?.thread_ts) {
1178
+ const clonedMessages = structuredClone(messages);
1179
+ const lastClonedMessage = clonedMessages[clonedMessages.length - 1];
1180
+ if (lastClonedMessage) {
1181
+ lastClonedMessage.parts.push({
1182
+ type: "text",
1183
+ text: \`*INTERNAL INSTRUCTION*: Clear the status of this thread after you finish: channel=\${threadInfo.channel} thread_ts=\${threadInfo.thread_ts}\`,
1184
+ });
1185
+ }
1186
+ messages = clonedMessages;
1187
+ }
1188
+
1189
+ return streamText({
1190
+ {{#if (eq aiProvider "anthropic")}}
1191
+ model: anthropic("claude-sonnet-4-5"),
1192
+ {{else if (eq aiProvider "openai")}}
1193
+ model: openai("gpt-5-codex"),
1194
+ providerOptions: {
1195
+ openai: {
1196
+ reasoningSummary: "detailed",
1197
+ },
1198
+ },
1199
+ {{else if (eq aiProvider "vercel")}}
1200
+ model: "anthropic/claude-sonnet-4.5",
1201
+ {{else}}
1202
+ // Unknown provider: {{aiProvider}}. Defaulting to Vercel AI Gateway syntax.
1203
+ model: "anthropic/claude-sonnet-4.5",
1204
+ {{/if}}
1205
+ system: "You are a helpful Slack bot assistant.",
1206
+ messages: convertToModelMessages(messages, {
1207
+ ignoreIncompleteToolCalls: true,
1208
+ tools,
1209
+ }),
1210
+ tools,
1211
+ });
1212
+ });
1213
+
1214
+ agent.serve();`,"package.json.hbs":`{
1215
+ "name": "{{packageName}}",
1216
+ "main": "agent.ts",
1217
+ "type": "module",
1218
+ "private": true,
1219
+ "scripts": {
1220
+ "dev": "blink dev",
1221
+ "deploy": "blink deploy"
1222
+ },
1223
+ "devDependencies": {
1224
+ "zod": "latest",
1225
+ "ai": "latest",
1226
+ {{#if (eq aiProvider "anthropic")}}
1227
+ "@ai-sdk/anthropic": "latest",
1228
+ {{else if (eq aiProvider "openai")}}
1229
+ "@ai-sdk/openai": "latest",
1230
+ {{/if}}
1231
+ "blink": "latest",
1232
+ "esbuild": "latest",
1233
+ "@types/node": "latest",
1234
+ "typescript": "latest",
1235
+ "@slack/bolt": "latest",
1236
+ "@blink-sdk/slack": "latest"
1237
+ }
1238
+ }
1239
+ `,"tsconfig.json":`{
1240
+ "compilerOptions": {
1241
+ "lib": ["ESNext"],
1242
+ "target": "ESNext",
1243
+ "module": "Preserve",
1244
+ "moduleDetection": "force",
1245
+
1246
+ "moduleResolution": "bundler",
1247
+ "allowImportingTsExtensions": true,
1248
+ "verbatimModuleSyntax": true,
1249
+ "resolveJsonModule": true,
1250
+ "noEmit": true,
1251
+
1252
+ "strict": true,
1253
+ "skipLibCheck": true,
1254
+ "noFallthroughCasesInSwitch": true,
1255
+ "noUncheckedIndexedAccess": true,
1256
+ "noImplicitOverride": true,
1257
+
1258
+ "noUnusedLocals": false,
1259
+ "noUnusedParameters": false,
1260
+
1261
+ "types": ["node"]
1262
+ }
1263
+ }
1278
1264
  `}};function ld(e,t,n){let r,i=U.createServer(O(async a=>{let o=new URL(a.url,r);if(o.pathname!==`/`)return new Response(`Not found`,{status:404});let s=o.searchParams.get(`code`);if(s)try{let e=await fetch(`https://api.github.com/app-manifests/${s}/conversions`,{method:`POST`,headers:{Accept:`application/vnd.github+json`,"User-Agent":`blink.so`,"X-GitHub-Api-Version":`2022-11-28`}});if(!e.ok){let t=await e.text();throw Error(`GitHub API error: ${e.status} ${e.statusText}${t?` - ${t}`:``}`)}let t=await e.json();return await n?.(null,t),new Response(`GitHub App created successfully! Return to your terminal to continue.`,{headers:{"Content-Type":`text/plain`}})}catch(e){let t=e instanceof Error?e:Error(String(e));try{await n?.(t,null)}catch(e){t=e instanceof Error?e:Error(String(e))}let r=t.message;return new Response(`Error: ${r}\n\nReturn to your terminal for more details.`,{status:500,headers:{"Content-Type":`text/plain`}})}finally{i.close()}let c={...e,redirect_url:r},l=`<!DOCTYPE html>
1279
1265
  <html>
1280
1266
  <body>
@@ -1376,4 +1362,4 @@ Slack:
1376
1362
  1. *ALWAYS* use the \`typecheck_agent\` tool to check for type errors before making changes. NEVER invoke \`tsc\` directly.
1377
1363
  2. Use the \`message_user_agent\` tool to test the agent after you make changes.
1378
1364
  </agent_development>
1379
- `});let p=cd.scratch[`AGENTS.md`];try{p=await Me(Se(e.directory,`AGENTS.md`),`utf-8`)}catch{}return f.unshift({role:`system`,content:p}),je({model:bd(e.env),messages:f,maxOutputTokens:64e3,tools:d,abortSignal:a,experimental_repairToolCall:({tools:e,toolCall:t})=>{throw Object.keys(e).includes(t.toolName)?Error(`You have this tool, but you used an invalid input.`):Error(`Invalid tool call. Tool "${t.toolName}" is not available to the EDIT AGENT.`)}})}),{agent:t,setUserAgentUrl:e=>{n=e},cleanup:()=>{r&&=(r.close(),void 0)}}}function yd(e){if(e.ANTHROPIC_API_KEY)return zt({apiKey:e.ANTHROPIC_API_KEY}).chat(`claude-sonnet-4-5`);if(e.OPENAI_API_KEY)return vi({apiKey:e.OPENAI_API_KEY}).responses(`gpt-5`);if(e.AI_GATEWAY_API_KEY)return C({apiKey:e.AI_GATEWAY_API_KEY})(`anthropic/claude-sonnet-4-5`)}function bd(e){let t=yd(e);if(!t)throw Error(`No API key available for edit mode`);return t}function xd(e){let[t,n]=q(void 0),[r,i]=q(void 0),[a,o]=q(!1),s=Le(void 0);return K(()=>{let t=new AbortController,r=!1;if(i(void 0),n(void 0),!yd(e.env)){o(!0);return}return o(!1),(async()=>{s.current=vd({directory:e.directory,env:e.env,getDevhookUrl:e.getDevhookUrl});let r=await Sd(),i=s.current.agent.serve({port:r,host:`127.0.0.1`,apiUrl:e.apiServerUrl});t.signal.addEventListener(`abort`,()=>{try{i.close()}catch{}s.current?.cleanup()});let a=new Wi({baseUrl:`http://127.0.0.1:${r}`});for(;!t.signal.aborted;){try{await a.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(t.signal.aborted)throw t.signal.reason;n(a)})().catch(e=>{r||i(e instanceof Error?e:Error(String(e)))}),()=>{r=!0,t.abort()}},[e.directory,e.apiServerUrl,e.env,e.getDevhookUrl]),Ie(()=>({client:t,error:r,missingApiKey:a,setUserAgentUrl:e=>{s.current?.setUserAgentUrl(e)}}),[t,r,a])}async function Sd(){let e=be();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function Cd(e){let{directory:t}=e,[n,r]=q(),[i,a]=q(!1),[o,s]=q(`run`),c=Le(`run`);K(()=>{c.current=o},[o]);let l=G(t=>{s(t),e.onModeChange?.(t),r(void 0)},[e.onModeChange]),u=G(()=>{l(o===`run`?`edit`:`run`)},[o,l]),{error:d,status:f,result:p,entry:m}=xl({directory:t,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),h=bl({autoCheck:!0,onAuthChange:e.onAuthChange,onLoginUrl:e.onLoginUrl}),g=Mu(t),_=Ie(()=>{let e=h.token;return e?{...g,BLINK_TOKEN:e}:g},[g,h.token]),v=Le(void 0);K(()=>{let t=Object.keys(_);if(t.length===v.current||v.current===void 0){v.current=t.length;return}v.current=t.length,e.onEnvLoaded?.(t)},[_,e.onEnvLoaded]);let y=Le(void 0),b=Ie(()=>Tu({port:0,dataDirectory:Se(t,`data`),getAgent:()=>y.current}),[t]),{agent:x,logs:S,error:C,capabilities:w}=Gi({buildResult:p,env:_,apiServerUrl:b.url}),{client:T,error:E,missingApiKey:D,setUserAgentUrl:O}=xd({directory:t,apiServerUrl:b.url,env:_,getDevhookUrl:G(()=>{let e=tu(t)??nu(t);return P(e),`https://${e}.blink.host`},[t])}),[k,A]=q(`00000000-0000-0000-0000-000000000000`);K(()=>{y.current=x},[x]),K(()=>{x&&O(x.baseUrl),(o===`run`&&!x||o===`edit`&&!T)&&b.getChatManager(k)?.stopStreaming()},[x,T,o,k,b,O]);let j=Le(void 0),M=Ql({chatId:k,agent:o===`run`?x:T,chatsDirectory:b.chatsDirectory,serializeMessage:e=>{let t=e.role===`user`&&j.current?{...typeof e.metadata==`object`&&e.metadata!==null?e.metadata:{},options:j.current}:e.metadata;return typeof t==`object`&&t&&(t.__blink_mode=c.current),{id:e.id??crypto.randomUUID(),created_at:new Date().toISOString(),role:e.role,parts:e.parts,mode:c.current,metadata:t}},filterMessages:e=>c.current===`edit`?!0:!(Xl(e.metadata)||e.mode===`edit`)}),te=Le(0);K(()=>{if(S.length===te.current)return;let t=te.current;for(let n of S.slice(t))e.onAgentLog?.(n);te.current=S.length},[S,e.onAgentLog,M.upsertMessage]);let[ne,re]=q([]);K(()=>{b.listChats().then(e=>{re(e.map(e=>e.key))})},[b]),K(()=>{k&&!ne.includes(k)&&re(e=>[...e,k])},[k,ne]);let[N,P]=q(()=>eu(t)?tu(t):nu(t)),F=Ou({id:N,directory:t,disabled:!w?.request,onRequest:async t=>{if(!x)throw Error(`No agent`);let n=new URL(t.url),r=new URL(x.baseUrl);r.pathname=n.pathname,r.search=n.search;try{let i=await fetch(r.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:`manual`,signal:t.signal,duplex:`half`});return e.onDevhookRequest?.({method:t.method,path:n.pathname,status:i.status}),i}catch(e){return console.error(`Error sending request to user's agent:`,e),new Response(`Internal server error`,{status:500})}}});K(()=>{F.status!==`connected`||!F.url||e.onDevhookConnected?.(F.url)},[F.status,F.url]);let{schema:I,options:L,error:R,setOption:ie}=Eu({agent:o===`run`?x:T,capabilities:w,messages:M.messages});K(()=>{j.current=L},[L]);let z=Ie(()=>{let e=new Map;return C&&o===`run`&&e.set(`agent`,C.message),E&&o===`edit`&&e.set(`editAgent`,`Edit agent error: ${E.message}`),M.error&&f!==`building`&&e.set(`chat`,`Chat error: ${M.error}`),R&&e.set(`options`,`Options error: ${R.message}`),e},[C,E,M.error,R,o,f]),ae=Le(new Map);K(()=>{let t=ae.current,n=z;for(let[r,i]of n.entries())t.get(r)!==i&&e.onError?.(i);for(let e of t.keys())n.has(e);ae.current=new Map(n)},[z,e.onError]);let oe=Ie(()=>{let e=[...M.messages].reverse().find(e=>!(e.role!==`assistant`||e.metadata&&e.metadata.ephemeral));if(!e||n===e.id)return;let t=e.parts.filter(ke);if(t.length!==0&&t.some(e=>ee(e.output)&&e.output.outcome===`pending`))return e},[M.messages,n]),se=G(async(e,t)=>{if(!oe)return;t&&e&&a(!0),r(oe.id);let n=M.messages;if(n.length===0)return;let i=n[n.length-1];if(!i||i.role!==`assistant`||!Array.isArray(i.parts))return;let o=i.parts.map(t=>t.output&&ee(t.output)&&t.output.outcome===`pending`?{...t,output:{...t.output,outcome:e?`approved`:`rejected`}}:t);await M.upsertMessage({...i,parts:o}),await M.start()},[oe,M]);K(()=>{i&&oe&&se(!0)},[i,oe,se]);let ce=G(()=>{let e=crypto.randomUUID();A(e),re(t=>[...t,e]),r(void 0)},[]),B=G(e=>{A(e),r(void 0)},[]),V=Ie(()=>{if(oe)return{message:oe,approve:e=>se(!0,e),reject:()=>se(!1),autoApproveEnabled:i}},[oe,se,i]),H=Ie(()=>{let e=M.messages;if(e.length!==0)for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n||n.role!==`assistant`||!n.metadata||typeof n.metadata!=`object`||!(`totalUsage`in n.metadata))continue;let r=n.metadata.totalUsage;if(!(!r||typeof r!=`object`)&&!(!(`inputTokens`in r)||!(`outputTokens`in r)||!(`totalTokens`in r)))return{inputTokens:r.inputTokens,outputTokens:r.outputTokens,totalTokens:r.totalTokens,cachedInputTokens:r.cachedInputTokens}}},[M.messages]),le=Ie(()=>{if(M.status!==`streaming`)return!1;if(!M.streamingMessage)return!0;let e=M.streamingMessage.parts.filter(ke);return e.length>0&&e.every(e=>e.state.startsWith(`output-`))},[M.status,M.streamingMessage]);return{mode:o,setMode:l,toggleMode:u,chat:M,chats:ne,switchChat:B,newChat:ce,build:{status:f,error:d,entrypoint:m},devhook:{connected:F.status===`connected`,url:F.status===`connected`?F.url:void 0},capabilities:w,options:{schema:I,selected:L,error:R,setOption:ie},approval:V,tokenUsage:H,auth:h,server:b,showWaitingPlaceholder:le,editModeMissingApiKey:D}}export{Gi as useAgent,bl as useAuth,xl as useBundler,Ql as useChat,Cd as useDevMode,Ou as useDevhook,Mu as useDotenv,xd as useEditAgent,Eu as useOptions};
1365
+ `});let p=cd.scratch[`AGENTS.md`];try{p=await Me(Se(e.directory,`AGENTS.md`),`utf-8`)}catch{}return f.unshift({role:`system`,content:p}),je({model:bd(e.env),messages:f,maxOutputTokens:64e3,tools:d,abortSignal:a,experimental_repairToolCall:({tools:e,toolCall:t})=>{throw Object.keys(e).includes(t.toolName)?Error(`You have this tool, but you used an invalid input.`):Error(`Invalid tool call. Tool "${t.toolName}" is not available to the EDIT AGENT.`)}})}),{agent:t,setUserAgentUrl:e=>{n=e},cleanup:()=>{r&&=(r.close(),void 0)}}}function yd(e){if(e.ANTHROPIC_API_KEY)return zt({apiKey:e.ANTHROPIC_API_KEY}).chat(`claude-sonnet-4-5`);if(e.OPENAI_API_KEY)return vi({apiKey:e.OPENAI_API_KEY}).responses(`gpt-5`);if(e.AI_GATEWAY_API_KEY)return C({apiKey:e.AI_GATEWAY_API_KEY})(`anthropic/claude-sonnet-4-5`)}function bd(e){let t=yd(e);if(!t)throw Error(`No API key available for edit mode`);return t}function xd(e){let[t,n]=q(void 0),[r,i]=q(void 0),[a,o]=q(!1),s=Le(void 0);return K(()=>{let t=new AbortController,r=!1;if(i(void 0),n(void 0),!yd(e.env)){o(!0);return}return o(!1),(async()=>{s.current=vd({directory:e.directory,env:e.env,getDevhookUrl:e.getDevhookUrl});let r=await Sd(),i=s.current.agent.serve({port:r,host:`127.0.0.1`,apiUrl:e.apiServerUrl});t.signal.addEventListener(`abort`,()=>{try{i.close()}catch{}s.current?.cleanup()});let a=new Wi({baseUrl:`http://127.0.0.1:${r}`});for(;!t.signal.aborted;){try{await a.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(t.signal.aborted)throw t.signal.reason;n(a)})().catch(e=>{r||i(e instanceof Error?e:Error(String(e)))}),()=>{r=!0,t.abort()}},[e.directory,e.apiServerUrl,e.env,e.getDevhookUrl]),Ie(()=>({client:t,error:r,missingApiKey:a,setUserAgentUrl:e=>{s.current?.setUserAgentUrl(e)}}),[t,r,a])}async function Sd(){let e=be();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function Cd(e){let{directory:t}=e,[n,r]=q(),[i,a]=q(!1),[o,s]=q(`run`),c=Le(`run`);K(()=>{c.current=o},[o]);let l=G(t=>{s(t),e.onModeChange?.(t),r(void 0)},[e.onModeChange]),u=G(()=>{l(o===`run`?`edit`:`run`)},[o,l]),{error:d,status:f,result:p,entry:m}=xl({directory:t,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),h=bl({autoCheck:!0,onAuthChange:e.onAuthChange,onLoginUrl:e.onLoginUrl}),g=Mu(t),_=Ie(()=>{let e=h.token;return e?{...g,BLINK_TOKEN:e}:g},[g,h.token]),v=Le(void 0);K(()=>{let t=Object.keys(_);if(t.length===v.current||v.current===void 0){v.current=t.length;return}v.current=t.length,e.onEnvLoaded?.(t)},[_,e.onEnvLoaded]);let y=Le(void 0),b=Ie(()=>Tu({port:0,dataDirectory:Se(t,`.blink`),getAgent:()=>y.current}),[t]),{agent:x,logs:S,error:C,capabilities:w}=Gi({buildResult:p,env:_,apiServerUrl:b.url}),{client:T,error:E,missingApiKey:D,setUserAgentUrl:O}=xd({directory:t,apiServerUrl:b.url,env:_,getDevhookUrl:G(()=>{let e=tu(t)??nu(t);return P(e),`https://${e}.blink.host`},[t])}),[k,A]=q(`00000000-0000-0000-0000-000000000000`);K(()=>{y.current=x},[x]),K(()=>{x&&O(x.baseUrl),(o===`run`&&!x||o===`edit`&&!T)&&b.getChatManager(k)?.stopStreaming()},[x,T,o,k,b,O]);let j=Le(void 0),M=Ql({chatId:k,agent:o===`run`?x:T,chatsDirectory:b.chatsDirectory,serializeMessage:e=>{let t=e.role===`user`&&j.current?{...typeof e.metadata==`object`&&e.metadata!==null?e.metadata:{},options:j.current}:e.metadata;return typeof t==`object`&&t&&(t.__blink_mode=c.current),{id:e.id??crypto.randomUUID(),created_at:new Date().toISOString(),role:e.role,parts:e.parts,mode:c.current,metadata:t}},filterMessages:e=>c.current===`edit`?!0:!(Xl(e.metadata)||e.mode===`edit`)}),te=Le(0);K(()=>{if(S.length===te.current)return;let t=te.current;for(let n of S.slice(t))e.onAgentLog?.(n);te.current=S.length},[S,e.onAgentLog,M.upsertMessage]);let[ne,re]=q([]);K(()=>{b.listChats().then(e=>{re(e.map(e=>e.key))})},[b]),K(()=>{k&&!ne.includes(k)&&re(e=>[...e,k])},[k,ne]);let[N,P]=q(()=>eu(t)?tu(t):nu(t)),F=Ou({id:N,directory:t,disabled:!w?.request,onRequest:async t=>{if(!x)throw Error(`No agent`);let n=new URL(t.url),r=new URL(x.baseUrl);r.pathname=n.pathname,r.search=n.search;try{let i=await fetch(r.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:`manual`,signal:t.signal,duplex:`half`});return e.onDevhookRequest?.({method:t.method,path:n.pathname,status:i.status}),i}catch(e){return console.error(`Error sending request to user's agent:`,e),new Response(`Internal server error`,{status:500})}}});K(()=>{F.status!==`connected`||!F.url||e.onDevhookConnected?.(F.url)},[F.status,F.url]);let{schema:I,options:L,error:R,setOption:ie}=Eu({agent:o===`run`?x:T,capabilities:w,messages:M.messages});K(()=>{j.current=L},[L]);let z=Ie(()=>{let e=new Map;return C&&o===`run`&&e.set(`agent`,C.message),E&&o===`edit`&&e.set(`editAgent`,`Edit agent error: ${E.message}`),M.error&&f!==`building`&&e.set(`chat`,`Chat error: ${M.error}`),R&&e.set(`options`,`Options error: ${R.message}`),e},[C,E,M.error,R,o,f]),ae=Le(new Map);K(()=>{let t=ae.current,n=z;for(let[r,i]of n.entries())t.get(r)!==i&&e.onError?.(i);for(let e of t.keys())n.has(e);ae.current=new Map(n)},[z,e.onError]);let oe=Ie(()=>{let e=[...M.messages].reverse().find(e=>!(e.role!==`assistant`||e.metadata&&e.metadata.ephemeral));if(!e||n===e.id)return;let t=e.parts.filter(ke);if(t.length!==0&&t.some(e=>ee(e.output)&&e.output.outcome===`pending`))return e},[M.messages,n]),se=G(async(e,t)=>{if(!oe)return;t&&e&&a(!0),r(oe.id);let n=M.messages;if(n.length===0)return;let i=n[n.length-1];if(!i||i.role!==`assistant`||!Array.isArray(i.parts))return;let o=i.parts.map(t=>t.output&&ee(t.output)&&t.output.outcome===`pending`?{...t,output:{...t.output,outcome:e?`approved`:`rejected`}}:t);await M.upsertMessage({...i,parts:o}),await M.start()},[oe,M]);K(()=>{i&&oe&&se(!0)},[i,oe,se]);let ce=G(()=>{let e=crypto.randomUUID();A(e),re(t=>[...t,e]),r(void 0)},[]),B=G(e=>{A(e),r(void 0)},[]),V=Ie(()=>{if(oe)return{message:oe,approve:e=>se(!0,e),reject:()=>se(!1),autoApproveEnabled:i}},[oe,se,i]),H=Ie(()=>{let e=M.messages;if(e.length!==0)for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n||n.role!==`assistant`||!n.metadata||typeof n.metadata!=`object`||!(`totalUsage`in n.metadata))continue;let r=n.metadata.totalUsage;if(!(!r||typeof r!=`object`)&&!(!(`inputTokens`in r)||!(`outputTokens`in r)||!(`totalTokens`in r)))return{inputTokens:r.inputTokens,outputTokens:r.outputTokens,totalTokens:r.totalTokens,cachedInputTokens:r.cachedInputTokens}}},[M.messages]),le=Ie(()=>{if(M.status!==`streaming`)return!1;if(!M.streamingMessage)return!0;let e=M.streamingMessage.parts.filter(ke);return e.length>0&&e.every(e=>e.state.startsWith(`output-`))},[M.status,M.streamingMessage]);return{mode:o,setMode:l,toggleMode:u,chat:M,chats:ne,switchChat:B,newChat:ce,build:{status:f,error:d,entrypoint:m},devhook:{connected:F.status===`connected`,url:F.status===`connected`?F.url:void 0},capabilities:w,options:{schema:I,selected:L,error:R,setOption:ie},approval:V,tokenUsage:H,auth:h,server:b,showWaitingPlaceholder:le,editModeMissingApiKey:D}}export{Gi as useAgent,bl as useAuth,xl as useBundler,Ql as useChat,Cd as useDevMode,Ou as useDevhook,Mu as useDotenv,xd as useEditAgent,Eu as useOptions};