@ai4b-team/fsaos-gateway-sdk 4.2.0 → 4.2.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.
@@ -1,10 +1,10 @@
1
- /* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-10-31T01:05:49.636Z */
2
- "use strict";var __FSAOS_GATEWAY__=(()=>{var il=Object.create;var Fn=Object.defineProperty;var ol=Object.getOwnPropertyDescriptor;var al=Object.getOwnPropertyNames;var cl=Object.getPrototypeOf,ul=Object.prototype.hasOwnProperty;var Wi=e=>{throw TypeError(e)};var ll=(e,t,n)=>t in e?Fn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var qn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),dl=(e,t)=>{for(var n in t)Fn(e,n,{get:t[n],enumerable:!0})},Bi=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of al(t))!ul.call(e,s)&&s!==n&&Fn(e,s,{get:()=>t[s],enumerable:!(r=ol(t,s))||r.enumerable});return e};var X=(e,t,n)=>(n=e!=null?il(cl(e)):{},Bi(t||!e||!e.__esModule?Fn(n,"default",{value:e,enumerable:!0}):n,e)),fl=e=>Bi(Fn({},"__esModule",{value:!0}),e);var te=(e,t,n)=>ll(e,typeof t!="symbol"?t+"":t,n),Cs=(e,t,n)=>t.has(e)||Wi("Cannot "+n);var l=(e,t,n)=>(Cs(e,t,"read from private field"),n?n.call(e):t.get(e)),C=(e,t,n)=>t.has(e)?Wi("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),w=(e,t,n,r)=>(Cs(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),q=(e,t,n)=>(Cs(e,t,"access private method"),n);var Qn=(e,t,n,r)=>({set _(s){w(e,t,s,n)},get _(){return l(e,t,r)}});var ae=qn((kd,Hi)=>{Hi.exports=React});var Ir=qn((Ip,Eo)=>{Eo.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var Lo=qn((om,Ko)=>{Ko.exports={createClient:window.supabase.createClient}});var ha=qn((vm,ma)=>{ma.exports=ReactDOM});var Su=qn((pg,wu)=>{wu.exports=ReactDOM});var Vi={};dl(Vi,{CHANNEL_AI_MODES:()=>Wc,ComponentRenderer:()=>Lc,EnforcementDeniedError:()=>rt,FormSubmissionError:()=>On,GatewayRequestError:()=>Ie,InteractionTrackingError:()=>kn,KernelProvider:()=>jc,QueryClientProvider:()=>Gn,acceptInvite:()=>Fi,answerInput:()=>Di,assignPersonalSection:()=>Xu,auth:()=>Mu,awaitAnchorReady:()=>er,awaitScopeReady:()=>Zo,callTool:()=>Iu,cancelQueuedTurn:()=>vu,cancelTurn:()=>yu,clearCachedToken:()=>ei,clearSession:()=>ci,configureGatewayReads:()=>ua,createAgent:()=>Qi,createItem:()=>Cu,disconnectSSE:()=>_i,disposeVfsRealtimeWs:()=>bi,electHomeAnchor:()=>Mt,emitEvent:()=>qa,fetchChannelMessages:()=>Wa,fetchChannelMessagesPage:()=>lr,fetchChannelMessagesWithCards:()=>as,fetchEdgesForItem:()=>ts,fetchItemHistory:()=>ss,fetchItemVersions:()=>ur,fetchItems:()=>xn,fetchMemberFocus:()=>is,fetchOpenEnvelope:()=>os,fetchRecentActivity:()=>rs,fetchResolvedItems:()=>Ni,fetchTimelineHistory:()=>Ki,fetchTurnQueueEntries:()=>ja,fetchTypeDefinitions:()=>es,fetchVfsChildren:()=>cr,fetchVfsChildrenPage:()=>Zr,fetchVfsItem:()=>ar,fetchVfsItemById:()=>Xr,fetchVfsTree:()=>ns,gatewayCall:()=>x,getAccessToken:()=>Ye,getAnchor:()=>pn,getAnchorRef:()=>ye,getAnchorVersion:()=>ri,getAssetUrl:()=>ku,getDefaultSort:()=>Lu,getHomeAnchor:()=>fe,getMountVersion:()=>tr,getMounts:()=>Te,getPathSubscriptionState:()=>Da,getQueryClient:()=>O,getRequiredFormFields:()=>ju,getScope:()=>H,getScopeVersion:()=>ee,getServerClockOffsetMs:()=>sa,getServerClockSyncedAt:()=>ia,getSessionEntry:()=>ht,hasServerClock:()=>ra,initSession:()=>Xe,initVfsRealtimeWs:()=>Qt,initializeFsaos:()=>gu,initializeWorkspace:()=>vs,interpretSchema:()=>Ui,invalidateAllVfs:()=>Ga,invalidateChannelMessages:()=>Ja,invalidateChildren:()=>Yr,invalidateItem:()=>vi,invalidateOpenEnvelope:()=>Ya,invalidatePathAndParent:()=>Ba,invalidateSubtree:()=>Ha,invalidateTypes:()=>za,inviteMember:()=>Oi,isAnchorReady:()=>ii,isChannelPath:()=>pe,isListableItemsFilter:()=>Rn,isScopeReady:()=>Dr,itemsFilterFromQueryFilter:()=>Va,listChildren:()=>Pu,loadMounts:()=>Dt,mount:()=>Ou,mountRealtimeScope:()=>Cn,normalizeItem:()=>_e,onConnectionStateChange:()=>Jr,pathSubscriptionMatches:()=>hi,personalSectionsKey:()=>vr,ping:()=>Qa,pushChanges:()=>Eu,queryClient:()=>Sa,readItem:()=>xu,refreshQuery:()=>Ae,registerCleanup:()=>ne,replaceMounts:()=>fs,resetAllSdkState:()=>mn,resolvePrincipalId:()=>Uc,resubscribePath:()=>Na,seatMember:()=>qi,selectMount:()=>mr,serverDeadlinePassed:()=>oa,serverMsUntil:()=>aa,serverNow:()=>Ur,setAnchor:()=>qr,setCachedToken:()=>$o,setQueryClient:()=>wa,setScope:()=>Xo,setupRequireShim:()=>Fu,signal:()=>Au,startTracking:()=>_s,steerTurn:()=>_u,submitForm:()=>bu,subscribeAnchor:()=>si,subscribeArtifactStream:()=>bs,subscribeMounts:()=>Qr,subscribeScope:()=>we,subscribeToEvents:()=>re,subscribeToPath:()=>zr,subscribeToScope:()=>Sn,trackAction:()=>pu,trackEvent:()=>Nt,trackPageView:()=>fu,unmountRealtimeScope:()=>ls,updateItem:()=>Tu,uploadFile:()=>Vu,useAcceptInvite:()=>Qu,useAccounts:()=>Ic,useAgentTimeline:()=>zu,useAllChannels:()=>gs,useAnswerInput:()=>Nu,useArrangement:()=>In,useArtifactStream:()=>Gu,useAsset:()=>kc,useAuth:()=>hs,useChannelMessages:()=>Vc,useChannels:()=>Bc,useChildren:()=>pc,useComponent:()=>Ci,useCreate:()=>zc,useCreateAgent:()=>Uu,useDelete:()=>Xc,useDmChannels:()=>Hc,useEdges:()=>bc,useEventStream:()=>nu,useFileUpload:()=>Wu,useIncrementalItems:()=>_c,useInfiniteChannelMessages:()=>$c,useInfiniteChildren:()=>vc,useInfiniteItems:()=>Pi,useInviteMember:()=>qu,useItem:()=>dc,useItemById:()=>fc,useItemHistory:()=>Cc,useItemVersions:()=>Pc,useItems:()=>yc,useLink:()=>eu,useList:()=>xi,useMemberFocus:()=>xc,useMintedAsset:()=>su,useMounts:()=>Ac,useMove:()=>Zc,useMutation:()=>tu,useNotifications:()=>Ti,useOpen:()=>Sc,usePermission:()=>qc,usePermissions:()=>Qc,usePersonalItemOrder:()=>ou,usePersonalSections:()=>el,usePinnedItems:()=>Yu,usePrincipal:()=>Nc,useRealtimeQuery:()=>ru,useRecentActivity:()=>Tc,useResolve:()=>gc,useResolvedItems:()=>Hu,useScope:()=>Ec,useScopeReady:()=>lc,useSearch:()=>hc,useSeatMember:()=>Du,useTheme:()=>Fc,useTimelineHistory:()=>Ju,useTool:()=>Kc,useTree:()=>mc,useType:()=>wc,useTypeHelpers:()=>Rc,useTypes:()=>ms,useUnreadCounts:()=>Gc,useUpdate:()=>Jc,useUpdatePrincipal:()=>Yc,vfsKeys:()=>P,waitForPathReady:()=>Ua});var rt=class e extends Error{constructor(n){let r=n.message||e.fallbackMessage(n);super(r);te(this,"name","EnforcementDeniedError");te(this,"deniedBy");te(this,"ruleKey");te(this,"displayName");this.deniedBy=n.denied_by||n.error_type||n.error||"unknown";let s=n.enforcement;this.ruleKey=s?.rule_key??void 0,this.displayName=s?.display_name??void 0}static fallbackMessage(n){let r=n.error||"",s=n.denied_by||"";return s==="rule"||r==="RULE_DENIED"?"This feature is not enabled for this workspace.":s==="entitlement"||r==="ENTITLEMENT_REQUIRED"?"This feature requires a plan upgrade.":s==="access"||r==="ACCESS_DENIED"||r==="PERMISSION_DENIED"?"You don't have permission to do this.":"This action is not allowed."}get isRuleDenial(){return this.deniedBy==="rule"||this.deniedBy==="RULE_DENIED"}get isAccessDenial(){return this.deniedBy==="access"||this.deniedBy==="ACCESS_DENIED"}get isEntitlementDenial(){return this.deniedBy==="entitlement"||this.deniedBy==="ENTITLEMENT_REQUIRED"}};var An=X(ae(),1);var xe=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var bt,st,Lt,Gi,pl=(Gi=class extends xe{constructor(){super();C(this,bt);C(this,st);C(this,Lt);w(this,Lt,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){l(this,st)||this.setEventListener(l(this,Lt))}onUnsubscribe(){var t;this.hasListeners()||((t=l(this,st))==null||t.call(this),w(this,st,void 0))}setEventListener(t){var n;w(this,Lt,t),(n=l(this,st))==null||n.call(this),w(this,st,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){l(this,bt)!==t&&(w(this,bt,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof l(this,bt)=="boolean"?l(this,bt):globalThis.document?.visibilityState!=="hidden"}},bt=new WeakMap,st=new WeakMap,Lt=new WeakMap,Gi),jt=new pl;var ml={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},it,Ts,zi,hl=(zi=class{constructor(){C(this,it,ml);C(this,Ts,!1)}setTimeoutProvider(e){w(this,it,e)}setTimeout(e,t){return l(this,it).setTimeout(e,t)}clearTimeout(e){l(this,it).clearTimeout(e)}setInterval(e,t){return l(this,it).setInterval(e,t)}clearInterval(e){l(this,it).clearInterval(e)}},it=new WeakMap,Ts=new WeakMap,zi),Qe=new hl;function Ji(e){setTimeout(e,0)}var Is=typeof window>"u"||"Deno"in globalThis;function G(){}function Zi(e,t){return typeof e=="function"?e(t):e}function Dn(e){return typeof e=="number"&&e>=0&&e!==1/0}function br(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Me(e,t){return typeof e=="function"?e(t):e}function me(e,t){return typeof e=="function"?e(t):e}function wr(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:o,stale:c}=e;if(o){if(r){if(t.queryHash!==Un(o,t.options))return!1}else if(!wt(t.queryKey,o))return!1}if(n!=="all"){let a=t.isActive();if(n==="active"&&!a||n==="inactive"&&a)return!1}return!(typeof c=="boolean"&&t.isStale()!==c||s&&s!==t.state.fetchStatus||i&&!i(t))}function Sr(e,t){let{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(De(t.options.mutationKey)!==De(i))return!1}else if(!wt(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function Un(e,t){return(t?.queryKeyHashFn||De)(e)}function De(e){return JSON.stringify(e,(t,n)=>Es(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function wt(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>wt(e[n],t[n])):!1}var gl=Object.prototype.hasOwnProperty;function As(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=Yi(e)&&Yi(t);if(!r&&!(Es(e)&&Es(t)))return t;let i=(r?e:Object.keys(e)).length,o=r?t:Object.keys(t),c=o.length,a=r?new Array(c):{},u=0;for(let d=0;d<c;d++){let p=r?d:o[d],m=e[p],f=t[p];if(m===f){a[p]=m,(r?d<i:gl.call(e,p))&&u++;continue}if(m===null||f===null||typeof m!="object"||typeof f!="object"){a[p]=f;continue}let y=As(m,f,n+1);a[p]=y,y===m&&u++}return i===c&&u===i?e:a}function Vt(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function Yi(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Es(e){if(!Xi(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Xi(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Xi(e){return Object.prototype.toString.call(e)==="[object Object]"}function eo(e){return new Promise(t=>{Qe.setTimeout(t,e)})}function Nn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?As(e,t):t}function to(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function no(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var $t=Symbol();function Rr(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===$t?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Wt(e,t){return typeof e=="function"?e(...t):!!e}function ro(e,t,n){let r=!1,s;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(s??(s=t()),r||(r=!0,s.aborted?n():s.addEventListener("abort",n,{once:!0})),s)}),e}var Ue=(()=>{let e=()=>Is;return{isServer(){return e()},setIsServer(t){e=t}}})();function Kn(){let e,t,n=new Promise((s,i)=>{e=s,t=i});n.status="pending",n.catch(()=>{});function r(s){Object.assign(n,s),delete n.resolve,delete n.reject}return n.resolve=s=>{r({status:"fulfilled",value:s}),e(s)},n.reject=s=>{r({status:"rejected",reason:s}),t(s)},n}var so=Ji;function yl(){let e=[],t=0,n=c=>{c()},r=c=>{c()},s=so,i=c=>{t?e.push(c):s(()=>{n(c)})},o=()=>{let c=e;e=[],c.length&&s(()=>{r(()=>{c.forEach(a=>{n(a)})})})};return{batch:c=>{let a;t++;try{a=c()}finally{t--,t||o()}return a},batchCalls:c=>(...a)=>{i(()=>{c(...a)})},schedule:i,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{r=c},setScheduler:c=>{s=c}}}var V=yl();var Bt,ot,Ht,io,_l=(io=class extends xe{constructor(){super();C(this,Bt,!0);C(this,ot);C(this,Ht);w(this,Ht,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){l(this,ot)||this.setEventListener(l(this,Ht))}onUnsubscribe(){var t;this.hasListeners()||((t=l(this,ot))==null||t.call(this),w(this,ot,void 0))}setEventListener(t){var n;w(this,Ht,t),(n=l(this,ot))==null||n.call(this),w(this,ot,t(this.setOnline.bind(this)))}setOnline(t){l(this,Bt)!==t&&(w(this,Bt,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return l(this,Bt)}},Bt=new WeakMap,ot=new WeakMap,Ht=new WeakMap,io),Gt=new _l;function vl(e){return Math.min(1e3*2**e,3e4)}function ks(e){return(e??"online")==="online"?Gt.isOnline():!0}var xr=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Pr(e){let t=!1,n=0,r,s=Kn(),i=()=>s.status!=="pending",o=g=>{if(!i()){let h=new xr(g);m(h),e.onCancel?.(h)}},c=()=>{t=!0},a=()=>{t=!1},u=()=>jt.isFocused()&&(e.networkMode==="always"||Gt.isOnline())&&e.canRun(),d=()=>ks(e.networkMode)&&e.canRun(),p=g=>{i()||(r?.(),s.resolve(g))},m=g=>{i()||(r?.(),s.reject(g))},f=()=>new Promise(g=>{r=h=>{(i()||u())&&g(h)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),y=()=>{if(i())return;let g,h=n===0?e.initialPromise:void 0;try{g=h??e.fn()}catch(v){g=Promise.reject(v)}Promise.resolve(g).then(p).catch(v=>{if(i())return;let b=e.retry??(Ue.isServer()?0:3),E=e.retryDelay??vl,I=typeof E=="function"?E(n,v):E,R=b===!0||typeof b=="number"&&n<b||typeof b=="function"&&b(n,v);if(t||!R){m(v);return}n++,e.onFail?.(n,v),eo(I).then(()=>u()?void 0:f()).then(()=>{t?m(v):y()})})};return{promise:s,status:()=>s.status,cancel:o,continue:()=>(r?.(),s),cancelRetry:c,continueRetry:a,canStart:d,start:()=>(d()?y():f().then(y),s)}}var St,oo,Cr=(oo=class{constructor(){C(this,St)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Dn(this.gcTime)&&w(this,St,Qe.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ue.isServer()?1/0:5*60*1e3))}clearGcTimeout(){l(this,St)!==void 0&&(Qe.clearTimeout(l(this,St)),w(this,St,void 0))}},St=new WeakMap,oo);var Rt,zt,Pe,xt,se,Ln,Pt,be,fo,$e,uo,lo=(uo=class extends Cr{constructor(t){super();C(this,be);C(this,Rt);C(this,zt);C(this,Pe);C(this,xt);C(this,se);C(this,Ln);C(this,Pt);w(this,Pt,!1),w(this,Ln,t.defaultOptions),this.setOptions(t.options),this.observers=[],w(this,xt,t.client),w(this,Pe,l(this,xt).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,w(this,Rt,co(this.options)),this.state=t.state??l(this,Rt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return l(this,se)?.promise}setOptions(t){if(this.options={...l(this,Ln),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=co(this.options);n.data!==void 0&&(this.setState(ao(n.data,n.dataUpdatedAt)),w(this,Rt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&l(this,Pe).remove(this)}setData(t,n){let r=Nn(this.state.data,t,this.options);return q(this,be,$e).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){q(this,be,$e).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=l(this,se)?.promise;return l(this,se)?.cancel(t),n?n.then(G).catch(G):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return l(this,Rt)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>me(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===$t||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>Me(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!br(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),l(this,se)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),l(this,se)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),l(this,Pe).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(l(this,se)&&(l(this,Pt)||q(this,be,fo).call(this)?l(this,se).cancel({revert:!0}):l(this,se).cancelRetry()),this.scheduleGc()),l(this,Pe).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||q(this,be,$e).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&l(this,se)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(l(this,se))return l(this,se).continueRetry(),l(this,se).promise}if(t&&this.setOptions(t),!this.options.queryFn){let a=this.observers.find(u=>u.options.queryFn);a&&this.setOptions(a.options)}let r=new AbortController,s=a=>{Object.defineProperty(a,"signal",{enumerable:!0,get:()=>(w(this,Pt,!0),r.signal)})},i=()=>{let a=Rr(this.options,n),d=(()=>{let p={client:l(this,xt),queryKey:this.queryKey,meta:this.meta};return s(p),p})();return w(this,Pt,!1),this.options.persister?this.options.persister(a,d,this):a(d)},c=(()=>{let a={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:l(this,xt),state:this.state,fetchFn:i};return s(a),a})();this.options.behavior?.onFetch(c,this),w(this,zt,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==c.fetchOptions?.meta)&&q(this,be,$e).call(this,{type:"fetch",meta:c.fetchOptions?.meta}),w(this,se,Pr({initialPromise:n?.initialPromise,fn:c.fetchFn,onCancel:a=>{a instanceof xr&&a.revert&&this.setState({...l(this,zt),fetchStatus:"idle"}),r.abort()},onFail:(a,u)=>{q(this,be,$e).call(this,{type:"failed",failureCount:a,error:u})},onPause:()=>{q(this,be,$e).call(this,{type:"pause"})},onContinue:()=>{q(this,be,$e).call(this,{type:"continue"})},retry:c.options.retry,retryDelay:c.options.retryDelay,networkMode:c.options.networkMode,canRun:()=>!0}));try{let a=await l(this,se).start();if(a===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(a),l(this,Pe).config.onSuccess?.(a,this),l(this,Pe).config.onSettled?.(a,this.state.error,this),a}catch(a){if(a instanceof xr){if(a.silent)return l(this,se).promise;if(a.revert){if(this.state.data===void 0)throw a;return this.state.data}}throw q(this,be,$e).call(this,{type:"error",error:a}),l(this,Pe).config.onError?.(a,this),l(this,Pe).config.onSettled?.(this.state.data,a,this),a}finally{this.scheduleGc()}}},Rt=new WeakMap,zt=new WeakMap,Pe=new WeakMap,xt=new WeakMap,se=new WeakMap,Ln=new WeakMap,Pt=new WeakMap,be=new WeakSet,fo=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},$e=function(t){let n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...Ms(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...ao(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return w(this,zt,t.manual?s:void 0),s;case"error":let i=t.error;return{...r,error:i,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),V.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),l(this,Pe).notify({query:this,type:"updated",action:t})})},uo);function Ms(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ks(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function ao(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function co(e){let t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var he,K,Vn,de,Ct,Jt,We,at,$n,Yt,Xt,Tt,Et,ct,Zt,j,jn,Os,Fs,qs,Qs,Ds,Us,Ns,go,ho,Wn=(ho=class extends xe{constructor(t,n){super();C(this,j);C(this,he);C(this,K);C(this,Vn);C(this,de);C(this,Ct);C(this,Jt);C(this,We);C(this,at);C(this,$n);C(this,Yt);C(this,Xt);C(this,Tt);C(this,Et);C(this,ct);C(this,Zt,new Set);this.options=n,w(this,he,t),w(this,at,null),w(this,We,Kn()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(l(this,K).addObserver(this),po(l(this,K),this.options)?q(this,j,jn).call(this):this.updateResult(),q(this,j,Qs).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ks(l(this,K),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ks(l(this,K),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,q(this,j,Ds).call(this),q(this,j,Us).call(this),l(this,K).removeObserver(this)}setOptions(t){let n=this.options,r=l(this,K);if(this.options=l(this,he).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof me(this.options.enabled,l(this,K))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");q(this,j,Ns).call(this),l(this,K).setOptions(this.options),n._defaulted&&!Vt(this.options,n)&&l(this,he).getQueryCache().notify({type:"observerOptionsUpdated",query:l(this,K),observer:this});let s=this.hasListeners();s&&mo(l(this,K),r,this.options,n)&&q(this,j,jn).call(this),this.updateResult(),s&&(l(this,K)!==r||me(this.options.enabled,l(this,K))!==me(n.enabled,l(this,K))||Me(this.options.staleTime,l(this,K))!==Me(n.staleTime,l(this,K)))&&q(this,j,Os).call(this);let i=q(this,j,Fs).call(this);s&&(l(this,K)!==r||me(this.options.enabled,l(this,K))!==me(n.enabled,l(this,K))||i!==l(this,ct))&&q(this,j,qs).call(this,i)}getOptimisticResult(t){let n=l(this,he).getQueryCache().build(l(this,he),t),r=this.createResult(n,t);return wl(this,r)&&(w(this,de,r),w(this,Jt,this.options),w(this,Ct,l(this,K).state)),r}getCurrentResult(){return l(this,de)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&l(this,We).status==="pending"&&l(this,We).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){l(this,Zt).add(t)}getCurrentQuery(){return l(this,K)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=l(this,he).defaultQueryOptions(t),r=l(this,he).getQueryCache().build(l(this,he),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return q(this,j,jn).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),l(this,de)))}createResult(t,n){let r=l(this,K),s=this.options,i=l(this,de),o=l(this,Ct),c=l(this,Jt),u=t!==r?t.state:l(this,Vn),{state:d}=t,p={...d},m=!1,f;if(n._optimisticResults){let T=this.hasListeners(),F=!T&&po(t,n),k=T&&mo(t,r,n,s);(F||k)&&(p={...p,...Ms(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(p.fetchStatus="idle")}let{error:y,errorUpdatedAt:g,status:h}=p;f=p.data;let v=!1;if(n.placeholderData!==void 0&&f===void 0&&h==="pending"){let T;i?.isPlaceholderData&&n.placeholderData===c?.placeholderData?(T=i.data,v=!0):T=typeof n.placeholderData=="function"?n.placeholderData(l(this,Xt)?.state.data,l(this,Xt)):n.placeholderData,T!==void 0&&(h="success",f=Nn(i?.data,T,n),m=!0)}if(n.select&&f!==void 0&&!v)if(i&&f===o?.data&&n.select===l(this,$n))f=l(this,Yt);else try{w(this,$n,n.select),f=n.select(f),f=Nn(i?.data,f,n),w(this,Yt,f),w(this,at,null)}catch(T){w(this,at,T)}l(this,at)&&(y=l(this,at),f=l(this,Yt),g=Date.now(),h="error");let b=p.fetchStatus==="fetching",E=h==="pending",I=h==="error",R=E&&b,M=f!==void 0,S={status:h,fetchStatus:p.fetchStatus,isPending:E,isSuccess:h==="success",isError:I,isInitialLoading:R,isLoading:R,data:f,dataUpdatedAt:p.dataUpdatedAt,error:y,errorUpdatedAt:g,failureCount:p.fetchFailureCount,failureReason:p.fetchFailureReason,errorUpdateCount:p.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:p.dataUpdateCount>u.dataUpdateCount||p.errorUpdateCount>u.errorUpdateCount,isFetching:b,isRefetching:b&&!E,isLoadingError:I&&!M,isPaused:p.fetchStatus==="paused",isPlaceholderData:m,isRefetchError:I&&M,isStale:Ls(t,n),refetch:this.refetch,promise:l(this,We),isEnabled:me(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let T=S.data!==void 0,F=S.status==="error"&&!T,k=Q=>{F?Q.reject(S.error):T&&Q.resolve(S.data)},A=()=>{let Q=w(this,We,S.promise=Kn());k(Q)},U=l(this,We);switch(U.status){case"pending":t.queryHash===r.queryHash&&k(U);break;case"fulfilled":(F||S.data!==U.value)&&A();break;case"rejected":(!F||S.error!==U.reason)&&A();break}}return S}updateResult(){let t=l(this,de),n=this.createResult(l(this,K),this.options);if(w(this,Ct,l(this,K).state),w(this,Jt,this.options),l(this,Ct).data!==void 0&&w(this,Xt,l(this,K)),Vt(n,t))return;w(this,de,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!l(this,Zt).size)return!0;let o=new Set(i??l(this,Zt));return this.options.throwOnError&&o.add("error"),Object.keys(l(this,de)).some(c=>{let a=c;return l(this,de)[a]!==t[a]&&o.has(a)})};q(this,j,go).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&q(this,j,Qs).call(this)}},he=new WeakMap,K=new WeakMap,Vn=new WeakMap,de=new WeakMap,Ct=new WeakMap,Jt=new WeakMap,We=new WeakMap,at=new WeakMap,$n=new WeakMap,Yt=new WeakMap,Xt=new WeakMap,Tt=new WeakMap,Et=new WeakMap,ct=new WeakMap,Zt=new WeakMap,j=new WeakSet,jn=function(t){q(this,j,Ns).call(this);let n=l(this,K).fetch(this.options,t);return t?.throwOnError||(n=n.catch(G)),n},Os=function(){q(this,j,Ds).call(this);let t=Me(this.options.staleTime,l(this,K));if(Ue.isServer()||l(this,de).isStale||!Dn(t))return;let r=br(l(this,de).dataUpdatedAt,t)+1;w(this,Tt,Qe.setTimeout(()=>{l(this,de).isStale||this.updateResult()},r))},Fs=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(l(this,K)):this.options.refetchInterval)??!1},qs=function(t){q(this,j,Us).call(this),w(this,ct,t),!(Ue.isServer()||me(this.options.enabled,l(this,K))===!1||!Dn(l(this,ct))||l(this,ct)===0)&&w(this,Et,Qe.setInterval(()=>{(this.options.refetchIntervalInBackground||jt.isFocused())&&q(this,j,jn).call(this)},l(this,ct)))},Qs=function(){q(this,j,Os).call(this),q(this,j,qs).call(this,q(this,j,Fs).call(this))},Ds=function(){l(this,Tt)!==void 0&&(Qe.clearTimeout(l(this,Tt)),w(this,Tt,void 0))},Us=function(){l(this,Et)!==void 0&&(Qe.clearInterval(l(this,Et)),w(this,Et,void 0))},Ns=function(){let t=l(this,he).getQueryCache().build(l(this,he),this.options);if(t===l(this,K))return;let n=l(this,K);w(this,K,t),w(this,Vn,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},go=function(t){V.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(l(this,de))}),l(this,he).getQueryCache().notify({query:l(this,K),type:"observerResultsUpdated"})})},ho);function bl(e,t){return me(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function po(e,t){return bl(e,t)||e.state.data!==void 0&&Ks(e,t,t.refetchOnMount)}function Ks(e,t,n){if(me(t.enabled,e)!==!1&&Me(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Ls(e,t)}return!1}function mo(e,t,n,r){return(e!==t||me(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Ls(e,n)}function Ls(e,t){return me(t.enabled,e)!==!1&&e.isStaleByTime(Me(t.staleTime,e))}function wl(e,t){return!Vt(e.getCurrentResult(),t)}function en(e){return{onFetch:(t,n)=>{let r=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],o=t.state.data?.pageParams||[],c={pages:[],pageParams:[]},a=0,u=async()=>{let d=!1,p=y=>{ro(y,()=>t.signal,()=>d=!0)},m=Rr(t.options,t.fetchOptions),f=async(y,g,h)=>{if(d)return Promise.reject();if(g==null&&y.pages.length)return Promise.resolve(y);let b=(()=>{let M={client:t.client,queryKey:t.queryKey,pageParam:g,direction:h?"backward":"forward",meta:t.options.meta};return p(M),M})(),E=await m(b),{maxPages:I}=t.options,R=h?no:to;return{pages:R(y.pages,E,I),pageParams:R(y.pageParams,g,I)}};if(s&&i.length){let y=s==="backward",g=y?yo:js,h={pages:i,pageParams:o},v=g(r,h);c=await f(h,v,y)}else{let y=e??i.length;do{let g=a===0?o[0]??r.initialPageParam:js(r,c);if(a>0&&g==null)break;c=await f(c,g),a++}while(a<y)}return c};t.options.persister?t.fetchFn=()=>t.options.persister?.(u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=u}}}function js(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function yo(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function _o(e,t){return t?js(e,t)!=null:!1}function vo(e,t){return!t||!e.getPreviousPageParam?!1:yo(e,t)!=null}var Vs=class extends Wn{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){super.setOptions({...e,behavior:en()})}getOptimisticResult(e){return e.behavior=en(),super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){let{state:n}=e,r=super.createResult(e,t),{isFetching:s,isRefetching:i,isError:o,isRefetchError:c}=r,a=n.fetchMeta?.fetchMore?.direction,u=o&&a==="forward",d=s&&a==="forward",p=o&&a==="backward",m=s&&a==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:_o(t,n.data),hasPreviousPage:vo(t,n.data),isFetchNextPageError:u,isFetchingNextPage:d,isFetchPreviousPageError:p,isFetchingPreviousPage:m,isRefetchError:c&&!u&&!p,isRefetching:i&&!d&&!m}}};var Bn,Ne,ce,It,Ke,ut,bo,wo=(bo=class extends Cr{constructor(t){super();C(this,Ke);C(this,Bn);C(this,Ne);C(this,ce);C(this,It);w(this,Bn,t.client),this.mutationId=t.mutationId,w(this,ce,t.mutationCache),w(this,Ne,[]),this.state=t.state||$s(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){l(this,Ne).includes(t)||(l(this,Ne).push(t),this.clearGcTimeout(),l(this,ce).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){w(this,Ne,l(this,Ne).filter(n=>n!==t)),this.scheduleGc(),l(this,ce).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){l(this,Ne).length||(this.state.status==="pending"?this.scheduleGc():l(this,ce).remove(this))}continue(){return l(this,It)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{q(this,Ke,ut).call(this,{type:"continue"})},r={client:l(this,Bn),meta:this.options.meta,mutationKey:this.options.mutationKey};w(this,It,Pr({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(o,c)=>{q(this,Ke,ut).call(this,{type:"failed",failureCount:o,error:c})},onPause:()=>{q(this,Ke,ut).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>l(this,ce).canRun(this)}));let s=this.state.status==="pending",i=!l(this,It).canStart();try{if(s)n();else{q(this,Ke,ut).call(this,{type:"pending",variables:t,isPaused:i}),l(this,ce).config.onMutate&&await l(this,ce).config.onMutate(t,this,r);let c=await this.options.onMutate?.(t,r);c!==this.state.context&&q(this,Ke,ut).call(this,{type:"pending",context:c,variables:t,isPaused:i})}let o=await l(this,It).start();return await l(this,ce).config.onSuccess?.(o,t,this.state.context,this,r),await this.options.onSuccess?.(o,t,this.state.context,r),await l(this,ce).config.onSettled?.(o,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(o,null,t,this.state.context,r),q(this,Ke,ut).call(this,{type:"success",data:o}),o}catch(o){try{await l(this,ce).config.onError?.(o,t,this.state.context,this,r)}catch(c){Promise.reject(c)}try{await this.options.onError?.(o,t,this.state.context,r)}catch(c){Promise.reject(c)}try{await l(this,ce).config.onSettled?.(void 0,o,this.state.variables,this.state.context,this,r)}catch(c){Promise.reject(c)}try{await this.options.onSettled?.(void 0,o,t,this.state.context,r)}catch(c){Promise.reject(c)}throw q(this,Ke,ut).call(this,{type:"error",error:o}),o}finally{l(this,ce).runNext(this)}}},Bn=new WeakMap,Ne=new WeakMap,ce=new WeakMap,It=new WeakMap,Ke=new WeakSet,ut=function(t){let n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),V.batch(()=>{l(this,Ne).forEach(r=>{r.onMutationUpdate(t)}),l(this,ce).notify({mutation:this,type:"updated",action:t})})},bo);function $s(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Be,Oe,Hn,So,Ro=(So=class extends xe{constructor(t={}){super();C(this,Be);C(this,Oe);C(this,Hn);this.config=t,w(this,Be,new Set),w(this,Oe,new Map),w(this,Hn,0)}build(t,n,r){let s=new wo({client:t,mutationCache:this,mutationId:++Qn(this,Hn)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){l(this,Be).add(t);let n=Tr(t);if(typeof n=="string"){let r=l(this,Oe).get(n);r?r.push(t):l(this,Oe).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(l(this,Be).delete(t)){let n=Tr(t);if(typeof n=="string"){let r=l(this,Oe).get(n);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&l(this,Oe).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=Tr(t);if(typeof n=="string"){let s=l(this,Oe).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=Tr(t);return typeof n=="string"?l(this,Oe).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){V.batch(()=>{l(this,Be).forEach(t=>{this.notify({type:"removed",mutation:t})}),l(this,Be).clear(),l(this,Oe).clear()})}getAll(){return Array.from(l(this,Be))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Sr(n,r))}findAll(t={}){return this.getAll().filter(n=>Sr(t,n))}notify(t){V.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){let t=this.getAll().filter(n=>n.state.isPaused);return V.batch(()=>Promise.all(t.map(n=>n.continue().catch(G))))}},Be=new WeakMap,Oe=new WeakMap,Hn=new WeakMap,So);function Tr(e){return e.options.scope?.id}var He,lt,ge,Ge,ze,Er,Ws,xo,Bs=(xo=class extends xe{constructor(t,n){super();C(this,ze);C(this,He);C(this,lt);C(this,ge);C(this,Ge);w(this,He,t),this.setOptions(n),this.bindMethods(),q(this,ze,Er).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let n=this.options;this.options=l(this,He).defaultMutationOptions(t),Vt(this.options,n)||l(this,He).getMutationCache().notify({type:"observerOptionsUpdated",mutation:l(this,ge),observer:this}),n?.mutationKey&&this.options.mutationKey&&De(n.mutationKey)!==De(this.options.mutationKey)?this.reset():l(this,ge)?.state.status==="pending"&&l(this,ge).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||l(this,ge)?.removeObserver(this)}onMutationUpdate(t){q(this,ze,Er).call(this),q(this,ze,Ws).call(this,t)}getCurrentResult(){return l(this,lt)}reset(){l(this,ge)?.removeObserver(this),w(this,ge,void 0),q(this,ze,Er).call(this),q(this,ze,Ws).call(this)}mutate(t,n){return w(this,Ge,n),l(this,ge)?.removeObserver(this),w(this,ge,l(this,He).getMutationCache().build(l(this,He),this.options)),l(this,ge).addObserver(this),l(this,ge).execute(t)}},He=new WeakMap,lt=new WeakMap,ge=new WeakMap,Ge=new WeakMap,ze=new WeakSet,Er=function(){let t=l(this,ge)?.state??$s();w(this,lt,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},Ws=function(t){V.batch(()=>{if(l(this,Ge)&&this.hasListeners()){let n=l(this,lt).variables,r=l(this,lt).context,s={client:l(this,He),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{l(this,Ge).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{l(this,Ge).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{l(this,Ge).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{l(this,Ge).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(l(this,lt))})})},xo);var Le,Po,Co=(Po=class extends xe{constructor(t={}){super();C(this,Le);this.config=t,w(this,Le,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??Un(s,n),o=this.get(i);return o||(o=new lo({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(o)),o}add(t){l(this,Le).has(t.queryHash)||(l(this,Le).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=l(this,Le).get(t.queryHash);n&&(t.destroy(),n===t&&l(this,Le).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){V.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return l(this,Le).get(t)}getAll(){return[...l(this,Le).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>wr(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>wr(t,r)):n}notify(t){V.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){V.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){V.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Le=new WeakMap,Po);var z,dt,ft,tn,nn,pt,rn,sn,To,Hs=(To=class{constructor(e={}){C(this,z);C(this,dt);C(this,ft);C(this,tn);C(this,nn);C(this,pt);C(this,rn);C(this,sn);w(this,z,e.queryCache||new Co),w(this,dt,e.mutationCache||new Ro),w(this,ft,e.defaultOptions||{}),w(this,tn,new Map),w(this,nn,new Map),w(this,pt,0)}mount(){Qn(this,pt)._++,l(this,pt)===1&&(w(this,rn,jt.subscribe(async e=>{e&&(await this.resumePausedMutations(),l(this,z).onFocus())})),w(this,sn,Gt.subscribe(async e=>{e&&(await this.resumePausedMutations(),l(this,z).onOnline())})))}unmount(){var e,t;Qn(this,pt)._--,l(this,pt)===0&&((e=l(this,rn))==null||e.call(this),w(this,rn,void 0),(t=l(this,sn))==null||t.call(this),w(this,sn,void 0))}isFetching(e){return l(this,z).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return l(this,dt).findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return l(this,z).get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=l(this,z).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Me(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return l(this,z).findAll(e).map(({queryKey:t,state:n})=>{let r=n.data;return[t,r]})}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=l(this,z).get(r.queryHash)?.state.data,o=Zi(t,i);if(o!==void 0)return l(this,z).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return V.batch(()=>l(this,z).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return l(this,z).get(t.queryHash)?.state}removeQueries(e){let t=l(this,z);V.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=l(this,z);return V.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=V.batch(()=>l(this,z).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(G).catch(G)}invalidateQueries(e,t={}){return V.batch(()=>(l(this,z).findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=V.batch(()=>l(this,z).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(G)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(G)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=l(this,z).build(this,t);return n.isStaleByTime(Me(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(G).catch(G)}fetchInfiniteQuery(e){return e.behavior=en(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(G).catch(G)}ensureInfiniteQueryData(e){return e.behavior=en(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Gt.isOnline()?l(this,dt).resumePausedMutations():Promise.resolve()}getQueryCache(){return l(this,z)}getMutationCache(){return l(this,dt)}getDefaultOptions(){return l(this,ft)}setDefaultOptions(e){w(this,ft,e)}setQueryDefaults(e,t){l(this,tn).set(De(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...l(this,tn).values()],n={};return t.forEach(r=>{wt(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){l(this,nn).set(De(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...l(this,nn).values()],n={};return t.forEach(r=>{wt(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...l(this,ft).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Un(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===$t&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...l(this,ft).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){l(this,z).clear(),l(this,dt).clear()}},z=new WeakMap,dt=new WeakMap,ft=new WeakMap,tn=new WeakMap,nn=new WeakMap,pt=new WeakMap,rn=new WeakMap,sn=new WeakMap,To);var on=X(ae(),1),Io=X(Ir(),1),Gs=on.createContext(void 0),L=e=>{let t=on.useContext(Gs);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Gn=({client:e,children:t})=>(on.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,Io.jsx)(Gs.Provider,{value:e,children:t}));var Ar=X(ae(),1),Ao=Ar.createContext(!1),ko=()=>Ar.useContext(Ao),kp=Ao.Provider;var zn=X(ae(),1),Sl=X(Ir(),1);function Rl(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var xl=zn.createContext(Rl()),Mo=()=>zn.useContext(xl);var Oo=X(ae(),1);var Fo=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?Wt(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},qo=e=>{Oo.useEffect(()=>{e.clearReset()},[e])},Qo=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||Wt(n,[e.error,r]));var Do=e=>{if(e.suspense){let n=s=>s==="static"?s:Math.max(s??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...s)=>n(r(...s)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},Uo=(e,t)=>e.isLoading&&e.isFetching&&!t,No=(e,t)=>e?.suspense&&t.isPending,zs=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var mt=X(ae(),1);function kr(e,t,n){let r=ko(),s=Mo(),i=L(n),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let c=i.getQueryCache().get(o.queryHash);o._optimisticResults=r?"isRestoring":"optimistic",Do(o),Fo(o,s,c),qo(s);let a=!i.getQueryCache().get(o.queryHash),[u]=mt.useState(()=>new t(i,o)),d=u.getOptimisticResult(o),p=!r&&e.subscribed!==!1;if(mt.useSyncExternalStore(mt.useCallback(m=>{let f=p?u.subscribe(V.batchCalls(m)):G;return u.updateResult(),f},[u,p]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),mt.useEffect(()=>{u.setOptions(o)},[o,u]),No(o,d))throw zs(o,u,s);if(Qo({result:d,errorResetBoundary:s,throwOnError:o.throwOnError,query:c,suspense:o.suspense}))throw d.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(o,d),o.experimental_prefetchInRender&&!Ue.isServer()&&Uo(d,r)&&(a?zs(o,u,s):c?.promise)?.catch(G).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?d:u.trackResult(d)}function $(e,t){return kr(e,Wn,t)}var Je=X(ae(),1);function Z(e,t){let n=L(t),[r]=Je.useState(()=>new Bs(n,e));Je.useEffect(()=>{r.setOptions(e)},[r,e]);let s=Je.useSyncExternalStore(Je.useCallback(o=>r.subscribe(V.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=Je.useCallback((o,c)=>{r.mutate(o,c).catch(G)},[r]);if(s.error&&Wt(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function Jn(e,t){return kr(e,Vs,t)}var jo=X(Lo(),1),Yn=typeof window<"u"&&window.__FSAOS_CONFIG__||{},At=Array.isArray(Yn.sources)?Yn.sources:[],Pl=Yn.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",Cl=Yn.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",Ce=Yn.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",W=(0,jo.createClient)(Pl,Cl,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var Xn=null,Mr=0,Vo,Zs,Or=!1;Vo=new Promise(e=>{Zs=e});W.auth.onAuthStateChange((e,t)=>{t?.access_token?(Xn=t.access_token,Mr=t.expires_at??Math.floor(Date.now()/1e3)+3600):(Xn=null,Mr=0),Or||(Or=!0,Zs())});setTimeout(()=>{Or||(Or=!0,Zs())},5e3);function $o(e,t){Xn=e,Mr=t??Math.floor(Date.now()/1e3)+3600}function ei(){Xn=null,Mr=0}async function Ye(){let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{};if(e.embedToken){if(typeof e.embedToken=="function")try{return await e.embedToken()??null}catch{return null}return e.embedToken}return await Vo,Xn}var ln=null,dn=null,Wo=0,Js=new Set,ti,Zn,fn=!1;ti=new Promise(e=>{Zn=e});function ni(){Wo++,Js.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function qr(e){let t=typeof e=="string"?e:e.path,n=ln!==t||dn?.id!==(typeof e=="string"?void 0:e.id);ln=t,dn=typeof e=="string"?null:e,typeof e!="string"&&!kt.some(r=>r.id===e.id)&&(kt=[...kt,e],oi()),fn||(fn=!0,Zn()),n&&ni()}function pn(){return ln}function ye(){return dn}function ri(){return Wo}function si(e){return Js.add(e),()=>{Js.delete(e)}}function er(){return ti}function ii(){return fn}var Fr=null;function Mt(e,t={}){if(Fr){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}Fr=e,t.activate!==!1&&qr(e)}function fe(){return Fr}var kt=[],Ys=new Set,Bo=0;function oi(){Bo++,Ys.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function Te(){return kt}function tr(){return Bo}function Qr(e){return Ys.add(e),()=>{Ys.delete(e)}}function Ho(e,t){let n=JSON.stringify(kt)!==JSON.stringify(e),r=ln!==t.path||dn?.id!==t.id;kt=e,ln=t.path,dn=t,fn||(fn=!0,Zn()),n&&oi(),r&&ni()}var cn=null,an=null,un=0,Xs=new Set,Go=0;function zo(){Go++,Xs.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Session listener error:",t)}})}function ie(){return un}function ai(){return Go}function Jo(e){return Xs.add(e),()=>{Xs.delete(e)}}async function Xe(){if(cn)return cn;if(an)return an;let e=un;return an=(async()=>{let t=Ot(),n=await Ye();if(e!==un)throw new Error("Session changed during initialization");let r={};n&&(r.Authorization=`Bearer ${n}`);let s=await fetch(`${Ce}/d/${t}/init`,{method:"GET",headers:r});if(!s.ok)throw new Error(`Session init failed: ${s.status} ${s.statusText}`);let i=await s.json();if(e!==un)throw new Error("Session changed during initialization");let o=i.entry||i;return cn={scope_id:o.scope_id,scope_path:o.scope_path,instance_path:o.instance_path||"/root",fractal_id:o.fractal_id||null,instance_name:o.instance_name||null,display_name:o.scope_display_name||o.display_name||null,principal_id:o.principal_id||null},zo(),cn})().catch(t=>{throw e===un&&(an=null),t}),an}function ht(){return cn}function ci(){un++,cn=null,an=null,ln=null,dn=null,Fr=null,kt=[],zo()}var Yo=[];function ne(e){Yo.push(e)}function mn(){ci(),ei(),Zn(),fn=!1,ti=new Promise(e=>{Zn=e}),ni(),oi();for(let e of Yo)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function Ot(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var Xo=qr,H=pn,ee=ri,we=si,Zo=er,Dr=ii;var ui=0,ea=!1,ta=0;function na(e){if(typeof e!="string")return;let t=Date.parse(e);Number.isNaN(t)||(ui=t-Date.now(),ea=!0,ta=Date.now())}function Ur(){return Date.now()+ui}function ra(){return ea}function sa(){return ui}function ia(){return ta}function oa(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Ur()>=t}function aa(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Math.max(0,t-Ur())}var hn,Ee=new Map,Ft=[],li=0,di={foreground:0,normal:1,background:2},Nr=()=>performance.now(),fi=()=>new DOMException("Read cancelled","AbortError");function ua(e={}){hn={concurrency:Math.max(1,Math.min(16,Math.floor(e.concurrency??6))),timeoutMs:Math.max(1e3,e.timeoutMs??15e3),onTiming:e.onTiming},Lr()}function la(){for(let e of Ee.values()){e.controller.abort();for(let t of e.consumers)t.detach(),t.reject(fi());e.consumers.clear(),e.timer&&clearTimeout(e.timer)}Ee.clear(),Ft.length=0}function da(e,t){return e==="query"?!("materialize"in t):["read","list","search","resolve","resolve-items","get-channel-messages","list-memberships"].includes(e)}function Kr(e){return Array.isArray(e)?`[${e.map(Kr).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${Kr(n)}`).join(",")}}`:JSON.stringify(e)}function fa(e,t,n,r){if(n.signal?.aborted)return Promise.reject(fi());if(!hn)return r(n.signal);let s=Ee.get(e);if(s)di[n.priority??"normal"]<di[s.priority]&&(s.priority=n.priority??"normal");else{s={key:e,method:t,priority:n.priority??"normal",queuedAt:Nr(),controller:new AbortController,consumers:new Set,run:r},Ee.set(e,s),Ft.push(s);let c=s;s.timer=setTimeout(()=>{c.controller.abort();let a=new Error("The read timed out. Please retry.");a.name="TimeoutError";for(let u of c.consumers)u.detach(),u.reject(a);c.consumers.clear(),Ee.get(c.key)===c&&Ee.delete(c.key),ca(c)},hn.timeoutMs)}let i=s,o=new Promise((c,a)=>{let u=()=>{d.detach(),i.consumers.delete(d),a(fi()),i.consumers.size||(i.controller.abort(),Ee.get(i.key)===i&&Ee.delete(i.key),ca(i))},d={resolve:p=>c(structuredClone(p)),reject:a,detach:()=>n.signal?.removeEventListener("abort",u)};i.consumers.add(d),n.signal?.addEventListener("abort",u,{once:!0})});return Lr(),o}function ca(e){let t=Ft.indexOf(e);t>=0&&(Ft.splice(t,1),Ee.get(e.key)===e&&Ee.delete(e.key),e.timer&&clearTimeout(e.timer)),Lr()}function Lr(){if(hn)for(;li<hn.concurrency&&Ft.length;){let e=r=>di[r.priority]-Math.floor((Nr()-r.queuedAt)/2e3);Ft.sort((r,s)=>e(r)-e(s)||r.queuedAt-s.queuedAt);let t=Ft.shift();if(!t.consumers.size)continue;li++,t.startedAt=Nr();let n="success";Promise.resolve().then(()=>t.run(t.controller.signal)).then(r=>{for(let s of t.consumers)s.detach(),s.resolve(r)},r=>{n=t.controller.signal.aborted?"aborted":"error";for(let s of t.consumers)s.detach(),s.reject(r)}).finally(()=>{t.timer&&clearTimeout(t.timer),t.consumers.clear(),Ee.get(t.key)===t&&Ee.delete(t.key),li--;try{hn?.onTiming?.({method:t.method,priority:t.priority,queueMs:Math.round(t.startedAt-t.queuedAt),requestMs:Math.round(Nr()-t.startedAt),outcome:n})}catch{}Lr()})}}ne(la);var Tl=new Set(["list-memberships","init"]),Ie=class extends Error{constructor(n){let r=typeof n.payload?.error=="string"?n.payload.error.trim():"",s=typeof n.payload?.message=="string"?n.payload.message.trim():"",i=n.responseBody.trim()||`Gateway HTTP error: ${n.status} ${n.statusText}`.trim(),o=r&&s?`${r}: ${s}`:s||r||i;super(o);te(this,"name","GatewayRequestError");te(this,"method");te(this,"status");te(this,"statusText");te(this,"payload");te(this,"responseBody");this.method=n.method,this.status=n.status,this.statusText=n.statusText,this.payload=n.payload,this.responseBody=n.responseBody}};async function x(e,t={},n={}){let r=ie(),s=pn(),i=Ot(),o=`${Ce}/d/${i}`,c={"Content-Type":"application/json"},a=await pa(Ye(),n.signal);if(r!==ie())throw new Error("Session changed before gateway request");if(a&&(c.Authorization=`Bearer ${a}`),!Tl.has(e)&&!t._scope_path&&await pa(er(),n.signal),r!==ie())throw new Error("Session changed before gateway request");let u={...t},d=ht();!u.domain_scope_id&&d?.scope_id&&(u.domain_scope_id=d.scope_id);let p=s??pn();!u._scope_path&&p&&(u._scope_path=p);let m=async f=>{if(r!==ie())throw new Error("Session changed before queued gateway request");let y=await fetch(o,{method:"POST",signal:f,headers:c,body:JSON.stringify({method:e,params:u})}),g=await y.text();if(r!==ie())throw new Error("Session changed during gateway request");let h=null;if(g)try{h=JSON.parse(g)}catch{}if(!y.ok||!h)throw new Ie({method:e,status:y.status,statusText:y.statusText,payload:h,responseBody:g});if(h.success===!1){let v=h.error||"",b=h.denied_by||h.error_type||"";throw b==="rule"||b==="access"||b==="entitlement"||v==="RULE_DENIED"||v==="ACCESS_DENIED"||v==="PERMISSION_DENIED"||v==="ENTITLEMENT_REQUIRED"?new rt(h):new Ie({method:e,status:y.status,statusText:y.statusText,payload:h,responseBody:g})}return h&&h.server_now!==void 0&&na(h.server_now),h};return da(e,u)?fa(Kr([r,i,a,e,u]),e,n,m):m(n.signal)}function pa(e,t){return t?t.aborted?Promise.reject(new DOMException("Read cancelled","AbortError")):new Promise((n,r)=>{let s=()=>r(new DOMException("Read cancelled","AbortError"));t.addEventListener("abort",s,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",s))}):e}var _=X(ae(),1),Jl=X(ha(),1),Yl=X(Ir(),1);var ga=new WeakMap;function Ae(e,t,n={}){let r=n.exact===!0,s=()=>e.invalidateQueries({queryKey:t,exact:r},{cancelRefetch:!1}),i=e.getQueryCache().findAll({queryKey:t,exact:r,fetchStatus:"fetching"}).flatMap(p=>p.promise?[p.promise]:[]);if(i.length===0)return s();let o=`${r?"=":"^"}${JSON.stringify(t)}`,c=ga.get(e);c||(c=new Map,ga.set(e,c));let a=c.get(o);if(a)return a;let u=c,d=Promise.allSettled(i).then(()=>(u.delete(o),s()));return u.set(o,d),d}function pe(e,t){return typeof e=="string"&&(e===t||e.startsWith(`${t}/`))}var jr=new WeakMap,ya=e=>e.meta?.arrangementRealtime===!0;function Ze(e,t){let n=e.getQueryCache().find({queryKey:t,exact:!0});if(!n)return;let r=jr.get(e);r||(r=new Map,jr.set(e,r));let s=r.get(n.queryHash);s&&clearTimeout(s),r.set(n.queryHash,setTimeout(()=>{r.delete(n.queryHash),e.getQueryCache().get(n.queryHash)===n&&Ae(e,t,{exact:!0})},250))}function _a(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){if(!ya(n))continue;let r=n.state.data;if(n.meta?.personalSections===!0){(r?.item_path&&[t.path,t.old_path].some(i=>typeof i=="string"&&(i===r.item_path||i.startsWith(r.item_path+"/")))||r?.sections?.some(i=>i.entries?.some(o=>o.target?.id===t.item_id))||!r?.item_id&&t.item_type==="item_arrangement"&&t.name==="sidebar-sections")&&Ze(e,n.queryKey);continue}if(!r?.item_id)continue;let s=(i,o)=>!!(i&&t.item_id===i||o&&(t.path===o||t.old_path===o));(s(r.item_id,r.item_path)||t.parent_id===r.item_id||t.old_parent_id===r.item_id||[t.path,t.old_path].some(i=>typeof i=="string"&&i.slice(0,i.lastIndexOf("/"))===r.item_path)||r.resolved_children?.some(i=>s(i.id,i.symlink_path||i.path)||i.target&&s(i.target.id,i.target.path)))&&Ze(e,n.queryKey)}}function va(e){for(let t of e.getQueryCache().getAll())ya(t)&&t.state.data!==void 0&&Ze(e,t.queryKey)}function ba(e){jr.get(e)?.forEach(clearTimeout),jr.delete(e)}var et=null;ne(()=>{et&&(et.cancelQueries({queryKey:["vfs"]}),et.removeQueries({queryKey:["vfs"]}))});function wa(e){if(et&&et!==e)throw new Error("[fsaos-gateway-sdk] setQueryClient() called after a QueryClient was already in use. Inject the host client before rendering or starting realtime subscriptions.");et=e}function O(){return et||(et=new Hs({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),et}var Sa=new Proxy({},{get(e,t,n){let r=O(),s=r[t];return typeof s=="function"?s.bind(r):s}});var Vr=new WeakMap;function pi(e){return e.meta?.infiniteItemsRealtime?.filter}function El(e,t){return e.state.data?.pages?.some(r=>r.items?.some(s=>t.item_id&&s.id===t.item_id||t.path&&s.path===t.path||t.old_path&&s.path===t.old_path))??!1}function Il(e){if(e.type)return new Set([e.type]);if(!e.any_of?.length)return null;let t=new Set;for(let n of e.any_of){if(!n.item_type)return null;t.add(n.item_type)}return t}function Al(e,t,n){if(El(e,n))return!0;if(t.spaceIds!==void 0&&(!t.spaceIds.length||n.space_item_id!==void 0&&!t.spaceIds.includes(n.space_item_id)&&!t.spaceIds.includes(n.old_space_item_id)))return!1;let r=t.scope,s=typeof r=="string"&&r!=="__unscoped__",i=typeof n.path=="string"||typeof n.old_path=="string";if(s&&i&&!pe(n.path,r)&&!pe(n.old_path,r))return!1;if(n.item_type==="symlink"&&s&&i)return!0;let o=Il(t);return n.item_type&&o&&!o.has(n.item_type)||t.parent_id&&n.parent_id!==void 0&&n.parent_id!==t.parent_id&&n.old_parent_id!==t.parent_id?!1:i||!!(t.parent_id&&n.parent_id===t.parent_id)}function Ra(e,t){let n=Vr.get(e);n||(n=new Map,Vr.set(e,n));let r=n.get(t.queryHash);r&&clearTimeout(r),n.set(t.queryHash,setTimeout(()=>{n.delete(t.queryHash),!(e.getQueryCache().get(t.queryHash)!==t||!pi(t))&&Ae(e,t.queryKey,{exact:!0})},500))}function xa(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){let r=pi(n);r&&Al(n,r,t)&&Ra(e,n)}}function Pa(e){for(let t of e.getQueryCache().getAll())pi(t)&&t.state.data!==void 0&&Ra(e,t)}function Ca(e){Vr.get(e)?.forEach(clearTimeout),Vr.delete(e)}var $r=class extends Error{constructor(){super("The server did not confirm the selected-Space listing contract")}};function Ta(e,t){if(!Array.isArray(t)||t.some(n=>typeof n!="string")||JSON.stringify([...new Set(t)].sort())!==JSON.stringify(e))throw new $r}function gt(e){return!e||e.spaceIds===void 0?e:{...e,spaceIds:[...new Set(e.spaceIds.map(t=>t.toLowerCase()))].sort(),...e.limit!==void 0?{limit:Math.max(1,Math.min(e.limit,500))}:{}}}function gn(e){return e instanceof $r||e instanceof rt||e instanceof Ie&&(e.payload?.error==="SPACE_SELECTION_UNAVAILABLE"||e.payload?.error==="QUERY_PARAMS_INVALID"||e.status===401||e.status===403)}function oe(){return H()??"__unscoped__"}var P={all:()=>["vfs",oe()],item:e=>["vfs",oe(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",oe(),"children",e],allChildren:()=>["vfs",oe(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",oe(),"search",e,...t??[]],items:(e,t)=>["vfs",oe(),"items",e,JSON.stringify(gt(t??{}))],allItems:()=>["vfs",oe(),"items"],tree:(e,t)=>["vfs",oe(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",oe(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",oe(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",oe(),"get-activity-feed",e,t,n],itemVersions:(e,t,n,r)=>["vfs","item-versions",e,t,n,r],itemHistory:(e,t,n)=>["vfs","item-history",e,t,n],channelMessages:(e,t)=>["vfs",oe(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",oe(),"channel-messages"],channels:e=>["vfs",oe(),"channels",e??"all"],allChannels:()=>["vfs",oe(),"channels"],notifications:(e,t)=>["vfs",oe(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",oe(),"notifications"],unreadCounts:()=>["vfs",oe(),"unread-counts"],memberships:e=>["memberships",e]};var kl=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function J(...e){kl&&console.log("[WS]",...e)}var D=null,yn=null,vn=null,nr=0,Ml=3e4,Ea=1e4,wn=!1,Ia=!1,Fa=3e4,Ol=Fa*2+5e3,Wr=0,Br=null,Aa=!1;function Fl(){sr(),Wr=Date.now(),Br=setInterval(()=>{if(D&&D.readyState===WebSocket.OPEN&&Date.now()-Wr>Ol){J("ping: no inbound traffic for",Date.now()-Wr,"ms \u2014 closing half-open socket");try{D.close(4e3,"liveness timeout")}catch{}return}nt({type:"ping"})},Fa)}function sr(){Br&&(clearInterval(Br),Br=null)}function ql(){typeof document>"u"||(document.hidden?sr():rr()&&(J("Tab visible, reconnecting..."),qt()))}function Ql(){Aa||typeof document>"u"||(document.addEventListener("visibilitychange",ql),Aa=!0)}var Se={};function hi(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return!n||!r?n===r:r===n||r.startsWith(`${n}/`)}var bn=[],tt=new Map,_n=new Map,ke=new Map;function Dl(e){let t=_n.get(e);return t?Array.from(new Set(Array.from(t.values()).flatMap(n=>n.event_types))).sort():[]}function ka(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):!1}function Ma(e){let t=Dl(e);if(t.length===0)return tt.delete(e),null;let n={scope_id:e,event_types:t};return tt.set(e,n),n}var je=new Map,yt=new Map,mi="disconnected",Hr=[];function Gr(e){if(mi!==e){mi=e;for(let t of[...Hr])try{t(e)}catch{}}}function Ul(e){je.set(e,"ready");let t=yt.get(e);if(t){yt.delete(e);for(let n of t)n()}}function Nl(){for(let e of je.keys())je.set(e,"disconnected")}function gi(e,t){je.set(e,"pending"),nt({type:"subscribe_path",path:e,event_types:t})}function Kl(){return Object.keys(Se).some(t=>Se[t]&&Se[t].length>0)||bn.length>0}function rr(){return tt.size>0||ke.size>0}async function qt(){if(!rr()){J("ensureConnection: no active subscriptions, skipping");return}if(D&&D.readyState===WebSocket.OPEN){J("ensureConnection: already open");return}if(yn)return J("ensureConnection: connection already in flight, waiting..."),yn;if(D){J("ensureConnection: killing stale WS in state",D.readyState);try{D.close()}catch{}D=null}return wn=!1,yn=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=Ce,n=await Ye();if(!n){J("ensureConnection: no token available, will retry"),Oa();return}let r=t.startsWith("https")?"wss":"ws",s=t.replace(/^https?:\/\//,""),i=`${r}://${s}/ws`;i+=`?token=${encodeURIComponent(n)}`,J("ensureConnection: opening WS to",i.substring(0,50)+"..."),Gr("connecting"),D=new WebSocket(i);let o=D;await new Promise((c,a)=>{if(!D)return a(new Error("WebSocket not created"));let u=setTimeout(()=>{if(D===o){if(J("ensureConnection: TIMEOUT after",Ea,"ms"),D&&D.readyState!==WebSocket.OPEN){try{D.close()}catch{}D=null}a(new Error("WebSocket connection timeout"))}},Ea);o.onopen=()=>{if(D!==o)return;clearTimeout(u),J("ensureConnection: CONNECTED");let d=Ia;Ia=!0,nr=0,Gr("connected"),Ll(d),(typeof document>"u"||!document.hidden)&&Fl(),Ql(),c()},o.onmessage=d=>{D===o&&jl(d.data)},o.onerror=()=>{J("ensureConnection: WS error event")},o.onclose=d=>{clearTimeout(u),D===o&&(J("ensureConnection: WS closed, code:",d.code,"reason:",d.reason),D=null,sr(),Nl(),Gr("disconnected"),!wn&&rr()&&Oa(),a(new Error(`WebSocket closed: ${d.code}`)))}})}catch(e){J("ensureConnection: failed -",e?.message||e)}finally{yn=null}})(),yn}function Oa(){if(vn||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,nr)+Math.random()*1e3,Ml);nr++,J("scheduleReconnect: attempt",nr,"in",Math.round(e),"ms"),vn=setTimeout(()=>{vn=null,rr()&&qt()},e)}function Ll(e=!1){for(let t of tt.values())J("resubscribeAll: scope",t.scope_id),nt({type:"subscribe",scope_id:t.scope_id,event_types:t.event_types});for(let t of ke.values())J("resubscribeAll: path",t.path),gi(t.path,t.event_types);if(e)try{let t=O();Pa(t),va(t);for(let n of ke.values())t.invalidateQueries({queryKey:P.item(n.path)}),t.invalidateQueries({queryKey:P.children(n.path)});J("resubscribeAll: invalidated",ke.size,"paths after reconnect")}catch(t){J("resubscribeAll: cache invalidation skipped",t)}}function nt(e){D&&D.readyState===WebSocket.OPEN&&D.send(JSON.stringify(e))}function jl(e){Wr=Date.now();try{let t=JSON.parse(e);if(t.type==="subscribed_path"){typeof t.path=="string"&&Ul(t.path);return}if(t.type==="subscribed"||t.type==="unsubscribed"||t.type==="unsubscribed_path"||t.type==="pong")return;if(t.type==="error"){console.warn("[WS] Server error:",t.message);return}if(t.type==="event"||t.event_type){let n=t.event_type||"message",r=t.data||t;if(n==="vfs_change"&&(xa(O(),r),_a(O(),r)),typeof r.path=="string")for(let[s,i]of Object.entries(Se))s!=="*"&&hi(s,r.path)&&i.forEach(o=>o(r));Se["*"]&&Se["*"].forEach(s=>s(r));for(let s of bn)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function yi(){!Kl()&&tt.size===0&&ke.size===0&&D&&(wn=!0,sr(),D.close(),D=null,wn=!1)}function zr(e,t){return Se[e]||(Se[e]=[]),Se[e].push(t),ke.has(e)||(ke.set(e,{path:e,event_types:["token_stream"]}),D&&D.readyState===WebSocket.OPEN?gi(e,["token_stream"]):je.set(e,"pending")),qt(),()=>{let n=Se[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete Se[e],ke.delete(e),je.delete(e),yt.delete(e),nt({type:"unsubscribe_path",path:e}))}yi()}}function re(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return bn.push(...s),rr()&&qt(),()=>{for(let i of s){let o=bn.indexOf(i);o!==-1&&bn.splice(o,1)}yi()}}function Sn(e,t=["vfs_change","ccm_change"]){let n=Symbol(e),r=Array.from(new Set(t)).sort();if(r.length===0)return()=>{};let s=_n.get(e)??new Map,i=tt.get(e)?.event_types;s.set(n,{event_types:r}),_n.set(e,s);let o=Ma(e);if(!o)return()=>{};J("subscribeToScope:",e,o.event_types),D&&D.readyState===WebSocket.OPEN&&!ka(i,o.event_types)&&nt({type:"subscribe",scope_id:e,event_types:o.event_types}),qt();let c=!0;return()=>{if(!c)return;c=!1;let a=_n.get(e);if(!a?.delete(n))return;let u=tt.get(e)?.event_types;if(a.size===0)_n.delete(e),tt.delete(e),nt({type:"unsubscribe",scope_id:e});else{let d=Ma(e);d&&D&&D.readyState===WebSocket.OPEN&&!ka(u,d.event_types)&&nt({type:"subscribe",scope_id:e,event_types:d.event_types})}yi()}}function qa(e,t,n={}){nt({type:"emit",scope_id:e,event_type:t,payload:n})}function _i(){J("disconnectSSE: tearing down"),Ca(O()),ba(O()),wn=!0,sr(),D&&(D.close(),D=null),vn&&(clearTimeout(vn),vn=null),yn=null,wn=!1,nr=0;for(let e of Object.keys(Se))delete Se[e];bn.length=0,tt.clear(),_n.clear(),ke.clear(),je.clear(),yt.clear(),Gr("disconnected")}function Qa(){nt({type:"ping"})}function Da(e){return ke.has(e)?je.get(e)??"pending":"unsubscribed"}function Ua(e,t=5e3){return ke.has(e)?je.get(e)==="ready"&&D&&D.readyState===WebSocket.OPEN?Promise.resolve(!0):(qt(),new Promise(n=>{let r=!1,s=yt.get(e)??[],i=()=>{r||(r=!0,clearTimeout(o),n(!0))};s.push(i),yt.set(e,s);let o=setTimeout(()=>{if(r)return;r=!0;let c=yt.get(e);if(c){let a=c.indexOf(i);a!==-1&&c.splice(a,1),c.length===0&&yt.delete(e)}n(!1)},t)})):Promise.resolve(!1)}function Na(e){let t=ke.get(e);if(!t){J("resubscribePath: no active subscription for",e);return}D&&D.readyState===WebSocket.OPEN?(J("resubscribePath: re-sending frame for",e),gi(t.path,t.event_types)):(je.set(e,"pending"),qt())}function Jr(e){Hr.push(e);try{e(mi)}catch{}return()=>{let t=Hr.indexOf(e);t!==-1&&Hr.splice(t,1)}}ne(_i);function Ka(){return new Date().toISOString()}function La(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function _e(e){let t=e.path||e.item_path||"",n=t.split("/");n.pop();let r=n.join("/"),s=e.type_data||{};return s.allowed_parent_types&&!s.accepts&&(s.accepts=s.allowed_parent_types),delete s.allowed_parent_types,{id:e.id||e.item_id||"",name:e.name||e.item_name||"",item_type:e.item_type||"unknown",path:t,parent_path:r,is_active:e.is_active!==!1,has_children:e.has_children??!1,created_at:e.created_at||Ka(),updated_at:e.updated_at||Ka(),visibility:e.visibility,type_data:s,scope_item_id:e.scope_item_id,fractal_id:e.fractal_id,parent_instance_id:e.parent_instance_id,owner_principal_id:e.owner_principal_id,created_by_principal_id:e.created_by_principal_id,parent_id:e.parent_id,space_item_id:e.space_item_id,account_item_id:e.account_item_id}}function or(e){return(e.content?.items||e.items||[]).map(_e)}async function Xr(e){try{let t=await x("read",{id:e});if(t.item_name||t.item_path){let r=_e(t);return r.path&&O().setQueryData(P.item(r.path),r),r}let n=t.item;if(n){let r=_e(n);return r.path&&O().setQueryData(P.item(r.path),r),r}return null}catch{return null}}async function ar(e){try{let t=await x("read",{path:e});if(t.item_name||t.item_path)return _e(t);let n=t.item;return n?_e(n):null}catch{return null}}async function cr(e){try{let t=await x("list",{path:e,limit:200}),n=or(t);for(let r of n)O().setQueryData(P.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function ja(e,t){let{items:n}=await xn({type:"turn_queue_entry",scope:e,parent_id:t,fields:{state:"queued"},sort_by:"created_at",sort_dir:"asc",limit:100});return n.map(r=>{let s=String(r.type_data?.conversation_anchor_item_id??r.type_data?.conversation_root_id??t);return{id:r.id,path:r.path,content:String(r.type_data?.content??""),state:String(r.type_data?.state??"queued"),queue_seq:Number(r.type_data?.queue_seq??0),created_at:r.created_at,conversation_anchor_item_id:s,conversation_root_id:s,client_request_id:typeof r.type_data?.client_request_id=="string"?r.type_data.client_request_id:void 0,promoted_message_id:typeof r.type_data?.promoted_message_id=="string"?r.type_data.promoted_message_id:void 0,promoted_event_id:typeof r.type_data?.promoted_event_id=="string"?r.type_data.promoted_event_id:void 0}}).sort((r,s)=>r.queue_seq-s.queue_seq||r.created_at.localeCompare(s.created_at))}async function Zr(e,t,n){try{let r=await x("list",{path:e,limit:t,offset:n}),s=or(r);for(let i of s)O().setQueryData(P.item(i.path),i);return{items:s,total_hint:r.total??r.content?.total??s.length}}catch(r){return console.error(`[gateway] Failed to fetch children page of ${e}:`,r),{items:[],total_hint:0}}}async function es(e){let n=await x("types-list",e?{scope_id:e}:{}),r=n.content?.items||n.items||[],s=new Map;for(let i of r){let o=i.name,c=i.type_data;!o||!c||s.set(o,{type_key:o,display_name:c.display_name||o,display_name_plural:c.display_name_plural||o+"s",icon:c.icon||"File",color:c.color||"gray",description:c.description||"",input_schema:c.input_schema||{},system_schema:c.system_schema||{},json_schema:c.input_schema||c.json_schema||{},default_data:c.default_data||{},field_defaults:c.field_defaults||{},renderer_config:c.renderer_config||{},is_system:c.is_system??!1,is_active:c.is_active??!0,is_container:c.is_container??!1,is_scope:c.is_scope??!1,render_mode:c.render_mode||"none",placement_mode:c.placement_mode,direct_parent_types:c.direct_parent_types,allowed_parent_types:c.allowed_parent_types,governed_create:c.governed_create,create_method:c.create_method,dedup:c.dedup,edges:c.edges,events:c.events})}return s}async function ts(e){try{let t=await x("edges",{item_id:e}),n=t.outgoing||[],r=t.incoming||[],s=[];for(let i of n)s.push({id:i.edge_id||La(),source_item_id:e,target_item_id:i.target_id||"",edge_type:i.edge_type||"",weight:i.weight??1,context:i.context||{},is_active:!0,is_bidirectional:i.is_bidirectional});for(let i of r)s.push({id:i.edge_id||La(),source_item_id:i.source_id||"",target_item_id:e,edge_type:i.edge_type||"",weight:i.weight??1,context:i.context||{},is_active:!0,is_bidirectional:i.is_bidirectional});return s}catch(t){return console.warn(`[gateway] Failed to fetch edges for ${e}:`,t),[]}}async function ns(e,t=1,n,r){try{let s={path:e,max_depth:t>0?t:999};n?.length&&(s.item_types=n),r&&(s.limit=r);let i=await x("tree",s),o=or(i);for(let c of o)O().setQueryData(P.item(c.path),c);return o}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function rs(e,t=50,n=0){try{let r=await x("get-activity-feed",{scope_path:e,limit:t,offset:n});return r.content?.items||r.items||r.entries||[]}catch(r){return console.error(`[gateway] Failed to fetch recent activity for ${e}:`,r),[]}}async function ur(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;try{let i=await x("item-versions",{id:e,limit:n,offset:r,include_snapshots:s});return{versions:i.content?.items||i.versions||[],total:i.total??0}}catch(i){return console.error(`[gateway] Failed to fetch item versions for ${e}:`,i),{versions:[],total:0}}}async function ss(e,t=50,n=0){return ur(e,{limit:t,offset:n})}async function is(e,t,n){try{let r={scope_id:e};t?.length&&(r.item_types=t),n&&(r.limit=n);let s=await x("member-focus",r),i=or(s);for(let o of i)O().setQueryData(P.item(o.path),o);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${e}:`,r),[]}}async function os(e,t){let n={path:e};t?.mode&&(n.mode=t.mode),t?.strategy&&(n.strategy=t.strategy),t?.arguments&&(n.arguments=t.arguments);let s=await x("open",n);return{item_id:s.item_id,item_path:s.item_path,item_name:s.item_name,item_type:s.item_type,render:s.render,compatible_components:s.compatible_components??[],content:s.content,metadata:s.metadata,instructions:s.instructions}}function Rn(e){return!!e&&(!!e.type||Array.isArray(e.any_of)&&e.any_of.length>0)}function Vl(e){let t={};e.item_type&&(t.item_type=e.item_type);for(let[n,r]of Object.entries(e.fields??{}))t[`field.${n}`]=String(r);for(let[n,r]of Object.entries(e.field_in??{}))t[`field_in.${n}`]=r.map(String);return t}var $l=["catalog","parent_only","internal"];function Va(e,t={}){if(!e||typeof e!="object")return null;let n=o=>typeof o=="string"||typeof o=="number"||typeof o=="boolean",r=o=>{let c={},a={};for(let[u,d]of Object.entries(o))u.startsWith("field.")&&u.length>6&&n(d)?c[u.slice(6)]=d:u.startsWith("field_in.")&&u.length>9&&Array.isArray(d)&&(a[u.slice(9)]=d.filter(n));return{fields:c,field_in:a}},s={};typeof e.type=="string"&&e.type&&(s.type=e.type),typeof e.sort_by=="string"&&(s.sort_by=e.sort_by),(e.sort_dir==="asc"||e.sort_dir==="desc")&&(s.sort_dir=e.sort_dir),typeof e.name=="string"&&e.name&&(s.name=e.name),typeof e.tag=="string"&&e.tag&&(s.tag=e.tag),typeof e.discovery=="string"&&$l.includes(e.discovery)&&(s.discovery=e.discovery);let i=r(e);if(Object.keys(i.fields).length&&(s.fields=i.fields),Object.keys(i.field_in).length&&(s.field_in=i.field_in),Array.isArray(e.any_of)){let o=[];for(let c of e.any_of){if(!c||typeof c!="object"||Array.isArray(c))continue;let a=c,u={};typeof a.item_type=="string"&&a.item_type&&(u.item_type=a.item_type);let d=r(a);Object.keys(d.fields).length&&(u.fields=d.fields),Object.keys(d.field_in).length&&(u.field_in=d.field_in),Object.keys(u).length&&o.push(u)}o.length&&(s.any_of=o)}return Rn(s)?{...s,...t}:null}async function xn(e,t={}){if(e=gt(e),e.spaceIds?.length===0)return{items:[],total_hint:0};let n={};e.type&&(n.item_type=e.type),e.scope&&(n.scope_path=e.scope);let r={};if(e.spaceIds!==void 0&&(r.space_ids=e.spaceIds),e.name&&(r.name=e.name),e.tag&&(r.tag=e.tag),e.parent_id&&(r.parent_id=e.parent_id),e.sort_by&&(r.sort_by=e.sort_by),e.sort_dir&&(r.sort_dir=e.sort_dir),e.offset!=null&&(r.offset=e.offset),e.fields)for(let[s,i]of Object.entries(e.fields))r[`field.${s}`]=String(i);if(e.field_in)for(let[s,i]of Object.entries(e.field_in))r[`field_in.${s}`]=i.map(String);e.discovery&&(r.discovery=e.discovery),e.any_of?.length&&(r.any_of=e.any_of.map(Vl)),Object.keys(r).length>0&&(n.filters=r),e.limit!=null&&(n.limit=e.limit);try{let s=await x("query",n,t);e.spaceIds!==void 0&&Ta(e.spaceIds,s.selected_space_ids??s.content?.selected_space_ids);let i=or(s);for(let o of i)O().setQueryData(P.item(o.path),o);return{items:i,total_hint:s.total??s.content?.total??i.length}}catch(s){if(t.signal?.aborted||s instanceof Error&&s.name==="AbortError"||(console.error(`[gateway] Failed to fetch items of type ${e.type??"(any_of)"}:`,s),t.throwOnError||e.spaceIds!==void 0))throw s;return{items:[],total_hint:0}}}function Wl(e){if(!e||typeof e!="object")return;let t=e;if(t.version!==1||typeof t.work_id!="string"||!t.work_id)return;let n=r=>{let s=t[r];return typeof s=="string"&&s?s:void 0};return{version:1,workId:t.work_id,threadRootId:n("thread_root_id"),requestMessageId:n("request_message_id"),replyMessageId:n("reply_message_id"),replyMessagePath:n("reply_message_path"),todoListId:n("todo_list_id"),todoListPath:n("todo_list_path"),stepId:n("step_id"),stepPath:n("step_path"),runId:n("run_id"),parentRunId:n("parent_run_id"),toolCallId:n("tool_call_id"),traceId:n("trace_id")}}function $a(e){return e.filter(t=>t.item_type==="card").map(t=>{let n=t.type_data||{},r=n.payload||{};return{id:t.id||"",path:t.path||"",name:t.name||(t.path||"").split("/").pop()||"",createdAt:t.created_at||"",action:n.action||"created",targetId:n.target_id||void 0,targetPath:n.target_path||"",targetDisplayName:n.target_display_name||"",targetDescription:n.target_description||"",targetItemType:n.target_item_type||"",toolId:(t.name||"").startsWith("card-")?(t.name||"").substring(5):void 0,parentMessagePath:t.parent_message_path||void 0,visibility:n.visibility||"private",openWith:r.open_with||void 0,hostBundled:r.host_bundled===!0?!0:void 0,bundleExport:r.bundle_export||void 0,launchArguments:r.launch_arguments||void 0,requiresUserAttention:r.requires_user_attention===!0?!0:void 0,origin:Wl(n.origin),presentationRole:r.presentation_role==="user-request"?"user-request":r.presentation_role==="output"?"output":void 0}}).sort((t,n)=>t.createdAt.localeCompare(n.createdAt))}function ir(e){return e.filter(t=>t.item_type==="message").map(t=>{let n=t.type_data||{},r="user";n.role==="assistant"?r="assistant":n.role==="system"&&(r="system");let s=n.metadata||{};return{id:t.id||"",path:t.path||"",content:n.message||n.content||"",created_at:t.created_at||"",role:r,status:typeof n.status=="string"?n.status:void 0,delivery_state:typeof n.delivery_state=="string"?n.delivery_state:void 0,cognition_event_id:typeof n.cognition_event_id=="string"?n.cognition_event_id:void 0,seq:n.seq||0,principal_id:n.principal_id,member_id:typeof n.member_id=="string"?n.member_id:void 0,reply_count:n.reply_count||0,member_count:n.member_count||0,parent_message_id:n.parent_message_id,intent_card:s.intent_card,metadata:Object.keys(s).length>0?s:void 0,thread_summary:Array.isArray(n.thread_summary)&&n.thread_summary.length>0?n.thread_summary:void 0}}).sort((t,n)=>t.seq-n.seq)}async function Wa(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await x("get-channel-messages",n),i=s.messages||s.content?.items||s.items||[];return ir(i)}catch(n){return console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),[]}}async function as(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await x("get-channel-messages",n),i=s.messages||[],o=ir(i),c=$a(i),a=new Map,u=[];for(let d of c)if(d.parentMessagePath){let p=a.get(d.parentMessagePath)||[];p.push(d),a.set(d.parentMessagePath,p)}else u.push(d);return{messages:o,activityMessages:ir(s.activity_messages||[]),messageCards:a,siblingCards:u,mode:s.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages with cards for ${e}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}async function lr(e,t){try{let n={channel_path:e};t?.parentMessageId&&(n.parent_message_id=t.parentMessageId),t?.limit&&(n.limit=t.limit),t?.before_seq!=null&&(n.before_seq=t.before_seq),t?.after_seq!=null&&(n.after_seq=t.after_seq);let s=await x("get-channel-messages",n),i=s.messages||[],o=$a(i),c=new Map,a=[];for(let u of o)if(u.parentMessagePath){let d=c.get(u.parentMessagePath)||[];d.push(u),c.set(u.parentMessagePath,d)}else a.push(u);return{messages:ir(i),activityMessages:ir(s.activity_messages||[]),messageCards:c,siblingCards:a,mode:s.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages page for ${e}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}function Yr(e){O().invalidateQueries({queryKey:P.children(e)})}function vi(e){O().invalidateQueries({queryKey:P.item(e)})}function Ba(e,t){vi(e),Yr(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&Yr(r)}function Ha(e){let t=e+"/";O().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function Ga(){O().invalidateQueries({queryKey:P.all()})}function za(e){O().invalidateQueries({queryKey:P.types(e)})}function Ja(e,t){e?O().invalidateQueries({queryKey:P.channelMessages(e,t)}):O().invalidateQueries({queryKey:P.allChannelMessages()})}function Ya(e,t){e&&t?O().invalidateQueries({queryKey:P.openEnvelope(e,t)}):e?O().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):O().invalidateQueries({queryKey:P.allOpenEnvelopes()})}function Ve(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}async function cs(){return((await x("list-memberships",{})).memberships||[]).map(n=>({accountId:n.account_id,path:n.account_path,name:n.account_name,role:n.role||"member",typeData:n.account_type_data||{},joinedAt:n.joined_at,via:n.via,placement:n.placement,subordinateTo:n.subordinate_to??null,cascadeAnchorId:n.cascade_anchor_id??null,isAccount:n.is_account??void 0,isSpace:n.is_space??void 0,isOwner:n.is_owner??void 0,billingResponsible:n.billing_responsible??void 0,grantedVia:n.granted_via??null,grantedUnderAccountId:n.granted_under_account_id??null,membershipPath:n.membership_path??null,personalSpaceId:n.personal_space_id??null,personalSpacePath:n.personal_space_path??null}))}var Pn=new Map,dr=null,us=null,_t=new Map,Xa=250;function Qt(e){if(dr){Cn(e);return}Cn(e),dr=re("vfs_change",t=>Bl(t)),us=re("ccm_change",t=>Hl(t))}function Cn(e){if(Pn.has(e))return;let t=Sn(e,["vfs_change","ccm_change"]);Pn.set(e,t)}function ls(e){let t=Pn.get(e);t&&(t(),Pn.delete(e))}function bi(){for(let[,e]of Pn)e();Pn.clear(),dr&&(dr(),dr=null),us&&(us(),us=null),_t.forEach(e=>clearTimeout(e)),_t.clear()}ne(bi);function Bl(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=_t.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{_t.delete(s),Gl(n,t,e,s)},Xa);_t.set(s,o)}function Hl(e){if(!e||typeof e!="object")return;let t=e.source_item_id||e.source_id,n=e.target_item_id||e.target_id;if(!(e.edge_type!=null||t!=null||n!=null)||!t&&!n||e.item_type==="message")return;let s=`ccm:${t??""}:${n??""}`,i=_t.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{_t.delete(s),t&&O().invalidateQueries({queryKey:P.edges(t)}),n&&O().invalidateQueries({queryKey:P.edges(n)})},Xa);_t.set(s,o)}function Gl(e,t,n,r){if((e||"").toUpperCase()==="DELETE")O().removeQueries({queryKey:P.item(t)}),O().removeQueries({queryKey:P.children(t)}),O().removeQueries({queryKey:P.tree(t)});else if(n.item_id)try{let i={id:n.item_id,path:n.path,name:n.name,item_type:n.item_type,parent_id:n.parent_id,scope_item_id:n.scope_item_id},o=_e(i);o&&o.id&&O().setQueryData(P.item(t),o)}catch{}O().invalidateQueries({queryKey:P.children(r)}),O().invalidateQueries({predicate:i=>{let o=i.queryKey;if(o[0]!=="vfs"||o[1]!=="tree")return!1;let c=o[2];return t.startsWith(c+"/")||t===c}}),n.item_id&&O().invalidateQueries({queryKey:P.itemById(n.item_id)})}var Tn=null;ne(()=>{Tn=null});function vt(e){if(e!==Tn||e.generation!==ie())throw new Error("Workspace session changed")}function zl(e){return e instanceof Ie&&e.payload?.error==="item_not_found"}function fr(e,t){let n=e.resolve(t.id);if(!n||n.path!==t.path||n.kind!==t.kind)throw new Error("Mount is not an available membership");return n}function pr(e){let t=fe();if(!t)throw new Error("Elect a home account before loading mounts");return[t,...e.filter((n,r)=>n.id!==t.id&&e.findIndex(s=>s.id===n.id)===r)]}function Za(e,t){return JSON.stringify({mounts:e.map(n=>n.id),last_anchor:t.id})}async function ec(e,t,n){vt(e);let r=Za(t,n);if(e.saved===r)return;let s=JSON.parse(r);await x(e.exists?"update":"create",e.exists?{_scope_path:e.scope,path:e.path,type_data:s}:{_scope_path:e.scope,parent_path:e.path.slice(0,e.path.lastIndexOf("/")),name:"mounts",item_type:"file",type_data:s}),vt(e),e.exists=!0,e.saved=r}function tc(e,t){let n=Te();Qt(fe().id);for(let r of n)e.some(s=>s.id===r.id)||ls(r.id);for(let r of e)Cn(r.id);Ho(e,t)}async function Dt(e,t,n={}){let r=fe();if(!r)throw new Error("Elect a home account before loading mounts");let s=`${e}/settings/mounts`;if(Tn&&Tn.path!==s)throw new Error("Reset the session before changing the mount declaration owner");let i=Tn??(Tn={generation:ie(),path:s,scope:r.path,resolve:t,exists:!1,ready:!1,saved:null,queue:Promise.resolve()});return vt(i),i.loading?i.loading:i.ready?Te():(i.resolve=t,i.loading=(async()=>{let o=null;try{let d=await x("read",{path:s,_scope_path:i.scope});if(vt(i),o=d.type_data??d.item?.type_data,!o||!Array.isArray(o.mounts)||!o.mounts.every(p=>typeof p=="string"))throw new Error("Invalid saved mount declaration");i.exists=!0}catch(d){if(vt(i),!zl(d))throw d;i.exists=!1}let c=n.initialAnchor?fr(i,n.initialAnchor):r,a=pr(o?o.mounts.map(t).filter(d=>d!==null):[c]),u=o?a.find(d=>d.id===o.last_anchor)??a.find(d=>d.kind==="space")??r:c;return o?i.saved=Za(a,u):n.initialAnchor&&await ec(i,a,u),vt(i),i.ready=!0,tc(a,u),a})().finally(()=>{i.loading=void 0}),i.loading)}function ds(e){let t=Tn;if(!t?.ready)return Promise.reject(new Error("Workspace mounts are not loaded"));let n=t.queue.then(async()=>{vt(t);let{refs:r,anchor:s}=e(t);await ec(t,r,s),vt(t),tc(r,s)});return t.queue=n.catch(()=>{}),n}function wi(e){return ds(t=>({refs:pr([...Te(),fr(t,e)]),anchor:ye()}))}function nc(e){return ds(()=>{if(e===fe().id)throw new Error("The home account cannot be unmounted");let t=pr(Te().filter(r=>r.id!==e)),n=t.find(r=>r.id===ye()?.id)??t.find(r=>r.kind==="space")??fe();return{refs:t,anchor:n}})}function mr(e){return ds(t=>{let n=fr(t,e);return{refs:pr([...Te(),n]),anchor:n}})}function fs(e,t){return ds(n=>{let r=pr(e.map(i=>fr(n,i))),s=fr(n,t);if(!r.some(i=>i.id===s.id))throw new Error("Selected mount must be in the working set");return{refs:r,anchor:s}})}function ps(e){if(typeof e.path!="string")return!1;let t=[...Te().map(n=>n.path),ye()?.path].filter(n=>!!n);return!t.length&&H()&&t.push(H()),t.some(n=>pe(e.path,n))}function Si(e,t,n,r){if(!["message","card"].includes(e?.item_type)||!pe(e.path,t))return!1;if(!n){let s=e.path.slice(t.length).replace(/^\//,""),i=s?s.split("/").length:0;return e.item_type==="message"?i===1:i===1||i===2}return e.item_id===n||e.parent_id===n?!0:r.some(s=>{if(e.item_id===s.id||e.parent_id===s.id)return!0;let i=s.id===n?s.path:s.parent_message_id===n?s.path.slice(0,s.path.lastIndexOf("/")):void 0;return!!i&&pe(e.path,i)})}var rc=new WeakMap;function sc(e,t,n){let r=rc.get(e);r||(r=new Map,rc.set(e,r));let s=JSON.stringify(t),i=r.get(s);if(!i){let c=!1,a,u=!1,d=!1,p=new Set,m=new Set,f=()=>e.getQueryData(t)??[],y=()=>{c||u||a||(a=setTimeout(()=>{a=void 0,g()},250))},g=async()=>{if(c)return;u=!0;let I=d;d=!1;let R=[...p],M=new Set(m);m.clear(),p.clear();try{if(I)await Ae(e,t,{exact:!0});else{let S=(await Promise.allSettled(R.map(async T=>{let F=e.getQueryCache().find({queryKey:t,exact:!0});if(!F)return;let k=await x("read",{id:T});if(k.success===!1)throw new Error("Channel refresh failed");if(c||!F||e.getQueryCache().find({queryKey:t,exact:!0})!==F)return;let A=_e(k.item??k);if(A.id!==T||A.item_type!=="channel")return;let U=f().find(B=>B.id===T);if(!U)return;let Q=n({...A}),le={...U,path:Q.path,name:Q.name,displayName:Q.displayName,messageCount:Q.messageCount,aiMode:Q.aiMode,activeAgentIds:Q.activeAgentIds,isPrivate:Q.isPrivate,isDm:Q.isDm,autoPilot:Q.autoPilot,isArchived:Q.isArchived,updatedAt:Q.updatedAt};M.has(T)&&(U.name!==le.name||U.displayName!==le.displayName||U.path!==le.path)&&(d=!0),e.setQueryData(t,B=>B?.map(qe=>qe.id===T?le:qe))}))).find(T=>T.status==="rejected");if(S?.status==="rejected")throw S.reason}}catch(N){console.warn("[channels] refresh failed",N)}finally{u=!1,(d||p.size)&&y()}},h=I=>f().some(R=>R.id===I.item_id||R.path===I.path)?!0:ps(I),v=I=>{if(!h(I))return;let R=String(I.action??"").toLowerCase();if(["insert","delete","rename","move"].includes(R))d=!0;else if(R==="update"){let M=f().find(N=>N.id===I.item_id||N.path===I.path);M&&(p.add(M.id),m.add(M.id))}(d||p.size)&&y()},b=I=>{let R=f().find(M=>M.id===I.parent_id);R&&(p.add(R.id),y())},E=["vfs_change","ccm_change"].flatMap(I=>[re(I,v,R=>R.item_type==="channel"),re(I,b,R=>R.item_type==="message")]);i={users:0,stop:()=>{c=!0,a&&clearTimeout(a),E.forEach(I=>I())}},r.set(s,i)}i.users++;let o=!1;return()=>{o||(o=!0,--i.users===0&&(i.stop(),r.delete(s)))}}function Y(){return(0,_.useSyncExternalStore)(we,ee,ee)}function lc(){return Y(),Dr()}function dc(e){return Y(),$({queryKey:P.item(e),queryFn:()=>ar(e),enabled:!!e,staleTime:1/0})}function fc(e){return Y(),$({queryKey:P.itemById(e),queryFn:()=>Xr(e),enabled:!!e,staleTime:1/0})}function xi(e){return Y(),$({queryKey:P.children(e),queryFn:()=>cr(e),enabled:!!e})}function pc(e){let t=xi(e);return{...t,children:t.data??[]}}function mc(e,t=1){return Y(),$({queryKey:P.tree(e,t),queryFn:()=>ns(e,t),enabled:!!e})}function hc(e,t){return Y(),$({queryKey:P.search(e,t),queryFn:async()=>{let n={query:e};t?.length&&(n.item_types=t);let r=await x("search",n);return(r.content?.items||r.items||r.results||[]).map(_e)},enabled:!!e&&e.length>0})}function gc(e){Y();let t=(0,_.useMemo)(()=>e,[JSON.stringify(e)]);return $({queryKey:["vfs",H()??"__unscoped__","resolve",JSON.stringify(t??{})],queryFn:async()=>await x("resolve",t),enabled:!!t?.query&&t.query.length>0})}function yc(e){Y();let t=gt(e),n=(0,_.useMemo)(()=>t,[JSON.stringify(t)]),r=$({queryKey:P.items(n?.type??"",n),queryFn:({signal:s})=>xn(n,{signal:s,throwOnError:!0}),enabled:Rn(n),...n?.spaceIds!==void 0?{retry:(s,i)=>!gn(i)&&iu(s,i)}:{},select:s=>s.items});return n?.spaceIds!==void 0&&gn(r.error)?{...r,data:void 0}:r}function Pi(e,t={}){let n=Y(),{realtime:r=!1}=t,s=gt(e),i=s?.limit??20,o=(0,_.useMemo)(()=>s,[JSON.stringify(s)]),c=(0,_.useMemo)(()=>["vfs",H()??"__unscoped__","infinite-items",o?.type??"",JSON.stringify(o??{})],[n,o]),a=Jn({queryKey:c,queryFn:async({pageParam:p=0,signal:m})=>xn({...o,limit:i,offset:p},{throwOnError:!0,signal:m,priority:t.priority}),initialPageParam:0,getNextPageParam:(p,m,f)=>{if(!(o?.spaceIds!==void 0&&p.total_hint!==void 0&&f+p.items.length>=p.total_hint)&&!(p.items.length<i))return f+p.items.length},enabled:Rn(o),...o?.spaceIds!==void 0?{retry:(p,m)=>!gn(m)&&iu(p,m)}:{},staleTime:r?1/0:t.staleTime,meta:r&&o?{infiniteItemsRealtime:{filter:o}}:{}}),u=(0,_.useMemo)(()=>{if(o?.spaceIds!==void 0&&gn(a.error))return[];if(!a.data?.pages)return[];let p=new Set,m=[];for(let f of a.data.pages)for(let y of f.items)y.id&&!p.has(y.id)&&(p.add(y.id),m.push(y));return m},[a.data?.pages,a.error,o]),d=o?.spaceIds!==void 0&&gn(a.error);return{allItems:u,refetch:a.refetch,fetchNextPage:a.fetchNextPage,isFetchingNextPage:a.isFetchingNextPage,isExhausted:d||!a.hasNextPage,isLoading:a.isLoading,isFetching:a.isFetching,error:a.error,totalHint:d?void 0:a.data?.pages?.[0]?.total_hint}}function ic(e){return!!e?.type&&!!e.scope&&e.sort_by==="created_at"&&!e.offset&&!e.spaceIds&&!e.any_of&&!e.name&&!e.tag&&!e.discovery}function Xl(e,t){if(e.is_active===!1||e.item_type!==t.type||!pe(e.path,t.scope)||t.parent_id&&e.parent_id!==t.parent_id)return!1;let n=e.type_data??{};for(let[r,s]of Object.entries(t.fields??{})){let i=n[r];if(typeof s=="string"&&s.endsWith("*")){if(typeof i!="string"||!i.startsWith(s.slice(0,-1)))return!1}else if(i!==s)return!1}for(let[r,s]of Object.entries(t.field_in??{}))if(!s.includes(n[r]))return!1;return!0}function _c(e,t={}){let n=ic(e),r=Pi(e,n?{realtime:!1,staleTime:3e4}:{realtime:!0}),s=L(),i=JSON.stringify([H(),gt(e)]),[o,c]=(0,_.useState)(()=>({identity:i,upserts:{},deleted:new Set})),a=o.identity===i?o:{identity:i,upserts:{},deleted:new Set},u=(0,_.useMemo)(()=>{if(!n)return r.allItems;let f=Object.values(a.upserts),y=new Set(f.map(b=>b.id)),g=[...f,...r.allItems.filter(b=>!y.has(b.id))].filter(b=>!a.deleted.has(b.path)),h=e.sort_by??"updated_at",v=e.sort_dir==="asc"?1:-1;return g.sort((b,E)=>v*String(b[h]??"").localeCompare(String(E[h]??"")))},[n,r.allItems,a,e?.sort_by,e?.sort_dir]),d=(0,_.useRef)(u);d.current=u;let p=(0,_.useRef)(t.shouldReadUpdate);p.current=t.shouldReadUpdate;let m=(0,_.useRef)(r.refetch);return m.current=r.refetch,(0,_.useEffect)(()=>{if(!ic(e))return;let f=e,y=!1,g=!1,h=!1,v=0,b=new Map,E=()=>{let S=v;m.current().then(T=>{!y&&!T.isError&&v===S&&c({identity:i,upserts:{},deleted:new Set})})},I=S=>{v++,c(F=>{let k=F.identity===i?F:{identity:i,upserts:{},deleted:new Set},A={...k.upserts};return delete A[S],{identity:i,upserts:A,deleted:new Set(k.deleted).add(S)}});let T=b.get("__reconcile__");T&&clearTimeout(T),b.set("__reconcile__",setTimeout(()=>{b.delete("__reconcile__"),E()},250))},R=S=>{let T=b.get(S);T&&clearTimeout(T),b.set(S,setTimeout(()=>{b.delete(S),s.fetchQuery({queryKey:P.item(S),queryFn:()=>ar(S),staleTime:0}).then(F=>{if(!y){if(!F||!Xl(F,f)){let k=d.current.find(A=>A.path===S||A.id===F?.id);k&&I(k.path);return}c(k=>{let A=k.identity===i?k:{identity:i,upserts:{},deleted:new Set},U=new Set(A.deleted);return U.delete(S),{identity:i,upserts:{...A.upserts,[S]:F},deleted:U}})}}).catch(F=>console.warn("[useIncrementalItems] item read failed:",F))},250))},M=re("vfs_change",S=>{if(!S||typeof S.path!="string"&&typeof S.old_path!="string")return;let T=typeof S.path=="string"?S.path:S.old_path,F=d.current.find(A=>A.path===T||A.path===S.old_path||S.item_id&&A.id===S.item_id),k=!!F;if(!(!pe(T,f.scope)&&!pe(S.old_path,f.scope)&&!k)&&!(S.item_type&&S.item_type!==f.type&&!k)&&!(f.parent_id&&S.parent_id&&S.parent_id!==f.parent_id&&!k)){if(F&&(T!==F.path||S.old_path&&S.old_path!==T||S.parent_id&&S.parent_id!==F.parent_id||S.item_type&&S.item_type!==f.type)){I(F.path);return}if(!F&&S.old_path&&S.old_path!==T&&pe(T,f.scope)){v++,R(T);return}if(S.action==="insert")v++,R(T);else if(S.action==="move")v++,R(T);else if(S.action==="update"){if(!p.current?.(S,d.current))return;v++,R(T)}else S.action==="delete"&&I(F?.path??S.old_path??T)}}),N=Jr(S=>{if(S!=="connected"){g&&(h=!0);return}g=!0,h&&(h=!1,E())});return()=>{y=!0,M(),N(),b.forEach(clearTimeout)}},[s,i]),{...r,allItems:u}}function vc(e){Y();let t=20,n=Jn({queryKey:["vfs",H()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>Zr(e,t,s),initialPageParam:0,getNextPageParam:(s,i,o)=>{if(!(s.items.length<t))return o+s.items.length},enabled:!!e});return{allItems:(0,_.useMemo)(()=>{if(!n.data?.pages)return[];let s=new Set,i=[];for(let o of n.data.pages)for(let c of o.items)c.id&&!s.has(c.id)&&(s.add(c.id),i.push(c));return i},[n.data?.pages]),fetchNextPage:n.fetchNextPage,isFetchingNextPage:n.isFetchingNextPage,isExhausted:!n.hasNextPage,isLoading:n.isLoading,isFetching:n.isFetching,error:n.error,totalHint:n.data?.pages?.[0]?.total_hint}}function bc(e){return Y(),$({queryKey:P.edges(e),queryFn:()=>ts(e),enabled:!!e})}function ms(e){return Y(),$({queryKey:P.types(e),queryFn:()=>es(e)})}function wc(e,t){let n=ms(t);return{...n,data:n.data?.get(e)??void 0}}function Sc(e,t){Y();let n=(0,_.useMemo)(()=>t?.arguments,[JSON.stringify(t?.arguments)]),r=t?.mode,s=t?.strategy,i=t?.width;return $({queryKey:[...P.openEnvelope(e,s),i],queryFn:async()=>{let o=await os(e,{mode:r,strategy:s,arguments:n});if(i&&o.render?.props?.url){let c=o.render.props.url,a=c.includes("?")?"&":"?";o.render.props.url=`${c}${a}w=${i}`}return o},enabled:!!e})}var oc={related_to:"Related To",depends_on:"Depends On",blocks:"Blocks",parent_of:"Parent Of",child_of:"Child Of",references:"References",implements:"Implements",extends:"Extends",contains:"Contains",belongs_to:"Belongs To",created_by:"Created By",assigned_to:"Assigned To",tagged_with:"Tagged With",linked_to:"Linked To"};function Rc(e){let t=ms(e),n=t.data??new Map;return(0,_.useMemo)(()=>({canHaveChildren:f=>n.get(f.item_type)?.is_container??!1,isScope:f=>n.get(f.item_type)?.is_scope??!1,isScopeType:f=>n.get(f)?.is_scope??!1,isContainerType:f=>n.get(f)?.is_container??!1,getTypeDefinition:f=>n.get(f),getTypeColor:f=>n.get(f)?.color??"gray",getTypeIcon:f=>n.get(f)?.icon??"File",getTypeDisplayName:f=>n.get(f)?.display_name??f,getKnownEdgeTypes:()=>Object.entries(oc).map(([f,y])=>({key:f,label:y})),getEdgeTypeLabel:f=>oc[f]??f.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function xc(e,t,n){return Y(),$({queryKey:P.memberFocus(e),queryFn:()=>is(e,t,n),enabled:!!e})}function Pc(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return $({queryKey:P.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>ur(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function Cc(e,t=50,n=0){return $({queryKey:P.itemHistory(e,String(t),String(n)),queryFn:()=>ss(e,t,n),enabled:!!e})}function Tc(e,t=50,n=0){return Y(),$({queryKey:P.recentActivity(e,String(t),String(n)),queryFn:()=>rs(e,t,n),enabled:!!e})}function Ec(){let[e,t]=(0,_.useState)(null),[n,r]=(0,_.useState)(!0),[s,i]=(0,_.useState)(null);return(0,_.useEffect)(()=>{let o=!1;return Xe().then(c=>{if(!o){let a=typeof window<"u"&&window.__FSAOS_CONFIG__||{};t({path:c.scope_path,scope_id:c.scope_id,fractal_id:c.fractal_id,instance_name:c.instance_name,display_name:c.display_name,componentPath:a.componentPath||"",isEmbed:!!a.embedToken}),r(!1)}}).catch(c=>{o||(i(c instanceof Error?c:new Error(String(c))),r(!1))}),()=>{o=!0}},[]),{data:e,loading:n,error:s}}var Zl=[];function ac(){if(typeof window>"u")return!1;let e=window.__FSAOS_CONFIG__?.embedToken;return typeof e=="function"||typeof e=="string"&&e.length>0}function ed(e){return e.filter(t=>t.placement==="switcher_entry").map(t=>({account:t,mountables:e.filter(n=>n.placement!=="switcher_entry"&&n.subordinateTo===t.accountId)}))}function Ic(){let{user:e}=hs(),t=(0,_.useSyncExternalStore)(Jo,ai,ai),n=ht()?.principal_id??null,r=(0,_.useRef)(null),[s,i]=(0,_.useState)(null),[o,c]=(0,_.useState)(null);(0,_.useEffect)(()=>{if(n){c(null);return}if(!e?.id&&!ac()){c(null);return}let b=!1;return Xe().then(E=>{b||E.principal_id||c(new Error("Memberships require an authenticated principal"))}).catch(E=>{b||c(E instanceof Error?E:new Error(String(E)))}),()=>{b=!0}},[n,e?.id,t]);let a=$({queryKey:P.memberships(n??"anonymous"),queryFn:cs,enabled:!!n,staleTime:1e3*60*2}),u=a.data??Zl,d=(0,_.useMemo)(()=>u.filter(b=>b.isAccount!==!1&&!b.isSpace),[u]),p=(0,_.useMemo)(()=>{let b=new Set(d.map(I=>I.accountId)),E=I=>!I.subordinateTo||!b.has(I.subordinateTo);return[...d].sort((I,R)=>Number(E(R))-Number(E(I)))},[d]),m=(0,_.useSyncExternalStore)(we,ee,ee),f=(0,_.useMemo)(()=>{let b=ye();return b?u.find(E=>E.accountId===b.id)??null:null},[m,u]),y=(0,_.useMemo)(()=>ed(d),[d]);(0,_.useEffect)(()=>{if(!n){r.current=null;return}if(r.current!==n)if(i(null),p.length===1){let b=p[0];fe()||Mt(Ve(b)),Qt(b.accountId),b.personalSpacePath&&Dt(b.personalSpacePath,E=>{let I=u.find(R=>R.accountId===E);return I?Ve(I):null}).catch(i),r.current=n}else p.length>1&&(r.current=n)},[n,p,u]);let g=(0,_.useCallback)(async b=>{let E=u.find(M=>M.path===b);if(!E)throw new Error("Account membership is unavailable");let I=Ve(E);fe()||Mt(I);let R=u.find(M=>M.accountId===fe()?.id);if(!R?.personalSpacePath)throw new Error("The home membership has no mount declaration location");await Dt(R.personalSpacePath,M=>{let N=u.find(S=>S.accountId===M);return N?Ve(N):null}),await mr(I),i(null),Qt(E.accountId)},[u]),h=(0,_.useCallback)(async b=>{let E=u.find(I=>I.path===b);if(!E)throw new Error("Scope membership is unavailable");await wi(Ve(E))},[u]),v=(!!e?.id||ac())&&!n&&!o;return{accounts:p,switcherAccounts:y,allMemberships:u,currentAccount:f,mountedScope:null,switchAccount:g,mountScope:h,loading:v||a.isLoading,error:o??a.error??s}}function Ac(){Y();let e=(0,_.useSyncExternalStore)(Qr,tr,tr),t=(0,_.useMemo)(()=>Te(),[e]),n=ye(),r=(0,_.useMemo)(()=>t.filter(i=>i.kind==="space"&&(n?.kind==="account"||i.id===n?.id)),[t,n]),s=(0,_.useMemo)(()=>r.map(i=>i.id).sort(),[r]);return{mounts:t,selectedSpaces:r,readSpaceIds:s,homeAnchor:fe(),anchor:n,setAnchor:mr,replaceMounts:fs,mount:wi,unmount:nc}}function hs(){let[e,t]=(0,_.useState)(null),[n,r]=(0,_.useState)(null),[s,i]=(0,_.useState)(!0),o=(0,_.useRef)(null);(0,_.useEffect)(()=>{W.auth.getSession().then(({data:f,error:y})=>{if(y){console.warn("[useAuth] getSession error, clearing stale session:",y.message),W.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(f?.session??null),t(f?.session?.user??null),i(!1)}).catch(f=>{console.warn("[useAuth] getSession threw, clearing stale session:",f?.message),W.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:m}}=W.auth.onAuthStateChange((f,y)=>{if(f==="TOKEN_REFRESHED"&&!y){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),W.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(y),t(y?.user??null),i(!1)});return o.current=m,()=>{m?.unsubscribe()}},[]);let c=(0,_.useCallback)(async m=>m.provider?W.auth.signInWithOAuth({provider:m.provider,options:m.redirectTo?{redirectTo:m.redirectTo}:{redirectTo:window.location.href}}):W.auth.signInWithPassword({email:m.email,password:m.password}),[]),a=(0,_.useCallback)(async m=>W.auth.signUp({email:m.email,password:m.password,options:{data:m.metadata||{}}}),[]),u=(0,_.useCallback)(async()=>{await W.auth.signOut(),mn(),O().clear()},[]),d=(0,_.useCallback)(async m=>{let{error:f}=await W.auth.resetPasswordForEmail(m);if(f)throw f},[]),p=(0,_.useCallback)(async(m,f)=>{let{error:y}=await W.auth.signInWithOtp({email:m,options:f?{emailRedirectTo:f}:{emailRedirectTo:window.location.href}});if(y)throw y},[]);return{user:e,session:n,loading:s,signIn:c,signUp:a,signOut:u,resetPassword:d,signInWithMagicLink:p}}function kc(e){let[t,n]=(0,_.useState)(null),[r,s]=(0,_.useState)(!1),[i,o]=(0,_.useState)(null);return(0,_.useEffect)(()=>{if(!e){n(null),s(!1);return}if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e))s(!0),x("resolve-asset",{asset_id:e}).then(a=>{a.success&&a.public_url?n({url:a.public_url,id:a.asset_id,name:a.name,mimeType:a.mime_type,width:a.width,height:a.height,sizeBytes:a.size_bytes}):o(new Error(a.error||"Asset not found")),s(!1)}).catch(a=>{o(a instanceof Error?a:new Error(String(a))),s(!1)});else{let u=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";n({url:u+e}),s(!1)}},[e]),{data:t,loading:r,error:i}}var hr={},cc={};ne(()=>{for(let e of Object.keys(hr))delete hr[e]});var Mc=null;function Oc(e){Mc=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function td(e){switch(e){case"react":return typeof window<"u"&&window.React||_.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||Jl;case"react/jsx-runtime":case"react/jsx-dev-runtime":return typeof window<"u"&&window.React?{jsx:window.React.createElement,jsxs:window.React.createElement,Fragment:window.React.Fragment}:Yl;case"@fsaos/gateway":case"@fsaos/react":return typeof window<"u"&&window.__FSAOS_GATEWAY__||Mc||{};case"@fsaos/ui":return typeof window<"u"&&window.__FSAOS_UI__||{};case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}function nd(e,t){return e.replace(/^(\s*)(:root|body)(\s*[{,])/gm,(n,r,s,i)=>`${r}.${t}${i}`)}async function rd(e,t){if(!cc[e])try{let n=await fetch(e);if(!n.ok)return;let r=await n.text();if(!r.trim()||r.includes("No CSS bundle for this component"))return;t&&!r.includes(`.fsaos-c-${t}`)&&(r=nd(r,`fsaos-c-${t}`));let s=document.createElement("style");s.setAttribute("data-fsaos-component-css",e),t&&s.setAttribute("data-fsaos-component-id",t),s.textContent=r,document.head.appendChild(s),cc[e]=s}catch{}}function sd(e){let t=null,n=window.__FSAOS_REGISTER__;window.__FSAOS_REGISTER__=r=>{t=r};try{let r=["var require = arguments[0];",e,"return window.__FSAOS_COMPONENT__;"].join(`
3
- `),i=new Function(r)(td),o=t??i;return o?o.default||o:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function Ci(e){let[t,n]=(0,_.useState)(null),[r,s]=(0,_.useState)(!0),[i,o]=(0,_.useState)(null);return(0,_.useEffect)(()=>{if(!e)return;let c=!1;s(!0),o(null);let u=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{try{let d=1,p=e+"@v1",m=u+e+"/__bundle.js";try{let v=await fetch(u+e+"/__meta",{cache:"no-store"});v.ok&&(d=(await v.json()).version||1,p=e+"@v"+d,m=u+e+"/__bundle.v"+d+".js")}catch{m=u+e+"/__bundle.js?v="+Date.now()}if(c)return;if(hr[p]){n(()=>hr[p]),s(!1);return}let f=await fetch(m);if(!f.ok)throw new Error(`Failed to fetch bundle: ${f.status} ${f.statusText} (${m})`);let y=await f.text();if(c)return;let g=m.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");rd(g).catch(()=>{});let h=sd(y);if(!h)throw new Error("Bundle did not export a component. Expected window.__FSAOS_COMPONENT__ (FSAOS build) or a __FSAOS_REGISTER__(Component) call.");if(typeof h!="function")throw new Error(`Bundle export is not a React component (got ${typeof h})`);hr[p]=h,c||(n(()=>h),s(!1))}catch(d){c||(o(d instanceof Error?d:new Error(String(d))),s(!1))}})(),()=>{c=!0}},[e]),{Component:t,loading:r,error:i}}var id=["--color-primary","--color-secondary","--color-background","--color-surface","--color-text","--color-text-secondary","--color-border","--color-accent","--color-success","--color-warning","--color-error","--font-family-heading","--font-family-body","--border-radius","--spacing-unit"];function Fc(){return{data:(0,_.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let t={},n=getComputedStyle(document.documentElement);return id.forEach(r=>{t[r]=n.getPropertyValue(r).trim()}),{tokens:t}},[]),loading:!1,error:null}}function qc(e,t){return{data:{allowed:!0},loading:!1,error:null}}function Qc(e,t){let n={};return(t||[]).forEach(r=>{n[r]=!0}),{data:n,loading:!1,error:null}}var ue=null,En=null,Ri=new Set;function od(){Ri.forEach(e=>e())}ne(()=>{ue=null,En=null});async function Dc(e){let t={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null},n=ht()?.principal_id??null;if(n){if(ue&&ue.principalId===n){let{principalId:s,displayName:i,createdAt:o,metadata:c,vfsPath:a}=ue;return{principalId:s,displayName:i,createdAt:o,metadata:c,vfsPath:a}}return{...t,principalId:n}}let r=e;if(!r){let{data:s}=await W.auth.getSession();r=s?.session?.user?.id}if(!r)return t;if(ue&&ue.authUserId===r){let{principalId:s,displayName:i,createdAt:o,metadata:c,vfsPath:a}=ue;return{principalId:s,displayName:i,createdAt:o,metadata:c,vfsPath:a}}return En||(En=(async()=>{try{let{data:s,error:i}=await W.from("os_principals").select("id, display_name, created_at, metadata").eq("auth_user_id",r).eq("principal_type","user").maybeSingle();if(i)return console.warn("[SDK] Could not resolve principal:",i.message),t;let o=s?.id??null,c=null;if(o){let{data:u}=await W.from("os_items").select("path").eq("owner_principal_id",o).eq("item_type","principal").eq("is_active",!0).like("path","/root/principals/%"),d=(u??[]).map(p=>p.path);c=d.find(p=>p.split("/").length===4)??d[0]??null}let a={principalId:o,displayName:s?.display_name??null,createdAt:s?.created_at??null,metadata:s?.metadata??null,vfsPath:c};return ue={authUserId:r,...a},a}finally{En=null}})(),En)}async function Uc(e){return(await Dc(e)).principalId}function Nc(){let e=hs(),t=e.user,n=ue?.authUserId===t?.id?ue:null,[r,s]=(0,_.useState)(n),i=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let o=()=>{let c=ue;c&&c.authUserId===t?.id&&s({principalId:c.principalId,displayName:c.displayName,createdAt:c.createdAt,metadata:c.metadata,vfsPath:c.vfsPath})};return Ri.add(o),()=>{Ri.delete(o)}},[t?.id]),(0,_.useEffect)(()=>{if(!t?.id){s(null),i.current=null;return}i.current===t.id&&r?.principalId!=null||(i.current=t.id,Dc(t.id).then(o=>{s(o)}))},[t?.id]),e.loading?{data:null,loading:!0,error:null}:t?{data:{id:t.id,principalId:r?.principalId??null,email:t.email,display_name:r?.displayName??void 0,created_at:r?.createdAt??void 0,vfs_path:r?.vfsPath??void 0,role:t.role||t.app_metadata?.role||"user",authenticated:!0,metadata:r?.metadata??t.user_metadata??{}},loading:!1,error:null}:{data:{id:"anonymous",principalId:null,role:"viewer",authenticated:!1},loading:!1,error:null}}function Kc(){return{data:null,loading:!1,error:null}}function Lc(e){let{path:t,...n}=e,r=Ci(t),s=r.Component,{loading:i,error:o}=r;return i?(0,_.createElement)("div",{className:"fsaos-loading"},""):o?(0,_.createElement)("div",{className:"fsaos-error"},"Failed to load component"):s?(0,_.createElement)(s,n):null}function jc(e){return e.children}function Vc(e){let t=Y(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=e,o=i!==void 0?i&&!!n:!!n,c=(0,_.useMemo)(()=>P.channelMessages(n??"",r),[n,r,t]),a=L(),u=(0,_.useRef)(null),d=$({queryKey:c,queryFn:()=>as(n,r),enabled:o});(0,_.useEffect)(()=>{if(!s||!o)return;let g=re("vfs_change",()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{Ae(a,c,{exact:!0})},500)},h=>{let v=a.getQueryData(c);return Si(h,n,r,[...v?.messages??[],...v?.activityMessages??[]])});return()=>{g(),u.current&&clearTimeout(u.current)}},[s,o,n,r,c,a]);let p=d.data,m=p?.messages??[],f=p?.messageCards??new Map,y=p?.siblingCards??[];return{messages:m,activityMessages:p?.activityMessages??[],messageCards:f,siblingCards:y,threads:(0,_.useMemo)(()=>m.filter(g=>g.reply_count>0),[m]),breakouts:(0,_.useMemo)(()=>m.filter(g=>g.member_count>0),[m]),isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,refetch:d.refetch}}function $c(e){Y();let{channelPath:t,parentMessageId:n,limit:r=50,realtime:s=!0,enabled:i=!0}=e,o=!!n,c=i&&!!t,a=Jn({queryKey:[...P.channelMessages(t||"",n),"infinite",r],queryFn:async({pageParam:g})=>lr(t,{parentMessageId:n,limit:r,before_seq:o?void 0:g,after_seq:o?g:void 0}),initialPageParam:void 0,getNextPageParam:g=>!o||g.messages.length<r?void 0:g.messages[g.messages.length-1]?.seq,getPreviousPageParam:g=>o||g.messages.length<r?void 0:g.messages[0]?.seq,enabled:c}),u=(0,_.useMemo)(()=>{if(!a.data?.pages)return[];let g=new Set,h=[];for(let v of a.data.pages)for(let b of v.messages)g.has(b.id)||(g.add(b.id),h.push(b));return h.sort((v,b)=>v.seq-b.seq)},[a.data?.pages]),{messageCards:d,siblingCards:p}=(0,_.useMemo)(()=>{let g=new Map,h=[];if(!a.data?.pages)return{messageCards:g,siblingCards:h};let v=new Set;for(let b of a.data.pages){for(let[E,I]of b.messageCards)for(let R of I){if(v.has(R.id))continue;v.add(R.id);let M=g.get(E)||[];M.push(R),g.set(E,M)}for(let E of b.siblingCards)v.has(E.id)||(v.add(E.id),h.push(E))}return{messageCards:g,siblingCards:h}},[a.data?.pages]),m=L(),f=(0,_.useRef)(null),y=(0,_.useMemo)(()=>[...P.channelMessages(t||"",n),"infinite",r],[t,n,r]);return(0,_.useEffect)(()=>{if(!s||!t||!c)return;let g=()=>void Ae(m,y,{exact:!0}),h=!1,v=!1,b=!1,E=async()=>{let M=m.getQueryData(y);if(!M?.pages?.length){g();return}let N=0;for(let S of M.pages)for(let T of S.messages)T.seq>N&&(N=T.seq);if(N===0){g();return}try{let S=await lr(t,{parentMessageId:n,limit:r,after_seq:N});if(S.messages.length===0&&S.siblingCards.length===0){g();return}if(S.messages.length>0){let T=Math.min(...S.messages.map(F=>F.seq));if(T>N+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${N}, minNewSeq=${T}. Triggering full refetch.`),g();return}}m.setQueryData(y,T=>{if(!T)return T;let F=[...T.pages],k=F.length-1,A=F[k],U=new Set(A.messages.map(Re=>Re.id)),Q=S.messages.filter(Re=>!U.has(Re.id)),le=[...A.messages,...Q].sort((Re,xs)=>Re.seq-xs.seq),B=new Map(A.messageCards);for(let[Re,xs]of S.messageCards){let $i=B.get(Re)||[],rl=new Set($i.map(Ps=>Ps.id)),sl=xs.filter(Ps=>!rl.has(Ps.id));B.set(Re,[...$i,...sl])}let qe=new Set(A.siblingCards.map(Re=>Re.id)),tl=S.siblingCards.filter(Re=>!qe.has(Re.id)),nl=[...A.siblingCards,...tl];return F[k]={...A,activityMessages:S.activityMessages??[],messages:le,messageCards:B,siblingCards:nl},{...T,pages:F}})}catch(S){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",S),g()}},I=async()=>{if(h){v=!0;return}h=!0;try{do v=!1,await E();while(v&&!b)}finally{h=!1}},R=re("vfs_change",()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{I()},500)},M=>Si(M,t,n,m.getQueryData(y)?.pages.flatMap(N=>N.messages)??[]));return()=>{b=!0,R(),f.current&&clearTimeout(f.current)}},[s,t,c,y,m,n,r]),{messages:u,activityMessages:a.data?.pages.at(-1)?.activityMessages??[],messageCards:d,siblingCards:p,threads:u.filter(g=>g.reply_count>0),breakouts:u.filter(g=>g.member_count>0),isLoading:a.isLoading,isFetching:a.isFetching,error:a.error,refetch:a.refetch,hasPreviousPage:a.hasPreviousPage??!1,fetchPreviousPage:a.fetchPreviousPage,isFetchingPreviousPage:a.isFetchingPreviousPage??!1,hasNextPage:a.hasNextPage??!1,fetchNextPage:a.fetchNextPage,isFetchingNextPage:a.isFetchingNextPage??!1}}var Wc=["open","active","strict","hand_raise"];function ad(e){return e==="open"||e==="active"||e==="strict"||e==="hand_raise"?e:e==="on"||e==="auto"?"active":"strict"}function cd(e){if(Array.isArray(e))return e.filter(t=>typeof t=="string")}function uc(e){let t=e.type_data||{},n=e._reader||{},r=n.context_lineage||{};return{id:e.id||"",path:e.path||"",name:e.name||"",displayName:t.display_name||e.name||"",aiMode:ad(t.ai_mode),activeAgentIds:cd(t.active_agent_ids),isPrivate:t.is_private||!1,isDm:t.is_dm||!1,messageCount:t.message_count||0,createdAt:e.created_at||"",updatedAt:e.updated_at||"",chatScopePath:r.context_path||"",contextId:e.scope_item_id||"",contextPath:r.context_path||"",contextType:r.context_type||"",contextName:r.context_name||"",contextDisplayName:r.context_name||"",contextPrincipalId:void 0,accountId:e.account_item_id||"",accountPath:"",accountDisplayName:"",memberRole:n.member_role||"member",memberPath:"",modePath:"",autoPilot:t.auto_pilot||!1,isArchived:t.is_archived===!0}}function gs(e={}){let t=Y(),{realtime:n=!0,enabled:r=!0,includeArchived:s=!1}=e,i=L(),o=(0,_.useMemo)(()=>P.channels("all"),[t]),c=$({queryKey:o,queryFn:async()=>((await x("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(uc),enabled:r});return(0,_.useEffect)(()=>{if(!(!n||!r))return sc(i,o,uc)},[n,r,o,i]),{channels:(0,_.useMemo)(()=>(c.data??[]).filter(u=>s||!u.isArchived),[c.data,s]),isLoading:c.isLoading,isFetching:c.isFetching,error:c.error,refetch:c.refetch}}function Bc(e={}){let t=gs(e),n=(0,_.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function Hc(e={}){let t=gs(e),n=(0,_.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function Ti(e={}){let t=Y(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=e,o=L(),c=(0,_.useRef)(null),a=(0,_.useMemo)(()=>P.notifications(n,r),[n,r,t]),u=$({queryKey:a,queryFn:async()=>{let p={limit:r};return n==="unread"&&(p.filter="unread"),(await x("get-notifications",p)).notifications||[]},enabled:i});return(0,_.useEffect)(()=>{if(!s||!i)return;let p=["vfs_change","ccm_change"].map(m=>re(m,()=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{o.invalidateQueries({queryKey:a})},2e3)},f=>f.item_type==="notification"&&ps(f)));return()=>{p.forEach(m=>m()),c.current&&clearTimeout(c.current)}},[s,i,a,o]),{notifications:u.data??[],isLoading:u.isLoading,isFetching:u.isFetching,error:u.error,refetch:u.refetch}}function Gc(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:o,error:c,refetch:a}=Ti({filter:"unread",limit:200,realtime:n,enabled:r}),u=(0,_.useMemo)(()=>{let f=new Map;for(let y of s)y.is_unread&&y.channel_id&&f.set(y.channel_id,(f.get(y.channel_id)||0)+1);return f},[s]),d=(0,_.useMemo)(()=>{let f=0;return u.forEach(y=>{f+=y}),f},[u]),{dmUnread:p,channelUnread:m}=(0,_.useMemo)(()=>{if(!t)return{dmUnread:0,channelUnread:0};let f=new Set(t.filter(h=>h.isDm).map(h=>h.id)),y=0,g=0;return u.forEach((h,v)=>{f.has(v)?y+=h:g+=h}),{dmUnread:y,channelUnread:g}},[t,u]);return{unreadByChannel:u,totalUnread:d,dmUnread:p,channelUnread:m,isLoading:i,isFetching:o,error:c,refetch:a}}function zc(){let e=L();return Z({mutationFn:t=>x("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:P.children(r)})}})}function Jc(){let e=L();return Z({mutationFn:t=>x("update",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.invalidateQueries({queryKey:P.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:P.children(i)})}}})}function Yc(){return Z({mutationFn:e=>x("update-principal",e),onSuccess:(e,t)=>{if(!ue)return;let n=e&&typeof e=="object"&&e.metadata?e.metadata:{...ue.metadata??{},...typeof t.language=="string"?{language:t.language}:{},...typeof t.timezone=="string"?{timezone:t.timezone}:{},..."avatar_file_id"in t?{avatar_file_id:t.avatar_file_id}:{}};ue={...ue,displayName:typeof t.display_name=="string"?t.display_name:ue.displayName,metadata:n},od()}})}function Xc(){let e=L();return Z({mutationFn:t=>x("delete",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.removeQueries({queryKey:P.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:P.children(i)})}}})}function Zc(){let e=L();return Z({mutationFn:t=>x("move",t),onSuccess:(t,n)=>{let r=n.path,s=n.new_parent_path;if(r){e.invalidateQueries({queryKey:P.item(r)});let i=r.split("/");i.pop();let o=i.join("/");o&&e.invalidateQueries({queryKey:P.children(o)})}s&&e.invalidateQueries({queryKey:P.children(s)})}})}function eu(){let e=L();return Z({mutationFn:t=>x("link",t),onSuccess:(t,n)=>{let r=n.source_id,s=n.target_id;r&&e.invalidateQueries({queryKey:P.edges(r)}),s&&e.invalidateQueries({queryKey:P.edges(s)})}})}function tu(e,t){let n=L(),{optimistic:r,...s}=t??{};return Z({mutationFn:i=>x(e,i),onMutate:r?async i=>{await n.cancelQueries({queryKey:r.queryKey});let o=n.getQueryData(r.queryKey);return n.setQueryData(r.queryKey,c=>r.update(c,i)),{previous:o}}:void 0,onError:(i,o,c)=>{r&&c?.previous!==void 0&&n.setQueryData(r.queryKey,c.previous),s.onError?.(i)},onSuccess:s.onSuccess,onSettled:r?()=>{n.invalidateQueries({queryKey:r.queryKey})}:void 0})}function nu(e,t,n){let r,s,i,o=!0;if(typeof e=="string")r=e,s=t,i=n;else{s=e;let u=t;r=u.eventType,i=u.filter,o=u.enabled??!0}let c=(0,_.useRef)(s),a=(0,_.useRef)(i);(0,_.useEffect)(()=>{c.current=s,a.current=i},[s,i]),(0,_.useEffect)(()=>o?re(r,d=>c.current(d),a.current?d=>a.current(d):void 0):void 0,[r,o])}function ru(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:o=500}=e,c=L(),a=(0,_.useRef)(s);a.current=s;let u=(0,_.useRef)(null),d=$({queryKey:t,queryFn:n,enabled:i});return(0,_.useEffect)(()=>{if(!i)return;let p=re(r,()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{Ae(c,t,{exact:!0})},o)},m=>a.current?.(m)??!0);return()=>{p(),u.current&&clearTimeout(u.current)}},[r,i,o,c,JSON.stringify(t)]),d}function In(e){Y();let t=H(),n=(0,_.useMemo)(()=>e?typeof e=="string"?{path:e}:e:null,[typeof e=="string"?e:JSON.stringify(e)]),r=!!t&&!!n&&!!(n.key||n.path||n.item_id),s=n?.key??n?.path??n?.item_id??"",i=["vfs",t??"__unscoped__","arrangement",s,n?.scope_id??""],o=$({queryKey:i,staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0},queryFn:async()=>{if(!n)return null;let m=await x("resolve-arrangement",{...n,_scope_path:t});if(m?.success===!1)throw new Error(m?.error||"Arrangement could not be loaded");return m??null},enabled:r}),c=o.data??null,a=(0,_.useMemo)(()=>c?.resolved_children??[],[c]),u=c?.resolution_level??null,d=(0,_.useMemo)(()=>{let f=(c?.type_data??null)?.order;return Array.isArray(f)?f:null},[c]),p=(0,_.useCallback)(m=>{if(!d||!m?.length)return m??[];let f=v=>v.id??v.name??"",y=new Map(d.map((v,b)=>[v,b])),g=[],h=[];for(let v of m)(y.has(f(v))?g:h).push(v);return g.sort((v,b)=>y.get(f(v))-y.get(f(b))),[...g,...h]},[d]);return{...o,arrangement:c,resolvedChildren:a,resolutionLevel:u,order:d,sourceScopeId:c?.scope_item_id??null,arrangementQueryKey:i,applyTo:p}}function su(e){let{origin:t,originField:n,fallbackUrl:r,mintError:s,scopeId:i,scopePath:o}=e,c=Y(),a=ht(),u=i??a?.scope_id??null,d=(0,_.useMemo)(()=>{if(!t)return null;let R="/accounts/",M=t.indexOf(R);if(M===-1)return null;let N=t.indexOf("/",M+R.length);return N===-1?t:t.slice(0,N)},[t]),p=o??d??a?.scope_path??null,m=n?.trim()||null,f=`${c}
1
+ /* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-11-04T20:43:58.812Z */
2
+ "use strict";var __FSAOS_GATEWAY__=(()=>{var ol=Object.create;var Fn=Object.defineProperty;var al=Object.getOwnPropertyDescriptor;var cl=Object.getOwnPropertyNames;var ul=Object.getPrototypeOf,ll=Object.prototype.hasOwnProperty;var Wi=e=>{throw TypeError(e)};var dl=(e,t,n)=>t in e?Fn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var qn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),fl=(e,t)=>{for(var n in t)Fn(e,n,{get:t[n],enumerable:!0})},Bi=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of cl(t))!ll.call(e,s)&&s!==n&&Fn(e,s,{get:()=>t[s],enumerable:!(r=al(t,s))||r.enumerable});return e};var X=(e,t,n)=>(n=e!=null?ol(ul(e)):{},Bi(t||!e||!e.__esModule?Fn(n,"default",{value:e,enumerable:!0}):n,e)),pl=e=>Bi(Fn({},"__esModule",{value:!0}),e);var te=(e,t,n)=>dl(e,typeof t!="symbol"?t+"":t,n),Cs=(e,t,n)=>t.has(e)||Wi("Cannot "+n);var l=(e,t,n)=>(Cs(e,t,"read from private field"),n?n.call(e):t.get(e)),T=(e,t,n)=>t.has(e)?Wi("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),w=(e,t,n,r)=>(Cs(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),q=(e,t,n)=>(Cs(e,t,"access private method"),n);var Qn=(e,t,n,r)=>({set _(s){w(e,t,s,n)},get _(){return l(e,t,r)}});var ae=qn((Md,Hi)=>{Hi.exports=React});var Ir=qn((Ap,Eo)=>{Eo.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var Lo=qn((am,Ko)=>{Ko.exports={createClient:window.supabase.createClient}});var ha=qn((bm,ma)=>{ma.exports=ReactDOM});var Su=qn((mg,wu)=>{wu.exports=ReactDOM});var Vi={};fl(Vi,{CHANNEL_AI_MODES:()=>Wc,ComponentRenderer:()=>Lc,EnforcementDeniedError:()=>rt,FormSubmissionError:()=>On,GatewayRequestError:()=>Ae,InteractionTrackingError:()=>kn,KernelProvider:()=>jc,QueryClientProvider:()=>Gn,acceptInvite:()=>Fi,answerInput:()=>Di,assignPersonalSection:()=>Xu,auth:()=>Mu,awaitAnchorReady:()=>er,awaitScopeReady:()=>Zo,callTool:()=>Iu,cancelQueuedTurn:()=>vu,cancelTurn:()=>yu,clearCachedToken:()=>ei,clearSession:()=>ci,configureGatewayReads:()=>ua,createAgent:()=>Qi,createItem:()=>Cu,disconnectSSE:()=>_i,disposeVfsRealtimeWs:()=>bi,electHomeAnchor:()=>Mt,emitEvent:()=>qa,fetchChannelMessages:()=>Wa,fetchChannelMessagesPage:()=>lr,fetchChannelMessagesWithCards:()=>as,fetchEdgesForItem:()=>ts,fetchItemHistory:()=>ss,fetchItemVersions:()=>ur,fetchItems:()=>xn,fetchMemberFocus:()=>is,fetchOpenEnvelope:()=>os,fetchRecentActivity:()=>rs,fetchResolvedItems:()=>Ni,fetchTimelineHistory:()=>Ki,fetchTurnQueueEntries:()=>ja,fetchTypeDefinitions:()=>es,fetchVfsChildren:()=>cr,fetchVfsChildrenPage:()=>Zr,fetchVfsItem:()=>ar,fetchVfsItemById:()=>Xr,fetchVfsTree:()=>ns,gatewayCall:()=>x,getAccessToken:()=>Ye,getAnchor:()=>pn,getAnchorRef:()=>ye,getAnchorVersion:()=>ri,getAssetUrl:()=>ku,getDefaultSort:()=>Lu,getHomeAnchor:()=>fe,getMountVersion:()=>tr,getMounts:()=>Ee,getPathSubscriptionState:()=>Da,getQueryClient:()=>O,getRequiredFormFields:()=>ju,getScope:()=>B,getScopeVersion:()=>ee,getServerClockOffsetMs:()=>sa,getServerClockSyncedAt:()=>ia,getSessionEntry:()=>ht,hasServerClock:()=>ra,initSession:()=>Xe,initVfsRealtimeWs:()=>Qt,initializeFsaos:()=>gu,initializeWorkspace:()=>vs,interpretSchema:()=>Ui,invalidateAllVfs:()=>Ga,invalidateChannelMessages:()=>Ja,invalidateChildren:()=>Yr,invalidateItem:()=>vi,invalidateOpenEnvelope:()=>Ya,invalidatePathAndParent:()=>Ba,invalidateSubtree:()=>Ha,invalidateTypes:()=>za,inviteMember:()=>Oi,isAnchorReady:()=>ii,isChannelPath:()=>pe,isListableItemsFilter:()=>Rn,isScopeReady:()=>Dr,itemsFilterFromQueryFilter:()=>Va,listChildren:()=>Pu,loadMounts:()=>Dt,mount:()=>Ou,mountRealtimeScope:()=>Cn,normalizeItem:()=>_e,onConnectionStateChange:()=>Jr,pathSubscriptionMatches:()=>hi,personalSectionsKey:()=>vr,ping:()=>Qa,pushChanges:()=>Eu,queryClient:()=>Sa,readItem:()=>xu,refreshQuery:()=>ke,registerCleanup:()=>ne,replaceMounts:()=>fs,resetAllSdkState:()=>mn,resolvePrincipalId:()=>Uc,resubscribePath:()=>Na,seatMember:()=>qi,selectMount:()=>mr,serverDeadlinePassed:()=>oa,serverMsUntil:()=>aa,serverNow:()=>Ur,setAnchor:()=>qr,setCachedToken:()=>$o,setQueryClient:()=>wa,setScope:()=>Xo,setupRequireShim:()=>Fu,signal:()=>Au,startTracking:()=>_s,steerTurn:()=>_u,submitForm:()=>bu,subscribeAnchor:()=>si,subscribeArtifactStream:()=>bs,subscribeMounts:()=>Qr,subscribeScope:()=>we,subscribeToEvents:()=>re,subscribeToPath:()=>zr,subscribeToScope:()=>Sn,trackAction:()=>pu,trackEvent:()=>Nt,trackPageView:()=>fu,unmountRealtimeScope:()=>ls,updateItem:()=>Tu,uploadFile:()=>Vu,useAcceptInvite:()=>Qu,useAccounts:()=>Ic,useAgentTimeline:()=>zu,useAllChannels:()=>gs,useAnswerInput:()=>Nu,useArrangement:()=>In,useArtifactStream:()=>Gu,useAsset:()=>kc,useAuth:()=>hs,useChannelMessages:()=>Vc,useChannels:()=>Bc,useChildren:()=>pc,useComponent:()=>Ci,useCreate:()=>zc,useCreateAgent:()=>Uu,useDelete:()=>Xc,useDmChannels:()=>Hc,useEdges:()=>bc,useEventStream:()=>nu,useFileUpload:()=>Wu,useIncrementalItems:()=>_c,useInfiniteChannelMessages:()=>$c,useInfiniteChildren:()=>vc,useInfiniteItems:()=>Pi,useInviteMember:()=>qu,useItem:()=>dc,useItemById:()=>fc,useItemHistory:()=>Cc,useItemVersions:()=>Pc,useItems:()=>yc,useLink:()=>eu,useList:()=>xi,useMemberFocus:()=>xc,useMintedAsset:()=>su,useMounts:()=>Ac,useMove:()=>Zc,useMutation:()=>tu,useNotifications:()=>Ti,useOpen:()=>Sc,usePermission:()=>qc,usePermissions:()=>Qc,usePersonalItemOrder:()=>ou,usePersonalSections:()=>el,usePinnedItems:()=>Yu,usePrincipal:()=>Nc,useRealtimeQuery:()=>ru,useRecentActivity:()=>Tc,useResolve:()=>gc,useResolvedItems:()=>Hu,useScope:()=>Ec,useScopeReady:()=>lc,useSearch:()=>hc,useSeatMember:()=>Du,useTheme:()=>Fc,useTimelineHistory:()=>Ju,useTool:()=>Kc,useTree:()=>mc,useType:()=>wc,useTypeHelpers:()=>Rc,useTypes:()=>ms,useUnreadCounts:()=>Gc,useUpdate:()=>Jc,useUpdatePrincipal:()=>Yc,vfsKeys:()=>P,waitForPathReady:()=>Ua});var rt=class e extends Error{constructor(n){let r=n.message||e.fallbackMessage(n);super(r);te(this,"name","EnforcementDeniedError");te(this,"deniedBy");te(this,"ruleKey");te(this,"displayName");this.deniedBy=n.denied_by||n.error_type||n.error||"unknown";let s=n.enforcement;this.ruleKey=s?.rule_key??void 0,this.displayName=s?.display_name??void 0}static fallbackMessage(n){let r=n.error||"",s=n.denied_by||"";return s==="rule"||r==="RULE_DENIED"?"This feature is not enabled for this workspace.":s==="entitlement"||r==="ENTITLEMENT_REQUIRED"?"This feature requires a plan upgrade.":s==="access"||r==="ACCESS_DENIED"||r==="PERMISSION_DENIED"?"You don't have permission to do this.":"This action is not allowed."}get isRuleDenial(){return this.deniedBy==="rule"||this.deniedBy==="RULE_DENIED"}get isAccessDenial(){return this.deniedBy==="access"||this.deniedBy==="ACCESS_DENIED"}get isEntitlementDenial(){return this.deniedBy==="entitlement"||this.deniedBy==="ENTITLEMENT_REQUIRED"}};var An=X(ae(),1);var Pe=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var bt,st,Lt,Gi,ml=(Gi=class extends Pe{constructor(){super();T(this,bt);T(this,st);T(this,Lt);w(this,Lt,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){l(this,st)||this.setEventListener(l(this,Lt))}onUnsubscribe(){var t;this.hasListeners()||((t=l(this,st))==null||t.call(this),w(this,st,void 0))}setEventListener(t){var n;w(this,Lt,t),(n=l(this,st))==null||n.call(this),w(this,st,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){l(this,bt)!==t&&(w(this,bt,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof l(this,bt)=="boolean"?l(this,bt):globalThis.document?.visibilityState!=="hidden"}},bt=new WeakMap,st=new WeakMap,Lt=new WeakMap,Gi),jt=new ml;var hl={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},it,Ts,zi,gl=(zi=class{constructor(){T(this,it,hl);T(this,Ts,!1)}setTimeoutProvider(e){w(this,it,e)}setTimeout(e,t){return l(this,it).setTimeout(e,t)}clearTimeout(e){l(this,it).clearTimeout(e)}setInterval(e,t){return l(this,it).setInterval(e,t)}clearInterval(e){l(this,it).clearInterval(e)}},it=new WeakMap,Ts=new WeakMap,zi),Qe=new gl;function Ji(e){setTimeout(e,0)}var Is=typeof window>"u"||"Deno"in globalThis;function G(){}function Zi(e,t){return typeof e=="function"?e(t):e}function Dn(e){return typeof e=="number"&&e>=0&&e!==1/0}function br(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Oe(e,t){return typeof e=="function"?e(t):e}function me(e,t){return typeof e=="function"?e(t):e}function wr(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:o,stale:a}=e;if(o){if(r){if(t.queryHash!==Un(o,t.options))return!1}else if(!wt(t.queryKey,o))return!1}if(n!=="all"){let c=t.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof a=="boolean"&&t.isStale()!==a||s&&s!==t.state.fetchStatus||i&&!i(t))}function Sr(e,t){let{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(De(t.options.mutationKey)!==De(i))return!1}else if(!wt(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function Un(e,t){return(t?.queryKeyHashFn||De)(e)}function De(e){return JSON.stringify(e,(t,n)=>Es(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function wt(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>wt(e[n],t[n])):!1}var yl=Object.prototype.hasOwnProperty;function As(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=Yi(e)&&Yi(t);if(!r&&!(Es(e)&&Es(t)))return t;let i=(r?e:Object.keys(e)).length,o=r?t:Object.keys(t),a=o.length,c=r?new Array(a):{},u=0;for(let d=0;d<a;d++){let p=r?d:o[d],h=e[p],f=t[p];if(h===f){c[p]=h,(r?d<i:yl.call(e,p))&&u++;continue}if(h===null||f===null||typeof h!="object"||typeof f!="object"){c[p]=f;continue}let g=As(h,f,n+1);c[p]=g,g===h&&u++}return i===a&&u===i?e:c}function Vt(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function Yi(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Es(e){if(!Xi(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Xi(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Xi(e){return Object.prototype.toString.call(e)==="[object Object]"}function eo(e){return new Promise(t=>{Qe.setTimeout(t,e)})}function Nn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?As(e,t):t}function to(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function no(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var $t=Symbol();function Rr(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===$t?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Wt(e,t){return typeof e=="function"?e(...t):!!e}function ro(e,t,n){let r=!1,s;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(s??(s=t()),r||(r=!0,s.aborted?n():s.addEventListener("abort",n,{once:!0})),s)}),e}var Ue=(()=>{let e=()=>Is;return{isServer(){return e()},setIsServer(t){e=t}}})();function Kn(){let e,t,n=new Promise((s,i)=>{e=s,t=i});n.status="pending",n.catch(()=>{});function r(s){Object.assign(n,s),delete n.resolve,delete n.reject}return n.resolve=s=>{r({status:"fulfilled",value:s}),e(s)},n.reject=s=>{r({status:"rejected",reason:s}),t(s)},n}var so=Ji;function _l(){let e=[],t=0,n=a=>{a()},r=a=>{a()},s=so,i=a=>{t?e.push(a):s(()=>{n(a)})},o=()=>{let a=e;e=[],a.length&&s(()=>{r(()=>{a.forEach(c=>{n(c)})})})};return{batch:a=>{let c;t++;try{c=a()}finally{t--,t||o()}return c},batchCalls:a=>(...c)=>{i(()=>{a(...c)})},schedule:i,setNotifyFunction:a=>{n=a},setBatchNotifyFunction:a=>{r=a},setScheduler:a=>{s=a}}}var V=_l();var Bt,ot,Ht,io,vl=(io=class extends Pe{constructor(){super();T(this,Bt,!0);T(this,ot);T(this,Ht);w(this,Ht,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){l(this,ot)||this.setEventListener(l(this,Ht))}onUnsubscribe(){var t;this.hasListeners()||((t=l(this,ot))==null||t.call(this),w(this,ot,void 0))}setEventListener(t){var n;w(this,Ht,t),(n=l(this,ot))==null||n.call(this),w(this,ot,t(this.setOnline.bind(this)))}setOnline(t){l(this,Bt)!==t&&(w(this,Bt,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return l(this,Bt)}},Bt=new WeakMap,ot=new WeakMap,Ht=new WeakMap,io),Gt=new vl;function bl(e){return Math.min(1e3*2**e,3e4)}function ks(e){return(e??"online")==="online"?Gt.isOnline():!0}var xr=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Pr(e){let t=!1,n=0,r,s=Kn(),i=()=>s.status!=="pending",o=y=>{if(!i()){let m=new xr(y);h(m),e.onCancel?.(m)}},a=()=>{t=!0},c=()=>{t=!1},u=()=>jt.isFocused()&&(e.networkMode==="always"||Gt.isOnline())&&e.canRun(),d=()=>ks(e.networkMode)&&e.canRun(),p=y=>{i()||(r?.(),s.resolve(y))},h=y=>{i()||(r?.(),s.reject(y))},f=()=>new Promise(y=>{r=m=>{(i()||u())&&y(m)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),g=()=>{if(i())return;let y,m=n===0?e.initialPromise:void 0;try{y=m??e.fn()}catch(v){y=Promise.reject(v)}Promise.resolve(y).then(p).catch(v=>{if(i())return;let b=e.retry??(Ue.isServer()?0:3),E=e.retryDelay??bl,I=typeof E=="function"?E(n,v):E,R=b===!0||typeof b=="number"&&n<b||typeof b=="function"&&b(n,v);if(t||!R){h(v);return}n++,e.onFail?.(n,v),eo(I).then(()=>u()?void 0:f()).then(()=>{t?h(v):g()})})};return{promise:s,status:()=>s.status,cancel:o,continue:()=>(r?.(),s),cancelRetry:a,continueRetry:c,canStart:d,start:()=>(d()?g():f().then(g),s)}}var St,oo,Cr=(oo=class{constructor(){T(this,St)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Dn(this.gcTime)&&w(this,St,Qe.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ue.isServer()?1/0:5*60*1e3))}clearGcTimeout(){l(this,St)!==void 0&&(Qe.clearTimeout(l(this,St)),w(this,St,void 0))}},St=new WeakMap,oo);var Rt,zt,Ce,xt,se,Ln,Pt,be,fo,$e,uo,lo=(uo=class extends Cr{constructor(t){super();T(this,be);T(this,Rt);T(this,zt);T(this,Ce);T(this,xt);T(this,se);T(this,Ln);T(this,Pt);w(this,Pt,!1),w(this,Ln,t.defaultOptions),this.setOptions(t.options),this.observers=[],w(this,xt,t.client),w(this,Ce,l(this,xt).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,w(this,Rt,co(this.options)),this.state=t.state??l(this,Rt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return l(this,se)?.promise}setOptions(t){if(this.options={...l(this,Ln),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=co(this.options);n.data!==void 0&&(this.setState(ao(n.data,n.dataUpdatedAt)),w(this,Rt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&l(this,Ce).remove(this)}setData(t,n){let r=Nn(this.state.data,t,this.options);return q(this,be,$e).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){q(this,be,$e).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=l(this,se)?.promise;return l(this,se)?.cancel(t),n?n.then(G).catch(G):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return l(this,Rt)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>me(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===$t||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>Oe(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!br(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),l(this,se)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),l(this,se)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),l(this,Ce).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(l(this,se)&&(l(this,Pt)||q(this,be,fo).call(this)?l(this,se).cancel({revert:!0}):l(this,se).cancelRetry()),this.scheduleGc()),l(this,Ce).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||q(this,be,$e).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&l(this,se)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(l(this,se))return l(this,se).continueRetry(),l(this,se).promise}if(t&&this.setOptions(t),!this.options.queryFn){let c=this.observers.find(u=>u.options.queryFn);c&&this.setOptions(c.options)}let r=new AbortController,s=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(w(this,Pt,!0),r.signal)})},i=()=>{let c=Rr(this.options,n),d=(()=>{let p={client:l(this,xt),queryKey:this.queryKey,meta:this.meta};return s(p),p})();return w(this,Pt,!1),this.options.persister?this.options.persister(c,d,this):c(d)},a=(()=>{let c={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:l(this,xt),state:this.state,fetchFn:i};return s(c),c})();this.options.behavior?.onFetch(a,this),w(this,zt,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&q(this,be,$e).call(this,{type:"fetch",meta:a.fetchOptions?.meta}),w(this,se,Pr({initialPromise:n?.initialPromise,fn:a.fetchFn,onCancel:c=>{c instanceof xr&&c.revert&&this.setState({...l(this,zt),fetchStatus:"idle"}),r.abort()},onFail:(c,u)=>{q(this,be,$e).call(this,{type:"failed",failureCount:c,error:u})},onPause:()=>{q(this,be,$e).call(this,{type:"pause"})},onContinue:()=>{q(this,be,$e).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0}));try{let c=await l(this,se).start();if(c===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(c),l(this,Ce).config.onSuccess?.(c,this),l(this,Ce).config.onSettled?.(c,this.state.error,this),c}catch(c){if(c instanceof xr){if(c.silent)return l(this,se).promise;if(c.revert){if(this.state.data===void 0)throw c;return this.state.data}}throw q(this,be,$e).call(this,{type:"error",error:c}),l(this,Ce).config.onError?.(c,this),l(this,Ce).config.onSettled?.(this.state.data,c,this),c}finally{this.scheduleGc()}}},Rt=new WeakMap,zt=new WeakMap,Ce=new WeakMap,xt=new WeakMap,se=new WeakMap,Ln=new WeakMap,Pt=new WeakMap,be=new WeakSet,fo=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},$e=function(t){let n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...Ms(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...ao(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return w(this,zt,t.manual?s:void 0),s;case"error":let i=t.error;return{...r,error:i,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),V.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),l(this,Ce).notify({query:this,type:"updated",action:t})})},uo);function Ms(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ks(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function ao(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function co(e){let t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var he,K,Vn,de,Ct,Jt,We,at,$n,Yt,Xt,Tt,Et,ct,Zt,j,jn,Os,Fs,qs,Qs,Ds,Us,Ns,go,ho,Wn=(ho=class extends Pe{constructor(t,n){super();T(this,j);T(this,he);T(this,K);T(this,Vn);T(this,de);T(this,Ct);T(this,Jt);T(this,We);T(this,at);T(this,$n);T(this,Yt);T(this,Xt);T(this,Tt);T(this,Et);T(this,ct);T(this,Zt,new Set);this.options=n,w(this,he,t),w(this,at,null),w(this,We,Kn()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(l(this,K).addObserver(this),po(l(this,K),this.options)?q(this,j,jn).call(this):this.updateResult(),q(this,j,Qs).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ks(l(this,K),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ks(l(this,K),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,q(this,j,Ds).call(this),q(this,j,Us).call(this),l(this,K).removeObserver(this)}setOptions(t){let n=this.options,r=l(this,K);if(this.options=l(this,he).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof me(this.options.enabled,l(this,K))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");q(this,j,Ns).call(this),l(this,K).setOptions(this.options),n._defaulted&&!Vt(this.options,n)&&l(this,he).getQueryCache().notify({type:"observerOptionsUpdated",query:l(this,K),observer:this});let s=this.hasListeners();s&&mo(l(this,K),r,this.options,n)&&q(this,j,jn).call(this),this.updateResult(),s&&(l(this,K)!==r||me(this.options.enabled,l(this,K))!==me(n.enabled,l(this,K))||Oe(this.options.staleTime,l(this,K))!==Oe(n.staleTime,l(this,K)))&&q(this,j,Os).call(this);let i=q(this,j,Fs).call(this);s&&(l(this,K)!==r||me(this.options.enabled,l(this,K))!==me(n.enabled,l(this,K))||i!==l(this,ct))&&q(this,j,qs).call(this,i)}getOptimisticResult(t){let n=l(this,he).getQueryCache().build(l(this,he),t),r=this.createResult(n,t);return Sl(this,r)&&(w(this,de,r),w(this,Jt,this.options),w(this,Ct,l(this,K).state)),r}getCurrentResult(){return l(this,de)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&l(this,We).status==="pending"&&l(this,We).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){l(this,Zt).add(t)}getCurrentQuery(){return l(this,K)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=l(this,he).defaultQueryOptions(t),r=l(this,he).getQueryCache().build(l(this,he),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return q(this,j,jn).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),l(this,de)))}createResult(t,n){let r=l(this,K),s=this.options,i=l(this,de),o=l(this,Ct),a=l(this,Jt),u=t!==r?t.state:l(this,Vn),{state:d}=t,p={...d},h=!1,f;if(n._optimisticResults){let C=this.hasListeners(),M=!C&&po(t,n),A=C&&mo(t,r,n,s);(M||A)&&(p={...p,...Ms(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(p.fetchStatus="idle")}let{error:g,errorUpdatedAt:y,status:m}=p;f=p.data;let v=!1;if(n.placeholderData!==void 0&&f===void 0&&m==="pending"){let C;i?.isPlaceholderData&&n.placeholderData===a?.placeholderData?(C=i.data,v=!0):C=typeof n.placeholderData=="function"?n.placeholderData(l(this,Xt)?.state.data,l(this,Xt)):n.placeholderData,C!==void 0&&(m="success",f=Nn(i?.data,C,n),h=!0)}if(n.select&&f!==void 0&&!v)if(i&&f===o?.data&&n.select===l(this,$n))f=l(this,Yt);else try{w(this,$n,n.select),f=n.select(f),f=Nn(i?.data,f,n),w(this,Yt,f),w(this,at,null)}catch(C){w(this,at,C)}l(this,at)&&(g=l(this,at),f=l(this,Yt),y=Date.now(),m="error");let b=p.fetchStatus==="fetching",E=m==="pending",I=m==="error",R=E&&b,F=f!==void 0,S={status:m,fetchStatus:p.fetchStatus,isPending:E,isSuccess:m==="success",isError:I,isInitialLoading:R,isLoading:R,data:f,dataUpdatedAt:p.dataUpdatedAt,error:g,errorUpdatedAt:y,failureCount:p.fetchFailureCount,failureReason:p.fetchFailureReason,errorUpdateCount:p.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:p.dataUpdateCount>u.dataUpdateCount||p.errorUpdateCount>u.errorUpdateCount,isFetching:b,isRefetching:b&&!E,isLoadingError:I&&!F,isPaused:p.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:I&&F,isStale:Ls(t,n),refetch:this.refetch,promise:l(this,We),isEnabled:me(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let C=S.data!==void 0,M=S.status==="error"&&!C,A=D=>{M?D.reject(S.error):C&&D.resolve(S.data)},k=()=>{let D=w(this,We,S.promise=Kn());A(D)},Q=l(this,We);switch(Q.status){case"pending":t.queryHash===r.queryHash&&A(Q);break;case"fulfilled":(M||S.data!==Q.value)&&k();break;case"rejected":(!M||S.error!==Q.reason)&&k();break}}return S}updateResult(){let t=l(this,de),n=this.createResult(l(this,K),this.options);if(w(this,Ct,l(this,K).state),w(this,Jt,this.options),l(this,Ct).data!==void 0&&w(this,Xt,l(this,K)),Vt(n,t))return;w(this,de,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!l(this,Zt).size)return!0;let o=new Set(i??l(this,Zt));return this.options.throwOnError&&o.add("error"),Object.keys(l(this,de)).some(a=>{let c=a;return l(this,de)[c]!==t[c]&&o.has(c)})};q(this,j,go).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&q(this,j,Qs).call(this)}},he=new WeakMap,K=new WeakMap,Vn=new WeakMap,de=new WeakMap,Ct=new WeakMap,Jt=new WeakMap,We=new WeakMap,at=new WeakMap,$n=new WeakMap,Yt=new WeakMap,Xt=new WeakMap,Tt=new WeakMap,Et=new WeakMap,ct=new WeakMap,Zt=new WeakMap,j=new WeakSet,jn=function(t){q(this,j,Ns).call(this);let n=l(this,K).fetch(this.options,t);return t?.throwOnError||(n=n.catch(G)),n},Os=function(){q(this,j,Ds).call(this);let t=Oe(this.options.staleTime,l(this,K));if(Ue.isServer()||l(this,de).isStale||!Dn(t))return;let r=br(l(this,de).dataUpdatedAt,t)+1;w(this,Tt,Qe.setTimeout(()=>{l(this,de).isStale||this.updateResult()},r))},Fs=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(l(this,K)):this.options.refetchInterval)??!1},qs=function(t){q(this,j,Us).call(this),w(this,ct,t),!(Ue.isServer()||me(this.options.enabled,l(this,K))===!1||!Dn(l(this,ct))||l(this,ct)===0)&&w(this,Et,Qe.setInterval(()=>{(this.options.refetchIntervalInBackground||jt.isFocused())&&q(this,j,jn).call(this)},l(this,ct)))},Qs=function(){q(this,j,Os).call(this),q(this,j,qs).call(this,q(this,j,Fs).call(this))},Ds=function(){l(this,Tt)!==void 0&&(Qe.clearTimeout(l(this,Tt)),w(this,Tt,void 0))},Us=function(){l(this,Et)!==void 0&&(Qe.clearInterval(l(this,Et)),w(this,Et,void 0))},Ns=function(){let t=l(this,he).getQueryCache().build(l(this,he),this.options);if(t===l(this,K))return;let n=l(this,K);w(this,K,t),w(this,Vn,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},go=function(t){V.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(l(this,de))}),l(this,he).getQueryCache().notify({query:l(this,K),type:"observerResultsUpdated"})})},ho);function wl(e,t){return me(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function po(e,t){return wl(e,t)||e.state.data!==void 0&&Ks(e,t,t.refetchOnMount)}function Ks(e,t,n){if(me(t.enabled,e)!==!1&&Oe(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Ls(e,t)}return!1}function mo(e,t,n,r){return(e!==t||me(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Ls(e,n)}function Ls(e,t){return me(t.enabled,e)!==!1&&e.isStaleByTime(Oe(t.staleTime,e))}function Sl(e,t){return!Vt(e.getCurrentResult(),t)}function en(e){return{onFetch:(t,n)=>{let r=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],o=t.state.data?.pageParams||[],a={pages:[],pageParams:[]},c=0,u=async()=>{let d=!1,p=g=>{ro(g,()=>t.signal,()=>d=!0)},h=Rr(t.options,t.fetchOptions),f=async(g,y,m)=>{if(d)return Promise.reject();if(y==null&&g.pages.length)return Promise.resolve(g);let b=(()=>{let F={client:t.client,queryKey:t.queryKey,pageParam:y,direction:m?"backward":"forward",meta:t.options.meta};return p(F),F})(),E=await h(b),{maxPages:I}=t.options,R=m?no:to;return{pages:R(g.pages,E,I),pageParams:R(g.pageParams,y,I)}};if(s&&i.length){let g=s==="backward",y=g?yo:js,m={pages:i,pageParams:o},v=y(r,m);a=await f(m,v,g)}else{let g=e??i.length;do{let y=c===0?o[0]??r.initialPageParam:js(r,a);if(c>0&&y==null)break;a=await f(a,y),c++}while(c<g)}return a};t.options.persister?t.fetchFn=()=>t.options.persister?.(u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=u}}}function js(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function yo(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function _o(e,t){return t?js(e,t)!=null:!1}function vo(e,t){return!t||!e.getPreviousPageParam?!1:yo(e,t)!=null}var Vs=class extends Wn{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){super.setOptions({...e,behavior:en()})}getOptimisticResult(e){return e.behavior=en(),super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){let{state:n}=e,r=super.createResult(e,t),{isFetching:s,isRefetching:i,isError:o,isRefetchError:a}=r,c=n.fetchMeta?.fetchMore?.direction,u=o&&c==="forward",d=s&&c==="forward",p=o&&c==="backward",h=s&&c==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:_o(t,n.data),hasPreviousPage:vo(t,n.data),isFetchNextPageError:u,isFetchingNextPage:d,isFetchPreviousPageError:p,isFetchingPreviousPage:h,isRefetchError:a&&!u&&!p,isRefetching:i&&!d&&!h}}};var Bn,Ne,ce,It,Ke,ut,bo,wo=(bo=class extends Cr{constructor(t){super();T(this,Ke);T(this,Bn);T(this,Ne);T(this,ce);T(this,It);w(this,Bn,t.client),this.mutationId=t.mutationId,w(this,ce,t.mutationCache),w(this,Ne,[]),this.state=t.state||$s(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){l(this,Ne).includes(t)||(l(this,Ne).push(t),this.clearGcTimeout(),l(this,ce).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){w(this,Ne,l(this,Ne).filter(n=>n!==t)),this.scheduleGc(),l(this,ce).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){l(this,Ne).length||(this.state.status==="pending"?this.scheduleGc():l(this,ce).remove(this))}continue(){return l(this,It)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{q(this,Ke,ut).call(this,{type:"continue"})},r={client:l(this,Bn),meta:this.options.meta,mutationKey:this.options.mutationKey};w(this,It,Pr({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(o,a)=>{q(this,Ke,ut).call(this,{type:"failed",failureCount:o,error:a})},onPause:()=>{q(this,Ke,ut).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>l(this,ce).canRun(this)}));let s=this.state.status==="pending",i=!l(this,It).canStart();try{if(s)n();else{q(this,Ke,ut).call(this,{type:"pending",variables:t,isPaused:i}),l(this,ce).config.onMutate&&await l(this,ce).config.onMutate(t,this,r);let a=await this.options.onMutate?.(t,r);a!==this.state.context&&q(this,Ke,ut).call(this,{type:"pending",context:a,variables:t,isPaused:i})}let o=await l(this,It).start();return await l(this,ce).config.onSuccess?.(o,t,this.state.context,this,r),await this.options.onSuccess?.(o,t,this.state.context,r),await l(this,ce).config.onSettled?.(o,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(o,null,t,this.state.context,r),q(this,Ke,ut).call(this,{type:"success",data:o}),o}catch(o){try{await l(this,ce).config.onError?.(o,t,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onError?.(o,t,this.state.context,r)}catch(a){Promise.reject(a)}try{await l(this,ce).config.onSettled?.(void 0,o,this.state.variables,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onSettled?.(void 0,o,t,this.state.context,r)}catch(a){Promise.reject(a)}throw q(this,Ke,ut).call(this,{type:"error",error:o}),o}finally{l(this,ce).runNext(this)}}},Bn=new WeakMap,Ne=new WeakMap,ce=new WeakMap,It=new WeakMap,Ke=new WeakSet,ut=function(t){let n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),V.batch(()=>{l(this,Ne).forEach(r=>{r.onMutationUpdate(t)}),l(this,ce).notify({mutation:this,type:"updated",action:t})})},bo);function $s(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Be,Fe,Hn,So,Ro=(So=class extends Pe{constructor(t={}){super();T(this,Be);T(this,Fe);T(this,Hn);this.config=t,w(this,Be,new Set),w(this,Fe,new Map),w(this,Hn,0)}build(t,n,r){let s=new wo({client:t,mutationCache:this,mutationId:++Qn(this,Hn)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){l(this,Be).add(t);let n=Tr(t);if(typeof n=="string"){let r=l(this,Fe).get(n);r?r.push(t):l(this,Fe).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(l(this,Be).delete(t)){let n=Tr(t);if(typeof n=="string"){let r=l(this,Fe).get(n);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&l(this,Fe).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=Tr(t);if(typeof n=="string"){let s=l(this,Fe).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=Tr(t);return typeof n=="string"?l(this,Fe).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){V.batch(()=>{l(this,Be).forEach(t=>{this.notify({type:"removed",mutation:t})}),l(this,Be).clear(),l(this,Fe).clear()})}getAll(){return Array.from(l(this,Be))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Sr(n,r))}findAll(t={}){return this.getAll().filter(n=>Sr(t,n))}notify(t){V.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){let t=this.getAll().filter(n=>n.state.isPaused);return V.batch(()=>Promise.all(t.map(n=>n.continue().catch(G))))}},Be=new WeakMap,Fe=new WeakMap,Hn=new WeakMap,So);function Tr(e){return e.options.scope?.id}var He,lt,ge,Ge,ze,Er,Ws,xo,Bs=(xo=class extends Pe{constructor(t,n){super();T(this,ze);T(this,He);T(this,lt);T(this,ge);T(this,Ge);w(this,He,t),this.setOptions(n),this.bindMethods(),q(this,ze,Er).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let n=this.options;this.options=l(this,He).defaultMutationOptions(t),Vt(this.options,n)||l(this,He).getMutationCache().notify({type:"observerOptionsUpdated",mutation:l(this,ge),observer:this}),n?.mutationKey&&this.options.mutationKey&&De(n.mutationKey)!==De(this.options.mutationKey)?this.reset():l(this,ge)?.state.status==="pending"&&l(this,ge).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||l(this,ge)?.removeObserver(this)}onMutationUpdate(t){q(this,ze,Er).call(this),q(this,ze,Ws).call(this,t)}getCurrentResult(){return l(this,lt)}reset(){l(this,ge)?.removeObserver(this),w(this,ge,void 0),q(this,ze,Er).call(this),q(this,ze,Ws).call(this)}mutate(t,n){return w(this,Ge,n),l(this,ge)?.removeObserver(this),w(this,ge,l(this,He).getMutationCache().build(l(this,He),this.options)),l(this,ge).addObserver(this),l(this,ge).execute(t)}},He=new WeakMap,lt=new WeakMap,ge=new WeakMap,Ge=new WeakMap,ze=new WeakSet,Er=function(){let t=l(this,ge)?.state??$s();w(this,lt,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},Ws=function(t){V.batch(()=>{if(l(this,Ge)&&this.hasListeners()){let n=l(this,lt).variables,r=l(this,lt).context,s={client:l(this,He),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{l(this,Ge).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{l(this,Ge).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{l(this,Ge).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{l(this,Ge).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(l(this,lt))})})},xo);var Le,Po,Co=(Po=class extends Pe{constructor(t={}){super();T(this,Le);this.config=t,w(this,Le,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??Un(s,n),o=this.get(i);return o||(o=new lo({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(o)),o}add(t){l(this,Le).has(t.queryHash)||(l(this,Le).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=l(this,Le).get(t.queryHash);n&&(t.destroy(),n===t&&l(this,Le).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){V.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return l(this,Le).get(t)}getAll(){return[...l(this,Le).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>wr(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>wr(t,r)):n}notify(t){V.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){V.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){V.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Le=new WeakMap,Po);var z,dt,ft,tn,nn,pt,rn,sn,To,Hs=(To=class{constructor(e={}){T(this,z);T(this,dt);T(this,ft);T(this,tn);T(this,nn);T(this,pt);T(this,rn);T(this,sn);w(this,z,e.queryCache||new Co),w(this,dt,e.mutationCache||new Ro),w(this,ft,e.defaultOptions||{}),w(this,tn,new Map),w(this,nn,new Map),w(this,pt,0)}mount(){Qn(this,pt)._++,l(this,pt)===1&&(w(this,rn,jt.subscribe(async e=>{e&&(await this.resumePausedMutations(),l(this,z).onFocus())})),w(this,sn,Gt.subscribe(async e=>{e&&(await this.resumePausedMutations(),l(this,z).onOnline())})))}unmount(){var e,t;Qn(this,pt)._--,l(this,pt)===0&&((e=l(this,rn))==null||e.call(this),w(this,rn,void 0),(t=l(this,sn))==null||t.call(this),w(this,sn,void 0))}isFetching(e){return l(this,z).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return l(this,dt).findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return l(this,z).get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=l(this,z).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Oe(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return l(this,z).findAll(e).map(({queryKey:t,state:n})=>{let r=n.data;return[t,r]})}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=l(this,z).get(r.queryHash)?.state.data,o=Zi(t,i);if(o!==void 0)return l(this,z).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return V.batch(()=>l(this,z).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return l(this,z).get(t.queryHash)?.state}removeQueries(e){let t=l(this,z);V.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=l(this,z);return V.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=V.batch(()=>l(this,z).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(G).catch(G)}invalidateQueries(e,t={}){return V.batch(()=>(l(this,z).findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=V.batch(()=>l(this,z).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(G)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(G)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=l(this,z).build(this,t);return n.isStaleByTime(Oe(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(G).catch(G)}fetchInfiniteQuery(e){return e.behavior=en(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(G).catch(G)}ensureInfiniteQueryData(e){return e.behavior=en(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Gt.isOnline()?l(this,dt).resumePausedMutations():Promise.resolve()}getQueryCache(){return l(this,z)}getMutationCache(){return l(this,dt)}getDefaultOptions(){return l(this,ft)}setDefaultOptions(e){w(this,ft,e)}setQueryDefaults(e,t){l(this,tn).set(De(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...l(this,tn).values()],n={};return t.forEach(r=>{wt(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){l(this,nn).set(De(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...l(this,nn).values()],n={};return t.forEach(r=>{wt(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...l(this,ft).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Un(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===$t&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...l(this,ft).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){l(this,z).clear(),l(this,dt).clear()}},z=new WeakMap,dt=new WeakMap,ft=new WeakMap,tn=new WeakMap,nn=new WeakMap,pt=new WeakMap,rn=new WeakMap,sn=new WeakMap,To);var on=X(ae(),1),Io=X(Ir(),1),Gs=on.createContext(void 0),L=e=>{let t=on.useContext(Gs);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Gn=({client:e,children:t})=>(on.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,Io.jsx)(Gs.Provider,{value:e,children:t}));var Ar=X(ae(),1),Ao=Ar.createContext(!1),ko=()=>Ar.useContext(Ao),Mp=Ao.Provider;var zn=X(ae(),1),Rl=X(Ir(),1);function xl(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Pl=zn.createContext(xl()),Mo=()=>zn.useContext(Pl);var Oo=X(ae(),1);var Fo=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?Wt(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},qo=e=>{Oo.useEffect(()=>{e.clearReset()},[e])},Qo=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||Wt(n,[e.error,r]));var Do=e=>{if(e.suspense){let n=s=>s==="static"?s:Math.max(s??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...s)=>n(r(...s)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},Uo=(e,t)=>e.isLoading&&e.isFetching&&!t,No=(e,t)=>e?.suspense&&t.isPending,zs=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var mt=X(ae(),1);function kr(e,t,n){let r=ko(),s=Mo(),i=L(n),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let a=i.getQueryCache().get(o.queryHash);o._optimisticResults=r?"isRestoring":"optimistic",Do(o),Fo(o,s,a),qo(s);let c=!i.getQueryCache().get(o.queryHash),[u]=mt.useState(()=>new t(i,o)),d=u.getOptimisticResult(o),p=!r&&e.subscribed!==!1;if(mt.useSyncExternalStore(mt.useCallback(h=>{let f=p?u.subscribe(V.batchCalls(h)):G;return u.updateResult(),f},[u,p]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),mt.useEffect(()=>{u.setOptions(o)},[o,u]),No(o,d))throw zs(o,u,s);if(Qo({result:d,errorResetBoundary:s,throwOnError:o.throwOnError,query:a,suspense:o.suspense}))throw d.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(o,d),o.experimental_prefetchInRender&&!Ue.isServer()&&Uo(d,r)&&(c?zs(o,u,s):a?.promise)?.catch(G).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?d:u.trackResult(d)}function $(e,t){return kr(e,Wn,t)}var Je=X(ae(),1);function Z(e,t){let n=L(t),[r]=Je.useState(()=>new Bs(n,e));Je.useEffect(()=>{r.setOptions(e)},[r,e]);let s=Je.useSyncExternalStore(Je.useCallback(o=>r.subscribe(V.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=Je.useCallback((o,a)=>{r.mutate(o,a).catch(G)},[r]);if(s.error&&Wt(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function Jn(e,t){return kr(e,Vs,t)}var jo=X(Lo(),1),Yn=typeof window<"u"&&window.__FSAOS_CONFIG__||{},At=Array.isArray(Yn.sources)?Yn.sources:[],Cl=Yn.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",Tl=Yn.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",Te=Yn.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",W=(0,jo.createClient)(Cl,Tl,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var Xn=null,Mr=0,Vo,Zs,Or=!1;Vo=new Promise(e=>{Zs=e});W.auth.onAuthStateChange((e,t)=>{t?.access_token?(Xn=t.access_token,Mr=t.expires_at??Math.floor(Date.now()/1e3)+3600):(Xn=null,Mr=0),Or||(Or=!0,Zs())});setTimeout(()=>{Or||(Or=!0,Zs())},5e3);function $o(e,t){Xn=e,Mr=t??Math.floor(Date.now()/1e3)+3600}function ei(){Xn=null,Mr=0}async function Ye(){let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{};if(e.embedToken){if(typeof e.embedToken=="function")try{return await e.embedToken()??null}catch{return null}return e.embedToken}return await Vo,Xn}var ln=null,dn=null,Wo=0,Js=new Set,ti,Zn,fn=!1;ti=new Promise(e=>{Zn=e});function ni(){Wo++,Js.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function qr(e){let t=typeof e=="string"?e:e.path,n=ln!==t||dn?.id!==(typeof e=="string"?void 0:e.id);ln=t,dn=typeof e=="string"?null:e,typeof e!="string"&&!kt.some(r=>r.id===e.id)&&(kt=[...kt,e],oi()),fn||(fn=!0,Zn()),n&&ni()}function pn(){return ln}function ye(){return dn}function ri(){return Wo}function si(e){return Js.add(e),()=>{Js.delete(e)}}function er(){return ti}function ii(){return fn}var Fr=null;function Mt(e,t={}){if(Fr){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}Fr=e,t.activate!==!1&&qr(e)}function fe(){return Fr}var kt=[],Ys=new Set,Bo=0;function oi(){Bo++,Ys.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function Ee(){return kt}function tr(){return Bo}function Qr(e){return Ys.add(e),()=>{Ys.delete(e)}}function Ho(e,t){let n=JSON.stringify(kt)!==JSON.stringify(e),r=ln!==t.path||dn?.id!==t.id;kt=e,ln=t.path,dn=t,fn||(fn=!0,Zn()),n&&oi(),r&&ni()}var cn=null,an=null,un=0,Xs=new Set,Go=0;function zo(){Go++,Xs.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Session listener error:",t)}})}function ie(){return un}function ai(){return Go}function Jo(e){return Xs.add(e),()=>{Xs.delete(e)}}async function Xe(){if(cn)return cn;if(an)return an;let e=un;return an=(async()=>{let t=Ot(),n=await Ye();if(e!==un)throw new Error("Session changed during initialization");let r={};n&&(r.Authorization=`Bearer ${n}`);let s=await fetch(`${Te}/d/${t}/init`,{method:"GET",headers:r});if(!s.ok)throw new Error(`Session init failed: ${s.status} ${s.statusText}`);let i=await s.json();if(e!==un)throw new Error("Session changed during initialization");let o=i.entry||i;return cn={scope_id:o.scope_id,scope_path:o.scope_path,instance_path:o.instance_path||"/root",fractal_id:o.fractal_id||null,instance_name:o.instance_name||null,display_name:o.scope_display_name||o.display_name||null,principal_id:o.principal_id||null},zo(),cn})().catch(t=>{throw e===un&&(an=null),t}),an}function ht(){return cn}function ci(){un++,cn=null,an=null,ln=null,dn=null,Fr=null,kt=[],zo()}var Yo=[];function ne(e){Yo.push(e)}function mn(){ci(),ei(),Zn(),fn=!1,ti=new Promise(e=>{Zn=e}),ni(),oi();for(let e of Yo)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function Ot(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var Xo=qr,B=pn,ee=ri,we=si,Zo=er,Dr=ii;var ui=0,ea=!1,ta=0;function na(e){if(typeof e!="string")return;let t=Date.parse(e);Number.isNaN(t)||(ui=t-Date.now(),ea=!0,ta=Date.now())}function Ur(){return Date.now()+ui}function ra(){return ea}function sa(){return ui}function ia(){return ta}function oa(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Ur()>=t}function aa(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Math.max(0,t-Ur())}var hn,Ie=new Map,Ft=[],li=0,di={foreground:0,normal:1,background:2},Nr=()=>performance.now(),fi=()=>new DOMException("Read cancelled","AbortError");function ua(e={}){hn={concurrency:Math.max(1,Math.min(16,Math.floor(e.concurrency??6))),timeoutMs:Math.max(1e3,e.timeoutMs??15e3),onTiming:e.onTiming},Lr()}function la(){for(let e of Ie.values()){e.controller.abort();for(let t of e.consumers)t.detach(),t.reject(fi());e.consumers.clear(),e.timer&&clearTimeout(e.timer)}Ie.clear(),Ft.length=0}function da(e,t){return e==="query"?!("materialize"in t):["read","list","search","resolve","resolve-items","get-channel-messages","list-memberships"].includes(e)}function Kr(e){return Array.isArray(e)?`[${e.map(Kr).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${Kr(n)}`).join(",")}}`:JSON.stringify(e)}function fa(e,t,n,r){if(n.signal?.aborted)return Promise.reject(fi());if(!hn)return r(n.signal);let s=Ie.get(e);if(s)di[n.priority??"normal"]<di[s.priority]&&(s.priority=n.priority??"normal");else{s={key:e,method:t,priority:n.priority??"normal",queuedAt:Nr(),controller:new AbortController,consumers:new Set,run:r},Ie.set(e,s),Ft.push(s);let a=s;s.timer=setTimeout(()=>{a.controller.abort();let c=new Error("The read timed out. Please retry.");c.name="TimeoutError";for(let u of a.consumers)u.detach(),u.reject(c);a.consumers.clear(),Ie.get(a.key)===a&&Ie.delete(a.key),ca(a)},hn.timeoutMs)}let i=s,o=new Promise((a,c)=>{let u=()=>{d.detach(),i.consumers.delete(d),c(fi()),i.consumers.size||(i.controller.abort(),Ie.get(i.key)===i&&Ie.delete(i.key),ca(i))},d={resolve:p=>a(structuredClone(p)),reject:c,detach:()=>n.signal?.removeEventListener("abort",u)};i.consumers.add(d),n.signal?.addEventListener("abort",u,{once:!0})});return Lr(),o}function ca(e){let t=Ft.indexOf(e);t>=0&&(Ft.splice(t,1),Ie.get(e.key)===e&&Ie.delete(e.key),e.timer&&clearTimeout(e.timer)),Lr()}function Lr(){if(hn)for(;li<hn.concurrency&&Ft.length;){let e=r=>di[r.priority]-Math.floor((Nr()-r.queuedAt)/2e3);Ft.sort((r,s)=>e(r)-e(s)||r.queuedAt-s.queuedAt);let t=Ft.shift();if(!t.consumers.size)continue;li++,t.startedAt=Nr();let n="success";Promise.resolve().then(()=>t.run(t.controller.signal)).then(r=>{for(let s of t.consumers)s.detach(),s.resolve(r)},r=>{n=t.controller.signal.aborted?"aborted":"error";for(let s of t.consumers)s.detach(),s.reject(r)}).finally(()=>{t.timer&&clearTimeout(t.timer),t.consumers.clear(),Ie.get(t.key)===t&&Ie.delete(t.key),li--;try{hn?.onTiming?.({method:t.method,priority:t.priority,queueMs:Math.round(t.startedAt-t.queuedAt),requestMs:Math.round(Nr()-t.startedAt),outcome:n})}catch{}Lr()})}}ne(la);var El=new Set(["list-memberships","init"]),Ae=class extends Error{constructor(n){let r=typeof n.payload?.error=="string"?n.payload.error.trim():"",s=typeof n.payload?.message=="string"?n.payload.message.trim():"",i=n.responseBody.trim()||`Gateway HTTP error: ${n.status} ${n.statusText}`.trim(),o=r&&s?`${r}: ${s}`:s||r||i;super(o);te(this,"name","GatewayRequestError");te(this,"method");te(this,"status");te(this,"statusText");te(this,"payload");te(this,"responseBody");this.method=n.method,this.status=n.status,this.statusText=n.statusText,this.payload=n.payload,this.responseBody=n.responseBody}};async function x(e,t={},n={}){let r=ie(),s=pn(),i=Ot(),o=`${Te}/d/${i}`,a={"Content-Type":"application/json"},c=await pa(Ye(),n.signal);if(r!==ie())throw new Error("Session changed before gateway request");if(c&&(a.Authorization=`Bearer ${c}`),!El.has(e)&&!t._scope_path&&await pa(er(),n.signal),r!==ie())throw new Error("Session changed before gateway request");let u={...t},d=ht();!u.domain_scope_id&&d?.scope_id&&(u.domain_scope_id=d.scope_id);let p=s??pn();!u._scope_path&&p&&(u._scope_path=p);let h=async f=>{if(r!==ie())throw new Error("Session changed before queued gateway request");let g=await fetch(o,{method:"POST",signal:f,headers:a,body:JSON.stringify({method:e,params:u})}),y=await g.text();if(r!==ie())throw new Error("Session changed during gateway request");let m=null;if(y)try{m=JSON.parse(y)}catch{}if(!g.ok||!m)throw new Ae({method:e,status:g.status,statusText:g.statusText,payload:m,responseBody:y});if(m.success===!1){let v=m.error||"",b=m.denied_by||m.error_type||"";throw b==="rule"||b==="access"||b==="entitlement"||v==="RULE_DENIED"||v==="ACCESS_DENIED"||v==="PERMISSION_DENIED"||v==="ENTITLEMENT_REQUIRED"?new rt(m):new Ae({method:e,status:g.status,statusText:g.statusText,payload:m,responseBody:y})}return m&&m.server_now!==void 0&&na(m.server_now),m};return da(e,u)?fa(Kr([r,i,c,e,u]),e,n,h):h(n.signal)}function pa(e,t){return t?t.aborted?Promise.reject(new DOMException("Read cancelled","AbortError")):new Promise((n,r)=>{let s=()=>r(new DOMException("Read cancelled","AbortError"));t.addEventListener("abort",s,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",s))}):e}var _=X(ae(),1),Yl=X(ha(),1),Xl=X(Ir(),1);var ga=new WeakMap;function ke(e,t,n={}){let r=n.exact===!0,s=()=>e.invalidateQueries({queryKey:t,exact:r},{cancelRefetch:!1}),i=e.getQueryCache().findAll({queryKey:t,exact:r,fetchStatus:"fetching"}).flatMap(p=>p.promise?[p.promise]:[]);if(i.length===0)return s();let o=`${r?"=":"^"}${JSON.stringify(t)}`,a=ga.get(e);a||(a=new Map,ga.set(e,a));let c=a.get(o);if(c)return c;let u=a,d=Promise.allSettled(i).then(()=>(u.delete(o),s()));return u.set(o,d),d}function pe(e,t){return typeof e=="string"&&(e===t||e.startsWith(`${t}/`))}var jr=new WeakMap,ya=e=>e.meta?.arrangementRealtime===!0;function Ze(e,t){let n=e.getQueryCache().find({queryKey:t,exact:!0});if(!n)return;let r=jr.get(e);r||(r=new Map,jr.set(e,r));let s=r.get(n.queryHash);s&&clearTimeout(s),r.set(n.queryHash,setTimeout(()=>{r.delete(n.queryHash),e.getQueryCache().get(n.queryHash)===n&&ke(e,t,{exact:!0})},250))}function _a(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){if(!ya(n))continue;let r=n.state.data;if(n.meta?.personalSections===!0){(r?.item_path&&[t.path,t.old_path].some(i=>typeof i=="string"&&(i===r.item_path||i.startsWith(r.item_path+"/")))||r?.sections?.some(i=>i.entries?.some(o=>o.target?.id===t.item_id))||!r?.item_id&&t.item_type==="item_arrangement"&&t.name==="sidebar-sections")&&Ze(e,n.queryKey);continue}if(!r?.item_id)continue;let s=(i,o)=>!!(i&&t.item_id===i||o&&(t.path===o||t.old_path===o));(s(r.item_id,r.item_path)||t.parent_id===r.item_id||t.old_parent_id===r.item_id||[t.path,t.old_path].some(i=>typeof i=="string"&&i.slice(0,i.lastIndexOf("/"))===r.item_path)||r.resolved_children?.some(i=>s(i.id,i.symlink_path||i.path)||i.target&&s(i.target.id,i.target.path)))&&Ze(e,n.queryKey)}}function va(e){for(let t of e.getQueryCache().getAll())ya(t)&&t.state.data!==void 0&&Ze(e,t.queryKey)}function ba(e){jr.get(e)?.forEach(clearTimeout),jr.delete(e)}var et=null;ne(()=>{et&&(et.cancelQueries({queryKey:["vfs"]}),et.removeQueries({queryKey:["vfs"]}))});function wa(e){if(et&&et!==e)throw new Error("[fsaos-gateway-sdk] setQueryClient() called after a QueryClient was already in use. Inject the host client before rendering or starting realtime subscriptions.");et=e}function O(){return et||(et=new Hs({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),et}var Sa=new Proxy({},{get(e,t,n){let r=O(),s=r[t];return typeof s=="function"?s.bind(r):s}});var Vr=new WeakMap;function pi(e){return e.meta?.infiniteItemsRealtime?.filter}function Il(e,t){return e.state.data?.pages?.some(r=>r.items?.some(s=>t.item_id&&s.id===t.item_id||t.path&&s.path===t.path||t.old_path&&s.path===t.old_path))??!1}function Al(e){if(e.type)return new Set([e.type]);if(!e.any_of?.length)return null;let t=new Set;for(let n of e.any_of){if(!n.item_type)return null;t.add(n.item_type)}return t}function kl(e,t,n){if(Il(e,n))return!0;if(t.spaceIds!==void 0&&(!t.spaceIds.length||n.space_item_id!==void 0&&!t.spaceIds.includes(n.space_item_id)&&!t.spaceIds.includes(n.old_space_item_id)))return!1;let r=t.scope,s=typeof r=="string"&&r!=="__unscoped__",i=typeof n.path=="string"||typeof n.old_path=="string";if(s&&i&&!pe(n.path,r)&&!pe(n.old_path,r))return!1;if(n.item_type==="symlink"&&s&&i)return!0;let o=Al(t);return n.item_type&&o&&!o.has(n.item_type)||t.parent_id&&n.parent_id!==void 0&&n.parent_id!==t.parent_id&&n.old_parent_id!==t.parent_id?!1:i||!!(t.parent_id&&n.parent_id===t.parent_id)}function Ra(e,t){let n=Vr.get(e);n||(n=new Map,Vr.set(e,n));let r=n.get(t.queryHash);r&&clearTimeout(r),n.set(t.queryHash,setTimeout(()=>{n.delete(t.queryHash),!(e.getQueryCache().get(t.queryHash)!==t||!pi(t))&&ke(e,t.queryKey,{exact:!0})},500))}function xa(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){let r=pi(n);r&&kl(n,r,t)&&Ra(e,n)}}function Pa(e){for(let t of e.getQueryCache().getAll())pi(t)&&t.state.data!==void 0&&Ra(e,t)}function Ca(e){Vr.get(e)?.forEach(clearTimeout),Vr.delete(e)}var $r=class extends Error{constructor(){super("The server did not confirm the selected-Space listing contract")}};function Ta(e,t){if(!Array.isArray(t)||t.some(n=>typeof n!="string")||JSON.stringify([...new Set(t)].sort())!==JSON.stringify(e))throw new $r}function gt(e){return!e||e.spaceIds===void 0?e:{...e,spaceIds:[...new Set(e.spaceIds.map(t=>t.toLowerCase()))].sort(),...e.limit!==void 0?{limit:Math.max(1,Math.min(e.limit,500))}:{}}}function gn(e){return e instanceof $r||e instanceof rt||e instanceof Ae&&(e.payload?.error==="SPACE_SELECTION_UNAVAILABLE"||e.payload?.error==="QUERY_PARAMS_INVALID"||e.status===401||e.status===403)}function oe(){return B()??"__unscoped__"}var P={all:()=>["vfs",oe()],item:e=>["vfs",oe(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",oe(),"children",e],allChildren:()=>["vfs",oe(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",oe(),"search",e,...t??[]],items:(e,t)=>["vfs",oe(),"items",e,JSON.stringify(gt(t??{}))],allItems:()=>["vfs",oe(),"items"],tree:(e,t)=>["vfs",oe(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",oe(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",oe(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",oe(),"get-activity-feed",e,t,n],itemVersions:(e,t,n,r)=>["vfs","item-versions",e,t,n,r],itemHistory:(e,t,n)=>["vfs","item-history",e,t,n],channelMessages:(e,t)=>["vfs",oe(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",oe(),"channel-messages"],channels:e=>["vfs",oe(),"channels",e??"all"],allChannels:()=>["vfs",oe(),"channels"],notifications:(e,t)=>["vfs",oe(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",oe(),"notifications"],unreadCounts:()=>["vfs",oe(),"unread-counts"],memberships:e=>["memberships",e]};var Ml=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function J(...e){Ml&&console.log("[WS]",...e)}var U=null,yn=null,vn=null,nr=0,Ol=3e4,Ea=1e4,wn=!1,Ia=!1,Fa=3e4,Fl=Fa*2+5e3,Wr=0,Br=null,Aa=!1;function ql(){sr(),Wr=Date.now(),Br=setInterval(()=>{if(U&&U.readyState===WebSocket.OPEN&&Date.now()-Wr>Fl){J("ping: no inbound traffic for",Date.now()-Wr,"ms \u2014 closing half-open socket");try{U.close(4e3,"liveness timeout")}catch{}return}nt({type:"ping"})},Fa)}function sr(){Br&&(clearInterval(Br),Br=null)}function Ql(){typeof document>"u"||(document.hidden?sr():rr()&&(J("Tab visible, reconnecting..."),qt()))}function Dl(){Aa||typeof document>"u"||(document.addEventListener("visibilitychange",Ql),Aa=!0)}var Se={};function hi(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return!n||!r?n===r:r===n||r.startsWith(`${n}/`)}var bn=[],tt=new Map,_n=new Map,Me=new Map;function Ul(e){let t=_n.get(e);return t?Array.from(new Set(Array.from(t.values()).flatMap(n=>n.event_types))).sort():[]}function ka(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):!1}function Ma(e){let t=Ul(e);if(t.length===0)return tt.delete(e),null;let n={scope_id:e,event_types:t};return tt.set(e,n),n}var je=new Map,yt=new Map,mi="disconnected",Hr=[];function Gr(e){if(mi!==e){mi=e;for(let t of[...Hr])try{t(e)}catch{}}}function Nl(e){je.set(e,"ready");let t=yt.get(e);if(t){yt.delete(e);for(let n of t)n()}}function Kl(){for(let e of je.keys())je.set(e,"disconnected")}function gi(e,t){je.set(e,"pending"),nt({type:"subscribe_path",path:e,event_types:t})}function Ll(){return Object.keys(Se).some(t=>Se[t]&&Se[t].length>0)||bn.length>0}function rr(){return tt.size>0||Me.size>0}async function qt(){if(!rr()){J("ensureConnection: no active subscriptions, skipping");return}if(U&&U.readyState===WebSocket.OPEN){J("ensureConnection: already open");return}if(yn)return J("ensureConnection: connection already in flight, waiting..."),yn;if(U){J("ensureConnection: killing stale WS in state",U.readyState);try{U.close()}catch{}U=null}return wn=!1,yn=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=Te,n=await Ye();if(!n){J("ensureConnection: no token available, will retry"),Oa();return}let r=t.startsWith("https")?"wss":"ws",s=t.replace(/^https?:\/\//,""),i=`${r}://${s}/ws`;i+=`?token=${encodeURIComponent(n)}`,J("ensureConnection: opening WS to",i.substring(0,50)+"..."),Gr("connecting"),U=new WebSocket(i);let o=U;await new Promise((a,c)=>{if(!U)return c(new Error("WebSocket not created"));let u=setTimeout(()=>{if(U===o){if(J("ensureConnection: TIMEOUT after",Ea,"ms"),U&&U.readyState!==WebSocket.OPEN){try{U.close()}catch{}U=null}c(new Error("WebSocket connection timeout"))}},Ea);o.onopen=()=>{if(U!==o)return;clearTimeout(u),J("ensureConnection: CONNECTED");let d=Ia;Ia=!0,nr=0,Gr("connected"),jl(d),(typeof document>"u"||!document.hidden)&&ql(),Dl(),a()},o.onmessage=d=>{U===o&&Vl(d.data)},o.onerror=()=>{J("ensureConnection: WS error event")},o.onclose=d=>{clearTimeout(u),U===o&&(J("ensureConnection: WS closed, code:",d.code,"reason:",d.reason),U=null,sr(),Kl(),Gr("disconnected"),!wn&&rr()&&Oa(),c(new Error(`WebSocket closed: ${d.code}`)))}})}catch(e){J("ensureConnection: failed -",e?.message||e)}finally{yn=null}})(),yn}function Oa(){if(vn||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,nr)+Math.random()*1e3,Ol);nr++,J("scheduleReconnect: attempt",nr,"in",Math.round(e),"ms"),vn=setTimeout(()=>{vn=null,rr()&&qt()},e)}function jl(e=!1){for(let t of tt.values())J("resubscribeAll: scope",t.scope_id),nt({type:"subscribe",scope_id:t.scope_id,event_types:t.event_types});for(let t of Me.values())J("resubscribeAll: path",t.path),gi(t.path,t.event_types);if(e)try{let t=O();Pa(t),va(t);for(let n of Me.values())t.invalidateQueries({queryKey:P.item(n.path)}),t.invalidateQueries({queryKey:P.children(n.path)});J("resubscribeAll: invalidated",Me.size,"paths after reconnect")}catch(t){J("resubscribeAll: cache invalidation skipped",t)}}function nt(e){U&&U.readyState===WebSocket.OPEN&&U.send(JSON.stringify(e))}function Vl(e){Wr=Date.now();try{let t=JSON.parse(e);if(t.type==="subscribed_path"){typeof t.path=="string"&&Nl(t.path);return}if(t.type==="subscribed"||t.type==="unsubscribed"||t.type==="unsubscribed_path"||t.type==="pong")return;if(t.type==="error"){console.warn("[WS] Server error:",t.message);return}if(t.type==="event"||t.event_type){let n=t.event_type||"message",r=t.data||t;if(n==="vfs_change"&&(xa(O(),r),_a(O(),r)),typeof r.path=="string")for(let[s,i]of Object.entries(Se))s!=="*"&&hi(s,r.path)&&i.forEach(o=>o(r));Se["*"]&&Se["*"].forEach(s=>s(r));for(let s of bn)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function yi(){!Ll()&&tt.size===0&&Me.size===0&&U&&(wn=!0,sr(),U.close(),U=null,wn=!1)}function zr(e,t){return Se[e]||(Se[e]=[]),Se[e].push(t),Me.has(e)||(Me.set(e,{path:e,event_types:["token_stream"]}),U&&U.readyState===WebSocket.OPEN?gi(e,["token_stream"]):je.set(e,"pending")),qt(),()=>{let n=Se[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete Se[e],Me.delete(e),je.delete(e),yt.delete(e),nt({type:"unsubscribe_path",path:e}))}yi()}}function re(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return bn.push(...s),rr()&&qt(),()=>{for(let i of s){let o=bn.indexOf(i);o!==-1&&bn.splice(o,1)}yi()}}function Sn(e,t=["vfs_change","ccm_change"]){let n=Symbol(e),r=Array.from(new Set(t)).sort();if(r.length===0)return()=>{};let s=_n.get(e)??new Map,i=tt.get(e)?.event_types;s.set(n,{event_types:r}),_n.set(e,s);let o=Ma(e);if(!o)return()=>{};J("subscribeToScope:",e,o.event_types),U&&U.readyState===WebSocket.OPEN&&!ka(i,o.event_types)&&nt({type:"subscribe",scope_id:e,event_types:o.event_types}),qt();let a=!0;return()=>{if(!a)return;a=!1;let c=_n.get(e);if(!c?.delete(n))return;let u=tt.get(e)?.event_types;if(c.size===0)_n.delete(e),tt.delete(e),nt({type:"unsubscribe",scope_id:e});else{let d=Ma(e);d&&U&&U.readyState===WebSocket.OPEN&&!ka(u,d.event_types)&&nt({type:"subscribe",scope_id:e,event_types:d.event_types})}yi()}}function qa(e,t,n={}){nt({type:"emit",scope_id:e,event_type:t,payload:n})}function _i(){J("disconnectSSE: tearing down"),Ca(O()),ba(O()),wn=!0,sr(),U&&(U.close(),U=null),vn&&(clearTimeout(vn),vn=null),yn=null,wn=!1,nr=0;for(let e of Object.keys(Se))delete Se[e];bn.length=0,tt.clear(),_n.clear(),Me.clear(),je.clear(),yt.clear(),Gr("disconnected")}function Qa(){nt({type:"ping"})}function Da(e){return Me.has(e)?je.get(e)??"pending":"unsubscribed"}function Ua(e,t=5e3){return Me.has(e)?je.get(e)==="ready"&&U&&U.readyState===WebSocket.OPEN?Promise.resolve(!0):(qt(),new Promise(n=>{let r=!1,s=yt.get(e)??[],i=()=>{r||(r=!0,clearTimeout(o),n(!0))};s.push(i),yt.set(e,s);let o=setTimeout(()=>{if(r)return;r=!0;let a=yt.get(e);if(a){let c=a.indexOf(i);c!==-1&&a.splice(c,1),a.length===0&&yt.delete(e)}n(!1)},t)})):Promise.resolve(!1)}function Na(e){let t=Me.get(e);if(!t){J("resubscribePath: no active subscription for",e);return}U&&U.readyState===WebSocket.OPEN?(J("resubscribePath: re-sending frame for",e),gi(t.path,t.event_types)):(je.set(e,"pending"),qt())}function Jr(e){Hr.push(e);try{e(mi)}catch{}return()=>{let t=Hr.indexOf(e);t!==-1&&Hr.splice(t,1)}}ne(_i);function Ka(){return new Date().toISOString()}function La(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function _e(e){let t=e.path||e.item_path||"",n=t.split("/");n.pop();let r=n.join("/"),s=e.type_data||{};return s.allowed_parent_types&&!s.accepts&&(s.accepts=s.allowed_parent_types),delete s.allowed_parent_types,{id:e.id||e.item_id||"",name:e.name||e.item_name||"",item_type:e.item_type||"unknown",path:t,parent_path:r,is_active:e.is_active!==!1,has_children:e.has_children??!1,created_at:e.created_at||Ka(),updated_at:e.updated_at||Ka(),visibility:e.visibility,type_data:s,scope_item_id:e.scope_item_id,fractal_id:e.fractal_id,parent_instance_id:e.parent_instance_id,owner_principal_id:e.owner_principal_id,created_by_principal_id:e.created_by_principal_id,parent_id:e.parent_id,space_item_id:e.space_item_id,account_item_id:e.account_item_id}}function or(e){return(e.content?.items||e.items||[]).map(_e)}async function Xr(e){try{let t=await x("read",{id:e});if(t.item_name||t.item_path){let r=_e(t);return r.path&&O().setQueryData(P.item(r.path),r),r}let n=t.item;if(n){let r=_e(n);return r.path&&O().setQueryData(P.item(r.path),r),r}return null}catch{return null}}async function ar(e){try{let t=await x("read",{path:e});if(t.item_name||t.item_path)return _e(t);let n=t.item;return n?_e(n):null}catch{return null}}async function cr(e){try{let t=await x("list",{path:e,limit:200}),n=or(t);for(let r of n)O().setQueryData(P.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function ja(e,t){let{items:n}=await xn({type:"turn_queue_entry",scope:e,parent_id:t,fields:{state:"queued"},sort_by:"created_at",sort_dir:"asc",limit:100});return n.map(r=>{let s=String(r.type_data?.conversation_anchor_item_id??r.type_data?.conversation_root_id??t);return{id:r.id,path:r.path,content:String(r.type_data?.content??""),state:String(r.type_data?.state??"queued"),queue_seq:Number(r.type_data?.queue_seq??0),created_at:r.created_at,conversation_anchor_item_id:s,conversation_root_id:s,client_request_id:typeof r.type_data?.client_request_id=="string"?r.type_data.client_request_id:void 0,promoted_message_id:typeof r.type_data?.promoted_message_id=="string"?r.type_data.promoted_message_id:void 0,promoted_event_id:typeof r.type_data?.promoted_event_id=="string"?r.type_data.promoted_event_id:void 0}}).sort((r,s)=>r.queue_seq-s.queue_seq||r.created_at.localeCompare(s.created_at))}async function Zr(e,t,n){try{let r=await x("list",{path:e,limit:t,offset:n}),s=or(r);for(let i of s)O().setQueryData(P.item(i.path),i);return{items:s,total_hint:r.total??r.content?.total??s.length}}catch(r){return console.error(`[gateway] Failed to fetch children page of ${e}:`,r),{items:[],total_hint:0}}}async function es(e){let n=await x("types-list",e?{scope_id:e}:{}),r=n.content?.items||n.items||[],s=new Map;for(let i of r){let o=i.name,a=i.type_data;!o||!a||s.set(o,{type_key:o,display_name:a.display_name||o,display_name_plural:a.display_name_plural||o+"s",icon:a.icon||"File",color:a.color||"gray",description:a.description||"",input_schema:a.input_schema||{},system_schema:a.system_schema||{},json_schema:a.input_schema||a.json_schema||{},default_data:a.default_data||{},field_defaults:a.field_defaults||{},renderer_config:a.renderer_config||{},is_system:a.is_system??!1,is_active:a.is_active??!0,is_container:a.is_container??!1,is_scope:a.is_scope??!1,render_mode:a.render_mode||"none",placement_mode:a.placement_mode,direct_parent_types:a.direct_parent_types,allowed_parent_types:a.allowed_parent_types,governed_create:a.governed_create,create_method:a.create_method,dedup:a.dedup,edges:a.edges,events:a.events})}return s}async function ts(e){try{let t=await x("edges",{item_id:e}),n=t.outgoing||[],r=t.incoming||[],s=[];for(let i of n)s.push({id:i.edge_id||La(),source_item_id:e,target_item_id:i.target_id||"",edge_type:i.edge_type||"",weight:i.weight??1,context:i.context||{},is_active:!0,is_bidirectional:i.is_bidirectional});for(let i of r)s.push({id:i.edge_id||La(),source_item_id:i.source_id||"",target_item_id:e,edge_type:i.edge_type||"",weight:i.weight??1,context:i.context||{},is_active:!0,is_bidirectional:i.is_bidirectional});return s}catch(t){return console.warn(`[gateway] Failed to fetch edges for ${e}:`,t),[]}}async function ns(e,t=1,n,r){try{let s={path:e,max_depth:t>0?t:999};n?.length&&(s.item_types=n),r&&(s.limit=r);let i=await x("tree",s),o=or(i);for(let a of o)O().setQueryData(P.item(a.path),a);return o}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function rs(e,t=50,n=0){try{let r=await x("get-activity-feed",{scope_path:e,limit:t,offset:n});return r.content?.items||r.items||r.entries||[]}catch(r){return console.error(`[gateway] Failed to fetch recent activity for ${e}:`,r),[]}}async function ur(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;try{let i=await x("item-versions",{id:e,limit:n,offset:r,include_snapshots:s});return{versions:i.content?.items||i.versions||[],total:i.total??0}}catch(i){return console.error(`[gateway] Failed to fetch item versions for ${e}:`,i),{versions:[],total:0}}}async function ss(e,t=50,n=0){return ur(e,{limit:t,offset:n})}async function is(e,t,n){try{let r={scope_id:e};t?.length&&(r.item_types=t),n&&(r.limit=n);let s=await x("member-focus",r),i=or(s);for(let o of i)O().setQueryData(P.item(o.path),o);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${e}:`,r),[]}}async function os(e,t){let n={path:e};t?.mode&&(n.mode=t.mode),t?.strategy&&(n.strategy=t.strategy),t?.arguments&&(n.arguments=t.arguments);let s=await x("open",n);return{item_id:s.item_id,item_path:s.item_path,item_name:s.item_name,item_type:s.item_type,render:s.render,compatible_components:s.compatible_components??[],content:s.content,metadata:s.metadata,instructions:s.instructions}}function Rn(e){return!!e&&(!!e.type||Array.isArray(e.any_of)&&e.any_of.length>0)}function $l(e){let t={};e.item_type&&(t.item_type=e.item_type);for(let[n,r]of Object.entries(e.fields??{}))t[`field.${n}`]=String(r);for(let[n,r]of Object.entries(e.field_in??{}))t[`field_in.${n}`]=r.map(String);return t}var Wl=["catalog","parent_only","internal"];function Va(e,t={}){if(!e||typeof e!="object")return null;let n=o=>typeof o=="string"||typeof o=="number"||typeof o=="boolean",r=o=>{let a={},c={};for(let[u,d]of Object.entries(o))u.startsWith("field.")&&u.length>6&&n(d)?a[u.slice(6)]=d:u.startsWith("field_in.")&&u.length>9&&Array.isArray(d)&&(c[u.slice(9)]=d.filter(n));return{fields:a,field_in:c}},s={};typeof e.type=="string"&&e.type&&(s.type=e.type),typeof e.sort_by=="string"&&(s.sort_by=e.sort_by),(e.sort_dir==="asc"||e.sort_dir==="desc")&&(s.sort_dir=e.sort_dir),typeof e.name=="string"&&e.name&&(s.name=e.name),typeof e.tag=="string"&&e.tag&&(s.tag=e.tag),typeof e.discovery=="string"&&Wl.includes(e.discovery)&&(s.discovery=e.discovery);let i=r(e);if(Object.keys(i.fields).length&&(s.fields=i.fields),Object.keys(i.field_in).length&&(s.field_in=i.field_in),Array.isArray(e.any_of)){let o=[];for(let a of e.any_of){if(!a||typeof a!="object"||Array.isArray(a))continue;let c=a,u={};typeof c.item_type=="string"&&c.item_type&&(u.item_type=c.item_type);let d=r(c);Object.keys(d.fields).length&&(u.fields=d.fields),Object.keys(d.field_in).length&&(u.field_in=d.field_in),Object.keys(u).length&&o.push(u)}o.length&&(s.any_of=o)}return Rn(s)?{...s,...t}:null}async function xn(e,t={}){if(e=gt(e),e.spaceIds?.length===0)return{items:[],total_hint:0};let n={};e.type&&(n.item_type=e.type),e.scope&&(n.scope_path=e.scope);let r={};if(e.spaceIds!==void 0&&(r.space_ids=e.spaceIds),e.name&&(r.name=e.name),e.tag&&(r.tag=e.tag),e.parent_id&&(r.parent_id=e.parent_id),e.sort_by&&(r.sort_by=e.sort_by),e.sort_dir&&(r.sort_dir=e.sort_dir),e.offset!=null&&(r.offset=e.offset),e.fields)for(let[s,i]of Object.entries(e.fields))r[`field.${s}`]=String(i);if(e.field_in)for(let[s,i]of Object.entries(e.field_in))r[`field_in.${s}`]=i.map(String);e.discovery&&(r.discovery=e.discovery),e.any_of?.length&&(r.any_of=e.any_of.map($l)),Object.keys(r).length>0&&(n.filters=r),e.limit!=null&&(n.limit=e.limit);try{let s=await x("query",n,t);e.spaceIds!==void 0&&Ta(e.spaceIds,s.selected_space_ids??s.content?.selected_space_ids);let i=or(s);for(let o of i)O().setQueryData(P.item(o.path),o);return{items:i,total_hint:s.total??s.content?.total??i.length}}catch(s){if(t.signal?.aborted||s instanceof Error&&s.name==="AbortError"||(console.error(`[gateway] Failed to fetch items of type ${e.type??"(any_of)"}:`,s),t.throwOnError||e.spaceIds!==void 0))throw s;return{items:[],total_hint:0}}}function Bl(e){if(!e||typeof e!="object")return;let t=e;if(t.version!==1||typeof t.work_id!="string"||!t.work_id)return;let n=r=>{let s=t[r];return typeof s=="string"&&s?s:void 0};return{version:1,workId:t.work_id,threadRootId:n("thread_root_id"),requestMessageId:n("request_message_id"),replyMessageId:n("reply_message_id"),replyMessagePath:n("reply_message_path"),todoListId:n("todo_list_id"),todoListPath:n("todo_list_path"),stepId:n("step_id"),stepPath:n("step_path"),runId:n("run_id"),parentRunId:n("parent_run_id"),toolCallId:n("tool_call_id"),traceId:n("trace_id")}}function $a(e){return e.filter(t=>t.item_type==="card").map(t=>{let n=t.type_data||{},r=n.payload||{};return{id:t.id||"",path:t.path||"",name:t.name||(t.path||"").split("/").pop()||"",createdAt:t.created_at||"",action:n.action||"created",targetId:n.target_id||void 0,targetPath:n.target_path||"",targetDisplayName:n.target_display_name||"",targetDescription:n.target_description||"",targetItemType:n.target_item_type||"",toolId:(t.name||"").startsWith("card-")?(t.name||"").substring(5):void 0,parentMessagePath:t.parent_message_path||void 0,visibility:n.visibility||"private",openWith:r.open_with||void 0,hostBundled:r.host_bundled===!0?!0:void 0,bundleExport:r.bundle_export||void 0,launchArguments:r.launch_arguments||void 0,requiresUserAttention:r.requires_user_attention===!0?!0:void 0,origin:Bl(n.origin),presentationRole:r.presentation_role==="user-request"?"user-request":r.presentation_role==="output"?"output":void 0}}).sort((t,n)=>t.createdAt.localeCompare(n.createdAt))}function ir(e){return e.filter(t=>t.item_type==="message").map(t=>{let n=t.type_data||{},r="user";n.role==="assistant"?r="assistant":n.role==="system"&&(r="system");let s=n.metadata||{};return{id:t.id||"",path:t.path||"",content:n.message||n.content||"",created_at:t.created_at||"",role:r,status:typeof n.status=="string"?n.status:void 0,delivery_state:typeof n.delivery_state=="string"?n.delivery_state:void 0,cognition_event_id:typeof n.cognition_event_id=="string"?n.cognition_event_id:void 0,seq:n.seq||0,principal_id:n.principal_id,member_id:typeof n.member_id=="string"?n.member_id:void 0,reply_count:n.reply_count||0,member_count:n.member_count||0,parent_message_id:n.parent_message_id,intent_card:s.intent_card,metadata:Object.keys(s).length>0?s:void 0,thread_summary:Array.isArray(n.thread_summary)&&n.thread_summary.length>0?n.thread_summary:void 0}}).sort((t,n)=>t.seq-n.seq)}async function Wa(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await x("get-channel-messages",n),i=s.messages||s.content?.items||s.items||[];return ir(i)}catch(n){throw console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),n}}async function as(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await x("get-channel-messages",n),i=s.messages||[],o=ir(i),a=$a(i),c=new Map,u=[];for(let d of a)if(d.parentMessagePath){let p=c.get(d.parentMessagePath)||[];p.push(d),c.set(d.parentMessagePath,p)}else u.push(d);return{messages:o,activityMessages:ir(s.activity_messages||[]),messageCards:c,siblingCards:u,mode:s.mode||"top_level"}}catch(n){throw console.error(`[gateway] Failed to fetch channel messages with cards for ${e}:`,n),n}}async function lr(e,t){try{let n={channel_path:e};t?.parentMessageId&&(n.parent_message_id=t.parentMessageId),t?.conversationsOnly&&(n.conversations_only=!0),t?.limit&&(n.limit=t.limit),t?.before_seq!=null&&(n.before_seq=t.before_seq),t?.after_seq!=null&&(n.after_seq=t.after_seq);let s=await x("get-channel-messages",n);if(t?.conversationsOnly&&s.conversations_only!==!0)throw new Error("This server does not support conversation history lists yet. Update the message reader.");let i=s.messages||[],o=$a(i),a=new Map,c=[];for(let u of o)if(u.parentMessagePath){let d=a.get(u.parentMessagePath)||[];d.push(u),a.set(u.parentMessagePath,d)}else c.push(u);return{messages:ir(i),activityMessages:ir(s.activity_messages||[]),messageCards:a,siblingCards:c,mode:s.mode||"top_level"}}catch(n){throw console.error(`[gateway] Failed to fetch channel messages page for ${e}:`,n),n}}function Yr(e){O().invalidateQueries({queryKey:P.children(e)})}function vi(e){O().invalidateQueries({queryKey:P.item(e)})}function Ba(e,t){vi(e),Yr(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&Yr(r)}function Ha(e){let t=e+"/";O().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function Ga(){O().invalidateQueries({queryKey:P.all()})}function za(e){O().invalidateQueries({queryKey:P.types(e)})}function Ja(e,t){e?O().invalidateQueries({queryKey:P.channelMessages(e,t)}):O().invalidateQueries({queryKey:P.allChannelMessages()})}function Ya(e,t){e&&t?O().invalidateQueries({queryKey:P.openEnvelope(e,t)}):e?O().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):O().invalidateQueries({queryKey:P.allOpenEnvelopes()})}function Ve(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}async function cs(){return((await x("list-memberships",{})).memberships||[]).map(n=>({accountId:n.account_id,path:n.account_path,name:n.account_name,role:n.role||"member",typeData:n.account_type_data||{},joinedAt:n.joined_at,via:n.via,placement:n.placement,subordinateTo:n.subordinate_to??null,cascadeAnchorId:n.cascade_anchor_id??null,isAccount:n.is_account??void 0,isSpace:n.is_space??void 0,isOwner:n.is_owner??void 0,billingResponsible:n.billing_responsible??void 0,grantedVia:n.granted_via??null,grantedUnderAccountId:n.granted_under_account_id??null,membershipPath:n.membership_path??null,personalSpaceId:n.personal_space_id??null,personalSpacePath:n.personal_space_path??null}))}var Pn=new Map,dr=null,us=null,_t=new Map,Xa=250;function Qt(e){if(dr){Cn(e);return}Cn(e),dr=re("vfs_change",t=>Hl(t)),us=re("ccm_change",t=>Gl(t))}function Cn(e){if(Pn.has(e))return;let t=Sn(e,["vfs_change","ccm_change"]);Pn.set(e,t)}function ls(e){let t=Pn.get(e);t&&(t(),Pn.delete(e))}function bi(){for(let[,e]of Pn)e();Pn.clear(),dr&&(dr(),dr=null),us&&(us(),us=null),_t.forEach(e=>clearTimeout(e)),_t.clear()}ne(bi);function Hl(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=_t.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{_t.delete(s),zl(n,t,e,s)},Xa);_t.set(s,o)}function Gl(e){if(!e||typeof e!="object")return;let t=e.source_item_id||e.source_id,n=e.target_item_id||e.target_id;if(!(e.edge_type!=null||t!=null||n!=null)||!t&&!n||e.item_type==="message")return;let s=`ccm:${t??""}:${n??""}`,i=_t.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{_t.delete(s),t&&O().invalidateQueries({queryKey:P.edges(t)}),n&&O().invalidateQueries({queryKey:P.edges(n)})},Xa);_t.set(s,o)}function zl(e,t,n,r){if((e||"").toUpperCase()==="DELETE")O().removeQueries({queryKey:P.item(t)}),O().removeQueries({queryKey:P.children(t)}),O().removeQueries({queryKey:P.tree(t)});else if(n.item_id)try{let i={id:n.item_id,path:n.path,name:n.name,item_type:n.item_type,parent_id:n.parent_id,scope_item_id:n.scope_item_id},o=_e(i);o&&o.id&&O().setQueryData(P.item(t),o)}catch{}O().invalidateQueries({queryKey:P.children(r)}),O().invalidateQueries({predicate:i=>{let o=i.queryKey;if(o[0]!=="vfs"||o[1]!=="tree")return!1;let a=o[2];return t.startsWith(a+"/")||t===a}}),n.item_id&&O().invalidateQueries({queryKey:P.itemById(n.item_id)})}var Tn=null;ne(()=>{Tn=null});function vt(e){if(e!==Tn||e.generation!==ie())throw new Error("Workspace session changed")}function Jl(e){return e instanceof Ae&&e.payload?.error==="item_not_found"}function fr(e,t){let n=e.resolve(t.id);if(!n||n.path!==t.path||n.kind!==t.kind)throw new Error("Mount is not an available membership");return n}function pr(e){let t=fe();if(!t)throw new Error("Elect a home account before loading mounts");return[t,...e.filter((n,r)=>n.id!==t.id&&e.findIndex(s=>s.id===n.id)===r)]}function Za(e,t){return JSON.stringify({mounts:e.map(n=>n.id),last_anchor:t.id})}async function ec(e,t,n){vt(e);let r=Za(t,n);if(e.saved===r)return;let s=JSON.parse(r);await x(e.exists?"update":"create",e.exists?{_scope_path:e.scope,path:e.path,type_data:s}:{_scope_path:e.scope,parent_path:e.path.slice(0,e.path.lastIndexOf("/")),name:"mounts",item_type:"file",type_data:s}),vt(e),e.exists=!0,e.saved=r}function tc(e,t){let n=Ee();Qt(fe().id);for(let r of n)e.some(s=>s.id===r.id)||ls(r.id);for(let r of e)Cn(r.id);Ho(e,t)}async function Dt(e,t,n={}){let r=fe();if(!r)throw new Error("Elect a home account before loading mounts");let s=`${e}/settings/mounts`;if(Tn&&Tn.path!==s)throw new Error("Reset the session before changing the mount declaration owner");let i=Tn??(Tn={generation:ie(),path:s,scope:r.path,resolve:t,exists:!1,ready:!1,saved:null,queue:Promise.resolve()});return vt(i),i.loading?i.loading:i.ready?Ee():(i.resolve=t,i.loading=(async()=>{let o=null;try{let d=await x("read",{path:s,_scope_path:i.scope});if(vt(i),o=d.type_data??d.item?.type_data,!o||!Array.isArray(o.mounts)||!o.mounts.every(p=>typeof p=="string"))throw new Error("Invalid saved mount declaration");i.exists=!0}catch(d){if(vt(i),!Jl(d))throw d;i.exists=!1}let a=n.initialAnchor?fr(i,n.initialAnchor):r,c=pr(o?o.mounts.map(t).filter(d=>d!==null):[a]),u=o?c.find(d=>d.id===o.last_anchor)??c.find(d=>d.kind==="space")??r:a;return o?i.saved=Za(c,u):n.initialAnchor&&await ec(i,c,u),vt(i),i.ready=!0,tc(c,u),c})().finally(()=>{i.loading=void 0}),i.loading)}function ds(e){let t=Tn;if(!t?.ready)return Promise.reject(new Error("Workspace mounts are not loaded"));let n=t.queue.then(async()=>{vt(t);let{refs:r,anchor:s}=e(t);await ec(t,r,s),vt(t),tc(r,s)});return t.queue=n.catch(()=>{}),n}function wi(e){return ds(t=>({refs:pr([...Ee(),fr(t,e)]),anchor:ye()}))}function nc(e){return ds(()=>{if(e===fe().id)throw new Error("The home account cannot be unmounted");let t=pr(Ee().filter(r=>r.id!==e)),n=t.find(r=>r.id===ye()?.id)??t.find(r=>r.kind==="space")??fe();return{refs:t,anchor:n}})}function mr(e){return ds(t=>{let n=fr(t,e);return{refs:pr([...Ee(),n]),anchor:n}})}function fs(e,t){return ds(n=>{let r=pr(e.map(i=>fr(n,i))),s=fr(n,t);if(!r.some(i=>i.id===s.id))throw new Error("Selected mount must be in the working set");return{refs:r,anchor:s}})}function ps(e){if(typeof e.path!="string")return!1;let t=[...Ee().map(n=>n.path),ye()?.path].filter(n=>!!n);return!t.length&&B()&&t.push(B()),t.some(n=>pe(e.path,n))}function Si(e,t,n,r){if(!["message","card"].includes(e?.item_type)||!pe(e.path,t))return!1;if(!n){let s=e.path.slice(t.length).replace(/^\//,""),i=s?s.split("/").length:0;return e.item_type==="message"?i===1:i===1||i===2}return e.item_id===n||e.parent_id===n?!0:r.some(s=>{if(e.item_id===s.id||e.parent_id===s.id)return!0;let i=s.id===n?s.path:s.parent_message_id===n?s.path.slice(0,s.path.lastIndexOf("/")):void 0;return!!i&&pe(e.path,i)})}var rc=new WeakMap;function sc(e,t,n){let r=rc.get(e);r||(r=new Map,rc.set(e,r));let s=JSON.stringify(t),i=r.get(s);if(!i){let a=!1,c,u=!1,d=!1,p=new Set,h=new Set,f=()=>e.getQueryData(t)??[],g=()=>{a||u||c||(c=setTimeout(()=>{c=void 0,y()},250))},y=async()=>{if(a)return;u=!0;let I=d;d=!1;let R=[...p],F=new Set(h);h.clear(),p.clear();try{if(I)await ke(e,t,{exact:!0});else{let S=(await Promise.allSettled(R.map(async C=>{let M=e.getQueryCache().find({queryKey:t,exact:!0});if(!M)return;let A=await x("read",{id:C});if(A.success===!1)throw new Error("Channel refresh failed");if(a||!M||e.getQueryCache().find({queryKey:t,exact:!0})!==M)return;let k=_e(A.item??A);if(k.id!==C||k.item_type!=="channel")return;let Q=f().find(H=>H.id===C);if(!Q)return;let D=n({...k}),le={...Q,path:D.path,name:D.name,displayName:D.displayName,messageCount:D.messageCount,aiMode:D.aiMode,activeAgentIds:D.activeAgentIds,isPrivate:D.isPrivate,isDm:D.isDm,autoPilot:D.autoPilot,isArchived:D.isArchived,updatedAt:D.updatedAt};F.has(C)&&(Q.name!==le.name||Q.displayName!==le.displayName||Q.path!==le.path)&&(d=!0),e.setQueryData(t,H=>H?.map(Re=>Re.id===C?le:Re))}))).find(C=>C.status==="rejected");if(S?.status==="rejected")throw S.reason}}catch(N){console.warn("[channels] refresh failed",N)}finally{u=!1,(d||p.size)&&g()}},m=I=>f().some(R=>R.id===I.item_id||R.path===I.path)?!0:ps(I),v=I=>{if(!m(I))return;let R=String(I.action??"").toLowerCase();if(["insert","delete","rename","move"].includes(R))d=!0;else if(R==="update"){let F=f().find(N=>N.id===I.item_id||N.path===I.path);F&&(p.add(F.id),h.add(F.id))}(d||p.size)&&g()},b=I=>{let R=f().find(F=>F.id===I.parent_id);R&&(p.add(R.id),g())},E=["vfs_change","ccm_change"].flatMap(I=>[re(I,v,R=>R.item_type==="channel"),re(I,b,R=>R.item_type==="message")]);i={users:0,stop:()=>{a=!0,c&&clearTimeout(c),E.forEach(I=>I())}},r.set(s,i)}i.users++;let o=!1;return()=>{o||(o=!0,--i.users===0&&(i.stop(),r.delete(s)))}}function Y(){return(0,_.useSyncExternalStore)(we,ee,ee)}function lc(){return Y(),Dr()}function dc(e){return Y(),$({queryKey:P.item(e),queryFn:()=>ar(e),enabled:!!e,staleTime:1/0})}function fc(e){return Y(),$({queryKey:P.itemById(e),queryFn:()=>Xr(e),enabled:!!e,staleTime:1/0})}function xi(e){return Y(),$({queryKey:P.children(e),queryFn:()=>cr(e),enabled:!!e})}function pc(e){let t=xi(e);return{...t,children:t.data??[]}}function mc(e,t=1){return Y(),$({queryKey:P.tree(e,t),queryFn:()=>ns(e,t),enabled:!!e})}function hc(e,t){return Y(),$({queryKey:P.search(e,t),queryFn:async()=>{let n={query:e};t?.length&&(n.item_types=t);let r=await x("search",n);return(r.content?.items||r.items||r.results||[]).map(_e)},enabled:!!e&&e.length>0})}function gc(e){Y();let t=(0,_.useMemo)(()=>e,[JSON.stringify(e)]);return $({queryKey:["vfs",B()??"__unscoped__","resolve",JSON.stringify(t??{})],queryFn:async()=>await x("resolve",t),enabled:!!t?.query&&t.query.length>0})}function yc(e){Y();let t=gt(e),n=(0,_.useMemo)(()=>t,[JSON.stringify(t)]),r=$({queryKey:P.items(n?.type??"",n),queryFn:({signal:s})=>xn(n,{signal:s,throwOnError:!0}),enabled:Rn(n),...n?.spaceIds!==void 0?{retry:(s,i)=>!gn(i)&&iu(s,i)}:{},select:s=>s.items});return n?.spaceIds!==void 0&&gn(r.error)?{...r,data:void 0}:r}function Pi(e,t={}){let n=Y(),{realtime:r=!1}=t,s=gt(e),i=s?.limit??20,o=(0,_.useMemo)(()=>s,[JSON.stringify(s)]),a=(0,_.useMemo)(()=>["vfs",B()??"__unscoped__","infinite-items",o?.type??"",JSON.stringify(o??{})],[n,o]),c=Jn({queryKey:a,queryFn:async({pageParam:p=0,signal:h})=>xn({...o,limit:i,offset:p},{throwOnError:!0,signal:h,priority:t.priority}),initialPageParam:0,getNextPageParam:(p,h,f)=>{if(!(o?.spaceIds!==void 0&&p.total_hint!==void 0&&f+p.items.length>=p.total_hint)&&!(p.items.length<i))return f+p.items.length},enabled:Rn(o),...o?.spaceIds!==void 0?{retry:(p,h)=>!gn(h)&&iu(p,h)}:{},staleTime:r?1/0:t.staleTime,meta:r&&o?{infiniteItemsRealtime:{filter:o}}:{}}),u=(0,_.useMemo)(()=>{if(o?.spaceIds!==void 0&&gn(c.error))return[];if(!c.data?.pages)return[];let p=new Set,h=[];for(let f of c.data.pages)for(let g of f.items)g.id&&!p.has(g.id)&&(p.add(g.id),h.push(g));return h},[c.data?.pages,c.error,o]),d=o?.spaceIds!==void 0&&gn(c.error);return{allItems:u,refetch:c.refetch,fetchNextPage:c.fetchNextPage,isFetchingNextPage:c.isFetchingNextPage,isExhausted:d||!c.hasNextPage,isLoading:c.isLoading,isFetching:c.isFetching,error:c.error,totalHint:d?void 0:c.data?.pages?.[0]?.total_hint}}function ic(e){return!!e?.type&&!!e.scope&&e.sort_by==="created_at"&&!e.offset&&!e.spaceIds&&!e.any_of&&!e.name&&!e.tag&&!e.discovery}function Zl(e,t){if(e.is_active===!1||e.item_type!==t.type||!pe(e.path,t.scope)||t.parent_id&&e.parent_id!==t.parent_id)return!1;let n=e.type_data??{};for(let[r,s]of Object.entries(t.fields??{})){let i=n[r];if(typeof s=="string"&&s.endsWith("*")){if(typeof i!="string"||!i.startsWith(s.slice(0,-1)))return!1}else if(i!==s)return!1}for(let[r,s]of Object.entries(t.field_in??{}))if(!s.includes(n[r]))return!1;return!0}function _c(e,t={}){let n=ic(e),r=Pi(e,n?{realtime:!1,staleTime:3e4}:{realtime:!0}),s=L(),i=JSON.stringify([B(),gt(e)]),[o,a]=(0,_.useState)(()=>({identity:i,upserts:{},deleted:new Set})),c=o.identity===i?o:{identity:i,upserts:{},deleted:new Set},u=(0,_.useMemo)(()=>{if(!n)return r.allItems;let f=Object.values(c.upserts),g=new Set(f.map(b=>b.id)),y=[...f,...r.allItems.filter(b=>!g.has(b.id))].filter(b=>!c.deleted.has(b.path)),m=e.sort_by??"updated_at",v=e.sort_dir==="asc"?1:-1;return y.sort((b,E)=>v*String(b[m]??"").localeCompare(String(E[m]??"")))},[n,r.allItems,c,e?.sort_by,e?.sort_dir]),d=(0,_.useRef)(u);d.current=u;let p=(0,_.useRef)(t.shouldReadUpdate);p.current=t.shouldReadUpdate;let h=(0,_.useRef)(r.refetch);return h.current=r.refetch,(0,_.useEffect)(()=>{if(!ic(e))return;let f=e,g=!1,y=!1,m=!1,v=0,b=new Map,E=()=>{let S=v;h.current().then(C=>{!g&&!C.isError&&v===S&&a({identity:i,upserts:{},deleted:new Set})})},I=S=>{v++,a(M=>{let A=M.identity===i?M:{identity:i,upserts:{},deleted:new Set},k={...A.upserts};return delete k[S],{identity:i,upserts:k,deleted:new Set(A.deleted).add(S)}});let C=b.get("__reconcile__");C&&clearTimeout(C),b.set("__reconcile__",setTimeout(()=>{b.delete("__reconcile__"),E()},250))},R=S=>{let C=b.get(S);C&&clearTimeout(C),b.set(S,setTimeout(()=>{b.delete(S),s.fetchQuery({queryKey:P.item(S),queryFn:()=>ar(S),staleTime:0}).then(M=>{if(!g){if(!M||!Zl(M,f)){let A=d.current.find(k=>k.path===S||k.id===M?.id);A&&I(A.path);return}a(A=>{let k=A.identity===i?A:{identity:i,upserts:{},deleted:new Set},Q=new Set(k.deleted);return Q.delete(S),{identity:i,upserts:{...k.upserts,[S]:M},deleted:Q}})}}).catch(M=>console.warn("[useIncrementalItems] item read failed:",M))},250))},F=re("vfs_change",S=>{if(!S||typeof S.path!="string"&&typeof S.old_path!="string")return;let C=typeof S.path=="string"?S.path:S.old_path,M=d.current.find(k=>k.path===C||k.path===S.old_path||S.item_id&&k.id===S.item_id),A=!!M;if(!(!pe(C,f.scope)&&!pe(S.old_path,f.scope)&&!A)&&!(S.item_type&&S.item_type!==f.type&&!A)&&!(f.parent_id&&S.parent_id&&S.parent_id!==f.parent_id&&!A)){if(M&&(C!==M.path||S.old_path&&S.old_path!==C||S.parent_id&&S.parent_id!==M.parent_id||S.item_type&&S.item_type!==f.type)){I(M.path);return}if(!M&&S.old_path&&S.old_path!==C&&pe(C,f.scope)){v++,R(C);return}if(S.action==="insert")v++,R(C);else if(S.action==="move")v++,R(C);else if(S.action==="update"){if(!p.current?.(S,d.current))return;v++,R(C)}else S.action==="delete"&&I(M?.path??S.old_path??C)}}),N=Jr(S=>{if(S!=="connected"){y&&(m=!0);return}y=!0,m&&(m=!1,E())});return()=>{g=!0,F(),N(),b.forEach(clearTimeout)}},[s,i]),{...r,allItems:u}}function vc(e){Y();let t=20,n=Jn({queryKey:["vfs",B()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>Zr(e,t,s),initialPageParam:0,getNextPageParam:(s,i,o)=>{if(!(s.items.length<t))return o+s.items.length},enabled:!!e});return{allItems:(0,_.useMemo)(()=>{if(!n.data?.pages)return[];let s=new Set,i=[];for(let o of n.data.pages)for(let a of o.items)a.id&&!s.has(a.id)&&(s.add(a.id),i.push(a));return i},[n.data?.pages]),fetchNextPage:n.fetchNextPage,isFetchingNextPage:n.isFetchingNextPage,isExhausted:!n.hasNextPage,isLoading:n.isLoading,isFetching:n.isFetching,error:n.error,totalHint:n.data?.pages?.[0]?.total_hint}}function bc(e){return Y(),$({queryKey:P.edges(e),queryFn:()=>ts(e),enabled:!!e})}function ms(e){return Y(),$({queryKey:P.types(e),queryFn:()=>es(e)})}function wc(e,t){let n=ms(t);return{...n,data:n.data?.get(e)??void 0}}function Sc(e,t){Y();let n=(0,_.useMemo)(()=>t?.arguments,[JSON.stringify(t?.arguments)]),r=t?.mode,s=t?.strategy,i=t?.width;return $({queryKey:[...P.openEnvelope(e,s),i],queryFn:async()=>{let o=await os(e,{mode:r,strategy:s,arguments:n});if(i&&o.render?.props?.url){let a=o.render.props.url,c=a.includes("?")?"&":"?";o.render.props.url=`${a}${c}w=${i}`}return o},enabled:!!e})}var oc={related_to:"Related To",depends_on:"Depends On",blocks:"Blocks",parent_of:"Parent Of",child_of:"Child Of",references:"References",implements:"Implements",extends:"Extends",contains:"Contains",belongs_to:"Belongs To",created_by:"Created By",assigned_to:"Assigned To",tagged_with:"Tagged With",linked_to:"Linked To"};function Rc(e){let t=ms(e),n=t.data??new Map;return(0,_.useMemo)(()=>({canHaveChildren:f=>n.get(f.item_type)?.is_container??!1,isScope:f=>n.get(f.item_type)?.is_scope??!1,isScopeType:f=>n.get(f)?.is_scope??!1,isContainerType:f=>n.get(f)?.is_container??!1,getTypeDefinition:f=>n.get(f),getTypeColor:f=>n.get(f)?.color??"gray",getTypeIcon:f=>n.get(f)?.icon??"File",getTypeDisplayName:f=>n.get(f)?.display_name??f,getKnownEdgeTypes:()=>Object.entries(oc).map(([f,g])=>({key:f,label:g})),getEdgeTypeLabel:f=>oc[f]??f.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function xc(e,t,n){return Y(),$({queryKey:P.memberFocus(e),queryFn:()=>is(e,t,n),enabled:!!e})}function Pc(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return $({queryKey:P.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>ur(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function Cc(e,t=50,n=0){return $({queryKey:P.itemHistory(e,String(t),String(n)),queryFn:()=>ss(e,t,n),enabled:!!e})}function Tc(e,t=50,n=0){return Y(),$({queryKey:P.recentActivity(e,String(t),String(n)),queryFn:()=>rs(e,t,n),enabled:!!e})}function Ec(){let[e,t]=(0,_.useState)(null),[n,r]=(0,_.useState)(!0),[s,i]=(0,_.useState)(null);return(0,_.useEffect)(()=>{let o=!1;return Xe().then(a=>{if(!o){let c=typeof window<"u"&&window.__FSAOS_CONFIG__||{};t({path:a.scope_path,scope_id:a.scope_id,fractal_id:a.fractal_id,instance_name:a.instance_name,display_name:a.display_name,componentPath:c.componentPath||"",isEmbed:!!c.embedToken}),r(!1)}}).catch(a=>{o||(i(a instanceof Error?a:new Error(String(a))),r(!1))}),()=>{o=!0}},[]),{data:e,loading:n,error:s}}var ed=[];function ac(){if(typeof window>"u")return!1;let e=window.__FSAOS_CONFIG__?.embedToken;return typeof e=="function"||typeof e=="string"&&e.length>0}function td(e){return e.filter(t=>t.placement==="switcher_entry").map(t=>({account:t,mountables:e.filter(n=>n.placement!=="switcher_entry"&&n.subordinateTo===t.accountId)}))}function Ic(){let{user:e}=hs(),t=(0,_.useSyncExternalStore)(Jo,ai,ai),n=ht()?.principal_id??null,r=(0,_.useRef)(null),[s,i]=(0,_.useState)(null),[o,a]=(0,_.useState)(null);(0,_.useEffect)(()=>{if(n){a(null);return}if(!e?.id&&!ac()){a(null);return}let b=!1;return Xe().then(E=>{b||E.principal_id||a(new Error("Memberships require an authenticated principal"))}).catch(E=>{b||a(E instanceof Error?E:new Error(String(E)))}),()=>{b=!0}},[n,e?.id,t]);let c=$({queryKey:P.memberships(n??"anonymous"),queryFn:cs,enabled:!!n,staleTime:1e3*60*2}),u=c.data??ed,d=(0,_.useMemo)(()=>u.filter(b=>b.isAccount!==!1&&!b.isSpace),[u]),p=(0,_.useMemo)(()=>{let b=new Set(d.map(I=>I.accountId)),E=I=>!I.subordinateTo||!b.has(I.subordinateTo);return[...d].sort((I,R)=>Number(E(R))-Number(E(I)))},[d]),h=(0,_.useSyncExternalStore)(we,ee,ee),f=(0,_.useMemo)(()=>{let b=ye();return b?u.find(E=>E.accountId===b.id)??null:null},[h,u]),g=(0,_.useMemo)(()=>td(d),[d]);(0,_.useEffect)(()=>{if(!n){r.current=null;return}if(r.current!==n)if(i(null),p.length===1){let b=p[0];fe()||Mt(Ve(b)),Qt(b.accountId),b.personalSpacePath&&Dt(b.personalSpacePath,E=>{let I=u.find(R=>R.accountId===E);return I?Ve(I):null}).catch(i),r.current=n}else p.length>1&&(r.current=n)},[n,p,u]);let y=(0,_.useCallback)(async b=>{let E=u.find(F=>F.path===b);if(!E)throw new Error("Account membership is unavailable");let I=Ve(E);fe()||Mt(I);let R=u.find(F=>F.accountId===fe()?.id);if(!R?.personalSpacePath)throw new Error("The home membership has no mount declaration location");await Dt(R.personalSpacePath,F=>{let N=u.find(S=>S.accountId===F);return N?Ve(N):null}),await mr(I),i(null),Qt(E.accountId)},[u]),m=(0,_.useCallback)(async b=>{let E=u.find(I=>I.path===b);if(!E)throw new Error("Scope membership is unavailable");await wi(Ve(E))},[u]),v=(!!e?.id||ac())&&!n&&!o;return{accounts:p,switcherAccounts:g,allMemberships:u,currentAccount:f,mountedScope:null,switchAccount:y,mountScope:m,loading:v||c.isLoading,error:o??c.error??s}}function Ac(){Y();let e=(0,_.useSyncExternalStore)(Qr,tr,tr),t=(0,_.useMemo)(()=>Ee(),[e]),n=ye(),r=(0,_.useMemo)(()=>t.filter(i=>i.kind==="space"&&(n?.kind==="account"||i.id===n?.id)),[t,n]),s=(0,_.useMemo)(()=>r.map(i=>i.id).sort(),[r]);return{mounts:t,selectedSpaces:r,readSpaceIds:s,homeAnchor:fe(),anchor:n,setAnchor:mr,replaceMounts:fs,mount:wi,unmount:nc}}function hs(){let[e,t]=(0,_.useState)(null),[n,r]=(0,_.useState)(null),[s,i]=(0,_.useState)(!0),o=(0,_.useRef)(null);(0,_.useEffect)(()=>{W.auth.getSession().then(({data:f,error:g})=>{if(g){console.warn("[useAuth] getSession error, clearing stale session:",g.message),W.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(f?.session??null),t(f?.session?.user??null),i(!1)}).catch(f=>{console.warn("[useAuth] getSession threw, clearing stale session:",f?.message),W.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:h}}=W.auth.onAuthStateChange((f,g)=>{if(f==="TOKEN_REFRESHED"&&!g){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),W.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(g),t(g?.user??null),i(!1)});return o.current=h,()=>{h?.unsubscribe()}},[]);let a=(0,_.useCallback)(async h=>h.provider?W.auth.signInWithOAuth({provider:h.provider,options:h.redirectTo?{redirectTo:h.redirectTo}:{redirectTo:window.location.href}}):W.auth.signInWithPassword({email:h.email,password:h.password}),[]),c=(0,_.useCallback)(async h=>W.auth.signUp({email:h.email,password:h.password,options:{data:h.metadata||{}}}),[]),u=(0,_.useCallback)(async()=>{await W.auth.signOut(),mn(),O().clear()},[]),d=(0,_.useCallback)(async h=>{let{error:f}=await W.auth.resetPasswordForEmail(h);if(f)throw f},[]),p=(0,_.useCallback)(async(h,f)=>{let{error:g}=await W.auth.signInWithOtp({email:h,options:f?{emailRedirectTo:f}:{emailRedirectTo:window.location.href}});if(g)throw g},[]);return{user:e,session:n,loading:s,signIn:a,signUp:c,signOut:u,resetPassword:d,signInWithMagicLink:p}}function kc(e){let[t,n]=(0,_.useState)(null),[r,s]=(0,_.useState)(!1),[i,o]=(0,_.useState)(null);return(0,_.useEffect)(()=>{if(!e){n(null),s(!1);return}if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e))s(!0),x("resolve-asset",{asset_id:e}).then(c=>{c.success&&c.public_url?n({url:c.public_url,id:c.asset_id,name:c.name,mimeType:c.mime_type,width:c.width,height:c.height,sizeBytes:c.size_bytes}):o(new Error(c.error||"Asset not found")),s(!1)}).catch(c=>{o(c instanceof Error?c:new Error(String(c))),s(!1)});else{let u=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";n({url:u+e}),s(!1)}},[e]),{data:t,loading:r,error:i}}var hr={},cc={};ne(()=>{for(let e of Object.keys(hr))delete hr[e]});var Mc=null;function Oc(e){Mc=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function nd(e){switch(e){case"react":return typeof window<"u"&&window.React||_.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||Yl;case"react/jsx-runtime":case"react/jsx-dev-runtime":return typeof window<"u"&&window.React?{jsx:window.React.createElement,jsxs:window.React.createElement,Fragment:window.React.Fragment}:Xl;case"@fsaos/gateway":case"@fsaos/react":return typeof window<"u"&&window.__FSAOS_GATEWAY__||Mc||{};case"@fsaos/ui":return typeof window<"u"&&window.__FSAOS_UI__||{};case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}function rd(e,t){return e.replace(/^(\s*)(:root|body)(\s*[{,])/gm,(n,r,s,i)=>`${r}.${t}${i}`)}async function sd(e,t){if(!cc[e])try{let n=await fetch(e);if(!n.ok)return;let r=await n.text();if(!r.trim()||r.includes("No CSS bundle for this component"))return;t&&!r.includes(`.fsaos-c-${t}`)&&(r=rd(r,`fsaos-c-${t}`));let s=document.createElement("style");s.setAttribute("data-fsaos-component-css",e),t&&s.setAttribute("data-fsaos-component-id",t),s.textContent=r,document.head.appendChild(s),cc[e]=s}catch{}}function id(e){let t=null,n=window.__FSAOS_REGISTER__;window.__FSAOS_REGISTER__=r=>{t=r};try{let r=["var require = arguments[0];",e,"return window.__FSAOS_COMPONENT__;"].join(`
3
+ `),i=new Function(r)(nd),o=t??i;return o?o.default||o:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function Ci(e){let[t,n]=(0,_.useState)(null),[r,s]=(0,_.useState)(!0),[i,o]=(0,_.useState)(null);return(0,_.useEffect)(()=>{if(!e)return;let a=!1;s(!0),o(null);let u=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{try{let d=1,p=e+"@v1",h=u+e+"/__bundle.js";try{let v=await fetch(u+e+"/__meta",{cache:"no-store"});v.ok&&(d=(await v.json()).version||1,p=e+"@v"+d,h=u+e+"/__bundle.v"+d+".js")}catch{h=u+e+"/__bundle.js?v="+Date.now()}if(a)return;if(hr[p]){n(()=>hr[p]),s(!1);return}let f=await fetch(h);if(!f.ok)throw new Error(`Failed to fetch bundle: ${f.status} ${f.statusText} (${h})`);let g=await f.text();if(a)return;let y=h.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");sd(y).catch(()=>{});let m=id(g);if(!m)throw new Error("Bundle did not export a component. Expected window.__FSAOS_COMPONENT__ (FSAOS build) or a __FSAOS_REGISTER__(Component) call.");if(typeof m!="function")throw new Error(`Bundle export is not a React component (got ${typeof m})`);hr[p]=m,a||(n(()=>m),s(!1))}catch(d){a||(o(d instanceof Error?d:new Error(String(d))),s(!1))}})(),()=>{a=!0}},[e]),{Component:t,loading:r,error:i}}var od=["--color-primary","--color-secondary","--color-background","--color-surface","--color-text","--color-text-secondary","--color-border","--color-accent","--color-success","--color-warning","--color-error","--font-family-heading","--font-family-body","--border-radius","--spacing-unit"];function Fc(){return{data:(0,_.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let t={},n=getComputedStyle(document.documentElement);return od.forEach(r=>{t[r]=n.getPropertyValue(r).trim()}),{tokens:t}},[]),loading:!1,error:null}}function qc(e,t){return{data:{allowed:!0},loading:!1,error:null}}function Qc(e,t){let n={};return(t||[]).forEach(r=>{n[r]=!0}),{data:n,loading:!1,error:null}}var ue=null,En=null,Ri=new Set;function ad(){Ri.forEach(e=>e())}ne(()=>{ue=null,En=null});async function Dc(e){let t={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null},n=ht()?.principal_id??null;if(n){if(ue&&ue.principalId===n){let{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}=ue;return{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}}return{...t,principalId:n}}let r=e;if(!r){let{data:s}=await W.auth.getSession();r=s?.session?.user?.id}if(!r)return t;if(ue&&ue.authUserId===r){let{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}=ue;return{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}}return En||(En=(async()=>{try{let{data:s,error:i}=await W.from("os_principals").select("id, display_name, created_at, metadata").eq("auth_user_id",r).eq("principal_type","user").maybeSingle();if(i)return console.warn("[SDK] Could not resolve principal:",i.message),t;let o=s?.id??null,a=null;if(o){let{data:u}=await W.from("os_items").select("path").eq("owner_principal_id",o).eq("item_type","principal").eq("is_active",!0).like("path","/root/principals/%"),d=(u??[]).map(p=>p.path);a=d.find(p=>p.split("/").length===4)??d[0]??null}let c={principalId:o,displayName:s?.display_name??null,createdAt:s?.created_at??null,metadata:s?.metadata??null,vfsPath:a};return ue={authUserId:r,...c},c}finally{En=null}})(),En)}async function Uc(e){return(await Dc(e)).principalId}function Nc(){let e=hs(),t=e.user,n=ue?.authUserId===t?.id?ue:null,[r,s]=(0,_.useState)(n),i=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let o=()=>{let a=ue;a&&a.authUserId===t?.id&&s({principalId:a.principalId,displayName:a.displayName,createdAt:a.createdAt,metadata:a.metadata,vfsPath:a.vfsPath})};return Ri.add(o),()=>{Ri.delete(o)}},[t?.id]),(0,_.useEffect)(()=>{if(!t?.id){s(null),i.current=null;return}i.current===t.id&&r?.principalId!=null||(i.current=t.id,Dc(t.id).then(o=>{s(o)}))},[t?.id]),e.loading?{data:null,loading:!0,error:null}:t?{data:{id:t.id,principalId:r?.principalId??null,email:t.email,display_name:r?.displayName??void 0,created_at:r?.createdAt??void 0,vfs_path:r?.vfsPath??void 0,role:t.role||t.app_metadata?.role||"user",authenticated:!0,metadata:r?.metadata??t.user_metadata??{}},loading:!1,error:null}:{data:{id:"anonymous",principalId:null,role:"viewer",authenticated:!1},loading:!1,error:null}}function Kc(){return{data:null,loading:!1,error:null}}function Lc(e){let{path:t,...n}=e,r=Ci(t),s=r.Component,{loading:i,error:o}=r;return i?(0,_.createElement)("div",{className:"fsaos-loading"},""):o?(0,_.createElement)("div",{className:"fsaos-error"},"Failed to load component"):s?(0,_.createElement)(s,n):null}function jc(e){return e.children}function Vc(e){let t=Y(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=e,o=i!==void 0?i&&!!n:!!n,a=(0,_.useMemo)(()=>P.channelMessages(n??"",r),[n,r,t]),c=L(),u=(0,_.useRef)(null),d=$({queryKey:a,queryFn:()=>as(n,r),enabled:o});(0,_.useEffect)(()=>{if(!s||!o)return;let y=re("vfs_change",()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{ke(c,a,{exact:!0})},500)},m=>{let v=c.getQueryData(a);return Si(m,n,r,[...v?.messages??[],...v?.activityMessages??[]])});return()=>{y(),u.current&&clearTimeout(u.current)}},[s,o,n,r,a,c]);let p=d.data,h=p?.messages??[],f=p?.messageCards??new Map,g=p?.siblingCards??[];return{messages:h,activityMessages:p?.activityMessages??[],messageCards:f,siblingCards:g,threads:(0,_.useMemo)(()=>h.filter(y=>y.reply_count>0),[h]),breakouts:(0,_.useMemo)(()=>h.filter(y=>y.member_count>0),[h]),isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,refetch:d.refetch}}function $c(e){Y();let{channelPath:t,parentMessageId:n,limit:r=50,realtime:s=!0,enabled:i=!0,conversationsOnly:o=!1}=e,a=!!n,c=i&&!!t,u=Jn({queryKey:[...P.channelMessages(t||"",n),"infinite",r,"latest-first",...o?["conversations"]:[]],queryFn:async({pageParam:m})=>lr(t,{parentMessageId:n,limit:r,conversationsOnly:o,before_seq:m?.before_seq,after_seq:m?.after_seq}),initialPageParam:void 0,getPreviousPageParam:m=>{if(!a||m.messages.length<r)return;let v=m.messages[m.messages.length-1]?.seq;return v==null?void 0:{after_seq:v}},getNextPageParam:m=>{if(m.messages.length<r)return;let v=m.messages[0]?.seq;return v==null?void 0:{before_seq:v}},enabled:c}),d=(0,_.useMemo)(()=>{if(!u.data?.pages)return[];let m=new Set,v=[];for(let b of u.data.pages)for(let E of b.messages)m.has(E.id)||(m.add(E.id),v.push(E));return v.sort((b,E)=>b.seq-E.seq)},[u.data?.pages]),{messageCards:p,siblingCards:h}=(0,_.useMemo)(()=>{let m=new Map,v=[];if(!u.data?.pages)return{messageCards:m,siblingCards:v};let b=new Set;for(let E of u.data.pages){for(let[I,R]of E.messageCards)for(let F of R){if(b.has(F.id))continue;b.add(F.id);let N=m.get(I)||[];N.push(F),m.set(I,N)}for(let I of E.siblingCards)b.has(I.id)||(b.add(I.id),v.push(I))}return{messageCards:m,siblingCards:v}},[u.data?.pages]),f=L(),g=(0,_.useRef)(null),y=(0,_.useMemo)(()=>[...P.channelMessages(t||"",n),"infinite",r,"latest-first",...o?["conversations"]:[]],[t,n,r,o]);return(0,_.useEffect)(()=>{if(!s||!t||!c)return;let m=()=>void ke(f,y,{exact:!0}),v=!1,b=!1,E=!1,I=async()=>{if(o){m();return}let N=f.getQueryData(y);if(!N?.pages?.length){m();return}let S=0;for(let C of N.pages)for(let M of C.messages)M.seq>S&&(S=M.seq);if(S===0){m();return}try{let C=await lr(t,{parentMessageId:n,limit:r,after_seq:S});if(C.messages.length===0&&C.siblingCards.length===0){m();return}if(C.messages.length>0){let M=Math.min(...C.messages.map(A=>A.seq));if(M>S+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${S}, minNewSeq=${M}. Triggering full refetch.`),m();return}}f.setQueryData(y,M=>{if(!M)return M;let A=[...M.pages],k=0,Q=A[k],D=new Set(Q.messages.map(xe=>xe.id)),le=C.messages.filter(xe=>!D.has(xe.id)),H=[...Q.messages,...le].sort((xe,xs)=>xe.seq-xs.seq),Re=new Map(Q.messageCards);for(let[xe,xs]of C.messageCards){let $i=Re.get(xe)||[],sl=new Set($i.map(Ps=>Ps.id)),il=xs.filter(Ps=>!sl.has(Ps.id));Re.set(xe,[...$i,...il])}let tl=new Set(Q.siblingCards.map(xe=>xe.id)),nl=C.siblingCards.filter(xe=>!tl.has(xe.id)),rl=[...Q.siblingCards,...nl];return A[k]={...Q,activityMessages:C.activityMessages??[],messages:H,messageCards:Re,siblingCards:rl},{...M,pages:A}})}catch(C){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",C),m()}},R=async()=>{if(v){b=!0;return}v=!0;try{do b=!1,await I();while(b&&!E)}finally{v=!1}},F=re("vfs_change",()=>{g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{R()},500)},N=>o&&N?.item_type==="message"&&(f.getQueryData(y)?.pages??[]).some(S=>S.messages.some(C=>C.id===N.parent_id))||Si(N,t,n,f.getQueryData(y)?.pages.flatMap(S=>S.messages)??[]));return()=>{E=!0,F(),g.current&&clearTimeout(g.current)}},[s,t,c,y,f,n,r,o]),{messages:d,activityMessages:u.data?.pages[0]?.activityMessages??[],messageCards:p,siblingCards:h,threads:d.filter(m=>m.reply_count>0),breakouts:d.filter(m=>m.member_count>0),isLoading:u.isLoading,isFetching:u.isFetching,error:u.error,refetch:u.refetch,hasPreviousPage:u.hasNextPage??!1,fetchPreviousPage:u.fetchNextPage,isFetchingPreviousPage:u.isFetchingNextPage??!1,hasNextPage:u.hasPreviousPage??!1,fetchNextPage:u.fetchPreviousPage,isFetchingNextPage:u.isFetchingPreviousPage??!1}}var Wc=["open","active","strict","hand_raise"];function cd(e){return e==="open"||e==="active"||e==="strict"||e==="hand_raise"?e:e==="on"||e==="auto"?"active":"strict"}function ud(e){if(Array.isArray(e))return e.filter(t=>typeof t=="string")}function uc(e){let t=e.type_data||{},n=e._reader||{},r=n.context_lineage||{};return{id:e.id||"",path:e.path||"",name:e.name||"",displayName:t.display_name||e.name||"",aiMode:cd(t.ai_mode),activeAgentIds:ud(t.active_agent_ids),isPrivate:t.is_private||!1,isDm:t.is_dm||!1,messageCount:t.message_count||0,createdAt:e.created_at||"",updatedAt:e.updated_at||"",chatScopePath:r.context_path||"",contextId:e.scope_item_id||"",contextPath:r.context_path||"",contextType:r.context_type||"",contextName:r.context_name||"",contextDisplayName:r.context_name||"",contextPrincipalId:void 0,accountId:e.account_item_id||"",accountPath:"",accountDisplayName:"",memberRole:n.member_role||"member",memberPath:"",modePath:"",autoPilot:t.auto_pilot||!1,isArchived:t.is_archived===!0}}function gs(e={}){let t=Y(),{realtime:n=!0,enabled:r=!0,includeArchived:s=!1}=e,i=L(),o=(0,_.useMemo)(()=>P.channels("all"),[t]),a=$({queryKey:o,queryFn:async()=>((await x("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(uc),enabled:r});return(0,_.useEffect)(()=>{if(!(!n||!r))return sc(i,o,uc)},[n,r,o,i]),{channels:(0,_.useMemo)(()=>(a.data??[]).filter(u=>s||!u.isArchived),[a.data,s]),isLoading:a.isLoading,isFetching:a.isFetching,error:a.error,refetch:a.refetch}}function Bc(e={}){let t=gs(e),n=(0,_.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function Hc(e={}){let t=gs(e),n=(0,_.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function Ti(e={}){let t=Y(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=e,o=L(),a=(0,_.useRef)(null),c=(0,_.useMemo)(()=>P.notifications(n,r),[n,r,t]),u=$({queryKey:c,queryFn:async()=>{let p={limit:r};return n==="unread"&&(p.filter="unread"),(await x("get-notifications",p)).notifications||[]},enabled:i});return(0,_.useEffect)(()=>{if(!s||!i)return;let p=["vfs_change","ccm_change"].map(h=>re(h,()=>{a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{o.invalidateQueries({queryKey:c})},2e3)},f=>f.item_type==="notification"&&ps(f)));return()=>{p.forEach(h=>h()),a.current&&clearTimeout(a.current)}},[s,i,c,o]),{notifications:u.data??[],isLoading:u.isLoading,isFetching:u.isFetching,error:u.error,refetch:u.refetch}}function Gc(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:o,error:a,refetch:c}=Ti({filter:"unread",limit:200,realtime:n,enabled:r}),u=(0,_.useMemo)(()=>{let f=new Map;for(let g of s)g.is_unread&&g.channel_id&&f.set(g.channel_id,(f.get(g.channel_id)||0)+1);return f},[s]),d=(0,_.useMemo)(()=>{let f=0;return u.forEach(g=>{f+=g}),f},[u]),{dmUnread:p,channelUnread:h}=(0,_.useMemo)(()=>{if(!t)return{dmUnread:0,channelUnread:0};let f=new Set(t.filter(m=>m.isDm).map(m=>m.id)),g=0,y=0;return u.forEach((m,v)=>{f.has(v)?g+=m:y+=m}),{dmUnread:g,channelUnread:y}},[t,u]);return{unreadByChannel:u,totalUnread:d,dmUnread:p,channelUnread:h,isLoading:i,isFetching:o,error:a,refetch:c}}function zc(){let e=L();return Z({mutationFn:t=>x("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:P.children(r)})}})}function Jc(){let e=L();return Z({mutationFn:t=>x("update",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.invalidateQueries({queryKey:P.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:P.children(i)})}}})}function Yc(){return Z({mutationFn:e=>x("update-principal",e),onSuccess:(e,t)=>{if(!ue)return;let n=e&&typeof e=="object"&&e.metadata?e.metadata:{...ue.metadata??{},...typeof t.language=="string"?{language:t.language}:{},...typeof t.timezone=="string"?{timezone:t.timezone}:{},..."avatar_file_id"in t?{avatar_file_id:t.avatar_file_id}:{}};ue={...ue,displayName:typeof t.display_name=="string"?t.display_name:ue.displayName,metadata:n},ad()}})}function Xc(){let e=L();return Z({mutationFn:t=>x("delete",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.removeQueries({queryKey:P.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:P.children(i)})}}})}function Zc(){let e=L();return Z({mutationFn:t=>x("move",t),onSuccess:(t,n)=>{let r=n.path,s=n.new_parent_path;if(r){e.invalidateQueries({queryKey:P.item(r)});let i=r.split("/");i.pop();let o=i.join("/");o&&e.invalidateQueries({queryKey:P.children(o)})}s&&e.invalidateQueries({queryKey:P.children(s)})}})}function eu(){let e=L();return Z({mutationFn:t=>x("link",t),onSuccess:(t,n)=>{let r=n.source_id,s=n.target_id;r&&e.invalidateQueries({queryKey:P.edges(r)}),s&&e.invalidateQueries({queryKey:P.edges(s)})}})}function tu(e,t){let n=L(),{optimistic:r,...s}=t??{};return Z({mutationFn:i=>x(e,i),onMutate:r?async i=>{await n.cancelQueries({queryKey:r.queryKey});let o=n.getQueryData(r.queryKey);return n.setQueryData(r.queryKey,a=>r.update(a,i)),{previous:o}}:void 0,onError:(i,o,a)=>{r&&a?.previous!==void 0&&n.setQueryData(r.queryKey,a.previous),s.onError?.(i)},onSuccess:s.onSuccess,onSettled:r?()=>{n.invalidateQueries({queryKey:r.queryKey})}:void 0})}function nu(e,t,n){let r,s,i,o=!0;if(typeof e=="string")r=e,s=t,i=n;else{s=e;let u=t;r=u.eventType,i=u.filter,o=u.enabled??!0}let a=(0,_.useRef)(s),c=(0,_.useRef)(i);(0,_.useEffect)(()=>{a.current=s,c.current=i},[s,i]),(0,_.useEffect)(()=>o?re(r,d=>a.current(d),c.current?d=>c.current(d):void 0):void 0,[r,o])}function ru(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:o=500}=e,a=L(),c=(0,_.useRef)(s);c.current=s;let u=(0,_.useRef)(null),d=$({queryKey:t,queryFn:n,enabled:i});return(0,_.useEffect)(()=>{if(!i)return;let p=re(r,()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{ke(a,t,{exact:!0})},o)},h=>c.current?.(h)??!0);return()=>{p(),u.current&&clearTimeout(u.current)}},[r,i,o,a,JSON.stringify(t)]),d}function In(e){Y();let t=B(),n=(0,_.useMemo)(()=>e?typeof e=="string"?{path:e}:e:null,[typeof e=="string"?e:JSON.stringify(e)]),r=!!t&&!!n&&!!(n.key||n.path||n.item_id),s=n?.key??n?.path??n?.item_id??"",i=["vfs",t??"__unscoped__","arrangement",s,n?.scope_id??""],o=$({queryKey:i,staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0},queryFn:async()=>{if(!n)return null;let h=await x("resolve-arrangement",{...n,_scope_path:t});if(h?.success===!1)throw new Error(h?.error||"Arrangement could not be loaded");return h??null},enabled:r}),a=o.data??null,c=(0,_.useMemo)(()=>a?.resolved_children??[],[a]),u=a?.resolution_level??null,d=(0,_.useMemo)(()=>{let f=(a?.type_data??null)?.order;return Array.isArray(f)?f:null},[a]),p=(0,_.useCallback)(h=>{if(!d||!h?.length)return h??[];let f=v=>v.id??v.name??"",g=new Map(d.map((v,b)=>[v,b])),y=[],m=[];for(let v of h)(g.has(f(v))?y:m).push(v);return y.sort((v,b)=>g.get(f(v))-g.get(f(b))),[...y,...m]},[d]);return{...o,arrangement:a,resolvedChildren:c,resolutionLevel:u,order:d,sourceScopeId:a?.scope_item_id??null,arrangementQueryKey:i,applyTo:p}}function su(e){let{origin:t,originField:n,fallbackUrl:r,mintError:s,scopeId:i,scopePath:o}=e,a=Y(),c=ht(),u=i??c?.scope_id??null,d=(0,_.useMemo)(()=>{if(!t)return null;let R="/accounts/",F=t.indexOf(R);if(F===-1)return null;let N=t.indexOf("/",F+R.length);return N===-1?t:t.slice(0,N)},[t]),p=o??d??c?.scope_path??null,h=n?.trim()||null,f=`${a}
4
4
  ${u??""}
5
5
  ${p??""}
6
- ${m??""}
7
- ${t??""}`,[y,g]=(0,_.useState)(null),h=(0,_.useRef)({key:f,found:null,earlyContentPaths:new Set}),v=y?.key===f?y:null;(0,_.useLayoutEffect)(()=>{h.current={key:f,found:v,earlyContentPaths:new Set}},[f]);let b=$({queryKey:["vfs",p??"__unscoped__","minted-asset",m??"",t??""],queryFn:async()=>{let R=await x("query",{scope_path:p,filters:{[`field.${m}`]:t},limit:1}),M=R.content?.items??R.items??[],N=M[0]?_e(M[0]):null;if(!N)return null;let T=(await cr(N.path)).some(F=>F.item_type==="file"&&!!F.type_data?.file_ref);return{asset:N,hasBytes:T}},enabled:!!(t&&p&&m&&!s),refetchInterval:R=>h.current.key===f&&h.current.found?.hasBytes||R.state.data?.hasBytes?!1:1500});(0,_.useEffect)(()=>{let R=b.data;if(!R||h.current.key!==f)return;let M=h.current.found,N={key:f,itemId:R.asset.id,itemPath:R.asset.path,displayName:typeof R.asset.type_data?.display_name=="string"?R.asset.type_data.display_name:R.asset.name,hasBytes:R.hasBytes||!!(M?.itemId===R.asset.id&&M.hasBytes)};h.current.found=N,g(N)},[b.data,f]);let E=!!(t&&u)&&!s&&!v?.hasBytes;return(0,_.useEffect)(()=>{if(!(!E||!u))return Sn(u,["asset.materialized","content.written"])},[E,u]),(0,_.useEffect)(()=>{if(!E||!t||!u)return;let R=f,M=k=>k?.payload??k,N=k=>{let U=M(k)?.scope_id??k?.scope_id;return typeof U=="string"?U:void 0},S=k=>{let U=M(k)?.item_path??k?.item_path;return typeof U=="string"&&U?U:void 0},T=(k,A)=>{let U=A.replace(/\/+$/,"");return k===U||k.startsWith(`${U}/`)},F=[re("asset.materialized",k=>{if(h.current.key!==R)return;let A=M(k);if(typeof A?.item_id!="string"||!A.item_id)return;let U=h.current.found,Q=typeof A.item_path=="string"?A.item_path:void 0,le=!!A.has_bytes||!!(Q&&Array.from(h.current.earlyContentPaths).some(qe=>T(qe,Q)))||!!(U&&U.itemId===A.item_id&&U.hasBytes),B={key:R,itemId:A.item_id,itemPath:Q,displayName:typeof A.display_name=="string"?A.display_name:void 0,hasBytes:le};h.current.found=B,g(B)},k=>{let A=N(k);return(!A||A===u)&&M(k)?.origin===t}),re("content.written",k=>{if(h.current.key!==R)return;let A=S(k);if(!A)return;let U=h.current.found;if(!U?.itemPath||!T(A,U.itemPath)){if(h.current.earlyContentPaths.add(A),h.current.earlyContentPaths.size>128){let le=h.current.earlyContentPaths.values().next().value;le&&h.current.earlyContentPaths.delete(le)}return}if(U.hasBytes)return;let Q={...U,hasBytes:!0};h.current.found=Q,g(Q)},k=>{let A=N(k);return(!A||A===u)&&!!S(k)})];return()=>F.forEach(k=>k())},[E,t,u,f]),{state:s?"failed":t?v?v.hasBytes?"ready":"materializing":"pending":"idle",itemId:v?.itemId,itemPath:v?.itemPath,displayName:v?.displayName,fallbackUrl:r??void 0,error:s??void 0}}function iu(e,t){let n=O().getDefaultOptions().queries?.retry??1;return typeof n=="function"?n(e,t):n===!0||typeof n=="number"&&e<n}function ou(e,t){let n=(0,An.useSyncExternalStore)(we,ee,ee),r=ye(),s=H(),i=r?.kind==="space",o=In(i&&s?{key:e,scope_id:r.id}:null),c=(0,An.useMemo)(()=>{let f=o.applyTo([...t]);if(e!=="channel-order")return f;let y=new Set(o.order??[]),g=f.filter(v=>!y.has(v.id)),h=v=>Date.parse(v.createdAt??"")||0;return g.sort((v,b)=>h(b)-h(v)),[...g,...f.filter(v=>y.has(v.id))]},[e,t,o.applyTo,o.order]),a=L(),u=(0,An.useRef)(!1),d=!!(i&&!o.error&&o.arrangement?.item_id&&o.resolutionLevel==="member"&&o.arrangement.write_target_id===o.arrangement.item_id),p=Z({mutationFn:async f=>{let y=await x("update",{_scope_path:f.scopePath,id:f.arrangementId,type_data:{order:f.ids}});if(y?.success===!1)throw new Error(y.error||"Order could not be saved");return y},onSettled:(f,y,g)=>Ze(a,g.queryKey)});async function m(f){if(!d||!s||n!==ee()||H()!==s)throw new Error("Personal order is not available in this Space");if(u.current)throw new Error("An order change is already being saved");let y=t.map(R=>R.id);if(f.length!==y.length||new Set(f).size!==y.length||y.some(R=>!f.includes(R)))throw new Error("Order must include each displayed item exactly once");let g=a.getQueryData(o.arrangementQueryKey);if(g?.item_id!==o.arrangement.item_id||JSON.stringify(g?.type_data?.order??[])!==JSON.stringify(o.order??[]))throw new Error("The saved order changed. Try dragging again");let h=c.map(R=>R.id);if(f.every((R,M)=>h[M]===R))return;let v=new Set(y),b=0,I=[...(o.order??[]).map(R=>v.has(R)?f[b++]:R),...f.slice(b)];u.current=!0;try{return await p.mutateAsync({ids:I,scopePath:s,arrangementId:o.arrangement.item_id,queryKey:o.arrangementQueryKey})}finally{u.current=!1}}return{items:c,ready:d,supported:i,contextKey:`${n}:${s}:${e}`,isLoading:i&&o.isLoading,error:o.error,refetch:o.refetch,isSaving:p.isPending,saveError:p.error,reorder:m}}var Ei=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,ud=/^[A-Za-z_:][A-Za-z0-9_:.-]{0,127}$/,au=new Map,cu=new Map,kn=class extends Error{constructor(n,r,s,i){super(n);te(this,"code");te(this,"status");te(this,"eventId");this.name="InteractionTrackingError",this.code=r,this.status=s,this.eventId=i}};function Ut(e){let t=e?At.find(n=>n.id===e):At.find(n=>n.default===!0)??(At.length===1?At[0]:void 0);if(!t)throw new TypeError("No unambiguous source is declared for this release");if(!t.id||!Number.isInteger(t.version)||t.version<1)throw new TypeError("The release source declaration is invalid");return t}function ys(e,t){let n=t.adapters?.find(r=>r.type===e);if(!n)throw new TypeError(`The source does not declare a ${e} adapter`);return n}function ld(e){return e.length>0&&e.length<=128&&!/[\u0000-\u001f\u007f]/.test(e)}function dd(e,t){if(!ld(t)||!e.observations?.includes(t))throw new TypeError("The observation is not declared by this release source")}function Ii(e){if(!(typeof window>"u"||e.storage==="memory"))try{return e.storage==="session"?window.sessionStorage:window.localStorage}catch{return}}function fd(e){try{let t=Ii(e)?.getItem(e.key)??void 0;return t&&Ei.test(t)?t:void 0}catch{return}}function uu(e,t){try{Ii(e)?.setItem(e.key,t)}catch{}}function lu(e){let t=e.identity?.visitor;if(!t?.key)throw new TypeError("The source visitor identity policy is invalid");let n=fd(t)??au.get(e.id);if(n)return n;let r=crypto.randomUUID();return au.set(e.id,r),uu(t,r),r}function du(e,t=Date.now()){let n=e.identity?.session;if(!n?.key||!Number.isInteger(n.idle_seconds)||n.idle_seconds<1)throw new TypeError("The source session identity policy is invalid");let r;try{let u=Ii(n)?.getItem(n.key);r=u?JSON.parse(u):void 0}catch{r=void 0}let s=cu.get(e.id),i=r&&typeof r.id=="string"&&Ei.test(r.id)&&typeof r.lastSeenAt=="number"?{id:r.id,lastSeenAt:r.lastSeenAt}:s,o=n.idle_seconds*1e3,a=i&&t-i.lastSeenAt>=0&&t-i.lastSeenAt<o?{id:i.id,lastSeenAt:t}:{id:crypto.randomUUID(),lastSeenAt:t};return cu.set(e.id,a),uu(n,JSON.stringify(a)),a.id}function pd(e,t){let n=e.source_keys?.query;if(!Array.isArray(n)||n.length===0)return;let r;try{r=new URL(t)}catch{return}let s=e.source_keys?.max_value_length,i=Number.isInteger(s)?Math.min(Math.max(s??1,1),4096):512,o=Object.fromEntries(n.flatMap(c=>{if(typeof c!="string"||c.length===0||c.length>128)return[];let a=r.searchParams.get(c);return a?[[c,a.slice(0,i)]]:[]}));return Object.keys(o).length>0?o:void 0}async function Nt(e,t={},n={}){let r=Ut(n.source);if(dd(r,e),!t||typeof t!="object"||Array.isArray(t))throw new TypeError("properties must be an object");let s=n.eventId??crypto.randomUUID(),i=n.visitorId??lu(r),o=n.sessionId??du(r);if(![s,i,o].every(h=>Ei.test(h)))throw new TypeError("event, visitor, and session IDs must be UUIDs");let c=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!c)throw new TypeError("pageUrl is required outside a browser");let a=n.occurredAt??new Date().toISOString();if(Number.isNaN(Date.parse(a)))throw new TypeError("occurredAt is invalid");let u=n.referrer??(typeof document<"u"&&document.referrer||void 0),d=pd(r,c),p=d?{...t,source_keys:d}:t,m=Ot(),f=`${Ce.replace(/\/+$/,"")}/d/${encodeURIComponent(m)}/interactions`,y;try{y=await fetch(f,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({source:r.id,page_url:c,visitor_id:i,session_id:o,referrer:u,events:[{id:s,event_type:e,occurred_at:a,properties:p}]}),signal:n.signal,credentials:"omit",keepalive:n.keepalive??!1})}catch(h){throw new kn(h instanceof Error?h.message:"Observation transport network error","OBSERVATION_NETWORK_ERROR",0,s)}let g=null;try{g=await y.json()}catch{}if(!y.ok||g?.success!==!0){let h=g;throw new kn(h?.message||h?.error||`Observation transport failed (${y.status})`,h?.error||"OBSERVATION_TRANSPORT_FAILED",y.status,s)}return g}function fu(e={},t={}){let n=Ut(t.source),r=ys("page_view",n),s=typeof document>"u"||!r.title_property?{}:{[r.title_property]:document.title.slice(0,512)};return Nt(r.observation,{...s,...e},{...t,source:n.id})}function pu(e,t={},n={}){if(!e||e.length>128)throw new TypeError("actionId is invalid");let r=Ut(n.source),s=ys("declared_action",r),i=s.id_property?{[s.id_property]:e}:{};return Nt(s.observation,{...t,...i},{...n,source:r.id})}function mu(){try{let e=Ut();return ys("form_receipt",e),{visitor_id:lu(e),session_id:du(e),source:e.id}}catch{return}}function md(e,t={}){let n=Ut(t.source),r=ys("form_receipt",n);return Nt(r.observation,e,{...t,source:n.id})}async function hd(e,t){let r=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${e}\0${t}`))).slice(0,16);r[6]=r[6]&15|80,r[8]=r[8]&63|128;let s=Array.from(r,i=>i.toString(16).padStart(2,"0")).join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}async function hu(e,t,n,r,s){let i=At.filter(o=>o.adapters?.some(c=>c.type==="form_receipt"));await Promise.allSettled(i.map(async o=>{let c=o.id===r?.source;return md(e,{source:o.id,eventId:c?t:await hd(t,o.id),pageUrl:n,signal:s,keepalive:!0,...c?{visitorId:r.visitor_id,sessionId:r.session_id}:{}})}))}var gr;function _s(e={}){if(typeof window>"u"||typeof document>"u")return()=>{};if(gr)return gr;if(window.__FSAOS_CONFIG__?.tracking?.enabled===!1)return()=>{};let t;try{t=e.source?[Ut(e.source)]:At.map(m=>Ut(m.id))}catch{return()=>{}}if(t.length===0)return()=>{};let n=e.pageViews===!1?[]:t.flatMap(m=>m.adapters.filter(f=>f.type==="page_view").map(f=>({source:m,adapter:f}))),r=e.declaredActions===!1?[]:t.flatMap(m=>m.adapters.filter(f=>f.type==="declared_action").map(f=>({source:m,adapter:f}))),s="",i=()=>{if(window.location.href!==s){s=window.location.href;for(let{source:m,adapter:f}of n){let y=f.title_property?{[f.title_property]:document.title.slice(0,512)}:{};Nt(f.observation,y,{source:m.id,keepalive:!0}).catch(()=>{})}}},o=m=>{if(m.target instanceof Element)for(let{source:f,adapter:y}of r){let g=y.attribute;if(!g||!ud.test(g))continue;let h=m.target.closest(`[${g}]`);if(!h)continue;let v=h.getAttribute(g)?.trim();if(!v||v.length>128)continue;let b={};y.id_property&&(b[y.id_property]=v),y.element_property&&(b[y.element_property]=h.tagName.toLowerCase()),Nt(y.observation,b,{source:f.id,keepalive:!0}).catch(()=>{})}},c=window.history.pushState,a=window.history.replaceState,u=()=>queueMicrotask(i),d=n.some(({adapter:m})=>m.history===!0),p=n.some(({adapter:m})=>m.pageshow===!0);return d&&(window.history.pushState=function(...f){c.apply(this,f),u()},window.history.replaceState=function(...f){a.apply(this,f),u()},window.addEventListener("popstate",i)),p&&window.addEventListener("pageshow",i),r.length>0&&document.addEventListener("click",o,{capture:!0}),n.length>0&&queueMicrotask(i),gr=()=>{window.removeEventListener("popstate",i),window.removeEventListener("pageshow",i),document.removeEventListener("click",o,{capture:!0}),d&&(window.history.pushState=c,window.history.replaceState=a),gr=void 0},gr}var Mn;ne(()=>{Mn=void 0});function vs(e){if(Mn)return Mn.accountPath!==e.accountPath?Promise.reject(new Error("Reset the session before changing accounts")):Mn.promise;let t=ie(),n=()=>{if(t!==ie())throw new Error("Workspace session changed")},r=(async()=>{let s=await Xe();if(n(),!s.principal_id)throw new Error("Workspace initialization requires an authenticated principal");let i=await O().fetchQuery({queryKey:P.memberships(s.principal_id),queryFn:cs,staleTime:12e4,retry:!1});n();let o=i.find(p=>p.path===e.accountPath&&p.isAccount&&!p.isSpace);if(!o)throw new Error("Authenticated account membership is unavailable");let c=i.find(p=>p.isSpace&&p.accountId===o.personalSpaceId&&p.path===o.personalSpacePath);if(!c||!o.personalSpacePath)throw new Error("A provisioned default Space membership is required");let a=Ve(o),u=Ve(c),d=fe();if(d&&d.id!==a.id)throw new Error("Reset the session before changing accounts");return d||Mt(a,{activate:!1}),await Dt(o.personalSpacePath,p=>{let m=i.find(f=>f.accountId===p&&(f.isAccount||f.isSpace));return m?Ve(m):null},{initialAnchor:u}),n(),{home:a,defaultSpace:u,memberships:i}})().catch(s=>{throw t===ie()&&(Mn=void 0),s});return Mn={accountPath:e.accountPath,promise:r},r}var Kt,_r,yr;ne(()=>{_r?.(),_r=void 0,Kt=void 0,yr=void 0});function gu(e={}){if(Kt)return e.workspace&&e.workspace.accountPath!==yr?Promise.reject(new Error("Initialize workspace through initializeWorkspace, or dispose the existing runtime first")):Kt;yr=e.workspace?.accountPath;let t=ie();return Kt=(async()=>{let n=e.tracking??!0,r=n===!1?()=>{}:_s(typeof n=="object"?n:{});_r=r;try{let s=e.session===!1?null:await Xe(),i=e.workspace?await vs(e.workspace):void 0;if(t!==ie())throw new Error("Session changed during initialization");let o=!1;return{session:s,workspace:i,dispose(){o||(o=!0,r(),t===ie()&&(Kt=void 0,yr=void 0,_r=void 0))}}}catch(s){throw r(),t===ie()&&(Kt=void 0,yr=void 0,_r=void 0),s}})(),Kt}async function Ai(e){try{return await x("execution-control-transition",e)}catch(t){if(!(t instanceof Ie)||t.status<500)throw t;return await new Promise(n=>setTimeout(n,250)),x("execution-control-transition",e)}}function ki(e){let t=e.conversation_anchor_item_id??e.conversation_root_id;return t?{...e,conversation_anchor_item_id:t,conversation_root_id:e.conversation_root_id??t}:e}async function yu(e,t={}){let n=e.trim();if(!n)throw new TypeError("cancelTurn requires a request message id");let r=(t.idempotencyKey??`cancel:${n}`).trim();if(!r)throw new TypeError("cancelTurn requires a non-empty idempotency key");if(r.length>128)throw new TypeError("cancelTurn idempotency key must be 128 characters or fewer");let s=await Ai({op:"request",command:"cancel",delivery:"immediate",request_message_id:n,idempotency_key:r,...t.scopePath?{_scope_path:t.scopePath}:{}}),i=s.outcome??s.state??s.status;return ki(i?{...s,state:i}:s)}async function _u(e,t,n={}){let r=e.trim(),s=t.trim();if(!r)throw new TypeError("steerTurn requires an active request message id");if(!s)throw new TypeError("steerTurn requires a selected queue entry id");if(r===s)throw new TypeError("steerTurn cannot target the active request message");let i=(n.idempotencyKey??`steer:${r}:${s}`).trim();if(!i)throw new TypeError("steerTurn requires a non-empty idempotency key");if(i.length>128)throw new TypeError("steerTurn idempotency key must be 128 characters or fewer");let o=await Ai({op:"request",command:"steer",delivery:"immediate",request_message_id:r,selected_queue_entry_id:s,idempotency_key:i,...n.scopePath?{_scope_path:n.scopePath}:{}}),c=o.outcome??o.state??o.status;return ki(c?{...o,state:c}:o)}async function vu(e,t={}){let n=e.trim();if(!n)throw new TypeError("cancelQueuedTurn requires a queue entry id");let r=(t.idempotencyKey??`cancel-queue:${n}`).trim();if(!r)throw new TypeError("cancelQueuedTurn requires a non-empty idempotency key");if(r.length>128)throw new TypeError("cancelQueuedTurn idempotency key must be 128 characters or fewer");let s=await Ai({op:"cancel_queue_entry",queue_entry_id:n,idempotency_key:r,...t.scopePath?{_scope_path:t.scopePath}:{}}),i=s.outcome??s.state??s.status;return ki(i?{...s,outcome:i}:s)}var gd=/^[a-z][a-z0-9_-]{0,63}$/,yd=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,On=class extends Error{constructor(n,r,s,i){super(n);te(this,"code");te(this,"status");te(this,"fillId");this.name="FormSubmissionError",this.code=r,this.status=s,this.fillId=i}};async function bu(e,t,n={}){if(!gd.test(e))throw new TypeError("capabilityId is invalid");if(!t||typeof t!="object"||Array.isArray(t))throw new TypeError("fields must be an object");let r=n.fillId??crypto.randomUUID();if(!yd.test(r))throw new TypeError("fillId must be a UUID");let s=Ot(),i=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!i)throw new TypeError("pageUrl is required outside a browser");let o=`${Ce.replace(/\/+$/,"")}/d/${encodeURIComponent(s)}/actions/${encodeURIComponent(e)}`,c=mu(),a=c?{visitor_id:c.visitor_id,session_id:c.session_id}:void 0,u;try{u=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({fill_id:r,page_url:i,fields:t,...a?{attribution:a}:{}}),signal:n.signal,credentials:"omit"})}catch(p){throw new On(p instanceof Error?p.message:"Form submission network error","FORM_NETWORK_ERROR",0,r)}let d=null;try{d=await u.json()}catch{}if(!u.ok||d?.success!==!0){let p=d;throw new On(p?.message||p?.error||`Form submission failed (${u.status})`,p?.error||"FORM_SUBMISSION_FAILED",u.status,r)}return await hu({fill_id:r,action_id:e,release_id:d.release_id},r,i,c,n.signal),d}var Mi=X(ae(),1),Ru=X(Su(),1);function xu(e){return x("read",{path:e})}function Pu(e,t){return x("list",{path:e,...t})}function Cu(e){return x("create",e)}function Tu(e){return x("update",e)}function Eu(e){return x("create",e)}function Iu(e,t){let r=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return x("tools/call",{name:e,instance_path:r,...t||{}})}function Au(e,t,n){return x("signal",{target_id:e,event_name:t,payload:n||{}})}function ku(e){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+e}var Mu={signIn:e=>e.provider?W.auth.signInWithOAuth({provider:e.provider,options:{redirectTo:e.redirectTo||window.location.href}}):W.auth.signInWithPassword({email:e.email,password:e.password}),signUp:e=>W.auth.signUp({email:e.email,password:e.password,options:{data:e.metadata||{}}}),signOut:async()=>{await W.auth.signOut(),mn(),O().clear()},getSession:()=>W.auth.getSession().then(e=>e.data.session),getUser:()=>W.auth.getUser().then(e=>e.data.user),onAuthStateChange:e=>{let{data:{subscription:t}}=W.auth.onAuthStateChange((n,r)=>{e({event:n,session:r,user:r?.user??null})});return()=>t?.unsubscribe()},resetPassword:e=>W.auth.resetPasswordForEmail(e),signInWithMagicLink:(e,t)=>W.auth.signInWithOtp({email:e,options:{emailRedirectTo:t||window.location.href}})};function Ou(){let e=document.getElementById("root");if(e)try{let t=window.__FSAOS_COMPONENT__;if(!t){e.innerHTML='<div style="padding:2rem;color:#ef4444;font-family:system-ui"><h2>Component Error</h2><pre>No component found. The bundle may have failed to load.</pre></div>';return}let n=t.default||t,r=window.__FSAOS_ITEM_DATA__||null,s=r?{item:r,...r}:{};(0,Ru.createRoot)(e).render((0,Mi.createElement)(Gn,{client:O()},(0,Mi.createElement)(n,s)))}catch(t){console.error("[FSAOS] Failed to mount root component:",t),e.innerHTML='<div style="padding:2rem;color:#ef4444;font-family:system-ui"><h2>Component Error</h2><pre>'+(t.message||t)+"</pre></div>"}}function Fu(){let e=window.React,t=window.ReactDOM,n=window.__FSAOS_GATEWAY__,r=window.__FSAOS_UI__;if(!n){console.error("[FSAOS] Cannot set up require shim: __FSAOS_GATEWAY__ not found");return}let s={react:e,"react-dom":t,"react-dom/client":t,"react/jsx-runtime":{jsx:e?.createElement,jsxs:e?.createElement,Fragment:e?.Fragment},"@fsaos/kernel":n,"@fsaos/react":n,"@fsaos/gateway":n,"@fsaos/ui":r||{}};window.require=function(o){if(s[o])return s[o];throw new Error("[FSAOS] Module not found: "+o)},window.__FSAOS_MOUNT__=n.mount}function Oi(e){return x("invite-member",e)}function Fi(e){return x("accept-invite",e)}function qi(e){let t={};return e.role&&(t.role=e.role),x("link",{source_id:e.chat_id,target_id:e.member_id,edge_type:"has_member",context:t})}function Qi(e){return x("create-agent",e)}function Di(e){return!e.input_request_id&&!e.input_request?Promise.reject(new Error("answerInput needs input_request_id or the input_request object read from the step.")):x("todo-control",{action:"answer_input",...e})}function qu(){return Z({mutationFn:Oi})}function Qu(){let e=L();return Z({mutationFn:Fi,onSuccess:()=>{e.invalidateQueries({queryKey:["memberships"]})}})}function Du(){let e=L();return Z({mutationFn:qi,onSuccess:(t,n)=>{e.invalidateQueries({queryKey:P.edges(n.chat_id)}),e.invalidateQueries({queryKey:P.edges(n.member_id)})}})}function Uu(){let e=L();return Z({mutationFn:Qi,onSuccess:()=>{e.invalidateQueries({queryKey:["memberships"]})}})}function Nu(){let e=L();return Z({mutationFn:Di,onSuccess:(t,n)=>{e.invalidateQueries({queryKey:P.itemById(n.step_id)})}})}function _d(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function vd(e,t){return t&&t.length>0?"select":e==="boolean"?"toggle":e==="integer"||e==="number"?"range":e==="string"?"text":"none"}function bd(e,t){return!(e==="object"||e==="array")}function wd(e){return["string","number","integer","boolean"].includes(e)}function Sd(e){return e!=="object"&&e!=="array"}function Ku(e,t,n,r){let s=e?.properties;if(!s||typeof s!="object")return[];let i=[];for(let[o,c]of Object.entries(s)){let a=c.type||"string",u=c.enum,d=bd(a,u),p=wd(a),m=vd(a,u);i.push({key:o,label:c.title||_d(o),type:a,description:c.description,enum_values:u,default_value:n[o]??r[o]??c.default,editable:t,filterable:d,sortable:p,filter_widget:m})}return i}function Ui(e){let t=e.default_data||{},n=e.field_defaults||{},r=Ku(e.input_schema,!0,t,n),s=Ku(e.system_schema,!1,t,n),i=[...r,...s],o=i.filter(u=>Sd(u.type)),c=i.filter(u=>u.filterable),a=i.filter(u=>u.sortable);return{fields:i,columns:o,filterable:c,sortable:a,form_fields:r,system_fields:s}}function Lu(e){return{field:"updated_at",direction:"desc"}}function ju(e){let t=Ui(e),n=new Set(e.input_schema?.required||[]);return t.form_fields.filter(r=>n.has(r.key)||r.default_value===void 0)}var ve=X(ae(),1);var Rd=0;function xd(){return`upload_${Date.now()}_${++Rd}`}async function Vu(e,t,n,r){let s=t.name||(e instanceof File?e.name:`file-${Date.now()}`),i=e.type||"application/octet-stream",o=t.itemType||"file",c={parent_path:t.parentPath,item_type:o,name:s,type_data:{...t.typeData||{},file_source:{type:"upload",content_type:i}}};t.cardParentPath&&(c.card_parent_path=t.cardParentPath);let u=await x("create",c);if(!u.id)throw new Error(u.error||u.message||"Failed to create file item");let d=u.id,p=u.path;if(u.storage_completed&&u.file_ref)return{itemId:d,itemPath:p,fileRef:u.file_ref};let m=u.storage_key,f=u.upload_token,y=u.storage_worker_url||"https://fsaos-storage.radns.workers.dev";if(!m)throw new Error("Gateway returned no storage_key \u2014 file_source may not be supported for this item type");await Pd(y,m,f,e,i,n,r);let g=await $u(d,m,i);return{itemId:d,itemPath:p,fileRef:g}}function Pd(e,t,n,r,s,i,o){return new Promise((c,a)=>{let u=new XMLHttpRequest;if(u.open("PUT",`${e}/upload`),u.setRequestHeader("X-Storage-Key",t),u.setRequestHeader("Content-Type",s),n&&u.setRequestHeader("X-Upload-Token",n),u.upload.onprogress=d=>{d.lengthComputable&&i&&i(Math.round(d.loaded/d.total*100))},u.onload=()=>{u.status>=200&&u.status<300?c():a(new Error(`Storage upload failed: HTTP ${u.status} \u2014 ${u.responseText?.slice(0,300)}`))},u.onerror=()=>a(new Error("Storage upload network error")),u.ontimeout=()=>a(new Error("Storage upload timed out")),o){if(o.aborted){a(new Error("Upload cancelled"));return}o.addEventListener("abort",()=>{u.abort(),a(new Error("Upload cancelled"))})}u.send(r)})}async function $u(e,t,n){let r=await Ye(),s=await fetch(`${Ce}/storage/upload-complete`,{method:"POST",headers:{"Content-Type":"application/json",...r?{Authorization:`Bearer ${r}`}:{}},body:JSON.stringify({item_id:e,storage_key:t,content_type:n})});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Upload confirmation failed: HTTP ${s.status} \u2014 ${o.slice(0,300)}`)}let i=await s.json();if(!i.success)throw new Error(i.error||i.message||"Upload confirmation rejected");return i.file_ref}function Wu(){let[e,t]=(0,ve.useState)([]),n=L(),r=(0,ve.useRef)(e);r.current=e;let s=(0,ve.useCallback)((g,h)=>{t(v=>v.map(b=>b.id===g?{...b,...h}:b))},[]),i=(0,ve.useCallback)(g=>{t(h=>[...h,g])},[]),o=(0,ve.useCallback)(async(g,h,v,b,E)=>{let I=v.name||h.name,R=h.type||"application/octet-stream",M=v.itemType||"file",N=E?.itemId||null,S=E?.itemPath||null,T=E?.storageKey||null,F=E?.uploadToken||null,k=E?.storageWorkerUrl||null;try{if(!b||b==="create"){s(g,{status:"creating",error:null,_failedAt:null});let Q=await x("create",{parent_path:v.parentPath,item_type:M,name:I,type_data:{...v.typeData||{},file_source:{type:"upload",content_type:R}}});if(!Q.id)throw Object.assign(new Error(Q.error||Q.message||"Failed to create file item"),{_step:"create"});if(N=Q.id,S=Q.path,s(g,{itemId:N,itemPath:S}),Q.storage_completed&&Q.file_ref){s(g,{status:"complete",progress:100,fileRef:Q.file_ref}),n.invalidateQueries({queryKey:P.children(v.parentPath)});return}if(T=Q.storage_key,F=Q.upload_token||"",k=Q.storage_worker_url||"https://fsaos-storage.radns.workers.dev",s(g,{_storageKey:T,_uploadToken:F,_storageWorkerUrl:k}),!T)throw Object.assign(new Error("Gateway returned no storage_key"),{_step:"create"})}(!b||b==="create"||b==="upload")&&(s(g,{status:"uploading",progress:0,error:null,_failedAt:null}),await new Promise((Q,le)=>{let B=new XMLHttpRequest;s(g,{_xhr:B}),B.open("PUT",`${k}/upload`),B.setRequestHeader("X-Storage-Key",T),B.setRequestHeader("Content-Type",R),F&&B.setRequestHeader("X-Upload-Token",F),B.upload.onprogress=qe=>{qe.lengthComputable&&s(g,{progress:Math.round(qe.loaded/qe.total*100)})},B.onload=()=>{B.status>=200&&B.status<300?Q():le(Object.assign(new Error(`Storage upload failed: HTTP ${B.status}`),{_step:"upload"}))},B.onerror=()=>le(Object.assign(new Error("Storage upload network error"),{_step:"upload"})),B.ontimeout=()=>le(Object.assign(new Error("Storage upload timed out"),{_step:"upload"})),B.send(h)}),s(g,{progress:100,_xhr:null})),s(g,{status:"confirming",error:null,_failedAt:null});let A=await $u(N,T,R);s(g,{status:"complete",fileRef:A}),n.invalidateQueries({queryKey:P.children(v.parentPath)})}catch(A){let U=A?.message||String(A),Q=A?._step||"create";s(g,{status:"error",error:U,_failedAt:Q,_xhr:null})}},[s,n]),c=(0,ve.useCallback)((g,h)=>{let v=xd();i({id:v,file:g,status:"creating",progress:0,error:null,itemId:null,itemPath:null,fileRef:null,options:h,_storageKey:null,_uploadToken:null,_storageWorkerUrl:null,_xhr:null,_failedAt:null}),o(v,g,h)},[i,o]),a=(0,ve.useCallback)((g,h)=>{for(let v of g)c(v,h)},[c]),u=(0,ve.useCallback)(g=>{let h=r.current.find(E=>E.id===g);if(!h||h.status!=="error")return;let v=h._failedAt||"create",b=h._storageKey&&h.itemId?{storageKey:h._storageKey,uploadToken:h._uploadToken||"",storageWorkerUrl:h._storageWorkerUrl||"https://fsaos-storage.radns.workers.dev",itemId:h.itemId,itemPath:h.itemPath||""}:void 0;o(g,h.file,h.options,v,b)},[o]),d=(0,ve.useCallback)(g=>{let h=r.current.find(v=>v.id===g);h&&(h._xhr&&h._xhr.abort(),s(g,{status:"error",error:"Cancelled",_xhr:null,_failedAt:null}))},[s]),p=(0,ve.useCallback)(g=>{t(h=>h.filter(v=>v.id!==g))},[]),m=(0,ve.useCallback)(()=>{t(g=>g.filter(h=>h.status!=="complete"))},[]),f=e.some(g=>g.status==="creating"||g.status==="uploading"||g.status==="confirming"),y=e.map(({_storageKey:g,_uploadToken:h,_storageWorkerUrl:v,_xhr:b,_failedAt:E,...I})=>I);return{upload:c,uploadMultiple:a,uploads:y,retryUpload:u,cancelUpload:d,removeUpload:p,clearCompleted:m,isUploading:f}}var Bu=X(ae(),1);async function Ni(e,t){return await x("resolve-items",{context_id:e,item_type:t})}function Hu(e,t){return(0,Bu.useSyncExternalStore)(we,ee,ee),$({queryKey:["vfs",H()??"__unscoped__","resolved-items",e??"",t],queryFn:()=>Ni(e,t),enabled:!!(e&&t)})}var Fe=X(ae(),1);function bs(e,t){let n={artifacts:new Map,timeline:[]},r=new Map;function s(o){if(!o.action?.startsWith("artifact_"))return;let a,u=o.name;if(typeof u=="string"&&u.startsWith("{"))try{a=JSON.parse(u)}catch{return}else if(o.artifact_id)a=o;else return;switch(a.type){case"artifact_opened":{let d=Date.now();if(n.artifacts.set(a.artifact_id,{artifact_id:a.artifact_id,surface_type:a.surface_type,tool_id:a.tool_id,tool_name:a.tool_name,target_uri:a.target_uri,status:"streaming",content:"",total_chars:0,delta_count:0,artifact_item_uri:null,evidence_uri:null,meta:a.meta,started_at:d,completed_at:null}),r.has(a.tool_id)){let p=r.get(a.tool_id);n.timeline[p].artifact_ids.push(a.artifact_id)}else{let p=n.timeline.length;n.timeline.push({tool_id:a.tool_id,tool_name:a.tool_name,status:"started",target_uri:a.target_uri,started_at:d,completed_at:null,artifact_ids:[a.artifact_id]}),r.set(a.tool_id,p)}break}case"artifact_delta":{let d=n.artifacts.get(a.artifact_id);d&&(d.content+=a.content_delta,d.total_chars+=a.content_delta.length,d.delta_count+=1,a.target_uri&&!d.target_uri&&(d.target_uri=a.target_uri));break}case"artifact_done":{let d=n.artifacts.get(a.artifact_id);d&&(d.status=a.status,d.total_chars=a.total_chars,d.artifact_item_uri=a.artifact_item_uri,d.evidence_uri=a.evidence_uri,a.target_uri&&(d.target_uri=a.target_uri),(a.status==="completed"||a.status==="failed")&&(d.completed_at=Date.now()));let p=r.get(a.tool_id);if(p!==void 0){let m=n.timeline[p];a.status==="executing"?m.status="executing":a.status==="completed"?(m.status="completed",m.completed_at=Date.now()):a.status==="failed"&&(m.status="failed",m.completed_at=Date.now()),a.target_uri&&!m.target_uri&&(m.target_uri=a.target_uri)}break}}t(n)}return zr(e,s)}function Gu(e,t=!0){let[n,r]=(0,Fe.useState)(new Map),[s,i]=(0,Fe.useState)([]),o=(0,Fe.useRef)({artifacts:new Map,timeline:[]});(0,Fe.useEffect)(()=>!e||!t?void 0:bs(e,p=>{o.current=p,r(new Map(p.artifacts)),i([...p.timeline])}),[e,t]);let c=(0,Fe.useCallback)(()=>{r(new Map),i([]),o.current={artifacts:new Map,timeline:[]}},[]),a=Array.from(n.values()).find(d=>d.surface_type==="file_editor"&&d.status==="streaming")??null,u=Array.from(n.values()).filter(d=>d.surface_type==="activity"&&(d.status==="streaming"||d.status==="executing"));return{artifacts:n,timeline:s,activeEditor:a,activeActivities:u,reset:c}}function zu(e,t=!0){let[n,r]=(0,Fe.useState)([]);(0,Fe.useEffect)(()=>!e||!t?void 0:bs(e,o=>{r([...o.timeline])}),[e,t]);let s=n.length>0?n[n.length-1]:null;return{timeline:n,latestActivity:s}}var ws=X(ae(),1);function Cd(e,t,n,r){return["vfs","timeline-history",e,t??"__all__",n??500,r??0]}async function Ki(e,t){let n=`${e}/datasets/agent-events`,r=t?.limit??500,s=t?.offset??0,i={limit:r,offset:s,sort:[{key:"seq",direction:"asc"}]};t?.turnId&&(i.filters=[{key:"turn_id",operator:"eq",value:t.turnId}]);try{let c=(await x("open",{path:n,mode:"extract",strategy:"rows",arguments:i}))?.content;return c?(c.rows??c.items??c.data??[]).map(Td).sort((u,d)=>u.seq-d.seq):[]}catch(o){if(o?.status===404||o?.message?.includes("not found"))return[];throw o}}function Ju(e,t){let{turnId:n,limit:r=500,offset:s=0,enabled:i=!0,debounceMs:o=300}=t??{},c=e?`${e}/datasets/agent-events`:null,a=L(),u=(0,ws.useRef)(null),d=c?Cd(c,n,r,s):["vfs","timeline-history","__disabled__"],p=$({queryKey:d,queryFn:()=>Ki(e,{turnId:n,limit:r,offset:s}),enabled:!!e&&i});return(0,ws.useEffect)(()=>{if(!c||!i)return;let m=re("vfs_change",()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{a.invalidateQueries({queryKey:d})},o)},f=>{let y=f?.path;return y?y===c&&f.item_type==="dataset":!1});return()=>{m(),u.current&&clearTimeout(u.current)}},[c,i,o,a,JSON.stringify(d)]),{events:p.data??[],isLoading:p.isLoading,error:p.error,isFetching:p.isFetching,refetch:()=>{p.refetch()}}}function Td(e){return{turn_id:String(e.turn_id??""),seq:Number(e.seq??0),kind:String(e.kind??""),status:String(e.status??""),title:String(e.title??""),tool_name:e.tool_name!=null?String(e.tool_name):void 0,tool_id:e.tool_id!=null?String(e.tool_id):void 0,evidence_uri:e.evidence_uri!=null?String(e.evidence_uri):void 0,artifact_item_uri:e.artifact_item_uri!=null?String(e.artifact_item_uri):void 0,preview:e.preview!=null?String(e.preview):void 0,duration_ms:e.duration_ms!=null?Number(e.duration_ms):void 0,started_at:String(e.started_at??""),completed_at:e.completed_at!=null?String(e.completed_at):void 0,error_type:e.error_type!=null?String(e.error_type):void 0,meta:e.meta!=null?e.meta:void 0}}var Ss=X(ae(),1);function Yu(){(0,Ss.useSyncExternalStore)(we,ee,ee);let e=H(),t=ye(),n=In(e?{key:"pinned",...t?{scope_id:t.id}:{}}:null),r=L(),s=n.resolvedChildren,i=!!(!n.error&&n.arrangement?.item_id&&n.resolutionLevel==="member"&&n.arrangement.write_target_id===n.arrangement.item_id),o=Z({mutationFn:async a=>{let u,d={_scope_path:a.scopePath};if(a.operation==="pin"?u=await x("create",{...d,parent_id:a.arrangementId,name:`pin-${a.target.id}`,item_type:"symlink",type_data:{target_item_id:a.target.id,target_type:a.target.item_type}}):a.operation==="unpin"?u=await x("delete",{...d,id:a.entry.id}):u=await x("update",{...d,id:a.arrangementId,type_data:{order:a.ids}}),u?.success===!1)throw new Error(u.error||"Pins could not be saved");return u},onSettled:(a,u,d)=>Ze(r,d.queryKey)}),c=(0,Ss.useCallback)(a=>!i||!e||H()!==e?Promise.reject(new Error("Personal pins are not available in this context")):a.operation==="unpin"&&!s.some(u=>u.id===a.entry.id)?Promise.reject(new Error("Pin is outside this arrangement")):a.operation==="reorder"&&(new Set(a.ids).size!==s.length||a.ids.length!==s.length||s.some(u=>!a.ids.includes(u.id)))?Promise.reject(new Error("Order must include each pin exactly once")):a.operation==="pin"&&s.some(u=>u.symlink_type_data?.target_item_id===a.target.id)?Promise.resolve(null):o.mutateAsync({...a,scopePath:e,arrangementId:n.arrangement.item_id,arrangementPath:n.arrangement.item_path,queryKey:n.arrangementQueryKey}),[i,e,s,n.arrangement,n.arrangementQueryKey,o.mutateAsync]);return{entries:s,isLoading:n.isLoading,error:n.error,refetch:n.refetch,ready:i,isSaving:o.isPending,saveError:o.error,isPinned:a=>s.some(u=>u.symlink_type_data?.target_item_id===a),pin:a=>c({operation:"pin",target:a}),unpin:a=>{let u=s.find(d=>d.symlink_type_data?.target_item_id===a||d.id===a);return u?c({operation:"unpin",entry:u}):Promise.resolve(null)},reorder:a=>c({operation:"reorder",ids:a})}}var Rs=X(ae(),1);var vr=(e,t,n)=>["vfs",e,"personal-sections",t,n];function Li(e,t){return e&&e.item_id===t.item_id&&e.version>t.version?e:t}async function ji(e,t,n,r){let s=await x("personal-sections",{...r,context_item_id:t,collection:n,_scope_path:e});if(!s||s.success===!1)throw new Error(s?.message||s?.error||"Sections could not be saved");if(!Array.isArray(s.sections)||s.context_item_id!==t||s.collection!==n)throw new Error("Invalid sections response");return s}async function Xu(e,t){let n=await ji(e.scopePath,e.contextId,e.collection,{operation:"assign",section_id:e.sectionId,target_id:t}),r=O();return r.setQueryData(vr(e.scopePath,e.contextId,e.collection),s=>Li(s,n)),Zu(r,e.scopePath),n}function Zu(e,t){for(let n of e.getQueryCache().getAll())n.queryKey[0]==="vfs"&&n.queryKey[1]===t&&n.queryKey[2]==="personal-sections"&&Ze(e,n.queryKey)}function el(e,t){let n=(0,Rs.useSyncExternalStore)(we,ee,ee),r=H(),s=L(),i=vr(r,e,t),o=$({queryKey:i,enabled:!!r&&!!e,queryFn:()=>ji(r,e,t,{operation:"list"}),staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0,personalSections:!0},structuralSharing:(p,m)=>Li(p,m)}),c=(0,Rs.useRef)(!1),a=Z({mutationFn:async p=>{let m=await ji(p.scope,p.context,p.collection,{...p.change,...p.change.operation.startsWith("reorder")?{expected_version:p.version}:{}});return s.setQueryData(vr(p.scope,p.context,p.collection),f=>Li(f,m)),m},onSettled:(p,m,f)=>Zu(s,f.scope)});async function u(p){if(!r||!e||n!==ee()||H()!==r||!o.data||o.error)throw new Error("Select the Space again before changing sections");if(c.current)throw new Error("A section change is still being saved");c.current=!0;try{return await a.mutateAsync({change:p,scope:r,context:e,collection:t,version:o.data.version})}finally{c.current=!1}}function d(p){if(!r||!e||!o.data?.sections.some(m=>m.id===p))throw new Error("Section is unavailable");return{scopePath:r,contextId:e,collection:t,sectionId:p}}return{sections:o.data?.sections??[],ready:!!o.data&&!o.error,isLoading:o.isLoading,error:o.error,refetch:o.refetch,isSaving:a.isPending,change:u,destination:d,contextKey:`${n}:${r}:${e}:${t}`}}Oc(Vi);return fl(Vi);})();
6
+ ${h??""}
7
+ ${t??""}`,[g,y]=(0,_.useState)(null),m=(0,_.useRef)({key:f,found:null,earlyContentPaths:new Set}),v=g?.key===f?g:null;(0,_.useLayoutEffect)(()=>{m.current={key:f,found:v,earlyContentPaths:new Set}},[f]);let b=$({queryKey:["vfs",p??"__unscoped__","minted-asset",h??"",t??""],queryFn:async()=>{let R=await x("query",{scope_path:p,filters:{[`field.${h}`]:t},limit:1}),F=R.content?.items??R.items??[],N=F[0]?_e(F[0]):null;if(!N)return null;let C=(await cr(N.path)).some(M=>M.item_type==="file"&&!!M.type_data?.file_ref);return{asset:N,hasBytes:C}},enabled:!!(t&&p&&h&&!s),refetchInterval:R=>m.current.key===f&&m.current.found?.hasBytes||R.state.data?.hasBytes?!1:1500});(0,_.useEffect)(()=>{let R=b.data;if(!R||m.current.key!==f)return;let F=m.current.found,N={key:f,itemId:R.asset.id,itemPath:R.asset.path,displayName:typeof R.asset.type_data?.display_name=="string"?R.asset.type_data.display_name:R.asset.name,hasBytes:R.hasBytes||!!(F?.itemId===R.asset.id&&F.hasBytes)};m.current.found=N,y(N)},[b.data,f]);let E=!!(t&&u)&&!s&&!v?.hasBytes;return(0,_.useEffect)(()=>{if(!(!E||!u))return Sn(u,["asset.materialized","content.written"])},[E,u]),(0,_.useEffect)(()=>{if(!E||!t||!u)return;let R=f,F=A=>A?.payload??A,N=A=>{let Q=F(A)?.scope_id??A?.scope_id;return typeof Q=="string"?Q:void 0},S=A=>{let Q=F(A)?.item_path??A?.item_path;return typeof Q=="string"&&Q?Q:void 0},C=(A,k)=>{let Q=k.replace(/\/+$/,"");return A===Q||A.startsWith(`${Q}/`)},M=[re("asset.materialized",A=>{if(m.current.key!==R)return;let k=F(A);if(typeof k?.item_id!="string"||!k.item_id)return;let Q=m.current.found,D=typeof k.item_path=="string"?k.item_path:void 0,le=!!k.has_bytes||!!(D&&Array.from(m.current.earlyContentPaths).some(Re=>C(Re,D)))||!!(Q&&Q.itemId===k.item_id&&Q.hasBytes),H={key:R,itemId:k.item_id,itemPath:D,displayName:typeof k.display_name=="string"?k.display_name:void 0,hasBytes:le};m.current.found=H,y(H)},A=>{let k=N(A);return(!k||k===u)&&F(A)?.origin===t}),re("content.written",A=>{if(m.current.key!==R)return;let k=S(A);if(!k)return;let Q=m.current.found;if(!Q?.itemPath||!C(k,Q.itemPath)){if(m.current.earlyContentPaths.add(k),m.current.earlyContentPaths.size>128){let le=m.current.earlyContentPaths.values().next().value;le&&m.current.earlyContentPaths.delete(le)}return}if(Q.hasBytes)return;let D={...Q,hasBytes:!0};m.current.found=D,y(D)},A=>{let k=N(A);return(!k||k===u)&&!!S(A)})];return()=>M.forEach(A=>A())},[E,t,u,f]),{state:s?"failed":t?v?v.hasBytes?"ready":"materializing":"pending":"idle",itemId:v?.itemId,itemPath:v?.itemPath,displayName:v?.displayName,fallbackUrl:r??void 0,error:s??void 0}}function iu(e,t){let n=O().getDefaultOptions().queries?.retry??1;return typeof n=="function"?n(e,t):n===!0||typeof n=="number"&&e<n}function ou(e,t){let n=(0,An.useSyncExternalStore)(we,ee,ee),r=ye(),s=B(),i=r?.kind==="space",o=In(i&&s?{key:e,scope_id:r.id}:null),a=(0,An.useMemo)(()=>{let f=o.applyTo([...t]);if(e!=="channel-order")return f;let g=new Set(o.order??[]),y=f.filter(v=>!g.has(v.id)),m=v=>Date.parse(v.createdAt??"")||0;return y.sort((v,b)=>m(b)-m(v)),[...y,...f.filter(v=>g.has(v.id))]},[e,t,o.applyTo,o.order]),c=L(),u=(0,An.useRef)(!1),d=!!(i&&!o.error&&o.arrangement?.item_id&&o.resolutionLevel==="member"&&o.arrangement.write_target_id===o.arrangement.item_id),p=Z({mutationFn:async f=>{let g=await x("update",{_scope_path:f.scopePath,id:f.arrangementId,type_data:{order:f.ids}});if(g?.success===!1)throw new Error(g.error||"Order could not be saved");return g},onSettled:(f,g,y)=>Ze(c,y.queryKey)});async function h(f){if(!d||!s||n!==ee()||B()!==s)throw new Error("Personal order is not available in this Space");if(u.current)throw new Error("An order change is already being saved");let g=t.map(R=>R.id);if(f.length!==g.length||new Set(f).size!==g.length||g.some(R=>!f.includes(R)))throw new Error("Order must include each displayed item exactly once");let y=c.getQueryData(o.arrangementQueryKey);if(y?.item_id!==o.arrangement.item_id||JSON.stringify(y?.type_data?.order??[])!==JSON.stringify(o.order??[]))throw new Error("The saved order changed. Try dragging again");let m=a.map(R=>R.id);if(f.every((R,F)=>m[F]===R))return;let v=new Set(g),b=0,I=[...(o.order??[]).map(R=>v.has(R)?f[b++]:R),...f.slice(b)];u.current=!0;try{return await p.mutateAsync({ids:I,scopePath:s,arrangementId:o.arrangement.item_id,queryKey:o.arrangementQueryKey})}finally{u.current=!1}}return{items:a,ready:d,supported:i,contextKey:`${n}:${s}:${e}`,isLoading:i&&o.isLoading,error:o.error,refetch:o.refetch,isSaving:p.isPending,saveError:p.error,reorder:h}}var Ei=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,ld=/^[A-Za-z_:][A-Za-z0-9_:.-]{0,127}$/,au=new Map,cu=new Map,kn=class extends Error{constructor(n,r,s,i){super(n);te(this,"code");te(this,"status");te(this,"eventId");this.name="InteractionTrackingError",this.code=r,this.status=s,this.eventId=i}};function Ut(e){let t=e?At.find(n=>n.id===e):At.find(n=>n.default===!0)??(At.length===1?At[0]:void 0);if(!t)throw new TypeError("No unambiguous source is declared for this release");if(!t.id||!Number.isInteger(t.version)||t.version<1)throw new TypeError("The release source declaration is invalid");return t}function ys(e,t){let n=t.adapters?.find(r=>r.type===e);if(!n)throw new TypeError(`The source does not declare a ${e} adapter`);return n}function dd(e){return e.length>0&&e.length<=128&&!/[\u0000-\u001f\u007f]/.test(e)}function fd(e,t){if(!dd(t)||!e.observations?.includes(t))throw new TypeError("The observation is not declared by this release source")}function Ii(e){if(!(typeof window>"u"||e.storage==="memory"))try{return e.storage==="session"?window.sessionStorage:window.localStorage}catch{return}}function pd(e){try{let t=Ii(e)?.getItem(e.key)??void 0;return t&&Ei.test(t)?t:void 0}catch{return}}function uu(e,t){try{Ii(e)?.setItem(e.key,t)}catch{}}function lu(e){let t=e.identity?.visitor;if(!t?.key)throw new TypeError("The source visitor identity policy is invalid");let n=pd(t)??au.get(e.id);if(n)return n;let r=crypto.randomUUID();return au.set(e.id,r),uu(t,r),r}function du(e,t=Date.now()){let n=e.identity?.session;if(!n?.key||!Number.isInteger(n.idle_seconds)||n.idle_seconds<1)throw new TypeError("The source session identity policy is invalid");let r;try{let u=Ii(n)?.getItem(n.key);r=u?JSON.parse(u):void 0}catch{r=void 0}let s=cu.get(e.id),i=r&&typeof r.id=="string"&&Ei.test(r.id)&&typeof r.lastSeenAt=="number"?{id:r.id,lastSeenAt:r.lastSeenAt}:s,o=n.idle_seconds*1e3,c=i&&t-i.lastSeenAt>=0&&t-i.lastSeenAt<o?{id:i.id,lastSeenAt:t}:{id:crypto.randomUUID(),lastSeenAt:t};return cu.set(e.id,c),uu(n,JSON.stringify(c)),c.id}function md(e,t){let n=e.source_keys?.query;if(!Array.isArray(n)||n.length===0)return;let r;try{r=new URL(t)}catch{return}let s=e.source_keys?.max_value_length,i=Number.isInteger(s)?Math.min(Math.max(s??1,1),4096):512,o=Object.fromEntries(n.flatMap(a=>{if(typeof a!="string"||a.length===0||a.length>128)return[];let c=r.searchParams.get(a);return c?[[a,c.slice(0,i)]]:[]}));return Object.keys(o).length>0?o:void 0}async function Nt(e,t={},n={}){let r=Ut(n.source);if(fd(r,e),!t||typeof t!="object"||Array.isArray(t))throw new TypeError("properties must be an object");let s=n.eventId??crypto.randomUUID(),i=n.visitorId??lu(r),o=n.sessionId??du(r);if(![s,i,o].every(m=>Ei.test(m)))throw new TypeError("event, visitor, and session IDs must be UUIDs");let a=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!a)throw new TypeError("pageUrl is required outside a browser");let c=n.occurredAt??new Date().toISOString();if(Number.isNaN(Date.parse(c)))throw new TypeError("occurredAt is invalid");let u=n.referrer??(typeof document<"u"&&document.referrer||void 0),d=md(r,a),p=d?{...t,source_keys:d}:t,h=Ot(),f=`${Te.replace(/\/+$/,"")}/d/${encodeURIComponent(h)}/interactions`,g;try{g=await fetch(f,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({source:r.id,page_url:a,visitor_id:i,session_id:o,referrer:u,events:[{id:s,event_type:e,occurred_at:c,properties:p}]}),signal:n.signal,credentials:"omit",keepalive:n.keepalive??!1})}catch(m){throw new kn(m instanceof Error?m.message:"Observation transport network error","OBSERVATION_NETWORK_ERROR",0,s)}let y=null;try{y=await g.json()}catch{}if(!g.ok||y?.success!==!0){let m=y;throw new kn(m?.message||m?.error||`Observation transport failed (${g.status})`,m?.error||"OBSERVATION_TRANSPORT_FAILED",g.status,s)}return y}function fu(e={},t={}){let n=Ut(t.source),r=ys("page_view",n),s=typeof document>"u"||!r.title_property?{}:{[r.title_property]:document.title.slice(0,512)};return Nt(r.observation,{...s,...e},{...t,source:n.id})}function pu(e,t={},n={}){if(!e||e.length>128)throw new TypeError("actionId is invalid");let r=Ut(n.source),s=ys("declared_action",r),i=s.id_property?{[s.id_property]:e}:{};return Nt(s.observation,{...t,...i},{...n,source:r.id})}function mu(){try{let e=Ut();return ys("form_receipt",e),{visitor_id:lu(e),session_id:du(e),source:e.id}}catch{return}}function hd(e,t={}){let n=Ut(t.source),r=ys("form_receipt",n);return Nt(r.observation,e,{...t,source:n.id})}async function gd(e,t){let r=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${e}\0${t}`))).slice(0,16);r[6]=r[6]&15|80,r[8]=r[8]&63|128;let s=Array.from(r,i=>i.toString(16).padStart(2,"0")).join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}async function hu(e,t,n,r,s){let i=At.filter(o=>o.adapters?.some(a=>a.type==="form_receipt"));await Promise.allSettled(i.map(async o=>{let a=o.id===r?.source;return hd(e,{source:o.id,eventId:a?t:await gd(t,o.id),pageUrl:n,signal:s,keepalive:!0,...a?{visitorId:r.visitor_id,sessionId:r.session_id}:{}})}))}var gr;function _s(e={}){if(typeof window>"u"||typeof document>"u")return()=>{};if(gr)return gr;if(window.__FSAOS_CONFIG__?.tracking?.enabled===!1)return()=>{};let t;try{t=e.source?[Ut(e.source)]:At.map(h=>Ut(h.id))}catch{return()=>{}}if(t.length===0)return()=>{};let n=e.pageViews===!1?[]:t.flatMap(h=>h.adapters.filter(f=>f.type==="page_view").map(f=>({source:h,adapter:f}))),r=e.declaredActions===!1?[]:t.flatMap(h=>h.adapters.filter(f=>f.type==="declared_action").map(f=>({source:h,adapter:f}))),s="",i=()=>{if(window.location.href!==s){s=window.location.href;for(let{source:h,adapter:f}of n){let g=f.title_property?{[f.title_property]:document.title.slice(0,512)}:{};Nt(f.observation,g,{source:h.id,keepalive:!0}).catch(()=>{})}}},o=h=>{if(h.target instanceof Element)for(let{source:f,adapter:g}of r){let y=g.attribute;if(!y||!ld.test(y))continue;let m=h.target.closest(`[${y}]`);if(!m)continue;let v=m.getAttribute(y)?.trim();if(!v||v.length>128)continue;let b={};g.id_property&&(b[g.id_property]=v),g.element_property&&(b[g.element_property]=m.tagName.toLowerCase()),Nt(g.observation,b,{source:f.id,keepalive:!0}).catch(()=>{})}},a=window.history.pushState,c=window.history.replaceState,u=()=>queueMicrotask(i),d=n.some(({adapter:h})=>h.history===!0),p=n.some(({adapter:h})=>h.pageshow===!0);return d&&(window.history.pushState=function(...f){a.apply(this,f),u()},window.history.replaceState=function(...f){c.apply(this,f),u()},window.addEventListener("popstate",i)),p&&window.addEventListener("pageshow",i),r.length>0&&document.addEventListener("click",o,{capture:!0}),n.length>0&&queueMicrotask(i),gr=()=>{window.removeEventListener("popstate",i),window.removeEventListener("pageshow",i),document.removeEventListener("click",o,{capture:!0}),d&&(window.history.pushState=a,window.history.replaceState=c),gr=void 0},gr}var Mn;ne(()=>{Mn=void 0});function vs(e){if(Mn)return Mn.accountPath!==e.accountPath?Promise.reject(new Error("Reset the session before changing accounts")):Mn.promise;let t=ie(),n=()=>{if(t!==ie())throw new Error("Workspace session changed")},r=(async()=>{let s=await Xe();if(n(),!s.principal_id)throw new Error("Workspace initialization requires an authenticated principal");let i=await O().fetchQuery({queryKey:P.memberships(s.principal_id),queryFn:cs,staleTime:12e4,retry:!1});n();let o=i.find(p=>p.path===e.accountPath&&p.isAccount&&!p.isSpace);if(!o)throw new Error("Authenticated account membership is unavailable");let a=i.find(p=>p.isSpace&&p.accountId===o.personalSpaceId&&p.path===o.personalSpacePath);if(!a||!o.personalSpacePath)throw new Error("A provisioned default Space membership is required");let c=Ve(o),u=Ve(a),d=fe();if(d&&d.id!==c.id)throw new Error("Reset the session before changing accounts");return d||Mt(c,{activate:!1}),await Dt(o.personalSpacePath,p=>{let h=i.find(f=>f.accountId===p&&(f.isAccount||f.isSpace));return h?Ve(h):null},{initialAnchor:u}),n(),{home:c,defaultSpace:u,memberships:i}})().catch(s=>{throw t===ie()&&(Mn=void 0),s});return Mn={accountPath:e.accountPath,promise:r},r}var Kt,_r,yr;ne(()=>{_r?.(),_r=void 0,Kt=void 0,yr=void 0});function gu(e={}){if(Kt)return e.workspace&&e.workspace.accountPath!==yr?Promise.reject(new Error("Initialize workspace through initializeWorkspace, or dispose the existing runtime first")):Kt;yr=e.workspace?.accountPath;let t=ie();return Kt=(async()=>{let n=e.tracking??!0,r=n===!1?()=>{}:_s(typeof n=="object"?n:{});_r=r;try{let s=e.session===!1?null:await Xe(),i=e.workspace?await vs(e.workspace):void 0;if(t!==ie())throw new Error("Session changed during initialization");let o=!1;return{session:s,workspace:i,dispose(){o||(o=!0,r(),t===ie()&&(Kt=void 0,yr=void 0,_r=void 0))}}}catch(s){throw r(),t===ie()&&(Kt=void 0,yr=void 0,_r=void 0),s}})(),Kt}async function Ai(e){try{return await x("execution-control-transition",e)}catch(t){if(!(t instanceof Ae)||t.status<500)throw t;return await new Promise(n=>setTimeout(n,250)),x("execution-control-transition",e)}}function ki(e){let t=e.conversation_anchor_item_id??e.conversation_root_id;return t?{...e,conversation_anchor_item_id:t,conversation_root_id:e.conversation_root_id??t}:e}async function yu(e,t={}){let n=e.trim();if(!n)throw new TypeError("cancelTurn requires a request message id");let r=(t.idempotencyKey??`cancel:${n}`).trim();if(!r)throw new TypeError("cancelTurn requires a non-empty idempotency key");if(r.length>128)throw new TypeError("cancelTurn idempotency key must be 128 characters or fewer");let s=await Ai({op:"request",command:"cancel",delivery:"immediate",request_message_id:n,idempotency_key:r,...t.scopePath?{_scope_path:t.scopePath}:{}}),i=s.outcome??s.state??s.status;return ki(i?{...s,state:i}:s)}async function _u(e,t,n={}){let r=e.trim(),s=t.trim();if(!r)throw new TypeError("steerTurn requires an active request message id");if(!s)throw new TypeError("steerTurn requires a selected queue entry id");if(r===s)throw new TypeError("steerTurn cannot target the active request message");let i=(n.idempotencyKey??`steer:${r}:${s}`).trim();if(!i)throw new TypeError("steerTurn requires a non-empty idempotency key");if(i.length>128)throw new TypeError("steerTurn idempotency key must be 128 characters or fewer");let o=await Ai({op:"request",command:"steer",delivery:"immediate",request_message_id:r,selected_queue_entry_id:s,idempotency_key:i,...n.scopePath?{_scope_path:n.scopePath}:{}}),a=o.outcome??o.state??o.status;return ki(a?{...o,state:a}:o)}async function vu(e,t={}){let n=e.trim();if(!n)throw new TypeError("cancelQueuedTurn requires a queue entry id");let r=(t.idempotencyKey??`cancel-queue:${n}`).trim();if(!r)throw new TypeError("cancelQueuedTurn requires a non-empty idempotency key");if(r.length>128)throw new TypeError("cancelQueuedTurn idempotency key must be 128 characters or fewer");let s=await Ai({op:"cancel_queue_entry",queue_entry_id:n,idempotency_key:r,...t.scopePath?{_scope_path:t.scopePath}:{}}),i=s.outcome??s.state??s.status;return ki(i?{...s,outcome:i}:s)}var yd=/^[a-z][a-z0-9_-]{0,63}$/,_d=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,On=class extends Error{constructor(n,r,s,i){super(n);te(this,"code");te(this,"status");te(this,"fillId");this.name="FormSubmissionError",this.code=r,this.status=s,this.fillId=i}};async function bu(e,t,n={}){if(!yd.test(e))throw new TypeError("capabilityId is invalid");if(!t||typeof t!="object"||Array.isArray(t))throw new TypeError("fields must be an object");let r=n.fillId??crypto.randomUUID();if(!_d.test(r))throw new TypeError("fillId must be a UUID");let s=Ot(),i=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!i)throw new TypeError("pageUrl is required outside a browser");let o=`${Te.replace(/\/+$/,"")}/d/${encodeURIComponent(s)}/actions/${encodeURIComponent(e)}`,a=mu(),c=a?{visitor_id:a.visitor_id,session_id:a.session_id}:void 0,u;try{u=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({fill_id:r,page_url:i,fields:t,...c?{attribution:c}:{}}),signal:n.signal,credentials:"omit"})}catch(p){throw new On(p instanceof Error?p.message:"Form submission network error","FORM_NETWORK_ERROR",0,r)}let d=null;try{d=await u.json()}catch{}if(!u.ok||d?.success!==!0){let p=d;throw new On(p?.message||p?.error||`Form submission failed (${u.status})`,p?.error||"FORM_SUBMISSION_FAILED",u.status,r)}return await hu({fill_id:r,action_id:e,release_id:d.release_id},r,i,a,n.signal),d}var Mi=X(ae(),1),Ru=X(Su(),1);function xu(e){return x("read",{path:e})}function Pu(e,t){return x("list",{path:e,...t})}function Cu(e){return x("create",e)}function Tu(e){return x("update",e)}function Eu(e){return x("create",e)}function Iu(e,t){let r=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return x("tools/call",{name:e,instance_path:r,...t||{}})}function Au(e,t,n){return x("signal",{target_id:e,event_name:t,payload:n||{}})}function ku(e){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+e}var Mu={signIn:e=>e.provider?W.auth.signInWithOAuth({provider:e.provider,options:{redirectTo:e.redirectTo||window.location.href}}):W.auth.signInWithPassword({email:e.email,password:e.password}),signUp:e=>W.auth.signUp({email:e.email,password:e.password,options:{data:e.metadata||{}}}),signOut:async()=>{await W.auth.signOut(),mn(),O().clear()},getSession:()=>W.auth.getSession().then(e=>e.data.session),getUser:()=>W.auth.getUser().then(e=>e.data.user),onAuthStateChange:e=>{let{data:{subscription:t}}=W.auth.onAuthStateChange((n,r)=>{e({event:n,session:r,user:r?.user??null})});return()=>t?.unsubscribe()},resetPassword:e=>W.auth.resetPasswordForEmail(e),signInWithMagicLink:(e,t)=>W.auth.signInWithOtp({email:e,options:{emailRedirectTo:t||window.location.href}})};function Ou(){let e=document.getElementById("root");if(e)try{let t=window.__FSAOS_COMPONENT__;if(!t){e.innerHTML='<div style="padding:2rem;color:#ef4444;font-family:system-ui"><h2>Component Error</h2><pre>No component found. The bundle may have failed to load.</pre></div>';return}let n=t.default||t,r=window.__FSAOS_ITEM_DATA__||null,s=r?{item:r,...r}:{};(0,Ru.createRoot)(e).render((0,Mi.createElement)(Gn,{client:O()},(0,Mi.createElement)(n,s)))}catch(t){console.error("[FSAOS] Failed to mount root component:",t),e.innerHTML='<div style="padding:2rem;color:#ef4444;font-family:system-ui"><h2>Component Error</h2><pre>'+(t.message||t)+"</pre></div>"}}function Fu(){let e=window.React,t=window.ReactDOM,n=window.__FSAOS_GATEWAY__,r=window.__FSAOS_UI__;if(!n){console.error("[FSAOS] Cannot set up require shim: __FSAOS_GATEWAY__ not found");return}let s={react:e,"react-dom":t,"react-dom/client":t,"react/jsx-runtime":{jsx:e?.createElement,jsxs:e?.createElement,Fragment:e?.Fragment},"@fsaos/kernel":n,"@fsaos/react":n,"@fsaos/gateway":n,"@fsaos/ui":r||{}};window.require=function(o){if(s[o])return s[o];throw new Error("[FSAOS] Module not found: "+o)},window.__FSAOS_MOUNT__=n.mount}function Oi(e){return x("invite-member",e)}function Fi(e){return x("accept-invite",e)}function qi(e){let t={};return e.role&&(t.role=e.role),x("link",{source_id:e.chat_id,target_id:e.member_id,edge_type:"has_member",context:t})}function Qi(e){return x("create-agent",e)}function Di(e){return!e.input_request_id&&!e.input_request?Promise.reject(new Error("answerInput needs input_request_id or the input_request object read from the step.")):x("todo-control",{action:"answer_input",...e})}function qu(){return Z({mutationFn:Oi})}function Qu(){let e=L();return Z({mutationFn:Fi,onSuccess:()=>{e.invalidateQueries({queryKey:["memberships"]})}})}function Du(){let e=L();return Z({mutationFn:qi,onSuccess:(t,n)=>{e.invalidateQueries({queryKey:P.edges(n.chat_id)}),e.invalidateQueries({queryKey:P.edges(n.member_id)})}})}function Uu(){let e=L();return Z({mutationFn:Qi,onSuccess:()=>{e.invalidateQueries({queryKey:["memberships"]})}})}function Nu(){let e=L();return Z({mutationFn:Di,onSuccess:(t,n)=>{e.invalidateQueries({queryKey:P.itemById(n.step_id)})}})}function vd(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function bd(e,t){return t&&t.length>0?"select":e==="boolean"?"toggle":e==="integer"||e==="number"?"range":e==="string"?"text":"none"}function wd(e,t){return!(e==="object"||e==="array")}function Sd(e){return["string","number","integer","boolean"].includes(e)}function Rd(e){return e!=="object"&&e!=="array"}function Ku(e,t,n,r){let s=e?.properties;if(!s||typeof s!="object")return[];let i=[];for(let[o,a]of Object.entries(s)){let c=a.type||"string",u=a.enum,d=wd(c,u),p=Sd(c),h=bd(c,u);i.push({key:o,label:a.title||vd(o),type:c,description:a.description,enum_values:u,default_value:n[o]??r[o]??a.default,editable:t,filterable:d,sortable:p,filter_widget:h})}return i}function Ui(e){let t=e.default_data||{},n=e.field_defaults||{},r=Ku(e.input_schema,!0,t,n),s=Ku(e.system_schema,!1,t,n),i=[...r,...s],o=i.filter(u=>Rd(u.type)),a=i.filter(u=>u.filterable),c=i.filter(u=>u.sortable);return{fields:i,columns:o,filterable:a,sortable:c,form_fields:r,system_fields:s}}function Lu(e){return{field:"updated_at",direction:"desc"}}function ju(e){let t=Ui(e),n=new Set(e.input_schema?.required||[]);return t.form_fields.filter(r=>n.has(r.key)||r.default_value===void 0)}var ve=X(ae(),1);var xd=0;function Pd(){return`upload_${Date.now()}_${++xd}`}async function Vu(e,t,n,r){let s=t.name||(e instanceof File?e.name:`file-${Date.now()}`),i=e.type||"application/octet-stream",o=t.itemType||"file",a={parent_path:t.parentPath,item_type:o,name:s,type_data:{...t.typeData||{},file_source:{type:"upload",content_type:i}}};t.cardParentPath&&(a.card_parent_path=t.cardParentPath);let u=await x("create",a);if(!u.id)throw new Error(u.error||u.message||"Failed to create file item");let d=u.id,p=u.path;if(u.storage_completed&&u.file_ref)return{itemId:d,itemPath:p,fileRef:u.file_ref};let h=u.storage_key,f=u.upload_token,g=u.storage_worker_url||"https://fsaos-storage.radns.workers.dev";if(!h)throw new Error("Gateway returned no storage_key \u2014 file_source may not be supported for this item type");await Cd(g,h,f,e,i,n,r);let y=await $u(d,h,i);return{itemId:d,itemPath:p,fileRef:y}}function Cd(e,t,n,r,s,i,o){return new Promise((a,c)=>{let u=new XMLHttpRequest;if(u.open("PUT",`${e}/upload`),u.setRequestHeader("X-Storage-Key",t),u.setRequestHeader("Content-Type",s),n&&u.setRequestHeader("X-Upload-Token",n),u.upload.onprogress=d=>{d.lengthComputable&&i&&i(Math.round(d.loaded/d.total*100))},u.onload=()=>{u.status>=200&&u.status<300?a():c(new Error(`Storage upload failed: HTTP ${u.status} \u2014 ${u.responseText?.slice(0,300)}`))},u.onerror=()=>c(new Error("Storage upload network error")),u.ontimeout=()=>c(new Error("Storage upload timed out")),o){if(o.aborted){c(new Error("Upload cancelled"));return}o.addEventListener("abort",()=>{u.abort(),c(new Error("Upload cancelled"))})}u.send(r)})}async function $u(e,t,n){let r=await Ye(),s=await fetch(`${Te}/storage/upload-complete`,{method:"POST",headers:{"Content-Type":"application/json",...r?{Authorization:`Bearer ${r}`}:{}},body:JSON.stringify({item_id:e,storage_key:t,content_type:n})});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Upload confirmation failed: HTTP ${s.status} \u2014 ${o.slice(0,300)}`)}let i=await s.json();if(!i.success)throw new Error(i.error||i.message||"Upload confirmation rejected");return i.file_ref}function Wu(){let[e,t]=(0,ve.useState)([]),n=L(),r=(0,ve.useRef)(e);r.current=e;let s=(0,ve.useCallback)((y,m)=>{t(v=>v.map(b=>b.id===y?{...b,...m}:b))},[]),i=(0,ve.useCallback)(y=>{t(m=>[...m,y])},[]),o=(0,ve.useCallback)(async(y,m,v,b,E)=>{let I=v.name||m.name,R=m.type||"application/octet-stream",F=v.itemType||"file",N=E?.itemId||null,S=E?.itemPath||null,C=E?.storageKey||null,M=E?.uploadToken||null,A=E?.storageWorkerUrl||null;try{if(!b||b==="create"){s(y,{status:"creating",error:null,_failedAt:null});let D=await x("create",{parent_path:v.parentPath,item_type:F,name:I,type_data:{...v.typeData||{},file_source:{type:"upload",content_type:R}}});if(!D.id)throw Object.assign(new Error(D.error||D.message||"Failed to create file item"),{_step:"create"});if(N=D.id,S=D.path,s(y,{itemId:N,itemPath:S}),D.storage_completed&&D.file_ref){s(y,{status:"complete",progress:100,fileRef:D.file_ref}),n.invalidateQueries({queryKey:P.children(v.parentPath)});return}if(C=D.storage_key,M=D.upload_token||"",A=D.storage_worker_url||"https://fsaos-storage.radns.workers.dev",s(y,{_storageKey:C,_uploadToken:M,_storageWorkerUrl:A}),!C)throw Object.assign(new Error("Gateway returned no storage_key"),{_step:"create"})}(!b||b==="create"||b==="upload")&&(s(y,{status:"uploading",progress:0,error:null,_failedAt:null}),await new Promise((D,le)=>{let H=new XMLHttpRequest;s(y,{_xhr:H}),H.open("PUT",`${A}/upload`),H.setRequestHeader("X-Storage-Key",C),H.setRequestHeader("Content-Type",R),M&&H.setRequestHeader("X-Upload-Token",M),H.upload.onprogress=Re=>{Re.lengthComputable&&s(y,{progress:Math.round(Re.loaded/Re.total*100)})},H.onload=()=>{H.status>=200&&H.status<300?D():le(Object.assign(new Error(`Storage upload failed: HTTP ${H.status}`),{_step:"upload"}))},H.onerror=()=>le(Object.assign(new Error("Storage upload network error"),{_step:"upload"})),H.ontimeout=()=>le(Object.assign(new Error("Storage upload timed out"),{_step:"upload"})),H.send(m)}),s(y,{progress:100,_xhr:null})),s(y,{status:"confirming",error:null,_failedAt:null});let k=await $u(N,C,R);s(y,{status:"complete",fileRef:k}),n.invalidateQueries({queryKey:P.children(v.parentPath)})}catch(k){let Q=k?.message||String(k),D=k?._step||"create";s(y,{status:"error",error:Q,_failedAt:D,_xhr:null})}},[s,n]),a=(0,ve.useCallback)((y,m)=>{let v=Pd();i({id:v,file:y,status:"creating",progress:0,error:null,itemId:null,itemPath:null,fileRef:null,options:m,_storageKey:null,_uploadToken:null,_storageWorkerUrl:null,_xhr:null,_failedAt:null}),o(v,y,m)},[i,o]),c=(0,ve.useCallback)((y,m)=>{for(let v of y)a(v,m)},[a]),u=(0,ve.useCallback)(y=>{let m=r.current.find(E=>E.id===y);if(!m||m.status!=="error")return;let v=m._failedAt||"create",b=m._storageKey&&m.itemId?{storageKey:m._storageKey,uploadToken:m._uploadToken||"",storageWorkerUrl:m._storageWorkerUrl||"https://fsaos-storage.radns.workers.dev",itemId:m.itemId,itemPath:m.itemPath||""}:void 0;o(y,m.file,m.options,v,b)},[o]),d=(0,ve.useCallback)(y=>{let m=r.current.find(v=>v.id===y);m&&(m._xhr&&m._xhr.abort(),s(y,{status:"error",error:"Cancelled",_xhr:null,_failedAt:null}))},[s]),p=(0,ve.useCallback)(y=>{t(m=>m.filter(v=>v.id!==y))},[]),h=(0,ve.useCallback)(()=>{t(y=>y.filter(m=>m.status!=="complete"))},[]),f=e.some(y=>y.status==="creating"||y.status==="uploading"||y.status==="confirming"),g=e.map(({_storageKey:y,_uploadToken:m,_storageWorkerUrl:v,_xhr:b,_failedAt:E,...I})=>I);return{upload:a,uploadMultiple:c,uploads:g,retryUpload:u,cancelUpload:d,removeUpload:p,clearCompleted:h,isUploading:f}}var Bu=X(ae(),1);async function Ni(e,t){return await x("resolve-items",{context_id:e,item_type:t})}function Hu(e,t){return(0,Bu.useSyncExternalStore)(we,ee,ee),$({queryKey:["vfs",B()??"__unscoped__","resolved-items",e??"",t],queryFn:()=>Ni(e,t),enabled:!!(e&&t)})}var qe=X(ae(),1);function bs(e,t){let n={artifacts:new Map,timeline:[]},r=new Map;function s(o){if(!o.action?.startsWith("artifact_"))return;let c,u=o.name;if(typeof u=="string"&&u.startsWith("{"))try{c=JSON.parse(u)}catch{return}else if(o.artifact_id)c=o;else return;switch(c.type){case"artifact_opened":{let d=Date.now();if(n.artifacts.set(c.artifact_id,{artifact_id:c.artifact_id,surface_type:c.surface_type,tool_id:c.tool_id,tool_name:c.tool_name,target_uri:c.target_uri,status:"streaming",content:"",total_chars:0,delta_count:0,artifact_item_uri:null,evidence_uri:null,meta:c.meta,started_at:d,completed_at:null}),r.has(c.tool_id)){let p=r.get(c.tool_id);n.timeline[p].artifact_ids.push(c.artifact_id)}else{let p=n.timeline.length;n.timeline.push({tool_id:c.tool_id,tool_name:c.tool_name,status:"started",target_uri:c.target_uri,started_at:d,completed_at:null,artifact_ids:[c.artifact_id]}),r.set(c.tool_id,p)}break}case"artifact_delta":{let d=n.artifacts.get(c.artifact_id);d&&(d.content+=c.content_delta,d.total_chars+=c.content_delta.length,d.delta_count+=1,c.target_uri&&!d.target_uri&&(d.target_uri=c.target_uri));break}case"artifact_done":{let d=n.artifacts.get(c.artifact_id);d&&(d.status=c.status,d.total_chars=c.total_chars,d.artifact_item_uri=c.artifact_item_uri,d.evidence_uri=c.evidence_uri,c.target_uri&&(d.target_uri=c.target_uri),(c.status==="completed"||c.status==="failed")&&(d.completed_at=Date.now()));let p=r.get(c.tool_id);if(p!==void 0){let h=n.timeline[p];c.status==="executing"?h.status="executing":c.status==="completed"?(h.status="completed",h.completed_at=Date.now()):c.status==="failed"&&(h.status="failed",h.completed_at=Date.now()),c.target_uri&&!h.target_uri&&(h.target_uri=c.target_uri)}break}}t(n)}return zr(e,s)}function Gu(e,t=!0){let[n,r]=(0,qe.useState)(new Map),[s,i]=(0,qe.useState)([]),o=(0,qe.useRef)({artifacts:new Map,timeline:[]});(0,qe.useEffect)(()=>!e||!t?void 0:bs(e,p=>{o.current=p,r(new Map(p.artifacts)),i([...p.timeline])}),[e,t]);let a=(0,qe.useCallback)(()=>{r(new Map),i([]),o.current={artifacts:new Map,timeline:[]}},[]),c=Array.from(n.values()).find(d=>d.surface_type==="file_editor"&&d.status==="streaming")??null,u=Array.from(n.values()).filter(d=>d.surface_type==="activity"&&(d.status==="streaming"||d.status==="executing"));return{artifacts:n,timeline:s,activeEditor:c,activeActivities:u,reset:a}}function zu(e,t=!0){let[n,r]=(0,qe.useState)([]);(0,qe.useEffect)(()=>!e||!t?void 0:bs(e,o=>{r([...o.timeline])}),[e,t]);let s=n.length>0?n[n.length-1]:null;return{timeline:n,latestActivity:s}}var ws=X(ae(),1);function Td(e,t,n,r){return["vfs","timeline-history",e,t??"__all__",n??500,r??0]}async function Ki(e,t){let n=`${e}/datasets/agent-events`,r=t?.limit??500,s=t?.offset??0,i={limit:r,offset:s,sort:[{key:"seq",direction:"asc"}]};t?.turnId&&(i.filters=[{key:"turn_id",operator:"eq",value:t.turnId}]);try{let a=(await x("open",{path:n,mode:"extract",strategy:"rows",arguments:i}))?.content;return a?(a.rows??a.items??a.data??[]).map(Ed).sort((u,d)=>u.seq-d.seq):[]}catch(o){if(o?.status===404||o?.message?.includes("not found"))return[];throw o}}function Ju(e,t){let{turnId:n,limit:r=500,offset:s=0,enabled:i=!0,debounceMs:o=300}=t??{},a=e?`${e}/datasets/agent-events`:null,c=L(),u=(0,ws.useRef)(null),d=a?Td(a,n,r,s):["vfs","timeline-history","__disabled__"],p=$({queryKey:d,queryFn:()=>Ki(e,{turnId:n,limit:r,offset:s}),enabled:!!e&&i});return(0,ws.useEffect)(()=>{if(!a||!i)return;let h=re("vfs_change",()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{c.invalidateQueries({queryKey:d})},o)},f=>{let g=f?.path;return g?g===a&&f.item_type==="dataset":!1});return()=>{h(),u.current&&clearTimeout(u.current)}},[a,i,o,c,JSON.stringify(d)]),{events:p.data??[],isLoading:p.isLoading,error:p.error,isFetching:p.isFetching,refetch:()=>{p.refetch()}}}function Ed(e){return{turn_id:String(e.turn_id??""),seq:Number(e.seq??0),kind:String(e.kind??""),status:String(e.status??""),title:String(e.title??""),tool_name:e.tool_name!=null?String(e.tool_name):void 0,tool_id:e.tool_id!=null?String(e.tool_id):void 0,evidence_uri:e.evidence_uri!=null?String(e.evidence_uri):void 0,artifact_item_uri:e.artifact_item_uri!=null?String(e.artifact_item_uri):void 0,preview:e.preview!=null?String(e.preview):void 0,duration_ms:e.duration_ms!=null?Number(e.duration_ms):void 0,started_at:String(e.started_at??""),completed_at:e.completed_at!=null?String(e.completed_at):void 0,error_type:e.error_type!=null?String(e.error_type):void 0,meta:e.meta!=null?e.meta:void 0}}var Ss=X(ae(),1);function Yu(){(0,Ss.useSyncExternalStore)(we,ee,ee);let e=B(),t=ye(),n=In(e?{key:"pinned",...t?{scope_id:t.id}:{}}:null),r=L(),s=n.resolvedChildren,i=!!(!n.error&&n.arrangement?.item_id&&n.resolutionLevel==="member"&&n.arrangement.write_target_id===n.arrangement.item_id),o=Z({mutationFn:async c=>{let u,d={_scope_path:c.scopePath};if(c.operation==="pin"?u=await x("create",{...d,parent_id:c.arrangementId,name:`pin-${c.target.id}`,item_type:"symlink",type_data:{target_item_id:c.target.id,target_type:c.target.item_type}}):c.operation==="unpin"?u=await x("delete",{...d,id:c.entry.id}):u=await x("update",{...d,id:c.arrangementId,type_data:{order:c.ids}}),u?.success===!1)throw new Error(u.error||"Pins could not be saved");return u},onSettled:(c,u,d)=>Ze(r,d.queryKey)}),a=(0,Ss.useCallback)(c=>!i||!e||B()!==e?Promise.reject(new Error("Personal pins are not available in this context")):c.operation==="unpin"&&!s.some(u=>u.id===c.entry.id)?Promise.reject(new Error("Pin is outside this arrangement")):c.operation==="reorder"&&(new Set(c.ids).size!==s.length||c.ids.length!==s.length||s.some(u=>!c.ids.includes(u.id)))?Promise.reject(new Error("Order must include each pin exactly once")):c.operation==="pin"&&s.some(u=>u.symlink_type_data?.target_item_id===c.target.id)?Promise.resolve(null):o.mutateAsync({...c,scopePath:e,arrangementId:n.arrangement.item_id,arrangementPath:n.arrangement.item_path,queryKey:n.arrangementQueryKey}),[i,e,s,n.arrangement,n.arrangementQueryKey,o.mutateAsync]);return{entries:s,isLoading:n.isLoading,error:n.error,refetch:n.refetch,ready:i,isSaving:o.isPending,saveError:o.error,isPinned:c=>s.some(u=>u.symlink_type_data?.target_item_id===c),pin:c=>a({operation:"pin",target:c}),unpin:c=>{let u=s.find(d=>d.symlink_type_data?.target_item_id===c||d.id===c);return u?a({operation:"unpin",entry:u}):Promise.resolve(null)},reorder:c=>a({operation:"reorder",ids:c})}}var Rs=X(ae(),1);var vr=(e,t,n)=>["vfs",e,"personal-sections",t,n];function Li(e,t){return e&&e.item_id===t.item_id&&e.version>t.version?e:t}async function ji(e,t,n,r){let s=await x("personal-sections",{...r,context_item_id:t,collection:n,_scope_path:e});if(!s||s.success===!1)throw new Error(s?.message||s?.error||"Sections could not be saved");if(!Array.isArray(s.sections)||s.context_item_id!==t||s.collection!==n)throw new Error("Invalid sections response");return s}async function Xu(e,t){let n=await ji(e.scopePath,e.contextId,e.collection,{operation:"assign",section_id:e.sectionId,target_id:t}),r=O();return r.setQueryData(vr(e.scopePath,e.contextId,e.collection),s=>Li(s,n)),Zu(r,e.scopePath),n}function Zu(e,t){for(let n of e.getQueryCache().getAll())n.queryKey[0]==="vfs"&&n.queryKey[1]===t&&n.queryKey[2]==="personal-sections"&&Ze(e,n.queryKey)}function el(e,t){let n=(0,Rs.useSyncExternalStore)(we,ee,ee),r=B(),s=L(),i=vr(r,e,t),o=$({queryKey:i,enabled:!!r&&!!e,queryFn:()=>ji(r,e,t,{operation:"list"}),staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0,personalSections:!0},structuralSharing:(p,h)=>Li(p,h)}),a=(0,Rs.useRef)(!1),c=Z({mutationFn:async p=>{let h=await ji(p.scope,p.context,p.collection,{...p.change,...p.change.operation.startsWith("reorder")?{expected_version:p.version}:{}});return s.setQueryData(vr(p.scope,p.context,p.collection),f=>Li(f,h)),h},onSettled:(p,h,f)=>Zu(s,f.scope)});async function u(p){if(!r||!e||n!==ee()||B()!==r||!o.data||o.error)throw new Error("Select the Space again before changing sections");if(a.current)throw new Error("A section change is still being saved");a.current=!0;try{return await c.mutateAsync({change:p,scope:r,context:e,collection:t,version:o.data.version})}finally{a.current=!1}}function d(p){if(!r||!e||!o.data?.sections.some(h=>h.id===p))throw new Error("Section is unavailable");return{scopePath:r,contextId:e,collection:t,sectionId:p}}return{sections:o.data?.sections??[],ready:!!o.data&&!o.error,isLoading:o.isLoading,error:o.error,refetch:o.refetch,isSaving:c.isPending,change:u,destination:d,contextKey:`${n}:${r}:${e}:${t}`}}Oc(Vi);return pl(Vi);})();
8
8
 
9
9
  /* ── Auto-setup: require shim + mount + backward compat globals ── */
10
10
  (function() {