@ai4b-team/fsaos-gateway-sdk 5.1.1 → 5.3.0

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-11-12T14:02:55.642Z */
2
- "use strict";var __FSAOS_GATEWAY__=(()=>{var Pl=Object.create;var Dn=Object.defineProperty;var Cl=Object.getOwnPropertyDescriptor;var Tl=Object.getOwnPropertyNames;var Il=Object.getPrototypeOf,El=Object.prototype.hasOwnProperty;var eo=e=>{throw TypeError(e)};var Al=(e,t,n)=>t in e?Dn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Un=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),to=(e,t)=>{for(var n in t)Dn(e,n,{get:t[n],enumerable:!0})},no=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Tl(t))!El.call(e,s)&&s!==n&&Dn(e,s,{get:()=>t[s],enumerable:!(r=Cl(t,s))||r.enumerable});return e};var z=(e,t,n)=>(n=e!=null?Pl(Il(e)):{},no(t||!e||!e.__esModule?Dn(n,"default",{value:e,enumerable:!0}):n,e)),kl=e=>no(Dn({},"__esModule",{value:!0}),e);var re=(e,t,n)=>Al(e,typeof t!="symbol"?t+"":t,n),Os=(e,t,n)=>t.has(e)||eo("Cannot "+n);var l=(e,t,n)=>(Os(e,t,"read from private field"),n?n.call(e):t.get(e)),I=(e,t,n)=>t.has(e)?eo("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),S=(e,t,n,r)=>(Os(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),F=(e,t,n)=>(Os(e,t,"access private method"),n);var Kn=(e,t,n,r)=>({set _(s){S(e,t,s,n)},get _(){return l(e,t,r)}});var ue=Un((gf,ro)=>{ro.exports=React});var Qr=Un((pm,Do)=>{Do.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var Yo=Un(($m,Jo)=>{Jo.exports={createClient:window.supabase.createClient}});var Pa=Un((rh,Ra)=>{Ra.exports=ReactDOM});var Ku=Un((Yg,Uu)=>{Uu.exports=ReactDOM});var Zi={};to(Zi,{CHANNEL_AI_MODES:()=>uu,ComponentRenderer:()=>iu,EnforcementDeniedError:()=>it,FormSubmissionError:()=>Qn,GatewayRequestError:()=>ke,InteractionTrackingError:()=>qn,KernelProvider:()=>ou,QueryClientProvider:()=>Zn,acceptInvite:()=>Bi,answerInput:()=>Wi,assignPersonalSection:()=>yl,auth:()=>Ju,awaitAnchorReady:()=>sr,awaitScopeReady:()=>ua,callTool:()=>Hu,cancelQueuedTurn:()=>Qu,cancelTurn:()=>qu,clearCachedToken:()=>ai,clearSession:()=>hi,configureGatewayReads:()=>ba,createAgent:()=>Vi,createItem:()=>$u,disconnectSSE:()=>Pi,disposeVfsRealtimeWs:()=>Ti,electHomeAnchor:()=>Nt,emitEvent:()=>Wa,fetchChannelMessages:()=>nc,fetchChannelMessagesPage:()=>gr,fetchChannelMessagesWithCards:()=>ps,fetchEdgesForItem:()=>cs,fetchItemHistory:()=>ds,fetchItemVersions:()=>mr,fetchItems:()=>Kt,fetchMemberFocus:()=>fs,fetchOpenEnvelope:()=>hr,fetchRecentActivity:()=>ls,fetchResolvedItems:()=>Gi,fetchTimelineHistory:()=>zi,fetchTurnQueueEntries:()=>Xa,fetchTypeDefinitions:()=>as,fetchVfsChildren:()=>pr,fetchVfsChildrenPage:()=>os,fetchVfsItem:()=>fr,fetchVfsItemById:()=>dr,fetchVfsTree:()=>us,gatewayCall:()=>P,getAccessToken:()=>Xe,getAnchor:()=>_n,getAnchorRef:()=>_e,getAnchorVersion:()=>li,getAssetUrl:()=>zu,getDefaultSort:()=>il,getHomeAnchor:()=>pe,getMountVersion:()=>ir,getMounts:()=>Ee,getPathSubscriptionState:()=>Ga,getQueryClient:()=>N,getRequiredFormFields:()=>ol,getScope:()=>H,getScopeVersion:()=>te,getServerClockOffsetMs:()=>ma,getServerClockSyncedAt:()=>ha,getSessionEntry:()=>yt,hasServerClock:()=>pa,initSession:()=>et,initVfsRealtimeWs:()=>Lt,initializeFsaos:()=>Fu,initializeWorkspace:()=>Cs,interpretSchema:()=>Hi,invalidateAllVfs:()=>ic,invalidateChannelMessages:()=>ac,invalidateChildren:()=>is,invalidateItem:()=>Ci,invalidateOpenEnvelope:()=>cc,invalidatePathAndParent:()=>rc,invalidateSubtree:()=>sc,invalidateTypes:()=>oc,inviteMember:()=>ji,isAnchorReady:()=>fi,isChannelPath:()=>me,isListableItemsFilter:()=>In,isScopeReady:()=>Vr,itemsFilterFromQueryFilter:()=>ec,listChildren:()=>Bu,loadMounts:()=>jt,loadPublishedBundle:()=>Yc,mount:()=>Yu,mountRealtimeScope:()=>An,normalizeItem:()=>Oe,onConnectionStateChange:()=>ss,pathSubscriptionMatches:()=>Si,personalSectionsKey:()=>Tr,ping:()=>Ha,pushChanges:()=>Wu,queryClient:()=>Ma,readItem:()=>ju,refreshQuery:()=>be,registerCleanup:()=>se,replaceMounts:()=>_s,resetAllSdkState:()=>bn,resolvePrincipalId:()=>ru,resubscribePath:()=>Ja,seatMember:()=>$i,selectMount:()=>wr,serverDeadlinePassed:()=>ga,serverMsUntil:()=>ya,serverNow:()=>Wr,setAnchor:()=>Br,setCachedToken:()=>ea,setQueryClient:()=>ka,setScope:()=>ca,setupRequireShim:()=>Zu,signal:()=>Gu,startTracking:()=>Ps,steerTurn:()=>Nu,submitForm:()=>Du,subscribeAnchor:()=>di,subscribeArtifactStream:()=>Ts,subscribeMounts:()=>$r,subscribeScope:()=>Se,subscribeToEvents:()=>ie,subscribeToPath:()=>rs,subscribeToScope:()=>Tn,trackAction:()=>ku,trackEvent:()=>$t,trackPageView:()=>Au,unmountRealtimeScope:()=>gs,updateItem:()=>Vu,uploadFile:()=>cl,useAcceptInvite:()=>el,useAccounts:()=>jc,useAgentTimeline:()=>ml,useAllChannels:()=>xs,useAnswerInput:()=>rl,useArrangement:()=>On,useArtifactStream:()=>pl,useAsset:()=>$c,useAuth:()=>Ss,useChannelMessages:()=>au,useChannels:()=>lu,useChildren:()=>Cc,useComponent:()=>qi,useCreate:()=>pu,useCreateAgent:()=>nl,useDelete:()=>gu,useDmChannels:()=>du,useEdges:()=>Oc,useEventStream:()=>vu,useFileUpload:()=>ll,useIncrementalItems:()=>kc,useInfiniteChannelMessages:()=>cu,useInfiniteChildren:()=>Mc,useInfiniteItems:()=>Fi,useInviteMember:()=>Xu,useItem:()=>Rc,useItemById:()=>Pc,useItemHistory:()=>Uc,useItemVersions:()=>Dc,useItems:()=>Ac,useLink:()=>_u,useList:()=>Oi,useMemberFocus:()=>Qc,useMintedAsset:()=>Su,useMounts:()=>Bc,useMove:()=>yu,useMutation:()=>bu,useNotifications:()=>Ni,useOpen:()=>qc,usePermission:()=>eu,usePermissions:()=>tu,usePersonalItemOrder:()=>Ru,usePersonalSections:()=>bl,usePinnedItems:()=>gl,usePrincipal:()=>su,usePublishedComponent:()=>Zc,useRealtimeQuery:()=>wu,useRecentActivity:()=>Kc,useResolve:()=>Ec,useResolvedItems:()=>fl,useScope:()=>Lc,useScopeReady:()=>xc,useSearch:()=>Ic,useSeatMember:()=>tl,useTheme:()=>Xc,useTimelineHistory:()=>hl,useTree:()=>Tc,useType:()=>Fc,useTypeHelpers:()=>Nc,useTypes:()=>ws,useUnreadCounts:()=>fu,useUpdate:()=>mu,useUpdatePrincipal:()=>hu,vfsKeys:()=>C,waitForPathReady:()=>za});var it=class e extends Error{constructor(n){let r=n.message||e.fallbackMessage(n);super(r);re(this,"name","EnforcementDeniedError");re(this,"deniedBy");re(this,"ruleKey");re(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 Fn=z(ue(),1);var Ce=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 Rt,ot,Wt,so,Ml=(so=class extends Ce{constructor(){super();I(this,Rt);I(this,ot);I(this,Wt);S(this,Wt,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){l(this,ot)||this.setEventListener(l(this,Wt))}onUnsubscribe(){var t;this.hasListeners()||((t=l(this,ot))==null||t.call(this),S(this,ot,void 0))}setEventListener(t){var n;S(this,Wt,t),(n=l(this,ot))==null||n.call(this),S(this,ot,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){l(this,Rt)!==t&&(S(this,Rt,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof l(this,Rt)=="boolean"?l(this,Rt):globalThis.document?.visibilityState!=="hidden"}},Rt=new WeakMap,ot=new WeakMap,Wt=new WeakMap,so),Ht=new Ml;var Ol={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},at,Fs,io,Fl=(io=class{constructor(){I(this,at,Ol);I(this,Fs,!1)}setTimeoutProvider(e){S(this,at,e)}setTimeout(e,t){return l(this,at).setTimeout(e,t)}clearTimeout(e){l(this,at).clearTimeout(e)}setInterval(e,t){return l(this,at).setInterval(e,t)}clearInterval(e){l(this,at).clearInterval(e)}},at=new WeakMap,Fs=new WeakMap,io),Qe=new Fl;function oo(e){setTimeout(e,0)}var Ns=typeof window>"u"||"Deno"in globalThis;function J(){}function uo(e,t){return typeof e=="function"?e(t):e}function Ln(e){return typeof e=="number"&&e>=0&&e!==1/0}function Ir(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Fe(e,t){return typeof e=="function"?e(t):e}function he(e,t){return typeof e=="function"?e(t):e}function Er(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:o,stale:a}=e;if(o){if(r){if(t.queryHash!==jn(o,t.options))return!1}else if(!Pt(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 Ar(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(!Pt(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function jn(e,t){return(t?.queryKeyHashFn||De)(e)}function De(e){return JSON.stringify(e,(t,n)=>qs(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function Pt(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>Pt(e[n],t[n])):!1}var ql=Object.prototype.hasOwnProperty;function Qs(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=ao(e)&&ao(t);if(!r&&!(qs(e)&&qs(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 f=r?d:o[d],m=e[f],p=t[f];if(m===p){c[f]=m,(r?d<i:ql.call(e,f))&&u++;continue}if(m===null||p===null||typeof m!="object"||typeof p!="object"){c[f]=p;continue}let g=Qs(m,p,n+1);c[f]=g,g===m&&u++}return i===a&&u===i?e:c}function Gt(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 ao(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function qs(e){if(!co(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!co(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function co(e){return Object.prototype.toString.call(e)==="[object Object]"}function lo(e){return new Promise(t=>{Qe.setTimeout(t,e)})}function Bn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Qs(e,t):t}function fo(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function po(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var zt=Symbol();function kr(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===zt?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Jt(e,t){return typeof e=="function"?e(...t):!!e}function mo(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=()=>Ns;return{isServer(){return e()},setIsServer(t){e=t}}})();function $n(){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 ho=oo;function Nl(){let e=[],t=0,n=a=>{a()},r=a=>{a()},s=ho,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 B=Nl();var Yt,ct,Zt,go,Ql=(go=class extends Ce{constructor(){super();I(this,Yt,!0);I(this,ct);I(this,Zt);S(this,Zt,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,ct)||this.setEventListener(l(this,Zt))}onUnsubscribe(){var t;this.hasListeners()||((t=l(this,ct))==null||t.call(this),S(this,ct,void 0))}setEventListener(t){var n;S(this,Zt,t),(n=l(this,ct))==null||n.call(this),S(this,ct,t(this.setOnline.bind(this)))}setOnline(t){l(this,Yt)!==t&&(S(this,Yt,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return l(this,Yt)}},Yt=new WeakMap,ct=new WeakMap,Zt=new WeakMap,go),Xt=new Ql;function Dl(e){return Math.min(1e3*2**e,3e4)}function Ds(e){return(e??"online")==="online"?Xt.isOnline():!0}var Mr=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Or(e){let t=!1,n=0,r,s=$n(),i=()=>s.status!=="pending",o=_=>{if(!i()){let h=new Mr(_);m(h),e.onCancel?.(h)}},a=()=>{t=!0},c=()=>{t=!1},u=()=>Ht.isFocused()&&(e.networkMode==="always"||Xt.isOnline())&&e.canRun(),d=()=>Ds(e.networkMode)&&e.canRun(),f=_=>{i()||(r?.(),s.resolve(_))},m=_=>{i()||(r?.(),s.reject(_))},p=()=>new Promise(_=>{r=h=>{(i()||u())&&_(h)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),g=()=>{if(i())return;let _,h=n===0?e.initialPromise:void 0;try{_=h??e.fn()}catch(y){_=Promise.reject(y)}Promise.resolve(_).then(f).catch(y=>{if(i())return;let v=e.retry??(Ue.isServer()?0:3),R=e.retryDelay??Dl,T=typeof R=="function"?R(n,y):R,w=v===!0||typeof v=="number"&&n<v||typeof v=="function"&&v(n,y);if(t||!w){m(y);return}n++,e.onFail?.(n,y),lo(T).then(()=>u()?void 0:p()).then(()=>{t?m(y):g()})})};return{promise:s,status:()=>s.status,cancel:o,continue:()=>(r?.(),s),cancelRetry:a,continueRetry:c,canStart:d,start:()=>(d()?g():p().then(g),s)}}var Ct,yo,Fr=(yo=class{constructor(){I(this,Ct)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Ln(this.gcTime)&&S(this,Ct,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,Ct)!==void 0&&(Qe.clearTimeout(l(this,Ct)),S(this,Ct,void 0))}},Ct=new WeakMap,yo);var Tt,en,Te,It,oe,Vn,Et,we,So,We,vo,wo=(vo=class extends Fr{constructor(t){super();I(this,we);I(this,Tt);I(this,en);I(this,Te);I(this,It);I(this,oe);I(this,Vn);I(this,Et);S(this,Et,!1),S(this,Vn,t.defaultOptions),this.setOptions(t.options),this.observers=[],S(this,It,t.client),S(this,Te,l(this,It).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,S(this,Tt,bo(this.options)),this.state=t.state??l(this,Tt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return l(this,oe)?.promise}setOptions(t){if(this.options={...l(this,Vn),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=bo(this.options);n.data!==void 0&&(this.setState(_o(n.data,n.dataUpdatedAt)),S(this,Tt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&l(this,Te).remove(this)}setData(t,n){let r=Bn(this.state.data,t,this.options);return F(this,we,We).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){F(this,we,We).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=l(this,oe)?.promise;return l(this,oe)?.cancel(t),n?n.then(J).catch(J):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return l(this,Tt)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>he(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===zt||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>Fe(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:!Ir(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),l(this,oe)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),l(this,oe)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),l(this,Te).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,oe)&&(l(this,Et)||F(this,we,So).call(this)?l(this,oe).cancel({revert:!0}):l(this,oe).cancelRetry()),this.scheduleGc()),l(this,Te).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||F(this,we,We).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&l(this,oe)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(l(this,oe))return l(this,oe).continueRetry(),l(this,oe).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:()=>(S(this,Et,!0),r.signal)})},i=()=>{let c=kr(this.options,n),d=(()=>{let f={client:l(this,It),queryKey:this.queryKey,meta:this.meta};return s(f),f})();return S(this,Et,!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,It),state:this.state,fetchFn:i};return s(c),c})();this.options.behavior?.onFetch(a,this),S(this,en,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&F(this,we,We).call(this,{type:"fetch",meta:a.fetchOptions?.meta}),S(this,oe,Or({initialPromise:n?.initialPromise,fn:a.fetchFn,onCancel:c=>{c instanceof Mr&&c.revert&&this.setState({...l(this,en),fetchStatus:"idle"}),r.abort()},onFail:(c,u)=>{F(this,we,We).call(this,{type:"failed",failureCount:c,error:u})},onPause:()=>{F(this,we,We).call(this,{type:"pause"})},onContinue:()=>{F(this,we,We).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0}));try{let c=await l(this,oe).start();if(c===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(c),l(this,Te).config.onSuccess?.(c,this),l(this,Te).config.onSettled?.(c,this.state.error,this),c}catch(c){if(c instanceof Mr){if(c.silent)return l(this,oe).promise;if(c.revert){if(this.state.data===void 0)throw c;return this.state.data}}throw F(this,we,We).call(this,{type:"error",error:c}),l(this,Te).config.onError?.(c,this),l(this,Te).config.onSettled?.(this.state.data,c,this),c}finally{this.scheduleGc()}}},Tt=new WeakMap,en=new WeakMap,Te=new WeakMap,It=new WeakMap,oe=new WeakMap,Vn=new WeakMap,Et=new WeakMap,we=new WeakSet,So=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},We=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,...Us(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,..._o(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return S(this,en,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),B.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),l(this,Te).notify({query:this,type:"updated",action:t})})},vo);function Us(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Ds(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function _o(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function bo(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 ge,D,Hn,fe,At,tn,He,ut,Gn,nn,rn,kt,Mt,lt,sn,j,Wn,Ks,Ls,js,Bs,$s,Vs,Ws,Co,Po,zn=(Po=class extends Ce{constructor(t,n){super();I(this,j);I(this,ge);I(this,D);I(this,Hn);I(this,fe);I(this,At);I(this,tn);I(this,He);I(this,ut);I(this,Gn);I(this,nn);I(this,rn);I(this,kt);I(this,Mt);I(this,lt);I(this,sn,new Set);this.options=n,S(this,ge,t),S(this,ut,null),S(this,He,$n()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(l(this,D).addObserver(this),xo(l(this,D),this.options)?F(this,j,Wn).call(this):this.updateResult(),F(this,j,Bs).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Hs(l(this,D),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Hs(l(this,D),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,F(this,j,$s).call(this),F(this,j,Vs).call(this),l(this,D).removeObserver(this)}setOptions(t){let n=this.options,r=l(this,D);if(this.options=l(this,ge).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof he(this.options.enabled,l(this,D))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");F(this,j,Ws).call(this),l(this,D).setOptions(this.options),n._defaulted&&!Gt(this.options,n)&&l(this,ge).getQueryCache().notify({type:"observerOptionsUpdated",query:l(this,D),observer:this});let s=this.hasListeners();s&&Ro(l(this,D),r,this.options,n)&&F(this,j,Wn).call(this),this.updateResult(),s&&(l(this,D)!==r||he(this.options.enabled,l(this,D))!==he(n.enabled,l(this,D))||Fe(this.options.staleTime,l(this,D))!==Fe(n.staleTime,l(this,D)))&&F(this,j,Ks).call(this);let i=F(this,j,Ls).call(this);s&&(l(this,D)!==r||he(this.options.enabled,l(this,D))!==he(n.enabled,l(this,D))||i!==l(this,lt))&&F(this,j,js).call(this,i)}getOptimisticResult(t){let n=l(this,ge).getQueryCache().build(l(this,ge),t),r=this.createResult(n,t);return Kl(this,r)&&(S(this,fe,r),S(this,tn,this.options),S(this,At,l(this,D).state)),r}getCurrentResult(){return l(this,fe)}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,He).status==="pending"&&l(this,He).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){l(this,sn).add(t)}getCurrentQuery(){return l(this,D)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=l(this,ge).defaultQueryOptions(t),r=l(this,ge).getQueryCache().build(l(this,ge),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return F(this,j,Wn).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),l(this,fe)))}createResult(t,n){let r=l(this,D),s=this.options,i=l(this,fe),o=l(this,At),a=l(this,tn),u=t!==r?t.state:l(this,Hn),{state:d}=t,f={...d},m=!1,p;if(n._optimisticResults){let A=this.hasListeners(),k=!A&&xo(t,n),E=A&&Ro(t,r,n,s);(k||E)&&(f={...f,...Us(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(f.fetchStatus="idle")}let{error:g,errorUpdatedAt:_,status:h}=f;p=f.data;let y=!1;if(n.placeholderData!==void 0&&p===void 0&&h==="pending"){let A;i?.isPlaceholderData&&n.placeholderData===a?.placeholderData?(A=i.data,y=!0):A=typeof n.placeholderData=="function"?n.placeholderData(l(this,rn)?.state.data,l(this,rn)):n.placeholderData,A!==void 0&&(h="success",p=Bn(i?.data,A,n),m=!0)}if(n.select&&p!==void 0&&!y)if(i&&p===o?.data&&n.select===l(this,Gn))p=l(this,nn);else try{S(this,Gn,n.select),p=n.select(p),p=Bn(i?.data,p,n),S(this,nn,p),S(this,ut,null)}catch(A){S(this,ut,A)}l(this,ut)&&(g=l(this,ut),p=l(this,nn),_=Date.now(),h="error");let v=f.fetchStatus==="fetching",R=h==="pending",T=h==="error",w=R&&v,O=p!==void 0,x={status:h,fetchStatus:f.fetchStatus,isPending:R,isSuccess:h==="success",isError:T,isInitialLoading:w,isLoading:w,data:p,dataUpdatedAt:f.dataUpdatedAt,error:g,errorUpdatedAt:_,failureCount:f.fetchFailureCount,failureReason:f.fetchFailureReason,errorUpdateCount:f.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:f.dataUpdateCount>u.dataUpdateCount||f.errorUpdateCount>u.errorUpdateCount,isFetching:v,isRefetching:v&&!R,isLoadingError:T&&!O,isPaused:f.fetchStatus==="paused",isPlaceholderData:m,isRefetchError:T&&O,isStale:Gs(t,n),refetch:this.refetch,promise:l(this,He),isEnabled:he(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let A=x.data!==void 0,k=x.status==="error"&&!A,E=U=>{k?U.reject(x.error):A&&U.resolve(x.data)},M=()=>{let U=S(this,He,x.promise=$n());E(U)},q=l(this,He);switch(q.status){case"pending":t.queryHash===r.queryHash&&E(q);break;case"fulfilled":(k||x.data!==q.value)&&M();break;case"rejected":(!k||x.error!==q.reason)&&M();break}}return x}updateResult(){let t=l(this,fe),n=this.createResult(l(this,D),this.options);if(S(this,At,l(this,D).state),S(this,tn,this.options),l(this,At).data!==void 0&&S(this,rn,l(this,D)),Gt(n,t))return;S(this,fe,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!l(this,sn).size)return!0;let o=new Set(i??l(this,sn));return this.options.throwOnError&&o.add("error"),Object.keys(l(this,fe)).some(a=>{let c=a;return l(this,fe)[c]!==t[c]&&o.has(c)})};F(this,j,Co).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&F(this,j,Bs).call(this)}},ge=new WeakMap,D=new WeakMap,Hn=new WeakMap,fe=new WeakMap,At=new WeakMap,tn=new WeakMap,He=new WeakMap,ut=new WeakMap,Gn=new WeakMap,nn=new WeakMap,rn=new WeakMap,kt=new WeakMap,Mt=new WeakMap,lt=new WeakMap,sn=new WeakMap,j=new WeakSet,Wn=function(t){F(this,j,Ws).call(this);let n=l(this,D).fetch(this.options,t);return t?.throwOnError||(n=n.catch(J)),n},Ks=function(){F(this,j,$s).call(this);let t=Fe(this.options.staleTime,l(this,D));if(Ue.isServer()||l(this,fe).isStale||!Ln(t))return;let r=Ir(l(this,fe).dataUpdatedAt,t)+1;S(this,kt,Qe.setTimeout(()=>{l(this,fe).isStale||this.updateResult()},r))},Ls=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(l(this,D)):this.options.refetchInterval)??!1},js=function(t){F(this,j,Vs).call(this),S(this,lt,t),!(Ue.isServer()||he(this.options.enabled,l(this,D))===!1||!Ln(l(this,lt))||l(this,lt)===0)&&S(this,Mt,Qe.setInterval(()=>{(this.options.refetchIntervalInBackground||Ht.isFocused())&&F(this,j,Wn).call(this)},l(this,lt)))},Bs=function(){F(this,j,Ks).call(this),F(this,j,js).call(this,F(this,j,Ls).call(this))},$s=function(){l(this,kt)!==void 0&&(Qe.clearTimeout(l(this,kt)),S(this,kt,void 0))},Vs=function(){l(this,Mt)!==void 0&&(Qe.clearInterval(l(this,Mt)),S(this,Mt,void 0))},Ws=function(){let t=l(this,ge).getQueryCache().build(l(this,ge),this.options);if(t===l(this,D))return;let n=l(this,D);S(this,D,t),S(this,Hn,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},Co=function(t){B.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(l(this,fe))}),l(this,ge).getQueryCache().notify({query:l(this,D),type:"observerResultsUpdated"})})},Po);function Ul(e,t){return he(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function xo(e,t){return Ul(e,t)||e.state.data!==void 0&&Hs(e,t,t.refetchOnMount)}function Hs(e,t,n){if(he(t.enabled,e)!==!1&&Fe(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Gs(e,t)}return!1}function Ro(e,t,n,r){return(e!==t||he(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Gs(e,n)}function Gs(e,t){return he(t.enabled,e)!==!1&&e.isStaleByTime(Fe(t.staleTime,e))}function Kl(e,t){return!Gt(e.getCurrentResult(),t)}function on(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,f=g=>{mo(g,()=>t.signal,()=>d=!0)},m=kr(t.options,t.fetchOptions),p=async(g,_,h)=>{if(d)return Promise.reject();if(_==null&&g.pages.length)return Promise.resolve(g);let v=(()=>{let O={client:t.client,queryKey:t.queryKey,pageParam:_,direction:h?"backward":"forward",meta:t.options.meta};return f(O),O})(),R=await m(v),{maxPages:T}=t.options,w=h?po:fo;return{pages:w(g.pages,R,T),pageParams:w(g.pageParams,_,T)}};if(s&&i.length){let g=s==="backward",_=g?To:zs,h={pages:i,pageParams:o},y=_(r,h);a=await p(h,y,g)}else{let g=e??i.length;do{let _=c===0?o[0]??r.initialPageParam:zs(r,a);if(c>0&&_==null)break;a=await p(a,_),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 zs(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 To(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function Io(e,t){return t?zs(e,t)!=null:!1}function Eo(e,t){return!t||!e.getPreviousPageParam?!1:To(e,t)!=null}var Js=class extends zn{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:on()})}getOptimisticResult(e){return e.behavior=on(),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",f=o&&c==="backward",m=s&&c==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Io(t,n.data),hasPreviousPage:Eo(t,n.data),isFetchNextPageError:u,isFetchingNextPage:d,isFetchPreviousPageError:f,isFetchingPreviousPage:m,isRefetchError:a&&!u&&!f,isRefetching:i&&!d&&!m}}};var Jn,Ke,le,Ot,Le,dt,Ao,ko=(Ao=class extends Fr{constructor(t){super();I(this,Le);I(this,Jn);I(this,Ke);I(this,le);I(this,Ot);S(this,Jn,t.client),this.mutationId=t.mutationId,S(this,le,t.mutationCache),S(this,Ke,[]),this.state=t.state||Ys(),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,Ke).includes(t)||(l(this,Ke).push(t),this.clearGcTimeout(),l(this,le).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){S(this,Ke,l(this,Ke).filter(n=>n!==t)),this.scheduleGc(),l(this,le).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){l(this,Ke).length||(this.state.status==="pending"?this.scheduleGc():l(this,le).remove(this))}continue(){return l(this,Ot)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{F(this,Le,dt).call(this,{type:"continue"})},r={client:l(this,Jn),meta:this.options.meta,mutationKey:this.options.mutationKey};S(this,Ot,Or({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(o,a)=>{F(this,Le,dt).call(this,{type:"failed",failureCount:o,error:a})},onPause:()=>{F(this,Le,dt).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>l(this,le).canRun(this)}));let s=this.state.status==="pending",i=!l(this,Ot).canStart();try{if(s)n();else{F(this,Le,dt).call(this,{type:"pending",variables:t,isPaused:i}),l(this,le).config.onMutate&&await l(this,le).config.onMutate(t,this,r);let a=await this.options.onMutate?.(t,r);a!==this.state.context&&F(this,Le,dt).call(this,{type:"pending",context:a,variables:t,isPaused:i})}let o=await l(this,Ot).start();return await l(this,le).config.onSuccess?.(o,t,this.state.context,this,r),await this.options.onSuccess?.(o,t,this.state.context,r),await l(this,le).config.onSettled?.(o,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(o,null,t,this.state.context,r),F(this,Le,dt).call(this,{type:"success",data:o}),o}catch(o){try{await l(this,le).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,le).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 F(this,Le,dt).call(this,{type:"error",error:o}),o}finally{l(this,le).runNext(this)}}},Jn=new WeakMap,Ke=new WeakMap,le=new WeakMap,Ot=new WeakMap,Le=new WeakSet,dt=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),B.batch(()=>{l(this,Ke).forEach(r=>{r.onMutationUpdate(t)}),l(this,le).notify({mutation:this,type:"updated",action:t})})},Ao);function Ys(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ge,qe,Yn,Mo,Oo=(Mo=class extends Ce{constructor(t={}){super();I(this,Ge);I(this,qe);I(this,Yn);this.config=t,S(this,Ge,new Set),S(this,qe,new Map),S(this,Yn,0)}build(t,n,r){let s=new ko({client:t,mutationCache:this,mutationId:++Kn(this,Yn)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){l(this,Ge).add(t);let n=qr(t);if(typeof n=="string"){let r=l(this,qe).get(n);r?r.push(t):l(this,qe).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(l(this,Ge).delete(t)){let n=qr(t);if(typeof n=="string"){let r=l(this,qe).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,qe).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=qr(t);if(typeof n=="string"){let s=l(this,qe).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=qr(t);return typeof n=="string"?l(this,qe).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){B.batch(()=>{l(this,Ge).forEach(t=>{this.notify({type:"removed",mutation:t})}),l(this,Ge).clear(),l(this,qe).clear()})}getAll(){return Array.from(l(this,Ge))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Ar(n,r))}findAll(t={}){return this.getAll().filter(n=>Ar(t,n))}notify(t){B.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){let t=this.getAll().filter(n=>n.state.isPaused);return B.batch(()=>Promise.all(t.map(n=>n.continue().catch(J))))}},Ge=new WeakMap,qe=new WeakMap,Yn=new WeakMap,Mo);function qr(e){return e.options.scope?.id}var ze,ft,ye,Je,Ye,Nr,Zs,Fo,Xs=(Fo=class extends Ce{constructor(t,n){super();I(this,Ye);I(this,ze);I(this,ft);I(this,ye);I(this,Je);S(this,ze,t),this.setOptions(n),this.bindMethods(),F(this,Ye,Nr).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,ze).defaultMutationOptions(t),Gt(this.options,n)||l(this,ze).getMutationCache().notify({type:"observerOptionsUpdated",mutation:l(this,ye),observer:this}),n?.mutationKey&&this.options.mutationKey&&De(n.mutationKey)!==De(this.options.mutationKey)?this.reset():l(this,ye)?.state.status==="pending"&&l(this,ye).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||l(this,ye)?.removeObserver(this)}onMutationUpdate(t){F(this,Ye,Nr).call(this),F(this,Ye,Zs).call(this,t)}getCurrentResult(){return l(this,ft)}reset(){l(this,ye)?.removeObserver(this),S(this,ye,void 0),F(this,Ye,Nr).call(this),F(this,Ye,Zs).call(this)}mutate(t,n){return S(this,Je,n),l(this,ye)?.removeObserver(this),S(this,ye,l(this,ze).getMutationCache().build(l(this,ze),this.options)),l(this,ye).addObserver(this),l(this,ye).execute(t)}},ze=new WeakMap,ft=new WeakMap,ye=new WeakMap,Je=new WeakMap,Ye=new WeakSet,Nr=function(){let t=l(this,ye)?.state??Ys();S(this,ft,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},Zs=function(t){B.batch(()=>{if(l(this,Je)&&this.hasListeners()){let n=l(this,ft).variables,r=l(this,ft).context,s={client:l(this,ze),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{l(this,Je).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{l(this,Je).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{l(this,Je).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{l(this,Je).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(l(this,ft))})})},Fo);var je,qo,No=(qo=class extends Ce{constructor(t={}){super();I(this,je);this.config=t,S(this,je,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??jn(s,n),o=this.get(i);return o||(o=new wo({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(o)),o}add(t){l(this,je).has(t.queryHash)||(l(this,je).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=l(this,je).get(t.queryHash);n&&(t.destroy(),n===t&&l(this,je).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){B.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return l(this,je).get(t)}getAll(){return[...l(this,je).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Er(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>Er(t,r)):n}notify(t){B.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){B.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){B.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},je=new WeakMap,qo);var Y,pt,mt,an,cn,ht,un,ln,Qo,ei=(Qo=class{constructor(e={}){I(this,Y);I(this,pt);I(this,mt);I(this,an);I(this,cn);I(this,ht);I(this,un);I(this,ln);S(this,Y,e.queryCache||new No),S(this,pt,e.mutationCache||new Oo),S(this,mt,e.defaultOptions||{}),S(this,an,new Map),S(this,cn,new Map),S(this,ht,0)}mount(){Kn(this,ht)._++,l(this,ht)===1&&(S(this,un,Ht.subscribe(async e=>{e&&(await this.resumePausedMutations(),l(this,Y).onFocus())})),S(this,ln,Xt.subscribe(async e=>{e&&(await this.resumePausedMutations(),l(this,Y).onOnline())})))}unmount(){var e,t;Kn(this,ht)._--,l(this,ht)===0&&((e=l(this,un))==null||e.call(this),S(this,un,void 0),(t=l(this,ln))==null||t.call(this),S(this,ln,void 0))}isFetching(e){return l(this,Y).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return l(this,pt).findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return l(this,Y).get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=l(this,Y).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Fe(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return l(this,Y).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,Y).get(r.queryHash)?.state.data,o=uo(t,i);if(o!==void 0)return l(this,Y).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return B.batch(()=>l(this,Y).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return l(this,Y).get(t.queryHash)?.state}removeQueries(e){let t=l(this,Y);B.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=l(this,Y);return B.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=B.batch(()=>l(this,Y).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(J).catch(J)}invalidateQueries(e,t={}){return B.batch(()=>(l(this,Y).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=B.batch(()=>l(this,Y).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(J)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(J)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=l(this,Y).build(this,t);return n.isStaleByTime(Fe(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(J).catch(J)}fetchInfiniteQuery(e){return e.behavior=on(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(J).catch(J)}ensureInfiniteQueryData(e){return e.behavior=on(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Xt.isOnline()?l(this,pt).resumePausedMutations():Promise.resolve()}getQueryCache(){return l(this,Y)}getMutationCache(){return l(this,pt)}getDefaultOptions(){return l(this,mt)}setDefaultOptions(e){S(this,mt,e)}setQueryDefaults(e,t){l(this,an).set(De(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...l(this,an).values()],n={};return t.forEach(r=>{Pt(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){l(this,cn).set(De(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...l(this,cn).values()],n={};return t.forEach(r=>{Pt(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...l(this,mt).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=jn(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===zt&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...l(this,mt).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){l(this,Y).clear(),l(this,pt).clear()}},Y=new WeakMap,pt=new WeakMap,mt=new WeakMap,an=new WeakMap,cn=new WeakMap,ht=new WeakMap,un=new WeakMap,ln=new WeakMap,Qo);var dn=z(ue(),1),Uo=z(Qr(),1),ti=dn.createContext(void 0),L=e=>{let t=dn.useContext(ti);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Zn=({client:e,children:t})=>(dn.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,Uo.jsx)(ti.Provider,{value:e,children:t}));var Dr=z(ue(),1),Ko=Dr.createContext(!1),Lo=()=>Dr.useContext(Ko),hm=Ko.Provider;var Xn=z(ue(),1),Ll=z(Qr(),1);function jl(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Bl=Xn.createContext(jl()),jo=()=>Xn.useContext(Bl);var Bo=z(ue(),1);var $o=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?Jt(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Vo=e=>{Bo.useEffect(()=>{e.clearReset()},[e])},Wo=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||Jt(n,[e.error,r]));var Ho=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))}},Go=(e,t)=>e.isLoading&&e.isFetching&&!t,zo=(e,t)=>e?.suspense&&t.isPending,ni=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var gt=z(ue(),1);function Ur(e,t,n){let r=Lo(),s=jo(),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",Ho(o),$o(o,s,a),Vo(s);let c=!i.getQueryCache().get(o.queryHash),[u]=gt.useState(()=>new t(i,o)),d=u.getOptimisticResult(o),f=!r&&e.subscribed!==!1;if(gt.useSyncExternalStore(gt.useCallback(m=>{let p=f?u.subscribe(B.batchCalls(m)):J;return u.updateResult(),p},[u,f]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),gt.useEffect(()=>{u.setOptions(o)},[o,u]),zo(o,d))throw ni(o,u,s);if(Wo({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()&&Go(d,r)&&(c?ni(o,u,s):a?.promise)?.catch(J).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?d:u.trackResult(d)}function $(e,t){return Ur(e,zn,t)}var Ze=z(ue(),1);function ee(e,t){let n=L(t),[r]=Ze.useState(()=>new Xs(n,e));Ze.useEffect(()=>{r.setOptions(e)},[r,e]);let s=Ze.useSyncExternalStore(Ze.useCallback(o=>r.subscribe(B.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=Ze.useCallback((o,a)=>{r.mutate(o,a).catch(J)},[r]);if(s.error&&Jt(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function er(e,t){return Ur(e,Js,t)}var Zo=z(Yo(),1),tr=typeof window<"u"&&window.__FSAOS_CONFIG__||{},Ft=Array.isArray(tr.sources)?tr.sources:[],$l=tr.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",Vl=tr.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",Ie=tr.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",W=(0,Zo.createClient)($l,Vl,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var nr=null,Kr=0,Xo,oi,Lr=!1;Xo=new Promise(e=>{oi=e});W.auth.onAuthStateChange((e,t)=>{t?.access_token?(nr=t.access_token,Kr=t.expires_at??Math.floor(Date.now()/1e3)+3600):(nr=null,Kr=0),Lr||(Lr=!0,oi())});setTimeout(()=>{Lr||(Lr=!0,oi())},5e3);function ea(e,t){nr=e,Kr=t??Math.floor(Date.now()/1e3)+3600}function ai(){nr=null,Kr=0}async function Xe(){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 Xo,nr}var hn=null,gn=null,ta=0,ri=new Set,ci,rr,yn=!1;ci=new Promise(e=>{rr=e});function ui(){ta++,ri.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function Br(e){let t=typeof e=="string"?e:e.path,n=hn!==t||gn?.id!==(typeof e=="string"?void 0:e.id);hn=t,gn=typeof e=="string"?null:e,typeof e!="string"&&!qt.some(r=>r.id===e.id)&&(qt=[...qt,e],pi()),yn||(yn=!0,rr()),n&&ui()}function _n(){return hn}function _e(){return gn}function li(){return ta}function di(e){return ri.add(e),()=>{ri.delete(e)}}function sr(){return ci}function fi(){return yn}var jr=null;function Nt(e,t={}){if(jr){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}jr=e,t.activate!==!1&&Br(e)}function pe(){return jr}var qt=[],si=new Set,na=0;function pi(){na++,si.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function Ee(){return qt}function ir(){return na}function $r(e){return si.add(e),()=>{si.delete(e)}}function ra(e,t){let n=JSON.stringify(qt)!==JSON.stringify(e),r=hn!==t.path||gn?.id!==t.id;qt=e,hn=t.path,gn=t,yn||(yn=!0,rr()),n&&pi(),r&&ui()}var pn=null,fn=null,mn=0,ii=new Set,sa=0;function ia(){sa++,ii.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Session listener error:",t)}})}function ae(){return mn}function mi(){return sa}function oa(e){return ii.add(e),()=>{ii.delete(e)}}async function et(){if(pn)return pn;if(fn)return fn;let e=mn;return fn=(async()=>{let t=Qt(),n=await Xe();if(e!==mn)throw new Error("Session changed during initialization");let r={};n&&(r.Authorization=`Bearer ${n}`);let s=await fetch(`${Ie}/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!==mn)throw new Error("Session changed during initialization");let o=i.entry||i;return pn={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},ia(),pn})().catch(t=>{throw e===mn&&(fn=null),t}),fn}function yt(){return pn}function hi(){mn++,pn=null,fn=null,hn=null,gn=null,jr=null,qt=[],ia()}var aa=[];function se(e){aa.push(e)}function bn(){hi(),ai(),rr(),yn=!1,ci=new Promise(e=>{rr=e}),ui(),pi();for(let e of aa)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function Qt(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var ca=Br,H=_n,te=li,Se=di,ua=sr,Vr=fi;var gi=0,la=!1,da=0;function fa(e){if(typeof e!="string")return;let t=Date.parse(e);Number.isNaN(t)||(gi=t-Date.now(),la=!0,da=Date.now())}function Wr(){return Date.now()+gi}function pa(){return la}function ma(){return gi}function ha(){return da}function ga(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Wr()>=t}function ya(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Math.max(0,t-Wr())}var vn,Ae=new Map,Dt=[],yi=0,_i={foreground:0,normal:1,background:2},Hr=()=>performance.now(),bi=()=>new DOMException("Read cancelled","AbortError");function ba(e={}){vn={concurrency:Math.max(1,Math.min(16,Math.floor(e.concurrency??6))),timeoutMs:Math.max(1e3,e.timeoutMs??15e3),onTiming:e.onTiming},zr()}function va(){for(let e of Ae.values()){e.controller.abort();for(let t of e.consumers)t.detach(),t.reject(bi());e.consumers.clear(),e.timer&&clearTimeout(e.timer)}Ae.clear(),Dt.length=0}function wa(e,t){return e==="query"?!("materialize"in t):["read","list","search","resolve","resolve-items","get-channel-messages","list-memberships"].includes(e)}function Gr(e){return Array.isArray(e)?`[${e.map(Gr).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)}:${Gr(n)}`).join(",")}}`:JSON.stringify(e)}function Sa(e,t,n,r){if(n.signal?.aborted)return Promise.reject(bi());if(!vn)return r(n.signal);let s=Ae.get(e);if(s)_i[n.priority??"normal"]<_i[s.priority]&&(s.priority=n.priority??"normal");else{s={key:e,method:t,priority:n.priority??"normal",queuedAt:Hr(),controller:new AbortController,consumers:new Set,run:r},Ae.set(e,s),Dt.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(),Ae.get(a.key)===a&&Ae.delete(a.key),_a(a)},vn.timeoutMs)}let i=s,o=new Promise((a,c)=>{let u=()=>{d.detach(),i.consumers.delete(d),c(bi()),i.consumers.size||(i.controller.abort(),Ae.get(i.key)===i&&Ae.delete(i.key),_a(i))},d={resolve:f=>a(structuredClone(f)),reject:c,detach:()=>n.signal?.removeEventListener("abort",u)};i.consumers.add(d),n.signal?.addEventListener("abort",u,{once:!0})});return zr(),o}function _a(e){let t=Dt.indexOf(e);t>=0&&(Dt.splice(t,1),Ae.get(e.key)===e&&Ae.delete(e.key),e.timer&&clearTimeout(e.timer)),zr()}function zr(){if(vn)for(;yi<vn.concurrency&&Dt.length;){let e=r=>_i[r.priority]-Math.floor((Hr()-r.queuedAt)/2e3);Dt.sort((r,s)=>e(r)-e(s)||r.queuedAt-s.queuedAt);let t=Dt.shift();if(!t.consumers.size)continue;yi++,t.startedAt=Hr();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(),Ae.get(t.key)===t&&Ae.delete(t.key),yi--;try{vn?.onTiming?.({method:t.method,priority:t.priority,queueMs:Math.round(t.startedAt-t.queuedAt),requestMs:Math.round(Hr()-t.startedAt),outcome:n})}catch{}zr()})}}se(va);var Wl=new Set(["list-memberships","init"]),ke=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);re(this,"name","GatewayRequestError");re(this,"method");re(this,"status");re(this,"statusText");re(this,"payload");re(this,"responseBody");this.method=n.method,this.status=n.status,this.statusText=n.statusText,this.payload=n.payload,this.responseBody=n.responseBody}};async function P(e,t={},n={}){let r=ae(),s=_n(),i=Qt(),o=`${Ie}/d/${i}`,a={"Content-Type":"application/json"},c=await xa(Xe(),n.signal);if(r!==ae())throw new Error("Session changed before gateway request");if(c&&(a.Authorization=`Bearer ${c}`),!Wl.has(e)&&!t._scope_path&&await xa(sr(),n.signal),r!==ae())throw new Error("Session changed before gateway request");let u={...t},d=yt();!u.domain_scope_id&&d?.scope_id&&(u.domain_scope_id=d.scope_id);let f=s??_n();!u._scope_path&&f&&(u._scope_path=f);let m=async p=>{if(r!==ae())throw new Error("Session changed before queued gateway request");let g=await fetch(o,{method:"POST",signal:p,headers:a,body:JSON.stringify({method:e,params:u})}),_=await g.text();if(r!==ae())throw new Error("Session changed during gateway request");let h=null;if(_)try{h=JSON.parse(_)}catch{}if(!g.ok||!h)throw new ke({method:e,status:g.status,statusText:g.statusText,payload:h,responseBody:_});if(h.success===!1){let y=h.error||"",v=h.denied_by||h.error_type||"";throw v==="rule"||v==="access"||v==="entitlement"||y==="RULE_DENIED"||y==="ACCESS_DENIED"||y==="PERMISSION_DENIED"||y==="ENTITLEMENT_REQUIRED"?new it(h):new ke({method:e,status:g.status,statusText:g.statusText,payload:h,responseBody:_})}return h&&h.server_now!==void 0&&fa(h.server_now),h};return wa(e,u)?Sa(Gr([r,i,c,e,u]),e,n,m):m(n.signal)}function xa(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 b=z(ue(),1),qd=z(Pa(),1),Nd=z(Qr(),1);var Ca=new WeakMap;function be(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(f=>f.promise?[f.promise]:[]);if(i.length===0)return s();let o=`${r?"=":"^"}${JSON.stringify(t)}`,a=Ca.get(e);a||(a=new Map,Ca.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 me(e,t){return typeof e=="string"&&(e===t||e.startsWith(`${t}/`))}var Jr=new WeakMap,Ta=e=>e.meta?.arrangementRealtime===!0;function tt(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&&be(e,t,{exact:!0})},250))}function Ia(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){if(!Ta(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")&&tt(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)))&&tt(e,n.queryKey)}}function Ea(e){for(let t of e.getQueryCache().getAll())Ta(t)&&t.state.data!==void 0&&tt(e,t.queryKey)}function Aa(e){Jr.get(e)?.forEach(clearTimeout),Jr.delete(e)}var nt=null;se(()=>{nt&&(nt.cancelQueries({queryKey:["vfs"]}),nt.removeQueries({queryKey:["vfs"]}))});function ka(e){if(nt&&nt!==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.");nt=e}function N(){return nt||(nt=new ei({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),nt}var Ma=new Proxy({},{get(e,t,n){let r=N(),s=r[t];return typeof s=="function"?s.bind(r):s}});var Yr=new WeakMap;function vi(e){return e.meta?.infiniteItemsRealtime?.filter}function Hl(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 Gl(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 zl(e,t,n){if(Hl(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&&!me(n.path,r)&&!me(n.old_path,r))return!1;if(n.item_type==="symlink"&&s&&i)return!0;let o=Gl(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 Oa(e,t){let n=Yr.get(e);n||(n=new Map,Yr.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||!vi(t))&&be(e,t.queryKey,{exact:!0})},500))}function Fa(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){let r=vi(n);r&&zl(n,r,t)&&Oa(e,n)}}function qa(e){for(let t of e.getQueryCache().getAll())vi(t)&&t.state.data!==void 0&&Oa(e,t)}function Na(e){Yr.get(e)?.forEach(clearTimeout),Yr.delete(e)}var Zr=class extends Error{constructor(){super("The server did not confirm the selected-Space listing contract")}};function Qa(e,t){if(!Array.isArray(t)||t.some(n=>typeof n!="string")||JSON.stringify([...new Set(t)].sort())!==JSON.stringify(e))throw new Zr}function _t(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 wn(e){return e instanceof Zr||e instanceof it||e instanceof ke&&(e.payload?.error==="SPACE_SELECTION_UNAVAILABLE"||e.payload?.error==="QUERY_PARAMS_INVALID"||e.status===401||e.status===403)}function ce(){return H()??"__unscoped__"}var C={all:()=>["vfs",ce()],item:e=>["vfs",ce(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",ce(),"children",e],allChildren:()=>["vfs",ce(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",ce(),"search",e,...t??[]],items:(e,t)=>["vfs",ce(),"items",e,JSON.stringify(_t(t??{}))],allItems:()=>["vfs",ce(),"items"],tree:(e,t)=>["vfs",ce(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",ce(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",ce(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",ce(),"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",ce(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",ce(),"channel-messages"],channels:e=>["vfs",ce(),"channels",e??"all"],allChannels:()=>["vfs",ce(),"channels"],notifications:(e,t)=>["vfs",ce(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",ce(),"notifications"],unreadCounts:()=>["vfs",ce(),"unread-counts"],memberships:e=>["memberships",e]};var Jl=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function Z(...e){Jl&&console.log("[WS]",...e)}var Q=null,Sn=null,Rn=null,or=0,Yl=3e4,Da=1e4,Cn=!1,Ua=!1,$a=3e4,Zl=$a*2+5e3,Xr=0,es=null,Ka=!1;function Xl(){cr(),Xr=Date.now(),es=setInterval(()=>{if(Q&&Q.readyState===WebSocket.OPEN&&Date.now()-Xr>Zl){Z("ping: no inbound traffic for",Date.now()-Xr,"ms \u2014 closing half-open socket");try{Q.close(4e3,"liveness timeout")}catch{}return}st({type:"ping"})},$a)}function cr(){es&&(clearInterval(es),es=null)}function ed(){typeof document>"u"||(document.hidden?cr():ar()&&(Z("Tab visible, reconnecting..."),Ut()))}function td(){Ka||typeof document>"u"||(document.addEventListener("visibilitychange",ed),Ka=!0)}var xe={};function Si(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return!n||!r?n===r:r===n||r.startsWith(`${n}/`)}var Pn=[],rt=new Map,xn=new Map,Me=new Map;function nd(e){let t=xn.get(e);return t?Array.from(new Set(Array.from(t.values()).flatMap(n=>n.event_types))).sort():[]}function La(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):!1}function ja(e){let t=nd(e);if(t.length===0)return rt.delete(e),null;let n={scope_id:e,event_types:t};return rt.set(e,n),n}var Be=new Map,bt=new Map,wi="disconnected",ts=[];function ns(e){if(wi!==e){wi=e;for(let t of[...ts])try{t(e)}catch{}}}function rd(e){Be.set(e,"ready");let t=bt.get(e);if(t){bt.delete(e);for(let n of t)n()}}function sd(){for(let e of Be.keys())Be.set(e,"disconnected")}function xi(e,t){Be.set(e,"pending"),st({type:"subscribe_path",path:e,event_types:t})}function id(){return Object.keys(xe).some(t=>xe[t]&&xe[t].length>0)||Pn.length>0}function ar(){return rt.size>0||Me.size>0}async function Ut(){if(!ar()){Z("ensureConnection: no active subscriptions, skipping");return}if(Q&&Q.readyState===WebSocket.OPEN){Z("ensureConnection: already open");return}if(Sn)return Z("ensureConnection: connection already in flight, waiting..."),Sn;if(Q){Z("ensureConnection: killing stale WS in state",Q.readyState);try{Q.close()}catch{}Q=null}return Cn=!1,Sn=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=Ie,n=await Xe();if(!n){Z("ensureConnection: no token available, will retry"),Ba();return}let r=t.startsWith("https")?"wss":"ws",s=t.replace(/^https?:\/\//,""),i=`${r}://${s}/ws`;i+=`?token=${encodeURIComponent(n)}`,Z("ensureConnection: opening WS to",i.substring(0,50)+"..."),ns("connecting"),Q=new WebSocket(i);let o=Q;await new Promise((a,c)=>{if(!Q)return c(new Error("WebSocket not created"));let u=setTimeout(()=>{if(Q===o){if(Z("ensureConnection: TIMEOUT after",Da,"ms"),Q&&Q.readyState!==WebSocket.OPEN){try{Q.close()}catch{}Q=null}c(new Error("WebSocket connection timeout"))}},Da);o.onopen=()=>{if(Q!==o)return;clearTimeout(u),Z("ensureConnection: CONNECTED");let d=Ua;Ua=!0,or=0,ns("connected"),od(d),(typeof document>"u"||!document.hidden)&&Xl(),td(),a()},o.onmessage=d=>{Q===o&&ad(d.data)},o.onerror=()=>{Z("ensureConnection: WS error event")},o.onclose=d=>{clearTimeout(u),Q===o&&(Z("ensureConnection: WS closed, code:",d.code,"reason:",d.reason),Q=null,cr(),sd(),ns("disconnected"),!Cn&&ar()&&Ba(),c(new Error(`WebSocket closed: ${d.code}`)))}})}catch(e){Z("ensureConnection: failed -",e?.message||e)}finally{Sn=null}})(),Sn}function Ba(){if(Rn||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,or)+Math.random()*1e3,Yl);or++,Z("scheduleReconnect: attempt",or,"in",Math.round(e),"ms"),Rn=setTimeout(()=>{Rn=null,ar()&&Ut()},e)}function od(e=!1){for(let t of rt.values())Z("resubscribeAll: scope",t.scope_id),st({type:"subscribe",scope_id:t.scope_id,event_types:t.event_types});for(let t of Me.values())Z("resubscribeAll: path",t.path),xi(t.path,t.event_types);e&&Va("reconnect")}function Va(e){try{let t=N();qa(t),Ea(t);for(let n of Me.values())t.invalidateQueries({queryKey:C.item(n.path)}),t.invalidateQueries({queryKey:C.children(n.path)});Z("catchUpAfterGap:",e,"- invalidated",Me.size,"paths")}catch(t){Z("catchUpAfterGap: cache invalidation skipped",t)}}function st(e){Q&&Q.readyState===WebSocket.OPEN&&Q.send(JSON.stringify(e))}function ad(e){Xr=Date.now();try{let t=JSON.parse(e);if(t.type==="subscribed_path"){typeof t.path=="string"&&rd(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==="resync"){Va(typeof t.reason=="string"?t.reason:"resync");return}if(t.type==="event"||t.event_type){let n=t.event_type||"message",r=t.data||t;if(n==="vfs_change"&&(Fa(N(),r),Ia(N(),r)),typeof r.path=="string")for(let[s,i]of Object.entries(xe))s!=="*"&&Si(s,r.path)&&i.forEach(o=>o(r));xe["*"]&&xe["*"].forEach(s=>s(r));for(let s of Pn)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function Ri(){!id()&&rt.size===0&&Me.size===0&&Q&&(Cn=!0,cr(),Q.close(),Q=null,Cn=!1)}function rs(e,t){return xe[e]||(xe[e]=[]),xe[e].push(t),Me.has(e)||(Me.set(e,{path:e,event_types:["token_stream"]}),Q&&Q.readyState===WebSocket.OPEN?xi(e,["token_stream"]):Be.set(e,"pending")),Ut(),()=>{let n=xe[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete xe[e],Me.delete(e),Be.delete(e),bt.delete(e),st({type:"unsubscribe_path",path:e}))}Ri()}}function ie(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return Pn.push(...s),ar()&&Ut(),()=>{for(let i of s){let o=Pn.indexOf(i);o!==-1&&Pn.splice(o,1)}Ri()}}function Tn(e,t=["vfs_change","ccm_change"]){let n=Symbol(e),r=Array.from(new Set(t)).sort();if(r.length===0)return()=>{};let s=xn.get(e)??new Map,i=rt.get(e)?.event_types;s.set(n,{event_types:r}),xn.set(e,s);let o=ja(e);if(!o)return()=>{};Z("subscribeToScope:",e,o.event_types),Q&&Q.readyState===WebSocket.OPEN&&!La(i,o.event_types)&&st({type:"subscribe",scope_id:e,event_types:o.event_types}),Ut();let a=!0;return()=>{if(!a)return;a=!1;let c=xn.get(e);if(!c?.delete(n))return;let u=rt.get(e)?.event_types;if(c.size===0)xn.delete(e),rt.delete(e),st({type:"unsubscribe",scope_id:e});else{let d=ja(e);d&&Q&&Q.readyState===WebSocket.OPEN&&!La(u,d.event_types)&&st({type:"subscribe",scope_id:e,event_types:d.event_types})}Ri()}}function Wa(e,t,n={}){st({type:"emit",scope_id:e,event_type:t,payload:n})}function Pi(){Z("disconnectSSE: tearing down"),Na(N()),Aa(N()),Cn=!0,cr(),Q&&(Q.close(),Q=null),Rn&&(clearTimeout(Rn),Rn=null),Sn=null,Cn=!1,or=0;for(let e of Object.keys(xe))delete xe[e];Pn.length=0,rt.clear(),xn.clear(),Me.clear(),Be.clear(),bt.clear(),ns("disconnected")}function Ha(){st({type:"ping"})}function Ga(e){return Me.has(e)?Be.get(e)??"pending":"unsubscribed"}function za(e,t=5e3){return Me.has(e)?Be.get(e)==="ready"&&Q&&Q.readyState===WebSocket.OPEN?Promise.resolve(!0):(Ut(),new Promise(n=>{let r=!1,s=bt.get(e)??[],i=()=>{r||(r=!0,clearTimeout(o),n(!0))};s.push(i),bt.set(e,s);let o=setTimeout(()=>{if(r)return;r=!0;let a=bt.get(e);if(a){let c=a.indexOf(i);c!==-1&&a.splice(c,1),a.length===0&&bt.delete(e)}n(!1)},t)})):Promise.resolve(!1)}function Ja(e){let t=Me.get(e);if(!t){Z("resubscribePath: no active subscription for",e);return}Q&&Q.readyState===WebSocket.OPEN?(Z("resubscribePath: re-sending frame for",e),xi(t.path,t.event_types)):(Be.set(e,"pending"),Ut())}function ss(e){ts.push(e);try{e(wi)}catch{}return()=>{let t=ts.indexOf(e);t!==-1&&ts.splice(t,1)}}se(Pi);function Ya(){return new Date().toISOString()}function Za(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function Oe(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||Ya(),updated_at:e.updated_at||Ya(),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 lr(e){return(e.content?.items||e.items||[]).map(Oe)}async function dr(e){try{let t=await P("read",{id:e});if(t.item_name||t.item_path){let r=Oe(t);return r.path&&N().setQueryData(C.item(r.path),r),r}let n=t.item;if(n){let r=Oe(n);return r.path&&N().setQueryData(C.item(r.path),r),r}return null}catch{return null}}async function fr(e){try{let t=await P("read",{path:e});if(t.item_name||t.item_path)return Oe(t);let n=t.item;return n?Oe(n):null}catch{return null}}async function pr(e){try{let t=await P("list",{path:e,limit:200}),n=lr(t);for(let r of n)N().setQueryData(C.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function Xa(e,t){let{items:n}=await Kt({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 os(e,t,n){try{let r=await P("list",{path:e,limit:t,offset:n}),s=lr(r);for(let i of s)N().setQueryData(C.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 as(e){let n=await P("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 cs(e){try{let t=await P("edges",{item_id:e}),n=t.outgoing||[],r=t.incoming||[],s=[];for(let i of n)s.push({id:i.edge_id||Za(),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||Za(),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 us(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 P("tree",s),o=lr(i);for(let a of o)N().setQueryData(C.item(a.path),a);return o}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function ls(e,t=50,n=0){try{let r=await P("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 mr(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;try{let i=await P("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 ds(e,t=50,n=0){return mr(e,{limit:t,offset:n})}async function fs(e,t,n){try{let r={scope_id:e};t?.length&&(r.item_types=t),n&&(r.limit=n);let s=await P("member-focus",r),i=lr(s);for(let o of i)N().setQueryData(C.item(o.path),o);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${e}:`,r),[]}}async function hr(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 P("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 In(e){return!!e&&(!!e.type||Array.isArray(e.any_of)&&e.any_of.length>0)}function cd(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 ud=["catalog","parent_only","internal"];function ec(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"&&ud.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 In(s)?{...s,...t}:null}async function Kt(e,t={}){if(e=_t(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(cd)),Object.keys(r).length>0&&(n.filters=r),e.limit!=null&&(n.limit=e.limit);try{let s=await P("query",n,t);e.spaceIds!==void 0&&Qa(e.spaceIds,s.selected_space_ids??s.content?.selected_space_ids);let i=lr(s);for(let o of i)N().setQueryData(C.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 ld(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 tc(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:ld(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 ur(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 nc(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await P("get-channel-messages",n),i=s.messages||s.content?.items||s.items||[];return ur(i)}catch(n){throw console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),n}}async function ps(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await P("get-channel-messages",n),i=s.messages||[],o=ur(i),a=tc(i),c=new Map,u=[];for(let d of a)if(d.parentMessagePath){let f=c.get(d.parentMessagePath)||[];f.push(d),c.set(d.parentMessagePath,f)}else u.push(d);return{messages:o,activityMessages:ur(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 gr(e,t){try{let n={channel_path:e};t?.parentMessageId&&(n.parent_message_id=t.parentMessageId),t?.conversationsOnly&&(n.conversations_only=!0),t?.transcriptOnly&&(n.transcript_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 P("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.");if(t?.transcriptOnly&&s.transcript_only!==!0)throw new Error("This server does not support channel transcript pages yet. Update the message reader.");let i=s.messages||[],o=tc(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:ur(i),activityMessages:ur(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 is(e){N().invalidateQueries({queryKey:C.children(e)})}function Ci(e){N().invalidateQueries({queryKey:C.item(e)})}function rc(e,t){Ci(e),is(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&is(r)}function sc(e){let t=e+"/";N().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function ic(){N().invalidateQueries({queryKey:C.all()})}function oc(e){N().invalidateQueries({queryKey:C.types(e)})}function ac(e,t){e?N().invalidateQueries({queryKey:C.channelMessages(e,t)}):N().invalidateQueries({queryKey:C.allChannelMessages()})}function cc(e,t){e&&t?N().invalidateQueries({queryKey:C.openEnvelope(e,t)}):e?N().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):N().invalidateQueries({queryKey:C.allOpenEnvelopes()})}function $e(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}async function ms(){return((await P("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 En=new Map,_r=null,hs=null,vt=new Map,uc=250,yr=new Map;function Lt(e){if(_r){An(e);return}An(e),_r=ie("vfs_change",t=>dd(t)),hs=ie("ccm_change",t=>fd(t))}function An(e){if(En.has(e))return;let t=Tn(e,["vfs_change","ccm_change"]);En.set(e,t)}function gs(e){let t=En.get(e);t&&(t(),En.delete(e))}function Ti(){for(let[,e]of En)e();En.clear(),_r&&(_r(),_r=null),hs&&(hs(),hs=null),vt.forEach(e=>clearTimeout(e)),vt.clear(),yr.clear()}se(Ti);function dd(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=yr.get(s);i||(i=new Map,yr.set(s,i)),i.set(t,{action:n,itemId:typeof e.item_id=="string"?e.item_id:void 0});let o=vt.get(s);o&&clearTimeout(o);let a=setTimeout(()=>{vt.delete(s);let c=yr.get(s);yr.delete(s),c&&pd(s,c)},uc);vt.set(s,a)}function fd(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=vt.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{vt.delete(s),t&&N().invalidateQueries({queryKey:C.edges(t)}),n&&N().invalidateQueries({queryKey:C.edges(n)})},uc);vt.set(s,o)}function pd(e,t){let n=N();for(let[s,i]of t)(i.action||"").toUpperCase()==="DELETE"?(n.removeQueries({queryKey:C.item(s)}),n.removeQueries({queryKey:C.children(s)}),n.removeQueries({queryKey:C.tree(s)})):be(n,C.item(s),{exact:!0}),i.itemId&&n.invalidateQueries({queryKey:C.itemById(i.itemId)});n.invalidateQueries({queryKey:C.children(e)});let r=[...t.keys()];n.invalidateQueries({predicate:s=>{let i=s.queryKey;if(i[0]!=="vfs"||i[1]!=="tree")return!1;let o=i[2];return r.some(a=>a.startsWith(o+"/")||a===o)}})}var kn=null;se(()=>{kn=null});function wt(e){if(e!==kn||e.generation!==ae())throw new Error("Workspace session changed")}function md(e){return e instanceof ke&&e.payload?.error==="item_not_found"}function br(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 vr(e){let t=pe();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 lc(e,t){return JSON.stringify({mounts:e.map(n=>n.id),last_anchor:t.id})}async function dc(e,t,n){wt(e);let r=lc(t,n);if(e.saved===r)return;let s=JSON.parse(r);await P(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}),wt(e),e.exists=!0,e.saved=r}function fc(e,t){let n=Ee();Lt(pe().id);for(let r of n)e.some(s=>s.id===r.id)||gs(r.id);for(let r of e)An(r.id);ra(e,t)}async function jt(e,t,n={}){let r=pe();if(!r)throw new Error("Elect a home account before loading mounts");let s=`${e}/settings/mounts`;if(kn&&kn.path!==s)throw new Error("Reset the session before changing the mount declaration owner");let i=kn??(kn={generation:ae(),path:s,scope:r.path,resolve:t,exists:!1,ready:!1,saved:null,queue:Promise.resolve()});return wt(i),i.loading?i.loading:i.ready?Ee():(i.resolve=t,i.loading=(async()=>{let o=null;try{let d=await P("read",{path:s,_scope_path:i.scope});if(wt(i),o=d.type_data??d.item?.type_data,!o||!Array.isArray(o.mounts)||!o.mounts.every(f=>typeof f=="string"))throw new Error("Invalid saved mount declaration");i.exists=!0}catch(d){if(wt(i),!md(d))throw d;i.exists=!1}let a=n.initialAnchor?br(i,n.initialAnchor):r,c=vr(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=lc(c,u):n.initialAnchor&&await dc(i,c,u),wt(i),i.ready=!0,fc(c,u),c})().finally(()=>{i.loading=void 0}),i.loading)}function ys(e){let t=kn;if(!t?.ready)return Promise.reject(new Error("Workspace mounts are not loaded"));let n=t.queue.then(async()=>{wt(t);let{refs:r,anchor:s}=e(t);await dc(t,r,s),wt(t),fc(r,s)});return t.queue=n.catch(()=>{}),n}function Ii(e){return ys(t=>({refs:vr([...Ee(),br(t,e)]),anchor:_e()}))}function pc(e){return ys(()=>{if(e===pe().id)throw new Error("The home account cannot be unmounted");let t=vr(Ee().filter(r=>r.id!==e)),n=t.find(r=>r.id===_e()?.id)??t.find(r=>r.kind==="space")??pe();return{refs:t,anchor:n}})}function wr(e){return ys(t=>{let n=br(t,e);return{refs:vr([...Ee(),n]),anchor:n}})}function _s(e,t){return ys(n=>{let r=vr(e.map(i=>br(n,i))),s=br(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}})}var Ei={};to(Ei,{Badge:()=>vd,Breadcrumbs:()=>kd,Button:()=>Sd,Card:()=>bd,DataView:()=>Rd,Detail:()=>Td,Empty:()=>xd,FilePreview:()=>Fd,Form:()=>Cd,Grid:()=>yd,Image:()=>Md,Link:()=>Ed,Page:()=>hd,Router:()=>Id,Sidebar:()=>_d,Spinner:()=>wd,Stack:()=>gd,Table:()=>Pd,Tabs:()=>Ad,Video:()=>Od});var G=z(ue(),1);function mc(){return(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||""}function hd(e){return(0,G.createElement)("div",{style:{minHeight:"100vh",display:"flex",flexDirection:"column"},className:e.className||""},e.children)}function gd(e){let t=e.direction||"vertical";return(0,G.createElement)("div",{style:{display:"flex",flexDirection:t==="horizontal"?"row":"column",gap:e.gap||"0.5rem",padding:e.padding||"0",alignItems:e.align||"stretch",justifyContent:e.justify||"flex-start",flex:e.flex||"initial"},className:e.className||""},e.children)}function yd(e){return(0,G.createElement)("div",{style:{display:"grid",gridTemplateColumns:"repeat("+(e.columns||3)+", 1fr)",gap:e.gap||"1rem",padding:e.padding||"0"},className:e.className||""},e.children)}function _d(e){return(0,G.createElement)("div",{style:{display:"flex",flexDirection:"row",minHeight:"100vh"},className:e.className||""},e.children)}function bd(e){return(0,G.createElement)("div",{style:{border:"1px solid var(--color-border, #e5e7eb)",borderRadius:"var(--border-radius, 0.5rem)",padding:e.padding||"1rem",background:"var(--color-surface, #fff)"},className:e.className||"",onClick:e.onClick},e.children)}function vd(e){return(0,G.createElement)("span",{style:{display:"inline-flex",alignItems:"center",padding:"0.125rem 0.5rem",fontSize:"0.75rem",fontWeight:"500",borderRadius:"9999px",background:e.color||"#e5e7eb",color:e.textColor||"#374151"},className:e.className||""},e.children||e.label)}function wd(e){let t=e.size||"1.5rem";return(0,G.createElement)("div",{style:{width:t,height:t,border:"2px solid #e5e7eb",borderTopColor:"var(--color-primary, #3b82f6)",borderRadius:"50%",animation:"fsaos-spin 0.6s linear infinite"}})}function Sd(e){return(0,G.createElement)("button",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:"0.5rem 1rem",fontSize:"0.875rem",fontWeight:"500",borderRadius:"var(--border-radius, 0.375rem)",border:e.variant==="outline"?"1px solid var(--color-border, #d1d5db)":"none",background:e.variant==="outline"||e.variant==="ghost"?"transparent":"var(--color-primary, #3b82f6)",color:e.variant==="outline"||e.variant==="ghost"?"var(--color-text, #1a1a1a)":"#fff",cursor:e.disabled?"not-allowed":"pointer",opacity:e.disabled?"0.5":"1",gap:"0.5rem"},className:e.className||"",onClick:e.onClick,disabled:e.disabled},e.children||e.label)}function xd(e){return(0,G.createElement)("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"3rem",color:"var(--color-text-secondary, #6b7280)",textAlign:"center"}},e.icon?(0,G.createElement)("div",{style:{fontSize:"2rem",marginBottom:"0.5rem"}},e.icon):null,(0,G.createElement)("div",{style:{fontWeight:500,marginBottom:"0.25rem"}},e.title||e.message||e.children||"No items"),e.description?(0,G.createElement)("div",{style:{fontSize:"0.875rem",opacity:.7}},e.description):null)}function Rd(e){return(0,G.createElement)("div",{className:e.className||""},e.children)}function Pd(e){return(0,G.createElement)("table",{className:e.className||""},e.children)}function Cd(e){return(0,G.createElement)("form",{className:e.className||"",onSubmit:e.onSubmit},e.children)}function Td(e){return(0,G.createElement)("div",{className:e.className||""},e.children)}function Id(e){return(0,G.createElement)("div",null,e.children)}function Ed(e){return(0,G.createElement)("a",{href:e.href||e.to,className:e.className||"",onClick:e.onClick},e.children)}function Ad(e){return(0,G.createElement)("div",{className:e.className||""},e.children)}function kd(e){return(0,G.createElement)("nav",{className:e.className||""},e.children)}function Md(e){return(0,G.createElement)("img",{src:e.src||(e.path?mc()+e.path:""),alt:e.alt||"",className:e.className||"",style:e.style})}function Od(e){return(0,G.createElement)("video",{src:e.src||(e.path?mc()+e.path:""),controls:!0,className:e.className||""})}function Fd(e){return(0,G.createElement)("div",{className:e.className||""},e.children||"File preview")}function bs(e){if(typeof e.path!="string")return!1;let t=[...Ee().map(n=>n.path),_e()?.path].filter(n=>!!n);return!t.length&&H()&&t.push(H()),t.some(n=>me(e.path,n))}function Ai(e,t,n,r){if(!["message","card"].includes(e?.item_type)||!me(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&&me(e.path,i)})}var hc=new WeakMap;function gc(e,t,n){let r=hc.get(e);r||(r=new Map,hc.set(e,r));let s=JSON.stringify(t),i=r.get(s);if(!i){let a=!1,c,u=!1,d=!1,f=new Set,m=new Set,p=()=>e.getQueryData(t)??[],g=()=>{a||u||c||(c=setTimeout(()=>{c=void 0,_()},250))},_=async()=>{if(a)return;u=!0;let T=d;d=!1;let w=[...f],O=new Set(m);m.clear(),f.clear();try{if(T)await be(e,t,{exact:!0});else{let x=(await Promise.allSettled(w.map(async A=>{let k=e.getQueryCache().find({queryKey:t,exact:!0});if(!k)return;let E=await P("read",{id:A});if(E.success===!1)throw new Error("Channel refresh failed");if(a||!k||e.getQueryCache().find({queryKey:t,exact:!0})!==k)return;let M=Oe(E.item??E);if(M.id!==A||M.item_type!=="channel")return;let q=p().find(Re=>Re.id===A);if(!q)return;let U=n({...M}),V={...q,path:U.path,name:U.name,displayName:U.displayName,messageCount:U.messageCount,aiMode:U.aiMode,activeAgentIds:U.activeAgentIds,isPrivate:U.isPrivate,isDm:U.isDm,autoPilot:U.autoPilot,isArchived:U.isArchived,updatedAt:U.updatedAt};O.has(A)&&(q.name!==V.name||q.displayName!==V.displayName||q.path!==V.path)&&(d=!0),e.setQueryData(t,Re=>Re?.map(ne=>ne.id===A?V:ne))}))).find(A=>A.status==="rejected");if(x?.status==="rejected")throw x.reason}}catch(K){console.warn("[channels] refresh failed",K)}finally{u=!1,(d||f.size)&&g()}},h=T=>p().some(w=>w.id===T.item_id||w.path===T.path)?!0:bs(T),y=T=>{if(!h(T))return;let w=String(T.action??"").toLowerCase();if(["insert","delete","rename","move"].includes(w))d=!0;else if(w==="update"){let O=p().find(K=>K.id===T.item_id||K.path===T.path);O&&(f.add(O.id),m.add(O.id))}(d||f.size)&&g()},v=T=>{let w=p().find(O=>O.id===T.parent_id);w&&(f.add(w.id),g())},R=["vfs_change","ccm_change"].flatMap(T=>[ie(T,y,w=>w.item_type==="channel"),ie(T,v,w=>w.item_type==="message")]);i={users:0,stop:()=>{a=!0,c&&clearTimeout(c),R.forEach(T=>T())}},r.set(s,i)}i.users++;let o=!1;return()=>{o||(o=!0,--i.users===0&&(i.stop(),r.delete(s)))}}function X(){return(0,b.useSyncExternalStore)(Se,te,te)}function xc(){return X(),Vr()}function Rc(e){return X(),$({queryKey:C.item(e),queryFn:()=>fr(e),enabled:!!e,staleTime:1/0})}function Pc(e){return X(),$({queryKey:C.itemById(e),queryFn:()=>dr(e),enabled:!!e,staleTime:1/0})}function Oi(e){return X(),$({queryKey:C.children(e),queryFn:()=>pr(e),enabled:!!e})}function Cc(e){let t=Oi(e);return{...t,children:t.data??[]}}function Tc(e,t=1){return X(),$({queryKey:C.tree(e,t),queryFn:()=>us(e,t),enabled:!!e})}function Ic(e,t){return X(),$({queryKey:C.search(e,t),queryFn:async()=>{let n={query:e};t?.length&&(n.item_types=t);let r=await P("search",n);return(r.content?.items||r.items||r.results||[]).map(Oe)},enabled:!!e&&e.length>0})}function Ec(e){X();let t=(0,b.useMemo)(()=>e,[JSON.stringify(e)]);return $({queryKey:["vfs",H()??"__unscoped__","resolve",JSON.stringify(t??{})],queryFn:async()=>await P("resolve",t),enabled:!!t?.query&&t.query.length>0})}function Ac(e){X();let t=_t(e),n=(0,b.useMemo)(()=>t,[JSON.stringify(t)]),r=$({queryKey:C.items(n?.type??"",n),queryFn:({signal:s})=>Kt(n,{signal:s,throwOnError:!0}),enabled:In(n),...n?.spaceIds!==void 0?{retry:(s,i)=>!wn(i)&&xu(s,i)}:{},select:s=>s.items});return n?.spaceIds!==void 0&&wn(r.error)?{...r,data:void 0}:r}function Fi(e,t={}){let n=X(),{realtime:r=!1}=t,s=_t(e),i=s?.limit??20,o=(0,b.useMemo)(()=>s,[JSON.stringify(s)]),a=(0,b.useMemo)(()=>["vfs",H()??"__unscoped__","infinite-items",o?.type??"",JSON.stringify(o??{})],[n,o]),c=er({queryKey:a,queryFn:async({pageParam:f=0,signal:m})=>Kt({...o,limit:i,offset:f},{throwOnError:!0,signal:m,priority:t.priority}),initialPageParam:0,getNextPageParam:(f,m,p)=>{if(!(o?.spaceIds!==void 0&&f.total_hint!==void 0&&p+f.items.length>=f.total_hint)&&!(f.items.length<i))return p+f.items.length},enabled:In(o),...o?.spaceIds!==void 0?{retry:(f,m)=>!wn(m)&&xu(f,m)}:{},staleTime:r?1/0:t.staleTime,meta:r&&o?{infiniteItemsRealtime:{filter:o}}:{}}),u=(0,b.useMemo)(()=>{if(o?.spaceIds!==void 0&&wn(c.error))return[];if(!c.data?.pages)return[];let f=new Set,m=[];for(let p of c.data.pages)for(let g of p.items)g.id&&!f.has(g.id)&&(f.add(g.id),m.push(g));return m},[c.data?.pages,c.error,o]),d=o?.spaceIds!==void 0&&wn(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 yc(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 Qd(e,t){if(e.is_active===!1||e.item_type!==t.type||!me(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 kc(e,t={}){let n=yc(e),r=Fi(e,n?{realtime:!1,staleTime:3e4}:{realtime:!0}),s=L(),i=JSON.stringify([H(),_t(e)]),[o,a]=(0,b.useState)(()=>({identity:i,upserts:{},deleted:new Set})),c=o.identity===i?o:{identity:i,upserts:{},deleted:new Set},u=(0,b.useMemo)(()=>{if(!n)return r.allItems;let p=Object.values(c.upserts),g=new Set(p.map(v=>v.id)),_=[...p,...r.allItems.filter(v=>!g.has(v.id))].filter(v=>!c.deleted.has(v.path)),h=e.sort_by??"updated_at",y=e.sort_dir==="asc"?1:-1;return _.sort((v,R)=>y*String(v[h]??"").localeCompare(String(R[h]??"")))},[n,r.allItems,c,e?.sort_by,e?.sort_dir]),d=(0,b.useRef)(u);d.current=u;let f=(0,b.useRef)(t.shouldReadUpdate);f.current=t.shouldReadUpdate;let m=(0,b.useRef)(r.refetch);return m.current=r.refetch,(0,b.useEffect)(()=>{if(!yc(e))return;let p=e,g=!1,_=!1,h=!1,y=0,v=new Map,R=()=>{let x=y;m.current().then(A=>{!g&&!A.isError&&y===x&&a({identity:i,upserts:{},deleted:new Set})})},T=x=>{y++,a(k=>{let E=k.identity===i?k:{identity:i,upserts:{},deleted:new Set},M={...E.upserts};return delete M[x],{identity:i,upserts:M,deleted:new Set(E.deleted).add(x)}});let A=v.get("__reconcile__");A&&clearTimeout(A),v.set("__reconcile__",setTimeout(()=>{v.delete("__reconcile__"),R()},250))},w=x=>{let A=v.get(x);A&&clearTimeout(A),v.set(x,setTimeout(()=>{v.delete(x),s.fetchQuery({queryKey:C.item(x),queryFn:()=>fr(x),staleTime:0}).then(k=>{if(!g){if(!k||!Qd(k,p)){let E=d.current.find(M=>M.path===x||M.id===k?.id);E&&T(E.path);return}a(E=>{let M=E.identity===i?E:{identity:i,upserts:{},deleted:new Set},q=new Set(M.deleted);return q.delete(x),{identity:i,upserts:{...M.upserts,[x]:k},deleted:q}})}}).catch(k=>console.warn("[useIncrementalItems] item read failed:",k))},250))},O=ie("vfs_change",x=>{if(!x||typeof x.path!="string"&&typeof x.old_path!="string")return;let A=typeof x.path=="string"?x.path:x.old_path,k=d.current.find(M=>M.path===A||M.path===x.old_path||x.item_id&&M.id===x.item_id),E=!!k;if(!(!me(A,p.scope)&&!me(x.old_path,p.scope)&&!E)&&!(x.item_type&&x.item_type!==p.type&&!E)&&!(p.parent_id&&x.parent_id&&x.parent_id!==p.parent_id&&!E)){if(k&&(A!==k.path||x.old_path&&x.old_path!==A||x.parent_id&&x.parent_id!==k.parent_id||x.item_type&&x.item_type!==p.type)){T(k.path);return}if(!k&&x.old_path&&x.old_path!==A&&me(A,p.scope)){y++,w(A);return}if(x.action==="insert")y++,w(A);else if(x.action==="move")y++,w(A);else if(x.action==="update"){if(!f.current?.(x,d.current))return;y++,w(A)}else x.action==="delete"&&T(k?.path??x.old_path??A)}}),K=ss(x=>{if(x!=="connected"){_&&(h=!0);return}_=!0,h&&(h=!1,R())});return()=>{g=!0,O(),K(),v.forEach(clearTimeout)}},[s,i]),{...r,allItems:u}}function Mc(e){X();let t=20,n=er({queryKey:["vfs",H()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>os(e,t,s),initialPageParam:0,getNextPageParam:(s,i,o)=>{if(!(s.items.length<t))return o+s.items.length},enabled:!!e});return{allItems:(0,b.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 Oc(e){return X(),$({queryKey:C.edges(e),queryFn:()=>cs(e),enabled:!!e})}function ws(e){return X(),$({queryKey:C.types(e),queryFn:()=>as(e)})}function Fc(e,t){let n=ws(t);return{...n,data:n.data?.get(e)??void 0}}function qc(e,t){X();let n=(0,b.useMemo)(()=>t?.arguments,[JSON.stringify(t?.arguments)]),r=t?.mode,s=t?.strategy,i=t?.width;return $({queryKey:[...C.openEnvelope(e,s),i],queryFn:async()=>{let o=await hr(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 _c={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 Nc(e){let t=ws(e),n=t.data??new Map;return(0,b.useMemo)(()=>({canHaveChildren:p=>n.get(p.item_type)?.is_container??!1,isScope:p=>n.get(p.item_type)?.is_scope??!1,isScopeType:p=>n.get(p)?.is_scope??!1,isContainerType:p=>n.get(p)?.is_container??!1,getTypeDefinition:p=>n.get(p),getTypeColor:p=>n.get(p)?.color??"gray",getTypeIcon:p=>n.get(p)?.icon??"File",getTypeDisplayName:p=>n.get(p)?.display_name??p,getKnownEdgeTypes:()=>Object.entries(_c).map(([p,g])=>({key:p,label:g})),getEdgeTypeLabel:p=>_c[p]??p.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function Qc(e,t,n){return X(),$({queryKey:C.memberFocus(e),queryFn:()=>fs(e,t,n),enabled:!!e})}function Dc(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return $({queryKey:C.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>mr(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function Uc(e,t=50,n=0){return $({queryKey:C.itemHistory(e,String(t),String(n)),queryFn:()=>ds(e,t,n),enabled:!!e})}function Kc(e,t=50,n=0){return X(),$({queryKey:C.recentActivity(e,String(t),String(n)),queryFn:()=>ls(e,t,n),enabled:!!e})}function Lc(){let[e,t]=(0,b.useState)(null),[n,r]=(0,b.useState)(!0),[s,i]=(0,b.useState)(null);return(0,b.useEffect)(()=>{let o=!1;return et().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 Dd=[];function bc(){if(typeof window>"u")return!1;let e=window.__FSAOS_CONFIG__?.embedToken;return typeof e=="function"||typeof e=="string"&&e.length>0}function Ud(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 jc(){let{user:e}=Ss(),t=(0,b.useSyncExternalStore)(oa,mi,mi),n=yt()?.principal_id??null,r=(0,b.useRef)(null),[s,i]=(0,b.useState)(null),[o,a]=(0,b.useState)(null);(0,b.useEffect)(()=>{if(n){a(null);return}if(!e?.id&&!bc()){a(null);return}let v=!1;return et().then(R=>{v||R.principal_id||a(new Error("Memberships require an authenticated principal"))}).catch(R=>{v||a(R instanceof Error?R:new Error(String(R)))}),()=>{v=!0}},[n,e?.id,t]);let c=$({queryKey:C.memberships(n??"anonymous"),queryFn:ms,enabled:!!n,staleTime:1e3*60*2}),u=c.data??Dd,d=(0,b.useMemo)(()=>u.filter(v=>v.isAccount!==!1&&!v.isSpace),[u]),f=(0,b.useMemo)(()=>{let v=new Set(d.map(T=>T.accountId)),R=T=>!T.subordinateTo||!v.has(T.subordinateTo);return[...d].sort((T,w)=>Number(R(w))-Number(R(T)))},[d]),m=(0,b.useSyncExternalStore)(Se,te,te),p=(0,b.useMemo)(()=>{let v=_e();return v?u.find(R=>R.accountId===v.id)??null:null},[m,u]),g=(0,b.useMemo)(()=>Ud(d),[d]);(0,b.useEffect)(()=>{if(!n){r.current=null;return}if(r.current!==n)if(i(null),f.length===1){let v=f[0];pe()||Nt($e(v)),Lt(v.accountId),v.personalSpacePath&&jt(v.personalSpacePath,R=>{let T=u.find(w=>w.accountId===R);return T?$e(T):null}).catch(i),r.current=n}else f.length>1&&(r.current=n)},[n,f,u]);let _=(0,b.useCallback)(async v=>{let R=u.find(O=>O.path===v);if(!R)throw new Error("Account membership is unavailable");let T=$e(R);pe()||Nt(T);let w=u.find(O=>O.accountId===pe()?.id);if(!w?.personalSpacePath)throw new Error("The home membership has no mount declaration location");await jt(w.personalSpacePath,O=>{let K=u.find(x=>x.accountId===O);return K?$e(K):null}),await wr(T),i(null),Lt(R.accountId)},[u]),h=(0,b.useCallback)(async v=>{let R=u.find(T=>T.path===v);if(!R)throw new Error("Scope membership is unavailable");await Ii($e(R))},[u]),y=(!!e?.id||bc())&&!n&&!o;return{accounts:f,switcherAccounts:g,allMemberships:u,currentAccount:p,mountedScope:null,switchAccount:_,mountScope:h,loading:y||c.isLoading,error:o??c.error??s}}function Bc(){X();let e=(0,b.useSyncExternalStore)($r,ir,ir),t=(0,b.useMemo)(()=>Ee(),[e]),n=_e(),r=(0,b.useMemo)(()=>t.filter(i=>i.kind==="space"&&(n?.kind==="account"||i.id===n?.id)),[t,n]),s=(0,b.useMemo)(()=>r.map(i=>i.id).sort(),[r]);return{mounts:t,selectedSpaces:r,readSpaceIds:s,homeAnchor:pe(),anchor:n,setAnchor:wr,replaceMounts:_s,mount:Ii,unmount:pc}}function Ss(){let[e,t]=(0,b.useState)(null),[n,r]=(0,b.useState)(null),[s,i]=(0,b.useState)(!0),o=(0,b.useRef)(null);(0,b.useEffect)(()=>{W.auth.getSession().then(({data:p,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(p?.session??null),t(p?.session?.user??null),i(!1)}).catch(p=>{console.warn("[useAuth] getSession threw, clearing stale session:",p?.message),W.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:m}}=W.auth.onAuthStateChange((p,g)=>{if(p==="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=m,()=>{m?.unsubscribe()}},[]);let a=(0,b.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}),[]),c=(0,b.useCallback)(async m=>W.auth.signUp({email:m.email,password:m.password,options:{data:m.metadata||{}}}),[]),u=(0,b.useCallback)(async()=>{await W.auth.signOut(),bn(),N().clear()},[]),d=(0,b.useCallback)(async m=>{let{error:p}=await W.auth.resetPasswordForEmail(m);if(p)throw p},[]),f=(0,b.useCallback)(async(m,p)=>{let{error:g}=await W.auth.signInWithOtp({email:m,options:p?{emailRedirectTo:p}:{emailRedirectTo:window.location.href}});if(g)throw g},[]);return{user:e,session:n,loading:s,signIn:a,signUp:c,signOut:u,resetPassword:d,signInWithMagicLink:f}}function $c(e){let[t,n]=(0,b.useState)(null),[r,s]=(0,b.useState)(!1),[i,o]=(0,b.useState)(null);return(0,b.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),P("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 vs={};se(()=>{for(let e of Object.keys(vs))delete vs[e]});var Vc=null;function Wc(e){Vc=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function Kd(e){switch(e){case"react":return typeof window<"u"&&window.React||b.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||qd;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}:Nd;case"@fsaos/gateway":case"@fsaos/react":case"@ai4b-team/fsaos-gateway-sdk":return typeof window<"u"&&window.__FSAOS_GATEWAY__||Vc||{};case"@fsaos/ui":case"@ai4b-team/fsaos-gateway-sdk/ui":return typeof window<"u"&&window.__FSAOS_UI__||Ei;case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}var xr={};async function Ld(e){try{let t=await fetch(e);if(!t.ok)return null;let n=await t.text();return!n.trim()||n.includes("No CSS bundle for this component")?null:n}catch{return null}}async function Hc(e,t=()=>Ld(e)){let n=xr[e];n||(n=xr[e]={users:0,text:t(),style:null}),n.users+=1;let r=await n.text;if(xr[e]!==n||n.users===0||n.style||!r||typeof document>"u")return;let s=document.createElement("style");s.setAttribute("data-fsaos-component-css",e),s.textContent=r,document.head.appendChild(s),n.style=s}function Ve(e){let t=xr[e];t&&(t.users-=1,!(t.users>0)&&(t.style?.remove(),delete xr[e]))}function Gc(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)(Kd),o=t??i;return o?o.default||o:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function qi(e,t){let[n,r]=(0,b.useState)(null),[s,i]=(0,b.useState)(!0),[o,a]=(0,b.useState)(null),c=(0,b.useRef)(null),u=Number.isSafeInteger(t?.version)&&t.version>0?t.version:null;return(0,b.useEffect)(()=>{if(!e)return;let d=!1;a(null),c.current?.path!==e&&(c.current?.cssUrl&&Ve(c.current.cssUrl),c.current=null,r(null),i(!0));let m=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{let p=null;try{let g=1,_=e+"@v1",h=m+e+"/__bundle.js";if(u!==null)g=u,_=e+"@v"+g,h=m+e+"/__bundle.v"+g+".js";else try{let w=await fetch(m+e+"/__meta",{cache:"no-store"});w.ok&&(g=(await w.json()).version||1,_=e+"@v"+g,h=m+e+"/__bundle.v"+g+".js")}catch{h=m+e+"/__bundle.js?v="+Date.now()}if(d)return;let y=h.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");p=y;let v=Hc(y),R=vs[_];if(!R){let w=await fetch(h);if(!w.ok)throw new Error(`Failed to fetch bundle: ${w.status} ${w.statusText} (${h})`);let O=await w.text();if(R=Gc(O),!R)throw new Error("Bundle did not export a component. Expected window.__FSAOS_COMPONENT__ (FSAOS build) or a __FSAOS_REGISTER__(Component) call.");if(typeof R!="function")throw new Error(`Bundle export is not a React component (got ${typeof R})`);vs[_]=R}if(await v,d){Ve(y);return}let T=c.current?.cssUrl??null;c.current={path:e,cssUrl:y},p=null,r(()=>R),i(!1),T&&Ve(T)}catch(g){p&&Ve(p),d||(a(g instanceof Error?g:new Error(String(g))),i(!1))}})(),()=>{d=!0}},[e,u]),(0,b.useEffect)(()=>()=>{c.current?.cssUrl&&Ve(c.current.cssUrl),c.current=null},[]),{Component:n,loading:s,error:o}}var jd=/^embed\/bundle-[A-Za-z0-9_-]+\.js$/,Bd=/^embed\/bundle-[A-Za-z0-9_-]+\.css$/;function vc(e,t,n){let r=Object.keys(e).filter(o=>t.test(o));if(r.length>1)throw new Error(`The published release has more than one in-app ${n}.`);let s=r[0];if(!s)return null;let i=St(e[s]).sha256;return typeof i=="string"&&i?{path:s,sha256:i}:null}var Sr=new Map,ki=new Map;se(()=>{Sr.clear(),ki.clear()});function St(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function zc(e){let t=St(St(e.type_data).published),n=t.published_release_item_id,r=t.published_version;return typeof n!="string"||!n||typeof r!="number"||!Number.isSafeInteger(r)||r<1?null:{releaseItemId:n,version:r}}async function wc(e,t,n){let r=await hr(e.path,{mode:"render"}),s=St(St(r.render).props).url;if(typeof s!="string"||!s)throw new Error(`The published ${n} could not be opened.`);let i=await fetch(s);if(!i.ok)throw new Error(`Failed to read the published ${n}: ${i.status} ${i.statusText}`.trim());let o=await i.arrayBuffer();if(Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",o))).map(c=>c.toString(16).padStart(2,"0")).join("")!==t)throw new Error(`The published ${n} does not match the bytes its release sealed.`);return new TextDecoder().decode(o)}async function $d(e,t,n){let r=await dr(t);if(!r)throw new Error("The published release could not be read.");let s=St(r.type_data);if(r.item_type!=="revdev_release"||s.component_item_id!==e||s.status!=="committed"||Number(s.version)!==n)throw new Error("This component's live version does not match its release record.");let i=St(s.artifacts),o=vc(i,jd,"script");if(!o)return{status:"no_in_app_version",releaseItemId:t,version:n};let a=vc(i,Bd,"stylesheet"),c=a?[o.path,a.path]:[o.path],u=s.build_item_id;if(typeof u!="string"||!u)throw new Error("The published release names no build.");let{items:d}=await Kt({type:"file",parent_id:u,field_in:{package_path:c},limit:c.length},{throwOnError:!0}),f=h=>d.find(y=>St(y.type_data).package_path===h),m=f(o.path),p=a?f(a.path):void 0;if(!m||a&&!p)throw new Error("The published release's in-app files could not be found in its build.");let[g,_]=await Promise.all([wc(m,o.sha256,"script"),p&&a?wc(p,a.sha256,"stylesheet"):Promise.resolve(null)]);return{status:"ready",releaseItemId:t,version:n,script:g,stylesheet:_?.trim()?_:null}}function Jc(e,t,n){let r=Sr.get(t);return r||(r=$d(e,t,n),Sr.set(t,r),r.catch(()=>{Sr.get(t)===r&&Sr.delete(t)})),r}function Yc(e){let t=zc(e);return!e.id||!t?Promise.resolve({status:"unpublished"}):Jc(e.id,t.releaseItemId,t.version)}function Zc(e){let[t,n]=(0,b.useState)(null),[r,s]=(0,b.useState)("loading"),[i,o]=(0,b.useState)(null),a=(0,b.useRef)(null),c=e!=null,u=e?.id||null,d=e?zc(e):null,f=d?.releaseItemId??null,m=d?.version??null;return(0,b.useEffect)(()=>{if(!c)return;let p=()=>{a.current?.cssKey&&Ve(a.current.cssKey),a.current=null,n(null)};if(!u||!f||m===null){p(),o(null),s("unpublished");return}let g=!1;return o(null),a.current&&a.current.componentId!==u&&p(),a.current||s("loading"),(async()=>{let _=null;try{let h=await Jc(u,f,m);if(g)return;if(h.status!=="ready"){p(),s(h.status);return}let y=ki.get(f);if(!y){if(y=Gc(h.script),!y)throw new Error("The published script did not hand over a component. Expected a __FSAOS_REGISTER__(Component) call or window.__FSAOS_COMPONENT__.");if(typeof y!="function")throw new Error(`The published script handed over something that is not a React component (${typeof y}).`);ki.set(f,y)}let v=h.stylesheet?`release:${f}`:null;if(v&&(_=v,await Hc(v,async()=>h.stylesheet)),g){_&&Ve(_);return}let R=a.current?.cssKey??null;a.current={componentId:u,releaseItemId:f,cssKey:v},_=null,n({Component:y,version:m}),s("ready"),R&&Ve(R)}catch(h){if(_&&Ve(_),g)return;o(h instanceof Error?h:new Error(String(h))),a.current||s("error")}})(),()=>{g=!0}},[c,u,f,m]),(0,b.useEffect)(()=>()=>{a.current?.cssKey&&Ve(a.current.cssKey),a.current=null},[]),{Component:t?.Component??null,status:r,error:i,version:t?.version??null}}var Vd=["--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 Xc(){return{data:(0,b.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let t={},n=getComputedStyle(document.documentElement);return Vd.forEach(r=>{t[r]=n.getPropertyValue(r).trim()}),{tokens:t}},[]),loading:!1,error:null}}function eu(e,t){return{data:{allowed:!0},loading:!1,error:null}}function tu(e,t){let n={};return(t||[]).forEach(r=>{n[r]=!0}),{data:n,loading:!1,error:null}}var de=null,Mn=null,Mi=new Set;function Wd(){Mi.forEach(e=>e())}se(()=>{de=null,Mn=null});async function nu(e){let t={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null},n=yt()?.principal_id??null;if(n){if(de&&de.principalId===n){let{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}=de;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(de&&de.authUserId===r){let{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}=de;return{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}}return Mn||(Mn=(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(f=>f.path);a=d.find(f=>f.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 de={authUserId:r,...c},c}finally{Mn=null}})(),Mn)}async function ru(e){return(await nu(e)).principalId}function su(){let e=Ss(),t=e.user,n=de?.authUserId===t?.id?de:null,[r,s]=(0,b.useState)(n),i=(0,b.useRef)(null);return(0,b.useEffect)(()=>{let o=()=>{let a=de;a&&a.authUserId===t?.id&&s({principalId:a.principalId,displayName:a.displayName,createdAt:a.createdAt,metadata:a.metadata,vfsPath:a.vfsPath})};return Mi.add(o),()=>{Mi.delete(o)}},[t?.id]),(0,b.useEffect)(()=>{if(!t?.id){s(null),i.current=null;return}i.current===t.id&&r?.principalId!=null||(i.current=t.id,nu(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 iu(e){let{path:t,...n}=e,r=qi(t),s=r.Component,{loading:i,error:o}=r;return i?(0,b.createElement)("div",{className:"fsaos-loading"},""):o?(0,b.createElement)("div",{className:"fsaos-error"},"Failed to load component"):s?(0,b.createElement)(s,n):null}function ou(e){return e.children}function au(e){let t=X(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=e,o=i!==void 0?i&&!!n:!!n,a=(0,b.useMemo)(()=>C.channelMessages(n??"",r),[n,r,t]),c=L(),u=(0,b.useRef)(null),d=$({queryKey:a,queryFn:()=>ps(n,r),enabled:o});(0,b.useEffect)(()=>{if(!s||!o)return;let _=ie("vfs_change",()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{be(c,a,{exact:!0})},500)},h=>{let y=c.getQueryData(a);return Ai(h,n,r,[...y?.messages??[],...y?.activityMessages??[]])});return()=>{_(),u.current&&clearTimeout(u.current)}},[s,o,n,r,a,c]);let f=d.data,m=f?.messages??[],p=f?.messageCards??new Map,g=f?.siblingCards??[];return{messages:m,activityMessages:f?.activityMessages??[],messageCards:p,siblingCards:g,threads:(0,b.useMemo)(()=>m.filter(_=>_.reply_count>0),[m]),breakouts:(0,b.useMemo)(()=>m.filter(_=>_.member_count>0),[m]),isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,refetch:d.refetch}}function cu(e){X();let{channelPath:t,parentMessageId:n,limit:r=50,realtime:s=!0,enabled:i=!0,conversationsOnly:o=!1,transcriptOnly:a=!1}=e,c=!!n,u=i&&!!t,d=er({queryKey:[...C.channelMessages(t||"",n),"infinite",r,"latest-first",...o?["conversations"]:[],...a?["transcript"]:[]],queryFn:async({pageParam:y})=>gr(t,{parentMessageId:n,limit:r,conversationsOnly:o,transcriptOnly:a,before_seq:y?.before_seq,after_seq:y?.after_seq}),initialPageParam:void 0,getPreviousPageParam:y=>{if(!c||y.messages.length<r)return;let v=y.messages[y.messages.length-1]?.seq;return v==null?void 0:{after_seq:v}},getNextPageParam:y=>{if(y.messages.length<r)return;let v=y.messages[0]?.seq;return v==null?void 0:{before_seq:v}},enabled:u}),f=(0,b.useMemo)(()=>{if(!d.data?.pages)return[];let y=new Set,v=[];for(let R of d.data.pages)for(let T of R.messages)y.has(T.id)||(y.add(T.id),v.push(T));return v.sort((R,T)=>R.seq-T.seq)},[d.data?.pages]),{messageCards:m,siblingCards:p}=(0,b.useMemo)(()=>{let y=new Map,v=[];if(!d.data?.pages)return{messageCards:y,siblingCards:v};let R=new Set;for(let T of d.data.pages){for(let[w,O]of T.messageCards)for(let K of O){if(R.has(K.id))continue;R.add(K.id);let x=y.get(w)||[];x.push(K),y.set(w,x)}for(let w of T.siblingCards)R.has(w.id)||(R.add(w.id),v.push(w))}return{messageCards:y,siblingCards:v}},[d.data?.pages]),g=L(),_=(0,b.useRef)(null),h=(0,b.useMemo)(()=>[...C.channelMessages(t||"",n),"infinite",r,"latest-first",...o?["conversations"]:[],...a?["transcript"]:[]],[t,n,r,o,a]);return(0,b.useEffect)(()=>{if(!s||!t||!u)return;let y=()=>void be(g,h,{exact:!0}),v=!1,R=!1,T=!1,w=async()=>{if(o||a){y();return}let x=g.getQueryData(h);if(!x?.pages?.length){y();return}let A=0;for(let k of x.pages)for(let E of k.messages)E.seq>A&&(A=E.seq);if(A===0){y();return}try{let k=await gr(t,{parentMessageId:n,limit:r,after_seq:A});if(k.messages.length===0&&k.siblingCards.length===0){y();return}if(k.messages.length>0){let E=Math.min(...k.messages.map(M=>M.seq));if(E>A+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${A}, minNewSeq=${E}. Triggering full refetch.`),y();return}}g.setQueryData(h,E=>{if(!E)return E;let M=[...E.pages],q=0,U=M[q],V=new Set(U.messages.map(Pe=>Pe.id)),Re=k.messages.filter(Pe=>!V.has(Pe.id)),ne=[...U.messages,...Re].sort((Pe,ks)=>Pe.seq-ks.seq),xt=new Map(U.messageCards);for(let[Pe,ks]of k.messageCards){let Xi=xt.get(Pe)||[],xl=new Set(Xi.map(Ms=>Ms.id)),Rl=ks.filter(Ms=>!xl.has(Ms.id));xt.set(Pe,[...Xi,...Rl])}let vl=new Set(U.siblingCards.map(Pe=>Pe.id)),wl=k.siblingCards.filter(Pe=>!vl.has(Pe.id)),Sl=[...U.siblingCards,...wl];return M[q]={...U,activityMessages:k.activityMessages??[],messages:ne,messageCards:xt,siblingCards:Sl},{...E,pages:M}})}catch(k){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",k),y()}},O=async()=>{if(v){R=!0;return}v=!0;try{do R=!1,await w();while(R&&!T)}finally{v=!1}},K=ie("vfs_change",()=>{_.current&&clearTimeout(_.current),_.current=setTimeout(()=>{O()},500)},x=>(o||a)&&x?.item_type==="message"&&(g.getQueryData(h)?.pages??[]).some(A=>A.messages.some(k=>k.id===x.parent_id))||Ai(x,t,n,g.getQueryData(h)?.pages.flatMap(A=>A.messages)??[]));return()=>{T=!0,K(),_.current&&clearTimeout(_.current)}},[s,t,u,h,g,n,r,o,a]),{messages:f,activityMessages:d.data?.pages[0]?.activityMessages??[],messageCards:m,siblingCards:p,threads:f.filter(y=>y.reply_count>0),breakouts:f.filter(y=>y.member_count>0),isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,refetch:d.refetch,hasPreviousPage:d.hasNextPage??!1,fetchPreviousPage:d.fetchNextPage,isFetchingPreviousPage:d.isFetchingNextPage??!1,hasNextPage:d.hasPreviousPage??!1,fetchNextPage:d.fetchPreviousPage,isFetchingNextPage:d.isFetchingPreviousPage??!1}}var uu=["open","active","strict","hand_raise"];function Hd(e){return e==="open"||e==="active"||e==="strict"||e==="hand_raise"?e:e==="on"||e==="auto"?"active":"strict"}function Gd(e){if(Array.isArray(e))return e.filter(t=>typeof t=="string")}function Sc(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:Hd(t.ai_mode),activeAgentIds:Gd(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 xs(e={}){let t=X(),{realtime:n=!0,enabled:r=!0,includeArchived:s=!1}=e,i=L(),o=(0,b.useMemo)(()=>C.channels("all"),[t]),a=$({queryKey:o,queryFn:async()=>((await P("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(Sc),enabled:r});return(0,b.useEffect)(()=>{if(!(!n||!r))return gc(i,o,Sc)},[n,r,o,i]),{channels:(0,b.useMemo)(()=>(a.data??[]).filter(u=>s||!u.isArchived),[a.data,s]),isLoading:a.isLoading,isFetching:a.isFetching,error:a.error,refetch:a.refetch}}function lu(e={}){let t=xs(e),n=(0,b.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function du(e={}){let t=xs(e),n=(0,b.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function Ni(e={}){let t=X(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=e,o=L(),a=(0,b.useRef)(null),c=(0,b.useMemo)(()=>C.notifications(n,r),[n,r,t]),u=$({queryKey:c,queryFn:async()=>{let f={limit:r};return n==="unread"&&(f.filter="unread"),(await P("get-notifications",f)).notifications||[]},enabled:i});return(0,b.useEffect)(()=>{if(!s||!i)return;let f=["vfs_change","ccm_change"].map(m=>ie(m,()=>{a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{o.invalidateQueries({queryKey:c})},2e3)},p=>p.item_type==="notification"&&bs(p)));return()=>{f.forEach(m=>m()),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 fu(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:o,error:a,refetch:c}=Ni({filter:"unread",limit:200,realtime:n,enabled:r}),u=(0,b.useMemo)(()=>{let p=new Map;for(let g of s)g.is_unread&&g.channel_id&&p.set(g.channel_id,(p.get(g.channel_id)||0)+1);return p},[s]),d=(0,b.useMemo)(()=>{let p=0;return u.forEach(g=>{p+=g}),p},[u]),{dmUnread:f,channelUnread:m}=(0,b.useMemo)(()=>{if(!t)return{dmUnread:0,channelUnread:0};let p=new Set(t.filter(h=>h.isDm).map(h=>h.id)),g=0,_=0;return u.forEach((h,y)=>{p.has(y)?g+=h:_+=h}),{dmUnread:g,channelUnread:_}},[t,u]);return{unreadByChannel:u,totalUnread:d,dmUnread:f,channelUnread:m,isLoading:i,isFetching:o,error:a,refetch:c}}function pu(){let e=L();return ee({mutationFn:t=>P("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:C.children(r)})}})}function mu(){let e=L();return ee({mutationFn:t=>P("update",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.invalidateQueries({queryKey:C.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:C.children(i)})}}})}function hu(){return ee({mutationFn:e=>P("update-principal",e),onSuccess:(e,t)=>{if(!de)return;let n=e&&typeof e=="object"&&e.metadata?e.metadata:{...de.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}:{}};de={...de,displayName:typeof t.display_name=="string"?t.display_name:de.displayName,metadata:n},Wd()}})}function gu(){let e=L();return ee({mutationFn:t=>P("delete",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.removeQueries({queryKey:C.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:C.children(i)})}}})}function yu(){let e=L();return ee({mutationFn:t=>P("move",t),onSuccess:(t,n)=>{let r=n.path,s=n.new_parent_path;if(r){e.invalidateQueries({queryKey:C.item(r)});let i=r.split("/");i.pop();let o=i.join("/");o&&e.invalidateQueries({queryKey:C.children(o)})}s&&e.invalidateQueries({queryKey:C.children(s)})}})}function _u(){let e=L();return ee({mutationFn:t=>P("link",t),onSuccess:(t,n)=>{let r=n.source_id,s=n.target_id;r&&e.invalidateQueries({queryKey:C.edges(r)}),s&&e.invalidateQueries({queryKey:C.edges(s)})}})}function bu(e,t){let n=L(),{optimistic:r,...s}=t??{};return ee({mutationFn:i=>P(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 vu(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,b.useRef)(s),c=(0,b.useRef)(i);(0,b.useEffect)(()=>{a.current=s,c.current=i},[s,i]),(0,b.useEffect)(()=>o?ie(r,d=>a.current(d),c.current?d=>c.current(d):void 0):void 0,[r,o])}function wu(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:o=500}=e,a=L(),c=(0,b.useRef)(s);c.current=s;let u=(0,b.useRef)(null),d=$({queryKey:t,queryFn:n,enabled:i});return(0,b.useEffect)(()=>{if(!i)return;let f=ie(r,()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{be(a,t,{exact:!0})},o)},m=>c.current?.(m)??!0);return()=>{f(),u.current&&clearTimeout(u.current)}},[r,i,o,a,JSON.stringify(t)]),d}function On(e){X();let t=H(),n=(0,b.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 P("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}),a=o.data??null,c=(0,b.useMemo)(()=>a?.resolved_children??[],[a]),u=a?.resolution_level??null,d=(0,b.useMemo)(()=>{let p=(a?.type_data??null)?.order;return Array.isArray(p)?p:null},[a]),f=(0,b.useCallback)(m=>{if(!d||!m?.length)return m??[];let p=y=>y.id??y.name??"",g=new Map(d.map((y,v)=>[y,v])),_=[],h=[];for(let y of m)(g.has(p(y))?_:h).push(y);return _.sort((y,v)=>g.get(p(y))-g.get(p(v))),[..._,...h]},[d]);return{...o,arrangement:a,resolvedChildren:c,resolutionLevel:u,order:d,sourceScopeId:a?.scope_item_id??null,arrangementQueryKey:i,applyTo:f}}function Su(e){let{origin:t,originField:n,fallbackUrl:r,mintError:s,scopeId:i,scopePath:o}=e,a=X(),c=yt(),u=i??c?.scope_id??null,d=(0,b.useMemo)(()=>{if(!t)return null;let w="/accounts/",O=t.indexOf(w);if(O===-1)return null;let K=t.indexOf("/",O+w.length);return K===-1?t:t.slice(0,K)},[t]),f=o??d??c?.scope_path??null,m=n?.trim()||null,p=`${a}
1
+ /* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-11-12T20:23:19.090Z */
2
+ "use strict";var __FSAOS_GATEWAY__=(()=>{var ql=Object.create;var jn=Object.defineProperty;var Nl=Object.getOwnPropertyDescriptor;var Ql=Object.getOwnPropertyNames;var Dl=Object.getPrototypeOf,Ul=Object.prototype.hasOwnProperty;var ao=e=>{throw TypeError(e)};var Kl=(e,t,n)=>t in e?jn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Bn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),co=(e,t)=>{for(var n in t)jn(e,n,{get:t[n],enumerable:!0})},uo=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ql(t))!Ul.call(e,s)&&s!==n&&jn(e,s,{get:()=>t[s],enumerable:!(r=Nl(t,s))||r.enumerable});return e};var Y=(e,t,n)=>(n=e!=null?ql(Dl(e)):{},uo(t||!e||!e.__esModule?jn(n,"default",{value:e,enumerable:!0}):n,e)),Ll=e=>uo(jn({},"__esModule",{value:!0}),e);var z=(e,t,n)=>Kl(e,typeof t!="symbol"?t+"":t,n),Ds=(e,t,n)=>t.has(e)||ao("Cannot "+n);var d=(e,t,n)=>(Ds(e,t,"read from private field"),n?n.call(e):t.get(e)),T=(e,t,n)=>t.has(e)?ao("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),S=(e,t,n,r)=>(Ds(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),F=(e,t,n)=>(Ds(e,t,"access private method"),n);var $n=(e,t,n,r)=>({set _(s){S(e,t,s,n)},get _(){return d(e,t,r)}});var ue=Bn((Af,lo)=>{lo.exports=React});var Lr=Bn((Em,$o)=>{$o.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var sa=Bn((sh,ra)=>{ra.exports={createClient:window.supabase.createClient}});var Fa=Bn((Sh,Oa)=>{Oa.exports=ReactDOM});var Ju=Bn((wy,zu)=>{zu.exports=ReactDOM});var io={};co(io,{CHANNEL_AI_MODES:()=>_u,ComponentRenderer:()=>mu,EnforcementDeniedError:()=>Fe,FormSubmissionError:()=>Hn,GatewayRequestError:()=>he,HostSessionUnavailableError:()=>Kt,InteractionTrackingError:()=>Kn,KernelProvider:()=>hu,QueryClientProvider:()=>rr,acceptInvite:()=>Ji,answerInput:()=>Xi,assignPersonalSection:()=>El,auth:()=>ol,awaitAnchorReady:()=>cr,awaitScopeReady:()=>ga,callTool:()=>rl,cancelQueuedTurn:()=>Wu,cancelTurn:()=>$u,clearCachedToken:()=>fi,clearSession:()=>vi,configureGatewayReads:()=>Ta,connectHostSession:()=>_a,createAgent:()=>Zi,createItem:()=>el,disconnectSSE:()=>Mi,disposeVfsRealtimeWs:()=>Fi,electHomeAnchor:()=>Dt,emitEvent:()=>tc,fetchChannelMessages:()=>dc,fetchChannelMessagesPage:()=>vr,fetchChannelMessagesWithCards:()=>_s,fetchEdgesForItem:()=>ps,fetchItemHistory:()=>gs,fetchItemVersions:()=>_r,fetchItems:()=>Bt,fetchMemberFocus:()=>ys,fetchOpenEnvelope:()=>br,fetchRecentActivity:()=>hs,fetchResolvedItems:()=>to,fetchTimelineHistory:()=>no,fetchTurnQueueEntries:()=>cc,fetchTypeDefinitions:()=>fs,fetchVfsChildren:()=>yr,fetchVfsChildrenPage:()=>ds,fetchVfsItem:()=>gr,fetchVfsItemById:()=>hr,fetchVfsTree:()=>ms,gatewayCall:()=>C,getAccessToken:()=>tt,getAnchor:()=>_t,getAnchorRef:()=>de,getAnchorVersion:()=>hi,getAssetUrl:()=>il,getDefaultSort:()=>hl,getHomeAnchor:()=>me,getMountVersion:()=>ur,getMounts:()=>Ae,getPathSubscriptionState:()=>rc,getQueryClient:()=>N,getRequiredFormFields:()=>gl,getScope:()=>W,getScopeVersion:()=>ne,getServerClockOffsetMs:()=>xa,getServerClockSyncedAt:()=>Ra,getSessionEntry:()=>bt,hasServerClock:()=>Sa,initSession:()=>nt,initVfsRealtimeWs:()=>$t,initializeFsaos:()=>ju,initializeWorkspace:()=>ks,interpretSchema:()=>eo,invalidateAllVfs:()=>mc,invalidateChannelMessages:()=>gc,invalidateChildren:()=>ls,invalidateItem:()=>Oi,invalidateOpenEnvelope:()=>yc,invalidatePathAndParent:()=>fc,invalidateSubtree:()=>pc,invalidateTypes:()=>hc,inviteMember:()=>zi,isAnchorReady:()=>yi,isChannelPath:()=>ge,isListableItemsFilter:()=>On,isScopeReady:()=>Gr,itemsFilterFromQueryFilter:()=>uc,listChildren:()=>Xu,loadMounts:()=>Vt,loadPublishedBundle:()=>ou,mount:()=>al,mountRealtimeScope:()=>qn,normalizeItem:()=>Oe,onConnectionStateChange:()=>us,pathSubscriptionMatches:()=>Ii,personalSectionsKey:()=>kr,ping:()=>nc,pushChanges:()=>nl,queryClient:()=>La,readItem:()=>Zu,refreshQuery:()=>ve,registerCleanup:()=>se,replaceMounts:()=>xs,resetAllSdkState:()=>Rn,resolvePrincipalId:()=>fu,resubscribePath:()=>ic,seatMember:()=>Yi,selectMount:()=>Cr,serveHostSession:()=>Bu,serverDeadlinePassed:()=>Ca,serverMsUntil:()=>Pa,serverNow:()=>Yr,setAnchor:()=>xn,setCachedToken:()=>aa,setQueryClient:()=>Ka,setScope:()=>ha,setupRequireShim:()=>cl,signal:()=>sl,startTracking:()=>As,steerTurn:()=>Vu,submitForm:()=>Gu,subscribeAnchor:()=>gi,subscribeArtifactStream:()=>Ms,subscribeMounts:()=>Wr,subscribeScope:()=>xe,subscribeToEvents:()=>ie,subscribeToPath:()=>cs,subscribeToScope:()=>Mn,trackAction:()=>Ku,trackEvent:()=>Gt,trackPageView:()=>Uu,unmountRealtimeScope:()=>ws,updateItem:()=>tl,uploadFile:()=>_l,useAcceptInvite:()=>ll,useAccounts:()=>Yc,useAgentTimeline:()=>Rl,useAllChannels:()=>Ts,useAnswerInput:()=>pl,useArrangement:()=>Dn,useArtifactStream:()=>xl,useAsset:()=>Xc,useAuth:()=>Es,useChannelMessages:()=>gu,useChannels:()=>bu,useChildren:()=>qc,useComponent:()=>Hi,useCreate:()=>Su,useCreateAgent:()=>fl,useDelete:()=>Cu,useDmChannels:()=>vu,useEdges:()=>Hc,useEventStream:()=>Iu,useFileUpload:()=>vl,useIncrementalItems:()=>Kc,useInfiniteChannelMessages:()=>yu,useInfiniteChildren:()=>Lc,useInfiniteItems:()=>Li,useInviteMember:()=>ul,useItem:()=>Oc,useItemById:()=>Fc,useItemHistory:()=>Gc,useItemVersions:()=>Wc,useItems:()=>Uc,useLink:()=>Eu,useList:()=>Ki,useMemberFocus:()=>Vc,useMintedAsset:()=>ku,useMounts:()=>Zc,useMove:()=>Pu,useMutation:()=>Tu,useNotifications:()=>ji,useOpen:()=>Bc,usePermission:()=>uu,usePermissions:()=>lu,usePersonalItemOrder:()=>Ou,usePersonalSections:()=>Il,usePinnedItems:()=>Pl,usePrincipal:()=>pu,usePublishedComponent:()=>au,useRealtimeQuery:()=>Au,useRecentActivity:()=>zc,useResolve:()=>Dc,useResolvedItems:()=>Sl,useScope:()=>Jc,useScopeReady:()=>Mc,useSearch:()=>Qc,useSeatMember:()=>dl,useTheme:()=>cu,useTimelineHistory:()=>Cl,useTree:()=>Nc,useType:()=>jc,useTypeHelpers:()=>$c,useTypes:()=>Ps,useUnreadCounts:()=>wu,useUpdate:()=>xu,useUpdatePrincipal:()=>Ru,vfsKeys:()=>P,waitForPathReady:()=>sc});var Fe=class e extends Error{constructor(n){let r=n.message||e.fallbackMessage(n);super(r);z(this,"name","EnforcementDeniedError");z(this,"deniedBy");z(this,"ruleKey");z(this,"displayName");z(this,"payload");this.payload=n,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 Un=Y(ue(),1);var Ee=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 Pt,at,Jt,fo,Hl=(fo=class extends Ee{constructor(){super();T(this,Pt);T(this,at);T(this,Jt);S(this,Jt,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){d(this,at)||this.setEventListener(d(this,Jt))}onUnsubscribe(){var t;this.hasListeners()||((t=d(this,at))==null||t.call(this),S(this,at,void 0))}setEventListener(t){var n;S(this,Jt,t),(n=d(this,at))==null||n.call(this),S(this,at,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){d(this,Pt)!==t&&(S(this,Pt,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof d(this,Pt)=="boolean"?d(this,Pt):globalThis.document?.visibilityState!=="hidden"}},Pt=new WeakMap,at=new WeakMap,Jt=new WeakMap,fo),Yt=new Hl;var jl={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},ct,Us,po,Bl=(po=class{constructor(){T(this,ct,jl);T(this,Us,!1)}setTimeoutProvider(e){S(this,ct,e)}setTimeout(e,t){return d(this,ct).setTimeout(e,t)}clearTimeout(e){d(this,ct).clearTimeout(e)}setInterval(e,t){return d(this,ct).setInterval(e,t)}clearInterval(e){d(this,ct).clearInterval(e)}},ct=new WeakMap,Us=new WeakMap,po),De=new Bl;function mo(e){setTimeout(e,0)}var Ls=typeof window>"u"||"Deno"in globalThis;function Z(){}function yo(e,t){return typeof e=="function"?e(t):e}function Vn(e){return typeof e=="number"&&e>=0&&e!==1/0}function Mr(e,t){return Math.max(e+(t||0)-Date.now(),0)}function qe(e,t){return typeof e=="function"?e(t):e}function ye(e,t){return typeof e=="function"?e(t):e}function Or(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:o,stale:a}=e;if(o){if(r){if(t.queryHash!==Wn(o,t.options))return!1}else if(!Et(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 Fr(e,t){let{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Ue(t.options.mutationKey)!==Ue(i))return!1}else if(!Et(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function Wn(e,t){return(t?.queryKeyHashFn||Ue)(e)}function Ue(e){return JSON.stringify(e,(t,n)=>Ks(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function Et(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>Et(e[n],t[n])):!1}var $l=Object.prototype.hasOwnProperty;function Hs(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=ho(e)&&ho(t);if(!r&&!(Ks(e)&&Ks(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 l=0;l<a;l++){let f=r?l:o[l],m=e[f],p=t[f];if(m===p){c[f]=m,(r?l<i:$l.call(e,f))&&u++;continue}if(m===null||p===null||typeof m!="object"||typeof p!="object"){c[f]=p;continue}let g=Hs(m,p,n+1);c[f]=g,g===m&&u++}return i===a&&u===i?e:c}function Zt(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 ho(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Ks(e){if(!go(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!go(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function go(e){return Object.prototype.toString.call(e)==="[object Object]"}function _o(e){return new Promise(t=>{De.setTimeout(t,e)})}function Gn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Hs(e,t):t}function bo(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function vo(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Xt=Symbol();function qr(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Xt?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function en(e,t){return typeof e=="function"?e(...t):!!e}function wo(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 Ke=(()=>{let e=()=>Ls;return{isServer(){return e()},setIsServer(t){e=t}}})();function zn(){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=mo;function Vl(){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 j=Vl();var tn,ut,nn,xo,Wl=(xo=class extends Ee{constructor(){super();T(this,tn,!0);T(this,ut);T(this,nn);S(this,nn,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(){d(this,ut)||this.setEventListener(d(this,nn))}onUnsubscribe(){var t;this.hasListeners()||((t=d(this,ut))==null||t.call(this),S(this,ut,void 0))}setEventListener(t){var n;S(this,nn,t),(n=d(this,ut))==null||n.call(this),S(this,ut,t(this.setOnline.bind(this)))}setOnline(t){d(this,tn)!==t&&(S(this,tn,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return d(this,tn)}},tn=new WeakMap,ut=new WeakMap,nn=new WeakMap,xo),rn=new Wl;function Gl(e){return Math.min(1e3*2**e,3e4)}function js(e){return(e??"online")==="online"?rn.isOnline():!0}var Nr=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Qr(e){let t=!1,n=0,r,s=zn(),i=()=>s.status!=="pending",o=_=>{if(!i()){let h=new Nr(_);m(h),e.onCancel?.(h)}},a=()=>{t=!0},c=()=>{t=!1},u=()=>Yt.isFocused()&&(e.networkMode==="always"||rn.isOnline())&&e.canRun(),l=()=>js(e.networkMode)&&e.canRun(),f=_=>{i()||(r?.(),s.resolve(_))},m=_=>{i()||(r?.(),s.reject(_))},p=()=>new Promise(_=>{r=h=>{(i()||u())&&_(h)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),g=()=>{if(i())return;let _,h=n===0?e.initialPromise:void 0;try{_=h??e.fn()}catch(y){_=Promise.reject(y)}Promise.resolve(_).then(f).catch(y=>{if(i())return;let v=e.retry??(Ke.isServer()?0:3),R=e.retryDelay??Gl,E=typeof R=="function"?R(n,y):R,w=v===!0||typeof v=="number"&&n<v||typeof v=="function"&&v(n,y);if(t||!w){m(y);return}n++,e.onFail?.(n,y),_o(E).then(()=>u()?void 0:p()).then(()=>{t?m(y):g()})})};return{promise:s,status:()=>s.status,cancel:o,continue:()=>(r?.(),s),cancelRetry:a,continueRetry:c,canStart:l,start:()=>(l()?g():p().then(g),s)}}var Tt,Ro,Dr=(Ro=class{constructor(){T(this,Tt)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Vn(this.gcTime)&&S(this,Tt,De.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ke.isServer()?1/0:5*60*1e3))}clearGcTimeout(){d(this,Tt)!==void 0&&(De.clearTimeout(d(this,Tt)),S(this,Tt,void 0))}},Tt=new WeakMap,Ro);var It,sn,Te,At,oe,Jn,kt,Se,Io,We,Eo,To=(Eo=class extends Dr{constructor(t){super();T(this,Se);T(this,It);T(this,sn);T(this,Te);T(this,At);T(this,oe);T(this,Jn);T(this,kt);S(this,kt,!1),S(this,Jn,t.defaultOptions),this.setOptions(t.options),this.observers=[],S(this,At,t.client),S(this,Te,d(this,At).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,S(this,It,Po(this.options)),this.state=t.state??d(this,It),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return d(this,oe)?.promise}setOptions(t){if(this.options={...d(this,Jn),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=Po(this.options);n.data!==void 0&&(this.setState(Co(n.data,n.dataUpdatedAt)),S(this,It,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&d(this,Te).remove(this)}setData(t,n){let r=Gn(this.state.data,t,this.options);return F(this,Se,We).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){F(this,Se,We).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=d(this,oe)?.promise;return d(this,oe)?.cancel(t),n?n.then(Z).catch(Z):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return d(this,It)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>ye(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Xt||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>qe(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:!Mr(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),d(this,oe)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),d(this,oe)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),d(this,Te).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(d(this,oe)&&(d(this,kt)||F(this,Se,Io).call(this)?d(this,oe).cancel({revert:!0}):d(this,oe).cancelRetry()),this.scheduleGc()),d(this,Te).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||F(this,Se,We).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&d(this,oe)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(d(this,oe))return d(this,oe).continueRetry(),d(this,oe).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:()=>(S(this,kt,!0),r.signal)})},i=()=>{let c=qr(this.options,n),l=(()=>{let f={client:d(this,At),queryKey:this.queryKey,meta:this.meta};return s(f),f})();return S(this,kt,!1),this.options.persister?this.options.persister(c,l,this):c(l)},a=(()=>{let c={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:d(this,At),state:this.state,fetchFn:i};return s(c),c})();this.options.behavior?.onFetch(a,this),S(this,sn,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&F(this,Se,We).call(this,{type:"fetch",meta:a.fetchOptions?.meta}),S(this,oe,Qr({initialPromise:n?.initialPromise,fn:a.fetchFn,onCancel:c=>{c instanceof Nr&&c.revert&&this.setState({...d(this,sn),fetchStatus:"idle"}),r.abort()},onFail:(c,u)=>{F(this,Se,We).call(this,{type:"failed",failureCount:c,error:u})},onPause:()=>{F(this,Se,We).call(this,{type:"pause"})},onContinue:()=>{F(this,Se,We).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0}));try{let c=await d(this,oe).start();if(c===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(c),d(this,Te).config.onSuccess?.(c,this),d(this,Te).config.onSettled?.(c,this.state.error,this),c}catch(c){if(c instanceof Nr){if(c.silent)return d(this,oe).promise;if(c.revert){if(this.state.data===void 0)throw c;return this.state.data}}throw F(this,Se,We).call(this,{type:"error",error:c}),d(this,Te).config.onError?.(c,this),d(this,Te).config.onSettled?.(this.state.data,c,this),c}finally{this.scheduleGc()}}},It=new WeakMap,sn=new WeakMap,Te=new WeakMap,At=new WeakMap,oe=new WeakMap,Jn=new WeakMap,kt=new WeakMap,Se=new WeakSet,Io=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},We=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,...Bs(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...Co(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return S(this,sn,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),j.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),d(this,Te).notify({query:this,type:"updated",action:t})})},Eo);function Bs(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:js(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Co(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Po(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 _e,D,Zn,pe,Mt,on,Ge,lt,Xn,an,cn,Ot,Ft,dt,un,H,Yn,$s,Vs,Ws,Gs,zs,Js,Ys,Oo,Mo,er=(Mo=class extends Ee{constructor(t,n){super();T(this,H);T(this,_e);T(this,D);T(this,Zn);T(this,pe);T(this,Mt);T(this,on);T(this,Ge);T(this,lt);T(this,Xn);T(this,an);T(this,cn);T(this,Ot);T(this,Ft);T(this,dt);T(this,un,new Set);this.options=n,S(this,_e,t),S(this,lt,null),S(this,Ge,zn()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(d(this,D).addObserver(this),Ao(d(this,D),this.options)?F(this,H,Yn).call(this):this.updateResult(),F(this,H,Gs).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Zs(d(this,D),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Zs(d(this,D),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,F(this,H,zs).call(this),F(this,H,Js).call(this),d(this,D).removeObserver(this)}setOptions(t){let n=this.options,r=d(this,D);if(this.options=d(this,_e).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof ye(this.options.enabled,d(this,D))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");F(this,H,Ys).call(this),d(this,D).setOptions(this.options),n._defaulted&&!Zt(this.options,n)&&d(this,_e).getQueryCache().notify({type:"observerOptionsUpdated",query:d(this,D),observer:this});let s=this.hasListeners();s&&ko(d(this,D),r,this.options,n)&&F(this,H,Yn).call(this),this.updateResult(),s&&(d(this,D)!==r||ye(this.options.enabled,d(this,D))!==ye(n.enabled,d(this,D))||qe(this.options.staleTime,d(this,D))!==qe(n.staleTime,d(this,D)))&&F(this,H,$s).call(this);let i=F(this,H,Vs).call(this);s&&(d(this,D)!==r||ye(this.options.enabled,d(this,D))!==ye(n.enabled,d(this,D))||i!==d(this,dt))&&F(this,H,Ws).call(this,i)}getOptimisticResult(t){let n=d(this,_e).getQueryCache().build(d(this,_e),t),r=this.createResult(n,t);return Jl(this,r)&&(S(this,pe,r),S(this,on,this.options),S(this,Mt,d(this,D).state)),r}getCurrentResult(){return d(this,pe)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&d(this,Ge).status==="pending"&&d(this,Ge).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){d(this,un).add(t)}getCurrentQuery(){return d(this,D)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=d(this,_e).defaultQueryOptions(t),r=d(this,_e).getQueryCache().build(d(this,_e),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return F(this,H,Yn).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),d(this,pe)))}createResult(t,n){let r=d(this,D),s=this.options,i=d(this,pe),o=d(this,Mt),a=d(this,on),u=t!==r?t.state:d(this,Zn),{state:l}=t,f={...l},m=!1,p;if(n._optimisticResults){let A=this.hasListeners(),k=!A&&Ao(t,n),I=A&&ko(t,r,n,s);(k||I)&&(f={...f,...Bs(l.data,t.options)}),n._optimisticResults==="isRestoring"&&(f.fetchStatus="idle")}let{error:g,errorUpdatedAt:_,status:h}=f;p=f.data;let y=!1;if(n.placeholderData!==void 0&&p===void 0&&h==="pending"){let A;i?.isPlaceholderData&&n.placeholderData===a?.placeholderData?(A=i.data,y=!0):A=typeof n.placeholderData=="function"?n.placeholderData(d(this,cn)?.state.data,d(this,cn)):n.placeholderData,A!==void 0&&(h="success",p=Gn(i?.data,A,n),m=!0)}if(n.select&&p!==void 0&&!y)if(i&&p===o?.data&&n.select===d(this,Xn))p=d(this,an);else try{S(this,Xn,n.select),p=n.select(p),p=Gn(i?.data,p,n),S(this,an,p),S(this,lt,null)}catch(A){S(this,lt,A)}d(this,lt)&&(g=d(this,lt),p=d(this,an),_=Date.now(),h="error");let v=f.fetchStatus==="fetching",R=h==="pending",E=h==="error",w=R&&v,O=p!==void 0,x={status:h,fetchStatus:f.fetchStatus,isPending:R,isSuccess:h==="success",isError:E,isInitialLoading:w,isLoading:w,data:p,dataUpdatedAt:f.dataUpdatedAt,error:g,errorUpdatedAt:_,failureCount:f.fetchFailureCount,failureReason:f.fetchFailureReason,errorUpdateCount:f.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:f.dataUpdateCount>u.dataUpdateCount||f.errorUpdateCount>u.errorUpdateCount,isFetching:v,isRefetching:v&&!R,isLoadingError:E&&!O,isPaused:f.fetchStatus==="paused",isPlaceholderData:m,isRefetchError:E&&O,isStale:Xs(t,n),refetch:this.refetch,promise:d(this,Ge),isEnabled:ye(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let A=x.data!==void 0,k=x.status==="error"&&!A,I=U=>{k?U.reject(x.error):A&&U.resolve(x.data)},M=()=>{let U=S(this,Ge,x.promise=zn());I(U)},q=d(this,Ge);switch(q.status){case"pending":t.queryHash===r.queryHash&&I(q);break;case"fulfilled":(k||x.data!==q.value)&&M();break;case"rejected":(!k||x.error!==q.reason)&&M();break}}return x}updateResult(){let t=d(this,pe),n=this.createResult(d(this,D),this.options);if(S(this,Mt,d(this,D).state),S(this,on,this.options),d(this,Mt).data!==void 0&&S(this,cn,d(this,D)),Zt(n,t))return;S(this,pe,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!d(this,un).size)return!0;let o=new Set(i??d(this,un));return this.options.throwOnError&&o.add("error"),Object.keys(d(this,pe)).some(a=>{let c=a;return d(this,pe)[c]!==t[c]&&o.has(c)})};F(this,H,Oo).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&F(this,H,Gs).call(this)}},_e=new WeakMap,D=new WeakMap,Zn=new WeakMap,pe=new WeakMap,Mt=new WeakMap,on=new WeakMap,Ge=new WeakMap,lt=new WeakMap,Xn=new WeakMap,an=new WeakMap,cn=new WeakMap,Ot=new WeakMap,Ft=new WeakMap,dt=new WeakMap,un=new WeakMap,H=new WeakSet,Yn=function(t){F(this,H,Ys).call(this);let n=d(this,D).fetch(this.options,t);return t?.throwOnError||(n=n.catch(Z)),n},$s=function(){F(this,H,zs).call(this);let t=qe(this.options.staleTime,d(this,D));if(Ke.isServer()||d(this,pe).isStale||!Vn(t))return;let r=Mr(d(this,pe).dataUpdatedAt,t)+1;S(this,Ot,De.setTimeout(()=>{d(this,pe).isStale||this.updateResult()},r))},Vs=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(d(this,D)):this.options.refetchInterval)??!1},Ws=function(t){F(this,H,Js).call(this),S(this,dt,t),!(Ke.isServer()||ye(this.options.enabled,d(this,D))===!1||!Vn(d(this,dt))||d(this,dt)===0)&&S(this,Ft,De.setInterval(()=>{(this.options.refetchIntervalInBackground||Yt.isFocused())&&F(this,H,Yn).call(this)},d(this,dt)))},Gs=function(){F(this,H,$s).call(this),F(this,H,Ws).call(this,F(this,H,Vs).call(this))},zs=function(){d(this,Ot)!==void 0&&(De.clearTimeout(d(this,Ot)),S(this,Ot,void 0))},Js=function(){d(this,Ft)!==void 0&&(De.clearInterval(d(this,Ft)),S(this,Ft,void 0))},Ys=function(){let t=d(this,_e).getQueryCache().build(d(this,_e),this.options);if(t===d(this,D))return;let n=d(this,D);S(this,D,t),S(this,Zn,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},Oo=function(t){j.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(d(this,pe))}),d(this,_e).getQueryCache().notify({query:d(this,D),type:"observerResultsUpdated"})})},Mo);function zl(e,t){return ye(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Ao(e,t){return zl(e,t)||e.state.data!==void 0&&Zs(e,t,t.refetchOnMount)}function Zs(e,t,n){if(ye(t.enabled,e)!==!1&&qe(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Xs(e,t)}return!1}function ko(e,t,n,r){return(e!==t||ye(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Xs(e,n)}function Xs(e,t){return ye(t.enabled,e)!==!1&&e.isStaleByTime(qe(t.staleTime,e))}function Jl(e,t){return!Zt(e.getCurrentResult(),t)}function ln(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 l=!1,f=g=>{wo(g,()=>t.signal,()=>l=!0)},m=qr(t.options,t.fetchOptions),p=async(g,_,h)=>{if(l)return Promise.reject();if(_==null&&g.pages.length)return Promise.resolve(g);let v=(()=>{let O={client:t.client,queryKey:t.queryKey,pageParam:_,direction:h?"backward":"forward",meta:t.options.meta};return f(O),O})(),R=await m(v),{maxPages:E}=t.options,w=h?vo:bo;return{pages:w(g.pages,R,E),pageParams:w(g.pageParams,_,E)}};if(s&&i.length){let g=s==="backward",_=g?Fo:ei,h={pages:i,pageParams:o},y=_(r,h);a=await p(h,y,g)}else{let g=e??i.length;do{let _=c===0?o[0]??r.initialPageParam:ei(r,a);if(c>0&&_==null)break;a=await p(a,_),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 ei(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 Fo(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function qo(e,t){return t?ei(e,t)!=null:!1}function No(e,t){return!t||!e.getPreviousPageParam?!1:Fo(e,t)!=null}var ti=class extends er{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:ln()})}getOptimisticResult(e){return e.behavior=ln(),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",l=s&&c==="forward",f=o&&c==="backward",m=s&&c==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:qo(t,n.data),hasPreviousPage:No(t,n.data),isFetchNextPageError:u,isFetchingNextPage:l,isFetchPreviousPageError:f,isFetchingPreviousPage:m,isRefetchError:a&&!u&&!f,isRefetching:i&&!l&&!m}}};var tr,Le,le,qt,He,ft,Qo,Do=(Qo=class extends Dr{constructor(t){super();T(this,He);T(this,tr);T(this,Le);T(this,le);T(this,qt);S(this,tr,t.client),this.mutationId=t.mutationId,S(this,le,t.mutationCache),S(this,Le,[]),this.state=t.state||ni(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){d(this,Le).includes(t)||(d(this,Le).push(t),this.clearGcTimeout(),d(this,le).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){S(this,Le,d(this,Le).filter(n=>n!==t)),this.scheduleGc(),d(this,le).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){d(this,Le).length||(this.state.status==="pending"?this.scheduleGc():d(this,le).remove(this))}continue(){return d(this,qt)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{F(this,He,ft).call(this,{type:"continue"})},r={client:d(this,tr),meta:this.options.meta,mutationKey:this.options.mutationKey};S(this,qt,Qr({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(o,a)=>{F(this,He,ft).call(this,{type:"failed",failureCount:o,error:a})},onPause:()=>{F(this,He,ft).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>d(this,le).canRun(this)}));let s=this.state.status==="pending",i=!d(this,qt).canStart();try{if(s)n();else{F(this,He,ft).call(this,{type:"pending",variables:t,isPaused:i}),d(this,le).config.onMutate&&await d(this,le).config.onMutate(t,this,r);let a=await this.options.onMutate?.(t,r);a!==this.state.context&&F(this,He,ft).call(this,{type:"pending",context:a,variables:t,isPaused:i})}let o=await d(this,qt).start();return await d(this,le).config.onSuccess?.(o,t,this.state.context,this,r),await this.options.onSuccess?.(o,t,this.state.context,r),await d(this,le).config.onSettled?.(o,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(o,null,t,this.state.context,r),F(this,He,ft).call(this,{type:"success",data:o}),o}catch(o){try{await d(this,le).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 d(this,le).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 F(this,He,ft).call(this,{type:"error",error:o}),o}finally{d(this,le).runNext(this)}}},tr=new WeakMap,Le=new WeakMap,le=new WeakMap,qt=new WeakMap,He=new WeakSet,ft=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),j.batch(()=>{d(this,Le).forEach(r=>{r.onMutationUpdate(t)}),d(this,le).notify({mutation:this,type:"updated",action:t})})},Qo);function ni(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var ze,Ne,nr,Uo,Ko=(Uo=class extends Ee{constructor(t={}){super();T(this,ze);T(this,Ne);T(this,nr);this.config=t,S(this,ze,new Set),S(this,Ne,new Map),S(this,nr,0)}build(t,n,r){let s=new Do({client:t,mutationCache:this,mutationId:++$n(this,nr)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){d(this,ze).add(t);let n=Ur(t);if(typeof n=="string"){let r=d(this,Ne).get(n);r?r.push(t):d(this,Ne).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(d(this,ze).delete(t)){let n=Ur(t);if(typeof n=="string"){let r=d(this,Ne).get(n);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&d(this,Ne).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=Ur(t);if(typeof n=="string"){let s=d(this,Ne).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=Ur(t);return typeof n=="string"?d(this,Ne).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){j.batch(()=>{d(this,ze).forEach(t=>{this.notify({type:"removed",mutation:t})}),d(this,ze).clear(),d(this,Ne).clear()})}getAll(){return Array.from(d(this,ze))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Fr(n,r))}findAll(t={}){return this.getAll().filter(n=>Fr(t,n))}notify(t){j.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){let t=this.getAll().filter(n=>n.state.isPaused);return j.batch(()=>Promise.all(t.map(n=>n.continue().catch(Z))))}},ze=new WeakMap,Ne=new WeakMap,nr=new WeakMap,Uo);function Ur(e){return e.options.scope?.id}var Je,pt,be,Ye,Ze,Kr,ri,Lo,si=(Lo=class extends Ee{constructor(t,n){super();T(this,Ze);T(this,Je);T(this,pt);T(this,be);T(this,Ye);S(this,Je,t),this.setOptions(n),this.bindMethods(),F(this,Ze,Kr).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let n=this.options;this.options=d(this,Je).defaultMutationOptions(t),Zt(this.options,n)||d(this,Je).getMutationCache().notify({type:"observerOptionsUpdated",mutation:d(this,be),observer:this}),n?.mutationKey&&this.options.mutationKey&&Ue(n.mutationKey)!==Ue(this.options.mutationKey)?this.reset():d(this,be)?.state.status==="pending"&&d(this,be).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||d(this,be)?.removeObserver(this)}onMutationUpdate(t){F(this,Ze,Kr).call(this),F(this,Ze,ri).call(this,t)}getCurrentResult(){return d(this,pt)}reset(){d(this,be)?.removeObserver(this),S(this,be,void 0),F(this,Ze,Kr).call(this),F(this,Ze,ri).call(this)}mutate(t,n){return S(this,Ye,n),d(this,be)?.removeObserver(this),S(this,be,d(this,Je).getMutationCache().build(d(this,Je),this.options)),d(this,be).addObserver(this),d(this,be).execute(t)}},Je=new WeakMap,pt=new WeakMap,be=new WeakMap,Ye=new WeakMap,Ze=new WeakSet,Kr=function(){let t=d(this,be)?.state??ni();S(this,pt,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},ri=function(t){j.batch(()=>{if(d(this,Ye)&&this.hasListeners()){let n=d(this,pt).variables,r=d(this,pt).context,s={client:d(this,Je),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{d(this,Ye).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{d(this,Ye).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{d(this,Ye).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{d(this,Ye).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(d(this,pt))})})},Lo);var je,Ho,jo=(Ho=class extends Ee{constructor(t={}){super();T(this,je);this.config=t,S(this,je,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??Wn(s,n),o=this.get(i);return o||(o=new To({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(o)),o}add(t){d(this,je).has(t.queryHash)||(d(this,je).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=d(this,je).get(t.queryHash);n&&(t.destroy(),n===t&&d(this,je).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){j.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return d(this,je).get(t)}getAll(){return[...d(this,je).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Or(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>Or(t,r)):n}notify(t){j.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){j.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){j.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},je=new WeakMap,Ho);var X,mt,ht,dn,fn,gt,pn,mn,Bo,ii=(Bo=class{constructor(e={}){T(this,X);T(this,mt);T(this,ht);T(this,dn);T(this,fn);T(this,gt);T(this,pn);T(this,mn);S(this,X,e.queryCache||new jo),S(this,mt,e.mutationCache||new Ko),S(this,ht,e.defaultOptions||{}),S(this,dn,new Map),S(this,fn,new Map),S(this,gt,0)}mount(){$n(this,gt)._++,d(this,gt)===1&&(S(this,pn,Yt.subscribe(async e=>{e&&(await this.resumePausedMutations(),d(this,X).onFocus())})),S(this,mn,rn.subscribe(async e=>{e&&(await this.resumePausedMutations(),d(this,X).onOnline())})))}unmount(){var e,t;$n(this,gt)._--,d(this,gt)===0&&((e=d(this,pn))==null||e.call(this),S(this,pn,void 0),(t=d(this,mn))==null||t.call(this),S(this,mn,void 0))}isFetching(e){return d(this,X).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return d(this,mt).findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return d(this,X).get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=d(this,X).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(qe(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return d(this,X).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=d(this,X).get(r.queryHash)?.state.data,o=yo(t,i);if(o!==void 0)return d(this,X).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return j.batch(()=>d(this,X).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return d(this,X).get(t.queryHash)?.state}removeQueries(e){let t=d(this,X);j.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=d(this,X);return j.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=j.batch(()=>d(this,X).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(Z).catch(Z)}invalidateQueries(e,t={}){return j.batch(()=>(d(this,X).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=j.batch(()=>d(this,X).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(Z)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Z)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=d(this,X).build(this,t);return n.isStaleByTime(qe(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Z).catch(Z)}fetchInfiniteQuery(e){return e.behavior=ln(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Z).catch(Z)}ensureInfiniteQueryData(e){return e.behavior=ln(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return rn.isOnline()?d(this,mt).resumePausedMutations():Promise.resolve()}getQueryCache(){return d(this,X)}getMutationCache(){return d(this,mt)}getDefaultOptions(){return d(this,ht)}setDefaultOptions(e){S(this,ht,e)}setQueryDefaults(e,t){d(this,dn).set(Ue(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...d(this,dn).values()],n={};return t.forEach(r=>{Et(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){d(this,fn).set(Ue(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...d(this,fn).values()],n={};return t.forEach(r=>{Et(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...d(this,ht).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Wn(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===Xt&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...d(this,ht).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){d(this,X).clear(),d(this,mt).clear()}},X=new WeakMap,mt=new WeakMap,ht=new WeakMap,dn=new WeakMap,fn=new WeakMap,gt=new WeakMap,pn=new WeakMap,mn=new WeakMap,Bo);var hn=Y(ue(),1),Vo=Y(Lr(),1),oi=hn.createContext(void 0),L=e=>{let t=hn.useContext(oi);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},rr=({client:e,children:t})=>(hn.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,Vo.jsx)(oi.Provider,{value:e,children:t}));var Hr=Y(ue(),1),Wo=Hr.createContext(!1),Go=()=>Hr.useContext(Wo),Im=Wo.Provider;var sr=Y(ue(),1),Yl=Y(Lr(),1);function Zl(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Xl=sr.createContext(Zl()),zo=()=>sr.useContext(Xl);var Jo=Y(ue(),1);var Yo=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?en(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Zo=e=>{Jo.useEffect(()=>{e.clearReset()},[e])},Xo=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||en(n,[e.error,r]));var ea=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))}},ta=(e,t)=>e.isLoading&&e.isFetching&&!t,na=(e,t)=>e?.suspense&&t.isPending,ai=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var yt=Y(ue(),1);function jr(e,t,n){let r=Go(),s=zo(),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",ea(o),Yo(o,s,a),Zo(s);let c=!i.getQueryCache().get(o.queryHash),[u]=yt.useState(()=>new t(i,o)),l=u.getOptimisticResult(o),f=!r&&e.subscribed!==!1;if(yt.useSyncExternalStore(yt.useCallback(m=>{let p=f?u.subscribe(j.batchCalls(m)):Z;return u.updateResult(),p},[u,f]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),yt.useEffect(()=>{u.setOptions(o)},[o,u]),na(o,l))throw ai(o,u,s);if(Xo({result:l,errorResetBoundary:s,throwOnError:o.throwOnError,query:a,suspense:o.suspense}))throw l.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(o,l),o.experimental_prefetchInRender&&!Ke.isServer()&&ta(l,r)&&(c?ai(o,u,s):a?.promise)?.catch(Z).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?l:u.trackResult(l)}function B(e,t){return jr(e,er,t)}var Xe=Y(ue(),1);function te(e,t){let n=L(t),[r]=Xe.useState(()=>new si(n,e));Xe.useEffect(()=>{r.setOptions(e)},[r,e]);let s=Xe.useSyncExternalStore(Xe.useCallback(o=>r.subscribe(j.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=Xe.useCallback((o,a)=>{r.mutate(o,a).catch(Z)},[r]);if(s.error&&en(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function ir(e,t){return jr(e,ti,t)}var ia=Y(sa(),1),gn=typeof window<"u"&&window.__FSAOS_CONFIG__||{},Nt=Array.isArray(gn.sources)?gn.sources:[],et=gn.hostSession===!0,ed=gn.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",td=gn.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",Ie=gn.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",V=(0,ia.createClient)(ed,td,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var or=null,Br=0,oa,di,$r=!1;oa=new Promise(e=>{di=e});V.auth.onAuthStateChange((e,t)=>{t?.access_token?(or=t.access_token,Br=t.expires_at??Math.floor(Date.now()/1e3)+3600):(or=null,Br=0),$r||($r=!0,di())});setTimeout(()=>{$r||($r=!0,di())},5e3);function aa(e,t){or=e,Br=t??Math.floor(Date.now()/1e3)+3600}function fi(){or=null,Br=0}async function tt(){let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{};if(et)return null;if(e.embedToken){if(typeof e.embedToken=="function")try{return await e.embedToken()??null}catch{return null}return e.embedToken}return await oa,or}var vn=null,wn=null,ca=0,ci=new Set,pi,ar,Sn=!1;pi=new Promise(e=>{ar=e});function mi(){ca++,ci.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function xn(e){let t=typeof e=="string"?e:e.path,n=vn!==t||wn?.id!==(typeof e=="string"?void 0:e.id);vn=t,wn=typeof e=="string"?null:e,typeof e!="string"&&!Qt.some(r=>r.id===e.id)&&(Qt=[...Qt,e],_i()),Sn||(Sn=!0,ar()),n&&mi()}function _t(){return vn}function de(){return wn}function hi(){return ca}function gi(e){return ci.add(e),()=>{ci.delete(e)}}function cr(){return pi}function yi(){return Sn}var Vr=null;function Dt(e,t={}){if(Vr){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}Vr=e,t.activate!==!1&&xn(e)}function me(){return Vr}var Qt=[],ui=new Set,ua=0;function _i(){ua++,ui.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function Ae(){return Qt}function ur(){return ua}function Wr(e){return ui.add(e),()=>{ui.delete(e)}}function la(e,t){let n=JSON.stringify(Qt)!==JSON.stringify(e),r=vn!==t.path||wn?.id!==t.id;Qt=e,vn=t.path,wn=t,Sn||(Sn=!0,ar()),n&&_i(),r&&mi()}var _n=null,yn=null,bn=0,li=new Set,da=0;function fa(){da++,li.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Session listener error:",t)}})}function ae(){return bn}function bi(){return da}function pa(e){return li.add(e),()=>{li.delete(e)}}async function nt(){if(_n)return _n;if(yn)return yn;let e=bn;return yn=(async()=>{let t=Ut(),n=await tt();if(e!==bn)throw new Error("Session changed during initialization");let r={};n&&(r.Authorization=`Bearer ${n}`);let s=await fetch(`${Ie}/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!==bn)throw new Error("Session changed during initialization");let o=i.entry||i;return _n={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},fa(),_n})().catch(t=>{throw e===bn&&(yn=null),t}),yn}function bt(){return _n}function vi(){bn++,_n=null,yn=null,vn=null,wn=null,Vr=null,Qt=[],fa()}var ma=[];function se(e){ma.push(e)}function Rn(){vi(),fi(),ar(),Sn=!1,pi=new Promise(e=>{ar=e}),mi(),_i();for(let e of ma)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function Ut(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var ha=xn,W=_t,ne=hi,xe=gi,ga=cr,Gr=yi;var Lt="host-session",nd=5e3;function wi(e){return typeof e=="object"&&e!==null&&e.fsaos===Lt&&typeof e.kind=="string"}var Kt=class extends Error{constructor(){super(...arguments);z(this,"name","HostSessionUnavailableError")}},zr=null,rd=0,Jr=new Map;function ya(){return zr||(zr=new Promise((e,t)=>{if(!et){t(new Kt("This page was not started with hostSession."));return}if(typeof window>"u"||!window.parent||window.parent===window){t(new Kt("This page is signed in only inside the app that frames it. Open it from there."));return}let n=window.parent,r=null,s=setTimeout(()=>{r===null&&(window.removeEventListener("message",i),t(new Kt("The window around this page did not sign it in. Open it from the app that owns it.")))},nd);function i(o){if(o.source!==n||!wi(o.data))return;let a=o.data;if(r===null){if(a.kind!=="welcome")return;r=o.origin,clearTimeout(s),a.anchor&&xn(a.anchor),e({host:n,origin:r,item:a.item??null});return}if(o.origin!==r||a.kind!=="result")return;let c=Jr.get(a.id);c&&(Jr.delete(a.id),c.resolve(a.ok?{ok:!0,response:a.response}:{ok:!1,error:a.error}))}window.addEventListener("message",i),n.postMessage({fsaos:Lt,kind:"hello"},"*")}),zr)}async function _a(){let{item:e}=await ya();return{item:e}}async function ba(e,t,n){if(n?.aborted)throw new DOMException("Read cancelled","AbortError");let{host:r,origin:s}=await ya();if(n?.aborted)throw new DOMException("Read cancelled","AbortError");let i=JSON.parse(JSON.stringify(t??{}));return new Promise((o,a)=>{let c=`${Date.now().toString(36)}-${(++rd).toString(36)}`,u=()=>{Jr.delete(c),a(new DOMException("Read cancelled","AbortError"))};Jr.set(c,{resolve:l=>{n?.removeEventListener("abort",u),o(l)}}),n?.addEventListener("abort",u,{once:!0}),r.postMessage({fsaos:Lt,kind:"call",id:c,method:e,params:i},s)})}var Si=0,va=!1,wa=0;function xi(e){if(typeof e!="string")return;let t=Date.parse(e);Number.isNaN(t)||(Si=t-Date.now(),va=!0,wa=Date.now())}function Yr(){return Date.now()+Si}function Sa(){return va}function xa(){return Si}function Ra(){return wa}function Ca(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Yr()>=t}function Pa(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Math.max(0,t-Yr())}var Cn,ke=new Map,Ht=[],Ri=0,Ci={foreground:0,normal:1,background:2},Zr=()=>performance.now(),Pi=()=>new DOMException("Read cancelled","AbortError");function Ta(e={}){Cn={concurrency:Math.max(1,Math.min(16,Math.floor(e.concurrency??6))),timeoutMs:Math.max(1e3,e.timeoutMs??15e3),onTiming:e.onTiming},es()}function Ia(){for(let e of ke.values()){e.controller.abort();for(let t of e.consumers)t.detach(),t.reject(Pi());e.consumers.clear(),e.timer&&clearTimeout(e.timer)}ke.clear(),Ht.length=0}function Aa(e,t){return e==="query"?!("materialize"in t):["read","list","search","resolve","resolve-items","get-channel-messages","list-memberships"].includes(e)}function Xr(e){return Array.isArray(e)?`[${e.map(Xr).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)}:${Xr(n)}`).join(",")}}`:JSON.stringify(e)}function ka(e,t,n,r){if(n.signal?.aborted)return Promise.reject(Pi());if(!Cn)return r(n.signal);let s=ke.get(e);if(s)Ci[n.priority??"normal"]<Ci[s.priority]&&(s.priority=n.priority??"normal");else{s={key:e,method:t,priority:n.priority??"normal",queuedAt:Zr(),controller:new AbortController,consumers:new Set,run:r},ke.set(e,s),Ht.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(),ke.get(a.key)===a&&ke.delete(a.key),Ea(a)},Cn.timeoutMs)}let i=s,o=new Promise((a,c)=>{let u=()=>{l.detach(),i.consumers.delete(l),c(Pi()),i.consumers.size||(i.controller.abort(),ke.get(i.key)===i&&ke.delete(i.key),Ea(i))},l={resolve:f=>a(structuredClone(f)),reject:c,detach:()=>n.signal?.removeEventListener("abort",u)};i.consumers.add(l),n.signal?.addEventListener("abort",u,{once:!0})});return es(),o}function Ea(e){let t=Ht.indexOf(e);t>=0&&(Ht.splice(t,1),ke.get(e.key)===e&&ke.delete(e.key),e.timer&&clearTimeout(e.timer)),es()}function es(){if(Cn)for(;Ri<Cn.concurrency&&Ht.length;){let e=r=>Ci[r.priority]-Math.floor((Zr()-r.queuedAt)/2e3);Ht.sort((r,s)=>e(r)-e(s)||r.queuedAt-s.queuedAt);let t=Ht.shift();if(!t.consumers.size)continue;Ri++,t.startedAt=Zr();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(),ke.get(t.key)===t&&ke.delete(t.key),Ri--;try{Cn?.onTiming?.({method:t.method,priority:t.priority,queueMs:Math.round(t.startedAt-t.queuedAt),requestMs:Math.round(Zr()-t.startedAt),outcome:n})}catch{}es()})}}se(Ia);var sd=new Set(["list-memberships","init"]),he=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);z(this,"name","GatewayRequestError");z(this,"method");z(this,"status");z(this,"statusText");z(this,"payload");z(this,"responseBody");this.method=n.method,this.status=n.status,this.statusText=n.statusText,this.payload=n.payload,this.responseBody=n.responseBody}};async function C(e,t={},n={}){if(et)return id(e,t,n);let r=ae(),s=_t(),i=Ut(),o=`${Ie}/d/${i}`,a={"Content-Type":"application/json"},c=await Ma(tt(),n.signal);if(r!==ae())throw new Error("Session changed before gateway request");if(c&&(a.Authorization=`Bearer ${c}`),!sd.has(e)&&!t._scope_path&&await Ma(cr(),n.signal),r!==ae())throw new Error("Session changed before gateway request");let u={...t},l=bt();!u.domain_scope_id&&l?.scope_id&&(u.domain_scope_id=l.scope_id);let f=s??_t();!u._scope_path&&f&&(u._scope_path=f);let m=async p=>{if(r!==ae())throw new Error("Session changed before queued gateway request");let g=await fetch(o,{method:"POST",signal:p,headers:a,body:JSON.stringify({method:e,params:u})}),_=await g.text();if(r!==ae())throw new Error("Session changed during gateway request");let h=null;if(_)try{h=JSON.parse(_)}catch{}if(!g.ok||!h)throw new he({method:e,status:g.status,statusText:g.statusText,payload:h,responseBody:_});if(h.success===!1){let y=h.error||"",v=h.denied_by||h.error_type||"";throw v==="rule"||v==="access"||v==="entitlement"||y==="RULE_DENIED"||y==="ACCESS_DENIED"||y==="PERMISSION_DENIED"||y==="ENTITLEMENT_REQUIRED"?new Fe(h):new he({method:e,status:g.status,statusText:g.statusText,payload:h,responseBody:_})}return h&&h.server_now!==void 0&&xi(h.server_now),h};return Aa(e,u)?ka(Xr([r,i,c,e,u]),e,n,m):m(n.signal)}async function id(e,t,n){let r=await ba(e,t,n.signal);if(r.ok){let o=r.response?.server_now;return o!==void 0&&xi(o),r.response}let s=r.error;if(s.kind==="denied")throw new Fe(s.payload);if(s.kind==="gateway")throw new he({method:s.method,status:s.status,statusText:s.statusText,payload:s.payload,responseBody:s.responseBody});let i=new Error(s.message);throw i.name=s.name,i}function Ma(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 b=Y(ue(),1),Gd=Y(Fa(),1),zd=Y(Lr(),1);var qa=new WeakMap;function ve(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(f=>f.promise?[f.promise]:[]);if(i.length===0)return s();let o=`${r?"=":"^"}${JSON.stringify(t)}`,a=qa.get(e);a||(a=new Map,qa.set(e,a));let c=a.get(o);if(c)return c;let u=a,l=Promise.allSettled(i).then(()=>(u.delete(o),s()));return u.set(o,l),l}function ge(e,t){return typeof e=="string"&&(e===t||e.startsWith(`${t}/`))}var ts=new WeakMap,Na=e=>e.meta?.arrangementRealtime===!0;function rt(e,t){let n=e.getQueryCache().find({queryKey:t,exact:!0});if(!n)return;let r=ts.get(e);r||(r=new Map,ts.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&&ve(e,t,{exact:!0})},250))}function Qa(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){if(!Na(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")&&rt(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)))&&rt(e,n.queryKey)}}function Da(e){for(let t of e.getQueryCache().getAll())Na(t)&&t.state.data!==void 0&&rt(e,t.queryKey)}function Ua(e){ts.get(e)?.forEach(clearTimeout),ts.delete(e)}var st=null;se(()=>{st&&(st.cancelQueries({queryKey:["vfs"]}),st.removeQueries({queryKey:["vfs"]}))});function Ka(e){if(st&&st!==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.");st=e}function N(){return st||(st=new ii({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),st}var La=new Proxy({},{get(e,t,n){let r=N(),s=r[t];return typeof s=="function"?s.bind(r):s}});var ns=new WeakMap;function Ei(e){return e.meta?.infiniteItemsRealtime?.filter}function od(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 ad(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 cd(e,t,n){if(od(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&&!ge(n.path,r)&&!ge(n.old_path,r))return!1;if(n.item_type==="symlink"&&s&&i)return!0;let o=ad(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 Ha(e,t){let n=ns.get(e);n||(n=new Map,ns.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||!Ei(t))&&ve(e,t.queryKey,{exact:!0})},500))}function ja(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){let r=Ei(n);r&&cd(n,r,t)&&Ha(e,n)}}function Ba(e){for(let t of e.getQueryCache().getAll())Ei(t)&&t.state.data!==void 0&&Ha(e,t)}function $a(e){ns.get(e)?.forEach(clearTimeout),ns.delete(e)}var rs=class extends Error{constructor(){super("The server did not confirm the selected-Space listing contract")}};function Va(e,t){if(!Array.isArray(t)||t.some(n=>typeof n!="string")||JSON.stringify([...new Set(t)].sort())!==JSON.stringify(e))throw new rs}function vt(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 Pn(e){return e instanceof rs||e instanceof Fe||e instanceof he&&(e.payload?.error==="SPACE_SELECTION_UNAVAILABLE"||e.payload?.error==="QUERY_PARAMS_INVALID"||e.status===401||e.status===403)}function ce(){return W()??"__unscoped__"}var P={all:()=>["vfs",ce()],item:e=>["vfs",ce(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",ce(),"children",e],allChildren:()=>["vfs",ce(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",ce(),"search",e,...t??[]],items:(e,t)=>["vfs",ce(),"items",e,JSON.stringify(vt(t??{}))],allItems:()=>["vfs",ce(),"items"],tree:(e,t)=>["vfs",ce(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",ce(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",ce(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",ce(),"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",ce(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",ce(),"channel-messages"],channels:e=>["vfs",ce(),"channels",e??"all"],allChannels:()=>["vfs",ce(),"channels"],notifications:(e,t)=>["vfs",ce(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",ce(),"notifications"],unreadCounts:()=>["vfs",ce(),"unread-counts"],memberships:e=>["memberships",e]};var ud=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function J(...e){ud&&console.log("[WS]",...e)}var Q=null,En=null,In=null,lr=0,ld=3e4,Wa=1e4,kn=!1,Ga=!1,Xa=3e4,dd=Xa*2+5e3,ss=0,is=null,za=!1;function fd(){fr(),ss=Date.now(),is=setInterval(()=>{if(Q&&Q.readyState===WebSocket.OPEN&&Date.now()-ss>dd){J("ping: no inbound traffic for",Date.now()-ss,"ms \u2014 closing half-open socket");try{Q.close(4e3,"liveness timeout")}catch{}return}ot({type:"ping"})},Xa)}function fr(){is&&(clearInterval(is),is=null)}function pd(){typeof document>"u"||(document.hidden?fr():dr()&&(J("Tab visible, reconnecting..."),jt()))}function md(){za||typeof document>"u"||(document.addEventListener("visibilitychange",pd),za=!0)}var Re={};function Ii(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return!n||!r?n===r:r===n||r.startsWith(`${n}/`)}var An=[],it=new Map,Tn=new Map,Me=new Map;function hd(e){let t=Tn.get(e);return t?Array.from(new Set(Array.from(t.values()).flatMap(n=>n.event_types))).sort():[]}function Ja(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):!1}function Ya(e){let t=hd(e);if(t.length===0)return it.delete(e),null;let n={scope_id:e,event_types:t};return it.set(e,n),n}var Be=new Map,wt=new Map,Ti="disconnected",os=[];function as(e){if(Ti!==e){Ti=e;for(let t of[...os])try{t(e)}catch{}}}function gd(e){Be.set(e,"ready");let t=wt.get(e);if(t){wt.delete(e);for(let n of t)n()}}function yd(){for(let e of Be.keys())Be.set(e,"disconnected")}function Ai(e,t){Be.set(e,"pending"),ot({type:"subscribe_path",path:e,event_types:t})}function _d(){return Object.keys(Re).some(t=>Re[t]&&Re[t].length>0)||An.length>0}function dr(){return it.size>0||Me.size>0}async function jt(){if(et){J("ensureConnection: the host holds the session, no realtime connection");return}if(!dr()){J("ensureConnection: no active subscriptions, skipping");return}if(Q&&Q.readyState===WebSocket.OPEN){J("ensureConnection: already open");return}if(En)return J("ensureConnection: connection already in flight, waiting..."),En;if(Q){J("ensureConnection: killing stale WS in state",Q.readyState);try{Q.close()}catch{}Q=null}return kn=!1,En=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=Ie,n=await tt();if(!n){J("ensureConnection: no token available, will retry"),Za();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)+"..."),as("connecting"),Q=new WebSocket(i);let o=Q;await new Promise((a,c)=>{if(!Q)return c(new Error("WebSocket not created"));let u=setTimeout(()=>{if(Q===o){if(J("ensureConnection: TIMEOUT after",Wa,"ms"),Q&&Q.readyState!==WebSocket.OPEN){try{Q.close()}catch{}Q=null}c(new Error("WebSocket connection timeout"))}},Wa);o.onopen=()=>{if(Q!==o)return;clearTimeout(u),J("ensureConnection: CONNECTED");let l=Ga;Ga=!0,lr=0,as("connected"),bd(l),(typeof document>"u"||!document.hidden)&&fd(),md(),a()},o.onmessage=l=>{Q===o&&vd(l.data)},o.onerror=()=>{J("ensureConnection: WS error event")},o.onclose=l=>{clearTimeout(u),Q===o&&(J("ensureConnection: WS closed, code:",l.code,"reason:",l.reason),Q=null,fr(),yd(),as("disconnected"),!kn&&dr()&&Za(),c(new Error(`WebSocket closed: ${l.code}`)))}})}catch(e){J("ensureConnection: failed -",e?.message||e)}finally{En=null}})(),En}function Za(){if(In||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,lr)+Math.random()*1e3,ld);lr++,J("scheduleReconnect: attempt",lr,"in",Math.round(e),"ms"),In=setTimeout(()=>{In=null,dr()&&jt()},e)}function bd(e=!1){for(let t of it.values())J("resubscribeAll: scope",t.scope_id),ot({type:"subscribe",scope_id:t.scope_id,event_types:t.event_types});for(let t of Me.values())J("resubscribeAll: path",t.path),Ai(t.path,t.event_types);e&&ec("reconnect")}function ec(e){try{let t=N();Ba(t),Da(t);for(let n of Me.values())t.invalidateQueries({queryKey:P.item(n.path)}),t.invalidateQueries({queryKey:P.children(n.path)});J("catchUpAfterGap:",e,"- invalidated",Me.size,"paths")}catch(t){J("catchUpAfterGap: cache invalidation skipped",t)}}function ot(e){Q&&Q.readyState===WebSocket.OPEN&&Q.send(JSON.stringify(e))}function vd(e){ss=Date.now();try{let t=JSON.parse(e);if(t.type==="subscribed_path"){typeof t.path=="string"&&gd(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==="resync"){ec(typeof t.reason=="string"?t.reason:"resync");return}if(t.type==="event"||t.event_type){let n=t.event_type||"message",r=t.data||t;if(n==="vfs_change"&&(ja(N(),r),Qa(N(),r)),typeof r.path=="string")for(let[s,i]of Object.entries(Re))s!=="*"&&Ii(s,r.path)&&i.forEach(o=>o(r));Re["*"]&&Re["*"].forEach(s=>s(r));for(let s of An)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function ki(){!_d()&&it.size===0&&Me.size===0&&Q&&(kn=!0,fr(),Q.close(),Q=null,kn=!1)}function cs(e,t){return Re[e]||(Re[e]=[]),Re[e].push(t),Me.has(e)||(Me.set(e,{path:e,event_types:["token_stream"]}),Q&&Q.readyState===WebSocket.OPEN?Ai(e,["token_stream"]):Be.set(e,"pending")),jt(),()=>{let n=Re[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete Re[e],Me.delete(e),Be.delete(e),wt.delete(e),ot({type:"unsubscribe_path",path:e}))}ki()}}function ie(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return An.push(...s),dr()&&jt(),()=>{for(let i of s){let o=An.indexOf(i);o!==-1&&An.splice(o,1)}ki()}}function Mn(e,t=["vfs_change","ccm_change"]){let n=Symbol(e),r=Array.from(new Set(t)).sort();if(r.length===0)return()=>{};let s=Tn.get(e)??new Map,i=it.get(e)?.event_types;s.set(n,{event_types:r}),Tn.set(e,s);let o=Ya(e);if(!o)return()=>{};J("subscribeToScope:",e,o.event_types),Q&&Q.readyState===WebSocket.OPEN&&!Ja(i,o.event_types)&&ot({type:"subscribe",scope_id:e,event_types:o.event_types}),jt();let a=!0;return()=>{if(!a)return;a=!1;let c=Tn.get(e);if(!c?.delete(n))return;let u=it.get(e)?.event_types;if(c.size===0)Tn.delete(e),it.delete(e),ot({type:"unsubscribe",scope_id:e});else{let l=Ya(e);l&&Q&&Q.readyState===WebSocket.OPEN&&!Ja(u,l.event_types)&&ot({type:"subscribe",scope_id:e,event_types:l.event_types})}ki()}}function tc(e,t,n={}){ot({type:"emit",scope_id:e,event_type:t,payload:n})}function Mi(){J("disconnectSSE: tearing down"),$a(N()),Ua(N()),kn=!0,fr(),Q&&(Q.close(),Q=null),In&&(clearTimeout(In),In=null),En=null,kn=!1,lr=0;for(let e of Object.keys(Re))delete Re[e];An.length=0,it.clear(),Tn.clear(),Me.clear(),Be.clear(),wt.clear(),as("disconnected")}function nc(){ot({type:"ping"})}function rc(e){return Me.has(e)?Be.get(e)??"pending":"unsubscribed"}function sc(e,t=5e3){return!Me.has(e)||et?Promise.resolve(!1):Be.get(e)==="ready"&&Q&&Q.readyState===WebSocket.OPEN?Promise.resolve(!0):(jt(),new Promise(n=>{let r=!1,s=wt.get(e)??[],i=()=>{r||(r=!0,clearTimeout(o),n(!0))};s.push(i),wt.set(e,s);let o=setTimeout(()=>{if(r)return;r=!0;let a=wt.get(e);if(a){let c=a.indexOf(i);c!==-1&&a.splice(c,1),a.length===0&&wt.delete(e)}n(!1)},t)}))}function ic(e){let t=Me.get(e);if(!t){J("resubscribePath: no active subscription for",e);return}Q&&Q.readyState===WebSocket.OPEN?(J("resubscribePath: re-sending frame for",e),Ai(t.path,t.event_types)):(Be.set(e,"pending"),jt())}function us(e){os.push(e);try{e(Ti)}catch{}return()=>{let t=os.indexOf(e);t!==-1&&os.splice(t,1)}}se(Mi);function oc(){return new Date().toISOString()}function ac(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function Oe(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||oc(),updated_at:e.updated_at||oc(),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 mr(e){return(e.content?.items||e.items||[]).map(Oe)}async function hr(e){try{let t=await C("read",{id:e});if(t.item_name||t.item_path){let r=Oe(t);return r.path&&N().setQueryData(P.item(r.path),r),r}let n=t.item;if(n){let r=Oe(n);return r.path&&N().setQueryData(P.item(r.path),r),r}return null}catch{return null}}async function gr(e){try{let t=await C("read",{path:e});if(t.item_name||t.item_path)return Oe(t);let n=t.item;return n?Oe(n):null}catch{return null}}async function yr(e){try{let t=await C("list",{path:e,limit:200}),n=mr(t);for(let r of n)N().setQueryData(P.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function cc(e,t){let{items:n}=await Bt({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 ds(e,t,n){try{let r=await C("list",{path:e,limit:t,offset:n}),s=mr(r);for(let i of s)N().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 fs(e){let n=await C("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 ps(e){try{let t=await C("edges",{item_id:e}),n=t.outgoing||[],r=t.incoming||[],s=[];for(let i of n)s.push({id:i.edge_id||ac(),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||ac(),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 ms(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 C("tree",s),o=mr(i);for(let a of o)N().setQueryData(P.item(a.path),a);return o}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function hs(e,t=50,n=0){try{let r=await C("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 _r(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;try{let i=await C("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 gs(e,t=50,n=0){return _r(e,{limit:t,offset:n})}async function ys(e,t,n){try{let r={scope_id:e};t?.length&&(r.item_types=t),n&&(r.limit=n);let s=await C("member-focus",r),i=mr(s);for(let o of i)N().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 br(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 C("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 On(e){return!!e&&(!!e.type||Array.isArray(e.any_of)&&e.any_of.length>0)}function wd(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 Sd=["catalog","parent_only","internal"];function uc(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,l]of Object.entries(o))u.startsWith("field.")&&u.length>6&&n(l)?a[u.slice(6)]=l:u.startsWith("field_in.")&&u.length>9&&Array.isArray(l)&&(c[u.slice(9)]=l.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"&&Sd.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 l=r(c);Object.keys(l.fields).length&&(u.fields=l.fields),Object.keys(l.field_in).length&&(u.field_in=l.field_in),Object.keys(u).length&&o.push(u)}o.length&&(s.any_of=o)}return On(s)?{...s,...t}:null}async function Bt(e,t={}){if(e=vt(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(wd)),Object.keys(r).length>0&&(n.filters=r),e.limit!=null&&(n.limit=e.limit);try{let s=await C("query",n,t);e.spaceIds!==void 0&&Va(e.spaceIds,s.selected_space_ids??s.content?.selected_space_ids);let i=mr(s);for(let o of i)N().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 xd(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 lc(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:xd(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 pr(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 dc(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await C("get-channel-messages",n),i=s.messages||s.content?.items||s.items||[];return pr(i)}catch(n){throw console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),n}}async function _s(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await C("get-channel-messages",n),i=s.messages||[],o=pr(i),a=lc(i),c=new Map,u=[];for(let l of a)if(l.parentMessagePath){let f=c.get(l.parentMessagePath)||[];f.push(l),c.set(l.parentMessagePath,f)}else u.push(l);return{messages:o,activityMessages:pr(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 vr(e,t){try{let n={channel_path:e};t?.parentMessageId&&(n.parent_message_id=t.parentMessageId),t?.conversationsOnly&&(n.conversations_only=!0),t?.transcriptOnly&&(n.transcript_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 C("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.");if(t?.transcriptOnly&&s.transcript_only!==!0)throw new Error("This server does not support channel transcript pages yet. Update the message reader.");let i=s.messages||[],o=lc(i),a=new Map,c=[];for(let u of o)if(u.parentMessagePath){let l=a.get(u.parentMessagePath)||[];l.push(u),a.set(u.parentMessagePath,l)}else c.push(u);return{messages:pr(i),activityMessages:pr(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 ls(e){N().invalidateQueries({queryKey:P.children(e)})}function Oi(e){N().invalidateQueries({queryKey:P.item(e)})}function fc(e,t){Oi(e),ls(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&ls(r)}function pc(e){let t=e+"/";N().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function mc(){N().invalidateQueries({queryKey:P.all()})}function hc(e){N().invalidateQueries({queryKey:P.types(e)})}function gc(e,t){e?N().invalidateQueries({queryKey:P.channelMessages(e,t)}):N().invalidateQueries({queryKey:P.allChannelMessages()})}function yc(e,t){e&&t?N().invalidateQueries({queryKey:P.openEnvelope(e,t)}):e?N().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):N().invalidateQueries({queryKey:P.allOpenEnvelopes()})}function $e(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}async function bs(){return((await C("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 Fn=new Map,Sr=null,vs=null,St=new Map,_c=250,wr=new Map;function $t(e){if(Sr){qn(e);return}qn(e),Sr=ie("vfs_change",t=>Rd(t)),vs=ie("ccm_change",t=>Cd(t))}function qn(e){if(Fn.has(e))return;let t=Mn(e,["vfs_change","ccm_change"]);Fn.set(e,t)}function ws(e){let t=Fn.get(e);t&&(t(),Fn.delete(e))}function Fi(){for(let[,e]of Fn)e();Fn.clear(),Sr&&(Sr(),Sr=null),vs&&(vs(),vs=null),St.forEach(e=>clearTimeout(e)),St.clear(),wr.clear()}se(Fi);function Rd(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=wr.get(s);i||(i=new Map,wr.set(s,i)),i.set(t,{action:n,itemId:typeof e.item_id=="string"?e.item_id:void 0});let o=St.get(s);o&&clearTimeout(o);let a=setTimeout(()=>{St.delete(s);let c=wr.get(s);wr.delete(s),c&&Pd(s,c)},_c);St.set(s,a)}function Cd(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=St.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{St.delete(s),t&&N().invalidateQueries({queryKey:P.edges(t)}),n&&N().invalidateQueries({queryKey:P.edges(n)})},_c);St.set(s,o)}function Pd(e,t){let n=N();for(let[s,i]of t)(i.action||"").toUpperCase()==="DELETE"?(n.removeQueries({queryKey:P.item(s)}),n.removeQueries({queryKey:P.children(s)}),n.removeQueries({queryKey:P.tree(s)})):ve(n,P.item(s),{exact:!0}),i.itemId&&n.invalidateQueries({queryKey:P.itemById(i.itemId)});n.invalidateQueries({queryKey:P.children(e)});let r=[...t.keys()];n.invalidateQueries({predicate:s=>{let i=s.queryKey;if(i[0]!=="vfs"||i[1]!=="tree")return!1;let o=i[2];return r.some(a=>a.startsWith(o+"/")||a===o)}})}var Nn=null;se(()=>{Nn=null});function xt(e){if(e!==Nn||e.generation!==ae())throw new Error("Workspace session changed")}function Ed(e){return e instanceof he&&e.payload?.error==="item_not_found"}function xr(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 Rr(e){let t=me();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 bc(e,t){return JSON.stringify({mounts:e.map(n=>n.id),last_anchor:t.id})}async function vc(e,t,n){xt(e);let r=bc(t,n);if(e.saved===r)return;let s=JSON.parse(r);await C(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}),xt(e),e.exists=!0,e.saved=r}function wc(e,t){let n=Ae();$t(me().id);for(let r of n)e.some(s=>s.id===r.id)||ws(r.id);for(let r of e)qn(r.id);la(e,t)}async function Vt(e,t,n={}){let r=me();if(!r)throw new Error("Elect a home account before loading mounts");let s=`${e}/settings/mounts`;if(Nn&&Nn.path!==s)throw new Error("Reset the session before changing the mount declaration owner");let i=Nn??(Nn={generation:ae(),path:s,scope:r.path,resolve:t,exists:!1,ready:!1,saved:null,queue:Promise.resolve()});return xt(i),i.loading?i.loading:i.ready?Ae():(i.resolve=t,i.loading=(async()=>{let o=null;try{let l=await C("read",{path:s,_scope_path:i.scope});if(xt(i),o=l.type_data??l.item?.type_data,!o||!Array.isArray(o.mounts)||!o.mounts.every(f=>typeof f=="string"))throw new Error("Invalid saved mount declaration");i.exists=!0}catch(l){if(xt(i),!Ed(l))throw l;i.exists=!1}let a=n.initialAnchor?xr(i,n.initialAnchor):r,c=Rr(o?o.mounts.map(t).filter(l=>l!==null):[a]),u=o?c.find(l=>l.id===o.last_anchor)??c.find(l=>l.kind==="space")??r:a;return o?i.saved=bc(c,u):n.initialAnchor&&await vc(i,c,u),xt(i),i.ready=!0,wc(c,u),c})().finally(()=>{i.loading=void 0}),i.loading)}function Ss(e){let t=Nn;if(!t?.ready)return Promise.reject(new Error("Workspace mounts are not loaded"));let n=t.queue.then(async()=>{xt(t);let{refs:r,anchor:s}=e(t);await vc(t,r,s),xt(t),wc(r,s)});return t.queue=n.catch(()=>{}),n}function qi(e){return Ss(t=>({refs:Rr([...Ae(),xr(t,e)]),anchor:de()}))}function Sc(e){return Ss(()=>{if(e===me().id)throw new Error("The home account cannot be unmounted");let t=Rr(Ae().filter(r=>r.id!==e)),n=t.find(r=>r.id===de()?.id)??t.find(r=>r.kind==="space")??me();return{refs:t,anchor:n}})}function Cr(e){return Ss(t=>{let n=xr(t,e);return{refs:Rr([...Ae(),n]),anchor:n}})}function xs(e,t){return Ss(n=>{let r=Rr(e.map(i=>xr(n,i))),s=xr(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}})}var Ni={};co(Ni,{Badge:()=>Od,Breadcrumbs:()=>Bd,Button:()=>qd,Card:()=>Md,DataView:()=>Qd,Detail:()=>Kd,Empty:()=>Nd,FilePreview:()=>Wd,Form:()=>Ud,Grid:()=>Ad,Image:()=>$d,Link:()=>Hd,Page:()=>Td,Router:()=>Ld,Sidebar:()=>kd,Spinner:()=>Fd,Stack:()=>Id,Table:()=>Dd,Tabs:()=>jd,Video:()=>Vd});var G=Y(ue(),1);function xc(){return(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||""}function Td(e){return(0,G.createElement)("div",{style:{minHeight:"100vh",display:"flex",flexDirection:"column"},className:e.className||""},e.children)}function Id(e){let t=e.direction||"vertical";return(0,G.createElement)("div",{style:{display:"flex",flexDirection:t==="horizontal"?"row":"column",gap:e.gap||"0.5rem",padding:e.padding||"0",alignItems:e.align||"stretch",justifyContent:e.justify||"flex-start",flex:e.flex||"initial"},className:e.className||""},e.children)}function Ad(e){return(0,G.createElement)("div",{style:{display:"grid",gridTemplateColumns:"repeat("+(e.columns||3)+", 1fr)",gap:e.gap||"1rem",padding:e.padding||"0"},className:e.className||""},e.children)}function kd(e){return(0,G.createElement)("div",{style:{display:"flex",flexDirection:"row",minHeight:"100vh"},className:e.className||""},e.children)}function Md(e){return(0,G.createElement)("div",{style:{border:"1px solid var(--color-border, #e5e7eb)",borderRadius:"var(--border-radius, 0.5rem)",padding:e.padding||"1rem",background:"var(--color-surface, #fff)"},className:e.className||"",onClick:e.onClick},e.children)}function Od(e){return(0,G.createElement)("span",{style:{display:"inline-flex",alignItems:"center",padding:"0.125rem 0.5rem",fontSize:"0.75rem",fontWeight:"500",borderRadius:"9999px",background:e.color||"#e5e7eb",color:e.textColor||"#374151"},className:e.className||""},e.children||e.label)}function Fd(e){let t=e.size||"1.5rem";return(0,G.createElement)("div",{style:{width:t,height:t,border:"2px solid #e5e7eb",borderTopColor:"var(--color-primary, #3b82f6)",borderRadius:"50%",animation:"fsaos-spin 0.6s linear infinite"}})}function qd(e){return(0,G.createElement)("button",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:"0.5rem 1rem",fontSize:"0.875rem",fontWeight:"500",borderRadius:"var(--border-radius, 0.375rem)",border:e.variant==="outline"?"1px solid var(--color-border, #d1d5db)":"none",background:e.variant==="outline"||e.variant==="ghost"?"transparent":"var(--color-primary, #3b82f6)",color:e.variant==="outline"||e.variant==="ghost"?"var(--color-text, #1a1a1a)":"#fff",cursor:e.disabled?"not-allowed":"pointer",opacity:e.disabled?"0.5":"1",gap:"0.5rem"},className:e.className||"",onClick:e.onClick,disabled:e.disabled},e.children||e.label)}function Nd(e){return(0,G.createElement)("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"3rem",color:"var(--color-text-secondary, #6b7280)",textAlign:"center"}},e.icon?(0,G.createElement)("div",{style:{fontSize:"2rem",marginBottom:"0.5rem"}},e.icon):null,(0,G.createElement)("div",{style:{fontWeight:500,marginBottom:"0.25rem"}},e.title||e.message||e.children||"No items"),e.description?(0,G.createElement)("div",{style:{fontSize:"0.875rem",opacity:.7}},e.description):null)}function Qd(e){return(0,G.createElement)("div",{className:e.className||""},e.children)}function Dd(e){return(0,G.createElement)("table",{className:e.className||""},e.children)}function Ud(e){return(0,G.createElement)("form",{className:e.className||"",onSubmit:e.onSubmit},e.children)}function Kd(e){return(0,G.createElement)("div",{className:e.className||""},e.children)}function Ld(e){return(0,G.createElement)("div",null,e.children)}function Hd(e){return(0,G.createElement)("a",{href:e.href||e.to,className:e.className||"",onClick:e.onClick},e.children)}function jd(e){return(0,G.createElement)("div",{className:e.className||""},e.children)}function Bd(e){return(0,G.createElement)("nav",{className:e.className||""},e.children)}function $d(e){return(0,G.createElement)("img",{src:e.src||(e.path?xc()+e.path:""),alt:e.alt||"",className:e.className||"",style:e.style})}function Vd(e){return(0,G.createElement)("video",{src:e.src||(e.path?xc()+e.path:""),controls:!0,className:e.className||""})}function Wd(e){return(0,G.createElement)("div",{className:e.className||""},e.children||"File preview")}function Rs(e){if(typeof e.path!="string")return!1;let t=[...Ae().map(n=>n.path),de()?.path].filter(n=>!!n);return!t.length&&W()&&t.push(W()),t.some(n=>ge(e.path,n))}function Qi(e,t,n,r){if(!["message","card"].includes(e?.item_type)||!ge(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&&ge(e.path,i)})}var Rc=new WeakMap;function Cc(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,l=!1,f=new Set,m=new Set,p=()=>e.getQueryData(t)??[],g=()=>{a||u||c||(c=setTimeout(()=>{c=void 0,_()},250))},_=async()=>{if(a)return;u=!0;let E=l;l=!1;let w=[...f],O=new Set(m);m.clear(),f.clear();try{if(E)await ve(e,t,{exact:!0});else{let x=(await Promise.allSettled(w.map(async A=>{let k=e.getQueryCache().find({queryKey:t,exact:!0});if(!k)return;let I=await C("read",{id:A});if(I.success===!1)throw new Error("Channel refresh failed");if(a||!k||e.getQueryCache().find({queryKey:t,exact:!0})!==k)return;let M=Oe(I.item??I);if(M.id!==A||M.item_type!=="channel")return;let q=p().find(Ce=>Ce.id===A);if(!q)return;let U=n({...M}),$={...q,path:U.path,name:U.name,displayName:U.displayName,messageCount:U.messageCount,aiMode:U.aiMode,activeAgentIds:U.activeAgentIds,isPrivate:U.isPrivate,isDm:U.isDm,autoPilot:U.autoPilot,isArchived:U.isArchived,updatedAt:U.updatedAt};O.has(A)&&(q.name!==$.name||q.displayName!==$.displayName||q.path!==$.path)&&(l=!0),e.setQueryData(t,Ce=>Ce?.map(re=>re.id===A?$:re))}))).find(A=>A.status==="rejected");if(x?.status==="rejected")throw x.reason}}catch(K){console.warn("[channels] refresh failed",K)}finally{u=!1,(l||f.size)&&g()}},h=E=>p().some(w=>w.id===E.item_id||w.path===E.path)?!0:Rs(E),y=E=>{if(!h(E))return;let w=String(E.action??"").toLowerCase();if(["insert","delete","rename","move"].includes(w))l=!0;else if(w==="update"){let O=p().find(K=>K.id===E.item_id||K.path===E.path);O&&(f.add(O.id),m.add(O.id))}(l||f.size)&&g()},v=E=>{let w=p().find(O=>O.id===E.parent_id);w&&(f.add(w.id),g())},R=["vfs_change","ccm_change"].flatMap(E=>[ie(E,y,w=>w.item_type==="channel"),ie(E,v,w=>w.item_type==="message")]);i={users:0,stop:()=>{a=!0,c&&clearTimeout(c),R.forEach(E=>E())}},r.set(s,i)}i.users++;let o=!1;return()=>{o||(o=!0,--i.users===0&&(i.stop(),r.delete(s)))}}function ee(){return(0,b.useSyncExternalStore)(xe,ne,ne)}function Mc(){return ee(),Gr()}function Oc(e){return ee(),B({queryKey:P.item(e),queryFn:()=>gr(e),enabled:!!e,staleTime:1/0})}function Fc(e){return ee(),B({queryKey:P.itemById(e),queryFn:()=>hr(e),enabled:!!e,staleTime:1/0})}function Ki(e){return ee(),B({queryKey:P.children(e),queryFn:()=>yr(e),enabled:!!e})}function qc(e){let t=Ki(e);return{...t,children:t.data??[]}}function Nc(e,t=1){return ee(),B({queryKey:P.tree(e,t),queryFn:()=>ms(e,t),enabled:!!e})}function Qc(e,t){return ee(),B({queryKey:P.search(e,t),queryFn:async()=>{let n={query:e};t?.length&&(n.item_types=t);let r=await C("search",n);return(r.content?.items||r.items||r.results||[]).map(Oe)},enabled:!!e&&e.length>0})}function Dc(e){ee();let t=(0,b.useMemo)(()=>e,[JSON.stringify(e)]);return B({queryKey:["vfs",W()??"__unscoped__","resolve",JSON.stringify(t??{})],queryFn:async()=>await C("resolve",t),enabled:!!t?.query&&t.query.length>0})}function Uc(e){ee();let t=vt(e),n=(0,b.useMemo)(()=>t,[JSON.stringify(t)]),r=B({queryKey:P.items(n?.type??"",n),queryFn:({signal:s})=>Bt(n,{signal:s,throwOnError:!0}),enabled:On(n),...n?.spaceIds!==void 0?{retry:(s,i)=>!Pn(i)&&Mu(s,i)}:{},select:s=>s.items});return n?.spaceIds!==void 0&&Pn(r.error)?{...r,data:void 0}:r}function Li(e,t={}){let n=ee(),{realtime:r=!1}=t,s=vt(e),i=s?.limit??20,o=(0,b.useMemo)(()=>s,[JSON.stringify(s)]),a=(0,b.useMemo)(()=>["vfs",W()??"__unscoped__","infinite-items",o?.type??"",JSON.stringify(o??{})],[n,o]),c=ir({queryKey:a,queryFn:async({pageParam:f=0,signal:m})=>Bt({...o,limit:i,offset:f},{throwOnError:!0,signal:m,priority:t.priority}),initialPageParam:0,getNextPageParam:(f,m,p)=>{if(!(o?.spaceIds!==void 0&&f.total_hint!==void 0&&p+f.items.length>=f.total_hint)&&!(f.items.length<i))return p+f.items.length},enabled:On(o),...o?.spaceIds!==void 0?{retry:(f,m)=>!Pn(m)&&Mu(f,m)}:{},staleTime:r?1/0:t.staleTime,meta:r&&o?{infiniteItemsRealtime:{filter:o}}:{}}),u=(0,b.useMemo)(()=>{if(o?.spaceIds!==void 0&&Pn(c.error))return[];if(!c.data?.pages)return[];let f=new Set,m=[];for(let p of c.data.pages)for(let g of p.items)g.id&&!f.has(g.id)&&(f.add(g.id),m.push(g));return m},[c.data?.pages,c.error,o]),l=o?.spaceIds!==void 0&&Pn(c.error);return{allItems:u,refetch:c.refetch,fetchNextPage:c.fetchNextPage,isFetchingNextPage:c.isFetchingNextPage,isExhausted:l||!c.hasNextPage,isLoading:c.isLoading,isFetching:c.isFetching,error:c.error,totalHint:l?void 0:c.data?.pages?.[0]?.total_hint}}function Pc(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 Jd(e,t){if(e.is_active===!1||e.item_type!==t.type||!ge(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 Kc(e,t={}){let n=Pc(e),r=Li(e,n?{realtime:!1,staleTime:3e4}:{realtime:!0}),s=L(),i=JSON.stringify([W(),vt(e)]),[o,a]=(0,b.useState)(()=>({identity:i,upserts:{},deleted:new Set})),c=o.identity===i?o:{identity:i,upserts:{},deleted:new Set},u=(0,b.useMemo)(()=>{if(!n)return r.allItems;let p=Object.values(c.upserts),g=new Set(p.map(v=>v.id)),_=[...p,...r.allItems.filter(v=>!g.has(v.id))].filter(v=>!c.deleted.has(v.path)),h=e.sort_by??"updated_at",y=e.sort_dir==="asc"?1:-1;return _.sort((v,R)=>y*String(v[h]??"").localeCompare(String(R[h]??"")))},[n,r.allItems,c,e?.sort_by,e?.sort_dir]),l=(0,b.useRef)(u);l.current=u;let f=(0,b.useRef)(t.shouldReadUpdate);f.current=t.shouldReadUpdate;let m=(0,b.useRef)(r.refetch);return m.current=r.refetch,(0,b.useEffect)(()=>{if(!Pc(e))return;let p=e,g=!1,_=!1,h=!1,y=0,v=new Map,R=()=>{let x=y;m.current().then(A=>{!g&&!A.isError&&y===x&&a({identity:i,upserts:{},deleted:new Set})})},E=x=>{y++,a(k=>{let I=k.identity===i?k:{identity:i,upserts:{},deleted:new Set},M={...I.upserts};return delete M[x],{identity:i,upserts:M,deleted:new Set(I.deleted).add(x)}});let A=v.get("__reconcile__");A&&clearTimeout(A),v.set("__reconcile__",setTimeout(()=>{v.delete("__reconcile__"),R()},250))},w=x=>{let A=v.get(x);A&&clearTimeout(A),v.set(x,setTimeout(()=>{v.delete(x),s.fetchQuery({queryKey:P.item(x),queryFn:()=>gr(x),staleTime:0}).then(k=>{if(!g){if(!k||!Jd(k,p)){let I=l.current.find(M=>M.path===x||M.id===k?.id);I&&E(I.path);return}a(I=>{let M=I.identity===i?I:{identity:i,upserts:{},deleted:new Set},q=new Set(M.deleted);return q.delete(x),{identity:i,upserts:{...M.upserts,[x]:k},deleted:q}})}}).catch(k=>console.warn("[useIncrementalItems] item read failed:",k))},250))},O=ie("vfs_change",x=>{if(!x||typeof x.path!="string"&&typeof x.old_path!="string")return;let A=typeof x.path=="string"?x.path:x.old_path,k=l.current.find(M=>M.path===A||M.path===x.old_path||x.item_id&&M.id===x.item_id),I=!!k;if(!(!ge(A,p.scope)&&!ge(x.old_path,p.scope)&&!I)&&!(x.item_type&&x.item_type!==p.type&&!I)&&!(p.parent_id&&x.parent_id&&x.parent_id!==p.parent_id&&!I)){if(k&&(A!==k.path||x.old_path&&x.old_path!==A||x.parent_id&&x.parent_id!==k.parent_id||x.item_type&&x.item_type!==p.type)){E(k.path);return}if(!k&&x.old_path&&x.old_path!==A&&ge(A,p.scope)){y++,w(A);return}if(x.action==="insert")y++,w(A);else if(x.action==="move")y++,w(A);else if(x.action==="update"){if(!f.current?.(x,l.current))return;y++,w(A)}else x.action==="delete"&&E(k?.path??x.old_path??A)}}),K=us(x=>{if(x!=="connected"){_&&(h=!0);return}_=!0,h&&(h=!1,R())});return()=>{g=!0,O(),K(),v.forEach(clearTimeout)}},[s,i]),{...r,allItems:u}}function Lc(e){ee();let t=20,n=ir({queryKey:["vfs",W()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>ds(e,t,s),initialPageParam:0,getNextPageParam:(s,i,o)=>{if(!(s.items.length<t))return o+s.items.length},enabled:!!e});return{allItems:(0,b.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 Hc(e){return ee(),B({queryKey:P.edges(e),queryFn:()=>ps(e),enabled:!!e})}function Ps(e){return ee(),B({queryKey:P.types(e),queryFn:()=>fs(e)})}function jc(e,t){let n=Ps(t);return{...n,data:n.data?.get(e)??void 0}}function Bc(e,t){ee();let n=(0,b.useMemo)(()=>t?.arguments,[JSON.stringify(t?.arguments)]),r=t?.mode,s=t?.strategy,i=t?.width;return B({queryKey:[...P.openEnvelope(e,s),i],queryFn:async()=>{let o=await br(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 Ec={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 $c(e){let t=Ps(e),n=t.data??new Map;return(0,b.useMemo)(()=>({canHaveChildren:p=>n.get(p.item_type)?.is_container??!1,isScope:p=>n.get(p.item_type)?.is_scope??!1,isScopeType:p=>n.get(p)?.is_scope??!1,isContainerType:p=>n.get(p)?.is_container??!1,getTypeDefinition:p=>n.get(p),getTypeColor:p=>n.get(p)?.color??"gray",getTypeIcon:p=>n.get(p)?.icon??"File",getTypeDisplayName:p=>n.get(p)?.display_name??p,getKnownEdgeTypes:()=>Object.entries(Ec).map(([p,g])=>({key:p,label:g})),getEdgeTypeLabel:p=>Ec[p]??p.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function Vc(e,t,n){return ee(),B({queryKey:P.memberFocus(e),queryFn:()=>ys(e,t,n),enabled:!!e})}function Wc(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return B({queryKey:P.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>_r(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function Gc(e,t=50,n=0){return B({queryKey:P.itemHistory(e,String(t),String(n)),queryFn:()=>gs(e,t,n),enabled:!!e})}function zc(e,t=50,n=0){return ee(),B({queryKey:P.recentActivity(e,String(t),String(n)),queryFn:()=>hs(e,t,n),enabled:!!e})}function Jc(){let[e,t]=(0,b.useState)(null),[n,r]=(0,b.useState)(!0),[s,i]=(0,b.useState)(null);return(0,b.useEffect)(()=>{let o=!1;return nt().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 Yd=[];function Tc(){if(typeof window>"u")return!1;let e=window.__FSAOS_CONFIG__?.embedToken;return typeof e=="function"||typeof e=="string"&&e.length>0}function Zd(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 Yc(){let{user:e}=Es(),t=(0,b.useSyncExternalStore)(pa,bi,bi),n=bt()?.principal_id??null,r=(0,b.useRef)(null),[s,i]=(0,b.useState)(null),[o,a]=(0,b.useState)(null);(0,b.useEffect)(()=>{if(n){a(null);return}if(!e?.id&&!Tc()){a(null);return}let v=!1;return nt().then(R=>{v||R.principal_id||a(new Error("Memberships require an authenticated principal"))}).catch(R=>{v||a(R instanceof Error?R:new Error(String(R)))}),()=>{v=!0}},[n,e?.id,t]);let c=B({queryKey:P.memberships(n??"anonymous"),queryFn:bs,enabled:!!n,staleTime:1e3*60*2}),u=c.data??Yd,l=(0,b.useMemo)(()=>u.filter(v=>v.isAccount!==!1&&!v.isSpace),[u]),f=(0,b.useMemo)(()=>{let v=new Set(l.map(E=>E.accountId)),R=E=>!E.subordinateTo||!v.has(E.subordinateTo);return[...l].sort((E,w)=>Number(R(w))-Number(R(E)))},[l]),m=(0,b.useSyncExternalStore)(xe,ne,ne),p=(0,b.useMemo)(()=>{let v=de();return v?u.find(R=>R.accountId===v.id)??null:null},[m,u]),g=(0,b.useMemo)(()=>Zd(l),[l]);(0,b.useEffect)(()=>{if(!n){r.current=null;return}if(r.current!==n)if(i(null),f.length===1){let v=f[0];me()||Dt($e(v)),$t(v.accountId),v.personalSpacePath&&Vt(v.personalSpacePath,R=>{let E=u.find(w=>w.accountId===R);return E?$e(E):null}).catch(i),r.current=n}else f.length>1&&(r.current=n)},[n,f,u]);let _=(0,b.useCallback)(async v=>{let R=u.find(O=>O.path===v);if(!R)throw new Error("Account membership is unavailable");let E=$e(R);me()||Dt(E);let w=u.find(O=>O.accountId===me()?.id);if(!w?.personalSpacePath)throw new Error("The home membership has no mount declaration location");await Vt(w.personalSpacePath,O=>{let K=u.find(x=>x.accountId===O);return K?$e(K):null}),await Cr(E),i(null),$t(R.accountId)},[u]),h=(0,b.useCallback)(async v=>{let R=u.find(E=>E.path===v);if(!R)throw new Error("Scope membership is unavailable");await qi($e(R))},[u]),y=(!!e?.id||Tc())&&!n&&!o;return{accounts:f,switcherAccounts:g,allMemberships:u,currentAccount:p,mountedScope:null,switchAccount:_,mountScope:h,loading:y||c.isLoading,error:o??c.error??s}}function Zc(){ee();let e=(0,b.useSyncExternalStore)(Wr,ur,ur),t=(0,b.useMemo)(()=>Ae(),[e]),n=de(),r=(0,b.useMemo)(()=>t.filter(i=>i.kind==="space"&&(n?.kind==="account"||i.id===n?.id)),[t,n]),s=(0,b.useMemo)(()=>r.map(i=>i.id).sort(),[r]);return{mounts:t,selectedSpaces:r,readSpaceIds:s,homeAnchor:me(),anchor:n,setAnchor:Cr,replaceMounts:xs,mount:qi,unmount:Sc}}function Es(){let[e,t]=(0,b.useState)(null),[n,r]=(0,b.useState)(null),[s,i]=(0,b.useState)(!0),o=(0,b.useRef)(null);(0,b.useEffect)(()=>{V.auth.getSession().then(({data:p,error:g})=>{if(g){console.warn("[useAuth] getSession error, clearing stale session:",g.message),V.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(p?.session??null),t(p?.session?.user??null),i(!1)}).catch(p=>{console.warn("[useAuth] getSession threw, clearing stale session:",p?.message),V.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:m}}=V.auth.onAuthStateChange((p,g)=>{if(p==="TOKEN_REFRESHED"&&!g){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),V.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(g),t(g?.user??null),i(!1)});return o.current=m,()=>{m?.unsubscribe()}},[]);let a=(0,b.useCallback)(async m=>m.provider?V.auth.signInWithOAuth({provider:m.provider,options:m.redirectTo?{redirectTo:m.redirectTo}:{redirectTo:window.location.href}}):V.auth.signInWithPassword({email:m.email,password:m.password}),[]),c=(0,b.useCallback)(async m=>V.auth.signUp({email:m.email,password:m.password,options:{data:m.metadata||{}}}),[]),u=(0,b.useCallback)(async()=>{await V.auth.signOut(),Rn(),N().clear()},[]),l=(0,b.useCallback)(async m=>{let{error:p}=await V.auth.resetPasswordForEmail(m);if(p)throw p},[]),f=(0,b.useCallback)(async(m,p)=>{let{error:g}=await V.auth.signInWithOtp({email:m,options:p?{emailRedirectTo:p}:{emailRedirectTo:window.location.href}});if(g)throw g},[]);return{user:e,session:n,loading:s,signIn:a,signUp:c,signOut:u,resetPassword:l,signInWithMagicLink:f}}function Xc(e){let[t,n]=(0,b.useState)(null),[r,s]=(0,b.useState)(!1),[i,o]=(0,b.useState)(null);return(0,b.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),C("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 Cs={};se(()=>{for(let e of Object.keys(Cs))delete Cs[e]});var eu=null;function tu(e){eu=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function Xd(e){switch(e){case"react":return typeof window<"u"&&window.React||b.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||Gd;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}:zd;case"@fsaos/gateway":case"@fsaos/react":case"@ai4b-team/fsaos-gateway-sdk":return typeof window<"u"&&window.__FSAOS_GATEWAY__||eu||{};case"@fsaos/ui":case"@ai4b-team/fsaos-gateway-sdk/ui":return typeof window<"u"&&window.__FSAOS_UI__||Ni;case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}var Er={};async function ef(e){try{let t=await fetch(e);if(!t.ok)return null;let n=await t.text();return!n.trim()||n.includes("No CSS bundle for this component")?null:n}catch{return null}}async function nu(e,t=()=>ef(e)){let n=Er[e];n||(n=Er[e]={users:0,text:t(),style:null}),n.users+=1;let r=await n.text;if(Er[e]!==n||n.users===0||n.style||!r||typeof document>"u")return;let s=document.createElement("style");s.setAttribute("data-fsaos-component-css",e),s.textContent=r,document.head.appendChild(s),n.style=s}function Ve(e){let t=Er[e];t&&(t.users-=1,!(t.users>0)&&(t.style?.remove(),delete Er[e]))}function ru(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)(Xd),o=t??i;return o?o.default||o:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function Hi(e,t){let[n,r]=(0,b.useState)(null),[s,i]=(0,b.useState)(!0),[o,a]=(0,b.useState)(null),c=(0,b.useRef)(null),u=Number.isSafeInteger(t?.version)&&t.version>0?t.version:null;return(0,b.useEffect)(()=>{if(!e)return;let l=!1;a(null),c.current?.path!==e&&(c.current?.cssUrl&&Ve(c.current.cssUrl),c.current=null,r(null),i(!0));let m=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{let p=null;try{let g=1,_=e+"@v1",h=m+e+"/__bundle.js";if(u!==null)g=u,_=e+"@v"+g,h=m+e+"/__bundle.v"+g+".js";else try{let w=await fetch(m+e+"/__meta",{cache:"no-store"});w.ok&&(g=(await w.json()).version||1,_=e+"@v"+g,h=m+e+"/__bundle.v"+g+".js")}catch{h=m+e+"/__bundle.js?v="+Date.now()}if(l)return;let y=h.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");p=y;let v=nu(y),R=Cs[_];if(!R){let w=await fetch(h);if(!w.ok)throw new Error(`Failed to fetch bundle: ${w.status} ${w.statusText} (${h})`);let O=await w.text();if(R=ru(O),!R)throw new Error("Bundle did not export a component. Expected window.__FSAOS_COMPONENT__ (FSAOS build) or a __FSAOS_REGISTER__(Component) call.");if(typeof R!="function")throw new Error(`Bundle export is not a React component (got ${typeof R})`);Cs[_]=R}if(await v,l){Ve(y);return}let E=c.current?.cssUrl??null;c.current={path:e,cssUrl:y},p=null,r(()=>R),i(!1),E&&Ve(E)}catch(g){p&&Ve(p),l||(a(g instanceof Error?g:new Error(String(g))),i(!1))}})(),()=>{l=!0}},[e,u]),(0,b.useEffect)(()=>()=>{c.current?.cssUrl&&Ve(c.current.cssUrl),c.current=null},[]),{Component:n,loading:s,error:o}}var tf=/^embed\/bundle-[A-Za-z0-9_-]+\.js$/,nf=/^embed\/bundle-[A-Za-z0-9_-]+\.css$/;function Ic(e,t,n){let r=Object.keys(e).filter(o=>t.test(o));if(r.length>1)throw new Error(`The published release has more than one in-app ${n}.`);let s=r[0];if(!s)return null;let i=Rt(e[s]).sha256;return typeof i=="string"&&i?{path:s,sha256:i}:null}var Pr=new Map,Di=new Map;se(()=>{Pr.clear(),Di.clear()});function Rt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function su(e){let t=Rt(Rt(e.type_data).published),n=t.published_release_item_id,r=t.published_version;return typeof n!="string"||!n||typeof r!="number"||!Number.isSafeInteger(r)||r<1?null:{releaseItemId:n,version:r}}async function Ac(e,t,n){let r=await br(e.path,{mode:"render"}),s=Rt(Rt(r.render).props).url;if(typeof s!="string"||!s)throw new Error(`The published ${n} could not be opened.`);let i=await fetch(s);if(!i.ok)throw new Error(`Failed to read the published ${n}: ${i.status} ${i.statusText}`.trim());let o=await i.arrayBuffer();if(Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",o))).map(c=>c.toString(16).padStart(2,"0")).join("")!==t)throw new Error(`The published ${n} does not match the bytes its release sealed.`);return new TextDecoder().decode(o)}async function rf(e,t,n){let r=await hr(t);if(!r)throw new Error("The published release could not be read.");let s=Rt(r.type_data);if(r.item_type!=="revdev_release"||s.component_item_id!==e||s.status!=="committed"||Number(s.version)!==n)throw new Error("This component's live version does not match its release record.");let i=Rt(s.artifacts),o=Ic(i,tf,"script");if(!o)return{status:"no_in_app_version",releaseItemId:t,version:n};let a=Ic(i,nf,"stylesheet"),c=a?[o.path,a.path]:[o.path],u=s.build_item_id;if(typeof u!="string"||!u)throw new Error("The published release names no build.");let{items:l}=await Bt({type:"file",parent_id:u,field_in:{package_path:c},limit:c.length},{throwOnError:!0}),f=h=>l.find(y=>Rt(y.type_data).package_path===h),m=f(o.path),p=a?f(a.path):void 0;if(!m||a&&!p)throw new Error("The published release's in-app files could not be found in its build.");let[g,_]=await Promise.all([Ac(m,o.sha256,"script"),p&&a?Ac(p,a.sha256,"stylesheet"):Promise.resolve(null)]);return{status:"ready",releaseItemId:t,version:n,script:g,stylesheet:_?.trim()?_:null}}function iu(e,t,n){let r=Pr.get(t);return r||(r=rf(e,t,n),Pr.set(t,r),r.catch(()=>{Pr.get(t)===r&&Pr.delete(t)})),r}function ou(e){let t=su(e);return!e.id||!t?Promise.resolve({status:"unpublished"}):iu(e.id,t.releaseItemId,t.version)}function au(e){let[t,n]=(0,b.useState)(null),[r,s]=(0,b.useState)("loading"),[i,o]=(0,b.useState)(null),a=(0,b.useRef)(null),c=e!=null,u=e?.id||null,l=e?su(e):null,f=l?.releaseItemId??null,m=l?.version??null;return(0,b.useEffect)(()=>{if(!c)return;let p=()=>{a.current?.cssKey&&Ve(a.current.cssKey),a.current=null,n(null)};if(!u||!f||m===null){p(),o(null),s("unpublished");return}let g=!1;return o(null),a.current&&a.current.componentId!==u&&p(),a.current||s("loading"),(async()=>{let _=null;try{let h=await iu(u,f,m);if(g)return;if(h.status!=="ready"){p(),s(h.status);return}let y=Di.get(f);if(!y){if(y=ru(h.script),!y)throw new Error("The published script did not hand over a component. Expected a __FSAOS_REGISTER__(Component) call or window.__FSAOS_COMPONENT__.");if(typeof y!="function")throw new Error(`The published script handed over something that is not a React component (${typeof y}).`);Di.set(f,y)}let v=h.stylesheet?`release:${f}`:null;if(v&&(_=v,await nu(v,async()=>h.stylesheet)),g){_&&Ve(_);return}let R=a.current?.cssKey??null;a.current={componentId:u,releaseItemId:f,cssKey:v},_=null,n({Component:y,version:m}),s("ready"),R&&Ve(R)}catch(h){if(_&&Ve(_),g)return;o(h instanceof Error?h:new Error(String(h))),a.current||s("error")}})(),()=>{g=!0}},[c,u,f,m]),(0,b.useEffect)(()=>()=>{a.current?.cssKey&&Ve(a.current.cssKey),a.current=null},[]),{Component:t?.Component??null,status:r,error:i,version:t?.version??null}}var sf=["--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 cu(){return{data:(0,b.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let t={},n=getComputedStyle(document.documentElement);return sf.forEach(r=>{t[r]=n.getPropertyValue(r).trim()}),{tokens:t}},[]),loading:!1,error:null}}function uu(e,t){return{data:{allowed:!0},loading:!1,error:null}}function lu(e,t){let n={};return(t||[]).forEach(r=>{n[r]=!0}),{data:n,loading:!1,error:null}}var fe=null,Qn=null,Ui=new Set;function of(){Ui.forEach(e=>e())}se(()=>{fe=null,Qn=null});async function du(e){let t={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null},n=bt()?.principal_id??null;if(n){if(fe&&fe.principalId===n){let{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}=fe;return{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}}return{...t,principalId:n}}let r=e;if(!r){let{data:s}=await V.auth.getSession();r=s?.session?.user?.id}if(!r)return t;if(fe&&fe.authUserId===r){let{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}=fe;return{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}}return Qn||(Qn=(async()=>{try{let{data:s,error:i}=await V.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 V.from("os_items").select("path").eq("owner_principal_id",o).eq("item_type","principal").eq("is_active",!0).like("path","/root/principals/%"),l=(u??[]).map(f=>f.path);a=l.find(f=>f.split("/").length===4)??l[0]??null}let c={principalId:o,displayName:s?.display_name??null,createdAt:s?.created_at??null,metadata:s?.metadata??null,vfsPath:a};return fe={authUserId:r,...c},c}finally{Qn=null}})(),Qn)}async function fu(e){return(await du(e)).principalId}function pu(){let e=Es(),t=e.user,n=fe?.authUserId===t?.id?fe:null,[r,s]=(0,b.useState)(n),i=(0,b.useRef)(null);return(0,b.useEffect)(()=>{let o=()=>{let a=fe;a&&a.authUserId===t?.id&&s({principalId:a.principalId,displayName:a.displayName,createdAt:a.createdAt,metadata:a.metadata,vfsPath:a.vfsPath})};return Ui.add(o),()=>{Ui.delete(o)}},[t?.id]),(0,b.useEffect)(()=>{if(!t?.id){s(null),i.current=null;return}i.current===t.id&&r?.principalId!=null||(i.current=t.id,du(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 mu(e){let{path:t,...n}=e,r=Hi(t),s=r.Component,{loading:i,error:o}=r;return i?(0,b.createElement)("div",{className:"fsaos-loading"},""):o?(0,b.createElement)("div",{className:"fsaos-error"},"Failed to load component"):s?(0,b.createElement)(s,n):null}function hu(e){return e.children}function gu(e){let t=ee(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=e,o=i!==void 0?i&&!!n:!!n,a=(0,b.useMemo)(()=>P.channelMessages(n??"",r),[n,r,t]),c=L(),u=(0,b.useRef)(null),l=B({queryKey:a,queryFn:()=>_s(n,r),enabled:o});(0,b.useEffect)(()=>{if(!s||!o)return;let _=ie("vfs_change",()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{ve(c,a,{exact:!0})},500)},h=>{let y=c.getQueryData(a);return Qi(h,n,r,[...y?.messages??[],...y?.activityMessages??[]])});return()=>{_(),u.current&&clearTimeout(u.current)}},[s,o,n,r,a,c]);let f=l.data,m=f?.messages??[],p=f?.messageCards??new Map,g=f?.siblingCards??[];return{messages:m,activityMessages:f?.activityMessages??[],messageCards:p,siblingCards:g,threads:(0,b.useMemo)(()=>m.filter(_=>_.reply_count>0),[m]),breakouts:(0,b.useMemo)(()=>m.filter(_=>_.member_count>0),[m]),isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function yu(e){ee();let{channelPath:t,parentMessageId:n,limit:r=50,realtime:s=!0,enabled:i=!0,conversationsOnly:o=!1,transcriptOnly:a=!1}=e,c=!!n,u=i&&!!t,l=ir({queryKey:[...P.channelMessages(t||"",n),"infinite",r,"latest-first",...o?["conversations"]:[],...a?["transcript"]:[]],queryFn:async({pageParam:y})=>vr(t,{parentMessageId:n,limit:r,conversationsOnly:o,transcriptOnly:a,before_seq:y?.before_seq,after_seq:y?.after_seq}),initialPageParam:void 0,getPreviousPageParam:y=>{if(!c||y.messages.length<r)return;let v=y.messages[y.messages.length-1]?.seq;return v==null?void 0:{after_seq:v}},getNextPageParam:y=>{if(y.messages.length<r)return;let v=y.messages[0]?.seq;return v==null?void 0:{before_seq:v}},enabled:u}),f=(0,b.useMemo)(()=>{if(!l.data?.pages)return[];let y=new Set,v=[];for(let R of l.data.pages)for(let E of R.messages)y.has(E.id)||(y.add(E.id),v.push(E));return v.sort((R,E)=>R.seq-E.seq)},[l.data?.pages]),{messageCards:m,siblingCards:p}=(0,b.useMemo)(()=>{let y=new Map,v=[];if(!l.data?.pages)return{messageCards:y,siblingCards:v};let R=new Set;for(let E of l.data.pages){for(let[w,O]of E.messageCards)for(let K of O){if(R.has(K.id))continue;R.add(K.id);let x=y.get(w)||[];x.push(K),y.set(w,x)}for(let w of E.siblingCards)R.has(w.id)||(R.add(w.id),v.push(w))}return{messageCards:y,siblingCards:v}},[l.data?.pages]),g=L(),_=(0,b.useRef)(null),h=(0,b.useMemo)(()=>[...P.channelMessages(t||"",n),"infinite",r,"latest-first",...o?["conversations"]:[],...a?["transcript"]:[]],[t,n,r,o,a]);return(0,b.useEffect)(()=>{if(!s||!t||!u)return;let y=()=>void ve(g,h,{exact:!0}),v=!1,R=!1,E=!1,w=async()=>{if(o||a){y();return}let x=g.getQueryData(h);if(!x?.pages?.length){y();return}let A=0;for(let k of x.pages)for(let I of k.messages)I.seq>A&&(A=I.seq);if(A===0){y();return}try{let k=await vr(t,{parentMessageId:n,limit:r,after_seq:A});if(k.messages.length===0&&k.siblingCards.length===0){y();return}if(k.messages.length>0){let I=Math.min(...k.messages.map(M=>M.seq));if(I>A+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${A}, minNewSeq=${I}. Triggering full refetch.`),y();return}}g.setQueryData(h,I=>{if(!I)return I;let M=[...I.pages],q=0,U=M[q],$=new Set(U.messages.map(Pe=>Pe.id)),Ce=k.messages.filter(Pe=>!$.has(Pe.id)),re=[...U.messages,...Ce].sort((Pe,Ns)=>Pe.seq-Ns.seq),Ct=new Map(U.messageCards);for(let[Pe,Ns]of k.messageCards){let oo=Ct.get(Pe)||[],Ol=new Set(oo.map(Qs=>Qs.id)),Fl=Ns.filter(Qs=>!Ol.has(Qs.id));Ct.set(Pe,[...oo,...Fl])}let Al=new Set(U.siblingCards.map(Pe=>Pe.id)),kl=k.siblingCards.filter(Pe=>!Al.has(Pe.id)),Ml=[...U.siblingCards,...kl];return M[q]={...U,activityMessages:k.activityMessages??[],messages:re,messageCards:Ct,siblingCards:Ml},{...I,pages:M}})}catch(k){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",k),y()}},O=async()=>{if(v){R=!0;return}v=!0;try{do R=!1,await w();while(R&&!E)}finally{v=!1}},K=ie("vfs_change",()=>{_.current&&clearTimeout(_.current),_.current=setTimeout(()=>{O()},500)},x=>(o||a)&&x?.item_type==="message"&&(g.getQueryData(h)?.pages??[]).some(A=>A.messages.some(k=>k.id===x.parent_id))||Qi(x,t,n,g.getQueryData(h)?.pages.flatMap(A=>A.messages)??[]));return()=>{E=!0,K(),_.current&&clearTimeout(_.current)}},[s,t,u,h,g,n,r,o,a]),{messages:f,activityMessages:l.data?.pages[0]?.activityMessages??[],messageCards:m,siblingCards:p,threads:f.filter(y=>y.reply_count>0),breakouts:f.filter(y=>y.member_count>0),isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch,hasPreviousPage:l.hasNextPage??!1,fetchPreviousPage:l.fetchNextPage,isFetchingPreviousPage:l.isFetchingNextPage??!1,hasNextPage:l.hasPreviousPage??!1,fetchNextPage:l.fetchPreviousPage,isFetchingNextPage:l.isFetchingPreviousPage??!1}}var _u=["open","active","strict","hand_raise"];function af(e){return e==="open"||e==="active"||e==="strict"||e==="hand_raise"?e:e==="on"||e==="auto"?"active":"strict"}function cf(e){if(Array.isArray(e))return e.filter(t=>typeof t=="string")}function kc(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:af(t.ai_mode),activeAgentIds:cf(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 Ts(e={}){let t=ee(),{realtime:n=!0,enabled:r=!0,includeArchived:s=!1}=e,i=L(),o=(0,b.useMemo)(()=>P.channels("all"),[t]),a=B({queryKey:o,queryFn:async()=>((await C("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(kc),enabled:r});return(0,b.useEffect)(()=>{if(!(!n||!r))return Cc(i,o,kc)},[n,r,o,i]),{channels:(0,b.useMemo)(()=>(a.data??[]).filter(u=>s||!u.isArchived),[a.data,s]),isLoading:a.isLoading,isFetching:a.isFetching,error:a.error,refetch:a.refetch}}function bu(e={}){let t=Ts(e),n=(0,b.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function vu(e={}){let t=Ts(e),n=(0,b.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function ji(e={}){let t=ee(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=e,o=L(),a=(0,b.useRef)(null),c=(0,b.useMemo)(()=>P.notifications(n,r),[n,r,t]),u=B({queryKey:c,queryFn:async()=>{let f={limit:r};return n==="unread"&&(f.filter="unread"),(await C("get-notifications",f)).notifications||[]},enabled:i});return(0,b.useEffect)(()=>{if(!s||!i)return;let f=["vfs_change","ccm_change"].map(m=>ie(m,()=>{a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{o.invalidateQueries({queryKey:c})},2e3)},p=>p.item_type==="notification"&&Rs(p)));return()=>{f.forEach(m=>m()),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 wu(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:o,error:a,refetch:c}=ji({filter:"unread",limit:200,realtime:n,enabled:r}),u=(0,b.useMemo)(()=>{let p=new Map;for(let g of s)g.is_unread&&g.channel_id&&p.set(g.channel_id,(p.get(g.channel_id)||0)+1);return p},[s]),l=(0,b.useMemo)(()=>{let p=0;return u.forEach(g=>{p+=g}),p},[u]),{dmUnread:f,channelUnread:m}=(0,b.useMemo)(()=>{if(!t)return{dmUnread:0,channelUnread:0};let p=new Set(t.filter(h=>h.isDm).map(h=>h.id)),g=0,_=0;return u.forEach((h,y)=>{p.has(y)?g+=h:_+=h}),{dmUnread:g,channelUnread:_}},[t,u]);return{unreadByChannel:u,totalUnread:l,dmUnread:f,channelUnread:m,isLoading:i,isFetching:o,error:a,refetch:c}}function Su(){let e=L();return te({mutationFn:t=>C("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:P.children(r)})}})}function xu(){let e=L();return te({mutationFn:t=>C("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 Ru(){return te({mutationFn:e=>C("update-principal",e),onSuccess:(e,t)=>{if(!fe)return;let n=e&&typeof e=="object"&&e.metadata?e.metadata:{...fe.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}:{}};fe={...fe,displayName:typeof t.display_name=="string"?t.display_name:fe.displayName,metadata:n},of()}})}function Cu(){let e=L();return te({mutationFn:t=>C("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 Pu(){let e=L();return te({mutationFn:t=>C("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 te({mutationFn:t=>C("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 te({mutationFn:i=>C(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 Iu(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,b.useRef)(s),c=(0,b.useRef)(i);(0,b.useEffect)(()=>{a.current=s,c.current=i},[s,i]),(0,b.useEffect)(()=>o?ie(r,l=>a.current(l),c.current?l=>c.current(l):void 0):void 0,[r,o])}function Au(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:o=500}=e,a=L(),c=(0,b.useRef)(s);c.current=s;let u=(0,b.useRef)(null),l=B({queryKey:t,queryFn:n,enabled:i});return(0,b.useEffect)(()=>{if(!i)return;let f=ie(r,()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{ve(a,t,{exact:!0})},o)},m=>c.current?.(m)??!0);return()=>{f(),u.current&&clearTimeout(u.current)}},[r,i,o,a,JSON.stringify(t)]),l}function Dn(e){ee();let t=W(),n=(0,b.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=B({queryKey:i,staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0},queryFn:async()=>{if(!n)return null;let m=await C("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}),a=o.data??null,c=(0,b.useMemo)(()=>a?.resolved_children??[],[a]),u=a?.resolution_level??null,l=(0,b.useMemo)(()=>{let p=(a?.type_data??null)?.order;return Array.isArray(p)?p:null},[a]),f=(0,b.useCallback)(m=>{if(!l||!m?.length)return m??[];let p=y=>y.id??y.name??"",g=new Map(l.map((y,v)=>[y,v])),_=[],h=[];for(let y of m)(g.has(p(y))?_:h).push(y);return _.sort((y,v)=>g.get(p(y))-g.get(p(v))),[..._,...h]},[l]);return{...o,arrangement:a,resolvedChildren:c,resolutionLevel:u,order:l,sourceScopeId:a?.scope_item_id??null,arrangementQueryKey:i,applyTo:f}}function ku(e){let{origin:t,originField:n,fallbackUrl:r,mintError:s,scopeId:i,scopePath:o}=e,a=ee(),c=bt(),u=i??c?.scope_id??null,l=(0,b.useMemo)(()=>{if(!t)return null;let w="/accounts/",O=t.indexOf(w);if(O===-1)return null;let K=t.indexOf("/",O+w.length);return K===-1?t:t.slice(0,K)},[t]),f=o??l??c?.scope_path??null,m=n?.trim()||null,p=`${a}
4
4
  ${u??""}
5
5
  ${f??""}
6
6
  ${m??""}
7
- ${t??""}`,[g,_]=(0,b.useState)(null),h=(0,b.useRef)({key:p,found:null,earlyContentPaths:new Set}),y=g?.key===p?g:null;(0,b.useLayoutEffect)(()=>{h.current={key:p,found:y,earlyContentPaths:new Set}},[p]);let v=$({queryKey:["vfs",f??"__unscoped__","minted-asset",m??"",t??""],queryFn:async()=>{let w=await P("query",{scope_path:f,filters:{[`field.${m}`]:t},limit:1}),O=w.content?.items??w.items??[],K=O[0]?Oe(O[0]):null;if(!K)return null;let A=(await pr(K.path)).some(k=>k.item_type==="file"&&!!k.type_data?.file_ref);return{asset:K,hasBytes:A}},enabled:!!(t&&f&&m&&!s),refetchInterval:w=>h.current.key===p&&h.current.found?.hasBytes||w.state.data?.hasBytes?!1:1500});(0,b.useEffect)(()=>{let w=v.data;if(!w||h.current.key!==p)return;let O=h.current.found,K={key:p,itemId:w.asset.id,itemPath:w.asset.path,displayName:typeof w.asset.type_data?.display_name=="string"?w.asset.type_data.display_name:w.asset.name,hasBytes:w.hasBytes||!!(O?.itemId===w.asset.id&&O.hasBytes)};h.current.found=K,_(K)},[v.data,p]);let R=!!(t&&u)&&!s&&!y?.hasBytes;return(0,b.useEffect)(()=>{if(!(!R||!u))return Tn(u,["asset.materialized","content.written"])},[R,u]),(0,b.useEffect)(()=>{if(!R||!t||!u)return;let w=p,O=E=>E?.payload??E,K=E=>{let q=O(E)?.scope_id??E?.scope_id;return typeof q=="string"?q:void 0},x=E=>{let q=O(E)?.item_path??E?.item_path;return typeof q=="string"&&q?q:void 0},A=(E,M)=>{let q=M.replace(/\/+$/,"");return E===q||E.startsWith(`${q}/`)},k=[ie("asset.materialized",E=>{if(h.current.key!==w)return;let M=O(E);if(typeof M?.item_id!="string"||!M.item_id)return;let q=h.current.found,U=typeof M.item_path=="string"?M.item_path:void 0,V=!!M.has_bytes||!!(U&&Array.from(h.current.earlyContentPaths).some(ne=>A(ne,U)))||!!(q&&q.itemId===M.item_id&&q.hasBytes),Re={key:w,itemId:M.item_id,itemPath:U,displayName:typeof M.display_name=="string"?M.display_name:void 0,hasBytes:V};h.current.found=Re,_(Re)},E=>{let M=K(E);return(!M||M===u)&&O(E)?.origin===t}),ie("content.written",E=>{if(h.current.key!==w)return;let M=x(E);if(!M)return;let q=h.current.found;if(!q?.itemPath||!A(M,q.itemPath)){if(h.current.earlyContentPaths.add(M),h.current.earlyContentPaths.size>128){let V=h.current.earlyContentPaths.values().next().value;V&&h.current.earlyContentPaths.delete(V)}return}if(q.hasBytes)return;let U={...q,hasBytes:!0};h.current.found=U,_(U)},E=>{let M=K(E);return(!M||M===u)&&!!x(E)})];return()=>k.forEach(E=>E())},[R,t,u,p]),{state:s?"failed":t?y?y.hasBytes?"ready":"materializing":"pending":"idle",itemId:y?.itemId,itemPath:y?.itemPath,displayName:y?.displayName,fallbackUrl:r??void 0,error:s??void 0}}function xu(e,t){let n=N().getDefaultOptions().queries?.retry??1;return typeof n=="function"?n(e,t):n===!0||typeof n=="number"&&e<n}function Ru(e,t){let n=(0,Fn.useSyncExternalStore)(Se,te,te),r=_e(),s=H(),i=r?.kind==="space",o=On(i&&s?{key:e,scope_id:r.id}:null),a=(0,Fn.useMemo)(()=>{let p=o.applyTo([...t]);if(e!=="channel-order")return p;let g=new Set(o.order??[]),_=p.filter(y=>!g.has(y.id)),h=y=>Date.parse(y.createdAt??"")||0;return _.sort((y,v)=>h(v)-h(y)),[..._,...p.filter(y=>g.has(y.id))]},[e,t,o.applyTo,o.order]),c=L(),u=(0,Fn.useRef)(!1),d=!!(i&&!o.error&&o.arrangement?.item_id&&o.resolutionLevel==="member"&&o.arrangement.write_target_id===o.arrangement.item_id),f=ee({mutationFn:async p=>{let g=await P("update",{_scope_path:p.scopePath,id:p.arrangementId,type_data:{order:p.ids}});if(g?.success===!1)throw new Error(g.error||"Order could not be saved");return g},onSettled:(p,g,_)=>tt(c,_.queryKey)});async function m(p){if(!d||!s||n!==te()||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 g=t.map(w=>w.id);if(p.length!==g.length||new Set(p).size!==g.length||g.some(w=>!p.includes(w)))throw new Error("Order must include each displayed item exactly once");let _=c.getQueryData(o.arrangementQueryKey);if(_?.item_id!==o.arrangement.item_id||JSON.stringify(_?.type_data?.order??[])!==JSON.stringify(o.order??[]))throw new Error("The saved order changed. Try dragging again");let h=a.map(w=>w.id);if(p.every((w,O)=>h[O]===w))return;let y=new Set(g),v=0,T=[...(o.order??[]).map(w=>y.has(w)?p[v++]:w),...p.slice(v)];u.current=!0;try{return await f.mutateAsync({ids:T,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:f.isPending,saveError:f.error,reorder:m}}var Qi=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,zd=/^[A-Za-z_:][A-Za-z0-9_:.-]{0,127}$/,Pu=new Map,Cu=new Map,qn=class extends Error{constructor(n,r,s,i){super(n);re(this,"code");re(this,"status");re(this,"eventId");this.name="InteractionTrackingError",this.code=r,this.status=s,this.eventId=i}};function Bt(e){let t=e?Ft.find(n=>n.id===e):Ft.find(n=>n.default===!0)??(Ft.length===1?Ft[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 Rs(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 Jd(e){return e.length>0&&e.length<=128&&!/[\u0000-\u001f\u007f]/.test(e)}function Yd(e,t){if(!Jd(t)||!e.observations?.includes(t))throw new TypeError("The observation is not declared by this release source")}function Di(e){if(!(typeof window>"u"||e.storage==="memory"))try{return e.storage==="session"?window.sessionStorage:window.localStorage}catch{return}}function Zd(e){try{let t=Di(e)?.getItem(e.key)??void 0;return t&&Qi.test(t)?t:void 0}catch{return}}function Tu(e,t){try{Di(e)?.setItem(e.key,t)}catch{}}function Iu(e){let t=e.identity?.visitor;if(!t?.key)throw new TypeError("The source visitor identity policy is invalid");let n=Zd(t)??Pu.get(e.id);if(n)return n;let r=crypto.randomUUID();return Pu.set(e.id,r),Tu(t,r),r}function Eu(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=Di(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"&&Qi.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),Tu(n,JSON.stringify(c)),c.id}function Xd(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 $t(e,t={},n={}){let r=Bt(n.source);if(Yd(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??Iu(r),o=n.sessionId??Eu(r);if(![s,i,o].every(h=>Qi.test(h)))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=Xd(r,a),f=d?{...t,source_keys:d}:t,m=Qt(),p=`${Ie.replace(/\/+$/,"")}/d/${encodeURIComponent(m)}/interactions`,g;try{g=await fetch(p,{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:f}]}),signal:n.signal,credentials:"omit",keepalive:n.keepalive??!1})}catch(h){throw new qn(h instanceof Error?h.message:"Observation transport network error","OBSERVATION_NETWORK_ERROR",0,s)}let _=null;try{_=await g.json()}catch{}if(!g.ok||_?.success!==!0){let h=_;throw new qn(h?.message||h?.error||`Observation transport failed (${g.status})`,h?.error||"OBSERVATION_TRANSPORT_FAILED",g.status,s)}return _}function Au(e={},t={}){let n=Bt(t.source),r=Rs("page_view",n),s=typeof document>"u"||!r.title_property?{}:{[r.title_property]:document.title.slice(0,512)};return $t(r.observation,{...s,...e},{...t,source:n.id})}function ku(e,t={},n={}){if(!e||e.length>128)throw new TypeError("actionId is invalid");let r=Bt(n.source),s=Rs("declared_action",r),i=s.id_property?{[s.id_property]:e}:{};return $t(s.observation,{...t,...i},{...n,source:r.id})}function Mu(){try{let e=Bt();return Rs("form_receipt",e),{visitor_id:Iu(e),session_id:Eu(e),source:e.id}}catch{return}}function ef(e,t={}){let n=Bt(t.source),r=Rs("form_receipt",n);return $t(r.observation,e,{...t,source:n.id})}async function tf(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 Ou(e,t,n,r,s){let i=Ft.filter(o=>o.adapters?.some(a=>a.type==="form_receipt"));await Promise.allSettled(i.map(async o=>{let a=o.id===r?.source;return ef(e,{source:o.id,eventId:a?t:await tf(t,o.id),pageUrl:n,signal:s,keepalive:!0,...a?{visitorId:r.visitor_id,sessionId:r.session_id}:{}})}))}var Rr;function Ps(e={}){if(typeof window>"u"||typeof document>"u")return()=>{};if(Rr)return Rr;if(window.__FSAOS_CONFIG__?.tracking?.enabled===!1)return()=>{};let t;try{t=e.source?[Bt(e.source)]:Ft.map(m=>Bt(m.id))}catch{return()=>{}}if(t.length===0)return()=>{};let n=e.pageViews===!1?[]:t.flatMap(m=>m.adapters.filter(p=>p.type==="page_view").map(p=>({source:m,adapter:p}))),r=e.declaredActions===!1?[]:t.flatMap(m=>m.adapters.filter(p=>p.type==="declared_action").map(p=>({source:m,adapter:p}))),s="",i=()=>{if(window.location.href!==s){s=window.location.href;for(let{source:m,adapter:p}of n){let g=p.title_property?{[p.title_property]:document.title.slice(0,512)}:{};$t(p.observation,g,{source:m.id,keepalive:!0}).catch(()=>{})}}},o=m=>{if(m.target instanceof Element)for(let{source:p,adapter:g}of r){let _=g.attribute;if(!_||!zd.test(_))continue;let h=m.target.closest(`[${_}]`);if(!h)continue;let y=h.getAttribute(_)?.trim();if(!y||y.length>128)continue;let v={};g.id_property&&(v[g.id_property]=y),g.element_property&&(v[g.element_property]=h.tagName.toLowerCase()),$t(g.observation,v,{source:p.id,keepalive:!0}).catch(()=>{})}},a=window.history.pushState,c=window.history.replaceState,u=()=>queueMicrotask(i),d=n.some(({adapter:m})=>m.history===!0),f=n.some(({adapter:m})=>m.pageshow===!0);return d&&(window.history.pushState=function(...p){a.apply(this,p),u()},window.history.replaceState=function(...p){c.apply(this,p),u()},window.addEventListener("popstate",i)),f&&window.addEventListener("pageshow",i),r.length>0&&document.addEventListener("click",o,{capture:!0}),n.length>0&&queueMicrotask(i),Rr=()=>{window.removeEventListener("popstate",i),window.removeEventListener("pageshow",i),document.removeEventListener("click",o,{capture:!0}),d&&(window.history.pushState=a,window.history.replaceState=c),Rr=void 0},Rr}var Nn;se(()=>{Nn=void 0});function Cs(e){if(Nn)return Nn.accountPath!==e.accountPath?Promise.reject(new Error("Reset the session before changing accounts")):Nn.promise;let t=ae(),n=()=>{if(t!==ae())throw new Error("Workspace session changed")},r=(async()=>{let s=await et();if(n(),!s.principal_id)throw new Error("Workspace initialization requires an authenticated principal");let i=await N().fetchQuery({queryKey:C.memberships(s.principal_id),queryFn:ms,staleTime:12e4,retry:!1});n();let o=i.find(f=>f.path===e.accountPath&&f.isAccount&&!f.isSpace);if(!o)throw new Error("Authenticated account membership is unavailable");let a=i.find(f=>f.isSpace&&f.accountId===o.personalSpaceId&&f.path===o.personalSpacePath);if(!a||!o.personalSpacePath)throw new Error("A provisioned default Space membership is required");let c=$e(o),u=$e(a),d=pe();if(d&&d.id!==c.id)throw new Error("Reset the session before changing accounts");return d||Nt(c,{activate:!1}),await jt(o.personalSpacePath,f=>{let m=i.find(p=>p.accountId===f&&(p.isAccount||p.isSpace));return m?$e(m):null},{initialAnchor:u}),n(),{home:c,defaultSpace:u,memberships:i}})().catch(s=>{throw t===ae()&&(Nn=void 0),s});return Nn={accountPath:e.accountPath,promise:r},r}var Vt,Cr,Pr;se(()=>{Cr?.(),Cr=void 0,Vt=void 0,Pr=void 0});function Fu(e={}){if(Vt)return e.workspace&&e.workspace.accountPath!==Pr?Promise.reject(new Error("Initialize workspace through initializeWorkspace, or dispose the existing runtime first")):Vt;Pr=e.workspace?.accountPath;let t=ae();return Vt=(async()=>{let n=e.tracking??!0,r=n===!1?()=>{}:Ps(typeof n=="object"?n:{});Cr=r;try{let s=e.session===!1?null:await et(),i=e.workspace?await Cs(e.workspace):void 0;if(t!==ae())throw new Error("Session changed during initialization");let o=!1;return{session:s,workspace:i,dispose(){o||(o=!0,r(),t===ae()&&(Vt=void 0,Pr=void 0,Cr=void 0))}}}catch(s){throw r(),t===ae()&&(Vt=void 0,Pr=void 0,Cr=void 0),s}})(),Vt}async function Ui(e){try{return await P("execution-control-transition",e)}catch(t){if(!(t instanceof ke)||t.status<500)throw t;return await new Promise(n=>setTimeout(n,250)),P("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 qu(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 Ui({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 Nu(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 Ui({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 Qu(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 Ui({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 nf=/^[a-z][a-z0-9_-]{0,63}$/,rf=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Qn=class extends Error{constructor(n,r,s,i){super(n);re(this,"code");re(this,"status");re(this,"fillId");this.name="FormSubmissionError",this.code=r,this.status=s,this.fillId=i}};async function Du(e,t,n={}){if(!nf.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(!rf.test(r))throw new TypeError("fillId must be a UUID");let s=Qt(),i=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!i)throw new TypeError("pageUrl is required outside a browser");let o=`${Ie.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(f){throw new Qn(f instanceof Error?f.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 f=d;throw new Qn(f?.message||f?.error||`Form submission failed (${u.status})`,f?.error||"FORM_SUBMISSION_FAILED",u.status,r)}return await Ou({fill_id:r,action_id:e,release_id:d.release_id},r,i,a,n.signal),d}var Li=z(ue(),1),Lu=z(Ku(),1);function ju(e){return P("read",{path:e})}function Bu(e,t){return P("list",{path:e,...t})}function $u(e){return P("create",e)}function Vu(e){return P("update",e)}function Wu(e){return P("create",e)}function Hu(e,t){let r=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return P("tools/call",{name:e,instance_path:r,...t||{}})}function Gu(e,t,n){return P("signal",{target_id:e,event_name:t,payload:n||{}})}function zu(e){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+e}var Ju={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(),bn(),N().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 Yu(){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,Lu.createRoot)(e).render((0,Li.createElement)(Zn,{client:N()},(0,Li.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 Zu(){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 ji(e){return P("invite-member",e)}function Bi(e){return P("accept-invite",e)}function $i(e){let t={};return e.role&&(t.role=e.role),P("link",{source_id:e.chat_id,target_id:e.member_id,edge_type:"has_member",context:t})}function Vi(e){return P("create-agent",e)}function Wi(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.")):P("todo-control",{action:"answer_input",...e})}function Xu(){return ee({mutationFn:ji})}function el(){let e=L();return ee({mutationFn:Bi,onSuccess:()=>{e.invalidateQueries({queryKey:["memberships"]})}})}function tl(){let e=L();return ee({mutationFn:$i,onSuccess:(t,n)=>{e.invalidateQueries({queryKey:C.edges(n.chat_id)}),e.invalidateQueries({queryKey:C.edges(n.member_id)})}})}function nl(){let e=L();return ee({mutationFn:Vi,onSuccess:()=>{e.invalidateQueries({queryKey:["memberships"]})}})}function rl(){let e=L();return ee({mutationFn:Wi,onSuccess:(t,n)=>{e.invalidateQueries({queryKey:C.itemById(n.step_id)})}})}function sf(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function of(e,t){return t&&t.length>0?"select":e==="boolean"?"toggle":e==="integer"||e==="number"?"range":e==="string"?"text":"none"}function af(e,t){return!(e==="object"||e==="array")}function cf(e){return["string","number","integer","boolean"].includes(e)}function uf(e){return e!=="object"&&e!=="array"}function sl(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=af(c,u),f=cf(c),m=of(c,u);i.push({key:o,label:a.title||sf(o),type:c,description:a.description,enum_values:u,default_value:n[o]??r[o]??a.default,editable:t,filterable:d,sortable:f,filter_widget:m})}return i}function Hi(e){let t=e.default_data||{},n=e.field_defaults||{},r=sl(e.input_schema,!0,t,n),s=sl(e.system_schema,!1,t,n),i=[...r,...s],o=i.filter(u=>uf(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 il(e){return{field:"updated_at",direction:"desc"}}function ol(e){let t=Hi(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=z(ue(),1);function al(){if(globalThis.crypto?.randomUUID)return globalThis.crypto.randomUUID();let e=new Uint8Array(16);if(globalThis.crypto?.getRandomValues){globalThis.crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,n=>n.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let n=Math.floor(Math.random()*16);return(t==="x"?n:n&3|8).toString(16)})}async function cl(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=t.collisionPolicy||"keep_both",c=a==="keep_both"?al():void 0,u={parent_path:t.parentPath,item_type:o,name:s,type_data:{...t.typeData||{},file_source:{type:"upload",content_type:i,collision_policy:a,...c?{upload_id:c}:{}}}};t.cardParentPath&&(u.card_parent_path=t.cardParentPath);let f=await P("create",u);if(!f.id)throw new Error(f.error||f.message||"Failed to create file item");let m=f.id,p=f.path;if(f.storage_completed&&f.file_ref)return{itemId:m,itemPath:p,fileRef:f.file_ref};let g=f.storage_key,_=f.upload_token,h=f.storage_worker_url||"https://fsaos-storage.radns.workers.dev";if(!g)throw new Error("Gateway returned no storage_key \u2014 file_source may not be supported for this item type");await lf(h,g,_,e,i,n,r);let y=await ul(m,g,i);return{itemId:m,itemPath:p,fileRef:y}}function lf(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 ul(e,t,n){let r=await Xe(),s=await fetch(`${Ie}/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 ll(){let[e,t]=(0,ve.useState)([]),n=L(),r=(0,ve.useRef)(e);r.current=e;let s=(0,ve.useCallback)((_,h)=>{t(y=>y.map(v=>v.id===_?{...v,...h}:v))},[]),i=(0,ve.useCallback)(_=>{t(h=>[...h,_])},[]),o=(0,ve.useCallback)(async(_,h,y,v,R)=>{let T=y.name||h.name,w=h.type||"application/octet-stream",O=y.itemType||"file",K=y.collisionPolicy||"keep_both",x=R?.itemId||null,A=R?.itemPath||null,k=R?.storageKey||null,E=R?.uploadToken||null,M=R?.storageWorkerUrl||null;try{if(!v||v==="create"){s(_,{status:"creating",error:null,_failedAt:null});let V=await P("create",{parent_path:y.parentPath,item_type:O,name:T,type_data:{...y.typeData||{},file_source:{type:"upload",content_type:w,collision_policy:K,...K==="keep_both"?{upload_id:_}:{}}}});if(!V.id)throw Object.assign(new Error(V.error||V.message||"Failed to create file item"),{_step:"create"});if(x=V.id,A=V.path,s(_,{itemId:x,itemPath:A}),V.storage_completed&&V.file_ref){s(_,{status:"complete",progress:100,fileRef:V.file_ref}),n.invalidateQueries({queryKey:C.children(y.parentPath)});return}if(k=V.storage_key,E=V.upload_token||"",M=V.storage_worker_url||"https://fsaos-storage.radns.workers.dev",s(_,{_storageKey:k,_uploadToken:E,_storageWorkerUrl:M}),!k)throw Object.assign(new Error("Gateway returned no storage_key"),{_step:"create"})}(!v||v==="create"||v==="upload")&&(s(_,{status:"uploading",progress:0,error:null,_failedAt:null}),await new Promise((V,Re)=>{let ne=new XMLHttpRequest;s(_,{_xhr:ne}),ne.open("PUT",`${M}/upload`),ne.setRequestHeader("X-Storage-Key",k),ne.setRequestHeader("Content-Type",w),E&&ne.setRequestHeader("X-Upload-Token",E),ne.upload.onprogress=xt=>{xt.lengthComputable&&s(_,{progress:Math.round(xt.loaded/xt.total*100)})},ne.onload=()=>{ne.status>=200&&ne.status<300?V():Re(Object.assign(new Error(`Storage upload failed: HTTP ${ne.status}`),{_step:"upload"}))},ne.onerror=()=>Re(Object.assign(new Error("Storage upload network error"),{_step:"upload"})),ne.ontimeout=()=>Re(Object.assign(new Error("Storage upload timed out"),{_step:"upload"})),ne.send(h)}),s(_,{progress:100,_xhr:null})),s(_,{status:"confirming",error:null,_failedAt:null});let q=await ul(x,k,w);s(_,{status:"complete",fileRef:q}),n.invalidateQueries({queryKey:C.children(y.parentPath)})}catch(q){let U=q?.message||String(q),V=q?._step||"create";s(_,{status:"error",error:U,_failedAt:V,_xhr:null})}},[s,n]),a=(0,ve.useCallback)((_,h)=>{let y=al();i({id:y,file:_,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(y,_,h)},[i,o]),c=(0,ve.useCallback)((_,h)=>{for(let y of _)a(y,h)},[a]),u=(0,ve.useCallback)(_=>{let h=r.current.find(R=>R.id===_);if(!h||h.status!=="error")return;let y=h._failedAt||"create",v=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(_,h.file,h.options,y,v)},[o]),d=(0,ve.useCallback)(_=>{let h=r.current.find(y=>y.id===_);h&&(h._xhr&&h._xhr.abort(),s(_,{status:"error",error:"Cancelled",_xhr:null,_failedAt:null}))},[s]),f=(0,ve.useCallback)(_=>{t(h=>h.filter(y=>y.id!==_))},[]),m=(0,ve.useCallback)(()=>{t(_=>_.filter(h=>h.status!=="complete"))},[]),p=e.some(_=>_.status==="creating"||_.status==="uploading"||_.status==="confirming"),g=e.map(({_storageKey:_,_uploadToken:h,_storageWorkerUrl:y,_xhr:v,_failedAt:R,...T})=>T);return{upload:a,uploadMultiple:c,uploads:g,retryUpload:u,cancelUpload:d,removeUpload:f,clearCompleted:m,isUploading:p}}var dl=z(ue(),1);async function Gi(e,t){return await P("resolve-items",{context_id:e,item_type:t})}function fl(e,t){return(0,dl.useSyncExternalStore)(Se,te,te),$({queryKey:["vfs",H()??"__unscoped__","resolved-items",e??"",t],queryFn:()=>Gi(e,t),enabled:!!(e&&t)})}var Ne=z(ue(),1);function Ts(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 f=r.get(c.tool_id);n.timeline[f].artifact_ids.push(c.artifact_id)}else{let f=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,f)}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 f=r.get(c.tool_id);if(f!==void 0){let m=n.timeline[f];c.status==="executing"?m.status="executing":c.status==="completed"?(m.status="completed",m.completed_at=Date.now()):c.status==="failed"&&(m.status="failed",m.completed_at=Date.now()),c.target_uri&&!m.target_uri&&(m.target_uri=c.target_uri)}break}}t(n)}return rs(e,s)}function pl(e,t=!0){let[n,r]=(0,Ne.useState)(new Map),[s,i]=(0,Ne.useState)([]),o=(0,Ne.useRef)({artifacts:new Map,timeline:[]});(0,Ne.useEffect)(()=>!e||!t?void 0:Ts(e,f=>{o.current=f,r(new Map(f.artifacts)),i([...f.timeline])}),[e,t]);let a=(0,Ne.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 ml(e,t=!0){let[n,r]=(0,Ne.useState)([]);(0,Ne.useEffect)(()=>!e||!t?void 0:Ts(e,o=>{r([...o.timeline])}),[e,t]);let s=n.length>0?n[n.length-1]:null;return{timeline:n,latestActivity:s}}var Is=z(ue(),1);function df(e,t,n,r){return["vfs","timeline-history",e,t??"__all__",n??500,r??0]}async function zi(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 P("open",{path:n,mode:"extract",strategy:"rows",arguments:i}))?.content;return a?(a.rows??a.items??a.data??[]).map(ff).sort((u,d)=>u.seq-d.seq):[]}catch(o){if(o?.status===404||o?.message?.includes("not found"))return[];throw o}}function hl(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,Is.useRef)(null),d=a?df(a,n,r,s):["vfs","timeline-history","__disabled__"],f=$({queryKey:d,queryFn:()=>zi(e,{turnId:n,limit:r,offset:s}),enabled:!!e&&i});return(0,Is.useEffect)(()=>{if(!a||!i)return;let m=ie("vfs_change",()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{c.invalidateQueries({queryKey:d})},o)},p=>{let g=p?.path;return g?g===a&&p.item_type==="dataset":!1});return()=>{m(),u.current&&clearTimeout(u.current)}},[a,i,o,c,JSON.stringify(d)]),{events:f.data??[],isLoading:f.isLoading,error:f.error,isFetching:f.isFetching,refetch:()=>{f.refetch()}}}function ff(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 Es=z(ue(),1);function gl(){(0,Es.useSyncExternalStore)(Se,te,te);let e=H(),t=_e(),n=On(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=ee({mutationFn:async c=>{let u,d={_scope_path:c.scopePath};if(c.operation==="pin"?u=await P("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 P("delete",{...d,id:c.entry.id}):u=await P("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)=>tt(r,d.queryKey)}),a=(0,Es.useCallback)(c=>!i||!e||H()!==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 As=z(ue(),1);var Tr=(e,t,n)=>["vfs",e,"personal-sections",t,n];function Ji(e,t){return e&&e.item_id===t.item_id&&e.version>t.version?e:t}async function Yi(e,t,n,r){let s=await P("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 yl(e,t){let n=await Yi(e.scopePath,e.contextId,e.collection,{operation:"assign",section_id:e.sectionId,target_id:t}),r=N();return r.setQueryData(Tr(e.scopePath,e.contextId,e.collection),s=>Ji(s,n)),_l(r,e.scopePath),n}function _l(e,t){for(let n of e.getQueryCache().getAll())n.queryKey[0]==="vfs"&&n.queryKey[1]===t&&n.queryKey[2]==="personal-sections"&&tt(e,n.queryKey)}function bl(e,t){let n=(0,As.useSyncExternalStore)(Se,te,te),r=H(),s=L(),i=Tr(r,e,t),o=$({queryKey:i,enabled:!!r&&!!e,queryFn:()=>Yi(r,e,t,{operation:"list"}),staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0,personalSections:!0},structuralSharing:(f,m)=>Ji(f,m)}),a=(0,As.useRef)(!1),c=ee({mutationFn:async f=>{let m=await Yi(f.scope,f.context,f.collection,{...f.change,...f.change.operation.startsWith("reorder")?{expected_version:f.version}:{}});return s.setQueryData(Tr(f.scope,f.context,f.collection),p=>Ji(p,m)),m},onSettled:(f,m,p)=>_l(s,p.scope)});async function u(f){if(!r||!e||n!==te()||H()!==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:f,scope:r,context:e,collection:t,version:o.data.version})}finally{a.current=!1}}function d(f){if(!r||!e||!o.data?.sections.some(m=>m.id===f))throw new Error("Section is unavailable");return{scopePath:r,contextId:e,collection:t,sectionId:f}}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}`}}Wc(Zi);return kl(Zi);})();
7
+ ${t??""}`,[g,_]=(0,b.useState)(null),h=(0,b.useRef)({key:p,found:null,earlyContentPaths:new Set}),y=g?.key===p?g:null;(0,b.useLayoutEffect)(()=>{h.current={key:p,found:y,earlyContentPaths:new Set}},[p]);let v=B({queryKey:["vfs",f??"__unscoped__","minted-asset",m??"",t??""],queryFn:async()=>{let w=await C("query",{scope_path:f,filters:{[`field.${m}`]:t},limit:1}),O=w.content?.items??w.items??[],K=O[0]?Oe(O[0]):null;if(!K)return null;let A=(await yr(K.path)).some(k=>k.item_type==="file"&&!!k.type_data?.file_ref);return{asset:K,hasBytes:A}},enabled:!!(t&&f&&m&&!s),refetchInterval:w=>h.current.key===p&&h.current.found?.hasBytes||w.state.data?.hasBytes?!1:1500});(0,b.useEffect)(()=>{let w=v.data;if(!w||h.current.key!==p)return;let O=h.current.found,K={key:p,itemId:w.asset.id,itemPath:w.asset.path,displayName:typeof w.asset.type_data?.display_name=="string"?w.asset.type_data.display_name:w.asset.name,hasBytes:w.hasBytes||!!(O?.itemId===w.asset.id&&O.hasBytes)};h.current.found=K,_(K)},[v.data,p]);let R=!!(t&&u)&&!s&&!y?.hasBytes;return(0,b.useEffect)(()=>{if(!(!R||!u))return Mn(u,["asset.materialized","content.written"])},[R,u]),(0,b.useEffect)(()=>{if(!R||!t||!u)return;let w=p,O=I=>I?.payload??I,K=I=>{let q=O(I)?.scope_id??I?.scope_id;return typeof q=="string"?q:void 0},x=I=>{let q=O(I)?.item_path??I?.item_path;return typeof q=="string"&&q?q:void 0},A=(I,M)=>{let q=M.replace(/\/+$/,"");return I===q||I.startsWith(`${q}/`)},k=[ie("asset.materialized",I=>{if(h.current.key!==w)return;let M=O(I);if(typeof M?.item_id!="string"||!M.item_id)return;let q=h.current.found,U=typeof M.item_path=="string"?M.item_path:void 0,$=!!M.has_bytes||!!(U&&Array.from(h.current.earlyContentPaths).some(re=>A(re,U)))||!!(q&&q.itemId===M.item_id&&q.hasBytes),Ce={key:w,itemId:M.item_id,itemPath:U,displayName:typeof M.display_name=="string"?M.display_name:void 0,hasBytes:$};h.current.found=Ce,_(Ce)},I=>{let M=K(I);return(!M||M===u)&&O(I)?.origin===t}),ie("content.written",I=>{if(h.current.key!==w)return;let M=x(I);if(!M)return;let q=h.current.found;if(!q?.itemPath||!A(M,q.itemPath)){if(h.current.earlyContentPaths.add(M),h.current.earlyContentPaths.size>128){let $=h.current.earlyContentPaths.values().next().value;$&&h.current.earlyContentPaths.delete($)}return}if(q.hasBytes)return;let U={...q,hasBytes:!0};h.current.found=U,_(U)},I=>{let M=K(I);return(!M||M===u)&&!!x(I)})];return()=>k.forEach(I=>I())},[R,t,u,p]),{state:s?"failed":t?y?y.hasBytes?"ready":"materializing":"pending":"idle",itemId:y?.itemId,itemPath:y?.itemPath,displayName:y?.displayName,fallbackUrl:r??void 0,error:s??void 0}}function Mu(e,t){let n=N().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,Un.useSyncExternalStore)(xe,ne,ne),r=de(),s=W(),i=r?.kind==="space",o=Dn(i&&s?{key:e,scope_id:r.id}:null),a=(0,Un.useMemo)(()=>{let p=o.applyTo([...t]);if(e!=="channel-order")return p;let g=new Set(o.order??[]),_=p.filter(y=>!g.has(y.id)),h=y=>Date.parse(y.createdAt??"")||0;return _.sort((y,v)=>h(v)-h(y)),[..._,...p.filter(y=>g.has(y.id))]},[e,t,o.applyTo,o.order]),c=L(),u=(0,Un.useRef)(!1),l=!!(i&&!o.error&&o.arrangement?.item_id&&o.resolutionLevel==="member"&&o.arrangement.write_target_id===o.arrangement.item_id),f=te({mutationFn:async p=>{let g=await C("update",{_scope_path:p.scopePath,id:p.arrangementId,type_data:{order:p.ids}});if(g?.success===!1)throw new Error(g.error||"Order could not be saved");return g},onSettled:(p,g,_)=>rt(c,_.queryKey)});async function m(p){if(!l||!s||n!==ne()||W()!==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(w=>w.id);if(p.length!==g.length||new Set(p).size!==g.length||g.some(w=>!p.includes(w)))throw new Error("Order must include each displayed item exactly once");let _=c.getQueryData(o.arrangementQueryKey);if(_?.item_id!==o.arrangement.item_id||JSON.stringify(_?.type_data?.order??[])!==JSON.stringify(o.order??[]))throw new Error("The saved order changed. Try dragging again");let h=a.map(w=>w.id);if(p.every((w,O)=>h[O]===w))return;let y=new Set(g),v=0,E=[...(o.order??[]).map(w=>y.has(w)?p[v++]:w),...p.slice(v)];u.current=!0;try{return await f.mutateAsync({ids:E,scopePath:s,arrangementId:o.arrangement.item_id,queryKey:o.arrangementQueryKey})}finally{u.current=!1}}return{items:a,ready:l,supported:i,contextKey:`${n}:${s}:${e}`,isLoading:i&&o.isLoading,error:o.error,refetch:o.refetch,isSaving:f.isPending,saveError:f.error,reorder:m}}var Bi=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,uf=/^[A-Za-z_:][A-Za-z0-9_:.-]{0,127}$/,Fu=new Map,qu=new Map,Kn=class extends Error{constructor(n,r,s,i){super(n);z(this,"code");z(this,"status");z(this,"eventId");this.name="InteractionTrackingError",this.code=r,this.status=s,this.eventId=i}};function Wt(e){let t=e?Nt.find(n=>n.id===e):Nt.find(n=>n.default===!0)??(Nt.length===1?Nt[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 Is(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 lf(e){return e.length>0&&e.length<=128&&!/[\u0000-\u001f\u007f]/.test(e)}function df(e,t){if(!lf(t)||!e.observations?.includes(t))throw new TypeError("The observation is not declared by this release source")}function $i(e){if(!(typeof window>"u"||e.storage==="memory"))try{return e.storage==="session"?window.sessionStorage:window.localStorage}catch{return}}function ff(e){try{let t=$i(e)?.getItem(e.key)??void 0;return t&&Bi.test(t)?t:void 0}catch{return}}function Nu(e,t){try{$i(e)?.setItem(e.key,t)}catch{}}function Qu(e){let t=e.identity?.visitor;if(!t?.key)throw new TypeError("The source visitor identity policy is invalid");let n=ff(t)??Fu.get(e.id);if(n)return n;let r=crypto.randomUUID();return Fu.set(e.id,r),Nu(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=$i(n)?.getItem(n.key);r=u?JSON.parse(u):void 0}catch{r=void 0}let s=qu.get(e.id),i=r&&typeof r.id=="string"&&Bi.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 qu.set(e.id,c),Nu(n,JSON.stringify(c)),c.id}function pf(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 Gt(e,t={},n={}){let r=Wt(n.source);if(df(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??Qu(r),o=n.sessionId??Du(r);if(![s,i,o].every(h=>Bi.test(h)))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),l=pf(r,a),f=l?{...t,source_keys:l}:t,m=Ut(),p=`${Ie.replace(/\/+$/,"")}/d/${encodeURIComponent(m)}/interactions`,g;try{g=await fetch(p,{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:f}]}),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 _=null;try{_=await g.json()}catch{}if(!g.ok||_?.success!==!0){let h=_;throw new Kn(h?.message||h?.error||`Observation transport failed (${g.status})`,h?.error||"OBSERVATION_TRANSPORT_FAILED",g.status,s)}return _}function Uu(e={},t={}){let n=Wt(t.source),r=Is("page_view",n),s=typeof document>"u"||!r.title_property?{}:{[r.title_property]:document.title.slice(0,512)};return Gt(r.observation,{...s,...e},{...t,source:n.id})}function Ku(e,t={},n={}){if(!e||e.length>128)throw new TypeError("actionId is invalid");let r=Wt(n.source),s=Is("declared_action",r),i=s.id_property?{[s.id_property]:e}:{};return Gt(s.observation,{...t,...i},{...n,source:r.id})}function Lu(){try{let e=Wt();return Is("form_receipt",e),{visitor_id:Qu(e),session_id:Du(e),source:e.id}}catch{return}}function mf(e,t={}){let n=Wt(t.source),r=Is("form_receipt",n);return Gt(r.observation,e,{...t,source:n.id})}async function hf(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=Nt.filter(o=>o.adapters?.some(a=>a.type==="form_receipt"));await Promise.allSettled(i.map(async o=>{let a=o.id===r?.source;return mf(e,{source:o.id,eventId:a?t:await hf(t,o.id),pageUrl:n,signal:s,keepalive:!0,...a?{visitorId:r.visitor_id,sessionId:r.session_id}:{}})}))}var Tr;function As(e={}){if(typeof window>"u"||typeof document>"u")return()=>{};if(Tr)return Tr;if(window.__FSAOS_CONFIG__?.tracking?.enabled===!1)return()=>{};let t;try{t=e.source?[Wt(e.source)]:Nt.map(m=>Wt(m.id))}catch{return()=>{}}if(t.length===0)return()=>{};let n=e.pageViews===!1?[]:t.flatMap(m=>m.adapters.filter(p=>p.type==="page_view").map(p=>({source:m,adapter:p}))),r=e.declaredActions===!1?[]:t.flatMap(m=>m.adapters.filter(p=>p.type==="declared_action").map(p=>({source:m,adapter:p}))),s="",i=()=>{if(window.location.href!==s){s=window.location.href;for(let{source:m,adapter:p}of n){let g=p.title_property?{[p.title_property]:document.title.slice(0,512)}:{};Gt(p.observation,g,{source:m.id,keepalive:!0}).catch(()=>{})}}},o=m=>{if(m.target instanceof Element)for(let{source:p,adapter:g}of r){let _=g.attribute;if(!_||!uf.test(_))continue;let h=m.target.closest(`[${_}]`);if(!h)continue;let y=h.getAttribute(_)?.trim();if(!y||y.length>128)continue;let v={};g.id_property&&(v[g.id_property]=y),g.element_property&&(v[g.element_property]=h.tagName.toLowerCase()),Gt(g.observation,v,{source:p.id,keepalive:!0}).catch(()=>{})}},a=window.history.pushState,c=window.history.replaceState,u=()=>queueMicrotask(i),l=n.some(({adapter:m})=>m.history===!0),f=n.some(({adapter:m})=>m.pageshow===!0);return l&&(window.history.pushState=function(...p){a.apply(this,p),u()},window.history.replaceState=function(...p){c.apply(this,p),u()},window.addEventListener("popstate",i)),f&&window.addEventListener("pageshow",i),r.length>0&&document.addEventListener("click",o,{capture:!0}),n.length>0&&queueMicrotask(i),Tr=()=>{window.removeEventListener("popstate",i),window.removeEventListener("pageshow",i),document.removeEventListener("click",o,{capture:!0}),l&&(window.history.pushState=a,window.history.replaceState=c),Tr=void 0},Tr}var Ln;se(()=>{Ln=void 0});function ks(e){if(Ln)return Ln.accountPath!==e.accountPath?Promise.reject(new Error("Reset the session before changing accounts")):Ln.promise;let t=ae(),n=()=>{if(t!==ae())throw new Error("Workspace session changed")},r=(async()=>{let s=await nt();if(n(),!s.principal_id)throw new Error("Workspace initialization requires an authenticated principal");let i=await N().fetchQuery({queryKey:P.memberships(s.principal_id),queryFn:bs,staleTime:12e4,retry:!1});n();let o=i.find(f=>f.path===e.accountPath&&f.isAccount&&!f.isSpace);if(!o)throw new Error("Authenticated account membership is unavailable");let a=i.find(f=>f.isSpace&&f.accountId===o.personalSpaceId&&f.path===o.personalSpacePath);if(!a||!o.personalSpacePath)throw new Error("A provisioned default Space membership is required");let c=$e(o),u=$e(a),l=me();if(l&&l.id!==c.id)throw new Error("Reset the session before changing accounts");return l||Dt(c,{activate:!1}),await Vt(o.personalSpacePath,f=>{let m=i.find(p=>p.accountId===f&&(p.isAccount||p.isSpace));return m?$e(m):null},{initialAnchor:u}),n(),{home:c,defaultSpace:u,memberships:i}})().catch(s=>{throw t===ae()&&(Ln=void 0),s});return Ln={accountPath:e.accountPath,promise:r},r}var zt,Ar,Ir;se(()=>{Ar?.(),Ar=void 0,zt=void 0,Ir=void 0});function ju(e={}){if(zt)return e.workspace&&e.workspace.accountPath!==Ir?Promise.reject(new Error("Initialize workspace through initializeWorkspace, or dispose the existing runtime first")):zt;Ir=e.workspace?.accountPath;let t=ae();return zt=(async()=>{let n=e.tracking??!0,r=n===!1?()=>{}:As(typeof n=="object"?n:{});Ar=r;try{let s=e.session===!1?null:await nt(),i=e.workspace?await ks(e.workspace):void 0;if(t!==ae())throw new Error("Session changed during initialization");let o=!1;return{session:s,workspace:i,dispose(){o||(o=!0,r(),t===ae()&&(zt=void 0,Ir=void 0,Ar=void 0))}}}catch(s){throw r(),t===ae()&&(zt=void 0,Ir=void 0,Ar=void 0),s}})(),zt}function gf(e){return e instanceof Fe?{kind:"denied",payload:e.payload}:e instanceof he?{kind:"gateway",method:e.method,status:e.status,statusText:e.statusText,payload:e.payload,responseBody:e.responseBody}:e instanceof Error?{kind:"other",name:e.name,message:e.message}:{kind:"other",name:"Error",message:String(e)}}function Bu(e){let t=(s,i)=>{s.postMessage(i,e.origin)},n=!0,r=s=>{if(s.origin!==e.origin)return;let i=e.frame();if(!i||s.source!==i||!wi(s.data))return;let o=s.data;if(o.kind==="hello"){t(i,{fsaos:Lt,kind:"welcome",anchor:de()??_t(),item:e.item?.()??null});return}if(o.kind!=="call"||typeof o.id!="string"||typeof o.method!="string")return;let{id:a,method:c,params:u}=o;C(c,u&&typeof u=="object"?u:{}).then(l=>{n&&t(i,{fsaos:Lt,kind:"result",id:a,ok:!0,response:l})},l=>{n&&t(i,{fsaos:Lt,kind:"result",id:a,ok:!1,error:gf(l)})})};return window.addEventListener("message",r),()=>{n=!1,window.removeEventListener("message",r)}}async function Vi(e){try{return await C("execution-control-transition",e)}catch(t){if(!(t instanceof he)||t.status<500)throw t;return await new Promise(n=>setTimeout(n,250)),C("execution-control-transition",e)}}function Wi(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 $u(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 Vi({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 Wi(i?{...s,state:i}:s)}async function Vu(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 Vi({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 Wi(a?{...o,state:a}:o)}async function Wu(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 Vi({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 Wi(i?{...s,outcome:i}:s)}var yf=/^[a-z][a-z0-9_-]{0,63}$/,_f=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Hn=class extends Error{constructor(n,r,s,i){super(n);z(this,"code");z(this,"status");z(this,"fillId");this.name="FormSubmissionError",this.code=r,this.status=s,this.fillId=i}};async function Gu(e,t,n={}){if(!yf.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(!_f.test(r))throw new TypeError("fillId must be a UUID");let s=Ut(),i=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!i)throw new TypeError("pageUrl is required outside a browser");let o=`${Ie.replace(/\/+$/,"")}/d/${encodeURIComponent(s)}/actions/${encodeURIComponent(e)}`,a=Lu(),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(f){throw new Hn(f instanceof Error?f.message:"Form submission network error","FORM_NETWORK_ERROR",0,r)}let l=null;try{l=await u.json()}catch{}if(!u.ok||l?.success!==!0){let f=l;throw new Hn(f?.message||f?.error||`Form submission failed (${u.status})`,f?.error||"FORM_SUBMISSION_FAILED",u.status,r)}return await Hu({fill_id:r,action_id:e,release_id:l.release_id},r,i,a,n.signal),l}var Gi=Y(ue(),1),Yu=Y(Ju(),1);function Zu(e){return C("read",{path:e})}function Xu(e,t){return C("list",{path:e,...t})}function el(e){return C("create",e)}function tl(e){return C("update",e)}function nl(e){return C("create",e)}function rl(e,t){let r=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return C("tools/call",{name:e,instance_path:r,...t||{}})}function sl(e,t,n){return C("signal",{target_id:e,event_name:t,payload:n||{}})}function il(e){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+e}var ol={signIn:e=>e.provider?V.auth.signInWithOAuth({provider:e.provider,options:{redirectTo:e.redirectTo||window.location.href}}):V.auth.signInWithPassword({email:e.email,password:e.password}),signUp:e=>V.auth.signUp({email:e.email,password:e.password,options:{data:e.metadata||{}}}),signOut:async()=>{await V.auth.signOut(),Rn(),N().clear()},getSession:()=>V.auth.getSession().then(e=>e.data.session),getUser:()=>V.auth.getUser().then(e=>e.data.user),onAuthStateChange:e=>{let{data:{subscription:t}}=V.auth.onAuthStateChange((n,r)=>{e({event:n,session:r,user:r?.user??null})});return()=>t?.unsubscribe()},resetPassword:e=>V.auth.resetPasswordForEmail(e),signInWithMagicLink:(e,t)=>V.auth.signInWithOtp({email:e,options:{emailRedirectTo:t||window.location.href}})};function al(){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,Yu.createRoot)(e).render((0,Gi.createElement)(rr,{client:N()},(0,Gi.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 cl(){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 zi(e){return C("invite-member",e)}function Ji(e){return C("accept-invite",e)}function Yi(e){let t={};return e.role&&(t.role=e.role),C("link",{source_id:e.chat_id,target_id:e.member_id,edge_type:"has_member",context:t})}function Zi(e){return C("create-agent",e)}function Xi(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.")):C("todo-control",{action:"answer_input",...e})}function ul(){return te({mutationFn:zi})}function ll(){let e=L();return te({mutationFn:Ji,onSuccess:()=>{e.invalidateQueries({queryKey:["memberships"]})}})}function dl(){let e=L();return te({mutationFn:Yi,onSuccess:(t,n)=>{e.invalidateQueries({queryKey:P.edges(n.chat_id)}),e.invalidateQueries({queryKey:P.edges(n.member_id)})}})}function fl(){let e=L();return te({mutationFn:Zi,onSuccess:()=>{e.invalidateQueries({queryKey:["memberships"]})}})}function pl(){let e=L();return te({mutationFn:Xi,onSuccess:(t,n)=>{e.invalidateQueries({queryKey:P.itemById(n.step_id)})}})}function bf(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function vf(e,t){return t&&t.length>0?"select":e==="boolean"?"toggle":e==="integer"||e==="number"?"range":e==="string"?"text":"none"}function wf(e,t){return!(e==="object"||e==="array")}function Sf(e){return["string","number","integer","boolean"].includes(e)}function xf(e){return e!=="object"&&e!=="array"}function ml(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,l=wf(c,u),f=Sf(c),m=vf(c,u);i.push({key:o,label:a.title||bf(o),type:c,description:a.description,enum_values:u,default_value:n[o]??r[o]??a.default,editable:t,filterable:l,sortable:f,filter_widget:m})}return i}function eo(e){let t=e.default_data||{},n=e.field_defaults||{},r=ml(e.input_schema,!0,t,n),s=ml(e.system_schema,!1,t,n),i=[...r,...s],o=i.filter(u=>xf(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 hl(e){return{field:"updated_at",direction:"desc"}}function gl(e){let t=eo(e),n=new Set(e.input_schema?.required||[]);return t.form_fields.filter(r=>n.has(r.key)||r.default_value===void 0)}var we=Y(ue(),1);function yl(){if(globalThis.crypto?.randomUUID)return globalThis.crypto.randomUUID();let e=new Uint8Array(16);if(globalThis.crypto?.getRandomValues){globalThis.crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,n=>n.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let n=Math.floor(Math.random()*16);return(t==="x"?n:n&3|8).toString(16)})}async function _l(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=t.collisionPolicy||"keep_both",c=a==="keep_both"?yl():void 0,u={parent_path:t.parentPath,item_type:o,name:s,type_data:{...t.typeData||{},file_source:{type:"upload",content_type:i,collision_policy:a,...c?{upload_id:c}:{}}}};t.cardParentPath&&(u.card_parent_path=t.cardParentPath);let f=await C("create",u);if(!f.id)throw new Error(f.error||f.message||"Failed to create file item");let m=f.id,p=f.path;if(f.storage_completed&&f.file_ref)return{itemId:m,itemPath:p,fileRef:f.file_ref};let g=f.storage_key,_=f.upload_token,h=f.storage_worker_url||"https://fsaos-storage.radns.workers.dev";if(!g)throw new Error("Gateway returned no storage_key \u2014 file_source may not be supported for this item type");await Rf(h,g,_,e,i,n,r);let y=await bl(m,g,i);return{itemId:m,itemPath:p,fileRef:y}}function Rf(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=l=>{l.lengthComputable&&i&&i(Math.round(l.loaded/l.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 bl(e,t,n){let r=await tt(),s=await fetch(`${Ie}/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 vl(){let[e,t]=(0,we.useState)([]),n=L(),r=(0,we.useRef)(e);r.current=e;let s=(0,we.useCallback)((_,h)=>{t(y=>y.map(v=>v.id===_?{...v,...h}:v))},[]),i=(0,we.useCallback)(_=>{t(h=>[...h,_])},[]),o=(0,we.useCallback)(async(_,h,y,v,R)=>{let E=y.name||h.name,w=h.type||"application/octet-stream",O=y.itemType||"file",K=y.collisionPolicy||"keep_both",x=R?.itemId||null,A=R?.itemPath||null,k=R?.storageKey||null,I=R?.uploadToken||null,M=R?.storageWorkerUrl||null;try{if(!v||v==="create"){s(_,{status:"creating",error:null,_failedAt:null});let $=await C("create",{parent_path:y.parentPath,item_type:O,name:E,type_data:{...y.typeData||{},file_source:{type:"upload",content_type:w,collision_policy:K,...K==="keep_both"?{upload_id:_}:{}}}});if(!$.id)throw Object.assign(new Error($.error||$.message||"Failed to create file item"),{_step:"create"});if(x=$.id,A=$.path,s(_,{itemId:x,itemPath:A}),$.storage_completed&&$.file_ref){s(_,{status:"complete",progress:100,fileRef:$.file_ref}),n.invalidateQueries({queryKey:P.children(y.parentPath)});return}if(k=$.storage_key,I=$.upload_token||"",M=$.storage_worker_url||"https://fsaos-storage.radns.workers.dev",s(_,{_storageKey:k,_uploadToken:I,_storageWorkerUrl:M}),!k)throw Object.assign(new Error("Gateway returned no storage_key"),{_step:"create"})}(!v||v==="create"||v==="upload")&&(s(_,{status:"uploading",progress:0,error:null,_failedAt:null}),await new Promise(($,Ce)=>{let re=new XMLHttpRequest;s(_,{_xhr:re}),re.open("PUT",`${M}/upload`),re.setRequestHeader("X-Storage-Key",k),re.setRequestHeader("Content-Type",w),I&&re.setRequestHeader("X-Upload-Token",I),re.upload.onprogress=Ct=>{Ct.lengthComputable&&s(_,{progress:Math.round(Ct.loaded/Ct.total*100)})},re.onload=()=>{re.status>=200&&re.status<300?$():Ce(Object.assign(new Error(`Storage upload failed: HTTP ${re.status}`),{_step:"upload"}))},re.onerror=()=>Ce(Object.assign(new Error("Storage upload network error"),{_step:"upload"})),re.ontimeout=()=>Ce(Object.assign(new Error("Storage upload timed out"),{_step:"upload"})),re.send(h)}),s(_,{progress:100,_xhr:null})),s(_,{status:"confirming",error:null,_failedAt:null});let q=await bl(x,k,w);s(_,{status:"complete",fileRef:q}),n.invalidateQueries({queryKey:P.children(y.parentPath)})}catch(q){let U=q?.message||String(q),$=q?._step||"create";s(_,{status:"error",error:U,_failedAt:$,_xhr:null})}},[s,n]),a=(0,we.useCallback)((_,h)=>{let y=yl();i({id:y,file:_,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(y,_,h)},[i,o]),c=(0,we.useCallback)((_,h)=>{for(let y of _)a(y,h)},[a]),u=(0,we.useCallback)(_=>{let h=r.current.find(R=>R.id===_);if(!h||h.status!=="error")return;let y=h._failedAt||"create",v=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(_,h.file,h.options,y,v)},[o]),l=(0,we.useCallback)(_=>{let h=r.current.find(y=>y.id===_);h&&(h._xhr&&h._xhr.abort(),s(_,{status:"error",error:"Cancelled",_xhr:null,_failedAt:null}))},[s]),f=(0,we.useCallback)(_=>{t(h=>h.filter(y=>y.id!==_))},[]),m=(0,we.useCallback)(()=>{t(_=>_.filter(h=>h.status!=="complete"))},[]),p=e.some(_=>_.status==="creating"||_.status==="uploading"||_.status==="confirming"),g=e.map(({_storageKey:_,_uploadToken:h,_storageWorkerUrl:y,_xhr:v,_failedAt:R,...E})=>E);return{upload:a,uploadMultiple:c,uploads:g,retryUpload:u,cancelUpload:l,removeUpload:f,clearCompleted:m,isUploading:p}}var wl=Y(ue(),1);async function to(e,t){return await C("resolve-items",{context_id:e,item_type:t})}function Sl(e,t){return(0,wl.useSyncExternalStore)(xe,ne,ne),B({queryKey:["vfs",W()??"__unscoped__","resolved-items",e??"",t],queryFn:()=>to(e,t),enabled:!!(e&&t)})}var Qe=Y(ue(),1);function Ms(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 l=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:l,completed_at:null}),r.has(c.tool_id)){let f=r.get(c.tool_id);n.timeline[f].artifact_ids.push(c.artifact_id)}else{let f=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:l,completed_at:null,artifact_ids:[c.artifact_id]}),r.set(c.tool_id,f)}break}case"artifact_delta":{let l=n.artifacts.get(c.artifact_id);l&&(l.content+=c.content_delta,l.total_chars+=c.content_delta.length,l.delta_count+=1,c.target_uri&&!l.target_uri&&(l.target_uri=c.target_uri));break}case"artifact_done":{let l=n.artifacts.get(c.artifact_id);l&&(l.status=c.status,l.total_chars=c.total_chars,l.artifact_item_uri=c.artifact_item_uri,l.evidence_uri=c.evidence_uri,c.target_uri&&(l.target_uri=c.target_uri),(c.status==="completed"||c.status==="failed")&&(l.completed_at=Date.now()));let f=r.get(c.tool_id);if(f!==void 0){let m=n.timeline[f];c.status==="executing"?m.status="executing":c.status==="completed"?(m.status="completed",m.completed_at=Date.now()):c.status==="failed"&&(m.status="failed",m.completed_at=Date.now()),c.target_uri&&!m.target_uri&&(m.target_uri=c.target_uri)}break}}t(n)}return cs(e,s)}function xl(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:Ms(e,f=>{o.current=f,r(new Map(f.artifacts)),i([...f.timeline])}),[e,t]);let a=(0,Qe.useCallback)(()=>{r(new Map),i([]),o.current={artifacts:new Map,timeline:[]}},[]),c=Array.from(n.values()).find(l=>l.surface_type==="file_editor"&&l.status==="streaming")??null,u=Array.from(n.values()).filter(l=>l.surface_type==="activity"&&(l.status==="streaming"||l.status==="executing"));return{artifacts:n,timeline:s,activeEditor:c,activeActivities:u,reset:a}}function Rl(e,t=!0){let[n,r]=(0,Qe.useState)([]);(0,Qe.useEffect)(()=>!e||!t?void 0:Ms(e,o=>{r([...o.timeline])}),[e,t]);let s=n.length>0?n[n.length-1]:null;return{timeline:n,latestActivity:s}}var Os=Y(ue(),1);function Cf(e,t,n,r){return["vfs","timeline-history",e,t??"__all__",n??500,r??0]}async function no(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 C("open",{path:n,mode:"extract",strategy:"rows",arguments:i}))?.content;return a?(a.rows??a.items??a.data??[]).map(Pf).sort((u,l)=>u.seq-l.seq):[]}catch(o){if(o?.status===404||o?.message?.includes("not found"))return[];throw o}}function Cl(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,Os.useRef)(null),l=a?Cf(a,n,r,s):["vfs","timeline-history","__disabled__"],f=B({queryKey:l,queryFn:()=>no(e,{turnId:n,limit:r,offset:s}),enabled:!!e&&i});return(0,Os.useEffect)(()=>{if(!a||!i)return;let m=ie("vfs_change",()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{c.invalidateQueries({queryKey:l})},o)},p=>{let g=p?.path;return g?g===a&&p.item_type==="dataset":!1});return()=>{m(),u.current&&clearTimeout(u.current)}},[a,i,o,c,JSON.stringify(l)]),{events:f.data??[],isLoading:f.isLoading,error:f.error,isFetching:f.isFetching,refetch:()=>{f.refetch()}}}function Pf(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 Fs=Y(ue(),1);function Pl(){(0,Fs.useSyncExternalStore)(xe,ne,ne);let e=W(),t=de(),n=Dn(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=te({mutationFn:async c=>{let u,l={_scope_path:c.scopePath};if(c.operation==="pin"?u=await C("create",{...l,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 C("delete",{...l,id:c.entry.id}):u=await C("update",{...l,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,l)=>rt(r,l.queryKey)}),a=(0,Fs.useCallback)(c=>!i||!e||W()!==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(l=>l.symlink_type_data?.target_item_id===c||l.id===c);return u?a({operation:"unpin",entry:u}):Promise.resolve(null)},reorder:c=>a({operation:"reorder",ids:c})}}var qs=Y(ue(),1);var kr=(e,t,n)=>["vfs",e,"personal-sections",t,n];function ro(e,t){return e&&e.item_id===t.item_id&&e.version>t.version?e:t}async function so(e,t,n,r){let s=await C("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 El(e,t){let n=await so(e.scopePath,e.contextId,e.collection,{operation:"assign",section_id:e.sectionId,target_id:t}),r=N();return r.setQueryData(kr(e.scopePath,e.contextId,e.collection),s=>ro(s,n)),Tl(r,e.scopePath),n}function Tl(e,t){for(let n of e.getQueryCache().getAll())n.queryKey[0]==="vfs"&&n.queryKey[1]===t&&n.queryKey[2]==="personal-sections"&&rt(e,n.queryKey)}function Il(e,t){let n=(0,qs.useSyncExternalStore)(xe,ne,ne),r=W(),s=L(),i=kr(r,e,t),o=B({queryKey:i,enabled:!!r&&!!e,queryFn:()=>so(r,e,t,{operation:"list"}),staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0,personalSections:!0},structuralSharing:(f,m)=>ro(f,m)}),a=(0,qs.useRef)(!1),c=te({mutationFn:async f=>{let m=await so(f.scope,f.context,f.collection,{...f.change,...f.change.operation.startsWith("reorder")?{expected_version:f.version}:{}});return s.setQueryData(kr(f.scope,f.context,f.collection),p=>ro(p,m)),m},onSettled:(f,m,p)=>Tl(s,p.scope)});async function u(f){if(!r||!e||n!==ne()||W()!==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:f,scope:r,context:e,collection:t,version:o.data.version})}finally{a.current=!1}}function l(f){if(!r||!e||!o.data?.sections.some(m=>m.id===f))throw new Error("Section is unavailable");return{scopePath:r,contextId:e,collection:t,sectionId:f}}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:l,contextKey:`${n}:${r}:${e}:${t}`}}tu(io);return Ll(io);})();
8
8
 
9
9
  /* ── Auto-setup: require shim + mount + backward compat globals ── */
10
10
  (function() {