blink 0.1.107 → 0.1.109

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.
@@ -1,4 +1,4 @@
1
- import{__commonJSMin as e,__reExport as t,__require as n,__toESM as r}from"../chunk-D9KrCrVq.js";import{APIServerURLEnvironmentVariable as i,Client as a,Hono as o,agent as s,createServerAdapter as c,isToolApprovalOutput as l,lastUIOptions as u,model as d,require_has_flag as f,tools as p,validator as m}from"../index.node-SyKw4kKs.js";import"../token-error-488npYdU.js";import"../esm-CbZfjZBn.js";import{resolveConfig as h}from"../build-D_L0gFGa.js";import{createRequire as g}from"node:module";import"zod/v4";import"zod/v3";import*as _ from"node:fs";import{createReadStream as v}from"node:fs";import{Writable as y}from"node:stream";import{stripVTControlCharacters as b}from"node:util";import x,{createServer as S}from"http";import{dirname as C,join as w}from"path";import{createRequire as T}from"module";import{existsSync as E,mkdirSync as D,readFileSync as O,watch as k,writeFileSync as A}from"fs";import j,{stdin as M,stdout as N}from"node:process";import{convertToModelMessages as P,isToolOrDynamicToolUIPart as F,readUIMessageStream as ee,streamText as te,tool as I}from"ai";import*as L from"fs/promises";import{readFile as ne,stat as R,writeFile as z}from"fs/promises";import{spawn as B}from"child_process";import{useCallback as V,useEffect as H,useMemo as U,useRef as W,useState as G}from"react";import*as K from"node:path";import{join as re}from"node:path";import q,{ZodFirstPartyTypeKind as J,ZodType as ie,z as Y}from"zod";import*as ae from"node:readline";import oe from"node:readline";import*as se from"node:fs/promises";function ce(e){let[t,n]=G(void 0),[r,o]=G([]),[s,c]=G(void 0),[l,u]=G(e.buildResult),[d,f]=G(e.env),[p,m]=G(e.apiServerUrl),[h,g]=G(void 0);return H(()=>{f(e.env),u(e.buildResult),m(e.apiServerUrl)},[e.env,e.buildResult,e.apiServerUrl]),H(()=>{if(!l||`error`in l){n(void 0),o([]),c(void 0);return}let e=new AbortController,t=!1;return c(void 0),(async()=>{let t=await le(),r=B(`node`,[`--no-deprecation`,l.entry],{stdio:`pipe`,env:{...process.env,...d,[i]:p,PORT:t.toString(),HOST:`127.0.0.1`}});e.signal.addEventListener(`abort`,()=>{try{r.kill()}catch{}});let s=!1;r.stdout.on(`data`,e=>{let t=Buffer.from(e).toString(`utf-8`).trim();!s&&t.startsWith(`Agent server listening on`)||(s||console.log(`stdout: ${t}`),t.length&&o(e=>[...e,{level:`log`,message:t}]))}),r.stderr.on(`data`,e=>{s||console.error(`stderr: ${Buffer.from(e).toString(`utf-8`).trim()}`);let t=Buffer.from(e).toString(`utf-8`).trim();t.length&&o(e=>[...e,{level:`error`,message:t}])}),r.on(`error`,t=>{e.abort(t)}),r.on(`exit`,(t,n)=>{e.abort(`Agent exited with code ${t??`unknown`} and signal ${n??`unknown`}. Be sure to call "blink.agent(...).serve()".`)});let c=new a({baseUrl:`http://127.0.0.1:${t}`});for(;!e.signal.aborted;){try{await c.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(e.signal.aborted)throw e.signal.reason;s=!0;let u=await c.capabilities();g(u),n(c)})().catch(e=>{t||c(e instanceof Error?e:Error(String(e)))}),()=>{t=!0,e.abort()}},[l,d,p]),U(()=>({agent:t,logs:r,error:s,capabilities:h}),[t,r,s,h])}async function le(){let e=S();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function ue(e){let{directory:t,onBuildStart:n,onBuildSuccess:r,onBuildError:i}=typeof e==`string`?{directory:e}:e,a=U(()=>h(t),[t]),[o,s]=G(void 0),[c,l]=G(void 0),[u,d]=G(`building`),f=W(n),p=W(r),m=W(i);return H(()=>{f.current=n,p.current=r,m.current=i},[n,r,i]),H(()=>{let e=new AbortController;return a.build({cwd:t,entry:a.entry,outdir:a.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{d(`building`),s(void 0),l(void 0),f.current?.()},onResult:e=>{`error`in e?(s(e.error),d(`error`),m.current?.(e.error)):(l(e),d(`success`),p.current?.(e))}}).catch(e=>{console.log(`error`,e),d(`error`),s(e),m.current?.(e)}),()=>{e.abort()}},[t]),U(()=>({error:o,status:u,result:c,entry:a.entry,outdir:a.outdir}),[o,u,c,a.entry,a.outdir])}function de(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function fe(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const pe=/^\.+(\\|\/)|^\.+$/,me=/[. ]+$/,he=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,ge=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,_e=e=>e===`‍`,ve=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,ye=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let be;function xe(){return be??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),be}function Se(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(de().test(n)||[...n].some(e=>ge.test(e)&&!_e(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(ye,` `),n.length>0&&(e=e.replaceAll(ve,`$1`)),e=e.replace(me,``),e=e.replace(pe,n),e=e.replace(de(),n),e=e.replaceAll(he,e=>_e(e)?e:n),e.length===0&&(e=n),e=fe().test(e)?e+n:e;let r=typeof t.maxLength==`number`?t.maxLength:100;if(e.length>r){let t=e.lastIndexOf(`.`);if(t===-1)e=Ce(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=Ce(n,a)+i}}return e}function Ce(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of xe().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function we(e){return`${e}.lock`}function Te(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function Ee(e,t={}){let n=we(e),r=process.pid.toString();try{return _.writeFileSync(n,r,{flag:`wx`}),!0}catch(r){if(r.code!==`EEXIST`)throw r;if(t.stale===0)return!1;let i;try{i=parseInt(_.readFileSync(n,`utf8`),10)}catch{return _.unlinkSync(n),Ee(e,{...t,stale:0})}if(!Te(i))try{return _.unlinkSync(n),Ee(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return Ee(e,{...t,stale:0});throw n}return!1}}async function De(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=K.resolve(e),i=0;for(;i<=n.retries;){if(Ee(r,n))return()=>Oe(r);i<n.retries&&await new Promise(e=>setTimeout(e,n.retryInterval)),i++}let a=Error(`Lock file is already being held`);throw a.code=`ELOCKED`,a.file=r,a}function Oe(e){let t=K.resolve(e),n=we(t);try{if(parseInt(_.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}_.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function ke(e){let t=K.resolve(e),n=we(t);try{if(!_.existsSync(n))return{locked:!1};let e=_.readFileSync(n,`utf8`),t=parseInt(e,10);return Te(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const Ae=e=>{_.mkdirSync(e,{recursive:!0})},je=e=>{try{_.fdatasyncSync(e)}catch{}try{_.closeSync(e)}catch{}},Me=e=>{try{let t=_.openSync(e,`r`);try{_.fsyncSync(t)}finally{_.closeSync(t)}}catch{}},Ne=(e,t)=>{let n=K.dirname(e);Ae(n);let r=K.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=_.openSync(r,`w`),_.writeFileSync(i,t,`utf-8`),je(i),i=void 0,_.renameSync(r,e),Me(e),Me(n)}catch(e){if(i!==void 0)try{_.closeSync(i)}catch{}try{_.rmSync(r,{force:!0})}catch{}throw e}},Pe=(e,t)=>{let n=new Map,r,i=e=>{if(_.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(_.readFileSync(e,`utf-8`))},a=(e,t)=>{Ne(e,JSON.stringify(t,null,2))},o=async()=>{if(r)throw Error(`Index is already locked`);let t=K.join(e,`index.json`);Ae(e),_.existsSync(t)||_.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await De(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},s=async()=>{let t=K.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},c=async t=>{let n=K.join(e,`index.json`);a(n,t)},l=async t=>{let n=(await s()).ids[t];if(n)return K.join(e,n)},u=async t=>{let n=(await s()).ids[t];if(!n)return;let r=K.join(e,n);if(_.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(_.readFileSync(r,`utf-8`))},d=async n=>{let r=n[t],i=String(r),l=Se(i,{replacement:`_`})+`.json`,u=await o();try{let t=await s();t.ids[i]=l,t.current=i;let r=K.join(e,l);a(r,n),await c(t)}finally{await u()}};return{async get(e){return await u(e)},async list(){if(!_.statSync(e,{throwIfNoEntry:!1}))return[];let t=await s(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=K.join(e,i),a=_.statSync(t,{throwIfNoEntry:!1});if(!a)continue;let o=ke(t);n.push({key:r,locked:o.locked,pid:o.pid,mtime:a.mtimeMs})}return n.sort((e,t)=>t.mtime-e.mtime),n},async lock(r,i){if(n.has(r))throw Error(`Key "${r}" is already locked in this process`);let a=await l(r);if(!a){let t=Se(r,{replacement:`_`})+`.json`,n=await o();try{let n=await s();n.ids[r]=t;let i=K.join(e,t);Ae(e),_.writeFileSync(i,JSON.stringify({}),`utf-8`),await c(n),a=i}finally{await n()}}if(i?.force){let e=ke(a);if(e.locked&&e.pid&&e.pid!==process.pid)try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,100))}catch(t){t.code!==`ESRCH`&&console.warn(`Failed to kill process ${e.pid}:`,t.message)}}let f=await De(a,{stale:!0,retries:i?.force?10:5,retryInterval:(i?.force,100)});return n.set(r,()=>Promise.resolve(f())),{async get(){let e=await u(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await d(e)},async update(e){let n=await u(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await d({...n,...e})},async delete(){let t=await o();try{let t=await s(),n=t.ids[r];if(n){delete t.ids[r],t.current===r&&(t.current=void 0),await c(t);let i=K.join(e,n);try{_.rmSync(i,{force:!0}),Me(e)}catch{}}}finally{await t()}},async release(){f(),n.delete(r)}}},dispose(){n.clear()}}},Fe=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,a,o,s=new Map,c=new Map,l=K.join(e,`index.json`),u=()=>{try{if(!_.statSync(l,{throwIfNoEntry:!1}))return{ids:{}};let e=_.readFileSync(l,`utf-8`);return{ids:JSON.parse(e).ids??{}}}catch{return{ids:{}}}},d=(e,t,n,r)=>{for(let a of i)try{a({key:e,value:t,locked:n,pid:r})}catch(e){console.error(`Error in onChange callback:`,e)}},f=(t,n,r=!1)=>{let i=K.join(e,n);try{let e=_.statSync(i,{throwIfNoEntry:!1}),a=c.get(n);if(!e){a&&(c.delete(n),d(t,void 0,!1));return}let o=e.mtimeMs,s=a?{locked:a.locked,pid:a.pid}:{locked:!1,pid:void 0};if((r||!a)&&(s=ke(i)),!a||a.mtime!==o||a.locked!==s.locked||a.pid!==s.pid){let e;e=!a||a.mtime!==o?JSON.parse(_.readFileSync(i,`utf-8`)):a.cachedValue,c.set(n,{mtime:o,key:t,locked:s.locked,pid:s.pid,cachedValue:e}),d(t,e,s.locked,s.pid)}}catch{}},p=()=>{try{let e=u(),t=new Set(Object.keys(e.ids));for(let[t,n]of Object.entries(e.ids))f(t,n,!0);for(let[e,n]of c.entries())t.has(n.key)||(c.delete(e),d(n.key,void 0,!1))}catch{}},m=(e,t,n=!1)=>{let i=s.get(e);i&&clearTimeout(i),s.set(e,setTimeout(()=>{s.delete(e),f(e,t,n)},r))},h=()=>{if(a)return;try{_.mkdirSync(e,{recursive:!0})}catch{}a=_.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){p();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=u(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&f(r,e,!0);return}let n=u(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&m(r,t,!1)});let t=()=>{p(),o=setTimeout(t,n)};p(),o=setTimeout(t,n)};return{onChange(e){return i.size===0&&h(),i.add(e),()=>{if(i.delete(e),i.size===0){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),c.clear()}}},dispose(){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),i.clear(),c.clear()}}};async function Ie({chatKey:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=Le}){n=[...n];let a=new TransformStream,o=a.writable.getWriter(),s=async()=>{let a;try{let c=await t.chat({messages:n,chat:{key:e}},{signal:r}),l=ee({message:{id:crypto.randomUUID(),role:`assistant`,parts:[],metadata:{}},stream:c,onError:e=>{e instanceof Error&&e.name===`AbortError`||o.abort(e)}});for await(let e of l)o.write(e),a=e;if(a&&i(a)){n.push(a),await s();return}await o.close()}catch(e){if(e?.name===`AbortError`||r?.aborted)return;await o.abort(e)}finally{await o.close()}};return s().catch(e=>{o.abort(e)}),a.readable}const Le=e=>{if(e.role!==`assistant`)return!1;let t=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),n=e.parts.slice(t+1).filter(F);return n.length===0||n.some(e=>l(e.output)&&e.output.outcome===`pending`)?!1:n.every(e=>e.state.startsWith(`output-`))},Re=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function ze(e){return typeof e==`object`&&e?.__blink_internal!==void 0}var Be=class{chatId;agent;chatStore;serializeMessage;filterMessages;chat;loading=!1;streamingMessage;status=`idle`;queue=[];abortController;isProcessingQueue=!1;listeners=new Set;watcher;disposed=!1;constructor(e){this.chatId=e.chatId,this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.loading=!0,this.chatStore=Pe(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.watcher=Fe(e.chatsDirectory,{pollInterval:1e3,debounce:50}),this.watcher.onChange(e=>{if(e.key!==this.chatId||this.isProcessingQueue)return;if(!e.value){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.status=`idle`,this.streamingMessage=void 0,this.notifyListeners();return}let t=e.value,n=e.value?.error?`error`:`idle`;e.locked&&(n=`streaming`);let r=this.chat.updated_at!==t?.updated_at||this.status!==n;this.chat=t,this.streamingMessage=void 0,this.status=n,r&&this.notifyListeners()}),this.chatStore.get(this.chatId).then(e=>{this.disposed||e&&(this.chat=e)}).catch(e=>{this.chat.error=e instanceof Error?e.message:String(e)}).finally(()=>{this.loading=!1,this.notifyListeners()})}setAgent(e){this.agent=e}getState(){return{id:this.chatId,messages:(this.chat?.messages??[]).filter(e=>!ze(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,error:this.chat?.error,loading:this.loading,queuedMessages:this.queue}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async upsertMessage(e,t){let n=!1,r;t?r=t:(r=await this.chatStore.lock(this.chatId),n=!0);try{let t=await r.get();(!t.id||!Array.isArray(t.messages))&&(t={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]});let n=e;if(this.serializeMessage){let t=this.serializeMessage(e);if(t===void 0)return;n=t}let i=n.id||crypto.randomUUID(),a=n.mode||`run`,o=Re(n,a,i),s=t.messages.find(e=>e.id===o.id)?t.messages.map(e=>e.id===o.id?o:e):[...t.messages,o];this.chat={...t,updated_at:new Date().toISOString(),messages:s},await r.set(this.chat),this.notifyListeners()}finally{n&&await r.release()}}async deleteMessage(e){let t;try{t=await this.chatStore.lock(this.chatId);let n=await t.get();this.chat.messages=n.messages.filter(t=>t.id!==e),this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),this.notifyListeners()}finally{t&&await t.release()}}async sendMessage(e){if(this.chat.error=void 0,this.status===`streaming`){this.queue.push(e),this.notifyListeners();return}this.queue=[e],await this.processQueueOrRun()}async start(){await this.processQueueOrRun()}async processQueueOrRun(){if(!this.agent){this.chat.error=`The agent is not available. Please wait for the build to succeed.`,this.status=`error`,this.queue=[],this.notifyListeners();return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0,this.chat.error=void 0;let e;try{e=await this.chatStore.lock(this.chatId);let t=!0;for(;this.queue.length>0||t;){t=!1;let n=new AbortController;this.abortController=n;let r=this.queue.shift();this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),r&&await this.upsertMessage(r,e);let i=this.chat.messages;this.filterMessages&&(i=i.filter(this.filterMessages)),i=i.map(e=>({...e,parts:e.parts.map(e=>!F(e)||e.input!==``?e:{...e,input:{}})}));let a=await Ie({agent:this.agent,chatKey:this.chatId,signal:n.signal,messages:i}),o=async t=>{let n=t;if(this.serializeMessage){let e=this.serializeMessage(t);if(e===void 0)return;n=e}this.chat.updated_at=new Date().toISOString(),this.chat.messages.push(n),this.streamingMessage=void 0,await e?.set(this.chat)},s=a.getReader();try{for(;;){let{done:e,value:t}=await s.read();if(e||n.signal.aborted)break;this.streamingMessage&&t.id!==this.streamingMessage.id&&await o(this.streamingMessage),this.streamingMessage=this.serializeMessage?this.serializeMessage(t):t,this.notifyListeners()}}finally{s.releaseLock()}this.streamingMessage&&await o(this.streamingMessage)}}catch(e){this.chat.error=e instanceof Error?e.message:String(e)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,this.chat.error?this.status=`error`:this.status=`idle`,e&&(this.chat.updated_at=new Date().toISOString(),await e.set(this.chat),await e.release(),this.notifyListeners())}}stopStreaming(){this.abortController?.abort()}clearQueue(){this.queue=[],this.notifyListeners()}async resetChat(){this.abortController?.abort(),this.resetChatState(),this.notifyListeners();let e;try{e=await this.chatStore.lock(this.chatId),await e.delete()}catch{}finally{if(e)try{await e.release()}catch{}}}dispose(){this.disposed=!0,this.watcher.dispose(),this.listeners.clear(),this.abortController?.abort()}resetChatState(){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.streamingMessage=void 0,this.status=`idle`,this.queue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};function Ve(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a}=e,o=W(null),[s,c]=G({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[]});H(()=>{o.current&&o.current.dispose();let e=new Be({chatId:t,chatsDirectory:r,serializeMessage:i,filterMessages:a}),n=e.subscribe(e=>{c(e)});return c(e.getState()),o.current=e,()=>{n(),e.dispose(),o.current=null}},[t,r]),H(()=>{o.current&&o.current.setAgent(n)},[n]);let l=V(async e=>{o.current&&await o.current.sendMessage(e)},[]),u=V(async e=>{o.current&&await o.current.upsertMessage(e)},[]),d=V(()=>{o.current&&o.current.stopStreaming()},[]),f=V(async()=>{o.current&&await o.current.resetChat()},[]),p=V(()=>{o.current&&o.current.clearQueue()},[]),m=V(async e=>{o.current&&await o.current.deleteMessage(e)},[]),h=V(async()=>{o.current&&await o.current.start()},[]);return{...s,sendMessage:l,upsertMessage:u,stopStreaming:d,resetChat:f,clearQueue:p,deleteMessage:m,start:h}}var He=Object.getOwnPropertyNames,Ue=(e,t)=>function(){return t||(0,e[He(e)[0]])((t={exports:{}}).exports,t),t.exports},X=g(import.meta.url);Y.object({email:Y.string().email(),password:Y.string().min(8)}),Y.object({email:Y.string().email(),code:Y.string()}),Y.object({email:Y.string().email(),password:Y.string().min(8)});var We=class{constructor(e,t){this.client=e,this.baseURL=t}async token(e,t={timeout:12e4}){return new Promise((n,r)=>{let i=crypto.randomUUID(),a=this.client.websocket(`/api/auth/token?id=${i}`),o=new URL(`/auth?id=${i}`,this.baseURL),s=setTimeout(()=>{r(Error(`Timeout waiting for the user to authenticate`))},t.timeout);a.onerror=e=>{clearTimeout(s),console.log(`error`,e),r(Error(`Failed to connect to server`))},a.onopen=()=>{e(o.toString(),i)},a.onmessage=e=>{typeof e.data==`string`&&(clearTimeout(s),n(e.data))}})}},Ge=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function Ke(e){}function qe(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=Ke,onError:n=Ke,onRetry:r=Ke,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=Je(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1,i=e.slice(t+r);f(n,i,e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t}
1
+ import{__commonJSMin as e,__reExport as t,__require as n,__toESM as r}from"../chunk-D9KrCrVq.js";import{APIServerURLEnvironmentVariable as i,Client as a,Hono as o,agent as s,createServerAdapter as c,isToolApprovalOutput as l,lastUIOptions as u,model as d,require_has_flag as f,tools as p,validator as m}from"../index.node-B0EokVTD.js";import"../token-error-488npYdU.js";import"../esm-CbZfjZBn.js";import{resolveConfig as h}from"../build-D_L0gFGa.js";import{createRequire as g}from"node:module";import"zod/v4";import"zod/v3";import*as _ from"node:fs";import{createReadStream as v}from"node:fs";import{Writable as y}from"node:stream";import{stripVTControlCharacters as b}from"node:util";import x,{createServer as S}from"http";import{dirname as C,join as w}from"path";import{createRequire as T}from"module";import{existsSync as E,mkdirSync as D,readFileSync as O,watch as k,writeFileSync as A}from"fs";import j,{stdin as M,stdout as N}from"node:process";import{convertToModelMessages as P,isToolOrDynamicToolUIPart as F,readUIMessageStream as ee,streamText as te,tool as I}from"ai";import*as L from"fs/promises";import{readFile as ne,stat as R,writeFile as z}from"fs/promises";import{spawn as B}from"child_process";import{useCallback as V,useEffect as H,useMemo as U,useRef as W,useState as G}from"react";import*as K from"node:path";import{join as re}from"node:path";import q,{ZodFirstPartyTypeKind as J,ZodType as ie,z as Y}from"zod";import*as ae from"node:readline";import oe from"node:readline";import*as se from"node:fs/promises";function ce(e){let[t,n]=G(void 0),[r,o]=G([]),[s,c]=G(void 0),[l,u]=G(e.buildResult),[d,f]=G(e.env),[p,m]=G(e.apiServerUrl),[h,g]=G(void 0);return H(()=>{f(e.env),u(e.buildResult),m(e.apiServerUrl)},[e.env,e.buildResult,e.apiServerUrl]),H(()=>{if(!l||`error`in l){n(void 0),o([]),c(void 0);return}let e=new AbortController,t=!1;return c(void 0),n(void 0),(async()=>{let t=await le(),r=B(`node`,[`--no-deprecation`,l.entry],{stdio:`pipe`,env:{...process.env,...d,[i]:p,PORT:t.toString(),HOST:`127.0.0.1`}});e.signal.addEventListener(`abort`,()=>{try{r.kill()}catch{}});let s=!1;r.stdout.on(`data`,e=>{let t=Buffer.from(e).toString(`utf-8`).trim();!s&&t.startsWith(`Agent server listening on`)||(s||console.log(`stdout: ${t}`),t.length&&o(e=>[...e,{level:`log`,message:t}]))}),r.stderr.on(`data`,e=>{s||console.error(`stderr: ${Buffer.from(e).toString(`utf-8`).trim()}`);let t=Buffer.from(e).toString(`utf-8`).trim();t.length&&o(e=>[...e,{level:`error`,message:t}])}),r.on(`error`,t=>{e.abort(t)}),r.on(`exit`,(t,n)=>{e.abort(`Agent exited with code ${t??`unknown`} and signal ${n??`unknown`}. Be sure to call "blink.agent(...).serve()".`)});let c=new a({baseUrl:`http://127.0.0.1:${t}`});for(;!e.signal.aborted;){try{await c.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(e.signal.aborted)throw e.signal.reason;s=!0;let u=await c.capabilities();g(u),n(c)})().catch(e=>{t||c(e instanceof Error?e:Error(String(e)))}),()=>{t=!0,e.abort()}},[l,d,p]),U(()=>({agent:t,logs:r,error:s,capabilities:h}),[t,r,s,h])}async function le(){let e=S();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function ue(e){let{directory:t,onBuildStart:n,onBuildSuccess:r,onBuildError:i}=typeof e==`string`?{directory:e}:e,a=U(()=>h(t),[t]),[o,s]=G(void 0),[c,l]=G(void 0),[u,d]=G(`building`),f=W(n),p=W(r),m=W(i);return H(()=>{f.current=n,p.current=r,m.current=i},[n,r,i]),H(()=>{let e=new AbortController;return a.build({cwd:t,entry:a.entry,outdir:a.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{d(`building`),s(void 0),l(void 0),f.current?.()},onResult:e=>{`error`in e?(s(e.error),d(`error`),m.current?.(e.error)):(l(e),d(`success`),p.current?.(e))}}).catch(e=>{console.log(`error`,e),d(`error`),s(e),m.current?.(e)}),()=>{e.abort()}},[t]),U(()=>({error:o,status:u,result:c,entry:a.entry,outdir:a.outdir}),[o,u,c,a.entry,a.outdir])}function de(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function fe(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const pe=/^\.+(\\|\/)|^\.+$/,me=/[. ]+$/,he=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,ge=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,_e=e=>e===`‍`,ve=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,ye=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let be;function xe(){return be??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),be}function Se(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(de().test(n)||[...n].some(e=>ge.test(e)&&!_e(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(ye,` `),n.length>0&&(e=e.replaceAll(ve,`$1`)),e=e.replace(me,``),e=e.replace(pe,n),e=e.replace(de(),n),e=e.replaceAll(he,e=>_e(e)?e:n),e.length===0&&(e=n),e=fe().test(e)?e+n:e;let r=typeof t.maxLength==`number`?t.maxLength:100;if(e.length>r){let t=e.lastIndexOf(`.`);if(t===-1)e=Ce(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=Ce(n,a)+i}}return e}function Ce(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of xe().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function we(e){return`${e}.lock`}function Te(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function Ee(e,t={}){let n=we(e),r=process.pid.toString();try{return _.writeFileSync(n,r,{flag:`wx`}),!0}catch(r){if(r.code!==`EEXIST`)throw r;if(t.stale===0)return!1;let i;try{i=parseInt(_.readFileSync(n,`utf8`),10)}catch{return _.unlinkSync(n),Ee(e,{...t,stale:0})}if(!Te(i))try{return _.unlinkSync(n),Ee(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return Ee(e,{...t,stale:0});throw n}return!1}}async function De(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=K.resolve(e),i=0;for(;i<=n.retries;){if(Ee(r,n))return()=>Oe(r);i<n.retries&&await new Promise(e=>setTimeout(e,n.retryInterval)),i++}let a=Error(`Lock file is already being held`);throw a.code=`ELOCKED`,a.file=r,a}function Oe(e){let t=K.resolve(e),n=we(t);try{if(parseInt(_.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}_.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function ke(e){let t=K.resolve(e),n=we(t);try{if(!_.existsSync(n))return{locked:!1};let e=_.readFileSync(n,`utf8`),t=parseInt(e,10);return Te(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const Ae=e=>{_.mkdirSync(e,{recursive:!0})},je=e=>{try{_.fdatasyncSync(e)}catch{}try{_.closeSync(e)}catch{}},Me=e=>{try{let t=_.openSync(e,`r`);try{_.fsyncSync(t)}finally{_.closeSync(t)}}catch{}},Ne=(e,t)=>{let n=K.dirname(e);Ae(n);let r=K.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=_.openSync(r,`w`),_.writeFileSync(i,t,`utf-8`),je(i),i=void 0,_.renameSync(r,e),Me(e),Me(n)}catch(e){if(i!==void 0)try{_.closeSync(i)}catch{}try{_.rmSync(r,{force:!0})}catch{}throw e}},Pe=(e,t)=>{let n=new Map,r,i=e=>{if(_.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(_.readFileSync(e,`utf-8`))},a=(e,t)=>{Ne(e,JSON.stringify(t,null,2))},o=async()=>{if(r)throw Error(`Index is already locked`);let t=K.join(e,`index.json`);Ae(e),_.existsSync(t)||_.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await De(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},s=async()=>{let t=K.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},c=async t=>{let n=K.join(e,`index.json`);a(n,t)},l=async t=>{let n=(await s()).ids[t];if(n)return K.join(e,n)},u=async t=>{let n=(await s()).ids[t];if(!n)return;let r=K.join(e,n);if(_.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(_.readFileSync(r,`utf-8`))},d=async n=>{let r=n[t],i=String(r),l=Se(i,{replacement:`_`})+`.json`,u=await o();try{let t=await s();t.ids[i]=l,t.current=i;let r=K.join(e,l);a(r,n),await c(t)}finally{await u()}};return{async get(e){return await u(e)},async list(){if(!_.statSync(e,{throwIfNoEntry:!1}))return[];let t=await s(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=K.join(e,i),a=_.statSync(t,{throwIfNoEntry:!1});if(!a)continue;let o=ke(t);n.push({key:r,locked:o.locked,pid:o.pid,mtime:a.mtimeMs})}return n.sort((e,t)=>t.mtime-e.mtime),n},async lock(r,i){if(n.has(r))throw Error(`Key "${r}" is already locked in this process`);let a=await l(r);if(!a){let t=Se(r,{replacement:`_`})+`.json`,n=await o();try{let n=await s();n.ids[r]=t;let i=K.join(e,t);Ae(e),_.writeFileSync(i,JSON.stringify({}),`utf-8`),await c(n),a=i}finally{await n()}}if(i?.force){let e=ke(a);if(e.locked&&e.pid&&e.pid!==process.pid)try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,100))}catch(t){t.code!==`ESRCH`&&console.warn(`Failed to kill process ${e.pid}:`,t.message)}}let f=await De(a,{stale:!0,retries:i?.force?10:5,retryInterval:(i?.force,100)});return n.set(r,()=>Promise.resolve(f())),{async get(){let e=await u(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await d(e)},async update(e){let n=await u(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await d({...n,...e})},async delete(){let t=await o();try{let t=await s(),n=t.ids[r];if(n){delete t.ids[r],t.current===r&&(t.current=void 0),await c(t);let i=K.join(e,n);try{_.rmSync(i,{force:!0}),Me(e)}catch{}}}finally{await t()}},async release(){f(),n.delete(r)}}},dispose(){n.clear()}}},Fe=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,a,o,s=new Map,c=new Map,l=K.join(e,`index.json`),u=()=>{try{if(!_.statSync(l,{throwIfNoEntry:!1}))return{ids:{}};let e=_.readFileSync(l,`utf-8`);return{ids:JSON.parse(e).ids??{}}}catch{return{ids:{}}}},d=(e,t,n,r)=>{for(let a of i)try{a({key:e,value:t,locked:n,pid:r})}catch(e){console.error(`Error in onChange callback:`,e)}},f=(t,n,r=!1)=>{let i=K.join(e,n);try{let e=_.statSync(i,{throwIfNoEntry:!1}),a=c.get(n);if(!e){a&&(c.delete(n),d(t,void 0,!1));return}let o=e.mtimeMs,s=a?{locked:a.locked,pid:a.pid}:{locked:!1,pid:void 0};if((r||!a)&&(s=ke(i)),!a||a.mtime!==o||a.locked!==s.locked||a.pid!==s.pid){let e;e=!a||a.mtime!==o?JSON.parse(_.readFileSync(i,`utf-8`)):a.cachedValue,c.set(n,{mtime:o,key:t,locked:s.locked,pid:s.pid,cachedValue:e}),d(t,e,s.locked,s.pid)}}catch{}},p=()=>{try{let e=u(),t=new Set(Object.keys(e.ids));for(let[t,n]of Object.entries(e.ids))f(t,n,!0);for(let[e,n]of c.entries())t.has(n.key)||(c.delete(e),d(n.key,void 0,!1))}catch{}},m=(e,t,n=!1)=>{let i=s.get(e);i&&clearTimeout(i),s.set(e,setTimeout(()=>{s.delete(e),f(e,t,n)},r))},h=()=>{if(a)return;try{_.mkdirSync(e,{recursive:!0})}catch{}a=_.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){p();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=u(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&f(r,e,!0);return}let n=u(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&m(r,t,!1)});let t=()=>{p(),o=setTimeout(t,n)};p(),o=setTimeout(t,n)};return{onChange(e){return i.size===0&&h(),i.add(e),()=>{if(i.delete(e),i.size===0){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),c.clear()}}},dispose(){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),i.clear(),c.clear()}}};async function Ie({chatKey:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=Le}){n=[...n];let a=new TransformStream,o=a.writable.getWriter(),s=async()=>{let a;try{let c=await t.chat({messages:n,chat:{key:e}},{signal:r}),l=ee({message:{id:crypto.randomUUID(),role:`assistant`,parts:[],metadata:{}},stream:c,onError:e=>{e instanceof Error&&e.name===`AbortError`||o.abort(e)}});for await(let e of l)o.write(e),a=e;if(a&&i(a)){n.push(a),await s();return}await o.close()}catch(e){if(e?.name===`AbortError`||r?.aborted)return;await o.abort(e)}finally{await o.close()}};return s().catch(e=>{o.abort(e)}),a.readable}const Le=e=>{if(e.role!==`assistant`)return!1;let t=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),n=e.parts.slice(t+1).filter(F);return n.length===0||n.some(e=>l(e.output)&&e.output.outcome===`pending`)?!1:n.every(e=>e.state.startsWith(`output-`))},Re=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function ze(e){return typeof e==`object`&&e?.__blink_internal!==void 0}var Be=class{chatId;agent;chatStore;serializeMessage;filterMessages;chat;loading=!1;streamingMessage;status=`idle`;queue=[];abortController;isProcessingQueue=!1;listeners=new Set;watcher;disposed=!1;constructor(e){this.chatId=e.chatId,this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.loading=!0,this.chatStore=Pe(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.watcher=Fe(e.chatsDirectory,{pollInterval:1e3,debounce:50}),this.watcher.onChange(e=>{if(e.key!==this.chatId||this.isProcessingQueue)return;if(!e.value){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.status=`idle`,this.streamingMessage=void 0,this.notifyListeners();return}let t=e.value,n=e.value?.error?`error`:`idle`;e.locked&&(n=`streaming`);let r=this.chat.updated_at!==t?.updated_at||this.status!==n;this.chat=t,this.streamingMessage=void 0,this.status=n,r&&this.notifyListeners()}),this.chatStore.get(this.chatId).then(e=>{this.disposed||e&&(this.chat=e)}).catch(e=>{this.chat.error=e instanceof Error?e.message:String(e)}).finally(()=>{this.loading=!1,this.notifyListeners()})}setAgent(e){this.agent=e}getState(){return{id:this.chatId,messages:(this.chat?.messages??[]).filter(e=>!ze(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,error:this.chat?.error,loading:this.loading,queuedMessages:this.queue}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async upsertMessage(e,t){let n=!1,r;t?r=t:(r=await this.chatStore.lock(this.chatId),n=!0);try{let t=await r.get();(!t.id||!Array.isArray(t.messages))&&(t={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]});let n=e;if(this.serializeMessage){let t=this.serializeMessage(e);if(t===void 0)return;n=t}let i=n.id||crypto.randomUUID(),a=n.mode||`run`,o=Re(n,a,i),s=t.messages.find(e=>e.id===o.id)?t.messages.map(e=>e.id===o.id?o:e):[...t.messages,o];this.chat={...t,updated_at:new Date().toISOString(),messages:s},await r.set(this.chat),this.notifyListeners()}finally{n&&await r.release()}}async deleteMessage(e){let t;try{t=await this.chatStore.lock(this.chatId);let n=await t.get();this.chat.messages=n.messages.filter(t=>t.id!==e),this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),this.notifyListeners()}finally{t&&await t.release()}}async sendMessage(e){if(this.chat.error=void 0,this.status===`streaming`){this.queue.push(e),this.notifyListeners();return}this.queue=[e],await this.processQueueOrRun()}async start(){await this.processQueueOrRun()}async processQueueOrRun(){if(!this.agent){this.chat.error=`The agent is not available. Please wait for the build to succeed.`,this.status=`error`,this.queue=[],this.notifyListeners();return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0,this.chat.error=void 0;let e;try{e=await this.chatStore.lock(this.chatId);let t=!0;for(;this.queue.length>0||t;){t=!1;let n=new AbortController;this.abortController=n;let r=this.queue.shift();this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),r&&await this.upsertMessage(r,e);let i=this.chat.messages;this.filterMessages&&(i=i.filter(this.filterMessages)),i=i.map(e=>({...e,parts:e.parts.map(e=>!F(e)||e.input!==``?e:{...e,input:{}})}));let a=await Ie({agent:this.agent,chatKey:this.chatId,signal:n.signal,messages:i}),o=async t=>{let n=t;if(this.serializeMessage){let e=this.serializeMessage(t);if(e===void 0)return;n=e}this.chat.updated_at=new Date().toISOString(),this.chat.messages.push(n),this.streamingMessage=void 0,await e?.set(this.chat)},s=a.getReader();try{for(;;){let{done:e,value:t}=await s.read();if(e||n.signal.aborted)break;this.streamingMessage&&t.id!==this.streamingMessage.id&&await o(this.streamingMessage),this.streamingMessage=this.serializeMessage?this.serializeMessage(t):t,this.notifyListeners()}}finally{s.releaseLock()}this.streamingMessage&&await o(this.streamingMessage)}}catch(e){this.chat.error=e instanceof Error?e.message:String(e)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,this.chat.error?this.status=`error`:this.status=`idle`,e&&(this.chat.updated_at=new Date().toISOString(),await e.set(this.chat),await e.release(),this.notifyListeners())}}stopStreaming(){this.abortController?.abort()}clearQueue(){this.queue=[],this.notifyListeners()}async resetChat(){this.abortController?.abort(),this.resetChatState(),this.notifyListeners();let e;try{e=await this.chatStore.lock(this.chatId),await e.delete()}catch{}finally{if(e)try{await e.release()}catch{}}}dispose(){this.disposed=!0,this.watcher.dispose(),this.listeners.clear(),this.abortController?.abort()}resetChatState(){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.streamingMessage=void 0,this.status=`idle`,this.queue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};function Ve(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a}=e,o=W(null),[s,c]=G({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[]});H(()=>{o.current&&o.current.dispose();let e=new Be({chatId:t,chatsDirectory:r,serializeMessage:i,filterMessages:a}),n=e.subscribe(e=>{c(e)});return c(e.getState()),o.current=e,()=>{n(),e.dispose(),o.current=null}},[t,r]),H(()=>{o.current&&o.current.setAgent(n)},[n]);let l=V(async e=>{o.current&&await o.current.sendMessage(e)},[]),u=V(async e=>{o.current&&await o.current.upsertMessage(e)},[]),d=V(()=>{o.current&&o.current.stopStreaming()},[]),f=V(async()=>{o.current&&await o.current.resetChat()},[]),p=V(()=>{o.current&&o.current.clearQueue()},[]),m=V(async e=>{o.current&&await o.current.deleteMessage(e)},[]),h=V(async()=>{o.current&&await o.current.start()},[]);return{...s,sendMessage:l,upsertMessage:u,stopStreaming:d,resetChat:f,clearQueue:p,deleteMessage:m,start:h}}var He=Object.getOwnPropertyNames,Ue=(e,t)=>function(){return t||(0,e[He(e)[0]])((t={exports:{}}).exports,t),t.exports},X=g(import.meta.url);Y.object({email:Y.string().email(),password:Y.string().min(8)}),Y.object({email:Y.string().email(),code:Y.string()}),Y.object({email:Y.string().email(),password:Y.string().min(8)});var We=class{constructor(e,t){this.client=e,this.baseURL=t}async token(e,t={timeout:12e4}){return new Promise((n,r)=>{let i=crypto.randomUUID(),a=this.client.websocket(`/api/auth/token?id=${i}`),o=new URL(`/auth?id=${i}`,this.baseURL),s=setTimeout(()=>{r(Error(`Timeout waiting for the user to authenticate`))},t.timeout);a.onerror=e=>{clearTimeout(s),console.log(`error`,e),r(Error(`Failed to connect to server`))},a.onopen=()=>{e(o.toString(),i)},a.onmessage=e=>{typeof e.data==`string`&&(clearTimeout(s),n(e.data))}})}},Ge=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function Ke(e){}function qe(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=Ke,onError:n=Ke,onRetry:r=Ke,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=Je(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1,i=e.slice(t+r);f(n,i,e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t}
2
2
  `;break;case`id`:s=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new Ge(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new Ge(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}));break}}function p(){c.length>0&&t({id:s,event:l||void 0,data:c.endsWith(`
3
3
  `)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function Je(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
4
4
  `,r),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i===-1?a!==-1&&(o=a):o=i===e.length-1?-1:i,o===-1){n=e.slice(r);break}else{let n=e.slice(r,o);t.push(n),r=o+1,e[r-1]===`\r`&&e[r]===`
@@ -546,4 +546,4 @@ Instead:
546
546
 
547
547
  The agent process can restart at any time, so all important state must be externalized.
548
548
  </technical_knowledge>
549
- `;function fu(e){let[t,n]=G(void 0),[r,i]=G(void 0),o=W(void 0);return H(()=>{let t=new AbortController;return(async()=>{o.current=uu({directory:e.directory});let r=await pu(),i=o.current.agent.serve({port:r,host:`127.0.0.1`,apiUrl:e.apiServerUrl});t.signal.addEventListener(`abort`,()=>{try{i.close()}catch{}o.current?.cleanup()});let s=new a({baseUrl:`http://127.0.0.1:${r}`});for(;!t.signal.aborted;){try{await s.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(t.signal.aborted)throw t.signal.reason;n(s)})().catch(e=>{i(e instanceof Error?e:Error(String(e)))}),()=>t.abort()},[e.directory,e.apiServerUrl]),U(()=>({client:t,error:r,setUserAgentUrl:e=>{o.current?.setUserAgentUrl(e)}}),[t,r])}async function pu(){let e=S();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function mu(e){let{directory:t}=e,[n,r]=G(`run`),i=W(`run`);H(()=>{i.current=n},[n]);let a=V(t=>{r(t),e.onModeChange?.(t)},[e.onModeChange]),o=V(()=>{a(n===`run`?`edit`:`run`)},[n,a]),{error:s,status:c,result:u,entry:d}=ue({directory:t,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),f=mi(t),p=U(()=>{let e=Zr();return e?{...f,BLINK_TOKEN:e}:f},[f]),m=W(void 0);H(()=>{let t=Object.keys(p);if(t.length===m.current||m.current===void 0){m.current=t.length;return}m.current=t.length,e.onEnvLoaded?.(t)},[p,e.onEnvLoaded]);let h=W(void 0),g=U(()=>ci({port:0,dataDirectory:w(t,`data`),getAgent:()=>h.current}),[t]),{agent:_,logs:v,error:y,capabilities:b}=ce({buildResult:u,env:p,apiServerUrl:g.url}),{client:x,error:S,setUserAgentUrl:C}=fu({directory:t,apiServerUrl:g.url}),[T,E]=G(`default`);H(()=>{_&&C(_.baseUrl),n===`run`?_?h.current=_:(h.current=void 0,g.stopChat(T)):n===`edit`&&(x?h.current=x:(h.current=void 0,g.stopChat(T)))},[_,x,n,T,g]);let D=W(void 0),O=Ve({chatId:T,agent:n===`run`?_:x,chatsDirectory:g.chatsDirectory,serializeMessage:e=>{let t=e.role===`user`&&D.current?{...typeof e.metadata==`object`&&e.metadata!==null?e.metadata:{},options:D.current}:e.metadata;return{id:e.id??crypto.randomUUID(),created_at:new Date().toISOString(),role:e.role,parts:e.parts,mode:i.current,metadata:t}},filterMessages:e=>i.current===`edit`?!0:!(ze(e.metadata)||e.mode===`edit`)}),k=W(0);H(()=>{if(v.length===k.current)return;let t=k.current;for(let n of v.slice(t))e.onAgentLog?.(n);k.current=v.length},[v,e.onAgentLog,O.upsertMessage]);let[A,j]=G([]);H(()=>{g.listChats().then(e=>{j(e.map(e=>e.key))})},[g]),H(()=>{T&&!A.includes(T)&&j(e=>[...e,T])},[T,A]);let M=U(()=>$r(t),[t]),N=ui({id:M,disabled:!b?.request,onRequest:async t=>{if(!_)throw Error(`No agent`);let n=new URL(t.url),r=new URL(_.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(e){return console.error(`Error sending request to user's agent:`,e),new Response(`Internal server error`,{status:500})}}});H(()=>{N.status===`connected`&&e.onDevhookConnected?.(`https://${N.id}.dev.blink.host`)},[N.status,N.id]);let{schema:P,options:ee,error:te,setOption:I}=li({agent:n===`run`?_:x,capabilities:b,messages:O.messages});H(()=>{D.current=ee},[ee]);let L=U(()=>{let e=[];return y&&n===`run`&&e.push(y.message),S&&n===`edit`&&e.push(`Edit agent error: ${S.message}`),O.error&&e.push(`Chat error: ${O.error}`),te&&e.push(`Options error: ${te.message}`),e},[y,S,O.error,te,n]);H(()=>{for(let t of L)e.onError?.(t)},[L]);let[ne,R]=G(),[z,B]=G(!1),K=U(()=>{let e=[...O.messages].reverse().find(e=>!(e.role!==`assistant`||e.metadata&&e.metadata.ephemeral));if(!e||ne===e.id)return;let t=e.parts.filter(F);if(t.length!==0&&t.some(e=>l(e.output)&&e.output.outcome===`pending`))return e},[O.messages,ne]),re=V(async(e,t)=>{if(!K)return;t&&e&&B(!0),R(K.id);let n=O.messages;if(n.length===0)return;let r=n[n.length-1];if(!r||r.role!==`assistant`||!Array.isArray(r.parts))return;let i=r.parts.map(t=>t.output&&l(t.output)&&t.output.outcome===`pending`?{...t,output:{...t.output,outcome:e?`approved`:`rejected`}}:t);await O.upsertMessage({...r,parts:i}),await O.start()},[K,O]);H(()=>{z&&K&&re(!0)},[z,K,re]);let q=V(()=>{let e=crypto.randomUUID();E(e),j(t=>[...t,e])},[]),J=U(()=>{if(K)return{message:K,approve:e=>re(!0,e),reject:()=>re(!1),autoApproveEnabled:z}},[K,re,z]),ie=U(()=>{let e=O.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}}},[O.messages]),Y=U(()=>{if(O.status!==`streaming`)return!1;if(!O.streamingMessage)return!0;let e=O.streamingMessage.parts.filter(F);return e.length>0&&e.every(e=>e.state.startsWith(`output-`))},[O.status,O.streamingMessage]);return{mode:n,setMode:a,toggleMode:o,chat:O,chats:A,switchChat:E,newChat:q,build:{status:c,error:s,entrypoint:d},devhook:{connected:N.status===`connected`,url:N.status===`connected`?`https://${N.id}.dev.blink.host`:void 0},capabilities:b,options:{schema:P,selected:ee,error:te,setOption:I},approval:J,tokenUsage:ie,server:g,showWaitingPlaceholder:Y}}export{ce as useAgent,ue as useBundler,Ve as useChat,mu as useDevMode,ui as useDevhook,mi as useDotenv,fu as useEditAgent,li as useOptions};
549
+ `;function fu(e){let[t,n]=G(void 0),[r,i]=G(void 0),o=W(void 0);return H(()=>{let t=new AbortController;return(async()=>{o.current=uu({directory:e.directory});let r=await pu(),i=o.current.agent.serve({port:r,host:`127.0.0.1`,apiUrl:e.apiServerUrl});t.signal.addEventListener(`abort`,()=>{try{i.close()}catch{}o.current?.cleanup()});let s=new a({baseUrl:`http://127.0.0.1:${r}`});for(;!t.signal.aborted;){try{await s.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(t.signal.aborted)throw t.signal.reason;n(s)})().catch(e=>{i(e instanceof Error?e:Error(String(e)))}),()=>t.abort()},[e.directory,e.apiServerUrl]),U(()=>({client:t,error:r,setUserAgentUrl:e=>{o.current?.setUserAgentUrl(e)}}),[t,r])}async function pu(){let e=S();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function mu(e){let{directory:t}=e,[n,r]=G(`run`),i=W(`run`);H(()=>{i.current=n},[n]);let a=V(t=>{r(t),e.onModeChange?.(t)},[e.onModeChange]),o=V(()=>{a(n===`run`?`edit`:`run`)},[n,a]),{error:s,status:c,result:u,entry:d}=ue({directory:t,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),f=mi(t),p=U(()=>{let e=Zr();return e?{...f,BLINK_TOKEN:e}:f},[f]),m=W(void 0);H(()=>{let t=Object.keys(p);if(t.length===m.current||m.current===void 0){m.current=t.length;return}m.current=t.length,e.onEnvLoaded?.(t)},[p,e.onEnvLoaded]);let h=W(void 0),g=U(()=>ci({port:0,dataDirectory:w(t,`data`),getAgent:()=>h.current}),[t]),{agent:_,logs:v,error:y,capabilities:b}=ce({buildResult:u,env:p,apiServerUrl:g.url}),{client:x,error:S,setUserAgentUrl:C}=fu({directory:t,apiServerUrl:g.url}),[T,E]=G(`default`);H(()=>{_&&C(_.baseUrl),n===`run`?_?h.current=_:(h.current=void 0,g.stopChat(T)):n===`edit`&&(x?h.current=x:(h.current=void 0,g.stopChat(T)))},[_,x,n,T,g]);let D=W(void 0),O=Ve({chatId:T,agent:n===`run`?_:x,chatsDirectory:g.chatsDirectory,serializeMessage:e=>{let t=e.role===`user`&&D.current?{...typeof e.metadata==`object`&&e.metadata!==null?e.metadata:{},options:D.current}:e.metadata;return{id:e.id??crypto.randomUUID(),created_at:new Date().toISOString(),role:e.role,parts:e.parts,mode:i.current,metadata:t}},filterMessages:e=>i.current===`edit`?!0:!(ze(e.metadata)||e.mode===`edit`)}),k=W(0);H(()=>{if(v.length===k.current)return;let t=k.current;for(let n of v.slice(t))e.onAgentLog?.(n);k.current=v.length},[v,e.onAgentLog,O.upsertMessage]);let[A,j]=G([]);H(()=>{g.listChats().then(e=>{j(e.map(e=>e.key))})},[g]),H(()=>{T&&!A.includes(T)&&j(e=>[...e,T])},[T,A]);let M=U(()=>$r(t),[t]),N=ui({id:M,disabled:!b?.request,onRequest:async t=>{if(!_)throw Error(`No agent`);let n=new URL(t.url),r=new URL(_.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(e){return console.error(`Error sending request to user's agent:`,e),new Response(`Internal server error`,{status:500})}}});H(()=>{N.status===`connected`&&e.onDevhookConnected?.(`https://${N.id}.dev.blink.host`)},[N.status,N.id]);let{schema:P,options:ee,error:te,setOption:I}=li({agent:n===`run`?_:x,capabilities:b,messages:O.messages});H(()=>{D.current=ee},[ee]);let L=U(()=>{let e=[];return y&&n===`run`&&e.push(y.message),S&&n===`edit`&&e.push(`Edit agent error: ${S.message}`),O.error&&c!==`building`&&e.push(`Chat error: ${O.error}`),te&&e.push(`Options error: ${te.message}`),e},[y,S,O.error,te,n,c]);H(()=>{for(let t of L)e.onError?.(t)},[L]);let[ne,R]=G(),[z,B]=G(!1),K=U(()=>{let e=[...O.messages].reverse().find(e=>!(e.role!==`assistant`||e.metadata&&e.metadata.ephemeral));if(!e||ne===e.id)return;let t=e.parts.filter(F);if(t.length!==0&&t.some(e=>l(e.output)&&e.output.outcome===`pending`))return e},[O.messages,ne]),re=V(async(e,t)=>{if(!K)return;t&&e&&B(!0),R(K.id);let n=O.messages;if(n.length===0)return;let r=n[n.length-1];if(!r||r.role!==`assistant`||!Array.isArray(r.parts))return;let i=r.parts.map(t=>t.output&&l(t.output)&&t.output.outcome===`pending`?{...t,output:{...t.output,outcome:e?`approved`:`rejected`}}:t);await O.upsertMessage({...r,parts:i}),await O.start()},[K,O]);H(()=>{z&&K&&re(!0)},[z,K,re]);let q=V(()=>{let e=crypto.randomUUID();E(e),j(t=>[...t,e])},[]),J=U(()=>{if(K)return{message:K,approve:e=>re(!0,e),reject:()=>re(!1),autoApproveEnabled:z}},[K,re,z]),ie=U(()=>{let e=O.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}}},[O.messages]),Y=U(()=>{if(O.status!==`streaming`)return!1;if(!O.streamingMessage)return!0;let e=O.streamingMessage.parts.filter(F);return e.length>0&&e.every(e=>e.state.startsWith(`output-`))},[O.status,O.streamingMessage]);return{mode:n,setMode:a,toggleMode:o,chat:O,chats:A,switchChat:E,newChat:q,build:{status:c,error:s,entrypoint:d},devhook:{connected:N.status===`connected`,url:N.status===`connected`?`https://${N.id}.dev.blink.host`:void 0},capabilities:b,options:{schema:P,selected:ee,error:te,setOption:I},approval:J,tokenUsage:ie,server:g,showWaitingPlaceholder:Y}}export{ce as useAgent,ue as useBundler,Ve as useChat,mu as useDevMode,ui as useDevhook,mi as useDotenv,fu as useEditAgent,li as useOptions};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blink",
3
- "version": "0.1.107",
3
+ "version": "0.1.109",
4
4
  "description": "Blink is a JavaScript runtime for building and deploying AI agents.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,28 +0,0 @@
1
- import{__commonJSMin as e,__require as t}from"./chunk-D9KrCrVq.js";import n,{dirname as r,join as i}from"path";import{existsSync as a}from"fs";import{builtinModules as o}from"module";import{mkdir as s,rm as c,stat as l,writeFile as u}from"fs/promises";const d=`ai-telemetry-wrapper`;function f(e={}){let{functions:t=[`streamText`,`generateText`,`generateObject`,`streamObject`,`embed`,`embedMany`],telemetryConfig:n={isEnabled:!0}}=e;return{name:`ai-telemetry`,setup(e){e.onResolve({filter:/^ai$/},e=>{if(e.namespace!==d)return{path:`ai`,namespace:d,pluginData:{resolveDir:e.resolveDir}}}),e.onLoad({filter:/^ai$/,namespace:d},e=>{let r=JSON.stringify(n),i=e.pluginData;return{contents:`
2
- // Import everything from the original 'ai' package
3
- import * as aiOriginal from 'ai';
4
-
5
- // Re-export everything from 'ai'
6
- export * from 'ai';
7
-
8
- // Create wrapped versions that inject telemetry by default
9
- ${t.map(e=>`
10
- export function ${e}(options) {
11
- // If experimental_telemetry is not provided, inject the default
12
- if (!options || !options.experimental_telemetry) {
13
- return aiOriginal.${e}({
14
- ...options,
15
- experimental_telemetry: ${r}
16
- });
17
- }
18
- // If it's already provided, use the original function as-is
19
- return aiOriginal.${e}(options);
20
- }
21
- `).join(``)}
22
- `,loader:`js`,resolveDir:i?.resolveDir}})}}}function p(e){return async t=>{let r=await(await import(`esbuild`)).context({entryPoints:[t.entry],outdir:t.outdir,bundle:!0,write:!1,logLevel:`silent`,format:`esm`,platform:`node`,target:`node22`,sourcemap:!1,mainFields:[`module`,`main`],conditions:[`import`,`module`],plugins:[{name:`blink-esm-require-to-import`,setup(e){e.onEnd(t=>{e.initialOptions.format!==`esm`||e.initialOptions.platform!==`node`||t.outputFiles?.forEach(e=>{if(e.path.endsWith(`.js`)||e.path.endsWith(`.mjs`)){let t=Buffer.from(e.contents).toString(`utf-8`),n=new Map,r=RegExp(`\\b__require\\("(node:)?(${o.join(`|`)})(/[^"]+)?"\\)`,`gm`);t=t.replace(r,(e,t,r,i=``)=>{let a=r+i,o=`__import_${a.toUpperCase().replace(/[/-]/g,`_`)}`,s=`node:${a}`;return n.set(o,s),o}),n.size>0&&(t=Array.from(n.entries()).map(([e,t])=>`import ${e} from "${t}";`).join(`
23
- `)+`
24
-
25
- `+t),e.contents=Buffer.from(t,`utf-8`)}})})}},{name:`blink-dev-server`,setup(e){let i;e.onStart(()=>{t.onStart(),i=performance.now()}),e.onEnd(async e=>{await c(t.outdir,{recursive:!0,force:!0}),await s(t.outdir,{recursive:!0});let a=e.outputFiles?.map(e=>({path:e.path,contents:e.contents}))??[];a.push({path:n.resolve(t.outdir,`package.json`),contents:Buffer.from(JSON.stringify({type:`module`},null,2),`utf-8`)});for(let e of a)await u(e.path,e.contents);e.errors.length>0?t.onResult({error:{message:e.errors.map(e=>`${e.text} (${e.location?.file})`).join(`
26
- `)}}):t.onResult({entry:n.resolve(t.outdir,n.basename(t.entry).replace(`.ts`,`.js`)),duration:performance.now()-i,outdir:t.outdir,warnings:e.warnings.map(e=>({message:e.text,file:e.location?.file}))}),t.watch||(r.dispose(),r.cancel())})}},f()],...e});await r.watch()}}function m(e){let r=[`blink.config.ts`],i;for(let o of r){let r=n.resolve(e,o);if(a(r)){let e=t(r);if(e.default){i={...e.default};break}}}if(i||={},!i.entry){for(let t of[`src/agent.ts`,`src/agent.js`,`agent.ts`,`agent.js`]){let r=n.resolve(e,t);if(a(r)){i.entry=r;break}}if(!i.entry)throw Error(`Agent entrypoint not found.
27
-
28
- Try creating "agent.ts" or specify "entry" in a blink.config.ts file.`)}return i.outdir||=n.resolve(e,`data/build`),i.build||=p(),i}async function h(e,t){let n=e;for(;n!==r(n);){let e=i(n,t);try{return await l(e),e}catch{}n=r(n)}}var g=e(((e,t)=>{function n(e){return Array.isArray(e)?e:[e]}let r=/^\s+$/,i=/(?:[^\\]|^)\\$/,a=/^\\!/,o=/^\\#/,s=/\r?\n/g,c=/^\.{0,2}\/|^\.{1,2}$/,l=/\/$/,u=`node-ignore`;typeof Symbol<`u`&&(u=Symbol.for(`node-ignore`));let d=u,f=(e,t,n)=>(Object.defineProperty(e,t,{value:n}),n),p=/([0-z])-([0-z])/g,m=()=>!1,h=e=>e.replace(p,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:``),g=e=>{let{length:t}=e;return e.slice(0,t-t%2)},_=[[/^\uFEFF/,()=>``],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf(`\\`)===0?` `:``)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+` `}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>`[^/]`],[/^\//,()=>`^`],[/\//g,()=>`\\/`],[/^\^*\\\*\\\*\\\//,()=>`^(?:.*\\/)?`],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?`^`:`(?:^|\\/)`}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,n)=>t+6<n.length?`(?:\\/[^\\/]+)*`:`\\/.+`],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,n)=>{let r=n.replace(/\\\*/g,`[^\\/]*`);return t+r}],[/\\\\\\(?=[$.|*+(){^])/g,()=>`\\`],[/\\\\/g,()=>`\\`],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,r,i)=>t===`\\`?`\\[${n}${g(r)}${i}`:i===`]`&&r.length%2==0?`[${h(n)}${r}]`:`[]`],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`]],v=/(^|\\\/)?\\\*$/,y=`regex`,b=`checkRegex`,x={[y](e,t){return`${t?`${t}[^/]+`:`[^/]*`}(?=$|\\/$)`},[b](e,t){return`${t?`${t}[^/]*`:`[^/]*`}(?=$|\\/$)`}},S=e=>_.reduce((t,[n,r])=>t.replace(n,r.bind(e)),e),C=e=>typeof e==`string`,w=e=>e&&C(e)&&!r.test(e)&&!i.test(e)&&e.indexOf(`#`)!==0,T=e=>e.split(s).filter(Boolean);var E=class{constructor(e,t,n,r,i,a){this.pattern=e,this.mark=t,this.negative=i,f(this,`body`,n),f(this,`ignoreCase`,r),f(this,`regexPrefix`,a)}get regex(){let e=`_`+y;return this[e]?this[e]:this._make(y,e)}get checkRegex(){let e=`_`+b;return this[e]?this[e]:this._make(b,e)}_make(e,t){let n=this.regexPrefix.replace(v,x[e]),r=this.ignoreCase?new RegExp(n,`i`):new RegExp(n);return f(this,t,r)}};let D=({pattern:e,mark:t},n)=>{let r=!1,i=e;i.indexOf(`!`)===0&&(r=!0,i=i.substr(1)),i=i.replace(a,`!`).replace(o,`#`);let s=S(i);return new E(e,t,i,n,r,s)};var O=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[d]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(C(e)&&(e={pattern:e}),w(e.pattern)){let t=D(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,n(C(e)?T(e):e).forEach(this._add,this),this._added}test(e,t,n){let r=!1,i=!1,a;this._rules.forEach(o=>{let{negative:s}=o;i===s&&r!==i||s&&!r&&!i&&!t||o[n].test(e)&&(r=!s,i=s,a=s?void 0:o)});let o={ignored:r,unignored:i};return a&&(o.rule=a),o}};let k=(e,t)=>{throw new t(e)},A=(e,t,n)=>C(e)?e?A.isNotRelative(e)?n(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):!0:n(`path must not be empty`,TypeError):n(`path must be a string, but got \`${t}\``,TypeError),j=e=>c.test(e);A.isNotRelative=j,A.convert=e=>e;var M=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){f(this,d,!0),this._rules=new O(t),this._strictPathCheck=!n,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(e){return this._rules.add(e)&&this._initCache(),this}addPattern(e){return this.add(e)}_test(e,t,n,r){let i=e&&A.convert(e);return A(i,e,this._strictPathCheck?k:m),this._t(i,t,n,r)}checkIgnore(e){if(!l.test(e))return this.test(e);let t=e.split(`/`).filter(Boolean);if(t.pop(),t.length){let e=this._t(t.join(`/`)+`/`,this._testCache,!0,t);if(e.ignored)return e}return this._rules.test(e,!1,b)}_t(e,t,n,r){if(e in t)return t[e];if(r||=e.split(`/`).filter(Boolean),r.pop(),!r.length)return t[e]=this._rules.test(e,n,y);let i=this._t(r.join(`/`)+`/`,t,n,r);return t[e]=i.ignored?i:this._rules.test(e,n,y)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return n(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}};let N=e=>new M(e),P=e=>A(e&&A.convert(e),e,m),F=()=>{A.convert=e=>/^\\\\\?\\/.test(e)||/["<>|\u0000-\u001F]+/u.test(e)?e:e.replace(/\\/g,`/`);let e=/^[a-z]:\//i;A.isNotRelative=t=>e.test(t)||j(t)};typeof process<`u`&&process.platform===`win32`&&F(),t.exports=N,N.default=N,t.exports.isPathValid=P,f(t.exports,Symbol.for(`setupWindows`),F)}));export{h as findNearestEntry,g as require_ignore,m as resolveConfig};
@@ -1 +0,0 @@
1
- import{__toESM as e}from"./chunk-D9KrCrVq.js";import{getAuthToken as t}from"./auth-DjAEZyZZ.js";import"./dist-BNbSDxaw.js";import"./open-DCYivxgo.js";import{migrateBlinkToData as n,require_main as r}from"./main-BdSSlDIs.js";import{ChatManager as i,Client as a}from"./chat-manager-BL3XfguD.js";import{spawn as o}from"node:child_process";import{join as s,resolve as c}from"node:path";import{readFile as l}from"node:fs/promises";import{createServer as u}from"node:net";async function d(e){let t=e.env?.PORT??await f(),n=e.env?.HOST??`127.0.0.1`,r=`http://${n}:${t}`,i={...e.env??process.env,PORT:t.toString(),HOST:n},s=o(e.command,e.args,{stdio:`pipe`,env:i});e.signal?.addEventListener(`abort`,()=>{try{s.kill()}catch{}},{once:!0});let c=new AbortController,l=[c.signal];e.signal&&l.push(e.signal);let u=AbortSignal.any(l);s.stdout.on(`data`,t=>{e.onStdout?.(Buffer.from(t).toString(`utf-8`))});let d=``;s.stderr.on(`data`,t=>{c.signal.aborted||(d+=Buffer.from(t).toString(`utf-8`)),e.onStderr?.(Buffer.from(t).toString(`utf-8`))}),s.on(`error`,e=>{c.abort(e)}),s.on(`exit`,(t,n)=>{c.signal.aborted?e.onExit?.(t,n):c.abort()});let p=new a({baseUrl:r}),m=0;for(;!u.aborted;){try{await p.health();break}catch{}if(await new Promise(e=>setTimeout(e,m*5)),m++,m>100)throw Error(`Health endpoint timed out`)}if(u.aborted)throw u.reason;return c.abort(),{client:p,dispose:()=>{s.kill()}}}async function f(){let e=u();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}var p=e(r(),1);async function m(e,r){let a=c(r?.directory??process.cwd());await n(a);let o=(0,p.parse)(await l(s(a,`.env.local`),`utf-8`)),u=await t(),f=await d({command:`node`,args:[`--experimental-strip-types`,`--no-deprecation`,c(a,`agent.ts`)],env:{...process.env,...o,BLINK_TOKEN:u}}),m=c(r?.directory??process.cwd(),`data`,`chats`),h=r?.chat??`default`,g=new i({chatId:h,chatsDirectory:m});g.setAgent(f.client);try{await g.sendMessage({id:crypto.randomUUID(),created_at:new Date().toISOString(),metadata:void 0,parts:[{type:`text`,text:e.join(` `)}],role:`user`,mode:`run`}),await new Promise(e=>{let t=g.subscribe(n=>{(n.status===`idle`||n.status===`error`)&&(t(),e()),n.streamingMessage&&console.log(n.streamingMessage)})});let t=g.getState();t.error&&console.error(`Error:`,t.error)}finally{g.dispose(),f.dispose()}}export{m as default};