blink 1.1.21 → 1.1.23
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.
- package/dist/cli/{auth-BilZuH-1.js → auth-DbpOUCTO.js} +1 -1
- package/dist/cli/{chat-manager-DfVg04yc.js → chat-manager-GWR_v50X.js} +1 -1
- package/dist/cli/{dev-DRWR8F1H.js → dev-DwwSnzeH.js} +9 -9
- package/dist/cli/index.js +9 -9
- package/dist/cli/{init-BuMKmaaZ.js → init-em410TZP.js} +8 -8
- package/dist/cli/{init-templates-B9PG-9Ei.js → init-templates-By3gx42M.js} +4 -2
- package/dist/cli/login-BDP8JC4X.js +1 -0
- package/dist/cli/{run-DF1dwAY_.js → run-CZZ6WAdr.js} +1 -1
- package/dist/node/react/index.node.cjs +6 -4
- package/dist/node/react/index.node.d.cts +9 -2
- package/dist/node/react/index.node.d.ts +9 -2
- package/dist/node/react/index.node.js +6 -4
- package/package.json +1 -1
- package/dist/cli/login-Bbj133_1.js +0 -1
|
@@ -49,7 +49,7 @@ ${Tf}`),t.includes(`
|
|
|
49
49
|
`)&&(n=3+oe(t.slice(t.lastIndexOf(`
|
|
50
50
|
`))).length);let e=oe(t).length;n+e<process.stdout.columns?(n+=e,process.stdout.write(t)):(process.stdout.write(`
|
|
51
51
|
${Tf}${t.trimStart()}`),n=3+oe(t.trimStart()).length)}process.stdout.write(`
|
|
52
|
-
`)},info:e=>Ef.message(e,{symbol:mf.default.blue(bf)}),success:e=>Ef.message(e,{symbol:mf.default.green(xf)}),step:e=>Ef.message(e,{symbol:mf.default.green(vf)}),warn:e=>Ef.message(e,{symbol:mf.default.yellow(Sf)}),warning:e=>Ef.warn(e),error:e=>Ef.message(e,{symbol:mf.default.red(Cf)})};let Df;function Of(){try{return ne.statSync(`/.dockerenv`),!0}catch{return!1}}function kf(){try{return ne.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function Af(){return Df===void 0&&(Df=Of()||kf()),Df}let jf;const Mf=()=>{try{return ne.statSync(`/run/.containerenv`),!0}catch{return!1}};function Nf(){return jf===void 0&&(jf=Mf()||Af()),jf}const Pf=()=>{if(J.platform!==`linux`)return!1;if(je.release().toLowerCase().includes(`microsoft`))return!Nf();try{return ne.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!Nf():!1}catch{return!1}};var Ff=J.env.__IS_WSL_TEST__?Pf:Pf();const If=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await Le.access(n,Re.F_OK),r=!0}catch{}if(!r)return e;let i=await Le.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}})(),Lf=async()=>`${await If()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Rf=async()=>Ff?Lf():`${J.env.SYSTEMROOT||J.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function zf(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 Bf=ae(Ie);async function Vf(){if(J.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await Bf(`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 Hf=ae(Ie);async function Uf(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 Hf(`osascript`,[`-e`,e,r],i);return a.trim()}async function Wf(e){return Uf(`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 Gf=ae(Ie),Kf={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 qf=class extends Error{};async function Jf(e=Gf){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 qf(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=Kf[r];if(!i)throw new qf(`Unknown browser ID: ${r}`);return i}const Yf=ae(Ie),Xf=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function Zf(){if(J.platform===`darwin`){let e=await Vf();return{name:await Wf(e),id:e}}if(J.platform===`linux`){let{stdout:e}=await Yf(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:Xf(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(J.platform===`win32`)return Jf();throw Error(`Only macOS, Linux, and Windows are supported`)}const Qf=ae(Fe.execFile),$f=Ee.dirname(ie(import.meta.url)),ep=Ee.join($f,`xdg-open`),{platform:tp,arch:np}=J;async function rp(){let e=await Rf(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=te.from(t,`utf16le`).toString(`base64`),{stdout:r}=await Qf(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 ip=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},ap=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return ip(e.app,t=>ap({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return ip(t,t=>ap({...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=Ff?await rp():await Zf();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),ap({...e,app:{name:lp[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,i=[],a={};if(tp===`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(tp===`win32`||Ff&&!Nf()&&!t){r=await Rf(),i.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),Ff||(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=te.from(o.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!$f||$f===`/`,t=!1;try{await Le.access(ep,Re.X_OK),t=!0}catch{}r=J.versions.electron??(tp===`android`||e||!t)?`xdg-open`:ep}n.length>0&&i.push(...n),e.wait||(a.stdio=`ignore`,a.detached=!0)}tp===`darwin`&&n.length>0&&i.push(`--args`,...n),e.target&&i.push(e.target);let o=Fe.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)},op=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return ap({...t,target:e})};function sp(e){if(typeof e==`string`||Array.isArray(e))return e;let{[np]:t}=e;if(!t)throw Error(`${np} is not supported`);return t}function cp({[tp]:e},{wsl:t}){if(t&&Ff)return sp(t);if(!e)throw Error(`${tp} is not supported`);return sp(e)}const lp={};zf(lp,`chrome`,()=>cp({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`]}})),zf(lp,`brave`,()=>cp({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`]}})),zf(lp,`firefox`,()=>cp({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),zf(lp,`edge`,()=>cp({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),zf(lp,`browser`,()=>`browser`),zf(lp,`browserPrivate`,()=>`browserPrivate`);var up=op;async function dp(e,t=void 0){try{(await up(e)).once(`error`,n=>{console.log(Zd.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))})}catch{console.log(Zd.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))}}function fp(e){let t=e||hp();if(F(t)){let e=L(t,`utf8`);return JSON.parse(e).token}}function pp(e,t){let n=t||hp();F(De(n))||I(De(n),{recursive:!0}),R(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function mp(e){let t=e||hp();F(t)&&re(t)}function hp(){let e=vd(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return Oe(e[0],`auth.json`)}function gp(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=G(),[s,c]=G(()=>fp(i)),[l,u]=G(),d=W(n),f=W(r);U(()=>{d.current=n,f.current=r},[n,r]);let p=H(async()=>{u(void 0);try{let e=fp(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new ed({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=H(async()=>{u(void 0);try{let e=new ed,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();pp(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=H(()=>{mp(i),c(void 0),o(void 0),u(void 0),d.current?.(void 0)},[i]);return U(()=>{t&&p()},[t,p]),{user:a,token:s,error:l,login:m,logout:h}}function _p(e){let{directory:t,onBuildStart:n,onBuildSuccess:r,onBuildError:i}=typeof e==`string`?{directory:e}:e,a=we(()=>A(t),[t]),[o,s]=G(void 0),[c,l]=G(void 0),[u,d]=G(`building`),f=W(n),p=W(r),m=W(i);return U(()=>{f.current=n,p.current=r,m.current=i},[n,r,i]),U(()=>{let e=new AbortController;return a.build({cwd:t,entry:a.entry,outdir:a.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{d(`building`),s(void 0),l(void 0),f.current?.()},onResult:e=>{`error`in e?(s(e.error),d(`error`),m.current?.(e.error)):(l(e),d(`success`),p.current?.(e))}}).catch(e=>{console.log(`error`,e),d(`error`),s(e),m.current?.(e)}),()=>{e.abort()}},[t]),we(()=>({error:o,status:u,result:c,entry:a.entry,outdir:a.outdir}),[o,u,c,a.entry,a.outdir])}function vp(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function yp(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const bp=/^\.+(\\|\/)|^\.+$/,xp=/[. ]+$/,Sp=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,Cp=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,wp=e=>e===``,Tp=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,Ep=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let Dp;function Op(){return Dp??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),Dp}function kp(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(vp().test(n)||[...n].some(e=>Cp.test(e)&&!wp(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(Ep,` `),n.length>0&&(e=e.replaceAll(Tp,`$1`)),e=e.replace(xp,``),e=e.replace(bp,n),e=e.replace(vp(),n),e=e.replaceAll(Sp,e=>wp(e)?e:n),e.length===0&&(e=n),e=yp().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=Ap(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=Ap(n,a)+i}}return e}function Ap(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of Op().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function jp(e){return`${e}.lock`}function Mp(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function Np(e,t={}){let n=jp(e),r=process.pid.toString();try{return P.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(P.readFileSync(n,`utf8`),10)}catch{return P.unlinkSync(n),Np(e,{...t,stale:0})}if(!Mp(i))try{return P.unlinkSync(n),Np(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return Np(e,{...t,stale:0});throw n}return!1}}async function Pp(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=Te.resolve(e),i=0;for(;i<=n.retries;){if(Np(r,n))return()=>Fp(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 Fp(e){let t=Te.resolve(e),n=jp(t);try{if(parseInt(P.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}P.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function Ip(e){let t=Te.resolve(e),n=jp(t);try{if(!P.existsSync(n))return{locked:!1};let e=P.readFileSync(n,`utf8`),t=parseInt(e,10);return Mp(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const Lp=e=>{P.mkdirSync(e,{recursive:!0})},Rp=e=>{try{P.fdatasyncSync(e)}catch{}try{P.closeSync(e)}catch{}},zp=e=>{try{let t=P.openSync(e,`r`);try{P.fsyncSync(t)}finally{P.closeSync(t)}}catch{}},Bp=(e,t)=>{let n=Te.dirname(e);Lp(n);let r=Te.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=P.openSync(r,`w`),P.writeFileSync(i,t,`utf-8`),Rp(i),i=void 0,P.renameSync(r,e),zp(e),zp(n)}catch(e){if(i!==void 0)try{P.closeSync(i)}catch{}try{P.rmSync(r,{force:!0})}catch{}throw e}},Vp=(e,t)=>{let n=new Map,r,i=e=>{if(P.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(P.readFileSync(e,`utf-8`))},a=(e,t)=>{Bp(e,JSON.stringify(t,null,2))},o=async()=>{if(r)throw Error(`Index is already locked`);let t=Te.join(e,`index.json`);Lp(e),P.existsSync(t)||P.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await Pp(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},s=async()=>{let t=Te.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},c=async t=>{let n=Te.join(e,`index.json`);a(n,t)},l=async t=>{let n=(await s()).ids[t];if(n)return Te.join(e,n)},u=async t=>{let n=(await s()).ids[t];if(!n)return;let r=Te.join(e,n);if(P.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(P.readFileSync(r,`utf-8`))},d=async n=>{let r=n[t],i=String(r),l=kp(i,{replacement:`_`})+`.json`,u=await o();try{let t=await s();t.ids[i]=l,t.current=i;let r=Te.join(e,l);a(r,n),await c(t)}finally{await u()}};return{async get(e){return await u(e)},async list(){if(!P.statSync(e,{throwIfNoEntry:!1}))return[];let t=await s(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=Te.join(e,i),a=P.statSync(t,{throwIfNoEntry:!1});if(!a)continue;let o=Ip(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=kp(r,{replacement:`_`})+`.json`,n=await o();try{let n=await s();n.ids[r]=t;let i=Te.join(e,t);Lp(e),P.writeFileSync(i,JSON.stringify({}),`utf-8`),await c(n),a=i}finally{await n()}}if(i?.force){let e=Ip(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 Pp(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=Te.join(e,n);try{P.rmSync(i,{force:!0}),zp(e)}catch{}}}finally{await t()}},async release(){try{f()}finally{n.delete(r)}}}},dispose(){n.clear()}}},Hp=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,a,o,s=new Map,c=new Map,l=Te.join(e,`index.json`),u=()=>{try{if(!P.statSync(l,{throwIfNoEntry:!1}))return{ids:{}};let e=P.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=Te.join(e,n);try{let e=P.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=Ip(i)),!a||a.mtime!==o||a.locked!==s.locked||a.pid!==s.pid){let e;e=!a||a.mtime!==o?JSON.parse(P.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{P.mkdirSync(e,{recursive:!0})}catch{}a=P.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 Up({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=Wp}){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=ve({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 Wp=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(_e);return n.length===0||n.some(e=>E(e.output)&&e.output.outcome===`pending`)?!1:n.every(e=>e.state.startsWith(`output-`))},Gp=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function Kp(e){return typeof e==`object`&&e?.__blink_internal!==void 0}var qp=class{chatId;agent;chatStore;serializeMessage;filterMessages;chat;loading=!1;streamingMessage;status=`idle`;queue=[];abortController;isProcessingQueue=!1;listeners=new Set;watcher;disposed=!1;constructor(e){this.chatId=e.chatId??`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=Vp(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.watcher=Hp(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.value?.error?`error`:`idle`;e.locked&&(n=`streaming`);let r=this.chat.updated_at!==t?.updated_at||this.status!==n;this.chat={...t,error:void 0},this.streamingMessage=void 0,this.status=n,r&&this.notifyListeners()}),this.chatStore.get(this.chatId).then(e=>{this.disposed||e&&(this.chat={...e,error:void 0})}).catch(e=>{this.chat.error=e instanceof Error?e.message:String(e)}).finally(()=>{this.loading=!1,this.notifyListeners()})}setAgent(e){this.agent=e}getState(){return{id:this.chatId,key:this.chat?.key,messages:(this.chat?.messages??[]).filter(e=>!Kp(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,error:this.chat?.error,loading:this.loading,queuedMessages:this.queue}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async 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 sendMessages(e){if(this.chat.error){let e=await this.chatStore.lock(this.chatId);try{this.chat={...await e.get(),error:void 0,updated_at:new Date().toISOString()},await e.set(this.chat)}finally{await e.release()}}if(this.status=`idle`,this.notifyListeners(),this.isProcessingQueue){this.queue.push(...e),this.notifyListeners();return}this.queue=e,this.processQueueOrRun()}async start(){this.chat.error=void 0,this.status=`idle`,this.notifyListeners(),this.processQueueOrRun()}async stop(){this.status=`idle`,this.abortController?.abort(),this.notifyListeners()}async processQueueOrRun(){if(!this.agent){this.chat.error=`The agent is not available. Please wait for the build to succeed.`,this.status=`error`,this.queue=[],this.notifyListeners();return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0,this.chat.error=void 0;let e;try{e=await this.chatStore.lock(this.chatId);let t=!0;for(;this.queue.length>0||t;){t=!1;let n=new AbortController;this.abortController=n;let r=[...this.queue];this.queue=[],this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),r.length>0&&await this.upsertMessages(r,e);let i=this.chat.messages;this.filterMessages&&(i=i.filter(this.filterMessages)),i=i.map(e=>({...e,parts:e.parts.map(e=>!_e(e)||e.input!==``?e:{...e,input:{}})}));let a=performance.now(),o=await Up({agent:this.agent,id:this.chatId,signal:n.signal,messages:i}),s=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)},c=o.getReader();n.signal.addEventListener(`abort`,()=>{c.cancel().catch(()=>{})},{once:!0});let l;try{for(;;){let{done:e,value:t}=await c.read();if(e||n.signal.aborted)break;l||=performance.now()-a,this.streamingMessage&&t.id!==this.streamingMessage.id&&await s(this.streamingMessage);let r={...t,metadata:{...typeof t.metadata==`object`&&t.metadata!==null?t.metadata:{},ttft:l}};this.streamingMessage=this.serializeMessage?this.serializeMessage(r):r,this.notifyListeners()}}finally{c.releaseLock()}this.streamingMessage&&await s(this.streamingMessage)}}catch(e){this.chat.error=e instanceof Error?e.message:String(e)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,this.chat.error?this.status=`error`:this.status=`idle`,e&&(this.chat.updated_at=new Date().toISOString(),await e.set(this.chat),await e.release(),this.notifyListeners())}}stopStreaming(){this.abortController?.abort()}clearQueue(){this.queue=[],this.notifyListeners()}async resetChat(){this.abortController?.abort(),this.resetChatState(),this.notifyListeners();let e;try{e=await this.chatStore.lock(this.chatId),await e.delete()}catch{}finally{if(e)try{await e.release()}catch{}}}dispose(){this.disposed=!0,this.watcher.dispose(),this.listeners.clear(),this.abortController?.abort()}resetChatState(){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.streamingMessage=void 0,this.status=`idle`,this.queue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};function Jp(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a}=e,o=W(null),[s,c]=G({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[]});U(()=>{o.current&&o.current.dispose();let e=new qp({chatId:t,chatsDirectory:r,serializeMessage:i,filterMessages:a}),n=e.subscribe(e=>{c(e)});return c(e.getState()),o.current=e,()=>{n(),e.dispose(),o.current=null}},[t,r]),U(()=>{o.current&&o.current.setAgent(n)},[n]);let l=H(async e=>{o.current&&await o.current.sendMessages([e])},[]),u=H(async e=>{o.current&&await o.current.upsertMessages([e])},[]),d=H(()=>{o.current&&o.current.stopStreaming()},[]),f=H(async()=>{o.current&&await o.current.resetChat()},[]),p=H(()=>{o.current&&o.current.clearQueue()},[]),m=H(async e=>{o.current&&await o.current.deleteMessages([e])},[]),h=H(async()=>{o.current&&await o.current.start()},[]);return{...s,sendMessage:l,upsertMessage:u,stopStreaming:d,resetChat:f,clearQueue:p,deleteMessage:m,start:h}}function Yp(e){return ue(e,`.blink`,`devhook.txt`)}function Xp(e){return de(Yp(e))}function Zp(e){let t=Yp(e);if(de(t))return pe(t,`utf-8`).trim()}function Qp(e){let t=Yp(e);if(fe(B(t),{recursive:!0}),de(t))return pe(t,`utf-8`);let n=crypto.randomUUID();return he(t,n),n}const $p=(e,t)=>e.json({error:t},400),em=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}},tm=()=>new f,nm=tm().get(`/:key`,async e=>{let{key:t,err:n}=em(e);if(n)return $p(e,n);let r=await e.env.store.get(t);return e.json({value:r},200)}).post(`/:key`,k(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?$p(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:$p(t,`Value must be a string`):$p(t,`Value is required`)}),async e=>{let{key:t,err:n}=em(e);if(n)return $p(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}=em(e);return n?$p(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})}),rm=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`}},im=k(`param`,e=>({id:e.id})),am=tm().post(`/:key`,async e=>{let{key:t,err:n}=rm(e);return n?$p(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,im,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,im,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.getMessages(t),200)}).post(`/:id/sendMessages`,k(`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)):$p(e,`ID is required`)}).delete(`/:id/messages`,im,k(`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`,im,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,im,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,im,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),om=tm().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),sm=new f().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,nm).route(`/chat`,am).route(`/otlp`,om);var cm=/^(?:[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 lm(e){return typeof e==`string`&&cm.test(e)}var um=lm;function dm(e){if(!um(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 fm=dm;const pm=[];for(let e=0;e<256;++e)pm.push((e+256).toString(16).slice(1));function mm(e,t=0){return(pm[e[t+0]]+pm[e[t+1]]+pm[e[t+2]]+pm[e[t+3]]+`-`+pm[e[t+4]]+pm[e[t+5]]+`-`+pm[e[t+6]]+pm[e[t+7]]+`-`+pm[e[t+8]]+pm[e[t+9]]+`-`+pm[e[t+10]]+pm[e[t+11]]+pm[e[t+12]]+pm[e[t+13]]+pm[e[t+14]]+pm[e[t+15]]).toLowerCase()}function hm(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 gm(e,t,n,r,i,a){let o=typeof n==`string`?hm(n):n,s=typeof r==`string`?fm(r):r;if(typeof r==`string`&&(r=fm(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 mm(c)}function _m(e){return Array.isArray(e)?e=Buffer.from(e):typeof e==`string`&&(e=Buffer.from(e,`utf8`)),se(`sha1`).update(e).digest()}var vm=_m;function ym(e,t,n,r){return gm(80,vm,e,t,n,r)}ym.DNS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,ym.URL=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;var bm=ym;function xm(e){let t=Oe(e.dataDirectory,`chats`),n={},r=Oe(e.dataDirectory,`storage.json`);P.existsSync(r)&&(n=JSON.parse(P.readFileSync(r,`utf-8`)));let i=new Map,a=n=>{let r=i.get(n);return r||(r=new qp({chatId:n,chatsDirectory:t}),i.set(n,r)),r.setAgent(e.getAgent()),r},o={async upsert(e){let t=bm(JSON.stringify(e),bm.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=>Gp(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,P.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},delete(e){return delete n[e],P.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=le(w(e=>sm.fetch(e,{chat:o,store:s})));c.listen(e.port??0);let l=Vp(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 Sm({agent:e,capabilities:t,messages:n}){let[r,i]=G(void 0),[a,o]=G(!0),[s,c]=G(void 0),l=W(s);U(()=>{l.current=s},[s]);let[u,d]=G(()=>D(n));U(()=>{d(e=>{let t=D(n);return JSON.stringify(t)===JSON.stringify(e)?e:t})},[n]);let[f,p]=G(void 0),m=H((e,t)=>{if(!l.current)return!1;let n=l.current[e];return n?n.values.some(e=>e.id===t):!1},[]),h=H(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]);U(()=>{if(!u&&!s){p(void 0);return}h()},[u,s,h]);let g=W(void 0),_=W(void 0);U(()=>{e!==_.current&&(_.current=e,c(void 0),p(void 0),i(void 0),o(!0),g.current=void 0)},[e]),U(()=>{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=H((e,t)=>{h({[e]:t})},[h]);return{schema:s,options:f,setOption:v,loading:a,error:r}}function Cm(e){let t=W(e.onRequest);U(()=>{t.current=e.onRequest},[e.onRequest]);let[n,r]=G(`disconnected`);return U(()=>{if(e.disabled||!e.id){r(`disconnected`);return}let n=!1,i,a,o=!1,s,c=Oe(e.directory,`.blink`,`devhook`);return(async()=>{try{s=await Pp(c,{stale:!0,retries:0})}catch(e){if(e&&typeof e==`object`&&`code`in e&&e.code===`ELOCKED`){let e=``;try{let t=Ip(c);t.locked&&t.pid&&(e=` (PID: ${t.pid})`)}catch{}console.error(Zd.red(`\nError: Another ${Zd.bold(`blink dev`)} process is already running in this directory${e}.`)),console.error(Zd.red(`Please stop the other process and try again.
|
|
52
|
+
`)},info:e=>Ef.message(e,{symbol:mf.default.blue(bf)}),success:e=>Ef.message(e,{symbol:mf.default.green(xf)}),step:e=>Ef.message(e,{symbol:mf.default.green(vf)}),warn:e=>Ef.message(e,{symbol:mf.default.yellow(Sf)}),warning:e=>Ef.warn(e),error:e=>Ef.message(e,{symbol:mf.default.red(Cf)})};let Df;function Of(){try{return ne.statSync(`/.dockerenv`),!0}catch{return!1}}function kf(){try{return ne.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function Af(){return Df===void 0&&(Df=Of()||kf()),Df}let jf;const Mf=()=>{try{return ne.statSync(`/run/.containerenv`),!0}catch{return!1}};function Nf(){return jf===void 0&&(jf=Mf()||Af()),jf}const Pf=()=>{if(J.platform!==`linux`)return!1;if(je.release().toLowerCase().includes(`microsoft`))return!Nf();try{return ne.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!Nf():!1}catch{return!1}};var Ff=J.env.__IS_WSL_TEST__?Pf:Pf();const If=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await Le.access(n,Re.F_OK),r=!0}catch{}if(!r)return e;let i=await Le.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}})(),Lf=async()=>`${await If()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Rf=async()=>Ff?Lf():`${J.env.SYSTEMROOT||J.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function zf(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 Bf=ae(Ie);async function Vf(){if(J.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await Bf(`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 Hf=ae(Ie);async function Uf(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 Hf(`osascript`,[`-e`,e,r],i);return a.trim()}async function Wf(e){return Uf(`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 Gf=ae(Ie),Kf={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 qf=class extends Error{};async function Jf(e=Gf){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 qf(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=Kf[r];if(!i)throw new qf(`Unknown browser ID: ${r}`);return i}const Yf=ae(Ie),Xf=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function Zf(){if(J.platform===`darwin`){let e=await Vf();return{name:await Wf(e),id:e}}if(J.platform===`linux`){let{stdout:e}=await Yf(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:Xf(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(J.platform===`win32`)return Jf();throw Error(`Only macOS, Linux, and Windows are supported`)}const Qf=ae(Fe.execFile),$f=Ee.dirname(ie(import.meta.url)),ep=Ee.join($f,`xdg-open`),{platform:tp,arch:np}=J;async function rp(){let e=await Rf(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=te.from(t,`utf16le`).toString(`base64`),{stdout:r}=await Qf(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 ip=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},ap=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return ip(e.app,t=>ap({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return ip(t,t=>ap({...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=Ff?await rp():await Zf();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),ap({...e,app:{name:lp[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,i=[],a={};if(tp===`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(tp===`win32`||Ff&&!Nf()&&!t){r=await Rf(),i.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),Ff||(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=te.from(o.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!$f||$f===`/`,t=!1;try{await Le.access(ep,Re.X_OK),t=!0}catch{}r=J.versions.electron??(tp===`android`||e||!t)?`xdg-open`:ep}n.length>0&&i.push(...n),e.wait||(a.stdio=`ignore`,a.detached=!0)}tp===`darwin`&&n.length>0&&i.push(`--args`,...n),e.target&&i.push(e.target);let o=Fe.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)},op=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return ap({...t,target:e})};function sp(e){if(typeof e==`string`||Array.isArray(e))return e;let{[np]:t}=e;if(!t)throw Error(`${np} is not supported`);return t}function cp({[tp]:e},{wsl:t}){if(t&&Ff)return sp(t);if(!e)throw Error(`${tp} is not supported`);return sp(e)}const lp={};zf(lp,`chrome`,()=>cp({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`]}})),zf(lp,`brave`,()=>cp({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`]}})),zf(lp,`firefox`,()=>cp({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),zf(lp,`edge`,()=>cp({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),zf(lp,`browser`,()=>`browser`),zf(lp,`browserPrivate`,()=>`browserPrivate`);var up=op;async function dp(e,t=void 0){try{(await up(e)).once(`error`,n=>{console.log(Zd.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))})}catch{console.log(Zd.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))}}function fp(e){let t=e||hp();if(F(t)){let e=L(t,`utf8`);return JSON.parse(e).token}}function pp(e,t){let n=t||hp();F(De(n))||I(De(n),{recursive:!0}),R(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function mp(e){let t=e||hp();F(t)&&re(t)}function hp(){let e=vd(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return Oe(e[0],`auth.json`)}function gp(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=G(),[s,c]=G(()=>fp(i)),[l,u]=G(),d=W(n),f=W(r);U(()=>{d.current=n,f.current=r},[n,r]);let p=H(async()=>{u(void 0);try{let e=fp(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new ed({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=H(async()=>{u(void 0);try{let e=new ed,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();pp(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=H(()=>{mp(i),c(void 0),o(void 0),u(void 0),d.current?.(void 0)},[i]);return U(()=>{t&&p()},[t,p]),{user:a,token:s,error:l,login:m,logout:h}}function _p(e){let{directory:t,onBuildStart:n,onBuildSuccess:r,onBuildError:i}=typeof e==`string`?{directory:e}:e,a=we(()=>A(t),[t]),[o,s]=G(void 0),[c,l]=G(void 0),[u,d]=G(`building`),f=W(n),p=W(r),m=W(i);return U(()=>{f.current=n,p.current=r,m.current=i},[n,r,i]),U(()=>{let e=new AbortController;return a.build({cwd:t,entry:a.entry,outdir:a.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{d(`building`),s(void 0),l(void 0),f.current?.()},onResult:e=>{`error`in e?(s(e.error),d(`error`),m.current?.(e.error)):(l(e),d(`success`),p.current?.(e))}}).catch(e=>{console.log(`error`,e),d(`error`),s(e),m.current?.(e)}),()=>{e.abort()}},[t]),we(()=>({error:o,status:u,result:c,entry:a.entry,outdir:a.outdir}),[o,u,c,a.entry,a.outdir])}function vp(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function yp(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const bp=/^\.+(\\|\/)|^\.+$/,xp=/[. ]+$/,Sp=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,Cp=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,wp=e=>e===``,Tp=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,Ep=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let Dp;function Op(){return Dp??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),Dp}function kp(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(vp().test(n)||[...n].some(e=>Cp.test(e)&&!wp(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(Ep,` `),n.length>0&&(e=e.replaceAll(Tp,`$1`)),e=e.replace(xp,``),e=e.replace(bp,n),e=e.replace(vp(),n),e=e.replaceAll(Sp,e=>wp(e)?e:n),e.length===0&&(e=n),e=yp().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=Ap(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=Ap(n,a)+i}}return e}function Ap(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of Op().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function jp(e){return`${e}.lock`}function Mp(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function Np(e,t={}){let n=jp(e),r=process.pid.toString();try{return P.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(P.readFileSync(n,`utf8`),10)}catch{return P.unlinkSync(n),Np(e,{...t,stale:0})}if(!Mp(i))try{return P.unlinkSync(n),Np(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return Np(e,{...t,stale:0});throw n}return!1}}async function Pp(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=Te.resolve(e),i=0;for(;i<=n.retries;){if(Np(r,n))return()=>Fp(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 Fp(e){let t=Te.resolve(e),n=jp(t);try{if(parseInt(P.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}P.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function Ip(e){let t=Te.resolve(e),n=jp(t);try{if(!P.existsSync(n))return{locked:!1};let e=P.readFileSync(n,`utf8`),t=parseInt(e,10);return Mp(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const Lp=e=>{P.mkdirSync(e,{recursive:!0})},Rp=e=>{try{P.fdatasyncSync(e)}catch{}try{P.closeSync(e)}catch{}},zp=e=>{try{let t=P.openSync(e,`r`);try{P.fsyncSync(t)}finally{P.closeSync(t)}}catch{}},Bp=(e,t)=>{let n=Te.dirname(e);Lp(n);let r=Te.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=P.openSync(r,`w`),P.writeFileSync(i,t,`utf-8`),Rp(i),i=void 0,P.renameSync(r,e),zp(e),zp(n)}catch(e){if(i!==void 0)try{P.closeSync(i)}catch{}try{P.rmSync(r,{force:!0})}catch{}throw e}},Vp=(e,t)=>{let n=new Map,r,i=e=>{if(P.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(P.readFileSync(e,`utf-8`))},a=(e,t)=>{Bp(e,JSON.stringify(t,null,2))},o=async()=>{if(r)throw Error(`Index is already locked`);let t=Te.join(e,`index.json`);Lp(e),P.existsSync(t)||P.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await Pp(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},s=async()=>{let t=Te.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},c=async t=>{let n=Te.join(e,`index.json`);a(n,t)},l=async t=>{let n=(await s()).ids[t];if(n)return Te.join(e,n)},u=async t=>{let n=(await s()).ids[t];if(!n)return;let r=Te.join(e,n);if(P.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(P.readFileSync(r,`utf-8`))},d=async n=>{let r=n[t],i=String(r),l=kp(i,{replacement:`_`})+`.json`,u=await o();try{let t=await s();t.ids[i]=l,t.current=i;let r=Te.join(e,l);a(r,n),await c(t)}finally{await u()}};return{async get(e){return await u(e)},async list(){if(!P.statSync(e,{throwIfNoEntry:!1}))return[];let t=await s(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=Te.join(e,i),a=P.statSync(t,{throwIfNoEntry:!1});if(!a)continue;let o=Ip(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=kp(r,{replacement:`_`})+`.json`,n=await o();try{let n=await s();n.ids[r]=t;let i=Te.join(e,t);Lp(e),P.writeFileSync(i,JSON.stringify({}),`utf-8`),await c(n),a=i}finally{await n()}}if(i?.force){let e=Ip(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 Pp(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=Te.join(e,n);try{P.rmSync(i,{force:!0}),zp(e)}catch{}}}finally{await t()}},async release(){try{f()}finally{n.delete(r)}}}},dispose(){n.clear()}}},Hp=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,a,o,s=new Map,c=new Map,l=Te.join(e,`index.json`),u=()=>{try{if(!P.statSync(l,{throwIfNoEntry:!1}))return{ids:{}};let e=P.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=Te.join(e,n);try{let e=P.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=Ip(i)),!a||a.mtime!==o||a.locked!==s.locked||a.pid!==s.pid){let e;e=!a||a.mtime!==o?JSON.parse(P.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{P.mkdirSync(e,{recursive:!0})}catch{}a=P.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 Up({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=Wp}){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=ve({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 Wp=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(_e);return n.length===0||n.some(e=>E(e.output)&&e.output.outcome===`pending`)?!1:n.every(e=>e.state.startsWith(`output-`))},Gp=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function Kp(e){return typeof e==`object`&&e?.__blink_internal!==void 0}var qp=class{chatId;agent;chatStore;serializeMessage;filterMessages;onError;chat;loading=!1;streamingMessage;status=`idle`;queue=[];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=Vp(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.onError=e.onError,this.watcher=Hp(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=>!Kp(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}}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 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);let t=!0;for(;this.queue.length>0||t;){t=!1;let n=new AbortController;this.abortController=n;let r=[...this.queue];this.queue=[],this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),r.length>0&&await this.upsertMessages(r,e);let i=this.chat.messages;this.filterMessages&&(i=i.filter(this.filterMessages)),i=i.map(e=>({...e,parts:e.parts.map(e=>!_e(e)||e.input!==``?e:{...e,input:{}})}));let a=performance.now(),o=await Up({agent:this.agent,id:this.chatId,signal:n.signal,messages:i}),s=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)},c=o.getReader();n.signal.addEventListener(`abort`,()=>{c.cancel().catch(()=>{})},{once:!0});let l;try{for(;;){let{done:e,value:t}=await c.read();if(e||n.signal.aborted)break;l||=performance.now()-a,this.streamingMessage&&t.id!==this.streamingMessage.id&&await s(this.streamingMessage);let r={...t,metadata:{...typeof t.metadata==`object`&&t.metadata!==null?t.metadata:{},ttft:l}};this.streamingMessage=this.serializeMessage?this.serializeMessage(r):r,this.notifyListeners()}}finally{c.releaseLock()}this.streamingMessage&&await s(this.streamingMessage)}}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&&(this.chat.updated_at=new Date().toISOString(),await e.set(this.chat),await e.release(),this.notifyListeners())}}stopStreaming(){this.abortController?.abort()}clearQueue(){this.queue=[],this.notifyListeners()}async resetChat(){this.abortController?.abort(),this.resetChatState(),this.notifyListeners();let e;try{e=await this.chatStore.lock(this.chatId),await e.delete()}catch{}finally{if(e)try{await e.release()}catch{}}}dispose(){this.disposed=!0,this.watcher.dispose(),this.listeners.clear(),this.abortController?.abort()}resetChatState(){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.streamingMessage=void 0,this.status=`idle`,this.queue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};function Jp(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a,onError:o}=e,s=W(null),[c,l]=G({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[]});U(()=>{s.current&&s.current.dispose();let e=new qp({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]),U(()=>{s.current&&s.current.setAgent(n)},[n]);let u=H(async e=>{s.current&&await s.current.sendMessages([e])},[]),d=H(async e=>{s.current&&await s.current.upsertMessages([e])},[]),f=H(()=>{s.current&&s.current.stopStreaming()},[]),p=H(async()=>{s.current&&await s.current.resetChat()},[]),m=H(()=>{s.current&&s.current.clearQueue()},[]),h=H(async e=>{s.current&&await s.current.deleteMessages([e])},[]),g=H(async()=>{s.current&&await s.current.start()},[]);return{...c,sendMessage:u,upsertMessage:d,stopStreaming:f,resetChat:p,clearQueue:m,deleteMessage:h,start:g}}function Yp(e){return ue(e,`.blink`,`devhook.txt`)}function Xp(e){return de(Yp(e))}function Zp(e){let t=Yp(e);if(de(t))return pe(t,`utf-8`).trim()}function Qp(e){let t=Yp(e);if(fe(B(t),{recursive:!0}),de(t))return pe(t,`utf-8`);let n=crypto.randomUUID();return he(t,n),n}const $p=(e,t)=>e.json({error:t},400),em=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}},tm=()=>new f,nm=tm().get(`/:key`,async e=>{let{key:t,err:n}=em(e);if(n)return $p(e,n);let r=await e.env.store.get(t);return e.json({value:r},200)}).post(`/:key`,k(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?$p(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:$p(t,`Value must be a string`):$p(t,`Value is required`)}),async e=>{let{key:t,err:n}=em(e);if(n)return $p(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}=em(e);return n?$p(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})}),rm=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`}},im=k(`param`,e=>({id:e.id})),am=tm().post(`/:key`,async e=>{let{key:t,err:n}=rm(e);return n?$p(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,im,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,im,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.getMessages(t),200)}).post(`/:id/sendMessages`,k(`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)):$p(e,`ID is required`)}).delete(`/:id/messages`,im,k(`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`,im,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,im,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,im,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),om=tm().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),sm=new f().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,nm).route(`/chat`,am).route(`/otlp`,om);var cm=/^(?:[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 lm(e){return typeof e==`string`&&cm.test(e)}var um=lm;function dm(e){if(!um(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 fm=dm;const pm=[];for(let e=0;e<256;++e)pm.push((e+256).toString(16).slice(1));function mm(e,t=0){return(pm[e[t+0]]+pm[e[t+1]]+pm[e[t+2]]+pm[e[t+3]]+`-`+pm[e[t+4]]+pm[e[t+5]]+`-`+pm[e[t+6]]+pm[e[t+7]]+`-`+pm[e[t+8]]+pm[e[t+9]]+`-`+pm[e[t+10]]+pm[e[t+11]]+pm[e[t+12]]+pm[e[t+13]]+pm[e[t+14]]+pm[e[t+15]]).toLowerCase()}function hm(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 gm(e,t,n,r,i,a){let o=typeof n==`string`?hm(n):n,s=typeof r==`string`?fm(r):r;if(typeof r==`string`&&(r=fm(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 mm(c)}function _m(e){return Array.isArray(e)?e=Buffer.from(e):typeof e==`string`&&(e=Buffer.from(e,`utf8`)),se(`sha1`).update(e).digest()}var vm=_m;function ym(e,t,n,r){return gm(80,vm,e,t,n,r)}ym.DNS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,ym.URL=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;var bm=ym;function xm(e){let t=Oe(e.dataDirectory,`chats`),n={},r=Oe(e.dataDirectory,`storage.json`);P.existsSync(r)&&(n=JSON.parse(P.readFileSync(r,`utf-8`)));let i=new Map,a=n=>{let r=i.get(n);return r||(r=new qp({chatId:n,chatsDirectory:t}),i.set(n,r)),r.setAgent(e.getAgent()),r},o={async upsert(e){let t=bm(JSON.stringify(e),bm.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=>Gp(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,P.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},delete(e){return delete n[e],P.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=le(w(e=>sm.fetch(e,{chat:o,store:s})));c.listen(e.port??0);let l=Vp(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 Sm({agent:e,capabilities:t,messages:n}){let[r,i]=G(void 0),[a,o]=G(!0),[s,c]=G(void 0),l=W(s);U(()=>{l.current=s},[s]);let[u,d]=G(()=>D(n));U(()=>{d(e=>{let t=D(n);return JSON.stringify(t)===JSON.stringify(e)?e:t})},[n]);let[f,p]=G(void 0),m=H((e,t)=>{if(!l.current)return!1;let n=l.current[e];return n?n.values.some(e=>e.id===t):!1},[]),h=H(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]);U(()=>{if(!u&&!s){p(void 0);return}h()},[u,s,h]);let g=W(void 0),_=W(void 0);U(()=>{e!==_.current&&(_.current=e,c(void 0),p(void 0),i(void 0),o(!0),g.current=void 0)},[e]),U(()=>{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=H((e,t)=>{h({[e]:t})},[h]);return{schema:s,options:f,setOption:v,loading:a,error:r}}function Cm(e){let t=W(e.onRequest);U(()=>{t.current=e.onRequest},[e.onRequest]);let[n,r]=G(`disconnected`);return U(()=>{if(e.disabled||!e.id){r(`disconnected`);return}let n=!1,i,a,o=!1,s,c=Oe(e.directory,`.blink`,`devhook`);return(async()=>{try{s=await Pp(c,{stale:!0,retries:0})}catch(e){if(e&&typeof e==`object`&&`code`in e&&e.code===`ELOCKED`){let e=``;try{let t=Ip(c);t.locked&&t.pid&&(e=` (PID: ${t.pid})`)}catch{}console.error(Zd.red(`\nError: Another ${Zd.bold(`blink dev`)} process is already running in this directory${e}.`)),console.error(Zd.red(`Please stop the other process and try again.
|
|
53
53
|
`)),process.exit(1)}let t=e&&typeof e==`object`&&`message`in e?String(e.message):String(e);console.warn(Zd.yellow(`\nWarning: Failed to acquire devhook lock: ${t}`)),console.warn(Zd.yellow(`Continuing without lock. Multiple ${Zd.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 ed({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(e){console.warn(`Failed to release devhook lock:`,e)}}},[e.disabled,e.directory]),{id:e.id,url:e.id?`https://${e.id}.blink.host`:void 0,status:n}}var wm=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}}})),Tm=o(e(((e,t)=>{let n=i(`fs`),r=i(`path`),a=i(`os`),o=i(`crypto`),s=wm().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=O.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=O.decrypt(i.ciphertext,i.key);break}catch(t){if(e+1>=i)throw t}return O.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=O._parseVault(e),i=process.env;return e&&e.processEnv!=null&&(i=e.processEnv),O.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=O.parse(n.readFileSync(t,{encoding:i}));O.populate(p,r,e)}catch(e){o&&_(`Failed to load ${t} ${e.message}`),d=e}let m=O.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 T(e){if(y(e).length===0)return O.configDotenv(e);let t=x(e);return t?O._configVault(e):(g(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),O.configDotenv(e))}function E(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 D(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 O={configDotenv:w,_configVault:C,_parseVault:h,config:T,decrypt:E,parse:m,populate:D};t.exports.configDotenv=O.configDotenv,t.exports._configVault=O._configVault,t.exports._parseVault=O._parseVault,t.exports.config=O.config,t.exports.decrypt=O.decrypt,t.exports.parse=O.parse,t.exports.populate=O.populate,t.exports=O}))());async function Em(e,t){let n=e;for(;n!==B(n);){let e=ue(n,t);try{return await V(e),e}catch{}n=B(n)}}function Dm(e,t=`.env.local`){let[n,r]=G({});return U(()=>{let n,i=e=>{try{let t=pe(e,`utf-8`),n=(0,Tm.parse)(t);r(n)}catch(e){console.error(`Error reading ${t}:`,e),r({})}};return Em(e,t).then(e=>{if(!e){r({});return}i(e),n=me(e,{persistent:!1},()=>{i(e)})}),()=>{n&&n.close()}},[e,t]),n}var Om=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 Om{};function km(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 Am(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 jm(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 Mm(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 Nm(e,t){return jm(e,t,``)}function Pm(e,t){return Mm(e,t,``)}function Fm(e,t){return t.slice(0,Im(e,t))}function Im(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 Lm(e){let t;for(t=e.length-1;t>=0&&e[t].match(/\s/);t--);return e.substring(t+1)}function Rm(e){let t=e.match(/^\s*/);return t?t[0]:``}const zm=`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}`,Bm=RegExp(`[${zm}]+|\\s+|[^${zm}]`,`ug`);new class extends Om{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(Bm)||[];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)&&Vm(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&Vm(n,i,r,null),e}};function Vm(e,t,n,r){if(t&&n){let i=Rm(t.value),a=Lm(t.value),o=Rm(n.value),s=Lm(n.value);if(e){let r=km(i,o);e.value=Mm(e.value,o,r),t.value=Nm(t.value,r),n.value=Nm(n.value,r)}if(r){let e=Am(a,s);r.value=jm(r.value,s,e),t.value=Pm(t.value,e),n.value=Pm(n.value,e)}}else if(n){if(e){let e=Rm(n.value);n.value=n.value.substring(e.length)}if(r){let e=Rm(r.value);r.value=r.value.substring(e.length)}}else if(e&&r){let n=Rm(r.value),i=Rm(t.value),a=Lm(t.value),o=km(n,i);t.value=Nm(t.value,o);let s=Am(Nm(n,o),a);t.value=Pm(t.value,s),r.value=jm(r.value,n,s),e.value=Mm(e.value,n,n.slice(0,n.length-s.length))}else if(r){let e=Rm(r.value),n=Lm(t.value),i=Fm(n,e);t.value=Pm(t.value,i)}else if(e){let n=Lm(e.value),r=Rm(t.value),i=Fm(n,r);t.value=Nm(t.value,i)}}new class extends Om{tokenize(e){let t=RegExp(`(\\r?\\n)|[${zm}]+|[^\\S\\n\\r]+|[^${zm}]`,`ug`);return e.match(t)||[]}};const Hm=new class extends Om{constructor(){super(...arguments),this.tokenize=Wm}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
|
|
@@ -379,7 +379,8 @@ import { openai } from "@ai-sdk/openai";
|
|
|
379
379
|
model: anthropic("claude-sonnet-4.5", {
|
|
380
380
|
apiKey: process.env.ANTHROPIC_API_KEY,
|
|
381
381
|
});
|
|
382
|
-
|
|
382
|
+
// Use chat API for OpenAI models - it's more reliable than the responses API
|
|
383
|
+
model: openai.chat("gpt-5", { apiKey: process.env.OPENAI_API_KEY });
|
|
383
384
|
\`\`\`
|
|
384
385
|
|
|
385
386
|
**Note about Edit Mode:** Edit mode (this agent) automatically selects models in this priority:
|
|
@@ -917,7 +918,8 @@ import { openai } from "@ai-sdk/openai";
|
|
|
917
918
|
model: anthropic("claude-sonnet-4.5", {
|
|
918
919
|
apiKey: process.env.ANTHROPIC_API_KEY,
|
|
919
920
|
});
|
|
920
|
-
|
|
921
|
+
// Use chat API for OpenAI models - it's more reliable than the responses API
|
|
922
|
+
model: openai.chat("gpt-5", { apiKey: process.env.OPENAI_API_KEY });
|
|
921
923
|
\`\`\`
|
|
922
924
|
|
|
923
925
|
**Note about Edit Mode:** Edit mode (this agent) automatically selects models in this priority:
|
|
@@ -1369,4 +1371,4 @@ Slack:
|
|
|
1369
1371
|
1. *ALWAYS* use the \`typecheck_agent\` tool to check for type errors before making changes. NEVER invoke \`tsc\` directly.
|
|
1370
1372
|
2. Use the \`message_user_agent\` tool to test the agent after you make changes.
|
|
1371
1373
|
</agent_development>
|
|
1372
|
-
`});let p=rh.scratch[`AGENTS.md`];try{p=await xe(ue(e.directory,`AGENTS.md`),`utf-8`)}catch{}return f.unshift({role:`system`,content:p}),ye({model:hh(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 mh(e){if(e.ANTHROPIC_API_KEY)return gn({apiKey:e.ANTHROPIC_API_KEY}).chat(`claude-sonnet-4-5`);if(e.OPENAI_API_KEY)return Ao({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 hh(e){let t=mh(e);if(!t)throw Error(`No API key available for edit mode`);return t}function gh(e){let[t,n]=G(void 0),[r,i]=G(void 0),[a,o]=G(!1),s=W(void 0);return U(()=>{let t=new AbortController,r=!1;if(i(void 0),n(void 0),!mh(e.env)){o(!0);return}return o(!1),(async()=>{s.current=ph({directory:e.directory,env:e.env,getDevhookUrl:e.getDevhookUrl});let r=await _h(),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 a=new vc({baseUrl:`http://127.0.0.1:${r}`});for(;!t.signal.aborted;){try{await a.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(t.signal.aborted)throw t.signal.reason;n(a)})().catch(e=>{r||i(e instanceof Error?e:Error(String(e)))}),()=>{r=!0,t.abort()}},[e.directory,e.apiServerUrl,e.env,e.getDevhookUrl]),we(()=>({client:t,error:r,missingApiKey:a,setUserAgentUrl:e=>{s.current?.setUserAgentUrl(e)}}),[t,r,a])}async function _h(){let e=le();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function vh(e){let{directory:t}=e,[n,r]=G(),[i,a]=G(!1),[o,s]=G(`run`),c=W(`run`);U(()=>{c.current=o},[o]);let l=H(t=>{s(t),e.onModeChange?.(t),r(void 0)},[e.onModeChange]),u=H(()=>{l(o===`run`?`edit`:`run`)},[o,l]),{error:d,status:f,result:p,entry:m}=_p({directory:t,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),h=gp({autoCheck:!0,onAuthChange:e.onAuthChange,onLoginUrl:e.onLoginUrl}),g=Dm(t),_=we(()=>{let e=h.token;return e?{...g,BLINK_TOKEN:e}:g},[g,h.token]),v=W(void 0);U(()=>{let t=Object.keys(_);if(t.length===v.current||v.current===void 0){v.current=t.length;return}v.current=t.length,e.onEnvLoaded?.(t)},[_,e.onEnvLoaded]);let y=W(void 0),b=we(()=>xm({port:0,dataDirectory:ue(t,`.blink`),getAgent:()=>y.current}),[t]),{agent:x,logs:S,error:C,capabilities:w}=yc({buildResult:p,env:_,apiServerUrl:b.url}),{client:T,error:D,missingApiKey:O,setUserAgentUrl:k}=gh({directory:t,apiServerUrl:b.url,env:_,getDevhookUrl:H(()=>{let e=Zp(t)??Qp(t);return F(e),`https://${e}.blink.host`},[t])}),[A,j]=G(`00000000-0000-0000-0000-000000000000`);U(()=>{y.current=x},[x]),U(()=>{x&&k(x.baseUrl),(o===`run`&&!x||o===`edit`&&!T)&&b.getChatManager(A)?.stopStreaming()},[x,T,o,A,b,k]);let M=W(void 0),N=Jp({chatId:A,agent:o===`run`?x:T,chatsDirectory:b.chatsDirectory,serializeMessage:e=>{let t=e.role===`user`&&M.current?{...typeof e.metadata==`object`&&e.metadata!==null?e.metadata:{},options:M.current}:e.metadata;return typeof t==`object`&&t&&(t.__blink_mode=c.current),{id:e.id??crypto.randomUUID(),created_at:new Date().toISOString(),role:e.role,parts:e.parts,mode:c.current,metadata:t}},filterMessages:e=>c.current===`edit`?!0:!(Kp(e.metadata)||e.mode===`edit`)}),ee=W(0);U(()=>{if(S.length===ee.current)return;let t=ee.current;for(let n of S.slice(t))e.onAgentLog?.(n);ee.current=S.length},[S,e.onAgentLog,N.upsertMessage]);let[te,P]=G([]);U(()=>{b.listChats().then(e=>{P(e.map(e=>e.key))})},[b]),U(()=>{A&&!te.includes(A)&&P(e=>[...e,A])},[A,te]);let[ne,F]=G(()=>Xp(t)?Zp(t):Qp(t)),I=Cm({id:ne,directory:t,disabled:!w?.request,onRequest:async t=>{if(!x)throw Error(`No agent`);let n=new URL(t.url),r=new URL(x.baseUrl);r.pathname=n.pathname,r.search=n.search;try{let i=await fetch(r.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:`manual`,signal:t.signal,duplex:`half`});return e.onDevhookRequest?.({method:t.method,path:n.pathname,status:i.status}),i}catch(e){return console.error(`Error sending request to user's agent:`,e),new Response(`Internal server error`,{status:500})}}});U(()=>{I.status!==`connected`||!I.url||e.onDevhookConnected?.(I.url)},[I.status,I.url]);let{schema:L,options:re,error:R,setOption:ie}=Sm({agent:o===`run`?x:T,capabilities:w,messages:N.messages});U(()=>{M.current=re},[re]);let z=we(()=>{let e=new Map;return C&&o===`run`&&e.set(`agent`,C.message),D&&o===`edit`&&e.set(`editAgent`,`Edit agent error: ${D.message}`),
|
|
1374
|
+
`});let p=rh.scratch[`AGENTS.md`];try{p=await xe(ue(e.directory,`AGENTS.md`),`utf-8`)}catch{}return f.unshift({role:`system`,content:p}),ye({model:hh(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 mh(e){if(e.ANTHROPIC_API_KEY)return gn({apiKey:e.ANTHROPIC_API_KEY}).chat(`claude-sonnet-4-5`);if(e.OPENAI_API_KEY)return Ao({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 hh(e){let t=mh(e);if(!t)throw Error(`No API key available for edit mode`);return t}function gh(e){let[t,n]=G(void 0),[r,i]=G(void 0),[a,o]=G(!1),s=W(void 0);return U(()=>{let t=new AbortController,r=!1;if(i(void 0),n(void 0),!mh(e.env)){o(!0);return}return o(!1),(async()=>{s.current=ph({directory:e.directory,env:e.env,getDevhookUrl:e.getDevhookUrl});let r=await _h(),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 a=new vc({baseUrl:`http://127.0.0.1:${r}`});for(;!t.signal.aborted;){try{await a.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(t.signal.aborted)throw t.signal.reason;n(a)})().catch(e=>{r||i(e instanceof Error?e:Error(String(e)))}),()=>{r=!0,t.abort()}},[e.directory,e.apiServerUrl,e.env,e.getDevhookUrl]),we(()=>({client:t,error:r,missingApiKey:a,setUserAgentUrl:e=>{s.current?.setUserAgentUrl(e)}}),[t,r,a])}async function _h(){let e=le();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function vh(e){let{directory:t}=e,[n,r]=G(),[i,a]=G(!1),[o,s]=G(`run`),c=W(`run`);U(()=>{c.current=o},[o]);let l=H(t=>{s(t),e.onModeChange?.(t),r(void 0)},[e.onModeChange]),u=H(()=>{l(o===`run`?`edit`:`run`)},[o,l]),{error:d,status:f,result:p,entry:m}=_p({directory:t,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),h=gp({autoCheck:!0,onAuthChange:e.onAuthChange,onLoginUrl:e.onLoginUrl}),g=Dm(t),_=we(()=>{let e=h.token;return e?{...g,BLINK_TOKEN:e}:g},[g,h.token]),v=W(void 0);U(()=>{let t=Object.keys(_);if(t.length===v.current||v.current===void 0){v.current=t.length;return}v.current=t.length,e.onEnvLoaded?.(t)},[_,e.onEnvLoaded]);let y=W(void 0),b=we(()=>xm({port:0,dataDirectory:ue(t,`.blink`),getAgent:()=>y.current}),[t]),{agent:x,logs:S,error:C,capabilities:w}=yc({buildResult:p,env:_,apiServerUrl:b.url}),{client:T,error:D,missingApiKey:O,setUserAgentUrl:k}=gh({directory:t,apiServerUrl:b.url,env:_,getDevhookUrl:H(()=>{let e=Zp(t)??Qp(t);return F(e),`https://${e}.blink.host`},[t])}),[A,j]=G(`00000000-0000-0000-0000-000000000000`);U(()=>{y.current=x},[x]),U(()=>{x&&k(x.baseUrl),(o===`run`&&!x||o===`edit`&&!T)&&b.getChatManager(A)?.stopStreaming()},[x,T,o,A,b,k]);let M=W(void 0),N=Jp({chatId:A,agent:o===`run`?x:T,chatsDirectory:b.chatsDirectory,serializeMessage:e=>{let t=e.role===`user`&&M.current?{...typeof e.metadata==`object`&&e.metadata!==null?e.metadata:{},options:M.current}:e.metadata;return typeof t==`object`&&t&&(t.__blink_mode=c.current),{id:e.id??crypto.randomUUID(),created_at:new Date().toISOString(),role:e.role,parts:e.parts,mode:c.current,metadata:t}},filterMessages:e=>c.current===`edit`?!0:!(Kp(e.metadata)||e.mode===`edit`),onError:t=>{e.onError?.(`${Zd.red(`⚙ [Chat Error]`)} ${Zd.gray(t)}`)}}),ee=W(0);U(()=>{if(S.length===ee.current)return;let t=ee.current;for(let n of S.slice(t))e.onAgentLog?.(n);ee.current=S.length},[S,e.onAgentLog,N.upsertMessage]);let[te,P]=G([]);U(()=>{b.listChats().then(e=>{P(e.map(e=>e.key))})},[b]),U(()=>{A&&!te.includes(A)&&P(e=>[...e,A])},[A,te]);let[ne,F]=G(()=>Xp(t)?Zp(t):Qp(t)),I=Cm({id:ne,directory:t,disabled:!w?.request,onRequest:async t=>{if(!x)throw Error(`No agent`);let n=new URL(t.url),r=new URL(x.baseUrl);r.pathname=n.pathname,r.search=n.search;try{let i=await fetch(r.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:`manual`,signal:t.signal,duplex:`half`});return e.onDevhookRequest?.({method:t.method,path:n.pathname,status:i.status}),i}catch(e){return console.error(`Error sending request to user's agent:`,e),new Response(`Internal server error`,{status:500})}}});U(()=>{I.status!==`connected`||!I.url||e.onDevhookConnected?.(I.url)},[I.status,I.url]);let{schema:L,options:re,error:R,setOption:ie}=Sm({agent:o===`run`?x:T,capabilities:w,messages:N.messages});U(()=>{M.current=re},[re]);let z=we(()=>{let e=new Map;return C&&o===`run`&&e.set(`agent`,C.message),D&&o===`edit`&&e.set(`editAgent`,`Edit agent error: ${D.message}`),R&&e.set(`options`,`Options error: ${R.message}`),e},[C,D,R,o]),ae=W(new Map);U(()=>{let t=ae.current,n=z;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)},[z,e.onError]);let oe=we(()=>{let e=[...N.messages].reverse().find(e=>!(e.role!==`assistant`||e.metadata&&e.metadata.ephemeral));if(!e||n===e.id)return;let t=e.parts.filter(_e);if(t.length!==0&&t.some(e=>E(e.output)&&e.output.outcome===`pending`))return e},[N.messages,n]),se=H(async(e,t)=>{if(!oe)return;t&&e&&a(!0),r(oe.id);let n=N.messages;if(n.length===0)return;let i=n[n.length-1];if(!i||i.role!==`assistant`||!Array.isArray(i.parts))return;let o=i.parts.map(t=>t.output&&E(t.output)&&t.output.outcome===`pending`?{...t,output:{...t.output,outcome:e?`approved`:`rejected`}}:t);await N.upsertMessage({...i,parts:o}),await N.start()},[oe,N]);U(()=>{i&&oe&&se(!0)},[i,oe,se]);let ce=H(()=>{let e=crypto.randomUUID();j(e),P(t=>[...t,e]),r(void 0)},[]),le=H(e=>{j(e),r(void 0)},[]),B=we(()=>{if(oe)return{message:oe,approve:e=>se(!0,e),reject:()=>se(!1),autoApproveEnabled:i}},[oe,se,i]),de=we(()=>{let e=N.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}}},[N.messages]),fe=we(()=>{if(N.status!==`streaming`)return!1;if(!N.streamingMessage)return!0;let e=N.streamingMessage.parts.filter(_e);return e.length>0&&e.every(e=>e.state.startsWith(`output-`))},[N.status,N.streamingMessage]);return{mode:o,setMode:l,toggleMode:u,chat:N,chats:te,switchChat:le,newChat:ce,build:{status:f,error:d,entrypoint:m},devhook:{connected:I.status===`connected`,url:I.status===`connected`?I.url:void 0},capabilities:w,options:{schema:L,selected:re,error:R,setOption:ie},approval:B,tokenUsage:de,auth:h,server:b,showWaitingPlaceholder:fe,editModeMissingApiKey:O}}export{yc as useAgent,gp as useAuth,_p as useBundler,Jp as useChat,vh as useDevMode,Cm as useDevhook,Dm as useDotenv,gh as useEditAgent,Sm as useOptions};
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"./dist-Ceoe3h7v.js";import{login as e}from"./auth-BilZuH-1.js";import"./util-CUfifM0g.js";async function t(){await e()}export{t as default};
|