blink 1.0.3 → 1.0.5
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/browser/agent/client/index.cjs +1 -1
- package/dist/browser/agent/client/index.js +1 -1
- package/dist/browser/agent/index.browser.cjs +1 -1
- package/dist/browser/agent/index.browser.js +1 -1
- package/dist/browser/control/index.d.cts +16 -16
- package/dist/browser/control/index.d.ts +16 -16
- package/dist/browser/{index.browser-C6dfHpox.cjs → index.browser-BBk81dZs.cjs} +1 -1
- package/dist/browser/{index.browser-D8y5NucV.js → index.browser-DPHICXmy.js} +1 -1
- package/dist/browser/react/index.browser.cjs +1 -1
- package/dist/browser/react/index.browser.js +1 -1
- package/dist/cli/{auth-CpUNsA0k.js → auth-DeHFQhPJ.js} +1 -1
- package/dist/cli/{chat-01Fdrhd_.js → chat-Jjsxhu91.js} +1 -1
- package/dist/cli/{chat-manager-CZFcRdLU.js → chat-manager-DWh8MCAU.js} +1 -1
- package/dist/cli/{dev-DnkYQ26a.js → dev-0DG-Xch_.js} +77 -74
- package/dist/cli/index.js +3 -3
- package/dist/cli/{init-DFXOMY0k.js → init-Ui3uJtsY.js} +1 -1
- package/dist/cli/login-Y9JfBHag.js +1 -0
- package/dist/cli/{run-Bsh7xK4H.js → run-CBQHAvUo.js} +1 -1
- package/dist/cli/{util-CkrO2lHF.js → util-dGFzG4wT.js} +1 -1
- package/dist/node/agent/index.node.cjs +1 -1
- package/dist/node/agent/index.node.js +1 -1
- package/dist/node/{index.node-X0B5XDkx.js → index.node-BdbWMIX0.js} +2 -6
- package/dist/node/{index.node-CziivD-D.cjs → index.node-C6sId3jT.cjs} +2 -6
- package/dist/node/react/index.node.cjs +3 -2
- package/dist/node/react/index.node.js +7 -6
- package/package.json +2 -1
- package/dist/cli/login-yMSEGrjU.js +0 -1
- /package/dist/cli/{dist-wyfWuz5A.js → dist-BNbSDxaw.js} +0 -0
- /package/dist/cli/{open-S_jcQ0nw.js → open-DCYivxgo.js} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__commonJSMin as e,__reExport as t,__require as n,__toESM as r}from"../chunk-D9KrCrVq.js";import{APIServerURLEnvironmentVariable as i,
|
|
1
|
+
import{__commonJSMin as e,__reExport as t,__require as n,__toESM as r}from"../chunk-D9KrCrVq.js";import{APIServerURLEnvironmentVariable as i,Agent as a,Client as o,Hono as s,createAnthropic as c,createOpenAI as l,createServerAdapter as u,isToolApprovalOutput as d,lastUIOptions as f,model as p,require_has_flag as m,tools as h,validator as g}from"../index.node-BdbWMIX0.js";import"../token-error-488npYdU.js";import"../esm-CbZfjZBn.js";import{resolveConfig as _}from"../build-D_L0gFGa.js";import{createRequire as v}from"node:module";import"zod/v4";import"zod/v3";import{Buffer as y}from"node:buffer";import*as b from"node:fs";import x,{createReadStream as S}from"node:fs";import{fileURLToPath as C}from"node:url";import{Writable as w}from"node:stream";import{promisify as T,stripVTControlCharacters as E}from"node:util";import{createHash as D}from"node:crypto";import O,{createServer as k}from"http";import{dirname as A,join as j}from"path";import{createRequire as M}from"module";import{existsSync as N,mkdirSync as P,readFileSync as F,unlinkSync as ee,watch as te,writeFileSync as I}from"fs";import L,{stdin as ne,stdout as R}from"node:process";import{convertToModelMessages as z,isToolOrDynamicToolUIPart as B,readUIMessageStream as re,streamText as ie,tool as V}from"ai";import*as ae from"fs/promises";import{readFile as oe,stat as se,writeFile as ce}from"fs/promises";import{spawn as le}from"child_process";import{useCallback as H,useEffect as U,useMemo as ue,useRef as de,useState as W}from"react";import G,{ZodFirstPartyTypeKind as K,ZodType as fe,z as q}from"zod";import*as pe from"node:readline";import me from"node:readline";import*as J from"node:path";import he,{join as ge}from"node:path";import _e,{execFile as ve}from"node:child_process";import*as ye from"node:fs/promises";import be,{constants as xe}from"node:fs/promises";import Se from"node:os";function Ce(e){let[t,n]=W(void 0),[r,a]=W([]),[s,c]=W(void 0),[l,u]=W(e.buildResult),[d,f]=W(e.env),[p,m]=W(e.apiServerUrl),[h,g]=W(void 0);return U(()=>{f(e.env),u(e.buildResult),m(e.apiServerUrl)},[e.env,e.buildResult,e.apiServerUrl]),U(()=>{if(!l||`error`in l){n(void 0),a([]),c(void 0),g(void 0);return}let e=new AbortController,t=!1;return c(void 0),n(void 0),g(void 0),(async()=>{let t=await we(),r=le(`node`,[`--no-deprecation`,l.entry],{stdio:`pipe`,env:{...process.env,...d,[i]:p,PORT:t.toString(),HOST:`127.0.0.1`}});e.signal.addEventListener(`abort`,()=>{try{r.kill()}catch{}});let s=!1;r.stdout.on(`data`,e=>{let t=Buffer.from(e).toString(`utf-8`).trim();!s&&t.startsWith(`Agent server listening on`)||(s||console.log(`stdout: ${t}`),t.length&&a(e=>[...e,{level:`log`,message:t}]))}),r.stderr.on(`data`,e=>{s||console.error(`stderr: ${Buffer.from(e).toString(`utf-8`).trim()}`);let t=Buffer.from(e).toString(`utf-8`).trim();t.length&&a(e=>[...e,{level:`error`,message:t}])}),r.on(`error`,t=>{e.abort(t)}),r.on(`exit`,(t,n)=>{e.abort(`Agent exited with code ${t??`unknown`} and signal ${n??`unknown`}. Be sure to call "blink.agent(...).serve()".`)});let c=new o({baseUrl:`http://127.0.0.1:${t}`});for(;!e.signal.aborted;){try{await c.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(e.signal.aborted)throw e.signal.reason;s=!0;let u=await c.capabilities();g(u),n(c)})().catch(e=>{t||c(e instanceof Error?e:Error(String(e)))}),()=>{t=!0,e.abort()}},[l,d,p]),ue(()=>({agent:t,logs:r,error:s,capabilities:h}),[t,r,s,h])}async function we(){let e=k();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}var Te=Object.getOwnPropertyNames,Ee=(e,t)=>function(){return t||(0,e[Te(e)[0]])((t={exports:{}}).exports,t),t.exports},Y=v(import.meta.url);q.object({email:q.string().email(),password:q.string().min(8)}),q.object({email:q.string().email(),code:q.string()}),q.object({email:q.string().email(),password:q.string().min(8)});var De=class{constructor(e,t){this.client=e,this.baseURL=t}async token(e,t={timeout:12e4}){return new Promise((n,r)=>{let i=crypto.randomUUID(),a=this.client.websocket(`/api/auth/token?id=${i}`),o=new URL(`/auth?id=${i}`,this.baseURL),s=setTimeout(()=>{r(Error(`Timeout waiting for the user to authenticate`))},t.timeout);a.onerror=e=>{clearTimeout(s),console.log(`error`,e),r(Error(`Failed to connect to server`))},a.onopen=()=>{e(o.toString(),i)},a.onmessage=e=>{typeof e.data==`string`&&(clearTimeout(s),n(e.data))}})}},Oe=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function ke(e){}function Ae(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=ke,onError:n=ke,onRetry:r=ke,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=je(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1,i=e.slice(t+r);f(n,i,e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t}
|
|
2
2
|
`;break;case`id`:s=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new Oe(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new Oe(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}));break}}function p(){c.length>0&&t({id:s,event:l||void 0,data:c.endsWith(`
|
|
3
3
|
`)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function je(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
|
|
4
4
|
`,r),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i===-1?a!==-1&&(o=a):o=i===e.length-1?-1:i,o===-1){n=e.slice(r);break}else{let n=e.slice(r,o);t.push(n),r=o+1,e[r-1]===`\r`&&e[r]===`
|
|
@@ -36,7 +36,7 @@ ${Mr}`),t.includes(`
|
|
|
36
36
|
`)&&(n=3+E(t.slice(t.lastIndexOf(`
|
|
37
37
|
`))).length);let e=E(t).length;n+e<process.stdout.columns?(n+=e,process.stdout.write(t)):(process.stdout.write(`
|
|
38
38
|
${Mr}${t.trimStart()}`),n=3+E(t.trimStart()).length)}process.stdout.write(`
|
|
39
|
-
`)},info:e=>Nr.message(e,{symbol:xr.default.blue(Dr)}),success:e=>Nr.message(e,{symbol:xr.default.green(Or)}),step:e=>Nr.message(e,{symbol:xr.default.green(Tr)}),warn:e=>Nr.message(e,{symbol:xr.default.yellow(kr)}),warning:e=>Nr.warn(e),error:e=>Nr.message(e,{symbol:xr.default.red(Ar)})};let Pr;function Fr(){try{return x.statSync(`/.dockerenv`),!0}catch{return!1}}function Ir(){try{return x.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function Lr(){return Pr===void 0&&(Pr=Fr()||Ir()),Pr}let Rr;const zr=()=>{try{return x.statSync(`/run/.containerenv`),!0}catch{return!1}};function Br(){return Rr===void 0&&(Rr=zr()||Lr()),Rr}const Vr=()=>{if(L.platform!==`linux`)return!1;if(Se.release().toLowerCase().includes(`microsoft`))return!Br();try{return x.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!Br():!1}catch{return!1}};var Hr=L.env.__IS_WSL_TEST__?Vr:Vr();const Ur=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await be.access(n,xe.F_OK),r=!0}catch{}if(!r)return e;let i=await be.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}})(),Wr=async()=>`${await Ur()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Gr=async()=>Hr?Wr():`${L.env.SYSTEMROOT||L.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function Kr(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 qr=T(ve);async function Jr(){if(L.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await qr(`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 Yr=T(ve);async function Xr(e,{humanReadableOutput:t=!0,signal:n}={}){if(L.platform!==`darwin`)throw Error(`macOS only`);let r=t?[]:[`-ss`],i={};n&&(i.signal=n);let{stdout:a}=await Yr(`osascript`,[`-e`,e,r],i);return a.trim()}async function Zr(e){return Xr(`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 Qr=T(ve),$r={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 ei=class extends Error{};async function ti(e=Qr){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 ei(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=$r[r];if(!i)throw new ei(`Unknown browser ID: ${r}`);return i}const ni=T(ve),ri=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function ii(){if(L.platform===`darwin`){let e=await Jr();return{name:await Zr(e),id:e}}if(L.platform===`linux`){let{stdout:e}=await ni(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:ri(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(L.platform===`win32`)return ti();throw Error(`Only macOS, Linux, and Windows are supported`)}const ai=T(_e.execFile),oi=he.dirname(C(import.meta.url)),si=he.join(oi,`xdg-open`),{platform:ci,arch:li}=L;async function ui(){let e=await Gr(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=y.from(t,`utf16le`).toString(`base64`),{stdout:r}=await ai(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 di=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},fi=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return di(e.app,t=>fi({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return di(t,t=>fi({...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=Hr?await ui():await ii();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),fi({...e,app:{name:gi[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,i=[],a={};if(ci===`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(ci===`win32`||Hr&&!Br()&&!t){r=await Gr(),i.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),Hr||(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=y.from(o.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!oi||oi===`/`,t=!1;try{await be.access(si,xe.X_OK),t=!0}catch{}r=L.versions.electron??(ci===`android`||e||!t)?`xdg-open`:si}n.length>0&&i.push(...n),e.wait||(a.stdio=`ignore`,a.detached=!0)}ci===`darwin`&&n.length>0&&i.push(`--args`,...n),e.target&&i.push(e.target);let o=_e.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)},pi=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return fi({...t,target:e})};function mi(e){if(typeof e==`string`||Array.isArray(e))return e;let{[li]:t}=e;if(!t)throw Error(`${li} is not supported`);return t}function hi({[ci]:e},{wsl:t}){if(t&&Hr)return mi(t);if(!e)throw Error(`${ci} is not supported`);return mi(e)}const gi={};Kr(gi,`chrome`,()=>hi({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`]}})),Kr(gi,`brave`,()=>hi({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`]}})),Kr(gi,`firefox`,()=>hi({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),Kr(gi,`edge`,()=>hi({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),Kr(gi,`browser`,()=>`browser`),Kr(gi,`browserPrivate`,()=>`browserPrivate`);var _i=pi;function vi(e){let t=e||xi();if(N(t)){let e=F(t,`utf8`);return JSON.parse(e).token}}function yi(e,t){let n=t||xi();N(A(n))||P(A(n),{recursive:!0}),I(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function bi(e){let t=e||xi();N(t)&&ee(t)}function xi(){let e=Xn(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return j(e[0],`auth.json`)}function Si(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=W(),[s,c]=W(()=>vi(i)),[l,u]=W(),d=de(n),f=de(r);U(()=>{d.current=n,f.current=r},[n,r]);let p=H(async()=>{u(void 0);try{let e=vi(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new Vn({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 Vn,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();yi(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(()=>{bi(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 Ci(e){let{directory:t,onBuildStart:n,onBuildSuccess:r,onBuildError:i}=typeof e==`string`?{directory:e}:e,a=ue(()=>_(t),[t]),[o,s]=W(void 0),[c,l]=W(void 0),[u,d]=W(`building`),f=de(n),p=de(r),m=de(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]),ue(()=>({error:o,status:u,result:c,entry:a.entry,outdir:a.outdir}),[o,u,c,a.entry,a.outdir])}function wi(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function Ti(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const Ei=/^\.+(\\|\/)|^\.+$/,Di=/[. ]+$/,Oi=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,ki=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,Ai=e=>e===``,ji=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,Mi=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let Ni;function Pi(){return Ni??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),Ni}function Fi(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(wi().test(n)||[...n].some(e=>ki.test(e)&&!Ai(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(Mi,` `),n.length>0&&(e=e.replaceAll(ji,`$1`)),e=e.replace(Di,``),e=e.replace(Ei,n),e=e.replace(wi(),n),e=e.replaceAll(Oi,e=>Ai(e)?e:n),e.length===0&&(e=n),e=Ti().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=Ii(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=Ii(n,a)+i}}return e}function Ii(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of Pi().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function Li(e){return`${e}.lock`}function Ri(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function zi(e,t={}){let n=Li(e),r=process.pid.toString();try{return b.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(b.readFileSync(n,`utf8`),10)}catch{return b.unlinkSync(n),zi(e,{...t,stale:0})}if(!Ri(i))try{return b.unlinkSync(n),zi(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return zi(e,{...t,stale:0});throw n}return!1}}async function Bi(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=J.resolve(e),i=0;for(;i<=n.retries;){if(zi(r,n))return()=>Vi(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 Vi(e){let t=J.resolve(e),n=Li(t);try{if(parseInt(b.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}b.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function Hi(e){let t=J.resolve(e),n=Li(t);try{if(!b.existsSync(n))return{locked:!1};let e=b.readFileSync(n,`utf8`),t=parseInt(e,10);return Ri(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const Ui=e=>{b.mkdirSync(e,{recursive:!0})},Wi=e=>{try{b.fdatasyncSync(e)}catch{}try{b.closeSync(e)}catch{}},Gi=e=>{try{let t=b.openSync(e,`r`);try{b.fsyncSync(t)}finally{b.closeSync(t)}}catch{}},Ki=(e,t)=>{let n=J.dirname(e);Ui(n);let r=J.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=b.openSync(r,`w`),b.writeFileSync(i,t,`utf-8`),Wi(i),i=void 0,b.renameSync(r,e),Gi(e),Gi(n)}catch(e){if(i!==void 0)try{b.closeSync(i)}catch{}try{b.rmSync(r,{force:!0})}catch{}throw e}},qi=(e,t)=>{let n=new Map,r,i=e=>{if(b.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(b.readFileSync(e,`utf-8`))},a=(e,t)=>{Ki(e,JSON.stringify(t,null,2))},o=async()=>{if(r)throw Error(`Index is already locked`);let t=J.join(e,`index.json`);Ui(e),b.existsSync(t)||b.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await Bi(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},s=async()=>{let t=J.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},c=async t=>{let n=J.join(e,`index.json`);a(n,t)},l=async t=>{let n=(await s()).ids[t];if(n)return J.join(e,n)},u=async t=>{let n=(await s()).ids[t];if(!n)return;let r=J.join(e,n);if(b.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(b.readFileSync(r,`utf-8`))},d=async n=>{let r=n[t],i=String(r),l=Fi(i,{replacement:`_`})+`.json`,u=await o();try{let t=await s();t.ids[i]=l,t.current=i;let r=J.join(e,l);a(r,n),await c(t)}finally{await u()}};return{async get(e){return await u(e)},async list(){if(!b.statSync(e,{throwIfNoEntry:!1}))return[];let t=await s(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=J.join(e,i),a=b.statSync(t,{throwIfNoEntry:!1});if(!a)continue;let o=Hi(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=Fi(r,{replacement:`_`})+`.json`,n=await o();try{let n=await s();n.ids[r]=t;let i=J.join(e,t);Ui(e),b.writeFileSync(i,JSON.stringify({}),`utf-8`),await c(n),a=i}finally{await n()}}if(i?.force){let e=Hi(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 Bi(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=J.join(e,n);try{b.rmSync(i,{force:!0}),Gi(e)}catch{}}}finally{await t()}},async release(){f(),n.delete(r)}}},dispose(){n.clear()}}},Ji=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,a,o,s=new Map,c=new Map,l=J.join(e,`index.json`),u=()=>{try{if(!b.statSync(l,{throwIfNoEntry:!1}))return{ids:{}};let e=b.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=J.join(e,n);try{let e=b.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=Hi(i)),!a||a.mtime!==o||a.locked!==s.locked||a.pid!==s.pid){let e;e=!a||a.mtime!==o?JSON.parse(b.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{b.mkdirSync(e,{recursive:!0})}catch{}a=b.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 Yi({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=Xi}){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=re({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 Xi=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(B);return n.length===0||n.some(e=>d(e.output)&&e.output.outcome===`pending`)?!1:n.every(e=>e.state.startsWith(`output-`))},Zi=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function Qi(e){return typeof e==`object`&&e?.__blink_internal!==void 0}var $i=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=qi(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.watcher=Ji(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=>!Qi(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=>!B(e)||e.input!==``?e:{...e,input:{}})}));let a=performance.now(),o=await Yi({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 ea(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a}=e,o=de(null),[s,c]=W({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[]});U(()=>{o.current&&o.current.dispose();let e=new $i({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 ta(e){let t=j(e,`data`,`devhook.txt`);if(P(A(t),{recursive:!0}),N(t))return F(t,`utf-8`);let n=crypto.randomUUID();return I(t,n),n}const na=(e,t)=>e.json({error:t},400),ra=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}},ia=()=>new o,aa=ia().get(`/:key`,async e=>{let{key:t,err:n}=ra(e);if(n)return na(e,n);let r=await e.env.store.get(t);return e.json({value:r},200)}).post(`/:key`,g(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?na(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:na(t,`Value must be a string`):na(t,`Value is required`)}),async e=>{let{key:t,err:n}=ra(e);if(n)return na(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}=ra(e);return n?na(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})}),oa=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`}},sa=g(`param`,e=>({id:e.id})),ca=ia().post(`/:key`,async e=>{let{key:t,err:n}=oa(e);return n?na(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,sa,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,sa,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.getMessages(t),200)}).post(`/:id/sendMessages`,g(`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)):na(e,`ID is required`)}).delete(`/:id/messages`,sa,g(`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`,sa,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,sa,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,sa,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),la=ia().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),ua=new o().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,aa).route(`/chat`,ca).route(`/otlp`,la);var da=/^(?:[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 fa(e){return typeof e==`string`&&da.test(e)}var pa=fa;function ma(e){if(!pa(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 ha=ma;const ga=[];for(let e=0;e<256;++e)ga.push((e+256).toString(16).slice(1));function _a(e,t=0){return(ga[e[t+0]]+ga[e[t+1]]+ga[e[t+2]]+ga[e[t+3]]+`-`+ga[e[t+4]]+ga[e[t+5]]+`-`+ga[e[t+6]]+ga[e[t+7]]+`-`+ga[e[t+8]]+ga[e[t+9]]+`-`+ga[e[t+10]]+ga[e[t+11]]+ga[e[t+12]]+ga[e[t+13]]+ga[e[t+14]]+ga[e[t+15]]).toLowerCase()}function va(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 ya(e,t,n,r,i,a){let o=typeof n==`string`?va(n):n,s=typeof r==`string`?ha(r):r;if(typeof r==`string`&&(r=ha(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 _a(c)}function ba(e){return Array.isArray(e)?e=Buffer.from(e):typeof e==`string`&&(e=Buffer.from(e,`utf8`)),D(`sha1`).update(e).digest()}var xa=ba;function Sa(e,t,n,r){return ya(80,xa,e,t,n,r)}Sa.DNS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,Sa.URL=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;var Ca=Sa;function wa(e){let t=ge(e.dataDirectory,`chats`),n={},r=ge(e.dataDirectory,`storage.json`);b.existsSync(r)&&(n=JSON.parse(b.readFileSync(r,`utf-8`)));let i=new Map,a=n=>{let r=i.get(n);return r||(r=new $i({chatId:n,chatsDirectory:t}),r.setAgent(e.getAgent()),i.set(n,r)),r},o={async upsert(e){let t=Ca(JSON.stringify(e),Ca.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=>Zi(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,b.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},delete(e){return delete n[e],b.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=k(u(e=>ua.fetch(e,{chat:o,store:s})));c.listen(e.port??0);let l=qi(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 Ta({agent:e,capabilities:t,messages:n}){let[r,i]=W(void 0),[a,o]=W(!0),[s,c]=W(void 0),l=de(s);U(()=>{l.current=s},[s]);let[u,d]=W(()=>f(n));U(()=>{d(e=>{let t=f(n);return JSON.stringify(t)===JSON.stringify(e)?e:t})},[n]);let[p,m]=W(void 0),h=H((e,t)=>{if(!l.current)return!1;let n=l.current[e];return n?n.values.some(e=>e.id===t):!1},[]),g=H(e=>{m(t=>{let n={...u,...t,...e};for(let[e,t]of Object.entries(n))h(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,h]);U(()=>{if(!u&&!s){m(void 0);return}g()},[u,s,g]);let _=de(void 0),v=de(void 0);U(()=>{e!==v.current&&(v.current=e,c(void 0),m(void 0),i(void 0),o(!0),_.current=void 0)},[e]),U(()=>{if(t&&!t.ui||!e){c(void 0),m(void 0),i(void 0),_.current=void 0;return}let n=p?JSON.stringify(p):``;if(_.current===n){o(!1),i(void 0);return}let r=new AbortController;return o(!0),i(void 0),e.ui(p?{selectedOptions:p}:{},{signal:r.signal}).then(e=>{if(!e){c(void 0);return}r.signal.aborted||(c(t=>JSON.stringify(t)===JSON.stringify(e)?t:e),_.current=n)}).catch(e=>{r.signal.aborted||i(e instanceof Error?e:Error(String(e)))}).finally(()=>{o(!1)}),()=>{r.abort()}},[e,t,p]);let y=H((e,t)=>{g({[e]:t})},[g]);return{schema:s,options:p,setOption:y,loading:a,error:r}}function Ea(e){let t=de(e.onRequest);U(()=>{t.current=e.onRequest},[e.onRequest]);let n=de(e.id??crypto.randomUUID()),[r,i]=W(`disconnected`);return U(()=>{if(e.disabled){i(`disconnected`);return}let r=!1,a,o,s=!1,c=()=>{if(!(r||s)){if(s=!0,a){try{a.dispose()}catch{}a=void 0}a=new Vn({baseURL:`https://blink.so`}).devhook.listen({id:n.current,onRequest:async e=>t.current(e),onConnect:()=>{s=!1,i(`connected`)},onDisconnect:()=>{s=!1,i(`disconnected`),!r&&!o&&(o=setTimeout(()=>{o=void 0,c()},2e3))},onError:e=>{s=!1,i(`error`),!r&&!o&&(o=setTimeout(()=>{o=void 0,c()},2e3))}})}};return c(),()=>{if(r=!0,o&&=(clearTimeout(o),void 0),a){try{a.dispose()}catch{}a=void 0}}},[e.disabled]),{id:n.current,status:r}}var Da=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}}})),Oa=r(e(((e,t)=>{let r=n(`fs`),i=n(`path`),a=n(`os`),o=n(`crypto`),s=Da().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,`
|
|
39
|
+
`)},info:e=>Nr.message(e,{symbol:xr.default.blue(Dr)}),success:e=>Nr.message(e,{symbol:xr.default.green(Or)}),step:e=>Nr.message(e,{symbol:xr.default.green(Tr)}),warn:e=>Nr.message(e,{symbol:xr.default.yellow(kr)}),warning:e=>Nr.warn(e),error:e=>Nr.message(e,{symbol:xr.default.red(Ar)})};let Pr;function Fr(){try{return x.statSync(`/.dockerenv`),!0}catch{return!1}}function Ir(){try{return x.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function Lr(){return Pr===void 0&&(Pr=Fr()||Ir()),Pr}let Rr;const zr=()=>{try{return x.statSync(`/run/.containerenv`),!0}catch{return!1}};function Br(){return Rr===void 0&&(Rr=zr()||Lr()),Rr}const Vr=()=>{if(L.platform!==`linux`)return!1;if(Se.release().toLowerCase().includes(`microsoft`))return!Br();try{return x.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!Br():!1}catch{return!1}};var Hr=L.env.__IS_WSL_TEST__?Vr:Vr();const Ur=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await be.access(n,xe.F_OK),r=!0}catch{}if(!r)return e;let i=await be.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}})(),Wr=async()=>`${await Ur()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Gr=async()=>Hr?Wr():`${L.env.SYSTEMROOT||L.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function Kr(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 qr=T(ve);async function Jr(){if(L.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await qr(`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 Yr=T(ve);async function Xr(e,{humanReadableOutput:t=!0,signal:n}={}){if(L.platform!==`darwin`)throw Error(`macOS only`);let r=t?[]:[`-ss`],i={};n&&(i.signal=n);let{stdout:a}=await Yr(`osascript`,[`-e`,e,r],i);return a.trim()}async function Zr(e){return Xr(`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 Qr=T(ve),$r={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 ei=class extends Error{};async function ti(e=Qr){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 ei(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=$r[r];if(!i)throw new ei(`Unknown browser ID: ${r}`);return i}const ni=T(ve),ri=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function ii(){if(L.platform===`darwin`){let e=await Jr();return{name:await Zr(e),id:e}}if(L.platform===`linux`){let{stdout:e}=await ni(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:ri(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(L.platform===`win32`)return ti();throw Error(`Only macOS, Linux, and Windows are supported`)}const ai=T(_e.execFile),oi=he.dirname(C(import.meta.url)),si=he.join(oi,`xdg-open`),{platform:ci,arch:li}=L;async function ui(){let e=await Gr(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=y.from(t,`utf16le`).toString(`base64`),{stdout:r}=await ai(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 di=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},fi=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return di(e.app,t=>fi({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return di(t,t=>fi({...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=Hr?await ui():await ii();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),fi({...e,app:{name:gi[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,i=[],a={};if(ci===`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(ci===`win32`||Hr&&!Br()&&!t){r=await Gr(),i.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),Hr||(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=y.from(o.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!oi||oi===`/`,t=!1;try{await be.access(si,xe.X_OK),t=!0}catch{}r=L.versions.electron??(ci===`android`||e||!t)?`xdg-open`:si}n.length>0&&i.push(...n),e.wait||(a.stdio=`ignore`,a.detached=!0)}ci===`darwin`&&n.length>0&&i.push(`--args`,...n),e.target&&i.push(e.target);let o=_e.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)},pi=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return fi({...t,target:e})};function mi(e){if(typeof e==`string`||Array.isArray(e))return e;let{[li]:t}=e;if(!t)throw Error(`${li} is not supported`);return t}function hi({[ci]:e},{wsl:t}){if(t&&Hr)return mi(t);if(!e)throw Error(`${ci} is not supported`);return mi(e)}const gi={};Kr(gi,`chrome`,()=>hi({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`]}})),Kr(gi,`brave`,()=>hi({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`]}})),Kr(gi,`firefox`,()=>hi({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),Kr(gi,`edge`,()=>hi({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),Kr(gi,`browser`,()=>`browser`),Kr(gi,`browserPrivate`,()=>`browserPrivate`);var _i=pi;function vi(e){let t=e||xi();if(N(t)){let e=F(t,`utf8`);return JSON.parse(e).token}}function yi(e,t){let n=t||xi();N(A(n))||P(A(n),{recursive:!0}),I(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function bi(e){let t=e||xi();N(t)&&ee(t)}function xi(){let e=Xn(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return j(e[0],`auth.json`)}function Si(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=W(),[s,c]=W(()=>vi(i)),[l,u]=W(),d=de(n),f=de(r);U(()=>{d.current=n,f.current=r},[n,r]);let p=H(async()=>{u(void 0);try{let e=vi(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new Vn({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 Vn,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();yi(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(()=>{bi(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 Ci(e){let{directory:t,onBuildStart:n,onBuildSuccess:r,onBuildError:i}=typeof e==`string`?{directory:e}:e,a=ue(()=>_(t),[t]),[o,s]=W(void 0),[c,l]=W(void 0),[u,d]=W(`building`),f=de(n),p=de(r),m=de(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]),ue(()=>({error:o,status:u,result:c,entry:a.entry,outdir:a.outdir}),[o,u,c,a.entry,a.outdir])}function wi(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function Ti(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const Ei=/^\.+(\\|\/)|^\.+$/,Di=/[. ]+$/,Oi=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,ki=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,Ai=e=>e===``,ji=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,Mi=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let Ni;function Pi(){return Ni??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),Ni}function Fi(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(wi().test(n)||[...n].some(e=>ki.test(e)&&!Ai(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(Mi,` `),n.length>0&&(e=e.replaceAll(ji,`$1`)),e=e.replace(Di,``),e=e.replace(Ei,n),e=e.replace(wi(),n),e=e.replaceAll(Oi,e=>Ai(e)?e:n),e.length===0&&(e=n),e=Ti().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=Ii(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=Ii(n,a)+i}}return e}function Ii(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of Pi().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function Li(e){return`${e}.lock`}function Ri(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function zi(e,t={}){let n=Li(e),r=process.pid.toString();try{return b.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(b.readFileSync(n,`utf8`),10)}catch{return b.unlinkSync(n),zi(e,{...t,stale:0})}if(!Ri(i))try{return b.unlinkSync(n),zi(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return zi(e,{...t,stale:0});throw n}return!1}}async function Bi(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=J.resolve(e),i=0;for(;i<=n.retries;){if(zi(r,n))return()=>Vi(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 Vi(e){let t=J.resolve(e),n=Li(t);try{if(parseInt(b.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}b.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function Hi(e){let t=J.resolve(e),n=Li(t);try{if(!b.existsSync(n))return{locked:!1};let e=b.readFileSync(n,`utf8`),t=parseInt(e,10);return Ri(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const Ui=e=>{b.mkdirSync(e,{recursive:!0})},Wi=e=>{try{b.fdatasyncSync(e)}catch{}try{b.closeSync(e)}catch{}},Gi=e=>{try{let t=b.openSync(e,`r`);try{b.fsyncSync(t)}finally{b.closeSync(t)}}catch{}},Ki=(e,t)=>{let n=J.dirname(e);Ui(n);let r=J.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=b.openSync(r,`w`),b.writeFileSync(i,t,`utf-8`),Wi(i),i=void 0,b.renameSync(r,e),Gi(e),Gi(n)}catch(e){if(i!==void 0)try{b.closeSync(i)}catch{}try{b.rmSync(r,{force:!0})}catch{}throw e}},qi=(e,t)=>{let n=new Map,r,i=e=>{if(b.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(b.readFileSync(e,`utf-8`))},a=(e,t)=>{Ki(e,JSON.stringify(t,null,2))},o=async()=>{if(r)throw Error(`Index is already locked`);let t=J.join(e,`index.json`);Ui(e),b.existsSync(t)||b.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await Bi(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},s=async()=>{let t=J.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},c=async t=>{let n=J.join(e,`index.json`);a(n,t)},l=async t=>{let n=(await s()).ids[t];if(n)return J.join(e,n)},u=async t=>{let n=(await s()).ids[t];if(!n)return;let r=J.join(e,n);if(b.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(b.readFileSync(r,`utf-8`))},d=async n=>{let r=n[t],i=String(r),l=Fi(i,{replacement:`_`})+`.json`,u=await o();try{let t=await s();t.ids[i]=l,t.current=i;let r=J.join(e,l);a(r,n),await c(t)}finally{await u()}};return{async get(e){return await u(e)},async list(){if(!b.statSync(e,{throwIfNoEntry:!1}))return[];let t=await s(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=J.join(e,i),a=b.statSync(t,{throwIfNoEntry:!1});if(!a)continue;let o=Hi(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=Fi(r,{replacement:`_`})+`.json`,n=await o();try{let n=await s();n.ids[r]=t;let i=J.join(e,t);Ui(e),b.writeFileSync(i,JSON.stringify({}),`utf-8`),await c(n),a=i}finally{await n()}}if(i?.force){let e=Hi(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 Bi(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=J.join(e,n);try{b.rmSync(i,{force:!0}),Gi(e)}catch{}}}finally{await t()}},async release(){f(),n.delete(r)}}},dispose(){n.clear()}}},Ji=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,a,o,s=new Map,c=new Map,l=J.join(e,`index.json`),u=()=>{try{if(!b.statSync(l,{throwIfNoEntry:!1}))return{ids:{}};let e=b.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=J.join(e,n);try{let e=b.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=Hi(i)),!a||a.mtime!==o||a.locked!==s.locked||a.pid!==s.pid){let e;e=!a||a.mtime!==o?JSON.parse(b.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{b.mkdirSync(e,{recursive:!0})}catch{}a=b.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 Yi({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=Xi}){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=re({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 Xi=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(B);return n.length===0||n.some(e=>d(e.output)&&e.output.outcome===`pending`)?!1:n.every(e=>e.state.startsWith(`output-`))},Zi=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function Qi(e){return typeof e==`object`&&e?.__blink_internal!==void 0}var $i=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=qi(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.watcher=Ji(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=>!Qi(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=>!B(e)||e.input!==``?e:{...e,input:{}})}));let a=performance.now(),o=await Yi({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 ea(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a}=e,o=de(null),[s,c]=W({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[]});U(()=>{o.current&&o.current.dispose();let e=new $i({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 ta(e){let t=j(e,`data`,`devhook.txt`);if(P(A(t),{recursive:!0}),N(t))return F(t,`utf-8`);let n=crypto.randomUUID();return I(t,n),n}const na=(e,t)=>e.json({error:t},400),ra=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}},ia=()=>new s,aa=ia().get(`/:key`,async e=>{let{key:t,err:n}=ra(e);if(n)return na(e,n);let r=await e.env.store.get(t);return e.json({value:r},200)}).post(`/:key`,g(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?na(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:na(t,`Value must be a string`):na(t,`Value is required`)}),async e=>{let{key:t,err:n}=ra(e);if(n)return na(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}=ra(e);return n?na(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})}),oa=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`}},sa=g(`param`,e=>({id:e.id})),ca=ia().post(`/:key`,async e=>{let{key:t,err:n}=oa(e);return n?na(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,sa,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,sa,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.getMessages(t),200)}).post(`/:id/sendMessages`,g(`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)):na(e,`ID is required`)}).delete(`/:id/messages`,sa,g(`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`,sa,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,sa,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,sa,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),la=ia().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),ua=new s().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,aa).route(`/chat`,ca).route(`/otlp`,la);var da=/^(?:[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 fa(e){return typeof e==`string`&&da.test(e)}var pa=fa;function ma(e){if(!pa(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 ha=ma;const ga=[];for(let e=0;e<256;++e)ga.push((e+256).toString(16).slice(1));function _a(e,t=0){return(ga[e[t+0]]+ga[e[t+1]]+ga[e[t+2]]+ga[e[t+3]]+`-`+ga[e[t+4]]+ga[e[t+5]]+`-`+ga[e[t+6]]+ga[e[t+7]]+`-`+ga[e[t+8]]+ga[e[t+9]]+`-`+ga[e[t+10]]+ga[e[t+11]]+ga[e[t+12]]+ga[e[t+13]]+ga[e[t+14]]+ga[e[t+15]]).toLowerCase()}function va(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 ya(e,t,n,r,i,a){let o=typeof n==`string`?va(n):n,s=typeof r==`string`?ha(r):r;if(typeof r==`string`&&(r=ha(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 _a(c)}function ba(e){return Array.isArray(e)?e=Buffer.from(e):typeof e==`string`&&(e=Buffer.from(e,`utf8`)),D(`sha1`).update(e).digest()}var xa=ba;function Sa(e,t,n,r){return ya(80,xa,e,t,n,r)}Sa.DNS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,Sa.URL=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;var Ca=Sa;function wa(e){let t=ge(e.dataDirectory,`chats`),n={},r=ge(e.dataDirectory,`storage.json`);b.existsSync(r)&&(n=JSON.parse(b.readFileSync(r,`utf-8`)));let i=new Map,a=n=>{let r=i.get(n);return r||(r=new $i({chatId:n,chatsDirectory:t}),r.setAgent(e.getAgent()),i.set(n,r)),r},o={async upsert(e){let t=Ca(JSON.stringify(e),Ca.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=>Zi(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,b.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},delete(e){return delete n[e],b.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=k(u(e=>ua.fetch(e,{chat:o,store:s})));c.listen(e.port??0);let l=qi(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 Ta({agent:e,capabilities:t,messages:n}){let[r,i]=W(void 0),[a,o]=W(!0),[s,c]=W(void 0),l=de(s);U(()=>{l.current=s},[s]);let[u,d]=W(()=>f(n));U(()=>{d(e=>{let t=f(n);return JSON.stringify(t)===JSON.stringify(e)?e:t})},[n]);let[p,m]=W(void 0),h=H((e,t)=>{if(!l.current)return!1;let n=l.current[e];return n?n.values.some(e=>e.id===t):!1},[]),g=H(e=>{m(t=>{let n={...u,...t,...e};for(let[e,t]of Object.entries(n))h(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,h]);U(()=>{if(!u&&!s){m(void 0);return}g()},[u,s,g]);let _=de(void 0),v=de(void 0);U(()=>{e!==v.current&&(v.current=e,c(void 0),m(void 0),i(void 0),o(!0),_.current=void 0)},[e]),U(()=>{if(t&&!t.ui||!e){c(void 0),m(void 0),i(void 0),_.current=void 0;return}let n=p?JSON.stringify(p):``;if(_.current===n){o(!1),i(void 0);return}let r=new AbortController;return o(!0),i(void 0),e.ui(p?{selectedOptions:p}:{},{signal:r.signal}).then(e=>{if(!e){c(void 0);return}r.signal.aborted||(c(t=>JSON.stringify(t)===JSON.stringify(e)?t:e),_.current=n)}).catch(e=>{r.signal.aborted||i(e instanceof Error?e:Error(String(e)))}).finally(()=>{o(!1)}),()=>{r.abort()}},[e,t,p]);let y=H((e,t)=>{g({[e]:t})},[g]);return{schema:s,options:p,setOption:y,loading:a,error:r}}function Ea(e){let t=de(e.onRequest);U(()=>{t.current=e.onRequest},[e.onRequest]);let n=de(e.id??crypto.randomUUID()),[r,i]=W(`disconnected`);return U(()=>{if(e.disabled){i(`disconnected`);return}let r=!1,a,o,s=!1,c=()=>{if(!(r||s)){if(s=!0,a){try{a.dispose()}catch{}a=void 0}a=new Vn({baseURL:`https://blink.so`}).devhook.listen({id:n.current,onRequest:async e=>t.current(e),onConnect:()=>{s=!1,i(`connected`)},onDisconnect:()=>{s=!1,i(`disconnected`),!r&&!o&&(o=setTimeout(()=>{o=void 0,c()},2e3))},onError:e=>{s=!1,i(`error`),!r&&!o&&(o=setTimeout(()=>{o=void 0,c()},2e3))}})}};return c(),()=>{if(r=!0,o&&=(clearTimeout(o),void 0),a){try{a.dispose()}catch{}a=void 0}}},[e.disabled]),{id:n.current,status:r}}var Da=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}}})),Oa=r(e(((e,t)=>{let r=n(`fs`),i=n(`path`),a=n(`os`),o=n(`crypto`),s=Da().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,`
|
|
40
40
|
`);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,`
|
|
41
41
|
`),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 n of e.path)r.existsSync(n)&&(t=n.endsWith(`.vault`)?n:`${n}.vault`);else t=e.path.endsWith(`.vault`)?e.path:`${e.path}.vault`;else t=i.resolve(process.cwd(),`.env.vault`);return r.existsSync(t)?t:null}function S(e){return e[0]===`~`?i.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=i.resolve(process.cwd(),`.env`),n=`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?n=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 i=O.parse(r.readFileSync(t,{encoding:n}));O.populate(p,i,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=i.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}))(),1);async function ka(e,t){let n=e;for(;n!==A(n);){let e=j(n,t);try{return await se(e),e}catch{}n=A(n)}}function Aa(e,t=`.env.local`){let[n,r]=W({});return U(()=>{let n,i=e=>{try{let t=F(e,`utf-8`),n=(0,Oa.parse)(t);r(n)}catch(e){console.error(`Error reading ${t}:`,e),r({})}};return ka(e,t).then(e=>{if(!e){r({});return}i(e),n=te(e,{persistent:!1},()=>{i(e)})}),()=>{n&&n.close()}},[e,t]),n}const ja=(e,t)=>{let n=typeof e==`string`;typeof e==`string`&&(e=t.encode(e));let r=new Uint8Array(1+e.byteLength);return r[0]=n?0:1,r.set(new Uint8Array(e),1),r},Ma=(e,t)=>e[0]===0?t.decode(e.subarray(1)):new Uint8Array(e.subarray(1));let Na=function(e){return e[e.REQUEST=0]=`REQUEST`,e[e.PROXY_INIT=1]=`PROXY_INIT`,e[e.PROXY_BODY=2]=`PROXY_BODY`,e[e.PROXY_WEBSOCKET_MESSAGE=3]=`PROXY_WEBSOCKET_MESSAGE`,e[e.PROXY_WEBSOCKET_CLOSE=4]=`PROXY_WEBSOCKET_CLOSE`,e}({}),Pa=function(e){return e[e.RESPONSE=0]=`RESPONSE`,e[e.NOTIFICATION=1]=`NOTIFICATION`,e[e.PROXY_INIT=2]=`PROXY_INIT`,e[e.PROXY_DATA=3]=`PROXY_DATA`,e[e.PROXY_WEBSOCKET_MESSAGE=4]=`PROXY_WEBSOCKET_MESSAGE`,e[e.PROXY_WEBSOCKET_CLOSE=5]=`PROXY_WEBSOCKET_CLOSE`,e}({});const Fa={[Na.REQUEST]:q.string(),[Na.PROXY_INIT]:q.object({method:q.string(),headers:q.record(q.string(),q.string()),url:q.string()}),[Na.PROXY_BODY]:q.instanceof(Uint8Array),[Na.PROXY_WEBSOCKET_MESSAGE]:q.object({type:q.enum([`text`,`binary`]),data:q.instanceof(Uint8Array)}),[Na.PROXY_WEBSOCKET_CLOSE]:q.object({code:q.number().optional(),reason:q.string().optional()})};Pa.RESPONSE,q.string(),Pa.NOTIFICATION,q.string(),Pa.PROXY_INIT,q.object({status_code:q.number(),status_message:q.string(),headers:q.record(q.string(),q.string())}),Pa.PROXY_DATA,q.instanceof(Uint8Array),Pa.PROXY_WEBSOCKET_MESSAGE,q.instanceof(Uint8Array),Pa.PROXY_WEBSOCKET_CLOSE,q.object({code:q.number(),reason:q.string()}),Na.PROXY_INIT,q.string(),q.record(q.string(),q.string()),q.string();const Ia={process_execute:q.object({command:q.string(),args:q.array(q.string()),env_file:q.string().optional(),env:q.record(q.string(),q.string()).optional(),cwd:q.string().optional()}),process_send_input:q.object({pid:q.number(),data:q.string()}),process_wait:q.object({pid:q.number(),output_idle_timeout_ms:q.number().optional(),timeout_ms:q.number().optional()}),process_list:q.object({include_dead:q.boolean().optional()}),process_read_plain_output:q.object({pid:q.number(),start_line:q.number().optional(),end_line:q.number().optional()}),process_kill:q.object({pid:q.number(),signal:q.string().optional()}),set_env:q.object({env:q.record(q.string(),q.string())}),read_file:q.object({path:q.string(),line_start:q.number().optional(),line_end:q.number().optional()}),write_file:q.object({path:q.string(),content:q.string(),base64:q.boolean().optional(),mode:q.number().optional()}),read_directory:q.object({path:q.string()}),watch_directory:q.object({path:q.string()}),deploy_static_files:q.object({path:q.string()})},La=q.object({pid:q.number(),command:q.string(),args:q.array(q.string()),title:q.string().optional(),cwd:q.string(),env:q.record(q.string(),q.string()),exit_code:q.number().optional(),exit_signal:q.number().optional(),duration_ms:q.number().optional(),output_total_lines:q.number()});La.extend({ansi_output:q.string(),plain_output:q.object({lines:q.array(q.string()),total_lines:q.number()})}),q.object({pid:q.number()}),q.object({}),q.object({processes:q.array(La)}),q.object({lines:q.array(q.string()),total_lines:q.number(),duration_ms:q.number(),exit_code:q.number().optional(),exit_signal:q.number().optional()}),q.object({}),q.object({}),q.object({total_lines:q.number(),lines_read:q.number(),start_line:q.number(),content:q.string(),mime_type:q.string()}),q.object({}),q.object({entries:q.array(q.object({name:q.string(),type:q.enum([`file`,`directory`,`symlink`])}))}),q.object({}),q.object({deployment_id:q.string()});const Ra=q.object({type:q.enum([`create`,`update`,`delete`]),path:q.string()}),za=q.object({type:q.enum([`context`,`added`,`deleted`]),content:q.string(),oldLineNumber:q.number().optional(),newLineNumber:q.number().optional()}),Ba=q.object({oldStart:q.number(),oldLines:q.number(),newStart:q.number(),newLines:q.number(),lines:q.array(za)}),Va=q.object({path:q.string(),status:q.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),oldPath:q.string().optional(),insertions:q.number(),deletions:q.number(),chunks:q.array(Ba)}),Ha=q.object({totalFiles:q.number(),totalInsertions:q.number(),totalDeletions:q.number(),netChange:q.number(),startHash:q.string().optional(),currentHash:q.string().optional(),timespan:q.number(),files:q.array(Va)}),Ua=q.object({path:q.string(),status:q.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),staged:q.boolean()}),Wa=q.object({hash:q.string(),shortHash:q.string(),message:q.string(),author:q.string(),email:q.string(),date:q.date(),timestamp:q.date(),filesChanged:q.number(),insertions:q.number(),deletions:q.number(),commitDiff:q.array(Va).optional()});q.object({files:q.array(Ua),branch:q.string(),ahead:q.number(),behind:q.number(),timestamp:q.date(),sessionDiff:Ha.optional(),workingDirectoryDiff:Ha.optional(),newCommits:q.array(Wa),currentCommit:q.object({hash:q.string(),shortHash:q.string(),message:q.string(),author:q.string(),date:q.date()}).optional(),diffSkipped:q.boolean().optional(),payloadTruncated:q.boolean().optional(),estimatedSizeKB:q.number().optional()}),q.object({debounceDelay:q.number().optional(),gitStatusInterval:q.number().optional(),ignoreDotfiles:q.boolean().optional(),ignored:q.array(q.string()).optional(),watchGit:q.boolean().optional(),includeDiffs:q.boolean().optional(),maxDiffFiles:q.number().optional(),maxPayloadSizeKB:q.number().optional(),truncateLargeDiffs:q.boolean().optional()}),q.object({status:La}),q.object({pid:q.number(),output:q.string()}),q.object({changes:q.array(Ra)});var Ga=class{notificationCallbacks=new Map;disposables=[];requestHandlers=new Map;send;jwt;requestTimeoutMS;constructor({send:e,jwt:t,requestTimeoutMS:n}){this.send=e,this.jwt=t,this.requestTimeoutMS=n}handleMessage(e){if(typeof e!=`string`)return;let t=JSON.parse(e);if(`id`in t){let e=this.requestHandlers.get(t.id);if(!e)return;e(t.payload,t.error)}else if(`type`in t)this.notificationCallbacks.get(t.type)?.forEach(e=>{e(t.payload)});else return}dispose(e){this.disposables.forEach(t=>t.dispose(e))}async request(e,t,n){let r=crypto.randomUUID(),i,a,o=new Promise((e,t)=>{i=e,a=t}),s={dispose:e=>{l();let t=`Client was disposed!`;e&&(t+=` Reason: ${e}`),a(Error(t))}};this.disposables.push(s);let c;this.requestTimeoutMS&&(c=setTimeout(()=>{a(Error(`Request timed out`))},this.requestTimeoutMS));let l=()=>{this.disposables.splice(this.disposables.indexOf(s),1),this.requestHandlers.delete(r),c&&clearTimeout(c)};n?.signal&&n.signal.addEventListener(`abort`,()=>{l(),a(n.signal?.reason)}),this.requestHandlers.set(r,(e,t)=>{if(l(),t)return a(Error(t));i(e)});let u={id:r,type:e,payload:t,jwt:this.jwt};return this.send(JSON.stringify(u)),o}onNotification(e,t){let n=this.notificationCallbacks.get(e)??[];return n.push(t),this.notificationCallbacks.set(e,n),{dispose:()=>{let n=this.notificationCallbacks.get(e)??[],r=n.indexOf(t);r!==-1&&n.splice(r,1)}}}},Ka=e(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),qa=e(((e,t)=>{let{EMPTY_BUFFER:r}=Ka(),i=Buffer[Symbol.species];function a(e,t){if(e.length===0)return r;if(e.length===1)return e[0];let n=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let r=e[t];n.set(r,a),a+=r.length}return a<t?new i(n.buffer,n.byteOffset,a):n}function o(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function s(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function c(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function l(e){if(l.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new i(e):ArrayBuffer.isView(e)?t=new i(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),l.readOnly=!1),t}if(t.exports={concat:a,mask:o,toArrayBuffer:c,toBuffer:l,unmask:s},!process.env.WS_NO_BUFFER_UTIL)try{let e=n(`bufferutil`);t.exports.mask=function(t,n,r,i,a){a<48?o(t,n,r,i,a):e.mask(t,n,r,i,a)},t.exports.unmask=function(t,n){t.length<32?s(t,n):e.unmask(t,n)}}catch{}})),Ja=e(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),Ya=e(((e,t)=>{let r=n(`zlib`),i=qa(),a=Ja(),{kStatusCode:o}=Ka(),s=Buffer[Symbol.species],c=Buffer.from([0,0,255,255]),l=Symbol(`permessage-deflate`),u=Symbol(`total-length`),d=Symbol(`callback`),f=Symbol(`buffers`),p=Symbol(`error`),m;t.exports=class{constructor(e,t,n){if(this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!m){let e=this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit;m=new a(e)}}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[d];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){m.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){m.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,n){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:r.Z_DEFAULT_WINDOWBITS;this._inflate=r.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[l]=this,this._inflate[u]=0,this._inflate[f]=[],this._inflate.on(`error`,_),this._inflate.on(`data`,g)}this._inflate[d]=n,this._inflate.write(e),t&&this._inflate.write(c),this._inflate.flush(()=>{let e=this._inflate[p];if(e){this._inflate.close(),this._inflate=null,n(e);return}let r=i.concat(this._inflate[f],this._inflate[u]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[u]=0,this._inflate[f]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),n(null,r)})}_compress(e,t,n){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:r.Z_DEFAULT_WINDOWBITS;this._deflate=r.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[u]=0,this._deflate[f]=[],this._deflate.on(`data`,h)}this._deflate[d]=n,this._deflate.write(e),this._deflate.flush(r.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=i.concat(this._deflate[f],this._deflate[u]);t&&(e=new s(e.buffer,e.byteOffset,e.length-4)),this._deflate[d]=null,this._deflate[u]=0,this._deflate[f]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),n(null,e)})}};function h(e){this[f].push(e),this[u]+=e.length}function g(e){if(this[u]+=e.length,this[l]._maxPayload<1||this[u]<=this[l]._maxPayload){this[f].push(e);return}this[p]=RangeError(`Max payload size exceeded`),this[p].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[p][o]=1009,this.removeListener(`data`,g),this.reset()}function _(e){if(this[l]._inflate=null,this[p]){this[d](this[p]);return}e[o]=1007,this[d](e)}})),Xa=e(((e,t)=>{let{isUtf8:r}=n(`buffer`),{hasBlob:i}=Ka(),a=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function o(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function s(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function c(e){return i&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:c,isValidStatusCode:o,isValidUTF8:s,tokenChars:a},r)t.exports.isValidUTF8=function(e){return e.length<24?s(e):r(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=n(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?s(t):e(t)}}catch{}})),Za=e(((e,t)=>{let{Writable:r}=n(`stream`),i=Ya(),{BINARY_TYPES:a,EMPTY_BUFFER:o,kStatusCode:s,kWebSocket:c}=Ka(),{concat:l,toArrayBuffer:u,unmask:d}=qa(),{isValidStatusCode:f,isValidUTF8:p}=Xa(),m=Buffer[Symbol.species];t.exports=class extends r{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||a[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[c]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new m(t.buffer,t.byteOffset+e,t.length-e),new m(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new m(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){let t=this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`);e(t);return}let n=(t[0]&64)==64;if(n&&!this._extensions[i.extensionName]){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(!this._fragmented){let t=this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let t=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let t=this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`);e(t);return}if(n){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let t=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`);e(t);return}}else{let t=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){let t=this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`);e(t);return}}else if(this._masked){let t=this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`);e(t);return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){let t=this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`);e(t);return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`);e(t);return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=o;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&d(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[i.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let e=this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`);t(e);return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?l(n,t):this._binaryType===`arraybuffer`?u(l(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=l(n,t);if(!this._skipUTF8Validation&&!p(r)){let t=this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`);e(t);return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,o),this.end();else{let n=e.readUInt16BE(0);if(!f(n)){let e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`);t(e);return}let r=new m(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!p(r)){let e=this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`);t(e);return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[s]=r,a}}})),Qa=e(((e,t)=>{let{Duplex:r}=n(`stream`),{randomFillSync:i}=n(`crypto`),a=Ya(),{EMPTY_BUFFER:o,kWebSocket:s,NOOP:c}=Ka(),{isBlob:l,isValidStatusCode:u}=Xa(),{mask:d,toBuffer:f}=qa(),p=Symbol(`kByteLength`),m=Buffer.alloc(4),h=8*1024,g,_=h;t.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=c,this[s]=void 0}static frame(e,t){let n,r=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||m,t.generateMask?t.generateMask(n):(_===h&&(g===void 0&&(g=Buffer.alloc(h)),i(g,0,h),_=0),n[0]=g[_++],n[1]=g[_++],n[2]=g[_++],n[3]=g[_++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[p]!==void 0?s=t[p]:(e=Buffer.from(e),s=e.length):(s=e.length,r=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(r?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:r?(d(e,n,l,a,s),[l]):(d(e,n,e,0,s),[l,e])}close(t,n,r,i){let a;if(t===void 0)a=o;else if(typeof t!=`number`||!u(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)a=Buffer.allocUnsafe(2),a.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);a=Buffer.allocUnsafe(2+e),a.writeUInt16BE(t,0),typeof n==`string`?a.write(n,2):a.set(n,2)}let s={[p]:a.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(a,s),i):this.enqueue([this.dispatch,a,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):l(t)?(i=t.size,a=!1):(t=f(t),i=t.length,a=f.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[p]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};l(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):l(t)?(i=t.size,a=!1):(t=f(t),i=t.length,a=f.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[p]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};l(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[a.extensionName],i=t.binary?2:1,o=t.compress,s,c;typeof e==`string`?(s=Buffer.byteLength(e),c=!1):l(e)?(s=e.size,c=!1):(e=f(e),s=e.length,c=f.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0);let u={[p]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};l(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[p],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(v,this,e,i);return}this._bufferedBytes-=r[p];let a=f(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(y,this,e,i)})}dispatch(t,n,r,i){if(!n){this.sendFrame(e.frame(t,r),i);return}let o=this._extensions[a.extensionName];this._bufferedBytes+=r[p],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){v(this,Error(`The socket was closed while data was being compressed`),i);return}this._bufferedBytes-=r[p],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),i),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][p],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][p],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function v(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function y(e,t,n){v(e,t,n),e.onerror(t)}})),$a=e(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=Ka(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,`target`,{enumerable:!0}),Object.defineProperty(f.prototype,`type`,{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,`code`,{enumerable:!0}),Object.defineProperty(p.prototype,`reason`,{enumerable:!0}),Object.defineProperty(p.prototype,`wasClean`,{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,`error`,{enumerable:!0}),Object.defineProperty(m.prototype,`message`,{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),eo=e(((e,t)=>{let{tokenChars:n}=Xa();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),to=e(((e,t)=>{let r=n(`events`),i=n(`https`),a=n(`http`),o=n(`net`),s=n(`tls`),{randomBytes:c,createHash:l}=n(`crypto`),{Duplex:u,Readable:d}=n(`stream`),{URL:f}=n(`url`),p=Ya(),m=Za(),h=Qa(),{isBlob:g}=Xa(),{BINARY_TYPES:_,EMPTY_BUFFER:v,GUID:y,kForOnEventAttribute:b,kListener:x,kStatusCode:S,kWebSocket:C,NOOP:w}=Ka(),{EventTarget:{addEventListener:T,removeEventListener:E}}=$a(),{format:D,parse:O}=eo(),{toBuffer:k}=qa(),A=Symbol(`kAborted`),j=[8,13],M=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],N=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var P=class e extends r{constructor(t,n,r){super(),this._binaryType=_[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=v,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),F(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){_.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new m({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new h(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[C]=this,a[C]=this,t[C]=this,i.on(`conclude`,R),i.on(`drain`,z),i.on(`error`,B),i.on(`message`,ie),i.on(`ping`,V),i.on(`pong`,ae),a.onerror=se,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,le),t.on(`data`,H),t.on(`end`,U),t.on(`error`,ue),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[p.extensionName]&&this._extensions[p.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){L(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),ce(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ne(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||v,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ne(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||v,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ne(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[p.extensionName]||(i.compress=!1),this._sender.send(t||v,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){L(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(P,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(P.prototype,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(P,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(P.prototype,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(P,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(P.prototype,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(P,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),Object.defineProperty(P.prototype,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(P.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(P.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[b])return t[x];return null},set(t){for(let t of this.listeners(e))if(t[b]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[b]:!0})}})}),P.prototype.addEventListener=T,P.prototype.removeEventListener=E,t.exports=P;function F(e,t,n,r){let o={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:j[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,!j.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${j.join(`, `)})`);let s;if(t instanceof f)s=t;else try{s=new f(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}s.protocol===`http:`?s.protocol=`ws:`:s.protocol===`https:`&&(s.protocol=`wss:`),e._url=s.href;let u=s.protocol===`wss:`,d=s.protocol===`ws+unix:`,m;if(s.protocol!==`ws:`&&!u&&!d?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:d&&!s.pathname?m=`The URL's pathname is empty`:s.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;ee(e,t);return}let h=u?443:80,g=c(16).toString(`base64`),_=u?i.request:a.request,v=new Set,b;if(o.createConnection=o.createConnection||(u?I:te),o.defaultPort=o.defaultPort||h,o.port=s.port||h,o.host=s.hostname.startsWith(`[`)?s.hostname.slice(1,-1):s.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=s.pathname+s.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(b=new p(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=D({[p.extensionName]:b.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!N.test(e)||v.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);v.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(s.username||s.password)&&(o.auth=`${s.username}:${s.password}`),d){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let x;if(o.followRedirects){if(e._redirects===0){e._originalIpc=d,e._originalSecure=u,e._originalHostOrSocketPath=d?o.socketPath:s.host;let t=r&&r.headers;if(r={...r,headers:{}},t)for(let[e,n]of Object.entries(t))r.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=d?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:s.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!r.headers.authorization&&(r.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),x=e._req=_(o),e._redirects&&e.emit(`redirect`,e.url,x)}else x=e._req=_(o);o.timeout&&x.on(`timeout`,()=>{L(e,x,`Opening handshake has timed out`)}),x.on(`error`,t=>{x===null||x[A]||(x=e._req=null,ee(e,t))}),x.on(`response`,i=>{let a=i.headers.location,s=i.statusCode;if(a&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){L(e,x,`Maximum redirects exceeded`);return}x.abort();let i;try{i=new f(a,t)}catch{let t=SyntaxError(`Invalid URL: ${a}`);ee(e,t);return}F(e,i,n,r)}else e.emit(`unexpected-response`,x,i)||L(e,x,`Unexpected server response: ${i.statusCode}`)}),x.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==P.CONNECTING)return;x=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){L(e,n,`Invalid Upgrade header`);return}let a=l(`sha1`).update(g+y).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){L(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],c;if(s===void 0?v.size&&(c=`Server sent no subprotocol`):v.size?v.has(s)||(c=`Server sent an invalid subprotocol`):c=`Server sent a subprotocol but none was requested`,c){L(e,n,c);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!b){L(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=O(u)}catch{L(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==p.extensionName){L(e,n,`Server indicated an extension that was not requested`);return}try{b.accept(t[p.extensionName])}catch{L(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[p.extensionName]=b}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(x,e):x.end()}function ee(e,t){e._readyState=P.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function te(e){return e.path=e.socketPath,o.connect(e)}function I(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=o.isIP(e.host)?``:e.host),s.connect(e)}function L(e,t,n){e._readyState=P.CLOSING;let r=Error(n);Error.captureStackTrace(r,L),t.setHeader?(t[A]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(ee,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function ne(e,t,n){if(t){let n=g(t)?t.size:k(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${M[e.readyState]})`);process.nextTick(n,t)}}function R(e,t){let n=this[C];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[C]!==void 0&&(n._socket.removeListener(`data`,H),process.nextTick(oe,n._socket),e===1005?n.close():n.close(e,t))}function z(){let e=this[C];e.isPaused||e._socket.resume()}function B(e){let t=this[C];t._socket[C]!==void 0&&(t._socket.removeListener(`data`,H),process.nextTick(oe,t._socket),t.close(e[S])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function re(){this[C].emitClose()}function ie(e,t){this[C].emit(`message`,e,t)}function V(e){let t=this[C];t._autoPong&&t.pong(e,!this._isServer,w),t.emit(`ping`,e)}function ae(e){this[C].emit(`pong`,e)}function oe(e){e.resume()}function se(e){let t=this[C];t.readyState!==P.CLOSED&&(t.readyState===P.OPEN&&(t._readyState=P.CLOSING,ce(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function ce(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),3e4)}function le(){let e=this[C];this.removeListener(`close`,le),this.removeListener(`data`,H),this.removeListener(`end`,U),e._readyState=P.CLOSING;let t;!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&(t=e._socket.read())!==null&&e._receiver.write(t),e._receiver.end(),this[C]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,re),e._receiver.on(`finish`,re))}function H(e){this[C]._receiver.write(e)||this.pause()}function U(){let e=this[C];e._readyState=P.CLOSING,e._receiver.end(),this.end()}function ue(){let e=this[C];this.removeListener(`error`,ue),this.on(`error`,w),e&&(e._readyState=P.CLOSING,this.destroy())}})),no=e(((e,t)=>{to();let{Duplex:r}=n(`stream`);function i(e){e.emit(`close`)}function a(){!this.destroyed&&this._writableState.finished&&this.destroy()}function o(e){this.removeListener(`error`,o),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function s(e,t){let n=!0,s=new r({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(n=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,r){if(e.readyState===e.CLOSED){r(t),process.nextTick(i,s);return}let a=!1;e.once(`error`,function(e){a=!0,r(e)}),e.once(`close`,function(){a||r(t),process.nextTick(i,s)}),n&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,a),s.on(`error`,o),s}t.exports=s})),ro=e(((e,t)=>{let{tokenChars:n}=Xa();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),io=e(((e,t)=>{let r=n(`events`),i=n(`http`),{Duplex:a}=n(`stream`),{createHash:o}=n(`crypto`),s=eo(),c=Ya(),l=ro(),u=to(),{GUID:d,kWebSocket:f}=Ka(),p=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends r{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:u,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=i.createServer((e,t)=>{let n=i.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=m(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(h,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(h,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{h(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,g);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,o=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){v(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){v(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!p.test(i)){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(o!==13&&o!==8){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){_(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=l.parse(u)}catch{v(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&f!==void 0){let n=new c(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=s.parse(f);e[c.extensionName]&&(n.accept(e[c.extensionName]),m[c.extensionName]=n)}catch{v(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${o===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return _(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return _(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,a,l){if(!i.readable||!i.writable)return i.destroy();if(i[f])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return _(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${o(`sha1`).update(t+d).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[c.extensionName]){let t=e[c.extensionName].params,n=s.format({[c.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
|
|
42
42
|
`).join(`\r
|
|
@@ -161,7 +161,7 @@ for await (const chunk of exa.streamAnswer(query)) {
|
|
|
161
161
|
</form>
|
|
162
162
|
<script>document.getElementById('f').submit()<\/script>
|
|
163
163
|
</body>
|
|
164
|
-
</html>`;return new Response(l,{headers:{"Content-Type":`text/html`}})}));return new Promise((e,t)=>{i.on(`error`,t),i.listen(0,`127.0.0.1`,()=>{let n=i.address();if(!n||typeof n==`string`){t(Error(`Failed to get server address`));return}r=`http://127.0.0.1:${n.port}`,e(r)})})}const Bd=q.enum([`read`,`write`]),Vd=q.union([q.literal(`branch_protection_rule`).describe(`Branch protection rule created, edited, or deleted`),q.literal(`check_run`).describe(`Check run created, completed, or requested`),q.literal(`check_suite`).describe(`Check suite completed or requested`),q.literal(`code_scanning_alert`).describe(`Code scanning alert created, fixed, or reopened`),q.literal(`commit_comment`).describe(`Commit comment created`),q.literal(`create`).describe(`Branch or tag created`),q.literal(`delete`).describe(`Branch or tag deleted`),q.literal(`deployment`).describe(`Deployment created`),q.literal(`deployment_status`).describe(`Deployment status created`),q.literal(`deployment_protection_rule`).describe(`Deployment protection rule requested`),q.literal(`discussion`).describe(`Discussion created, edited, or deleted`),q.literal(`discussion_comment`).describe(`Discussion comment created, edited, or deleted`),q.literal(`fork`).describe(`Repository forked`),q.literal(`gollum`).describe(`Wiki page created or updated`),q.literal(`issue_comment`).describe(`Issue comment created, edited, or deleted`),q.literal(`issues`).describe(`Issue opened, edited, closed, or labeled`),q.literal(`label`).describe(`Label created, edited, or deleted`),q.literal(`member`).describe(`Collaborator added, removed, or edited`),q.literal(`membership`).describe(`Team membership added or removed`),q.literal(`meta`).describe(`GitHub App webhook configuration changed`),q.literal(`milestone`).describe(`Milestone created, closed, or deleted`),q.literal(`organization`).describe(`Organization member added, removed, or invited`),q.literal(`org_block`).describe(`Organization blocked or unblocked a user`),q.literal(`package`).describe(`Package published or updated`),q.literal(`page_build`).describe(`GitHub Pages site built`),q.literal(`project`).describe(`Project created, updated, or deleted`),q.literal(`project_card`).describe(`Project card created, edited, or deleted`),q.literal(`project_column`).describe(`Project column created, updated, or deleted`),q.literal(`public`).describe(`Repository visibility changed to public`),q.literal(`pull_request`).describe(`Pull request opened, closed, edited, or synchronized`),q.literal(`pull_request_review`).describe(`Pull request review submitted, edited, or dismissed`),q.literal(`pull_request_review_comment`).describe(`Pull request review comment created or edited`),q.literal(`pull_request_review_thread`).describe(`Pull request review thread resolved or unresolved`),q.literal(`push`).describe(`Git push to a repository`),q.literal(`registry_package`).describe(`Registry package published or updated`),q.literal(`release`).describe(`Release published or edited`),q.literal(`repository`).describe(`Repository created, deleted, archived, or publicized`),q.literal(`repository_dispatch`).describe(`Custom webhook event triggered`),q.literal(`secret_scanning_alert`).describe(`Secret scanning alert created or resolved`),q.literal(`security_and_analysis`).describe(`Security features enabled or disabled`),q.literal(`star`).describe(`Repository starred or unstarred`),q.literal(`status`).describe(`Commit status created`),q.literal(`team`).describe(`Team created, deleted, or edited`),q.literal(`team_add`).describe(`Repository added to team`),q.literal(`watch`).describe(`User started watching repository`),q.literal(`workflow_dispatch`).describe(`Workflow manually triggered`),q.literal(`workflow_job`).describe(`Workflow job queued, started, or completed`),q.literal(`workflow_run`).describe(`Workflow run requested or completed`)]),Hd=q.object({name:q.string().optional().describe(`The name of the GitHub App. Leave blank to let the user name it on GitHub.`),url:q.url().describe(`The homepage URL of the GitHub App. If unknown, set to https://blink.so.`),description:q.string().optional().describe(`The description of the GitHub App.`),public:q.boolean().optional().describe(`Whether the GitHub App is public. Always default to false unless the user explicitly requests otherwise.`),hook_attributes:q.object({url:q.url(),active:q.boolean().optional().default(!0)}).optional().describe(`The webhook configuration for the GitHub App.`),callback_urls:q.array(q.url()).max(10).optional().describe(`Callback URLs for the GitHub App after the user authenticates with GitHub.`),setup_url:q.url().optional().describe(`The URL to redirect the user to after they install the GitHub App.`),setup_on_update:q.boolean().optional().describe(`Whether to redirect the user to the setup URL after an update to the installed app.`),request_oauth_on_install:q.boolean().optional().describe(`Whether to request OAuth on install.`),default_events:q.array(Vd).optional().describe(`Webhook events sent to the webhook URL.`),default_permissions:q.record(q.string(),Bd).optional().describe(`Repository and organization permissions for the GitHub App. Available permissions: actions (GitHub Actions workflows), administration (repository settings), checks (check runs), contents (repository code), deployments, environments, issues, metadata (always granted), packages, pages, pull_requests, repository_hooks (webhooks), repository_projects, secret_scanning_alerts, secrets (Actions secrets), security_events (code scanning/Dependabot), single_file, statuses (commit statuses), vulnerability_alerts (Dependabot), workflows (workflow files), members (collaborators). Values can be 'read' or 'write'.`)});function Ud(e){return`https://api.slack.com/apps?new_app=1&manifest_json=${encodeURIComponent(JSON.stringify(e))}`}const Wd=q.union([q.literal(`app_mention`).describe(`Bot is @mentioned in a channel or conversation. Requires scope: app_mentions:read`),q.literal(`app_home_opened`).describe(`User opened the app's Home tab. No additional scope required beyond bot token`),q.literal(`app_installed`).describe(`App was installed to a workspace. No additional scope required beyond bot token`),q.literal(`app_uninstalled`).describe(`App was uninstalled from a workspace. No additional scope required beyond bot token`),q.literal(`assistant_thread_context_changed`).describe(`Context changed in an assistant thread. Requires scope: assistant:write`),q.literal(`assistant_thread_started`).describe(`New assistant thread was started. Requires scope: assistant:write`),q.literal(`channel_archive`).describe(`Public channel was archived. Requires scope: channels:read`),q.literal(`channel_created`).describe(`Public channel was created. Requires scope: channels:read`),q.literal(`channel_deleted`).describe(`Public channel was deleted. Requires scope: channels:read`),q.literal(`channel_rename`).describe(`Public channel was renamed. Requires scope: channels:read`),q.literal(`channel_unarchive`).describe(`Public channel was unarchived. Requires scope: channels:read`),q.literal(`dnd_updated_user`).describe(`User's Do Not Disturb settings changed. Requires scope: dnd:read`),q.literal(`email_domain_changed`).describe(`Workspace's email domain changed. Requires scope: team:read`),q.literal(`emoji_changed`).describe(`Custom emoji was added or changed. Requires scope: emoji:read`),q.literal(`file_change`).describe(`File was changed. Requires scope: files:read`),q.literal(`file_created`).describe(`File was created. Requires scope: files:read`),q.literal(`file_deleted`).describe(`File was deleted. Requires scope: files:read`),q.literal(`file_public`).describe(`File was made public. Requires scope: files:read`),q.literal(`file_shared`).describe(`File was shared. Requires scope: files:read`),q.literal(`file_unshared`).describe(`File was unshared. Requires scope: files:read`),q.literal(`group_archive`).describe(`Private channel was archived. Requires scope: groups:read`),q.literal(`group_deleted`).describe(`Private channel was deleted. Requires scope: groups:read`),q.literal(`group_rename`).describe(`Private channel was renamed. Requires scope: groups:read`),q.literal(`group_unarchive`).describe(`Private channel was unarchived. Requires scope: groups:read`),q.literal(`link_shared`).describe(`Link from a registered domain was shared. Requires scope: links:read`),q.literal(`member_joined_channel`).describe(`User joined a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),q.literal(`member_left_channel`).describe(`User left a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),q.literal(`message.channels`).describe(`Message was posted in a public channel. Requires scope: channels:history`),q.literal(`message.groups`).describe(`Message was posted in a private channel. Requires scope: groups:history`),q.literal(`message.im`).describe(`Message was posted in a direct message. Requires scope: im:history`),q.literal(`message.mpim`).describe(`Message was posted in a multi-party direct message. Requires scope: mpim:history`),q.literal(`pin_added`).describe(`Item was pinned in a channel. Requires scope: pins:read`),q.literal(`pin_removed`).describe(`Item was unpinned from a channel. Requires scope: pins:read`),q.literal(`reaction_added`).describe(`Reaction was added to a message. Requires scope: reactions:read`),q.literal(`reaction_removed`).describe(`Reaction was removed from a message. Requires scope: reactions:read`),q.literal(`team_join`).describe(`New user joined the workspace. Requires scope: users:read`),q.literal(`user_change`).describe(`User's profile or settings changed. Requires scope: users:read`)]),Gd=q.union([q.literal(`app_mentions:read`).describe(`Read messages that directly mention the bot. Required for: app_mention event`),q.literal(`assistant:write`).describe(`Update bot status and write assistant messages. This should *always* be included for Slack bots. It improves the UX dramatically for users. Required for: assistant_thread_context_changed, assistant_thread_started events`),q.literal(`channels:history`).describe(`Read message history in public channels the bot has access to. Required for: message.channels event`),q.literal(`channels:join`).describe(`Join public channels`),q.literal(`channels:manage`).describe(`Manage public channels (archive, rename, etc.)`),q.literal(`channels:read`).describe(`View basic information about public channels. Required for: channel_archive, channel_created, channel_deleted, channel_rename, channel_unarchive, member_joined_channel, member_left_channel events`),q.literal(`chat:write`).describe(`Send messages as the bot`),q.literal(`chat:write.customize`).describe(`Send messages with a customized username and avatar`),q.literal(`chat:write.public`).describe(`Send messages to public channels without joining`),q.literal(`commands`).describe(`Add and use slash commands`),q.literal(`dnd:read`).describe(`View Do Not Disturb settings for users. Required for: dnd_updated_user event`),q.literal(`emoji:read`).describe(`View custom emoji in the workspace. Required for: emoji_changed event`),q.literal(`files:read`).describe(`View files shared in channels and conversations. Required for: file_change, file_created, file_deleted, file_public, file_shared, file_unshared events`),q.literal(`files:write`).describe(`Upload, edit, and delete files`),q.literal(`groups:history`).describe(`Read message history in private channels the bot has access to. Required for: message.groups event`),q.literal(`groups:read`).describe(`View basic information about private channels. Required for: group_archive, group_deleted, group_rename, group_unarchive, member_joined_channel, member_left_channel events`),q.literal(`groups:write`).describe(`Manage private channels (archive, rename, create, etc.)`),q.literal(`im:history`).describe(`Read message history in direct messages with the bot. Required for: message.im event`),q.literal(`im:read`).describe(`View basic information about direct messages with the bot`),q.literal(`im:write`).describe(`Start and manage direct messages with users`),q.literal(`links:read`).describe(`View URLs in messages. Required for: link_shared event`),q.literal(`links:write`).describe(`Show previews of URLs (unfurling)`),q.literal(`metadata.message:read`).describe(`Read message metadata`),q.literal(`mpim:history`).describe(`Read message history in multi-party direct messages. Required for: message.mpim event`),q.literal(`mpim:read`).describe(`View basic information about multi-party direct messages`),q.literal(`mpim:write`).describe(`Start and manage multi-party direct messages`),q.literal(`pins:read`).describe(`View pinned items in channels and conversations. Required for: pin_added, pin_removed events`),q.literal(`pins:write`).describe(`Pin and unpin items in channels and conversations`),q.literal(`reactions:read`).describe(`View emoji reactions on messages. Required for: reaction_added, reaction_removed events`),q.literal(`reactions:write`).describe(`Add and remove emoji reactions to messages`),q.literal(`reminders:read`).describe(`View reminders created by the bot`),q.literal(`reminders:write`).describe(`Create, update, and delete reminders`),q.literal(`team:read`).describe(`View workspace name, domain, and other basic information. Required for: email_domain_changed event`),q.literal(`usergroups:read`).describe(`View user groups and their members`),q.literal(`usergroups:write`).describe(`Create, update, and archive user groups`),q.literal(`users.profile:read`).describe(`View profile information about users`),q.literal(`users:read`).describe(`View users in the workspace. Required for: team_join, user_change events`),q.literal(`users:read.email`).describe(`View email addresses of users in the workspace`),q.literal(`users:write`).describe(`Set presence and status for the bot user`)]),Kd=q.union([q.literal(`channels:history`).describe(`Read message history in public channels on behalf of the user`),q.literal(`channels:read`).describe(`View basic information about public channels on behalf of the user`),q.literal(`channels:write`).describe(`Manage public channels on behalf of the user`),q.literal(`chat:write`).describe(`Send messages on behalf of the user`),q.literal(`emoji:read`).describe(`View custom emoji on behalf of the user`),q.literal(`files:read`).describe(`View files on behalf of the user`),q.literal(`files:write`).describe(`Upload, edit, and delete files on behalf of the user`),q.literal(`groups:history`).describe(`Read message history in private channels on behalf of the user`),q.literal(`groups:read`).describe(`View basic information about private channels on behalf of the user`),q.literal(`groups:write`).describe(`Manage private channels on behalf of the user`),q.literal(`im:history`).describe(`Read direct message history on behalf of the user`),q.literal(`im:read`).describe(`View basic information about direct messages on behalf of the user`),q.literal(`im:write`).describe(`Manage direct messages on behalf of the user`),q.literal(`links:read`).describe(`View URLs in messages on behalf of the user`),q.literal(`links:write`).describe(`Show URL previews on behalf of the user`),q.literal(`mpim:history`).describe(`Read multi-party direct message history on behalf of the user`),q.literal(`mpim:read`).describe(`View basic information about multi-party direct messages on behalf of the user`),q.literal(`mpim:write`).describe(`Manage multi-party direct messages on behalf of the user`),q.literal(`pins:read`).describe(`View pinned items on behalf of the user`),q.literal(`pins:write`).describe(`Pin and unpin items on behalf of the user`),q.literal(`reactions:read`).describe(`View emoji reactions on behalf of the user`),q.literal(`reactions:write`).describe(`Add and remove emoji reactions on behalf of the user`),q.literal(`reminders:read`).describe(`View reminders on behalf of the user`),q.literal(`reminders:write`).describe(`Create, update, and delete reminders on behalf of the user`),q.literal(`search:read`).describe(`Search messages and files on behalf of the user`),q.literal(`stars:read`).describe(`View starred items on behalf of the user`),q.literal(`stars:write`).describe(`Star and unstar items on behalf of the user`),q.literal(`team:read`).describe(`View workspace information on behalf of the user`),q.literal(`usergroups:read`).describe(`View user groups on behalf of the user`),q.literal(`usergroups:write`).describe(`Manage user groups on behalf of the user`),q.literal(`users.profile:read`).describe(`View user profile information on behalf of the user`),q.literal(`users.profile:write`).describe(`Edit the user's profile information`),q.literal(`users:read`).describe(`View users in the workspace on behalf of the user`),q.literal(`users:read.email`).describe(`View email addresses on behalf of the user`),q.literal(`users:write`).describe(`Set presence for the user`)]),qd=q.object({display_information:q.object({name:q.string().describe(`The name of the Slack app.`),description:q.string().optional().describe(`A short description of the app.`),background_color:q.string().regex(/^#[0-9A-Fa-f]{6}$/).optional().describe(`Background color for the app in hex format (e.g., #4A154B).`),long_description:q.string().optional().describe(`A longer description of the app.`)}).describe(`Display information for the Slack app.`),features:q.object({bot_user:q.object({display_name:q.string().describe(`The display name for the bot user.`),always_online:q.boolean().optional().default(!0).describe(`Whether the bot always appears online.`)}).optional().describe(`Configuration for the bot user.`),app_home:q.object({home_tab_enabled:q.boolean().optional().describe(`Enable the Home tab.`),messages_tab_enabled:q.boolean().optional().describe(`Enable the Messages tab.`),messages_tab_read_only_enabled:q.boolean().optional().describe(`Make the Messages tab read-only.`)}).optional().describe(`Configuration for the App Home.`),assistant_view:q.object({assistant_description:q.string().optional().describe(`Description for the assistant view.`)}).optional().describe(`Configuration for the assistant view.`),slash_commands:q.array(q.object({command:q.string().regex(/^\//).describe(`The command (must start with /).`),description:q.string().describe(`Description of the command.`),usage_hint:q.string().optional().describe(`Usage hint for the command.`),should_escape:q.boolean().optional().describe(`Whether to escape special characters.`)})).optional().describe(`Slash commands for the app.`),unfurl_domains:q.array(q.string()).optional().describe(`Domains for link unfurling.`)}).optional().describe(`Features configuration for the Slack app.`),oauth_config:q.object({redirect_urls:q.array(q.string().url()).optional().describe(`OAuth redirect URLs.`),scopes:q.object({bot:q.array(q.union([Gd,q.string()])).optional().describe(`Bot scopes required by the app. Each scope defines specific permissions for what the bot can do.`),user:q.array(q.union([Kd,q.string()])).optional().describe(`User scopes required by the app. Each scope defines specific permissions for actions performed on behalf of users.`)}).describe(`OAuth scopes for bot and user tokens.`)}).optional().describe(`OAuth configuration for the Slack app.`),settings:q.object({event_subscriptions:q.object({request_url:q.string().url().describe(`The webhook URL for event subscriptions.`),bot_events:q.array(q.union([Wd,q.string()])).optional().describe(`Bot events to subscribe to. Each event notifies your app when specific actions occur in the workspace.`)}).optional().describe(`Event subscriptions configuration.`),interactivity:q.object({is_enabled:q.boolean().describe(`Enable interactivity.`),request_url:q.string().url().describe(`The webhook URL for interactive components.`),message_menu_options_url:q.string().url().optional().describe(`URL for message menu options.`)}).optional().describe(`Interactivity configuration.`),org_deploy_enabled:q.boolean().optional().default(!1).describe(`Enable organization-wide deployment.`),socket_mode_enabled:q.boolean().optional().default(!1).describe(`Enable Socket Mode.`),token_rotation_enabled:q.boolean().optional().default(!1).describe(`Enable automatic token rotation.`)}).optional().describe(`Settings for the Slack app.`)});function Jd(e){let t=s(),n,r;return t.on(`chat`,async({id:r,messages:i,abortSignal:o})=>{let{execute_bash:s,execute_bash_sync:c,...l}=pl,u={execute_bash:s,execute_bash_sync:c};process.env.BLINK_AUTO_APPROVE||(u=await h.withApproval({messages:i,tools:u}));let d={...l,...u,...Rd,...await h.withApproval({messages:i,tools:{create_github_app:V({description:`Creates a GitHub App using GitHub's app manifest flow.
|
|
164
|
+
</html>`;return new Response(l,{headers:{"Content-Type":`text/html`}})}));return new Promise((e,t)=>{i.on(`error`,t),i.listen(0,`127.0.0.1`,()=>{let n=i.address();if(!n||typeof n==`string`){t(Error(`Failed to get server address`));return}r=`http://127.0.0.1:${n.port}`,e(r)})})}const Bd=q.enum([`read`,`write`]),Vd=q.union([q.literal(`branch_protection_rule`).describe(`Branch protection rule created, edited, or deleted`),q.literal(`check_run`).describe(`Check run created, completed, or requested`),q.literal(`check_suite`).describe(`Check suite completed or requested`),q.literal(`code_scanning_alert`).describe(`Code scanning alert created, fixed, or reopened`),q.literal(`commit_comment`).describe(`Commit comment created`),q.literal(`create`).describe(`Branch or tag created`),q.literal(`delete`).describe(`Branch or tag deleted`),q.literal(`deployment`).describe(`Deployment created`),q.literal(`deployment_status`).describe(`Deployment status created`),q.literal(`deployment_protection_rule`).describe(`Deployment protection rule requested`),q.literal(`discussion`).describe(`Discussion created, edited, or deleted`),q.literal(`discussion_comment`).describe(`Discussion comment created, edited, or deleted`),q.literal(`fork`).describe(`Repository forked`),q.literal(`gollum`).describe(`Wiki page created or updated`),q.literal(`issue_comment`).describe(`Issue comment created, edited, or deleted`),q.literal(`issues`).describe(`Issue opened, edited, closed, or labeled`),q.literal(`label`).describe(`Label created, edited, or deleted`),q.literal(`member`).describe(`Collaborator added, removed, or edited`),q.literal(`membership`).describe(`Team membership added or removed`),q.literal(`meta`).describe(`GitHub App webhook configuration changed`),q.literal(`milestone`).describe(`Milestone created, closed, or deleted`),q.literal(`organization`).describe(`Organization member added, removed, or invited`),q.literal(`org_block`).describe(`Organization blocked or unblocked a user`),q.literal(`package`).describe(`Package published or updated`),q.literal(`page_build`).describe(`GitHub Pages site built`),q.literal(`project`).describe(`Project created, updated, or deleted`),q.literal(`project_card`).describe(`Project card created, edited, or deleted`),q.literal(`project_column`).describe(`Project column created, updated, or deleted`),q.literal(`public`).describe(`Repository visibility changed to public`),q.literal(`pull_request`).describe(`Pull request opened, closed, edited, or synchronized`),q.literal(`pull_request_review`).describe(`Pull request review submitted, edited, or dismissed`),q.literal(`pull_request_review_comment`).describe(`Pull request review comment created or edited`),q.literal(`pull_request_review_thread`).describe(`Pull request review thread resolved or unresolved`),q.literal(`push`).describe(`Git push to a repository`),q.literal(`registry_package`).describe(`Registry package published or updated`),q.literal(`release`).describe(`Release published or edited`),q.literal(`repository`).describe(`Repository created, deleted, archived, or publicized`),q.literal(`repository_dispatch`).describe(`Custom webhook event triggered`),q.literal(`secret_scanning_alert`).describe(`Secret scanning alert created or resolved`),q.literal(`security_and_analysis`).describe(`Security features enabled or disabled`),q.literal(`star`).describe(`Repository starred or unstarred`),q.literal(`status`).describe(`Commit status created`),q.literal(`team`).describe(`Team created, deleted, or edited`),q.literal(`team_add`).describe(`Repository added to team`),q.literal(`watch`).describe(`User started watching repository`),q.literal(`workflow_dispatch`).describe(`Workflow manually triggered`),q.literal(`workflow_job`).describe(`Workflow job queued, started, or completed`),q.literal(`workflow_run`).describe(`Workflow run requested or completed`)]),Hd=q.object({name:q.string().optional().describe(`The name of the GitHub App. Leave blank to let the user name it on GitHub.`),url:q.url().describe(`The homepage URL of the GitHub App. If unknown, set to https://blink.so.`),description:q.string().optional().describe(`The description of the GitHub App.`),public:q.boolean().optional().describe(`Whether the GitHub App is public. Always default to false unless the user explicitly requests otherwise.`),hook_attributes:q.object({url:q.url(),active:q.boolean().optional().default(!0)}).optional().describe(`The webhook configuration for the GitHub App.`),callback_urls:q.array(q.url()).max(10).optional().describe(`Callback URLs for the GitHub App after the user authenticates with GitHub.`),setup_url:q.url().optional().describe(`The URL to redirect the user to after they install the GitHub App.`),setup_on_update:q.boolean().optional().describe(`Whether to redirect the user to the setup URL after an update to the installed app.`),request_oauth_on_install:q.boolean().optional().describe(`Whether to request OAuth on install.`),default_events:q.array(Vd).optional().describe(`Webhook events sent to the webhook URL.`),default_permissions:q.record(q.string(),Bd).optional().describe(`Repository and organization permissions for the GitHub App. Available permissions: actions (GitHub Actions workflows), administration (repository settings), checks (check runs), contents (repository code), deployments, environments, issues, metadata (always granted), packages, pages, pull_requests, repository_hooks (webhooks), repository_projects, secret_scanning_alerts, secrets (Actions secrets), security_events (code scanning/Dependabot), single_file, statuses (commit statuses), vulnerability_alerts (Dependabot), workflows (workflow files), members (collaborators). Values can be 'read' or 'write'.`)});function Ud(e){return`https://api.slack.com/apps?new_app=1&manifest_json=${encodeURIComponent(JSON.stringify(e))}`}const Wd=q.union([q.literal(`app_mention`).describe(`Bot is @mentioned in a channel or conversation. Requires scope: app_mentions:read`),q.literal(`app_home_opened`).describe(`User opened the app's Home tab. No additional scope required beyond bot token`),q.literal(`app_installed`).describe(`App was installed to a workspace. No additional scope required beyond bot token`),q.literal(`app_uninstalled`).describe(`App was uninstalled from a workspace. No additional scope required beyond bot token`),q.literal(`assistant_thread_context_changed`).describe(`Context changed in an assistant thread. Requires scope: assistant:write`),q.literal(`assistant_thread_started`).describe(`New assistant thread was started. Requires scope: assistant:write`),q.literal(`channel_archive`).describe(`Public channel was archived. Requires scope: channels:read`),q.literal(`channel_created`).describe(`Public channel was created. Requires scope: channels:read`),q.literal(`channel_deleted`).describe(`Public channel was deleted. Requires scope: channels:read`),q.literal(`channel_rename`).describe(`Public channel was renamed. Requires scope: channels:read`),q.literal(`channel_unarchive`).describe(`Public channel was unarchived. Requires scope: channels:read`),q.literal(`dnd_updated_user`).describe(`User's Do Not Disturb settings changed. Requires scope: dnd:read`),q.literal(`email_domain_changed`).describe(`Workspace's email domain changed. Requires scope: team:read`),q.literal(`emoji_changed`).describe(`Custom emoji was added or changed. Requires scope: emoji:read`),q.literal(`file_change`).describe(`File was changed. Requires scope: files:read`),q.literal(`file_created`).describe(`File was created. Requires scope: files:read`),q.literal(`file_deleted`).describe(`File was deleted. Requires scope: files:read`),q.literal(`file_public`).describe(`File was made public. Requires scope: files:read`),q.literal(`file_shared`).describe(`File was shared. Requires scope: files:read`),q.literal(`file_unshared`).describe(`File was unshared. Requires scope: files:read`),q.literal(`group_archive`).describe(`Private channel was archived. Requires scope: groups:read`),q.literal(`group_deleted`).describe(`Private channel was deleted. Requires scope: groups:read`),q.literal(`group_rename`).describe(`Private channel was renamed. Requires scope: groups:read`),q.literal(`group_unarchive`).describe(`Private channel was unarchived. Requires scope: groups:read`),q.literal(`link_shared`).describe(`Link from a registered domain was shared. Requires scope: links:read`),q.literal(`member_joined_channel`).describe(`User joined a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),q.literal(`member_left_channel`).describe(`User left a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),q.literal(`message.channels`).describe(`Message was posted in a public channel. Requires scope: channels:history`),q.literal(`message.groups`).describe(`Message was posted in a private channel. Requires scope: groups:history`),q.literal(`message.im`).describe(`Message was posted in a direct message. Requires scope: im:history`),q.literal(`message.mpim`).describe(`Message was posted in a multi-party direct message. Requires scope: mpim:history`),q.literal(`pin_added`).describe(`Item was pinned in a channel. Requires scope: pins:read`),q.literal(`pin_removed`).describe(`Item was unpinned from a channel. Requires scope: pins:read`),q.literal(`reaction_added`).describe(`Reaction was added to a message. Requires scope: reactions:read`),q.literal(`reaction_removed`).describe(`Reaction was removed from a message. Requires scope: reactions:read`),q.literal(`team_join`).describe(`New user joined the workspace. Requires scope: users:read`),q.literal(`user_change`).describe(`User's profile or settings changed. Requires scope: users:read`)]),Gd=q.union([q.literal(`app_mentions:read`).describe(`Read messages that directly mention the bot. Required for: app_mention event`),q.literal(`assistant:write`).describe(`Update bot status and write assistant messages. This should *always* be included for Slack bots. It improves the UX dramatically for users. Required for: assistant_thread_context_changed, assistant_thread_started events`),q.literal(`channels:history`).describe(`Read message history in public channels the bot has access to. Required for: message.channels event`),q.literal(`channels:join`).describe(`Join public channels`),q.literal(`channels:manage`).describe(`Manage public channels (archive, rename, etc.)`),q.literal(`channels:read`).describe(`View basic information about public channels. Required for: channel_archive, channel_created, channel_deleted, channel_rename, channel_unarchive, member_joined_channel, member_left_channel events`),q.literal(`chat:write`).describe(`Send messages as the bot`),q.literal(`chat:write.customize`).describe(`Send messages with a customized username and avatar`),q.literal(`chat:write.public`).describe(`Send messages to public channels without joining`),q.literal(`commands`).describe(`Add and use slash commands`),q.literal(`dnd:read`).describe(`View Do Not Disturb settings for users. Required for: dnd_updated_user event`),q.literal(`emoji:read`).describe(`View custom emoji in the workspace. Required for: emoji_changed event`),q.literal(`files:read`).describe(`View files shared in channels and conversations. Required for: file_change, file_created, file_deleted, file_public, file_shared, file_unshared events`),q.literal(`files:write`).describe(`Upload, edit, and delete files`),q.literal(`groups:history`).describe(`Read message history in private channels the bot has access to. Required for: message.groups event`),q.literal(`groups:read`).describe(`View basic information about private channels. Required for: group_archive, group_deleted, group_rename, group_unarchive, member_joined_channel, member_left_channel events`),q.literal(`groups:write`).describe(`Manage private channels (archive, rename, create, etc.)`),q.literal(`im:history`).describe(`Read message history in direct messages with the bot. Required for: message.im event`),q.literal(`im:read`).describe(`View basic information about direct messages with the bot`),q.literal(`im:write`).describe(`Start and manage direct messages with users`),q.literal(`links:read`).describe(`View URLs in messages. Required for: link_shared event`),q.literal(`links:write`).describe(`Show previews of URLs (unfurling)`),q.literal(`metadata.message:read`).describe(`Read message metadata`),q.literal(`mpim:history`).describe(`Read message history in multi-party direct messages. Required for: message.mpim event`),q.literal(`mpim:read`).describe(`View basic information about multi-party direct messages`),q.literal(`mpim:write`).describe(`Start and manage multi-party direct messages`),q.literal(`pins:read`).describe(`View pinned items in channels and conversations. Required for: pin_added, pin_removed events`),q.literal(`pins:write`).describe(`Pin and unpin items in channels and conversations`),q.literal(`reactions:read`).describe(`View emoji reactions on messages. Required for: reaction_added, reaction_removed events`),q.literal(`reactions:write`).describe(`Add and remove emoji reactions to messages`),q.literal(`reminders:read`).describe(`View reminders created by the bot`),q.literal(`reminders:write`).describe(`Create, update, and delete reminders`),q.literal(`team:read`).describe(`View workspace name, domain, and other basic information. Required for: email_domain_changed event`),q.literal(`usergroups:read`).describe(`View user groups and their members`),q.literal(`usergroups:write`).describe(`Create, update, and archive user groups`),q.literal(`users.profile:read`).describe(`View profile information about users`),q.literal(`users:read`).describe(`View users in the workspace. Required for: team_join, user_change events`),q.literal(`users:read.email`).describe(`View email addresses of users in the workspace`),q.literal(`users:write`).describe(`Set presence and status for the bot user`)]),Kd=q.union([q.literal(`channels:history`).describe(`Read message history in public channels on behalf of the user`),q.literal(`channels:read`).describe(`View basic information about public channels on behalf of the user`),q.literal(`channels:write`).describe(`Manage public channels on behalf of the user`),q.literal(`chat:write`).describe(`Send messages on behalf of the user`),q.literal(`emoji:read`).describe(`View custom emoji on behalf of the user`),q.literal(`files:read`).describe(`View files on behalf of the user`),q.literal(`files:write`).describe(`Upload, edit, and delete files on behalf of the user`),q.literal(`groups:history`).describe(`Read message history in private channels on behalf of the user`),q.literal(`groups:read`).describe(`View basic information about private channels on behalf of the user`),q.literal(`groups:write`).describe(`Manage private channels on behalf of the user`),q.literal(`im:history`).describe(`Read direct message history on behalf of the user`),q.literal(`im:read`).describe(`View basic information about direct messages on behalf of the user`),q.literal(`im:write`).describe(`Manage direct messages on behalf of the user`),q.literal(`links:read`).describe(`View URLs in messages on behalf of the user`),q.literal(`links:write`).describe(`Show URL previews on behalf of the user`),q.literal(`mpim:history`).describe(`Read multi-party direct message history on behalf of the user`),q.literal(`mpim:read`).describe(`View basic information about multi-party direct messages on behalf of the user`),q.literal(`mpim:write`).describe(`Manage multi-party direct messages on behalf of the user`),q.literal(`pins:read`).describe(`View pinned items on behalf of the user`),q.literal(`pins:write`).describe(`Pin and unpin items on behalf of the user`),q.literal(`reactions:read`).describe(`View emoji reactions on behalf of the user`),q.literal(`reactions:write`).describe(`Add and remove emoji reactions on behalf of the user`),q.literal(`reminders:read`).describe(`View reminders on behalf of the user`),q.literal(`reminders:write`).describe(`Create, update, and delete reminders on behalf of the user`),q.literal(`search:read`).describe(`Search messages and files on behalf of the user`),q.literal(`stars:read`).describe(`View starred items on behalf of the user`),q.literal(`stars:write`).describe(`Star and unstar items on behalf of the user`),q.literal(`team:read`).describe(`View workspace information on behalf of the user`),q.literal(`usergroups:read`).describe(`View user groups on behalf of the user`),q.literal(`usergroups:write`).describe(`Manage user groups on behalf of the user`),q.literal(`users.profile:read`).describe(`View user profile information on behalf of the user`),q.literal(`users.profile:write`).describe(`Edit the user's profile information`),q.literal(`users:read`).describe(`View users in the workspace on behalf of the user`),q.literal(`users:read.email`).describe(`View email addresses on behalf of the user`),q.literal(`users:write`).describe(`Set presence for the user`)]),qd=q.object({display_information:q.object({name:q.string().describe(`The name of the Slack app.`),description:q.string().optional().describe(`A short description of the app.`),background_color:q.string().regex(/^#[0-9A-Fa-f]{6}$/).optional().describe(`Background color for the app in hex format (e.g., #4A154B).`),long_description:q.string().optional().describe(`A longer description of the app.`)}).describe(`Display information for the Slack app.`),features:q.object({bot_user:q.object({display_name:q.string().describe(`The display name for the bot user.`),always_online:q.boolean().optional().default(!0).describe(`Whether the bot always appears online.`)}).optional().describe(`Configuration for the bot user.`),app_home:q.object({home_tab_enabled:q.boolean().optional().describe(`Enable the Home tab.`),messages_tab_enabled:q.boolean().optional().describe(`Enable the Messages tab.`),messages_tab_read_only_enabled:q.boolean().optional().describe(`Make the Messages tab read-only.`)}).optional().describe(`Configuration for the App Home.`),assistant_view:q.object({assistant_description:q.string().optional().describe(`Description for the assistant view.`)}).optional().describe(`Configuration for the assistant view.`),slash_commands:q.array(q.object({command:q.string().regex(/^\//).describe(`The command (must start with /).`),description:q.string().describe(`Description of the command.`),usage_hint:q.string().optional().describe(`Usage hint for the command.`),should_escape:q.boolean().optional().describe(`Whether to escape special characters.`)})).optional().describe(`Slash commands for the app.`),unfurl_domains:q.array(q.string()).optional().describe(`Domains for link unfurling.`)}).optional().describe(`Features configuration for the Slack app.`),oauth_config:q.object({redirect_urls:q.array(q.string().url()).optional().describe(`OAuth redirect URLs.`),scopes:q.object({bot:q.array(q.union([Gd,q.string()])).optional().describe(`Bot scopes required by the app. Each scope defines specific permissions for what the bot can do.`),user:q.array(q.union([Kd,q.string()])).optional().describe(`User scopes required by the app. Each scope defines specific permissions for actions performed on behalf of users.`)}).describe(`OAuth scopes for bot and user tokens.`)}).optional().describe(`OAuth configuration for the Slack app.`),settings:q.object({event_subscriptions:q.object({request_url:q.string().url().describe(`The webhook URL for event subscriptions.`),bot_events:q.array(q.union([Wd,q.string()])).optional().describe(`Bot events to subscribe to. Each event notifies your app when specific actions occur in the workspace.`)}).optional().describe(`Event subscriptions configuration.`),interactivity:q.object({is_enabled:q.boolean().describe(`Enable interactivity.`),request_url:q.string().url().describe(`The webhook URL for interactive components.`),message_menu_options_url:q.string().url().optional().describe(`URL for message menu options.`)}).optional().describe(`Interactivity configuration.`),org_deploy_enabled:q.boolean().optional().default(!1).describe(`Enable organization-wide deployment.`),socket_mode_enabled:q.boolean().optional().default(!1).describe(`Enable Socket Mode.`),token_rotation_enabled:q.boolean().optional().default(!1).describe(`Enable automatic token rotation.`)}).optional().describe(`Settings for the Slack app.`)});function Jd(e){let t=new a,n,r;return t.on(`chat`,async({id:r,messages:i,abortSignal:a})=>{let{execute_bash:s,execute_bash_sync:c,...l}=pl,u={execute_bash:s,execute_bash_sync:c};process.env.BLINK_AUTO_APPROVE||(u=await h.withApproval({messages:i,tools:u}));let d={...l,...u,...Rd,...await h.withApproval({messages:i,tools:{create_github_app:V({description:`Creates a GitHub App using GitHub's app manifest flow.
|
|
165
165
|
|
|
166
166
|
IMPORTANT: You must explain to the user what's happening and why:
|
|
167
167
|
- Tell them this will open a localhost URL that redirects them to GitHub
|
|
@@ -196,6 +196,7 @@ do should *not* provide "oauth_config" in the manifest.
|
|
|
196
196
|
For the best user experience, default to the following bot scopes:
|
|
197
197
|
- "app_mentions:read"
|
|
198
198
|
- "reactions:write"
|
|
199
|
+
- "reactions:read"
|
|
199
200
|
- "channels:history"
|
|
200
201
|
- "chat:write"
|
|
201
202
|
- "groups:history"
|
|
@@ -224,7 +225,7 @@ Default to the following events:
|
|
|
224
225
|
*NEVER* include user scopes unless the user explicitly asks for them.
|
|
225
226
|
`,inputSchema:qd,execute:async(e,t)=>{let n=Ud(e);try{await _i(n)}catch{}return`Opened Slack App creation URL in browser: ${n}`}})}}),message_user_agent:V({description:`Messages the user agent. There is no conversation history - this will be the only message sent, and only one message responds. Every time you invoke this tool, a new conversation occurs.
|
|
226
227
|
|
|
227
|
-
Instruct the agent to invoke tools you are debugging. e.g. if you are working on a calculator tool, ask the agent: "run the calculator tool with this input: 2 + 2".`,inputSchema:q.object({message:q.string()}),execute:async(e,t)=>{if(!n)return`User agent URL is not available. Cannot test user agent.`;let r=await new
|
|
228
|
+
Instruct the agent to invoke tools you are debugging. e.g. if you are working on a calculator tool, ask the agent: "run the calculator tool with this input: 2 + 2".`,inputSchema:q.object({message:q.string()}),execute:async(e,t)=>{if(!n)return`User agent URL is not available. Cannot test user agent.`;let r=await new o({baseUrl:n}).chat({id:crypto.randomUUID(),messages:[{id:crypto.randomUUID(),role:`user`,parts:[{type:`text`,text:e.message}]}]},{signal:t.abortSignal}),i=re({stream:r}),a;for await(let e of i)a=e;return a}}),typecheck_agent:V({description:`*ONLY* typecheck the agent being worked on. Reports all syntax errors.
|
|
228
229
|
|
|
229
230
|
Do *NOT* confuse this with tools in run mode for typechecking.`,inputSchema:q.object({}),execute:async()=>{let t=le(`node`,[j(e.directory,`node_modules/.bin/tsc`),`--noEmit`],{stdio:`pipe`,cwd:e.directory}),n=``,r=``,i;return t.stdout.on(`data`,e=>{n+=Buffer.from(e).toString(`utf-8`)}),t.stderr.on(`data`,e=>{r+=Buffer.from(e).toString(`utf-8`)}),await new Promise(e=>{t.on(`close`,t=>{i=t??void 0,e()})}),{stdout:n,stderr:r,exitCode:i}}})},f=z(i,{ignoreIncompleteToolCalls:!0,tools:d});f.unshift({role:`system`,content:Xd});let p=f.findLastIndex(e=>e.role===`user`);return p!==-1&&f.splice(p,0,{role:`user`,content:`*INTERNAL*: THIS IS A HIDDEN MESSAGE. YOU ARE IN EDIT MODE.
|
|
230
231
|
|
|
@@ -254,7 +255,7 @@ You are *NOT* responsible for:
|
|
|
254
255
|
- Continuing any work the run mode agent started
|
|
255
256
|
|
|
256
257
|
Your job is to improve the agent based on run mode failures, NOT to complete the user's original run-mode request yourself.
|
|
257
|
-
`}),ie({model:Yd(e.token),messages:f,maxOutputTokens:64e3,tools:d,abortSignal:
|
|
258
|
+
`}),ie({model:Yd(e.token),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 Yd(e){return process.env.ANTHROPIC_API_KEY?c({apiKey:process.env.ANTHROPIC_API_KEY}).chat(`claude-sonnet-4-5`):process.env.OPENAI_API_KEY?l({apiKey:process.env.OPENAI_API_KEY}).responses(`gpt-5`):p(`anthropic/claude-sonnet-4.5`,{token:e})}const Xd=`You are the Blink Edit Agent, an AI assistant that helps developers build and debug Blink agents.
|
|
258
259
|
|
|
259
260
|
You are integrated into the \`blink dev\` command-line interface, where users can toggle between **run mode** (testing their agent) and **edit mode** (getting your help) using Ctrl+E. After making changes, instruct the user to switch to run mode to use their agent.
|
|
260
261
|
|
|
@@ -613,4 +614,4 @@ The agent process can restart at any time, so all important state must be extern
|
|
|
613
614
|
<code_quality>
|
|
614
615
|
- Never use "as any" type assertions. Always figure out the correct typings.
|
|
615
616
|
</code_quality>
|
|
616
|
-
`;function Zd(e){let[t,n]=W(void 0),[r,i]=W(void 0),
|
|
617
|
+
`;function Zd(e){let[t,n]=W(void 0),[r,i]=W(void 0),a=de(void 0);return U(()=>{let t=new AbortController,r=!1;return i(void 0),n(void 0),(async()=>{a.current=Jd({directory:e.directory,token:e.token});let r=await Qd(),i=a.current.agent.serve({port:r,host:`127.0.0.1`,apiUrl:e.apiServerUrl});t.signal.addEventListener(`abort`,()=>{try{i.close()}catch{}a.current?.cleanup()});let s=new o({baseUrl:`http://127.0.0.1:${r}`});for(;!t.signal.aborted;){try{await s.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(t.signal.aborted)throw t.signal.reason;n(s)})().catch(e=>{r||i(e instanceof Error?e:Error(String(e)))}),()=>{r=!0,t.abort()}},[e.directory,e.apiServerUrl,e.token]),ue(()=>({client:t,error:r,setUserAgentUrl:e=>{a.current?.setUserAgentUrl(e)}}),[t,r])}async function Qd(){let e=k();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function $d(e){let{directory:t}=e,[n,r]=W(),[i,a]=W(!1),[o,s]=W(`run`),c=de(`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:f,status:p,result:m,entry:h}=Ci({directory:t,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),g=Si({autoCheck:!0,onAuthChange:e.onAuthChange,onLoginUrl:e.onLoginUrl}),_=Aa(t),v=ue(()=>{let e=g.token;return e?{..._,BLINK_TOKEN:e}:_},[_,g.token]),y=de(void 0);U(()=>{let t=Object.keys(v);if(t.length===y.current||y.current===void 0){y.current=t.length;return}y.current=t.length,e.onEnvLoaded?.(t)},[v,e.onEnvLoaded]);let b=de(void 0),x=ue(()=>wa({port:0,dataDirectory:j(t,`data`),getAgent:()=>b.current}),[t]),{agent:S,logs:C,error:w,capabilities:T}=Ce({buildResult:m,env:v,apiServerUrl:x.url}),{client:E,error:D,setUserAgentUrl:O}=Zd({directory:t,apiServerUrl:x.url,token:g.token}),[k,A]=W(`00000000-0000-0000-0000-000000000000`);U(()=>{S&&O(S.baseUrl),o===`run`?S?b.current=S:(b.current=void 0,x.getChatManager(k)?.stopStreaming()):o===`edit`&&(E?b.current=E:(b.current=void 0,x.getChatManager(k)?.stopStreaming()))},[S,E,o,k,x]);let M=de(void 0),N=ea({chatId:k,agent:o===`run`?S:E,chatsDirectory:x.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{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:!(Qi(e.metadata)||e.mode===`edit`)}),P=de(0);U(()=>{if(C.length===P.current)return;let t=P.current;for(let n of C.slice(t))e.onAgentLog?.(n);P.current=C.length},[C,e.onAgentLog,N.upsertMessage]);let[F,ee]=W([]);U(()=>{x.listChats().then(e=>{ee(e.map(e=>e.key))})},[x]),U(()=>{k&&!F.includes(k)&&ee(e=>[...e,k])},[k,F]);let te=ue(()=>ta(t),[t]),I=Ea({id:te,disabled:!T?.request,onRequest:async t=>{if(!S)throw Error(`No agent`);let n=new URL(t.url),r=new URL(S.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`&&e.onDevhookConnected?.(`https://${I.id}.dev.blink.host`)},[I.status,I.id]);let{schema:L,options:ne,error:R,setOption:z}=Ta({agent:o===`run`?S:E,capabilities:T,messages:N.messages});U(()=>{M.current=ne},[ne]);let re=ue(()=>{let e=new Map;return w&&o===`run`&&e.set(`agent`,w.message),D&&o===`edit`&&e.set(`editAgent`,`Edit agent error: ${D.message}`),N.error&&p!==`building`&&e.set(`chat`,`Chat error: ${N.error}`),R&&e.set(`options`,`Options error: ${R.message}`),e},[w,D,N.error,R,o,p]),ie=de(new Map);U(()=>{let t=ie.current,n=re;for(let[r,i]of n.entries())t.get(r)!==i&&e.onError?.(i);for(let e of t.keys())n.has(e);ie.current=new Map(n)},[re,e.onError]);let V=ue(()=>{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(B);if(t.length!==0&&t.some(e=>d(e.output)&&e.output.outcome===`pending`))return e},[N.messages,n]),ae=H(async(e,t)=>{if(!V)return;t&&e&&a(!0),r(V.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&&d(t.output)&&t.output.outcome===`pending`?{...t,output:{...t.output,outcome:e?`approved`:`rejected`}}:t);await N.upsertMessage({...i,parts:o}),await N.start()},[V,N]);U(()=>{i&&V&&ae(!0)},[i,V,ae]);let oe=H(()=>{let e=crypto.randomUUID();A(e),ee(t=>[...t,e]),r(void 0)},[]),se=H(e=>{A(e),r(void 0)},[]),ce=ue(()=>{if(V)return{message:V,approve:e=>ae(!0,e),reject:()=>ae(!1),autoApproveEnabled:i}},[V,ae,i]),le=ue(()=>{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]),G=ue(()=>{if(N.status!==`streaming`)return!1;if(!N.streamingMessage)return!0;let e=N.streamingMessage.parts.filter(B);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:F,switchChat:se,newChat:oe,build:{status:p,error:f,entrypoint:h},devhook:{connected:I.status===`connected`,url:I.status===`connected`?`https://${I.id}.dev.blink.host`:void 0},capabilities:T,options:{schema:L,selected:ne,error:R,setOption:z},approval:ce,tokenUsage:le,auth:g,server:x,showWaitingPlaceholder:G}}export{Ce as useAgent,Si as useAuth,Ci as useBundler,ea as useChat,$d as useDevMode,Ea as useDevhook,Aa as useDotenv,Zd as useEditAgent,Ta as useOptions};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "blink",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.5",
|
|
4
4
|
"description": "Blink is a JavaScript runtime for building and deploying AI agents.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -79,6 +79,7 @@
|
|
|
79
79
|
"@ai-sdk/openai-compatible": "^1.0.19",
|
|
80
80
|
"@ai-sdk/react": "^2.0.35",
|
|
81
81
|
"@ai-sdk/xai": "^2.0.16",
|
|
82
|
+
"@blink-sdk/compute-protocol": "^0.0.6",
|
|
82
83
|
"@blink.so/api": "^0.0.11",
|
|
83
84
|
"@clack/prompts": "^0.11.0",
|
|
84
85
|
"@hono/node-server": "^1.19.3",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{login as e}from"./auth-CpUNsA0k.js";import"./dist-wyfWuz5A.js";import"./open-S_jcQ0nw.js";async function t(){await e()}export{t as default};
|
|
File without changes
|
|
File without changes
|