blink 1.1.31 → 1.1.33

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
  } & {
@@ -0,0 +1 @@
1
+ import{__require as e}from"./chunk-D9KrCrVq.js";import{import_websocket_server as t}from"./wrapper-DRdRnzOz.js";import{_usingCtx as n}from"./usingCtx-B1FpoePI.js";import"./events-DKgZ2LNM.js";import{Buffer as r}from"node:buffer";import{Server as i}from"@blink-sdk/compute-protocol/server";let a=function(e){return e[e.DATA=0]=`DATA`,e[e.CLOSE=1]=`CLOSE`,e[e.ERROR=2]=`ERROR`,e}({});var o=class{static MAX_POOL_SIZE=100;static COMMON_SIZES=[64,256,1024,4096,16384];static pools=new Map;static{for(let e of this.COMMON_SIZES)this.pools.set(e,[])}static acquire(e){for(let t of this.COMMON_SIZES)if(t>=e){let e=this.pools.get(t);if(e&&e.length>0)return e.pop();break}return new Uint8Array(e)}static release(e){let t=e.length;for(let n of this.COMMON_SIZES)if(n===t){let t=this.pools.get(n);t&&t.length<this.MAX_POOL_SIZE&&t.push(e);break}}},s=class e{static HEADER_SIZE=4;static MAX_FRAME_SIZE=1024*1024-e.HEADER_SIZE;static encode(e){let t=e.payload.length;if(t>this.MAX_FRAME_SIZE)throw Error(`Frame payload too large: ${t} > ${this.MAX_FRAME_SIZE}`);let n=this.HEADER_SIZE+t,r=o.acquire(n),i=e.streamId<<8|e.type<<4|e.flags&15;return r[0]=i>>>24&255,r[1]=i>>>16&255,r[2]=i>>>8&255,r[3]=i&255,t>0&&r.set(e.payload,this.HEADER_SIZE),r.length===n?r:r.subarray(0,n)}static encodeTyped(t,n,r,i,a){let s=1+a.length;if(s>this.MAX_FRAME_SIZE)throw Error(`Frame payload too large: ${s} > ${this.MAX_FRAME_SIZE}`);let c=this.HEADER_SIZE+s,l=o.acquire(c),u=t<<8|n<<4|r&15;return l[0]=u>>>24&255,l[1]=u>>>16&255,l[2]=u>>>8&255,l[3]=u&255,l[e.HEADER_SIZE]=i&255,a.length>0&&l.set(a,e.HEADER_SIZE+1),l.length===c?l:l.subarray(0,c)}static decode(t){if(t.length<e.HEADER_SIZE)throw Error(`Invalid frame: too short (${t.length} < ${e.HEADER_SIZE})`);let n=t[0]<<24|t[1]<<16|t[2]<<8|t[3],r=n>>>8,i=n&255,a=i>>>4,o=i&15,s=t.length>e.HEADER_SIZE?t.subarray(e.HEADER_SIZE):new Uint8Array;return{streamId:r,type:a,flags:o,payload:s}}static releaseBuffer(e){o.release(e)}static getMaxPayloadSize(){return e.MAX_FRAME_SIZE}};const c={GIT_TERMINAL_PROMPT:`0`,GIT_PAGER:`cat`,GIT_AUTHOR_NAME:`blink-so[bot]`,GIT_AUTHOR_EMAIL:`211532188+blink-so[bot]@users.noreply.github.com`,GIT_COMMITTER_NAME:`blink-so[bot]`,GIT_COMMITTER_EMAIL:`211532188+blink-so[bot]@users.noreply.github.com`,GIT_CONFIG_COUNT:`1`,GIT_CONFIG_KEY_0:`credential.https://github.com.helper`,GIT_CONFIG_VALUE_0:`!gh auth git-credential`},l=e=>{if(Array.isArray(e)){let t=r.concat(e);return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}return e instanceof Uint8Array?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e)},u=(e,t)=>{let n=s.encode({streamId:t,type:e.type,flags:e.flags,payload:e.payload});return{buffer:r.from(n.buffer,n.byteOffset,n.byteLength),release:()=>s.releaseBuffer(n)}},d=(e,t)=>s.encode({streamId:t,type:e.type,flags:e.flags,payload:e.payload}),f=e=>new Promise(t=>{if(e.address()){t();return}e.once(`listening`,()=>t())}),p=(e,t)=>{let n=e.address();return typeof n==`object`&&n?n.port:typeof n==`number`?n:t};async function m(o={}){let m=o.logger??console;for(let[e,t]of Object.entries(c))process.env[e]===void 0&&(process.env[e]=t);let h=o.port??(process.env.PORT?parseInt(process.env.PORT,10):22137);if(isNaN(h))throw Error(`PORT environment variable is not a number`);let g=o.host??process.env.HOST??`127.0.0.1`,_;try{_=e(`@lydell/node-pty`)}catch{}typeof Bun<`u`&&(_=void 0);let v=new Set,y=new Map,b=1,x=e=>{for(let t of v)t.ws.send(r.from(e))},S=(e,t)=>{let n=e.serverToClientStream.get(t);n!==void 0&&(e.serverToClientStream.delete(t),e.clientToServerStream.delete(n)),y.delete(t)},C=new i({nodePty:_,send:e=>{try{var t=n();let r;t.u({[Symbol.dispose](){s.releaseBuffer(e)}});try{r=s.decode(e)}catch(e){m.error(`Failed to decode server frame`,e);return}let i=y.get(r.streamId);if(i){let e=i.serverToClientStream.get(r.streamId);if(e===void 0){S(i,r.streamId);return}let{buffer:t,release:n}=u(r,e);try{i.ws.send(t)}finally{n()}(r.type===a.CLOSE||r.type===a.ERROR)&&S(i,r.streamId);return}r.streamId%2==0&&x(e)}catch(e){t.e=e}finally{t.d()}}}),w=()=>{let e=b;return b+=2,e},T=e=>{let t=d(e,e.streamId);try{C.handleMessage(t)}finally{s.releaseBuffer(t)}},E=o.createWebSocketServer?.({port:h,host:g})??new t.default({port:h,host:g});await f(E);let D=p(E,h);return m.info(`Compute server running on ${g}:${D}`),E.on(`connection`,e=>{m.info(`Client connected`);let t={ws:e,clientToServerStream:new Map,serverToClientStream:new Map};v.add(t),e.on(`message`,n=>{if(typeof n==`string`){m.warn(`Ignoring unexpected text message from client`);return}let r=l(n),i;try{i=s.decode(r)}catch(t){m.error(`Failed to decode client frame`,t),e.close(1002,`invalid frame`);return}let o=t.clientToServerStream.get(i.streamId);o===void 0&&(o=w(),t.clientToServerStream.set(i.streamId,o),t.serverToClientStream.set(o,i.streamId),y.set(o,t)),i.streamId=o,T(i),(i.type===a.CLOSE||i.type===a.ERROR)&&S(t,o)});let n=()=>{for(let e of[...t.serverToClientStream.keys()]){let n={streamId:e,type:a.CLOSE,flags:0,payload:new Uint8Array};T(n),S(t,e)}};e.on(`close`,()=>{n(),v.delete(t),m.info(`Client disconnected`)}),e.on(`error`,()=>{n(),v.delete(t)})}),E}export{m as default};
@@ -463,7 +463,7 @@ Slack:
463
463
  1. *ALWAYS* use the \`typecheck_agent\` tool to check for type errors before making changes. NEVER invoke \`tsc\` directly.
464
464
  2. Use the \`message_user_agent\` tool to test the agent after you make changes.
465
465
  </agent_development>
466
- `});let agentsMDContent=templates.scratch[`AGENTS.md`];try{agentsMDContent=await readFile(join$1(options$1.directory,`AGENTS.md`),`utf-8`)}catch{}return converted.unshift({role:`system`,content:agentsMDContent}),streamText({model:getEditModeModelOrThrow(options$1.env),messages:converted,maxOutputTokens:64e3,tools:tools$2,abortSignal,experimental_repairToolCall:({tools:tools$3,toolCall})=>{throw Object.keys(tools$3).includes(toolCall.toolName)?Error(`You have this tool, but you used an invalid input.`):Error(`Invalid tool call. Tool "${toolCall.toolName}" is not available to the EDIT AGENT.`)}})}),{agent,setUserAgentUrl:url$3=>{userAgentUrl=url$3},cleanup:()=>{tsserver&&=(tsserver.close(),void 0)}}}function getEditModeModel(env$8){if(env$8.ANTHROPIC_API_KEY)return createAnthropic({apiKey:env$8.ANTHROPIC_API_KEY}).chat(`claude-sonnet-4-5`);if(env$8.OPENAI_API_KEY)return createOpenAI({apiKey:env$8.OPENAI_API_KEY}).chat(`gpt-5`);if(env$8.AI_GATEWAY_API_KEY)return createGatewayProvider({apiKey:env$8.AI_GATEWAY_API_KEY})(`anthropic/claude-sonnet-4-5`)}function getEditModeModelOrThrow(env$8){let model=getEditModeModel(env$8);if(!model)throw Error(`No API key available for edit mode`);return model}function useEditAgent(options$1){let[clientAndLock,setClientAndLock]=useState(void 0),[error$3,setError]=useState(void 0),[missingApiKey,setMissingApiKey]=useState(!1),editAgentRef=useRef(void 0);return useEffect(()=>{let controller=new AbortController,isCleanup=!1;if(setError(void 0),setClientAndLock(void 0),!getEditModeModel(options$1.env)){setMissingApiKey(!0);return}setMissingApiKey(!1);let lock$1;return(async()=>{editAgentRef.current=createEditAgent({directory:options$1.directory,env:options$1.env,getDevhookUrl:options$1.getDevhookUrl});let port$1=await getRandomPort(),server=editAgentRef.current.agent.serve({port:port$1,host:`127.0.0.1`,apiUrl:options$1.apiServerUrl});controller.signal.addEventListener(`abort`,()=>{try{server.close()}catch{}editAgentRef.current?.cleanup()});let editClient=new Client$3({baseUrl:`http://127.0.0.1:${port$1}`}),editAgentLock=new RWLock;for(lock$1=editAgentLock;!controller.signal.aborted;){try{await editClient.health();break}catch{}await new Promise(resolve$11=>setTimeout(resolve$11,100))}if(controller.signal.aborted)throw controller.signal.reason;setClientAndLock({client:editClient,lock:editAgentLock})})().catch(err=>{isCleanup||setError(err instanceof Error?err:Error(String(err)))}),()=>{isCleanup=!0,(async()=>{try{var _usingCtx$1=_usingCtx();let _writeLock=_usingCtx$1.u(await lock$1?.write());controller.abort()}catch(_$3){_usingCtx$1.e=_$3}finally{_usingCtx$1.d()}})()}},[options$1.directory,options$1.apiServerUrl,options$1.env,options$1.getDevhookUrl]),useMemo(()=>({agent:clientAndLock,error:error$3,missingApiKey,setUserAgentUrl:url$3=>{editAgentRef.current?.setUserAgentUrl(url$3)}}),[clientAndLock,error$3,missingApiKey])}async function getRandomPort(){let server=createServer();return new Promise((resolve$11,reject)=>{server.listen(0,()=>{let port$1=server.address().port;resolve$11(port$1)}).on(`error`,err=>{reject(err)})}).finally(()=>{server.close()})}function useAuth(options$1={}){let{autoCheck=!0,onAuthChange,onLoginUrl,testAuthPath}=options$1,[user,setUser]=useState(),[token$1,setToken]=useState(()=>getAuthToken(testAuthPath)),[error$3,setError]=useState(),onAuthChangeRef=useRef(onAuthChange),onLoginUrlRef=useRef(onLoginUrl);useEffect(()=>{onAuthChangeRef.current=onAuthChange,onLoginUrlRef.current=onLoginUrl},[onAuthChange,onLoginUrl]);let checkAuth=useCallback(async()=>{setError(void 0);try{let currentToken=getAuthToken(testAuthPath);if(setToken(currentToken),!currentToken){setUser(void 0),onAuthChangeRef.current?.(void 0);return}let client=new Client$2({baseURL:`https://blink.so`});client.authToken=currentToken;let userInfo={email:(await client.users.me()).email};setUser(userInfo),onAuthChangeRef.current?.(userInfo)}catch(err){setUser(void 0),setError(err instanceof Error?err.message:String(err)),onAuthChangeRef.current?.(void 0)}},[testAuthPath]),login=useCallback(async()=>{setError(void 0);try{let client=new Client$2,newToken=await client.auth.token((url$3,id)=>{onLoginUrlRef.current?.(url$3,id)});client.authToken=newToken;let userData=await client.users.me();setAuthToken(newToken,testAuthPath),setToken(newToken);let userInfo={email:userData.email};return setUser(userInfo),onAuthChangeRef.current?.(userInfo),userInfo}catch(err){let errorMessage=err instanceof Error?err.message:String(err);throw setError(errorMessage),err}},[testAuthPath]),logout=useCallback(()=>{deleteAuthToken(testAuthPath),setToken(void 0),setUser(void 0),setError(void 0),onAuthChangeRef.current?.(void 0)},[testAuthPath]);return useEffect(()=>{autoCheck&&checkAuth()},[autoCheck,checkAuth]),{user,token:token$1,error:error$3,login,logout}}function useDevMode(options$1){let{directory}=options$1,[autoApprove,setAutoApprove]=useState(!1),[mode,setModeState]=useState(`run`),modeRef=useRef(`run`);useEffect(()=>{modeRef.current=mode},[mode]);let setMode=useCallback(newMode=>{setModeState(newMode),options$1.onModeChange?.(newMode)},[options$1.onModeChange]),toggleMode=useCallback(()=>{setMode(mode===`run`?`edit`:`run`)},[mode,setMode]),{error:buildError,status:buildStatus,result:buildResult,entry:entrypoint}=useBundler({directory,logger:options$1.logger,onBuildStart:options$1.onBuildStart,onBuildSuccess:options$1.onBuildSuccess,onBuildError:options$1.onBuildError}),auth$2=useAuth({autoCheck:!0,onAuthChange:options$1.onAuthChange,onLoginUrl:options$1.onLoginUrl}),dotenv=useDotenv(directory,options$1.logger),env$8=useMemo(()=>{let blinkToken=auth$2.token;return blinkToken?{...dotenv,BLINK_TOKEN:blinkToken}:dotenv},[dotenv,auth$2.token]),lastReportedKeys=useRef(void 0);useEffect(()=>{let keys=Object.keys(env$8);if(keys.length===lastReportedKeys.current||lastReportedKeys.current===void 0){lastReportedKeys.current=keys.length;return}lastReportedKeys.current=keys.length,options$1.onEnvLoaded?.(keys)},[env$8,options$1.onEnvLoaded]);let runAgentRef=useRef(void 0),server=useMemo(()=>createLocalServer({port:0,dataDirectory:join$1(directory,`.blink`),getAgent:()=>runAgentRef.current}),[directory]),{agent,logs:logs$1,error:agentError,capabilities}=useAgent({buildResult,env:env$8,apiServerUrl:server.url}),{agent:editAgent,error:editAgentError,missingApiKey:editModeMissingApiKey,setUserAgentUrl}=useEditAgent({directory,apiServerUrl:server.url,env:env$8,getDevhookUrl:useCallback(()=>{let id=getDevhookID(directory)??createDevhookID(directory);return setDevhookID(id),`https://${id}.blink.host`},[directory])}),[chatId,setChatId]=useState(`00000000-0000-0000-0000-000000000000`);useEffect(()=>{runAgentRef.current=agent},[agent]),useEffect(()=>{agent&&setUserAgentUrl(agent.client.baseUrl),(mode===`run`&&!agent||mode===`edit`&&!editAgent)&&server.getChatManager(chatId)?.stopStreaming()},[agent,editAgent,mode,chatId,server,setUserAgentUrl]);let selectedOptionsRef=useRef(void 0),chat$1=useChat({chatId,agent:mode===`run`?agent:editAgent,chatsDirectory:server.chatsDirectory,serializeMessage:msg=>{let metadata=msg.role===`user`&&selectedOptionsRef.current?{...typeof msg.metadata==`object`&&msg.metadata!==null?msg.metadata:{},options:selectedOptionsRef.current}:msg.metadata;return typeof metadata==`object`&&metadata&&(metadata.__blink_mode=modeRef.current),{id:msg.id??crypto.randomUUID(),created_at:new Date().toISOString(),role:msg.role,parts:msg.parts,mode:modeRef.current,metadata}},filterMessages:msg=>modeRef.current===`edit`?!0:!(isStoredMessageMetadata(msg.metadata)||isLogMessage(msg)||msg.mode===`edit`),onError:error$3=>{options$1.onError?.(`${source_default.red(`⚙ [Chat Error]`)} ${source_default.gray(error$3)}`)}}),lastLogsLength=useRef(0);useEffect(()=>{if(logs$1.length===lastLogsLength.current)return;let currentLength=lastLogsLength.current;for(let log$5 of logs$1.slice(currentLength))options$1.onAgentLog?.(log$5);lastLogsLength.current=logs$1.length},[logs$1,options$1.onAgentLog,chat$1.upsertMessage]);let[chatIds,setChatIds]=useState([]);useEffect(()=>{server.listChats().then(entries$1=>{setChatIds(entries$1.map(e$1=>e$1.key))})},[server]),useEffect(()=>{chatId&&!chatIds.includes(chatId)&&setChatIds(prev=>[...prev,chatId])},[chatId,chatIds]);let[devhookID,setDevhookID]=useState(()=>hasDevhook(directory)?getDevhookID(directory):createDevhookID(directory)),devhook=useDevhook({id:devhookID,directory,logger:options$1.logger,disabled:!capabilities?.request,onRequest:async request$2=>{if(!agent)throw Error(`No agent`);let requestURL=new URL(request$2.url),agentURL=new URL(agent.client.baseUrl);agentURL.pathname=requestURL.pathname,agentURL.search=requestURL.search;try{let response=await fetch(agentURL.toString(),{method:request$2.method,body:request$2.body,headers:request$2.headers,redirect:`manual`,signal:request$2.signal,duplex:`half`});return options$1.onDevhookRequest?.({method:request$2.method,path:requestURL.pathname,status:response.status}),response}catch(err){return options$1.logger.error(`system`,`Error sending request to user's agent:`,err),new Response(`Internal server error`,{status:500})}}});useEffect(()=>{devhook.status!==`connected`||!devhook.url||options$1.onDevhookConnected?.(devhook.url)},[devhook.status,devhook.url]);let{schema:optionsSchema,options:selectedOptions,error:optionsError,setOption:setOption$1}=useOptions({agent:mode===`run`?agent?.client:editAgent?.client,capabilities,messages:chat$1.messages});useEffect(()=>{selectedOptionsRef.current=selectedOptions},[selectedOptions]);let errors=useMemo(()=>{let errorMap=new Map;return agentError&&mode===`run`&&errorMap.set(`agent`,agentError.message),editAgentError&&mode===`edit`&&errorMap.set(`editAgent`,`Edit agent error: ${editAgentError.message}`),optionsError&&errorMap.set(`options`,`Options error: ${optionsError.message}`),errorMap},[agentError,editAgentError,optionsError,mode]),prevErrorsRef=useRef(new Map);useEffect(()=>{let prev=prevErrorsRef.current,current=errors;for(let[key$1,error$3]of current.entries())prev.get(key$1)!==error$3&&options$1.onError?.(error$3);for(let key$1 of prev.keys())current.has(key$1);prevErrorsRef.current=new Map(current)},[errors,options$1.onError]);let needsApproval=useMemo(()=>{let lastMessage=[...chat$1.messages].reverse().find(message=>!(message.role!==`assistant`||message.metadata&&message.metadata.ephemeral));if(!lastMessage)return;let parts=lastMessage.parts.filter(isToolOrDynamicToolUIPart);if(parts.length!==0&&parts.some(part=>isToolApprovalOutput(part.output)&&part.output.outcome===`pending`))return lastMessage},[chat$1.messages]),approvalHandledRef=useRef(void 0),handleApproval=useCallback(async(approved,enableAutoApprove)=>{if(!needsApproval)return;enableAutoApprove&&approved&&setAutoApprove(!0);let lastApprovalMessage=chat$1.messages.reverse().find(msg=>msg.role!==`assistant`||!Array.isArray(msg.parts)?!1:msg.parts.some(part=>`output`in part&&isToolApprovalOutput(part.output)&&part.output.outcome===`pending`));if(!lastApprovalMessage)return;approvalHandledRef.current=lastApprovalMessage.id;let updatedParts=lastApprovalMessage.parts.map(part=>part.output&&isToolApprovalOutput(part.output)&&part.output.outcome===`pending`?{...part,output:{...part.output,outcome:approved?`approved`:`rejected`}}:part);await chat$1.upsertMessage({...lastApprovalMessage,parts:updatedParts}),await chat$1.start()},[needsApproval,chat$1]);useEffect(()=>{autoApprove&&needsApproval&&handleApproval(!0)},[autoApprove,needsApproval,handleApproval]);let newChat=useCallback(()=>{let id=crypto.randomUUID();setChatId(id),setChatIds(prev=>[...prev,id])},[]),switchChat=useCallback(id=>{setChatId(id)},[]),approval=useMemo(()=>{if(needsApproval)return{message:needsApproval,approve:enableAutoApprove=>handleApproval(!0,enableAutoApprove),reject:()=>handleApproval(!1),autoApproveEnabled:autoApprove}},[needsApproval,handleApproval,autoApprove]),tokenUsage=useMemo(()=>{let messages$1=chat$1.messages;if(messages$1.length!==0)for(let i$7=messages$1.length-1;i$7>=0;i$7--){let msg=messages$1[i$7];if(!msg||msg.role!==`assistant`||!msg.metadata||typeof msg.metadata!=`object`||!(`totalUsage`in msg.metadata))continue;let totalUsage=msg.metadata.totalUsage;if(!(!totalUsage||typeof totalUsage!=`object`)&&!(!(`inputTokens`in totalUsage)||!(`outputTokens`in totalUsage)||!(`totalTokens`in totalUsage)))return{inputTokens:totalUsage.inputTokens,outputTokens:totalUsage.outputTokens,totalTokens:totalUsage.totalTokens,cachedInputTokens:totalUsage.cachedInputTokens}}},[chat$1.messages]),showWaitingPlaceholder=useMemo(()=>{if(chat$1.status!==`streaming`)return!1;if(!chat$1.streamingMessage)return!0;let toolParts=chat$1.streamingMessage.parts.filter(isToolOrDynamicToolUIPart);return toolParts.length>0&&toolParts.every(part=>part.state.startsWith(`output-`))},[chat$1.status,chat$1.streamingMessage]);return{mode,setMode,toggleMode,chat:chat$1,chats:chatIds,switchChat,newChat,build:{status:buildStatus,error:buildError,entrypoint},devhook:{connected:devhook.status===`connected`,url:devhook.status===`connected`?devhook.url:void 0},capabilities,options:{schema:optionsSchema,selected:selectedOptions,error:optionsError,setOption:setOption$1},approval,tokenUsage,auth:auth$2,server,showWaitingPlaceholder,editModeMissingApiKey}}function L(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var O$1=L();function G(l$1){O$1=l$1}var E$1={exec:()=>null};function h$1(l$1,e$1=``){let t$1=typeof l$1==`string`?l$1:l$1.source,n$2={replace:(r$2,i$7)=>{let s$3=typeof i$7==`string`?i$7:i$7.source;return s$3=s$3.replace(m.caret,`$1`),t$1=t$1.replace(r$2,s$3),n$2},getRegex:()=>new RegExp(t$1,e$1)};return n$2}var m={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/gi,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:l$1=>RegExp(`^( {0,3}${l$1})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:l$1=>RegExp(`^ {0,${Math.min(3,l$1-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:l$1=>RegExp(`^ {0,${Math.min(3,l$1-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:l$1=>RegExp(`^ {0,${Math.min(3,l$1-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:l$1=>RegExp(`^ {0,${Math.min(3,l$1-1)}}#`),htmlBeginRegex:l$1=>RegExp(`^ {0,${Math.min(3,l$1-1)}}<(?:[a-z].*>|!--)`,`i`)},xe=/^(?:[ \t]*(?:\n|$))+/,be=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Re=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,C=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Oe=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,j=/(?:[*+-]|\d{1,9}[.)])/,se=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ie=h$1(se).replace(/bull/g,j).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,``).getRegex(),Te=h$1(se).replace(/bull/g,j).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),F=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,we=/^[^\n]+/,Q=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,ye=h$1(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,Q).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Pe=h$1(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,j).getRegex(),v=`address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul`,U=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Se=h$1(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))`,`i`).replace(`comment`,U).replace(`tag`,v).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),oe=h$1(F).replace(`hr`,C).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)]) `).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,v).getRegex(),K={blockquote:h$1(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,oe).getRegex(),code:be,def:ye,fences:Re,heading:Oe,hr:C,html:Se,lheading:ie,list:Pe,newline:xe,paragraph:oe,table:E$1,text:we},re=h$1(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,C).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`blockquote`,` {0,3}>`).replace(`code`,`(?: {4}| {0,3} )[^\\n]`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)]) `).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,v).getRegex(),_e={...K,lheading:Te,table:re,paragraph:h$1(F).replace(`hr`,C).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,re).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)]) `).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,v).getRegex()},Le={...K,html:h$1(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,U).replace(/tag/g,`(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b`).getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:E$1,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:h$1(F).replace(`hr`,C).replace(`heading`,` *#{1,6} *[^
466
+ `});let agentsMDContent=templates.scratch[`AGENTS.md`];try{agentsMDContent=await readFile(join$1(options$1.directory,`AGENTS.md`),`utf-8`)}catch{}return converted.unshift({role:`system`,content:agentsMDContent}),streamText({model:getEditModeModelOrThrow(options$1.env),messages:converted,maxOutputTokens:64e3,tools:tools$2,abortSignal,experimental_repairToolCall:({tools:tools$3,toolCall})=>{throw Object.keys(tools$3).includes(toolCall.toolName)?Error(`You have this tool, but you used an invalid input.`):Error(`Invalid tool call. Tool "${toolCall.toolName}" is not available to the EDIT AGENT.`)}})}),{agent,setUserAgentUrl:url$3=>{userAgentUrl=url$3},cleanup:()=>{tsserver&&=(tsserver.close(),void 0)}}}function getEditModeModel(env$8){if(env$8.ANTHROPIC_API_KEY)return createAnthropic({apiKey:env$8.ANTHROPIC_API_KEY,baseURL:env$8.ANTHROPIC_BASE_URL}).chat(`claude-sonnet-4-5`);if(env$8.OPENAI_API_KEY)return createOpenAI({apiKey:env$8.OPENAI_API_KEY,baseURL:env$8.OPENAI_BASE_URL}).chat(`gpt-5`);if(env$8.AI_GATEWAY_API_KEY)return createGatewayProvider({apiKey:env$8.AI_GATEWAY_API_KEY})(`anthropic/claude-sonnet-4-5`)}function getEditModeModelOrThrow(env$8){let model=getEditModeModel(env$8);if(!model)throw Error(`No API key available for edit mode`);return model}function useEditAgent(options$1){let[clientAndLock,setClientAndLock]=useState(void 0),[error$3,setError]=useState(void 0),[missingApiKey,setMissingApiKey]=useState(!1),editAgentRef=useRef(void 0);return useEffect(()=>{let controller=new AbortController,isCleanup=!1;if(setError(void 0),setClientAndLock(void 0),!getEditModeModel(options$1.env)){setMissingApiKey(!0);return}setMissingApiKey(!1);let lock$1;return(async()=>{editAgentRef.current=createEditAgent({directory:options$1.directory,env:options$1.env,getDevhookUrl:options$1.getDevhookUrl});let port$1=await getRandomPort(),server=editAgentRef.current.agent.serve({port:port$1,host:`127.0.0.1`,apiUrl:options$1.apiServerUrl});controller.signal.addEventListener(`abort`,()=>{try{server.close()}catch{}editAgentRef.current?.cleanup()});let editClient=new Client$3({baseUrl:`http://127.0.0.1:${port$1}`}),editAgentLock=new RWLock;for(lock$1=editAgentLock;!controller.signal.aborted;){try{await editClient.health();break}catch{}await new Promise(resolve$11=>setTimeout(resolve$11,100))}if(controller.signal.aborted)throw controller.signal.reason;setClientAndLock({client:editClient,lock:editAgentLock})})().catch(err=>{isCleanup||setError(err instanceof Error?err:Error(String(err)))}),()=>{isCleanup=!0,(async()=>{try{var _usingCtx$1=_usingCtx();let _writeLock=_usingCtx$1.u(await lock$1?.write());controller.abort()}catch(_$3){_usingCtx$1.e=_$3}finally{_usingCtx$1.d()}})()}},[options$1.directory,options$1.apiServerUrl,options$1.env,options$1.getDevhookUrl]),useMemo(()=>({agent:clientAndLock,error:error$3,missingApiKey,setUserAgentUrl:url$3=>{editAgentRef.current?.setUserAgentUrl(url$3)}}),[clientAndLock,error$3,missingApiKey])}async function getRandomPort(){let server=createServer();return new Promise((resolve$11,reject)=>{server.listen(0,()=>{let port$1=server.address().port;resolve$11(port$1)}).on(`error`,err=>{reject(err)})}).finally(()=>{server.close()})}function useAuth(options$1={}){let{autoCheck=!0,onAuthChange,onLoginUrl,testAuthPath}=options$1,[user,setUser]=useState(),[token$1,setToken]=useState(()=>getAuthToken(testAuthPath)),[error$3,setError]=useState(),onAuthChangeRef=useRef(onAuthChange),onLoginUrlRef=useRef(onLoginUrl);useEffect(()=>{onAuthChangeRef.current=onAuthChange,onLoginUrlRef.current=onLoginUrl},[onAuthChange,onLoginUrl]);let checkAuth=useCallback(async()=>{setError(void 0);try{let currentToken=getAuthToken(testAuthPath);if(setToken(currentToken),!currentToken){setUser(void 0),onAuthChangeRef.current?.(void 0);return}let client=new Client$2({baseURL:`https://blink.so`});client.authToken=currentToken;let userInfo={email:(await client.users.me()).email};setUser(userInfo),onAuthChangeRef.current?.(userInfo)}catch(err){setUser(void 0),setError(err instanceof Error?err.message:String(err)),onAuthChangeRef.current?.(void 0)}},[testAuthPath]),login=useCallback(async()=>{setError(void 0);try{let client=new Client$2,newToken=await client.auth.token((url$3,id)=>{onLoginUrlRef.current?.(url$3,id)});client.authToken=newToken;let userData=await client.users.me();setAuthToken(newToken,testAuthPath),setToken(newToken);let userInfo={email:userData.email};return setUser(userInfo),onAuthChangeRef.current?.(userInfo),userInfo}catch(err){let errorMessage=err instanceof Error?err.message:String(err);throw setError(errorMessage),err}},[testAuthPath]),logout=useCallback(()=>{deleteAuthToken(testAuthPath),setToken(void 0),setUser(void 0),setError(void 0),onAuthChangeRef.current?.(void 0)},[testAuthPath]);return useEffect(()=>{autoCheck&&checkAuth()},[autoCheck,checkAuth]),{user,token:token$1,error:error$3,login,logout}}function useDevMode(options$1){let{directory}=options$1,[autoApprove,setAutoApprove]=useState(!1),[mode,setModeState]=useState(`run`),modeRef=useRef(`run`);useEffect(()=>{modeRef.current=mode},[mode]);let setMode=useCallback(newMode=>{setModeState(newMode),options$1.onModeChange?.(newMode)},[options$1.onModeChange]),toggleMode=useCallback(()=>{setMode(mode===`run`?`edit`:`run`)},[mode,setMode]),{error:buildError,status:buildStatus,result:buildResult,entry:entrypoint}=useBundler({directory,logger:options$1.logger,onBuildStart:options$1.onBuildStart,onBuildSuccess:options$1.onBuildSuccess,onBuildError:options$1.onBuildError}),auth$2=useAuth({autoCheck:!0,onAuthChange:options$1.onAuthChange,onLoginUrl:options$1.onLoginUrl}),dotenv=useDotenv(directory,options$1.logger),env$8=useMemo(()=>{let blinkToken=auth$2.token,allEnv={...process.env,...dotenv};return blinkToken&&(allEnv.BLINK_TOKEN=blinkToken),Object.fromEntries(Object.entries(allEnv).filter(([_$3,value])=>value!==void 0))},[dotenv,auth$2.token]),lastReportedKeys=useRef(void 0);useEffect(()=>{let keys=Object.keys(env$8);if(keys.length===lastReportedKeys.current||lastReportedKeys.current===void 0){lastReportedKeys.current=keys.length;return}lastReportedKeys.current=keys.length,options$1.onEnvLoaded?.(keys)},[env$8,options$1.onEnvLoaded]);let runAgentRef=useRef(void 0),server=useMemo(()=>createLocalServer({port:0,dataDirectory:join$1(directory,`.blink`),getAgent:()=>runAgentRef.current}),[directory]),{agent,logs:logs$1,error:agentError,capabilities}=useAgent({buildResult,env:env$8,apiServerUrl:server.url}),{agent:editAgent,error:editAgentError,missingApiKey:editModeMissingApiKey,setUserAgentUrl}=useEditAgent({directory,apiServerUrl:server.url,env:env$8,getDevhookUrl:useCallback(()=>{let id=getDevhookID(directory)??createDevhookID(directory);return setDevhookID(id),`https://${id}.blink.host`},[directory])}),[chatId,setChatId]=useState(`00000000-0000-0000-0000-000000000000`);useEffect(()=>{runAgentRef.current=agent},[agent]),useEffect(()=>{agent&&setUserAgentUrl(agent.client.baseUrl),(mode===`run`&&!agent||mode===`edit`&&!editAgent)&&server.getChatManager(chatId)?.stopStreaming()},[agent,editAgent,mode,chatId,server,setUserAgentUrl]);let selectedOptionsRef=useRef(void 0),chat$1=useChat({chatId,agent:mode===`run`?agent:editAgent,chatsDirectory:server.chatsDirectory,serializeMessage:msg=>{let metadata=msg.role===`user`&&selectedOptionsRef.current?{...typeof msg.metadata==`object`&&msg.metadata!==null?msg.metadata:{},options:selectedOptionsRef.current}:msg.metadata;return typeof metadata==`object`&&metadata&&(metadata.__blink_mode=modeRef.current),{id:msg.id??crypto.randomUUID(),created_at:new Date().toISOString(),role:msg.role,parts:msg.parts,mode:modeRef.current,metadata}},filterMessages:msg=>modeRef.current===`edit`?!0:!(isStoredMessageMetadata(msg.metadata)||isLogMessage(msg)||msg.mode===`edit`),onError:error$3=>{options$1.onError?.(`${source_default.red(`⚙ [Chat Error]`)} ${source_default.gray(error$3)}`)}}),lastLogsLength=useRef(0);useEffect(()=>{if(logs$1.length===lastLogsLength.current)return;let currentLength=lastLogsLength.current;for(let log$5 of logs$1.slice(currentLength))options$1.onAgentLog?.(log$5);lastLogsLength.current=logs$1.length},[logs$1,options$1.onAgentLog,chat$1.upsertMessage]);let[chatIds,setChatIds]=useState([]);useEffect(()=>{server.listChats().then(entries$1=>{setChatIds(entries$1.map(e$1=>e$1.key))})},[server]),useEffect(()=>{chatId&&!chatIds.includes(chatId)&&setChatIds(prev=>[...prev,chatId])},[chatId,chatIds]);let[devhookID,setDevhookID]=useState(()=>hasDevhook(directory)?getDevhookID(directory):createDevhookID(directory)),devhook=useDevhook({id:devhookID,directory,logger:options$1.logger,disabled:!capabilities?.request,onRequest:async request$2=>{if(!agent)throw Error(`No agent`);let requestURL=new URL(request$2.url),agentURL=new URL(agent.client.baseUrl);agentURL.pathname=requestURL.pathname,agentURL.search=requestURL.search;try{let response=await fetch(agentURL.toString(),{method:request$2.method,body:request$2.body,headers:request$2.headers,redirect:`manual`,signal:request$2.signal,duplex:`half`});return options$1.onDevhookRequest?.({method:request$2.method,path:requestURL.pathname,status:response.status}),response}catch(err){return options$1.logger.error(`system`,`Error sending request to user's agent:`,err),new Response(`Internal server error`,{status:500})}}});useEffect(()=>{devhook.status!==`connected`||!devhook.url||options$1.onDevhookConnected?.(devhook.url)},[devhook.status,devhook.url]);let{schema:optionsSchema,options:selectedOptions,error:optionsError,setOption:setOption$1}=useOptions({agent:mode===`run`?agent?.client:editAgent?.client,capabilities,messages:chat$1.messages});useEffect(()=>{selectedOptionsRef.current=selectedOptions},[selectedOptions]);let errors=useMemo(()=>{let errorMap=new Map;return agentError&&mode===`run`&&errorMap.set(`agent`,agentError.message),editAgentError&&mode===`edit`&&errorMap.set(`editAgent`,`Edit agent error: ${editAgentError.message}`),optionsError&&errorMap.set(`options`,`Options error: ${optionsError.message}`),errorMap},[agentError,editAgentError,optionsError,mode]),prevErrorsRef=useRef(new Map);useEffect(()=>{let prev=prevErrorsRef.current,current=errors;for(let[key$1,error$3]of current.entries())prev.get(key$1)!==error$3&&options$1.onError?.(error$3);for(let key$1 of prev.keys())current.has(key$1);prevErrorsRef.current=new Map(current)},[errors,options$1.onError]);let needsApproval=useMemo(()=>{let lastMessage=[...chat$1.messages].reverse().find(message=>!(message.role!==`assistant`||message.metadata&&message.metadata.ephemeral));if(!lastMessage)return;let parts=lastMessage.parts.filter(isToolOrDynamicToolUIPart);if(parts.length!==0&&parts.some(part=>isToolApprovalOutput(part.output)&&part.output.outcome===`pending`))return lastMessage},[chat$1.messages]),approvalHandledRef=useRef(void 0),handleApproval=useCallback(async(approved,enableAutoApprove)=>{if(!needsApproval)return;enableAutoApprove&&approved&&setAutoApprove(!0);let lastApprovalMessage=chat$1.messages.reverse().find(msg=>msg.role!==`assistant`||!Array.isArray(msg.parts)?!1:msg.parts.some(part=>`output`in part&&isToolApprovalOutput(part.output)&&part.output.outcome===`pending`));if(!lastApprovalMessage)return;approvalHandledRef.current=lastApprovalMessage.id;let updatedParts=lastApprovalMessage.parts.map(part=>part.output&&isToolApprovalOutput(part.output)&&part.output.outcome===`pending`?{...part,output:{...part.output,outcome:approved?`approved`:`rejected`}}:part);await chat$1.upsertMessage({...lastApprovalMessage,parts:updatedParts}),await chat$1.start()},[needsApproval,chat$1]);useEffect(()=>{autoApprove&&needsApproval&&handleApproval(!0)},[autoApprove,needsApproval,handleApproval]);let newChat=useCallback(()=>{let id=crypto.randomUUID();setChatId(id),setChatIds(prev=>[...prev,id])},[]),switchChat=useCallback(id=>{setChatId(id)},[]),approval=useMemo(()=>{if(needsApproval)return{message:needsApproval,approve:enableAutoApprove=>handleApproval(!0,enableAutoApprove),reject:()=>handleApproval(!1),autoApproveEnabled:autoApprove}},[needsApproval,handleApproval,autoApprove]),tokenUsage=useMemo(()=>{let messages$1=chat$1.messages;if(messages$1.length!==0)for(let i$7=messages$1.length-1;i$7>=0;i$7--){let msg=messages$1[i$7];if(!msg||msg.role!==`assistant`||!msg.metadata||typeof msg.metadata!=`object`||!(`totalUsage`in msg.metadata))continue;let totalUsage=msg.metadata.totalUsage;if(!(!totalUsage||typeof totalUsage!=`object`)&&!(!(`inputTokens`in totalUsage)||!(`outputTokens`in totalUsage)||!(`totalTokens`in totalUsage)))return{inputTokens:totalUsage.inputTokens,outputTokens:totalUsage.outputTokens,totalTokens:totalUsage.totalTokens,cachedInputTokens:totalUsage.cachedInputTokens}}},[chat$1.messages]),showWaitingPlaceholder=useMemo(()=>{if(chat$1.status!==`streaming`)return!1;if(!chat$1.streamingMessage)return!0;let toolParts=chat$1.streamingMessage.parts.filter(isToolOrDynamicToolUIPart);return toolParts.length>0&&toolParts.every(part=>part.state.startsWith(`output-`))},[chat$1.status,chat$1.streamingMessage]);return{mode,setMode,toggleMode,chat:chat$1,chats:chatIds,switchChat,newChat,build:{status:buildStatus,error:buildError,entrypoint},devhook:{connected:devhook.status===`connected`,url:devhook.status===`connected`?devhook.url:void 0},capabilities,options:{schema:optionsSchema,selected:selectedOptions,error:optionsError,setOption:setOption$1},approval,tokenUsage,auth:auth$2,server,showWaitingPlaceholder,editModeMissingApiKey}}function L(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var O$1=L();function G(l$1){O$1=l$1}var E$1={exec:()=>null};function h$1(l$1,e$1=``){let t$1=typeof l$1==`string`?l$1:l$1.source,n$2={replace:(r$2,i$7)=>{let s$3=typeof i$7==`string`?i$7:i$7.source;return s$3=s$3.replace(m.caret,`$1`),t$1=t$1.replace(r$2,s$3),n$2},getRegex:()=>new RegExp(t$1,e$1)};return n$2}var m={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/gi,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:l$1=>RegExp(`^( {0,3}${l$1})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:l$1=>RegExp(`^ {0,${Math.min(3,l$1-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:l$1=>RegExp(`^ {0,${Math.min(3,l$1-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:l$1=>RegExp(`^ {0,${Math.min(3,l$1-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:l$1=>RegExp(`^ {0,${Math.min(3,l$1-1)}}#`),htmlBeginRegex:l$1=>RegExp(`^ {0,${Math.min(3,l$1-1)}}<(?:[a-z].*>|!--)`,`i`)},xe=/^(?:[ \t]*(?:\n|$))+/,be=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Re=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,C=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Oe=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,j=/(?:[*+-]|\d{1,9}[.)])/,se=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ie=h$1(se).replace(/bull/g,j).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,``).getRegex(),Te=h$1(se).replace(/bull/g,j).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),F=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,we=/^[^\n]+/,Q=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,ye=h$1(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,Q).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Pe=h$1(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,j).getRegex(),v=`address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul`,U=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Se=h$1(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))`,`i`).replace(`comment`,U).replace(`tag`,v).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),oe=h$1(F).replace(`hr`,C).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)]) `).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,v).getRegex(),K={blockquote:h$1(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,oe).getRegex(),code:be,def:ye,fences:Re,heading:Oe,hr:C,html:Se,lheading:ie,list:Pe,newline:xe,paragraph:oe,table:E$1,text:we},re=h$1(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,C).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`blockquote`,` {0,3}>`).replace(`code`,`(?: {4}| {0,3} )[^\\n]`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)]) `).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,v).getRegex(),_e={...K,lheading:Te,table:re,paragraph:h$1(F).replace(`hr`,C).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,re).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)]) `).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,v).getRegex()},Le={...K,html:h$1(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,U).replace(/tag/g,`(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b`).getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:E$1,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:h$1(F).replace(`hr`,C).replace(`heading`,` *#{1,6} *[^
467
467
  ]`).replace(`lheading`,ie).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},Me=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,ze=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,ae=/^( {2,}|\\)\n(?!\s*$)/,Ae=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,D=/[\p{P}\p{S}]/u,W=/[\s\p{P}\p{S}]/u,le=/[^\s\p{P}\p{S}]/u,Ee=h$1(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,W).getRegex(),ue=/(?!~)[\p{P}\p{S}]/u,Ce=/(?!~)[\s\p{P}\p{S}]/u,Ie=/(?:[^\s\p{P}\p{S}]|~)/u,Be=/\[[^\[\]]*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)|`[^`]*?`|<(?! )[^<>]*?>/g,pe=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,qe=h$1(pe,`u`).replace(/punct/g,D).getRegex(),ve=h$1(pe,`u`).replace(/punct/g,ue).getRegex(),ce=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,De=h$1(ce,`gu`).replace(/notPunctSpace/g,le).replace(/punctSpace/g,W).replace(/punct/g,D).getRegex(),He=h$1(ce,`gu`).replace(/notPunctSpace/g,Ie).replace(/punctSpace/g,Ce).replace(/punct/g,ue).getRegex(),Ze=h$1(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,le).replace(/punctSpace/g,W).replace(/punct/g,D).getRegex(),Ge=h$1(/\\(punct)/,`gu`).replace(/punct/g,D).getRegex(),Ne=h$1(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace(`scheme`,/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace(`email`,/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),je=h$1(U).replace(`(?:-->|$)`,`-->`).getRegex(),Fe=h$1(`^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>`).replace(`comment`,je).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),q$1=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`[^`]*`|[^\[\]\\`])*?/,Qe=h$1(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace(`label`,q$1).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),he=h$1(/^!?\[(label)\]\[(ref)\]/).replace(`label`,q$1).replace(`ref`,Q).getRegex(),de=h$1(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,Q).getRegex(),Ue=h$1(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,he).replace(`nolink`,de).getRegex(),X={_backpedal:E$1,anyPunctuation:Ge,autolink:Ne,blockSkip:Be,br:ae,code:ze,del:E$1,emStrongLDelim:qe,emStrongRDelimAst:De,emStrongRDelimUnd:Ze,escape:Me,link:Qe,nolink:de,punctuation:Ee,reflink:he,reflinkSearch:Ue,tag:Fe,text:Ae,url:E$1},Ke={...X,link:h$1(/^!?\[(label)\]\((.*?)\)/).replace(`label`,q$1).getRegex(),reflink:h$1(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,q$1).getRegex()},N={...X,emStrongRDelimAst:He,emStrongLDelim:ve,url:h$1(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,`i`).replace(`email`,/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},We={...N,br:h$1(ae).replace(`{2,}`,`*`).getRegex(),text:h$1(N.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},I$1={normal:K,gfm:_e,pedantic:Le},M={normal:X,gfm:N,breaks:We,pedantic:Ke},Xe={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`},ke=l$1=>Xe[l$1];function w(l$1,e$1){if(e$1){if(m.escapeTest.test(l$1))return l$1.replace(m.escapeReplace,ke)}else if(m.escapeTestNoEncode.test(l$1))return l$1.replace(m.escapeReplaceNoEncode,ke);return l$1}function J(l$1){try{l$1=encodeURI(l$1).replace(m.percentDecode,`%`)}catch{return null}return l$1}function V$1(l$1,e$1){let n$2=l$1.replace(m.findPipe,(i$7,s$3,o$2)=>{let a$2=!1,u$17=s$3;for(;--u$17>=0&&o$2[u$17]===`\\`;)a$2=!a$2;return a$2?`|`:` |`}).split(m.splitPipe),r$2=0;if(n$2[0].trim()||n$2.shift(),n$2.length>0&&!n$2.at(-1)?.trim()&&n$2.pop(),e$1)if(n$2.length>e$1)n$2.splice(e$1);else for(;n$2.length<e$1;)n$2.push(``);for(;r$2<n$2.length;r$2++)n$2[r$2]=n$2[r$2].trim().replace(m.slashPipe,`|`);return n$2}function z$3(l$1,e$1,t$1){let n$2=l$1.length;if(n$2===0)return``;let r$2=0;for(;r$2<n$2;){let i$7=l$1.charAt(n$2-r$2-1);if(i$7===e$1&&!t$1)r$2++;else if(i$7!==e$1&&t$1)r$2++;else break}return l$1.slice(0,n$2-r$2)}function ge(l$1,e$1){if(l$1.indexOf(e$1[1])===-1)return-1;let t$1=0;for(let n$2=0;n$2<l$1.length;n$2++)if(l$1[n$2]===`\\`)n$2++;else if(l$1[n$2]===e$1[0])t$1++;else if(l$1[n$2]===e$1[1]&&(t$1--,t$1<0))return n$2;return t$1>0?-2:-1}function fe(l$1,e$1,t$1,n$2,r$2){let i$7=e$1.href,s$3=e$1.title||null,o$2=l$1[1].replace(r$2.other.outputLinkReplace,`$1`);n$2.state.inLink=!0;let a$2={type:l$1[0].charAt(0)===`!`?`image`:`link`,raw:t$1,href:i$7,title:s$3,text:o$2,tokens:n$2.inlineTokens(o$2)};return n$2.state.inLink=!1,a$2}function Je(l$1,e$1,t$1){let n$2=l$1.match(t$1.other.indentCodeCompensation);if(n$2===null)return e$1;let r$2=n$2[1];return e$1.split(`
468
468
  `).map(i$7=>{let s$3=i$7.match(t$1.other.beginningSpace);if(s$3===null)return i$7;let[o$2]=s$3;return o$2.length>=r$2.length?i$7.slice(r$2.length):i$7}).join(`
469
469
  `)}var y$1=class{options;rules;lexer;constructor(e$1){this.options=e$1||O$1}space(e$1){let t$1=this.rules.block.newline.exec(e$1);if(t$1&&t$1[0].length>0)return{type:`space`,raw:t$1[0]}}code(e$1){let t$1=this.rules.block.code.exec(e$1);if(t$1){let n$2=t$1[0].replace(this.rules.other.codeRemoveIndent,``);return{type:`code`,raw:t$1[0],codeBlockStyle:`indented`,text:this.options.pedantic?n$2:z$3(n$2,`
@@ -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.31`;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(`
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.33`;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-BNkFG8kC.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{};
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-DTCSw4OQ.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-CyGc-fpM.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{};
@@ -1462,4 +1462,4 @@ Slack:
1462
1462
  1. *ALWAYS* use the \`typecheck_agent\` tool to check for type errors before making changes. NEVER invoke \`tsc\` directly.
1463
1463
  2. Use the \`message_user_agent\` tool to test the agent after you make changes.
1464
1464
  </agent_development>
1465
- `});let v=C_.scratch[`AGENTS.md`];try{v=await(0,h.readFile)((0,f.join)(e.directory,`AGENTS.md`),`utf-8`)}catch{}return _.unshift({role:`system`,content:v}),(0,m.streamText)({model:F_(e.env),messages:_,maxOutputTokens:64e3,tools:p,abortSignal:o,experimental_repairToolCall:({tools:e,toolCall:t})=>{throw Object.keys(e).includes(t.toolName)?Error(`You have this tool, but you used an invalid input.`):Error(`Invalid tool call. Tool "${t.toolName}" is not available to the EDIT AGENT.`)}})}),{agent:n,setUserAgentUrl:e=>{r=e},cleanup:()=>{i&&=(i.close(),void 0)}}}function P_(e){if(e.ANTHROPIC_API_KEY)return gt({apiKey:e.ANTHROPIC_API_KEY}).chat(`claude-sonnet-4-5`);if(e.OPENAI_API_KEY)return Ra({apiKey:e.OPENAI_API_KEY}).chat(`gpt-5`);if(e.AI_GATEWAY_API_KEY)return t.createGatewayProvider({apiKey:e.AI_GATEWAY_API_KEY})(`anthropic/claude-sonnet-4-5`)}function F_(e){let t=P_(e);if(!t)throw Error(`No API key available for edit mode`);return t}function I_(e){let[t,n]=(0,_.useState)(void 0),[r,i]=(0,_.useState)(void 0),[a,o]=(0,_.useState)(!1),s=(0,_.useRef)(void 0);return(0,_.useEffect)(()=>{let t=new AbortController,r=!1;if(i(void 0),n(void 0),!P_(e.env)){o(!0);return}o(!1);let a;return(async()=>{s.current=N_({directory:e.directory,env:e.env,getDevhookUrl:e.getDevhookUrl});let r=await L_(),i=s.current.agent.serve({port:r,host:`127.0.0.1`,apiUrl:e.apiServerUrl});t.signal.addEventListener(`abort`,()=>{try{i.close()}catch{}s.current?.cleanup()});let o=new Ys({baseUrl:`http://127.0.0.1:${r}`}),c=new Js;for(a=c;!t.signal.aborted;){try{await o.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(t.signal.aborted)throw t.signal.reason;n({client:o,lock:c})})().catch(e=>{r||i(e instanceof Error?e:Error(String(e)))}),()=>{r=!0,(async()=>{try{var e=Xs();e.u(await a?.write()),t.abort()}catch(t){e.e=t}finally{e.d()}})()}},[e.directory,e.apiServerUrl,e.env,e.getDevhookUrl]),(0,_.useMemo)(()=>({agent:t,error:r,missingApiKey:a,setUserAgentUrl:e=>{s.current?.setUserAgentUrl(e)}}),[t,r,a])}async function L_(){let e=(0,d.createServer)();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function R_(e){let{directory:n}=e,[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)(`run`),s=(0,_.useRef)(`run`);(0,_.useEffect)(()=>{s.current=a},[a]);let c=(0,_.useCallback)(t=>{o(t),e.onModeChange?.(t)},[e.onModeChange]),l=(0,_.useCallback)(()=>{c(a===`run`?`edit`:`run`)},[a,c]),{error:u,status:d,result:p,entry:h}=Th({directory:n,logger:e.logger,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),g=xh({autoCheck:!0,onAuthChange:e.onAuthChange,onLoginUrl:e.onLoginUrl}),v=zg(n,e.logger),y=(0,_.useMemo)(()=>{let e=g.token;return e?{...v,BLINK_TOKEN:e}:v},[v,g.token]),b=(0,_.useRef)(void 0);(0,_.useEffect)(()=>{let t=Object.keys(y);if(t.length===b.current||b.current===void 0){b.current=t.length;return}b.current=t.length,e.onEnvLoaded?.(t)},[y,e.onEnvLoaded]);let x=(0,_.useRef)(void 0),S=(0,_.useMemo)(()=>Mg({port:0,dataDirectory:(0,f.join)(n,`.blink`),getAgent:()=>x.current}),[n]),{agent:C,logs:w,error:T,capabilities:E}=Zs({buildResult:p,env:y,apiServerUrl:S.url}),{agent:D,error:O,missingApiKey:k,setUserAgentUrl:A}=I_({directory:n,apiServerUrl:S.url,env:y,getDevhookUrl:(0,_.useCallback)(()=>{let e=sg(n)??cg(n);return ne(e),`https://${e}.blink.host`},[n])}),[j,M]=(0,_.useState)(`00000000-0000-0000-0000-000000000000`);(0,_.useEffect)(()=>{x.current=C},[C]),(0,_.useEffect)(()=>{C&&A(C.client.baseUrl),(a===`run`&&!C||a===`edit`&&!D)&&S.getChatManager(j)?.stopStreaming()},[C,D,a,j,S,A]);let N=(0,_.useRef)(void 0),P=ig({chatId:j,agent:a===`run`?C:D,chatsDirectory:S.chatsDirectory,serializeMessage:e=>{let t=e.role===`user`&&N.current?{...typeof e.metadata==`object`&&e.metadata!==null?e.metadata:{},options:N.current}:e.metadata;return typeof t==`object`&&t&&(t.__blink_mode=s.current),{id:e.id??crypto.randomUUID(),created_at:new Date().toISOString(),role:e.role,parts:e.parts,mode:s.current,metadata:t}},filterMessages:e=>s.current===`edit`?!0:!(tg(e.metadata)||ng(e)||e.mode===`edit`),onError:t=>{e.onError?.(`${Sf.red(`⚙ [Chat Error]`)} ${Sf.gray(t)}`)}}),F=(0,_.useRef)(0);(0,_.useEffect)(()=>{if(w.length===F.current)return;let t=F.current;for(let n of w.slice(t))e.onAgentLog?.(n);F.current=w.length},[w,e.onAgentLog,P.upsertMessage]);let[ee,te]=(0,_.useState)([]);(0,_.useEffect)(()=>{S.listChats().then(e=>{te(e.map(e=>e.key))})},[S]),(0,_.useEffect)(()=>{j&&!ee.includes(j)&&te(e=>[...e,j])},[j,ee]);let[I,ne]=(0,_.useState)(()=>og(n)?sg(n):cg(n)),L=Pg({id:I,directory:n,logger:e.logger,disabled:!E?.request,onRequest:async t=>{if(!C)throw Error(`No agent`);let n=new URL(t.url),r=new URL(C.client.baseUrl);r.pathname=n.pathname,r.search=n.search;try{let i=await fetch(r.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:`manual`,signal:t.signal,duplex:`half`});return e.onDevhookRequest?.({method:t.method,path:n.pathname,status:i.status}),i}catch(t){return e.logger.error(`system`,`Error sending request to user's agent:`,t),new Response(`Internal server error`,{status:500})}}});(0,_.useEffect)(()=>{L.status!==`connected`||!L.url||e.onDevhookConnected?.(L.url)},[L.status,L.url]);let{schema:re,options:R,error:z,setOption:B}=Ng({agent:a===`run`?C?.client:D?.client,capabilities:E,messages:P.messages});(0,_.useEffect)(()=>{N.current=R},[R]);let ie=(0,_.useMemo)(()=>{let e=new Map;return T&&a===`run`&&e.set(`agent`,T.message),O&&a===`edit`&&e.set(`editAgent`,`Edit agent error: ${O.message}`),z&&e.set(`options`,`Options error: ${z.message}`),e},[T,O,z,a]),ae=(0,_.useRef)(new Map);(0,_.useEffect)(()=>{let t=ae.current,n=ie;for(let[r,i]of n.entries())t.get(r)!==i&&e.onError?.(i);for(let e of t.keys())n.has(e);ae.current=new Map(n)},[ie,e.onError]);let oe=(0,_.useMemo)(()=>{let e=[...P.messages].reverse().find(e=>!(e.role!==`assistant`||e.metadata&&e.metadata.ephemeral));if(!e)return;let n=e.parts.filter(m.isToolOrDynamicToolUIPart);if(n.length!==0&&n.some(e=>t.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`))return e},[P.messages]),se=(0,_.useRef)(void 0),ce=(0,_.useCallback)(async(e,n)=>{if(!oe)return;n&&e&&i(!0);let r=P.messages.reverse().find(e=>e.role!==`assistant`||!Array.isArray(e.parts)?!1:e.parts.some(e=>`output`in e&&t.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`));if(!r)return;se.current=r.id;let a=r.parts.map(n=>n.output&&t.isToolApprovalOutput(n.output)&&n.output.outcome===`pending`?{...n,output:{...n.output,outcome:e?`approved`:`rejected`}}:n);await P.upsertMessage({...r,parts:a}),await P.start()},[oe,P]);(0,_.useEffect)(()=>{r&&oe&&ce(!0)},[r,oe,ce]);let V=(0,_.useCallback)(()=>{let e=crypto.randomUUID();M(e),te(t=>[...t,e])},[]),le=(0,_.useCallback)(e=>{M(e)},[]),ue=(0,_.useMemo)(()=>{if(oe)return{message:oe,approve:e=>ce(!0,e),reject:()=>ce(!1),autoApproveEnabled:r}},[oe,ce,r]),de=(0,_.useMemo)(()=>{let e=P.messages;if(e.length!==0)for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n||n.role!==`assistant`||!n.metadata||typeof n.metadata!=`object`||!(`totalUsage`in n.metadata))continue;let r=n.metadata.totalUsage;if(!(!r||typeof r!=`object`)&&!(!(`inputTokens`in r)||!(`outputTokens`in r)||!(`totalTokens`in r)))return{inputTokens:r.inputTokens,outputTokens:r.outputTokens,totalTokens:r.totalTokens,cachedInputTokens:r.cachedInputTokens}}},[P.messages]),fe=(0,_.useMemo)(()=>{if(P.status!==`streaming`)return!1;if(!P.streamingMessage)return!0;let e=P.streamingMessage.parts.filter(m.isToolOrDynamicToolUIPart);return e.length>0&&e.every(e=>e.state.startsWith(`output-`))},[P.status,P.streamingMessage]);return{mode:a,setMode:c,toggleMode:l,chat:P,chats:ee,switchChat:le,newChat:V,build:{status:d,error:u,entrypoint:h},devhook:{connected:L.status===`connected`,url:L.status===`connected`?L.url:void 0},capabilities:E,options:{schema:re,selected:R,error:z,setOption:B},approval:ue,tokenUsage:de,auth:g,server:S,showWaitingPlaceholder:fe,editModeMissingApiKey:k}}exports.Logger=Ch,exports.LoggerContext=wh,exports.useAgent=Zs,exports.useAuth=xh,exports.useBundler=Th,exports.useChat=ig,exports.useDevMode=R_,exports.useDevhook=Pg,exports.useDotenv=zg,exports.useEditAgent=I_,exports.useOptions=Ng;
1465
+ `});let v=C_.scratch[`AGENTS.md`];try{v=await(0,h.readFile)((0,f.join)(e.directory,`AGENTS.md`),`utf-8`)}catch{}return _.unshift({role:`system`,content:v}),(0,m.streamText)({model:F_(e.env),messages:_,maxOutputTokens:64e3,tools:p,abortSignal:o,experimental_repairToolCall:({tools:e,toolCall:t})=>{throw Object.keys(e).includes(t.toolName)?Error(`You have this tool, but you used an invalid input.`):Error(`Invalid tool call. Tool "${t.toolName}" is not available to the EDIT AGENT.`)}})}),{agent:n,setUserAgentUrl:e=>{r=e},cleanup:()=>{i&&=(i.close(),void 0)}}}function P_(e){if(e.ANTHROPIC_API_KEY)return gt({apiKey:e.ANTHROPIC_API_KEY,baseURL:e.ANTHROPIC_BASE_URL}).chat(`claude-sonnet-4-5`);if(e.OPENAI_API_KEY)return Ra({apiKey:e.OPENAI_API_KEY,baseURL:e.OPENAI_BASE_URL}).chat(`gpt-5`);if(e.AI_GATEWAY_API_KEY)return t.createGatewayProvider({apiKey:e.AI_GATEWAY_API_KEY})(`anthropic/claude-sonnet-4-5`)}function F_(e){let t=P_(e);if(!t)throw Error(`No API key available for edit mode`);return t}function I_(e){let[t,n]=(0,_.useState)(void 0),[r,i]=(0,_.useState)(void 0),[a,o]=(0,_.useState)(!1),s=(0,_.useRef)(void 0);return(0,_.useEffect)(()=>{let t=new AbortController,r=!1;if(i(void 0),n(void 0),!P_(e.env)){o(!0);return}o(!1);let a;return(async()=>{s.current=N_({directory:e.directory,env:e.env,getDevhookUrl:e.getDevhookUrl});let r=await L_(),i=s.current.agent.serve({port:r,host:`127.0.0.1`,apiUrl:e.apiServerUrl});t.signal.addEventListener(`abort`,()=>{try{i.close()}catch{}s.current?.cleanup()});let o=new Ys({baseUrl:`http://127.0.0.1:${r}`}),c=new Js;for(a=c;!t.signal.aborted;){try{await o.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(t.signal.aborted)throw t.signal.reason;n({client:o,lock:c})})().catch(e=>{r||i(e instanceof Error?e:Error(String(e)))}),()=>{r=!0,(async()=>{try{var e=Xs();e.u(await a?.write()),t.abort()}catch(t){e.e=t}finally{e.d()}})()}},[e.directory,e.apiServerUrl,e.env,e.getDevhookUrl]),(0,_.useMemo)(()=>({agent:t,error:r,missingApiKey:a,setUserAgentUrl:e=>{s.current?.setUserAgentUrl(e)}}),[t,r,a])}async function L_(){let e=(0,d.createServer)();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function R_(e){let{directory:n}=e,[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)(`run`),s=(0,_.useRef)(`run`);(0,_.useEffect)(()=>{s.current=a},[a]);let c=(0,_.useCallback)(t=>{o(t),e.onModeChange?.(t)},[e.onModeChange]),l=(0,_.useCallback)(()=>{c(a===`run`?`edit`:`run`)},[a,c]),{error:u,status:d,result:p,entry:h}=Th({directory:n,logger:e.logger,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),g=xh({autoCheck:!0,onAuthChange:e.onAuthChange,onLoginUrl:e.onLoginUrl}),v=zg(n,e.logger),y=(0,_.useMemo)(()=>{let e=g.token,t={...process.env,...v};return e&&(t.BLINK_TOKEN=e),Object.fromEntries(Object.entries(t).filter(([e,t])=>t!==void 0))},[v,g.token]),b=(0,_.useRef)(void 0);(0,_.useEffect)(()=>{let t=Object.keys(y);if(t.length===b.current||b.current===void 0){b.current=t.length;return}b.current=t.length,e.onEnvLoaded?.(t)},[y,e.onEnvLoaded]);let x=(0,_.useRef)(void 0),S=(0,_.useMemo)(()=>Mg({port:0,dataDirectory:(0,f.join)(n,`.blink`),getAgent:()=>x.current}),[n]),{agent:C,logs:w,error:T,capabilities:E}=Zs({buildResult:p,env:y,apiServerUrl:S.url}),{agent:D,error:O,missingApiKey:k,setUserAgentUrl:A}=I_({directory:n,apiServerUrl:S.url,env:y,getDevhookUrl:(0,_.useCallback)(()=>{let e=sg(n)??cg(n);return ne(e),`https://${e}.blink.host`},[n])}),[j,M]=(0,_.useState)(`00000000-0000-0000-0000-000000000000`);(0,_.useEffect)(()=>{x.current=C},[C]),(0,_.useEffect)(()=>{C&&A(C.client.baseUrl),(a===`run`&&!C||a===`edit`&&!D)&&S.getChatManager(j)?.stopStreaming()},[C,D,a,j,S,A]);let N=(0,_.useRef)(void 0),P=ig({chatId:j,agent:a===`run`?C:D,chatsDirectory:S.chatsDirectory,serializeMessage:e=>{let t=e.role===`user`&&N.current?{...typeof e.metadata==`object`&&e.metadata!==null?e.metadata:{},options:N.current}:e.metadata;return typeof t==`object`&&t&&(t.__blink_mode=s.current),{id:e.id??crypto.randomUUID(),created_at:new Date().toISOString(),role:e.role,parts:e.parts,mode:s.current,metadata:t}},filterMessages:e=>s.current===`edit`?!0:!(tg(e.metadata)||ng(e)||e.mode===`edit`),onError:t=>{e.onError?.(`${Sf.red(`⚙ [Chat Error]`)} ${Sf.gray(t)}`)}}),F=(0,_.useRef)(0);(0,_.useEffect)(()=>{if(w.length===F.current)return;let t=F.current;for(let n of w.slice(t))e.onAgentLog?.(n);F.current=w.length},[w,e.onAgentLog,P.upsertMessage]);let[ee,te]=(0,_.useState)([]);(0,_.useEffect)(()=>{S.listChats().then(e=>{te(e.map(e=>e.key))})},[S]),(0,_.useEffect)(()=>{j&&!ee.includes(j)&&te(e=>[...e,j])},[j,ee]);let[I,ne]=(0,_.useState)(()=>og(n)?sg(n):cg(n)),L=Pg({id:I,directory:n,logger:e.logger,disabled:!E?.request,onRequest:async t=>{if(!C)throw Error(`No agent`);let n=new URL(t.url),r=new URL(C.client.baseUrl);r.pathname=n.pathname,r.search=n.search;try{let i=await fetch(r.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:`manual`,signal:t.signal,duplex:`half`});return e.onDevhookRequest?.({method:t.method,path:n.pathname,status:i.status}),i}catch(t){return e.logger.error(`system`,`Error sending request to user's agent:`,t),new Response(`Internal server error`,{status:500})}}});(0,_.useEffect)(()=>{L.status!==`connected`||!L.url||e.onDevhookConnected?.(L.url)},[L.status,L.url]);let{schema:re,options:R,error:z,setOption:B}=Ng({agent:a===`run`?C?.client:D?.client,capabilities:E,messages:P.messages});(0,_.useEffect)(()=>{N.current=R},[R]);let ie=(0,_.useMemo)(()=>{let e=new Map;return T&&a===`run`&&e.set(`agent`,T.message),O&&a===`edit`&&e.set(`editAgent`,`Edit agent error: ${O.message}`),z&&e.set(`options`,`Options error: ${z.message}`),e},[T,O,z,a]),ae=(0,_.useRef)(new Map);(0,_.useEffect)(()=>{let t=ae.current,n=ie;for(let[r,i]of n.entries())t.get(r)!==i&&e.onError?.(i);for(let e of t.keys())n.has(e);ae.current=new Map(n)},[ie,e.onError]);let oe=(0,_.useMemo)(()=>{let e=[...P.messages].reverse().find(e=>!(e.role!==`assistant`||e.metadata&&e.metadata.ephemeral));if(!e)return;let n=e.parts.filter(m.isToolOrDynamicToolUIPart);if(n.length!==0&&n.some(e=>t.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`))return e},[P.messages]),se=(0,_.useRef)(void 0),ce=(0,_.useCallback)(async(e,n)=>{if(!oe)return;n&&e&&i(!0);let r=P.messages.reverse().find(e=>e.role!==`assistant`||!Array.isArray(e.parts)?!1:e.parts.some(e=>`output`in e&&t.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`));if(!r)return;se.current=r.id;let a=r.parts.map(n=>n.output&&t.isToolApprovalOutput(n.output)&&n.output.outcome===`pending`?{...n,output:{...n.output,outcome:e?`approved`:`rejected`}}:n);await P.upsertMessage({...r,parts:a}),await P.start()},[oe,P]);(0,_.useEffect)(()=>{r&&oe&&ce(!0)},[r,oe,ce]);let V=(0,_.useCallback)(()=>{let e=crypto.randomUUID();M(e),te(t=>[...t,e])},[]),le=(0,_.useCallback)(e=>{M(e)},[]),ue=(0,_.useMemo)(()=>{if(oe)return{message:oe,approve:e=>ce(!0,e),reject:()=>ce(!1),autoApproveEnabled:r}},[oe,ce,r]),de=(0,_.useMemo)(()=>{let e=P.messages;if(e.length!==0)for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n||n.role!==`assistant`||!n.metadata||typeof n.metadata!=`object`||!(`totalUsage`in n.metadata))continue;let r=n.metadata.totalUsage;if(!(!r||typeof r!=`object`)&&!(!(`inputTokens`in r)||!(`outputTokens`in r)||!(`totalTokens`in r)))return{inputTokens:r.inputTokens,outputTokens:r.outputTokens,totalTokens:r.totalTokens,cachedInputTokens:r.cachedInputTokens}}},[P.messages]),fe=(0,_.useMemo)(()=>{if(P.status!==`streaming`)return!1;if(!P.streamingMessage)return!0;let e=P.streamingMessage.parts.filter(m.isToolOrDynamicToolUIPart);return e.length>0&&e.every(e=>e.state.startsWith(`output-`))},[P.status,P.streamingMessage]);return{mode:a,setMode:c,toggleMode:l,chat:P,chats:ee,switchChat:le,newChat:V,build:{status:d,error:u,entrypoint:h},devhook:{connected:L.status===`connected`,url:L.status===`connected`?L.url:void 0},capabilities:E,options:{schema:re,selected:R,error:z,setOption:B},approval:ue,tokenUsage:de,auth:g,server:S,showWaitingPlaceholder:fe,editModeMissingApiKey:k}}exports.Logger=Ch,exports.LoggerContext=wh,exports.useAgent=Zs,exports.useAuth=xh,exports.useBundler=Th,exports.useChat=ig,exports.useDevMode=R_,exports.useDevhook=Pg,exports.useDotenv=zg,exports.useEditAgent=I_,exports.useOptions=Ng;
@@ -1373,4 +1373,4 @@ Slack:
1373
1373
  1. *ALWAYS* use the \`typecheck_agent\` tool to check for type errors before making changes. NEVER invoke \`tsc\` directly.
1374
1374
  2. Use the \`message_user_agent\` tool to test the agent after you make changes.
1375
1375
  </agent_development>
1376
- `});let p=gh.scratch[`AGENTS.md`];try{p=await xe(ue(e.directory,`AGENTS.md`),`utf-8`)}catch{}return f.unshift({role:`system`,content:p}),ye({model:Oh(e.env),messages:f,maxOutputTokens:64e3,tools:d,abortSignal:a,experimental_repairToolCall:({tools:e,toolCall:t})=>{throw Object.keys(e).includes(t.toolName)?Error(`You have this tool, but you used an invalid input.`):Error(`Invalid tool call. Tool "${t.toolName}" is not available to the EDIT AGENT.`)}})}),{agent:t,setUserAgentUrl:e=>{n=e},cleanup:()=>{r&&=(r.close(),void 0)}}}function Dh(e){if(e.ANTHROPIC_API_KEY)return _n({apiKey:e.ANTHROPIC_API_KEY}).chat(`claude-sonnet-4-5`);if(e.OPENAI_API_KEY)return jo({apiKey:e.OPENAI_API_KEY}).chat(`gpt-5`);if(e.AI_GATEWAY_API_KEY)return C({apiKey:e.AI_GATEWAY_API_KEY})(`anthropic/claude-sonnet-4-5`)}function Oh(e){let t=Dh(e);if(!t)throw Error(`No API key available for edit mode`);return t}function kh(e){let[t,n]=G(void 0),[r,i]=G(void 0),[a,o]=G(!1),s=W(void 0);return U(()=>{let t=new AbortController,r=!1;if(i(void 0),n(void 0),!Dh(e.env)){o(!0);return}o(!1);let a;return(async()=>{s.current=Eh({directory:e.directory,env:e.env,getDevhookUrl:e.getDevhookUrl});let r=await Ah(),i=s.current.agent.serve({port:r,host:`127.0.0.1`,apiUrl:e.apiServerUrl});t.signal.addEventListener(`abort`,()=>{try{i.close()}catch{}s.current?.cleanup()});let o=new Ec({baseUrl:`http://127.0.0.1:${r}`}),c=new Tc;for(a=c;!t.signal.aborted;){try{await o.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(t.signal.aborted)throw t.signal.reason;n({client:o,lock:c})})().catch(e=>{r||i(e instanceof Error?e:Error(String(e)))}),()=>{r=!0,(async()=>{try{var e=Dc();e.u(await a?.write()),t.abort()}catch(t){e.e=t}finally{e.d()}})()}},[e.directory,e.apiServerUrl,e.env,e.getDevhookUrl]),Te(()=>({agent:t,error:r,missingApiKey:a,setUserAgentUrl:e=>{s.current?.setUserAgentUrl(e)}}),[t,r,a])}async function Ah(){let e=le();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function jh(e){let{directory:t}=e,[n,r]=G(!1),[i,a]=G(`run`),o=W(`run`);U(()=>{o.current=i},[i]);let s=H(t=>{a(t),e.onModeChange?.(t)},[e.onModeChange]),c=H(()=>{s(i===`run`?`edit`:`run`)},[i,s]),{error:l,status:u,result:d,entry:f}=kp({directory:t,logger:e.logger,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),p=Tp({autoCheck:!0,onAuthChange:e.onAuthChange,onLoginUrl:e.onLoginUrl}),m=Bm(t,e.logger),h=Te(()=>{let e=p.token;return e?{...m,BLINK_TOKEN:e}:m},[m,p.token]),g=W(void 0);U(()=>{let t=Object.keys(h);if(t.length===g.current||g.current===void 0){g.current=t.length;return}g.current=t.length,e.onEnvLoaded?.(t)},[h,e.onEnvLoaded]);let _=W(void 0),v=Te(()=>Pm({port:0,dataDirectory:ue(t,`.blink`),getAgent:()=>_.current}),[t]),{agent:y,logs:b,error:x,capabilities:S}=Oc({buildResult:d,env:h,apiServerUrl:v.url}),{agent:C,error:w,missingApiKey:T,setUserAgentUrl:D}=kh({directory:t,apiServerUrl:v.url,env:h,getDevhookUrl:H(()=>{let e=um(t)??dm(t);return P(e),`https://${e}.blink.host`},[t])}),[O,k]=G(`00000000-0000-0000-0000-000000000000`);U(()=>{_.current=y},[y]),U(()=>{y&&D(y.client.baseUrl),(i===`run`&&!y||i===`edit`&&!C)&&v.getChatManager(O)?.stopStreaming()},[y,C,i,O,v,D]);let A=W(void 0),j=sm({chatId:O,agent:i===`run`?y:C,chatsDirectory:v.chatsDirectory,serializeMessage:e=>{let t=e.role===`user`&&A.current?{...typeof e.metadata==`object`&&e.metadata!==null?e.metadata:{},options:A.current}:e.metadata;return typeof t==`object`&&t&&(t.__blink_mode=o.current),{id:e.id??crypto.randomUUID(),created_at:new Date().toISOString(),role:e.role,parts:e.parts,mode:o.current,metadata:t}},filterMessages:e=>o.current===`edit`?!0:!(im(e.metadata)||am(e)||e.mode===`edit`),onError:t=>{e.onError?.(`${cf.red(`⚙ [Chat Error]`)} ${cf.gray(t)}`)}}),M=W(0);U(()=>{if(b.length===M.current)return;let t=M.current;for(let n of b.slice(t))e.onAgentLog?.(n);M.current=b.length},[b,e.onAgentLog,j.upsertMessage]);let[N,ee]=G([]);U(()=>{v.listChats().then(e=>{ee(e.map(e=>e.key))})},[v]),U(()=>{O&&!N.includes(O)&&ee(e=>[...e,O])},[O,N]);let[te,P]=G(()=>lm(t)?um(t):dm(t)),F=Im({id:te,directory:t,logger:e.logger,disabled:!S?.request,onRequest:async t=>{if(!y)throw Error(`No agent`);let n=new URL(t.url),r=new URL(y.client.baseUrl);r.pathname=n.pathname,r.search=n.search;try{let i=await fetch(r.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:`manual`,signal:t.signal,duplex:`half`});return e.onDevhookRequest?.({method:t.method,path:n.pathname,status:i.status}),i}catch(t){return e.logger.error(`system`,`Error sending request to user's agent:`,t),new Response(`Internal server error`,{status:500})}}});U(()=>{F.status!==`connected`||!F.url||e.onDevhookConnected?.(F.url)},[F.status,F.url]);let{schema:I,options:ne,error:L,setOption:re}=Fm({agent:i===`run`?y?.client:C?.client,capabilities:S,messages:j.messages});U(()=>{A.current=ne},[ne]);let R=Te(()=>{let e=new Map;return x&&i===`run`&&e.set(`agent`,x.message),w&&i===`edit`&&e.set(`editAgent`,`Edit agent error: ${w.message}`),L&&e.set(`options`,`Options error: ${L.message}`),e},[x,w,L,i]),ie=W(new Map);U(()=>{let t=ie.current,n=R;for(let[r,i]of n.entries())t.get(r)!==i&&e.onError?.(i);for(let e of t.keys())n.has(e);ie.current=new Map(n)},[R,e.onError]);let z=Te(()=>{let e=[...j.messages].reverse().find(e=>!(e.role!==`assistant`||e.metadata&&e.metadata.ephemeral));if(!e)return;let t=e.parts.filter(_e);if(t.length!==0&&t.some(e=>E(e.output)&&e.output.outcome===`pending`))return e},[j.messages]),ae=W(void 0),oe=H(async(e,t)=>{if(!z)return;t&&e&&r(!0);let n=j.messages.reverse().find(e=>e.role!==`assistant`||!Array.isArray(e.parts)?!1:e.parts.some(e=>`output`in e&&E(e.output)&&e.output.outcome===`pending`));if(!n)return;ae.current=n.id;let i=n.parts.map(t=>t.output&&E(t.output)&&t.output.outcome===`pending`?{...t,output:{...t.output,outcome:e?`approved`:`rejected`}}:t);await j.upsertMessage({...n,parts:i}),await j.start()},[z,j]);U(()=>{n&&z&&oe(!0)},[n,z,oe]);let se=H(()=>{let e=crypto.randomUUID();k(e),ee(t=>[...t,e])},[]),ce=H(e=>{k(e)},[]),le=Te(()=>{if(z)return{message:z,approve:e=>oe(!0,e),reject:()=>oe(!1),autoApproveEnabled:n}},[z,oe,n]),B=Te(()=>{let e=j.messages;if(e.length!==0)for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n||n.role!==`assistant`||!n.metadata||typeof n.metadata!=`object`||!(`totalUsage`in n.metadata))continue;let r=n.metadata.totalUsage;if(!(!r||typeof r!=`object`)&&!(!(`inputTokens`in r)||!(`outputTokens`in r)||!(`totalTokens`in r)))return{inputTokens:r.inputTokens,outputTokens:r.outputTokens,totalTokens:r.totalTokens,cachedInputTokens:r.cachedInputTokens}}},[j.messages]),de=Te(()=>{if(j.status!==`streaming`)return!1;if(!j.streamingMessage)return!0;let e=j.streamingMessage.parts.filter(_e);return e.length>0&&e.every(e=>e.state.startsWith(`output-`))},[j.status,j.streamingMessage]);return{mode:i,setMode:s,toggleMode:c,chat:j,chats:N,switchChat:ce,newChat:se,build:{status:u,error:l,entrypoint:f},devhook:{connected:F.status===`connected`,url:F.status===`connected`?F.url:void 0},capabilities:S,options:{schema:I,selected:ne,error:L,setOption:re},approval:le,tokenUsage:B,auth:p,server:v,showWaitingPlaceholder:de,editModeMissingApiKey:T}}export{Dp as Logger,Op as LoggerContext,Oc as useAgent,Tp as useAuth,kp as useBundler,sm as useChat,jh as useDevMode,Im as useDevhook,Bm as useDotenv,kh as useEditAgent,Fm as useOptions};
1376
+ `});let p=gh.scratch[`AGENTS.md`];try{p=await xe(ue(e.directory,`AGENTS.md`),`utf-8`)}catch{}return f.unshift({role:`system`,content:p}),ye({model:Oh(e.env),messages:f,maxOutputTokens:64e3,tools:d,abortSignal:a,experimental_repairToolCall:({tools:e,toolCall:t})=>{throw Object.keys(e).includes(t.toolName)?Error(`You have this tool, but you used an invalid input.`):Error(`Invalid tool call. Tool "${t.toolName}" is not available to the EDIT AGENT.`)}})}),{agent:t,setUserAgentUrl:e=>{n=e},cleanup:()=>{r&&=(r.close(),void 0)}}}function Dh(e){if(e.ANTHROPIC_API_KEY)return _n({apiKey:e.ANTHROPIC_API_KEY,baseURL:e.ANTHROPIC_BASE_URL}).chat(`claude-sonnet-4-5`);if(e.OPENAI_API_KEY)return jo({apiKey:e.OPENAI_API_KEY,baseURL:e.OPENAI_BASE_URL}).chat(`gpt-5`);if(e.AI_GATEWAY_API_KEY)return C({apiKey:e.AI_GATEWAY_API_KEY})(`anthropic/claude-sonnet-4-5`)}function Oh(e){let t=Dh(e);if(!t)throw Error(`No API key available for edit mode`);return t}function kh(e){let[t,n]=G(void 0),[r,i]=G(void 0),[a,o]=G(!1),s=W(void 0);return U(()=>{let t=new AbortController,r=!1;if(i(void 0),n(void 0),!Dh(e.env)){o(!0);return}o(!1);let a;return(async()=>{s.current=Eh({directory:e.directory,env:e.env,getDevhookUrl:e.getDevhookUrl});let r=await Ah(),i=s.current.agent.serve({port:r,host:`127.0.0.1`,apiUrl:e.apiServerUrl});t.signal.addEventListener(`abort`,()=>{try{i.close()}catch{}s.current?.cleanup()});let o=new Ec({baseUrl:`http://127.0.0.1:${r}`}),c=new Tc;for(a=c;!t.signal.aborted;){try{await o.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(t.signal.aborted)throw t.signal.reason;n({client:o,lock:c})})().catch(e=>{r||i(e instanceof Error?e:Error(String(e)))}),()=>{r=!0,(async()=>{try{var e=Dc();e.u(await a?.write()),t.abort()}catch(t){e.e=t}finally{e.d()}})()}},[e.directory,e.apiServerUrl,e.env,e.getDevhookUrl]),Te(()=>({agent:t,error:r,missingApiKey:a,setUserAgentUrl:e=>{s.current?.setUserAgentUrl(e)}}),[t,r,a])}async function Ah(){let e=le();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function jh(e){let{directory:t}=e,[n,r]=G(!1),[i,a]=G(`run`),o=W(`run`);U(()=>{o.current=i},[i]);let s=H(t=>{a(t),e.onModeChange?.(t)},[e.onModeChange]),c=H(()=>{s(i===`run`?`edit`:`run`)},[i,s]),{error:l,status:u,result:d,entry:f}=kp({directory:t,logger:e.logger,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),p=Tp({autoCheck:!0,onAuthChange:e.onAuthChange,onLoginUrl:e.onLoginUrl}),m=Bm(t,e.logger),h=Te(()=>{let e=p.token,t={...process.env,...m};return e&&(t.BLINK_TOKEN=e),Object.fromEntries(Object.entries(t).filter(([e,t])=>t!==void 0))},[m,p.token]),g=W(void 0);U(()=>{let t=Object.keys(h);if(t.length===g.current||g.current===void 0){g.current=t.length;return}g.current=t.length,e.onEnvLoaded?.(t)},[h,e.onEnvLoaded]);let _=W(void 0),v=Te(()=>Pm({port:0,dataDirectory:ue(t,`.blink`),getAgent:()=>_.current}),[t]),{agent:y,logs:b,error:x,capabilities:S}=Oc({buildResult:d,env:h,apiServerUrl:v.url}),{agent:C,error:w,missingApiKey:T,setUserAgentUrl:D}=kh({directory:t,apiServerUrl:v.url,env:h,getDevhookUrl:H(()=>{let e=um(t)??dm(t);return P(e),`https://${e}.blink.host`},[t])}),[O,k]=G(`00000000-0000-0000-0000-000000000000`);U(()=>{_.current=y},[y]),U(()=>{y&&D(y.client.baseUrl),(i===`run`&&!y||i===`edit`&&!C)&&v.getChatManager(O)?.stopStreaming()},[y,C,i,O,v,D]);let A=W(void 0),j=sm({chatId:O,agent:i===`run`?y:C,chatsDirectory:v.chatsDirectory,serializeMessage:e=>{let t=e.role===`user`&&A.current?{...typeof e.metadata==`object`&&e.metadata!==null?e.metadata:{},options:A.current}:e.metadata;return typeof t==`object`&&t&&(t.__blink_mode=o.current),{id:e.id??crypto.randomUUID(),created_at:new Date().toISOString(),role:e.role,parts:e.parts,mode:o.current,metadata:t}},filterMessages:e=>o.current===`edit`?!0:!(im(e.metadata)||am(e)||e.mode===`edit`),onError:t=>{e.onError?.(`${cf.red(`⚙ [Chat Error]`)} ${cf.gray(t)}`)}}),M=W(0);U(()=>{if(b.length===M.current)return;let t=M.current;for(let n of b.slice(t))e.onAgentLog?.(n);M.current=b.length},[b,e.onAgentLog,j.upsertMessage]);let[N,ee]=G([]);U(()=>{v.listChats().then(e=>{ee(e.map(e=>e.key))})},[v]),U(()=>{O&&!N.includes(O)&&ee(e=>[...e,O])},[O,N]);let[te,P]=G(()=>lm(t)?um(t):dm(t)),F=Im({id:te,directory:t,logger:e.logger,disabled:!S?.request,onRequest:async t=>{if(!y)throw Error(`No agent`);let n=new URL(t.url),r=new URL(y.client.baseUrl);r.pathname=n.pathname,r.search=n.search;try{let i=await fetch(r.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:`manual`,signal:t.signal,duplex:`half`});return e.onDevhookRequest?.({method:t.method,path:n.pathname,status:i.status}),i}catch(t){return e.logger.error(`system`,`Error sending request to user's agent:`,t),new Response(`Internal server error`,{status:500})}}});U(()=>{F.status!==`connected`||!F.url||e.onDevhookConnected?.(F.url)},[F.status,F.url]);let{schema:I,options:ne,error:L,setOption:re}=Fm({agent:i===`run`?y?.client:C?.client,capabilities:S,messages:j.messages});U(()=>{A.current=ne},[ne]);let R=Te(()=>{let e=new Map;return x&&i===`run`&&e.set(`agent`,x.message),w&&i===`edit`&&e.set(`editAgent`,`Edit agent error: ${w.message}`),L&&e.set(`options`,`Options error: ${L.message}`),e},[x,w,L,i]),ie=W(new Map);U(()=>{let t=ie.current,n=R;for(let[r,i]of n.entries())t.get(r)!==i&&e.onError?.(i);for(let e of t.keys())n.has(e);ie.current=new Map(n)},[R,e.onError]);let z=Te(()=>{let e=[...j.messages].reverse().find(e=>!(e.role!==`assistant`||e.metadata&&e.metadata.ephemeral));if(!e)return;let t=e.parts.filter(_e);if(t.length!==0&&t.some(e=>E(e.output)&&e.output.outcome===`pending`))return e},[j.messages]),ae=W(void 0),oe=H(async(e,t)=>{if(!z)return;t&&e&&r(!0);let n=j.messages.reverse().find(e=>e.role!==`assistant`||!Array.isArray(e.parts)?!1:e.parts.some(e=>`output`in e&&E(e.output)&&e.output.outcome===`pending`));if(!n)return;ae.current=n.id;let i=n.parts.map(t=>t.output&&E(t.output)&&t.output.outcome===`pending`?{...t,output:{...t.output,outcome:e?`approved`:`rejected`}}:t);await j.upsertMessage({...n,parts:i}),await j.start()},[z,j]);U(()=>{n&&z&&oe(!0)},[n,z,oe]);let se=H(()=>{let e=crypto.randomUUID();k(e),ee(t=>[...t,e])},[]),ce=H(e=>{k(e)},[]),le=Te(()=>{if(z)return{message:z,approve:e=>oe(!0,e),reject:()=>oe(!1),autoApproveEnabled:n}},[z,oe,n]),B=Te(()=>{let e=j.messages;if(e.length!==0)for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n||n.role!==`assistant`||!n.metadata||typeof n.metadata!=`object`||!(`totalUsage`in n.metadata))continue;let r=n.metadata.totalUsage;if(!(!r||typeof r!=`object`)&&!(!(`inputTokens`in r)||!(`outputTokens`in r)||!(`totalTokens`in r)))return{inputTokens:r.inputTokens,outputTokens:r.outputTokens,totalTokens:r.totalTokens,cachedInputTokens:r.cachedInputTokens}}},[j.messages]),de=Te(()=>{if(j.status!==`streaming`)return!1;if(!j.streamingMessage)return!0;let e=j.streamingMessage.parts.filter(_e);return e.length>0&&e.every(e=>e.state.startsWith(`output-`))},[j.status,j.streamingMessage]);return{mode:i,setMode:s,toggleMode:c,chat:j,chats:N,switchChat:ce,newChat:se,build:{status:u,error:l,entrypoint:f},devhook:{connected:F.status===`connected`,url:F.status===`connected`?F.url:void 0},capabilities:S,options:{schema:I,selected:ne,error:L,setOption:re},approval:le,tokenUsage:B,auth:p,server:v,showWaitingPlaceholder:de,editModeMissingApiKey:T}}export{Dp as Logger,Op as LoggerContext,Oc as useAgent,Tp as useAuth,kp as useBundler,sm as useChat,jh as useDevMode,Im as useDevhook,Bm as useDotenv,kh as useEditAgent,Fm as useOptions};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blink",
3
- "version": "1.1.31",
3
+ "version": "1.1.33",
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.6"
77
+ "@blink-sdk/compute-protocol": "^0.0.7"
78
78
  },
79
79
  "devDependencies": {
80
80
  "@ai-sdk/anthropic": "^2.0.15",
@@ -1 +0,0 @@
1
- import{__require as e}from"./chunk-D9KrCrVq.js";import{import_websocket_server as t}from"./wrapper-DRdRnzOz.js";import"./events-DKgZ2LNM.js";import n from"node:path";import r from"node:fs";import i from"node:os";import{Server as a}from"@blink-sdk/compute-protocol/server";const o={GIT_TERMINAL_PROMPT:`0`,GIT_PAGER:`cat`,GIT_AUTHOR_NAME:`blink-so[bot]`,GIT_AUTHOR_EMAIL:`211532188+blink-so[bot]@users.noreply.github.com`,GIT_COMMITTER_NAME:`blink-so[bot]`,GIT_COMMITTER_EMAIL:`211532188+blink-so[bot]@users.noreply.github.com`,GIT_CONFIG_COUNT:`1`,GIT_CONFIG_KEY_0:`credential.https://github.com.helper`,GIT_CONFIG_VALUE_0:`!gh auth git-credential`};async function s(){for(let[e,t]of Object.entries(o))process.env[e]===void 0&&(process.env[e]=t);let n=parseInt(process.env.PORT??`22137`);if(isNaN(n))throw Error(`PORT environment variable is not a number`);let r=process.env.HOST??`127.0.0.1`,i=new t.default({port:n,host:r});console.log(`Compute server running on ${r}:${n}`),i.on(`connection`,t=>{console.log(`Client connected`);let n;try{n=e(`@lydell/node-pty`)}catch{}typeof Bun<`u`&&(n=void 0);let r=new a({nodePty:n,send:e=>{t.send(e)}});t.on(`message`,e=>{r.handleMessage(new Uint8Array(e))}),t.on(`close`,()=>{console.log(`Client disconnected`)})})}export{s as default};