blink 0.1.97 → 0.1.99

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-hG-farUz.js";import"../token-error-488npYdU.js";import"../esm-CbZfjZBn.js";import{resolveConfig as h}from"../build-D_4dvv5-.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=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:t,metadata:e.metadata});function ze(e){return typeof e==`object`&&e?.__blink_internal===!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=Re(n,i),o=t.messages.find(e=>e.id===a.id)?t.messages.map(e=>e.id===a.id?a:e):[...t.messages,a];this.chat={...t,updated_at:new Date().toISOString(),messages:o},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.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;let e=new AbortController;this.abortController=e,this.chat.error=void 0;let t;try{t=await this.chatStore.lock(this.chatId);let n=!0;for(;this.queue.length>0||n;){n=!1;let r=this.queue.shift();this.status=`streaming`,this.streamingMessage=void 0,r&&await this.upsertMessage(r,t);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:e.signal,messages:i}),o=async e=>{this.chat.updated_at=new Date().toISOString(),this.chat.messages.push(Re(e)),this.streamingMessage=void 0,await t?.set(this.chat)},s=a.getReader();try{for(;;){let{done:t,value:n}=await s.read();if(t||e.signal.aborted)break;this.streamingMessage&&n.id!==this.streamingMessage.id&&await o(this.streamingMessage),this.streamingMessage=n,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`,t&&(this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),await t.release(),this.notifyListeners())}}stopStreaming(){this.abortController?.abort(),this.queue.length>0&&setTimeout(()=>{this.processQueueOrRun()},100)}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)},[]);return{...s,sendMessage:l,upsertMessage:u,stopStreaming:d,resetChat:f,clearQueue:p,deleteMessage:m}}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-hG-farUz.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=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:t,metadata:e.metadata});function ze(e){return typeof e==`object`&&e?.__blink_internal===!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=Re(n,i),o=t.messages.find(e=>e.id===a.id)?t.messages.map(e=>e.id===a.id?a:e):[...t.messages,a];this.chat={...t,updated_at:new Date().toISOString(),messages:o},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.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;let e=new AbortController;this.abortController=e,this.chat.error=void 0;let t;try{t=await this.chatStore.lock(this.chatId);let n=!0;for(;this.queue.length>0||n;){n=!1;let r=this.queue.shift();this.status=`streaming`,this.streamingMessage=void 0,r&&await this.upsertMessage(r,t);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:e.signal,messages:i}),o=async e=>{this.chat.updated_at=new Date().toISOString(),this.chat.messages.push(Re(e)),this.streamingMessage=void 0,await t?.set(this.chat)},s=a.getReader();try{for(;;){let{done:t,value:n}=await s.read();if(t||e.signal.aborted)break;this.streamingMessage&&n.id!==this.streamingMessage.id&&await o(this.streamingMessage),this.streamingMessage=n,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`,t&&(this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),await t.release(),this.notifyListeners())}}stopStreaming(){this.abortController?.abort(),this.queue.length>0&&setTimeout(()=>{this.processQueueOrRun()},100)}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)},[]);return{...s,sendMessage:l,upsertMessage:u,stopStreaming:d,resetChat:f,clearQueue:p,deleteMessage:m}}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]===`
@@ -56,7 +56,7 @@ ${Yr}${t.trimStart()}`),n=3+b(t.trimStart()).length)}process.stdout.write(`
56
56
  `));let r=e.pax;if(r)for(let e in r)n+=y(` `+e+`=`+r[e]+`
57
57
  `);return t.from(n)},e.decodePax=function(e){let n={};for(;e.length;){let r=0;for(;r<e.length&&e[r]!==32;)r++;let i=parseInt(t.toString(e.subarray(0,r)),10);if(!i)return n;let a=t.toString(e.subarray(r+1,i-1)),o=a.indexOf(`=`);if(o===-1)return n;n[a.slice(0,o)]=a.slice(o+1),e=e.subarray(i)}return n},e.encode=function(e){let i=t.alloc(512),a=e.name,o=``;if(e.typeflag===5&&a[a.length-1]!==`/`&&(a+=`/`),t.byteLength(a)!==a.length)return null;for(;t.byteLength(a)>100;){let e=a.indexOf(`/`);if(e===-1)return null;o+=o?`/`+a.slice(0,e):a.slice(0,e),a=a.slice(e+1)}return t.byteLength(a)>100||t.byteLength(o)>155||e.linkname&&t.byteLength(e.linkname)>100?null:(t.write(i,a),t.write(i,p(e.mode&4095,6),100),t.write(i,p(e.uid,6),108),t.write(i,p(e.gid,6),116),h(e.size,i,124),t.write(i,p(e.mtime.getTime()/1e3|0,11),136),i[156]=48+u(e.type),e.linkname&&t.write(i,e.linkname,157),t.copy(n,i,257),t.copy(r,i,263),e.uname&&t.write(i,e.uname,265),e.gname&&t.write(i,e.gname,297),t.write(i,p(e.devmajor||0,6),329),t.write(i,p(e.devminor||0,6),337),o&&t.write(i,o,345),t.write(i,p(f(i),6),148),i)},e.decode=function(e,t,n){let r=e[156]===0?0:e[156]-48,i=v(e,0,100,t),a=_(e,100,8),c=_(e,108,8),u=_(e,116,8),d=_(e,124,12),p=_(e,136,12),m=l(r),h=e[157]===0?null:v(e,157,100,t),g=v(e,265,32),y=v(e,297,32),b=_(e,329,8),x=_(e,337,8),S=f(e);if(S===256)return null;if(S!==_(e,148,8))throw Error(`Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?`);if(o(e))e[345]&&(i=v(e,345,155,t)+`/`+i);else if(!s(e)&&!n)throw Error(`Invalid tar header: unknown format.`);return r===0&&i&&i[i.length-1]===`/`&&(r=5),{name:i,mode:a,uid:c,gid:u,size:d,mtime:new Date(1e3*p),type:m,linkname:h,uname:g,gname:y,devmajor:b,devminor:x,pax:null}};function o(e){return t.equals(n,e.subarray(257,263))}function s(e){return t.equals(i,e.subarray(257,263))&&t.equals(a,e.subarray(263,265))}function c(e,t,n){return typeof e==`number`?(e=~~e,e>=t?t:e>=0||(e+=t,e>=0)?e:0):n}function l(e){switch(e){case 0:return`file`;case 1:return`link`;case 2:return`symlink`;case 3:return`character-device`;case 4:return`block-device`;case 5:return`directory`;case 6:return`fifo`;case 7:return`contiguous-file`;case 72:return`pax-header`;case 55:return`pax-global-header`;case 27:return`gnu-long-link-path`;case 28:case 30:return`gnu-long-path`}return null}function u(e){switch(e){case`file`:return 0;case`link`:return 1;case`symlink`:return 2;case`character-device`:return 3;case`block-device`:return 4;case`directory`:return 5;case`fifo`:return 6;case`contiguous-file`:return 7;case`pax-header`:return 72}return 0}function d(e,t,n,r){for(;n<r;n++)if(e[n]===t)return n;return r}function f(e){let t=256;for(let n=0;n<148;n++)t+=e[n];for(let n=156;n<512;n++)t+=e[n];return t}function p(e,t){return e=e.toString(8),e.length>t?`7777777777777777777`.slice(0,t)+` `:`0000000000000000000`.slice(0,t-e.length)+e+` `}function m(e,t,n){t[n]=128;for(let r=11;r>0;r--)t[n+r]=e&255,e=Math.floor(e/256)}function h(e,n,r){e.toString(8).length>11?m(e,n,r):t.write(n,p(e,11),r)}function g(e){let t;if(e[0]===128)t=!0;else if(e[0]===255)t=!1;else return null;let n=[],r;for(r=e.length-1;r>0;r--){let i=e[r];t?n.push(i):n.push(255-i)}let i=0,a=n.length;for(r=0;r<a;r++)i+=n[r]*256**r;return t?i:-1*i}function _(e,n,r){if(e=e.subarray(n,n+r),n=0,e[n]&128)return g(e);{for(;n<e.length&&e[n]===32;)n++;let r=c(d(e,32,n,e.length),e.length,e.length);for(;n<r&&e[n]===0;)n++;return r===n?0:parseInt(t.toString(e.subarray(n,r)),8)}}function v(e,n,r,i){return t.toString(e.subarray(n,d(e,0,n,n+r)),i)}function y(e){let n=t.byteLength(e),r=Math.floor(Math.log(n)/Math.log(10))+1;return n+r>=10**r&&r++,n+r+e}})}),hs=Xi({"../../node_modules/tar-stream/extract.js":((e,t)=>{let{Writable:n,Readable:r,getStreamError:i}=ps(),a=cs(),o=ls(),s=ms(),c=o.alloc(0);var l=class{constructor(){this.buffered=0,this.shifted=0,this.queue=new a,this._offset=0}push(e){this.buffered+=e.byteLength,this.queue.push(e)}shiftFirst(e){return this._buffered===0?null:this._next(e)}shift(e){if(e>this.buffered)return null;if(e===0)return c;let t=this._next(e);if(e===t.byteLength)return t;let n=[t];for(;(e-=t.byteLength)>0;)t=this._next(e),n.push(t);return o.concat(n)}_next(e){let t=this.queue.peek(),n=t.byteLength-this._offset;if(e>=n){let e=this._offset?t.subarray(this._offset,t.byteLength):t;return this.queue.shift(),this._offset=0,this.buffered-=n,this.shifted+=n,e}return this.buffered-=e,this.shifted+=e,t.subarray(this._offset,this._offset+=e)}},u=class extends r{constructor(e,t,n){super(),this.header=t,this.offset=n,this._parent=e}_read(e){this.header.size===0&&this.push(null),this._parent._stream===this&&this._parent._update(),e(null)}_predestroy(){this._parent.destroy(i(this))}_detach(){this._parent._stream===this&&(this._parent._stream=null,this._parent._missing=p(this.header.size),this._parent._update())}_destroy(e){this._detach(),e(null)}},d=class extends n{constructor(e){super(e),e||={},this._buffer=new l,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=f,this._locked=!1,this._finished=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null,this._filenameEncoding=e.filenameEncoding||`utf-8`,this._allowUnknownFormat=!!e.allowUnknownFormat,this._unlockBound=this._unlock.bind(this)}_unlock(e){if(this._locked=!1,e){this.destroy(e),this._continueWrite(e);return}this._update()}_consumeHeader(){if(this._locked)return!1;this._offset=this._buffer.shifted;try{this._header=s.decode(this._buffer.shift(512),this._filenameEncoding,this._allowUnknownFormat)}catch(e){return this._continueWrite(e),!1}if(!this._header)return!0;switch(this._header.type){case`gnu-long-path`:case`gnu-long-link-path`:case`pax-global-header`:case`pax-header`:return this._longHeader=!0,this._missing=this._header.size,!0}return this._locked=!0,this._applyLongHeaders(),this._header.size===0||this._header.type===`directory`?(this.emit(`entry`,this._header,this._createStream(),this._unlockBound),!0):(this._stream=this._createStream(),this._missing=this._header.size,this.emit(`entry`,this._header,this._stream,this._unlockBound),!0)}_applyLongHeaders(){this._gnuLongPath&&=(this._header.name=this._gnuLongPath,null),this._gnuLongLinkPath&&=(this._header.linkname=this._gnuLongLinkPath,null),this._pax&&=(this._pax.path&&(this._header.name=this._pax.path),this._pax.linkpath&&(this._header.linkname=this._pax.linkpath),this._pax.size&&(this._header.size=parseInt(this._pax.size,10)),this._header.pax=this._pax,null)}_decodeLongHeader(e){switch(this._header.type){case`gnu-long-path`:this._gnuLongPath=s.decodeLongPath(e,this._filenameEncoding);break;case`gnu-long-link-path`:this._gnuLongLinkPath=s.decodeLongPath(e,this._filenameEncoding);break;case`pax-global-header`:this._paxGlobal=s.decodePax(e);break;case`pax-header`:this._pax=this._paxGlobal===null?s.decodePax(e):Object.assign({},this._paxGlobal,s.decodePax(e));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=p(this._header.size);let e=this._buffer.shift(this._header.size);try{this._decodeLongHeader(e)}catch(e){return this._continueWrite(e),!1}return!0}_consumeStream(){let e=this._buffer.shiftFirst(this._missing);if(e===null)return!1;this._missing-=e.byteLength;let t=this._stream.push(e);return this._missing===0?(this._stream.push(null),t&&this._stream._detach(),t&&this._locked===!1):t}_createStream(){return new u(this,this._header,this._offset)}_update(){for(;this._buffer.buffered>0&&!this.destroying;){if(this._missing>0){if(this._stream!==null){if(this._consumeStream()===!1)return;continue}if(this._longHeader===!0){if(this._missing>this._buffer.buffered)break;if(this._consumeLongHeader()===!1)return!1;continue}let e=this._buffer.shiftFirst(this._missing);e!==null&&(this._missing-=e.byteLength);continue}if(this._buffer.buffered<512)break;if(this._stream!==null||this._consumeHeader()===!1)return}this._continueWrite(null)}_continueWrite(e){let t=this._callback;this._callback=f,t(e)}_write(e,t){this._callback=t,this._buffer.push(e),this._update()}_final(e){this._finished=this._missing===0&&this._buffer.buffered===0,e(this._finished?null:Error(`Unexpected end of data`))}_predestroy(){this._continueWrite(null)}_destroy(e){this._stream&&this._stream.destroy(i(this)),e(null)}[Symbol.asyncIterator](){let e=null,t=null,n=null,r=null,i=null,a=this;return this.on(`entry`,c),this.on(`error`,t=>{e=t}),this.on(`close`,l),{[Symbol.asyncIterator](){return this},next(){return new Promise(s)},return(){return u(null)},throw(e){return u(e)}};function o(e){if(!i)return;let t=i;i=null,t(e)}function s(i,s){if(e)return s(e);if(r){i({value:r,done:!1}),r=null;return}t=i,n=s,o(null),a._finished&&t&&(t({value:void 0,done:!0}),t=n=null)}function c(e,a,o){i=o,a.on(`error`,f),t?(t({value:a,done:!1}),t=n=null):r=a}function l(){o(e),t&&=(e?n(e):t({value:void 0,done:!0}),n=null)}function u(e){return a.destroy(e),o(e),new Promise((t,n)=>{if(a.destroyed)return t({value:void 0,done:!0});a.once(`close`,function(){e?n(e):t({value:void 0,done:!0})})})}}};t.exports=function(e){return new d(e)};function f(){}function p(e){return e&=511,e&&512-e}})}),gs=Xi({"../../node_modules/tar-stream/constants.js":((e,t)=>{let n={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{t.exports=$i(`fs`).constants||n}catch{t.exports=n}})}),_s=Xi({"../../node_modules/tar-stream/pack.js":((e,t)=>{let{Readable:n,Writable:r,getStreamError:i}=ps(),a=ls(),o=gs(),s=ms(),c=a.alloc(1024);var l=class extends r{constructor(e,t,n){super({mapWritable:m,eagerOpen:!0}),this.written=0,this.header=t,this._callback=n,this._linkname=null,this._isLinkname=t.type===`symlink`&&!t.linkname,this._isVoid=t.type!==`file`&&t.type!==`contiguous-file`,this._finished=!1,this._pack=e,this._openCallback=null,this._pack._stream===null?this._pack._stream=this:this._pack._pending.push(this)}_open(e){this._openCallback=e,this._pack._stream===this&&this._continueOpen()}_continuePack(e){if(this._callback===null)return;let t=this._callback;this._callback=null,t(e)}_continueOpen(){this._pack._stream===null&&(this._pack._stream=this);let e=this._openCallback;if(this._openCallback=null,e!==null){if(this._pack.destroying)return e(Error(`pack stream destroyed`));if(this._pack._finalized)return e(Error(`pack stream is already finalized`));this._pack._stream=this,this._isLinkname||this._pack._encode(this.header),this._isVoid&&(this._finish(),this._continuePack(null)),e(null)}}_write(e,t){if(this._isLinkname)return this._linkname=this._linkname?a.concat([this._linkname,e]):e,t(null);if(this._isVoid)return e.byteLength>0?t(Error(`No body allowed for this entry`)):t();if(this.written+=e.byteLength,this._pack.push(e))return t();this._pack._drain=t}_finish(){this._finished||(this._finished=!0,this._isLinkname&&(this.header.linkname=this._linkname?a.toString(this._linkname,`utf-8`):``,this._pack._encode(this.header)),p(this._pack,this.header.size),this._pack._done(this))}_final(e){if(this.written!==this.header.size)return e(Error(`Size mismatch`));this._finish(),e(null)}_getError(){return i(this)||Error(`tar entry destroyed`)}_predestroy(){this._pack.destroy(this._getError())}_destroy(e){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),e()}},u=class extends n{constructor(e){super(e),this._drain=f,this._finalized=!1,this._finalizing=!1,this._pending=[],this._stream=null}entry(e,t,n){if(this._finalized||this.destroying)throw Error(`already finalized or destroyed`);typeof t==`function`&&(n=t,t=null),n||=f,(!e.size||e.type===`symlink`)&&(e.size=0),e.type||=d(e.mode),e.mode||=e.type===`directory`?493:420,e.uid||=0,e.gid||=0,e.mtime||=new Date,typeof t==`string`&&(t=a.from(t));let r=new l(this,e,n);return a.isBuffer(t)?(e.size=t.byteLength,r.write(t),r.end(),r):(r._isVoid,r)}finalize(){if(this._stream||this._pending.length>0){this._finalizing=!0;return}this._finalized||(this._finalized=!0,this.push(c),this.push(null))}_done(e){e===this._stream&&(this._stream=null,this._finalizing&&this.finalize(),this._pending.length&&this._pending.shift()._continueOpen())}_encode(e){if(!e.pax){let t=s.encode(e);if(t){this.push(t);return}}this._encodePax(e)}_encodePax(e){let t=s.encodePax({name:e.name,linkname:e.linkname,pax:e.pax}),n={name:`PaxHeader`,mode:e.mode,uid:e.uid,gid:e.gid,size:t.byteLength,mtime:e.mtime,type:`pax-header`,linkname:e.linkname&&`PaxHeader`,uname:e.uname,gname:e.gname,devmajor:e.devmajor,devminor:e.devminor};this.push(s.encode(n)),this.push(t),p(this,t.byteLength),n.size=e.size,n.type=e.type,this.push(s.encode(n))}_doDrain(){let e=this._drain;this._drain=f,e()}_predestroy(){let e=i(this);for(this._stream&&this._stream.destroy(e);this._pending.length;){let t=this._pending.shift();t.destroy(e),t._continueOpen()}this._doDrain()}_read(e){this._doDrain(),e()}};t.exports=function(e){return new u(e)};function d(e){switch(e&o.S_IFMT){case o.S_IFBLK:return`block-device`;case o.S_IFCHR:return`character-device`;case o.S_IFDIR:return`directory`;case o.S_IFIFO:return`fifo`;case o.S_IFLNK:return`symlink`}return`file`}function f(){}function p(e,t){t&=511,t&&e.push(c.subarray(0,512-t))}function m(e){return a.isBuffer(e)?e:a.from(e)}})}),vs=Qi(Xi({"../../node_modules/tar-stream/index.js":(e=>{e.extract=hs(),e.pack=_s()})})(),1);const ys=async(e,t)=>{let{maxBytes:n=50*1024*1024}=t??{};if(!(await se.stat(e)).isDirectory())throw Error(`Path is not a directory: ${e}`);let r=vs.pack(),i=async(e,t=``)=>{let n=await se.readdir(e,{withFileTypes:!0});for(let a of n){let n=`${e}/${a.name}`,o=t?`${t}/${a.name}`:a.name;if(a.isDirectory()){r.entry({name:`${o}/`,type:`directory`}),await i(n,o);continue}if(a.isSymbolicLink?.()){let e=await se.readlink(n);r.entry({name:o,type:`symlink`,linkname:e});continue}if(a.isFile()){let e=await se.stat(n);await new Promise((t,i)=>{let a=v(n),s=r.entry({name:o,size:e.size,mode:e.mode,mtime:e.mtime},e=>{e&&i(e)});a.on(`error`,i),a.on(`data`,e=>s.write(e)),a.on(`end`,()=>{s.end(),t()})});continue}}};(async()=>{try{await i(e),r.finalize()}catch(e){r.destroy(e)}})();let a=r,o=0,s=!1;return new ReadableStream({start(e){a.on(`data`,t=>{if(!s){if(o+=t.length,o>n){s=!0,e.error(Error(`Archive exceeds size limit (${n} bytes). Emitted=${o} bytes.`));try{a.destroy()}catch{}return}e.enqueue(new Uint8Array(t))}}),a.once(`error`,t=>{s||(s=!0,e.error(t instanceof Error?t:Error(String(t))))}),a.once(`end`,()=>{s||(s=!0,e.close())})},cancel(){try{a.destroy()}catch{}}})};var bs=Xi({"../../node_modules/dotenv/package.json":((e,t)=>{t.exports={name:`dotenv`,version:`17.2.3`,description:`Loads environment variables from .env file`,main:`lib/main.js`,types:`lib/main.d.ts`,exports:{".":{types:`./lib/main.d.ts`,require:`./lib/main.js`,default:`./lib/main.js`},"./config":`./config.js`,"./config.js":`./config.js`,"./lib/env-options":`./lib/env-options.js`,"./lib/env-options.js":`./lib/env-options.js`,"./lib/cli-options":`./lib/cli-options.js`,"./lib/cli-options.js":`./lib/cli-options.js`,"./package.json":`./package.json`},scripts:{"dts-check":`tsc --project tests/types/tsconfig.json`,lint:`standard`,pretest:`npm run lint && npm run dts-check`,test:`tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000`,"test:coverage":`tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov`,prerelease:`npm test`,release:`standard-version`},repository:{type:`git`,url:`git://github.com/motdotla/dotenv.git`},homepage:`https://github.com/motdotla/dotenv#readme`,funding:`https://dotenvx.com`,keywords:[`dotenv`,`env`,`.env`,`environment`,`variables`,`config`,`settings`],readmeFilename:`README.md`,license:`BSD-2-Clause`,devDependencies:{"@types/node":`^18.11.3`,decache:`^4.6.2`,sinon:`^14.0.1`,standard:`^17.0.0`,"standard-version":`^9.5.0`,tap:`^19.2.0`,typescript:`^4.8.4`},engines:{node:`>=12`},browser:{fs:!1}}})}),xs=Qi(Xi({"../../node_modules/dotenv/lib/main.js":((e,t)=>{let n=$i(`fs`),r=$i(`path`),i=$i(`os`),a=$i(`crypto`),o=bs().version,s=[`🔐 encrypt with Dotenvx: https://dotenvx.com`,`🔐 prevent committing .env to code: https://dotenvx.com/precommit`,`🔐 prevent building .env in docker: https://dotenvx.com/prebuild`,`📡 add observability to secrets: https://dotenvx.com/ops`,`👥 sync secrets across teammates & machines: https://dotenvx.com/ops`,`🗂️ backup and recover secrets: https://dotenvx.com/ops`,`✅ audit secrets and track compliance: https://dotenvx.com/ops`,`🔄 add secrets lifecycle management: https://dotenvx.com/ops`,`🔑 add access controls to secrets: https://dotenvx.com/ops`,"🛠️ run anywhere with `dotenvx run -- yourcommand`",`⚙️ specify custom .env file path with { path: '/custom/path/.env' }`,`⚙️ enable debug logging with { debug: true }`,`⚙️ override existing env vars with { override: true }`,`⚙️ suppress all logs with { quiet: true }`,`⚙️ write to custom object with { processEnv: myObject }`,`⚙️ load multiple .env files with { path: ['.env.local', '.env'] }`];function c(){return s[Math.floor(Math.random()*s.length)]}function l(e){return typeof e==`string`?![`false`,`0`,`no`,`off`,``].includes(e.toLowerCase()):!!e}function u(){return process.stdout.isTTY}function d(e){return u()?`\x1b[2m${e}\x1b[0m`:e}let f=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function p(e){let t={},n=e.toString();n=n.replace(/\r\n?/gm,`
58
58
  `);let r;for(;(r=f.exec(n))!=null;){let e=r[1],n=r[2]||``;n=n.trim();let i=n[0];n=n.replace(/^(['"`])([\s\S]*)\1$/gm,`$2`),i===`"`&&(n=n.replace(/\\n/g,`
59
- `),n=n.replace(/\\r/g,`\r`)),t[e]=n}return t}function m(e){e||={};let t=b(e);e.path=t;let n=D.configDotenv(e);if(!n.parsed){let e=Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code=`MISSING_DATA`,e}let r=v(e).split(`,`),i=r.length,a;for(let e=0;e<i;e++)try{let t=r[e].trim(),i=y(n,t);a=D.decrypt(i.ciphertext,i.key);break}catch(t){if(e+1>=i)throw t}return D.parse(a)}function h(e){console.error(`[dotenv@${o}][WARN] ${e}`)}function g(e){console.log(`[dotenv@${o}][DEBUG] ${e}`)}function _(e){console.log(`[dotenv@${o}] ${e}`)}function v(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:``}function y(e,t){let n;try{n=new URL(t)}catch(e){if(e.code===`ERR_INVALID_URL`){let e=Error(`INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development`);throw e.code=`INVALID_DOTENV_KEY`,e}throw e}let r=n.password;if(!r){let e=Error(`INVALID_DOTENV_KEY: Missing key part`);throw e.code=`INVALID_DOTENV_KEY`,e}let i=n.searchParams.get(`environment`);if(!i){let e=Error(`INVALID_DOTENV_KEY: Missing environment part`);throw e.code=`INVALID_DOTENV_KEY`,e}let a=`DOTENV_VAULT_${i.toUpperCase()}`,o=e.parsed[a];if(!o){let e=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${a} in your .env.vault file.`);throw e.code=`NOT_FOUND_DOTENV_ENVIRONMENT`,e}return{ciphertext:o,key:r}}function b(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let r of e.path)n.existsSync(r)&&(t=r.endsWith(`.vault`)?r:`${r}.vault`);else t=e.path.endsWith(`.vault`)?e.path:`${e.path}.vault`;else t=r.resolve(process.cwd(),`.env.vault`);return n.existsSync(t)?t:null}function x(e){return e[0]===`~`?r.join(i.homedir(),e.slice(1)):e}function S(e){let t=l(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=l(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(t||!n)&&_(`Loading env from encrypted .env.vault`);let r=D._parseVault(e),i=process.env;return e&&e.processEnv!=null&&(i=e.processEnv),D.populate(i,r,e),{parsed:r}}function C(e){let t=r.resolve(process.cwd(),`.env`),i=`utf8`,a=process.env;e&&e.processEnv!=null&&(a=e.processEnv);let o=l(a.DOTENV_CONFIG_DEBUG||e&&e.debug),s=l(a.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?i=e.encoding:o&&g(`No encoding is specified. UTF-8 is used by default`);let u=[t];if(e&&e.path)if(!Array.isArray(e.path))u=[x(e.path)];else{u=[];for(let t of e.path)u.push(x(t))}let f,p={};for(let t of u)try{let r=D.parse(n.readFileSync(t,{encoding:i}));D.populate(p,r,e)}catch(e){o&&g(`Failed to load ${t} ${e.message}`),f=e}let m=D.populate(a,p,e);if(o=l(a.DOTENV_CONFIG_DEBUG||o),s=l(a.DOTENV_CONFIG_QUIET||s),o||!s){let e=Object.keys(m).length,t=[];for(let e of u)try{let n=r.relative(process.cwd(),e);t.push(n)}catch(t){o&&g(`Failed to load ${e} ${t.message}`),f=t}_(`injecting env (${e}) from ${t.join(`,`)} ${d(`-- tip: ${c()}`)}`)}return f?{parsed:p,error:f}:{parsed:p}}function w(e){if(v(e).length===0)return D.configDotenv(e);let t=b(e);return t?D._configVault(e):(h(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),D.configDotenv(e))}function T(e,t){let n=Buffer.from(t.slice(-64),`hex`),r=Buffer.from(e,`base64`),i=r.subarray(0,12),o=r.subarray(-16);r=r.subarray(12,-16);try{let e=a.createDecipheriv(`aes-256-gcm`,n,i);return e.setAuthTag(o),`${e.update(r)}${e.final()}`}catch(e){let t=e instanceof RangeError,n=e.message===`Invalid key length`,r=e.message===`Unsupported state or unable to authenticate data`;if(t||n){let e=Error(`INVALID_DOTENV_KEY: It must be 64 characters long (or more)`);throw e.code=`INVALID_DOTENV_KEY`,e}else if(r){let e=Error(`DECRYPTION_FAILED: Please check your DOTENV_KEY`);throw e.code=`DECRYPTION_FAILED`,e}else throw e}}function E(e,t,n={}){let r=!!(n&&n.debug),i=!!(n&&n.override),a={};if(typeof t!=`object`){let e=Error(`OBJECT_REQUIRED: Please check the processEnv argument being passed to populate`);throw e.code=`OBJECT_REQUIRED`,e}for(let n of Object.keys(t))Object.prototype.hasOwnProperty.call(e,n)?(i===!0&&(e[n]=t[n],a[n]=t[n]),r&&g(i===!0?`"${n}" is already defined and WAS overwritten`:`"${n}" is already defined and was NOT overwritten`)):(e[n]=t[n],a[n]=t[n]);return a}let D={configDotenv:C,_configVault:S,_parseVault:m,config:w,decrypt:T,parse:p,populate:E};t.exports.configDotenv=D.configDotenv,t.exports._configVault=D._configVault,t.exports._parseVault=D._parseVault,t.exports.config=D.config,t.exports.decrypt=D.decrypt,t.exports.parse=D.parse,t.exports.populate=D.populate,t.exports=D})})(),1);const Ss=(e,t)=>e.length<=t?e:e.slice(e.length-t),Cs=(e,t)=>{if(e.length===0)return{lines:[],truncated:!1};let n=0,r=e.length;for(let i=e.length-1;i>=0;i--){let a=e[i].length;if(n+a>t&&r!==e.length)break;n+=a,r=i}return r===0?{lines:e,truncated:!1}:{lines:e.slice(r),truncated:!0}};var ws=class{multiplexer;notificationStream;decoder=new TextDecoder;encoder=new TextEncoder;processManager;createDeploymentFromTar;proxyOnly;fetchProxyRequest;constructor(e){this.createDeploymentFromTar=e.createDeploymentFromTar,this.proxyOnly=e.proxyOnly,this.fetchProxyRequest=e.fetchProxyRequest,this.multiplexer=new sa({send:t=>{e.send(t)}}),this.multiplexer.onStream(e=>{this.handleStream(e)}),this.notificationStream=this.multiplexer.createStream(),this.processManager=new ns({env:e.env,nodePty:e.nodePty}),this.processManager.onSpawn(e=>{let t=()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})};t(),e.terminal.onTitleChange(()=>{t()}),e.onExit(()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})}),e.onOutput(t=>{let n=ia.getMaxPayloadSize()-1;for(let r=0;r<t.length;r+=n){let i=t.slice(r,r+n);this.sendNotification({type:`process_output`,payload:{pid:e.pid,output:i}})}})})}handleMessage(e){this.multiplexer.handleMessage(e)}handleStream(e){let t=new AbortController;e.onClose(()=>{t.abort()}),e.onData(n=>{let r=n[0],i=n.subarray(1);switch(r){case _i.REQUEST:{let n=JSON.parse(this.decoder.decode(i));if(this.proxyOnly){this.sendResponse(e,{id:n.id,error:`This server is in proxy only mode.`});return}this.handleRequest(e,n,t.signal).catch(t=>{this.sendResponse(e,{id:n.id,error:t instanceof Error?t.message:String(t)})});break}case _i.PROXY_INIT:{let t=yi[_i.PROXY_INIT].safeParse(JSON.parse(this.decoder.decode(i)));if(!t.success)throw Error(`Invalid proxy init message`);let n;n=t.data.headers.upgrade===`websocket`?this.handleProxyWebSocket(e,t.data):this.handleProxyRequest(e,t.data),n.catch(t=>{e.error(t.message)});break}}})}async handleProxyWebSocket(e,t){let n=new URL(t.url);n.protocol===`http:`?n.protocol=`ws:`:n.protocol===`https:`&&(n.protocol=`wss:`);let r=new Ui.default(n.toString(),t.headers[`sec-websocket-protocol`]?t.headers[`sec-websocket-protocol`]:void 0,{headers:t.headers,perMessageDeflate:!1});r.addEventListener(`open`,()=>{e.writeTyped(vi.PROXY_INIT,this.encoder.encode(JSON.stringify({status_code:101,status_message:`Switching Protocols`,headers:{}})))}),r.addEventListener(`message`,t=>{e.disposed||e.writeTyped(vi.PROXY_WEBSOCKET_MESSAGE,hi(t.data,this.encoder))}),r.addEventListener(`close`,t=>{if(e.disposed)return;let n={code:t.code,reason:t.reason};e.writeTyped(vi.PROXY_WEBSOCKET_CLOSE,this.encoder.encode(JSON.stringify(n))),e.close()}),r.addEventListener(`error`,e=>{console.log(`err`,e)}),e.onClose(()=>{r.close()}),e.onError(e=>{r.close(1011,e)}),e.onData(t=>{let n=t.subarray(1);switch(t[0]){case _i.PROXY_WEBSOCKET_MESSAGE:{let e=gi(n,this.decoder);r.send(e);break}case _i.PROXY_WEBSOCKET_CLOSE:{let e=yi[_i.PROXY_WEBSOCKET_CLOSE].safeParse(JSON.parse(this.decoder.decode(n)));if(!e.success)throw Error(`Invalid proxy websocket close message`);try{r.close(e.data.code,e.data.reason)}catch(t){console.error(`Error closing websocket`,t,e.data)}break}default:e.error(`Unexpected message type: ${t[0]}`)}})}async handleProxyRequest(e,t){let n,r;if(t.method!==`GET`&&t.method!==`HEAD`&&t.method!==`OPTIONS`){let e=new TransformStream;n=e.writable.getWriter(),r=e.readable}e.onData(t=>{switch(t[0]){case _i.PROXY_BODY:if(n){let e=t.subarray(1);e.length===0?n.close():n.write(e)}break;default:e.error(`Unexpected message type: ${t[0]}`)}});let i={headers:t.headers,method:t.method,body:r},a;a=this.fetchProxyRequest?await this.fetchProxyRequest(t.url,i):await fetch(t.url,i);let o={};a.headers.forEach((e,t)=>{o[t]=e});let s={headers:o,status_code:a.status,status_message:a.statusText};e.writeTyped(vi.PROXY_INIT,this.encoder.encode(JSON.stringify(s)));let c=a.headers.get(`content-length`),l=c?parseInt(c):0,u=ia.getMaxPayloadSize()-1;if(l>=u){if(!a.body){e.close();return}let t=a.body.getReader();try{for(;;){let{done:n,value:r}=await t.read();if(n)break;if(r){let t=0;for(;t<r.length;){let n=Math.min(u,r.length-t),i=r.subarray(t,t+n);e.writeTyped(vi.PROXY_DATA,i),t+=n}}}}finally{t.releaseLock()}}else a.body&&await a.body.pipeTo(new WritableStream({write:t=>{e.writeTyped(vi.PROXY_DATA,t)}}));e.close()}async handleRequest(e,t,n){let r=bi[t.type].safeParse(t.payload);if(!r.success)throw Error(`Invalid request payload: ${r.error.message}`);switch(t.type){case`process_execute`:{if(t.payload.env_file){let e=await L.readFile(t.payload.env_file,`utf-8`),n=(0,xs.parse)(e);t.payload.env={...t.payload.env,...n}}let n=await this.processManager.execute(t.payload.command,t.payload.args,{cwd:t.payload.cwd,env:t.payload.env});this.sendResponse(e,{id:t.id,payload:{pid:n.pid}});break}case`process_wait`:this.handleProcessWait(e,t,n);break;case`process_kill`:this.mustGetProcess(t.payload.pid).kill(t.payload.signal),this.sendResponse(e,{id:t.id,payload:{}});break;case`process_list`:this.sendResponse(e,{id:t.id,payload:{processes:this.processManager.list(t.payload.include_dead??!1)}});break;case`process_read_plain_output`:{let n=this.mustGetProcess(t.payload.pid),r=this.processManager.readPlainOutput(t.payload.pid,t.payload.start_line,t.payload.end_line),i=Cs(r.lines,256e3);this.sendResponse(e,{id:t.id,payload:{lines:i.lines,total_lines:r.totalLines,duration_ms:Date.now()-n.startTimeMS,exit_code:n.exitCode,exit_signal:n.exitSignal}});break}case`process_send_input`:this.mustGetProcess(t.payload.pid).sendInput(t.payload.data),this.sendResponse(e,{id:t.id,payload:{}});break;case`set_env`:this.processManager.setEnv(t.payload.env),this.sendResponse(e,{id:t.id,payload:{}});break;case`deploy_static_files`:{if(!this.createDeploymentFromTar)throw Error(`This server does not support static file deployments!`);let n=await ys(t.payload.path),r=await this.createDeploymentFromTar(n);this.sendResponse(e,{id:t.id,payload:{deployment_id:r}});break}case`read_file`:{let n=await L.readFile(t.payload.path),r=await Jo(n);if(!(!r||r?.mime===`text/plain`)){this.sendResponse(e,{id:t.id,payload:{content:n.toString(`base64`),mime_type:r?.mime,total_lines:0,lines_read:0,start_line:0}});break}let i=n.toString(`utf-8`).split(`
59
+ `),n=n.replace(/\\r/g,`\r`)),t[e]=n}return t}function m(e){e||={};let t=b(e);e.path=t;let n=D.configDotenv(e);if(!n.parsed){let e=Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code=`MISSING_DATA`,e}let r=v(e).split(`,`),i=r.length,a;for(let e=0;e<i;e++)try{let t=r[e].trim(),i=y(n,t);a=D.decrypt(i.ciphertext,i.key);break}catch(t){if(e+1>=i)throw t}return D.parse(a)}function h(e){console.error(`[dotenv@${o}][WARN] ${e}`)}function g(e){console.log(`[dotenv@${o}][DEBUG] ${e}`)}function _(e){console.log(`[dotenv@${o}] ${e}`)}function v(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:``}function y(e,t){let n;try{n=new URL(t)}catch(e){if(e.code===`ERR_INVALID_URL`){let e=Error(`INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development`);throw e.code=`INVALID_DOTENV_KEY`,e}throw e}let r=n.password;if(!r){let e=Error(`INVALID_DOTENV_KEY: Missing key part`);throw e.code=`INVALID_DOTENV_KEY`,e}let i=n.searchParams.get(`environment`);if(!i){let e=Error(`INVALID_DOTENV_KEY: Missing environment part`);throw e.code=`INVALID_DOTENV_KEY`,e}let a=`DOTENV_VAULT_${i.toUpperCase()}`,o=e.parsed[a];if(!o){let e=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${a} in your .env.vault file.`);throw e.code=`NOT_FOUND_DOTENV_ENVIRONMENT`,e}return{ciphertext:o,key:r}}function b(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let r of e.path)n.existsSync(r)&&(t=r.endsWith(`.vault`)?r:`${r}.vault`);else t=e.path.endsWith(`.vault`)?e.path:`${e.path}.vault`;else t=r.resolve(process.cwd(),`.env.vault`);return n.existsSync(t)?t:null}function x(e){return e[0]===`~`?r.join(i.homedir(),e.slice(1)):e}function S(e){let t=l(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=l(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(t||!n)&&_(`Loading env from encrypted .env.vault`);let r=D._parseVault(e),i=process.env;return e&&e.processEnv!=null&&(i=e.processEnv),D.populate(i,r,e),{parsed:r}}function C(e){let t=r.resolve(process.cwd(),`.env`),i=`utf8`,a=process.env;e&&e.processEnv!=null&&(a=e.processEnv);let o=l(a.DOTENV_CONFIG_DEBUG||e&&e.debug),s=l(a.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?i=e.encoding:o&&g(`No encoding is specified. UTF-8 is used by default`);let u=[t];if(e&&e.path)if(!Array.isArray(e.path))u=[x(e.path)];else{u=[];for(let t of e.path)u.push(x(t))}let f,p={};for(let t of u)try{let r=D.parse(n.readFileSync(t,{encoding:i}));D.populate(p,r,e)}catch(e){o&&g(`Failed to load ${t} ${e.message}`),f=e}let m=D.populate(a,p,e);if(o=l(a.DOTENV_CONFIG_DEBUG||o),s=l(a.DOTENV_CONFIG_QUIET||s),o||!s){let e=Object.keys(m).length,t=[];for(let e of u)try{let n=r.relative(process.cwd(),e);t.push(n)}catch(t){o&&g(`Failed to load ${e} ${t.message}`),f=t}_(`injecting env (${e}) from ${t.join(`,`)} ${d(`-- tip: ${c()}`)}`)}return f?{parsed:p,error:f}:{parsed:p}}function w(e){if(v(e).length===0)return D.configDotenv(e);let t=b(e);return t?D._configVault(e):(h(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),D.configDotenv(e))}function T(e,t){let n=Buffer.from(t.slice(-64),`hex`),r=Buffer.from(e,`base64`),i=r.subarray(0,12),o=r.subarray(-16);r=r.subarray(12,-16);try{let e=a.createDecipheriv(`aes-256-gcm`,n,i);return e.setAuthTag(o),`${e.update(r)}${e.final()}`}catch(e){let t=e instanceof RangeError,n=e.message===`Invalid key length`,r=e.message===`Unsupported state or unable to authenticate data`;if(t||n){let e=Error(`INVALID_DOTENV_KEY: It must be 64 characters long (or more)`);throw e.code=`INVALID_DOTENV_KEY`,e}else if(r){let e=Error(`DECRYPTION_FAILED: Please check your DOTENV_KEY`);throw e.code=`DECRYPTION_FAILED`,e}else throw e}}function E(e,t,n={}){let r=!!(n&&n.debug),i=!!(n&&n.override),a={};if(typeof t!=`object`){let e=Error(`OBJECT_REQUIRED: Please check the processEnv argument being passed to populate`);throw e.code=`OBJECT_REQUIRED`,e}for(let n of Object.keys(t))Object.prototype.hasOwnProperty.call(e,n)?(i===!0&&(e[n]=t[n],a[n]=t[n]),r&&g(i===!0?`"${n}" is already defined and WAS overwritten`:`"${n}" is already defined and was NOT overwritten`)):(e[n]=t[n],a[n]=t[n]);return a}let D={configDotenv:C,_configVault:S,_parseVault:m,config:w,decrypt:T,parse:p,populate:E};t.exports.configDotenv=D.configDotenv,t.exports._configVault=D._configVault,t.exports._parseVault=D._parseVault,t.exports.config=D.config,t.exports.decrypt=D.decrypt,t.exports.parse=D.parse,t.exports.populate=D.populate,t.exports=D})})(),1);const Ss=(e,t)=>e.length<=t?e:e.slice(e.length-t),Cs=(e,t)=>{if(e.length===0)return{lines:[],truncated:!1};let n=0,r=e.length;for(let i=e.length-1;i>=0;i--){let a=e[i].length;if(n+a>t&&r!==e.length)break;n+=a,r=i}return r===0?{lines:e,truncated:!1}:{lines:e.slice(r),truncated:!0}};var ws=class{multiplexer;notificationStream;decoder=new TextDecoder;encoder=new TextEncoder;processManager;createDeploymentFromTar;proxyOnly;fetchProxyRequest;constructor(e){this.createDeploymentFromTar=e.createDeploymentFromTar,this.proxyOnly=e.proxyOnly,this.fetchProxyRequest=e.fetchProxyRequest,this.multiplexer=new sa({send:t=>{e.send(t)}}),this.multiplexer.onStream(e=>{this.handleStream(e)}),this.notificationStream=this.multiplexer.createStream(),this.processManager=new ns({env:e.env,nodePty:e.nodePty}),this.processManager.onSpawn(e=>{let t=()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})};t(),e.terminal.onTitleChange(()=>{t()}),e.onExit(()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})}),e.onOutput(t=>{let n=ia.getMaxPayloadSize()-1;for(let r=0;r<t.length;r+=n){let i=t.slice(r,r+n);this.sendNotification({type:`process_output`,payload:{pid:e.pid,output:i}})}})})}handleMessage(e){this.multiplexer.handleMessage(e)}handleStream(e){let t=new AbortController;e.onClose(()=>{t.abort()}),e.onData(n=>{let r=n[0],i=n.subarray(1);switch(r){case _i.REQUEST:{let n=JSON.parse(this.decoder.decode(i));if(this.proxyOnly){this.sendResponse(e,{id:n.id,error:`This server is in proxy only mode.`});return}this.handleRequest(e,n,t.signal).catch(t=>{this.sendResponse(e,{id:n.id,error:t instanceof Error?t.message:String(t)})});break}case _i.PROXY_INIT:{let t=yi[_i.PROXY_INIT].safeParse(JSON.parse(this.decoder.decode(i)));if(!t.success)throw Error(`Invalid proxy init message`);let n;n=t.data.headers.upgrade===`websocket`?this.handleProxyWebSocket(e,t.data):this.handleProxyRequest(e,t.data),n.catch(t=>{e.error(t.message)});break}}})}async handleProxyWebSocket(e,t){let n=new URL(t.url);n.protocol===`http:`?n.protocol=`ws:`:n.protocol===`https:`&&(n.protocol=`wss:`);let r=new Ui.default(n.toString(),t.headers[`sec-websocket-protocol`]?t.headers[`sec-websocket-protocol`]:void 0,{headers:t.headers,perMessageDeflate:!1});r.addEventListener(`open`,()=>{e.writeTyped(vi.PROXY_INIT,this.encoder.encode(JSON.stringify({status_code:101,status_message:`Switching Protocols`,headers:{}})))}),r.addEventListener(`message`,t=>{e.disposed||e.writeTyped(vi.PROXY_WEBSOCKET_MESSAGE,hi(t.data,this.encoder))}),r.addEventListener(`close`,t=>{if(e.disposed)return;let n={code:t.code,reason:t.reason};e.writeTyped(vi.PROXY_WEBSOCKET_CLOSE,this.encoder.encode(JSON.stringify(n))),e.close()}),r.addEventListener(`error`,e=>{console.log(`err`,e)}),e.onClose(()=>{r.close()}),e.onError(e=>{r.close(1011,e)}),e.onData(t=>{let n=t.subarray(1);switch(t[0]){case _i.PROXY_WEBSOCKET_MESSAGE:{let e=gi(n,this.decoder);r.send(e);break}case _i.PROXY_WEBSOCKET_CLOSE:{let e=yi[_i.PROXY_WEBSOCKET_CLOSE].safeParse(JSON.parse(this.decoder.decode(n)));if(!e.success)throw Error(`Invalid proxy websocket close message`);try{r.close(e.data.code,e.data.reason)}catch(t){console.error(`Error closing websocket`,t,e.data)}break}default:e.error(`Unexpected message type: ${t[0]}`)}})}async handleProxyRequest(e,t){let n,r;if(t.method!==`GET`&&t.method!==`HEAD`&&t.method!==`OPTIONS`){let e=new TransformStream;n=e.writable.getWriter(),r=e.readable}e.onData(t=>{switch(t[0]){case _i.PROXY_BODY:if(n){let e=t.subarray(1);e.length===0?n.close():n.write(e)}break;default:e.error(`Unexpected message type: ${t[0]}`)}});let i={headers:t.headers,method:t.method,body:r,redirect:`manual`},a;a=this.fetchProxyRequest?await this.fetchProxyRequest(t.url,i):await fetch(t.url,i);let o={};a.headers.forEach((e,t)=>{o[t]=e});let s={headers:o,status_code:a.status,status_message:a.statusText};e.writeTyped(vi.PROXY_INIT,this.encoder.encode(JSON.stringify(s)));let c=a.headers.get(`content-length`),l=c?parseInt(c):0,u=ia.getMaxPayloadSize()-1;if(l>=u){if(!a.body){e.close();return}let t=a.body.getReader();try{for(;;){let{done:n,value:r}=await t.read();if(n)break;if(r){let t=0;for(;t<r.length;){let n=Math.min(u,r.length-t),i=r.subarray(t,t+n);e.writeTyped(vi.PROXY_DATA,i),t+=n}}}}finally{t.releaseLock()}}else a.body&&await a.body.pipeTo(new WritableStream({write:t=>{e.writeTyped(vi.PROXY_DATA,t)}}));e.close()}async handleRequest(e,t,n){let r=bi[t.type].safeParse(t.payload);if(!r.success)throw Error(`Invalid request payload: ${r.error.message}`);switch(t.type){case`process_execute`:{if(t.payload.env_file){let e=await L.readFile(t.payload.env_file,`utf-8`),n=(0,xs.parse)(e);t.payload.env={...t.payload.env,...n}}let n=await this.processManager.execute(t.payload.command,t.payload.args,{cwd:t.payload.cwd,env:t.payload.env});this.sendResponse(e,{id:t.id,payload:{pid:n.pid}});break}case`process_wait`:this.handleProcessWait(e,t,n);break;case`process_kill`:this.mustGetProcess(t.payload.pid).kill(t.payload.signal),this.sendResponse(e,{id:t.id,payload:{}});break;case`process_list`:this.sendResponse(e,{id:t.id,payload:{processes:this.processManager.list(t.payload.include_dead??!1)}});break;case`process_read_plain_output`:{let n=this.mustGetProcess(t.payload.pid),r=this.processManager.readPlainOutput(t.payload.pid,t.payload.start_line,t.payload.end_line),i=Cs(r.lines,256e3);this.sendResponse(e,{id:t.id,payload:{lines:i.lines,total_lines:r.totalLines,duration_ms:Date.now()-n.startTimeMS,exit_code:n.exitCode,exit_signal:n.exitSignal}});break}case`process_send_input`:this.mustGetProcess(t.payload.pid).sendInput(t.payload.data),this.sendResponse(e,{id:t.id,payload:{}});break;case`set_env`:this.processManager.setEnv(t.payload.env),this.sendResponse(e,{id:t.id,payload:{}});break;case`deploy_static_files`:{if(!this.createDeploymentFromTar)throw Error(`This server does not support static file deployments!`);let n=await ys(t.payload.path),r=await this.createDeploymentFromTar(n);this.sendResponse(e,{id:t.id,payload:{deployment_id:r}});break}case`read_file`:{let n=await L.readFile(t.payload.path),r=await Jo(n);if(!(!r||r?.mime===`text/plain`)){this.sendResponse(e,{id:t.id,payload:{content:n.toString(`base64`),mime_type:r?.mime,total_lines:0,lines_read:0,start_line:0}});break}let i=n.toString(`utf-8`).split(`
60
60
  `),a=Math.max(0,(t.payload.line_start??1)-1),o=Math.min(i.length,t.payload.line_end??i.length),s=i.slice(a,o);this.sendResponse(e,{id:t.id,payload:{content:s.join(`
61
61
  `),mime_type:`text/plain`,total_lines:i.length,lines_read:s.length,start_line:a}});break}case`write_file`:t.payload.base64?await L.writeFile(t.payload.path,Buffer.from(t.payload.content,`base64`)):await L.writeFile(t.payload.path,t.payload.content),typeof t.payload.mode==`number`&&await L.chmod(t.payload.path,t.payload.mode),this.sendResponse(e,{id:t.id,payload:{}});break;case`read_directory`:{let n=await L.readdir(t.payload.path,{withFileTypes:!0});this.sendResponse(e,{id:t.id,payload:{entries:n.map(e=>({name:e.name,type:e.isDirectory()?`directory`:e.isSymbolicLink()?`symlink`:`file`}))}});break}default:throw Error(`Unknown request type: ${t.type}`)}}sendResponse(e,t){e.writeTyped(vi.RESPONSE,this.encoder.encode(JSON.stringify(t)))}sendNotification(e){this.notificationStream.write(new Uint8Array([vi.NOTIFICATION,...this.encoder.encode(JSON.stringify(e))]))}handleProcessWait(e,t,n){let r=t.payload,i=this.mustGetProcess(r.pid),a,o,s=!1,c,l;typeof r.timeout_ms==`number`&&(l=setTimeout(()=>{u()},r.timeout_ms));let u=()=>{if(s||(s=!0,a&&a.dispose(),o&&o.dispose(),l&&clearTimeout(l),c&&clearTimeout(c),n?.aborted))return;let i=this.processManager.status(r.pid),u=this.processManager.readPlainOutput(i.pid),d=Ss(this.processManager.readANSIOutput(i.pid),64e3),f=Cs(u.lines,256e3);this.sendResponse(e,{id:t.id,payload:{...i,ansi_output:d,plain_output:{lines:f.lines,total_lines:u.totalLines}}})};if(typeof i.exitCode==`number`||typeof i.exitSignal==`number`){u();return}a=i.onOutput(()=>{c&&clearTimeout(c),typeof r.output_idle_timeout_ms==`number`&&(c=setTimeout(()=>{u()},r.output_idle_timeout_ms))}),o=i.onExit(()=>{setTimeout(()=>{u()},10)}),n.addEventListener(`abort`,()=>{u()})}mustGetProcess(e){let t=this.processManager.getProcess(e);if(!t)throw Error(`Process ${e} not found`);return t}};function Ts(e){let t=new TextEncoder,n=new TextDecoder,r=new ws({...e,send:e=>{i.handleMessage(e)}}),i=new sa({send:e=>{r.handleMessage(e)},isClient:!0}),a=i.createStream(),o=new ki({send:e=>{a.writeTyped(0,t.encode(e),!0)}});return a.onData(e=>{let t=e.subarray(1);o.handleMessage(n.decode(t))}),i.onStream(e=>{e.onData(e=>{let t=e.subarray(1);o.handleMessage(n.decode(t))})}),{client:o,server:r}}var Es=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}else return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h){d[r]=void 0;continue}if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}};new class extends Es{};function Ds(e,t){let n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function Os(e,t){let n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function ks(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function As(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function js(e,t){return ks(e,t,``)}function Ms(e,t){return As(e,t,``)}function Ns(e,t){return t.slice(0,Ps(e,t))}function Ps(e,t){let n=0;e.length>t.length&&(n=e.length-t.length);let r=t.length;e.length<t.length&&(r=e.length);let i=Array(r),a=0;i[0]=0;for(let e=1;e<r;e++){for(t[e]==t[a]?i[e]=i[a]:i[e]=a;a>0&&t[e]!=t[a];)a=i[a];t[e]==t[a]&&a++}a=0;for(let r=n;r<e.length;r++){for(;a>0&&e[r]!=t[a];)a=i[a];e[r]==t[a]&&a++}return a}function Fs(e){let t;for(t=e.length-1;t>=0&&e[t].match(/\s/);t--);return e.substring(t+1)}function Is(e){let t=e.match(/^\s*/);return t?t[0]:``}const Ls=`a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,Rs=RegExp(`[${Ls}]+|\\s+|[^${Ls}]`,`ug`);new class extends Es{equals(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()}tokenize(e,t={}){let n;if(t.intlSegmenter){let r=t.intlSegmenter;if(r.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=Array.from(r.segment(e),e=>e.segment)}else n=e.match(Rs)||[];let r=[],i=null;return n.forEach(e=>{/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):i!=null&&/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r}join(e){return e.map((e,t)=>t==0?e:e.replace(/^\s+/,``)).join(``)}postProcess(e,t){if(!e||t.oneChangePerToken)return e;let n=null,r=null,i=null;return e.forEach(e=>{e.added?r=e:e.removed?i=e:((r||i)&&zs(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&zs(n,i,r,null),e}};function zs(e,t,n,r){if(t&&n){let i=Is(t.value),a=Fs(t.value),o=Is(n.value),s=Fs(n.value);if(e){let r=Ds(i,o);e.value=As(e.value,o,r),t.value=js(t.value,r),n.value=js(n.value,r)}if(r){let e=Os(a,s);r.value=ks(r.value,s,e),t.value=Ms(t.value,e),n.value=Ms(n.value,e)}}else if(n){if(e){let e=Is(n.value);n.value=n.value.substring(e.length)}if(r){let e=Is(r.value);r.value=r.value.substring(e.length)}}else if(e&&r){let n=Is(r.value),i=Is(t.value),a=Fs(t.value),o=Ds(n,i);t.value=js(t.value,o);let s=Os(js(n,o),a);t.value=Ms(t.value,s),r.value=ks(r.value,n,s),e.value=As(e.value,n,n.slice(0,n.length-s.length))}else if(r){let e=Is(r.value),n=Fs(t.value),i=Ns(n,e);t.value=Ms(t.value,i)}else if(e){let n=Fs(e.value),r=Is(t.value),i=Ns(n,r);t.value=js(t.value,i)}}new class extends Es{tokenize(e){let t=RegExp(`(\\r?\\n)|[${Ls}]+|[^\\S\\n\\r]+|[^${Ls}]`,`ug`);return e.match(t)||[]}};const Bs=new class extends Es{constructor(){super(...arguments),this.tokenize=Hs}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
62
62
  `))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(`
@@ -539,4 +539,4 @@ Instead:
539
539
 
540
540
  The agent process can restart at any time, so all important state must be externalized.
541
541
  </technical_knowledge>
542
- `;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{}});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=W(0);H(()=>{if(v.length===T.current)return;let t=T.current;for(let n of v.slice(t))e.onAgentLog?.(n);T.current=v.length},[v,e.onAgentLog]);let[E,D]=G(`default`);H(()=>{_&&C(_.baseUrl),n===`run`?_?h.current=_:(h.current=void 0,g.stopChat(E)):n===`edit`&&(x?h.current=x:(h.current=void 0,g.stopChat(E)))},[_,x,n,E,g]);let O=Ve({chatId:E,agent:n===`run`?_:x,chatsDirectory:g.chatsDirectory,filterMessages:n===`run`?e=>!ze(e.metadata):void 0}),[k,A]=G([]);H(()=>{g.listChats().then(e=>{A(e.map(e=>e.key))})},[g]),H(()=>{E&&!k.includes(E)&&A(e=>[...e,E])},[E,k]);let j=U(()=>$r(t),[t]),M=ui({id:j,disabled:!b?.request,onRequest:async e=>{if(!_)throw Error(`No agent`);let t=new URL(e.url),n=new URL(_.baseUrl);return n.pathname=t.pathname,n.search=t.search,await fetch(n.toString(),e)}});H(()=>{M.status===`connected`&&e.onDevhookConnected?.(`https://${M.id}.dev.blink.host`)},[M.status,M.id]);let{schema:N,options:P,error:ee,setOption:te}=li({agent:h.current,capabilities:b,messages:O.messages}),I=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}`),ee&&e.push(`Options error: ${ee.message}`),e},[y,S,O.error,ee,n]);H(()=>{for(let t of I)e.onError?.(t)},[I]),H(()=>{O.upsertMessage({id:crypto.randomUUID(),created_at:new Date().toISOString(),role:`assistant`,parts:[{type:`text`,text:n===`run`?`<run_mode />`:`<edit_mode />`}],metadata:{__blink_internal:!0,type:`mode`,mode:n}}).catch(e=>{console.error(`Error inserting mode delimiter:`,e)})},[n,O.upsertMessage]);let[L,ne]=G(),R=U(()=>{let e=[...O.messages].reverse().find(e=>!(e.role!==`assistant`||e.metadata&&e.metadata.ephemeral));if(!e||L===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,L]),z=V(async e=>{if(!R)return;ne(R.id);let t=await g.lockChat(E);try{let n=await t.get();if(n.messages.length>0){let r=n.messages[n.messages.length-1];if(r&&r.role===`assistant`&&Array.isArray(r.parts)){let i=r.parts.map(t=>F(t)&&t.output&&l(t.output)&&t.output.outcome===`pending`?{...t,output:{...t.output,outcome:e?`approved`:`rejected`}}:t),a=[...n.messages];a[a.length-1]={...r,parts:i},await t.update({messages:a})}}}finally{await t.release()}await g.startChat(E)},[R,g,E]),B=V(()=>{let e=crypto.randomUUID();D(e),A(t=>[...t,e])},[]),K=U(()=>{if(R)return{message:R,approve:()=>z(!0),reject:()=>z(!1)}},[R,z]),re=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]),q=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:k,switchChat:D,newChat:B,build:{status:c,error:s,entrypoint:d},devhook:{connected:M.status===`connected`,url:M.status===`connected`?`https://${M.id}.dev.blink.host`:void 0},capabilities:b,options:{schema:N,selected:P,error:ee,setOption:te},approval:K,tokenUsage:re,server:g,showWaitingPlaceholder:q}}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};
542
+ `;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{}});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=W(0);H(()=>{if(v.length===T.current)return;let t=T.current;for(let n of v.slice(t))e.onAgentLog?.(n);T.current=v.length},[v,e.onAgentLog]);let[E,D]=G(`default`);H(()=>{_&&C(_.baseUrl),n===`run`?_?h.current=_:(h.current=void 0,g.stopChat(E)):n===`edit`&&(x?h.current=x:(h.current=void 0,g.stopChat(E)))},[_,x,n,E,g]);let O=Ve({chatId:E,agent:n===`run`?_:x,chatsDirectory:g.chatsDirectory,filterMessages:n===`run`?e=>!ze(e.metadata):void 0}),[k,A]=G([]);H(()=>{g.listChats().then(e=>{A(e.map(e=>e.key))})},[g]),H(()=>{E&&!k.includes(E)&&A(e=>[...e,E])},[E,k]);let j=U(()=>$r(t),[t]),M=ui({id:j,disabled:!b?.request,onRequest:async e=>{if(!_)throw Error(`No agent`);let t=new URL(e.url),n=new URL(_.baseUrl);return n.pathname=t.pathname,n.search=t.search,await fetch(n.toString(),{...e,redirect:`manual`})}});H(()=>{M.status===`connected`&&e.onDevhookConnected?.(`https://${M.id}.dev.blink.host`)},[M.status,M.id]);let{schema:N,options:P,error:ee,setOption:te}=li({agent:n===`run`?_:x,capabilities:b,messages:O.messages}),I=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}`),ee&&e.push(`Options error: ${ee.message}`),e},[y,S,O.error,ee,n]);H(()=>{for(let t of I)e.onError?.(t)},[I]),H(()=>{O.upsertMessage({id:crypto.randomUUID(),created_at:new Date().toISOString(),role:`assistant`,parts:[{type:`text`,text:n===`run`?`<run_mode />`:`<edit_mode />`}],metadata:{__blink_internal:!0,type:`mode`,mode:n}}).catch(e=>{console.error(`Error inserting mode delimiter:`,e)})},[n,O.upsertMessage]);let[L,ne]=G(),R=U(()=>{let e=[...O.messages].reverse().find(e=>!(e.role!==`assistant`||e.metadata&&e.metadata.ephemeral));if(!e||L===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,L]),z=V(async e=>{if(!R)return;ne(R.id);let t=await g.lockChat(E);try{let n=await t.get();if(n.messages.length>0){let r=n.messages[n.messages.length-1];if(r&&r.role===`assistant`&&Array.isArray(r.parts)){let i=r.parts.map(t=>F(t)&&t.output&&l(t.output)&&t.output.outcome===`pending`?{...t,output:{...t.output,outcome:e?`approved`:`rejected`}}:t),a=[...n.messages];a[a.length-1]={...r,parts:i},await t.update({messages:a})}}}finally{await t.release()}await g.startChat(E)},[R,g,E]),B=V(()=>{let e=crypto.randomUUID();D(e),A(t=>[...t,e])},[]),K=U(()=>{if(R)return{message:R,approve:()=>z(!0),reject:()=>z(!1)}},[R,z]),re=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]),q=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:k,switchChat:D,newChat:B,build:{status:c,error:s,entrypoint:d},devhook:{connected:M.status===`connected`,url:M.status===`connected`?`https://${M.id}.dev.blink.host`:void 0},capabilities:b,options:{schema:N,selected:P,error:ee,setOption:te},approval:K,tokenUsage:re,server:g,showWaitingPlaceholder:q}}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.97",
3
+ "version": "0.1.99",
4
4
  "description": "Blink is a JavaScript runtime for building and deploying AI agents.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1 +0,0 @@
1
- import"./wrapper-B0SBsJWP.js";import"./node-pty-BfteYoG-.js";import"./server-DyzkvVFu-D6nxD1-6.js";import{WorkspaceConnect as e,connect as t}from"./connect-Cmwhnvok.js";export{e as WorkspaceConnect,t as default};