@fungi.computer/grove 0.16.1 → 0.17.1

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.
Files changed (49) hide show
  1. package/dist/assets/{Effect-DeiDqvoz.js → Effect-pxRavrBh.js} +11 -11
  2. package/dist/assets/{anthropic-messages-DQiQ4Cgh.js → anthropic-messages-CkLFXbme.js} +3 -3
  3. package/dist/assets/{azure-openai-responses-BdsogfXX.js → azure-openai-responses-BjItkyTn.js} +1 -1
  4. package/dist/assets/{base-face-BYExcFAP.js → base-face-CsIbc1by.js} +1 -1
  5. package/dist/assets/burger-BgftDtiM.js +1 -0
  6. package/dist/assets/cat-CfNEurUg.js +1 -0
  7. package/dist/assets/{classifier-shared-BCGGOIh6.js → classifier-shared-JiMD88Sh.js} +1 -1
  8. package/dist/assets/{cloudflare-workers-ai-system-one-BjlnhHlD.js → cloudflare-workers-ai-system-one-tEpgPfLW.js} +1 -1
  9. package/dist/assets/compat-CxZajpXB.js +2 -0
  10. package/dist/assets/conversation-toast-DUFOMoQ9.js +33 -0
  11. package/dist/assets/{document-EWUYmKg3.js → document-BBvRlLC3.js} +1 -1
  12. package/dist/assets/{document-BiiUDQ73.js → document-Bpcy9TTA.js} +1 -1
  13. package/dist/assets/extension-hook-Da3ATgkY.js +890 -0
  14. package/dist/assets/extensions-D2Z9guoO.js +1 -0
  15. package/dist/assets/{google-generative-ai-DZR_Ze6f.js → google-generative-ai-DJB3dC5c.js} +1 -1
  16. package/dist/assets/{google-shared-BpSgfzOZ.js → google-shared-DVq-_IDX.js} +1 -1
  17. package/dist/assets/{google-vertex-ghIH-83b.js → google-vertex-CYm5wNps.js} +1 -1
  18. package/dist/assets/index-BaCEAFz2.js +117 -0
  19. package/dist/assets/index-CIiuRnlU.css +1 -0
  20. package/dist/assets/{mistral-conversations-Dz3sIOsn.js → mistral-conversations-DDg7eeLe.js} +1 -1
  21. package/dist/assets/{mushroom-CjQXC8r7.js → mushroom-FKArpulr.js} +1 -1
  22. package/dist/assets/{node.browser-Bg-Udc28.js → node.browser-CdLsHXpS.js} +1 -1
  23. package/dist/assets/{openai-codex-responses-CsLh-FB3.js → openai-codex-responses-H7WhI66H.js} +1 -1
  24. package/dist/assets/{openai-completions-F-1Tomjo.js → openai-completions-CkqQ2fFp.js} +1 -1
  25. package/dist/assets/{openai-decisions-BMWT3gOP.js → openai-decisions-DMV8tZy4.js} +1 -1
  26. package/dist/assets/{openai-responses-CZ6dqUTL.js → openai-responses-Csql8sEY.js} +1 -1
  27. package/dist/assets/{openai-responses-shared-Btjx9mL_.js → openai-responses-shared-DAZ5Qapp.js} +1 -1
  28. package/dist/assets/{openrouter-images-D5Uqwk0h.js → openrouter-images-DFWtFOvI.js} +1 -1
  29. package/dist/assets/parakeet-BUkzxkvS.js +35 -0
  30. package/dist/assets/parakeet-conversation-D8vRtIjX.js +4 -0
  31. package/dist/assets/{pi-messages-1JTpG1Us.js → pi-messages-DoPiztqV.js} +1 -1
  32. package/dist/assets/{renderer-DOUDAFcS.js → renderer-BVZdPJB6.js} +1 -1
  33. package/dist/assets/runtime-core-U8lOfyYX.js +40 -0
  34. package/dist/assets/{system-one-shared-qsmpMW29.js → system-one-shared-D7AS4c2W.js} +1 -1
  35. package/dist/assets/{transform-messages-AGWoIDpj.js → transform-messages-CCZNew0k.js} +1 -1
  36. package/dist/assets/{typesafe-system-one-D8FWi62S.js → typesafe-system-one-Cl52u7Mq.js} +1 -1
  37. package/dist/assets/{website-conversation-kQbo5VTI.js → website-conversation-CpPJ8N_o.js} +1 -1
  38. package/dist/index.html +9 -8
  39. package/package.json +9 -9
  40. package/dist/assets/burger-Bn2ocNTG.js +0 -1
  41. package/dist/assets/cat-x9tMcsRE.js +0 -1
  42. package/dist/assets/compat-CAkhM7lX.js +0 -2
  43. package/dist/assets/conversation-toast-BLAWHMmE.js +0 -32
  44. package/dist/assets/extension-hook-BEwrceUI.js +0 -869
  45. package/dist/assets/index-BaZH2cO3.js +0 -117
  46. package/dist/assets/index-ODpmGtEN.css +0 -1
  47. package/dist/assets/parakeet-Cq96KyZe.js +0 -36
  48. package/dist/assets/parakeet-conversation-m2Bl3XXj.js +0 -4
  49. package/dist/assets/runtime-core-DDK2YKwN.js +0 -40
@@ -1,117 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/runtime-core-DDK2YKwN.js","assets/rolldown-runtime-hePW80VL.js","assets/Effect-DeiDqvoz.js","assets/extension-hook-BEwrceUI.js","assets/preload-helper-CfILh1TC.js","assets/text-_WthCHzw.js","assets/estimate-DElUjJag.js","assets/website-conversation-kQbo5VTI.js","assets/conversation-toast-BLAWHMmE.js","assets/document-EWUYmKg3.js","assets/parakeet-Cq96KyZe.js","assets/openai-codex.models-DXmil0i7.js","assets/parakeet-conversation-m2Bl3XXj.js","assets/parakeet-conversation-COndlivb.css"])))=>i.map(i=>d[i]);
2
- import{r as e,t}from"./rolldown-runtime-hePW80VL.js";import{$ as n,$n as r,$r as i,A as a,Ai as o,An as s,Ar as c,At as l,B as u,Bn as d,Br as f,Bt as p,C as m,Cn as h,Cr as g,D as _,Di as v,Dn as y,Dr as b,E as x,Ei as S,En as C,Er as w,Et as T,F as E,Fn as D,Fr as O,Ft as k,G as A,Gn as j,Gt as M,H as ee,Hi as te,Hn as ne,Hr as re,Ht as ie,I as ae,In as oe,Ir as se,It as ce,J as le,Jr as N,Jt as ue,K as de,Kn as fe,Kt as pe,L as P,Ln as me,Lr as he,Lt as ge,M as _e,Mi as ve,Mn as ye,Mt as be,N as xe,Ni as Se,Nn as Ce,Nr as we,Nt as Te,O as Ee,Oi as De,Or as Oe,P as ke,Pi as Ae,Pn as je,Pr as Me,Pt as Ne,Q as Pe,Qn as Fe,Qr as Ie,Qt as Le,R as Re,Rn as ze,Rr as Be,Rt as Ve,S as He,Sr as Ue,T as We,Ti as Ge,Tn as Ke,Tr as qe,Tt as Je,U as Ye,Ui as Xe,Un as Ze,Ut as Qe,V as $e,Vi as et,Vn as tt,Vr as nt,Vt as rt,W as it,Wi as at,Wn as ot,Wt as st,X as ct,Xn as lt,Xt as ut,Y as dt,Yr as ft,Yt as pt,Z as mt,Zn as ht,Zr as gt,Zt as _t,_ as vt,_i as yt,_r as bt,a as xt,ai as St,an as Ct,ar as wt,b as Tt,bi as Et,bn as Dt,c as Ot,cn as kt,cr as At,d as jt,di as Mt,dn as Nt,dr as Pt,ei as Ft,en as It,er as Lt,et as Rt,f as zt,fi as Bt,fn as Vt,fr as Ht,gi as Ut,gn as Wt,gr as Gt,h as Kt,hi as qt,hn as Jt,hr as Yt,i as Xt,ii as Zt,in as Qt,ir as $t,j as en,ji as tn,jn as nn,jr as rn,jt as an,k as on,ki as sn,kn as cn,kr as ln,l as un,ln as dn,lr as fn,m as pn,mi as mn,mr as hn,n as gn,ni as _n,nn as vn,nr as yn,nt as bn,o as xn,oi as Sn,on as Cn,or as wn,p as Tn,pi as En,pn as Dn,pr as On,q as kn,qi as An,qr as jn,qt as Mn,r as Nn,ri as Pn,rn as Fn,rr as In,rt as Ln,s as Rn,si as zn,sn as Bn,sr as Vn,t as Hn,ti as Un,tn as Wn,tr as Gn,u as Kn,un as qn,ur as Jn,v as Yn,vi as Xn,vn as Zn,vr as Qn,w as $n,wi as er,wn as tr,wr as nr,wt as rr,x as ir,xn as ar,y as or,yi as sr,yr as cr,z as lr,zn as ur,zr as dr,zt as fr}from"./conversation-toast-BLAWHMmE.js";import{$i as pr,Aa as mr,Bi as hr,Ct as gr,E as _r,Ei as vr,F as yr,Fa as br,Gi as xr,Hi as Sr,I as Cr,Ji as wr,Jn as Tr,K as Er,Ki as Dr,Na as Or,Nn as kr,Oa as Ar,Qi as jr,Qn as Mr,Ri as Nr,St as Pr,Ta as Fr,Ui as Ir,V as Lr,Vi as Rr,Wi as zr,Xi as Br,Y as Vr,Yi as Hr,Z as Ur,Zi as Wr,_ as Gr,_a as Kr,a as qr,ar as Jr,ba as Yr,bt as Xr,ca as Zr,d as Qr,da as $r,ea as ei,fa as ti,fr as ni,g as ri,ga as ii,gi as ai,gt as oi,h as si,ht as ci,i as li,ir as ui,it as di,j as fi,ji as pi,ka as mi,l as hi,lr as gi,m as _i,ma as vi,mt as yi,na as bi,oa as xi,pa as Si,pt as Ci,qi as wi,ra as Ti,rr as Ei,s as Di,sr as Oi,t as ki,tt as Ai,ur as ji,va as Mi,wa as Ni,wt as Pi,xa as Fi,xi as Ii,xt as Li,y as Ri,ya as zi,zi as Bi}from"./Effect-DeiDqvoz.js";import{$i as Vi,$r as Hi,Ai as Ui,Ar as Wi,Bo as Gi,Ci as Ki,Di as F,Do as qi,Dr as Ji,Ei as I,Eo as Yi,Fi as Xi,Ga as Zi,Gi as Qi,Go as $i,Hi as ea,Ho as ta,Ia as L,Ii as na,Ja as ra,Jr as ia,Ki as R,La as z,Li as B,Lr as aa,Mi as oa,Mo as sa,Na as ca,No as la,Oo as ua,Or as da,Pi as V,Qa as fa,Qi as pa,Qr as ma,Ra as H,Ri as ha,Si as ga,Ta as U,Ti as _a,To as va,Ua as ya,Ui as ba,Wi as xa,Wo as Sa,Xa as Ca,Xi as wa,Ya as Ta,Za as Ea,Zn as Da,_a as Oa,_i as W,_r as ka,ao as Aa,c as ja,ci as G,co as Ma,d as Na,do as Pa,ea as Fa,eo as Ia,f as La,fi as Ra,gi as K,go as za,gr as Ba,hi as Va,ho as Ha,hr as Ua,i as Wa,io as Ga,ji as Ka,jo as qa,ka as q,ki as Ja,kr as Ya,la as Xa,lo as Za,m as Qa,mi as $a,ni as eo,no as to,oi as no,oo as ro,p as io,pa as ao,pi as oo,qa as so,ri as co,ro as lo,si as uo,so as fo,ta as po,ti as mo,to as ho,tr as go,ua as _o,ui as vo,uo as yo,wi as bo,wo as xo,xa as So,za as Co,zi as wo}from"./extension-hook-BEwrceUI.js";import{i as To}from"./document-EWUYmKg3.js";import{t as Eo}from"./preload-helper-CfILh1TC.js";import{t as Do}from"./document-BiiUDQ73.js";import{a as Oo,i as ko,n as Ao,r as jo,t as Mo}from"./base-face-BYExcFAP.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var J=e(An(),1),No=new WeakMap;function Po(e,t){let n=!1,r=[];for(let i of t){let{availability:t,handler:a,...o}=i,s=a,c=t===void 0?o:{...o,availability:t()},l=No.get(e)??new Map;No.set(e,l);let u=l.get(i.id),d=()=>e.register(c,async({arguments:e,origin:t,signal:n})=>{let r=await s(e===void 0?{origin:t,signal:n}:{arguments:e,origin:t,signal:n});return r===void 0?void 0:at(r)}),f=(u?u.then(d):d()).then(e=>{n?e():r.push(e)},e=>{console.warn(`App command ${i.id} was not registered`,e)});l.set(i.id,f),f.finally(()=>{l.get(i.id)===f&&l.delete(i.id)})}return()=>{if(!n){n=!0;for(let e of r.splice(0))e()}}}var Fo=I.pipe(B(q(1)),B(U(80))),Io=[`CANCELLED`,`CAPABILITY_DENIED`,`CAPABILITY_REVOKED`,`COMMAND_NOT_DECLARED`,`CONFLICT`,`DAILY_LIMIT_REACHED`,`DELIVERY_PENDING`,`DISCONNECTED`,`FILE_TOO_LARGE`,`HOST_FAILURE`,`IDENTITY`,`INSUFFICIENT_CREDIT`,`INVALID_ARGUMENT`,`MEDIA_PROVIDER_FAILURE`,`MEDIA_PROVIDER_FAILURE_UNCHARGED`,`PROTOCOL`,`SAFETY_FILTER_REFUSED`,`SELECTION_CHANGED`,`SETUP_REQUIRED`,`TIMEOUT`];F({name:K(`AppError`),code:W(Io),retryable:vo,need:z(I)});var Y=class extends Error{code;retryable;need;constructor(e,t){super(e,{cause:t.cause}),this.name=`AppError`,this.code=t.code,this.retryable=t.retryable,this.need=t.need}};function Lo(e){return`This needs ${e??`setup`} first.`}Lo(void 0),Wr(`light.dark.latte.mocha.readout.readout-night.field-guide.field-guide-night.embed.embed-dark.phosphor.codec.paper.ember.tide.tape.sunrise.pirate-radio.pirate-radio-night.consulting.consulting-ink.consulting-night.consulting-night-ink.consulting-riso-latte.consulting-riso-latte-ink.consulting-riso-glomzy.consulting-riso-glomzy-ink.vishnu.coin.coin-night.chamfer`.split(`.`));var Ro=`data-theme`;function zo(e){return e||(globalThis.document?.documentElement??null)}function Bo(e){let t=e.trim();if(t.length===0)throw TypeError(`Theme must be a non-empty string`);return t}function Vo(e,t){let n=Bo(e),r=zo(t);r&&r.setAttribute(Ro,n)}function Ho(e){return zo(e)?.getAttribute(Ro)??null}function Uo(e,t){let n=new Set(t);return e.filter(e=>!n.has(e))}var Wo=class extends Ge{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l=[];constructor(e,t,n){super(),this.#e=e,this.#r=n,this.#n=[],this.#i=[],this.#t=[],this.setQueries(t)}onSubscribe(){this.listeners.size===1&&this.#i.forEach(e=>{e.subscribe(t=>{this.#m(e,t)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,this.#i.forEach(e=>{e.destroy()})}setQueries(e,t){this.#n=e,this.#r=t,er.batch(()=>{let e=this.#i,t=this.#p(this.#n);t.forEach(e=>e.observer.setOptions(e.defaultedQueryOptions));let n=t.map(e=>e.observer),r=n.map(e=>e.getCurrentResult()),i=e.length!==n.length,a=n.some((t,n)=>t!==e[n]),o=i||a,s=o?!0:r.some((e,t)=>{let n=this.#t[t];return!n||!De(e,n)});!o&&!s||(o&&(this.#l=t,this.#i=n),this.#t=r,this.hasListeners()&&(o&&(Uo(e,n).forEach(e=>{e.destroy()}),Uo(n,e).forEach(e=>{e.subscribe(t=>{this.#m(e,t)})})),this.#h()))})}getCurrentResult(){return this.#t}getQueries(){return this.#i.map(e=>e.getCurrentQuery())}getObservers(){return this.#i}getOptimisticResult(e,t){let n=this.#p(e),r=n.map(e=>e.observer.getOptimisticResult(e.defaultedQueryOptions)),i=n.map(e=>e.defaultedQueryOptions.queryHash);return[r,e=>this.#d(e??r,t,i),()=>this.#u(r,n)]}#u(e,t){let n=new Set;return t.map((r,i)=>{let a=e[i];return r.defaultedQueryOptions.notifyOnChangeProps?a:r.observer.trackResult(a,e=>{n.has(e)||(n.add(e),t.forEach(t=>{t.observer.trackProp(e)}))})})}#d(e,t,n){if(t){let r=this.#c,i=n!==void 0&&r!==void 0&&(r.length!==n.length||n.some((e,t)=>e!==r[t]));return(this.#t!==this.#s||i||t!==this.#o)&&(this.#o=t,this.#s=this.#t,n!==void 0&&(this.#c=n),this.#a=v(this.#a,t(e))),this.#a}return e}#f(){return!this.#r?.combine||this.#i.some((e,t)=>e.options.suspense&&this.#t[t]?.data===void 0)}#p(e){let t=new Map;this.#i.forEach(e=>{let n=e.options.queryHash;if(!n)return;let r=t.get(n);r?r.push(e):t.set(n,[e])});let n=[];return e.forEach(e=>{let r=this.#e.defaultQueryOptions(e),i=t.get(r.queryHash)?.shift()??new Et(this.#e,r);n.push({defaultedQueryOptions:r,observer:i})}),n}#m(e,t){let n=this.#i.indexOf(e);n!==-1&&(this.#t=this.#t.slice(),this.#t[n]=t,this.#h())}#h(){if(this.hasListeners()){let e=this.#f(),t=this.#a,n=e?t:this.#d(this.#u(this.#t,this.#l),this.#r?.combine);(e||t!==n)&&er.batch(()=>{this.listeners.forEach(e=>{e(this.#t)})})}}},Go=J.createContext(!1),Ko=()=>J.useContext(Go);Go.Provider;var X=ve();function qo(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Jo=J.createContext(qo()),Yo=()=>J.useContext(Jo),Xo=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?sn(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||r)&&(t.isReset()||(e.retryOnMount=!1))},Zo=e=>{J.useEffect(()=>{e.clearReset()},[e])},Qo=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||sn(n,[e.error,r])),$o=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},es=(e,t)=>e?.suspense&&t.isPending,ts=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function ns({queries:e,...t},n){let r=tn(n),i=Ko(),a=Yo(),o=t.subscribed!==!1,s=J.useMemo(()=>e.map(e=>{let t=r.defaultQueryOptions(e);return t._optimisticResults=i?`isRestoring`:o?`optimistic`:void 0,t}),[e,r,i,o]);s.forEach(e=>{$o(e);let t=r.getQueryCache().get(e.queryHash);Xo(e,a,t)}),Zo(a);let[c]=J.useState(()=>new Wo(r,s,t)),[l,u,d]=c.getOptimisticResult(s,t.combine),f=!i&&o;J.useSyncExternalStore(J.useCallback(e=>f?c.subscribe(er.batchCalls(e)):S,[c,f]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),J.useEffect(()=>{c.setQueries(s,t)},[s,t,c]);let p=l.some((e,t)=>es(s[t],e))?l.flatMap((e,t)=>{let n=s[t];return n&&es(n,e)?ts(n,new Et(r,n),a):[]}):[];if(p.length>0)throw Promise.all(p);let m=l.find((e,t)=>{let n=s[t];return n&&Qo({result:e,errorResetBoundary:a,throwOnError:n.throwOnError,query:r.getQueryCache().get(n.queryHash),suspense:n.suspense})});if(m)throw m.error;return u(d())}function rs(e,t,n){let r=Ko(),i=Yo(),a=tn(n),o=a.defaultQueryOptions(e),s=a.getQueryCache().get(o.queryHash),c=e.subscribed!==!1;o._optimisticResults=r?`isRestoring`:c?`optimistic`:void 0,$o(o),Xo(o,i,s),Zo(i);let[l]=J.useState(()=>new t(a,o)),u=l.getOptimisticResult(o),d=!r&&c;if(J.useSyncExternalStore(J.useCallback(e=>{let t=d?l.subscribe(er.batchCalls(e)):S;return l.updateResult(),t},[l,d]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),J.useEffect(()=>{l.setOptions(o)},[o,l]),es(o,u))throw ts(o,l,i);if(Qo({result:u,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw u.error;return o.notifyOnChangeProps?u:l.trackResult(u)}function is(e,t){return rs(e,Et,t)}function as(e,t){let n=tn(t),[r]=J.useState(()=>new sr(n,e));J.useEffect(()=>{r.setOptions(e)},[r,e]);let i=J.useSyncExternalStore(J.useCallback(e=>r.subscribe(er.batchCalls(e)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=J.useCallback((...e)=>{r.mutate(e[0],e[1]).catch(S)},[r]);if(i.error&&sn(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}var os=t((e=>{var t=qt();e.createRoot=t.createRoot,e.hydrateRoot=t.hydrateRoot}))();function ss(e,t){console.error(JSON.stringify({source:`agar`,operation:e,failureKind:t instanceof Error?`Error`:`NonErrorThrown`}),za(t))}var cs=Symbol(`workers-module`);Symbol.dispose||(Symbol.dispose=Symbol.for(`dispose`)),Symbol.asyncDispose||(Symbol.asyncDispose=Symbol.for(`asyncDispose`)),Promise.withResolvers||(Promise.withResolvers=function(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}});var ls=globalThis[cs],us=ls?ls.RpcTarget:class{},ds=async function(){}.constructor,fs=typeof Buffer<`u`?Buffer.prototype:void 0;function ps(e){switch(typeof e){case`boolean`:case`number`:case`string`:return`primitive`;case`undefined`:return`undefined`;case`object`:case`function`:break;case`bigint`:return`bigint`;default:return`unsupported`}if(e===null)return`primitive`;let t=Object.getPrototypeOf(e);switch(t){case Object.prototype:return`object`;case Function.prototype:case ds.prototype:return`function`;case Array.prototype:return`array`;case Date.prototype:return`date`;case Uint8Array.prototype:case fs:case ArrayBuffer.prototype:case DataView.prototype:case Int8Array.prototype:case Uint8ClampedArray.prototype:case Int16Array.prototype:case Uint16Array.prototype:case Int32Array.prototype:case Uint32Array.prototype:case BigInt64Array.prototype:case BigUint64Array.prototype:case Float32Array.prototype:case Float64Array.prototype:return`bytes`;case WritableStream.prototype:return`writable`;case ReadableStream.prototype:return`readable`;case URL.prototype:return`url`;case Headers.prototype:return`headers`;case Request.prototype:return`request`;case Response.prototype:return`response`;case Blob.prototype:return`blob`;case Ts.prototype:return`stub`;case Es.prototype:return`rpc-promise`;default:if(ls){if(t==ls.RpcStub.prototype||e instanceof ls.ServiceStub)return`rpc-target`;if(t==ls.RpcPromise.prototype||t==ls.RpcProperty.prototype)return`rpc-thenable`}return e instanceof us?`rpc-target`:e instanceof Error?`error`:`unsupported`}}function ms(){throw Error(`RPC map() implementation was not loaded.`)}var hs={applyMap:ms,sendMap:ms};function gs(){throw Error(`Stream implementation was not loaded.`)}var _s={createWritableStreamHook:gs,createWritableStreamFromHook:gs,createReadableStreamHook:gs},vs=class{stream(e,t){let n=this.call(e,t),r;try{r=n.pull()}catch(e){throw n.dispose(),e}let i;return r instanceof Promise?i=r.then(e=>{e.dispose()}):(r.dispose(),i=Promise.resolve()),{promise:i}}},ys=class extends vs{error;constructor(e){super(),this.error=e}call(e,t){return t.dispose(),this}map(e,t,n){for(let e of t)e.dispose();return this}get(e){return this}dup(){return this}pull(){return Promise.reject(this.error)}ignoreUnhandledRejections(){}dispose(){}onBroken(e){try{e(this.error)}catch(e){Promise.resolve(e)}}},bs=new ys(Error(`Attempted to use RPC stub after it has been disposed.`)),xs=(e,t,n)=>e.call(t,n);function Ss(e,t){let n=xs;xs=e;try{return t()}finally{xs=n}}var Cs=Symbol(`realStub`),ws={apply(e,t,n){let r=e.raw;return new Es(xs(r.hook,r.pathIfPromise||[],Ns.fromAppParams(n)),[])},get(e,t,n){let r=e.raw;if(t===Cs)return r;if(t in Es.prototype)return r[t];if(typeof t==`string`)return new Es(r.hook,r.pathIfPromise?[...r.pathIfPromise,t]:[t]);if(t===Symbol.dispose&&(!r.pathIfPromise||r.pathIfPromise.length==0))return()=>{r.hook.dispose(),r.hook=bs}},has(e,t){let n=e.raw;return t===Cs?!0:t in Es.prototype?t in n:typeof t==`string`||t===Symbol.dispose&&(!n.pathIfPromise||n.pathIfPromise.length==0)},construct(e,t){throw Error(`An RPC stub cannot be used as a constructor.`)},defineProperty(e,t,n){throw Error(`Can't define properties on RPC stubs.`)},deleteProperty(e,t){throw Error(`Can't delete properties on RPC stubs.`)},getOwnPropertyDescriptor(e,t){},getPrototypeOf(e){return Object.getPrototypeOf(e.raw)},isExtensible(e){return!1},ownKeys(e){return[]},preventExtensions(e){return!0},set(e,t,n,r){throw Error(`Can't assign properties on RPC stubs.`)},setPrototypeOf(e,t){throw Error(`Can't override prototype of RPC stubs.`)}},Ts=class e extends us{constructor(e,t){if(super(),!(e instanceof vs)){let n=e;if(e=n instanceof us||n instanceof Function?Rs.create(n,void 0):new Is(Ns.fromAppReturn(n)),t)throw TypeError(`RpcStub constructor expected one argument, received two.`)}this.hook=e,this.pathIfPromise=t;let n=()=>{};return n.raw=this,new Proxy(n,ws)}hook;pathIfPromise;dup(){let t=this[Cs];return t.pathIfPromise?new e(t.hook.get(t.pathIfPromise)):new e(t.hook.dup())}onRpcBroken(e){this[Cs].hook.onBroken(e)}map(e){let{hook:t,pathIfPromise:n}=this[Cs];return hs.sendMap(t,n||[],e)}toString(){return`[object RpcStub]`}},Es=class extends Ts{constructor(e,t){if(e instanceof vs)super(e,t??[]);else{if(t!==void 0)throw TypeError(`RpcPromise constructor expected one argument, received two.`);let n=ps(e);if(n===`rpc-promise`){let t=js(e);if(t.pathIfPromise.length>0)super(t.hook,t.pathIfPromise);else{let e=t.hook;t.hook=bs,super(e,[])}}else if(n===`rpc-thenable`)super(Rs.create(e,void 0),[]);else{let t=new zs(Promise.resolve(e).then(e=>new Is(Ns.fromAppReturn(e))));t.ignoreUnhandledRejections(),super(t,[])}}}then(e,t){return Ms(this).then(...arguments)}catch(e){return Ms(this).catch(...arguments)}finally(e){return Ms(this).finally(...arguments)}toString(){return`[object RpcPromise]`}};function Ds(e){let{hook:t,pathIfPromise:n}=e[Cs];return n&&n.length>0?t.get(n):t}function Os(e){let{hook:t,pathIfPromise:n}=e[Cs];return n?t.get(n):t.dup()}function ks(e){let{hook:t,pathIfPromise:n}=e[Cs];if(!(n&&n.length>0))return t}function As(e){return e[Cs].hook}function js(e){return e[Cs]}async function Ms(e){let{hook:t,pathIfPromise:n}=e[Cs];return n.length>0&&(t=t.get(n)),(await t.pull()).deliverResolve()}var Ns=class e{value;source;hooks;promises;static fromAppParams(t){return new e(t,`params`)}static fromAppReturn(t){return new e(t,`return`)}static fromArray(t){let n=[],r=[],i=[];for(let e of t){e.ensureDeepCopied();for(let t of e.hooks)n.push(t);for(let t of e.promises)t.parent===e&&(t={parent:i,property:i.length,promise:t.promise}),r.push(t);i.push(e.value)}return new e(i,`owned`,n,r)}static forEvaluate(t,n){return new e(null,`owned`,t,n)}static deepCopyFrom(t,n,r){let i=new e(null,`owned`,[],[]);return i.value=i.deepCopy(t,n,`value`,i,!0,r),i}constructor(e,t,n,r){this.value=e,this.source=t,this.hooks=n,this.promises=r}rpcTargets;getHookForRpcTarget(e,t,n=!0){if(this.source===`params`){if(n){let t=e;typeof t.dup==`function`&&(e=t.dup())}return Rs.create(e,t)}if(this.source===`return`){let r=this.rpcTargets?.get(e);return r?n?r.dup():(this.rpcTargets?.delete(e),r):(r=Rs.create(e,t),n?(this.rpcTargets||=new Map,this.rpcTargets.set(e,r),r.dup()):r)}throw Error(`owned payload shouldn't contain raw RpcTargets`)}getHookForWritableStream(e,t,n=!0){if(this.source===`params`)return _s.createWritableStreamHook(e);if(this.source===`return`){let t=this.rpcTargets?.get(e);return t?n?t.dup():(this.rpcTargets?.delete(e),t):(t=_s.createWritableStreamHook(e),n?(this.rpcTargets||=new Map,this.rpcTargets.set(e,t),t.dup()):t)}throw Error(`owned payload shouldn't contain raw WritableStreams`)}getHookForReadableStream(e,t,n=!0){if(this.source===`params`)return _s.createReadableStreamHook(e);if(this.source===`return`){let t=this.rpcTargets?.get(e);return t?n?t.dup():(this.rpcTargets?.delete(e),t):(t=_s.createReadableStreamHook(e),n?(this.rpcTargets||=new Map,this.rpcTargets.set(e,t),t.dup()):t)}throw Error(`owned payload shouldn't contain raw ReadableStreams`)}deepCopy(e,t,n,r,i,a){switch(ps(e)){case`unsupported`:return e;case`primitive`:case`bigint`:case`date`:case`bytes`:case`blob`:case`url`:case`error`:case`undefined`:return e;case`array`:{let t=e,n=t.length,r=Array(n);for(let e=0;e<n;e++)r[e]=this.deepCopy(t[e],t,e,r,i,a);return r}case`object`:{let t={},n=e;for(let e in n)t[e]=this.deepCopy(n[e],n,e,t,i,a);return t}case`stub`:case`rpc-promise`:{let t=e,a;if(a=i?Os(t):Ds(t),t instanceof Es){let e=new Es(a,[]);return this.promises.push({parent:r,property:n,promise:e}),e}return this.hooks.push(a),new Ts(a)}case`function`:case`rpc-target`:{let n=e,r;return r=a?a.getHookForRpcTarget(n,t,i):Rs.create(n,t),this.hooks.push(r),new Ts(r)}case`rpc-thenable`:{let o=e,s;return s=a?new Es(a.getHookForRpcTarget(o,t,i),[]):new Es(Rs.create(o,t),[]),this.promises.push({parent:r,property:n,promise:s}),s}case`writable`:{let n=e,r;return r=a?a.getHookForWritableStream(n,t,i):_s.createWritableStreamHook(n),this.hooks.push(r),n}case`readable`:{let n=e,r;return r=a?a.getHookForReadableStream(n,t,i):_s.createReadableStreamHook(n),this.hooks.push(r),n}case`headers`:return new Headers(e);case`request`:{let t=e;return t.body&&this.deepCopy(t.body,t,`body`,t,i,a),new Request(t)}case`response`:{let t=e;return t.body&&this.deepCopy(t.body,t,`body`,t,i,a),new Response(t.body,t)}default:throw Error(`unreachable`)}}ensureDeepCopied(){if(this.source!==`owned`){let e=this.source===`params`;this.hooks=[],this.promises=[];try{this.value=this.deepCopy(this.value,void 0,`value`,this,e,this)}catch(e){throw this.hooks=void 0,this.promises=void 0,e}if(this.source=`owned`,this.rpcTargets&&this.rpcTargets.size>0)throw Error(`Not all rpcTargets were accounted for in deep-copy?`);this.rpcTargets=void 0}}deliverTo(t,n,r){if(this.ensureDeepCopied(),this.value instanceof Es)e.deliverRpcPromiseTo(this.value,t,n,r);else{t[n]=this.value;for(let t of this.promises)e.deliverRpcPromiseTo(t.promise,t.parent,t.property,r)}}static deliverRpcPromiseTo(t,n,r,i){let a=ks(t);if(!a)throw Error(`property promises should have been resolved earlier`);let o=a.pull();o instanceof e?o.deliverTo(n,r,i):i.push(o.then(e=>{let t=[];if(e.deliverTo(n,r,t),t.length>0)return Promise.all(t)}))}async deliverCall(t,n){try{let r=[];this.deliverTo(this,`value`,r),r.length>0&&await Promise.all(r);let i=Function.prototype.apply.call(t,n,this.value);return i instanceof Es?e.fromAppReturn(i):e.fromAppReturn(await i)}finally{this.dispose()}}async deliverStreamWrite(t){try{let n=[];this.deliverTo(this,`value`,n),n.length>0&&await Promise.all(n);let r=this.value[0];return(this.hooks.length>0||this.promises.length>0)&&r instanceof Object?(Symbol.dispose in r||Object.defineProperty(r,Symbol.dispose,{value:()=>this.dispose(),writable:!0,enumerable:!1,configurable:!0}),await t.write(r),e.fromAppReturn(void 0)):(await t.write(r),this.dispose(),e.fromAppReturn(void 0))}catch(e){throw this.dispose(),e}}async deliverResolve(){try{let e=[];this.deliverTo(this,`value`,e),e.length>0&&await Promise.all(e);let t=this.value;return t instanceof Object&&(Symbol.dispose in t||Object.defineProperty(t,Symbol.dispose,{value:()=>this.dispose(),writable:!0,enumerable:!1,configurable:!0})),t}catch(e){throw this.dispose(),e}}dispose(){if(this.source===`owned`)this.hooks.forEach(e=>e.dispose()),this.promises.forEach(e=>e.promise[Symbol.dispose]());else if(this.source===`return`&&(this.disposeImpl(this.value,void 0),this.rpcTargets&&this.rpcTargets.size>0))throw Error(`Not all rpcTargets were accounted for in disposeImpl()?`);this.source=`owned`,this.hooks=[],this.promises=[]}disposeImpl(e,t){switch(ps(e)){case`unsupported`:case`primitive`:case`bigint`:case`bytes`:case`blob`:case`date`:case`url`:case`error`:case`undefined`:return;case`array`:{let t=e,n=t.length;for(let e=0;e<n;e++)this.disposeImpl(t[e],t);return}case`object`:{let t=e;for(let e in t)this.disposeImpl(t[e],t);return}case`stub`:case`rpc-promise`:{let t=ks(e);t&&t.dispose();return}case`function`:case`rpc-target`:{let t=e,n=this.rpcTargets?.get(t);n?(n.dispose(),this.rpcTargets.delete(t)):Ls(t);return}case`rpc-thenable`:return;case`headers`:return;case`request`:{let t=e;t.body&&this.disposeImpl(t.body,t);return}case`response`:{let t=e;t.body&&this.disposeImpl(t.body,t);return}case`writable`:{let t=e,n=this.rpcTargets?.get(t);n?this.rpcTargets.delete(t):n=_s.createWritableStreamHook(t),n.dispose();return}case`readable`:{let t=e,n=this.rpcTargets?.get(t);n?this.rpcTargets.delete(t):n=_s.createReadableStreamHook(t),n.dispose();return}default:return}}ignoreUnhandledRejections(){this.hooks?(this.hooks.forEach(e=>{e.ignoreUnhandledRejections()}),this.promises.forEach(e=>As(e.promise).ignoreUnhandledRejections())):this.ignoreUnhandledRejectionsImpl(this.value)}ignoreUnhandledRejectionsImpl(e){switch(ps(e)){case`unsupported`:case`primitive`:case`bigint`:case`bytes`:case`blob`:case`date`:case`error`:case`undefined`:case`function`:case`rpc-target`:case`writable`:case`readable`:case`url`:case`headers`:case`request`:case`response`:return;case`array`:{let t=e,n=t.length;for(let e=0;e<n;e++)this.ignoreUnhandledRejectionsImpl(t[e]);return}case`object`:{let t=e;for(let e in t)this.ignoreUnhandledRejectionsImpl(t[e]);return}case`stub`:case`rpc-promise`:As(e).ignoreUnhandledRejections();return;case`rpc-thenable`:e.then(e=>{},e=>{});return;default:return}}};function Ps(e,t,n,r){for(let i=0;i<n.length;i++){t=e;let a=n[i];if(a in Object.prototype){e=void 0;continue}switch(ps(e)){case`object`:case`function`:e=Object.hasOwn(e,a)?e[a]:void 0;break;case`array`:e=Number.isInteger(a)&&a>=0?e[a]:void 0;break;case`rpc-target`:case`rpc-thenable`:if(Object.hasOwn(e,a))throw TypeError(`Attempted to access property '${a}', which is an instance property of the RpcTarget. To avoid leaking private internals, instance properties cannot be accessed over RPC. If you want to make this property available over RPC, define it as a method or getter on the class, instead of an instance property.`);e=e[a],r=null;break;case`stub`:case`rpc-promise`:{let{hook:t,pathIfPromise:r}=js(e);return{hook:t,remainingPath:r?r.concat(n.slice(i)):n.slice(i)}}case`writable`:e=void 0;break;case`readable`:e=void 0;break;case`primitive`:case`bigint`:case`bytes`:case`blob`:case`date`:case`error`:case`url`:case`headers`:case`request`:case`response`:e=void 0;break;case`undefined`:e=e[a];break;case`unsupported`:if(i===0)throw TypeError(`RPC stub points at a non-serializable type.`);{let e=n.slice(0,i).join(`.`),t=n.slice(0,i).join(`.`);throw TypeError(`'${e}' is not a serializable type, so property ${t} cannot be accessed.`)}default:throw TypeError(`unreachable`)}}if(e instanceof Es){let{hook:t,pathIfPromise:n}=js(e);return{hook:t,remainingPath:n||[]}}return{value:e,parent:t,owner:r}}var Fs=class extends vs{call(e,t){let n;try{let{value:t,owner:r}=this.getValue();n=Ps(t,void 0,e,r)}catch(e){return t.dispose(),new ys(e)}return n.hook?n.hook.call(n.remainingPath,t):typeof n.value==`function`?new zs(t.deliverCall(n.value,n.parent).then(e=>new Is(e))):(t.dispose(),new ys(TypeError(`'${e.join(`.`)}' is not a function.`)))}map(e,t,n){try{let r;try{let{value:t,owner:n}=this.getValue();r=Ps(t,void 0,e,n)}catch(e){for(let e of t)e.dispose();throw e}return r.hook?r.hook.map(r.remainingPath,t,n):hs.applyMap(r.value,r.parent,r.owner,t,n)}catch(e){return new ys(e)}}get(e){try{let{value:t,owner:n}=this.getValue();if(e.length===0&&n===null){if(t instanceof Object&&`then`in t)return this.dup();throw Error(`Can't dup an RpcTarget stub as a promise.`)}let r=Ps(t,void 0,e,n);return r.hook?r.hook.get(r.remainingPath):new Is(Ns.deepCopyFrom(r.value,r.parent,r.owner))}catch(e){return new ys(e)}}},Is=class e extends Fs{constructor(e){super(),this.payload=e}payload;getPayload(){if(this.payload)return this.payload;throw Error(`Attempted to use an RPC StubHook after it was disposed.`)}getValue(){let e=this.getPayload();return{value:e.value,owner:e}}dup(){let t=this.getPayload();return new e(Ns.deepCopyFrom(t.value,void 0,t))}pull(){return this.getPayload()}ignoreUnhandledRejections(){this.payload&&this.payload.ignoreUnhandledRejections()}dispose(){this.payload&&=(this.payload.dispose(),void 0)}onBroken(e){this.payload&&this.payload.value instanceof Ts&&this.payload.value.onRpcBroken(e)}};function Ls(e){if(Symbol.dispose in e)try{e[Symbol.dispose]()}catch(e){Promise.reject(e)}}var Rs=class e extends Fs{static create(t,n){return typeof t!=`function`&&(n=void 0),new e(t,n)}constructor(e,t,n){super(),this.target=e,this.parent=t,n?n.refcount&&(this.refcount=n.refcount,++this.refcount.count):Symbol.dispose in e&&(this.refcount={count:1})}target;parent;refcount;getTarget(){if(this.target)return this.target;throw Error(`Attempted to use an RPC StubHook after it was disposed.`)}getValue(){return{value:this.getTarget(),owner:null}}dup(){return new e(this.getTarget(),this.parent,this)}pull(){let e=this.getTarget();return`then`in e?Promise.resolve(e).then(e=>Ns.fromAppReturn(e)):Promise.reject(Error(`Tried to resolve a non-promise stub.`))}ignoreUnhandledRejections(){}dispose(){this.target&&=(this.refcount&&--this.refcount.count==0&&Ls(this.target),void 0)}onBroken(e){let t=this.target;t&&`then`in t&&Promise.resolve(t).then(()=>{},e)}},zs=class e extends vs{promise;resolution;constructor(e){super(),this.promise=e.then(e=>(this.resolution=e,e))}call(t,n){return n.ensureDeepCopied(),new e(this.promise.then(e=>e.call(t,n),e=>{throw n.dispose(),e}))}stream(e,t){return t.ensureDeepCopied(),{promise:this.promise.then(n=>n.stream(e,t).promise,e=>{throw t.dispose(),e})}}map(t,n,r){return new e(this.promise.then(e=>e.map(t,n,r),e=>{for(let e of n)e.dispose();throw e}))}get(t){return new e(this.promise.then(e=>e.get(t)))}dup(){return this.resolution?this.resolution.dup():new e(this.promise.then(e=>e.dup()))}pull(){return this.resolution?this.resolution.pull():this.promise.then(e=>e.pull())}ignoreUnhandledRejections(){this.resolution?this.resolution.ignoreUnhandledRejections():this.promise.then(e=>{e.ignoreUnhandledRejections()},e=>{})}dispose(){this.promise.then(e=>e.dispose(),()=>{})}onBroken(e){this.resolution?this.resolution.onBroken(e):this.promise.then(t=>{t.onBroken(e)},e)}},Bs={maxBigIntDigits:16384,maxDepth:256,maxMessageSize:33554432},Vs=new Uint8Array(new Uint16Array([1]).buffer)[0]===1,Hs=[`ArrayBuffer`,`DataView`,`Int8Array`,`Uint8Array`,`Uint8ClampedArray`,`Int16Array`,`Uint16Array`,`Int32Array`,`Uint32Array`,`BigInt64Array`,`BigUint64Array`,`Float32Array`,`Float64Array`];function Us(e){return Hs.includes(e)}var Ws={ArrayBuffer:void 0,DataView:void 0,Int8Array:void 0,Uint8Array:void 0,Uint8ClampedArray:void 0,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,BigInt64Array:8,BigUint64Array:8,Float32Array:4,Float64Array:8},Gs={ArrayBuffer:ArrayBuffer.prototype,DataView:DataView.prototype,Int8Array:Int8Array.prototype,Uint8ClampedArray:Uint8ClampedArray.prototype,Int16Array:Int16Array.prototype,Uint16Array:Uint16Array.prototype,Int32Array:Int32Array.prototype,Uint32Array:Uint32Array.prototype,BigInt64Array:BigInt64Array.prototype,BigUint64Array:BigUint64Array.prototype,Float32Array:Float32Array.prototype,Float64Array:Float64Array.prototype},Ks=new Map;for(let e of Object.keys(Gs))Ks.set(Gs[e],e);function qs(e,t){if(t!==2&&t!==4&&t!==8)throw RangeError(`Unsupported element size: ${t}`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let r=0;r<e.byteLength;r+=t)switch(t){case 2:n.setUint16(r,n.getUint16(r,!1),!0);break;case 4:n.setUint32(r,n.getUint32(r,!1),!0);break;case 8:n.setBigUint64(r,n.getBigUint64(r,!1),!0)}}var Js=new class{exportStub(e){throw Error(`Cannot serialize RPC stubs without an RPC session.`)}exportPromise(e){throw Error(`Cannot serialize RPC stubs without an RPC session.`)}getImport(e){}unexport(e){}createPipe(e){throw Error(`Cannot create pipes without an RPC session.`)}onSendError(e){}};async function Ys(e,t){let n=await new Response(e).blob();return n.type===t?n:n.slice(0,n.size,t)}var Xs={__proto__:null,Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError},Zs=class e{exporter;source;encodingLevel;constructor(e,t,n){this.exporter=e,this.source=t,this.encodingLevel=n}static devaluate(t,n,r=Js,i,a=`string`){let o=new e(r,i,a);try{return o.devaluateImpl(t,n,0)}catch(e){if(o.exports)try{r.unexport(o.exports)}catch{}throw e}}exports;devaluateImpl(e,t,n){if(n>=256)throw Error(`Serialization exceeded maximum allowed depth. (Does the message contain cycles?)`);switch(ps(e)){case`unsupported`:{let t;try{t=`Cannot serialize value: ${e}`}catch{t=`Cannot serialize value: (couldn't stringify value)`}throw TypeError(t)}case`primitive`:return typeof e==`number`&&!isFinite(e)?this.encodingLevel===`structuredClonable`?e:e===1/0?[`inf`]:e===-1/0?[`-inf`]:[`nan`]:e;case`object`:{let t=e,r={};for(let e in t)r[e]=this.devaluateImpl(t[e],t,n+1);return r}case`array`:{let t=e,r=t.length,i=Array(r);for(let e=0;e<r;e++)i[e]=this.devaluateImpl(t[e],t,n+1);return[i]}case`bigint`:return this.encodingLevel===`structuredClonable`?e:[`bigint`,e.toString()];case`date`:{if(this.encodingLevel===`structuredClonable`)return e;let t=e.getTime();return[`date`,Number.isNaN(t)?null:t]}case`bytes`:{let t=Ks.get(Object.getPrototypeOf(e)),n;if(t===`ArrayBuffer`)n=new Uint8Array(e);else if(t===void 0)n=e;else{let r=e;n=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);let i=Ws[t];!Vs&&i&&(n=n.slice(),qs(n,i))}if(this.encodingLevel===`structuredClonable`||this.encodingLevel===`jsonCompatibleWithBytes`)return t===void 0?[`bytes`,n]:[`bytes`,n,t];let r;if(n.toBase64)r=n.toBase64({omitPadding:!0});else if(typeof Buffer<`u`)r=(n instanceof Buffer?n:Buffer.from(n.buffer,n.byteOffset,n.byteLength)).toString(`base64`);else{let e=``;for(let t=0;t<n.length;t++)e+=String.fromCharCode(n[t]);r=btoa(e)}return r=r.replace(/=+$/,``),t===void 0?[`bytes`,r]:[`bytes`,r,t]}case`url`:return[`url`,e.href];case`headers`:return[`headers`,[...e]];case`request`:{let t=e,r={};t.method!==`GET`&&(r.method=t.method);let i=[...t.headers];if(i.length>0&&(r.headers=i),t.body)r.body=this.devaluateImpl(t.body,t,n+1),r.duplex=t.duplex||`half`;else if(t.body===void 0&&![`GET`,`HEAD`,`OPTIONS`,`TRACE`,`DELETE`].includes(t.method)){let e=t.arrayBuffer(),n=new ReadableStream({async start(t){try{t.enqueue(new Uint8Array(await e)),t.close()}catch(e){t.error(e)}}}),i=_s.createReadableStreamHook(n);r.body=[`readable`,this.exporter.createPipe(n,i)],r.duplex=t.duplex||`half`}t.cache&&t.cache!=="default"&&(r.cache=t.cache),t.redirect!==`follow`&&(r.redirect=t.redirect),t.integrity&&(r.integrity=t.integrity),t.mode&&t.mode!==`cors`&&(r.mode=t.mode),t.credentials&&t.credentials!==`same-origin`&&(r.credentials=t.credentials),t.referrer&&t.referrer!==`about:client`&&(r.referrer=t.referrer),t.referrerPolicy&&(r.referrerPolicy=t.referrerPolicy),t.keepalive&&(r.keepalive=t.keepalive);let a=t;return a.cf&&(r.cf=a.cf),a.encodeResponseBody&&a.encodeResponseBody!==`automatic`&&(r.encodeResponseBody=a.encodeResponseBody),[`request`,t.url,r]}case`response`:{let t=e,r=this.devaluateImpl(t.body,t,n+1),i={};t.status!==200&&(i.status=t.status),t.statusText&&(i.statusText=t.statusText);let a=[...t.headers];a.length>0&&(i.headers=a);let o=t;if(o.cf&&(i.cf=o.cf),o.encodeBody&&o.encodeBody!==`automatic`&&(i.encodeBody=o.encodeBody),o.webSocket)throw TypeError(`Can't serialize a Response containing a webSocket.`);return[`response`,r,i]}case`blob`:{let t=e,n=t.stream(),r=_s.createReadableStreamHook(n),i=this.exporter.createPipe(n,r);return[`blob`,t.type,[`readable`,i]]}case`error`:{let t=e,r=this.exporter.onSendError(t);r&&(t=r);let i=t,a,o=(e,r)=>{let i=this.exports?.length??0;try{let i=this.devaluateImpl(r,t,n+1);a||={},a[e]=i}catch{if(this.exports&&this.exports.length>i){let e=this.exports.splice(i);try{this.exporter.unexport(e)}catch{}}}};for(let e of Object.keys(t))e!==`name`&&e!==`message`&&e!==`stack`&&o(e,i[e]);`cause`in t&&o(`cause`,i.cause),t instanceof AggregateError&&o(`errors`,t.errors);let s=[`error`,t.name,t.message];return a?(s.push(r&&r.stack?r.stack:null),s.push(a)):r&&r.stack&&s.push(r.stack),s}case`undefined`:return this.encodingLevel===`structuredClonable`?void 0:[`undefined`];case`stub`:case`rpc-promise`:{if(!this.source)throw Error(`Can't serialize RPC stubs in this context.`);let{hook:t,pathIfPromise:n}=js(e),r=this.exporter.getImport(t);return r===void 0?(t=n?t.get(n):t.dup(),this.devaluateHook(n?`promise`:`export`,t)):n?n.length>0?[`pipeline`,r,n]:[`pipeline`,r]:[`import`,r]}case`function`:case`rpc-target`:{if(!this.source)throw Error(`Can't serialize RPC stubs in this context.`);let n=this.source.getHookForRpcTarget(e,t);return this.devaluateHook(`export`,n)}case`rpc-thenable`:{if(!this.source)throw Error(`Can't serialize RPC stubs in this context.`);let n=this.source.getHookForRpcTarget(e,t);return this.devaluateHook(`promise`,n)}case`writable`:{if(!this.source)throw Error(`Can't serialize WritableStream in this context.`);let n=this.source.getHookForWritableStream(e,t);return this.devaluateHook(`writable`,n)}case`readable`:{if(!this.source)throw Error(`Can't serialize ReadableStream in this context.`);let n=e,r=this.source.getHookForReadableStream(n,t);return[`readable`,this.exporter.createPipe(n,r)]}default:throw Error(`unreachable`)}}devaluateHook(e,t){this.exports||=[];let n=e===`promise`?this.exporter.exportPromise(t):this.exporter.exportStub(t);return this.exports.push(n),[e,n]}};new class{importStub(e){throw Error(`Cannot deserialize RPC stubs without an RPC session.`)}importPromise(e){throw Error(`Cannot deserialize RPC stubs without an RPC session.`)}getExport(e){}getPipeReadable(e){throw Error(`Cannot retrieve pipe readable without an RPC session.`)}getLimits(){return Bs}};function Qs(e,t){return new Es(new zs(new Response(t).arrayBuffer().then(t=>{let n=new Uint8Array(t),r=new Request(e,{body:n});return new Is(Ns.fromAppReturn(r))})),[])}function $s(e,t){return new Es(new zs(Ys(e,t).then(e=>new Is(Ns.fromAppReturn(e)))),[])}var ec=class e{importer;encodingLevel;limits;constructor(e,t=`string`){this.importer=e,this.encodingLevel=t,this.limits=e.getLimits()}hooks=[];promises=[];evaluate(e){return this.evaluateWithDepth(e,0)}evaluateWithDepth(e,t){let n=Ns.forEvaluate(this.hooks,this.promises);try{return n.value=this.evaluateImpl(e,n,`value`,t),n}catch(e){throw n.dispose(),e}}evaluateCopy(e){return this.evaluate(structuredClone(e))}evaluateImpl(t,n,r,i){let a=this.limits.maxDepth;if(i>=a)throw TypeError(`Deserialization exceeded maximum allowed message depth of ${a}.`);if(this.encodingLevel===`structuredClonable`&&(t instanceof Date||typeof t==`bigint`))return t;if(t instanceof Array){if(t.length==1&&t[0]instanceof Array){let e=t[0];for(let t=0;t<e.length;t++)e[t]=this.evaluateImpl(e[t],e,t,i+1);return e}switch(t[0]){case`bigint`:if(typeof t[1]==`string`){let e=t[1],n=this.limits.maxBigIntDigits;if(e.length>n)throw TypeError(`Deserialized bigint exceeds maximum length of ${n} digits.`);return BigInt(e)}break;case`date`:if(t[1]===null)return new Date(NaN);if(typeof t[1]==`number`)return new Date(t[1]);break;case`bytes`:{let e;if(t[1]instanceof Uint8Array)e=t[1];else if(typeof t[1]==`string`){if(typeof Buffer<`u`)e=Buffer.from(t[1],`base64`);else if(Uint8Array.fromBase64)e=Uint8Array.fromBase64(t[1]);else{let n=atob(t[1]),r=n.length;e=new Uint8Array(r);for(let t=0;t<r;t++)e[t]=n.charCodeAt(t)}}else break;if(t.length===2)return e;if(typeof t[2]!=`string`)throw TypeError(`Unknown bytes type marker type: ${typeof t[2]}`);if(!Us(t[2])){let e=t[2].slice(0,64);throw TypeError(`Unknown bytes type marker: ${e}`)}let n=t[2],r=Ws[n];if(r!==void 0&&e.byteLength%r!==0)throw TypeError(`Invalid byte length ${e.byteLength} for ${n}; expected a multiple of ${r}`);let i=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);switch(!Vs&&r!==void 0&&qs(new Uint8Array(i),r),n){case`ArrayBuffer`:return i;case`DataView`:return new DataView(i);case`Int8Array`:return new Int8Array(i);case`Uint8Array`:return new Uint8Array(i);case`Uint8ClampedArray`:return new Uint8ClampedArray(i);case`Int16Array`:return new Int16Array(i);case`Uint16Array`:return new Uint16Array(i);case`Int32Array`:return new Int32Array(i);case`Uint32Array`:return new Uint32Array(i);case`BigInt64Array`:return new BigInt64Array(i);case`BigUint64Array`:return new BigUint64Array(i);case`Float32Array`:return new Float32Array(i);case`Float64Array`:return new Float64Array(i)}}case`error`:if(t.length>=3&&typeof t[1]==`string`&&typeof t[2]==`string`){let e=Xs[t[1]]||Error,n=e===AggregateError?new e([],t[2]):new e(t[2]);if(typeof t[3]==`string`&&(n.stack=t[3]),t.length>=5){let e=t[4];if(!e||typeof e!=`object`||Array.isArray(e))break;let r=n,a=e;for(let e of Object.keys(a))if(e!==`name`&&e!==`message`&&e!==`stack`){if(e in Object.prototype||e===`toJSON`){this.evaluateImpl(a[e],n,e,i+1);continue}r[e]=this.evaluateImpl(a[e],n,e,i+1)}}return n}break;case`undefined`:if(t.length===1)return;break;case`inf`:return 1/0;case`-inf`:return-1/0;case`nan`:return NaN;case`url`:if(t.length===2&&typeof t[1]==`string`)return new URL(t[1]);break;case`headers`:if(t.length===2&&t[1]instanceof Array)return new Headers(t[1]);break;case`request`:{if(t.length!==3||typeof t[1]!=`string`)break;let e=t[1],a=t[2];if(typeof a!=`object`||!a)break;if(a.body&&(a.body=this.evaluateImpl(a.body,a,`body`,i+1),!(a.body===null||typeof a.body==`string`||a.body instanceof Uint8Array||a.body instanceof ReadableStream)))throw TypeError(`Request body must be of type ReadableStream.`);if(a.signal&&(a.signal=this.evaluateImpl(a.signal,a,`signal`,i+1),!(a.signal instanceof AbortSignal)))throw TypeError(`Request siganl must be of type AbortSignal.`);if(a.headers&&!(a.headers instanceof Array))throw TypeError(`Request headers must be serialized as an array of pairs.`);let o=new Request(e,a);if(a.body instanceof ReadableStream&&o.body===void 0){let e=Qs(o,a.body);return this.promises.push({promise:e,parent:n,property:r}),e}return o}case`response`:{if(t.length!==3)break;let e=this.evaluateImpl(t[1],n,r,i+1);if(!(e===null||typeof e==`string`||e instanceof Uint8Array||e instanceof ReadableStream))throw TypeError(`Response body must be of type ReadableStream.`);let a=t[2];if(typeof a!=`object`||!a)break;if(a.webSocket)throw TypeError(`Can't deserialize a Response containing a webSocket.`);if(a.headers&&!(a.headers instanceof Array))throw TypeError(`Request headers must be serialized as an array of pairs.`);return new Response(e,a)}case`blob`:{if(t.length!==3||typeof t[1]!=`string`)break;let e=t[1],a=this.evaluateImpl(t[2],n,r,i+1);if(!(a instanceof ReadableStream))throw TypeError(`Blob content must be serialized as a ReadableStream.`);let o=$s(a,e);return this.promises.push({promise:o,parent:n,property:r}),o}case`import`:case`pipeline`:{if(t.length<2||t.length>4||typeof t[1]!=`number`)break;let a=this.importer.getExport(t[1]);if(!a)throw Error(`no such entry on exports table: ${t[1]}`);let o=t[0]==`pipeline`,s=e=>{if(o){let t=new Es(e,[]);return this.promises.push({promise:t,parent:n,property:r}),t}return this.hooks.push(e),new Es(e,[])};if(t.length==2)return s(o?a.get([]):a.dup());let c=t[2];if(!(c instanceof Array)||!c.every(e=>typeof e==`string`||typeof e==`number`))break;if(t.length==3)return s(a.get(c));let l=t[3];if(!(l instanceof Array))break;return l=new e(this.importer).evaluateWithDepth([l],i),s(a.call(c,l))}case`remap`:{if(t.length!==5||typeof t[1]!=`number`||!(t[2]instanceof Array)||!(t[3]instanceof Array)||!(t[4]instanceof Array))break;let e=this.importer.getExport(t[1]);if(!e)throw Error(`no such entry on exports table: ${t[1]}`);let i=t[2];if(!i.every(e=>typeof e==`string`||typeof e==`number`))break;let a=t[3].map(e=>{if(!(e instanceof Array)||e.length!==2||e[0]!==`import`&&e[0]!==`export`||typeof e[1]!=`number`)throw TypeError(`unknown map capture: ${JSON.stringify(e)}`);if(e[0]===`export`)return this.importer.importStub(e[1]);{let t=this.importer.getExport(e[1]);if(!t)throw Error(`no such entry on exports table: ${e[1]}`);return t.dup()}}),o=t[4],s=new Es(e.map(i,a,o),[]);return this.promises.push({promise:s,parent:n,property:r}),s}case`export`:case`promise`:if(typeof t[1]==`number`){if(t[0]==`promise`){let e=new Es(this.importer.importPromise(t[1]),[]);return this.promises.push({parent:n,property:r,promise:e}),e}{let e=this.importer.importStub(t[1]);return this.hooks.push(e),new Ts(e)}}break;case`writable`:if(typeof t[1]==`number`){let e=this.importer.importStub(t[1]),n=_s.createWritableStreamFromHook(e);return this.hooks.push(e),n}break;case`readable`:if(typeof t[1]==`number`){let e=this.importer.getPipeReadable(t[1]),n=_s.createReadableStreamHook(e);return this.hooks.push(n),e}}throw TypeError(`unknown special value: ${JSON.stringify(t)}`)}if(t instanceof Object){let e=t;for(let t in e)t in Object.prototype||t===`toJSON`?(this.evaluateImpl(e[t],e,t,i+1),delete e[t]):e[t]=this.evaluateImpl(e[t],e,t,i+1);return e}return t}},tc=16,nc=8,rc=16,ic=64;function ac(e){return 2+e.length*3}function oc(e,t,n=0){if(n>=ic)return nc;switch(typeof e){case`string`:return ac(e);case`number`:return 16;case`bigint`:return 16;case`boolean`:return 8;case`undefined`:return 16;case`object`:{if(e===null)return 8;if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return rc+e.byteLength;if(typeof Blob<`u`&&e instanceof Blob)return rc+e.size;if(e instanceof Date)return 16;if(t??=new WeakSet,t.has(e))return nc;if(t.add(e),e instanceof Array){let r=tc;for(let i of e)r+=nc+oc(i,t,n+1);return r}if(e instanceof Error){let r=tc+ac(e.name)+ac(e.message)+ac(e.stack??``);for(let i of Object.keys(e))r+=nc+ac(i)+oc(e[i],t,n+1);return r}let r=tc;for(let i of Object.keys(e))r+=nc+ac(i)+oc(e[i],t,n+1);return r}default:return 16}}var sc=class{session;importId;constructor(e,t,n){this.session=e,this.importId=t,n&&(this.activePull=Promise.withResolvers())}localRefcount=0;remoteRefcount=1;activePull;resolution;onBrokenRegistrations;resolve(e){if(this.localRefcount==0){e.dispose();return}if(this.resolution=e,this.sendRelease(),this.onBrokenRegistrations){for(let t of this.onBrokenRegistrations){let n=this.session.onBrokenCallbacks[t],r=this.session.onBrokenCallbacks.length;e.onBroken(n),this.session.onBrokenCallbacks[r]===n?delete this.session.onBrokenCallbacks[r]:delete this.session.onBrokenCallbacks[t]}this.onBrokenRegistrations=void 0}this.activePull&&=(this.activePull.resolve(),void 0)}async awaitResolution(){return this.activePull||=(this.session.sendPull(this.importId),Promise.withResolvers()),await this.activePull.promise,this.resolution.pull()}dispose(){this.resolution?this.resolution.dispose():(this.abort(Error(`RPC was canceled because the RpcPromise was disposed.`)),this.sendRelease())}abort(e){if(!this.resolution){if(this.resolution=new ys(e),this.activePull&&=(this.activePull.reject(e),void 0),this.onBrokenRegistrations)for(let e of this.onBrokenRegistrations)delete this.session.onBrokenCallbacks[e];this.onBrokenRegistrations=void 0}}onBroken(e){if(this.resolution)this.resolution.onBroken(e);else{let t=this.session.onBrokenCallbacks.length;this.session.onBrokenCallbacks.push(e),this.onBrokenRegistrations||=[],this.onBrokenRegistrations.push(t)}}sendRelease(){this.remoteRefcount>0&&(this.session.sendRelease(this.importId,this.remoteRefcount),this.remoteRefcount=0)}},cc=class e extends vs{isPromise;entry;constructor(e,t){super(),this.isPromise=e,++t.localRefcount,this.entry=t}collectPath(e){return this}getEntry(){if(this.entry)return this.entry;throw Error(`This RpcImportHook was already disposed.`)}getEntryTakingOwnership(e){try{return this.getEntry()}catch(t){throw e(),t}}call(e,t){let n=this.getEntryTakingOwnership(()=>t.dispose());return n.resolution?n.resolution.call(e,t):n.session.sendCall(n.importId,e,t)}stream(e,t){let n=this.getEntryTakingOwnership(()=>t.dispose());return n.resolution?n.resolution.stream(e,t):n.session.sendStream(n.importId,e,t)}map(e,t,n){let r=this.getEntryTakingOwnership(()=>{for(let e of t)e.dispose()});return r.resolution?r.resolution.map(e,t,n):r.session.sendMap(r.importId,e,t,n)}get(e){let t=this.getEntry();return t.resolution?t.resolution.get(e):t.session.sendCall(t.importId,e)}dup(){return new e(!1,this.getEntry())}pull(){let e=this.getEntry();if(!this.isPromise)throw Error(`Can't pull this hook because it's not a promise hook.`);return e.resolution?e.resolution.pull():e.awaitResolution()}ignoreUnhandledRejections(){}dispose(){let e=this.entry;this.entry=void 0,e&&--e.localRefcount===0&&e.dispose()}onBroken(e){this.entry&&this.entry.onBroken(e)}},lc=class extends cc{session;constructor(e){super(!1,e),this.session=e.session}dispose(){if(this.session){let e=this.session;this.session=void 0,e.shutdown()}}},uc=class{transport;options;exports=[];reverseExports=new Map;imports=[];abortReason;cancelReadLoop;nextExportId=-1;onBatchDone;pullCount=0;onBrokenCallbacks=[];encodingLevel;limits;constructor(e,t,n){this.transport=e,this.options=n;let r=`string`;if(`encodingLevel`in e){let t=e.encodingLevel;if(t!==void 0){if(t!==`string`&&t!==`jsonCompatible`&&t!==`jsonCompatibleWithBytes`&&t!==`structuredClonable`)throw TypeError(`Unknown transport encodingLevel: ${String(t)}`);r=t}}this.encodingLevel=r,this.limits={...Bs,...n.limits},this.exports.push({hook:t,refcount:1}),this.imports.push(new sc(this,0,!1)),this.readLoop().catch(e=>this.abort(e))}getMainImport(){return new lc(this.imports[0])}shutdown(){this.abort(Error(`RPC session was shut down by disposing the main stub`),!1)}exportStub(e){if(this.abortReason)throw this.abortReason;let t=this.reverseExports.get(e);if(t!==void 0)return++this.exports[t].refcount,t;{let t=this.nextExportId--;return this.exports[t]={hook:e,refcount:1},this.reverseExports.set(e,t),this.watchExport(t,e),t}}exportPromise(e){if(this.abortReason)throw this.abortReason;let t=this.nextExportId--;return this.exports[t]={hook:e,refcount:1},this.reverseExports.set(e,t),this.ensureResolvingExport(t),t}unexport(e){for(let t of e)this.releaseExport(t,1)}watchExport(e,t){t.onBroken(n=>{queueMicrotask(()=>{if(this.abortReason===void 0&&this.exports[e]?.hook===t)try{this.send([`reject`,e,Zs.devaluate(n,void 0,this,void 0,this.encodingLevel)])}catch(e){this.abort(e)}})})}releaseExport(e,t){let n=this.exports[e];if(!n)throw Error(`no such export ID: ${e}`);if(n.refcount<t)throw Error(`refcount would go negative: ${n.refcount} < ${t}`);n.refcount-=t,n.refcount===0&&(delete this.exports[e],this.reverseExports.delete(n.hook),n.hook.dispose())}onSendError(e){if(this.options.onSendError)return this.options.onSendError(e)}ensureResolvingExport(e){let t=this.exports[e];if(!t)throw Error(`no such export ID: ${e}`);if(!t.pull){let n=async()=>{let e=t.hook;for(;;){let t=await e.pull();if(t.value instanceof Ts){let{hook:n,pathIfPromise:r}=js(t.value);if(r&&r.length==0&&this.getImport(e)===void 0){e=n;continue}}return t}},r=t.autoRelease;++this.pullCount,t.pull=n().then(t=>{let n=Zs.devaluate(t.value,void 0,this,t,this.encodingLevel);this.send([`resolve`,e,n]),r&&this.releaseExport(e,1)},t=>{this.send([`reject`,e,Zs.devaluate(t,void 0,this,void 0,this.encodingLevel)]),r&&this.releaseExport(e,1)}).catch(t=>{try{this.send([`reject`,e,Zs.devaluate(t,void 0,this,void 0,this.encodingLevel)]),r&&this.releaseExport(e,1)}catch(e){this.abort(e)}}).finally(()=>{--this.pullCount===0&&this.onBatchDone&&this.onBatchDone.resolve()})}}getImport(e){if(e instanceof cc&&e.entry&&e.entry.session===this)return e.entry.importId}importStub(e){if(this.abortReason)throw this.abortReason;let t=this.imports[e];return t||(t=new sc(this,e,!1),this.imports[e]=t),new cc(!1,t)}importPromise(e){if(this.abortReason)throw this.abortReason;if(this.imports[e])return new ys(Error(`Bug in RPC system: The peer sent a promise reusing an existing export ID.`));let t=new sc(this,e,!0);return this.imports[e]=t,new cc(!0,t)}getExport(e){return this.exports[e]?.hook}getPipeReadable(e){let t=this.exports[e];if(!t||!t.pipeReadable)throw Error(`Export ${e} is not a pipe or its readable end was already consumed.`);let n=t.pipeReadable;return t.pipeReadable=void 0,n}getLimits(){return this.limits}createPipe(e,t){if(this.abortReason)throw this.abortReason;this.send([`pipe`]);let n=this.imports.length,r=new sc(this,n,!1);this.imports.push(r);let i=new cc(!1,r),a=_s.createWritableStreamFromHook(i);return e.pipeTo(a).catch(()=>{}).finally(()=>t.dispose()),n}send(e){if(this.abortReason!==void 0)return 0;if(this.encodingLevel===`string`){let t;try{t=JSON.stringify(e)}catch(e){try{this.abort(e)}catch{}throw e}try{let e=this.transport.send(t);e!==void 0&&typeof e.catch==`function`&&e.catch(e=>this.abort(e,!1))}catch(e){queueMicrotask(()=>this.abort(e,!1))}return t.length}try{let t=this.transport.send(e);if(typeof t==`number`)return t;let n=t;n&&typeof n.then==`function`&&Promise.resolve(n).catch(e=>this.abort(e,!1));return}catch(e){queueMicrotask(()=>this.abort(e,!1));return}}sendCall(e,t,n){if(this.abortReason)throw n?.dispose(),this.abortReason;let r=[`pipeline`,e,t];if(n){let e;try{e=Zs.devaluate(n.value,void 0,this,n,this.encodingLevel)}catch(e){throw n.dispose(),e}r.push(e[0])}this.send([`push`,r]);let i=new sc(this,this.imports.length,!1);return this.imports.push(i),new cc(!0,i)}sendStream(e,t,n){if(this.abortReason)throw n.dispose(),this.abortReason;let r=[`pipeline`,e,t],i;try{i=Zs.devaluate(n.value,void 0,this,n,this.encodingLevel)}catch(e){throw n.dispose(),e}r.push(i[0]);let a=[`stream`,r],o=this.send(a);o===void 0&&(o=oc(a));let s=this.imports.length,c=new sc(this,s,!0);return c.remoteRefcount=0,c.localRefcount=1,this.imports.push(c),{promise:c.awaitResolution().then(e=>{e.dispose(),delete this.imports[s]},e=>{throw delete this.imports[s],e}),size:o}}sendMap(e,t,n,r){if(this.abortReason){for(let e of n)e.dispose();throw this.abortReason}let i=[`remap`,e,t,n.map(e=>{let t=this.getImport(e);return t===void 0?[`export`,this.exportStub(e)]:[`import`,t]}),r];this.send([`push`,i]);let a=new sc(this,this.imports.length,!1);return this.imports.push(a),new cc(!0,a)}sendPull(e){if(this.abortReason)throw this.abortReason;this.send([`pull`,e])}sendRelease(e,t){this.abortReason||(this.send([`release`,e,t]),delete this.imports[e])}abort(e,t=!0){if(this.abortReason===void 0){if(this.cancelReadLoop?.(e),this.cancelReadLoop=void 0,t)try{let t=[`abort`,Zs.devaluate(e,void 0,this,void 0,this.encodingLevel)];if(this.encodingLevel===`string`){let e=this.transport.send(JSON.stringify(t));e!==void 0&&typeof e.catch==`function`&&e.catch(e=>{})}else{let e=this.transport.send(t);e&&typeof e.then==`function`&&Promise.resolve(e).catch(e=>{})}}catch{}if(e===void 0&&(e=`undefined`),this.abortReason=e,this.onBatchDone&&this.onBatchDone.reject(e),this.transport.abort)try{this.transport.abort(e)}catch(e){Promise.resolve(e)}for(let t of Object.values(this.onBrokenCallbacks))try{t(e)}catch(e){Promise.resolve(e)}for(let t in this.imports)this.imports[t].abort(e);for(let e in this.exports)this.exports[e].hook.dispose()}}async readLoop(){for(;!this.abortReason;){let e=Promise.withResolvers();this.cancelReadLoop=e.reject;let t;try{t=await Promise.race([this.transport.receive(),e.promise])}finally{this.cancelReadLoop===e.reject&&(this.cancelReadLoop=void 0)}if(this.encodingLevel===`string`&&t.length>this.limits.maxMessageSize)throw TypeError(`Incoming message exceeds maximum size of ${this.limits.maxMessageSize} UTF-16 code units.`);if(this.abortReason)break;let n=this.encodingLevel===`string`?JSON.parse(t):t;if(n instanceof Array)switch(n[0]){case`push`:if(n.length>1){let e=new Is(new ec(this,this.encodingLevel).evaluate(n[1]));e.ignoreUnhandledRejections(),this.exports.push({hook:e,refcount:1});continue}break;case`stream`:if(n.length>1){let e=new Is(new ec(this,this.encodingLevel).evaluate(n[1]));e.ignoreUnhandledRejections();let t=this.exports.length;this.exports.push({hook:e,refcount:1,autoRelease:!0}),this.ensureResolvingExport(t);continue}break;case`pipe`:{let{readable:e,writable:t}=new TransformStream,n=_s.createWritableStreamHook(t),r=this.exports.length;this.exports.push({hook:n,refcount:1,pipeReadable:e}),this.watchExport(r,n);continue}case`pull`:{let e=n[1];if(typeof e==`number`){this.ensureResolvingExport(e);continue}break}case`resolve`:case`reject`:{let e=n[1];if(typeof e==`number`&&n.length>2){let t=this.imports[e];if(t){if(n[0]==`resolve`)t.resolve(new Is(new ec(this,this.encodingLevel).evaluate(n[2])));else{let e=new ec(this,this.encodingLevel).evaluate(n[2]);e.dispose(),t.resolve(new ys(e.value))}}else n[0]==`resolve`&&new ec(this,this.encodingLevel).evaluate(n[2]).dispose();continue}break}case`release`:{let e=n[1],t=n[2];if(typeof e==`number`&&typeof t==`number`){this.releaseExport(e,t);continue}break}case`abort`:{let e=new ec(this,this.encodingLevel).evaluate(n[1]);e.dispose(),this.abort(e.value,!1);break}}throw Error(`bad RPC message: ${JSON.stringify(n)}`)}}async drain(){if(this.abortReason)throw this.abortReason;if(this.pullCount>0){let{promise:e,resolve:t,reject:n}=Promise.withResolvers();this.onBatchDone={resolve:t,reject:n},await e}}getStats(){let e={imports:0,exports:0};for(let t in this.imports)++e.imports;for(let t in this.exports)++e.exports;return e}},dc=class{#e;#t;constructor(e,t,n={}){let r;r=t?new Is(Ns.fromAppReturn(t)):new ys(Error(`This connection has no main object.`)),this.#e=new uc(e,r,n),this.#t=new Ts(this.#e.getMainImport())}getRemoteMain(){return this.#t}getStats(){return this.#e.getStats()}drain(){return this.#e.drain()}};function fc(e,t,n){return new dc(new pc(e),t,n).getRemoteMain()}var pc=class{encodingLevel=`structuredClonable`;constructor(e){this.#e=e,e.start(),e.addEventListener(`message`,e=>{this.#i||(e.data===null?this.#a(Error(`Peer closed MessagePort connection.`)):this.#t?(this.#t(e.data),this.#t=void 0,this.#n=void 0):this.#r.push(e.data))}),e.addEventListener(`messageerror`,e=>{this.#a(Error(`MessagePort message error.`))})}#e;#t;#n;#r=[];#i;send(e){if(this.#i)throw this.#i;this.#e.postMessage(e)}async receive(){if(this.#r.length>0)return this.#r.shift();if(this.#i)throw this.#i;return new Promise((e,t)=>{this.#t=e,this.#n=t})}abort(e){try{this.#e.postMessage(null)}catch{}this.#e.close(),this.#i||=e}#a(e){this.#i||(this.#i=e,this.#n&&=(this.#n(e),this.#t=void 0,void 0))}},mc,hc=class{context;captureMap=new Map;instructions=[];constructor(e,t){this.context=mc?{parent:mc,captures:[],subject:mc.capture(e),path:t}:{parent:void 0,captures:[],subject:e,path:t},mc=this}unregister(){mc=this.context.parent}makeInput(){return new _c(this,0)}makeOutput(e){let t;try{t=Zs.devaluate(e.value,void 0,this,e)}finally{e.dispose()}return this.instructions.push(t),this.context.parent?(this.context.parent.instructions.push([`remap`,this.context.subject,this.context.path,this.context.captures.map(e=>[`import`,e]),this.instructions]),new _c(this.context.parent,this.context.parent.instructions.length)):this.context.subject.map(this.context.path,this.context.captures,this.instructions)}pushCall(e,t,n){let r=Zs.devaluate(n.value,void 0,this,n);r=r[0];let i=this.capture(e.dup());return this.instructions.push([`pipeline`,i,t,r]),new _c(this,this.instructions.length)}pushGet(e,t){let n=this.capture(e.dup());return this.instructions.push([`pipeline`,n,t]),new _c(this,this.instructions.length)}capture(e){if(e instanceof _c&&e.mapper===this)return e.idx;let t=this.captureMap.get(e);if(t===void 0){if(this.context.parent){let t=this.context.parent.capture(e);this.context.captures.push(t)}else this.context.captures.push(e);t=-this.context.captures.length,this.captureMap.set(e,t)}return t}exportStub(e){throw Error(`Can't construct an RpcTarget or RPC callback inside a mapper function. Try creating a new RpcStub outside the callback first, then using it inside the callback.`)}exportPromise(e){return this.exportStub(e)}getImport(e){return this.capture(e)}unexport(e){}createPipe(e){throw Error(`Cannot send ReadableStream inside a mapper function.`)}onSendError(e){}};hs.sendMap=(e,t,n)=>{let r=new hc(e,t),i;try{i=Ns.fromAppReturn(Ss(r.pushCall.bind(r),()=>n(new Es(r.makeInput(),[]))))}finally{r.unregister()}if(i instanceof Promise)throw i.catch(e=>{}),Error(`RPC map() callbacks cannot be async.`);return new Es(r.makeOutput(i),[])};function gc(){throw Error(`Attempted to use an abstract placeholder from a mapper function. Please make sure your map function has no side effects.`)}var _c=class extends vs{mapper;idx;constructor(e,t){super(),this.mapper=e,this.idx=t}dup(){return this}dispose(){}get(e){if(e.length==0)return this;if(mc)return mc.pushGet(this,e);gc()}call(e,t){t.dispose(),gc()}map(e,t,n){for(let e of t)e.dispose();gc()}pull(){gc()}ignoreUnhandledRejections(){}onBroken(e){gc()}},vc=class{captures;variables;constructor(e,t){this.captures=e,this.variables=[t]}dispose(){for(let e of this.variables)e.dispose()}apply(e){try{if(e.length<1)throw Error(`Invalid empty mapper function.`);for(let t of e.slice(0,-1)){let e=new ec(this).evaluateCopy(t);if(e.value instanceof Ts){let t=ks(e.value);if(t){this.variables.push(t);continue}}this.variables.push(new Is(e))}return new ec(this).evaluateCopy(e[e.length-1])}finally{for(let e of this.variables)e.dispose()}}importStub(e){throw Error(`A mapper function cannot refer to exports.`)}importPromise(e){return this.importStub(e)}getExport(e){return e<0?this.captures[-e-1]:this.variables[e]}getPipeReadable(e){throw Error(`A mapper function cannot use pipe readables.`)}getLimits(){return Bs}};function yc(e,t,n,r,i){let a=new vc(r,new Is(Ns.deepCopyFrom(e,t,n)));try{return a.apply(i)}finally{a.dispose()}}hs.applyMap=(e,t,n,r,i)=>{try{let a;if(e instanceof Es)throw Error(`applyMap() can't be called on RpcPromise`);if(e instanceof Array){let t=[];try{for(let a of e)t.push(yc(a,e,n,r,i))}catch(e){for(let e of t)e.dispose();throw e}a=Ns.fromArray(t)}else a=e==null?Ns.fromAppReturn(e):yc(e,t,n,r,i);return new Is(a)}finally{for(let e of r)e.dispose()}};var bc=class e extends vs{state;static create(t){let n=t.getWriter();return new e({refcount:1,writer:n,closed:!1})}constructor(e,t){super(),this.state=e,t&&++e.refcount}getState(){if(this.state)return this.state;throw Error(`Attempted to use a WritableStreamStubHook after it was disposed.`)}call(e,t){try{let n=this.getState();if(e.length!==1||typeof e[0]!=`string`)throw Error(`WritableStream stub only supports direct method calls`);let r=e[0];if(r!==`write`&&r!==`close`&&r!==`abort`)throw Error(`Unknown WritableStream method: ${r}`);return(r===`close`||r===`abort`)&&(n.closed=!0),new zs((r===`write`?t.deliverStreamWrite(n.writer):t.deliverCall(n.writer[r],n.writer)).then(e=>new Is(e)))}catch(e){return t.dispose(),new ys(e)}}map(e,t,n){for(let e of t)e.dispose();return new ys(Error(`Cannot use map() on a WritableStream`))}get(e){return new ys(Error(`Cannot access properties on a WritableStream stub`))}dup(){let t=this.getState();return new e(t,this)}pull(){return Promise.reject(Error(`Cannot pull a WritableStream stub`))}ignoreUnhandledRejections(){}dispose(){let e=this.state;this.state=void 0,e&&--e.refcount===0&&(e.closed||e.writer.abort(Error(`WritableStream RPC stub was disposed without calling close()`)).catch(()=>{}),e.writer.releaseLock())}onBroken(e){this.getState().writer.closed.then(void 0,e)}},xc=262144,Sc=1073741824,Cc=65536,wc=2,Tc=1.25,Ec=.9,Dc=3,Oc=class{now;window=xc;bytesInFlight=0;inStartupPhase=!0;delivered=0;deliveredTime=0;firstAckTime=0;firstAckDelivered=0;minRtt=1/0;roundsWithoutIncrease=0;lastRoundWindow=0;roundStartTime=0;constructor(e){this.now=e}onSend(e){this.bytesInFlight+=e;let t={sentTime:this.now(),size:e,deliveredAtSend:this.delivered,deliveredTimeAtSend:this.deliveredTime,windowAtSend:this.window,windowFullAtSend:this.bytesInFlight>=this.window};return{token:t,shouldBlock:t.windowFullAtSend}}onError(e){this.bytesInFlight-=e.size}onAck(e){let t=this.now();this.delivered+=e.size,this.deliveredTime=t,this.bytesInFlight-=e.size;let n=t-e.sentTime;if(this.minRtt=Math.min(this.minRtt,n),this.firstAckTime===0)this.firstAckTime=t,this.firstAckDelivered=this.delivered;else{let n,r;e.deliveredTimeAtSend===0?(n=this.firstAckTime,r=this.firstAckDelivered):(n=e.deliveredTimeAtSend,r=e.deliveredAtSend);let i=t-n,a=(this.delivered-r)/i,o=this.inStartupPhase?wc:Tc,s=a*this.minRtt*o;s=Math.min(s,e.windowAtSend*o),s=e.windowFullAtSend?Math.max(s,e.windowAtSend*Ec):Math.max(s,this.window),this.window=Math.max(Math.min(s,Sc),Cc),this.inStartupPhase&&e.sentTime>=this.roundStartTime&&(this.window>this.lastRoundWindow*Tc?this.roundsWithoutIncrease=0:++this.roundsWithoutIncrease>=Dc&&(this.inStartupPhase=!1),this.roundStartTime=t,this.lastRoundWindow=this.window)}return this.bytesInFlight<this.window}};function kc(e){let t,n=!1,r=new Oc(()=>performance.now()),i,a,o=()=>{n||(n=!0,e.dispose())};return new WritableStream({start(n){e.onBroken(e=>{t===void 0&&(t=e,n.error(e),o()),a&&=(a(e),i=void 0,void 0)})},write(n,s){if(t!==void 0)throw t;let c=Ns.fromAppParams([n]),{promise:l,size:u}=e.stream([`write`],c);if(u===void 0)return l.catch(e=>{throw t===void 0&&(t=e),e});{let{token:e,shouldBlock:n}=r.onSend(u);if(l.then(()=>{r.onAck(e)&&i&&(i(),i=void 0,a=void 0)},n=>{r.onError(e),t===void 0&&(t=n,s.error(n),o()),a&&=(a(n),i=void 0,void 0)}),n)return new Promise((e,t)=>{i=e,a=t})}},async close(){if(t!==void 0)throw o(),t;let{promise:n}=e.stream([`close`],Ns.fromAppParams([]));try{await n}catch(e){throw t??e}finally{o()}},abort(n){if(t!==void 0)return;t=n??Error(`WritableStream was aborted`),a&&=(a(t),i=void 0,void 0);let{promise:r}=e.stream([`abort`],Ns.fromAppParams([n]));r.then(()=>o(),()=>o())}})}var Ac=class e extends vs{state;static create(t){return new e({refcount:1,stream:t,canceled:!1})}constructor(e,t){super(),this.state=e,t&&++e.refcount}call(e,t){return t.dispose(),new ys(Error(`Cannot call methods on a ReadableStream stub`))}map(e,t,n){for(let e of t)e.dispose();return new ys(Error(`Cannot use map() on a ReadableStream`))}get(e){return new ys(Error(`Cannot access properties on a ReadableStream stub`))}dup(){let t=this.state;if(!t)throw Error(`Attempted to dup a ReadableStreamStubHook after it was disposed.`);return new e(t,this)}pull(){return Promise.reject(Error(`Cannot pull a ReadableStream stub`))}ignoreUnhandledRejections(){}dispose(){let e=this.state;this.state=void 0,e&&--e.refcount===0&&(e.canceled||(e.canceled=!0,e.stream.locked||e.stream.cancel(Error(`ReadableStream RPC stub was disposed without being consumed`)).catch(()=>{})))}onBroken(e){}};_s.createWritableStreamHook=bc.create,_s.createWritableStreamFromHook=kc,_s.createReadableStreamHook=Ac.create;var jc=Ts,Mc=us,Nc=fc;function Pc(e){return e<32||e>=127&&e<=159||e===1564||e>=8203&&e<=8207||e===8232||e===8233||e>=8234&&e<=8238||e>=8294&&e<=8297||e===65279}function Fc(e,t){let n=e.find(e=>e.id===t.itemId);if(n===void 0||n.kind===`text`)return!1;if(n.kind===`menu`){let e=n.options.find(e=>e.id===t.optionId);return e!==void 0&&e.disabled!==!0}return t.optionId===void 0?n.kind!==`button`||n.disabled!==!0:!1}Object.freeze({publish:()=>Promise.resolve(),onBack:()=>()=>void 0,onForward:()=>()=>void 0,onActivate:()=>()=>void 0});function Ic(e,t){if(t.kind===`action`){let n=[...e.primary??[],...e.menu??[]].find(e=>e.id===t.actionId);return n!==void 0&&n.disabled!==!0}let n=e.crumbs?.find(e=>e.id===t.crumbId);return n===void 0?!1:t.siblingId===void 0||n.siblings?.some(e=>e.id===t.siblingId)===!0}function Lc(e){let t=e.trim().toLowerCase();if(!t)throw Error(`Invalid keymap token: token cannot be empty`);return t}function Rc(e){let t=e.trim().toLowerCase();if(!t)throw Error(`Invalid key name: key name cannot be empty`);return t}function zc(e){return{name:Rc(e.name),ctrl:e.ctrl??!1,shift:e.shift??!1,meta:e.meta??!1,super:e.super??!1,hyper:e.hyper||void 0}}function Bc(e){return{name:e.name,ctrl:e.ctrl,shift:e.shift,meta:e.meta,super:e.super,hyper:e.hyper||void 0}}function Vc(e,t){let n=Bc(zc(e));return{stroke:n,display:t?.display??Yc(n),match:t?.match??Gc(n),tokenName:t?.tokenName?Lc(t.tokenName):void 0}}function Hc(e){return{stroke:Bc(e.stroke),display:e.display,match:e.match,tokenName:e.tokenName,patternName:e.patternName,payloadKey:e.payloadKey}}function Uc(e){return e.map(e=>Hc(e))}function Wc(e){return`match`in e?e.match:`stroke`in e?Gc(e.stroke):Gc(e)}function Gc(e){return`key:${Xc(zc(e))}`}function Kc(e){let t=e.trim();if(!t)throw Error(`Invalid keymap match id: id cannot be empty`);return`text:${t}`}function qc(e,t){return`stroke`in e?t?.preferDisplay&&e.display?e.display:Yc(e.stroke):Yc(zc(e))}function Jc(e,t){return e.map(e=>qc(e,t)).join(t?.separator??``)}function Yc(e){let t=[];return e.ctrl&&t.push(`ctrl`),e.shift&&t.push(`shift`),e.meta&&t.push(`meta`),e.super&&t.push(`super`),e.hyper&&t.push(`hyper`),t.push(e.name===`return`?`enter`:e.name),t.join(`+`)}function Xc(e){return`${e.name}:${+!!e.ctrl}:${+!!e.shift}:${+!!e.meta}:${+!!e.super}:${+!!e.hyper}`}var Zc=Symbol(`keymap-extension-context`);function Qc(e){return e.isDestroyed?null:e.getFocusedTarget()}function $c(e,t,n){let r=t??e.rootTarget,i=t!==null;for(;r;){if(n(r,i)===!1)return;r=e.getParentTarget(r),i=!1}}function el(e,t){let n=new Set;return $c(e,t,e=>{n.add(e)}),n}function tl(e,t,n){let r=[],i=el(t,n),a=Array.isArray(e)?e:nl(e);for(let e of a)rl(t,e,n,i)&&r.push(e);return r}function nl(e){return[...e].sort((e,t)=>t.priority-e.priority||t.order-e.order)}function rl(e,t,n,r=el(e,n)){let i=t.target;return i?e.isTargetDestroyed(i)?!1:t.targetMode===`focus`?i===n:r.has(i):!0}function il(e){let t=e.binding.sequence[e.index];if(!t?.patternName)return 0;let n=e.patterns?.at(-1);return n?.name===t.patternName?n.values.length:0}function al(e,t,n=!0){let r=e.binding.sequence[e.index];if(!r?.patternName)return!0;let i=t.get(r.patternName);return i?il(e)>=i.min:n}function ol(e,t,n=!0){let r=e.binding.sequence[e.index];if(r?.patternName){let n=t.get(r.patternName);if(n&&il(e)<n.max)return!0}return al(e,t,n)&&e.index+1<e.binding.sequence.length}function sl(e,t){return e.index===e.binding.sequence.length-1&&al(e,t,!1)}function cl(e,t,n,r){return{parent:e,depth:e?e.depth+1:0,stroke:t,match:n,pattern:r,children:new Map,patternChildren:[],bindings:[],reachableBindings:[]}}function ll(e,t){let n=cl(null,null,null);for(let r of e){if(r.event!==`press`)continue;let e=n;for(let n of r.sequence){let i;if(n.patternName){let r=t.get(n.patternName);i=e.patternChildren.find(e=>e.pattern?.name===n.patternName),i||(i=cl(e,n.stroke,n.match,r),e.patternChildren.push(i))}else i=e.children.get(n.match),i||(i=cl(e,n.stroke,n.match),e.children.set(n.match,i));i.reachableBindings.push(r),e=i}e.bindings.push(r)}return n}function ul(e,t){let n=[];for(let r of e){if(!al(r,t))continue;let e=r.index+1,i=r.binding.sequence[e];i&&n.push({part:i,binding:r.binding,index:e,exact:e===r.binding.sequence.length-1,continues:e<r.binding.sequence.length-1})}return n}function dl(e,t,n,r){let i=n.patternName;if(!i)return{...e,index:t};let a=[...e.patterns??[]],o=a.at(-1);return o?.name===i?a[a.length-1]={...o,values:[...o.values,r],parts:[...o.parts,n]}:a.push({name:i,payloadKey:n.payloadKey??i,values:[r],parts:[n]}),{layer:e.layer,binding:e.binding,index:t,parts:[...e.parts,n],patterns:a}}function fl(e,t){let n=e.parts.at(-1);if(!n||n.patternName)return t.length;let r=t.indexOf(n.match);return r===-1?t.length:r}function pl(e,t,n,r,i,a,o,s,c){let l=t.sequence[n];if(l){if(l.patternName){let a=s(l.patternName,o);if(!a)return;let u=c(o,l.patternName,a);return dl({layer:e,binding:t,index:n,parts:r,patterns:i},n,u,a.value??o.name)}if(a.includes(l.match))return{layer:e,binding:t,index:n,parts:[...r,l],patterns:i}}}function ml(e,t,n,r,i,a){let o=e.binding.sequence[e.index];if(o?.patternName){let s=r.get(o.patternName);if(s&&il(e)<s.max){let t=i(s.name,n);if(t){let r=a(n,s.name,t);return dl(e,e.index,r,t.value??n.name)}}return al(e,r,!1)?pl(e.layer,e.binding,e.index+1,e.parts,e.patterns,t,n,i,a):void 0}return pl(e.layer,e.binding,e.index+1,e.parts,e.patterns,t,n,i,a)}function hl(e,t,n,r,i){let a=[],o=1/0;for(let s of e.bindings){if(s.event!==`press`)continue;let c=pl(e,s,0,[],void 0,t,n,r,i);if(!c)continue;let l=fl(c,t);l<o&&(o=l,a.length=0),l===o&&a.push(c)}return a}import.meta.require;function gl(e){let t=Object.create(null),n=(e,n)=>{let r=t[e];if(!r)return;let i=r.filter(e=>e!==n);i.length===0?delete t[e]:i.length!==r.length&&(t[e]=i)};return{hook(e,r){return t[e]=[...t[e]??[],r],()=>n(e,r)},has(e){return(t[e]?.length??0)>0},emit(n,...r){let i=t[n];if(i)for(let t of i)try{r.length===0?t():t(r[0])}catch(t){e(n,t)}}}}function _l(){let e=[];return{get:()=>e,set:t=>{e=t},remove(t){e=e.filter(e=>e!==t)},has:()=>e.length>0,clear:()=>{e=[]}}}function vl(){let e=_l();return{append(t){return e.set([...e.get(),t]),()=>e.remove(t)},prepend(t){return e.set([t,...e.get()]),()=>e.remove(t)},values:e.get,has:e.has,clear:e.clear}}function yl(){let e=_l(),t=0;return{register(n,r){let i={...r,listener:n,order:t++};return e.set([...e.get(),i].sort((e,t)=>t.priority-e.priority||e.order-t.order)),()=>e.remove(i)},entries:e.get,has:e.has,clear:e.clear}}function bl(e){return typeof e==`string`||!!e&&typeof e==`object`&&!Array.isArray(e)}function xl(e){if(!Array.isArray(e))return{ok:!1,reason:`Invalid keymap bindings: expected an array of binding objects`};for(let[t,n]of e.entries()){if(!n||typeof n!=`object`||Array.isArray(n))return{ok:!1,reason:`Invalid keymap binding at index ${t}: expected a binding object`};if(!bl(n.key))return{ok:!1,reason:`Invalid keymap binding at index ${t}: expected "key" to be a string or keystroke object`}}return{ok:!0}}function Sl(e){let t=xl(e);if(!t.ok)throw Error(t.reason);return e.map(e=>({...e,key:typeof e.key==`string`?e.key:{...e.key}}))}function Cl(e){return{...e,sequence:Uc(e.sequence)}}function wl(e,t){let n=vl();return{prependLayerAnalyzer(e){return n.prepend(e)},appendLayerAnalyzer(e){return n.append(e)},clearLayerAnalyzers(){n.clear()},analyzeLayer(r){let i=n.values();if(i.length===0)return;let a=Tl(r.bindings),o={target:r.target,order:r.order,sourceBindings:r.sourceBindings,bindings:a,hasTokenBindings:r.hasTokenBindings,checkCommandResolution(e){return t.getCommandResolutionStatus(e,r.commands)},warn(t,n,r){e.emitWarning(t,n,r)},warnOnce(t,n,r,i){e.warnOnce(t,n,r,i)},error(t,n,r){e.emitError(t,n,r)}};for(let t of i)try{t(o)}catch(t){e.emitError(`layer-analyzer-error`,t,`[Keymap] Error in layer analyzer:`)}}}}function Tl(e){return e.map(t=>({sequence:Uc(t.sequence),command:t.command,attrs:t.attrs,event:t.event,preventDefault:t.preventDefault,fallthrough:t.fallthrough,parsedBinding:Cl(t.parsedBinding),sourceTarget:t.sourceTarget,sourceLayerOrder:t.sourceLayerOrder,bindingIndex:t.bindingIndex,hasCommandAtSequence:e.some(e=>e.event===`press`&&e.command!==void 0&&El(e,t)),hasContinuations:e.some(e=>e.event===`press`&&Dl(t,e))}))}function El(e,t){return e.sequence.length===t.sequence.length&&e.sequence.every((e,n)=>e.match===t.sequence[n]?.match)}function Dl(e,t){return e.sequence.length<t.sequence.length&&e.sequence.every((e,n)=>e.match===t.sequence[n]?.match)}function Ol(){return{version:-1,notifyVersion:-1,focused:void 0,value:[],targets:new WeakMap}}function kl(){return{plain:Ol(),bindings:Ol(),metadata:Ol(),bindingsAndMetadata:Ol()}}function Al(e,t){if(t===void 0)return e.plain;let n=t.includeBindings===!0,r=t.includeMetadata===!0;return n?r?e.bindingsAndMetadata:e.bindings:r?e.metadata:e.plain}function jl(e,t,n){let r=n?e.targets.get(n):e.nullTarget;return r?.version===t?r:void 0}function Ml(e,t,n,r){let i={version:t,value:r};n?e.targets.set(n,i):e.nullTarget=i}function Nl(e,t){if(e===t)return!0;if(!e||!t||e.captures.length!==t.captures.length)return!1;for(let n=0;n<e.captures.length;n+=1){let r=e.captures[n],i=t.captures[n];if(!r||!i||r.layer!==i.layer||r.binding!==i.binding||r.index!==i.index||r.parts.length!==i.parts.length)return!1;for(let e=0;e<r.parts.length;e+=1)if(r.parts[e]?.match!==i.parts[e]?.match)return!1;let a=r.patterns??[],o=i.patterns??[];if(a.length!==o.length)return!1;for(let e=0;e<a.length;e+=1){let t=a[e],n=o[e];if(!t||!n||t.name!==n.name||t.values.length!==n.values.length)return!1;for(let e=0;e<t.values.length;e+=1)if(!Object.is(t.values[e],n.values[e]))return!1}}return!0}function Pl(e){let t=e.parts.at(-1);if(!t||e.parts.length<=1)return;let n=e.index-1,r=e.patterns;if(t.patternName){let i=r?.at(-1);i?.name===t.patternName&&(i.values.length>1?(n=e.index,r=[...(r??[]).slice(0,-1),{...i,values:i.values.slice(0,-1),parts:i.parts.slice(0,-1)}]):r=(r??[]).slice(0,-1))}return{layer:e.layer,binding:e.binding,index:n,parts:e.parts.slice(0,-1),patterns:r}}function Fl(e){let t=e.captures[0];if(!t||t.parts.length===0)return[];let n=[];for(let r=0;r<t.parts.length;r+=1){let i=t.parts[r];if(!i)continue;let a,o,s=!1,c=!1;for(let t of e.captures){let e=t.parts[r];if(e){if(a===void 0){a=e.display,o=e.tokenName;continue}!s&&a!==e.display&&(s=!0),!c&&o!==e.tokenName&&(c=!0)}}(a===void 0||s)&&(a=qc(i.stroke)),c&&(o=void 0),n.push(Vc(i.stroke,{display:a,match:i.match,tokenName:o}))}return n}function Il(e){if(e.isDestroyed)throw Error(`Cannot use a keymap after its host was destroyed`);return e}function Ll(e,t,n,r,i,a,o={}){let s=kl(),c=-1,l=[],u=()=>Il(t).getFocusedTarget(),d=()=>Qc(t),f=t=>{let n=e.pending;Nl(n,t)||(e.pending=t,o.onPendingSequenceChanged?.(n,t),de(),r.queueStateChange())},p=()=>{let t=e.pending;if(!t)return;let n=u(),r=a.getActiveCommandView(n),o=t.captures.filter(t=>e.layers.has(t.layer)&&C(t.layer,n)&&i.matchesConditions(t.layer)&&D(t.binding,n,r)&&ol(t,e.patterns));if(o.length===0){f(null);return}return o.length!==t.captures.length&&f({captures:o}),e.pending??void 0},m=()=>{t.isDestroyed||!e.pending||p()},h=()=>!t.isDestroyed&&e.pending!==null,g=()=>{if(c===e.cacheVersion)return l;let t=p(),n=t?Fl(t):[];return(!t||T())&&(c=e.cacheVersion,l=n),n},_=()=>{let e=p();if(!e)return!1;let t=e.captures[0];if(!t||t.parts.length<=1)return f(null),!0;let n=[];for(let t of e.captures){let e=Pl(t);e&&n.push(e)}return n.length===0?(f(null),!0):(f({captures:n}),!0)},v=t=>{let n=t?.includeBindings===!0,r=t?.includeMetadata===!0,i=Al(s,t);return i.notifyVersion===e.derivedVersion?i.value:y(i,n,r)},y=(n,r,i)=>{t.isDestroyed&&Il(t);let o=u(),s=jl(n,e.cacheVersion,o);if(s)return n.notifyVersion=e.derivedVersion,n.version=e.cacheVersion,n.focused=o,n.value=s.value,s.value;let c=a.getActiveCommandView(o),l=p(),d=l?[]:S(o),f=l?ne(l.captures,r,i,o,c):j(d,r,i,o,c);return(l?T():w(d))&&(n.version=e.cacheVersion,n.notifyVersion=e.derivedVersion,n.focused=o,n.value=f,Ml(n,e.cacheVersion,o,f)),f},b=(e,t)=>{let n=t?.includeBindings===!0,r=t?.includeMetadata===!0,i=u(),o=a.getActiveCommandView(i);return ne(e,n,r,i,o)},x=(e,t)=>{let n=t?.includeBindings===!0,r=t?.includeMetadata===!0,i=e===d()?p():void 0,o=a.getActiveCommandView(e);return i?ne(i.captures,n,r,e,o):j(S(e),n,r,e,o)},S=n=>e.activeLayersCacheVersion===e.cacheVersion&&e.activeLayersCacheFocused===n?e.activeLayersCache:(e.activeLayersCacheVersion=e.cacheVersion,e.activeLayersCacheFocused=n,e.activeLayersCache=tl(e.sortedLayers,t,n),e.activeLayersCache),C=(e,n)=>rl(t,e,n),w=t=>!e.commandResolvers.has()&&e.activeKeyCacheBlockers===0,T=()=>!e.commandResolvers.has()&&e.activeKeyCacheBlockers===0,E=(e,t,n)=>{let r=[];for(let o of e)i.matchesConditions(o)&&a.isBindingVisible(o,t,n)&&r.push(o);return r},D=(e,t,n)=>i.matchesConditions(e)&&a.isBindingVisible(e,t,n),O=(e,t)=>{let n,r,i=!1,a=!1;for(let o of e){let e=o.sequence[t];if(e){if(n===void 0){n=e.display,r=e.tokenName;continue}!i&&n!==e.display&&(i=!0),!a&&r!==e.tokenName&&(a=!0)}}if(n===void 0||i){let r=e[0]?.sequence[t]?.stroke;n=r?qc(r):``}return a&&(r=void 0),{display:n,tokenName:r}},k=(e,t,n)=>({sequence:e.sequence,command:e.command,commandAttrs:a.getBindingCommandAttrs(e,t,n),attrs:e.attrs,event:e.event,preventDefault:e.preventDefault,fallthrough:e.fallthrough}),A=(e,t,n)=>e.map(e=>k(e,t,n)),j=(e,t,n,r,a)=>{let o=new Map,s=new Set;for(let n of e)n.root.children.size===0&&n.root.patternChildren.length===0||!i.matchesConditions(n)||(M(n.root.children.values(),o,s,t,r,a),M(n.root.patternChildren,o,s,t,r,a));return ae(o,t,n,r,a)},M=(e,t,n,r,i,a)=>{for(let o of e){let e=o.match;if(!e||n.has(e)||!o.stroke)continue;let s=ee(o,r,i,a);if(!s)continue;let c=t.get(e);c?N(c,s,r):t.set(e,le(o.stroke,s,r)),s.stop&&n.add(e)}},ee=(e,t,n,r)=>{if(!(e.children.size>0||e.patternChildren.length>0)){let i=ce(te(e)?E(e.bindings,n,r):e.bindings,n,r);if(!i)return;let a=O(i.bindings,e.depth-1);return{display:a.display,tokenName:a.tokenName,continues:!1,firstBinding:i.bindings[0],commandBinding:i.commandBinding,bindings:t?[...i.bindings]:void 0,stop:i.stop}}let i=E(e.reachableBindings,n,r);if(i.length===0)return;let a=ce(e.bindings,n,r),o=O(i,e.depth-1);return{display:o.display,tokenName:o.tokenName,continues:!0,firstBinding:a?.bindings[0],commandBinding:a?.commandBinding,bindings:t&&a?[...a.bindings]:void 0,stop:!0}},te=t=>{if(e.commandResolvers.has())return!0;for(let e of t.bindings)if(e.matchers.length>0)return!0;return!1},ne=(t,n,r,i,a)=>{let o=new Map,s=new Set;return re(ul(t,e.patterns),o,s,n,i,a),ae(o,n,r,i,a)},re=(e,t,n,r,i,a)=>{let o=new Set;for(let s of e)o.has(s.part.match)||(o.add(s.part.match),ie(s,e,t,n,r,i,a))},ie=(e,t,n,r,i,a,o)=>{let s=e.part.match;if(r.has(s))return;let c=oe(e,t,i,a,o);if(!c)return;let l=n.get(s);l?N(l,c,i):n.set(s,le(e.part.stroke,c,i)),c.stop&&r.add(s)},ae=(e,t,n,r,i)=>{let a=[];for(let o of e.values()){let e=ue(o,t,n,r,i);e&&a.push(e)}return a},oe=(e,t,n,r,i)=>{let a=t.filter(t=>t.part.match===e.part.match),o=a.filter(e=>e.exact).map(e=>e.binding),s=ce(o,r,i),c=a.some(e=>e.continues);if(!c&&!s)return;let l=se(a);return{display:l.display,tokenName:l.tokenName,continues:c,firstBinding:s?.bindings[0],commandBinding:s?.commandBinding,bindings:n&&s?[...s.bindings]:void 0,stop:c||s?.stop===!0}},se=e=>{let t,n,r=!1,i=!1;for(let a of e){let e=a.part;if(t===void 0){t=e.display,n=e.tokenName;continue}!r&&t!==e.display&&(r=!0),!i&&n!==e.tokenName&&(i=!0)}let a=e[0]?.part;return(t===void 0||r)&&(t=a?qc(a.stroke):``),i&&(n=void 0),{display:t,tokenName:n}},ce=(e,t,n)=>{let r=[],o;for(let s of e)if(!(!i.matchesConditions(s)||!a.isBindingVisible(s,t,n))&&(r.push(s),s.command!==void 0&&(o??=s,!s.fallthrough)))return{bindings:r,commandBinding:o,stop:!0};if(r.length!==0)return{bindings:r,commandBinding:o,stop:!1}},le=(e,t,n)=>({stroke:e,display:t.display,tokenName:t.tokenName,continues:t.continues,firstBinding:t.firstBinding,commandBinding:t.commandBinding,bindings:n&&t.bindings?[...t.bindings]:void 0}),N=(e,t,n)=>{if(!e.firstBinding&&t.firstBinding&&(e.firstBinding=t.firstBinding),!e.commandBinding&&t.commandBinding&&(e.commandBinding=t.commandBinding),t.continues&&(e.continues=!0),!(!n||!t.bindings||t.bindings.length===0)){if(!e.bindings){e.bindings=[...t.bindings];return}e.bindings.push(...t.bindings)}},ue=(e,t,n,r,i)=>{if(!e.commandBinding&&!e.continues)return;let o={stroke:Bc(e.stroke),display:e.display,continues:e.continues};if(e.tokenName&&(o.tokenName=e.tokenName),e.commandBinding&&(o.command=e.commandBinding.command),t&&e.bindings&&e.bindings.length>0&&(o.bindings=e.bindings.length===1?[k(e.bindings[0],r,i)]:A(e.bindings,r,i)),n){e.firstBinding?.attrs&&(o.bindingAttrs=e.firstBinding.attrs);let t=e.commandBinding?a.getBindingCommandAttrs(e.commandBinding,r,i):void 0;t&&(o.commandAttrs=t)}return o},de=()=>{n.has(`pendingSequence`)&&n.emit(`pendingSequence`,e.pending?Fl(e.pending):[])};return{getFocusedTarget:u,getFocusedTargetIfAvailable:d,setPendingSequence:f,ensureValidPendingSequence:p,revalidatePendingSequenceIfNeeded:m,hasPendingSequenceState:h,getPendingSequence:g,popPendingSequence:_,getActiveKeys:v,getActiveKeysForCaptures:b,getActiveKeysForFocused:x,getActiveLayers:S,isLayerActiveForFocused:C,collectSequencePartsFromPending:Fl,collectMatchingBindings:E,collectActiveBindings:A}}var Rl=new Set([`name`,`run`,`fields`,`attrs`,`rejectedResult`]),zl=new Set([`key`,`cmd`,`event`,`preventDefault`,`fallthrough`]),Bl=new Set([`target`,`targetMode`,`priority`,`bindings`,`commands`]);function Vl(e){if(e===void 0||typeof e==`function`)return e;let t=e.trim();if(!t)throw Error(`Invalid keymap command: command cannot be empty`);return t}function Hl(e){let t=e.trim();if(!t)throw Error(`Invalid keymap command name: name cannot be empty`);if(/\s/.test(t))throw Error(`Invalid keymap command name "${e}": command names cannot contain whitespace`);return t}function Ul(e,t,n){let r=e.get(t);r?r.push(n):e.set(t,[n])}function Wl(e){let t=[],n=new Map;for(let r of e.layers)for(let e of r.commands){let i={layer:r,commandState:e};t.push(i),Ul(n,e.command.name,i)}return{entries:t,chainsByName:n}}function Gl(e,t,n){let r=[],i=[],a=new Map,o=new Map;for(let s of e)if(s.commands.length!==0&&!(n&&!t.matchesConditions(s)))for(let e of s.commands){if(!t.matchesConditions(e))continue;let n={layer:s,commandState:e};r.push(n),Ul(o,e.command.name,n),a.has(e.command.name)||(a.set(e.command.name,n),i.push(n))}return{layers:e,entries:r,reachable:i,reachableByName:a,chainsByName:o}}function Kl(e,t,n,r){return(e.activeLayersCacheVersion!==e.cacheVersion||e.activeLayersCacheFocused!==r)&&(e.activeLayersCacheVersion=e.cacheVersion,e.activeLayersCacheFocused=r,e.activeLayersCache=tl(e.sortedLayers,t,r)),Gl(e.activeLayersCache,n,!0)}function ql(e,t,n,r){if(Object.prototype.hasOwnProperty.call(e,t)&&!Object.is(e[t],n))throw Error(`Conflicting keymap requirement for "${t}" from ${r}`);e[t]=n}function Jl(e,t,n,r){if(Object.prototype.hasOwnProperty.call(e,t)&&!Object.is(e[t],n))throw Error(`Conflicting keymap attribute for "${t}" from ${r}`);e[t]=n}function Yl(e){let t=`field ${e.fieldName}`;return{require(n,r){ql(e.requirements,n,r,t)},attr(n,r){if(!e.attrs)throw Error(`Keymap ${t} cannot publish attrs`);Jl(e.attrs,n,r,t)},activeWhen(n){e.matchers.push(e.conditions.buildRuntimeMatcher(n,t))}}}function Xl(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Zl(e,t){return e instanceof Error&&e.message?e.message:t}function Ql(e){return!e||typeof e!=`object`&&typeof e!=`function`?!1:typeof e.then==`function`}function $l(e,t){let n=t?.deep===!0,r=t?.freeze===!0,i=t?.preserveNonPlainObjects===!0;if(Array.isArray(e)){let i=n?e.map(e=>$l(e,t)):[...e];return r?Object.freeze(i):i}if(e&&typeof e==`object`){if(i&&!Xl(e))return e;let a={};for(let[r,i]of Object.entries(e))a[r]=n?$l(i,t):i;return r?Object.freeze(a):a}return e}var eu=[`name`],tu=Object.freeze({}),nu=new WeakMap;function ru(e,t,n,r,i){let a=-1,o,s=-1,c,l,u=-1,d,f,p=-1,m,h=-1,g=new Map,_=t=>au({commands:t,commandFields:e.commandFields,conditions:r,onError:(e,t,r)=>{n.emitError(e,t,r)}}),v=t=>ae(()=>e.commandResolvers.prepend(t),t),y=t=>ae(()=>e.commandResolvers.append(t),t),b=()=>{e.commandResolvers.has()&&n.runWithStateChangeBatch(()=>{e.commandResolvers.clear(),i.onCommandResolversChanged(),n.queueStateChange()})},x=e=>pe(e).map(e=>iu(e.commandState)),S=e=>{let t=fe(e),n=pe(e,t);if(n.length===0)return[];let r=n.map(e=>({entry:e,command:iu(e.commandState),commandAttrs:e.commandState.attrs,bindings:[]})),i=new Map;for(let[e,t]of r.entries()){let n=i.get(t.command.name);n?n.push(e):i.set(t.command.name,[e])}return i.size>0&&P(r,i,t),r.map(e=>({command:e.command,bindings:e.bindings}))},C=t=>{if(t.visibility===`registered`&&u===e.derivedVersion&&d===t.commands&&f)return f;let n=new Map;for(let e of t.commands)n.has(e)||n.set(e,[]);return n.size===0?n:(me(n,fe(t)),t.visibility===`registered`&&(u=e.derivedVersion,d=t.commands,f=n),n)},w=(e,t,n)=>{let r=M(t);if(n){let i=[],a=r.chainsByName.get(e);if(a)for(let e of a)i.push({target:e.layer.target,command:e.commandState.command,attrs:e.commandState.attrs,payload:n.payload});let o=be(e,t,{mode:`active`,execution:n});return o.resolved&&i.push(o.resolved),{entries:i.length>0?i:void 0,hadError:o.hadError}}let i=[];for(let t of r.chainsByName.get(e)??[])i.push({target:t.layer.target,command:t.commandState.command,attrs:t.commandState.attrs});let a=be(e,t,{mode:`active`});return a.resolved&&i.push(a.resolved),{entries:i.length>0?i:void 0,hadError:a.hadError}},T=t=>{if(h!==e.derivedVersion&&(h=e.derivedVersion,g=new Map),g.has(t))return g.get(t)??void 0;let n=le(ce(t));return g.set(t,n??null),n},E=(e,t)=>le(M(t).chainsByName.get(e)),D=(e,t)=>be(e,null,{mode:`registered`,execution:t}),O=(e,t,n)=>be(e,t,{mode:`active`,execution:n}),k=(e,t)=>oe(e,t)?.command,A=e=>se(e)?.commandState.command,j=(e,n,i)=>{let a=ee().chainsByName.get(e);if(!a||a.length===0)return;let o,s;for(let e of a){if(!rl(t,e.layer,n)){o??=e;continue}(!r.matchesConditions(e.layer)||!r.matchesConditions(e.commandState))&&(s??=e)}let c=s??o;if(c)return{reason:s?`disabled`:`inactive`,command:i?c.commandState.command:void 0}},M=n=>{if(s===e.derivedVersion&&c===n&&l)return l;let i=Kl(e,t,r,n);return te()&&(s=e.derivedVersion,c=n,l=i),i},ee=()=>a===e.derivedVersion&&o?o:(a=e.derivedVersion,o=Wl(e),o),te=()=>e.activeCommandViewCacheBlockers===0,ne=(e,t,n)=>e.command===void 0||e.run?!0:typeof e.command==`string`?n.reachableByName.has(e.command)?!0:N(e.command,t,`active`)!==void 0:!1,re=(e,t,n)=>{if(typeof e.command!=`string`)return;let r=n.reachableByName.get(e.command);return r?r.commandState.attrs:N(e.command,t,`active`)?.attrs},ie=(e,n)=>{if(n?.some(t=>t.command.name===e)||ee().chainsByName.has(e))return`resolved`;let r=be(e,Qc(t));return r.resolved||r.hadError?r.resolved?`resolved`:`error`:`unresolved`},ae=(t,r)=>n.runWithStateChangeBatch(()=>{let a=t();return i.onCommandResolversChanged(),n.queueStateChange(),()=>{n.runWithStateChangeBatch(()=>{a(),!e.commandResolvers.values().includes(r)&&(i.onCommandResolversChanged(),n.queueStateChange())})}}),oe=(e,t)=>{let n=M(t).reachableByName.get(e);return n?{target:n.layer.target,command:n.commandState.command,attrs:n.commandState.attrs}:N(e,t,`active`)},se=e=>ce(e)?.[0],ce=t=>{let n=[];for(let r of e.sortedLayers)for(let e of r.commands)e.command.name===t&&n.push({layer:r,commandState:e});return n.length>0?n:void 0},le=e=>{if(e?.length)return e.map(e=>({target:e.layer.target,command:e.commandState.command,attrs:e.commandState.attrs}))},N=(e,t,n)=>be(e,t,{mode:n}).resolved,ue=()=>ee().entries,de=()=>{if(p===e.derivedVersion&&m)return m;let t=new Map;for(let n of e.layers)for(let e of n.bindings){if(typeof e.command!=`string`)continue;let n=t.get(e.command);n?n.push(e):t.set(e.command,[e])}return p=e.derivedVersion,m=t,t},fe=e=>{let n=e?.visibility??`reachable`,r=e&&Object.prototype.hasOwnProperty.call(e,`focused`)?e.focused??null:Qc(t);return n===`registered`?{visibility:n,focused:r}:{visibility:n,focused:r,activeView:M(r)}},pe=(e,t=fe(e))=>{let r;return r=t.visibility===`registered`?ue():t.visibility===`active`?t.activeView?.entries??[]:t.activeView?.reachable??[],uu({entries:r,query:e,getCommand:e=>iu(e),onFilterError:e=>{n.emitError(`command-query-filter-error`,e,`[Keymap] Error in command query filter:`)}})},P=(e,t,n)=>{he(n,n=>{ge(e,t,n)})},me=(e,t)=>{if(t.visibility===`registered`){let t=de();for(let[n,r]of e){let e=ee().chainsByName.get(n)?.[0]?.commandState.attrs;for(let i of t.get(n)??[])r.push(ve(i,e))}return}he(t,n=>{_e(e,n,t)})},he=(t,n)=>{if(t.visibility===`registered`){for(let t of e.layers)for(let e of t.bindings)n(e);return}let i=t.activeView;if(i){for(let e of i.layers)if(!(e.bindings.length===0||!r.matchesConditions(e)))for(let a of e.bindings)r.matchesConditions(a)&&ne(a,t.focused,i)&&n(a)}},ge=(e,t,n)=>{if(typeof n.command!=`string`)return;let r=t.get(n.command);if(!(!r||r.length===0))for(let t of r){let r=e[t];r&&r.bindings.push(ve(n,r.commandAttrs))}},_e=(e,t,n)=>{if(typeof t.command!=`string`)return;let r=e.get(t.command);r&&r.push(ve(t,ye(t,n)))},ve=(e,t)=>({sequence:e.sequence,command:e.command,commandAttrs:t,attrs:e.attrs,event:e.event,preventDefault:e.preventDefault,fallthrough:e.fallthrough}),ye=(e,t)=>{if(typeof e.command!=`string`)return;if(t.visibility===`registered`)return ee().chainsByName.get(e.command)?.[0]?.commandState.attrs;let n=t.activeView;if(n)return re(e,t.focused,n)},be=(t,r,i)=>{let a=i?.mode??`active`,o=i?.execution??{input:t},s=ou(t,e.commandResolvers.values(),()=>Ce(r,a,o),e=>{n.emitError(`command-resolver-error`,e,`[Keymap] Error in command resolver for "${t}":`)}),c=s.resolved;if(c){let e=Se(c.command.name,r,a);e?.commandState.command===c.command&&c.target===void 0&&(c={...c,target:e.layer.target},s.resolved=c)}if(c&&!c.attrs){let e=xe(c.command.name,r,a)??lu(c.command);e&&(s.resolved={...c,attrs:e})}return s},xe=(e,t,n)=>n===`registered`?se(e)?.commandState.attrs:M(t).reachableByName.get(e)?.commandState.attrs,Se=(e,t,n)=>n===`registered`?se(e):M(t).reachableByName.get(e),Ce=(e,t,n)=>{let r=n.input,i=n.payload;return{context:{get input(){return r},get payload(){return i},setInput(e){r=e},setPayload(e){i=e},getCommand:n=>t===`registered`?A(n):k(n,e)},getExecutionFields(){return{input:r,payload:i}}}};return{normalizeCommands:_,prependCommandResolver:v,appendCommandResolver:y,clearCommandResolvers:b,getCommands:x,getCommandEntries:S,getCommandBindings:C,getResolvedCommandChain:w,getRegisteredResolvedEntries:T,getActiveRegisteredResolvedEntries:E,resolveRegisteredResolverFallback:D,resolveActiveResolverFallback:O,getTopCommand:k,getDispatchUnavailableCommandState:j,getActiveCommandView:M,isBindingVisible:ne,getBindingCommandAttrs:re,getCommandResolutionStatus:ie}}function iu(e){return e.command}function au(e){let t=[],n=new Set;for(let r of e.commands)try{let i={},a=[],o=Hl(r.name),s=su(r),c={};if(n.has(o)){e.onError(`duplicate-command`,{command:o},`Duplicate keymap command "${o}" in the same layer`);continue}r.name=o;for(let[t,n]of Object.entries(s)){if(n===void 0)continue;let r=e.commandFields.get(t);r&&r(n,Yl({fieldName:t,conditions:e.conditions,requirements:i,matchers:a,attrs:c}))}let l={command:r,fields:s,attrs:Object.keys(c).length===0?void 0:c,requires:Object.entries(i),matchers:a};n.add(l.command.name),t.push(l)}catch(t){e.onError(`register-command-failed`,t,Zl(t,`Failed to register keymap command "${String(r.name)}"`));continue}return t}function ou(e,t,n,r){if(t.length===0)return{hadError:!1};let i=!1;for(let a of t){let t,o=n();try{t=a(e,o.context)}catch(e){i=!0,r(e);continue}if(t)return{hadError:i,resolved:cu(t,o.getExecutionFields())}}return{hadError:i}}function su(e){let t={};for(let[n,r]of Object.entries(e))!Rl.has(n)&&r!==void 0&&(t[n]=r);return Object.keys(t).length===0?tu:t}function cu(e,t){return{command:e,input:t.input,payload:t.payload}}function lu(e){let t=su(e);return t===tu?void 0:t}function uu(e){let t=e.query?.namespace,n=du(e.query?.limit);if(n===0)return[];let r=e.query?.search?.trim().toLowerCase()??``,i=eu;e.query?.searchIn&&e.query.searchIn.length>0&&(i=e.query.searchIn);let a=e.query?.filter,o,s,c;if(typeof a==`function`)s=a;else if(a){let e=Object.entries(a),t=[];for(let[n,r]of e){if(n===`name`){if(typeof r==`string`){c=new Set([r]);continue}if(Array.isArray(r)){let e=new Set;for(let t of r)typeof t==`string`&&e.add(t);c=e;continue}}t.push([n,r])}o=t.length>0?t:void 0}let l=[];for(let a of e.entries){let u=a.commandState;if(pu(u,t)&&fu(u,r,i)&&!(c&&!c.has(u.command.name))&&mu(u,o,e)){if(s){let t=!1;try{t=s(e.getCommand(u))}catch(t){e.onFilterError(t);continue}if(!t)continue}if(l.push(a),n!==void 0&&l.length>=n)break}}return l}function du(e){if(e===void 0)return;let t=Math.floor(Number(e));return!Number.isFinite(t)||t<=0?0:t}function fu(e,t,n){if(!t)return!0;for(let r of n)if(hu(e,r,t))return!0;return!1}function pu(e,t){if(t===void 0)return!0;let n=e.fields;return Object.prototype.hasOwnProperty.call(n,`namespace`)?Su(n.namespace,t):!1}function mu(e,t,n){if(!t)return!0;for(let[r,i]of t)if(!yu(e,r,i,n))return!1;return!0}function hu(e,t,n){return gu(e,t)?.includes(n)===!0}function gu(e,t){let n=nu.get(e);if(n||(n=new Map,nu.set(e,n)),n.has(t))return n.get(t);let r=e.fields,i=e.attrs,a;t===`name`?a=e.command.name:Object.prototype.hasOwnProperty.call(r,t)?a=r[t]:i&&Object.prototype.hasOwnProperty.call(i,t)&&(a=i[t]);let o=_u(a);return n.set(t,o),o}function _u(e){if(Array.isArray(e)){let t=[];for(let n of e){let e=_u(n);e!==void 0&&t.push(e)}return t.length>0?t.join(`\0`):void 0}if(typeof e==`string`)return e.toLowerCase();if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e).toLowerCase()}function vu(e,t,n,r){try{return e(t,n)}catch(e){return r(e),!1}}function yu(e,t,n,r){return typeof n==`function`?bu(e,t,n,r):xu(e,t,n)}function bu(e,t,n,r){let i=e.command,a=e.fields,o=e.attrs,s,c=!1,l=()=>s??=r.getCommand(e);return t===`name`&&(c=!0,vu(n,i.name,l(),r.onFilterError))||Object.prototype.hasOwnProperty.call(a,t)&&(c=!0,vu(n,a[t],l(),r.onFilterError))||o&&Object.prototype.hasOwnProperty.call(o,t)&&(c=!0,vu(n,o[t],l(),r.onFilterError))?!0:!c&&vu(n,void 0,l(),r.onFilterError)}function xu(e,t,n){let r=e.command,i=e.fields,a=e.attrs;return t===`name`&&Su(r.name,n)||Object.prototype.hasOwnProperty.call(i,t)&&Su(i[t],n)?!0:!!a&&Object.prototype.hasOwnProperty.call(a,t)&&Su(a[t],n)}function Su(e,t){return Array.isArray(t)?t.some(t=>Cu(e,t)):Cu(e,t)}function Cu(e,t){return Array.isArray(e)?e.some(e=>Cu(e,t)):Object.is(e,t)}function wu(e,t,n,r,i){let a=(e,t,n,r,a,o)=>({keymap:i.keymap,event:e,focused:t,target:n,data:r,input:a,payload:o}),o=(t,n,r,i)=>{let a=typeof n==`function`?void 0:n,o=typeof n==`function`?n:n.run,s=i?a:void 0,c;try{c=o(a?{...r,command:a}:r)}catch(n){return e.emitError(`command-execution-error`,n,`[Keymap] Error running command "${t}":`),{status:`error`,result:s?{ok:!1,reason:`error`,command:s}:{ok:!1,reason:`error`}}}if(Ql(c))return c.catch(n=>{e.emitError(`async-command-error`,n,`[Keymap] Async error in command "${t}":`)}),{status:`handled`,result:s?{ok:!0,command:s}:{ok:!0}};if(Tu(c)){let e=c;return(!c.ok&&c.reason!==`not-found`&&i&&a&&!c.command||c.ok&&i&&a&&!c.command)&&(e={...c,command:a}),{status:c.ok?`handled`:`rejected`,result:e}}return c===!1?{status:`rejected`,result:s?{ok:!1,reason:`rejected`,command:s}:{ok:!1,reason:`rejected`}}:{status:`handled`,result:s?{ok:!0,command:s}:{ok:!0}}},s=(e,t,n,r,i,s,c,l)=>{let u;for(let d of t??[]){let t=o(e,d.command,a(n,r,i??d.target??null,s,e,c),l);if(t.status===`handled`||t.status===`error`)return[t.result,u];u=t.result}return[void 0,u]},c=(e,c,l)=>{let u;try{u=Vl(e)}catch{return{ok:!1,reason:`invalid-args`}}if(typeof u!=`string`)return{ok:!1,reason:`not-found`};let d=c?.includeCommand===!0,f=c?.focused??n.getFocusedTargetIfAvailable(),p=c?.event??i.createCommandEvent(),m=t.getReadonlyData(),h=c?.payload,g=l===`registered`?r.getRegisteredResolvedEntries(u):r.getActiveRegisteredResolvedEntries(u,f),[_,v]=s(u,g,p,f,c?.target,m,h,d);if(_)return _;let y=v,b=l===`registered`?r.resolveRegisteredResolverFallback(u,{input:u,payload:h}):r.resolveActiveResolverFallback(u,f,{input:u,payload:h});if(b.resolved){let e=o(u,b.resolved.command,a(p,f,c?.target??b.resolved.target??null,m,b.resolved.input??u,b.resolved.payload),d);if(e.status===`handled`||e.status===`error`)return e.result;y=e.result}if(b.hadError)return{ok:!1,reason:`error`};if(l===`active`){let e=r.getDispatchUnavailableCommandState(u,f,d);if(e)return e.command?{ok:!1,reason:e.reason,command:e.command}:{ok:!1,reason:e.reason}}return y??{ok:!1,reason:`not-found`}};return{runCommand(e,t){return c(e,t,`registered`)},dispatchCommand(e,t){return c(e,t,`active`)},runBinding(e,n,i,s,c){let l=t.getReadonlyData();if(n.run)return o(typeof n.command==`string`?n.command:`<function>`,n.run,a(i,s,e.target??null,l,typeof n.command==`string`?n.command:`<function>`,c),!1).status!==`rejected`&&(Eu(n,i),!0);if(typeof n.command!=`string`)return!1;let u=r.getResolvedCommandChain(n.command,s,c===void 0?void 0:{input:n.command,payload:c}).entries;for(let t of u??[])if(o(n.command,t.command,a(i,s,t.target??e.target??null,l,t.input??n.command,t.payload),!1).status!==`rejected`)return Eu(n,i),!0;return!1}}}function Tu(e){return typeof e==`object`&&!!e&&`ok`in e}function Eu(e,t){e.preventDefault&&(t.preventDefault(),t.stopPropagation())}var Du=Object.freeze({}),Ou=[],ku=[];function Au(e){if(Object.keys(e).length!==0)return $l(e,{freeze:!0})}function ju(e,t,n,r){let i=t=>Lu(t,e.bindingParsers.values(),{tokens:e.tokens,patterns:e.patterns,layer:Du,parseObjectKey:(e,t)=>c(e,t)}),a=t=>{if(typeof t!=`string`)return[c(t)];let n=Iu(t,e.bindingParsers.values(),{tokens:e.tokens,patterns:e.patterns,layer:Du,parseObjectKey:(e,t)=>c(e,t)});for(let e of n.unknownTokens)r.warnUnknownToken(e,t);return n.unknownTokens.length>0?[]:n.parts},o=(e,t)=>Jc(a(e),t),s=(i,a,o,s,d)=>{let f=[],p=!1,m=e.bindingExpanders.values(),h=e.bindingParsers.values(),g=e.bindingFields,_=e.disambiguationResolvers.has(),v=r.warnUnknownField,y=r.warnUnknownToken;for(let[r,b]of i.entries()){let i;try{i=Pu(b.key,m,{layer:d})}catch(e){t.emitError(`binding-expand-error`,e,Zl(e,`Failed to expand keymap binding`));continue}for(let m of i){let i=m.key,x;try{x=typeof i==`string`?Iu(i,h,{tokens:a,patterns:e.patterns,layer:d,parseObjectKey:(e,t)=>c(e,t)}):{parts:[c(i)],usedTokens:[],unknownTokens:[],hasTokenBindings:!1},x=Fu(x,m)}catch(e){t.emitError(`binding-parse-error`,e,Zl(e,`Failed to parse keymap binding`));continue}let S=x.parts;p||=x.hasTokenBindings;for(let e of x.unknownTokens)y(e,typeof i==`string`?i:String(i.name));if(!(x.unknownTokens.length>0))for(let i of u(b,S,a,h,d))try{let t=l(i.event),a=i.sequence,c={},u={},d=[];for(let e in i){if(e===`sequence`||zl.has(e))continue;let t=i[e];if(t===void 0)continue;let r=g.get(e);if(!r){v(`binding`,e);continue}r(t,Yl({fieldName:e,conditions:n,requirements:c,matchers:d,attrs:u}))}let p=Object.keys(u).length>0?Au(u):void 0,m=Vl(i.cmd),h={binding:b,sequence:a,command:m,event:t,parsedBinding:Cl(i),sourceTarget:o,sourceLayerOrder:s,bindingIndex:r,requires:Object.keys(c).length>0?Object.entries(c):Ou,matchers:d.length>0?d:ku,preventDefault:i.preventDefault!==!1,fallthrough:i.fallthrough??!1};if(p&&(h.attrs=p),typeof m==`function`&&(h.run=m),a.length===0)continue;if(t===`release`&&a.length>1)throw Error(`Keymap release bindings only support a single key stroke`);let y=a.at(-1);if(y?.patternName){let t=e.patterns.get(y.patternName);if(t&&t.max!==t.min)throw Error(`Keymap unbounded sequence patterns must be followed by a concrete continuation`)}t===`press`&&!_&&Nu(f,h),f.push(h)}catch(e){t.emitError(`binding-compile-error`,e,Zl(e,`Failed to compile keymap binding`))}}}return{bindings:f,hasTokenBindings:p}},c=(e,t)=>Vc(e,t),l=e=>{if(e===void 0||e===`press`)return`press`;if(e===`release`)return`release`;throw Error(`Invalid keymap binding event "${String(e)}": expected "press" or "release"`)},u=(n,r,i,a,o)=>{let s=e.bindingTransformers.values();if(s.length===0)return[{...n,sequence:Uc(r)}];let l={...n,sequence:Uc(r)},u=[],d=!0,f=o??Du;for(let n of s)try{n(l,{layer:f,parseKey:t=>Lu(t,a,{tokens:i,patterns:e.patterns,layer:f,parseObjectKey:(e,t)=>c(e,t)}),add:e=>{u.push(Cl(e))},skipOriginal:()=>{d=!1}})}catch(e){t.emitError(`binding-transformer-error`,e,`[Keymap] Error in binding transformer:`)}return d?u.length===0?[l]:[l,...u]:u};return{parseTokenKey:i,parseKeySequence:a,formatKey:o,compileBindings:s}}function Mu(e,t){if(e.length>=t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]?.match!==t[n]?.match)return!1;return!0}function Nu(e,t){for(let n of e)if(n.event===`press`&&(n.command!==void 0&&Mu(n.sequence,t.sequence)||t.command!==void 0&&Mu(t.sequence,n.sequence)))throw Error(`Keymap bindings cannot use the same sequence as both an exact match and a prefix in the same layer`)}function Pu(e,t,n){if(typeof e!=`string`||t.length===0)return[{key:e}];let r=n?.layer??Du,i=[{key:e}];for(let e of t){let t=[];for(let n of i){let i=e({input:n.key,displays:n.displays,layer:r});if(!i){t.push(n);continue}if(i.length===0)throw Error(`Keymap binding expander must return at least one key sequence for "${n.key}"`);for(let e of i){if(!e||typeof e!=`object`||Array.isArray(e)||typeof e.key!=`string`)throw Error(`Keymap binding expander must return expansion objects with string keys for "${n.key}"`);if(e.displays!==void 0){if(!Array.isArray(e.displays))throw Error(`Keymap binding expander displays must be an array of strings for "${n.key}"`);for(let t of e.displays)if(typeof t!=`string`)throw Error(`Keymap binding expander displays must be an array of strings for "${n.key}"`)}t.push(e)}}i=t}return i}function Fu(e,t){if(!t.displays)return e;if(t.displays.length!==e.parts.length)throw Error(`Keymap binding expansion displays length must match parsed sequence length for "${String(t.key)}"`);return{...e,parts:e.parts.map((e,n)=>({...e,display:t.displays[n]}))}}function Iu(e,t,n){if(e.length===0)throw Error(`Invalid key sequence: sequence cannot be empty`);if(t.length===0)throw Error(`No keymap binding parsers are registered`);let r=n.tokens??new Map,i=n.patterns??new Map,a=n.layer??Du,o=n.parseObjectKey,s=[],c=new Set,l=new Set,u=0;for(;u<e.length;){let n=!1;for(let d of t){let t=d({input:e,index:u,layer:a,tokens:r,patterns:i,normalizeTokenName:Lc,createMatch:Kc,parseObjectKey:o});if(t){if(t.nextIndex<=u||t.nextIndex>e.length)throw Error(`Keymap binding parser must advance the input for "${e}" at index ${u}`);s.push(...t.parts);for(let e of t.usedTokens??[])c.add(e);for(let e of t.unknownTokens??[])l.add(e);u=t.nextIndex,n=!0;break}}if(!n)throw Error(`No keymap binding parser handled input at index ${u} in "${e}"`)}return{parts:s,usedTokens:[...c],unknownTokens:[...l],hasTokenBindings:c.size>0||l.size>0}}function Lu(e,t,n){if(typeof e!=`string`)return n.parseObjectKey(e);let{parts:r}=Iu(e,t,n),[i]=r;if(!i||r.length!==1)throw Error(`Invalid key "${String(e)}": expected a single key stroke`);return i}function Ru(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.get==`function`&&typeof t.subscribe==`function`}function zu(e,t){let n=e=>e.requires.length===0&&e.matchers.length===0,r=e=>{try{return e.match()}catch(n){return t.emitError(`runtime-matcher-error`,n,`[Keymap] Error evaluating runtime matcher from ${e.source}:`),!1}},i=e=>{if(e.matchers.length===0)return!0;if(e.matchers.length===1){let[t]=e.matchers;return!t||r(t)}for(let t of e.matchers)if(!r(t))return!1;return!0},a=t=>{if(t.length===0)return!0;for(let[n,r]of t)if(!Object.is(e.data[n],r))return!1;return!0};return{buildRuntimeMatcher(e,t){if(typeof e==`function`)return{source:t,match:e};if(Ru(e))return{source:t,match:()=>e.get(),subscribe:t=>e.subscribe(t)};throw Error(`Keymap ${t} expected a function or a reactive matcher`)},matchesConditions:e=>n(e)||a(e.requires)&&i(e)}}var Bu=Symbol(`keymap-disambiguation-decision`),Vu=Symbol(`keymap-deferred-disambiguation-decision`);function Hu(e,t){return{[Bu]:!0,action:e,handler:t}}function Uu(e){return{[Vu]:!0,action:e}}function Wu(e){return!!e&&typeof e==`object`&&e[Bu]===!0}function Gu(e){return!!e&&typeof e==`object`&&e[Vu]===!0}function Ku(e,t){return t.aborted?Promise.resolve(!1):new Promise(n=>{let r=setTimeout(()=>{t.removeEventListener(`abort`,i),n(!0)},Math.max(0,e)),i=()=>{clearTimeout(r),t.removeEventListener(`abort`,i),n(!1)};t.addEventListener(`abort`,i,{once:!0})})}function qu(e,t,n,r){let i=e.get(n);if(i)try{return i.matcher(r)}catch(e){t.emitError(`sequence-pattern-match-error`,e,`[Keymap] Error matching sequence pattern "${i.name}":`);return}}function Ju(e,t,n,r){let i=e.get(n)?.payloadKey??n;return{...Vc({name:t.name,ctrl:t.ctrl,shift:t.shift,meta:t.meta,super:t.super??!1,hyper:t.hyper||void 0},{display:r.display??String(r.value??t.name)}),patternName:n,payloadKey:i}}function Yu(e,t,n){if(!n?.patterns||n.patterns.length===0)return;let r={},i=!1;for(let a of n.patterns){let n=e.get(a.name),o;try{o=n?.finalize?n.finalize(a.values):a.values.length===1?a.values[0]:[...a.values]}catch(e){t.emitError(`sequence-pattern-finalize-error`,e,`[Keymap] Error finalizing sequence pattern "${a.name}":`);continue}let s=r[a.payloadKey];s===void 0?(r[a.payloadKey]=o,i=!0):Array.isArray(s)?s.push(o):r[a.payloadKey]=[s,o]}return i?r:void 0}function Xu(e,t,n,r,i,a,o,s,c,l){let u={resolveKey:e=>o.parseTokenKey(e).match},d=null,f=0;function p(t,n,r){if(t===`key`){let t=r;return e.keyHooks.register(n,{priority:t?.priority??0,release:t?.release??!1})}if(t===`key:after`){let t=r;return e.keyAfterHooks.register(n,{priority:t?.priority??0,release:t?.release??!1})}let i=r;return e.rawHooks.register(n,{priority:i?.priority??0})}function m(t){return e.eventMatchResolvers.prepend(t)}function h(t){return e.eventMatchResolvers.append(t)}function g(){e.eventMatchResolvers.clear()}function _(t){return ie(()=>e.disambiguationResolvers.prepend(t),t)}function v(t){return ie(()=>e.disambiguationResolvers.append(t),t)}function y(){e.disambiguationResolvers.has()&&t.runWithStateChangeBatch(()=>{e.disambiguationResolvers.clear(),c.recompileBindings()})}function b(e,t){d&&ve()}function x(n){let r=e.rawHooks.entries();if(r.length===0)return!1;let i=!1,a={sequence:n,stop(){i=!0}};for(let e of r){try{e.listener(a)}catch(e){t.emitError(`raw-intercept-error`,e,`[Keymap] Error in raw intercept listener:`)}if(i)return!0}return!1}function S(e,t){return{sequence:Uc(e.sequence),command:e.command,commandAttrs:s.getBindingCommandAttrs(e,t,s.getActiveCommandView(t)),attrs:e.attrs,event:e.event,preventDefault:e.preventDefault,fallthrough:e.fallthrough,sourceLayerOrder:e.sourceLayerOrder,bindingIndex:e.bindingIndex}}function C(e){l.has(`dispatch`)&&l.emit(`dispatch`,e)}function w(e,t,n,r){l.has(`dispatch`)&&C({phase:e,event:n.event,focused:r,layer:{order:t.order,priority:t.priority,target:t.target,targetMode:t.targetMode},binding:S(n,r),sequence:Uc(n.sequence),command:n.command})}function T(e,t,n){if(!l.has(`dispatch`))return;let i=t[0],a=t.length>0?r.collectSequencePartsFromPending({captures:t}):[];C({phase:e,event:`press`,focused:n,layer:i?{order:i.layer.order,priority:i.layer.priority,target:i.layer.target,targetMode:i.layer.targetMode}:void 0,sequence:a})}function E(t){let n=e.keyAfterHooks.entries();for(let e of n)if(e.release===t)return n}function D(e){return e.sequence?Uc(e.sequence):e.captures?r.collectSequencePartsFromPending({captures:e.captures}):[]}function O(e,t){return{handled:e!==`sequence-miss`,reason:e,captures:t}}function k(e,t){return{handled:t,reason:t?`binding-handled`:`binding-rejected`,sequence:e.sequence}}function A(e,t){return t.handled||e.reason===`no-match`?t:e}function j(e,i,a,o,s){let c={event:i,eventType:a?`release`:`press`,focused:o,handled:s.handled,reason:s.reason,sequence:D(s),pendingSequence:r.getPendingSequence(),setData:(e,t)=>{n.setData(e,t)},getData:e=>n.getData(e),consume:e=>{let t=e?.preventDefault??!0,n=e?.stopPropagation??!0;t&&i.preventDefault(),n&&i.stopPropagation()}};for(let n of e)if(n.release===a)try{n.listener(c)}catch(e){t.emitError(`key-after-intercept-error`,e,`[Keymap] Error in key:after intercept listener:`)}}function M(){return{handled:!1,reason:`no-match`}}function ee(e){e.preventDefault(),e.stopPropagation()}function te(e,t,n,i){r.setPendingSequence({captures:t});let a=O(`sequence-pending`,t);return T(e,t,n),ee(i),a}function ne(e,t,n,i){let a=O(e,t);return T(`sequence-clear`,t,n),r.setPendingSequence(null),ee(i),a}function re(i,a){a||ve();let o=E(a),s=o?r.getFocusedTarget():null,c=e.keyHooks.entries(),l={event:i,setData:(e,t)=>{n.setData(e,t)},getData:e=>n.getData(e),consume:e=>{let t=e?.preventDefault??!0,n=e?.stopPropagation??!0;t&&i.preventDefault(),n&&i.stopPropagation()}};for(let e of c)if(e.release===a){try{e.listener(l)}catch(e){t.emitError(`key-intercept-error`,e,`[Keymap] Error in key intercept listener:`)}if(i.propagationStopped){o&&j(o,i,a,s,{handled:!0,reason:`intercept-consumed`,sequence:[]});return}}if(a){let e=ae(i);o&&j(o,i,a,s,e);return}let u=oe(i);o&&j(o,i,a,s,u)}function ie(n,r){return t.runWithStateChangeBatch(()=>{let i=e.disambiguationResolvers.has(),a=n();return!i&&e.disambiguationResolvers.has()&&c.recompileBindings(),()=>{t.runWithStateChangeBatch(()=>{let t=e.disambiguationResolvers.has();a(),!e.disambiguationResolvers.values().includes(r)&&t&&!e.disambiguationResolvers.has()&&c.recompileBindings()})}})}function ae(e){let t=r.getFocusedTarget(),n=r.getActiveLayers(t),a=we(e),o=M();for(let r of a)layerLoop:for(let a of n){if(a.bindings.length===0||!i.matchesConditions(a))continue;let n=Te(a,r,e,t);if(o=A(o,n.outcome),n.handled){if(n.stop)return o;continue layerLoop}}return o}function oe(e){let t=r.getFocusedTarget(),n=r.ensureValidPendingSequence(),i=we(e);if(n)return se(n,i,e,t);let a=r.getActiveLayers(t),o=M();for(let n of i){let r=le(a,[n],e,t);if(o=A(o,r),r.handled)return o}return o}function se(t,n,i,a){let o=s.getActiveCommandView(a),c=[];for(let r of t.captures){let t=ml(r,n,i,e.patterns,Ee,De);t&&c.push(t)}let l=c.reduce((e,t)=>Math.min(e,fl(t,n)),1/0),u=c.filter(e=>fl(e,n)===l);if(u.length===0||!u.some(e=>je(e,a,o))){let e=O(`sequence-miss`,t.captures);return T(`sequence-clear`,t.captures,a),r.setPendingSequence(null),e}return ce(u,0,!1,i,a)}function ce(t,n,i,a,o){let s=i,c=M(),l=new Set;for(let i=n;i<t.length;i+=1){let n=t[i];if(!n||l.has(n))continue;let u=Se(t,i,n);if(u.length>0){if(s)continue;let e=Ce(t,n);return de(t,i,u,e,a,o,s)||te(`sequence-advance`,u,o,a)}if(!sl(n,e.patterns))continue;let d=Ce(t,n);for(let e of d)l.add(e);let f=Me(n.layer,d,a,o);if(c=A(c,f.outcome),f.handled&&(s=!0,f.stop))return T(`sequence-clear`,t,o),r.setPendingSequence(null),c}return T(`sequence-clear`,t,o),r.setPendingSequence(null),c}function le(e,t,n,r){return N(e,0,t,n,r)}function N(t,n,r,a,o){let c=s.getActiveCommandView(o),l=M();for(let s=n;s<t.length;s+=1){let n=t[s];if(!n||!i.matchesConditions(n))continue;let u=Oe(n,r,a,o,c);if(u.length===0)continue;if(u.filter(t=>ol(t,e.patterns,!1)).length>0){let n=u.filter(t=>sl(t,e.patterns)),i=xe(t,s,r,a,o);return ue(t,s,r,i,n,a,o)||te(`sequence-start`,i,o,a)}let d=Me(n,u.filter(t=>sl(t,e.patterns)),a,o);if(l=A(l,d.outcome),d.handled&&d.stop)return l}return l}function ue(e,t,n,i,a,o,s){return fe({event:o,focused:s,continuationCaptures:i,exactBindingsSource:a.map(e=>e.binding),sequencePhase:`sequence-start`,runExact:()=>{r.setPendingSequence(null);let i=a[0]?.layer;if(!i)return M();let c=Me(i,a,o,s);return c.stop?c.outcome:A(c.outcome,N(e,t+1,n,o,s))}})}function de(e,t,n,i,a,o,s){return fe({event:a,focused:o,continuationCaptures:n,exactBindingsSource:i.map(e=>e.binding),sequencePhase:`sequence-advance`,runExact:()=>{r.setPendingSequence(null);let n=i[0]?.layer;if(!n)return M();let c=Me(n,i,a,o);return c.stop?c.outcome:A(c.outcome,ce(e,t+1,s||c.handled,a,o))}})}function fe(t){let{event:n,focused:i,continuationCaptures:a,exactBindingsSource:o,sequencePhase:c,runExact:l}=t;if(!e.disambiguationResolvers.has()||a.length===0)return;let u=s.getActiveCommandView(i),d=r.collectMatchingBindings(o,i,u);if(!d.some(e=>e.command!==void 0))return;let f=()=>te(c,a,i,n),p=()=>ne(`sequence-cleared`,a,i,n),m,h=()=>(m??=r.collectSequencePartsFromPending({captures:a}),m),g=P({event:n,focused:i,getSequence:h,exactBindings:d,continuationCaptures:a,activeView:u});return g?pe(g,a,l,f,p,i,h):(be(h()),f())}function pe(e,t,n,r,i,a,o){if(e.action===`run-exact`)return n();if(e.action===`continue-sequence`)return r();if(e.action===`clear`)return i();let s=r();return me(t,e.handler,a,o(),e=>{if(e){if(e.action===`run-exact`){n();return}if(e.action===`continue-sequence`){r();return}i()}}),s}function P(i){let a,o,s,c,l={event:i.event,focused:i.focused,get sequence(){return a??=Uc(i.getSequence()),a},get stroke(){let e=i.getSequence().at(-1);if(!e)throw Error(`Disambiguation context expected a non-empty sequence`);return c??={...e,stroke:Bc(e.stroke)},c},get exact(){return o??=r.collectActiveBindings(i.exactBindings,i.focused,i.activeView).map(e=>({...e,sequence:Uc(e.sequence)})),o},get continuations(){return s??=r.getActiveKeysForCaptures(i.continuationCaptures,{includeBindings:!0,includeMetadata:!0}),s},getData:e=>n.getData(e),setData:(e,t)=>{n.setData(e,t)},runExact:()=>Hu(`run-exact`),continueSequence:()=>Hu(`continue-sequence`),clear:()=>Hu(`clear`),defer:e=>Hu(`defer`,e)};for(let n of e.disambiguationResolvers.values()){let e;try{e=n(l)}catch(e){t.emitError(`disambiguation-resolver-error`,e,`[Keymap] Error in disambiguation resolver:`);continue}if(e!==void 0){if(Ql(e)){t.emitError(`invalid-disambiguation-resolver-return`,e,`[Keymap] Disambiguation resolvers must return synchronously; use ctx.defer(...) for async handling`);continue}if(!Wu(e)){t.emitError(`invalid-disambiguation-decision`,e,`[Keymap] Invalid disambiguation decision returned by resolver:`);continue}return e}}}function me(e,t,n,r,i){ve();let a=new AbortController,o={id:f++,controller:a,captures:e,apply:i};d=o,queueMicrotask(()=>{he(o,t,n,r)})}function he(e,n,r,i){if(!ye(e))return;let a={signal:e.controller.signal,sequence:Uc(i),focused:r,sleep:t=>Ku(t,e.controller.signal),runExact:()=>Uu(`run-exact`),continueSequence:()=>Uu(`continue-sequence`),clear:()=>Uu(`clear`)},o;try{o=n(a)}catch(n){ye(e)&&(t.emitError(`deferred-disambiguation-error`,n,`[Keymap] Error in deferred disambiguation handler:`),_e(e));return}if(Ql(o)){o.then(t=>{ge(e,t)}).catch(n=>{ye(e)&&(t.emitError(`deferred-disambiguation-error`,n,`[Keymap] Error in deferred disambiguation handler:`),_e(e))});return}ge(e,o)}function ge(e,n){if(ye(e)){if(n!==void 0&&!Gu(n)){t.emitError(`invalid-deferred-disambiguation-decision`,n,`[Keymap] Invalid deferred disambiguation decision returned by handler:`),_e(e);return}_e(e),e.apply(n)}}function _e(e){ye(e)&&(d=null)}function ve(){let e=d;e&&(d=null,e.controller.abort())}function ye(e){return d===e}function be(e){let n=Jc(e,{preferDisplay:!0});t.warnOnce(`unresolved-disambiguation:${n}`,`unresolved-disambiguation`,{sequence:n},`[Keymap] Ambiguous exact/prefix sequence "${n}" fell back to prefix handling because no disambiguation resolver resolved it`)}function xe(t,n,r,a,o){let c=[],l=s.getActiveCommandView(o);for(let s=n;s<t.length;s+=1){let n=t[s];if(n&&i.matchesConditions(n))for(let t of Oe(n,r,a,o,l))ol(t,e.patterns,!1)&&c.push(t)}return c}function Se(t,n,r){return t.filter((t,i)=>i>=n&&ol(t,e.patterns,!1)&&Qu(t.parts,r.parts))}function Ce(t,n){return t.filter(t=>t.layer===n.layer&&sl(t,e.patterns)&&Qu(t.parts,n.parts))}function we(n){let r=e.eventMatchResolvers.values();if(r.length===0)return[];if(r.length===1)return Zu(r[0],n,u,t);let i=[],a=new Set;for(let e of r){let r;try{r=e(n,u)}catch(e){t.emitError(`event-match-resolver-error`,e,`[Keymap] Error in event match resolver:`);continue}if(!(!r||r.length===0))for(let e of r){if(typeof e!=`string`){t.emitError(`invalid-event-match-resolver-candidate`,e,`[Keymap] Invalid event match resolver candidate:`);continue}a.has(e)||(a.add(e),i.push(e))}}return i}function Te(e,t,n,r){let o=!1,s=M();for(let c of e.bindings){if(c.event!==`release`)continue;let l=c.sequence[0];if(!l||l.match!==t||!i.matchesConditions(c))continue;let u=a.runBinding(e,c,n,r);if(s=A(s,k(c,u)),!u){w(`binding-reject`,e,c,r);continue}if(w(`binding-execute`,e,c,r),o=!0,!c.fallthrough)return{handled:!0,stop:!0,outcome:s}}return{handled:o,stop:!1,outcome:s}}function Ee(n,r){return qu(e.patterns,t,n,r)}function De(t,n,r){return Ju(e.patterns,t,n,r)}function Oe(e,t,n,r,i){let a=hl(e,t,n,Ee,De);return a.some(e=>je(e,r,i))?a:[]}function ke(n){return Yu(e.patterns,t,n)}function Ae(e,t,n){return i.matchesConditions(e)&&s.isBindingVisible(e,t,n)}function je(e,t,n){return Ae(e.binding,t,n)}function Me(e,t,n,r){let o=!1,s=M();for(let c of t){let t=c.binding;if(!i.matchesConditions(t))continue;let l=a.runBinding(e,t,n,r,ke(c));if(s=A(s,k(t,l)),!l){w(`binding-reject`,e,t,r);continue}if(w(`binding-execute`,e,t,r),o=!0,!t.fallthrough)return{handled:!0,stop:!0,outcome:s}}return{handled:o,stop:!1,outcome:s}}return{intercept:p,prependEventMatchResolver:m,appendEventMatchResolver:h,clearEventMatchResolvers:g,prependDisambiguationResolver:_,appendDisambiguationResolver:v,clearDisambiguationResolvers:y,handlePendingSequenceChange:b,handleRawSequence:x,handleKeyEvent:re}}function Zu(e,t,n,r){let i;try{i=e(t,n)}catch(e){return r.emitError(`event-match-resolver-error`,e,`[Keymap] Error in event match resolver:`),[]}if(!i||i.length===0)return[];if(i.length===1){let[e]=i;return typeof e==`string`?[e]:(r.emitError(`invalid-event-match-resolver-candidate`,e,`[Keymap] Invalid event match resolver candidate:`),[])}let a=[],o=new Set;for(let e of i){if(typeof e!=`string`){r.emitError(`invalid-event-match-resolver-candidate`,e,`[Keymap] Invalid event match resolver candidate:`);continue}o.has(e)||(o.add(e),a.push(e))}return a}function Qu(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]?.match!==t[n]?.match)return!1;return!0}var $u=()=>{};function ed(e,t,n,r){if(n===void 0)return r;if(typeof n!=`number`||!Number.isInteger(n)||n<0)throw Error(`Keymap sequence pattern "${e}" ${t} must be a non-negative integer`);return n}function td(e,t){let{kind:n,reservedFields:r,registeredFields:i,emitError:a}=t,o=Object.entries(e),s=[];for(let[e,t]of o){if(r.has(e)){a(`reserved-${n}-field`,{field:e,kind:n},`Keymap ${n} field "${e}" is reserved`);continue}if(i.has(e)){a(`duplicate-${n}-field`,{field:e,kind:n},`Keymap ${n} field "${e}" is already registered`);continue}i.set(e,t),s.push([e,t])}return()=>{for(let[e,t]of s)i.get(e)===t&&i.delete(e)}}function nd(e,t,n,r,i){let a;try{a=Lc(i.name)}catch(e){return t.emitError(`token-name-normalize-error`,e,Zl(e,`Failed to register keymap token`)),$u}if(e.tokens.has(a)||e.patterns.has(a))return t.emitError(`duplicate-token`,{token:a},`Keymap token "${a}" is already registered`),$u;let o;try{if(o=n.parseTokenKey(i.key),o.patternName)throw Error(`Invalid key "${String(i.key)}": expected a concrete key stroke`)}catch(e){return t.emitError(`token-parse-error`,e,Zl(e,`Failed to register keymap token "${a}"`)),$u}let s={stroke:o.stroke,match:o.match},c=new Map(e.tokens);c.set(a,s);try{r.applyTokenState(c)}catch(e){return t.emitError(`token-register-error`,e,Zl(e,`Failed to register keymap token "${a}"`)),$u}return()=>{if(e.tokens.get(a)!==s)return;let n=new Map(e.tokens);n.delete(a);try{r.applyTokenState(n)}catch(e){t.emitError(`token-unregister-error`,e,Zl(e,`Failed to unregister keymap token "${a}"`))}}}function rd(e,t,n,r){let i,a;try{i=Lc(r.name);let e=ed(i,`min`,r.min,1),t=ed(i,`max`,r.max,2**53-1);if(t<e)throw Error(`Keymap sequence pattern "${i}" max must be greater than or equal to min`);a={name:i,display:r.display,payloadKey:r.payloadKey??i,match:Kc(`pattern:${i}`),min:e,max:t,matcher:e=>r.match(e),finalize:r.finalize}}catch(e){return t.emitError(`sequence-pattern-register-error`,e,Zl(e,`Failed to register keymap sequence pattern`)),$u}return e.tokens.has(i)||e.patterns.has(i)?(t.emitError(`duplicate-sequence-pattern`,{pattern:i},`Keymap sequence pattern "${i}" is already registered`),$u):(e.patterns.set(i,a),n.recompileBindings(),()=>{e.patterns.get(i)===a&&(e.patterns.delete(i),n.recompileBindings())})}function id(e,t,n,r){return td(r,{kind:n,reservedFields:n===`layer`?Bl:n===`binding`?zl:Rl,registeredFields:n===`layer`?e.layerFields:n===`binding`?e.bindingFields:e.commandFields,emitError:(e,n,r)=>t.emitError(e,n,r)})}var ad=()=>{};function od(e,t){return t.priority-e.priority||t.order-e.order}function sd(e){if(e.matchers.length>0)return!0;for(let t of e.commands)if(t.matchers.length>0)return!0;for(let t of e.bindings)if(t.matchers.length>0)return!0;return!1}function cd(e){if(e.commands.length===0)return!1;if(e.matchers.length>0)return!0;for(let t of e.commands)if(t.matchers.length>0)return!0;return!1}function ld(e,t,n,r,i){let a=n=>t.runWithStateChangeBatch(()=>{let a=n.target;if(a&&i.host.isTargetDestroyed(a))return t.emitError(`destroyed-layer-target`,{target:a},`Cannot register a keymap layer for a destroyed keymap target`),ad;let o,s,c,p,m,v,y;try{y=l(n),o=u(Sl(n.bindings??[]),n);let e=d(n.commands??[],n);v=e.length===0?[]:i.commands.normalizeCommands(e),{requires:s,matchers:c,fields:p,attrs:m}=f(n)}catch(e){return t.emitError(`register-layer-failed`,e,Zl(e,`Failed to register keymap layer`)),ad}let b=e.order++,x=i.compiler.compileBindings(o,e.tokens,a,b,p);if(x.bindings.length===0&&!x.hasTokenBindings&&v.length===0)return ad;i.diagnostics?.analyzeLayer({target:a,order:b,commands:v,sourceBindings:o,bindings:x.bindings,hasTokenBindings:x.hasTokenBindings});let S={order:b,target:a,targetMode:y,priority:n.priority??0,requires:s,matchers:c,fields:p,attrs:m,commands:v,sourceBindings:o,bindings:x.bindings,root:ll(x.bindings,e.patterns),hasTokenBindings:x.hasTokenBindings,activeKeyCacheBlocked:!1,activeCommandViewCacheBlocked:!1};_(S),e.layers.add(S),e.sortedLayers=[...e.sortedLayers,S].sort(od),g(S);for(let e of S.commands)g(e);for(let e of S.bindings)g(e);return a&&(S.offTargetDestroy=i.host.onTargetDestroy(a,()=>{h(S)})),S.commands.length>0&&r.ensureValidPendingSequence(),t.queueStateChange(),()=>{h(S)}}),o=n=>{t.runWithStateChangeBatch(()=>{let i=new Map;for(let t of e.layers)t.hasTokenBindings&&i.set(t,p(t,n));e.tokens=n;let a=!1;for(let[e,t]of i)m(e,t)&&(a=!0);a&&r.setPendingSequence(null),i.size>0&&t.queueStateChange()})},s=()=>{t.runWithStateChangeBatch(()=>{let n=0,i=!1;for(let t of e.layers){if(t.sourceBindings.length===0)continue;let r=p(t,e.tokens);m(t,r)&&(i=!0),n+=1}i&&r.setPendingSequence(null),n>0&&t.queueStateChange()})},c=()=>{for(let t of e.layers){y(t);for(let e of t.commands)y(e);for(let e of t.bindings)y(e);t.offTargetDestroy?.(),t.offTargetDestroy=void 0}},l=e=>{if(e.targetMode){if(!e.target)throw Error(`Keymap targetMode "${e.targetMode}" requires a target`);return e.targetMode}return e.target?`focus-within`:void 0},u=(t,n)=>{let r=e.layerBindingsTransformers.values();if(r.length===0)return t;let i=t;for(let e of r){let t=e(i,{layer:n,validateBindings:e=>xl(e)});t&&(i=Sl(t))}return i},d=(n,r)=>{let i=e.commandTransformers.values();if(n.length===0||i.length===0)return n;let a=[];for(let e of n){let n={...e},o=[],s=!0;for(let e of i)try{e(n,{layer:r,add(e){o.push({...e})},skipOriginal(){s=!1}})}catch(e){t.emitError(`command-transformer-error`,e,`[Keymap] Error in command transformer:`)}s&&a.push(n),a.push(...o)}return a},f=t=>{let r={},a=[],o=Object.create(null),s={};for(let[c,l]of Object.entries(t)){if(Bl.has(c)||l===void 0)continue;o[c]=$l(l);let t=e.layerFields.get(c);if(!t){i.warnUnknownField(`layer`,c);continue}t(l,Yl({fieldName:c,conditions:n,requirements:r,matchers:a,attrs:s}))}return{requires:Object.entries(r),matchers:a,fields:Object.keys(o).length>0?Object.freeze(o):void 0,attrs:Object.keys(s).length>0?$l(s,{freeze:!0}):void 0}},p=(e,t)=>i.compiler.compileBindings(e.sourceBindings,t,e.target,e.order,e.fields),m=(t,n)=>{i.diagnostics?.analyzeLayer({target:t.target,order:t.order,commands:t.commands,sourceBindings:t.sourceBindings,bindings:n.bindings,hasTokenBindings:n.hasTokenBindings}),v(t);for(let e of t.bindings)y(e);t.bindings=n.bindings,t.root=ll(n.bindings,e.patterns),t.hasTokenBindings=n.hasTokenBindings,_(t);for(let e of t.bindings)g(e);return e.pending?.captures.some(e=>e.layer===t)??!1},h=n=>{t.runWithStateChangeBatch(()=>{if(e.layers.delete(n)){e.sortedLayers=e.sortedLayers.filter(e=>e!==n),v(n),y(n);for(let e of n.commands)y(e);for(let e of n.bindings)y(e);n.offTargetDestroy?.(),n.offTargetDestroy=void 0,e.pending?.captures.some(e=>e.layer===n)?r.setPendingSequence(null):n.commands.length>0&&!i.host.isDestroyed&&r.ensureValidPendingSequence(),t.queueStateChange()}})},g=e=>{for(let n of e.matchers)if(n.subscribe)try{n.dispose=n.subscribe(()=>{if(!r.hasPendingSequenceState()){t.queueStateChange();return}t.runWithStateChangeBatch(()=>{r.revalidatePendingSequenceIfNeeded(),t.queueStateChange()})})}catch(e){t.emitError(`reactive-matcher-subscribe-error`,e,Zl(e,`Failed to subscribe to reactive matcher from ${n.source}`))}},_=t=>{let n=sd(t),r=cd(t);t.activeKeyCacheBlocked=n,t.activeCommandViewCacheBlocked=r,n&&(e.activeKeyCacheBlockers+=1),r&&(e.activeCommandViewCacheBlockers+=1)},v=t=>{t.activeKeyCacheBlocked&&=(--e.activeKeyCacheBlockers,!1),t.activeCommandViewCacheBlocked&&=(--e.activeCommandViewCacheBlockers,!1)},y=e=>{for(let n of e.matchers)if(n.dispose){try{n.dispose()}catch(e){t.emitError(`reactive-matcher-dispose-error`,e,Zl(e,`Failed to dispose reactive matcher from ${n.source}`))}n.dispose=void 0}};return{registerLayer:a,applyTokenState:o,recompileBindings:s,cleanup:c}}var ud=1e3;function dd(e,t,n){let r=(e,n,r)=>{if(!t.has(`warning`)){let t=`[${e}] ${r}`;n instanceof Error?console.warn(t,n):console.warn(t);return}t.emit(`warning`,{code:e,message:r,warning:n})},i=(e,n,r)=>{if(!t.has(`error`)){let t=`[${e}] ${r}`;n instanceof Error?console.error(t,n):console.error(t);return}t.emit(`error`,{code:e,message:r,error:n})},a=()=>{if(!(!e.stateChangePending||e.stateChangeDepth>0||e.flushingStateChange)){e.flushingStateChange=!0;try{let t=0;for(;e.stateChangePending&&e.stateChangeDepth===0;){if(t>=ud){e.stateChangePending=!1,i(`state-change-feedback-loop`,{iterations:ud},`[Keymap] Possible infinite state listener feedback loop detected after ${ud} iterations; pending state notifications were dropped`);break}t+=1,e.stateChangePending=!1,n.emit(`state`)}}finally{e.flushingStateChange=!1}}};return{runWithStateChangeBatch(t){e.stateChangeDepth+=1;try{return t()}finally{--e.stateChangeDepth,e.stateChangeDepth===0&&a()}},queueStateChange(t){e.derivedVersion+=1,t?.invalidateCaches!==!1&&(e.cacheVersion+=1),n.has(`state`)&&(e.stateChangePending=!0,e.stateChangeDepth===0&&!e.flushingStateChange&&a())},emitWarning:r,emitError:i,reportListenerError(e,t){if(e===`state`){i(`state-listener-error`,t,`[Keymap] Error in state listener:`);return}if(e===`pendingSequence`){i(`pending-sequence-listener-error`,t,`[Keymap] Error in pending sequence listener:`);return}e===`dispatch`&&i(`dispatch-listener-error`,t,`[Keymap] Error in dispatch listener:`)},warnOnce(t,n,i,a){e.usedWarningKeys.has(t)||(e.usedWarningKeys.add(t),r(n,i,a))}}}function fd(e,t,n){return{getData(t){return e.data[t]},setData(r,i){t.runWithStateChangeBatch(()=>{if(i===void 0){if(!(r in e.data))return;delete e.data[r],e.dataVersion+=1,n.ensureValidPendingSequence(),t.queueStateChange();return}Object.is(e.data[r],i)||(e.data[r]=i,e.dataVersion+=1,n.ensureValidPendingSequence(),t.queueStateChange())})},getReadonlyData(){return e.readonlyDataVersion===e.dataVersion?e.readonlyData:(e.readonlyData=Object.freeze({...e.data}),e.readonlyDataVersion=e.dataVersion,e.readonlyData)}}}var pd=Object.freeze({});function md(){return{order:0,tokens:new Map,patterns:new Map,layerFields:new Map,layerBindingsTransformers:vl(),bindingExpanders:vl(),bindingParsers:vl(),bindingTransformers:vl(),bindingFields:new Map,commandTransformers:vl(),commandFields:new Map,eventMatchResolvers:vl(),disambiguationResolvers:vl(),keyHooks:yl(),keyAfterHooks:yl(),rawHooks:yl(),layers:new Set,sortedLayers:[],activeLayersCacheVersion:-1,activeLayersCacheFocused:void 0,activeLayersCache:[],activeKeyCacheBlockers:0,activeCommandViewCacheBlockers:0,commandResolvers:vl(),pending:null,data:{},dataVersion:0,readonlyDataVersion:-1,readonlyData:pd,cacheVersion:0,derivedVersion:0,stateChangeDepth:0,stateChangePending:!1,flushingStateChange:!1,usedWarningKeys:new Set}}function hd(e){return Wc(e)}var gd=class{#e=md();#t=!1;#n=new Map;#r=[];#i=gl(()=>{});#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;getPendingSequence;getActiveKeys;constructor(e){if(this.#b=e,e.isDestroyed)throw Error(`Cannot create a keymap for a destroyed host`);this.#a=gl((e,t)=>{this.#o.reportListenerError(e,t)}),this.#o=dd(this.#e,this.#i,this.#a),this.#l=zu(this.#e,this.#o),this.#u=ru(this.#e,this.#b,this.#o,this.#l,{onCommandResolversChanged:()=>{this.#s.ensureValidPendingSequence()}}),this.#s=Ll(this.#e,this.#b,this.#a,this.#o,this.#l,this.#u,{onPendingSequenceChanged:(e,t)=>{this.#p?.handlePendingSequenceChange(e,t)}}),this.#c=fd(this.#e,this.#o,this.#s),this.#d=wu(this.#o,this.#c,this.#s,this.#u,{keymap:this,createCommandEvent:()=>this.#b.createCommandEvent()}),this.#f=ju(this.#e,this.#o,this.#l,{warnUnknownField:(e,t)=>{this.#C(e,t)},warnUnknownToken:(e,t)=>{this.#w(e,t)}}),this.#h=wl(this.#o,this.#u),this.#m=ld(this.#e,this.#o,this.#l,this.#s,{compiler:this.#f,commands:this.#u,host:this.#b,diagnostics:this.#h,warnUnknownField:(e,t)=>{this.#C(e,t)}}),this.#p=Xu(this.#e,this.#o,this.#c,this.#s,this.#l,this.#d,this.#f,this.#u,this.#m,this.#a),this.getPendingSequence=this.#s.getPendingSequence,this.getActiveKeys=this.#s.getActiveKeys,this.#g=e=>{this.#p.handleKeyEvent(e,!1)},this.#_=e=>{this.#p.handleKeyEvent(e,!0)},this.#v=e=>this.#p.handleRawSequence(e),this.#y=e=>{this.#S(e)},this.#r.push(this.#b.onKeyPress(this.#g)),this.#r.push(this.#b.onKeyRelease(this.#_)),this.#b.onRawInput&&this.#r.push(this.#b.onRawInput(this.#v)),this.#r.push(this.#b.onFocusChange(this.#y)),this.#b.onDestroy&&this.#r.push(this.#b.onDestroy(()=>{this.#x()}))}[Zc](){return{state:this.#e,host:this.#b,conditions:this.#l,catalog:this.#u,activation:this.#s}}#x(){if(!this.#t){this.#t=!0,this.#s.setPendingSequence(null);for(let e of this.#n.values())e.dispose();this.#n.clear(),this.#m.cleanup();for(let e of this.#r.splice(0))e()}}setData(e,t){this.#c.setData(e,t)}getData(e){return this.#c.getData(e)}getHostMetadata(){return this.#b.metadata}hasPendingSequence(){return this.#s.ensureValidPendingSequence()!==void 0}createKeyMatcher(e){let t=this.#f.parseTokenKey(e).match;return e=>e?hd(e)===t:!1}parseKeySequence(e){return this.#f.parseKeySequence(e)}formatKey(e,t){return this.#f.formatKey(e,t)}clearPendingSequence(){this.#s.setPendingSequence(null)}popPendingSequence(){return this.#s.popPendingSequence()}getCommands(e){return this.#u.getCommands(e)}getCommandEntries(e){return this.#u.getCommandEntries(e)}getCommandBindings(e){return this.#u.getCommandBindings(e)}acquireResource(e,t){if(this.#t||this.#b.isDestroyed)throw Error(`Cannot use a keymap after its host was destroyed`);let n=this.#n.get(e);if(n)return n.count+=1,()=>{this.#T(e,n)};let r={count:1,dispose:t()};return this.#n.set(e,r),()=>{this.#T(e,r)}}runCommand(e,t){return this.#d.runCommand(e,t)}dispatchCommand(e,t){return this.#d.dispatchCommand(e,t)}on(e,t){return e===`warning`||e===`error`?this.#i.hook(e,t):this.#a.hook(e,t)}intercept(e,t,n){return this.#p.intercept(e,t,n)}registerLayer(e){return this.#m.registerLayer(e)}registerLayerFields(e){return id(this.#e,this.#o,`layer`,e)}prependLayerBindingsTransformer(e){return this.#e.layerBindingsTransformers.prepend(e)}appendLayerBindingsTransformer(e){return this.#e.layerBindingsTransformers.append(e)}clearLayerBindingsTransformers(){this.#e.layerBindingsTransformers.clear()}prependBindingTransformer(e){return this.#e.bindingTransformers.prepend(e)}appendBindingTransformer(e){return this.#e.bindingTransformers.append(e)}clearBindingTransformers(){this.#e.bindingTransformers.clear()}prependCommandTransformer(e){return this.#e.commandTransformers.prepend(e)}appendCommandTransformer(e){return this.#e.commandTransformers.append(e)}clearCommandTransformers(){this.#e.commandTransformers.clear()}prependBindingParser(e){return this.#e.bindingParsers.prepend(e)}appendBindingParser(e){return this.#e.bindingParsers.append(e)}clearBindingParsers(){this.#e.bindingParsers.clear()}registerToken(e){return nd(this.#e,this.#o,this.#f,this.#m,e)}registerSequencePattern(e){return rd(this.#e,this.#o,this.#m,e)}prependBindingExpander(e){return this.#e.bindingExpanders.prepend(e)}appendBindingExpander(e){return this.#e.bindingExpanders.append(e)}clearBindingExpanders(){this.#e.bindingExpanders.clear()}registerBindingFields(e){return id(this.#e,this.#o,`binding`,e)}registerCommandFields(e){return id(this.#e,this.#o,`command`,e)}prependCommandResolver(e){return this.#u.prependCommandResolver(e)}appendCommandResolver(e){return this.#u.appendCommandResolver(e)}clearCommandResolvers(){this.#u.clearCommandResolvers()}prependLayerAnalyzer(e){return this.#h.prependLayerAnalyzer(e)}appendLayerAnalyzer(e){return this.#h.appendLayerAnalyzer(e)}clearLayerAnalyzers(){this.#h.clearLayerAnalyzers()}prependEventMatchResolver(e){return this.#p.prependEventMatchResolver(e)}appendEventMatchResolver(e){return this.#p.appendEventMatchResolver(e)}clearEventMatchResolvers(){this.#p.clearEventMatchResolvers()}prependDisambiguationResolver(e){return this.#p.prependDisambiguationResolver(e)}appendDisambiguationResolver(e){return this.#p.appendDisambiguationResolver(e)}clearDisambiguationResolvers(){this.#p.clearDisambiguationResolvers()}#S(e){this.#o.runWithStateChangeBatch(()=>{this.#s.setPendingSequence(null),this.#o.queueStateChange({invalidateCaches:!1})})}#C(e,t){this.#o.warnOnce(`${e}:${t}`,`unknown-${e}-field`,{field:t,kind:e},`[Keymap] Unknown ${e} field "${t}" was ignored`)}#w(e,t){this.#o.warnOnce(`token:${e}`,`unknown-token`,{token:e,sequence:t},`[Keymap] Unknown token "${e}" in key sequence "${t}"; binding was skipped until the token is registered`)}#T(e,t){this.#n.get(e)===t&&(--t.count,!(t.count>0)&&(t.dispose(),this.#n.delete(e)))}},_d=new Set(`up.down.left.right.clear.escape.return.linefeed.enter.tab.backspace.delete.insert.home.end.pageup.pagedown.space.lt.gt.plus.minus.equal.comma.period.slash.backslash.semicolon.quote.backquote.leftbracket.rightbracket.capslock.numlock.scrolllock.printscreen.pause.menu.apps.kp0.kp1.kp2.kp3.kp4.kp5.kp6.kp7.kp8.kp9.kpdecimal.kpdivide.kpmultiply.kpminus.kpplus.kpenter.kpequal.kpseparator.kpleft.kpright.kpup.kpdown.kppageup.kppagedown.kphome.kpend.kpinsert.kpdelete.mediaplay.mediapause.mediaplaypause.mediareverse.mediastop.mediafastforward.mediarewind.medianext.mediaprev.mediarecord.volumedown.volumeup.mute.leftshift.leftctrl.leftalt.leftsuper.lefthyper.leftmeta.rightshift.rightctrl.rightalt.rightsuper.righthyper.rightmeta.iso_level3_shift.iso_level5_shift.option.alt.meta.super.hyper.control.ctrl.shift`.split(`.`)),vd=new Set([`ctrl`,`control`,`shift`,`meta`,`alt`,`option`,`super`,`hyper`]),yd=xd(_d),bd=xd(vd);function xd(e){let t=new Map;for(let n of e){let e=n.charCodeAt(0);if(Number.isNaN(e))continue;let r=t.get(e);r||(r=[],t.set(e,r)),r.push(n)}for(let e of t.values())e.sort((e,t)=>t.length-e.length);return t}function Sd(e){return e>=65&&e<=90?e+32:e}function Cd(e){return e>=48&&e<=57}function wd(e,t,n){if(e.startsWith(t,n))return!0;if(n+t.length>e.length)return!1;for(let r=0;r<t.length;r+=1)if(Sd(e.charCodeAt(n+r))!==t.charCodeAt(r))return!1;return!0}function Td(e,t,n){let r=t.charCodeAt(n);if(Number.isNaN(r))return;let i=e.get(Sd(r));if(i){for(let e of i)if(wd(t,e,n))return e}}function Ed(e,t,n,r,i){return e.parseObjectKey(t,{display:n,match:r,tokenName:i})}function Dd(e,t){if(e===` `)return t.parseObjectKey({name:`space`},{display:`space`});if(e===`+`)return t.parseObjectKey({name:`+`},{display:`+`});let n=e.split(`+`),r=``,i=``,a=!1,o=!1,s=!1,c=!1,l=!1;for(let t of n){let n=t.trim();if(!n)continue;let u=n.toLowerCase();if(u===`ctrl`||u===`control`){a=!0;continue}if(u===`shift`){o=!0;continue}if(u===`meta`||u===`alt`||u===`option`){s=!0;continue}if(u===`super`){c=!0;continue}if(u===`hyper`){l=!0;continue}if(r)throw Error(`Invalid key "${e}": multiple key names are not supported`);r=n,i=u}if(!r)throw Error(`Invalid key "${e}": missing key name`);let u=[];return a&&u.push(`ctrl`),o&&u.push(`shift`),s&&u.push(`meta`),c&&u.push(`super`),l&&u.push(`hyper`),u.push(i),t.parseObjectKey({name:r,ctrl:a,shift:o,meta:s,super:c,hyper:l||void 0},{display:u.join(`+`)})}function Od(e,t){let n=e.trim().toLowerCase();return t.parseObjectKey({name:n},{display:n})}function kd(e,t){let n=Td(yd,e,t);if(n)return n;if(Sd(e.charCodeAt(t))!==102||!Cd(e.charCodeAt(t+1)))return;let r=Cd(e.charCodeAt(t+2))?t+3:t+2;return e.slice(t,r).toLowerCase()}function Ad(e,t){return Td(bd,e,t)}function jd(e,t,n){let r=t,i=!1,a=!1,o=!1,s=!1,c=!1;for(;r<e.length;){let t=Ad(e,r);if(!t)break;let n=r+t.length;if(e[n]!==`+`)break;t===`ctrl`||t===`control`?i=!0:t===`shift`?a=!0:t===`meta`||t===`alt`||t===`option`?o=!0:t===`super`?s=!0:t===`hyper`&&(c=!0),r=n+1}if(r===t)return;let l=e[r];if(l===void 0)throw Error(`Invalid key "${e.slice(t)}": missing key name`);let u=kd(e,r)??l,d=u===` `?`space`:u===`+`?`+`:u.toLowerCase(),f=[];return i&&f.push(`ctrl`),a&&f.push(`shift`),o&&f.push(`meta`),s&&f.push(`super`),c&&f.push(`hyper`),f.push(d),{part:n.parseObjectKey({name:u===` `?`space`:u,ctrl:i,shift:a,meta:o,super:s,hyper:c||void 0},{display:f.join(`+`)}),nextIndex:r+u.length}}var Md=e=>{let{input:t,index:n,tokens:r,normalizeTokenName:i}=e;if(n===0&&t.includes(`+`)&&/\s/.test(t))return{parts:[Dd(t,e)],nextIndex:t.length};let a=t[n];if(a===void 0)return;if(a===`<`){let o=t.indexOf(`>`,n);if(o===-1)return{parts:[Dd(a,e)],nextIndex:n+1};let s=i(t.slice(n+1,o)),c=r.get(s);return c?{parts:[Ed(e,c.stroke,`<${s}>`,c.match,s)],nextIndex:o+1,usedTokens:[s]}:{parts:[],nextIndex:o+1,unknownTokens:[s]}}if(a===`{`){let r=t.indexOf(`}`,n);if(r===-1)return{parts:[Dd(a,e)],nextIndex:n+1};let o=i(t.slice(n+1,r)),s=e.patterns.get(o);return s?{parts:[{...e.parseObjectKey({name:o,ctrl:!1,shift:!1,meta:!1,super:!1},{display:s.display??`{${o}}`,match:s.match}),patternName:s.name,payloadKey:s.payloadKey}],nextIndex:r+1,usedTokens:[o]}:{parts:[],nextIndex:r+1,unknownTokens:[o]}}let o=jd(t,n,e);if(o)return{parts:[o.part],nextIndex:o.nextIndex};let s=kd(t,n);return s?{parts:[Od(s,e)],nextIndex:n+s.length}:{parts:[Dd(a,e)],nextIndex:n+1}},Nd=(e,t)=>[t.resolveKey({name:e.name,ctrl:e.ctrl,shift:e.shift,meta:e.meta,super:e.super??!1,hyper:e.hyper||void 0})];function Pd(e){return e.appendBindingParser(e=>Md(e))}function Fd(e){return e.appendEventMatchResolver((e,t)=>Nd(e,t))}function Id(e){let t=Pd(e),n=Fd(e);return()=>{n(),t()}}var Ld=Symbol(`keymap:mod-bindings`),Rd=/(^|[+,\s])mod(?=\s*\+)/i,zd=/(^|[+,\s])mod(?=\s*\+)/gi;function Bd(e){let t=e.primaryModifier;return(t===`ctrl`||t===`super`)&&e.modifiers[t]!==`unsupported`?t:e.modifiers.ctrl===`unsupported`?`super`:`ctrl`}function Vd(e){if(e.includes(`,`))return[e];let t=e.trim();return t.includes(` `)?t.split(/\s+/):[e]}function Hd(e){return e.acquireResource(Ld,()=>e.appendBindingExpander(({input:t,displays:n})=>{if(!Rd.test(t))return;let r=Bd(e.getHostMetadata());return[{key:t.replace(zd,(e,t)=>`${t}${r}`),displays:n??Vd(t)}]}))}var Ud=new Map([[` `,`space`],[`Spacebar`,`space`],[`ArrowUp`,`up`],[`ArrowDown`,`down`],[`ArrowLeft`,`left`],[`ArrowRight`,`right`],[`Escape`,`escape`],[`Esc`,`escape`],[`Enter`,`return`],[`Backspace`,`backspace`],[`Delete`,`delete`],[`Tab`,`tab`],[`Home`,`home`],[`End`,`end`],[`PageUp`,`pageup`],[`PageDown`,`pagedown`],[`Insert`,`insert`],[`CapsLock`,`capslock`],[`NumLock`,`numlock`],[`ScrollLock`,`scrolllock`],[`ContextMenu`,`menu`],[`Meta`,`super`],[`OS`,`super`],[`Alt`,`alt`],[`Control`,`control`],[`Shift`,`shift`]]);function Wd(e){let t=e?.trim().toLowerCase();return t?t.includes(`mac`)||t.includes(`darwin`)?`macos`:t.includes(`win`)?`windows`:t.includes(`linux`)||t.includes(`x11`)?`linux`:`unknown`:`unknown`}function Gd(){let e=globalThis.navigator,t=e?.userAgentData?.platform,n=Wd(t);return n===`unknown`?Wd(e?.platform??e?.userAgent):n}function Kd(){let e=Gd();return{platform:e,primaryModifier:e===`macos`?`super`:e===`unknown`?`unknown`:`ctrl`,modifiers:{ctrl:`supported`,shift:`supported`,meta:`supported`,super:`supported`,hyper:`unsupported`}}}function qd(e){return e.length===1&&!/^[a-z0-9]$/i.test(e)}function Jd(e){let t={name:e.name,ctrl:e.ctrl,shift:e.shift,meta:e.meta,super:e.super??!1,hyper:e.hyper||void 0};return!t.shift||!qd(t.name)?[t]:[t,{...t,shift:!1}]}var Yd=class{name;ctrl;shift;meta;superKey;originalEvent;propagationStopped=!1;constructor(e,t,n,r,i,a){this.name=e,this.ctrl=t,this.shift=n,this.meta=r,this.superKey=i,this.originalEvent=a}get super(){return this.superKey}preventDefault(){this.originalEvent?.preventDefault()}stopPropagation(){this.propagationStopped=!0,this.originalEvent?.stopPropagation()}};function Xd(){return globalThis.MutationObserver}function Zd(e){return Ud.get(e)||(/^F\d{1,2}$/i.test(e)||e.length===1?e.toLowerCase():e.trim().toLowerCase().replace(/\s+/g,``))}function Qd(e){if(!e)return new Yd(`command`,!1,!1,!1,!1);let t=globalThis.KeyboardEvent;return new Yd(Zd(e.key),e.ctrlKey,e.shiftKey,e.altKey,e.metaKey,t&&e instanceof t?e:void 0)}var $d=class{metadata=Kd();rootTarget;isDestroyed=!1;observer;targetDestroyListeners=new Map;constructor(e){this.rootTarget=e}getFocusedTarget(){let e=this.rootTarget.ownerDocument.activeElement;return!e||typeof e!=`object`?null:e===this.rootTarget||this.rootTarget.contains(e)?e:null}getParentTarget(e){return e.parentElement}isTargetDestroyed(e){return e===this.rootTarget?!1:!e.isConnected||!this.rootTarget.contains(e)}onKeyPress(e){let t=t=>{e(Qd(t))};return this.rootTarget.addEventListener(`keydown`,t,{capture:!0}),()=>{this.rootTarget.removeEventListener(`keydown`,t,{capture:!0})}}onKeyRelease(e){let t=t=>{e(Qd(t))};return this.rootTarget.addEventListener(`keyup`,t,{capture:!0}),()=>{this.rootTarget.removeEventListener(`keyup`,t,{capture:!0})}}onFocusChange(e){let t=()=>{queueMicrotask(()=>{e(this.getFocusedTarget())})};return this.rootTarget.addEventListener(`focusin`,t,{capture:!0}),this.rootTarget.addEventListener(`focusout`,t,{capture:!0}),()=>{this.rootTarget.removeEventListener(`focusin`,t,{capture:!0}),this.rootTarget.removeEventListener(`focusout`,t,{capture:!0})}}onTargetDestroy(e,t){let n=this.targetDestroyListeners.get(e);return n||(n=new Set,this.targetDestroyListeners.set(e,n)),n.add(t),this.ensureObserver(),this.flushDisconnectedTargets(),()=>{let n=this.targetDestroyListeners.get(e);n&&(n.delete(t),n.size===0&&this.targetDestroyListeners.delete(e),this.targetDestroyListeners.size===0&&this.disconnectObserver())}}createCommandEvent(){return Qd()}ensureObserver(){if(this.observer||this.targetDestroyListeners.size===0)return;let e=Xd();e&&(this.observer=new e(()=>{this.flushDisconnectedTargets()}),this.observer.observe(this.rootTarget,{childList:!0,subtree:!0}))}disconnectObserver(){this.observer&&=(this.observer.disconnect(),void 0)}flushDisconnectedTargets(){for(let[e,t]of this.targetDestroyListeners)if(this.isTargetDestroyed(e)){this.targetDestroyListeners.delete(e);for(let e of[...t])e()}this.targetDestroyListeners.size===0&&this.disconnectObserver()}};function ef(e){return new $d(e)}var tf=(e,t)=>Jd(e).map(e=>t.resolveKey(e)),nf=[2,3],rf=`fungi.app.ready.v3`,af=`fungi.app.ready`,of=`fungi.app.connect`,Z=e=>I.pipe(B(q(1)),B(U(e))),sf=e=>z(Z(e)),cf=bo.pipe(B(Oa()),B(L(Number.isSafeInteger,{message:`Expected a safe integer`}))),lf=cf.pipe(B(ao(0))),uf=cf.pipe(B(_o(0))),df=F({appId:Z(160),releaseId:Z(160),surfaceId:Z(160)}),ff=F({editing:vo,surface:V([Z(160),ga])}),pf=V([F({kind:K(`compose`),requestId:Z(160),text:Z(2e3)}),F({kind:K(`navigate`),requestId:Z(160),params:G(F({key:Z(64),value:Z(4096)})).pipe(B(U(16)))})]),mf=H(W([`granted`,`missing`])),hf=F({"agent.list":mf,"agent.manage":mf,"agent.read":mf,"agent.send":mf,"computer.list":mf,"computer.readFile":mf,"computer.writeFile":mf,"computer.execute":mf,"git.repository":mf,"workflow.publish":mf,"workflow.arm":mf,"workflow.run":mf,"app.events.emit":mf,"llm.generation":mf,"media.generation":mf,"media.share":mf}),gf=W([`ready`,`missing`,`unknown`]),_f=F({models:gf,media:gf,git:gf,terminal:W([`ready`,`exec-only`,`missing`,`unknown`]),terminalReason:z(I)}),vf=W([`model`,`media`,`git`,`computer`]),yf=W([`opened`,`unavailable`]),bf=F({computerId:V([Z(256),ga]),computerName:z(Ki(I)),teamHasComputers:z(Ki(vo)),computerAccessGranted:z(vo),setup:z(_f),permissions:z(hf),focus:ff,openRequest:V([ga,pf]),visibility:W([`visible`,`hidden`])}),xf=W([`connecting`,`connected`,`suspended`,`disconnected`,`disposing`,`disposed`]),Sf=F({altKey:vo,ctrlKey:vo,id:Z(160),key:Z(64),metaKey:vo,shiftKey:vo}),Cf=F({action:z(Xi),availability:z(Xi),category:Z(160),description:sf(512),id:Z(160),projections:z(Xi),title:Z(160)}),wf=F({arguments:z(Xi),commandId:Z(321),origin:W([`agent`,`browser`,`keyboard`,`menu`,`palette`,`programmatic`,`slash`,`terminal`]),requestId:Z(160)}),Tf=V([F({result:z(Xi),status:K(`handled`)}),F({error:Xi,status:K(`failed`)})]),Ef=e=>Z(e).pipe(B(L(e=>{for(let t=0;t<e.length;t+=1)if(Pc(e.charCodeAt(t)))return!1;return!0},{message:`Expected one line of plain text`}))),Df={id:Z(64),text:Ef(80),end:H(vo),priority:H(K(`low`))},Of=H(bo.pipe(B(Oa()),B(po({minimum:0,maximum:9999})))),kf=G(V([F({...Df,kind:K(`text`),tone:H(W([`neutral`,`success`,`warning`,`error`]))}),F({...Df,kind:K(`button`),icon:H(W([`folder`,`ports`,`processes`,`access`])),count:Of,tone:H(W([`neutral`,`success`,`warning`,`error`])),busy:H(vo),title:H(Ef(1024)),disabled:H(vo),opens:H(K(`dialog`)),expanded:H(vo)}),F({...Df,kind:K(`toggle`),pressed:vo}),F({...Df,kind:K(`menu`),count:Of,title:H(Ef(1024)),options:G(F({id:Z(64),text:Ef(80),checked:H(vo),disabled:H(vo)})).pipe(B(U(16)),B(L(e=>new Set(e.map(e=>e.id)).size===e.length,{message:`Expected unique status option ids`})))})])).pipe(B(U(6)),B(L(e=>new Set(e.map(e=>e.id)).size===e.length,{message:`Expected unique status item ids`}))),Af=F({computerId:Z(256),path:Z(1024)}),jf=Z(80).pipe(B(L(e=>e.trim()===e,{message:`Expected a trimmed title`}))),Mf=Z(64),Nf=Z(80),Pf=e=>new Set(e.map(e=>e.id)).size===e.length,Ff=F({id:Mf,label:Nf,siblings:z(G(F({id:Mf,label:Nf})).pipe(B(U(16)),B(L(Pf,{message:`Expected unique crumb sibling ids`}))))}),If=F({id:Mf,label:Nf,icon:z(K(`play`)),variant:z(W([`primary`,`outline`,`ghost`])),tone:z(K(`destructive`)),disabled:z(vo)}),Lf=e=>G(If).pipe(B(U(e)),B(L(Pf,{message:`Expected unique header command ids`}))),Rf=F({id:Mf,label:Nf,presentation:z(K(`bead`)),tone:z(W([`neutral`,`info`,`warning`,`success`,`error`]))}),zf={status:z(G(Rf).pipe(B(U(4)),B(L(Pf,{message:`Expected unique header status ids`})))),crumbs:z(G(Ff).pipe(B(U(8)),B(L(Pf,{message:`Expected unique crumb ids`})))),primary:z(Lf(3)),menu:z(Lf(12))},Bf=F({contractVersion:K(2),canGoBack:vo,canGoForward:vo,title:z(jf),...zf}),Vf=F({canGoBack:vo,canGoForward:vo,title:z(I),...zf}),Hf=V([F({kind:K(`crumb`),crumbId:Mf,siblingId:z(Mf)}),F({kind:K(`action`),actionId:Mf})]),Uf=Ki(F({agentId:Z(256),sessionId:Z(256)})),Wf=e=>z(G(W(e)).pipe(B(U(e.length)))),Gf=F({agents:z(G(W([`agent.list`,`agent.manage`,`agent.read`,`agent.send`])).pipe(B(U(4)))),computers:z(G(W([`computer.list`,`computer.readFile`,`computer.writeFile`,`computer.execute`])).pipe(B(U(4)))),git:Wf([`git.repository`]),workflows:Wf([`workflow.publish`,`workflow.arm`,`workflow.run`]),events:Wf([`app.events.emit`]),generation:Wf([`llm.generation`,`media.generation`,`media.share`])}),Kf=W([`granted`,`declined`,`customize`]),qf=F({message:Z(512),tone:z(W([`info`,`success`,`warning`,`error`]))}),Jf=W(Io);F({code:Jf.pick([`DELIVERY_PENDING`])});var Yf=F({code:Jf,message:Z(512),retryable:vo,need:H(Fo)}),Xf=V([F({protocolVersion:K(3),type:K(rf)}),F({protocolVersion:K(2),type:K(af)})]),Zf=F({epoch:Z(160),protocolVersion:W(nf),type:K(of)}),Qf=F({epoch:Z(160),protocolVersion:W(nf)}),$f={[Symbol.dispose]:z(Xi)},ep=V([F({...$f,ok:K(!0),value:Xi}),F({...$f,error:Yf,ok:K(!1)})]);function Q(e,t,n=`PROTOCOL`){return pi(Qi(e,{onExcessProperty:`error`}),Mr({onFailure:e=>{throw new Y(`The peer sent malformed protocol data`,{cause:e,code:n,retryable:!1})},onSuccess:t}))}function $(e){return Object.freeze(e)}function tp(e,t){let n=e.arguments===void 0?void 0:at(e.arguments),r={origin:e.origin,signal:t};return n!==void 0&&Object.assign(r,{arguments:n}),$(r)}var np=Q(Cf,e=>{let t={category:e.category,id:e.id,title:e.title};return e.action!==void 0&&Object.assign(t,{action:e.action}),e.availability!==void 0&&Object.assign(t,{availability:e.availability}),e.description!==void 0&&Object.assign(t,{description:e.description}),e.projections!==void 0&&Object.assign(t,{projections:e.projections}),$(qp(()=>et(t)))},`INVALID_ARGUMENT`),rp=Q(Z(321),e=>e),ip=Q(wf,e=>{let t=e.arguments===void 0?void 0:at(e.arguments),n={commandId:e.commandId,origin:e.origin,requestId:e.requestId};return t!==void 0&&Object.assign(n,{arguments:t}),$(n)}),ap=Q(V([oa,Xi]),e=>e===void 0?void 0:at(e)),op=Q(Zf,e=>$(e));Q(Qf,e=>$(e));var sp=Q(bf,e=>{let t={computerId:e.computerId,focus:$({...e.focus}),openRequest:e.openRequest===null?null:$({...e.openRequest}),visibility:e.visibility};return e.teamHasComputers!==void 0&&(t.teamHasComputers=e.teamHasComputers),e.computerName!==void 0&&(t.computerName=e.computerName),e.computerAccessGranted!==void 0&&(t.computerAccessGranted=e.computerAccessGranted),e.setup!==void 0&&(t.setup=$({...e.setup})),e.permissions!==void 0&&(t.permissions=$({...e.permissions})),$(t)}),cp=Q(Yf,e=>$({...e})),lp=Q(ff,e=>$({...e}),`INVALID_ARGUMENT`),up=Q(df,e=>$({...e})),dp=Q(xf,e=>e),fp=Q(kf,e=>$(e.map(e=>e.kind===`menu`?$({...e,options:$(e.options.map(e=>$(e)))}):$(e))),`INVALID_ARGUMENT`),pp=Q(F({itemId:Z(64),optionId:H(Z(64)),anchor:H(F({start:bo.pipe(B(po({minimum:0,maximum:1e5}))),width:bo.pipe(B(po({minimum:0,maximum:1e5})))}))}),e=>$(e.anchor===void 0?{...e}:{...e,anchor:$({...e.anchor})}),`INVALID_ARGUMENT`),mp=Q(Af,e=>$({...e}),`INVALID_ARGUMENT`);function hp(e){let t={id:e.id,label:e.label};return e.presentation!==void 0&&(t={...t,presentation:e.presentation}),e.tone!==void 0&&(t={...t,tone:e.tone}),$(t)}function gp(e){let t={id:e.id,label:e.label};return e.siblings===void 0?$(t):$({...t,siblings:$(e.siblings.map(e=>$({...e})))})}function _p(e){let t={id:e.id,label:e.label};return e.icon!==void 0&&(t={...t,icon:e.icon}),e.variant!==void 0&&(t={...t,variant:e.variant}),e.tone!==void 0&&(t={...t,tone:e.tone}),e.disabled!==void 0&&(t={...t,disabled:e.disabled}),$(t)}function vp(e){let t={canGoBack:e.canGoBack,canGoForward:e.canGoForward};return e.title!==void 0&&(t={...t,title:e.title}),e.crumbs!==void 0&&(t={...t,crumbs:$(e.crumbs.map(gp))}),e.primary!==void 0&&(t={...t,primary:$(e.primary.map(_p))}),e.menu!==void 0&&(t={...t,menu:$(e.menu.map(_p))}),e.status!==void 0&&(t={...t,status:$(e.status.map(hp))}),$(t)}var yp=Q(Bf,vp,`INVALID_ARGUMENT`),bp=Q(Vf,e=>{let t=e.title?.trim();return xp({...vp({...e,title:t===void 0||t.length===0?void 0:t}),contractVersion:2})},`INVALID_ARGUMENT`),xp=Q(Bf,e=>$({...vp(e),contractVersion:2}),`INVALID_ARGUMENT`),Sp=Q(Hf,e=>e.kind===`action`?$({...e}):$(e.siblingId===void 0?{kind:e.kind,crumbId:e.crumbId}:e),`INVALID_ARGUMENT`),Cp=Q(Uf,e=>e===null?null:$({...e}),`INVALID_ARGUMENT`),wp=Q(Gf,e=>$({agents:$([...new Set(e.agents??[])]),computers:$([...new Set(e.computers??[])]),...e.git&&{git:$([...new Set(e.git)])},...e.workflows&&{workflows:$([...new Set(e.workflows)])},...e.events&&{events:$([...new Set(e.events)])},...e.generation&&{generation:$([...new Set(e.generation)])}}),`INVALID_ARGUMENT`),Tp=Q(vf,e=>e,`INVALID_ARGUMENT`);Q(Xf,e=>$(e));var Ep=Q(Z(512),e=>e),Dp=Q(qf,e=>$({...e}),`INVALID_ARGUMENT`);Q(F({id:Z(160),repeat:vo}),e=>$(e));var Op=Q(G(Sf).pipe(B(U(64))),e=>{if(new Set(e.map(e=>e.id)).size!==e.length)throw new Y(`Reserved chords are invalid`,{code:`PROTOCOL`,retryable:!1});return $(e.map(e=>$({...e})))});function kp(e){return Q(F({value:Xi,version:lf}),t=>$({value:e(t.value),version:t.version}))}var Ap=kp(sp),jp=Q(F({capabilities:G(Xi).pipe(B(U(128))),context:Xi}),e=>$({capabilities:$(e.capabilities.map(e=>Lp(e))),context:Ap(e.context)})),Mp=kp(dp),Np=kp(Op),Pp=kp(Ep),Fp=pi(Mp,e=>{if(e.value!==`connected`&&e.value!==`suspended`)throw new Y(`The host lifecycle is invalid`,{code:`PROTOCOL`,retryable:!1});return $({value:e.value,version:e.version})});function Ip(e){return Q(F({handle:Xi,id:Z(160),version:uf}),t=>{if(!(t.handle instanceof jc)&&!(e&&t.handle instanceof Mc))throw new Y(`A capability handle is invalid`,{code:`PROTOCOL`,retryable:!1});return $({handle:t.handle,id:t.id,version:t.version})})}var Lp=Ip(!1),Rp=Ip(!0);function zp(e){let t=e?Rp:Lp;return Q(F({capabilities:G(Xi).pipe(B(U(128))),context:Xi,identity:Xi,lifecycle:Xi,reservedChords:Xi,theme:Xi}),e=>$({capabilities:$(e.capabilities.map(e=>t(e))),context:Ap(e.context),identity:up(e.identity),lifecycle:Fp(e.lifecycle),reservedChords:Np(e.reservedChords),theme:Pp(e.theme)}))}var Bp=zp(!1);zp(!0);function Vp(e){return Q(ep,t=>t.ok?$({ok:!0,value:e(t.value)}):$({ok:!1,error:cp(t.error)}))}var Hp=Vp(Bp),Up=Vp(Q(F({commandId:Z(321)}),e=>$(e)));Vp(Q(Tf,e=>{if(e.status===`failed`)return $({status:`failed`,error:qp(()=>te(e.error))});let t=e.result===void 0?void 0:at(e.result);return $(t===void 0?{status:`handled`}:{status:`handled`,result:t})}));var Wp=Vp(Q(oa,()=>void 0)),Gp=Vp(Q(Kf,e=>e)),Kp=Vp(Q(yf,e=>e));Vp(Q(vo,e=>e)),Vp(Q(vo,e=>e));function qp(e){try{return e()}catch(e){throw new Y(`The command metadata is invalid`,{cause:e,code:`INVALID_ARGUMENT`,retryable:!1})}}var Jp=V([F({kind:K(`saveFile`),name:Z(255).pipe(B(ca(/^[^\p{Cc}/\\]+$/u))),mime:Z(255),bytes:Ka}),F({kind:K(`copyText`),text:I})]);function Yp(e){let t=Qi(Jp,{onExcessProperty:`error`})(e);if(Tr(t))return{kind:`refused`,reason:`invalid-request`};let n=t.success;return n.kind===`saveFile`?n.name===`.`||n.name===`..`?{kind:`refused`,reason:`invalid-request`}:n.bytes.byteLength>33554432?{kind:`refused`,reason:`too-large`}:{...n,bytes:new Uint8Array(n.bytes)}:n.text.length>1048576||new TextEncoder().encode(n.text).byteLength>1048576?{kind:`refused`,reason:`too-large`}:n}var Xp=Vp(Q(V([F({kind:K(`saved`)}),F({kind:K(`copied`)}),F({kind:K(`refused`),reason:W([`no-user-gesture`,`too-large`,`invalid-request`,`unavailable`,`denied`,`busy`])})]),e=>$(e)));function Zp(e){return e instanceof Y?{code:e.code,message:$p(e.message),retryable:e.retryable,...e.need!==void 0&&{need:e.need}}:{code:`HOST_FAILURE`,message:`Host operation failed`,retryable:!1}}function Qp(e){try{let t=cp(e);return new Y(t.message,{code:t.code,retryable:t.retryable,...t.need!==void 0&&{need:t.need}})}catch(e){return new Y(`The host returned a malformed error`,{cause:e,code:`PROTOCOL`,retryable:!1})}}function $p(e){return e.trim().slice(0,512)||`Host operation failed`}var em=e=>({ok:!0,value:e}),tm=e=>({error:Zp(e),ok:!1});async function nm(e,t){let n,r=new Set;try{return n=await e,rm(t(n))}catch(e){throw im(e)&&am(e,r),e instanceof Y?e:new Y(`The remote operation failed`,{cause:e,code:`HOST_FAILURE`,retryable:!0})}finally{n!==e&&im(n)&&am(n,r)}}function rm(e){if(e.ok)return e.value;throw Qp(e.error)}function im(e){return Ii(e)&&Symbol.dispose in e&&ai(e[Symbol.dispose])}function am(e,t){if(!t.has(e)){t.add(e);try{e[Symbol.dispose]()}catch(e){console.warn(`RPC result disposal failed`,e)}}}function om(){let e=[],t=new Set;return{get:()=>e,subscribe:e=>(t.add(e),()=>t.delete(e)),update:n=>{e=n;for(let e of Array.from(t))try{e()}catch(e){console.warn(`App binding subscriber failed`,e)}}}}function sm(e){let t=Op(e),n=new Set;return{get:()=>t,subscribe:e=>(n.add(e),()=>n.delete(e)),update:e=>{t=Op(e);for(let e of Array.from(n))try{e()}catch(e){console.warn(`Reserved chord subscriber failed`,e)}}}}function cm(e){let t=!0,n,r=e.window.document.querySelector(`html`);if(!r)return()=>{t=!1};let i=ef(r),a=new gd(i);Id(a),Hd(a),a.prependEventMatchResolver(tf);let o=um(e.onBroken),s=mm(a,e.chords,e.remote,o),c=lm(e,o,()=>t,e=>{n=e},()=>n),l=i.onFocusChange(()=>{queueMicrotask(c)}),u=()=>{queueMicrotask(c)};e.window.addEventListener(`focus`,u),e.window.addEventListener(`blur`,u);let d=e.bindings,f=()=>dm(e.window.document,e.identity.surfaceId).editing,p=d===void 0?()=>void 0:fm(a,d,f),m=d===void 0?()=>void 0:d.subscribe(()=>{p(),p=fm(a,d,f)}),h=e.chords.subscribe(()=>{s(),s=mm(a,e.chords,e.remote,o)});return queueMicrotask(c),()=>{t&&(t=!1,l(),e.window.removeEventListener(`focus`,u),e.window.removeEventListener(`blur`,u),h(),s(),m(),p())}}function lm(e,t,n,r,i){return()=>{if(!n())return;let a=dm(e.window.document,e.identity.surfaceId),o=i();(a.editing!==o?.editing||a.surface!==o.surface)&&(r(a),t(()=>e.remote.reportFocus(a)))}}function um(e){return t=>{try{nm(t(),Wp).catch(t=>{ss(`browser-bridge.host-call`,t),e(t)})}catch(t){ss(`browser-bridge.host-call`,t),e(t)}}}function dm(e,t){let n=e.activeElement;return lp({editing:!!(n?.matches(`input, textarea, select, [contenteditable='true']`)===!0||n?.closest(`[contenteditable='true']`)),surface:e.hasFocus()?t:null})}function fm(e,t,n){let r=t.get();return e.registerLayer({bindings:r.map((e,t)=>({cmd:`app/${String(t)}`,key:e.key})),commands:r.map((e,t)=>({name:`app/${String(t)}`,run:t=>{let r=t.event.originalEvent;if(r?.defaultPrevented||r?.isComposing||pm(e.key)&&n())return!1;e.run()}})),priority:500})}function pm(e){return!/(?:^|\+)(?:ctrl|control|super|meta|cmd|alt|option|mod)\+/iu.test(e)}function mm(e,t,n,r){let i=t.get();return e.registerLayer({bindings:i.map(e=>({cmd:`reserved/${e.id}`,key:{ctrl:e.ctrlKey,meta:e.altKey,name:Zd(e.key),shift:e.shiftKey,super:e.metaKey}})),commands:i.map(e=>({name:`reserved/${e.id}`,run:t=>{let i=t.event.originalEvent;if(i?.defaultPrevented||i?.isComposing)return!1;r(()=>n.invokeReservedChord(e.id,i?.repeat??!1))}})),priority:1e3})}function hm(e){let t=t=>{if(t.defaultPrevented||t.isComposing)return;let n=vm(t,e.mac);n!==null&&(t.preventDefault(),!t.repeat&&(n===`back`&&e.canGoBack()&&e.back(),n===`forward`&&e.canGoForward()&&e.forward()))},n=t=>{let n=_m(t.button);if(n===null)return;let r=t.defaultPrevented;t.preventDefault(),!(t.type!==`mouseup`||r)&&(n===`back`&&e.canGoBack()&&e.back(),n===`forward`&&e.canGoForward()&&e.forward())};e.window.addEventListener(`keydown`,t);for(let t of gm)e.window.addEventListener(t,n);return()=>{e.window.removeEventListener(`keydown`,t);for(let t of gm)e.window.removeEventListener(t,n)}}var gm=[`mousedown`,`mouseup`,`auxclick`];function _m(e){return e===3?`back`:e===4?`forward`:null}function vm(e,t){return e.shiftKey||e.ctrlKey?null:t?!e.metaKey||e.altKey?null:e.key===`[`?`back`:e.key===`]`?`forward`:ym(e.target)?null:e.key===`ArrowLeft`?`back`:e.key===`ArrowRight`?`forward`:null:!e.altKey||e.metaKey?null:e.key===`ArrowLeft`?`back`:e.key===`ArrowRight`?`forward`:null}function ym(e){return e instanceof HTMLElement?e.isContentEditable||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement:!1}function bm(){return!vr(globalThis.navigator)&&/Mac|iPhone|iPad/u.test(globalThis.navigator.userAgent)}function xm(e){let t=e,n=new Set;return{get:()=>t,subscribe(e){n.add(e);let t=!0;return()=>{t&&(t=!1,n.delete(e))}},update(e){if(!Object.is(t,e)){t=e;for(let e of Array.from(n))try{e(t)}catch(e){console.warn(`App store subscriber failed`,e)}}}}}function Sm(e){let t=new Map,n=xm(0),r=!1,i=e=>{let t=new Map;try{for(let n of e){let e=Lp(n),r=Em(e.id,e.version);if(t.has(r))throw wm(e.handle),new Y(`Duplicate capability grant`,{code:`PROTOCOL`,retryable:!1});t.set(r,e.handle)}}catch(e){for(let e of t.values())wm(e);throw e}return t};for(let[n,r]of i(e))t.set(n,r);let a=e=>{for(let t of e)wm(t)},o=e=>{if(r)throw new Y(`The app connection is disposed`,{code:`DISCONNECTED`,retryable:!0});let n=Em(e.id,e.version);return t.get(n)};return{directory:Object.freeze({get version(){return n.get()},subscribe:e=>n.subscribe(e),has(e){return!!o(e)},require(e){let t=o(e);if(!t)throw new Y(`The capability is not granted`,{code:`CAPABILITY_DENIED`,retryable:!1});try{return e.schema.parse(t)}catch(e){throw new Y(`The capability interface is malformed`,{cause:e,code:`PROTOCOL`,retryable:!1})}}}),replace(e){if(r)throw new Y(`The app connection is disposed`,{code:`DISCONNECTED`,retryable:!0});let o=i(e),s=[...t.values()];t.clear();for(let[e,n]of o)t.set(e,n);a(s.filter(e=>![...o.values()].includes(e))),n.update(n.get()+1)},disconnect(){r||(r=!0,a(t.values()),t.clear(),n.update(n.get()+1))}}}var Cm=Fr().transform(e=>{let t=pr(Object).safeParse(e);if(!t.success)return;let n=Object.create(t.data),r=R(F({[Symbol.dispose]:z(Vi(Function))}))(n);return{owner:t.data,dispose:r[Symbol.dispose]}});function wm(e){try{let t=Cm.parse(e);if(t===void 0||Tm.has(t.owner))return;Tm.add(t.owner),t.dispose?.call(t.owner)}catch(e){console.warn(`RPC value disposal failed`,e)}}var Tm=new WeakSet;function Em(e,t){return`${e}@${String(t)}`}var Dm=class extends Mc{#e=!0;#t;#n=new Map;constructor(e){super(),this.#t=e}cancel(e){try{return this.#n.get(rp(e))?.abort(),Promise.resolve(em(void 0))}catch(e){return Promise.resolve(tm(e))}}dispose(){if(this.#e){this.#e=!1;for(let e of this.#n.values())e.abort();this.#n.clear()}}async invoke(e){try{if(!this.#e)throw new Y(`The command is disposed`,{code:`DISCONNECTED`,retryable:!0});let t=ip(e);if(this.#n.has(t.requestId))throw new Y(`Duplicate command request`,{code:`PROTOCOL`,retryable:!1});if(this.#n.size>=64)throw new Y(`Too many command requests`,{code:`HOST_FAILURE`,retryable:!0});let n=new AbortController;this.#n.set(t.requestId,n);try{let e=ap(await this.#t(tp(t,n.signal)));return em(e===void 0?{status:`handled`}:{status:`handled`,result:e})}finally{this.#n.delete(t.requestId)}}catch(e){if(e instanceof Se)try{let t={code:e.code,message:e.message,details:e.details};return em({status:`failed`,error:te(t)})}catch(e){return tm(e)}return tm(e)}}[Symbol.dispose](){this.dispose()}};function Om(e){let t=[];for(let n of e.values()){let{commandId:e,definition:r,target:i}=n;if(e===void 0)continue;let a=r.availability?.status!==`unavailable`;for(let n of r.projections?.bindings?.values??[])n.trim().includes(` `)||n.startsWith(`<`)||t.push({key:n,run:()=>{a&&Promise.resolve().then(async()=>{let t=rm(await i.invoke({commandId:e,origin:`keyboard`,requestId:mn()}));if(t.status===`failed`)throw new Se(t.error.code,t.error.message,t.error.details)}).catch(e=>{console.warn(`App key command failed`,e)})}})}return t}function km(e,t,n,r){let i=new Map,a=!1,o=()=>{r?.update(a?[]:Om(i))},s=e=>{try{n()}catch(t){console.warn(`App command failure callback failed`,t,e)}},c=e=>{try{nm(e(),Wp).catch(e=>{s(e)})}catch(e){console.warn(`App command RPC supervision failed`,e),s(e)}};return{commands:jm(e,t,i,()=>a,t=>{let n=i.get(t);if(!n)return;i.delete(t),n.target.dispose(),o();let r=n.commandId;!a&&r!==void 0&&c(()=>e.unregisterCommand(r))},o),dispose(){if(!a){a=!0;for(let e of i.values())e.target[Symbol.dispose]();i.clear(),o()}}}}function Am(e,t,n){let r=t.id;if(e.size>=128||e.has(r))throw n.dispose(),new Y(`Command registration is unavailable`,{code:`INVALID_ARGUMENT`,retryable:!1});let i={commandId:void 0,definition:t,target:n};e.set(r,i);let a=!1;return{commit(e){a||(i.commandId=e)},release(){a||(a=!0,e.get(r)===i&&e.delete(r),n.dispose())},target:n}}function jm(e,t,n,r,i,a){return Object.freeze({async register(o,s){if(t(),!ai(s))throw new Y(`Command handler must be a function`,{code:`INVALID_ARGUMENT`,retryable:!1});let c=np(o),l=new Dm(s),u=Am(n,c,l);try{let t=await Mm(e,c,u.target);r()&&await Nm(e,t.commandId,l),u.commit(t.commandId),a()}catch(e){throw u.release(),e}let d=!0;return()=>{d&&(d=!1,i(c.id))}}})}async function Mm(e,t,n){return nm(e.registerCommand(t,n),Up)}async function Nm(e,t,n){throw n.dispose(),await nm(e.unregisterCommand(t),Wp),new Y(`The command controller is disposed`,{code:`DISCONNECTED`,retryable:!0})}var Pm=ha(e=>e instanceof jc),Fm=class extends Mc{#e=!1;#t;constructor(e){super(),this.#t=e}disconnect(e){try{if(this.#e)throw Km();let t=e===void 0?void 0:cp(e);return setTimeout(()=>this.#t.disconnect?.(t??Xm()),0),Promise.resolve(em(void 0))}catch(e){return Promise.resolve(tm(e))}}async requestClose(){try{if(this.#e)throw Km();return em(await(this.#t.beforeClose?.()??!0))}catch(e){return tm(e)}}async requestBack(){try{if(this.#e)throw Km();return em(await(this.#t.back?.()??!1))}catch(e){return tm(e)}}async requestForward(){try{if(this.#e)throw Km();return em(await(this.#t.forward?.()??!1))}catch(e){return tm(e)}}async activateNavigation(e){try{if(this.#e)throw Km();let t=Sp(e);return Ic(this.#t.navigation,t)?em(await(this.#t.activate?.(t)??!1)):em(!1)}catch(e){return tm(e)}}async activateStatus(e){try{if(this.#e)throw Km();let t=pp(e);return Fc(this.#t.statusItems,t)?em(await(this.#t.statusAction?.(t)??!1)):em(!1)}catch(e){return tm(e)}}[Symbol.dispose](){this.#e=!0}async updateContext(e){return this.#e?tm(Km()):this.#n(e,`context`,sp,e=>{this.#t.context.update(e)})}reconfigure(e){let t=[];try{if(this.#e)throw Km();let n=jp(e);if(n.context.version<=this.#t.versions.context)return Promise.resolve(em(void 0));for(let e of n.capabilities)t.push({...e,handle:R(Pm)(e.handle).dup()});if(!this.#t.capabilities)throw Km();return this.#t.capabilities.replace(t),t=[],this.#t.versions.context=n.context.version,this.#t.context.update(n.context.value),Promise.resolve(em(void 0))}catch(e){for(let e of t)wm(e.handle);return Promise.resolve(tm(e))}}updateLifecycle(e){try{if(this.#e)throw Km();let t=kp(dp)(e);if(t.version<=this.#t.versions.lifecycle)return Promise.resolve(em(void 0));if(!Zm(this.#t.lifecycle.get(),t.value))throw new Y(`The host sent an invalid lifecycle transition`,{code:`PROTOCOL`,retryable:!1});return this.#t.versions.lifecycle=t.version,this.#t.lifecycle.update(t.value),Promise.resolve(em(void 0))}catch(e){return Promise.resolve(tm(e))}}async updateReservedChords(e){return this.#e?tm(Km()):this.#n(e,`chords`,Op,e=>{this.#t.chords.update(e)})}async updateTheme(e){return this.#e?tm(Km()):this.#n(e,`theme`,Ep,e=>{this.#t.theme.update(e)})}#n(e,t,n,r){try{let i=kp(n)(e);return i.version>this.#t.versions[t]&&(this.#t.versions[t]=i.version,r(i.value)),Promise.resolve(em(void 0))}catch(e){return Promise.resolve(tm(e))}}};async function Im(e){let t=Bm(),n=new Fm(t),r=Nc(e.port,n),i,a=zm(r);try{performance.mark(`fungi.app-open.agar-rpc-connect-start`);let o=await Promise.race([r.connect({epoch:e.epoch,protocolVersion:e.protocolVersion}),a]);performance.mark(`fungi.app-open.agar-rpc-connect-ready`),i=o;let s=rm(Hp(o));if(!e.isActive())throw Rm();let c=Vm({bootstrap:s,bootstrapOwner:i,options:e,remote:r,state:t,target:n});return performance.mark(`fungi.app-open.agar-root-created`),i=void 0,c}catch(t){return $m(t,e,n,r,i)}}function Lm(e,t){e.context.update(t.context.value),e.theme.update(t.theme.value),e.lifecycle.update(t.lifecycle.value),e.chords.update(t.chords.value),e.versions.context=t.context.version,e.versions.theme=t.theme.version,e.versions.lifecycle=t.lifecycle.version,e.versions.chords=t.chords.version}function Rm(){return new Y(`App connection was cancelled`,{code:`CANCELLED`,retryable:!1})}function zm(e){let t,n=new Promise((e,n)=>{t=n});return n.catch(e=>{ss(`app-session.rpc-disconnect`,e)}),e.onRpcBroken(()=>t?.(new Y(`The app host disconnected`,{code:`DISCONNECTED`,retryable:!0}))),n}function Bm(){return{statusItems:[],navigation:{canGoBack:!1,canGoForward:!1},bindings:om(),chords:sm([]),context:xm({computerId:null,focus:{editing:!1,surface:null},openRequest:null,visibility:`hidden`}),lifecycle:xm(`connecting`),theme:xm(`default`),canGoBack:!1,canGoForward:!1,versions:{chords:-1,context:-1,lifecycle:-1,theme:-1}}}function Vm(e){let t=up(e.bootstrap.identity),n=Qm(e.bootstrap);Lm(e.state,n);let r=Sm(e.bootstrap.capabilities);return e.state.capabilities=r,Um(e,t,r)}function Hm(e,t,n){return cm({bindings:e.state.bindings,chords:e.state.chords,identity:t,onBroken:e=>{n({code:`DISCONNECTED`,message:e instanceof Y?e.message:`The app host rejected a browser bridge operation`,retryable:!0})},remote:e.remote,window:e.options.window})}function Um(e,t,n){let r=!1,i=t=>{r||(r=!0,Jm([()=>{t&&e.state.lifecycle.update(`disconnected`)},()=>{e.state.lifecycle.update(`disposing`)},l,u,()=>{o.dispose()},()=>{e.state.beforeClose=void 0,e.state.back=void 0,e.state.forward=void 0,e.state.activate=void 0,e.state.statusAction=void 0},()=>{n.disconnect()},()=>{e.target[Symbol.dispose]()},()=>{wm(e.bootstrapOwner)},()=>{wm(e.remote)},()=>{e.options.port.close()},()=>{e.state.lifecycle.update(`disposed`)},e.options.onDisposed],`app connection disposal`))},a=()=>{if(r)throw new Y(`The app connection is disposed`,{code:`DISCONNECTED`,retryable:!0})},o=km(e.remote,a,()=>{i({code:`DISCONNECTED`,message:`The app host rejected a terminal command operation`,retryable:!0})},e.state.bindings),s=Gm(e.remote,a,e.state),c=Wm(e.state,e.remote,a),l=Hm(e,t,i),u=hm({window:e.options.window,mac:bm(),canGoBack:()=>e.state.canGoBack&&e.state.back!==void 0,back:()=>{let t=e.state.back;t&&Promise.resolve().then(t).catch(e=>{ss(`app-window.back-input`,e)})},canGoForward:()=>e.state.canGoForward&&e.state.forward!==void 0,forward:()=>{let t=e.state.forward;t&&Promise.resolve().then(t).catch(e=>{ss(`app-window.forward-input`,e)})}});return e.state.disconnect=i,e.remote.onRpcBroken(()=>{qm(i)}),Ym({capabilities:n.directory,commands:o.commands,context:e.state.context,dispose:i,identity:t,lifecycle:e.state.lifecycle,theme:e.state.theme,ui:s,window:c})}function Wm(e,t,n){let r=Object.freeze({async publish(r){n();let i=bp(r);e.canGoBack=i.canGoBack,e.canGoForward=i.canGoForward,e.navigation=yp(i),await nm(t.reportNavigation(i),Wp)},onActivate(t){if(n(),e.activate!==void 0)throw new Y(`The App already owns navigation activations`,{code:`INVALID_ARGUMENT`,retryable:!1});e.activate=t;let r=!1;return()=>{r||(r=!0,e.activate===t&&(e.activate=void 0))}},onForward(t){if(n(),e.forward!==void 0)throw new Y(`The App already owns Forward requests`,{code:`INVALID_ARGUMENT`,retryable:!1});e.forward=t;let r=!1;return()=>{r||(r=!0,e.forward===t&&(e.forward=void 0))}},onBack(t){if(n(),e.back!==void 0)throw new Y(`The App already owns Back requests`,{code:`INVALID_ARGUMENT`,retryable:!1});e.back=t;let r=!1;return()=>{r||(r=!0,e.back===t&&(e.back=void 0))}}});return Object.freeze({navigation:r,onBeforeClose(t){if(n(),e.beforeClose!==void 0)throw new Y(`The App already owns a close consultation`,{code:`INVALID_ARGUMENT`,retryable:!1});e.beforeClose=t;let r=!1;return()=>{r||(r=!0,e.beforeClose===t&&(e.beforeClose=void 0))}}})}function Gm(e,t,n){return Object.freeze({async requestComputerChoice(){t(),await nm(e.requestComputerChoice(),Wp)},async requestBrowserAction(n){t();let r=Yp(n);return r.kind===`refused`?r:await nm(e.requestBrowserAction(r),Xp)},onStatusAction(e){if(t(),n.statusAction!==void 0)throw new Y(`The App already owns its status actions`,{code:`INVALID_ARGUMENT`,retryable:!1});n.statusAction=e;let r=!1;return()=>{r||(r=!0,n.statusAction===e&&(n.statusAction=void 0))}},async requestAppPermissions(n){return t(),await nm(e.requestAppPermissions(wp(n)),Gp)},async openDesktopSettings(){t(),await nm(e.openDesktopSettings(),Wp)},async openSetup(n){return t(),await nm(e.openSetup(Tp(n)),Kp)},async openTeamBilling(){t(),await nm(e.openTeamBilling(),Wp)},async openNavigation(n){t(),await nm(e.openNavigation(mp(n)),Wp)},async reportStatus(r){t();let i=fp(r);n.statusItems=i,await nm(e.reportStatus(i),Wp)},async reportAgentSessionSelection(n){t(),await nm(e.reportAgentSessionSelection(Cp(n)),Wp)},async showToast(n){t(),await nm(e.showToast(Dp(n)),Wp)}})}function Km(){return new Y(`The app connection is disposed`,{code:`DISCONNECTED`,retryable:!0})}function qm(e){e({code:`DISCONNECTED`,message:`The app host disconnected`,retryable:!0})}function Jm(e,t){for(let n of e)try{n()}catch(e){console.warn(`${t} cleanup failed`,e)}}function Ym(e){return Object.freeze(e)}function Xm(){return{code:`DISCONNECTED`,message:`The app host disconnected`,retryable:!1}}function Zm(e,t){return e===t||e===`connected`&&t===`suspended`||e===`suspended`&&t===`connected`}function Qm(e){let t=kp(sp)(e.context),n=kp(Ep)(e.theme),r=kp(dp)(e.lifecycle),i=kp(Op)(e.reservedChords);if(r.value!==`connected`&&r.value!==`suspended`)throw new Y(`The bootstrap lifecycle is invalid`,{code:`PROTOCOL`,retryable:!1});return{chords:i,context:t,lifecycle:r,theme:n}}function $m(e,t,n,r,i){throw Jm([()=>{n[Symbol.dispose]()},()=>{i&&wm(i)},()=>{wm(r)},()=>{t.port.close()},t.onDisposed],`app connection rejection`),e instanceof Y?e:new Y(`Unable to establish the app RPC session`,{cause:e,code:`PROTOCOL`,retryable:!1})}var eh=!1,th=class{options;#e;#t;#n=!1;#r;#i;constructor(e){this.options=e,this.#e=globalThis.window}start(){performance.mark(`fungi.app-open.agar-connect-start`);let e=this.#l();return e?Promise.reject(e):(eh=!0,this.#a())}#a(){return new Promise((e,t)=>{let n=(n,a)=>{this.#o(n,a,i,r,e,t)},r=()=>{n(rh())},i=e=>{this.#s(e,n,i)};this.#e.addEventListener(`message`,i),this.options.signal?.addEventListener(`abort`,r,{once:!0});let a=()=>{try{performance.mark(`fungi.app-open.agar-ready-sent`),this.#e.parent.postMessage({protocolVersion:3,type:rf},`*`),this.#e.parent.postMessage({protocolVersion:2,type:af},`*`)}catch(e){ss(`connect.notify-host`,e),n(lh(e))}};this.#r=setInterval(a,200),this.#i=setTimeout(()=>{n(ah())},1e4),a()})}#o(e,t,n,r,i,a){if(!this.#n){if(this.#n=!0,this.#c(),this.#e.removeEventListener(`message`,n),this.options.signal?.removeEventListener(`abort`,r),e||!t){this.#t?.close(),eh=!1,a(e??ah());return}i(t)}}#s(e,t,n){if(!ch(e.data))return;if(performance.mark(`fungi.app-open.agar-connect-received`),e.source!==this.#e.parent||oh(e.origin)===void 0){t(sh());return}let r=uh(e,t);if(!r)return;let i=e.ports.length===1?e.ports[0]:void 0;if(!i){t(dh(`The app host did not transfer exactly one port`));return}this.#t=i,this.#c(),this.#e.removeEventListener(`message`,n),Im({epoch:r.epoch,protocolVersion:r.protocolVersion,isActive:()=>!this.#n,onDisposed:()=>{eh=!1},port:i,window:this.#e}).then(e=>{performance.mark(`fungi.app-open.agar-root-ready`),t(void 0,e)},e=>{t(ih(e))})}#c(){clearInterval(this.#r),clearTimeout(this.#i),this.#r=void 0,this.#i=void 0}#l(){if(this.options.signal?.aborted)return rh();if(eh)return new Y(`An app connection is already live`,{code:`IDENTITY`,retryable:!1});if(vr(globalThis.window)||this.#e.parent===this.#e)return new Y(`The app host is unavailable`,{code:`DISCONNECTED`,retryable:!0})}};function nh(e){return new th(e).start()}function rh(){return new Y(`App connection was cancelled`,{code:`CANCELLED`,retryable:!1})}function ih(e){return e instanceof Y?e:new Y(`Unable to connect to the app host`,{cause:e,code:`PROTOCOL`,retryable:!1})}function ah(){return new Y(`The app host disconnected`,{code:`DISCONNECTED`,retryable:!0})}function oh(e){if(!URL.canParse(e))return;let t=new URL(e).origin;return t===e?t:void 0}function sh(){return new Y(`The app connection identity is invalid`,{code:`IDENTITY`,retryable:!1})}var ch=Fa(F({type:K(of)}));function lh(e){return new Y(`Unable to notify the app host`,{cause:e,code:`DISCONNECTED`,retryable:!0})}function uh(e,t){try{return op(e.data)}catch(e){ss(`connect.decode-message`,e),t(e instanceof Y?e:new Y(`Malformed app connection`,{cause:e,code:`PROTOCOL`,retryable:!1}));return}}function dh(e){return new Y(e,{code:`PROTOCOL`,retryable:!1})}function fh(e,t,n){e.style.isolation=`isolate`;let r=(0,os.createRoot)(e),i=new AbortController,a=e.ownerDocument.documentElement,s=Ho(a),c,l,u,d=!1,f=e=>{let i=(0,J.createElement)(ph,{state:e,render:n});r.render(t.queryClient?(0,J.createElement)(o,{client:t.queryClient},i):i)},p=()=>{u?.(),u=void 0,l?.(),l=void 0;let e=c;c=void 0,e?.dispose(),d&&=(s===null?a.removeAttribute(`data-theme`):Vo(s,a),!1)},{defaultView:m}=e.ownerDocument;return performance.mark(`fungi.app-open.react-root-render-start`),m?m.parent===m?f({app:null,status:`standalone`}):(f({app:null,status:`connecting`}),nh({host:`parent`,signal:i.signal}).then(e=>{if(i.signal.aborted){e.dispose();return}c=e;let t=()=>{let t=e.lifecycle.get();return t===`disposing`||t===`disconnected`||t===`disposed`?(p(),f({app:null,status:`ended`}),!0):!1};u=e.lifecycle.subscribe(t),!t()&&(d=!0,Vo(e.theme.get(),a),l=e.theme.subscribe(e=>{Vo(e,a)}),f({app:e,status:`live`}))}).catch(e=>{i.signal.aborted&&e instanceof Y&&e.code===`CANCELLED`||(console.error(`${t.name} host connection failed`,e),p(),i.signal.aborted||f({app:null,status:`not-hosted`,error:e instanceof Y?e:new Y(`The App host is unavailable`,{cause:e,code:`HOST_FAILURE`,retryable:!0})}))})):f({app:null,status:`not-hosted`,error:new Y(`The App document has no window`,{code:`DISCONNECTED`,retryable:!1})}),()=>{i.signal.aborted||(i.abort(),r.unmount(),p())}}function ph({state:e,render:t}){return(0,J.useLayoutEffect)(()=>{performance.mark(`fungi.app-open.react-initial-commit`)},[]),(0,J.useLayoutEffect)(()=>{e.app&&performance.mark(`fungi.app-open.react-connected-commit`)},[e.app]),(0,J.createElement)(J.Fragment,null,e.status===`not-hosted`?(0,J.createElement)(`p`,{role:`alert`},`App host connection unavailable. Open this App through its host to try again.`):null,t(e))}function mh(e){let t=(0,J.useCallback)(t=>e?.subscribe(t)??(()=>void 0),[e]),n=(0,J.useCallback)(()=>e?.get(),[e]);return(0,J.useSyncExternalStore)(t,n,n)}function hh(e){return mh(e?.context)??null}function gh(e,t,n,r){let i=(0,J.useRef)(t);i.current=t;let a=(0,J.useRef)(n);a.current=n;let o=(0,J.useRef)(r);o.current=r;let s=JSON.stringify(t),c=n!==void 0;(0,J.useEffect)(()=>{e&&e.ui.reportStatus(i.current).catch(e=>{o.current?o.current(e):console.error(`Window status report failed`,e)})},[e,s]),(0,J.useEffect)(()=>{if(!(!e||!c))return e.ui.onStatusAction(e=>a.current?.(e)??!1)},[e,c]),(0,J.useEffect)(()=>()=>{e?.ui.reportStatus([]).catch(e=>{console.error(`Window status report failed`,e)})},[e])}function _h(e,{canGoBack:t,canGoForward:n,title:r,crumbs:i,primary:a,menu:o,status:s,onBack:c,onForward:l,onCrumb:u,onAction:d}){let f=(0,J.useRef)(c),p=(0,J.useRef)(l),m=(0,J.useRef)(u),h=(0,J.useRef)(d);(0,J.useEffect)(()=>{f.current=c,p.current=l,m.current=u,h.current=d},[c,l,u,d]),(0,J.useEffect)(()=>{if(!e)return;let t=e.onBack(()=>f.current()),n=e.onForward(()=>p.current()),r=e.onActivate(e=>{if(e.kind===`action`){let t=h.current;return t?.(e.actionId),t!==void 0}let t=m.current;return e.siblingId===void 0?t?.(e.crumbId):t?.(e.crumbId,e.siblingId),t!==void 0});return()=>{t(),n(),r(),vh(e,{canGoBack:!1,canGoForward:!1})}},[e]);let g=JSON.stringify([i,a,o,s]),_=(0,J.useRef)({crumbs:i,primary:a,menu:o,status:s});(0,J.useEffect)(()=>{_.current={crumbs:i,primary:a,menu:o,status:s}},[i,a,o,s]),(0,J.useEffect)(()=>{if(!e)return;let i={canGoBack:t,canGoForward:n};r!==void 0&&(i={...i,title:r});let a=_.current;a.crumbs!==void 0&&(i={...i,crumbs:a.crumbs}),a.primary!==void 0&&(i={...i,primary:a.primary}),a.menu!==void 0&&(i={...i,menu:a.menu}),a.status!==void 0&&(i={...i,status:a.status}),vh(e,i)},[e,t,n,r,g])}function vh(e,t){e.publish(t).catch(e=>{e instanceof Y&&e.code===`DISCONNECTED`||console.warn(`App navigation report failed`,e)})}var yh=class{id;version;#e;constructor(e,t,n){this.id=e,this.version=t,this.#e=n,Object.freeze(this)}get schema(){return this.#e}};function bh(e,t,n){return new yh(e,t,n)}function xh(e){let t=Kr(e),n=pr(Object),r=Kr(Object.fromEntries(Object.keys(e).map(e=>[e,Fr().optional()])));return Fr().transform(e=>{let i=n.parse(e),a=Object.create(i),o=r.parse(a),s=Object.fromEntries(Object.entries(o).flatMap(([e,t])=>t===void 0?[]:[[e,jr().parse(t).bind(i)]]));return{...t.parse(s),[Symbol.dispose](){wm(e)}}})}function Sh(e){return Fr().transform(t=>{try{return e.parse(t)}catch(e){throw e instanceof Y?e:new Y(`The capability returned malformed data`,{cause:e,code:`PROTOCOL`,retryable:!1})}finally{wm(t)}})}function Ch(e){return jr({output:Mi(Fr().transform(t=>{try{return e.parse(t)}catch(e){throw wm(t),e instanceof Y?e:new Y(`The capability returned a malformed result`,{cause:e,code:`PROTOCOL`,retryable:!1})}}))})}var wh=Ch(Sh(bi())),Th=xh({fetch:Ch(pr(Response)),close:wh}),Eh=I.pipe(B(q(1)),B(U(256))),Dh=ha(e=>Bt.safeParse(e).success,{expected:`an Avatar v1 descriptor`}),Oh=F({agentId:Eh,name:Eh,avatar:Dh,sessionOperations:G(W([`agent.read`,`agent.send`,`agent.manage`]))});ti(()=>Yr({agents:Ti(Yr({agentId:Fi(),name:Fi()}))}));var kh=V([W([`new`,`none`]),F({computerId:Eh})]),Ah=F({computerId:Eh,name:Eh,createdAt:bo.pipe(B(Oa()))}),jh=Ki(G(Ah)),Mh=R(jh,{onExcessProperty:`error`}),Nh=F({name:Eh,requestId:Eh,computer:H(kh),avatar:H(Dh)}),Ph=G(Oh),Fh=R(Ph,{onExcessProperty:`error`}),Ih=R(Eh),Lh=R(Vi(Response)),Rh=bh(`agent.list`,1,ti(()=>xh({list:Ch(Sh(Fr().transform(e=>Fh(e))))}))),zh=bh(`agent.manage`,1,ti(()=>xh({open:Ch(Th),computers:Ch(Sh(Fr().transform(e=>Mh(e)))),create:Ch(Sh(Fr().transform(e=>R(Oh)(e))))}))),Bh=F({agentId:Eh,name:Eh}),Vh=bh(`agent.rename`,1,ti(()=>xh({rename:Ch(Sh(Fr().transform(e=>R(Oh)(e))))})));async function Hh(e,t){let n=R(Bh)(t),r=await e.require(Vh).rename(n);return R(Oh)(r)}var Uh=F({agentId:Eh,avatar:Dh}),Wh=bh(`agent.avatar`,1,ti(()=>xh({setAvatar:Ch(Sh(Fr().transform(e=>R(Oh)(e))))})));async function Gh(e,t){let n=R(Uh)(t),r=await e.require(Wh).setAvatar(n);return R(Oh)(r)}var Kh=F({agentId:Eh}),qh=F({agentId:Eh,expectedContent:Ki(I),content:I}),Jh=F({agentId:Eh,home:Ki(F({name:I})),content:Ki(I),bytes:oo.pipe(B(ao(0))),limit:oo.pipe(B(_o(0)))}),Yh=bh(`agent.instructions`,2,ti(()=>xh({read:Ch(Sh(Fr().transform(e=>R(Jh)(e)))),set:Ch(Sh(Fr().transform(e=>R(Jh)(e))))})));async function Xh(e,t){let n=R(Kh)({agentId:t});return R(Jh)(await e.require(Yh).read(n))}async function Zh(e,t){let n=R(qh)(t);return R(Jh)(await e.require(Yh).set(n))}var Qh=ti(()=>Ni([Kr({status:Si(`pending`),revision:Fi()}),Kr({status:Si(`approved`),revision:Fi()})])),$h=ti(()=>Ni([Qh,Kr({error:Fi()})])),eg=bh(`agent.toolPolicy`,1,ti(()=>xh({status:Ch(Sh(Ni([Qh,ei()]))),approve:Ch(Sh($h))}))),tg=bh(`agent.read`,1,ti(()=>xh({open:Ch(Th),openInbox:Ch(Th)}))),ng=bh(`agent.send`,1,ti(()=>xh({open:Ch(Th),openInbox:Ch(Th)})));async function rg(e,t){let n=R(Nh)(t),r=await e.require(zh).create(n);return R(Oh)(r)}async function ig(e){let t=Mh(await e.require(zh).computers());return t===null?null:[...t].sort((e,t)=>t.createdAt-e.createdAt)}async function ag(e,t){let n=await e(),r,i,a=()=>{if(i)throw new Y(`The Agent connection is closed`,{code:`DISCONNECTED`,retryable:!0})},o=async e=>{try{await e.close()}finally{e[Symbol.dispose]()}};return{fetch:async i=>{a(),i.signal.throwIfAborted();let o=i.method===`GET`||i.method===`HEAD`||e===t?n:await(r??=t());a(),i.signal.throwIfAborted();let s=Lh(await o.fetch(i));return s.body===null?s:new Response(s.body.pipeThrough(new TransformStream,{signal:i.signal}),s)},close:()=>(i||(i=Promise.all([o(n),...r?[r.then(o)]:[]]).then(()=>void 0),i.catch(e=>{ss(`agents.close`,e)})),i)}}var og=`https://agent-session.fungi.invalid`;async function sg(e,t){let n=Ih(t.agentId),r=`/agents/id-${encodeURIComponent(n)}`,i=`${og}${r}`,a=e.has(tg)?e.require(tg):e.has(ng)?e.require(ng):e.require(zh),o=()=>a.open({agentId:n}),s=await ag(o,e.has(tg)?()=>(e.has(ng)?e.require(ng):e.require(zh)).open({agentId:n}):o);return Object.freeze({baseUrl:i,fetch:async(e,t)=>{let n=new Request(e,t),i=new URL(n.url);if(i.origin!==og||!i.pathname.startsWith(`${r}/`))throw new Y(`The Agent request target is invalid`,{code:`INVALID_ARGUMENT`,retryable:!1});return i.pathname=i.pathname.slice(r.length),s.fetch(new Request(i,n))},close:s.close})}var cg=`${og}/member`;async function lg(e){let t=e.has(tg)?tg:ng,n=()=>e.require(t).openInbox(),r=await ag(n,e.has(tg)?()=>e.require(ng).openInbox():n);return Object.freeze({baseUrl:cg,fetch:async(e,t)=>{let n=new Request(e,t),i=new URL(n.url);if(i.origin!==og||!i.pathname.startsWith(`/member/inbox`))throw new Y(`The inbox request target is invalid`,{code:`INVALID_ARGUMENT`,retryable:!1});return i.pathname=i.pathname.slice(7),r.fetch(new Request(i,n))},close:r.close})}var ug=class extends Event{code;message;constructor(e,t){super(e),this.code=t?.code??void 0,this.message=t?.message??void 0}[Symbol.for(`nodejs.util.inspect.custom`)](e,t,n){return n(pg(this),t)}[Symbol.for(`Deno.customInspect`)](e,t){return e(pg(this),t)}};function dg(e){let t=globalThis.DOMException;return typeof t==`function`?new t(e,`SyntaxError`):SyntaxError(e)}function fg(e){return e instanceof Error?`errors`in e&&Array.isArray(e.errors)?e.errors.map(fg).join(`, `):`cause`in e&&e.cause instanceof Error?`${e}: ${fg(e.cause)}`:e.message:`${e}`}function pg(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var mg=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}},hg=10,gg=13,_g=32,vg=6;function yg(e){if(typeof e==`function`)throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{maxBufferSize:t,onComment:n,onError:r,onEvent:i,onId:a,onRetry:o}=e,s=[],c=0,l=!0,u,d=``,f=0,p,m=!1,h=!1,g=!1;function _(e){if(m)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,e.charCodeAt(0)===65279?e=e.slice(1):e.charCodeAt(0)===239&&e.charCodeAt(1)===187&&e.charCodeAt(2)===191&&(e=e.slice(3))),(h||g)&&(e=v(e),!e))return;if(!s.length){let t=S(e);t!==``&&y(t),x();return}if(e.indexOf(`
3
- `)===-1&&e.indexOf(`\r`)===-1){if(c<vg&&!b(s.join(``)+e.slice(0,vg-c))){s.length=0,c=0,h=!0;return}s.push(e),c+=e.length,x();return}s.push(e);let t=s.join(``);s.length=0,c=0,y(S(t)),x()}function v(e){if(e.length===0)return e;if(g)return g=!1,e.charCodeAt(0)===hg?e.slice(1):e;let t=e.indexOf(`\r`),n=e.indexOf(`
4
- `),r=t===-1?n:n===-1||t<n?t:n;return r===-1?``:r===e.length-1&&e.charCodeAt(r)===gg?(h=!1,g=!0,``):(h=!1,e.slice(r+(e.charCodeAt(r)===gg&&e.charCodeAt(r+1)===hg?2:1)))}function y(e){if(e){if(e.charCodeAt(e.length-1)===gg){C(e,0,e.length-1),g=!0;return}if(b(e)){s.push(e),c=e.length;return}h=!0}}function b(e){let t=e.charCodeAt(0);return t===58&&!!n||t===100&&Sg(e,`data`)||t===101&&Sg(e,`event`)||t===105&&Sg(e,`id`)||t===114&&Sg(e,`retry`)}function x(){t!==void 0&&(c+d.length<=t||(m=!0,s.length=0,c=0,u=void 0,d=``,f=0,p=void 0,h=!1,g=!1,r?.(new mg(`Buffered data exceeded max buffer size of ${t} characters`,{type:`max-buffer-size-exceeded`}))))}function S(e){let t=0;if(e.indexOf(`\r`)===-1){let n=e.indexOf(`
5
- `,t);for(;n!==-1;){if(t===n){u!==void 0&&a?.(u),f>0&&i?.({id:u,event:p,data:d}),u=void 0,d=``,f=0,p=void 0,t=n+1,n=e.indexOf(`
6
- `,t);continue}let r=e.charCodeAt(t);if(bg(e,t,r)){let r=e.charCodeAt(t+5)===_g?t+6:t+5,o=e.slice(r,n);if(f===0&&e.charCodeAt(n+1)===hg){u!==void 0&&a?.(u),i?.({id:u,event:p,data:o}),u=void 0,d=``,p=void 0,t=n+2,n=e.indexOf(`
7
- `,t);continue}d=f===0?o:`${d}\n${o}`,f++}else xg(e,t,r)?p=e.slice(e.charCodeAt(t+6)===_g?t+7:t+6,n)||void 0:C(e,t,n);t=n+1,n=e.indexOf(`
8
- `,t)}return e.slice(t)}for(;t<e.length;){let n=e.indexOf(`\r`,t),r=e.indexOf(`
9
- `,t),i=-1;if(n!==-1&&r!==-1?i=n<r?n:r:n===-1?r!==-1&&(i=r):i=n===e.length-1?-1:n,i===-1)break;C(e,t,i),t=i+1,e.charCodeAt(t-1)===gg&&e.charCodeAt(t)===hg&&t++}return e.slice(t)}function C(e,t,r){if(t===r){T();return}let i=e.charCodeAt(t);if(bg(e,t,i)){let n=e.charCodeAt(t+5)===_g?t+6:t+5,i=e.slice(n,r);d=f===0?i:`${d}\n${i}`,f++;return}if(xg(e,t,i)){p=e.slice(e.charCodeAt(t+6)===_g?t+7:t+6,r)||void 0;return}if(i===105&&e.charCodeAt(t+1)===100&&e.charCodeAt(t+2)===58){let n=e.slice(e.charCodeAt(t+3)===_g?t+4:t+3,r);n.includes(`\0`)||(u=n);return}if(i===58){if(n){let i=e.slice(t,r);n(i.slice(e.charCodeAt(t+1)===_g?2:1))}return}let a=e.slice(t,r),o=a.indexOf(`:`);if(o===-1){w(a,``,a);return}let s=a.slice(0,o),c=a.charCodeAt(o+1)===_g?2:1;w(s,a.slice(o+c),a)}function w(e,t,n){switch(e){case`event`:p=t||void 0;break;case`data`:d=f===0?t:`${d}\n${t}`,f++;break;case`id`:t.includes(`\0`)||(u=t);break;case`retry`:/^\d+$/.test(t)?o?.(parseInt(t,10)):r?.(new mg(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:n}));break;default:r?.(new mg(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:`unknown-field`,field:e,value:t,line:n}))}}function T(){u!==void 0&&a?.(u),f>0&&i?.({id:u,event:p,data:d}),u=void 0,d=``,f=0,p=void 0}function E(e={}){if(e.consume&&s.length>0){let e=s.join(``);C(e,0,e.length)}l=!0,u=void 0,d=``,f=0,p=void 0,s.length=0,c=0,m=!1,h=!1,g=!1}return{feed:_,reset:E}}function bg(e,t,n){return n===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function xg(e,t,n){return n===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}function Sg(e,t){let n=1;for(;n<e.length&&n<t.length;){if(e.charCodeAt(n)!==t.charCodeAt(n))return!1;n++}return e.length<=t.length||e.charCodeAt(t.length)===58}var Cg=104857600,wg=class extends EventTarget{static CONNECTING=0;static OPEN=1;static CLOSED=2;CONNECTING=0;OPEN=1;CLOSED=2;get readyState(){return this.#e}get url(){return this.#t.href}get withCredentials(){return this.#r}get onerror(){return this.#u}set onerror(e){this.#u&&this.removeEventListener(`error`,this.#u),this.#u=e,e&&this.addEventListener(`error`,e)}get onmessage(){return this.#d}set onmessage(e){this.#d&&this.removeEventListener(`message`,this.#d),this.#d=e,e&&this.addEventListener(`message`,e)}get onopen(){return this.#f}set onopen(e){this.#f&&this.removeEventListener(`open`,this.#f),this.#f=e,e&&this.addEventListener(`open`,e)}addEventListener(e,t,n){let r=t;super.addEventListener(e,r,n)}removeEventListener(e,t,n){let r=t;super.removeEventListener(e,r,n)}constructor(e,t){super();try{if(e instanceof URL)this.#t=e;else if(typeof e==`string`)this.#t=new URL(e,Eg());else throw Error(`Invalid URL`)}catch{throw dg(`An invalid or illegal string was specified`)}this.#l=yg({maxBufferSize:t?.maxBufferSize??Cg,onEvent:this.#v,onError:this.#b,onId:this.#_,onRetry:this.#y}),this.#e=this.CONNECTING,this.#a=3e3,this.#i=t?.fetch??globalThis.fetch,this.#r=t?.withCredentials??!1,this.#p()}close(){this.#o&&clearTimeout(this.#o),this.#e!==this.CLOSED&&(this.#c&&this.#c.abort(),this.#e=this.CLOSED,this.#c=void 0)}#e;#t;#n;#r;#i;#a;#o;#s=null;#c;#l;#u=null;#d=null;#f=null;#p(){this.#e=this.CONNECTING,this.#c=new AbortController;let e=this.#i;e(this.#t,this.#g()).then(this.#m).catch(this.#h)}#m=async e=>{this.#l.reset();let{body:t,redirected:n,status:r,headers:i}=e;if(r===204){this.#x(`Server sent HTTP 204, not reconnecting`,204),this.close();return}if(this.#n=n?new URL(e.url):void 0,r!==200){this.#x(`Non-200 status code (${r})`,r);return}if(!(i.get(`content-type`)||``).startsWith(`text/event-stream`)){this.#x(`Invalid content type, expected "text/event-stream"`,r);return}if(this.#e===this.CLOSED)return;this.#e=this.OPEN;let a=new Event(`open`);if(this.dispatchEvent(a),typeof t!=`object`||!t||!(`getReader`in t)){this.#x(`Invalid response body, expected a web ReadableStream`,r),this.close();return}let o=new TextDecoder,s=t.getReader(),c=!0;do{let{done:e,value:t}=await s.read();if(this.#e===this.CLOSED){c=!1;break}t&&this.#l.feed(o.decode(t,{stream:!e})),e&&(c=!1,this.#l.reset(),this.#S())}while(c)};#h=e=>{this.#c=void 0,e.name!==`AbortError`&&e.type!==`aborted`&&this.#S(fg(e))};#g(){let e={mode:`cors`,redirect:`follow`,headers:{Accept:`text/event-stream`,...this.#s?{"Last-Event-ID":this.#s}:void 0},cache:`no-store`,signal:this.#c?.signal};return`window`in globalThis&&(e.credentials=this.withCredentials?`include`:`same-origin`),e}#_=e=>{this.#s=e};#v=e=>{let t=this.#n?this.#n.origin:this.#t.origin,n=this.#s??``,r=new MessageEvent(e.event||`message`,{data:e.data,origin:t,lastEventId:n});r.origin!==t&&Dg(r,`origin`,t),r.lastEventId!==n&&Dg(r,`lastEventId`,n),this.dispatchEvent(r)};#y=e=>{this.#a=e};#b=e=>{e.type===`max-buffer-size-exceeded`&&(this.close(),this.#x(e.message))};#x(e,t){this.#e!==this.CLOSED&&(this.#e=this.CLOSED);let n=new ug(`error`,{code:t,message:e});this.dispatchEvent(n)}#S(e,t){if(this.#e===this.CLOSED)return;this.#e=this.CONNECTING;let n=new ug(`error`,{code:t,message:e});this.dispatchEvent(n);let r=setTimeout(this.#C,this.#a);typeof r==`object`&&r&&`unref`in r&&r.unref(),this.#o=r}#C=()=>{this.#o=void 0,this.#e===this.CONNECTING&&this.#p()}};Object.defineProperty(wg,"name",{value:`EventSource`}),Object.defineProperty(wg,Symbol.for(`eventsource.supports-fetch-override`),{value:!0,writable:!1,configurable:!1,enumerable:!1});var Tg=wg;function Eg(){let e=`document`in globalThis?globalThis.document:void 0;return e&&typeof e==`object`&&`baseURI`in e&&typeof e.baseURI==`string`?e.baseURI:void 0}function Dg(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0})}var Og=I.check(q(1),U(256)),kg=bo.check(Oa(),ao(0)),Ag=V([F({agentId:Og,sessionId:Og,title:I.check(U(4096)),triggerId:H(Og),createdAt:kg,lastActivityAt:kg,settledAt:H(kg),visitedAt:H(kg),state:W([`needs_you`,`running`,`errored`,`done`])}),F({agentId:Og,sessionId:Og,state:K(`unavailable`)})]),jg=F({runId:Og,nodeId:Og,iteration:Og}),Mg=F({kind:K(`workflow-review`),key:jg,installationId:Og,workflowId:Ki(Og),workflowTitle:I,reviewTitle:I,reviewers:W([`runner`,`owners`]),show:G($a),choices:H(G(Og)),openedAt:kg,expiresAt:kg,state:W([`pending`,`answered`,`delivered`,`timed_out`,`closed`])}),Ng=V([Ag,Mg]),Pg=V([Ng,F({agentId:Og,sessionId:Og,deleted:K(!0)})]);function Fg(e,t){return`${e}\u0000${t}`}function Ig(e){return`kind`in e?JSON.stringify([e.kind,e.installationId,e.key.runId,e.key.nodeId,e.key.iteration]):Fg(e.agentId,e.sessionId)}var Lg=I.pipe(B(q(1),U(256))),Rg=F({kind:K(`seller-closed`),dispositionId:I.pipe(B(q(1),U(1024))),sellerAccountId:Lg,buyerAccountId:Lg,appId:Lg,releaseIds:Ui([Lg]),displayName:Lg,sellerName:Lg,requestId:Lg}),zg={BACKGROUND:{name:`BACKGROUND`,operations:{admit:{cap:`app.background.admit`,requires:[],effect:`read`}}},GIT:{name:`GIT`,operations:{create:{cap:`app.git.create`,requires:[`git.repository`],effect:`write`},fork:{cap:`app.git.fork`,requires:[`git.repository`],effect:`write`},read:{cap:`app.git.read`,requires:[`git.repository`],effect:`read`},write:{cap:`app.git.write`,requires:[`git.repository`],effect:`write`},exchange:{cap:`app.git.exchange`,requires:[`git.repository`],effect:`write`}}},EVENTS:{name:`EVENTS`,operations:{emit:{cap:`app.events.emit`,requires:[`app.events.emit`],effect:`write`}}},APPS:{name:`APPS`,operations:{register:{cap:`app.register`,requires:[`git.repository`],effect:`write`},repository:{cap:`app.catalog.read`,requires:[`git.repository`],effect:`read`},build:{cap:`app.build`,requires:[`git.repository`,`computer.execute`],effect:`write`},buildStatus:{cap:`app.build`,requires:[`git.repository`,`computer.execute`],effect:`read`},select:{cap:`app.select`,requires:[`git.repository`,`computer.execute`],effect:`write`},catalog:{cap:`app.catalog.read`,requires:[`team.workbenchHost`],effect:`read`},fork:{cap:`app.fork`,requires:[`git.repository`],effect:`write`}}},WORKFLOWS:{name:`WORKFLOWS`,operations:{catalog:{cap:`app.workflow.read`,requires:[`workflow.run`],effect:`read`},runGraph:{cap:`app.workflow.run`,requires:[`workflow.run`],effect:`write`},armSchedule:{cap:`app.workflow.run`,requires:[`workflow.run`,`workflow.arm`],effect:`write`},disarmSchedule:{cap:`app.workflow.run`,requires:[`workflow.run`,`workflow.arm`],effect:`write`},pauseSchedule:{cap:`app.workflow.run`,requires:[`workflow.run`,`workflow.arm`],effect:`write`},resumeSchedule:{cap:`app.workflow.run`,requires:[`workflow.run`,`workflow.arm`],effect:`write`},schedules:{cap:`app.workflow.read`,requires:[`workflow.run`],effect:`read`},armEventTrigger:{cap:`app.workflow.run`,requires:[`workflow.run`,`workflow.arm`],effect:`write`},disarmEventTrigger:{cap:`app.workflow.run`,requires:[`workflow.run`,`workflow.arm`],effect:`write`},eventTriggers:{cap:`app.workflow.read`,requires:[`workflow.run`],effect:`read`},cancel:{cap:`app.workflow.run`,requires:[`workflow.run`],effect:`write`},answerReview:{cap:`app.workflow.run`,requires:[`workflow.run`],effect:`write`},graphStatus:{cap:`app.workflow.read`,requires:[`workflow.run`],effect:`read`},runs:{cap:`app.workflow.read`,requires:[`workflow.run`],effect:`read`}}},APP_STORAGE:{name:`APP_STORAGE`,operations:{read:{cap:`app.storage.read`,requires:[`app.storage`],effect:`read`},write:{cap:`app.storage.write`,requires:[`app.storage`],effect:`write`},reset:{cap:`app.storage.write`,requires:[`app.storage`],effect:`write`}}},MEDIA:{name:`MEDIA`,operations:{models:{cap:`app.media.read`,requires:[`media.generation`],effect:`read`},generate:{cap:`app.media.generate`,requires:[`media.generation`,`computer.writeFile`],effect:`write`}}},COMPUTER:{name:`COMPUTER`,operations:{list:{cap:`app.computer.read`,requires:[`computer.list`],effect:`read`},read:{cap:`app.computer.read`,requires:[`computer.readFile`],effect:`read`},ports:{cap:`app.computer.read`,requires:[`computer.execute`],effect:`read`},processes:{cap:`app.computer.read`,requires:[`computer.execute`],effect:`read`},gitChanges:{cap:`app.computer.read`,requires:[`computer.readFile`],effect:`read`},write:{cap:`app.computer.write`,requires:[`computer.writeFile`],effect:`write`},mkdir:{cap:`app.computer.write`,requires:[`computer.writeFile`],effect:`write`},move:{cap:`app.computer.write`,requires:[`computer.writeFile`],effect:`write`},preview:{cap:`app.computer.exec`,requires:[`computer.execute`],effect:`write`},processKill:{cap:`app.computer.exec`,requires:[`computer.execute`],effect:`write`},processStart:{cap:`app.computer.exec`,requires:[`computer.execute`],effect:`write`},exec:{cap:`app.computer.exec`,requires:[`computer.execute`],effect:`write`}}},INBOX:{name:`INBOX`,operations:{page:{cap:`inbox.read`,requires:[`agent.read`],effect:`read`},visit:{cap:`inbox.visit`,requires:[`agent.read`],effect:`write`}}},AGENTS:{name:`AGENTS`,operations:{list:{cap:`agent.list`,requires:[`agent.list`],effect:`read`},send:{cap:`agent.send`,requires:[`agent.send`],effect:`write`},schedules:{cap:`agent.read`,requires:[`agent.read`],effect:`read`},pauseSchedule:{cap:`agent.manage`,requires:[`agent.manage`],effect:`write`},resumeSchedule:{cap:`agent.manage`,requires:[`agent.manage`],effect:`write`},deleteSchedule:{cap:`agent.manage`,requires:[`agent.manage`],effect:`write`}}}},Bg=[`dashboard`,`inbox`,`files`,`media`,`sessions`,`terminal`],Vg=`approvals,agent.list,agent.manage,agent.rename,agent.avatar,agent.instructions,agent.toolPolicy,agent.read,agent.send,computer.list,computer.readFile,computer.writeFile,computer.execute,llm.generation,media.generation,media.share,games:servers,git.repository,apps.open,apps.call,app.storage,app.events.emit,team.workbenchHost,marketplace.browse,marketplace.purchase,workflow.run,workflow.publish,workflow.arm,world,channels.read,channels.personal.manage`.split(`,`),Hg=[`file.open`],Ug=[`team`,`member`],Wg=Object.freeze({capabilities:[],handlers:[],roles:[]}),Gg=Object.freeze([`owner`,`admin`,`member`]),Kg=ti(()=>Wr(Gg));function qg(e,t){if(t===void 0)return!0;let n=e?.methods[t.method];return n?.effect===`write`&&Object.values(e?.methods??{}).every(e=>e.effect!==`write`||e.requires.every(e=>n.requires.includes(e)))}var Jg=Object.freeze({intrinsic:[`constructor`,`toString`,`valueOf`,`hasOwnProperty`,`isPrototypeOf`,`propertyIsEnumerable`,`toLocaleString`],rpc:[`then`,`dup`,`connect`,`id`,`name`],instance:[`ctx`,`env`],lifecycle:[`gill`,`onGitPush`,`syncRefused`,`authorizeGitPush`,`fetch`,`alarm`,`queue`,`scheduled`,`tail`,`trace`,`email`,`test`,`tailStream`,`webSocketMessage`,`webSocketClose`,`webSocketError`]}),Yg=St().check(mr(1),mi(256)),Xg=Ie(`kind`,[Zt({kind:i(`team`),teamId:Yg}),Zt({kind:i(`standalone`),tenant:Yg})]),Zg=Un({kind:i(`member`),memberId:Yg}),Qg=Un({kind:i(`agent`),agentId:Yg}),$g=Un({kind:i(`team-key`),keyId:Yg}),e_=Ie(`kind`,[Zg,Qg,$g]),t_=Un({workflowId:Yg,runId:Yg,nodeId:Yg,armedBy:e_}),n_=gt(()=>Zt({method:St().check(Pn(e=>c_(e))),seal:St().check(Or(/^[A-Za-z0-9_-]{43}$/u))})),r_=Un({scope:Xg,computerId:Ft(Yg),actor:e_,backgroundLane:_n(St().check(mr(8),mi(263))),backgroundOrigin:_n(n_),role:_n(Kg),soleMember:_n(i(!0)),workflow:_n(t_),idempotencyKey:_n(St().check(mr(1),mi(128)))}),i_=Ie(`kind`,[Zt(Zg.shape),Zt(Qg.shape),Zt($g.shape)]),a_=Zt({...r_.shape,actor:i_,workflow:_n(Zt({...t_.shape,armedBy:i_}))}),o_=(e,t=!1)=>s_((t?a_:r_).parse(e));function s_(e){if(e.soleMember!==void 0&&(e.actor.kind!==`member`||e.workflow!==void 0))throw Error(`Only a member's own call can be its Team's sole member`);if(e.backgroundLane===void 0!=(e.backgroundOrigin===void 0))throw Error(`Background lane and origin must be attested together`);if(e.backgroundLane!==void 0&&(e.actor.kind!==`member`||e.workflow!==void 0||e.backgroundLane!==`member:${e.actor.memberId}`))throw Error(`Background lane must name an ordinary member`);return e}var c_=e=>e.length<=80&&/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*$/.test(e)&&!Object.values(Jg).flat().some(t=>t===e),l_=I.check(L(c_));function u_(e){return typeof e==`object`&&!!e}function d_(e,t=0){if(t>16)return!1;if(u_(e)){for(let n of Object.values(e))if(!d_(n,t+1))return!1}return!0}var f_=Va.pipe(B(L(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=2e4&&d_(e),{message:`App API schema exceeds its byte or depth bound`}))),p_=I.check(q(1),U(128)),m_=F({description:I.pipe(B(q(1)),B(U(1e3))),input:f_,output:f_,pending:z(K(!0)),hidden:z(K(!0)),present:z(F({verb:I.check(q(1),U(32))})),effect:W([`read`,`write`,`external`]),requires:G(W(Vg)).pipe(B(L(e=>new Set(e).size===e.length)))}),h_=F({methods:_a(I,m_).pipe(B(L(e=>Object.keys(e).every(Fa(l_)),{message:`Invalid App API method name`})),B(L(e=>Object.keys(e).length<=64)),B(L(e=>{let t=Object.keys(e);return t.every(e=>!t.some(t=>t.startsWith(`${e}.`)))},{message:`App API method name is also a method group`}))),toolFamily:H(F({name:l_.check(L(e=>!e.includes(`.`))),list:l_,call:l_})),events:H(_a(I,F({description:I.check(q(1),U(1e3)),payload:f_})).check(L(e=>Object.keys(e).every(Fa(p_)),{message:`Invalid App API event name`}),L(e=>Object.keys(e).length<=64)))}).pipe(B(L(e=>{if(e.toolFamily===void 0)return!0;let{name:t,list:n,call:r}=e.toolFamily,i=e.methods[n],a=e.methods[r];return i?.effect===`read`&&a!==void 0&&a.effect!==`external`&&a.hidden!==!0&&!Object.keys(e.methods).some(e=>e.split(`.`)[0]===t)},{message:`Tool family must reference declared callable methods in a distinct namespace`})),B(L(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=256e3,{message:`App API exceeds its total byte bound`}))),g_=e=>new Set(e).size===e.length;function __(e,t){let n=Object.keys(t);for(let e of n)R(l_)(e);return{declaration:F({name:K(e),operations:G(W(n)).pipe(B(q(1)),B(U(n.length)),B(L(g_)))}),shard:F({name:K(e),operations:G(V(Object.entries(t).map(([e,t])=>F({name:K(e),cap:K(t.cap)})))).pipe(B(q(1)),B(U(n.length)),B(L(e=>g_(e.map(e=>e.name)),{message:`App backend operation repeated`})))})}}var v_=Object.values(zg).map(e=>__(e.name,e.operations)),y_=v_.length,b_=G(V(v_.map(e=>e.declaration))).pipe(B(U(y_)),B(L(e=>g_(e.map(e=>e.name)))));G(V(v_.map(e=>e.shard))).pipe(B(U(y_)),B(L(e=>g_(e.map(e=>e.name)))));var x_=new Map(Object.entries(zg).map(([e,t])=>[e,new Map(Object.entries(t.operations))]));function S_(e,t){return x_.get(e)?.get(t)}var C_=W(Bg),w_=W(Vg),T_=W(Hg),E_={message:`App declaration entries must be unique`},D_=e=>new Set(e).size===e.length,O_=new Set([`super+k`,`meta+k`,`cmd+k`,`mod+k`,`ctrl+k`,`control+k`]),k_=I.pipe(B(U(256)),B(L(e=>e.trim().length>0,{message:`Declared command text must not be blank`}))),A_={order:z(oo)},j_=F(A_),M_=F({id:k_.pipe(B(L(e=>!e.includes(`:`),{message:`Declared command IDs are namespace-local`}))),title:k_,category:k_,description:z(I.pipe(B(U(1024)))),sigil:z(k_.pipe(B(U(64)))),projections:z(F({bindings:z(F({...A_,values:G(k_).pipe(B(U(16)),B(L(e=>!e.some(e=>O_.has(e.trim().toLowerCase())),{message:`Apps cannot bind the reserved leader chord`})))})),agent:z(F({...A_,keybind:z(I)})),help:z(j_),menu:z(j_),palette:z(j_),slash:z(F({...A_,aliases:G(k_).pipe(B(U(16)))}))}))}),N_=e=>D_(e.map(e=>e.id))&&D_(e.flatMap(e=>e.projections?.slash?.aliases??[])),P_=e=>D_(e.map(e=>e.id)),F_=I.check(ca(/^[a-z][a-z0-9.-]{0,63}$/)),I_=F({key:F_,scopes:G(W(Ug)).check(q(1),L(D_,E_)),maxBytes:oo.check(po({minimum:1,maximum:65536}))}),L_=wo()([I_],([e])=>(t,n,r)=>Ta(e)(t,{...r,onExcessProperty:`error`}),{toCodecJson:()=>new Ca(I_.ast,Pa())}),R_=F({appId:I.check(q(1),U(128)),methods:G(l_).check(q(1),U(16),L(D_,E_))}),z_=wo()([R_],([e])=>(t,n,r)=>Ta(e)(t,{...r,onExcessProperty:`error`}),{toCodecJson:()=>new Ca(R_.ast,Pa())}),B_=G(z_).check(q(1),U(16),L(e=>D_(e.map(e=>e.appId)),E_)),V_=e=>F({api:H(h_),displayName:z(I.pipe(B(q(1)),B(U(64)))),capabilities:G(w_).pipe(B(L(D_,E_))),calls:H(B_),guidance:z(I.pipe(B(q(1)),B(U(12e3)))),handlers:G(T_).pipe(B(L(D_,E_))),receives:H(G(K(`git.push`)).check(U(1),L(D_,E_))),icon:H(I.pipe(B(q(1)),B(U(80)))),roles:G(C_).pipe(B(L(D_,E_))),storage:H(G(L_).check(U(16),L(e=>D_(e.map(e=>e.key)),E_))),commands:z(G(M_).pipe(B(U(64)),B(L(N_,{message:`Declared command IDs and slash aliases must be unique`})))),gills:z(G(e).pipe(B(U(16)),B(L(P_,{message:`Declared Gill IDs must be unique`})))),backend:z(F({bindings:b_,sync:H(F({method:l_}))}))}).pipe(B(L(e=>e.calls===void 0||e.capabilities.includes(`apps.call`),{message:`App calls require apps.call`})),B(L(e=>e.backend?.bindings.every(e=>e.name!==`BACKGROUND`)??!0,{message:`BACKGROUND is host-minted and cannot be declared by an App`})),B(L(e=>qg(e.api,e.backend?.sync),{message:`Background continuation must be a declared write covering all write requirements`})),B(L(e=>!(e.receives?.includes(`git.push`)??!1)||e.capabilities.includes(`git.repository`),{message:`Git push reception requires git.repository`})),B(L(e=>e.backend?.bindings.every(t=>t.operations.every(n=>S_(t.name,n)?.requires.every(t=>e.capabilities.includes(t))===!0))??!0,{message:`Backend bindings require declared App capabilities`})),B(L(e=>!e.backend?.bindings.some(e=>e.name===`APP_STORAGE`)||(e.storage?.length??0)>0,{message:`App storage bindings require declared keys`})),B(L(e=>Object.values(e.api?.methods??{}).every(t=>t.requires.every(t=>e.capabilities.includes(t))),{message:`App API requires capabilities outside the App declaration`})));V_(Sn);var H_=V_(zn);function U_(e){return/^app_[a-z0-9]{1,63}$/u.test(e)}function W_(e){return/^rel_[a-z0-9]{1,63}$/u.test(e)}function G_(e){return/^ps_[a-z0-9]{1,63}$/u.test(e)}function K_(e){return/^artifact:[a-z0-9](?:[a-z0-9._-]{0,126}[a-z0-9])?$/u.test(e)}function q_(e){return/^idem_[a-z0-9](?:[a-z0-9_-]{0,126}[a-z0-9])?$/u.test(e)}function J_(e){return/^git:[0-9a-f]{40}$/u.test(e)}function Y_(e){return/^sha256:[0-9a-f]{64}$/u.test(e)}function X_(e){return/^\/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u.test(e)}var Z_=no({family:`app-release`,version:1,kinds:{transition:{prefix:`app_transition`},surface:{prefix:`ps`},erasure:{prefix:`app_erasure`}}}),Q_=Z_.transition;Z_.surface,Z_.erasure;var $_=I.pipe(Co(U_)),ev=I.pipe(Co(W_)),tv=I.pipe(Co(G_)),nv=I.pipe(Co(K_)),rv=I.pipe(Co(q_)),iv=I.pipe(Co(J_)),av=I.pipe(Co(Y_)),ov=I.pipe(Co(X_)),sv=F({byteLength:bo,copy:Vi(Function)}).pipe(Co(e=>e.byteLength>=0)),cv=F({appId:$_}),lv=F({sourceRevision:iv,sourceTreeDigest:av,buildRecipeDigest:av}),uv=F({artifactRef:nv,artifactDigest:av,provenance:lv}),dv=F({releaseId:ev,appId:$_,artifact:uv}),fv=F({publicSurfaceId:tv,appId:$_,stableRoute:ov}),pv=I.pipe(B(q(1)),B(U(256))),mv=F({...fv.fields,publisher:F({kind:W([`customer`,`platform`]),teamId:pv,userId:pv,requestKey:pv})}),hv=W([`text/html; charset=utf-8`,`application/vnd.fungi.app-backend+json`,`application/vnd.fungi.app-assets+json`,`application/vnd.fungi.app+json`]),gv=F({artifactRef:nv,digest:av,mediaType:W([`text/html; charset=utf-8`,`application/vnd.fungi.app-backend+json`,`application/vnd.fungi.app-assets+json`]),version:I.pipe(B(q(1))),byteLength:bo.pipe(B(Oa()),B(_o(0)),B(L(Number.isSafeInteger)))}),_v=F({runtime:F({kind:K(`durable-facet`),stateSchema:bo.pipe(B(Oa()),B(_o(0)))}),compatibilityDate:I.pipe(B(ca(/^\d{4}-\d{2}-\d{2}$/))),exportName:I.pipe(B(q(1)))}),vv=F({format:K(`fungi-app-v1`),ui:Ki(gv),backend:Ki(F({artifact:gv,profile:_v})),declaration:H_.pipe(so(Ci(Wg)))}),yv=F({kind:K(`verified`),digest:av,mediaType:hv,bytes:sv,byteLength:bo}),bv=V([yv,F({kind:K(`unavailable`)}),F({kind:K(`missing`)}),F({kind:K(`digest-mismatch`),actualDigest:av})]),xv=V([F({kind:K(`found`),app:cv}),F({kind:K(`absent`)})]),Sv=V([F({kind:K(`created`),app:cv}),F({kind:K(`existing`),app:cv})]),Cv=V([F({kind:K(`found`),release:dv}),F({kind:K(`absent`)})]),wv=V([F({kind:K(`created`),release:dv}),F({kind:K(`existing`),release:dv})]),Tv=V([F({kind:K(`found`),surface:fv}),F({kind:K(`absent`)})]),Ev=V([F({kind:K(`created`),surface:fv}),F({kind:K(`existing`),surface:fv}),F({kind:K(`conflict`)})]),Dv=V([F({kind:K(`verified`),digest:av,mediaType:K(`application/vnd.fungi.app+json`),description:vv}),F({kind:K(`unverified`)})]),Ov=V([F({kind:K(`active`)}),F({kind:K(`revoked`)})]),kv=V([F({kind:K(`promotion`),publicSurfaceId:tv,releaseId:ev,idempotencyKey:rv}),F({kind:K(`rollback`),publicSurfaceId:tv,releaseId:ev,idempotencyKey:rv}),F({kind:K(`revocation`),releaseId:ev,idempotencyKey:rv})]),Av=ha(e=>Q_.schema.safeParse(e).success),jv=F({transition:kv,transitionId:Av}),Mv=V([F({kind:K(`none`)}),F({kind:K(`selected`),releaseId:ev})]),Nv=V([F({kind:K(`found`),release:dv,verification:Dv,revocation:Ov}),F({kind:K(`absent`)})]);V([F({kind:K(`found`),surface:fv,selection:Mv}),F({kind:K(`absent`)})]);var Pv=V([F({kind:K(`absent`)}),F({kind:K(`found`),receipt:jv}),F({kind:K(`conflict`)})]),Fv=V([F({kind:K(`created`),receipt:jv}),F({kind:K(`existing`),receipt:jv}),F({kind:K(`conflict`)}),F({kind:K(`identity-collision`)}),F({kind:K(`lifecycle-conflict`)})]),Iv=F({kind:K(`recorded`)}),Lv=F({kind:K(`unavailable`)});function Rv(e){return V([F({kind:K(`success`),value:e}),F({kind:K(`failure`),failure:Lv})])}var zv=Rv(xv),Bv=Rv(Sv),Vv=Rv(Cv),Hv=Rv(wv),Uv=Rv(Tv),Wv=Rv(Ev),Gv=Rv(Nv),Kv=Rv(Iv),qv=Rv(Pv),Jv=Rv(Fv);Qi($_,{onExcessProperty:`error`}),Qi(ev,{onExcessProperty:`error`}),Qi(tv,{onExcessProperty:`error`}),Qi(nv,{onExcessProperty:`error`}),Qi(rv,{onExcessProperty:`error`}),Qi(iv,{onExcessProperty:`error`}),Qi(av,{onExcessProperty:`error`}),Qi(ov,{onExcessProperty:`error`}),Qi(Av,{onExcessProperty:`error`}),ea(bv,{onExcessProperty:`error`}),Qi(cv,{onExcessProperty:`error`}),Qi(dv,{onExcessProperty:`error`}),Qi(fv,{onExcessProperty:`error`}),Qi(mv,{onExcessProperty:`error`}),Qi(zv,{onExcessProperty:`error`}),Qi(Bv,{onExcessProperty:`error`}),Qi(Vv,{onExcessProperty:`error`}),Qi(Hv,{onExcessProperty:`error`}),Qi(Uv,{onExcessProperty:`error`}),Qi(Wv,{onExcessProperty:`error`}),Qi(kv,{onExcessProperty:`error`}),Qi(Gv,{onExcessProperty:`error`}),Qi(Kv,{onExcessProperty:`error`}),Qi(qv,{onExcessProperty:`error`}),Qi(Jv,{onExcessProperty:`error`});var Yv=I.pipe(B(q(1)),B(U(256))),Xv=I.pipe(B(ca(/\S/u)),B(U(1e3)));F({dispositionId:Yv,requestId:Yv,operatorId:Yv,reason:Xv,action:V([F({kind:K(`retain-detached`)}),F({kind:K(`revoke-with-notice`)})])});var Zv=F({dispositionId:Yv,appId:$_,displayName:I.pipe(B(q(1)),B(U(64))),releaseIds:G(ev).pipe(B(q(1)),B(U(1e4))),reason:Xv}),Qv=F({disposition_id:Yv,app_id:$_,release_ids_json:I,artifact_roots_json:I,created_at:bo,state:W([`pending`,`retaining`,`retained`,`revoking`,`revoked`]),request_id:Ki(Yv),reason:Ki(Xv),completed_at:Ki(bo)});F({...Qv.fields,releaseIds:G(ev).pipe(B(U(1e4)))}),pa(G(ev).pipe(B(U(1e4)))),pa(G(nv).pipe(B(U(1e4)))),[`CREATE TABLE app_release_artifact_dispositions(disposition_id TEXT PRIMARY KEY, app_id TEXT NOT NULL UNIQUE REFERENCES app_release_apps(app_id),
10
- release_ids_json TEXT NOT NULL CHECK(json_valid(release_ids_json)), artifact_roots_json TEXT NOT NULL CHECK(json_valid(artifact_roots_json)),
11
- created_at INTEGER NOT NULL,state TEXT NOT NULL CHECK(state IN ('pending','retaining','retained','revoking','revoked')),
12
- request_id TEXT,reason TEXT,completed_at INTEGER,
13
- CHECK((state='pending' AND request_id IS NULL AND reason IS NULL) OR (state<>'pending' AND request_id IS NOT NULL AND length(request_id) BETWEEN 1 AND 256 AND reason IS NOT NULL AND length(trim(reason)) BETWEEN 1 AND 1000)),
14
- CHECK((state IN ('retained','revoked'))=(completed_at IS NOT NULL))) STRICT;`,`CREATE TABLE app_release_artifact_notice_recipients(recipient_id INTEGER PRIMARY KEY,disposition_id TEXT NOT NULL REFERENCES app_release_artifact_dispositions(disposition_id),
15
- buyer_team_id TEXT CHECK(buyer_team_id IS NULL OR length(buyer_team_id) BETWEEN 1 AND 256),receipt TEXT CHECK(receipt IS NULL OR length(receipt) BETWEEN 1 AND 256),
16
- erased_by TEXT,erased_at INTEGER,
17
- CHECK((erased_by IS NULL)=(erased_at IS NULL)),
18
- CHECK(erased_by IS NULL OR length(erased_by) BETWEEN 1 AND 256),
19
- CHECK(receipt IS NULL OR erased_at IS NULL),
20
- CHECK(buyer_team_id IS NOT NULL OR erased_at IS NOT NULL),
21
- UNIQUE(disposition_id,buyer_team_id)) STRICT;`,`CREATE INDEX app_release_artifact_dispositions_pending ON app_release_artifact_dispositions(state,disposition_id);`,`CREATE TABLE app_release_artifact_disposition_steps(step_id INTEGER PRIMARY KEY,disposition_id TEXT NOT NULL REFERENCES app_release_artifact_dispositions(disposition_id),
22
- phase TEXT NOT NULL CHECK(phase IN ('prepared','completed')),operator_id TEXT NOT NULL,recorded_at INTEGER NOT NULL) STRICT;`,`CREATE INDEX app_release_artifact_disposition_steps_by_action ON app_release_artifact_disposition_steps(disposition_id,phase);`].map(e=>e.replaceAll(`
23
- `,` `)).join(`
24
- `);var $v=bo.pipe(B(Oa()),B(ao(0))),ey=F({items:G(Ng),next:Ki(I),cursor:$v});Yr({visited:Si(!0)});var ty=R(ey),ny=R(pa(F({kind:K(`rows`),from:$v,to:$v,items:G(Pg),more:vo})));function ry(e){let t=new Map,n=0,r=!1,i,a=0,o=n=>{r||e.onChange({items:[...t.values()],status:n})},s=e=>{for(let n of e){let e=Ig(n);`deleted`in n?t.delete(e):t.set(e,n)}},c=()=>{i?.close();let t=++a,u=e.openEvents(`${e.baseUrl}/inbox/events?after=${String(n)}`);i=u;let d=!1;u.addEventListener(`error`,()=>{r||t!==a||(d=!0,ss(`inbox.observe`,Error(`Member inbox stream disconnected`)),o(`error`))}),u.addEventListener(`open`,()=>{r||t!==a||!d||l()}),u.addEventListener(`rows`,e=>{if(r||t!==a)return;let i;try{i=ny(e.data)}catch(e){ss(`inbox.decode-event`,e),o(`loading`),c();return}if(i.from!==n){o(`loading`),c();return}s(i.items),n=i.to,o(`live`)}),u.addEventListener(`reset`,()=>{r||t!==a||l()})},l=async()=>{let l=++a;i?.close(),i=void 0,o(`loading`);try{t.clear();let i=null,u=!0;for(let t=0;t<5;t+=1){let t=i===null?``:`?after=${encodeURIComponent(i)}`,o=await e.fetch(`${e.baseUrl}/inbox${t}`,{cache:`no-store`});if(!o.ok)throw Error(`Inbox unavailable`);let c=ty(await o.json());if(r||l!==a)return;if(u&&(n=c.cursor),u=!1,s(c.items),i=c.next,i===null)break}o(`live`),c()}catch(e){if(r||l!==a)return;ss(`inbox.refresh`,e),o(`error`)}};return l(),Object.freeze({refresh:()=>r?Promise.resolve():l(),visit:async(t,n)=>{let r=await e.fetch(`${e.baseUrl}/inbox/visits`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({agentId:t,sessionId:n})});if(!r.ok&&r.status!==404)throw Error(`Visit was not recorded`)},close:()=>{r=!0,a+=1,i?.close()}})}var iy=R(F({items:G(V([F({...Zv.fields,reason:z(Zv.fields.reason),createdAt:$v}),F({...Rg.fields,createdAt:$v})])).pipe(B(U(100))),next:Ki(I.pipe(B(U(1024))))}),{onExcessProperty:`error`});async function ay(e,t=null){let n=new URL(`${e.baseUrl}/inbox/notices`);t!==null&&n.searchParams.set(`after`,t);let r=await e.fetch(n);if(!r.ok)throw Error(`Team notices unavailable`);return iy(await r.json())}var oy=vi({status:ii()}),sy=3,cy=/network ?(?:changed|error)|failed to fetch|load failed|network connection was lost/iu;function ly(e){let t=[];for(let n=e;n!==void 0&&t.length<5;n=n instanceof Error?n.cause:void 0)t.push(n);return t}function uy(e){return ly(e).some(e=>{if(e instanceof TypeError)return!0;if(e instanceof Y)return e.code===`HOST_FAILURE`&&e.retryable;let t=oy.safeParse(e);return t.success?t.data.status>=500:e instanceof Error&&cy.test(e.message)})}function dy(e,t){return e<sy&&uy(t)}function fy(e){return 250*2**e}function py(e,t){return t.status===`live`?t:{...t,data:t.data??e.data}}function my(e,t,n={}){return is({queryKey:e,...n,retry:dy,retryDelay:fy,staleTime:1/0,refetchOnMount:`always`,queryFn:yt({initialValue:{status:`loading`},refetchMode:`append`,reducer:py,streamFn:({signal:e})=>ia(aa(n=>fi(function*(){let r={status:`loading`},i=()=>{mo(n)};if(yield*ki(ci(()=>{e.addEventListener(`abort`,i,{once:!0})}),()=>ci(()=>{e.removeEventListener(`abort`,i)})),e.aborted){i();return}yield*ki(Xr({try:()=>Promise.resolve(t(e=>{r=py(r,e),co(n,r)},e)),catch:gy}),e=>ci(e))}).pipe(Qr(e=>eo(n,e))),{bufferSize:1,strategy:`sliding`}))})})}async function hy(e,t,n){if(!e)throw new Y(`No App connection`,{code:`DISCONNECTED`,retryable:!0});let r=await lg(e.capabilities),i=()=>{r.close().catch(e=>{ss(`inbox.query-close`,e)})};if(n.aborted)return i(),()=>void 0;let a=ry({baseUrl:r.baseUrl,fetch:r.fetch,openEvents:e=>{let t=new Tg(e,{fetch:(e,t)=>r.fetch(e,t)});return{addEventListener:(e,n)=>{t.addEventListener(e,t=>{e===`open`||e===`error`?n(new MessageEvent(e)):t instanceof MessageEvent&&n(new MessageEvent(e,{data:Fi().parse(t.data)}))})},close:()=>{t.close()}}},onChange:e=>{t(e.status===`live`?{status:`live`,data:e.items}:{status:e.status})}});return()=>{a.close(),i()}}function gy(e){return e instanceof Y?e:new Y(`App operation failed`,{cause:e,code:`HOST_FAILURE`,retryable:!1})}var _y=new WeakMap,vy={of(e,...t){return[e?.identity.surfaceId??null,e?.context.get().computerId??null,...t]}};function yy(e){let t={};return e&&_y.set(t,e),t}function by(){let e=new Xn({defaultOptions:{queries:{retry:!1,staleTime:3e4,refetchOnWindowFocus:!1},mutations:{retry:!1}}}),t=new Map;return e.getQueryCache().subscribe(n=>{let r=n.query;if(n.type===`removed`){t.get(r.queryHash)?.release(),t.delete(r.queryHash);return}let i=r.meta&&_y.get(r.meta),a=t.get(r.queryHash);if(a?.app===i||(a?.release(),t.delete(r.queryHash),!i))return;let o=()=>{queueMicrotask(()=>{e.getQueryCache().get(r.queryHash)===r&&t.get(r.queryHash)?.app===i&&e.resetQueries({predicate:e=>e===r})})},s=i.capabilities.subscribe(o);t.set(r.queryHash,{app:i,release:s}),a&&o()}),e}function xy(e,t,n,r){let i=e?.context.get().computerId;return Ut({queryKey:n,meta:yy(e),enabled:e!==null,retry:dy,retryDelay:fy,queryFn:async({signal:n})=>{try{if(!e)throw new Y(`No App connection`,{code:`DISCONNECTED`,retryable:!0});if(e.context.get().computerId!==i)throw new Y(`The selected Computer changed`,{code:`SELECTION_CHANGED`,retryable:!1});return await r(e.capabilities.require(t),n)}catch(e){throw gy(e)}}})}function Sy(e){mh(e?.context);let t=tn(),n=e?.context.get().computerId,r=(0,J.useMemo)(()=>vy.of(e,`member-inbox`),[e,n]),i=my(r,(0,J.useCallback)((t,r)=>{if(e?.context.get().computerId!==n)throw new Y(`The selected Computer changed`,{code:`SELECTION_CHANGED`,retryable:!1});return hy(e,t,r)},[e,n]),{enabled:e!==null,meta:yy(e)}),a=(0,J.useCallback)(()=>{t.invalidateQueries({queryKey:r,exact:!0})},[t,r]),o=(0,J.useCallback)(async(t,n)=>{if(!e)throw new Y(`No App connection`,{code:`DISCONNECTED`,retryable:!0});let r=await lg(e.capabilities);try{let e=await r.fetch(`${r.baseUrl}/inbox/visits`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({agentId:t,sessionId:n})});if(!e.ok&&e.status!==404)throw new Y(`Visit was not recorded`,{code:`HOST_FAILURE`,retryable:!0})}finally{await r.close()}},[e]);return{items:i.data?.data??[],status:i.isError?`error`:i.data?.status??`loading`,error:i.error,refresh:a,visit:o}}wo()([],()=>(e,t,n)=>Li({try:()=>o_(e,n.onExcessProperty===`error`),catch:()=>new Ha(t,e,n)}));var Cy={artifactRef:nv,digest:av,version:I.pipe(B(q(1))),byteLength:bo.pipe(B(Oa()),B(_o(0)),B(L(Number.isSafeInteger)))},wy=F({...Cy,mediaType:W([`text/html; charset=utf-8`,`application/vnd.fungi.app-assets+json`])}),Ty=F({...Cy,mediaType:K(`application/vnd.fungi.app-backend+json`)}),Ey={declaration:H(H_)},Dy=V([F({format:K(`fungi-app-v1`),ui:wy,backend:Ty,...Ey}),F({format:K(`fungi-app-v1`),ui:wy,...Ey}),F({format:K(`fungi-app-v1`),backend:Ty,...Ey})]).pipe(B(L(e=>e.declaration?.api===void 0||`backend`in e,{message:`An App API requires a backend`})));pa(Dy);var Oy=W([`invalid`,`undeclared_key`,`scope_not_declared`,`owner_required`,`too_large`,`quota_exceeded`,`conflict`,`unavailable`]),ky=class extends Error{code;constructor(e,t){super(e,t),this.code=e}},Ay=oo.check(_o(0)),jy=F({value:$a,revision:Ay}),My=F({value:$a,source:W([`member`,`team`,`none`]),team:Ki(jy),member:Ki(jy),canWriteTeam:vo}),Ny={key:F_,scope:W(Ug),basedOn:Ki(Ay)},Py=F({...Ny,value:$a}),Fy=F(Ny),Iy=F({revision:Ay}),Ly=F({appId:I,key:F_,scope:W(Ug),revision:Ay}),Ry=V([F({kind:K(`accepted`),value:My}),F({kind:K(`rejected`),code:Oy})]),zy=V([F({kind:K(`accepted`),value:Iy}),F({kind:K(`rejected`),code:Oy})]),By=F({error:I});V([Ry,By]),V([zy,By]);var Vy=e=>Sh(Fr().transform(t=>R(e,{onExcessProperty:`error`})(t))),Hy=xh({read:Ch(Vy(Ry)),write:Ch(Vy(zy)),reset:Ch(Vy(zy)),openEvents:Ch(Th)}),Uy=e=>{if(e.kind===`rejected`)throw new ky(e.code);return e.value},Wy=(e,t)=>{let n=Qi(e,{onExcessProperty:`error`})(t);if(n._tag===`Failure`)throw new ky(`invalid`,{cause:n.failure});return n.success},Gy=e=>Wy(F_,e);function Ky(e){let t=async t=>Uy(await e.read(Gy(t)));return{read:t,write:async t=>Uy(await e.write(Wy(Py,t))),reset:async t=>Uy(await e.reset(Wy(Fy,t))),async watch(n){let r=Gy(n),i=await e.openEvents(r),a=!1,o=()=>a,s,c=!1,l=()=>c&&!o(),u,d=()=>void 0,f=()=>void 0,p=new Promise((e,t)=>{d=e,f=t}),m=new Tg(`https://app-storage.fungi.invalid/events`,{fetch:async(e,t)=>{let n=await i.fetch(new Request(e,t));if(!n.ok){let e=Qi(Ry)(await n.json()),t=new ky(e._tag===`Success`&&e.success.kind===`rejected`?e.success.code:`unavailable`);throw g(t),t}return n}}),h=()=>{a||(a=!0,m.close(),f(new ky(`unavailable`)),i.close().catch(e=>{ss(`storage.watch.close`,e)}).finally(()=>{i[Symbol.dispose]()}))},g=e=>{f(e instanceof ky?e:new ky(`unavailable`,{cause:e})),!a&&u!==void 0&&ss(`storage.watch`,e),h()},_=()=>{c=!0,!(s!==void 0||a)&&(s=(async()=>{for(;l();){c=!1;let e=await t(r);if(o())return;if(u===void 0){let t=xm(e);u=t,d({get:()=>t.get(),subscribe:e=>t.subscribe(e),close:h,[Symbol.dispose]:h})}else u.update(e)}})().catch(g).finally(()=>{s=void 0,c&&!a&&_()}))};return m.addEventListener(`ready`,_),m.addEventListener(`changed`,e=>{let t=Qi(pa(Ly),{onExcessProperty:`error`})(e.data);t._tag===`Failure`?g(t.failure):t.success.key===r?_():g(new ky(`invalid`))}),m.onerror=e=>{(u===void 0||m.readyState===Tg.CLOSED)&&g(e)},p}}}var qy=bh(`app.storage`,1,ti(()=>Hy.transform(Ky))),Jy=J.createContext(void 0);function Yy(){let e=J.useContext(Jy);if(e===void 0)throw Error(Ue(53));return e}function Xy(e,t,n){if(!e)return 0;let r=getComputedStyle(e),i=`${t}${n===`x`?`Inline`:`Block`}`,a=parseFloat(r[`${i}Start`]);return n===`x`&&t===`margin`?a*2:a+parseFloat(r[`${i}End`])}var Zy=`base-ui-disable-scrollbar`,Qy={className:Zy,getElement(e){return(0,X.jsx)(`style`,{nonce:e,href:Zy,precedence:`base-ui:low`,children:`.${Zy}{scrollbar-width:none}.${Zy}::-webkit-scrollbar{display:none}`})}},$y=`data-has-overflow-x`,eb=`data-has-overflow-y`,tb=`data-overflow-x-start`,nb=`data-overflow-x-end`,rb=`data-overflow-y-start`,ib=`data-overflow-y-end`,ab=e=>t=>t?{[e]:``}:null,ob={hasOverflowX:ab($y),hasOverflowY:ab(eb),overflowXStart:ab(tb),overflowXEnd:ab(nb),overflowYStart:ab(rb),overflowYEnd:ab(ib),cornerHidden:()=>null},sb=Math.min,cb=Math.max,lb=Math.round,ub=Math.floor,db=e=>({x:e,y:e}),fb={left:`right`,right:`left`,bottom:`top`,top:`bottom`};function pb(e,t,n){return cb(e,sb(t,n))}function mb(e,t){return typeof e==`function`?e(t):e}function hb(e){return e.split(`-`)[0]}function gb(e){return e.split(`-`)[1]}function _b(e){return e===`x`?`y`:`x`}function vb(e){return e===`y`?`height`:`width`}function yb(e){let t=e[0];return t===`t`||t===`b`?`y`:`x`}function bb(e){return _b(yb(e))}function xb(e,t,n){n===void 0&&(n=!1);let r=gb(e),i=bb(e),a=vb(i),o=i===`x`?r===(n?`end`:`start`)?`right`:`left`:r===`start`?`bottom`:`top`;return t.reference[a]>t.floating[a]&&(o=Ab(o)),[o,Ab(o)]}function Sb(e){let t=Ab(e);return[Cb(e),t,Cb(t)]}function Cb(e){return e.includes(`start`)?e.replace(`start`,`end`):e.replace(`end`,`start`)}var wb=[`left`,`right`],Tb=[`right`,`left`],Eb=[`top`,`bottom`],Db=[`bottom`,`top`];function Ob(e,t,n){switch(e){case`top`:case`bottom`:return n?t?Tb:wb:t?wb:Tb;case`left`:case`right`:return t?Eb:Db;default:return[]}}function kb(e,t,n,r){let i=gb(e),a=Ob(hb(e),n===`start`,r);return i&&(a=a.map(e=>e+`-`+i),t&&(a=a.concat(a.map(Cb)))),a}function Ab(e){let t=hb(e);return fb[t]+e.slice(t.length)}function jb(e){return{top:e.top??0,right:e.right??0,bottom:e.bottom??0,left:e.left??0}}function Mb(e){return typeof e==`number`?{top:e,right:e,bottom:e,left:e}:jb(e)}function Nb(e){let{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}var Pb=J.createContext(void 0),Fb={disableStyleElements:!1};function Ib(){return J.useContext(Pb)??Fb}var Lb=`--scroll-area-corner-height`,Rb=`--scroll-area-corner-width`,zb=`data-orientation`,Bb={x:0,y:0},Vb={width:0,height:0},Hb={xStart:!1,xEnd:!1,yStart:!1,yEnd:!1},Ub={x:!0,y:!0,corner:!0},Wb=J.forwardRef(function(e,t){let{render:n,className:r,overflowEdgeThreshold:i,style:a,...o}=e,{xStart:s,xEnd:c,yStart:l,yEnd:u}=Gb(i),d=bt(),f=nr(),p=nr(),{nonce:m,disableStyleElements:h}=Ib(),[g,_]=J.useState(!1),[v,y]=J.useState(!1),[b,x]=J.useState(!1),[S,C]=J.useState(!1),[w,T]=J.useState(!1),[E,D]=J.useState(Vb),[O,k]=J.useState(Vb),[A,j]=J.useState(Hb),[M,ee]=J.useState(Ub),te=J.useRef(null),ne=J.useRef(null),re=J.useRef(null),ie=J.useRef(null),ae=J.useRef(null),oe=J.useRef(null),se=J.useRef(null),ce=J.useRef(null),le=J.useRef(0),N=J.useRef(0),ue=J.useRef(0),de=J.useRef(0),fe=J.useRef(`vertical`),pe=J.useRef(Bb),P=J.useRef(null);function me(e){let t=e?x:y,n=e?f:p;t(!0),n.start(500,()=>{t(!1)})}let he=Oe(e=>{let t=e.x-pe.current.x,n=e.y-pe.current.y;pe.current=e,n!==0&&me(!0),t!==0&&me(!1)}),ge=Oe(()=>{let e=ne.current;e&&P.current===null&&(P.current=e.style.scrollSnapType,e.style.scrollSnapType=`none`)}),_e=Oe(e=>{if(e.button!==0||ce.current!==null&&(fe.current===`vertical`?ae.current:oe.current)?.hasPointerCapture(ce.current))return;ce.current=e.pointerId,le.current=e.clientY,N.current=e.clientX,fe.current=e.currentTarget.getAttribute(zb);let t=ne.current;t&&(ue.current=t.scrollTop,de.current=t.scrollLeft,ge()),(fe.current===`vertical`?ae.current:oe.current)?.setPointerCapture(e.pointerId)}),ve=Oe(e=>{if(e.pointerId!==ce.current)return;ce.current=null,(fe.current===`vertical`?x:y)(!1),P.current!==null&&(ne.current&&(ne.current.style.scrollSnapType=P.current),P.current=null);let t=fe.current===`vertical`?ae.current:oe.current;t?.hasPointerCapture(e.pointerId)&&t.releasePointerCapture(e.pointerId)}),ye=Oe(e=>{if(e.pointerId!==ce.current)return;if(e.buttons%2==0){ve(e);return}let t=ne.current;if(!t)return;let n=fe.current===`vertical`,r=n?ae.current:oe.current,i=n?re.current:ie.current;if(!r||!i)return;let a=n?`y`:`x`,o=Xy(i,`padding`,a),s=Xy(r,`margin`,a),c=n?r.offsetHeight:r.offsetWidth,l=(n?i.offsetHeight:i.offsetWidth)-c-o-s,u=n?e.clientY-le.current:e.clientX-N.current,d=l<=0?0:u/l,f=n?t.scrollHeight:t.scrollWidth,p=n?t.clientHeight:t.clientWidth,m=(n?ue.current:de.current)+d*(f-p);n?t.scrollTop=m:t.scrollLeft=m,e.preventDefault(),me(n)});function be(e){C(e.pointerType===`touch`)}function xe(e){if(be(e),e.pointerType!==`touch`){let t=ht(te.current,e.target);_(t)}}let Se=J.useMemo(()=>({scrolling:v||b,hasOverflowX:!M.x,hasOverflowY:!M.y,overflowXStart:A.xStart,overflowXEnd:A.xEnd,overflowYStart:A.yStart,overflowYEnd:A.yEnd,cornerHidden:M.corner}),[v,b,M.x,M.y,M.corner,A]),Ce={role:`presentation`,onPointerEnter:xe,onPointerMove:xe,onPointerDown:be,onPointerLeave(){_(!1)},style:{position:`relative`,[Lb]:`${E.height}px`,[Rb]:`${E.width}px`}},we=Qn(`div`,e,{state:Se,ref:[t,te],props:[Ce,o],stateAttributesMapping:ob}),Te=J.useMemo(()=>({handlePointerDown:_e,handlePointerMove:ye,handlePointerUp:ve,handleScroll:he,disableViewportSnap:ge,cornerSize:E,setCornerSize:D,thumbSize:O,setThumbSize:k,hasMeasuredScrollbar:w,setHasMeasuredScrollbar:T,touchModality:S,cornerRef:se,scrollingX:v,scrollingY:b,hovering:g,setHovering:_,viewportRef:ne,scrollbarYRef:re,scrollbarXRef:ie,thumbYRef:ae,thumbXRef:oe,rootId:d,hiddenState:M,setHiddenState:ee,overflowEdges:A,setOverflowEdges:j,viewportState:Se,overflowEdgeThreshold:{xStart:s,xEnd:c,yStart:l,yEnd:u}}),[_e,ye,ve,he,ge,E,O,w,S,v,b,g,d,M,A,Se,s,c,l,u]);return(0,X.jsxs)(Jy.Provider,{value:Te,children:[!h&&Qy.getElement(m),we]})});function Gb(e){let t=typeof e==`number`?{xStart:e,xEnd:e,yStart:e,yEnd:e}:e;return{xStart:Math.max(0,t?.xStart||0),xEnd:Math.max(0,t?.xEnd||0),yStart:Math.max(0,t?.yStart||0),yEnd:Math.max(0,t?.yEnd||0)}}function Kb(e,t=-(2**53-1),n=2**53-1){return Math.max(t,Math.min(e,n))}var qb=J.createContext(void 0);function Jb(){let e=J.useContext(qb);if(e===void 0)throw Error(Ue(55));return e}var Yb=J.createContext(void 0);function Xb(){return J.useContext(Yb)?.direction??`ltr`}function Zb(e,t){if(t<=0)return 0;let n=Kb(e,0,t),r=n,i=t-n,a=r<=1,o=i<=1;return a&&o?r<=i?0:t:a?0:o?t:n}var Qb=`--scroll-area-overflow-x-start`,$b=`--scroll-area-overflow-x-end`,ex=`--scroll-area-overflow-y-start`,tx=`--scroll-area-overflow-y-end`,nx=`--scroll-area-thumb-height`,rx=`--scroll-area-thumb-width`,ix=[Qb,$b,ex,tx],ax=!1;function ox(){ax||r||(typeof CSS<`u`&&`registerProperty`in CSS&&ix.forEach(e=>{try{CSS.registerProperty({name:e,syntax:`<length>`,inherits:!1,initialValue:`0px`})}catch{}}),ax=!0)}var sx=J.forwardRef(function(e,t){let{render:n,className:r,style:i,...a}=e,{viewportRef:o,scrollbarYRef:s,scrollbarXRef:c,thumbYRef:l,thumbXRef:u,cornerRef:d,cornerSize:f,setCornerSize:p,setThumbSize:m,rootId:h,setHiddenState:g,hiddenState:_,setHasMeasuredScrollbar:v,handleScroll:y,touchModality:x,setHovering:S,setOverflowEdges:C,overflowEdgeThreshold:w,viewportState:T}=Yy(),E=Xb(),O=J.useRef(!0),k=J.useRef([NaN,NaN,NaN,NaN]),A=nr(),j=nr(),M=Oe(()=>{let e=o.current,t=s.current,n=c.current,r=l.current,i=u.current,a=d.current;if(!e)return;let h=e.scrollHeight,_=e.scrollWidth,y=e.clientHeight,b=e.clientWidth,x=e.scrollTop,S=e.scrollLeft,T=k.current,D=Number.isNaN(T[0]);if(T[0]=y,T[1]=h,T[2]=b,T[3]=_,D&&v(!0),h===0||_===0)return;let O=cx(e),A=O.y,j=O.x,M=b/_,ee=y/h,te=Math.max(0,_-b),ne=Math.max(0,h-y),re=0,ie=0;j||(re=Zb(E===`rtl`?-S:S,te),ie=te-re);let ae=A?0:Zb(x,ne),oe=A?0:ne-ae,se=j?0:b,ce=A?0:y,le=0,N=0;!j&&!A&&(le=t?.offsetWidth||0,N=n?.offsetHeight||0);let ue=f.width===0&&f.height===0,de=ue?le:0,fe=ue?N:0,pe=Xy(n,`padding`,`x`),P=Xy(t,`padding`,`y`),me=Xy(i,`margin`,`x`),he=Xy(r,`margin`,`y`),ge=se-pe-me,_e=ce-P-he,ve=n?Math.min(n.offsetWidth-de,ge):ge,ye=t?Math.min(t.offsetHeight-fe,_e):_e,be=Math.max(16,ve*M),xe=Math.max(16,ye*ee);if(m(e=>lx(e,{width:be,height:xe})),t&&r){let e=ux(r,nx,x,ne,h,xe,t.offsetHeight-xe-P-he);r.style.transform=`translate3d(0,${e}px,0)`}if(n&&i){let e=n.offsetWidth-be-pe-me,t=ux(i,rx,E===`rtl`?-S:S,te,_,be,e);i.style.transform=`translate3d(${E===`rtl`?-t:t}px,0,0)`}let Se=[re,ie,ae,oe];ix.forEach((t,n)=>{e.style.setProperty(t,`${Se[n]}px`)}),a&&p(e=>lx(e,{width:le,height:N})),g(e=>lx(e,O));let Ce={xStart:!j&&re>w.xStart,xEnd:!j&&ie>w.xEnd,yStart:!A&&ae>w.yStart,yEnd:!A&&oe>w.yEnd};C(e=>lx(e,Ce))});D(()=>{ox()},[]),D(()=>{queueMicrotask(M)},[M,_,E,w.xStart,w.xEnd,w.yStart,w.yEnd]),D(()=>{o.current?.matches(`:hover`)&&S(!0)},[o,S]),D(()=>{let e=o.current;if(typeof ResizeObserver>`u`||!e)return;let t=!1,n=new ResizeObserver(()=>{if(!t){t=!0;let n=k.current;if(n[0]===e.clientHeight&&n[1]===e.scrollHeight&&n[2]===e.clientWidth&&n[3]===e.scrollWidth)return}M()});return n.observe(e),j.start(0,()=>{let t=je(e,{subtree:!0});t.length!==0&&Promise.allSettled(t.map(e=>e.finished.then(b))).then(M).catch(()=>{})}),()=>{n.disconnect(),j.clear()}},[M,o,j]);function ee(){O.current=!1}let te={...h&&{"data-id":`${h}-viewport`},tabIndex:_.x&&_.y?-1:0,className:Qy.className,style:{overflow:`scroll`},onScroll(){o.current&&(M(),(x||!O.current)&&y({x:o.current.scrollLeft,y:o.current.scrollTop}),A.start(100,()=>{O.current=!0}))},onWheel:ee,onPointerMove:ee,onPointerEnter:ee,onKeyDown:ee},ne=Qn(`div`,e,{ref:[t,o],state:T,props:[te,a],stateAttributesMapping:ob}),re=J.useMemo(()=>({computeThumbPosition:M}),[M]);return(0,X.jsx)(qb.Provider,{value:re,children:ne})});function cx(e){let t=e.clientHeight>=e.scrollHeight,n=e.clientWidth>=e.scrollWidth;return{y:t,x:n,corner:t||n}}function lx(e,t){for(let n in t)if(e[n]!==t[n])return t;return e}function ux(e,t,n,r,i,a,o){let s=Kb(n,0,r),c=n-s,l=Math.max(16,a*i/(i+Math.abs(c)));return e.style.setProperty(t,c?`${l}px`:``),(r?s/r*o:0)+(c>0?a-l:0)}var dx=J.createContext(void 0);function fx(){let e=J.useContext(dx);if(e===void 0)throw Error(Ue(54));return e}var px=J.forwardRef(function(e,t){let{render:n,className:r,orientation:i=`vertical`,keepMounted:a=!1,style:o,...s}=e,{hovering:c,scrollingX:l,scrollingY:u,hiddenState:d,scrollbarYRef:f,scrollbarXRef:p,viewportRef:m,thumbYRef:h,thumbXRef:g,handlePointerDown:_,handlePointerUp:v,handleScroll:y,disableViewportSnap:b,rootId:x,thumbSize:S,hasMeasuredScrollbar:C,viewportState:w}=Yy(),T=i===`vertical`,E={...w,hovering:c,scrolling:T?u:l,orientation:i},D=Xb(),O=!C&&!a,k=T?d.y:d.x,A=a||!k;J.useEffect(()=>{if(!A)return;let e=m.current,t=T?f.current:p.current;if(!t)return;function n(t){if(!e||t.ctrlKey)return;let n=!T,r=n?`scrollLeft`:`scrollTop`,i=n?t.deltaX:t.deltaY;if(i===0)return;let a=n?e.scrollWidth-e.clientWidth:e.scrollHeight-e.clientHeight,o=n&&D===`rtl`?-a:0,s=n&&D===`rtl`?0:a,c=e[r];c<=o&&i<0||c>=s&&i>0||(t.preventDefault(),e[r]=Math.min(s,Math.max(o,c+i)),y({x:e.scrollLeft,y:e.scrollTop}))}return Ce(t,`wheel`,n,{passive:!1})},[D,y,T,p,f,A,m]);let j={...x&&{"data-id":`${x}-scrollbar`},"aria-hidden":!0,onPointerDown(e){if(e.button!==0)return;let t=Fe(e.nativeEvent),n=T?h.current:g.current;if(n&&ht(n,t))return;let r=m.current;if(!r)return;let i=T?f.current:p.current;if(!n||!i)return;let a=T?`y`:`x`,o=Xy(n,`margin`,a),s=Xy(i,`padding`,a),c=T?n.offsetHeight:n.offsetWidth,l=i.getBoundingClientRect(),u=T?e.clientY-l.top-c/2-s+o/2:e.clientX-l.left-c/2-s+o/2,d=T?r.scrollHeight:r.scrollWidth,v=T?r.clientHeight:r.clientWidth,x=(T?i.offsetHeight:i.offsetWidth)-c-s-o;if(x<=0)return;let S=u/x,C=d-v;b(),T?r.scrollTop=S*C:r.scrollLeft=D===`rtl`?-(1-S)*C:S*C,y({x:r.scrollLeft,y:r.scrollTop}),_(e)},onMouseDown(e){e.preventDefault()},onPointerUp:v,onPointerCancel:v,style:{position:`absolute`,touchAction:`none`,WebkitUserSelect:`none`,userSelect:`none`,visibility:O?`hidden`:void 0,...T?{top:0,bottom:`var(${Lb})`,insetInlineEnd:0,[nx]:`${S.height}px`}:{insetInlineStart:0,insetInlineEnd:`var(${Rb})`,bottom:0,[rx]:`${S.width}px`}}},M=Qn(`div`,e,{ref:[t,T?f:p],state:E,props:[j,s],stateAttributesMapping:ob});return A?(0,X.jsx)(dx.Provider,{value:i,children:M}):null}),mx=J.forwardRef(function(e,t){let{render:n,className:r,style:i,...a}=e,{computeThumbPosition:o}=Jb(),{hasMeasuredScrollbar:s,viewportState:c}=Yy(),l=J.useRef(null),u=J.useRef(s);return D(()=>{if(typeof ResizeObserver>`u`)return;let e=!1,t=new ResizeObserver(()=>{!e&&(e=!0,!u.current)||o()});return l.current&&t.observe(l.current),()=>{t.disconnect()}},[o]),Qn(`div`,e,{ref:[t,l],state:c,stateAttributesMapping:ob,props:[{role:`presentation`,style:{minWidth:`fit-content`}},a]})}),hx=J.forwardRef(function(e,t){let{render:n,className:r,style:i,...a}=e,{thumbYRef:o,thumbXRef:s,handlePointerDown:c,handlePointerMove:l,handlePointerUp:u,scrollingX:d,scrollingY:f,hasMeasuredScrollbar:p}=Yy(),m=fx(),h=m===`vertical`;return Qn(`div`,e,{ref:[t,h?o:s],state:{scrolling:h?f:d,orientation:m},props:[{onPointerDown:c,onPointerMove:l,onPointerUp:u,onPointerCancel:u,style:{visibility:p?void 0:`hidden`,...h?{height:`var(--scroll-area-thumb-height)`}:{width:`var(--scroll-area-thumb-width)`}}},a]})});function gx(e,t,n){let r=(Math.abs(t)-Math.abs(e))/Math.max(16,n);if(Math.abs(r)<.035)return null;let i=Math.min(.04,Math.abs(r)*.3),a=r>0,o=Math.sign(t||e);return{scaleY:1+(a?i:-i),scaleX:1+(a?-i/2:i/2),origin:(a?o>0:o<0)?`center top`:`center bottom`}}function _x(e,t,n){if(t<=0||Math.abs(n)<4)return null;let r=e<=0&&n<0,i=e>=t-1&&n>0;if(!r&&!i)return null;let a=Math.min(.06,Math.abs(n)/120*.06);return{scaleY:1-a,scaleX:1+a/2,origin:r?`center top`:`center bottom`}}var vx=(0,J.forwardRef)(function({children:e,className:t,surface:n=!1,surfaceSize:r,surfaceDepth:i,screen:a=!1,...o},c){let l=(0,J.useRef)(null),u=(0,J.useRef)(null),d=nt();(0,J.useEffect)(()=>{let e=l.current,t=e?.querySelector(`.caps-scroll-viewport`);if(!t||!e)return;let n=null,r,i=t.scrollTop,a=performance.now(),o=0,s=e=>{let t=u.current;if(!e||d||!t)return;n?.cancel(),t.style.transformOrigin=e.origin;let r=dr(t),i=nn(r,{ease:`outQuad`,duration:45}),a=ye(r,{bounce:.18,duration:180});n=To(t,{scaleY:[{to:e.scaleY,...i},{to:1,...a}],scaleX:[{to:e.scaleX,...i},{to:1,...a}]})},c=(e,t)=>{let n=gx(o,e,t);o=e,s(n)},f=e=>{if(e.ctrlKey||Math.abs(e.deltaX)>Math.abs(e.deltaY))return;let n=e.deltaMode===1?16:e.deltaMode===2?t.clientHeight:1,i=_x(t.scrollTop,t.scrollHeight-t.clientHeight,e.deltaY*n);i&&(clearTimeout(r),o=0,s(i))},p=()=>{let e=performance.now(),n=e-a,s=n>100?16:Math.max(16,n),l=t.scrollTop-i;n>100&&(o=0),c(l/s,s),i=t.scrollTop,a=e,clearTimeout(r),r=setTimeout(()=>{c(0,32)},64)};return t.addEventListener(`scroll`,p,{passive:!0}),e.addEventListener(`wheel`,f,{passive:!0}),()=>{clearTimeout(r),n?.cancel(),u.current&&(u.current.style.transform=`none`),t.removeEventListener(`scroll`,p),e.removeEventListener(`wheel`,f)}},[a,n,d]);let f=(0,X.jsx)(sx,{render:a?(0,X.jsx)(cn,{}):(0,X.jsx)(`div`,{}),...o,ref:c,className:`caps-scroll-viewport`,children:(0,X.jsx)(mx,{style:{minWidth:0},children:e})});return(0,X.jsxs)(Wb,{render:n?(0,X.jsx)(s,{size:r??`md`,depth:i??`shallow`}):(0,X.jsx)(`div`,{}),ref:l,className:ft(`caps-scroll-area`,t),children:[a?(0,X.jsx)(`div`,{className:`caps-display-gasket caps-scroll-display`,children:f}):f,(0,X.jsx)(s,{size:`sm`,depth:`deep`,placement:`embedded`,className:`caps-scroll-track-surface`,children:(0,X.jsx)(px,{className:`caps-scroll-track`,children:(0,X.jsx)(hx,{className:`caps-scroll-thumb`,children:(0,X.jsx)(`span`,{className:`caps-scroll-thumb-surface`,ref:u})})})})]})}),yx=J.createContext(void 0);function bx(e){let t=J.useContext(yx);if(t===void 0&&!e)throw Error(Ue(72));return t}function xx(e,t){return t!=null&&!ur(t)?0:typeof e==`function`?e():e}function Sx(e,t,n){let r=xx(e,n);return typeof r==`number`?r:r?.[t]}function Cx(e){return typeof e==`function`?e():e}function wx(e,t){return t||e===`click`||e===`mousedown`}function Tx(e){return e?.includes(`mouse`)&&e!==`mousedown`}function Ex(e,t){let n=null,r=null,i=!1;return{contextElement:e||void 0,getBoundingClientRect(){let a=e?.getBoundingClientRect()||{width:0,height:0,x:0,y:0},o=t.axis===`x`||t.axis===`both`,s=t.axis===`y`||t.axis===`both`,c=[`mouseenter`,`mousemove`].includes(t.dataRef.current.openEvent?.type||``)&&t.pointerType!==`touch`,l=t.axis===`y`?a.width:0,u=t.axis===`x`?a.height:0,d=a.x,f=a.y;return n==null&&t.x&&o&&(n=a.x-t.x),r==null&&t.y&&s&&(r=a.y-t.y),d-=n||0,f-=r||0,(!i||c)&&(d=o&&t.x!=null?t.x:d,f=s&&t.y!=null?t.y:f),i=!0,{width:l,height:u,x:d,y:f,top:f,right:d+l,bottom:f+u,left:d}}}}function Dx(e){return e!=null&&e.clientX!=null}function Ox(e,t={}){let{enabled:n=!0,axis:r=`both`}=t,i=e.useState(`open`),a=e.useState(`floatingElement`),o=e.useState(`domReferenceElement`),s=e.context.dataRef,c=J.useRef(!1),l=J.useRef(null),[u,d]=J.useState(),[f,p]=J.useState([]),m=Oe(t=>{e.set(`positionReference`,t)}),h=Oe((t,n,i)=>{c.current||s.current.openEvent&&!Dx(s.current.openEvent)||e.set(`positionReference`,Ex(i??o,{x:t,y:n,axis:r,dataRef:s,pointerType:u}))}),g=Oe(e=>{i?l.current||(h(e.clientX,e.clientY,e.currentTarget),p([])):h(e.clientX,e.clientY,e.currentTarget)}),_=ur(u)?a:i;J.useEffect(()=>{if(!n){m(o);return}if(!_)return;function e(){l.current?.(),l.current=null}let t=At(a);function r(t){let n=Fe(t);ht(a,n)?e():h(t.clientX,t.clientY)}return!s.current.openEvent||Dx(s.current.openEvent)?l.current=Ce(t,`mousemove`,r):m(o),e},[_,n,a,s,o,e,h,m,f]),J.useEffect(()=>()=>{e.set(`positionReference`,null)},[e]),J.useEffect(()=>{n&&!a&&(c.current=!1)},[n,a]),J.useEffect(()=>{!n&&i&&(c.current=!0)},[n,i]);let v=J.useMemo(()=>{function e(e){d(e.pointerType)}return{onPointerDown:e,onPointerEnter:e,onMouseMove:g,onMouseEnter:g}},[g]);return J.useMemo(()=>n?{reference:v,trigger:v}:{},[n,v])}var kx=class e{pointerType=void 0;interactedInside=!1;handler=void 0;blockMouseMove=!0;performedPointerEventsMutation=!1;pointerEventsScopeElement=null;pointerEventsReferenceElement=null;pointerEventsFloatingElement=null;restTimeoutPending=!1;openChangeTimeout=new g;restTimeout=new g;handleCloseOptions=void 0;static create(){return new e}dispose=()=>{this.openChangeTimeout.clear(),this.restTimeout.clear()};disposeEffect=()=>this.dispose},Ax=new WeakMap;function jx(e){if(!e.performedPointerEventsMutation)return;let t=e.pointerEventsScopeElement;t&&Ax.get(t)===e&&(e.pointerEventsScopeElement?.style.removeProperty(`pointer-events`),e.pointerEventsReferenceElement?.style.removeProperty(`pointer-events`),e.pointerEventsFloatingElement?.style.removeProperty(`pointer-events`),Ax.delete(t)),e.performedPointerEventsMutation=!1,e.pointerEventsScopeElement=null,e.pointerEventsReferenceElement=null,e.pointerEventsFloatingElement=null}function Mx(e,t){let{scopeElement:n,referenceElement:r,floatingElement:i}=t,a=Ax.get(n);a&&a!==e&&jx(a),jx(e),e.performedPointerEventsMutation=!0,e.pointerEventsScopeElement=n,e.pointerEventsReferenceElement=r,e.pointerEventsFloatingElement=i,Ax.set(n,e),n.style.pointerEvents=`none`,r.style.pointerEvents=`auto`,i.style.pointerEvents=`auto`}function Nx(e){let t=e.context.dataRef.current,n=ln(()=>t.hoverInteractionState??kx.create()).current;return t.hoverInteractionState||=n,qe(t.hoverInteractionState.disposeEffect),t.hoverInteractionState}function Px(e,t={}){let{enabled:n=!0,closeDelay:r=0,nodeId:i}=t,a=e.useState(`open`),o=e.useState(`floatingElement`),s=e.useState(`domReferenceElement`),{dataRef:c}=e.context,l=Bn(),u=Cn(),f=Nx(e),p=nr(),m=Oe(()=>wx(c.current.openEvent?.type,f.interactedInside)),g=Oe(()=>Tx(c.current.openEvent?.type)),_=Oe(()=>{jx(f)});D(()=>{a||(f.pointerType=void 0,f.restTimeoutPending=!1,f.interactedInside=!1,_())},[a,f,_]),J.useEffect(()=>_,[_]),D(()=>{if(n&&a&&f.handleCloseOptions?.blockPointerEvents&&g()&&Jn(s)&&o){let e=s,t=o,n=ze(o),r=l?.nodesRef.current.find(e=>e.id===u)?.context?.elements.floating;r&&(r.style.pointerEvents=``);let i=f.pointerEventsScopeElement===t?null:f.pointerEventsScopeElement,a=r===t?null:r,c=f.handleCloseOptions?.getScope?.()??i??a??lt(e,`[data-rootownerid]`)??n.body;return Mx(f,{scopeElement:c,referenceElement:e,floatingElement:t}),()=>{_()}}},[n,a,s,o,f,g,l,u,_]),J.useEffect(()=>{if(!n)return;function t(){return!!(l&&u&&d(l.nodesRef.current,u).length>0)}function a(t){let n=Sx(r,`close`,f.pointerType),i=()=>{e.setOpen(!1,Ke(h,t)),l?.events.emit(`floating.closed`,t)};n?f.openChangeTimeout.start(n,i):(f.openChangeTimeout.clear(),i())}function s(e){let t=Fe(e);if(!tt(t)){f.interactedInside=!1;return}f.interactedInside=lt(t,`[aria-haspopup]`)!=null}function v(){f.openChangeTimeout.clear(),p.clear(),l?.events.off(`floating.closed`,b),_()}function y(n){if(t()&&l){l.events.on(`floating.closed`,b);return}if(ne(n.relatedTarget,e.context.triggerElements))return;let r=c.current.floatingContext?.nodeId??i,o=n.relatedTarget;if(!(l&&r&&Jn(o)&&d(l.nodesRef.current,r,!1).some(e=>ht(e.context?.elements.floating,o)))){if(f.handler){f.handler(n);return}_(),g()&&!m()&&a(n)}}function b(n){!l||!u||t()||p.start(0,()=>{l.events.off(`floating.closed`,b),e.setOpen(!1,Ke(h,n)),l.events.emit(`floating.closed`,n)})}let x=o;return Wt(x&&Ce(x,`mouseenter`,v),x&&Ce(x,`mouseleave`,y),x&&Ce(x,`pointerdown`,s,!0),()=>{l?.events.off(`floating.closed`,b)})},[n,o,e,c,r,i,g,m,_,f,l,u,p])}var Fx=e(qt(),1),Ix={current:null};function Lx(e,t={}){let{enabled:n=!0,delay:r=0,handleClose:i=null,mouseOnly:a=!1,restMs:o=0,move:s=!0,triggerElementRef:c=Ix,externalTree:l,isActiveTrigger:u=!0,getHandleCloseContext:d,isClosing:f,shouldOpen:p,guardStaleOpen:m=!1}=t,{dataRef:g,events:_}=e.context,v=Bn(l),y=Nx(e),b=J.useRef(!1),x=Jt(i),S=Jt(r),C=Jt(o),w=Jt(n),T=Jt(p),E=Jt(f),D=Oe(()=>wx(g.current.openEvent?.type,y.interactedInside)),O=Oe(()=>T.current?.()!==!1),k=Oe((t,n,r)=>{let i=e.context.triggerElements;if(i.hasElement(n))return!t||!ht(t,n);if(!Jn(r))return!1;let a=r;return i.hasMatchingElement(e=>ht(e,a))&&(!t||!ht(t,a))}),A=Oe(()=>{y.handler&&=(ze(e.select(`domReferenceElement`)).removeEventListener(`mousemove`,y.handler),void 0)}),j=Oe(()=>{jx(y)});return u&&(y.handleCloseOptions=i?.__options),J.useEffect(()=>A,[A]),J.useEffect(()=>{if(!n)return;function e(e){e.open?b.current=!1:(b.current=e.reason===h,A(),y.openChangeTimeout.clear(),y.restTimeout.clear(),y.blockMouseMove=!0,y.restTimeoutPending=!1)}return _.on(`openchange`,e),()=>{_.off(`openchange`,e)}},[n,_,y,A]),J.useEffect(()=>{if(!n)return;function t(t,n=!0){let r=Sx(S.current,`close`,y.pointerType);r?y.openChangeTimeout.start(r,()=>{e.setOpen(!1,Ke(h,t)),v?.events.emit(`floating.closed`,t)}):n&&(y.openChangeTimeout.clear(),e.setOpen(!1,Ke(h,t)),v?.events.emit(`floating.closed`,t))}let r=c.current??(u?e.select(`domReferenceElement`):null);if(!Jn(r))return;function i(t){if(y.openChangeTimeout.clear(),y.blockMouseMove=!1,a&&!ur(y.pointerType))return;let n=Cx(C.current),r=Sx(S.current,`open`,y.pointerType),i=Fe(t),o=t.currentTarget??null,s=e.select(`domReferenceElement`),c=o;if(Jn(i)&&!e.context.triggerElements.hasElement(i)){for(let t of e.context.triggerElements.elements())if(ht(t,i)){c=t;break}}Jn(o)&&Jn(s)&&!e.context.triggerElements.hasElement(o)&&ht(o,s)&&(c=s);let l=c!=null&&k(s,c,i),u=e.select(`open`),d=E.current?.()??e.select(`transitionStatus`)===`ending`,f=!u&&d&&b.current,p=!l&&Jn(c)&&Jn(s)&&ht(s,c)&&f,m=n>0&&!r,g=l&&(u||f)||p,_=!u||l;if(g){O()&&e.setOpen(!0,Ke(h,t,c));return}m||(r?y.openChangeTimeout.start(r,()=>{_&&O()&&e.setOpen(!0,Ke(h,t,c))}):_&&O()&&e.setOpen(!0,Ke(h,t,c)))}function o(n){if(D()){j();return}A();let r=e.select(`domReferenceElement`),i=ze(r);y.restTimeout.clear(),y.restTimeoutPending=!1;let a=g.current.floatingContext??d?.();if(!ne(n.relatedTarget,e.context.triggerElements)){if(x.current&&a){e.select(`open`)||y.openChangeTimeout.clear();let r=c.current;y.handler=x.current({...a,tree:v,x:n.clientX,y:n.clientY,onClose(){j(),A(),w.current&&!D()&&r===e.select(`domReferenceElement`)&&t(n,!0)}}),i.addEventListener(`mousemove`,y.handler),y.handler(n);return}(y.pointerType!==`touch`||!ht(e.select(`floatingElement`),n.relatedTarget))&&t(n)}}function l(e){ht(r,e.relatedTarget)||(y.openChangeTimeout.clear(),y.restTimeout.clear(),y.restTimeoutPending=!1)}let f=m?Ce(r,`mouseout`,l):void 0;return s?Wt(Ce(r,`mousemove`,i,{once:!0}),Ce(r,`mouseenter`,i),Ce(r,`mouseleave`,o),f):Wt(Ce(r,`mouseenter`,i),Ce(r,`mouseleave`,o),f)},[A,j,g,S,e,n,x,y,u,k,D,a,s,C,c,v,w,d,E,O,m]),J.useMemo(()=>{if(!n)return;function t(e){y.pointerType=e.pointerType}return{onPointerDown:t,onPointerEnter:t,onMouseMove(t){let{nativeEvent:n}=t,r=t.currentTarget,i=e.select(`domReferenceElement`),o=e.select(`open`),s=k(i,r,t.target);if(a&&!ur(y.pointerType))return;if(o&&s&&y.handleCloseOptions?.blockPointerEvents){let t=e.select(`floatingElement`);if(t){let e=y.handleCloseOptions?.getScope?.()??r.ownerDocument.body;Mx(y,{scopeElement:e,referenceElement:r,floatingElement:t})}}let c=Cx(C.current);if(o&&!s||c===0||!s&&y.restTimeoutPending&&t.movementX**2+t.movementY**2<2)return;y.restTimeout.clear();function l(){if(y.restTimeoutPending=!1,D())return;let t=e.select(`open`);!y.blockMouseMove&&(!t||s)&&O()&&e.setOpen(!0,Ke(h,n,r))}y.pointerType===`touch`?Fx.flushSync(()=>{l()}):s&&o?l():(y.restTimeoutPending=!0,y.restTimeout.start(c,l))}}},[n,y,D,k,a,e,C,O])}var Rx=.1,zx=Rx*Rx,Bx=.5;function Vx(e,t,n,r,i,a){return r>=t!=a>=t&&e<=(i-n)*(t-r)/(a-r)+n}function Hx(e,t,n,r,i,a,o,s,c,l){let u=!1;return Vx(e,t,n,r,i,a)&&(u=!u),Vx(e,t,i,a,o,s)&&(u=!u),Vx(e,t,o,s,c,l)&&(u=!u),Vx(e,t,c,l,n,r)&&(u=!u),u}function Ux(e,t,n){return e>=n.x&&e<=n.x+n.width&&t>=n.y&&t<=n.y+n.height}function Wx(e,t,n,r,i,a){return e>=Math.min(n,i)&&e<=Math.max(n,i)&&t>=Math.min(r,a)&&t<=Math.max(r,a)}function Gx(e={}){let{blockPointerEvents:t=!1}=e,n=new g,r=({x:e,y:t,placement:r,elements:i,onClose:a,nodeId:o,tree:s})=>{let c=r?.split(`-`)[0],l=!1,u=null,f=null,p=typeof performance<`u`?performance.now():0;function m(e,t){let n=performance.now(),r=n-p;if(u===null||f===null||r===0)return u=e,f=t,p=n,!1;let i=e-u,a=t-f,o=i*i+a*a,s=r*r*zx;return u=e,f=t,p=n,o<s}function h(){n.clear(),a()}return function(r){n.clear();let a=i.domReference,u=i.floating;if(!a||!u||c==null||e==null||t==null)return;let{clientX:f,clientY:p}=r,g=Fe(r),_=r.type===`mouseleave`,v=ht(u,g),y=ht(a,g);if(v&&(l=!0,!_))return;if(y&&(l=!1,!_)){l=!0;return}if(_&&Jn(r.relatedTarget)&&ht(u,r.relatedTarget))return;function b(){return!!(s&&d(s.nodesRef.current,o).length>0)}function x(){b()||h()}if(b())return;let S=a.getBoundingClientRect(),C=u.getBoundingClientRect(),w=e>C.right-C.width/2,T=t>C.bottom-C.height/2,E=C.width>S.width,D=C.height>S.height,O=(E?S:C).left,k=(E?S:C).right,A=(D?S:C).top,j=(D?S:C).bottom;if(c===`top`&&t>=S.bottom-1||c===`bottom`&&t<=S.top+1||c===`left`&&e>=S.right-1||c===`right`&&e<=S.left+1){x();return}let M=!1;switch(c){case`top`:M=Wx(f,p,O,S.top+1,k,C.bottom-1);break;case`bottom`:M=Wx(f,p,O,C.top+1,k,S.bottom-1);break;case`left`:M=Wx(f,p,C.right-1,j,S.left+1,A);break;case`right`:M=Wx(f,p,S.right-1,j,C.left+1,A)}if(M)return;if(l&&!Ux(f,p,S)){x();return}if(!_&&m(f,p)){x();return}let ee=!1;switch(c){case`top`:{let n=E?Bx/2:Bx*4,r=E||w?e+n:e-n,i=E?e-n:w?e+n:e-n,a=t+Bx+1,o=w||E?C.bottom-Bx:C.top,s=w?E?C.bottom-Bx:C.top:C.bottom-Bx;ee=Hx(f,p,r,a,i,a,C.left,o,C.right,s);break}case`bottom`:{let n=E?Bx/2:Bx*4,r=E||w?e+n:e-n,i=E?e-n:w?e+n:e-n,a=t-Bx,o=w||E?C.top+Bx:C.bottom,s=w?E?C.top+Bx:C.bottom:C.top+Bx;ee=Hx(f,p,r,a,i,a,C.left,o,C.right,s);break}case`left`:{let n=D?Bx/2:Bx*4,r=D||T?t+n:t-n,i=D?t-n:T?t+n:t-n,a=e+Bx+1,o=T||D?C.right-Bx:C.left,s=T?D?C.right-Bx:C.left:C.right-Bx;ee=Hx(f,p,o,C.top,s,C.bottom,a,r,a,i);break}case`right`:{let n=D?Bx/2:Bx*4,r=D||T?t+n:t-n,i=D?t-n:T?t+n:t-n,a=e-Bx,o=T||D?C.left+Bx:C.right,s=T?D?C.left+Bx:C.right:C.left+Bx;ee=Hx(f,p,a,r,a,i,o,C.top,s,C.bottom);break}}ee?l||n.start(40,x):x()}};return r.__options={...e,blockPointerEvents:t},r}function Kx(e,t,n){let{reference:r,floating:i}=e,a=yb(t),o=bb(t),s=vb(o),c=hb(t),l=a===`y`,u=r.x+r.width/2-i.width/2,d=r.y+r.height/2-i.height/2,f=r[s]/2-i[s]/2,p;switch(c){case`top`:p={x:u,y:r.y-i.height};break;case`bottom`:p={x:u,y:r.y+r.height};break;case`right`:p={x:r.x+r.width,y:d};break;case`left`:p={x:r.x-i.width,y:d};break;default:p={x:r.x,y:r.y}}let m=gb(t);return m&&(p[o]+=f*(m===`end`?1:-1)*(n&&l?-1:1)),p}async function qx(e,t){t===void 0&&(t={});let{x:n,y:r,platform:i,rects:a,elements:o,strategy:s}=e,{boundary:c=`clippingAncestors`,rootBoundary:l=`viewport`,elementContext:u=`floating`,altBoundary:d=!1,padding:f=0}=mb(t,e),p=Mb(f),m=o[d?u===`floating`?`reference`:`floating`:u],h=Nb(await i.getClippingRect({element:await(i.isElement==null?void 0:i.isElement(m))??!0?m:m.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(o.floating)),boundary:c,rootBoundary:l,strategy:s})),g=u===`floating`?{x:n,y:r,width:a.floating.width,height:a.floating.height}:a.reference,_=await(i.getOffsetParent==null?void 0:i.getOffsetParent(o.floating)),v=await(i.isElement==null?void 0:i.isElement(_))&&await(i.getScale==null?void 0:i.getScale(_))||{x:1,y:1},y=Nb(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:o,rect:g,offsetParent:_,strategy:s}):g);return{top:(h.top-y.top+p.top)/v.y,bottom:(y.bottom-h.bottom+p.bottom)/v.y,left:(h.left-y.left+p.left)/v.x,right:(y.right-h.right+p.right)/v.x}}var Jx=50,Yx=async(e,t,n)=>{let{placement:r=`bottom`,strategy:i=`absolute`,middleware:a=[],platform:o}=n,s=o.detectOverflow?o:{...o,detectOverflow:qx},c=await(o.isRTL==null?void 0:o.isRTL(t)),l=await o.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:d}=Kx(l,r,c),f=r,p=0,m={};for(let n=0;n<a.length;n++){let h=a[n];if(!h)continue;let{name:g,fn:_}=h,{x:v,y,data:b,reset:x}=await _({x:u,y:d,initialPlacement:r,placement:f,strategy:i,middlewareData:m,rects:l,platform:s,elements:{reference:e,floating:t}});u=v??u,d=y??d,m[g]={...m[g],...b},x&&p<Jx&&(p++,typeof x==`object`&&(x.placement&&(f=x.placement),x.rects&&(l=x.rects===!0?await o.getElementRects({reference:e,floating:t,strategy:i}):x.rects),{x:u,y:d}=Kx(l,f,c)),n=-1)}return{x:u,y:d,placement:f,strategy:i,middlewareData:m}},Xx=function(e){return e===void 0&&(e={}),{name:`flip`,options:e,async fn(t){var n;let{placement:r,middlewareData:i,rects:a,initialPlacement:o,platform:s,elements:c}=t,{mainAxis:l=!0,crossAxis:u=!0,fallbackPlacements:d,fallbackStrategy:f=`bestFit`,fallbackAxisSideDirection:p=`none`,flipAlignment:m=!0,...h}=mb(e,t);if((n=i.arrow)!=null&&n.alignmentOffset)return{};let g=hb(r),_=yb(o),v=hb(o)===o,y=await(s.isRTL==null?void 0:s.isRTL(c.floating)),b=d||(v||!m?[Ab(o)]:Sb(o)),x=p!==`none`;!d&&x&&b.push(...kb(o,m,p,y));let S=[o,...b],C=await s.detectOverflow(t,h),w=[],T=i.flip?.overflows||[];if(l&&w.push(C[g]),u){let e=xb(r,a,y);w.push(C[e[0]],C[e[1]])}if(T=[...T,{placement:r,overflows:w}],!w.every(e=>e<=0)){let e=(i.flip?.index||0)+1,t=S[e];if(t&&(u!==`alignment`||_===yb(t)||T.every(e=>yb(e.placement)!==_||e.overflows[0]>0)))return{data:{index:e,overflows:T},reset:{placement:t}};let n=T.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0]?.placement;if(!n)switch(f){case`bestFit`:{let e=T.filter(e=>{if(x){let t=yb(e.placement);return t===_||t===`y`}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0]?.[0];e&&(n=e);break}case`initialPlacement`:n=o}if(r!==n)return{reset:{placement:n}}}return{}}}},Zx=new Set([`left`,`top`]);async function Qx(e,t){let{placement:n,platform:r,elements:i}=e,a=await(r.isRTL==null?void 0:r.isRTL(i.floating)),o=hb(n),s=gb(n),c=yb(n)===`y`,l=Zx.has(o)?-1:1,u=a&&c?-1:1,d=mb(t,e),{mainAxis:f,crossAxis:p,alignmentAxis:m}=typeof d==`number`?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return s&&typeof m==`number`&&(p=s===`end`?m*-1:m),c?{x:p*u,y:f*l}:{x:f*l,y:p*u}}var $x=function(e){return e===void 0&&(e=0),{name:`offset`,options:e,async fn(t){var n;let{x:r,y:i,placement:a,middlewareData:o}=t,s=await Qx(t,e);return a===o.offset?.placement&&(n=o.arrow)!=null&&n.alignmentOffset?{}:{x:r+s.x,y:i+s.y,data:{...s,placement:a}}}}},eS=function(e){return e===void 0&&(e={}),{name:`shift`,options:e,async fn(t){let{x:n,y:r,placement:i,platform:a}=t,{mainAxis:o=!0,crossAxis:s=!1,limiter:c={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...l}=mb(e,t),u={x:n,y:r},d=await a.detectOverflow(t,l),f=yb(i),p=_b(f),m=u[p],h=u[f],g=(e,t)=>pb(t+d[e===`y`?`top`:`left`],t,t-d[e===`y`?`bottom`:`right`]);o&&(m=g(p,m)),s&&(h=g(f,h));let _=c.fn({...t,[p]:m,[f]:h});return{..._,data:{x:_.x-n,y:_.y-r,enabled:{[p]:o,[f]:s}}}}}},tS=function(e){return e===void 0&&(e={}),{options:e,fn(t){let{x:n,y:r,placement:i,rects:a,middlewareData:o}=t,{offset:s=0,mainAxis:c=!0,crossAxis:l=!0}=mb(e,t),u={x:n,y:r},d=yb(i),f=_b(d),p=u[f],m=u[d],h=mb(s,t),g=typeof h==`number`?{mainAxis:h,crossAxis:0}:{mainAxis:h.mainAxis??0,crossAxis:h.crossAxis??0};if(c){let e=f===`y`?`height`:`width`,t=a.reference[f]-a.floating[e]+g.mainAxis,n=a.reference[f]+a.reference[e]-g.mainAxis;p<t?p=t:p>n&&(p=n)}if(l){let e=f===`y`?`width`:`height`,t=Zx.has(hb(i)),n=a.reference[d]-a.floating[e]+(t&&o.offset?.[d]||0)+(t?0:g.crossAxis),r=a.reference[d]+a.reference[e]+(t?0:o.offset?.[d]||0)-(t?g.crossAxis:0);m<n?m=n:m>r&&(m=r)}return{[f]:p,[d]:m}}}},nS=function(e){return e===void 0&&(e={}),{name:`size`,options:e,async fn(t){let{placement:n,rects:r,platform:i,elements:a}=t,{apply:o=()=>{},...s}=mb(e,t),c=await i.detectOverflow(t,s),l=hb(n),u=gb(n),d=yb(n)===`y`,{width:f,height:p}=r.floating,m,h;l===`top`||l===`bottom`?(m=l,h=u===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?`start`:`end`)?`left`:`right`):(h=l,m=u===`end`?`top`:`bottom`);let g=p-c.top-c.bottom,_=f-c.left-c.right,v=sb(p-c[m],g),y=sb(f-c[h],_),b=t.middlewareData.shift,x=!b,S=v,C=y;b!=null&&b.enabled.x&&(C=_),b!=null&&b.enabled.y&&(S=g),x&&!u&&(d?C=f-2*cb(c.left,c.right):S=p-2*cb(c.top,c.bottom)),await o({...t,availableWidth:C,availableHeight:S});let w=await i.getDimensions(a.floating);return f!==w.width||p!==w.height?{reset:{rects:!0}}:{}}}};function rS(e){let t=Lt(e),n=parseFloat(t.width)||0,r=parseFloat(t.height)||0,i=Pt(e),a=i?e.offsetWidth:n,o=i?e.offsetHeight:r,s=lb(n)!==a||lb(r)!==o;return s&&(n=a,r=o),{width:n,height:r,$:s}}function iS(e){return Jn(e)?e:e.contextElement}function aS(e){let t=iS(e);if(!Pt(t))return db(1);let n=t.getBoundingClientRect(),{width:r,height:i,$:a}=rS(t),o=(a?lb(n.width):n.width)/r,s=(a?lb(n.height):n.height)/i;return(!o||!Number.isFinite(o))&&(o=1),(!s||!Number.isFinite(s))&&(s=1),{x:o,y:s}}var oS=db(0);function sS(e){let t=At(e);return!Gt()||!t.visualViewport?oS:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function cS(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===At(e)}function lS(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);let i=e.getBoundingClientRect(),a=iS(e),o=db(1);t&&(r?Jn(r)&&(o=aS(r)):o=aS(e));let s=cS(a,n,r)?sS(a):db(0),c=(i.left+s.x)/o.x,l=(i.top+s.y)/o.y,u=i.width/o.x,d=i.height/o.y;if(a&&r){let e=At(a),t=Jn(r)?At(r):r,n=e,i=In(n);for(;i&&t!==n;){let e=aS(i),t=i.getBoundingClientRect(),r=Lt(i),a=t.left+(i.clientLeft+parseFloat(r.paddingLeft))*e.x,o=t.top+(i.clientTop+parseFloat(r.paddingTop))*e.y;c*=e.x,l*=e.y,u*=e.x,d*=e.y,c+=a,l+=o,n=At(i),i=In(n)}}return Nb({width:u,height:d,x:c,y:l})}function uS(e,t){let n=wt(e).scrollLeft;return t?t.left+n:lS(yn(e)).left+n}function dS(e,t){let n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-uS(e,n),y:n.top+t.scrollTop}}function fS(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e,a=i===`fixed`,o=yn(r),s=t?Yt(t.floating):!1;if(r===o||s&&a)return n;let c={scrollLeft:0,scrollTop:0},l=db(1),u=db(0),d=Pt(r);if((d||!a)&&(($t(r)!==`body`||On(o))&&(c=wt(r)),d)){let e=lS(r);l=aS(r),u.x=e.x+r.clientLeft,u.y=e.y+r.clientTop}let f=o&&!d&&!a?dS(o,c):db(0);return{width:n.width*l.x,height:n.height*l.y,x:n.x*l.x-c.scrollLeft*l.x+u.x+f.x,y:n.y*l.y-c.scrollTop*l.y+u.y+f.y}}function pS(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function mS(e){let t=wt(e),n=e.ownerDocument.body,r=cb(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=cb(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight),a=-t.scrollLeft+uS(e),o=-t.scrollTop;return Lt(n).direction===`rtl`&&(a+=cb(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:a,y:o}}var hS=25;function gS(e,t,n){n===void 0&&(n=`viewport`);let r=n===`layoutViewport`,i=At(e),a=yn(e),o=i.visualViewport,s=a.clientWidth,c=a.clientHeight,l=0,u=0;if(o){let e=!Gt()||t===`fixed`;r?e||(l=-o.offsetLeft,u=-o.offsetTop):(s=o.width,c=o.height,e&&(l=o.offsetLeft,u=o.offsetTop))}if(uS(a)<=0){let e=a.ownerDocument,t=e.body,n=getComputedStyle(t),r=e.compatMode===`CSS1Compat`&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,i=Math.abs(a.clientWidth-t.clientWidth-r),o=getComputedStyle(a).scrollbarGutter===`stable both-edges`?i/2:i;o<=hS&&(s-=o)}return{width:s,height:c,x:l,y:u}}function _S(e,t){let n=lS(e,!0,t===`fixed`),r=n.top+e.clientTop,i=n.left+e.clientLeft,a=aS(e);return{width:e.clientWidth*a.x,height:e.clientHeight*a.y,x:i*a.x,y:r*a.y}}function vS(e,t,n){let r;if(t===`viewport`||t===`layoutViewport`)r=gS(e,n,t);else if(t===`document`)r=mS(yn(e));else if(Jn(t))r=_S(t,n);else{let n=sS(e);r={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return Nb(r)}function yS(e,t){let n=t.get(e);if(n)return n;let r=wn(e,[],!1).filter(e=>Jn(e)&&$t(e)!==`body`),i=null,a=Lt(e).position===`fixed`,o=a?Vn(e):e;for(;Jn(o)&&!Ht(o);){let e=Lt(o),t=fn(o),n=i?i.position:a?`fixed`:``;!t&&(n===`fixed`||n===`absolute`&&e.position===`static`)?r=r.filter(e=>e!==o):i=e,o=Vn(o)}return t.set(e,r),r}function bS(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e,a=[...n===`clippingAncestors`?Yt(t)?[]:yS(t,this._c):[].concat(n),r],o=vS(t,a[0],i),s=o.top,c=o.right,l=o.bottom,u=o.left;for(let e=1;e<a.length;e++){let n=vS(t,a[e],i);s=cb(n.top,s),c=sb(n.right,c),l=sb(n.bottom,l),u=cb(n.left,u)}return{width:c-u,height:l-s,x:u,y:s}}function xS(e){let{width:t,height:n}=rS(e);return{width:t,height:n}}function SS(e,t,n){let r=Pt(t),i=yn(t),a=n===`fixed`,o=lS(e,!0,a,t),s={scrollLeft:0,scrollTop:0},c=db(0);if((r||!a)&&(($t(t)!==`body`||On(i))&&(s=wt(t)),r)){let e=lS(t,!0,a,t);c.x=e.x+t.clientLeft,c.y=e.y+t.clientTop}!r&&i&&(c.x=uS(i));let l=i&&!r&&!a?dS(i,s):db(0);return{x:o.left+s.scrollLeft-c.x-l.x,y:o.top+s.scrollTop-c.y-l.y,width:o.width,height:o.height}}function CS(e){return Lt(e).position===`static`}function wS(e,t){if(!Pt(e)||Lt(e).position===`fixed`)return null;if(t)return t(e);let n=e.offsetParent;return yn(e)===n&&(n=n.ownerDocument.body),n}function TS(e,t){let n=At(e);if(Yt(e))return n;if(!Pt(e)){let t=Vn(e);for(;t&&!Ht(t);){if(Jn(t)&&!CS(t))return t;t=Vn(t)}return n}let r=wS(e,t);for(;r&&hn(r)&&CS(r);)r=wS(r,t);return r&&Ht(r)&&CS(r)&&!fn(r)?n:r||Gn(e)||n}var ES=async function(e){let t=this.getOffsetParent||TS,n=this.getDimensions,r=await n(e.floating);return{reference:SS(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function DS(e){return Lt(e).direction===`rtl`}var OS={convertOffsetParentRelativeRectToViewportRelativeRect:fS,getDocumentElement:yn,getClippingRect:bS,getOffsetParent:TS,getElementRects:ES,getClientRects:pS,getDimensions:xS,getScale:aS,isElement:Jn,isRTL:DS};function kS(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function AS(e,t,n){let r=null,i,a=yn(e);function o(){var e;clearTimeout(i),(e=r)==null||e.disconnect(),r=null}function s(n,c){n===void 0&&(n=!1),c===void 0&&(c=1),o();let l=e.getBoundingClientRect(),{left:u,top:d,width:f,height:p}=l;if(n||t(),!f||!p)return;let m=ub(d),h=ub(a.clientWidth-(u+f)),g=ub(a.clientHeight-(d+p)),_=ub(u),v={rootMargin:-m+`px `+-h+`px `+-g+`px `+-_+`px`,threshold:cb(0,sb(1,c))||1},y=!0;function b(t){let n=t[0].intersectionRatio;if(!kS(l,e.getBoundingClientRect()))return s();if(n!==c){if(!y)return s();n?s(!1,n):i=setTimeout(()=>{s(!1,1e-7)},1e3)}y=!1}try{r=new IntersectionObserver(b,{...v,root:a.ownerDocument})}catch{r=new IntersectionObserver(b,v)}r.observe(e)}let c=At(e),l=()=>s(n);return c.addEventListener(`resize`,l),s(!0),()=>{c.removeEventListener(`resize`,l),o()}}function jS(e,t,n,r){r===void 0&&(r={});let{ancestorScroll:i=!0,ancestorResize:a=!0,elementResize:o=typeof ResizeObserver==`function`,layoutShift:s=typeof IntersectionObserver==`function`,animationFrame:c=!1}=r,l=iS(e),u=i||a?[...l?wn(l):[],...t?wn(t):[]]:[];u.forEach(e=>{i&&e.addEventListener(`scroll`,n),a&&e.addEventListener(`resize`,n)});let d=l&&s?AS(l,n,a):null,f=-1,p=null;o&&(p=new ResizeObserver(e=>{let[r]=e;r&&r.target===l&&p&&t&&(p.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var e;(e=p)==null||e.observe(t)})),n()}),l&&!c&&p.observe(l),t&&p.observe(t));let m,h=c?lS(e):null;c&&g();function g(){let t=lS(e);h&&!kS(h,t)&&n(),h=t,m=requestAnimationFrame(g)}return n(),()=>{var e;u.forEach(e=>{i&&e.removeEventListener(`scroll`,n),a&&e.removeEventListener(`resize`,n)}),d?.(),(e=p)==null||e.disconnect(),p=null,c&&cancelAnimationFrame(m)}}var MS=$x,NS=eS,PS=Xx,FS=nS,IS=tS,LS=(e,t,n)=>{let r=new Map,i=n??{},a={...OS,...i.platform,_c:r};return Yx(e,t,{...i,platform:a})},RS=typeof document<`u`?J.useLayoutEffect:function(){};function zS(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e==`function`&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e==`object`){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!zS(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){let n=i[r];if(!(n===`_owner`&&e.$$typeof)&&!zS(e[n],t[n]))return!1}return!0}return e!==e&&t!==t}function BS(e){return typeof window>`u`?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function VS(e,t){let n=BS(e);return Math.round(t*n)/n}function HS(e){let t=J.useRef(e);return RS(()=>{t.current=e}),t}function US(e){e===void 0&&(e={});let{placement:t=`bottom`,strategy:n=`absolute`,middleware:r=[],platform:i,elements:{reference:a,floating:o}={},transform:s=!0,whileElementsMounted:c,open:l}=e,[u,d]=J.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,p]=J.useState(r);zS(f,r)||p(r);let[m,h]=J.useState(null),[g,_]=J.useState(null),v=J.useCallback(e=>{e!==S.current&&(S.current=e,h(e))},[]),y=J.useCallback(e=>{e!==C.current&&(C.current=e,_(e))},[]),b=a||m,x=o||g,S=J.useRef(null),C=J.useRef(null),w=J.useRef(u),T=c!=null,E=HS(c),D=HS(i),O=HS(l),k=J.useCallback(()=>{if(!S.current||!C.current)return;let e={placement:t,strategy:n,middleware:f};D.current&&(e.platform=D.current),LS(S.current,C.current,e).then(e=>{let t={...e,isPositioned:O.current!==!1};A.current&&!zS(w.current,t)&&(w.current=t,Fx.flushSync(()=>{d(t)}))})},[f,t,n,D,O]);RS(()=>{l===!1&&w.current.isPositioned&&(w.current.isPositioned=!1,d(e=>({...e,isPositioned:!1})))},[l]);let A=J.useRef(!1);RS(()=>(A.current=!0,()=>{A.current=!1}),[]),RS(()=>{if(b&&(S.current=b),x&&(C.current=x),b&&x){if(E.current)return E.current(b,x,k);k()}},[b,x,k,E,T]);let j=J.useMemo(()=>({reference:S,floating:C,setReference:v,setFloating:y}),[v,y]),M=J.useMemo(()=>({reference:b,floating:x}),[b,x]),ee=J.useMemo(()=>{let e={position:n,left:0,top:0};if(!M.floating)return e;let t=VS(M.floating,u.x),r=VS(M.floating,u.y);return s?{...e,transform:`translate(`+t+`px, `+r+`px)`,...BS(M.floating)>=1.5&&{willChange:`transform`}}:{position:n,left:t,top:r}},[n,s,M.floating,u.x,u.y]);return J.useMemo(()=>({...u,update:k,refs:j,elements:M,floatingStyles:ee}),[u,k,j,M,ee])}var WS=(e,t)=>{let n=MS(e);return{name:n.name,fn:n.fn,options:[e,t]}},GS=(e,t)=>{let n=NS(e);return{name:n.name,fn:n.fn,options:[e,t]}},KS=(e,t)=>({fn:IS(e).fn,options:[e,t]}),qS=(e,t)=>{let n=PS(e);return{name:n.name,fn:n.fn,options:[e,t]}},JS=(e,t)=>{let n=FS(e);return{name:n.name,fn:n.fn,options:[e,t]}},YS={...k,disabled:e=>e.disabled,instantType:e=>e.instantType,isInstantPhase:e=>e.isInstantPhase,trackCursorAxis:e=>e.trackCursorAxis,disableHoverablePopup:e=>e.disableHoverablePopup,lastOpenChangeReason:e=>e.openChangeReason,closeOnClick:e=>e.closeOnClick,appliedTriggerProps:(e,t)=>t?e.activeTriggerProps:void 0,closeDelay:e=>e.closeDelay,adaptiveOrigin:e=>e.adaptiveOrigin},XS=class extends ce{constructor(e,t,n){let r=new Ve;super(ZS(e,r,t,n),QS(r),YS)}setOpen=(e,t)=>{rt(this,e,t,{extraState:{openChangeReason:t.reason}})};cancelPendingOpen(e){this.state.floatingRootContext.dispatchOpenChange(!1,Ke(tr,e))}};function ZS(e,t,n,r=!1){return{...Ne(t,n,r),disabled:!1,instantType:void 0,isInstantPhase:!1,trackCursorAxis:`none`,disableHoverablePopup:!1,openChangeReason:null,closeOnClick:!0,closeDelay:0,adaptiveOrigin:void 0,...e}}function QS(e){return{popupRef:J.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerElements:e}}var $S=C(function(e){let{disabled:t=!1,defaultOpen:n=!1,open:r,disableHoverablePopup:i=!1,trackCursorAxis:a=`none`,actionsRef:o,onOpenChange:s,onOpenChangeComplete:c,handle:l,triggerId:u,defaultTriggerId:d=null,children:f}=e,m=ue((e,t)=>new XS({open:n,openProp:r,activeTriggerId:d,triggerIdProp:u},e,t));m.useControlledProp(`openProp`,r),m.useControlledProp(`triggerIdProp`,u),m.useContextCallback(`onOpenChange`,s),m.useContextCallback(`onOpenChangeComplete`,c);let h=m.useState(`open`),g=!t&&h,_=m.useState(`activeTriggerId`),v=m.useState(`mounted`),y=m.useState(`payload`);m.useSyncedValues({trackCursorAxis:a,disableHoverablePopup:i,disabled:t}),M(m,{closeOnActiveTriggerUnmount:!0});let{forceUnmount:b,transitionStatus:x}=pe(g,m),S=m.useState(`isInstantPhase`),C=m.useState(`instantType`),w=m.useState(`lastOpenChangeReason`),T=J.useRef(null);D(()=>{h&&t&&m.setOpen(!1,Ke(Zn))},[h,t,m]),D(()=>{x===`ending`&&w===`none`||x!==`ending`&&S?(C!==`delay`&&(T.current=C),m.set(`instantType`,`delay`)):T.current!==null&&(m.set(`instantType`,T.current),T.current=null)},[x,S,w,C,m]),D(()=>{g&&(_??m.set(`payload`,void 0))},[m,_,g]),J.useImperativeHandle(o,()=>({unmount:b,close:()=>m.setOpen(!1,Ke(ar))}),[b,m]);let E=g||v||!t&&a!==`none`;return(0,X.jsxs)(yx.Provider,{value:m,children:[l&&(0,X.jsx)(p,{handle:l,store:m}),E&&(0,X.jsx)(eC,{store:m,disabled:t,trackCursorAxis:a}),typeof f==`function`?f({payload:y}):f]})});function eC({store:e,disabled:t,trackCursorAxis:n}){let r=e.useState(`floatingRootContext`),i=It(r,{enabled:!t,referencePress:()=>e.select(`closeOnClick`)}),a=Ox(r,{enabled:!t&&n!==`none`,axis:n===`none`?void 0:n}),o=J.useMemo(()=>cr(a.reference,i.reference),[a.reference,i.reference]);return Mn(e,{activeTriggerProps:o,inactiveTriggerProps:o,popupProps:i.floating??w}),null}var tC=J.createContext(void 0);function nC(){let e=J.useContext(tC);if(e===void 0)throw Error(Ue(70));return e}var rC=J.forwardRef(function(e,t){let{children:n,container:r,className:i,render:a,style:o,...s}=e,{node:c,subtree:l}=dn({container:r,ref:t,componentProps:e,elementProps:s});return!l&&!c?null:(0,X.jsxs)(J.Fragment,{children:[l,c&&Fx.createPortal(n,c)]})}),iC=J.forwardRef(function(e,t){let{keepMounted:n=!1,...r}=e;return bx().useState(`mounted`)||n?(0,X.jsx)(tC.Provider,{value:n,children:(0,X.jsx)(rC,{ref:t,...r})}):null}),aC=J.createContext(void 0);function oC(){let e=J.useContext(aC);if(e===void 0)throw Error(Ue(71));return e}function sC(e){let{nodeId:t,externalTree:n,rootContext:r}=e,i=r.useState(`referenceElement`),a=r.useState(`floatingElement`),o=r.useState(`domReferenceElement`),s=r.useState(`open`),c=r.useState(`floatingId`),[l,u]=J.useState(null),d=J.useRef(null),f=Bn(n),p=J.useMemo(()=>({reference:i,floating:a,domReference:o}),[i,a,o]),m=US({...e,elements:{...p,...l&&{reference:l}}}),h=J.useCallback(e=>{let t=Jn(e)?{getBoundingClientRect:()=>e.getBoundingClientRect(),getClientRects:()=>e.getClientRects(),contextElement:e}:e;u(t),m.refs.setReference(t)},[m.refs]),g=J.useMemo(()=>({...m.refs,setPositionReference:h,domReference:d}),[m.refs,h]),_=J.useMemo(()=>({...m.elements,domReference:o}),[m.elements,o]),v=J.useMemo(()=>({...m,dataRef:r.context.dataRef,open:s,onOpenChange:r.setOpen,events:r.context.events,floatingId:c,refs:g,elements:_,nodeId:t,rootStore:r}),[m,g,_,t,r,s,c]);return D(()=>{o&&(d.current=o)},[o]),D(()=>{r.context.dataRef.current.floatingContext=v;let e=f?.nodesRef.current.find(e=>e.id===t);e&&(e.context=v)}),J.useMemo(()=>({...m,context:v,refs:g,elements:_,rootStore:r}),[m,g,_,v,r])}var cC=e=>({name:`arrow`,options:e,async fn(t){let{x:n,y:r,placement:i,rects:a,platform:o,elements:s,middlewareData:c}=t,{element:l,padding:u=0}=mb(e,t)||{};if(l==null)return{};let d=Mb(u),f={x:n,y:r},p=bb(i),m=vb(p),h=await o.getDimensions(l),g=p===`y`,_=g?`top`:`left`,v=g?`bottom`:`right`,y=g?`clientHeight`:`clientWidth`,b=a.reference[m]+a.reference[p]-f[p]-a.floating[m],x=f[p]-a.reference[p],S=s.floating[y]||a.floating[m],C=b/2-x/2,w=S/2-h[m]/2-1,T=Math.min(d[_],w),E=Math.min(d[v],w),D=T,O=S-h[m]-E,k=S/2-h[m]/2+C,A=pb(D,k,O),j=!c.arrow&&gb(i)!=null&&k!==A&&a.reference[m]/2-(k<D?T:E)-h[m]/2<0,M=j?k<D?k-D:k-O:0;return{[p]:f[p]+M,data:{[p]:A,centerOffset:k-A-M,...j&&{alignmentOffset:M}},reset:j}}}),lC=(e,t)=>{let{name:n,fn:r}=cC(e);return{name:n,fn:r,options:[e,t]}},uC={name:`hide`,async fn(e){let{width:t,height:n,x:r,y:i}=e.rects.reference,a=t===0&&n===0&&r===0&&i===0,o=await e.platform.detectOverflow(e,{elementContext:`reference`});return{data:{referenceHidden:o.top-n>=0||o.right-t>=0||o.bottom-n>=0||o.left-t>=0||a}}}},dC={sideX:`left`,sideY:`top`},fC=`--available-width`,pC=`--available-height`,mC=`--anchor-width`,hC=`--anchor-height`,gC=`--transform-origin`,_C=fC,vC=pC;function yC(e,t,n){let r=e===`inline-start`||e===`inline-end`;return{top:`top`,right:r?n?`inline-start`:`inline-end`:`right`,bottom:`bottom`,left:r?n?`inline-end`:`inline-start`:`left`}[t]}function bC(e,t,n){let{rects:r,placement:i}=e;return{side:yC(t,hb(i),n),align:gb(i)||`center`,anchor:{width:r.reference.width,height:r.reference.height},positioner:{width:r.floating.width,height:r.floating.height}}}function xC(e){return SC(e,sC)}function SC(e,t){let{anchor:n,positionMethod:r=`absolute`,side:i=`bottom`,sideOffset:a=0,align:o=`center`,alignOffset:s=0,collisionBoundary:c,collisionPadding:l=5,sticky:u=!1,arrowPadding:d=5,disableAnchorTracking:f=!1,inline:p,keepMounted:m=!1,floatingRootContext:h,mounted:g,collisionAvoidance:_,shift:v,nodeId:y,adaptiveOrigin:b,lazyFlip:x=!1,externalTree:S}=e,C=_.side||`flip`,w=_.align||`flip`,T=_.fallbackAxisSide||`end`,E=v?.crossAxis??!1,O=v?.rootBoundary,k=typeof n==`function`?n:void 0,A=Oe(k),j=k?A:n,M=Jt(n),ee=Jt(g),te=Xb()===`rtl`,[ne,re]=J.useState(null);!g&&ne!==null&&re(null);let ie=x===`placement`,ae=ne?hb(ne):null,oe=ne&&ie?gb(ne)||`center`:null,se=ae||{top:`top`,right:`right`,bottom:`bottom`,left:`left`,"inline-end":te?`left`:`right`,"inline-start":te?`right`:`left`}[i],ce=oe||o,le=ce===`center`?se:`${se}-${ce}`,N=l;typeof N==`number`?N={top:N,right:N,bottom:N,left:N}:N&&={top:N.top||0,right:N.right||0,bottom:N.bottom||0,left:N.left||0};let ue=+(i===`bottom`),de=+(i===`top`),fe=+(i===`right`),pe=+(i===`left`),P={boundary:c===`clipping-ancestors`?`clippingAncestors`:c,padding:N},me=J.useRef(null),he=Jt(a),ge=Jt(s),_e=typeof a==`function`?0:a,ve=typeof s==`function`?0:s,ye=[];p&&ye.push(p),ye.push(WS(e=>{let t=bC(e,i,te),n=typeof he.current==`function`?he.current(t):he.current,r=typeof ge.current==`function`?ge.current(t):ge.current;return{mainAxis:n,crossAxis:r,alignmentAxis:r}},[_e,ve,te,i]));let be=w===`none`&&C!==`shift`,xe=!be&&(u||E||C===`shift`),Se=C===`none`?null:qS({...P,padding:{top:N.top+1+ue,right:N.right+1+pe,bottom:N.bottom+1+de,left:N.left+1+fe},mainAxis:!E&&C===`flip`,crossAxis:w===`flip`&&`alignment`,fallbackAxisSideDirection:T}),Ce=be?null:GS({...P,rootBoundary:O,mainAxis:w!==`none`,crossAxis:xe,limiter:u||E?void 0:KS(e=>{if(!me.current)return{};let{width:t,height:n}=me.current.getBoundingClientRect(),r=yb(hb(e.placement)),i=r===`y`?t:n,a=r===`y`?N.left+N.right:N.top+N.bottom;return{offset:i/2+a/2}})},[P,u,E,O,N,w]);C===`shift`||w===`shift`||ce===`center`?ye.push(Ce,Se):ye.push(Se,Ce),ye.push(JS({...P,apply({elements:{floating:e},availableWidth:t,availableHeight:n,rects:r}){if(!ee.current)return;let i=e.style;i.setProperty(_C,`${t}px`),i.setProperty(vC,`${n}px`);let a=At(e).devicePixelRatio||1,{x:o,y:s,width:c,height:l}=r.reference,u=(Math.round((o+c)*a)-Math.round(o*a))/a,d=(Math.round((s+l)*a)-Math.round(s*a))/a;i.setProperty(mC,`${u}px`),i.setProperty(hC,`${d}px`)}}),lC(e=>({element:me.current||ze(e.elements.floating).createElement(`div`),padding:me.current?d:0}),[d]),{name:`transformOrigin`,fn(e){let{elements:{floating:t},middlewareData:n,placement:r,platform:o,rects:s,y:c}=e,l=hb(r),u=gb(r),d=yb(l)===`y`,f=me.current,p=typeof a==`function`?a(bC(e,i,te)):a,m;m=!f&&u&&Math.abs(d?n.shift?.x||0:n.shift?.y||0)<=1?u===`start`===(d&&o.isRTL?.(t)===!0)?`100%`:`0%`:`${(d?n.arrow?.x||0:n.arrow?.y||0)+(d?f?.clientWidth||0:f?.clientHeight||0)/2}px`;let h=l===`top`||l===`left`?`calc(100% + ${p}px)`:`${-p}px`;return xe&&d&&Math.abs(n.shift?.y||0)>p&&(h=`${s.reference.y+s.reference.height/2-c}px`),t.style.setProperty(gC,d?`${m} ${h}`:`${h} ${m}`),{}}},uC,b),D(()=>{!g&&h&&h.update({referenceElement:null,floatingElement:null,domReferenceElement:null,positionReference:null})},[g,h]);let we=J.useMemo(()=>({ancestorScroll:!f,elementResize:!f&&typeof ResizeObserver<`u`,layoutShift:!f&&typeof IntersectionObserver<`u`}),[f]),{refs:Te,elements:Ee,x:De,y:ke,middlewareData:Ae,update:je,placement:Me,context:Ne,isPositioned:Pe,floatingStyles:Fe}=t({rootContext:h,open:m?g:void 0,placement:le,middleware:ye,strategy:r,whileElementsMounted:m?void 0:(...e)=>jS(...e,we),nodeId:y,externalTree:S}),{sideX:Ie,sideY:Le}=Ae.adaptiveOrigin||dC,Re=Pe?r:`fixed`,Be=J.useMemo(()=>{let e;return e=Pe?b?{position:Re,[Ie]:De,[Le]:ke}:{...Fe,position:Re}:{position:Re,top:0,left:0},e[_C]=`100vw`,e[vC]=`100vh`,Pe||(e.opacity=0),e},[b,Re,Ie,De,Le,ke,Fe,Pe]),Ve=J.useRef(null);D(()=>{if(!g)return;let e=M.current,t=typeof e==`function`?e():e,n=(CC(t)?t.current:t)||null;n!==Ve.current&&(Te.setPositionReference(n),Ve.current=n)},[g,Te,j,M]),J.useEffect(()=>{if(!g)return;let e=M.current;typeof e!=`function`&&CC(e)&&e.current!==Ve.current&&(Te.setPositionReference(e.current),Ve.current=e.current)},[g,Te,j,M]),J.useEffect(()=>{if(m&&g&&Ee.reference&&Ee.floating)return jS(Ee.reference,Ee.floating,je,we)},[m,g,Ee,je,we]);let He=hb(Me),Ue=yC(i,He,te),We=gb(Me)||`center`,Ge=!!Ae.hide?.referenceHidden;D(()=>{x&&g&&Pe&&(He!==se||ie&&We!==ce)&&re(Me)},[x,ie,g,Pe,Me,He,We,se,ce]);let Ke=J.useMemo(()=>({position:`absolute`,top:Ae.arrow?.y,left:Ae.arrow?.x}),[Ae.arrow]),qe=Ae.arrow?.centerOffset!==0;return J.useMemo(()=>({positionerStyles:Be,arrowStyles:Ke,arrowRef:me,arrowUncentered:qe,side:Ue,align:We,physicalSide:He,anchorHidden:Ge,refs:Te,context:Ne,isPositioned:Pe,update:je}),[Be,Ke,me,qe,Ue,We,He,Ge,Te,Ne,Pe,je])}function CC(e){return e!=null&&`current`in e}function wC(e){return e===`starting`?Nt:w}function TC(e,t,{styles:n,transitionStatus:r,props:i,refs:a,hidden:o,inert:s=!1}){let c={...n};return s&&(c.pointerEvents=`none`),Qn(`div`,e,{state:t,ref:a,props:[{role:`presentation`,hidden:o,style:c},wC(r),i],stateAttributesMapping:Ze})}var EC=J.forwardRef(function(e,t){let{render:n,className:r,anchor:i,positionMethod:a=`absolute`,side:o=`top`,align:s=`center`,sideOffset:c=0,alignOffset:l=0,collisionBoundary:u=`clipping-ancestors`,collisionPadding:d=5,arrowPadding:f=5,sticky:p=!1,disableAnchorTracking:m=!1,collisionAvoidance:h=Vt,style:g,..._}=e,v=bx(),y=nC(),b=v.useState(`open`),x=v.useState(`mounted`),S=v.useState(`trackCursorAxis`),C=v.useState(`disableHoverablePopup`),w=v.useState(`floatingRootContext`),T=v.useState(`instantType`),E=v.useState(`transitionStatus`),D=xC({anchor:i,positionMethod:a,floatingRootContext:w,mounted:x,side:o,sideOffset:c,align:s,alignOffset:l,collisionBoundary:u,collisionPadding:d,sticky:p,arrowPadding:f,disableAnchorTracking:m,keepMounted:y,collisionAvoidance:h,adaptiveOrigin:v.useState(`adaptiveOrigin`)}),O=TC(e,J.useMemo(()=>({open:b,side:D.side,align:D.align,anchorHidden:D.anchorHidden,instant:S===`none`?T:`tracking-cursor`}),[b,D.side,D.align,D.anchorHidden,S,T]),{styles:D.positionerStyles,transitionStatus:E,props:_,refs:[t,v.useStateSetter(`positionerElement`)],hidden:!x,inert:!b||S===`both`||C});return(0,X.jsx)(aC.Provider,{value:D,children:O})}),DC=J.forwardRef(function(e,t){let{render:n,className:r,style:i,...a}=e,o=bx(),{side:s,align:c}=oC(),l=o.useState(`open`),u=o.useState(`instantType`),d=o.useState(`transitionStatus`),f=o.useState(`popupProps`),p=o.useState(`floatingRootContext`),m=o.useState(`disabled`),h=o.useState(`closeDelay`);_t({open:l,ref:o.context.popupRef,onComplete(){l&&o.context.onOpenChangeComplete?.(!0)}}),Px(p,{enabled:!m,closeDelay:h});let g=o.useStateSetter(`popupElement`);return Qn(`div`,e,{state:{open:l,side:s,align:c,instant:u,transitionStatus:d},ref:[t,o.context.popupRef,g],props:[fr,f,wC(d),a],stateAttributesMapping:ot})}),OC={open:0,warm:!1,cooling:void 0},kC=600,AC=(0,J.createContext)(null);function jC(){let e=(0,J.useContext)(AC);if(!e)throw Error(`Tooltip parts must be used inside <Tooltip>`);return e}var MC=(0,J.forwardRef)(function({children:e,className:t,defaultOpen:n=!1,delayDuration:r=300,onOpenChange:i,open:a,side:o=`top`,...s},c){let u=(0,J.useRef)(null),[d,f]=(0,J.useState)(n),[p,m]=(0,J.useState)(!1),h=a??d;(0,J.useEffect)(()=>{if(h)return OC.open+=1,OC.warm=!0,clearTimeout(OC.cooling),()=>{--OC.open,!(OC.open>0)&&(OC.cooling=setTimeout(()=>{OC.warm=!1},kC))}},[h]);let g=`${(0,J.useId)()}-content`,_=(0,J.useRef)(null),v=()=>{_.current!==null&&(clearTimeout(_.current),_.current=null)},y=e=>{v(),a===void 0&&f(e),i?.(e)};return l(()=>{y(!1)}),(0,J.useEffect)(()=>v,[]),(0,X.jsx)(AC.Provider,{value:{arrivedWarm:p,cancelClose:v,contentId:g,open:h,scheduleClose:()=>{v(),h&&(_.current=setTimeout(()=>{y(!1)},0))},scheduleOpen:()=>{if(v(),h)return;let e=OC.warm;_.current=setTimeout(()=>{m(e),y(!0)},e?0:Math.max(0,r))},side:o,trigger:u},children:(0,X.jsx)($S,{open:h,onOpenChange:y,children:(0,X.jsx)(`span`,{...s,className:ft(`relative inline-flex`,t),ref:c,children:e})})})}),NC=(0,J.forwardRef)(function({asChild:e=!1,children:t,className:n,onBlur:r,onFocus:i,onPointerEnter:a,onPointerLeave:o,...s},c){let l=jC(),u=(0,J.useCallback)(e=>{l.trigger.current=e},[l.trigger]);(0,J.useImperativeHandle)(c,()=>l.trigger.current);let{"aria-describedby":d,...f}=s,p={...f,"aria-describedby":[d,l.open?l.contentId:void 0].filter(Boolean).join(` `)||void 0,"data-state":l.open?`open`:`closed`,onBlur:e=>{r?.(e),e.defaultPrevented||l.scheduleClose()},onFocus:e=>{i?.(e),e.defaultPrevented||l.scheduleOpen()},onPointerEnter:e=>{a?.(e),e.defaultPrevented||l.scheduleOpen()},onPointerLeave:e=>{o?.(e),e.defaultPrevented||l.scheduleClose()}};return e?(0,X.jsx)(re,{...p,className:ft(n),ref:u,children:t}):(0,X.jsx)(`button`,{...p,className:ft(`btn`,n),ref:u,type:s.type??`button`,children:t})}),PC=(0,J.forwardRef)(function({children:e,className:t,onPointerEnter:n,onPointerLeave:r,...i},a){let o=jC(),s=an(`tooltip`),[c,l]=(0,J.useState)(null);return(0,J.useImperativeHandle)(a,()=>c,[c]),(0,J.useLayoutEffect)(()=>{let e=c;if(!o.open||!e||!he(e))return;let t=dr(e),n=o.arrivedWarm?0:t.distance,r={bottom:`0 ${String(-n)}px`,left:`${String(n)}px 0`,right:`${String(-n)}px 0`,top:`0 ${String(n)}px`}[o.side],i=e.animate([{opacity:0,translate:r},{opacity:1,translate:`0 0`}],{duration:o.arrivedWarm?t.fast:t.normal,easing:Be(t,t.ease),composite:`add`});return()=>{i.cancel()}},[c,o.open,o.arrivedWarm,o.side]),!o.open||!s?null:(0,X.jsx)(iC,{container:s,children:(0,X.jsx)(EC,{anchor:o.trigger,side:o.side,sideOffset:8,collisionPadding:8,collisionBoundary:s===document.body?void 0:s,className:`pointer-events-auto z-(--stipe-layer-tooltip)`,children:(0,X.jsx)(DC,{...i,"aria-live":`polite`,className:ft(`pointer-events-auto max-w-(--container-xs) rounded-box bg-base-content px-md py-sm text-xs text-base-100 shadow-lg`,t),id:o.contentId,onPointerEnter:e=>{n?.(e),e.defaultPrevented||o.cancelClose()},onPointerLeave:e=>{r?.(e),e.defaultPrevented||o.scheduleClose()},ref:l,role:`tooltip`,children:e})})})}),FC=e=>String(e).padStart(2,`0`),IC=e=>new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime();function LC(e,t){let n=new Date(e),r=Math.round((IC(new Date(t))-IC(n))/864e5);return r<=0?`${FC(n.getHours())}:${FC(n.getMinutes())}`:r===1?`Yesterday`:`${String(n.getFullYear())}-${FC(n.getMonth()+1)}-${FC(n.getDate())}`}function RC(e,t){let n=e.replace(/\s+/gu,` `).trim();if(n.length<=t)return n;let r=n.slice(0,Math.max(0,t-1)),i=r.lastIndexOf(` `);return`${(i>t/2?r.slice(0,i):r).trimEnd()}…`}function zC(e,t,n,r){let i=new Map(t.map(e=>[e.providerId,e])),a=new Map(n.map((e,t)=>[e,t])),o=e=>i.has(e)?0:r===`login`&&a.has(e)?1:2,s=e=>r===`model`&&e===`fungi`;return[...new Map(e.map(e=>[e.id,e])).values()].sort((e,t)=>Number(s(t.id))-Number(s(e.id))||o(e.id)-o(t.id)||(o(e.id)<2?(a.get(e.id)??n.length)-(a.get(t.id)??n.length):0)||e.name.localeCompare(t.name)||e.id.localeCompare(t.id)).map(e=>{let t=e.methods.map(e=>e.kind===`api_key`?`API key`:`Subscription`),n=i.get(e.id),r=e.id===`fungi`?`Fungi account`:t.length>0?t.join(` or `):n?.type===`oauth`?`Subscription`:n?.type===`api_key`?`API key`:void 0,a={value:e.id,label:e.name,group:s(e.id)&&!i.has(e.id)?`Default`:o(e.id)===0?`Signed in`:o(e.id)===1?`Popular`:`More providers`};return r===void 0?a:{...a,description:r}})}function BC(e,t){return e.map(e=>({...e,methods:e.methods.filter(n=>t.policy.loginAllowed({providerId:e.id,method:n.kind,host:t.host,scope:t.scope}))})).filter(e=>e.methods.length>0).sort((e,t)=>e.name.localeCompare(t.name)||e.id.localeCompare(t.id))}var VC=Yr({providerId:Fi().min(1).max(200).optional(),method:Wr([`api_key`,`subscription`]).optional(),option:Fi().min(1).max(200).optional()});zi(Fi(),$r()).parse(structuredClone(Ar(VC)));var HC=Yr({providerId:Fi().min(1).max(200).optional()});zi(Fi(),$r()).parse(structuredClone(Ar(HC)));function UC(e,t){return e.kind===`api_key`?`Paste an API key you created`:`Sign in with your ${t.name} account`}async function WC(e,t,n){if(t!==void 0){let n=e.methods.find(e=>e.kind===t);if(n===void 0)throw new Se(`method_unavailable`,`${e.name} does not offer that sign-in method here.`);return n}let[r,...i]=e.methods;if(r!==void 0&&i.length===0)return r;let a=await n.prompt({type:`choice`,message:`How do you want to sign in to ${e.name}?`,summary:`You can add the other kind later.`,options:e.methods.map(t=>({value:t.kind,label:t.label,description:UC(t,e)}))}),o=e.methods.find(e=>e.kind===a);if(o===void 0)throw new Se(`method_unavailable`,`Choose a listed method.`);return o}async function GC(e,t,n,r={}){let i=await WC(t,r.method,n);n.notify({type:`progress`,message:`Signing in to ${t.name}…`}),await n.run(()=>e.login(r.option===void 0?{providerId:t.id,method:i.kind}:{providerId:t.id,method:i.kind,option:r.option},n))}var KC=ra(ya(da,{onExcessProperty:`error`})).schema;I.pipe(B(ca(/^[^/\s]+\/[^\s]+$/u)),B(U(513)));var qC=`default`,JC=new WeakMap,YC=256;function XC(e,t,n){return[...e].sort((e,r)=>{let i=t?.providerId===e.providerId?t:n.get(e.providerId),a=t?.providerId===r.providerId?t:n.get(r.providerId),o=e.id===i?.modelId;return o===(r.id===a?.modelId)?e.providerName.localeCompare(r.providerName):o?-1:1})}async function ZC(e,t,n){if(t.reasoning.length===0)return;let r=await e.prompt({type:`choice`,message:`Thinking level for ${t.name}`,summary:`How long the model thinks before it answers.`,current:n??qC,options:[{value:qC,label:`Model default`},...t.reasoning.map(e=>({value:e,label:e}))]});return t.reasoning.find(e=>e===r)}var QC=255;async function $C(e,t,n,r,i){if(n===void 0){let n=[...new Map(t.map(e=>[e.providerId,e.providerName]))].slice(0,QC),a=await e.prompt({type:`choice`,message:`Choose a provider`,summary:`Or follow the Agent's own model.`,current:i??qC,options:[{value:qC,label:`Use agent model`},...n.map(([e,t])=>({value:e,label:t}))]});if(a===qC)return null;let o=(await e.run(()=>r(e.signal))).filter(e=>e.providerId===a).slice(0,QC);if(o.length===0)throw new Se(`model_unavailable`,`That provider has no available models. Retry /model.`);return o}let{owner:a}=n,[o,s]=await Promise.all([a.access(e.signal),a.providers(e.signal).then(e=>BC(e,n))]),c=s.filter(e=>e.id===`fungi`);for(let e of new Map(t.map(e=>[e.providerId,e])).values()){let t=s.find(t=>t.id===e.providerId);c.some(t=>t.id===e.providerId)||(t?c.push(t):o.some(t=>t.providerId===e.providerId&&n.policy.loginAllowed({providerId:t.providerId,method:t.type===`oauth`?`subscription`:`api_key`,host:n.host,scope:n.scope}))&&c.push({id:e.providerId,name:e.providerName,methods:[]}))}let l=await e.prompt({type:`choice`,message:`Choose a provider`,summary:`Or follow the Agent's own model.`,current:i??qC,collapsedGroup:`More providers`,options:[{value:qC,label:`Use agent model`},...zC(c,o,a.popularProviderIds,`model`).slice(0,QC)]});if(l===qC)return null;let u=c.find(e=>e.id===l);if(!u)throw new Se(`provider_unavailable`,`Choose a listed provider.`);let d=t;o.some(e=>e.providerId===l)||(await GC(a,u,e),d=await e.run(()=>r(e.signal)));let f=d.filter(e=>e.providerId===l).slice(0,QC);if(f.length===0)throw new Se(`model_unavailable`,`${u.name} has no available models. Retry /model.`);return f}function ew(e,t){let n=JC.get(e.modelPreference.read)??new Map;JC.set(e.modelPreference.read,n);let r=e=>{if(e!==null&&(n.delete(e.providerId),n.set(e.providerId,e),n.size>YC)){let e=n.keys().next().value;e!==void 0&&n.delete(e)}},i=zi(Fi(),$r()).parse(KC),a=t.models.map(e=>({title:`${e.providerName} · ${e.name}`,properties:{providerId:{const:e.providerId},modelId:{const:e.id},reasoning:e.reasoning.length!==0&&{enum:[...e.reasoning]}}}));return[{id:`model`,title:`Model`,category:`Settings`,description:`Choose a model`,projections:{agent:{},palette:{},help:{},slash:{aliases:[`model`],consumesDraft:!0}},action:{inputSchema:{anyOf:[{type:`null`,title:`Use agent model`},a.length===0?{not:{}}:{allOf:[i,{oneOf:a}]}]},outputSchema:{anyOf:[{type:`null`},i]}},availability:t.availability??(()=>({status:`available`})),handler:async i=>{if(i.arguments===void 0){let a=i.interaction;if(i.origin===`agent`||a===void 0)return e.modelPreference.read();let o=await e.modelPreference.read();r(o);let s=await $C(a,t.models,t.account,t.refreshModels,o?.providerId);if(s===null)return await a.run(()=>e.modelPreference.set(null)),a.run(()=>e.modelPreference.read());let c=XC(s,o,n),l=c.findIndex(e=>e.providerId===o?.providerId&&e.id===o.modelId),u=await a.prompt({type:`choice`,message:`Choose a model`,summary:`Models from ${c[0]?.providerName??`this provider`}.`,current:l<0?void 0:String(l),options:c.map((e,t)=>({value:String(t),label:e.name}))}),d=c[Number(u)];if(d===void 0)throw new Se(`model_unavailable`,`Choose a listed model.`);let f=await ZC(a,d,(o?.providerId===d.providerId?o:n.get(d.providerId))?.reasoning),p=f===void 0?{providerId:d.providerId,modelId:d.id}:{providerId:d.providerId,modelId:d.id,reasoning:f};return await a.run(()=>e.modelPreference.set(p)),r(p),a.run(()=>e.modelPreference.read())}let a;try{a=Ya(i.arguments)}catch{throw new Se(`invalid_model_preference`,`Model preference arguments are invalid`)}if(a!==null){let e=a,n=(t.account===void 0?await t.refreshModels(i.signal??new AbortController().signal):t.models).find(t=>t.providerId===e.providerId&&t.id===e.modelId);if(n===void 0)throw new Se(`model_unavailable`,`That model is not in the current catalog`);if(e.reasoning!==void 0&&!n.reasoning.includes(e.reasoning))throw new Se(`reasoning_unavailable`,`That thinking level is not supported by this model`)}return await e.modelPreference.set(a),r(a),e.modelPreference.read()}},{id:`thinking`,title:`Thinking level`,category:`Settings`,description:`Choose thinking effort`,projections:{palette:{order:1},help:{},slash:{aliases:[`thinking`],consumesDraft:!0}},availability:t.availability??(()=>({status:`available`})),handler:async n=>{let r=n.interaction;if(r===void 0)throw new Se(`interaction_required`,`Choosing a thinking level needs a person.`);let i=await e.modelPreference.read(),a=t.models.find(e=>e.providerId===i?.providerId&&e.id===i.modelId);if(i===null||a===void 0)throw new Se(`model_required`,`Choose a model with /model before its thinking level.`);if(a.reasoning.length===0)throw new Se(`reasoning_unavailable`,`${a.name} has no thinking levels.`);let o=await ZC(r,a,i.reasoning),s=o===void 0?{providerId:a.providerId,modelId:a.id}:{providerId:a.providerId,modelId:a.id,reasoning:o};return await r.run(()=>e.modelPreference.set(s)),r.run(()=>e.modelPreference.read())}}]}var tw=(e,t)=>Math.min(t.baseMs===0?0:t.baseMs*2**Math.max(0,e-1),t.maxMs),nw=oo.check(ao(0),So(2**53-1)),rw=F({baseMs:nw,maxMs:nw,limit:V([F({maxAttempts:nw}),F({deadlineAt:nw})])}),iw=R(rw);function aw(e,t,n){return Math.min(t+tw(e,n),`deadlineAt`in n.limit?n.limit.deadlineAt:2**53-1)}function ow(e,t,n){let r=`maxAttempts`in n.limit?e>=n.limit.maxAttempts:t>=n.limit.deadlineAt,i=r?e:e+1;return{attempt:{count:i,status:r?`exhausted`:`admitted`,final:r||`maxAttempts`in n.limit&&i>=n.limit.maxAttempts},notBefore:aw(i,t,n)}}var sw=class extends Error{_tag=`WatchdogError`;cause;underlying;constructor(e,t){super(`Watchdog ${e.replaceAll(`_`,` `)}`),this.name=this._tag,this.cause=e,this.underlying=t}},cw=no({family:`watchdog`,version:1,kinds:{claim:{prefix:`watchdog_claim`}}});function lw(e){if(ta(e))return`execution_interrupted`;let t=Gi(e);return t._tag===`Some`?t.value.cause:`execution_defect`}var uw=(e,t)=>{let n=`idle`,r,i=`open`,a,o,s=yi(()=>{if(o!==void 0)return xo(o);let e=qi();o=e,i=`stopping`;let t=a;return r?.fiber.interruptUnsafe(),(t===void 0?Ci(void 0):xo(t)).pipe(Er(t=>(i=`stopped`,va(e,la(t,()=>void 0)))),Pr)}),c=t=>(e.executor.retryPolicy?.(t)??Ci(void 0)).pipe(Ri(e=>e===void 0?Ci(void 0):Li({try:()=>iw(e),catch:e=>new sw(`store_invalid`,e)}))),l=e=>t.ingest(e),u=e=>t.read(e).pipe(Cr(e=>e.status===`missing`?e:{status:`found`,job:e.job,cancellation:e.cancellation})),d=e=>t.readQueueHead(e),f=(e,n,r)=>t.readSettled(e,n,r),p=n=>t.recordCancellation(n).pipe(oi(t=>{if(t.status!==`recorded`&&t.status!==`replayed`)return Pi;let i=r;return i?.jobId===n.jobId?ci(()=>{i.fiber.interruptUnsafe()}):e.wake.recompute()})),m=n=>t.failLane(n).pipe(oi(t=>{let n=r,i=t.jobs.find(e=>e.jobId===n?.jobId);return n!==void 0&&i!==void 0&&(n.failed=i,n.fiber.interruptUnsafe()),t.jobs.length===0?Pi:e.wake.recompute()}),Cr(({jobs:e,more:t})=>({settled:e.length,more:t}))),h=e=>t.purgeQueued(e),g=()=>Li({try:()=>cw.claim.generate(),catch:()=>new sw(`claim_unavailable`)}).pipe(Ri(e=>t.selectAndClaim(e))),_=()=>fi(function*(){let n=yield*t.nextRunningClaim();if(n===void 0)return{status:`none`};let r=yield*Ai(e.isAlive(n.job));if(r._tag===`Failure`)return{status:`liveness_unknown`,jobId:n.job.jobId,reason:r.failure.cause};if(r.success)return{status:`none`};let i=yield*c(n.job),a=yield*t.reconcileDisappearedClaim({...n,requeue:i!==void 0||e.executor.replaySafe?.(n.job)===!0});switch(a.status){case`requeued`:return yield*e.wake.recompute(),{status:`none`};case`settled`:return yield*e.wake.recompute(),{status:`recovered`,job:a.job};case`conflict`:case`missing`:{let e=yield*t.read(n.job.jobId);return e.status===`found`&&(e.job.state!==`running`||e.claimToken!==n.claimToken||e.recoveryCount!==n.recoveryCount)?{status:`none`}:yield*ri(new sw(`settlement_rejected`))}}}),v=n=>t.finishCompletingClaim(n).pipe(Ri(t=>t.status===`settled`||t.status===`replayed`?e.wake.recompute().pipe(Di({status:`settled`,job:t.job})):ri(new sw(`settlement_rejected`))));return Object.freeze({close:s,wakeState:t.wakeState,ingest:l,read:u,readQueueHead:d,readSettled:f,tick:()=>yi(()=>{if(i!==`open`)return Ci({status:`stopped`});if(n!==`idle`)return Ci({status:`busy`});n=`running`;let o=qi();return a=o,fi(function*(){let n=yield*t.nextCompletingClaim();return n===void 0?yield*_().pipe(Ri(e=>e.status===`recovered`?Ci({status:`recovered`,job:e.job}):g().pipe(Cr(t=>t.status===`no_ready`&&e.status===`liveness_unknown`?e:t))),Ri(n=>n.status===`no_ready`?Ci({status:`no_ready`}):n.status===`liveness_unknown`?Ci(n):n.status===`claim_unavailable`?ri(new sw(`claim_unavailable`)):n.status===`cancelled`?e.wake.recompute().pipe(Di({status:`settled`,job:n.job})):n.status===`recovered`?Ci({status:`settled`,job:n.job}):fi(function*(){let a=yield*c(n.job),o=e.executor.replaySafe?.(n.job)===!0,s=yield*Yi(),l={started:!1},u=yield*_r(xo(s).pipe(qr(ci(()=>{l.started=!0})),qr(a===void 0?Ci(void 0):t.reserveAttempt({jobId:n.job.jobId,claimToken:n.claimToken,policy:a})),Ri(t=>e.executor.execute(n.job,t)))),d={jobId:n.job.jobId,fiber:u};r=d;let f=yield*t.read(n.job.jobId);i!==`open`||f.status!==`found`||f.job.state!==`running`||f.cancellation.status===`present`?(f.status===`found`&&f.job.state===`settled`&&f.job.outcome===`failed`&&(d.failed=f.job),yield*Hi(u)):yield*ua(s,void 0);let p=yield*ma(u).pipe(_i(ci(()=>{r?.fiber===u&&(r=void 0)})));if(d.failed!==void 0)return yield*e.wake.recompute().pipe(Di({status:`settled`,job:d.failed}));if(i!==`open`&&qa(p)){if(!(ta(p.cause)&&(!l.started||(yield*e.executor.isDrained?.(n.job)??Ci(!1)))))return yield*ri(new sw(`drain_failed`));let r=yield*t.handoffExactClaim({jobId:n.job.jobId,claimToken:n.claimToken});if(r.status===`requeued`)return yield*e.wake.recompute().pipe(Di({status:`stopped`}));if(r.status!==`cancelled`)return yield*ri(new sw(`settlement_rejected`))}let m=sa(p)?p.value:{kind:`failed`,reason:lw(p.cause)};if(a!==void 0&&(m.kind===`retry`||qa(p))||o&&qa(p)){let r={jobId:n.job.jobId,claimToken:n.claimToken};a!==void 0&&Object.assign(r,{policy:a});let i=yield*t.retryExactClaim(r);if(i.status===`requeued`&&o&&qa(p))return yield*Gr(p.cause);if(i.status===`requeued`)return yield*e.wake.recompute().pipe(Di({status:`requeued`,jobId:n.job.jobId}));if(i.status===`conflict`)return yield*ri(new sw(`settlement_rejected`))}switch((yield*t.recordExecutionDecision({jobId:n.job.jobId,claimToken:n.claimToken,decision:m.kind===`retry`?{kind:`failed`,reason:`retry_policy_missing`}:m})).status){case`recorded`:case`replayed`:return yield*v({jobId:n.job.jobId,claimToken:n.claimToken});case`conflict`:case`missing`:return yield*ri(new sw(`settlement_rejected`))}}))):yield*v({jobId:n.job.jobId,claimToken:n.claimToken})}).pipe(Er(e=>(n=`idle`,a=void 0,va(o,la(e,()=>void 0)))))}),cancel:p,failLane:m,purge:h})};function dw(e,t,n,r){if(e===void 0)return{kind:`interrupted`};let i=e.windowMs!==void 0&&n!==null&&r-n>=e.windowMs,a=i?0:t;return a>=e.maxRecoveries?{kind:`interrupted`}:{kind:`requeue`,recoveryCount:a+1,windowStartedAt:e.windowMs===void 0?null:i||n===null?r:n}}var fw=I.check(q(1),U(512)),pw=I.check(q(1),U(256)),mw=oo.check(ao(-(2**53-1)),So(2**53-1)),hw=oo.check(ao(0),So(2**53-1)),gw=I.check(q(1),U(200)),_w=F({lane:fw,reason:gw});function vw(e){try{return R(_w,{onExcessProperty:`error`})(e)}catch(e){throw new sw(`store_invalid`,e)}}var yw=F({sequence:oo,job_id:pw,queue_name:pw,lane:fw,priority:mw,payload_json:I,not_before:hw,attempt_count:hw,recovery_max:Ki(hw),recovery_window_ms:Ki(hw),recovery_window_started_at:Ki(hw),state:W([`queued`,`running`,`completing`,`settled`]),outcome:Ki(W([`completed`,`failed`,`cancelled`,`outcome_unknown`,`interrupted`])),claim_token:Ki(pw),recovery_count:hw,cancellation_id:Ki(pw),failure_reason:Ki(gw)}),bw=pa(Xi),xw=ba(yw,{onExcessProperty:`error`}),Sw=ba(bw),Cw=wa(bw);function ww(e){return e===void 0?{predicate:`1 = 1`,values:[]}:{predicate:e.include?`lane = ?`:`lane <> ?`,values:[e.lane]}}var Tw=`sequence, job_id, queue_name, lane, priority, payload_json, not_before, attempt_count,
25
- recovery_max, recovery_window_ms, recovery_window_started_at, state, outcome, claim_token, recovery_count,
26
- cancellation_id, failure_reason`,Ew=`(cancellation_id IS NOT NULL OR NOT EXISTS (
27
- SELECT 1 FROM watchdog_jobs predecessor
28
- WHERE predecessor.queue_name = watchdog_jobs.queue_name
29
- AND predecessor.state IN ('queued', 'running', 'completing')
30
- AND (predecessor.state IN ('running', 'completing') OR
31
- (predecessor.state = 'queued' AND
32
- (predecessor.priority > watchdog_jobs.priority OR
33
- (predecessor.priority = watchdog_jobs.priority AND
34
- predecessor.sequence < watchdog_jobs.sequence))))))`,Dw=F({pending:W([0,1]),next_wake_at:Ki(hw)}),Ow=R(hw);function kw(e){let t=R(Dw)(e);return{pending:t.pending===1,nextWakeAt:t.next_wake_at}}function Aw(e,t){return Ow(t),kw(e.sql.exec(`SELECT
35
- COALESCE(MAX(CASE WHEN state IN ('running','completing') OR cancellation_id IS NOT NULL OR not_before <= ? THEN 1 ELSE 0 END),0) AS pending,
36
- MIN(CASE WHEN state='queued' AND cancellation_id IS NULL AND not_before > ? THEN not_before END) AS next_wake_at
37
- FROM watchdog_jobs WHERE state IN ('running','completing') OR (state='queued' AND ${Ew})`,t,t).toArray()[0])}function jw(e){return new sw(`store_unavailable`,e)}function Mw(e){return Li({try:e,catch:e=>e instanceof sw?e:jw(e)})}function Nw(e){let t=Cw(e);if(t._tag===`Failure`)throw jw(Sa(t.cause));return t.value}function Pw(e){let t=xw(e);if(t._tag===`Failure`)throw jw(Sa(t.cause));let n=t.value,r=Sw(n.payload_json);if(r._tag===`Failure`)throw jw(Sa(r.cause));let i={jobId:n.job_id,queue:n.queue_name,lane:n.lane,priority:n.priority,payload:r.value};if(n.not_before!==0&&(i={...i,notBefore:n.not_before}),n.recovery_max!==null){let e=n.recovery_window_ms===null?{maxRecoveries:n.recovery_max}:{maxRecoveries:n.recovery_max,windowMs:n.recovery_window_ms};i={...i,recovery:e}}if(n.state===`queued`)return{row:n,job:{...i,state:`queued`}};if(n.state===`running`){if(n.claim_token===null)throw jw();return{row:n,job:{...i,state:`running`}}}if(n.outcome===null)throw jw();let a={...i,state:n.state,outcome:n.outcome};return{row:n,job:(n.outcome===`failed`||n.outcome===`interrupted`)&&n.failure_reason!==null?{...a,failureReason:n.failure_reason}:a}}function Fw(e,t){let n=e.sql.exec(`SELECT ${Tw}
38
- FROM watchdog_jobs
39
- WHERE job_id = ?`,t).toArray()[0];return n===void 0?void 0:Pw(n)}function Iw(e,t,n,r,i){let a=ww(r),o=i===void 0?a:{predicate:`${a.predicate} AND lane = ?`,values:[...a.values,R(fw)(i)]};return e.sql.exec(`SELECT ${Tw} FROM watchdog_jobs NOT INDEXED WHERE state = 'settled' AND ${o.predicate} AND sequence > ?
40
- AND sequence < COALESCE(
41
- (SELECT MIN(sequence) FROM watchdog_jobs INDEXED BY idx_watchdog_ready
42
- WHERE state IN ('queued', 'running', 'completing') AND ${o.predicate}),
43
- 9223372036854775807)
44
- ORDER BY sequence ASC LIMIT ?`,...o.values,n??0,...o.values,t).toArray().map(e=>{let t=Pw(e);if(t.job.state!==`settled`)throw jw();return{sequence:t.row.sequence,job:t.job}})}function Lw(e,t){let n=e.sql.exec(`SELECT ${Tw}
45
- FROM watchdog_jobs
46
- WHERE queue_name = ? AND state IN ('running', 'completing', 'queued')
47
- ORDER BY CASE state WHEN 'queued' THEN 1 ELSE 0 END,
48
- priority DESC, sequence ASC
49
- LIMIT 1`,t).toArray()[0];if(n===void 0)return{state:`idle`};let r=Pw(n);if(r.job.state===`settled`)throw jw();return{state:r.job.state===`completing`?`running`:r.job.state,jobId:r.job.jobId,cancellationRequested:r.row.cancellation_id!==null}}function Rw(e,t){let n=e.sql.exec(`SELECT ${Tw}
50
- FROM watchdog_jobs
51
- WHERE queue_name = ? AND state = 'settled'
52
- ORDER BY sequence DESC
53
- LIMIT 1`,t).toArray()[0];if(n===void 0)return;let r=Pw(n);if(r.job.state!==`settled`)throw jw();return r.job}function zw(e,t,n,r){if(t===void 0)return;let i=Lw(e,n);t(r===void 0?{queue:n,head:i}:{queue:n,head:i,settled:r})}function Bw(e){e.transactionSync(()=>{if(e.sql.exec(`
54
- CREATE TABLE IF NOT EXISTS watchdog_jobs (
55
- sequence INTEGER PRIMARY KEY AUTOINCREMENT,
56
- job_id TEXT UNIQUE NOT NULL,
57
- queue_name TEXT NOT NULL,
58
- lane TEXT NOT NULL,
59
- priority INTEGER NOT NULL,
60
- payload_json TEXT NOT NULL,
61
- not_before INTEGER NOT NULL DEFAULT 0 CHECK (not_before >= 0),
62
- attempt_count INTEGER NOT NULL DEFAULT 0 CHECK (attempt_count >= 0),
63
- recovery_max INTEGER,
64
- recovery_window_ms INTEGER CHECK (recovery_window_ms IS NULL OR recovery_window_ms > 0),
65
- recovery_window_started_at INTEGER,
66
- state TEXT NOT NULL CHECK (state IN ('queued', 'running', 'completing', 'settled')),
67
- outcome TEXT CHECK (
68
- outcome IS NULL OR outcome IN (
69
- 'completed', 'failed', 'cancelled', 'outcome_unknown', 'interrupted'
70
- )
71
- ),
72
- claim_token TEXT,
73
- recovery_count INTEGER NOT NULL DEFAULT 0,
74
- cancellation_id TEXT UNIQUE,
75
- failure_reason TEXT,
76
- CHECK (recovery_max IS NULL OR recovery_max >= 0),
77
- CONSTRAINT watchdog_execution_state CHECK (
78
- (state = 'queued' AND outcome IS NULL AND claim_token IS NULL) OR
79
- (state = 'running' AND outcome IS NULL AND claim_token IS NOT NULL) OR
80
- (state = 'completing' AND outcome IS NOT NULL AND claim_token IS NOT NULL) OR
81
- (state = 'settled' AND outcome IS NOT NULL)
82
- )
83
- )
84
- `),e.sql.exec(`SELECT 1 AS current FROM sqlite_schema WHERE name = 'watchdog_jobs' AND instr(sql, 'watchdog_execution_state') > 0`).toArray().length!==1)throw new sw(`store_invalid`,Error(`Obsolete Watchdog execution schema`));try{e.sql.exec(`SELECT ${Tw} FROM watchdog_jobs LIMIT 0`)}catch(e){throw new sw(`store_invalid`,e)}e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_watchdog_lane_failure
85
- ON watchdog_jobs(lane, state DESC, sequence ASC)`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_watchdog_ready
86
- ON watchdog_jobs(state, not_before, priority DESC, sequence ASC)`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_watchdog_queue_head
87
- ON watchdog_jobs(queue_name, state, priority DESC, sequence ASC)`)})}function Vw(e,t,n){let r=Nw(n.payload),i=Fw(e,n.jobId);if(i!==void 0){let e=i.job.recovery?.maxRecoveries,t=n.recovery?.maxRecoveries;if(i.job.queue!==n.queue||i.job.lane!==n.lane||i.job.priority!==n.priority||i.row.payload_json!==r||e!==t||i.job.recovery?.windowMs!==n.recovery?.windowMs)throw jw();return!1}return e.sql.exec(`INSERT INTO watchdog_jobs
88
- (job_id, queue_name, lane, priority, payload_json, recovery_max, recovery_window_ms, not_before,
89
- state, outcome, claim_token, recovery_count, cancellation_id)
90
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'queued', NULL, NULL, 0, NULL)`,n.jobId,n.queue,n.lane,n.priority,r,n.recovery?.maxRecoveries??null,n.recovery?.windowMs??null,n.notBefore??0),zw(e,t,n.queue),!0}function Hw(e,t,n){let r=Fw(e,n.jobId);return r===void 0?{status:`missing`}:r.job.state===`completing`||r.job.state===`settled`?{status:`decided`,outcome:r.job.outcome}:r.row.cancellation_id===null?n.onlyIfQueued===!0&&r.job.state!==`queued`?{status:`conflict`}:(e.sql.exec(`UPDATE watchdog_jobs
91
- SET cancellation_id = ?
92
- WHERE job_id = ? AND cancellation_id IS NULL`,n.cancellationId,n.jobId),zw(e,t,r.job.queue),{status:`recorded`,intent:n}):r.row.cancellation_id===n.cancellationId?{status:`replayed`,intent:n}:{status:`conflict`}}function Uw(e,t,n,r){let i=ww(r);return e.transactionSync(()=>{let r=e.sql.exec(`SELECT ${Tw}
93
- FROM watchdog_jobs
94
- WHERE state = 'queued' AND ${i.predicate}
95
- AND (cancellation_id IS NOT NULL OR not_before <= ?)
96
- AND ${Ew}
97
- ORDER BY priority DESC, sequence ASC
98
- LIMIT 1`,...i.values,Date.now()).toArray()[0];if(r===void 0)return{status:`no_ready`};let a=Pw(r);if(a.job.state!==`queued`)return{status:`claim_unavailable`};if(a.row.cancellation_id!==null){e.sql.exec(`UPDATE watchdog_jobs
99
- SET state = 'settled', outcome = 'cancelled'
100
- WHERE job_id = ? AND state = 'queued' AND cancellation_id = ?`,a.job.jobId,a.row.cancellation_id);let n=Fw(e,a.job.jobId)?.job;return n?.state!==`settled`||n.outcome!==`cancelled`?{status:`claim_unavailable`}:(zw(e,t,n.queue,n),{status:`cancelled`,job:n})}e.sql.exec(`UPDATE watchdog_jobs
101
- SET state = 'running', claim_token = ?
102
- WHERE job_id = ? AND state = 'queued'`,n,a.job.jobId);let o=Fw(e,a.job.jobId)?.job;return o?.state===`running`?(zw(e,t,o.queue),{status:`claimed`,job:o,claimToken:n}):{status:`claim_unavailable`}})}function Ww(e,t){return e.transactionSync(()=>{let n=Fw(e,t.jobId);if(n===void 0)return{status:`missing`};let r=n.row.cancellation_id===null?t.decision.kind:`cancelled`;if(n.job.state===`completing`||n.job.state===`settled`)return n.row.claim_token===t.claimToken&&n.job.outcome===r?{status:`replayed`,job:n.job}:{status:`conflict`};if(n.job.state!==`running`||n.row.claim_token!==t.claimToken)return{status:`conflict`};e.sql.exec(`UPDATE watchdog_jobs SET state = 'completing', outcome = ?, failure_reason = ?
103
- WHERE job_id = ? AND state = 'running' AND claim_token = ?`,r,r===`failed`&&t.decision.kind===`failed`?t.decision.reason??null:null,t.jobId,t.claimToken);let i=Fw(e,t.jobId)?.job;return i?.state===`completing`?{status:`recorded`,job:i}:{status:`conflict`}})}function Gw(e,t,n){return e.transactionSync(()=>{let r=Fw(e,n.jobId);if(r===void 0)return{status:`missing`};if(r.row.claim_token!==n.claimToken)return{status:`conflict`};if(r.job.state===`settled`)return{status:`replayed`,job:r.job};if(r.job.state!==`completing`)return{status:`conflict`};e.sql.exec(`UPDATE watchdog_jobs SET state = 'settled' WHERE job_id = ? AND state = 'completing' AND claim_token = ?`,n.jobId,n.claimToken);let i=Fw(e,n.jobId)?.job;return i?.state===`settled`?(zw(e,t,i.queue,i),{status:`settled`,job:i}):{status:`conflict`}})}function Kw(e,t,n){Bw(e);let r=Object.freeze({wakeState:t=>Aw(e,t),readJob:t=>{let n=Fw(e,t);return n===void 0?void 0:{state:n.row.state,notBefore:n.row.not_before}},expediteQueuedJob:(t,n)=>(Ow(n),e.sql.exec(`UPDATE watchdog_jobs SET not_before=? WHERE job_id=? AND state='queued' AND not_before>? RETURNING job_id`,n,t,n).toArray().length===1),readQueueHead:t=>Lw(e,t),readLatestSettledJob:t=>Rw(e,t),enqueueAcceptedJob:n=>{Vw(e,t,n)},recordCancellationIntent:n=>Hw(e,t,n)}),i=n=>{let r=ww(n);return Object.freeze({wakeState:t=>Mw(()=>Aw(e,t)),ingest:n=>Mw(()=>e.transactionSync(()=>({status:Vw(e,t,n)?`queued`:`duplicate`}))),read:t=>Mw(()=>{let n=Fw(e,t);return n===void 0?{status:`missing`}:{status:`found`,job:n.job,claimToken:n.row.claim_token,recoveryCount:n.row.recovery_count,cancellation:n.row.cancellation_id===null?{status:`absent`}:{status:`present`,cancellation:{jobId:t,cancellationId:n.row.cancellation_id}}}}),readQueueHead:t=>Mw(()=>Lw(e,t)),readSettled:(t,r,i)=>Mw(()=>Iw(e,t,r,n,i)),selectAndClaim:r=>Mw(()=>Uw(e,t,r,n)),reserveAttempt:t=>Mw(()=>e.transactionSync(()=>{let n=Fw(e,t.jobId);if(n?.job.state!==`running`||n.row.claim_token!==t.claimToken||n.row.cancellation_id!==null)throw new sw(`claim_unavailable`);let r=ow(n.row.attempt_count,Date.now(),t.policy);return e.sql.exec(`UPDATE watchdog_jobs SET attempt_count=?, not_before=? WHERE job_id=? AND state='running' AND claim_token=?`,r.attempt.count,r.notBefore,t.jobId,t.claimToken),r.attempt})),retryExactClaim:n=>Mw(()=>e.transactionSync(()=>{let r=Fw(e,n.jobId);if(r?.job.state!==`running`||r.row.claim_token!==n.claimToken)return{status:`conflict`};if(r.row.cancellation_id!==null)return{status:`cancelled`};let i=n.policy===void 0?r.row.not_before:aw(r.row.attempt_count,Date.now(),n.policy);return e.sql.exec(`UPDATE watchdog_jobs SET state='queued', claim_token=NULL, not_before=? WHERE job_id=? AND state='running' AND claim_token=?`,i,n.jobId,n.claimToken),zw(e,t,r.job.queue),{status:`requeued`}})),recordExecutionDecision:t=>Mw(()=>Ww(e,t)),nextCompletingClaim:()=>Mw(()=>{let t=e.sql.exec(`SELECT ${Tw} FROM watchdog_jobs WHERE state = 'completing' AND ${r.predicate} ORDER BY sequence LIMIT 1`,...r.values).toArray()[0];if(t===void 0)return;let n=Pw(t);if(n.job.state!==`completing`||n.row.claim_token===null)throw jw();return{job:n.job,claimToken:n.row.claim_token}}),finishCompletingClaim:n=>Mw(()=>Gw(e,t,n)),recordCancellation:n=>Mw(()=>e.transactionSync(()=>{let r=Hw(e,t,n);return r.status===`decided`?r:{status:r.status}})),failLane:n=>Mw(()=>{let r=vw(n);return e.transactionSync(()=>{let n=e.sql.exec(`SELECT ${Tw} FROM watchdog_jobs
104
- WHERE lane = ? AND state IN ('queued', 'running', 'completing')
105
- ORDER BY state DESC, sequence ASC LIMIT ?`,r.lane,256).toArray(),i=[];for(let a of n){let n=Pw(a);e.sql.exec(`UPDATE watchdog_jobs SET state = 'settled', outcome = 'failed', failure_reason = ?, claim_token = NULL
106
- WHERE job_id = ? AND state IN ('queued', 'running', 'completing')`,r.reason,n.job.jobId);let o=Fw(e,n.job.jobId)?.job;if(o?.state!==`settled`||o.outcome!==`failed`)throw jw();zw(e,t,o.queue,o),i.push(o)}return{jobs:i,more:e.sql.exec(`SELECT 1 FROM watchdog_jobs WHERE lane = ? AND state IN ('queued', 'running', 'completing') LIMIT 1`,r.lane).toArray().length!==0}})}),purgeQueued:n=>Mw(()=>{e.transactionSync(()=>{e.sql.exec(`DELETE FROM watchdog_jobs
107
- WHERE queue_name = ? AND state = 'queued'`,n),zw(e,t,n)})}),handoffExactClaim:n=>Mw(()=>e.transactionSync(()=>{let r=Fw(e,n.jobId);return r===void 0?{status:`missing`}:r.job.state!==`running`||r.row.claim_token!==n.claimToken?{status:`conflict`}:r.row.cancellation_id===null?(e.sql.exec(`UPDATE watchdog_jobs SET state = 'queued', claim_token = NULL WHERE job_id = ? AND state = 'running' AND claim_token = ?`,n.jobId,n.claimToken),zw(e,t,r.job.queue),{status:`requeued`}):{status:`cancelled`}})),nextRunningClaim:()=>Mw(()=>{let t=e.sql.exec(`SELECT ${Tw}
108
- FROM watchdog_jobs
109
- WHERE state = 'running' AND ${r.predicate}
110
- ORDER BY sequence ASC
111
- LIMIT 1`,...r.values).toArray()[0];if(t===void 0)return;let n=Pw(t);if(n.job.state!==`running`||n.row.claim_token===null)throw jw();return{job:n.job,claimToken:n.row.claim_token,recoveryCount:n.row.recovery_count}}),reconcileDisappearedClaim:n=>Mw(()=>e.transactionSync(()=>{let r=Fw(e,n.job.jobId);if(r===void 0)return{status:`missing`};if(r.job.state!==`running`||r.row.claim_token!==n.claimToken||r.row.recovery_count!==n.recoveryCount)return{status:`conflict`};let i=n.requeue?{kind:`requeue`,recoveryCount:r.row.recovery_count,windowStartedAt:r.row.recovery_window_started_at}:dw(r.job.recovery,r.row.recovery_count,r.row.recovery_window_started_at,Date.now());if(i.kind===`requeue`&&r.row.cancellation_id===null)return e.sql.exec(`UPDATE watchdog_jobs
112
- SET state = 'queued', claim_token = NULL,
113
- recovery_count = ?, recovery_window_started_at = ?
114
- WHERE job_id = ? AND state = 'running' AND claim_token = ?`,i.recoveryCount,i.windowStartedAt,n.job.jobId,n.claimToken),zw(e,t,n.job.queue),{status:`requeued`};let a=r.row.cancellation_id!==null,o=a?null:r.job.recovery===void 0?`Execution disappeared without a recovery policy`:`Restart recovery budget exhausted (${String(r.job.recovery.maxRecoveries)} recoveries)`;e.sql.exec(`UPDATE watchdog_jobs
115
- SET state = 'settled', outcome = ?, failure_reason = ?
116
- WHERE job_id = ? AND state = 'running' AND claim_token = ?`,a?`cancelled`:`interrupted`,o,n.job.jobId,n.claimToken);let s=Fw(e,n.job.jobId)?.job;return s?.state===`settled`?(zw(e,t,s.queue,s),{status:`settled`,job:s}):{status:`conflict`}}))})};return Object.freeze({store:i(n),partition:i,transactional:r})}var qw=I.check(q(1),U(256)),Jw=I.check(q(1),U(200)),Yw=oo.check(ao(-(2**53-1)),So(2**53-1)),Xw=oo.check(ao(0),So(2**53-1)),Zw=F({maxRecoveries:Xw,windowMs:H(oo.check(_o(0),So(2**53-1)))}),Qw={jobId:qw,queue:qw,lane:fw,priority:Yw,payload:Xi,notBefore:H(Xw),recovery:z(Zw)},$w=F({...Qw,state:K(`queued`)}),eT=W([`completed`,`failed`,`cancelled`,`outcome_unknown`,`interrupted`]),tT={...Qw,outcome:eT,failureReason:H(Jw)},nT=F({...tT,state:K(`completing`)}),rT=F({...tT,state:K(`settled`)}),iT=F({...Qw,state:K(`running`)}),aT=V([$w,iT,nT,rT]);V([F({kind:K(`retry`)}),F({kind:K(`completed`)}),F({kind:K(`failed`),reason:H(Jw)}),F({kind:K(`cancelled`)}),F({kind:K(`outcome_unknown`)})]);var oT=F({jobId:qw,cancellationId:qw,onlyIfQueued:z(vo)}),sT=V([F({status:K(`absent`)}),F({status:K(`present`),cancellation:oT})]);V([F({status:K(`found`),job:aT,cancellation:sT}),F({status:K(`missing`)})]),V([F({state:K(`idle`)}),F({state:W([`queued`,`running`]),jobId:qw,cancellationRequested:vo})]),V([F({status:K(`queued`)}),F({status:K(`duplicate`)})]),V([F({status:K(`decided`),outcome:eT}),F({status:W([`recorded`,`replayed`])}),F({status:W([`conflict`,`missing`])})]);var cT=V([Vi(ArrayBuffer),I,bo,ga]);_a(I,cT);function lT(e){return Li({try:()=>{let t=e.concurrentLane===void 0?void 0:R(fw)(e.concurrentLane),n=Kw(e.owner,e.project,t===void 0?void 0:{lane:t,include:!1}),r=uw(e,n.store),i={...r,transactional:n.transactional};if(t===void 0)return Object.freeze(i);let a=uw(e,n.partition({lane:t,include:!0}));return Object.freeze({...i,tickConcurrent:a.tick,close:li([si(r.close),si(a.close)],{concurrency:2}).pipe(Ri(e=>{let t=e.find(qa);return t===void 0?Pi:Gr(t.cause)})),failLane:e=>e.lane===t?a.failLane(e):r.failLane(e),cancel:e=>r.read(e.jobId).pipe(Ri(n=>n.status===`found`&&n.job.lane===t?a.cancel(e):r.cancel(e)))})},catch:e=>e instanceof sw?e:new sw(`store_unavailable`,e)})}var uT=e=>({owner:e.owner,project:e.project,isAlive:t=>Xr({try:()=>e.isAlive(t),catch:e=>new sw(`liveness_unavailable`,e)}),executor:{retryPolicy:t=>{let n=e.retryPolicy;return n===void 0?Ci(void 0):Xr({try:()=>n(t),catch:e=>new sw(`execution_failed`,e)})},execute:(t,n)=>Xr({try:r=>e.execute(t,r,n),catch:()=>new sw(`execution_failed`)})},wake:{recompute:()=>Xr({try:()=>e.wake.recompute(),catch:()=>new sw(`wake_unavailable`)})}}),dT=e=>di(e).then(e=>{if(sa(e))return e.value;let t=ui(Gi(e.cause))??Sa(e.cause);return Promise.reject(t instanceof Error?t:Error(String(t)))});function fT(e){let t=uT(e);return e.concurrentLane===void 0?dT(lT(t)).then(pT):dT(lT({...t,concurrentLane:e.concurrentLane})).then(e=>Object.freeze({...pT(e),tickConcurrent:()=>dT(e.tickConcurrent())}))}function pT(e){return Object.freeze({wakeState:t=>dT(e.wakeState(t)),ingest:t=>dT(e.ingest(t)),read:t=>dT(e.read(t)),readQueueHead:t=>dT(e.readQueueHead(t)),tick:()=>dT(e.tick()),cancel:t=>dT(e.cancel(t)),failLane:t=>dT(e.failLane(t)),purge:t=>dT(e.purge(t)),transactional:e.transactional})}Object.freeze({make:fT});function mT(e){return Ur(()=>Eo(()=>import(`./runtime-core-DDK2YKwN.js`).then(e=>e.t),__vite__mapDeps([0,1,2,3,4,5,6]))).pipe(Ri(({openRuntimeCore:t})=>t(e)),Cr(({agent:e})=>e))}Object.freeze({module:Ua,operation:Ba,gate:ka}),ea(go),R(pa(go));var hT=class extends kr()(`@fungi.computer/shiitake/ExtensionRead`){},gT=class extends kr()(`@fungi.computer/shiitake/ExtensionTx`){},_T=class extends $i(`ExtensionStateError`){},vT=class extends $i(`AdmissionError`){},yT=class extends $i(`ExtensionCommandError`){},bT=class extends $i(`ExtensionStop`){};$i(`ExtensionActivationError`),R(Wa),R(ja),Fa(I);function xT(e){try{e.release?.()}catch(e){Da(`late-instruction-release`,e)}}function ST(e,t,n){return hi((r,i)=>{if(i.aborted)return;let a;try{a=Promise.resolve(e(i))}catch{r(ri(t()));return}let o=a.then(e=>{i.aborted?xT(e):r(Ci(e))},e=>{i.aborted?Da(`late-instruction-acquisition`,e):r(ri(t()))});return ci(()=>{n?.(o)})})}var CT=W([`Error`,`TypeError`,`RangeError`,`SyntaxError`,`ReferenceError`,`URIError`,`EvalError`,`AggregateError`,`AbortError`,`TimeoutError`]),wT=W([`EACCES`,`EPERM`,`ENOENT`,`EISDIR`,`ENOTDIR`,`EIO`,`EMFILE`,`ENFILE`,`ELOOP`,`ENOSPC`,`EROFS`,`ECONNRESET`,`ECONNREFUSED`,`ETIMEDOUT`,`ENOTFOUND`,`EAI_AGAIN`]);function TT(e){if(e instanceof Ji)return e;let t=e instanceof Error?Fa(CT)(e.name)?e.name:`OtherError`:`NonErrorThrown`,n=e instanceof Error&&`code`in e?e.code:void 0,r=Fa(wT)(n)?{errorName:t,errorCode:n}:{errorName:t};return Da(`model-acquisition`,e,r),new Ji(`model`,`rejected`,`Model acquisition failed`,void 0,e)}function ET(e){return new Ji(`model`,`rejected`,`Model release failed`,void 0,e)}function DT(e){let t=Xr({try:()=>e.release(),catch:ET}),n={model:e.model,release:t,retryable:e.retryable};return e.failureReason!==void 0&&(n={...n,failureReason:e.failureReason}),e.providerError!==void 0&&(n={...n,providerError:e.providerError}),e.rejection!==void 0&&(n={...n,rejection:e.rejection}),e.stream===void 0?e.retryAfterMs===void 0?Object.freeze(n):Object.freeze({...n,retryAfterMs:e.retryAfterMs}):e.retryAfterMs===void 0?Object.freeze({...n,stream:e.stream}):Object.freeze({...n,stream:e.stream,retryAfterMs:e.retryAfterMs})}function OT(e){return hi((t,n)=>{if(n.aborted)return;let r;try{r=Promise.resolve(e(n))}catch(e){t(ri(TT(e)));return}let i=r.then(e=>{if(n.aborted)return Promise.resolve(e.release()).then(()=>void 0);t(Ci(DT(e)))},e=>{n.aborted?Da(`late-model-acquisition`,e):t(ri(TT(e)))});return Xr({try:()=>i,catch:ET}).pipe(Vr)})}function kT(e){let t,n=gr(n=>Ri(n(e),e=>ci(()=>(t=e,e))));return ki(n,()=>t===void 0?Pi:t.release.pipe(Vr),{interruptible:!0})}function AT(e){let t=({sessionId:t,preference:n})=>OT(r=>e.acquire({sessionId:t,preference:n,signal:r})),n=e.describe;return Object.freeze(n===void 0?{acquire:t}:{acquire:t,describe:({sessionId:e,preference:t})=>Xr({try:r=>n({sessionId:e,preference:t,signal:r}),catch:TT})})}function jT(e,t){return new Ji(e,`rejected`,t)}var MT=I.pipe(B(q(1)),B(U(256))),NT=I.pipe(B(q(1)),B(L(e=>new TextEncoder().encode(e).byteLength<=32e3))),PT=F({revision:MT,text:NT,modules:H(ha(e=>Array.isArray(e)&&e.every(Ii)))}),FT=ha(e=>ai(e)),IT=ha(e=>ai(e)),LT=F({bind:FT}),RT=ha(e=>ai(e)),zT=F({commit:RT,requestWake:IT,close:IT}),BT=F({close:IT}),VT=Qi(PT),HT=Qi(LT),UT=Qi(zT),WT=Qi(BT);function GT(e){return new Ji(`runtime`,`invalid`,`Runtime host is invalid`,void 0,e)}function KT(){return new Ji(`runtime`,`unavailable`,`Runtime host is unavailable`)}function qT(e,t){return Li({try:()=>t.call(e),catch:KT}).pipe(Ri(e=>Xr({try:()=>Promise.resolve(e),catch:KT})),Ri(e=>e===void 0?Pi:ri(GT())))}function JT(e,t,n){let r=WT({close:t});return r._tag===`Failure`?ri(GT(n)):Pr(qT(e,r.success.close)).pipe(Lr({onFailure:e=>ri(GT({cause:n,cleanup:e})),onSuccess:()=>ri(GT(n))}))}function YT(e){return yi(()=>{if(!Ii(e))return ri(GT());let t=e,n;try{n=t.close}catch(e){return ri(GT(e))}let r;try{r=t.requestWake}catch(e){return JT(t,n,e)}let i=UT({commit:t.commit,requestWake:r,close:n});return i._tag===`Failure`?JT(t,n):Ci(Object.freeze({commit:e=>Xr({try:()=>t.commit(()=>io(e)),catch:e=>e instanceof Ji?e:KT()}),requestWake:qT(t,i.success.requestWake),close:qT(t,i.success.close)}))})}function XT(e){return Li({try:()=>{let t=e.runtime;if(!Ii(t))throw GT();let n=HT(t);if(n._tag===`Failure`)throw GT();return{receiver:t,bind:n.success.bind}},catch:GT}).pipe(Cr(({receiver:e,bind:t})=>Object.freeze({bind:({reconcile:n,reconcileHost:r,pendingWork:i})=>Li({try:()=>t.call(e,{reconcile:()=>io(n),reconcileHost:r===void 0?void 0:()=>io(r),pendingWork:()=>io(i)}),catch:KT}).pipe(Ri(e=>Xr({try:()=>Promise.resolve(e),catch:KT})),Ri(YT))})))}function ZT(e){return{lane:e.lane,open:t=>{let n=e.open({transactional:t.transactional,readJob:e=>io(t.read(e)),tickConcurrent:()=>io(t.tickConcurrent())});return{retryPolicy:e=>{let t=n.retryPolicy;return t===void 0?Ci(void 0):Xr({try:()=>t(e),catch:e=>new sw(`execution_failed`,e)})},execute:(e,t)=>Xr({try:r=>n.execute(e,r,t),catch:e=>new sw(`execution_failed`,e)})}}}}function QT(e,t){let n={store:e.store,runtime:t,extensions:e.extensions,instructions:{load:({sessionId:t,commandId:n,track:r})=>ST(r=>e.instructions.load({sessionId:t,commandId:n,signal:r}),()=>jT(`instructions`,`Instruction acquisition failed`),r).pipe(Ri(e=>{let t=VT(e);return t._tag===`Success`?Ci(t.success):ri(new Ji(`contract`,`invalid`,`Instruction revision is invalid`))}))},model:AT(e.model)},r=e.recipientStatus,i=e.recipientParent;i!==void 0&&Object.assign(n,{recipientParent:e=>Xr(()=>i(e)).pipe(Qr(e=>yr(`recipient.parent_unavailable`,za(e)).pipe(qr(ri(new _T({reason:`unavailable`,message:`Recipient parent is unavailable`}))))))}),r!==void 0&&Object.assign(n,{recipientStatus:e=>Xr(()=>r(e)).pipe(Qr(e=>yr(`recipient.status_unavailable`,za(e)).pipe(Di(`unknown`))))}),e.hostJobs!==void 0&&Object.assign(n,{hostJobs:ZT(e.hostJobs)}),e.meta!==void 0&&Object.assign(n,{meta:e.meta}),e.storagePressure!==void 0&&Object.assign(n,{storagePressure:e.storagePressure}),e.admission!==void 0&&Object.assign(n,{admission:e.admission}),e.compaction!==void 0&&Object.assign(n,{compaction:e.compaction});let a=e.tools;return a===void 0?n:{...n,tools:La(a)}}function $T(e,t){return io(XT(e).pipe(Ri(n=>t(QT(e,n))))).then(Qa)}Object.freeze({make:e=>$T(e,mT)});var eE=200,tE=Yr({action:Si(`list`)}),nE=zi(Fi(),$r()).parse(structuredClone(Ar(tE))),rE=120,iE=Yr({title:Fi()}).optional().transform(e=>e?.title.trim().replaceAll(/\s+/gu,` `)??``),aE=4096,oE=Yr({instructions:Fi()}).optional().transform(e=>e?.instructions.trim()??``);function sE(e,t){return e?.notify({type:`info`,message:t}),t}function cE(e,t){let n=e=>{throw Error(`${e} is unavailable in this host.`)};return{sourceId:t.sourceId,namespace:t.namespace,commands:[{id:`session`,title:`Session status`,category:`Advanced`,projections:{help:{order:1},palette:{order:1},slash:{aliases:[`session`],order:1}},handler:async({interaction:t})=>{let n=await e.read();return sE(t,`Session ${n.sessionId} is ${rr(Je(n))}; ${String(n.pending.prompts.length)} queued prompt${n.pending.prompts.length===1?``:`s`}.`)}},{id:`queue`,title:`Queued prompts`,category:`Advanced`,projections:{help:{order:3},palette:{order:3},slash:{aliases:[`queue`],order:3,arguments:{hint:`list`,words:[{word:`list`,description:`List accepted queued prompts`,arguments:{action:`list`}}]}}},action:{inputSchema:nE},handler:async({arguments:t,interaction:n})=>{if(!tE.safeParse(t??{action:`list`}).success)throw Error(`/queue requires list.`);let r=await e.read(),i=r.pending.prompts,a=r.terminals.map(e=>`${e.outcome} · ${e.commandId}`);sE(n,i.length===0&&a.length===0?`No queued prompts.`:[...i.map((e,t)=>`${String(t+1)}. queued · accepted: ${e.text}`),...a,...r.pending.hasMore===!0?[`More accepted prompts are waiting outside this view.`]:[]].join(`
117
- `))}},{id:`resume`,title:`Resume a conversation`,category:`Conversation`,projections:{help:{order:5},palette:{order:5},slash:{aliases:[`resume`],order:5}},handler:async()=>{if(!t.sessionResumeAvailable||t.sessionResume===void 0){n(`/resume`);return}await t.sessionResume()}},{id:`fork`,title:`Fork conversation`,category:`Conversation`,projections:{help:{order:7},palette:{order:7},slash:{aliases:[`fork`],order:7}},handler:async({interaction:r})=>{let i=t.onForked;if(!t.forkAvailable||i===void 0){n(`/fork`);return}let a=await e.read();if(rr(Je(a))!==`idle`)throw Error(`Wait for the current run to finish, then fork.`);let o=Ln(a.messages??[],a.compactions??[]).items.filter(e=>e.kind===`user_message`);if(o.length===0)throw Error(`No messages to fork from.`);if(r===void 0)throw Error(`Forking a Session needs a person.`);let s=[...o].reverse().slice(0,eE),c=Date.now(),l=await r.prompt({type:`choice`,message:`Fork from which message?`,summary:`Start a new conversation from your message.`,options:s.map(e=>({value:e.id,label:RC(e.text,44)||`(empty message)`,description:e.at===void 0?void 0:LC(e.at,c)}))}),u=await r.run(async()=>{try{return await e.command({type:`fork`,entryId:l})}catch(e){if(e instanceof Ji){if(e.boundary===`runtime`&&e.cause===`conflict`)throw Error(`Wait for the current run to finish, then fork.`,{cause:e});if(e.boundary===`store`&&e.cause===`unavailable`)throw Error(`That message is no longer available to fork from.`,{cause:e});if(e.boundary===`runtime`&&e.cause===`rejected`)throw Error(`This Session is bound to a channel and cannot be forked.`,{cause:e})}throw e}});await r.run(async()=>{await i(u.sessionId)})}},{id:`compact`,title:`Compact conversation`,category:`Conversation`,description:`Summarize older context now; optional text sets its focus`,projections:{help:{order:8},palette:{order:8},slash:{aliases:[`compact`],order:8,arguments:{hint:`[instructions]`,text:{field:`instructions`,arguments:{}}}}},handler:async({arguments:t})=>{let n=oE.safeParse(t);if(!n.success)throw Error(`Use /compact, or /compact <what to focus on>.`);let r=n.data;if(r.length>aE)throw Error(`Compaction instructions are at most ${String(aE)} characters.`);return await e.command(r.length===0?{type:`compact`,requestId:uo()}:{type:`compact`,requestId:uo(),instructions:r}),`Compaction queued; it runs after any current work.`}},{id:`name`,title:`Name conversation`,category:`Conversation`,description:`Set the conversation title; no text restores it`,projections:{help:{order:9},palette:{order:9},slash:{aliases:[`name`],order:9,arguments:{hint:`[title]`,text:{field:`title`,arguments:{}}}}},handler:async({arguments:n})=>{let r=iE.safeParse(n);if(!r.success)throw Error(`Use /name <title>, or /name to clear it.`);let i=r.data;if(Array.from(i).length>rE)throw Error(`A conversation title is at most ${String(rE)} characters.`);let a=i.length===0?null:i;return await e.command({type:`title`,title:a}),await t.onTitled?.(a),a===null?`Conversation title cleared; it follows the first prompt again.`:`Conversation named "${a}".`}}]}.commands}var lE=xe(`EyeOff`,[[`path`,{d:`M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49`,key:`ct8e1f`}],[`path`,{d:`M14.084 14.158a3 3 0 0 1-4.242-4.242`,key:`151rxh`}],[`path`,{d:`M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143`,key:`13bj9a`}],[`path`,{d:`m2 2 20 20`,key:`1ooewy`}]]),uE=xe(`Eye`,[[`path`,{d:`M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0`,key:`1nclc0`}],[`circle`,{cx:`12`,cy:`12`,r:`3`,key:`1v7zrd`}]]),dE=xe(`FileImage`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`circle`,{cx:`10`,cy:`12`,r:`2`,key:`737tya`}],[`path`,{d:`m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22`,key:`wt3hpn`}]]),fE=xe(`NotebookPen`,[[`path`,{d:`M13.4 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-7.4`,key:`re6nr2`}],[`path`,{d:`M2 6h4`,key:`aawbzj`}],[`path`,{d:`M2 10h4`,key:`l0bgd4`}],[`path`,{d:`M2 14h4`,key:`1gsvsf`}],[`path`,{d:`M2 18h4`,key:`1bu2t1`}],[`path`,{d:`M21.378 5.626a1 1 0 1 0-3.004-3.004l-5.01 5.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z`,key:`pqwjuv`}]]),pE=xe(`PanelLeftOpen`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M9 3v18`,key:`fh3hqa`}],[`path`,{d:`m14 9 3 3-3 3`,key:`8010ee`}]]),mE=xe(`Pencil`,[[`path`,{d:`M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z`,key:`1a8usu`}],[`path`,{d:`m15 5 4 4`,key:`1mk7zo`}]]),hE=xe(`RotateCcw`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}]]),gE=xe(`SquarePen`,[[`path`,{d:`M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7`,key:`1m0v6g`}],[`path`,{d:`M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z`,key:`ohrbg2`}]]),_E=xe(`Trash2`,[[`path`,{d:`M3 6h18`,key:`d0wm0j`}],[`path`,{d:`M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6`,key:`4alrt4`}],[`path`,{d:`M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2`,key:`v07s0e`}],[`line`,{x1:`10`,x2:`10`,y1:`11`,y2:`17`,key:`1uufr5`}],[`line`,{x1:`14`,x2:`14`,y1:`11`,y2:`17`,key:`xtxkd`}]]),vE=(0,J.memo)(function({avatar:e,className:t=`h-12 w-12 shrink-0`,service:n=Nn,state:r}){let i=(0,J.useMemo)(()=>e?Xt(e):void 0,[e]);return(0,X.jsx)(xt,{"aria-hidden":`true`,className:t,service:n,src:i?.src??{local:`mushroom`},...i?{appearance:i.appearance,renderStyle:i.renderStyle}:{},...r})}),yE={needs_you:`Waiting for you`,running:`Working`,errored:`Failed`,done:`Done`},bE={needs_you:0,errored_unseen:1,running:2,recent:3};function xE(e){return e===`running`||e===`needs_you`}function SE(e,t){return e!==void 0&&(t===void 0||e>t)}function CE(e,t){switch(e){case`needs_you`:return`needs_you`;case`running`:return`running`;case`errored`:return t?`errored_unseen`:`recent`;case`done`:return`recent`}}function wE(e,t){return bE[e.tier]-bE[t.tier]||(t.settledAt??t.createdAt)-(e.settledAt??e.createdAt)||e.agentId.localeCompare(t.agentId)||e.sessionId.localeCompare(t.sessionId)}var TE=[`Needs you`,`Working`,`Ready`,`Finished`];function EE(e){return e.tier===`running`?`Working`:e.shelf===`active`?`Needs you`:e.ready?`Ready`:`Finished`}function DE(e){return{key:NE(e.agentId,e.sessionId),shelf:EE(e),attention:e.tier===`needs_you`||e.tier===`errored_unseen`?`${e.tier}:${String(e.settledAt??e.createdAt)}`:null}}function OE(e,t,n){let r=new Map(t.map(e=>[NE(e.agentId,e.sessionId),e]));if(e!==null&&e.length>0&&n.held)return e;let i=[...t].sort((e,t)=>(t.settledAt??t.createdAt)-(e.settledAt??e.createdAt)||e.agentId.localeCompare(t.agentId)||e.sessionId.localeCompare(t.sessionId)),a=new Map(e?.map(e=>[e.key,e])),o=i.map(DE).filter(e=>{let t=a.get(e.key);return t===void 0||e.key!==n.openKey&&e.attention!==null&&e.attention!==t.attention}),s=new Set(o.map(e=>e.key)),c=a.get(n.openKey??``),l=c===void 0?-1:(e??[]).filter(e=>e.shelf===c.shelf).findIndex(e=>e.key===c.key),u=TE.flatMap(t=>{let a;a=e===null||n.reorder?i.map(DE).filter(e=>e.shelf===t):[...o.filter(e=>e.shelf===t),...e.filter(e=>e.shelf===t&&!s.has(e.key)).flatMap(e=>{let t=r.get(e.key);return t===void 0?[]:[{...e,attention:DE(t).attention}]})];let u=c===void 0?void 0:r.get(c.key);return c!==void 0&&u!==void 0&&(a=a.filter(e=>e.key!==c.key),c.shelf===t&&a.splice(Math.min(l,a.length),0,{...c,attention:DE(u).attention})),a});return e!==null&&u.length===e.length&&u.every((t,n)=>t.key===e[n]?.key&&t.shelf===e[n]?.shelf&&t.attention===e[n]?.attention)?e:u}function kE(e){switch(e.kind){case`idle`:return`done`;case`waiting_for_you`:return`needs_you`;case`error`:return`errored`;default:return`running`}}function AE(e,t,n=null,r){let i=new Set(e.map(e=>e.agentId));return jE(t.filter(e=>!(`kind`in e)&&i.has(e.agentId)&&(n===null||e.agentId===n)),r)}function jE(e,t){let n=[],r=[];for(let i of e){if(`kind`in i)continue;if(i.state===`unavailable`){r.push({agentId:i.agentId,sessionId:i.sessionId});continue}let e=SE(i.settledAt,i.visitedAt),a=t?.agentId===i.agentId&&t.sessionId===i.sessionId?t.state:void 0,o=a?kE(a):i.state,s=a?a.kind===`idle`:o===`done`&&i.settledAt===void 0,c=CE(o,e);n.push({...i,state:o,ready:s,unseen:e,tier:c,shelf:c===`recent`?`settled`:`active`})}return n.sort(wE),{active:n.filter(e=>e.shelf===`active`),settled:n.filter(e=>e.shelf===`settled`),unavailable:r.sort((e,t)=>e.agentId.localeCompare(t.agentId)||e.sessionId.localeCompare(t.sessionId))}}function ME(e){return[...e.active,...e.settled].filter(e=>!(e.title===``&&e.ready))}function NE(e,t){return`${e}\u0000${t}`}function PE(e){return e.name}var FE=`Connect a model first`;function IE({children:e}){return(0,X.jsx)(`span`,{className:`grove-rail-mark grid size-full place-items-center`,children:e})}function LE({open:e,agents:t,agentActivity:n,agentFilterId:r,websitesSelected:i,websitesVisible:o,canCreate:s,modelsMissing:l,createOpen:u,onAll:d,onWebsites:f,onAgent:p,onCreate:m}){let[h,g]=(0,J.useState)(null),_=`grove-rail-cell relative size-12 rounded-field p-0`,v=r===null&&!(i&&o);return(0,X.jsxs)(`nav`,{id:`grove-agent-rail`,"aria-label":`Agents`,className:`grove-rail min-h-0 w-16 flex-none flex-col items-center gap-1 border-r border-base-300 py-2 ${e?`flex`:`flex @min-[900px]/grove:hidden`}`,children:[(0,X.jsx)(c,{variant:`ghost`,"aria-label":`All Agents`,"aria-pressed":v,className:`${_} text-xs ${v?`bg-base-300`:``}`,onClick:d,children:(0,X.jsx)(IE,{children:`All`})}),o?(0,X.jsx)(c,{variant:`ghost`,"aria-label":`Websites`,"aria-pressed":i,className:`${_} ${i?`bg-base-300`:``}`,onClick:f,children:(0,X.jsx)(IE,{children:(0,X.jsx)(xn,{name:`internet`,size:28})})}):null,(0,X.jsx)(vx,{className:`w-full flex-1`,style:{width:`100%`},children:(0,X.jsx)(`div`,{className:`flex flex-col items-center gap-1 py-1`,children:t.map(e=>(0,X.jsx)(c,{variant:`ghost`,"aria-label":PE(e),title:PE(e),"aria-pressed":r===e.agentId&&!i,"data-agent-id":e.agentId,className:`${_} ${r===e.agentId&&!i?`bg-base-300`:``}`,onPointerEnter:()=>{g(e.agentId)},onPointerLeave:()=>{g(null)},onFocus:()=>{g(e.agentId)},onBlur:()=>{g(null)},onClick:()=>{p(e.agentId)},children:(0,X.jsx)(IE,{children:(0,X.jsx)(gn,{activity:n.get(e.agentId)??(h===e.agentId?`thinking`:`idle`),avatar:e.avatar,name:PE(e),size:32})})},e.agentId))})}),s?(0,X.jsxs)(MC,{side:`right`,children:[(0,X.jsx)(NC,{asChild:!0,children:(0,X.jsx)(c,{variant:`ghost`,"aria-label":`New Agent`,"aria-disabled":l,"aria-expanded":u,"aria-haspopup":`dialog`,className:`${_} mt-auto ${l?`opacity-50`:``}`,onClick:m,children:(0,X.jsx)(`span`,{className:`grove-rail-mark grid size-full place-items-center`,children:(0,X.jsx)(a,{size:20})})})}),l?(0,X.jsx)(PC,{children:FE}):null]}):null]})}function RE({app:e}){let[t,r]=(0,J.useState)(null),i=is({queryKey:vy.of(e,`team-inbox-notices`,t),enabled:e!==null&&(e.capabilities.has(tg)||e.capabilities.has(ng)),queryFn:async()=>{if(!e)throw Error(`No App connection`);let n=await lg(e.capabilities);try{return await ay(n,t)}finally{await n.close()}}});return!i.isError&&!i.data?.items.length?null:(0,X.jsx)(`section`,{"aria-label":`Team notices`,className:`min-h-0 shrink-0`,children:(0,X.jsxs)(vx,{className:`max-h-52 border-b border-base-300`,children:[i.isError?(0,X.jsx)(`p`,{role:`alert`,className:`text-sm`,children:`Team notices unavailable.`}):(0,X.jsx)(vt,{density:`compact`,className:`px-3 py-2`,children:i.data.items.map(e=>(0,X.jsx)(or,{children:(0,X.jsxs)(`div`,{className:`grid min-w-0 grid-cols-[auto_minmax(0,1fr)] gap-x-[var(--spacing-xs)]`,children:[(0,X.jsx)(n,{className:`col-span-2 grid grid-cols-subgrid`,size:`compact`,tone:`warning`,label:`kind`in e?`Seller closed`:`Installed App safety notice`}),(0,X.jsx)(`p`,{className:`m-0 col-start-2 text-sm [overflow-wrap:anywhere]`,children:`kind`in e?`${e.sellerName} closed. Your installation of ${e.displayName} continues; no new purchases are available.`:`${e.displayName} was removed. Fungi will disable it on your Team.`})]})},e.dispositionId))}),i.data?.next?(0,X.jsx)(c,{variant:`ghost`,size:`sm`,onClick:()=>{r(i.data.next)},children:`Older notices`}):null,t===null?null:(0,X.jsx)(c,{variant:`ghost`,size:`sm`,onClick:()=>{r(null)},children:`Newest notices`})]})})}var zE=900;function BE(e){let[t,n]=(0,J.useState)(null);return(0,J.useLayoutEffect)(()=>{let t=e.current;if(!t)return;let r=e=>{n(e===0||e>=zE)};r(t.getBoundingClientRect().width);let i=`ResizeObserver`in globalThis?new ResizeObserver(([e])=>{r(e.contentRect.width)}):void 0;return i?.observe(t),()=>{i?.disconnect()}},[e]),t}function VE({open:e,onOpenChange:t,returnFocus:n,desktop:r,children:i}){let[a,o]=(0,J.useState)(null);return(0,X.jsxs)(ke,{open:r||e,modal:!r,disablePointerDismissal:r,onOpenChange:e=>{r||t(e)},children:[(0,X.jsx)(`div`,{ref:o,className:`contents`}),(0,X.jsxs)(ee,{container:a,keepMounted:!0,className:`contents`,children:[r?null:(0,X.jsx)(E,{className:`grove-nav-scrim z-30 bg-base-200`}),(0,X.jsx)($e,{id:`grove-nav`,role:r?`presentation`:`dialog`,"aria-label":r?void 0:`Agents and conversations`,initialFocus:!r&&void 0,finalFocus:!r&&n,className:`grove-nav min-h-0 flex-none rounded-none p-0 overflow-visible max-w-none max-h-none ${r?`static flex w-auto shadow-none`:`fixed inset-y-0 left-0 z-40 w-[min(22rem,88cqw)] data-[open]:flex`}`,children:i})]})]})}function HE({update:e,notify:t,unwatched:n}){return{link:r,unlink:i,propagate:a,checkDirty:o,shallowPropagate:s};function r(e,t,n){let r=t.depsTail;if(r!==void 0&&r.dep===e)return;let i=r===void 0?t.deps:r.nextDep;if(i!==void 0&&i.dep===e){i.version=n,t.depsTail=i;return}let a=e.subsTail;if(a!==void 0&&a.version===n&&a.sub===t)return;let o=t.depsTail=e.subsTail={version:n,dep:e,sub:t,prevDep:r,nextDep:i,prevSub:a,nextSub:void 0};i!==void 0&&(i.prevDep=o),r===void 0?t.deps=o:r.nextDep=o,a===void 0?e.subs=o:a.nextSub=o}function i(e,t=e.sub){let r=e.dep,i=e.prevDep,a=e.nextDep,o=e.nextSub,s=e.prevSub;return a===void 0?t.depsTail=i:a.prevDep=i,i===void 0?t.deps=a:i.nextDep=a,o===void 0?r.subsTail=s:o.prevSub=s,s===void 0?(r.subs=o)===void 0&&n(r):s.nextSub=o,a}function a(e){let n=e.nextSub,r;top:do{let i=e.sub,a=i.flags;if(a&60?a&12?a&4?!(a&48)&&c(e,i)?(i.flags=a|40,a&=1):a=0:i.flags=a&-9|32:a=0:i.flags=a|32,a&2&&t(i),a&1){let t=i.subs;if(t!==void 0){let i=(e=t).nextSub;i!==void 0&&(r={value:n,prev:r},n=i);continue}}if((e=n)!==void 0){n=e.nextSub;continue}for(;r!==void 0;)if(e=r.value,r=r.prev,e!==void 0){n=e.nextSub;continue top}break}while(!0)}function o(t,n){let r,i=0,a=!1;top:do{let o=t.dep,c=o.flags;if(n.flags&16)a=!0;else if((c&17)==17){if(e(o)){let e=o.subs;e.nextSub!==void 0&&s(e),a=!0}}else if((c&33)==33){(t.nextSub!==void 0||t.prevSub!==void 0)&&(r={value:t,prev:r}),t=o.deps,n=o,++i;continue}if(!a){let e=t.nextDep;if(e!==void 0){t=e;continue}}for(;i--;){let i=n.subs,o=i.nextSub!==void 0;if(o?(t=r.value,r=r.prev):t=i,a){if(e(n)){o&&s(i),n=t.sub;continue}a=!1}else n.flags&=-33;n=t.sub;let c=t.nextDep;if(c!==void 0){t=c;continue top}}return a}while(!0)}function s(e){do{let n=e.sub,r=n.flags;(r&48)==32&&(n.flags=r|16,(r&6)==2&&t(n))}while((e=e.nextSub)!==void 0)}function c(e,t){let n=t.depsTail;for(;n!==void 0;){if(n===e)return!0;n=n.prevDep}return!1}}function UE(e,t,n){let r=typeof e==`object`,i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}var WE=[],GE=0,{link:KE,unlink:qE,propagate:JE,checkDirty:YE,shallowPropagate:XE}=HE({update(e){return e._update()},notify(e){WE[QE++]=e,e.flags&=-3},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=17,nD(e))}}),ZE=0,QE=0,$E,eD=0;function tD(e){try{++eD,e()}finally{--eD||rD()}}function nD(e){let t=e.depsTail,n=t===void 0?e.deps:t.nextDep;for(;n!==void 0;)n=qE(n,e)}function rD(){if(!(eD>0)){for(;ZE<QE;){let e=WE[ZE];WE[ZE++]=void 0,e.notify()}ZE=0,QE=0}}function iD(e,t){let n=typeof e==`function`,r=e,i={_snapshot:n?void 0:e,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:+!n,get(){return $E!==void 0&&KE(i,$E,GE),i._snapshot},subscribe(e){let t=UE(e),n={current:!1},r=aD(()=>{i.get(),n.current?t.next?.(i._snapshot):n.current=!0});return{unsubscribe:()=>{r.stop()}}},_update(e){let a=$E,o=t?.compare??Object.is;if(n)$E=i,++GE,i.depsTail=void 0;else if(e===void 0)return!1;n&&(i.flags=5);try{let t=i._snapshot,a=typeof e==`function`?e(t):e===void 0&&n?r(t):e;return t===void 0||!o(t,a)?(i._snapshot=a,!0):!1}finally{$E=a,n&&(i.flags&=-5),nD(i)}}};return n?(i.flags=17,i.get=function(){let e=i.flags;if(e&16||e&32&&YE(i.deps,i)){if(i._update()){let e=i.subs;e!==void 0&&XE(e)}}else e&32&&(i.flags=e&-33);return $E!==void 0&&KE(i,$E,GE),i._snapshot}):i.set=function(e){if(i._update(e)){let e=i.subs;e!==void 0&&(JE(e),XE(e),rD())}},i}function aD(e){let t=()=>{let t=$E;$E=n,++GE,n.depsTail=void 0,n.flags=6;try{return e()}finally{$E=t,n.flags&=-5,nD(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:6,notify(){let e=this.flags;e&16||e&32&&YE(this.deps,this)?t():this.flags=2},stop(){this.flags=0,this.depsTail=void 0,nD(this)}};return t(),n}var oD=class{constructor(e,t){this.atom=iD(e),this.get=this.get.bind(this),this.setState=this.setState.bind(this),this.subscribe=this.subscribe.bind(this),t&&(this.actions=t(this))}setState(e){this.atom.set(e)}get state(){return this.atom.get()}get(){return this.state}subscribe(e){return this.atom.subscribe(UE(e))}},sD=class{constructor(e){this.atom=iD(e)}get state(){return this.atom.get()}get(){return this.state}subscribe(e){return this.atom.subscribe(UE(e))}};function cD(e,t){return typeof e==`function`?new sD(e):t?new oD(e,t):new oD(e)}var lD=class{constructor(e,t){this.fn=e,this.options=t,this.lastExecutionTime=0,this.isPending=!1,this.maybeExecute=(...e)=>{let t=Date.now()-this.lastExecutionTime;if(this.options.leading&&t>=this.options.wait)this.execute(...e);else if(this.lastArgs=e,!this.timeoutId&&this.options.trailing){let e=this.options.wait-t;this.isPending=!0,this.timeoutId=setTimeout(()=>{this.lastArgs!==void 0&&this.execute(...this.lastArgs)},e)}},this.execute=(...e)=>{this.fn(...e),this.options.onExecute?.(e,this),this.lastExecutionTime=Date.now(),this.clearTimeout(),this.lastArgs=void 0,this.isPending=!1},this.flush=()=>{this.isPending&&this.lastArgs&&this.execute(...this.lastArgs)},this.cancel=()=>{this.clearTimeout(),this.lastArgs=void 0,this.isPending=!1},this.clearTimeout=()=>{this.timeoutId&&=(clearTimeout(this.timeoutId),void 0)},this.options.leading===void 0&&this.options.trailing===void 0&&(this.options.leading=!0,this.options.trailing=!0)}};function uD(e,t){return new lD(e,t).maybeExecute}var dD=class{#e=!0;#t;#n;#r;#i;#a;#o;#s;#c=0;#l=5;#u=!1;#d=!1;#f=null;#p=()=>{this.debugLog(`Connected to event bus`),this.#a=!0,this.#u=!1,this.debugLog(`Emitting queued events`,this.#i),this.#i.forEach(e=>this.emitEventToBus(e)),this.#i=[],this.stopConnectLoop(),this.#n().removeEventListener(`tanstack-connect-success`,this.#p)};#m=()=>{if(this.#c<this.#l){this.#c++,this.dispatchCustomEvent(`tanstack-connect`,{});return}this.#n().removeEventListener(`tanstack-connect`,this.#m),this.#d=!0,this.debugLog(`Max retries reached, giving up on connection`),this.stopConnectLoop()};#h=()=>{this.#u||(this.#u=!0,this.#n().addEventListener(`tanstack-connect-success`,this.#p),this.#m())};constructor({pluginId:e,debug:t=!1,enabled:n=!0,reconnectEveryMs:r=300}){this.#t=e,this.#e=n,this.#n=this.getGlobalTarget,this.#r=t,this.debugLog(` Initializing event subscription for plugin`,this.#t),this.#i=[],this.#a=!1,this.#d=!1,this.#o=null,this.#s=r}startConnectLoop(){this.#o!==null||this.#a||(this.debugLog(`Starting connect loop (every ${this.#s}ms)`),this.#o=setInterval(this.#m,this.#s))}stopConnectLoop(){this.#u=!1,this.#o!==null&&(clearInterval(this.#o),this.#o=null,this.#i=[],this.debugLog(`Stopped connect loop`))}debugLog(...e){this.#r&&console.log(`🌴 [tanstack-devtools:${this.#t}-plugin]`,...e)}getGlobalTarget(){if(typeof globalThis<`u`&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog(`Using global event target`),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window<`u`&&window.addEventListener!==void 0)return this.debugLog(`Using window as event target`),window;let e=typeof EventTarget<`u`?new EventTarget:void 0;return e===void 0||e.addEventListener===void 0?(this.debugLog(`No event mechanism available, running in non-web environment`),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>!1}):(this.debugLog(`Using new EventTarget as fallback`),e)}getPluginId(){return this.#t}dispatchCustomEventShim(e,t){try{let n=new Event(e,{detail:t});this.#n().dispatchEvent(n)}catch{this.debugLog(`Failed to dispatch shim event`)}}dispatchCustomEvent(e,t){try{this.#n().dispatchEvent(new CustomEvent(e,{detail:t}))}catch{this.dispatchCustomEventShim(e,t)}}emitEventToBus(e){this.debugLog(`Emitting event to client bus`,e),this.dispatchCustomEvent(`tanstack-dispatch-event`,e)}createEventPayload(e,t){return{type:`${this.#t}:${e}`,payload:t,pluginId:this.#t}}emit(e,t){if(!this.#e){this.debugLog(`Event bus client is disabled, not emitting event`,e,t);return}if(this.#f&&(this.debugLog(`Emitting event to internal event target`,e,t),this.#f.dispatchEvent(new CustomEvent(`${this.#t}:${e}`,{detail:this.createEventPayload(e,t)}))),this.#d){this.debugLog(`Previously failed to connect, not emitting to bus`);return}if(!this.#a){this.debugLog(`Bus not available, will be pushed as soon as connected`),this.#i.push(this.createEventPayload(e,t)),typeof CustomEvent<`u`&&!this.#u&&(this.#h(),this.startConnectLoop());return}return this.emitEventToBus(this.createEventPayload(e,t))}on(e,t,n){let r=n?.withEventTarget??!1,i=`${this.#t}:${e}`;if(r&&(this.#f||=new EventTarget,this.#f.addEventListener(i,e=>{t(e.detail)})),!this.#e)return this.debugLog(`Event bus client is disabled, not registering event`,i),()=>{};let a=e=>{this.debugLog(`Received event from bus`,e.detail),t(e.detail)};return this.#n().addEventListener(i,a),this.debugLog(`Registered event to bus`,i),()=>{r&&this.#f?.removeEventListener(i,a),this.#n().removeEventListener(i,a)}}onAll(e){if(!this.#e)return this.debugLog(`Event bus client is disabled, not registering event`),()=>{};let t=t=>{let n=t.detail;e(n)};return this.#n().addEventListener(`tanstack-devtools-global`,t),()=>this.#n().removeEventListener(`tanstack-devtools-global`,t)}onAllPluginEvents(e){if(!this.#e)return this.debugLog(`Event bus client is disabled, not registering event`),()=>{};let t=t=>{let n=t.detail;this.#t&&n.pluginId!==this.#t||e(n)};return this.#n().addEventListener(`tanstack-devtools-global`,t),()=>this.#n().removeEventListener(`tanstack-devtools-global`,t)}},fD=new class extends dD{constructor(){super({pluginId:`form-devtools`,reconnectEveryMs:1e3})}};function pD(e,t){return typeof e==`function`?e(t):e}function mD(e,t){return SD(t).reduce((e,t)=>{if(e===null)return null;if(e!==void 0)return e[t]},e)}function hD(e,t,n){let r=SD(t);function i(e){if(!r.length)return pD(n,e);let t=r.shift();if(typeof t==`string`||typeof t==`number`&&!Array.isArray(e))return typeof e==`object`?(e===null&&(e={}),{...e,[t]:i(e[t])}):{[t]:i()};if(Array.isArray(e)&&typeof t==`number`){let n=e.slice(0,t);return[...n.length?n:Array(t),i(e[t]),...e.slice(t+1)]}return[...Array(t),i()]}return i(e)}function gD(e,t){let n=SD(t);function r(e){if(!e)return;if(n.length===1){let t=n[0];if(Array.isArray(e)&&typeof t==`number`)return e.filter((e,n)=>n!==t);let{[t]:r,...i}=e;return i}let t=n.shift();if((typeof t==`string`||typeof t==`number`&&!Array.isArray(e))&&typeof e==`object`)return{...e,[t]:r(e[t])};if(typeof t==`number`&&Array.isArray(e)){if(t>=e.length)return e;let n=e.slice(0,t);return[...n.length?n:Array(t),r(e[t]),...e.slice(t+1)]}throw Error(`It seems we have created an infinite loop in deleteBy. `)}return r(e)}var _D=46,vD=91,yD=93,bD=48,xD=57;function SD(e){if(Array.isArray(e))return[...e];if(typeof e!=`string`)throw Error(`Path must be a string.`);let t=e.length,n=[],r=+(t>0&&e.charCodeAt(0)===vD),i=!0,a=-1;for(let o=r;o<=t;o++){let s=o<t?e.charCodeAt(o):-1;if(o===t||s===_D||s===vD||s===yD){let t=o-r;if(t>0){let a=i&&(t===1||e.charCodeAt(r)!==bD),s=e.slice(r,o);if(a){let e=parseInt(s,10);t<=15||String(e)===s?n.push(e):n.push(s)}else n.push(s)}else a!==yD&&(a!==-1||s!==yD)&&(a!==s||s!==_D&&s!==vD)&&n.push(``);r=o+1,i=!0}else(s<bD||s>xD)&&(i=!1);a=s}return n.length||n.push(``),n}function CD(e){return!(Array.isArray(e)&&e.length===0)}function wD(e,t){return t.validationLogic({form:t.form,group:t.group,validators:t.validators,event:{type:e,fieldName:t.fieldName,async:!1},runValidation:e=>e.validators.filter(Boolean).map(e=>({cause:e.cause,validate:e.fn}))})}function TD(e,t){let{asyncDebounceMs:n}=t,{onBlurAsyncDebounceMs:r,onChangeAsyncDebounceMs:i,onDynamicAsyncDebounceMs:a}=t.validators||{},o=n??0;return t.validationLogic({form:t.form,group:t.group,validators:t.validators,event:{type:e,fieldName:t.fieldName,async:!0},runValidation:t=>t.validators.filter(Boolean).map(t=>{let n=t?.cause||e,s=o;switch(n){case`change`:s=i??o;break;case`blur`:s=r??o;break;case`dynamic`:s=a??o;break;case`submit`:s=0}return e===`submit`&&(s=0),{cause:n,validate:t.fn,debounceMs:s}})})}var ED=e=>!!e&&typeof e==`object`&&`fields`in e;function DD(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(let[n,r]of e)if(!t.has(n)||!Object.is(r,t.get(n)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length||n.length===0&&!Array.isArray(e)&&!Array.isArray(t)&&(Object.getPrototypeOf(e)!==Object.prototype||Object.getPrototypeOf(t)!==Object.prototype))return!1;for(let i of n)if(!r.includes(i)||!DD(e[i],t[i]))return!1;return!0}var OD=({newFormValidatorError:e,isPreviousErrorFromFormValidator:t,previousErrorValue:n})=>e?{newErrorValue:e,newSource:`form`}:t?{newErrorValue:void 0,newSource:void 0}:n?{newErrorValue:n,newSource:`field`}:{newErrorValue:void 0,newSource:void 0},kD=({formLevelError:e,fieldLevelError:t})=>t?{newErrorValue:t,newSource:`field`}:e?{newErrorValue:e,newSource:`form`}:{newErrorValue:void 0,newSource:void 0};function AD(e,t){return e==null?t:{...e,...t}}for(var jD=256,MD=[],ND;jD--;)MD[jD]=(jD+256).toString(16).substring(1);function PD(){let e=0,t,n=``;if(!ND||jD+16>256){for(ND=Array(256),e=256;e--;)ND[e]=256*Math.random()|0;e=0,jD=0}for(;e<16;e++)t=ND[jD+e],n+=e===6?MD[t&15|64]:e===8?MD[t&63|128]:MD[t],e&1&&e>1&&e<11&&(n+=`-`);return jD++,n}var FD=uD(e=>fD.emit(`form-state`,{id:e.formId,state:e.store.state}),{wait:300});function ID(e){if(typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e)){let t=[];for(let n=0;n<e.length;n++)t[n]=ID(e[n]);return t}if(e instanceof Map){let t=new Map;return e.forEach((e,n)=>{t.set(n,ID(e))}),t}if(e instanceof Set){let t=new Set;return e.forEach(e=>{t.add(ID(e))}),t}let t={};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=ID(e[n]));return t}function LD(e,t){return t===e||t.startsWith(`${e}.`)||t.startsWith(`${e}[`)}var RD=e=>{if(!e.validators)return e.runValidation({validators:[],form:e.form});let t=e.event.async,n=t?void 0:{fn:e.validators.onMount,cause:`mount`},r={fn:t?e.validators.onChangeAsync:e.validators.onChange,cause:`change`},i={fn:t?e.validators.onBlurAsync:e.validators.onBlur,cause:`blur`},a={fn:t?e.validators.onSubmitAsync:e.validators.onSubmit,cause:`submit`},o=t?void 0:{fn:()=>void 0,cause:`server`};switch(e.event.type){case`mount`:return e.runValidation({validators:[n],form:e.form});case`submit`:return e.runValidation({validators:[r,i,a,o],form:e.form});case`server`:return e.runValidation({validators:[],form:e.form});case`blur`:return e.runValidation({validators:[i,o],form:e.form});case`change`:return e.runValidation({validators:[r,o],form:e.form});default:throw Error(`Unknown validation event type: ${e.event.type}`)}};function zD(e,t){let n=new Map;for(let r of e){let e=r.path??[],i=t,a=``;for(let t=0;t<e.length;t++){let n=e[t];if(n===void 0)continue;let r=typeof n==`object`?n.key:n,o=Number(r);a+=Array.isArray(i)&&!Number.isNaN(o)?`[${o}]`:(t>0?`.`:``)+String(r),i=typeof i==`object`&&i?i[r]:void 0}n.set(a,(n.get(a)??[]).concat(r))}return Object.fromEntries(n)}var BD=(e,t)=>{let n=zD(e,t);return{form:n,fields:n}},VD={validate({value:e,validationSource:t},n){let r=n[`~standard`].validate(e);if(r instanceof Promise)throw Error(`async function passed to sync validator`);if(r.issues)return t===`field`?r.issues:BD(r.issues,e)},async validateAsync({value:e,validationSource:t},n){let r=await n[`~standard`].validate(e);if(r.issues)return t===`field`?r.issues:BD(r.issues,e)}},HD=e=>!!e&&`~standard`in e,UD={isValidating:!1,isTouched:!1,isBlurred:!1,isDirty:!1,isPristine:!0,isValid:!0,isDefaultValue:!0,errors:[],errorMap:{},errorSourceMap:{},_arrayVersion:0,_pendingValidationsCount:0};function WD(e){function t(t){let n=e.getFieldMeta(t)??UD;e.setFieldMeta(t,{...n,_arrayVersion:(n._arrayVersion||0)+1})}function n(n,r,i){t(n);let a=s(n,r,`move`,i),c=Math.min(r,i),u=Math.max(r,i);for(let e=c;e<=u;e++)a.push(o(n,e));let d=Object.keys(e.fieldInfo).reduce((t,i)=>(i.startsWith(o(n,r))&&t.set(i,e.getFieldMeta(i)),t),new Map);l(a,r<i?`up`:`down`),Object.keys(e.fieldInfo).filter(e=>e.startsWith(o(n,i))).forEach(t=>{let a=t.replace(o(n,i),o(n,r)),s=d.get(a);s&&e.setFieldMeta(t,s)})}function r(e,n){t(e),l(s(e,n,`remove`),`up`)}function i(n,r,i){t(n),s(n,r,`swap`,i).forEach(t=>{if(!t.toString().startsWith(o(n,r)))return;let a=t.toString().replace(o(n,r),o(n,i)),[s,c]=[e.getFieldMeta(t),e.getFieldMeta(a)];s&&e.setFieldMeta(a,s),c&&e.setFieldMeta(t,c)})}function a(n,r){t(n);let i=s(n,r,`insert`);l(i,`down`),i.forEach(t=>{t.toString().startsWith(o(n,r))&&e.setFieldMeta(t,u())})}function o(e,t){return`${e}[${t}]`}function s(t,n,r,i){let a=[o(t,n)];switch(r){case`swap`:a.push(o(t,i));break;case`move`:{let[e,r]=[Math.min(n,i),Math.max(n,i)];for(let n=e;n<=r;n++)a.push(o(t,n));break}default:{let r=e.getFieldValue(t),i=Array.isArray(r)?r.length:0;for(let e=n+1;e<i;e++)a.push(o(t,e));break}}return Object.keys(e.fieldInfo).filter(e=>a.some(t=>e.startsWith(t)))}function c(e,t){return e.replace(/\[(\d+)\]/,(e,n)=>{let r=parseInt(n,10);return`[${t===`up`?r+1:Math.max(0,r-1)}]`})}function l(t,n){(n===`up`?t:[...t].reverse()).forEach(t=>{let r=c(t.toString(),n),i=e.getFieldMeta(r);i?e.setFieldMeta(t,i):e.setFieldMeta(t,u())})}let u=()=>UD;return{bumpArrayVersion:t,handleArrayMove:n,handleArrayRemove:r,handleArraySwap:i,handleArrayInsert:a}}function GD(e){return{values:e.values??{},errorMap:e.errorMap??{},fieldMetaBase:e.fieldMetaBase??{},formGroupStateBase:e.formGroupStateBase??{},isSubmitted:e.isSubmitted??!1,isSubmitting:e.isSubmitting??!1,isValidating:e.isValidating??!1,submissionAttempts:e.submissionAttempts??0,isSubmitSuccessful:e.isSubmitSuccessful??!1,validationMetaMap:e.validationMetaMap??{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}}}var KD=class{constructor(e){this.options={},this.fieldInfo={},this.formGroupApis=new Set,this.mount=()=>{let e=this.store.subscribe(()=>{FD(this)}),t=fD.on(`request-form-state`,e=>{e.payload.id===this._formId&&fD.emit(`form-api`,{id:this._formId,state:this.store.state,options:this.options})}),n=fD.on(`request-form-reset`,e=>{e.payload.id===this._formId&&this.reset()}),r=fD.on(`request-form-force-submit`,e=>{e.payload.id===this._formId&&(this._devtoolsSubmissionOverride=!0,this.handleSubmit(),this._devtoolsSubmissionOverride=!1)}),i=()=>{r(),n(),t(),e.unsubscribe(),fD.emit(`form-unmounted`,{id:this._formId})};this.options.listeners?.onMount?.({formApi:this});let{onMount:a}=this.options.validators||{};return fD.emit(`form-api`,{id:this._formId,state:this.store.state,options:this.options}),a&&this.validateSync(`mount`),i},this.update=e=>{if(!e)return;let t=this.options;this.options=e;let n=e.defaultValues&&!DD(e.defaultValues,t.defaultValues)&&!this.state.isTouched,r=!DD(e.defaultState,t.defaultState)&&!this.state.isTouched;if(!(!n&&!r)){if(tD(()=>{this.baseStore.setState(()=>GD(Object.assign({},this.state,r?e.defaultState:{},n?{values:e.defaultValues}:{})))}),n){let e=WD(this);for(let t of Object.keys(this.fieldInfo))Array.isArray(this.getFieldValue(t))&&e.bumpArrayVersion(t)}fD.emit(`form-api`,{id:this._formId,state:this.store.state,options:this.options})}},this.reset=(e,t)=>{let{fieldMeta:n}=this.state,r=this.resetFieldMeta(n);e&&!t?.keepDefaultValues&&(this.options={...this.options,defaultValues:e}),this.baseStore.setState(()=>{let t=e??this.options.defaultValues??this.options.defaultState?.values;return e||Object.values(this.fieldInfo).forEach(e=>{e.instance&&e.instance.options.defaultValue!==void 0&&(t=hD(t,e.instance.name,e.instance.options.defaultValue))}),GD({...this.options.defaultState,values:t,fieldMetaBase:r})})},this.validateAllFields=async e=>{let t=[];return tD(()=>{Object.values(this.fieldInfo).forEach(n=>{if(!n.instance)return;let r=n.instance;t.push(Promise.resolve().then(()=>r.validate(e,{skipFormValidation:!0,skipGroupValidation:!0}))),n.instance.store.state.meta.isTouched||n.instance.setMeta(e=>({...e,isTouched:!0}))})}),(await Promise.all(t)).flat()},this.validateArrayFieldsStartingFrom=async(e,t,n)=>{let r=this.getFieldValue(e),i=Array.isArray(r)?Math.max(r.length-1,0):null,a=[`${e}[${t}]`];for(let n=t+1;n<=(i??0);n++)a.push(`${e}[${n}]`);let o=Object.keys(this.fieldInfo).filter(e=>a.some(t=>e.startsWith(t))),s=[];return tD(()=>{o.forEach(e=>{s.push(Promise.resolve().then(()=>this.validateField(e,n)))})}),(await Promise.all(s)).flat()},this.validateField=(e,t)=>{let n=this.fieldInfo[e]?.instance;if(!n){let{hasErrored:n}=this.validateSync(t);return n&&!this.options.asyncAlways?this.getFieldMeta(e)?.errors??[]:this.validateAsync(t).then(()=>this.getFieldMeta(e)?.errors??[])}return n.store.state.meta.isTouched||n.setMeta(e=>({...e,isTouched:!0})),n.validate(t)},this.validateSync=(e,t)=>{let n=wD(e,{...this.options,form:this,group:t?.group,validationLogic:this.options.validationLogic||RD}),r=!1,i={};return tD(()=>{for(let e of n){if(!e.validate)continue;let{formError:n,fieldErrors:a}=qD(this.runValidator({validate:e.validate,value:{value:this.state.values,formApi:this,validationSource:`form`},type:`validate`})),o=JD(e.cause),s=new Set([...Object.keys(this.state.fieldMeta),...Object.keys(a||{})]);t?.filterFieldNames&&(s=new Set([...s].filter(t.filterFieldNames)));for(let e of s){if(this.baseStore.state.fieldMetaBase[e]===void 0&&!a?.[e])continue;let{errorMap:t,errorSourceMap:n}=this.getFieldMeta(e)??UD,r=a?.[e],{newErrorValue:s,newSource:c}=OD({newFormValidatorError:r,isPreviousErrorFromFormValidator:n?.[o]===`form`,previousErrorValue:t?.[o]});c===`form`&&(i[e]={...i[e],[o]:r}),t?.[o]!==s&&this.setFieldMeta(e,(e=UD)=>({...e,errorMap:{...e.errorMap,[o]:s},errorSourceMap:{...e.errorSourceMap,[o]:c}}))}t?.dontUpdateFormErrorMap||this.state.errorMap?.[o]!==n&&this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[o]:n}})),(n||a)&&(r=!0)}if(t?.dontUpdateFormErrorMap)return;let a=JD(`submit`);this.state.errorMap?.[a]&&e!==`submit`&&!r&&this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[a]:void 0}}));let o=JD(`server`);this.state.errorMap?.[o]&&e!==`server`&&!r&&this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[o]:void 0}}))}),{hasErrored:r,fieldsErrorMap:i}},this.validateAsync=async(e,t)=>{let n=TD(e,{...this.options,form:this,group:t?.group,validationLogic:this.options.validationLogic||RD});this.state.isFormValidating||this.baseStore.setState(e=>({...e,isFormValidating:!0}));let r=[],i;for(let e of n){if(!e.validate)continue;let n=JD(e.cause);this.state.validationMetaMap[n]?.lastAbortController.abort();let a=new AbortController;this.state.validationMetaMap[n]={lastAbortController:a},r.push(new Promise(async n=>{let r;try{r=await new Promise((t,n)=>{setTimeout(async()=>{if(a.signal.aborted)return t(void 0);try{t(await this.runValidator({validate:e.validate,value:{value:this.state.values,formApi:this,validationSource:`form`,signal:a.signal},type:`validateAsync`}))}catch(e){n(e)}},e.debounceMs)})}catch(e){r=e}let{formError:o,fieldErrors:s}=qD(r);s&&(i=i?{...i,...s}:s);let c=JD(e.cause),l=new Set([...Object.keys(this.state.fieldMeta),...Object.keys(i||{})]),u=Array.from(l);t?.filterFieldNames&&(u=u.filter(t.filterFieldNames));for(let e of u){if(this.baseStore.state.fieldMetaBase[e]===void 0&&!i?.[e])continue;let{errorMap:t,errorSourceMap:n}=this.getFieldMeta(e)??UD,r=i?.[e],{newErrorValue:a,newSource:o}=OD({newFormValidatorError:r,isPreviousErrorFromFormValidator:n?.[c]===`form`,previousErrorValue:t?.[c]});t?.[c]!==a&&this.setFieldMeta(e,(e=UD)=>({...e,errorMap:{...e.errorMap,[c]:a},errorSourceMap:{...e.errorSourceMap,[c]:o}}))}t?.dontUpdateFormErrorMap||this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[c]:o}})),n(i?{fieldErrors:i,errorMapKey:c}:void 0)}))}let a=[],o={};if(r.length){a=await Promise.all(r);for(let e of a)if(e?.fieldErrors){let{errorMapKey:t}=e;for(let[n,r]of Object.entries(e.fieldErrors))o[n]={...o[n]||{},[t]:r}}}return this.baseStore.setState(e=>({...e,isFormValidating:!1})),o},this.validate=(e,t)=>{let{hasErrored:n,fieldsErrorMap:r}=this.validateSync(e,t);return n&&!this.options.asyncAlways?r:this.validateAsync(e,t)},this._handleSubmit=async e=>{this.baseStore.setState(e=>({...e,isSubmitted:!1,submissionAttempts:e.submissionAttempts+1,isSubmitSuccessful:!1})),tD(()=>{Object.values(this.fieldInfo).forEach(e=>{e.instance&&(e.instance.store.state.meta.isTouched||e.instance.setMeta(e=>({...e,isTouched:!0})))})});let t=e??this.options.onSubmitMeta;if(!this.state.canSubmit&&!this._devtoolsSubmissionOverride&&this.baseStore.state.submissionAttempts<=1){this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t});return}this.baseStore.setState(e=>({...e,isSubmitting:!0}));let n=()=>{this.baseStore.setState(e=>({...e,isSubmitting:!1}))};if(await this.validateAllFields(`submit`),!this.state.isFieldsValid){n(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),fD.emit(`form-submission`,{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:`validateAllFields`,errors:Object.values(this.state.fieldMeta).map(e=>e.errors).flat()});return}if(await this.validate(`submit`),!this.state.isValid){n(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),fD.emit(`form-submission`,{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:`validate`,errors:this.state.errors});return}tD(()=>{Object.values(this.fieldInfo).forEach(e=>{e.instance?.triggerOnSubmitListener()})}),this.options.listeners?.onSubmit?.({formApi:this,meta:t});try{await this.options.onSubmit?.({value:this.state.values,formApi:this,meta:t}),tD(()=>{this.baseStore.setState(e=>({...e,isSubmitted:!0,isSubmitSuccessful:!0})),fD.emit(`form-submission`,{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),n()})}catch(e){throw this.baseStore.setState(e=>({...e,isSubmitSuccessful:!1})),fD.emit(`form-submission`,{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:`inflight`,onError:e}),n(),e}},this.getFieldValue=e=>mD(this.state.values,e),this.getFieldMeta=e=>this.state.fieldMeta[e],this.getFormGroupMeta=e=>this.formGroupMetaDerived.state[e],this.getFieldInfo=e=>this.fieldInfo[e]||={instance:null,validationMetaMap:{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}},this.setFieldMeta=(e,t)=>{this.baseStore.setState(n=>({...n,fieldMetaBase:{...n.fieldMetaBase,[e]:pD(t,n.fieldMetaBase[e])}}))},this.resetFieldMeta=e=>Object.keys(e).reduce((e,t)=>{let n=t;return e[n]=UD,e},{}),this.setFieldValue=(e,t,n)=>{let r=n?.dontUpdateMeta??!1,i=n?.dontRunListeners??!1,a=n?.dontValidate??!1;tD(()=>{r||this.setFieldMeta(e,e=>({...e,isTouched:!0,isDirty:!0,errorMap:{...e?.errorMap,onMount:void 0}})),this.baseStore.setState(n=>({...n,values:hD(n.values,e,t)}))}),i||this.getFieldInfo(e).instance?.triggerOnChangeListener(),a||this.validateField(e,`change`)},this.deleteField=e=>{let t=[...Object.keys(this.fieldInfo).filter(t=>{let n=e.toString();return t!==n&&t.startsWith(n)}),e];this.baseStore.setState(e=>{let n={...e};return t.forEach(e=>{n.values=gD(n.values,e),delete this.fieldInfo[e],delete n.fieldMetaBase[e]}),n})},this.pushFieldValue=(e,t,n)=>{this.setFieldValue(e,e=>[...Array.isArray(e)?e:[],t],n),WD(this).bumpArrayVersion(e)},this.insertFieldValue=async(e,t,n,r)=>{this.setFieldValue(e,e=>[...e.slice(0,t),n,...e.slice(t)],AD(r,{dontValidate:!0}));let i=r?.dontValidate??!1;i||await this.validateField(e,`change`),WD(this).handleArrayInsert(e,t),i||await this.validateArrayFieldsStartingFrom(e,t,`change`)},this.replaceFieldValue=async(e,t,n,r)=>{this.setFieldValue(e,e=>e.map((e,r)=>r===t?n:e),AD(r,{dontValidate:!0})),WD(this).bumpArrayVersion(e),(r?.dontValidate??!1)||(await this.validateField(e,`change`),await this.validateArrayFieldsStartingFrom(e,t,`change`))},this.removeFieldValue=async(e,t,n)=>{let r=this.getFieldValue(e),i=Array.isArray(r)?Math.max(r.length-1,0):null;if(this.setFieldValue(e,e=>e.filter((e,n)=>n!==t),AD(n,{dontValidate:!0})),WD(this).handleArrayRemove(e,t),i!==null){let t=`${e}[${i}]`;this.deleteField(t)}(n?.dontValidate??!1)||(await this.validateField(e,`change`),await this.validateArrayFieldsStartingFrom(e,t,`change`))},this.swapFieldValues=(e,t,n,r)=>{this.setFieldValue(e,e=>{let r=e[t],i=e[n];return hD(hD(e,`${t}`,i),`${n}`,r)},AD(r,{dontValidate:!0})),WD(this).handleArraySwap(e,t,n),(r?.dontValidate??!1)||(this.validateField(e,`change`),this.validateField(`${e}[${t}]`,`change`),this.validateField(`${e}[${n}]`,`change`))},this.moveFieldValues=(e,t,n,r)=>{this.setFieldValue(e,e=>{let r=[...e];return r.splice(n,0,r.splice(t,1)[0]),r},AD(r,{dontValidate:!0})),WD(this).handleArrayMove(e,t,n),(r?.dontValidate??!1)||(this.validateField(e,`change`),this.validateField(`${e}[${t}]`,`change`),this.validateField(`${e}[${n}]`,`change`))},this.clearFieldValues=(e,t)=>{let n=this.getFieldValue(e),r=Array.isArray(n)?Math.max(n.length-1,0):null;if(this.setFieldValue(e,[],AD(t,{dontValidate:!0})),WD(this).bumpArrayVersion(e),r!==null)for(let t=0;t<=r;t++){let n=`${e}[${t}]`;this.deleteField(n)}(t?.dontValidate??!1)||this.validateField(e,`change`)},this.resetField=e=>{this.baseStore.setState(t=>{let n=this.getFieldInfo(e).instance?.options.defaultValue,r=mD(this.options.defaultValues,e),i=n??r;return{...t,fieldMetaBase:{...t.fieldMetaBase,[e]:UD},values:i===void 0?t.values:hD(t.values,e,i)}})},this.setErrorMap=e=>{tD(()=>{Object.entries(e).forEach(([e,t])=>{let n=e;if(ED(t)){let{formError:e,fieldErrors:r}=qD(t);for(let e of Object.keys(this.fieldInfo))this.getFieldMeta(e)&&this.setFieldMeta(e,t=>({...t,errorMap:{...t.errorMap,[n]:r?.[e]},errorSourceMap:{...t.errorSourceMap,[n]:`form`}}));this.baseStore.setState(t=>({...t,errorMap:{...t.errorMap,[n]:e}}))}else this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[n]:t}}))})})},this.getAllErrors=()=>({form:{errors:this.state.errors,errorMap:this.state.errorMap},fields:Object.entries(this.state.fieldMeta).reduce((e,[t,n])=>(Object.keys(n).length&&n.errors.length&&(e[t]={errors:n.errors,errorMap:n.errorMap}),e),{})}),this.parseValuesWithSchema=e=>VD.validate({value:this.state.values,validationSource:`form`},e),this.parseValuesWithSchemaAsync=e=>VD.validateAsync({value:this.state.values,validationSource:`form`},e),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=e?.formId??PD(),this._devtoolsSubmissionOverride=!1;let t=GD({...e?.defaultState,values:e?.defaultValues??e?.defaultState?.values});if(e?.transform){t=e.transform({state:t}).state;for(let e of Object.keys(t.errorMap)){let n=t.errorMap[e];if(!(n===void 0||!ED(n)))for(let r of Object.keys(n.fields)){let i=n.fields[r];if(i===void 0)continue;let a=t.fieldMetaBase[r];t.fieldMetaBase[r]={isTouched:!1,isValidating:!1,isBlurred:!1,isDirty:!1,_arrayVersion:0,_pendingValidationsCount:0,...a??{},errorSourceMap:{...a?.errorSourceMap??{},onChange:`form`},errorMap:{...a?.errorMap??{},[e]:i}}}}}this.baseStore=cD(t);let n;this.fieldMetaDerived=cD(e=>{let t=this.baseStore.get(),r=0,i={};for(let a of Object.keys(t.fieldMetaBase)){let o=t.fieldMetaBase[a],s=n?.fieldMetaBase[a],c=e?.[a],l=mD(t.values,a),u=c?.errors;if(!s||o.errorMap!==s.errorMap){u=Object.values(o.errorMap??{}).filter(e=>e!==void 0);let e=this.getFieldInfo(a)?.instance;(!e||!e.options.disableErrorFlat)&&(u=u.flat(1))}let d=!CD(u),f=!o.isDirty,p=DD(l,this.getFieldInfo(a)?.instance?.options.defaultValue??mD(this.options.defaultValues,a));if(c&&c.isPristine===f&&c.isValid===d&&c.isDefaultValue===p&&c.errors===u&&o===s){i[a]=c,r++;continue}i[a]={...o,errors:u??[],isPristine:f,isValid:d,isDefaultValue:p}}return Object.keys(t.fieldMetaBase).length?e&&r===Object.keys(t.fieldMetaBase).length?e:(n=this.baseStore.get(),i):i}),this.formGroupMetaDerived=cD(e=>{let t=this.baseStore.get(),n=this.fieldMetaDerived.get(),r={};for(let i of this.formGroupApis){let a=i.name,o=t.formGroupStateBase[a]??{isSubmitted:!1,isSubmitting:!1,isValidating:!1,submissionAttempts:0,isSubmitSuccessful:!1},s=n[a],c=!1,l=!0,u=!1,d=!1,f=!0,p=!1;for(let e in n){if(e===a||!LD(a,e))continue;let t=n[e];t&&(t.isValidating&&(c=!0),t.isValid||(l=!1),t.isTouched&&(u=!0),t.isBlurred&&(d=!0),t.isDefaultValue||(f=!1),t.isDirty&&(p=!0))}let m=!p,h=!!c||o.isValidating,g=s?.errorMap??{},_=s?.errorSourceMap??{},v=!!(g.onMount||Object.entries(n).some(([e,t])=>t&&e!==a&&LD(a,e)&&t.errorMap.onMount)),y=e?.[a],b=y?.errors??[];(!y||y.__srcErrorMap!==g)&&(b=Object.values(g).reduce((e,t)=>{if(t===void 0)return e;if(t&&typeof t==`object`&&`fields`in t){let n=t.group;return n!==void 0&&e.push(n),e}return e.push(t),e},[]));let x=b.length===0,S=l&&x,C=i.options.canSubmitWhenInvalid??!1,w=o.submissionAttempts===0&&!u&&!v||!h&&!o.isSubmitting&&S||C;if(y&&y.errorMap===g&&y.errorSourceMap===_&&y.errors===b&&y.isFieldsValidating===c&&y.isFieldsValid===l&&y.isGroupValid===x&&y.isValid===S&&y.canSubmit===w&&y.isTouched===u&&y.isBlurred===d&&y.isPristine===m&&y.isDefaultValue===f&&y.isDirty===p&&y.isValidating===h&&y.isSubmitting===o.isSubmitting&&y.isSubmitted===o.isSubmitted&&y.submissionAttempts===o.submissionAttempts&&y.isSubmitSuccessful===o.isSubmitSuccessful){r[a]=y;continue}let T={...o,errorMap:g,errorSourceMap:_,_arrayVersion:s?._arrayVersion??0,isTouched:u,isBlurred:d,isDirty:p,isPristine:m,isDefaultValue:f,isValid:S,errors:b,isValidating:h,isFieldsValidating:c,isFieldsValid:l,isGroupValid:x,canSubmit:w};Object.defineProperty(T,"__srcErrorMap",{value:g,enumerable:!1,configurable:!0}),r[a]=T}return r});let r;this.store=cD(e=>{let t=this.baseStore.get(),n=this.fieldMetaDerived.get(),i=Object.values(n).filter(Boolean),a=i.some(e=>e.isValidating),o=i.every(e=>e.isValid),s=i.some(e=>e.isTouched),c=i.some(e=>e.isBlurred),l=i.every(e=>e.isDefaultValue),u=s&&t.errorMap?.onMount,d=i.some(e=>e.isDirty),f=!d,p=!!(t.errorMap?.onMount||i.some(e=>e?.errorMap?.onMount)),m=!!a,h=e?.errors??[];(!r||t.errorMap!==r.errorMap)&&(h=Object.values(t.errorMap).reduce((e,t)=>t===void 0?e:t&&ED(t)?(e.push(t.form),e):(e.push(t),e),[]));let g=h.length===0,_=o&&g,v=this.options.canSubmitWhenInvalid??!1,y=t.submissionAttempts===0&&!s&&!p||!m&&!t.isSubmitting&&_||v,b=t.errorMap;if(u&&(h=h.filter(e=>e!==t.errorMap.onMount),b=Object.assign(b,{onMount:void 0})),e&&r&&e.errorMap===b&&e.fieldMeta===this.fieldMetaDerived.state&&e.errors===h&&e.isFieldsValidating===a&&e.isFieldsValid===o&&e.isFormValid===g&&e.isValid===_&&e.canSubmit===y&&e.isTouched===s&&e.isBlurred===c&&e.isPristine===f&&e.isDefaultValue===l&&e.isDirty===d&&DD(r,t))return e;let x={...t,errorMap:b,fieldMeta:this.fieldMetaDerived.state,errors:h,isFieldsValidating:a,isFieldsValid:o,isFormValid:g,isValid:_,canSubmit:y,isTouched:s,isBlurred:c,isPristine:f,isDefaultValue:l,isDirty:d};return r=this.baseStore.get(),x}),this.handleSubmit=this.handleSubmit.bind(this),this.update(e||{})}get state(){return this.store.state}get formId(){return this._formId}runValidator(e){return HD(e.validate)?VD[e.type](e.value,e.validate):e.validate(e.value)}handleSubmit(e){return this._handleSubmit(e)}};function qD(e){return e?ED(e)?{formError:qD(e.form).formError,fieldErrors:e.fields}:{formError:e}:{formError:void 0}}function JD(e){switch(e){case`submit`:return`onSubmit`;case`blur`:return`onBlur`;case`mount`:return`onMount`;case`server`:return`onServer`;case`dynamic`:return`onDynamic`;default:return`onChange`}}var YD=class e{constructor(t){this.options={},this.mount=()=>{this.options.defaultValue!==void 0&&!this.getMeta().isTouched&&this.form.setFieldValue(this.name,this.options.defaultValue,{dontUpdateMeta:!0});let e=this.getInfo();e.instance=this,this.update(this.options);let{onMount:t}=this.options.validators||{};if(t){let e=this.runValidator({validate:t,value:{value:this.state.value,fieldApi:this,validationSource:`field`},type:`validate`});e&&this.setMeta(t=>({...t,errorMap:{...t?.errorMap,onMount:e},errorSourceMap:{...t?.errorSourceMap,onMount:`field`}}))}return this.options.listeners?.onMount?.({value:this.state.value,fieldApi:this}),()=>{for(let[e,t]of Object.entries(this.timeoutIds.validations))t&&(clearTimeout(t),this.timeoutIds.validations[e]=null);for(let[e,t]of Object.entries(this.timeoutIds.listeners))t&&(clearTimeout(t),this.timeoutIds.listeners[e]=null);for(let[e,t]of Object.entries(this.timeoutIds.formListeners))t&&(clearTimeout(t),this.timeoutIds.formListeners[e]=null);let e=this.form.fieldInfo[this.name];if(e&&e.instance===this){for(let[t,n]of Object.entries(e.validationMetaMap))n?.lastAbortController.abort(),e.validationMetaMap[t]=void 0;this.form.baseStore.setState(e=>({...e,fieldMetaBase:{...e.fieldMetaBase,[this.name]:{...UD,isTouched:e.fieldMetaBase[this.name]?.isTouched??UD.isTouched,isBlurred:e.fieldMetaBase[this.name]?.isBlurred??UD.isBlurred,isDirty:e.fieldMetaBase[this.name]?.isDirty??UD.isDirty}}})),e.instance=null,this.options.listeners?.onUnmount?.({value:this.state.value,fieldApi:this}),this.form.options.listeners?.onFieldUnmount?.({formApi:this.form,fieldApi:this})}}},this.update=e=>{this.options=e,this.name=e.name,!this.state.meta.isTouched&&this.options.defaultValue!==void 0&&(DD(this.form.getFieldValue(this.name),e.defaultValue)||this.form.setFieldValue(this.name,e.defaultValue,{dontUpdateMeta:!0,dontValidate:!0,dontRunListeners:!0})),this.form.getFieldMeta(this.name)||this.form.setFieldMeta(this.name,this.state.meta)},this.getValue=()=>this.form.getFieldValue(this.name),this.setValue=(e,t)=>{this.form.setFieldValue(this.name,e,AD(t,{dontRunListeners:!0,dontValidate:!0})),t?.dontRunListeners||this.triggerOnChangeListener(),t?.dontValidate||this.validate(`change`)},this.getMeta=()=>this.store.state.meta,this.setMeta=e=>this.form.setFieldMeta(this.name,e),this.getInfo=()=>this.form.getFieldInfo(this.name),this.pushValue=(e,t)=>{this.form.pushFieldValue(this.name,e,AD(t,{dontRunListeners:!0})),t?.dontRunListeners||this.triggerOnChangeListener()},this.insertValue=(e,t,n)=>{this.form.insertFieldValue(this.name,e,t,AD(n,{dontRunListeners:!0})),n?.dontRunListeners||this.triggerOnChangeListener()},this.replaceValue=(e,t,n)=>{this.form.replaceFieldValue(this.name,e,t,AD(n,{dontRunListeners:!0})),n?.dontRunListeners||this.triggerOnChangeListener()},this.removeValue=(e,t)=>{this.form.removeFieldValue(this.name,e,AD(t,{dontRunListeners:!0})),t?.dontRunListeners||this.triggerOnChangeListener()},this.swapValues=(e,t,n)=>{this.form.swapFieldValues(this.name,e,t,AD(n,{dontRunListeners:!0})),n?.dontRunListeners||this.triggerOnChangeListener()},this.moveValue=(e,t,n)=>{this.form.moveFieldValues(this.name,e,t,AD(n,{dontRunListeners:!0})),n?.dontRunListeners||this.triggerOnChangeListener()},this.clearValues=e=>{this.form.clearFieldValues(this.name,AD(e,{dontRunListeners:!0})),e?.dontRunListeners||this.triggerOnChangeListener()},this.getLinkedFields=t=>{let n=Object.values(this.form.fieldInfo),r=[];for(let i of n){if(!i.instance||!(i.instance instanceof e))continue;let{onChangeListenTo:n,onBlurListenTo:a}=i.instance.options.validators||{};t===`change`&&n?.includes(this.name)&&r.push(i.instance),t===`blur`&&a?.includes(this.name)&&r.push(i.instance)}return r},this.validateSync=(e,t)=>{let n=wD(e,{...this.options,form:this.form,fieldName:this.name,validationLogic:this.form.options.validationLogic||RD}),r=this.getLinkedFields(e).reduce((t,n)=>{let r=wD(e,{...n.options,form:n.form,fieldName:n.name,validationLogic:n.form.options.validationLogic||RD});return r.forEach(e=>{e.field=n}),t.concat(r)},[]),i=!1;tD(()=>{let e=(e,n)=>{let r=ZD(n.cause),a=n.validate?XD(e.runValidator({validate:n.validate,value:{value:e.store.state.value,validationSource:`field`,fieldApi:e},type:`validate`})):void 0,o=t[r],{newErrorValue:s,newSource:c}=kD({formLevelError:o,fieldLevelError:a});e.state.meta.errorMap?.[r]!==s&&e.setMeta(e=>({...e,errorMap:{...e.errorMap,[r]:s},errorSourceMap:{...e.errorSourceMap,[r]:c}})),s&&(i=!0)};for(let t of n)e(this,t);for(let t of r)t.validate&&e(t.field,t)});let a=ZD(`submit`);return this.state.meta.errorMap?.[a]&&e!==`submit`&&!i&&this.setMeta(e=>({...e,errorMap:{...e.errorMap,[a]:void 0},errorSourceMap:{...e.errorSourceMap,[a]:void 0}})),{hasErrored:i}},this.validateAsync=async(e,t)=>{let n=TD(e,{...this.options,form:this.form,fieldName:this.name,validationLogic:this.form.options.validationLogic||RD}),r=await t,i=this.getLinkedFields(e).reduce((t,n)=>{let r=TD(e,{...n.options,form:n.form,fieldName:n.name,validationLogic:n.form.options.validationLogic||RD});return r.forEach(e=>{e.field=n}),t.concat(r)},[]),a=[],o=[],s=n.some(e=>e.validate),c=Array.from(new Set(i.filter(e=>e.validate).map(e=>e.field)));tD(()=>{s&&this.startValidation();for(let e of c)e.startValidation()});let l=(e,t,n)=>{let i=ZD(t.cause),a=e.getInfo();a.validationMetaMap[i]?.lastAbortController.abort();let o=new AbortController;a.validationMetaMap[i]={lastAbortController:o},n.push(new Promise(async n=>{let a;try{a=await new Promise((n,r)=>{e.timeoutIds.validations[t.cause]&&(clearTimeout(e.timeoutIds.validations[t.cause]),e.endValidation()),e.timeoutIds.validations[t.cause]=setTimeout(async()=>{if(o.signal.aborted)return n(void 0);try{n(await this.runValidator({validate:t.validate,value:{value:e.store.state.value,fieldApi:e,signal:o.signal,validationSource:`field`},type:`validateAsync`}))}catch(e){r(e)}},t.debounceMs)})}catch(e){a=e}if(o.signal.aborted)return n(void 0);let s=XD(a),c=r[e.name]?.[i],{newErrorValue:l,newSource:u}=kD({formLevelError:c,fieldLevelError:s});if(e.getInfo().instance!==e)return n(void 0);e.setMeta(e=>({...e,errorMap:{...e?.errorMap,[i]:l},errorSourceMap:{...e.errorSourceMap,[i]:u}})),n(l)}))};for(let e of n)e.validate&&l(this,e,a);for(let e of i)e.validate&&l(e.field,e,o);let u=[];return(a.length||o.length)&&(u=await Promise.all(a),await Promise.all(o)),tD(()=>{s&&this.endValidation();for(let e of c)e.endValidation()}),u.filter(Boolean)},this.validate=(e,t)=>{if(!this.state.meta.isTouched)return[];let n=t?.skipGroupValidation?[]:Array.from(this.form.formGroupApis).filter(e=>this.name.startsWith(e.name)),r=(t?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(e)).fieldsErrorMap[this.name]??{};if(!t?.skipFormValidation)for(let t of n){if(t.state.meta.submissionAttempts===0)continue;let{fieldsErrorMap:n}=this.form.validateSync(e,{group:t,dontUpdateFormErrorMap:!0,filterFieldNames:e=>LD(t.name,e)});r={...r,...n[this.name]??{}}}let{hasErrored:i}=this.validateSync(e,r),a=new WeakMap;for(let t of n){let{hasErrored:n}=t.validateSync(e,{},{skipRelatedFieldValidation:!0});a.set(t,n)}if(i&&!this.options.asyncAlways){this.getInfo().validationMetaMap[ZD(e)]?.lastAbortController.abort();let t=[];for(let r of n)r.getInfo().validationMetaMap[ZD(e)]?.lastAbortController.abort(),t.push(r.state.meta.errors);return[...this.state.meta.errors,...t.flat()]}let o=t?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(e),s=this.validateAsync(e,o),c=[];for(let t of n)a.get(t)&&!t.options.asyncAlways||c.push(t.validateAsync(e,o,{skipRelatedFieldValidation:!0}));return c.length===0?s:Promise.all([s,...c]).then(e=>e.flat())},this.handleChange=e=>{this.setValue(e)},this.handleBlur=()=>{this.state.meta.isTouched||this.setMeta(e=>({...e,isTouched:!0})),this.state.meta.isBlurred||this.setMeta(e=>({...e,isBlurred:!0})),this.validate(`blur`),this.triggerOnBlurListener()},this.setErrorMap=e=>{this.setMeta(t=>({...t,errorMap:{...t.errorMap,...e}}))},this.parseValueWithSchema=e=>VD.validate({value:this.state.value,validationSource:`field`},e),this.parseValueWithSchemaAsync=e=>VD.validateAsync({value:this.state.value,validationSource:`field`},e),this.triggerOnBlurListener=()=>{let e=this.form.options.listeners?.onBlurDebounceMs;e&&e>0?(this.timeoutIds.formListeners.blur&&clearTimeout(this.timeoutIds.formListeners.blur),this.timeoutIds.formListeners.blur=setTimeout(()=>{this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this})},e)):this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onBlurDebounceMs;t&&t>0?(this.timeoutIds.listeners.blur&&clearTimeout(this.timeoutIds.listeners.blur),this.timeoutIds.listeners.blur=setTimeout(()=>{this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this})},t)):this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this})},this.triggerOnChangeListener=()=>{let e=this.form.options.listeners?.onChangeDebounceMs;e&&e>0?(this.timeoutIds.formListeners.change&&clearTimeout(this.timeoutIds.formListeners.change),this.timeoutIds.formListeners.change=setTimeout(()=>{this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this})},e)):this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onChangeDebounceMs;t&&t>0?(this.timeoutIds.listeners.change&&clearTimeout(this.timeoutIds.listeners.change),this.timeoutIds.listeners.change=setTimeout(()=>{this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this})},t)):this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this});for(let e of this.form.formGroupApis)LD(e.name,this.name)&&e.triggerOnChangeListener()},this.triggerOnSubmitListener=()=>{this.options.listeners?.onSubmit?.({value:this.state.value,fieldApi:this})},this.form=t.form,this.name=t.name,this.options=t,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=cD(e=>{this.form.store.get();let n=this.form.getFieldMeta(this.name)??{...UD,...t.defaultMeta},r=this.form.getFieldValue(this.name);return!n.isTouched&&r===void 0&&this.options.defaultValue!==void 0&&!DD(r,this.options.defaultValue)&&(r=this.options.defaultValue),e&&e.value===r&&e.meta===n?e:{value:r,meta:n}})}get state(){return this.store.state}runValidator(e){return HD(e.validate)?VD[e.type](e.value,e.validate):e.validate(e.value)}startValidation(){this.setMeta(e=>{let t=e._pendingValidationsCount+1;return{...e,_pendingValidationsCount:t,isValidating:t>0&&!e.isValidating||e.isValidating}})}endValidation(){this.setMeta(e=>{let t=Math.max(0,e._pendingValidationsCount-1);return{...e,_pendingValidationsCount:t,isValidating:t===0&&e.isValidating?!1:e.isValidating}})}};function XD(e){if(e)return e}function ZD(e){switch(e){case`submit`:return`onSubmit`;case`blur`:return`onBlur`;case`mount`:return`onMount`;case`server`:return`onServer`;case`dynamic`:return`onDynamic`;default:return`onChange`}}function QD(e){return{isSubmitted:e.isSubmitted??!1,isSubmitting:e.isSubmitting??!1,isValidating:e.isValidating??!1,submissionAttempts:e.submissionAttempts??0,isSubmitSuccessful:e.isSubmitSuccessful??!1}}function $D(e){return{...UD,...e,errors:[],isPristine:!0,isValid:!0,isDefaultValue:!0,isFieldsValidating:!1,isFieldsValid:!0,isGroupValid:!0,canSubmit:!0,isSubmitting:!1,isSubmitted:!1,isValidating:!1,submissionAttempts:0,isSubmitSuccessful:!1}}var eO=class e{constructor(t){this.options={},this.setFormGroupState=e=>{this.form.baseStore.setState(t=>{let n=t.formGroupStateBase[this.name]??QD({});return{...t,formGroupStateBase:{...t.formGroupStateBase,[this.name]:e(n)}}})},this._lastDistributedFieldNames={},this.update=e=>{this.options=e,this.name=e.name,!this.state.meta.isTouched&&this.options.defaultValue!==void 0&&(DD(this.form.getFieldValue(this.name),e.defaultValue)||this.form.setFieldValue(this.name,e.defaultValue,{dontUpdateMeta:!0,dontValidate:!0,dontRunListeners:!0})),this.form.getFieldMeta(this.name)||this.form.setFieldMeta(this.name,{...UD,...this.options.defaultMeta})},this.mount=()=>{this.update(this.options),this.form.formGroupApis.add(this),this.fieldInfo.instance=this,this.form.baseStore.setState(e=>({...e,formGroupStateBase:{...e.formGroupStateBase,[this.name]:e.formGroupStateBase[this.name]??QD({...this.options.defaultState})}}));let{onMount:e}=this.options.validators||{};if(e){let t=this.runValidator({validate:e,value:{value:this.state.value,groupApi:this,validationSource:`form`},type:`validate`}),n=t,r;nO(t)&&(n=t.group,r=t.fields);let i=tO(n);i&&this.setMeta(e=>({...e,errorMap:{...e.errorMap,onMount:i},errorSourceMap:{...e.errorSourceMap,onMount:`field`}})),this.distributeFieldErrors(`onMount`,r)}return this.options.listeners?.onMount?.({value:this.state.value,groupApi:this}),()=>{for(let[e,t]of Object.entries(this.timeoutIds.validations))t&&(clearTimeout(t),this.timeoutIds.validations[e]=null);for(let[e,t]of Object.entries(this.timeoutIds.listeners))t&&(clearTimeout(t),this.timeoutIds.listeners[e]=null);for(let[e,t]of Object.entries(this.timeoutIds.formListeners))t&&(clearTimeout(t),this.timeoutIds.formListeners[e]=null);if(this.fieldInfo.instance===this){for(let[e,t]of Object.entries(this.fieldInfo.validationMetaMap))t?.lastAbortController.abort(),this.fieldInfo.validationMetaMap[e]=void 0;this.form.formGroupApis.delete(this),this.form.baseStore.setState(e=>({...e,formGroupStateBase:{...e.formGroupStateBase,[this.name]:QD({})}})),this.fieldInfo.instance=null,this.options.listeners?.onUnmount?.({value:this.state.value,groupApi:this})}}},this.setValue=(e,t)=>{this.form.setFieldValue(this.name,e,AD(t,{dontRunListeners:!0,dontValidate:!0})),t?.dontRunListeners||this.triggerOnChangeListener(),t?.dontValidate||this.validate(`change`)},this.getMeta=()=>this.store.state.meta,this.setMeta=e=>this.form.setFieldMeta(this.name,e),this.getInfo=()=>this.fieldInfo,this.getRelatedFields=()=>{let e=Object.values(this.form.fieldInfo),t=[];for(let n of e)n.instance&&n.instance instanceof YD&&n.instance.name.startsWith(this.name)&&t.push(n.instance);return t},this.getRelatedFieldMetasDerived=()=>{let e=Object.entries(this.form.fieldMetaDerived.state),t=[];for(let[n,r]of e)n!==this.name&&LD(this.name,n)&&t.push({...r,name:n});return t},this.buildChildFieldName=e=>e===``?this.name:e.startsWith(`[`)?`${this.name}${e}`:`${this.name}.${e}`,this.distributeFieldErrors=(e,t)=>{let n=this._lastDistributedFieldNames[e]??new Set,r=new Set;if(t)for(let[e,n]of Object.entries(t))n!=null&&n!==!1&&r.add(this.buildChildFieldName(e));let i=new Set([...n,...r]),a=!1;for(let n of i){let r=n.startsWith(this.name+`[`)?n.slice(this.name.length):n.slice(this.name.length+1),i=t?.[r],o=this.form.getFieldMeta(n);if(!o&&!i)continue;let s=o?.errorMap[e],{newErrorValue:c,newSource:l}=OD({newFormValidatorError:i,isPreviousErrorFromFormValidator:o?.errorSourceMap[e]===`form`,previousErrorValue:s});c&&(a=!0),(s!==c||o?.errorSourceMap[e]!==l)&&this.form.setFieldMeta(n,(t=UD)=>({...t,errorMap:{...t.errorMap,[e]:c},errorSourceMap:{...t.errorSourceMap,[e]:l}}))}return this._lastDistributedFieldNames[e]=r,a},this.validateSync=(t,n,r={})=>{let i=wD(t,{...this.options,form:this.form,group:this,validationLogic:this.options.validationLogic||this.form.options.validationLogic||RD}),a=(r.skipRelatedFieldValidation?[]:this.getRelatedFields()).reduce((e,n)=>{let r=wD(t,{...n.options,form:n.form,validationLogic:n.form.options.validationLogic||RD});return r.forEach(e=>{e.field=n}),e.concat(r)},[]),o=!1;tD(()=>{let t=(t,r)=>{let i=iO(r.cause),a=t===this,s;r.validate&&(s=t.runValidator({validate:r.validate,value:{value:t.store.state.value,validationSource:a?`form`:`field`,...t instanceof e?{groupApi:t}:{fieldApi:t}},type:`validate`}));let c=s,l;a&&nO(s)&&(c=s.group,l=s.fields);let u=tO(c),d=n[i],{newErrorValue:f,newSource:p}=kD({formLevelError:d,fieldLevelError:u});t.state.meta.errorMap?.[i]!==f&&t.setMeta(e=>({...e,errorMap:{...e.errorMap,[i]:f},errorSourceMap:{...e.errorSourceMap,[i]:p}})),f&&(o=!0),a&&this.distributeFieldErrors(i,l)&&(o=!0)};for(let e of i)t(this,e);for(let e of a)e.validate&&t(e.field,e)});let s=iO(`submit`);return this.state.meta.errorMap?.[s]&&t!==`submit`&&!o&&this.setMeta(e=>({...e,errorMap:{...e.errorMap,[s]:void 0},errorSourceMap:{...e.errorSourceMap,[s]:void 0}})),{hasErrored:o}},this.validateAsync=async(t,n,r={})=>{let i=TD(t,{...this.options,form:this.form,group:this,validationLogic:this.options.validationLogic||this.form.options.validationLogic||RD}),a=await n,o=r.skipRelatedFieldValidation?[]:this.getRelatedFields(),s=o.reduce((e,n)=>{let r=TD(t,{...n.options,form:n.form,validationLogic:n.form.options.validationLogic||RD});return r.forEach(e=>{e.field=n}),e.concat(r)},[]),c=[],l=[],u=i.some(e=>e.validate)||s.some(e=>e.validate);if(u){this.state.meta.isValidating||this.setMeta(e=>({...e,isValidating:!0}));for(let e of o)e.setMeta(e=>({...e,isValidating:!0}))}let d=(t,n,r)=>{let i=iO(n.cause),o=t.getInfo();o.validationMetaMap[i]?.lastAbortController.abort();let s=new AbortController;o.validationMetaMap[i]={lastAbortController:s};let c=t===this;r.push(new Promise(async r=>{let o;try{o=await new Promise((r,i)=>{t.timeoutIds.validations[n.cause]&&clearTimeout(t.timeoutIds.validations[n.cause]),t.timeoutIds.validations[n.cause]=setTimeout(async()=>{if(s.signal.aborted)return r(void 0);try{r(await this.runValidator({validate:n.validate,value:{value:t.store.state.value,signal:s.signal,validationSource:c?`form`:`field`,...t instanceof e?{groupApi:t}:{fieldApi:t}},type:`validateAsync`}))}catch(e){i(e)}},n.debounceMs)})}catch(e){o=e}if(s.signal.aborted)return r(void 0);let l=o,u;c&&nO(o)&&(l=o.group,u=o.fields);let d=tO(l),f=a[t.name]?.[i],{newErrorValue:p,newSource:m}=kD({formLevelError:f,fieldLevelError:d});if(t.getInfo().instance!==t)return r(void 0);t.setMeta(e=>({...e,errorMap:{...e?.errorMap,[i]:p},errorSourceMap:{...e.errorSourceMap,[i]:m}})),c&&this.distributeFieldErrors(i,u),r(p)}))};for(let e of i)e.validate&&d(this,e,c);for(let e of s)e.validate&&d(e.field,e,l);let f=[];if((c.length||l.length)&&(f=await Promise.all(c),await Promise.all(l)),u){this.setMeta(e=>({...e,isValidating:!1}));for(let e of o)e.setMeta(e=>({...e,isValidating:!1}))}return f.filter(Boolean)},this.validateAllFields=async e=>{let t=[];return tD(()=>{Object.values(this.getRelatedFields()).forEach(n=>{t.push(Promise.resolve().then(()=>n.validate(e,{skipFormValidation:!0,skipGroupValidation:!0}))),n.store.state.meta.isTouched||n.setMeta(e=>({...e,isTouched:!0}))})}),(await Promise.all(t)).flat()},this.validateArrayFieldsStartingFrom=(e,t,n)=>this.form.validateArrayFieldsStartingFrom(e,t,n),this.validateField=(e,t)=>this.form.validateField(e,t),this.getFieldValue=e=>this.form.getFieldValue(e),this.getFieldMeta=e=>this.form.getFieldMeta(e),this.setFieldMeta=(e,t)=>this.form.setFieldMeta(e,t),this.setFieldValue=(e,t)=>this.form.setFieldValue(e,t),this.deleteField=e=>this.form.deleteField(e),this.pushFieldValue=(e,t)=>this.form.pushFieldValue(e,t),this.insertFieldValue=(e,t,n)=>this.form.insertFieldValue(e,t,n),this.replaceFieldValue=(e,t,n)=>this.form.replaceFieldValue(e,t,n),this.swapFieldValues=(e,t,n)=>this.form.swapFieldValues(e,t,n),this.moveFieldValues=(e,t,n)=>this.form.moveFieldValues(e,t,n),this.clearFieldValues=e=>this.form.clearFieldValues(e),this.resetField=e=>this.form.resetField(e),this.removeFieldValue=(e,t)=>this.form.removeFieldValue(e,t),this.areRelatedFieldsValid=()=>Object.values(this.getRelatedFields()).every(e=>e.state.meta.isValid),this.validate=(e,t)=>{let{fieldsErrorMap:n}=t?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(e,{dontUpdateFormErrorMap:!0,filterFieldNames:e=>LD(this.name,e)}),{hasErrored:r}=this.validateSync(e,n[this.name]??{},{skipRelatedFieldValidation:t?.skipRelatedFieldValidation});if(r&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[iO(e)]?.lastAbortController.abort(),this.state.meta.errors;let i=t?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(e,{dontUpdateFormErrorMap:!0,filterFieldNames:e=>LD(this.name,e)});return this.validateAsync(e,i,{skipRelatedFieldValidation:t?.skipRelatedFieldValidation})},this.triggerOnChangeListener=()=>{let e=this.form.options.listeners?.onChangeGroupDebounceMs;e&&e>0?(this.timeoutIds.formListeners.change&&clearTimeout(this.timeoutIds.formListeners.change),this.timeoutIds.formListeners.change=setTimeout(()=>{this.form.options.listeners?.onChangeGroup?.({formApi:this.form,groupApi:this})},e)):this.form.options.listeners?.onChangeGroup?.({formApi:this.form,groupApi:this});let t=this.options.listeners?.onChangeDebounceMs;t&&t>0?(this.timeoutIds.listeners.change&&clearTimeout(this.timeoutIds.listeners.change),this.timeoutIds.listeners.change=setTimeout(()=>{this.options.listeners?.onChange?.({value:this.state.value,groupApi:this})},t)):this.options.listeners?.onChange?.({value:this.state.value,groupApi:this})},this.triggerOnSubmitListener=()=>{this.options.listeners?.onSubmit?.({value:this.state.value,groupApi:this})},this._handleSubmit=async e=>{this.setFormGroupState(e=>({...e,isSubmitted:!1,submissionAttempts:e.submissionAttempts+1,isSubmitSuccessful:!1})),tD(()=>{Object.values(this.getRelatedFields()).forEach(e=>{e.state.meta.isTouched||e.setMeta(e=>({...e,isTouched:!0}))})});let t=e??this.options.onSubmitMeta;this.setFormGroupState(e=>({...e,isSubmitting:!0}));let n=()=>{this.setFormGroupState(e=>({...e,isSubmitting:!1}))};if(await this.validateAllFields(`submit`),!this.areRelatedFieldsValid()){n(),this.options.onGroupSubmitInvalid?.({value:this.state.value,groupApi:this,meta:t});return}if(await this.validate(`submit`,{skipRelatedFieldValidation:!0}),!this.areRelatedFieldsValid()||!this.state.meta.isValid){n(),this.options.onGroupSubmitInvalid?.({value:this.state.value,groupApi:this,meta:t});return}tD(()=>{Object.values(this.getRelatedFields()).forEach(e=>{e.options.listeners?.onGroupSubmit?.({value:e.state.value,fieldApi:e})})}),this.options.listeners?.onSubmit?.({groupApi:this,value:this.state.value});try{await this.options.onGroupSubmit?.({value:this.state.value,groupApi:this,meta:t}),tD(()=>{this.setFormGroupState(e=>({...e,isSubmitted:!0,isSubmitSuccessful:!0})),n()})}catch(e){throw this.setFormGroupState(e=>({...e,isSubmitSuccessful:!1})),n(),e}},this.form=t.form,this.name=t.name,this.options=t,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.fieldInfo={instance:null,validationMetaMap:{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}},this.store=cD(e=>{this.form.formGroupMetaDerived.get(),this.form.baseStore.get();let n=this.form.getFormGroupMeta(this.name)??$D(t.defaultMeta),r=this.form.getFieldValue(this.name);return!n.isTouched&&r===void 0&&this.options.defaultValue!==void 0&&!DD(r,this.options.defaultValue)&&(r=this.options.defaultValue),e&&e.value===r&&e.meta===n?e:{value:r,meta:n}}),this.handleSubmit=this.handleSubmit.bind(this)}get state(){return this.store.state}runValidator(e){if(HD(e.validate)){let t=VD[e.type](e.value,e.validate);return e.type===`validate`?rO(t):t.then(rO)}return e.validate(e.value)}handleSubmit(e){return this._handleSubmit(e)}};function tO(e){if(e)return e}function nO(e){return!!e&&typeof e==`object`&&`fields`in e}function rO(e){if(!e||typeof e!=`object`||!(`form`in e)&&!(`fields`in e))return e;let{form:t,fields:n,...r}=e;return{...r,group:t,fields:n}}function iO(e){switch(e){case`submit`:return`onSubmit`;case`blur`:return`onBlur`;case`mount`:return`onMount`;case`server`:return`onServer`;case`dynamic`:return`onDynamic`;default:return`onChange`}}function aO(e,t){if(!t)return;let n=Object.assign({},e,{state:ID(e.state)});t(n),n.fieldInfo!==e.fieldInfo&&(e.fieldInfo=n.fieldInfo),n.options!==e.options&&(e.options=n.options);let r=Object.keys({values:null,validationMetaMap:null,fieldMetaBase:null,formGroupStateBase:null,isSubmitting:null,isSubmitted:null,isValidating:null,submissionAttempts:null,isSubmitSuccessful:null,_force_re_eval:null}).reduce((t,r)=>(e.state[r]!==n.state[r]&&(t[r]=n.state[r]),t),{});return tD(()=>{Object.keys(r).length&&e.baseStore.setState(e=>({...e,...r})),n.state.errorMap!==e.state.errorMap&&e.setErrorMap(n.state.errorMap)}),n}var oO=ge();function sO(e,t){return e===t}function cO(e,t=e=>e,n){let r=n?.compare??sO,i=(0,J.useCallback)(t=>{let{unsubscribe:n}=e.subscribe(t);return n},[e]),a=(0,J.useCallback)(()=>e.get(),[e]);return(0,oO.useSyncExternalStoreWithSelector)(i,a,a,t,r)}var lO=typeof window<`u`?J.useLayoutEffect:J.useEffect;function uO(e){let[t,n]=(0,J.useState)(()=>({form:e.form,name:e.name})),[r,i]=(0,J.useState)(()=>new YD({...e})),a=r;(t.form!==e.form||t.name!==e.name)&&(a=new YD({...e}),i(a),n({form:e.form,name:e.name}));let o=cO(a.store,e.mode===`array`?e=>e.meta._arrayVersion||0:e=>e.value),s=cO(a.store,e=>e.meta.isTouched),c=cO(a.store,e=>e.meta.isBlurred),l=cO(a.store,e=>e.meta.isDirty),u=cO(a.store,e=>e.meta.errorMap),d=cO(a.store,e=>e.meta.errorSourceMap),f=cO(a.store,e=>e.meta.isValidating),p=(0,J.useMemo)(()=>({...a,get state(){return{value:e.mode===`array`?a.state.value:o,get meta(){return{...a.state.meta,isTouched:s,isBlurred:c,isDirty:l,errorMap:u,errorSourceMap:d,isValidating:f}}}}}),[a,e.mode,o,s,c,l,u,d,f]);return lO(a.mount,[a]),lO(()=>{a.update(e)}),p}var dO=(({children:e,...t})=>{let n=uO(t),r=(0,J.useMemo)(()=>pD(e,n),[e,n]);return(0,X.jsx)(X.Fragment,{children:r})});function fO(){return(0,J.useState)(()=>PD())[0]}var pO=J,mO=`18.3.1`.split(`.`)[0]===`17`?fO:pO.useId;function hO(e){let[t,n]=(0,J.useState)(()=>({form:e.form,name:e.name})),[r,i]=(0,J.useState)(()=>new eO({...e}));(t.form!==e.form||t.name!==e.name)&&(i(new eO({...e})),n({form:e.form,name:e.name}));let a=cO(r.store,e=>e.value),o=cO(r.store,e=>e.meta.isTouched),s=cO(r.store,e=>e.meta.isBlurred),c=cO(r.store,e=>e.meta.isDirty),l=cO(r.store,e=>e.meta.errorMap),u=cO(r.store,e=>e.meta.errorSourceMap),d=cO(r.store,e=>e.meta.isValidating),f=cO(r.store,e=>e.meta.isSubmitting),p=cO(r.store,e=>e.meta.isSubmitted),m=cO(r.store,e=>e.meta.submissionAttempts),h=cO(r.store,e=>e.meta.isSubmitSuccessful),g=cO(r.store,e=>e.meta.canSubmit),_=cO(r.store,e=>e.meta.isValid),v=cO(r.store,e=>e.meta.isFieldsValid),y=cO(r.store,e=>e.meta.isFieldsValidating),b=cO(r.store,e=>e.meta.isGroupValid),x=(0,J.useMemo)(()=>({...r,handleSubmit:((...e)=>r._handleSubmit(...e)),get state(){return{...r.state,value:a,get meta(){return{...r.state.meta,isTouched:o,isBlurred:s,isDirty:c,errorMap:l,errorSourceMap:u,isValidating:d,isSubmitting:f,isSubmitted:p,submissionAttempts:m,isSubmitSuccessful:h,canSubmit:g,isValid:_,isFieldsValid:v,isFieldsValidating:y,isGroupValid:b}}}}}),[r,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b]);return lO(r.mount,[r]),lO(()=>{r.update(e)}),x}var gO=(({children:e,...t})=>{let n=hO(t),r=(0,J.useMemo)(()=>pD(e,n),[e,n]);return(0,X.jsx)(X.Fragment,{children:r})});function _O({form:e,selector:t=e=>e,children:n}){let r=cO(e.store,t);return(0,X.jsx)(X.Fragment,{children:pD(n,r)})}function vO(e){let t=mO(),[n,r]=(0,J.useState)(e?.formId),[i,a]=(0,J.useState)(()=>new KD({...e,formId:e?.formId??t}));if(n!==e?.formId){let n=e?.formId??t;a(new KD({...e,formId:n})),r(n)}let o=(0,J.useMemo)(()=>{let e={...i,handleSubmit:((...e)=>i._handleSubmit(...e)),get formId(){return i._formId},get state(){return i.store.state}};return e.Field=function(e){return(0,X.jsx)(dO,{...e,form:i})},e.FormGroup=function(e){return(0,X.jsx)(gO,{...e,form:i})},e.Subscribe=function(e){return(0,X.jsx)(_O,{form:i,selector:e.selector,children:e.children})},e},[i]);lO(i.mount,[]),lO(()=>{i.update(e)});let s=(0,J.useRef)(!1);return lO(()=>{s.current&&e?.transform&&aO(i,e.transform)},[i,e?.transform]),lO(()=>{s.current=!0}),o}var yO=xa(I),bO=xa(F({message:I}));function xO(e){for(let t of e.errors){let e=ui(ni(gi(bO(t),e=>e.message),()=>yO(t)));if(e!==void 0&&e.length>0)return e}}var SO={neutral:`progress-neutral`,primary:`progress-primary`,secondary:`progress-secondary`,accent:`progress-accent`,success:`progress-success`,info:`progress-info`,warning:`progress-warning`,error:`progress-error`},CO=(0,J.forwardRef)(function({className:e,tone:t=`primary`,...n},r){return(0,X.jsx)(`progress`,{...n,"data-complete":n.value!==void 0&&Number(n.value)>=Number(n.max??1)?`true`:void 0,className:ft(`progress caps-gooey-motion caps-gooey-progress w-full`,SO[t],e),ref:r})});(0,J.forwardRef)(function({label:e,value:t,max:n,tone:r=`info`,className:i,...a},o){return(0,X.jsxs)(`div`,{...a,ref:o,className:ft(`caps-game-meter`,i),children:[(0,X.jsxs)(`div`,{className:`caps-game-meter-readout`,children:[(0,X.jsx)(`span`,{children:e}),(0,X.jsxs)(`span`,{className:`caps-game-meter-value`,children:[t,` / `,n]})]}),(0,X.jsx)(CO,{"aria-label":e,value:t,max:n,tone:r})]})});function wO({className:e,items:t,onCancel:n,onRemove:r,onRetry:i,rowClassName:a}){return t.length?(0,X.jsx)(`div`,{"aria-live":`polite`,className:`caps-upload-queue flex w-full min-w-0 flex-col gap-sm ${e??``}`,"data-upload-rows":!0,children:t.map(e=>(0,X.jsx)(DO,{item:e,onCancel:n,onRemove:r,onRetry:i,...a===void 0?{}:{rowClassName:a}},e.id))}):null}function TO({action:e,id:t,onAction:n,retry:r=!1}){return e?(0,X.jsx)(We,{"aria-label":e.accessibleLabel,title:e.label,variant:`ghost`,size:`xs`,className:`motion-reduce:transition-none`,icon:r?(0,X.jsx)(hE,{}):(0,X.jsx)(on,{}),onClick:()=>void n(t),type:`button`}):null}function EO({item:e}){return(0,X.jsxs)(`div`,{className:`min-w-0`,children:[(0,X.jsx)(`span`,{className:`block min-w-0 truncate`,title:e.name,children:e.name}),(0,X.jsx)(`div`,{className:`caps-upload-details`,children:(0,X.jsxs)(`span`,{"aria-live":e.alert?`assertive`:void 0,className:`caps-upload-status min-w-0 break-words`,"data-upload-status":!0,role:e.alert?`alert`:void 0,children:[e.alert??e.statusLabel,` `,e.progressLabel]})})]})}function DO({item:e,onCancel:t,onRemove:n,onRetry:r,rowClassName:i}){return(0,X.jsxs)(`div`,{className:`caps-upload-row grid w-full min-w-0 max-w-full grid-cols-[2rem_minmax(0,1fr)_auto] items-center gap-sm p-sm text-xs ${i??``}`,children:[e.preview.kind===`image`?(0,X.jsx)(`img`,{alt:``,className:`caps-upload-preview mask mask-squircle size-8 shrink-0 object-cover`,src:e.preview.url}):(0,X.jsx)(`span`,{"aria-hidden":`true`,className:`caps-upload-preview mask mask-squircle flex size-8 shrink-0 items-center justify-center bg-base-300`,children:(0,X.jsx)(dE,{className:`size-4`})}),(0,X.jsx)(EO,{item:e}),(0,X.jsx)(OO,{actions:e.actions,id:e.id,onCancel:t,onRemove:n,onRetry:r}),(0,X.jsx)(CO,{"aria-label":`${e.name} progress`,className:`caps-upload-progress`,tone:e.alert?`error`:e.progress===100?`success`:`accent`,max:100,value:e.progress??(e.alert?0:void 0)})]})}function OO({actions:e,id:t,onCancel:n,onRemove:r,onRetry:i}){return(0,X.jsxs)(`div`,{className:`caps-upload-actions flex min-w-0 flex-wrap justify-end gap-xs`,children:[(0,X.jsx)(TO,{action:e.retry,id:t,onAction:i,retry:!0}),(0,X.jsx)(TO,{action:e.cancel,id:t,onAction:n}),(0,X.jsx)(TO,{action:e.remove,id:t,onAction:r})]})}var kO=J.createContext(void 0);function AO(e){let t=J.useContext(kO);if(t===void 0&&!e)throw Error(Ue(47));return t}var jO={...k,disabled:e=>e.disabled,instantType:e=>e.instantType===`trigger-change`&&!k.open(e)?void 0:e.instantType,openMethod:e=>e.openMethod,openChangeReason:e=>e.openChangeReason,isPressOpenedByTrigger:(e,t)=>e.openChangeReason===`trigger-press`&&k.isOpenedByTrigger(e,t),isTouchPressOpen:(e,t)=>t&&e.openMethod===`touch`&&e.openChangeReason===`trigger-press`,hasTriggerFocusGuards:(e,t)=>k.isOpenedByTrigger(e,t)&&!e.focusManagerModal,modal:e=>e.modal,titleElementId:e=>e.titleElementId,descriptionElementId:e=>e.descriptionElementId,openOnHover:e=>e.openOnHover,closeDelay:e=>e.closeDelay,adaptiveOrigin:e=>e.adaptiveOrigin},MO=class extends ce{constructor(e,t,n){let r=new Ve;super(NO(e,r,t,n),PO(r),jO)}setOpen=(e,t)=>{let n=t.reason===h,r=t.reason===`trigger-press`&&t.event.detail===0,i=!e&&(t.reason===`escape-key`||t.reason==null),a=ie(t),o=this.select(`activeTriggerId`);if(!e&&t.reason===`close-press`&&t.trigger==null&&o!=null&&(t.trigger=this.context.triggerElements.getById(o)??this.select(`activeTriggerElement`)??void 0),this.context.onOpenChange?.(e,t),t.isCanceled)return;this.state.floatingRootContext.dispatchOpenChange(e,t);let s=()=>{let n=st(this.state,e,t.trigger,a());n.openChangeReason=t.reason,this.update(n)};n?(this.context.stickIfOpen=!0,this.context.stickIfOpenTimeout.start(500,()=>{this.context.stickIfOpen=!1}),Fx.flushSync(s)):s();let c;r?c=`click`:i?c=`dismiss`:t.reason===`focus-out`&&(c=`focus`),this.set(`instantType`,c)}};function NO(e,t,n,r=!1){let i={...Ne(t,n,r),disabled:!1,modal:!1,focusManagerModal:!1,instantType:void 0,openMethod:null,openChangeReason:null,titleElementId:void 0,descriptionElementId:void 0,openOnHover:!1,closeDelay:0,adaptiveOrigin:void 0,...e};return i.open&&e?.mounted===void 0&&(i.mounted=!0),i}function PO(e){return{popupRef:J.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerFocusTargetRef:J.createRef(),beforeTriggerFocusGuardRef:J.createRef(),beforeContentFocusGuardRef:J.createRef(),stickIfOpenTimeout:new g,stickIfOpen:!0,triggerElements:e}}var FO=C(function({props:e}){let{children:t,open:n,defaultOpen:r=!1,onOpenChange:i,onOpenChangeComplete:a,modal:o=!1,handle:s,triggerId:c,defaultTriggerId:l=null}=e,u=LO(s,{modal:o,open:r,openProp:n,activeTriggerId:l,triggerIdProp:c});u.useControlledProp(`openProp`,n),u.useControlledProp(`triggerIdProp`,c);let d=u.useState(`open`),f=u.useState(`mounted`),m=u.useState(`payload`);u.useContextCallback(`onOpenChange`,i),u.useContextCallback(`onOpenChangeComplete`,a),pt(u,d),M(u);let{forceUnmount:h}=pe(d,u,()=>{u.context.stickIfOpen=!0,u.set(`openChangeReason`,null)});u.useSyncedValues({modal:o}),J.useEffect(()=>{d||u.context.stickIfOpenTimeout.clear()},[u,d]),J.useImperativeHandle(e.actionsRef,()=>({unmount:h,close:()=>u.setOpen(!1,Ke(ar))}),[h,u]);let g=d||f||s!=null;return(0,X.jsxs)(kO.Provider,{value:u,children:[s&&(0,X.jsx)(p,{handle:s,store:u}),g&&(0,X.jsx)(RO,{store:u,modal:o}),typeof t==`function`?t({payload:m}):t]})});function IO(e){return AO(!0)?(0,X.jsx)(FO,{props:e}):(0,X.jsx)(Qt,{children:(0,X.jsx)(FO,{props:e})})}function LO(e,t){let n=ue((e,n)=>new MO(t,e,n));return J.useEffect(()=>n.context.stickIfOpenTimeout.disposeEffect(),[n]),n}function RO({store:e,modal:t}){let n=e.useState(`floatingRootContext`),r=It(n,{outsidePressEvent:{mouse:t===`trap-focus`?`sloppy`:`intentional`,touch:`sloppy`}}),i=r.reference,a=r.floating;return Mn(e,{activeTriggerProps:i,inactiveTriggerProps:i,popupProps:a}),null}function zO(e,t){function n(n,r,i){let a=n.currentTarget;Fx.flushSync(()=>{e.setOpen(!1,Ke(Dt,n.nativeEvent,a))}),oe(a.isConnected?a:t.current,r,i)?.focus()}function r(t){n(t,-1,e.select(`positionerElement`))}function i(t){let r=e.select(`positionerElement`);r&&me(t,r)?e.context.beforeContentFocusGuardRef.current?.focus():n(t,1,r)}return{handlePreFocusGuardFocus:r,handleFocusTargetFocus:i}}var BO=y(function(e,t){let{render:n,className:r,style:i,disabled:a=!1,nativeButton:o=!0,handle:s,payload:c,openOnHover:l=!1,delay:u=300,closeDelay:d=0,id:f,...p}=e,m=AO(!0),h=Te(s)??m;if(!h)throw Error(Ue(74));let g=bt(f),_=h.useState(`isTriggerActive`,g),v=h.useState(`floatingRootContext`),y=h.useState(`isOpenedByTrigger`,g),b=h.useState(`triggerPopupId`,g),x=J.useRef(null),{registerTrigger:S,isMountedByThisTrigger:C}=ut(g,x,h,{payload:c,disabled:a,openOnHover:l,closeDelay:d}),w=h.useState(`isPressOpenedByTrigger`,g),T=h.useState(`isTouchPressOpen`,l),E=h.useState(`hasTriggerFocusGuards`,g),D=Lx(v,{enabled:!a&&l&&!T,mouseOnly:!0,move:!1,handleClose:Gx(),restMs:u,delay:{close:d},triggerElementRef:x,isActiveTrigger:_,isClosing:()=>h.select(`transitionStatus`)===`ending`}),O=Oe(()=>h.context.stickIfOpen),k=Wn(v,{stickIfOpen:O}),M=A(()=>h.select(`open`),e=>{h.set(`openMethod`,e)}),ee=h.useState(`triggerProps`,C),{getButtonProps:te,buttonRef:ne}=dt({disabled:a,native:o}),re={open(e){return w?j.open(e):fe.open(e)}},{handlePreFocusGuardFocus:ie,handleFocusTargetFocus:ae}=zO(h,x),oe=Qn(`button`,e,{state:{disabled:a,open:y},ref:[ne,t,S,x],props:[k.reference,D,ee,M,{[qn]:``,id:g,"aria-haspopup":`dialog`,"aria-expanded":y,"aria-controls":b},p,te],stateAttributesMapping:re}),se=(0,X.jsx)(J.Fragment,{children:oe},g);return E?(0,X.jsxs)(J.Fragment,{children:[(0,X.jsx)(Dn,{ref:h.context.beforeTriggerFocusGuardRef,onFocus:ie}),se,(0,X.jsx)(Dn,{ref:h.context.triggerFocusTargetRef,onFocus:ae})]}):se}),VO=J.createContext(void 0);function HO(){let e=J.useContext(VO);if(e===void 0)throw Error(Ue(45));return e}var UO=J.forwardRef(function(e,t){let{keepMounted:n=!1,...r}=e;return AO().useState(`mounted`)||n?(0,X.jsx)(VO.Provider,{value:n,children:(0,X.jsx)(kt,{ref:t,...r})}):null}),WO=J.createContext(void 0);function GO(){let e=J.useContext(WO);if(!e)throw Error(Ue(46));return e}function KO(e){let{store:t,domReference:n,positionerElement:r,open:i}=e,a=J.useRef(null),o=J.useRef(null),s=Le(r);D(()=>{i||(o.current?.abort(),o.current=null,t.state.instantType===`trigger-change`&&t.set(`instantType`,void 0))},[i,t]),D(()=>{let e=n,r=a.current;if(e&&(a.current=e),!r||!e||e===r||!t.select(`open`))return;t.set(`instantType`,void 0);let i=new AbortController;return o.current=i,s(()=>{t.select(`open`)&&t.set(`instantType`,`trigger-change`)},i.signal),()=>{i.abort()}},[n,s,t])}var qO=20;function JO(e,t,n,r){let[i,a]=J.useState(!1);D(()=>{if(!e||!t||n==null){a(!1);return}let r=ze(n).documentElement.clientWidth,i=n.offsetWidth;a(r>0&&i>0&&i>=r-qO)},[e,t,n]),de(e&&(!t||i),r)}var YO=J.forwardRef(function(e,t){let{render:n,className:r,style:i,anchor:a,positionMethod:o,side:s,align:c,sideOffset:l,alignOffset:u,collisionBoundary:d=`clipping-ancestors`,collisionPadding:f,arrowPadding:p,sticky:m,disableAnchorTracking:h=!1,collisionAvoidance:g=Vt,..._}=e,v=AO(),y=HO(),b=Ct(),x=v.useState(`floatingRootContext`),S=v.useState(`mounted`),C=v.useState(`open`),w=v.useState(`openChangeReason`),T=v.useState(`activeTriggerElement`),E=v.useState(`modal`),D=v.useState(`openMethod`),O=v.useState(`positionerElement`),k=v.useState(`instantType`),A=v.useState(`transitionStatus`),j=xC({anchor:a,floatingRootContext:x,positionMethod:o,mounted:S,side:s,sideOffset:l,align:c,alignOffset:u,arrowPadding:p,collisionBoundary:d,collisionPadding:f,sticky:m,disableAnchorTracking:h,keepMounted:y,nodeId:b,collisionAvoidance:g,adaptiveOrigin:v.useState(`adaptiveOrigin`)});KO({store:v,domReference:x.useState(`domReferenceElement`),positionerElement:O,open:C});let M=E===!0&&w!==`trigger-hover`;JO(C&&M,D===`touch`,O,T);let ee=v.useStateSetter(`positionerElement`),te=TC(e,{open:C,side:j.side,align:j.align,anchorHidden:j.anchorHidden,instant:k},{styles:j.positionerStyles,transitionStatus:A,props:_,refs:[t,ee],hidden:!S,inert:!C});return(0,X.jsxs)(WO.Provider,{value:j,children:[S&&M&&(0,X.jsx)(kn,{inert:be(!C),cutout:T}),(0,X.jsx)(Fn,{id:b,children:te})]})}),XO=J.createContext(void 0);function ZO(e){let t=J.useContext(XO);if(t===void 0&&!e)throw Error(Ue(69));return t}var QO=J.createContext(void 0);function $O(){let[e,t]=J.useState(0),n=Oe(()=>(t(e=>e+1),()=>{t(e=>Math.max(0,e-1))}));return{context:J.useMemo(()=>({register:n}),[n]),hasClosePart:e>0}}var ek=J.forwardRef(function(e,t){let{render:n,className:r,style:i,initialFocus:a,finalFocus:o,...s}=e,c=AO(),l=GO(),u=ZO(!0)!=null,{context:d,hasClosePart:f}=$O(),p=c.useState(`open`),m=c.useState(`openMethod`),h=c.useState(`instantType`),g=c.useState(`transitionStatus`),_=c.useState(`popupProps`),v=c.useState(`titleElementId`),y=c.useState(`descriptionElementId`),b=c.useState(`modal`),x=c.useState(`mounted`),S=c.useState(`openChangeReason`),C=c.useState(`activeTriggerElement`),w=c.useState(`floatingRootContext`),T=w.useState(`floatingId`),E=c.useState(`disabled`),D=c.useState(`openOnHover`),O=c.useState(`closeDelay`);_t({open:p,ref:c.context.popupRef,onComplete(){p&&c.context.onOpenChangeComplete?.(!0)}}),Px(w,{enabled:D&&!E,closeDelay:O});let k=a===void 0?Qe(c.context.popupRef):a,A=b!==!1&&f;c.useSyncedValue(`focusManagerModal`,A);let j=c.useStateSetter(`popupElement`),M={open:p,side:l.side,align:l.align,instant:h,transitionStatus:g},ee=Qn(`div`,e,{state:M,ref:[t,c.context.popupRef,j],props:[_,{id:T,role:`dialog`,...fr,"aria-labelledby":v,"aria-describedby":y,onKeyDown(e){u&&le.has(e.key)&&e.stopPropagation()}},wC(g),s],stateAttributesMapping:ot});return(0,X.jsx)(vn,{context:w,openInteractionType:m,modal:A,disabled:!x||S===`trigger-hover`,initialFocus:k,returnFocus:o,restoreFocus:`popup`,getInsideElements:()=>[c.context.beforeTriggerFocusGuardRef.current],previousFocusableElement:Pt(C)?C:void 0,nextFocusableElement:c.context.triggerFocusTargetRef,beforeContentFocusGuardRef:c.context.beforeContentFocusGuardRef,children:(0,X.jsx)(QO.Provider,{value:d,children:ee})})}),tk=(0,J.forwardRef)(function({children:e,className:t,type:n=`button`,...r},i){return(0,X.jsxs)(`button`,{...r,ref:i,type:n,className:ft(`select caps-select caps-combobox-trigger w-full`,t),children:[(0,X.jsx)(`span`,{children:e}),(0,X.jsx)(en,{className:`caps-select-chevron`,"aria-hidden":`true`})]})});function nk({defaultInputValue:e,defaultOpen:t,defaultValue:n,getKey:r,getSearchText:i,groupBy:a,id:o,isDisabled:s,items:c,onOpenChange:l,onCommit:u,multiple:d,controlledOpen:f,controlledKeys:p,trigger:m}){let h=`${o}-listbox`,[g,_]=(0,J.useState)(e),[v,y]=(0,J.useState)(!1),[b,S]=(0,J.useState)(n),[C,w]=(0,J.useState)(t),T=p??(b===null?[]:[b]),E=m?f??C:!0,D=(0,J.useMemo)(()=>{let e=g.trim().toLowerCase();return e?c.filter(t=>i(t).toLowerCase().includes(e)):c},[i,c,g]),O=Tt({getKey:r,isDisabled:s,items:D});(0,J.useEffect)(()=>{if(O.activeKey!==null)return;let e=O.enabledItems.find(e=>T.includes(r(e)))??O.enabledItems[0];e&&O.setActiveKey(r(e))},[O.activeKey,O.enabledItems,O.setActiveKey,r,T]);let k=e=>{y(!1),e||_(``),f===void 0&&w(e),l?.(e)},A=e=>`${h}-option-${encodeURIComponent(e)}`,j=e=>{let t=r(e);p===void 0&&S(t),u(e),m&&!d&&k(!1)},M=e=>{y(!0),_(e.target.value),O.setActiveKey(null)},ee=e=>{if(x(e))return;let t;switch(e.key){case`ArrowDown`:t=[1,void 0];break;case`ArrowUp`:t=[-1,void 0];break;case`End`:t=[1,`end`];break;case`Home`:t=[-1,`start`]}t?(y(!0),e.preventDefault(),O.move(t[0],t[1])):e.key===`Enter`&&O.activeItem&&(e.preventDefault(),j(O.activeItem))},te=(0,J.useMemo)(()=>{if(!a)return[{label:``,items:D}];let e=new Map;for(let t of D){let n=a(t),r=e.get(n);r?r.push(t):e.set(n,[t])}return[...e].map(([e,t])=>({label:e,items:t}))},[D,a]);return{keyboardNavigation:v,onPointerMove:()=>{y(!1)},activeKey:O.activeKey,activeItem:O.activeItem,groups:te,inputValue:g,listboxId:h,onInputChange:M,onInputKeyDown:ee,optionId:A,open:E,commit:j,selectedKeys:T,setOpen:k}}function rk(e){let{"aria-describedby":t,"aria-invalid":n,"aria-label":r,"aria-labelledby":i,"aria-required":a,activeTone:o=`neutral`,container:s,contentClassName:c,defaultInputValue:u=``,defaultOpen:d=!1,defaultValue:f=null,emptyMessage:p=`No matches`,getKey:m,getLabel:h,getSearchText:g=h,groupBy:_,id:v,inputProps:y,inputRef:b,isDisabled:x=()=>!1,items:S,onOpenChange:C,onValueChange:w,multiple:T,open:E,placeholder:D=`Search…`,renderItem:O,rootRef:k,trigger:A,triggerRef:j,value:M,...ee}=e,te=e=>{let t=m(e);if(T){let e=M.includes(t)?M.filter(e=>e!==t):[...M,t];w?.(e,S.filter(t=>e.includes(m(t))))}else w?.(t,e)},ne;T?ne=M:M!==void 0&&(ne=M===null?[]:[M]);let re=(0,J.useId)(),ie=A?.props??y,ae=v??ie?.id??re,oe={id:ae,"aria-describedby":[t,ie?.[`aria-describedby`]].filter(Boolean).join(` `)||void 0,"aria-invalid":n??ie?.[`aria-invalid`],"aria-label":ie?.[`aria-label`]??r,"aria-labelledby":ie?.[`aria-labelledby`]??i,"aria-required":a??ie?.[`aria-required`]},{keyboardNavigation:se,onPointerMove:ce,activeItem:le,activeKey:N,commit:ue,groups:de,inputValue:fe,listboxId:pe,onInputChange:P,onInputKeyDown:me,open:he,optionId:ge,selectedKeys:ve,setOpen:ye}=nk({defaultInputValue:u,defaultOpen:d,defaultValue:f,getKey:m,getSearchText:g,groupBy:_,id:ae,isDisabled:x,items:S,onOpenChange:C,onCommit:te,multiple:T??!1,controlledOpen:E,controlledKeys:ne,trigger:A});l(()=>{A&&ye(!1)});let be=an(`popover`),xe=s===void 0?be:s,Se=ir(`.caps-combobox-option[data-active="true"]:not(:disabled), [data-navigation="pointer"] .caps-combobox-option:hover:not(:disabled)`),Ce=(0,X.jsx)(He,{...y,...A?{}:oe,"aria-activedescendant":le?ge(m(le)):void 0,"aria-autocomplete":`list`,"aria-controls":pe,"aria-expanded":!0,className:ft(`input-sm`,y?.className),id:A?y?.id??`${ae}-input`:ae,onChange:e=>{y?.onChange?.(e),P(e)},onKeyDown:e=>{y?.onKeyDown?.(e),e.defaultPrevented||me(e)},placeholder:y?.placeholder??D,ref:b,role:`combobox`,value:fe}),we=(0,X.jsx)(`div`,{id:pe,ref:Se,className:`caps-combobox-list`,"data-navigation":se?`keyboard`:`pointer`,onPointerMove:ce,role:`listbox`,"aria-multiselectable":T??void 0,children:de.every(e=>e.items.length===0)?(0,X.jsx)(`div`,{className:`px-md py-md text-sm text-base-content`,children:p}):de.map(e=>(0,X.jsxs)(`div`,{"aria-label":e.label||void 0,role:e.label?`group`:void 0,children:[e.label?(0,X.jsx)(`div`,{className:`px-md pb-xs pt-sm text-xs text-base-content uppercase tracking-wider`,children:e.label}):null,e.items.map(e=>{let t=m(e),n=x(e),r=N===t,i={active:r,disabled:n,selected:ve.includes(t)};return(0,X.jsxs)(`button`,{"aria-disabled":n||void 0,"aria-selected":i.selected,className:`caps-combobox-option`,"data-active":r&&se,disabled:n,id:ge(t),onClick:()=>{ue(e)},onMouseDown:e=>{e.preventDefault()},role:`option`,tabIndex:-1,type:`button`,children:[(0,X.jsx)(`span`,{"aria-hidden":`true`,className:`caps-combobox-check`,children:i.selected?(0,X.jsx)(_e,{}):null}),O?.(e,r,i)??h(e)]},t)})]},e.label))});return A?(0,X.jsx)(`div`,{...ee,className:ft(ee.className),ref:k,children:(0,X.jsxs)(IO,{modal:!0,onOpenChange:ye,open:he,children:[(0,X.jsx)(BO,{...oe,"aria-haspopup":`dialog`,className:`btn`,ref:j,render:A}),xe===null?null:(0,X.jsx)(UO,{container:xe,children:(0,X.jsx)(YO,{align:`start`,side:`bottom`,sideOffset:4,children:(0,X.jsxs)(ek,{"data-active-tone":o,className:ft(`min-w-40 rounded-box border border-base-300 bg-base-100 p-xs shadow-lg outline-none caps-combobox-panel caps-combobox-popup`,c),children:[(0,X.jsx)(`div`,{className:`caps-combobox-search`,children:Ce}),we]})})})]})}):(0,X.jsx)(`div`,{...ee,className:ft(ee.className),ref:k,children:(0,X.jsxs)(`div`,{className:ft(`caps-combobox-panel`,c),"data-active-tone":o,children:[(0,X.jsx)(`div`,{className:`caps-combobox-search`,children:Ce}),we]})})}function ik({icon:e,caption:t}){return(0,X.jsxs)(`span`,{className:`caps-icon-choice-mark`,"aria-hidden":`true`,children:[(0,X.jsx)(`span`,{className:`caps-icon-choice-art`,children:e}),t?(0,X.jsx)(`span`,{className:`caps-icon-choice-caption`,children:t}):null,(0,X.jsx)(`span`,{className:`caps-icon-choice-lamp`})]})}var ak=(0,J.forwardRef)(function({label:e,icon:t,caption:n,appearance:r,className:i,...a},o){return(0,X.jsx)(`label`,{className:`caps-icon-choice`,"data-appearance":r===`compact`?r:void 0,children:(0,X.jsx)(m,{...a,appearance:r??`default`,"aria-label":e,className:ft(`caps-icon-choice-input`,i),indicator:(0,X.jsx)(ik,{icon:t,caption:n}),ref:o})})}),ok=(0,J.forwardRef)(function({label:e,icon:t,hint:n,className:r,...i},a){let o=(0,J.useId)(),s=[i[`aria-describedby`],n?o:null].filter(Boolean).join(` `)||void 0;return(0,X.jsx)(`label`,{className:`caps-check-key`,children:(0,X.jsx)(m,{...i,"aria-label":e,"aria-describedby":s,className:ft(`caps-check-key-input`,r),indicator:(0,X.jsxs)(`span`,{className:`caps-check-key-face`,"aria-hidden":`true`,children:[t?(0,X.jsx)(`span`,{className:`caps-check-key-icon`,children:t}):null,(0,X.jsxs)(`span`,{className:`caps-check-key-copy`,children:[(0,X.jsx)(`span`,{className:`caps-check-key-label`,children:e}),n?(0,X.jsx)(`span`,{className:`caps-check-key-hint`,id:o,children:n}):null]}),(0,X.jsx)(`span`,{className:`caps-check-key-lamp`})]}),ref:a})})});function sk({className:e,...t}){return(0,X.jsx)(`div`,{...t,className:ft(`caps-check-keys`,e)})}function ck({checked:e}){let t=`caps-radio-${(0,J.useId)().replaceAll(`:`,``)}`,n=(0,J.useRef)(null),r=(0,J.useRef)(e).current,i=(0,J.useRef)(e),a=(0,J.useRef)(null),o=f(a),{reduced:s}=o;return(0,J.useLayoutEffect)(()=>{if(!n.current)return;let t=s||i.current===e;i.current=e;let r=e?4:0,a=nn(o,{ease:`outCubic`,duration:75}),c=e?ye(o,{bounce:.65,duration:300}):nn(o,{ease:`inCubic`,duration:100}),l=To(n.current,t?{rx:r,ry:r,cy:6,duration:0}:{rx:[{to:e?3.5:4.15,...a},{to:r,...c}],ry:[{to:e?4.5:3.85,...a},{to:r,...c}],cy:[{to:e?5.85:6.1,...a},{to:6,...c}]});return()=>{l.cancel()}},[e,s,o]),(0,X.jsxs)(`svg`,{ref:a,className:`caps-radio-visual`,width:`24`,height:`24`,viewBox:`0 0 12 12`,"aria-hidden":`true`,focusable:`false`,children:[(0,X.jsxs)(`defs`,{children:[(0,X.jsx)(O,{id:`${t}-surface`,transform:`matrix(1 0 0 1 6 6)`}),(0,X.jsx)(Me,{id:`${t}-shadow`}),(0,X.jsx)(we,{id:`${t}-inset`}),(0,X.jsx)(`clipPath`,{id:`${t}-well`,children:(0,X.jsx)(`circle`,{cx:`6`,cy:`6`,r:`5`})})]}),(0,X.jsx)(`circle`,{className:`caps-radio-track`,cx:`6`,cy:`6`,r:`5.5`,filter:`url(#${t}-inset)`}),(0,X.jsx)(`g`,{clipPath:`url(#${t}-well)`,children:(0,X.jsx)(`ellipse`,{ref:n,cx:`6`,cy:`6`,rx:r?4:0,ry:r?4:0,fill:`url(#${t}-surface)`,filter:`url(#${t}-shadow)`})})]})}var lk=(0,J.createContext)(null),uk=(0,J.forwardRef)(function({children:e,className:t,defaultValue:n,disabled:r=!1,name:i,onValueChange:a,orientation:o=`vertical`,value:s,...c},l){let u=(0,J.useId)(),d=(0,J.useRef)(null);(0,J.useImperativeHandle)(l,()=>{if(!d.current)throw Error(`RadioGroup is not mounted`);return d.current},[]);let f=i??`radio-group-${u}`,[p,m]=(0,J.useState)(n),h=s??p;return(0,J.useEffect)(()=>{let e=d.current?.form;if(!e||s!==void 0)return;let t=e=>{queueMicrotask(()=>{e.defaultPrevented||m(n)})};return e.addEventListener(`reset`,t),()=>{e.removeEventListener(`reset`,t)}},[s,n,c.form]),(0,X.jsx)(lk.Provider,{value:{disabled:r,name:f,onValueChange:e=>{s===void 0&&m(e),a?.(e)},value:h},children:(0,X.jsx)(`fieldset`,{...c,className:ft(`flex gap-md`,o===`horizontal`?`flex-row flex-wrap`:`flex-col`,t),disabled:r,role:c.role??`radiogroup`,ref:d,children:e})})}),dk=(0,J.forwardRef)(function({className:e,indicator:t,onChange:n,onClick:r,value:i,...a},o){let s=(0,J.useContext)(lk);if(!s)throw Error(`RadioGroupItem must be used inside <RadioGroup>`);let c=s.value===i,l=e=>{n?.(e),e.target.checked&&s.onValueChange?.(i)};return(0,X.jsxs)(`span`,{className:`caps-radio`,"data-checked":c,"data-custom-indicator":t!==void 0||void 0,children:[(0,X.jsx)(`input`,{...a,"aria-checked":c,checked:c,className:ft(`caps-radio-input`,e),disabled:s.disabled||a.disabled,name:s.name,onChange:l,onClick:r,ref:o,type:`radio`,value:i}),t===void 0?(0,X.jsx)(ck,{checked:c}):t]})}),fk=(0,J.forwardRef)(function({description:e,id:t,meta:n,title:r,...i},a){let o=(0,J.useContext)(lk),s=(0,J.useId)(),c=t??s,l=o?.value===i.value,u=o?.disabled===!0||i.disabled===!0;return(0,X.jsxs)(`label`,{className:`caps-choice-card`,"data-checked":l,"data-disabled":u||void 0,htmlFor:c,children:[(0,X.jsx)(dk,{...i,"aria-describedby":e?`${c}-description`:void 0,"aria-labelledby":`${c}-title`,id:c,ref:a}),(0,X.jsxs)(`span`,{className:`caps-choice-card-copy`,children:[(0,X.jsx)(`span`,{className:`caps-choice-card-title`,id:`${c}-title`,children:r}),e?(0,X.jsx)(`span`,{className:`caps-choice-card-description`,id:`${c}-description`,children:e}):null]}),n?(0,X.jsx)(`span`,{className:`caps-choice-card-meta`,children:n}):null]})}),pk=(0,J.forwardRef)(function({label:e,icon:t,caption:n,art:r=`dim`,className:i,...a},o){return(0,X.jsx)(`label`,{className:`caps-icon-choice`,"data-art":r===`color`?r:void 0,children:(0,X.jsx)(dk,{...a,"aria-label":e,className:ft(`caps-icon-choice-input`,i),indicator:(0,X.jsx)(ik,{icon:t,caption:n}),ref:o})})}),mk=(0,J.forwardRef)(function({label:e,color:t,className:n,...r},i){return(0,X.jsx)(`label`,{className:`caps-icon-choice`,"data-art":`color`,"data-swatch":``,title:e,children:(0,X.jsx)(dk,{...r,"aria-label":e,className:ft(`caps-icon-choice-input`,n),indicator:(0,X.jsx)(ik,{icon:(0,X.jsx)(`span`,{className:`caps-swatch-dot`,style:{backgroundColor:t}})}),ref:i})})}),hk=(0,J.forwardRef)(function({className:e,invalid:t,...n},r){return(0,X.jsxs)(`span`,{className:`caps-select-shell`,children:[(0,X.jsx)(`select`,{...n,"aria-invalid":t?!0:n[`aria-invalid`]===!1?void 0:n[`aria-invalid`],className:ft(`select select-bordered caps-select w-full`,t&&`select-error`,e),ref:r}),!n.multiple&&(!n.size||n.size<=1)?(0,X.jsx)(en,{className:`caps-select-chevron`,"aria-hidden":`true`}):null]})});function gk({checked:e}){let t=`caps-switch-${(0,J.useId)().replaceAll(`:`,``)}`,n=(0,J.useRef)(null),r=(0,J.useRef)(null),i=(0,J.useRef)(e).current,a=(0,J.useRef)(e),o=nt();return(0,J.useLayoutEffect)(()=>{if(!n.current||!r.current)return;let t=o||a.current===e;a.current=e;let i=e?16:8,s=dr(n.current),c=ye(s,{bounce:.25,duration:440}),l=nn(s,{ease:`inOutSine`,duration:100}),u=To(n.current,t?{x:2,y:2,width:i,height:8,duration:0}:{x:[{to:e?2.5:1.5,...l},{to:2,...c}],y:[{to:1.5,...l},{to:2,...c}],height:[{to:9,...l},{to:8,...c}],width:[{to:e?7:16.5,...l},{to:i,...c}]}),d=To(r.current,{gradientTransform:e?`matrix(2 0 0 1 10 6)`:`matrix(1 0 0 1 6 6)`,...t?{duration:0}:{delay:l.duration,...c}});return()=>{u.cancel(),d.cancel()}},[e,o]),(0,X.jsxs)(`svg`,{className:`caps-switch-visual`,width:`40`,height:`24`,viewBox:`0 0 20 12`,"aria-hidden":`true`,focusable:`false`,children:[(0,X.jsxs)(`defs`,{children:[(0,X.jsx)(O,{ref:r,id:`${t}-surface`,transform:i?`matrix(2 0 0 1 10 6)`:`matrix(1 0 0 1 6 6)`}),(0,X.jsx)(Me,{id:`${t}-shadow`}),(0,X.jsx)(we,{id:`${t}-inset`}),(0,X.jsx)(`clipPath`,{id:`${t}-track`,children:(0,X.jsx)(`rect`,{x:`1`,y:`1`,width:`18`,height:`10`,rx:`5`})})]}),(0,X.jsx)(`rect`,{className:`caps-switch-track`,filter:`url(#${t}-inset)`,x:`0.5`,y:`0.5`,width:`19`,height:`11`,rx:`5.5`}),(0,X.jsx)(`g`,{clipPath:`url(#${t}-track)`,children:(0,X.jsx)(`rect`,{ref:n,x:`2`,y:`2`,width:i?16:8,height:`8`,rx:`4`,fill:`url(#${t}-surface)`,filter:`url(#${t}-shadow)`})})]})}var _k=(0,J.forwardRef)(function({className:e,checked:t,defaultChecked:n=!1,onChange:r,onCheckedChange:i,...a},o){let s=(0,J.useRef)(null),[c,l]=(0,J.useState)(n),u=t??c;return(0,J.useImperativeHandle)(o,()=>{if(!s.current)throw Error(`Switch input is not mounted`);return s.current},[]),(0,J.useEffect)(()=>{let e=s.current?.form;if(!e||t!==void 0)return;let r=e=>{queueMicrotask(()=>{!e.defaultPrevented&&s.current&&l(n)})};return e.addEventListener(`reset`,r),()=>{e.removeEventListener(`reset`,r)}},[t,n,a.form]),(0,X.jsxs)(`span`,{className:`caps-switch`,"data-checked":u,children:[(0,X.jsx)(`input`,{...a,checked:u,className:ft(`caps-switch-input`,e),onChange:e=>{t===void 0&&l(e.target.checked),r?.(e),i?.(e.target.checked)},ref:s,role:`switch`,type:`checkbox`}),(0,X.jsx)(gk,{checked:u})]})}),vk=xa(I),yk=xa(vo),bk=xa(Ki(Ra)),xk=xa(G(I)),Sk=G(Vi(File)),Ck=xa(Sk),wk=V([I,Ra,vo,ga,oa,G(I),Sk]),Tk=xa(wk),Ek=e=>Ei(vk(e.state.value),()=>``),Dk=e=>Ei(yk(e.state.value),()=>!1),Ok=e=>Ei(bk(e.state.value),()=>null),kk=e=>Ei(xk(e.state.value),()=>[]),Ak=e=>Ei(Ck(e.state.value),()=>[]),jk=e=>Ei(Tk(e.state.value),()=>null);function Mk({field:e,spec:t,locked:n,...r}){let[i,a]=(0,J.useState)(!1);return(0,X.jsxs)(pn,{children:[(0,X.jsx)(He,{...r,name:t.name,disabled:n,type:i?`text`:`password`,autoComplete:`off`,spellCheck:!1,className:`caps-field-secret`,placeholder:t.placeholder,readOnly:t.readOnly,value:Ek(e),onBlur:e.handleBlur,onChange:t=>{e.handleChange(t.currentTarget.value)}}),(0,X.jsx)(c,{type:`button`,variant:`outline`,size:`icon`,"aria-label":i?`Hide`:`Show`,"aria-pressed":i,disabled:n,onClick:()=>{a(e=>!e)},children:i?(0,X.jsx)(lE,{"aria-hidden":`true`}):(0,X.jsx)(uE,{"aria-hidden":`true`})})]})}var Nk={text:`text`,email:`email`,url:`url`,tel:`tel`};function Pk({spec:e,field:t,locked:n,...r}){let i=Ak(t),a=n||e.readOnly===!0,o=(0,J.useRef)(null);return(0,X.jsxs)(`div`,{className:`flex flex-col gap-sm`,children:[(0,X.jsx)(se,{asChild:!0,children:(0,X.jsx)(`input`,{...r,ref:o,type:`file`,tabIndex:-1,required:r.required===!0&&i.length===0,name:e.name,accept:e.accept,multiple:e.multiple,disabled:a,onBlur:t.handleBlur,onChange:e=>{t.handleChange(Array.from(e.currentTarget.files??[])),e.currentTarget.value=``}})}),(0,X.jsx)(c,{type:`button`,variant:`outline`,"aria-label":`Choose files for ${e.label}`,"aria-describedby":r[`aria-describedby`],"aria-invalid":r[`aria-invalid`],disabled:a,onBlur:t.handleBlur,onClick:()=>{o.current?.click()},children:`Choose files`}),(0,X.jsx)(wO,{items:i.map((e,t)=>({id:String(t),name:e.name,preview:{kind:`file`},progress:0,progressLabel:`${String(e.size)} bytes`,statusLabel:`Selected`,actions:a?{}:{remove:{label:`Remove`,accessibleLabel:`Remove ${e.name}`}}})),onRemove:e=>{t.handleChange(i.filter((t,n)=>String(n)!==e))},onCancel:()=>void 0,onRetry:()=>void 0})]})}function Fk({spec:e,field:t,locked:n,...r}){let i=e=>{t.handleChange(e)},a={...r,name:e.name,disabled:n,onBlur:t.handleBlur};switch(e.kind){case`text`:case`email`:case`url`:case`tel`:return(0,X.jsx)(He,{...a,type:Nk[e.kind],inputMode:e.kind===`text`?void 0:e.kind,autoComplete:e.autoComplete,placeholder:e.placeholder,maxLength:e.maxLength,readOnly:e.readOnly,value:Ek(t),onChange:e=>{i(e.currentTarget.value)}});case`textarea`:return(0,X.jsx)($n,{...a,rows:e.rows??3,placeholder:e.placeholder,maxLength:e.maxLength,readOnly:e.readOnly,value:Ek(t),onChange:e=>{i(e.currentTarget.value)}});case`secret`:return(0,X.jsx)(Mk,{...r,field:t,spec:e,locked:n});case`money`:return(0,X.jsxs)(pn,{children:[(0,X.jsx)(Kt,{className:`caps-field-currency`,children:e.currency??`USD`}),(0,X.jsx)(He,{...a,inputMode:`decimal`,autoComplete:`off`,className:`caps-field-amount`,placeholder:e.placeholder??`0.00`,readOnly:e.readOnly,value:Ek(t),onChange:e=>{i(e.currentTarget.value)}})]});case`date`:return(0,X.jsx)(He,{...a,type:`date`,readOnly:e.readOnly,value:Ek(t),onChange:e=>{i(e.currentTarget.value)}});case`number`:return(0,X.jsx)(Tn,{...a,...e.min===void 0?{}:{min:e.min},...e.max===void 0?{}:{max:e.max},...e.step===void 0?{}:{step:e.step},...e.unit===void 0?{}:{unit:e.unit},...e.wrap===void 0?{}:{wrap:e.wrap},disabled:n||e.readOnly===!0,decrementLabel:`Decrease ${e.label}`,incrementLabel:`Increase ${e.label}`,value:Ok(t),onValueChange:e=>{t.handleChange(e)}});case`select`:return(0,X.jsxs)(hk,{...a,value:Ek(t),onChange:e=>{i(e.currentTarget.value)},children:[e.placeholder===void 0?null:(0,X.jsx)(`option`,{value:``,disabled:!0,children:e.placeholder}),e.options.map(e=>(0,X.jsx)(`option`,{value:e.value,disabled:e.disabled,children:e.label},e.value))]});case`combobox`:return(0,X.jsx)(rk,{id:r.id??e.name,"aria-describedby":r[`aria-describedby`],"aria-invalid":r[`aria-invalid`],"aria-required":r[`aria-required`],items:e.options,getKey:e=>e.value,getLabel:e=>e.label,isDisabled:t=>t.disabled||n||e.readOnly===!0,value:Ek(t),...e.placeholder===void 0?{}:{placeholder:e.placeholder},trigger:(0,X.jsx)(tk,{name:e.name,disabled:n||e.readOnly===!0,onBlur:t.handleBlur,children:e.options.find(e=>e.value===Ek(t))?.label??e.placeholder??`Choose…`}),inputProps:{"aria-label":`Search ${e.label}`,disabled:n||e.readOnly===!0},onValueChange:e=>{i(e??``),t.handleBlur()}});case`file`:return(0,X.jsx)(Pk,{...r,spec:e,field:t,locked:n});case`checkbox`:return(0,X.jsx)(m,{...a,disabled:n||e.readOnly===!0,checked:Dk(t),onChange:e=>{t.handleChange(e.currentTarget.checked)}});case`switch`:return(0,X.jsx)(_k,{...a,disabled:n||e.readOnly===!0,checked:Dk(t),onCheckedChange:e=>{t.handleChange(e)}});case`radio`:case`icon-radio`:case`checkboxes`:case`icon-checkboxes`:return null}}var Ik=new Set([`radio`,`icon-radio`,`checkboxes`,`icon-checkboxes`]);function Lk({spec:e,field:t,locked:n,error:r,layout:i}){let a=n||e.readOnly===!0,o=e.label;if(e.kind===`checkboxes`||e.kind===`icon-checkboxes`){let n=kk(t),s=(e,r)=>{t.handleChange(r?[...n,e]:n.filter(t=>t!==e))};return(0,X.jsx)(un,{legend:o,icon:e.icon,layout:i,...i===`columns`?{legendTitle:o}:{},description:e.help,disabled:a,error:r??null,children:e.kind===`icon-checkboxes`?(0,X.jsx)(`div`,{className:`caps-field-icon-choices`,children:e.options.map(r=>(0,X.jsx)(ak,{name:e.name,value:r.value,label:r.label,...r.caption===void 0?{}:{caption:r.caption},icon:r.icon,disabled:r.disabled,checked:n.includes(r.value),onBlur:t.handleBlur,onChange:e=>{s(r.value,e.currentTarget.checked)}},r.value))}):(0,X.jsx)(sk,{children:e.options.map(r=>(0,X.jsx)(ok,{name:e.name,value:r.value,label:r.label,icon:r.icon,hint:r.description,disabled:r.disabled,checked:n.includes(r.value),onBlur:t.handleBlur,onChange:e=>{s(r.value,e.currentTarget.checked)}},r.value))})})}let s=e.options.some(e=>e.description!==void 0||e.meta!==void 0);return(0,X.jsx)(un,{legend:o,icon:e.icon,layout:i,...i===`columns`?{legendTitle:o}:{},description:e.help,disabled:a,error:r??null,children:(0,X.jsx)(uk,{name:e.name,"aria-label":o,value:Ek(t),onValueChange:e=>{t.handleChange(e),t.handleBlur()},orientation:e.kind===`icon-radio`||s?`horizontal`:`vertical`,children:e.options.map(t=>e.kind===`icon-radio`?(0,X.jsx)(pk,{value:t.value,label:t.label,...t.caption===void 0?{}:{caption:t.caption},icon:t.icon,disabled:t.disabled},t.value):s?(0,X.jsx)(fk,{value:t.value,title:t.label,description:t.description,meta:t.meta,disabled:t.disabled},t.value):(0,X.jsx)(Rn,{label:t.label,orientation:`inline`,children:(0,X.jsx)(dk,{value:t.value,disabled:t.disabled})},t.value))})})}function Rk({spec:e,field:t,locked:n,error:r,render:i,...a}){return i({name:e.name,label:e.label,help:e.help,value:jk(t),onChange:e=>{t.handleChange(e)},onBlur:t.handleBlur,error:r,disabled:n,id:a.id??e.name,"aria-describedby":a[`aria-describedby`],"aria-invalid":r!==void 0})}function zk({form:e,spec:t,locked:n,layout:r}){let i=uO({form:e,name:t.name}),a=cO(e.store,e=>e.submissionAttempts>0),o=i.state.meta.isBlurred||a?xO(i.state.meta):void 0;if(t.render===void 0&&Ik.has(t.kind))return(0,X.jsx)(Lk,{spec:t,field:i,locked:n,error:o,layout:r});let s=r===`columns`?t.kind===`switch`||t.kind===`checkbox`?`horizontal`:`vertical`:t.kind===`checkbox`?`inline`:(t.layout??(t.kind===`switch`?`row`:`stacked`))===`row`?`horizontal`:`vertical`;return(0,X.jsx)(Rn,{label:t.label,...r===`columns`?{labelTitle:t.label}:{},description:t.help,icon:t.icon,orientation:s,error:o,...t.required===void 0?{}:{required:t.required},...t.optional===void 0?{}:{optional:t.optional},children:t.render===void 0?(0,X.jsx)(Fk,{spec:t,field:i,locked:n}):(0,X.jsx)(Rk,{spec:t,field:i,locked:n,error:o,render:t.render})})}var Bk=xa(_a(I,wk));function Vk({form:e,spec:t,locked:n,layout:r}){let i=t.when;return cO(e.store,e=>i===void 0||i(Ei(Bk(e.values),()=>({}))))?(0,X.jsx)(zk,{form:e,spec:t,locked:n,layout:r}):null}function Hk({form:e,section:t,locked:n,layout:r}){let i=t.fields.map(t=>(0,X.jsx)(Vk,{form:e,spec:t,locked:n,layout:r},t.name));return t.title===void 0?i:(0,X.jsx)(zt,{title:t.title,description:t.description,layout:r,children:i})}function Uk({model:e,names:t,disabled:n=!1,layout:r}){let i=e.form;return t===void 0?e.description.sections.map(e=>(0,X.jsx)(Hk,{form:i,section:e,locked:n,layout:r},e.id??``)):t.map(t=>{let a=e.description.fields.find(e=>e.name===t);return a===void 0?null:(0,X.jsx)(Vk,{form:i,spec:a,locked:n,layout:r},t)})}var Wk=class{annotation;constructor(e){this.annotation=e}},Gk=class{sections;constructor(e){this.sections=e}},Kk=`caps/form`,qk=0;function Jk(e){qk+=1;let t={[`${Kk}:${String(qk)}`]:new Wk(e)};return e.label!==void 0&&(t.title=e.label),e.help!==void 0&&(t.description=e.help),t}I.annotate(Jk({kind:`secret`})).pipe(na(`Secret`));var Yk=e=>{let t=e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/[-_]+/g,` `).toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)};function Xk(e){return Object.values(e??{}).reduce((e,t)=>t instanceof Wk?{...e,...t.annotation}:e,{})}function Zk(e){return e.reduce((e,t)=>({...e,...Xk(t)}),{})}function Qk(e){let t=e?.[Kk];return t instanceof Gk?t.sections:{}}var $k=xa(I);function eA(e){if(Ia(e))return ji($k(e.literal),{onNone:()=>null,onSome:e=>[e]});if(!ro(e))return null;let t=[];for(let n of e.types){if(Aa(n))continue;let e=eA(n);if(e===null)return null;t.push(...e)}return t}function tA(e){if(Ga(e))return{type:`string`,literals:[]};if(to(e))return{type:`number`,nullable:!1};if(fa(e))return{type:`boolean`};let t=eA(e);if(t!==null)return{type:`string`,literals:t};if(Ea(e)){let[t]=e.rest;if(t===void 0)return null;if(Ga(t))return{type:`strings`,literals:[]};let n=eA(t);return n===null?null:{type:`strings`,literals:n}}if(ro(e)){let t=e.types.filter(e=>!Aa(e)&&!ho(e)),n=e.types.some(e=>ho(e)),[r]=t;if(t.length!==1||r===void 0)return null;let i=tA(r);return i?.type===`number`?{type:`number`,nullable:n}:n?null:i}return null}function nA(e){let t=e.ast;if(!lo(t))throw Error(`A schema form needs a Schema.Struct.`);return{fields:t.propertySignatures.map(e=>{let t=String(e.name),n=yo(e.type),r=Zk([e.type.annotations,...(e.type.checks??[]).map(e=>e.annotations)]),i=r.kind===`file`?{type:`files`}:tA(n);if(i===null)throw Error(`Schema field "${t}" has no form control. Annotate it with field({ render }) or a kind.`);return{name:t,valueType:i,optional:e.type.context?.isOptional===!0,annotation:r,title:Za(e.type),description:Ma(e.type)}}),sections:Qk(fo(t))}}function rA(e){let t=e,n=!1,r=!1;for(;;)if(t instanceof Dr)n=!0,t=t.unwrap();else if(t instanceof Ir)r=!0,t=t.unwrap();else if(t instanceof hr)t=t.unwrap();else if(t instanceof wi)t=t.in;else return{node:t,optional:n,nullable:r}}function iA(e){if(e instanceof Br){let t=e.options.map(e=>iA(e));return t.some(e=>e===null)?null:t.flatMap(e=>e??[])}let t=e instanceof Rr?e.options:e instanceof Sr?[...e.values]:null;if(t===null)return null;let n=t.map(e=>$k(e));return n.every(Oi)?n.map(e=>e.value):null}function aA(e){let{node:t,nullable:n}=rA(e);if(t instanceof wr)return{type:`string`,literals:[]};if(t instanceof zr)return{type:`number`,nullable:n};if(t instanceof Bi)return{type:`boolean`};let r=iA(t);if(r!==null)return{type:`string`,literals:r};if(t instanceof Nr){let e=rA(t.element).node;if(e instanceof wr)return{type:`strings`,literals:[]};let n=iA(e);return n===null?null:{type:`strings`,literals:n}}return null}function oA(e){let t=[e];for(;;){let e=t[t.length-1];if(e===void 0)break;let n=e instanceof Dr||e instanceof Ir||e instanceof hr?e.unwrap():e instanceof wi?e.in:e;if(n===e)break;t.push(n)}return t.reverse().map(e=>br.get(e))}function sA(e){return oA(e).reduce((e,t)=>({...e,...t}),{})}function cA(e){return Object.entries(e.shape)}function lA(e){let t=rA(e).node;if(!(t instanceof xr))throw Error(`A schema form needs a z.object.`);return{fields:cA(t).map(([e,t])=>{let n=Zk(oA(t)),r=n.kind===`file`?{type:`files`}:aA(t);if(r===null)throw Error(`Schema field "${e}" has no form control. Annotate it with field({ render }) or a kind.`);let i=sA(t);return{name:e,valueType:r,optional:rA(t).optional,annotation:n,title:i.title,description:i.description}}),sections:Qk(sA(e))}}function uA(e,t){let n=t.options??{};return(e.length>0?e:Object.keys(n)).map(e=>{let t=n[e],r=t===void 0?{}:t instanceof Object?t:{label:t};return{value:e,label:r.label??Yk(e),description:r.description,meta:r.meta,icon:r.icon,caption:r.caption,disabled:r.disabled===!0}})}function dA(e,t){let n=t.some(e=>e.icon!==void 0);switch(e.type){case`boolean`:return`switch`;case`number`:return`number`;case`strings`:return n?`icon-checkboxes`:`checkboxes`;case`files`:return`file`;case`string`:return t.length===0?`text`:t.length>12?`combobox`:n?`icon-radio`:t.some(e=>e.description!==void 0||e.meta!==void 0)||t.length<=3?`radio`:`select`}}function fA(e,t){switch(e.type){case`boolean`:return!1;case`number`:return e.nullable?null:0;case`strings`:case`files`:return[];case`string`:return t[0]?.value??``}}function pA(e){let t=e instanceof Hr?lA(e):nA(e),n=t.fields.map((e,t)=>{let{kind:n,...r}=e.annotation,i=uA(e.valueType.type===`string`||e.valueType.type===`strings`?e.valueType.literals:[],e.annotation),a=r.help??e.description;return{...r,name:e.name,label:r.label??e.title??Yk(e.name),help:a,kind:n??dA(e.valueType,i),options:i,optionalInSchema:e.optional,index:t}}),r={};t.fields.forEach((e,t)=>{let i=n[t];i&&(r[e.name]=fA(e.valueType,i.options))});let i=e=>e.order??e.index,a=e=>e.section!==void 0&&Object.hasOwn(t.sections,e.section)?e.section:null,o=e=>n.filter(t=>a(t)===e).sort((e,t)=>i(e)-i(t)),s=Object.entries(t.sections).map(([e,t])=>({id:e,title:t.title,description:t.description,fields:o(e)}));return{fields:n,sections:[{id:null,title:void 0,description:void 0,fields:o(null)},...s].filter(e=>e.fields.length>0),defaults:r}}function mA(e){let t=e instanceof Hr?e:Zi(e);return{"~standard":{...t[`~standard`],validate:e=>{let n=t[`~standard`].validate(e);return n instanceof Promise?n.then(e=>hA(e)):hA(n)}}}}function hA(e){return e.issues===void 0?e:{issues:e.issues.map(e=>e.path===void 0?e:{...e,path:e.path.slice(0,1)})}}var gA=`onServer`;function _A(e){let t=e.querySelector(`[aria-invalid="true"]`),n=t?.matches(`input, select, textarea, button, [tabindex]`)?t:t?.querySelector(`input, select, textarea, button`);return n?.focus(),n!=null}function vA(e){if(_A(e))return()=>void 0;let t=new MutationObserver(()=>{_A(e)&&t.disconnect()});return t.observe(e,{subtree:!0,childList:!0,attributes:!0,attributeFilter:[`aria-invalid`]}),()=>{t.disconnect()}}function yA(e){return e.state.meta.errorMap.onServer!==void 0}function bA(e){e.setMeta(e=>({...e,errorMap:{...e.errorMap,[gA]:void 0}}))}function xA(e,t,n){e.setFieldMeta(t,e=>({...e,isBlurred:!0,errorMap:{...e.errorMap,[gA]:n}}))}function SA(e){let[t,n]=(0,J.useState)(null),[r,i]=(0,J.useState)(null),[a,o]=(0,J.useState)(e.defaultValues),[s,c]=(0,J.useState)(null);DD(a,e.defaultValues)||(o(e.defaultValues),c(null));let{schema:l}=e,u=(0,J.useMemo)(()=>pA(l),[l]),d=(0,J.useMemo)(()=>mA(l),[l]),f=vO({defaultValues:s??a,validators:{onChange:d,onSubmit:d},listeners:{onChange:({fieldApi:e})=>{n(null),i(null),yA(e)&&bA(e)}},onSubmit:async({value:t,formApi:r})=>{n(null),i(null);let a=await mA(l)[`~standard`].validate(t);if(a.issues){n(a.issues[0]?.message??`Check the form and try again.`);return}let o;try{o=await e.onSubmit(a.value,t)??{kind:`saved`}}catch(t){console.error(`SchemaForm submit failed`,t),n(e.failure??`Couldn't save changes. Try again.`);return}if(o.kind===`refused`){n(o.error??null);let e=r;for(let[t,n]of Object.entries(o.fields??{}))n!==void 0&&n.length>0&&xA(e,t,n);return}let s=o.values??t;c(s),r.reset(s),i(o.message??`Saved`),e.onSaved?.(s)}});return{description:u,form:f,error:t,saved:r,discard:()=>{n(null),i(null),f.reset()},submit:()=>f.handleSubmit()}}function CA(e){return{dirty:cO(e.form.store,e=>!e.isDefaultValue),submitting:cO(e.form.store,e=>e.isSubmitting),canSubmit:cO(e.form.store,e=>e.canSubmit)}}function wA({model:e,submitLabel:t=`Save changes`,discardLabel:n,onCancel:r,cancelLabel:i,allowClean:a,layout:o,footer:s,children:c,disabled:l=!1,...u}){let{submitting:d}=CA(e),f=(0,J.useRef)(null),p=(0,J.useRef)(()=>void 0);return(0,J.useEffect)(()=>()=>{p.current()},[]),(0,X.jsxs)(Kn,{...u,ref:f,layout:o,busy:d,noValidate:!0,onSubmit:t=>{t.preventDefault(),e.form.state.isSubmitting||e.submit().then(()=>{p.current();let t=f.current;t!==null&&!e.form.state.isValid&&(p.current=vA(t))})},children:[c??(0,X.jsx)(Uk,{model:e,disabled:l,layout:o}),s===void 0?(0,X.jsx)(DA,{model:e,label:t,discardLabel:r===void 0?n:void 0,onCancel:r,cancelLabel:i,allowClean:a??r!==void 0,divider:r===void 0}):s]})}function TA({schema:e,defaultValues:t,onSubmit:n,onSaved:r,failure:i,...a}){let o=SA({schema:e,defaultValues:t,onSubmit:n,onSaved:r,failure:i});return(0,X.jsx)(wA,{...a,model:o})}function EA(e){return`model`in e?(0,X.jsx)(wA,{...e}):(0,X.jsx)(TA,{...e})}function DA({model:e,label:t,discardLabel:r,onCancel:i,cancelLabel:a=`Cancel`,allowClean:o=!1,dirtyLabel:s=`Unsaved changes`,buttonProps:l,...u}){let{dirty:d,submitting:f}=CA(e),p=f?null:e.saved&&!d?(0,X.jsx)(n,{tone:`success`,size:`compact`,label:e.saved}):d?(0,X.jsx)(n,{tone:`neutral`,size:`compact`,label:s}):null;return(0,X.jsxs)(jt,{...u,error:e.error,status:p,children:[i?(0,X.jsx)(c,{type:`button`,variant:`ghost`,disabled:f,onClick:i,children:a}):r&&d?(0,X.jsx)(c,{type:`button`,variant:`ghost`,disabled:f,onClick:e.discard,children:r}):null,(0,X.jsx)(c,{...l,type:`submit`,loading:f,disabled:f||!d&&!o,title:!d&&!o?`No changes to save`:void 0,children:t})]})}var OA=e=>e,kA=(e,t)=>{let n=e[t];if(!n)throw Error(`Missing burger path: ${t}`);return n},AA={apiVersion:1,name:`burger`,palette:{bottomBun:`#e9c46a`,bunSpot:`#d4a373`,cheese:`#f4d03f`,dead:`#636e72`,deadTongue:`#b2bec3`,eye:`#2d3436`,lettuce:`#7cb342`,mouth:`#2d3436`,patty:`#5d4037`,tomato:`#e74c3c`,topBun:`#f4a261`,blush:`#feaae4`,tongue:`#f98284`,sweat:`#accce4`,white:`#ffffff`},build({scene:e,color:t}){let n=e.group({name:`root`}),r=e.group({parent:n,name:`body`,updateSort:!0});e.cylinder({parent:r,name:`bottom-bun`,backface:t(`bottomBun`),color:t(`bottomBun`),diameter:34,frontFace:t(`bunSpot`),length:6,rotate:{x:Math.PI/2},stroke:!1,translate:{y:8}}),e.cylinder({parent:r,name:`patty`,color:t(`patty`),diameter:36,frontFace:t(`patty`),length:4,rotate:{x:Math.PI/2},stroke:!1,translate:{y:3}}),e.cylinder({parent:r,name:`tomato`,color:t(`tomato`),diameter:34,frontFace:t(`tomato`),length:2,rotate:{x:Math.PI/2},stroke:!1,translate:{y:-2}});let i=e.hemisphere({parent:r,name:`top-bun`,backface:t(`bunSpot`),color:t(`topBun`),diameter:38,rotate:{x:Math.PI/2},stroke:!1,translate:{y:-3}});for(let[n,r]of[{x:-8,y:-6,z:14},{x:6,y:-8,z:13},{x:0,y:-10,z:12},{x:10,y:-4,z:13},{x:-5,y:-2,z:15},{x:4,y:-12,z:11}].entries())e.path({parent:i,name:`seed.${String(n+1)}`,path:[{x:0,y:0}],color:t(`bunSpot`),stroke:1.2,translate:r});let a=e.group({parent:r,name:`face`,translate:{y:-5,z:16}}),o=jo(e,t,a,{blushMode:`medium-alias`,hideMouth:!0}),s=e.group({parent:r,name:`burger.mouth`,translate:{y:1,z:10}}),c=OA({angry:[{x:-13,y:2},{x:13,y:2},{x:13,y:5},{bezier:[{x:7,y:4},{x:0,y:5},{x:-7,y:4}]},{x:-13,y:5}],happy:[{x:-12,y:0},{bezier:[{x:-6,y:3},{x:0,y:5},{x:6,y:3}]},{x:12,y:0},{x:13,y:2},{bezier:[{x:7,y:5},{x:0,y:7},{x:-7,y:5}]},{x:-13,y:2}],open:[{x:-10,y:0},{bezier:[{x:-10,y:5},{x:-5,y:8},{x:0,y:8}]},{bezier:[{x:5,y:8},{x:10,y:5},{x:10,y:0}]},{x:10,y:1},{bezier:[{x:5,y:6},{x:-5,y:6},{x:-10,y:1}]}],pout:[{x:-8,y:2},{bezier:[{x:0,y:5},{x:8,y:2},{x:8,y:4}]},{x:0,y:6},{x:-8,y:4}],sad:[{x:-12,y:3},{bezier:[{x:-6,y:0},{x:0,y:-1},{x:6,y:0}]},{x:12,y:3},{x:13,y:5},{bezier:[{x:7,y:2},{x:0,y:1},{x:-7,y:2}]},{x:-13,y:5}],small:[{x:-6,y:1},{x:6,y:1},{x:7,y:3},{x:0,y:2},{x:-7,y:3}],surprised:[],worried:[{x:-11,y:1},{bezier:[{x:-6,y:3},{x:-3,y:1},{x:0,y:2}]},{bezier:[{x:3,y:1},{x:6,y:3},{x:11,y:1}]},{x:12,y:3},{x:0,y:4},{x:-12,y:3}],dead:[{x:-12,y:1},{x:12,y:1},{x:13,y:4},{bezier:[{x:7,y:3},{x:0,y:4},{x:-7,y:3}]},{x:-13,y:4}],normal:[{x:-12,y:1},{x:12,y:1},{x:13,y:4},{bezier:[{x:7,y:3},{x:0,y:4},{x:-7,y:3}]},{x:-13,y:4}]}),l=OA({angry:[{x:-13,y:0},{x:13,y:0},{x:13,y:2},{bezier:[{x:7,y:1},{x:0,y:2},{x:-7,y:1}]},{x:-13,y:2}],happy:[{x:-12,y:2},{bezier:[{x:-6,y:0},{x:0,y:-1},{x:6,y:0}]},{x:12,y:2},{x:13,y:3},{bezier:[{x:7,y:1},{x:0,y:0},{x:-7,y:1}]},{x:-13,y:3}],open:[{x:-10,y:2},{bezier:[{x:-10,y:-3},{x:-5,y:-6},{x:0,y:-6}]},{bezier:[{x:5,y:-6},{x:10,y:-3},{x:10,y:2}]},{x:10,y:1},{bezier:[{x:5,y:-4},{x:-5,y:-4},{x:-10,y:1}]}],pout:[{x:-8,y:0},{bezier:[{x:-4,y:-1},{x:0,y:0},{x:4,y:-1}]},{x:8,y:0},{x:9,y:1},{x:0,y:1},{x:-9,y:1}],sad:[{x:-12,y:0},{bezier:[{x:-6,y:2},{x:0,y:3},{x:6,y:2}]},{x:12,y:0},{x:13,y:1},{bezier:[{x:7,y:3},{x:0,y:4},{x:-7,y:3}]},{x:-13,y:1}],small:[{x:-6,y:0},{bezier:[{x:-3,y:1},{x:0,y:0},{x:3,y:1}]},{x:6,y:0},{x:7,y:1},{x:0,y:1},{x:-7,y:1}],surprised:[{x:-13,y:2},{bezier:[{x:-7,y:-2},{x:0,y:-3},{x:7,y:-2}]},{x:13,y:2},{x:14,y:3},{bezier:[{x:8,y:0},{x:0,y:-1},{x:-8,y:0}]},{x:-14,y:3}],worried:[{x:-11,y:1},{bezier:[{x:-6,y:0},{x:-3,y:1},{x:0,y:0}]},{bezier:[{x:3,y:2},{x:6,y:0},{x:11,y:1}]},{x:12,y:2},{bezier:[{x:7,y:1},{x:0,y:1},{x:-7,y:1}]},{x:-12,y:2}],dead:[{x:-12,y:1},{bezier:[{x:-6,y:0},{x:0,y:-.5},{x:6,y:0}]},{x:12,y:1},{x:13,y:2},{bezier:[{x:7,y:1},{x:0,y:.5},{x:-7,y:1}]},{x:-13,y:2}],normal:[{x:-12,y:1},{bezier:[{x:-6,y:0},{x:0,y:-.5},{x:6,y:0}]},{x:12,y:1},{x:13,y:2},{bezier:[{x:7,y:1},{x:0,y:.5},{x:-7,y:1}]},{x:-13,y:2}]}),u={};for(let n of[`normal`,`happy`,`sad`,`angry`,`surprised`,`dead`,`small`,`worried`,`pout`,`open`]){let r=e.group({parent:s,name:`burger.mouth.${n}`}),i={y:n===`open`?2:n===`small`?.5:1.5,z:+(n===`pout`)};n===`surprised`?e.ellipse({parent:r,name:`cheese.${n}`,color:t(`cheese`),fill:!0,height:8,stroke:2,translate:{y:2,z:0},width:6}):e.path({parent:r,name:`cheese.${n}`,color:t(`cheese`),fill:!0,path:kA(c,n),stroke:2,translate:i});let a={y:n===`open`?1:n===`surprised`?-1:-.5,z:n===`pout`?2:1};e.path({parent:r,name:`lettuce.${n}`,color:t(`lettuce`),fill:!0,path:kA(l,n),stroke:1.5,translate:a}),u[n]=r}return{root:n,variants:{eyes:o.eyes,mouth:u,blush:o.blush}}},expressions:Ao,activities:Mo,defaultPresentation:{activity:`idle`,expression:`normal`}},jA=(e,t)=>{let n=e[t];if(!n)throw Error(`Missing cat face node: ${t}`);return n},MA=e=>e,NA={apiVersion:1,name:`cat`,palette:{body:`#ffe6c6`,eye:`#28282e`,mouth:`#28282e`,blush:`#feaae4`,dead:`#6c5671`,deadTongue:`#d9c8bf`,tongue:`#f98284`,stripes:`#dea38b`,sweat:`#accce4`,white:`#ffffff`},build({scene:e,color:t}){let n=e.group({name:`root`}),r=e.group({parent:n,name:`body`,updateSort:!0});e.path({parent:r,name:`body.sphere`,path:[{x:0,y:0}],color:t(`body`),stroke:32});for(let n of[-1,1])e.path({parent:r,name:`ear.${n<0?`left`:`right`}`,color:t(`body`),fill:!0,path:[{x:-6,y:0},{x:6,y:0},{x:0,y:-10}],rotate:{z:.6*n},stroke:3,translate:{x:9*n,y:-10}});let i=e.group({parent:r,name:`face`,translate:{z:20}}),a=jo(e,t,i,{hideMouth:!0}),o=e.group({parent:i,name:`cat.mouth`,translate:{y:6,z:2}}),s=(n,r,i)=>e.path({parent:o,name:`cat.mouth.${n}`,closed:!1,color:t(`mouth`),path:r,stroke:i}),c=MA({normal:s(`normal`,[{x:-2,y:-1},{x:0,y:0},{x:2,y:-1}],1.5),sad:s(`sad`,[{x:-2.5,y:2},{bezier:[{x:0,y:0},{x:2.5,y:2},{x:2.5,y:2}]}],1.5),angry:s(`angry`,[{x:-3,y:1},{x:3,y:1}],2),small:s(`small`,[{x:-1.5,y:0},{x:1.5,y:0}],1),worried:s(`worried`,[{x:-2,y:1},{bezier:[{x:-.5,y:.5},{x:.5,y:.5},{x:2,y:1}]}],1)}),l=e.group({parent:o,name:`cat.mouth.happy`,translate:{y:1}});e.path({parent:l,closed:!1,color:t(`mouth`),path:[{x:-2.5,y:1},{bezier:[{x:0,y:3},{x:2.5,y:1},{x:2.5,y:1}]}],stroke:1.5}),e.ellipse({parent:l,width:2,height:1.5,stroke:0,fill:!0,color:t(`tongue`),translate:{y:2}}),c.happy=l,c.surprised=e.ellipse({parent:o,name:`cat.mouth.surprised`,width:2.5,height:3,stroke:1.5,fill:!0,color:t(`mouth`),translate:{y:1}});let u=e.group({parent:o,name:`cat.mouth.dead`,translate:{y:3}});e.ellipse({parent:u,width:2.5,height:1.5,stroke:1.5,fill:!0,color:t(`dead`)}),e.ellipse({parent:u,width:1.2,height:.8,stroke:0,fill:!0,color:t(`deadTongue`),translate:{y:.5}}),c.dead=u,c.pout=e.ellipse({parent:o,name:`cat.mouth.pout`,width:2,height:2.5,stroke:1.5,fill:!0,color:t(`mouth`),translate:{y:1}}),c.open=e.ellipse({parent:o,name:`cat.mouth.open`,width:4,height:5,stroke:1.5,fill:!0,color:t(`mouth`),translate:{y:1}});let d=e.group({parent:i,name:`whiskers`,translate:{y:5,z:2}});for(let n of[-1,1]){let r=n*12;for(let[i,a]of[-2,0,2].entries())e.path({parent:d,name:`whisker.${n<0?`left`:`right`}.${String(i)}`,closed:!1,color:t(`eye`),path:[{x:0,y:a},{x:n*8,y:a+(i-1)*1.5}],stroke:.8,translate:{x:r,y:a*.5}})}let f={normal:jA(c,`normal`),happy:c.happy,sad:jA(c,`sad`),angry:jA(c,`angry`),surprised:c.surprised,dead:c.dead,small:jA(c,`small`),worried:jA(c,`worried`),pout:c.pout,open:c.open};return{root:n,variants:{eyes:a.eyes,mouth:f,blush:a.blush}}},expressions:Ao,activities:{...Mo,listening:{motion:{target:`root`,rotate:{x:-.2},durationMs:300,repeat:`yoyo`},mouseInfluence:.3},thinking:{motion:{target:`root`,rotate:{z:.1},durationMs:800,repeat:`yoyo`},mouseInfluence:0}},defaultPresentation:{activity:`idle`,expression:`normal`}},PA={apiVersion:1,name:`mushroom`,palette:{body:`#fff7e4`,cap:`#f98284`,capSpot:`#ffe6c6`,eye:`#28282e`,mouth:`#28282e`,dead:`#6c5671`,deadTongue:`#d9c8bf`,tongue:`#f98284`,sweat:`#accce4`,white:`#ffffff`},build({scene:e,color:t}){let n=e.group({name:`root`}),r=e.group({parent:n,name:`body`,updateSort:!0});e.hemisphere({parent:r,name:`body.hemisphere`,backface:t(`cap`),color:t(`body`),diameter:32,rotate:{x:3*Math.PI/2},stroke:!1,translate:{y:2}});let i=e.hemisphere({parent:r,name:`cap.hemisphere`,backface:t(`capSpot`),color:t(`cap`),diameter:42,rotate:{x:Math.PI/2},stroke:!1,translate:{y:2}});e.path({parent:i,name:`cap.spot.front`,path:[{x:0,y:0}],color:t(`capSpot`),stroke:12,translate:{x:-8,y:8,z:12}}),e.path({parent:i,name:`cap.spot.top`,path:[{x:0,y:0}],color:t(`capSpot`),stroke:18,translate:{x:8,y:-4,z:13}});let a=e.group({parent:r,name:`face`,translate:{y:7,z:8}}),o=jo(e,t,a,{blushMode:`none`});return{root:n,variants:{eyes:o.eyes,mouth:o.mouth,blush:o.blush}}},expressions:Ao,activities:{...Mo,error:{geometry:{eyes:`dead`,mouth:`dead`},motion:{target:`root`,rotate:{x:.9},durationMs:600,repeat:`none`},mouseInfluence:.1}},defaultPresentation:{activity:`idle`,expression:`sleepy`}},FA={mushroom:[`cap`,`capSpot`],cat:[`body`,`stripes`],burger:[`topBun`,`bottomBun`]},IA={mushroom:PA,cat:NA,burger:AA};function LA(e){let t=Oo(ko(IA[e])),n=Do.parse(t.data);return{controls:t.controls,expressions:Object.keys(n.expressions),identitySlots:FA[e]}}var RA=new Map;function zA(e){let t=RA.get(e);return t||(t=LA(e),RA.set(e,t)),t}var BA=Object.freeze({get mushroom(){return zA(`mushroom`)},get cat(){return zA(`cat`)},get burger(){return zA(`burger`)}}),VA={mushroom:`Shiitake`,cat:`Cat`,burger:`Burger`},HA=[[`Rose`,`#f98284`,`#ffe6c6`],[`Peach`,`#f6a55c`,`#ffe9c9`],[`Gold`,`#f2d06b`,`#fff6d1`],[`Leaf`,`#9bd47a`,`#e6f8d8`],[`Mint`,`#5fc7b4`,`#d9f6ef`],[`Sky`,`#6aaee8`,`#dcefff`],[`Lilac`,`#9b8cf0`,`#ebe6ff`],[`Plum`,`#e58bd6`,`#fbe2f6`]];function UA(e,t){if(t===e.character)return e;let n=BA[e.character].identitySlots,r=BA[t].identitySlots,i=Object.fromEntries(r.flatMap((t,r)=>{let i=n[r];return Object.hasOwn(e.appearance,i)?[[t,e.appearance[i]]]:[]}));return{...e,character:t,appearance:i,expression:`normal`}}function WA(e,[,t,n]){let r=BA[e.character].identitySlots;return{...e,appearance:{...e.appearance,...Object.fromEntries(r.map((e,r)=>[e,r===0?t:n]))}}}function GA(e,t){let n=0;for(let e of t)n+=e.codePointAt(0)??0;return WA(e,HA[n%HA.length]??HA[0])}function KA({value:e,disabled:t=!1,onChange:n}){let r=BA[e.character].identitySlots,i=HA.find(([,t,n])=>r.every((r,i)=>e.appearance[r]===(i===0?t:n)))?.[0]??``;return(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(un,{legend:`Avatar`,icon:(0,X.jsx)(xn,{name:`agent`}),layout:`columns`,disabled:t,children:(0,X.jsx)(uk,{"aria-label":`Character`,className:`caps-field-icon-choices`,disabled:t,orientation:`horizontal`,value:e.character,onValueChange:t=>{n(UA(e,Bt.shape.character.parse(t)))},children:Mt.map(t=>(0,X.jsx)(pk,{value:t,label:VA[t],caption:VA[t],art:`color`,icon:(0,X.jsx)(gn,{avatar:UA(e,t),name:VA[t],size:32})},t))})}),(0,X.jsx)(un,{legend:`Colour`,icon:(0,X.jsx)(xn,{name:`prints`}),layout:`columns`,disabled:t,children:(0,X.jsx)(uk,{"aria-label":`Colour`,className:`caps-field-icon-choices`,disabled:t,orientation:`horizontal`,value:i,onValueChange:t=>{let r=HA.find(([e])=>e===t);r&&n(WA(e,r))},children:HA.map(([e,t])=>(0,X.jsx)(mk,{value:e,label:e,color:t},e))})})]})}var qA=Ja.check(q(1,{message:`Give your Agent a name.`}),U(256,{message:`Use at most 256 characters.`})),JA=xa(qA),YA=e=>e===`new`||e===`none`?e:e.computerId,XA=e=>e===`new`||e===`none`?e:{computerId:e},ZA=e=>e?.[0]?.computerId??`none`;function QA(e,t){let n=Object.fromEntries(e.map(e=>[e.computerId,e.name]));n.new=`New Computer`,n.none=`No Computer`;let r={label:`Computer`,kind:`select`,icon:(0,X.jsx)(xn,{name:`computer`}),options:n};return I.check(L(e=>Object.hasOwn(n,e)||`Choose a Computer.`)).annotate(Jk(t===null?r:{...r,help:t}))}var $A=no({family:`grove-agent-create-request`,version:1,kinds:{request:{prefix:`request`}}});function ej({create:e,computers:t,computersUnavailable:n,inputRef:r,error:i,addCredit:a,onCancel:o}){let s=(0,J.useRef)(null),[l,u]=(0,J.useState)(()=>{let e=$A.request.generate();return GA(En(e),e)}),d=(0,J.useMemo)(()=>F({name:qA.annotate(Jk({label:`Name`,icon:(0,X.jsx)(xn,{name:`write`}),render:e=>(0,X.jsx)(He,{ref:r,id:e.id,name:e.name,"aria-label":`New Agent name`,"aria-required":`true`,"aria-describedby":e[`aria-describedby`],"aria-invalid":e[`aria-invalid`],placeholder:`Name your Agent`,maxLength:256,disabled:e.disabled,value:e.value,onBlur:e.onBlur,onChange:t=>{e.onChange(t.currentTarget.value)}})})),computer:QA(t??[],n)}),[r,t,n]),f=t!==null,[p,m]=(0,J.useState)(!1),h={name:``,computer:ZA(t)},g=SA({schema:d,defaultValues:h,onSubmit:async({name:t,computer:n})=>{let r=f?XA(n):void 0,i=s.current;if(i?.name!==t||(i.computer===void 0?void 0:YA(i.computer))!==(r===void 0?void 0:YA(r))||i.avatar!==l){let e={name:t,requestId:$A.request.generate(),avatar:l};i=r===void 0?e:{...e,computer:r}}return s.current=i,await e(i)?(s.current=null,{kind:`saved`,values:h}):{kind:`refused`}}}),{submitting:_,canSubmit:v,dirty:y}=CA(g);return(0,X.jsxs)(EA,{model:g,layout:`columns`,"aria-label":`Create Agent`,footer:(0,X.jsxs)(jt,{divider:!1,error:a===null?i:null,children:[(0,X.jsx)(c,{type:`button`,variant:`ghost`,"aria-expanded":p,onClick:()=>{m(e=>!e)},children:p?`Fewer options`:`More options`}),(0,X.jsx)(c,{type:`button`,variant:`ghost`,disabled:_,onClick:o,children:`Cancel`}),(0,X.jsx)(c,{type:`submit`,className:`shrink-0 disabled:-outline-offset-1`,variant:`primary`,loading:_,disabled:_||!v||!y,children:`Create Agent`})]}),onSubmitCapture:e=>{Jr(JA(g.form.state.values.name))&&e.currentTarget.querySelector(`input[name="name"]`)?.focus()},onChange:()=>{let e=g.form.state.values;(e.name.trim()!==s.current?.name||f&&s.current.computer!==void 0&&e.computer!==YA(s.current.computer))&&(s.current=null)},children:[a===null?null:(0,X.jsx)(tj,{openBilling:a}),(0,X.jsx)(Uk,{model:g,names:f&&p?[`name`,`computer`]:[`name`]}),p?(0,X.jsx)(KA,{value:l,disabled:_,onChange:e=>{u(e),s.current=null}}):null]})}function tj({openBilling:e}){let t=as({mutationFn:e});return(0,X.jsx)(ct,{variant:`inline`,need:`Add credit to create your Agent`,cause:t.isError?`Billing could not open. Try again.`:`This Team needs credit to run Agents and Computers.`,fix:{label:t.isError?`Retry Billing`:`Add credit`,onSelect:()=>{t.mutate()},pending:t.isPending},waitingFor:`Billing`})}function nj({open:e,pending:t,error:n,addCredit:r,computers:i,create:a,onClose:o,returnFocus:s}){let c=(0,J.useRef)(null);return(0,X.jsx)(ke,{open:e,onOpenChange:e=>{!e&&!t&&o()},children:(0,X.jsxs)(P,{className:`flex flex-col gap-lg`,initialFocus:c,finalFocus:s,keepMounted:!1,children:[(0,X.jsxs)(u,{children:[(0,X.jsx)(Ye,{children:`New Agent`}),(0,X.jsx)(Re,{children:`Agents chat, write and work with you.`})]}),i.status===`loading`?(0,X.jsx)(`p`,{role:`status`,children:`Loading your Computers…`}):(0,X.jsx)(ej,{create:a,computers:i.status===`offered`?i.computers:i.status===`unavailable`?[]:null,computersUnavailable:i.status===`unavailable`?i.message:null,inputRef:c,error:n,addCredit:r,onCancel:o})]})})}function rj({open:e,agents:t,defaultAgentId:n,start:r,pending:i,onClose:a,onNewAgent:o,returnFocus:s}){let l=SA({schema:(0,J.useMemo)(()=>F({agentId:I.check(L(e=>t.some(t=>t.agentId===e)||`Choose an Agent.`)).annotate(Jk({label:`Agent`,kind:`select`,options:Object.fromEntries(t.map(e=>[e.agentId,PE(e)]))}))}),[t]),defaultValues:{agentId:n??``},onSubmit:async({agentId:e})=>{let t=await r(e);if(t)return{kind:`refused`,error:t}}}),{submitting:d,canSubmit:f}=CA(l);return(0,X.jsx)(ke,{open:e,onOpenChange:e=>{!e&&!i&&!l.form.state.isSubmitting&&a()},children:(0,X.jsxs)(P,{className:`flex flex-col gap-lg`,keepMounted:!1,finalFocus:s,children:[(0,X.jsxs)(u,{children:[(0,X.jsx)(Ye,{children:`New conversation`}),(0,X.jsx)(Re,{children:`Choose who to talk with.`})]}),t.length===0?(0,X.jsxs)(`div`,{className:`grid gap-sm`,children:[(0,X.jsx)(`p`,{children:`No Agent has conversation access yet.`}),o?(0,X.jsx)(c,{onClick:o,children:`New Agent`}):null,(0,X.jsx)(c,{variant:`ghost`,onClick:a,children:`Cancel`})]}):(0,X.jsx)(EA,{model:l,"aria-label":`New conversation`,footer:(0,X.jsxs)(jt,{divider:!1,error:l.error,children:[(0,X.jsx)(c,{type:`button`,variant:`ghost`,disabled:d||i,onClick:a,children:`Cancel`}),(0,X.jsx)(c,{type:`submit`,loading:d||i,disabled:!f||d||i,children:`Start`})]})})]})})}var ij=J.useLayoutEffect;function aj(e,t,n){J.useEffect(()=>{if(!e.current||n||typeof IntersectionObserver!=`function`)return()=>t();let r=new IntersectionObserver(e=>{t(e.pop())},{rootMargin:`100px`});return r.observe(e.current),()=>{r.disconnect(),t()}},[t,n,e])}function oj(e){let t=J.useRef(null);return J.useImperativeHandle(e,()=>t.current,[]),t}function sj(e){return e[e.length-1]}function cj(e){return typeof e==`function`}function lj(e,t){return cj(e)?e(t):e}var uj=Object.prototype.hasOwnProperty,dj=Object.prototype.propertyIsEnumerable;function fj(e){for(let t in e)if(uj.call(e,t))return!0;return!1}var pj=()=>Object.create(null),mj=(e,t)=>hj(e,t,pj);function hj(e,t,n=()=>({}),r=0){if(e===t)return e;if(r>500)return t;let i=t,a=yj(e)&&yj(i);if(!a&&!(_j(e)&&_j(i)))return i;let o=a?e:gj(e);if(!o)return i;let s=a?i:gj(i);if(!s)return i;let c=o.length,l=s.length,u=a?Array(l):n(),d=0;for(let t=0;t<l;t++){let o=a?t:s[t],l=e[o],f=i[o];if(l===f){u[o]=l,(a?t<c:uj.call(e,o))&&d++;continue}if(l===null||f===null||typeof l!=`object`||typeof f!=`object`){u[o]=f;continue}let p=hj(l,f,n,r+1);u[o]=p,p===l&&d++}return c===l&&d===c?e:u}function gj(e){let t=Object.keys(e);if(t.length!==Object.getOwnPropertyNames(e).length)return!1;let n=Object.getOwnPropertySymbols(e);if(n.length===0)return t;for(let r of n){if(!dj.call(e,r))return!1;t.push(r)}return t}function _j(e){if(!vj(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!vj(n)||!n.hasOwnProperty(`isPrototypeOf`))}function vj(e){return Object.prototype.toString.call(e)===`[object Object]`}function yj(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function bj(e,t,n){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0,i=e.length;r<i;r++)if(!bj(e[r],t[r],n))return!1;return!0}if(_j(e)&&_j(t)){let r=n?.ignoreUndefined??!0;if(n?.partial){for(let i in t)if((!r||t[i]!==void 0)&&!bj(e[i],t[i],n))return!1;return!0}let i=0;if(!r)i=Object.keys(e).length;else for(let t in e)e[t]!==void 0&&i++;let a=0;for(let o in t)if((!r||t[o]!==void 0)&&(a++,a>i||!bj(e[o],t[o],n)))return!1;return i===a}return!1}var xj=/[\x00-\x1f\x7f"<>`{}]/g;function Sj(e){return e.replace(xj,e=>`%`+e.charCodeAt(0).toString(16).toUpperCase().padStart(2,`0`))}function Cj(e){let t;try{t=decodeURI(e)}catch{t=e.replaceAll(/%[0-9A-F]{2}/gi,e=>{try{return decodeURI(e)}catch{return e}})}return Sj(t)}var wj=[`http:`,`https:`,`mailto:`,`tel:`];function Tj(e,t){if(!e)return!1;try{let n=new URL(e);return!t.has(n.protocol)}catch{return!1}}function Ej(e){if(!e||!/[%\\\x00-\x1f\x7f]/.test(e)&&!e.startsWith(`//`))return{path:e,handledProtocolRelativeURL:!1};let t=/%25|%5C/gi,n=0,r=``,i;for(;(i=t.exec(e))!==null;)r+=Cj(e.slice(n,i.index))+i[0],n=t.lastIndex;r+=Cj(n?e.slice(n):e);let a=!1;return r.startsWith(`//`)&&(a=!0,r=`/`+r.replace(/^\/+/,``)),{path:r,handledProtocolRelativeURL:a}}function Dj(e){return/\s|[^\u0000-\u007F]/.test(e)?e.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):e}function Oj(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function kj(){throw Error(`Invariant failed`)}function Aj(e){let t=new Map,n,r,i=e=>{e.next&&(e.prev?(e.prev.next=e.next,e.next.prev=e.prev,e.next=void 0,r&&(r.next=e,e.prev=r)):(e.next.prev=void 0,n=e.next,e.next=void 0,r&&(e.prev=r,r.next=e)),r=e)};return{get(e){let n=t.get(e);if(n)return i(n),n.value},set(a,o){if(t.size>=e&&n){let e=n;t.delete(e.key),e.next&&(n=e.next,e.next.prev=void 0),e===r&&(r=void 0)}let s=t.get(a);if(s)s.value=o,i(s);else{let e={key:a,value:o,prev:r};r&&(r.next=e),r=e,n||=e,t.set(a,e)}},clear(){t.clear(),n=void 0,r=void 0}}}var jj=4,Mj=5;function Nj(e){let t=e.indexOf(`{`);if(t===-1)return null;let n=e.indexOf(`}`,t);return n===-1||t+1>=e.length?null:[t,n]}function Pj(e,t,n=new Uint16Array(6)){let r=e.indexOf(`/`,t),i=r===-1?e.length:r,a=e.substring(t,i);if(!a||!a.includes(`$`))return n[0]=0,n[1]=t,n[2]=t,n[3]=i,n[4]=i,n[5]=i,n;if(a===`$`){let r=e.length;return n[0]=2,n[1]=t,n[2]=t,n[3]=r,n[4]=r,n[5]=r,n}if(a.charCodeAt(0)===36)return n[0]=1,n[1]=t,n[2]=t+1,n[3]=i,n[4]=i,n[5]=i,n;let o=Nj(a);if(o){let[r,s]=o,c=a.charCodeAt(r+1);if(c===45){if(r+2<a.length&&a.charCodeAt(r+2)===36){let e=r+3,a=s;if(e<a)return n[0]=3,n[1]=t+r,n[2]=t+e,n[3]=t+a,n[4]=t+s+1,n[5]=i,n}}else if(c===36){let a=r+1,o=r+2;return o===s?(n[0]=2,n[1]=t+r,n[2]=t+a,n[3]=t+o,n[4]=t+s+1,n[5]=e.length,n):(n[0]=1,n[1]=t+r,n[2]=t+o,n[3]=t+s,n[4]=t+s+1,n[5]=i,n)}}return n[0]=0,n[1]=t,n[2]=t,n[3]=i,n[4]=i,n[5]=i,n}function Fj(e,t,n,r,i,a,o,s){s?.(n);let c=r;{let r=n.fullPath??n.from,s=n.options,l=r.length,u=s?.caseSensitive??e,d=s?.params?.parse??s?.parseParams;for(;c<l;){let e=Pj(r,c,t),n,s=c,l=e[5];c=l+1,a++;let f=e[0];switch(f){case 0:{let t=r.substring(e[2],e[3]),o=t,s;u?s=i.static??=new Map:(o=t.toLowerCase(),s=i.staticInsensitive??=new Map);let c=s.get(o);if(c)n=c;else{let e=Lj(r);e.parent=i,e.depth=a,n=e,s.set(o,e)}break}case 1:case 3:case 2:{let t=r.substring(s,e[1]),c=r.substring(e[4],l),p=u&&!!(t||c),m=t?p?t:t.toLowerCase():void 0,h=c?p?c:c.toLowerCase():void 0,g=f===1?i.dynamic:f===3?i.optional:i.wildcard,_=f!==2&&!d&&g?.find(e=>!e.parse&&e.caseSensitive===p&&e.prefix===m&&e.suffix===h);if(_)n=_;else{let e=Rj(f,r,p,m,h);n=e,e.parent=i,e.depth=a;let t;t=f===1?i.dynamic??=[]:f===3?i.optional??=[]:i.wildcard??=[],t.push(e),t.length===2&&o?.push(t)}break}}i=n}if(d&&n.children&&!n.isRoot&&n.id&&n.id.charCodeAt(n.id.lastIndexOf(`/`)+1)===95){let e=Lj(r);e.kind=Mj,e.parent=i,a++,e.depth=a,i.pathless??=[],i.pathless.push(e),i=e}let f=(n.path||!n.children)&&!n.isRoot;if(f&&r.endsWith(`/`)){let e=Lj(r);e.kind=jj,e.parent=i,a++,e.depth=a,i.index=e,i=e}i.parse=d??null,i.priority=s?.params?.priority??0,f&&!i.route&&(i.route=n,i.fullPath=r)}if(n.children)for(let r of n.children)Fj(e,t,r,c,i,a,o,s)}function Ij(e,t){if(e.parse&&!t.parse)return-1;if(!e.parse&&t.parse)return 1;if(e.parse&&t.parse&&(e.priority||t.priority))return t.priority-e.priority;if(e.prefix&&t.prefix&&e.prefix!==t.prefix){if(e.prefix.startsWith(t.prefix))return-1;if(t.prefix.startsWith(e.prefix))return 1}if(e.suffix&&t.suffix&&e.suffix!==t.suffix){if(e.suffix.endsWith(t.suffix))return-1;if(t.suffix.endsWith(e.suffix))return 1}return e.prefix&&!t.prefix?-1:!e.prefix&&t.prefix?1:e.suffix&&!t.suffix?-1:!e.suffix&&t.suffix?1:e.caseSensitive&&!t.caseSensitive?-1:!e.caseSensitive&&t.caseSensitive?1:0}function Lj(e){return{kind:0,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:e,parent:null,parse:null,priority:0}}function Rj(e,t,n,r,i){return{kind:e,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:t,parent:null,parse:null,priority:0,caseSensitive:n,prefix:r,suffix:i}}function zj(e,t){let n=Lj(`/`),r=new Uint16Array(6),i=[];for(let t of e)Fj(!1,r,t,1,n,0,i);for(let e of i)e.sort(Ij);t.masksTree=n,t.flatCache=Aj(1e3)}function Bj(e,t){e||=`/`;let n=t.flatCache.get(e);if(n)return n;let r=Gj(e,t.masksTree);return t.flatCache.set(e,r),r}function Vj(e,t,n,r,i){e||=`/`,r||=`/`;let a=t?`case\0${e}`:e,o=i.singleCache.get(a);return o||(o=Lj(`/`),Fj(t,new Uint16Array(6),{from:e},1,o,0),i.singleCache.set(a,o)),Gj(r,o,n)}function Hj(e,t,n=!1){let r=n?e:`nofuzz\0${e}`,i=t.matchCache.get(r);if(i!==void 0)return i;e||=`/`;let a;try{a=Gj(e,t.segmentTree,n)}catch(e){if(e instanceof URIError)a=null;else throw e}return a&&(a.branch=qj(a.route)),t.matchCache.set(r,a),a}function Uj(e){return e===`/`?e:e.replace(/\/{1,}$/,``)}function Wj(e,t=!1,n){let r=Lj(e.fullPath),i=new Uint16Array(6),a=[],o={},s={},c=0;Fj(t,i,e,1,r,0,a,e=>{if(n?.(e,c),e.id in o&&kj(),o[e.id]=e,c!==0&&e.path){let t=Uj(e.fullPath);(!s[t]||e.fullPath.endsWith(`/`))&&(s[t]=e)}c++});for(let e of a)e.sort(Ij);return{processedTree:{segmentTree:r,singleCache:Aj(1e3),matchCache:Aj(1e3),flatCache:null,masksTree:null},routesById:o,routesByPath:s}}function Gj(e,t,n=!1){let r=e.split(`/`),i=Yj(e,r,t,n);if(!i)return null;let[a]=Kj(e,r,i);return{route:i.node.route,rawParams:a}}function Kj(e,t,n){let r=Jj(n.node),i=null,a=Object.create(null),o=n.extract?.part??0,s=n.extract?.node??0,c=n.extract?.path??0,l=n.extract?.segment??0;for(;s<r.length;o++,s++,c++,l++){let u=r[s];if(u.kind===jj)break;if(u.kind===Mj){l--,o--,c--;continue}let d=t[o],f=c;if(d&&(c+=d.length),u.kind===1){i??=n.node.fullPath.split(`/`);let e=i[l],t=u.prefix?.length??0;if(e.charCodeAt(t)===123){let n=u.suffix?.length??0,r=e.substring(t+2,e.length-n-1),i=d.substring(t,d.length-n);a[r]=decodeURIComponent(i)}else{let t=e.substring(1);a[t]=decodeURIComponent(d)}}else if(u.kind===3){if(n.skipped&1<<s){o--,c=f-1;continue}i??=n.node.fullPath.split(`/`);let e=i[l],t=u.prefix?.length??0,r=u.suffix?.length??0,p=e.substring(t+3,e.length-r-1),m=u.suffix||u.prefix?d.substring(t,d.length-r):d;m&&(a[p]=decodeURIComponent(m))}else if(u.kind===2){let t=u,n=e.substring(f+(t.prefix?.length??0),e.length-(t.suffix?.length??0)),r=decodeURIComponent(n);a[`*`]=r,a._splat=r;break}}return n.rawParams&&Object.assign(a,n.rawParams),[a,{part:o,node:s,path:c,segment:l}]}function qj(e){let t=[e];for(;e.parentRoute;)e=e.parentRoute,t.push(e);return t.reverse(),t}function Jj(e){let t=Array(e.depth+1);do t[e.depth]=e,e=e.parent;while(e);return t}function Yj(e,t,n,r){if(e===`/`&&n.index)return{node:n.index,skipped:0};let i=!sj(t),a=i&&e!==`/`,o=t.length-+!!i,s=[{node:n,index:1,skipped:0,statics:0,dynamics:0,optionals:0}],c=null,l=null;for(;s.length;){let n=s.pop(),{node:i,index:u,skipped:d,statics:f,dynamics:p,optionals:m}=n,{extract:h,rawParams:g}=n;if(i.kind===2&&i.route&&!$j(l,n))continue;if(i.parse){if(!Qj(e,t,n))continue;g=n.rawParams,h=n.extract}r&&i.route&&i.kind!==jj&&$j(c,n)&&(c=n);let _=u===o;if(_&&(i.route&&(!a||i.kind===jj||i.kind===2)&&$j(l,n)&&(l=n),!i.optional&&!i.wildcard&&!i.index&&!i.pathless))continue;let v=_?void 0:t[u],y;if(_&&i.index){let n={node:i.index,index:u,skipped:d,statics:f,dynamics:p,optionals:m,extract:h,rawParams:g},r=!0;if(i.index.parse&&(Qj(e,t,n)||(r=!1)),r){if(!p&&!m&&!d&&Zj(f,o))return n;$j(l,n)&&(l=n)}}if(i.wildcard)for(let e=i.wildcard.length-1;e>=0;e--){let n=i.wildcard[e],{prefix:r,suffix:a}=n;if(!(r&&(_||!(n.caseSensitive?v:y??=v.toLowerCase()).startsWith(r)))){if(a){if(_)continue;let e=t.slice(u).join(`/`).slice(-a.length);if((n.caseSensitive?e:e.toLowerCase())!==a)continue}s.push({node:n,index:o,skipped:d,statics:f,dynamics:p,optionals:m,extract:h,rawParams:g})}}if(i.optional){let e=d|1<<i.depth+1;for(let t=i.optional.length-1;t>=0;t--){let n=i.optional[t];s.push({node:n,index:u,skipped:e,statics:f,dynamics:p,optionals:m,extract:h,rawParams:g})}if(!_)for(let e=i.optional.length-1;e>=0;e--){let t=i.optional[e],{prefix:n,suffix:r}=t;if(n||r){let e=t.caseSensitive?v:y??=v.toLowerCase();if(n&&!e.startsWith(n)||r&&!e.endsWith(r))continue}s.push({node:t,index:u+1,skipped:d,statics:f,dynamics:p,optionals:m+Xj(o,u),extract:h,rawParams:g})}}if(!_&&i.dynamic&&v)for(let e=i.dynamic.length-1;e>=0;e--){let t=i.dynamic[e],{prefix:n,suffix:r}=t;if(n||r){let e=t.caseSensitive?v:y??=v.toLowerCase();if(n&&!e.startsWith(n)||r&&!e.endsWith(r))continue}s.push({node:t,index:u+1,skipped:d,statics:f,dynamics:p+Xj(o,u),optionals:m,extract:h,rawParams:g})}if(!_&&i.staticInsensitive){let e=i.staticInsensitive.get(y??=v.toLowerCase());e&&s.push({node:e,index:u+1,skipped:d,statics:f+Xj(o,u),dynamics:p,optionals:m,extract:h,rawParams:g})}if(!_&&i.static){let e=i.static.get(v);e&&s.push({node:e,index:u+1,skipped:d,statics:f+Xj(o,u),dynamics:p,optionals:m,extract:h,rawParams:g})}if(i.pathless)for(let e=i.pathless.length-1;e>=0;e--){let t=i.pathless[e];s.push({node:t,index:u,skipped:d,statics:f,dynamics:p,optionals:m,extract:h,rawParams:g})}}if(l)return l;if(r&&c){let n=c.index;for(let e=0;e<c.index;e++)n+=t[e].length;let r=n===e.length?`/`:e.slice(n);return c.rawParams??=Object.create(null),c.rawParams[`**`]=decodeURIComponent(r),c}return null}function Xj(e,t){return 2**(e-t-1)}function Zj(e,t){return e===2**(t-1)-1}function Qj(e,t,n){let r,i;try{[r,i]=Kj(e,t,n)}catch{return null}if(n.rawParams=r,n.extract=i,!n.node.parse)return!0;try{if(n.node.parse(r)===!1)return null}catch{}return!0}function $j(e,t){return!e||t.statics>e.statics||t.statics===e.statics&&(t.dynamics>e.dynamics||t.dynamics===e.dynamics&&(t.optionals>e.optionals||t.optionals===e.optionals&&((t.node.kind===jj)>(e.node.kind===jj)||t.node.kind===jj==(e.node.kind===jj)&&t.node.depth>e.node.depth)))}function eM(e){return tM(e.filter(e=>e!==void 0).join(`/`))}function tM(e){return e.replace(/\/{2,}/g,`/`)}function nM(e){return e===`/`?e:e.replace(/^\/{1,}/,``)}function rM(e){let t=e.length;return t>1&&e[t-1]===`/`?e.replace(/\/{1,}$/,``):e}function iM(e){return rM(nM(e))}function aM(e,t){return e?.endsWith(`/`)&&e!==`/`&&e!==`${t}/`?e.slice(0,-1):e}function oM(e,t,n){return aM(e,n)===aM(t,n)}function sM({base:e,to:t,trailingSlash:n=`never`,cache:r}){let i=t===`.`,a=t.startsWith(`/`),o;if(r){o=a?t:i?e:e+`\0`+t;let n=r.get(o);if(n)return n}let s;if(i)s=e.split(`/`);else if(a)s=t.split(`/`);else{for(s=e.split(`/`);s.length>1&&sj(s)===``;)s.pop();let n=t.split(`/`);for(let e=0,t=n.length;e<t;e++){let r=n[e];r===``?e?e===t-1&&s.push(r):s=[r]:r===`..`?s.length>1?s.pop():s=[``]:r===`.`||s.push(r)}}s.length>1&&(sj(s)===``?n===`never`&&s.pop():n===`always`&&s.push(``));let c=tM(s.join(`/`))||`/`;return o&&r&&r.set(o,c),c}function cM(e){let t=new Map(e.map(e=>[encodeURIComponent(e),e])),n=Array.from(t.keys()).map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)).join(`|`),r=new RegExp(n,`g`);return e=>e.replace(r,e=>t.get(e)??e)}function lM(e,t,n){let r=t[e];return typeof r==`string`?e===`_splat`?/^[a-zA-Z0-9\-._~!/]*$/.test(r)?r:r.split(`/`).map(e=>dM(e,n)).join(`/`):dM(r,n):r}function uM({path:e,params:t,decoder:n,...r}){let i=!1,a=Object.create(null);if(!e||e===`/`)return{interpolatedPath:`/`,usedParams:a,isMissingParams:i};if(!e.includes(`$`))return{interpolatedPath:e,usedParams:a,isMissingParams:i};let o=e.length,s=0,c,l=``;for(;s<o;){let r=s;c=Pj(e,r,c);let o=c[5];if(s=o+1,r===o)continue;let u=c[0];if(u===0){l+=`/`+e.substring(r,o);continue}if(u===2){let s=t._splat;a._splat=s,a[`*`]=s;let u=e.substring(r,c[1]),d=e.substring(c[4],o);if(!s){i=!0,(u||d)&&(l+=`/`+u+d);continue}let f=lM(`_splat`,t,n);l+=`/`+u+f+d;continue}if(u===1){let s=e.substring(c[2],c[3]);!i&&!(s in t)&&(i=!0),a[s]=t[s];let u=e.substring(r,c[1]),d=e.substring(c[4],o),f=lM(s,t,n)??`undefined`;l+=`/`+u+f+d;continue}if(u===3){let i=e.substring(c[2],c[3]),s=t[i];if(s==null)continue;a[i]=s;let u=e.substring(r,c[1]),d=e.substring(c[4],o),f=lM(i,t,n)??``;l+=`/`+u+f+d;continue}}return e.endsWith(`/`)&&(l+=`/`),{usedParams:a,interpolatedPath:l||`/`,isMissingParams:i}}function dM(e,t){let n=encodeURIComponent(e);return t?.(n)??n}function fM(e){return e?.isNotFound===!0}function pM(){try{return sessionStorage}catch{return}}var mM=`tsr-scroll-restoration-v1_3`,hM=pM();function gM(){try{return JSON.parse(hM?.getItem(`tsr-scroll-restoration-v1_3`)||`{}`)}catch{return{}}}function _M(){try{hM?.setItem(mM,JSON.stringify(vM))}catch{}}var vM=gM(),yM=`data-scroll-restoration-id`,bM=e=>e.state.__TSR_key||e.href;function xM(e){let t=e.getAttribute(yM);if(t)return`[${yM}="${t}"]`;let n=``,r=e,i;for(;i=r.parentNode;){let e=1,t=r;for(;t=t.previousElementSibling;)e++;let a=`${r.localName}:nth-child(${e})`;n=n?`${a} > ${n}`:a,r=i}return n}var SM=!1,CM=`window`;function wM(e){try{return typeof e==`function`?e():document.querySelector(e)}catch{}}function TM(e){let t=new Set;for(let n of e){if(n===CM)continue;let e=wM(n);e&&t.add(e)}return t}function EM(e,t){let n=t??e.options.scrollRestoration,r=e._scroll;n&&(r.restoring=!0);let i=e.options.getScrollRestorationKey||bM,a=new Set,o=e=>{let t=vM[e]||={};for(let e of a)e===document?t[CM]={scrollX,scrollY}:e.isConnected&&(t[xM(e)]={scrollX:e.scrollLeft,scrollY:e.scrollTop})};n&&!r.restoration&&(r.restoration=!0,SM=!1,history.scrollRestoration=`manual`,document.addEventListener(`scroll`,e=>{SM||a.add(e.target)},!0),e.subscribe(`onBeforeLoad`,e=>{e.fromLocation&&o(i(e.fromLocation)),a.clear()}),addEventListener(`pagehide`,()=>{o(i(e.stores.resolvedLocation.get()??e.stores.location.get())),_M()})),!r.reset&&(r.reset=!0,e.subscribe(`onRendered`,t=>{let n=e.options.scrollRestorationBehavior,o=e.options.scrollToTopSelectors,s=r.next,c=r.hash,l;if(a.clear(),r.next=!0,r.hash=!1,typeof e.options.scrollRestoration==`function`&&!e.options.scrollRestoration({location:e.latestLocation}))return;let u=i(t.toLocation),d=t.fromLocation&&i(t.fromLocation);if(r.restoring&&d&&d!==u){let e=vM[d];if(e){let t=vM[u];for(let n in e){if(n===CM){if(s)continue}else{let e=wM(n);if(!e||s&&o&&(l??=TM(o),l.has(e)))continue}t||=vM[u]={},t[n]??=e[n]}}}SM=!0;try{let e=t.toLocation.hash,i=t.toLocation.state.__hashScrollIntoViewOptions??!0,a=!1;if(s){!e&&o&&(l??=TM(o));let t=e&&i&&c,s=r.restoring?vM[u]:void 0;if(s)for(let e in s){let{scrollX:r,scrollY:i}=s[e];if(e===CM){if(t)continue;scrollTo({top:i,left:r,behavior:n}),a=!0}else{let t=wM(e);t&&(t.scrollLeft=r,t.scrollTop=i,l?.delete(t))}}if(!e){let e={top:0,left:0,behavior:n};if(a||scrollTo(e),l)for(let t of l)t.scrollTo(e)}}!a&&e&&i&&document.getElementById(e)?.scrollIntoView(i)}finally{SM=!1}}))}function DM(e,t=String){let n=new URLSearchParams;for(let r in e){let i=e[r];i!==void 0&&n.set(r,t(i))}return n.toString()}function OM(e){return e?e===`false`?!1:e===`true`?!0:e*0==0&&+e+``===e?+e:e:``}function kM(e){let t=new URLSearchParams(e),n=Object.create(null);for(let[e,r]of t.entries()){let t=n[e];t==null?n[e]=OM(r):Array.isArray(t)?t.push(OM(r)):n[e]=[t,OM(r)]}return n}var AM=/^(?:\s|["[{\d-]|fa|nu|tr)/,jM=NM(JSON.parse),MM=PM(JSON.stringify,JSON.parse);function NM(e){return t=>{t[0]===`?`&&(t=t.substring(1));let n=kM(t);for(let t in n){let r=n[t];if(typeof r==`string`)try{n[t]=e(r)}catch{}}return n}}function PM(e,t){let n=t===JSON.parse;function r(r){if(r&&typeof r==`object`)try{return e(r)}catch{}else if(t&&typeof r==`string`){if(n&&!AM.test(r))return r;try{return t(r),e(r)}catch{}}return r}return e=>{let t=DM(e,r);return t?`?${t}`:``}}var FM=`__root__`;function IM(e){if(e.statusCode=e.statusCode||e.code||307,!e._builtLocation&&!e.reloadDocument&&typeof e.href==`string`)try{new URL(e.href),e.reloadDocument=!0}catch{}let t=new Headers(e.headers);e.href&&t.get(`Location`)===null&&t.set(`Location`,e.href);let n=new Response(null,{status:e.statusCode,headers:t});if(n.options=e,e.throw)throw n;return n}function LM(e){return e instanceof Response&&!!e.options}function RM(e){return{input:({url:t})=>{for(let n of e)t=BM(n,t);return t},output:({url:t})=>{for(let n=e.length-1;n>=0;n--)t=VM(e[n],t);return t}}}function zM(e){let t=iM(e.basepath),n=`/${t}`,r=e.caseSensitive?n:n.toLowerCase(),i=`${r}/`;return{input:({url:t})=>{let a=e.caseSensitive?t.pathname:t.pathname.toLowerCase();return a===r?t.pathname=`/`:a.startsWith(i)&&(t.pathname=t.pathname.slice(n.length)),t},output:({url:e})=>(e.pathname=eM([`/`,t,e.pathname]),e)}}function BM(e,t){let n=e?.input?.({url:t});if(n){if(typeof n==`string`)return new URL(n);if(n instanceof URL)return n}return t}function VM(e,t){let n=e?.output?.({url:t});if(n){if(typeof n==`string`)return new URL(n);if(n instanceof URL)return n}return t}function HM(e,t){let{createMutableStore:n,createReadonlyStore:r,batch:i}=t,a=new Map,o=n(`idle`),s=n(e),c=n(void 0),l=n([]),u=r(()=>l.get().map(e=>a.get(e).get())),d=r(()=>({status:o.get(),isLoading:o.get()===`pending`,matches:u.get(),location:s.get(),resolvedLocation:c.get()}));function f(e){let t=a.get(e);return t||(t=n(void 0),a.set(e,t)),t}let p={status:o,location:s,resolvedLocation:c,ids:l,matches:u,byRoute:a,__store:d,getMatchStore:f,setMatches:m};function m(e){let t=l.get(),n=e.map(e=>e.routeId);i(()=>{Oj(t,n)||l.set(n);for(let e of t)n.includes(e)||a.get(e).set(()=>void 0);for(let t of e){let e=f(t.routeId);e.get()!==t&&e.set(t)}})}return p}var UM=`__TSR_index`,WM=`popstate`,GM=`beforeunload`;function KM(e){let t=e.getLocation(),n=new Set,r=r=>{t=e.getLocation(),n.forEach(e=>e({location:t,action:r}))},i=n=>{e.notifyOnIndexChange??!0?r(n):t=e.getLocation()},a=async({task:n,navigateOpts:r,...i})=>{if(r?.ignoreBlocker??!1){n();return}let a=e.getBlockers?.()??[],o=i.type===`PUSH`||i.type===`REPLACE`;if(typeof document<`u`&&a.length&&o)for(let n of a){let r=ZM(i.path,i.state);if(await n.blockerFn({currentLocation:t,nextLocation:r,action:i.type})){e.onBlocked?.();return}}n()};return{get location(){return t},get length(){return e.getLength()},subscribers:n,subscribe:e=>(n.add(e),()=>{n.delete(e)}),push:(n,i,o)=>{let s=t.state[UM];i=qM(s+1,i),a({task:()=>{e.pushState(n,i),r({type:`PUSH`})},navigateOpts:o,type:`PUSH`,path:n,state:i})},replace:(n,i,o)=>{let s=t.state[UM];i=qM(s,i),a({task:()=>{e.replaceState(n,i),r({type:`REPLACE`})},navigateOpts:o,type:`REPLACE`,path:n,state:i})},go:(t,n)=>{a({task:()=>{e.go(t),i({type:`GO`,index:t})},navigateOpts:n,type:`GO`})},back:t=>{a({task:()=>{e.back(t?.ignoreBlocker??!1),i({type:`BACK`})},navigateOpts:t,type:`BACK`})},forward:t=>{a({task:()=>{e.forward(t?.ignoreBlocker??!1),i({type:`FORWARD`})},navigateOpts:t,type:`FORWARD`})},canGoBack:()=>t.state[UM]!==0,createHref:t=>e.createHref(t),block:t=>{if(!e.setBlockers)return()=>{};let n=e.getBlockers?.()??[];return e.setBlockers([...n,t]),()=>{let n=e.getBlockers?.()??[];e.setBlockers?.(n.filter(e=>e!==t))}},flush:()=>e.flush?.(),destroy:()=>e.destroy?.(),notify:r}}function qM(e,t){t||={};let n=QM();return{...t,key:n,__TSR_key:n,[UM]:e}}function JM(e){let t=e?.window??(typeof document<`u`?window:void 0),n=t.history.pushState,r=t.history.replaceState,i=[],a=()=>i,o=e=>i=e,s=e?.createHref??(e=>e),c=e?.parseLocation??(()=>ZM(`${t.location.pathname}${t.location.search}${t.location.hash}`,t.history.state));if(!t.history.state?.__TSR_key&&!t.history.state?.key){let e=QM();t.history.replaceState({[UM]:0,key:e,__TSR_key:e},``)}let l=c(),u,d=!1,f=!1,p=!1,m=!1,h=()=>l,g,_=()=>{g&&(S._ignoreSubscribers=!0,(g[2]?t.history.pushState:t.history.replaceState)(g[1],``,g[0]),S._ignoreSubscribers=!1,g=void 0,u=void 0)},v=(e,t,n)=>{let r=s(t),i=!!g;i||(u=l),l=ZM(t,n),g=[r,n,g?.[2]||e],i||queueMicrotask(()=>_())},y=e=>{l=c(),S.notify({type:e})},b=async()=>{if(f){f=!1;return}let e=c(),n=e.state[UM]-l.state[UM],r=n===1,i=n===-1,o=!r&&!i||d;d=!1;let s=o?`GO`:i?`BACK`:`FORWARD`,u=o?{type:`GO`,index:n}:{type:i?`BACK`:`FORWARD`};if(p)p=!1;else{let n=a();if(typeof document<`u`&&n.length){for(let r of n)if(await r.blockerFn({currentLocation:l,nextLocation:e,action:s})){f=!0,t.history.go(1),S.notify(u);return}}}l=c(),S.notify(u)},x=e=>{if(m){m=!1;return}let t=!1,n=a();if(typeof document<`u`&&n.length)for(let e of n){let n=e.enableBeforeUnload??!0;if(n===!0){t=!0;break}if(typeof n==`function`&&n()===!0){t=!0;break}}if(t)return e.preventDefault(),e.returnValue=``},S=KM({getLocation:h,getLength:()=>t.history.length,pushState:(e,t)=>v(!0,e,t),replaceState:(e,t)=>v(!1,e,t),back:e=>(e&&(p=!0),m=!0,t.history.back()),forward:e=>{e&&(p=!0),m=!0,t.history.forward()},go:e=>{d=!0,t.history.go(e)},createHref:e=>s(e),flush:_,destroy:()=>{t.history.pushState=n,t.history.replaceState=r,t.removeEventListener(GM,x,{capture:!0}),t.removeEventListener(WM,b)},onBlocked:()=>{u&&l!==u&&(l=u)},getBlockers:a,setBlockers:o,notifyOnIndexChange:!1});return t.addEventListener(GM,x,{capture:!0}),t.addEventListener(WM,b),t.history.pushState=function(...e){let r=n.apply(t.history,e);return S._ignoreSubscribers||y(`PUSH`),r},t.history.replaceState=function(...e){let n=r.apply(t.history,e);return S._ignoreSubscribers||y(`REPLACE`),n},S}function YM(e={initialEntries:[`/`]}){let t=e.initialEntries,n=e.initialIndex?Math.min(Math.max(e.initialIndex,0),t.length-1):t.length-1,r=t.map((e,t)=>qM(t,void 0)),i=()=>ZM(t[n],r[n]),a=[];return KM({getLocation:i,getLength:()=>t.length,pushState:(e,i)=>{n<t.length-1&&(t.splice(n+1),r.splice(n+1)),r.push(i),t.push(e),n=Math.max(t.length-1,0)},replaceState:(e,i)=>{r[n]=i,t[n]=e},back:()=>{n=Math.max(n-1,0)},forward:()=>{n=Math.min(n+1,t.length-1)},go:e=>{n=Math.min(Math.max(n+e,0),t.length-1)},createHref:e=>e,getBlockers:()=>a,setBlockers:e=>a=e})}function XM(e){let t=e.replace(/[\x00-\x1f\x7f]/g,``);return t.startsWith(`//`)&&(t=`/`+t.replace(/^\/+/,``)),t}function ZM(e,t){let n=XM(e),r=n.indexOf(`#`),i=n.indexOf(`?`),a=QM();return{href:n,pathname:n.substring(0,r>0?i>0?Math.min(r,i):r:i>0?i:n.length),hash:r>-1?n.substring(r):``,search:i>-1?n.slice(i,r===-1?void 0:r):``,state:t||{[UM]:0,key:a,__TSR_key:a}}}function QM(){return(Math.random()+1).toString(36).substring(7)}function $M(e){return e.options.loader||e.options.beforeLoad||e.lazyFn||e.options.component?.preload||e.options.pendingComponent?.preload}function eN(e,t){return{fromLocation:t,toLocation:e,pathChanged:t?.pathname!==e.pathname,hrefChanged:t?.href!==e.href,hashChanged:t?.hash!==e.hash}}function tN({key:e,__TSR_key:t,__TSR_index:n,__hashScrollIntoViewOptions:r,...i}){return i}function nN(e,t,n,r){for(let i of t){if(r?.()===!1)return;n.some(e=>e.routeId===i.routeId)||e.routesById[i.routeId].options.onLeave?.(i)}for(let i of n){if(r?.()===!1)return;e.routesById[i.routeId].options[t.some(e=>e.routeId===i.routeId)?`onStay`:`onEnter`]?.(i)}}var rN=class{constructor(e,t){this.tempLocationKey=`${Math.round(Math.random()*1e7)}`,this._scroll={next:!0},this.subscribers=new Set,this._cache=new Map,this._committed=[],this.routeBranchCache=new WeakMap,this.lightweightCache=new WeakMap,this.startTransition=async e=>(e(),!1),this.update=e=>{let t=this.options,n=this.basepath??t?.basepath??`/`,r=this.basepath===void 0,i=t?.rewrite;if(this.options={...t,...e},this.isServer=this.options.isServer??!1??typeof document>`u`,this.protocolAllowlist=new Set(this.options.protocolAllowlist),this.options.pathParamsAllowedCharacters&&(this.pathParamsDecoder=cM(this.options.pathParamsAllowedCharacters)),(!this.history||this.options.history&&this.options.history!==this.history)&&(this.history=this.options.history?this.options.history:JM()),this.origin=this.options.origin,this.origin||=window?.origin&&window.origin!==`null`?window.origin:`http://localhost`,this.history&&this.updateLatestLocation(),this.options.routeTree!==this.routeTree){this.routeTree=this.options.routeTree;let e;this.resolvePathCache=Aj(1e3),e=this.buildRouteTree(),this.setRoutes(e)}if(!this.stores&&this.latestLocation){let e=this.getStoreConfig(this);this.batch=e.batch,this.stores=HM(this.latestLocation,e),EM(this)}let a=this.options.basepath??`/`,o=this.options.rewrite;if(r||n!==a||i!==o){this.basepath=a;let e=[],t=iM(a);t&&t!==`/`&&e.push(zM({basepath:a})),o&&e.push(o),this.rewrite=e.length===0?void 0:e.length===1?e[0]:RM(e),this.history&&this.updateLatestLocation(),this.stores&&this.stores.location.set(this.latestLocation)}},this.updateLatestLocation=()=>{this.latestLocation=this.parseLocation(this.history.location,this.latestLocation)},this.buildRouteTree=()=>{let e=Wj(this.routeTree,this.options.caseSensitive,(e,t)=>{e.init({originalIndex:t})});return this.options.routeMasks&&zj(this.options.routeMasks,e.processedTree),e},this.subscribe=(e,t)=>{let n={eventType:e,fn:t};return this.subscribers.add(n),()=>{this.subscribers.delete(n)}},this.emit=e=>{for(let t of this.subscribers)if(t.eventType===e.type)try{t.fn(e)}catch(e){console.error(e)}},this.parseLocation=(e,t)=>{let n=({pathname:e,search:n,hash:r,href:i,state:a})=>{if(!this.rewrite&&!/[ \x00-\x1f\x7f\u0080-\uffff]/.test(e)){let i=this.options.parseSearch(n),o=this.options.stringifySearch(i);return{href:e+o+r,publicHref:e+o+r,pathname:Ej(e).path,external:!1,searchStr:o,search:mj(t?.search,i),hash:Ej(r.slice(1)).path,state:hj(t?.state,a)}}let o=new URL(i,this.origin),s=BM(this.rewrite,o),c=this.options.parseSearch(s.search),l=this.options.stringifySearch(c);return s.search=l,{href:s.href.replace(s.origin,``),publicHref:i,pathname:Ej(s.pathname).path,external:!!this.rewrite&&s.origin!==this.origin,searchStr:l,search:mj(t?.search,c),hash:Ej(s.hash.slice(1)).path,state:hj(t?.state,a)}},r=n(e),{__tempLocation:i,__tempKey:a}=r.state;if(i&&(!a||a===this.tempLocationKey)){let e=n(i);return e.state.key=r.state.key,e.state.__TSR_key=r.state.__TSR_key,delete e.state.__tempLocation,{...e,maskedLocation:r}}return r},this.resolvePathWithBase=(e,t)=>sM({base:e,to:t.includes(`//`)?tM(t):t,trailingSlash:this.options.trailingSlash,cache:this.resolvePathCache}),this.matchRoutes=(e,t,n)=>typeof e==`string`?this.matchRoutesInternal({pathname:e,search:t},n):this.matchRoutesInternal(e,t),this.getMatchedRoutes=e=>{let t=Object.create(null),n=Hj(rM(e),this.processedTree,!0);return n&&Object.assign(t,n.rawParams),[n?.branch||[this.routesById.__root__],t,n?.route]},this.buildLocation=e=>{let t=(t={})=>{let n=t._fromLocation||this._pendingLocation||this.latestLocation,r=this.matchRoutesLightweight(n);t.from;let i=t.unsafeRelative===`path`?n.pathname:t.from??r[1],a=t.to?`${t.to}`:void 0,o=r[2],s=Object.assign(Object.create(null),r[3]),c=a?.charCodeAt(0)===47?`/`:this.resolvePathWithBase(i,`.`),l=a?this.resolvePathWithBase(c,a):c,u=lN(t.params,s),d=this.routesByPath[rM(l)],f;if(d)f=this.getRouteBranch(d);else if(l.includes(`$`))f=[];else{let[e,t,n]=this.getMatchedRoutes(l);f=e,this.options.notFoundRoute&&(!n||n.path!==`/`&&t[`**`])&&(f=[...f,this.options.notFoundRoute])}if(f.length&&fj(u))for(let e of f){let t=e.options.params?.stringify??e.options.stringifyParams;if(t)try{Object.assign(u,t(u))}catch{}}let p=e.leaveParams?l:Ej(uM({path:l,params:u,decoder:this.pathParamsDecoder,server:this.isServer}).interpolatedPath).path,m=o;if(e._includeValidateSearch&&this.options.search?.strict){let e={};f.forEach(t=>{if(t.options.validateSearch)try{Object.assign(e,oN(t.options.validateSearch,{...e,...m}))}catch{}}),m=e}m=sN(m,t,f,e._includeValidateSearch),m=mj(o,m);let h=this.options.stringifySearch(m),g=t.hash===!0?n.hash:t.hash?lj(t.hash,n.hash):void 0,_=g?`#${g}`:``,v=t.state===!0?n.state:t.state?lj(t.state,n.state):{};v=hj(n.state,v);let y=`${p}${h}${_}`,b,x,S=!1;if(this.rewrite){let e=new URL(y,this.origin),t=VM(this.rewrite,e);b=e.href.replace(e.origin,``),t.origin===this.origin?x=t.pathname+t.search+t.hash:(x=t.href,S=!0)}else b=Dj(y),x=b;return{publicHref:x,href:b,pathname:p,search:m,searchStr:h,state:v,hash:g??``,external:S,unmaskOnReload:t.unmaskOnReload}},n=(n={},r)=>{let i=t(n),a=r?t(r):void 0;if(!a){let n=Object.create(null);if(this.options.routeMasks){let o=Bj(i.pathname,this.processedTree);if(o){Object.assign(n,o.rawParams);let{from:i,params:s,...c}=o.route,l=lN(s,n);r={from:e.from,...c,params:l},a=t(r)}}}return a&&(i.maskedLocation=a),i};return e.mask?n(e,{from:e.from,...e.mask}):n(e)},this.commitLocation=async({viewTransition:e,ignoreBlocker:t,...n})=>{let r,i=rM(this.latestLocation.href)===rM(n.href)&&bj(tN(n.state),tN(this.latestLocation.state)),a=this._commitPromise,o,s=new Promise(e=>{o=e});if(s.resolve=()=>{o(),a?.resolve()},this._commitPromise=s,i)this.load();else{let{maskedLocation:i,hashScrollIntoView:a,...o}=n;i&&(o={...i,state:{...i.state,__tempKey:void 0,__tempLocation:{...o,search:o.searchStr,state:{...o.state,__tempKey:void 0,__tempLocation:void 0,__TSR_key:void 0,key:void 0}}}},(o.unmaskOnReload??this.options.unmaskOnReload??!1)&&(o.state.__tempKey=this.tempLocationKey)),o.state.__hashScrollIntoViewOptions=a??this.options.defaultHashScrollIntoView??!0,this.shouldViewTransition=e,r=n.replace?`REPLACE`:`PUSH`,this.history[r===`REPLACE`?`replace`:`push`](o.publicHref,o.state,{ignoreBlocker:t}),this.history.subscribers.size||this.load({action:{type:r}})}return this._scroll.next=n.resetScroll??!0,this._commitPromise},this.buildAndCommitLocation=({replace:e,resetScroll:t,hashScrollIntoView:n,viewTransition:r,ignoreBlocker:i,_redirects:a,href:o,...s}={})=>{if(o){let t=this.history.location.state.__TSR_index,n=ZM(o,{__TSR_index:e?t:t+1}),r=new URL(n.pathname,this.origin);s.to=BM(this.rewrite,r).pathname,s.search=this.options.parseSearch(n.search),s.hash=n.hash.slice(1)}let c=this.buildLocation({...s,_includeValidateSearch:!0});a&&(c._redirects=a),this._pendingLocation=c;let l=this.commitLocation({...c,viewTransition:r,replace:e,resetScroll:t,hashScrollIntoView:n,ignoreBlocker:i});return queueMicrotask(()=>{this._pendingLocation===c&&(this._pendingLocation=void 0)}),l},this.navigate=async({to:e,reloadDocument:t,href:n,publicHref:r,...i})=>{let a=!1;if(n)try{new URL(`${n}`),a=!0}catch{}if(a&&!t&&(t=!0),t){if(e!==void 0||!n){let t=this.buildLocation({to:e,...i});n??=t.publicHref,r??=t.publicHref}let t=!a&&r?r:n;if(Tj(t,this.protocolAllowlist))return;if(!i.ignoreBlocker){let e=this.history.getBlockers?.()??[];for(let t of e)if(t?.blockerFn&&await t.blockerFn({currentLocation:this.latestLocation,nextLocation:this.latestLocation,action:`PUSH`}))return}i.replace?window.location.replace(t):window.location.href=t;return}return this.buildAndCommitLocation({...i,href:n,to:e,_isNavigate:!0})},this.load=async e=>{this.updateLatestLocation(),e?.action&&(this._scroll.hash=e.action.type===`PUSH`||e.action.type===`REPLACE`),await tP(this,e)},this.startViewTransition=e=>{let t=this.shouldViewTransition??this.options.defaultViewTransition;if(this.shouldViewTransition=void 0,t&&typeof document.startViewTransition==`function`){let n;if(typeof t==`object`&&window.CSS?.supports?.(`selector(:active-view-transition-type(a))`)){let r=this.latestLocation,i=this.stores.resolvedLocation.get(),a=typeof t.types==`function`?t.types(eN(r,i)):t.types;if(a===!1)return e();n={update:e,types:a}}else n=e;return document.startViewTransition(n).updateCallbackDone}return e()},this.invalidate=e=>{let t=this._committed,n=e?.filter,r=this._preloads,i=new Set([...t,...this._cache.values(),...[...r?.values()??[]].flat(),...this._tx?.[3]??[]].filter(e=>!n||n(e)).map(e=>e.id)),a=[];for(let[e,t]of r??[])t.some(e=>i.has(e.id))&&(r.delete(e),a.push(e));let o=t=>{if(i.has(t.id)){let n=this.routesById[t.routeId],r={...t,invalid:!0,...(e?.forcePending||t.status===`error`||t.status===`notFound`)&&$M(n)?{status:`pending`,error:void 0}:void 0};return t._flight=void 0,r}return t};this._committed=t.map(o);for(let[t,n]of this._cache)i.has(t)&&(n.invalid=!0,e?.forcePending&&(n.status=`pending`));for(let e of i)this._flights?.delete(e);for(let e of a)e.abort();return this.shouldViewTransition=!1,this.load({sync:e?.sync})},this.resolveRedirect=e=>{let t=e.headers.get(`Location`);if(!e.options.href||e.options._builtLocation){let t=(e.options._builtLocation??this.buildLocation(e.options)).publicHref||`/`;e.options.href=t,e.headers.set(`Location`,t)}else if(t)try{let n=new URL(t);if(this.origin&&n.origin===this.origin){let t=n.pathname+n.search+n.hash;e.options.href=t,e.headers.set(`Location`,t)}}catch{}if(e.options.href&&!e.options._builtLocation&&Tj(e.options.href,this.protocolAllowlist))throw Error(`Redirect blocked: unsafe protocol`);return e.headers.get(`Location`)||e.headers.set(`Location`,e.options.href),e},this.clearCache=e=>{let t=this._cache,n=this._preloads,r=e?.filter,i=[],a=[];for(let[e,n]of t)(!r||r(n))&&(a.push(e),i.push(n));let o=[];for(let[e,t]of n??[])(!r||t.some(r))&&(o.push(e),i.push(...t));for(let e of a)t.delete(e);for(let e of o)n.delete(e);for(let e of i){let t=e._flight;e._flight=void 0,t&&!--t[2]&&(this._flights?.get(e.id)===t&&this._flights.delete(e.id),o.push(t[1]))}for(let e of o)e.abort()},this.loadRouteChunk=pN,this.preloadRoute=e=>nP(this,e),this.matchRoute=(e,t)=>{let n={...e,to:e.to?this.resolvePathWithBase(e.from||``,e.to):void 0,params:e.params||{},leaveParams:!0},r=this.buildLocation(n),i=this.stores.status.get()===`pending`;if(t?.pending&&!i)return!1;let a=t?.pending??!i?this.latestLocation:this.stores.resolvedLocation.get()||this.stores.location.get(),o=Vj(r.pathname,t?.caseSensitive??!1,t?.fuzzy??!1,a.pathname,this.processedTree);return!o||e.params&&!bj(o.rawParams,e.params,{partial:!0})?!1:t?.includeSearch??!0?bj(a.search,r.search,{partial:!0})?o.rawParams:!1:o.rawParams},this.getStoreConfig=t,this.update({defaultPreloadDelay:50,defaultPendingMs:1e3,defaultPendingMinMs:500,context:void 0,...e,caseSensitive:e.caseSensitive??!1,notFoundMode:e.notFoundMode??`fuzzy`,stringifySearch:e.stringifySearch??MM,parseSearch:e.parseSearch??jM,protocolAllowlist:e.protocolAllowlist??wj}),self.__TSR_ROUTER__=this}isShell(){return!!this.options.isShell}get state(){return this.stores.__store.get()}setRoutes({routesById:e,routesByPath:t,processedTree:n}){this.routesById=e,this.routesByPath=t,this.processedTree=n;let r=this.options.notFoundRoute;r&&(r.init({originalIndex:99999999999}),this.routesById[r.id]=r)}getRouteBranch(e){let t=this.routeBranchCache.get(e);return t||(t=qj(e),this.routeBranchCache.set(e,t)),t}matchRoutesInternal(e,t){let[n,r,i]=this.getMatchedRoutes(e.pathname),a=n,o=!1;(i?i.path!==`/`&&r[`**`]:rM(e.pathname))&&(this.options.notFoundRoute?a=[...a,this.options.notFoundRoute]:o=!0);let s=o?cN(this.options.notFoundMode,a):void 0,c=Array(a.length),l=this._committed,u=(e,t)=>{let n=l[t];return n?.routeId===e.id?n:e===this.options.notFoundRoute?l.find(t=>t.routeId===e.id):void 0},d;for(let n=0;n<a.length;n++){let i=a[n],o=c[n-1],l,f,p;{let n=o?.search??e.search,r=o?._strictSearch??void 0;try{let e=oN(i.options.validateSearch,{...n})??void 0;l={...n,...e},f={...r,...e}}catch(e){let r=e;if(e instanceof iN||(r=new iN(e.message,{cause:e})),t?.throwOnError)throw r;l=n,f={},p=r}}let m=``,h=``;try{m=i.options.loaderDeps?.({search:l})??``,h=m&&JSON.stringify(m)||``}catch(e){if(t?.throwOnError)throw e;p??=e}let{interpolatedPath:g,usedParams:_}=uM({path:i.fullPath,params:r,decoder:this.pathParamsDecoder,server:this.isServer}),v=i.id+g+h,y=u(i,n),b=this._cache.get(v)??(y?.id===v?y:void 0);d=b?._strictParams??Object.assign(_,d);let x;if(!b)try{uN(i,d)}catch(e){if(x=fM(e)||LM(e)?e:new aN(e.message,{cause:e}),t?.throwOnError)throw x}let S=y?`stay`:`enter`,C;if(b)C={...b,cause:S,search:mj(y?y.search:b.search,l),_strictSearch:f,searchError:p};else{let e=$M(i)?`pending`:`success`;C={id:v,ssr:i.options.ssr,index:n,routeId:i.id,params:y?.params??d,_strictParams:d,pathname:g,updatedAt:Date.now(),search:y?mj(y.search,l):l,_strictSearch:f,searchError:p,status:e,isFetching:!1,error:void 0,paramsError:x,context:{},abortController:t?._controller??new AbortController,cause:S,loaderDeps:y?hj(y.loaderDeps,m):m,invalid:!1,preload:!1,staticData:i.options.staticData||{},fullPath:i.fullPath}}let w=s===i.id;C._notFound&&!w&&(C.error=void 0),C._notFound=w,c[n]=C}for(let e=0;e<c.length;e++){let n=c[e];n.params=n.cause===`stay`?mj(n.params,d):d,t?._controller&&(n.context={})}return c}matchRoutesLightweight(e){let t=sj(this.stores.ids.get()),n=t?this.stores.byRoute.get(t).get():void 0,r=n?.id,i=this.lightweightCache.get(e);if(i&&i[0]===r)return i[1];let[a,o]=this.getMatchedRoutes(e.pathname),s=sj(a),c={...e.search};for(let e of a)try{Object.assign(c,oN(e.options.validateSearch,c))}catch{}let l=n&&n.routeId===s.id&&n.pathname===e.pathname,u;if(l)u=n.params;else{let e=Object.assign(Object.create(null),o);for(let t of a)try{uN(t,e)}catch{}u=e}let d=[a,s.fullPath,c,u];return this.lightweightCache.set(e,[r,d]),d}},iN=class extends Error{},aN=class extends Error{};function oN(e,t){if(e==null)return{};if(`~standard`in e){let n=e[`~standard`].validate(t);if(n instanceof Promise)throw new iN(`Async validation not supported`);if(n.issues)throw new iN(JSON.stringify(n.issues,void 0,2),{cause:n});return n.value}return`parse`in e?e.parse(t):typeof e==`function`?e(t):{}}function sN(e,t,n,r){let i=[];for(let e of n){let t=e.options;`search`in t?t.search?.middlewares&&i.push(...t.search.middlewares):(t.preSearchFilters||t.postSearchFilters)&&i.push(({search:e,next:n})=>{let r=n(t.preSearchFilters?t.preSearchFilters.reduce((e,t)=>t(e),e):e);return t.postSearchFilters?t.postSearchFilters.reduce((e,t)=>t(e),r):r});let n=t.validateSearch;n&&i.push(({search:e,next:t,meta:i})=>{let a=t(e);if(r)try{let e=oN(n,a);if(i&&e)for(let t in e)t in a||(i.defaulted||=new Map).set(t,e[t]);return{...a,...e}}catch{}return a})}let a=(e,n,r)=>{if(e>=i.length){if(!t.search)return{};if(t.search===!0)return n;let e=lj(t.search,n);return r&&(r.explicit=e),e}return i[e]({search:n,next:(t,n)=>{if(n){let n=r||{};return{search:a(e+1,t,n),meta:n}}return a(e+1,t,r)},meta:r})};return a(0,e)}function cN(e,t){if(e!==`root`){let e;for(let n=t.length-1;n>=0;n--){let r=t[n];if(r.options.notFoundComponent)return r.id;e||=r.children&&r.id}if(e)return e}return FM}function lN(e,t){return e===!1||e===null?Object.create(null):(e??!0)===!0?t:Object.assign(t,lj(e,t))}function uN(e,t){let n=e.options.params?.parse??e.options.parseParams;n&&Object.assign(t,n(t))}function dN(e,t){return e.options[t]?.preload?.()}function fN(e,t){let n=dN(e,`component`),r=dN(e,`pendingComponent`),i=t&&r?r.then(t):r;return t&&!r&&t(),n&&i?Promise.all([n,i]).then(()=>{}):n??i}function pN(e,t,n){let r=()=>t===!1?void 0:t?dN(e,t):fN(e,n),i=e._lazy;if(i)return i===!0?r():i.then(r);if(!e.lazyFn)return r();let a=e.lazyFn().then(t=>{{let{id:n,...r}=t.options;Object.assign(e.options,r),e._lazy=!0}},t=>{throw e._lazy=void 0,t});return e._lazy=a,a.then(r)}function mN(e){let t=e.findIndex(e=>e.status!==`success`||e._notFound)+1;return t&&t<e.length?e.slice(0,t):e}var hN=0,gN=1,_N=2,vN=3,yN=4;function bN(e){return typeof e[0]==`number`}function xN(e,t){return t.aborted?Promise.race([Promise.reject(t),e]):new Promise((n,r)=>{let i=()=>r(t);t.addEventListener(`abort`,i,{once:!0}),Promise.resolve(e).then(n,r).finally(()=>t.removeEventListener(`abort`,i))})}function SN(e,t){return e.routesById[t.routeId]}function CN(e,t,n){return LM(e)?[vN,e]:fM(e)?(e.routeId||=n,[_N,e]):(t&&typeof e?.then==`function`&&(e=Error(`A Promise was thrown`,{cause:e})),t?[gN,e]:[hN,e])}function wN(e,t){let n=CN(t,!0,e.id);if(n[0]!==gN)return n;try{e.options.onError?.(n[1])}catch(t){n=CN(t,!0,e.id)}return n}function TN(e,t,n){return n[0].signal.aborted||!n[2]()?(n[0].abort(),[yN]):wN(e,t)}function EN(e,t){return n=>e.navigate({...n,_fromLocation:t})}async function DN(e,t,n,r,i,a){let[o,s]=t,c=n[0].signal,l=!!n[4];for(let t=n[7]??0;t<r;t++){let r=s[t],i=SN(e,r);r.abortController=n[0];let u=s[t-1]?.context??e.options.context??{},d={params:r.params,location:o,navigate:EN(e,o),buildLocation:e.buildLocation,cause:l?`preload`:r.cause,abortController:n[0],preload:l,matches:s,routeId:i.id},f=u;try{let e=r._ctx;!e&&i.options.context&&(e=r._ctx=i.options.context({...d,deps:r.loaderDeps,context:u})||{}),f={...u,...e},r.context=f}catch(a){return kN(e,r),[t,TN(i,a,n)]}if(c.aborted||!n[2]())return n[0].abort(),[t,[yN]];let p=r.paramsError??r.searchError;if(p!==void 0)return kN(e,r),[t,TN(i,p,n)];let m=i.options.beforeLoad;if(!m)continue;let h={...d,search:r.search,context:f,...e.options.additionalContext},g=r.status;g===`success`&&t>=a&&(r.status=`pending`),n[8]?.();try{MN(e,r,`beforeLoad`,n[0]);let a=await xN(m(h),c);if(!n[2]())return n[0].abort(),[t,[yN]];let o=CN(a,!1,i.id);if(o[0]!==hN)return kN(e,r),[t,o];r.context={...f,...a}}catch(a){return kN(e,r),[t,TN(i,a,n)]}finally{g===`success`&&r.status===`pending`&&(r.status=`success`),MN(e,r,!1,n[0])}}i()}function ON(e,t,n){if(!(!n||--n[2])){if(e._flights?.get(t.id)===n){let n=e._tx;if(n&&!n[0].signal.aborted&&!n[3].includes(t)&&n[3].some(e=>e.id===t.id)&&n[3].some(e=>e.isFetching===`beforeLoad`))return;e._flights.delete(t.id)}return n[1]}}function kN(e,t){let n=t._flight;t._flight=void 0,ON(e,t,n)?.abort()}function AN(e,t,n,r){let i=[];for(let a of t)if(!n?.includes(a)){let t=a._flight;if(a._flight=void 0,r&&t?.[2]===1&&e._flights?.get(a.id)===t&&n?.some(e=>e.id===a.id))t[2]=0;else{let n=ON(e,a,t);n&&i.push(n)}}for(let e of i)e.abort()}function jN(e){for(let t of e){let e=t._flight;e&&e[2]++}}function MN(e,t,n,r){if(t.isFetching=n,r&&e._tx?.[0]!==r)return;let i=e.stores.byRoute.get(t.routeId),a=i?.get();a?.id===t.id&&i.set({...a,isFetching:n})}function NN(e,t,n,r,i,a,o){let s=t[0];return{params:n.params,location:s,navigate:EN(e,s),cause:o?`preload`:n.cause,abortController:i,preload:o,deps:n.loaderDeps,parentMatchPromise:a,context:n.context,route:r,...e.options.additionalContext}}async function PN(e,t,n,r,i,a,o,s){let c=s.signal;if(c.aborted)return[yN];if(!i)return[hN,void 0];let l=n._flight;MN(e,n,`loader`,s);try{if(!l){let s=new AbortController;l=[Promise.resolve().then(()=>i(NN(e,t,n,r,s,a,o))).then(e=>CN(e,!1,r.id),e=>CN(e,!0,r.id)).then(t=>(t[0]!==hN&&e._flights?.get(n.id)===l&&(e._flights.delete(n.id),l[2]||s.abort()),t[0]===gN&&l[2]?wN(r,t[1]):t)),s,1],(e._flights??=new Map).set(n.id,l)}return n._flight=l,n.abortController=l[1],await xN(l[0],c)}catch(t){if(t!==c)throw t;return kN(e,n),[yN]}finally{MN(e,n,!1,s)}}function FN(e,t,n){t[0]===hN?(e.loaderData=t[1],e.error=void 0,e.status=`success`,e.invalid=!1,e.updatedAt=Date.now(),e.preload=n):t[0]!==vN&&(e.status=`success`,e.error=void 0,e.invalid=!0)}function IN(e,t,n){let r=e._cache.get(t.id);if(r!==n||e._committed.some(e=>e.id===t.id&&e._flight===t._flight))return;let i={...t,_notFound:void 0,context:{}};i._flight&&i._flight[2]++,e._cache.set(t.id,i),r&&kN(e,r)}function LN(e,t){return t[0]===gN||t[0]===_N?{...e,status:t[0]===gN?`error`:`notFound`,error:t[1],_flight:void 0}:e}function RN(e,t,n,r,i,a,o){let s=t[1][n],c=SN(e,s),l=!!a[4],u=e._cache.get(s.id),d,f=!1,p;try{if(s.status===`success`&&(d=c.options.shouldReload,typeof d==`function`&&(d=d(NN(e,t,s,c,a[0],i,l))),a[2]()||(a[0].abort(),p=[yN])),!p){if(s.status!==`success`)f=!0;else{let t=a[4]||s.preload?c.options.preloadStaleTime??e.options.defaultPreloadStaleTime??3e4:c.options.staleTime??e.options.defaultStaleTime??0;f=!!(s.invalid||d||d===void 0&&Date.now()-s.updatedAt>=t&&(a[6]||s.cause===`enter`||a[3].some(e=>e.routeId===s.routeId&&e.id!==s.id)))}}}catch(t){s.invalid=!0,kN(e,s),p=TN(c,t,a)}let m=c.options.loader,h=typeof m==`function`?m:m?.handler,g=(!l||c.options.preload!==!1)&&m?e._flights?.get(s.id):void 0;g===s._flight||p?g=void 0:g&&!f&&!l&&d===void 0?f=!0:f||(g=void 0);let _=!!(m&&f&&s.status===`success`&&!l&&!a[5]&&((typeof m==`function`?void 0:m?.staleReloadMode)??e.options.defaultStaleReloadMode)!==`blocking`),v=f&&(!l||c.options.preload!==!1),y=v&&!_&&(s.status!==`success`||!!m),b=c.lazyFn&&c._lazy!==!0?a[8]:void 0;if(v&&!m&&(s.invalid=!1,s.updatedAt=Date.now()),g&&g[2]++,y){let t=s._flight;s._flight=g,ON(e,s,t)?.abort(),s.status===`success`&&n>=o&&(s.status=`pending`),a[8]?.()}v||(s.isFetching=!1);let x=(p?Promise.resolve(p):y?PN(e,t,s,c,h,i,l,a[0]):Promise.resolve([hN,s.loaderData])).then(t=>(y&&(FN(s,t,l),t[0]===hN&&(m&&!a[0].signal.aborted&&IN(e,s,u),s.status=`pending`)),t)),S=xN(Promise.resolve().then(()=>pN(c,void 0,b)),a[0].signal).then(()=>void 0,e=>[n,TN(c,e,a)]).then(e=>x.then(t=>(y&&!e&&t[0]===hN&&s.status===`pending`&&a[2]()&&(s.status=`success`,a[8]?.()),e)));if(r.push([n,x,S]),!_)return x.then(e=>LN(s,e));let C={...s,status:`pending`,preload:!1,_flight:g};s.invalid=!1,s.isFetching=`loader`;let w=PN(e,t,C,c,h,i,!1,a[0]).then(e=>(s.isFetching=!1,FN(C,e,!1),e));return(t[2]??=[]).push([n,w,S,C]),w.then(e=>LN(C,e))}async function zN(e,t,n,r,i=0){let a=n?.[1][1],o=a?.routeId?t.findIndex(e=>e.routeId===a.routeId):n?.[0]??t.length-1;o<0&&(o=0);for(let n=o;n>=0;n--){let i=SN(e,t[n]),a=pN(i,!1);if(a)try{await xN(a,r)}catch(e){if(e===r)throw e}if(i.options.notFoundComponent)return n}return a?.routeId?o:i}function BN(e,t){t[2]&&=(AN(e,t[2].map(e=>e[3])),void 0)}async function VN(e,t,n,r){let i;try{await Promise.all(e.map(e=>e[1].then(async t=>{let a=e[0];if(!(r&&a>=await r)){if(t[0]>=vN)throw[a,t];!i&&t[0]!==hN&&(i=[a,t],await Promise.all((n??[]).map(e=>{if(!(e[0]<=a))return e[1].then(t=>{if(t[0]===vN)throw[e[0],t]})})))}})))}catch(e){return e}return t??i}async function HN(e,t,n,r,i,a,o){let s=t[1],c=await a,l=!1,u=s.findIndex(e=>e._notFound),d=t=>t[1][0]===_N?zN(e,s,t,r.signal):t[0],f=u<0?s.length:u;if((c?.[1][0]??0)>=vN)f=0;else if(c){f=c[2]??=await d(c);for(let e of n){if(e[0]>=f)break;let t=await e[1];if(t[0]!==hN&&t[0]<vN&&!(`loaderData`in s[e[0]])){c=[e[0],t],f=c[2]=await d(c);break}}}for(let e of n){if(e[0]>=f)break;let t=await e[2];if(t){c=t;break}}if((c?.[1][0]??0)>=vN){let n=c[1];if(n[0]!==vN||n[1].options.reloadDocument||i<20)return BN(e,t),n;l=!0,c=[0,[gN,Error(`Too many redirects`)]]}let p=c?c[2]??await d(c):u;if(p>=0){let i=c?.[1],a=i?.[0],u=s[p],d=i?.[1],f=()=>{i&&(u._notFound=void 0,a===gN?u.status=`error`:(d.routeId=u.routeId,u.routeId===e.routeTree.id?(u.status=`success`,u._notFound=!0):u.status=`notFound`),u.error=d,u.isFetching=!1)};f();let m=SN(e,u);try{await xN(i?Promise.resolve().then(()=>pN(m,a===gN?`errorComponent`:`notFoundComponent`)):Promise.all([pN(m),pN(m,`notFoundComponent`)]),r.signal)}catch(n){if(n===r.signal)return BN(e,t),[yN]}i?l&&(r.abort(),await Promise.all([...n.map(e=>e[1]),...n.map(e=>e[2]),...(t[2]??[]).map(e=>e[1])]),BN(e,t),AN(e,s),f()):(u.status=`success`,o?.())}return t}async function UN(e,t,n,r=0,i=t[1].length){let a=t[1];for(let t=r;t<i;t++){let r=a[t],i=SN(e,r).options;if(i.head||i.scripts)try{let t={ssr:e.options.ssr,matches:a,match:r,params:r.params,loaderData:r.loaderData},[o,s]=await xN(Promise.all([i.head?.(t),i.scripts?.(t)]),n);r.meta=o?.meta,r.links=o?.links,r.headScripts=o?.scripts,r.styles=o?.styles,r.scripts=s}catch(e){if(e===n)break;console.error(e)}if(r.status!==`success`||r._notFound)break}return t}async function WN(e,t,n,r){let i=[t,n],a=e.stores.matches.get(),o=n.findIndex(e=>e._notFound);if(e.options.notFoundMode!==`root`&&o>=0){let t=await zN(e,i[1],void 0,r[0].signal,o);t!==o&&(n[o]._notFound=void 0,n[t]._notFound=!0),o=t}let s=o<0?n.length:o+1,c=0;for(;c<s&&c!==o;){let e=n[c],t=r[3][c],i=a[c];if(t?.id!==e.id||t.status!==`success`||t._notFound||e.preload||i?.id!==e.id||i.status!==`success`||i._notFound)break;c++}let l=[],u=r[7]??0,d=u?Promise.resolve(i[1][u-1]):void 0,f=()=>{for(let t=u;t<s&&!r[0].signal.aborted;t++)d=RN(e,i,t,l,d,r,c)},p=await DN(e,i,r,s,f,c);if(p&&(r[5]=!0,s=p[0],p[1][0]===_N?(p[2]=await zN(e,i[1],p,r[0].signal),s=Math.min(s,p[2]+1)):p[1][0]>=vN&&(s=0),f()),r[2]()&&!r[4]){let t=[];for(let[n,r]of e._flights??[])r[2]||(e._flights.delete(n),t.push(r[1]));for(let e of t)e.abort()}let m;try{let t=HN(e,i,l,r[0],r[1],VN(l,p,i[2]),r[8]);i[2]?.length&&(i[3]=VN(i[2],void 0,void 0,t.then(e=>bN(e)?0:mN(e[1]).length,()=>0))),m=await t}catch(t){throw BN(e,i),t}return bN(m)?m:UN(e,m,r[0].signal,r[7]===m[1].length?r[7]:0)}function GN(e,t){if(e._tx!==t)return;let n=e._pending,r=!1,i=n?.[0][3][n[1]]?.id;n?.[0]!==t&&(n&&t[3][n[1]]?.id===i?(n[0]=t,r=!0):(clearTimeout(n?.[3]),e._pending=n=void 0));let a=t[3],o=e.stores.matches.get(),s=-1,c,l,u,d=!1;for(let t=0;t<a.length;t++){let n=a[t],r=n.status===`success`;if(d=o[t]?.id===n.id&&o[t]?.status===`pending`,r&&!d)continue;let i=SN(e,n);if(c=r&&d||n.invalid?0:i.options.pendingMs??e.options.defaultPendingMs,u=i.options.pendingComponent??e.options.defaultPendingComponent,!u||typeof c!=`number`||c===1/0)return;s=t,l=i.options.pendingMinMs??e.options.defaultPendingMinMs??0;break}if(s<0)return;let f=a[s].id;if((!n||n[1]!==s||i!==f)&&(clearTimeout(n?.[3]),e._pending=n=[t,s,d?Date.now()+l:t[4]+c,void 0,d?Promise.resolve(!0):void 0,u]),n[4]&&!r&&n[5]===u)return;if(n[5]=u,!n[4]){clearTimeout(n[3]);let r=n[2]-Date.now();if(r>0){n[3]=setTimeout(()=>GN(e,t),r);return}n[2]=0}let p=a.map(e=>({...e,_flight:void 0}));p[s].status=`pending`;let m=e.startTransition(()=>e.stores.setMatches(p),p).then(t=>(t&&e._pending===n&&n[4]===m&&!n[2]&&(n[2]=Date.now()+l),t));n[4]=m}function KN(e,t){let n=e._pending;n?.[0]===t&&(clearTimeout(n[3]),e._pending=void 0)}function qN(e,t){e._committed=t,e.stores.setMatches(t)}function JN(e,t){AN(e,t[1]),BN(e,t)}function YN(e,t,n,r){let i=e._committed,a=e._cache;for(let e of n)e.preload=!1,r&&(e._assetEnd=void 0);let o=mN(n).length,s=new Map,c=Date.now();for(let t of[...i,...a.values()]){if(t.status!==`success`||n.some((e,n)=>e.id===t.id&&(n<o||e.status===`success`)))continue;let r=SN(e,t);!r.options.loader||c-t.updatedAt>=(t.preload?r.options.preloadGcTime??e.options.defaultPreloadGcTime??3e5:r.options.gcTime??e.options.defaultGcTime??3e5)||s.set(t.id,a.get(t.id)===t?t:{...t,_flight:void 0,isFetching:!1,context:{}})}t[3]=[],e._cache=s,qN(e,n),AN(e,[...a.values(),...i],[...n,...s.values()]),nN(e,i,n,()=>e._tx===t)}async function XN(e,t){let n=e._tx;for(;n&&n!==t;){if(await n[5],e._tx===n)return;n=e._tx}}async function ZN(e,t,n){await e.navigate({...n.options,replace:!0,ignoreBlocker:!0,_redirects:t[1]+1})}function QN(e,t){KN(e,t),t[0].abort(),AN(e,t[3]),t[3]=[],e._tx===t&&(e.batch(()=>{e.stores.status.set(`idle`),e.stores.setMatches(e._committed)}),e._tx===t&&(e._commitPromise?.resolve(),e._commitPromise=void 0))}async function $N(e,t,n,r,i){let a=n.map(e=>({...e}));jN(a);for(let t of r)kN(e,a[t[0]]),a[t[0]]=t[3];let o=[t[2],a],s;try{s=await HN(e,o,r,t[0],t[1],i)}catch(t){throw AN(e,a),t}if(bN(s)){AN(e,a),s[0]===vN&&e._tx===t&&e._committed===n&&await ZN(e,t,s[1]);return}let c=await UN(e,s,t[0].signal);if(e._tx!==t||e._committed!==n){AN(e,c[1]);return}for(let t of c[1]){let n=e._cache.get(t.id);n?._flight&&n._flight===t._flight&&(e._cache.delete(t.id),kN(e,n))}qN(e,c[1]),AN(e,n,c[1])}async function eP(e,t,n,r,i,a){let o=[t[0],t[1],()=>e._tx===t&&!!t[3].length,e._committed,void 0,i,n,a,r],s=await WN(e,t[2],t[3],o);if(bN(s)){s[0]===vN&&e._tx===t?(KN(e,t),AN(e,t[3]),t[3]=[],e._tx===t&&await ZN(e,t,s[1])):QN(e,t);return}let c=e._pending;if(c?.[0]===t&&(clearTimeout(c[3]),c[4])){let n=t[0].signal,r=!1;try{r=await xN(c[4],n)}catch(e){if(e!==n)throw e}if(r&&e._pending===c&&c[0]===t){let e=c[2]-Date.now();if(e>0){try{await xN(new Promise(t=>{c[3]=setTimeout(t,e)}),n)}catch{}clearTimeout(c[3])}}}if(e._tx!==t){KN(e,t),JN(e,s);return}let l=t[2],u=eN(l,e.stores.resolvedLocation.get()),d=s[2];await e.startViewTransition(async()=>{if(e._tx!==t){JN(e,s);return}let n=await e.startTransition(()=>{KN(e,t),YN(e,t,s[1],a),e._tx===t&&(e.emit({type:`onLoad`,...u}),e._tx===t&&e.emit({type:`onBeforeRouteMount`,...u}))},s[1]);if(e._tx!==t){BN(e,s);return}d?.length&&$N(e,t,s[1],d,s[3]).catch(console.error),e.batch(()=>{e.stores.resolvedLocation.set(l),e.stores.status.set(`idle`),e._tx===t&&e.emit({type:`onResolved`,...u}),n&&e._tx===t&&e.emit({type:`onRendered`,...u})}),e._tx===t&&(e._commitPromise?.resolve(),e._commitPromise=void 0)})}async function tP(e,t){let n=e._tx,r=e.stores.resolvedLocation.get(),i=r??e.stores.location.get(),a=e.latestLocation,o=e._pendingLocation,s=o?.href===a.href?o._redirects??0:0,c=e._handoff,l=c?.[0](),u=new AbortController,d=e._preflight;if(e._preflight=u,l||c?.[1](),d?.abort(),u.signal.aborted){await XN(e,n);return}let f=eN(a,r);if(e.emit({type:`onBeforeNavigate`,...f}),u.signal.aborted||e.emit({type:`onBeforeLoad`,...f}),u.signal.aborted){await XN(e,n);return}let p=i.href===a.href,m,h=u;try{m=e.matchRoutes(a,{_controller:u}),jN(m)}catch(t){if(u.abort(),!LM(t)){await XN(e),e._commitPromise?.resolve(),e._commitPromise=void 0;return}await e.navigate({...t.options,replace:!0,ignoreBlocker:!0}),await XN(e,n);return}let g=l?c[1](m):void 0;if(g?h=l:l?.abort(),u.signal.aborted){AN(e,m),await XN(e,n);return}e._preflight=void 0;let _=[h,s,a,m,Date.now(),Promise.resolve().then(()=>eP(e,_,p,()=>GN(e,_),t?.sync,g)).catch(()=>{e._tx===_&&QN(e,_)})];if(e._tx=_,n){for(let t of e.stores.matches.get()){if(e._tx!==_)break;t.isFetching&&MN(e,t,!1)}n[0].abort(),AN(e,n[3],_[3],!0)}if(e._tx!==_){AN(e,_[3]),_[3]=[],await XN(e,_);return}e.batch(()=>{e.stores.status.set(`pending`),e.stores.location.set(a)}),!r&&!m.some(e=>e._notFound)&&GN(e,_);try{await _[5]}finally{await XN(e,_)}}async function nP(e,t,n=0){if(n>20)return;let r=t._builtLocation??e.buildLocation(t),i=e._committed,a=new AbortController,o;try{o=e.matchRoutes(r,{_controller:a}),jN(o)}catch(e){a.abort(),fM(e)||console.error(e);return}(e._preloads??=new Map).set(a,o);let s;try{let t;try{t=await WN(e,r,o,[a,n,()=>!0,i,!0])}finally{s=e._preloads.delete(a),AN(e,o),a.abort()}if(!bN(t))return t[1];if(s&&t[0]===vN&&!t[1].options.reloadDocument)return nP(e,{...t[1].options,_fromLocation:r},n+1)}catch(e){fM(e)||console.error(e)}}var rP=`Error preloading route! ☝️`,iP=class{get to(){return this._to}get id(){return this._id}get path(){return this._path}get fullPath(){return this._fullPath}constructor(e){if(this.init=e=>{this.originalIndex=e.originalIndex;let t=this.options,n=!t?.path&&!t?.id;this.parentRoute=this.options.getParentRoute?.(),n?this._path=FM:this.parentRoute||kj();let r=n?FM:t?.path;r&&r!==`/`&&(r=nM(r));let i=t?.id||r,a=n?FM:eM([this.parentRoute.id===`__root__`?``:this.parentRoute.id,i]);r===`__root__`&&(r=`/`),a!==`__root__`&&(a=eM([`/`,a]));let o=a===`__root__`?`/`:eM([this.parentRoute.fullPath,r]);this._path=r,this._id=a,this._fullPath=o,this._to=rM(o)},this.addChildren=e=>this._addFileChildren(e),this._addFileChildren=e=>(Array.isArray(e)&&(this.children=e),typeof e==`object`&&e&&(this.children=Object.values(e)),this),this._addFileTypes=()=>this,this.updateLoader=e=>(Object.assign(this.options,e),this),this.update=e=>(Object.assign(this.options,e),this),this.lazy=e=>(this.lazyFn=e,this),this.redirect=e=>IM({from:this.fullPath,...e}),this.options=e||{},this.isRoot=!e?.getParentRoute,e?.id&&e?.path)throw Error(`Route cannot have both an 'id' and a 'path' option.`)}},aP=class extends iP{constructor(e){super(e)}};function oP(e){return(0,X.jsx)(sP,{...e})}var sP=class extends J.Component{constructor(...e){super(...e),this.state={error:null},this.reset=()=>{this.setState({error:null})}}static getDerivedStateFromProps(e,t){let n=e.getResetKey();return t.error&&t.resetKey!==n?{resetKey:n,error:null}:{resetKey:n}}static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){this.props.onCatch?.(e,t)}render(){let e=this.state.error;return e?J.createElement(this.props.errorComponent??cP,{error:e,reset:this.reset}):this.props.children}};function cP({error:e}){let[t,n]=J.useState(!1);return(0,X.jsxs)(`div`,{style:{padding:`.5rem`,maxWidth:`100%`},children:[(0,X.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`.5rem`},children:[(0,X.jsx)(`strong`,{style:{fontSize:`1rem`},children:`Something went wrong!`}),(0,X.jsx)(`button`,{style:{appearance:`none`,fontSize:`.6em`,border:`1px solid currentColor`,padding:`.1rem .2rem`,fontWeight:`bold`,borderRadius:`.25rem`},onClick:()=>n(e=>!e),children:t?`Hide Error`:`Show Error`})]}),(0,X.jsx)(`div`,{style:{height:`.25rem`}}),t?(0,X.jsx)(`div`,{children:(0,X.jsx)(`pre`,{style:{fontSize:`.7em`,border:`1px solid red`,borderRadius:`.25rem`,padding:`.3rem`,color:`red`,overflow:`auto`},children:e.message?(0,X.jsx)(`code`,{children:e.message}):null})}):null]})}function lP({children:e,fallback:t=null}){return(0,X.jsx)(J.Fragment,{children:uP()?e:t})}function uP(){return J.useSyncExternalStore(dP,()=>!0,()=>!1)}function dP(){return()=>{}}var fP=J.createContext(null);function pP(e){return J.useContext(fP)}var mP=J.createContext(void 0),hP=J.createContext(void 0),gP=(e=>(e[e.None=0]=`None`,e[e.Mutable=1]=`Mutable`,e[e.Watching=2]=`Watching`,e[e.RecursedCheck=4]=`RecursedCheck`,e[e.Recursed=8]=`Recursed`,e[e.Dirty=16]=`Dirty`,e[e.Pending=32]=`Pending`,e))(gP||{});function _P({update:e,notify:t,unwatched:n}){return{link:r,unlink:i,propagate:a,checkDirty:o,shallowPropagate:s};function r(e,t,n){let r=t.depsTail;if(r!==void 0&&r.dep===e)return;let i=r===void 0?t.deps:r.nextDep;if(i!==void 0&&i.dep===e){i.version=n,t.depsTail=i;return}let a=e.subsTail;if(a!==void 0&&a.version===n&&a.sub===t)return;let o=t.depsTail=e.subsTail={version:n,dep:e,sub:t,prevDep:r,nextDep:i,prevSub:a,nextSub:void 0};i!==void 0&&(i.prevDep=o),r===void 0?t.deps=o:r.nextDep=o,a===void 0?e.subs=o:a.nextSub=o}function i(e,t=e.sub){let r=e.dep,i=e.prevDep,a=e.nextDep,o=e.nextSub,s=e.prevSub;return a===void 0?t.depsTail=i:a.prevDep=i,i===void 0?t.deps=a:i.nextDep=a,o===void 0?r.subsTail=s:o.prevSub=s,s===void 0?(r.subs=o)===void 0&&n(r):s.nextSub=o,a}function a(e){let n=e.nextSub,r;top:do{let i=e.sub,a=i.flags;if(a&60?a&12?a&4?!(a&48)&&c(e,i)?(i.flags=a|40,a&=1):a=0:i.flags=a&-9|32:a=0:i.flags=a|32,a&2&&t(i),a&1){let t=i.subs;if(t!==void 0){let i=(e=t).nextSub;i!==void 0&&(r={value:n,prev:r},n=i);continue}}if((e=n)!==void 0){n=e.nextSub;continue}for(;r!==void 0;)if(e=r.value,r=r.prev,e!==void 0){n=e.nextSub;continue top}break}while(!0)}function o(t,n){let r,i=0,a=!1;top:do{let o=t.dep,c=o.flags;if(n.flags&16)a=!0;else if((c&17)==17){if(e(o)){let e=o.subs;e.nextSub!==void 0&&s(e),a=!0}}else if((c&33)==33){(t.nextSub!==void 0||t.prevSub!==void 0)&&(r={value:t,prev:r}),t=o.deps,n=o,++i;continue}if(!a){let e=t.nextDep;if(e!==void 0){t=e;continue}}for(;i--;){let i=n.subs,o=i.nextSub!==void 0;if(o?(t=r.value,r=r.prev):t=i,a){if(e(n)){o&&s(i),n=t.sub;continue}a=!1}else n.flags&=-33;n=t.sub;let c=t.nextDep;if(c!==void 0){t=c;continue top}}return a}while(!0)}function s(e){do{let n=e.sub,r=n.flags;(r&48)==32&&(n.flags=r|16,(r&6)==2&&t(n))}while((e=e.nextSub)!==void 0)}function c(e,t){let n=t.depsTail;for(;n!==void 0;){if(n===e)return!0;n=n.prevDep}return!1}}function vP(e,t,n){let r=typeof e==`object`,i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}var yP=[],bP=0,{link:xP,unlink:SP,propagate:CP,checkDirty:wP,shallowPropagate:TP}=_P({update(e){return e._update()},notify(e){yP[DP++]=e,e.flags&=~gP.Watching},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=gP.Mutable|gP.Dirty,jP(e))}}),EP=0,DP=0,OP,kP=0;function AP(e){try{++kP,e()}finally{--kP||MP()}}function jP(e){let t=e.depsTail,n=t===void 0?e.deps:t.nextDep;for(;n!==void 0;)n=SP(n,e)}function MP(){if(!(kP>0)){for(;EP<DP;){let e=yP[EP];yP[EP++]=void 0,e.notify()}EP=0,DP=0}}function NP(e,t){let n=typeof e==`function`,r=e,i={_snapshot:n?void 0:e,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:n?gP.None:gP.Mutable,get(){return OP!==void 0&&xP(i,OP,bP),i._snapshot},subscribe(e){let t=vP(e),n={current:!1},r=PP(()=>{i.get(),n.current?t.next?.(i._snapshot):n.current=!0});return{unsubscribe:()=>{r.stop()}}},_update(e){let a=OP,o=t?.compare??Object.is;if(n)OP=i,++bP,i.depsTail=void 0;else if(e===void 0)return!1;n&&(i.flags=gP.Mutable|gP.RecursedCheck);try{let t=i._snapshot,a=typeof e==`function`?e(t):e===void 0&&n?r(t):e;return t===void 0||!o(t,a)?(i._snapshot=a,!0):!1}finally{OP=a,n&&(i.flags&=~gP.RecursedCheck),jP(i)}}};return n?(i.flags=gP.Mutable|gP.Dirty,i.get=function(){let e=i.flags;if(e&gP.Dirty||e&gP.Pending&&wP(i.deps,i)){if(i._update()){let e=i.subs;e!==void 0&&TP(e)}}else e&gP.Pending&&(i.flags=e&~gP.Pending);return OP!==void 0&&xP(i,OP,bP),i._snapshot}):i.set=function(e){if(i._update(e)){let e=i.subs;e!==void 0&&(CP(e),TP(e),MP())}},i}function PP(e){let t=()=>{let t=OP;OP=n,++bP,n.depsTail=void 0,n.flags=gP.Watching|gP.RecursedCheck;try{return e()}finally{OP=t,n.flags&=~gP.RecursedCheck,jP(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:gP.Watching|gP.RecursedCheck,notify(){let e=this.flags;e&gP.Dirty||e&gP.Pending&&wP(this.deps,this)?t():this.flags=gP.Watching},stop(){this.flags=gP.None,this.depsTail=void 0,jP(this)}};return t(),n}var FP=t((e=>{var t=An();function n(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var r=typeof Object.is==`function`?Object.is:n,i=t.useState,a=t.useEffect,o=t.useLayoutEffect,s=t.useDebugValue;function c(e,t){var n=t(),r=i({inst:{value:n,getSnapshot:t}}),c=r[0].inst,u=r[1];return o(function(){c.value=n,c.getSnapshot=t,l(c)&&u({inst:c})},[e,n,t]),a(function(){return l(c)&&u({inst:c}),e(function(){l(c)&&u({inst:c})})},[e]),s(n),n}function l(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!r(e,n)}catch{return!0}}function u(e,t){return t()}var d=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?u:c;e.useSyncExternalStore=t.useSyncExternalStore===void 0?d:t.useSyncExternalStore})),IP=t(((e,t)=>{t.exports=FP()})),LP=t((e=>{var t=An(),n=IP();function r(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var i=typeof Object.is==`function`?Object.is:r,a=n.useSyncExternalStore,o=t.useRef,s=t.useEffect,c=t.useMemo,l=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(e,t,n,r,u){var d=o(null);if(d.current===null){var f={hasValue:!1,value:null};d.current=f}else f=d.current;d=c(function(){function e(e){if(!a){if(a=!0,o=e,e=r(e),u!==void 0&&f.hasValue){var t=f.value;if(u(t,e))return s=t}return s=e}if(t=s,i(o,e))return t;var n=r(e);return u!==void 0&&u(t,n)?(o=e,t):(o=e,s=n)}var a=!1,o,s,c=n===void 0?null:n;return[function(){return e(t())},c===null?void 0:function(){return e(c())}]},[t,n,r,u]);var p=a(e,d[0],d[1]);return s(function(){f.hasValue=!0,f.value=p},[p]),l(p),p}})),RP=t(((e,t)=>{t.exports=LP()}))();function zP(e,t){return e===t}function BP(e,t,n=zP){let r=(0,J.useCallback)(t=>{if(!e)return()=>{};let{unsubscribe:n}=e.subscribe(t);return n},[e]),i=(0,J.useCallback)(()=>e?.get(),[e]);return(0,RP.useSyncExternalStoreWithSelector)(r,i,i,t,n)}var VP={};function HP(e,t){let n=J.useRef();return r=>{let i=e?.select?e.select(r):r;return e?.structuralSharing??t.options.defaultStructuralSharing?n.current=hj(n.current,i):i}}function UP(e){let t=pP(),n=J.useContext(e.from?hP:mP),r=e.from??n,i=t.stores.getMatchStore(r),a=HP(e,t),o=BP(i,e=>e?a(e):VP);if(o!==VP)return o;(e.shouldThrow??!0)&&kj()}function WP(e){return UP({from:e.from,strict:e.strict,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.loaderData):t.loaderData})}function GP(e){let{select:t,...n}=e;return UP({...n,select:e=>t?t(e.loaderDeps):e.loaderDeps})}function KP(e){return UP({from:e.from,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,strict:e.strict,select:t=>{let n=e.strict===!1?t.params:t._strictParams;return e.select?e.select(n):n}})}function qP(e){return UP({from:e.from,strict:e.strict,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.search):t.search})}function JP(e){let t=pP();return J.useCallback(n=>t.navigate({...n,from:n.from??e?.from}),[e?.from,t])}function YP(e){return UP({...e,select:t=>e.select?e.select(t.context):t.context})}function XP(e){let t=J.useRef(e);return bj(t.current,e,{ignoreUndefined:!1})||(t.current=e),t.current}function ZP(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]}function QP(e,t,n){if(e?.external)return Tj(e.href,n)?void 0:e.href;if(!lF(t)&&typeof t==`string`&&t.indexOf(`:`)!==-1)try{return new URL(t),Tj(t,n)?void 0:t}catch{}}function $P(e,t,n,r,i,a){if(a)return!1;if(n?.exact){if(!oM(e.pathname,t.pathname,r))return!1}else{let n=aM(e.pathname,r),i=aM(t.pathname,r);if(!(n.startsWith(i)&&(n.length===i.length||n[i.length]===`/`)))return!1}return(n?.includeSearch??!0)&&!bj(e.search,t.search,{partial:!n?.exact,ignoreUndefined:!n?.explicitUndefined})?!1:!n?.includeHash||i&&e.hash===t.hash}function eF(e,t){let n=pP(),r=oj(t),{activeProps:i,inactiveProps:a,activeOptions:o,to:s,preload:c,preloadDelay:l,preloadIntentProximity:u,hashScrollIntoView:d,replace:f,startTransition:p,resetScroll:m,viewTransition:h,children:g,target:_,disabled:v,style:y,className:b,onClick:x,onBlur:S,onFocus:C,onMouseEnter:w,onMouseLeave:T,onTouchStart:E,ignoreBlocker:D,params:O,search:k,hash:A,state:j,mask:M,reloadDocument:ee,unsafeRelative:te,from:ne,_fromLocation:re,...ie}=e,ae=uP(),oe=XP(e.search),se=XP(e.params),ce=XP(o),le=J.useMemo(()=>e,[n,e.from,e._fromLocation,e.hash,e.to,oe,se,e.state,e.mask,e.unsafeRelative]),N=J.useCallback(e=>{let t=n.buildLocation({_fromLocation:e,...le}),r=cF(t.maskedLocation?t.maskedLocation.publicHref:t.publicHref,t.maskedLocation?t.maskedLocation.external:t.external,n.history,v),i=QP(r,s,n.protocolAllowlist);return[r?.href,i,$P(e,t,ce,n.basepath,ae,i!==void 0)]},[ce,v,ae,le,n,s]),[ue,de,fe]=BP(n.stores.location,N,ZP),pe=fe?lj(i,{})??nF:tF,P=fe?tF:lj(a,{})??tF,me=[b,pe.className,P.className].filter(Boolean).join(` `),he=(y||pe.style||P.style)&&{...y,...pe.style,...P.style},ge=J.useRef(!1),_e=e.reloadDocument||de||v?!1:c??n.options.defaultPreload,ve=l??n.options.defaultPreloadDelay??0,ye=J.useCallback(()=>{n.preloadRoute(le).catch(e=>{console.warn(e),console.warn(rP)})},[n,le]),be=J.useCallback(e=>{if(!e){oF(r);return}if(!(e.isIntersecting??_e===`intent`)){e.isIntersecting===!1&&oF(r);return}if(!ve){ye();return}aF.has(r)||aF.set(r,setTimeout(()=>{aF.delete(r),ye()},ve))},[ye,r,_e,ve]);aj(r,be,_e!==`viewport`),J.useEffect(()=>{ge.current||_e===`render`&&(ye(),ge.current=!0)},[ye,_e]);let xe=e=>{let t=e.currentTarget.getAttribute(`target`),r=_===void 0?t:_;!v&&!dF(e)&&!e.defaultPrevented&&(!r||r===`_self`)&&e.button===0&&(e.preventDefault(),n.navigate({...le,replace:f,resetScroll:m,hashScrollIntoView:d,startTransition:p,viewTransition:h,ignoreBlocker:D}))};if(de)return{...ie,ref:r,href:de,...g&&{children:g},..._&&{target:_},...v&&{disabled:v},...y&&{style:y},...b&&{className:b},...x&&{onClick:x},...S&&{onBlur:S},...C&&{onFocus:C},...w&&{onMouseEnter:w},...T&&{onMouseLeave:T},...E&&{onTouchStart:E}};let Se=()=>{_e===`intent`&&ye()},Ce=()=>{_e===`intent`&&oF(r)};return{...ie,...pe,...P,href:ue,ref:r,onClick:sF([x,xe]),onBlur:sF([S,Ce]),onFocus:sF([C,be]),onMouseEnter:sF([w,be]),onMouseLeave:sF([T,Ce]),onTouchStart:sF([E,Se]),disabled:!!v,target:_,...he&&{style:he},...me&&{className:me},...v&&rF,...fe&&iF}}var tF={},nF={className:`active`},rF={role:`link`,"aria-disabled":!0},iF={"data-status":`active`,"aria-current":`page`},aF=new WeakMap,oF=e=>{clearTimeout(aF.get(e)),aF.delete(e)},sF=e=>t=>{for(let n of e)if(n){if(t.defaultPrevented)return;n(t)}};function cF(e,t,n,r){if(!r)return t?{href:e,external:!0}:{href:n.createHref(e)||`/`,external:!1}}function lF(e){if(typeof e!=`string`)return!1;let t=e.charCodeAt(0);return t===47?e.charCodeAt(1)!==47:t===46}var uF=J.forwardRef((e,t)=>{let{_asChild:n,...r}=e,{type:i,...a}=eF(r,t),o=typeof r.children==`function`?r.children({isActive:a[`data-status`]===`active`}):r.children;if(!n){let{disabled:e,...t}=a;return J.createElement(`a`,t,o)}return J.createElement(n,a,o)});function dF(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}var fF=class extends iP{constructor(e){super(e),this.useMatch=e=>UP({select:e?.select,from:this.id,structuralSharing:e?.structuralSharing}),this.useRouteContext=e=>YP({...e,from:this.id}),this.useSearch=e=>qP({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useParams=e=>KP({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useLoaderDeps=e=>GP({...e,from:this.id}),this.useLoaderData=e=>WP({...e,from:this.id}),this.useNavigate=()=>JP({from:this.fullPath}),this.Link=J.forwardRef((e,t)=>(0,X.jsx)(uF,{ref:t,from:this.fullPath,...e}))}};function pF(e){return new fF(e)}var mF=class extends aP{constructor(e){super(e),this.useMatch=e=>UP({select:e?.select,from:this.id,structuralSharing:e?.structuralSharing}),this.useRouteContext=e=>YP({...e,from:this.id}),this.useSearch=e=>qP({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useParams=e=>KP({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useLoaderDeps=e=>GP({...e,from:this.id}),this.useLoaderData=e=>WP({...e,from:this.id}),this.useNavigate=()=>JP({from:this.fullPath}),this.Link=J.forwardRef((e,t)=>(0,X.jsx)(uF,{ref:t,from:this.fullPath,...e}))}};function hF(e){return new mF(e)}function gF(e){let t=pP(),n=`not-found-${BP(t.stores.location,e=>e.pathname)}-${BP(t.stores.status,e=>e)}`;return(0,X.jsx)(oP,{getResetKey:()=>n,onCatch:(t,n)=>{if(fM(t))e.onCatch?.(t,n);else throw t},errorComponent:({error:t})=>{if(fM(t))return e.fallback?.(t);throw t},children:e.children})}function _F(){return(0,X.jsx)(`p`,{children:`Not Found`})}function vF(e){return(0,X.jsx)(X.Fragment,{children:e.children})}function yF(e,t,n){return t.options.notFoundComponent?(0,X.jsx)(t.options.notFoundComponent,{...n}):e.options.defaultNotFoundComponent?(0,X.jsx)(e.options.defaultNotFoundComponent,{...n}):(0,X.jsx)(_F,{})}function bF(e,t){let n=t?.options.pendingComponent??e.options.defaultPendingComponent;return n?(0,X.jsx)(n,{}):null}var xF=(e,t)=>e[0]===t[0]&&e[1]===t[1],SF=(e,t,n)=>!t.isRoot||t.options.shellComponent||t.options.wrapInSuspense||n===!1||n===`data-only`||!e.ssr,CF=J.memo(function({routeId:e}){let t=pP();return(0,X.jsx)(wF,{router:t,match:BP(t.stores.getMatchStore(e),e=>e)})});function wF({router:e,match:t}){let n=e.routesById[t.routeId],r=bF(e,n),i=n.options.errorComponent??e.options.defaultErrorComponent,a=n.options.onCatch??e.options.defaultOnCatch,o=n.isRoot?n.options.notFoundComponent??e.options.notFoundRoute?.options.component:n.options.notFoundComponent,s=t.ssr===!1||t.ssr===`data-only`,c=SF(e,n,t.ssr)&&(n.options.wrapInSuspense??r??(n.options.errorComponent?.preload||s))?J.Suspense:vF,l=i?oP:vF,u=o?gF:vF;return(0,X.jsxs)(n.isRoot?n.options.shellComponent??vF:vF,{children:[(0,X.jsx)(mP.Provider,{value:t.routeId,children:(0,X.jsx)(c,{fallback:r,children:(0,X.jsx)(l,{getResetKey:()=>t,errorComponent:i,onCatch:(e,n)=>{if(fM(e))throw e.routeId??=t.routeId,e;a?.(e,n)},children:(0,X.jsx)(u,{fallback:e=>{if(e.routeId??=t.routeId,e.routeId!==t.routeId)throw e;return J.createElement(o,e)},children:s?(0,X.jsx)(lP,{fallback:r,children:(0,X.jsx)(TF,{match:t})}):(0,X.jsx)(TF,{match:t})})})})}),null]})}var TF=J.memo(function({match:e}){let t=pP(),n=e.routeId,r=t.routesById[n],i=J.useMemo(()=>{let i=(r.options.remountDeps??t.options.defaultRemountDeps)?.({routeId:n,loaderDeps:e.loaderDeps,params:e._strictParams,search:e._strictSearch});return i?JSON.stringify(i):void 0},[n,e.loaderDeps,e._strictParams,e._strictSearch,r.options.remountDeps,t.options.defaultRemountDeps]),a=J.useMemo(()=>{let e=r.options.component??t.options.defaultComponent;return e?(0,X.jsx)(e,{},i):(0,X.jsx)(EF,{})},[i,r.options.component,t.options.defaultComponent]);if(e.status===`pending`){if(t.ssr&&!SF(t,r,e.ssr))return a;if(t._tx)throw t._tx[5];return bF(t,r)}if(e.status===`notFound`)return yF(t,r,e.error);if(e.status===`error`)throw e.error;return a}),EF=J.memo(function(){let e=pP(),t=J.useContext(mP),n,r,i;{let a=e.stores.getMatchStore(t);[n,r]=BP(a,e=>[!!e._notFound,e.error],xF),i=BP(e.stores.ids,e=>e[e.indexOf(t)+1])}if(n)return yF(e,e.routesById[t],r);if(!i)return null;let a=(0,X.jsx)(CF,{routeId:i});return t===`__root__`?(0,X.jsx)(J.Suspense,{fallback:bF(e),children:a}):a});function DF(e,t){let n=e[1];e.length=0,n?.(t)}function OF({t:e}){let t=pP(),n=t._rendered??=[];return t.startTransition=(r,i)=>new Promise((a,o)=>{DF(n,!1),n.push(i,a),e(t),J.startTransition(()=>{try{r()}catch(e){n[1]===a&&(n.length=0),o(e)}})}),ij(()=>{let e=t.history.subscribe(t.load);t.updateLatestLocation();let r=t.latestLocation,i=t.buildLocation({to:r.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});if(rM(r.publicHref)!==rM(i.publicHref))return t.commitLocation({...i,replace:!0,ignoreBlocker:!0}),e;let a=t.stores.resolvedLocation.get();return a?.href===r.href&&a.state.__TSR_key===r.state.__TSR_key?n.push(t.stores.matches.get(),e=>{e&&t.emit({type:`onRendered`,...eN(a,a)})}):t._tx||t.load().catch(console.error),e},[t,t.history]),null}function kF(){let e=pP(),t=e.routesById[FM],n=bF(e,t),r=e.ssr?vF:J.Suspense,i=(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(OF,{t:J.useState()[1]}),(0,X.jsx)(r,{fallback:n,children:(0,X.jsx)(AF,{})})]});return e.options.InnerWrap?(0,X.jsx)(e.options.InnerWrap,{children:i}):i}function AF(){let e=pP(),t=e._rendered,n=BP(e.stores.matches,e=>t[0]??e),r=n[0],i=r?.routeId;ij(()=>{t[0]===n&&DF(t,!0)},[t,n]);let a=i?(0,X.jsx)(CF,{routeId:i}):null;return(0,X.jsx)(mP.Provider,{value:i,children:e.options.disableGlobalCatchBoundary?a:(0,X.jsx)(oP,{getResetKey:()=>r,onCatch:void 0,children:a})})}var jF=e=>({createMutableStore:NP,createReadonlyStore:NP,batch:AP}),MF=e=>new NF(e),NF=class extends rN{constructor(e){super(e,jF)}};function PF({router:e,children:t,...n}){fj(n)&&e.update({...e.options,...n,context:{...e.options.context,...n.context}});let r=(0,X.jsx)(fP.Provider,{value:e,children:t});return e.options.Wrap?(0,X.jsx)(e.options.Wrap,{children:r}):r}function FF({router:e,...t}){return(0,X.jsx)(PF,{router:e,...t,children:(0,X.jsx)(kF,{})})}function IF(e){let t=pP({warn:e?.router===void 0}),n=e?.router||t;return BP(n.stores.__store,HP(e,n))}function LF(){return BP(pP().stores.location,e=>e.state.__TSR_index!==0)}var RF=(0,J.createContext)(null),zF=RF.Provider,BF=hF({validateSearch:Kr({agent:Fi().min(1).optional()}),component:()=>null}),VF=pF({getParentRoute:()=>BF,path:`/`}),HF=Kr({agentId:Fi().min(1),sessionId:Fi().min(1)}),UF=pF({getParentRoute:()=>BF,path:`/sessions/$agentId/$sessionId`,params:{parse:e=>HF.parse(e)}});function WF(){return MF({routeTree:BF.addChildren([VF,UF]),history:YM(),InnerWrap:({children:e})=>(0,X.jsxs)(X.Fragment,{children:[(0,J.useContext)(RF),e]}),defaultPendingMs:0,defaultPendingMinMs:0})}function GF(e){let t=e.state.matches.find(e=>e.routeId===UF.id),n=HF.safeParse(t?.params);return n.success?n.data:null}function KF(e,t){let n=IF({router:e,select:e=>e.location.search}),r=UP({from:UF.id,shouldThrow:!1});_h(t,{canGoBack:LF(),canGoForward:!1,onForward:()=>!1,onBack:()=>e.history.canGoBack()?(e.history.back(),!0):!1});let i=(0,J.useCallback)(t=>{e.navigate({to:`.`,search:{agent:t??void 0},replace:!0})},[e]),a=(0,J.useCallback)((t,n)=>e.navigate({to:`/sessions/$agentId/$sessionId`,params:{agentId:t,sessionId:n},search:!0}),[e]);return{agentFilterId:n.agent??null,setFilter:i,selection:r?.params,open:a}}var qF=Ja.check(q(1,{message:`Give your Agent a name.`}),U(256,{message:`Use at most 256 characters.`}));function JF({agentId:e,name:t,rename:n}){let[r,i]=(0,J.useState)(!1),a=SA({schema:(0,J.useMemo)(()=>F({name:qF.annotate(Jk({label:`Agent name`,render:e=>(0,X.jsx)(He,{id:e.id,name:e.name,"aria-label":`Agent name`,"aria-invalid":e[`aria-invalid`],"aria-describedby":e[`aria-describedby`],autoFocus:!0,maxLength:256,disabled:e.disabled,value:e.value,onBlur:e.onBlur,onChange:t=>{e.onChange(t.currentTarget.value)}})}))}),[]),defaultValues:{name:t},onSubmit:async({name:r})=>r===t||await n(e,r)?(i(!1),{kind:`saved`,values:{name:r}}):{kind:`refused`}}),{submitting:o,canSubmit:s}=CA(a);return r?(0,X.jsxs)(EA,{model:a,"aria-label":`Rename Agent`,footer:null,className:`flex min-w-0 items-center gap-1`,children:[(0,X.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,X.jsx)(Uk,{model:a,names:[`name`]})}),(0,X.jsx)(c,{type:`submit`,size:`sm`,loading:o,disabled:o||!s,children:`Save`}),(0,X.jsx)(We,{"aria-label":`Cancel rename`,type:`button`,icon:(0,X.jsx)(on,{size:14,"aria-hidden":`true`}),onClick:()=>{i(!1)}})]}):(0,X.jsx)(We,{"aria-label":`Rename Agent`,icon:(0,X.jsx)(mE,{size:14,"aria-hidden":`true`}),onClick:()=>{i(!0)}})}function YF({status:e,approving:t,onApprove:n}){return e?.status===`pending`?(0,X.jsx)(c,{variant:`outline`,size:`sm`,className:`flex-none`,loading:t,disabled:t,onClick:n,children:`Allow App tools`}):null}var XF=F({text:I}),ZF=Xe(structuredClone(ya(XF,{onExcessProperty:`error`}).schema));function QF(e){return[{id:`new-conversation`,title:`New conversation`,category:`Conversation`,description:`Start a new conversation with this Agent`,projections:{slash:{aliases:[`new`],order:20},palette:{}},handler:()=>{e().newConversation()}},{id:`permissions`,title:`App permissions`,category:`Conversation`,description:`Review what Grove may access`,projections:{slash:{aliases:[`permissions`],order:21},palette:{}},handler:()=>{e().openPermissions()}},{id:`set-draft`,title:`Set draft`,category:`Conversation`,description:`Replace the open writable Grove conversation's draft without sending it`,projections:{agent:{}},action:{inputSchema:ZF,presentation:{type:`action`}},handler:({arguments:t})=>{let{text:n}=R(XF,{onExcessProperty:`error`})(t);return{accepted:e().setDraft(n)}}}]}function $F(e,t){let n=(0,J.useRef)(e);n.current=e;let r=(0,J.useMemo)(()=>QF(()=>n.current),[]),i=(0,J.useMemo)(()=>Ae(),[]);return(0,J.useEffect)(()=>{let e=i.contribute({sourceId:`grove`,namespace:`grove`,commands:r});return()=>{e.dispose()}},[r,i]),(0,J.useEffect)(()=>t?Po(t,r):void 0,[r,t]),i}var eI=Ti(Yr({providerId:Fi().min(1).max(256),providerName:Fi().min(1).max(256),id:Fi().min(1).max(256),name:Fi().min(1).max(256),reasoning:Ti(Wr(Wi)).max(6).readonly()})).max(1024).readonly();async function tI(e,t,n,r=sg){if(!e.has(tg))throw Error(`Agent read authority is unavailable`);let i=await r(e,{agentId:t});try{let e=await i.fetch(new Request(`${i.baseUrl}/models`,{signal:n}));if(!e.ok)throw Error(`Agent model catalog is unavailable`);return eI.parse(await e.json())}finally{await i.close()}}function nI(e){let t=tn(),n=e?.capabilities.has(tg)===!0||e?.capabilities.has(ng)===!0,r=Sy(n?e:null),i=e&&!n?{...r,status:`live`}:r,a=vy.of(e,`agents`),o=is({...xy(e,Rh,a,e=>e.list()),enabled:e?.capabilities.has(Rh)===!0}),{refetch:s}=o,c=(0,J.useRef)(null);(0,J.useEffect)(()=>{if(e===null||!o.isSuccess||i.status!==`live`)return;let t=i.items.filter(e=>!(`kind`in e));if(t.length===0)return;let n=JSON.stringify(t.map(e=>[e.agentId,e.sessionId,e.state,`lastActivityAt`in e?e.lastActivityAt:null])),r=c.current?.app===e&&c.current.key!==n;c.current={app:e,key:n};let a=new Set(o.data.map(e=>e.agentId));(r||t.some(e=>!a.has(e.agentId)))&&s()},[e,o.isSuccess,o.data,i.status,i.items,s]);let l=vy.of(e,`agent-computers`);return{directory:o,inbox:i,computerChoices:is({...xy(e,zh,l,()=>{if(!e)throw Error(`No App connection`);return ig(e.capabilities)}),enabled:e?.capabilities.has(zh)===!0}),createAgent:as({mutationFn:t=>{if(!e)throw Error(`No App connection`);return rg(e.capabilities,t)},onMutate:()=>({directoryKey:a}),onSettled:(e,n,r)=>{r.computer===`new`&&t.invalidateQueries({queryKey:l})},onSuccess:(e,n,r)=>{t.setQueryData(r.directoryKey,(t=[])=>t.some(t=>t.agentId===e.agentId)?t:[...t,e])}}),renameAgent:as({mutationFn:t=>{if(!e)throw Error(`No App connection`);return Hh(e.capabilities,t)},onSuccess:e=>{t.setQueryData(a,(t=[])=>t.map(t=>t.agentId===e.agentId?e:t))}}),setAgentAvatar:as({mutationFn:t=>{if(!e)throw Error(`No App connection`);return Gh(e.capabilities,t)},onSuccess:e=>{t.setQueryData(a,(t=[])=>t.map(t=>t.agentId===e.agentId?e:t))}})}}function rI(e,t){let n=tn(),r=e?.capabilities.has(eg)===!0,i=vy.of(e,`agent-tool-policy`,t??`none`);return{canRead:r,status:is({...xy(e,eg,i,e=>t===null?Promise.resolve(null):e.status({agentId:t})),enabled:r&&t!==null}),approve:as({mutationFn:t=>{if(!e)throw Error(`No App connection`);return e.capabilities.require(eg).approve({agentId:t.agentId,level:`write`,expectedRevision:t.expectedRevision})},onSuccess:e=>{`error`in e||n.setQueryData(i,e)}})}}function iI(e,t){let n=tn(),r=e?.capabilities.has(Yh)===!0;return{canUse:r,read:is({...xy(e,Yh,vy.of(e,`agent-instructions`,t??`none`),()=>{if(!e||t===null)throw Error(`No Agent is open`);return Xh(e.capabilities,t)}),enabled:r&&t!==null}),save:as({mutationFn:t=>{if(!e)throw Error(`No App connection`);return Zh(e.capabilities,t)},onSuccess:t=>{n.setQueryData(vy.of(e,`agent-instructions`,t.agentId),t)}})}}var aI=new Set([`Enter`,` `]),oI=(0,J.forwardRef)(function({children:e,onConfirm:t,holdMs:n=900,holdHint:r=`Press and hold to confirm.`,className:i,disabled:a,loading:o=!1,result:s,resultLabel:l,onBlur:u,onKeyDown:d,onKeyUp:f,onPointerDown:p,onPointerUp:m,onPointerLeave:h,onPointerCancel:g,..._},v){let y=(0,J.useRef)(null),b=(0,J.useRef)(null),x=(0,J.useRef)(null),S=(0,J.useRef)(null),C=(0,J.useRef)(t),w=(0,J.useId)();(0,J.useEffect)(()=>{C.current=t},[t]),(0,J.useEffect)(()=>()=>{b.current?.cancel(),x.current!==null&&clearTimeout(x.current)},[]);let T=()=>{b.current=null,x.current=null,S.current=null,C.current();let e=y.current;if(!e||!he(e))return;let t=dr(e);e.animate([{opacity:1},{opacity:0}],{duration:t.normal,easing:Be(t,t.easeExit)})},E=e=>{let t=y.current;if(a===!0||o||!t||b.current||x.current)return;if(S.current=e,!he(t)){x.current=setTimeout(T,n);return}let r=dr(t),i=t.animate([{transform:`scaleY(0)`},{transform:`scaleY(1)`}],{duration:n,easing:r.reduced?`steps(3, end)`:Be(r,`cubic-bezier(0.3, 0, 0.7, 1)`)});i.addEventListener(`finish`,T),b.current=i},D=e=>{if(e!==void 0&&S.current!==e)return;S.current=null,x.current!==null&&(clearTimeout(x.current),x.current=null);let t=b.current,n=y.current;if(!t||!n)return;b.current=null;let r=getComputedStyle(n).transform;t.cancel();let i=dr(n);n.animate([{transform:r===`none`?`scaleY(0)`:r},{transform:`scaleY(0)`}],{duration:i.fast,easing:Be(i,i.ease)})};return(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(c,{..._,ref:v,disabled:a,loading:o,result:s,resultLabel:l??(s===void 0?void 0:e),"aria-describedby":w,className:ft(`caps-hold-button`,i),onBlur:e=>{D(),u?.(e)},onPointerDown:e=>{p?.(e),e.button===0&&E(e.pointerId)},onPointerUp:e=>{m?.(e),D(e.pointerId)},onPointerLeave:e=>{h?.(e),D(e.pointerId)},onPointerCancel:e=>{g?.(e),D(e.pointerId)},onKeyDown:e=>{d?.(e),e.key===`Escape`&&D(),aI.has(e.key)&&(e.preventDefault(),e.repeat||E(`key`))},onKeyUp:e=>{f?.(e),aI.has(e.key)&&(e.preventDefault(),D(`key`))},children:[(0,X.jsx)(`span`,{ref:y,"aria-hidden":`true`,className:`caps-hold-fill`}),e]}),(0,X.jsx)(se,{id:w,children:r})]})});function sI({label:e,confirmLabel:t,onConfirm:n,error:r,variant:i=`destructive`,size:a,mode:o,phrase:s}){let[l,d]=(0,J.useState)(!1),[f,p]=(0,J.useState)(``),[m,h]=(0,J.useState)(`idle`),g=(0,J.useRef)(!1),_=(0,J.useRef)(null),v=m===`busy`,y=o===`hold`||s.length>0&&f===s,b=v?void 0:r!==void 0&&r!==``?r:m instanceof Error?m.message:void 0,x=b?`failed`:m===`done`?`done`:void 0;async function S(){if(!(g.current||!y)){g.current=!0,h(`busy`);try{await n(),h(`done`),d(!1),p(``)}catch(e){h(Error(`Could not confirm the action. Try again.`,{cause:e}))}finally{g.current=!1}}}return o===`hold`?(0,X.jsxs)(`div`,{className:`grid gap-sm`,children:[(0,X.jsx)(oI,{variant:i,...a===void 0?{}:{size:a},loading:v,result:x,holdHint:t,onConfirm:()=>void S(),children:e}),(0,X.jsx)(Ot,{children:b})]}):(0,X.jsxs)(ke,{open:l,onOpenChange:(e,t)=>{if(g.current){t.cancel();return}d(e),p(``),h(`idle`)},children:[(0,X.jsx)(it,{render:(0,X.jsx)(c,{variant:i,...a===void 0?{}:{size:a}}),children:e}),(0,X.jsx)(P,{initialFocus:_,children:(0,X.jsxs)(Kn,{busy:v,onSubmit:e=>{e.preventDefault(),S()},children:[(0,X.jsxs)(u,{children:[(0,X.jsx)(Ye,{children:e}),(0,X.jsx)(Re,{children:`Type the phrase exactly to confirm.`})]}),(0,X.jsx)(Rn,{label:`Type ${s} to confirm`,children:(0,X.jsx)(He,{ref:_,autoComplete:`off`,autoCapitalize:`none`,spellCheck:!1,value:f,onChange:e=>{p(e.currentTarget.value)}})}),(0,X.jsxs)(jt,{error:b,children:[(0,X.jsx)(ae,{render:(0,X.jsx)(c,{variant:`ghost`}),disabled:v,children:`Cancel`}),(0,X.jsx)(c,{type:`submit`,variant:`destructive`,disabled:!y,loading:v,result:x,children:t})]})]})})]})}function cI(e){return`# ${e}'s instructions\n\nWrite what ${e} should do in every conversation, in plain language.\n\n- Keep replies short.\n`}var lI=new TextEncoder,uI=e=>e.toLocaleString(`en-US`),dI=.8,fI=`No Home Computer. An Agent gets one when it is created with a Computer; with several, choose one in a conversation with /home <name>.`;function pI({agentId:e,name:t,file:n,loading:r,save:i,reload:a,notify:o}){let[s,l]=(0,J.useState)(null),[d,f]=(0,J.useState)(null),[p,m]=(0,J.useState)(!1),[h,g]=(0,J.useState)(!1),_=(0,J.useId)(),v=n?.limit??0,y=lI.encode(s??``).byteLength,b=s!==null&&y>v,x=b||y>=v*dI,S=s===(d??``),C=n?.home===null,w=e=>{g(!1),f(e.content),l(e.content??``)},T=async()=>{try{w(await a())}catch(e){console.error(`Instructions reload failed`,e),o(`Couldn't reload this file. Try again.`,`error`)}};return(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(MC,{children:[(0,X.jsx)(NC,{asChild:!0,children:(0,X.jsx)(We,{"aria-label":`Instructions`,"aria-haspopup":C?void 0:`dialog`,className:C?`opacity-40`:void 0,icon:(0,X.jsx)(fE,{size:14,"aria-hidden":`true`}),disabled:r||n===void 0,onClick:()=>{n!==void 0&&(C?o(fI,`warning`):w(n))}})}),(0,X.jsx)(PC,{children:C?fI:`Instructions`})]}),(0,X.jsx)(ke,{open:s!==null,onOpenChange:e=>{!e&&!p&&l(null)},children:(0,X.jsxs)(P,{className:`flex flex-col gap-lg`,keepMounted:!1,forceBackdrop:!0,children:[(0,X.jsxs)(u,{children:[(0,X.jsxs)(Ye,{children:[t,`'s instructions`]}),(0,X.jsxs)(Re,{children:[t,` follows these at the start of every conversation, and can update them as it learns.`]}),n?.home?(0,X.jsxs)(`p`,{className:`text-xs text-base-content/70`,children:[`Saved as AGENTS.md on `,n.home.name,`. Other Agents that use`,` `,n.home.name,` read it too.`]}):null]}),(0,X.jsxs)(`div`,{className:`grid gap-xs`,children:[(0,X.jsx)(`label`,{htmlFor:_,className:`text-sm font-medium`,children:`Instructions`}),(0,X.jsx)($n,{id:_,rows:14,className:`font-mono text-sm`,value:s??``,invalid:b,disabled:p,placeholder:cI(t),onChange:e=>{l(e.currentTarget.value)}}),x?(0,X.jsxs)(`p`,{className:`text-xs ${b?`text-error`:`text-base-content/70`}`,role:b?`alert`:void 0,children:[s!==null&&y!==s.length?`About `:``,uI(y),` of `,uI(v),` characters`,b?`. Shorten it to save.`:``]}):null]}),(0,X.jsxs)(lr,{children:[(0,X.jsx)(c,{type:`button`,variant:`ghost`,disabled:p,onClick:()=>{l(null)},children:`Cancel`}),h?s===(d??``)?(0,X.jsx)(c,{type:`button`,variant:`primary`,onClick:()=>{T()},children:`Reload`}):(0,X.jsx)(sI,{mode:`hold`,variant:`primary`,label:`Hold to reload`,confirmLabel:`Hold to reload and lose your edits`,onConfirm:T}):(0,X.jsx)(c,{type:`button`,variant:`primary`,loading:p,disabled:p||s===null||b||S,onClick:()=>{s!==null&&(m(!0),i(e,{expectedContent:d,content:s}).then(e=>{m(!1),e===`saved`?l(null):e===`conflict`?(g(!0),o(`${t} changed this file. Reload to see it.`,`warning`)):o(e===`too_large`?`That file is too large to save.`:`The instructions could not be saved. Try again.`,`error`)}))},children:`Save`})]})]})})]})}function mI({agentId:e,name:t,avatar:n,setAvatar:r}){let[i,a]=(0,J.useState)(null),[o,s]=(0,J.useState)(!1),l=(0,X.jsx)(gn,{avatar:n,name:t,size:24});return r===void 0?(0,X.jsx)(`span`,{className:`flex-none`,children:l}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(c,{variant:`ghost`,size:`sm`,"aria-label":`Change avatar`,className:`flex-none p-0`,onClick:()=>{a(n)},children:l}),(0,X.jsx)(ke,{open:i!==null,onOpenChange:e=>{!e&&!o&&a(null)},children:(0,X.jsxs)(P,{className:`flex flex-col gap-lg`,keepMounted:!1,children:[(0,X.jsxs)(u,{children:[(0,X.jsxs)(Ye,{children:[t,`'s avatar`]}),(0,X.jsxs)(Re,{children:[`Every conversation with `,t,` shows this look.`]})]}),i===null?null:(0,X.jsx)(KA,{value:i,disabled:o,onChange:a}),(0,X.jsxs)(lr,{children:[(0,X.jsx)(c,{type:`button`,variant:`ghost`,disabled:o,onClick:()=>{a(null)},children:`Cancel`}),(0,X.jsx)(c,{type:`button`,variant:`primary`,loading:o,disabled:o||i===null,onClick:()=>{i!==null&&(s(!0),r(e,i).then(e=>{s(!1),e&&a(null)}))},children:`Save`})]})]})})]})}var hI=(0,J.forwardRef)(function({className:e,orientation:t,variant:n=`grip`,value:r,min:i,max:a,onValueChange:o,onKeyDown:s,...c},l){return(0,X.jsx)(`div`,{...c,ref:l,className:ft(`caps-resize-handle`,e),"data-resize-variant":n,role:`separator`,"aria-orientation":t,"aria-valuemin":Math.round(i),"aria-valuemax":Math.round(a),"aria-valuenow":Math.round(r),tabIndex:c.tabIndex??0,onKeyDown:e=>{if(s?.(e),e.defaultPrevented)return;if(e.key===`Home`||e.key===`End`){e.preventDefault(),o(e.key===`Home`?i:a);return}let n=t===`horizontal`?e.key===`ArrowUp`?-32:e.key===`ArrowDown`?32:null:e.key===`ArrowLeft`?-32:e.key===`ArrowRight`?32:null;n!==null&&(e.preventDefault(),o(Math.min(a,Math.max(i,r+n))))},children:(0,X.jsx)(`span`,{className:`caps-resize-grip`,"aria-hidden":`true`})})});T({frames:new Map,order:[],tiles:[],minima:new Map,participating:new Set,mainSize:void 0,zoomed:null,gesture:null,restore:new Map});function gI(e,t=!0,n){let r=(0,J.useRef)(e);r.current=e;let i=(0,J.useRef)(null);return(0,J.useEffect)(()=>(t||i.current?.release(!0),()=>i.current?.release(!0)),[t]),(0,J.useEffect)(()=>{let e=()=>{i.current?.release(!0)};return n?.addEventListener(`abort`,e),()=>{n?.removeEventListener(`abort`,e)}},[n]),{onPointerDown:e=>{if(!t||n?.aborted||i.current||e.pointerType===`mouse`&&e.button!==0)return;let{currentTarget:a,pointerId:o}=e;if(a.setPointerCapture(o),!r.current.begin(e)){a.releasePointerCapture(o);return}let s=r.current.end,c=()=>{l(!0)},l=e=>{a.removeEventListener(`lostpointercapture`,c),i.current=null,s(e),a.hasPointerCapture(o)&&a.releasePointerCapture(o)};i.current={id:o,element:a,x:e.clientX,y:e.clientY,release:l},a.addEventListener(`lostpointercapture`,c)},onPointerMove:e=>{let t=i.current;t?.id===e.pointerId&&(r.current.move(e.clientX-t.x,e.clientY-t.y,e),t.x=e.clientX,t.y=e.clientY)},onPointerUp:e=>{i.current?.id===e.pointerId&&i.current.release(!1)},onPointerCancel:e=>{i.current?.id===e.pointerId&&i.current.release(!0)}}}(0,J.createContext)(null);var _I=(0,J.createContext)(null);(0,J.forwardRef)(function({layer:e,style:t,children:n,...r},i){let a=(0,J.useContext)(_I),o=a?.update,s=a?.roots.get(`dialog`),[c,l]=(0,J.useState)(!1);(0,J.useEffect)(()=>{if(!s)return;let e=()=>{l(Array.from(s.querySelectorAll(`*`)).some(e=>{let t=e.getBoundingClientRect();return t.width>0&&t.height>0}))};e();let t=new MutationObserver(e);return t.observe(s,{childList:!0,subtree:!0,attributes:!0}),()=>{t.disconnect()}},[s]);let u=(0,J.useRef)(null);(0,J.useImperativeHandle)(i,()=>u.current);let d=(0,J.useCallback)(t=>{u.current=t,o?.(e,t)},[o,e]);return(0,J.createElement)(`div`,{...r,ref:d,onFocusCapture:t=>{e===`windows`&&t.target instanceof Node&&t.currentTarget.contains(t.target)&&a?.dismiss?.(),r.onFocusCapture?.(t)},"data-maosaico-layer":e,inert:e===`windows`&&c?``:void 0,style:{position:`relative`,...t,isolation:`isolate`,zIndex:`var(--stipe-layer-${e})`}},n)});var vI={min:224,max:480,initial:320},yI={agentRailOpen:!0,listRailOpen:!0,listWidth:vI.initial},bI=`layout`,xI=xa(F({agentRailOpen:vo,listRailOpen:vo,listWidth:bo.pipe(B(Xa()))}));function SI(e){return Math.round(Math.min(vI.max,Math.max(vI.min,e)))}async function CI(e){let t=await e.read(bI),n=xI(t.member?.value);return{layout:Oi(n)?{...n.value,listWidth:SI(n.value.listWidth)}:yI,revision:t.member?.revision??null}}async function wI(e,t,n){let{revision:r}=await e.write({key:bI,scope:`member`,basedOn:n,value:t});return r}function TI(e){let[t,n]=(0,J.useState)(yI),r=(0,J.useRef)(null),i=(0,J.useRef)(!1),a=(0,J.useRef)(!1);return(0,J.useEffect)(()=>{if(e===void 0)return;let t=!1;return CI(e).then(e=>{t||(r.current=e.revision,i.current=!0,a.current||n(e.layout))},e=>{console.warn(`Grove could not read its saved rail layout`,e),i.current=!0}),()=>{t=!0}},[e]),(0,J.useEffect)(()=>{e===void 0||!a.current||!i.current||wI(e,t,r.current).then(e=>{r.current=e},e=>{console.warn(`Grove could not save its rail layout`,e)})},[e,t]),[t,(0,J.useCallback)(e=>{a.current=!0,n(e)},[])]}var EI=8e3,DI=(0,J.forwardRef)(function({className:e,detail:t,framed:n=!0,icon:r,message:i,onRetry:a,size:o=`md`,slowAfterMs:s=EI,variant:l=`line`,...u},d){let[f,p]=(0,J.useState)(!1);return(0,J.useEffect)(()=>{if(p(!1),!Number.isFinite(s))return;let e=globalThis.setTimeout(()=>{p(!0)},s);return()=>{globalThis.clearTimeout(e)}},[s,i]),(0,X.jsxs)(`div`,{...u,className:ft(`caps-loading-state`,e),"data-framed":n?void 0:`false`,"data-icon":r?``:void 0,"data-size":o,"data-slow":f||void 0,ref:d,role:`status`,children:[r?(0,X.jsx)(`span`,{"aria-hidden":`true`,className:`caps-loading-state-icon`,children:r}):null,(0,X.jsx)(rn,{decorative:!0,size:o,variant:l}),(0,X.jsxs)(`span`,{className:`caps-loading-state-copy`,children:[(0,X.jsx)(`span`,{children:i}),t?(0,X.jsx)(`span`,{className:`caps-loading-state-detail`,children:t}):null,f?(0,X.jsx)(`span`,{className:`caps-loading-state-detail`,children:`Still working…`}):null]}),f&&a?(0,X.jsx)(c,{className:`caps-loading-state-retry`,size:`sm`,variant:`outline`,onClick:a,children:`Retry`}):null]})}),OI=[{title:`Add your key`,detail:`Choose your provider in Model keys. Your key stays private.`},{title:`Come back and ask`,detail:`Close Settings to return here. Start with a question or a short writing task.`},{title:`Pick up where you left off`,detail:`Find your conversations in Grove and your desktop Inbox.`}];function kI({connection:e,navigation:t}){let[n,r]=(0,J.useState)(!1),[i,a]=(0,J.useState)(!1),o=async()=>{r(!1),a(!0);try{r(await e.ui.openSetup(`model`)!==`opened`)}catch(e){console.error(`Grove could not open model setup`,e),r(!0)}finally{a(!1)}};return(0,X.jsxs)(`section`,{className:`inbox-empty @container m-auto flex max-h-full min-h-0 w-full max-w-3xl flex-col gap-xl overflow-y-auto px-lg py-xl`,"aria-label":`Get started with Grove`,children:[(0,X.jsx)(mt,{variant:`panel`,title:`Connect a model to start chatting`,description:`An Agent is an AI helper that writes, thinks through ideas and works with your Apps. A model powers its replies: connect Cloudflare Workers AI, or bring a key from your own model provider.`,visual:(0,X.jsx)(`span`,{className:`block`,style:{width:`3.5rem`,height:`3.5rem`},children:(0,X.jsx)(vE,{className:`h-full w-full`,state:{activity:`idle`,expression:`normal`}})}),primaryAction:{label:i?`Opening Model keys…`:`Add a model key`,onSelect:()=>void o(),pending:i}}),t?(0,X.jsx)(c,{variant:`outline`,className:`self-center`,"aria-haspopup":`dialog`,"aria-controls":`grove-nav`,"aria-expanded":t.open,onClick:t.onOpen,children:`Agents and conversations`}):null,n?(0,X.jsx)(Pe,{role:`alert`,message:`Model keys could not open. Try opening them again.`,onRetry:()=>void o(),onDismiss:()=>{r(!1)}}):null,(0,X.jsx)(`ol`,{className:`m-0 grid list-none gap-lg p-0 text-sm @xl:grid-cols-3`,children:OI.map((e,t)=>(0,X.jsxs)(`li`,{className:`flex flex-col gap-xs border-t border-base-300 pt-md`,children:[(0,X.jsxs)(`strong`,{className:`font-semibold`,children:[String(t+1),`. `,e.title]}),(0,X.jsx)(`span`,{className:`text-(--stipe-fg-muted)`,children:e.detail})]},e.title))})]})}var AI=[`Make me a tiny game where a mushroom catches raindrops.`,`Write a short poem about a rainy morning.`,`What can you help me with?`];function jI({description:e,icon:t,label:n,density:r=`regular`,appearance:i=`plain`,iconSize:a=`default`,size:o,trailing:s,...l}){return(0,X.jsxs)(c,{...l,className:ft(`caps-action-row`,i===`card`&&`caps-action-row-card`,r===`compact`?`h-auto min-h-10 w-full justify-start gap-xs px-xs py-2xs text-left`:`h-auto min-h-14 w-full justify-start gap-sm px-sm py-xs text-left`,l.className),size:o??(r===`compact`?`default`:`lg`),variant:l.variant??`ghost`,children:[t?(0,X.jsx)(`span`,{className:r===`compact`?`grid ${a===`lg`?`size-8`:`size-7`} shrink-0 place-items-center [&_:is(svg,.caps-monogram)]:size-5`:`grid ${a===`lg`?`size-12`:`size-10`} shrink-0 place-items-center [&_:is(svg,.caps-monogram)]:size-7`,children:t}):null,(0,X.jsxs)(`span`,{className:`caps-action-row-copy`,children:[(0,X.jsx)(`span`,{className:`caps-action-row-label max-w-full truncate`,children:n}),e?(0,X.jsx)(`span`,{className:`caps-action-row-description max-w-full truncate`,children:e}):null]}),s?(0,X.jsx)(`span`,{className:`caps-action-row-trailing`,children:s}):null]})}function MI(e,t,n,r,i,a){let o=[];r&&o.push({kind:`hint`,key:`loading`,loading:!0});let s=0,c=ME(e),l=new Map(c.map(e=>[NE(e.agentId,e.sessionId),e]));for(let e of[`Needs you`,`Working`,`Ready`,`Finished`]){let n=t.flatMap(t=>{let n=l.get(t.key),r=n?.state===`errored`?`Needs you`:t.shelf;return n===void 0||r!==e?[]:[n]});if(n.length!==0){o.push({kind:`heading`,key:e,title:e,gap:s++>0});for(let t of n)o.push({kind:`session`,key:NE(t.agentId,t.sessionId),shelf:e,session:t})}}if(e.unavailable.length>0){o.push({kind:`heading`,key:`Unavailable`,title:`Unavailable`,gap:s>0});for(let t of e.unavailable)o.push({kind:`unavailable`,key:NE(t.agentId,t.sessionId),session:t})}if(n.length>0){o.push({kind:`heading`,key:`Websites`,title:`Websites`,gap:o.length>0});for(let e of n)o.push({kind:`website`,key:`website:${e.bindingId}:${e.conversation.sessionId}`,website:e})}return o.length===0&&!i&&a&&o.push({kind:`hint`,key:`empty`,loading:!1}),o}function NI({viewport:e,view:t,agents:r,loading:i,failed:a,showEmptyState:o,pendingSelection:s,selectedAgentId:c,selectedSessionId:l,onSelect:u,onDelete:d,deleting:f,websites:p,selectedWebsite:m,onSelectWebsite:h}){let g=c!==null&&l!==null?NE(c,l):null,[v,y]=(0,J.useState)(!1),[b,x]=(0,J.useState)(!1),S=v||b,[C,w]=(0,J.useState)(0),[T,E]=(0,J.useState)({placements:null,openKey:g,reopened:C}),D=(0,J.useMemo)(()=>OE(T.placements,[...t.active,...t.settled],{openKey:T.openKey===g?g:null,held:S,reorder:T.openKey!==g||T.reopened!==C}),[T,t,g,S,C]);(0,J.useEffect)(()=>{!S&&(T.placements!==D||T.openKey!==g||T.reopened!==C)&&E({placements:D,openKey:g,reopened:C})},[S,T,D,g,C]),(0,J.useEffect)(()=>{let t=e.current;if(t===null)return;let n=t.clientWidth>0&&t.clientHeight>0,r=`ResizeObserver`in globalThis?new ResizeObserver(([e])=>{let t=e.contentRect.width>0&&e.contentRect.height>0;t&&!n&&w(e=>e+1),n=t}):void 0;r?.observe(t);let i=()=>{document.visibilityState===`visible`&&w(e=>e+1)};return document.addEventListener(`visibilitychange`,i),()=>{r?.disconnect(),document.removeEventListener(`visibilitychange`,i)}},[e]);let O=(0,J.useMemo)(()=>MI(t,D,p,i,a,o),[t,D,p,i,a,o]),k=(0,J.useCallback)(e=>O[e]?.key??e,[O]),A=_({count:O.length,getScrollElement:()=>e.current,getItemKey:k,estimateSize:e=>O[e]?.kind===`heading`?24:44,measureElement:(e,t,n)=>{let r=Ee(e,t,n);return r>0?r:Ee(e,void 0,n)||n.options.estimateSize(n.indexFromElement(e))},initialRect:{width:320,height:800},overscan:5,useFlushSync:!1});return(0,X.jsx)(`div`,{className:`inbox-list px-1 py-1`,onPointerEnter:()=>{y(!0)},onPointerLeave:()=>{y(!1)},onFocusCapture:()=>{x(!0)},onBlurCapture:e=>{e.currentTarget.contains(e.relatedTarget)||x(!1)},children:(0,X.jsx)(`div`,{style:{height:A.getTotalSize(),position:`relative`,width:`100%`},children:A.getVirtualItems().map(e=>{let t=O[e.index],i=t.kind===`session`||t.kind===`unavailable`?t.session:null,a=i?r.get(i.agentId):void 0;return(0,X.jsx)(`div`,{"data-index":e.index,ref:A.measureElement,"data-inbox-shelf":t.kind===`session`?t.shelf:t.kind===`unavailable`?`Unavailable`:void 0,className:t.kind===`heading`?`inbox-shelf`:void 0,style:{position:`absolute`,top:0,left:0,width:`100%`,transform:`translateY(${String(e.start)}px)`,paddingTop:t.kind===`heading`&&t.gap?4:0},children:t.kind===`heading`?(0,X.jsx)(Yn,{style:{paddingBottom:0},children:t.title}):t.kind===`hint`?t.loading?(0,X.jsx)(DI,{className:`inbox-empty px-2 py-3 text-sm text-(--stipe-fg-muted)`,message:`Loading conversations…`}):(0,X.jsx)(`p`,{className:`m-0 px-2 py-3 text-xs text-(--stipe-fg-muted)`,children:`Conversations you start with Agents appear here.`}):t.kind===`website`?(0,X.jsx)(jI,{appearance:`plain`,density:`compact`,className:`inbox-row${m?.bindingId===t.website.bindingId&&m.conversation.sessionId===t.website.conversation.sessionId?` is-selected bg-base-300`:``}`,"data-testid":`inbox-website-row`,label:t.website.conversation.label||`Website visitor`,description:(0,X.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[(0,X.jsx)(xn,{name:`internet`,size:14}),t.website.siteLabel]}),trailing:t.website.conversation.held?(0,X.jsx)(`span`,{className:`text-xs`,children:t.website.conversation.heldByYou?`You're replying`:`With a teammate`}):t.website.conversation.needsYou?(0,X.jsx)(n,{size:`compact`,tone:`accent`,title:t.website.conversation.needsYou.reason}):null,onClick:()=>{h(t.website)},variant:`ghost`}):t.kind===`unavailable`?a?(0,X.jsx)(FI,{agent:a,row:t.session}):null:a?(0,X.jsx)(PI,{agent:a,session:t.session,attention:t.session.unseen,pending:s?.agentId===t.session.agentId&&s.sessionId===t.session.sessionId,selected:c===t.session.agentId&&l===t.session.sessionId,onDelete:d&&a.sessionOperations.includes(`agent.manage`)?()=>{d(t.session.agentId,t.session.sessionId)}:void 0,deleting:f?.agentId===t.session.agentId&&f.sessionId===t.session.sessionId,onSelect:()=>{u(t.session.agentId,t.session.sessionId)}}):null},e.key)})})})}function PI({agent:e,session:t,attention:r,pending:i,selected:a,onSelect:o,onDelete:s,deleting:c}){let l=xE(t.state),u=t.state===`errored`,d=(0,X.jsxs)(`span`,{className:`inbox-row-activity inline-grid shrink-0 grid-cols-[1rem_7ch] items-center gap-1.5 text-[0.6875rem]`,children:[(0,X.jsxs)(`span`,{className:`inbox-row-status flex items-center justify-center`,children:[i||l||u?(0,X.jsx)(`span`,{className:`sr-only`,children:i?`Opening`:yE[t.state]}):null,i||l?(0,X.jsx)(n,{size:`compact`,title:i?`Opening`:yE[t.state],motion:t.state===`running`||i?`pulse`:`none`,tone:i?`neutral`:t.state===`needs_you`?`accent`:`info`}):u?(0,X.jsx)(n,{size:`compact`,title:yE.errored,tone:`error`}):r?(0,X.jsx)(n,{size:`compact`,title:`Finished since your last visit`,tone:`neutral`}):null]}),(0,X.jsx)(`time`,{className:`inbox-row-age min-w-0 truncate text-right tabular-nums text-(--stipe-fg-muted)`,dateTime:new Date(t.lastActivityAt).toISOString(),children:II(t.lastActivityAt)})]});return(0,X.jsxs)(`div`,{className:`relative group`,children:[(0,X.jsx)(jI,{"aria-current":a?`page`:void 0,"aria-label":`${t.title||`New conversation`} — ${PE(e)}${r?` — Finished since your last visit`:``}${t.ready?` — Ready`:l||u?` — ${yE[t.state]}`:``}`,"aria-busy":i||void 0,appearance:`plain`,className:`inbox-row pr-9${a?` is-selected bg-base-300`:``}`,"data-attention":r?`true`:`false`,"data-pending":i?`true`:`false`,"data-session-id":t.sessionId,"data-status":t.state,"data-testid":`inbox-session-row`,density:`compact`,description:PE(e),label:t.title||`New conversation`,onClick:o,trailing:d,variant:`ghost`}),s?(0,X.jsx)(We,{"aria-label":`Delete conversation ${t.title||`New conversation`}`,title:`Delete conversation`,icon:(0,X.jsx)(_E,{}),iconSize:`sm`,size:`sm`,className:`absolute right-1 top-1/2 -translate-y-1/2 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 @max-[899px]/grove:opacity-100`,disabled:l||c,onClick:s}):null]})}function FI({agent:e,row:t}){return(0,X.jsxs)(`div`,{className:`inbox-row is-unavailable flex min-h-11 w-full items-center gap-2 rounded-field border-(length:--border) border-transparent px-2 py-1 pr-9 text-left text-base-content`,"data-session-id":t.sessionId,"data-testid":`inbox-unavailable-row`,role:`group`,children:[(0,X.jsxs)(`span`,{className:`inbox-row-copy flex min-w-0 flex-1 flex-col`,children:[(0,X.jsx)(`strong`,{className:`truncate text-sm font-medium`,children:`Conversation unavailable`}),(0,X.jsxs)(`small`,{className:`truncate text-xs text-(--stipe-fg-muted)`,children:[PE(e),` `,(0,X.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),` This saved conversation could not be read.`]})]}),(0,X.jsx)(`span`,{className:`inbox-row-activity inline-grid shrink-0 grid-cols-[1rem_7ch] items-center gap-1.5 text-[0.6875rem]`,children:(0,X.jsx)(`span`,{className:`inbox-row-status flex items-center justify-center`,children:(0,X.jsx)(n,{size:`compact`,tone:`error`,title:`This saved conversation could not be read`})})})]})}function II(e){let t=Math.max(0,Date.now()-e);return t<6e4?`now`:t<36e5?`${String(Math.floor(t/6e4))}m`:t<864e5?`${String(Math.floor(t/36e5))}h`:new Date(e).toLocaleDateString(void 0,{month:`short`,day:`numeric`})}var LI=Fi().min(1).max(256),RI=ii().int().nonnegative();Zr(`state`,[Yr({state:Si(`agent`),version:RI}),Yr({state:Si(`requested`),version:RI,reason:Fi().max(4e3),at:ii().int().nonnegative()}),Yr({state:Si(`person`),version:RI,memberId:LI,memberName:Fi().min(1).max(128),since:ii().int().nonnegative()})]);var zI=Yr({bindingId:LI,agentId:LI,origins:Ti(Fi().min(1).max(2048)).min(1).max(16),lifecycle:Wr([`active`,`suspended`])}),BI=Yr({sessionId:LI,label:Fi().max(4096),lastEventAt:ii().int().nonnegative(),needsYou:Yr({at:ii().int().nonnegative(),reason:Fi().max(4e3)}).nullable(),held:xi(),heldByYou:xi(),heldByName:Fi().min(1).max(128).nullable(),holdVersion:ii().int().nonnegative()}),VI=Yr({bindingId:LI}).extend({sessionId:LI});VI.extend({requestId:Fi().min(1).max(128),text:Fi().trim().min(1).max(4e3)});var HI=Yr({expectedVersion:RI,confirm:xi()});VI.extend(HI.shape),VI.extend({expectedVersion:RI});var UI=Yr({websites:Ti(zI).max(1e3)}),WI=Yr({conversations:Ti(BI).max(100)});Yr({conversation:BI});var GI=Yr({status:Si(`sent`)}),KI=bh(`channels.read`,1,ti(()=>xh({list:Ch(Sh(UI)),conversations:Ch(Sh(WI))}))),qI=bh(`channels.personal.manage`,1,ti(()=>xh({hold:Ch(Sh(BI)),release:Ch(Sh(BI)),dismiss:Ch(Sh(BI)),reply:Ch(Sh(GI))}))),JI=3e4;function YI(e){let t=new Set,n=e=>{let n=e.then(()=>{t.delete(n)},()=>{t.delete(n)});t.add(n)};function r(t){let r=e.command(t);return n(r),r}return{session:{...e,command:r,withdraw:t=>{let r=e.withdraw(t);return n(r),r}},settled:async()=>{let e,n=new Promise(t=>{e=setTimeout(t,JI)});await Promise.race([Promise.all(t),n]),clearTimeout(e)}}}function XI(e,t){let n=!1,r=async()=>{try{return await t.read()}catch(e){if(!(e instanceof Ji)||e.boundary!==`runtime`||e.cause!==`unavailable`)throw e;if(await new Promise(e=>setTimeout(e,150)),n)throw Error(`Conversation opening cancelled`,{cause:e});return t.read()}},i,a=new Promise((e,t)=>{i=()=>{t(Error(`Conversation opening cancelled`))}});return{ready:Promise.race([r(),a]).then(r=>{if(n)throw Error(`Conversation opening cancelled`);Rt(e,t,r)}),close:()=>{n=!0,i()}}}function ZI(e){return class{#e;constructor(t){this.#e=new Tg(t,{fetch:(t,n)=>e(t,n)})}get readyState(){return this.#e.readyState}addEventListener(e,t,n){this.#e.addEventListener(e,t,n)}close(){this.#e.close()}}}function QI(e){let{connection:t,queryClient:n,services:r}=e,i=null,a=null,o=null,s=!1,c=(e,t)=>e?.agentId===t.agentId&&e.sessionId===t.sessionId,l=e=>!s&&i===e,u=(u,d,f=!1)=>{if(s)return;let p={agentId:u,sessionId:d};if(c(i,p)||(i?.close(),i=null,e.onPending(null),e.onError(null),c(a,p)))return;let m=null,h=!1,g={...p,close:()=>{h||(h=!0,m?.())}};i=g,e.onPending(p),(async()=>{try{let s=await r.openAgent(t.capabilities,{agentId:u});if(!l(g)){await s.close();return}let c=r.createClient({baseUrl:s.baseUrl,eventSource:ZI(s.fetch),fetch:s.fetch}),f=YI(c.session(d)),p=f.session,h=XI(n,p);if(m=()=>{h.close(),f.settled().then(()=>Promise.allSettled([c.close(),s.close()]))},await h.ready,e.reportsSelection!==!1&&await t.ui.reportAgentSessionSelection({agentId:u,sessionId:d}),!l(g))return;let _={agentId:u,sessionId:d,session:p},v=o;i=null,a=_,o=g.close,e.onConversation(_),e.onPending(null),v?.()}catch(t){console.error(`Chat Session opening failed`,t),g.close(),l(g)&&(i=null,e.onPending(null),e.onError(f?`That Session could not be opened. ${a?`The current conversation remains open.`:`Choose another Session from the list.`}`:`Could not open this Session${t instanceof Error?`: ${t.message}`:``}. ${a?`The previous conversation remains open.`:`Try opening it again.`}`))}})()},d=()=>{if(s)return;let n=i!==null||a!==null;i?.close(),i=null,o?.(),o=null,a=null,e.onPending(null),e.onConversation(null),e.onError(null),!(!n||e.reportsSelection===!1)&&t.ui.reportAgentSessionSelection(null).catch(e=>{console.error(`Chat Session selection could not be reported`,e)})};return{select:u,clear:d,close:()=>{d(),s=!0}}}function $I(e,t){async function n(e){if(e.type!==`prompt`||(e.images?.length??0)>0)throw new Y(`Website conversations support text replies only`,{code:`COMMAND_NOT_DECLARED`,retryable:!1});if(!t.canReply())throw new Y(`Use Take over to reply to this visitor`,{code:`CAPABILITY_DENIED`,retryable:!1});return await t.reply({bindingId:t.bindingId,sessionId:t.sessionId,requestId:e.requestId,text:e.text}),{status:`recorded`}}return{latestPending:()=>Promise.resolve(null),withdraw:t=>e.withdraw(t),address:e.address,read:t=>e.read(t),watch:t=>e.watch(t),extension:()=>({call:()=>Promise.reject(new Y(`Website Session controls are unavailable`,{code:`COMMAND_NOT_DECLARED`,retryable:!1}))}),command:n}}function eL(e,t){(0,J.useSyncExternalStore)(t=>e?.capabilities.subscribe(t)??(()=>void 0),()=>e?.capabilities.version??0);let n=tn(),[r,i]=(0,J.useState)(null),[a,o]=(0,J.useState)(null),s=e?.capabilities.has(KI)===!0,c=e?.capabilities.has(qI)===!0,l=is({...xy(e,KI,vy.of(e,`websites`),e=>e.list()),enabled:s}),u=s?l.data?.websites??[]:[],d=ns({queries:u.map(t=>({...xy(e,KI,vy.of(e,`website-conversations`,t.bindingId),e=>e.conversations({bindingId:t.bindingId})),enabled:s}))}),f=u.flatMap((e,t)=>(d[t]?.data?.conversations??[]).map(t=>({bindingId:e.bindingId,agentId:e.agentId,siteLabel:e.origins.map(e=>new URL(e).host).join(`, `),conversation:t}))).sort((e,t)=>t.conversation.lastEventAt-e.conversation.lastEventAt),p=f.find(e=>e.bindingId===r?.bindingId&&e.conversation.sessionId===r.sessionId),m=(0,J.useMemo)(()=>e===null?null:QI({connection:e,queryClient:n,services:t,onPending:()=>void 0,onConversation:o,onError:t=>{t!==null&&Hn(e.ui,{variant:`error`,message:`That conversation could not be opened. Try again.`})}}),[e,n,t]);(0,J.useEffect)(()=>()=>{m?.close()},[m]),(0,J.useEffect)(()=>{s||m?.clear()},[s,m]);let h=as({mutationFn:t=>{if(e===null)throw Error(`No App connection`);let n=e.capabilities.require(qI);return t.kind===`hold`?n.hold({bindingId:t.bindingId,sessionId:t.sessionId,expectedVersion:t.expectedVersion,confirm:t.confirm}):n.release({bindingId:t.bindingId,sessionId:t.sessionId,expectedVersion:t.expectedVersion,confirm:t.confirm})},onSuccess:(t,r)=>{n.setQueryData(vy.of(e,`website-conversations`,r.bindingId),e=>e===void 0?void 0:{conversations:e.conversations.map(e=>e.sessionId===t.sessionId?t:e)})}}),g=p?.bindingId,_=p?.conversation.sessionId,v=p?.conversation.heldByYou===!0,y=(0,J.useMemo)(()=>a===null||g===void 0||_===void 0||e===null?null:$I(a.session,{bindingId:g,sessionId:_,canReply:()=>v&&e.capabilities.has(qI),reply:t=>e.capabilities.require(qI).reply(t)}),[e,a,g,_,v]),b=(0,J.useCallback)(()=>{m?.clear(),i(null),o(null),h.reset()},[m,h.reset]);return{canRead:s,canManage:c,rows:f,selected:p,session:y,action:h,loading:s&&(l.isPending||d.some(e=>e.isPending)),failed:s&&(l.isError||d.some(e=>e.isError)),clear:b,select:e=>{s&&(p?.bindingId!==e.bindingId||p.conversation.sessionId!==e.conversation.sessionId||a===null)&&(i({bindingId:e.bindingId,sessionId:e.conversation.sessionId}),o(null),h.reset(),m?.select(e.agentId,e.conversation.sessionId))}}}var tL={view:{kind:`none`},creating:null,awaitingRoute:void 0,route:null,nextTicket:1},nL=(e,t)=>e===t||!!e&&!!t&&e.agentId===t.agentId&&e.sessionId===t.sessionId;function rL(e,t){return e.awaitingRoute!==void 0||!nL(e.route,t)?{awaitingRoute:t,effects:[{type:`navigate`,target:t}]}:{awaitingRoute:void 0,effects:[]}}function iL(e){return e.kind===`opening`?e.target:e.kind===`open`?e.conversation:null}function aL(e){return e.kind===`open`?e.conversation:e.kind===`opening`?e.previous:null}function oL(e,t=[],n=!0,r=null){return{state:e,effects:t,accepted:n,ticket:r}}function sL(e,t,n){let r=iL(e.view),i=n===`host`;if(nL(r,t)){let n=rL(e,t);return oL({...e,creating:null,awaitingRoute:n.awaitingRoute},n.effects)}let a=aL(e.view);if(n!==`route`&&a!==null&&nL(a,t)){let n=rL(e,t);return oL({...e,view:{kind:`open`,conversation:a},creating:null,awaitingRoute:n.awaitingRoute},[{type:`open`,target:t,fromHost:i},...n.effects])}let o=n===`route`?null:rL(e,t);return oL({...e,view:{kind:`opening`,target:t,cause:n,previous:aL(e.view)},creating:null,awaitingRoute:o?o.awaitingRoute:void 0},[{type:`open`,target:t,fromHost:i},...o?o.effects:[]])}function cL(e,t){switch(t.type){case`select`:return sL(e,t.target,t.cause);case`route`:{let n={...e,route:t.target},r=n.awaitingRoute;return r===void 0?t.target===null?n.view.kind===`none`||n.creating?.cause===`person`?oL(n):oL({...n,view:{kind:`none`},creating:null},[{type:`clear`}]):nL(iL(n.view),t.target)||n.creating?.cause===`person`?oL(n):sL(n,t.target,`route`):oL(nL(r,t.target)?{...n,awaitingRoute:void 0}:n)}case`route-confirmed`:{let n={...e,route:t.target};return oL(nL(n.awaitingRoute,t.target)?{...n,awaitingRoute:void 0}:n)}case`create`:{if(t.cause===`auto`&&(e.view.kind!==`none`||e.creating!==null||e.awaitingRoute!==void 0))return oL(e,[],!1);let n=e.nextTicket;return oL({...e,creating:{ticket:n,cause:t.cause},nextTicket:n+1},[],!0,n)}case`created`:{if(e.creating?.ticket!==t.ticket)return oL(e,[],!1);let n=e.creating.cause;return n===`auto`&&e.view.kind!==`none`?oL({...e,creating:null},[],!1):sL({...e,creating:null},t.target,n)}case`create-failed`:return e.creating?.ticket===t.ticket?oL({...e,creating:null}):oL(e,[],!1);case`opened`:{let n=e.view;return n.kind!==`opening`||!nL(n.target,t.conversation)?oL(e,[],!1):oL({...e,view:{kind:`open`,conversation:t.conversation}})}case`open-failed`:{let t=e.view;if(t.kind!==`opening`)return oL(e,[],!1);let n=t.previous,r=rL(e,n);return oL({...e,view:n?{kind:`open`,conversation:n}:{kind:`none`},awaitingRoute:r.awaitingRoute},r.effects)}case`leave`:{let n=t.navigate?rL(e,null):null;return oL({...e,view:{kind:`none`},creating:null,awaitingRoute:n?n.awaitingRoute:void 0},[{type:`clear`},...n?n.effects:[]])}case`reset`:return oL({...e,view:{kind:`none`},creating:null,awaitingRoute:void 0})}}function lL(e){return aL(e.view)}function uL(e){return e.view.kind===`opening`?e.view.target:null}function dL(e){let t={state:tL,error:null},n=!1,r=new Set,i=e=>{t={...t,...e};for(let e of r)e()},a=QI({connection:e.connection,queryClient:e.queryClient,services:e.services,onPending:()=>void 0,onConversation:e=>{e!==null&&s({type:`opened`,conversation:e})},onError:e=>{i({error:e}),e!==null&&s({type:`open-failed`})}}),o=t=>{if(t.type===`open`)a.select(t.target.agentId,t.target.sessionId,t.fromHost);else if(t.type===`clear`)a.clear();else if(e.navigate!==void 0){let n=()=>{s({type:`route-confirmed`,target:e.shownRoute?.()??null})};e.navigate(t.target).then(n,n)}};function s(e){if(n)return{accepted:!1,ticket:null};let r=cL(t.state,e);i({state:r.state});for(let e of r.effects)o(e);return{accepted:r.accepted,ticket:r.ticket}}return{snapshot:()=>t,subscribe:e=>(r.add(e),()=>{r.delete(e)}),select:(e,t=`person`)=>s({type:`select`,target:e,cause:t}),observeRoute:e=>s({type:`route`,target:e}),create:(e=`person`)=>s({type:`create`,cause:e}),created:(e,t)=>s({type:`created`,ticket:e,target:t}),createFailed:e=>s({type:`create-failed`,ticket:e}),leave:e=>s({type:`leave`,navigate:e}),close:()=>{n||(s({type:`reset`}),n=!0,a.close(),r.clear())}}}var fL=(0,J.lazy)(async()=>({default:(await Eo(()=>import(`./website-conversation-kQbo5VTI.js`),__vite__mapDeps([7,1,8,2,3,4,5,9,10,11]))).WebsiteConversation})),pL=(0,J.lazy)(async()=>({default:(await Eo(()=>import(`./parakeet-conversation-m2Bl3XXj.js`),__vite__mapDeps([12,1,8,2,3,4,5,9,10,11,13]))).ParakeetConversation})),mL={openAgent:sg,createClient:Na,autoOpen:!0},hL=[`agent.list`,`agent.manage`,`agent.read`,`agent.send`],gL=[`agent.read`,`agent.send`,`agent.manage`],_L=no({family:`grove-session-create-request`,version:1,kinds:{request:{prefix:`request`}}});async function vL(e,t,n,r){let i=await n.openAgent(e.capabilities,{agentId:t}),a=n.createClient({baseUrl:i.baseUrl,eventSource:ZI(i.fetch),fetch:i.fetch});try{return await r(a)}finally{Promise.allSettled([a.close(),i.close()])}}function yL({open:e,renderConversation:t,connection:n,commands:r,composeDraft:i,onPrefilled:a,onForked:o,onOpen:s,models:c,autoFocus:l,opening:u=!1,label:d=`Conversation`}){let f=e.session,p=(0,J.useRef)(null);(0,J.useEffect)(()=>{p.current?.toggleAttribute(`inert`,u)},[u]);let[m,h]=(0,J.useState)({kind:`loading`});return(0,J.useEffect)(()=>{if(!n||t)return;let r=new AbortController;return h({kind:`loading`}),tI(n.capabilities,e.agentId,r.signal).then(e=>{r.signal.aborted||h({kind:`ready`,models:e})},()=>{r.signal.aborted||h({kind:`unavailable`})}),()=>{r.abort()}},[n,e.agentId,t]),(0,J.useEffect)(()=>{let i=r.contribute({sourceId:`grove-session`,namespace:`session`,commands:[...cE(f,{sourceId:`grove-session`,namespace:`session`,sessionResumeAvailable:!1,forkAvailable:!0,onForked:o}),...t?[]:ew(f,{sourceId:`grove-session`,namespace:`session`,models:m.kind===`ready`?m.models:[],refreshModels:t=>n?tI(n.capabilities,e.agentId,t):Promise.reject(Error(`Agent connection is unavailable`)),availability:()=>m.kind===`ready`&&m.models.length>0?{status:`available`}:{status:`unavailable`,reason:m.kind===`loading`?`Loading this Agent's models`:m.kind===`ready`?`This Agent has no available models`:`This Agent's model catalog is unavailable`}})]});return()=>{i.dispose()}},[r,f,o,t,m,n,e.agentId]),(0,X.jsx)(`section`,{ref:p,className:`inbox-conversation min-h-0 min-w-0 flex-1`,"data-inbox-conversation":!0,"aria-busy":u,"aria-label":d,children:t?t(e,i,s):(0,X.jsx)(J.Suspense,{fallback:(0,X.jsx)(DI,{className:`m-auto`,framed:!1,message:`Opening conversation…`}),children:(0,X.jsx)(pL,{session:f,draftIdentity:{agentId:e.agentId,sessionId:e.sessionId},connection:n,commands:r,prefill:i,onPrefilled:a,onOpen:s,models:c,autoFocus:l})})})}var bL={state:tL,error:null},xL=()=>()=>void 0;function SL(e){return hh(e.connection),(0,X.jsx)(CL,{...e},JSON.stringify(vy.of(e.connection)))}function CL(e){let t=(0,J.useMemo)(WF,[e.connection]);return(0,X.jsx)(zF,{value:(0,X.jsx)(wL,{...e,router:t}),children:(0,X.jsx)(FF,{router:t})})}function wL({router:e,connection:t,services:n=mL}){let{agentFilterId:r,setFilter:i,selection:a,open:o}=KF(e,t?.window.navigation),s=tn(),l=eL(t,n),u=(0,J.useMemo)(()=>t===null?null:dL({connection:t,queryClient:s,services:n,navigate:t=>t===null?e.navigate({to:`/`,search:!0,replace:!0}):o(t.agentId,t.sessionId),shownRoute:()=>GF(e)}),[t,o,s,e,n]),d=(0,J.useSyncExternalStore)(u?.subscribe??xL,u?.snapshot??(()=>bL)),{directory:f,inbox:p,computerChoices:m,createAgent:h,renameAgent:g,setAgentAvatar:_}=nI(t),v=f.data??[],y=f.isPending&&(t?.capabilities.has(Rh)??!0),b=f.error?.message??null,x=h.isPending,S=as({mutationFn:e=>{if(!t)throw Error(`No App connection`);return vL(t,e.agentId,n,t=>t.createSession(e.requestId))}}),C=as({mutationFn:e=>{if(!t)throw Error(`No App connection`);return vL(t,e.agentId,n,t=>t.deleteSession(e.sessionId))},onError:()=>{t&&Hn(t.ui,{variant:`error`,message:`The conversation could not be deleted. Try again.`})},onSuccess:(e,t)=>{a?.agentId===t.agentId&&a.sessionId===t.sessionId&&u?.leave(!0),p.refresh()}}),w=S.isPending?S.variables.agentId:null,T=uL(d.state),E=lL(d.state),[D,O]=(0,J.useState)(!1),k=E?.agentId??null,A=E?.sessionId??null,[j,M]=(0,J.useState)(null),ee=(0,J.useRef)(null),[te,ne]=TI((0,J.useMemo)(()=>t?.capabilities.has(qy)?t.capabilities.require(qy):void 0,[t])),{agentRailOpen:re,listRailOpen:ie,listWidth:ae}=te,oe=e=>{ne(t=>({...t,agentRailOpen:e(t.agentRailOpen)}))},se=e=>{ne(t=>({...t,listRailOpen:e(t.listRailOpen)}))},ce=e=>{ne(t=>({...t,listWidth:SI(e(t.listWidth))}))},le=gI({begin:()=>!0,move:e=>{ce(t=>t+e)},end:()=>void 0}),[ue,de]=(0,J.useState)(!1),fe=(0,J.useRef)(null),pe=BE(fe),P=pe??!0,me=(0,J.useRef)(null),[he,ge]=(0,J.useState)(null),_e=h.error?.message??null,ve=h.data,ye=(0,J.useRef)(null),[be,xe]=(0,J.useState)(null),[Se,Ce]=(0,J.useState)(null),we=hh(t),Te=we?.openRequest??null,Ee=we?.setup?.models===`missing`,De=(0,J.useRef)(null),Oe=(0,J.useRef)(null);(0,J.useEffect)(()=>{if(u!==null)return u.observeRoute(Oe.current),()=>{ye.current=null,u.close()}},[u]);let[ke,je]=(0,J.useState)(null),Me=(0,J.useMemo)(()=>Ae(),[]),Ne=(0,J.useMemo)(()=>t===null?null:QI({connection:t,queryClient:s,services:n,onPending:()=>void 0,onConversation:je,onError:xe,reportsSelection:!1}),[t,s,n]);(0,J.useEffect)(()=>Ne===null?void 0:()=>{Ne.close()},[Ne]);let Pe=(0,J.useCallback)(e=>{let t=t=>e.params.find(e=>e.key===t)?.value,n=t(`agent`),r=t(`session`);n!==void 0&&r!==void 0&&Ne?.select(n,r)},[Ne]),Fe=(0,J.useCallback)((e,t,n=!1)=>{u!==null&&(S.isError&&S.reset(),l.clear(),O(!1),u.select({agentId:e,sessionId:t},n?`host`:`person`))},[u,l.clear,S.isError,S.reset]),Ie=a?.agentId,Le=a?.sessionId;Oe.current=Ie!==void 0&&Le!==void 0?{agentId:Ie,sessionId:Le}:null,(0,J.useEffect)(()=>{u?.observeRoute(Oe.current)},[u,Ie,Le]);let Re=(0,J.useCallback)(e=>{E&&(Fe(E.agentId,e),p.refresh())},[E,Fe,p.refresh]);(0,J.useEffect)(()=>{if(!t||Te===null){Te===null&&(De.current=null);return}if(Te.kind!==`navigate`||De.current===Te.requestId)return;let e=Te.params.find(e=>e.key===`agent`)?.value,n=Te.params.find(e=>e.key===`session`)?.value;!e||!n||(De.current=Te.requestId,i(e),Fe(e,n,!0))},[t,Te,Fe,i]);let ze=(0,J.useCallback)(async e=>{if(!t||x||!t.capabilities.has(zh))return!1;try{let t=await h.mutateAsync(e);return i(t.agentId),ge(t.agentId),M(null),!0}catch{return!1}},[t,x,h.mutateAsync,i]),Be=!!E||l.selected!==void 0,Ve=(0,J.useCallback)(async(e,n,r=`person`)=>{if(!t||!u||w!==null)return`Conversation creation is unavailable.`;let i=u.create(r);if(!i.accepted||i.ticket===null)return;xe(null);let a=ye.current?.agentId===e?ye.current:{agentId:e,requestId:_L.request.generate()};ye.current=a;try{let t=await S.mutateAsync(a);u.created(i.ticket,{agentId:e,sessionId:t}).accepted&&(S.isError&&S.reset(),l.clear(),O(!1),n!==void 0&&Ce({requestId:mn(),text:n,send:!0})),p.refresh(),M(null),de(!1),ye.current===a&&(ye.current=null);return}catch(e){return u.createFailed(i.ticket),console.error(`Grove conversation creation failed`,e),Be&&Hn(t.ui,{variant:`error`,message:`The conversation could not be started. Try again.`}),e instanceof Error?e.message:`Couldn't start the conversation.`}},[t,Be,u,w,S.isError,S.mutateAsync,S.reset,l.clear,p.refresh]);(0,J.useEffect)(()=>{if(!(!t||Te?.kind!==`compose`)&&De.current!==Te.requestId&&!(!E&&y)&&(De.current=Te.requestId,Ce({requestId:Te.requestId,text:Te.text}),!E)){let e=t.capabilities.has(ng)?v.find(e=>e.sessionOperations.includes(`agent.read`)&&e.sessionOperations.includes(`agent.send`)&&e.sessionOperations.includes(`agent.manage`)):void 0;e?Ve(e.agentId):M(`agent`)}},[v,t,y,E,Te,Ve]);let He=$F({setDraft:e=>T!==null||!E||!t?.capabilities.has(ng)||!v.some(e=>e.agentId===E.agentId&&e.sessionOperations.includes(`agent.send`))?!1:(Ce({requestId:mn(),text:e}),!0),newConversation:()=>{E&&Ve(E.agentId)},openPermissions:()=>{t?.ui.requestAppPermissions({}).catch(e=>{console.error(`Chat inbox or permission request failed`,e)})}},t?.commands),Ue=new Set(l.rows.map(e=>`${e.agentId}:${e.conversation.sessionId}`)),Ge=p.items.filter(e=>!(`kind`in e)).filter(e=>!Ue.has(`${e.agentId}:${e.sessionId}`)),Ke=ns({queries:(E?[E.session]:[]).map(e=>({...bn(e),enabled:!1}))}).at(0)?.data?.snapshot,qe=(0,J.useMemo)(()=>E&&Ke?{agentId:E.agentId,sessionId:E.sessionId,state:Je(Ke)}:void 0,[E,Ke]),Ye=(0,J.useMemo)(()=>AE(v,D&&l.canRead?[]:Ge,r,qe),[r,v,Ge,D,l.canRead,qe]),Xe=(0,J.useMemo)(()=>{let e=new Map;for(let t of Ge)`state`in t&&(t.state===`needs_you`?e.set(t.agentId,`speaking`):t.state===`running`&&!e.has(t.agentId)&&e.set(t.agentId,`thinking`));return e},[Ge]),Ze=(0,J.useMemo)(()=>new Map(v.map(e=>[e.agentId,e])),[v]),Qe=(0,J.useRef)(null),$e=Ge.find(e=>e.agentId===k&&e.sessionId===A),et=$e!==void 0&&$e.state!==`unavailable`,tt=$e!==void 0&&$e.state!==`unavailable`?$e.settledAt:void 0;(0,J.useEffect)(()=>{!et||k===null||A===null||p.visit(k,A).catch(e=>{console.error(`Chat inbox or permission request failed`,e)})},[et,tt,k,A,p.visit]);let nt=p.status===`loading`,rt=p.status===`error`,it=t?.capabilities.has(zh)??!1,at=t?.capabilities.has(ng)??!1,ot=v.filter(e=>e.sessionOperations.includes(`agent.read`)&&e.sessionOperations.includes(`agent.send`)&&e.sessionOperations.includes(`agent.manage`)),st=ot.find(e=>e.agentId===(he??r))??ot.at(0),ct=at&&st!==void 0,lt=()=>{t?.ui.requestAppPermissions({agents:hL}).catch(e=>{console.error(`Chat inbox or permission request failed`,e)})},ut=ve&&(!ve.sessionOperations.includes(`agent.read`)||!ve.sessionOperations.includes(`agent.send`)||!ve.sessionOperations.includes(`agent.manage`))?`Agent created. Allow Grove to read, send messages and manage its sessions to start a conversation.`:Se&&!E&&!ct&&h.isIdle?`Choose an Agent to compose your game idea.`:null,dt=(0,J.useMemo)(()=>AE(v,Ge,null,qe),[v,Ge,qe]),ft=(e,t)=>{de(!1),Fe(e,t)},pt=()=>{me.current=document.activeElement instanceof HTMLElement?document.activeElement:null,de(!0)},ht=ME(Ye).length,gt=P&&ie,_t=P&&Ee&&ht===0&&Ye.unavailable.length===0&&l.rows.length===0&&!E&&!l.selected&&!y&&!nt&&!l.loading&&!rt&&!b&&!l.failed;gh(t,[...P?[{kind:`button`,id:`agents`,text:`Agents`,expanded:re,title:re?`Hide Agents`:`Show Agents`},..._t?[]:[{kind:`button`,id:`conversations`,text:`Conversations`,expanded:ie,title:ie?`Hide conversations`:`Show conversations`}]]:[{kind:`button`,id:`agents`,text:`Agents and conversations`,opens:`dialog`,expanded:ue}],...ke===null?[]:[{kind:`button`,id:`close-beside`,text:`Close beside`,title:`Close beside conversation`}]],e=>{if(j!==null)return!1;if(e.itemId===`close-beside`&&ke!==null)Ne?.clear();else if(P&&e.itemId===`agents`)oe(e=>!e);else if(P&&e.itemId===`conversations`)se(e=>!e);else if(!P&&e.itemId===`agents`)ue?de(!1):pt();else return!1;return!0});let vt=e=>{i(e),ge(e);let t=[...dt.active,...dt.settled].filter(t=>t.agentId===e).sort((e,t)=>t.lastActivityAt-e.lastActivityAt).at(0);t&&ft(e,t.sessionId)},yt={"--grove-list-width":`${String(ae)}px`},bt=E?Ze.get(E.agentId):void 0,xt=r===null?void 0:Ze.get(r),St=t?.capabilities.has(Vh)??!1,Ct=v.length===1?v[0]:void 0,wt=xt??Ct,Tt=t?.capabilities.has(Wh)??!1,Et=rI(t,xt?.agentId??null),Dt=iI(t,xt?.agentId??null),Ot=(0,J.useCallback)(async(e,t)=>{try{return await Dt.save.mutateAsync({agentId:e,...t}),`saved`}catch(e){return e instanceof Y&&e.code===`CONFLICT`?`conflict`:e instanceof Y&&e.code===`FILE_TOO_LARGE`?`too_large`:`failed`}},[Dt.save.mutateAsync]),kt=(0,J.useCallback)(async()=>{let e=await Dt.read.refetch({throwOnError:!0});if(e.data===void 0)throw Error(`No instructions file`);return e.data},[Dt.read.refetch]),At=(0,J.useCallback)((e,n)=>{t?.ui.showToast({message:e,tone:n}).catch(e=>{console.error(`Instructions toast failed`,e)})},[t]),jt=(0,J.useRef)(!1);(0,J.useEffect)(()=>{n.autoOpen!==!0||jt.current||!t||E||Te!==null||y||nt||rt||b||Ee||ht>0||st===void 0||!at||w!==null||(jt.current=!0,Ve(st.agentId,void 0,`auto`))},[at,t,y,b,rt,ht,nt,Ee,E,Te,n.autoOpen,st,Ve,w]);let Mt=(0,J.useCallback)(async(e,n)=>{if(!t)return!1;try{return await g.mutateAsync({agentId:e,name:n}),!0}catch{return!1}},[t,g.mutateAsync]),Nt=(0,J.useCallback)(async(e,n)=>{if(!t)return!1;try{return await _.mutateAsync({agentId:e,avatar:n}),!0}catch{return!1}},[t,_.mutateAsync]),Pt=(0,J.useCallback)(()=>{let e=Et.status.data;!xt||e==null||Et.approve.mutate({agentId:xt.agentId,expectedRevision:e.revision})},[xt,Et.status.data,Et.approve]),Ft=(0,J.useCallback)(e=>{if(!(!t||x||w!==null||e===`agent`&&!it)){if(e===`agent`&&Ee){t.ui.showToast({message:FE,tone:`info`}).catch(e=>{console.error(`Grove toast failed`,e)});return}j===null&&(ee.current=ue?me.current:document.activeElement instanceof HTMLElement?document.activeElement:null),de(!1),e===`session`&&ge(bt?.agentId??r??ot.at(0)?.agentId??null),M(e)}},[t,x,w,it,Ee,j,ue,bt?.agentId,r,ot]);(0,J.useEffect)(()=>{let e=e=>{e.defaultPrevented||e.repeat||!e.ctrlKey||e.altKey||e.metaKey||e.key.toLowerCase()!==`n`||!t||e.shiftKey&&!it||(e.preventDefault(),Ft(e.shiftKey?`agent`:`session`))};return window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`keydown`,e)}},[t,it,Ft]);let It=S.isError?S.variables:null,Lt=It&&j!==`session`&&!Be?(0,X.jsx)(N,{className:`inbox-empty m-auto max-w-[28rem]`,tone:`error`,title:`Couldn't start the conversation.`,description:S.error?.message,action:(0,X.jsx)(c,{variant:`outline`,onClick:()=>void Ve(It.agentId),children:`Retry`})}):null;return(0,X.jsxs)(`main`,{ref:fe,className:`inbox-app grove-shell @container/grove relative flex h-dvh min-h-0 bg-base-200 font-sans text-base-content`,"data-inbox-app":!0,"data-conversation":!!E||l.selected!==void 0,children:[t?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(nj,{open:j===`agent`,pending:x,error:_e,addCredit:h.error instanceof Y&&h.error.code===`INSUFFICIENT_CREDIT`?()=>t.ui.openTeamBilling():null,computers:m.isError?{status:`unavailable`,message:`Your Computers could not be loaded. New Computer and No Computer still work.`}:m.isPending?{status:`loading`}:m.data===null?{status:`not-offered`}:{status:`offered`,computers:m.data},create:ze,onClose:()=>{M(null)},returnFocus:ee}),j===`session`?(0,X.jsx)(rj,{open:!0,agents:at?ot:[],defaultAgentId:st?.agentId??null,start:Ve,pending:w!==null,onClose:()=>{M(null)},onNewAgent:it?()=>{M(`agent`)}:void 0,returnFocus:ee}):null]}):null,pe===null?null:(0,X.jsxs)(VE,{desktop:P,open:ue,onOpenChange:de,returnFocus:me,children:[(0,X.jsx)(LE,{open:re,agents:v,agentActivity:Xe,agentFilterId:r,websitesSelected:D,websitesVisible:l.canRead,canCreate:t!==null&&it,modelsMissing:Ee,createOpen:j===`agent`,onAll:()=>{i(null),O(!1)},onWebsites:()=>{i(null),O(!0)},onAgent:e=>{O(!1),vt(e)},onCreate:()=>{Ft(`agent`)}}),_t?null:(0,X.jsxs)(`aside`,{id:`grove-list-rail`,className:`inbox-sidebar group relative min-h-0 min-w-0 flex-1 flex-col border-r border-base-300 @min-[900px]/grove:w-[var(--grove-list-width)] @min-[900px]/grove:flex-none ${ie?`flex`:`flex @min-[900px]/grove:hidden`}`,style:yt,"aria-label":`Conversations`,children:[P?(0,X.jsx)(hI,{"aria-label":`Conversation list width`,"aria-controls":`grove-list-rail`,className:`absolute right-0 top-1/2 z-10 translate-x-1/2 -translate-y-1/2`,orientation:`vertical`,value:ae,min:vI.min,max:vI.max,onValueChange:e=>{ce(()=>e)},onDoubleClick:()=>{ce(()=>vI.initial)},...le}):null,(0,X.jsxs)(`header`,{className:`inbox-header flex h-10 flex-none items-center gap-1 border-b border-base-300 pl-3 pr-1`,children:[xt?(0,X.jsx)(mI,{agentId:xt.agentId,name:PE(xt),avatar:xt.avatar,...Tt?{setAvatar:Nt}:{}},xt.agentId):null,(0,X.jsx)(jn,{level:2,className:`m-0 min-w-0 flex-1 truncate text-sm`,children:D&&l.canRead?`Websites`:xt?PE(xt):`All agents`}),wt&&St?(0,X.jsx)(JF,{agentId:wt.agentId,name:wt.name,rename:Mt},wt.agentId):null,xt&&Dt.canUse?(0,X.jsx)(pI,{agentId:xt.agentId,name:xt.name,file:Dt.read.data,loading:Dt.read.isPending,save:Ot,reload:kt,notify:At},xt.agentId):null,t&&(ct||it)?(0,X.jsx)(We,{"aria-label":`New conversation`,"aria-haspopup":`dialog`,icon:(0,X.jsx)(gE,{}),iconSize:`sm`,size:`sm`,onClick:()=>{Ft(`session`)}}):null]}),xt&&Et.canRead?(0,X.jsx)(YF,{status:Et.status.data,approving:Et.approve.isPending,onApprove:Pt}):null,ut?(0,X.jsx)(N,{tone:`info`,title:ut,action:(0,X.jsx)(c,{variant:`ghost`,onClick:()=>{t?.ui.requestAppPermissions({agents:gL}).catch(e=>{console.error(`Chat inbox or permission request failed`,e)})},children:`Allow conversation access`})}):null,t&&v.length>0&&!ct&&!it?(0,X.jsxs)(`section`,{className:`inbox-create inbox-access flex flex-col items-start gap-3 border-b border-base-300 py-2`,"aria-labelledby":`inbox-agent-access-title`,children:[(0,X.jsx)(jn,{level:2,id:`inbox-agent-access-title`,className:`inbox-access-title m-0`,children:`Let Grove manage your Agents`}),(0,X.jsx)(`p`,{children:`Grove creates Agents and carries their conversations. Your Team decides what it may do.`}),(0,X.jsx)(c,{size:`sm`,onClick:lt,children:`Allow Agent access`})]}):null,b?(0,X.jsx)(N,{className:`inbox-error`,tone:`error`,title:b,action:(0,X.jsx)(c,{variant:`ghost`,size:`sm`,onClick:()=>{f.refetch()},children:`Try again`})}):null,rt?(0,X.jsx)(N,{className:`inbox-error`,tone:`error`,title:`Conversations are unavailable.`,action:(0,X.jsx)(c,{variant:`ghost`,size:`sm`,onClick:()=>{p.refresh()},children:`Retry conversations`})}):null,(0,X.jsx)(vx,{ref:Qe,className:`inbox-surface min-h-0 flex-1`,"aria-label":`Conversations`,children:t?y?(0,X.jsx)(DI,{framed:!1,message:`Loading Agents…`}):(0,X.jsx)(NI,{viewport:Qe,view:Ye,agents:Ze,loading:nt||l.loading,failed:!!b||rt||l.failed,showEmptyState:!Ee,pendingSelection:T,selectedAgentId:k,selectedSessionId:A,onSelect:ft,onDelete:at?(e,t)=>{C.mutate({agentId:e,sessionId:t})}:void 0,deleting:C.isPending?C.variables:null,websites:l.rows.filter(e=>r===null||e.agentId===r),selectedWebsite:l.selected,onSelectWebsite:e=>{u?.leave(!1),de(!1),l.select(e)}}):(0,X.jsx)(`p`,{className:`inbox-empty m-0 px-2 py-3 text-sm text-(--stipe-fg-muted)`,children:`Connect to the host to browse Agents.`})},r)]}),P&&!ie&&!_t?(0,X.jsx)(`div`,{className:`flex w-10 flex-none flex-col items-center border-r border-base-300 pt-1`,children:(0,X.jsx)(We,{"aria-label":`Show conversations`,"aria-controls":`grove-list-rail`,"aria-expanded":!1,icon:(0,X.jsx)(pE,{}),iconSize:`sm`,size:`sm`,onClick:()=>{se(()=>!0)}})}):null]}),(0,X.jsxs)(`section`,{className:`inbox-conversation-shell flex min-h-0 min-w-0 flex-1 flex-col`,"aria-label":`Conversation`,children:[(0,X.jsx)(RE,{app:t}),be??d.error?(0,X.jsx)(N,{className:`inbox-error m-2`,tone:`error`,title:be??d.error??``}):null,l.selected?(0,X.jsx)(J.Suspense,{fallback:null,children:(0,X.jsx)(fL,{inbox:l,ui:t?.ui??null})}):T!==null&&E===null?(0,X.jsx)(DI,{className:`m-auto`,framed:!1,message:`Opening conversation…`}):E?(0,X.jsx)(yL,{open:E,connection:t,commands:He,renderConversation:n.renderConversation,composeDraft:Se,onPrefilled:()=>{Ce(null)},onForked:Re,onOpen:Pe,models:we?.setup?.models,autoFocus:P&&j===null,opening:T!==null}):!t||y?(0,X.jsx)(DI,{className:`m-auto`,framed:!1,message:t?`Loading Agents…`:`Connecting to Oyster…`}):Ee&&(v.length>0||it)?(0,X.jsx)(kI,{connection:t,navigation:P?void 0:{open:ue,onOpen:pt}}):v.length===0&&!b?(0,X.jsx)(mt,{className:`inbox-empty m-auto max-w-[28rem]`,variant:`speech`,thinking:x,renderVisual:({speaking:e,thinking:t})=>(0,X.jsx)(vE,{className:`h-full w-full`,state:{activity:t?`thinking`:e?`speaking`:`idle`,expression:`normal`}}),title:it?`Meet your first Agent`:`Welcome to Grove`,description:it?`An Agent is an AI helper. Name one to chat, write and make things together.`:`Let Grove find your AI helpers, create new ones, and open conversations. Your Team controls this access.`,actions:it?(0,X.jsx)(c,{onClick:()=>{Ft(`agent`)},children:`Name your first Agent`}):(0,X.jsx)(c,{onClick:lt,children:`Allow Agent access`})}):Lt??(0,X.jsx)(mt,{className:`inbox-empty m-auto max-w-[28rem]`,variant:`panel`,title:ht>0?`Pick up a conversation`:st?`Say hello to ${PE(st)}`:`No conversations yet`,description:ht>0?`${gt?`Choose one from the list`:`Open the conversation list to choose one`}, or ask for something new. A short writing task is a good start.`:`Ask for anything. Pick one to start.`,suggestions:ht===0&&ct?AI.map(e=>({label:e,disabled:w!==null,onSelect:()=>{Ve(st.agentId,e)}})):void 0,actions:(0,X.jsxs)(X.Fragment,{children:[P||ht===0?null:(0,X.jsx)(c,{variant:`outline`,"aria-haspopup":`dialog`,"aria-controls":`grove-nav`,"aria-expanded":ue,onClick:pt,children:`Agents and conversations`}),ct?(0,X.jsx)(c,{variant:`outline`,loading:w===st.agentId,disabled:w!==null,onClick:()=>void Ve(st.agentId),children:ht>0?`Ask ${PE(st)} something`:`Start a conversation`}):null]})})]}),ke===null?null:(0,X.jsx)(`section`,{className:`inbox-conversation-shell flex min-h-0 min-w-0 flex-1 flex-col border-l border-base-300`,"aria-label":`Beside conversation`,"data-inbox-beside":!0,children:(0,X.jsx)(yL,{open:ke,connection:t,commands:Me,renderConversation:n.renderConversation,composeDraft:null,onPrefilled:()=>void 0,onForked:e=>{Ne?.select(ke.agentId,e)},onOpen:Pe,models:we?.setup?.models,label:`Beside conversation`})})]})}var TL=document.getElementById(`inbox-root`);if(!TL)throw Error(`Inbox root is missing`);fh(TL,{name:`Grove`,queryClient:by()},({app:e})=>(0,J.createElement)(SL,{connection:e}));export{wh as _,vT as a,_T as c,lT as d,sw as f,Ch as g,xh as h,kT as i,bT as l,Sh as m,NA as n,yT as o,vy as p,AA as r,hT as s,AI as t,gT as u,bh as v,is as y};