blink 1.1.34 → 1.1.35

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 (33) hide show
  1. package/dist/browser/control/index.d.cts +16 -16
  2. package/dist/browser/control/index.d.ts +16 -16
  3. package/dist/cli/chat-BfOX7Zpn.js +1 -0
  4. package/dist/cli/{chat-manager-bMAuoSb5.js → chat-manager-cUXPlLU4.js} +6 -6
  5. package/dist/cli/connect-3pBvxI6u.js +1 -0
  6. package/dist/cli/connect-XRcF_tn8.js +1 -0
  7. package/dist/cli/{create-github-app-Dld06QIC.js → create-github-app-CaCP607a.js} +1 -1
  8. package/dist/cli/{dev-9EzQCNmd.js → dev-DOvBAIjm.js} +143 -136
  9. package/dist/cli/index.js +4 -4
  10. package/dist/cli/{init-CByRT25U.js → init-LtTUYXzn.js} +1 -1
  11. package/dist/cli/{run-Lp28Ogb_.js → run-BHKBjgkK.js} +1 -1
  12. package/dist/cli/setup-github-app-DBiuq7cy.js +9 -0
  13. package/dist/cli/{token-util-DIx5k-1f.js → token-util-3NkPUSqu.js} +1 -1
  14. package/dist/cli/{token-util-h1hcKvQX.js → token-util-BgEcL2NM.js} +1 -1
  15. package/dist/cli/{token-ClGOahUF.js → token-v4NJW7VU.js} +1 -1
  16. package/dist/node/agent/index.node.cjs +1 -1
  17. package/dist/node/agent/index.node.js +1 -1
  18. package/dist/node/{index.node-Btg8Ii_o.cjs → index.node-CFR7FTuY.cjs} +4 -4
  19. package/dist/node/{index.node-xL4mvvNL.js → index.node-CITcyk6b.js} +4 -4
  20. package/dist/node/react/index.node.cjs +7 -7
  21. package/dist/node/react/index.node.js +7 -7
  22. package/dist/node/{token-CI2_C_5D.js → token-B2MtKe6w.js} +1 -1
  23. package/dist/node/{token-D4jFpAk0.cjs → token-BQ-EqDMB.cjs} +1 -1
  24. package/dist/node/{token-util-BxSJFXkT.cjs → token-util--zh4M6Ze.cjs} +1 -1
  25. package/dist/node/{token-util-idU3T5iM.js → token-util-CtaB7NzM.js} +1 -1
  26. package/dist/node/token-util-P8_cV3Yu.cjs +1 -0
  27. package/dist/node/{token-util-ChGcRyiF.js → token-util-RdQsj3MK.js} +1 -1
  28. package/package.json +10 -8
  29. package/dist/cli/chat-mj0wnV3_.js +0 -1
  30. package/dist/cli/connect-BnhWpzRI.js +0 -1
  31. package/dist/cli/connect-Cd-0O7Uu.js +0 -1
  32. package/dist/cli/setup-github-app-D-K7e6al.js +0 -9
  33. package/dist/node/token-util-BENsR1Bn.cjs +0 -1
@@ -1,4 +1,4 @@
1
- const e=require(`../chunk-iXuH7AlR.cjs`),t=require(`../index.node-Btg8Ii_o.cjs`);require(`../token-error-BoNG8ooW.cjs`),require(`../esm-0UNjvroT.cjs`);const n=require(`../build-EgdtUZTI.cjs`);let r=require(`zod/v4`);r=e.__toESM(r);let i=require(`zod/v3`);i=e.__toESM(i);let a=require(`node:buffer`);a=e.__toESM(a);let o=require(`node:fs`);o=e.__toESM(o);let s=require(`node:url`);s=e.__toESM(s);let c=require(`node:stream`);c=e.__toESM(c);let l=require(`node:util`);l=e.__toESM(l);let u=require(`node:crypto`);u=e.__toESM(u);let d=require(`http`);d=e.__toESM(d);let f=require(`path`);f=e.__toESM(f);let p=require(`fs`);p=e.__toESM(p);let m=require(`ai`);m=e.__toESM(m);let h=require(`fs/promises`);h=e.__toESM(h);let g=require(`child_process`);g=e.__toESM(g);let _=require(`react`);_=e.__toESM(_);let v=require(`node:module`);v=e.__toESM(v);let y=require(`zod`);y=e.__toESM(y);let b=require(`node:path`);b=e.__toESM(b);let x=require(`node:process`);x=e.__toESM(x);let S=require(`node:os`);S=e.__toESM(S);let C=require(`node:tty`);C=e.__toESM(C);let w=require(`node:readline`);w=e.__toESM(w);let T=require(`node:child_process`);T=e.__toESM(T);let E=require(`node:fs/promises`);E=e.__toESM(E),require(`@blink-sdk/compute-protocol/client`);let D=require(`@blink-sdk/compute-protocol/transport`);D=e.__toESM(D);function O(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function k(e){return Object.fromEntries([...e.headers])}function A(e=globalThis){return e.window?`runtime/browser`:e.navigator?.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:e.process?.versions?.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?`runtime/vercel-edge`:`runtime/unknown`}function j(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function M(e,...t){let n=j(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var N=({prefix:e,size:n=16,alphabet:r=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:i=`-`}={})=>{let a=()=>{let e=r.length,t=Array(n);for(let i=0;i<n;i++)t[i]=r[Math.random()*e|0];return t.join(``)};if(e==null)return a;if(r.includes(i))throw new t.InvalidArgumentError({argument:`separator`,message:`The separator "${i}" must not be part of the alphabet "${r}".`});return()=>`${e}${i}${a()}`},P=N();function F(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var ee=[`fetch failed`,`failed to fetch`];function te({error:e,url:n,requestBodyValues:r}){if(F(e))return e;if(e instanceof TypeError&&ee.includes(e.message.toLowerCase())){let i=e.cause;if(i!=null)return new t.APICallError({message:`Cannot connect to API: ${i.message}`,cause:i,url:n,requestBodyValues:r,isRetryable:!0})}return e}var I=`3.0.10`;function ne({apiKey:e,environmentVariableName:n,apiKeyParameterName:r=`apiKey`,description:i}){if(typeof e==`string`)return e;if(e!=null)throw new t.LoadAPIKeyError({message:`${i} API key must be a string.`});if(typeof process>`u`)throw new t.LoadAPIKeyError({message:`${i} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[n],e==null)throw new t.LoadAPIKeyError({message:`${i} API key is missing. Pass it using the '${r}' parameter or the ${n} environment variable.`});if(typeof e!=`string`)throw new t.LoadAPIKeyError({message:`${i} API key must be a string. The value of the ${n} environment variable is not a string.`});return e}var L=/"__proto__"\s*:/,re=/"constructor"\s*:/;function R(e){let t=JSON.parse(e);return typeof t!=`object`||!t||L.test(e)===!1&&re.test(e)===!1?t:z(t)}function z(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function B(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return R(e)}finally{Error.stackTraceLimit=t}}var ie=Symbol.for(`vercel.ai.validator`);function ae(e){return{[ie]:!0,validate:e}}function oe(e){return typeof e==`object`&&!!e&&ie in e&&e[ie]===!0&&`validate`in e}function se(e){return oe(e)?e:ce(e)}function ce(e){return ae(async n=>{let r=await e[`~standard`].validate(n);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new t.TypeValidationError({value:n,cause:r.issues})}})}async function V({value:e,schema:n}){let r=await le({value:e,schema:n});if(!r.success)throw t.TypeValidationError.wrap({value:e,cause:r.error});return r.value}async function le({value:e,schema:n}){let r=se(n);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};let n=await r.validate(e);return n.success?{success:!0,value:n.value,rawValue:e}:{success:!1,error:t.TypeValidationError.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:t.TypeValidationError.wrap({value:e,cause:n}),rawValue:e}}}async function ue({text:e,schema:n}){try{let t=B(e);return n==null?t:V({value:t,schema:n})}catch(n){throw t.JSONParseError.isInstance(n)||t.TypeValidationError.isInstance(n)?n:new t.JSONParseError({text:e,cause:n})}}async function de({text:e,schema:n}){try{let t=B(e);return n==null?{success:!0,value:t,rawValue:t}:await le({value:t,schema:n})}catch(n){return{success:!1,error:t.JSONParseError.isInstance(n)?n:new t.JSONParseError({text:e,cause:n}),rawValue:void 0}}}function fe({stream:e,schema:n}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new t.EventSourceParserStream).pipeThrough(new TransformStream({async transform({data:e},t){e!==`[DONE]`&&t.enqueue(await de({text:e,schema:n}))}}))}async function pe({provider:e,providerOptions:n,schema:r}){if(n?.[e]==null)return;let i=await le({value:n[e],schema:r});if(!i.success)throw new t.InvalidArgumentError({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:i.error});return i.value}var me=()=>globalThis.fetch,he=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>ge({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),ge=async({url:e,headers:n={},body:r,successfulResponseHandler:i,failedResponseHandler:a,abortSignal:o,fetch:s=me()})=>{try{let c=await s(e,{method:`POST`,headers:M(n,`ai-sdk/provider-utils/${I}`,A()),body:r.content,signal:o}),l=k(c);if(!c.ok){let n;try{n=await a({response:c,url:e,requestBodyValues:r.values})}catch(n){throw F(n)||t.APICallError.isInstance(n)?n:new t.APICallError({message:`Failed to process error response`,cause:n,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw n.value}try{return await i({response:c,url:e,requestBodyValues:r.values})}catch(n){throw n instanceof Error&&(F(n)||t.APICallError.isInstance(n))?n:new t.APICallError({message:`Failed to process successful response`,cause:n,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(t){throw te({error:t,url:e,requestBodyValues:r.values})}};function _e(e){return e}function ve({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>_e({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function ye({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>_e({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:r,execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}async function be(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var H=({errorSchema:e,errorToMessage:n,isRetryable:r})=>async({response:i,url:a,requestBodyValues:o})=>{let s=await i.text(),c=k(i);if(s.trim()===``)return{responseHeaders:c,value:new t.APICallError({message:i.statusText,url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,isRetryable:r?.(i)})};try{let l=await ue({text:s,schema:e});return{responseHeaders:c,value:new t.APICallError({message:n(l),url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,data:l,isRetryable:r?.(i,l)})}}catch{return{responseHeaders:c,value:new t.APICallError({message:i.statusText,url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,isRetryable:r?.(i)})}}},xe=e=>async({response:n})=>{let r=k(n);if(n.body==null)throw new t.EmptyResponseBodyError({});return{responseHeaders:r,value:fe({stream:n.body,schema:e})}},Se=e=>async({response:n,url:r,requestBodyValues:i})=>{let a=await n.text(),o=await de({text:a,schema:e}),s=k(n);if(!o.success)throw new t.APICallError({message:`Invalid JSON response`,cause:o.error,statusCode:n.status,responseHeaders:s,responseBody:a,url:r,requestBodyValues:i});return{responseHeaders:s,value:o.value,rawValue:o.rawValue}},Ce=Symbol(`Let zodToJsonSchema decide on which parser to use`),we=Symbol.for(`vercel.ai.schema`),{btoa:Te,atob:Ee}=globalThis;function De(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return Te(t)}function Oe(e){return e instanceof Uint8Array?De(e):e}function ke(e){return e?.replace(/\/$/,``)}var Ae=`2.0.23`,je=r.z.object({type:r.z.literal(`error`),error:r.z.object({type:r.z.string(),message:r.z.string()})}),Me=H({errorSchema:je,errorToMessage:e=>e.error.message}),U=r.z.object({citations:r.z.object({enabled:r.z.boolean()}).optional(),title:r.z.string().optional(),context:r.z.string().optional()}),Ne=r.z.object({sendReasoning:r.z.boolean().optional(),thinking:r.z.object({type:r.z.union([r.z.literal(`enabled`),r.z.literal(`disabled`)]),budgetTokens:r.z.number().optional()}).optional(),disableParallelToolUse:r.z.boolean().optional(),cacheControl:r.z.object({type:r.z.literal(`ephemeral`),ttl:r.z.union([r.z.literal(`5m`),r.z.literal(`1h`)]).optional()}).optional()});function Pe(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var Fe=r.z.object({maxCharacters:r.z.number().optional()}),Ie=ve({id:`anthropic.text_editor_20250728`,name:`str_replace_based_edit_tool`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),Le=(e={})=>Ie(e),Re=r.z.object({maxUses:r.z.number().optional(),allowedDomains:r.z.array(r.z.string()).optional(),blockedDomains:r.z.array(r.z.string()).optional(),userLocation:r.z.object({type:r.z.literal(`approximate`),city:r.z.string().optional(),region:r.z.string().optional(),country:r.z.string().optional(),timezone:r.z.string().optional()}).optional()}),ze=r.z.array(r.z.object({url:r.z.string(),title:r.z.string(),pageAge:r.z.string().nullable(),encryptedContent:r.z.string(),type:r.z.literal(`web_search_result`)})),Be=ye({id:`anthropic.web_search_20250305`,name:`web_search`,inputSchema:r.z.object({query:r.z.string()}),outputSchema:ze}),Ve=(e={})=>Be(e),He=r.z.object({maxUses:r.z.number().optional(),allowedDomains:r.z.array(r.z.string()).optional(),blockedDomains:r.z.array(r.z.string()).optional(),citations:r.z.object({enabled:r.z.boolean()}).optional(),maxContentTokens:r.z.number().optional()}),Ue=r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.union([r.z.object({type:r.z.literal(`base64`),mediaType:r.z.literal(`application/pdf`),data:r.z.string()}),r.z.object({type:r.z.literal(`text`),mediaType:r.z.literal(`text/plain`),data:r.z.string()})])}),retrievedAt:r.z.string().nullable()}),We=ye({id:`anthropic.web_fetch_20250910`,name:`web_fetch`,inputSchema:r.z.object({url:r.z.string()}),outputSchema:Ue}),Ge=(e={})=>We(e);function Ke({tools:e,toolChoice:n,disableParallelToolUse:r}){e=e?.length?e:void 0;let i=[],a=new Set;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:a};let o=[];for(let t of e)switch(t.type){case`function`:{let e=Pe(t.providerOptions);o.push({name:t.name,description:t.description,input_schema:t.inputSchema,cache_control:e});break}case`provider-defined`:switch(t.id){case`anthropic.code_execution_20250522`:a.add(`code-execution-2025-05-22`),o.push({type:`code_execution_20250522`,name:`code_execution`});break;case`anthropic.computer_20250124`:a.add(`computer-use-2025-01-24`),o.push({name:`computer`,type:`computer_20250124`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.computer_20241022`:a.add(`computer-use-2024-10-22`),o.push({name:`computer`,type:`computer_20241022`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.text_editor_20250124`:a.add(`computer-use-2025-01-24`),o.push({name:`str_replace_editor`,type:`text_editor_20250124`});break;case`anthropic.text_editor_20241022`:a.add(`computer-use-2024-10-22`),o.push({name:`str_replace_editor`,type:`text_editor_20241022`});break;case`anthropic.text_editor_20250429`:a.add(`computer-use-2025-01-24`),o.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`});break;case`anthropic.text_editor_20250728`:{let e=Fe.parse(t.args);o.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250728`,max_characters:e.maxCharacters});break}case`anthropic.bash_20250124`:a.add(`computer-use-2025-01-24`),o.push({name:`bash`,type:`bash_20250124`});break;case`anthropic.bash_20241022`:a.add(`computer-use-2024-10-22`),o.push({name:`bash`,type:`bash_20241022`});break;case`anthropic.web_fetch_20250910`:{a.add(`web-fetch-2025-09-10`);let e=He.parse(t.args);o.push({type:`web_fetch_20250910`,name:`web_fetch`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens});break}case`anthropic.web_search_20250305`:{let e=Re.parse(t.args);o.push({type:`web_search_20250305`,name:`web_search`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation});break}default:i.push({type:`unsupported-tool`,tool:t});break}break;default:i.push({type:`unsupported-tool`,tool:t});break}if(n==null)return{tools:o,toolChoice:r?{type:`auto`,disable_parallel_tool_use:r}:void 0,toolWarnings:i,betas:a};let s=n.type;switch(s){case`auto`:return{tools:o,toolChoice:{type:`auto`,disable_parallel_tool_use:r},toolWarnings:i,betas:a};case`required`:return{tools:o,toolChoice:{type:`any`,disable_parallel_tool_use:r},toolWarnings:i,betas:a};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:a};case`tool`:return{tools:o,toolChoice:{type:`tool`,name:n.toolName,disable_parallel_tool_use:r},toolWarnings:i,betas:a};default:throw new t.UnsupportedFunctionalityError({functionality:`tool choice type: ${s}`})}}var qe=r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),Je=ye({id:`anthropic.code_execution_20250522`,name:`code_execution`,inputSchema:r.z.object({code:r.z.string()}),outputSchema:qe}),Ye=(e={})=>Je(e);function Xe(e){if(typeof e==`string`)return Buffer.from(e,`base64`).toString(`utf-8`);if(e instanceof Uint8Array)return new TextDecoder().decode(e);throw e instanceof URL?new t.UnsupportedFunctionalityError({functionality:`URL-based text documents are not supported for citations`}):new t.UnsupportedFunctionalityError({functionality:`unsupported data type for text documents: ${typeof e}`})}async function Ze({prompt:e,sendReasoning:n,warnings:r}){let i=new Set,a=Qe(e),o,s=[];async function c(e){return(await pe({provider:`anthropic`,providerOptions:e,schema:U}))?.citations?.enabled??!1}async function l(e){let t=await pe({provider:`anthropic`,providerOptions:e,schema:U});return{title:t?.title,context:t?.context}}for(let e=0;e<a.length;e++){let u=a[e],d=e===a.length-1,f=u.type;switch(f){case`system`:if(o!=null)throw new t.UnsupportedFunctionalityError({functionality:`Multiple system messages that are separated by user/assistant messages`});o=u.messages.map(({content:e,providerOptions:t})=>({type:`text`,text:e,cache_control:Pe(t)}));break;case`user`:{let e=[];for(let n of u.messages){let{role:r,content:a}=n;switch(r){case`user`:for(let r=0;r<a.length;r++){let o=a[r],s=r===a.length-1,u=Pe(o.providerOptions)??(s?Pe(n.providerOptions):void 0);switch(o.type){case`text`:e.push({type:`text`,text:o.text,cache_control:u});break;case`file`:if(o.mediaType.startsWith(`image/`))e.push({type:`image`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`base64`,media_type:o.mediaType===`image/*`?`image/jpeg`:o.mediaType,data:Oe(o.data)},cache_control:u});else if(o.mediaType===`application/pdf`){i.add(`pdfs-2024-09-25`);let t=await c(o.providerOptions),n=await l(o.providerOptions);e.push({type:`document`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`base64`,media_type:`application/pdf`,data:Oe(o.data)},title:n.title??o.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:u})}else if(o.mediaType===`text/plain`){let t=await c(o.providerOptions),n=await l(o.providerOptions);e.push({type:`document`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`text`,media_type:`text/plain`,data:Xe(o.data)},title:n.title??o.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:u})}else throw new t.UnsupportedFunctionalityError({functionality:`media type: ${o.mediaType}`});break}}break;case`tool`:for(let r=0;r<a.length;r++){let i=a[r],o=r===a.length-1,s=Pe(i.providerOptions)??(o?Pe(n.providerOptions):void 0),c=i.output,l;switch(c.type){case`content`:l=c.value.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text,cache_control:void 0};case`media`:if(e.mediaType.startsWith(`image/`))return{type:`image`,source:{type:`base64`,media_type:e.mediaType,data:e.data},cache_control:void 0};throw new t.UnsupportedFunctionalityError({functionality:`media type: ${e.mediaType}`})}});break;case`text`:case`error-text`:l=c.value;break;case`json`:case`error-json`:default:l=JSON.stringify(c.value);break}e.push({type:`tool_result`,tool_use_id:i.toolCallId,content:l,is_error:c.type===`error-text`||c.type===`error-json`?!0:void 0,cache_control:s})}break;default:{let e=r;throw Error(`Unsupported role: ${e}`)}}}s.push({role:`user`,content:e});break}case`assistant`:{let e=[];for(let t=0;t<u.messages.length;t++){let i=u.messages[t],a=t===u.messages.length-1,{content:o}=i;for(let t=0;t<o.length;t++){let s=o[t],c=t===o.length-1,l=Pe(s.providerOptions)??(c?Pe(i.providerOptions):void 0);switch(s.type){case`text`:e.push({type:`text`,text:d&&a&&c?s.text.trim():s.text,cache_control:l});break;case`reasoning`:if(n){let t=await pe({provider:`anthropic`,providerOptions:s.providerOptions,schema:st});t==null?r.push({type:`other`,message:`unsupported reasoning metadata`}):t.signature==null?t.redactedData==null?r.push({type:`other`,message:`unsupported reasoning metadata`}):e.push({type:`redacted_thinking`,data:t.redactedData,cache_control:l}):e.push({type:`thinking`,thinking:s.text,signature:t.signature,cache_control:l})}else r.push({type:`other`,message:`sending reasoning content is disabled for this model`});break;case`tool-call`:if(s.providerExecuted){s.toolName===`code_execution`||s.toolName===`web_fetch`||s.toolName===`web_search`?e.push({type:`server_tool_use`,id:s.toolCallId,name:s.toolName,input:s.input,cache_control:l}):r.push({type:`other`,message:`provider executed tool call for tool ${s.toolName} is not supported`});break}e.push({type:`tool_use`,id:s.toolCallId,name:s.toolName,input:s.input,cache_control:l});break;case`tool-result`:if(s.toolName===`code_execution`){let t=s.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let n=qe.parse(t.value);e.push({type:`code_execution_tool_result`,tool_use_id:s.toolCallId,content:{type:n.type,stdout:n.stdout,stderr:n.stderr,return_code:n.return_code},cache_control:l});break}if(s.toolName===`web_fetch`){let t=s.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let n=Ue.parse(t.value);e.push({type:`web_fetch_tool_result`,tool_use_id:s.toolCallId,content:{type:`web_fetch_result`,url:n.url,retrieved_at:n.retrievedAt,content:{type:`document`,title:n.content.title,citations:n.content.citations,source:{type:n.content.source.type,media_type:n.content.source.mediaType,data:n.content.source.data}}},cache_control:l});break}if(s.toolName===`web_search`){let t=s.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let n=ze.parse(t.value);e.push({type:`web_search_tool_result`,tool_use_id:s.toolCallId,content:n.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:l});break}r.push({type:`other`,message:`provider executed tool result for tool ${s.toolName} is not supported`});break}}}s.push({role:`assistant`,content:e});break}default:{let e=f;throw Error(`content type: ${e}`)}}}return{prompt:{system:o,messages:s},betas:i}}function Qe(e){let t=[],n;for(let r of e){let{role:e}=r;switch(e){case`system`:n?.type!==`system`&&(n={type:`system`,messages:[]},t.push(n)),n.messages.push(r);break;case`assistant`:n?.type!==`assistant`&&(n={type:`assistant`,messages:[]},t.push(n)),n.messages.push(r);break;case`user`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;case`tool`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;default:{let t=e;throw Error(`Unsupported role: ${t}`)}}}return t}function $e({finishReason:e,isJsonResponseFromTool:t}){switch(e){case`pause_turn`:case`end_turn`:case`stop_sequence`:return`stop`;case`refusal`:return`content-filter`;case`tool_use`:return t?`stop`:`tool-calls`;case`max_tokens`:return`length`;default:return`unknown`}}var et={webSearchResult:r.z.object({type:r.z.literal(`web_search_result_location`),cited_text:r.z.string(),url:r.z.string(),title:r.z.string(),encrypted_index:r.z.string()}),pageLocation:r.z.object({type:r.z.literal(`page_location`),cited_text:r.z.string(),document_index:r.z.number(),document_title:r.z.string().nullable(),start_page_number:r.z.number(),end_page_number:r.z.number()}),charLocation:r.z.object({type:r.z.literal(`char_location`),cited_text:r.z.string(),document_index:r.z.number(),document_title:r.z.string().nullable(),start_char_index:r.z.number(),end_char_index:r.z.number()})},tt=r.z.discriminatedUnion(`type`,[et.webSearchResult,et.pageLocation,et.charLocation]);r.z.discriminatedUnion(`type`,[et.pageLocation,et.charLocation]);function nt(e,t,n,r){if(e.type===`page_location`||e.type===`char_location`){let i=rt(e,t,n);i&&r(i)}}function rt(e,t,n){let r=t[e.document_index];if(!r)return null;let i=e.type===`page_location`?{citedText:e.cited_text,startPageNumber:e.start_page_number,endPageNumber:e.end_page_number}:{citedText:e.cited_text,startCharIndex:e.start_char_index,endCharIndex:e.end_char_index};return{type:`source`,sourceType:`document`,id:n(),mediaType:r.mediaType,title:e.document_title??r.title,filename:r.filename,providerMetadata:{anthropic:i}}}var it=class{constructor(e,t){this.specificationVersion=`v2`,this.modelId=e,this.config=t,this.generateId=t.generateId??P}supportsUrl(e){return e.protocol===`https:`}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:n=4096,temperature:r,topP:i,topK:a,frequencyPenalty:o,presencePenalty:s,stopSequences:c,responseFormat:l,seed:u,tools:d,toolChoice:f,providerOptions:p}){let m=[];o!=null&&m.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),s!=null&&m.push({type:`unsupported-setting`,setting:`presencePenalty`}),u!=null&&m.push({type:`unsupported-setting`,setting:`seed`}),l?.type===`json`&&(l.schema==null?m.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format requires a schema. The response format is ignored.`}):d!=null&&m.push({type:`unsupported-setting`,setting:`tools`,details:`JSON response format does not support tools. The provided tools are ignored.`}));let h=l?.type===`json`&&l.schema!=null?{type:`function`,name:`json`,description:`Respond with a JSON object.`,inputSchema:l.schema}:void 0,g=await pe({provider:`anthropic`,providerOptions:p,schema:Ne}),{prompt:_,betas:v}=await Ze({prompt:e,sendReasoning:g?.sendReasoning??!0,warnings:m}),y=g?.thinking?.type===`enabled`,b=g?.thinking?.budgetTokens,x={model:this.modelId,max_tokens:n,temperature:r,top_k:a,top_p:i,stop_sequences:c,...y&&{thinking:{type:`enabled`,budget_tokens:b}},system:_.system,messages:_.messages};if(y){if(b==null)throw new t.UnsupportedFunctionalityError({functionality:`thinking requires a budget`});x.temperature!=null&&(x.temperature=void 0,m.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported when thinking is enabled`})),a!=null&&(x.top_k=void 0,m.push({type:`unsupported-setting`,setting:`topK`,details:`topK is not supported when thinking is enabled`})),i!=null&&(x.top_p=void 0,m.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported when thinking is enabled`})),x.max_tokens=n+b}let{tools:S,toolChoice:C,toolWarnings:w,betas:T}=Ke(h==null?{tools:d??[],toolChoice:f,disableParallelToolUse:g?.disableParallelToolUse}:{tools:[h],toolChoice:{type:`tool`,toolName:h.name},disableParallelToolUse:!0});return{args:{...x,tools:S,tool_choice:C},warnings:[...m,...w],betas:new Set([...v,...T]),usesJsonResponseTool:h!=null}}async getHeaders({betas:e,headers:t}){return O(await be(this.config.headers),e.size>0?{"anthropic-beta":Array.from(e).join(`,`)}:{},t)}buildRequestUrl(e){var t;return(t=this.config).buildRequestUrl?.call(t,this.config.baseURL,e)??`${this.config.baseURL}/messages`}transformRequestBody(e){var t;return(t=this.config).transformRequestBody?.call(t,e)??e}extractCitationDocuments(e){return e.filter(e=>e.role===`user`).flatMap(e=>e.content).filter(e=>e.type!==`file`||e.mediaType!==`application/pdf`&&e.mediaType!==`text/plain`?!1:e.providerOptions?.anthropic?.citations?.enabled??!1).map(e=>{let t=e;return{title:t.filename??`Untitled Document`,filename:t.filename,mediaType:t.mediaType}})}async doGenerate(e){let{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),a=this.extractCitationDocuments(e.prompt),{responseHeaders:o,value:s,rawValue:c}=await he({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(t),failedResponseHandler:Me,successfulResponseHandler:Se(at),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=[];for(let e of s.content)switch(e.type){case`text`:if(!i&&(l.push({type:`text`,text:e.text}),e.citations))for(let t of e.citations)nt(t,a,this.generateId,e=>l.push(e));break;case`thinking`:l.push({type:`reasoning`,text:e.thinking,providerMetadata:{anthropic:{signature:e.signature}}});break;case`redacted_thinking`:l.push({type:`reasoning`,text:``,providerMetadata:{anthropic:{redactedData:e.data}}});break;case`tool_use`:l.push(i?{type:`text`,text:JSON.stringify(e.input)}:{type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input)});break;case`server_tool_use`:(e.name===`web_search`||e.name===`code_execution`||e.name===`web_fetch`)&&l.push({type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input),providerExecuted:!0});break;case`web_fetch_tool_result`:e.content.type===`web_fetch_result`?l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,result:{type:`web_fetch_result`,url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}},providerExecuted:!0}):e.content.type===`web_fetch_tool_result_error`&&l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,isError:!0,result:{type:`web_fetch_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break;case`web_search_tool_result`:if(Array.isArray(e.content)){l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type})),providerExecuted:!0});for(let t of e.content)l.push({type:`source`,sourceType:`url`,id:this.generateId(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break;case`code_execution_tool_result`:e.content.type===`code_execution_result`?l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break}return{content:l,finishReason:$e({finishReason:s.stop_reason,isJsonResponseFromTool:i}),usage:{inputTokens:s.usage.input_tokens,outputTokens:s.usage.output_tokens,totalTokens:s.usage.input_tokens+s.usage.output_tokens,cachedInputTokens:s.usage.cache_read_input_tokens??void 0},request:{body:t},response:{id:s.id??void 0,modelId:s.model??void 0,headers:o,body:c},warnings:n,providerMetadata:{anthropic:{usage:s.usage,cacheCreationInputTokens:s.usage.cache_creation_input_tokens??null,stopSequence:s.stop_sequence??null}}}}async doStream(e){let{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),a=this.extractCitationDocuments(e.prompt),o={...t,stream:!0},{responseHeaders:s,value:c}=await he({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(o),failedResponseHandler:Me,successfulResponseHandler:xe(ot),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=`unknown`,u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},d={},f,p=null,m=null,h,g=this.generateId;return{stream:c.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let r=t.value;switch(r.type){case`ping`:return;case`content_block_start`:{let e=r.content_block.type;switch(h=e,e){case`text`:d[r.index]={type:`text`},n.enqueue({type:`text-start`,id:String(r.index)});return;case`thinking`:d[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index)});return;case`redacted_thinking`:d[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index),providerMetadata:{anthropic:{redactedData:r.content_block.data}}});return;case`tool_use`:d[r.index]=i?{type:`text`}:{type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``},n.enqueue(i?{type:`text-start`,id:String(r.index)}:{type:`tool-input-start`,id:r.content_block.id,toolName:r.content_block.name});return;case`server_tool_use`:(r.content_block.name===`web_fetch`||r.content_block.name===`web_search`||r.content_block.name===`code_execution`)&&(d[r.index]={type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``,providerExecuted:!0},n.enqueue({type:`tool-input-start`,id:r.content_block.id,toolName:r.content_block.name,providerExecuted:!0}));return;case`web_fetch_tool_result`:{let e=r.content_block;e.content.type===`web_fetch_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,result:{type:`web_fetch_result`,url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}}}):e.content.type===`web_fetch_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,isError:!0,result:{type:`web_fetch_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}case`web_search_tool_result`:{let e=r.content_block;if(Array.isArray(e.content)){n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type})),providerExecuted:!0});for(let t of e.content)n.enqueue({type:`source`,sourceType:`url`,id:g(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}case`code_execution_tool_result`:{let e=r.content_block;e.content.type===`code_execution_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}default:{let t=e;throw Error(`Unsupported content block type: ${t}`)}}}case`content_block_stop`:if(d[r.index]!=null){let e=d[r.index];switch(e.type){case`text`:n.enqueue({type:`text-end`,id:String(r.index)});break;case`reasoning`:n.enqueue({type:`reasoning-end`,id:String(r.index)});break;case`tool-call`:i||(n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue(e));break}delete d[r.index]}h=void 0;return;case`content_block_delta`:{let e=r.delta.type;switch(e){case`text_delta`:if(i)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:r.delta.text});return;case`thinking_delta`:n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:r.delta.thinking});return;case`signature_delta`:h===`thinking`&&n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:``,providerMetadata:{anthropic:{signature:r.delta.signature}}});return;case`input_json_delta`:{let e=d[r.index],t=r.delta.partial_json;if(i){if(e?.type!==`text`)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:t})}else{if(e?.type!==`tool-call`)return;n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:t}),e.input+=t}return}case`citations_delta`:{let e=r.delta.citation;nt(e,a,g,e=>n.enqueue(e));return}default:{let t=e;throw Error(`Unsupported delta type: ${t}`)}}}case`message_start`:u.inputTokens=r.message.usage.input_tokens,u.cachedInputTokens=r.message.usage.cache_read_input_tokens??void 0,f={...r.message.usage},p=r.message.usage.cache_creation_input_tokens??null,n.enqueue({type:`response-metadata`,id:r.message.id??void 0,modelId:r.message.model??void 0});return;case`message_delta`:u.outputTokens=r.usage.output_tokens,u.totalTokens=(u.inputTokens??0)+(r.usage.output_tokens??0),l=$e({finishReason:r.delta.stop_reason,isJsonResponseFromTool:i}),m=r.delta.stop_sequence??null,f={...f,...r.usage};return;case`message_stop`:n.enqueue({type:`finish`,finishReason:l,usage:u,providerMetadata:{anthropic:{usage:f??null,cacheCreationInputTokens:p,stopSequence:m}}});return;case`error`:n.enqueue({type:`error`,error:r.error});return;default:{let e=r;throw Error(`Unsupported chunk type: ${e}`)}}}})),request:{body:o},response:{headers:s}}}},at=r.z.object({type:r.z.literal(`message`),id:r.z.string().nullish(),model:r.z.string().nullish(),content:r.z.array(r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`text`),text:r.z.string(),citations:r.z.array(tt).optional()}),r.z.object({type:r.z.literal(`thinking`),thinking:r.z.string(),signature:r.z.string()}),r.z.object({type:r.z.literal(`redacted_thinking`),data:r.z.string()}),r.z.object({type:r.z.literal(`tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.unknown()}),r.z.object({type:r.z.literal(`server_tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.record(r.z.string(),r.z.unknown()).nullish()}),r.z.object({type:r.z.literal(`web_fetch_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),retrieved_at:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string().nullable(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.object({type:r.z.literal(`text`),media_type:r.z.string(),data:r.z.string()})})}),r.z.object({type:r.z.literal(`web_fetch_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`web_search_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.array(r.z.object({type:r.z.literal(`web_search_result`),url:r.z.string(),title:r.z.string(),encrypted_content:r.z.string(),page_age:r.z.string().nullish()})),r.z.object({type:r.z.literal(`web_search_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`code_execution_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),r.z.object({type:r.z.literal(`code_execution_tool_result_error`),error_code:r.z.string()})])})])),stop_reason:r.z.string().nullish(),stop_sequence:r.z.string().nullish(),usage:r.z.looseObject({input_tokens:r.z.number(),output_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish(),cache_read_input_tokens:r.z.number().nullish()})}),ot=r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`message_start`),message:r.z.object({id:r.z.string().nullish(),model:r.z.string().nullish(),usage:r.z.looseObject({input_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish(),cache_read_input_tokens:r.z.number().nullish()})})}),r.z.object({type:r.z.literal(`content_block_start`),index:r.z.number(),content_block:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`text`),text:r.z.string()}),r.z.object({type:r.z.literal(`thinking`),thinking:r.z.string()}),r.z.object({type:r.z.literal(`tool_use`),id:r.z.string(),name:r.z.string()}),r.z.object({type:r.z.literal(`redacted_thinking`),data:r.z.string()}),r.z.object({type:r.z.literal(`server_tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.record(r.z.string(),r.z.unknown()).nullish()}),r.z.object({type:r.z.literal(`web_fetch_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),retrieved_at:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string().nullable(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.object({type:r.z.literal(`text`),media_type:r.z.string(),data:r.z.string()})})}),r.z.object({type:r.z.literal(`web_fetch_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`web_search_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.array(r.z.object({type:r.z.literal(`web_search_result`),url:r.z.string(),title:r.z.string(),encrypted_content:r.z.string(),page_age:r.z.string().nullish()})),r.z.object({type:r.z.literal(`web_search_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`code_execution_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),r.z.object({type:r.z.literal(`code_execution_tool_result_error`),error_code:r.z.string()})])})])}),r.z.object({type:r.z.literal(`content_block_delta`),index:r.z.number(),delta:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`input_json_delta`),partial_json:r.z.string()}),r.z.object({type:r.z.literal(`text_delta`),text:r.z.string()}),r.z.object({type:r.z.literal(`thinking_delta`),thinking:r.z.string()}),r.z.object({type:r.z.literal(`signature_delta`),signature:r.z.string()}),r.z.object({type:r.z.literal(`citations_delta`),citation:tt})])}),r.z.object({type:r.z.literal(`content_block_stop`),index:r.z.number()}),r.z.object({type:r.z.literal(`error`),error:r.z.object({type:r.z.string(),message:r.z.string()})}),r.z.object({type:r.z.literal(`message_delta`),delta:r.z.object({stop_reason:r.z.string().nullish(),stop_sequence:r.z.string().nullish()}),usage:r.z.looseObject({output_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish()})}),r.z.object({type:r.z.literal(`message_stop`)}),r.z.object({type:r.z.literal(`ping`)})]),st=r.z.object({signature:r.z.string().optional(),redactedData:r.z.string().optional()}),ct=ve({id:`anthropic.bash_20241022`,name:`bash`,inputSchema:r.default.object({command:r.default.string(),restart:r.default.boolean().optional()})}),lt=ve({id:`anthropic.bash_20250124`,name:`bash`,inputSchema:r.default.object({command:r.default.string(),restart:r.default.boolean().optional()})}),ut=ve({id:`anthropic.computer_20241022`,name:`computer`,inputSchema:r.z.object({action:r.z.enum([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:r.z.array(r.z.number().int()).optional(),text:r.z.string().optional()})}),dt=ve({id:`anthropic.computer_20250124`,name:`computer`,inputSchema:r.z.object({action:r.z.enum([`key`,`hold_key`,`type`,`cursor_position`,`mouse_move`,`left_mouse_down`,`left_mouse_up`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`triple_click`,`scroll`,`wait`,`screenshot`]),coordinate:r.z.tuple([r.z.number().int(),r.z.number().int()]).optional(),duration:r.z.number().optional(),scroll_amount:r.z.number().optional(),scroll_direction:r.z.enum([`up`,`down`,`left`,`right`]).optional(),start_coordinate:r.z.tuple([r.z.number().int(),r.z.number().int()]).optional(),text:r.z.string().optional()})}),ft=ve({id:`anthropic.text_editor_20241022`,name:`str_replace_editor`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),pt=ve({id:`anthropic.text_editor_20250124`,name:`str_replace_editor`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),mt=ve({id:`anthropic.text_editor_20250429`,name:`str_replace_based_edit_tool`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),ht={bash_20241022:ct,bash_20250124:lt,codeExecution_20250522:Ye,computer_20241022:ut,computer_20250124:dt,textEditor_20241022:ft,textEditor_20250124:pt,textEditor_20250429:mt,textEditor_20250728:Le,webFetch_20250910:Ge,webSearch_20250305:Ve};function gt(e={}){let n=ke(e.baseURL)??`https://api.anthropic.com/v1`,r=()=>M({"anthropic-version":`2023-06-01`,"x-api-key":ne({apiKey:e.apiKey,environmentVariableName:`ANTHROPIC_API_KEY`,description:`Anthropic`}),...e.headers},`ai-sdk/anthropic/${Ae}`),i=t=>new it(t,{provider:`anthropic.messages`,baseURL:n,headers:r,fetch:e.fetch,generateId:e.generateId??P,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})}),a=function(e){if(new.target)throw Error(`The Anthropic model function cannot be called with the new keyword.`);return i(e)};return a.languageModel=i,a.chat=i,a.messages=i,a.textEmbeddingModel=e=>{throw new t.NoSuchModelError({modelId:e,modelType:`textEmbeddingModel`})},a.imageModel=e=>{throw new t.NoSuchModelError({modelId:e,modelType:`imageModel`})},a.tools=ht,a}var _t=gt();function vt(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function yt(e){return Object.fromEntries([...e.headers])}function bt(e=globalThis){return e.window?`runtime/browser`:e.navigator?.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:e.process?.versions?.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?`runtime/vercel-edge`:`runtime/unknown`}function xt(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function St(e,...t){let n=xt(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var Ct=({prefix:e,size:n=16,alphabet:r=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:i=`-`}={})=>{let a=()=>{let e=r.length,t=Array(n);for(let i=0;i<n;i++)t[i]=r[Math.random()*e|0];return t.join(``)};if(e==null)return a;if(r.includes(i))throw new t.InvalidArgumentError({argument:`separator`,message:`The separator "${i}" must not be part of the alphabet "${r}".`});return()=>`${e}${i}${a()}`},wt=Ct();function Tt(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Et=[`fetch failed`,`failed to fetch`];function Dt({error:e,url:n,requestBodyValues:r}){if(Tt(e))return e;if(e instanceof TypeError&&Et.includes(e.message.toLowerCase())){let i=e.cause;if(i!=null)return new t.APICallError({message:`Cannot connect to API: ${i.message}`,cause:i,url:n,requestBodyValues:r,isRetryable:!0})}return e}var Ot=`3.0.10`;function kt({apiKey:e,environmentVariableName:n,apiKeyParameterName:r=`apiKey`,description:i}){if(typeof e==`string`)return e;if(e!=null)throw new t.LoadAPIKeyError({message:`${i} API key must be a string.`});if(typeof process>`u`)throw new t.LoadAPIKeyError({message:`${i} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[n],e==null)throw new t.LoadAPIKeyError({message:`${i} API key is missing. Pass it using the '${r}' parameter or the ${n} environment variable.`});if(typeof e!=`string`)throw new t.LoadAPIKeyError({message:`${i} API key must be a string. The value of the ${n} environment variable is not a string.`});return e}var At=/"__proto__"\s*:/,jt=/"constructor"\s*:/;function Mt(e){let t=JSON.parse(e);return typeof t!=`object`||!t||At.test(e)===!1&&jt.test(e)===!1?t:Nt(t)}function Nt(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function Pt(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Mt(e)}finally{Error.stackTraceLimit=t}}var Ft=Symbol.for(`vercel.ai.validator`);function It(e){return{[Ft]:!0,validate:e}}function Lt(e){return typeof e==`object`&&!!e&&Ft in e&&e[Ft]===!0&&`validate`in e}function Rt(e){return Lt(e)?e:zt(e)}function zt(e){return It(async n=>{let r=await e[`~standard`].validate(n);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new t.TypeValidationError({value:n,cause:r.issues})}})}async function Bt({value:e,schema:n}){let r=await Vt({value:e,schema:n});if(!r.success)throw t.TypeValidationError.wrap({value:e,cause:r.error});return r.value}async function Vt({value:e,schema:n}){let r=Rt(n);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};let n=await r.validate(e);return n.success?{success:!0,value:n.value,rawValue:e}:{success:!1,error:t.TypeValidationError.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:t.TypeValidationError.wrap({value:e,cause:n}),rawValue:e}}}async function Ht({text:e,schema:n}){try{let t=Pt(e);return n==null?t:Bt({value:t,schema:n})}catch(n){throw t.JSONParseError.isInstance(n)||t.TypeValidationError.isInstance(n)?n:new t.JSONParseError({text:e,cause:n})}}async function Ut({text:e,schema:n}){try{let t=Pt(e);return n==null?{success:!0,value:t,rawValue:t}:await Vt({value:t,schema:n})}catch(n){return{success:!1,error:t.JSONParseError.isInstance(n)?n:new t.JSONParseError({text:e,cause:n}),rawValue:void 0}}}function Wt({stream:e,schema:n}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new t.EventSourceParserStream).pipeThrough(new TransformStream({async transform({data:e},t){e!==`[DONE]`&&t.enqueue(await Ut({text:e,schema:n}))}}))}async function Gt({provider:e,providerOptions:n,schema:r}){if(n?.[e]==null)return;let i=await Vt({value:n[e],schema:r});if(!i.success)throw new t.InvalidArgumentError({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:i.error});return i.value}var Kt=()=>globalThis.fetch,qt=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>Jt({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),Jt=async({url:e,headers:n={},body:r,successfulResponseHandler:i,failedResponseHandler:a,abortSignal:o,fetch:s=Kt()})=>{try{let c=await s(e,{method:`POST`,headers:St(n,`ai-sdk/provider-utils/${Ot}`,bt()),body:r.content,signal:o}),l=yt(c);if(!c.ok){let n;try{n=await a({response:c,url:e,requestBodyValues:r.values})}catch(n){throw Tt(n)||t.APICallError.isInstance(n)?n:new t.APICallError({message:`Failed to process error response`,cause:n,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw n.value}try{return await i({response:c,url:e,requestBodyValues:r.values})}catch(n){throw n instanceof Error&&(Tt(n)||t.APICallError.isInstance(n))?n:new t.APICallError({message:`Failed to process successful response`,cause:n,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(t){throw Dt({error:t,url:e,requestBodyValues:r.values})}};function Yt(e){return e}function Xt({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>Yt({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function Zt({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>Yt({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:r,execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}async function Qt(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var $t=({errorSchema:e,errorToMessage:n,isRetryable:r})=>async({response:i,url:a,requestBodyValues:o})=>{let s=await i.text(),c=yt(i);if(s.trim()===``)return{responseHeaders:c,value:new t.APICallError({message:i.statusText,url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,isRetryable:r?.(i)})};try{let l=await Ht({text:s,schema:e});return{responseHeaders:c,value:new t.APICallError({message:n(l),url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,data:l,isRetryable:r?.(i,l)})}}catch{return{responseHeaders:c,value:new t.APICallError({message:i.statusText,url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,isRetryable:r?.(i)})}}},en=e=>async({response:n})=>{let r=yt(n);if(n.body==null)throw new t.EmptyResponseBodyError({});return{responseHeaders:r,value:Wt({stream:n.body,schema:e})}},tn=e=>async({response:n,url:r,requestBodyValues:i})=>{let a=await n.text(),o=await Ut({text:a,schema:e}),s=yt(n);if(!o.success)throw new t.APICallError({message:`Invalid JSON response`,cause:o.error,statusCode:n.status,responseHeaders:s,responseBody:a,url:r,requestBodyValues:i});return{responseHeaders:s,value:o.value,rawValue:o.rawValue}},nn=Symbol(`Let zodToJsonSchema decide on which parser to use`),rn=Symbol.for(`vercel.ai.schema`),{btoa:an,atob:on}=globalThis;function sn(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return an(t)}function cn(e){return e instanceof Uint8Array?sn(e):e}function ln(e){return e?.replace(/\/$/,``)}var un=`2.0.17`,dn=r.z.object({error:r.z.object({code:r.z.number().nullable(),message:r.z.string(),status:r.z.string()})}),fn=$t({errorSchema:dn,errorToMessage:e=>e.error.message}),pn=r.z.object({outputDimensionality:r.z.number().optional(),taskType:r.z.enum([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional()}),mn=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:n,abortSignal:r,providerOptions:i}){let a=await Gt({provider:`google`,providerOptions:i,schema:pn});if(e.length>this.maxEmbeddingsPerCall)throw new t.TooManyEmbeddingValuesForCallError({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let o=vt(await Qt(this.config.headers),n);if(e.length===1){let{responseHeaders:t,value:n,rawValue:i}=await qt({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:o,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType},failedResponseHandler:fn,successfulResponseHandler:tn(gn),abortSignal:r,fetch:this.config.fetch});return{embeddings:[n.embedding.values],usage:void 0,response:{headers:t,body:i}}}let{responseHeaders:s,value:c,rawValue:l}=await qt({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:o,body:{requests:e.map(e=>({model:`models/${this.modelId}`,content:{role:`user`,parts:[{text:e}]},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType}))},failedResponseHandler:fn,successfulResponseHandler:tn(hn),abortSignal:r,fetch:this.config.fetch});return{embeddings:c.embeddings.map(e=>e.values),usage:void 0,response:{headers:s,body:l}}}},hn=r.z.object({embeddings:r.z.array(r.z.object({values:r.z.array(r.z.number())}))}),gn=r.z.object({embedding:r.z.object({values:r.z.array(r.z.number())})});function _n(e){if(e==null||vn(e))return;if(typeof e==`boolean`)return{type:`boolean`,properties:{}};let{type:t,description:n,required:r,properties:i,items:a,allOf:o,anyOf:s,oneOf:c,format:l,const:u,minLength:d,enum:f}=e,p={};if(n&&(p.description=n),r&&(p.required=r),l&&(p.format=l),u!==void 0&&(p.enum=[u]),t&&(Array.isArray(t)?t.includes(`null`)?(p.type=t.filter(e=>e!==`null`)[0],p.nullable=!0):p.type=t:t===`null`?p.type=`null`:p.type=t),f!==void 0&&(p.enum=f),i!=null&&(p.properties=Object.entries(i).reduce((e,[t,n])=>(e[t]=_n(n),e),{})),a&&(p.items=Array.isArray(a)?a.map(_n):_n(a)),o&&(p.allOf=o.map(_n)),s)if(s.some(e=>typeof e==`object`&&e?.type===`null`)){let e=s.filter(e=>!(typeof e==`object`&&e?.type===`null`));if(e.length===1){let t=_n(e[0]);typeof t==`object`&&(p.nullable=!0,Object.assign(p,t))}else p.anyOf=e.map(_n),p.nullable=!0}else p.anyOf=s.map(_n);return c&&(p.oneOf=c.map(_n)),d!==void 0&&(p.minLength=d),p}function vn(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}function yn(e,n){let r=[],i=[],a=!0,o=n?.isGemmaModel??!1;for(let{role:n,content:o}of e)switch(n){case`system`:if(!a)throw new t.UnsupportedFunctionalityError({functionality:`system messages are only supported at the beginning of the conversation`});r.push({text:o});break;case`user`:{a=!1;let e=[];for(let t of o)switch(t.type){case`text`:e.push({text:t.text});break;case`file`:{let n=t.mediaType===`image/*`?`image/jpeg`:t.mediaType;e.push(t.data instanceof URL?{fileData:{mimeType:n,fileUri:t.data.toString()}}:{inlineData:{mimeType:n,data:cn(t.data)}});break}}i.push({role:`user`,parts:e});break}case`assistant`:a=!1,i.push({role:`model`,parts:o.map(e=>{switch(e.type){case`text`:return e.text.length===0?void 0:{text:e.text,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`reasoning`:return e.text.length===0?void 0:{text:e.text,thought:!0,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`file`:if(e.mediaType!==`image/png`)throw new t.UnsupportedFunctionalityError({functionality:`Only PNG images are supported in assistant messages`});if(e.data instanceof URL)throw new t.UnsupportedFunctionalityError({functionality:`File data URLs in assistant messages are not supported`});return{inlineData:{mimeType:e.mediaType,data:cn(e.data)}};case`tool-call`:return{functionCall:{name:e.toolName,args:e.input},thoughtSignature:e.providerOptions?.google?.thoughtSignature}}}).filter(e=>e!==void 0)});break;case`tool`:{a=!1;let e=[];for(let t of o){let n=t.output;if(n.type===`content`)for(let r of n.value)switch(r.type){case`text`:e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:r.text}}});break;case`media`:e.push({inlineData:{mimeType:r.mediaType,data:r.data}},{text:`Tool executed successfully and returned this image as a response`});break;default:e.push({text:JSON.stringify(r)});break}else e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:n.value}}})}i.push({role:`user`,parts:e});break}}if(o&&r.length>0&&i.length>0&&i[0].role===`user`){let e=r.map(e=>e.text).join(`
1
+ const e=require(`../chunk-iXuH7AlR.cjs`),t=require(`../index.node-CFR7FTuY.cjs`);require(`../token-error-BoNG8ooW.cjs`),require(`../esm-0UNjvroT.cjs`);const n=require(`../build-EgdtUZTI.cjs`);let r=require(`zod/v4`);r=e.__toESM(r);let i=require(`zod/v3`);i=e.__toESM(i);let a=require(`node:buffer`);a=e.__toESM(a);let o=require(`node:fs`);o=e.__toESM(o);let s=require(`node:url`);s=e.__toESM(s);let c=require(`node:stream`);c=e.__toESM(c);let l=require(`node:util`);l=e.__toESM(l);let u=require(`node:crypto`);u=e.__toESM(u);let d=require(`http`);d=e.__toESM(d);let f=require(`path`);f=e.__toESM(f);let p=require(`fs`);p=e.__toESM(p);let m=require(`ai`);m=e.__toESM(m);let h=require(`fs/promises`);h=e.__toESM(h);let g=require(`child_process`);g=e.__toESM(g);let _=require(`react`);_=e.__toESM(_);let v=require(`node:module`);v=e.__toESM(v);let y=require(`zod`);y=e.__toESM(y);let b=require(`node:path`);b=e.__toESM(b);let x=require(`node:process`);x=e.__toESM(x);let S=require(`node:os`);S=e.__toESM(S);let C=require(`node:tty`);C=e.__toESM(C);let w=require(`node:readline`);w=e.__toESM(w);let T=require(`node:child_process`);T=e.__toESM(T);let E=require(`node:fs/promises`);E=e.__toESM(E),require(`@blink-sdk/compute-protocol/client`);let D=require(`@blink-sdk/compute-protocol/transport`);D=e.__toESM(D);function O(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function k(e){return Object.fromEntries([...e.headers])}function A(e=globalThis){return e.window?`runtime/browser`:e.navigator?.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:e.process?.versions?.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?`runtime/vercel-edge`:`runtime/unknown`}function j(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function M(e,...t){let n=j(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var N=({prefix:e,size:n=16,alphabet:r=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:i=`-`}={})=>{let a=()=>{let e=r.length,t=Array(n);for(let i=0;i<n;i++)t[i]=r[Math.random()*e|0];return t.join(``)};if(e==null)return a;if(r.includes(i))throw new t.InvalidArgumentError({argument:`separator`,message:`The separator "${i}" must not be part of the alphabet "${r}".`});return()=>`${e}${i}${a()}`},P=N();function F(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var ee=[`fetch failed`,`failed to fetch`];function te({error:e,url:n,requestBodyValues:r}){if(F(e))return e;if(e instanceof TypeError&&ee.includes(e.message.toLowerCase())){let i=e.cause;if(i!=null)return new t.APICallError({message:`Cannot connect to API: ${i.message}`,cause:i,url:n,requestBodyValues:r,isRetryable:!0})}return e}var I=`3.0.10`;function ne({apiKey:e,environmentVariableName:n,apiKeyParameterName:r=`apiKey`,description:i}){if(typeof e==`string`)return e;if(e!=null)throw new t.LoadAPIKeyError({message:`${i} API key must be a string.`});if(typeof process>`u`)throw new t.LoadAPIKeyError({message:`${i} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[n],e==null)throw new t.LoadAPIKeyError({message:`${i} API key is missing. Pass it using the '${r}' parameter or the ${n} environment variable.`});if(typeof e!=`string`)throw new t.LoadAPIKeyError({message:`${i} API key must be a string. The value of the ${n} environment variable is not a string.`});return e}var L=/"__proto__"\s*:/,re=/"constructor"\s*:/;function R(e){let t=JSON.parse(e);return typeof t!=`object`||!t||L.test(e)===!1&&re.test(e)===!1?t:z(t)}function z(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function B(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return R(e)}finally{Error.stackTraceLimit=t}}var ie=Symbol.for(`vercel.ai.validator`);function ae(e){return{[ie]:!0,validate:e}}function oe(e){return typeof e==`object`&&!!e&&ie in e&&e[ie]===!0&&`validate`in e}function se(e){return oe(e)?e:ce(e)}function ce(e){return ae(async n=>{let r=await e[`~standard`].validate(n);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new t.TypeValidationError({value:n,cause:r.issues})}})}async function V({value:e,schema:n}){let r=await le({value:e,schema:n});if(!r.success)throw t.TypeValidationError.wrap({value:e,cause:r.error});return r.value}async function le({value:e,schema:n}){let r=se(n);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};let n=await r.validate(e);return n.success?{success:!0,value:n.value,rawValue:e}:{success:!1,error:t.TypeValidationError.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:t.TypeValidationError.wrap({value:e,cause:n}),rawValue:e}}}async function ue({text:e,schema:n}){try{let t=B(e);return n==null?t:V({value:t,schema:n})}catch(n){throw t.JSONParseError.isInstance(n)||t.TypeValidationError.isInstance(n)?n:new t.JSONParseError({text:e,cause:n})}}async function de({text:e,schema:n}){try{let t=B(e);return n==null?{success:!0,value:t,rawValue:t}:await le({value:t,schema:n})}catch(n){return{success:!1,error:t.JSONParseError.isInstance(n)?n:new t.JSONParseError({text:e,cause:n}),rawValue:void 0}}}function fe({stream:e,schema:n}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new t.EventSourceParserStream).pipeThrough(new TransformStream({async transform({data:e},t){e!==`[DONE]`&&t.enqueue(await de({text:e,schema:n}))}}))}async function pe({provider:e,providerOptions:n,schema:r}){if(n?.[e]==null)return;let i=await le({value:n[e],schema:r});if(!i.success)throw new t.InvalidArgumentError({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:i.error});return i.value}var me=()=>globalThis.fetch,he=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>ge({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),ge=async({url:e,headers:n={},body:r,successfulResponseHandler:i,failedResponseHandler:a,abortSignal:o,fetch:s=me()})=>{try{let c=await s(e,{method:`POST`,headers:M(n,`ai-sdk/provider-utils/${I}`,A()),body:r.content,signal:o}),l=k(c);if(!c.ok){let n;try{n=await a({response:c,url:e,requestBodyValues:r.values})}catch(n){throw F(n)||t.APICallError.isInstance(n)?n:new t.APICallError({message:`Failed to process error response`,cause:n,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw n.value}try{return await i({response:c,url:e,requestBodyValues:r.values})}catch(n){throw n instanceof Error&&(F(n)||t.APICallError.isInstance(n))?n:new t.APICallError({message:`Failed to process successful response`,cause:n,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(t){throw te({error:t,url:e,requestBodyValues:r.values})}};function _e(e){return e}function ve({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>_e({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function ye({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>_e({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:r,execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}async function be(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var H=({errorSchema:e,errorToMessage:n,isRetryable:r})=>async({response:i,url:a,requestBodyValues:o})=>{let s=await i.text(),c=k(i);if(s.trim()===``)return{responseHeaders:c,value:new t.APICallError({message:i.statusText,url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,isRetryable:r?.(i)})};try{let l=await ue({text:s,schema:e});return{responseHeaders:c,value:new t.APICallError({message:n(l),url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,data:l,isRetryable:r?.(i,l)})}}catch{return{responseHeaders:c,value:new t.APICallError({message:i.statusText,url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,isRetryable:r?.(i)})}}},xe=e=>async({response:n})=>{let r=k(n);if(n.body==null)throw new t.EmptyResponseBodyError({});return{responseHeaders:r,value:fe({stream:n.body,schema:e})}},Se=e=>async({response:n,url:r,requestBodyValues:i})=>{let a=await n.text(),o=await de({text:a,schema:e}),s=k(n);if(!o.success)throw new t.APICallError({message:`Invalid JSON response`,cause:o.error,statusCode:n.status,responseHeaders:s,responseBody:a,url:r,requestBodyValues:i});return{responseHeaders:s,value:o.value,rawValue:o.rawValue}},Ce=Symbol(`Let zodToJsonSchema decide on which parser to use`),we=Symbol.for(`vercel.ai.schema`),{btoa:Te,atob:Ee}=globalThis;function De(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return Te(t)}function Oe(e){return e instanceof Uint8Array?De(e):e}function ke(e){return e?.replace(/\/$/,``)}var Ae=`2.0.23`,je=r.z.object({type:r.z.literal(`error`),error:r.z.object({type:r.z.string(),message:r.z.string()})}),Me=H({errorSchema:je,errorToMessage:e=>e.error.message}),U=r.z.object({citations:r.z.object({enabled:r.z.boolean()}).optional(),title:r.z.string().optional(),context:r.z.string().optional()}),Ne=r.z.object({sendReasoning:r.z.boolean().optional(),thinking:r.z.object({type:r.z.union([r.z.literal(`enabled`),r.z.literal(`disabled`)]),budgetTokens:r.z.number().optional()}).optional(),disableParallelToolUse:r.z.boolean().optional(),cacheControl:r.z.object({type:r.z.literal(`ephemeral`),ttl:r.z.union([r.z.literal(`5m`),r.z.literal(`1h`)]).optional()}).optional()});function Pe(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var Fe=r.z.object({maxCharacters:r.z.number().optional()}),Ie=ve({id:`anthropic.text_editor_20250728`,name:`str_replace_based_edit_tool`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),Le=(e={})=>Ie(e),Re=r.z.object({maxUses:r.z.number().optional(),allowedDomains:r.z.array(r.z.string()).optional(),blockedDomains:r.z.array(r.z.string()).optional(),userLocation:r.z.object({type:r.z.literal(`approximate`),city:r.z.string().optional(),region:r.z.string().optional(),country:r.z.string().optional(),timezone:r.z.string().optional()}).optional()}),ze=r.z.array(r.z.object({url:r.z.string(),title:r.z.string(),pageAge:r.z.string().nullable(),encryptedContent:r.z.string(),type:r.z.literal(`web_search_result`)})),Be=ye({id:`anthropic.web_search_20250305`,name:`web_search`,inputSchema:r.z.object({query:r.z.string()}),outputSchema:ze}),Ve=(e={})=>Be(e),He=r.z.object({maxUses:r.z.number().optional(),allowedDomains:r.z.array(r.z.string()).optional(),blockedDomains:r.z.array(r.z.string()).optional(),citations:r.z.object({enabled:r.z.boolean()}).optional(),maxContentTokens:r.z.number().optional()}),Ue=r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.union([r.z.object({type:r.z.literal(`base64`),mediaType:r.z.literal(`application/pdf`),data:r.z.string()}),r.z.object({type:r.z.literal(`text`),mediaType:r.z.literal(`text/plain`),data:r.z.string()})])}),retrievedAt:r.z.string().nullable()}),We=ye({id:`anthropic.web_fetch_20250910`,name:`web_fetch`,inputSchema:r.z.object({url:r.z.string()}),outputSchema:Ue}),Ge=(e={})=>We(e);function Ke({tools:e,toolChoice:n,disableParallelToolUse:r}){e=e?.length?e:void 0;let i=[],a=new Set;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:a};let o=[];for(let t of e)switch(t.type){case`function`:{let e=Pe(t.providerOptions);o.push({name:t.name,description:t.description,input_schema:t.inputSchema,cache_control:e});break}case`provider-defined`:switch(t.id){case`anthropic.code_execution_20250522`:a.add(`code-execution-2025-05-22`),o.push({type:`code_execution_20250522`,name:`code_execution`});break;case`anthropic.computer_20250124`:a.add(`computer-use-2025-01-24`),o.push({name:`computer`,type:`computer_20250124`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.computer_20241022`:a.add(`computer-use-2024-10-22`),o.push({name:`computer`,type:`computer_20241022`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.text_editor_20250124`:a.add(`computer-use-2025-01-24`),o.push({name:`str_replace_editor`,type:`text_editor_20250124`});break;case`anthropic.text_editor_20241022`:a.add(`computer-use-2024-10-22`),o.push({name:`str_replace_editor`,type:`text_editor_20241022`});break;case`anthropic.text_editor_20250429`:a.add(`computer-use-2025-01-24`),o.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`});break;case`anthropic.text_editor_20250728`:{let e=Fe.parse(t.args);o.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250728`,max_characters:e.maxCharacters});break}case`anthropic.bash_20250124`:a.add(`computer-use-2025-01-24`),o.push({name:`bash`,type:`bash_20250124`});break;case`anthropic.bash_20241022`:a.add(`computer-use-2024-10-22`),o.push({name:`bash`,type:`bash_20241022`});break;case`anthropic.web_fetch_20250910`:{a.add(`web-fetch-2025-09-10`);let e=He.parse(t.args);o.push({type:`web_fetch_20250910`,name:`web_fetch`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens});break}case`anthropic.web_search_20250305`:{let e=Re.parse(t.args);o.push({type:`web_search_20250305`,name:`web_search`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation});break}default:i.push({type:`unsupported-tool`,tool:t});break}break;default:i.push({type:`unsupported-tool`,tool:t});break}if(n==null)return{tools:o,toolChoice:r?{type:`auto`,disable_parallel_tool_use:r}:void 0,toolWarnings:i,betas:a};let s=n.type;switch(s){case`auto`:return{tools:o,toolChoice:{type:`auto`,disable_parallel_tool_use:r},toolWarnings:i,betas:a};case`required`:return{tools:o,toolChoice:{type:`any`,disable_parallel_tool_use:r},toolWarnings:i,betas:a};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:a};case`tool`:return{tools:o,toolChoice:{type:`tool`,name:n.toolName,disable_parallel_tool_use:r},toolWarnings:i,betas:a};default:throw new t.UnsupportedFunctionalityError({functionality:`tool choice type: ${s}`})}}var qe=r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),Je=ye({id:`anthropic.code_execution_20250522`,name:`code_execution`,inputSchema:r.z.object({code:r.z.string()}),outputSchema:qe}),Ye=(e={})=>Je(e);function Xe(e){if(typeof e==`string`)return Buffer.from(e,`base64`).toString(`utf-8`);if(e instanceof Uint8Array)return new TextDecoder().decode(e);throw e instanceof URL?new t.UnsupportedFunctionalityError({functionality:`URL-based text documents are not supported for citations`}):new t.UnsupportedFunctionalityError({functionality:`unsupported data type for text documents: ${typeof e}`})}async function Ze({prompt:e,sendReasoning:n,warnings:r}){let i=new Set,a=Qe(e),o,s=[];async function c(e){return(await pe({provider:`anthropic`,providerOptions:e,schema:U}))?.citations?.enabled??!1}async function l(e){let t=await pe({provider:`anthropic`,providerOptions:e,schema:U});return{title:t?.title,context:t?.context}}for(let e=0;e<a.length;e++){let u=a[e],d=e===a.length-1,f=u.type;switch(f){case`system`:if(o!=null)throw new t.UnsupportedFunctionalityError({functionality:`Multiple system messages that are separated by user/assistant messages`});o=u.messages.map(({content:e,providerOptions:t})=>({type:`text`,text:e,cache_control:Pe(t)}));break;case`user`:{let e=[];for(let n of u.messages){let{role:r,content:a}=n;switch(r){case`user`:for(let r=0;r<a.length;r++){let o=a[r],s=r===a.length-1,u=Pe(o.providerOptions)??(s?Pe(n.providerOptions):void 0);switch(o.type){case`text`:e.push({type:`text`,text:o.text,cache_control:u});break;case`file`:if(o.mediaType.startsWith(`image/`))e.push({type:`image`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`base64`,media_type:o.mediaType===`image/*`?`image/jpeg`:o.mediaType,data:Oe(o.data)},cache_control:u});else if(o.mediaType===`application/pdf`){i.add(`pdfs-2024-09-25`);let t=await c(o.providerOptions),n=await l(o.providerOptions);e.push({type:`document`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`base64`,media_type:`application/pdf`,data:Oe(o.data)},title:n.title??o.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:u})}else if(o.mediaType===`text/plain`){let t=await c(o.providerOptions),n=await l(o.providerOptions);e.push({type:`document`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`text`,media_type:`text/plain`,data:Xe(o.data)},title:n.title??o.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:u})}else throw new t.UnsupportedFunctionalityError({functionality:`media type: ${o.mediaType}`});break}}break;case`tool`:for(let r=0;r<a.length;r++){let i=a[r],o=r===a.length-1,s=Pe(i.providerOptions)??(o?Pe(n.providerOptions):void 0),c=i.output,l;switch(c.type){case`content`:l=c.value.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text,cache_control:void 0};case`media`:if(e.mediaType.startsWith(`image/`))return{type:`image`,source:{type:`base64`,media_type:e.mediaType,data:e.data},cache_control:void 0};throw new t.UnsupportedFunctionalityError({functionality:`media type: ${e.mediaType}`})}});break;case`text`:case`error-text`:l=c.value;break;case`json`:case`error-json`:default:l=JSON.stringify(c.value);break}e.push({type:`tool_result`,tool_use_id:i.toolCallId,content:l,is_error:c.type===`error-text`||c.type===`error-json`?!0:void 0,cache_control:s})}break;default:{let e=r;throw Error(`Unsupported role: ${e}`)}}}s.push({role:`user`,content:e});break}case`assistant`:{let e=[];for(let t=0;t<u.messages.length;t++){let i=u.messages[t],a=t===u.messages.length-1,{content:o}=i;for(let t=0;t<o.length;t++){let s=o[t],c=t===o.length-1,l=Pe(s.providerOptions)??(c?Pe(i.providerOptions):void 0);switch(s.type){case`text`:e.push({type:`text`,text:d&&a&&c?s.text.trim():s.text,cache_control:l});break;case`reasoning`:if(n){let t=await pe({provider:`anthropic`,providerOptions:s.providerOptions,schema:st});t==null?r.push({type:`other`,message:`unsupported reasoning metadata`}):t.signature==null?t.redactedData==null?r.push({type:`other`,message:`unsupported reasoning metadata`}):e.push({type:`redacted_thinking`,data:t.redactedData,cache_control:l}):e.push({type:`thinking`,thinking:s.text,signature:t.signature,cache_control:l})}else r.push({type:`other`,message:`sending reasoning content is disabled for this model`});break;case`tool-call`:if(s.providerExecuted){s.toolName===`code_execution`||s.toolName===`web_fetch`||s.toolName===`web_search`?e.push({type:`server_tool_use`,id:s.toolCallId,name:s.toolName,input:s.input,cache_control:l}):r.push({type:`other`,message:`provider executed tool call for tool ${s.toolName} is not supported`});break}e.push({type:`tool_use`,id:s.toolCallId,name:s.toolName,input:s.input,cache_control:l});break;case`tool-result`:if(s.toolName===`code_execution`){let t=s.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let n=qe.parse(t.value);e.push({type:`code_execution_tool_result`,tool_use_id:s.toolCallId,content:{type:n.type,stdout:n.stdout,stderr:n.stderr,return_code:n.return_code},cache_control:l});break}if(s.toolName===`web_fetch`){let t=s.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let n=Ue.parse(t.value);e.push({type:`web_fetch_tool_result`,tool_use_id:s.toolCallId,content:{type:`web_fetch_result`,url:n.url,retrieved_at:n.retrievedAt,content:{type:`document`,title:n.content.title,citations:n.content.citations,source:{type:n.content.source.type,media_type:n.content.source.mediaType,data:n.content.source.data}}},cache_control:l});break}if(s.toolName===`web_search`){let t=s.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let n=ze.parse(t.value);e.push({type:`web_search_tool_result`,tool_use_id:s.toolCallId,content:n.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:l});break}r.push({type:`other`,message:`provider executed tool result for tool ${s.toolName} is not supported`});break}}}s.push({role:`assistant`,content:e});break}default:{let e=f;throw Error(`content type: ${e}`)}}}return{prompt:{system:o,messages:s},betas:i}}function Qe(e){let t=[],n;for(let r of e){let{role:e}=r;switch(e){case`system`:n?.type!==`system`&&(n={type:`system`,messages:[]},t.push(n)),n.messages.push(r);break;case`assistant`:n?.type!==`assistant`&&(n={type:`assistant`,messages:[]},t.push(n)),n.messages.push(r);break;case`user`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;case`tool`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;default:{let t=e;throw Error(`Unsupported role: ${t}`)}}}return t}function $e({finishReason:e,isJsonResponseFromTool:t}){switch(e){case`pause_turn`:case`end_turn`:case`stop_sequence`:return`stop`;case`refusal`:return`content-filter`;case`tool_use`:return t?`stop`:`tool-calls`;case`max_tokens`:return`length`;default:return`unknown`}}var et={webSearchResult:r.z.object({type:r.z.literal(`web_search_result_location`),cited_text:r.z.string(),url:r.z.string(),title:r.z.string(),encrypted_index:r.z.string()}),pageLocation:r.z.object({type:r.z.literal(`page_location`),cited_text:r.z.string(),document_index:r.z.number(),document_title:r.z.string().nullable(),start_page_number:r.z.number(),end_page_number:r.z.number()}),charLocation:r.z.object({type:r.z.literal(`char_location`),cited_text:r.z.string(),document_index:r.z.number(),document_title:r.z.string().nullable(),start_char_index:r.z.number(),end_char_index:r.z.number()})},tt=r.z.discriminatedUnion(`type`,[et.webSearchResult,et.pageLocation,et.charLocation]);r.z.discriminatedUnion(`type`,[et.pageLocation,et.charLocation]);function nt(e,t,n,r){if(e.type===`page_location`||e.type===`char_location`){let i=rt(e,t,n);i&&r(i)}}function rt(e,t,n){let r=t[e.document_index];if(!r)return null;let i=e.type===`page_location`?{citedText:e.cited_text,startPageNumber:e.start_page_number,endPageNumber:e.end_page_number}:{citedText:e.cited_text,startCharIndex:e.start_char_index,endCharIndex:e.end_char_index};return{type:`source`,sourceType:`document`,id:n(),mediaType:r.mediaType,title:e.document_title??r.title,filename:r.filename,providerMetadata:{anthropic:i}}}var it=class{constructor(e,t){this.specificationVersion=`v2`,this.modelId=e,this.config=t,this.generateId=t.generateId??P}supportsUrl(e){return e.protocol===`https:`}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:n=4096,temperature:r,topP:i,topK:a,frequencyPenalty:o,presencePenalty:s,stopSequences:c,responseFormat:l,seed:u,tools:d,toolChoice:f,providerOptions:p}){let m=[];o!=null&&m.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),s!=null&&m.push({type:`unsupported-setting`,setting:`presencePenalty`}),u!=null&&m.push({type:`unsupported-setting`,setting:`seed`}),l?.type===`json`&&(l.schema==null?m.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format requires a schema. The response format is ignored.`}):d!=null&&m.push({type:`unsupported-setting`,setting:`tools`,details:`JSON response format does not support tools. The provided tools are ignored.`}));let h=l?.type===`json`&&l.schema!=null?{type:`function`,name:`json`,description:`Respond with a JSON object.`,inputSchema:l.schema}:void 0,g=await pe({provider:`anthropic`,providerOptions:p,schema:Ne}),{prompt:_,betas:v}=await Ze({prompt:e,sendReasoning:g?.sendReasoning??!0,warnings:m}),y=g?.thinking?.type===`enabled`,b=g?.thinking?.budgetTokens,x={model:this.modelId,max_tokens:n,temperature:r,top_k:a,top_p:i,stop_sequences:c,...y&&{thinking:{type:`enabled`,budget_tokens:b}},system:_.system,messages:_.messages};if(y){if(b==null)throw new t.UnsupportedFunctionalityError({functionality:`thinking requires a budget`});x.temperature!=null&&(x.temperature=void 0,m.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported when thinking is enabled`})),a!=null&&(x.top_k=void 0,m.push({type:`unsupported-setting`,setting:`topK`,details:`topK is not supported when thinking is enabled`})),i!=null&&(x.top_p=void 0,m.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported when thinking is enabled`})),x.max_tokens=n+b}let{tools:S,toolChoice:C,toolWarnings:w,betas:T}=Ke(h==null?{tools:d??[],toolChoice:f,disableParallelToolUse:g?.disableParallelToolUse}:{tools:[h],toolChoice:{type:`tool`,toolName:h.name},disableParallelToolUse:!0});return{args:{...x,tools:S,tool_choice:C},warnings:[...m,...w],betas:new Set([...v,...T]),usesJsonResponseTool:h!=null}}async getHeaders({betas:e,headers:t}){return O(await be(this.config.headers),e.size>0?{"anthropic-beta":Array.from(e).join(`,`)}:{},t)}buildRequestUrl(e){var t;return(t=this.config).buildRequestUrl?.call(t,this.config.baseURL,e)??`${this.config.baseURL}/messages`}transformRequestBody(e){var t;return(t=this.config).transformRequestBody?.call(t,e)??e}extractCitationDocuments(e){return e.filter(e=>e.role===`user`).flatMap(e=>e.content).filter(e=>e.type!==`file`||e.mediaType!==`application/pdf`&&e.mediaType!==`text/plain`?!1:e.providerOptions?.anthropic?.citations?.enabled??!1).map(e=>{let t=e;return{title:t.filename??`Untitled Document`,filename:t.filename,mediaType:t.mediaType}})}async doGenerate(e){let{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),a=this.extractCitationDocuments(e.prompt),{responseHeaders:o,value:s,rawValue:c}=await he({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(t),failedResponseHandler:Me,successfulResponseHandler:Se(at),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=[];for(let e of s.content)switch(e.type){case`text`:if(!i&&(l.push({type:`text`,text:e.text}),e.citations))for(let t of e.citations)nt(t,a,this.generateId,e=>l.push(e));break;case`thinking`:l.push({type:`reasoning`,text:e.thinking,providerMetadata:{anthropic:{signature:e.signature}}});break;case`redacted_thinking`:l.push({type:`reasoning`,text:``,providerMetadata:{anthropic:{redactedData:e.data}}});break;case`tool_use`:l.push(i?{type:`text`,text:JSON.stringify(e.input)}:{type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input)});break;case`server_tool_use`:(e.name===`web_search`||e.name===`code_execution`||e.name===`web_fetch`)&&l.push({type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input),providerExecuted:!0});break;case`web_fetch_tool_result`:e.content.type===`web_fetch_result`?l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,result:{type:`web_fetch_result`,url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}},providerExecuted:!0}):e.content.type===`web_fetch_tool_result_error`&&l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,isError:!0,result:{type:`web_fetch_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break;case`web_search_tool_result`:if(Array.isArray(e.content)){l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type})),providerExecuted:!0});for(let t of e.content)l.push({type:`source`,sourceType:`url`,id:this.generateId(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break;case`code_execution_tool_result`:e.content.type===`code_execution_result`?l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break}return{content:l,finishReason:$e({finishReason:s.stop_reason,isJsonResponseFromTool:i}),usage:{inputTokens:s.usage.input_tokens,outputTokens:s.usage.output_tokens,totalTokens:s.usage.input_tokens+s.usage.output_tokens,cachedInputTokens:s.usage.cache_read_input_tokens??void 0},request:{body:t},response:{id:s.id??void 0,modelId:s.model??void 0,headers:o,body:c},warnings:n,providerMetadata:{anthropic:{usage:s.usage,cacheCreationInputTokens:s.usage.cache_creation_input_tokens??null,stopSequence:s.stop_sequence??null}}}}async doStream(e){let{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),a=this.extractCitationDocuments(e.prompt),o={...t,stream:!0},{responseHeaders:s,value:c}=await he({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(o),failedResponseHandler:Me,successfulResponseHandler:xe(ot),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=`unknown`,u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},d={},f,p=null,m=null,h,g=this.generateId;return{stream:c.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let r=t.value;switch(r.type){case`ping`:return;case`content_block_start`:{let e=r.content_block.type;switch(h=e,e){case`text`:d[r.index]={type:`text`},n.enqueue({type:`text-start`,id:String(r.index)});return;case`thinking`:d[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index)});return;case`redacted_thinking`:d[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index),providerMetadata:{anthropic:{redactedData:r.content_block.data}}});return;case`tool_use`:d[r.index]=i?{type:`text`}:{type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``},n.enqueue(i?{type:`text-start`,id:String(r.index)}:{type:`tool-input-start`,id:r.content_block.id,toolName:r.content_block.name});return;case`server_tool_use`:(r.content_block.name===`web_fetch`||r.content_block.name===`web_search`||r.content_block.name===`code_execution`)&&(d[r.index]={type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``,providerExecuted:!0},n.enqueue({type:`tool-input-start`,id:r.content_block.id,toolName:r.content_block.name,providerExecuted:!0}));return;case`web_fetch_tool_result`:{let e=r.content_block;e.content.type===`web_fetch_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,result:{type:`web_fetch_result`,url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}}}):e.content.type===`web_fetch_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,isError:!0,result:{type:`web_fetch_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}case`web_search_tool_result`:{let e=r.content_block;if(Array.isArray(e.content)){n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type})),providerExecuted:!0});for(let t of e.content)n.enqueue({type:`source`,sourceType:`url`,id:g(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}case`code_execution_tool_result`:{let e=r.content_block;e.content.type===`code_execution_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}default:{let t=e;throw Error(`Unsupported content block type: ${t}`)}}}case`content_block_stop`:if(d[r.index]!=null){let e=d[r.index];switch(e.type){case`text`:n.enqueue({type:`text-end`,id:String(r.index)});break;case`reasoning`:n.enqueue({type:`reasoning-end`,id:String(r.index)});break;case`tool-call`:i||(n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue(e));break}delete d[r.index]}h=void 0;return;case`content_block_delta`:{let e=r.delta.type;switch(e){case`text_delta`:if(i)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:r.delta.text});return;case`thinking_delta`:n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:r.delta.thinking});return;case`signature_delta`:h===`thinking`&&n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:``,providerMetadata:{anthropic:{signature:r.delta.signature}}});return;case`input_json_delta`:{let e=d[r.index],t=r.delta.partial_json;if(i){if(e?.type!==`text`)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:t})}else{if(e?.type!==`tool-call`)return;n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:t}),e.input+=t}return}case`citations_delta`:{let e=r.delta.citation;nt(e,a,g,e=>n.enqueue(e));return}default:{let t=e;throw Error(`Unsupported delta type: ${t}`)}}}case`message_start`:u.inputTokens=r.message.usage.input_tokens,u.cachedInputTokens=r.message.usage.cache_read_input_tokens??void 0,f={...r.message.usage},p=r.message.usage.cache_creation_input_tokens??null,n.enqueue({type:`response-metadata`,id:r.message.id??void 0,modelId:r.message.model??void 0});return;case`message_delta`:u.outputTokens=r.usage.output_tokens,u.totalTokens=(u.inputTokens??0)+(r.usage.output_tokens??0),l=$e({finishReason:r.delta.stop_reason,isJsonResponseFromTool:i}),m=r.delta.stop_sequence??null,f={...f,...r.usage};return;case`message_stop`:n.enqueue({type:`finish`,finishReason:l,usage:u,providerMetadata:{anthropic:{usage:f??null,cacheCreationInputTokens:p,stopSequence:m}}});return;case`error`:n.enqueue({type:`error`,error:r.error});return;default:{let e=r;throw Error(`Unsupported chunk type: ${e}`)}}}})),request:{body:o},response:{headers:s}}}},at=r.z.object({type:r.z.literal(`message`),id:r.z.string().nullish(),model:r.z.string().nullish(),content:r.z.array(r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`text`),text:r.z.string(),citations:r.z.array(tt).optional()}),r.z.object({type:r.z.literal(`thinking`),thinking:r.z.string(),signature:r.z.string()}),r.z.object({type:r.z.literal(`redacted_thinking`),data:r.z.string()}),r.z.object({type:r.z.literal(`tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.unknown()}),r.z.object({type:r.z.literal(`server_tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.record(r.z.string(),r.z.unknown()).nullish()}),r.z.object({type:r.z.literal(`web_fetch_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),retrieved_at:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string().nullable(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.object({type:r.z.literal(`text`),media_type:r.z.string(),data:r.z.string()})})}),r.z.object({type:r.z.literal(`web_fetch_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`web_search_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.array(r.z.object({type:r.z.literal(`web_search_result`),url:r.z.string(),title:r.z.string(),encrypted_content:r.z.string(),page_age:r.z.string().nullish()})),r.z.object({type:r.z.literal(`web_search_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`code_execution_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),r.z.object({type:r.z.literal(`code_execution_tool_result_error`),error_code:r.z.string()})])})])),stop_reason:r.z.string().nullish(),stop_sequence:r.z.string().nullish(),usage:r.z.looseObject({input_tokens:r.z.number(),output_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish(),cache_read_input_tokens:r.z.number().nullish()})}),ot=r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`message_start`),message:r.z.object({id:r.z.string().nullish(),model:r.z.string().nullish(),usage:r.z.looseObject({input_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish(),cache_read_input_tokens:r.z.number().nullish()})})}),r.z.object({type:r.z.literal(`content_block_start`),index:r.z.number(),content_block:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`text`),text:r.z.string()}),r.z.object({type:r.z.literal(`thinking`),thinking:r.z.string()}),r.z.object({type:r.z.literal(`tool_use`),id:r.z.string(),name:r.z.string()}),r.z.object({type:r.z.literal(`redacted_thinking`),data:r.z.string()}),r.z.object({type:r.z.literal(`server_tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.record(r.z.string(),r.z.unknown()).nullish()}),r.z.object({type:r.z.literal(`web_fetch_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),retrieved_at:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string().nullable(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.object({type:r.z.literal(`text`),media_type:r.z.string(),data:r.z.string()})})}),r.z.object({type:r.z.literal(`web_fetch_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`web_search_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.array(r.z.object({type:r.z.literal(`web_search_result`),url:r.z.string(),title:r.z.string(),encrypted_content:r.z.string(),page_age:r.z.string().nullish()})),r.z.object({type:r.z.literal(`web_search_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`code_execution_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),r.z.object({type:r.z.literal(`code_execution_tool_result_error`),error_code:r.z.string()})])})])}),r.z.object({type:r.z.literal(`content_block_delta`),index:r.z.number(),delta:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`input_json_delta`),partial_json:r.z.string()}),r.z.object({type:r.z.literal(`text_delta`),text:r.z.string()}),r.z.object({type:r.z.literal(`thinking_delta`),thinking:r.z.string()}),r.z.object({type:r.z.literal(`signature_delta`),signature:r.z.string()}),r.z.object({type:r.z.literal(`citations_delta`),citation:tt})])}),r.z.object({type:r.z.literal(`content_block_stop`),index:r.z.number()}),r.z.object({type:r.z.literal(`error`),error:r.z.object({type:r.z.string(),message:r.z.string()})}),r.z.object({type:r.z.literal(`message_delta`),delta:r.z.object({stop_reason:r.z.string().nullish(),stop_sequence:r.z.string().nullish()}),usage:r.z.looseObject({output_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish()})}),r.z.object({type:r.z.literal(`message_stop`)}),r.z.object({type:r.z.literal(`ping`)})]),st=r.z.object({signature:r.z.string().optional(),redactedData:r.z.string().optional()}),ct=ve({id:`anthropic.bash_20241022`,name:`bash`,inputSchema:r.default.object({command:r.default.string(),restart:r.default.boolean().optional()})}),lt=ve({id:`anthropic.bash_20250124`,name:`bash`,inputSchema:r.default.object({command:r.default.string(),restart:r.default.boolean().optional()})}),ut=ve({id:`anthropic.computer_20241022`,name:`computer`,inputSchema:r.z.object({action:r.z.enum([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:r.z.array(r.z.number().int()).optional(),text:r.z.string().optional()})}),dt=ve({id:`anthropic.computer_20250124`,name:`computer`,inputSchema:r.z.object({action:r.z.enum([`key`,`hold_key`,`type`,`cursor_position`,`mouse_move`,`left_mouse_down`,`left_mouse_up`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`triple_click`,`scroll`,`wait`,`screenshot`]),coordinate:r.z.tuple([r.z.number().int(),r.z.number().int()]).optional(),duration:r.z.number().optional(),scroll_amount:r.z.number().optional(),scroll_direction:r.z.enum([`up`,`down`,`left`,`right`]).optional(),start_coordinate:r.z.tuple([r.z.number().int(),r.z.number().int()]).optional(),text:r.z.string().optional()})}),ft=ve({id:`anthropic.text_editor_20241022`,name:`str_replace_editor`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),pt=ve({id:`anthropic.text_editor_20250124`,name:`str_replace_editor`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),mt=ve({id:`anthropic.text_editor_20250429`,name:`str_replace_based_edit_tool`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),ht={bash_20241022:ct,bash_20250124:lt,codeExecution_20250522:Ye,computer_20241022:ut,computer_20250124:dt,textEditor_20241022:ft,textEditor_20250124:pt,textEditor_20250429:mt,textEditor_20250728:Le,webFetch_20250910:Ge,webSearch_20250305:Ve};function gt(e={}){let n=ke(e.baseURL)??`https://api.anthropic.com/v1`,r=()=>M({"anthropic-version":`2023-06-01`,"x-api-key":ne({apiKey:e.apiKey,environmentVariableName:`ANTHROPIC_API_KEY`,description:`Anthropic`}),...e.headers},`ai-sdk/anthropic/${Ae}`),i=t=>new it(t,{provider:`anthropic.messages`,baseURL:n,headers:r,fetch:e.fetch,generateId:e.generateId??P,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})}),a=function(e){if(new.target)throw Error(`The Anthropic model function cannot be called with the new keyword.`);return i(e)};return a.languageModel=i,a.chat=i,a.messages=i,a.textEmbeddingModel=e=>{throw new t.NoSuchModelError({modelId:e,modelType:`textEmbeddingModel`})},a.imageModel=e=>{throw new t.NoSuchModelError({modelId:e,modelType:`imageModel`})},a.tools=ht,a}var _t=gt();function vt(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function yt(e){return Object.fromEntries([...e.headers])}function bt(e=globalThis){return e.window?`runtime/browser`:e.navigator?.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:e.process?.versions?.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?`runtime/vercel-edge`:`runtime/unknown`}function xt(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function St(e,...t){let n=xt(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var Ct=({prefix:e,size:n=16,alphabet:r=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:i=`-`}={})=>{let a=()=>{let e=r.length,t=Array(n);for(let i=0;i<n;i++)t[i]=r[Math.random()*e|0];return t.join(``)};if(e==null)return a;if(r.includes(i))throw new t.InvalidArgumentError({argument:`separator`,message:`The separator "${i}" must not be part of the alphabet "${r}".`});return()=>`${e}${i}${a()}`},wt=Ct();function Tt(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Et=[`fetch failed`,`failed to fetch`];function Dt({error:e,url:n,requestBodyValues:r}){if(Tt(e))return e;if(e instanceof TypeError&&Et.includes(e.message.toLowerCase())){let i=e.cause;if(i!=null)return new t.APICallError({message:`Cannot connect to API: ${i.message}`,cause:i,url:n,requestBodyValues:r,isRetryable:!0})}return e}var Ot=`3.0.10`;function kt({apiKey:e,environmentVariableName:n,apiKeyParameterName:r=`apiKey`,description:i}){if(typeof e==`string`)return e;if(e!=null)throw new t.LoadAPIKeyError({message:`${i} API key must be a string.`});if(typeof process>`u`)throw new t.LoadAPIKeyError({message:`${i} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[n],e==null)throw new t.LoadAPIKeyError({message:`${i} API key is missing. Pass it using the '${r}' parameter or the ${n} environment variable.`});if(typeof e!=`string`)throw new t.LoadAPIKeyError({message:`${i} API key must be a string. The value of the ${n} environment variable is not a string.`});return e}var At=/"__proto__"\s*:/,jt=/"constructor"\s*:/;function Mt(e){let t=JSON.parse(e);return typeof t!=`object`||!t||At.test(e)===!1&&jt.test(e)===!1?t:Nt(t)}function Nt(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function Pt(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Mt(e)}finally{Error.stackTraceLimit=t}}var Ft=Symbol.for(`vercel.ai.validator`);function It(e){return{[Ft]:!0,validate:e}}function Lt(e){return typeof e==`object`&&!!e&&Ft in e&&e[Ft]===!0&&`validate`in e}function Rt(e){return Lt(e)?e:zt(e)}function zt(e){return It(async n=>{let r=await e[`~standard`].validate(n);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new t.TypeValidationError({value:n,cause:r.issues})}})}async function Bt({value:e,schema:n}){let r=await Vt({value:e,schema:n});if(!r.success)throw t.TypeValidationError.wrap({value:e,cause:r.error});return r.value}async function Vt({value:e,schema:n}){let r=Rt(n);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};let n=await r.validate(e);return n.success?{success:!0,value:n.value,rawValue:e}:{success:!1,error:t.TypeValidationError.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:t.TypeValidationError.wrap({value:e,cause:n}),rawValue:e}}}async function Ht({text:e,schema:n}){try{let t=Pt(e);return n==null?t:Bt({value:t,schema:n})}catch(n){throw t.JSONParseError.isInstance(n)||t.TypeValidationError.isInstance(n)?n:new t.JSONParseError({text:e,cause:n})}}async function Ut({text:e,schema:n}){try{let t=Pt(e);return n==null?{success:!0,value:t,rawValue:t}:await Vt({value:t,schema:n})}catch(n){return{success:!1,error:t.JSONParseError.isInstance(n)?n:new t.JSONParseError({text:e,cause:n}),rawValue:void 0}}}function Wt({stream:e,schema:n}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new t.EventSourceParserStream).pipeThrough(new TransformStream({async transform({data:e},t){e!==`[DONE]`&&t.enqueue(await Ut({text:e,schema:n}))}}))}async function Gt({provider:e,providerOptions:n,schema:r}){if(n?.[e]==null)return;let i=await Vt({value:n[e],schema:r});if(!i.success)throw new t.InvalidArgumentError({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:i.error});return i.value}var Kt=()=>globalThis.fetch,qt=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>Jt({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),Jt=async({url:e,headers:n={},body:r,successfulResponseHandler:i,failedResponseHandler:a,abortSignal:o,fetch:s=Kt()})=>{try{let c=await s(e,{method:`POST`,headers:St(n,`ai-sdk/provider-utils/${Ot}`,bt()),body:r.content,signal:o}),l=yt(c);if(!c.ok){let n;try{n=await a({response:c,url:e,requestBodyValues:r.values})}catch(n){throw Tt(n)||t.APICallError.isInstance(n)?n:new t.APICallError({message:`Failed to process error response`,cause:n,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw n.value}try{return await i({response:c,url:e,requestBodyValues:r.values})}catch(n){throw n instanceof Error&&(Tt(n)||t.APICallError.isInstance(n))?n:new t.APICallError({message:`Failed to process successful response`,cause:n,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(t){throw Dt({error:t,url:e,requestBodyValues:r.values})}};function Yt(e){return e}function Xt({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>Yt({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function Zt({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>Yt({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:r,execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}async function Qt(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var $t=({errorSchema:e,errorToMessage:n,isRetryable:r})=>async({response:i,url:a,requestBodyValues:o})=>{let s=await i.text(),c=yt(i);if(s.trim()===``)return{responseHeaders:c,value:new t.APICallError({message:i.statusText,url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,isRetryable:r?.(i)})};try{let l=await Ht({text:s,schema:e});return{responseHeaders:c,value:new t.APICallError({message:n(l),url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,data:l,isRetryable:r?.(i,l)})}}catch{return{responseHeaders:c,value:new t.APICallError({message:i.statusText,url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,isRetryable:r?.(i)})}}},en=e=>async({response:n})=>{let r=yt(n);if(n.body==null)throw new t.EmptyResponseBodyError({});return{responseHeaders:r,value:Wt({stream:n.body,schema:e})}},tn=e=>async({response:n,url:r,requestBodyValues:i})=>{let a=await n.text(),o=await Ut({text:a,schema:e}),s=yt(n);if(!o.success)throw new t.APICallError({message:`Invalid JSON response`,cause:o.error,statusCode:n.status,responseHeaders:s,responseBody:a,url:r,requestBodyValues:i});return{responseHeaders:s,value:o.value,rawValue:o.rawValue}},nn=Symbol(`Let zodToJsonSchema decide on which parser to use`),rn=Symbol.for(`vercel.ai.schema`),{btoa:an,atob:on}=globalThis;function sn(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return an(t)}function cn(e){return e instanceof Uint8Array?sn(e):e}function ln(e){return e?.replace(/\/$/,``)}var un=`2.0.17`,dn=r.z.object({error:r.z.object({code:r.z.number().nullable(),message:r.z.string(),status:r.z.string()})}),fn=$t({errorSchema:dn,errorToMessage:e=>e.error.message}),pn=r.z.object({outputDimensionality:r.z.number().optional(),taskType:r.z.enum([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional()}),mn=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:n,abortSignal:r,providerOptions:i}){let a=await Gt({provider:`google`,providerOptions:i,schema:pn});if(e.length>this.maxEmbeddingsPerCall)throw new t.TooManyEmbeddingValuesForCallError({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let o=vt(await Qt(this.config.headers),n);if(e.length===1){let{responseHeaders:t,value:n,rawValue:i}=await qt({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:o,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType},failedResponseHandler:fn,successfulResponseHandler:tn(gn),abortSignal:r,fetch:this.config.fetch});return{embeddings:[n.embedding.values],usage:void 0,response:{headers:t,body:i}}}let{responseHeaders:s,value:c,rawValue:l}=await qt({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:o,body:{requests:e.map(e=>({model:`models/${this.modelId}`,content:{role:`user`,parts:[{text:e}]},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType}))},failedResponseHandler:fn,successfulResponseHandler:tn(hn),abortSignal:r,fetch:this.config.fetch});return{embeddings:c.embeddings.map(e=>e.values),usage:void 0,response:{headers:s,body:l}}}},hn=r.z.object({embeddings:r.z.array(r.z.object({values:r.z.array(r.z.number())}))}),gn=r.z.object({embedding:r.z.object({values:r.z.array(r.z.number())})});function _n(e){if(e==null||vn(e))return;if(typeof e==`boolean`)return{type:`boolean`,properties:{}};let{type:t,description:n,required:r,properties:i,items:a,allOf:o,anyOf:s,oneOf:c,format:l,const:u,minLength:d,enum:f}=e,p={};if(n&&(p.description=n),r&&(p.required=r),l&&(p.format=l),u!==void 0&&(p.enum=[u]),t&&(Array.isArray(t)?t.includes(`null`)?(p.type=t.filter(e=>e!==`null`)[0],p.nullable=!0):p.type=t:t===`null`?p.type=`null`:p.type=t),f!==void 0&&(p.enum=f),i!=null&&(p.properties=Object.entries(i).reduce((e,[t,n])=>(e[t]=_n(n),e),{})),a&&(p.items=Array.isArray(a)?a.map(_n):_n(a)),o&&(p.allOf=o.map(_n)),s)if(s.some(e=>typeof e==`object`&&e?.type===`null`)){let e=s.filter(e=>!(typeof e==`object`&&e?.type===`null`));if(e.length===1){let t=_n(e[0]);typeof t==`object`&&(p.nullable=!0,Object.assign(p,t))}else p.anyOf=e.map(_n),p.nullable=!0}else p.anyOf=s.map(_n);return c&&(p.oneOf=c.map(_n)),d!==void 0&&(p.minLength=d),p}function vn(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}function yn(e,n){let r=[],i=[],a=!0,o=n?.isGemmaModel??!1;for(let{role:n,content:o}of e)switch(n){case`system`:if(!a)throw new t.UnsupportedFunctionalityError({functionality:`system messages are only supported at the beginning of the conversation`});r.push({text:o});break;case`user`:{a=!1;let e=[];for(let t of o)switch(t.type){case`text`:e.push({text:t.text});break;case`file`:{let n=t.mediaType===`image/*`?`image/jpeg`:t.mediaType;e.push(t.data instanceof URL?{fileData:{mimeType:n,fileUri:t.data.toString()}}:{inlineData:{mimeType:n,data:cn(t.data)}});break}}i.push({role:`user`,parts:e});break}case`assistant`:a=!1,i.push({role:`model`,parts:o.map(e=>{switch(e.type){case`text`:return e.text.length===0?void 0:{text:e.text,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`reasoning`:return e.text.length===0?void 0:{text:e.text,thought:!0,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`file`:if(e.mediaType!==`image/png`)throw new t.UnsupportedFunctionalityError({functionality:`Only PNG images are supported in assistant messages`});if(e.data instanceof URL)throw new t.UnsupportedFunctionalityError({functionality:`File data URLs in assistant messages are not supported`});return{inlineData:{mimeType:e.mediaType,data:cn(e.data)}};case`tool-call`:return{functionCall:{name:e.toolName,args:e.input},thoughtSignature:e.providerOptions?.google?.thoughtSignature}}}).filter(e=>e!==void 0)});break;case`tool`:{a=!1;let e=[];for(let t of o){let n=t.output;if(n.type===`content`)for(let r of n.value)switch(r.type){case`text`:e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:r.text}}});break;case`media`:e.push({inlineData:{mimeType:r.mediaType,data:r.data}},{text:`Tool executed successfully and returned this image as a response`});break;default:e.push({text:JSON.stringify(r)});break}else e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:n.value}}})}i.push({role:`user`,parts:e});break}}if(o&&r.length>0&&i.length>0&&i[0].role===`user`){let e=r.map(e=>e.text).join(`
2
2
 
3
3
  `);i[0].parts.unshift({text:e+`
4
4
 
@@ -138,15 +138,15 @@ ${Dm}${t.trimStart()}`),n=3+(0,l.stripVTControlCharacters)(t.trimStart()).length
138
138
  `);process.stdout.write(Wp.cursor.move(-999,e.length-1)),process.stdout.write(Wp.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=fp(),s=g(u),l=performance.now(),process.stdout.write(`${X.default.gray(Q)}
139
139
  `);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(Xp):n===1?X.default.red(Jp):X.default.red(Yp);s=g(t??s),e===`timer`?process.stdout.write(`${r} ${s} ${_(l)}
140
140
  `):process.stdout.write(`${r} ${s}
141
- `),m(),i()};return{start:v,stop:y,message:(e=``)=>{s=g(e??s)}}},Am=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`&&up(a)){n[i]=`canceled`,t.onCancel({results:n});continue}n[i]=a}return n},jm=async e=>{for(let t of e){if(t.enabled===!1)continue;let e=km();e.start(t.title);let n=await t.task(e.message);e.stop(n||t.title)}};let Mm;function Nm(){try{return o.default.statSync(`/.dockerenv`),!0}catch{return!1}}function Pm(){try{return o.default.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function Fm(){return Mm===void 0&&(Mm=Nm()||Pm()),Mm}let Im;const Lm=()=>{try{return o.default.statSync(`/run/.containerenv`),!0}catch{return!1}};function Rm(){return Im===void 0&&(Im=Lm()||Fm()),Im}const zm=()=>{if(x.default.platform!==`linux`)return!1;if(S.default.release().toLowerCase().includes(`microsoft`))return!Rm();try{return o.default.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!Rm():!1}catch{return!1}};var Bm=x.default.env.__IS_WSL_TEST__?zm:zm();const Vm=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await E.default.access(n,E.constants.F_OK),r=!0}catch{}if(!r)return e;let i=await E.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}})(),Hm=async()=>`${await Vm()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Um=async()=>Bm?Hm():`${x.default.env.SYSTEMROOT||x.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function Wm(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 Gm=(0,l.promisify)(T.execFile);async function Km(){if(x.default.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await Gm(`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 qm=(0,l.promisify)(T.execFile);async function Jm(e,{humanReadableOutput:t=!0,signal:n}={}){if(x.default.platform!==`darwin`)throw Error(`macOS only`);let r=t?[]:[`-ss`],i={};n&&(i.signal=n);let{stdout:a}=await qm(`osascript`,[`-e`,e,r],i);return a.trim()}async function Ym(e){return Jm(`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 Xm=(0,l.promisify)(T.execFile),Zm={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 Qm=class extends Error{};async function $m(e=Xm){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 Qm(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=Zm[r];if(!i)throw new Qm(`Unknown browser ID: ${r}`);return i}const eh=(0,l.promisify)(T.execFile),th=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function nh(){if(x.default.platform===`darwin`){let e=await Km();return{name:await Ym(e),id:e}}if(x.default.platform===`linux`){let{stdout:e}=await eh(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:th(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(x.default.platform===`win32`)return $m();throw Error(`Only macOS, Linux, and Windows are supported`)}const rh=(0,l.promisify)(T.default.execFile),ih=b.default.dirname((0,s.fileURLToPath)(require(`url`).pathToFileURL(__filename).href)),ah=b.default.join(ih,`xdg-open`),{platform:oh,arch:sh}=x.default;async function ch(){let e=await Um(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=a.Buffer.from(t,`utf16le`).toString(`base64`),{stdout:r}=await rh(e,[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,n],{encoding:`utf8`}),i=r.trim(),o={ChromeHTML:`com.google.chrome`,BraveHTML:`com.brave.Browser`,MSEdgeHTM:`com.microsoft.edge`,FirefoxURL:`org.mozilla.firefox`};return o[i]?{id:o[i]}:{}}const lh=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},uh=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return lh(e.app,t=>uh({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return lh(t,t=>uh({...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=Bm?await ch():await nh();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),uh({...e,app:{name:mh[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,i=[],o={};if(oh===`darwin`)r=`open`,e.wait&&i.push(`--wait-apps`),e.background&&i.push(`--background`),e.newInstance&&i.push(`--new`),t&&i.push(`-a`,t);else if(oh===`win32`||Bm&&!Rm()&&!t){r=await Um(),i.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),Bm||(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=a.Buffer.from(s.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!ih||ih===`/`,t=!1;try{await E.default.access(ah,E.constants.X_OK),t=!0}catch{}r=x.default.versions.electron??(oh===`android`||e||!t)?`xdg-open`:ah}n.length>0&&i.push(...n),e.wait||(o.stdio=`ignore`,o.detached=!0)}oh===`darwin`&&n.length>0&&i.push(`--args`,...n),e.target&&i.push(e.target);let s=T.default.spawn(r,i,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)},dh=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return uh({...t,target:e})};function fh(e){if(typeof e==`string`||Array.isArray(e))return e;let{[sh]:t}=e;if(!t)throw Error(`${sh} is not supported`);return t}function ph({[oh]:e},{wsl:t}){if(t&&Bm)return fh(t);if(!e)throw Error(`${oh} is not supported`);return fh(e)}const mh={};Wm(mh,`chrome`,()=>ph({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`]}})),Wm(mh,`brave`,()=>ph({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`]}})),Wm(mh,`firefox`,()=>ph({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),Wm(mh,`edge`,()=>ph({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),Wm(mh,`browser`,()=>`browser`),Wm(mh,`browserPrivate`,()=>`browserPrivate`);var hh=dh;async function gh(e,t=void 0){try{(await hh(e)).once(`error`,n=>{console.log(Sf.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))})}catch{console.log(Sf.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))}}function _h(e){let t=e||bh();if((0,o.existsSync)(t)){let e=(0,o.readFileSync)(t,`utf8`);return JSON.parse(e).token}}function vh(e,t){let n=t||bh();(0,o.existsSync)((0,b.dirname)(n))||(0,o.mkdirSync)((0,b.dirname)(n),{recursive:!0}),(0,o.writeFileSync)(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function yh(e){let t=e||bh();(0,o.existsSync)(t)&&(0,o.unlinkSync)(t)}function bh(){let e=Fd(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return(0,b.join)(e[0],`auth.json`)}function xh(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=(0,_.useState)(),[s,c]=(0,_.useState)(()=>_h(i)),[l,u]=(0,_.useState)(),d=(0,_.useRef)(n),f=(0,_.useRef)(r);(0,_.useEffect)(()=>{d.current=n,f.current=r},[n,r]);let p=(0,_.useCallback)(async()=>{u(void 0);try{let e=_h(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new hd({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,_.useCallback)(async()=>{u(void 0);try{let e=new hd,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();vh(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,_.useCallback)(()=>{yh(i),c(void 0),o(void 0),u(void 0),d.current?.(void 0)},[i]);return(0,_.useEffect)(()=>{t&&p()},[t,p]),{user:a,token:s,error:l,login:m,logout:h}}let Sh=Promise.resolve();var Ch=class{constructor(e){this.printLog=e}setPrintLog(e){this.printLog=e}error(e,...t){Sh=Sh.then(()=>this.printLog(`error`,e,...t).catch(e=>{console.error(`Error printing log:`,e)}))}log(e,...t){Sh=Sh.then(()=>this.printLog(`log`,e,...t).catch(e=>{console.error(`Error printing log:`,e)}))}flush(){return Sh}};const wh=(0,_.createContext)(void 0);function Th(e){let{directory:t,logger:r,onBuildStart:i,onBuildSuccess:a,onBuildError:o}=typeof e==`string`?{directory:e,logger:new Ch(async()=>{})}:e,s=(0,_.useMemo)(()=>n.resolveConfig(t),[t]),[c,l]=(0,_.useState)(void 0),[u,d]=(0,_.useState)(void 0),[f,p]=(0,_.useState)(`building`),m=(0,_.useRef)(i),h=(0,_.useRef)(a),g=(0,_.useRef)(o);return(0,_.useEffect)(()=>{m.current=i,h.current=a,g.current=o},[i,a,o]),(0,_.useEffect)(()=>{let e=new AbortController;return s.build({cwd:t,entry:s.entry,outdir:s.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{p(`building`),l(void 0),d(void 0),m.current?.()},onResult:e=>{`error`in e?(l(e.error),p(`error`),g.current?.(e.error)):(d(e),p(`success`),h.current?.(e))}}).catch(e=>{r.error(`system`,`error`,e),p(`error`),l(e),g.current?.(e)}),()=>{e.abort()}},[t]),(0,_.useMemo)(()=>({error:c,status:f,result:u,entry:s.entry,outdir:s.outdir}),[c,f,u,s.entry,s.outdir])}function Eh(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function Dh(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const Oh=100,kh=/^\.+(\\|\/)|^\.+$/,Ah=/[. ]+$/,jh=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,Mh=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,Nh=e=>e===`‍`,Ph=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,Fh=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let Ih;function Lh(){return Ih??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),Ih}function Rh(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(Eh().test(n)||[...n].some(e=>Mh.test(e)&&!Nh(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(Fh,` `),n.length>0&&(e=e.replaceAll(Ph,`$1`)),e=e.replace(Ah,``),e=e.replace(kh,n),e=e.replace(Eh(),n),e=e.replaceAll(jh,e=>Nh(e)?e:n),e.length===0&&(e=n),e=Dh().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=zh(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=zh(n,a)+i}}return e}function zh(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of Lh().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function Bh(e){return`${e}.lock`}function Vh(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function Hh(e,t={}){let n=Bh(e),r=process.pid.toString();try{return o.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(o.readFileSync(n,`utf8`),10)}catch{return o.unlinkSync(n),Hh(e,{...t,stale:0})}if(!Vh(i))try{return o.unlinkSync(n),Hh(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return Hh(e,{...t,stale:0});throw n}return!1}}async function Uh(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=b.resolve(e),i=0;for(;i<=n.retries;){if(Hh(r,n))return()=>Wh(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 Wh(e){let t=b.resolve(e),n=Bh(t);try{if(parseInt(o.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}o.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function Gh(e){let t=b.resolve(e),n=Bh(t);try{if(!o.existsSync(n))return{locked:!1};let e=o.readFileSync(n,`utf8`),t=parseInt(e,10);return Vh(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const Kh=e=>{o.mkdirSync(e,{recursive:!0})},qh=e=>{try{o.fdatasyncSync(e)}catch{}try{o.closeSync(e)}catch{}},Jh=e=>{try{let t=o.openSync(e,`r`);try{o.fsyncSync(t)}finally{o.closeSync(t)}}catch{}},Yh=(e,t)=>{let n=b.dirname(e);Kh(n);let r=b.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=o.openSync(r,`w`),o.writeFileSync(i,t,`utf-8`),qh(i),i=void 0,o.renameSync(r,e),Jh(e),Jh(n)}catch(e){if(i!==void 0)try{o.closeSync(i)}catch{}try{o.rmSync(r,{force:!0})}catch{}throw e}},Xh=(e,t)=>{let n=new Map,r,i=e=>{if(o.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(o.readFileSync(e,`utf-8`))},a=(e,t)=>{Yh(e,JSON.stringify(t,null,2))},s=async()=>{if(r)throw Error(`Index is already locked`);let t=b.join(e,`index.json`);Kh(e),o.existsSync(t)||o.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await Uh(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},c=async()=>{let t=b.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},l=async t=>{let n=b.join(e,`index.json`);a(n,t)},u=async t=>{let n=(await c()).ids[t];if(n)return b.join(e,n)},d=async t=>{let n=(await c()).ids[t];if(!n)return;let r=b.join(e,n);if(o.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(o.readFileSync(r,`utf-8`))},f=async n=>{let r=n[t],i=String(r),o=Rh(i,{replacement:`_`})+`.json`,u=await s();try{let t=await c();t.ids[i]=o,t.current=i;let r=b.join(e,o);a(r,n),await l(t)}finally{await u()}};return{async get(e){return await d(e)},async list(){if(!o.statSync(e,{throwIfNoEntry:!1}))return[];let t=await c(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=b.join(e,i),a=o.statSync(t,{throwIfNoEntry:!1});if(!a)continue;let s=Gh(t);n.push({key:r,locked:s.locked,pid:s.pid,mtime:a.mtimeMs})}return n.sort((e,t)=>t.mtime-e.mtime),n},async lock(r,i){if(n.has(r))throw Error(`Key "${r}" is already locked in this process`);let a=await u(r);if(!a){let t=Rh(r,{replacement:`_`})+`.json`,n=await s();try{let n=await c();n.ids[r]=t;let i=b.join(e,t);Kh(e),o.writeFileSync(i,JSON.stringify({}),`utf-8`),await l(n),a=i}finally{await n()}}if(i?.force){let e=Gh(a);if(e.locked&&e.pid&&e.pid!==process.pid)try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,100))}catch(t){t.code!==`ESRCH`&&console.warn(`Failed to kill process ${e.pid}:`,t.message)}}let p=await Uh(a,{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=b.join(e,n);try{o.rmSync(i,{force:!0}),Jh(e)}catch{}}}finally{await t()}},async release(){try{p()}finally{n.delete(r)}}}},dispose(){n.clear()}}},Zh=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,a,s,c=new Map,l=new Map,u=b.join(e,`index.json`),d=()=>{try{if(!o.statSync(u,{throwIfNoEntry:!1}))return{ids:{}};let e=o.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=b.join(e,n);try{let e=o.statSync(i,{throwIfNoEntry:!1}),a=l.get(n);if(!e){a&&(l.delete(n),f(t,void 0,!1));return}let s=e.mtimeMs,c=a?{locked:a.locked,pid:a.pid}:{locked:!1,pid:void 0};if((r||!a)&&(c=Gh(i)),!a||a.mtime!==s||a.locked!==c.locked||a.pid!==c.pid){let e;e=!a||a.mtime!==s?JSON.parse(o.readFileSync(i,`utf-8`)):a.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(a)return;try{o.mkdirSync(e,{recursive:!0})}catch{}a=o.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){a&&=(a.close(),void 0),s&&=(clearTimeout(s),void 0);for(let e of c.values())clearTimeout(e);c.clear(),l.clear()}}},dispose(){a&&=(a.close(),void 0),s&&=(clearTimeout(s),void 0);for(let e of c.values())clearTimeout(e);c.clear(),i.clear(),l.clear()}}};async function Qh({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=$h}){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,m.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 $h=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(m.isToolOrDynamicToolUIPart);return r.length===0||r.some(e=>t.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`)?!1:r.every(e=>e.state.startsWith(`output-`))},eg=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function tg(e){return typeof e==`object`&&e?.__blink_internal!==void 0}function ng(e){return typeof e.metadata==`object`&&e.metadata!==null&&`__blink_log`in e.metadata&&e.metadata.__blink_log===!0&&`level`in e.metadata&&`source`in e.metadata&&`message`in e.metadata}var rg=class{chatId;agent;chatStore;serializeMessage;filterMessages;onError;chat;loading=!1;streamingMessage;status=`idle`;queue=[];logQueue=[];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=Xh(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.onError=e.onError,this.watcher=Zh(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.locked?`streaming`:`idle`,r=this.chat.updated_at!==t?.updated_at||this.status!==n;this.chat=t,this.streamingMessage=void 0,this.status=n,r&&this.notifyListeners()}),this.chatStore.get(this.chatId).then(e=>{this.disposed||e&&(this.chat=e)}).catch(e=>{let t=e instanceof Error?e.message:String(e);this.onError?.(t)}).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=>!tg(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,loading:this.loading,queuedMessages:this.queue,queuedLogs:this.logQueue}}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 queueLogMessage({message:e,level:t,source:n}){let r=`(EDIT MODE NOTE) ${n===`agent`?`The agent`:"The `blink dev` CLI"} printed the following ${t}:\n\`\`\`\n${(0,l.stripVTControlCharacters)(e)}\n\`\`\`\n`,i={id:crypto.randomUUID(),created_at:new Date().toISOString(),role:`user`,parts:[{type:`text`,text:r}],metadata:{__blink_log:!0,level:t,source:n,message:e},mode:`edit`};this.logQueue.push(i),this.notifyListeners()}async flushLogQueue(e){if(this.logQueue.length===0)return;let t=[...this.logQueue];this.logQueue=[],await this.upsertMessages(t,e)}async sendMessages(e){if(this.status=`idle`,this.notifyListeners(),this.isProcessingQueue){this.queue.push(...e),this.notifyListeners();return}this.queue=e,this.processQueueOrRun()}async start(){this.status=`idle`,this.notifyListeners(),this.processQueueOrRun()}async stop(){this.status=`idle`,this.abortController?.abort(),this.notifyListeners()}async processQueueOrRun(){if(!this.agent){this.onError?.(`The agent is not available. Please wait for the build to succeed.`),this.queue=[];return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0;let e;try{e=await this.chatStore.lock(this.chatId),await this.flushLogQueue(e);let n=!0;for(;this.queue.length>0||n;)try{var t=Xs();n=!1;let r=new AbortController;this.abortController=r;let i=[...this.queue];this.queue=[],this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),i.length>0&&await this.upsertMessages(i,e);let a=this.chat.messages;this.filterMessages&&(a=a.filter(this.filterMessages)),a=a.map(e=>({...e,parts:e.parts.map(e=>!(0,m.isToolOrDynamicToolUIPart)(e)||e.input!==``?e:{...e,input:{}})})),t.u(await this.agent.lock.read());let o=performance.now(),s=await Qh({agent:this.agent.client,id:this.chatId,signal:r.signal,messages:a}),c=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)},l=s.getReader();r.signal.addEventListener(`abort`,()=>{l.cancel().catch(()=>{})},{once:!0});let u;try{for(;;){let{done:e,value:t}=await l.read();if(e||r.signal.aborted)break;u||=performance.now()-o,this.streamingMessage&&t.id!==this.streamingMessage.id&&await c(this.streamingMessage);let n={...t,metadata:{...typeof t.metadata==`object`&&t.metadata!==null?t.metadata:{},ttft:u}};this.streamingMessage=this.serializeMessage?this.serializeMessage(n):n,this.notifyListeners()}}finally{l.releaseLock()}this.streamingMessage&&await c(this.streamingMessage)}catch(e){t.e=e}finally{t.d()}}catch(e){let t=e instanceof Error?e.message:String(e);this.onError?.(t)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,this.status=`idle`,e&&(await this.flushLogQueue(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.stopStreaming()}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=[],this.logQueue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};function ig(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a,onError:o}=e,s=(0,_.useRef)(null),[c,l]=(0,_.useState)({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[],queuedLogs:[]});(0,_.useEffect)(()=>{s.current&&s.current.dispose();let e=new rg({chatId:t,chatsDirectory:r,serializeMessage:i,filterMessages:a,onError:o}),n=e.subscribe(e=>{l(e)});return l(e.getState()),s.current=e,()=>{n(),e.dispose(),s.current=null}},[t,r]),(0,_.useEffect)(()=>{s.current&&s.current.setAgent(n)},[n]);let u=(0,_.useCallback)(async e=>{s.current&&await s.current.sendMessages([e])},[]),d=(0,_.useCallback)(async e=>{s.current&&await s.current.upsertMessages([e])},[]),f=(0,_.useCallback)(async e=>{s.current&&await s.current.queueLogMessage(e)},[]),p=(0,_.useCallback)(()=>{s.current&&s.current.stopStreaming()},[]),m=(0,_.useCallback)(async()=>{s.current&&await s.current.resetChat()},[]),h=(0,_.useCallback)(()=>{s.current&&s.current.clearQueue()},[]),g=(0,_.useCallback)(async e=>{s.current&&await s.current.deleteMessages([e])},[]),v=(0,_.useCallback)(async()=>{s.current&&await s.current.start()},[]);return{...c,sendMessage:u,upsertMessage:d,queueLogMessage:f,stopStreaming:p,resetChat:m,clearQueue:h,deleteMessage:g,start:v}}function ag(e){return(0,f.join)(e,`.blink`,`devhook.txt`)}function og(e){return(0,p.existsSync)(ag(e))}function sg(e){let t=ag(e);if((0,p.existsSync)(t))return(0,p.readFileSync)(t,`utf-8`).trim()}function cg(e){let t=ag(e);if((0,p.mkdirSync)((0,f.dirname)(t),{recursive:!0}),(0,p.existsSync)(t))return(0,p.readFileSync)(t,`utf-8`);let n=crypto.randomUUID();return(0,p.writeFileSync)(t,n),n}const lg=(e,t)=>e.json({error:t},400),ug=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}},dg=()=>new t.Hono,fg=dg().get(`/:key`,async e=>{let{key:t,err:n}=ug(e);if(n)return lg(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?lg(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:lg(t,`Value must be a string`):lg(t,`Value is required`)}),async e=>{let{key:t,err:n}=ug(e);if(n)return lg(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}=ug(e);return n?lg(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})}),pg=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`}},mg=t.validator(`param`,e=>({id:e.id})),hg=dg().post(`/:key`,async e=>{let{key:t,err:n}=pg(e);return n?lg(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,mg,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,mg,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)):lg(e,`ID is required`)}).delete(`/:id/messages`,mg,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`,mg,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,mg,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,mg,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),gg=dg().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),_g=new t.Hono().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,fg).route(`/chat`,hg).route(`/otlp`,gg);var vg=/^(?:[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 yg(e){return typeof e==`string`&&vg.test(e)}var bg=yg;function xg(e){if(!bg(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 Sg=xg;const $=[];for(let e=0;e<256;++e)$.push((e+256).toString(16).slice(1));function Cg(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 wg(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 Tg=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,Eg=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;function Dg(e,t,n,r,i,a){let o=typeof n==`string`?wg(n):n,s=typeof r==`string`?Sg(r):r;if(typeof r==`string`&&(r=Sg(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 Cg(c)}function Og(e){return Array.isArray(e)?e=Buffer.from(e):typeof e==`string`&&(e=Buffer.from(e,`utf8`)),(0,u.createHash)(`sha1`).update(e).digest()}var kg=Og;function Ag(e,t,n,r){return Dg(80,kg,e,t,n,r)}Ag.DNS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,Ag.URL=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;var jg=Ag;function Mg(e){let n=(0,b.join)(e.dataDirectory,`chats`),r={},i=(0,b.join)(e.dataDirectory,`storage.json`);o.existsSync(i)&&(r=JSON.parse(o.readFileSync(i,`utf-8`)));let a=new Map,s=t=>{let r=a.get(t);return r||(r=new rg({chatId:t,chatsDirectory:n}),a.set(t,r)),r.setAgent(e.getAgent()),r},c={async upsert(e){let t=jg(JSON.stringify(e),jg.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=>eg(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,o.writeFileSync(i,JSON.stringify(r),`utf-8`),Promise.resolve()},delete(e){return delete r[e],o.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})}},u=(0,d.createServer)(t.createServerAdapter(e=>_g.fetch(e,{chat:c,store:l})));u.listen(e.port??0);let f=Xh(n,`id`);return{url:`http://127.0.0.1:${u.address().port}`,chatsDirectory:n,getChatManager:s,listChats:()=>f.list(),dispose:()=>{for(let e of a.values())e.dispose();a.clear(),f.dispose(),u.close()}}}function Ng({agent:e,capabilities:n,messages:r}){let[i,a]=(0,_.useState)(void 0),[o,s]=(0,_.useState)(!0),[c,l]=(0,_.useState)(void 0),u=(0,_.useRef)(c);(0,_.useEffect)(()=>{u.current=c},[c]);let[d,f]=(0,_.useState)(()=>t.lastUIOptions(r));(0,_.useEffect)(()=>{f(e=>{let n=t.lastUIOptions(r);return JSON.stringify(n)===JSON.stringify(e)?e:n})},[r]);let[p,m]=(0,_.useState)(void 0),h=(0,_.useCallback)((e,t)=>{if(!u.current)return!1;let n=u.current[e];return n?n.values.some(e=>e.id===t):!1},[]),g=(0,_.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,_.useEffect)(()=>{if(!d&&!c){m(void 0);return}g()},[d,c,g]);let v=(0,_.useRef)(void 0),y=(0,_.useRef)(void 0);(0,_.useEffect)(()=>{e!==y.current&&(y.current=e,l(void 0),m(void 0),a(void 0),s(!0),v.current=void 0)},[e]),(0,_.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,_.useCallback)((e,t)=>{g({[e]:t})},[g]);return{schema:c,options:p,setOption:b,loading:o,error:i}}function Pg(e){let t=(0,_.useRef)(e.onRequest);(0,_.useEffect)(()=>{t.current=e.onRequest},[e.onRequest]);let[n,r]=(0,_.useState)(`disconnected`);return(0,_.useEffect)(()=>{if(e.disabled||!e.id){r(`disconnected`);return}let n=!1,i,a,o=!1,s,c=(0,b.join)(e.directory,`.blink`,`devhook`);return(async()=>{try{s=await Uh(c,{stale:!0,retries:0})}catch(t){if(t&&typeof t==`object`&&`code`in t&&t.code===`ELOCKED`){let e=``;try{let t=Gh(c);t.locked&&t.pid&&(e=` (PID: ${t.pid})`)}catch{}console.error(Sf.red(`\nError: Another ${Sf.bold(`blink dev`)} process is already running in this directory${e}.`)),console.error(Sf.red(`Please stop the other process and try again.
142
- `)),process.exit(1)}let n=t&&typeof t==`object`&&`message`in t?String(t.message):String(t);e.logger.error(`system`,Sf.yellow(`\nWarning: Failed to acquire devhook lock: ${n}`)),e.logger.error(`system`,Sf.yellow(`Continuing without lock. Multiple ${Sf.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 hd({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(t){e.logger.error(`system`,`Failed to release devhook lock:`,t)}}},[e.disabled,e.directory]),{id:e.id,url:e.id?`https://${e.id}.blink.host`:void 0,status:n}}var Fg=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}}})),Ig=e.__commonJSMin(((e,t)=>{let n=require(`fs`),r=require(`path`),i=require(`os`),a=require(`crypto`),o=Fg().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,`
141
+ `),m(),i()};return{start:v,stop:y,message:(e=``)=>{s=g(e??s)}}},Am=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`&&up(a)){n[i]=`canceled`,t.onCancel({results:n});continue}n[i]=a}return n},jm=async e=>{for(let t of e){if(t.enabled===!1)continue;let e=km();e.start(t.title);let n=await t.task(e.message);e.stop(n||t.title)}};let Mm;function Nm(){try{return o.default.statSync(`/.dockerenv`),!0}catch{return!1}}function Pm(){try{return o.default.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function Fm(){return Mm===void 0&&(Mm=Nm()||Pm()),Mm}let Im;const Lm=()=>{try{return o.default.statSync(`/run/.containerenv`),!0}catch{return!1}};function Rm(){return Im===void 0&&(Im=Lm()||Fm()),Im}const zm=()=>{if(x.default.platform!==`linux`)return!1;if(S.default.release().toLowerCase().includes(`microsoft`))return!Rm();try{return o.default.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!Rm():!1}catch{return!1}};var Bm=x.default.env.__IS_WSL_TEST__?zm:zm();const Vm=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await E.default.access(n,E.constants.F_OK),r=!0}catch{}if(!r)return e;let i=await E.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}})(),Hm=async()=>`${await Vm()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Um=async()=>Bm?Hm():`${x.default.env.SYSTEMROOT||x.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function Wm(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 Gm=(0,l.promisify)(T.execFile);async function Km(){if(x.default.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await Gm(`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 qm=(0,l.promisify)(T.execFile);async function Jm(e,{humanReadableOutput:t=!0,signal:n}={}){if(x.default.platform!==`darwin`)throw Error(`macOS only`);let r=t?[]:[`-ss`],i={};n&&(i.signal=n);let{stdout:a}=await qm(`osascript`,[`-e`,e,r],i);return a.trim()}async function Ym(e){return Jm(`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 Xm=(0,l.promisify)(T.execFile),Zm={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 Qm=class extends Error{};async function $m(e=Xm){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 Qm(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=Zm[r];if(!i)throw new Qm(`Unknown browser ID: ${r}`);return i}const eh=(0,l.promisify)(T.execFile),th=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function nh(){if(x.default.platform===`darwin`){let e=await Km();return{name:await Ym(e),id:e}}if(x.default.platform===`linux`){let{stdout:e}=await eh(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:th(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(x.default.platform===`win32`)return $m();throw Error(`Only macOS, Linux, and Windows are supported`)}const rh=(0,l.promisify)(T.default.execFile),ih=b.default.dirname((0,s.fileURLToPath)(require(`url`).pathToFileURL(__filename).href)),ah=b.default.join(ih,`xdg-open`),{platform:oh,arch:sh}=x.default;async function ch(){let e=await Um(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=a.Buffer.from(t,`utf16le`).toString(`base64`),{stdout:r}=await rh(e,[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,n],{encoding:`utf8`}),i=r.trim(),o={ChromeHTML:`com.google.chrome`,BraveHTML:`com.brave.Browser`,MSEdgeHTM:`com.microsoft.edge`,FirefoxURL:`org.mozilla.firefox`};return o[i]?{id:o[i]}:{}}const lh=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},uh=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return lh(e.app,t=>uh({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return lh(t,t=>uh({...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=Bm?await ch():await nh();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),uh({...e,app:{name:mh[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,i=[],o={};if(oh===`darwin`)r=`open`,e.wait&&i.push(`--wait-apps`),e.background&&i.push(`--background`),e.newInstance&&i.push(`--new`),t&&i.push(`-a`,t);else if(oh===`win32`||Bm&&!Rm()&&!t){r=await Um(),i.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),Bm||(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=a.Buffer.from(s.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!ih||ih===`/`,t=!1;try{await E.default.access(ah,E.constants.X_OK),t=!0}catch{}r=x.default.versions.electron??(oh===`android`||e||!t)?`xdg-open`:ah}n.length>0&&i.push(...n),e.wait||(o.stdio=`ignore`,o.detached=!0)}oh===`darwin`&&n.length>0&&i.push(`--args`,...n),e.target&&i.push(e.target);let s=T.default.spawn(r,i,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)},dh=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return uh({...t,target:e})};function fh(e){if(typeof e==`string`||Array.isArray(e))return e;let{[sh]:t}=e;if(!t)throw Error(`${sh} is not supported`);return t}function ph({[oh]:e},{wsl:t}){if(t&&Bm)return fh(t);if(!e)throw Error(`${oh} is not supported`);return fh(e)}const mh={};Wm(mh,`chrome`,()=>ph({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`]}})),Wm(mh,`brave`,()=>ph({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`]}})),Wm(mh,`firefox`,()=>ph({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),Wm(mh,`edge`,()=>ph({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),Wm(mh,`browser`,()=>`browser`),Wm(mh,`browserPrivate`,()=>`browserPrivate`);var hh=dh;async function gh(e,t=void 0){try{(await hh(e)).once(`error`,n=>{console.log(Sf.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))})}catch{console.log(Sf.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))}}function _h(e){let t=e||bh();if((0,o.existsSync)(t)){let e=(0,o.readFileSync)(t,`utf8`);return JSON.parse(e).token}}function vh(e,t){let n=t||bh();(0,o.existsSync)((0,b.dirname)(n))||(0,o.mkdirSync)((0,b.dirname)(n),{recursive:!0}),(0,o.writeFileSync)(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function yh(e){let t=e||bh();(0,o.existsSync)(t)&&(0,o.unlinkSync)(t)}function bh(){let e=Fd(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return(0,b.join)(e[0],`auth.json`)}function xh(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=(0,_.useState)(),[s,c]=(0,_.useState)(()=>_h(i)),[l,u]=(0,_.useState)(),d=(0,_.useRef)(n),f=(0,_.useRef)(r);(0,_.useEffect)(()=>{d.current=n,f.current=r},[n,r]);let p=(0,_.useCallback)(async()=>{u(void 0);try{let e=_h(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new hd({baseURL:`https://blink.coder.com`});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,_.useCallback)(async()=>{u(void 0);try{let e=new hd,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();vh(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,_.useCallback)(()=>{yh(i),c(void 0),o(void 0),u(void 0),d.current?.(void 0)},[i]);return(0,_.useEffect)(()=>{t&&p()},[t,p]),{user:a,token:s,error:l,login:m,logout:h}}let Sh=Promise.resolve();var Ch=class{constructor(e){this.printLog=e}setPrintLog(e){this.printLog=e}error(e,...t){Sh=Sh.then(()=>this.printLog(`error`,e,...t).catch(e=>{console.error(`Error printing log:`,e)}))}log(e,...t){Sh=Sh.then(()=>this.printLog(`log`,e,...t).catch(e=>{console.error(`Error printing log:`,e)}))}flush(){return Sh}};const wh=(0,_.createContext)(void 0);function Th(e){let{directory:t,logger:r,onBuildStart:i,onBuildSuccess:a,onBuildError:o}=typeof e==`string`?{directory:e,logger:new Ch(async()=>{})}:e,s=(0,_.useMemo)(()=>n.resolveConfig(t),[t]),[c,l]=(0,_.useState)(void 0),[u,d]=(0,_.useState)(void 0),[f,p]=(0,_.useState)(`building`),m=(0,_.useRef)(i),h=(0,_.useRef)(a),g=(0,_.useRef)(o);return(0,_.useEffect)(()=>{m.current=i,h.current=a,g.current=o},[i,a,o]),(0,_.useEffect)(()=>{let e=new AbortController;return s.build({cwd:t,entry:s.entry,outdir:s.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{p(`building`),l(void 0),d(void 0),m.current?.()},onResult:e=>{`error`in e?(l(e.error),p(`error`),g.current?.(e.error)):(d(e),p(`success`),h.current?.(e))}}).catch(e=>{r.error(`system`,`error`,e),p(`error`),l(e),g.current?.(e)}),()=>{e.abort()}},[t]),(0,_.useMemo)(()=>({error:c,status:f,result:u,entry:s.entry,outdir:s.outdir}),[c,f,u,s.entry,s.outdir])}function Eh(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function Dh(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const Oh=100,kh=/^\.+(\\|\/)|^\.+$/,Ah=/[. ]+$/,jh=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,Mh=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,Nh=e=>e===`‍`,Ph=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,Fh=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let Ih;function Lh(){return Ih??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),Ih}function Rh(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(Eh().test(n)||[...n].some(e=>Mh.test(e)&&!Nh(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(Fh,` `),n.length>0&&(e=e.replaceAll(Ph,`$1`)),e=e.replace(Ah,``),e=e.replace(kh,n),e=e.replace(Eh(),n),e=e.replaceAll(jh,e=>Nh(e)?e:n),e.length===0&&(e=n),e=Dh().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=zh(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=zh(n,a)+i}}return e}function zh(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of Lh().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function Bh(e){return`${e}.lock`}function Vh(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function Hh(e,t={}){let n=Bh(e),r=process.pid.toString();try{return o.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(o.readFileSync(n,`utf8`),10)}catch{return o.unlinkSync(n),Hh(e,{...t,stale:0})}if(!Vh(i))try{return o.unlinkSync(n),Hh(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return Hh(e,{...t,stale:0});throw n}return!1}}async function Uh(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=b.resolve(e),i=0;for(;i<=n.retries;){if(Hh(r,n))return()=>Wh(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 Wh(e){let t=b.resolve(e),n=Bh(t);try{if(parseInt(o.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}o.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function Gh(e){let t=b.resolve(e),n=Bh(t);try{if(!o.existsSync(n))return{locked:!1};let e=o.readFileSync(n,`utf8`),t=parseInt(e,10);return Vh(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const Kh=e=>{o.mkdirSync(e,{recursive:!0})},qh=e=>{try{o.fdatasyncSync(e)}catch{}try{o.closeSync(e)}catch{}},Jh=e=>{try{let t=o.openSync(e,`r`);try{o.fsyncSync(t)}finally{o.closeSync(t)}}catch{}},Yh=(e,t)=>{let n=b.dirname(e);Kh(n);let r=b.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=o.openSync(r,`w`),o.writeFileSync(i,t,`utf-8`),qh(i),i=void 0,o.renameSync(r,e),Jh(e),Jh(n)}catch(e){if(i!==void 0)try{o.closeSync(i)}catch{}try{o.rmSync(r,{force:!0})}catch{}throw e}},Xh=(e,t)=>{let n=new Map,r,i=e=>{if(o.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(o.readFileSync(e,`utf-8`))},a=(e,t)=>{Yh(e,JSON.stringify(t,null,2))},s=async()=>{if(r)throw Error(`Index is already locked`);let t=b.join(e,`index.json`);Kh(e),o.existsSync(t)||o.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await Uh(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},c=async()=>{let t=b.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},l=async t=>{let n=b.join(e,`index.json`);a(n,t)},u=async t=>{let n=(await c()).ids[t];if(n)return b.join(e,n)},d=async t=>{let n=(await c()).ids[t];if(!n)return;let r=b.join(e,n);if(o.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(o.readFileSync(r,`utf-8`))},f=async n=>{let r=n[t],i=String(r),o=Rh(i,{replacement:`_`})+`.json`,u=await s();try{let t=await c();t.ids[i]=o,t.current=i;let r=b.join(e,o);a(r,n),await l(t)}finally{await u()}};return{async get(e){return await d(e)},async list(){if(!o.statSync(e,{throwIfNoEntry:!1}))return[];let t=await c(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=b.join(e,i),a=o.statSync(t,{throwIfNoEntry:!1});if(!a)continue;let s=Gh(t);n.push({key:r,locked:s.locked,pid:s.pid,mtime:a.mtimeMs})}return n.sort((e,t)=>t.mtime-e.mtime),n},async lock(r,i){if(n.has(r))throw Error(`Key "${r}" is already locked in this process`);let a=await u(r);if(!a){let t=Rh(r,{replacement:`_`})+`.json`,n=await s();try{let n=await c();n.ids[r]=t;let i=b.join(e,t);Kh(e),o.writeFileSync(i,JSON.stringify({}),`utf-8`),await l(n),a=i}finally{await n()}}if(i?.force){let e=Gh(a);if(e.locked&&e.pid&&e.pid!==process.pid)try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,100))}catch(t){t.code!==`ESRCH`&&console.warn(`Failed to kill process ${e.pid}:`,t.message)}}let p=await Uh(a,{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=b.join(e,n);try{o.rmSync(i,{force:!0}),Jh(e)}catch{}}}finally{await t()}},async release(){try{p()}finally{n.delete(r)}}}},dispose(){n.clear()}}},Zh=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,a,s,c=new Map,l=new Map,u=b.join(e,`index.json`),d=()=>{try{if(!o.statSync(u,{throwIfNoEntry:!1}))return{ids:{}};let e=o.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=b.join(e,n);try{let e=o.statSync(i,{throwIfNoEntry:!1}),a=l.get(n);if(!e){a&&(l.delete(n),f(t,void 0,!1));return}let s=e.mtimeMs,c=a?{locked:a.locked,pid:a.pid}:{locked:!1,pid:void 0};if((r||!a)&&(c=Gh(i)),!a||a.mtime!==s||a.locked!==c.locked||a.pid!==c.pid){let e;e=!a||a.mtime!==s?JSON.parse(o.readFileSync(i,`utf-8`)):a.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(a)return;try{o.mkdirSync(e,{recursive:!0})}catch{}a=o.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){a&&=(a.close(),void 0),s&&=(clearTimeout(s),void 0);for(let e of c.values())clearTimeout(e);c.clear(),l.clear()}}},dispose(){a&&=(a.close(),void 0),s&&=(clearTimeout(s),void 0);for(let e of c.values())clearTimeout(e);c.clear(),i.clear(),l.clear()}}};async function Qh({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=$h}){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,m.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 $h=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(m.isToolOrDynamicToolUIPart);return r.length===0||r.some(e=>t.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`)?!1:r.every(e=>e.state.startsWith(`output-`))},eg=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function tg(e){return typeof e==`object`&&e?.__blink_internal!==void 0}function ng(e){return typeof e.metadata==`object`&&e.metadata!==null&&`__blink_log`in e.metadata&&e.metadata.__blink_log===!0&&`level`in e.metadata&&`source`in e.metadata&&`message`in e.metadata}var rg=class{chatId;agent;chatStore;serializeMessage;filterMessages;onError;chat;loading=!1;streamingMessage;status=`idle`;queue=[];logQueue=[];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=Xh(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.onError=e.onError,this.watcher=Zh(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.locked?`streaming`:`idle`,r=this.chat.updated_at!==t?.updated_at||this.status!==n;this.chat=t,this.streamingMessage=void 0,this.status=n,r&&this.notifyListeners()}),this.chatStore.get(this.chatId).then(e=>{this.disposed||e&&(this.chat=e)}).catch(e=>{let t=e instanceof Error?e.message:String(e);this.onError?.(t)}).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=>!tg(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,loading:this.loading,queuedMessages:this.queue,queuedLogs:this.logQueue}}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 queueLogMessage({message:e,level:t,source:n}){let r=`(EDIT MODE NOTE) ${n===`agent`?`The agent`:"The `blink dev` CLI"} printed the following ${t}:\n\`\`\`\n${(0,l.stripVTControlCharacters)(e)}\n\`\`\`\n`,i={id:crypto.randomUUID(),created_at:new Date().toISOString(),role:`user`,parts:[{type:`text`,text:r}],metadata:{__blink_log:!0,level:t,source:n,message:e},mode:`edit`};this.logQueue.push(i),this.notifyListeners()}async flushLogQueue(e){if(this.logQueue.length===0)return;let t=[...this.logQueue];this.logQueue=[],await this.upsertMessages(t,e)}async sendMessages(e){if(this.status=`idle`,this.notifyListeners(),this.isProcessingQueue){this.queue.push(...e),this.notifyListeners();return}this.queue=e,this.processQueueOrRun()}async start(){this.status=`idle`,this.notifyListeners(),this.processQueueOrRun()}async stop(){this.status=`idle`,this.abortController?.abort(),this.notifyListeners()}async processQueueOrRun(){if(!this.agent){this.onError?.(`The agent is not available. Please wait for the build to succeed.`),this.queue=[];return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0;let e;try{e=await this.chatStore.lock(this.chatId),await this.flushLogQueue(e);let n=!0;for(;this.queue.length>0||n;)try{var t=Xs();n=!1;let r=new AbortController;this.abortController=r;let i=[...this.queue];this.queue=[],this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),i.length>0&&await this.upsertMessages(i,e);let a=this.chat.messages;this.filterMessages&&(a=a.filter(this.filterMessages)),a=a.map(e=>({...e,parts:e.parts.map(e=>!(0,m.isToolOrDynamicToolUIPart)(e)||e.input!==``?e:{...e,input:{}})})),t.u(await this.agent.lock.read());let o=performance.now(),s=await Qh({agent:this.agent.client,id:this.chatId,signal:r.signal,messages:a}),c=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)},l=s.getReader();r.signal.addEventListener(`abort`,()=>{l.cancel().catch(()=>{})},{once:!0});let u;try{for(;;){let{done:e,value:t}=await l.read();if(e||r.signal.aborted)break;u||=performance.now()-o,this.streamingMessage&&t.id!==this.streamingMessage.id&&await c(this.streamingMessage);let n={...t,metadata:{...typeof t.metadata==`object`&&t.metadata!==null?t.metadata:{},ttft:u}};this.streamingMessage=this.serializeMessage?this.serializeMessage(n):n,this.notifyListeners()}}finally{l.releaseLock()}this.streamingMessage&&await c(this.streamingMessage)}catch(e){t.e=e}finally{t.d()}}catch(e){let t=e instanceof Error?e.message:String(e);this.onError?.(t)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,this.status=`idle`,e&&(await this.flushLogQueue(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.stopStreaming()}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=[],this.logQueue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};function ig(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a,onError:o}=e,s=(0,_.useRef)(null),[c,l]=(0,_.useState)({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[],queuedLogs:[]});(0,_.useEffect)(()=>{s.current&&s.current.dispose();let e=new rg({chatId:t,chatsDirectory:r,serializeMessage:i,filterMessages:a,onError:o}),n=e.subscribe(e=>{l(e)});return l(e.getState()),s.current=e,()=>{n(),e.dispose(),s.current=null}},[t,r]),(0,_.useEffect)(()=>{s.current&&s.current.setAgent(n)},[n]);let u=(0,_.useCallback)(async e=>{s.current&&await s.current.sendMessages([e])},[]),d=(0,_.useCallback)(async e=>{s.current&&await s.current.upsertMessages([e])},[]),f=(0,_.useCallback)(async e=>{s.current&&await s.current.queueLogMessage(e)},[]),p=(0,_.useCallback)(()=>{s.current&&s.current.stopStreaming()},[]),m=(0,_.useCallback)(async()=>{s.current&&await s.current.resetChat()},[]),h=(0,_.useCallback)(()=>{s.current&&s.current.clearQueue()},[]),g=(0,_.useCallback)(async e=>{s.current&&await s.current.deleteMessages([e])},[]),v=(0,_.useCallback)(async()=>{s.current&&await s.current.start()},[]);return{...c,sendMessage:u,upsertMessage:d,queueLogMessage:f,stopStreaming:p,resetChat:m,clearQueue:h,deleteMessage:g,start:v}}function ag(e){return(0,f.join)(e,`.blink`,`devhook.txt`)}function og(e){return(0,p.existsSync)(ag(e))}function sg(e){let t=ag(e);if((0,p.existsSync)(t))return(0,p.readFileSync)(t,`utf-8`).trim()}function cg(e){let t=ag(e);if((0,p.mkdirSync)((0,f.dirname)(t),{recursive:!0}),(0,p.existsSync)(t))return(0,p.readFileSync)(t,`utf-8`);let n=crypto.randomUUID();return(0,p.writeFileSync)(t,n),n}const lg=(e,t)=>e.json({error:t},400),ug=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}},dg=()=>new t.Hono,fg=dg().get(`/:key`,async e=>{let{key:t,err:n}=ug(e);if(n)return lg(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?lg(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:lg(t,`Value must be a string`):lg(t,`Value is required`)}),async e=>{let{key:t,err:n}=ug(e);if(n)return lg(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}=ug(e);return n?lg(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})}),pg=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`}},mg=t.validator(`param`,e=>({id:e.id})),hg=dg().post(`/:key`,async e=>{let{key:t,err:n}=pg(e);return n?lg(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,mg,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,mg,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)):lg(e,`ID is required`)}).delete(`/:id/messages`,mg,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`,mg,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,mg,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,mg,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),gg=dg().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),_g=new t.Hono().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,fg).route(`/chat`,hg).route(`/otlp`,gg);var vg=/^(?:[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 yg(e){return typeof e==`string`&&vg.test(e)}var bg=yg;function xg(e){if(!bg(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 Sg=xg;const $=[];for(let e=0;e<256;++e)$.push((e+256).toString(16).slice(1));function Cg(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 wg(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 Tg=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,Eg=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;function Dg(e,t,n,r,i,a){let o=typeof n==`string`?wg(n):n,s=typeof r==`string`?Sg(r):r;if(typeof r==`string`&&(r=Sg(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 Cg(c)}function Og(e){return Array.isArray(e)?e=Buffer.from(e):typeof e==`string`&&(e=Buffer.from(e,`utf8`)),(0,u.createHash)(`sha1`).update(e).digest()}var kg=Og;function Ag(e,t,n,r){return Dg(80,kg,e,t,n,r)}Ag.DNS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,Ag.URL=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;var jg=Ag;function Mg(e){let n=(0,b.join)(e.dataDirectory,`chats`),r={},i=(0,b.join)(e.dataDirectory,`storage.json`);o.existsSync(i)&&(r=JSON.parse(o.readFileSync(i,`utf-8`)));let a=new Map,s=t=>{let r=a.get(t);return r||(r=new rg({chatId:t,chatsDirectory:n}),a.set(t,r)),r.setAgent(e.getAgent()),r},c={async upsert(e){let t=jg(JSON.stringify(e),jg.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=>eg(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,o.writeFileSync(i,JSON.stringify(r),`utf-8`),Promise.resolve()},delete(e){return delete r[e],o.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})}},u=(0,d.createServer)(t.createServerAdapter(e=>_g.fetch(e,{chat:c,store:l})));u.listen(e.port??0);let f=Xh(n,`id`);return{url:`http://127.0.0.1:${u.address().port}`,chatsDirectory:n,getChatManager:s,listChats:()=>f.list(),dispose:()=>{for(let e of a.values())e.dispose();a.clear(),f.dispose(),u.close()}}}function Ng({agent:e,capabilities:n,messages:r}){let[i,a]=(0,_.useState)(void 0),[o,s]=(0,_.useState)(!0),[c,l]=(0,_.useState)(void 0),u=(0,_.useRef)(c);(0,_.useEffect)(()=>{u.current=c},[c]);let[d,f]=(0,_.useState)(()=>t.lastUIOptions(r));(0,_.useEffect)(()=>{f(e=>{let n=t.lastUIOptions(r);return JSON.stringify(n)===JSON.stringify(e)?e:n})},[r]);let[p,m]=(0,_.useState)(void 0),h=(0,_.useCallback)((e,t)=>{if(!u.current)return!1;let n=u.current[e];return n?n.values.some(e=>e.id===t):!1},[]),g=(0,_.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,_.useEffect)(()=>{if(!d&&!c){m(void 0);return}g()},[d,c,g]);let v=(0,_.useRef)(void 0),y=(0,_.useRef)(void 0);(0,_.useEffect)(()=>{e!==y.current&&(y.current=e,l(void 0),m(void 0),a(void 0),s(!0),v.current=void 0)},[e]),(0,_.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,_.useCallback)((e,t)=>{g({[e]:t})},[g]);return{schema:c,options:p,setOption:b,loading:o,error:i}}function Pg(e){let t=(0,_.useRef)(e.onRequest);(0,_.useEffect)(()=>{t.current=e.onRequest},[e.onRequest]);let[n,r]=(0,_.useState)(`disconnected`);return(0,_.useEffect)(()=>{if(e.disabled||!e.id){r(`disconnected`);return}let n=!1,i,a,o=!1,s,c=(0,b.join)(e.directory,`.blink`,`devhook`);return(async()=>{try{s=await Uh(c,{stale:!0,retries:0})}catch(t){if(t&&typeof t==`object`&&`code`in t&&t.code===`ELOCKED`){let e=``;try{let t=Gh(c);t.locked&&t.pid&&(e=` (PID: ${t.pid})`)}catch{}console.error(Sf.red(`\nError: Another ${Sf.bold(`blink dev`)} process is already running in this directory${e}.`)),console.error(Sf.red(`Please stop the other process and try again.
142
+ `)),process.exit(1)}let n=t&&typeof t==`object`&&`message`in t?String(t.message):String(t);e.logger.error(`system`,Sf.yellow(`\nWarning: Failed to acquire devhook lock: ${n}`)),e.logger.error(`system`,Sf.yellow(`Continuing without lock. Multiple ${Sf.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 hd({baseURL:`https://blink.coder.com`}).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(t){e.logger.error(`system`,`Failed to release devhook lock:`,t)}}},[e.disabled,e.directory]),{id:e.id,url:e.id?`https://${e.id}.blink.host`:void 0,status:n}}var Fg=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}}})),Ig=e.__commonJSMin(((e,t)=>{let n=require(`fs`),r=require(`path`),i=require(`os`),a=require(`crypto`),o=Fg().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,`
143
143
  `);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,`
144
- `),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})),Lg=e.__toESM(Ig());async function Rg(e,t){let n=e;for(;n!==(0,f.dirname)(n);){let e=(0,f.join)(n,t);try{return await(0,h.stat)(e),e}catch{}n=(0,f.dirname)(n)}}function zg(e,t,n=`.env.local`){let[r,i]=(0,_.useState)({});return(0,_.useEffect)(()=>{let r,a=e=>{try{let t=(0,p.readFileSync)(e,`utf-8`),n=(0,Lg.parse)(t);i(n)}catch(e){t.error(`system`,`Error reading ${n}:`,e),i({})}};return Rg(e,n).then(e=>{if(!e){i({});return}a(e),r=(0,p.watch)(e,{persistent:!1},()=>{a(e)})}),()=>{r&&r.close()}},[e,n]),r}var Bg=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}},Vg=class extends Bg{};new Vg;function Hg(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 Ug(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 Wg(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 Gg(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 Kg(e,t){return Wg(e,t,``)}function qg(e,t){return Gg(e,t,``)}function Jg(e,t){return t.slice(0,Yg(e,t))}function Yg(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 Xg(e){let t;for(t=e.length-1;t>=0&&e[t].match(/\s/);t--);return e.substring(t+1)}function Zg(e){let t=e.match(/^\s*/);return t?t[0]:``}const Qg=`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}`,$g=RegExp(`[${Qg}]+|\\s+|[^${Qg}]`,`ug`);var e_=class extends Bg{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($g)||[];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)&&t_(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&t_(n,i,r,null),e}};new e_;function t_(e,t,n,r){if(t&&n){let i=Zg(t.value),a=Xg(t.value),o=Zg(n.value),s=Xg(n.value);if(e){let r=Hg(i,o);e.value=Gg(e.value,o,r),t.value=Kg(t.value,r),n.value=Kg(n.value,r)}if(r){let e=Ug(a,s);r.value=Wg(r.value,s,e),t.value=qg(t.value,e),n.value=qg(n.value,e)}}else if(n){if(e){let e=Zg(n.value);n.value=n.value.substring(e.length)}if(r){let e=Zg(r.value);r.value=r.value.substring(e.length)}}else if(e&&r){let n=Zg(r.value),i=Zg(t.value),a=Xg(t.value),o=Hg(n,i);t.value=Kg(t.value,o);let s=Ug(Kg(n,o),a);t.value=qg(t.value,s),r.value=Wg(r.value,n,s),e.value=Gg(e.value,n,n.slice(0,n.length-s.length))}else if(r){let e=Zg(r.value),n=Xg(t.value),i=Jg(n,e);t.value=qg(t.value,i)}else if(e){let n=Xg(e.value),r=Zg(t.value),i=Jg(n,r);t.value=Kg(t.value,i)}}var n_=class extends Bg{tokenize(e){let t=RegExp(`(\\r?\\n)|[${Qg}]+|[^\\S\\n\\r]+|[^${Qg}]`,`ug`);return e.match(t)||[]}};new n_;var r_=class extends Bg{constructor(){super(...arguments),this.tokenize=o_}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
144
+ `),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})),Lg=e.__toESM(Ig());async function Rg(e,t){let n=e;for(;n!==(0,f.dirname)(n);){let e=(0,f.join)(n,t);try{return await(0,h.stat)(e),e}catch{}n=(0,f.dirname)(n)}}function zg(e,t,n=`.env.local`){let[r,i]=(0,_.useState)({});return(0,_.useEffect)(()=>{let r,a=e=>{try{let t=(0,p.readFileSync)(e,`utf-8`),n=(0,Lg.parse)(t);i(n)}catch(e){t.error(`system`,`Error reading ${n}:`,e),i({})}};return Rg(e,n).then(e=>{if(!e){i({});return}a(e),r=(0,p.watch)(e,{persistent:!1},()=>{a(e)})}),()=>{r&&r.close()}},[e,n]),r}var Bg=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}},Vg=class extends Bg{};new Vg;function Hg(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 Ug(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 Wg(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 Gg(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 Kg(e,t){return Wg(e,t,``)}function qg(e,t){return Gg(e,t,``)}function Jg(e,t){return t.slice(0,Yg(e,t))}function Yg(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 Xg(e){let t;for(t=e.length-1;t>=0&&e[t].match(/\s/);t--);return e.substring(t+1)}function Zg(e){let t=e.match(/^\s*/);return t?t[0]:``}const Qg=`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}`,$g=RegExp(`[${Qg}]+|\\s+|[^${Qg}]`,`ug`);var e_=class extends Bg{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($g)||[];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)&&t_(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&t_(n,i,r,null),e}};new e_;function t_(e,t,n,r){if(t&&n){let i=Zg(t.value),a=Xg(t.value),o=Zg(n.value),s=Xg(n.value);if(e){let r=Hg(i,o);e.value=Gg(e.value,o,r),t.value=Kg(t.value,r),n.value=Kg(n.value,r)}if(r){let e=Ug(a,s);r.value=Wg(r.value,s,e),t.value=qg(t.value,e),n.value=qg(n.value,e)}}else if(n){if(e){let e=Zg(n.value);n.value=n.value.substring(e.length)}if(r){let e=Zg(r.value);r.value=r.value.substring(e.length)}}else if(e&&r){let n=Zg(r.value),i=Zg(t.value),a=Xg(t.value),o=Hg(n,i);t.value=Kg(t.value,o);let s=Ug(Kg(n,o),a);t.value=qg(t.value,s),r.value=Wg(r.value,n,s),e.value=Gg(e.value,n,n.slice(0,n.length-s.length))}else if(r){let e=Zg(r.value),n=Jg(Xg(t.value),e);t.value=qg(t.value,n)}else if(e){let n=Jg(Xg(e.value),Zg(t.value));t.value=Kg(t.value,n)}}var n_=class extends Bg{tokenize(e){let t=RegExp(`(\\r?\\n)|[${Qg}]+|[^\\S\\n\\r]+|[^${Qg}]`,`ug`);return e.match(t)||[]}};new n_;var r_=class extends Bg{constructor(){super(...arguments),this.tokenize=o_}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
145
145
  `))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(`
146
146
  `))&&(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
147
147
  `)&&(e=e.slice(0,-1)),t.endsWith(`
148
148
  `)&&(t=t.slice(0,-1))),super.equals(e,t,n)}};const i_=new r_;function a_(e,t,n){return i_.diff(e,t,n)}function o_(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
149
- `));let n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(let e=0;e<r.length;e++){let i=r[e];e%2&&!t.newlineIsToken?n[n.length-1]+=i:n.push(i)}return n}function s_(e){return e==`.`||e==`!`||e==`?`}var c_=class extends Bg{tokenize(e){let t=[],n=0;for(let r=0;r<e.length;r++){if(r==e.length-1){t.push(e.slice(n));break}if(s_(e[r])&&e[r+1].match(/\s/)){for(t.push(e.slice(n,r+1)),r=n=r+1;e[r+1]?.match(/\s/);)r++;t.push(e.slice(n,r+1)),n=r+1}}return t}};new c_;var l_=class extends Bg{tokenize(e){return e.split(/([{}:;,]|\s+)/)}};new l_;var u_=class extends Bg{constructor(){super(...arguments),this.tokenize=o_}get useLongestToken(){return!0}castInput(e,t){let{undefinedReplacement:n,stringifyReplacer:r=(e,t)=>t===void 0?n:t}=t;return typeof e==`string`?e:JSON.stringify(d_(e,null,null,r),null,` `)}equals(e,t,n){return super.equals(e.replace(/,([\r\n])/g,`$1`),t.replace(/,([\r\n])/g,`$1`),n)}};new u_;function d_(e,t,n,r,i){t||=[],n||=[],r&&(e=r(i===void 0?``:i,e));let a;for(a=0;a<t.length;a+=1)if(t[a]===e)return n[a];let o;if(Object.prototype.toString.call(e)===`[object Array]`){for(t.push(e),o=Array(e.length),n.push(o),a=0;a<e.length;a+=1)o[a]=d_(e[a],t,n,r,String(a));return t.pop(),n.pop(),o}if(e&&e.toJSON&&(e=e.toJSON()),typeof e==`object`&&e){t.push(e),o={},n.push(o);let i=[],s;for(s in e)Object.prototype.hasOwnProperty.call(e,s)&&i.push(s);for(i.sort(),a=0;a<i.length;a+=1)s=i[a],o[s]=d_(e[s],t,n,r,s);t.pop(),n.pop()}else o=e;return o}var f_=class extends Bg{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}};new f_;function p_(e,t,n,r,i,a,o){let s;s=o?typeof o==`function`?{callback:o}:o:{},s.context===void 0&&(s.context=4);let c=s.context;if(s.newlineIsToken)throw Error(`newlineIsToken may not be used with patch-generation functions, only with diffing functions`);if(s.callback){let{callback:e}=s;a_(n,r,Object.assign(Object.assign({},s),{callback:t=>{let n=l(t);e(n)}}))}else return l(a_(n,r,s));function l(n){if(!n)return;n.push({value:``,lines:[]});function r(e){return e.map(function(e){return` `+e})}let o=[],s=0,l=0,u=[],d=1,f=1;for(let e=0;e<n.length;e++){let t=n[e],i=t.lines||m_(t.value);if(t.lines=i,t.added||t.removed){if(!s){let t=n[e-1];s=d,l=f,t&&(u=c>0?r(t.lines.slice(-c)):[],s-=u.length,l-=u.length)}for(let e of i)u.push((t.added?`+`:`-`)+e);t.added?f+=i.length:d+=i.length}else{if(s)if(i.length<=c*2&&e<n.length-2)for(let e of r(i))u.push(e);else{let e=Math.min(i.length,c);for(let t of r(i.slice(0,e)))u.push(t);let t={oldStart:s,oldLines:d-s+e,newStart:l,newLines:f-l+e,lines:u};o.push(t),s=0,l=0,u=[]}d+=i.length,f+=i.length}}for(let e of o)for(let t=0;t<e.lines.length;t++)e.lines[t].endsWith(`
149
+ `));let n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(let e=0;e<r.length;e++){let i=r[e];e%2&&!t.newlineIsToken?n[n.length-1]+=i:n.push(i)}return n}function s_(e){return e==`.`||e==`!`||e==`?`}var c_=class extends Bg{tokenize(e){let t=[],n=0;for(let r=0;r<e.length;r++){if(r==e.length-1){t.push(e.slice(n));break}if(s_(e[r])&&e[r+1].match(/\s/)){for(t.push(e.slice(n,r+1)),r=n=r+1;e[r+1]?.match(/\s/);)r++;t.push(e.slice(n,r+1)),n=r+1}}return t}};new c_;var l_=class extends Bg{tokenize(e){return e.split(/([{}:;,]|\s+)/)}};new l_;var u_=class extends Bg{constructor(){super(...arguments),this.tokenize=o_}get useLongestToken(){return!0}castInput(e,t){let{undefinedReplacement:n,stringifyReplacer:r=(e,t)=>t===void 0?n:t}=t;return typeof e==`string`?e:JSON.stringify(d_(e,null,null,r),null,` `)}equals(e,t,n){return super.equals(e.replace(/,([\r\n])/g,`$1`),t.replace(/,([\r\n])/g,`$1`),n)}};new u_;function d_(e,t,n,r,i){t||=[],n||=[],r&&(e=r(i===void 0?``:i,e));let a;for(a=0;a<t.length;a+=1)if(t[a]===e)return n[a];let o;if(Object.prototype.toString.call(e)===`[object Array]`){for(t.push(e),o=Array(e.length),n.push(o),a=0;a<e.length;a+=1)o[a]=d_(e[a],t,n,r,String(a));return t.pop(),n.pop(),o}if(e&&e.toJSON&&(e=e.toJSON()),typeof e==`object`&&e){t.push(e),o={},n.push(o);let i=[],s;for(s in e)Object.prototype.hasOwnProperty.call(e,s)&&i.push(s);for(i.sort(),a=0;a<i.length;a+=1)s=i[a],o[s]=d_(e[s],t,n,r,s);t.pop(),n.pop()}else o=e;return o}var f_=class extends Bg{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}};new f_;function p_(e,t,n,r,i,a,o){let s;s=o?typeof o==`function`?{callback:o}:o:{},s.context===void 0&&(s.context=4);let c=s.context;if(s.newlineIsToken)throw Error(`newlineIsToken may not be used with patch-generation functions, only with diffing functions`);if(s.callback){let{callback:e}=s;a_(n,r,Object.assign(Object.assign({},s),{callback:t=>{e(l(t))}}))}else return l(a_(n,r,s));function l(n){if(!n)return;n.push({value:``,lines:[]});function r(e){return e.map(function(e){return` `+e})}let o=[],s=0,l=0,u=[],d=1,f=1;for(let e=0;e<n.length;e++){let t=n[e],i=t.lines||m_(t.value);if(t.lines=i,t.added||t.removed){if(!s){let t=n[e-1];s=d,l=f,t&&(u=c>0?r(t.lines.slice(-c)):[],s-=u.length,l-=u.length)}for(let e of i)u.push((t.added?`+`:`-`)+e);t.added?f+=i.length:d+=i.length}else{if(s)if(i.length<=c*2&&e<n.length-2)for(let e of r(i))u.push(e);else{let e=Math.min(i.length,c);for(let t of r(i.slice(0,e)))u.push(t);let t={oldStart:s,oldLines:d-s+e,newStart:l,newLines:f-l+e,lines:u};o.push(t),s=0,l=0,u=[]}d+=i.length,f+=i.length}}for(let e of o)for(let t=0;t<e.lines.length;t++)e.lines[t].endsWith(`
150
150
  `)?e.lines[t]=e.lines[t].slice(0,-1):(e.lines.splice(t+1,0,`\`),t++);return{oldFileName:e,newFileName:t,oldHeader:i,newHeader:a,hunks:o}}}function m_(e){let t=e.endsWith(`
151
151
  `),n=e.split(`
152
152
  `).map(e=>e+`
@@ -210,7 +210,7 @@ When making edits:
210
210
  If you want to create a new file, use:
211
211
  - A new file path, including dir name if needed
212
212
  - First edit: empty old_string and the new file's contents as new_string
213
- - Subsequent edits: normal edit operations on the created content`,inputSchema:y.z.object({file_path:y.z.string(),edits:y.z.array(y.z.object({old_string:y.z.string(),new_string:y.z.string(),expected_replacements:y.z.number()}))}),execute:async(t,n)=>{let r=await e(),i;try{i=(await r.request(`read_file`,{path:t.file_path},{signal:n.abortSignal})).content}catch{if(i=t.edits[0].new_string,t.edits.length>0&&t.edits[0].old_string===``)i=t.edits[0].new_string,t.edits.shift();else throw Error(`input is invalid: File does not exist and first edit is not for file creation.\nFile: ${t.file_path}`)}let a=i,o=[];for(let e of t.edits){let t=e.expected_replacements??1,n=e.old_string,r=e.new_string;if(n===r)throw Error(`input is invalid: old_string and new_string are identical.\nString: ${n}`);let i=x_(a,n);if(i===0)throw Error(`input is invalid: String to replace not found in file.\nString: ${n}`);if(i!==t)throw Error(`input is invalid: Found ${i} matches of the string to replace, but expected ${t}. The number of actual matches must equal the expected replacements. Please adjust your string to match or update the expected count.\nString: ${n}`)}for(let e of t.edits){let t=e.old_string,n=e.new_string;a=S_(a,t,n),o.push({old_string:t,new_string:n})}await r.request(`write_file`,{path:t.file_path,content:a},{signal:n.abortSignal});let s=p_(t.file_path,t.file_path,i,a);return{edits:o,file_path:t.file_path,structured_patch:s.hunks.map(e=>({old_start:e.oldStart,old_end:e.oldLines,new_start:e.newStart,new_end:e.newLines,lines:e.lines}))}}})),process_grep_output:__(({client:e})=>({description:`Search through the output of a running or completed process. **This is the PRIMARY tool for analyzing command output** - use this instead of piping commands to grep, tail, or re-running commands with filters.
213
+ - Subsequent edits: normal edit operations on the created content`,inputSchema:y.z.object({file_path:y.z.string(),edits:y.z.array(y.z.object({old_string:y.z.string(),new_string:y.z.string(),expected_replacements:y.z.number()}))}),execute:async(t,n)=>{let r=await e(),i;try{i=(await r.request(`read_file`,{path:t.file_path},{signal:n.abortSignal})).content}catch{if(i=t.edits[0].new_string,t.edits.length>0&&t.edits[0].old_string===``)i=t.edits[0].new_string,t.edits.shift();else throw Error(`input is invalid: File does not exist and first edit is not for file creation.\nFile: ${t.file_path}`)}let a=i,o=[];for(let e of t.edits){let t=e.expected_replacements??1,n=e.old_string;if(n===e.new_string)throw Error(`input is invalid: old_string and new_string are identical.\nString: ${n}`);let r=x_(a,n);if(r===0)throw Error(`input is invalid: String to replace not found in file.\nString: ${n}`);if(r!==t)throw Error(`input is invalid: Found ${r} matches of the string to replace, but expected ${t}. The number of actual matches must equal the expected replacements. Please adjust your string to match or update the expected count.\nString: ${n}`)}for(let e of t.edits){let t=e.old_string,n=e.new_string;a=S_(a,t,n),o.push({old_string:t,new_string:n})}await r.request(`write_file`,{path:t.file_path,content:a},{signal:n.abortSignal});let s=p_(t.file_path,t.file_path,i,a);return{edits:o,file_path:t.file_path,structured_patch:s.hunks.map(e=>({old_start:e.oldStart,old_end:e.oldLines,new_start:e.newStart,new_end:e.newLines,lines:e.lines}))}}})),process_grep_output:__(({client:e})=>({description:`Search through the output of a running or completed process. **This is the PRIMARY tool for analyzing command output** - use this instead of piping commands to grep, tail, or re-running commands with filters.
214
214
 
215
215
  Use this for:
216
216
  - Finding test failures and error messages
@@ -1982,7 +1982,7 @@ agent.serve();`,"package.json.hbs":`{
1982
1982
  </form>
1983
1983
  <script>document.getElementById('f').submit()<\/script>
1984
1984
  </body>
1985
- </html>`;return new Response(l,{headers:{"Content-Type":`text/html`}})}));return new Promise((e,t)=>{a.on(`error`,t),a.listen(0,`127.0.0.1`,()=>{let n=a.address();if(!n||typeof n==`string`){t(Error(`Failed to get server address`));return}i=`http://127.0.0.1:${n.port}`,e(i)})})}const T_=y.z.enum([`read`,`write`]),E_=y.z.union([y.z.literal(`branch_protection_rule`).describe(`Branch protection rule created, edited, or deleted`),y.z.literal(`check_run`).describe(`Check run created, completed, or requested`),y.z.literal(`check_suite`).describe(`Check suite completed or requested`),y.z.literal(`code_scanning_alert`).describe(`Code scanning alert created, fixed, or reopened`),y.z.literal(`commit_comment`).describe(`Commit comment created`),y.z.literal(`create`).describe(`Branch or tag created`),y.z.literal(`delete`).describe(`Branch or tag deleted`),y.z.literal(`deployment`).describe(`Deployment created`),y.z.literal(`deployment_status`).describe(`Deployment status created`),y.z.literal(`deployment_protection_rule`).describe(`Deployment protection rule requested`),y.z.literal(`discussion`).describe(`Discussion created, edited, or deleted`),y.z.literal(`discussion_comment`).describe(`Discussion comment created, edited, or deleted`),y.z.literal(`fork`).describe(`Repository forked`),y.z.literal(`gollum`).describe(`Wiki page created or updated`),y.z.literal(`issue_comment`).describe(`Issue comment created, edited, or deleted`),y.z.literal(`issues`).describe(`Issue opened, edited, closed, or labeled`),y.z.literal(`label`).describe(`Label created, edited, or deleted`),y.z.literal(`member`).describe(`Collaborator added, removed, or edited`),y.z.literal(`membership`).describe(`Team membership added or removed`),y.z.literal(`meta`).describe(`GitHub App webhook configuration changed`),y.z.literal(`milestone`).describe(`Milestone created, closed, or deleted`),y.z.literal(`organization`).describe(`Organization member added, removed, or invited`),y.z.literal(`org_block`).describe(`Organization blocked or unblocked a user`),y.z.literal(`package`).describe(`Package published or updated`),y.z.literal(`page_build`).describe(`GitHub Pages site built`),y.z.literal(`project`).describe(`Project created, updated, or deleted`),y.z.literal(`project_card`).describe(`Project card created, edited, or deleted`),y.z.literal(`project_column`).describe(`Project column created, updated, or deleted`),y.z.literal(`public`).describe(`Repository visibility changed to public`),y.z.literal(`pull_request`).describe(`Pull request opened, closed, edited, or synchronized`),y.z.literal(`pull_request_review`).describe(`Pull request review submitted, edited, or dismissed`),y.z.literal(`pull_request_review_comment`).describe(`Pull request review comment created or edited`),y.z.literal(`pull_request_review_thread`).describe(`Pull request review thread resolved or unresolved`),y.z.literal(`push`).describe(`Git push to a repository`),y.z.literal(`registry_package`).describe(`Registry package published or updated`),y.z.literal(`release`).describe(`Release published or edited`),y.z.literal(`repository`).describe(`Repository created, deleted, archived, or publicized`),y.z.literal(`repository_dispatch`).describe(`Custom webhook event triggered`),y.z.literal(`secret_scanning_alert`).describe(`Secret scanning alert created or resolved`),y.z.literal(`security_and_analysis`).describe(`Security features enabled or disabled`),y.z.literal(`star`).describe(`Repository starred or unstarred`),y.z.literal(`status`).describe(`Commit status created`),y.z.literal(`team`).describe(`Team created, deleted, or edited`),y.z.literal(`team_add`).describe(`Repository added to team`),y.z.literal(`watch`).describe(`User started watching repository`),y.z.literal(`workflow_dispatch`).describe(`Workflow manually triggered`),y.z.literal(`workflow_job`).describe(`Workflow job queued, started, or completed`),y.z.literal(`workflow_run`).describe(`Workflow run requested or completed`)]),D_=y.z.object({name:y.z.string().optional().describe(`The name of the GitHub App. Leave blank to let the user name it on GitHub.`),url:y.z.url().describe(`The homepage URL of the GitHub App. If unknown, set to https://blink.so.`),description:y.z.string().optional().describe(`The description of the GitHub App.`),public:y.z.boolean().optional().describe(`Whether the GitHub App is public. Always default to false unless the user explicitly requests otherwise.`),hook_attributes:y.z.object({url:y.z.url(),active:y.z.boolean().optional().default(!0)}).optional().describe(`The webhook configuration for the GitHub App.`),callback_urls:y.z.array(y.z.url()).max(10).optional().describe(`Callback URLs for the GitHub App after the user authenticates with GitHub.`),setup_url:y.z.url().optional().describe(`The URL to redirect the user to after they install the GitHub App.`),setup_on_update:y.z.boolean().optional().describe(`Whether to redirect the user to the setup URL after an update to the installed app.`),request_oauth_on_install:y.z.boolean().optional().describe(`Whether to request OAuth on install.`),default_events:y.z.array(E_).optional().describe(`Webhook events sent to the webhook URL.`),default_permissions:y.z.record(y.z.string(),T_).optional().describe(`Repository and organization permissions for the GitHub App. Available permissions: actions (GitHub Actions workflows), administration (repository settings), checks (check runs), contents (repository code), deployments, environments, issues, metadata (always granted), packages, pages, pull_requests, repository_hooks (webhooks), repository_projects, secret_scanning_alerts, secrets (Actions secrets), security_events (code scanning/Dependabot), single_file, statuses (commit statuses), vulnerability_alerts (Dependabot), workflows (workflow files), members (collaborators). Values can be 'read' or 'write'.`)});function O_(e){return`https://api.slack.com/apps?new_app=1&manifest_json=${encodeURIComponent(JSON.stringify(e))}`}const k_=y.z.union([y.z.literal(`app_mention`).describe(`Bot is @mentioned in a channel or conversation. Requires scope: app_mentions:read`),y.z.literal(`app_home_opened`).describe(`User opened the app's Home tab. No additional scope required beyond bot token`),y.z.literal(`app_installed`).describe(`App was installed to a workspace. No additional scope required beyond bot token`),y.z.literal(`app_uninstalled`).describe(`App was uninstalled from a workspace. No additional scope required beyond bot token`),y.z.literal(`assistant_thread_context_changed`).describe(`Context changed in an assistant thread. Requires scope: assistant:write`),y.z.literal(`assistant_thread_started`).describe(`New assistant thread was started. Requires scope: assistant:write`),y.z.literal(`channel_archive`).describe(`Public channel was archived. Requires scope: channels:read`),y.z.literal(`channel_created`).describe(`Public channel was created. Requires scope: channels:read`),y.z.literal(`channel_deleted`).describe(`Public channel was deleted. Requires scope: channels:read`),y.z.literal(`channel_rename`).describe(`Public channel was renamed. Requires scope: channels:read`),y.z.literal(`channel_unarchive`).describe(`Public channel was unarchived. Requires scope: channels:read`),y.z.literal(`dnd_updated_user`).describe(`User's Do Not Disturb settings changed. Requires scope: dnd:read`),y.z.literal(`email_domain_changed`).describe(`Workspace's email domain changed. Requires scope: team:read`),y.z.literal(`emoji_changed`).describe(`Custom emoji was added or changed. Requires scope: emoji:read`),y.z.literal(`file_change`).describe(`File was changed. Requires scope: files:read`),y.z.literal(`file_created`).describe(`File was created. Requires scope: files:read`),y.z.literal(`file_deleted`).describe(`File was deleted. Requires scope: files:read`),y.z.literal(`file_public`).describe(`File was made public. Requires scope: files:read`),y.z.literal(`file_shared`).describe(`File was shared. Requires scope: files:read`),y.z.literal(`file_unshared`).describe(`File was unshared. Requires scope: files:read`),y.z.literal(`group_archive`).describe(`Private channel was archived. Requires scope: groups:read`),y.z.literal(`group_deleted`).describe(`Private channel was deleted. Requires scope: groups:read`),y.z.literal(`group_rename`).describe(`Private channel was renamed. Requires scope: groups:read`),y.z.literal(`group_unarchive`).describe(`Private channel was unarchived. Requires scope: groups:read`),y.z.literal(`link_shared`).describe(`Link from a registered domain was shared. Requires scope: links:read`),y.z.literal(`member_joined_channel`).describe(`User joined a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),y.z.literal(`member_left_channel`).describe(`User left a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),y.z.literal(`message.channels`).describe(`Message was posted in a public channel. Requires scope: channels:history`),y.z.literal(`message.groups`).describe(`Message was posted in a private channel. Requires scope: groups:history`),y.z.literal(`message.im`).describe(`Message was posted in a direct message. Requires scope: im:history`),y.z.literal(`message.mpim`).describe(`Message was posted in a multi-party direct message. Requires scope: mpim:history`),y.z.literal(`pin_added`).describe(`Item was pinned in a channel. Requires scope: pins:read`),y.z.literal(`pin_removed`).describe(`Item was unpinned from a channel. Requires scope: pins:read`),y.z.literal(`reaction_added`).describe(`Reaction was added to a message. Requires scope: reactions:read`),y.z.literal(`reaction_removed`).describe(`Reaction was removed from a message. Requires scope: reactions:read`),y.z.literal(`team_join`).describe(`New user joined the workspace. Requires scope: users:read`),y.z.literal(`user_change`).describe(`User's profile or settings changed. Requires scope: users:read`)]),A_=y.z.union([y.z.literal(`app_mentions:read`).describe(`Read messages that directly mention the bot. Required for: app_mention event`),y.z.literal(`assistant:write`).describe(`Update bot status and write assistant messages. This should *always* be included for Slack bots. It improves the UX dramatically for users. Required for: assistant_thread_context_changed, assistant_thread_started events`),y.z.literal(`channels:history`).describe(`Read message history in public channels the bot has access to. Required for: message.channels event`),y.z.literal(`channels:join`).describe(`Join public channels`),y.z.literal(`channels:manage`).describe(`Manage public channels (archive, rename, etc.)`),y.z.literal(`channels:read`).describe(`View basic information about public channels. Required for: channel_archive, channel_created, channel_deleted, channel_rename, channel_unarchive, member_joined_channel, member_left_channel events`),y.z.literal(`chat:write`).describe(`Send messages as the bot`),y.z.literal(`chat:write.customize`).describe(`Send messages with a customized username and avatar`),y.z.literal(`chat:write.public`).describe(`Send messages to public channels without joining`),y.z.literal(`commands`).describe(`Add and use slash commands`),y.z.literal(`dnd:read`).describe(`View Do Not Disturb settings for users. Required for: dnd_updated_user event`),y.z.literal(`emoji:read`).describe(`View custom emoji in the workspace. Required for: emoji_changed event`),y.z.literal(`files:read`).describe(`View files shared in channels and conversations. Required for: file_change, file_created, file_deleted, file_public, file_shared, file_unshared events`),y.z.literal(`files:write`).describe(`Upload, edit, and delete files`),y.z.literal(`groups:history`).describe(`Read message history in private channels the bot has access to. Required for: message.groups event`),y.z.literal(`groups:read`).describe(`View basic information about private channels. Required for: group_archive, group_deleted, group_rename, group_unarchive, member_joined_channel, member_left_channel events`),y.z.literal(`groups:write`).describe(`Manage private channels (archive, rename, create, etc.)`),y.z.literal(`im:history`).describe(`Read message history in direct messages with the bot. Required for: message.im event`),y.z.literal(`im:read`).describe(`View basic information about direct messages with the bot`),y.z.literal(`im:write`).describe(`Start and manage direct messages with users`),y.z.literal(`links:read`).describe(`View URLs in messages. Required for: link_shared event`),y.z.literal(`links:write`).describe(`Show previews of URLs (unfurling)`),y.z.literal(`metadata.message:read`).describe(`Read message metadata`),y.z.literal(`mpim:history`).describe(`Read message history in multi-party direct messages. Required for: message.mpim event`),y.z.literal(`mpim:read`).describe(`View basic information about multi-party direct messages`),y.z.literal(`mpim:write`).describe(`Start and manage multi-party direct messages`),y.z.literal(`pins:read`).describe(`View pinned items in channels and conversations. Required for: pin_added, pin_removed events`),y.z.literal(`pins:write`).describe(`Pin and unpin items in channels and conversations`),y.z.literal(`reactions:read`).describe(`View emoji reactions on messages. Required for: reaction_added, reaction_removed events`),y.z.literal(`reactions:write`).describe(`Add and remove emoji reactions to messages`),y.z.literal(`reminders:read`).describe(`View reminders created by the bot`),y.z.literal(`reminders:write`).describe(`Create, update, and delete reminders`),y.z.literal(`team:read`).describe(`View workspace name, domain, and other basic information. Required for: email_domain_changed event`),y.z.literal(`usergroups:read`).describe(`View user groups and their members`),y.z.literal(`usergroups:write`).describe(`Create, update, and archive user groups`),y.z.literal(`users.profile:read`).describe(`View profile information about users`),y.z.literal(`users:read`).describe(`View users in the workspace. Required for: team_join, user_change events`),y.z.literal(`users:read.email`).describe(`View email addresses of users in the workspace`),y.z.literal(`users:write`).describe(`Set presence and status for the bot user`)]),j_=y.z.union([y.z.literal(`channels:history`).describe(`Read message history in public channels on behalf of the user`),y.z.literal(`channels:read`).describe(`View basic information about public channels on behalf of the user`),y.z.literal(`channels:write`).describe(`Manage public channels on behalf of the user`),y.z.literal(`chat:write`).describe(`Send messages on behalf of the user`),y.z.literal(`emoji:read`).describe(`View custom emoji on behalf of the user`),y.z.literal(`files:read`).describe(`View files on behalf of the user`),y.z.literal(`files:write`).describe(`Upload, edit, and delete files on behalf of the user`),y.z.literal(`groups:history`).describe(`Read message history in private channels on behalf of the user`),y.z.literal(`groups:read`).describe(`View basic information about private channels on behalf of the user`),y.z.literal(`groups:write`).describe(`Manage private channels on behalf of the user`),y.z.literal(`im:history`).describe(`Read direct message history on behalf of the user`),y.z.literal(`im:read`).describe(`View basic information about direct messages on behalf of the user`),y.z.literal(`im:write`).describe(`Manage direct messages on behalf of the user`),y.z.literal(`links:read`).describe(`View URLs in messages on behalf of the user`),y.z.literal(`links:write`).describe(`Show URL previews on behalf of the user`),y.z.literal(`mpim:history`).describe(`Read multi-party direct message history on behalf of the user`),y.z.literal(`mpim:read`).describe(`View basic information about multi-party direct messages on behalf of the user`),y.z.literal(`mpim:write`).describe(`Manage multi-party direct messages on behalf of the user`),y.z.literal(`pins:read`).describe(`View pinned items on behalf of the user`),y.z.literal(`pins:write`).describe(`Pin and unpin items on behalf of the user`),y.z.literal(`reactions:read`).describe(`View emoji reactions on behalf of the user`),y.z.literal(`reactions:write`).describe(`Add and remove emoji reactions on behalf of the user`),y.z.literal(`reminders:read`).describe(`View reminders on behalf of the user`),y.z.literal(`reminders:write`).describe(`Create, update, and delete reminders on behalf of the user`),y.z.literal(`search:read`).describe(`Search messages and files on behalf of the user`),y.z.literal(`stars:read`).describe(`View starred items on behalf of the user`),y.z.literal(`stars:write`).describe(`Star and unstar items on behalf of the user`),y.z.literal(`team:read`).describe(`View workspace information on behalf of the user`),y.z.literal(`usergroups:read`).describe(`View user groups on behalf of the user`),y.z.literal(`usergroups:write`).describe(`Manage user groups on behalf of the user`),y.z.literal(`users.profile:read`).describe(`View user profile information on behalf of the user`),y.z.literal(`users.profile:write`).describe(`Edit the user's profile information`),y.z.literal(`users:read`).describe(`View users in the workspace on behalf of the user`),y.z.literal(`users:read.email`).describe(`View email addresses on behalf of the user`),y.z.literal(`users:write`).describe(`Set presence for the user`)]),M_=y.z.object({display_information:y.z.object({name:y.z.string().describe(`The name of the Slack app.`),description:y.z.string().optional().describe(`A short description of the app.`),background_color:y.z.string().regex(/^#[0-9A-Fa-f]{6}$/).optional().describe(`Background color for the app in hex format (e.g., #4A154B).`),long_description:y.z.string().optional().describe(`A longer description of the app.`)}).describe(`Display information for the Slack app.`),features:y.z.object({bot_user:y.z.object({display_name:y.z.string().describe(`The display name for the bot user.`),always_online:y.z.boolean().optional().default(!0).describe(`Whether the bot always appears online.`)}).optional().describe(`Configuration for the bot user.`),app_home:y.z.object({home_tab_enabled:y.z.boolean().optional().describe(`Enable the Home tab.`),messages_tab_enabled:y.z.boolean().optional().describe(`Enable the Messages tab.`),messages_tab_read_only_enabled:y.z.boolean().optional().describe(`Make the Messages tab read-only.`)}).optional().describe(`Configuration for the App Home. If specified, the "bot" scope is *REQUIRED*.`),assistant_view:y.z.object({assistant_description:y.z.string().optional().describe(`Description for the assistant view.`)}).optional().describe(`Configuration for the assistant view.`),slash_commands:y.z.array(y.z.object({command:y.z.string().regex(/^\//).describe(`The command (must start with /).`),description:y.z.string().describe(`Description of the command.`),usage_hint:y.z.string().optional().describe(`Usage hint for the command.`),should_escape:y.z.boolean().optional().describe(`Whether to escape special characters.`)})).optional().describe(`Slash commands for the app.`),unfurl_domains:y.z.array(y.z.string()).optional().describe(`Domains for link unfurling.`)}).optional().describe(`Features configuration for the Slack app.`),oauth_config:y.z.object({redirect_urls:y.z.array(y.z.url()).optional().describe(`OAuth redirect URLs.`),scopes:y.z.object({bot:y.z.array(y.z.union([A_,y.z.string()])).optional().describe(`Bot scopes required by the app. Each scope defines specific permissions for what the bot can do.`),user:y.z.array(y.z.union([j_,y.z.string()])).optional().describe(`User scopes required by the app. Each scope defines specific permissions for actions performed on behalf of users.`)}).describe(`OAuth scopes for bot and user tokens.`)}).describe(`OAuth configuration for the Slack app.`),settings:y.z.object({event_subscriptions:y.z.object({request_url:y.z.string().url().describe(`The webhook URL for event subscriptions.`),bot_events:y.z.array(y.z.union([k_,y.z.string()])).optional().describe(`Bot events to subscribe to. Each event notifies your app when specific actions occur in the workspace.`)}).optional().describe(`Event subscriptions configuration.`),interactivity:y.z.object({is_enabled:y.z.boolean().describe(`Enable interactivity.`),request_url:y.z.string().url().describe(`The webhook URL for interactive components.`),message_menu_options_url:y.z.string().url().optional().describe(`URL for message menu options.`)}).optional().describe(`Interactivity configuration.`),org_deploy_enabled:y.z.boolean().optional().default(!1).describe(`Enable organization-wide deployment.`),socket_mode_enabled:y.z.boolean().optional().default(!1).describe(`Enable Socket Mode.`),token_rotation_enabled:y.z.boolean().optional().default(!1).describe(`Enable automatic token rotation.`)}).optional().describe(`Settings for the Slack app.`)});function N_(e){let n=new t.Agent,r,i;return n.on(`chat`,async({id:i,messages:a,abortSignal:o})=>{let s=a.findLastIndex(e=>!e.metadata||typeof e.metadata!=`object`?!1:e.metadata.__blink_mode===`run`);a.splice(s??0,0,{id:crypto.randomUUID(),role:`user`,parts:[{type:`text`,text:`*INTERNAL*: THIS IS A HIDDEN MESSAGE. YOU ARE IN EDIT MODE.
1985
+ </html>`;return new Response(l,{headers:{"Content-Type":`text/html`}})}));return new Promise((e,t)=>{a.on(`error`,t),a.listen(0,`127.0.0.1`,()=>{let n=a.address();if(!n||typeof n==`string`){t(Error(`Failed to get server address`));return}i=`http://127.0.0.1:${n.port}`,e(i)})})}const T_=y.z.enum([`read`,`write`]),E_=y.z.union([y.z.literal(`branch_protection_rule`).describe(`Branch protection rule created, edited, or deleted`),y.z.literal(`check_run`).describe(`Check run created, completed, or requested`),y.z.literal(`check_suite`).describe(`Check suite completed or requested`),y.z.literal(`code_scanning_alert`).describe(`Code scanning alert created, fixed, or reopened`),y.z.literal(`commit_comment`).describe(`Commit comment created`),y.z.literal(`create`).describe(`Branch or tag created`),y.z.literal(`delete`).describe(`Branch or tag deleted`),y.z.literal(`deployment`).describe(`Deployment created`),y.z.literal(`deployment_status`).describe(`Deployment status created`),y.z.literal(`deployment_protection_rule`).describe(`Deployment protection rule requested`),y.z.literal(`discussion`).describe(`Discussion created, edited, or deleted`),y.z.literal(`discussion_comment`).describe(`Discussion comment created, edited, or deleted`),y.z.literal(`fork`).describe(`Repository forked`),y.z.literal(`gollum`).describe(`Wiki page created or updated`),y.z.literal(`issue_comment`).describe(`Issue comment created, edited, or deleted`),y.z.literal(`issues`).describe(`Issue opened, edited, closed, or labeled`),y.z.literal(`label`).describe(`Label created, edited, or deleted`),y.z.literal(`member`).describe(`Collaborator added, removed, or edited`),y.z.literal(`membership`).describe(`Team membership added or removed`),y.z.literal(`meta`).describe(`GitHub App webhook configuration changed`),y.z.literal(`milestone`).describe(`Milestone created, closed, or deleted`),y.z.literal(`organization`).describe(`Organization member added, removed, or invited`),y.z.literal(`org_block`).describe(`Organization blocked or unblocked a user`),y.z.literal(`package`).describe(`Package published or updated`),y.z.literal(`page_build`).describe(`GitHub Pages site built`),y.z.literal(`project`).describe(`Project created, updated, or deleted`),y.z.literal(`project_card`).describe(`Project card created, edited, or deleted`),y.z.literal(`project_column`).describe(`Project column created, updated, or deleted`),y.z.literal(`public`).describe(`Repository visibility changed to public`),y.z.literal(`pull_request`).describe(`Pull request opened, closed, edited, or synchronized`),y.z.literal(`pull_request_review`).describe(`Pull request review submitted, edited, or dismissed`),y.z.literal(`pull_request_review_comment`).describe(`Pull request review comment created or edited`),y.z.literal(`pull_request_review_thread`).describe(`Pull request review thread resolved or unresolved`),y.z.literal(`push`).describe(`Git push to a repository`),y.z.literal(`registry_package`).describe(`Registry package published or updated`),y.z.literal(`release`).describe(`Release published or edited`),y.z.literal(`repository`).describe(`Repository created, deleted, archived, or publicized`),y.z.literal(`repository_dispatch`).describe(`Custom webhook event triggered`),y.z.literal(`secret_scanning_alert`).describe(`Secret scanning alert created or resolved`),y.z.literal(`security_and_analysis`).describe(`Security features enabled or disabled`),y.z.literal(`star`).describe(`Repository starred or unstarred`),y.z.literal(`status`).describe(`Commit status created`),y.z.literal(`team`).describe(`Team created, deleted, or edited`),y.z.literal(`team_add`).describe(`Repository added to team`),y.z.literal(`watch`).describe(`User started watching repository`),y.z.literal(`workflow_dispatch`).describe(`Workflow manually triggered`),y.z.literal(`workflow_job`).describe(`Workflow job queued, started, or completed`),y.z.literal(`workflow_run`).describe(`Workflow run requested or completed`)]),D_=y.z.object({name:y.z.string().optional().describe(`The name of the GitHub App. Leave blank to let the user name it on GitHub.`),url:y.z.url().describe(`The homepage URL of the GitHub App. If unknown, set to https://blink.coder.com.`),description:y.z.string().optional().describe(`The description of the GitHub App.`),public:y.z.boolean().optional().describe(`Whether the GitHub App is public. Always default to false unless the user explicitly requests otherwise.`),hook_attributes:y.z.object({url:y.z.url(),active:y.z.boolean().optional().default(!0)}).optional().describe(`The webhook configuration for the GitHub App.`),callback_urls:y.z.array(y.z.url()).max(10).optional().describe(`Callback URLs for the GitHub App after the user authenticates with GitHub.`),setup_url:y.z.url().optional().describe(`The URL to redirect the user to after they install the GitHub App.`),setup_on_update:y.z.boolean().optional().describe(`Whether to redirect the user to the setup URL after an update to the installed app.`),request_oauth_on_install:y.z.boolean().optional().describe(`Whether to request OAuth on install.`),default_events:y.z.array(E_).optional().describe(`Webhook events sent to the webhook URL.`),default_permissions:y.z.record(y.z.string(),T_).optional().describe(`Repository and organization permissions for the GitHub App. Available permissions: actions (GitHub Actions workflows), administration (repository settings), checks (check runs), contents (repository code), deployments, environments, issues, metadata (always granted), packages, pages, pull_requests, repository_hooks (webhooks), repository_projects, secret_scanning_alerts, secrets (Actions secrets), security_events (code scanning/Dependabot), single_file, statuses (commit statuses), vulnerability_alerts (Dependabot), workflows (workflow files), members (collaborators). Values can be 'read' or 'write'.`)});function O_(e){return`https://api.slack.com/apps?new_app=1&manifest_json=${encodeURIComponent(JSON.stringify(e))}`}const k_=y.z.union([y.z.literal(`app_mention`).describe(`Bot is @mentioned in a channel or conversation. Requires scope: app_mentions:read`),y.z.literal(`app_home_opened`).describe(`User opened the app's Home tab. No additional scope required beyond bot token`),y.z.literal(`app_installed`).describe(`App was installed to a workspace. No additional scope required beyond bot token`),y.z.literal(`app_uninstalled`).describe(`App was uninstalled from a workspace. No additional scope required beyond bot token`),y.z.literal(`assistant_thread_context_changed`).describe(`Context changed in an assistant thread. Requires scope: assistant:write`),y.z.literal(`assistant_thread_started`).describe(`New assistant thread was started. Requires scope: assistant:write`),y.z.literal(`channel_archive`).describe(`Public channel was archived. Requires scope: channels:read`),y.z.literal(`channel_created`).describe(`Public channel was created. Requires scope: channels:read`),y.z.literal(`channel_deleted`).describe(`Public channel was deleted. Requires scope: channels:read`),y.z.literal(`channel_rename`).describe(`Public channel was renamed. Requires scope: channels:read`),y.z.literal(`channel_unarchive`).describe(`Public channel was unarchived. Requires scope: channels:read`),y.z.literal(`dnd_updated_user`).describe(`User's Do Not Disturb settings changed. Requires scope: dnd:read`),y.z.literal(`email_domain_changed`).describe(`Workspace's email domain changed. Requires scope: team:read`),y.z.literal(`emoji_changed`).describe(`Custom emoji was added or changed. Requires scope: emoji:read`),y.z.literal(`file_change`).describe(`File was changed. Requires scope: files:read`),y.z.literal(`file_created`).describe(`File was created. Requires scope: files:read`),y.z.literal(`file_deleted`).describe(`File was deleted. Requires scope: files:read`),y.z.literal(`file_public`).describe(`File was made public. Requires scope: files:read`),y.z.literal(`file_shared`).describe(`File was shared. Requires scope: files:read`),y.z.literal(`file_unshared`).describe(`File was unshared. Requires scope: files:read`),y.z.literal(`group_archive`).describe(`Private channel was archived. Requires scope: groups:read`),y.z.literal(`group_deleted`).describe(`Private channel was deleted. Requires scope: groups:read`),y.z.literal(`group_rename`).describe(`Private channel was renamed. Requires scope: groups:read`),y.z.literal(`group_unarchive`).describe(`Private channel was unarchived. Requires scope: groups:read`),y.z.literal(`link_shared`).describe(`Link from a registered domain was shared. Requires scope: links:read`),y.z.literal(`member_joined_channel`).describe(`User joined a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),y.z.literal(`member_left_channel`).describe(`User left a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),y.z.literal(`message.channels`).describe(`Message was posted in a public channel. Requires scope: channels:history`),y.z.literal(`message.groups`).describe(`Message was posted in a private channel. Requires scope: groups:history`),y.z.literal(`message.im`).describe(`Message was posted in a direct message. Requires scope: im:history`),y.z.literal(`message.mpim`).describe(`Message was posted in a multi-party direct message. Requires scope: mpim:history`),y.z.literal(`pin_added`).describe(`Item was pinned in a channel. Requires scope: pins:read`),y.z.literal(`pin_removed`).describe(`Item was unpinned from a channel. Requires scope: pins:read`),y.z.literal(`reaction_added`).describe(`Reaction was added to a message. Requires scope: reactions:read`),y.z.literal(`reaction_removed`).describe(`Reaction was removed from a message. Requires scope: reactions:read`),y.z.literal(`team_join`).describe(`New user joined the workspace. Requires scope: users:read`),y.z.literal(`user_change`).describe(`User's profile or settings changed. Requires scope: users:read`)]),A_=y.z.union([y.z.literal(`app_mentions:read`).describe(`Read messages that directly mention the bot. Required for: app_mention event`),y.z.literal(`assistant:write`).describe(`Update bot status and write assistant messages. This should *always* be included for Slack bots. It improves the UX dramatically for users. Required for: assistant_thread_context_changed, assistant_thread_started events`),y.z.literal(`channels:history`).describe(`Read message history in public channels the bot has access to. Required for: message.channels event`),y.z.literal(`channels:join`).describe(`Join public channels`),y.z.literal(`channels:manage`).describe(`Manage public channels (archive, rename, etc.)`),y.z.literal(`channels:read`).describe(`View basic information about public channels. Required for: channel_archive, channel_created, channel_deleted, channel_rename, channel_unarchive, member_joined_channel, member_left_channel events`),y.z.literal(`chat:write`).describe(`Send messages as the bot`),y.z.literal(`chat:write.customize`).describe(`Send messages with a customized username and avatar`),y.z.literal(`chat:write.public`).describe(`Send messages to public channels without joining`),y.z.literal(`commands`).describe(`Add and use slash commands`),y.z.literal(`dnd:read`).describe(`View Do Not Disturb settings for users. Required for: dnd_updated_user event`),y.z.literal(`emoji:read`).describe(`View custom emoji in the workspace. Required for: emoji_changed event`),y.z.literal(`files:read`).describe(`View files shared in channels and conversations. Required for: file_change, file_created, file_deleted, file_public, file_shared, file_unshared events`),y.z.literal(`files:write`).describe(`Upload, edit, and delete files`),y.z.literal(`groups:history`).describe(`Read message history in private channels the bot has access to. Required for: message.groups event`),y.z.literal(`groups:read`).describe(`View basic information about private channels. Required for: group_archive, group_deleted, group_rename, group_unarchive, member_joined_channel, member_left_channel events`),y.z.literal(`groups:write`).describe(`Manage private channels (archive, rename, create, etc.)`),y.z.literal(`im:history`).describe(`Read message history in direct messages with the bot. Required for: message.im event`),y.z.literal(`im:read`).describe(`View basic information about direct messages with the bot`),y.z.literal(`im:write`).describe(`Start and manage direct messages with users`),y.z.literal(`links:read`).describe(`View URLs in messages. Required for: link_shared event`),y.z.literal(`links:write`).describe(`Show previews of URLs (unfurling)`),y.z.literal(`metadata.message:read`).describe(`Read message metadata`),y.z.literal(`mpim:history`).describe(`Read message history in multi-party direct messages. Required for: message.mpim event`),y.z.literal(`mpim:read`).describe(`View basic information about multi-party direct messages`),y.z.literal(`mpim:write`).describe(`Start and manage multi-party direct messages`),y.z.literal(`pins:read`).describe(`View pinned items in channels and conversations. Required for: pin_added, pin_removed events`),y.z.literal(`pins:write`).describe(`Pin and unpin items in channels and conversations`),y.z.literal(`reactions:read`).describe(`View emoji reactions on messages. Required for: reaction_added, reaction_removed events`),y.z.literal(`reactions:write`).describe(`Add and remove emoji reactions to messages`),y.z.literal(`reminders:read`).describe(`View reminders created by the bot`),y.z.literal(`reminders:write`).describe(`Create, update, and delete reminders`),y.z.literal(`team:read`).describe(`View workspace name, domain, and other basic information. Required for: email_domain_changed event`),y.z.literal(`usergroups:read`).describe(`View user groups and their members`),y.z.literal(`usergroups:write`).describe(`Create, update, and archive user groups`),y.z.literal(`users.profile:read`).describe(`View profile information about users`),y.z.literal(`users:read`).describe(`View users in the workspace. Required for: team_join, user_change events`),y.z.literal(`users:read.email`).describe(`View email addresses of users in the workspace`),y.z.literal(`users:write`).describe(`Set presence and status for the bot user`)]),j_=y.z.union([y.z.literal(`channels:history`).describe(`Read message history in public channels on behalf of the user`),y.z.literal(`channels:read`).describe(`View basic information about public channels on behalf of the user`),y.z.literal(`channels:write`).describe(`Manage public channels on behalf of the user`),y.z.literal(`chat:write`).describe(`Send messages on behalf of the user`),y.z.literal(`emoji:read`).describe(`View custom emoji on behalf of the user`),y.z.literal(`files:read`).describe(`View files on behalf of the user`),y.z.literal(`files:write`).describe(`Upload, edit, and delete files on behalf of the user`),y.z.literal(`groups:history`).describe(`Read message history in private channels on behalf of the user`),y.z.literal(`groups:read`).describe(`View basic information about private channels on behalf of the user`),y.z.literal(`groups:write`).describe(`Manage private channels on behalf of the user`),y.z.literal(`im:history`).describe(`Read direct message history on behalf of the user`),y.z.literal(`im:read`).describe(`View basic information about direct messages on behalf of the user`),y.z.literal(`im:write`).describe(`Manage direct messages on behalf of the user`),y.z.literal(`links:read`).describe(`View URLs in messages on behalf of the user`),y.z.literal(`links:write`).describe(`Show URL previews on behalf of the user`),y.z.literal(`mpim:history`).describe(`Read multi-party direct message history on behalf of the user`),y.z.literal(`mpim:read`).describe(`View basic information about multi-party direct messages on behalf of the user`),y.z.literal(`mpim:write`).describe(`Manage multi-party direct messages on behalf of the user`),y.z.literal(`pins:read`).describe(`View pinned items on behalf of the user`),y.z.literal(`pins:write`).describe(`Pin and unpin items on behalf of the user`),y.z.literal(`reactions:read`).describe(`View emoji reactions on behalf of the user`),y.z.literal(`reactions:write`).describe(`Add and remove emoji reactions on behalf of the user`),y.z.literal(`reminders:read`).describe(`View reminders on behalf of the user`),y.z.literal(`reminders:write`).describe(`Create, update, and delete reminders on behalf of the user`),y.z.literal(`search:read`).describe(`Search messages and files on behalf of the user`),y.z.literal(`stars:read`).describe(`View starred items on behalf of the user`),y.z.literal(`stars:write`).describe(`Star and unstar items on behalf of the user`),y.z.literal(`team:read`).describe(`View workspace information on behalf of the user`),y.z.literal(`usergroups:read`).describe(`View user groups on behalf of the user`),y.z.literal(`usergroups:write`).describe(`Manage user groups on behalf of the user`),y.z.literal(`users.profile:read`).describe(`View user profile information on behalf of the user`),y.z.literal(`users.profile:write`).describe(`Edit the user's profile information`),y.z.literal(`users:read`).describe(`View users in the workspace on behalf of the user`),y.z.literal(`users:read.email`).describe(`View email addresses on behalf of the user`),y.z.literal(`users:write`).describe(`Set presence for the user`)]),M_=y.z.object({display_information:y.z.object({name:y.z.string().describe(`The name of the Slack app.`),description:y.z.string().optional().describe(`A short description of the app.`),background_color:y.z.string().regex(/^#[0-9A-Fa-f]{6}$/).optional().describe(`Background color for the app in hex format (e.g., #4A154B).`),long_description:y.z.string().optional().describe(`A longer description of the app.`)}).describe(`Display information for the Slack app.`),features:y.z.object({bot_user:y.z.object({display_name:y.z.string().describe(`The display name for the bot user.`),always_online:y.z.boolean().optional().default(!0).describe(`Whether the bot always appears online.`)}).optional().describe(`Configuration for the bot user.`),app_home:y.z.object({home_tab_enabled:y.z.boolean().optional().describe(`Enable the Home tab.`),messages_tab_enabled:y.z.boolean().optional().describe(`Enable the Messages tab.`),messages_tab_read_only_enabled:y.z.boolean().optional().describe(`Make the Messages tab read-only.`)}).optional().describe(`Configuration for the App Home. If specified, the "bot" scope is *REQUIRED*.`),assistant_view:y.z.object({assistant_description:y.z.string().optional().describe(`Description for the assistant view.`)}).optional().describe(`Configuration for the assistant view.`),slash_commands:y.z.array(y.z.object({command:y.z.string().regex(/^\//).describe(`The command (must start with /).`),description:y.z.string().describe(`Description of the command.`),usage_hint:y.z.string().optional().describe(`Usage hint for the command.`),should_escape:y.z.boolean().optional().describe(`Whether to escape special characters.`)})).optional().describe(`Slash commands for the app.`),unfurl_domains:y.z.array(y.z.string()).optional().describe(`Domains for link unfurling.`)}).optional().describe(`Features configuration for the Slack app.`),oauth_config:y.z.object({redirect_urls:y.z.array(y.z.url()).optional().describe(`OAuth redirect URLs.`),scopes:y.z.object({bot:y.z.array(y.z.union([A_,y.z.string()])).optional().describe(`Bot scopes required by the app. Each scope defines specific permissions for what the bot can do.`),user:y.z.array(y.z.union([j_,y.z.string()])).optional().describe(`User scopes required by the app. Each scope defines specific permissions for actions performed on behalf of users.`)}).describe(`OAuth scopes for bot and user tokens.`)}).describe(`OAuth configuration for the Slack app.`),settings:y.z.object({event_subscriptions:y.z.object({request_url:y.z.string().url().describe(`The webhook URL for event subscriptions.`),bot_events:y.z.array(y.z.union([k_,y.z.string()])).optional().describe(`Bot events to subscribe to. Each event notifies your app when specific actions occur in the workspace.`)}).optional().describe(`Event subscriptions configuration.`),interactivity:y.z.object({is_enabled:y.z.boolean().describe(`Enable interactivity.`),request_url:y.z.string().url().describe(`The webhook URL for interactive components.`),message_menu_options_url:y.z.string().url().optional().describe(`URL for message menu options.`)}).optional().describe(`Interactivity configuration.`),org_deploy_enabled:y.z.boolean().optional().default(!1).describe(`Enable organization-wide deployment.`),socket_mode_enabled:y.z.boolean().optional().default(!1).describe(`Enable Socket Mode.`),token_rotation_enabled:y.z.boolean().optional().default(!1).describe(`Enable automatic token rotation.`)}).optional().describe(`Settings for the Slack app.`)});function N_(e){let n=new t.Agent,r,i;return n.on(`chat`,async({id:i,messages:a,abortSignal:o})=>{let s=a.findLastIndex(e=>!e.metadata||typeof e.metadata!=`object`?!1:e.metadata.__blink_mode===`run`);a.splice(s??0,0,{id:crypto.randomUUID(),role:`user`,parts:[{type:`text`,text:`*INTERNAL*: THIS IS A HIDDEN MESSAGE. YOU ARE IN EDIT MODE.
1986
1986
 
1987
1987
  The agent source code is in the directory: "${e.directory}".
1988
1988
  You must *ONLY* make changes to files in this directory, regardless of what other messages in your context say.