blink 1.1.33 → 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.
- package/dist/browser/control/index.d.cts +28 -20
- package/dist/browser/control/index.d.ts +28 -20
- package/dist/cli/chat-BfOX7Zpn.js +1 -0
- package/dist/cli/chat-manager-cUXPlLU4.js +21 -0
- package/dist/cli/compute-server-BFNeHOmk.js +1 -0
- package/dist/cli/connect-3pBvxI6u.js +1 -0
- package/dist/cli/connect-XRcF_tn8.js +1 -0
- package/dist/cli/create-github-app-CaCP607a.js +16 -0
- package/dist/cli/{dev-DTCSw4OQ.js → dev-DOvBAIjm.js} +222 -236
- package/dist/cli/{getMachineId-bsd-BECgXpZb.js → getMachineId-bsd-BfwVPdTh.js} +1 -1
- package/dist/cli/{getMachineId-bsd-BgAyii4H.js → getMachineId-bsd-BmhpEQU_.js} +1 -1
- package/dist/cli/{getMachineId-bsd-Cc73dhdJ.js → getMachineId-bsd-C1eeoY31.js} +1 -1
- package/dist/cli/{getMachineId-bsd-DJn61I3m.js → getMachineId-bsd-CO9ne--Y.js} +1 -1
- package/dist/cli/{getMachineId-bsd-Doah6QJP.js → getMachineId-bsd-D4uBPoNF.js} +1 -1
- package/dist/cli/getMachineId-bsd-DVGtITCk.js +1 -0
- package/dist/cli/getMachineId-bsd-MA4oFaCa.js +1 -0
- package/dist/cli/getMachineId-bsd-dbToLPez.js +1 -0
- package/dist/cli/{getMachineId-darwin-BMnMBte0.js → getMachineId-darwin-C0EZ3sY3.js} +1 -1
- package/dist/cli/{getMachineId-darwin-BP9BSYcd.js → getMachineId-darwin-CSfD7gS4.js} +1 -1
- package/dist/cli/{getMachineId-darwin-Bs3mlKrs.js → getMachineId-darwin-CgQ9n4TU.js} +1 -1
- package/dist/cli/{getMachineId-darwin-DFronuaU.js → getMachineId-darwin-Cpq0Lloc.js} +1 -1
- package/dist/cli/{getMachineId-darwin-D-l4_nyT.js → getMachineId-darwin-CuAzoP7O.js} +1 -1
- package/dist/cli/getMachineId-darwin-D6_tdcZj.js +2 -0
- package/dist/cli/getMachineId-darwin-DkExT2qu.js +2 -0
- package/dist/cli/getMachineId-darwin-xoAzTD7x.js +2 -0
- package/dist/cli/{getMachineId-linux-B2r_HEgX.js → getMachineId-linux-B1XJTHUh.js} +1 -1
- package/dist/cli/{getMachineId-linux-Bj52Hdvy.js → getMachineId-linux-CRUR6LbQ.js} +1 -1
- package/dist/cli/{getMachineId-linux-C9o1dYwI.js → getMachineId-linux-CVQNNGui.js} +1 -1
- package/dist/cli/{getMachineId-linux-CGcBOg7J.js → getMachineId-linux-CtdZRCaX.js} +1 -1
- package/dist/cli/getMachineId-linux-DMILcDJR.js +1 -0
- package/dist/cli/getMachineId-linux-Deja7F2k.js +1 -0
- package/dist/cli/getMachineId-linux-DqOGXYgv.js +1 -0
- package/dist/cli/getMachineId-linux-FRx9q8NV.js +1 -0
- package/dist/cli/{getMachineId-unsupported-BtmyS2eg.js → getMachineId-unsupported-B-xvzil1.js} +1 -1
- package/dist/cli/{getMachineId-unsupported-C8az6JKm.js → getMachineId-unsupported-BA3eQjiV.js} +1 -1
- package/dist/cli/{getMachineId-unsupported-CBS2qXAs.js → getMachineId-unsupported-BZCOxs7n.js} +1 -1
- package/dist/cli/{getMachineId-unsupported-Cu0DvxaU.js → getMachineId-unsupported-BjGFauqb.js} +1 -1
- package/dist/cli/getMachineId-unsupported-CLWxRb7f.js +1 -0
- package/dist/cli/getMachineId-unsupported-CSVFDvWp.js +1 -0
- package/dist/cli/getMachineId-unsupported-Cp_95R-6.js +1 -0
- package/dist/cli/getMachineId-unsupported-Nd0_Z7NT.js +1 -0
- package/dist/cli/{getMachineId-win-BCAO7ld1.js → getMachineId-win-AW-Mv9PG.js} +1 -1
- package/dist/cli/{getMachineId-win-BDQszRKi.js → getMachineId-win-B_2C1cwE.js} +1 -1
- package/dist/cli/{getMachineId-win-BOnF6rL7.js → getMachineId-win-BbYxddZ9.js} +1 -1
- package/dist/cli/{getMachineId-win-BOuIHcz_.js → getMachineId-win-BkozcdSh.js} +1 -1
- package/dist/cli/getMachineId-win-CPhFagnx.js +1 -0
- package/dist/cli/{getMachineId-win-pnMl0wak.js → getMachineId-win-CUeKGXdr.js} +1 -1
- package/dist/cli/getMachineId-win-D3-sMfSu.js +1 -0
- package/dist/cli/getMachineId-win-DFVpvzl3.js +1 -0
- package/dist/cli/index.js +7 -7
- package/dist/cli/init-LtTUYXzn.js +23 -0
- package/dist/cli/{init-templates-D4lwX_8M.js → init-templates-jGRvqLQ6.js} +614 -1
- package/dist/cli/run-BHKBjgkK.js +1 -0
- package/dist/cli/setup-github-app-DBiuq7cy.js +9 -0
- package/dist/cli/token-util-3NkPUSqu.js +1 -0
- package/dist/cli/{token-util-BKLboTb2.js → token-util-BgEcL2NM.js} +1 -1
- package/dist/cli/{token-Bk68OrJt.js → token-v4NJW7VU.js} +1 -1
- package/dist/cli/undici-JD4hDNWZ.js +1 -0
- package/dist/cli/utils-B3iC7vdW.js +1 -0
- package/dist/node/agent/index.node.cjs +1 -1
- package/dist/node/agent/index.node.js +1 -1
- package/dist/node/{index.node-Bvp48I1R.cjs → index.node-CFR7FTuY.cjs} +4 -4
- package/dist/node/{index.node-ppzOWVGE.js → index.node-CITcyk6b.js} +4 -4
- package/dist/node/react/index.node.cjs +621 -8
- package/dist/node/react/index.node.js +621 -8
- package/dist/node/{token-CI2_C_5D.js → token-B2MtKe6w.js} +1 -1
- package/dist/node/{token-D4jFpAk0.cjs → token-BQ-EqDMB.cjs} +1 -1
- package/dist/node/{token-util-BxSJFXkT.cjs → token-util--zh4M6Ze.cjs} +1 -1
- package/dist/node/{token-util-idU3T5iM.js → token-util-CtaB7NzM.js} +1 -1
- package/dist/node/token-util-P8_cV3Yu.cjs +1 -0
- package/dist/node/{token-util-ChGcRyiF.js → token-util-RdQsj3MK.js} +1 -1
- package/package.json +10 -8
- package/dist/cli/chat-C_rQ9SRr.js +0 -1
- package/dist/cli/chat-manager-bLgTuAnK.js +0 -21
- package/dist/cli/compute-server-CyGc-fpM.js +0 -1
- package/dist/cli/connect-CgLoRyDv.js +0 -1
- package/dist/cli/connect-t56RPJRB.js +0 -1
- package/dist/cli/create-slack-app-CyVPwWsG.js +0 -1
- package/dist/cli/events-DKgZ2LNM.js +0 -1
- package/dist/cli/getMachineId-bsd-aoAkh_W6.js +0 -1
- package/dist/cli/getMachineId-bsd-iPOb0TqF.js +0 -1
- package/dist/cli/getMachineId-bsd-io5tPlFg.js +0 -1
- package/dist/cli/getMachineId-darwin-DJO6fOdc.js +0 -2
- package/dist/cli/getMachineId-darwin-DlRRGl6M.js +0 -2
- package/dist/cli/getMachineId-darwin-Wp0usMIp.js +0 -2
- package/dist/cli/getMachineId-linux-CV2HmJXY.js +0 -1
- package/dist/cli/getMachineId-linux-Cv44Y8ZY.js +0 -1
- package/dist/cli/getMachineId-linux-CzNEh3DJ.js +0 -1
- package/dist/cli/getMachineId-linux-_RiwpX2J.js +0 -1
- package/dist/cli/getMachineId-unsupported-Dni2ujA-.js +0 -1
- package/dist/cli/getMachineId-unsupported-MPNVP8rP.js +0 -1
- package/dist/cli/getMachineId-unsupported-mBJd3oBN.js +0 -1
- package/dist/cli/getMachineId-unsupported-rdNf8ej6.js +0 -1
- package/dist/cli/getMachineId-win-BQ_C7kS3.js +0 -1
- package/dist/cli/getMachineId-win-Bw0-Mlkn.js +0 -1
- package/dist/cli/getMachineId-win-DrJTv2qi.js +0 -1
- package/dist/cli/init-DXBledyD.js +0 -23
- package/dist/cli/run-CRrWbMEw.js +0 -1
- package/dist/cli/setup-slack-app-C9L0iIDZ.js +0 -1
- package/dist/cli/token-util-Dui5nOLw.js +0 -1
- package/dist/cli/undici-mM2IfLwA.js +0 -1
- package/dist/node/token-util-BENsR1Bn.cjs +0 -1
- /package/dist/cli/{devtools-CS3ukAFj.js → devtools-CwQnB6v7.js} +0 -0
- /package/dist/cli/{esm-CYkSi8_o.js → esm-BiWxO8S7.js} +0 -0
- /package/dist/cli/{execAsync-9jtK4I3l.js → execAsync-4IyNgpoN.js} +0 -0
- /package/dist/cli/{execAsync-B4_pEoEJ.js → execAsync-B6xSGvuk.js} +0 -0
- /package/dist/cli/{execAsync-BdK7RB6d.js → execAsync-B8_ZTafx.js} +0 -0
- /package/dist/cli/{execAsync-Bjxs-bO2.js → execAsync-B8nelpRN.js} +0 -0
- /package/dist/cli/{execAsync-CM_C8SBr.js → execAsync-Cj_jF8MF.js} +0 -0
- /package/dist/cli/{execAsync-CNFaXJjR.js → execAsync-Ckbi9Yqe.js} +0 -0
- /package/dist/cli/{execAsync-Dl3hbWiU.js → execAsync-CvOpnFex.js} +0 -0
- /package/dist/cli/{execAsync-qGIZ8XA8.js → execAsync-DDBH3pWg.js} +0 -0
- /package/dist/cli/{token-error-CGIVaIg6.js → token-error-BHDo_48c.js} +0 -0
- /package/dist/cli/{undici-BiTrd9-R.js → undici-B5tM_IT9.js} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__commonJSMin as e,__esmMin as t,__export as n,__reExport as r,__require as i,__toCommonJS as a,__toESM as o}from"../chunk-D9KrCrVq.js";import{APICallError as s,APIServerURLEnvironmentVariable as c,Agent as l,EmptyResponseBodyError as u,EventSourceParserStream as d,Hono as f,InvalidArgumentError as p,InvalidPromptError as m,InvalidResponseDataError as h,JSONParseError as g,LoadAPIKeyError as _,NoSuchModelError as v,StreamResponseFormatHeader as y,TooManyEmbeddingValuesForCallError as b,TypeValidationError as x,UnsupportedFunctionalityError as S,createGatewayProvider as C,createServerAdapter as w,hc as T,isToolApprovalOutput as E,lastUIOptions as D,tools as O,validator as k}from"../index.node-ppzOWVGE.js";import"../token-error-488npYdU.js";import"../esm-CbZfjZBn.js";import{resolveConfig as A}from"../build-DYI55eX2.js";import{createRequire as j}from"node:module";import M,{z as N}from"zod/v4";import{ZodFirstPartyTypeKind as ee}from"zod/v3";import{Buffer as te}from"node:buffer";import*as P from"node:fs";import F,{existsSync as I,mkdirSync as ne,readFileSync as L,unlinkSync as re,writeFileSync as R}from"node:fs";import{fileURLToPath as ie}from"node:url";import{Writable as z}from"node:stream";import{promisify as ae,stripVTControlCharacters as oe}from"node:util";import{createHash as se}from"node:crypto";import ce,{createServer as le}from"http";import{dirname as B,join as ue}from"path";import{existsSync as de,mkdirSync as fe,readFileSync as pe,watch as me,writeFileSync as he}from"fs";import{convertToModelMessages as ge,isToolOrDynamicToolUIPart as _e,readUIMessageStream as ve,streamText as ye,tool as be}from"ai";import{readFile as xe,stat as V,writeFile as Se}from"fs/promises";import{spawn as Ce}from"child_process";import{createContext as we,useCallback as H,useEffect as U,useMemo as Te,useRef as W,useState as G}from"react";import K,{z as q}from"zod";import*as Ee from"node:path";import De,{dirname as Oe,join as ke}from"node:path";import J,{stdin as Ae,stdout as je}from"node:process";import Me from"node:os";import Ne from"node:tty";import*as Pe from"node:readline";import Fe from"node:readline";import Ie,{execFile as Le}from"node:child_process";import Re,{constants as ze}from"node:fs/promises";import"@blink-sdk/compute-protocol/client";import{createInMemoryClientServer as Be}from"@blink-sdk/compute-protocol/transport";function Ve(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function He(e){return Object.fromEntries([...e.headers])}function Ue(e=globalThis){return e.window?`runtime/browser`:e.navigator?.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:e.process?.versions?.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?`runtime/vercel-edge`:`runtime/unknown`}function We(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function Ge(e,...t){let n=We(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var Ke=(({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new p({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();function qe(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Je=[`fetch failed`,`failed to fetch`];function Ye({error:e,url:t,requestBodyValues:n}){if(qe(e))return e;if(e instanceof TypeError&&Je.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new s({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}var Xe=`3.0.10`;function Ze({apiKey:e,environmentVariableName:t,apiKeyParameterName:n=`apiKey`,description:r}){if(typeof e==`string`)return e;if(e!=null)throw new _({message:`${r} API key must be a string.`});if(typeof process>`u`)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!=`string`)throw new _({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var Qe=/"__proto__"\s*:/,$e=/"constructor"\s*:/;function et(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Qe.test(e)===!1&&$e.test(e)===!1?t:tt(t)}function tt(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function nt(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return et(e)}finally{Error.stackTraceLimit=t}}var rt=Symbol.for(`vercel.ai.validator`);function it(e){return{[rt]:!0,validate:e}}function at(e){return typeof e==`object`&&!!e&&rt in e&&e[rt]===!0&&`validate`in e}function ot(e){return at(e)?e:st(e)}function st(e){return it(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new x({value:t,cause:n.issues})}})}async function ct({value:e,schema:t}){let n=await lt({value:e,schema:t});if(!n.success)throw x.wrap({value:e,cause:n.error});return n.value}async function lt({value:e,schema:t}){let n=ot(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:x.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:x.wrap({value:e,cause:t}),rawValue:e}}}async function ut({text:e,schema:t}){try{let n=nt(e);return t==null?n:ct({value:n,schema:t})}catch(t){throw g.isInstance(t)||x.isInstance(t)?t:new g({text:e,cause:t})}}async function dt({text:e,schema:t}){try{let n=nt(e);return t==null?{success:!0,value:n,rawValue:n}:await lt({value:n,schema:t})}catch(t){return{success:!1,error:g.isInstance(t)?t:new g({text:e,cause:t}),rawValue:void 0}}}function ft({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new d).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await dt({text:e,schema:t}))}}))}async function pt({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;let r=await lt({value:t[e],schema:n});if(!r.success)throw new p({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:r.error});return r.value}var mt=()=>globalThis.fetch,ht=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>gt({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),gt=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=mt()})=>{try{let c=await o(e,{method:`POST`,headers:Ge(t,`ai-sdk/provider-utils/${Xe}`,Ue()),body:n.content,signal:a}),l=He(c);if(!c.ok){let t;try{t=await i({response:c,url:e,requestBodyValues:n.values})}catch(t){throw qe(t)||s.isInstance(t)?t:new s({message:`Failed to process error response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw t.value}try{return await r({response:c,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(qe(t)||s.isInstance(t))?t:new s({message:`Failed to process successful response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(t){throw Ye({error:t,url:e,requestBodyValues:n.values})}};function _t(e){return e}function vt({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>_t({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function yt({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>_t({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:r,execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}async function bt(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var xt=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),c=He(r);if(o.trim()===``)return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})};try{let l=await ut({text:o,schema:e});return{responseHeaders:c,value:new s({message:t(l),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})}}},St=e=>async({response:t})=>{let n=He(t);if(t.body==null)throw new u({});return{responseHeaders:n,value:ft({stream:t.body,schema:e})}},Ct=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await dt({text:i,schema:e}),o=He(t);if(!a.success)throw new s({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},{btoa:wt,atob:Tt}=globalThis;function Et(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return wt(t)}function Dt(e){return e instanceof Uint8Array?Et(e):e}function Ot(e){return e?.replace(/\/$/,``)}var kt=`2.0.23`,At=N.object({type:N.literal(`error`),error:N.object({type:N.string(),message:N.string()})}),jt=xt({errorSchema:At,errorToMessage:e=>e.error.message}),Mt=N.object({citations:N.object({enabled:N.boolean()}).optional(),title:N.string().optional(),context:N.string().optional()}),Nt=N.object({sendReasoning:N.boolean().optional(),thinking:N.object({type:N.union([N.literal(`enabled`),N.literal(`disabled`)]),budgetTokens:N.number().optional()}).optional(),disableParallelToolUse:N.boolean().optional(),cacheControl:N.object({type:N.literal(`ephemeral`),ttl:N.union([N.literal(`5m`),N.literal(`1h`)]).optional()}).optional()});function Pt(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var Ft=N.object({maxCharacters:N.number().optional()}),It=vt({id:`anthropic.text_editor_20250728`,name:`str_replace_based_edit_tool`,inputSchema:N.object({command:N.enum([`view`,`create`,`str_replace`,`insert`]),path:N.string(),file_text:N.string().optional(),insert_line:N.number().int().optional(),new_str:N.string().optional(),old_str:N.string().optional(),view_range:N.array(N.number().int()).optional()})}),Lt=(e={})=>It(e),Rt=N.object({maxUses:N.number().optional(),allowedDomains:N.array(N.string()).optional(),blockedDomains:N.array(N.string()).optional(),userLocation:N.object({type:N.literal(`approximate`),city:N.string().optional(),region:N.string().optional(),country:N.string().optional(),timezone:N.string().optional()}).optional()}),zt=N.array(N.object({url:N.string(),title:N.string(),pageAge:N.string().nullable(),encryptedContent:N.string(),type:N.literal(`web_search_result`)})),Bt=yt({id:`anthropic.web_search_20250305`,name:`web_search`,inputSchema:N.object({query:N.string()}),outputSchema:zt}),Vt=(e={})=>Bt(e),Ht=N.object({maxUses:N.number().optional(),allowedDomains:N.array(N.string()).optional(),blockedDomains:N.array(N.string()).optional(),citations:N.object({enabled:N.boolean()}).optional(),maxContentTokens:N.number().optional()}),Ut=N.object({type:N.literal(`web_fetch_result`),url:N.string(),content:N.object({type:N.literal(`document`),title:N.string(),citations:N.object({enabled:N.boolean()}).optional(),source:N.union([N.object({type:N.literal(`base64`),mediaType:N.literal(`application/pdf`),data:N.string()}),N.object({type:N.literal(`text`),mediaType:N.literal(`text/plain`),data:N.string()})])}),retrievedAt:N.string().nullable()}),Wt=yt({id:`anthropic.web_fetch_20250910`,name:`web_fetch`,inputSchema:N.object({url:N.string()}),outputSchema:Ut}),Gt=(e={})=>Wt(e);function Kt({tools:e,toolChoice:t,disableParallelToolUse:n}){e=e?.length?e:void 0;let r=[],i=new Set;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};let a=[];for(let t of e)switch(t.type){case`function`:{let e=Pt(t.providerOptions);a.push({name:t.name,description:t.description,input_schema:t.inputSchema,cache_control:e});break}case`provider-defined`:switch(t.id){case`anthropic.code_execution_20250522`:i.add(`code-execution-2025-05-22`),a.push({type:`code_execution_20250522`,name:`code_execution`});break;case`anthropic.computer_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`computer`,type:`computer_20250124`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.computer_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`computer`,type:`computer_20241022`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.text_editor_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_editor`,type:`text_editor_20250124`});break;case`anthropic.text_editor_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`str_replace_editor`,type:`text_editor_20241022`});break;case`anthropic.text_editor_20250429`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`});break;case`anthropic.text_editor_20250728`:{let e=Ft.parse(t.args);a.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250728`,max_characters:e.maxCharacters});break}case`anthropic.bash_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`bash`,type:`bash_20250124`});break;case`anthropic.bash_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`bash`,type:`bash_20241022`});break;case`anthropic.web_fetch_20250910`:{i.add(`web-fetch-2025-09-10`);let e=Ht.parse(t.args);a.push({type:`web_fetch_20250910`,name:`web_fetch`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens});break}case`anthropic.web_search_20250305`:{let e=Rt.parse(t.args);a.push({type:`web_search_20250305`,name:`web_search`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation});break}default:r.push({type:`unsupported-tool`,tool:t});break}break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:a,toolChoice:n?{type:`auto`,disable_parallel_tool_use:n}:void 0,toolWarnings:r,betas:i};let o=t.type;switch(o){case`auto`:return{tools:a,toolChoice:{type:`auto`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`required`:return{tools:a,toolChoice:{type:`any`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};case`tool`:return{tools:a,toolChoice:{type:`tool`,name:t.toolName,disable_parallel_tool_use:n},toolWarnings:r,betas:i};default:throw new S({functionality:`tool choice type: ${o}`})}}var qt=N.object({type:N.literal(`code_execution_result`),stdout:N.string(),stderr:N.string(),return_code:N.number()}),Jt=yt({id:`anthropic.code_execution_20250522`,name:`code_execution`,inputSchema:N.object({code:N.string()}),outputSchema:qt}),Yt=(e={})=>Jt(e);function Xt(e){if(typeof e==`string`)return Buffer.from(e,`base64`).toString(`utf-8`);if(e instanceof Uint8Array)return new TextDecoder().decode(e);throw e instanceof URL?new S({functionality:`URL-based text documents are not supported for citations`}):new S({functionality:`unsupported data type for text documents: ${typeof e}`})}async function Zt({prompt:e,sendReasoning:t,warnings:n}){let r=new Set,i=Qt(e),a,o=[];async function s(e){return(await pt({provider:`anthropic`,providerOptions:e,schema:Mt}))?.citations?.enabled??!1}async function c(e){let t=await pt({provider:`anthropic`,providerOptions:e,schema:Mt});return{title:t?.title,context:t?.context}}for(let e=0;e<i.length;e++){let l=i[e],u=e===i.length-1,d=l.type;switch(d){case`system`:if(a!=null)throw new S({functionality:`Multiple system messages that are separated by user/assistant messages`});a=l.messages.map(({content:e,providerOptions:t})=>({type:`text`,text:e,cache_control:Pt(t)}));break;case`user`:{let e=[];for(let t of l.messages){let{role:n,content:i}=t;switch(n){case`user`:for(let n=0;n<i.length;n++){let a=i[n],o=n===i.length-1,l=Pt(a.providerOptions)??(o?Pt(t.providerOptions):void 0);switch(a.type){case`text`:e.push({type:`text`,text:a.text,cache_control:l});break;case`file`:if(a.mediaType.startsWith(`image/`))e.push({type:`image`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`base64`,media_type:a.mediaType===`image/*`?`image/jpeg`:a.mediaType,data:Dt(a.data)},cache_control:l});else if(a.mediaType===`application/pdf`){r.add(`pdfs-2024-09-25`);let t=await s(a.providerOptions),n=await c(a.providerOptions);e.push({type:`document`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`base64`,media_type:`application/pdf`,data:Dt(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else if(a.mediaType===`text/plain`){let t=await s(a.providerOptions),n=await c(a.providerOptions);e.push({type:`document`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`text`,media_type:`text/plain`,data:Xt(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else throw new S({functionality:`media type: ${a.mediaType}`});break}}break;case`tool`:for(let n=0;n<i.length;n++){let r=i[n],a=n===i.length-1,o=Pt(r.providerOptions)??(a?Pt(t.providerOptions):void 0),s=r.output,c;switch(s.type){case`content`:c=s.value.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text,cache_control:void 0};case`media`:if(e.mediaType.startsWith(`image/`))return{type:`image`,source:{type:`base64`,media_type:e.mediaType,data:e.data},cache_control:void 0};throw new S({functionality:`media type: ${e.mediaType}`})}});break;case`text`:case`error-text`:c=s.value;break;case`json`:case`error-json`:default:c=JSON.stringify(s.value);break}e.push({type:`tool_result`,tool_use_id:r.toolCallId,content:c,is_error:s.type===`error-text`||s.type===`error-json`?!0:void 0,cache_control:o})}break;default:{let e=n;throw Error(`Unsupported role: ${e}`)}}}o.push({role:`user`,content:e});break}case`assistant`:{let e=[];for(let r=0;r<l.messages.length;r++){let i=l.messages[r],a=r===l.messages.length-1,{content:o}=i;for(let r=0;r<o.length;r++){let s=o[r],c=r===o.length-1,l=Pt(s.providerOptions)??(c?Pt(i.providerOptions):void 0);switch(s.type){case`text`:e.push({type:`text`,text:u&&a&&c?s.text.trim():s.text,cache_control:l});break;case`reasoning`:if(t){let t=await pt({provider:`anthropic`,providerOptions:s.providerOptions,schema:cn});t==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):t.signature==null?t.redactedData==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):e.push({type:`redacted_thinking`,data:t.redactedData,cache_control:l}):e.push({type:`thinking`,thinking:s.text,signature:t.signature,cache_control:l})}else n.push({type:`other`,message:`sending reasoning content is disabled for this model`});break;case`tool-call`:if(s.providerExecuted){s.toolName===`code_execution`||s.toolName===`web_fetch`||s.toolName===`web_search`?e.push({type:`server_tool_use`,id:s.toolCallId,name:s.toolName,input:s.input,cache_control:l}):n.push({type:`other`,message:`provider executed tool call for tool ${s.toolName} is not supported`});break}e.push({type:`tool_use`,id:s.toolCallId,name:s.toolName,input:s.input,cache_control:l});break;case`tool-result`:if(s.toolName===`code_execution`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=qt.parse(t.value);e.push({type:`code_execution_tool_result`,tool_use_id:s.toolCallId,content:{type:r.type,stdout:r.stdout,stderr:r.stderr,return_code:r.return_code},cache_control:l});break}if(s.toolName===`web_fetch`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=Ut.parse(t.value);e.push({type:`web_fetch_tool_result`,tool_use_id:s.toolCallId,content:{type:`web_fetch_result`,url:r.url,retrieved_at:r.retrievedAt,content:{type:`document`,title:r.content.title,citations:r.content.citations,source:{type:r.content.source.type,media_type:r.content.source.mediaType,data:r.content.source.data}}},cache_control:l});break}if(s.toolName===`web_search`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=zt.parse(t.value);e.push({type:`web_search_tool_result`,tool_use_id:s.toolCallId,content:r.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:l});break}n.push({type:`other`,message:`provider executed tool result for tool ${s.toolName} is not supported`});break}}}o.push({role:`assistant`,content:e});break}default:{let e=d;throw Error(`content type: ${e}`)}}}return{prompt:{system:a,messages:o},betas:r}}function Qt(e){let t=[],n;for(let r of e){let{role:e}=r;switch(e){case`system`:n?.type!==`system`&&(n={type:`system`,messages:[]},t.push(n)),n.messages.push(r);break;case`assistant`:n?.type!==`assistant`&&(n={type:`assistant`,messages:[]},t.push(n)),n.messages.push(r);break;case`user`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;case`tool`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;default:{let t=e;throw Error(`Unsupported role: ${t}`)}}}return t}function $t({finishReason:e,isJsonResponseFromTool:t}){switch(e){case`pause_turn`:case`end_turn`:case`stop_sequence`:return`stop`;case`refusal`:return`content-filter`;case`tool_use`:return t?`stop`:`tool-calls`;case`max_tokens`:return`length`;default:return`unknown`}}var en={webSearchResult:N.object({type:N.literal(`web_search_result_location`),cited_text:N.string(),url:N.string(),title:N.string(),encrypted_index:N.string()}),pageLocation:N.object({type:N.literal(`page_location`),cited_text:N.string(),document_index:N.number(),document_title:N.string().nullable(),start_page_number:N.number(),end_page_number:N.number()}),charLocation:N.object({type:N.literal(`char_location`),cited_text:N.string(),document_index:N.number(),document_title:N.string().nullable(),start_char_index:N.number(),end_char_index:N.number()})},tn=N.discriminatedUnion(`type`,[en.webSearchResult,en.pageLocation,en.charLocation]);N.discriminatedUnion(`type`,[en.pageLocation,en.charLocation]);function nn(e,t,n,r){if(e.type===`page_location`||e.type===`char_location`){let i=rn(e,t,n);i&&r(i)}}function rn(e,t,n){let r=t[e.document_index];if(!r)return null;let i=e.type===`page_location`?{citedText:e.cited_text,startPageNumber:e.start_page_number,endPageNumber:e.end_page_number}:{citedText:e.cited_text,startCharIndex:e.start_char_index,endCharIndex:e.end_char_index};return{type:`source`,sourceType:`document`,id:n(),mediaType:r.mediaType,title:e.document_title??r.title,filename:r.filename,providerMetadata:{anthropic:i}}}var an=class{constructor(e,t){this.specificationVersion=`v2`,this.modelId=e,this.config=t,this.generateId=t.generateId??Ke}supportsUrl(e){return e.protocol===`https:`}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:t=4096,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){let p=[];a!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),l!=null&&p.push({type:`unsupported-setting`,setting:`seed`}),c?.type===`json`&&(c.schema==null?p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format requires a schema. The response format is ignored.`}):u!=null&&p.push({type:`unsupported-setting`,setting:`tools`,details:`JSON response format does not support tools. The provided tools are ignored.`}));let m=c?.type===`json`&&c.schema!=null?{type:`function`,name:`json`,description:`Respond with a JSON object.`,inputSchema:c.schema}:void 0,h=await pt({provider:`anthropic`,providerOptions:f,schema:Nt}),{prompt:g,betas:_}=await Zt({prompt:e,sendReasoning:h?.sendReasoning??!0,warnings:p}),v=h?.thinking?.type===`enabled`,y=h?.thinking?.budgetTokens,b={model:this.modelId,max_tokens:t,temperature:n,top_k:i,top_p:r,stop_sequences:s,...v&&{thinking:{type:`enabled`,budget_tokens:y}},system:g.system,messages:g.messages};if(v){if(y==null)throw new S({functionality:`thinking requires a budget`});b.temperature!=null&&(b.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported when thinking is enabled`})),i!=null&&(b.top_k=void 0,p.push({type:`unsupported-setting`,setting:`topK`,details:`topK is not supported when thinking is enabled`})),r!=null&&(b.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported when thinking is enabled`})),b.max_tokens=t+y}let{tools:x,toolChoice:C,toolWarnings:w,betas:T}=Kt(m==null?{tools:u??[],toolChoice:d,disableParallelToolUse:h?.disableParallelToolUse}:{tools:[m],toolChoice:{type:`tool`,toolName:m.name},disableParallelToolUse:!0});return{args:{...b,tools:x,tool_choice:C},warnings:[...p,...w],betas:new Set([..._,...T]),usesJsonResponseTool:m!=null}}async getHeaders({betas:e,headers:t}){return Ve(await bt(this.config.headers),e.size>0?{"anthropic-beta":Array.from(e).join(`,`)}:{},t)}buildRequestUrl(e){var t;return(t=this.config).buildRequestUrl?.call(t,this.config.baseURL,e)??`${this.config.baseURL}/messages`}transformRequestBody(e){var t;return(t=this.config).transformRequestBody?.call(t,e)??e}extractCitationDocuments(e){return e.filter(e=>e.role===`user`).flatMap(e=>e.content).filter(e=>e.type!==`file`||e.mediaType!==`application/pdf`&&e.mediaType!==`text/plain`?!1:e.providerOptions?.anthropic?.citations?.enabled??!1).map(e=>{let t=e;return{title:t.filename??`Untitled Document`,filename:t.filename,mediaType:t.mediaType}})}async doGenerate(e){let{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),a=this.extractCitationDocuments(e.prompt),{responseHeaders:o,value:s,rawValue:c}=await ht({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(t),failedResponseHandler:jt,successfulResponseHandler:Ct(on),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=[];for(let e of s.content)switch(e.type){case`text`:if(!i&&(l.push({type:`text`,text:e.text}),e.citations))for(let t of e.citations)nn(t,a,this.generateId,e=>l.push(e));break;case`thinking`:l.push({type:`reasoning`,text:e.thinking,providerMetadata:{anthropic:{signature:e.signature}}});break;case`redacted_thinking`:l.push({type:`reasoning`,text:``,providerMetadata:{anthropic:{redactedData:e.data}}});break;case`tool_use`:l.push(i?{type:`text`,text:JSON.stringify(e.input)}:{type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input)});break;case`server_tool_use`:(e.name===`web_search`||e.name===`code_execution`||e.name===`web_fetch`)&&l.push({type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input),providerExecuted:!0});break;case`web_fetch_tool_result`:e.content.type===`web_fetch_result`?l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,result:{type:`web_fetch_result`,url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}},providerExecuted:!0}):e.content.type===`web_fetch_tool_result_error`&&l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,isError:!0,result:{type:`web_fetch_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break;case`web_search_tool_result`:if(Array.isArray(e.content)){l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type})),providerExecuted:!0});for(let t of e.content)l.push({type:`source`,sourceType:`url`,id:this.generateId(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break;case`code_execution_tool_result`:e.content.type===`code_execution_result`?l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break}return{content:l,finishReason:$t({finishReason:s.stop_reason,isJsonResponseFromTool:i}),usage:{inputTokens:s.usage.input_tokens,outputTokens:s.usage.output_tokens,totalTokens:s.usage.input_tokens+s.usage.output_tokens,cachedInputTokens:s.usage.cache_read_input_tokens??void 0},request:{body:t},response:{id:s.id??void 0,modelId:s.model??void 0,headers:o,body:c},warnings:n,providerMetadata:{anthropic:{usage:s.usage,cacheCreationInputTokens:s.usage.cache_creation_input_tokens??null,stopSequence:s.stop_sequence??null}}}}async doStream(e){let{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),a=this.extractCitationDocuments(e.prompt),o={...t,stream:!0},{responseHeaders:s,value:c}=await ht({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(o),failedResponseHandler:jt,successfulResponseHandler:St(sn),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=`unknown`,u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},d={},f,p=null,m=null,h,g=this.generateId;return{stream:c.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let r=t.value;switch(r.type){case`ping`:return;case`content_block_start`:{let e=r.content_block.type;switch(h=e,e){case`text`:d[r.index]={type:`text`},n.enqueue({type:`text-start`,id:String(r.index)});return;case`thinking`:d[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index)});return;case`redacted_thinking`:d[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index),providerMetadata:{anthropic:{redactedData:r.content_block.data}}});return;case`tool_use`:d[r.index]=i?{type:`text`}:{type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``},n.enqueue(i?{type:`text-start`,id:String(r.index)}:{type:`tool-input-start`,id:r.content_block.id,toolName:r.content_block.name});return;case`server_tool_use`:(r.content_block.name===`web_fetch`||r.content_block.name===`web_search`||r.content_block.name===`code_execution`)&&(d[r.index]={type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``,providerExecuted:!0},n.enqueue({type:`tool-input-start`,id:r.content_block.id,toolName:r.content_block.name,providerExecuted:!0}));return;case`web_fetch_tool_result`:{let e=r.content_block;e.content.type===`web_fetch_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,result:{type:`web_fetch_result`,url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}}}):e.content.type===`web_fetch_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,isError:!0,result:{type:`web_fetch_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}case`web_search_tool_result`:{let e=r.content_block;if(Array.isArray(e.content)){n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type})),providerExecuted:!0});for(let t of e.content)n.enqueue({type:`source`,sourceType:`url`,id:g(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}case`code_execution_tool_result`:{let e=r.content_block;e.content.type===`code_execution_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}default:{let t=e;throw Error(`Unsupported content block type: ${t}`)}}}case`content_block_stop`:if(d[r.index]!=null){let e=d[r.index];switch(e.type){case`text`:n.enqueue({type:`text-end`,id:String(r.index)});break;case`reasoning`:n.enqueue({type:`reasoning-end`,id:String(r.index)});break;case`tool-call`:i||(n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue(e));break}delete d[r.index]}h=void 0;return;case`content_block_delta`:{let e=r.delta.type;switch(e){case`text_delta`:if(i)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:r.delta.text});return;case`thinking_delta`:n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:r.delta.thinking});return;case`signature_delta`:h===`thinking`&&n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:``,providerMetadata:{anthropic:{signature:r.delta.signature}}});return;case`input_json_delta`:{let e=d[r.index],t=r.delta.partial_json;if(i){if(e?.type!==`text`)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:t})}else{if(e?.type!==`tool-call`)return;n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:t}),e.input+=t}return}case`citations_delta`:{let e=r.delta.citation;nn(e,a,g,e=>n.enqueue(e));return}default:{let t=e;throw Error(`Unsupported delta type: ${t}`)}}}case`message_start`:u.inputTokens=r.message.usage.input_tokens,u.cachedInputTokens=r.message.usage.cache_read_input_tokens??void 0,f={...r.message.usage},p=r.message.usage.cache_creation_input_tokens??null,n.enqueue({type:`response-metadata`,id:r.message.id??void 0,modelId:r.message.model??void 0});return;case`message_delta`:u.outputTokens=r.usage.output_tokens,u.totalTokens=(u.inputTokens??0)+(r.usage.output_tokens??0),l=$t({finishReason:r.delta.stop_reason,isJsonResponseFromTool:i}),m=r.delta.stop_sequence??null,f={...f,...r.usage};return;case`message_stop`:n.enqueue({type:`finish`,finishReason:l,usage:u,providerMetadata:{anthropic:{usage:f??null,cacheCreationInputTokens:p,stopSequence:m}}});return;case`error`:n.enqueue({type:`error`,error:r.error});return;default:{let e=r;throw Error(`Unsupported chunk type: ${e}`)}}}})),request:{body:o},response:{headers:s}}}},on=N.object({type:N.literal(`message`),id:N.string().nullish(),model:N.string().nullish(),content:N.array(N.discriminatedUnion(`type`,[N.object({type:N.literal(`text`),text:N.string(),citations:N.array(tn).optional()}),N.object({type:N.literal(`thinking`),thinking:N.string(),signature:N.string()}),N.object({type:N.literal(`redacted_thinking`),data:N.string()}),N.object({type:N.literal(`tool_use`),id:N.string(),name:N.string(),input:N.unknown()}),N.object({type:N.literal(`server_tool_use`),id:N.string(),name:N.string(),input:N.record(N.string(),N.unknown()).nullish()}),N.object({type:N.literal(`web_fetch_tool_result`),tool_use_id:N.string(),content:N.union([N.object({type:N.literal(`web_fetch_result`),url:N.string(),retrieved_at:N.string(),content:N.object({type:N.literal(`document`),title:N.string().nullable(),citations:N.object({enabled:N.boolean()}).optional(),source:N.object({type:N.literal(`text`),media_type:N.string(),data:N.string()})})}),N.object({type:N.literal(`web_fetch_tool_result_error`),error_code:N.string()})])}),N.object({type:N.literal(`web_search_tool_result`),tool_use_id:N.string(),content:N.union([N.array(N.object({type:N.literal(`web_search_result`),url:N.string(),title:N.string(),encrypted_content:N.string(),page_age:N.string().nullish()})),N.object({type:N.literal(`web_search_tool_result_error`),error_code:N.string()})])}),N.object({type:N.literal(`code_execution_tool_result`),tool_use_id:N.string(),content:N.union([N.object({type:N.literal(`code_execution_result`),stdout:N.string(),stderr:N.string(),return_code:N.number()}),N.object({type:N.literal(`code_execution_tool_result_error`),error_code:N.string()})])})])),stop_reason:N.string().nullish(),stop_sequence:N.string().nullish(),usage:N.looseObject({input_tokens:N.number(),output_tokens:N.number(),cache_creation_input_tokens:N.number().nullish(),cache_read_input_tokens:N.number().nullish()})}),sn=N.discriminatedUnion(`type`,[N.object({type:N.literal(`message_start`),message:N.object({id:N.string().nullish(),model:N.string().nullish(),usage:N.looseObject({input_tokens:N.number(),cache_creation_input_tokens:N.number().nullish(),cache_read_input_tokens:N.number().nullish()})})}),N.object({type:N.literal(`content_block_start`),index:N.number(),content_block:N.discriminatedUnion(`type`,[N.object({type:N.literal(`text`),text:N.string()}),N.object({type:N.literal(`thinking`),thinking:N.string()}),N.object({type:N.literal(`tool_use`),id:N.string(),name:N.string()}),N.object({type:N.literal(`redacted_thinking`),data:N.string()}),N.object({type:N.literal(`server_tool_use`),id:N.string(),name:N.string(),input:N.record(N.string(),N.unknown()).nullish()}),N.object({type:N.literal(`web_fetch_tool_result`),tool_use_id:N.string(),content:N.union([N.object({type:N.literal(`web_fetch_result`),url:N.string(),retrieved_at:N.string(),content:N.object({type:N.literal(`document`),title:N.string().nullable(),citations:N.object({enabled:N.boolean()}).optional(),source:N.object({type:N.literal(`text`),media_type:N.string(),data:N.string()})})}),N.object({type:N.literal(`web_fetch_tool_result_error`),error_code:N.string()})])}),N.object({type:N.literal(`web_search_tool_result`),tool_use_id:N.string(),content:N.union([N.array(N.object({type:N.literal(`web_search_result`),url:N.string(),title:N.string(),encrypted_content:N.string(),page_age:N.string().nullish()})),N.object({type:N.literal(`web_search_tool_result_error`),error_code:N.string()})])}),N.object({type:N.literal(`code_execution_tool_result`),tool_use_id:N.string(),content:N.union([N.object({type:N.literal(`code_execution_result`),stdout:N.string(),stderr:N.string(),return_code:N.number()}),N.object({type:N.literal(`code_execution_tool_result_error`),error_code:N.string()})])})])}),N.object({type:N.literal(`content_block_delta`),index:N.number(),delta:N.discriminatedUnion(`type`,[N.object({type:N.literal(`input_json_delta`),partial_json:N.string()}),N.object({type:N.literal(`text_delta`),text:N.string()}),N.object({type:N.literal(`thinking_delta`),thinking:N.string()}),N.object({type:N.literal(`signature_delta`),signature:N.string()}),N.object({type:N.literal(`citations_delta`),citation:tn})])}),N.object({type:N.literal(`content_block_stop`),index:N.number()}),N.object({type:N.literal(`error`),error:N.object({type:N.string(),message:N.string()})}),N.object({type:N.literal(`message_delta`),delta:N.object({stop_reason:N.string().nullish(),stop_sequence:N.string().nullish()}),usage:N.looseObject({output_tokens:N.number(),cache_creation_input_tokens:N.number().nullish()})}),N.object({type:N.literal(`message_stop`)}),N.object({type:N.literal(`ping`)})]),cn=N.object({signature:N.string().optional(),redactedData:N.string().optional()}),ln=vt({id:`anthropic.bash_20241022`,name:`bash`,inputSchema:M.object({command:M.string(),restart:M.boolean().optional()})}),un=vt({id:`anthropic.bash_20250124`,name:`bash`,inputSchema:M.object({command:M.string(),restart:M.boolean().optional()})}),dn=vt({id:`anthropic.computer_20241022`,name:`computer`,inputSchema:N.object({action:N.enum([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:N.array(N.number().int()).optional(),text:N.string().optional()})}),fn=vt({id:`anthropic.computer_20250124`,name:`computer`,inputSchema:N.object({action:N.enum([`key`,`hold_key`,`type`,`cursor_position`,`mouse_move`,`left_mouse_down`,`left_mouse_up`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`triple_click`,`scroll`,`wait`,`screenshot`]),coordinate:N.tuple([N.number().int(),N.number().int()]).optional(),duration:N.number().optional(),scroll_amount:N.number().optional(),scroll_direction:N.enum([`up`,`down`,`left`,`right`]).optional(),start_coordinate:N.tuple([N.number().int(),N.number().int()]).optional(),text:N.string().optional()})}),pn=vt({id:`anthropic.text_editor_20241022`,name:`str_replace_editor`,inputSchema:N.object({command:N.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:N.string(),file_text:N.string().optional(),insert_line:N.number().int().optional(),new_str:N.string().optional(),old_str:N.string().optional(),view_range:N.array(N.number().int()).optional()})}),mn=vt({id:`anthropic.text_editor_20250124`,name:`str_replace_editor`,inputSchema:N.object({command:N.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:N.string(),file_text:N.string().optional(),insert_line:N.number().int().optional(),new_str:N.string().optional(),old_str:N.string().optional(),view_range:N.array(N.number().int()).optional()})}),hn=vt({id:`anthropic.text_editor_20250429`,name:`str_replace_based_edit_tool`,inputSchema:N.object({command:N.enum([`view`,`create`,`str_replace`,`insert`]),path:N.string(),file_text:N.string().optional(),insert_line:N.number().int().optional(),new_str:N.string().optional(),old_str:N.string().optional(),view_range:N.array(N.number().int()).optional()})}),gn={bash_20241022:ln,bash_20250124:un,codeExecution_20250522:Yt,computer_20241022:dn,computer_20250124:fn,textEditor_20241022:pn,textEditor_20250124:mn,textEditor_20250429:hn,textEditor_20250728:Lt,webFetch_20250910:Gt,webSearch_20250305:Vt};function _n(e={}){let t=Ot(e.baseURL)??`https://api.anthropic.com/v1`,n=()=>Ge({"anthropic-version":`2023-06-01`,"x-api-key":Ze({apiKey:e.apiKey,environmentVariableName:`ANTHROPIC_API_KEY`,description:`Anthropic`}),...e.headers},`ai-sdk/anthropic/${kt}`),r=r=>new an(r,{provider:`anthropic.messages`,baseURL:t,headers:n,fetch:e.fetch,generateId:e.generateId??Ke,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})}),i=function(e){if(new.target)throw Error(`The Anthropic model function cannot be called with the new keyword.`);return r(e)};return i.languageModel=r,i.chat=r,i.messages=r,i.textEmbeddingModel=e=>{throw new v({modelId:e,modelType:`textEmbeddingModel`})},i.imageModel=e=>{throw new v({modelId:e,modelType:`imageModel`})},i.tools=gn,i}_n();function vn(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function yn(e){return Object.fromEntries([...e.headers])}function bn(e=globalThis){return e.window?`runtime/browser`:e.navigator?.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:e.process?.versions?.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?`runtime/vercel-edge`:`runtime/unknown`}function xn(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function Sn(e,...t){let n=xn(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var Cn=(({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new p({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();function wn(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Tn=[`fetch failed`,`failed to fetch`];function En({error:e,url:t,requestBodyValues:n}){if(wn(e))return e;if(e instanceof TypeError&&Tn.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new s({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}var Dn=`3.0.10`;function On({apiKey:e,environmentVariableName:t,apiKeyParameterName:n=`apiKey`,description:r}){if(typeof e==`string`)return e;if(e!=null)throw new _({message:`${r} API key must be a string.`});if(typeof process>`u`)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!=`string`)throw new _({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var kn=/"__proto__"\s*:/,An=/"constructor"\s*:/;function jn(e){let t=JSON.parse(e);return typeof t!=`object`||!t||kn.test(e)===!1&&An.test(e)===!1?t:Mn(t)}function Mn(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function Nn(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return jn(e)}finally{Error.stackTraceLimit=t}}var Pn=Symbol.for(`vercel.ai.validator`);function Fn(e){return{[Pn]:!0,validate:e}}function In(e){return typeof e==`object`&&!!e&&Pn in e&&e[Pn]===!0&&`validate`in e}function Ln(e){return In(e)?e:Rn(e)}function Rn(e){return Fn(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new x({value:t,cause:n.issues})}})}async function zn({value:e,schema:t}){let n=await Bn({value:e,schema:t});if(!n.success)throw x.wrap({value:e,cause:n.error});return n.value}async function Bn({value:e,schema:t}){let n=Ln(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:x.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:x.wrap({value:e,cause:t}),rawValue:e}}}async function Vn({text:e,schema:t}){try{let n=Nn(e);return t==null?n:zn({value:n,schema:t})}catch(t){throw g.isInstance(t)||x.isInstance(t)?t:new g({text:e,cause:t})}}async function Hn({text:e,schema:t}){try{let n=Nn(e);return t==null?{success:!0,value:n,rawValue:n}:await Bn({value:n,schema:t})}catch(t){return{success:!1,error:g.isInstance(t)?t:new g({text:e,cause:t}),rawValue:void 0}}}function Un({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new d).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await Hn({text:e,schema:t}))}}))}async function Wn({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;let r=await Bn({value:t[e],schema:n});if(!r.success)throw new p({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:r.error});return r.value}var Gn=()=>globalThis.fetch,Kn=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>qn({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),qn=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=Gn()})=>{try{let c=await o(e,{method:`POST`,headers:Sn(t,`ai-sdk/provider-utils/${Dn}`,bn()),body:n.content,signal:a}),l=yn(c);if(!c.ok){let t;try{t=await i({response:c,url:e,requestBodyValues:n.values})}catch(t){throw wn(t)||s.isInstance(t)?t:new s({message:`Failed to process error response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw t.value}try{return await r({response:c,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(wn(t)||s.isInstance(t))?t:new s({message:`Failed to process successful response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(t){throw En({error:t,url:e,requestBodyValues:n.values})}};function Jn(e){return e}function Yn({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>Jn({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function Xn({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>Jn({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:r,execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}async function Zn(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var Qn=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),c=yn(r);if(o.trim()===``)return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})};try{let l=await Vn({text:o,schema:e});return{responseHeaders:c,value:new s({message:t(l),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})}}},$n=e=>async({response:t})=>{let n=yn(t);if(t.body==null)throw new u({});return{responseHeaders:n,value:Un({stream:t.body,schema:e})}},er=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await Hn({text:i,schema:e}),o=yn(t);if(!a.success)throw new s({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},{btoa:tr,atob:nr}=globalThis;function rr(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return tr(t)}function ir(e){return e instanceof Uint8Array?rr(e):e}function ar(e){return e?.replace(/\/$/,``)}var or=`2.0.17`,sr=N.object({error:N.object({code:N.number().nullable(),message:N.string(),status:N.string()})}),cr=Qn({errorSchema:sr,errorToMessage:e=>e.error.message}),lr=N.object({outputDimensionality:N.number().optional(),taskType:N.enum([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional()}),ur=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){let i=await Wn({provider:`google`,providerOptions:r,schema:lr});if(e.length>this.maxEmbeddingsPerCall)throw new b({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let a=vn(await Zn(this.config.headers),t);if(e.length===1){let{responseHeaders:t,value:r,rawValue:o}=await Kn({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:a,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType},failedResponseHandler:cr,successfulResponseHandler:er(fr),abortSignal:n,fetch:this.config.fetch});return{embeddings:[r.embedding.values],usage:void 0,response:{headers:t,body:o}}}let{responseHeaders:o,value:s,rawValue:c}=await Kn({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:a,body:{requests:e.map(e=>({model:`models/${this.modelId}`,content:{role:`user`,parts:[{text:e}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType}))},failedResponseHandler:cr,successfulResponseHandler:er(dr),abortSignal:n,fetch:this.config.fetch});return{embeddings:s.embeddings.map(e=>e.values),usage:void 0,response:{headers:o,body:c}}}},dr=N.object({embeddings:N.array(N.object({values:N.array(N.number())}))}),fr=N.object({embedding:N.object({values:N.array(N.number())})});function pr(e){if(e==null||mr(e))return;if(typeof e==`boolean`)return{type:`boolean`,properties:{}};let{type:t,description:n,required:r,properties:i,items:a,allOf:o,anyOf:s,oneOf:c,format:l,const:u,minLength:d,enum:f}=e,p={};if(n&&(p.description=n),r&&(p.required=r),l&&(p.format=l),u!==void 0&&(p.enum=[u]),t&&(Array.isArray(t)?t.includes(`null`)?(p.type=t.filter(e=>e!==`null`)[0],p.nullable=!0):p.type=t:t===`null`?p.type=`null`:p.type=t),f!==void 0&&(p.enum=f),i!=null&&(p.properties=Object.entries(i).reduce((e,[t,n])=>(e[t]=pr(n),e),{})),a&&(p.items=Array.isArray(a)?a.map(pr):pr(a)),o&&(p.allOf=o.map(pr)),s)if(s.some(e=>typeof e==`object`&&e?.type===`null`)){let e=s.filter(e=>!(typeof e==`object`&&e?.type===`null`));if(e.length===1){let t=pr(e[0]);typeof t==`object`&&(p.nullable=!0,Object.assign(p,t))}else p.anyOf=e.map(pr),p.nullable=!0}else p.anyOf=s.map(pr);return c&&(p.oneOf=c.map(pr)),d!==void 0&&(p.minLength=d),p}function mr(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}function hr(e,t){let n=[],r=[],i=!0,a=t?.isGemmaModel??!1;for(let{role:t,content:a}of e)switch(t){case`system`:if(!i)throw new S({functionality:`system messages are only supported at the beginning of the conversation`});n.push({text:a});break;case`user`:{i=!1;let e=[];for(let t of a)switch(t.type){case`text`:e.push({text:t.text});break;case`file`:{let n=t.mediaType===`image/*`?`image/jpeg`:t.mediaType;e.push(t.data instanceof URL?{fileData:{mimeType:n,fileUri:t.data.toString()}}:{inlineData:{mimeType:n,data:ir(t.data)}});break}}r.push({role:`user`,parts:e});break}case`assistant`:i=!1,r.push({role:`model`,parts:a.map(e=>{switch(e.type){case`text`:return e.text.length===0?void 0:{text:e.text,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`reasoning`:return e.text.length===0?void 0:{text:e.text,thought:!0,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`file`:if(e.mediaType!==`image/png`)throw new S({functionality:`Only PNG images are supported in assistant messages`});if(e.data instanceof URL)throw new S({functionality:`File data URLs in assistant messages are not supported`});return{inlineData:{mimeType:e.mediaType,data:ir(e.data)}};case`tool-call`:return{functionCall:{name:e.toolName,args:e.input},thoughtSignature:e.providerOptions?.google?.thoughtSignature}}}).filter(e=>e!==void 0)});break;case`tool`:{i=!1;let e=[];for(let t of a){let n=t.output;if(n.type===`content`)for(let r of n.value)switch(r.type){case`text`:e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:r.text}}});break;case`media`:e.push({inlineData:{mimeType:r.mediaType,data:r.data}},{text:`Tool executed successfully and returned this image as a response`});break;default:e.push({text:JSON.stringify(r)});break}else e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:n.value}}})}r.push({role:`user`,parts:e});break}}if(a&&n.length>0&&r.length>0&&r[0].role===`user`){let e=n.map(e=>e.text).join(`
|
|
1
|
+
import{__commonJSMin as e,__esmMin as t,__export as n,__reExport as r,__require as i,__toCommonJS as a,__toESM as o}from"../chunk-D9KrCrVq.js";import{APICallError as s,APIServerURLEnvironmentVariable as c,Agent as l,EmptyResponseBodyError as u,EventSourceParserStream as d,Hono as f,InvalidArgumentError as p,InvalidPromptError as m,InvalidResponseDataError as h,JSONParseError as g,LoadAPIKeyError as _,NoSuchModelError as v,StreamResponseFormatHeader as y,TooManyEmbeddingValuesForCallError as b,TypeValidationError as x,UnsupportedFunctionalityError as S,createGatewayProvider as C,createServerAdapter as w,hc as T,isToolApprovalOutput as E,lastUIOptions as D,tools as O,validator as k}from"../index.node-CITcyk6b.js";import"../token-error-488npYdU.js";import"../esm-CbZfjZBn.js";import{resolveConfig as A}from"../build-DYI55eX2.js";import{createRequire as j}from"node:module";import M,{z as N}from"zod/v4";import{ZodFirstPartyTypeKind as ee}from"zod/v3";import{Buffer as te}from"node:buffer";import*as P from"node:fs";import F,{existsSync as I,mkdirSync as ne,readFileSync as L,unlinkSync as re,writeFileSync as R}from"node:fs";import{fileURLToPath as ie}from"node:url";import{Writable as z}from"node:stream";import{promisify as ae,stripVTControlCharacters as oe}from"node:util";import{createHash as se}from"node:crypto";import ce,{createServer as le}from"http";import{dirname as B,join as ue}from"path";import{existsSync as de,mkdirSync as fe,readFileSync as pe,watch as me,writeFileSync as he}from"fs";import{convertToModelMessages as ge,isToolOrDynamicToolUIPart as _e,readUIMessageStream as ve,streamText as ye,tool as be}from"ai";import{readFile as xe,stat as V,writeFile as Se}from"fs/promises";import{spawn as Ce}from"child_process";import{createContext as we,useCallback as H,useEffect as U,useMemo as Te,useRef as W,useState as G}from"react";import K,{z as q}from"zod";import*as Ee from"node:path";import De,{dirname as Oe,join as ke}from"node:path";import J,{stdin as Ae,stdout as je}from"node:process";import Me from"node:os";import Ne from"node:tty";import*as Pe from"node:readline";import Fe from"node:readline";import Ie,{execFile as Le}from"node:child_process";import Re,{constants as ze}from"node:fs/promises";import"@blink-sdk/compute-protocol/client";import{createInMemoryClientServer as Be}from"@blink-sdk/compute-protocol/transport";function Ve(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function He(e){return Object.fromEntries([...e.headers])}function Ue(e=globalThis){return e.window?`runtime/browser`:e.navigator?.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:e.process?.versions?.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?`runtime/vercel-edge`:`runtime/unknown`}function We(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function Ge(e,...t){let n=We(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var Ke=(({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new p({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();function qe(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Je=[`fetch failed`,`failed to fetch`];function Ye({error:e,url:t,requestBodyValues:n}){if(qe(e))return e;if(e instanceof TypeError&&Je.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new s({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}var Xe=`3.0.10`;function Ze({apiKey:e,environmentVariableName:t,apiKeyParameterName:n=`apiKey`,description:r}){if(typeof e==`string`)return e;if(e!=null)throw new _({message:`${r} API key must be a string.`});if(typeof process>`u`)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!=`string`)throw new _({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var Qe=/"__proto__"\s*:/,$e=/"constructor"\s*:/;function et(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Qe.test(e)===!1&&$e.test(e)===!1?t:tt(t)}function tt(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function nt(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return et(e)}finally{Error.stackTraceLimit=t}}var rt=Symbol.for(`vercel.ai.validator`);function it(e){return{[rt]:!0,validate:e}}function at(e){return typeof e==`object`&&!!e&&rt in e&&e[rt]===!0&&`validate`in e}function ot(e){return at(e)?e:st(e)}function st(e){return it(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new x({value:t,cause:n.issues})}})}async function ct({value:e,schema:t}){let n=await lt({value:e,schema:t});if(!n.success)throw x.wrap({value:e,cause:n.error});return n.value}async function lt({value:e,schema:t}){let n=ot(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:x.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:x.wrap({value:e,cause:t}),rawValue:e}}}async function ut({text:e,schema:t}){try{let n=nt(e);return t==null?n:ct({value:n,schema:t})}catch(t){throw g.isInstance(t)||x.isInstance(t)?t:new g({text:e,cause:t})}}async function dt({text:e,schema:t}){try{let n=nt(e);return t==null?{success:!0,value:n,rawValue:n}:await lt({value:n,schema:t})}catch(t){return{success:!1,error:g.isInstance(t)?t:new g({text:e,cause:t}),rawValue:void 0}}}function ft({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new d).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await dt({text:e,schema:t}))}}))}async function pt({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;let r=await lt({value:t[e],schema:n});if(!r.success)throw new p({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:r.error});return r.value}var mt=()=>globalThis.fetch,ht=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>gt({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),gt=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=mt()})=>{try{let c=await o(e,{method:`POST`,headers:Ge(t,`ai-sdk/provider-utils/${Xe}`,Ue()),body:n.content,signal:a}),l=He(c);if(!c.ok){let t;try{t=await i({response:c,url:e,requestBodyValues:n.values})}catch(t){throw qe(t)||s.isInstance(t)?t:new s({message:`Failed to process error response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw t.value}try{return await r({response:c,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(qe(t)||s.isInstance(t))?t:new s({message:`Failed to process successful response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(t){throw Ye({error:t,url:e,requestBodyValues:n.values})}};function _t(e){return e}function vt({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>_t({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function yt({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>_t({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:r,execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}async function bt(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var xt=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),c=He(r);if(o.trim()===``)return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})};try{let l=await ut({text:o,schema:e});return{responseHeaders:c,value:new s({message:t(l),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})}}},St=e=>async({response:t})=>{let n=He(t);if(t.body==null)throw new u({});return{responseHeaders:n,value:ft({stream:t.body,schema:e})}},Ct=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await dt({text:i,schema:e}),o=He(t);if(!a.success)throw new s({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},{btoa:wt,atob:Tt}=globalThis;function Et(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return wt(t)}function Dt(e){return e instanceof Uint8Array?Et(e):e}function Ot(e){return e?.replace(/\/$/,``)}var kt=`2.0.23`,At=N.object({type:N.literal(`error`),error:N.object({type:N.string(),message:N.string()})}),jt=xt({errorSchema:At,errorToMessage:e=>e.error.message}),Mt=N.object({citations:N.object({enabled:N.boolean()}).optional(),title:N.string().optional(),context:N.string().optional()}),Nt=N.object({sendReasoning:N.boolean().optional(),thinking:N.object({type:N.union([N.literal(`enabled`),N.literal(`disabled`)]),budgetTokens:N.number().optional()}).optional(),disableParallelToolUse:N.boolean().optional(),cacheControl:N.object({type:N.literal(`ephemeral`),ttl:N.union([N.literal(`5m`),N.literal(`1h`)]).optional()}).optional()});function Pt(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var Ft=N.object({maxCharacters:N.number().optional()}),It=vt({id:`anthropic.text_editor_20250728`,name:`str_replace_based_edit_tool`,inputSchema:N.object({command:N.enum([`view`,`create`,`str_replace`,`insert`]),path:N.string(),file_text:N.string().optional(),insert_line:N.number().int().optional(),new_str:N.string().optional(),old_str:N.string().optional(),view_range:N.array(N.number().int()).optional()})}),Lt=(e={})=>It(e),Rt=N.object({maxUses:N.number().optional(),allowedDomains:N.array(N.string()).optional(),blockedDomains:N.array(N.string()).optional(),userLocation:N.object({type:N.literal(`approximate`),city:N.string().optional(),region:N.string().optional(),country:N.string().optional(),timezone:N.string().optional()}).optional()}),zt=N.array(N.object({url:N.string(),title:N.string(),pageAge:N.string().nullable(),encryptedContent:N.string(),type:N.literal(`web_search_result`)})),Bt=yt({id:`anthropic.web_search_20250305`,name:`web_search`,inputSchema:N.object({query:N.string()}),outputSchema:zt}),Vt=(e={})=>Bt(e),Ht=N.object({maxUses:N.number().optional(),allowedDomains:N.array(N.string()).optional(),blockedDomains:N.array(N.string()).optional(),citations:N.object({enabled:N.boolean()}).optional(),maxContentTokens:N.number().optional()}),Ut=N.object({type:N.literal(`web_fetch_result`),url:N.string(),content:N.object({type:N.literal(`document`),title:N.string(),citations:N.object({enabled:N.boolean()}).optional(),source:N.union([N.object({type:N.literal(`base64`),mediaType:N.literal(`application/pdf`),data:N.string()}),N.object({type:N.literal(`text`),mediaType:N.literal(`text/plain`),data:N.string()})])}),retrievedAt:N.string().nullable()}),Wt=yt({id:`anthropic.web_fetch_20250910`,name:`web_fetch`,inputSchema:N.object({url:N.string()}),outputSchema:Ut}),Gt=(e={})=>Wt(e);function Kt({tools:e,toolChoice:t,disableParallelToolUse:n}){e=e?.length?e:void 0;let r=[],i=new Set;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};let a=[];for(let t of e)switch(t.type){case`function`:{let e=Pt(t.providerOptions);a.push({name:t.name,description:t.description,input_schema:t.inputSchema,cache_control:e});break}case`provider-defined`:switch(t.id){case`anthropic.code_execution_20250522`:i.add(`code-execution-2025-05-22`),a.push({type:`code_execution_20250522`,name:`code_execution`});break;case`anthropic.computer_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`computer`,type:`computer_20250124`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.computer_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`computer`,type:`computer_20241022`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.text_editor_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_editor`,type:`text_editor_20250124`});break;case`anthropic.text_editor_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`str_replace_editor`,type:`text_editor_20241022`});break;case`anthropic.text_editor_20250429`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`});break;case`anthropic.text_editor_20250728`:{let e=Ft.parse(t.args);a.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250728`,max_characters:e.maxCharacters});break}case`anthropic.bash_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`bash`,type:`bash_20250124`});break;case`anthropic.bash_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`bash`,type:`bash_20241022`});break;case`anthropic.web_fetch_20250910`:{i.add(`web-fetch-2025-09-10`);let e=Ht.parse(t.args);a.push({type:`web_fetch_20250910`,name:`web_fetch`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens});break}case`anthropic.web_search_20250305`:{let e=Rt.parse(t.args);a.push({type:`web_search_20250305`,name:`web_search`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation});break}default:r.push({type:`unsupported-tool`,tool:t});break}break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:a,toolChoice:n?{type:`auto`,disable_parallel_tool_use:n}:void 0,toolWarnings:r,betas:i};let o=t.type;switch(o){case`auto`:return{tools:a,toolChoice:{type:`auto`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`required`:return{tools:a,toolChoice:{type:`any`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};case`tool`:return{tools:a,toolChoice:{type:`tool`,name:t.toolName,disable_parallel_tool_use:n},toolWarnings:r,betas:i};default:throw new S({functionality:`tool choice type: ${o}`})}}var qt=N.object({type:N.literal(`code_execution_result`),stdout:N.string(),stderr:N.string(),return_code:N.number()}),Jt=yt({id:`anthropic.code_execution_20250522`,name:`code_execution`,inputSchema:N.object({code:N.string()}),outputSchema:qt}),Yt=(e={})=>Jt(e);function Xt(e){if(typeof e==`string`)return Buffer.from(e,`base64`).toString(`utf-8`);if(e instanceof Uint8Array)return new TextDecoder().decode(e);throw e instanceof URL?new S({functionality:`URL-based text documents are not supported for citations`}):new S({functionality:`unsupported data type for text documents: ${typeof e}`})}async function Zt({prompt:e,sendReasoning:t,warnings:n}){let r=new Set,i=Qt(e),a,o=[];async function s(e){return(await pt({provider:`anthropic`,providerOptions:e,schema:Mt}))?.citations?.enabled??!1}async function c(e){let t=await pt({provider:`anthropic`,providerOptions:e,schema:Mt});return{title:t?.title,context:t?.context}}for(let e=0;e<i.length;e++){let l=i[e],u=e===i.length-1,d=l.type;switch(d){case`system`:if(a!=null)throw new S({functionality:`Multiple system messages that are separated by user/assistant messages`});a=l.messages.map(({content:e,providerOptions:t})=>({type:`text`,text:e,cache_control:Pt(t)}));break;case`user`:{let e=[];for(let t of l.messages){let{role:n,content:i}=t;switch(n){case`user`:for(let n=0;n<i.length;n++){let a=i[n],o=n===i.length-1,l=Pt(a.providerOptions)??(o?Pt(t.providerOptions):void 0);switch(a.type){case`text`:e.push({type:`text`,text:a.text,cache_control:l});break;case`file`:if(a.mediaType.startsWith(`image/`))e.push({type:`image`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`base64`,media_type:a.mediaType===`image/*`?`image/jpeg`:a.mediaType,data:Dt(a.data)},cache_control:l});else if(a.mediaType===`application/pdf`){r.add(`pdfs-2024-09-25`);let t=await s(a.providerOptions),n=await c(a.providerOptions);e.push({type:`document`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`base64`,media_type:`application/pdf`,data:Dt(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else if(a.mediaType===`text/plain`){let t=await s(a.providerOptions),n=await c(a.providerOptions);e.push({type:`document`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`text`,media_type:`text/plain`,data:Xt(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else throw new S({functionality:`media type: ${a.mediaType}`});break}}break;case`tool`:for(let n=0;n<i.length;n++){let r=i[n],a=n===i.length-1,o=Pt(r.providerOptions)??(a?Pt(t.providerOptions):void 0),s=r.output,c;switch(s.type){case`content`:c=s.value.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text,cache_control:void 0};case`media`:if(e.mediaType.startsWith(`image/`))return{type:`image`,source:{type:`base64`,media_type:e.mediaType,data:e.data},cache_control:void 0};throw new S({functionality:`media type: ${e.mediaType}`})}});break;case`text`:case`error-text`:c=s.value;break;case`json`:case`error-json`:default:c=JSON.stringify(s.value);break}e.push({type:`tool_result`,tool_use_id:r.toolCallId,content:c,is_error:s.type===`error-text`||s.type===`error-json`?!0:void 0,cache_control:o})}break;default:{let e=n;throw Error(`Unsupported role: ${e}`)}}}o.push({role:`user`,content:e});break}case`assistant`:{let e=[];for(let r=0;r<l.messages.length;r++){let i=l.messages[r],a=r===l.messages.length-1,{content:o}=i;for(let r=0;r<o.length;r++){let s=o[r],c=r===o.length-1,l=Pt(s.providerOptions)??(c?Pt(i.providerOptions):void 0);switch(s.type){case`text`:e.push({type:`text`,text:u&&a&&c?s.text.trim():s.text,cache_control:l});break;case`reasoning`:if(t){let t=await pt({provider:`anthropic`,providerOptions:s.providerOptions,schema:cn});t==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):t.signature==null?t.redactedData==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):e.push({type:`redacted_thinking`,data:t.redactedData,cache_control:l}):e.push({type:`thinking`,thinking:s.text,signature:t.signature,cache_control:l})}else n.push({type:`other`,message:`sending reasoning content is disabled for this model`});break;case`tool-call`:if(s.providerExecuted){s.toolName===`code_execution`||s.toolName===`web_fetch`||s.toolName===`web_search`?e.push({type:`server_tool_use`,id:s.toolCallId,name:s.toolName,input:s.input,cache_control:l}):n.push({type:`other`,message:`provider executed tool call for tool ${s.toolName} is not supported`});break}e.push({type:`tool_use`,id:s.toolCallId,name:s.toolName,input:s.input,cache_control:l});break;case`tool-result`:if(s.toolName===`code_execution`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=qt.parse(t.value);e.push({type:`code_execution_tool_result`,tool_use_id:s.toolCallId,content:{type:r.type,stdout:r.stdout,stderr:r.stderr,return_code:r.return_code},cache_control:l});break}if(s.toolName===`web_fetch`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=Ut.parse(t.value);e.push({type:`web_fetch_tool_result`,tool_use_id:s.toolCallId,content:{type:`web_fetch_result`,url:r.url,retrieved_at:r.retrievedAt,content:{type:`document`,title:r.content.title,citations:r.content.citations,source:{type:r.content.source.type,media_type:r.content.source.mediaType,data:r.content.source.data}}},cache_control:l});break}if(s.toolName===`web_search`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=zt.parse(t.value);e.push({type:`web_search_tool_result`,tool_use_id:s.toolCallId,content:r.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:l});break}n.push({type:`other`,message:`provider executed tool result for tool ${s.toolName} is not supported`});break}}}o.push({role:`assistant`,content:e});break}default:{let e=d;throw Error(`content type: ${e}`)}}}return{prompt:{system:a,messages:o},betas:r}}function Qt(e){let t=[],n;for(let r of e){let{role:e}=r;switch(e){case`system`:n?.type!==`system`&&(n={type:`system`,messages:[]},t.push(n)),n.messages.push(r);break;case`assistant`:n?.type!==`assistant`&&(n={type:`assistant`,messages:[]},t.push(n)),n.messages.push(r);break;case`user`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;case`tool`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;default:{let t=e;throw Error(`Unsupported role: ${t}`)}}}return t}function $t({finishReason:e,isJsonResponseFromTool:t}){switch(e){case`pause_turn`:case`end_turn`:case`stop_sequence`:return`stop`;case`refusal`:return`content-filter`;case`tool_use`:return t?`stop`:`tool-calls`;case`max_tokens`:return`length`;default:return`unknown`}}var en={webSearchResult:N.object({type:N.literal(`web_search_result_location`),cited_text:N.string(),url:N.string(),title:N.string(),encrypted_index:N.string()}),pageLocation:N.object({type:N.literal(`page_location`),cited_text:N.string(),document_index:N.number(),document_title:N.string().nullable(),start_page_number:N.number(),end_page_number:N.number()}),charLocation:N.object({type:N.literal(`char_location`),cited_text:N.string(),document_index:N.number(),document_title:N.string().nullable(),start_char_index:N.number(),end_char_index:N.number()})},tn=N.discriminatedUnion(`type`,[en.webSearchResult,en.pageLocation,en.charLocation]);N.discriminatedUnion(`type`,[en.pageLocation,en.charLocation]);function nn(e,t,n,r){if(e.type===`page_location`||e.type===`char_location`){let i=rn(e,t,n);i&&r(i)}}function rn(e,t,n){let r=t[e.document_index];if(!r)return null;let i=e.type===`page_location`?{citedText:e.cited_text,startPageNumber:e.start_page_number,endPageNumber:e.end_page_number}:{citedText:e.cited_text,startCharIndex:e.start_char_index,endCharIndex:e.end_char_index};return{type:`source`,sourceType:`document`,id:n(),mediaType:r.mediaType,title:e.document_title??r.title,filename:r.filename,providerMetadata:{anthropic:i}}}var an=class{constructor(e,t){this.specificationVersion=`v2`,this.modelId=e,this.config=t,this.generateId=t.generateId??Ke}supportsUrl(e){return e.protocol===`https:`}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:t=4096,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){let p=[];a!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),l!=null&&p.push({type:`unsupported-setting`,setting:`seed`}),c?.type===`json`&&(c.schema==null?p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format requires a schema. The response format is ignored.`}):u!=null&&p.push({type:`unsupported-setting`,setting:`tools`,details:`JSON response format does not support tools. The provided tools are ignored.`}));let m=c?.type===`json`&&c.schema!=null?{type:`function`,name:`json`,description:`Respond with a JSON object.`,inputSchema:c.schema}:void 0,h=await pt({provider:`anthropic`,providerOptions:f,schema:Nt}),{prompt:g,betas:_}=await Zt({prompt:e,sendReasoning:h?.sendReasoning??!0,warnings:p}),v=h?.thinking?.type===`enabled`,y=h?.thinking?.budgetTokens,b={model:this.modelId,max_tokens:t,temperature:n,top_k:i,top_p:r,stop_sequences:s,...v&&{thinking:{type:`enabled`,budget_tokens:y}},system:g.system,messages:g.messages};if(v){if(y==null)throw new S({functionality:`thinking requires a budget`});b.temperature!=null&&(b.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported when thinking is enabled`})),i!=null&&(b.top_k=void 0,p.push({type:`unsupported-setting`,setting:`topK`,details:`topK is not supported when thinking is enabled`})),r!=null&&(b.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported when thinking is enabled`})),b.max_tokens=t+y}let{tools:x,toolChoice:C,toolWarnings:w,betas:T}=Kt(m==null?{tools:u??[],toolChoice:d,disableParallelToolUse:h?.disableParallelToolUse}:{tools:[m],toolChoice:{type:`tool`,toolName:m.name},disableParallelToolUse:!0});return{args:{...b,tools:x,tool_choice:C},warnings:[...p,...w],betas:new Set([..._,...T]),usesJsonResponseTool:m!=null}}async getHeaders({betas:e,headers:t}){return Ve(await bt(this.config.headers),e.size>0?{"anthropic-beta":Array.from(e).join(`,`)}:{},t)}buildRequestUrl(e){var t;return(t=this.config).buildRequestUrl?.call(t,this.config.baseURL,e)??`${this.config.baseURL}/messages`}transformRequestBody(e){var t;return(t=this.config).transformRequestBody?.call(t,e)??e}extractCitationDocuments(e){return e.filter(e=>e.role===`user`).flatMap(e=>e.content).filter(e=>e.type!==`file`||e.mediaType!==`application/pdf`&&e.mediaType!==`text/plain`?!1:e.providerOptions?.anthropic?.citations?.enabled??!1).map(e=>{let t=e;return{title:t.filename??`Untitled Document`,filename:t.filename,mediaType:t.mediaType}})}async doGenerate(e){let{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),a=this.extractCitationDocuments(e.prompt),{responseHeaders:o,value:s,rawValue:c}=await ht({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(t),failedResponseHandler:jt,successfulResponseHandler:Ct(on),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=[];for(let e of s.content)switch(e.type){case`text`:if(!i&&(l.push({type:`text`,text:e.text}),e.citations))for(let t of e.citations)nn(t,a,this.generateId,e=>l.push(e));break;case`thinking`:l.push({type:`reasoning`,text:e.thinking,providerMetadata:{anthropic:{signature:e.signature}}});break;case`redacted_thinking`:l.push({type:`reasoning`,text:``,providerMetadata:{anthropic:{redactedData:e.data}}});break;case`tool_use`:l.push(i?{type:`text`,text:JSON.stringify(e.input)}:{type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input)});break;case`server_tool_use`:(e.name===`web_search`||e.name===`code_execution`||e.name===`web_fetch`)&&l.push({type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input),providerExecuted:!0});break;case`web_fetch_tool_result`:e.content.type===`web_fetch_result`?l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,result:{type:`web_fetch_result`,url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}},providerExecuted:!0}):e.content.type===`web_fetch_tool_result_error`&&l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,isError:!0,result:{type:`web_fetch_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break;case`web_search_tool_result`:if(Array.isArray(e.content)){l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type})),providerExecuted:!0});for(let t of e.content)l.push({type:`source`,sourceType:`url`,id:this.generateId(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break;case`code_execution_tool_result`:e.content.type===`code_execution_result`?l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break}return{content:l,finishReason:$t({finishReason:s.stop_reason,isJsonResponseFromTool:i}),usage:{inputTokens:s.usage.input_tokens,outputTokens:s.usage.output_tokens,totalTokens:s.usage.input_tokens+s.usage.output_tokens,cachedInputTokens:s.usage.cache_read_input_tokens??void 0},request:{body:t},response:{id:s.id??void 0,modelId:s.model??void 0,headers:o,body:c},warnings:n,providerMetadata:{anthropic:{usage:s.usage,cacheCreationInputTokens:s.usage.cache_creation_input_tokens??null,stopSequence:s.stop_sequence??null}}}}async doStream(e){let{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),a=this.extractCitationDocuments(e.prompt),o={...t,stream:!0},{responseHeaders:s,value:c}=await ht({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(o),failedResponseHandler:jt,successfulResponseHandler:St(sn),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=`unknown`,u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},d={},f,p=null,m=null,h,g=this.generateId;return{stream:c.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let r=t.value;switch(r.type){case`ping`:return;case`content_block_start`:{let e=r.content_block.type;switch(h=e,e){case`text`:d[r.index]={type:`text`},n.enqueue({type:`text-start`,id:String(r.index)});return;case`thinking`:d[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index)});return;case`redacted_thinking`:d[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index),providerMetadata:{anthropic:{redactedData:r.content_block.data}}});return;case`tool_use`:d[r.index]=i?{type:`text`}:{type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``},n.enqueue(i?{type:`text-start`,id:String(r.index)}:{type:`tool-input-start`,id:r.content_block.id,toolName:r.content_block.name});return;case`server_tool_use`:(r.content_block.name===`web_fetch`||r.content_block.name===`web_search`||r.content_block.name===`code_execution`)&&(d[r.index]={type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``,providerExecuted:!0},n.enqueue({type:`tool-input-start`,id:r.content_block.id,toolName:r.content_block.name,providerExecuted:!0}));return;case`web_fetch_tool_result`:{let e=r.content_block;e.content.type===`web_fetch_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,result:{type:`web_fetch_result`,url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}}}):e.content.type===`web_fetch_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,isError:!0,result:{type:`web_fetch_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}case`web_search_tool_result`:{let e=r.content_block;if(Array.isArray(e.content)){n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type})),providerExecuted:!0});for(let t of e.content)n.enqueue({type:`source`,sourceType:`url`,id:g(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}case`code_execution_tool_result`:{let e=r.content_block;e.content.type===`code_execution_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}default:{let t=e;throw Error(`Unsupported content block type: ${t}`)}}}case`content_block_stop`:if(d[r.index]!=null){let e=d[r.index];switch(e.type){case`text`:n.enqueue({type:`text-end`,id:String(r.index)});break;case`reasoning`:n.enqueue({type:`reasoning-end`,id:String(r.index)});break;case`tool-call`:i||(n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue(e));break}delete d[r.index]}h=void 0;return;case`content_block_delta`:{let e=r.delta.type;switch(e){case`text_delta`:if(i)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:r.delta.text});return;case`thinking_delta`:n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:r.delta.thinking});return;case`signature_delta`:h===`thinking`&&n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:``,providerMetadata:{anthropic:{signature:r.delta.signature}}});return;case`input_json_delta`:{let e=d[r.index],t=r.delta.partial_json;if(i){if(e?.type!==`text`)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:t})}else{if(e?.type!==`tool-call`)return;n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:t}),e.input+=t}return}case`citations_delta`:{let e=r.delta.citation;nn(e,a,g,e=>n.enqueue(e));return}default:{let t=e;throw Error(`Unsupported delta type: ${t}`)}}}case`message_start`:u.inputTokens=r.message.usage.input_tokens,u.cachedInputTokens=r.message.usage.cache_read_input_tokens??void 0,f={...r.message.usage},p=r.message.usage.cache_creation_input_tokens??null,n.enqueue({type:`response-metadata`,id:r.message.id??void 0,modelId:r.message.model??void 0});return;case`message_delta`:u.outputTokens=r.usage.output_tokens,u.totalTokens=(u.inputTokens??0)+(r.usage.output_tokens??0),l=$t({finishReason:r.delta.stop_reason,isJsonResponseFromTool:i}),m=r.delta.stop_sequence??null,f={...f,...r.usage};return;case`message_stop`:n.enqueue({type:`finish`,finishReason:l,usage:u,providerMetadata:{anthropic:{usage:f??null,cacheCreationInputTokens:p,stopSequence:m}}});return;case`error`:n.enqueue({type:`error`,error:r.error});return;default:{let e=r;throw Error(`Unsupported chunk type: ${e}`)}}}})),request:{body:o},response:{headers:s}}}},on=N.object({type:N.literal(`message`),id:N.string().nullish(),model:N.string().nullish(),content:N.array(N.discriminatedUnion(`type`,[N.object({type:N.literal(`text`),text:N.string(),citations:N.array(tn).optional()}),N.object({type:N.literal(`thinking`),thinking:N.string(),signature:N.string()}),N.object({type:N.literal(`redacted_thinking`),data:N.string()}),N.object({type:N.literal(`tool_use`),id:N.string(),name:N.string(),input:N.unknown()}),N.object({type:N.literal(`server_tool_use`),id:N.string(),name:N.string(),input:N.record(N.string(),N.unknown()).nullish()}),N.object({type:N.literal(`web_fetch_tool_result`),tool_use_id:N.string(),content:N.union([N.object({type:N.literal(`web_fetch_result`),url:N.string(),retrieved_at:N.string(),content:N.object({type:N.literal(`document`),title:N.string().nullable(),citations:N.object({enabled:N.boolean()}).optional(),source:N.object({type:N.literal(`text`),media_type:N.string(),data:N.string()})})}),N.object({type:N.literal(`web_fetch_tool_result_error`),error_code:N.string()})])}),N.object({type:N.literal(`web_search_tool_result`),tool_use_id:N.string(),content:N.union([N.array(N.object({type:N.literal(`web_search_result`),url:N.string(),title:N.string(),encrypted_content:N.string(),page_age:N.string().nullish()})),N.object({type:N.literal(`web_search_tool_result_error`),error_code:N.string()})])}),N.object({type:N.literal(`code_execution_tool_result`),tool_use_id:N.string(),content:N.union([N.object({type:N.literal(`code_execution_result`),stdout:N.string(),stderr:N.string(),return_code:N.number()}),N.object({type:N.literal(`code_execution_tool_result_error`),error_code:N.string()})])})])),stop_reason:N.string().nullish(),stop_sequence:N.string().nullish(),usage:N.looseObject({input_tokens:N.number(),output_tokens:N.number(),cache_creation_input_tokens:N.number().nullish(),cache_read_input_tokens:N.number().nullish()})}),sn=N.discriminatedUnion(`type`,[N.object({type:N.literal(`message_start`),message:N.object({id:N.string().nullish(),model:N.string().nullish(),usage:N.looseObject({input_tokens:N.number(),cache_creation_input_tokens:N.number().nullish(),cache_read_input_tokens:N.number().nullish()})})}),N.object({type:N.literal(`content_block_start`),index:N.number(),content_block:N.discriminatedUnion(`type`,[N.object({type:N.literal(`text`),text:N.string()}),N.object({type:N.literal(`thinking`),thinking:N.string()}),N.object({type:N.literal(`tool_use`),id:N.string(),name:N.string()}),N.object({type:N.literal(`redacted_thinking`),data:N.string()}),N.object({type:N.literal(`server_tool_use`),id:N.string(),name:N.string(),input:N.record(N.string(),N.unknown()).nullish()}),N.object({type:N.literal(`web_fetch_tool_result`),tool_use_id:N.string(),content:N.union([N.object({type:N.literal(`web_fetch_result`),url:N.string(),retrieved_at:N.string(),content:N.object({type:N.literal(`document`),title:N.string().nullable(),citations:N.object({enabled:N.boolean()}).optional(),source:N.object({type:N.literal(`text`),media_type:N.string(),data:N.string()})})}),N.object({type:N.literal(`web_fetch_tool_result_error`),error_code:N.string()})])}),N.object({type:N.literal(`web_search_tool_result`),tool_use_id:N.string(),content:N.union([N.array(N.object({type:N.literal(`web_search_result`),url:N.string(),title:N.string(),encrypted_content:N.string(),page_age:N.string().nullish()})),N.object({type:N.literal(`web_search_tool_result_error`),error_code:N.string()})])}),N.object({type:N.literal(`code_execution_tool_result`),tool_use_id:N.string(),content:N.union([N.object({type:N.literal(`code_execution_result`),stdout:N.string(),stderr:N.string(),return_code:N.number()}),N.object({type:N.literal(`code_execution_tool_result_error`),error_code:N.string()})])})])}),N.object({type:N.literal(`content_block_delta`),index:N.number(),delta:N.discriminatedUnion(`type`,[N.object({type:N.literal(`input_json_delta`),partial_json:N.string()}),N.object({type:N.literal(`text_delta`),text:N.string()}),N.object({type:N.literal(`thinking_delta`),thinking:N.string()}),N.object({type:N.literal(`signature_delta`),signature:N.string()}),N.object({type:N.literal(`citations_delta`),citation:tn})])}),N.object({type:N.literal(`content_block_stop`),index:N.number()}),N.object({type:N.literal(`error`),error:N.object({type:N.string(),message:N.string()})}),N.object({type:N.literal(`message_delta`),delta:N.object({stop_reason:N.string().nullish(),stop_sequence:N.string().nullish()}),usage:N.looseObject({output_tokens:N.number(),cache_creation_input_tokens:N.number().nullish()})}),N.object({type:N.literal(`message_stop`)}),N.object({type:N.literal(`ping`)})]),cn=N.object({signature:N.string().optional(),redactedData:N.string().optional()}),ln=vt({id:`anthropic.bash_20241022`,name:`bash`,inputSchema:M.object({command:M.string(),restart:M.boolean().optional()})}),un=vt({id:`anthropic.bash_20250124`,name:`bash`,inputSchema:M.object({command:M.string(),restart:M.boolean().optional()})}),dn=vt({id:`anthropic.computer_20241022`,name:`computer`,inputSchema:N.object({action:N.enum([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:N.array(N.number().int()).optional(),text:N.string().optional()})}),fn=vt({id:`anthropic.computer_20250124`,name:`computer`,inputSchema:N.object({action:N.enum([`key`,`hold_key`,`type`,`cursor_position`,`mouse_move`,`left_mouse_down`,`left_mouse_up`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`triple_click`,`scroll`,`wait`,`screenshot`]),coordinate:N.tuple([N.number().int(),N.number().int()]).optional(),duration:N.number().optional(),scroll_amount:N.number().optional(),scroll_direction:N.enum([`up`,`down`,`left`,`right`]).optional(),start_coordinate:N.tuple([N.number().int(),N.number().int()]).optional(),text:N.string().optional()})}),pn=vt({id:`anthropic.text_editor_20241022`,name:`str_replace_editor`,inputSchema:N.object({command:N.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:N.string(),file_text:N.string().optional(),insert_line:N.number().int().optional(),new_str:N.string().optional(),old_str:N.string().optional(),view_range:N.array(N.number().int()).optional()})}),mn=vt({id:`anthropic.text_editor_20250124`,name:`str_replace_editor`,inputSchema:N.object({command:N.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:N.string(),file_text:N.string().optional(),insert_line:N.number().int().optional(),new_str:N.string().optional(),old_str:N.string().optional(),view_range:N.array(N.number().int()).optional()})}),hn=vt({id:`anthropic.text_editor_20250429`,name:`str_replace_based_edit_tool`,inputSchema:N.object({command:N.enum([`view`,`create`,`str_replace`,`insert`]),path:N.string(),file_text:N.string().optional(),insert_line:N.number().int().optional(),new_str:N.string().optional(),old_str:N.string().optional(),view_range:N.array(N.number().int()).optional()})}),gn={bash_20241022:ln,bash_20250124:un,codeExecution_20250522:Yt,computer_20241022:dn,computer_20250124:fn,textEditor_20241022:pn,textEditor_20250124:mn,textEditor_20250429:hn,textEditor_20250728:Lt,webFetch_20250910:Gt,webSearch_20250305:Vt};function _n(e={}){let t=Ot(e.baseURL)??`https://api.anthropic.com/v1`,n=()=>Ge({"anthropic-version":`2023-06-01`,"x-api-key":Ze({apiKey:e.apiKey,environmentVariableName:`ANTHROPIC_API_KEY`,description:`Anthropic`}),...e.headers},`ai-sdk/anthropic/${kt}`),r=r=>new an(r,{provider:`anthropic.messages`,baseURL:t,headers:n,fetch:e.fetch,generateId:e.generateId??Ke,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})}),i=function(e){if(new.target)throw Error(`The Anthropic model function cannot be called with the new keyword.`);return r(e)};return i.languageModel=r,i.chat=r,i.messages=r,i.textEmbeddingModel=e=>{throw new v({modelId:e,modelType:`textEmbeddingModel`})},i.imageModel=e=>{throw new v({modelId:e,modelType:`imageModel`})},i.tools=gn,i}_n();function vn(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function yn(e){return Object.fromEntries([...e.headers])}function bn(e=globalThis){return e.window?`runtime/browser`:e.navigator?.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:e.process?.versions?.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?`runtime/vercel-edge`:`runtime/unknown`}function xn(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function Sn(e,...t){let n=xn(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var Cn=(({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new p({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();function wn(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Tn=[`fetch failed`,`failed to fetch`];function En({error:e,url:t,requestBodyValues:n}){if(wn(e))return e;if(e instanceof TypeError&&Tn.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new s({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}var Dn=`3.0.10`;function On({apiKey:e,environmentVariableName:t,apiKeyParameterName:n=`apiKey`,description:r}){if(typeof e==`string`)return e;if(e!=null)throw new _({message:`${r} API key must be a string.`});if(typeof process>`u`)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!=`string`)throw new _({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var kn=/"__proto__"\s*:/,An=/"constructor"\s*:/;function jn(e){let t=JSON.parse(e);return typeof t!=`object`||!t||kn.test(e)===!1&&An.test(e)===!1?t:Mn(t)}function Mn(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function Nn(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return jn(e)}finally{Error.stackTraceLimit=t}}var Pn=Symbol.for(`vercel.ai.validator`);function Fn(e){return{[Pn]:!0,validate:e}}function In(e){return typeof e==`object`&&!!e&&Pn in e&&e[Pn]===!0&&`validate`in e}function Ln(e){return In(e)?e:Rn(e)}function Rn(e){return Fn(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new x({value:t,cause:n.issues})}})}async function zn({value:e,schema:t}){let n=await Bn({value:e,schema:t});if(!n.success)throw x.wrap({value:e,cause:n.error});return n.value}async function Bn({value:e,schema:t}){let n=Ln(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:x.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:x.wrap({value:e,cause:t}),rawValue:e}}}async function Vn({text:e,schema:t}){try{let n=Nn(e);return t==null?n:zn({value:n,schema:t})}catch(t){throw g.isInstance(t)||x.isInstance(t)?t:new g({text:e,cause:t})}}async function Hn({text:e,schema:t}){try{let n=Nn(e);return t==null?{success:!0,value:n,rawValue:n}:await Bn({value:n,schema:t})}catch(t){return{success:!1,error:g.isInstance(t)?t:new g({text:e,cause:t}),rawValue:void 0}}}function Un({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new d).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await Hn({text:e,schema:t}))}}))}async function Wn({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;let r=await Bn({value:t[e],schema:n});if(!r.success)throw new p({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:r.error});return r.value}var Gn=()=>globalThis.fetch,Kn=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>qn({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),qn=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=Gn()})=>{try{let c=await o(e,{method:`POST`,headers:Sn(t,`ai-sdk/provider-utils/${Dn}`,bn()),body:n.content,signal:a}),l=yn(c);if(!c.ok){let t;try{t=await i({response:c,url:e,requestBodyValues:n.values})}catch(t){throw wn(t)||s.isInstance(t)?t:new s({message:`Failed to process error response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw t.value}try{return await r({response:c,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(wn(t)||s.isInstance(t))?t:new s({message:`Failed to process successful response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(t){throw En({error:t,url:e,requestBodyValues:n.values})}};function Jn(e){return e}function Yn({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>Jn({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function Xn({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>Jn({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:r,execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}async function Zn(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var Qn=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),c=yn(r);if(o.trim()===``)return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})};try{let l=await Vn({text:o,schema:e});return{responseHeaders:c,value:new s({message:t(l),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})}}},$n=e=>async({response:t})=>{let n=yn(t);if(t.body==null)throw new u({});return{responseHeaders:n,value:Un({stream:t.body,schema:e})}},er=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await Hn({text:i,schema:e}),o=yn(t);if(!a.success)throw new s({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},{btoa:tr,atob:nr}=globalThis;function rr(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return tr(t)}function ir(e){return e instanceof Uint8Array?rr(e):e}function ar(e){return e?.replace(/\/$/,``)}var or=`2.0.17`,sr=N.object({error:N.object({code:N.number().nullable(),message:N.string(),status:N.string()})}),cr=Qn({errorSchema:sr,errorToMessage:e=>e.error.message}),lr=N.object({outputDimensionality:N.number().optional(),taskType:N.enum([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional()}),ur=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){let i=await Wn({provider:`google`,providerOptions:r,schema:lr});if(e.length>this.maxEmbeddingsPerCall)throw new b({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let a=vn(await Zn(this.config.headers),t);if(e.length===1){let{responseHeaders:t,value:r,rawValue:o}=await Kn({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:a,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType},failedResponseHandler:cr,successfulResponseHandler:er(fr),abortSignal:n,fetch:this.config.fetch});return{embeddings:[r.embedding.values],usage:void 0,response:{headers:t,body:o}}}let{responseHeaders:o,value:s,rawValue:c}=await Kn({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:a,body:{requests:e.map(e=>({model:`models/${this.modelId}`,content:{role:`user`,parts:[{text:e}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType}))},failedResponseHandler:cr,successfulResponseHandler:er(dr),abortSignal:n,fetch:this.config.fetch});return{embeddings:s.embeddings.map(e=>e.values),usage:void 0,response:{headers:o,body:c}}}},dr=N.object({embeddings:N.array(N.object({values:N.array(N.number())}))}),fr=N.object({embedding:N.object({values:N.array(N.number())})});function pr(e){if(e==null||mr(e))return;if(typeof e==`boolean`)return{type:`boolean`,properties:{}};let{type:t,description:n,required:r,properties:i,items:a,allOf:o,anyOf:s,oneOf:c,format:l,const:u,minLength:d,enum:f}=e,p={};if(n&&(p.description=n),r&&(p.required=r),l&&(p.format=l),u!==void 0&&(p.enum=[u]),t&&(Array.isArray(t)?t.includes(`null`)?(p.type=t.filter(e=>e!==`null`)[0],p.nullable=!0):p.type=t:t===`null`?p.type=`null`:p.type=t),f!==void 0&&(p.enum=f),i!=null&&(p.properties=Object.entries(i).reduce((e,[t,n])=>(e[t]=pr(n),e),{})),a&&(p.items=Array.isArray(a)?a.map(pr):pr(a)),o&&(p.allOf=o.map(pr)),s)if(s.some(e=>typeof e==`object`&&e?.type===`null`)){let e=s.filter(e=>!(typeof e==`object`&&e?.type===`null`));if(e.length===1){let t=pr(e[0]);typeof t==`object`&&(p.nullable=!0,Object.assign(p,t))}else p.anyOf=e.map(pr),p.nullable=!0}else p.anyOf=s.map(pr);return c&&(p.oneOf=c.map(pr)),d!==void 0&&(p.minLength=d),p}function mr(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}function hr(e,t){let n=[],r=[],i=!0,a=t?.isGemmaModel??!1;for(let{role:t,content:a}of e)switch(t){case`system`:if(!i)throw new S({functionality:`system messages are only supported at the beginning of the conversation`});n.push({text:a});break;case`user`:{i=!1;let e=[];for(let t of a)switch(t.type){case`text`:e.push({text:t.text});break;case`file`:{let n=t.mediaType===`image/*`?`image/jpeg`:t.mediaType;e.push(t.data instanceof URL?{fileData:{mimeType:n,fileUri:t.data.toString()}}:{inlineData:{mimeType:n,data:ir(t.data)}});break}}r.push({role:`user`,parts:e});break}case`assistant`:i=!1,r.push({role:`model`,parts:a.map(e=>{switch(e.type){case`text`:return e.text.length===0?void 0:{text:e.text,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`reasoning`:return e.text.length===0?void 0:{text:e.text,thought:!0,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`file`:if(e.mediaType!==`image/png`)throw new S({functionality:`Only PNG images are supported in assistant messages`});if(e.data instanceof URL)throw new S({functionality:`File data URLs in assistant messages are not supported`});return{inlineData:{mimeType:e.mediaType,data:ir(e.data)}};case`tool-call`:return{functionCall:{name:e.toolName,args:e.input},thoughtSignature:e.providerOptions?.google?.thoughtSignature}}}).filter(e=>e!==void 0)});break;case`tool`:{i=!1;let e=[];for(let t of a){let n=t.output;if(n.type===`content`)for(let r of n.value)switch(r.type){case`text`:e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:r.text}}});break;case`media`:e.push({inlineData:{mimeType:r.mediaType,data:r.data}},{text:`Tool executed successfully and returned this image as a response`});break;default:e.push({text:JSON.stringify(r)});break}else e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:n.value}}})}r.push({role:`user`,parts:e});break}}if(a&&n.length>0&&r.length>0&&r[0].role===`user`){let e=n.map(e=>e.text).join(`
|
|
2
2
|
|
|
3
3
|
`);r[0].parts.unshift({text:e+`
|
|
4
4
|
|
|
@@ -49,15 +49,15 @@ ${Pf}`),t.includes(`
|
|
|
49
49
|
`)&&(n=3+oe(t.slice(t.lastIndexOf(`
|
|
50
50
|
`))).length);let e=oe(t).length;n+e<process.stdout.columns?(n+=e,process.stdout.write(t)):(process.stdout.write(`
|
|
51
51
|
${Pf}${t.trimStart()}`),n=3+oe(t.trimStart()).length)}process.stdout.write(`
|
|
52
|
-
`)},info:e=>Ff.message(e,{symbol:Cf.default.blue(kf)}),success:e=>Ff.message(e,{symbol:Cf.default.green(Af)}),step:e=>Ff.message(e,{symbol:Cf.default.green(Df)}),warn:e=>Ff.message(e,{symbol:Cf.default.yellow(jf)}),warning:e=>Ff.warn(e),error:e=>Ff.message(e,{symbol:Cf.default.red(Mf)})};let If;function Lf(){try{return F.statSync(`/.dockerenv`),!0}catch{return!1}}function Rf(){try{return F.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function zf(){return If===void 0&&(If=Lf()||Rf()),If}let Bf;const Vf=()=>{try{return F.statSync(`/run/.containerenv`),!0}catch{return!1}};function Hf(){return Bf===void 0&&(Bf=Vf()||zf()),Bf}const Uf=()=>{if(J.platform!==`linux`)return!1;if(Me.release().toLowerCase().includes(`microsoft`))return!Hf();try{return F.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!Hf():!1}catch{return!1}};var Wf=J.env.__IS_WSL_TEST__?Uf:Uf();const Gf=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await Re.access(n,ze.F_OK),r=!0}catch{}if(!r)return e;let i=await Re.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}})(),Kf=async()=>`${await Gf()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,qf=async()=>Wf?Kf():`${J.env.SYSTEMROOT||J.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function Jf(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 Yf=ae(Le);async function Xf(){if(J.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await Yf(`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 Zf=ae(Le);async function Qf(e,{humanReadableOutput:t=!0,signal:n}={}){if(J.platform!==`darwin`)throw Error(`macOS only`);let r=t?[]:[`-ss`],i={};n&&(i.signal=n);let{stdout:a}=await Zf(`osascript`,[`-e`,e,r],i);return a.trim()}async function $f(e){return Qf(`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 ep=ae(Le),tp={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 np=class extends Error{};async function rp(e=ep){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 np(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=tp[r];if(!i)throw new np(`Unknown browser ID: ${r}`);return i}const ip=ae(Le),ap=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function op(){if(J.platform===`darwin`){let e=await Xf();return{name:await $f(e),id:e}}if(J.platform===`linux`){let{stdout:e}=await ip(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:ap(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(J.platform===`win32`)return rp();throw Error(`Only macOS, Linux, and Windows are supported`)}const sp=ae(Ie.execFile),cp=De.dirname(ie(import.meta.url)),lp=De.join(cp,`xdg-open`),{platform:up,arch:dp}=J;async function fp(){let e=await qf(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=te.from(t,`utf16le`).toString(`base64`),{stdout:r}=await sp(e,[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,n],{encoding:`utf8`}),i=r.trim(),a={ChromeHTML:`com.google.chrome`,BraveHTML:`com.brave.Browser`,MSEdgeHTM:`com.microsoft.edge`,FirefoxURL:`org.mozilla.firefox`};return a[i]?{id:a[i]}:{}}const pp=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},mp=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return pp(e.app,t=>mp({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return pp(t,t=>mp({...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=Wf?await fp():await op();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),mp({...e,app:{name:vp[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,i=[],a={};if(up===`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(up===`win32`||Wf&&!Hf()&&!t){r=await qf(),i.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),Wf||(a.windowsVerbatimArguments=!0);let o=[`Start`];e.wait&&o.push(`-Wait`),t?(o.push(`"\`"${t}\`""`),e.target&&n.push(e.target)):e.target&&o.push(`"${e.target}"`),n.length>0&&(n=n.map(e=>`"\`"${e}\`""`),o.push(`-ArgumentList`,n.join(`,`))),e.target=te.from(o.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!cp||cp===`/`,t=!1;try{await Re.access(lp,ze.X_OK),t=!0}catch{}r=J.versions.electron??(up===`android`||e||!t)?`xdg-open`:lp}n.length>0&&i.push(...n),e.wait||(a.stdio=`ignore`,a.detached=!0)}up===`darwin`&&n.length>0&&i.push(`--args`,...n),e.target&&i.push(e.target);let o=Ie.spawn(r,i,a);return e.wait?new Promise((t,n)=>{o.once(`error`,n),o.once(`close`,r=>{if(!e.allowNonzeroExitCode&&r>0){n(Error(`Exited with code ${r}`));return}t(o)})}):(o.unref(),o)},hp=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return mp({...t,target:e})};function gp(e){if(typeof e==`string`||Array.isArray(e))return e;let{[dp]:t}=e;if(!t)throw Error(`${dp} is not supported`);return t}function _p({[up]:e},{wsl:t}){if(t&&Wf)return gp(t);if(!e)throw Error(`${up} is not supported`);return gp(e)}const vp={};Jf(vp,`chrome`,()=>_p({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`]}})),Jf(vp,`brave`,()=>_p({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`]}})),Jf(vp,`firefox`,()=>_p({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),Jf(vp,`edge`,()=>_p({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),Jf(vp,`browser`,()=>`browser`),Jf(vp,`browserPrivate`,()=>`browserPrivate`);var yp=hp;async function bp(e,t=void 0){try{(await yp(e)).once(`error`,n=>{console.log(cf.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))})}catch{console.log(cf.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))}}function xp(e){let t=e||wp();if(I(t)){let e=L(t,`utf8`);return JSON.parse(e).token}}function Sp(e,t){let n=t||wp();I(Oe(n))||ne(Oe(n),{recursive:!0}),R(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function Cp(e){let t=e||wp();I(t)&&re(t)}function wp(){let e=Dd(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return ke(e[0],`auth.json`)}function Tp(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=G(),[s,c]=G(()=>xp(i)),[l,u]=G(),d=W(n),f=W(r);U(()=>{d.current=n,f.current=r},[n,r]);let p=H(async()=>{u(void 0);try{let e=xp(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new ld({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=H(async()=>{u(void 0);try{let e=new ld,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();Sp(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=H(()=>{Cp(i),c(void 0),o(void 0),u(void 0),d.current?.(void 0)},[i]);return U(()=>{t&&p()},[t,p]),{user:a,token:s,error:l,login:m,logout:h}}let Ep=Promise.resolve();var Dp=class{constructor(e){this.printLog=e}setPrintLog(e){this.printLog=e}error(e,...t){Ep=Ep.then(()=>this.printLog(`error`,e,...t).catch(e=>{console.error(`Error printing log:`,e)}))}log(e,...t){Ep=Ep.then(()=>this.printLog(`log`,e,...t).catch(e=>{console.error(`Error printing log:`,e)}))}flush(){return Ep}};const Op=we(void 0);function kp(e){let{directory:t,logger:n,onBuildStart:r,onBuildSuccess:i,onBuildError:a}=typeof e==`string`?{directory:e,logger:new Dp(async()=>{})}:e,o=Te(()=>A(t),[t]),[s,c]=G(void 0),[l,u]=G(void 0),[d,f]=G(`building`),p=W(r),m=W(i),h=W(a);return U(()=>{p.current=r,m.current=i,h.current=a},[r,i,a]),U(()=>{let e=new AbortController;return o.build({cwd:t,entry:o.entry,outdir:o.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{f(`building`),c(void 0),u(void 0),p.current?.()},onResult:e=>{`error`in e?(c(e.error),f(`error`),h.current?.(e.error)):(u(e),f(`success`),m.current?.(e))}}).catch(e=>{n.error(`system`,`error`,e),f(`error`),c(e),h.current?.(e)}),()=>{e.abort()}},[t]),Te(()=>({error:s,status:d,result:l,entry:o.entry,outdir:o.outdir}),[s,d,l,o.entry,o.outdir])}function Ap(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function jp(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const Mp=/^\.+(\\|\/)|^\.+$/,Np=/[. ]+$/,Pp=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,Fp=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,Ip=e=>e===``,Lp=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,Rp=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let zp;function Bp(){return zp??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),zp}function Vp(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(Ap().test(n)||[...n].some(e=>Fp.test(e)&&!Ip(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(Rp,` `),n.length>0&&(e=e.replaceAll(Lp,`$1`)),e=e.replace(Np,``),e=e.replace(Mp,n),e=e.replace(Ap(),n),e=e.replaceAll(Pp,e=>Ip(e)?e:n),e.length===0&&(e=n),e=jp().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=Hp(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=Hp(n,a)+i}}return e}function Hp(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of Bp().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function Up(e){return`${e}.lock`}function Wp(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function Gp(e,t={}){let n=Up(e),r=process.pid.toString();try{return P.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(P.readFileSync(n,`utf8`),10)}catch{return P.unlinkSync(n),Gp(e,{...t,stale:0})}if(!Wp(i))try{return P.unlinkSync(n),Gp(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return Gp(e,{...t,stale:0});throw n}return!1}}async function Kp(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=Ee.resolve(e),i=0;for(;i<=n.retries;){if(Gp(r,n))return()=>qp(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 qp(e){let t=Ee.resolve(e),n=Up(t);try{if(parseInt(P.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}P.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function Jp(e){let t=Ee.resolve(e),n=Up(t);try{if(!P.existsSync(n))return{locked:!1};let e=P.readFileSync(n,`utf8`),t=parseInt(e,10);return Wp(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const Yp=e=>{P.mkdirSync(e,{recursive:!0})},Xp=e=>{try{P.fdatasyncSync(e)}catch{}try{P.closeSync(e)}catch{}},Zp=e=>{try{let t=P.openSync(e,`r`);try{P.fsyncSync(t)}finally{P.closeSync(t)}}catch{}},Qp=(e,t)=>{let n=Ee.dirname(e);Yp(n);let r=Ee.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=P.openSync(r,`w`),P.writeFileSync(i,t,`utf-8`),Xp(i),i=void 0,P.renameSync(r,e),Zp(e),Zp(n)}catch(e){if(i!==void 0)try{P.closeSync(i)}catch{}try{P.rmSync(r,{force:!0})}catch{}throw e}},$p=(e,t)=>{let n=new Map,r,i=e=>{if(P.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(P.readFileSync(e,`utf-8`))},a=(e,t)=>{Qp(e,JSON.stringify(t,null,2))},o=async()=>{if(r)throw Error(`Index is already locked`);let t=Ee.join(e,`index.json`);Yp(e),P.existsSync(t)||P.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await Kp(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},s=async()=>{let t=Ee.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},c=async t=>{let n=Ee.join(e,`index.json`);a(n,t)},l=async t=>{let n=(await s()).ids[t];if(n)return Ee.join(e,n)},u=async t=>{let n=(await s()).ids[t];if(!n)return;let r=Ee.join(e,n);if(P.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(P.readFileSync(r,`utf-8`))},d=async n=>{let r=n[t],i=String(r),l=Vp(i,{replacement:`_`})+`.json`,u=await o();try{let t=await s();t.ids[i]=l,t.current=i;let r=Ee.join(e,l);a(r,n),await c(t)}finally{await u()}};return{async get(e){return await u(e)},async list(){if(!P.statSync(e,{throwIfNoEntry:!1}))return[];let t=await s(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=Ee.join(e,i),a=P.statSync(t,{throwIfNoEntry:!1});if(!a)continue;let o=Jp(t);n.push({key:r,locked:o.locked,pid:o.pid,mtime:a.mtimeMs})}return n.sort((e,t)=>t.mtime-e.mtime),n},async lock(r,i){if(n.has(r))throw Error(`Key "${r}" is already locked in this process`);let a=await l(r);if(!a){let t=Vp(r,{replacement:`_`})+`.json`,n=await o();try{let n=await s();n.ids[r]=t;let i=Ee.join(e,t);Yp(e),P.writeFileSync(i,JSON.stringify({}),`utf-8`),await c(n),a=i}finally{await n()}}if(i?.force){let e=Jp(a);if(e.locked&&e.pid&&e.pid!==process.pid)try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,100))}catch(t){t.code!==`ESRCH`&&console.warn(`Failed to kill process ${e.pid}:`,t.message)}}let f=await Kp(a,{stale:!0,retries:i?.force?10:5,retryInterval:(i?.force,100)});return n.set(r,()=>Promise.resolve(f())),{async get(){let e=await u(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await d(e)},async update(e){let n=await u(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await d({...n,...e})},async delete(){let t=await o();try{let t=await s(),n=t.ids[r];if(n){delete t.ids[r],t.current===r&&(t.current=void 0),await c(t);let i=Ee.join(e,n);try{P.rmSync(i,{force:!0}),Zp(e)}catch{}}}finally{await t()}},async release(){try{f()}finally{n.delete(r)}}}},dispose(){n.clear()}}},em=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,a,o,s=new Map,c=new Map,l=Ee.join(e,`index.json`),u=()=>{try{if(!P.statSync(l,{throwIfNoEntry:!1}))return{ids:{}};let e=P.readFileSync(l,`utf-8`);return{ids:JSON.parse(e).ids??{}}}catch{return{ids:{}}}},d=(e,t,n,r)=>{for(let a of i)try{a({key:e,value:t,locked:n,pid:r})}catch(e){console.error(`Error in onChange callback:`,e)}},f=(t,n,r=!1)=>{let i=Ee.join(e,n);try{let e=P.statSync(i,{throwIfNoEntry:!1}),a=c.get(n);if(!e){a&&(c.delete(n),d(t,void 0,!1));return}let o=e.mtimeMs,s=a?{locked:a.locked,pid:a.pid}:{locked:!1,pid:void 0};if((r||!a)&&(s=Jp(i)),!a||a.mtime!==o||a.locked!==s.locked||a.pid!==s.pid){let e;e=!a||a.mtime!==o?JSON.parse(P.readFileSync(i,`utf-8`)):a.cachedValue,c.set(n,{mtime:o,key:t,locked:s.locked,pid:s.pid,cachedValue:e}),d(t,e,s.locked,s.pid)}}catch{}},p=()=>{try{let e=u(),t=new Set(Object.keys(e.ids));for(let[t,n]of Object.entries(e.ids))f(t,n,!0);for(let[e,n]of c.entries())t.has(n.key)||(c.delete(e),d(n.key,void 0,!1))}catch{}},m=(e,t,n=!1)=>{let i=s.get(e);i&&clearTimeout(i),s.set(e,setTimeout(()=>{s.delete(e),f(e,t,n)},r))},h=()=>{if(a)return;try{P.mkdirSync(e,{recursive:!0})}catch{}a=P.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){p();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=u(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&f(r,e,!0);return}let n=u(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&m(r,t,!1)});let t=()=>{p(),o=setTimeout(t,n)};p(),o=setTimeout(t,n)};return{onChange(e){return i.size===0&&h(),i.add(e),()=>{if(i.delete(e),i.size===0){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),c.clear()}}},dispose(){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),i.clear(),c.clear()}}};async function tm({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=nm}){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=ve({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 nm=e=>{if(e.role!==`assistant`)return!1;let t=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),n=e.parts.slice(t+1).filter(_e);return n.length===0||n.some(e=>E(e.output)&&e.output.outcome===`pending`)?!1:n.every(e=>e.state.startsWith(`output-`))},rm=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function im(e){return typeof e==`object`&&e?.__blink_internal!==void 0}function am(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 om=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=$p(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.onError=e.onError,this.watcher=em(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=>!im(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${oe(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=Dc();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=>!_e(e)||e.input!==``?e:{...e,input:{}})})),t.u(await this.agent.lock.read());let o=performance.now(),s=await tm({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 sm(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a,onError:o}=e,s=W(null),[c,l]=G({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[],queuedLogs:[]});U(()=>{s.current&&s.current.dispose();let e=new om({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]),U(()=>{s.current&&s.current.setAgent(n)},[n]);let u=H(async e=>{s.current&&await s.current.sendMessages([e])},[]),d=H(async e=>{s.current&&await s.current.upsertMessages([e])},[]),f=H(async e=>{s.current&&await s.current.queueLogMessage(e)},[]),p=H(()=>{s.current&&s.current.stopStreaming()},[]),m=H(async()=>{s.current&&await s.current.resetChat()},[]),h=H(()=>{s.current&&s.current.clearQueue()},[]),g=H(async e=>{s.current&&await s.current.deleteMessages([e])},[]),_=H(async()=>{s.current&&await s.current.start()},[]);return{...c,sendMessage:u,upsertMessage:d,queueLogMessage:f,stopStreaming:p,resetChat:m,clearQueue:h,deleteMessage:g,start:_}}function cm(e){return ue(e,`.blink`,`devhook.txt`)}function lm(e){return de(cm(e))}function um(e){let t=cm(e);if(de(t))return pe(t,`utf-8`).trim()}function dm(e){let t=cm(e);if(fe(B(t),{recursive:!0}),de(t))return pe(t,`utf-8`);let n=crypto.randomUUID();return he(t,n),n}const fm=(e,t)=>e.json({error:t},400),pm=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}},mm=()=>new f,hm=mm().get(`/:key`,async e=>{let{key:t,err:n}=pm(e);if(n)return fm(e,n);let r=await e.env.store.get(t);return e.json({value:r},200)}).post(`/:key`,k(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?fm(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:fm(t,`Value must be a string`):fm(t,`Value is required`)}),async e=>{let{key:t,err:n}=pm(e);if(n)return fm(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}=pm(e);return n?fm(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})}),gm=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`}},_m=k(`param`,e=>({id:e.id})),vm=mm().post(`/:key`,async e=>{let{key:t,err:n}=gm(e);return n?fm(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,_m,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,_m,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.getMessages(t),200)}).post(`/:id/sendMessages`,k(`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)):fm(e,`ID is required`)}).delete(`/:id/messages`,_m,k(`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`,_m,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,_m,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,_m,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),ym=mm().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),bm=new f().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,hm).route(`/chat`,vm).route(`/otlp`,ym);var xm=/^(?:[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 Sm(e){return typeof e==`string`&&xm.test(e)}var Cm=Sm;function wm(e){if(!Cm(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 Tm=wm;const Em=[];for(let e=0;e<256;++e)Em.push((e+256).toString(16).slice(1));function Dm(e,t=0){return(Em[e[t+0]]+Em[e[t+1]]+Em[e[t+2]]+Em[e[t+3]]+`-`+Em[e[t+4]]+Em[e[t+5]]+`-`+Em[e[t+6]]+Em[e[t+7]]+`-`+Em[e[t+8]]+Em[e[t+9]]+`-`+Em[e[t+10]]+Em[e[t+11]]+Em[e[t+12]]+Em[e[t+13]]+Em[e[t+14]]+Em[e[t+15]]).toLowerCase()}function Om(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t}function km(e,t,n,r,i,a){let o=typeof n==`string`?Om(n):n,s=typeof r==`string`?Tm(r):r;if(typeof r==`string`&&(r=Tm(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 Dm(c)}function Am(e){return Array.isArray(e)?e=Buffer.from(e):typeof e==`string`&&(e=Buffer.from(e,`utf8`)),se(`sha1`).update(e).digest()}var jm=Am;function Mm(e,t,n,r){return km(80,jm,e,t,n,r)}Mm.DNS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,Mm.URL=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;var Nm=Mm;function Pm(e){let t=ke(e.dataDirectory,`chats`),n={},r=ke(e.dataDirectory,`storage.json`);P.existsSync(r)&&(n=JSON.parse(P.readFileSync(r,`utf-8`)));let i=new Map,a=n=>{let r=i.get(n);return r||(r=new om({chatId:n,chatsDirectory:t}),i.set(n,r)),r.setAgent(e.getAgent()),r},o={async upsert(e){let t=Nm(JSON.stringify(e),Nm.URL),n=a(t).getState(),r=n.messages.length===0&&!n.created_at;return{id:n.id,created:r,createdAt:n.created_at??new Date().toISOString(),key:e}},async get(e){let t=a(e).getState();return{id:t.id,createdAt:t.created_at??new Date().toISOString()}},async getMessages(e){return a(e).getState().messages},async sendMessages(e,t,n){let r=a(e),i=t.map(e=>rm(e,`run`));if(n?.behavior===`append`){await r.upsertMessages(i);return}if(n?.behavior===`interrupt`){await r.sendMessages(i);return}await r.sendMessages(i)},async deleteMessages(e,t){await a(e).deleteMessages(t)},async start(e){await a(e).start()},async stop(e){await a(e).stop()},async delete(e){await a(e).resetChat()}},s={get(e){return Promise.resolve(n[e])},set(e,t){return n[e]=t,P.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},delete(e){return delete n[e],P.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},list(e,t){let r=Math.min(t?.limit??100,1e3),i=t?.cursor,a=Object.keys(n).filter(t=>t.startsWith(e??``)).sort(),o=0;if(i){let e=a.indexOf(i);e!==-1&&(o=e+1)}let s=a.slice(o,o+r),c=o+r<a.length?s[s.length-1]:void 0;return Promise.resolve({entries:s.map(e=>({key:e})),cursor:c})}},c=le(w(e=>bm.fetch(e,{chat:o,store:s})));c.listen(e.port??0);let l=$p(t,`id`);return{url:`http://127.0.0.1:${c.address().port}`,chatsDirectory:t,getChatManager:a,listChats:()=>l.list(),dispose:()=>{for(let e of i.values())e.dispose();i.clear(),l.dispose(),c.close()}}}function Fm({agent:e,capabilities:t,messages:n}){let[r,i]=G(void 0),[a,o]=G(!0),[s,c]=G(void 0),l=W(s);U(()=>{l.current=s},[s]);let[u,d]=G(()=>D(n));U(()=>{d(e=>{let t=D(n);return JSON.stringify(t)===JSON.stringify(e)?e:t})},[n]);let[f,p]=G(void 0),m=H((e,t)=>{if(!l.current)return!1;let n=l.current[e];return n?n.values.some(e=>e.id===t):!1},[]),h=H(e=>{p(t=>{let n={...u,...t,...e};for(let[e,t]of Object.entries(n))m(e,t)||delete n[e];for(let[e,t]of Object.entries(l.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[u,m]);U(()=>{if(!u&&!s){p(void 0);return}h()},[u,s,h]);let g=W(void 0),_=W(void 0);U(()=>{e!==_.current&&(_.current=e,c(void 0),p(void 0),i(void 0),o(!0),g.current=void 0)},[e]),U(()=>{if(t&&!t.ui||!e){c(void 0),p(void 0),i(void 0),g.current=void 0;return}let n=f?JSON.stringify(f):``;if(g.current===n){o(!1),i(void 0);return}let r=new AbortController;return o(!0),i(void 0),e.ui(f?{selectedOptions:f}:{},{signal:r.signal}).then(e=>{if(!e){c(void 0);return}r.signal.aborted||(c(t=>JSON.stringify(t)===JSON.stringify(e)?t:e),g.current=n)}).catch(e=>{r.signal.aborted||i(e instanceof Error?e:Error(String(e)))}).finally(()=>{o(!1)}),()=>{r.abort()}},[e,t,f]);let v=H((e,t)=>{h({[e]:t})},[h]);return{schema:s,options:f,setOption:v,loading:a,error:r}}function Im(e){let t=W(e.onRequest);U(()=>{t.current=e.onRequest},[e.onRequest]);let[n,r]=G(`disconnected`);return U(()=>{if(e.disabled||!e.id){r(`disconnected`);return}let n=!1,i,a,o=!1,s,c=ke(e.directory,`.blink`,`devhook`);return(async()=>{try{s=await Kp(c,{stale:!0,retries:0})}catch(t){if(t&&typeof t==`object`&&`code`in t&&t.code===`ELOCKED`){let e=``;try{let t=Jp(c);t.locked&&t.pid&&(e=` (PID: ${t.pid})`)}catch{}console.error(cf.red(`\nError: Another ${cf.bold(`blink dev`)} process is already running in this directory${e}.`)),console.error(cf.red(`Please stop the other process and try again.
|
|
53
|
-
`)),process.exit(1)}let n=t&&typeof t==`object`&&`message`in t?String(t.message):String(t);e.logger.error(`system`,cf.yellow(`\nWarning: Failed to acquire devhook lock: ${n}`)),e.logger.error(`system`,cf.yellow(`Continuing without lock. Multiple ${cf.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 ld({baseURL:`https://blink.
|
|
52
|
+
`)},info:e=>Ff.message(e,{symbol:Cf.default.blue(kf)}),success:e=>Ff.message(e,{symbol:Cf.default.green(Af)}),step:e=>Ff.message(e,{symbol:Cf.default.green(Df)}),warn:e=>Ff.message(e,{symbol:Cf.default.yellow(jf)}),warning:e=>Ff.warn(e),error:e=>Ff.message(e,{symbol:Cf.default.red(Mf)})};let If;function Lf(){try{return F.statSync(`/.dockerenv`),!0}catch{return!1}}function Rf(){try{return F.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function zf(){return If===void 0&&(If=Lf()||Rf()),If}let Bf;const Vf=()=>{try{return F.statSync(`/run/.containerenv`),!0}catch{return!1}};function Hf(){return Bf===void 0&&(Bf=Vf()||zf()),Bf}const Uf=()=>{if(J.platform!==`linux`)return!1;if(Me.release().toLowerCase().includes(`microsoft`))return!Hf();try{return F.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!Hf():!1}catch{return!1}};var Wf=J.env.__IS_WSL_TEST__?Uf:Uf();const Gf=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await Re.access(n,ze.F_OK),r=!0}catch{}if(!r)return e;let i=await Re.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}})(),Kf=async()=>`${await Gf()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,qf=async()=>Wf?Kf():`${J.env.SYSTEMROOT||J.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function Jf(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 Yf=ae(Le);async function Xf(){if(J.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await Yf(`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 Zf=ae(Le);async function Qf(e,{humanReadableOutput:t=!0,signal:n}={}){if(J.platform!==`darwin`)throw Error(`macOS only`);let r=t?[]:[`-ss`],i={};n&&(i.signal=n);let{stdout:a}=await Zf(`osascript`,[`-e`,e,r],i);return a.trim()}async function $f(e){return Qf(`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 ep=ae(Le),tp={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 np=class extends Error{};async function rp(e=ep){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 np(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=tp[r];if(!i)throw new np(`Unknown browser ID: ${r}`);return i}const ip=ae(Le),ap=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function op(){if(J.platform===`darwin`){let e=await Xf();return{name:await $f(e),id:e}}if(J.platform===`linux`){let{stdout:e}=await ip(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:ap(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(J.platform===`win32`)return rp();throw Error(`Only macOS, Linux, and Windows are supported`)}const sp=ae(Ie.execFile),cp=De.dirname(ie(import.meta.url)),lp=De.join(cp,`xdg-open`),{platform:up,arch:dp}=J;async function fp(){let e=await qf(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=te.from(t,`utf16le`).toString(`base64`),{stdout:r}=await sp(e,[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,n],{encoding:`utf8`}),i=r.trim(),a={ChromeHTML:`com.google.chrome`,BraveHTML:`com.brave.Browser`,MSEdgeHTM:`com.microsoft.edge`,FirefoxURL:`org.mozilla.firefox`};return a[i]?{id:a[i]}:{}}const pp=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},mp=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return pp(e.app,t=>mp({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return pp(t,t=>mp({...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=Wf?await fp():await op();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),mp({...e,app:{name:vp[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,i=[],a={};if(up===`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(up===`win32`||Wf&&!Hf()&&!t){r=await qf(),i.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),Wf||(a.windowsVerbatimArguments=!0);let o=[`Start`];e.wait&&o.push(`-Wait`),t?(o.push(`"\`"${t}\`""`),e.target&&n.push(e.target)):e.target&&o.push(`"${e.target}"`),n.length>0&&(n=n.map(e=>`"\`"${e}\`""`),o.push(`-ArgumentList`,n.join(`,`))),e.target=te.from(o.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!cp||cp===`/`,t=!1;try{await Re.access(lp,ze.X_OK),t=!0}catch{}r=J.versions.electron??(up===`android`||e||!t)?`xdg-open`:lp}n.length>0&&i.push(...n),e.wait||(a.stdio=`ignore`,a.detached=!0)}up===`darwin`&&n.length>0&&i.push(`--args`,...n),e.target&&i.push(e.target);let o=Ie.spawn(r,i,a);return e.wait?new Promise((t,n)=>{o.once(`error`,n),o.once(`close`,r=>{if(!e.allowNonzeroExitCode&&r>0){n(Error(`Exited with code ${r}`));return}t(o)})}):(o.unref(),o)},hp=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return mp({...t,target:e})};function gp(e){if(typeof e==`string`||Array.isArray(e))return e;let{[dp]:t}=e;if(!t)throw Error(`${dp} is not supported`);return t}function _p({[up]:e},{wsl:t}){if(t&&Wf)return gp(t);if(!e)throw Error(`${up} is not supported`);return gp(e)}const vp={};Jf(vp,`chrome`,()=>_p({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`]}})),Jf(vp,`brave`,()=>_p({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`]}})),Jf(vp,`firefox`,()=>_p({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),Jf(vp,`edge`,()=>_p({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),Jf(vp,`browser`,()=>`browser`),Jf(vp,`browserPrivate`,()=>`browserPrivate`);var yp=hp;async function bp(e,t=void 0){try{(await yp(e)).once(`error`,n=>{console.log(cf.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))})}catch{console.log(cf.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))}}function xp(e){let t=e||wp();if(I(t)){let e=L(t,`utf8`);return JSON.parse(e).token}}function Sp(e,t){let n=t||wp();I(Oe(n))||ne(Oe(n),{recursive:!0}),R(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function Cp(e){let t=e||wp();I(t)&&re(t)}function wp(){let e=Dd(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return ke(e[0],`auth.json`)}function Tp(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=G(),[s,c]=G(()=>xp(i)),[l,u]=G(),d=W(n),f=W(r);U(()=>{d.current=n,f.current=r},[n,r]);let p=H(async()=>{u(void 0);try{let e=xp(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new ld({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=H(async()=>{u(void 0);try{let e=new ld,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();Sp(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=H(()=>{Cp(i),c(void 0),o(void 0),u(void 0),d.current?.(void 0)},[i]);return U(()=>{t&&p()},[t,p]),{user:a,token:s,error:l,login:m,logout:h}}let Ep=Promise.resolve();var Dp=class{constructor(e){this.printLog=e}setPrintLog(e){this.printLog=e}error(e,...t){Ep=Ep.then(()=>this.printLog(`error`,e,...t).catch(e=>{console.error(`Error printing log:`,e)}))}log(e,...t){Ep=Ep.then(()=>this.printLog(`log`,e,...t).catch(e=>{console.error(`Error printing log:`,e)}))}flush(){return Ep}};const Op=we(void 0);function kp(e){let{directory:t,logger:n,onBuildStart:r,onBuildSuccess:i,onBuildError:a}=typeof e==`string`?{directory:e,logger:new Dp(async()=>{})}:e,o=Te(()=>A(t),[t]),[s,c]=G(void 0),[l,u]=G(void 0),[d,f]=G(`building`),p=W(r),m=W(i),h=W(a);return U(()=>{p.current=r,m.current=i,h.current=a},[r,i,a]),U(()=>{let e=new AbortController;return o.build({cwd:t,entry:o.entry,outdir:o.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{f(`building`),c(void 0),u(void 0),p.current?.()},onResult:e=>{`error`in e?(c(e.error),f(`error`),h.current?.(e.error)):(u(e),f(`success`),m.current?.(e))}}).catch(e=>{n.error(`system`,`error`,e),f(`error`),c(e),h.current?.(e)}),()=>{e.abort()}},[t]),Te(()=>({error:s,status:d,result:l,entry:o.entry,outdir:o.outdir}),[s,d,l,o.entry,o.outdir])}function Ap(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function jp(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const Mp=/^\.+(\\|\/)|^\.+$/,Np=/[. ]+$/,Pp=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,Fp=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,Ip=e=>e===``,Lp=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,Rp=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let zp;function Bp(){return zp??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),zp}function Vp(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(Ap().test(n)||[...n].some(e=>Fp.test(e)&&!Ip(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(Rp,` `),n.length>0&&(e=e.replaceAll(Lp,`$1`)),e=e.replace(Np,``),e=e.replace(Mp,n),e=e.replace(Ap(),n),e=e.replaceAll(Pp,e=>Ip(e)?e:n),e.length===0&&(e=n),e=jp().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=Hp(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=Hp(n,a)+i}}return e}function Hp(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of Bp().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function Up(e){return`${e}.lock`}function Wp(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function Gp(e,t={}){let n=Up(e),r=process.pid.toString();try{return P.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(P.readFileSync(n,`utf8`),10)}catch{return P.unlinkSync(n),Gp(e,{...t,stale:0})}if(!Wp(i))try{return P.unlinkSync(n),Gp(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return Gp(e,{...t,stale:0});throw n}return!1}}async function Kp(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=Ee.resolve(e),i=0;for(;i<=n.retries;){if(Gp(r,n))return()=>qp(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 qp(e){let t=Ee.resolve(e),n=Up(t);try{if(parseInt(P.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}P.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function Jp(e){let t=Ee.resolve(e),n=Up(t);try{if(!P.existsSync(n))return{locked:!1};let e=P.readFileSync(n,`utf8`),t=parseInt(e,10);return Wp(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const Yp=e=>{P.mkdirSync(e,{recursive:!0})},Xp=e=>{try{P.fdatasyncSync(e)}catch{}try{P.closeSync(e)}catch{}},Zp=e=>{try{let t=P.openSync(e,`r`);try{P.fsyncSync(t)}finally{P.closeSync(t)}}catch{}},Qp=(e,t)=>{let n=Ee.dirname(e);Yp(n);let r=Ee.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=P.openSync(r,`w`),P.writeFileSync(i,t,`utf-8`),Xp(i),i=void 0,P.renameSync(r,e),Zp(e),Zp(n)}catch(e){if(i!==void 0)try{P.closeSync(i)}catch{}try{P.rmSync(r,{force:!0})}catch{}throw e}},$p=(e,t)=>{let n=new Map,r,i=e=>{if(P.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(P.readFileSync(e,`utf-8`))},a=(e,t)=>{Qp(e,JSON.stringify(t,null,2))},o=async()=>{if(r)throw Error(`Index is already locked`);let t=Ee.join(e,`index.json`);Yp(e),P.existsSync(t)||P.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await Kp(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},s=async()=>{let t=Ee.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},c=async t=>{let n=Ee.join(e,`index.json`);a(n,t)},l=async t=>{let n=(await s()).ids[t];if(n)return Ee.join(e,n)},u=async t=>{let n=(await s()).ids[t];if(!n)return;let r=Ee.join(e,n);if(P.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(P.readFileSync(r,`utf-8`))},d=async n=>{let r=n[t],i=String(r),l=Vp(i,{replacement:`_`})+`.json`,u=await o();try{let t=await s();t.ids[i]=l,t.current=i;let r=Ee.join(e,l);a(r,n),await c(t)}finally{await u()}};return{async get(e){return await u(e)},async list(){if(!P.statSync(e,{throwIfNoEntry:!1}))return[];let t=await s(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=Ee.join(e,i),a=P.statSync(t,{throwIfNoEntry:!1});if(!a)continue;let o=Jp(t);n.push({key:r,locked:o.locked,pid:o.pid,mtime:a.mtimeMs})}return n.sort((e,t)=>t.mtime-e.mtime),n},async lock(r,i){if(n.has(r))throw Error(`Key "${r}" is already locked in this process`);let a=await l(r);if(!a){let t=Vp(r,{replacement:`_`})+`.json`,n=await o();try{let n=await s();n.ids[r]=t;let i=Ee.join(e,t);Yp(e),P.writeFileSync(i,JSON.stringify({}),`utf-8`),await c(n),a=i}finally{await n()}}if(i?.force){let e=Jp(a);if(e.locked&&e.pid&&e.pid!==process.pid)try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,100))}catch(t){t.code!==`ESRCH`&&console.warn(`Failed to kill process ${e.pid}:`,t.message)}}let f=await Kp(a,{stale:!0,retries:i?.force?10:5,retryInterval:(i?.force,100)});return n.set(r,()=>Promise.resolve(f())),{async get(){let e=await u(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await d(e)},async update(e){let n=await u(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await d({...n,...e})},async delete(){let t=await o();try{let t=await s(),n=t.ids[r];if(n){delete t.ids[r],t.current===r&&(t.current=void 0),await c(t);let i=Ee.join(e,n);try{P.rmSync(i,{force:!0}),Zp(e)}catch{}}}finally{await t()}},async release(){try{f()}finally{n.delete(r)}}}},dispose(){n.clear()}}},em=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,a,o,s=new Map,c=new Map,l=Ee.join(e,`index.json`),u=()=>{try{if(!P.statSync(l,{throwIfNoEntry:!1}))return{ids:{}};let e=P.readFileSync(l,`utf-8`);return{ids:JSON.parse(e).ids??{}}}catch{return{ids:{}}}},d=(e,t,n,r)=>{for(let a of i)try{a({key:e,value:t,locked:n,pid:r})}catch(e){console.error(`Error in onChange callback:`,e)}},f=(t,n,r=!1)=>{let i=Ee.join(e,n);try{let e=P.statSync(i,{throwIfNoEntry:!1}),a=c.get(n);if(!e){a&&(c.delete(n),d(t,void 0,!1));return}let o=e.mtimeMs,s=a?{locked:a.locked,pid:a.pid}:{locked:!1,pid:void 0};if((r||!a)&&(s=Jp(i)),!a||a.mtime!==o||a.locked!==s.locked||a.pid!==s.pid){let e;e=!a||a.mtime!==o?JSON.parse(P.readFileSync(i,`utf-8`)):a.cachedValue,c.set(n,{mtime:o,key:t,locked:s.locked,pid:s.pid,cachedValue:e}),d(t,e,s.locked,s.pid)}}catch{}},p=()=>{try{let e=u(),t=new Set(Object.keys(e.ids));for(let[t,n]of Object.entries(e.ids))f(t,n,!0);for(let[e,n]of c.entries())t.has(n.key)||(c.delete(e),d(n.key,void 0,!1))}catch{}},m=(e,t,n=!1)=>{let i=s.get(e);i&&clearTimeout(i),s.set(e,setTimeout(()=>{s.delete(e),f(e,t,n)},r))},h=()=>{if(a)return;try{P.mkdirSync(e,{recursive:!0})}catch{}a=P.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){p();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=u(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&f(r,e,!0);return}let n=u(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&m(r,t,!1)});let t=()=>{p(),o=setTimeout(t,n)};p(),o=setTimeout(t,n)};return{onChange(e){return i.size===0&&h(),i.add(e),()=>{if(i.delete(e),i.size===0){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),c.clear()}}},dispose(){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),i.clear(),c.clear()}}};async function tm({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=nm}){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=ve({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 nm=e=>{if(e.role!==`assistant`)return!1;let t=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),n=e.parts.slice(t+1).filter(_e);return n.length===0||n.some(e=>E(e.output)&&e.output.outcome===`pending`)?!1:n.every(e=>e.state.startsWith(`output-`))},rm=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function im(e){return typeof e==`object`&&e?.__blink_internal!==void 0}function am(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 om=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=$p(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.onError=e.onError,this.watcher=em(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=>!im(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${oe(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=Dc();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=>!_e(e)||e.input!==``?e:{...e,input:{}})})),t.u(await this.agent.lock.read());let o=performance.now(),s=await tm({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 sm(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a,onError:o}=e,s=W(null),[c,l]=G({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[],queuedLogs:[]});U(()=>{s.current&&s.current.dispose();let e=new om({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]),U(()=>{s.current&&s.current.setAgent(n)},[n]);let u=H(async e=>{s.current&&await s.current.sendMessages([e])},[]),d=H(async e=>{s.current&&await s.current.upsertMessages([e])},[]),f=H(async e=>{s.current&&await s.current.queueLogMessage(e)},[]),p=H(()=>{s.current&&s.current.stopStreaming()},[]),m=H(async()=>{s.current&&await s.current.resetChat()},[]),h=H(()=>{s.current&&s.current.clearQueue()},[]),g=H(async e=>{s.current&&await s.current.deleteMessages([e])},[]),_=H(async()=>{s.current&&await s.current.start()},[]);return{...c,sendMessage:u,upsertMessage:d,queueLogMessage:f,stopStreaming:p,resetChat:m,clearQueue:h,deleteMessage:g,start:_}}function cm(e){return ue(e,`.blink`,`devhook.txt`)}function lm(e){return de(cm(e))}function um(e){let t=cm(e);if(de(t))return pe(t,`utf-8`).trim()}function dm(e){let t=cm(e);if(fe(B(t),{recursive:!0}),de(t))return pe(t,`utf-8`);let n=crypto.randomUUID();return he(t,n),n}const fm=(e,t)=>e.json({error:t},400),pm=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}},mm=()=>new f,hm=mm().get(`/:key`,async e=>{let{key:t,err:n}=pm(e);if(n)return fm(e,n);let r=await e.env.store.get(t);return e.json({value:r},200)}).post(`/:key`,k(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?fm(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:fm(t,`Value must be a string`):fm(t,`Value is required`)}),async e=>{let{key:t,err:n}=pm(e);if(n)return fm(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}=pm(e);return n?fm(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})}),gm=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`}},_m=k(`param`,e=>({id:e.id})),vm=mm().post(`/:key`,async e=>{let{key:t,err:n}=gm(e);return n?fm(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,_m,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,_m,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.getMessages(t),200)}).post(`/:id/sendMessages`,k(`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)):fm(e,`ID is required`)}).delete(`/:id/messages`,_m,k(`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`,_m,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,_m,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,_m,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),ym=mm().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),bm=new f().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,hm).route(`/chat`,vm).route(`/otlp`,ym);var xm=/^(?:[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 Sm(e){return typeof e==`string`&&xm.test(e)}var Cm=Sm;function wm(e){if(!Cm(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 Tm=wm;const Em=[];for(let e=0;e<256;++e)Em.push((e+256).toString(16).slice(1));function Dm(e,t=0){return(Em[e[t+0]]+Em[e[t+1]]+Em[e[t+2]]+Em[e[t+3]]+`-`+Em[e[t+4]]+Em[e[t+5]]+`-`+Em[e[t+6]]+Em[e[t+7]]+`-`+Em[e[t+8]]+Em[e[t+9]]+`-`+Em[e[t+10]]+Em[e[t+11]]+Em[e[t+12]]+Em[e[t+13]]+Em[e[t+14]]+Em[e[t+15]]).toLowerCase()}function Om(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t}function km(e,t,n,r,i,a){let o=typeof n==`string`?Om(n):n,s=typeof r==`string`?Tm(r):r;if(typeof r==`string`&&(r=Tm(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 Dm(c)}function Am(e){return Array.isArray(e)?e=Buffer.from(e):typeof e==`string`&&(e=Buffer.from(e,`utf8`)),se(`sha1`).update(e).digest()}var jm=Am;function Mm(e,t,n,r){return km(80,jm,e,t,n,r)}Mm.DNS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,Mm.URL=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;var Nm=Mm;function Pm(e){let t=ke(e.dataDirectory,`chats`),n={},r=ke(e.dataDirectory,`storage.json`);P.existsSync(r)&&(n=JSON.parse(P.readFileSync(r,`utf-8`)));let i=new Map,a=n=>{let r=i.get(n);return r||(r=new om({chatId:n,chatsDirectory:t}),i.set(n,r)),r.setAgent(e.getAgent()),r},o={async upsert(e){let t=Nm(JSON.stringify(e),Nm.URL),n=a(t).getState(),r=n.messages.length===0&&!n.created_at;return{id:n.id,created:r,createdAt:n.created_at??new Date().toISOString(),key:e}},async get(e){let t=a(e).getState();return{id:t.id,createdAt:t.created_at??new Date().toISOString()}},async getMessages(e){return a(e).getState().messages},async sendMessages(e,t,n){let r=a(e),i=t.map(e=>rm(e,`run`));if(n?.behavior===`append`){await r.upsertMessages(i);return}if(n?.behavior===`interrupt`){await r.sendMessages(i);return}await r.sendMessages(i)},async deleteMessages(e,t){await a(e).deleteMessages(t)},async start(e){await a(e).start()},async stop(e){await a(e).stop()},async delete(e){await a(e).resetChat()}},s={get(e){return Promise.resolve(n[e])},set(e,t){return n[e]=t,P.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},delete(e){return delete n[e],P.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},list(e,t){let r=Math.min(t?.limit??100,1e3),i=t?.cursor,a=Object.keys(n).filter(t=>t.startsWith(e??``)).sort(),o=0;if(i){let e=a.indexOf(i);e!==-1&&(o=e+1)}let s=a.slice(o,o+r),c=o+r<a.length?s[s.length-1]:void 0;return Promise.resolve({entries:s.map(e=>({key:e})),cursor:c})}},c=le(w(e=>bm.fetch(e,{chat:o,store:s})));c.listen(e.port??0);let l=$p(t,`id`);return{url:`http://127.0.0.1:${c.address().port}`,chatsDirectory:t,getChatManager:a,listChats:()=>l.list(),dispose:()=>{for(let e of i.values())e.dispose();i.clear(),l.dispose(),c.close()}}}function Fm({agent:e,capabilities:t,messages:n}){let[r,i]=G(void 0),[a,o]=G(!0),[s,c]=G(void 0),l=W(s);U(()=>{l.current=s},[s]);let[u,d]=G(()=>D(n));U(()=>{d(e=>{let t=D(n);return JSON.stringify(t)===JSON.stringify(e)?e:t})},[n]);let[f,p]=G(void 0),m=H((e,t)=>{if(!l.current)return!1;let n=l.current[e];return n?n.values.some(e=>e.id===t):!1},[]),h=H(e=>{p(t=>{let n={...u,...t,...e};for(let[e,t]of Object.entries(n))m(e,t)||delete n[e];for(let[e,t]of Object.entries(l.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[u,m]);U(()=>{if(!u&&!s){p(void 0);return}h()},[u,s,h]);let g=W(void 0),_=W(void 0);U(()=>{e!==_.current&&(_.current=e,c(void 0),p(void 0),i(void 0),o(!0),g.current=void 0)},[e]),U(()=>{if(t&&!t.ui||!e){c(void 0),p(void 0),i(void 0),g.current=void 0;return}let n=f?JSON.stringify(f):``;if(g.current===n){o(!1),i(void 0);return}let r=new AbortController;return o(!0),i(void 0),e.ui(f?{selectedOptions:f}:{},{signal:r.signal}).then(e=>{if(!e){c(void 0);return}r.signal.aborted||(c(t=>JSON.stringify(t)===JSON.stringify(e)?t:e),g.current=n)}).catch(e=>{r.signal.aborted||i(e instanceof Error?e:Error(String(e)))}).finally(()=>{o(!1)}),()=>{r.abort()}},[e,t,f]);let v=H((e,t)=>{h({[e]:t})},[h]);return{schema:s,options:f,setOption:v,loading:a,error:r}}function Im(e){let t=W(e.onRequest);U(()=>{t.current=e.onRequest},[e.onRequest]);let[n,r]=G(`disconnected`);return U(()=>{if(e.disabled||!e.id){r(`disconnected`);return}let n=!1,i,a,o=!1,s,c=ke(e.directory,`.blink`,`devhook`);return(async()=>{try{s=await Kp(c,{stale:!0,retries:0})}catch(t){if(t&&typeof t==`object`&&`code`in t&&t.code===`ELOCKED`){let e=``;try{let t=Jp(c);t.locked&&t.pid&&(e=` (PID: ${t.pid})`)}catch{}console.error(cf.red(`\nError: Another ${cf.bold(`blink dev`)} process is already running in this directory${e}.`)),console.error(cf.red(`Please stop the other process and try again.
|
|
53
|
+
`)),process.exit(1)}let n=t&&typeof t==`object`&&`message`in t?String(t.message):String(t);e.logger.error(`system`,cf.yellow(`\nWarning: Failed to acquire devhook lock: ${n}`)),e.logger.error(`system`,cf.yellow(`Continuing without lock. Multiple ${cf.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 ld({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 Lm=e(((e,t)=>{t.exports={name:`dotenv`,version:`17.2.3`,description:`Loads environment variables from .env file`,main:`lib/main.js`,types:`lib/main.d.ts`,exports:{".":{types:`./lib/main.d.ts`,require:`./lib/main.js`,default:`./lib/main.js`},"./config":`./config.js`,"./config.js":`./config.js`,"./lib/env-options":`./lib/env-options.js`,"./lib/env-options.js":`./lib/env-options.js`,"./lib/cli-options":`./lib/cli-options.js`,"./lib/cli-options.js":`./lib/cli-options.js`,"./package.json":`./package.json`},scripts:{"dts-check":`tsc --project tests/types/tsconfig.json`,lint:`standard`,pretest:`npm run lint && npm run dts-check`,test:`tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000`,"test:coverage":`tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov`,prerelease:`npm test`,release:`standard-version`},repository:{type:`git`,url:`git://github.com/motdotla/dotenv.git`},homepage:`https://github.com/motdotla/dotenv#readme`,funding:`https://dotenvx.com`,keywords:[`dotenv`,`env`,`.env`,`environment`,`variables`,`config`,`settings`],readmeFilename:`README.md`,license:`BSD-2-Clause`,devDependencies:{"@types/node":`^18.11.3`,decache:`^4.6.2`,sinon:`^14.0.1`,standard:`^17.0.0`,"standard-version":`^9.5.0`,tap:`^19.2.0`,typescript:`^4.8.4`},engines:{node:`>=12`},browser:{fs:!1}}})),Rm=o(e(((e,t)=>{let n=i(`fs`),r=i(`path`),a=i(`os`),o=i(`crypto`),s=Lm().version,c=[`🔐 encrypt with Dotenvx: https://dotenvx.com`,`🔐 prevent committing .env to code: https://dotenvx.com/precommit`,`🔐 prevent building .env in docker: https://dotenvx.com/prebuild`,`📡 add observability to secrets: https://dotenvx.com/ops`,`👥 sync secrets across teammates & machines: https://dotenvx.com/ops`,`🗂️ backup and recover secrets: https://dotenvx.com/ops`,`✅ audit secrets and track compliance: https://dotenvx.com/ops`,`🔄 add secrets lifecycle management: https://dotenvx.com/ops`,`🔑 add access controls to secrets: https://dotenvx.com/ops`,"🛠️ run anywhere with `dotenvx run -- yourcommand`",`⚙️ specify custom .env file path with { path: '/custom/path/.env' }`,`⚙️ enable debug logging with { debug: true }`,`⚙️ override existing env vars with { override: true }`,`⚙️ suppress all logs with { quiet: true }`,`⚙️ write to custom object with { processEnv: myObject }`,`⚙️ load multiple .env files with { path: ['.env.local', '.env'] }`];function l(){return c[Math.floor(Math.random()*c.length)]}function u(e){return typeof e==`string`?![`false`,`0`,`no`,`off`,``].includes(e.toLowerCase()):!!e}function d(){return process.stdout.isTTY}function f(e){return d()?`\x1b[2m${e}\x1b[0m`:e}let p=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function m(e){let t={},n=e.toString();n=n.replace(/\r\n?/gm,`
|
|
54
54
|
`);let r;for(;(r=p.exec(n))!=null;){let e=r[1],n=r[2]||``;n=n.trim();let i=n[0];n=n.replace(/^(['"`])([\s\S]*)\1$/gm,`$2`),i===`"`&&(n=n.replace(/\\n/g,`
|
|
55
|
-
`),n=n.replace(/\\r/g,`\r`)),t[e]=n}return t}function h(e){e||={};let t=x(e);e.path=t;let n=O.configDotenv(e);if(!n.parsed){let e=Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code=`MISSING_DATA`,e}let r=y(e).split(`,`),i=r.length,a;for(let e=0;e<i;e++)try{let t=r[e].trim(),i=b(n,t);a=O.decrypt(i.ciphertext,i.key);break}catch(t){if(e+1>=i)throw t}return O.parse(a)}function g(e){console.error(`[dotenv@${s}][WARN] ${e}`)}function _(e){console.log(`[dotenv@${s}][DEBUG] ${e}`)}function v(e){console.log(`[dotenv@${s}] ${e}`)}function y(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:``}function b(e,t){let n;try{n=new URL(t)}catch(e){if(e.code===`ERR_INVALID_URL`){let e=Error(`INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development`);throw e.code=`INVALID_DOTENV_KEY`,e}throw e}let r=n.password;if(!r){let e=Error(`INVALID_DOTENV_KEY: Missing key part`);throw e.code=`INVALID_DOTENV_KEY`,e}let i=n.searchParams.get(`environment`);if(!i){let e=Error(`INVALID_DOTENV_KEY: Missing environment part`);throw e.code=`INVALID_DOTENV_KEY`,e}let a=`DOTENV_VAULT_${i.toUpperCase()}`,o=e.parsed[a];if(!o){let e=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${a} in your .env.vault file.`);throw e.code=`NOT_FOUND_DOTENV_ENVIRONMENT`,e}return{ciphertext:o,key:r}}function x(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let r of e.path)n.existsSync(r)&&(t=r.endsWith(`.vault`)?r:`${r}.vault`);else t=e.path.endsWith(`.vault`)?e.path:`${e.path}.vault`;else t=r.resolve(process.cwd(),`.env.vault`);return n.existsSync(t)?t:null}function S(e){return e[0]===`~`?r.join(a.homedir(),e.slice(1)):e}function C(e){let t=u(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=u(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(t||!n)&&v(`Loading env from encrypted .env.vault`);let r=O._parseVault(e),i=process.env;return e&&e.processEnv!=null&&(i=e.processEnv),O.populate(i,r,e),{parsed:r}}function w(e){let t=r.resolve(process.cwd(),`.env`),i=`utf8`,a=process.env;e&&e.processEnv!=null&&(a=e.processEnv);let o=u(a.DOTENV_CONFIG_DEBUG||e&&e.debug),s=u(a.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?i=e.encoding:o&&_(`No encoding is specified. UTF-8 is used by default`);let c=[t];if(e&&e.path)if(!Array.isArray(e.path))c=[S(e.path)];else{c=[];for(let t of e.path)c.push(S(t))}let d,p={};for(let t of c)try{let r=O.parse(n.readFileSync(t,{encoding:i}));O.populate(p,r,e)}catch(e){o&&_(`Failed to load ${t} ${e.message}`),d=e}let m=O.populate(a,p,e);if(o=u(a.DOTENV_CONFIG_DEBUG||o),s=u(a.DOTENV_CONFIG_QUIET||s),o||!s){let e=Object.keys(m).length,t=[];for(let e of c)try{let n=r.relative(process.cwd(),e);t.push(n)}catch(t){o&&_(`Failed to load ${e} ${t.message}`),d=t}v(`injecting env (${e}) from ${t.join(`,`)} ${f(`-- tip: ${l()}`)}`)}return d?{parsed:p,error:d}:{parsed:p}}function T(e){if(y(e).length===0)return O.configDotenv(e);let t=x(e);return t?O._configVault(e):(g(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),O.configDotenv(e))}function E(e,t){let n=Buffer.from(t.slice(-64),`hex`),r=Buffer.from(e,`base64`),i=r.subarray(0,12),a=r.subarray(-16);r=r.subarray(12,-16);try{let e=o.createDecipheriv(`aes-256-gcm`,n,i);return e.setAuthTag(a),`${e.update(r)}${e.final()}`}catch(e){let t=e instanceof RangeError,n=e.message===`Invalid key length`,r=e.message===`Unsupported state or unable to authenticate data`;if(t||n){let e=Error(`INVALID_DOTENV_KEY: It must be 64 characters long (or more)`);throw e.code=`INVALID_DOTENV_KEY`,e}else if(r){let e=Error(`DECRYPTION_FAILED: Please check your DOTENV_KEY`);throw e.code=`DECRYPTION_FAILED`,e}else throw e}}function D(e,t,n={}){let r=!!(n&&n.debug),i=!!(n&&n.override),a={};if(typeof t!=`object`){let e=Error(`OBJECT_REQUIRED: Please check the processEnv argument being passed to populate`);throw e.code=`OBJECT_REQUIRED`,e}for(let n of Object.keys(t))Object.prototype.hasOwnProperty.call(e,n)?(i===!0&&(e[n]=t[n],a[n]=t[n]),r&&_(i===!0?`"${n}" is already defined and WAS overwritten`:`"${n}" is already defined and was NOT overwritten`)):(e[n]=t[n],a[n]=t[n]);return a}let O={configDotenv:w,_configVault:C,_parseVault:h,config:T,decrypt:E,parse:m,populate:D};t.exports.configDotenv=O.configDotenv,t.exports._configVault=O._configVault,t.exports._parseVault=O._parseVault,t.exports.config=O.config,t.exports.decrypt=O.decrypt,t.exports.parse=O.parse,t.exports.populate=O.populate,t.exports=O}))());async function zm(e,t){let n=e;for(;n!==B(n);){let e=ue(n,t);try{return await V(e),e}catch{}n=B(n)}}function Bm(e,t,n=`.env.local`){let[r,i]=G({});return U(()=>{let r,a=e=>{try{let t=pe(e,`utf-8`),n=(0,Rm.parse)(t);i(n)}catch(e){t.error(`system`,`Error reading ${n}:`,e),i({})}};return zm(e,n).then(e=>{if(!e){i({});return}a(e),r=me(e,{persistent:!1},()=>{a(e)})}),()=>{r&&r.close()}},[e,n]),r}var Vm=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}else return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h){d[r]=void 0;continue}if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}};new class extends Vm{};function Hm(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 Um(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 Wm(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 Gm(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 Km(e,t){return Wm(e,t,``)}function qm(e,t){return Gm(e,t,``)}function Jm(e,t){return t.slice(0,Ym(e,t))}function Ym(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 Xm(e){let t;for(t=e.length-1;t>=0&&e[t].match(/\s/);t--);return e.substring(t+1)}function Zm(e){let t=e.match(/^\s*/);return t?t[0]:``}const Qm=`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}`,$m=RegExp(`[${Qm}]+|\\s+|[^${Qm}]`,`ug`);new class extends Vm{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($m)||[];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)&&eh(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&eh(n,i,r,null),e}};function eh(e,t,n,r){if(t&&n){let i=Zm(t.value),a=Xm(t.value),o=Zm(n.value),s=Xm(n.value);if(e){let r=Hm(i,o);e.value=Gm(e.value,o,r),t.value=Km(t.value,r),n.value=Km(n.value,r)}if(r){let e=Um(a,s);r.value=Wm(r.value,s,e),t.value=qm(t.value,e),n.value=qm(n.value,e)}}else if(n){if(e){let e=Zm(n.value);n.value=n.value.substring(e.length)}if(r){let e=Zm(r.value);r.value=r.value.substring(e.length)}}else if(e&&r){let n=Zm(r.value),i=Zm(t.value),a=Xm(t.value),o=Hm(n,i);t.value=Km(t.value,o);let s=Um(Km(n,o),a);t.value=qm(t.value,s),r.value=Wm(r.value,n,s),e.value=Gm(e.value,n,n.slice(0,n.length-s.length))}else if(r){let e=Zm(r.value),n=Xm(t.value),i=Jm(n,e);t.value=qm(t.value,i)}else if(e){let n=Xm(e.value),r=Zm(t.value),i=Jm(n,r);t.value=Km(t.value,i)}}new class extends Vm{tokenize(e){let t=RegExp(`(\\r?\\n)|[${Qm}]+|[^\\S\\n\\r]+|[^${Qm}]`,`ug`);return e.match(t)||[]}};const th=new class extends Vm{constructor(){super(...arguments),this.tokenize=rh}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
|
|
55
|
+
`),n=n.replace(/\\r/g,`\r`)),t[e]=n}return t}function h(e){e||={};let t=x(e);e.path=t;let n=O.configDotenv(e);if(!n.parsed){let e=Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code=`MISSING_DATA`,e}let r=y(e).split(`,`),i=r.length,a;for(let e=0;e<i;e++)try{let t=r[e].trim(),i=b(n,t);a=O.decrypt(i.ciphertext,i.key);break}catch(t){if(e+1>=i)throw t}return O.parse(a)}function g(e){console.error(`[dotenv@${s}][WARN] ${e}`)}function _(e){console.log(`[dotenv@${s}][DEBUG] ${e}`)}function v(e){console.log(`[dotenv@${s}] ${e}`)}function y(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:``}function b(e,t){let n;try{n=new URL(t)}catch(e){if(e.code===`ERR_INVALID_URL`){let e=Error(`INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development`);throw e.code=`INVALID_DOTENV_KEY`,e}throw e}let r=n.password;if(!r){let e=Error(`INVALID_DOTENV_KEY: Missing key part`);throw e.code=`INVALID_DOTENV_KEY`,e}let i=n.searchParams.get(`environment`);if(!i){let e=Error(`INVALID_DOTENV_KEY: Missing environment part`);throw e.code=`INVALID_DOTENV_KEY`,e}let a=`DOTENV_VAULT_${i.toUpperCase()}`,o=e.parsed[a];if(!o){let e=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${a} in your .env.vault file.`);throw e.code=`NOT_FOUND_DOTENV_ENVIRONMENT`,e}return{ciphertext:o,key:r}}function x(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let r of e.path)n.existsSync(r)&&(t=r.endsWith(`.vault`)?r:`${r}.vault`);else t=e.path.endsWith(`.vault`)?e.path:`${e.path}.vault`;else t=r.resolve(process.cwd(),`.env.vault`);return n.existsSync(t)?t:null}function S(e){return e[0]===`~`?r.join(a.homedir(),e.slice(1)):e}function C(e){let t=u(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=u(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(t||!n)&&v(`Loading env from encrypted .env.vault`);let r=O._parseVault(e),i=process.env;return e&&e.processEnv!=null&&(i=e.processEnv),O.populate(i,r,e),{parsed:r}}function w(e){let t=r.resolve(process.cwd(),`.env`),i=`utf8`,a=process.env;e&&e.processEnv!=null&&(a=e.processEnv);let o=u(a.DOTENV_CONFIG_DEBUG||e&&e.debug),s=u(a.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?i=e.encoding:o&&_(`No encoding is specified. UTF-8 is used by default`);let c=[t];if(e&&e.path)if(!Array.isArray(e.path))c=[S(e.path)];else{c=[];for(let t of e.path)c.push(S(t))}let d,p={};for(let t of c)try{let r=O.parse(n.readFileSync(t,{encoding:i}));O.populate(p,r,e)}catch(e){o&&_(`Failed to load ${t} ${e.message}`),d=e}let m=O.populate(a,p,e);if(o=u(a.DOTENV_CONFIG_DEBUG||o),s=u(a.DOTENV_CONFIG_QUIET||s),o||!s){let e=Object.keys(m).length,t=[];for(let e of c)try{let n=r.relative(process.cwd(),e);t.push(n)}catch(t){o&&_(`Failed to load ${e} ${t.message}`),d=t}v(`injecting env (${e}) from ${t.join(`,`)} ${f(`-- tip: ${l()}`)}`)}return d?{parsed:p,error:d}:{parsed:p}}function T(e){if(y(e).length===0)return O.configDotenv(e);let t=x(e);return t?O._configVault(e):(g(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),O.configDotenv(e))}function E(e,t){let n=Buffer.from(t.slice(-64),`hex`),r=Buffer.from(e,`base64`),i=r.subarray(0,12),a=r.subarray(-16);r=r.subarray(12,-16);try{let e=o.createDecipheriv(`aes-256-gcm`,n,i);return e.setAuthTag(a),`${e.update(r)}${e.final()}`}catch(e){let t=e instanceof RangeError,n=e.message===`Invalid key length`,r=e.message===`Unsupported state or unable to authenticate data`;if(t||n){let e=Error(`INVALID_DOTENV_KEY: It must be 64 characters long (or more)`);throw e.code=`INVALID_DOTENV_KEY`,e}else if(r){let e=Error(`DECRYPTION_FAILED: Please check your DOTENV_KEY`);throw e.code=`DECRYPTION_FAILED`,e}else throw e}}function D(e,t,n={}){let r=!!(n&&n.debug),i=!!(n&&n.override),a={};if(typeof t!=`object`){let e=Error(`OBJECT_REQUIRED: Please check the processEnv argument being passed to populate`);throw e.code=`OBJECT_REQUIRED`,e}for(let n of Object.keys(t))Object.prototype.hasOwnProperty.call(e,n)?(i===!0&&(e[n]=t[n],a[n]=t[n]),r&&_(i===!0?`"${n}" is already defined and WAS overwritten`:`"${n}" is already defined and was NOT overwritten`)):(e[n]=t[n],a[n]=t[n]);return a}let O={configDotenv:w,_configVault:C,_parseVault:h,config:T,decrypt:E,parse:m,populate:D};t.exports.configDotenv=O.configDotenv,t.exports._configVault=O._configVault,t.exports._parseVault=O._parseVault,t.exports.config=O.config,t.exports.decrypt=O.decrypt,t.exports.parse=O.parse,t.exports.populate=O.populate,t.exports=O}))());async function zm(e,t){let n=e;for(;n!==B(n);){let e=ue(n,t);try{return await V(e),e}catch{}n=B(n)}}function Bm(e,t,n=`.env.local`){let[r,i]=G({});return U(()=>{let r,a=e=>{try{let t=pe(e,`utf-8`),n=(0,Rm.parse)(t);i(n)}catch(e){t.error(`system`,`Error reading ${n}:`,e),i({})}};return zm(e,n).then(e=>{if(!e){i({});return}a(e),r=me(e,{persistent:!1},()=>{a(e)})}),()=>{r&&r.close()}},[e,n]),r}var Vm=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}else return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h){d[r]=void 0;continue}if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}};new class extends Vm{};function Hm(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 Um(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 Wm(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 Gm(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 Km(e,t){return Wm(e,t,``)}function qm(e,t){return Gm(e,t,``)}function Jm(e,t){return t.slice(0,Ym(e,t))}function Ym(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 Xm(e){let t;for(t=e.length-1;t>=0&&e[t].match(/\s/);t--);return e.substring(t+1)}function Zm(e){let t=e.match(/^\s*/);return t?t[0]:``}const Qm=`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}`,$m=RegExp(`[${Qm}]+|\\s+|[^${Qm}]`,`ug`);new class extends Vm{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($m)||[];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)&&eh(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&eh(n,i,r,null),e}};function eh(e,t,n,r){if(t&&n){let i=Zm(t.value),a=Xm(t.value),o=Zm(n.value),s=Xm(n.value);if(e){let r=Hm(i,o);e.value=Gm(e.value,o,r),t.value=Km(t.value,r),n.value=Km(n.value,r)}if(r){let e=Um(a,s);r.value=Wm(r.value,s,e),t.value=qm(t.value,e),n.value=qm(n.value,e)}}else if(n){if(e){let e=Zm(n.value);n.value=n.value.substring(e.length)}if(r){let e=Zm(r.value);r.value=r.value.substring(e.length)}}else if(e&&r){let n=Zm(r.value),i=Zm(t.value),a=Xm(t.value),o=Hm(n,i);t.value=Km(t.value,o);let s=Um(Km(n,o),a);t.value=qm(t.value,s),r.value=Wm(r.value,n,s),e.value=Gm(e.value,n,n.slice(0,n.length-s.length))}else if(r){let e=Zm(r.value),n=Jm(Xm(t.value),e);t.value=qm(t.value,n)}else if(e){let n=Jm(Xm(e.value),Zm(t.value));t.value=Km(t.value,n)}}new class extends Vm{tokenize(e){let t=RegExp(`(\\r?\\n)|[${Qm}]+|[^\\S\\n\\r]+|[^${Qm}]`,`ug`);return e.match(t)||[]}};const th=new class extends Vm{constructor(){super(...arguments),this.tokenize=rh}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
|
|
56
56
|
`))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(`
|
|
57
57
|
`))&&(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
|
|
58
58
|
`)&&(e=e.slice(0,-1)),t.endsWith(`
|
|
59
59
|
`)&&(t=t.slice(0,-1))),super.equals(e,t,n)}};function nh(e,t,n){return th.diff(e,t,n)}function rh(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
|
|
60
|
-
`));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 ih(e){return e==`.`||e==`!`||e==`?`}new class extends Vm{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(ih(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 class extends Vm{tokenize(e){return e.split(/([{}:;,]|\s+)/)}},new class extends Vm{constructor(){super(...arguments),this.tokenize=rh}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(ah(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)}};function ah(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]=ah(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]=ah(e[s],t,n,r,s);t.pop(),n.pop()}else o=e;return o}new class extends Vm{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}};function oh(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;nh(n,r,Object.assign(Object.assign({},s),{callback:t=>{
|
|
60
|
+
`));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 ih(e){return e==`.`||e==`!`||e==`?`}new class extends Vm{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(ih(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 class extends Vm{tokenize(e){return e.split(/([{}:;,]|\s+)/)}},new class extends Vm{constructor(){super(...arguments),this.tokenize=rh}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(ah(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)}};function ah(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]=ah(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]=ah(e[s],t,n,r,s);t.pop(),n.pop()}else o=e;return o}new class extends Vm{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}};function oh(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;nh(n,r,Object.assign(Object.assign({},s),{callback:t=>{e(l(t))}}))}else return l(nh(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||sh(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(`
|
|
61
61
|
`)?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 sh(e){let t=e.endsWith(`
|
|
62
62
|
`),n=e.split(`
|
|
63
63
|
`).map(e=>e+`
|
|
@@ -121,7 +121,7 @@ When making edits:
|
|
|
121
121
|
If you want to create a new file, use:
|
|
122
122
|
- A new file path, including dir name if needed
|
|
123
123
|
- First edit: empty old_string and the new file's contents as new_string
|
|
124
|
-
- Subsequent edits: normal edit operations on the created content`,inputSchema:q.object({file_path:q.string(),edits:q.array(q.object({old_string:q.string(),new_string:q.string(),expected_replacements:q.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
|
|
124
|
+
- Subsequent edits: normal edit operations on the created content`,inputSchema:q.object({file_path:q.string(),edits:q.array(q.object({old_string:q.string(),new_string:q.string(),expected_replacements:q.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=mh(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=hh(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=oh(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:uh(({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.
|
|
125
125
|
|
|
126
126
|
Use this for:
|
|
127
127
|
- Finding test failures and error messages
|
|
@@ -129,7 +129,620 @@ Use this for:
|
|
|
129
129
|
- Extracting relevant information from verbose output
|
|
130
130
|
- Analyzing build or test results
|
|
131
131
|
|
|
132
|
-
Example: After running tests with \`workspace_bash\`, use this to find all FAIL: lines rather than re-running the test command.`,inputSchema:q.object({pid:q.number(),pattern:q.string(),before_lines:q.number(),after_lines:q.number()}),execute:async(t,n)=>{let r;try{r=new RegExp(t.pattern)}catch{throw Error(`Invalid regex pattern: ${t.pattern}`)}let{lines:i}=await(await e()).request(`process_read_plain_output`,{pid:t.pid},{signal:n.abortSignal}),a=[];for(let e=0;e<i.length;e++)if(i[e].match(r)){let n=Math.max(0,e-t.before_lines),r=Math.min(i.length-1,e+t.after_lines),o=i.slice(n,r+1);a.push({line_number:e,lines:o})}if(a.length>256)throw Error(`Too many matches. Please refine your search.`);return{matches:a,total_matches:a.length}}}))},ph=async function*({client:e,pid:t,abortSignal:n,timeoutMs:r}){let i=await e,a=[],o=null,s=!1,c=null,l=``,u=i.onNotification(`process_output`,e=>{e.pid===t&&(l+=e.output,a.push({pid:t,ansiOutput:l}),o?.())}),d=i.request(`process_wait`,{pid:t,output_idle_timeout_ms:3e3,timeout_ms:r??25e3},{signal:n}).then(e=>{a.push({pid:e.pid,title:e.title,command:e.command,args:e.args,cwd:e.cwd,env:e.env,ansiOutput:e.ansi_output,plainOutput:{totalLines:e.plain_output.total_lines,lines:e.plain_output.lines},durationMs:e.duration_ms,exitCode:e.exit_code,exitSignal:e.exit_signal,stillRunning:typeof e.exit_code!=`number`&&typeof e.exit_signal!=`number`}),s=!0,o?.()}).catch(e=>{c=e,s=!0,o?.()});try{for(;!s||a.length>0;){if(c)throw c;for(a.length===0&&(await new Promise(e=>{o=e}),o=null);a.length>0;)yield a.shift()}await d}finally{u.dispose()}};q.union([q.object({pid:q.number(),ansiOutput:q.string()}),q.object({pid:q.number(),title:q.string().optional(),command:q.string(),args:q.array(q.string()),cwd:q.string(),env:q.record(q.string(),q.string()),ansiOutput:q.string(),plainOutput:q.object({totalLines:q.number(),lines:q.array(q.string())}),durationMs:q.number(),exitCode:q.number().optional(),exitSignal:q.number().optional(),stillRunning:q.boolean()})]);const mh=(e,t)=>{if(t.length===0)return 0;let n=0,r=0;for(;(r=e.indexOf(t,r))!==-1;)n++,r+=t.length;return n},hh=(e,t,n)=>t.length===0?e:e.split(t).join(n),gh={
|
|
132
|
+
Example: After running tests with \`workspace_bash\`, use this to find all FAIL: lines rather than re-running the test command.`,inputSchema:q.object({pid:q.number(),pattern:q.string(),before_lines:q.number(),after_lines:q.number()}),execute:async(t,n)=>{let r;try{r=new RegExp(t.pattern)}catch{throw Error(`Invalid regex pattern: ${t.pattern}`)}let{lines:i}=await(await e()).request(`process_read_plain_output`,{pid:t.pid},{signal:n.abortSignal}),a=[];for(let e=0;e<i.length;e++)if(i[e].match(r)){let n=Math.max(0,e-t.before_lines),r=Math.min(i.length-1,e+t.after_lines),o=i.slice(n,r+1);a.push({line_number:e,lines:o})}if(a.length>256)throw Error(`Too many matches. Please refine your search.`);return{matches:a,total_matches:a.length}}}))},ph=async function*({client:e,pid:t,abortSignal:n,timeoutMs:r}){let i=await e,a=[],o=null,s=!1,c=null,l=``,u=i.onNotification(`process_output`,e=>{e.pid===t&&(l+=e.output,a.push({pid:t,ansiOutput:l}),o?.())}),d=i.request(`process_wait`,{pid:t,output_idle_timeout_ms:3e3,timeout_ms:r??25e3},{signal:n}).then(e=>{a.push({pid:e.pid,title:e.title,command:e.command,args:e.args,cwd:e.cwd,env:e.env,ansiOutput:e.ansi_output,plainOutput:{totalLines:e.plain_output.total_lines,lines:e.plain_output.lines},durationMs:e.duration_ms,exitCode:e.exit_code,exitSignal:e.exit_signal,stillRunning:typeof e.exit_code!=`number`&&typeof e.exit_signal!=`number`}),s=!0,o?.()}).catch(e=>{c=e,s=!0,o?.()});try{for(;!s||a.length>0;){if(c)throw c;for(a.length===0&&(await new Promise(e=>{o=e}),o=null);a.length>0;)yield a.shift()}await d}finally{u.dispose()}};q.union([q.object({pid:q.number(),ansiOutput:q.string()}),q.object({pid:q.number(),title:q.string().optional(),command:q.string(),args:q.array(q.string()),cwd:q.string(),env:q.record(q.string(),q.string()),ansiOutput:q.string(),plainOutput:q.object({totalLines:q.number(),lines:q.array(q.string())}),durationMs:q.number(),exitCode:q.number().optional(),exitSignal:q.number().optional(),stillRunning:q.boolean()})]);const mh=(e,t)=>{if(t.length===0)return 0;let n=0,r=0;for(;(r=e.indexOf(t,r))!==-1;)n++,r+=t.length;return n},hh=(e,t,n)=>t.length===0?e:e.split(t).join(n),gh={scout:{".env.local.hbs":`# Store local environment variables here.
|
|
133
|
+
# They will be used by blink dev for development.
|
|
134
|
+
{{#each envLocal}}
|
|
135
|
+
{{this.[0]}}={{this.[1]}}
|
|
136
|
+
{{/each}}
|
|
137
|
+
{{#unless (hasAnyEnvVar envLocal "OPENAI_API_KEY" "ANTHROPIC_API_KEY" "AI_GATEWAY_API_KEY")}}
|
|
138
|
+
# OPENAI_API_KEY=
|
|
139
|
+
# ANTHROPIC_API_KEY=
|
|
140
|
+
# AI_GATEWAY_API_KEY=
|
|
141
|
+
{{/unless}}
|
|
142
|
+
|
|
143
|
+
# Web search (optional - get an API key from https://exa.ai)
|
|
144
|
+
# EXA_API_KEY=
|
|
145
|
+
|
|
146
|
+
# Coder credentials (optional - for production compute)
|
|
147
|
+
# CODER_URL=
|
|
148
|
+
# CODER_SESSION_TOKEN=
|
|
149
|
+
# CODER_TEMPLATE=
|
|
150
|
+
# CODER_PRESET_NAME=
|
|
151
|
+
`,".env.production":`# Store production environment variables here.
|
|
152
|
+
# They will be upserted as secrets on blink deploy.
|
|
153
|
+
# OPENAI_API_KEY=
|
|
154
|
+
# ANTHROPIC_API_KEY=
|
|
155
|
+
# AI_GATEWAY_API_KEY=
|
|
156
|
+
|
|
157
|
+
# Slack App credentials
|
|
158
|
+
# SLACK_BOT_TOKEN=
|
|
159
|
+
# SLACK_SIGNING_SECRET=
|
|
160
|
+
|
|
161
|
+
# GitHub App credentials
|
|
162
|
+
# GITHUB_APP_ID=
|
|
163
|
+
# GITHUB_CLIENT_ID=
|
|
164
|
+
# GITHUB_CLIENT_SECRET=
|
|
165
|
+
# GITHUB_WEBHOOK_SECRET=
|
|
166
|
+
# GITHUB_PRIVATE_KEY=
|
|
167
|
+
|
|
168
|
+
# Web search
|
|
169
|
+
# EXA_API_KEY=
|
|
170
|
+
|
|
171
|
+
# Coder credentials (recommended for production)
|
|
172
|
+
# CODER_URL=
|
|
173
|
+
# CODER_SESSION_TOKEN=
|
|
174
|
+
# CODER_TEMPLATE=
|
|
175
|
+
# CODER_PRESET_NAME=
|
|
176
|
+
`,".gitignore":`# dependencies
|
|
177
|
+
node_modules
|
|
178
|
+
|
|
179
|
+
# config and build
|
|
180
|
+
.blink/*
|
|
181
|
+
!.blink/config.json
|
|
182
|
+
|
|
183
|
+
# dotenv environment variables file
|
|
184
|
+
.env
|
|
185
|
+
.env.*
|
|
186
|
+
|
|
187
|
+
# Finder (MacOS) folder config
|
|
188
|
+
.DS_Store
|
|
189
|
+
`,"AGENTS.md":`This project is a Blink agent.
|
|
190
|
+
|
|
191
|
+
You are an expert software engineer, which makes you an expert agent developer. You are highly idiomatic, opinionated, concise, and precise. The user prefers accuracy over speed.
|
|
192
|
+
|
|
193
|
+
<communication>
|
|
194
|
+
1. Be concise, direct, and to the point.
|
|
195
|
+
2. You are communicating via a terminal interface, so avoid verbosity, preambles, postambles, and unnecessary whitespace.
|
|
196
|
+
3. NEVER use emojis unless the user explicitly asks for them.
|
|
197
|
+
4. You must avoid text before/after your response, such as "The answer is" or "Short answer:", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...".
|
|
198
|
+
5. Mimic the style of the user's messages.
|
|
199
|
+
6. Do not remind the user you are happy to help.
|
|
200
|
+
7. Do not act with sycophantic flattery or over-the-top enthusiasm.
|
|
201
|
+
8. Do not regurgitate tool output. e.g. if a command succeeds, acknowledge briefly (e.g. "Done" or "Formatted").
|
|
202
|
+
9. *NEVER* create markdown files for the user - *always* guide the user through your efforts.
|
|
203
|
+
10. *NEVER* create example scripts for the user, or examples scripts for you to run. Leverage your tools to accomplish the user's goals.
|
|
204
|
+
</communication>
|
|
205
|
+
|
|
206
|
+
<goals>
|
|
207
|
+
Your method of assisting the user is by iterating their agent using the context provided by the user in run mode.
|
|
208
|
+
|
|
209
|
+
You can obtain additional context by leveraging web search and compute tools to read files, run commands, and search the web.
|
|
210
|
+
|
|
211
|
+
The user is _extremely happy_ to provide additional context. They prefer this over you guessing, and then potentially getting it wrong.
|
|
212
|
+
|
|
213
|
+
<example>
|
|
214
|
+
user: i want a coding agent
|
|
215
|
+
assistant: Let me take a look at your codebase...
|
|
216
|
+
... tool calls to investigate the codebase...
|
|
217
|
+
assistant: I've created tools for linting, testing, and formatting. Hop back in run mode to use your agent! If you ever encounter undesired behavior from your agent, switch back to edit mode to refine your agent.
|
|
218
|
+
</example>
|
|
219
|
+
|
|
220
|
+
Always investigate the current state of the agent before assisting the user.
|
|
221
|
+
</goals>
|
|
222
|
+
|
|
223
|
+
<agent_development>
|
|
224
|
+
Agents are written in TypeScript, and mostly stored in a single \`agent.ts\` file. Complex agents will have multiple files, like a proper codebase.
|
|
225
|
+
|
|
226
|
+
Environment variables are stored in \`.env.local\` and \`.env.production\`. \`blink dev\` will hot-reload environment variable changes in \`.env.local\`.
|
|
227
|
+
|
|
228
|
+
Changes to the agent are hot-reloaded. As you make edits, the user can immediately try them in run mode.
|
|
229
|
+
|
|
230
|
+
1. _ALWAYS_ use the package manager the user is using (inferred from lock files or \`process.argv\`).
|
|
231
|
+
2. You _MUST_ use \`agent.store\` to persist state. The agent process is designed to be stateless.
|
|
232
|
+
3. Test your changes to the user's agent by using the \`message_user_agent\` tool. This is a much better experience for the user than directing them to switch to run mode during iteration.
|
|
233
|
+
4. Use console.log for debugging. The console output appears for the user.
|
|
234
|
+
5. Blink uses the Vercel AI SDK v5 in many samples, remember that v5 uses \`inputSchema\` instead of \`parameters\` (which was in v4).
|
|
235
|
+
6. Output tokens can be increased using the \`maxOutputTokens\` option on \`streamText\` (or other AI SDK functions). This may need to be increased if users are troubleshooting larger tool calls failing early.
|
|
236
|
+
7. Use the TypeScript language service tools (\`typescript_completions\`, \`typescript_quickinfo\`, \`typescript_definition\`, \`typescript_diagnostics\`) to understand APIs, discover available methods, check types, and debug errors. These tools use tsserver to provide IDE-like intelligence.
|
|
237
|
+
|
|
238
|
+
If the user is asking for a behavioral change, you should update the agent's system prompt.
|
|
239
|
+
This will not ensure the behavior, but it will guide the agent towards the desired behavior.
|
|
240
|
+
If the user needs 100% behavioral certainty, adjust tool behavior instead.
|
|
241
|
+
</agent_development>
|
|
242
|
+
|
|
243
|
+
<agent_web_requests>
|
|
244
|
+
Agents are HTTP servers, so they can handle web requests. This is commonly used to async-invoke an agent. e.g. for a Slack bot, messages are sent to the agent via a webhook.
|
|
245
|
+
|
|
246
|
+
Blink automatically creates a reverse-tunnel to your local machine for simple local development with external services (think Slack Bot, GitHub Bot, etc.).
|
|
247
|
+
|
|
248
|
+
To trigger chats based on web requests, use the \`agent.chat.upsert\` and \`agent.chat.message\` APIs.
|
|
249
|
+
</agent_web_requests>
|
|
250
|
+
|
|
251
|
+
<technical_knowledge>
|
|
252
|
+
Blink agents are Node.js HTTP servers built on the Vercel AI SDK:
|
|
253
|
+
|
|
254
|
+
\`\`\`typescript
|
|
255
|
+
import { convertToModelMessages, streamText } from "ai";
|
|
256
|
+
import * as blink from "blink";
|
|
257
|
+
|
|
258
|
+
const agent = new blink.Agent();
|
|
259
|
+
|
|
260
|
+
agent.on("chat", async ({ messages, chat, abortSignal }) => {
|
|
261
|
+
return streamText({
|
|
262
|
+
model: "anthropic/claude-sonnet-4.5",
|
|
263
|
+
system: "You are a helpful assistant.",
|
|
264
|
+
messages: convertToModelMessages(messages, {
|
|
265
|
+
ignoreIncompleteToolCalls: true,
|
|
266
|
+
}),
|
|
267
|
+
tools: {
|
|
268
|
+
/* your tools */
|
|
269
|
+
},
|
|
270
|
+
});
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
agent.on("request", async (request) => {
|
|
274
|
+
// Handle webhooks, OAuth callbacks, etc.
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
agent.serve();
|
|
278
|
+
\`\`\`
|
|
279
|
+
|
|
280
|
+
Event Handlers:
|
|
281
|
+
|
|
282
|
+
**\`agent.on("chat", handler)\`**
|
|
283
|
+
|
|
284
|
+
1. Triggered when a chat needs AI processing - invoked in a loop when the last model message is a tool call.
|
|
285
|
+
2. Must return: \`streamText()\` result, \`Response\`, \`ReadableStream<UIMessageChunk>\`, or \`void\`
|
|
286
|
+
3. Parameters: \`messages\`, \`id\`, \`abortSignal\`
|
|
287
|
+
|
|
288
|
+
_NEVER_ use "maxSteps" from the Vercel AI SDK. It is unnecessary and will cause a worse experience for the user.
|
|
289
|
+
|
|
290
|
+
**\`agent.on("request", handler)\`**
|
|
291
|
+
• Handles raw HTTP requests before Blink processes them
|
|
292
|
+
• Use for: OAuth callbacks, webhook verification, custom endpoints
|
|
293
|
+
• Return \`Response\` to handle, or \`void\` to pass through
|
|
294
|
+
|
|
295
|
+
**\`agent.on("ui", handler)\`**
|
|
296
|
+
• Provides dynamic UI options for chat interfaces
|
|
297
|
+
• Returns schema defining user-selectable options
|
|
298
|
+
|
|
299
|
+
**\`agent.on("error", handler)\`**
|
|
300
|
+
• Global error handler for the agent
|
|
301
|
+
|
|
302
|
+
Chat Management:
|
|
303
|
+
|
|
304
|
+
Blink automatically manages chat state:
|
|
305
|
+
|
|
306
|
+
\`\`\`typescript
|
|
307
|
+
// Create or get existing chat
|
|
308
|
+
// The parameter can be any JSON-serializable value.
|
|
309
|
+
// e.g. for a Slack bot to preserve context in a thread, you might use: ["slack", teamId, channelId, threadTs]
|
|
310
|
+
const chat = await agent.chat.upsert("unique-key");
|
|
311
|
+
|
|
312
|
+
// Send a message to a chat
|
|
313
|
+
await agent.chat.sendMessages(
|
|
314
|
+
chat.id,
|
|
315
|
+
[
|
|
316
|
+
{
|
|
317
|
+
role: "user",
|
|
318
|
+
parts: [{ type: "text", text: "Message" }],
|
|
319
|
+
},
|
|
320
|
+
],
|
|
321
|
+
{
|
|
322
|
+
behavior: "interrupt" | "enqueue" | "append",
|
|
323
|
+
}
|
|
324
|
+
);
|
|
325
|
+
|
|
326
|
+
// When sending messages, feel free to inject additional parts to direct the model.
|
|
327
|
+
// e.g. if the user is asking for specific behavior in specific scenarios, the simplest
|
|
328
|
+
// answer is to append a text part: "always do X when Y".
|
|
329
|
+
\`\`\`
|
|
330
|
+
|
|
331
|
+
Behaviors:
|
|
332
|
+
• "interrupt": Stop current processing and handle immediately
|
|
333
|
+
• "enqueue": Queue message, process when current chat finishes
|
|
334
|
+
• "append": Add to history without triggering processing
|
|
335
|
+
|
|
336
|
+
Chat keys: Use structured keys like \`"slack-\${teamId}-\${channelId}-\${threadTs}"\` for uniqueness.
|
|
337
|
+
|
|
338
|
+
Storage API:
|
|
339
|
+
|
|
340
|
+
Persistent key-value storage per agent:
|
|
341
|
+
|
|
342
|
+
\`\`\`typescript
|
|
343
|
+
// Store data
|
|
344
|
+
await agent.store.set("key", "value", { ttl: 3600 });
|
|
345
|
+
|
|
346
|
+
// Retrieve data
|
|
347
|
+
const value = await agent.store.get("key");
|
|
348
|
+
|
|
349
|
+
// Delete data
|
|
350
|
+
await agent.store.delete("key");
|
|
351
|
+
|
|
352
|
+
// List keys by prefix
|
|
353
|
+
const result = await agent.store.list("prefix-", { limit: 100 });
|
|
354
|
+
\`\`\`
|
|
355
|
+
|
|
356
|
+
Common uses: OAuth tokens, user preferences, caching, chat-resource associations.
|
|
357
|
+
|
|
358
|
+
Tools:
|
|
359
|
+
|
|
360
|
+
Tools follow Vercel AI SDK patterns with Zod validation:
|
|
361
|
+
|
|
362
|
+
\`\`\`typescript
|
|
363
|
+
import { tool } from "ai";
|
|
364
|
+
import { z } from "zod";
|
|
365
|
+
|
|
366
|
+
const myTool = tool({
|
|
367
|
+
description: "Clear description of what this tool does",
|
|
368
|
+
inputSchema: z.object({
|
|
369
|
+
param: z.string().describe("Parameter description"),
|
|
370
|
+
}),
|
|
371
|
+
execute: async (args, opts) => {
|
|
372
|
+
// opts.abortSignal for cancellation
|
|
373
|
+
// opts.toolCallId for unique identification
|
|
374
|
+
return result;
|
|
375
|
+
},
|
|
376
|
+
});
|
|
377
|
+
\`\`\`
|
|
378
|
+
|
|
379
|
+
Tool Approvals for destructive operations:
|
|
380
|
+
|
|
381
|
+
\`\`\`typescript
|
|
382
|
+
...await blink.tools.withApproval({
|
|
383
|
+
messages,
|
|
384
|
+
tools: {
|
|
385
|
+
delete_database: tool({ /* ... */ }),
|
|
386
|
+
},
|
|
387
|
+
})
|
|
388
|
+
\`\`\`
|
|
389
|
+
|
|
390
|
+
Tool Context for dependency injection:
|
|
391
|
+
|
|
392
|
+
\`\`\`typescript
|
|
393
|
+
...blink.tools.withContext(github.tools, {
|
|
394
|
+
accessToken: process.env.GITHUB_TOKEN,
|
|
395
|
+
})
|
|
396
|
+
\`\`\`
|
|
397
|
+
|
|
398
|
+
Tool Prefixing to avoid collisions:
|
|
399
|
+
|
|
400
|
+
\`\`\`typescript
|
|
401
|
+
...blink.tools.prefix(github.tools, "github_")
|
|
402
|
+
\`\`\`
|
|
403
|
+
|
|
404
|
+
LLM Models:
|
|
405
|
+
|
|
406
|
+
\`\`\`typescript
|
|
407
|
+
import { anthropic } from "@ai-sdk/anthropic";
|
|
408
|
+
import { openai } from "@ai-sdk/openai";
|
|
409
|
+
|
|
410
|
+
model: anthropic("claude-sonnet-4.5", {
|
|
411
|
+
apiKey: process.env.ANTHROPIC_API_KEY,
|
|
412
|
+
});
|
|
413
|
+
// Use chat API for OpenAI models - it's more reliable than the responses API
|
|
414
|
+
model: openai.chat("gpt-5", { apiKey: process.env.OPENAI_API_KEY });
|
|
415
|
+
\`\`\`
|
|
416
|
+
|
|
417
|
+
**Note about Edit Mode:** Edit mode (this agent) automatically selects models in this priority:
|
|
418
|
+
|
|
419
|
+
1. If \`ANTHROPIC_API_KEY\` is set: uses \`claude-sonnet-4.5\` via \`@ai-sdk/anthropic\`
|
|
420
|
+
2. If \`OPENAI_API_KEY\` is set: uses \`gpt-5\` via \`@ai-sdk/openai\`
|
|
421
|
+
|
|
422
|
+
Available SDKs:
|
|
423
|
+
|
|
424
|
+
**@blink-sdk/compute**
|
|
425
|
+
|
|
426
|
+
\`\`\`typescript
|
|
427
|
+
import * as compute from "@blink-sdk/compute";
|
|
428
|
+
|
|
429
|
+
tools: {
|
|
430
|
+
...compute.tools, // execute_bash, read_file, write_file, edit_file, process management
|
|
431
|
+
}
|
|
432
|
+
\`\`\`
|
|
433
|
+
|
|
434
|
+
**@blink-sdk/github**
|
|
435
|
+
|
|
436
|
+
\`\`\`typescript
|
|
437
|
+
import * as github from "@blink-sdk/github";
|
|
438
|
+
|
|
439
|
+
tools: {
|
|
440
|
+
...blink.tools.withContext(github.tools, {
|
|
441
|
+
accessToken: process.env.GITHUB_TOKEN,
|
|
442
|
+
}),
|
|
443
|
+
}
|
|
444
|
+
\`\`\`
|
|
445
|
+
|
|
446
|
+
**@blink-sdk/slack**
|
|
447
|
+
|
|
448
|
+
\`\`\`typescript
|
|
449
|
+
import * as slack from "@blink-sdk/slack";
|
|
450
|
+
import { App } from "@slack/bolt";
|
|
451
|
+
|
|
452
|
+
const receiver = new slack.Receiver();
|
|
453
|
+
const app = new App({
|
|
454
|
+
token: process.env.SLACK_BOT_TOKEN,
|
|
455
|
+
signingSecret: process.env.SLACK_SIGNING_SECRET,
|
|
456
|
+
receiver,
|
|
457
|
+
});
|
|
458
|
+
|
|
459
|
+
// This will trigger when the bot is @mentioned.
|
|
460
|
+
app.event("app_mention", async ({ event }) => {
|
|
461
|
+
// The argument here is a JSON-serializable value.
|
|
462
|
+
// To maintain the same chat context, use the same key.
|
|
463
|
+
const chat = await agent.chat.upsert([
|
|
464
|
+
"slack",
|
|
465
|
+
event.channel,
|
|
466
|
+
event.thread_ts ?? event.ts,
|
|
467
|
+
]);
|
|
468
|
+
const { message } = await slack.createMessageFromEvent({
|
|
469
|
+
client: app.client,
|
|
470
|
+
event,
|
|
471
|
+
});
|
|
472
|
+
await agent.chat.sendMessages(chat.id, [message]);
|
|
473
|
+
// This is a nice immediate indicator for the user.
|
|
474
|
+
await app.client.assistant.threads.setStatus({
|
|
475
|
+
channel_id: event.channel,
|
|
476
|
+
status: "is typing...",
|
|
477
|
+
thread_ts: event.thread_ts ?? event.ts,
|
|
478
|
+
});
|
|
479
|
+
});
|
|
480
|
+
|
|
481
|
+
const agent = new blink.Agent();
|
|
482
|
+
|
|
483
|
+
agent.on("request", async (request) => {
|
|
484
|
+
return receiver.handle(app, request);
|
|
485
|
+
});
|
|
486
|
+
|
|
487
|
+
agent.on("chat", async ({ messages }) => {
|
|
488
|
+
const tools = slack.createTools({ client: app.client });
|
|
489
|
+
return streamText({
|
|
490
|
+
model: "anthropic/claude-sonnet-4.5",
|
|
491
|
+
system: "You chatting with users in Slack.",
|
|
492
|
+
messages: convertToModelMessages(messages, {
|
|
493
|
+
ignoreIncompleteToolCalls: true,
|
|
494
|
+
tools,
|
|
495
|
+
}),
|
|
496
|
+
});
|
|
497
|
+
});
|
|
498
|
+
\`\`\`
|
|
499
|
+
|
|
500
|
+
Slack SDK Notes:
|
|
501
|
+
|
|
502
|
+
- "app_mention" event is triggered in both private channels and public channels.
|
|
503
|
+
- "message" event is triggered regardless of being mentioned or not, and will _also_ be fired when "app_mention" is triggered.
|
|
504
|
+
- _NEVER_ register app event listeners in the "on" handler of the agent. This will cause the handler to be called multiple times.
|
|
505
|
+
- Think about how you scope chats - for example, in IMs or if the user wants to make a bot for a whole channel, you would not want to add "ts" or "thread_ts" to the chat key.
|
|
506
|
+
- When using "assistant.threads.setStatus", you need to ensure the status of that same "thread_ts" is cleared. You can do this by inserting a message part that directs the agent to clear the status (there is a tool if using @blink-sdk/slack called "reportStatus" that does this). e.g. \`message.parts.push({ type: "text", text: "*INTERNAL INSTRUCTION*: Clear the status of this thread after you finish: channel=\${channel} thread_ts=\${thread_ts}" })\`
|
|
507
|
+
- The Slack SDK has many functions that allow users to completely customize the message format. If the user asks for customization, look at the types for @blink-sdk/slack - specifically: "createPartsFromMessageMetadata", "createMessageFromEvent", and "extractMessagesMetadata".
|
|
508
|
+
|
|
509
|
+
Slack App Manifest:
|
|
510
|
+
|
|
511
|
+
- _ALWAYS_ include the "assistant:write" scope unless the user explicitly states otherwise - this allows Slack apps to set their status, which makes for a significantly better user experience. You _MUST_ provide "assistant_view" if you provide this scope.
|
|
512
|
+
- The user can always edit the manifest after creation, but you'd have to suggest it to them.
|
|
513
|
+
- "oauth_config" MUST BE PROVIDED - otherwise the app will have NO ACCESS.
|
|
514
|
+
- _ALWAYS_ default \`token_rotation_enabled\` to false unless the user explicitly asks for it. It is a _much_ simpler user-experience to not rotate tokens.
|
|
515
|
+
- For the best user experience, default to the following bot scopes (in the "oauth_config" > "scopes" > "bot"):
|
|
516
|
+
- "app_mentions:read"
|
|
517
|
+
- "reactions:write"
|
|
518
|
+
- "reactions:read"
|
|
519
|
+
- "channels:history"
|
|
520
|
+
- "chat:write"
|
|
521
|
+
- "groups:history"
|
|
522
|
+
- "groups:read"
|
|
523
|
+
- "files:read"
|
|
524
|
+
- "im:history"
|
|
525
|
+
- "im:read"
|
|
526
|
+
- "im:write"
|
|
527
|
+
- "mpim:history"
|
|
528
|
+
- "mpim:read"
|
|
529
|
+
- "users:read"
|
|
530
|
+
- "links:read"
|
|
531
|
+
- "commands"
|
|
532
|
+
- For the best user experience, default to the following bot events (in the "settings" > "event_subscriptions" > "bot_events"):
|
|
533
|
+
- "app_mention"
|
|
534
|
+
- "message.channels",
|
|
535
|
+
- "message.groups",
|
|
536
|
+
- "message.im",
|
|
537
|
+
- "reaction_added"
|
|
538
|
+
- "reaction_removed"
|
|
539
|
+
- "assistant_thread_started"
|
|
540
|
+
- "member_joined_channel"
|
|
541
|
+
- _NEVER_ include USER SCOPES unless the user explicitly asks for them.
|
|
542
|
+
|
|
543
|
+
WARNING: Beware of attaching multiple event listeners to the same chat. This could cause the agent to respond multiple times.
|
|
544
|
+
|
|
545
|
+
State Management:
|
|
546
|
+
|
|
547
|
+
Blink agents are short-lived HTTP servers that restart on code changes and do not persist in-memory state between requests.
|
|
548
|
+
|
|
549
|
+
_NEVER_ use module-level Maps, Sets, or variables to store state (e.g. \`const activeBots = new Map()\`).
|
|
550
|
+
|
|
551
|
+
For global state persistence, you can use the agent store:
|
|
552
|
+
|
|
553
|
+
- Use \`agent.store\` for persistent key-value storage
|
|
554
|
+
- Query external APIs to fetch current state
|
|
555
|
+
- Use webhooks to trigger actions rather than polling in-memory state
|
|
556
|
+
|
|
557
|
+
For message-level state persistence, use message metadata:
|
|
558
|
+
|
|
559
|
+
\`\`\`typescript
|
|
560
|
+
import { UIMessage } from "blink";
|
|
561
|
+
import * as blink from "blink";
|
|
562
|
+
|
|
563
|
+
const agent = new blink.Agent<
|
|
564
|
+
UIMessage<{
|
|
565
|
+
source: "github";
|
|
566
|
+
associated_id: string;
|
|
567
|
+
}>
|
|
568
|
+
>();
|
|
569
|
+
|
|
570
|
+
agent.on("request", async (request) => {
|
|
571
|
+
// comes from github, we want to do something deterministic in the chat loop with that ID...
|
|
572
|
+
// insert a message with that metadata into the chat
|
|
573
|
+
const chat = await agent.chat.upsert("some-github-key");
|
|
574
|
+
await agent.chat.sendMessages(request.chat.id, [
|
|
575
|
+
{
|
|
576
|
+
role: "user",
|
|
577
|
+
parts: [
|
|
578
|
+
{
|
|
579
|
+
type: "text",
|
|
580
|
+
text: "example",
|
|
581
|
+
},
|
|
582
|
+
],
|
|
583
|
+
metadata: {
|
|
584
|
+
source: "github",
|
|
585
|
+
associated_id: "some-github-id",
|
|
586
|
+
},
|
|
587
|
+
},
|
|
588
|
+
]);
|
|
589
|
+
});
|
|
590
|
+
|
|
591
|
+
agent.on("chat", async ({ messages }) => {
|
|
592
|
+
const message = messages.find(
|
|
593
|
+
(message) => message.metadata?.source === "github"
|
|
594
|
+
);
|
|
595
|
+
|
|
596
|
+
// Now we can use that metadata...
|
|
597
|
+
});
|
|
598
|
+
\`\`\`
|
|
599
|
+
|
|
600
|
+
The agent process can restart at any time, so all important state must be externalized.
|
|
601
|
+
</technical_knowledge>
|
|
602
|
+
|
|
603
|
+
<code_quality>
|
|
604
|
+
|
|
605
|
+
- Never use "as any" type assertions. Always figure out the correct typings.
|
|
606
|
+
</code_quality>
|
|
607
|
+
`,"agent.ts.hbs":`{{#if (eq aiProvider "anthropic")}}
|
|
608
|
+
import { anthropic } from "@ai-sdk/anthropic";
|
|
609
|
+
{{else if (eq aiProvider "openai")}}
|
|
610
|
+
import { openai } from "@ai-sdk/openai";
|
|
611
|
+
{{/if}}
|
|
612
|
+
import { type Message, Scout } from "@blink-sdk/scout-agent";
|
|
613
|
+
import { streamText, tool } from "ai";
|
|
614
|
+
import * as blink from "blink";
|
|
615
|
+
import { z } from "zod";
|
|
616
|
+
|
|
617
|
+
export const agent = new blink.Agent<Message>();
|
|
618
|
+
|
|
619
|
+
const scout = new Scout({
|
|
620
|
+
agent,
|
|
621
|
+
// GitHub integration (optional).
|
|
622
|
+
// Run \`blink setup github-app\` to set up your GitHub App, or remove this section if not needed.
|
|
623
|
+
github: {
|
|
624
|
+
appID: process.env.GITHUB_APP_ID,
|
|
625
|
+
privateKey: process.env.GITHUB_PRIVATE_KEY,
|
|
626
|
+
webhookSecret: process.env.GITHUB_WEBHOOK_SECRET,
|
|
627
|
+
},
|
|
628
|
+
// Slack integration (optional).
|
|
629
|
+
// Run \`blink setup slack-app\` to set up your Slack App, or remove this section if not needed.
|
|
630
|
+
slack: {
|
|
631
|
+
botToken: process.env.SLACK_BOT_TOKEN,
|
|
632
|
+
signingSecret: process.env.SLACK_SIGNING_SECRET,
|
|
633
|
+
},
|
|
634
|
+
// Web search integration (optional). Visit https://exa.ai to get an API key.
|
|
635
|
+
webSearch: {
|
|
636
|
+
exaApiKey: process.env.EXA_API_KEY,
|
|
637
|
+
},
|
|
638
|
+
// Compute environment for running code.
|
|
639
|
+
// Using Docker by default for local development.
|
|
640
|
+
// For production, you can use Coder (https://coder.com) instead:
|
|
641
|
+
// compute: {
|
|
642
|
+
// type: "coder",
|
|
643
|
+
// options: {
|
|
644
|
+
// url: process.env.CODER_URL,
|
|
645
|
+
// sessionToken: process.env.CODER_SESSION_TOKEN,
|
|
646
|
+
// template: process.env.CODER_TEMPLATE,
|
|
647
|
+
// presetName: process.env.CODER_PRESET_NAME,
|
|
648
|
+
// },
|
|
649
|
+
// },
|
|
650
|
+
compute: {
|
|
651
|
+
type: "docker",
|
|
652
|
+
},
|
|
653
|
+
});
|
|
654
|
+
|
|
655
|
+
agent.on("request", async (request) => {
|
|
656
|
+
const url = new URL(request.url);
|
|
657
|
+
if (url.pathname.startsWith("/slack")) {
|
|
658
|
+
return scout.handleSlackWebhook(request);
|
|
659
|
+
}
|
|
660
|
+
if (url.pathname.startsWith("/github")) {
|
|
661
|
+
return scout.handleGitHubWebhook(request);
|
|
662
|
+
}
|
|
663
|
+
return new Response("Hey there!", { status: 200 });
|
|
664
|
+
});
|
|
665
|
+
|
|
666
|
+
agent.on("chat", async ({ id, messages }) => {
|
|
667
|
+
const params = await scout.buildStreamTextParams({
|
|
668
|
+
messages,
|
|
669
|
+
chatID: id,
|
|
670
|
+
{{#if (eq aiProvider "anthropic")}}
|
|
671
|
+
model: anthropic("claude-opus-4-5"),
|
|
672
|
+
{{else if (eq aiProvider "openai")}}
|
|
673
|
+
model: openai.chat("gpt-5"),
|
|
674
|
+
{{else if (eq aiProvider "vercel")}}
|
|
675
|
+
model: "anthropic/claude-opus-4.5",
|
|
676
|
+
{{else}}
|
|
677
|
+
// Unknown provider: {{aiProvider}}. Defaulting to Vercel AI Gateway syntax.
|
|
678
|
+
model: "anthropic/claude-opus-4.5",
|
|
679
|
+
{{/if}}
|
|
680
|
+
providerOptions: { anthropic: { cacheControl: { type: "ephemeral" } } },
|
|
681
|
+
tools: {
|
|
682
|
+
// Add your custom tools here
|
|
683
|
+
get_favorite_color: tool({
|
|
684
|
+
description: "Get your favorite color",
|
|
685
|
+
inputSchema: z.object({}),
|
|
686
|
+
execute() {
|
|
687
|
+
return "blue";
|
|
688
|
+
},
|
|
689
|
+
}),
|
|
690
|
+
},
|
|
691
|
+
});
|
|
692
|
+
return streamText(params);
|
|
693
|
+
});
|
|
694
|
+
|
|
695
|
+
agent.serve();
|
|
696
|
+
`,"package.json.hbs":`{
|
|
697
|
+
"name": "{{packageName}}",
|
|
698
|
+
"main": "agent.ts",
|
|
699
|
+
"type": "module",
|
|
700
|
+
"private": true,
|
|
701
|
+
"scripts": {
|
|
702
|
+
"dev": "blink dev",
|
|
703
|
+
"deploy": "blink deploy"
|
|
704
|
+
},
|
|
705
|
+
"devDependencies": {
|
|
706
|
+
"zod": "latest",
|
|
707
|
+
"ai": "latest",
|
|
708
|
+
{{#if (eq aiProvider "anthropic")}}
|
|
709
|
+
"@ai-sdk/anthropic": "latest",
|
|
710
|
+
{{else if (eq aiProvider "openai")}}
|
|
711
|
+
"@ai-sdk/openai": "latest",
|
|
712
|
+
{{/if}}
|
|
713
|
+
"blink": "latest",
|
|
714
|
+
"esbuild": "latest",
|
|
715
|
+
"@types/node": "latest",
|
|
716
|
+
"typescript": "latest",
|
|
717
|
+
"@blink-sdk/scout-agent": "latest"
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
`,"tsconfig.json":`{
|
|
721
|
+
"compilerOptions": {
|
|
722
|
+
"lib": ["ESNext"],
|
|
723
|
+
"target": "ESNext",
|
|
724
|
+
"module": "Preserve",
|
|
725
|
+
"moduleDetection": "force",
|
|
726
|
+
|
|
727
|
+
"moduleResolution": "bundler",
|
|
728
|
+
"allowImportingTsExtensions": true,
|
|
729
|
+
"verbatimModuleSyntax": true,
|
|
730
|
+
"resolveJsonModule": true,
|
|
731
|
+
"noEmit": true,
|
|
732
|
+
|
|
733
|
+
"strict": true,
|
|
734
|
+
"skipLibCheck": true,
|
|
735
|
+
"noFallthroughCasesInSwitch": true,
|
|
736
|
+
"noUncheckedIndexedAccess": true,
|
|
737
|
+
"noImplicitOverride": true,
|
|
738
|
+
|
|
739
|
+
"noUnusedLocals": false,
|
|
740
|
+
"noUnusedParameters": false,
|
|
741
|
+
|
|
742
|
+
"types": ["node"]
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
`},scratch:{".env.local.hbs":`# Store local environment variables here.
|
|
133
746
|
# They will be used by blink dev for development.
|
|
134
747
|
{{#each envLocal}}
|
|
135
748
|
{{this.[0]}}={{this.[1]}}
|
|
@@ -1280,7 +1893,7 @@ agent.serve();`,"package.json.hbs":`{
|
|
|
1280
1893
|
</form>
|
|
1281
1894
|
<script>document.getElementById('f').submit()<\/script>
|
|
1282
1895
|
</body>
|
|
1283
|
-
</html>`;return new Response(l,{headers:{"Content-Type":`text/html`}})}));return new Promise((e,t)=>{i.on(`error`,t),i.listen(0,`127.0.0.1`,()=>{let n=i.address();if(!n||typeof n==`string`){t(Error(`Failed to get server address`));return}r=`http://127.0.0.1:${n.port}`,e(r)})})}const vh=q.enum([`read`,`write`]),yh=q.union([q.literal(`branch_protection_rule`).describe(`Branch protection rule created, edited, or deleted`),q.literal(`check_run`).describe(`Check run created, completed, or requested`),q.literal(`check_suite`).describe(`Check suite completed or requested`),q.literal(`code_scanning_alert`).describe(`Code scanning alert created, fixed, or reopened`),q.literal(`commit_comment`).describe(`Commit comment created`),q.literal(`create`).describe(`Branch or tag created`),q.literal(`delete`).describe(`Branch or tag deleted`),q.literal(`deployment`).describe(`Deployment created`),q.literal(`deployment_status`).describe(`Deployment status created`),q.literal(`deployment_protection_rule`).describe(`Deployment protection rule requested`),q.literal(`discussion`).describe(`Discussion created, edited, or deleted`),q.literal(`discussion_comment`).describe(`Discussion comment created, edited, or deleted`),q.literal(`fork`).describe(`Repository forked`),q.literal(`gollum`).describe(`Wiki page created or updated`),q.literal(`issue_comment`).describe(`Issue comment created, edited, or deleted`),q.literal(`issues`).describe(`Issue opened, edited, closed, or labeled`),q.literal(`label`).describe(`Label created, edited, or deleted`),q.literal(`member`).describe(`Collaborator added, removed, or edited`),q.literal(`membership`).describe(`Team membership added or removed`),q.literal(`meta`).describe(`GitHub App webhook configuration changed`),q.literal(`milestone`).describe(`Milestone created, closed, or deleted`),q.literal(`organization`).describe(`Organization member added, removed, or invited`),q.literal(`org_block`).describe(`Organization blocked or unblocked a user`),q.literal(`package`).describe(`Package published or updated`),q.literal(`page_build`).describe(`GitHub Pages site built`),q.literal(`project`).describe(`Project created, updated, or deleted`),q.literal(`project_card`).describe(`Project card created, edited, or deleted`),q.literal(`project_column`).describe(`Project column created, updated, or deleted`),q.literal(`public`).describe(`Repository visibility changed to public`),q.literal(`pull_request`).describe(`Pull request opened, closed, edited, or synchronized`),q.literal(`pull_request_review`).describe(`Pull request review submitted, edited, or dismissed`),q.literal(`pull_request_review_comment`).describe(`Pull request review comment created or edited`),q.literal(`pull_request_review_thread`).describe(`Pull request review thread resolved or unresolved`),q.literal(`push`).describe(`Git push to a repository`),q.literal(`registry_package`).describe(`Registry package published or updated`),q.literal(`release`).describe(`Release published or edited`),q.literal(`repository`).describe(`Repository created, deleted, archived, or publicized`),q.literal(`repository_dispatch`).describe(`Custom webhook event triggered`),q.literal(`secret_scanning_alert`).describe(`Secret scanning alert created or resolved`),q.literal(`security_and_analysis`).describe(`Security features enabled or disabled`),q.literal(`star`).describe(`Repository starred or unstarred`),q.literal(`status`).describe(`Commit status created`),q.literal(`team`).describe(`Team created, deleted, or edited`),q.literal(`team_add`).describe(`Repository added to team`),q.literal(`watch`).describe(`User started watching repository`),q.literal(`workflow_dispatch`).describe(`Workflow manually triggered`),q.literal(`workflow_job`).describe(`Workflow job queued, started, or completed`),q.literal(`workflow_run`).describe(`Workflow run requested or completed`)]),bh=q.object({name:q.string().optional().describe(`The name of the GitHub App. Leave blank to let the user name it on GitHub.`),url:q.url().describe(`The homepage URL of the GitHub App. If unknown, set to https://blink.so.`),description:q.string().optional().describe(`The description of the GitHub App.`),public:q.boolean().optional().describe(`Whether the GitHub App is public. Always default to false unless the user explicitly requests otherwise.`),hook_attributes:q.object({url:q.url(),active:q.boolean().optional().default(!0)}).optional().describe(`The webhook configuration for the GitHub App.`),callback_urls:q.array(q.url()).max(10).optional().describe(`Callback URLs for the GitHub App after the user authenticates with GitHub.`),setup_url:q.url().optional().describe(`The URL to redirect the user to after they install the GitHub App.`),setup_on_update:q.boolean().optional().describe(`Whether to redirect the user to the setup URL after an update to the installed app.`),request_oauth_on_install:q.boolean().optional().describe(`Whether to request OAuth on install.`),default_events:q.array(yh).optional().describe(`Webhook events sent to the webhook URL.`),default_permissions:q.record(q.string(),vh).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 xh(e){return`https://api.slack.com/apps?new_app=1&manifest_json=${encodeURIComponent(JSON.stringify(e))}`}const Sh=q.union([q.literal(`app_mention`).describe(`Bot is @mentioned in a channel or conversation. Requires scope: app_mentions:read`),q.literal(`app_home_opened`).describe(`User opened the app's Home tab. No additional scope required beyond bot token`),q.literal(`app_installed`).describe(`App was installed to a workspace. No additional scope required beyond bot token`),q.literal(`app_uninstalled`).describe(`App was uninstalled from a workspace. No additional scope required beyond bot token`),q.literal(`assistant_thread_context_changed`).describe(`Context changed in an assistant thread. Requires scope: assistant:write`),q.literal(`assistant_thread_started`).describe(`New assistant thread was started. Requires scope: assistant:write`),q.literal(`channel_archive`).describe(`Public channel was archived. Requires scope: channels:read`),q.literal(`channel_created`).describe(`Public channel was created. Requires scope: channels:read`),q.literal(`channel_deleted`).describe(`Public channel was deleted. Requires scope: channels:read`),q.literal(`channel_rename`).describe(`Public channel was renamed. Requires scope: channels:read`),q.literal(`channel_unarchive`).describe(`Public channel was unarchived. Requires scope: channels:read`),q.literal(`dnd_updated_user`).describe(`User's Do Not Disturb settings changed. Requires scope: dnd:read`),q.literal(`email_domain_changed`).describe(`Workspace's email domain changed. Requires scope: team:read`),q.literal(`emoji_changed`).describe(`Custom emoji was added or changed. Requires scope: emoji:read`),q.literal(`file_change`).describe(`File was changed. Requires scope: files:read`),q.literal(`file_created`).describe(`File was created. Requires scope: files:read`),q.literal(`file_deleted`).describe(`File was deleted. Requires scope: files:read`),q.literal(`file_public`).describe(`File was made public. Requires scope: files:read`),q.literal(`file_shared`).describe(`File was shared. Requires scope: files:read`),q.literal(`file_unshared`).describe(`File was unshared. Requires scope: files:read`),q.literal(`group_archive`).describe(`Private channel was archived. Requires scope: groups:read`),q.literal(`group_deleted`).describe(`Private channel was deleted. Requires scope: groups:read`),q.literal(`group_rename`).describe(`Private channel was renamed. Requires scope: groups:read`),q.literal(`group_unarchive`).describe(`Private channel was unarchived. Requires scope: groups:read`),q.literal(`link_shared`).describe(`Link from a registered domain was shared. Requires scope: links:read`),q.literal(`member_joined_channel`).describe(`User joined a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),q.literal(`member_left_channel`).describe(`User left a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),q.literal(`message.channels`).describe(`Message was posted in a public channel. Requires scope: channels:history`),q.literal(`message.groups`).describe(`Message was posted in a private channel. Requires scope: groups:history`),q.literal(`message.im`).describe(`Message was posted in a direct message. Requires scope: im:history`),q.literal(`message.mpim`).describe(`Message was posted in a multi-party direct message. Requires scope: mpim:history`),q.literal(`pin_added`).describe(`Item was pinned in a channel. Requires scope: pins:read`),q.literal(`pin_removed`).describe(`Item was unpinned from a channel. Requires scope: pins:read`),q.literal(`reaction_added`).describe(`Reaction was added to a message. Requires scope: reactions:read`),q.literal(`reaction_removed`).describe(`Reaction was removed from a message. Requires scope: reactions:read`),q.literal(`team_join`).describe(`New user joined the workspace. Requires scope: users:read`),q.literal(`user_change`).describe(`User's profile or settings changed. Requires scope: users:read`)]),Ch=q.union([q.literal(`app_mentions:read`).describe(`Read messages that directly mention the bot. Required for: app_mention event`),q.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`),q.literal(`channels:history`).describe(`Read message history in public channels the bot has access to. Required for: message.channels event`),q.literal(`channels:join`).describe(`Join public channels`),q.literal(`channels:manage`).describe(`Manage public channels (archive, rename, etc.)`),q.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`),q.literal(`chat:write`).describe(`Send messages as the bot`),q.literal(`chat:write.customize`).describe(`Send messages with a customized username and avatar`),q.literal(`chat:write.public`).describe(`Send messages to public channels without joining`),q.literal(`commands`).describe(`Add and use slash commands`),q.literal(`dnd:read`).describe(`View Do Not Disturb settings for users. Required for: dnd_updated_user event`),q.literal(`emoji:read`).describe(`View custom emoji in the workspace. Required for: emoji_changed event`),q.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`),q.literal(`files:write`).describe(`Upload, edit, and delete files`),q.literal(`groups:history`).describe(`Read message history in private channels the bot has access to. Required for: message.groups event`),q.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`),q.literal(`groups:write`).describe(`Manage private channels (archive, rename, create, etc.)`),q.literal(`im:history`).describe(`Read message history in direct messages with the bot. Required for: message.im event`),q.literal(`im:read`).describe(`View basic information about direct messages with the bot`),q.literal(`im:write`).describe(`Start and manage direct messages with users`),q.literal(`links:read`).describe(`View URLs in messages. Required for: link_shared event`),q.literal(`links:write`).describe(`Show previews of URLs (unfurling)`),q.literal(`metadata.message:read`).describe(`Read message metadata`),q.literal(`mpim:history`).describe(`Read message history in multi-party direct messages. Required for: message.mpim event`),q.literal(`mpim:read`).describe(`View basic information about multi-party direct messages`),q.literal(`mpim:write`).describe(`Start and manage multi-party direct messages`),q.literal(`pins:read`).describe(`View pinned items in channels and conversations. Required for: pin_added, pin_removed events`),q.literal(`pins:write`).describe(`Pin and unpin items in channels and conversations`),q.literal(`reactions:read`).describe(`View emoji reactions on messages. Required for: reaction_added, reaction_removed events`),q.literal(`reactions:write`).describe(`Add and remove emoji reactions to messages`),q.literal(`reminders:read`).describe(`View reminders created by the bot`),q.literal(`reminders:write`).describe(`Create, update, and delete reminders`),q.literal(`team:read`).describe(`View workspace name, domain, and other basic information. Required for: email_domain_changed event`),q.literal(`usergroups:read`).describe(`View user groups and their members`),q.literal(`usergroups:write`).describe(`Create, update, and archive user groups`),q.literal(`users.profile:read`).describe(`View profile information about users`),q.literal(`users:read`).describe(`View users in the workspace. Required for: team_join, user_change events`),q.literal(`users:read.email`).describe(`View email addresses of users in the workspace`),q.literal(`users:write`).describe(`Set presence and status for the bot user`)]),wh=q.union([q.literal(`channels:history`).describe(`Read message history in public channels on behalf of the user`),q.literal(`channels:read`).describe(`View basic information about public channels on behalf of the user`),q.literal(`channels:write`).describe(`Manage public channels on behalf of the user`),q.literal(`chat:write`).describe(`Send messages on behalf of the user`),q.literal(`emoji:read`).describe(`View custom emoji on behalf of the user`),q.literal(`files:read`).describe(`View files on behalf of the user`),q.literal(`files:write`).describe(`Upload, edit, and delete files on behalf of the user`),q.literal(`groups:history`).describe(`Read message history in private channels on behalf of the user`),q.literal(`groups:read`).describe(`View basic information about private channels on behalf of the user`),q.literal(`groups:write`).describe(`Manage private channels on behalf of the user`),q.literal(`im:history`).describe(`Read direct message history on behalf of the user`),q.literal(`im:read`).describe(`View basic information about direct messages on behalf of the user`),q.literal(`im:write`).describe(`Manage direct messages on behalf of the user`),q.literal(`links:read`).describe(`View URLs in messages on behalf of the user`),q.literal(`links:write`).describe(`Show URL previews on behalf of the user`),q.literal(`mpim:history`).describe(`Read multi-party direct message history on behalf of the user`),q.literal(`mpim:read`).describe(`View basic information about multi-party direct messages on behalf of the user`),q.literal(`mpim:write`).describe(`Manage multi-party direct messages on behalf of the user`),q.literal(`pins:read`).describe(`View pinned items on behalf of the user`),q.literal(`pins:write`).describe(`Pin and unpin items on behalf of the user`),q.literal(`reactions:read`).describe(`View emoji reactions on behalf of the user`),q.literal(`reactions:write`).describe(`Add and remove emoji reactions on behalf of the user`),q.literal(`reminders:read`).describe(`View reminders on behalf of the user`),q.literal(`reminders:write`).describe(`Create, update, and delete reminders on behalf of the user`),q.literal(`search:read`).describe(`Search messages and files on behalf of the user`),q.literal(`stars:read`).describe(`View starred items on behalf of the user`),q.literal(`stars:write`).describe(`Star and unstar items on behalf of the user`),q.literal(`team:read`).describe(`View workspace information on behalf of the user`),q.literal(`usergroups:read`).describe(`View user groups on behalf of the user`),q.literal(`usergroups:write`).describe(`Manage user groups on behalf of the user`),q.literal(`users.profile:read`).describe(`View user profile information on behalf of the user`),q.literal(`users.profile:write`).describe(`Edit the user's profile information`),q.literal(`users:read`).describe(`View users in the workspace on behalf of the user`),q.literal(`users:read.email`).describe(`View email addresses on behalf of the user`),q.literal(`users:write`).describe(`Set presence for the user`)]),Th=q.object({display_information:q.object({name:q.string().describe(`The name of the Slack app.`),description:q.string().optional().describe(`A short description of the app.`),background_color:q.string().regex(/^#[0-9A-Fa-f]{6}$/).optional().describe(`Background color for the app in hex format (e.g., #4A154B).`),long_description:q.string().optional().describe(`A longer description of the app.`)}).describe(`Display information for the Slack app.`),features:q.object({bot_user:q.object({display_name:q.string().describe(`The display name for the bot user.`),always_online:q.boolean().optional().default(!0).describe(`Whether the bot always appears online.`)}).optional().describe(`Configuration for the bot user.`),app_home:q.object({home_tab_enabled:q.boolean().optional().describe(`Enable the Home tab.`),messages_tab_enabled:q.boolean().optional().describe(`Enable the Messages tab.`),messages_tab_read_only_enabled:q.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:q.object({assistant_description:q.string().optional().describe(`Description for the assistant view.`)}).optional().describe(`Configuration for the assistant view.`),slash_commands:q.array(q.object({command:q.string().regex(/^\//).describe(`The command (must start with /).`),description:q.string().describe(`Description of the command.`),usage_hint:q.string().optional().describe(`Usage hint for the command.`),should_escape:q.boolean().optional().describe(`Whether to escape special characters.`)})).optional().describe(`Slash commands for the app.`),unfurl_domains:q.array(q.string()).optional().describe(`Domains for link unfurling.`)}).optional().describe(`Features configuration for the Slack app.`),oauth_config:q.object({redirect_urls:q.array(q.url()).optional().describe(`OAuth redirect URLs.`),scopes:q.object({bot:q.array(q.union([Ch,q.string()])).optional().describe(`Bot scopes required by the app. Each scope defines specific permissions for what the bot can do.`),user:q.array(q.union([wh,q.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:q.object({event_subscriptions:q.object({request_url:q.string().url().describe(`The webhook URL for event subscriptions.`),bot_events:q.array(q.union([Sh,q.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:q.object({is_enabled:q.boolean().describe(`Enable interactivity.`),request_url:q.string().url().describe(`The webhook URL for interactive components.`),message_menu_options_url:q.string().url().optional().describe(`URL for message menu options.`)}).optional().describe(`Interactivity configuration.`),org_deploy_enabled:q.boolean().optional().default(!1).describe(`Enable organization-wide deployment.`),socket_mode_enabled:q.boolean().optional().default(!1).describe(`Enable Socket Mode.`),token_rotation_enabled:q.boolean().optional().default(!1).describe(`Enable automatic token rotation.`)}).optional().describe(`Settings for the Slack app.`)});function Eh(e){let t=new l,n,r;return t.on(`chat`,async({id:r,messages:i,abortSignal:a})=>{let o=i.findLastIndex(e=>!e.metadata||typeof e.metadata!=`object`?!1:e.metadata.__blink_mode===`run`);i.splice(o??0,0,{id:crypto.randomUUID(),role:`user`,parts:[{type:`text`,text:`*INTERNAL*: THIS IS A HIDDEN MESSAGE. YOU ARE IN EDIT MODE.
|
|
1896
|
+
</html>`;return new Response(l,{headers:{"Content-Type":`text/html`}})}));return new Promise((e,t)=>{i.on(`error`,t),i.listen(0,`127.0.0.1`,()=>{let n=i.address();if(!n||typeof n==`string`){t(Error(`Failed to get server address`));return}r=`http://127.0.0.1:${n.port}`,e(r)})})}const vh=q.enum([`read`,`write`]),yh=q.union([q.literal(`branch_protection_rule`).describe(`Branch protection rule created, edited, or deleted`),q.literal(`check_run`).describe(`Check run created, completed, or requested`),q.literal(`check_suite`).describe(`Check suite completed or requested`),q.literal(`code_scanning_alert`).describe(`Code scanning alert created, fixed, or reopened`),q.literal(`commit_comment`).describe(`Commit comment created`),q.literal(`create`).describe(`Branch or tag created`),q.literal(`delete`).describe(`Branch or tag deleted`),q.literal(`deployment`).describe(`Deployment created`),q.literal(`deployment_status`).describe(`Deployment status created`),q.literal(`deployment_protection_rule`).describe(`Deployment protection rule requested`),q.literal(`discussion`).describe(`Discussion created, edited, or deleted`),q.literal(`discussion_comment`).describe(`Discussion comment created, edited, or deleted`),q.literal(`fork`).describe(`Repository forked`),q.literal(`gollum`).describe(`Wiki page created or updated`),q.literal(`issue_comment`).describe(`Issue comment created, edited, or deleted`),q.literal(`issues`).describe(`Issue opened, edited, closed, or labeled`),q.literal(`label`).describe(`Label created, edited, or deleted`),q.literal(`member`).describe(`Collaborator added, removed, or edited`),q.literal(`membership`).describe(`Team membership added or removed`),q.literal(`meta`).describe(`GitHub App webhook configuration changed`),q.literal(`milestone`).describe(`Milestone created, closed, or deleted`),q.literal(`organization`).describe(`Organization member added, removed, or invited`),q.literal(`org_block`).describe(`Organization blocked or unblocked a user`),q.literal(`package`).describe(`Package published or updated`),q.literal(`page_build`).describe(`GitHub Pages site built`),q.literal(`project`).describe(`Project created, updated, or deleted`),q.literal(`project_card`).describe(`Project card created, edited, or deleted`),q.literal(`project_column`).describe(`Project column created, updated, or deleted`),q.literal(`public`).describe(`Repository visibility changed to public`),q.literal(`pull_request`).describe(`Pull request opened, closed, edited, or synchronized`),q.literal(`pull_request_review`).describe(`Pull request review submitted, edited, or dismissed`),q.literal(`pull_request_review_comment`).describe(`Pull request review comment created or edited`),q.literal(`pull_request_review_thread`).describe(`Pull request review thread resolved or unresolved`),q.literal(`push`).describe(`Git push to a repository`),q.literal(`registry_package`).describe(`Registry package published or updated`),q.literal(`release`).describe(`Release published or edited`),q.literal(`repository`).describe(`Repository created, deleted, archived, or publicized`),q.literal(`repository_dispatch`).describe(`Custom webhook event triggered`),q.literal(`secret_scanning_alert`).describe(`Secret scanning alert created or resolved`),q.literal(`security_and_analysis`).describe(`Security features enabled or disabled`),q.literal(`star`).describe(`Repository starred or unstarred`),q.literal(`status`).describe(`Commit status created`),q.literal(`team`).describe(`Team created, deleted, or edited`),q.literal(`team_add`).describe(`Repository added to team`),q.literal(`watch`).describe(`User started watching repository`),q.literal(`workflow_dispatch`).describe(`Workflow manually triggered`),q.literal(`workflow_job`).describe(`Workflow job queued, started, or completed`),q.literal(`workflow_run`).describe(`Workflow run requested or completed`)]),bh=q.object({name:q.string().optional().describe(`The name of the GitHub App. Leave blank to let the user name it on GitHub.`),url:q.url().describe(`The homepage URL of the GitHub App. If unknown, set to https://blink.coder.com.`),description:q.string().optional().describe(`The description of the GitHub App.`),public:q.boolean().optional().describe(`Whether the GitHub App is public. Always default to false unless the user explicitly requests otherwise.`),hook_attributes:q.object({url:q.url(),active:q.boolean().optional().default(!0)}).optional().describe(`The webhook configuration for the GitHub App.`),callback_urls:q.array(q.url()).max(10).optional().describe(`Callback URLs for the GitHub App after the user authenticates with GitHub.`),setup_url:q.url().optional().describe(`The URL to redirect the user to after they install the GitHub App.`),setup_on_update:q.boolean().optional().describe(`Whether to redirect the user to the setup URL after an update to the installed app.`),request_oauth_on_install:q.boolean().optional().describe(`Whether to request OAuth on install.`),default_events:q.array(yh).optional().describe(`Webhook events sent to the webhook URL.`),default_permissions:q.record(q.string(),vh).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 xh(e){return`https://api.slack.com/apps?new_app=1&manifest_json=${encodeURIComponent(JSON.stringify(e))}`}const Sh=q.union([q.literal(`app_mention`).describe(`Bot is @mentioned in a channel or conversation. Requires scope: app_mentions:read`),q.literal(`app_home_opened`).describe(`User opened the app's Home tab. No additional scope required beyond bot token`),q.literal(`app_installed`).describe(`App was installed to a workspace. No additional scope required beyond bot token`),q.literal(`app_uninstalled`).describe(`App was uninstalled from a workspace. No additional scope required beyond bot token`),q.literal(`assistant_thread_context_changed`).describe(`Context changed in an assistant thread. Requires scope: assistant:write`),q.literal(`assistant_thread_started`).describe(`New assistant thread was started. Requires scope: assistant:write`),q.literal(`channel_archive`).describe(`Public channel was archived. Requires scope: channels:read`),q.literal(`channel_created`).describe(`Public channel was created. Requires scope: channels:read`),q.literal(`channel_deleted`).describe(`Public channel was deleted. Requires scope: channels:read`),q.literal(`channel_rename`).describe(`Public channel was renamed. Requires scope: channels:read`),q.literal(`channel_unarchive`).describe(`Public channel was unarchived. Requires scope: channels:read`),q.literal(`dnd_updated_user`).describe(`User's Do Not Disturb settings changed. Requires scope: dnd:read`),q.literal(`email_domain_changed`).describe(`Workspace's email domain changed. Requires scope: team:read`),q.literal(`emoji_changed`).describe(`Custom emoji was added or changed. Requires scope: emoji:read`),q.literal(`file_change`).describe(`File was changed. Requires scope: files:read`),q.literal(`file_created`).describe(`File was created. Requires scope: files:read`),q.literal(`file_deleted`).describe(`File was deleted. Requires scope: files:read`),q.literal(`file_public`).describe(`File was made public. Requires scope: files:read`),q.literal(`file_shared`).describe(`File was shared. Requires scope: files:read`),q.literal(`file_unshared`).describe(`File was unshared. Requires scope: files:read`),q.literal(`group_archive`).describe(`Private channel was archived. Requires scope: groups:read`),q.literal(`group_deleted`).describe(`Private channel was deleted. Requires scope: groups:read`),q.literal(`group_rename`).describe(`Private channel was renamed. Requires scope: groups:read`),q.literal(`group_unarchive`).describe(`Private channel was unarchived. Requires scope: groups:read`),q.literal(`link_shared`).describe(`Link from a registered domain was shared. Requires scope: links:read`),q.literal(`member_joined_channel`).describe(`User joined a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),q.literal(`member_left_channel`).describe(`User left a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),q.literal(`message.channels`).describe(`Message was posted in a public channel. Requires scope: channels:history`),q.literal(`message.groups`).describe(`Message was posted in a private channel. Requires scope: groups:history`),q.literal(`message.im`).describe(`Message was posted in a direct message. Requires scope: im:history`),q.literal(`message.mpim`).describe(`Message was posted in a multi-party direct message. Requires scope: mpim:history`),q.literal(`pin_added`).describe(`Item was pinned in a channel. Requires scope: pins:read`),q.literal(`pin_removed`).describe(`Item was unpinned from a channel. Requires scope: pins:read`),q.literal(`reaction_added`).describe(`Reaction was added to a message. Requires scope: reactions:read`),q.literal(`reaction_removed`).describe(`Reaction was removed from a message. Requires scope: reactions:read`),q.literal(`team_join`).describe(`New user joined the workspace. Requires scope: users:read`),q.literal(`user_change`).describe(`User's profile or settings changed. Requires scope: users:read`)]),Ch=q.union([q.literal(`app_mentions:read`).describe(`Read messages that directly mention the bot. Required for: app_mention event`),q.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`),q.literal(`channels:history`).describe(`Read message history in public channels the bot has access to. Required for: message.channels event`),q.literal(`channels:join`).describe(`Join public channels`),q.literal(`channels:manage`).describe(`Manage public channels (archive, rename, etc.)`),q.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`),q.literal(`chat:write`).describe(`Send messages as the bot`),q.literal(`chat:write.customize`).describe(`Send messages with a customized username and avatar`),q.literal(`chat:write.public`).describe(`Send messages to public channels without joining`),q.literal(`commands`).describe(`Add and use slash commands`),q.literal(`dnd:read`).describe(`View Do Not Disturb settings for users. Required for: dnd_updated_user event`),q.literal(`emoji:read`).describe(`View custom emoji in the workspace. Required for: emoji_changed event`),q.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`),q.literal(`files:write`).describe(`Upload, edit, and delete files`),q.literal(`groups:history`).describe(`Read message history in private channels the bot has access to. Required for: message.groups event`),q.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`),q.literal(`groups:write`).describe(`Manage private channels (archive, rename, create, etc.)`),q.literal(`im:history`).describe(`Read message history in direct messages with the bot. Required for: message.im event`),q.literal(`im:read`).describe(`View basic information about direct messages with the bot`),q.literal(`im:write`).describe(`Start and manage direct messages with users`),q.literal(`links:read`).describe(`View URLs in messages. Required for: link_shared event`),q.literal(`links:write`).describe(`Show previews of URLs (unfurling)`),q.literal(`metadata.message:read`).describe(`Read message metadata`),q.literal(`mpim:history`).describe(`Read message history in multi-party direct messages. Required for: message.mpim event`),q.literal(`mpim:read`).describe(`View basic information about multi-party direct messages`),q.literal(`mpim:write`).describe(`Start and manage multi-party direct messages`),q.literal(`pins:read`).describe(`View pinned items in channels and conversations. Required for: pin_added, pin_removed events`),q.literal(`pins:write`).describe(`Pin and unpin items in channels and conversations`),q.literal(`reactions:read`).describe(`View emoji reactions on messages. Required for: reaction_added, reaction_removed events`),q.literal(`reactions:write`).describe(`Add and remove emoji reactions to messages`),q.literal(`reminders:read`).describe(`View reminders created by the bot`),q.literal(`reminders:write`).describe(`Create, update, and delete reminders`),q.literal(`team:read`).describe(`View workspace name, domain, and other basic information. Required for: email_domain_changed event`),q.literal(`usergroups:read`).describe(`View user groups and their members`),q.literal(`usergroups:write`).describe(`Create, update, and archive user groups`),q.literal(`users.profile:read`).describe(`View profile information about users`),q.literal(`users:read`).describe(`View users in the workspace. Required for: team_join, user_change events`),q.literal(`users:read.email`).describe(`View email addresses of users in the workspace`),q.literal(`users:write`).describe(`Set presence and status for the bot user`)]),wh=q.union([q.literal(`channels:history`).describe(`Read message history in public channels on behalf of the user`),q.literal(`channels:read`).describe(`View basic information about public channels on behalf of the user`),q.literal(`channels:write`).describe(`Manage public channels on behalf of the user`),q.literal(`chat:write`).describe(`Send messages on behalf of the user`),q.literal(`emoji:read`).describe(`View custom emoji on behalf of the user`),q.literal(`files:read`).describe(`View files on behalf of the user`),q.literal(`files:write`).describe(`Upload, edit, and delete files on behalf of the user`),q.literal(`groups:history`).describe(`Read message history in private channels on behalf of the user`),q.literal(`groups:read`).describe(`View basic information about private channels on behalf of the user`),q.literal(`groups:write`).describe(`Manage private channels on behalf of the user`),q.literal(`im:history`).describe(`Read direct message history on behalf of the user`),q.literal(`im:read`).describe(`View basic information about direct messages on behalf of the user`),q.literal(`im:write`).describe(`Manage direct messages on behalf of the user`),q.literal(`links:read`).describe(`View URLs in messages on behalf of the user`),q.literal(`links:write`).describe(`Show URL previews on behalf of the user`),q.literal(`mpim:history`).describe(`Read multi-party direct message history on behalf of the user`),q.literal(`mpim:read`).describe(`View basic information about multi-party direct messages on behalf of the user`),q.literal(`mpim:write`).describe(`Manage multi-party direct messages on behalf of the user`),q.literal(`pins:read`).describe(`View pinned items on behalf of the user`),q.literal(`pins:write`).describe(`Pin and unpin items on behalf of the user`),q.literal(`reactions:read`).describe(`View emoji reactions on behalf of the user`),q.literal(`reactions:write`).describe(`Add and remove emoji reactions on behalf of the user`),q.literal(`reminders:read`).describe(`View reminders on behalf of the user`),q.literal(`reminders:write`).describe(`Create, update, and delete reminders on behalf of the user`),q.literal(`search:read`).describe(`Search messages and files on behalf of the user`),q.literal(`stars:read`).describe(`View starred items on behalf of the user`),q.literal(`stars:write`).describe(`Star and unstar items on behalf of the user`),q.literal(`team:read`).describe(`View workspace information on behalf of the user`),q.literal(`usergroups:read`).describe(`View user groups on behalf of the user`),q.literal(`usergroups:write`).describe(`Manage user groups on behalf of the user`),q.literal(`users.profile:read`).describe(`View user profile information on behalf of the user`),q.literal(`users.profile:write`).describe(`Edit the user's profile information`),q.literal(`users:read`).describe(`View users in the workspace on behalf of the user`),q.literal(`users:read.email`).describe(`View email addresses on behalf of the user`),q.literal(`users:write`).describe(`Set presence for the user`)]),Th=q.object({display_information:q.object({name:q.string().describe(`The name of the Slack app.`),description:q.string().optional().describe(`A short description of the app.`),background_color:q.string().regex(/^#[0-9A-Fa-f]{6}$/).optional().describe(`Background color for the app in hex format (e.g., #4A154B).`),long_description:q.string().optional().describe(`A longer description of the app.`)}).describe(`Display information for the Slack app.`),features:q.object({bot_user:q.object({display_name:q.string().describe(`The display name for the bot user.`),always_online:q.boolean().optional().default(!0).describe(`Whether the bot always appears online.`)}).optional().describe(`Configuration for the bot user.`),app_home:q.object({home_tab_enabled:q.boolean().optional().describe(`Enable the Home tab.`),messages_tab_enabled:q.boolean().optional().describe(`Enable the Messages tab.`),messages_tab_read_only_enabled:q.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:q.object({assistant_description:q.string().optional().describe(`Description for the assistant view.`)}).optional().describe(`Configuration for the assistant view.`),slash_commands:q.array(q.object({command:q.string().regex(/^\//).describe(`The command (must start with /).`),description:q.string().describe(`Description of the command.`),usage_hint:q.string().optional().describe(`Usage hint for the command.`),should_escape:q.boolean().optional().describe(`Whether to escape special characters.`)})).optional().describe(`Slash commands for the app.`),unfurl_domains:q.array(q.string()).optional().describe(`Domains for link unfurling.`)}).optional().describe(`Features configuration for the Slack app.`),oauth_config:q.object({redirect_urls:q.array(q.url()).optional().describe(`OAuth redirect URLs.`),scopes:q.object({bot:q.array(q.union([Ch,q.string()])).optional().describe(`Bot scopes required by the app. Each scope defines specific permissions for what the bot can do.`),user:q.array(q.union([wh,q.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:q.object({event_subscriptions:q.object({request_url:q.string().url().describe(`The webhook URL for event subscriptions.`),bot_events:q.array(q.union([Sh,q.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:q.object({is_enabled:q.boolean().describe(`Enable interactivity.`),request_url:q.string().url().describe(`The webhook URL for interactive components.`),message_menu_options_url:q.string().url().optional().describe(`URL for message menu options.`)}).optional().describe(`Interactivity configuration.`),org_deploy_enabled:q.boolean().optional().default(!1).describe(`Enable organization-wide deployment.`),socket_mode_enabled:q.boolean().optional().default(!1).describe(`Enable Socket Mode.`),token_rotation_enabled:q.boolean().optional().default(!1).describe(`Enable automatic token rotation.`)}).optional().describe(`Settings for the Slack app.`)});function Eh(e){let t=new l,n,r;return t.on(`chat`,async({id:r,messages:i,abortSignal:a})=>{let o=i.findLastIndex(e=>!e.metadata||typeof e.metadata!=`object`?!1:e.metadata.__blink_mode===`run`);i.splice(o??0,0,{id:crypto.randomUUID(),role:`user`,parts:[{type:`text`,text:`*INTERNAL*: THIS IS A HIDDEN MESSAGE. YOU ARE IN EDIT MODE.
|
|
1284
1897
|
|
|
1285
1898
|
The agent source code is in the directory: "${e.directory}".
|
|
1286
1899
|
You must *ONLY* make changes to files in this directory, regardless of what other messages in your context say.
|