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
- const e=require(`../chunk-iXuH7AlR.cjs`),t=require(`../index.node-D7Cvmag9.cjs`);require(`../token-error-BoNG8ooW.cjs`),require(`../esm-0UNjvroT.cjs`);const n=require(`../build-BzoNpizh.cjs`);let r=require(`zod/v4`);r=e.__toESM(r),require(`zod/v3`);let i=require(`node:buffer`);i=e.__toESM(i);let a=require(`node:fs`);a=e.__toESM(a);let o=require(`node:url`);o=e.__toESM(o);let s=require(`node:stream`);s=e.__toESM(s);let c=require(`node:util`);c=e.__toESM(c);let l=require(`node:crypto`);l=e.__toESM(l);let u=require(`http`);u=e.__toESM(u);let d=require(`path`);d=e.__toESM(d);let f=require(`fs`);f=e.__toESM(f);let p=require(`ai`);p=e.__toESM(p);let m=require(`fs/promises`);m=e.__toESM(m);let h=require(`child_process`);h=e.__toESM(h);let g=require(`react`);g=e.__toESM(g);let _=require(`node:module`);_=e.__toESM(_);let v=require(`zod`);v=e.__toESM(v);let y=require(`node:path`);y=e.__toESM(y);let b=require(`node:process`);b=e.__toESM(b);let x=require(`node:readline`);x=e.__toESM(x);let S=require(`node:child_process`);S=e.__toESM(S);let C=require(`node:fs/promises`);C=e.__toESM(C);let w=require(`node:os`);w=e.__toESM(w),require(`@blink-sdk/compute-protocol/client`);let T=require(`@blink-sdk/compute-protocol/transport`);T=e.__toESM(T);var E=`2.0.23`,D=r.z.object({type:r.z.literal(`error`),error:r.z.object({type:r.z.string(),message:r.z.string()})}),O=t.createJsonErrorResponseHandler({errorSchema:D,errorToMessage:e=>e.error.message}),k=r.z.object({citations:r.z.object({enabled:r.z.boolean()}).optional(),title:r.z.string().optional(),context:r.z.string().optional()}),A=r.z.object({sendReasoning:r.z.boolean().optional(),thinking:r.z.object({type:r.z.union([r.z.literal(`enabled`),r.z.literal(`disabled`)]),budgetTokens:r.z.number().optional()}).optional(),disableParallelToolUse:r.z.boolean().optional(),cacheControl:r.z.object({type:r.z.literal(`ephemeral`),ttl:r.z.union([r.z.literal(`5m`),r.z.literal(`1h`)]).optional()}).optional()});function j(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var M=r.z.object({maxCharacters:r.z.number().optional()}),N=t.createProviderDefinedToolFactory({id:`anthropic.text_editor_20250728`,name:`str_replace_based_edit_tool`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),ee=(e={})=>N(e),P=r.z.object({maxUses:r.z.number().optional(),allowedDomains:r.z.array(r.z.string()).optional(),blockedDomains:r.z.array(r.z.string()).optional(),userLocation:r.z.object({type:r.z.literal(`approximate`),city:r.z.string().optional(),region:r.z.string().optional(),country:r.z.string().optional(),timezone:r.z.string().optional()}).optional()}),F=r.z.array(r.z.object({url:r.z.string(),title:r.z.string(),pageAge:r.z.string().nullable(),encryptedContent:r.z.string(),type:r.z.literal(`web_search_result`)})),te=t.createProviderDefinedToolFactoryWithOutputSchema({id:`anthropic.web_search_20250305`,name:`web_search`,inputSchema:r.z.object({query:r.z.string()}),outputSchema:F}),I=(e={})=>te(e),L=r.z.object({maxUses:r.z.number().optional(),allowedDomains:r.z.array(r.z.string()).optional(),blockedDomains:r.z.array(r.z.string()).optional(),citations:r.z.object({enabled:r.z.boolean()}).optional(),maxContentTokens:r.z.number().optional()}),R=r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.union([r.z.object({type:r.z.literal(`base64`),mediaType:r.z.literal(`application/pdf`),data:r.z.string()}),r.z.object({type:r.z.literal(`text`),mediaType:r.z.literal(`text/plain`),data:r.z.string()})])}),retrievedAt:r.z.string().nullable()}),ne=t.createProviderDefinedToolFactoryWithOutputSchema({id:`anthropic.web_fetch_20250910`,name:`web_fetch`,inputSchema:r.z.object({url:r.z.string()}),outputSchema:R}),z=(e={})=>ne(e);function re({tools:e,toolChoice:n,disableParallelToolUse:r}){e=e?.length?e:void 0;let i=[],a=new Set;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:a};let o=[];for(let t of e)switch(t.type){case`function`:{let e=j(t.providerOptions);o.push({name:t.name,description:t.description,input_schema:t.inputSchema,cache_control:e});break}case`provider-defined`:switch(t.id){case`anthropic.code_execution_20250522`:a.add(`code-execution-2025-05-22`),o.push({type:`code_execution_20250522`,name:`code_execution`});break;case`anthropic.computer_20250124`:a.add(`computer-use-2025-01-24`),o.push({name:`computer`,type:`computer_20250124`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.computer_20241022`:a.add(`computer-use-2024-10-22`),o.push({name:`computer`,type:`computer_20241022`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.text_editor_20250124`:a.add(`computer-use-2025-01-24`),o.push({name:`str_replace_editor`,type:`text_editor_20250124`});break;case`anthropic.text_editor_20241022`:a.add(`computer-use-2024-10-22`),o.push({name:`str_replace_editor`,type:`text_editor_20241022`});break;case`anthropic.text_editor_20250429`:a.add(`computer-use-2025-01-24`),o.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`});break;case`anthropic.text_editor_20250728`:{let e=M.parse(t.args);o.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250728`,max_characters:e.maxCharacters});break}case`anthropic.bash_20250124`:a.add(`computer-use-2025-01-24`),o.push({name:`bash`,type:`bash_20250124`});break;case`anthropic.bash_20241022`:a.add(`computer-use-2024-10-22`),o.push({name:`bash`,type:`bash_20241022`});break;case`anthropic.web_fetch_20250910`:{a.add(`web-fetch-2025-09-10`);let e=L.parse(t.args);o.push({type:`web_fetch_20250910`,name:`web_fetch`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens});break}case`anthropic.web_search_20250305`:{let e=P.parse(t.args);o.push({type:`web_search_20250305`,name:`web_search`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation});break}default:i.push({type:`unsupported-tool`,tool:t});break}break;default:i.push({type:`unsupported-tool`,tool:t});break}if(n==null)return{tools:o,toolChoice:r?{type:`auto`,disable_parallel_tool_use:r}:void 0,toolWarnings:i,betas:a};let s=n.type;switch(s){case`auto`:return{tools:o,toolChoice:{type:`auto`,disable_parallel_tool_use:r},toolWarnings:i,betas:a};case`required`:return{tools:o,toolChoice:{type:`any`,disable_parallel_tool_use:r},toolWarnings:i,betas:a};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:a};case`tool`:return{tools:o,toolChoice:{type:`tool`,name:n.toolName,disable_parallel_tool_use:r},toolWarnings:i,betas:a};default:throw new t.UnsupportedFunctionalityError({functionality:`tool choice type: ${s}`})}}var B=r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),ie=t.createProviderDefinedToolFactoryWithOutputSchema({id:`anthropic.code_execution_20250522`,name:`code_execution`,inputSchema:r.z.object({code:r.z.string()}),outputSchema:B}),ae=(e={})=>ie(e);function oe(e){if(typeof e==`string`)return Buffer.from(e,`base64`).toString(`utf-8`);if(e instanceof Uint8Array)return new TextDecoder().decode(e);throw e instanceof URL?new t.UnsupportedFunctionalityError({functionality:`URL-based text documents are not supported for citations`}):new t.UnsupportedFunctionalityError({functionality:`unsupported data type for text documents: ${typeof e}`})}async function se({prompt:e,sendReasoning:n,warnings:r}){let i=new Set,a=ce(e),o,s=[];async function c(e){return(await t.parseProviderOptions({provider:`anthropic`,providerOptions:e,schema:k}))?.citations?.enabled??!1}async function l(e){let n=await t.parseProviderOptions({provider:`anthropic`,providerOptions:e,schema:k});return{title:n?.title,context:n?.context}}for(let e=0;e<a.length;e++){let u=a[e],d=e===a.length-1,f=u.type;switch(f){case`system`:if(o!=null)throw new t.UnsupportedFunctionalityError({functionality:`Multiple system messages that are separated by user/assistant messages`});o=u.messages.map(({content:e,providerOptions:t})=>({type:`text`,text:e,cache_control:j(t)}));break;case`user`:{let e=[];for(let n of u.messages){let{role:r,content:a}=n;switch(r){case`user`:for(let r=0;r<a.length;r++){let o=a[r],s=r===a.length-1,u=j(o.providerOptions)??(s?j(n.providerOptions):void 0);switch(o.type){case`text`:e.push({type:`text`,text:o.text,cache_control:u});break;case`file`:if(o.mediaType.startsWith(`image/`))e.push({type:`image`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`base64`,media_type:o.mediaType===`image/*`?`image/jpeg`:o.mediaType,data:t.convertToBase64(o.data)},cache_control:u});else if(o.mediaType===`application/pdf`){i.add(`pdfs-2024-09-25`);let n=await c(o.providerOptions),r=await l(o.providerOptions);e.push({type:`document`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`base64`,media_type:`application/pdf`,data:t.convertToBase64(o.data)},title:r.title??o.filename,...r.context&&{context:r.context},...n&&{citations:{enabled:!0}},cache_control:u})}else if(o.mediaType===`text/plain`){let t=await c(o.providerOptions),n=await l(o.providerOptions);e.push({type:`document`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`text`,media_type:`text/plain`,data:oe(o.data)},title:n.title??o.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:u})}else throw new t.UnsupportedFunctionalityError({functionality:`media type: ${o.mediaType}`});break}}break;case`tool`:for(let r=0;r<a.length;r++){let i=a[r],o=r===a.length-1,s=j(i.providerOptions)??(o?j(n.providerOptions):void 0),c=i.output,l;switch(c.type){case`content`:l=c.value.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text,cache_control:void 0};case`media`:if(e.mediaType.startsWith(`image/`))return{type:`image`,source:{type:`base64`,media_type:e.mediaType,data:e.data},cache_control:void 0};throw new t.UnsupportedFunctionalityError({functionality:`media type: ${e.mediaType}`})}});break;case`text`:case`error-text`:l=c.value;break;case`json`:case`error-json`:default:l=JSON.stringify(c.value);break}e.push({type:`tool_result`,tool_use_id:i.toolCallId,content:l,is_error:c.type===`error-text`||c.type===`error-json`?!0:void 0,cache_control:s})}break;default:{let e=r;throw Error(`Unsupported role: ${e}`)}}}s.push({role:`user`,content:e});break}case`assistant`:{let e=[];for(let i=0;i<u.messages.length;i++){let a=u.messages[i],o=i===u.messages.length-1,{content:s}=a;for(let i=0;i<s.length;i++){let c=s[i],l=i===s.length-1,u=j(c.providerOptions)??(l?j(a.providerOptions):void 0);switch(c.type){case`text`:e.push({type:`text`,text:d&&o&&l?c.text.trim():c.text,cache_control:u});break;case`reasoning`:if(n){let n=await t.parseProviderOptions({provider:`anthropic`,providerOptions:c.providerOptions,schema:he});n==null?r.push({type:`other`,message:`unsupported reasoning metadata`}):n.signature==null?n.redactedData==null?r.push({type:`other`,message:`unsupported reasoning metadata`}):e.push({type:`redacted_thinking`,data:n.redactedData,cache_control:u}):e.push({type:`thinking`,thinking:c.text,signature:n.signature,cache_control:u})}else r.push({type:`other`,message:`sending reasoning content is disabled for this model`});break;case`tool-call`:if(c.providerExecuted){c.toolName===`code_execution`||c.toolName===`web_fetch`||c.toolName===`web_search`?e.push({type:`server_tool_use`,id:c.toolCallId,name:c.toolName,input:c.input,cache_control:u}):r.push({type:`other`,message:`provider executed tool call for tool ${c.toolName} is not supported`});break}e.push({type:`tool_use`,id:c.toolCallId,name:c.toolName,input:c.input,cache_control:u});break;case`tool-result`:if(c.toolName===`code_execution`){let t=c.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${c.toolName} is not supported`});break}let n=B.parse(t.value);e.push({type:`code_execution_tool_result`,tool_use_id:c.toolCallId,content:{type:n.type,stdout:n.stdout,stderr:n.stderr,return_code:n.return_code},cache_control:u});break}if(c.toolName===`web_fetch`){let t=c.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${c.toolName} is not supported`});break}let n=R.parse(t.value);e.push({type:`web_fetch_tool_result`,tool_use_id:c.toolCallId,content:{type:`web_fetch_result`,url:n.url,retrieved_at:n.retrievedAt,content:{type:`document`,title:n.content.title,citations:n.content.citations,source:{type:n.content.source.type,media_type:n.content.source.mediaType,data:n.content.source.data}}},cache_control:u});break}if(c.toolName===`web_search`){let t=c.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${c.toolName} is not supported`});break}let n=F.parse(t.value);e.push({type:`web_search_tool_result`,tool_use_id:c.toolCallId,content:n.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:u});break}r.push({type:`other`,message:`provider executed tool result for tool ${c.toolName} is not supported`});break}}}s.push({role:`assistant`,content:e});break}default:{let e=f;throw Error(`content type: ${e}`)}}}return{prompt:{system:o,messages:s},betas:i}}function ce(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 V({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 H={webSearchResult:r.z.object({type:r.z.literal(`web_search_result_location`),cited_text:r.z.string(),url:r.z.string(),title:r.z.string(),encrypted_index:r.z.string()}),pageLocation:r.z.object({type:r.z.literal(`page_location`),cited_text:r.z.string(),document_index:r.z.number(),document_title:r.z.string().nullable(),start_page_number:r.z.number(),end_page_number:r.z.number()}),charLocation:r.z.object({type:r.z.literal(`char_location`),cited_text:r.z.string(),document_index:r.z.number(),document_title:r.z.string().nullable(),start_char_index:r.z.number(),end_char_index:r.z.number()})},le=r.z.discriminatedUnion(`type`,[H.webSearchResult,H.pageLocation,H.charLocation]);r.z.discriminatedUnion(`type`,[H.pageLocation,H.charLocation]);function ue(e,t,n,r){if(e.type===`page_location`||e.type===`char_location`){let i=de(e,t,n);i&&r(i)}}function de(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 fe=class{constructor(e,n){this.specificationVersion=`v2`,this.modelId=e,this.config=n,this.generateId=n.generateId??t.generateId}supportsUrl(e){return e.protocol===`https:`}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:n=4096,temperature:r,topP:i,topK:a,frequencyPenalty:o,presencePenalty:s,stopSequences:c,responseFormat:l,seed:u,tools:d,toolChoice:f,providerOptions:p}){let m=[];o!=null&&m.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),s!=null&&m.push({type:`unsupported-setting`,setting:`presencePenalty`}),u!=null&&m.push({type:`unsupported-setting`,setting:`seed`}),l?.type===`json`&&(l.schema==null?m.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format requires a schema. The response format is ignored.`}):d!=null&&m.push({type:`unsupported-setting`,setting:`tools`,details:`JSON response format does not support tools. The provided tools are ignored.`}));let h=l?.type===`json`&&l.schema!=null?{type:`function`,name:`json`,description:`Respond with a JSON object.`,inputSchema:l.schema}:void 0,g=await t.parseProviderOptions({provider:`anthropic`,providerOptions:p,schema:A}),{prompt:_,betas:v}=await se({prompt:e,sendReasoning:g?.sendReasoning??!0,warnings:m}),y=g?.thinking?.type===`enabled`,b=g?.thinking?.budgetTokens,x={model:this.modelId,max_tokens:n,temperature:r,top_k:a,top_p:i,stop_sequences:c,...y&&{thinking:{type:`enabled`,budget_tokens:b}},system:_.system,messages:_.messages};if(y){if(b==null)throw new t.UnsupportedFunctionalityError({functionality:`thinking requires a budget`});x.temperature!=null&&(x.temperature=void 0,m.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported when thinking is enabled`})),a!=null&&(x.top_k=void 0,m.push({type:`unsupported-setting`,setting:`topK`,details:`topK is not supported when thinking is enabled`})),i!=null&&(x.top_p=void 0,m.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported when thinking is enabled`})),x.max_tokens=n+b}let{tools:S,toolChoice:C,toolWarnings:w,betas:T}=re(h==null?{tools:d??[],toolChoice:f,disableParallelToolUse:g?.disableParallelToolUse}:{tools:[h],toolChoice:{type:`tool`,toolName:h.name},disableParallelToolUse:!0});return{args:{...x,tools:S,tool_choice:C},warnings:[...m,...w],betas:new Set([...v,...T]),usesJsonResponseTool:h!=null}}async getHeaders({betas:e,headers:n}){return t.combineHeaders(await t.resolve(this.config.headers),e.size>0?{"anthropic-beta":Array.from(e).join(`,`)}:{},n)}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:n,warnings:r,betas:i,usesJsonResponseTool:a}=await this.getArgs(e),o=this.extractCitationDocuments(e.prompt),{responseHeaders:s,value:c,rawValue:l}=await t.postJsonToApi({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:i,headers:e.headers}),body:this.transformRequestBody(n),failedResponseHandler:O,successfulResponseHandler:t.createJsonResponseHandler(pe),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=[];for(let e of c.content)switch(e.type){case`text`:if(!a&&(u.push({type:`text`,text:e.text}),e.citations))for(let t of e.citations)ue(t,o,this.generateId,e=>u.push(e));break;case`thinking`:u.push({type:`reasoning`,text:e.thinking,providerMetadata:{anthropic:{signature:e.signature}}});break;case`redacted_thinking`:u.push({type:`reasoning`,text:``,providerMetadata:{anthropic:{redactedData:e.data}}});break;case`tool_use`:u.push(a?{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`)&&u.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`?u.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`&&u.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)){u.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)u.push({type:`source`,sourceType:`url`,id:this.generateId(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else u.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`?u.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`&&u.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:u,finishReason:V({finishReason:c.stop_reason,isJsonResponseFromTool:a}),usage:{inputTokens:c.usage.input_tokens,outputTokens:c.usage.output_tokens,totalTokens:c.usage.input_tokens+c.usage.output_tokens,cachedInputTokens:c.usage.cache_read_input_tokens??void 0},request:{body:n},response:{id:c.id??void 0,modelId:c.model??void 0,headers:s,body:l},warnings:r,providerMetadata:{anthropic:{usage:c.usage,cacheCreationInputTokens:c.usage.cache_creation_input_tokens??null,stopSequence:c.stop_sequence??null}}}}async doStream(e){let{args:n,warnings:r,betas:i,usesJsonResponseTool:a}=await this.getArgs(e),o=this.extractCitationDocuments(e.prompt),s={...n,stream:!0},{responseHeaders:c,value:l}=await t.postJsonToApi({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:i,headers:e.headers}),body:this.transformRequestBody(s),failedResponseHandler:O,successfulResponseHandler:t.createEventSourceResponseHandler(me),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=`unknown`,d={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},f={},p,m=null,h=null,g,_=this.generateId;return{stream:l.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:r})},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(g=e,e){case`text`:f[r.index]={type:`text`},n.enqueue({type:`text-start`,id:String(r.index)});return;case`thinking`:f[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index)});return;case`redacted_thinking`:f[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index),providerMetadata:{anthropic:{redactedData:r.content_block.data}}});return;case`tool_use`:f[r.index]=a?{type:`text`}:{type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``},n.enqueue(a?{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`)&&(f[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:_(),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(f[r.index]!=null){let e=f[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`:a||(n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue(e));break}delete f[r.index]}g=void 0;return;case`content_block_delta`:{let e=r.delta.type;switch(e){case`text_delta`:if(a)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`:g===`thinking`&&n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:``,providerMetadata:{anthropic:{signature:r.delta.signature}}});return;case`input_json_delta`:{let e=f[r.index],t=r.delta.partial_json;if(a){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;ue(e,o,_,e=>n.enqueue(e));return}default:{let t=e;throw Error(`Unsupported delta type: ${t}`)}}}case`message_start`:d.inputTokens=r.message.usage.input_tokens,d.cachedInputTokens=r.message.usage.cache_read_input_tokens??void 0,p={...r.message.usage},m=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`:d.outputTokens=r.usage.output_tokens,d.totalTokens=(d.inputTokens??0)+(r.usage.output_tokens??0),u=V({finishReason:r.delta.stop_reason,isJsonResponseFromTool:a}),h=r.delta.stop_sequence??null,p={...p,...r.usage};return;case`message_stop`:n.enqueue({type:`finish`,finishReason:u,usage:d,providerMetadata:{anthropic:{usage:p??null,cacheCreationInputTokens:m,stopSequence:h}}});return;case`error`:n.enqueue({type:`error`,error:r.error});return;default:{let e=r;throw Error(`Unsupported chunk type: ${e}`)}}}})),request:{body:s},response:{headers:c}}}},pe=r.z.object({type:r.z.literal(`message`),id:r.z.string().nullish(),model:r.z.string().nullish(),content:r.z.array(r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`text`),text:r.z.string(),citations:r.z.array(le).optional()}),r.z.object({type:r.z.literal(`thinking`),thinking:r.z.string(),signature:r.z.string()}),r.z.object({type:r.z.literal(`redacted_thinking`),data:r.z.string()}),r.z.object({type:r.z.literal(`tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.unknown()}),r.z.object({type:r.z.literal(`server_tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.record(r.z.string(),r.z.unknown()).nullish()}),r.z.object({type:r.z.literal(`web_fetch_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),retrieved_at:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string().nullable(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.object({type:r.z.literal(`text`),media_type:r.z.string(),data:r.z.string()})})}),r.z.object({type:r.z.literal(`web_fetch_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`web_search_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.array(r.z.object({type:r.z.literal(`web_search_result`),url:r.z.string(),title:r.z.string(),encrypted_content:r.z.string(),page_age:r.z.string().nullish()})),r.z.object({type:r.z.literal(`web_search_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`code_execution_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),r.z.object({type:r.z.literal(`code_execution_tool_result_error`),error_code:r.z.string()})])})])),stop_reason:r.z.string().nullish(),stop_sequence:r.z.string().nullish(),usage:r.z.looseObject({input_tokens:r.z.number(),output_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish(),cache_read_input_tokens:r.z.number().nullish()})}),me=r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`message_start`),message:r.z.object({id:r.z.string().nullish(),model:r.z.string().nullish(),usage:r.z.looseObject({input_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish(),cache_read_input_tokens:r.z.number().nullish()})})}),r.z.object({type:r.z.literal(`content_block_start`),index:r.z.number(),content_block:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`text`),text:r.z.string()}),r.z.object({type:r.z.literal(`thinking`),thinking:r.z.string()}),r.z.object({type:r.z.literal(`tool_use`),id:r.z.string(),name:r.z.string()}),r.z.object({type:r.z.literal(`redacted_thinking`),data:r.z.string()}),r.z.object({type:r.z.literal(`server_tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.record(r.z.string(),r.z.unknown()).nullish()}),r.z.object({type:r.z.literal(`web_fetch_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),retrieved_at:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string().nullable(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.object({type:r.z.literal(`text`),media_type:r.z.string(),data:r.z.string()})})}),r.z.object({type:r.z.literal(`web_fetch_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`web_search_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.array(r.z.object({type:r.z.literal(`web_search_result`),url:r.z.string(),title:r.z.string(),encrypted_content:r.z.string(),page_age:r.z.string().nullish()})),r.z.object({type:r.z.literal(`web_search_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`code_execution_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),r.z.object({type:r.z.literal(`code_execution_tool_result_error`),error_code:r.z.string()})])})])}),r.z.object({type:r.z.literal(`content_block_delta`),index:r.z.number(),delta:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`input_json_delta`),partial_json:r.z.string()}),r.z.object({type:r.z.literal(`text_delta`),text:r.z.string()}),r.z.object({type:r.z.literal(`thinking_delta`),thinking:r.z.string()}),r.z.object({type:r.z.literal(`signature_delta`),signature:r.z.string()}),r.z.object({type:r.z.literal(`citations_delta`),citation:le})])}),r.z.object({type:r.z.literal(`content_block_stop`),index:r.z.number()}),r.z.object({type:r.z.literal(`error`),error:r.z.object({type:r.z.string(),message:r.z.string()})}),r.z.object({type:r.z.literal(`message_delta`),delta:r.z.object({stop_reason:r.z.string().nullish(),stop_sequence:r.z.string().nullish()}),usage:r.z.looseObject({output_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish()})}),r.z.object({type:r.z.literal(`message_stop`)}),r.z.object({type:r.z.literal(`ping`)})]),he=r.z.object({signature:r.z.string().optional(),redactedData:r.z.string().optional()}),ge=t.createProviderDefinedToolFactory({id:`anthropic.bash_20241022`,name:`bash`,inputSchema:r.default.object({command:r.default.string(),restart:r.default.boolean().optional()})}),_e=t.createProviderDefinedToolFactory({id:`anthropic.bash_20250124`,name:`bash`,inputSchema:r.default.object({command:r.default.string(),restart:r.default.boolean().optional()})}),ve=t.createProviderDefinedToolFactory({id:`anthropic.computer_20241022`,name:`computer`,inputSchema:r.z.object({action:r.z.enum([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:r.z.array(r.z.number().int()).optional(),text:r.z.string().optional()})}),ye=t.createProviderDefinedToolFactory({id:`anthropic.computer_20250124`,name:`computer`,inputSchema:r.z.object({action:r.z.enum([`key`,`hold_key`,`type`,`cursor_position`,`mouse_move`,`left_mouse_down`,`left_mouse_up`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`triple_click`,`scroll`,`wait`,`screenshot`]),coordinate:r.z.tuple([r.z.number().int(),r.z.number().int()]).optional(),duration:r.z.number().optional(),scroll_amount:r.z.number().optional(),scroll_direction:r.z.enum([`up`,`down`,`left`,`right`]).optional(),start_coordinate:r.z.tuple([r.z.number().int(),r.z.number().int()]).optional(),text:r.z.string().optional()})}),U=t.createProviderDefinedToolFactory({id:`anthropic.text_editor_20241022`,name:`str_replace_editor`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),be=t.createProviderDefinedToolFactory({id:`anthropic.text_editor_20250124`,name:`str_replace_editor`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),xe=t.createProviderDefinedToolFactory({id:`anthropic.text_editor_20250429`,name:`str_replace_based_edit_tool`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),Se={bash_20241022:ge,bash_20250124:_e,codeExecution_20250522:ae,computer_20241022:ve,computer_20250124:ye,textEditor_20241022:U,textEditor_20250124:be,textEditor_20250429:xe,textEditor_20250728:ee,webFetch_20250910:z,webSearch_20250305:I};function Ce(e={}){let n=t.withoutTrailingSlash(e.baseURL)??`https://api.anthropic.com/v1`,r=()=>t.withUserAgentSuffix({"anthropic-version":`2023-06-01`,"x-api-key":t.loadApiKey({apiKey:e.apiKey,environmentVariableName:`ANTHROPIC_API_KEY`,description:`Anthropic`}),...e.headers},`ai-sdk/anthropic/${E}`),i=i=>new fe(i,{provider:`anthropic.messages`,baseURL:n,headers:r,fetch:e.fetch,generateId:e.generateId??t.generateId,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})}),a=function(e){if(new.target)throw Error(`The Anthropic model function cannot be called with the new keyword.`);return i(e)};return a.languageModel=i,a.chat=i,a.messages=i,a.textEmbeddingModel=e=>{throw new t.NoSuchModelError({modelId:e,modelType:`textEmbeddingModel`})},a.imageModel=e=>{throw new t.NoSuchModelError({modelId:e,modelType:`imageModel`})},a.tools=Se,a}var we=Ce(),Te=`2.0.17`,Ee=r.z.object({error:r.z.object({code:r.z.number().nullable(),message:r.z.string(),status:r.z.string()})}),W=t.createJsonErrorResponseHandler({errorSchema:Ee,errorToMessage:e=>e.error.message}),De=r.z.object({outputDimensionality:r.z.number().optional(),taskType:r.z.enum([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional()}),Oe=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:n,abortSignal:r,providerOptions:i}){let a=await t.parseProviderOptions({provider:`google`,providerOptions:i,schema:De});if(e.length>this.maxEmbeddingsPerCall)throw new t.TooManyEmbeddingValuesForCallError({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let o=t.combineHeaders(await t.resolve(this.config.headers),n);if(e.length===1){let{responseHeaders:n,value:i,rawValue:s}=await t.postJsonToApi({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:o,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType},failedResponseHandler:W,successfulResponseHandler:t.createJsonResponseHandler(Ae),abortSignal:r,fetch:this.config.fetch});return{embeddings:[i.embedding.values],usage:void 0,response:{headers:n,body:s}}}let{responseHeaders:s,value:c,rawValue:l}=await t.postJsonToApi({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:o,body:{requests:e.map(e=>({model:`models/${this.modelId}`,content:{role:`user`,parts:[{text:e}]},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType}))},failedResponseHandler:W,successfulResponseHandler:t.createJsonResponseHandler(ke),abortSignal:r,fetch:this.config.fetch});return{embeddings:c.embeddings.map(e=>e.values),usage:void 0,response:{headers:s,body:l}}}},ke=r.z.object({embeddings:r.z.array(r.z.object({values:r.z.array(r.z.number())}))}),Ae=r.z.object({embedding:r.z.object({values:r.z.array(r.z.number())})});function G(e){if(e==null||je(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]=G(n),e),{})),a&&(p.items=Array.isArray(a)?a.map(G):G(a)),o&&(p.allOf=o.map(G)),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=G(e[0]);typeof t==`object`&&(p.nullable=!0,Object.assign(p,t))}else p.anyOf=e.map(G),p.nullable=!0}else p.anyOf=s.map(G);return c&&(p.oneOf=c.map(G)),d!==void 0&&(p.minLength=d),p}function je(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}function Me(e,n){let r=[],i=[],a=!0,o=n?.isGemmaModel??!1;for(let{role:n,content:o}of e)switch(n){case`system`:if(!a)throw new t.UnsupportedFunctionalityError({functionality:`system messages are only supported at the beginning of the conversation`});r.push({text:o});break;case`user`:{a=!1;let e=[];for(let n of o)switch(n.type){case`text`:e.push({text:n.text});break;case`file`:{let r=n.mediaType===`image/*`?`image/jpeg`:n.mediaType;e.push(n.data instanceof URL?{fileData:{mimeType:r,fileUri:n.data.toString()}}:{inlineData:{mimeType:r,data:t.convertToBase64(n.data)}});break}}i.push({role:`user`,parts:e});break}case`assistant`:a=!1,i.push({role:`model`,parts:o.map(e=>{switch(e.type){case`text`:return e.text.length===0?void 0:{text:e.text,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`reasoning`:return e.text.length===0?void 0:{text:e.text,thought:!0,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`file`:if(e.mediaType!==`image/png`)throw new t.UnsupportedFunctionalityError({functionality:`Only PNG images are supported in assistant messages`});if(e.data instanceof URL)throw new t.UnsupportedFunctionalityError({functionality:`File data URLs in assistant messages are not supported`});return{inlineData:{mimeType:e.mediaType,data:t.convertToBase64(e.data)}};case`tool-call`:return{functionCall:{name:e.toolName,args:e.input},thoughtSignature:e.providerOptions?.google?.thoughtSignature}}}).filter(e=>e!==void 0)});break;case`tool`:{a=!1;let e=[];for(let t of o){let n=t.output;if(n.type===`content`)for(let r of n.value)switch(r.type){case`text`:e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:r.text}}});break;case`media`:e.push({inlineData:{mimeType:r.mediaType,data:r.data}},{text:`Tool executed successfully and returned this image as a response`});break;default:e.push({text:JSON.stringify(r)});break}else e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:n.value}}})}i.push({role:`user`,parts:e});break}}if(o&&r.length>0&&i.length>0&&i[0].role===`user`){let e=r.map(e=>e.text).join(`
1
+ const e=require(`../chunk-iXuH7AlR.cjs`),t=require(`../index.node-BrLfthBj.cjs`);require(`../token-error-BoNG8ooW.cjs`),require(`../esm-0UNjvroT.cjs`);const n=require(`../build-EgdtUZTI.cjs`);let r=require(`zod/v4`);r=e.__toESM(r),require(`zod/v3`);let i=require(`node:buffer`);i=e.__toESM(i);let a=require(`node:fs`);a=e.__toESM(a);let o=require(`node:url`);o=e.__toESM(o);let s=require(`node:stream`);s=e.__toESM(s);let c=require(`node:util`);c=e.__toESM(c);let l=require(`node:crypto`);l=e.__toESM(l);let u=require(`http`);u=e.__toESM(u);let d=require(`path`);d=e.__toESM(d);let f=require(`fs`);f=e.__toESM(f);let p=require(`ai`);p=e.__toESM(p);let m=require(`fs/promises`);m=e.__toESM(m);let h=require(`child_process`);h=e.__toESM(h);let g=require(`react`);g=e.__toESM(g);let _=require(`node:module`);_=e.__toESM(_);let v=require(`zod`);v=e.__toESM(v);let y=require(`node:path`);y=e.__toESM(y);let b=require(`node:process`);b=e.__toESM(b);let x=require(`node:readline`);x=e.__toESM(x);let S=require(`node:child_process`);S=e.__toESM(S);let C=require(`node:fs/promises`);C=e.__toESM(C);let w=require(`node:os`);w=e.__toESM(w),require(`@blink-sdk/compute-protocol/client`);let T=require(`@blink-sdk/compute-protocol/transport`);T=e.__toESM(T);var E=`2.0.23`,D=r.z.object({type:r.z.literal(`error`),error:r.z.object({type:r.z.string(),message:r.z.string()})}),O=t.createJsonErrorResponseHandler({errorSchema:D,errorToMessage:e=>e.error.message}),k=r.z.object({citations:r.z.object({enabled:r.z.boolean()}).optional(),title:r.z.string().optional(),context:r.z.string().optional()}),A=r.z.object({sendReasoning:r.z.boolean().optional(),thinking:r.z.object({type:r.z.union([r.z.literal(`enabled`),r.z.literal(`disabled`)]),budgetTokens:r.z.number().optional()}).optional(),disableParallelToolUse:r.z.boolean().optional(),cacheControl:r.z.object({type:r.z.literal(`ephemeral`),ttl:r.z.union([r.z.literal(`5m`),r.z.literal(`1h`)]).optional()}).optional()});function j(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var M=r.z.object({maxCharacters:r.z.number().optional()}),N=t.createProviderDefinedToolFactory({id:`anthropic.text_editor_20250728`,name:`str_replace_based_edit_tool`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),ee=(e={})=>N(e),P=r.z.object({maxUses:r.z.number().optional(),allowedDomains:r.z.array(r.z.string()).optional(),blockedDomains:r.z.array(r.z.string()).optional(),userLocation:r.z.object({type:r.z.literal(`approximate`),city:r.z.string().optional(),region:r.z.string().optional(),country:r.z.string().optional(),timezone:r.z.string().optional()}).optional()}),F=r.z.array(r.z.object({url:r.z.string(),title:r.z.string(),pageAge:r.z.string().nullable(),encryptedContent:r.z.string(),type:r.z.literal(`web_search_result`)})),te=t.createProviderDefinedToolFactoryWithOutputSchema({id:`anthropic.web_search_20250305`,name:`web_search`,inputSchema:r.z.object({query:r.z.string()}),outputSchema:F}),I=(e={})=>te(e),L=r.z.object({maxUses:r.z.number().optional(),allowedDomains:r.z.array(r.z.string()).optional(),blockedDomains:r.z.array(r.z.string()).optional(),citations:r.z.object({enabled:r.z.boolean()}).optional(),maxContentTokens:r.z.number().optional()}),R=r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.union([r.z.object({type:r.z.literal(`base64`),mediaType:r.z.literal(`application/pdf`),data:r.z.string()}),r.z.object({type:r.z.literal(`text`),mediaType:r.z.literal(`text/plain`),data:r.z.string()})])}),retrievedAt:r.z.string().nullable()}),ne=t.createProviderDefinedToolFactoryWithOutputSchema({id:`anthropic.web_fetch_20250910`,name:`web_fetch`,inputSchema:r.z.object({url:r.z.string()}),outputSchema:R}),z=(e={})=>ne(e);function re({tools:e,toolChoice:n,disableParallelToolUse:r}){e=e?.length?e:void 0;let i=[],a=new Set;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:a};let o=[];for(let t of e)switch(t.type){case`function`:{let e=j(t.providerOptions);o.push({name:t.name,description:t.description,input_schema:t.inputSchema,cache_control:e});break}case`provider-defined`:switch(t.id){case`anthropic.code_execution_20250522`:a.add(`code-execution-2025-05-22`),o.push({type:`code_execution_20250522`,name:`code_execution`});break;case`anthropic.computer_20250124`:a.add(`computer-use-2025-01-24`),o.push({name:`computer`,type:`computer_20250124`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.computer_20241022`:a.add(`computer-use-2024-10-22`),o.push({name:`computer`,type:`computer_20241022`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.text_editor_20250124`:a.add(`computer-use-2025-01-24`),o.push({name:`str_replace_editor`,type:`text_editor_20250124`});break;case`anthropic.text_editor_20241022`:a.add(`computer-use-2024-10-22`),o.push({name:`str_replace_editor`,type:`text_editor_20241022`});break;case`anthropic.text_editor_20250429`:a.add(`computer-use-2025-01-24`),o.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`});break;case`anthropic.text_editor_20250728`:{let e=M.parse(t.args);o.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250728`,max_characters:e.maxCharacters});break}case`anthropic.bash_20250124`:a.add(`computer-use-2025-01-24`),o.push({name:`bash`,type:`bash_20250124`});break;case`anthropic.bash_20241022`:a.add(`computer-use-2024-10-22`),o.push({name:`bash`,type:`bash_20241022`});break;case`anthropic.web_fetch_20250910`:{a.add(`web-fetch-2025-09-10`);let e=L.parse(t.args);o.push({type:`web_fetch_20250910`,name:`web_fetch`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens});break}case`anthropic.web_search_20250305`:{let e=P.parse(t.args);o.push({type:`web_search_20250305`,name:`web_search`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation});break}default:i.push({type:`unsupported-tool`,tool:t});break}break;default:i.push({type:`unsupported-tool`,tool:t});break}if(n==null)return{tools:o,toolChoice:r?{type:`auto`,disable_parallel_tool_use:r}:void 0,toolWarnings:i,betas:a};let s=n.type;switch(s){case`auto`:return{tools:o,toolChoice:{type:`auto`,disable_parallel_tool_use:r},toolWarnings:i,betas:a};case`required`:return{tools:o,toolChoice:{type:`any`,disable_parallel_tool_use:r},toolWarnings:i,betas:a};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:a};case`tool`:return{tools:o,toolChoice:{type:`tool`,name:n.toolName,disable_parallel_tool_use:r},toolWarnings:i,betas:a};default:throw new t.UnsupportedFunctionalityError({functionality:`tool choice type: ${s}`})}}var B=r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),ie=t.createProviderDefinedToolFactoryWithOutputSchema({id:`anthropic.code_execution_20250522`,name:`code_execution`,inputSchema:r.z.object({code:r.z.string()}),outputSchema:B}),ae=(e={})=>ie(e);function oe(e){if(typeof e==`string`)return Buffer.from(e,`base64`).toString(`utf-8`);if(e instanceof Uint8Array)return new TextDecoder().decode(e);throw e instanceof URL?new t.UnsupportedFunctionalityError({functionality:`URL-based text documents are not supported for citations`}):new t.UnsupportedFunctionalityError({functionality:`unsupported data type for text documents: ${typeof e}`})}async function se({prompt:e,sendReasoning:n,warnings:r}){let i=new Set,a=ce(e),o,s=[];async function c(e){return(await t.parseProviderOptions({provider:`anthropic`,providerOptions:e,schema:k}))?.citations?.enabled??!1}async function l(e){let n=await t.parseProviderOptions({provider:`anthropic`,providerOptions:e,schema:k});return{title:n?.title,context:n?.context}}for(let e=0;e<a.length;e++){let u=a[e],d=e===a.length-1,f=u.type;switch(f){case`system`:if(o!=null)throw new t.UnsupportedFunctionalityError({functionality:`Multiple system messages that are separated by user/assistant messages`});o=u.messages.map(({content:e,providerOptions:t})=>({type:`text`,text:e,cache_control:j(t)}));break;case`user`:{let e=[];for(let n of u.messages){let{role:r,content:a}=n;switch(r){case`user`:for(let r=0;r<a.length;r++){let o=a[r],s=r===a.length-1,u=j(o.providerOptions)??(s?j(n.providerOptions):void 0);switch(o.type){case`text`:e.push({type:`text`,text:o.text,cache_control:u});break;case`file`:if(o.mediaType.startsWith(`image/`))e.push({type:`image`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`base64`,media_type:o.mediaType===`image/*`?`image/jpeg`:o.mediaType,data:t.convertToBase64(o.data)},cache_control:u});else if(o.mediaType===`application/pdf`){i.add(`pdfs-2024-09-25`);let n=await c(o.providerOptions),r=await l(o.providerOptions);e.push({type:`document`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`base64`,media_type:`application/pdf`,data:t.convertToBase64(o.data)},title:r.title??o.filename,...r.context&&{context:r.context},...n&&{citations:{enabled:!0}},cache_control:u})}else if(o.mediaType===`text/plain`){let t=await c(o.providerOptions),n=await l(o.providerOptions);e.push({type:`document`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`text`,media_type:`text/plain`,data:oe(o.data)},title:n.title??o.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:u})}else throw new t.UnsupportedFunctionalityError({functionality:`media type: ${o.mediaType}`});break}}break;case`tool`:for(let r=0;r<a.length;r++){let i=a[r],o=r===a.length-1,s=j(i.providerOptions)??(o?j(n.providerOptions):void 0),c=i.output,l;switch(c.type){case`content`:l=c.value.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text,cache_control:void 0};case`media`:if(e.mediaType.startsWith(`image/`))return{type:`image`,source:{type:`base64`,media_type:e.mediaType,data:e.data},cache_control:void 0};throw new t.UnsupportedFunctionalityError({functionality:`media type: ${e.mediaType}`})}});break;case`text`:case`error-text`:l=c.value;break;case`json`:case`error-json`:default:l=JSON.stringify(c.value);break}e.push({type:`tool_result`,tool_use_id:i.toolCallId,content:l,is_error:c.type===`error-text`||c.type===`error-json`?!0:void 0,cache_control:s})}break;default:{let e=r;throw Error(`Unsupported role: ${e}`)}}}s.push({role:`user`,content:e});break}case`assistant`:{let e=[];for(let i=0;i<u.messages.length;i++){let a=u.messages[i],o=i===u.messages.length-1,{content:s}=a;for(let i=0;i<s.length;i++){let c=s[i],l=i===s.length-1,u=j(c.providerOptions)??(l?j(a.providerOptions):void 0);switch(c.type){case`text`:e.push({type:`text`,text:d&&o&&l?c.text.trim():c.text,cache_control:u});break;case`reasoning`:if(n){let n=await t.parseProviderOptions({provider:`anthropic`,providerOptions:c.providerOptions,schema:he});n==null?r.push({type:`other`,message:`unsupported reasoning metadata`}):n.signature==null?n.redactedData==null?r.push({type:`other`,message:`unsupported reasoning metadata`}):e.push({type:`redacted_thinking`,data:n.redactedData,cache_control:u}):e.push({type:`thinking`,thinking:c.text,signature:n.signature,cache_control:u})}else r.push({type:`other`,message:`sending reasoning content is disabled for this model`});break;case`tool-call`:if(c.providerExecuted){c.toolName===`code_execution`||c.toolName===`web_fetch`||c.toolName===`web_search`?e.push({type:`server_tool_use`,id:c.toolCallId,name:c.toolName,input:c.input,cache_control:u}):r.push({type:`other`,message:`provider executed tool call for tool ${c.toolName} is not supported`});break}e.push({type:`tool_use`,id:c.toolCallId,name:c.toolName,input:c.input,cache_control:u});break;case`tool-result`:if(c.toolName===`code_execution`){let t=c.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${c.toolName} is not supported`});break}let n=B.parse(t.value);e.push({type:`code_execution_tool_result`,tool_use_id:c.toolCallId,content:{type:n.type,stdout:n.stdout,stderr:n.stderr,return_code:n.return_code},cache_control:u});break}if(c.toolName===`web_fetch`){let t=c.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${c.toolName} is not supported`});break}let n=R.parse(t.value);e.push({type:`web_fetch_tool_result`,tool_use_id:c.toolCallId,content:{type:`web_fetch_result`,url:n.url,retrieved_at:n.retrievedAt,content:{type:`document`,title:n.content.title,citations:n.content.citations,source:{type:n.content.source.type,media_type:n.content.source.mediaType,data:n.content.source.data}}},cache_control:u});break}if(c.toolName===`web_search`){let t=c.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${c.toolName} is not supported`});break}let n=F.parse(t.value);e.push({type:`web_search_tool_result`,tool_use_id:c.toolCallId,content:n.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:u});break}r.push({type:`other`,message:`provider executed tool result for tool ${c.toolName} is not supported`});break}}}s.push({role:`assistant`,content:e});break}default:{let e=f;throw Error(`content type: ${e}`)}}}return{prompt:{system:o,messages:s},betas:i}}function ce(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 V({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 H={webSearchResult:r.z.object({type:r.z.literal(`web_search_result_location`),cited_text:r.z.string(),url:r.z.string(),title:r.z.string(),encrypted_index:r.z.string()}),pageLocation:r.z.object({type:r.z.literal(`page_location`),cited_text:r.z.string(),document_index:r.z.number(),document_title:r.z.string().nullable(),start_page_number:r.z.number(),end_page_number:r.z.number()}),charLocation:r.z.object({type:r.z.literal(`char_location`),cited_text:r.z.string(),document_index:r.z.number(),document_title:r.z.string().nullable(),start_char_index:r.z.number(),end_char_index:r.z.number()})},le=r.z.discriminatedUnion(`type`,[H.webSearchResult,H.pageLocation,H.charLocation]);r.z.discriminatedUnion(`type`,[H.pageLocation,H.charLocation]);function ue(e,t,n,r){if(e.type===`page_location`||e.type===`char_location`){let i=de(e,t,n);i&&r(i)}}function de(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 fe=class{constructor(e,n){this.specificationVersion=`v2`,this.modelId=e,this.config=n,this.generateId=n.generateId??t.generateId}supportsUrl(e){return e.protocol===`https:`}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:n=4096,temperature:r,topP:i,topK:a,frequencyPenalty:o,presencePenalty:s,stopSequences:c,responseFormat:l,seed:u,tools:d,toolChoice:f,providerOptions:p}){let m=[];o!=null&&m.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),s!=null&&m.push({type:`unsupported-setting`,setting:`presencePenalty`}),u!=null&&m.push({type:`unsupported-setting`,setting:`seed`}),l?.type===`json`&&(l.schema==null?m.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format requires a schema. The response format is ignored.`}):d!=null&&m.push({type:`unsupported-setting`,setting:`tools`,details:`JSON response format does not support tools. The provided tools are ignored.`}));let h=l?.type===`json`&&l.schema!=null?{type:`function`,name:`json`,description:`Respond with a JSON object.`,inputSchema:l.schema}:void 0,g=await t.parseProviderOptions({provider:`anthropic`,providerOptions:p,schema:A}),{prompt:_,betas:v}=await se({prompt:e,sendReasoning:g?.sendReasoning??!0,warnings:m}),y=g?.thinking?.type===`enabled`,b=g?.thinking?.budgetTokens,x={model:this.modelId,max_tokens:n,temperature:r,top_k:a,top_p:i,stop_sequences:c,...y&&{thinking:{type:`enabled`,budget_tokens:b}},system:_.system,messages:_.messages};if(y){if(b==null)throw new t.UnsupportedFunctionalityError({functionality:`thinking requires a budget`});x.temperature!=null&&(x.temperature=void 0,m.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported when thinking is enabled`})),a!=null&&(x.top_k=void 0,m.push({type:`unsupported-setting`,setting:`topK`,details:`topK is not supported when thinking is enabled`})),i!=null&&(x.top_p=void 0,m.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported when thinking is enabled`})),x.max_tokens=n+b}let{tools:S,toolChoice:C,toolWarnings:w,betas:T}=re(h==null?{tools:d??[],toolChoice:f,disableParallelToolUse:g?.disableParallelToolUse}:{tools:[h],toolChoice:{type:`tool`,toolName:h.name},disableParallelToolUse:!0});return{args:{...x,tools:S,tool_choice:C},warnings:[...m,...w],betas:new Set([...v,...T]),usesJsonResponseTool:h!=null}}async getHeaders({betas:e,headers:n}){return t.combineHeaders(await t.resolve(this.config.headers),e.size>0?{"anthropic-beta":Array.from(e).join(`,`)}:{},n)}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:n,warnings:r,betas:i,usesJsonResponseTool:a}=await this.getArgs(e),o=this.extractCitationDocuments(e.prompt),{responseHeaders:s,value:c,rawValue:l}=await t.postJsonToApi({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:i,headers:e.headers}),body:this.transformRequestBody(n),failedResponseHandler:O,successfulResponseHandler:t.createJsonResponseHandler(pe),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=[];for(let e of c.content)switch(e.type){case`text`:if(!a&&(u.push({type:`text`,text:e.text}),e.citations))for(let t of e.citations)ue(t,o,this.generateId,e=>u.push(e));break;case`thinking`:u.push({type:`reasoning`,text:e.thinking,providerMetadata:{anthropic:{signature:e.signature}}});break;case`redacted_thinking`:u.push({type:`reasoning`,text:``,providerMetadata:{anthropic:{redactedData:e.data}}});break;case`tool_use`:u.push(a?{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`)&&u.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`?u.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`&&u.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)){u.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)u.push({type:`source`,sourceType:`url`,id:this.generateId(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else u.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`?u.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`&&u.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:u,finishReason:V({finishReason:c.stop_reason,isJsonResponseFromTool:a}),usage:{inputTokens:c.usage.input_tokens,outputTokens:c.usage.output_tokens,totalTokens:c.usage.input_tokens+c.usage.output_tokens,cachedInputTokens:c.usage.cache_read_input_tokens??void 0},request:{body:n},response:{id:c.id??void 0,modelId:c.model??void 0,headers:s,body:l},warnings:r,providerMetadata:{anthropic:{usage:c.usage,cacheCreationInputTokens:c.usage.cache_creation_input_tokens??null,stopSequence:c.stop_sequence??null}}}}async doStream(e){let{args:n,warnings:r,betas:i,usesJsonResponseTool:a}=await this.getArgs(e),o=this.extractCitationDocuments(e.prompt),s={...n,stream:!0},{responseHeaders:c,value:l}=await t.postJsonToApi({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:i,headers:e.headers}),body:this.transformRequestBody(s),failedResponseHandler:O,successfulResponseHandler:t.createEventSourceResponseHandler(me),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=`unknown`,d={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},f={},p,m=null,h=null,g,_=this.generateId;return{stream:l.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:r})},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(g=e,e){case`text`:f[r.index]={type:`text`},n.enqueue({type:`text-start`,id:String(r.index)});return;case`thinking`:f[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index)});return;case`redacted_thinking`:f[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index),providerMetadata:{anthropic:{redactedData:r.content_block.data}}});return;case`tool_use`:f[r.index]=a?{type:`text`}:{type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``},n.enqueue(a?{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`)&&(f[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:_(),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(f[r.index]!=null){let e=f[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`:a||(n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue(e));break}delete f[r.index]}g=void 0;return;case`content_block_delta`:{let e=r.delta.type;switch(e){case`text_delta`:if(a)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`:g===`thinking`&&n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:``,providerMetadata:{anthropic:{signature:r.delta.signature}}});return;case`input_json_delta`:{let e=f[r.index],t=r.delta.partial_json;if(a){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;ue(e,o,_,e=>n.enqueue(e));return}default:{let t=e;throw Error(`Unsupported delta type: ${t}`)}}}case`message_start`:d.inputTokens=r.message.usage.input_tokens,d.cachedInputTokens=r.message.usage.cache_read_input_tokens??void 0,p={...r.message.usage},m=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`:d.outputTokens=r.usage.output_tokens,d.totalTokens=(d.inputTokens??0)+(r.usage.output_tokens??0),u=V({finishReason:r.delta.stop_reason,isJsonResponseFromTool:a}),h=r.delta.stop_sequence??null,p={...p,...r.usage};return;case`message_stop`:n.enqueue({type:`finish`,finishReason:u,usage:d,providerMetadata:{anthropic:{usage:p??null,cacheCreationInputTokens:m,stopSequence:h}}});return;case`error`:n.enqueue({type:`error`,error:r.error});return;default:{let e=r;throw Error(`Unsupported chunk type: ${e}`)}}}})),request:{body:s},response:{headers:c}}}},pe=r.z.object({type:r.z.literal(`message`),id:r.z.string().nullish(),model:r.z.string().nullish(),content:r.z.array(r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`text`),text:r.z.string(),citations:r.z.array(le).optional()}),r.z.object({type:r.z.literal(`thinking`),thinking:r.z.string(),signature:r.z.string()}),r.z.object({type:r.z.literal(`redacted_thinking`),data:r.z.string()}),r.z.object({type:r.z.literal(`tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.unknown()}),r.z.object({type:r.z.literal(`server_tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.record(r.z.string(),r.z.unknown()).nullish()}),r.z.object({type:r.z.literal(`web_fetch_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),retrieved_at:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string().nullable(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.object({type:r.z.literal(`text`),media_type:r.z.string(),data:r.z.string()})})}),r.z.object({type:r.z.literal(`web_fetch_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`web_search_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.array(r.z.object({type:r.z.literal(`web_search_result`),url:r.z.string(),title:r.z.string(),encrypted_content:r.z.string(),page_age:r.z.string().nullish()})),r.z.object({type:r.z.literal(`web_search_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`code_execution_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),r.z.object({type:r.z.literal(`code_execution_tool_result_error`),error_code:r.z.string()})])})])),stop_reason:r.z.string().nullish(),stop_sequence:r.z.string().nullish(),usage:r.z.looseObject({input_tokens:r.z.number(),output_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish(),cache_read_input_tokens:r.z.number().nullish()})}),me=r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`message_start`),message:r.z.object({id:r.z.string().nullish(),model:r.z.string().nullish(),usage:r.z.looseObject({input_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish(),cache_read_input_tokens:r.z.number().nullish()})})}),r.z.object({type:r.z.literal(`content_block_start`),index:r.z.number(),content_block:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`text`),text:r.z.string()}),r.z.object({type:r.z.literal(`thinking`),thinking:r.z.string()}),r.z.object({type:r.z.literal(`tool_use`),id:r.z.string(),name:r.z.string()}),r.z.object({type:r.z.literal(`redacted_thinking`),data:r.z.string()}),r.z.object({type:r.z.literal(`server_tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.record(r.z.string(),r.z.unknown()).nullish()}),r.z.object({type:r.z.literal(`web_fetch_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),retrieved_at:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string().nullable(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.object({type:r.z.literal(`text`),media_type:r.z.string(),data:r.z.string()})})}),r.z.object({type:r.z.literal(`web_fetch_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`web_search_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.array(r.z.object({type:r.z.literal(`web_search_result`),url:r.z.string(),title:r.z.string(),encrypted_content:r.z.string(),page_age:r.z.string().nullish()})),r.z.object({type:r.z.literal(`web_search_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`code_execution_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),r.z.object({type:r.z.literal(`code_execution_tool_result_error`),error_code:r.z.string()})])})])}),r.z.object({type:r.z.literal(`content_block_delta`),index:r.z.number(),delta:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`input_json_delta`),partial_json:r.z.string()}),r.z.object({type:r.z.literal(`text_delta`),text:r.z.string()}),r.z.object({type:r.z.literal(`thinking_delta`),thinking:r.z.string()}),r.z.object({type:r.z.literal(`signature_delta`),signature:r.z.string()}),r.z.object({type:r.z.literal(`citations_delta`),citation:le})])}),r.z.object({type:r.z.literal(`content_block_stop`),index:r.z.number()}),r.z.object({type:r.z.literal(`error`),error:r.z.object({type:r.z.string(),message:r.z.string()})}),r.z.object({type:r.z.literal(`message_delta`),delta:r.z.object({stop_reason:r.z.string().nullish(),stop_sequence:r.z.string().nullish()}),usage:r.z.looseObject({output_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish()})}),r.z.object({type:r.z.literal(`message_stop`)}),r.z.object({type:r.z.literal(`ping`)})]),he=r.z.object({signature:r.z.string().optional(),redactedData:r.z.string().optional()}),ge=t.createProviderDefinedToolFactory({id:`anthropic.bash_20241022`,name:`bash`,inputSchema:r.default.object({command:r.default.string(),restart:r.default.boolean().optional()})}),_e=t.createProviderDefinedToolFactory({id:`anthropic.bash_20250124`,name:`bash`,inputSchema:r.default.object({command:r.default.string(),restart:r.default.boolean().optional()})}),ve=t.createProviderDefinedToolFactory({id:`anthropic.computer_20241022`,name:`computer`,inputSchema:r.z.object({action:r.z.enum([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:r.z.array(r.z.number().int()).optional(),text:r.z.string().optional()})}),ye=t.createProviderDefinedToolFactory({id:`anthropic.computer_20250124`,name:`computer`,inputSchema:r.z.object({action:r.z.enum([`key`,`hold_key`,`type`,`cursor_position`,`mouse_move`,`left_mouse_down`,`left_mouse_up`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`triple_click`,`scroll`,`wait`,`screenshot`]),coordinate:r.z.tuple([r.z.number().int(),r.z.number().int()]).optional(),duration:r.z.number().optional(),scroll_amount:r.z.number().optional(),scroll_direction:r.z.enum([`up`,`down`,`left`,`right`]).optional(),start_coordinate:r.z.tuple([r.z.number().int(),r.z.number().int()]).optional(),text:r.z.string().optional()})}),U=t.createProviderDefinedToolFactory({id:`anthropic.text_editor_20241022`,name:`str_replace_editor`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),be=t.createProviderDefinedToolFactory({id:`anthropic.text_editor_20250124`,name:`str_replace_editor`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),xe=t.createProviderDefinedToolFactory({id:`anthropic.text_editor_20250429`,name:`str_replace_based_edit_tool`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),Se={bash_20241022:ge,bash_20250124:_e,codeExecution_20250522:ae,computer_20241022:ve,computer_20250124:ye,textEditor_20241022:U,textEditor_20250124:be,textEditor_20250429:xe,textEditor_20250728:ee,webFetch_20250910:z,webSearch_20250305:I};function Ce(e={}){let n=t.withoutTrailingSlash(e.baseURL)??`https://api.anthropic.com/v1`,r=()=>t.withUserAgentSuffix({"anthropic-version":`2023-06-01`,"x-api-key":t.loadApiKey({apiKey:e.apiKey,environmentVariableName:`ANTHROPIC_API_KEY`,description:`Anthropic`}),...e.headers},`ai-sdk/anthropic/${E}`),i=i=>new fe(i,{provider:`anthropic.messages`,baseURL:n,headers:r,fetch:e.fetch,generateId:e.generateId??t.generateId,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})}),a=function(e){if(new.target)throw Error(`The Anthropic model function cannot be called with the new keyword.`);return i(e)};return a.languageModel=i,a.chat=i,a.messages=i,a.textEmbeddingModel=e=>{throw new t.NoSuchModelError({modelId:e,modelType:`textEmbeddingModel`})},a.imageModel=e=>{throw new t.NoSuchModelError({modelId:e,modelType:`imageModel`})},a.tools=Se,a}var we=Ce(),Te=`2.0.17`,Ee=r.z.object({error:r.z.object({code:r.z.number().nullable(),message:r.z.string(),status:r.z.string()})}),W=t.createJsonErrorResponseHandler({errorSchema:Ee,errorToMessage:e=>e.error.message}),De=r.z.object({outputDimensionality:r.z.number().optional(),taskType:r.z.enum([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional()}),Oe=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:n,abortSignal:r,providerOptions:i}){let a=await t.parseProviderOptions({provider:`google`,providerOptions:i,schema:De});if(e.length>this.maxEmbeddingsPerCall)throw new t.TooManyEmbeddingValuesForCallError({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let o=t.combineHeaders(await t.resolve(this.config.headers),n);if(e.length===1){let{responseHeaders:n,value:i,rawValue:s}=await t.postJsonToApi({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:o,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType},failedResponseHandler:W,successfulResponseHandler:t.createJsonResponseHandler(Ae),abortSignal:r,fetch:this.config.fetch});return{embeddings:[i.embedding.values],usage:void 0,response:{headers:n,body:s}}}let{responseHeaders:s,value:c,rawValue:l}=await t.postJsonToApi({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:o,body:{requests:e.map(e=>({model:`models/${this.modelId}`,content:{role:`user`,parts:[{text:e}]},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType}))},failedResponseHandler:W,successfulResponseHandler:t.createJsonResponseHandler(ke),abortSignal:r,fetch:this.config.fetch});return{embeddings:c.embeddings.map(e=>e.values),usage:void 0,response:{headers:s,body:l}}}},ke=r.z.object({embeddings:r.z.array(r.z.object({values:r.z.array(r.z.number())}))}),Ae=r.z.object({embedding:r.z.object({values:r.z.array(r.z.number())})});function G(e){if(e==null||je(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]=G(n),e),{})),a&&(p.items=Array.isArray(a)?a.map(G):G(a)),o&&(p.allOf=o.map(G)),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=G(e[0]);typeof t==`object`&&(p.nullable=!0,Object.assign(p,t))}else p.anyOf=e.map(G),p.nullable=!0}else p.anyOf=s.map(G);return c&&(p.oneOf=c.map(G)),d!==void 0&&(p.minLength=d),p}function je(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}function Me(e,n){let r=[],i=[],a=!0,o=n?.isGemmaModel??!1;for(let{role:n,content:o}of e)switch(n){case`system`:if(!a)throw new t.UnsupportedFunctionalityError({functionality:`system messages are only supported at the beginning of the conversation`});r.push({text:o});break;case`user`:{a=!1;let e=[];for(let n of o)switch(n.type){case`text`:e.push({text:n.text});break;case`file`:{let r=n.mediaType===`image/*`?`image/jpeg`:n.mediaType;e.push(n.data instanceof URL?{fileData:{mimeType:r,fileUri:n.data.toString()}}:{inlineData:{mimeType:r,data:t.convertToBase64(n.data)}});break}}i.push({role:`user`,parts:e});break}case`assistant`:a=!1,i.push({role:`model`,parts:o.map(e=>{switch(e.type){case`text`:return e.text.length===0?void 0:{text:e.text,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`reasoning`:return e.text.length===0?void 0:{text:e.text,thought:!0,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`file`:if(e.mediaType!==`image/png`)throw new t.UnsupportedFunctionalityError({functionality:`Only PNG images are supported in assistant messages`});if(e.data instanceof URL)throw new t.UnsupportedFunctionalityError({functionality:`File data URLs in assistant messages are not supported`});return{inlineData:{mimeType:e.mediaType,data:t.convertToBase64(e.data)}};case`tool-call`:return{functionCall:{name:e.toolName,args:e.input},thoughtSignature:e.providerOptions?.google?.thoughtSignature}}}).filter(e=>e!==void 0)});break;case`tool`:{a=!1;let e=[];for(let t of o){let n=t.output;if(n.type===`content`)for(let r of n.value)switch(r.type){case`text`:e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:r.text}}});break;case`media`:e.push({inlineData:{mimeType:r.mediaType,data:r.data}},{text:`Tool executed successfully and returned this image as a response`});break;default:e.push({text:JSON.stringify(r)});break}else e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:n.value}}})}i.push({role:`user`,parts:e});break}}if(o&&r.length>0&&i.length>0&&i[0].role===`user`){let e=r.map(e=>e.text).join(`
2
2
 
3
3
  `);i[0].parts.unshift({text:e+`
4
4
 
@@ -139,7 +139,7 @@ ${zl}${t.trimStart()}`),n=3+(0,c.stripVTControlCharacters)(t.trimStart()).length
139
139
  `);process.stdout.write(nl.cursor.move(-999,e.length-1)),process.stdout.write(nl.erase.down(e.length))},g=e=>e.replace(/\.+$/,``),_=e=>{let t=(performance.now()-e)/1e3,n=Math.floor(t/60),r=Math.floor(t%60);return n>0?`[${n}m ${r}s]`:`[${r}s]`},v=(u=``)=>{o=!0,i=wc(),s=g(u),l=performance.now(),process.stdout.write(`${X.default.gray(Q)}
140
140
  `);let d=0,f=0;p(),a=setInterval(()=>{if(r&&s===c)return;h(),c=s;let n=X.default.magenta(t[d]);if(r)process.stdout.write(`${n} ${s}...`);else if(e===`timer`)process.stdout.write(`${n} ${s} ${_(l)}`);else{let e=`.`.repeat(Math.floor(f)).slice(0,3);process.stdout.write(`${n} ${s}${e}`)}d=d+1<t.length?d+1:0,f=f<t.length?f+.125:0},n)},y=(t=``,n=0)=>{o=!1,clearInterval(a),h();let r=n===0?X.default.green(cl):n===1?X.default.red(ol):X.default.red(sl);s=g(t??s),e===`timer`?process.stdout.write(`${r} ${s} ${_(l)}
141
141
  `):process.stdout.write(`${r} ${s}
142
- `),m(),i()};return{start:v,stop:y,message:(e=``)=>{s=g(e??s)}}},Hl=async(e,t)=>{let n={},r=Object.keys(e);for(let i of r){let r=e[i],a=await r({results:n})?.catch(e=>{throw e});if(typeof t?.onCancel==`function`&&Sc(a)){n[i]=`canceled`,t.onCancel({results:n});continue}n[i]=a}return n},Ul=async e=>{for(let t of e){if(t.enabled===!1)continue;let e=Vl();e.start(t.title);let n=await t.task(e.message);e.stop(n||t.title)}};let Wl;function Gl(){try{return a.default.statSync(`/.dockerenv`),!0}catch{return!1}}function Kl(){try{return a.default.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function ql(){return Wl===void 0&&(Wl=Gl()||Kl()),Wl}let Jl;const Yl=()=>{try{return a.default.statSync(`/run/.containerenv`),!0}catch{return!1}};function Xl(){return Jl===void 0&&(Jl=Yl()||ql()),Jl}const Zl=()=>{if(b.default.platform!==`linux`)return!1;if(w.default.release().toLowerCase().includes(`microsoft`))return!Xl();try{return a.default.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!Xl():!1}catch{return!1}};var Ql=b.default.env.__IS_WSL_TEST__?Zl:Zl();const $l=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await C.default.access(n,C.constants.F_OK),r=!0}catch{}if(!r)return e;let i=await C.default.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}})(),eu=async()=>`${await $l()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,tu=async()=>Ql?eu():`${b.default.env.SYSTEMROOT||b.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function nu(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 ru=(0,c.promisify)(S.execFile);async function iu(){if(b.default.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await ru(`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 au=(0,c.promisify)(S.execFile);async function ou(e,{humanReadableOutput:t=!0,signal:n}={}){if(b.default.platform!==`darwin`)throw Error(`macOS only`);let r=t?[]:[`-ss`],i={};n&&(i.signal=n);let{stdout:a}=await au(`osascript`,[`-e`,e,r],i);return a.trim()}async function su(e){return ou(`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 cu=(0,c.promisify)(S.execFile),lu={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 uu=class extends Error{};async function du(e=cu){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 uu(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=lu[r];if(!i)throw new uu(`Unknown browser ID: ${r}`);return i}const fu=(0,c.promisify)(S.execFile),pu=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function mu(){if(b.default.platform===`darwin`){let e=await iu();return{name:await su(e),id:e}}if(b.default.platform===`linux`){let{stdout:e}=await fu(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:pu(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(b.default.platform===`win32`)return du();throw Error(`Only macOS, Linux, and Windows are supported`)}const hu=(0,c.promisify)(S.default.execFile),gu=y.default.dirname((0,o.fileURLToPath)(require(`url`).pathToFileURL(__filename).href)),_u=y.default.join(gu,`xdg-open`),{platform:vu,arch:yu}=b.default;async function bu(){let e=await tu(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=i.Buffer.from(t,`utf16le`).toString(`base64`),{stdout:r}=await hu(e,[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,n],{encoding:`utf8`}),a=r.trim(),o={ChromeHTML:`com.google.chrome`,BraveHTML:`com.brave.Browser`,MSEdgeHTM:`com.microsoft.edge`,FirefoxURL:`org.mozilla.firefox`};return o[a]?{id:o[a]}:{}}const xu=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},Su=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return xu(e.app,t=>Su({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return xu(t,t=>Su({...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=Ql?await bu():await mu();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),Su({...e,app:{name:Eu[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,a=[],o={};if(vu===`darwin`)r=`open`,e.wait&&a.push(`--wait-apps`),e.background&&a.push(`--background`),e.newInstance&&a.push(`--new`),t&&a.push(`-a`,t);else if(vu===`win32`||Ql&&!Xl()&&!t){r=await tu(),a.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),Ql||(o.windowsVerbatimArguments=!0);let s=[`Start`];e.wait&&s.push(`-Wait`),t?(s.push(`"\`"${t}\`""`),e.target&&n.push(e.target)):e.target&&s.push(`"${e.target}"`),n.length>0&&(n=n.map(e=>`"\`"${e}\`""`),s.push(`-ArgumentList`,n.join(`,`))),e.target=i.Buffer.from(s.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!gu||gu===`/`,t=!1;try{await C.default.access(_u,C.constants.X_OK),t=!0}catch{}r=b.default.versions.electron??(vu===`android`||e||!t)?`xdg-open`:_u}n.length>0&&a.push(...n),e.wait||(o.stdio=`ignore`,o.detached=!0)}vu===`darwin`&&n.length>0&&a.push(`--args`,...n),e.target&&a.push(e.target);let s=S.default.spawn(r,a,o);return e.wait?new Promise((t,n)=>{s.once(`error`,n),s.once(`close`,r=>{if(!e.allowNonzeroExitCode&&r>0){n(Error(`Exited with code ${r}`));return}t(s)})}):(s.unref(),s)},Cu=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return Su({...t,target:e})};function wu(e){if(typeof e==`string`||Array.isArray(e))return e;let{[yu]:t}=e;if(!t)throw Error(`${yu} is not supported`);return t}function Tu({[vu]:e},{wsl:t}){if(t&&Ql)return wu(t);if(!e)throw Error(`${vu} is not supported`);return wu(e)}const Eu={};nu(Eu,`chrome`,()=>Tu({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`]}})),nu(Eu,`brave`,()=>Tu({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`]}})),nu(Eu,`firefox`,()=>Tu({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),nu(Eu,`edge`,()=>Tu({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),nu(Eu,`browser`,()=>`browser`),nu(Eu,`browserPrivate`,()=>`browserPrivate`);var Du=Cu;async function Ou(e,t=void 0){try{(await Du(e)).once(`error`,n=>{console.log(Is.default.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))})}catch{console.log(Is.default.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))}}var ku=e.__toESM(Ns());function Au(e){let t=e||Nu();if((0,a.existsSync)(t)){let e=(0,a.readFileSync)(t,`utf8`);return JSON.parse(e).token}}function ju(e,t){let n=t||Nu();(0,a.existsSync)((0,y.dirname)(n))||(0,a.mkdirSync)((0,y.dirname)(n),{recursive:!0}),(0,a.writeFileSync)(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function Mu(e){let t=e||Nu();(0,a.existsSync)(t)&&(0,a.unlinkSync)(t)}function Nu(){let e=ws(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return(0,y.join)(e[0],`auth.json`)}function Pu(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=(0,g.useState)(),[s,c]=(0,g.useState)(()=>Au(i)),[l,u]=(0,g.useState)(),d=(0,g.useRef)(n),f=(0,g.useRef)(r);(0,g.useEffect)(()=>{d.current=n,f.current=r},[n,r]);let p=(0,g.useCallback)(async()=>{u(void 0);try{let e=Au(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new ns({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=(0,g.useCallback)(async()=>{u(void 0);try{let e=new ns,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();ju(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=(0,g.useCallback)(()=>{Mu(i),c(void 0),o(void 0),u(void 0),d.current?.(void 0)},[i]);return(0,g.useEffect)(()=>{t&&p()},[t,p]),{user:a,token:s,error:l,login:m,logout:h}}function Fu(e){let{directory:t,onBuildStart:r,onBuildSuccess:i,onBuildError:a}=typeof e==`string`?{directory:e}:e,o=(0,g.useMemo)(()=>n.resolveConfig(t),[t]),[s,c]=(0,g.useState)(void 0),[l,u]=(0,g.useState)(void 0),[d,f]=(0,g.useState)(`building`),p=(0,g.useRef)(r),m=(0,g.useRef)(i),h=(0,g.useRef)(a);return(0,g.useEffect)(()=>{p.current=r,m.current=i,h.current=a},[r,i,a]),(0,g.useEffect)(()=>{let e=new AbortController;return o.build({cwd:t,entry:o.entry,outdir:o.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{f(`building`),c(void 0),u(void 0),p.current?.()},onResult:e=>{`error`in e?(c(e.error),f(`error`),h.current?.(e.error)):(u(e),f(`success`),m.current?.(e))}}).catch(e=>{console.log(`error`,e),f(`error`),c(e),h.current?.(e)}),()=>{e.abort()}},[t]),(0,g.useMemo)(()=>({error:s,status:d,result:l,entry:o.entry,outdir:o.outdir}),[s,d,l,o.entry,o.outdir])}function Iu(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function Lu(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const Ru=100,zu=/^\.+(\\|\/)|^\.+$/,Bu=/[. ]+$/,Vu=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,Hu=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,Uu=e=>e===`‍`,Wu=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,Gu=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let Ku;function qu(){return Ku??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),Ku}function Ju(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(Iu().test(n)||[...n].some(e=>Hu.test(e)&&!Uu(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(Gu,` `),n.length>0&&(e=e.replaceAll(Wu,`$1`)),e=e.replace(Bu,``),e=e.replace(zu,n),e=e.replace(Iu(),n),e=e.replaceAll(Vu,e=>Uu(e)?e:n),e.length===0&&(e=n),e=Lu().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=Yu(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=Yu(n,a)+i}}return e}function Yu(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of qu().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function Xu(e){return`${e}.lock`}function Zu(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function Qu(e,t={}){let n=Xu(e),r=process.pid.toString();try{return a.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(a.readFileSync(n,`utf8`),10)}catch{return a.unlinkSync(n),Qu(e,{...t,stale:0})}if(!Zu(i))try{return a.unlinkSync(n),Qu(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return Qu(e,{...t,stale:0});throw n}return!1}}async function $u(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=y.resolve(e),i=0;for(;i<=n.retries;){if(Qu(r,n))return()=>ed(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 ed(e){let t=y.resolve(e),n=Xu(t);try{if(parseInt(a.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}a.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function td(e){let t=y.resolve(e),n=Xu(t);try{if(!a.existsSync(n))return{locked:!1};let e=a.readFileSync(n,`utf8`),t=parseInt(e,10);return Zu(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const nd=e=>{a.mkdirSync(e,{recursive:!0})},rd=e=>{try{a.fdatasyncSync(e)}catch{}try{a.closeSync(e)}catch{}},id=e=>{try{let t=a.openSync(e,`r`);try{a.fsyncSync(t)}finally{a.closeSync(t)}}catch{}},ad=(e,t)=>{let n=y.dirname(e);nd(n);let r=y.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=a.openSync(r,`w`),a.writeFileSync(i,t,`utf-8`),rd(i),i=void 0,a.renameSync(r,e),id(e),id(n)}catch(e){if(i!==void 0)try{a.closeSync(i)}catch{}try{a.rmSync(r,{force:!0})}catch{}throw e}},od=(e,t)=>{let n=new Map,r,i=e=>{if(a.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(a.readFileSync(e,`utf-8`))},o=(e,t)=>{ad(e,JSON.stringify(t,null,2))},s=async()=>{if(r)throw Error(`Index is already locked`);let t=y.join(e,`index.json`);nd(e),a.existsSync(t)||a.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await $u(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},c=async()=>{let t=y.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},l=async t=>{let n=y.join(e,`index.json`);o(n,t)},u=async t=>{let n=(await c()).ids[t];if(n)return y.join(e,n)},d=async t=>{let n=(await c()).ids[t];if(!n)return;let r=y.join(e,n);if(a.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(a.readFileSync(r,`utf-8`))},f=async n=>{let r=n[t],i=String(r),a=Ju(i,{replacement:`_`})+`.json`,u=await s();try{let t=await c();t.ids[i]=a,t.current=i;let r=y.join(e,a);o(r,n),await l(t)}finally{await u()}};return{async get(e){return await d(e)},async list(){if(!a.statSync(e,{throwIfNoEntry:!1}))return[];let t=await c(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=y.join(e,i),o=a.statSync(t,{throwIfNoEntry:!1});if(!o)continue;let s=td(t);n.push({key:r,locked:s.locked,pid:s.pid,mtime:o.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 o=await u(r);if(!o){let t=Ju(r,{replacement:`_`})+`.json`,n=await s();try{let n=await c();n.ids[r]=t;let i=y.join(e,t);nd(e),a.writeFileSync(i,JSON.stringify({}),`utf-8`),await l(n),o=i}finally{await n()}}if(i?.force){let e=td(o);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 p=await $u(o,{stale:!0,retries:i?.force?10:5,retryInterval:(i?.force,100)});return n.set(r,()=>Promise.resolve(p())),{async get(){let e=await d(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await f(e)},async update(e){let n=await d(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await f({...n,...e})},async delete(){let t=await s();try{let t=await c(),n=t.ids[r];if(n){delete t.ids[r],t.current===r&&(t.current=void 0),await l(t);let i=y.join(e,n);try{a.rmSync(i,{force:!0}),id(e)}catch{}}}finally{await t()}},async release(){try{p()}finally{n.delete(r)}}}},dispose(){n.clear()}}},sd=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,o,s,c=new Map,l=new Map,u=y.join(e,`index.json`),d=()=>{try{if(!a.statSync(u,{throwIfNoEntry:!1}))return{ids:{}};let e=a.readFileSync(u,`utf-8`);return{ids:JSON.parse(e).ids??{}}}catch{return{ids:{}}}},f=(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)}},p=(t,n,r=!1)=>{let i=y.join(e,n);try{let e=a.statSync(i,{throwIfNoEntry:!1}),o=l.get(n);if(!e){o&&(l.delete(n),f(t,void 0,!1));return}let s=e.mtimeMs,c=o?{locked:o.locked,pid:o.pid}:{locked:!1,pid:void 0};if((r||!o)&&(c=td(i)),!o||o.mtime!==s||o.locked!==c.locked||o.pid!==c.pid){let e;e=!o||o.mtime!==s?JSON.parse(a.readFileSync(i,`utf-8`)):o.cachedValue,l.set(n,{mtime:s,key:t,locked:c.locked,pid:c.pid,cachedValue:e}),f(t,e,c.locked,c.pid)}}catch{}},m=()=>{try{let e=d(),t=new Set(Object.keys(e.ids));for(let[t,n]of Object.entries(e.ids))p(t,n,!0);for(let[e,n]of l.entries())t.has(n.key)||(l.delete(e),f(n.key,void 0,!1))}catch{}},h=(e,t,n=!1)=>{let i=c.get(e);i&&clearTimeout(i),c.set(e,setTimeout(()=>{c.delete(e),p(e,t,n)},r))},g=()=>{if(o)return;try{a.mkdirSync(e,{recursive:!0})}catch{}o=a.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){m();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=d(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&p(r,e,!0);return}let n=d(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&h(r,t,!1)});let t=()=>{m(),s=setTimeout(t,n)};m(),s=setTimeout(t,n)};return{onChange(e){return i.size===0&&g(),i.add(e),()=>{if(i.delete(e),i.size===0){o&&=(o.close(),void 0),s&&=(clearTimeout(s),void 0);for(let e of c.values())clearTimeout(e);c.clear(),l.clear()}}},dispose(){o&&=(o.close(),void 0),s&&=(clearTimeout(s),void 0);for(let e of c.values())clearTimeout(e);c.clear(),i.clear(),l.clear()}}};async function cd({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=ld}){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=(0,p.readUIMessageStream)({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 ld=e=>{if(e.role!==`assistant`)return!1;let n=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),r=e.parts.slice(n+1).filter(p.isToolOrDynamicToolUIPart);return r.length===0||r.some(e=>t.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`)?!1:r.every(e=>e.state.startsWith(`output-`))},ud=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function dd(e){return typeof e==`object`&&e?.__blink_internal!==void 0}var fd=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=od(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.watcher=sd(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=>!dd(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=>!(0,p.isToolOrDynamicToolUIPart)(e)||e.input!==``?e:{...e,input:{}})}));let a=performance.now(),o=await cd({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 pd(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a}=e,o=(0,g.useRef)(null),[s,c]=(0,g.useState)({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[]});(0,g.useEffect)(()=>{o.current&&o.current.dispose();let e=new fd({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]),(0,g.useEffect)(()=>{o.current&&o.current.setAgent(n)},[n]);let l=(0,g.useCallback)(async e=>{o.current&&await o.current.sendMessages([e])},[]),u=(0,g.useCallback)(async e=>{o.current&&await o.current.upsertMessages([e])},[]),d=(0,g.useCallback)(()=>{o.current&&o.current.stopStreaming()},[]),f=(0,g.useCallback)(async()=>{o.current&&await o.current.resetChat()},[]),p=(0,g.useCallback)(()=>{o.current&&o.current.clearQueue()},[]),m=(0,g.useCallback)(async e=>{o.current&&await o.current.deleteMessages([e])},[]),h=(0,g.useCallback)(async()=>{o.current&&await o.current.start()},[]);return{...s,sendMessage:l,upsertMessage:u,stopStreaming:d,resetChat:f,clearQueue:p,deleteMessage:m,start:h}}function md(e){return(0,d.join)(e,`data`,`devhook.txt`)}function hd(e){return(0,f.existsSync)(md(e))}function gd(e){let t=md(e);if((0,f.existsSync)(t))return(0,f.readFileSync)(t,`utf-8`).trim()}function _d(e){let t=md(e);if((0,f.mkdirSync)((0,d.dirname)(t),{recursive:!0}),(0,f.existsSync)(t))return(0,f.readFileSync)(t,`utf-8`);let n=crypto.randomUUID();return(0,f.writeFileSync)(t,n),n}const vd=(e,t)=>e.json({error:t},400),yd=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}},bd=()=>new t.Hono,xd=bd().get(`/:key`,async e=>{let{key:t,err:n}=yd(e);if(n)return vd(e,n);let r=await e.env.store.get(t);return e.json({value:r},200)}).post(`/:key`,t.validator(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?vd(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:vd(t,`Value must be a string`):vd(t,`Value is required`)}),async e=>{let{key:t,err:n}=yd(e);if(n)return vd(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}=yd(e);return n?vd(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})}),Sd=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`}},Cd=t.validator(`param`,e=>({id:e.id})),wd=bd().post(`/:key`,async e=>{let{key:t,err:n}=Sd(e);return n?vd(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,Cd,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,Cd,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.getMessages(t),200)}).post(`/:id/sendMessages`,t.validator(`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)):vd(e,`ID is required`)}).delete(`/:id/messages`,Cd,t.validator(`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`,Cd,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,Cd,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,Cd,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),Td=bd().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),Ed=new t.Hono().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,xd).route(`/chat`,wd).route(`/otlp`,Td);var Dd=/^(?:[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 Od(e){return typeof e==`string`&&Dd.test(e)}var kd=Od;function Ad(e){if(!kd(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 jd=Ad;const $=[];for(let e=0;e<256;++e)$.push((e+256).toString(16).slice(1));function Md(e,t=0){return($[e[t+0]]+$[e[t+1]]+$[e[t+2]]+$[e[t+3]]+`-`+$[e[t+4]]+$[e[t+5]]+`-`+$[e[t+6]]+$[e[t+7]]+`-`+$[e[t+8]]+$[e[t+9]]+`-`+$[e[t+10]]+$[e[t+11]]+$[e[t+12]]+$[e[t+13]]+$[e[t+14]]+$[e[t+15]]).toLowerCase()}function Nd(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}const Pd=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,Fd=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;function Id(e,t,n,r,i,a){let o=typeof n==`string`?Nd(n):n,s=typeof r==`string`?jd(r):r;if(typeof r==`string`&&(r=jd(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 Md(c)}function Ld(e){return Array.isArray(e)?e=Buffer.from(e):typeof e==`string`&&(e=Buffer.from(e,`utf8`)),(0,l.createHash)(`sha1`).update(e).digest()}var Rd=Ld;function zd(e,t,n,r){return Id(80,Rd,e,t,n,r)}zd.DNS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,zd.URL=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;var Bd=zd;function Vd(e){let n=(0,y.join)(e.dataDirectory,`chats`),r={},i=(0,y.join)(e.dataDirectory,`storage.json`);a.existsSync(i)&&(r=JSON.parse(a.readFileSync(i,`utf-8`)));let o=new Map,s=t=>{let r=o.get(t);return r||(r=new fd({chatId:t,chatsDirectory:n}),o.set(t,r)),r.setAgent(e.getAgent()),r},c={async upsert(e){let t=Bd(JSON.stringify(e),Bd.URL),n=s(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=s(e).getState();return{id:t.id,createdAt:t.created_at??new Date().toISOString()}},async getMessages(e){return s(e).getState().messages},async sendMessages(e,t,n){let r=s(e),i=t.map(e=>ud(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 s(e).deleteMessages(t)},async start(e){await s(e).start()},async stop(e){await s(e).stop()},async delete(e){await s(e).resetChat()}},l={get(e){return Promise.resolve(r[e])},set(e,t){return r[e]=t,a.writeFileSync(i,JSON.stringify(r),`utf-8`),Promise.resolve()},delete(e){return delete r[e],a.writeFileSync(i,JSON.stringify(r),`utf-8`),Promise.resolve()},list(e,t){let n=Math.min(t?.limit??100,1e3),i=t?.cursor,a=Object.keys(r).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+n),c=o+n<a.length?s[s.length-1]:void 0;return Promise.resolve({entries:s.map(e=>({key:e})),cursor:c})}},d=(0,u.createServer)(t.createServerAdapter(e=>Ed.fetch(e,{chat:c,store:l})));d.listen(e.port??0);let f=od(n,`id`);return{url:`http://127.0.0.1:${d.address().port}`,chatsDirectory:n,getChatManager:s,listChats:()=>f.list(),dispose:()=>{for(let e of o.values())e.dispose();o.clear(),f.dispose(),d.close()}}}function Hd({agent:e,capabilities:n,messages:r}){let[i,a]=(0,g.useState)(void 0),[o,s]=(0,g.useState)(!0),[c,l]=(0,g.useState)(void 0),u=(0,g.useRef)(c);(0,g.useEffect)(()=>{u.current=c},[c]);let[d,f]=(0,g.useState)(()=>t.lastUIOptions(r));(0,g.useEffect)(()=>{f(e=>{let n=t.lastUIOptions(r);return JSON.stringify(n)===JSON.stringify(e)?e:n})},[r]);let[p,m]=(0,g.useState)(void 0),h=(0,g.useCallback)((e,t)=>{if(!u.current)return!1;let n=u.current[e];return n?n.values.some(e=>e.id===t):!1},[]),_=(0,g.useCallback)(e=>{m(t=>{let n={...d,...t,...e};for(let[e,t]of Object.entries(n))h(e,t)||delete n[e];for(let[e,t]of Object.entries(u.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[d,h]);(0,g.useEffect)(()=>{if(!d&&!c){m(void 0);return}_()},[d,c,_]);let v=(0,g.useRef)(void 0),y=(0,g.useRef)(void 0);(0,g.useEffect)(()=>{e!==y.current&&(y.current=e,l(void 0),m(void 0),a(void 0),s(!0),v.current=void 0)},[e]),(0,g.useEffect)(()=>{if(n&&!n.ui||!e){l(void 0),m(void 0),a(void 0),v.current=void 0;return}let t=p?JSON.stringify(p):``;if(v.current===t){s(!1),a(void 0);return}let r=new AbortController;return s(!0),a(void 0),e.ui(p?{selectedOptions:p}:{},{signal:r.signal}).then(e=>{if(!e){l(void 0);return}r.signal.aborted||(l(t=>JSON.stringify(t)===JSON.stringify(e)?t:e),v.current=t)}).catch(e=>{r.signal.aborted||a(e instanceof Error?e:Error(String(e)))}).finally(()=>{s(!1)}),()=>{r.abort()}},[e,n,p]);let b=(0,g.useCallback)((e,t)=>{_({[e]:t})},[_]);return{schema:c,options:p,setOption:b,loading:o,error:i}}var Ud=e.__toESM(Ns());function Wd(e){let t=(0,g.useRef)(e.onRequest);(0,g.useEffect)(()=>{t.current=e.onRequest},[e.onRequest]);let[n,r]=(0,g.useState)(`disconnected`);return(0,g.useEffect)(()=>{if(e.disabled||!e.id){r(`disconnected`);return}let n=!1,i,a,o=!1,s,c=(0,y.join)(e.directory,`data`,`devhook`);return(async()=>{try{s=await $u(c,{stale:!0,retries:0})}catch(e){if(e&&typeof e==`object`&&`code`in e&&e.code===`ELOCKED`){let e=``;try{let t=td(c);t.locked&&t.pid&&(e=` (PID: ${t.pid})`)}catch{}console.error(Ud.default.red(`\nError: Another ${Ud.default.bold(`blink dev`)} process is already running in this directory${e}.`)),console.error(Ud.default.red(`Please stop the other process and try again.
142
+ `),m(),i()};return{start:v,stop:y,message:(e=``)=>{s=g(e??s)}}},Hl=async(e,t)=>{let n={},r=Object.keys(e);for(let i of r){let r=e[i],a=await r({results:n})?.catch(e=>{throw e});if(typeof t?.onCancel==`function`&&Sc(a)){n[i]=`canceled`,t.onCancel({results:n});continue}n[i]=a}return n},Ul=async e=>{for(let t of e){if(t.enabled===!1)continue;let e=Vl();e.start(t.title);let n=await t.task(e.message);e.stop(n||t.title)}};let Wl;function Gl(){try{return a.default.statSync(`/.dockerenv`),!0}catch{return!1}}function Kl(){try{return a.default.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function ql(){return Wl===void 0&&(Wl=Gl()||Kl()),Wl}let Jl;const Yl=()=>{try{return a.default.statSync(`/run/.containerenv`),!0}catch{return!1}};function Xl(){return Jl===void 0&&(Jl=Yl()||ql()),Jl}const Zl=()=>{if(b.default.platform!==`linux`)return!1;if(w.default.release().toLowerCase().includes(`microsoft`))return!Xl();try{return a.default.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!Xl():!1}catch{return!1}};var Ql=b.default.env.__IS_WSL_TEST__?Zl:Zl();const $l=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await C.default.access(n,C.constants.F_OK),r=!0}catch{}if(!r)return e;let i=await C.default.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}})(),eu=async()=>`${await $l()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,tu=async()=>Ql?eu():`${b.default.env.SYSTEMROOT||b.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function nu(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 ru=(0,c.promisify)(S.execFile);async function iu(){if(b.default.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await ru(`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 au=(0,c.promisify)(S.execFile);async function ou(e,{humanReadableOutput:t=!0,signal:n}={}){if(b.default.platform!==`darwin`)throw Error(`macOS only`);let r=t?[]:[`-ss`],i={};n&&(i.signal=n);let{stdout:a}=await au(`osascript`,[`-e`,e,r],i);return a.trim()}async function su(e){return ou(`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 cu=(0,c.promisify)(S.execFile),lu={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 uu=class extends Error{};async function du(e=cu){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 uu(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=lu[r];if(!i)throw new uu(`Unknown browser ID: ${r}`);return i}const fu=(0,c.promisify)(S.execFile),pu=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function mu(){if(b.default.platform===`darwin`){let e=await iu();return{name:await su(e),id:e}}if(b.default.platform===`linux`){let{stdout:e}=await fu(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:pu(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(b.default.platform===`win32`)return du();throw Error(`Only macOS, Linux, and Windows are supported`)}const hu=(0,c.promisify)(S.default.execFile),gu=y.default.dirname((0,o.fileURLToPath)(require(`url`).pathToFileURL(__filename).href)),_u=y.default.join(gu,`xdg-open`),{platform:vu,arch:yu}=b.default;async function bu(){let e=await tu(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=i.Buffer.from(t,`utf16le`).toString(`base64`),{stdout:r}=await hu(e,[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,n],{encoding:`utf8`}),a=r.trim(),o={ChromeHTML:`com.google.chrome`,BraveHTML:`com.brave.Browser`,MSEdgeHTM:`com.microsoft.edge`,FirefoxURL:`org.mozilla.firefox`};return o[a]?{id:o[a]}:{}}const xu=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},Su=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return xu(e.app,t=>Su({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return xu(t,t=>Su({...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=Ql?await bu():await mu();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),Su({...e,app:{name:Eu[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,a=[],o={};if(vu===`darwin`)r=`open`,e.wait&&a.push(`--wait-apps`),e.background&&a.push(`--background`),e.newInstance&&a.push(`--new`),t&&a.push(`-a`,t);else if(vu===`win32`||Ql&&!Xl()&&!t){r=await tu(),a.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),Ql||(o.windowsVerbatimArguments=!0);let s=[`Start`];e.wait&&s.push(`-Wait`),t?(s.push(`"\`"${t}\`""`),e.target&&n.push(e.target)):e.target&&s.push(`"${e.target}"`),n.length>0&&(n=n.map(e=>`"\`"${e}\`""`),s.push(`-ArgumentList`,n.join(`,`))),e.target=i.Buffer.from(s.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!gu||gu===`/`,t=!1;try{await C.default.access(_u,C.constants.X_OK),t=!0}catch{}r=b.default.versions.electron??(vu===`android`||e||!t)?`xdg-open`:_u}n.length>0&&a.push(...n),e.wait||(o.stdio=`ignore`,o.detached=!0)}vu===`darwin`&&n.length>0&&a.push(`--args`,...n),e.target&&a.push(e.target);let s=S.default.spawn(r,a,o);return e.wait?new Promise((t,n)=>{s.once(`error`,n),s.once(`close`,r=>{if(!e.allowNonzeroExitCode&&r>0){n(Error(`Exited with code ${r}`));return}t(s)})}):(s.unref(),s)},Cu=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return Su({...t,target:e})};function wu(e){if(typeof e==`string`||Array.isArray(e))return e;let{[yu]:t}=e;if(!t)throw Error(`${yu} is not supported`);return t}function Tu({[vu]:e},{wsl:t}){if(t&&Ql)return wu(t);if(!e)throw Error(`${vu} is not supported`);return wu(e)}const Eu={};nu(Eu,`chrome`,()=>Tu({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`]}})),nu(Eu,`brave`,()=>Tu({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`]}})),nu(Eu,`firefox`,()=>Tu({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),nu(Eu,`edge`,()=>Tu({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),nu(Eu,`browser`,()=>`browser`),nu(Eu,`browserPrivate`,()=>`browserPrivate`);var Du=Cu;async function Ou(e,t=void 0){try{(await Du(e)).once(`error`,n=>{console.log(Is.default.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))})}catch{console.log(Is.default.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))}}var ku=e.__toESM(Ns());function Au(e){let t=e||Nu();if((0,a.existsSync)(t)){let e=(0,a.readFileSync)(t,`utf8`);return JSON.parse(e).token}}function ju(e,t){let n=t||Nu();(0,a.existsSync)((0,y.dirname)(n))||(0,a.mkdirSync)((0,y.dirname)(n),{recursive:!0}),(0,a.writeFileSync)(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function Mu(e){let t=e||Nu();(0,a.existsSync)(t)&&(0,a.unlinkSync)(t)}function Nu(){let e=ws(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return(0,y.join)(e[0],`auth.json`)}function Pu(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=(0,g.useState)(),[s,c]=(0,g.useState)(()=>Au(i)),[l,u]=(0,g.useState)(),d=(0,g.useRef)(n),f=(0,g.useRef)(r);(0,g.useEffect)(()=>{d.current=n,f.current=r},[n,r]);let p=(0,g.useCallback)(async()=>{u(void 0);try{let e=Au(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new ns({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=(0,g.useCallback)(async()=>{u(void 0);try{let e=new ns,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();ju(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=(0,g.useCallback)(()=>{Mu(i),c(void 0),o(void 0),u(void 0),d.current?.(void 0)},[i]);return(0,g.useEffect)(()=>{t&&p()},[t,p]),{user:a,token:s,error:l,login:m,logout:h}}function Fu(e){let{directory:t,onBuildStart:r,onBuildSuccess:i,onBuildError:a}=typeof e==`string`?{directory:e}:e,o=(0,g.useMemo)(()=>n.resolveConfig(t),[t]),[s,c]=(0,g.useState)(void 0),[l,u]=(0,g.useState)(void 0),[d,f]=(0,g.useState)(`building`),p=(0,g.useRef)(r),m=(0,g.useRef)(i),h=(0,g.useRef)(a);return(0,g.useEffect)(()=>{p.current=r,m.current=i,h.current=a},[r,i,a]),(0,g.useEffect)(()=>{let e=new AbortController;return o.build({cwd:t,entry:o.entry,outdir:o.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{f(`building`),c(void 0),u(void 0),p.current?.()},onResult:e=>{`error`in e?(c(e.error),f(`error`),h.current?.(e.error)):(u(e),f(`success`),m.current?.(e))}}).catch(e=>{console.log(`error`,e),f(`error`),c(e),h.current?.(e)}),()=>{e.abort()}},[t]),(0,g.useMemo)(()=>({error:s,status:d,result:l,entry:o.entry,outdir:o.outdir}),[s,d,l,o.entry,o.outdir])}function Iu(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function Lu(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const Ru=100,zu=/^\.+(\\|\/)|^\.+$/,Bu=/[. ]+$/,Vu=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,Hu=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,Uu=e=>e===`‍`,Wu=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,Gu=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let Ku;function qu(){return Ku??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),Ku}function Ju(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(Iu().test(n)||[...n].some(e=>Hu.test(e)&&!Uu(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(Gu,` `),n.length>0&&(e=e.replaceAll(Wu,`$1`)),e=e.replace(Bu,``),e=e.replace(zu,n),e=e.replace(Iu(),n),e=e.replaceAll(Vu,e=>Uu(e)?e:n),e.length===0&&(e=n),e=Lu().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=Yu(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=Yu(n,a)+i}}return e}function Yu(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of qu().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function Xu(e){return`${e}.lock`}function Zu(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function Qu(e,t={}){let n=Xu(e),r=process.pid.toString();try{return a.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(a.readFileSync(n,`utf8`),10)}catch{return a.unlinkSync(n),Qu(e,{...t,stale:0})}if(!Zu(i))try{return a.unlinkSync(n),Qu(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return Qu(e,{...t,stale:0});throw n}return!1}}async function $u(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=y.resolve(e),i=0;for(;i<=n.retries;){if(Qu(r,n))return()=>ed(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 ed(e){let t=y.resolve(e),n=Xu(t);try{if(parseInt(a.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}a.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function td(e){let t=y.resolve(e),n=Xu(t);try{if(!a.existsSync(n))return{locked:!1};let e=a.readFileSync(n,`utf8`),t=parseInt(e,10);return Zu(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const nd=e=>{a.mkdirSync(e,{recursive:!0})},rd=e=>{try{a.fdatasyncSync(e)}catch{}try{a.closeSync(e)}catch{}},id=e=>{try{let t=a.openSync(e,`r`);try{a.fsyncSync(t)}finally{a.closeSync(t)}}catch{}},ad=(e,t)=>{let n=y.dirname(e);nd(n);let r=y.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=a.openSync(r,`w`),a.writeFileSync(i,t,`utf-8`),rd(i),i=void 0,a.renameSync(r,e),id(e),id(n)}catch(e){if(i!==void 0)try{a.closeSync(i)}catch{}try{a.rmSync(r,{force:!0})}catch{}throw e}},od=(e,t)=>{let n=new Map,r,i=e=>{if(a.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(a.readFileSync(e,`utf-8`))},o=(e,t)=>{ad(e,JSON.stringify(t,null,2))},s=async()=>{if(r)throw Error(`Index is already locked`);let t=y.join(e,`index.json`);nd(e),a.existsSync(t)||a.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await $u(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},c=async()=>{let t=y.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},l=async t=>{let n=y.join(e,`index.json`);o(n,t)},u=async t=>{let n=(await c()).ids[t];if(n)return y.join(e,n)},d=async t=>{let n=(await c()).ids[t];if(!n)return;let r=y.join(e,n);if(a.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(a.readFileSync(r,`utf-8`))},f=async n=>{let r=n[t],i=String(r),a=Ju(i,{replacement:`_`})+`.json`,u=await s();try{let t=await c();t.ids[i]=a,t.current=i;let r=y.join(e,a);o(r,n),await l(t)}finally{await u()}};return{async get(e){return await d(e)},async list(){if(!a.statSync(e,{throwIfNoEntry:!1}))return[];let t=await c(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=y.join(e,i),o=a.statSync(t,{throwIfNoEntry:!1});if(!o)continue;let s=td(t);n.push({key:r,locked:s.locked,pid:s.pid,mtime:o.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 o=await u(r);if(!o){let t=Ju(r,{replacement:`_`})+`.json`,n=await s();try{let n=await c();n.ids[r]=t;let i=y.join(e,t);nd(e),a.writeFileSync(i,JSON.stringify({}),`utf-8`),await l(n),o=i}finally{await n()}}if(i?.force){let e=td(o);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 p=await $u(o,{stale:!0,retries:i?.force?10:5,retryInterval:(i?.force,100)});return n.set(r,()=>Promise.resolve(p())),{async get(){let e=await d(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await f(e)},async update(e){let n=await d(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await f({...n,...e})},async delete(){let t=await s();try{let t=await c(),n=t.ids[r];if(n){delete t.ids[r],t.current===r&&(t.current=void 0),await l(t);let i=y.join(e,n);try{a.rmSync(i,{force:!0}),id(e)}catch{}}}finally{await t()}},async release(){try{p()}finally{n.delete(r)}}}},dispose(){n.clear()}}},sd=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,o,s,c=new Map,l=new Map,u=y.join(e,`index.json`),d=()=>{try{if(!a.statSync(u,{throwIfNoEntry:!1}))return{ids:{}};let e=a.readFileSync(u,`utf-8`);return{ids:JSON.parse(e).ids??{}}}catch{return{ids:{}}}},f=(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)}},p=(t,n,r=!1)=>{let i=y.join(e,n);try{let e=a.statSync(i,{throwIfNoEntry:!1}),o=l.get(n);if(!e){o&&(l.delete(n),f(t,void 0,!1));return}let s=e.mtimeMs,c=o?{locked:o.locked,pid:o.pid}:{locked:!1,pid:void 0};if((r||!o)&&(c=td(i)),!o||o.mtime!==s||o.locked!==c.locked||o.pid!==c.pid){let e;e=!o||o.mtime!==s?JSON.parse(a.readFileSync(i,`utf-8`)):o.cachedValue,l.set(n,{mtime:s,key:t,locked:c.locked,pid:c.pid,cachedValue:e}),f(t,e,c.locked,c.pid)}}catch{}},m=()=>{try{let e=d(),t=new Set(Object.keys(e.ids));for(let[t,n]of Object.entries(e.ids))p(t,n,!0);for(let[e,n]of l.entries())t.has(n.key)||(l.delete(e),f(n.key,void 0,!1))}catch{}},h=(e,t,n=!1)=>{let i=c.get(e);i&&clearTimeout(i),c.set(e,setTimeout(()=>{c.delete(e),p(e,t,n)},r))},g=()=>{if(o)return;try{a.mkdirSync(e,{recursive:!0})}catch{}o=a.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){m();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=d(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&p(r,e,!0);return}let n=d(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&h(r,t,!1)});let t=()=>{m(),s=setTimeout(t,n)};m(),s=setTimeout(t,n)};return{onChange(e){return i.size===0&&g(),i.add(e),()=>{if(i.delete(e),i.size===0){o&&=(o.close(),void 0),s&&=(clearTimeout(s),void 0);for(let e of c.values())clearTimeout(e);c.clear(),l.clear()}}},dispose(){o&&=(o.close(),void 0),s&&=(clearTimeout(s),void 0);for(let e of c.values())clearTimeout(e);c.clear(),i.clear(),l.clear()}}};async function cd({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=ld}){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=(0,p.readUIMessageStream)({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 ld=e=>{if(e.role!==`assistant`)return!1;let n=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),r=e.parts.slice(n+1).filter(p.isToolOrDynamicToolUIPart);return r.length===0||r.some(e=>t.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`)?!1:r.every(e=>e.state.startsWith(`output-`))},ud=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function dd(e){return typeof e==`object`&&e?.__blink_internal!==void 0}var fd=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=od(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.watcher=sd(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=>!dd(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=>!(0,p.isToolOrDynamicToolUIPart)(e)||e.input!==``?e:{...e,input:{}})}));let a=performance.now(),o=await cd({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 pd(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a}=e,o=(0,g.useRef)(null),[s,c]=(0,g.useState)({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[]});(0,g.useEffect)(()=>{o.current&&o.current.dispose();let e=new fd({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]),(0,g.useEffect)(()=>{o.current&&o.current.setAgent(n)},[n]);let l=(0,g.useCallback)(async e=>{o.current&&await o.current.sendMessages([e])},[]),u=(0,g.useCallback)(async e=>{o.current&&await o.current.upsertMessages([e])},[]),d=(0,g.useCallback)(()=>{o.current&&o.current.stopStreaming()},[]),f=(0,g.useCallback)(async()=>{o.current&&await o.current.resetChat()},[]),p=(0,g.useCallback)(()=>{o.current&&o.current.clearQueue()},[]),m=(0,g.useCallback)(async e=>{o.current&&await o.current.deleteMessages([e])},[]),h=(0,g.useCallback)(async()=>{o.current&&await o.current.start()},[]);return{...s,sendMessage:l,upsertMessage:u,stopStreaming:d,resetChat:f,clearQueue:p,deleteMessage:m,start:h}}function md(e){return(0,d.join)(e,`.blink`,`devhook.txt`)}function hd(e){return(0,f.existsSync)(md(e))}function gd(e){let t=md(e);if((0,f.existsSync)(t))return(0,f.readFileSync)(t,`utf-8`).trim()}function _d(e){let t=md(e);if((0,f.mkdirSync)((0,d.dirname)(t),{recursive:!0}),(0,f.existsSync)(t))return(0,f.readFileSync)(t,`utf-8`);let n=crypto.randomUUID();return(0,f.writeFileSync)(t,n),n}const vd=(e,t)=>e.json({error:t},400),yd=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}},bd=()=>new t.Hono,xd=bd().get(`/:key`,async e=>{let{key:t,err:n}=yd(e);if(n)return vd(e,n);let r=await e.env.store.get(t);return e.json({value:r},200)}).post(`/:key`,t.validator(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?vd(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:vd(t,`Value must be a string`):vd(t,`Value is required`)}),async e=>{let{key:t,err:n}=yd(e);if(n)return vd(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}=yd(e);return n?vd(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})}),Sd=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`}},Cd=t.validator(`param`,e=>({id:e.id})),wd=bd().post(`/:key`,async e=>{let{key:t,err:n}=Sd(e);return n?vd(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,Cd,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,Cd,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.getMessages(t),200)}).post(`/:id/sendMessages`,t.validator(`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)):vd(e,`ID is required`)}).delete(`/:id/messages`,Cd,t.validator(`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`,Cd,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,Cd,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,Cd,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),Td=bd().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),Ed=new t.Hono().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,xd).route(`/chat`,wd).route(`/otlp`,Td);var Dd=/^(?:[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 Od(e){return typeof e==`string`&&Dd.test(e)}var kd=Od;function Ad(e){if(!kd(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 jd=Ad;const $=[];for(let e=0;e<256;++e)$.push((e+256).toString(16).slice(1));function Md(e,t=0){return($[e[t+0]]+$[e[t+1]]+$[e[t+2]]+$[e[t+3]]+`-`+$[e[t+4]]+$[e[t+5]]+`-`+$[e[t+6]]+$[e[t+7]]+`-`+$[e[t+8]]+$[e[t+9]]+`-`+$[e[t+10]]+$[e[t+11]]+$[e[t+12]]+$[e[t+13]]+$[e[t+14]]+$[e[t+15]]).toLowerCase()}function Nd(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}const Pd=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,Fd=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;function Id(e,t,n,r,i,a){let o=typeof n==`string`?Nd(n):n,s=typeof r==`string`?jd(r):r;if(typeof r==`string`&&(r=jd(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 Md(c)}function Ld(e){return Array.isArray(e)?e=Buffer.from(e):typeof e==`string`&&(e=Buffer.from(e,`utf8`)),(0,l.createHash)(`sha1`).update(e).digest()}var Rd=Ld;function zd(e,t,n,r){return Id(80,Rd,e,t,n,r)}zd.DNS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,zd.URL=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;var Bd=zd;function Vd(e){let n=(0,y.join)(e.dataDirectory,`chats`),r={},i=(0,y.join)(e.dataDirectory,`storage.json`);a.existsSync(i)&&(r=JSON.parse(a.readFileSync(i,`utf-8`)));let o=new Map,s=t=>{let r=o.get(t);return r||(r=new fd({chatId:t,chatsDirectory:n}),o.set(t,r)),r.setAgent(e.getAgent()),r},c={async upsert(e){let t=Bd(JSON.stringify(e),Bd.URL),n=s(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=s(e).getState();return{id:t.id,createdAt:t.created_at??new Date().toISOString()}},async getMessages(e){return s(e).getState().messages},async sendMessages(e,t,n){let r=s(e),i=t.map(e=>ud(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 s(e).deleteMessages(t)},async start(e){await s(e).start()},async stop(e){await s(e).stop()},async delete(e){await s(e).resetChat()}},l={get(e){return Promise.resolve(r[e])},set(e,t){return r[e]=t,a.writeFileSync(i,JSON.stringify(r),`utf-8`),Promise.resolve()},delete(e){return delete r[e],a.writeFileSync(i,JSON.stringify(r),`utf-8`),Promise.resolve()},list(e,t){let n=Math.min(t?.limit??100,1e3),i=t?.cursor,a=Object.keys(r).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+n),c=o+n<a.length?s[s.length-1]:void 0;return Promise.resolve({entries:s.map(e=>({key:e})),cursor:c})}},d=(0,u.createServer)(t.createServerAdapter(e=>Ed.fetch(e,{chat:c,store:l})));d.listen(e.port??0);let f=od(n,`id`);return{url:`http://127.0.0.1:${d.address().port}`,chatsDirectory:n,getChatManager:s,listChats:()=>f.list(),dispose:()=>{for(let e of o.values())e.dispose();o.clear(),f.dispose(),d.close()}}}function Hd({agent:e,capabilities:n,messages:r}){let[i,a]=(0,g.useState)(void 0),[o,s]=(0,g.useState)(!0),[c,l]=(0,g.useState)(void 0),u=(0,g.useRef)(c);(0,g.useEffect)(()=>{u.current=c},[c]);let[d,f]=(0,g.useState)(()=>t.lastUIOptions(r));(0,g.useEffect)(()=>{f(e=>{let n=t.lastUIOptions(r);return JSON.stringify(n)===JSON.stringify(e)?e:n})},[r]);let[p,m]=(0,g.useState)(void 0),h=(0,g.useCallback)((e,t)=>{if(!u.current)return!1;let n=u.current[e];return n?n.values.some(e=>e.id===t):!1},[]),_=(0,g.useCallback)(e=>{m(t=>{let n={...d,...t,...e};for(let[e,t]of Object.entries(n))h(e,t)||delete n[e];for(let[e,t]of Object.entries(u.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[d,h]);(0,g.useEffect)(()=>{if(!d&&!c){m(void 0);return}_()},[d,c,_]);let v=(0,g.useRef)(void 0),y=(0,g.useRef)(void 0);(0,g.useEffect)(()=>{e!==y.current&&(y.current=e,l(void 0),m(void 0),a(void 0),s(!0),v.current=void 0)},[e]),(0,g.useEffect)(()=>{if(n&&!n.ui||!e){l(void 0),m(void 0),a(void 0),v.current=void 0;return}let t=p?JSON.stringify(p):``;if(v.current===t){s(!1),a(void 0);return}let r=new AbortController;return s(!0),a(void 0),e.ui(p?{selectedOptions:p}:{},{signal:r.signal}).then(e=>{if(!e){l(void 0);return}r.signal.aborted||(l(t=>JSON.stringify(t)===JSON.stringify(e)?t:e),v.current=t)}).catch(e=>{r.signal.aborted||a(e instanceof Error?e:Error(String(e)))}).finally(()=>{s(!1)}),()=>{r.abort()}},[e,n,p]);let b=(0,g.useCallback)((e,t)=>{_({[e]:t})},[_]);return{schema:c,options:p,setOption:b,loading:o,error:i}}var Ud=e.__toESM(Ns());function Wd(e){let t=(0,g.useRef)(e.onRequest);(0,g.useEffect)(()=>{t.current=e.onRequest},[e.onRequest]);let[n,r]=(0,g.useState)(`disconnected`);return(0,g.useEffect)(()=>{if(e.disabled||!e.id){r(`disconnected`);return}let n=!1,i,a,o=!1,s,c=(0,y.join)(e.directory,`.blink`,`devhook`);return(async()=>{try{s=await $u(c,{stale:!0,retries:0})}catch(e){if(e&&typeof e==`object`&&`code`in e&&e.code===`ELOCKED`){let e=``;try{let t=td(c);t.locked&&t.pid&&(e=` (PID: ${t.pid})`)}catch{}console.error(Ud.default.red(`\nError: Another ${Ud.default.bold(`blink dev`)} process is already running in this directory${e}.`)),console.error(Ud.default.red(`Please stop the other process and try again.
143
143
  `)),process.exit(1)}let t=e&&typeof e==`object`&&`message`in e?String(e.message):String(e);console.warn(Ud.default.yellow(`\nWarning: Failed to acquire devhook lock: ${t}`)),console.warn(Ud.default.yellow(`Continuing without lock. Multiple ${Ud.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 ns({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 Gd=e.__commonJSMin(((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}}})),Kd=e.__commonJSMin(((e,t)=>{let n=require(`fs`),r=require(`path`),i=require(`os`),a=require(`crypto`),o=Gd().version,s=[`🔐 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 c(){return s[Math.floor(Math.random()*s.length)]}function l(e){return typeof e==`string`?![`false`,`0`,`no`,`off`,``].includes(e.toLowerCase()):!!e}function u(){return process.stdout.isTTY}function d(e){return u()?`\x1b[2m${e}\x1b[0m`:e}let f=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function p(e){let t={},n=e.toString();n=n.replace(/\r\n?/gm,`
144
144
  `);let r;for(;(r=f.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,`
145
145
  `),n=n.replace(/\\r/g,`\r`)),t[e]=n}return t}function m(e){e||={};let t=b(e);e.path=t;let n=D.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=v(e).split(`,`),i=r.length,a;for(let e=0;e<i;e++)try{let t=r[e].trim(),i=y(n,t);a=D.decrypt(i.ciphertext,i.key);break}catch(t){if(e+1>=i)throw t}return D.parse(a)}function h(e){console.error(`[dotenv@${o}][WARN] ${e}`)}function g(e){console.log(`[dotenv@${o}][DEBUG] ${e}`)}function _(e){console.log(`[dotenv@${o}] ${e}`)}function v(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 y(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 b(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 x(e){return e[0]===`~`?r.join(i.homedir(),e.slice(1)):e}function S(e){let t=l(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=l(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(t||!n)&&_(`Loading env from encrypted .env.vault`);let r=D._parseVault(e),i=process.env;return e&&e.processEnv!=null&&(i=e.processEnv),D.populate(i,r,e),{parsed:r}}function C(e){let t=r.resolve(process.cwd(),`.env`),i=`utf8`,a=process.env;e&&e.processEnv!=null&&(a=e.processEnv);let o=l(a.DOTENV_CONFIG_DEBUG||e&&e.debug),s=l(a.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?i=e.encoding:o&&g(`No encoding is specified. UTF-8 is used by default`);let u=[t];if(e&&e.path)if(!Array.isArray(e.path))u=[x(e.path)];else{u=[];for(let t of e.path)u.push(x(t))}let f,p={};for(let t of u)try{let r=D.parse(n.readFileSync(t,{encoding:i}));D.populate(p,r,e)}catch(e){o&&g(`Failed to load ${t} ${e.message}`),f=e}let m=D.populate(a,p,e);if(o=l(a.DOTENV_CONFIG_DEBUG||o),s=l(a.DOTENV_CONFIG_QUIET||s),o||!s){let e=Object.keys(m).length,t=[];for(let e of u)try{let n=r.relative(process.cwd(),e);t.push(n)}catch(t){o&&g(`Failed to load ${e} ${t.message}`),f=t}_(`injecting env (${e}) from ${t.join(`,`)} ${d(`-- tip: ${c()}`)}`)}return f?{parsed:p,error:f}:{parsed:p}}function w(e){if(v(e).length===0)return D.configDotenv(e);let t=b(e);return t?D._configVault(e):(h(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),D.configDotenv(e))}function T(e,t){let n=Buffer.from(t.slice(-64),`hex`),r=Buffer.from(e,`base64`),i=r.subarray(0,12),o=r.subarray(-16);r=r.subarray(12,-16);try{let e=a.createDecipheriv(`aes-256-gcm`,n,i);return e.setAuthTag(o),`${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 E(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&&g(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 D={configDotenv:C,_configVault:S,_parseVault:m,config:w,decrypt:T,parse:p,populate:E};t.exports.configDotenv=D.configDotenv,t.exports._configVault=D._configVault,t.exports._parseVault=D._parseVault,t.exports.config=D.config,t.exports.decrypt=D.decrypt,t.exports.parse=D.parse,t.exports.populate=D.populate,t.exports=D})),qd=e.__toESM(Kd());async function Jd(e,t){let n=e;for(;n!==(0,d.dirname)(n);){let e=(0,d.join)(n,t);try{return await(0,m.stat)(e),e}catch{}n=(0,d.dirname)(n)}}function Yd(e,t=`.env.local`){let[n,r]=(0,g.useState)({});return(0,g.useEffect)(()=>{let n,i=e=>{try{let t=(0,f.readFileSync)(e,`utf-8`),n=(0,qd.parse)(t);r(n)}catch(e){console.error(`Error reading ${t}:`,e),r({})}};return Jd(e,t).then(e=>{if(!e){r({});return}i(e),n=(0,f.watch)(e,{persistent:!1},()=>{i(e)})}),()=>{n&&n.close()}},[e,t]),n}var Xd=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}},Zd=class extends Xd{};new Zd;function Qd(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 $d(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 ef(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 tf(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 nf(e,t){return ef(e,t,``)}function rf(e,t){return tf(e,t,``)}function af(e,t){return t.slice(0,sf(e,t))}function sf(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 cf(e){let t;for(t=e.length-1;t>=0&&e[t].match(/\s/);t--);return e.substring(t+1)}function lf(e){let t=e.match(/^\s*/);return t?t[0]:``}const uf=`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}`,df=RegExp(`[${uf}]+|\\s+|[^${uf}]`,`ug`);var ff=class extends Xd{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(df)||[];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)&&pf(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&pf(n,i,r,null),e}};new ff;function pf(e,t,n,r){if(t&&n){let i=lf(t.value),a=cf(t.value),o=lf(n.value),s=cf(n.value);if(e){let r=Qd(i,o);e.value=tf(e.value,o,r),t.value=nf(t.value,r),n.value=nf(n.value,r)}if(r){let e=$d(a,s);r.value=ef(r.value,s,e),t.value=rf(t.value,e),n.value=rf(n.value,e)}}else if(n){if(e){let e=lf(n.value);n.value=n.value.substring(e.length)}if(r){let e=lf(r.value);r.value=r.value.substring(e.length)}}else if(e&&r){let n=lf(r.value),i=lf(t.value),a=cf(t.value),o=Qd(n,i);t.value=nf(t.value,o);let s=$d(nf(n,o),a);t.value=rf(t.value,s),r.value=ef(r.value,n,s),e.value=tf(e.value,n,n.slice(0,n.length-s.length))}else if(r){let e=lf(r.value),n=cf(t.value),i=af(n,e);t.value=rf(t.value,i)}else if(e){let n=cf(e.value),r=lf(t.value),i=af(n,r);t.value=nf(t.value,i)}}var mf=class extends Xd{tokenize(e){let t=RegExp(`(\\r?\\n)|[${uf}]+|[^\\S\\n\\r]+|[^${uf}]`,`ug`);return e.match(t)||[]}};new mf;var hf=class extends Xd{constructor(){super(...arguments),this.tokenize=vf}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
@@ -219,11 +219,18 @@ Use this for:
219
219
  - Extracting relevant information from verbose output
220
220
  - Analyzing build or test results
221
221
 
222
- Example: After running tests with \`workspace_bash\`, use this to find all FAIL: lines rather than re-running the test command.`,inputSchema:v.z.object({pid:v.z.number(),pattern:v.z.string(),before_lines:v.z.number(),after_lines:v.z.number()}),execute:async(t,n)=>{let r;try{r=new RegExp(t.pattern)}catch{throw Error(`Invalid regex pattern: ${t.pattern}`)}let{lines:i}=await(await e()).request(`process_read_plain_output`,{pid:t.pid},{signal:n.abortSignal}),a=[];for(let e=0;e<i.length;e++)if(i[e].match(r)){let n=Math.max(0,e-t.before_lines),r=Math.min(i.length-1,e+t.after_lines),o=i.slice(n,r+1);a.push({line_number:e,lines:o})}if(a.length>256)throw Error(`Too many matches. Please refine your search.`);return{matches:a,total_matches:a.length}}}))},Mf=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()}};v.z.union([v.z.object({pid:v.z.number(),ansiOutput:v.z.string()}),v.z.object({pid:v.z.number(),title:v.z.string().optional(),command:v.z.string(),args:v.z.array(v.z.string()),cwd:v.z.string(),env:v.z.record(v.z.string(),v.z.string()),ansiOutput:v.z.string(),plainOutput:v.z.object({totalLines:v.z.number(),lines:v.z.array(v.z.string())}),durationMs:v.z.number(),exitCode:v.z.number().optional(),exitSignal:v.z.number().optional(),stillRunning:v.z.boolean()})]);const Nf=(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},Pf=(e,t,n)=>t.length===0?e:e.split(t).join(n),Ff={scratch:{".gitignore":`# dependencies
222
+ Example: After running tests with \`workspace_bash\`, use this to find all FAIL: lines rather than re-running the test command.`,inputSchema:v.z.object({pid:v.z.number(),pattern:v.z.string(),before_lines:v.z.number(),after_lines:v.z.number()}),execute:async(t,n)=>{let r;try{r=new RegExp(t.pattern)}catch{throw Error(`Invalid regex pattern: ${t.pattern}`)}let{lines:i}=await(await e()).request(`process_read_plain_output`,{pid:t.pid},{signal:n.abortSignal}),a=[];for(let e=0;e<i.length;e++)if(i[e].match(r)){let n=Math.max(0,e-t.before_lines),r=Math.min(i.length-1,e+t.after_lines),o=i.slice(n,r+1);a.push({line_number:e,lines:o})}if(a.length>256)throw Error(`Too many matches. Please refine your search.`);return{matches:a,total_matches:a.length}}}))},Mf=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()}};v.z.union([v.z.object({pid:v.z.number(),ansiOutput:v.z.string()}),v.z.object({pid:v.z.number(),title:v.z.string().optional(),command:v.z.string(),args:v.z.array(v.z.string()),cwd:v.z.string(),env:v.z.record(v.z.string(),v.z.string()),ansiOutput:v.z.string(),plainOutput:v.z.object({totalLines:v.z.number(),lines:v.z.array(v.z.string())}),durationMs:v.z.number(),exitCode:v.z.number().optional(),exitSignal:v.z.number().optional(),stillRunning:v.z.boolean()})]);const Nf=(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},Pf=(e,t,n)=>t.length===0?e:e.split(t).join(n),Ff={scratch:{".env.local":`
223
+ # Store local environment variables here.
224
+ # They will be used by blink dev for development.
225
+ # EXTERNAL_SERVICE_API_KEY=
226
+ `,".env.production":`# Store production environment variables here.
227
+ # They will be upserted as secrets on blink deploy.
228
+ # EXTERNAL_SERVICE_API_KEY=
229
+ `,".gitignore":`# dependencies
223
230
  node_modules
224
231
 
225
232
  # config and build
226
- data
233
+ .blink
227
234
 
228
235
  # dotenv environment variables file
229
236
  .env
@@ -231,103 +238,6 @@ data
231
238
 
232
239
  # Finder (MacOS) folder config
233
240
  .DS_Store
234
- `,"tsconfig.json":`{
235
- "compilerOptions": {
236
- "lib": ["ESNext"],
237
- "target": "ESNext",
238
- "module": "Preserve",
239
- "moduleDetection": "force",
240
-
241
- "moduleResolution": "bundler",
242
- "allowImportingTsExtensions": true,
243
- "verbatimModuleSyntax": true,
244
- "resolveJsonModule": true,
245
- "noEmit": true,
246
-
247
- "strict": true,
248
- "skipLibCheck": true,
249
- "noFallthroughCasesInSwitch": true,
250
- "noUncheckedIndexedAccess": true,
251
- "noImplicitOverride": true,
252
-
253
- "noUnusedLocals": false,
254
- "noUnusedParameters": false,
255
-
256
- "types": ["node"]
257
- }
258
- }
259
- `,".env.local":`
260
- # Store local environment variables here.
261
- # They will be used by blink dev for development.
262
- # EXTERNAL_SERVICE_API_KEY=
263
- `,".env.production":`# Store production environment variables here.
264
- # They will be upserted as secrets on blink deploy.
265
- # EXTERNAL_SERVICE_API_KEY=
266
- `,"agent.ts.hbs":`import { convertToModelMessages, streamText, tool } from "ai";
267
- import * as blink from "blink";
268
- import { z } from "zod";
269
- {{#if (eq aiProvider "anthropic")}}
270
- import { anthropic } from "@ai-sdk/anthropic";
271
- {{else if (eq aiProvider "openai")}}
272
- import { openai } from "@ai-sdk/openai";
273
- {{/if}}
274
-
275
- const agent = new blink.Agent();
276
-
277
- agent.on("chat", async ({ messages }) => {
278
- return streamText({
279
- {{#if (eq aiProvider "anthropic")}}
280
- model: anthropic("claude-sonnet-4-5"),
281
- {{else if (eq aiProvider "openai")}}
282
- model: openai("gpt-5-chat-latest"),
283
- {{else if (eq aiProvider "vercel")}}
284
- model: "anthropic/claude-sonnet-4.5",
285
- {{else}}
286
- // Unknown provider: {{aiProvider}}. Defaulting to Vercel AI Gateway syntax.
287
- model: "anthropic/claude-sonnet-4.5",
288
- {{/if}}
289
- system: \`You are a basic agent the user will customize.
290
-
291
- Suggest the user enters edit mode with Ctrl+T or /edit to customize the agent.
292
- Demonstrate your capabilities with the IP tool.\`,
293
- messages: convertToModelMessages(messages),
294
- tools: {
295
- get_ip_info: tool({
296
- description: "Get IP address information of the computer.",
297
- inputSchema: z.object({}),
298
- execute: async () => {
299
- const response = await fetch("https://ipinfo.io/json");
300
- return response.json();
301
- },
302
- }),
303
- },
304
- });
305
- });
306
-
307
- agent.serve();
308
- `,"package.json.hbs":`{
309
- "name": "{{packageName}}",
310
- "main": "agent.ts",
311
- "type": "module",
312
- "private": true,
313
- "scripts": {
314
- "dev": "blink dev",
315
- "deploy": "blink deploy"
316
- },
317
- "devDependencies": {
318
- "zod": "latest",
319
- "ai": "latest",
320
- {{#if (eq aiProvider "anthropic")}}
321
- "@ai-sdk/anthropic": "latest",
322
- {{else if (eq aiProvider "openai")}}
323
- "@ai-sdk/openai": "latest",
324
- {{/if}}
325
- "blink": "latest",
326
- "esbuild": "latest",
327
- "@types/node": "latest",
328
- "typescript": "latest"
329
- }
330
- }
331
241
  `,"AGENTS.md":`This project is a Blink agent.
332
242
 
333
243
  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.
@@ -401,7 +311,7 @@ const agent = new blink.Agent();
401
311
 
402
312
  agent.on("chat", async ({ messages, chat, abortSignal }) => {
403
313
  return streamText({
404
- model: blink.model("anthropic/claude-sonnet-4.5"),
314
+ model: "anthropic/claude-sonnet-4.5",
405
315
  system: "You are a helpful assistant.",
406
316
  messages: convertToModelMessages(messages, {
407
317
  ignoreIncompleteToolCalls: true,
@@ -545,17 +455,6 @@ Tool Prefixing to avoid collisions:
545
455
 
546
456
  LLM Models:
547
457
 
548
- **Option 1: Blink Gateway** (Quick Start)
549
-
550
- \`\`\`typescript
551
- model: blink.model("anthropic/claude-sonnet-4.5");
552
- model: blink.model("openai/gpt-5");
553
- \`\`\`
554
-
555
- Requires: \`blink login\` or \`BLINK_TOKEN\` env var
556
-
557
- **Option 2: Direct Provider** (Production Recommended)
558
-
559
458
  \`\`\`typescript
560
459
  import { anthropic } from "@ai-sdk/anthropic";
561
460
  import { openai } from "@ai-sdk/openai";
@@ -570,7 +469,6 @@ model: openai("gpt-5", { apiKey: process.env.OPENAI_API_KEY });
570
469
 
571
470
  1. If \`ANTHROPIC_API_KEY\` is set: uses \`claude-sonnet-4.5\` via \`@ai-sdk/anthropic\`
572
471
  2. If \`OPENAI_API_KEY\` is set: uses \`gpt-5\` via \`@ai-sdk/openai\`
573
- 3. Otherwise: falls back to \`blink.model("anthropic/claude-sonnet-4.5")\`
574
472
 
575
473
  Available SDKs:
576
474
 
@@ -640,7 +538,7 @@ agent.on("request", async (request) => {
640
538
  agent.on("chat", async ({ messages }) => {
641
539
  const tools = slack.createTools({ client: app.client });
642
540
  return streamText({
643
- model: blink.model("anthropic/claude-sonnet-4.5"),
541
+ model: "anthropic/claude-sonnet-4.5",
644
542
  system: "You chatting with users in Slack.",
645
543
  messages: convertToModelMessages(messages, {
646
544
  ignoreIncompleteToolCalls: true,
@@ -664,7 +562,7 @@ Slack App Manifest:
664
562
  - _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.
665
563
  - The user can always edit the manifest after creation, but you'd have to suggest it to them.
666
564
  - "oauth_config" MUST BE PROVIDED - otherwise the app will have NO ACCESS.
667
- - _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.
565
+ - _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.
668
566
  - For the best user experience, default to the following bot scopes (in the "oauth_config" > "scopes" > "bot"):
669
567
  - "app_mentions:read"
670
568
  - "reactions:write"
@@ -757,160 +655,54 @@ The agent process can restart at any time, so all important state must be extern
757
655
 
758
656
  - Never use "as any" type assertions. Always figure out the correct typings.
759
657
  </code_quality>
760
- `},"slack-bot":{".gitignore":`# dependencies
761
- node_modules
762
-
763
- # config and build
764
- data
765
-
766
- # dotenv environment variables file
767
- .env
768
- .env.*
769
-
770
- # Finder (MacOS) folder config
771
- .DS_Store
772
- `,"tsconfig.json":`{
773
- "compilerOptions": {
774
- "lib": ["ESNext"],
775
- "target": "ESNext",
776
- "module": "Preserve",
777
- "moduleDetection": "force",
778
-
779
- "moduleResolution": "bundler",
780
- "allowImportingTsExtensions": true,
781
- "verbatimModuleSyntax": true,
782
- "resolveJsonModule": true,
783
- "noEmit": true,
784
-
785
- "strict": true,
786
- "skipLibCheck": true,
787
- "noFallthroughCasesInSwitch": true,
788
- "noUncheckedIndexedAccess": true,
789
- "noImplicitOverride": true,
790
-
791
- "noUnusedLocals": false,
792
- "noUnusedParameters": false,
793
-
794
- "types": ["node"]
795
- }
796
- }
797
- `,".env.local":`
798
- # Store local environment variables here.
799
- # They will be used by blink dev for development.
800
- SLACK_BOT_TOKEN=xoxb-your-token-here
801
- SLACK_SIGNING_SECRET=your-signing-secret-here
802
- `,".env.production":`# Store production environment variables here.
803
- # They will be upserted as secrets on blink deploy.
804
- # EXTERNAL_SERVICE_API_KEY=
805
- `,"agent.ts.hbs":`import { convertToModelMessages, streamText } from "ai";
658
+ `,"agent.ts.hbs":`import { convertToModelMessages, streamText, tool } from "ai";
806
659
  import * as blink from "blink";
807
- import * as slack from "@blink-sdk/slack";
808
- import { App } from "@slack/bolt";
660
+ import { z } from "zod";
809
661
  {{#if (eq aiProvider "anthropic")}}
810
662
  import { anthropic } from "@ai-sdk/anthropic";
811
663
  {{else if (eq aiProvider "openai")}}
812
664
  import { openai } from "@ai-sdk/openai";
813
665
  {{/if}}
814
666
 
815
- const receiver = new slack.Receiver();
816
- const app = new App({
817
- token: process.env.SLACK_BOT_TOKEN,
818
- signingSecret: process.env.SLACK_SIGNING_SECRET,
819
- receiver,
820
- });
821
-
822
- // Handle messages in channels (only when @mentioned)
823
- app.event("app_mention", async ({ event }) => {
824
- const chat = await agent.chat.upsert([
825
- "slack",
826
- event.channel,
827
- event.thread_ts ?? event.ts,
828
- ]);
829
- const { message } = await slack.createMessageFromEvent({
830
- client: app.client,
831
- event,
832
- });
833
- await agent.chat.sendMessages(chat.id, [message]);
834
- await app.client.assistant.threads.setStatus({
835
- channel_id: event.channel,
836
- status: "is typing...",
837
- thread_ts: event.thread_ts ?? event.ts,
838
- });
839
- });
840
-
841
- // Handle direct messages (always respond)
842
- app.event("message", async ({ event }) => {
843
- // Ignore bot messages and message changes
844
- if (event.subtype || event.bot_id) {
845
- return;
846
- }
847
- // Only handle DMs (channel type is 'im')
848
- const channelInfo = await app.client.conversations.info({
849
- channel: event.channel,
850
- });
851
- if (!channelInfo.channel?.is_im) {
852
- return;
853
- }
854
- const chat = await agent.chat.upsert(["slack", event.channel]);
855
- const { message } = await slack.createMessageFromEvent({
856
- client: app.client,
857
- event,
858
- });
859
- await agent.chat.sendMessages(chat.id, [message]);
860
- await app.client.assistant.threads.setStatus({
861
- channel_id: event.channel,
862
- status: "is typing...",
863
- thread_ts: event.thread_ts ?? event.ts,
864
- });
865
- });
866
-
867
667
  const agent = new blink.Agent();
868
668
 
869
- agent.on("request", async (request) => {
870
- return receiver.handle(app, request);
871
- });
872
-
873
669
  agent.on("chat", async ({ messages }) => {
874
- const tools = slack.createTools({ client: app.client });
875
- const lastMessage = messages[messages.length - 1];
876
- const threadInfo = lastMessage?.metadata as
877
- | { channel?: string; thread_ts?: string }
878
- | undefined;
879
-
880
- // Add instruction to clear status after completion
881
- if (threadInfo?.channel && threadInfo?.thread_ts) {
882
- const clonedMessages = structuredClone(messages);
883
- const lastClonedMessage = clonedMessages[clonedMessages.length - 1];
884
- if (lastClonedMessage) {
885
- lastClonedMessage.parts.push({
886
- type: "text",
887
- text: \`*INTERNAL INSTRUCTION*: Clear the status of this thread after you finish: channel=\${threadInfo.channel} thread_ts=\${threadInfo.thread_ts}\`,
888
- });
889
- }
890
- messages = clonedMessages;
891
- }
892
-
893
670
  return streamText({
894
671
  {{#if (eq aiProvider "anthropic")}}
895
672
  model: anthropic("claude-sonnet-4-5"),
896
673
  {{else if (eq aiProvider "openai")}}
897
- model: openai("gpt-5-chat-latest"),
674
+ model: openai("gpt-5-codex"),
675
+ providerOptions: {
676
+ openai: {
677
+ reasoningSummary: "detailed",
678
+ },
679
+ },
898
680
  {{else if (eq aiProvider "vercel")}}
899
681
  model: "anthropic/claude-sonnet-4.5",
900
682
  {{else}}
901
683
  // Unknown provider: {{aiProvider}}. Defaulting to Vercel AI Gateway syntax.
902
684
  model: "anthropic/claude-sonnet-4.5",
903
685
  {{/if}}
904
- system: "You are a helpful Slack bot assistant.",
905
- messages: convertToModelMessages(messages, {
906
- ignoreIncompleteToolCalls: true,
907
- tools,
908
- }),
909
- tools,
686
+ system: \`You are a basic agent the user will customize.
687
+
688
+ Suggest the user enters edit mode with Ctrl+T or /edit to customize the agent.
689
+ Demonstrate your capabilities with the IP tool.\`,
690
+ messages: convertToModelMessages(messages),
691
+ tools: {
692
+ get_ip_info: tool({
693
+ description: "Get IP address information of the computer.",
694
+ inputSchema: z.object({}),
695
+ execute: async () => {
696
+ const response = await fetch("https://ipinfo.io/json");
697
+ return response.json();
698
+ },
699
+ }),
700
+ },
910
701
  });
911
702
  });
912
703
 
913
- agent.serve();`,"package.json.hbs":`{
704
+ agent.serve();
705
+ `,"package.json.hbs":`{
914
706
  "name": "{{packageName}}",
915
707
  "main": "agent.ts",
916
708
  "type": "module",
@@ -930,11 +722,54 @@ agent.serve();`,"package.json.hbs":`{
930
722
  "blink": "latest",
931
723
  "esbuild": "latest",
932
724
  "@types/node": "latest",
933
- "typescript": "latest",
934
- "@slack/bolt": "latest",
935
- "@blink-sdk/slack": "latest"
725
+ "typescript": "latest"
936
726
  }
937
727
  }
728
+ `,"tsconfig.json":`{
729
+ "compilerOptions": {
730
+ "lib": ["ESNext"],
731
+ "target": "ESNext",
732
+ "module": "Preserve",
733
+ "moduleDetection": "force",
734
+
735
+ "moduleResolution": "bundler",
736
+ "allowImportingTsExtensions": true,
737
+ "verbatimModuleSyntax": true,
738
+ "resolveJsonModule": true,
739
+ "noEmit": true,
740
+
741
+ "strict": true,
742
+ "skipLibCheck": true,
743
+ "noFallthroughCasesInSwitch": true,
744
+ "noUncheckedIndexedAccess": true,
745
+ "noImplicitOverride": true,
746
+
747
+ "noUnusedLocals": false,
748
+ "noUnusedParameters": false,
749
+
750
+ "types": ["node"]
751
+ }
752
+ }
753
+ `},"slack-bot":{".env.local":`
754
+ # Store local environment variables here.
755
+ # They will be used by blink dev for development.
756
+ SLACK_BOT_TOKEN=xoxb-your-token-here
757
+ SLACK_SIGNING_SECRET=your-signing-secret-here
758
+ `,".env.production":`# Store production environment variables here.
759
+ # They will be upserted as secrets on blink deploy.
760
+ # EXTERNAL_SERVICE_API_KEY=
761
+ `,".gitignore":`# dependencies
762
+ node_modules
763
+
764
+ # config and build
765
+ .blink
766
+
767
+ # dotenv environment variables file
768
+ .env
769
+ .env.*
770
+
771
+ # Finder (MacOS) folder config
772
+ .DS_Store
938
773
  `,"AGENTS.md":`This project is a Blink agent.
939
774
 
940
775
  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.
@@ -1008,7 +843,7 @@ const agent = new blink.Agent();
1008
843
 
1009
844
  agent.on("chat", async ({ messages, chat, abortSignal }) => {
1010
845
  return streamText({
1011
- model: blink.model("anthropic/claude-sonnet-4.5"),
846
+ model: "anthropic/claude-sonnet-4.5",
1012
847
  system: "You are a helpful assistant.",
1013
848
  messages: convertToModelMessages(messages, {
1014
849
  ignoreIncompleteToolCalls: true,
@@ -1152,17 +987,6 @@ Tool Prefixing to avoid collisions:
1152
987
 
1153
988
  LLM Models:
1154
989
 
1155
- **Option 1: Blink Gateway** (Quick Start)
1156
-
1157
- \`\`\`typescript
1158
- model: blink.model("anthropic/claude-sonnet-4.5");
1159
- model: blink.model("openai/gpt-5");
1160
- \`\`\`
1161
-
1162
- Requires: \`blink login\` or \`BLINK_TOKEN\` env var
1163
-
1164
- **Option 2: Direct Provider** (Production Recommended)
1165
-
1166
990
  \`\`\`typescript
1167
991
  import { anthropic } from "@ai-sdk/anthropic";
1168
992
  import { openai } from "@ai-sdk/openai";
@@ -1177,7 +1001,6 @@ model: openai("gpt-5", { apiKey: process.env.OPENAI_API_KEY });
1177
1001
 
1178
1002
  1. If \`ANTHROPIC_API_KEY\` is set: uses \`claude-sonnet-4.5\` via \`@ai-sdk/anthropic\`
1179
1003
  2. If \`OPENAI_API_KEY\` is set: uses \`gpt-5\` via \`@ai-sdk/openai\`
1180
- 3. Otherwise: falls back to \`blink.model("anthropic/claude-sonnet-4.5")\`
1181
1004
 
1182
1005
  Available SDKs:
1183
1006
 
@@ -1247,7 +1070,7 @@ agent.on("request", async (request) => {
1247
1070
  agent.on("chat", async ({ messages }) => {
1248
1071
  const tools = slack.createTools({ client: app.client });
1249
1072
  return streamText({
1250
- model: blink.model("anthropic/claude-sonnet-4.5"),
1073
+ model: "anthropic/claude-sonnet-4.5",
1251
1074
  system: "You chatting with users in Slack.",
1252
1075
  messages: convertToModelMessages(messages, {
1253
1076
  ignoreIncompleteToolCalls: true,
@@ -1271,7 +1094,7 @@ Slack App Manifest:
1271
1094
  - _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.
1272
1095
  - The user can always edit the manifest after creation, but you'd have to suggest it to them.
1273
1096
  - "oauth_config" MUST BE PROVIDED - otherwise the app will have NO ACCESS.
1274
- - _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.
1097
+ - _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.
1275
1098
  - For the best user experience, default to the following bot scopes (in the "oauth_config" > "scopes" > "bot"):
1276
1099
  - "app_mentions:read"
1277
1100
  - "reactions:write"
@@ -1364,6 +1187,169 @@ The agent process can restart at any time, so all important state must be extern
1364
1187
 
1365
1188
  - Never use "as any" type assertions. Always figure out the correct typings.
1366
1189
  </code_quality>
1190
+ `,"agent.ts.hbs":`import { convertToModelMessages, streamText } from "ai";
1191
+ import * as blink from "blink";
1192
+ import * as slack from "@blink-sdk/slack";
1193
+ import { App } from "@slack/bolt";
1194
+ {{#if (eq aiProvider "anthropic")}}
1195
+ import { anthropic } from "@ai-sdk/anthropic";
1196
+ {{else if (eq aiProvider "openai")}}
1197
+ import { openai } from "@ai-sdk/openai";
1198
+ {{/if}}
1199
+
1200
+ const receiver = new slack.Receiver();
1201
+ const app = new App({
1202
+ token: process.env.SLACK_BOT_TOKEN,
1203
+ signingSecret: process.env.SLACK_SIGNING_SECRET,
1204
+ receiver,
1205
+ });
1206
+
1207
+ // Handle messages in channels (only when @mentioned)
1208
+ app.event("app_mention", async ({ event }) => {
1209
+ const chat = await agent.chat.upsert([
1210
+ "slack",
1211
+ event.channel,
1212
+ event.thread_ts ?? event.ts,
1213
+ ]);
1214
+ const { message } = await slack.createMessageFromEvent({
1215
+ client: app.client,
1216
+ event,
1217
+ });
1218
+ await agent.chat.sendMessages(chat.id, [message]);
1219
+ await app.client.assistant.threads.setStatus({
1220
+ channel_id: event.channel,
1221
+ status: "is typing...",
1222
+ thread_ts: event.thread_ts ?? event.ts,
1223
+ });
1224
+ });
1225
+
1226
+ // Handle direct messages (always respond)
1227
+ app.event("message", async ({ event }) => {
1228
+ // Ignore bot messages and message changes
1229
+ if (event.subtype || event.bot_id) {
1230
+ return;
1231
+ }
1232
+ // Only handle DMs (channel type is 'im')
1233
+ const channelInfo = await app.client.conversations.info({
1234
+ channel: event.channel,
1235
+ });
1236
+ if (!channelInfo.channel?.is_im) {
1237
+ return;
1238
+ }
1239
+ const chat = await agent.chat.upsert(["slack", event.channel]);
1240
+ const { message } = await slack.createMessageFromEvent({
1241
+ client: app.client,
1242
+ event,
1243
+ });
1244
+ await agent.chat.sendMessages(chat.id, [message]);
1245
+ await app.client.assistant.threads.setStatus({
1246
+ channel_id: event.channel,
1247
+ status: "is typing...",
1248
+ thread_ts: event.thread_ts ?? event.ts,
1249
+ });
1250
+ });
1251
+
1252
+ const agent = new blink.Agent();
1253
+
1254
+ agent.on("request", async (request) => {
1255
+ return receiver.handle(app, request);
1256
+ });
1257
+
1258
+ agent.on("chat", async ({ messages }) => {
1259
+ const tools = slack.createTools({ client: app.client });
1260
+ const lastMessage = messages[messages.length - 1];
1261
+ const threadInfo = lastMessage?.metadata as
1262
+ | { channel?: string; thread_ts?: string }
1263
+ | undefined;
1264
+
1265
+ // Add instruction to clear status after completion
1266
+ if (threadInfo?.channel && threadInfo?.thread_ts) {
1267
+ const clonedMessages = structuredClone(messages);
1268
+ const lastClonedMessage = clonedMessages[clonedMessages.length - 1];
1269
+ if (lastClonedMessage) {
1270
+ lastClonedMessage.parts.push({
1271
+ type: "text",
1272
+ text: \`*INTERNAL INSTRUCTION*: Clear the status of this thread after you finish: channel=\${threadInfo.channel} thread_ts=\${threadInfo.thread_ts}\`,
1273
+ });
1274
+ }
1275
+ messages = clonedMessages;
1276
+ }
1277
+
1278
+ return streamText({
1279
+ {{#if (eq aiProvider "anthropic")}}
1280
+ model: anthropic("claude-sonnet-4-5"),
1281
+ {{else if (eq aiProvider "openai")}}
1282
+ model: openai("gpt-5-codex"),
1283
+ providerOptions: {
1284
+ openai: {
1285
+ reasoningSummary: "detailed",
1286
+ },
1287
+ },
1288
+ {{else if (eq aiProvider "vercel")}}
1289
+ model: "anthropic/claude-sonnet-4.5",
1290
+ {{else}}
1291
+ // Unknown provider: {{aiProvider}}. Defaulting to Vercel AI Gateway syntax.
1292
+ model: "anthropic/claude-sonnet-4.5",
1293
+ {{/if}}
1294
+ system: "You are a helpful Slack bot assistant.",
1295
+ messages: convertToModelMessages(messages, {
1296
+ ignoreIncompleteToolCalls: true,
1297
+ tools,
1298
+ }),
1299
+ tools,
1300
+ });
1301
+ });
1302
+
1303
+ agent.serve();`,"package.json.hbs":`{
1304
+ "name": "{{packageName}}",
1305
+ "main": "agent.ts",
1306
+ "type": "module",
1307
+ "private": true,
1308
+ "scripts": {
1309
+ "dev": "blink dev",
1310
+ "deploy": "blink deploy"
1311
+ },
1312
+ "devDependencies": {
1313
+ "zod": "latest",
1314
+ "ai": "latest",
1315
+ {{#if (eq aiProvider "anthropic")}}
1316
+ "@ai-sdk/anthropic": "latest",
1317
+ {{else if (eq aiProvider "openai")}}
1318
+ "@ai-sdk/openai": "latest",
1319
+ {{/if}}
1320
+ "blink": "latest",
1321
+ "esbuild": "latest",
1322
+ "@types/node": "latest",
1323
+ "typescript": "latest",
1324
+ "@slack/bolt": "latest",
1325
+ "@blink-sdk/slack": "latest"
1326
+ }
1327
+ }
1328
+ `,"tsconfig.json":`{
1329
+ "compilerOptions": {
1330
+ "lib": ["ESNext"],
1331
+ "target": "ESNext",
1332
+ "module": "Preserve",
1333
+ "moduleDetection": "force",
1334
+
1335
+ "moduleResolution": "bundler",
1336
+ "allowImportingTsExtensions": true,
1337
+ "verbatimModuleSyntax": true,
1338
+ "resolveJsonModule": true,
1339
+ "noEmit": true,
1340
+
1341
+ "strict": true,
1342
+ "skipLibCheck": true,
1343
+ "noFallthroughCasesInSwitch": true,
1344
+ "noUncheckedIndexedAccess": true,
1345
+ "noImplicitOverride": true,
1346
+
1347
+ "noUnusedLocals": false,
1348
+ "noUnusedParameters": false,
1349
+
1350
+ "types": ["node"]
1351
+ }
1352
+ }
1367
1353
  `}};function If(e,n,r){let i,a=u.default.createServer(t.createServerAdapter(async t=>{let o=new URL(t.url,i);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 r?.(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 r?.(t,null)}catch(e){t=e instanceof Error?e:Error(String(e))}let n=t.message;return new Response(`Error: ${n}\n\nReturn to your terminal for more details.`,{status:500,headers:{"Content-Type":`text/plain`}})}finally{a.close()}let c={...e,redirect_url:i},l=`<!DOCTYPE html>
1368
1354
  <html>
1369
1355
  <body>
@@ -1465,4 +1451,4 @@ Slack:
1465
1451
  1. *ALWAYS* use the \`typecheck_agent\` tool to check for type errors before making changes. NEVER invoke \`tsc\` directly.
1466
1452
  2. Use the \`message_user_agent\` tool to test the agent after you make changes.
1467
1453
  </agent_development>
1468
- `});let y=Ff.scratch[`AGENTS.md`];try{y=await(0,m.readFile)((0,d.join)(e.directory,`AGENTS.md`),`utf-8`)}catch{}return _.unshift({role:`system`,content:y}),(0,p.streamText)({model:qf(e.env),messages:_,maxOutputTokens:64e3,tools:g,abortSignal:o,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:n,setUserAgentUrl:e=>{r=e},cleanup:()=>{i&&=(i.close(),void 0)}}}function Kf(e){if(e.ANTHROPIC_API_KEY)return Ce({apiKey:e.ANTHROPIC_API_KEY}).chat(`claude-sonnet-4-5`);if(e.OPENAI_API_KEY)return nr({apiKey:e.OPENAI_API_KEY}).responses(`gpt-5`);if(e.AI_GATEWAY_API_KEY)return t.createGatewayProvider({apiKey:e.AI_GATEWAY_API_KEY})(`anthropic/claude-sonnet-4-5`)}function qf(e){let t=Kf(e);if(!t)throw Error(`No API key available for edit mode`);return t}function Jf(e){let[t,n]=(0,g.useState)(void 0),[r,i]=(0,g.useState)(void 0),[a,o]=(0,g.useState)(!1),s=(0,g.useRef)(void 0);return(0,g.useEffect)(()=>{let t=new AbortController,r=!1;if(i(void 0),n(void 0),!Kf(e.env)){o(!0);return}return o(!1),(async()=>{s.current=Gf({directory:e.directory,env:e.env,getDevhookUrl:e.getDevhookUrl});let r=await Yf(),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 Ir({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]),(0,g.useMemo)(()=>({client:t,error:r,missingApiKey:a,setUserAgentUrl:e=>{s.current?.setUserAgentUrl(e)}}),[t,r,a])}async function Yf(){let e=(0,u.createServer)();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function Xf(e){let{directory:n}=e,[r,i]=(0,g.useState)(),[a,o]=(0,g.useState)(!1),[s,c]=(0,g.useState)(`run`),l=(0,g.useRef)(`run`);(0,g.useEffect)(()=>{l.current=s},[s]);let u=(0,g.useCallback)(t=>{c(t),e.onModeChange?.(t),i(void 0)},[e.onModeChange]),f=(0,g.useCallback)(()=>{u(s===`run`?`edit`:`run`)},[s,u]),{error:m,status:h,result:_,entry:v}=Fu({directory:n,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),y=Pu({autoCheck:!0,onAuthChange:e.onAuthChange,onLoginUrl:e.onLoginUrl}),b=Yd(n),x=(0,g.useMemo)(()=>{let e=y.token;return e?{...b,BLINK_TOKEN:e}:b},[b,y.token]),S=(0,g.useRef)(void 0);(0,g.useEffect)(()=>{let t=Object.keys(x);if(t.length===S.current||S.current===void 0){S.current=t.length;return}S.current=t.length,e.onEnvLoaded?.(t)},[x,e.onEnvLoaded]);let C=(0,g.useRef)(void 0),w=(0,g.useMemo)(()=>Vd({port:0,dataDirectory:(0,d.join)(n,`data`),getAgent:()=>C.current}),[n]),{agent:T,logs:E,error:D,capabilities:O}=Lr({buildResult:_,env:x,apiServerUrl:w.url}),{client:k,error:A,missingApiKey:j,setUserAgentUrl:M}=Jf({directory:n,apiServerUrl:w.url,env:x,getDevhookUrl:(0,g.useCallback)(()=>{let e=gd(n)??_d(n);return ne(e),`https://${e}.blink.host`},[n])}),[N,ee]=(0,g.useState)(`00000000-0000-0000-0000-000000000000`);(0,g.useEffect)(()=>{C.current=T},[T]),(0,g.useEffect)(()=>{T&&M(T.baseUrl),(s===`run`&&!T||s===`edit`&&!k)&&w.getChatManager(N)?.stopStreaming()},[T,k,s,N,w,M]);let P=(0,g.useRef)(void 0),F=pd({chatId:N,agent:s===`run`?T:k,chatsDirectory:w.chatsDirectory,serializeMessage:e=>{let t=e.role===`user`&&P.current?{...typeof e.metadata==`object`&&e.metadata!==null?e.metadata:{},options:P.current}:e.metadata;return typeof t==`object`&&t&&(t.__blink_mode=l.current),{id:e.id??crypto.randomUUID(),created_at:new Date().toISOString(),role:e.role,parts:e.parts,mode:l.current,metadata:t}},filterMessages:e=>l.current===`edit`?!0:!(dd(e.metadata)||e.mode===`edit`)}),te=(0,g.useRef)(0);(0,g.useEffect)(()=>{if(E.length===te.current)return;let t=te.current;for(let n of E.slice(t))e.onAgentLog?.(n);te.current=E.length},[E,e.onAgentLog,F.upsertMessage]);let[I,L]=(0,g.useState)([]);(0,g.useEffect)(()=>{w.listChats().then(e=>{L(e.map(e=>e.key))})},[w]),(0,g.useEffect)(()=>{N&&!I.includes(N)&&L(e=>[...e,N])},[N,I]);let[R,ne]=(0,g.useState)(()=>hd(n)?gd(n):_d(n)),z=Wd({id:R,directory:n,disabled:!O?.request,onRequest:async t=>{if(!T)throw Error(`No agent`);let n=new URL(t.url),r=new URL(T.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})}}});(0,g.useEffect)(()=>{z.status!==`connected`||!z.url||e.onDevhookConnected?.(z.url)},[z.status,z.url]);let{schema:re,options:B,error:ie,setOption:ae}=Hd({agent:s===`run`?T:k,capabilities:O,messages:F.messages});(0,g.useEffect)(()=>{P.current=B},[B]);let oe=(0,g.useMemo)(()=>{let e=new Map;return D&&s===`run`&&e.set(`agent`,D.message),A&&s===`edit`&&e.set(`editAgent`,`Edit agent error: ${A.message}`),F.error&&h!==`building`&&e.set(`chat`,`Chat error: ${F.error}`),ie&&e.set(`options`,`Options error: ${ie.message}`),e},[D,A,F.error,ie,s,h]),se=(0,g.useRef)(new Map);(0,g.useEffect)(()=>{let t=se.current,n=oe;for(let[r,i]of n.entries())t.get(r)!==i&&e.onError?.(i);for(let e of t.keys())n.has(e);se.current=new Map(n)},[oe,e.onError]);let ce=(0,g.useMemo)(()=>{let e=[...F.messages].reverse().find(e=>!(e.role!==`assistant`||e.metadata&&e.metadata.ephemeral));if(!e||r===e.id)return;let n=e.parts.filter(p.isToolOrDynamicToolUIPart);if(n.length!==0&&n.some(e=>t.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`))return e},[F.messages,r]),V=(0,g.useCallback)(async(e,n)=>{if(!ce)return;n&&e&&o(!0),i(ce.id);let r=F.messages;if(r.length===0)return;let a=r[r.length-1];if(!a||a.role!==`assistant`||!Array.isArray(a.parts))return;let s=a.parts.map(n=>n.output&&t.isToolApprovalOutput(n.output)&&n.output.outcome===`pending`?{...n,output:{...n.output,outcome:e?`approved`:`rejected`}}:n);await F.upsertMessage({...a,parts:s}),await F.start()},[ce,F]);(0,g.useEffect)(()=>{a&&ce&&V(!0)},[a,ce,V]);let H=(0,g.useCallback)(()=>{let e=crypto.randomUUID();ee(e),L(t=>[...t,e]),i(void 0)},[]),le=(0,g.useCallback)(e=>{ee(e),i(void 0)},[]),ue=(0,g.useMemo)(()=>{if(ce)return{message:ce,approve:e=>V(!0,e),reject:()=>V(!1),autoApproveEnabled:a}},[ce,V,a]),de=(0,g.useMemo)(()=>{let e=F.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}}},[F.messages]),fe=(0,g.useMemo)(()=>{if(F.status!==`streaming`)return!1;if(!F.streamingMessage)return!0;let e=F.streamingMessage.parts.filter(p.isToolOrDynamicToolUIPart);return e.length>0&&e.every(e=>e.state.startsWith(`output-`))},[F.status,F.streamingMessage]);return{mode:s,setMode:u,toggleMode:f,chat:F,chats:I,switchChat:le,newChat:H,build:{status:h,error:m,entrypoint:v},devhook:{connected:z.status===`connected`,url:z.status===`connected`?z.url:void 0},capabilities:O,options:{schema:re,selected:B,error:ie,setOption:ae},approval:ue,tokenUsage:de,auth:y,server:w,showWaitingPlaceholder:fe,editModeMissingApiKey:j}}exports.useAgent=Lr,exports.useAuth=Pu,exports.useBundler=Fu,exports.useChat=pd,exports.useDevMode=Xf,exports.useDevhook=Wd,exports.useDotenv=Yd,exports.useEditAgent=Jf,exports.useOptions=Hd;
1454
+ `});let y=Ff.scratch[`AGENTS.md`];try{y=await(0,m.readFile)((0,d.join)(e.directory,`AGENTS.md`),`utf-8`)}catch{}return _.unshift({role:`system`,content:y}),(0,p.streamText)({model:qf(e.env),messages:_,maxOutputTokens:64e3,tools:g,abortSignal:o,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:n,setUserAgentUrl:e=>{r=e},cleanup:()=>{i&&=(i.close(),void 0)}}}function Kf(e){if(e.ANTHROPIC_API_KEY)return Ce({apiKey:e.ANTHROPIC_API_KEY}).chat(`claude-sonnet-4-5`);if(e.OPENAI_API_KEY)return nr({apiKey:e.OPENAI_API_KEY}).responses(`gpt-5`);if(e.AI_GATEWAY_API_KEY)return t.createGatewayProvider({apiKey:e.AI_GATEWAY_API_KEY})(`anthropic/claude-sonnet-4-5`)}function qf(e){let t=Kf(e);if(!t)throw Error(`No API key available for edit mode`);return t}function Jf(e){let[t,n]=(0,g.useState)(void 0),[r,i]=(0,g.useState)(void 0),[a,o]=(0,g.useState)(!1),s=(0,g.useRef)(void 0);return(0,g.useEffect)(()=>{let t=new AbortController,r=!1;if(i(void 0),n(void 0),!Kf(e.env)){o(!0);return}return o(!1),(async()=>{s.current=Gf({directory:e.directory,env:e.env,getDevhookUrl:e.getDevhookUrl});let r=await Yf(),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 Ir({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]),(0,g.useMemo)(()=>({client:t,error:r,missingApiKey:a,setUserAgentUrl:e=>{s.current?.setUserAgentUrl(e)}}),[t,r,a])}async function Yf(){let e=(0,u.createServer)();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function Xf(e){let{directory:n}=e,[r,i]=(0,g.useState)(),[a,o]=(0,g.useState)(!1),[s,c]=(0,g.useState)(`run`),l=(0,g.useRef)(`run`);(0,g.useEffect)(()=>{l.current=s},[s]);let u=(0,g.useCallback)(t=>{c(t),e.onModeChange?.(t),i(void 0)},[e.onModeChange]),f=(0,g.useCallback)(()=>{u(s===`run`?`edit`:`run`)},[s,u]),{error:m,status:h,result:_,entry:v}=Fu({directory:n,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),y=Pu({autoCheck:!0,onAuthChange:e.onAuthChange,onLoginUrl:e.onLoginUrl}),b=Yd(n),x=(0,g.useMemo)(()=>{let e=y.token;return e?{...b,BLINK_TOKEN:e}:b},[b,y.token]),S=(0,g.useRef)(void 0);(0,g.useEffect)(()=>{let t=Object.keys(x);if(t.length===S.current||S.current===void 0){S.current=t.length;return}S.current=t.length,e.onEnvLoaded?.(t)},[x,e.onEnvLoaded]);let C=(0,g.useRef)(void 0),w=(0,g.useMemo)(()=>Vd({port:0,dataDirectory:(0,d.join)(n,`.blink`),getAgent:()=>C.current}),[n]),{agent:T,logs:E,error:D,capabilities:O}=Lr({buildResult:_,env:x,apiServerUrl:w.url}),{client:k,error:A,missingApiKey:j,setUserAgentUrl:M}=Jf({directory:n,apiServerUrl:w.url,env:x,getDevhookUrl:(0,g.useCallback)(()=>{let e=gd(n)??_d(n);return ne(e),`https://${e}.blink.host`},[n])}),[N,ee]=(0,g.useState)(`00000000-0000-0000-0000-000000000000`);(0,g.useEffect)(()=>{C.current=T},[T]),(0,g.useEffect)(()=>{T&&M(T.baseUrl),(s===`run`&&!T||s===`edit`&&!k)&&w.getChatManager(N)?.stopStreaming()},[T,k,s,N,w,M]);let P=(0,g.useRef)(void 0),F=pd({chatId:N,agent:s===`run`?T:k,chatsDirectory:w.chatsDirectory,serializeMessage:e=>{let t=e.role===`user`&&P.current?{...typeof e.metadata==`object`&&e.metadata!==null?e.metadata:{},options:P.current}:e.metadata;return typeof t==`object`&&t&&(t.__blink_mode=l.current),{id:e.id??crypto.randomUUID(),created_at:new Date().toISOString(),role:e.role,parts:e.parts,mode:l.current,metadata:t}},filterMessages:e=>l.current===`edit`?!0:!(dd(e.metadata)||e.mode===`edit`)}),te=(0,g.useRef)(0);(0,g.useEffect)(()=>{if(E.length===te.current)return;let t=te.current;for(let n of E.slice(t))e.onAgentLog?.(n);te.current=E.length},[E,e.onAgentLog,F.upsertMessage]);let[I,L]=(0,g.useState)([]);(0,g.useEffect)(()=>{w.listChats().then(e=>{L(e.map(e=>e.key))})},[w]),(0,g.useEffect)(()=>{N&&!I.includes(N)&&L(e=>[...e,N])},[N,I]);let[R,ne]=(0,g.useState)(()=>hd(n)?gd(n):_d(n)),z=Wd({id:R,directory:n,disabled:!O?.request,onRequest:async t=>{if(!T)throw Error(`No agent`);let n=new URL(t.url),r=new URL(T.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})}}});(0,g.useEffect)(()=>{z.status!==`connected`||!z.url||e.onDevhookConnected?.(z.url)},[z.status,z.url]);let{schema:re,options:B,error:ie,setOption:ae}=Hd({agent:s===`run`?T:k,capabilities:O,messages:F.messages});(0,g.useEffect)(()=>{P.current=B},[B]);let oe=(0,g.useMemo)(()=>{let e=new Map;return D&&s===`run`&&e.set(`agent`,D.message),A&&s===`edit`&&e.set(`editAgent`,`Edit agent error: ${A.message}`),F.error&&h!==`building`&&e.set(`chat`,`Chat error: ${F.error}`),ie&&e.set(`options`,`Options error: ${ie.message}`),e},[D,A,F.error,ie,s,h]),se=(0,g.useRef)(new Map);(0,g.useEffect)(()=>{let t=se.current,n=oe;for(let[r,i]of n.entries())t.get(r)!==i&&e.onError?.(i);for(let e of t.keys())n.has(e);se.current=new Map(n)},[oe,e.onError]);let ce=(0,g.useMemo)(()=>{let e=[...F.messages].reverse().find(e=>!(e.role!==`assistant`||e.metadata&&e.metadata.ephemeral));if(!e||r===e.id)return;let n=e.parts.filter(p.isToolOrDynamicToolUIPart);if(n.length!==0&&n.some(e=>t.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`))return e},[F.messages,r]),V=(0,g.useCallback)(async(e,n)=>{if(!ce)return;n&&e&&o(!0),i(ce.id);let r=F.messages;if(r.length===0)return;let a=r[r.length-1];if(!a||a.role!==`assistant`||!Array.isArray(a.parts))return;let s=a.parts.map(n=>n.output&&t.isToolApprovalOutput(n.output)&&n.output.outcome===`pending`?{...n,output:{...n.output,outcome:e?`approved`:`rejected`}}:n);await F.upsertMessage({...a,parts:s}),await F.start()},[ce,F]);(0,g.useEffect)(()=>{a&&ce&&V(!0)},[a,ce,V]);let H=(0,g.useCallback)(()=>{let e=crypto.randomUUID();ee(e),L(t=>[...t,e]),i(void 0)},[]),le=(0,g.useCallback)(e=>{ee(e),i(void 0)},[]),ue=(0,g.useMemo)(()=>{if(ce)return{message:ce,approve:e=>V(!0,e),reject:()=>V(!1),autoApproveEnabled:a}},[ce,V,a]),de=(0,g.useMemo)(()=>{let e=F.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}}},[F.messages]),fe=(0,g.useMemo)(()=>{if(F.status!==`streaming`)return!1;if(!F.streamingMessage)return!0;let e=F.streamingMessage.parts.filter(p.isToolOrDynamicToolUIPart);return e.length>0&&e.every(e=>e.state.startsWith(`output-`))},[F.status,F.streamingMessage]);return{mode:s,setMode:u,toggleMode:f,chat:F,chats:I,switchChat:le,newChat:H,build:{status:h,error:m,entrypoint:v},devhook:{connected:z.status===`connected`,url:z.status===`connected`?z.url:void 0},capabilities:O,options:{schema:re,selected:B,error:ie,setOption:ae},approval:ue,tokenUsage:de,auth:y,server:w,showWaitingPlaceholder:fe,editModeMissingApiKey:j}}exports.useAgent=Lr,exports.useAuth=Pu,exports.useBundler=Fu,exports.useChat=pd,exports.useDevMode=Xf,exports.useDevhook=Wd,exports.useDotenv=Yd,exports.useEditAgent=Jf,exports.useOptions=Hd;