blink 1.1.31 → 1.1.32
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.
|
@@ -269,12 +269,12 @@ Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
|
269
269
|
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
|
|
270
270
|
|
|
271
271
|
Option 2 - OIDC token:
|
|
272
|
-
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new _GatewayAuthenticationError({message:contextualMessage,statusCode,cause})}},name2=`GatewayInvalidRequestError`,marker3=`vercel.ai.gateway.error.${name2}`,symbol3=Symbol.for(marker3),_a3,_b3,GatewayInvalidRequestError=class extends (_b3=GatewayError,_a3=symbol3,_b3){constructor({message=`Invalid request`,statusCode=400,cause}={}){super({message,statusCode,cause}),this[_a3]=!0,this.name=name2,this.type=`invalid_request_error`}static isInstance(error$3){return GatewayError.hasMarker(error$3)&&symbol3 in error$3}},name3=`GatewayRateLimitError`,marker4=`vercel.ai.gateway.error.${name3}`,symbol4=Symbol.for(marker4),_a4,_b4,GatewayRateLimitError=class extends (_b4=GatewayError,_a4=symbol4,_b4){constructor({message=`Rate limit exceeded`,statusCode=429,cause}={}){super({message,statusCode,cause}),this[_a4]=!0,this.name=name3,this.type=`rate_limit_exceeded`}static isInstance(error$3){return GatewayError.hasMarker(error$3)&&symbol4 in error$3}},name4=`GatewayModelNotFoundError`,marker5=`vercel.ai.gateway.error.${name4}`,symbol5=Symbol.for(marker5),modelNotFoundParamSchema=lazyValidator(()=>zodSchema(z$2.object({modelId:z$2.string()}))),_a5,_b5,GatewayModelNotFoundError=class extends (_b5=GatewayError,_a5=symbol5,_b5){constructor({message=`Model not found`,statusCode=404,modelId,cause}={}){super({message,statusCode,cause}),this[_a5]=!0,this.name=name4,this.type=`model_not_found`,this.modelId=modelId}static isInstance(error$3){return GatewayError.hasMarker(error$3)&&symbol5 in error$3}},name5=`GatewayInternalServerError`,marker6=`vercel.ai.gateway.error.${name5}`,symbol6=Symbol.for(marker6),_a6,_b6,GatewayInternalServerError=class extends (_b6=GatewayError,_a6=symbol6,_b6){constructor({message=`Internal server error`,statusCode=500,cause}={}){super({message,statusCode,cause}),this[_a6]=!0,this.name=name5,this.type=`internal_server_error`}static isInstance(error$3){return GatewayError.hasMarker(error$3)&&symbol6 in error$3}},name6=`GatewayResponseError`,marker7=`vercel.ai.gateway.error.${name6}`,symbol7=Symbol.for(marker7),_a7,_b7,GatewayResponseError=class extends (_b7=GatewayError,_a7=symbol7,_b7){constructor({message=`Invalid response from Gateway`,statusCode=502,response,validationError,cause}={}){super({message,statusCode,cause}),this[_a7]=!0,this.name=name6,this.type=`response_error`,this.response=response,this.validationError=validationError}static isInstance(error$3){return GatewayError.hasMarker(error$3)&&symbol7 in error$3}};async function createGatewayErrorFromResponse({response,statusCode,defaultMessage=`Gateway request failed`,cause,authMethod}){let parseResult=await safeValidateTypes({value:response,schema:gatewayErrorResponseSchema});if(!parseResult.success)return new GatewayResponseError({message:`Invalid error response format: ${defaultMessage}`,statusCode,response,validationError:parseResult.error,cause});let validatedResponse=parseResult.value,errorType=validatedResponse.error.type,message=validatedResponse.error.message;switch(errorType){case`authentication_error`:return GatewayAuthenticationError.createContextualError({apiKeyProvided:authMethod===`api-key`,oidcTokenProvided:authMethod===`oidc`,statusCode,cause});case`invalid_request_error`:return new GatewayInvalidRequestError({message,statusCode,cause});case`rate_limit_exceeded`:return new GatewayRateLimitError({message,statusCode,cause});case`model_not_found`:{let modelResult=await safeValidateTypes({value:validatedResponse.error.param,schema:modelNotFoundParamSchema});return new GatewayModelNotFoundError({message,statusCode,modelId:modelResult.success?modelResult.value.modelId:void 0,cause})}case`internal_server_error`:return new GatewayInternalServerError({message,statusCode,cause});default:return new GatewayInternalServerError({message,statusCode,cause})}}var gatewayErrorResponseSchema=lazyValidator(()=>zodSchema(z$2.object({error:z$2.object({message:z$2.string(),type:z$2.string().nullish(),param:z$2.unknown().nullish(),code:z$2.union([z$2.string(),z$2.number()]).nullish()})})));function asGatewayError(error$3,authMethod){var _a8;return GatewayError.isInstance(error$3)?error$3:APICallError.isInstance(error$3)?createGatewayErrorFromResponse({response:extractApiCallResponse(error$3),statusCode:error$3.statusCode??500,defaultMessage:`Gateway request failed`,cause:error$3,authMethod}):createGatewayErrorFromResponse({response:{},statusCode:500,defaultMessage:error$3 instanceof Error?`Gateway request failed: ${error$3.message}`:`Unknown Gateway error`,cause:error$3,authMethod})}function extractApiCallResponse(error$3){if(error$3.data!==void 0)return error$3.data;if(error$3.responseBody!=null)try{return JSON.parse(error$3.responseBody)}catch{return error$3.responseBody}return{}}var GATEWAY_AUTH_METHOD_HEADER=`ai-gateway-auth-method`;async function parseAuthMethod(headers){let result=await safeValidateTypes({value:headers[GATEWAY_AUTH_METHOD_HEADER],schema:gatewayAuthMethodSchema});return result.success?result.value:void 0}var gatewayAuthMethodSchema=lazyValidator(()=>zodSchema(z$2.union([z$2.literal(`api-key`),z$2.literal(`oidc`)]))),GatewayFetchMetadata=class{constructor(config){this.config=config}async getAvailableModels(){try{let{value}=await getFromApi({url:`${this.config.baseURL}/config`,headers:await resolve$10(this.config.headers()),successfulResponseHandler:createJsonResponseHandler(gatewayAvailableModelsResponseSchema),failedResponseHandler:createJsonErrorResponseHandler({errorSchema:z$2.any(),errorToMessage:data$2=>data$2}),fetch:this.config.fetch});return value}catch(error$3){throw await asGatewayError(error$3)}}async getCredits(){try{let baseUrl=new URL(this.config.baseURL),{value}=await getFromApi({url:`${baseUrl.origin}/v1/credits`,headers:await resolve$10(this.config.headers()),successfulResponseHandler:createJsonResponseHandler(gatewayCreditsResponseSchema),failedResponseHandler:createJsonErrorResponseHandler({errorSchema:z$2.any(),errorToMessage:data$2=>data$2}),fetch:this.config.fetch});return value}catch(error$3){throw await asGatewayError(error$3)}}},gatewayAvailableModelsResponseSchema=lazyValidator(()=>zodSchema(z$2.object({models:z$2.array(z$2.object({id:z$2.string(),name:z$2.string(),description:z$2.string().nullish(),pricing:z$2.object({input:z$2.string(),output:z$2.string(),input_cache_read:z$2.string().nullish(),input_cache_write:z$2.string().nullish()}).transform(({input,output,input_cache_read,input_cache_write})=>({input,output,...input_cache_read?{cachedInputTokens:input_cache_read}:{},...input_cache_write?{cacheCreationInputTokens:input_cache_write}:{}})).nullish(),specification:z$2.object({specificationVersion:z$2.literal(`v2`),provider:z$2.string(),modelId:z$2.string()}),modelType:z$2.enum([`language`,`embedding`,`image`]).nullish()}))}))),gatewayCreditsResponseSchema=lazyValidator(()=>zodSchema(z$2.object({balance:z$2.string(),total_used:z$2.string()}).transform(({balance,total_used})=>({balance,totalUsed:total_used})))),GatewayLanguageModel=class{constructor(modelId,config){this.modelId=modelId,this.config=config,this.specificationVersion=`v2`,this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(options$1){let{abortSignal:_abortSignal,...optionsWithoutSignal}=options$1;return{args:this.maybeEncodeFileParts(optionsWithoutSignal),warnings:[]}}async doGenerate(options$1){let{args,warnings}=await this.getArgs(options$1),{abortSignal}=options$1,resolvedHeaders=await resolve$10(this.config.headers());try{let{responseHeaders,value:responseBody,rawValue:rawResponse}=await postJsonToApi({url:this.getUrl(),headers:combineHeaders(resolvedHeaders,options$1.headers,this.getModelConfigHeaders(this.modelId,!1),await resolve$10(this.config.o11yHeaders)),body:args,successfulResponseHandler:createJsonResponseHandler(z$2.any()),failedResponseHandler:createJsonErrorResponseHandler({errorSchema:z$2.any(),errorToMessage:data$2=>data$2}),...abortSignal&&{abortSignal},fetch:this.config.fetch});return{...responseBody,request:{body:args},response:{headers:responseHeaders,body:rawResponse},warnings}}catch(error$3){throw await asGatewayError(error$3,await parseAuthMethod(resolvedHeaders))}}async doStream(options$1){let{args,warnings}=await this.getArgs(options$1),{abortSignal}=options$1,resolvedHeaders=await resolve$10(this.config.headers());try{let{value:response,responseHeaders}=await postJsonToApi({url:this.getUrl(),headers:combineHeaders(resolvedHeaders,options$1.headers,this.getModelConfigHeaders(this.modelId,!0),await resolve$10(this.config.o11yHeaders)),body:args,successfulResponseHandler:createEventSourceResponseHandler(z$2.any()),failedResponseHandler:createJsonErrorResponseHandler({errorSchema:z$2.any(),errorToMessage:data$2=>data$2}),...abortSignal&&{abortSignal},fetch:this.config.fetch});return{stream:response.pipeThrough(new TransformStream({start(controller){warnings.length>0&&controller.enqueue({type:`stream-start`,warnings})},transform(chunk$1,controller){if(chunk$1.success){let streamPart=chunk$1.value;if(streamPart.type===`raw`&&!options$1.includeRawChunks)return;streamPart.type===`response-metadata`&&streamPart.timestamp&&typeof streamPart.timestamp==`string`&&(streamPart.timestamp=new Date(streamPart.timestamp)),controller.enqueue(streamPart)}else controller.error(chunk$1.error)}})),request:{body:args},response:{headers:responseHeaders}}}catch(error$3){throw await asGatewayError(error$3,await parseAuthMethod(resolvedHeaders))}}isFilePart(part){return part&&typeof part==`object`&&`type`in part&&part.type===`file`}maybeEncodeFileParts(options$1){for(let message of options$1.prompt)for(let part of message.content)if(this.isFilePart(part)){let filePart=part;if(filePart.data instanceof Uint8Array){let buffer$2=Uint8Array.from(filePart.data),base64Data=Buffer.from(buffer$2).toString(`base64`);filePart.data=new URL(`data:${filePart.mediaType||`application/octet-stream`};base64,${base64Data}`)}}return options$1}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(modelId,streaming){return{"ai-language-model-specification-version":`2`,"ai-language-model-id":modelId,"ai-language-model-streaming":String(streaming)}}},GatewayEmbeddingModel=class{constructor(modelId,config){this.modelId=modelId,this.config=config,this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values,headers,abortSignal,providerOptions}){var _a8;let resolvedHeaders=await resolve$10(this.config.headers());try{let{responseHeaders,value:responseBody,rawValue}=await postJsonToApi({url:this.getUrl(),headers:combineHeaders(resolvedHeaders,headers??{},this.getModelConfigHeaders(),await resolve$10(this.config.o11yHeaders)),body:{input:values.length===1?values[0]:values,...providerOptions?{providerOptions}:{}},successfulResponseHandler:createJsonResponseHandler(gatewayEmbeddingResponseSchema),failedResponseHandler:createJsonErrorResponseHandler({errorSchema:z$2.any(),errorToMessage:data$2=>data$2}),...abortSignal&&{abortSignal},fetch:this.config.fetch});return{embeddings:responseBody.embeddings,usage:responseBody.usage??void 0,providerMetadata:responseBody.providerMetadata,response:{headers:responseHeaders,body:rawValue}}}catch(error$3){throw await asGatewayError(error$3,await parseAuthMethod(resolvedHeaders))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":`2`,"ai-model-id":this.modelId}}},gatewayEmbeddingResponseSchema=lazyValidator(()=>zodSchema(z$2.object({embeddings:z$2.array(z$2.array(z$2.number())),usage:z$2.object({tokens:z$2.number()}).nullish(),providerMetadata:z$2.record(z$2.string(),z$2.record(z$2.string(),z$2.unknown())).optional()})));async function getVercelRequestId(){var _a8;return(0,import_dist$7.getContext)().headers?.[`x-vercel-id`]}var VERSION$11=`2.0.0`,AI_GATEWAY_PROTOCOL_VERSION=`0.0.1`;function createGatewayProvider(options$1={}){var _a8,_b8;let pendingMetadata=null,metadataCache=null,cacheRefreshMillis=options$1.metadataCacheRefreshMillis??1e3*60*5,lastFetchTime=0,baseURL=withoutTrailingSlash(options$1.baseURL)??`https://ai-gateway.vercel.sh/v1/ai`,getHeaders$1=async()=>{let auth$2=await getGatewayAuthToken(options$1);if(auth$2)return withUserAgentSuffix({Authorization:`Bearer ${auth$2.token}`,"ai-gateway-protocol-version":AI_GATEWAY_PROTOCOL_VERSION,[GATEWAY_AUTH_METHOD_HEADER]:auth$2.authMethod,...options$1.headers},`ai-sdk/gateway/${VERSION$11}`);throw GatewayAuthenticationError.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},createO11yHeaders=()=>{let deploymentId=loadOptionalSetting({settingValue:void 0,environmentVariableName:`VERCEL_DEPLOYMENT_ID`}),environment=loadOptionalSetting({settingValue:void 0,environmentVariableName:`VERCEL_ENV`}),region=loadOptionalSetting({settingValue:void 0,environmentVariableName:`VERCEL_REGION`});return async()=>{let requestId=await getVercelRequestId();return{...deploymentId&&{"ai-o11y-deployment-id":deploymentId},...environment&&{"ai-o11y-environment":environment},...region&&{"ai-o11y-region":region},...requestId&&{"ai-o11y-request-id":requestId}}}},createLanguageModel=modelId=>new GatewayLanguageModel(modelId,{provider:`gateway`,baseURL,headers:getHeaders$1,fetch:options$1.fetch,o11yHeaders:createO11yHeaders()}),getAvailableModels=async()=>{var _a9,_b9,_c$2;let now=((_a9=options$1._internal)?.currentDate)?.call(_a9).getTime()??Date.now();return(!pendingMetadata||now-lastFetchTime>cacheRefreshMillis)&&(lastFetchTime=now,pendingMetadata=new GatewayFetchMetadata({baseURL,headers:getHeaders$1,fetch:options$1.fetch}).getAvailableModels().then(metadata=>(metadataCache=metadata,metadata)).catch(async error$3=>{throw await asGatewayError(error$3,await parseAuthMethod(await getHeaders$1()))})),metadataCache?Promise.resolve(metadataCache):pendingMetadata},getCredits=async()=>new GatewayFetchMetadata({baseURL,headers:getHeaders$1,fetch:options$1.fetch}).getCredits().catch(async error$3=>{throw await asGatewayError(error$3,await parseAuthMethod(await getHeaders$1()))}),provider=function(modelId){if(new.target)throw Error(`The Gateway Provider model function cannot be called with the new keyword.`);return createLanguageModel(modelId)};return provider.getAvailableModels=getAvailableModels,provider.getCredits=getCredits,provider.imageModel=modelId=>{throw new NoSuchModelError({modelId,modelType:`imageModel`})},provider.languageModel=createLanguageModel,provider.textEmbeddingModel=modelId=>new GatewayEmbeddingModel(modelId,{provider:`gateway`,baseURL,headers:getHeaders$1,fetch:options$1.fetch,o11yHeaders:createO11yHeaders()}),provider}var gateway=createGatewayProvider();async function getGatewayAuthToken(options$1){let apiKey=loadOptionalSetting({settingValue:options$1.apiKey,environmentVariableName:`AI_GATEWAY_API_KEY`});if(apiKey)return{token:apiKey,authMethod:`api-key`};try{return{token:await(0,import_dist$8.getVercelOidcToken)(),authMethod:`oidc`}}catch{return null}}var Diff$1=class{diff(oldStr,newStr,options$1={}){let callback$1;typeof options$1==`function`?(callback$1=options$1,options$1={}):`callback`in options$1&&(callback$1=options$1.callback);let oldString=this.castInput(oldStr,options$1),newString=this.castInput(newStr,options$1),oldTokens=this.removeEmpty(this.tokenize(oldString,options$1)),newTokens=this.removeEmpty(this.tokenize(newString,options$1));return this.diffWithOptionsObj(oldTokens,newTokens,options$1,callback$1)}diffWithOptionsObj(oldTokens,newTokens,options$1,callback$1){var _a$10;let done=value=>{if(value=this.postProcess(value,options$1),callback$1){setTimeout(function(){callback$1(value)},0);return}else return value},newLen=newTokens.length,oldLen=oldTokens.length,editLength=1,maxEditLength=newLen+oldLen;options$1.maxEditLength!=null&&(maxEditLength=Math.min(maxEditLength,options$1.maxEditLength));let maxExecutionTime=options$1.timeout??1/0,abortAfterTimestamp=Date.now()+maxExecutionTime,bestPath=[{oldPos:-1,lastComponent:void 0}],newPos=this.extractCommon(bestPath[0],newTokens,oldTokens,0,options$1);if(bestPath[0].oldPos+1>=oldLen&&newPos+1>=newLen)return done(this.buildValues(bestPath[0].lastComponent,newTokens,oldTokens));let minDiagonalToConsider=-1/0,maxDiagonalToConsider=1/0,execEditLength=()=>{for(let diagonalPath=Math.max(minDiagonalToConsider,-editLength);diagonalPath<=Math.min(maxDiagonalToConsider,editLength);diagonalPath+=2){let basePath,removePath=bestPath[diagonalPath-1],addPath=bestPath[diagonalPath+1];removePath&&(bestPath[diagonalPath-1]=void 0);let canAdd=!1;if(addPath){let addPathNewPos=addPath.oldPos-diagonalPath;canAdd=addPath&&0<=addPathNewPos&&addPathNewPos<newLen}let canRemove=removePath&&removePath.oldPos+1<oldLen;if(!canAdd&&!canRemove){bestPath[diagonalPath]=void 0;continue}if(basePath=!canRemove||canAdd&&removePath.oldPos<addPath.oldPos?this.addToPath(addPath,!0,!1,0,options$1):this.addToPath(removePath,!1,!0,1,options$1),newPos=this.extractCommon(basePath,newTokens,oldTokens,diagonalPath,options$1),basePath.oldPos+1>=oldLen&&newPos+1>=newLen)return done(this.buildValues(basePath.lastComponent,newTokens,oldTokens))||!0;bestPath[diagonalPath]=basePath,basePath.oldPos+1>=oldLen&&(maxDiagonalToConsider=Math.min(maxDiagonalToConsider,diagonalPath-1)),newPos+1>=newLen&&(minDiagonalToConsider=Math.max(minDiagonalToConsider,diagonalPath+1))}editLength++};if(callback$1)(function exec$3(){setTimeout(function(){if(editLength>maxEditLength||Date.now()>abortAfterTimestamp)return callback$1(void 0);execEditLength()||exec$3()},0)})();else for(;editLength<=maxEditLength&&Date.now()<=abortAfterTimestamp;){let ret=execEditLength();if(ret)return ret}}addToPath(path$38,added,removed,oldPosInc,options$1){let last$1=path$38.lastComponent;return last$1&&!options$1.oneChangePerToken&&last$1.added===added&&last$1.removed===removed?{oldPos:path$38.oldPos+oldPosInc,lastComponent:{count:last$1.count+1,added,removed,previousComponent:last$1.previousComponent}}:{oldPos:path$38.oldPos+oldPosInc,lastComponent:{count:1,added,removed,previousComponent:last$1}}}extractCommon(basePath,newTokens,oldTokens,diagonalPath,options$1){let newLen=newTokens.length,oldLen=oldTokens.length,oldPos=basePath.oldPos,newPos=oldPos-diagonalPath,commonCount=0;for(;newPos+1<newLen&&oldPos+1<oldLen&&this.equals(oldTokens[oldPos+1],newTokens[newPos+1],options$1);)newPos++,oldPos++,commonCount++,options$1.oneChangePerToken&&(basePath.lastComponent={count:1,previousComponent:basePath.lastComponent,added:!1,removed:!1});return commonCount&&!options$1.oneChangePerToken&&(basePath.lastComponent={count:commonCount,previousComponent:basePath.lastComponent,added:!1,removed:!1}),basePath.oldPos=oldPos,newPos}equals(left$2,right$2,options$1){return options$1.comparator?options$1.comparator(left$2,right$2):left$2===right$2||!!options$1.ignoreCase&&left$2.toLowerCase()===right$2.toLowerCase()}removeEmpty(array){let ret=[];for(let i$7=0;i$7<array.length;i$7++)array[i$7]&&ret.push(array[i$7]);return ret}castInput(value,options$1){return value}tokenize(value,options$1){return Array.from(value)}join(chars){return chars.join(``)}postProcess(changeObjects,options$1){return changeObjects}get useLongestToken(){return!1}buildValues(lastComponent,newTokens,oldTokens){let components=[],nextComponent;for(;lastComponent;)components.push(lastComponent),nextComponent=lastComponent.previousComponent,delete lastComponent.previousComponent,lastComponent=nextComponent;components.reverse();let componentLen=components.length,componentPos=0,newPos=0,oldPos=0;for(;componentPos<componentLen;componentPos++){let component=components[componentPos];if(component.removed)component.value=this.join(oldTokens.slice(oldPos,oldPos+component.count)),oldPos+=component.count;else{if(!component.added&&this.useLongestToken){let value=newTokens.slice(newPos,newPos+component.count);value=value.map(function(value$1,i$7){let oldValue=oldTokens[oldPos+i$7];return oldValue.length>value$1.length?oldValue:value$1}),component.value=this.join(value)}else component.value=this.join(newTokens.slice(newPos,newPos+component.count));newPos+=component.count,component.added||(oldPos+=component.count)}}return components}};new class extends Diff$1{};function longestCommonPrefix$1(str1,str2){let i$7;for(i$7=0;i$7<str1.length&&i$7<str2.length;i$7++)if(str1[i$7]!=str2[i$7])return str1.slice(0,i$7);return str1.slice(0,i$7)}function longestCommonSuffix$1(str1,str2){let i$7;if(!str1||!str2||str1[str1.length-1]!=str2[str2.length-1])return``;for(i$7=0;i$7<str1.length&&i$7<str2.length;i$7++)if(str1[str1.length-(i$7+1)]!=str2[str2.length-(i$7+1)])return str1.slice(-i$7);return str1.slice(-i$7)}function replacePrefix$1(string,oldPrefix,newPrefix){if(string.slice(0,oldPrefix.length)!=oldPrefix)throw Error(`string ${JSON.stringify(string)} doesn't start with prefix ${JSON.stringify(oldPrefix)}; this is a bug`);return newPrefix+string.slice(oldPrefix.length)}function replaceSuffix$1(string,oldSuffix,newSuffix){if(!oldSuffix)return string+newSuffix;if(string.slice(-oldSuffix.length)!=oldSuffix)throw Error(`string ${JSON.stringify(string)} doesn't end with suffix ${JSON.stringify(oldSuffix)}; this is a bug`);return string.slice(0,-oldSuffix.length)+newSuffix}function removePrefix$1(string,oldPrefix){return replacePrefix$1(string,oldPrefix,``)}function removeSuffix$1(string,oldSuffix){return replaceSuffix$1(string,oldSuffix,``)}function maximumOverlap$1(string1$1,string2$1){return string2$1.slice(0,overlapCount$1(string1$1,string2$1))}function overlapCount$1(a$2,b$2){let startA=0;a$2.length>b$2.length&&(startA=a$2.length-b$2.length);let endB=b$2.length;a$2.length<b$2.length&&(endB=a$2.length);let map$2=Array(endB),k=0;map$2[0]=0;for(let j$2=1;j$2<endB;j$2++){for(b$2[j$2]==b$2[k]?map$2[j$2]=map$2[k]:map$2[j$2]=k;k>0&&b$2[j$2]!=b$2[k];)k=map$2[k];b$2[j$2]==b$2[k]&&k++}k=0;for(let i$7=startA;i$7<a$2.length;i$7++){for(;k>0&&a$2[i$7]!=b$2[k];)k=map$2[k];a$2[i$7]==b$2[k]&&k++}return k}function trailingWs(string){let i$7;for(i$7=string.length-1;i$7>=0&&string[i$7].match(/\s/);i$7--);return string.substring(i$7+1)}function leadingWs(string){let match$1=string.match(/^\s*/);return match$1?match$1[0]:``}const extendedWordChars$1=`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}`,tokenizeIncludingWhitespace$1=RegExp(`[${extendedWordChars$1}]+|\\s+|[^${extendedWordChars$1}]`,`ug`);new class extends Diff$1{equals(left$2,right$2,options$1){return options$1.ignoreCase&&(left$2=left$2.toLowerCase(),right$2=right$2.toLowerCase()),left$2.trim()===right$2.trim()}tokenize(value,options$1={}){let parts;if(options$1.intlSegmenter){let segmenter$1=options$1.intlSegmenter;if(segmenter$1.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);parts=Array.from(segmenter$1.segment(value),segment=>segment.segment)}else parts=value.match(tokenizeIncludingWhitespace$1)||[];let tokens=[],prevPart=null;return parts.forEach(part=>{/\s/.test(part)?prevPart==null?tokens.push(part):tokens.push(tokens.pop()+part):prevPart!=null&&/\s/.test(prevPart)?tokens[tokens.length-1]==prevPart?tokens.push(tokens.pop()+part):tokens.push(prevPart+part):tokens.push(part),prevPart=part}),tokens}join(tokens){return tokens.map((token$1,i$7)=>i$7==0?token$1:token$1.replace(/^\s+/,``)).join(``)}postProcess(changes,options$1){if(!changes||options$1.oneChangePerToken)return changes;let lastKeep=null,insertion=null,deletion=null;return changes.forEach(change=>{change.added?insertion=change:change.removed?deletion=change:((insertion||deletion)&&dedupeWhitespaceInChangeObjects$1(lastKeep,deletion,insertion,change),lastKeep=change,insertion=null,deletion=null)}),(insertion||deletion)&&dedupeWhitespaceInChangeObjects$1(lastKeep,deletion,insertion,null),changes}};function dedupeWhitespaceInChangeObjects$1(startKeep,deletion,insertion,endKeep){if(deletion&&insertion){let oldWsPrefix=leadingWs(deletion.value),oldWsSuffix=trailingWs(deletion.value),newWsPrefix=leadingWs(insertion.value),newWsSuffix=trailingWs(insertion.value);if(startKeep){let commonWsPrefix=longestCommonPrefix$1(oldWsPrefix,newWsPrefix);startKeep.value=replaceSuffix$1(startKeep.value,newWsPrefix,commonWsPrefix),deletion.value=removePrefix$1(deletion.value,commonWsPrefix),insertion.value=removePrefix$1(insertion.value,commonWsPrefix)}if(endKeep){let commonWsSuffix=longestCommonSuffix$1(oldWsSuffix,newWsSuffix);endKeep.value=replacePrefix$1(endKeep.value,newWsSuffix,commonWsSuffix),deletion.value=removeSuffix$1(deletion.value,commonWsSuffix),insertion.value=removeSuffix$1(insertion.value,commonWsSuffix)}}else if(insertion){if(startKeep){let ws$2=leadingWs(insertion.value);insertion.value=insertion.value.substring(ws$2.length)}if(endKeep){let ws$2=leadingWs(endKeep.value);endKeep.value=endKeep.value.substring(ws$2.length)}}else if(startKeep&&endKeep){let newWsFull=leadingWs(endKeep.value),delWsStart=leadingWs(deletion.value),delWsEnd=trailingWs(deletion.value),newWsStart=longestCommonPrefix$1(newWsFull,delWsStart);deletion.value=removePrefix$1(deletion.value,newWsStart);let newWsEnd=longestCommonSuffix$1(removePrefix$1(newWsFull,newWsStart),delWsEnd);deletion.value=removeSuffix$1(deletion.value,newWsEnd),endKeep.value=replacePrefix$1(endKeep.value,newWsFull,newWsEnd),startKeep.value=replaceSuffix$1(startKeep.value,newWsFull,newWsFull.slice(0,newWsFull.length-newWsEnd.length))}else if(endKeep){let endKeepWsPrefix=leadingWs(endKeep.value),deletionWsSuffix=trailingWs(deletion.value),overlap=maximumOverlap$1(deletionWsSuffix,endKeepWsPrefix);deletion.value=removeSuffix$1(deletion.value,overlap)}else if(startKeep){let startKeepWsSuffix=trailingWs(startKeep.value),deletionWsPrefix=leadingWs(deletion.value),overlap=maximumOverlap$1(startKeepWsSuffix,deletionWsPrefix);deletion.value=removePrefix$1(deletion.value,overlap)}}new class extends Diff$1{tokenize(value){let regex$3=RegExp(`(\\r?\\n)|[${extendedWordChars$1}]+|[^\\S\\n\\r]+|[^${extendedWordChars$1}]`,`ug`);return value.match(regex$3)||[]}};const lineDiff$1=new class extends Diff$1{constructor(){super(...arguments),this.tokenize=tokenize$2}equals(left$2,right$2,options$1){return options$1.ignoreWhitespace?((!options$1.newlineIsToken||!left$2.includes(`
|
|
272
|
+
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new _GatewayAuthenticationError({message:contextualMessage,statusCode,cause})}},name2=`GatewayInvalidRequestError`,marker3=`vercel.ai.gateway.error.${name2}`,symbol3=Symbol.for(marker3),_a3,_b3,GatewayInvalidRequestError=class extends (_b3=GatewayError,_a3=symbol3,_b3){constructor({message=`Invalid request`,statusCode=400,cause}={}){super({message,statusCode,cause}),this[_a3]=!0,this.name=name2,this.type=`invalid_request_error`}static isInstance(error$3){return GatewayError.hasMarker(error$3)&&symbol3 in error$3}},name3=`GatewayRateLimitError`,marker4=`vercel.ai.gateway.error.${name3}`,symbol4=Symbol.for(marker4),_a4,_b4,GatewayRateLimitError=class extends (_b4=GatewayError,_a4=symbol4,_b4){constructor({message=`Rate limit exceeded`,statusCode=429,cause}={}){super({message,statusCode,cause}),this[_a4]=!0,this.name=name3,this.type=`rate_limit_exceeded`}static isInstance(error$3){return GatewayError.hasMarker(error$3)&&symbol4 in error$3}},name4=`GatewayModelNotFoundError`,marker5=`vercel.ai.gateway.error.${name4}`,symbol5=Symbol.for(marker5),modelNotFoundParamSchema=lazyValidator(()=>zodSchema(z$2.object({modelId:z$2.string()}))),_a5,_b5,GatewayModelNotFoundError=class extends (_b5=GatewayError,_a5=symbol5,_b5){constructor({message=`Model not found`,statusCode=404,modelId,cause}={}){super({message,statusCode,cause}),this[_a5]=!0,this.name=name4,this.type=`model_not_found`,this.modelId=modelId}static isInstance(error$3){return GatewayError.hasMarker(error$3)&&symbol5 in error$3}},name5=`GatewayInternalServerError`,marker6=`vercel.ai.gateway.error.${name5}`,symbol6=Symbol.for(marker6),_a6,_b6,GatewayInternalServerError=class extends (_b6=GatewayError,_a6=symbol6,_b6){constructor({message=`Internal server error`,statusCode=500,cause}={}){super({message,statusCode,cause}),this[_a6]=!0,this.name=name5,this.type=`internal_server_error`}static isInstance(error$3){return GatewayError.hasMarker(error$3)&&symbol6 in error$3}},name6=`GatewayResponseError`,marker7=`vercel.ai.gateway.error.${name6}`,symbol7=Symbol.for(marker7),_a7,_b7,GatewayResponseError=class extends (_b7=GatewayError,_a7=symbol7,_b7){constructor({message=`Invalid response from Gateway`,statusCode=502,response,validationError,cause}={}){super({message,statusCode,cause}),this[_a7]=!0,this.name=name6,this.type=`response_error`,this.response=response,this.validationError=validationError}static isInstance(error$3){return GatewayError.hasMarker(error$3)&&symbol7 in error$3}};async function createGatewayErrorFromResponse({response,statusCode,defaultMessage=`Gateway request failed`,cause,authMethod}){let parseResult=await safeValidateTypes({value:response,schema:gatewayErrorResponseSchema});if(!parseResult.success)return new GatewayResponseError({message:`Invalid error response format: ${defaultMessage}`,statusCode,response,validationError:parseResult.error,cause});let validatedResponse=parseResult.value,errorType=validatedResponse.error.type,message=validatedResponse.error.message;switch(errorType){case`authentication_error`:return GatewayAuthenticationError.createContextualError({apiKeyProvided:authMethod===`api-key`,oidcTokenProvided:authMethod===`oidc`,statusCode,cause});case`invalid_request_error`:return new GatewayInvalidRequestError({message,statusCode,cause});case`rate_limit_exceeded`:return new GatewayRateLimitError({message,statusCode,cause});case`model_not_found`:{let modelResult=await safeValidateTypes({value:validatedResponse.error.param,schema:modelNotFoundParamSchema});return new GatewayModelNotFoundError({message,statusCode,modelId:modelResult.success?modelResult.value.modelId:void 0,cause})}case`internal_server_error`:return new GatewayInternalServerError({message,statusCode,cause});default:return new GatewayInternalServerError({message,statusCode,cause})}}var gatewayErrorResponseSchema=lazyValidator(()=>zodSchema(z$2.object({error:z$2.object({message:z$2.string(),type:z$2.string().nullish(),param:z$2.unknown().nullish(),code:z$2.union([z$2.string(),z$2.number()]).nullish()})})));function asGatewayError(error$3,authMethod){var _a8;return GatewayError.isInstance(error$3)?error$3:APICallError.isInstance(error$3)?createGatewayErrorFromResponse({response:extractApiCallResponse(error$3),statusCode:error$3.statusCode??500,defaultMessage:`Gateway request failed`,cause:error$3,authMethod}):createGatewayErrorFromResponse({response:{},statusCode:500,defaultMessage:error$3 instanceof Error?`Gateway request failed: ${error$3.message}`:`Unknown Gateway error`,cause:error$3,authMethod})}function extractApiCallResponse(error$3){if(error$3.data!==void 0)return error$3.data;if(error$3.responseBody!=null)try{return JSON.parse(error$3.responseBody)}catch{return error$3.responseBody}return{}}var GATEWAY_AUTH_METHOD_HEADER=`ai-gateway-auth-method`;async function parseAuthMethod(headers){let result=await safeValidateTypes({value:headers[GATEWAY_AUTH_METHOD_HEADER],schema:gatewayAuthMethodSchema});return result.success?result.value:void 0}var gatewayAuthMethodSchema=lazyValidator(()=>zodSchema(z$2.union([z$2.literal(`api-key`),z$2.literal(`oidc`)]))),GatewayFetchMetadata=class{constructor(config){this.config=config}async getAvailableModels(){try{let{value}=await getFromApi({url:`${this.config.baseURL}/config`,headers:await resolve$10(this.config.headers()),successfulResponseHandler:createJsonResponseHandler(gatewayAvailableModelsResponseSchema),failedResponseHandler:createJsonErrorResponseHandler({errorSchema:z$2.any(),errorToMessage:data$2=>data$2}),fetch:this.config.fetch});return value}catch(error$3){throw await asGatewayError(error$3)}}async getCredits(){try{let baseUrl=new URL(this.config.baseURL),{value}=await getFromApi({url:`${baseUrl.origin}/v1/credits`,headers:await resolve$10(this.config.headers()),successfulResponseHandler:createJsonResponseHandler(gatewayCreditsResponseSchema),failedResponseHandler:createJsonErrorResponseHandler({errorSchema:z$2.any(),errorToMessage:data$2=>data$2}),fetch:this.config.fetch});return value}catch(error$3){throw await asGatewayError(error$3)}}},gatewayAvailableModelsResponseSchema=lazyValidator(()=>zodSchema(z$2.object({models:z$2.array(z$2.object({id:z$2.string(),name:z$2.string(),description:z$2.string().nullish(),pricing:z$2.object({input:z$2.string(),output:z$2.string(),input_cache_read:z$2.string().nullish(),input_cache_write:z$2.string().nullish()}).transform(({input,output,input_cache_read,input_cache_write})=>({input,output,...input_cache_read?{cachedInputTokens:input_cache_read}:{},...input_cache_write?{cacheCreationInputTokens:input_cache_write}:{}})).nullish(),specification:z$2.object({specificationVersion:z$2.literal(`v2`),provider:z$2.string(),modelId:z$2.string()}),modelType:z$2.enum([`language`,`embedding`,`image`]).nullish()}))}))),gatewayCreditsResponseSchema=lazyValidator(()=>zodSchema(z$2.object({balance:z$2.string(),total_used:z$2.string()}).transform(({balance,total_used})=>({balance,totalUsed:total_used})))),GatewayLanguageModel=class{constructor(modelId,config){this.modelId=modelId,this.config=config,this.specificationVersion=`v2`,this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(options$1){let{abortSignal:_abortSignal,...optionsWithoutSignal}=options$1;return{args:this.maybeEncodeFileParts(optionsWithoutSignal),warnings:[]}}async doGenerate(options$1){let{args,warnings}=await this.getArgs(options$1),{abortSignal}=options$1,resolvedHeaders=await resolve$10(this.config.headers());try{let{responseHeaders,value:responseBody,rawValue:rawResponse}=await postJsonToApi({url:this.getUrl(),headers:combineHeaders(resolvedHeaders,options$1.headers,this.getModelConfigHeaders(this.modelId,!1),await resolve$10(this.config.o11yHeaders)),body:args,successfulResponseHandler:createJsonResponseHandler(z$2.any()),failedResponseHandler:createJsonErrorResponseHandler({errorSchema:z$2.any(),errorToMessage:data$2=>data$2}),...abortSignal&&{abortSignal},fetch:this.config.fetch});return{...responseBody,request:{body:args},response:{headers:responseHeaders,body:rawResponse},warnings}}catch(error$3){throw await asGatewayError(error$3,await parseAuthMethod(resolvedHeaders))}}async doStream(options$1){let{args,warnings}=await this.getArgs(options$1),{abortSignal}=options$1,resolvedHeaders=await resolve$10(this.config.headers());try{let{value:response,responseHeaders}=await postJsonToApi({url:this.getUrl(),headers:combineHeaders(resolvedHeaders,options$1.headers,this.getModelConfigHeaders(this.modelId,!0),await resolve$10(this.config.o11yHeaders)),body:args,successfulResponseHandler:createEventSourceResponseHandler(z$2.any()),failedResponseHandler:createJsonErrorResponseHandler({errorSchema:z$2.any(),errorToMessage:data$2=>data$2}),...abortSignal&&{abortSignal},fetch:this.config.fetch});return{stream:response.pipeThrough(new TransformStream({start(controller){warnings.length>0&&controller.enqueue({type:`stream-start`,warnings})},transform(chunk$1,controller){if(chunk$1.success){let streamPart=chunk$1.value;if(streamPart.type===`raw`&&!options$1.includeRawChunks)return;streamPart.type===`response-metadata`&&streamPart.timestamp&&typeof streamPart.timestamp==`string`&&(streamPart.timestamp=new Date(streamPart.timestamp)),controller.enqueue(streamPart)}else controller.error(chunk$1.error)}})),request:{body:args},response:{headers:responseHeaders}}}catch(error$3){throw await asGatewayError(error$3,await parseAuthMethod(resolvedHeaders))}}isFilePart(part){return part&&typeof part==`object`&&`type`in part&&part.type===`file`}maybeEncodeFileParts(options$1){for(let message of options$1.prompt)for(let part of message.content)if(this.isFilePart(part)){let filePart=part;if(filePart.data instanceof Uint8Array){let buffer$2=Uint8Array.from(filePart.data),base64Data=Buffer.from(buffer$2).toString(`base64`);filePart.data=new URL(`data:${filePart.mediaType||`application/octet-stream`};base64,${base64Data}`)}}return options$1}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(modelId,streaming){return{"ai-language-model-specification-version":`2`,"ai-language-model-id":modelId,"ai-language-model-streaming":String(streaming)}}},GatewayEmbeddingModel=class{constructor(modelId,config){this.modelId=modelId,this.config=config,this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values,headers,abortSignal,providerOptions}){var _a8;let resolvedHeaders=await resolve$10(this.config.headers());try{let{responseHeaders,value:responseBody,rawValue}=await postJsonToApi({url:this.getUrl(),headers:combineHeaders(resolvedHeaders,headers??{},this.getModelConfigHeaders(),await resolve$10(this.config.o11yHeaders)),body:{input:values.length===1?values[0]:values,...providerOptions?{providerOptions}:{}},successfulResponseHandler:createJsonResponseHandler(gatewayEmbeddingResponseSchema),failedResponseHandler:createJsonErrorResponseHandler({errorSchema:z$2.any(),errorToMessage:data$2=>data$2}),...abortSignal&&{abortSignal},fetch:this.config.fetch});return{embeddings:responseBody.embeddings,usage:responseBody.usage??void 0,providerMetadata:responseBody.providerMetadata,response:{headers:responseHeaders,body:rawValue}}}catch(error$3){throw await asGatewayError(error$3,await parseAuthMethod(resolvedHeaders))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":`2`,"ai-model-id":this.modelId}}},gatewayEmbeddingResponseSchema=lazyValidator(()=>zodSchema(z$2.object({embeddings:z$2.array(z$2.array(z$2.number())),usage:z$2.object({tokens:z$2.number()}).nullish(),providerMetadata:z$2.record(z$2.string(),z$2.record(z$2.string(),z$2.unknown())).optional()})));async function getVercelRequestId(){var _a8;return(0,import_dist$7.getContext)().headers?.[`x-vercel-id`]}var VERSION$11=`2.0.0`,AI_GATEWAY_PROTOCOL_VERSION=`0.0.1`;function createGatewayProvider(options$1={}){var _a8,_b8;let pendingMetadata=null,metadataCache=null,cacheRefreshMillis=options$1.metadataCacheRefreshMillis??1e3*60*5,lastFetchTime=0,baseURL=withoutTrailingSlash(options$1.baseURL)??`https://ai-gateway.vercel.sh/v1/ai`,getHeaders$1=async()=>{let auth$2=await getGatewayAuthToken(options$1);if(auth$2)return withUserAgentSuffix({Authorization:`Bearer ${auth$2.token}`,"ai-gateway-protocol-version":AI_GATEWAY_PROTOCOL_VERSION,[GATEWAY_AUTH_METHOD_HEADER]:auth$2.authMethod,...options$1.headers},`ai-sdk/gateway/${VERSION$11}`);throw GatewayAuthenticationError.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},createO11yHeaders=()=>{let deploymentId=loadOptionalSetting({settingValue:void 0,environmentVariableName:`VERCEL_DEPLOYMENT_ID`}),environment=loadOptionalSetting({settingValue:void 0,environmentVariableName:`VERCEL_ENV`}),region=loadOptionalSetting({settingValue:void 0,environmentVariableName:`VERCEL_REGION`});return async()=>{let requestId=await getVercelRequestId();return{...deploymentId&&{"ai-o11y-deployment-id":deploymentId},...environment&&{"ai-o11y-environment":environment},...region&&{"ai-o11y-region":region},...requestId&&{"ai-o11y-request-id":requestId}}}},createLanguageModel=modelId=>new GatewayLanguageModel(modelId,{provider:`gateway`,baseURL,headers:getHeaders$1,fetch:options$1.fetch,o11yHeaders:createO11yHeaders()}),getAvailableModels=async()=>{var _a9,_b9,_c$2;let now=((_a9=options$1._internal)?.currentDate)?.call(_a9).getTime()??Date.now();return(!pendingMetadata||now-lastFetchTime>cacheRefreshMillis)&&(lastFetchTime=now,pendingMetadata=new GatewayFetchMetadata({baseURL,headers:getHeaders$1,fetch:options$1.fetch}).getAvailableModels().then(metadata=>(metadataCache=metadata,metadata)).catch(async error$3=>{throw await asGatewayError(error$3,await parseAuthMethod(await getHeaders$1()))})),metadataCache?Promise.resolve(metadataCache):pendingMetadata},getCredits=async()=>new GatewayFetchMetadata({baseURL,headers:getHeaders$1,fetch:options$1.fetch}).getCredits().catch(async error$3=>{throw await asGatewayError(error$3,await parseAuthMethod(await getHeaders$1()))}),provider=function(modelId){if(new.target)throw Error(`The Gateway Provider model function cannot be called with the new keyword.`);return createLanguageModel(modelId)};return provider.getAvailableModels=getAvailableModels,provider.getCredits=getCredits,provider.imageModel=modelId=>{throw new NoSuchModelError({modelId,modelType:`imageModel`})},provider.languageModel=createLanguageModel,provider.textEmbeddingModel=modelId=>new GatewayEmbeddingModel(modelId,{provider:`gateway`,baseURL,headers:getHeaders$1,fetch:options$1.fetch,o11yHeaders:createO11yHeaders()}),provider}var gateway=createGatewayProvider();async function getGatewayAuthToken(options$1){let apiKey=loadOptionalSetting({settingValue:options$1.apiKey,environmentVariableName:`AI_GATEWAY_API_KEY`});if(apiKey)return{token:apiKey,authMethod:`api-key`};try{return{token:await(0,import_dist$8.getVercelOidcToken)(),authMethod:`oidc`}}catch{return null}}var Diff$1=class{diff(oldStr,newStr,options$1={}){let callback$1;typeof options$1==`function`?(callback$1=options$1,options$1={}):`callback`in options$1&&(callback$1=options$1.callback);let oldString=this.castInput(oldStr,options$1),newString=this.castInput(newStr,options$1),oldTokens=this.removeEmpty(this.tokenize(oldString,options$1)),newTokens=this.removeEmpty(this.tokenize(newString,options$1));return this.diffWithOptionsObj(oldTokens,newTokens,options$1,callback$1)}diffWithOptionsObj(oldTokens,newTokens,options$1,callback$1){var _a$10;let done=value=>{if(value=this.postProcess(value,options$1),callback$1){setTimeout(function(){callback$1(value)},0);return}else return value},newLen=newTokens.length,oldLen=oldTokens.length,editLength=1,maxEditLength=newLen+oldLen;options$1.maxEditLength!=null&&(maxEditLength=Math.min(maxEditLength,options$1.maxEditLength));let maxExecutionTime=options$1.timeout??1/0,abortAfterTimestamp=Date.now()+maxExecutionTime,bestPath=[{oldPos:-1,lastComponent:void 0}],newPos=this.extractCommon(bestPath[0],newTokens,oldTokens,0,options$1);if(bestPath[0].oldPos+1>=oldLen&&newPos+1>=newLen)return done(this.buildValues(bestPath[0].lastComponent,newTokens,oldTokens));let minDiagonalToConsider=-1/0,maxDiagonalToConsider=1/0,execEditLength=()=>{for(let diagonalPath=Math.max(minDiagonalToConsider,-editLength);diagonalPath<=Math.min(maxDiagonalToConsider,editLength);diagonalPath+=2){let basePath,removePath=bestPath[diagonalPath-1],addPath=bestPath[diagonalPath+1];removePath&&(bestPath[diagonalPath-1]=void 0);let canAdd=!1;if(addPath){let addPathNewPos=addPath.oldPos-diagonalPath;canAdd=addPath&&0<=addPathNewPos&&addPathNewPos<newLen}let canRemove=removePath&&removePath.oldPos+1<oldLen;if(!canAdd&&!canRemove){bestPath[diagonalPath]=void 0;continue}if(basePath=!canRemove||canAdd&&removePath.oldPos<addPath.oldPos?this.addToPath(addPath,!0,!1,0,options$1):this.addToPath(removePath,!1,!0,1,options$1),newPos=this.extractCommon(basePath,newTokens,oldTokens,diagonalPath,options$1),basePath.oldPos+1>=oldLen&&newPos+1>=newLen)return done(this.buildValues(basePath.lastComponent,newTokens,oldTokens))||!0;bestPath[diagonalPath]=basePath,basePath.oldPos+1>=oldLen&&(maxDiagonalToConsider=Math.min(maxDiagonalToConsider,diagonalPath-1)),newPos+1>=newLen&&(minDiagonalToConsider=Math.max(minDiagonalToConsider,diagonalPath+1))}editLength++};if(callback$1)(function exec$3(){setTimeout(function(){if(editLength>maxEditLength||Date.now()>abortAfterTimestamp)return callback$1(void 0);execEditLength()||exec$3()},0)})();else for(;editLength<=maxEditLength&&Date.now()<=abortAfterTimestamp;){let ret=execEditLength();if(ret)return ret}}addToPath(path$38,added,removed,oldPosInc,options$1){let last$1=path$38.lastComponent;return last$1&&!options$1.oneChangePerToken&&last$1.added===added&&last$1.removed===removed?{oldPos:path$38.oldPos+oldPosInc,lastComponent:{count:last$1.count+1,added,removed,previousComponent:last$1.previousComponent}}:{oldPos:path$38.oldPos+oldPosInc,lastComponent:{count:1,added,removed,previousComponent:last$1}}}extractCommon(basePath,newTokens,oldTokens,diagonalPath,options$1){let newLen=newTokens.length,oldLen=oldTokens.length,oldPos=basePath.oldPos,newPos=oldPos-diagonalPath,commonCount=0;for(;newPos+1<newLen&&oldPos+1<oldLen&&this.equals(oldTokens[oldPos+1],newTokens[newPos+1],options$1);)newPos++,oldPos++,commonCount++,options$1.oneChangePerToken&&(basePath.lastComponent={count:1,previousComponent:basePath.lastComponent,added:!1,removed:!1});return commonCount&&!options$1.oneChangePerToken&&(basePath.lastComponent={count:commonCount,previousComponent:basePath.lastComponent,added:!1,removed:!1}),basePath.oldPos=oldPos,newPos}equals(left$2,right$2,options$1){return options$1.comparator?options$1.comparator(left$2,right$2):left$2===right$2||!!options$1.ignoreCase&&left$2.toLowerCase()===right$2.toLowerCase()}removeEmpty(array){let ret=[];for(let i$7=0;i$7<array.length;i$7++)array[i$7]&&ret.push(array[i$7]);return ret}castInput(value,options$1){return value}tokenize(value,options$1){return Array.from(value)}join(chars){return chars.join(``)}postProcess(changeObjects,options$1){return changeObjects}get useLongestToken(){return!1}buildValues(lastComponent,newTokens,oldTokens){let components=[],nextComponent;for(;lastComponent;)components.push(lastComponent),nextComponent=lastComponent.previousComponent,delete lastComponent.previousComponent,lastComponent=nextComponent;components.reverse();let componentLen=components.length,componentPos=0,newPos=0,oldPos=0;for(;componentPos<componentLen;componentPos++){let component=components[componentPos];if(component.removed)component.value=this.join(oldTokens.slice(oldPos,oldPos+component.count)),oldPos+=component.count;else{if(!component.added&&this.useLongestToken){let value=newTokens.slice(newPos,newPos+component.count);value=value.map(function(value$1,i$7){let oldValue=oldTokens[oldPos+i$7];return oldValue.length>value$1.length?oldValue:value$1}),component.value=this.join(value)}else component.value=this.join(newTokens.slice(newPos,newPos+component.count));newPos+=component.count,component.added||(oldPos+=component.count)}}return components}};new class extends Diff$1{};function longestCommonPrefix$1(str1,str2){let i$7;for(i$7=0;i$7<str1.length&&i$7<str2.length;i$7++)if(str1[i$7]!=str2[i$7])return str1.slice(0,i$7);return str1.slice(0,i$7)}function longestCommonSuffix$1(str1,str2){let i$7;if(!str1||!str2||str1[str1.length-1]!=str2[str2.length-1])return``;for(i$7=0;i$7<str1.length&&i$7<str2.length;i$7++)if(str1[str1.length-(i$7+1)]!=str2[str2.length-(i$7+1)])return str1.slice(-i$7);return str1.slice(-i$7)}function replacePrefix$1(string,oldPrefix,newPrefix){if(string.slice(0,oldPrefix.length)!=oldPrefix)throw Error(`string ${JSON.stringify(string)} doesn't start with prefix ${JSON.stringify(oldPrefix)}; this is a bug`);return newPrefix+string.slice(oldPrefix.length)}function replaceSuffix$1(string,oldSuffix,newSuffix){if(!oldSuffix)return string+newSuffix;if(string.slice(-oldSuffix.length)!=oldSuffix)throw Error(`string ${JSON.stringify(string)} doesn't end with suffix ${JSON.stringify(oldSuffix)}; this is a bug`);return string.slice(0,-oldSuffix.length)+newSuffix}function removePrefix$1(string,oldPrefix){return replacePrefix$1(string,oldPrefix,``)}function removeSuffix$1(string,oldSuffix){return replaceSuffix$1(string,oldSuffix,``)}function maximumOverlap$1(string1$1,string2$1){return string2$1.slice(0,overlapCount$1(string1$1,string2$1))}function overlapCount$1(a$2,b$2){let startA=0;a$2.length>b$2.length&&(startA=a$2.length-b$2.length);let endB=b$2.length;a$2.length<b$2.length&&(endB=a$2.length);let map$2=Array(endB),k=0;map$2[0]=0;for(let j$2=1;j$2<endB;j$2++){for(b$2[j$2]==b$2[k]?map$2[j$2]=map$2[k]:map$2[j$2]=k;k>0&&b$2[j$2]!=b$2[k];)k=map$2[k];b$2[j$2]==b$2[k]&&k++}k=0;for(let i$7=startA;i$7<a$2.length;i$7++){for(;k>0&&a$2[i$7]!=b$2[k];)k=map$2[k];a$2[i$7]==b$2[k]&&k++}return k}function trailingWs(string){let i$7;for(i$7=string.length-1;i$7>=0&&string[i$7].match(/\s/);i$7--);return string.substring(i$7+1)}function leadingWs(string){let match$1=string.match(/^\s*/);return match$1?match$1[0]:``}const extendedWordChars$1=`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}`,tokenizeIncludingWhitespace$1=RegExp(`[${extendedWordChars$1}]+|\\s+|[^${extendedWordChars$1}]`,`ug`);new class extends Diff$1{equals(left$2,right$2,options$1){return options$1.ignoreCase&&(left$2=left$2.toLowerCase(),right$2=right$2.toLowerCase()),left$2.trim()===right$2.trim()}tokenize(value,options$1={}){let parts;if(options$1.intlSegmenter){let segmenter$1=options$1.intlSegmenter;if(segmenter$1.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);parts=Array.from(segmenter$1.segment(value),segment=>segment.segment)}else parts=value.match(tokenizeIncludingWhitespace$1)||[];let tokens=[],prevPart=null;return parts.forEach(part=>{/\s/.test(part)?prevPart==null?tokens.push(part):tokens.push(tokens.pop()+part):prevPart!=null&&/\s/.test(prevPart)?tokens[tokens.length-1]==prevPart?tokens.push(tokens.pop()+part):tokens.push(prevPart+part):tokens.push(part),prevPart=part}),tokens}join(tokens){return tokens.map((token$1,i$7)=>i$7==0?token$1:token$1.replace(/^\s+/,``)).join(``)}postProcess(changes,options$1){if(!changes||options$1.oneChangePerToken)return changes;let lastKeep=null,insertion=null,deletion=null;return changes.forEach(change=>{change.added?insertion=change:change.removed?deletion=change:((insertion||deletion)&&dedupeWhitespaceInChangeObjects$1(lastKeep,deletion,insertion,change),lastKeep=change,insertion=null,deletion=null)}),(insertion||deletion)&&dedupeWhitespaceInChangeObjects$1(lastKeep,deletion,insertion,null),changes}};function dedupeWhitespaceInChangeObjects$1(startKeep,deletion,insertion,endKeep){if(deletion&&insertion){let oldWsPrefix=leadingWs(deletion.value),oldWsSuffix=trailingWs(deletion.value),newWsPrefix=leadingWs(insertion.value),newWsSuffix=trailingWs(insertion.value);if(startKeep){let commonWsPrefix=longestCommonPrefix$1(oldWsPrefix,newWsPrefix);startKeep.value=replaceSuffix$1(startKeep.value,newWsPrefix,commonWsPrefix),deletion.value=removePrefix$1(deletion.value,commonWsPrefix),insertion.value=removePrefix$1(insertion.value,commonWsPrefix)}if(endKeep){let commonWsSuffix=longestCommonSuffix$1(oldWsSuffix,newWsSuffix);endKeep.value=replacePrefix$1(endKeep.value,newWsSuffix,commonWsSuffix),deletion.value=removeSuffix$1(deletion.value,commonWsSuffix),insertion.value=removeSuffix$1(insertion.value,commonWsSuffix)}}else if(insertion){if(startKeep){let ws$2=leadingWs(insertion.value);insertion.value=insertion.value.substring(ws$2.length)}if(endKeep){let ws$2=leadingWs(endKeep.value);endKeep.value=endKeep.value.substring(ws$2.length)}}else if(startKeep&&endKeep){let newWsFull=leadingWs(endKeep.value),delWsStart=leadingWs(deletion.value),delWsEnd=trailingWs(deletion.value),newWsStart=longestCommonPrefix$1(newWsFull,delWsStart);deletion.value=removePrefix$1(deletion.value,newWsStart);let newWsEnd=longestCommonSuffix$1(removePrefix$1(newWsFull,newWsStart),delWsEnd);deletion.value=removeSuffix$1(deletion.value,newWsEnd),endKeep.value=replacePrefix$1(endKeep.value,newWsFull,newWsEnd),startKeep.value=replaceSuffix$1(startKeep.value,newWsFull,newWsFull.slice(0,newWsFull.length-newWsEnd.length))}else if(endKeep){let endKeepWsPrefix=leadingWs(endKeep.value),overlap=maximumOverlap$1(trailingWs(deletion.value),endKeepWsPrefix);deletion.value=removeSuffix$1(deletion.value,overlap)}else if(startKeep){let overlap=maximumOverlap$1(trailingWs(startKeep.value),leadingWs(deletion.value));deletion.value=removePrefix$1(deletion.value,overlap)}}new class extends Diff$1{tokenize(value){let regex$3=RegExp(`(\\r?\\n)|[${extendedWordChars$1}]+|[^\\S\\n\\r]+|[^${extendedWordChars$1}]`,`ug`);return value.match(regex$3)||[]}};const lineDiff$1=new class extends Diff$1{constructor(){super(...arguments),this.tokenize=tokenize$2}equals(left$2,right$2,options$1){return options$1.ignoreWhitespace?((!options$1.newlineIsToken||!left$2.includes(`
|
|
273
273
|
`))&&(left$2=left$2.trim()),(!options$1.newlineIsToken||!right$2.includes(`
|
|
274
274
|
`))&&(right$2=right$2.trim())):options$1.ignoreNewlineAtEof&&!options$1.newlineIsToken&&(left$2.endsWith(`
|
|
275
275
|
`)&&(left$2=left$2.slice(0,-1)),right$2.endsWith(`
|
|
276
276
|
`)&&(right$2=right$2.slice(0,-1))),super.equals(left$2,right$2,options$1)}};function diffLines$1(oldStr,newStr,options$1){return lineDiff$1.diff(oldStr,newStr,options$1)}function tokenize$2(value,options$1){options$1.stripTrailingCr&&(value=value.replace(/\r\n/g,`
|
|
277
|
-
`));let retLines=[],linesAndNewlines=value.split(/(\n|\r\n)/);linesAndNewlines[linesAndNewlines.length-1]||linesAndNewlines.pop();for(let i$7=0;i$7<linesAndNewlines.length;i$7++){let line$1=linesAndNewlines[i$7];i$7%2&&!options$1.newlineIsToken?retLines[retLines.length-1]+=line$1:retLines.push(line$1)}return retLines}function isSentenceEndPunct(char){return char==`.`||char==`!`||char==`?`}new class extends Diff$1{tokenize(value){var _a$10;let result=[],tokenStartI=0;for(let i$7=0;i$7<value.length;i$7++){if(i$7==value.length-1){result.push(value.slice(tokenStartI));break}if(isSentenceEndPunct(value[i$7])&&value[i$7+1].match(/\s/)){for(result.push(value.slice(tokenStartI,i$7+1)),i$7=tokenStartI=i$7+1;value[i$7+1]?.match(/\s/);)i$7++;result.push(value.slice(tokenStartI,i$7+1)),tokenStartI=i$7+1}}return result}},new class extends Diff$1{tokenize(value){return value.split(/([{}:;,]|\s+)/)}},new class extends Diff$1{constructor(){super(...arguments),this.tokenize=tokenize$2}get useLongestToken(){return!0}castInput(value,options$1){let{undefinedReplacement,stringifyReplacer=(k,v$1)=>v$1===void 0?undefinedReplacement:v$1}=options$1;return typeof value==`string`?value:JSON.stringify(canonicalize$1(value,null,null,stringifyReplacer),null,` `)}equals(left$2,right$2,options$1){return super.equals(left$2.replace(/,([\r\n])/g,`$1`),right$2.replace(/,([\r\n])/g,`$1`),options$1)}};function canonicalize$1(obj,stack,replacementStack,replacer,key$1){stack||=[],replacementStack||=[],replacer&&(obj=replacer(key$1===void 0?``:key$1,obj));let i$7;for(i$7=0;i$7<stack.length;i$7+=1)if(stack[i$7]===obj)return replacementStack[i$7];let canonicalizedObj;if(Object.prototype.toString.call(obj)===`[object Array]`){for(stack.push(obj),canonicalizedObj=Array(obj.length),replacementStack.push(canonicalizedObj),i$7=0;i$7<obj.length;i$7+=1)canonicalizedObj[i$7]=canonicalize$1(obj[i$7],stack,replacementStack,replacer,String(i$7));return stack.pop(),replacementStack.pop(),canonicalizedObj}if(obj&&obj.toJSON&&(obj=obj.toJSON()),typeof obj==`object`&&obj){stack.push(obj),canonicalizedObj={},replacementStack.push(canonicalizedObj);let sortedKeys=[],key$1$1;for(key$1$1 in obj)Object.prototype.hasOwnProperty.call(obj,key$1$1)&&sortedKeys.push(key$1$1);for(sortedKeys.sort(),i$7=0;i$7<sortedKeys.length;i$7+=1)key$1$1=sortedKeys[i$7],canonicalizedObj[key$1$1]=canonicalize$1(obj[key$1$1],stack,replacementStack,replacer,key$1$1);stack.pop(),replacementStack.pop()}else canonicalizedObj=obj;return canonicalizedObj}new class extends Diff$1{tokenize(value){return value.slice()}join(value){return value}removeEmpty(value){return value}};function structuredPatch$1(oldFileName,newFileName,oldStr,newStr,oldHeader,newHeader,options$1){let optionsObj;optionsObj=options$1?typeof options$1==`function`?{callback:options$1}:options$1:{},optionsObj.context===void 0&&(optionsObj.context=4);let context=optionsObj.context;if(optionsObj.newlineIsToken)throw Error(`newlineIsToken may not be used with patch-generation functions, only with diffing functions`);if(optionsObj.callback){let{callback:callback$1}=optionsObj;diffLines$1(oldStr,newStr,Object.assign(Object.assign({},optionsObj),{callback:diff$2=>{
|
|
277
|
+
`));let retLines=[],linesAndNewlines=value.split(/(\n|\r\n)/);linesAndNewlines[linesAndNewlines.length-1]||linesAndNewlines.pop();for(let i$7=0;i$7<linesAndNewlines.length;i$7++){let line$1=linesAndNewlines[i$7];i$7%2&&!options$1.newlineIsToken?retLines[retLines.length-1]+=line$1:retLines.push(line$1)}return retLines}function isSentenceEndPunct(char){return char==`.`||char==`!`||char==`?`}new class extends Diff$1{tokenize(value){var _a$10;let result=[],tokenStartI=0;for(let i$7=0;i$7<value.length;i$7++){if(i$7==value.length-1){result.push(value.slice(tokenStartI));break}if(isSentenceEndPunct(value[i$7])&&value[i$7+1].match(/\s/)){for(result.push(value.slice(tokenStartI,i$7+1)),i$7=tokenStartI=i$7+1;value[i$7+1]?.match(/\s/);)i$7++;result.push(value.slice(tokenStartI,i$7+1)),tokenStartI=i$7+1}}return result}},new class extends Diff$1{tokenize(value){return value.split(/([{}:;,]|\s+)/)}},new class extends Diff$1{constructor(){super(...arguments),this.tokenize=tokenize$2}get useLongestToken(){return!0}castInput(value,options$1){let{undefinedReplacement,stringifyReplacer=(k,v$1)=>v$1===void 0?undefinedReplacement:v$1}=options$1;return typeof value==`string`?value:JSON.stringify(canonicalize$1(value,null,null,stringifyReplacer),null,` `)}equals(left$2,right$2,options$1){return super.equals(left$2.replace(/,([\r\n])/g,`$1`),right$2.replace(/,([\r\n])/g,`$1`),options$1)}};function canonicalize$1(obj,stack,replacementStack,replacer,key$1){stack||=[],replacementStack||=[],replacer&&(obj=replacer(key$1===void 0?``:key$1,obj));let i$7;for(i$7=0;i$7<stack.length;i$7+=1)if(stack[i$7]===obj)return replacementStack[i$7];let canonicalizedObj;if(Object.prototype.toString.call(obj)===`[object Array]`){for(stack.push(obj),canonicalizedObj=Array(obj.length),replacementStack.push(canonicalizedObj),i$7=0;i$7<obj.length;i$7+=1)canonicalizedObj[i$7]=canonicalize$1(obj[i$7],stack,replacementStack,replacer,String(i$7));return stack.pop(),replacementStack.pop(),canonicalizedObj}if(obj&&obj.toJSON&&(obj=obj.toJSON()),typeof obj==`object`&&obj){stack.push(obj),canonicalizedObj={},replacementStack.push(canonicalizedObj);let sortedKeys=[],key$1$1;for(key$1$1 in obj)Object.prototype.hasOwnProperty.call(obj,key$1$1)&&sortedKeys.push(key$1$1);for(sortedKeys.sort(),i$7=0;i$7<sortedKeys.length;i$7+=1)key$1$1=sortedKeys[i$7],canonicalizedObj[key$1$1]=canonicalize$1(obj[key$1$1],stack,replacementStack,replacer,key$1$1);stack.pop(),replacementStack.pop()}else canonicalizedObj=obj;return canonicalizedObj}new class extends Diff$1{tokenize(value){return value.slice()}join(value){return value}removeEmpty(value){return value}};function structuredPatch$1(oldFileName,newFileName,oldStr,newStr,oldHeader,newHeader,options$1){let optionsObj;optionsObj=options$1?typeof options$1==`function`?{callback:options$1}:options$1:{},optionsObj.context===void 0&&(optionsObj.context=4);let context=optionsObj.context;if(optionsObj.newlineIsToken)throw Error(`newlineIsToken may not be used with patch-generation functions, only with diffing functions`);if(optionsObj.callback){let{callback:callback$1}=optionsObj;diffLines$1(oldStr,newStr,Object.assign(Object.assign({},optionsObj),{callback:diff$2=>{callback$1(diffLinesResultToPatch(diff$2))}}))}else return diffLinesResultToPatch(diffLines$1(oldStr,newStr,optionsObj));function diffLinesResultToPatch(diff$2){if(!diff$2)return;diff$2.push({value:``,lines:[]});function contextLines(lines){return lines.map(function(entry){return` `+entry})}let hunks=[],oldRangeStart=0,newRangeStart=0,curRange=[],oldLine=1,newLine=1;for(let i$7=0;i$7<diff$2.length;i$7++){let current=diff$2[i$7],lines=current.lines||splitLines$1(current.value);if(current.lines=lines,current.added||current.removed){if(!oldRangeStart){let prev=diff$2[i$7-1];oldRangeStart=oldLine,newRangeStart=newLine,prev&&(curRange=context>0?contextLines(prev.lines.slice(-context)):[],oldRangeStart-=curRange.length,newRangeStart-=curRange.length)}for(let line$1 of lines)curRange.push((current.added?`+`:`-`)+line$1);current.added?newLine+=lines.length:oldLine+=lines.length}else{if(oldRangeStart)if(lines.length<=context*2&&i$7<diff$2.length-2)for(let line$1 of contextLines(lines))curRange.push(line$1);else{let contextSize=Math.min(lines.length,context);for(let line$1 of contextLines(lines.slice(0,contextSize)))curRange.push(line$1);let hunk={oldStart:oldRangeStart,oldLines:oldLine-oldRangeStart+contextSize,newStart:newRangeStart,newLines:newLine-newRangeStart+contextSize,lines:curRange};hunks.push(hunk),oldRangeStart=0,newRangeStart=0,curRange=[]}oldLine+=lines.length,newLine+=lines.length}}for(let hunk of hunks)for(let i$7=0;i$7<hunk.lines.length;i$7++)hunk.lines[i$7].endsWith(`
|
|
278
278
|
`)?hunk.lines[i$7]=hunk.lines[i$7].slice(0,-1):(hunk.lines.splice(i$7+1,0,`\`),i$7++);return{oldFileName,newFileName,oldHeader,newHeader,hunks}}}function splitLines$1(text){let hasTrailingNl=text.endsWith(`
|
|
279
279
|
`),result=text.split(`
|
|
280
280
|
`).map(line$1=>line$1+`
|
|
@@ -300,7 +300,7 @@ Usage:
|
|
|
300
300
|
- This tool allows Blink to read images (eg PNG, JPG, etc). When reading an image file the contents are presented visually as Blink is a multimodal LLM
|
|
301
301
|
- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.
|
|
302
302
|
- You will regularly be asked to read screenshots. If the user provides a path to a screenshot ALWAYS use this tool to view the file at the path. This tool will work with all temporary file paths like /var/folders/123/abc/T/TemporaryItems/NSIRD_screencaptureui_ZfB1tD/Screenshot.png
|
|
303
|
-
- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.`,inputSchema:z.object({file_path:z.string(),line_offset:z.number(),line_limit:z.number()}),execute:async(args,opts)=>await(await client()).request(`read_file`,{path:args.file_path,line_start:args.line_offset,line_end:args.line_offset+args.line_limit},{signal:opts.abortSignal}),toModelOutput:output=>output.mime_type?.startsWith(`image/`)?{type:`content`,value:[{type:`media`,data:output.content,mediaType:output.mime_type}]}:{type:`json`,value:output}})),write_file:toolWithCompute(({client})=>({description:`Write a file to the filesystem.`,inputSchema:z.object({file_path:z.string(),content:z.string()}),execute:async(args,opts)=>{await(await client()).request(`write_file`,{path:args.file_path,content:args.content},{signal:opts.abortSignal})}})),read_directory:toolWithCompute(({client})=>tool({description:`Reads a directory from the workspace filesystem.`,inputSchema:z.object({directory_path:z.string()}),execute:async(args,opts)=>(await client()).request(`read_directory`,{path:args.directory_path})})),edit_file:toolWithCompute(({client:promiseClient})=>({description:`This is a tool for making multiple edits to a single file in one operation. It is built on top of the "workspace_edit_file" tool and allows you to perform multiple find-and-replace operations efficiently. Prefer this tool over the "workspace_edit_file" tool when you need to make multiple edits to the same file.
|
|
303
|
+
- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.`,inputSchema:z.object({file_path:z.string(),line_offset:z.number(),line_limit:z.number()}),execute:async(args,opts)=>(console.log(`reading file`,args),await(await client()).request(`read_file`,{path:args.file_path,line_start:args.line_offset,line_end:args.line_offset+args.line_limit},{signal:opts.abortSignal})),toModelOutput:output=>output.mime_type?.startsWith(`image/`)?{type:`content`,value:[{type:`media`,data:output.content,mediaType:output.mime_type}]}:{type:`json`,value:output}})),write_file:toolWithCompute(({client})=>({description:`Write a file to the filesystem.`,inputSchema:z.object({file_path:z.string(),content:z.string()}),execute:async(args,opts)=>{await(await client()).request(`write_file`,{path:args.file_path,content:args.content},{signal:opts.abortSignal})}})),read_directory:toolWithCompute(({client})=>tool({description:`Reads a directory from the workspace filesystem.`,inputSchema:z.object({directory_path:z.string()}),execute:async(args,opts)=>(await client()).request(`read_directory`,{path:args.directory_path})})),edit_file:toolWithCompute(({client:promiseClient})=>({description:`This is a tool for making multiple edits to a single file in one operation. It is built on top of the "workspace_edit_file" tool and allows you to perform multiple find-and-replace operations efficiently. Prefer this tool over the "workspace_edit_file" tool when you need to make multiple edits to the same file.
|
|
304
304
|
|
|
305
305
|
Before using this tool:
|
|
306
306
|
|
|
@@ -338,7 +338,7 @@ When making edits:
|
|
|
338
338
|
If you want to create a new file, use:
|
|
339
339
|
- A new file path, including dir name if needed
|
|
340
340
|
- First edit: empty old_string and the new file's contents as new_string
|
|
341
|
-
- Subsequent edits: normal edit operations on the created content`,inputSchema:z.object({file_path:z.string(),edits:z.array(z.object({old_string:z.string(),new_string:z.string(),expected_replacements:z.number()}))}),execute:async(args,opts)=>{let client=await promiseClient(),file;try{file=(await client.request(`read_file`,{path:args.file_path},{signal:opts.abortSignal})).content}catch{if(file=args.edits[0].new_string,args.edits.length>0&&args.edits[0].old_string===``)file=args.edits[0].new_string,args.edits.shift();else throw Error(`input is invalid: File does not exist and first edit is not for file creation.\nFile: ${args.file_path}`)}let newFile=file,edits=[];for(let edit$1 of args.edits){let expectedReplacements=edit$1.expected_replacements??1,oldString=edit$1.old_string
|
|
341
|
+
- Subsequent edits: normal edit operations on the created content`,inputSchema:z.object({file_path:z.string(),edits:z.array(z.object({old_string:z.string(),new_string:z.string(),expected_replacements:z.number()}))}),execute:async(args,opts)=>{let client=await promiseClient(),file;try{file=(await client.request(`read_file`,{path:args.file_path},{signal:opts.abortSignal})).content}catch{if(file=args.edits[0].new_string,args.edits.length>0&&args.edits[0].old_string===``)file=args.edits[0].new_string,args.edits.shift();else throw Error(`input is invalid: File does not exist and first edit is not for file creation.\nFile: ${args.file_path}`)}let newFile=file,edits=[];for(let edit$1 of args.edits){let expectedReplacements=edit$1.expected_replacements??1,oldString=edit$1.old_string;if(oldString===edit$1.new_string)throw Error(`input is invalid: old_string and new_string are identical.\nString: ${oldString}`);let occurrences=countStringOccurrences(newFile,oldString);if(occurrences===0)throw Error(`input is invalid: String to replace not found in file.\nString: ${oldString}`);if(occurrences!==expectedReplacements)throw Error(`input is invalid: Found ${occurrences} matches of the string to replace, but expected ${expectedReplacements}. The number of actual matches must equal the expected replacements. Please adjust your string to match or update the expected count.\nString: ${oldString}`)}for(let edit$1 of args.edits){let oldString=edit$1.old_string,newString=edit$1.new_string;newFile=replaceAllOccurrences(newFile,oldString,newString),edits.push({old_string:oldString,new_string:newString})}await client.request(`write_file`,{path:args.file_path,content:newFile},{signal:opts.abortSignal});let patch$2=structuredPatch$1(args.file_path,args.file_path,file,newFile);return{edits,file_path:args.file_path,structured_patch:patch$2.hunks.map(hunk=>({old_start:hunk.oldStart,old_end:hunk.oldLines,new_start:hunk.newStart,new_end:hunk.newLines,lines:hunk.lines}))}}})),process_grep_output:toolWithCompute(({client})=>({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.
|
|
342
342
|
|
|
343
343
|
Use this for:
|
|
344
344
|
- Finding test failures and error messages
|
|
@@ -1740,7 +1740,13 @@ The structure MUST be as follows:
|
|
|
1740
1740
|
**Decision Rules (apply in order):**
|
|
1741
1741
|
1. **Model Continues:** If your last response explicitly states an immediate next action *you* intend to take (e.g., "Next, I will...", "Now I'll process...", "Moving on to analyze...", indicates an intended tool call that didn't execute), OR if the response seems clearly incomplete (cut off mid-thought without a natural conclusion), then the **'model'** should speak next.
|
|
1742
1742
|
2. **Question to User:** If your last response ends with a direct question specifically addressed *to the user*, then the **'user'** should speak next.
|
|
1743
|
-
3. **Waiting for User:** If your last response completed a thought, statement, or task *and* does not meet the criteria for Rule 1 (Model Continues) or Rule 2 (Question to User), it implies a pause expecting user input or reaction. In this case, the **'user'** should speak next.`}]}];try{let parsedResponse=await geminiClient.generateJson(contents,RESPONSE_SCHEMA,abortSignal,DEFAULT_GEMINI_FLASH_MODEL);return parsedResponse&&parsedResponse.next_speaker&&[`user`,`model`].includes(parsedResponse.next_speaker)?parsedResponse:null}catch(error$3){return console.warn(`Failed to talk to Gemini endpoint when seeing if conversation should continue.`,error$3),null}}var import_levenshtein=__toESM(__commonJSMin(((exports,module)=>{(function(){var collator;try{collator=typeof Intl<`u`&&Intl.Collator!==void 0?Intl.Collator(`generic`,{sensitivity:`base`}):null}catch{console.log(`Collator could not be initialized and wouldn't be used`)}var prevRow=[],str2Char=[],Levenshtein={get:function(str1,str2,options$1){var useCollator=options$1&&collator&&options$1.useCollator,str1Len=str1.length,str2Len=str2.length;if(str1Len===0)return str2Len;if(str2Len===0)return str1Len;var curCol,nextCol,i$7,j$2,tmp;for(i$7=0;i$7<str2Len;++i$7)prevRow[i$7]=i$7,str2Char[i$7]=str2.charCodeAt(i$7);prevRow[str2Len]=str2Len;var strCmp;if(useCollator)for(i$7=0;i$7<str1Len;++i$7){for(nextCol=i$7+1,j$2=0;j$2<str2Len;++j$2)curCol=nextCol,strCmp=collator.compare(str1.charAt(i$7),String.fromCharCode(str2Char[j$2]))===0,nextCol=prevRow[j$2]+(strCmp?0:1),tmp=curCol+1,nextCol>tmp&&(nextCol=tmp),tmp=prevRow[j$2+1]+1,nextCol>tmp&&(nextCol=tmp),prevRow[j$2]=curCol;prevRow[j$2]=nextCol}else for(i$7=0;i$7<str1Len;++i$7){for(nextCol=i$7+1,j$2=0;j$2<str2Len;++j$2)curCol=nextCol,strCmp=str1.charCodeAt(i$7)===str2Char[j$2],nextCol=prevRow[j$2]+(strCmp?0:1),tmp=curCol+1,nextCol>tmp&&(nextCol=tmp),tmp=prevRow[j$2+1]+1,nextCol>tmp&&(nextCol=tmp),prevRow[j$2]=curCol;prevRow[j$2]=nextCol}return nextCol}};typeof define<`u`&&define!==null&&define.amd?define(function(){return Levenshtein}):module!=null&&exports!==void 0&&module.exports===exports?module.exports=Levenshtein:typeof self<`u`&&typeof self.postMessage==`function`&&typeof self.importScripts==`function`?self.Levenshtein=Levenshtein:typeof window<`u`&&window!==null&&(window.Levenshtein=Levenshtein)})()}))(),1),ChatRecordingService=class{conversationFile=null;cachedLastConvData=null;sessionId;projectHash;queuedThoughts=[];queuedTokens=null;config;constructor(config){this.config=config,this.sessionId=config.getSessionId(),this.projectHash=getProjectHash(config.getProjectRoot())}initialize(resumedSessionData){try{if(resumedSessionData)this.conversationFile=resumedSessionData.filePath,this.sessionId=resumedSessionData.conversation.sessionId,this.updateConversation(conversation=>{conversation.sessionId=this.sessionId}),this.cachedLastConvData=null;else{let chatsDir=path.join(this.config.storage.getProjectTempDir(),`chats`);fs.mkdirSync(chatsDir,{recursive:!0});let filename=`session-${new Date().toISOString().slice(0,16).replace(/:/g,`-`)}-${this.sessionId.slice(0,8)}.json`;this.conversationFile=path.join(chatsDir,filename),this.writeConversation({sessionId:this.sessionId,projectHash:this.projectHash,startTime:new Date().toISOString(),lastUpdated:new Date().toISOString(),messages:[]})}this.queuedThoughts=[],this.queuedTokens=null}catch(error$3){throw console.error(`Error initializing chat recording service:`,error$3),error$3}}getLastMessage(conversation){return conversation.messages.at(-1)}newMessage(type,content){return{id:randomUUID$1(),timestamp:new Date().toISOString(),type,content}}recordMessage(message){if(this.conversationFile)try{this.updateConversation(conversation=>{let msg=this.newMessage(message.type,message.content);msg.type===`gemini`?(conversation.messages.push({...msg,thoughts:this.queuedThoughts,tokens:this.queuedTokens,model:this.config.getModel()}),this.queuedThoughts=[],this.queuedTokens=null):conversation.messages.push(msg)})}catch(error$3){throw console.error(`Error saving message:`,error$3),error$3}}recordThought(thought){if(this.conversationFile)try{this.queuedThoughts.push({...thought,timestamp:new Date().toISOString()})}catch(error$3){throw console.error(`Error saving thought:`,error$3),error$3}}recordMessageTokens(respUsageMetadata){if(this.conversationFile)try{let tokens={input:respUsageMetadata.promptTokenCount??0,output:respUsageMetadata.candidatesTokenCount??0,cached:respUsageMetadata.cachedContentTokenCount??0,thoughts:respUsageMetadata.thoughtsTokenCount??0,tool:respUsageMetadata.toolUsePromptTokenCount??0,total:respUsageMetadata.totalTokenCount??0};this.updateConversation(conversation=>{let lastMsg=this.getLastMessage(conversation);lastMsg&&lastMsg.type===`gemini`&&!lastMsg.tokens?(lastMsg.tokens=tokens,this.queuedTokens=null):this.queuedTokens=tokens})}catch(error$3){throw console.error(`Error updating message tokens:`,error$3),error$3}}recordToolCalls(toolCalls){if(!this.conversationFile)return;let toolRegistry=this.config.getToolRegistry(),enrichedToolCalls=toolCalls.map(toolCall=>{let toolInstance=toolRegistry.getTool(toolCall.name);return{...toolCall,displayName:toolInstance?.displayName||toolCall.name,description:toolInstance?.description||``,renderOutputAsMarkdown:toolInstance?.isOutputMarkdown||!1}});try{this.updateConversation(conversation=>{let lastMsg=this.getLastMessage(conversation);if(!lastMsg||lastMsg.type!==`gemini`||this.queuedThoughts.length>0){let newMsg={...this.newMessage(`gemini`,``),type:`gemini`,toolCalls:enrichedToolCalls,thoughts:this.queuedThoughts,model:this.config.getModel()};this.queuedThoughts.length>0&&(newMsg.thoughts=this.queuedThoughts,this.queuedThoughts=[]),this.queuedTokens&&=(newMsg.tokens=this.queuedTokens,null),conversation.messages.push(newMsg)}else{lastMsg.toolCalls||=[],lastMsg.toolCalls=lastMsg.toolCalls.map(toolCall=>{let incomingToolCall=toolCalls.find(tc=>tc.id===toolCall.id);return incomingToolCall?{...toolCall,...incomingToolCall}:toolCall});for(let toolCall of enrichedToolCalls)lastMsg.toolCalls.find(tc=>tc.id===toolCall.id)||lastMsg.toolCalls.push(toolCall)}})}catch(error$3){throw console.error(`Error adding tool call to message:`,error$3),error$3}}readConversation(){try{return this.cachedLastConvData=fs.readFileSync(this.conversationFile,`utf8`),JSON.parse(this.cachedLastConvData)}catch(error$3){if(error$3.code!==`ENOENT`)throw console.error(`Error reading conversation file:`,error$3),error$3;return{sessionId:this.sessionId,projectHash:this.projectHash,startTime:new Date().toISOString(),lastUpdated:new Date().toISOString(),messages:[]}}}writeConversation(conversation){try{if(!this.conversationFile||conversation.messages.length===0)return;if(this.cachedLastConvData!==JSON.stringify(conversation,null,2)){conversation.lastUpdated=new Date().toISOString();let newContent=JSON.stringify(conversation,null,2);this.cachedLastConvData=newContent,fs.writeFileSync(this.conversationFile,newContent)}}catch(error$3){throw console.error(`Error writing conversation file:`,error$3),error$3}}updateConversation(updateFn){let conversation=this.readConversation();updateFn(conversation),this.writeConversation(conversation)}deleteSession(sessionId$1){try{let chatsDir=path.join(this.config.storage.getProjectTempDir(),`chats`),sessionPath=path.join(chatsDir,`${sessionId$1}.json`);fs.unlinkSync(sessionPath)}catch(error$3){throw console.error(`Error deleting session:`,error$3),error$3}}},TelemetryTarget;(function(TelemetryTarget$1){TelemetryTarget$1.GCP=`gcp`,TelemetryTarget$1.LOCAL=`local`})(TelemetryTarget||={});const DEFAULT_TELEMETRY_TARGET=TelemetryTarget.LOCAL,DEFAULT_OTLP_ENDPOINT=`http://localhost:4317`;async function handleFallback(config,failedModel,authType,error$3){if(authType!==AuthType.LOGIN_WITH_GOOGLE)return null;let fallbackModel=DEFAULT_GEMINI_FLASH_MODEL;if(failedModel===fallbackModel)return null;let fallbackModelHandler=config.fallbackModelHandler;if(typeof fallbackModelHandler!=`function`)return null;try{let intent=await fallbackModelHandler(failedModel,fallbackModel,error$3);switch(intent){case`retry`:return activateFallbackMode(config,authType),!0;case`stop`:return activateFallbackMode(config,authType),!1;case`auth`:return!1;default:throw Error(`Unexpected fallback intent received from fallbackModelHandler: "${intent}"`)}}catch(handlerError){return console.error(`Fallback UI handler failed:`,handlerError),null}}function activateFallbackMode(config,authType){config.isInFallbackMode()||(config.setFallbackMode(!0),authType&&logFlashFallback(config,new FlashFallbackEvent(authType)))}function partListUnionToString(value){return partToString(value,{verbose:!0})}var StreamEventType;(function(StreamEventType$1){StreamEventType$1.CHUNK=`chunk`,StreamEventType$1.RETRY=`retry`})(StreamEventType||={});const INVALID_CONTENT_RETRY_OPTIONS={maxAttempts:3,initialDelayMs:500};function isValidResponse(response){if(response.candidates===void 0||response.candidates.length===0)return!1;let content=response.candidates[0]?.content;return content===void 0?!1:isValidContent(content)}function isValidContent(content){if(content.parts===void 0||content.parts.length===0)return!1;for(let part of content.parts)if(part===void 0||Object.keys(part).length===0||!part.thought&&part.text!==void 0&&part.text===``)return!1;return!0}function validateHistory(history){for(let content of history)if(content.role!==`user`&&content.role!==`model`)throw Error(`Role must be user or model, but got ${content.role}.`)}function extractCuratedHistory(comprehensiveHistory){if(comprehensiveHistory===void 0||comprehensiveHistory.length===0)return[];let curatedHistory=[],length=comprehensiveHistory.length,i$7=0;for(;i$7<length;)if(comprehensiveHistory[i$7].role===`user`)curatedHistory.push(comprehensiveHistory[i$7]),i$7++;else{let modelOutput=[],isValid=!0;for(;i$7<length&&comprehensiveHistory[i$7].role===`model`;)modelOutput.push(comprehensiveHistory[i$7]),isValid&&!isValidContent(comprehensiveHistory[i$7])&&(isValid=!1),i$7++;isValid&&curatedHistory.push(...modelOutput)}return curatedHistory}var EmptyStreamError=class extends Error{constructor(message){super(message),this.name=`EmptyStreamError`}},GeminiChat=class{config;generationConfig;history;sendPromise=Promise.resolve();chatRecordingService;constructor(config,generationConfig={},history=[]){this.config=config,this.generationConfig=generationConfig,this.history=history,validateHistory(history),this.chatRecordingService=new ChatRecordingService(config),this.chatRecordingService.initialize()}setSystemInstruction(sysInstr){this.generationConfig.systemInstruction=sysInstr}async sendMessageStream(params,prompt_id){await this.sendPromise;let streamDoneResolver;this.sendPromise=new Promise(resolve$11=>{streamDoneResolver=resolve$11});let userContent=createUserContent(params.message);if(!isFunctionResponse(userContent)){let userMessage=Array.isArray(params.message)?params.message:[params.message],userMessageContent=partListUnionToString(toParts(userMessage));this.chatRecordingService.recordMessage({type:`user`,content:userMessageContent})}this.history.push(userContent);let requestContents=this.getHistory(!0),self$1=this;return(async function*(){try{let lastError=Error(`Request failed after all retries.`);for(let attempt=0;attempt<INVALID_CONTENT_RETRY_OPTIONS.maxAttempts;attempt++)try{attempt>0&&(yield{type:StreamEventType.RETRY});let stream$8=await self$1.makeApiCallAndProcessStream(requestContents,params,prompt_id,userContent);for await(let chunk$1 of stream$8)yield{type:StreamEventType.CHUNK,value:chunk$1};lastError=null;break}catch(error$3){if(lastError=error$3,error$3 instanceof EmptyStreamError&&attempt<INVALID_CONTENT_RETRY_OPTIONS.maxAttempts-1){logContentRetry(self$1.config,new ContentRetryEvent(attempt,`EmptyStreamError`,INVALID_CONTENT_RETRY_OPTIONS.initialDelayMs)),await new Promise(res=>setTimeout(res,INVALID_CONTENT_RETRY_OPTIONS.initialDelayMs*(attempt+1)));continue}break}if(lastError)throw lastError instanceof EmptyStreamError&&logContentRetryFailure(self$1.config,new ContentRetryFailureEvent(INVALID_CONTENT_RETRY_OPTIONS.maxAttempts,`EmptyStreamError`)),self$1.history[self$1.history.length-1]===userContent&&self$1.history.pop(),lastError}finally{streamDoneResolver()}})()}async makeApiCallAndProcessStream(requestContents,params,prompt_id,userContent){let currentAttemptModel,streamResponse=await retryWithBackoff(()=>{let modelToUse=this.config.isInFallbackMode()?DEFAULT_GEMINI_FLASH_MODEL:this.config.getModel();if(currentAttemptModel=modelToUse,this.config.getQuotaErrorOccurred()&&modelToUse===DEFAULT_GEMINI_FLASH_MODEL)throw Error(`Please submit a new query to continue with the Flash model.`);return this.config.getContentGenerator().generateContentStream({model:modelToUse,contents:requestContents,config:{...this.generationConfig,...params.config}},prompt_id)},{shouldRetry:error$3=>{if(error$3 instanceof Error&&error$3.message){if(isSchemaDepthError(error$3.message))return!1;if(error$3.message.includes(`429`)||error$3.message.match(/5\d{2}/))return!0}return!1},onPersistent429:async(authType,error$3)=>currentAttemptModel?await handleFallback(this.config,currentAttemptModel,authType,error$3):null,authType:this.config.getContentGeneratorConfig()?.authType});return this.processStreamResponse(streamResponse,userContent)}getHistory(curated=!1){let history=curated?extractCuratedHistory(this.history):this.history;return structuredClone(history)}clearHistory(){this.history=[]}addHistory(content){this.history.push(content)}setHistory(history){this.history=history}stripThoughtsFromHistory(){this.history=this.history.map(content=>{let newContent={...content};return newContent.parts&&=newContent.parts.map(part=>{if(part&&typeof part==`object`&&`thoughtSignature`in part){let newPart={...part};return delete newPart.thoughtSignature,newPart}return part}),newContent})}setTools(tools$2){this.generationConfig.tools=tools$2}async maybeIncludeSchemaDepthContext(error$3){if(isSchemaDepthError(error$3.message)||isInvalidArgumentError(error$3.message)){let tools$2=this.config.getToolRegistry().getAllTools(),cyclicSchemaTools=[];for(let tool$1 of tools$2)(tool$1.schema.parametersJsonSchema&&hasCycleInSchema(tool$1.schema.parametersJsonSchema)||tool$1.schema.parameters&&hasCycleInSchema(tool$1.schema.parameters))&&cyclicSchemaTools.push(tool$1.displayName);if(cyclicSchemaTools.length>0){let extraDetails=`
|
|
1743
|
+
3. **Waiting for User:** If your last response completed a thought, statement, or task *and* does not meet the criteria for Rule 1 (Model Continues) or Rule 2 (Question to User), it implies a pause expecting user input or reaction. In this case, the **'user'** should speak next.`}]}];try{let parsedResponse=await geminiClient.generateJson(contents,RESPONSE_SCHEMA,abortSignal,DEFAULT_GEMINI_FLASH_MODEL);return parsedResponse&&parsedResponse.next_speaker&&[`user`,`model`].includes(parsedResponse.next_speaker)?parsedResponse:null}catch(error$3){return console.warn(`Failed to talk to Gemini endpoint when seeing if conversation should continue.`,error$3),null}}var import_levenshtein=__toESM(__commonJSMin(((exports,module)=>{(function(){var collator;try{collator=typeof Intl<`u`&&Intl.Collator!==void 0?Intl.Collator(`generic`,{sensitivity:`base`}):null}catch{console.log(`Collator could not be initialized and wouldn't be used`)}var prevRow=[],str2Char=[],Levenshtein={get:function(str1,str2,options$1){var useCollator=options$1&&collator&&options$1.useCollator,str1Len=str1.length,str2Len=str2.length;if(str1Len===0)return str2Len;if(str2Len===0)return str1Len;var curCol,nextCol,i$7,j$2,tmp;for(i$7=0;i$7<str2Len;++i$7)prevRow[i$7]=i$7,str2Char[i$7]=str2.charCodeAt(i$7);prevRow[str2Len]=str2Len;var strCmp;if(useCollator)for(i$7=0;i$7<str1Len;++i$7){for(nextCol=i$7+1,j$2=0;j$2<str2Len;++j$2)curCol=nextCol,strCmp=collator.compare(str1.charAt(i$7),String.fromCharCode(str2Char[j$2]))===0,nextCol=prevRow[j$2]+(strCmp?0:1),tmp=curCol+1,nextCol>tmp&&(nextCol=tmp),tmp=prevRow[j$2+1]+1,nextCol>tmp&&(nextCol=tmp),prevRow[j$2]=curCol;prevRow[j$2]=nextCol}else for(i$7=0;i$7<str1Len;++i$7){for(nextCol=i$7+1,j$2=0;j$2<str2Len;++j$2)curCol=nextCol,strCmp=str1.charCodeAt(i$7)===str2Char[j$2],nextCol=prevRow[j$2]+(strCmp?0:1),tmp=curCol+1,nextCol>tmp&&(nextCol=tmp),tmp=prevRow[j$2+1]+1,nextCol>tmp&&(nextCol=tmp),prevRow[j$2]=curCol;prevRow[j$2]=nextCol}return nextCol}};typeof define<`u`&&define!==null&&define.amd?define(function(){return Levenshtein}):module!=null&&exports!==void 0&&module.exports===exports?module.exports=Levenshtein:typeof self<`u`&&typeof self.postMessage==`function`&&typeof self.importScripts==`function`?self.Levenshtein=Levenshtein:typeof window<`u`&&window!==null&&(window.Levenshtein=Levenshtein)})()}))(),1),ChatRecordingService=class{conversationFile=null;cachedLastConvData=null;sessionId;projectHash;queuedThoughts=[];queuedTokens=null;config;constructor(config){this.config=config,this.sessionId=config.getSessionId(),this.projectHash=getProjectHash(config.getProjectRoot())}initialize(resumedSessionData){try{if(resumedSessionData)this.conversationFile=resumedSessionData.filePath,this.sessionId=resumedSessionData.conversation.sessionId,this.updateConversation(conversation=>{conversation.sessionId=this.sessionId}),this.cachedLastConvData=null;else{let chatsDir=path.join(this.config.storage.getProjectTempDir(),`chats`);fs.mkdirSync(chatsDir,{recursive:!0});let filename=`session-${new Date().toISOString().slice(0,16).replace(/:/g,`-`)}-${this.sessionId.slice(0,8)}.json`;this.conversationFile=path.join(chatsDir,filename),this.writeConversation({sessionId:this.sessionId,projectHash:this.projectHash,startTime:new Date().toISOString(),lastUpdated:new Date().toISOString(),messages:[]})}this.queuedThoughts=[],this.queuedTokens=null}catch(error$3){throw console.error(`Error initializing chat recording service:`,error$3),error$3}}getLastMessage(conversation){return conversation.messages.at(-1)}newMessage(type,content){return{id:randomUUID$1(),timestamp:new Date().toISOString(),type,content}}recordMessage(message){if(this.conversationFile)try{this.updateConversation(conversation=>{let msg=this.newMessage(message.type,message.content);msg.type===`gemini`?(conversation.messages.push({...msg,thoughts:this.queuedThoughts,tokens:this.queuedTokens,model:this.config.getModel()}),this.queuedThoughts=[],this.queuedTokens=null):conversation.messages.push(msg)})}catch(error$3){throw console.error(`Error saving message:`,error$3),error$3}}recordThought(thought){if(this.conversationFile)try{this.queuedThoughts.push({...thought,timestamp:new Date().toISOString()})}catch(error$3){throw console.error(`Error saving thought:`,error$3),error$3}}recordMessageTokens(respUsageMetadata){if(this.conversationFile)try{let tokens={input:respUsageMetadata.promptTokenCount??0,output:respUsageMetadata.candidatesTokenCount??0,cached:respUsageMetadata.cachedContentTokenCount??0,thoughts:respUsageMetadata.thoughtsTokenCount??0,tool:respUsageMetadata.toolUsePromptTokenCount??0,total:respUsageMetadata.totalTokenCount??0};this.updateConversation(conversation=>{let lastMsg=this.getLastMessage(conversation);lastMsg&&lastMsg.type===`gemini`&&!lastMsg.tokens?(lastMsg.tokens=tokens,this.queuedTokens=null):this.queuedTokens=tokens})}catch(error$3){throw console.error(`Error updating message tokens:`,error$3),error$3}}recordToolCalls(toolCalls){if(!this.conversationFile)return;let toolRegistry=this.config.getToolRegistry(),enrichedToolCalls=toolCalls.map(toolCall=>{let toolInstance=toolRegistry.getTool(toolCall.name);return{...toolCall,displayName:toolInstance?.displayName||toolCall.name,description:toolInstance?.description||``,renderOutputAsMarkdown:toolInstance?.isOutputMarkdown||!1}});try{this.updateConversation(conversation=>{let lastMsg=this.getLastMessage(conversation);if(!lastMsg||lastMsg.type!==`gemini`||this.queuedThoughts.length>0){let newMsg={...this.newMessage(`gemini`,``),type:`gemini`,toolCalls:enrichedToolCalls,thoughts:this.queuedThoughts,model:this.config.getModel()};this.queuedThoughts.length>0&&(newMsg.thoughts=this.queuedThoughts,this.queuedThoughts=[]),this.queuedTokens&&=(newMsg.tokens=this.queuedTokens,null),conversation.messages.push(newMsg)}else{lastMsg.toolCalls||=[],lastMsg.toolCalls=lastMsg.toolCalls.map(toolCall=>{let incomingToolCall=toolCalls.find(tc=>tc.id===toolCall.id);return incomingToolCall?{...toolCall,...incomingToolCall}:toolCall});for(let toolCall of enrichedToolCalls)lastMsg.toolCalls.find(tc=>tc.id===toolCall.id)||lastMsg.toolCalls.push(toolCall)}})}catch(error$3){throw console.error(`Error adding tool call to message:`,error$3),error$3}}readConversation(){try{return this.cachedLastConvData=fs.readFileSync(this.conversationFile,`utf8`),JSON.parse(this.cachedLastConvData)}catch(error$3){if(error$3.code!==`ENOENT`)throw console.error(`Error reading conversation file:`,error$3),error$3;return{sessionId:this.sessionId,projectHash:this.projectHash,startTime:new Date().toISOString(),lastUpdated:new Date().toISOString(),messages:[]}}}writeConversation(conversation){try{if(!this.conversationFile||conversation.messages.length===0)return;if(this.cachedLastConvData!==JSON.stringify(conversation,null,2)){conversation.lastUpdated=new Date().toISOString();let newContent=JSON.stringify(conversation,null,2);this.cachedLastConvData=newContent,fs.writeFileSync(this.conversationFile,newContent)}}catch(error$3){throw console.error(`Error writing conversation file:`,error$3),error$3}}updateConversation(updateFn){let conversation=this.readConversation();updateFn(conversation),this.writeConversation(conversation)}deleteSession(sessionId$1){try{let chatsDir=path.join(this.config.storage.getProjectTempDir(),`chats`),sessionPath=path.join(chatsDir,`${sessionId$1}.json`);fs.unlinkSync(sessionPath)}catch(error$3){throw console.error(`Error deleting session:`,error$3),error$3}}};init_esm$9();
|
|
1744
|
+
/**
|
|
1745
|
+
* @license
|
|
1746
|
+
* Copyright 2025 Google LLC
|
|
1747
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
1748
|
+
*/
|
|
1749
|
+
var TelemetryTarget;(function(TelemetryTarget$1){TelemetryTarget$1.GCP=`gcp`,TelemetryTarget$1.LOCAL=`local`})(TelemetryTarget||={});const DEFAULT_TELEMETRY_TARGET=TelemetryTarget.LOCAL,DEFAULT_OTLP_ENDPOINT=`http://localhost:4317`;async function handleFallback(config,failedModel,authType,error$3){if(authType!==AuthType.LOGIN_WITH_GOOGLE)return null;let fallbackModel=DEFAULT_GEMINI_FLASH_MODEL;if(failedModel===fallbackModel)return null;let fallbackModelHandler=config.fallbackModelHandler;if(typeof fallbackModelHandler!=`function`)return null;try{let intent=await fallbackModelHandler(failedModel,fallbackModel,error$3);switch(intent){case`retry`:return activateFallbackMode(config,authType),!0;case`stop`:return activateFallbackMode(config,authType),!1;case`auth`:return!1;default:throw Error(`Unexpected fallback intent received from fallbackModelHandler: "${intent}"`)}}catch(handlerError){return console.error(`Fallback UI handler failed:`,handlerError),null}}function activateFallbackMode(config,authType){config.isInFallbackMode()||(config.setFallbackMode(!0),authType&&logFlashFallback(config,new FlashFallbackEvent(authType)))}function partListUnionToString(value){return partToString(value,{verbose:!0})}var StreamEventType;(function(StreamEventType$1){StreamEventType$1.CHUNK=`chunk`,StreamEventType$1.RETRY=`retry`})(StreamEventType||={});const INVALID_CONTENT_RETRY_OPTIONS={maxAttempts:3,initialDelayMs:500};function isValidResponse(response){if(response.candidates===void 0||response.candidates.length===0)return!1;let content=response.candidates[0]?.content;return content===void 0?!1:isValidContent(content)}function isValidContent(content){if(content.parts===void 0||content.parts.length===0)return!1;for(let part of content.parts)if(part===void 0||Object.keys(part).length===0||!part.thought&&part.text!==void 0&&part.text===``)return!1;return!0}function validateHistory(history){for(let content of history)if(content.role!==`user`&&content.role!==`model`)throw Error(`Role must be user or model, but got ${content.role}.`)}function extractCuratedHistory(comprehensiveHistory){if(comprehensiveHistory===void 0||comprehensiveHistory.length===0)return[];let curatedHistory=[],length=comprehensiveHistory.length,i$7=0;for(;i$7<length;)if(comprehensiveHistory[i$7].role===`user`)curatedHistory.push(comprehensiveHistory[i$7]),i$7++;else{let modelOutput=[],isValid=!0;for(;i$7<length&&comprehensiveHistory[i$7].role===`model`;)modelOutput.push(comprehensiveHistory[i$7]),isValid&&!isValidContent(comprehensiveHistory[i$7])&&(isValid=!1),i$7++;isValid&&curatedHistory.push(...modelOutput)}return curatedHistory}var EmptyStreamError=class extends Error{constructor(message){super(message),this.name=`EmptyStreamError`}},GeminiChat=class{config;generationConfig;history;sendPromise=Promise.resolve();chatRecordingService;constructor(config,generationConfig={},history=[]){this.config=config,this.generationConfig=generationConfig,this.history=history,validateHistory(history),this.chatRecordingService=new ChatRecordingService(config),this.chatRecordingService.initialize()}setSystemInstruction(sysInstr){this.generationConfig.systemInstruction=sysInstr}async sendMessageStream(params,prompt_id){await this.sendPromise;let streamDoneResolver;this.sendPromise=new Promise(resolve$11=>{streamDoneResolver=resolve$11});let userContent=createUserContent(params.message);if(!isFunctionResponse(userContent)){let userMessage=Array.isArray(params.message)?params.message:[params.message],userMessageContent=partListUnionToString(toParts(userMessage));this.chatRecordingService.recordMessage({type:`user`,content:userMessageContent})}this.history.push(userContent);let requestContents=this.getHistory(!0),self$1=this;return(async function*(){try{let lastError=Error(`Request failed after all retries.`);for(let attempt=0;attempt<INVALID_CONTENT_RETRY_OPTIONS.maxAttempts;attempt++)try{attempt>0&&(yield{type:StreamEventType.RETRY});let stream$8=await self$1.makeApiCallAndProcessStream(requestContents,params,prompt_id,userContent);for await(let chunk$1 of stream$8)yield{type:StreamEventType.CHUNK,value:chunk$1};lastError=null;break}catch(error$3){if(lastError=error$3,error$3 instanceof EmptyStreamError&&attempt<INVALID_CONTENT_RETRY_OPTIONS.maxAttempts-1){logContentRetry(self$1.config,new ContentRetryEvent(attempt,`EmptyStreamError`,INVALID_CONTENT_RETRY_OPTIONS.initialDelayMs)),await new Promise(res=>setTimeout(res,INVALID_CONTENT_RETRY_OPTIONS.initialDelayMs*(attempt+1)));continue}break}if(lastError)throw lastError instanceof EmptyStreamError&&logContentRetryFailure(self$1.config,new ContentRetryFailureEvent(INVALID_CONTENT_RETRY_OPTIONS.maxAttempts,`EmptyStreamError`)),self$1.history[self$1.history.length-1]===userContent&&self$1.history.pop(),lastError}finally{streamDoneResolver()}})()}async makeApiCallAndProcessStream(requestContents,params,prompt_id,userContent){let currentAttemptModel,streamResponse=await retryWithBackoff(()=>{let modelToUse=this.config.isInFallbackMode()?DEFAULT_GEMINI_FLASH_MODEL:this.config.getModel();if(currentAttemptModel=modelToUse,this.config.getQuotaErrorOccurred()&&modelToUse===DEFAULT_GEMINI_FLASH_MODEL)throw Error(`Please submit a new query to continue with the Flash model.`);return this.config.getContentGenerator().generateContentStream({model:modelToUse,contents:requestContents,config:{...this.generationConfig,...params.config}},prompt_id)},{shouldRetry:error$3=>{if(error$3 instanceof Error&&error$3.message){if(isSchemaDepthError(error$3.message))return!1;if(error$3.message.includes(`429`)||error$3.message.match(/5\d{2}/))return!0}return!1},onPersistent429:async(authType,error$3)=>currentAttemptModel?await handleFallback(this.config,currentAttemptModel,authType,error$3):null,authType:this.config.getContentGeneratorConfig()?.authType});return this.processStreamResponse(streamResponse,userContent)}getHistory(curated=!1){let history=curated?extractCuratedHistory(this.history):this.history;return structuredClone(history)}clearHistory(){this.history=[]}addHistory(content){this.history.push(content)}setHistory(history){this.history=history}stripThoughtsFromHistory(){this.history=this.history.map(content=>{let newContent={...content};return newContent.parts&&=newContent.parts.map(part=>{if(part&&typeof part==`object`&&`thoughtSignature`in part){let newPart={...part};return delete newPart.thoughtSignature,newPart}return part}),newContent})}setTools(tools$2){this.generationConfig.tools=tools$2}async maybeIncludeSchemaDepthContext(error$3){if(isSchemaDepthError(error$3.message)||isInvalidArgumentError(error$3.message)){let tools$2=this.config.getToolRegistry().getAllTools(),cyclicSchemaTools=[];for(let tool$1 of tools$2)(tool$1.schema.parametersJsonSchema&&hasCycleInSchema(tool$1.schema.parametersJsonSchema)||tool$1.schema.parameters&&hasCycleInSchema(tool$1.schema.parameters))&&cyclicSchemaTools.push(tool$1.displayName);if(cyclicSchemaTools.length>0){let extraDetails=`
|
|
1744
1750
|
|
|
1745
1751
|
This error was probably caused by cyclic schema references in one of the following tools, try disabling them with excludeTools:
|
|
1746
1752
|
|
package/dist/cli/index.js
CHANGED
|
@@ -17,9 +17,9 @@ Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._life
|
|
|
17
17
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
18
18
|
- ${r}`;throw Error(i)}_executeSubCommand(e,t){t=t.slice();let n=!1,s=[`.js`,`.ts`,`.tsx`,`.mjs`,`.cjs`];function c(e,t){let n=i.resolve(e,t);if(a.existsSync(n))return n;if(s.includes(i.extname(t)))return;let r=s.find(e=>a.existsSync(`${n}${e}`));if(r)return`${n}${r}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let u=e._executableFile||`${this._name}-${e._name}`,d=this._executableDir||``;if(this._scriptPath){let e;try{e=a.realpathSync(this._scriptPath)}catch{e=this._scriptPath}d=i.resolve(i.dirname(e),d)}if(d){let t=c(d,u);if(!t&&!e._executableFile&&this._scriptPath){let n=i.basename(this._scriptPath,i.extname(this._scriptPath));n!==this._name&&(t=c(d,`${n}-${e._name}`))}u=t||u}n=s.includes(i.extname(u));let f;o.platform===`win32`?(this._checkForMissingExecutable(u,d,e._name),t.unshift(u),t=g(o.execArgv).concat(t),f=r.spawn(o.execPath,t,{stdio:`inherit`})):n?(t.unshift(u),t=g(o.execArgv).concat(t),f=r.spawn(o.argv[0],t,{stdio:`inherit`})):f=r.spawn(u,t,{stdio:`inherit`}),f.killed||[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`].forEach(e=>{o.on(e,()=>{f.killed===!1&&f.exitCode===null&&f.kill(e)})});let p=this._exitCallback;f.on(`close`,e=>{e??=1,p?p(new l(e,`commander.executeSubCommandAsync`,`(close)`)):o.exit(e)}),f.on(`error`,t=>{if(t.code===`ENOENT`)this._checkForMissingExecutable(u,d,e._name);else if(t.code===`EACCES`)throw Error(`'${u}' not executable`);if(!p)o.exit(1);else{let e=new l(1,`commander.executeSubCommandAsync`,`(error)`);e.nestedError=t,p(e)}}),this.runningCommand=f}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);r||this.help({error:!0}),r._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,r,`preSubcommand`),i=this._chainOrCall(i,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??`--help`])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(e,t,n)=>{let r=t;if(t!==null&&e.parseArg){let i=`error: command-argument value '${t}' is invalid for argument '${e.name()}'.`;r=this._callParseArg(e,t,n,i)}return r};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let i=n.defaultValue;n.variadic?r<this.args.length?(i=this.args.slice(r),n.parseArg&&(i=i.reduce((t,r)=>e(n,r,t),n.defaultValue))):i===void 0&&(i=[]):r<this.args.length&&(i=this.args[r],n.parseArg&&(i=e(n,i,n.defaultValue))),t[r]=i}),this.processedArgs=t}_chainOrCall(e,t){return e?.then&&typeof e.then==`function`?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,r=[];return this._getCommandAndAncestors().reverse().filter(e=>e._lifeCycleHooks[t]!==void 0).forEach(e=>{e._lifeCycleHooks[t].forEach(t=>{r.push({hookedCommand:e,callback:t})})}),t===`postAction`&&r.reverse(),r.forEach(e=>{n=this._chainOrCall(n,()=>e.callback(e.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(e=>{r=this._chainOrCall(r,()=>e(this,t))}),r}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let n;return n=this._chainOrCallHooks(n,`preAction`),n=this._chainOrCall(n,()=>this._actionHandler(this.processedArgs)),this.parent&&(n=this._chainOrCall(n,()=>{this.parent.emit(i,e,t)})),n=this._chainOrCallHooks(n,`postAction`),n}if(this.parent?.listenerCount(i))r(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand(`*`))return this._dispatchSubcommand(`*`,e,t);this.listenerCount(`command:*`)?this.emit(`command:*`,e,t):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(e=>{let t=e.attributeName();return this.getOptionValue(t)===void 0?!1:this.getOptionValueSource(t)!==`default`});e.filter(e=>e.conflictsWith.length>0).forEach(t=>{let n=e.find(e=>t.conflictsWith.includes(e.attributeName()));n&&this._conflictingOption(t,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t;function i(e){return e.length>1&&e[0]===`-`}let a=e=>/^-\d*\.?\d+(e[+-]?\d+)?$/.test(e)?!this._getCommandAndAncestors().some(e=>e.options.map(e=>e.short).some(e=>/^-\d$/.test(e))):!1,o=null,s=null,c=0;for(;c<e.length||s;){let l=s??e[c++];if(s=null,l===`--`){r===n&&r.push(l),r.push(...e.slice(c));break}if(o&&(!i(l)||a(l))){this.emit(`option:${o.name()}`,l);continue}if(o=null,i(l)){let t=this._findOption(l);if(t){if(t.required){let n=e[c++];n===void 0&&this.optionMissingArgument(t),this.emit(`option:${t.name()}`,n)}else if(t.optional){let n=null;c<e.length&&(!i(e[c])||a(e[c]))&&(n=e[c++]),this.emit(`option:${t.name()}`,n)}else this.emit(`option:${t.name()}`);o=t.variadic?t:null;continue}}if(l.length>2&&l[0]===`-`&&l[1]!==`-`){let e=this._findOption(`-${l[1]}`);if(e){e.required||e.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${e.name()}`,l.slice(2)):(this.emit(`option:${e.name()}`),s=`-${l.slice(2)}`);continue}}if(/^--[^=]+=/.test(l)){let e=l.indexOf(`=`),t=this._findOption(l.slice(0,e));if(t&&(t.required||t.optional)){this.emit(`option:${t.name()}`,l.slice(e+1));continue}}if(r===t&&i(l)&&!(this.commands.length===0&&a(l))&&(r=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),n.push(...e.slice(c));break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l,...e.slice(c));break}else if(this._defaultCommandName){n.push(l,...e.slice(c));break}}if(this._passThroughOptions){r.push(l,...e.slice(c));break}r.push(l)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let t=this.options[n].attributeName();e[t]=t===this._versionOptionName?this._version:this[t]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}\n`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==`string`?this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
19
19
|
`),this.outputHelp({error:!0}));let n=t||{},r=n.exitCode||1,i=n.code||`commander.error`;this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in o.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||[`default`,`config`,`env`].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,o.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new p(this.options),t=e=>this.getOptionValue(e)!==void 0&&![`default`,`implied`].includes(this.getOptionValueSource(e));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(e=>{Object.keys(e.implied).filter(e=>!t(e)).forEach(t=>{this.setOptionValueWithSource(t,e.implied[t],`implied`)})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:`commander.missingArgument`})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:`commander.optionMissingArgument`})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:`commander.missingMandatoryOptionValue`})}_conflictingOption(e,t){let n=e=>{let t=e.attributeName(),n=this.getOptionValue(t),r=this.options.find(e=>e.negate&&t===e.attributeName()),i=this.options.find(e=>!e.negate&&t===e.attributeName());return r&&(r.presetArg===void 0&&n===!1||r.presetArg!==void 0&&n===r.presetArg)?r:i||e},r=e=>{let t=n(e),r=t.attributeName();return this.getOptionValueSource(r)===`env`?`environment variable '${t.envVar}'`:`option '${t.flags}'`},i=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(i,{code:`commander.conflictingOption`})}unknownOption(e){if(this._allowUnknownOption)return;let t=``;if(e.startsWith(`--`)&&this._showSuggestionAfterError){let n=[],r=this;do{let e=r.createHelp().visibleOptions(r).filter(e=>e.long).map(e=>e.long);n=n.concat(e),r=r.parent}while(r&&!r._enablePositionalOptions);t=m(e,n)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:`commander.unknownOption`})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?``:`s`,r=`error: too many arguments${this.parent?` for '${this.name()}'`:``}. Expected ${t} argument${n} but got ${e.length}.`;this.error(r,{code:`commander.excessArguments`})}unknownCommand(){let e=this.args[0],t=``;if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(e=>{n.push(e.name()),e.alias()&&n.push(e.alias())}),t=m(e,n)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:`commander.unknownCommand`})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t||=`-V, --version`,n||=`output the version number`;let r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on(`option:`+r.name(),()=>{this._outputConfiguration.writeOut(`${e}\n`),this._exit(0,`commander.version`,e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw Error(`Command alias can't be the same as its name`);let n=this.parent?._findCommand(e);if(n){let t=[n.name()].concat(n.aliases()).join(`|`);throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${t}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(e=>this.alias(e)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(e=>c(e));return[].concat(this.options.length||this._helpOption!==null?`[options]`:[],this.commands.length?`[command]`:[],this.registeredArguments.length?e:[]).join(` `)}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??``:(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??``:(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??``:(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=i.basename(e,i.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let r=t.formatHelp(this,t);return n.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(e){e||={};let t=!!e.error,n,r,i;return t?(n=e=>this._outputConfiguration.writeErr(e),r=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(n=e=>this._outputConfiguration.writeOut(e),r=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:t,write:e=>(r||(e=this._outputConfiguration.stripColor(e)),n(e)),hasColors:r,helpWidth:i}}outputHelp(e){let t;typeof e==`function`&&(t=e,e=void 0);let n=this._getOutputContext(e),r={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(e=>e.emit(`beforeAllHelp`,r)),this.emit(`beforeHelp`,r);let i=this.helpInformation({error:n.error});if(t&&(i=t(i),typeof i!=`string`&&!Buffer.isBuffer(i)))throw Error(`outputHelp callback must return a string or a Buffer`);n.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit(`afterHelp`,r),this._getCommandAndAncestors().forEach(e=>e.emit(`afterAllHelp`,r))}helpOption(e,t){return typeof e==`boolean`?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??`-h, --help`,t??`display help for command`),(e||t)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(o.exitCode??0);t===0&&e&&typeof e!=`function`&&e.error&&(t=1),this._exit(t,`commander.help`,`(outputHelp)`)}addHelpText(e,t){let n=[`beforeAll`,`before`,`after`,`afterAll`];if(!n.includes(e))throw Error(`Unexpected value for position to addHelpText.
|
|
20
|
-
Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function g(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function _(){if(o.env.NO_COLOR||o.env.FORCE_COLOR===`0`||o.env.FORCE_COLOR===`false`)return!1;if(o.env.FORCE_COLOR||o.env.CLICOLOR_FORCE!==void 0)return!0}e.Command=h,e.useColor=_}));const{program:M,createCommand:N,createArgument:oe,createOption:se,CommanderError:ce,InvalidArgumentError:P,InvalidOptionArgumentError:le,Command:ue,Argument:F,Option:de,Help:I}=n(e((e=>{let{Argument:t}=O(),{Command:n}=ae(),{CommanderError:r,InvalidArgumentError:i}=D(),{Help:a}=k(),{Option:o}=A();e.program=new n,e.createCommand=e=>new n(e),e.createOption=(e,t)=>new o(e,t),e.createArgument=(e,n)=>new t(e,n),e.Command=n,e.Option=o,e.Argument=t,e.Help=a,e.CommanderError=r,e.InvalidArgumentError=i,e.InvalidOptionArgumentError=i}))(),1).default;var L=`1.1.
|
|
20
|
+
Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function g(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function _(){if(o.env.NO_COLOR||o.env.FORCE_COLOR===`0`||o.env.FORCE_COLOR===`false`)return!1;if(o.env.FORCE_COLOR||o.env.CLICOLOR_FORCE!==void 0)return!0}e.Command=h,e.useColor=_}));const{program:M,createCommand:N,createArgument:oe,createOption:se,CommanderError:ce,InvalidArgumentError:P,InvalidOptionArgumentError:le,Command:ue,Argument:F,Option:de,Help:I}=n(e((e=>{let{Argument:t}=O(),{Command:n}=ae(),{CommanderError:r,InvalidArgumentError:i}=D(),{Help:a}=k(),{Option:o}=A();e.program=new n,e.createCommand=e=>new n(e),e.createOption=(e,t)=>new o(e,t),e.createArgument=(e,n)=>new t(e,n),e.Command=n,e.Option=o,e.Argument=t,e.Help=a,e.CommanderError=r,e.InvalidArgumentError=i,e.InvalidOptionArgumentError=i}))(),1).default;var L=`1.1.32`;async function R(e){e||=process.cwd();let t=s(e);await t.build({cwd:e,entry:t.entry,outdir:t.outdir,watch:!1,onStart:()=>{console.log(`Building agent...`)},onResult:e=>{`error`in e&&(console.error(e.error),process.exit(1));for(let t of e.warnings)console.warn(t.message);console.log(`Built agent to ${e.entry}`)}})}var z=n(o(),1),B=n(g(),1);async function V(e,t){e||=process.cwd();let n=process.env.CI===`true`||!process.stdout.isTTY;await a(e);let r=await m(),o=new c({authToken:r,fetch:(e,t)=>{let n=new Headers(t?.headers);return n.set(`x-blink-cli-version`,L),fetch(e,{...t,headers:n})}}),l=await i(e,`package.json`);if(!l)throw Error(`package.json not found`);let g=await T(l,`utf-8`),v=JSON.parse(g),y=te(l),C=x(y,`.blink`,`config.json`),D={};if(ne(C)){let e=await T(C,`utf-8`);D=JSON.parse(e)}process.env.BLINK_ORGANIZATION_ID&&(D.organizationId=process.env.BLINK_ORGANIZATION_ID),process.env.BLINK_AGENT_ID&&(D.agentId=process.env.BLINK_AGENT_ID);let O;if(D?.organizationId)try{O=(await o.organizations.get(D.organizationId)).name}catch{D.organizationId=void 0}if(!D?.organizationId){let e=await o.organizations.list();if(e.length===1)D.organizationId=e[0].id,O=e[0].name;else if(n)throw Error(`Multiple organizations found. To use CI mode, please deploy in interactive mode first to select an organization and generate .blink/config.json`);else{let t=await f({message:`Which organization should contain this agent?`,options:e.map(e=>({value:e.id,label:e.name}))});if(d(t))return;D.organizationId=t,O=e.find(e=>e.id===t).name,console.log()}}let k,A=!1,j=!1;if(D?.agentId)try{k=(await o.agents.get(D.agentId)).name}catch{D.agentId=void 0}if(!D?.agentId)try{let e=await o.organizations.agents.get({organization_id:D.organizationId,agent_name:v.name});D.agentId=e.id,k=e.name}catch{A=!0,k=v.name}A?console.log(h.bold(`blink■`)+` creating agent `+O+`/`+k):console.log(h.bold(`blink■`)+` deploying agent `+O+`/`+k);let ae=Date.now(),M=s(y),N=await new Promise((e,t)=>{M.build({cwd:y,entry:M.entry,outdir:M.outdir,watch:!1,onStart:()=>{},onResult:t=>{e(t)}}).catch(t)});if(!N)throw Error(`Failed to build agent`);if(`error`in N)throw Error(N.error.message);let oe=Date.now()-ae;console.log(h.gray(`Built ${h.dim(`(${oe}ms)`)}`));let se=await w(N.outdir),ce=Object.fromEntries(se.map(e=>[x(N.outdir,e),e])),P=x(e,`README.md`);await H(P)&&(ce[P]=`README.md`);let le=await me(y),ue=Object.fromEntries(le.map(e=>[e,S(y,e)])),F=Object.entries(ce),de=Object.entries(ue),I=[...F,...de],R=I.length,z=0,B=0,V=0,K=Array(R);await pe(I,10,async([e,t],n)=>{let r=(await E(e)).size,i=++z;G(`${h.dim(`[${i}/${R}]`)} Uploading ${t} (${W(r)})...`);let a=await T(e),s=await o.files.upload(new File([Buffer.from(a)],t));K[n]={path:t,id:s.id},B+=1,V+=r}),G(h.gray(`Uploaded ${R} ${R===1?`file`:`files`} ${h.dim(`(${W(V)})`)}`)),process.stdout.write(`
|
|
21
21
|
`);let q=K.filter(Boolean),he=q.slice(0,F.length),ge=q.slice(F.length),J=await U(x(e,`.env.production`));if(A){let t=x(e,`.env.local`),r=x(e,`.env.production`),i=await U(t),a=Object.keys(i).filter(e=>!J[e]);if(a.length>0)if(n)console.log(h.yellow(`Warning:`)+` Missing ${a.length} var${a.length===1?``:`s`} in .env.production: ${a.join(`, `)}`),console.log(h.dim(` Skipping in CI mode. Set these in .env.production if needed.`));else{console.log(`
|
|
22
22
|
`+h.cyan(`Environment Variables`)),console.log(h.dim(` Missing ${a.length} var${a.length===1?``:`s`} in .env.production: ${a.join(`, `)}`));let e=await p({message:`Copy missing vars from .env.local to .env.production?`,initialValue:!0});if(d(e))return;if(console.log(),e){for(let e of a)J[e]=i[e];await re(r,`# Environment variables for production deployment\n${Object.entries(J).map(([e,t])=>`${e}=${t}`).join(`
|
|
23
23
|
`)}`,`utf-8`)}}let o=_(e);if(o)if(n)console.log(h.dim(` Skipping webhook tunnel migration in CI mode`));else{let e=`https://${o}.blink.host`;console.log(`
|
|
24
24
|
`+h.cyan(`Webhook Tunnel`)),console.log(h.dim(` Current: ${e} → local dev`)),console.log(h.dim(` After: ${e} → production`)),console.log(h.dim(` Migrating will keep your webhooks working in production`));let t=await p({message:`Migrate tunnel to production?`});if(d(t))return;console.log(),t&&(j=!0)}}let Y=Object.entries(J);if(A){let t=_(e),n=await o.agents.create({name:v.name,organization_id:D.organizationId,request_id:j?t:void 0,entrypoint:b(N.entry),output_files:he,source_files:ge,env:Y.map(([e,t])=>({key:e,value:t,target:[`production`,`preview`],secret:!0}))});D.agentId=n.id,k=n.name;let r=`https://blink.so/${O}/${k}`;console.log(h.gray(`Agent created ${h.dim(r)}`))}else if(Y.length>0){let e=0;for(let[t,n]of Y)await o.agents.env.create({agent_id:D.agentId,key:t,value:n,target:[`production`,`preview`],secret:!0,upsert:!0}),G(`${h.dim(`[${++e}/${Y.length}]`)} Updating environment variable: ${t} ${h.dim(`(.env.production)`)}`);G(h.gray(`Updated ${Y.length} environment ${Y.length===1?`variable`:`variables`} ${h.dim(`(.env.production)`)}`)),process.stdout.write(`
|
|
25
|
-
`)}let X=await U(x(e,`.env.local`)),Z=Object.keys(X).filter(e=>!Object.keys(J).includes(e));if(Z.length>0)if(n){console.log(h.yellow(`Warning:`)+` The following environment variables are set in .env.local but not in .env.production:`);for(let e of Z)console.log(`- ${e}`);console.log(h.dim(` Continuing deployment in CI mode`))}else{console.log(`Warning: The following environment variables are set in .env.local but not in .env.production:`);for(let e of Z)console.log(`- ${e}`);let e=await p({message:`Do you want to deploy anyway?`});if(e===!1||d(e))return}let _e=A?(await o.agents.deployments.list({agent_id:D.agentId})).items[0]:await o.agents.deployments.create({agent_id:D.agentId,target:`production`,entrypoint:b(N.entry),output_files:he,source_files:ge,message:t?.message}),Q=`https://blink.so/${O}/${k}/deployments/${_e.number}`;console.log(h.gray(`View Deployment ${h.dim(Q)}`)),n||await fe(C,D);let $=u();$.start(`Waiting for deployment to be live...`);try{for(;;){let t=await o.agents.deployments.get({agent_id:D.agentId,deployment_id:_e.id});if(t.status===`success`){$.stop(),A?(console.log(`Your agent is live.`),console.log(h.dim(Q))):(console.log(`Deployed. All new chats will use this version.`),console.log(h.dim(Q))),j&&(ee(e),console.log(h.yellow(`Note:`)+` To continue developing locally with webhooks, you'll need to reconfigure external services (Slack, GitHub, etc.)`),Object.keys(X).some(e=>e.toLowerCase().includes(`slack`))&&console.log(`Run ${h.cyan(`blink setup slack-app`)} to create a new Slack app for development.`));break}if(t.status===`failed`){$.stop(`Failed`+(t.error_message?`: ${t.error_message}`:``)),console.log(),console.log(`Logs: `+h.dim(Q));return}await new Promise(e=>setTimeout(e,500))}}catch(e){$.stop(`Failed to poll deployment status`),console.log(),console.log(`Error: `+ie(e)),console.log(`Logs: `+h.dim(Q))}}const H=async e=>{try{return await E(e),!0}catch{return!1}};async function U(e){return await H(e)?(0,z.parse)(await T(e,`utf-8`)):{}}async function fe(e,t){await C(te(e),{recursive:!0}),await re(e,JSON.stringify({_:`This file can be source controlled. It contains no secrets.`,...t},null,2),`utf-8`)}async function pe(e,t,n){let r=Array(e.length),i=0,a=Array(Math.min(t,e.length)).fill(0).map(async()=>{for(;;){let t=i++;if(t>=e.length)break;r[t]=await n(e[t],t)}});return await Promise.all(a),r}function W(e){if(e===0)return`0B`;let t=1024,n=[`B`,`KB`,`MB`,`GB`,`TB`],r=Math.floor(Math.log(e)/Math.log(t)),i=e/t**+r;return`${i.toFixed(i>=100?0:i>=10?1:2)}${n[r]}`}function G(e){if(process.stdout.isTTY)try{process.stdout.clearLine(0),process.stdout.cursorTo(0),process.stdout.write(e);return}catch{}console.log(e)}async function me(e){let t=[],n=(0,B.default)().add([`.git`,`node_modules`,`.blink`,`.env`,`.env.*`]),r=x(e,`.gitignore`);if(await H(r)){let e=await T(r,`utf-8`);n.add(e)}async function i(r,a=e){let o=await w(r,{withFileTypes:!0});for(let e of o){let o=x(r,e.name),s=S(a,o);n.ignores(s)||(e.isDirectory()?await i(o,a):e.isFile()&&t.push(o))}}return await i(e),t}if(globalThis.WebSocket||(globalThis.WebSocket=r.default),globalThis.Bun!==void 0){let e=t(`perf_hooks`);e.monitorEventLoopDelay=()=>({enable:()=>{}})}globalThis.crypto||(globalThis.crypto={}),globalThis.crypto.randomUUID||(globalThis.crypto.randomUUID=()=>y()),M.name(`blink`).description(`Blink is a runtime for building and deploying AI agents.`).version(L).action(()=>{M.outputHelp()});const K=e=>async(...t)=>{let{default:n}=await e();return n(...t)};M.command(`init [directory]`).description(`Initialize a new Blink agent.`).action(K(()=>import(`./init-DXBledyD.js`))),M.command(`dev [directory] [options]`).description(`Start a development server for your agent.`).action(K(()=>import(`./dev-
|
|
25
|
+
`)}let X=await U(x(e,`.env.local`)),Z=Object.keys(X).filter(e=>!Object.keys(J).includes(e));if(Z.length>0)if(n){console.log(h.yellow(`Warning:`)+` The following environment variables are set in .env.local but not in .env.production:`);for(let e of Z)console.log(`- ${e}`);console.log(h.dim(` Continuing deployment in CI mode`))}else{console.log(`Warning: The following environment variables are set in .env.local but not in .env.production:`);for(let e of Z)console.log(`- ${e}`);let e=await p({message:`Do you want to deploy anyway?`});if(e===!1||d(e))return}let _e=A?(await o.agents.deployments.list({agent_id:D.agentId})).items[0]:await o.agents.deployments.create({agent_id:D.agentId,target:`production`,entrypoint:b(N.entry),output_files:he,source_files:ge,message:t?.message}),Q=`https://blink.so/${O}/${k}/deployments/${_e.number}`;console.log(h.gray(`View Deployment ${h.dim(Q)}`)),n||await fe(C,D);let $=u();$.start(`Waiting for deployment to be live...`);try{for(;;){let t=await o.agents.deployments.get({agent_id:D.agentId,deployment_id:_e.id});if(t.status===`success`){$.stop(),A?(console.log(`Your agent is live.`),console.log(h.dim(Q))):(console.log(`Deployed. All new chats will use this version.`),console.log(h.dim(Q))),j&&(ee(e),console.log(h.yellow(`Note:`)+` To continue developing locally with webhooks, you'll need to reconfigure external services (Slack, GitHub, etc.)`),Object.keys(X).some(e=>e.toLowerCase().includes(`slack`))&&console.log(`Run ${h.cyan(`blink setup slack-app`)} to create a new Slack app for development.`));break}if(t.status===`failed`){$.stop(`Failed`+(t.error_message?`: ${t.error_message}`:``)),console.log(),console.log(`Logs: `+h.dim(Q));return}await new Promise(e=>setTimeout(e,500))}}catch(e){$.stop(`Failed to poll deployment status`),console.log(),console.log(`Error: `+ie(e)),console.log(`Logs: `+h.dim(Q))}}const H=async e=>{try{return await E(e),!0}catch{return!1}};async function U(e){return await H(e)?(0,z.parse)(await T(e,`utf-8`)):{}}async function fe(e,t){await C(te(e),{recursive:!0}),await re(e,JSON.stringify({_:`This file can be source controlled. It contains no secrets.`,...t},null,2),`utf-8`)}async function pe(e,t,n){let r=Array(e.length),i=0,a=Array(Math.min(t,e.length)).fill(0).map(async()=>{for(;;){let t=i++;if(t>=e.length)break;r[t]=await n(e[t],t)}});return await Promise.all(a),r}function W(e){if(e===0)return`0B`;let t=1024,n=[`B`,`KB`,`MB`,`GB`,`TB`],r=Math.floor(Math.log(e)/Math.log(t)),i=e/t**+r;return`${i.toFixed(i>=100?0:i>=10?1:2)}${n[r]}`}function G(e){if(process.stdout.isTTY)try{process.stdout.clearLine(0),process.stdout.cursorTo(0),process.stdout.write(e);return}catch{}console.log(e)}async function me(e){let t=[],n=(0,B.default)().add([`.git`,`node_modules`,`.blink`,`.env`,`.env.*`]),r=x(e,`.gitignore`);if(await H(r)){let e=await T(r,`utf-8`);n.add(e)}async function i(r,a=e){let o=await w(r,{withFileTypes:!0});for(let e of o){let o=x(r,e.name),s=S(a,o);n.ignores(s)||(e.isDirectory()?await i(o,a):e.isFile()&&t.push(o))}}return await i(e),t}if(globalThis.WebSocket||(globalThis.WebSocket=r.default),globalThis.Bun!==void 0){let e=t(`perf_hooks`);e.monitorEventLoopDelay=()=>({enable:()=>{}})}globalThis.crypto||(globalThis.crypto={}),globalThis.crypto.randomUUID||(globalThis.crypto.randomUUID=()=>y()),M.name(`blink`).description(`Blink is a runtime for building and deploying AI agents.`).version(L).action(()=>{M.outputHelp()});const K=e=>async(...t)=>{let{default:n}=await e();return n(...t)};M.command(`init [directory]`).description(`Initialize a new Blink agent.`).action(K(()=>import(`./init-DXBledyD.js`))),M.command(`dev [directory] [options]`).description(`Start a development server for your agent.`).action(K(()=>import(`./dev-1VmtF950.js`))),M.command(`deploy [directory]`).description(`Deploy your agent to the Blink Cloud.`).option(`-m, --message <message>`,`Message for this deployment`).action(V),M.command(`build [directory]`).description(`Build your agent for production.`).action(R),M.command(`setup`).description(`Set up integrations for your agent.`).command(`slack-app [directory]`).description(`Set up Slack app integration`).action(v),M.command(`telemetry [boolean]`).description(`Enable or disable telemetry.`),M.command(`start [directory]`).description("Starts the Blink runtime in production mode. The agent must be compiled with `blink build` first."),M.command(`run <message...>`).description(`Run your agent programmatically and get the response.`).option(`-d, --directory <directory>`,`Directory to run the agent from (default: current directory)`).option(`-c, --chat <chat>`,`Chat key to use (default: 'default')`).action(K(()=>import(`./run-CRrWbMEw.js`))),M.command(`connect`,{hidden:!0}).description(`Connect compute to the Blink Cloud.`).action(K(()=>import(`./connect-CgLoRyDv.js`))),M.command(`chat`,{hidden:!0}).description(`Start a Blink chat connected to your machine.`).action(K(()=>import(`./chat-C_rQ9SRr.js`))),M.command(`login`).description(`Log in to the Blink Cloud.`).action(K(()=>import(`./login-POW3H6LQ.js`))),M.command(`compute`).description(`Compute-related commands.`).command(`server`).description(`Run a compute protocol server on localhost.`).action(K(()=>import(`./compute-server-BDrjNQ0q.js`))),M.configureOutput({writeErr:e=>{let t=e.replace(/\x1b\[[0-9;]*m/g,``);l.error(t.trim())}}),process.on(`unhandledRejection`,e=>{l.error(e?.message||String(e)),process.exit(1)}),M.parse(process.argv);export{};
|
|
@@ -141,12 +141,12 @@ ${Dm}${t.trimStart()}`),n=3+(0,l.stripVTControlCharacters)(t.trimStart()).length
|
|
|
141
141
|
`),m(),i()};return{start:v,stop:y,message:(e=``)=>{s=g(e??s)}}},Am=async(e,t)=>{let n={},r=Object.keys(e);for(let i of r){let r=e[i],a=await r({results:n})?.catch(e=>{throw e});if(typeof t?.onCancel==`function`&&up(a)){n[i]=`canceled`,t.onCancel({results:n});continue}n[i]=a}return n},jm=async e=>{for(let t of e){if(t.enabled===!1)continue;let e=km();e.start(t.title);let n=await t.task(e.message);e.stop(n||t.title)}};let Mm;function Nm(){try{return o.default.statSync(`/.dockerenv`),!0}catch{return!1}}function Pm(){try{return o.default.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function Fm(){return Mm===void 0&&(Mm=Nm()||Pm()),Mm}let Im;const Lm=()=>{try{return o.default.statSync(`/run/.containerenv`),!0}catch{return!1}};function Rm(){return Im===void 0&&(Im=Lm()||Fm()),Im}const zm=()=>{if(x.default.platform!==`linux`)return!1;if(S.default.release().toLowerCase().includes(`microsoft`))return!Rm();try{return o.default.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!Rm():!1}catch{return!1}};var Bm=x.default.env.__IS_WSL_TEST__?zm:zm();const Vm=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await E.default.access(n,E.constants.F_OK),r=!0}catch{}if(!r)return e;let i=await E.default.readFile(n,{encoding:`utf8`}),a=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(i);return a?(t=a.groups.mountPoint.trim(),t=t.endsWith(`/`)?t:`${t}/`,t):e}})(),Hm=async()=>`${await Vm()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Um=async()=>Bm?Hm():`${x.default.env.SYSTEMROOT||x.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function Wm(e,t,n){let r=n=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0});return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){let e=n();return r(e),e},set(e){r(e)}}),e}const Gm=(0,l.promisify)(T.execFile);async function Km(){if(x.default.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await Gm(`defaults`,[`read`,`com.apple.LaunchServices/com.apple.launchservices.secure`,`LSHandlers`]);return/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??`com.apple.Safari`}const qm=(0,l.promisify)(T.execFile);async function Jm(e,{humanReadableOutput:t=!0,signal:n}={}){if(x.default.platform!==`darwin`)throw Error(`macOS only`);let r=t?[]:[`-ss`],i={};n&&(i.signal=n);let{stdout:a}=await qm(`osascript`,[`-e`,e,r],i);return a.trim()}async function Ym(e){return Jm(`tell application "Finder" to set app_path to application file id "${e}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}const Xm=(0,l.promisify)(T.execFile),Zm={AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:`Edge`,id:`com.microsoft.edge.old`},MSEdgeDHTML:{name:`Edge`,id:`com.microsoft.edge`},MSEdgeHTM:{name:`Edge`,id:`com.microsoft.edge`},"IE.HTTP":{name:`Internet Explorer`,id:`com.microsoft.ie`},FirefoxURL:{name:`Firefox`,id:`org.mozilla.firefox`},ChromeHTML:{name:`Chrome`,id:`com.google.chrome`},BraveHTML:{name:`Brave`,id:`com.brave.Browser`},BraveBHTML:{name:`Brave Beta`,id:`com.brave.Browser.beta`},BraveSSHTM:{name:`Brave Nightly`,id:`com.brave.Browser.nightly`}};var Qm=class extends Error{};async function $m(e=Xm){let{stdout:t}=await e(`reg`,[`QUERY`,` HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice`,`/v`,`ProgId`]),n=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(t);if(!n)throw new Qm(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=Zm[r];if(!i)throw new Qm(`Unknown browser ID: ${r}`);return i}const eh=(0,l.promisify)(T.execFile),th=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function nh(){if(x.default.platform===`darwin`){let e=await Km();return{name:await Ym(e),id:e}}if(x.default.platform===`linux`){let{stdout:e}=await eh(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:th(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(x.default.platform===`win32`)return $m();throw Error(`Only macOS, Linux, and Windows are supported`)}const rh=(0,l.promisify)(T.default.execFile),ih=b.default.dirname((0,s.fileURLToPath)(require(`url`).pathToFileURL(__filename).href)),ah=b.default.join(ih,`xdg-open`),{platform:oh,arch:sh}=x.default;async function ch(){let e=await Um(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=a.Buffer.from(t,`utf16le`).toString(`base64`),{stdout:r}=await rh(e,[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,n],{encoding:`utf8`}),i=r.trim(),o={ChromeHTML:`com.google.chrome`,BraveHTML:`com.brave.Browser`,MSEdgeHTM:`com.microsoft.edge`,FirefoxURL:`org.mozilla.firefox`};return o[i]?{id:o[i]}:{}}const lh=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},uh=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return lh(e.app,t=>uh({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return lh(t,t=>uh({...e,app:{name:t,arguments:n}}));if(t===`browser`||t===`browserPrivate`){let r={"com.google.chrome":`chrome`,"google-chrome.desktop":`chrome`,"com.brave.Browser":`brave`,"org.mozilla.firefox":`firefox`,"firefox.desktop":`firefox`,"com.microsoft.msedge":`edge`,"com.microsoft.edge":`edge`,"com.microsoft.edgemac":`edge`,"microsoft-edge.desktop":`edge`},i={chrome:`--incognito`,brave:`--incognito`,firefox:`--private-window`,edge:`--inPrivate`},a=Bm?await ch():await nh();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),uh({...e,app:{name:mh[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,i=[],o={};if(oh===`darwin`)r=`open`,e.wait&&i.push(`--wait-apps`),e.background&&i.push(`--background`),e.newInstance&&i.push(`--new`),t&&i.push(`-a`,t);else if(oh===`win32`||Bm&&!Rm()&&!t){r=await Um(),i.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),Bm||(o.windowsVerbatimArguments=!0);let s=[`Start`];e.wait&&s.push(`-Wait`),t?(s.push(`"\`"${t}\`""`),e.target&&n.push(e.target)):e.target&&s.push(`"${e.target}"`),n.length>0&&(n=n.map(e=>`"\`"${e}\`""`),s.push(`-ArgumentList`,n.join(`,`))),e.target=a.Buffer.from(s.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!ih||ih===`/`,t=!1;try{await E.default.access(ah,E.constants.X_OK),t=!0}catch{}r=x.default.versions.electron??(oh===`android`||e||!t)?`xdg-open`:ah}n.length>0&&i.push(...n),e.wait||(o.stdio=`ignore`,o.detached=!0)}oh===`darwin`&&n.length>0&&i.push(`--args`,...n),e.target&&i.push(e.target);let s=T.default.spawn(r,i,o);return e.wait?new Promise((t,n)=>{s.once(`error`,n),s.once(`close`,r=>{if(!e.allowNonzeroExitCode&&r>0){n(Error(`Exited with code ${r}`));return}t(s)})}):(s.unref(),s)},dh=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return uh({...t,target:e})};function fh(e){if(typeof e==`string`||Array.isArray(e))return e;let{[sh]:t}=e;if(!t)throw Error(`${sh} is not supported`);return t}function ph({[oh]:e},{wsl:t}){if(t&&Bm)return fh(t);if(!e)throw Error(`${oh} is not supported`);return fh(e)}const mh={};Wm(mh,`chrome`,()=>ph({darwin:`google chrome`,win32:`chrome`,linux:[`google-chrome`,`google-chrome-stable`,`chromium`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`,x64:[`/mnt/c/Program Files/Google/Chrome/Application/chrome.exe`,`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`]}})),Wm(mh,`brave`,()=>ph({darwin:`brave browser`,win32:`brave`,linux:[`brave-browser`,`brave`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`,x64:[`/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe`,`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`]}})),Wm(mh,`firefox`,()=>ph({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),Wm(mh,`edge`,()=>ph({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),Wm(mh,`browser`,()=>`browser`),Wm(mh,`browserPrivate`,()=>`browserPrivate`);var hh=dh;async function gh(e,t=void 0){try{(await hh(e)).once(`error`,n=>{console.log(Sf.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))})}catch{console.log(Sf.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))}}function _h(e){let t=e||bh();if((0,o.existsSync)(t)){let e=(0,o.readFileSync)(t,`utf8`);return JSON.parse(e).token}}function vh(e,t){let n=t||bh();(0,o.existsSync)((0,b.dirname)(n))||(0,o.mkdirSync)((0,b.dirname)(n),{recursive:!0}),(0,o.writeFileSync)(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function yh(e){let t=e||bh();(0,o.existsSync)(t)&&(0,o.unlinkSync)(t)}function bh(){let e=Fd(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return(0,b.join)(e[0],`auth.json`)}function xh(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=(0,_.useState)(),[s,c]=(0,_.useState)(()=>_h(i)),[l,u]=(0,_.useState)(),d=(0,_.useRef)(n),f=(0,_.useRef)(r);(0,_.useEffect)(()=>{d.current=n,f.current=r},[n,r]);let p=(0,_.useCallback)(async()=>{u(void 0);try{let e=_h(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new hd({baseURL:`https://blink.so`});t.authToken=e;let n={email:(await t.users.me()).email};o(n),d.current?.(n)}catch(e){o(void 0),u(e instanceof Error?e.message:String(e)),d.current?.(void 0)}},[i]),m=(0,_.useCallback)(async()=>{u(void 0);try{let e=new hd,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();vh(t,i),c(t);let r={email:n.email};return o(r),d.current?.(r),r}catch(e){let t=e instanceof Error?e.message:String(e);throw u(t),e}},[i]),h=(0,_.useCallback)(()=>{yh(i),c(void 0),o(void 0),u(void 0),d.current?.(void 0)},[i]);return(0,_.useEffect)(()=>{t&&p()},[t,p]),{user:a,token:s,error:l,login:m,logout:h}}let Sh=Promise.resolve();var Ch=class{constructor(e){this.printLog=e}setPrintLog(e){this.printLog=e}error(e,...t){Sh=Sh.then(()=>this.printLog(`error`,e,...t).catch(e=>{console.error(`Error printing log:`,e)}))}log(e,...t){Sh=Sh.then(()=>this.printLog(`log`,e,...t).catch(e=>{console.error(`Error printing log:`,e)}))}flush(){return Sh}};const wh=(0,_.createContext)(void 0);function Th(e){let{directory:t,logger:r,onBuildStart:i,onBuildSuccess:a,onBuildError:o}=typeof e==`string`?{directory:e,logger:new Ch(async()=>{})}:e,s=(0,_.useMemo)(()=>n.resolveConfig(t),[t]),[c,l]=(0,_.useState)(void 0),[u,d]=(0,_.useState)(void 0),[f,p]=(0,_.useState)(`building`),m=(0,_.useRef)(i),h=(0,_.useRef)(a),g=(0,_.useRef)(o);return(0,_.useEffect)(()=>{m.current=i,h.current=a,g.current=o},[i,a,o]),(0,_.useEffect)(()=>{let e=new AbortController;return s.build({cwd:t,entry:s.entry,outdir:s.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{p(`building`),l(void 0),d(void 0),m.current?.()},onResult:e=>{`error`in e?(l(e.error),p(`error`),g.current?.(e.error)):(d(e),p(`success`),h.current?.(e))}}).catch(e=>{r.error(`system`,`error`,e),p(`error`),l(e),g.current?.(e)}),()=>{e.abort()}},[t]),(0,_.useMemo)(()=>({error:c,status:f,result:u,entry:s.entry,outdir:s.outdir}),[c,f,u,s.entry,s.outdir])}function Eh(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function Dh(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const Oh=100,kh=/^\.+(\\|\/)|^\.+$/,Ah=/[. ]+$/,jh=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,Mh=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,Nh=e=>e===``,Ph=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,Fh=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let Ih;function Lh(){return Ih??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),Ih}function Rh(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(Eh().test(n)||[...n].some(e=>Mh.test(e)&&!Nh(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(Fh,` `),n.length>0&&(e=e.replaceAll(Ph,`$1`)),e=e.replace(Ah,``),e=e.replace(kh,n),e=e.replace(Eh(),n),e=e.replaceAll(jh,e=>Nh(e)?e:n),e.length===0&&(e=n),e=Dh().test(e)?e+n:e;let r=typeof t.maxLength==`number`?t.maxLength:100;if(e.length>r){let t=e.lastIndexOf(`.`);if(t===-1)e=zh(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=zh(n,a)+i}}return e}function zh(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of Lh().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function Bh(e){return`${e}.lock`}function Vh(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function Hh(e,t={}){let n=Bh(e),r=process.pid.toString();try{return o.writeFileSync(n,r,{flag:`wx`}),!0}catch(r){if(r.code!==`EEXIST`)throw r;if(t.stale===0)return!1;let i;try{i=parseInt(o.readFileSync(n,`utf8`),10)}catch{return o.unlinkSync(n),Hh(e,{...t,stale:0})}if(!Vh(i))try{return o.unlinkSync(n),Hh(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return Hh(e,{...t,stale:0});throw n}return!1}}async function Uh(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=b.resolve(e),i=0;for(;i<=n.retries;){if(Hh(r,n))return()=>Wh(r);i<n.retries&&await new Promise(e=>setTimeout(e,n.retryInterval)),i++}let a=Error(`Lock file is already being held`);throw a.code=`ELOCKED`,a.file=r,a}function Wh(e){let t=b.resolve(e),n=Bh(t);try{if(parseInt(o.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}o.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function Gh(e){let t=b.resolve(e),n=Bh(t);try{if(!o.existsSync(n))return{locked:!1};let e=o.readFileSync(n,`utf8`),t=parseInt(e,10);return Vh(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const Kh=e=>{o.mkdirSync(e,{recursive:!0})},qh=e=>{try{o.fdatasyncSync(e)}catch{}try{o.closeSync(e)}catch{}},Jh=e=>{try{let t=o.openSync(e,`r`);try{o.fsyncSync(t)}finally{o.closeSync(t)}}catch{}},Yh=(e,t)=>{let n=b.dirname(e);Kh(n);let r=b.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=o.openSync(r,`w`),o.writeFileSync(i,t,`utf-8`),qh(i),i=void 0,o.renameSync(r,e),Jh(e),Jh(n)}catch(e){if(i!==void 0)try{o.closeSync(i)}catch{}try{o.rmSync(r,{force:!0})}catch{}throw e}},Xh=(e,t)=>{let n=new Map,r,i=e=>{if(o.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(o.readFileSync(e,`utf-8`))},a=(e,t)=>{Yh(e,JSON.stringify(t,null,2))},s=async()=>{if(r)throw Error(`Index is already locked`);let t=b.join(e,`index.json`);Kh(e),o.existsSync(t)||o.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await Uh(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},c=async()=>{let t=b.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},l=async t=>{let n=b.join(e,`index.json`);a(n,t)},u=async t=>{let n=(await c()).ids[t];if(n)return b.join(e,n)},d=async t=>{let n=(await c()).ids[t];if(!n)return;let r=b.join(e,n);if(o.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(o.readFileSync(r,`utf-8`))},f=async n=>{let r=n[t],i=String(r),o=Rh(i,{replacement:`_`})+`.json`,u=await s();try{let t=await c();t.ids[i]=o,t.current=i;let r=b.join(e,o);a(r,n),await l(t)}finally{await u()}};return{async get(e){return await d(e)},async list(){if(!o.statSync(e,{throwIfNoEntry:!1}))return[];let t=await c(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=b.join(e,i),a=o.statSync(t,{throwIfNoEntry:!1});if(!a)continue;let s=Gh(t);n.push({key:r,locked:s.locked,pid:s.pid,mtime:a.mtimeMs})}return n.sort((e,t)=>t.mtime-e.mtime),n},async lock(r,i){if(n.has(r))throw Error(`Key "${r}" is already locked in this process`);let a=await u(r);if(!a){let t=Rh(r,{replacement:`_`})+`.json`,n=await s();try{let n=await c();n.ids[r]=t;let i=b.join(e,t);Kh(e),o.writeFileSync(i,JSON.stringify({}),`utf-8`),await l(n),a=i}finally{await n()}}if(i?.force){let e=Gh(a);if(e.locked&&e.pid&&e.pid!==process.pid)try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,100))}catch(t){t.code!==`ESRCH`&&console.warn(`Failed to kill process ${e.pid}:`,t.message)}}let p=await Uh(a,{stale:!0,retries:i?.force?10:5,retryInterval:(i?.force,100)});return n.set(r,()=>Promise.resolve(p())),{async get(){let e=await d(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await f(e)},async update(e){let n=await d(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await f({...n,...e})},async delete(){let t=await s();try{let t=await c(),n=t.ids[r];if(n){delete t.ids[r],t.current===r&&(t.current=void 0),await l(t);let i=b.join(e,n);try{o.rmSync(i,{force:!0}),Jh(e)}catch{}}}finally{await t()}},async release(){try{p()}finally{n.delete(r)}}}},dispose(){n.clear()}}},Zh=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,a,s,c=new Map,l=new Map,u=b.join(e,`index.json`),d=()=>{try{if(!o.statSync(u,{throwIfNoEntry:!1}))return{ids:{}};let e=o.readFileSync(u,`utf-8`);return{ids:JSON.parse(e).ids??{}}}catch{return{ids:{}}}},f=(e,t,n,r)=>{for(let a of i)try{a({key:e,value:t,locked:n,pid:r})}catch(e){console.error(`Error in onChange callback:`,e)}},p=(t,n,r=!1)=>{let i=b.join(e,n);try{let e=o.statSync(i,{throwIfNoEntry:!1}),a=l.get(n);if(!e){a&&(l.delete(n),f(t,void 0,!1));return}let s=e.mtimeMs,c=a?{locked:a.locked,pid:a.pid}:{locked:!1,pid:void 0};if((r||!a)&&(c=Gh(i)),!a||a.mtime!==s||a.locked!==c.locked||a.pid!==c.pid){let e;e=!a||a.mtime!==s?JSON.parse(o.readFileSync(i,`utf-8`)):a.cachedValue,l.set(n,{mtime:s,key:t,locked:c.locked,pid:c.pid,cachedValue:e}),f(t,e,c.locked,c.pid)}}catch{}},m=()=>{try{let e=d(),t=new Set(Object.keys(e.ids));for(let[t,n]of Object.entries(e.ids))p(t,n,!0);for(let[e,n]of l.entries())t.has(n.key)||(l.delete(e),f(n.key,void 0,!1))}catch{}},h=(e,t,n=!1)=>{let i=c.get(e);i&&clearTimeout(i),c.set(e,setTimeout(()=>{c.delete(e),p(e,t,n)},r))},g=()=>{if(a)return;try{o.mkdirSync(e,{recursive:!0})}catch{}a=o.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){m();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=d(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&p(r,e,!0);return}let n=d(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&h(r,t,!1)});let t=()=>{m(),s=setTimeout(t,n)};m(),s=setTimeout(t,n)};return{onChange(e){return i.size===0&&g(),i.add(e),()=>{if(i.delete(e),i.size===0){a&&=(a.close(),void 0),s&&=(clearTimeout(s),void 0);for(let e of c.values())clearTimeout(e);c.clear(),l.clear()}}},dispose(){a&&=(a.close(),void 0),s&&=(clearTimeout(s),void 0);for(let e of c.values())clearTimeout(e);c.clear(),i.clear(),l.clear()}}};async function Qh({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=$h}){n=[...n];let a=new TransformStream,o=a.writable.getWriter(),s=async()=>{let a;try{let c=await t.chat({messages:n,id:e},{signal:r}),l=(0,m.readUIMessageStream)({message:{id:crypto.randomUUID(),role:`assistant`,parts:[],metadata:{}},stream:c,onError:e=>{e instanceof Error&&e.name===`AbortError`||o.abort(e)}});for await(let e of l)o.write(e),a=e;if(a&&i(a)){n.push(a),await s();return}await o.close()}catch(e){if(e?.name===`AbortError`||r?.aborted)return;await o.abort(e)}finally{await o.close()}};return s().catch(e=>{o.abort(e)}),a.readable}const $h=e=>{if(e.role!==`assistant`)return!1;let n=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),r=e.parts.slice(n+1).filter(m.isToolOrDynamicToolUIPart);return r.length===0||r.some(e=>t.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`)?!1:r.every(e=>e.state.startsWith(`output-`))},eg=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function tg(e){return typeof e==`object`&&e?.__blink_internal!==void 0}function ng(e){return typeof e.metadata==`object`&&e.metadata!==null&&`__blink_log`in e.metadata&&e.metadata.__blink_log===!0&&`level`in e.metadata&&`source`in e.metadata&&`message`in e.metadata}var rg=class{chatId;agent;chatStore;serializeMessage;filterMessages;onError;chat;loading=!1;streamingMessage;status=`idle`;queue=[];logQueue=[];abortController;isProcessingQueue=!1;listeners=new Set;watcher;disposed=!1;constructor(e){this.chatId=e.chatId??`00000000-0000-0000-0000-000000000000`,this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.loading=!0,this.chatStore=Xh(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.onError=e.onError,this.watcher=Zh(e.chatsDirectory,{pollInterval:1e3,debounce:50}),this.watcher.onChange(e=>{if(e.key!==this.chatId||this.isProcessingQueue)return;if(!e.value){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.status=`idle`,this.streamingMessage=void 0,this.notifyListeners();return}if(this.chat.updated_at===e.value?.updated_at)return;let t=e.value,n=e.locked?`streaming`:`idle`,r=this.chat.updated_at!==t?.updated_at||this.status!==n;this.chat=t,this.streamingMessage=void 0,this.status=n,r&&this.notifyListeners()}),this.chatStore.get(this.chatId).then(e=>{this.disposed||e&&(this.chat=e)}).catch(e=>{let t=e instanceof Error?e.message:String(e);this.onError?.(t)}).finally(()=>{this.loading=!1,this.notifyListeners()})}setAgent(e){this.agent=e}getState(){return{id:this.chatId,key:this.chat?.key,messages:(this.chat?.messages??[]).filter(e=>!tg(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,loading:this.loading,queuedMessages:this.queue,queuedLogs:this.logQueue}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async upsertMessages(e,t){let n=!1,r;t?r=t:(r=await this.chatStore.lock(this.chatId),n=!0);try{let t=await r.get();(!t.id||!Array.isArray(t.messages))&&(t={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]});let n=[...t.messages];for(let t of e){let e;if(this.serializeMessage){let n=this.serializeMessage(t);if(n===void 0)return;e=n}else e={...t,created_at:new Date().toISOString(),mode:`run`,metadata:t.metadata,id:t.id??crypto.randomUUID()};let r=n.findIndex(t=>t.id===e.id);r===-1?n.push(e):n.splice(r,1,e)}this.chat={...t,updated_at:new Date().toISOString(),messages:n},await r.set(this.chat),this.notifyListeners()}finally{n&&await r.release()}}async deleteMessages(e){let t;try{t=await this.chatStore.lock(this.chatId);let n=await t.get();this.chat.messages=n.messages.filter(t=>!e.includes(t.id)),this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),this.notifyListeners()}finally{t&&await t.release()}}async queueLogMessage({message:e,level:t,source:n}){let r=`(EDIT MODE NOTE) ${n===`agent`?`The agent`:"The `blink dev` CLI"} printed the following ${t}:\n\`\`\`\n${(0,l.stripVTControlCharacters)(e)}\n\`\`\`\n`,i={id:crypto.randomUUID(),created_at:new Date().toISOString(),role:`user`,parts:[{type:`text`,text:r}],metadata:{__blink_log:!0,level:t,source:n,message:e},mode:`edit`};this.logQueue.push(i),this.notifyListeners()}async flushLogQueue(e){if(this.logQueue.length===0)return;let t=[...this.logQueue];this.logQueue=[],await this.upsertMessages(t,e)}async sendMessages(e){if(this.status=`idle`,this.notifyListeners(),this.isProcessingQueue){this.queue.push(...e),this.notifyListeners();return}this.queue=e,this.processQueueOrRun()}async start(){this.status=`idle`,this.notifyListeners(),this.processQueueOrRun()}async stop(){this.status=`idle`,this.abortController?.abort(),this.notifyListeners()}async processQueueOrRun(){if(!this.agent){this.onError?.(`The agent is not available. Please wait for the build to succeed.`),this.queue=[];return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0;let e;try{e=await this.chatStore.lock(this.chatId),await this.flushLogQueue(e);let n=!0;for(;this.queue.length>0||n;)try{var t=Xs();n=!1;let r=new AbortController;this.abortController=r;let i=[...this.queue];this.queue=[],this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),i.length>0&&await this.upsertMessages(i,e);let a=this.chat.messages;this.filterMessages&&(a=a.filter(this.filterMessages)),a=a.map(e=>({...e,parts:e.parts.map(e=>!(0,m.isToolOrDynamicToolUIPart)(e)||e.input!==``?e:{...e,input:{}})})),t.u(await this.agent.lock.read());let o=performance.now(),s=await Qh({agent:this.agent.client,id:this.chatId,signal:r.signal,messages:a}),c=async t=>{let n=t;if(this.serializeMessage){let e=this.serializeMessage(t);if(e===void 0)return;n=e}this.chat.updated_at=new Date().toISOString(),this.chat.messages.push(n),this.streamingMessage=void 0,await e?.set(this.chat)},l=s.getReader();r.signal.addEventListener(`abort`,()=>{l.cancel().catch(()=>{})},{once:!0});let u;try{for(;;){let{done:e,value:t}=await l.read();if(e||r.signal.aborted)break;u||=performance.now()-o,this.streamingMessage&&t.id!==this.streamingMessage.id&&await c(this.streamingMessage);let n={...t,metadata:{...typeof t.metadata==`object`&&t.metadata!==null?t.metadata:{},ttft:u}};this.streamingMessage=this.serializeMessage?this.serializeMessage(n):n,this.notifyListeners()}}finally{l.releaseLock()}this.streamingMessage&&await c(this.streamingMessage)}catch(e){t.e=e}finally{t.d()}}catch(e){let t=e instanceof Error?e.message:String(e);this.onError?.(t)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,this.status=`idle`,e&&(await this.flushLogQueue(e),this.chat.updated_at=new Date().toISOString(),await e.set(this.chat),await e.release(),this.notifyListeners())}}stopStreaming(){this.abortController?.abort()}clearQueue(){this.queue=[],this.notifyListeners()}async resetChat(){this.abortController?.abort(),this.resetChatState(),this.notifyListeners();let e;try{e=await this.chatStore.lock(this.chatId),await e.delete()}catch{}finally{if(e)try{await e.release()}catch{}}}dispose(){this.disposed=!0,this.watcher.dispose(),this.listeners.clear(),this.stopStreaming()}resetChatState(){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.streamingMessage=void 0,this.status=`idle`,this.queue=[],this.logQueue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};function ig(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a,onError:o}=e,s=(0,_.useRef)(null),[c,l]=(0,_.useState)({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[],queuedLogs:[]});(0,_.useEffect)(()=>{s.current&&s.current.dispose();let e=new rg({chatId:t,chatsDirectory:r,serializeMessage:i,filterMessages:a,onError:o}),n=e.subscribe(e=>{l(e)});return l(e.getState()),s.current=e,()=>{n(),e.dispose(),s.current=null}},[t,r]),(0,_.useEffect)(()=>{s.current&&s.current.setAgent(n)},[n]);let u=(0,_.useCallback)(async e=>{s.current&&await s.current.sendMessages([e])},[]),d=(0,_.useCallback)(async e=>{s.current&&await s.current.upsertMessages([e])},[]),f=(0,_.useCallback)(async e=>{s.current&&await s.current.queueLogMessage(e)},[]),p=(0,_.useCallback)(()=>{s.current&&s.current.stopStreaming()},[]),m=(0,_.useCallback)(async()=>{s.current&&await s.current.resetChat()},[]),h=(0,_.useCallback)(()=>{s.current&&s.current.clearQueue()},[]),g=(0,_.useCallback)(async e=>{s.current&&await s.current.deleteMessages([e])},[]),v=(0,_.useCallback)(async()=>{s.current&&await s.current.start()},[]);return{...c,sendMessage:u,upsertMessage:d,queueLogMessage:f,stopStreaming:p,resetChat:m,clearQueue:h,deleteMessage:g,start:v}}function ag(e){return(0,f.join)(e,`.blink`,`devhook.txt`)}function og(e){return(0,p.existsSync)(ag(e))}function sg(e){let t=ag(e);if((0,p.existsSync)(t))return(0,p.readFileSync)(t,`utf-8`).trim()}function cg(e){let t=ag(e);if((0,p.mkdirSync)((0,f.dirname)(t),{recursive:!0}),(0,p.existsSync)(t))return(0,p.readFileSync)(t,`utf-8`);let n=crypto.randomUUID();return(0,p.writeFileSync)(t,n),n}const lg=(e,t)=>e.json({error:t},400),ug=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}},dg=()=>new t.Hono,fg=dg().get(`/:key`,async e=>{let{key:t,err:n}=ug(e);if(n)return lg(e,n);let r=await e.env.store.get(t);return e.json({value:r},200)}).post(`/:key`,t.validator(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?lg(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:lg(t,`Value must be a string`):lg(t,`Value is required`)}),async e=>{let{key:t,err:n}=ug(e);if(n)return lg(e,n);let{value:r}=e.req.valid(`json`);return await e.env.store.set(t,r),e.body(null,204)}).delete(`/:key`,async e=>{let{key:t,err:n}=ug(e);return n?lg(e,n):(await e.env.store.delete(t),e.body(null,204))}).get(`/`,async e=>{let{cursor:t,limit:n,prefix:r}=e.req.query(),{entries:i,cursor:a}=await e.env.store.list(r,{cursor:t?String(t):void 0,limit:n?Number(n):100});return e.json({entries:i,cursor:a})}),pg=e=>{let t=e.req.param(`key`);return t?t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}:{key:t,err:`Key is required`}},mg=t.validator(`param`,e=>({id:e.id})),hg=dg().post(`/:key`,async e=>{let{key:t,err:n}=pg(e);return n?lg(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,mg,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,mg,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.getMessages(t),200)}).post(`/:id/sendMessages`,t.validator(`json`,e=>({id:e.id,messages:e.messages,options:e.options})),async e=>{let{id:t,messages:n,options:r}=e.req.valid(`json`);return t?(await e.env.chat.sendMessages(t,n,r),e.body(null,204)):lg(e,`ID is required`)}).delete(`/:id/messages`,mg,t.validator(`query`,e=>(typeof e.message==`string`&&(e.message=[e.message]),{messages:e.message})),async e=>{let{id:t}=e.req.valid(`param`),{messages:n}=e.req.valid(`query`);return await e.env.chat.deleteMessages(t,n),e.body(null,204)}).post(`/:id/start`,mg,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,mg,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,mg,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),gg=dg().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),_g=new t.Hono().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,fg).route(`/chat`,hg).route(`/otlp`,gg);var vg=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function yg(e){return typeof e==`string`&&vg.test(e)}var bg=yg;function xg(e){if(!bg(e))throw TypeError(`Invalid UUID`);let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,t&255,(t=parseInt(e.slice(9,13),16))>>>8,t&255,(t=parseInt(e.slice(14,18),16))>>>8,t&255,(t=parseInt(e.slice(19,23),16))>>>8,t&255,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255)}var Sg=xg;const $=[];for(let e=0;e<256;++e)$.push((e+256).toString(16).slice(1));function Cg(e,t=0){return($[e[t+0]]+$[e[t+1]]+$[e[t+2]]+$[e[t+3]]+`-`+$[e[t+4]]+$[e[t+5]]+`-`+$[e[t+6]]+$[e[t+7]]+`-`+$[e[t+8]]+$[e[t+9]]+`-`+$[e[t+10]]+$[e[t+11]]+$[e[t+12]]+$[e[t+13]]+$[e[t+14]]+$[e[t+15]]).toLowerCase()}function wg(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t}const Tg=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,Eg=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;function Dg(e,t,n,r,i,a){let o=typeof n==`string`?wg(n):n,s=typeof r==`string`?Sg(r):r;if(typeof r==`string`&&(r=Sg(r)),r?.length!==16)throw TypeError(`Namespace must be array-like (16 iterable integer values, 0-255)`);let c=new Uint8Array(16+o.length);if(c.set(s),c.set(o,s.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,i){a||=0;for(let e=0;e<16;++e)i[a+e]=c[e];return i}return Cg(c)}function Og(e){return Array.isArray(e)?e=Buffer.from(e):typeof e==`string`&&(e=Buffer.from(e,`utf8`)),(0,u.createHash)(`sha1`).update(e).digest()}var kg=Og;function Ag(e,t,n,r){return Dg(80,kg,e,t,n,r)}Ag.DNS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,Ag.URL=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;var jg=Ag;function Mg(e){let n=(0,b.join)(e.dataDirectory,`chats`),r={},i=(0,b.join)(e.dataDirectory,`storage.json`);o.existsSync(i)&&(r=JSON.parse(o.readFileSync(i,`utf-8`)));let a=new Map,s=t=>{let r=a.get(t);return r||(r=new rg({chatId:t,chatsDirectory:n}),a.set(t,r)),r.setAgent(e.getAgent()),r},c={async upsert(e){let t=jg(JSON.stringify(e),jg.URL),n=s(t).getState(),r=n.messages.length===0&&!n.created_at;return{id:n.id,created:r,createdAt:n.created_at??new Date().toISOString(),key:e}},async get(e){let t=s(e).getState();return{id:t.id,createdAt:t.created_at??new Date().toISOString()}},async getMessages(e){return s(e).getState().messages},async sendMessages(e,t,n){let r=s(e),i=t.map(e=>eg(e,`run`));if(n?.behavior===`append`){await r.upsertMessages(i);return}if(n?.behavior===`interrupt`){await r.sendMessages(i);return}await r.sendMessages(i)},async deleteMessages(e,t){await s(e).deleteMessages(t)},async start(e){await s(e).start()},async stop(e){await s(e).stop()},async delete(e){await s(e).resetChat()}},l={get(e){return Promise.resolve(r[e])},set(e,t){return r[e]=t,o.writeFileSync(i,JSON.stringify(r),`utf-8`),Promise.resolve()},delete(e){return delete r[e],o.writeFileSync(i,JSON.stringify(r),`utf-8`),Promise.resolve()},list(e,t){let n=Math.min(t?.limit??100,1e3),i=t?.cursor,a=Object.keys(r).filter(t=>t.startsWith(e??``)).sort(),o=0;if(i){let e=a.indexOf(i);e!==-1&&(o=e+1)}let s=a.slice(o,o+n),c=o+n<a.length?s[s.length-1]:void 0;return Promise.resolve({entries:s.map(e=>({key:e})),cursor:c})}},u=(0,d.createServer)(t.createServerAdapter(e=>_g.fetch(e,{chat:c,store:l})));u.listen(e.port??0);let f=Xh(n,`id`);return{url:`http://127.0.0.1:${u.address().port}`,chatsDirectory:n,getChatManager:s,listChats:()=>f.list(),dispose:()=>{for(let e of a.values())e.dispose();a.clear(),f.dispose(),u.close()}}}function Ng({agent:e,capabilities:n,messages:r}){let[i,a]=(0,_.useState)(void 0),[o,s]=(0,_.useState)(!0),[c,l]=(0,_.useState)(void 0),u=(0,_.useRef)(c);(0,_.useEffect)(()=>{u.current=c},[c]);let[d,f]=(0,_.useState)(()=>t.lastUIOptions(r));(0,_.useEffect)(()=>{f(e=>{let n=t.lastUIOptions(r);return JSON.stringify(n)===JSON.stringify(e)?e:n})},[r]);let[p,m]=(0,_.useState)(void 0),h=(0,_.useCallback)((e,t)=>{if(!u.current)return!1;let n=u.current[e];return n?n.values.some(e=>e.id===t):!1},[]),g=(0,_.useCallback)(e=>{m(t=>{let n={...d,...t,...e};for(let[e,t]of Object.entries(n))h(e,t)||delete n[e];for(let[e,t]of Object.entries(u.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[d,h]);(0,_.useEffect)(()=>{if(!d&&!c){m(void 0);return}g()},[d,c,g]);let v=(0,_.useRef)(void 0),y=(0,_.useRef)(void 0);(0,_.useEffect)(()=>{e!==y.current&&(y.current=e,l(void 0),m(void 0),a(void 0),s(!0),v.current=void 0)},[e]),(0,_.useEffect)(()=>{if(n&&!n.ui||!e){l(void 0),m(void 0),a(void 0),v.current=void 0;return}let t=p?JSON.stringify(p):``;if(v.current===t){s(!1),a(void 0);return}let r=new AbortController;return s(!0),a(void 0),e.ui(p?{selectedOptions:p}:{},{signal:r.signal}).then(e=>{if(!e){l(void 0);return}r.signal.aborted||(l(t=>JSON.stringify(t)===JSON.stringify(e)?t:e),v.current=t)}).catch(e=>{r.signal.aborted||a(e instanceof Error?e:Error(String(e)))}).finally(()=>{s(!1)}),()=>{r.abort()}},[e,n,p]);let b=(0,_.useCallback)((e,t)=>{g({[e]:t})},[g]);return{schema:c,options:p,setOption:b,loading:o,error:i}}function Pg(e){let t=(0,_.useRef)(e.onRequest);(0,_.useEffect)(()=>{t.current=e.onRequest},[e.onRequest]);let[n,r]=(0,_.useState)(`disconnected`);return(0,_.useEffect)(()=>{if(e.disabled||!e.id){r(`disconnected`);return}let n=!1,i,a,o=!1,s,c=(0,b.join)(e.directory,`.blink`,`devhook`);return(async()=>{try{s=await Uh(c,{stale:!0,retries:0})}catch(t){if(t&&typeof t==`object`&&`code`in t&&t.code===`ELOCKED`){let e=``;try{let t=Gh(c);t.locked&&t.pid&&(e=` (PID: ${t.pid})`)}catch{}console.error(Sf.red(`\nError: Another ${Sf.bold(`blink dev`)} process is already running in this directory${e}.`)),console.error(Sf.red(`Please stop the other process and try again.
|
|
142
142
|
`)),process.exit(1)}let n=t&&typeof t==`object`&&`message`in t?String(t.message):String(t);e.logger.error(`system`,Sf.yellow(`\nWarning: Failed to acquire devhook lock: ${n}`)),e.logger.error(`system`,Sf.yellow(`Continuing without lock. Multiple ${Sf.bold(`blink dev`)} processes may conflict with each other.\n`))}let l=()=>{if(!(n||o)){if(o=!0,i){try{i.dispose()}catch{}i=void 0}i=new hd({baseURL:`https://blink.so`}).devhook.listen({id:e.id,onRequest:async e=>t.current(e),onConnect:()=>{o=!1,r(`connected`)},onDisconnect:()=>{o=!1,r(`disconnected`),!n&&!a&&(a=setTimeout(()=>{a=void 0,l()},2e3))},onError:e=>{o=!1,r(`error`),!n&&!a&&(a=setTimeout(()=>{a=void 0,l()},2e3))}})}};l()})(),()=>{if(n=!0,a&&=(clearTimeout(a),void 0),i){try{i.dispose()}catch{}i=void 0}if(s)try{s()}catch(t){e.logger.error(`system`,`Failed to release devhook lock:`,t)}}},[e.disabled,e.directory]),{id:e.id,url:e.id?`https://${e.id}.blink.host`:void 0,status:n}}var Fg=e.__commonJSMin(((e,t)=>{t.exports={name:`dotenv`,version:`17.2.3`,description:`Loads environment variables from .env file`,main:`lib/main.js`,types:`lib/main.d.ts`,exports:{".":{types:`./lib/main.d.ts`,require:`./lib/main.js`,default:`./lib/main.js`},"./config":`./config.js`,"./config.js":`./config.js`,"./lib/env-options":`./lib/env-options.js`,"./lib/env-options.js":`./lib/env-options.js`,"./lib/cli-options":`./lib/cli-options.js`,"./lib/cli-options.js":`./lib/cli-options.js`,"./package.json":`./package.json`},scripts:{"dts-check":`tsc --project tests/types/tsconfig.json`,lint:`standard`,pretest:`npm run lint && npm run dts-check`,test:`tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000`,"test:coverage":`tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov`,prerelease:`npm test`,release:`standard-version`},repository:{type:`git`,url:`git://github.com/motdotla/dotenv.git`},homepage:`https://github.com/motdotla/dotenv#readme`,funding:`https://dotenvx.com`,keywords:[`dotenv`,`env`,`.env`,`environment`,`variables`,`config`,`settings`],readmeFilename:`README.md`,license:`BSD-2-Clause`,devDependencies:{"@types/node":`^18.11.3`,decache:`^4.6.2`,sinon:`^14.0.1`,standard:`^17.0.0`,"standard-version":`^9.5.0`,tap:`^19.2.0`,typescript:`^4.8.4`},engines:{node:`>=12`},browser:{fs:!1}}})),Ig=e.__commonJSMin(((e,t)=>{let n=require(`fs`),r=require(`path`),i=require(`os`),a=require(`crypto`),o=Fg().version,s=[`🔐 encrypt with Dotenvx: https://dotenvx.com`,`🔐 prevent committing .env to code: https://dotenvx.com/precommit`,`🔐 prevent building .env in docker: https://dotenvx.com/prebuild`,`📡 add observability to secrets: https://dotenvx.com/ops`,`👥 sync secrets across teammates & machines: https://dotenvx.com/ops`,`🗂️ backup and recover secrets: https://dotenvx.com/ops`,`✅ audit secrets and track compliance: https://dotenvx.com/ops`,`🔄 add secrets lifecycle management: https://dotenvx.com/ops`,`🔑 add access controls to secrets: https://dotenvx.com/ops`,"🛠️ run anywhere with `dotenvx run -- yourcommand`",`⚙️ specify custom .env file path with { path: '/custom/path/.env' }`,`⚙️ enable debug logging with { debug: true }`,`⚙️ override existing env vars with { override: true }`,`⚙️ suppress all logs with { quiet: true }`,`⚙️ write to custom object with { processEnv: myObject }`,`⚙️ load multiple .env files with { path: ['.env.local', '.env'] }`];function c(){return s[Math.floor(Math.random()*s.length)]}function l(e){return typeof e==`string`?![`false`,`0`,`no`,`off`,``].includes(e.toLowerCase()):!!e}function u(){return process.stdout.isTTY}function d(e){return u()?`\x1b[2m${e}\x1b[0m`:e}let f=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function p(e){let t={},n=e.toString();n=n.replace(/\r\n?/gm,`
|
|
143
143
|
`);let r;for(;(r=f.exec(n))!=null;){let e=r[1],n=r[2]||``;n=n.trim();let i=n[0];n=n.replace(/^(['"`])([\s\S]*)\1$/gm,`$2`),i===`"`&&(n=n.replace(/\\n/g,`
|
|
144
|
-
`),n=n.replace(/\\r/g,`\r`)),t[e]=n}return t}function m(e){e||={};let t=b(e);e.path=t;let n=D.configDotenv(e);if(!n.parsed){let e=Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code=`MISSING_DATA`,e}let r=v(e).split(`,`),i=r.length,a;for(let e=0;e<i;e++)try{let t=r[e].trim(),i=y(n,t);a=D.decrypt(i.ciphertext,i.key);break}catch(t){if(e+1>=i)throw t}return D.parse(a)}function h(e){console.error(`[dotenv@${o}][WARN] ${e}`)}function g(e){console.log(`[dotenv@${o}][DEBUG] ${e}`)}function _(e){console.log(`[dotenv@${o}] ${e}`)}function v(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:``}function y(e,t){let n;try{n=new URL(t)}catch(e){if(e.code===`ERR_INVALID_URL`){let e=Error(`INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development`);throw e.code=`INVALID_DOTENV_KEY`,e}throw e}let r=n.password;if(!r){let e=Error(`INVALID_DOTENV_KEY: Missing key part`);throw e.code=`INVALID_DOTENV_KEY`,e}let i=n.searchParams.get(`environment`);if(!i){let e=Error(`INVALID_DOTENV_KEY: Missing environment part`);throw e.code=`INVALID_DOTENV_KEY`,e}let a=`DOTENV_VAULT_${i.toUpperCase()}`,o=e.parsed[a];if(!o){let e=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${a} in your .env.vault file.`);throw e.code=`NOT_FOUND_DOTENV_ENVIRONMENT`,e}return{ciphertext:o,key:r}}function b(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let r of e.path)n.existsSync(r)&&(t=r.endsWith(`.vault`)?r:`${r}.vault`);else t=e.path.endsWith(`.vault`)?e.path:`${e.path}.vault`;else t=r.resolve(process.cwd(),`.env.vault`);return n.existsSync(t)?t:null}function x(e){return e[0]===`~`?r.join(i.homedir(),e.slice(1)):e}function S(e){let t=l(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=l(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(t||!n)&&_(`Loading env from encrypted .env.vault`);let r=D._parseVault(e),i=process.env;return e&&e.processEnv!=null&&(i=e.processEnv),D.populate(i,r,e),{parsed:r}}function C(e){let t=r.resolve(process.cwd(),`.env`),i=`utf8`,a=process.env;e&&e.processEnv!=null&&(a=e.processEnv);let o=l(a.DOTENV_CONFIG_DEBUG||e&&e.debug),s=l(a.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?i=e.encoding:o&&g(`No encoding is specified. UTF-8 is used by default`);let u=[t];if(e&&e.path)if(!Array.isArray(e.path))u=[x(e.path)];else{u=[];for(let t of e.path)u.push(x(t))}let f,p={};for(let t of u)try{let r=D.parse(n.readFileSync(t,{encoding:i}));D.populate(p,r,e)}catch(e){o&&g(`Failed to load ${t} ${e.message}`),f=e}let m=D.populate(a,p,e);if(o=l(a.DOTENV_CONFIG_DEBUG||o),s=l(a.DOTENV_CONFIG_QUIET||s),o||!s){let e=Object.keys(m).length,t=[];for(let e of u)try{let n=r.relative(process.cwd(),e);t.push(n)}catch(t){o&&g(`Failed to load ${e} ${t.message}`),f=t}_(`injecting env (${e}) from ${t.join(`,`)} ${d(`-- tip: ${c()}`)}`)}return f?{parsed:p,error:f}:{parsed:p}}function w(e){if(v(e).length===0)return D.configDotenv(e);let t=b(e);return t?D._configVault(e):(h(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),D.configDotenv(e))}function T(e,t){let n=Buffer.from(t.slice(-64),`hex`),r=Buffer.from(e,`base64`),i=r.subarray(0,12),o=r.subarray(-16);r=r.subarray(12,-16);try{let e=a.createDecipheriv(`aes-256-gcm`,n,i);return e.setAuthTag(o),`${e.update(r)}${e.final()}`}catch(e){let t=e instanceof RangeError,n=e.message===`Invalid key length`,r=e.message===`Unsupported state or unable to authenticate data`;if(t||n){let e=Error(`INVALID_DOTENV_KEY: It must be 64 characters long (or more)`);throw e.code=`INVALID_DOTENV_KEY`,e}else if(r){let e=Error(`DECRYPTION_FAILED: Please check your DOTENV_KEY`);throw e.code=`DECRYPTION_FAILED`,e}else throw e}}function E(e,t,n={}){let r=!!(n&&n.debug),i=!!(n&&n.override),a={};if(typeof t!=`object`){let e=Error(`OBJECT_REQUIRED: Please check the processEnv argument being passed to populate`);throw e.code=`OBJECT_REQUIRED`,e}for(let n of Object.keys(t))Object.prototype.hasOwnProperty.call(e,n)?(i===!0&&(e[n]=t[n],a[n]=t[n]),r&&g(i===!0?`"${n}" is already defined and WAS overwritten`:`"${n}" is already defined and was NOT overwritten`)):(e[n]=t[n],a[n]=t[n]);return a}let D={configDotenv:C,_configVault:S,_parseVault:m,config:w,decrypt:T,parse:p,populate:E};t.exports.configDotenv=D.configDotenv,t.exports._configVault=D._configVault,t.exports._parseVault=D._parseVault,t.exports.config=D.config,t.exports.decrypt=D.decrypt,t.exports.parse=D.parse,t.exports.populate=D.populate,t.exports=D})),Lg=e.__toESM(Ig());async function Rg(e,t){let n=e;for(;n!==(0,f.dirname)(n);){let e=(0,f.join)(n,t);try{return await(0,h.stat)(e),e}catch{}n=(0,f.dirname)(n)}}function zg(e,t,n=`.env.local`){let[r,i]=(0,_.useState)({});return(0,_.useEffect)(()=>{let r,a=e=>{try{let t=(0,p.readFileSync)(e,`utf-8`),n=(0,Lg.parse)(t);i(n)}catch(e){t.error(`system`,`Error reading ${n}:`,e),i({})}};return Rg(e,n).then(e=>{if(!e){i({});return}a(e),r=(0,p.watch)(e,{persistent:!1},()=>{a(e)})}),()=>{r&&r.close()}},[e,n]),r}var Bg=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}else return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h){d[r]=void 0;continue}if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}},Vg=class extends Bg{};new Vg;function Hg(e,t){let n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function Ug(e,t){let n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function Wg(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function Gg(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function Kg(e,t){return Wg(e,t,``)}function qg(e,t){return Gg(e,t,``)}function Jg(e,t){return t.slice(0,Yg(e,t))}function Yg(e,t){let n=0;e.length>t.length&&(n=e.length-t.length);let r=t.length;e.length<t.length&&(r=e.length);let i=Array(r),a=0;i[0]=0;for(let e=1;e<r;e++){for(t[e]==t[a]?i[e]=i[a]:i[e]=a;a>0&&t[e]!=t[a];)a=i[a];t[e]==t[a]&&a++}a=0;for(let r=n;r<e.length;r++){for(;a>0&&e[r]!=t[a];)a=i[a];e[r]==t[a]&&a++}return a}function Xg(e){let t;for(t=e.length-1;t>=0&&e[t].match(/\s/);t--);return e.substring(t+1)}function Zg(e){let t=e.match(/^\s*/);return t?t[0]:``}const Qg=`a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,$g=RegExp(`[${Qg}]+|\\s+|[^${Qg}]`,`ug`);var e_=class extends Bg{equals(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()}tokenize(e,t={}){let n;if(t.intlSegmenter){let r=t.intlSegmenter;if(r.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=Array.from(r.segment(e),e=>e.segment)}else n=e.match($g)||[];let r=[],i=null;return n.forEach(e=>{/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):i!=null&&/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r}join(e){return e.map((e,t)=>t==0?e:e.replace(/^\s+/,``)).join(``)}postProcess(e,t){if(!e||t.oneChangePerToken)return e;let n=null,r=null,i=null;return e.forEach(e=>{e.added?r=e:e.removed?i=e:((r||i)&&t_(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&t_(n,i,r,null),e}};new e_;function t_(e,t,n,r){if(t&&n){let i=Zg(t.value),a=Xg(t.value),o=Zg(n.value),s=Xg(n.value);if(e){let r=Hg(i,o);e.value=Gg(e.value,o,r),t.value=Kg(t.value,r),n.value=Kg(n.value,r)}if(r){let e=Ug(a,s);r.value=Wg(r.value,s,e),t.value=qg(t.value,e),n.value=qg(n.value,e)}}else if(n){if(e){let e=Zg(n.value);n.value=n.value.substring(e.length)}if(r){let e=Zg(r.value);r.value=r.value.substring(e.length)}}else if(e&&r){let n=Zg(r.value),i=Zg(t.value),a=Xg(t.value),o=Hg(n,i);t.value=Kg(t.value,o);let s=Ug(Kg(n,o),a);t.value=qg(t.value,s),r.value=Wg(r.value,n,s),e.value=Gg(e.value,n,n.slice(0,n.length-s.length))}else if(r){let e=Zg(r.value),n=Xg(t.value),i=Jg(n,e);t.value=qg(t.value,i)}else if(e){let n=Xg(e.value),r=Zg(t.value),i=Jg(n,r);t.value=Kg(t.value,i)}}var n_=class extends Bg{tokenize(e){let t=RegExp(`(\\r?\\n)|[${Qg}]+|[^\\S\\n\\r]+|[^${Qg}]`,`ug`);return e.match(t)||[]}};new n_;var r_=class extends Bg{constructor(){super(...arguments),this.tokenize=o_}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
|
|
144
|
+
`),n=n.replace(/\\r/g,`\r`)),t[e]=n}return t}function m(e){e||={};let t=b(e);e.path=t;let n=D.configDotenv(e);if(!n.parsed){let e=Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code=`MISSING_DATA`,e}let r=v(e).split(`,`),i=r.length,a;for(let e=0;e<i;e++)try{let t=r[e].trim(),i=y(n,t);a=D.decrypt(i.ciphertext,i.key);break}catch(t){if(e+1>=i)throw t}return D.parse(a)}function h(e){console.error(`[dotenv@${o}][WARN] ${e}`)}function g(e){console.log(`[dotenv@${o}][DEBUG] ${e}`)}function _(e){console.log(`[dotenv@${o}] ${e}`)}function v(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:``}function y(e,t){let n;try{n=new URL(t)}catch(e){if(e.code===`ERR_INVALID_URL`){let e=Error(`INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development`);throw e.code=`INVALID_DOTENV_KEY`,e}throw e}let r=n.password;if(!r){let e=Error(`INVALID_DOTENV_KEY: Missing key part`);throw e.code=`INVALID_DOTENV_KEY`,e}let i=n.searchParams.get(`environment`);if(!i){let e=Error(`INVALID_DOTENV_KEY: Missing environment part`);throw e.code=`INVALID_DOTENV_KEY`,e}let a=`DOTENV_VAULT_${i.toUpperCase()}`,o=e.parsed[a];if(!o){let e=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${a} in your .env.vault file.`);throw e.code=`NOT_FOUND_DOTENV_ENVIRONMENT`,e}return{ciphertext:o,key:r}}function b(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let r of e.path)n.existsSync(r)&&(t=r.endsWith(`.vault`)?r:`${r}.vault`);else t=e.path.endsWith(`.vault`)?e.path:`${e.path}.vault`;else t=r.resolve(process.cwd(),`.env.vault`);return n.existsSync(t)?t:null}function x(e){return e[0]===`~`?r.join(i.homedir(),e.slice(1)):e}function S(e){let t=l(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=l(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(t||!n)&&_(`Loading env from encrypted .env.vault`);let r=D._parseVault(e),i=process.env;return e&&e.processEnv!=null&&(i=e.processEnv),D.populate(i,r,e),{parsed:r}}function C(e){let t=r.resolve(process.cwd(),`.env`),i=`utf8`,a=process.env;e&&e.processEnv!=null&&(a=e.processEnv);let o=l(a.DOTENV_CONFIG_DEBUG||e&&e.debug),s=l(a.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?i=e.encoding:o&&g(`No encoding is specified. UTF-8 is used by default`);let u=[t];if(e&&e.path)if(!Array.isArray(e.path))u=[x(e.path)];else{u=[];for(let t of e.path)u.push(x(t))}let f,p={};for(let t of u)try{let r=D.parse(n.readFileSync(t,{encoding:i}));D.populate(p,r,e)}catch(e){o&&g(`Failed to load ${t} ${e.message}`),f=e}let m=D.populate(a,p,e);if(o=l(a.DOTENV_CONFIG_DEBUG||o),s=l(a.DOTENV_CONFIG_QUIET||s),o||!s){let e=Object.keys(m).length,t=[];for(let e of u)try{let n=r.relative(process.cwd(),e);t.push(n)}catch(t){o&&g(`Failed to load ${e} ${t.message}`),f=t}_(`injecting env (${e}) from ${t.join(`,`)} ${d(`-- tip: ${c()}`)}`)}return f?{parsed:p,error:f}:{parsed:p}}function w(e){if(v(e).length===0)return D.configDotenv(e);let t=b(e);return t?D._configVault(e):(h(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),D.configDotenv(e))}function T(e,t){let n=Buffer.from(t.slice(-64),`hex`),r=Buffer.from(e,`base64`),i=r.subarray(0,12),o=r.subarray(-16);r=r.subarray(12,-16);try{let e=a.createDecipheriv(`aes-256-gcm`,n,i);return e.setAuthTag(o),`${e.update(r)}${e.final()}`}catch(e){let t=e instanceof RangeError,n=e.message===`Invalid key length`,r=e.message===`Unsupported state or unable to authenticate data`;if(t||n){let e=Error(`INVALID_DOTENV_KEY: It must be 64 characters long (or more)`);throw e.code=`INVALID_DOTENV_KEY`,e}else if(r){let e=Error(`DECRYPTION_FAILED: Please check your DOTENV_KEY`);throw e.code=`DECRYPTION_FAILED`,e}else throw e}}function E(e,t,n={}){let r=!!(n&&n.debug),i=!!(n&&n.override),a={};if(typeof t!=`object`){let e=Error(`OBJECT_REQUIRED: Please check the processEnv argument being passed to populate`);throw e.code=`OBJECT_REQUIRED`,e}for(let n of Object.keys(t))Object.prototype.hasOwnProperty.call(e,n)?(i===!0&&(e[n]=t[n],a[n]=t[n]),r&&g(i===!0?`"${n}" is already defined and WAS overwritten`:`"${n}" is already defined and was NOT overwritten`)):(e[n]=t[n],a[n]=t[n]);return a}let D={configDotenv:C,_configVault:S,_parseVault:m,config:w,decrypt:T,parse:p,populate:E};t.exports.configDotenv=D.configDotenv,t.exports._configVault=D._configVault,t.exports._parseVault=D._parseVault,t.exports.config=D.config,t.exports.decrypt=D.decrypt,t.exports.parse=D.parse,t.exports.populate=D.populate,t.exports=D})),Lg=e.__toESM(Ig());async function Rg(e,t){let n=e;for(;n!==(0,f.dirname)(n);){let e=(0,f.join)(n,t);try{return await(0,h.stat)(e),e}catch{}n=(0,f.dirname)(n)}}function zg(e,t,n=`.env.local`){let[r,i]=(0,_.useState)({});return(0,_.useEffect)(()=>{let r,a=e=>{try{let t=(0,p.readFileSync)(e,`utf-8`),n=(0,Lg.parse)(t);i(n)}catch(e){t.error(`system`,`Error reading ${n}:`,e),i({})}};return Rg(e,n).then(e=>{if(!e){i({});return}a(e),r=(0,p.watch)(e,{persistent:!1},()=>{a(e)})}),()=>{r&&r.close()}},[e,n]),r}var Bg=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}else return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h){d[r]=void 0;continue}if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}},Vg=class extends Bg{};new Vg;function Hg(e,t){let n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function Ug(e,t){let n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function Wg(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function Gg(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function Kg(e,t){return Wg(e,t,``)}function qg(e,t){return Gg(e,t,``)}function Jg(e,t){return t.slice(0,Yg(e,t))}function Yg(e,t){let n=0;e.length>t.length&&(n=e.length-t.length);let r=t.length;e.length<t.length&&(r=e.length);let i=Array(r),a=0;i[0]=0;for(let e=1;e<r;e++){for(t[e]==t[a]?i[e]=i[a]:i[e]=a;a>0&&t[e]!=t[a];)a=i[a];t[e]==t[a]&&a++}a=0;for(let r=n;r<e.length;r++){for(;a>0&&e[r]!=t[a];)a=i[a];e[r]==t[a]&&a++}return a}function Xg(e){let t;for(t=e.length-1;t>=0&&e[t].match(/\s/);t--);return e.substring(t+1)}function Zg(e){let t=e.match(/^\s*/);return t?t[0]:``}const Qg=`a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,$g=RegExp(`[${Qg}]+|\\s+|[^${Qg}]`,`ug`);var e_=class extends Bg{equals(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()}tokenize(e,t={}){let n;if(t.intlSegmenter){let r=t.intlSegmenter;if(r.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=Array.from(r.segment(e),e=>e.segment)}else n=e.match($g)||[];let r=[],i=null;return n.forEach(e=>{/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):i!=null&&/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r}join(e){return e.map((e,t)=>t==0?e:e.replace(/^\s+/,``)).join(``)}postProcess(e,t){if(!e||t.oneChangePerToken)return e;let n=null,r=null,i=null;return e.forEach(e=>{e.added?r=e:e.removed?i=e:((r||i)&&t_(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&t_(n,i,r,null),e}};new e_;function t_(e,t,n,r){if(t&&n){let i=Zg(t.value),a=Xg(t.value),o=Zg(n.value),s=Xg(n.value);if(e){let r=Hg(i,o);e.value=Gg(e.value,o,r),t.value=Kg(t.value,r),n.value=Kg(n.value,r)}if(r){let e=Ug(a,s);r.value=Wg(r.value,s,e),t.value=qg(t.value,e),n.value=qg(n.value,e)}}else if(n){if(e){let e=Zg(n.value);n.value=n.value.substring(e.length)}if(r){let e=Zg(r.value);r.value=r.value.substring(e.length)}}else if(e&&r){let n=Zg(r.value),i=Zg(t.value),a=Xg(t.value),o=Hg(n,i);t.value=Kg(t.value,o);let s=Ug(Kg(n,o),a);t.value=qg(t.value,s),r.value=Wg(r.value,n,s),e.value=Gg(e.value,n,n.slice(0,n.length-s.length))}else if(r){let e=Zg(r.value),n=Jg(Xg(t.value),e);t.value=qg(t.value,n)}else if(e){let n=Jg(Xg(e.value),Zg(t.value));t.value=Kg(t.value,n)}}var n_=class extends Bg{tokenize(e){let t=RegExp(`(\\r?\\n)|[${Qg}]+|[^\\S\\n\\r]+|[^${Qg}]`,`ug`);return e.match(t)||[]}};new n_;var r_=class extends Bg{constructor(){super(...arguments),this.tokenize=o_}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
|
|
145
145
|
`))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(`
|
|
146
146
|
`))&&(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
|
|
147
147
|
`)&&(e=e.slice(0,-1)),t.endsWith(`
|
|
148
148
|
`)&&(t=t.slice(0,-1))),super.equals(e,t,n)}};const i_=new r_;function a_(e,t,n){return i_.diff(e,t,n)}function o_(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
|
|
149
|
-
`));let n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(let e=0;e<r.length;e++){let i=r[e];e%2&&!t.newlineIsToken?n[n.length-1]+=i:n.push(i)}return n}function s_(e){return e==`.`||e==`!`||e==`?`}var c_=class extends Bg{tokenize(e){let t=[],n=0;for(let r=0;r<e.length;r++){if(r==e.length-1){t.push(e.slice(n));break}if(s_(e[r])&&e[r+1].match(/\s/)){for(t.push(e.slice(n,r+1)),r=n=r+1;e[r+1]?.match(/\s/);)r++;t.push(e.slice(n,r+1)),n=r+1}}return t}};new c_;var l_=class extends Bg{tokenize(e){return e.split(/([{}:;,]|\s+)/)}};new l_;var u_=class extends Bg{constructor(){super(...arguments),this.tokenize=o_}get useLongestToken(){return!0}castInput(e,t){let{undefinedReplacement:n,stringifyReplacer:r=(e,t)=>t===void 0?n:t}=t;return typeof e==`string`?e:JSON.stringify(d_(e,null,null,r),null,` `)}equals(e,t,n){return super.equals(e.replace(/,([\r\n])/g,`$1`),t.replace(/,([\r\n])/g,`$1`),n)}};new u_;function d_(e,t,n,r,i){t||=[],n||=[],r&&(e=r(i===void 0?``:i,e));let a;for(a=0;a<t.length;a+=1)if(t[a]===e)return n[a];let o;if(Object.prototype.toString.call(e)===`[object Array]`){for(t.push(e),o=Array(e.length),n.push(o),a=0;a<e.length;a+=1)o[a]=d_(e[a],t,n,r,String(a));return t.pop(),n.pop(),o}if(e&&e.toJSON&&(e=e.toJSON()),typeof e==`object`&&e){t.push(e),o={},n.push(o);let i=[],s;for(s in e)Object.prototype.hasOwnProperty.call(e,s)&&i.push(s);for(i.sort(),a=0;a<i.length;a+=1)s=i[a],o[s]=d_(e[s],t,n,r,s);t.pop(),n.pop()}else o=e;return o}var f_=class extends Bg{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}};new f_;function p_(e,t,n,r,i,a,o){let s;s=o?typeof o==`function`?{callback:o}:o:{},s.context===void 0&&(s.context=4);let c=s.context;if(s.newlineIsToken)throw Error(`newlineIsToken may not be used with patch-generation functions, only with diffing functions`);if(s.callback){let{callback:e}=s;a_(n,r,Object.assign(Object.assign({},s),{callback:t=>{
|
|
149
|
+
`));let n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(let e=0;e<r.length;e++){let i=r[e];e%2&&!t.newlineIsToken?n[n.length-1]+=i:n.push(i)}return n}function s_(e){return e==`.`||e==`!`||e==`?`}var c_=class extends Bg{tokenize(e){let t=[],n=0;for(let r=0;r<e.length;r++){if(r==e.length-1){t.push(e.slice(n));break}if(s_(e[r])&&e[r+1].match(/\s/)){for(t.push(e.slice(n,r+1)),r=n=r+1;e[r+1]?.match(/\s/);)r++;t.push(e.slice(n,r+1)),n=r+1}}return t}};new c_;var l_=class extends Bg{tokenize(e){return e.split(/([{}:;,]|\s+)/)}};new l_;var u_=class extends Bg{constructor(){super(...arguments),this.tokenize=o_}get useLongestToken(){return!0}castInput(e,t){let{undefinedReplacement:n,stringifyReplacer:r=(e,t)=>t===void 0?n:t}=t;return typeof e==`string`?e:JSON.stringify(d_(e,null,null,r),null,` `)}equals(e,t,n){return super.equals(e.replace(/,([\r\n])/g,`$1`),t.replace(/,([\r\n])/g,`$1`),n)}};new u_;function d_(e,t,n,r,i){t||=[],n||=[],r&&(e=r(i===void 0?``:i,e));let a;for(a=0;a<t.length;a+=1)if(t[a]===e)return n[a];let o;if(Object.prototype.toString.call(e)===`[object Array]`){for(t.push(e),o=Array(e.length),n.push(o),a=0;a<e.length;a+=1)o[a]=d_(e[a],t,n,r,String(a));return t.pop(),n.pop(),o}if(e&&e.toJSON&&(e=e.toJSON()),typeof e==`object`&&e){t.push(e),o={},n.push(o);let i=[],s;for(s in e)Object.prototype.hasOwnProperty.call(e,s)&&i.push(s);for(i.sort(),a=0;a<i.length;a+=1)s=i[a],o[s]=d_(e[s],t,n,r,s);t.pop(),n.pop()}else o=e;return o}var f_=class extends Bg{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}};new f_;function p_(e,t,n,r,i,a,o){let s;s=o?typeof o==`function`?{callback:o}:o:{},s.context===void 0&&(s.context=4);let c=s.context;if(s.newlineIsToken)throw Error(`newlineIsToken may not be used with patch-generation functions, only with diffing functions`);if(s.callback){let{callback:e}=s;a_(n,r,Object.assign(Object.assign({},s),{callback:t=>{e(l(t))}}))}else return l(a_(n,r,s));function l(n){if(!n)return;n.push({value:``,lines:[]});function r(e){return e.map(function(e){return` `+e})}let o=[],s=0,l=0,u=[],d=1,f=1;for(let e=0;e<n.length;e++){let t=n[e],i=t.lines||m_(t.value);if(t.lines=i,t.added||t.removed){if(!s){let t=n[e-1];s=d,l=f,t&&(u=c>0?r(t.lines.slice(-c)):[],s-=u.length,l-=u.length)}for(let e of i)u.push((t.added?`+`:`-`)+e);t.added?f+=i.length:d+=i.length}else{if(s)if(i.length<=c*2&&e<n.length-2)for(let e of r(i))u.push(e);else{let e=Math.min(i.length,c);for(let t of r(i.slice(0,e)))u.push(t);let t={oldStart:s,oldLines:d-s+e,newStart:l,newLines:f-l+e,lines:u};o.push(t),s=0,l=0,u=[]}d+=i.length,f+=i.length}}for(let e of o)for(let t=0;t<e.lines.length;t++)e.lines[t].endsWith(`
|
|
150
150
|
`)?e.lines[t]=e.lines[t].slice(0,-1):(e.lines.splice(t+1,0,`\`),t++);return{oldFileName:e,newFileName:t,oldHeader:i,newHeader:a,hunks:o}}}function m_(e){let t=e.endsWith(`
|
|
151
151
|
`),n=e.split(`
|
|
152
152
|
`).map(e=>e+`
|
|
@@ -172,7 +172,7 @@ Usage:
|
|
|
172
172
|
- This tool allows Blink to read images (eg PNG, JPG, etc). When reading an image file the contents are presented visually as Blink is a multimodal LLM
|
|
173
173
|
- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.
|
|
174
174
|
- You will regularly be asked to read screenshots. If the user provides a path to a screenshot ALWAYS use this tool to view the file at the path. This tool will work with all temporary file paths like /var/folders/123/abc/T/TemporaryItems/NSIRD_screencaptureui_ZfB1tD/Screenshot.png
|
|
175
|
-
- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.`,inputSchema:y.z.object({file_path:y.z.string(),line_offset:y.z.number(),line_limit:y.z.number()}),execute:async(t,n)=>await(await e()).request(`read_file`,{path:t.file_path,line_start:t.line_offset,line_end:t.line_offset+t.line_limit},{signal:n.abortSignal}),toModelOutput:e=>e.mime_type?.startsWith(`image/`)?{type:`content`,value:[{type:`media`,data:e.content,mediaType:e.mime_type}]}:{type:`json`,value:e}})),write_file:__(({client:e})=>({description:`Write a file to the filesystem.`,inputSchema:y.z.object({file_path:y.z.string(),content:y.z.string()}),execute:async(t,n)=>{await(await e()).request(`write_file`,{path:t.file_path,content:t.content},{signal:n.abortSignal})}})),read_directory:__(({client:e})=>(0,m.tool)({description:`Reads a directory from the workspace filesystem.`,inputSchema:y.z.object({directory_path:y.z.string()}),execute:async(t,n)=>(await e()).request(`read_directory`,{path:t.directory_path})})),edit_file:__(({client:e})=>({description:`This is a tool for making multiple edits to a single file in one operation. It is built on top of the "workspace_edit_file" tool and allows you to perform multiple find-and-replace operations efficiently. Prefer this tool over the "workspace_edit_file" tool when you need to make multiple edits to the same file.
|
|
175
|
+
- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.`,inputSchema:y.z.object({file_path:y.z.string(),line_offset:y.z.number(),line_limit:y.z.number()}),execute:async(t,n)=>(console.log(`reading file`,t),await(await e()).request(`read_file`,{path:t.file_path,line_start:t.line_offset,line_end:t.line_offset+t.line_limit},{signal:n.abortSignal})),toModelOutput:e=>e.mime_type?.startsWith(`image/`)?{type:`content`,value:[{type:`media`,data:e.content,mediaType:e.mime_type}]}:{type:`json`,value:e}})),write_file:__(({client:e})=>({description:`Write a file to the filesystem.`,inputSchema:y.z.object({file_path:y.z.string(),content:y.z.string()}),execute:async(t,n)=>{await(await e()).request(`write_file`,{path:t.file_path,content:t.content},{signal:n.abortSignal})}})),read_directory:__(({client:e})=>(0,m.tool)({description:`Reads a directory from the workspace filesystem.`,inputSchema:y.z.object({directory_path:y.z.string()}),execute:async(t,n)=>(await e()).request(`read_directory`,{path:t.directory_path})})),edit_file:__(({client:e})=>({description:`This is a tool for making multiple edits to a single file in one operation. It is built on top of the "workspace_edit_file" tool and allows you to perform multiple find-and-replace operations efficiently. Prefer this tool over the "workspace_edit_file" tool when you need to make multiple edits to the same file.
|
|
176
176
|
|
|
177
177
|
Before using this tool:
|
|
178
178
|
|
|
@@ -210,7 +210,7 @@ When making edits:
|
|
|
210
210
|
If you want to create a new file, use:
|
|
211
211
|
- A new file path, including dir name if needed
|
|
212
212
|
- First edit: empty old_string and the new file's contents as new_string
|
|
213
|
-
- Subsequent edits: normal edit operations on the created content`,inputSchema:y.z.object({file_path:y.z.string(),edits:y.z.array(y.z.object({old_string:y.z.string(),new_string:y.z.string(),expected_replacements:y.z.number()}))}),execute:async(t,n)=>{let r=await e(),i;try{i=(await r.request(`read_file`,{path:t.file_path},{signal:n.abortSignal})).content}catch{if(i=t.edits[0].new_string,t.edits.length>0&&t.edits[0].old_string===``)i=t.edits[0].new_string,t.edits.shift();else throw Error(`input is invalid: File does not exist and first edit is not for file creation.\nFile: ${t.file_path}`)}let a=i,o=[];for(let e of t.edits){let t=e.expected_replacements??1,n=e.old_string
|
|
213
|
+
- Subsequent edits: normal edit operations on the created content`,inputSchema:y.z.object({file_path:y.z.string(),edits:y.z.array(y.z.object({old_string:y.z.string(),new_string:y.z.string(),expected_replacements:y.z.number()}))}),execute:async(t,n)=>{let r=await e(),i;try{i=(await r.request(`read_file`,{path:t.file_path},{signal:n.abortSignal})).content}catch{if(i=t.edits[0].new_string,t.edits.length>0&&t.edits[0].old_string===``)i=t.edits[0].new_string,t.edits.shift();else throw Error(`input is invalid: File does not exist and first edit is not for file creation.\nFile: ${t.file_path}`)}let a=i,o=[];for(let e of t.edits){let t=e.expected_replacements??1,n=e.old_string;if(n===e.new_string)throw Error(`input is invalid: old_string and new_string are identical.\nString: ${n}`);let r=x_(a,n);if(r===0)throw Error(`input is invalid: String to replace not found in file.\nString: ${n}`);if(r!==t)throw Error(`input is invalid: Found ${r} matches of the string to replace, but expected ${t}. The number of actual matches must equal the expected replacements. Please adjust your string to match or update the expected count.\nString: ${n}`)}for(let e of t.edits){let t=e.old_string,n=e.new_string;a=S_(a,t,n),o.push({old_string:t,new_string:n})}await r.request(`write_file`,{path:t.file_path,content:a},{signal:n.abortSignal});let s=p_(t.file_path,t.file_path,i,a);return{edits:o,file_path:t.file_path,structured_patch:s.hunks.map(e=>({old_start:e.oldStart,old_end:e.oldLines,new_start:e.newStart,new_end:e.newLines,lines:e.lines}))}}})),process_grep_output:__(({client:e})=>({description:`Search through the output of a running or completed process. **This is the PRIMARY tool for analyzing command output** - use this instead of piping commands to grep, tail, or re-running commands with filters.
|
|
214
214
|
|
|
215
215
|
Use this for:
|
|
216
216
|
- Finding test failures and error messages
|
|
@@ -52,12 +52,12 @@ ${Pf}${t.trimStart()}`),n=3+oe(t.trimStart()).length)}process.stdout.write(`
|
|
|
52
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
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.so`}).devhook.listen({id:e.id,onRequest:async e=>t.current(e),onConnect:()=>{o=!1,r(`connected`)},onDisconnect:()=>{o=!1,r(`disconnected`),!n&&!a&&(a=setTimeout(()=>{a=void 0,l()},2e3))},onError:e=>{o=!1,r(`error`),!n&&!a&&(a=setTimeout(()=>{a=void 0,l()},2e3))}})}};l()})(),()=>{if(n=!0,a&&=(clearTimeout(a),void 0),i){try{i.dispose()}catch{}i=void 0}if(s)try{s()}catch(t){e.logger.error(`system`,`Failed to release devhook lock:`,t)}}},[e.disabled,e.directory]),{id:e.id,url:e.id?`https://${e.id}.blink.host`:void 0,status:n}}var 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+`
|
|
@@ -83,7 +83,7 @@ Usage:
|
|
|
83
83
|
- This tool allows Blink to read images (eg PNG, JPG, etc). When reading an image file the contents are presented visually as Blink is a multimodal LLM
|
|
84
84
|
- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.
|
|
85
85
|
- You will regularly be asked to read screenshots. If the user provides a path to a screenshot ALWAYS use this tool to view the file at the path. This tool will work with all temporary file paths like /var/folders/123/abc/T/TemporaryItems/NSIRD_screencaptureui_ZfB1tD/Screenshot.png
|
|
86
|
-
- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.`,inputSchema:q.object({file_path:q.string(),line_offset:q.number(),line_limit:q.number()}),execute:async(t,n)=>await(await e()).request(`read_file`,{path:t.file_path,line_start:t.line_offset,line_end:t.line_offset+t.line_limit},{signal:n.abortSignal}),toModelOutput:e=>e.mime_type?.startsWith(`image/`)?{type:`content`,value:[{type:`media`,data:e.content,mediaType:e.mime_type}]}:{type:`json`,value:e}})),write_file:uh(({client:e})=>({description:`Write a file to the filesystem.`,inputSchema:q.object({file_path:q.string(),content:q.string()}),execute:async(t,n)=>{await(await e()).request(`write_file`,{path:t.file_path,content:t.content},{signal:n.abortSignal})}})),read_directory:uh(({client:e})=>be({description:`Reads a directory from the workspace filesystem.`,inputSchema:q.object({directory_path:q.string()}),execute:async(t,n)=>(await e()).request(`read_directory`,{path:t.directory_path})})),edit_file:uh(({client:e})=>({description:`This is a tool for making multiple edits to a single file in one operation. It is built on top of the "workspace_edit_file" tool and allows you to perform multiple find-and-replace operations efficiently. Prefer this tool over the "workspace_edit_file" tool when you need to make multiple edits to the same file.
|
|
86
|
+
- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.`,inputSchema:q.object({file_path:q.string(),line_offset:q.number(),line_limit:q.number()}),execute:async(t,n)=>(console.log(`reading file`,t),await(await e()).request(`read_file`,{path:t.file_path,line_start:t.line_offset,line_end:t.line_offset+t.line_limit},{signal:n.abortSignal})),toModelOutput:e=>e.mime_type?.startsWith(`image/`)?{type:`content`,value:[{type:`media`,data:e.content,mediaType:e.mime_type}]}:{type:`json`,value:e}})),write_file:uh(({client:e})=>({description:`Write a file to the filesystem.`,inputSchema:q.object({file_path:q.string(),content:q.string()}),execute:async(t,n)=>{await(await e()).request(`write_file`,{path:t.file_path,content:t.content},{signal:n.abortSignal})}})),read_directory:uh(({client:e})=>be({description:`Reads a directory from the workspace filesystem.`,inputSchema:q.object({directory_path:q.string()}),execute:async(t,n)=>(await e()).request(`read_directory`,{path:t.directory_path})})),edit_file:uh(({client:e})=>({description:`This is a tool for making multiple edits to a single file in one operation. It is built on top of the "workspace_edit_file" tool and allows you to perform multiple find-and-replace operations efficiently. Prefer this tool over the "workspace_edit_file" tool when you need to make multiple edits to the same file.
|
|
87
87
|
|
|
88
88
|
Before using this tool:
|
|
89
89
|
|
|
@@ -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
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "blink",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.32",
|
|
4
4
|
"description": "Blink is a tool for building and deploying AI agents.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -74,7 +74,7 @@
|
|
|
74
74
|
"gen-templates": "bun run src/cli/scripts/generate-templates.ts && cd ../.. && bun format"
|
|
75
75
|
},
|
|
76
76
|
"dependencies": {
|
|
77
|
-
"@blink-sdk/compute-protocol": "^0.0.
|
|
77
|
+
"@blink-sdk/compute-protocol": "^0.0.7"
|
|
78
78
|
},
|
|
79
79
|
"devDependencies": {
|
|
80
80
|
"@ai-sdk/anthropic": "^2.0.15",
|