blink 1.1.10 → 1.1.11

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.
@@ -65,9 +65,11 @@ declare const api: hono_hono_base0.HonoBase<{
65
65
  key: string;
66
66
  };
67
67
  };
68
- output: null;
69
- outputFormat: "body";
70
- status: 204;
68
+ output: {
69
+ error: string;
70
+ };
71
+ outputFormat: "json";
72
+ status: 400;
71
73
  } | {
72
74
  input: {
73
75
  json: {
@@ -78,11 +80,9 @@ declare const api: hono_hono_base0.HonoBase<{
78
80
  key: string;
79
81
  };
80
82
  };
81
- output: {
82
- error: string;
83
- };
84
- outputFormat: "json";
85
- status: 400;
83
+ output: null;
84
+ outputFormat: "body";
85
+ status: 204;
86
86
  };
87
87
  };
88
88
  } & {
@@ -340,9 +340,11 @@ declare const api: hono_hono_base0.HonoBase<{
340
340
  id: string;
341
341
  };
342
342
  };
343
- output: null;
344
- outputFormat: "body";
345
- status: 204;
343
+ output: {
344
+ error: string;
345
+ };
346
+ outputFormat: "json";
347
+ status: 400;
346
348
  } | {
347
349
  input: {
348
350
  json: {
@@ -355,11 +357,9 @@ declare const api: hono_hono_base0.HonoBase<{
355
357
  id: string;
356
358
  };
357
359
  };
358
- output: {
359
- error: string;
360
- };
361
- outputFormat: "json";
362
- status: 400;
360
+ output: null;
361
+ outputFormat: "body";
362
+ status: 204;
363
363
  };
364
364
  };
365
365
  } & {
@@ -65,9 +65,11 @@ declare const api: hono_hono_base0.HonoBase<{
65
65
  key: string;
66
66
  };
67
67
  };
68
- output: null;
69
- outputFormat: "body";
70
- status: 204;
68
+ output: {
69
+ error: string;
70
+ };
71
+ outputFormat: "json";
72
+ status: 400;
71
73
  } | {
72
74
  input: {
73
75
  json: {
@@ -78,11 +80,9 @@ declare const api: hono_hono_base0.HonoBase<{
78
80
  key: string;
79
81
  };
80
82
  };
81
- output: {
82
- error: string;
83
- };
84
- outputFormat: "json";
85
- status: 400;
83
+ output: null;
84
+ outputFormat: "body";
85
+ status: 204;
86
86
  };
87
87
  };
88
88
  } & {
@@ -340,9 +340,11 @@ declare const api: hono_hono_base0.HonoBase<{
340
340
  id: string;
341
341
  };
342
342
  };
343
- output: null;
344
- outputFormat: "body";
345
- status: 204;
343
+ output: {
344
+ error: string;
345
+ };
346
+ outputFormat: "json";
347
+ status: 400;
346
348
  } | {
347
349
  input: {
348
350
  json: {
@@ -355,11 +357,9 @@ declare const api: hono_hono_base0.HonoBase<{
355
357
  id: string;
356
358
  };
357
359
  };
358
- output: {
359
- error: string;
360
- };
361
- outputFormat: "json";
362
- status: 400;
360
+ output: null;
361
+ outputFormat: "body";
362
+ status: 204;
363
363
  };
364
364
  };
365
365
  } & {
@@ -1722,7 +1722,13 @@ The structure MUST be as follows:
1722
1722
  **Decision Rules (apply in order):**
1723
1723
  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.
1724
1724
  2. **Question to User:** If your last response ends with a direct question specifically addressed *to the user*, then the **'user'** should speak next.
1725
- 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$1(__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$10=>{streamDoneResolver=resolve$10});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$3){this.generationConfig.tools=tools$3}async maybeIncludeSchemaDepthContext(error$3){if(isSchemaDepthError(error$3.message)||isInvalidArgumentError(error$3.message)){let tools$3=this.config.getToolRegistry().getAllTools(),cyclicSchemaTools=[];for(let tool$2 of tools$3)(tool$2.schema.parametersJsonSchema&&hasCycleInSchema(tool$2.schema.parametersJsonSchema)||tool$2.schema.parameters&&hasCycleInSchema(tool$2.schema.parameters))&&cyclicSchemaTools.push(tool$2.displayName);if(cyclicSchemaTools.length>0){let extraDetails=`
1725
+ 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$1(__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$1();
1726
+ /**
1727
+ * @license
1728
+ * Copyright 2025 Google LLC
1729
+ * SPDX-License-Identifier: Apache-2.0
1730
+ */
1731
+ 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$10=>{streamDoneResolver=resolve$10});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$3){this.generationConfig.tools=tools$3}async maybeIncludeSchemaDepthContext(error$3){if(isSchemaDepthError(error$3.message)||isInvalidArgumentError(error$3.message)){let tools$3=this.config.getToolRegistry().getAllTools(),cyclicSchemaTools=[];for(let tool$2 of tools$3)(tool$2.schema.parametersJsonSchema&&hasCycleInSchema(tool$2.schema.parametersJsonSchema)||tool$2.schema.parameters&&hasCycleInSchema(tool$2.schema.parameters))&&cyclicSchemaTools.push(tool$2.displayName);if(cyclicSchemaTools.length>0){let extraDetails=`
1726
1732
 
1727
1733
  This error was probably caused by cyclic schema references in one of the following tools, try disabling them with excludeTools:
1728
1734
 
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:ie,createOption:ae,CommanderError:P,InvalidArgumentError:oe,InvalidOptionArgumentError:se,Command:ce,Argument:F,Option:le,Help:I}=n(e((e=>{let{Argument:t}=D(),{Command:n}=j(),{CommanderError:r,InvalidArgumentError:i}=E(),{Help:a}=O(),{Option:o}=k();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.10`;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(u(),1),V=n(g(),1);async function H(e,t){e||=process.cwd(),await a(e);let n=await l(),r=new c({authToken:n,fetch:(e,t)=>{let n=new Headers(t?.headers);return n.set(`x-blink-cli-version`,L),fetch(e,{...t,headers:n})}}),o=await i(e,`package.json`);if(!o)throw Error(`package.json not found`);let u=await w(o,`utf-8`),g=JSON.parse(u),v=y(o),x=b(v,`data`,`config.json`),E={};if(ne(x)){let e=await w(x,`utf-8`);E=JSON.parse(e)}let D;if(E?.organizationId)try{D=(await r.organizations.get(E.organizationId)).name}catch{E.organizationId=void 0}if(!E?.organizationId){let e=await r.organizations.list();if(e.length===1)E.organizationId=e[0].id,D=e[0].name;else{let t=await p({message:`Which organization should contain this agent?`,options:e.map(e=>({value:e.id,label:e.name}))});if(f(t))return;E.organizationId=t,D=e.find(e=>e.id===t).name,console.log()}}let O,k=!1,A=!1;if(E?.agentId)try{O=(await r.agents.get(E.agentId)).name}catch{E.agentId=void 0}if(!E?.agentId)try{let e=await r.organizations.agents.get({organization_id:E.organizationId,agent_name:g.name});E.agentId=e.id,O=e.name}catch{k=!0,O=g.name}k?console.log(B.default.bold(`blink■`)+` creating agent `+D+`/`+O):console.log(B.default.bold(`blink■`)+` deploying agent `+D+`/`+O);let j=Date.now(),M=s(v),N=await new Promise((e,t)=>{M.build({cwd:v,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 ie=Date.now()-j;console.log(B.default.gray(`Built ${B.default.dim(`(${ie}ms)`)}`));let ae=await S(N.outdir),P=Object.fromEntries(ae.map(e=>[b(N.outdir,e),e])),oe=b(e,`README.md`);await U(oe)&&(P[oe]=`README.md`);let se=await fe(v),ce=Object.fromEntries(se.map(e=>[e,te(v,e)])),F=Object.entries(P),le=Object.entries(ce),I=[...F,...le],R=I.length,z=0,V=0,H=0,q=Array(R);await de(I,10,async([e,t],n)=>{let i=(await T(e)).size,a=++z;K(`${B.default.dim(`[${a}/${R}]`)} Uploading ${t} (${G(i)})...`);let o=await w(e),s=await r.files.upload(new File([Buffer.from(o)],t));q[n]={path:t,id:s.id},V+=1,H+=i}),K(B.default.gray(`Uploaded ${R} ${R===1?`file`:`files`} ${B.default.dim(`(${G(H)})`)}`)),process.stdout.write(`
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:ie,createOption:ae,CommanderError:P,InvalidArgumentError:oe,InvalidOptionArgumentError:se,Command:ce,Argument:F,Option:le,Help:I}=n(e((e=>{let{Argument:t}=D(),{Command:n}=j(),{CommanderError:r,InvalidArgumentError:i}=E(),{Help:a}=O(),{Option:o}=k();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.11`;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(u(),1),V=n(g(),1);async function H(e,t){e||=process.cwd(),await a(e);let n=await l(),r=new c({authToken:n,fetch:(e,t)=>{let n=new Headers(t?.headers);return n.set(`x-blink-cli-version`,L),fetch(e,{...t,headers:n})}}),o=await i(e,`package.json`);if(!o)throw Error(`package.json not found`);let u=await w(o,`utf-8`),g=JSON.parse(u),v=y(o),x=b(v,`data`,`config.json`),E={};if(ne(x)){let e=await w(x,`utf-8`);E=JSON.parse(e)}let D;if(E?.organizationId)try{D=(await r.organizations.get(E.organizationId)).name}catch{E.organizationId=void 0}if(!E?.organizationId){let e=await r.organizations.list();if(e.length===1)E.organizationId=e[0].id,D=e[0].name;else{let t=await p({message:`Which organization should contain this agent?`,options:e.map(e=>({value:e.id,label:e.name}))});if(f(t))return;E.organizationId=t,D=e.find(e=>e.id===t).name,console.log()}}let O,k=!1,A=!1;if(E?.agentId)try{O=(await r.agents.get(E.agentId)).name}catch{E.agentId=void 0}if(!E?.agentId)try{let e=await r.organizations.agents.get({organization_id:E.organizationId,agent_name:g.name});E.agentId=e.id,O=e.name}catch{k=!0,O=g.name}k?console.log(B.default.bold(`blink■`)+` creating agent `+D+`/`+O):console.log(B.default.bold(`blink■`)+` deploying agent `+D+`/`+O);let j=Date.now(),M=s(v),N=await new Promise((e,t)=>{M.build({cwd:v,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 ie=Date.now()-j;console.log(B.default.gray(`Built ${B.default.dim(`(${ie}ms)`)}`));let ae=await S(N.outdir),P=Object.fromEntries(ae.map(e=>[b(N.outdir,e),e])),oe=b(e,`README.md`);await U(oe)&&(P[oe]=`README.md`);let se=await fe(v),ce=Object.fromEntries(se.map(e=>[e,te(v,e)])),F=Object.entries(P),le=Object.entries(ce),I=[...F,...le],R=I.length,z=0,V=0,H=0,q=Array(R);await de(I,10,async([e,t],n)=>{let i=(await T(e)).size,a=++z;K(`${B.default.dim(`[${a}/${R}]`)} Uploading ${t} (${G(i)})...`);let o=await w(e),s=await r.files.upload(new File([Buffer.from(o)],t));q[n]={path:t,id:s.id},V+=1,H+=i}),K(B.default.gray(`Uploaded ${R} ${R===1?`file`:`files`} ${B.default.dim(`(${G(H)})`)}`)),process.stdout.write(`
21
21
  `);let J=q.filter(Boolean),Y=J.slice(0,F.length),pe=J.slice(F.length),X=await W(b(e,`.env.production`));if(k){let t=b(e,`.env.local`),n=b(e,`.env.production`),r=await W(t),i=Object.keys(r).filter(e=>!Object.keys(X).includes(e));if(i.length>0){console.log(`
22
22
  `+B.default.cyan(`Environment Variables`)),console.log(B.default.dim(` Missing ${i.length} var${i.length===1?``:`s`} in .env.production: ${i.join(`, `)}`));let e=await m({message:`Copy missing vars from .env.local to .env.production?`,initialValue:!0});if(f(e))return;if(console.log(),e){for(let e of i)X[e]=r[e];await C(n,`# Environment variables for production deployment\n${Object.entries(X).map(([e,t])=>`${e}=${t}`).join(`
23
- `)}`,`utf-8`)}}let a=h(e);if(a){let e=`https://${a}.blink.so`;console.log(`
23
+ `)}`,`utf-8`)}}let a=h(e);if(a){let e=`https://${a}.blink.host`;console.log(`
24
24
  `+B.default.cyan(`Webhook Tunnel`)),console.log(B.default.dim(` Current: ${e} → local dev`)),console.log(B.default.dim(` After: ${e} → production`)),console.log(B.default.dim(` Migrating will keep your webhooks working in production`));let t=await m({message:`Migrate tunnel to production?`});if(f(t))return;console.log(),t&&(A=!0)}}let Z=Object.entries(X);if(k){let t=h(e),n=await r.agents.create({name:g.name,organization_id:E.organizationId,request_id:A?t:void 0,entrypoint:ee(N.entry),output_files:Y,source_files:pe,env:Z.map(([e,t])=>({key:e,value:t,target:[`production`,`preview`],secret:!0}))});E.agentId=n.id,O=n.name;let i=`https://blink.so/${D}/${O}`;console.log(B.default.gray(`Agent created ${B.default.dim(i)}`))}else if(Z.length>0){let e=0;for(let[t,n]of Z)await r.agents.env.create({agent_id:E.agentId,key:t,value:n,target:[`production`,`preview`],secret:!0,upsert:!0}),K(`${B.default.dim(`[${++e}/${Z.length}]`)} Updating environment variable: ${t} ${B.default.dim(`(.env.production)`)}`);K(B.default.gray(`Updated ${Z.length} environment ${Z.length===1?`variable`:`variables`} ${B.default.dim(`(.env.production)`)}`)),process.stdout.write(`
25
- `)}let me=await W(b(e,`.env.local`)),he=Object.keys(me).filter(e=>!Object.keys(X).includes(e));if(he.length>0){console.log(`Warning: The following environment variables are set in .env.local but not in .env.production:`);for(let e of he)console.log(`- ${e}`);let e=await m({message:`Do you want to deploy anyway?`});if(e===!1||f(e))return}let ge=k?(await r.agents.deployments.list({agent_id:E.agentId})).items[0]:await r.agents.deployments.create({agent_id:E.agentId,target:`production`,entrypoint:ee(N.entry),output_files:Y,source_files:pe,message:t?.message}),Q=`https://blink.so/${D}/${O}/deployments/${ge.number}`;console.log(B.default.gray(`View Deployment ${B.default.dim(Q)}`)),await ue(x,E);let $=d();$.start(`Waiting for deployment to be live...`);try{for(;;){let t=await r.agents.deployments.get({agent_id:E.agentId,deployment_id:ge.id});if(t.status===`success`){$.stop(),k?(console.log(`Your agent is live.`),console.log(B.default.dim(Q))):(console.log(`Deployed. All new chats will use this version.`),console.log(B.default.dim(Q))),A&&(_(e),console.log(B.default.yellow(`Note:`)+` To continue developing locally with webhooks, you'll need to reconfigure external services (Slack, GitHub, etc.)`));break}if(t.status===`failed`){$.stop(`Failed`+(t.error_message?`: ${t.error_message}`:``)),console.log(),console.log(`Logs: `+B.default.dim(Q));return}await new Promise(e=>setTimeout(e,500))}}catch(e){$.stop(`Failed to poll deployment status`),console.log(),console.log(`Error: `+re(e)),console.log(`Logs: `+B.default.dim(Q))}}const U=async e=>{try{return await T(e),!0}catch{return!1}};async function W(e){return await U(e)?(0,z.parse)(await w(e,`utf-8`)):{}}async function ue(e,t){await x(y(e),{recursive:!0}),await C(e,JSON.stringify({_:`This file can be source controlled. It contains no secrets.`,...t},null,2),`utf-8`)}async function de(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 G(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 K(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 fe(e){let t=[],n=(0,V.default)().add([`.git`,`node_modules`,`data`,`.env`,`.env.*`]),r=b(e,`.gitignore`);if(await U(r)){let e=await w(r,`utf-8`);n.add(e)}async function i(r,a=e){let o=await S(r,{withFileTypes:!0});for(let e of o){let o=b(r,e.name),s=te(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=()=>v()),M.name(`blink`).description(`Blink is a runtime for building and deploying AI agents.`).version(L).action(()=>{M.outputHelp()});const q=e=>async(...t)=>{let{default:n}=await e();return n(...t)};M.command(`init [directory]`).description(`Initialize a new Blink agent.`).action(q(()=>import(`./init-lHUh7gYE.js`))),M.command(`dev [directory] [options]`).description(`Start a development server for your agent.`).action(q(()=>import(`./dev-s0j6vbYi.js`))),M.command(`deploy [directory]`).description(`Deploy your agent to the Blink Cloud.`).option(`-m, --message <message>`,`Message for this deployment`).action(H),M.command(`build [directory]`).description(`Build your agent for production.`).action(R),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(q(()=>import(`./run-DtICLjeJ.js`))),M.command(`connect`,{hidden:!0}).description(`Connect compute to the Blink Cloud.`).action(q(()=>import(`./connect-O43Nkqhm.js`))),M.command(`chat`,{hidden:!0}).description(`Start a Blink chat connected to your machine.`).action(q(()=>import(`./chat-Jjsxhu91.js`))),M.command(`login`,{hidden:!0}).description(`Log in to the Blink Cloud.`).action(q(()=>import(`./login-BaxIl8sF.js`))),M.parse(process.argv);export{};
25
+ `)}let me=await W(b(e,`.env.local`)),he=Object.keys(me).filter(e=>!Object.keys(X).includes(e));if(he.length>0){console.log(`Warning: The following environment variables are set in .env.local but not in .env.production:`);for(let e of he)console.log(`- ${e}`);let e=await m({message:`Do you want to deploy anyway?`});if(e===!1||f(e))return}let ge=k?(await r.agents.deployments.list({agent_id:E.agentId})).items[0]:await r.agents.deployments.create({agent_id:E.agentId,target:`production`,entrypoint:ee(N.entry),output_files:Y,source_files:pe,message:t?.message}),Q=`https://blink.so/${D}/${O}/deployments/${ge.number}`;console.log(B.default.gray(`View Deployment ${B.default.dim(Q)}`)),await ue(x,E);let $=d();$.start(`Waiting for deployment to be live...`);try{for(;;){let t=await r.agents.deployments.get({agent_id:E.agentId,deployment_id:ge.id});if(t.status===`success`){$.stop(),k?(console.log(`Your agent is live.`),console.log(B.default.dim(Q))):(console.log(`Deployed. All new chats will use this version.`),console.log(B.default.dim(Q))),A&&(_(e),console.log(B.default.yellow(`Note:`)+` To continue developing locally with webhooks, you'll need to reconfigure external services (Slack, GitHub, etc.)`));break}if(t.status===`failed`){$.stop(`Failed`+(t.error_message?`: ${t.error_message}`:``)),console.log(),console.log(`Logs: `+B.default.dim(Q));return}await new Promise(e=>setTimeout(e,500))}}catch(e){$.stop(`Failed to poll deployment status`),console.log(),console.log(`Error: `+re(e)),console.log(`Logs: `+B.default.dim(Q))}}const U=async e=>{try{return await T(e),!0}catch{return!1}};async function W(e){return await U(e)?(0,z.parse)(await w(e,`utf-8`)):{}}async function ue(e,t){await x(y(e),{recursive:!0}),await C(e,JSON.stringify({_:`This file can be source controlled. It contains no secrets.`,...t},null,2),`utf-8`)}async function de(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 G(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 K(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 fe(e){let t=[],n=(0,V.default)().add([`.git`,`node_modules`,`data`,`.env`,`.env.*`]),r=b(e,`.gitignore`);if(await U(r)){let e=await w(r,`utf-8`);n.add(e)}async function i(r,a=e){let o=await S(r,{withFileTypes:!0});for(let e of o){let o=b(r,e.name),s=te(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=()=>v()),M.name(`blink`).description(`Blink is a runtime for building and deploying AI agents.`).version(L).action(()=>{M.outputHelp()});const q=e=>async(...t)=>{let{default:n}=await e();return n(...t)};M.command(`init [directory]`).description(`Initialize a new Blink agent.`).action(q(()=>import(`./init-lHUh7gYE.js`))),M.command(`dev [directory] [options]`).description(`Start a development server for your agent.`).action(q(()=>import(`./dev-8UEn9f59.js`))),M.command(`deploy [directory]`).description(`Deploy your agent to the Blink Cloud.`).option(`-m, --message <message>`,`Message for this deployment`).action(H),M.command(`build [directory]`).description(`Build your agent for production.`).action(R),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(q(()=>import(`./run-DtICLjeJ.js`))),M.command(`connect`,{hidden:!0}).description(`Connect compute to the Blink Cloud.`).action(q(()=>import(`./connect-O43Nkqhm.js`))),M.command(`chat`,{hidden:!0}).description(`Start a Blink chat connected to your machine.`).action(q(()=>import(`./chat-Jjsxhu91.js`))),M.command(`login`,{hidden:!0}).description(`Log in to the Blink Cloud.`).action(q(()=>import(`./login-BaxIl8sF.js`))),M.parse(process.argv);export{};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blink",
3
- "version": "1.1.10",
3
+ "version": "1.1.11",
4
4
  "description": "Blink is a JavaScript runtime for building and deploying AI agents.",
5
5
  "type": "module",
6
6
  "bin": {