blink 1.1.26 → 1.1.28
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.
|
@@ -49,7 +49,7 @@ ${Pf}`),t.includes(`
|
|
|
49
49
|
`)&&(n=3+se(t.slice(t.lastIndexOf(`
|
|
50
50
|
`))).length);let e=se(t).length;n+e<process.stdout.columns?(n+=e,process.stdout.write(t)):(process.stdout.write(`
|
|
51
51
|
${Pf}${t.trimStart()}`),n=3+se(t.trimStart()).length)}process.stdout.write(`
|
|
52
|
-
`)},info:e=>Ff.message(e,{symbol:Cf.default.blue(kf)}),success:e=>Ff.message(e,{symbol:Cf.default.green(Af)}),step:e=>Ff.message(e,{symbol:Cf.default.green(Df)}),warn:e=>Ff.message(e,{symbol:Cf.default.yellow(jf)}),warning:e=>Ff.warn(e),error:e=>Ff.message(e,{symbol:Cf.default.red(Mf)})};let If;function Lf(){try{return P.statSync(`/.dockerenv`),!0}catch{return!1}}function Rf(){try{return P.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function zf(){return If===void 0&&(If=Lf()||Rf()),If}let Bf;const Vf=()=>{try{return P.statSync(`/run/.containerenv`),!0}catch{return!1}};function Hf(){return Bf===void 0&&(Bf=Vf()||zf()),Bf}const Uf=()=>{if(J.platform!==`linux`)return!1;if(Me.release().toLowerCase().includes(`microsoft`))return!Hf();try{return P.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!Hf():!1}catch{return!1}};var Wf=J.env.__IS_WSL_TEST__?Uf:Uf();const Gf=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await Re.access(n,ze.F_OK),r=!0}catch{}if(!r)return e;let i=await Re.readFile(n,{encoding:`utf8`}),a=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(i);return a?(t=a.groups.mountPoint.trim(),t=t.endsWith(`/`)?t:`${t}/`,t):e}})(),Kf=async()=>`${await Gf()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,qf=async()=>Wf?Kf():`${J.env.SYSTEMROOT||J.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function Jf(e,t,n){let r=n=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0});return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){let e=n();return r(e),e},set(e){r(e)}}),e}const Yf=oe(Le);async function Xf(){if(J.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await Yf(`defaults`,[`read`,`com.apple.LaunchServices/com.apple.launchservices.secure`,`LSHandlers`]);return/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??`com.apple.Safari`}const Zf=oe(Le);async function Qf(e,{humanReadableOutput:t=!0,signal:n}={}){if(J.platform!==`darwin`)throw Error(`macOS only`);let r=t?[]:[`-ss`],i={};n&&(i.signal=n);let{stdout:a}=await Zf(`osascript`,[`-e`,e,r],i);return a.trim()}async function $f(e){return Qf(`tell application "Finder" to set app_path to application file id "${e}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}const ep=oe(Le),tp={AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:`Edge`,id:`com.microsoft.edge.old`},MSEdgeDHTML:{name:`Edge`,id:`com.microsoft.edge`},MSEdgeHTM:{name:`Edge`,id:`com.microsoft.edge`},"IE.HTTP":{name:`Internet Explorer`,id:`com.microsoft.ie`},FirefoxURL:{name:`Firefox`,id:`org.mozilla.firefox`},ChromeHTML:{name:`Chrome`,id:`com.google.chrome`},BraveHTML:{name:`Brave`,id:`com.brave.Browser`},BraveBHTML:{name:`Brave Beta`,id:`com.brave.Browser.beta`},BraveSSHTM:{name:`Brave Nightly`,id:`com.brave.Browser.nightly`}};var np=class extends Error{};async function rp(e=ep){let{stdout:t}=await e(`reg`,[`QUERY`,` HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice`,`/v`,`ProgId`]),n=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(t);if(!n)throw new np(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=tp[r];if(!i)throw new np(`Unknown browser ID: ${r}`);return i}const ip=oe(Le),ap=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function op(){if(J.platform===`darwin`){let e=await Xf();return{name:await $f(e),id:e}}if(J.platform===`linux`){let{stdout:e}=await ip(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:ap(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(J.platform===`win32`)return rp();throw Error(`Only macOS, Linux, and Windows are supported`)}const sp=oe(Ie.execFile),cp=De.dirname(ae(import.meta.url)),lp=De.join(cp,`xdg-open`),{platform:up,arch:dp}=J;async function fp(){let e=await qf(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=ne.from(t,`utf16le`).toString(`base64`),{stdout:r}=await sp(e,[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,n],{encoding:`utf8`}),i=r.trim(),a={ChromeHTML:`com.google.chrome`,BraveHTML:`com.brave.Browser`,MSEdgeHTM:`com.microsoft.edge`,FirefoxURL:`org.mozilla.firefox`};return a[i]?{id:a[i]}:{}}const pp=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},mp=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return pp(e.app,t=>mp({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return pp(t,t=>mp({...e,app:{name:t,arguments:n}}));if(t===`browser`||t===`browserPrivate`){let r={"com.google.chrome":`chrome`,"google-chrome.desktop":`chrome`,"com.brave.Browser":`brave`,"org.mozilla.firefox":`firefox`,"firefox.desktop":`firefox`,"com.microsoft.msedge":`edge`,"com.microsoft.edge":`edge`,"com.microsoft.edgemac":`edge`,"microsoft-edge.desktop":`edge`},i={chrome:`--incognito`,brave:`--incognito`,firefox:`--private-window`,edge:`--inPrivate`},a=Wf?await fp():await op();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),mp({...e,app:{name:vp[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,i=[],a={};if(up===`darwin`)r=`open`,e.wait&&i.push(`--wait-apps`),e.background&&i.push(`--background`),e.newInstance&&i.push(`--new`),t&&i.push(`-a`,t);else if(up===`win32`||Wf&&!Hf()&&!t){r=await qf(),i.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),Wf||(a.windowsVerbatimArguments=!0);let o=[`Start`];e.wait&&o.push(`-Wait`),t?(o.push(`"\`"${t}\`""`),e.target&&n.push(e.target)):e.target&&o.push(`"${e.target}"`),n.length>0&&(n=n.map(e=>`"\`"${e}\`""`),o.push(`-ArgumentList`,n.join(`,`))),e.target=ne.from(o.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!cp||cp===`/`,t=!1;try{await Re.access(lp,ze.X_OK),t=!0}catch{}r=J.versions.electron??(up===`android`||e||!t)?`xdg-open`:lp}n.length>0&&i.push(...n),e.wait||(a.stdio=`ignore`,a.detached=!0)}up===`darwin`&&n.length>0&&i.push(`--args`,...n),e.target&&i.push(e.target);let o=Ie.spawn(r,i,a);return e.wait?new Promise((t,n)=>{o.once(`error`,n),o.once(`close`,r=>{if(!e.allowNonzeroExitCode&&r>0){n(Error(`Exited with code ${r}`));return}t(o)})}):(o.unref(),o)},hp=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return mp({...t,target:e})};function gp(e){if(typeof e==`string`||Array.isArray(e))return e;let{[dp]:t}=e;if(!t)throw Error(`${dp} is not supported`);return t}function _p({[up]:e},{wsl:t}){if(t&&Wf)return gp(t);if(!e)throw Error(`${up} is not supported`);return gp(e)}const vp={};Jf(vp,`chrome`,()=>_p({darwin:`google chrome`,win32:`chrome`,linux:[`google-chrome`,`google-chrome-stable`,`chromium`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`,x64:[`/mnt/c/Program Files/Google/Chrome/Application/chrome.exe`,`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`]}})),Jf(vp,`brave`,()=>_p({darwin:`brave browser`,win32:`brave`,linux:[`brave-browser`,`brave`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`,x64:[`/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe`,`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`]}})),Jf(vp,`firefox`,()=>_p({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),Jf(vp,`edge`,()=>_p({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),Jf(vp,`browser`,()=>`browser`),Jf(vp,`browserPrivate`,()=>`browserPrivate`);var yp=hp;async function bp(e,t=void 0){try{(await yp(e)).once(`error`,n=>{console.log(cf.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))})}catch{console.log(cf.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))}}function xp(e){let t=e||wp();if(F(t)){let e=I(t,`utf8`);return JSON.parse(e).token}}function Sp(e,t){let n=t||wp();F(Oe(n))||re(Oe(n),{recursive:!0}),L(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function Cp(e){let t=e||wp();F(t)&&ie(t)}function wp(){let e=Dd(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return ke(e[0],`auth.json`)}function Tp(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=W(),[s,c]=W(()=>xp(i)),[l,u]=W(),d=U(n),f=U(r);H(()=>{d.current=n,f.current=r},[n,r]);let p=V(async()=>{u(void 0);try{let e=xp(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new ld({baseURL:`https://blink.so`});t.authToken=e;let n={email:(await t.users.me()).email};o(n),d.current?.(n)}catch(e){o(void 0),u(e instanceof Error?e.message:String(e)),d.current?.(void 0)}},[i]),m=V(async()=>{u(void 0);try{let e=new ld,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();Sp(t,i),c(t);let r={email:n.email};return o(r),d.current?.(r),r}catch(e){let t=e instanceof Error?e.message:String(e);throw u(t),e}},[i]),h=V(()=>{Cp(i),c(void 0),o(void 0),u(void 0),d.current?.(void 0)},[i]);return H(()=>{t&&p()},[t,p]),{user:a,token:s,error:l,login:m,logout:h}}let Ep=Promise.resolve();var Dp=class{constructor(e){this.printLog=e}setPrintLog(e){this.printLog=e}error(e,...t){Ep=Ep.then(()=>this.printLog(`error`,e,...t).catch(e=>{console.error(`Error printing log:`,e)}))}log(e,...t){Ep=Ep.then(()=>this.printLog(`log`,e,...t).catch(e=>{console.error(`Error printing log:`,e)}))}flush(){return Ep}};const Op=Te(void 0);function kp(e){let{directory:t,logger:n,onBuildStart:r,onBuildSuccess:i,onBuildError:a}=typeof e==`string`?{directory:e,logger:new Dp(async()=>{})}:e,o=Ee(()=>k(t),[t]),[s,c]=W(void 0),[l,u]=W(void 0),[d,f]=W(`building`),p=U(r),m=U(i),h=U(a);return H(()=>{p.current=r,m.current=i,h.current=a},[r,i,a]),H(()=>{let e=new AbortController;return o.build({cwd:t,entry:o.entry,outdir:o.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{f(`building`),c(void 0),u(void 0),p.current?.()},onResult:e=>{`error`in e?(c(e.error),f(`error`),h.current?.(e.error)):(u(e),f(`success`),m.current?.(e))}}).catch(e=>{n.error(`system`,`error`,e),f(`error`),c(e),h.current?.(e)}),()=>{e.abort()}},[t]),Ee(()=>({error:s,status:d,result:l,entry:o.entry,outdir:o.outdir}),[s,d,l,o.entry,o.outdir])}function Ap(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function jp(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const Mp=/^\.+(\\|\/)|^\.+$/,Np=/[. ]+$/,Pp=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,Fp=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,Ip=e=>e===``,Lp=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,Rp=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let zp;function Bp(){return zp??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),zp}function Vp(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(Ap().test(n)||[...n].some(e=>Fp.test(e)&&!Ip(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(Rp,` `),n.length>0&&(e=e.replaceAll(Lp,`$1`)),e=e.replace(Np,``),e=e.replace(Mp,n),e=e.replace(Ap(),n),e=e.replaceAll(Pp,e=>Ip(e)?e:n),e.length===0&&(e=n),e=jp().test(e)?e+n:e;let r=typeof t.maxLength==`number`?t.maxLength:100;if(e.length>r){let t=e.lastIndexOf(`.`);if(t===-1)e=Hp(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=Hp(n,a)+i}}return e}function Hp(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of Bp().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function Up(e){return`${e}.lock`}function Wp(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function Gp(e,t={}){let n=Up(e),r=process.pid.toString();try{return N.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(N.readFileSync(n,`utf8`),10)}catch{return N.unlinkSync(n),Gp(e,{...t,stale:0})}if(!Wp(i))try{return N.unlinkSync(n),Gp(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return Gp(e,{...t,stale:0});throw n}return!1}}async function Kp(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=q.resolve(e),i=0;for(;i<=n.retries;){if(Gp(r,n))return()=>qp(r);i<n.retries&&await new Promise(e=>setTimeout(e,n.retryInterval)),i++}let a=Error(`Lock file is already being held`);throw a.code=`ELOCKED`,a.file=r,a}function qp(e){let t=q.resolve(e),n=Up(t);try{if(parseInt(N.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}N.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function Jp(e){let t=q.resolve(e),n=Up(t);try{if(!N.existsSync(n))return{locked:!1};let e=N.readFileSync(n,`utf8`),t=parseInt(e,10);return Wp(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const Yp=e=>{N.mkdirSync(e,{recursive:!0})},Xp=e=>{try{N.fdatasyncSync(e)}catch{}try{N.closeSync(e)}catch{}},Zp=e=>{try{let t=N.openSync(e,`r`);try{N.fsyncSync(t)}finally{N.closeSync(t)}}catch{}},Qp=(e,t)=>{let n=q.dirname(e);Yp(n);let r=q.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=N.openSync(r,`w`),N.writeFileSync(i,t,`utf-8`),Xp(i),i=void 0,N.renameSync(r,e),Zp(e),Zp(n)}catch(e){if(i!==void 0)try{N.closeSync(i)}catch{}try{N.rmSync(r,{force:!0})}catch{}throw e}},$p=(e,t)=>{let n=new Map,r,i=e=>{if(N.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(N.readFileSync(e,`utf-8`))},a=(e,t)=>{Qp(e,JSON.stringify(t,null,2))},o=async()=>{if(r)throw Error(`Index is already locked`);let t=q.join(e,`index.json`);Yp(e),N.existsSync(t)||N.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await Kp(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},s=async()=>{let t=q.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},c=async t=>{let n=q.join(e,`index.json`);a(n,t)},l=async t=>{let n=(await s()).ids[t];if(n)return q.join(e,n)},u=async t=>{let n=(await s()).ids[t];if(!n)return;let r=q.join(e,n);if(N.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(N.readFileSync(r,`utf-8`))},d=async n=>{let r=n[t],i=String(r),l=Vp(i,{replacement:`_`})+`.json`,u=await o();try{let t=await s();t.ids[i]=l,t.current=i;let r=q.join(e,l);a(r,n),await c(t)}finally{await u()}};return{async get(e){return await u(e)},async list(){if(!N.statSync(e,{throwIfNoEntry:!1}))return[];let t=await s(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=q.join(e,i),a=N.statSync(t,{throwIfNoEntry:!1});if(!a)continue;let o=Jp(t);n.push({key:r,locked:o.locked,pid:o.pid,mtime:a.mtimeMs})}return n.sort((e,t)=>t.mtime-e.mtime),n},async lock(r,i){if(n.has(r))throw Error(`Key "${r}" is already locked in this process`);let a=await l(r);if(!a){let t=Vp(r,{replacement:`_`})+`.json`,n=await o();try{let n=await s();n.ids[r]=t;let i=q.join(e,t);Yp(e),N.writeFileSync(i,JSON.stringify({}),`utf-8`),await c(n),a=i}finally{await n()}}if(i?.force){let e=Jp(a);if(e.locked&&e.pid&&e.pid!==process.pid)try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,100))}catch(t){t.code!==`ESRCH`&&console.warn(`Failed to kill process ${e.pid}:`,t.message)}}let f=await Kp(a,{stale:!0,retries:i?.force?10:5,retryInterval:(i?.force,100)});return n.set(r,()=>Promise.resolve(f())),{async get(){let e=await u(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await d(e)},async update(e){let n=await u(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await d({...n,...e})},async delete(){let t=await o();try{let t=await s(),n=t.ids[r];if(n){delete t.ids[r],t.current===r&&(t.current=void 0),await c(t);let i=q.join(e,n);try{N.rmSync(i,{force:!0}),Zp(e)}catch{}}}finally{await t()}},async release(){try{f()}finally{n.delete(r)}}}},dispose(){n.clear()}}},em=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,a,o,s=new Map,c=new Map,l=q.join(e,`index.json`),u=()=>{try{if(!N.statSync(l,{throwIfNoEntry:!1}))return{ids:{}};let e=N.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=q.join(e,n);try{let e=N.statSync(i,{throwIfNoEntry:!1}),a=c.get(n);if(!e){a&&(c.delete(n),d(t,void 0,!1));return}let o=e.mtimeMs,s=a?{locked:a.locked,pid:a.pid}:{locked:!1,pid:void 0};if((r||!a)&&(s=Jp(i)),!a||a.mtime!==o||a.locked!==s.locked||a.pid!==s.pid){let e;e=!a||a.mtime!==o?JSON.parse(N.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{N.mkdirSync(e,{recursive:!0})}catch{}a=N.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){p();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=u(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&f(r,e,!0);return}let n=u(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&m(r,t,!1)});let t=()=>{p(),o=setTimeout(t,n)};p(),o=setTimeout(t,n)};return{onChange(e){return i.size===0&&h(),i.add(e),()=>{if(i.delete(e),i.size===0){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),c.clear()}}},dispose(){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),i.clear(),c.clear()}}};async function tm({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=nm}){n=[...n];let a=new TransformStream,o=a.writable.getWriter(),s=async()=>{let a;try{let c=await t.chat({messages:n,id:e},{signal:r}),l=ye({message:{id:crypto.randomUUID(),role:`assistant`,parts:[],metadata:{}},stream:c,onError:e=>{e instanceof Error&&e.name===`AbortError`||o.abort(e)}});for await(let e of l)o.write(e),a=e;if(a&&i(a)){n.push(a),await s();return}await o.close()}catch(e){if(e?.name===`AbortError`||r?.aborted)return;await o.abort(e)}finally{await o.close()}};return s().catch(e=>{o.abort(e)}),a.readable}const nm=e=>{if(e.role!==`assistant`)return!1;let t=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),n=e.parts.slice(t+1).filter(ve);return n.length===0||n.some(e=>T(e.output)&&e.output.outcome===`pending`)?!1:n.every(e=>e.state.startsWith(`output-`))},rm=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function im(e){return typeof e==`object`&&e?.__blink_internal!==void 0}function am(e){return typeof e.metadata==`object`&&e.metadata!==null&&`__blink_log`in e.metadata&&e.metadata.__blink_log===!0&&`level`in e.metadata&&`source`in e.metadata&&`message`in e.metadata}var om=class{chatId;agent;chatStore;serializeMessage;filterMessages;onError;chat;loading=!1;streamingMessage;status=`idle`;queue=[];logQueue=[];abortController;isProcessingQueue=!1;listeners=new Set;watcher;disposed=!1;constructor(e){this.chatId=e.chatId??`00000000-0000-0000-0000-000000000000`,this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.loading=!0,this.chatStore=$p(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.onError=e.onError,this.watcher=em(e.chatsDirectory,{pollInterval:1e3,debounce:50}),this.watcher.onChange(e=>{if(e.key!==this.chatId||this.isProcessingQueue)return;if(!e.value){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.status=`idle`,this.streamingMessage=void 0,this.notifyListeners();return}if(this.chat.updated_at===e.value?.updated_at)return;let t=e.value,n=e.locked?`streaming`:`idle`,r=this.chat.updated_at!==t?.updated_at||this.status!==n;this.chat=t,this.streamingMessage=void 0,this.status=n,r&&this.notifyListeners()}),this.chatStore.get(this.chatId).then(e=>{this.disposed||e&&(this.chat=e)}).catch(e=>{let t=e instanceof Error?e.message:String(e);this.onError?.(t)}).finally(()=>{this.loading=!1,this.notifyListeners()})}setAgent(e){this.agent=e}getState(){return{id:this.chatId,key:this.chat?.key,messages:(this.chat?.messages??[]).filter(e=>!im(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,loading:this.loading,queuedMessages:this.queue,queuedLogs:this.logQueue}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async upsertMessages(e,t){let n=!1,r;t?r=t:(r=await this.chatStore.lock(this.chatId),n=!0);try{let t=await r.get();(!t.id||!Array.isArray(t.messages))&&(t={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]});let n=[...t.messages];for(let t of e){let e;if(this.serializeMessage){let n=this.serializeMessage(t);if(n===void 0)return;e=n}else e={...t,created_at:new Date().toISOString(),mode:`run`,metadata:t.metadata,id:t.id??crypto.randomUUID()};let r=n.findIndex(t=>t.id===e.id);r===-1?n.push(e):n.splice(r,1,e)}this.chat={...t,updated_at:new Date().toISOString(),messages:n},await r.set(this.chat),this.notifyListeners()}finally{n&&await r.release()}}async deleteMessages(e){let t;try{t=await this.chatStore.lock(this.chatId);let n=await t.get();this.chat.messages=n.messages.filter(t=>!e.includes(t.id)),this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),this.notifyListeners()}finally{t&&await t.release()}}async queueLogMessage({message:e,level:t,source:n}){let r=`(EDIT MODE NOTE) ${n===`agent`?`The agent`:"The `blink dev` CLI"} printed the following ${t}:\n\`\`\`\n${se(e)}\n\`\`\`\n`,i={id:crypto.randomUUID(),created_at:new Date().toISOString(),role:`user`,parts:[{type:`text`,text:r}],metadata:{__blink_log:!0,level:t,source:n,message:e},mode:`edit`};this.logQueue.push(i),this.notifyListeners()}async flushLogQueue(e){if(this.logQueue.length===0)return;let t=[...this.logQueue];this.logQueue=[],await this.upsertMessages(t,e)}async sendMessages(e){if(this.status=`idle`,this.notifyListeners(),this.isProcessingQueue){this.queue.push(...e),this.notifyListeners();return}this.queue=e,this.processQueueOrRun()}async start(){this.status=`idle`,this.notifyListeners(),this.processQueueOrRun()}async stop(){this.status=`idle`,this.abortController?.abort(),this.notifyListeners()}async processQueueOrRun(){if(!this.agent){this.onError?.(`The agent is not available. Please wait for the build to succeed.`),this.queue=[];return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0;let e;try{e=await this.chatStore.lock(this.chatId),await this.flushLogQueue(e);let n=!0;for(;this.queue.length>0||n;)try{var t=Dc();n=!1;let r=new AbortController;this.abortController=r;let i=[...this.queue];this.queue=[],this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),i.length>0&&await this.upsertMessages(i,e);let a=this.chat.messages;this.filterMessages&&(a=a.filter(this.filterMessages)),a=a.map(e=>({...e,parts:e.parts.map(e=>!ve(e)||e.input!==``?e:{...e,input:{}})})),t.u(await this.agent.agentLock.read());let o=performance.now(),s=await tm({agent:this.agent,id:this.chatId,signal:r.signal,messages:a}),c=async t=>{let n=t;if(this.serializeMessage){let e=this.serializeMessage(t);if(e===void 0)return;n=e}this.chat.updated_at=new Date().toISOString(),this.chat.messages.push(n),this.streamingMessage=void 0,await e?.set(this.chat)},l=s.getReader();r.signal.addEventListener(`abort`,()=>{l.cancel().catch(()=>{})},{once:!0});let u;try{for(;;){let{done:e,value:t}=await l.read();if(e||r.signal.aborted)break;u||=performance.now()-o,this.streamingMessage&&t.id!==this.streamingMessage.id&&await c(this.streamingMessage);let n={...t,metadata:{...typeof t.metadata==`object`&&t.metadata!==null?t.metadata:{},ttft:u}};this.streamingMessage=this.serializeMessage?this.serializeMessage(n):n,this.notifyListeners()}}finally{l.releaseLock()}this.streamingMessage&&await c(this.streamingMessage)}catch(e){t.e=e}finally{t.d()}}catch(e){let t=e instanceof Error?e.message:String(e);this.onError?.(t)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,this.status=`idle`,e&&(await this.flushLogQueue(e),this.chat.updated_at=new Date().toISOString(),await e.set(this.chat),await e.release(),this.notifyListeners())}}stopStreaming(){this.abortController?.abort()}clearQueue(){this.queue=[],this.notifyListeners()}async resetChat(){this.abortController?.abort(),this.resetChatState(),this.notifyListeners();let e;try{e=await this.chatStore.lock(this.chatId),await e.delete()}catch{}finally{if(e)try{await e.release()}catch{}}}dispose(){this.disposed=!0,this.watcher.dispose(),this.listeners.clear(),this.stopStreaming()}resetChatState(){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.streamingMessage=void 0,this.status=`idle`,this.queue=[],this.logQueue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};function sm(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a,onError:o}=e,s=U(null),[c,l]=W({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[],queuedLogs:[]});H(()=>{s.current&&s.current.dispose();let e=new om({chatId:t,chatsDirectory:r,serializeMessage:i,filterMessages:a,onError:o}),n=e.subscribe(e=>{l(e)});return l(e.getState()),s.current=e,()=>{n(),e.dispose(),s.current=null}},[t,r]),H(()=>{s.current&&s.current.setAgent(n)},[n]);let u=V(async e=>{s.current&&await s.current.sendMessages([e])},[]),d=V(async e=>{s.current&&await s.current.upsertMessages([e])},[]),f=V(async e=>{s.current&&await s.current.queueLogMessage(e)},[]),p=V(()=>{s.current&&s.current.stopStreaming()},[]),m=V(async()=>{s.current&&await s.current.resetChat()},[]),h=V(()=>{s.current&&s.current.clearQueue()},[]),g=V(async e=>{s.current&&await s.current.deleteMessages([e])},[]),_=V(async()=>{s.current&&await s.current.start()},[]);return{...c,sendMessage:u,upsertMessage:d,queueLogMessage:f,stopStreaming:p,resetChat:m,clearQueue:h,deleteMessage:g,start:_}}function cm(e){return de(e,`.blink`,`devhook.txt`)}function lm(e){return fe(cm(e))}function um(e){let t=cm(e);if(fe(t))return me(t,`utf-8`).trim()}function dm(e){let t=cm(e);if(pe(z(t),{recursive:!0}),fe(t))return me(t,`utf-8`);let n=crypto.randomUUID();return ge(t,n),n}const fm=(e,t)=>e.json({error:t},400),pm=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}},mm=()=>new f,hm=mm().get(`/:key`,async e=>{let{key:t,err:n}=pm(e);if(n)return fm(e,n);let r=await e.env.store.get(t);return e.json({value:r},200)}).post(`/:key`,O(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?fm(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:fm(t,`Value must be a string`):fm(t,`Value is required`)}),async e=>{let{key:t,err:n}=pm(e);if(n)return fm(e,n);let{value:r}=e.req.valid(`json`);return await e.env.store.set(t,r),e.body(null,204)}).delete(`/:key`,async e=>{let{key:t,err:n}=pm(e);return n?fm(e,n):(await e.env.store.delete(t),e.body(null,204))}).get(`/`,async e=>{let{cursor:t,limit:n,prefix:r}=e.req.query(),{entries:i,cursor:a}=await e.env.store.list(r,{cursor:t?String(t):void 0,limit:n?Number(n):100});return e.json({entries:i,cursor:a})}),gm=e=>{let t=e.req.param(`key`);return t?t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}:{key:t,err:`Key is required`}},_m=O(`param`,e=>({id:e.id})),vm=mm().post(`/:key`,async e=>{let{key:t,err:n}=gm(e);return n?fm(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,_m,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,_m,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.getMessages(t),200)}).post(`/:id/sendMessages`,O(`json`,e=>({id:e.id,messages:e.messages,options:e.options})),async e=>{let{id:t,messages:n,options:r}=e.req.valid(`json`);return t?(await e.env.chat.sendMessages(t,n,r),e.body(null,204)):fm(e,`ID is required`)}).delete(`/:id/messages`,_m,O(`query`,e=>(typeof e.message==`string`&&(e.message=[e.message]),{messages:e.message})),async e=>{let{id:t}=e.req.valid(`param`),{messages:n}=e.req.valid(`query`);return await e.env.chat.deleteMessages(t,n),e.body(null,204)}).post(`/:id/start`,_m,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,_m,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,_m,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),ym=mm().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),bm=new f().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,hm).route(`/chat`,vm).route(`/otlp`,ym);var xm=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function Sm(e){return typeof e==`string`&&xm.test(e)}var Cm=Sm;function wm(e){if(!Cm(e))throw TypeError(`Invalid UUID`);let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,t&255,(t=parseInt(e.slice(9,13),16))>>>8,t&255,(t=parseInt(e.slice(14,18),16))>>>8,t&255,(t=parseInt(e.slice(19,23),16))>>>8,t&255,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255)}var Tm=wm;const Em=[];for(let e=0;e<256;++e)Em.push((e+256).toString(16).slice(1));function Dm(e,t=0){return(Em[e[t+0]]+Em[e[t+1]]+Em[e[t+2]]+Em[e[t+3]]+`-`+Em[e[t+4]]+Em[e[t+5]]+`-`+Em[e[t+6]]+Em[e[t+7]]+`-`+Em[e[t+8]]+Em[e[t+9]]+`-`+Em[e[t+10]]+Em[e[t+11]]+Em[e[t+12]]+Em[e[t+13]]+Em[e[t+14]]+Em[e[t+15]]).toLowerCase()}function Om(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t}function km(e,t,n,r,i,a){let o=typeof n==`string`?Om(n):n,s=typeof r==`string`?Tm(r):r;if(typeof r==`string`&&(r=Tm(r)),r?.length!==16)throw TypeError(`Namespace must be array-like (16 iterable integer values, 0-255)`);let c=new Uint8Array(16+o.length);if(c.set(s),c.set(o,s.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,i){a||=0;for(let e=0;e<16;++e)i[a+e]=c[e];return i}return Dm(c)}function Am(e){return Array.isArray(e)?e=Buffer.from(e):typeof e==`string`&&(e=Buffer.from(e,`utf8`)),ce(`sha1`).update(e).digest()}var jm=Am;function Mm(e,t,n,r){return km(80,jm,e,t,n,r)}Mm.DNS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,Mm.URL=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;var Nm=Mm;function Pm(e){let t=ke(e.dataDirectory,`chats`),n={},r=ke(e.dataDirectory,`storage.json`);N.existsSync(r)&&(n=JSON.parse(N.readFileSync(r,`utf-8`)));let i=new Map,a=n=>{let r=i.get(n);return r||(r=new om({chatId:n,chatsDirectory:t}),i.set(n,r)),r.setAgent(e.getAgent()),r},o={async upsert(e){let t=Nm(JSON.stringify(e),Nm.URL),n=a(t).getState(),r=n.messages.length===0&&!n.created_at;return{id:n.id,created:r,createdAt:n.created_at??new Date().toISOString(),key:e}},async get(e){let t=a(e).getState();return{id:t.id,createdAt:t.created_at??new Date().toISOString()}},async getMessages(e){return a(e).getState().messages},async sendMessages(e,t,n){let r=a(e),i=t.map(e=>rm(e,`run`));if(n?.behavior===`append`){await r.upsertMessages(i);return}if(n?.behavior===`interrupt`){await r.sendMessages(i);return}await r.sendMessages(i)},async deleteMessages(e,t){await a(e).deleteMessages(t)},async start(e){await a(e).start()},async stop(e){await a(e).stop()},async delete(e){await a(e).resetChat()}},s={get(e){return Promise.resolve(n[e])},set(e,t){return n[e]=t,N.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},delete(e){return delete n[e],N.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},list(e,t){let r=Math.min(t?.limit??100,1e3),i=t?.cursor,a=Object.keys(n).filter(t=>t.startsWith(e??``)).sort(),o=0;if(i){let e=a.indexOf(i);e!==-1&&(o=e+1)}let s=a.slice(o,o+r),c=o+r<a.length?s[s.length-1]:void 0;return Promise.resolve({entries:s.map(e=>({key:e})),cursor:c})}},c=ue(w(e=>bm.fetch(e,{chat:o,store:s})));c.listen(e.port??0);let l=$p(t,`id`);return{url:`http://127.0.0.1:${c.address().port}`,chatsDirectory:t,getChatManager:a,listChats:()=>l.list(),dispose:()=>{for(let e of i.values())e.dispose();i.clear(),l.dispose(),c.close()}}}function Fm({agent:e,capabilities:t,messages:n}){let[r,i]=W(void 0),[a,o]=W(!0),[s,c]=W(void 0),l=U(s);H(()=>{l.current=s},[s]);let[u,d]=W(()=>E(n));H(()=>{d(e=>{let t=E(n);return JSON.stringify(t)===JSON.stringify(e)?e:t})},[n]);let[f,p]=W(void 0),m=V((e,t)=>{if(!l.current)return!1;let n=l.current[e];return n?n.values.some(e=>e.id===t):!1},[]),h=V(e=>{p(t=>{let n={...u,...t,...e};for(let[e,t]of Object.entries(n))m(e,t)||delete n[e];for(let[e,t]of Object.entries(l.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[u,m]);H(()=>{if(!u&&!s){p(void 0);return}h()},[u,s,h]);let g=U(void 0),_=U(void 0);H(()=>{e!==_.current&&(_.current=e,c(void 0),p(void 0),i(void 0),o(!0),g.current=void 0)},[e]),H(()=>{if(t&&!t.ui||!e){c(void 0),p(void 0),i(void 0),g.current=void 0;return}let n=f?JSON.stringify(f):``;if(g.current===n){o(!1),i(void 0);return}let r=new AbortController;return o(!0),i(void 0),e.ui(f?{selectedOptions:f}:{},{signal:r.signal}).then(e=>{if(!e){c(void 0);return}r.signal.aborted||(c(t=>JSON.stringify(t)===JSON.stringify(e)?t:e),g.current=n)}).catch(e=>{r.signal.aborted||i(e instanceof Error?e:Error(String(e)))}).finally(()=>{o(!1)}),()=>{r.abort()}},[e,t,f]);let v=V((e,t)=>{h({[e]:t})},[h]);return{schema:s,options:f,setOption:v,loading:a,error:r}}function Im(e){let t=U(e.onRequest);H(()=>{t.current=e.onRequest},[e.onRequest]);let[n,r]=W(`disconnected`);return H(()=>{if(e.disabled||!e.id){r(`disconnected`);return}let n=!1,i,a,o=!1,s,c=ke(e.directory,`.blink`,`devhook`);return(async()=>{try{s=await Kp(c,{stale:!0,retries:0})}catch(t){if(t&&typeof t==`object`&&`code`in t&&t.code===`ELOCKED`){let t=``;try{let e=Jp(c);e.locked&&e.pid&&(t=` (PID: ${e.pid})`)}catch{}e.logger.error(`system`,cf.red(`\nError: Another ${cf.bold(`blink dev`)} process is already running in this directory${t}.`)),e.logger.error(`system`,cf.red(`Please stop the other process and try again.
|
|
52
|
+
`)},info:e=>Ff.message(e,{symbol:Cf.default.blue(kf)}),success:e=>Ff.message(e,{symbol:Cf.default.green(Af)}),step:e=>Ff.message(e,{symbol:Cf.default.green(Df)}),warn:e=>Ff.message(e,{symbol:Cf.default.yellow(jf)}),warning:e=>Ff.warn(e),error:e=>Ff.message(e,{symbol:Cf.default.red(Mf)})};let If;function Lf(){try{return P.statSync(`/.dockerenv`),!0}catch{return!1}}function Rf(){try{return P.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function zf(){return If===void 0&&(If=Lf()||Rf()),If}let Bf;const Vf=()=>{try{return P.statSync(`/run/.containerenv`),!0}catch{return!1}};function Hf(){return Bf===void 0&&(Bf=Vf()||zf()),Bf}const Uf=()=>{if(J.platform!==`linux`)return!1;if(Me.release().toLowerCase().includes(`microsoft`))return!Hf();try{return P.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!Hf():!1}catch{return!1}};var Wf=J.env.__IS_WSL_TEST__?Uf:Uf();const Gf=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await Re.access(n,ze.F_OK),r=!0}catch{}if(!r)return e;let i=await Re.readFile(n,{encoding:`utf8`}),a=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(i);return a?(t=a.groups.mountPoint.trim(),t=t.endsWith(`/`)?t:`${t}/`,t):e}})(),Kf=async()=>`${await Gf()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,qf=async()=>Wf?Kf():`${J.env.SYSTEMROOT||J.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function Jf(e,t,n){let r=n=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0});return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){let e=n();return r(e),e},set(e){r(e)}}),e}const Yf=oe(Le);async function Xf(){if(J.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await Yf(`defaults`,[`read`,`com.apple.LaunchServices/com.apple.launchservices.secure`,`LSHandlers`]);return/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??`com.apple.Safari`}const Zf=oe(Le);async function Qf(e,{humanReadableOutput:t=!0,signal:n}={}){if(J.platform!==`darwin`)throw Error(`macOS only`);let r=t?[]:[`-ss`],i={};n&&(i.signal=n);let{stdout:a}=await Zf(`osascript`,[`-e`,e,r],i);return a.trim()}async function $f(e){return Qf(`tell application "Finder" to set app_path to application file id "${e}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}const ep=oe(Le),tp={AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:`Edge`,id:`com.microsoft.edge.old`},MSEdgeDHTML:{name:`Edge`,id:`com.microsoft.edge`},MSEdgeHTM:{name:`Edge`,id:`com.microsoft.edge`},"IE.HTTP":{name:`Internet Explorer`,id:`com.microsoft.ie`},FirefoxURL:{name:`Firefox`,id:`org.mozilla.firefox`},ChromeHTML:{name:`Chrome`,id:`com.google.chrome`},BraveHTML:{name:`Brave`,id:`com.brave.Browser`},BraveBHTML:{name:`Brave Beta`,id:`com.brave.Browser.beta`},BraveSSHTM:{name:`Brave Nightly`,id:`com.brave.Browser.nightly`}};var np=class extends Error{};async function rp(e=ep){let{stdout:t}=await e(`reg`,[`QUERY`,` HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice`,`/v`,`ProgId`]),n=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(t);if(!n)throw new np(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=tp[r];if(!i)throw new np(`Unknown browser ID: ${r}`);return i}const ip=oe(Le),ap=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function op(){if(J.platform===`darwin`){let e=await Xf();return{name:await $f(e),id:e}}if(J.platform===`linux`){let{stdout:e}=await ip(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:ap(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(J.platform===`win32`)return rp();throw Error(`Only macOS, Linux, and Windows are supported`)}const sp=oe(Ie.execFile),cp=De.dirname(ae(import.meta.url)),lp=De.join(cp,`xdg-open`),{platform:up,arch:dp}=J;async function fp(){let e=await qf(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=ne.from(t,`utf16le`).toString(`base64`),{stdout:r}=await sp(e,[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,n],{encoding:`utf8`}),i=r.trim(),a={ChromeHTML:`com.google.chrome`,BraveHTML:`com.brave.Browser`,MSEdgeHTM:`com.microsoft.edge`,FirefoxURL:`org.mozilla.firefox`};return a[i]?{id:a[i]}:{}}const pp=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},mp=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return pp(e.app,t=>mp({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return pp(t,t=>mp({...e,app:{name:t,arguments:n}}));if(t===`browser`||t===`browserPrivate`){let r={"com.google.chrome":`chrome`,"google-chrome.desktop":`chrome`,"com.brave.Browser":`brave`,"org.mozilla.firefox":`firefox`,"firefox.desktop":`firefox`,"com.microsoft.msedge":`edge`,"com.microsoft.edge":`edge`,"com.microsoft.edgemac":`edge`,"microsoft-edge.desktop":`edge`},i={chrome:`--incognito`,brave:`--incognito`,firefox:`--private-window`,edge:`--inPrivate`},a=Wf?await fp():await op();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),mp({...e,app:{name:vp[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,i=[],a={};if(up===`darwin`)r=`open`,e.wait&&i.push(`--wait-apps`),e.background&&i.push(`--background`),e.newInstance&&i.push(`--new`),t&&i.push(`-a`,t);else if(up===`win32`||Wf&&!Hf()&&!t){r=await qf(),i.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),Wf||(a.windowsVerbatimArguments=!0);let o=[`Start`];e.wait&&o.push(`-Wait`),t?(o.push(`"\`"${t}\`""`),e.target&&n.push(e.target)):e.target&&o.push(`"${e.target}"`),n.length>0&&(n=n.map(e=>`"\`"${e}\`""`),o.push(`-ArgumentList`,n.join(`,`))),e.target=ne.from(o.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!cp||cp===`/`,t=!1;try{await Re.access(lp,ze.X_OK),t=!0}catch{}r=J.versions.electron??(up===`android`||e||!t)?`xdg-open`:lp}n.length>0&&i.push(...n),e.wait||(a.stdio=`ignore`,a.detached=!0)}up===`darwin`&&n.length>0&&i.push(`--args`,...n),e.target&&i.push(e.target);let o=Ie.spawn(r,i,a);return e.wait?new Promise((t,n)=>{o.once(`error`,n),o.once(`close`,r=>{if(!e.allowNonzeroExitCode&&r>0){n(Error(`Exited with code ${r}`));return}t(o)})}):(o.unref(),o)},hp=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return mp({...t,target:e})};function gp(e){if(typeof e==`string`||Array.isArray(e))return e;let{[dp]:t}=e;if(!t)throw Error(`${dp} is not supported`);return t}function _p({[up]:e},{wsl:t}){if(t&&Wf)return gp(t);if(!e)throw Error(`${up} is not supported`);return gp(e)}const vp={};Jf(vp,`chrome`,()=>_p({darwin:`google chrome`,win32:`chrome`,linux:[`google-chrome`,`google-chrome-stable`,`chromium`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`,x64:[`/mnt/c/Program Files/Google/Chrome/Application/chrome.exe`,`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`]}})),Jf(vp,`brave`,()=>_p({darwin:`brave browser`,win32:`brave`,linux:[`brave-browser`,`brave`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`,x64:[`/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe`,`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`]}})),Jf(vp,`firefox`,()=>_p({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),Jf(vp,`edge`,()=>_p({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),Jf(vp,`browser`,()=>`browser`),Jf(vp,`browserPrivate`,()=>`browserPrivate`);var yp=hp;async function bp(e,t=void 0){try{(await yp(e)).once(`error`,n=>{console.log(cf.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))})}catch{console.log(cf.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))}}function xp(e){let t=e||wp();if(F(t)){let e=I(t,`utf8`);return JSON.parse(e).token}}function Sp(e,t){let n=t||wp();F(Oe(n))||re(Oe(n),{recursive:!0}),L(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function Cp(e){let t=e||wp();F(t)&&ie(t)}function wp(){let e=Dd(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return ke(e[0],`auth.json`)}function Tp(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=W(),[s,c]=W(()=>xp(i)),[l,u]=W(),d=U(n),f=U(r);H(()=>{d.current=n,f.current=r},[n,r]);let p=V(async()=>{u(void 0);try{let e=xp(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new ld({baseURL:`https://blink.so`});t.authToken=e;let n={email:(await t.users.me()).email};o(n),d.current?.(n)}catch(e){o(void 0),u(e instanceof Error?e.message:String(e)),d.current?.(void 0)}},[i]),m=V(async()=>{u(void 0);try{let e=new ld,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();Sp(t,i),c(t);let r={email:n.email};return o(r),d.current?.(r),r}catch(e){let t=e instanceof Error?e.message:String(e);throw u(t),e}},[i]),h=V(()=>{Cp(i),c(void 0),o(void 0),u(void 0),d.current?.(void 0)},[i]);return H(()=>{t&&p()},[t,p]),{user:a,token:s,error:l,login:m,logout:h}}let Ep=Promise.resolve();var Dp=class{constructor(e){this.printLog=e}setPrintLog(e){this.printLog=e}error(e,...t){Ep=Ep.then(()=>this.printLog(`error`,e,...t).catch(e=>{console.error(`Error printing log:`,e)}))}log(e,...t){Ep=Ep.then(()=>this.printLog(`log`,e,...t).catch(e=>{console.error(`Error printing log:`,e)}))}flush(){return Ep}};const Op=Te(void 0);function kp(e){let{directory:t,logger:n,onBuildStart:r,onBuildSuccess:i,onBuildError:a}=typeof e==`string`?{directory:e,logger:new Dp(async()=>{})}:e,o=Ee(()=>k(t),[t]),[s,c]=W(void 0),[l,u]=W(void 0),[d,f]=W(`building`),p=U(r),m=U(i),h=U(a);return H(()=>{p.current=r,m.current=i,h.current=a},[r,i,a]),H(()=>{let e=new AbortController;return o.build({cwd:t,entry:o.entry,outdir:o.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{f(`building`),c(void 0),u(void 0),p.current?.()},onResult:e=>{`error`in e?(c(e.error),f(`error`),h.current?.(e.error)):(u(e),f(`success`),m.current?.(e))}}).catch(e=>{n.error(`system`,`error`,e),f(`error`),c(e),h.current?.(e)}),()=>{e.abort()}},[t]),Ee(()=>({error:s,status:d,result:l,entry:o.entry,outdir:o.outdir}),[s,d,l,o.entry,o.outdir])}function Ap(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function jp(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const Mp=/^\.+(\\|\/)|^\.+$/,Np=/[. ]+$/,Pp=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,Fp=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,Ip=e=>e===``,Lp=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,Rp=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let zp;function Bp(){return zp??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),zp}function Vp(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(Ap().test(n)||[...n].some(e=>Fp.test(e)&&!Ip(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(Rp,` `),n.length>0&&(e=e.replaceAll(Lp,`$1`)),e=e.replace(Np,``),e=e.replace(Mp,n),e=e.replace(Ap(),n),e=e.replaceAll(Pp,e=>Ip(e)?e:n),e.length===0&&(e=n),e=jp().test(e)?e+n:e;let r=typeof t.maxLength==`number`?t.maxLength:100;if(e.length>r){let t=e.lastIndexOf(`.`);if(t===-1)e=Hp(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=Hp(n,a)+i}}return e}function Hp(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of Bp().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function Up(e){return`${e}.lock`}function Wp(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function Gp(e,t={}){let n=Up(e),r=process.pid.toString();try{return N.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(N.readFileSync(n,`utf8`),10)}catch{return N.unlinkSync(n),Gp(e,{...t,stale:0})}if(!Wp(i))try{return N.unlinkSync(n),Gp(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return Gp(e,{...t,stale:0});throw n}return!1}}async function Kp(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=q.resolve(e),i=0;for(;i<=n.retries;){if(Gp(r,n))return()=>qp(r);i<n.retries&&await new Promise(e=>setTimeout(e,n.retryInterval)),i++}let a=Error(`Lock file is already being held`);throw a.code=`ELOCKED`,a.file=r,a}function qp(e){let t=q.resolve(e),n=Up(t);try{if(parseInt(N.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}N.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function Jp(e){let t=q.resolve(e),n=Up(t);try{if(!N.existsSync(n))return{locked:!1};let e=N.readFileSync(n,`utf8`),t=parseInt(e,10);return Wp(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const Yp=e=>{N.mkdirSync(e,{recursive:!0})},Xp=e=>{try{N.fdatasyncSync(e)}catch{}try{N.closeSync(e)}catch{}},Zp=e=>{try{let t=N.openSync(e,`r`);try{N.fsyncSync(t)}finally{N.closeSync(t)}}catch{}},Qp=(e,t)=>{let n=q.dirname(e);Yp(n);let r=q.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=N.openSync(r,`w`),N.writeFileSync(i,t,`utf-8`),Xp(i),i=void 0,N.renameSync(r,e),Zp(e),Zp(n)}catch(e){if(i!==void 0)try{N.closeSync(i)}catch{}try{N.rmSync(r,{force:!0})}catch{}throw e}},$p=(e,t)=>{let n=new Map,r,i=e=>{if(N.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(N.readFileSync(e,`utf-8`))},a=(e,t)=>{Qp(e,JSON.stringify(t,null,2))},o=async()=>{if(r)throw Error(`Index is already locked`);let t=q.join(e,`index.json`);Yp(e),N.existsSync(t)||N.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await Kp(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},s=async()=>{let t=q.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},c=async t=>{let n=q.join(e,`index.json`);a(n,t)},l=async t=>{let n=(await s()).ids[t];if(n)return q.join(e,n)},u=async t=>{let n=(await s()).ids[t];if(!n)return;let r=q.join(e,n);if(N.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(N.readFileSync(r,`utf-8`))},d=async n=>{let r=n[t],i=String(r),l=Vp(i,{replacement:`_`})+`.json`,u=await o();try{let t=await s();t.ids[i]=l,t.current=i;let r=q.join(e,l);a(r,n),await c(t)}finally{await u()}};return{async get(e){return await u(e)},async list(){if(!N.statSync(e,{throwIfNoEntry:!1}))return[];let t=await s(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=q.join(e,i),a=N.statSync(t,{throwIfNoEntry:!1});if(!a)continue;let o=Jp(t);n.push({key:r,locked:o.locked,pid:o.pid,mtime:a.mtimeMs})}return n.sort((e,t)=>t.mtime-e.mtime),n},async lock(r,i){if(n.has(r))throw Error(`Key "${r}" is already locked in this process`);let a=await l(r);if(!a){let t=Vp(r,{replacement:`_`})+`.json`,n=await o();try{let n=await s();n.ids[r]=t;let i=q.join(e,t);Yp(e),N.writeFileSync(i,JSON.stringify({}),`utf-8`),await c(n),a=i}finally{await n()}}if(i?.force){let e=Jp(a);if(e.locked&&e.pid&&e.pid!==process.pid)try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,100))}catch(t){t.code!==`ESRCH`&&console.warn(`Failed to kill process ${e.pid}:`,t.message)}}let f=await Kp(a,{stale:!0,retries:i?.force?10:5,retryInterval:(i?.force,100)});return n.set(r,()=>Promise.resolve(f())),{async get(){let e=await u(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await d(e)},async update(e){let n=await u(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await d({...n,...e})},async delete(){let t=await o();try{let t=await s(),n=t.ids[r];if(n){delete t.ids[r],t.current===r&&(t.current=void 0),await c(t);let i=q.join(e,n);try{N.rmSync(i,{force:!0}),Zp(e)}catch{}}}finally{await t()}},async release(){try{f()}finally{n.delete(r)}}}},dispose(){n.clear()}}},em=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,a,o,s=new Map,c=new Map,l=q.join(e,`index.json`),u=()=>{try{if(!N.statSync(l,{throwIfNoEntry:!1}))return{ids:{}};let e=N.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=q.join(e,n);try{let e=N.statSync(i,{throwIfNoEntry:!1}),a=c.get(n);if(!e){a&&(c.delete(n),d(t,void 0,!1));return}let o=e.mtimeMs,s=a?{locked:a.locked,pid:a.pid}:{locked:!1,pid:void 0};if((r||!a)&&(s=Jp(i)),!a||a.mtime!==o||a.locked!==s.locked||a.pid!==s.pid){let e;e=!a||a.mtime!==o?JSON.parse(N.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{N.mkdirSync(e,{recursive:!0})}catch{}a=N.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){p();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=u(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&f(r,e,!0);return}let n=u(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&m(r,t,!1)});let t=()=>{p(),o=setTimeout(t,n)};p(),o=setTimeout(t,n)};return{onChange(e){return i.size===0&&h(),i.add(e),()=>{if(i.delete(e),i.size===0){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),c.clear()}}},dispose(){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),i.clear(),c.clear()}}};async function tm({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=nm}){n=[...n];let a=new TransformStream,o=a.writable.getWriter(),s=async()=>{let a;try{let c=await t.chat({messages:n,id:e},{signal:r}),l=ye({message:{id:crypto.randomUUID(),role:`assistant`,parts:[],metadata:{}},stream:c,onError:e=>{e instanceof Error&&e.name===`AbortError`||o.abort(e)}});for await(let e of l)o.write(e),a=e;if(a&&i(a)){n.push(a),await s();return}await o.close()}catch(e){if(e?.name===`AbortError`||r?.aborted)return;await o.abort(e)}finally{await o.close()}};return s().catch(e=>{o.abort(e)}),a.readable}const nm=e=>{if(e.role!==`assistant`)return!1;let t=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),n=e.parts.slice(t+1).filter(ve);return n.length===0||n.some(e=>T(e.output)&&e.output.outcome===`pending`)?!1:n.every(e=>e.state.startsWith(`output-`))},rm=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function im(e){return typeof e==`object`&&e?.__blink_internal!==void 0}function am(e){return typeof e.metadata==`object`&&e.metadata!==null&&`__blink_log`in e.metadata&&e.metadata.__blink_log===!0&&`level`in e.metadata&&`source`in e.metadata&&`message`in e.metadata}var om=class{chatId;agent;chatStore;serializeMessage;filterMessages;onError;chat;loading=!1;streamingMessage;status=`idle`;queue=[];logQueue=[];abortController;isProcessingQueue=!1;listeners=new Set;watcher;disposed=!1;constructor(e){this.chatId=e.chatId??`00000000-0000-0000-0000-000000000000`,this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.loading=!0,this.chatStore=$p(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.onError=e.onError,this.watcher=em(e.chatsDirectory,{pollInterval:1e3,debounce:50}),this.watcher.onChange(e=>{if(e.key!==this.chatId||this.isProcessingQueue)return;if(!e.value){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.status=`idle`,this.streamingMessage=void 0,this.notifyListeners();return}if(this.chat.updated_at===e.value?.updated_at)return;let t=e.value,n=e.locked?`streaming`:`idle`,r=this.chat.updated_at!==t?.updated_at||this.status!==n;this.chat=t,this.streamingMessage=void 0,this.status=n,r&&this.notifyListeners()}),this.chatStore.get(this.chatId).then(e=>{this.disposed||e&&(this.chat=e)}).catch(e=>{let t=e instanceof Error?e.message:String(e);this.onError?.(t)}).finally(()=>{this.loading=!1,this.notifyListeners()})}setAgent(e){this.agent=e}getState(){return{id:this.chatId,key:this.chat?.key,messages:(this.chat?.messages??[]).filter(e=>!im(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,loading:this.loading,queuedMessages:this.queue,queuedLogs:this.logQueue}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async upsertMessages(e,t){let n=!1,r;t?r=t:(r=await this.chatStore.lock(this.chatId),n=!0);try{let t=await r.get();(!t.id||!Array.isArray(t.messages))&&(t={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]});let n=[...t.messages];for(let t of e){let e;if(this.serializeMessage){let n=this.serializeMessage(t);if(n===void 0)return;e=n}else e={...t,created_at:new Date().toISOString(),mode:`run`,metadata:t.metadata,id:t.id??crypto.randomUUID()};let r=n.findIndex(t=>t.id===e.id);r===-1?n.push(e):n.splice(r,1,e)}this.chat={...t,updated_at:new Date().toISOString(),messages:n},await r.set(this.chat),this.notifyListeners()}finally{n&&await r.release()}}async deleteMessages(e){let t;try{t=await this.chatStore.lock(this.chatId);let n=await t.get();this.chat.messages=n.messages.filter(t=>!e.includes(t.id)),this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),this.notifyListeners()}finally{t&&await t.release()}}async queueLogMessage({message:e,level:t,source:n}){let r=`(EDIT MODE NOTE) ${n===`agent`?`The agent`:"The `blink dev` CLI"} printed the following ${t}:\n\`\`\`\n${se(e)}\n\`\`\`\n`,i={id:crypto.randomUUID(),created_at:new Date().toISOString(),role:`user`,parts:[{type:`text`,text:r}],metadata:{__blink_log:!0,level:t,source:n,message:e},mode:`edit`};this.logQueue.push(i),this.notifyListeners()}async flushLogQueue(e){if(this.logQueue.length===0)return;let t=[...this.logQueue];this.logQueue=[],await this.upsertMessages(t,e)}async sendMessages(e){if(this.status=`idle`,this.notifyListeners(),this.isProcessingQueue){this.queue.push(...e),this.notifyListeners();return}this.queue=e,this.processQueueOrRun()}async start(){this.status=`idle`,this.notifyListeners(),this.processQueueOrRun()}async stop(){this.status=`idle`,this.abortController?.abort(),this.notifyListeners()}async processQueueOrRun(){if(!this.agent){this.onError?.(`The agent is not available. Please wait for the build to succeed.`),this.queue=[];return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0;let e;try{e=await this.chatStore.lock(this.chatId),await this.flushLogQueue(e);let n=!0;for(;this.queue.length>0||n;)try{var t=Dc();n=!1;let r=new AbortController;this.abortController=r;let i=[...this.queue];this.queue=[],this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),i.length>0&&await this.upsertMessages(i,e);let a=this.chat.messages;this.filterMessages&&(a=a.filter(this.filterMessages)),a=a.map(e=>({...e,parts:e.parts.map(e=>!ve(e)||e.input!==``?e:{...e,input:{}})})),t.u(await this.agent.agentLock.read());let o=performance.now(),s=await tm({agent:this.agent,id:this.chatId,signal:r.signal,messages:a}),c=async t=>{let n=t;if(this.serializeMessage){let e=this.serializeMessage(t);if(e===void 0)return;n=e}this.chat.updated_at=new Date().toISOString(),this.chat.messages.push(n),this.streamingMessage=void 0,await e?.set(this.chat)},l=s.getReader();r.signal.addEventListener(`abort`,()=>{l.cancel().catch(()=>{})},{once:!0});let u;try{for(;;){let{done:e,value:t}=await l.read();if(e||r.signal.aborted)break;u||=performance.now()-o,this.streamingMessage&&t.id!==this.streamingMessage.id&&await c(this.streamingMessage);let n={...t,metadata:{...typeof t.metadata==`object`&&t.metadata!==null?t.metadata:{},ttft:u}};this.streamingMessage=this.serializeMessage?this.serializeMessage(n):n,this.notifyListeners()}}finally{l.releaseLock()}this.streamingMessage&&await c(this.streamingMessage)}catch(e){t.e=e}finally{t.d()}}catch(e){let t=e instanceof Error?e.message:String(e);this.onError?.(t)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,this.status=`idle`,e&&(await this.flushLogQueue(e),this.chat.updated_at=new Date().toISOString(),await e.set(this.chat),await e.release(),this.notifyListeners())}}stopStreaming(){this.abortController?.abort()}clearQueue(){this.queue=[],this.notifyListeners()}async resetChat(){this.abortController?.abort(),this.resetChatState(),this.notifyListeners();let e;try{e=await this.chatStore.lock(this.chatId),await e.delete()}catch{}finally{if(e)try{await e.release()}catch{}}}dispose(){this.disposed=!0,this.watcher.dispose(),this.listeners.clear(),this.stopStreaming()}resetChatState(){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.streamingMessage=void 0,this.status=`idle`,this.queue=[],this.logQueue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};function sm(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a,onError:o}=e,s=U(null),[c,l]=W({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[],queuedLogs:[]});H(()=>{s.current&&s.current.dispose();let e=new om({chatId:t,chatsDirectory:r,serializeMessage:i,filterMessages:a,onError:o}),n=e.subscribe(e=>{l(e)});return l(e.getState()),s.current=e,()=>{n(),e.dispose(),s.current=null}},[t,r]),H(()=>{s.current&&s.current.setAgent(n)},[n]);let u=V(async e=>{s.current&&await s.current.sendMessages([e])},[]),d=V(async e=>{s.current&&await s.current.upsertMessages([e])},[]),f=V(async e=>{s.current&&await s.current.queueLogMessage(e)},[]),p=V(()=>{s.current&&s.current.stopStreaming()},[]),m=V(async()=>{s.current&&await s.current.resetChat()},[]),h=V(()=>{s.current&&s.current.clearQueue()},[]),g=V(async e=>{s.current&&await s.current.deleteMessages([e])},[]),_=V(async()=>{s.current&&await s.current.start()},[]);return{...c,sendMessage:u,upsertMessage:d,queueLogMessage:f,stopStreaming:p,resetChat:m,clearQueue:h,deleteMessage:g,start:_}}function cm(e){return de(e,`.blink`,`devhook.txt`)}function lm(e){return fe(cm(e))}function um(e){let t=cm(e);if(fe(t))return me(t,`utf-8`).trim()}function dm(e){let t=cm(e);if(pe(z(t),{recursive:!0}),fe(t))return me(t,`utf-8`);let n=crypto.randomUUID();return ge(t,n),n}const fm=(e,t)=>e.json({error:t},400),pm=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}},mm=()=>new f,hm=mm().get(`/:key`,async e=>{let{key:t,err:n}=pm(e);if(n)return fm(e,n);let r=await e.env.store.get(t);return e.json({value:r},200)}).post(`/:key`,O(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?fm(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:fm(t,`Value must be a string`):fm(t,`Value is required`)}),async e=>{let{key:t,err:n}=pm(e);if(n)return fm(e,n);let{value:r}=e.req.valid(`json`);return await e.env.store.set(t,r),e.body(null,204)}).delete(`/:key`,async e=>{let{key:t,err:n}=pm(e);return n?fm(e,n):(await e.env.store.delete(t),e.body(null,204))}).get(`/`,async e=>{let{cursor:t,limit:n,prefix:r}=e.req.query(),{entries:i,cursor:a}=await e.env.store.list(r,{cursor:t?String(t):void 0,limit:n?Number(n):100});return e.json({entries:i,cursor:a})}),gm=e=>{let t=e.req.param(`key`);return t?t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}:{key:t,err:`Key is required`}},_m=O(`param`,e=>({id:e.id})),vm=mm().post(`/:key`,async e=>{let{key:t,err:n}=gm(e);return n?fm(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,_m,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,_m,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.getMessages(t),200)}).post(`/:id/sendMessages`,O(`json`,e=>({id:e.id,messages:e.messages,options:e.options})),async e=>{let{id:t,messages:n,options:r}=e.req.valid(`json`);return t?(await e.env.chat.sendMessages(t,n,r),e.body(null,204)):fm(e,`ID is required`)}).delete(`/:id/messages`,_m,O(`query`,e=>(typeof e.message==`string`&&(e.message=[e.message]),{messages:e.message})),async e=>{let{id:t}=e.req.valid(`param`),{messages:n}=e.req.valid(`query`);return await e.env.chat.deleteMessages(t,n),e.body(null,204)}).post(`/:id/start`,_m,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,_m,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,_m,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),ym=mm().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),bm=new f().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,hm).route(`/chat`,vm).route(`/otlp`,ym);var xm=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function Sm(e){return typeof e==`string`&&xm.test(e)}var Cm=Sm;function wm(e){if(!Cm(e))throw TypeError(`Invalid UUID`);let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,t&255,(t=parseInt(e.slice(9,13),16))>>>8,t&255,(t=parseInt(e.slice(14,18),16))>>>8,t&255,(t=parseInt(e.slice(19,23),16))>>>8,t&255,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255)}var Tm=wm;const Em=[];for(let e=0;e<256;++e)Em.push((e+256).toString(16).slice(1));function Dm(e,t=0){return(Em[e[t+0]]+Em[e[t+1]]+Em[e[t+2]]+Em[e[t+3]]+`-`+Em[e[t+4]]+Em[e[t+5]]+`-`+Em[e[t+6]]+Em[e[t+7]]+`-`+Em[e[t+8]]+Em[e[t+9]]+`-`+Em[e[t+10]]+Em[e[t+11]]+Em[e[t+12]]+Em[e[t+13]]+Em[e[t+14]]+Em[e[t+15]]).toLowerCase()}function Om(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t}function km(e,t,n,r,i,a){let o=typeof n==`string`?Om(n):n,s=typeof r==`string`?Tm(r):r;if(typeof r==`string`&&(r=Tm(r)),r?.length!==16)throw TypeError(`Namespace must be array-like (16 iterable integer values, 0-255)`);let c=new Uint8Array(16+o.length);if(c.set(s),c.set(o,s.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,i){a||=0;for(let e=0;e<16;++e)i[a+e]=c[e];return i}return Dm(c)}function Am(e){return Array.isArray(e)?e=Buffer.from(e):typeof e==`string`&&(e=Buffer.from(e,`utf8`)),ce(`sha1`).update(e).digest()}var jm=Am;function Mm(e,t,n,r){return km(80,jm,e,t,n,r)}Mm.DNS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,Mm.URL=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;var Nm=Mm;function Pm(e){let t=ke(e.dataDirectory,`chats`),n={},r=ke(e.dataDirectory,`storage.json`);N.existsSync(r)&&(n=JSON.parse(N.readFileSync(r,`utf-8`)));let i=new Map,a=n=>{let r=i.get(n);return r||(r=new om({chatId:n,chatsDirectory:t}),i.set(n,r)),r.setAgent(e.getAgent()),r},o={async upsert(e){let t=Nm(JSON.stringify(e),Nm.URL),n=a(t).getState(),r=n.messages.length===0&&!n.created_at;return{id:n.id,created:r,createdAt:n.created_at??new Date().toISOString(),key:e}},async get(e){let t=a(e).getState();return{id:t.id,createdAt:t.created_at??new Date().toISOString()}},async getMessages(e){return a(e).getState().messages},async sendMessages(e,t,n){let r=a(e),i=t.map(e=>rm(e,`run`));if(n?.behavior===`append`){await r.upsertMessages(i);return}if(n?.behavior===`interrupt`){await r.sendMessages(i);return}await r.sendMessages(i)},async deleteMessages(e,t){await a(e).deleteMessages(t)},async start(e){await a(e).start()},async stop(e){await a(e).stop()},async delete(e){await a(e).resetChat()}},s={get(e){return Promise.resolve(n[e])},set(e,t){return n[e]=t,N.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},delete(e){return delete n[e],N.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},list(e,t){let r=Math.min(t?.limit??100,1e3),i=t?.cursor,a=Object.keys(n).filter(t=>t.startsWith(e??``)).sort(),o=0;if(i){let e=a.indexOf(i);e!==-1&&(o=e+1)}let s=a.slice(o,o+r),c=o+r<a.length?s[s.length-1]:void 0;return Promise.resolve({entries:s.map(e=>({key:e})),cursor:c})}},c=ue(w(e=>bm.fetch(e,{chat:o,store:s})));c.listen(e.port??0);let l=$p(t,`id`);return{url:`http://127.0.0.1:${c.address().port}`,chatsDirectory:t,getChatManager:a,listChats:()=>l.list(),dispose:()=>{for(let e of i.values())e.dispose();i.clear(),l.dispose(),c.close()}}}function Fm({agent:e,capabilities:t,messages:n}){let[r,i]=W(void 0),[a,o]=W(!0),[s,c]=W(void 0),l=U(s);H(()=>{l.current=s},[s]);let[u,d]=W(()=>E(n));H(()=>{d(e=>{let t=E(n);return JSON.stringify(t)===JSON.stringify(e)?e:t})},[n]);let[f,p]=W(void 0),m=V((e,t)=>{if(!l.current)return!1;let n=l.current[e];return n?n.values.some(e=>e.id===t):!1},[]),h=V(e=>{p(t=>{let n={...u,...t,...e};for(let[e,t]of Object.entries(n))m(e,t)||delete n[e];for(let[e,t]of Object.entries(l.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[u,m]);H(()=>{if(!u&&!s){p(void 0);return}h()},[u,s,h]);let g=U(void 0),_=U(void 0);H(()=>{e!==_.current&&(_.current=e,c(void 0),p(void 0),i(void 0),o(!0),g.current=void 0)},[e]),H(()=>{if(t&&!t.ui||!e){c(void 0),p(void 0),i(void 0),g.current=void 0;return}let n=f?JSON.stringify(f):``;if(g.current===n){o(!1),i(void 0);return}let r=new AbortController;return o(!0),i(void 0),e.ui(f?{selectedOptions:f}:{},{signal:r.signal}).then(e=>{if(!e){c(void 0);return}r.signal.aborted||(c(t=>JSON.stringify(t)===JSON.stringify(e)?t:e),g.current=n)}).catch(e=>{r.signal.aborted||i(e instanceof Error?e:Error(String(e)))}).finally(()=>{o(!1)}),()=>{r.abort()}},[e,t,f]);let v=V((e,t)=>{h({[e]:t})},[h]);return{schema:s,options:f,setOption:v,loading:a,error:r}}function Im(e){let t=U(e.onRequest);H(()=>{t.current=e.onRequest},[e.onRequest]);let[n,r]=W(`disconnected`);return H(()=>{if(e.disabled||!e.id){r(`disconnected`);return}let n=!1,i,a,o=!1,s,c=ke(e.directory,`.blink`,`devhook`);return(async()=>{try{s=await Kp(c,{stale:!0,retries:0})}catch(t){if(t&&typeof t==`object`&&`code`in t&&t.code===`ELOCKED`){let e=``;try{let t=Jp(c);t.locked&&t.pid&&(e=` (PID: ${t.pid})`)}catch{}console.error(cf.red(`\nError: Another ${cf.bold(`blink dev`)} process is already running in this directory${e}.`)),console.error(cf.red(`Please stop the other process and try again.
|
|
53
53
|
`)),process.exit(1)}let n=t&&typeof t==`object`&&`message`in t?String(t.message):String(t);e.logger.error(`system`,cf.yellow(`\nWarning: Failed to acquire devhook lock: ${n}`)),e.logger.error(`system`,cf.yellow(`Continuing without lock. Multiple ${cf.bold(`blink dev`)} processes may conflict with each other.\n`))}let l=()=>{if(!(n||o)){if(o=!0,i){try{i.dispose()}catch{}i=void 0}i=new ld({baseURL:`https://blink.so`}).devhook.listen({id:e.id,onRequest:async e=>t.current(e),onConnect:()=>{o=!1,r(`connected`)},onDisconnect:()=>{o=!1,r(`disconnected`),!n&&!a&&(a=setTimeout(()=>{a=void 0,l()},2e3))},onError:e=>{o=!1,r(`error`),!n&&!a&&(a=setTimeout(()=>{a=void 0,l()},2e3))}})}};l()})(),()=>{if(n=!0,a&&=(clearTimeout(a),void 0),i){try{i.dispose()}catch{}i=void 0}if(s)try{s()}catch(t){e.logger.error(`system`,`Failed to release devhook lock:`,t)}}},[e.disabled,e.directory]),{id:e.id,url:e.id?`https://${e.id}.blink.host`:void 0,status:n}}var Lm=e(((e,t)=>{t.exports={name:`dotenv`,version:`17.2.3`,description:`Loads environment variables from .env file`,main:`lib/main.js`,types:`lib/main.d.ts`,exports:{".":{types:`./lib/main.d.ts`,require:`./lib/main.js`,default:`./lib/main.js`},"./config":`./config.js`,"./config.js":`./config.js`,"./lib/env-options":`./lib/env-options.js`,"./lib/env-options.js":`./lib/env-options.js`,"./lib/cli-options":`./lib/cli-options.js`,"./lib/cli-options.js":`./lib/cli-options.js`,"./package.json":`./package.json`},scripts:{"dts-check":`tsc --project tests/types/tsconfig.json`,lint:`standard`,pretest:`npm run lint && npm run dts-check`,test:`tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000`,"test:coverage":`tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov`,prerelease:`npm test`,release:`standard-version`},repository:{type:`git`,url:`git://github.com/motdotla/dotenv.git`},homepage:`https://github.com/motdotla/dotenv#readme`,funding:`https://dotenvx.com`,keywords:[`dotenv`,`env`,`.env`,`environment`,`variables`,`config`,`settings`],readmeFilename:`README.md`,license:`BSD-2-Clause`,devDependencies:{"@types/node":`^18.11.3`,decache:`^4.6.2`,sinon:`^14.0.1`,standard:`^17.0.0`,"standard-version":`^9.5.0`,tap:`^19.2.0`,typescript:`^4.8.4`},engines:{node:`>=12`},browser:{fs:!1}}})),Rm=o(e(((e,t)=>{let n=i(`fs`),r=i(`path`),a=i(`os`),o=i(`crypto`),s=Lm().version,c=[`🔐 encrypt with Dotenvx: https://dotenvx.com`,`🔐 prevent committing .env to code: https://dotenvx.com/precommit`,`🔐 prevent building .env in docker: https://dotenvx.com/prebuild`,`📡 add observability to secrets: https://dotenvx.com/ops`,`👥 sync secrets across teammates & machines: https://dotenvx.com/ops`,`🗂️ backup and recover secrets: https://dotenvx.com/ops`,`✅ audit secrets and track compliance: https://dotenvx.com/ops`,`🔄 add secrets lifecycle management: https://dotenvx.com/ops`,`🔑 add access controls to secrets: https://dotenvx.com/ops`,"🛠️ run anywhere with `dotenvx run -- yourcommand`",`⚙️ specify custom .env file path with { path: '/custom/path/.env' }`,`⚙️ enable debug logging with { debug: true }`,`⚙️ override existing env vars with { override: true }`,`⚙️ suppress all logs with { quiet: true }`,`⚙️ write to custom object with { processEnv: myObject }`,`⚙️ load multiple .env files with { path: ['.env.local', '.env'] }`];function l(){return c[Math.floor(Math.random()*c.length)]}function u(e){return typeof e==`string`?![`false`,`0`,`no`,`off`,``].includes(e.toLowerCase()):!!e}function d(){return process.stdout.isTTY}function f(e){return d()?`\x1b[2m${e}\x1b[0m`:e}let p=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function m(e){let t={},n=e.toString();n=n.replace(/\r\n?/gm,`
|
|
54
54
|
`);let r;for(;(r=p.exec(n))!=null;){let e=r[1],n=r[2]||``;n=n.trim();let i=n[0];n=n.replace(/^(['"`])([\s\S]*)\1$/gm,`$2`),i===`"`&&(n=n.replace(/\\n/g,`
|
|
55
55
|
`),n=n.replace(/\\r/g,`\r`)),t[e]=n}return t}function h(e){e||={};let t=x(e);e.path=t;let n=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=y(e).split(`,`),i=r.length,a;for(let e=0;e<i;e++)try{let t=r[e].trim(),i=b(n,t);a=D.decrypt(i.ciphertext,i.key);break}catch(t){if(e+1>=i)throw t}return D.parse(a)}function g(e){console.error(`[dotenv@${s}][WARN] ${e}`)}function _(e){console.log(`[dotenv@${s}][DEBUG] ${e}`)}function v(e){console.log(`[dotenv@${s}] ${e}`)}function y(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:``}function b(e,t){let n;try{n=new URL(t)}catch(e){if(e.code===`ERR_INVALID_URL`){let e=Error(`INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development`);throw e.code=`INVALID_DOTENV_KEY`,e}throw e}let r=n.password;if(!r){let e=Error(`INVALID_DOTENV_KEY: Missing key part`);throw e.code=`INVALID_DOTENV_KEY`,e}let i=n.searchParams.get(`environment`);if(!i){let e=Error(`INVALID_DOTENV_KEY: Missing environment part`);throw e.code=`INVALID_DOTENV_KEY`,e}let a=`DOTENV_VAULT_${i.toUpperCase()}`,o=e.parsed[a];if(!o){let e=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${a} in your .env.vault file.`);throw e.code=`NOT_FOUND_DOTENV_ENVIRONMENT`,e}return{ciphertext:o,key:r}}function x(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let r of e.path)n.existsSync(r)&&(t=r.endsWith(`.vault`)?r:`${r}.vault`);else t=e.path.endsWith(`.vault`)?e.path:`${e.path}.vault`;else t=r.resolve(process.cwd(),`.env.vault`);return n.existsSync(t)?t:null}function S(e){return e[0]===`~`?r.join(a.homedir(),e.slice(1)):e}function C(e){let t=u(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=u(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(t||!n)&&v(`Loading env from encrypted .env.vault`);let r=D._parseVault(e),i=process.env;return e&&e.processEnv!=null&&(i=e.processEnv),D.populate(i,r,e),{parsed:r}}function w(e){let t=r.resolve(process.cwd(),`.env`),i=`utf8`,a=process.env;e&&e.processEnv!=null&&(a=e.processEnv);let o=u(a.DOTENV_CONFIG_DEBUG||e&&e.debug),s=u(a.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?i=e.encoding:o&&_(`No encoding is specified. UTF-8 is used by default`);let c=[t];if(e&&e.path)if(!Array.isArray(e.path))c=[S(e.path)];else{c=[];for(let t of e.path)c.push(S(t))}let d,p={};for(let t of c)try{let r=D.parse(n.readFileSync(t,{encoding:i}));D.populate(p,r,e)}catch(e){o&&_(`Failed to load ${t} ${e.message}`),d=e}let m=D.populate(a,p,e);if(o=u(a.DOTENV_CONFIG_DEBUG||o),s=u(a.DOTENV_CONFIG_QUIET||s),o||!s){let e=Object.keys(m).length,t=[];for(let e of c)try{let n=r.relative(process.cwd(),e);t.push(n)}catch(t){o&&_(`Failed to load ${e} ${t.message}`),d=t}v(`injecting env (${e}) from ${t.join(`,`)} ${f(`-- tip: ${l()}`)}`)}return d?{parsed:p,error:d}:{parsed:p}}function ee(e){if(y(e).length===0)return D.configDotenv(e);let t=x(e);return t?D._configVault(e):(g(`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),a=r.subarray(-16);r=r.subarray(12,-16);try{let e=o.createDecipheriv(`aes-256-gcm`,n,i);return e.setAuthTag(a),`${e.update(r)}${e.final()}`}catch(e){let t=e instanceof RangeError,n=e.message===`Invalid key length`,r=e.message===`Unsupported state or unable to authenticate data`;if(t||n){let e=Error(`INVALID_DOTENV_KEY: It must be 64 characters long (or more)`);throw e.code=`INVALID_DOTENV_KEY`,e}else if(r){let e=Error(`DECRYPTION_FAILED: Please check your DOTENV_KEY`);throw e.code=`DECRYPTION_FAILED`,e}else throw e}}function 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&&_(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:w,_configVault:C,_parseVault:h,config:ee,decrypt:T,parse:m,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}))());async function zm(e,t){let n=e;for(;n!==z(n);){let e=de(n,t);try{return await B(e),e}catch{}n=z(n)}}function Bm(e,t,n=`.env.local`){let[r,i]=W({});return H(()=>{let r,a=e=>{try{let t=me(e,`utf-8`),n=(0,Rm.parse)(t);i(n)}catch(e){t.error(`system`,`Error reading ${n}:`,e),i({})}};return zm(e,n).then(e=>{if(!e){i({});return}a(e),r=he(e,{persistent:!1},()=>{a(e)})}),()=>{r&&r.close()}},[e,n]),r}var Vm=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}else return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h){d[r]=void 0;continue}if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}};new class extends Vm{};function Hm(e,t){let n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function Um(e,t){let n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function Wm(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function Gm(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function Km(e,t){return Wm(e,t,``)}function qm(e,t){return Gm(e,t,``)}function Jm(e,t){return t.slice(0,Ym(e,t))}function Ym(e,t){let n=0;e.length>t.length&&(n=e.length-t.length);let r=t.length;e.length<t.length&&(r=e.length);let i=Array(r),a=0;i[0]=0;for(let e=1;e<r;e++){for(t[e]==t[a]?i[e]=i[a]:i[e]=a;a>0&&t[e]!=t[a];)a=i[a];t[e]==t[a]&&a++}a=0;for(let r=n;r<e.length;r++){for(;a>0&&e[r]!=t[a];)a=i[a];e[r]==t[a]&&a++}return a}function Xm(e){let t;for(t=e.length-1;t>=0&&e[t].match(/\s/);t--);return e.substring(t+1)}function Zm(e){let t=e.match(/^\s*/);return t?t[0]:``}const Qm=`a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,$m=RegExp(`[${Qm}]+|\\s+|[^${Qm}]`,`ug`);new class extends Vm{equals(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()}tokenize(e,t={}){let n;if(t.intlSegmenter){let r=t.intlSegmenter;if(r.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=Array.from(r.segment(e),e=>e.segment)}else n=e.match($m)||[];let r=[],i=null;return n.forEach(e=>{/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):i!=null&&/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r}join(e){return e.map((e,t)=>t==0?e:e.replace(/^\s+/,``)).join(``)}postProcess(e,t){if(!e||t.oneChangePerToken)return e;let n=null,r=null,i=null;return e.forEach(e=>{e.added?r=e:e.removed?i=e:((r||i)&&eh(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&eh(n,i,r,null),e}};function eh(e,t,n,r){if(t&&n){let i=Zm(t.value),a=Xm(t.value),o=Zm(n.value),s=Xm(n.value);if(e){let r=Hm(i,o);e.value=Gm(e.value,o,r),t.value=Km(t.value,r),n.value=Km(n.value,r)}if(r){let e=Um(a,s);r.value=Wm(r.value,s,e),t.value=qm(t.value,e),n.value=qm(n.value,e)}}else if(n){if(e){let e=Zm(n.value);n.value=n.value.substring(e.length)}if(r){let e=Zm(r.value);r.value=r.value.substring(e.length)}}else if(e&&r){let n=Zm(r.value),i=Zm(t.value),a=Xm(t.value),o=Hm(n,i);t.value=Km(t.value,o);let s=Um(Km(n,o),a);t.value=qm(t.value,s),r.value=Wm(r.value,n,s),e.value=Gm(e.value,n,n.slice(0,n.length-s.length))}else if(r){let e=Zm(r.value),n=Xm(t.value),i=Jm(n,e);t.value=qm(t.value,i)}else if(e){let n=Xm(e.value),r=Zm(t.value),i=Jm(n,r);t.value=Km(t.value,i)}}new class extends Vm{tokenize(e){let t=RegExp(`(\\r?\\n)|[${Qm}]+|[^\\S\\n\\r]+|[^${Qm}]`,`ug`);return e.match(t)||[]}};const th=new class extends Vm{constructor(){super(...arguments),this.tokenize=rh}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
|
|
@@ -1371,4 +1371,4 @@ Slack:
|
|
|
1371
1371
|
1. *ALWAYS* use the \`typecheck_agent\` tool to check for type errors before making changes. NEVER invoke \`tsc\` directly.
|
|
1372
1372
|
2. Use the \`message_user_agent\` tool to test the agent after you make changes.
|
|
1373
1373
|
</agent_development>
|
|
1374
|
-
`});let p=gh.scratch[`AGENTS.md`];try{p=await Se(de(e.directory,`AGENTS.md`),`utf-8`)}catch{}return f.unshift({role:`system`,content:p}),be({model:Oh(e.env),messages:f,maxOutputTokens:64e3,tools:d,abortSignal:a,experimental_repairToolCall:({tools:e,toolCall:t})=>{throw Object.keys(e).includes(t.toolName)?Error(`You have this tool, but you used an invalid input.`):Error(`Invalid tool call. Tool "${t.toolName}" is not available to the EDIT AGENT.`)}})}),{agent:t,setUserAgentUrl:e=>{n=e},cleanup:()=>{r&&=(r.close(),void 0)}}}function Dh(e){if(e.ANTHROPIC_API_KEY)return _n({apiKey:e.ANTHROPIC_API_KEY}).chat(`claude-sonnet-4-5`);if(e.OPENAI_API_KEY)return jo({apiKey:e.OPENAI_API_KEY}).chat(`gpt-5`);if(e.AI_GATEWAY_API_KEY)return C({apiKey:e.AI_GATEWAY_API_KEY})(`anthropic/claude-sonnet-4-5`)}function Oh(e){let t=Dh(e);if(!t)throw Error(`No API key available for edit mode`);return t}function kh(e){let[t,n]=W(void 0),[r,i]=W(void 0),[a,o]=W(!1),s=U(void 0);return H(()=>{let t=new AbortController,r=!1;if(i(void 0),n(void 0),!Dh(e.env)){o(!0);return}o(!1);let a;return(async()=>{s.current=Eh({directory:e.directory,env:e.env,getDevhookUrl:e.getDevhookUrl});let r=await Ah(),i=s.current.agent.serve({port:r,host:`127.0.0.1`,apiUrl:e.apiServerUrl});t.signal.addEventListener(`abort`,()=>{try{i.close()}catch{}s.current?.cleanup()});let o=new Ec({baseUrl:`http://127.0.0.1:${r}`});for(a=o.agentLock;!t.signal.aborted;){try{await o.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(t.signal.aborted)throw t.signal.reason;n(o)})().catch(e=>{r||i(e instanceof Error?e:Error(String(e)))}),()=>{r=!0,(async()=>{try{var e=Dc();e.u(await a?.write()),t.abort()}catch(t){e.e=t}finally{e.d()}})()}},[e.directory,e.apiServerUrl,e.env,e.getDevhookUrl]),Ee(()=>({client:t,error:r,missingApiKey:a,setUserAgentUrl:e=>{s.current?.setUserAgentUrl(e)}}),[t,r,a])}async function Ah(){let e=ue();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function jh(e){let{directory:t}=e,[n,r]=W(!1),[i,a]=W(`run`),o=U(`run`);H(()=>{o.current=i},[i]);let s=V(t=>{a(t),e.onModeChange?.(t)},[e.onModeChange]),c=V(()=>{s(i===`run`?`edit`:`run`)},[i,s]),{error:l,status:u,result:d,entry:f}=kp({directory:t,logger:e.logger,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),p=Tp({autoCheck:!0,onAuthChange:e.onAuthChange,onLoginUrl:e.onLoginUrl}),m=Bm(t,e.logger),h=Ee(()=>{let e=p.token;return e?{...m,BLINK_TOKEN:e}:m},[m,p.token]),g=U(void 0);H(()=>{let t=Object.keys(h);if(t.length===g.current||g.current===void 0){g.current=t.length;return}g.current=t.length,e.onEnvLoaded?.(t)},[h,e.onEnvLoaded]);let _=U(void 0),v=Ee(()=>Pm({port:0,dataDirectory:de(t,`.blink`),getAgent:()=>_.current}),[t]),{agent:y,logs:b,error:x,capabilities:S}=Oc({buildResult:d,env:h,apiServerUrl:v.url}),{client:C,error:w,missingApiKey:ee,setUserAgentUrl:E}=kh({directory:t,apiServerUrl:v.url,env:h,getDevhookUrl:V(()=>{let e=um(t)??dm(t);return N(e),`https://${e}.blink.host`},[t])}),[D,O]=W(`00000000-0000-0000-0000-000000000000`);H(()=>{_.current=y},[y]),H(()=>{y&&E(y.baseUrl),(i===`run`&&!y||i===`edit`&&!C)&&v.getChatManager(D)?.stopStreaming()},[y,C,i,D,v,E]);let k=U(void 0),A=sm({chatId:D,agent:i===`run`?y:C,chatsDirectory:v.chatsDirectory,serializeMessage:e=>{let t=e.role===`user`&&k.current?{...typeof e.metadata==`object`&&e.metadata!==null?e.metadata:{},options:k.current}:e.metadata;return typeof t==`object`&&t&&(t.__blink_mode=o.current),{id:e.id??crypto.randomUUID(),created_at:new Date().toISOString(),role:e.role,parts:e.parts,mode:o.current,metadata:t}},filterMessages:e=>o.current===`edit`?!0:!(im(e.metadata)||am(e)||e.mode===`edit`),onError:t=>{e.onError?.(`${cf.red(`⚙ [Chat Error]`)} ${cf.gray(t)}`)}}),j=U(0);H(()=>{if(b.length===j.current)return;let t=j.current;for(let n of b.slice(t))e.onAgentLog?.(n);j.current=b.length},[b,e.onAgentLog,A.upsertMessage]);let[M,te]=W([]);H(()=>{v.listChats().then(e=>{te(e.map(e=>e.key))})},[v]),H(()=>{D&&!M.includes(D)&&te(e=>[...e,D])},[D,M]);let[ne,N]=W(()=>lm(t)?um(t):dm(t)),P=Im({id:ne,directory:t,logger:e.logger,disabled:!S?.request,onRequest:async t=>{if(!y)throw Error(`No agent`);let n=new URL(t.url),r=new URL(y.baseUrl);r.pathname=n.pathname,r.search=n.search;try{let i=await fetch(r.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:`manual`,signal:t.signal,duplex:`half`});return e.onDevhookRequest?.({method:t.method,path:n.pathname,status:i.status}),i}catch(t){return e.logger.error(`system`,`Error sending request to user's agent:`,t),new Response(`Internal server error`,{status:500})}}});H(()=>{P.status!==`connected`||!P.url||e.onDevhookConnected?.(P.url)},[P.status,P.url]);let{schema:F,options:re,error:I,setOption:ie}=Fm({agent:i===`run`?y:C,capabilities:S,messages:A.messages});H(()=>{k.current=re},[re]);let L=Ee(()=>{let e=new Map;return x&&i===`run`&&e.set(`agent`,x.message),w&&i===`edit`&&e.set(`editAgent`,`Edit agent error: ${w.message}`),I&&e.set(`options`,`Options error: ${I.message}`),e},[x,w,I,i]),ae=U(new Map);H(()=>{let t=ae.current,n=L;for(let[r,i]of n.entries())t.get(r)!==i&&e.onError?.(i);for(let e of t.keys())n.has(e);ae.current=new Map(n)},[L,e.onError]);let R=Ee(()=>{let e=[...A.messages].reverse().find(e=>!(e.role!==`assistant`||e.metadata&&e.metadata.ephemeral));if(!e)return;let t=e.parts.filter(ve);if(t.length!==0&&t.some(e=>T(e.output)&&e.output.outcome===`pending`))return e},[A.messages]),oe=U(void 0),se=V(async(e,t)=>{if(!R)return;t&&e&&r(!0);let n=A.messages
|
|
1374
|
+
`});let p=gh.scratch[`AGENTS.md`];try{p=await Se(de(e.directory,`AGENTS.md`),`utf-8`)}catch{}return f.unshift({role:`system`,content:p}),be({model:Oh(e.env),messages:f,maxOutputTokens:64e3,tools:d,abortSignal:a,experimental_repairToolCall:({tools:e,toolCall:t})=>{throw Object.keys(e).includes(t.toolName)?Error(`You have this tool, but you used an invalid input.`):Error(`Invalid tool call. Tool "${t.toolName}" is not available to the EDIT AGENT.`)}})}),{agent:t,setUserAgentUrl:e=>{n=e},cleanup:()=>{r&&=(r.close(),void 0)}}}function Dh(e){if(e.ANTHROPIC_API_KEY)return _n({apiKey:e.ANTHROPIC_API_KEY}).chat(`claude-sonnet-4-5`);if(e.OPENAI_API_KEY)return jo({apiKey:e.OPENAI_API_KEY}).chat(`gpt-5`);if(e.AI_GATEWAY_API_KEY)return C({apiKey:e.AI_GATEWAY_API_KEY})(`anthropic/claude-sonnet-4-5`)}function Oh(e){let t=Dh(e);if(!t)throw Error(`No API key available for edit mode`);return t}function kh(e){let[t,n]=W(void 0),[r,i]=W(void 0),[a,o]=W(!1),s=U(void 0);return H(()=>{let t=new AbortController,r=!1;if(i(void 0),n(void 0),!Dh(e.env)){o(!0);return}o(!1);let a;return(async()=>{s.current=Eh({directory:e.directory,env:e.env,getDevhookUrl:e.getDevhookUrl});let r=await Ah(),i=s.current.agent.serve({port:r,host:`127.0.0.1`,apiUrl:e.apiServerUrl});t.signal.addEventListener(`abort`,()=>{try{i.close()}catch{}s.current?.cleanup()});let o=new Ec({baseUrl:`http://127.0.0.1:${r}`});for(a=o.agentLock;!t.signal.aborted;){try{await o.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(t.signal.aborted)throw t.signal.reason;n(o)})().catch(e=>{r||i(e instanceof Error?e:Error(String(e)))}),()=>{r=!0,(async()=>{try{var e=Dc();e.u(await a?.write()),t.abort()}catch(t){e.e=t}finally{e.d()}})()}},[e.directory,e.apiServerUrl,e.env,e.getDevhookUrl]),Ee(()=>({client:t,error:r,missingApiKey:a,setUserAgentUrl:e=>{s.current?.setUserAgentUrl(e)}}),[t,r,a])}async function Ah(){let e=ue();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function jh(e){let{directory:t}=e,[n,r]=W(!1),[i,a]=W(`run`),o=U(`run`);H(()=>{o.current=i},[i]);let s=V(t=>{a(t),e.onModeChange?.(t)},[e.onModeChange]),c=V(()=>{s(i===`run`?`edit`:`run`)},[i,s]),{error:l,status:u,result:d,entry:f}=kp({directory:t,logger:e.logger,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),p=Tp({autoCheck:!0,onAuthChange:e.onAuthChange,onLoginUrl:e.onLoginUrl}),m=Bm(t,e.logger),h=Ee(()=>{let e=p.token;return e?{...m,BLINK_TOKEN:e}:m},[m,p.token]),g=U(void 0);H(()=>{let t=Object.keys(h);if(t.length===g.current||g.current===void 0){g.current=t.length;return}g.current=t.length,e.onEnvLoaded?.(t)},[h,e.onEnvLoaded]);let _=U(void 0),v=Ee(()=>Pm({port:0,dataDirectory:de(t,`.blink`),getAgent:()=>_.current}),[t]),{agent:y,logs:b,error:x,capabilities:S}=Oc({buildResult:d,env:h,apiServerUrl:v.url}),{client:C,error:w,missingApiKey:ee,setUserAgentUrl:E}=kh({directory:t,apiServerUrl:v.url,env:h,getDevhookUrl:V(()=>{let e=um(t)??dm(t);return N(e),`https://${e}.blink.host`},[t])}),[D,O]=W(`00000000-0000-0000-0000-000000000000`);H(()=>{_.current=y},[y]),H(()=>{y&&E(y.baseUrl),(i===`run`&&!y||i===`edit`&&!C)&&v.getChatManager(D)?.stopStreaming()},[y,C,i,D,v,E]);let k=U(void 0),A=sm({chatId:D,agent:i===`run`?y:C,chatsDirectory:v.chatsDirectory,serializeMessage:e=>{let t=e.role===`user`&&k.current?{...typeof e.metadata==`object`&&e.metadata!==null?e.metadata:{},options:k.current}:e.metadata;return typeof t==`object`&&t&&(t.__blink_mode=o.current),{id:e.id??crypto.randomUUID(),created_at:new Date().toISOString(),role:e.role,parts:e.parts,mode:o.current,metadata:t}},filterMessages:e=>o.current===`edit`?!0:!(im(e.metadata)||am(e)||e.mode===`edit`),onError:t=>{e.onError?.(`${cf.red(`⚙ [Chat Error]`)} ${cf.gray(t)}`)}}),j=U(0);H(()=>{if(b.length===j.current)return;let t=j.current;for(let n of b.slice(t))e.onAgentLog?.(n);j.current=b.length},[b,e.onAgentLog,A.upsertMessage]);let[M,te]=W([]);H(()=>{v.listChats().then(e=>{te(e.map(e=>e.key))})},[v]),H(()=>{D&&!M.includes(D)&&te(e=>[...e,D])},[D,M]);let[ne,N]=W(()=>lm(t)?um(t):dm(t)),P=Im({id:ne,directory:t,logger:e.logger,disabled:!S?.request,onRequest:async t=>{if(!y)throw Error(`No agent`);let n=new URL(t.url),r=new URL(y.baseUrl);r.pathname=n.pathname,r.search=n.search;try{let i=await fetch(r.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:`manual`,signal:t.signal,duplex:`half`});return e.onDevhookRequest?.({method:t.method,path:n.pathname,status:i.status}),i}catch(t){return e.logger.error(`system`,`Error sending request to user's agent:`,t),new Response(`Internal server error`,{status:500})}}});H(()=>{P.status!==`connected`||!P.url||e.onDevhookConnected?.(P.url)},[P.status,P.url]);let{schema:F,options:re,error:I,setOption:ie}=Fm({agent:i===`run`?y:C,capabilities:S,messages:A.messages});H(()=>{k.current=re},[re]);let L=Ee(()=>{let e=new Map;return x&&i===`run`&&e.set(`agent`,x.message),w&&i===`edit`&&e.set(`editAgent`,`Edit agent error: ${w.message}`),I&&e.set(`options`,`Options error: ${I.message}`),e},[x,w,I,i]),ae=U(new Map);H(()=>{let t=ae.current,n=L;for(let[r,i]of n.entries())t.get(r)!==i&&e.onError?.(i);for(let e of t.keys())n.has(e);ae.current=new Map(n)},[L,e.onError]);let R=Ee(()=>{let e=[...A.messages].reverse().find(e=>!(e.role!==`assistant`||e.metadata&&e.metadata.ephemeral));if(!e)return;let t=e.parts.filter(ve);if(t.length!==0&&t.some(e=>T(e.output)&&e.output.outcome===`pending`))return e},[A.messages]),oe=U(void 0),se=V(async(e,t)=>{if(!R)return;t&&e&&r(!0);let n=A.messages.reverse().find(e=>e.role!==`assistant`||!Array.isArray(e.parts)?!1:e.parts.some(e=>`output`in e&&T(e.output)&&e.output.outcome===`pending`));if(!n)return;oe.current=n.id;let i=n.parts.map(t=>t.output&&T(t.output)&&t.output.outcome===`pending`?{...t,output:{...t.output,outcome:e?`approved`:`rejected`}}:t);await A.upsertMessage({...n,parts:i}),await A.start()},[R,A]);H(()=>{n&&R&&se(!0)},[n,R,se]);let ce=V(()=>{let e=crypto.randomUUID();O(e),te(t=>[...t,e])},[]),le=V(e=>{O(e)},[]),ue=Ee(()=>{if(R)return{message:R,approve:e=>se(!0,e),reject:()=>se(!1),autoApproveEnabled:n}},[R,se,n]),z=Ee(()=>{let e=A.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}}},[A.messages]),fe=Ee(()=>{if(A.status!==`streaming`)return!1;if(!A.streamingMessage)return!0;let e=A.streamingMessage.parts.filter(ve);return e.length>0&&e.every(e=>e.state.startsWith(`output-`))},[A.status,A.streamingMessage]);return{mode:i,setMode:s,toggleMode:c,chat:A,chats:M,switchChat:le,newChat:ce,build:{status:u,error:l,entrypoint:f},devhook:{connected:P.status===`connected`,url:P.status===`connected`?P.url:void 0},capabilities:S,options:{schema:F,selected:re,error:I,setOption:ie},approval:ue,tokenUsage:z,auth:p,server:v,showWaitingPlaceholder:fe,editModeMissingApiKey:ee}}export{Dp as Logger,Op as LoggerContext,Oc as useAgent,Tp as useAuth,kp as useBundler,sm as useChat,jh as useDevMode,Im as useDevhook,Bm as useDotenv,kh as useEditAgent,Fm as useOptions};
|