@ai4b-team/fsaos-gateway-sdk 4.3.0 → 4.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,10 @@
1
- /* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-11-05T00:06:41.953Z */
2
- "use strict";var __FSAOS_GATEWAY__=(()=>{var cl=Object.create;var Fn=Object.defineProperty;var ul=Object.getOwnPropertyDescriptor;var ll=Object.getOwnPropertyNames;var dl=Object.getPrototypeOf,fl=Object.prototype.hasOwnProperty;var Bi=e=>{throw TypeError(e)};var pl=(e,t,n)=>t in e?Fn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var qn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ml=(e,t)=>{for(var n in t)Fn(e,n,{get:t[n],enumerable:!0})},Hi=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ll(t))!fl.call(e,s)&&s!==n&&Fn(e,s,{get:()=>t[s],enumerable:!(r=ul(t,s))||r.enumerable});return e};var X=(e,t,n)=>(n=e!=null?cl(dl(e)):{},Hi(t||!e||!e.__esModule?Fn(n,"default",{value:e,enumerable:!0}):n,e)),hl=e=>Hi(Fn({},"__esModule",{value:!0}),e);var te=(e,t,n)=>pl(e,typeof t!="symbol"?t+"":t,n),Ts=(e,t,n)=>t.has(e)||Bi("Cannot "+n);var l=(e,t,n)=>(Ts(e,t,"read from private field"),n?n.call(e):t.get(e)),C=(e,t,n)=>t.has(e)?Bi("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),w=(e,t,n,r)=>(Ts(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),q=(e,t,n)=>(Ts(e,t,"access private method"),n);var Qn=(e,t,n,r)=>({set _(s){w(e,t,s,n)},get _(){return l(e,t,r)}});var ae=qn((Fd,Gi)=>{Gi.exports=React});var Ir=qn((Mp,Io)=>{Io.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var jo=qn((um,Lo)=>{Lo.exports={createClient:window.supabase.createClient}});var ga=qn((Sm,ha)=>{ha.exports=ReactDOM});var xu=qn((gg,Ru)=>{Ru.exports=ReactDOM});var $i={};ml($i,{CHANNEL_AI_MODES:()=>Hc,ComponentRenderer:()=>Vc,EnforcementDeniedError:()=>rt,FormSubmissionError:()=>On,GatewayRequestError:()=>Ie,InteractionTrackingError:()=>kn,KernelProvider:()=>$c,QueryClientProvider:()=>Gn,acceptInvite:()=>qi,answerInput:()=>Ui,assignPersonalSection:()=>el,auth:()=>Fu,awaitAnchorReady:()=>er,awaitScopeReady:()=>ea,callTool:()=>ku,cancelQueuedTurn:()=>wu,cancelTurn:()=>vu,clearCachedToken:()=>ti,clearSession:()=>ui,configureGatewayReads:()=>la,createAgent:()=>Di,createItem:()=>Eu,disconnectSSE:()=>vi,disposeVfsRealtimeWs:()=>wi,electHomeAnchor:()=>Mt,emitEvent:()=>Da,fetchChannelMessages:()=>Ha,fetchChannelMessagesPage:()=>lr,fetchChannelMessagesWithCards:()=>as,fetchEdgesForItem:()=>ts,fetchItemHistory:()=>ss,fetchItemVersions:()=>ur,fetchItems:()=>xn,fetchMemberFocus:()=>is,fetchOpenEnvelope:()=>os,fetchRecentActivity:()=>rs,fetchResolvedItems:()=>Ki,fetchTimelineHistory:()=>Li,fetchTurnQueueEntries:()=>$a,fetchTypeDefinitions:()=>es,fetchVfsChildren:()=>cr,fetchVfsChildrenPage:()=>Zr,fetchVfsItem:()=>ar,fetchVfsItemById:()=>Xr,fetchVfsTree:()=>ns,gatewayCall:()=>x,getAccessToken:()=>Ye,getAnchor:()=>pn,getAnchorRef:()=>ye,getAnchorVersion:()=>si,getAssetUrl:()=>Ou,getDefaultSort:()=>Vu,getHomeAnchor:()=>fe,getMountVersion:()=>tr,getMounts:()=>Te,getPathSubscriptionState:()=>Na,getQueryClient:()=>O,getRequiredFormFields:()=>$u,getScope:()=>B,getScopeVersion:()=>ee,getServerClockOffsetMs:()=>ia,getServerClockSyncedAt:()=>oa,getSessionEntry:()=>ht,hasServerClock:()=>sa,initSession:()=>Xe,initVfsRealtimeWs:()=>Qt,initializeFsaos:()=>_u,initializeWorkspace:()=>vs,interpretSchema:()=>Ni,invalidateAllVfs:()=>Ja,invalidateChannelMessages:()=>Xa,invalidateChildren:()=>Yr,invalidateItem:()=>bi,invalidateOpenEnvelope:()=>Za,invalidatePathAndParent:()=>Ga,invalidateSubtree:()=>za,invalidateTypes:()=>Ya,inviteMember:()=>Fi,isAnchorReady:()=>oi,isChannelPath:()=>pe,isListableItemsFilter:()=>Rn,isScopeReady:()=>Dr,itemsFilterFromQueryFilter:()=>Wa,listChildren:()=>Tu,loadMounts:()=>Dt,mount:()=>qu,mountRealtimeScope:()=>Cn,normalizeItem:()=>_e,onConnectionStateChange:()=>Jr,pathSubscriptionMatches:()=>gi,personalSectionsKey:()=>vr,ping:()=>Ua,pushChanges:()=>Au,queryClient:()=>Ra,readItem:()=>Cu,refreshQuery:()=>Ae,registerCleanup:()=>ne,replaceMounts:()=>fs,resetAllSdkState:()=>mn,resolvePrincipalId:()=>Kc,resubscribePath:()=>La,seatMember:()=>Qi,selectMount:()=>mr,serverDeadlinePassed:()=>aa,serverMsUntil:()=>ca,serverNow:()=>Ur,setAnchor:()=>qr,setCachedToken:()=>Wo,setQueryClient:()=>Sa,setScope:()=>Zo,setupRequireShim:()=>Qu,signal:()=>Mu,startTracking:()=>_s,steerTurn:()=>bu,submitForm:()=>Su,subscribeAnchor:()=>ii,subscribeArtifactStream:()=>bs,subscribeMounts:()=>Qr,subscribeScope:()=>we,subscribeToEvents:()=>re,subscribeToPath:()=>zr,subscribeToScope:()=>Sn,trackAction:()=>hu,trackEvent:()=>Nt,trackPageView:()=>mu,unmountRealtimeScope:()=>ls,updateItem:()=>Iu,uploadFile:()=>Wu,useAcceptInvite:()=>Uu,useAccounts:()=>kc,useAgentTimeline:()=>Yu,useAllChannels:()=>gs,useAnswerInput:()=>Lu,useArrangement:()=>In,useArtifactStream:()=>Ju,useAsset:()=>Oc,useAuth:()=>hs,useChannelMessages:()=>Wc,useChannels:()=>Gc,useChildren:()=>hc,useComponent:()=>Ti,useCreate:()=>Yc,useCreateAgent:()=>Ku,useDelete:()=>eu,useDmChannels:()=>zc,useEdges:()=>Sc,useEventStream:()=>su,useFileUpload:()=>Hu,useIncrementalItems:()=>bc,useInfiniteChannelMessages:()=>Bc,useInfiniteChildren:()=>wc,useInfiniteItems:()=>Ci,useInviteMember:()=>Du,useItem:()=>pc,useItemById:()=>mc,useItemHistory:()=>Ec,useItemVersions:()=>Tc,useItems:()=>vc,useLink:()=>nu,useList:()=>Pi,useMemberFocus:()=>Cc,useMintedAsset:()=>ou,useMounts:()=>Mc,useMove:()=>tu,useMutation:()=>ru,useNotifications:()=>Ei,useOpen:()=>xc,usePermission:()=>Dc,usePermissions:()=>Uc,usePersonalItemOrder:()=>cu,usePersonalSections:()=>nl,usePinnedItems:()=>Zu,usePrincipal:()=>Lc,useRealtimeQuery:()=>iu,useRecentActivity:()=>Ic,useResolve:()=>_c,useResolvedItems:()=>zu,useScope:()=>Ac,useScopeReady:()=>fc,useSearch:()=>yc,useSeatMember:()=>Nu,useTheme:()=>Qc,useTimelineHistory:()=>Xu,useTool:()=>jc,useTree:()=>gc,useType:()=>Rc,useTypeHelpers:()=>Pc,useTypes:()=>ms,useUnreadCounts:()=>Jc,useUpdate:()=>Xc,useUpdatePrincipal:()=>Zc,vfsKeys:()=>P,waitForPathReady:()=>Ka});var rt=class e extends Error{constructor(n){let r=n.message||e.fallbackMessage(n);super(r);te(this,"name","EnforcementDeniedError");te(this,"deniedBy");te(this,"ruleKey");te(this,"displayName");this.deniedBy=n.denied_by||n.error_type||n.error||"unknown";let s=n.enforcement;this.ruleKey=s?.rule_key??void 0,this.displayName=s?.display_name??void 0}static fallbackMessage(n){let r=n.error||"",s=n.denied_by||"";return s==="rule"||r==="RULE_DENIED"?"This feature is not enabled for this workspace.":s==="entitlement"||r==="ENTITLEMENT_REQUIRED"?"This feature requires a plan upgrade.":s==="access"||r==="ACCESS_DENIED"||r==="PERMISSION_DENIED"?"You don't have permission to do this.":"This action is not allowed."}get isRuleDenial(){return this.deniedBy==="rule"||this.deniedBy==="RULE_DENIED"}get isAccessDenial(){return this.deniedBy==="access"||this.deniedBy==="ACCESS_DENIED"}get isEntitlementDenial(){return this.deniedBy==="entitlement"||this.deniedBy==="ENTITLEMENT_REQUIRED"}};var An=X(ae(),1);var xe=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var bt,st,Lt,zi,gl=(zi=class extends xe{constructor(){super();C(this,bt);C(this,st);C(this,Lt);w(this,Lt,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){l(this,st)||this.setEventListener(l(this,Lt))}onUnsubscribe(){var t;this.hasListeners()||((t=l(this,st))==null||t.call(this),w(this,st,void 0))}setEventListener(t){var n;w(this,Lt,t),(n=l(this,st))==null||n.call(this),w(this,st,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){l(this,bt)!==t&&(w(this,bt,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof l(this,bt)=="boolean"?l(this,bt):globalThis.document?.visibilityState!=="hidden"}},bt=new WeakMap,st=new WeakMap,Lt=new WeakMap,zi),jt=new gl;var yl={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},it,Es,Ji,_l=(Ji=class{constructor(){C(this,it,yl);C(this,Es,!1)}setTimeoutProvider(e){w(this,it,e)}setTimeout(e,t){return l(this,it).setTimeout(e,t)}clearTimeout(e){l(this,it).clearTimeout(e)}setInterval(e,t){return l(this,it).setInterval(e,t)}clearInterval(e){l(this,it).clearInterval(e)}},it=new WeakMap,Es=new WeakMap,Ji),Qe=new _l;function Yi(e){setTimeout(e,0)}var As=typeof window>"u"||"Deno"in globalThis;function G(){}function eo(e,t){return typeof e=="function"?e(t):e}function Dn(e){return typeof e=="number"&&e>=0&&e!==1/0}function br(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Me(e,t){return typeof e=="function"?e(t):e}function me(e,t){return typeof e=="function"?e(t):e}function wr(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:o,stale:a}=e;if(o){if(r){if(t.queryHash!==Un(o,t.options))return!1}else if(!wt(t.queryKey,o))return!1}if(n!=="all"){let c=t.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof a=="boolean"&&t.isStale()!==a||s&&s!==t.state.fetchStatus||i&&!i(t))}function Sr(e,t){let{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(De(t.options.mutationKey)!==De(i))return!1}else if(!wt(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function Un(e,t){return(t?.queryKeyHashFn||De)(e)}function De(e){return JSON.stringify(e,(t,n)=>Is(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function wt(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>wt(e[n],t[n])):!1}var vl=Object.prototype.hasOwnProperty;function ks(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=Xi(e)&&Xi(t);if(!r&&!(Is(e)&&Is(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:vl.call(e,f))&&u++;continue}if(m===null||p===null||typeof m!="object"||typeof p!="object"){c[f]=p;continue}let g=ks(m,p,n+1);c[f]=g,g===m&&u++}return i===a&&u===i?e:c}function Vt(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function Xi(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Is(e){if(!Zi(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Zi(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Zi(e){return Object.prototype.toString.call(e)==="[object Object]"}function to(e){return new Promise(t=>{Qe.setTimeout(t,e)})}function Nn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?ks(e,t):t}function no(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function ro(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var $t=Symbol();function Rr(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===$t?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Wt(e,t){return typeof e=="function"?e(...t):!!e}function so(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=()=>As;return{isServer(){return e()},setIsServer(t){e=t}}})();function Kn(){let e,t,n=new Promise((s,i)=>{e=s,t=i});n.status="pending",n.catch(()=>{});function r(s){Object.assign(n,s),delete n.resolve,delete n.reject}return n.resolve=s=>{r({status:"fulfilled",value:s}),e(s)},n.reject=s=>{r({status:"rejected",reason:s}),t(s)},n}var io=Yi;function bl(){let e=[],t=0,n=a=>{a()},r=a=>{a()},s=io,i=a=>{t?e.push(a):s(()=>{n(a)})},o=()=>{let a=e;e=[],a.length&&s(()=>{r(()=>{a.forEach(c=>{n(c)})})})};return{batch:a=>{let c;t++;try{c=a()}finally{t--,t||o()}return c},batchCalls:a=>(...c)=>{i(()=>{a(...c)})},schedule:i,setNotifyFunction:a=>{n=a},setBatchNotifyFunction:a=>{r=a},setScheduler:a=>{s=a}}}var V=bl();var Bt,ot,Ht,oo,wl=(oo=class extends xe{constructor(){super();C(this,Bt,!0);C(this,ot);C(this,Ht);w(this,Ht,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){l(this,ot)||this.setEventListener(l(this,Ht))}onUnsubscribe(){var t;this.hasListeners()||((t=l(this,ot))==null||t.call(this),w(this,ot,void 0))}setEventListener(t){var n;w(this,Ht,t),(n=l(this,ot))==null||n.call(this),w(this,ot,t(this.setOnline.bind(this)))}setOnline(t){l(this,Bt)!==t&&(w(this,Bt,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return l(this,Bt)}},Bt=new WeakMap,ot=new WeakMap,Ht=new WeakMap,oo),Gt=new wl;function Sl(e){return Math.min(1e3*2**e,3e4)}function Ms(e){return(e??"online")==="online"?Gt.isOnline():!0}var xr=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Pr(e){let t=!1,n=0,r,s=Kn(),i=()=>s.status!=="pending",o=_=>{if(!i()){let h=new xr(_);m(h),e.onCancel?.(h)}},a=()=>{t=!0},c=()=>{t=!1},u=()=>jt.isFocused()&&(e.networkMode==="always"||Gt.isOnline())&&e.canRun(),d=()=>Ms(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 b=e.retry??(Ue.isServer()?0:3),T=e.retryDelay??Sl,E=typeof T=="function"?T(n,y):T,S=b===!0||typeof b=="number"&&n<b||typeof b=="function"&&b(n,y);if(t||!S){m(y);return}n++,e.onFail?.(n,y),to(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:d,start:()=>(d()?g():p().then(g),s)}}var St,ao,Cr=(ao=class{constructor(){C(this,St)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Dn(this.gcTime)&&w(this,St,Qe.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ue.isServer()?1/0:5*60*1e3))}clearGcTimeout(){l(this,St)!==void 0&&(Qe.clearTimeout(l(this,St)),w(this,St,void 0))}},St=new WeakMap,ao);var Rt,zt,Pe,xt,se,Ln,Pt,be,po,$e,lo,fo=(lo=class extends Cr{constructor(t){super();C(this,be);C(this,Rt);C(this,zt);C(this,Pe);C(this,xt);C(this,se);C(this,Ln);C(this,Pt);w(this,Pt,!1),w(this,Ln,t.defaultOptions),this.setOptions(t.options),this.observers=[],w(this,xt,t.client),w(this,Pe,l(this,xt).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,w(this,Rt,uo(this.options)),this.state=t.state??l(this,Rt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return l(this,se)?.promise}setOptions(t){if(this.options={...l(this,Ln),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=uo(this.options);n.data!==void 0&&(this.setState(co(n.data,n.dataUpdatedAt)),w(this,Rt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&l(this,Pe).remove(this)}setData(t,n){let r=Nn(this.state.data,t,this.options);return q(this,be,$e).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){q(this,be,$e).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=l(this,se)?.promise;return l(this,se)?.cancel(t),n?n.then(G).catch(G):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return l(this,Rt)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>me(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===$t||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>Me(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!br(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),l(this,se)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),l(this,se)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),l(this,Pe).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(l(this,se)&&(l(this,Pt)||q(this,be,po).call(this)?l(this,se).cancel({revert:!0}):l(this,se).cancelRetry()),this.scheduleGc()),l(this,Pe).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||q(this,be,$e).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&l(this,se)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(l(this,se))return l(this,se).continueRetry(),l(this,se).promise}if(t&&this.setOptions(t),!this.options.queryFn){let c=this.observers.find(u=>u.options.queryFn);c&&this.setOptions(c.options)}let r=new AbortController,s=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(w(this,Pt,!0),r.signal)})},i=()=>{let c=Rr(this.options,n),d=(()=>{let f={client:l(this,xt),queryKey:this.queryKey,meta:this.meta};return s(f),f})();return w(this,Pt,!1),this.options.persister?this.options.persister(c,d,this):c(d)},a=(()=>{let c={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:l(this,xt),state:this.state,fetchFn:i};return s(c),c})();this.options.behavior?.onFetch(a,this),w(this,zt,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&q(this,be,$e).call(this,{type:"fetch",meta:a.fetchOptions?.meta}),w(this,se,Pr({initialPromise:n?.initialPromise,fn:a.fetchFn,onCancel:c=>{c instanceof xr&&c.revert&&this.setState({...l(this,zt),fetchStatus:"idle"}),r.abort()},onFail:(c,u)=>{q(this,be,$e).call(this,{type:"failed",failureCount:c,error:u})},onPause:()=>{q(this,be,$e).call(this,{type:"pause"})},onContinue:()=>{q(this,be,$e).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0}));try{let c=await l(this,se).start();if(c===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(c),l(this,Pe).config.onSuccess?.(c,this),l(this,Pe).config.onSettled?.(c,this.state.error,this),c}catch(c){if(c instanceof xr){if(c.silent)return l(this,se).promise;if(c.revert){if(this.state.data===void 0)throw c;return this.state.data}}throw q(this,be,$e).call(this,{type:"error",error:c}),l(this,Pe).config.onError?.(c,this),l(this,Pe).config.onSettled?.(this.state.data,c,this),c}finally{this.scheduleGc()}}},Rt=new WeakMap,zt=new WeakMap,Pe=new WeakMap,xt=new WeakMap,se=new WeakMap,Ln=new WeakMap,Pt=new WeakMap,be=new WeakSet,po=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},$e=function(t){let n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...Os(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 w(this,zt,t.manual?s:void 0),s;case"error":let i=t.error;return{...r,error:i,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),V.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),l(this,Pe).notify({query:this,type:"updated",action:t})})},lo);function Os(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Ms(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 uo(e){let t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var he,N,Vn,de,Ct,Jt,We,at,$n,Yt,Xt,Tt,Et,ct,Zt,j,jn,Fs,qs,Qs,Ds,Us,Ns,Ks,yo,go,Wn=(go=class extends xe{constructor(t,n){super();C(this,j);C(this,he);C(this,N);C(this,Vn);C(this,de);C(this,Ct);C(this,Jt);C(this,We);C(this,at);C(this,$n);C(this,Yt);C(this,Xt);C(this,Tt);C(this,Et);C(this,ct);C(this,Zt,new Set);this.options=n,w(this,he,t),w(this,at,null),w(this,We,Kn()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(l(this,N).addObserver(this),mo(l(this,N),this.options)?q(this,j,jn).call(this):this.updateResult(),q(this,j,Ds).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ls(l(this,N),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ls(l(this,N),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,q(this,j,Us).call(this),q(this,j,Ns).call(this),l(this,N).removeObserver(this)}setOptions(t){let n=this.options,r=l(this,N);if(this.options=l(this,he).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof me(this.options.enabled,l(this,N))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");q(this,j,Ks).call(this),l(this,N).setOptions(this.options),n._defaulted&&!Vt(this.options,n)&&l(this,he).getQueryCache().notify({type:"observerOptionsUpdated",query:l(this,N),observer:this});let s=this.hasListeners();s&&ho(l(this,N),r,this.options,n)&&q(this,j,jn).call(this),this.updateResult(),s&&(l(this,N)!==r||me(this.options.enabled,l(this,N))!==me(n.enabled,l(this,N))||Me(this.options.staleTime,l(this,N))!==Me(n.staleTime,l(this,N)))&&q(this,j,Fs).call(this);let i=q(this,j,qs).call(this);s&&(l(this,N)!==r||me(this.options.enabled,l(this,N))!==me(n.enabled,l(this,N))||i!==l(this,ct))&&q(this,j,Qs).call(this,i)}getOptimisticResult(t){let n=l(this,he).getQueryCache().build(l(this,he),t),r=this.createResult(n,t);return xl(this,r)&&(w(this,de,r),w(this,Jt,this.options),w(this,Ct,l(this,N).state)),r}getCurrentResult(){return l(this,de)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&l(this,We).status==="pending"&&l(this,We).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){l(this,Zt).add(t)}getCurrentQuery(){return l(this,N)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=l(this,he).defaultQueryOptions(t),r=l(this,he).getQueryCache().build(l(this,he),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return q(this,j,jn).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),l(this,de)))}createResult(t,n){let r=l(this,N),s=this.options,i=l(this,de),o=l(this,Ct),a=l(this,Jt),u=t!==r?t.state:l(this,Vn),{state:d}=t,f={...d},m=!1,p;if(n._optimisticResults){let I=this.hasListeners(),M=!I&&mo(t,n),A=I&&ho(t,r,n,s);(M||A)&&(f={...f,...Os(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 I;i?.isPlaceholderData&&n.placeholderData===a?.placeholderData?(I=i.data,y=!0):I=typeof n.placeholderData=="function"?n.placeholderData(l(this,Xt)?.state.data,l(this,Xt)):n.placeholderData,I!==void 0&&(h="success",p=Nn(i?.data,I,n),m=!0)}if(n.select&&p!==void 0&&!y)if(i&&p===o?.data&&n.select===l(this,$n))p=l(this,Yt);else try{w(this,$n,n.select),p=n.select(p),p=Nn(i?.data,p,n),w(this,Yt,p),w(this,at,null)}catch(I){w(this,at,I)}l(this,at)&&(g=l(this,at),p=l(this,Yt),_=Date.now(),h="error");let b=f.fetchStatus==="fetching",T=h==="pending",E=h==="error",S=T&&b,Q=p!==void 0,R={status:h,fetchStatus:f.fetchStatus,isPending:T,isSuccess:h==="success",isError:E,isInitialLoading:S,isLoading:S,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:b,isRefetching:b&&!T,isLoadingError:E&&!Q,isPaused:f.fetchStatus==="paused",isPlaceholderData:m,isRefetchError:E&&Q,isStale:js(t,n),refetch:this.refetch,promise:l(this,We),isEnabled:me(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let I=R.data!==void 0,M=R.status==="error"&&!I,A=F=>{M?F.reject(R.error):I&&F.resolve(R.data)},k=()=>{let F=w(this,We,R.promise=Kn());A(F)},U=l(this,We);switch(U.status){case"pending":t.queryHash===r.queryHash&&A(U);break;case"fulfilled":(M||R.data!==U.value)&&k();break;case"rejected":(!M||R.error!==U.reason)&&k();break}}return R}updateResult(){let t=l(this,de),n=this.createResult(l(this,N),this.options);if(w(this,Ct,l(this,N).state),w(this,Jt,this.options),l(this,Ct).data!==void 0&&w(this,Xt,l(this,N)),Vt(n,t))return;w(this,de,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!l(this,Zt).size)return!0;let o=new Set(i??l(this,Zt));return this.options.throwOnError&&o.add("error"),Object.keys(l(this,de)).some(a=>{let c=a;return l(this,de)[c]!==t[c]&&o.has(c)})};q(this,j,yo).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&q(this,j,Ds).call(this)}},he=new WeakMap,N=new WeakMap,Vn=new WeakMap,de=new WeakMap,Ct=new WeakMap,Jt=new WeakMap,We=new WeakMap,at=new WeakMap,$n=new WeakMap,Yt=new WeakMap,Xt=new WeakMap,Tt=new WeakMap,Et=new WeakMap,ct=new WeakMap,Zt=new WeakMap,j=new WeakSet,jn=function(t){q(this,j,Ks).call(this);let n=l(this,N).fetch(this.options,t);return t?.throwOnError||(n=n.catch(G)),n},Fs=function(){q(this,j,Us).call(this);let t=Me(this.options.staleTime,l(this,N));if(Ue.isServer()||l(this,de).isStale||!Dn(t))return;let r=br(l(this,de).dataUpdatedAt,t)+1;w(this,Tt,Qe.setTimeout(()=>{l(this,de).isStale||this.updateResult()},r))},qs=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(l(this,N)):this.options.refetchInterval)??!1},Qs=function(t){q(this,j,Ns).call(this),w(this,ct,t),!(Ue.isServer()||me(this.options.enabled,l(this,N))===!1||!Dn(l(this,ct))||l(this,ct)===0)&&w(this,Et,Qe.setInterval(()=>{(this.options.refetchIntervalInBackground||jt.isFocused())&&q(this,j,jn).call(this)},l(this,ct)))},Ds=function(){q(this,j,Fs).call(this),q(this,j,Qs).call(this,q(this,j,qs).call(this))},Us=function(){l(this,Tt)!==void 0&&(Qe.clearTimeout(l(this,Tt)),w(this,Tt,void 0))},Ns=function(){l(this,Et)!==void 0&&(Qe.clearInterval(l(this,Et)),w(this,Et,void 0))},Ks=function(){let t=l(this,he).getQueryCache().build(l(this,he),this.options);if(t===l(this,N))return;let n=l(this,N);w(this,N,t),w(this,Vn,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},yo=function(t){V.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(l(this,de))}),l(this,he).getQueryCache().notify({query:l(this,N),type:"observerResultsUpdated"})})},go);function Rl(e,t){return me(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function mo(e,t){return Rl(e,t)||e.state.data!==void 0&&Ls(e,t,t.refetchOnMount)}function Ls(e,t,n){if(me(t.enabled,e)!==!1&&Me(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&js(e,t)}return!1}function ho(e,t,n,r){return(e!==t||me(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&js(e,n)}function js(e,t){return me(t.enabled,e)!==!1&&e.isStaleByTime(Me(t.staleTime,e))}function xl(e,t){return!Vt(e.getCurrentResult(),t)}function en(e){return{onFetch:(t,n)=>{let r=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],o=t.state.data?.pageParams||[],a={pages:[],pageParams:[]},c=0,u=async()=>{let d=!1,f=g=>{so(g,()=>t.signal,()=>d=!0)},m=Rr(t.options,t.fetchOptions),p=async(g,_,h)=>{if(d)return Promise.reject();if(_==null&&g.pages.length)return Promise.resolve(g);let b=(()=>{let Q={client:t.client,queryKey:t.queryKey,pageParam:_,direction:h?"backward":"forward",meta:t.options.meta};return f(Q),Q})(),T=await m(b),{maxPages:E}=t.options,S=h?ro:no;return{pages:S(g.pages,T,E),pageParams:S(g.pageParams,_,E)}};if(s&&i.length){let g=s==="backward",_=g?_o:Vs,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:Vs(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 Vs(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 _o(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function vo(e,t){return t?Vs(e,t)!=null:!1}function bo(e,t){return!t||!e.getPreviousPageParam?!1:_o(e,t)!=null}var $s=class extends Wn{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){super.setOptions({...e,behavior:en()})}getOptimisticResult(e){return e.behavior=en(),super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){let{state:n}=e,r=super.createResult(e,t),{isFetching:s,isRefetching:i,isError:o,isRefetchError:a}=r,c=n.fetchMeta?.fetchMore?.direction,u=o&&c==="forward",d=s&&c==="forward",f=o&&c==="backward",m=s&&c==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:vo(t,n.data),hasPreviousPage:bo(t,n.data),isFetchNextPageError:u,isFetchingNextPage:d,isFetchPreviousPageError:f,isFetchingPreviousPage:m,isRefetchError:a&&!u&&!f,isRefetching:i&&!d&&!m}}};var Bn,Ne,ce,It,Ke,ut,wo,So=(wo=class extends Cr{constructor(t){super();C(this,Ke);C(this,Bn);C(this,Ne);C(this,ce);C(this,It);w(this,Bn,t.client),this.mutationId=t.mutationId,w(this,ce,t.mutationCache),w(this,Ne,[]),this.state=t.state||Ws(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){l(this,Ne).includes(t)||(l(this,Ne).push(t),this.clearGcTimeout(),l(this,ce).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){w(this,Ne,l(this,Ne).filter(n=>n!==t)),this.scheduleGc(),l(this,ce).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){l(this,Ne).length||(this.state.status==="pending"?this.scheduleGc():l(this,ce).remove(this))}continue(){return l(this,It)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{q(this,Ke,ut).call(this,{type:"continue"})},r={client:l(this,Bn),meta:this.options.meta,mutationKey:this.options.mutationKey};w(this,It,Pr({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(o,a)=>{q(this,Ke,ut).call(this,{type:"failed",failureCount:o,error:a})},onPause:()=>{q(this,Ke,ut).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>l(this,ce).canRun(this)}));let s=this.state.status==="pending",i=!l(this,It).canStart();try{if(s)n();else{q(this,Ke,ut).call(this,{type:"pending",variables:t,isPaused:i}),l(this,ce).config.onMutate&&await l(this,ce).config.onMutate(t,this,r);let a=await this.options.onMutate?.(t,r);a!==this.state.context&&q(this,Ke,ut).call(this,{type:"pending",context:a,variables:t,isPaused:i})}let o=await l(this,It).start();return await l(this,ce).config.onSuccess?.(o,t,this.state.context,this,r),await this.options.onSuccess?.(o,t,this.state.context,r),await l(this,ce).config.onSettled?.(o,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(o,null,t,this.state.context,r),q(this,Ke,ut).call(this,{type:"success",data:o}),o}catch(o){try{await l(this,ce).config.onError?.(o,t,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onError?.(o,t,this.state.context,r)}catch(a){Promise.reject(a)}try{await l(this,ce).config.onSettled?.(void 0,o,this.state.variables,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onSettled?.(void 0,o,t,this.state.context,r)}catch(a){Promise.reject(a)}throw q(this,Ke,ut).call(this,{type:"error",error:o}),o}finally{l(this,ce).runNext(this)}}},Bn=new WeakMap,Ne=new WeakMap,ce=new WeakMap,It=new WeakMap,Ke=new WeakSet,ut=function(t){let n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),V.batch(()=>{l(this,Ne).forEach(r=>{r.onMutationUpdate(t)}),l(this,ce).notify({mutation:this,type:"updated",action:t})})},wo);function Ws(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Be,Oe,Hn,Ro,xo=(Ro=class extends xe{constructor(t={}){super();C(this,Be);C(this,Oe);C(this,Hn);this.config=t,w(this,Be,new Set),w(this,Oe,new Map),w(this,Hn,0)}build(t,n,r){let s=new So({client:t,mutationCache:this,mutationId:++Qn(this,Hn)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){l(this,Be).add(t);let n=Tr(t);if(typeof n=="string"){let r=l(this,Oe).get(n);r?r.push(t):l(this,Oe).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(l(this,Be).delete(t)){let n=Tr(t);if(typeof n=="string"){let r=l(this,Oe).get(n);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&l(this,Oe).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=Tr(t);if(typeof n=="string"){let s=l(this,Oe).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=Tr(t);return typeof n=="string"?l(this,Oe).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){V.batch(()=>{l(this,Be).forEach(t=>{this.notify({type:"removed",mutation:t})}),l(this,Be).clear(),l(this,Oe).clear()})}getAll(){return Array.from(l(this,Be))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Sr(n,r))}findAll(t={}){return this.getAll().filter(n=>Sr(t,n))}notify(t){V.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){let t=this.getAll().filter(n=>n.state.isPaused);return V.batch(()=>Promise.all(t.map(n=>n.continue().catch(G))))}},Be=new WeakMap,Oe=new WeakMap,Hn=new WeakMap,Ro);function Tr(e){return e.options.scope?.id}var He,lt,ge,Ge,ze,Er,Bs,Po,Hs=(Po=class extends xe{constructor(t,n){super();C(this,ze);C(this,He);C(this,lt);C(this,ge);C(this,Ge);w(this,He,t),this.setOptions(n),this.bindMethods(),q(this,ze,Er).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let n=this.options;this.options=l(this,He).defaultMutationOptions(t),Vt(this.options,n)||l(this,He).getMutationCache().notify({type:"observerOptionsUpdated",mutation:l(this,ge),observer:this}),n?.mutationKey&&this.options.mutationKey&&De(n.mutationKey)!==De(this.options.mutationKey)?this.reset():l(this,ge)?.state.status==="pending"&&l(this,ge).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||l(this,ge)?.removeObserver(this)}onMutationUpdate(t){q(this,ze,Er).call(this),q(this,ze,Bs).call(this,t)}getCurrentResult(){return l(this,lt)}reset(){l(this,ge)?.removeObserver(this),w(this,ge,void 0),q(this,ze,Er).call(this),q(this,ze,Bs).call(this)}mutate(t,n){return w(this,Ge,n),l(this,ge)?.removeObserver(this),w(this,ge,l(this,He).getMutationCache().build(l(this,He),this.options)),l(this,ge).addObserver(this),l(this,ge).execute(t)}},He=new WeakMap,lt=new WeakMap,ge=new WeakMap,Ge=new WeakMap,ze=new WeakSet,Er=function(){let t=l(this,ge)?.state??Ws();w(this,lt,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},Bs=function(t){V.batch(()=>{if(l(this,Ge)&&this.hasListeners()){let n=l(this,lt).variables,r=l(this,lt).context,s={client:l(this,He),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{l(this,Ge).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{l(this,Ge).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{l(this,Ge).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{l(this,Ge).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(l(this,lt))})})},Po);var Le,Co,To=(Co=class extends xe{constructor(t={}){super();C(this,Le);this.config=t,w(this,Le,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??Un(s,n),o=this.get(i);return o||(o=new fo({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(o)),o}add(t){l(this,Le).has(t.queryHash)||(l(this,Le).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=l(this,Le).get(t.queryHash);n&&(t.destroy(),n===t&&l(this,Le).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){V.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return l(this,Le).get(t)}getAll(){return[...l(this,Le).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>wr(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>wr(t,r)):n}notify(t){V.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){V.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){V.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Le=new WeakMap,Co);var z,dt,ft,tn,nn,pt,rn,sn,Eo,Gs=(Eo=class{constructor(e={}){C(this,z);C(this,dt);C(this,ft);C(this,tn);C(this,nn);C(this,pt);C(this,rn);C(this,sn);w(this,z,e.queryCache||new To),w(this,dt,e.mutationCache||new xo),w(this,ft,e.defaultOptions||{}),w(this,tn,new Map),w(this,nn,new Map),w(this,pt,0)}mount(){Qn(this,pt)._++,l(this,pt)===1&&(w(this,rn,jt.subscribe(async e=>{e&&(await this.resumePausedMutations(),l(this,z).onFocus())})),w(this,sn,Gt.subscribe(async e=>{e&&(await this.resumePausedMutations(),l(this,z).onOnline())})))}unmount(){var e,t;Qn(this,pt)._--,l(this,pt)===0&&((e=l(this,rn))==null||e.call(this),w(this,rn,void 0),(t=l(this,sn))==null||t.call(this),w(this,sn,void 0))}isFetching(e){return l(this,z).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return l(this,dt).findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return l(this,z).get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=l(this,z).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Me(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return l(this,z).findAll(e).map(({queryKey:t,state:n})=>{let r=n.data;return[t,r]})}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=l(this,z).get(r.queryHash)?.state.data,o=eo(t,i);if(o!==void 0)return l(this,z).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return V.batch(()=>l(this,z).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return l(this,z).get(t.queryHash)?.state}removeQueries(e){let t=l(this,z);V.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=l(this,z);return V.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=V.batch(()=>l(this,z).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(G).catch(G)}invalidateQueries(e,t={}){return V.batch(()=>(l(this,z).findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=V.batch(()=>l(this,z).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(G)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(G)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=l(this,z).build(this,t);return n.isStaleByTime(Me(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(G).catch(G)}fetchInfiniteQuery(e){return e.behavior=en(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(G).catch(G)}ensureInfiniteQueryData(e){return e.behavior=en(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Gt.isOnline()?l(this,dt).resumePausedMutations():Promise.resolve()}getQueryCache(){return l(this,z)}getMutationCache(){return l(this,dt)}getDefaultOptions(){return l(this,ft)}setDefaultOptions(e){w(this,ft,e)}setQueryDefaults(e,t){l(this,tn).set(De(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...l(this,tn).values()],n={};return t.forEach(r=>{wt(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){l(this,nn).set(De(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...l(this,nn).values()],n={};return t.forEach(r=>{wt(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...l(this,ft).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Un(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===$t&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...l(this,ft).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){l(this,z).clear(),l(this,dt).clear()}},z=new WeakMap,dt=new WeakMap,ft=new WeakMap,tn=new WeakMap,nn=new WeakMap,pt=new WeakMap,rn=new WeakMap,sn=new WeakMap,Eo);var on=X(ae(),1),Ao=X(Ir(),1),zs=on.createContext(void 0),L=e=>{let t=on.useContext(zs);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Gn=({client:e,children:t})=>(on.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,Ao.jsx)(zs.Provider,{value:e,children:t}));var Ar=X(ae(),1),ko=Ar.createContext(!1),Mo=()=>Ar.useContext(ko),Fp=ko.Provider;var zn=X(ae(),1),Pl=X(Ir(),1);function Cl(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Tl=zn.createContext(Cl()),Oo=()=>zn.useContext(Tl);var Fo=X(ae(),1);var qo=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?Wt(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Qo=e=>{Fo.useEffect(()=>{e.clearReset()},[e])},Do=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||Wt(n,[e.error,r]));var Uo=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))}},No=(e,t)=>e.isLoading&&e.isFetching&&!t,Ko=(e,t)=>e?.suspense&&t.isPending,Js=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var mt=X(ae(),1);function kr(e,t,n){let r=Mo(),s=Oo(),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",Uo(o),qo(o,s,a),Qo(s);let c=!i.getQueryCache().get(o.queryHash),[u]=mt.useState(()=>new t(i,o)),d=u.getOptimisticResult(o),f=!r&&e.subscribed!==!1;if(mt.useSyncExternalStore(mt.useCallback(m=>{let p=f?u.subscribe(V.batchCalls(m)):G;return u.updateResult(),p},[u,f]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),mt.useEffect(()=>{u.setOptions(o)},[o,u]),Ko(o,d))throw Js(o,u,s);if(Do({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()&&No(d,r)&&(c?Js(o,u,s):a?.promise)?.catch(G).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?d:u.trackResult(d)}function $(e,t){return kr(e,Wn,t)}var Je=X(ae(),1);function Z(e,t){let n=L(t),[r]=Je.useState(()=>new Hs(n,e));Je.useEffect(()=>{r.setOptions(e)},[r,e]);let s=Je.useSyncExternalStore(Je.useCallback(o=>r.subscribe(V.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=Je.useCallback((o,a)=>{r.mutate(o,a).catch(G)},[r]);if(s.error&&Wt(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function Jn(e,t){return kr(e,$s,t)}var Vo=X(jo(),1),Yn=typeof window<"u"&&window.__FSAOS_CONFIG__||{},At=Array.isArray(Yn.sources)?Yn.sources:[],El=Yn.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",Il=Yn.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",Ce=Yn.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",W=(0,Vo.createClient)(El,Il,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var Xn=null,Mr=0,$o,ei,Or=!1;$o=new Promise(e=>{ei=e});W.auth.onAuthStateChange((e,t)=>{t?.access_token?(Xn=t.access_token,Mr=t.expires_at??Math.floor(Date.now()/1e3)+3600):(Xn=null,Mr=0),Or||(Or=!0,ei())});setTimeout(()=>{Or||(Or=!0,ei())},5e3);function Wo(e,t){Xn=e,Mr=t??Math.floor(Date.now()/1e3)+3600}function ti(){Xn=null,Mr=0}async function Ye(){let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{};if(e.embedToken){if(typeof e.embedToken=="function")try{return await e.embedToken()??null}catch{return null}return e.embedToken}return await $o,Xn}var ln=null,dn=null,Bo=0,Ys=new Set,ni,Zn,fn=!1;ni=new Promise(e=>{Zn=e});function ri(){Bo++,Ys.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function qr(e){let t=typeof e=="string"?e:e.path,n=ln!==t||dn?.id!==(typeof e=="string"?void 0:e.id);ln=t,dn=typeof e=="string"?null:e,typeof e!="string"&&!kt.some(r=>r.id===e.id)&&(kt=[...kt,e],ai()),fn||(fn=!0,Zn()),n&&ri()}function pn(){return ln}function ye(){return dn}function si(){return Bo}function ii(e){return Ys.add(e),()=>{Ys.delete(e)}}function er(){return ni}function oi(){return fn}var Fr=null;function Mt(e,t={}){if(Fr){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}Fr=e,t.activate!==!1&&qr(e)}function fe(){return Fr}var kt=[],Xs=new Set,Ho=0;function ai(){Ho++,Xs.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function Te(){return kt}function tr(){return Ho}function Qr(e){return Xs.add(e),()=>{Xs.delete(e)}}function Go(e,t){let n=JSON.stringify(kt)!==JSON.stringify(e),r=ln!==t.path||dn?.id!==t.id;kt=e,ln=t.path,dn=t,fn||(fn=!0,Zn()),n&&ai(),r&&ri()}var cn=null,an=null,un=0,Zs=new Set,zo=0;function Jo(){zo++,Zs.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Session listener error:",t)}})}function ie(){return un}function ci(){return zo}function Yo(e){return Zs.add(e),()=>{Zs.delete(e)}}async function Xe(){if(cn)return cn;if(an)return an;let e=un;return an=(async()=>{let t=Ot(),n=await Ye();if(e!==un)throw new Error("Session changed during initialization");let r={};n&&(r.Authorization=`Bearer ${n}`);let s=await fetch(`${Ce}/d/${t}/init`,{method:"GET",headers:r});if(!s.ok)throw new Error(`Session init failed: ${s.status} ${s.statusText}`);let i=await s.json();if(e!==un)throw new Error("Session changed during initialization");let o=i.entry||i;return cn={scope_id:o.scope_id,scope_path:o.scope_path,instance_path:o.instance_path||"/root",fractal_id:o.fractal_id||null,instance_name:o.instance_name||null,display_name:o.scope_display_name||o.display_name||null,principal_id:o.principal_id||null},Jo(),cn})().catch(t=>{throw e===un&&(an=null),t}),an}function ht(){return cn}function ui(){un++,cn=null,an=null,ln=null,dn=null,Fr=null,kt=[],Jo()}var Xo=[];function ne(e){Xo.push(e)}function mn(){ui(),ti(),Zn(),fn=!1,ni=new Promise(e=>{Zn=e}),ri(),ai();for(let e of Xo)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function Ot(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var Zo=qr,B=pn,ee=si,we=ii,ea=er,Dr=oi;var li=0,ta=!1,na=0;function ra(e){if(typeof e!="string")return;let t=Date.parse(e);Number.isNaN(t)||(li=t-Date.now(),ta=!0,na=Date.now())}function Ur(){return Date.now()+li}function sa(){return ta}function ia(){return li}function oa(){return na}function aa(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Ur()>=t}function ca(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Math.max(0,t-Ur())}var hn,Ee=new Map,Ft=[],di=0,fi={foreground:0,normal:1,background:2},Nr=()=>performance.now(),pi=()=>new DOMException("Read cancelled","AbortError");function la(e={}){hn={concurrency:Math.max(1,Math.min(16,Math.floor(e.concurrency??6))),timeoutMs:Math.max(1e3,e.timeoutMs??15e3),onTiming:e.onTiming},Lr()}function da(){for(let e of Ee.values()){e.controller.abort();for(let t of e.consumers)t.detach(),t.reject(pi());e.consumers.clear(),e.timer&&clearTimeout(e.timer)}Ee.clear(),Ft.length=0}function fa(e,t){return e==="query"?!("materialize"in t):["read","list","search","resolve","resolve-items","get-channel-messages","list-memberships"].includes(e)}function Kr(e){return Array.isArray(e)?`[${e.map(Kr).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${Kr(n)}`).join(",")}}`:JSON.stringify(e)}function pa(e,t,n,r){if(n.signal?.aborted)return Promise.reject(pi());if(!hn)return r(n.signal);let s=Ee.get(e);if(s)fi[n.priority??"normal"]<fi[s.priority]&&(s.priority=n.priority??"normal");else{s={key:e,method:t,priority:n.priority??"normal",queuedAt:Nr(),controller:new AbortController,consumers:new Set,run:r},Ee.set(e,s),Ft.push(s);let 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(),Ee.get(a.key)===a&&Ee.delete(a.key),ua(a)},hn.timeoutMs)}let i=s,o=new Promise((a,c)=>{let u=()=>{d.detach(),i.consumers.delete(d),c(pi()),i.consumers.size||(i.controller.abort(),Ee.get(i.key)===i&&Ee.delete(i.key),ua(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 Lr(),o}function ua(e){let t=Ft.indexOf(e);t>=0&&(Ft.splice(t,1),Ee.get(e.key)===e&&Ee.delete(e.key),e.timer&&clearTimeout(e.timer)),Lr()}function Lr(){if(hn)for(;di<hn.concurrency&&Ft.length;){let e=r=>fi[r.priority]-Math.floor((Nr()-r.queuedAt)/2e3);Ft.sort((r,s)=>e(r)-e(s)||r.queuedAt-s.queuedAt);let t=Ft.shift();if(!t.consumers.size)continue;di++,t.startedAt=Nr();let n="success";Promise.resolve().then(()=>t.run(t.controller.signal)).then(r=>{for(let s of t.consumers)s.detach(),s.resolve(r)},r=>{n=t.controller.signal.aborted?"aborted":"error";for(let s of t.consumers)s.detach(),s.reject(r)}).finally(()=>{t.timer&&clearTimeout(t.timer),t.consumers.clear(),Ee.get(t.key)===t&&Ee.delete(t.key),di--;try{hn?.onTiming?.({method:t.method,priority:t.priority,queueMs:Math.round(t.startedAt-t.queuedAt),requestMs:Math.round(Nr()-t.startedAt),outcome:n})}catch{}Lr()})}}ne(da);var Al=new Set(["list-memberships","init"]),Ie=class extends Error{constructor(n){let r=typeof n.payload?.error=="string"?n.payload.error.trim():"",s=typeof n.payload?.message=="string"?n.payload.message.trim():"",i=n.responseBody.trim()||`Gateway HTTP error: ${n.status} ${n.statusText}`.trim(),o=r&&s?`${r}: ${s}`:s||r||i;super(o);te(this,"name","GatewayRequestError");te(this,"method");te(this,"status");te(this,"statusText");te(this,"payload");te(this,"responseBody");this.method=n.method,this.status=n.status,this.statusText=n.statusText,this.payload=n.payload,this.responseBody=n.responseBody}};async function x(e,t={},n={}){let r=ie(),s=pn(),i=Ot(),o=`${Ce}/d/${i}`,a={"Content-Type":"application/json"},c=await ma(Ye(),n.signal);if(r!==ie())throw new Error("Session changed before gateway request");if(c&&(a.Authorization=`Bearer ${c}`),!Al.has(e)&&!t._scope_path&&await ma(er(),n.signal),r!==ie())throw new Error("Session changed before gateway request");let u={...t},d=ht();!u.domain_scope_id&&d?.scope_id&&(u.domain_scope_id=d.scope_id);let f=s??pn();!u._scope_path&&f&&(u._scope_path=f);let m=async p=>{if(r!==ie())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!==ie())throw new Error("Session changed during gateway request");let h=null;if(_)try{h=JSON.parse(_)}catch{}if(!g.ok||!h)throw new Ie({method:e,status:g.status,statusText:g.statusText,payload:h,responseBody:_});if(h.success===!1){let y=h.error||"",b=h.denied_by||h.error_type||"";throw b==="rule"||b==="access"||b==="entitlement"||y==="RULE_DENIED"||y==="ACCESS_DENIED"||y==="PERMISSION_DENIED"||y==="ENTITLEMENT_REQUIRED"?new rt(h):new Ie({method:e,status:g.status,statusText:g.statusText,payload:h,responseBody:_})}return h&&h.server_now!==void 0&&ra(h.server_now),h};return fa(e,u)?pa(Kr([r,i,c,e,u]),e,n,m):m(n.signal)}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 v=X(ae(),1),Zl=X(ga(),1),ed=X(Ir(),1);var ya=new WeakMap;function Ae(e,t,n={}){let r=n.exact===!0,s=()=>e.invalidateQueries({queryKey:t,exact:r},{cancelRefetch:!1}),i=e.getQueryCache().findAll({queryKey:t,exact:r,fetchStatus:"fetching"}).flatMap(f=>f.promise?[f.promise]:[]);if(i.length===0)return s();let o=`${r?"=":"^"}${JSON.stringify(t)}`,a=ya.get(e);a||(a=new Map,ya.set(e,a));let c=a.get(o);if(c)return c;let u=a,d=Promise.allSettled(i).then(()=>(u.delete(o),s()));return u.set(o,d),d}function pe(e,t){return typeof e=="string"&&(e===t||e.startsWith(`${t}/`))}var jr=new WeakMap,_a=e=>e.meta?.arrangementRealtime===!0;function Ze(e,t){let n=e.getQueryCache().find({queryKey:t,exact:!0});if(!n)return;let r=jr.get(e);r||(r=new Map,jr.set(e,r));let s=r.get(n.queryHash);s&&clearTimeout(s),r.set(n.queryHash,setTimeout(()=>{r.delete(n.queryHash),e.getQueryCache().get(n.queryHash)===n&&Ae(e,t,{exact:!0})},250))}function va(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){if(!_a(n))continue;let r=n.state.data;if(n.meta?.personalSections===!0){(r?.item_path&&[t.path,t.old_path].some(i=>typeof i=="string"&&(i===r.item_path||i.startsWith(r.item_path+"/")))||r?.sections?.some(i=>i.entries?.some(o=>o.target?.id===t.item_id))||!r?.item_id&&t.item_type==="item_arrangement"&&t.name==="sidebar-sections")&&Ze(e,n.queryKey);continue}if(!r?.item_id)continue;let s=(i,o)=>!!(i&&t.item_id===i||o&&(t.path===o||t.old_path===o));(s(r.item_id,r.item_path)||t.parent_id===r.item_id||t.old_parent_id===r.item_id||[t.path,t.old_path].some(i=>typeof i=="string"&&i.slice(0,i.lastIndexOf("/"))===r.item_path)||r.resolved_children?.some(i=>s(i.id,i.symlink_path||i.path)||i.target&&s(i.target.id,i.target.path)))&&Ze(e,n.queryKey)}}function ba(e){for(let t of e.getQueryCache().getAll())_a(t)&&t.state.data!==void 0&&Ze(e,t.queryKey)}function wa(e){jr.get(e)?.forEach(clearTimeout),jr.delete(e)}var et=null;ne(()=>{et&&(et.cancelQueries({queryKey:["vfs"]}),et.removeQueries({queryKey:["vfs"]}))});function Sa(e){if(et&&et!==e)throw new Error("[fsaos-gateway-sdk] setQueryClient() called after a QueryClient was already in use. Inject the host client before rendering or starting realtime subscriptions.");et=e}function O(){return et||(et=new Gs({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),et}var Ra=new Proxy({},{get(e,t,n){let r=O(),s=r[t];return typeof s=="function"?s.bind(r):s}});var Vr=new WeakMap;function mi(e){return e.meta?.infiniteItemsRealtime?.filter}function kl(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 Ml(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 Ol(e,t,n){if(kl(e,n))return!0;if(t.spaceIds!==void 0&&(!t.spaceIds.length||n.space_item_id!==void 0&&!t.spaceIds.includes(n.space_item_id)&&!t.spaceIds.includes(n.old_space_item_id)))return!1;let r=t.scope,s=typeof r=="string"&&r!=="__unscoped__",i=typeof n.path=="string"||typeof n.old_path=="string";if(s&&i&&!pe(n.path,r)&&!pe(n.old_path,r))return!1;if(n.item_type==="symlink"&&s&&i)return!0;let o=Ml(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 xa(e,t){let n=Vr.get(e);n||(n=new Map,Vr.set(e,n));let r=n.get(t.queryHash);r&&clearTimeout(r),n.set(t.queryHash,setTimeout(()=>{n.delete(t.queryHash),!(e.getQueryCache().get(t.queryHash)!==t||!mi(t))&&Ae(e,t.queryKey,{exact:!0})},500))}function Pa(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){let r=mi(n);r&&Ol(n,r,t)&&xa(e,n)}}function Ca(e){for(let t of e.getQueryCache().getAll())mi(t)&&t.state.data!==void 0&&xa(e,t)}function Ta(e){Vr.get(e)?.forEach(clearTimeout),Vr.delete(e)}var $r=class extends Error{constructor(){super("The server did not confirm the selected-Space listing contract")}};function Ea(e,t){if(!Array.isArray(t)||t.some(n=>typeof n!="string")||JSON.stringify([...new Set(t)].sort())!==JSON.stringify(e))throw new $r}function gt(e){return!e||e.spaceIds===void 0?e:{...e,spaceIds:[...new Set(e.spaceIds.map(t=>t.toLowerCase()))].sort(),...e.limit!==void 0?{limit:Math.max(1,Math.min(e.limit,500))}:{}}}function gn(e){return e instanceof $r||e instanceof rt||e instanceof Ie&&(e.payload?.error==="SPACE_SELECTION_UNAVAILABLE"||e.payload?.error==="QUERY_PARAMS_INVALID"||e.status===401||e.status===403)}function oe(){return B()??"__unscoped__"}var P={all:()=>["vfs",oe()],item:e=>["vfs",oe(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",oe(),"children",e],allChildren:()=>["vfs",oe(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",oe(),"search",e,...t??[]],items:(e,t)=>["vfs",oe(),"items",e,JSON.stringify(gt(t??{}))],allItems:()=>["vfs",oe(),"items"],tree:(e,t)=>["vfs",oe(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",oe(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",oe(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",oe(),"get-activity-feed",e,t,n],itemVersions:(e,t,n,r)=>["vfs","item-versions",e,t,n,r],itemHistory:(e,t,n)=>["vfs","item-history",e,t,n],channelMessages:(e,t)=>["vfs",oe(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",oe(),"channel-messages"],channels:e=>["vfs",oe(),"channels",e??"all"],allChannels:()=>["vfs",oe(),"channels"],notifications:(e,t)=>["vfs",oe(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",oe(),"notifications"],unreadCounts:()=>["vfs",oe(),"unread-counts"],memberships:e=>["memberships",e]};var Fl=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function J(...e){Fl&&console.log("[WS]",...e)}var D=null,yn=null,vn=null,nr=0,ql=3e4,Ia=1e4,wn=!1,Aa=!1,qa=3e4,Ql=qa*2+5e3,Wr=0,Br=null,ka=!1;function Dl(){sr(),Wr=Date.now(),Br=setInterval(()=>{if(D&&D.readyState===WebSocket.OPEN&&Date.now()-Wr>Ql){J("ping: no inbound traffic for",Date.now()-Wr,"ms \u2014 closing half-open socket");try{D.close(4e3,"liveness timeout")}catch{}return}nt({type:"ping"})},qa)}function sr(){Br&&(clearInterval(Br),Br=null)}function Ul(){typeof document>"u"||(document.hidden?sr():rr()&&(J("Tab visible, reconnecting..."),qt()))}function Nl(){ka||typeof document>"u"||(document.addEventListener("visibilitychange",Ul),ka=!0)}var Se={};function gi(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return!n||!r?n===r:r===n||r.startsWith(`${n}/`)}var bn=[],tt=new Map,_n=new Map,ke=new Map;function Kl(e){let t=_n.get(e);return t?Array.from(new Set(Array.from(t.values()).flatMap(n=>n.event_types))).sort():[]}function Ma(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):!1}function Oa(e){let t=Kl(e);if(t.length===0)return tt.delete(e),null;let n={scope_id:e,event_types:t};return tt.set(e,n),n}var je=new Map,yt=new Map,hi="disconnected",Hr=[];function Gr(e){if(hi!==e){hi=e;for(let t of[...Hr])try{t(e)}catch{}}}function Ll(e){je.set(e,"ready");let t=yt.get(e);if(t){yt.delete(e);for(let n of t)n()}}function jl(){for(let e of je.keys())je.set(e,"disconnected")}function yi(e,t){je.set(e,"pending"),nt({type:"subscribe_path",path:e,event_types:t})}function Vl(){return Object.keys(Se).some(t=>Se[t]&&Se[t].length>0)||bn.length>0}function rr(){return tt.size>0||ke.size>0}async function qt(){if(!rr()){J("ensureConnection: no active subscriptions, skipping");return}if(D&&D.readyState===WebSocket.OPEN){J("ensureConnection: already open");return}if(yn)return J("ensureConnection: connection already in flight, waiting..."),yn;if(D){J("ensureConnection: killing stale WS in state",D.readyState);try{D.close()}catch{}D=null}return wn=!1,yn=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=Ce,n=await Ye();if(!n){J("ensureConnection: no token available, will retry"),Fa();return}let r=t.startsWith("https")?"wss":"ws",s=t.replace(/^https?:\/\//,""),i=`${r}://${s}/ws`;i+=`?token=${encodeURIComponent(n)}`,J("ensureConnection: opening WS to",i.substring(0,50)+"..."),Gr("connecting"),D=new WebSocket(i);let o=D;await new Promise((a,c)=>{if(!D)return c(new Error("WebSocket not created"));let u=setTimeout(()=>{if(D===o){if(J("ensureConnection: TIMEOUT after",Ia,"ms"),D&&D.readyState!==WebSocket.OPEN){try{D.close()}catch{}D=null}c(new Error("WebSocket connection timeout"))}},Ia);o.onopen=()=>{if(D!==o)return;clearTimeout(u),J("ensureConnection: CONNECTED");let d=Aa;Aa=!0,nr=0,Gr("connected"),$l(d),(typeof document>"u"||!document.hidden)&&Dl(),Nl(),a()},o.onmessage=d=>{D===o&&Wl(d.data)},o.onerror=()=>{J("ensureConnection: WS error event")},o.onclose=d=>{clearTimeout(u),D===o&&(J("ensureConnection: WS closed, code:",d.code,"reason:",d.reason),D=null,sr(),jl(),Gr("disconnected"),!wn&&rr()&&Fa(),c(new Error(`WebSocket closed: ${d.code}`)))}})}catch(e){J("ensureConnection: failed -",e?.message||e)}finally{yn=null}})(),yn}function Fa(){if(vn||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,nr)+Math.random()*1e3,ql);nr++,J("scheduleReconnect: attempt",nr,"in",Math.round(e),"ms"),vn=setTimeout(()=>{vn=null,rr()&&qt()},e)}function $l(e=!1){for(let t of tt.values())J("resubscribeAll: scope",t.scope_id),nt({type:"subscribe",scope_id:t.scope_id,event_types:t.event_types});for(let t of ke.values())J("resubscribeAll: path",t.path),yi(t.path,t.event_types);e&&Qa("reconnect")}function Qa(e){try{let t=O();Ca(t),ba(t);for(let n of ke.values())t.invalidateQueries({queryKey:P.item(n.path)}),t.invalidateQueries({queryKey:P.children(n.path)});J("catchUpAfterGap:",e,"- invalidated",ke.size,"paths")}catch(t){J("catchUpAfterGap: cache invalidation skipped",t)}}function nt(e){D&&D.readyState===WebSocket.OPEN&&D.send(JSON.stringify(e))}function Wl(e){Wr=Date.now();try{let t=JSON.parse(e);if(t.type==="subscribed_path"){typeof t.path=="string"&&Ll(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"){Qa(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"&&(Pa(O(),r),va(O(),r)),typeof r.path=="string")for(let[s,i]of Object.entries(Se))s!=="*"&&gi(s,r.path)&&i.forEach(o=>o(r));Se["*"]&&Se["*"].forEach(s=>s(r));for(let s of bn)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function _i(){!Vl()&&tt.size===0&&ke.size===0&&D&&(wn=!0,sr(),D.close(),D=null,wn=!1)}function zr(e,t){return Se[e]||(Se[e]=[]),Se[e].push(t),ke.has(e)||(ke.set(e,{path:e,event_types:["token_stream"]}),D&&D.readyState===WebSocket.OPEN?yi(e,["token_stream"]):je.set(e,"pending")),qt(),()=>{let n=Se[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete Se[e],ke.delete(e),je.delete(e),yt.delete(e),nt({type:"unsubscribe_path",path:e}))}_i()}}function re(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return bn.push(...s),rr()&&qt(),()=>{for(let i of s){let o=bn.indexOf(i);o!==-1&&bn.splice(o,1)}_i()}}function Sn(e,t=["vfs_change","ccm_change"]){let n=Symbol(e),r=Array.from(new Set(t)).sort();if(r.length===0)return()=>{};let s=_n.get(e)??new Map,i=tt.get(e)?.event_types;s.set(n,{event_types:r}),_n.set(e,s);let o=Oa(e);if(!o)return()=>{};J("subscribeToScope:",e,o.event_types),D&&D.readyState===WebSocket.OPEN&&!Ma(i,o.event_types)&&nt({type:"subscribe",scope_id:e,event_types:o.event_types}),qt();let a=!0;return()=>{if(!a)return;a=!1;let c=_n.get(e);if(!c?.delete(n))return;let u=tt.get(e)?.event_types;if(c.size===0)_n.delete(e),tt.delete(e),nt({type:"unsubscribe",scope_id:e});else{let d=Oa(e);d&&D&&D.readyState===WebSocket.OPEN&&!Ma(u,d.event_types)&&nt({type:"subscribe",scope_id:e,event_types:d.event_types})}_i()}}function Da(e,t,n={}){nt({type:"emit",scope_id:e,event_type:t,payload:n})}function vi(){J("disconnectSSE: tearing down"),Ta(O()),wa(O()),wn=!0,sr(),D&&(D.close(),D=null),vn&&(clearTimeout(vn),vn=null),yn=null,wn=!1,nr=0;for(let e of Object.keys(Se))delete Se[e];bn.length=0,tt.clear(),_n.clear(),ke.clear(),je.clear(),yt.clear(),Gr("disconnected")}function Ua(){nt({type:"ping"})}function Na(e){return ke.has(e)?je.get(e)??"pending":"unsubscribed"}function Ka(e,t=5e3){return ke.has(e)?je.get(e)==="ready"&&D&&D.readyState===WebSocket.OPEN?Promise.resolve(!0):(qt(),new Promise(n=>{let r=!1,s=yt.get(e)??[],i=()=>{r||(r=!0,clearTimeout(o),n(!0))};s.push(i),yt.set(e,s);let o=setTimeout(()=>{if(r)return;r=!0;let a=yt.get(e);if(a){let c=a.indexOf(i);c!==-1&&a.splice(c,1),a.length===0&&yt.delete(e)}n(!1)},t)})):Promise.resolve(!1)}function La(e){let t=ke.get(e);if(!t){J("resubscribePath: no active subscription for",e);return}D&&D.readyState===WebSocket.OPEN?(J("resubscribePath: re-sending frame for",e),yi(t.path,t.event_types)):(je.set(e,"pending"),qt())}function Jr(e){Hr.push(e);try{e(hi)}catch{}return()=>{let t=Hr.indexOf(e);t!==-1&&Hr.splice(t,1)}}ne(vi);function ja(){return new Date().toISOString()}function Va(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function _e(e){let t=e.path||e.item_path||"",n=t.split("/");n.pop();let r=n.join("/"),s=e.type_data||{};return s.allowed_parent_types&&!s.accepts&&(s.accepts=s.allowed_parent_types),delete s.allowed_parent_types,{id:e.id||e.item_id||"",name:e.name||e.item_name||"",item_type:e.item_type||"unknown",path:t,parent_path:r,is_active:e.is_active!==!1,has_children:e.has_children??!1,created_at:e.created_at||ja(),updated_at:e.updated_at||ja(),visibility:e.visibility,type_data:s,scope_item_id:e.scope_item_id,fractal_id:e.fractal_id,parent_instance_id:e.parent_instance_id,owner_principal_id:e.owner_principal_id,created_by_principal_id:e.created_by_principal_id,parent_id:e.parent_id,space_item_id:e.space_item_id,account_item_id:e.account_item_id}}function or(e){return(e.content?.items||e.items||[]).map(_e)}async function Xr(e){try{let t=await x("read",{id:e});if(t.item_name||t.item_path){let r=_e(t);return r.path&&O().setQueryData(P.item(r.path),r),r}let n=t.item;if(n){let r=_e(n);return r.path&&O().setQueryData(P.item(r.path),r),r}return null}catch{return null}}async function ar(e){try{let t=await x("read",{path:e});if(t.item_name||t.item_path)return _e(t);let n=t.item;return n?_e(n):null}catch{return null}}async function cr(e){try{let t=await x("list",{path:e,limit:200}),n=or(t);for(let r of n)O().setQueryData(P.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function $a(e,t){let{items:n}=await xn({type:"turn_queue_entry",scope:e,parent_id:t,fields:{state:"queued"},sort_by:"created_at",sort_dir:"asc",limit:100});return n.map(r=>{let s=String(r.type_data?.conversation_anchor_item_id??r.type_data?.conversation_root_id??t);return{id:r.id,path:r.path,content:String(r.type_data?.content??""),state:String(r.type_data?.state??"queued"),queue_seq:Number(r.type_data?.queue_seq??0),created_at:r.created_at,conversation_anchor_item_id:s,conversation_root_id:s,client_request_id:typeof r.type_data?.client_request_id=="string"?r.type_data.client_request_id:void 0,promoted_message_id:typeof r.type_data?.promoted_message_id=="string"?r.type_data.promoted_message_id:void 0,promoted_event_id:typeof r.type_data?.promoted_event_id=="string"?r.type_data.promoted_event_id:void 0}}).sort((r,s)=>r.queue_seq-s.queue_seq||r.created_at.localeCompare(s.created_at))}async function Zr(e,t,n){try{let r=await x("list",{path:e,limit:t,offset:n}),s=or(r);for(let i of s)O().setQueryData(P.item(i.path),i);return{items:s,total_hint:r.total??r.content?.total??s.length}}catch(r){return console.error(`[gateway] Failed to fetch children page of ${e}:`,r),{items:[],total_hint:0}}}async function es(e){let n=await x("types-list",e?{scope_id:e}:{}),r=n.content?.items||n.items||[],s=new Map;for(let i of r){let o=i.name,a=i.type_data;!o||!a||s.set(o,{type_key:o,display_name:a.display_name||o,display_name_plural:a.display_name_plural||o+"s",icon:a.icon||"File",color:a.color||"gray",description:a.description||"",input_schema:a.input_schema||{},system_schema:a.system_schema||{},json_schema:a.input_schema||a.json_schema||{},default_data:a.default_data||{},field_defaults:a.field_defaults||{},renderer_config:a.renderer_config||{},is_system:a.is_system??!1,is_active:a.is_active??!0,is_container:a.is_container??!1,is_scope:a.is_scope??!1,render_mode:a.render_mode||"none",placement_mode:a.placement_mode,direct_parent_types:a.direct_parent_types,allowed_parent_types:a.allowed_parent_types,governed_create:a.governed_create,create_method:a.create_method,dedup:a.dedup,edges:a.edges,events:a.events})}return s}async function ts(e){try{let t=await x("edges",{item_id:e}),n=t.outgoing||[],r=t.incoming||[],s=[];for(let i of n)s.push({id:i.edge_id||Va(),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||Va(),source_item_id:i.source_id||"",target_item_id:e,edge_type:i.edge_type||"",weight:i.weight??1,context:i.context||{},is_active:!0,is_bidirectional:i.is_bidirectional});return s}catch(t){return console.warn(`[gateway] Failed to fetch edges for ${e}:`,t),[]}}async function ns(e,t=1,n,r){try{let s={path:e,max_depth:t>0?t:999};n?.length&&(s.item_types=n),r&&(s.limit=r);let i=await x("tree",s),o=or(i);for(let a of o)O().setQueryData(P.item(a.path),a);return o}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function rs(e,t=50,n=0){try{let r=await x("get-activity-feed",{scope_path:e,limit:t,offset:n});return r.content?.items||r.items||r.entries||[]}catch(r){return console.error(`[gateway] Failed to fetch recent activity for ${e}:`,r),[]}}async function ur(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;try{let i=await x("item-versions",{id:e,limit:n,offset:r,include_snapshots:s});return{versions:i.content?.items||i.versions||[],total:i.total??0}}catch(i){return console.error(`[gateway] Failed to fetch item versions for ${e}:`,i),{versions:[],total:0}}}async function ss(e,t=50,n=0){return ur(e,{limit:t,offset:n})}async function is(e,t,n){try{let r={scope_id:e};t?.length&&(r.item_types=t),n&&(r.limit=n);let s=await x("member-focus",r),i=or(s);for(let o of i)O().setQueryData(P.item(o.path),o);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${e}:`,r),[]}}async function os(e,t){let n={path:e};t?.mode&&(n.mode=t.mode),t?.strategy&&(n.strategy=t.strategy),t?.arguments&&(n.arguments=t.arguments);let s=await x("open",n);return{item_id:s.item_id,item_path:s.item_path,item_name:s.item_name,item_type:s.item_type,render:s.render,compatible_components:s.compatible_components??[],content:s.content,metadata:s.metadata,instructions:s.instructions}}function Rn(e){return!!e&&(!!e.type||Array.isArray(e.any_of)&&e.any_of.length>0)}function Bl(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 Hl=["catalog","parent_only","internal"];function Wa(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"&&Hl.includes(e.discovery)&&(s.discovery=e.discovery);let i=r(e);if(Object.keys(i.fields).length&&(s.fields=i.fields),Object.keys(i.field_in).length&&(s.field_in=i.field_in),Array.isArray(e.any_of)){let o=[];for(let a of e.any_of){if(!a||typeof a!="object"||Array.isArray(a))continue;let c=a,u={};typeof c.item_type=="string"&&c.item_type&&(u.item_type=c.item_type);let d=r(c);Object.keys(d.fields).length&&(u.fields=d.fields),Object.keys(d.field_in).length&&(u.field_in=d.field_in),Object.keys(u).length&&o.push(u)}o.length&&(s.any_of=o)}return Rn(s)?{...s,...t}:null}async function xn(e,t={}){if(e=gt(e),e.spaceIds?.length===0)return{items:[],total_hint:0};let n={};e.type&&(n.item_type=e.type),e.scope&&(n.scope_path=e.scope);let r={};if(e.spaceIds!==void 0&&(r.space_ids=e.spaceIds),e.name&&(r.name=e.name),e.tag&&(r.tag=e.tag),e.parent_id&&(r.parent_id=e.parent_id),e.sort_by&&(r.sort_by=e.sort_by),e.sort_dir&&(r.sort_dir=e.sort_dir),e.offset!=null&&(r.offset=e.offset),e.fields)for(let[s,i]of Object.entries(e.fields))r[`field.${s}`]=String(i);if(e.field_in)for(let[s,i]of Object.entries(e.field_in))r[`field_in.${s}`]=i.map(String);e.discovery&&(r.discovery=e.discovery),e.any_of?.length&&(r.any_of=e.any_of.map(Bl)),Object.keys(r).length>0&&(n.filters=r),e.limit!=null&&(n.limit=e.limit);try{let s=await x("query",n,t);e.spaceIds!==void 0&&Ea(e.spaceIds,s.selected_space_ids??s.content?.selected_space_ids);let i=or(s);for(let o of i)O().setQueryData(P.item(o.path),o);return{items:i,total_hint:s.total??s.content?.total??i.length}}catch(s){if(t.signal?.aborted||s instanceof Error&&s.name==="AbortError"||(console.error(`[gateway] Failed to fetch items of type ${e.type??"(any_of)"}:`,s),t.throwOnError||e.spaceIds!==void 0))throw s;return{items:[],total_hint:0}}}function Gl(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 Ba(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:Gl(n.origin),presentationRole:r.presentation_role==="user-request"?"user-request":r.presentation_role==="output"?"output":void 0}}).sort((t,n)=>t.createdAt.localeCompare(n.createdAt))}function ir(e){return e.filter(t=>t.item_type==="message").map(t=>{let n=t.type_data||{},r="user";n.role==="assistant"?r="assistant":n.role==="system"&&(r="system");let s=n.metadata||{};return{id:t.id||"",path:t.path||"",content:n.message||n.content||"",created_at:t.created_at||"",role:r,status:typeof n.status=="string"?n.status:void 0,delivery_state:typeof n.delivery_state=="string"?n.delivery_state:void 0,cognition_event_id:typeof n.cognition_event_id=="string"?n.cognition_event_id:void 0,seq:n.seq||0,principal_id:n.principal_id,member_id:typeof n.member_id=="string"?n.member_id:void 0,reply_count:n.reply_count||0,member_count:n.member_count||0,parent_message_id:n.parent_message_id,intent_card:s.intent_card,metadata:Object.keys(s).length>0?s:void 0,thread_summary:Array.isArray(n.thread_summary)&&n.thread_summary.length>0?n.thread_summary:void 0}}).sort((t,n)=>t.seq-n.seq)}async function Ha(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await x("get-channel-messages",n),i=s.messages||s.content?.items||s.items||[];return ir(i)}catch(n){throw console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),n}}async function as(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await x("get-channel-messages",n),i=s.messages||[],o=ir(i),a=Ba(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:ir(s.activity_messages||[]),messageCards:c,siblingCards:u,mode:s.mode||"top_level"}}catch(n){throw console.error(`[gateway] Failed to fetch channel messages with cards for ${e}:`,n),n}}async function lr(e,t){try{let n={channel_path:e};t?.parentMessageId&&(n.parent_message_id=t.parentMessageId),t?.conversationsOnly&&(n.conversations_only=!0),t?.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 x("get-channel-messages",n);if(t?.conversationsOnly&&s.conversations_only!==!0)throw new Error("This server does not support conversation history lists yet. Update the message reader.");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=Ba(i),a=new Map,c=[];for(let u of o)if(u.parentMessagePath){let d=a.get(u.parentMessagePath)||[];d.push(u),a.set(u.parentMessagePath,d)}else c.push(u);return{messages:ir(i),activityMessages:ir(s.activity_messages||[]),messageCards:a,siblingCards:c,mode:s.mode||"top_level"}}catch(n){throw console.error(`[gateway] Failed to fetch channel messages page for ${e}:`,n),n}}function Yr(e){O().invalidateQueries({queryKey:P.children(e)})}function bi(e){O().invalidateQueries({queryKey:P.item(e)})}function Ga(e,t){bi(e),Yr(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&Yr(r)}function za(e){let t=e+"/";O().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function Ja(){O().invalidateQueries({queryKey:P.all()})}function Ya(e){O().invalidateQueries({queryKey:P.types(e)})}function Xa(e,t){e?O().invalidateQueries({queryKey:P.channelMessages(e,t)}):O().invalidateQueries({queryKey:P.allChannelMessages()})}function Za(e,t){e&&t?O().invalidateQueries({queryKey:P.openEnvelope(e,t)}):e?O().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):O().invalidateQueries({queryKey:P.allOpenEnvelopes()})}function Ve(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}async function cs(){return((await x("list-memberships",{})).memberships||[]).map(n=>({accountId:n.account_id,path:n.account_path,name:n.account_name,role:n.role||"member",typeData:n.account_type_data||{},joinedAt:n.joined_at,via:n.via,placement:n.placement,subordinateTo:n.subordinate_to??null,cascadeAnchorId:n.cascade_anchor_id??null,isAccount:n.is_account??void 0,isSpace:n.is_space??void 0,isOwner:n.is_owner??void 0,billingResponsible:n.billing_responsible??void 0,grantedVia:n.granted_via??null,grantedUnderAccountId:n.granted_under_account_id??null,membershipPath:n.membership_path??null,personalSpaceId:n.personal_space_id??null,personalSpacePath:n.personal_space_path??null}))}var Pn=new Map,dr=null,us=null,_t=new Map,ec=250;function Qt(e){if(dr){Cn(e);return}Cn(e),dr=re("vfs_change",t=>zl(t)),us=re("ccm_change",t=>Jl(t))}function Cn(e){if(Pn.has(e))return;let t=Sn(e,["vfs_change","ccm_change"]);Pn.set(e,t)}function ls(e){let t=Pn.get(e);t&&(t(),Pn.delete(e))}function wi(){for(let[,e]of Pn)e();Pn.clear(),dr&&(dr(),dr=null),us&&(us(),us=null),_t.forEach(e=>clearTimeout(e)),_t.clear()}ne(wi);function zl(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=_t.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{_t.delete(s),Yl(n,t,e,s)},ec);_t.set(s,o)}function Jl(e){if(!e||typeof e!="object")return;let t=e.source_item_id||e.source_id,n=e.target_item_id||e.target_id;if(!(e.edge_type!=null||t!=null||n!=null)||!t&&!n||e.item_type==="message")return;let s=`ccm:${t??""}:${n??""}`,i=_t.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{_t.delete(s),t&&O().invalidateQueries({queryKey:P.edges(t)}),n&&O().invalidateQueries({queryKey:P.edges(n)})},ec);_t.set(s,o)}function Yl(e,t,n,r){if((e||"").toUpperCase()==="DELETE")O().removeQueries({queryKey:P.item(t)}),O().removeQueries({queryKey:P.children(t)}),O().removeQueries({queryKey:P.tree(t)});else if(n.item_id)try{let i={id:n.item_id,path:n.path,name:n.name,item_type:n.item_type,parent_id:n.parent_id,scope_item_id:n.scope_item_id},o=_e(i);o&&o.id&&O().setQueryData(P.item(t),o)}catch{}O().invalidateQueries({queryKey:P.children(r)}),O().invalidateQueries({predicate:i=>{let o=i.queryKey;if(o[0]!=="vfs"||o[1]!=="tree")return!1;let a=o[2];return t.startsWith(a+"/")||t===a}}),n.item_id&&O().invalidateQueries({queryKey:P.itemById(n.item_id)})}var Tn=null;ne(()=>{Tn=null});function vt(e){if(e!==Tn||e.generation!==ie())throw new Error("Workspace session changed")}function Xl(e){return e instanceof Ie&&e.payload?.error==="item_not_found"}function fr(e,t){let n=e.resolve(t.id);if(!n||n.path!==t.path||n.kind!==t.kind)throw new Error("Mount is not an available membership");return n}function pr(e){let t=fe();if(!t)throw new Error("Elect a home account before loading mounts");return[t,...e.filter((n,r)=>n.id!==t.id&&e.findIndex(s=>s.id===n.id)===r)]}function tc(e,t){return JSON.stringify({mounts:e.map(n=>n.id),last_anchor:t.id})}async function nc(e,t,n){vt(e);let r=tc(t,n);if(e.saved===r)return;let s=JSON.parse(r);await x(e.exists?"update":"create",e.exists?{_scope_path:e.scope,path:e.path,type_data:s}:{_scope_path:e.scope,parent_path:e.path.slice(0,e.path.lastIndexOf("/")),name:"mounts",item_type:"file",type_data:s}),vt(e),e.exists=!0,e.saved=r}function rc(e,t){let n=Te();Qt(fe().id);for(let r of n)e.some(s=>s.id===r.id)||ls(r.id);for(let r of e)Cn(r.id);Go(e,t)}async function Dt(e,t,n={}){let r=fe();if(!r)throw new Error("Elect a home account before loading mounts");let s=`${e}/settings/mounts`;if(Tn&&Tn.path!==s)throw new Error("Reset the session before changing the mount declaration owner");let i=Tn??(Tn={generation:ie(),path:s,scope:r.path,resolve:t,exists:!1,ready:!1,saved:null,queue:Promise.resolve()});return vt(i),i.loading?i.loading:i.ready?Te():(i.resolve=t,i.loading=(async()=>{let o=null;try{let d=await x("read",{path:s,_scope_path:i.scope});if(vt(i),o=d.type_data??d.item?.type_data,!o||!Array.isArray(o.mounts)||!o.mounts.every(f=>typeof f=="string"))throw new Error("Invalid saved mount declaration");i.exists=!0}catch(d){if(vt(i),!Xl(d))throw d;i.exists=!1}let a=n.initialAnchor?fr(i,n.initialAnchor):r,c=pr(o?o.mounts.map(t).filter(d=>d!==null):[a]),u=o?c.find(d=>d.id===o.last_anchor)??c.find(d=>d.kind==="space")??r:a;return o?i.saved=tc(c,u):n.initialAnchor&&await nc(i,c,u),vt(i),i.ready=!0,rc(c,u),c})().finally(()=>{i.loading=void 0}),i.loading)}function ds(e){let t=Tn;if(!t?.ready)return Promise.reject(new Error("Workspace mounts are not loaded"));let n=t.queue.then(async()=>{vt(t);let{refs:r,anchor:s}=e(t);await nc(t,r,s),vt(t),rc(r,s)});return t.queue=n.catch(()=>{}),n}function Si(e){return ds(t=>({refs:pr([...Te(),fr(t,e)]),anchor:ye()}))}function sc(e){return ds(()=>{if(e===fe().id)throw new Error("The home account cannot be unmounted");let t=pr(Te().filter(r=>r.id!==e)),n=t.find(r=>r.id===ye()?.id)??t.find(r=>r.kind==="space")??fe();return{refs:t,anchor:n}})}function mr(e){return ds(t=>{let n=fr(t,e);return{refs:pr([...Te(),n]),anchor:n}})}function fs(e,t){return ds(n=>{let r=pr(e.map(i=>fr(n,i))),s=fr(n,t);if(!r.some(i=>i.id===s.id))throw new Error("Selected mount must be in the working set");return{refs:r,anchor:s}})}function ps(e){if(typeof e.path!="string")return!1;let t=[...Te().map(n=>n.path),ye()?.path].filter(n=>!!n);return!t.length&&B()&&t.push(B()),t.some(n=>pe(e.path,n))}function Ri(e,t,n,r){if(!["message","card"].includes(e?.item_type)||!pe(e.path,t))return!1;if(!n){let s=e.path.slice(t.length).replace(/^\//,""),i=s?s.split("/").length:0;return e.item_type==="message"?i===1:i===1||i===2}return e.item_id===n||e.parent_id===n?!0:r.some(s=>{if(e.item_id===s.id||e.parent_id===s.id)return!0;let i=s.id===n?s.path:s.parent_message_id===n?s.path.slice(0,s.path.lastIndexOf("/")):void 0;return!!i&&pe(e.path,i)})}var ic=new WeakMap;function oc(e,t,n){let r=ic.get(e);r||(r=new Map,ic.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 E=d;d=!1;let S=[...f],Q=new Set(m);m.clear(),f.clear();try{if(E)await Ae(e,t,{exact:!0});else{let R=(await Promise.allSettled(S.map(async I=>{let M=e.getQueryCache().find({queryKey:t,exact:!0});if(!M)return;let A=await x("read",{id:I});if(A.success===!1)throw new Error("Channel refresh failed");if(a||!M||e.getQueryCache().find({queryKey:t,exact:!0})!==M)return;let k=_e(A.item??A);if(k.id!==I||k.item_type!=="channel")return;let U=p().find(H=>H.id===I);if(!U)return;let F=n({...k}),le={...U,path:F.path,name:F.name,displayName:F.displayName,messageCount:F.messageCount,aiMode:F.aiMode,activeAgentIds:F.activeAgentIds,isPrivate:F.isPrivate,isDm:F.isDm,autoPilot:F.autoPilot,isArchived:F.isArchived,updatedAt:F.updatedAt};Q.has(I)&&(U.name!==le.name||U.displayName!==le.displayName||U.path!==le.path)&&(d=!0),e.setQueryData(t,H=>H?.map(qe=>qe.id===I?le:qe))}))).find(I=>I.status==="rejected");if(R?.status==="rejected")throw R.reason}}catch(K){console.warn("[channels] refresh failed",K)}finally{u=!1,(d||f.size)&&g()}},h=E=>p().some(S=>S.id===E.item_id||S.path===E.path)?!0:ps(E),y=E=>{if(!h(E))return;let S=String(E.action??"").toLowerCase();if(["insert","delete","rename","move"].includes(S))d=!0;else if(S==="update"){let Q=p().find(K=>K.id===E.item_id||K.path===E.path);Q&&(f.add(Q.id),m.add(Q.id))}(d||f.size)&&g()},b=E=>{let S=p().find(Q=>Q.id===E.parent_id);S&&(f.add(S.id),g())},T=["vfs_change","ccm_change"].flatMap(E=>[re(E,y,S=>S.item_type==="channel"),re(E,b,S=>S.item_type==="message")]);i={users:0,stop:()=>{a=!0,c&&clearTimeout(c),T.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 Y(){return(0,v.useSyncExternalStore)(we,ee,ee)}function fc(){return Y(),Dr()}function pc(e){return Y(),$({queryKey:P.item(e),queryFn:()=>ar(e),enabled:!!e,staleTime:1/0})}function mc(e){return Y(),$({queryKey:P.itemById(e),queryFn:()=>Xr(e),enabled:!!e,staleTime:1/0})}function Pi(e){return Y(),$({queryKey:P.children(e),queryFn:()=>cr(e),enabled:!!e})}function hc(e){let t=Pi(e);return{...t,children:t.data??[]}}function gc(e,t=1){return Y(),$({queryKey:P.tree(e,t),queryFn:()=>ns(e,t),enabled:!!e})}function yc(e,t){return Y(),$({queryKey:P.search(e,t),queryFn:async()=>{let n={query:e};t?.length&&(n.item_types=t);let r=await x("search",n);return(r.content?.items||r.items||r.results||[]).map(_e)},enabled:!!e&&e.length>0})}function _c(e){Y();let t=(0,v.useMemo)(()=>e,[JSON.stringify(e)]);return $({queryKey:["vfs",B()??"__unscoped__","resolve",JSON.stringify(t??{})],queryFn:async()=>await x("resolve",t),enabled:!!t?.query&&t.query.length>0})}function vc(e){Y();let t=gt(e),n=(0,v.useMemo)(()=>t,[JSON.stringify(t)]),r=$({queryKey:P.items(n?.type??"",n),queryFn:({signal:s})=>xn(n,{signal:s,throwOnError:!0}),enabled:Rn(n),...n?.spaceIds!==void 0?{retry:(s,i)=>!gn(i)&&au(s,i)}:{},select:s=>s.items});return n?.spaceIds!==void 0&&gn(r.error)?{...r,data:void 0}:r}function Ci(e,t={}){let n=Y(),{realtime:r=!1}=t,s=gt(e),i=s?.limit??20,o=(0,v.useMemo)(()=>s,[JSON.stringify(s)]),a=(0,v.useMemo)(()=>["vfs",B()??"__unscoped__","infinite-items",o?.type??"",JSON.stringify(o??{})],[n,o]),c=Jn({queryKey:a,queryFn:async({pageParam:f=0,signal:m})=>xn({...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:Rn(o),...o?.spaceIds!==void 0?{retry:(f,m)=>!gn(m)&&au(f,m)}:{},staleTime:r?1/0:t.staleTime,meta:r&&o?{infiniteItemsRealtime:{filter:o}}:{}}),u=(0,v.useMemo)(()=>{if(o?.spaceIds!==void 0&&gn(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&&gn(c.error);return{allItems:u,refetch:c.refetch,fetchNextPage:c.fetchNextPage,isFetchingNextPage:c.isFetchingNextPage,isExhausted:d||!c.hasNextPage,isLoading:c.isLoading,isFetching:c.isFetching,error:c.error,totalHint:d?void 0:c.data?.pages?.[0]?.total_hint}}function ac(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 td(e,t){if(e.is_active===!1||e.item_type!==t.type||!pe(e.path,t.scope)||t.parent_id&&e.parent_id!==t.parent_id)return!1;let n=e.type_data??{};for(let[r,s]of Object.entries(t.fields??{})){let i=n[r];if(typeof s=="string"&&s.endsWith("*")){if(typeof i!="string"||!i.startsWith(s.slice(0,-1)))return!1}else if(i!==s)return!1}for(let[r,s]of Object.entries(t.field_in??{}))if(!s.includes(n[r]))return!1;return!0}function bc(e,t={}){let n=ac(e),r=Ci(e,n?{realtime:!1,staleTime:3e4}:{realtime:!0}),s=L(),i=JSON.stringify([B(),gt(e)]),[o,a]=(0,v.useState)(()=>({identity:i,upserts:{},deleted:new Set})),c=o.identity===i?o:{identity:i,upserts:{},deleted:new Set},u=(0,v.useMemo)(()=>{if(!n)return r.allItems;let p=Object.values(c.upserts),g=new Set(p.map(b=>b.id)),_=[...p,...r.allItems.filter(b=>!g.has(b.id))].filter(b=>!c.deleted.has(b.path)),h=e.sort_by??"updated_at",y=e.sort_dir==="asc"?1:-1;return _.sort((b,T)=>y*String(b[h]??"").localeCompare(String(T[h]??"")))},[n,r.allItems,c,e?.sort_by,e?.sort_dir]),d=(0,v.useRef)(u);d.current=u;let f=(0,v.useRef)(t.shouldReadUpdate);f.current=t.shouldReadUpdate;let m=(0,v.useRef)(r.refetch);return m.current=r.refetch,(0,v.useEffect)(()=>{if(!ac(e))return;let p=e,g=!1,_=!1,h=!1,y=0,b=new Map,T=()=>{let R=y;m.current().then(I=>{!g&&!I.isError&&y===R&&a({identity:i,upserts:{},deleted:new Set})})},E=R=>{y++,a(M=>{let A=M.identity===i?M:{identity:i,upserts:{},deleted:new Set},k={...A.upserts};return delete k[R],{identity:i,upserts:k,deleted:new Set(A.deleted).add(R)}});let I=b.get("__reconcile__");I&&clearTimeout(I),b.set("__reconcile__",setTimeout(()=>{b.delete("__reconcile__"),T()},250))},S=R=>{let I=b.get(R);I&&clearTimeout(I),b.set(R,setTimeout(()=>{b.delete(R),s.fetchQuery({queryKey:P.item(R),queryFn:()=>ar(R),staleTime:0}).then(M=>{if(!g){if(!M||!td(M,p)){let A=d.current.find(k=>k.path===R||k.id===M?.id);A&&E(A.path);return}a(A=>{let k=A.identity===i?A:{identity:i,upserts:{},deleted:new Set},U=new Set(k.deleted);return U.delete(R),{identity:i,upserts:{...k.upserts,[R]:M},deleted:U}})}}).catch(M=>console.warn("[useIncrementalItems] item read failed:",M))},250))},Q=re("vfs_change",R=>{if(!R||typeof R.path!="string"&&typeof R.old_path!="string")return;let I=typeof R.path=="string"?R.path:R.old_path,M=d.current.find(k=>k.path===I||k.path===R.old_path||R.item_id&&k.id===R.item_id),A=!!M;if(!(!pe(I,p.scope)&&!pe(R.old_path,p.scope)&&!A)&&!(R.item_type&&R.item_type!==p.type&&!A)&&!(p.parent_id&&R.parent_id&&R.parent_id!==p.parent_id&&!A)){if(M&&(I!==M.path||R.old_path&&R.old_path!==I||R.parent_id&&R.parent_id!==M.parent_id||R.item_type&&R.item_type!==p.type)){E(M.path);return}if(!M&&R.old_path&&R.old_path!==I&&pe(I,p.scope)){y++,S(I);return}if(R.action==="insert")y++,S(I);else if(R.action==="move")y++,S(I);else if(R.action==="update"){if(!f.current?.(R,d.current))return;y++,S(I)}else R.action==="delete"&&E(M?.path??R.old_path??I)}}),K=Jr(R=>{if(R!=="connected"){_&&(h=!0);return}_=!0,h&&(h=!1,T())});return()=>{g=!0,Q(),K(),b.forEach(clearTimeout)}},[s,i]),{...r,allItems:u}}function wc(e){Y();let t=20,n=Jn({queryKey:["vfs",B()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>Zr(e,t,s),initialPageParam:0,getNextPageParam:(s,i,o)=>{if(!(s.items.length<t))return o+s.items.length},enabled:!!e});return{allItems:(0,v.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 Sc(e){return Y(),$({queryKey:P.edges(e),queryFn:()=>ts(e),enabled:!!e})}function ms(e){return Y(),$({queryKey:P.types(e),queryFn:()=>es(e)})}function Rc(e,t){let n=ms(t);return{...n,data:n.data?.get(e)??void 0}}function xc(e,t){Y();let n=(0,v.useMemo)(()=>t?.arguments,[JSON.stringify(t?.arguments)]),r=t?.mode,s=t?.strategy,i=t?.width;return $({queryKey:[...P.openEnvelope(e,s),i],queryFn:async()=>{let o=await os(e,{mode:r,strategy:s,arguments:n});if(i&&o.render?.props?.url){let a=o.render.props.url,c=a.includes("?")?"&":"?";o.render.props.url=`${a}${c}w=${i}`}return o},enabled:!!e})}var cc={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 Pc(e){let t=ms(e),n=t.data??new Map;return(0,v.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(cc).map(([p,g])=>({key:p,label:g})),getEdgeTypeLabel:p=>cc[p]??p.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function Cc(e,t,n){return Y(),$({queryKey:P.memberFocus(e),queryFn:()=>is(e,t,n),enabled:!!e})}function Tc(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return $({queryKey:P.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>ur(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function Ec(e,t=50,n=0){return $({queryKey:P.itemHistory(e,String(t),String(n)),queryFn:()=>ss(e,t,n),enabled:!!e})}function Ic(e,t=50,n=0){return Y(),$({queryKey:P.recentActivity(e,String(t),String(n)),queryFn:()=>rs(e,t,n),enabled:!!e})}function Ac(){let[e,t]=(0,v.useState)(null),[n,r]=(0,v.useState)(!0),[s,i]=(0,v.useState)(null);return(0,v.useEffect)(()=>{let o=!1;return Xe().then(a=>{if(!o){let c=typeof window<"u"&&window.__FSAOS_CONFIG__||{};t({path:a.scope_path,scope_id:a.scope_id,fractal_id:a.fractal_id,instance_name:a.instance_name,display_name:a.display_name,componentPath:c.componentPath||"",isEmbed:!!c.embedToken}),r(!1)}}).catch(a=>{o||(i(a instanceof Error?a:new Error(String(a))),r(!1))}),()=>{o=!0}},[]),{data:e,loading:n,error:s}}var nd=[];function uc(){if(typeof window>"u")return!1;let e=window.__FSAOS_CONFIG__?.embedToken;return typeof e=="function"||typeof e=="string"&&e.length>0}function rd(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 kc(){let{user:e}=hs(),t=(0,v.useSyncExternalStore)(Yo,ci,ci),n=ht()?.principal_id??null,r=(0,v.useRef)(null),[s,i]=(0,v.useState)(null),[o,a]=(0,v.useState)(null);(0,v.useEffect)(()=>{if(n){a(null);return}if(!e?.id&&!uc()){a(null);return}let b=!1;return Xe().then(T=>{b||T.principal_id||a(new Error("Memberships require an authenticated principal"))}).catch(T=>{b||a(T instanceof Error?T:new Error(String(T)))}),()=>{b=!0}},[n,e?.id,t]);let c=$({queryKey:P.memberships(n??"anonymous"),queryFn:cs,enabled:!!n,staleTime:1e3*60*2}),u=c.data??nd,d=(0,v.useMemo)(()=>u.filter(b=>b.isAccount!==!1&&!b.isSpace),[u]),f=(0,v.useMemo)(()=>{let b=new Set(d.map(E=>E.accountId)),T=E=>!E.subordinateTo||!b.has(E.subordinateTo);return[...d].sort((E,S)=>Number(T(S))-Number(T(E)))},[d]),m=(0,v.useSyncExternalStore)(we,ee,ee),p=(0,v.useMemo)(()=>{let b=ye();return b?u.find(T=>T.accountId===b.id)??null:null},[m,u]),g=(0,v.useMemo)(()=>rd(d),[d]);(0,v.useEffect)(()=>{if(!n){r.current=null;return}if(r.current!==n)if(i(null),f.length===1){let b=f[0];fe()||Mt(Ve(b)),Qt(b.accountId),b.personalSpacePath&&Dt(b.personalSpacePath,T=>{let E=u.find(S=>S.accountId===T);return E?Ve(E):null}).catch(i),r.current=n}else f.length>1&&(r.current=n)},[n,f,u]);let _=(0,v.useCallback)(async b=>{let T=u.find(Q=>Q.path===b);if(!T)throw new Error("Account membership is unavailable");let E=Ve(T);fe()||Mt(E);let S=u.find(Q=>Q.accountId===fe()?.id);if(!S?.personalSpacePath)throw new Error("The home membership has no mount declaration location");await Dt(S.personalSpacePath,Q=>{let K=u.find(R=>R.accountId===Q);return K?Ve(K):null}),await mr(E),i(null),Qt(T.accountId)},[u]),h=(0,v.useCallback)(async b=>{let T=u.find(E=>E.path===b);if(!T)throw new Error("Scope membership is unavailable");await Si(Ve(T))},[u]),y=(!!e?.id||uc())&&!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 Mc(){Y();let e=(0,v.useSyncExternalStore)(Qr,tr,tr),t=(0,v.useMemo)(()=>Te(),[e]),n=ye(),r=(0,v.useMemo)(()=>t.filter(i=>i.kind==="space"&&(n?.kind==="account"||i.id===n?.id)),[t,n]),s=(0,v.useMemo)(()=>r.map(i=>i.id).sort(),[r]);return{mounts:t,selectedSpaces:r,readSpaceIds:s,homeAnchor:fe(),anchor:n,setAnchor:mr,replaceMounts:fs,mount:Si,unmount:sc}}function hs(){let[e,t]=(0,v.useState)(null),[n,r]=(0,v.useState)(null),[s,i]=(0,v.useState)(!0),o=(0,v.useRef)(null);(0,v.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,v.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,v.useCallback)(async m=>W.auth.signUp({email:m.email,password:m.password,options:{data:m.metadata||{}}}),[]),u=(0,v.useCallback)(async()=>{await W.auth.signOut(),mn(),O().clear()},[]),d=(0,v.useCallback)(async m=>{let{error:p}=await W.auth.resetPasswordForEmail(m);if(p)throw p},[]),f=(0,v.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 Oc(e){let[t,n]=(0,v.useState)(null),[r,s]=(0,v.useState)(!1),[i,o]=(0,v.useState)(null);return(0,v.useEffect)(()=>{if(!e){n(null),s(!1);return}if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e))s(!0),x("resolve-asset",{asset_id:e}).then(c=>{c.success&&c.public_url?n({url:c.public_url,id:c.asset_id,name:c.name,mimeType:c.mime_type,width:c.width,height:c.height,sizeBytes:c.size_bytes}):o(new Error(c.error||"Asset not found")),s(!1)}).catch(c=>{o(c instanceof Error?c:new Error(String(c))),s(!1)});else{let u=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";n({url:u+e}),s(!1)}},[e]),{data:t,loading:r,error:i}}var hr={},lc={};ne(()=>{for(let e of Object.keys(hr))delete hr[e]});var Fc=null;function qc(e){Fc=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function sd(e){switch(e){case"react":return typeof window<"u"&&window.React||v.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||Zl;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}:ed;case"@fsaos/gateway":case"@fsaos/react":return typeof window<"u"&&window.__FSAOS_GATEWAY__||Fc||{};case"@fsaos/ui":return typeof window<"u"&&window.__FSAOS_UI__||{};case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}function id(e,t){return e.replace(/^(\s*)(:root|body)(\s*[{,])/gm,(n,r,s,i)=>`${r}.${t}${i}`)}async function od(e,t){if(!lc[e])try{let n=await fetch(e);if(!n.ok)return;let r=await n.text();if(!r.trim()||r.includes("No CSS bundle for this component"))return;t&&!r.includes(`.fsaos-c-${t}`)&&(r=id(r,`fsaos-c-${t}`));let s=document.createElement("style");s.setAttribute("data-fsaos-component-css",e),t&&s.setAttribute("data-fsaos-component-id",t),s.textContent=r,document.head.appendChild(s),lc[e]=s}catch{}}function ad(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)(sd),o=t??i;return o?o.default||o:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function Ti(e){let[t,n]=(0,v.useState)(null),[r,s]=(0,v.useState)(!0),[i,o]=(0,v.useState)(null);return(0,v.useEffect)(()=>{if(!e)return;let a=!1;s(!0),o(null);let u=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{try{let d=1,f=e+"@v1",m=u+e+"/__bundle.js";try{let y=await fetch(u+e+"/__meta",{cache:"no-store"});y.ok&&(d=(await y.json()).version||1,f=e+"@v"+d,m=u+e+"/__bundle.v"+d+".js")}catch{m=u+e+"/__bundle.js?v="+Date.now()}if(a)return;if(hr[f]){n(()=>hr[f]),s(!1);return}let p=await fetch(m);if(!p.ok)throw new Error(`Failed to fetch bundle: ${p.status} ${p.statusText} (${m})`);let g=await p.text();if(a)return;let _=m.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");od(_).catch(()=>{});let h=ad(g);if(!h)throw new Error("Bundle did not export a component. Expected window.__FSAOS_COMPONENT__ (FSAOS build) or a __FSAOS_REGISTER__(Component) call.");if(typeof h!="function")throw new Error(`Bundle export is not a React component (got ${typeof h})`);hr[f]=h,a||(n(()=>h),s(!1))}catch(d){a||(o(d instanceof Error?d:new Error(String(d))),s(!1))}})(),()=>{a=!0}},[e]),{Component:t,loading:r,error:i}}var cd=["--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 Qc(){return{data:(0,v.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let t={},n=getComputedStyle(document.documentElement);return cd.forEach(r=>{t[r]=n.getPropertyValue(r).trim()}),{tokens:t}},[]),loading:!1,error:null}}function Dc(e,t){return{data:{allowed:!0},loading:!1,error:null}}function Uc(e,t){let n={};return(t||[]).forEach(r=>{n[r]=!0}),{data:n,loading:!1,error:null}}var ue=null,En=null,xi=new Set;function ud(){xi.forEach(e=>e())}ne(()=>{ue=null,En=null});async function Nc(e){let t={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null},n=ht()?.principal_id??null;if(n){if(ue&&ue.principalId===n){let{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}=ue;return{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}}return{...t,principalId:n}}let r=e;if(!r){let{data:s}=await W.auth.getSession();r=s?.session?.user?.id}if(!r)return t;if(ue&&ue.authUserId===r){let{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}=ue;return{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}}return En||(En=(async()=>{try{let{data:s,error:i}=await W.from("os_principals").select("id, display_name, created_at, metadata").eq("auth_user_id",r).eq("principal_type","user").maybeSingle();if(i)return console.warn("[SDK] Could not resolve principal:",i.message),t;let o=s?.id??null,a=null;if(o){let{data:u}=await W.from("os_items").select("path").eq("owner_principal_id",o).eq("item_type","principal").eq("is_active",!0).like("path","/root/principals/%"),d=(u??[]).map(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 ue={authUserId:r,...c},c}finally{En=null}})(),En)}async function Kc(e){return(await Nc(e)).principalId}function Lc(){let e=hs(),t=e.user,n=ue?.authUserId===t?.id?ue:null,[r,s]=(0,v.useState)(n),i=(0,v.useRef)(null);return(0,v.useEffect)(()=>{let o=()=>{let a=ue;a&&a.authUserId===t?.id&&s({principalId:a.principalId,displayName:a.displayName,createdAt:a.createdAt,metadata:a.metadata,vfsPath:a.vfsPath})};return xi.add(o),()=>{xi.delete(o)}},[t?.id]),(0,v.useEffect)(()=>{if(!t?.id){s(null),i.current=null;return}i.current===t.id&&r?.principalId!=null||(i.current=t.id,Nc(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 jc(){return{data:null,loading:!1,error:null}}function Vc(e){let{path:t,...n}=e,r=Ti(t),s=r.Component,{loading:i,error:o}=r;return i?(0,v.createElement)("div",{className:"fsaos-loading"},""):o?(0,v.createElement)("div",{className:"fsaos-error"},"Failed to load component"):s?(0,v.createElement)(s,n):null}function $c(e){return e.children}function Wc(e){let t=Y(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=e,o=i!==void 0?i&&!!n:!!n,a=(0,v.useMemo)(()=>P.channelMessages(n??"",r),[n,r,t]),c=L(),u=(0,v.useRef)(null),d=$({queryKey:a,queryFn:()=>as(n,r),enabled:o});(0,v.useEffect)(()=>{if(!s||!o)return;let _=re("vfs_change",()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{Ae(c,a,{exact:!0})},500)},h=>{let y=c.getQueryData(a);return Ri(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,v.useMemo)(()=>m.filter(_=>_.reply_count>0),[m]),breakouts:(0,v.useMemo)(()=>m.filter(_=>_.member_count>0),[m]),isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,refetch:d.refetch}}function Bc(e){Y();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=Jn({queryKey:[...P.channelMessages(t||"",n),"infinite",r,"latest-first",...o?["conversations"]:[],...a?["transcript"]:[]],queryFn:async({pageParam:y})=>lr(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 b=y.messages[y.messages.length-1]?.seq;return b==null?void 0:{after_seq:b}},getNextPageParam:y=>{if(y.messages.length<r)return;let b=y.messages[0]?.seq;return b==null?void 0:{before_seq:b}},enabled:u}),f=(0,v.useMemo)(()=>{if(!d.data?.pages)return[];let y=new Set,b=[];for(let T of d.data.pages)for(let E of T.messages)y.has(E.id)||(y.add(E.id),b.push(E));return b.sort((T,E)=>T.seq-E.seq)},[d.data?.pages]),{messageCards:m,siblingCards:p}=(0,v.useMemo)(()=>{let y=new Map,b=[];if(!d.data?.pages)return{messageCards:y,siblingCards:b};let T=new Set;for(let E of d.data.pages){for(let[S,Q]of E.messageCards)for(let K of Q){if(T.has(K.id))continue;T.add(K.id);let R=y.get(S)||[];R.push(K),y.set(S,R)}for(let S of E.siblingCards)T.has(S.id)||(T.add(S.id),b.push(S))}return{messageCards:y,siblingCards:b}},[d.data?.pages]),g=L(),_=(0,v.useRef)(null),h=(0,v.useMemo)(()=>[...P.channelMessages(t||"",n),"infinite",r,"latest-first",...o?["conversations"]:[],...a?["transcript"]:[]],[t,n,r,o,a]);return(0,v.useEffect)(()=>{if(!s||!t||!u)return;let y=()=>void Ae(g,h,{exact:!0}),b=!1,T=!1,E=!1,S=async()=>{if(o||a){y();return}let R=g.getQueryData(h);if(!R?.pages?.length){y();return}let I=0;for(let M of R.pages)for(let A of M.messages)A.seq>I&&(I=A.seq);if(I===0){y();return}try{let M=await lr(t,{parentMessageId:n,limit:r,after_seq:I});if(M.messages.length===0&&M.siblingCards.length===0){y();return}if(M.messages.length>0){let A=Math.min(...M.messages.map(k=>k.seq));if(A>I+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${I}, minNewSeq=${A}. Triggering full refetch.`),y();return}}g.setQueryData(h,A=>{if(!A)return A;let k=[...A.pages],U=0,F=k[U],le=new Set(F.messages.map(Re=>Re.id)),H=M.messages.filter(Re=>!le.has(Re.id)),qe=[...F.messages,...H].sort((Re,Ps)=>Re.seq-Ps.seq),xs=new Map(F.messageCards);for(let[Re,Ps]of M.messageCards){let Wi=xs.get(Re)||[],ol=new Set(Wi.map(Cs=>Cs.id)),al=Ps.filter(Cs=>!ol.has(Cs.id));xs.set(Re,[...Wi,...al])}let rl=new Set(F.siblingCards.map(Re=>Re.id)),sl=M.siblingCards.filter(Re=>!rl.has(Re.id)),il=[...F.siblingCards,...sl];return k[U]={...F,activityMessages:M.activityMessages??[],messages:qe,messageCards:xs,siblingCards:il},{...A,pages:k}})}catch(M){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",M),y()}},Q=async()=>{if(b){T=!0;return}b=!0;try{do T=!1,await S();while(T&&!E)}finally{b=!1}},K=re("vfs_change",()=>{_.current&&clearTimeout(_.current),_.current=setTimeout(()=>{Q()},500)},R=>(o||a)&&R?.item_type==="message"&&(g.getQueryData(h)?.pages??[]).some(I=>I.messages.some(M=>M.id===R.parent_id))||Ri(R,t,n,g.getQueryData(h)?.pages.flatMap(I=>I.messages)??[]));return()=>{E=!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 Hc=["open","active","strict","hand_raise"];function ld(e){return e==="open"||e==="active"||e==="strict"||e==="hand_raise"?e:e==="on"||e==="auto"?"active":"strict"}function dd(e){if(Array.isArray(e))return e.filter(t=>typeof t=="string")}function dc(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:ld(t.ai_mode),activeAgentIds:dd(t.active_agent_ids),isPrivate:t.is_private||!1,isDm:t.is_dm||!1,messageCount:t.message_count||0,createdAt:e.created_at||"",updatedAt:e.updated_at||"",chatScopePath:r.context_path||"",contextId:e.scope_item_id||"",contextPath:r.context_path||"",contextType:r.context_type||"",contextName:r.context_name||"",contextDisplayName:r.context_name||"",contextPrincipalId:void 0,accountId:e.account_item_id||"",accountPath:"",accountDisplayName:"",memberRole:n.member_role||"member",memberPath:"",modePath:"",autoPilot:t.auto_pilot||!1,isArchived:t.is_archived===!0}}function gs(e={}){let t=Y(),{realtime:n=!0,enabled:r=!0,includeArchived:s=!1}=e,i=L(),o=(0,v.useMemo)(()=>P.channels("all"),[t]),a=$({queryKey:o,queryFn:async()=>((await x("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(dc),enabled:r});return(0,v.useEffect)(()=>{if(!(!n||!r))return oc(i,o,dc)},[n,r,o,i]),{channels:(0,v.useMemo)(()=>(a.data??[]).filter(u=>s||!u.isArchived),[a.data,s]),isLoading:a.isLoading,isFetching:a.isFetching,error:a.error,refetch:a.refetch}}function Gc(e={}){let t=gs(e),n=(0,v.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function zc(e={}){let t=gs(e),n=(0,v.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function Ei(e={}){let t=Y(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=e,o=L(),a=(0,v.useRef)(null),c=(0,v.useMemo)(()=>P.notifications(n,r),[n,r,t]),u=$({queryKey:c,queryFn:async()=>{let f={limit:r};return n==="unread"&&(f.filter="unread"),(await x("get-notifications",f)).notifications||[]},enabled:i});return(0,v.useEffect)(()=>{if(!s||!i)return;let f=["vfs_change","ccm_change"].map(m=>re(m,()=>{a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{o.invalidateQueries({queryKey:c})},2e3)},p=>p.item_type==="notification"&&ps(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 Jc(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:o,error:a,refetch:c}=Ei({filter:"unread",limit:200,realtime:n,enabled:r}),u=(0,v.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,v.useMemo)(()=>{let p=0;return u.forEach(g=>{p+=g}),p},[u]),{dmUnread:f,channelUnread:m}=(0,v.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 Yc(){let e=L();return Z({mutationFn:t=>x("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:P.children(r)})}})}function Xc(){let e=L();return Z({mutationFn:t=>x("update",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.invalidateQueries({queryKey:P.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:P.children(i)})}}})}function Zc(){return Z({mutationFn:e=>x("update-principal",e),onSuccess:(e,t)=>{if(!ue)return;let n=e&&typeof e=="object"&&e.metadata?e.metadata:{...ue.metadata??{},...typeof t.language=="string"?{language:t.language}:{},...typeof t.timezone=="string"?{timezone:t.timezone}:{},..."avatar_file_id"in t?{avatar_file_id:t.avatar_file_id}:{}};ue={...ue,displayName:typeof t.display_name=="string"?t.display_name:ue.displayName,metadata:n},ud()}})}function eu(){let e=L();return Z({mutationFn:t=>x("delete",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.removeQueries({queryKey:P.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:P.children(i)})}}})}function tu(){let e=L();return Z({mutationFn:t=>x("move",t),onSuccess:(t,n)=>{let r=n.path,s=n.new_parent_path;if(r){e.invalidateQueries({queryKey:P.item(r)});let i=r.split("/");i.pop();let o=i.join("/");o&&e.invalidateQueries({queryKey:P.children(o)})}s&&e.invalidateQueries({queryKey:P.children(s)})}})}function nu(){let e=L();return Z({mutationFn:t=>x("link",t),onSuccess:(t,n)=>{let r=n.source_id,s=n.target_id;r&&e.invalidateQueries({queryKey:P.edges(r)}),s&&e.invalidateQueries({queryKey:P.edges(s)})}})}function ru(e,t){let n=L(),{optimistic:r,...s}=t??{};return Z({mutationFn:i=>x(e,i),onMutate:r?async i=>{await n.cancelQueries({queryKey:r.queryKey});let o=n.getQueryData(r.queryKey);return n.setQueryData(r.queryKey,a=>r.update(a,i)),{previous:o}}:void 0,onError:(i,o,a)=>{r&&a?.previous!==void 0&&n.setQueryData(r.queryKey,a.previous),s.onError?.(i)},onSuccess:s.onSuccess,onSettled:r?()=>{n.invalidateQueries({queryKey:r.queryKey})}:void 0})}function su(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,v.useRef)(s),c=(0,v.useRef)(i);(0,v.useEffect)(()=>{a.current=s,c.current=i},[s,i]),(0,v.useEffect)(()=>o?re(r,d=>a.current(d),c.current?d=>c.current(d):void 0):void 0,[r,o])}function iu(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:o=500}=e,a=L(),c=(0,v.useRef)(s);c.current=s;let u=(0,v.useRef)(null),d=$({queryKey:t,queryFn:n,enabled:i});return(0,v.useEffect)(()=>{if(!i)return;let f=re(r,()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{Ae(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 In(e){Y();let t=B(),n=(0,v.useMemo)(()=>e?typeof e=="string"?{path:e}:e:null,[typeof e=="string"?e:JSON.stringify(e)]),r=!!t&&!!n&&!!(n.key||n.path||n.item_id),s=n?.key??n?.path??n?.item_id??"",i=["vfs",t??"__unscoped__","arrangement",s,n?.scope_id??""],o=$({queryKey:i,staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0},queryFn:async()=>{if(!n)return null;let m=await x("resolve-arrangement",{...n,_scope_path:t});if(m?.success===!1)throw new Error(m?.error||"Arrangement could not be loaded");return m??null},enabled:r}),a=o.data??null,c=(0,v.useMemo)(()=>a?.resolved_children??[],[a]),u=a?.resolution_level??null,d=(0,v.useMemo)(()=>{let p=(a?.type_data??null)?.order;return Array.isArray(p)?p:null},[a]),f=(0,v.useCallback)(m=>{if(!d||!m?.length)return m??[];let p=y=>y.id??y.name??"",g=new Map(d.map((y,b)=>[y,b])),_=[],h=[];for(let y of m)(g.has(p(y))?_:h).push(y);return _.sort((y,b)=>g.get(p(y))-g.get(p(b))),[..._,...h]},[d]);return{...o,arrangement:a,resolvedChildren:c,resolutionLevel:u,order:d,sourceScopeId:a?.scope_item_id??null,arrangementQueryKey:i,applyTo:f}}function ou(e){let{origin:t,originField:n,fallbackUrl:r,mintError:s,scopeId:i,scopePath:o}=e,a=Y(),c=ht(),u=i??c?.scope_id??null,d=(0,v.useMemo)(()=>{if(!t)return null;let S="/accounts/",Q=t.indexOf(S);if(Q===-1)return null;let K=t.indexOf("/",Q+S.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-10T14:04:26.983Z */
2
+ "use strict";var __FSAOS_GATEWAY__=(()=>{var ul=Object.create;var qn=Object.defineProperty;var ll=Object.getOwnPropertyDescriptor;var dl=Object.getOwnPropertyNames;var fl=Object.getPrototypeOf,pl=Object.prototype.hasOwnProperty;var Bi=e=>{throw TypeError(e)};var ml=(e,t,n)=>t in e?qn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Qn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),hl=(e,t)=>{for(var n in t)qn(e,n,{get:t[n],enumerable:!0})},Hi=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of dl(t))!pl.call(e,s)&&s!==n&&qn(e,s,{get:()=>t[s],enumerable:!(r=ll(t,s))||r.enumerable});return e};var X=(e,t,n)=>(n=e!=null?ul(fl(e)):{},Hi(t||!e||!e.__esModule?qn(n,"default",{value:e,enumerable:!0}):n,e)),gl=e=>Hi(qn({},"__esModule",{value:!0}),e);var ne=(e,t,n)=>ml(e,typeof t!="symbol"?t+"":t,n),Ts=(e,t,n)=>t.has(e)||Bi("Cannot "+n);var l=(e,t,n)=>(Ts(e,t,"read from private field"),n?n.call(e):t.get(e)),C=(e,t,n)=>t.has(e)?Bi("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),w=(e,t,n,r)=>(Ts(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),F=(e,t,n)=>(Ts(e,t,"access private method"),n);var Dn=(e,t,n,r)=>({set _(s){w(e,t,s,n)},get _(){return l(e,t,r)}});var ce=Qn((Od,Gi)=>{Gi.exports=React});var Ar=Qn((kp,Io)=>{Io.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var jo=Qn((cm,Lo)=>{Lo.exports={createClient:window.supabase.createClient}});var ga=Qn((wm,ha)=>{ha.exports=ReactDOM});var Ru=Qn((hg,xu)=>{xu.exports=ReactDOM});var $i={};hl($i,{CHANNEL_AI_MODES:()=>Hc,ComponentRenderer:()=>Vc,EnforcementDeniedError:()=>rt,FormSubmissionError:()=>Fn,GatewayRequestError:()=>Ae,InteractionTrackingError:()=>Mn,KernelProvider:()=>$c,QueryClientProvider:()=>zn,acceptInvite:()=>qi,answerInput:()=>Ui,assignPersonalSection:()=>tl,auth:()=>Fu,awaitAnchorReady:()=>tr,awaitScopeReady:()=>ea,callTool:()=>ku,cancelQueuedTurn:()=>wu,cancelTurn:()=>vu,clearCachedToken:()=>ti,clearSession:()=>ui,configureGatewayReads:()=>la,createAgent:()=>Di,createItem:()=>Eu,disconnectSSE:()=>vi,disposeVfsRealtimeWs:()=>wi,electHomeAnchor:()=>Ot,emitEvent:()=>Da,fetchChannelMessages:()=>Ha,fetchChannelMessagesPage:()=>dr,fetchChannelMessagesWithCards:()=>cs,fetchEdgesForItem:()=>ns,fetchItemHistory:()=>is,fetchItemVersions:()=>lr,fetchItems:()=>Pn,fetchMemberFocus:()=>os,fetchOpenEnvelope:()=>as,fetchRecentActivity:()=>ss,fetchResolvedItems:()=>Ki,fetchTimelineHistory:()=>Li,fetchTurnQueueEntries:()=>$a,fetchTypeDefinitions:()=>ts,fetchVfsChildren:()=>ur,fetchVfsChildrenPage:()=>es,fetchVfsItem:()=>cr,fetchVfsItemById:()=>Zr,fetchVfsTree:()=>rs,gatewayCall:()=>R,getAccessToken:()=>Ye,getAnchor:()=>mn,getAnchorRef:()=>ye,getAnchorVersion:()=>si,getAssetUrl:()=>Ou,getDefaultSort:()=>Vu,getHomeAnchor:()=>fe,getMountVersion:()=>nr,getMounts:()=>Ee,getPathSubscriptionState:()=>Na,getQueryClient:()=>O,getRequiredFormFields:()=>$u,getScope:()=>H,getScopeVersion:()=>ee,getServerClockOffsetMs:()=>ia,getServerClockSyncedAt:()=>oa,getSessionEntry:()=>ht,hasServerClock:()=>sa,initSession:()=>Xe,initVfsRealtimeWs:()=>Dt,initializeFsaos:()=>_u,initializeWorkspace:()=>bs,interpretSchema:()=>Ni,invalidateAllVfs:()=>Ja,invalidateChannelMessages:()=>Xa,invalidateChildren:()=>Xr,invalidateItem:()=>bi,invalidateOpenEnvelope:()=>Za,invalidatePathAndParent:()=>Ga,invalidateSubtree:()=>za,invalidateTypes:()=>Ya,inviteMember:()=>Fi,isAnchorReady:()=>oi,isChannelPath:()=>pe,isListableItemsFilter:()=>Rn,isScopeReady:()=>Ur,itemsFilterFromQueryFilter:()=>Wa,listChildren:()=>Tu,loadMounts:()=>Ut,mount:()=>qu,mountRealtimeScope:()=>Tn,normalizeItem:()=>_e,onConnectionStateChange:()=>Yr,pathSubscriptionMatches:()=>gi,personalSectionsKey:()=>br,ping:()=>Ua,pushChanges:()=>Au,queryClient:()=>xa,readItem:()=>Cu,refreshQuery:()=>ke,registerCleanup:()=>re,replaceMounts:()=>ps,resetAllSdkState:()=>hn,resolvePrincipalId:()=>Kc,resubscribePath:()=>La,seatMember:()=>Qi,selectMount:()=>hr,serverDeadlinePassed:()=>aa,serverMsUntil:()=>ca,serverNow:()=>Nr,setAnchor:()=>Qr,setCachedToken:()=>Wo,setQueryClient:()=>Sa,setScope:()=>Zo,setupRequireShim:()=>Qu,signal:()=>Mu,startTracking:()=>vs,steerTurn:()=>bu,submitForm:()=>Su,subscribeAnchor:()=>ii,subscribeArtifactStream:()=>ws,subscribeMounts:()=>Dr,subscribeScope:()=>we,subscribeToEvents:()=>se,subscribeToPath:()=>Jr,subscribeToScope:()=>xn,trackAction:()=>hu,trackEvent:()=>Kt,trackPageView:()=>mu,unmountRealtimeScope:()=>ds,updateItem:()=>Iu,uploadFile:()=>Bu,useAcceptInvite:()=>Uu,useAccounts:()=>kc,useAgentTimeline:()=>Xu,useAllChannels:()=>ys,useAnswerInput:()=>Lu,useArrangement:()=>An,useArtifactStream:()=>Yu,useAsset:()=>Oc,useAuth:()=>gs,useChannelMessages:()=>Wc,useChannels:()=>Gc,useChildren:()=>hc,useComponent:()=>Ti,useCreate:()=>Yc,useCreateAgent:()=>Ku,useDelete:()=>eu,useDmChannels:()=>zc,useEdges:()=>Sc,useEventStream:()=>su,useFileUpload:()=>Gu,useIncrementalItems:()=>bc,useInfiniteChannelMessages:()=>Bc,useInfiniteChildren:()=>wc,useInfiniteItems:()=>Ci,useInviteMember:()=>Du,useItem:()=>pc,useItemById:()=>mc,useItemHistory:()=>Ec,useItemVersions:()=>Tc,useItems:()=>vc,useLink:()=>nu,useList:()=>Pi,useMemberFocus:()=>Cc,useMintedAsset:()=>ou,useMounts:()=>Mc,useMove:()=>tu,useMutation:()=>ru,useNotifications:()=>Ei,useOpen:()=>Rc,usePermission:()=>Dc,usePermissions:()=>Uc,usePersonalItemOrder:()=>cu,usePersonalSections:()=>rl,usePinnedItems:()=>el,usePrincipal:()=>Lc,useRealtimeQuery:()=>iu,useRecentActivity:()=>Ic,useResolve:()=>_c,useResolvedItems:()=>Ju,useScope:()=>Ac,useScopeReady:()=>fc,useSearch:()=>yc,useSeatMember:()=>Nu,useTheme:()=>Qc,useTimelineHistory:()=>Zu,useTool:()=>jc,useTree:()=>gc,useType:()=>xc,useTypeHelpers:()=>Pc,useTypes:()=>hs,useUnreadCounts:()=>Jc,useUpdate:()=>Xc,useUpdatePrincipal:()=>Zc,vfsKeys:()=>P,waitForPathReady:()=>Ka});var rt=class e extends Error{constructor(n){let r=n.message||e.fallbackMessage(n);super(r);ne(this,"name","EnforcementDeniedError");ne(this,"deniedBy");ne(this,"ruleKey");ne(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 kn=X(ce(),1);var Pe=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var wt,st,jt,zi,yl=(zi=class extends Pe{constructor(){super();C(this,wt);C(this,st);C(this,jt);w(this,jt,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){l(this,st)||this.setEventListener(l(this,jt))}onUnsubscribe(){var t;this.hasListeners()||((t=l(this,st))==null||t.call(this),w(this,st,void 0))}setEventListener(t){var n;w(this,jt,t),(n=l(this,st))==null||n.call(this),w(this,st,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){l(this,wt)!==t&&(w(this,wt,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof l(this,wt)=="boolean"?l(this,wt):globalThis.document?.visibilityState!=="hidden"}},wt=new WeakMap,st=new WeakMap,jt=new WeakMap,zi),Vt=new yl;var _l={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},it,Es,Ji,vl=(Ji=class{constructor(){C(this,it,_l);C(this,Es,!1)}setTimeoutProvider(e){w(this,it,e)}setTimeout(e,t){return l(this,it).setTimeout(e,t)}clearTimeout(e){l(this,it).clearTimeout(e)}setInterval(e,t){return l(this,it).setInterval(e,t)}clearInterval(e){l(this,it).clearInterval(e)}},it=new WeakMap,Es=new WeakMap,Ji),Qe=new vl;function Yi(e){setTimeout(e,0)}var As=typeof window>"u"||"Deno"in globalThis;function G(){}function eo(e,t){return typeof e=="function"?e(t):e}function Un(e){return typeof e=="number"&&e>=0&&e!==1/0}function wr(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Oe(e,t){return typeof e=="function"?e(t):e}function me(e,t){return typeof e=="function"?e(t):e}function Sr(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:o,stale:a}=e;if(o){if(r){if(t.queryHash!==Nn(o,t.options))return!1}else if(!St(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 xr(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(!St(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function Nn(e,t){return(t?.queryKeyHashFn||De)(e)}function De(e){return JSON.stringify(e,(t,n)=>Is(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function St(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>St(e[n],t[n])):!1}var bl=Object.prototype.hasOwnProperty;function ks(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=Xi(e)&&Xi(t);if(!r&&!(Is(e)&&Is(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:bl.call(e,f))&&u++;continue}if(m===null||p===null||typeof m!="object"||typeof p!="object"){c[f]=p;continue}let g=ks(m,p,n+1);c[f]=g,g===m&&u++}return i===a&&u===i?e:c}function $t(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 Xi(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Is(e){if(!Zi(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Zi(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Zi(e){return Object.prototype.toString.call(e)==="[object Object]"}function to(e){return new Promise(t=>{Qe.setTimeout(t,e)})}function Kn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?ks(e,t):t}function no(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function ro(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Wt=Symbol();function Rr(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Wt?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Bt(e,t){return typeof e=="function"?e(...t):!!e}function so(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=()=>As;return{isServer(){return e()},setIsServer(t){e=t}}})();function Ln(){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 io=Yi;function wl(){let e=[],t=0,n=a=>{a()},r=a=>{a()},s=io,i=a=>{t?e.push(a):s(()=>{n(a)})},o=()=>{let a=e;e=[],a.length&&s(()=>{r(()=>{a.forEach(c=>{n(c)})})})};return{batch:a=>{let c;t++;try{c=a()}finally{t--,t||o()}return c},batchCalls:a=>(...c)=>{i(()=>{a(...c)})},schedule:i,setNotifyFunction:a=>{n=a},setBatchNotifyFunction:a=>{r=a},setScheduler:a=>{s=a}}}var V=wl();var Ht,ot,Gt,oo,Sl=(oo=class extends Pe{constructor(){super();C(this,Ht,!0);C(this,ot);C(this,Gt);w(this,Gt,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){l(this,ot)||this.setEventListener(l(this,Gt))}onUnsubscribe(){var t;this.hasListeners()||((t=l(this,ot))==null||t.call(this),w(this,ot,void 0))}setEventListener(t){var n;w(this,Gt,t),(n=l(this,ot))==null||n.call(this),w(this,ot,t(this.setOnline.bind(this)))}setOnline(t){l(this,Ht)!==t&&(w(this,Ht,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return l(this,Ht)}},Ht=new WeakMap,ot=new WeakMap,Gt=new WeakMap,oo),zt=new Sl;function xl(e){return Math.min(1e3*2**e,3e4)}function Ms(e){return(e??"online")==="online"?zt.isOnline():!0}var Pr=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Cr(e){let t=!1,n=0,r,s=Ln(),i=()=>s.status!=="pending",o=_=>{if(!i()){let h=new Pr(_);m(h),e.onCancel?.(h)}},a=()=>{t=!0},c=()=>{t=!1},u=()=>Vt.isFocused()&&(e.networkMode==="always"||zt.isOnline())&&e.canRun(),d=()=>Ms(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 b=e.retry??(Ue.isServer()?0:3),T=e.retryDelay??xl,E=typeof T=="function"?T(n,y):T,S=b===!0||typeof b=="number"&&n<b||typeof b=="function"&&b(n,y);if(t||!S){m(y);return}n++,e.onFail?.(n,y),to(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:d,start:()=>(d()?g():p().then(g),s)}}var xt,ao,Tr=(ao=class{constructor(){C(this,xt)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Un(this.gcTime)&&w(this,xt,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,xt)!==void 0&&(Qe.clearTimeout(l(this,xt)),w(this,xt,void 0))}},xt=new WeakMap,ao);var Rt,Jt,Ce,Pt,ie,jn,Ct,be,po,$e,lo,fo=(lo=class extends Tr{constructor(t){super();C(this,be);C(this,Rt);C(this,Jt);C(this,Ce);C(this,Pt);C(this,ie);C(this,jn);C(this,Ct);w(this,Ct,!1),w(this,jn,t.defaultOptions),this.setOptions(t.options),this.observers=[],w(this,Pt,t.client),w(this,Ce,l(this,Pt).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,w(this,Rt,uo(this.options)),this.state=t.state??l(this,Rt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return l(this,ie)?.promise}setOptions(t){if(this.options={...l(this,jn),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=uo(this.options);n.data!==void 0&&(this.setState(co(n.data,n.dataUpdatedAt)),w(this,Rt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&l(this,Ce).remove(this)}setData(t,n){let r=Kn(this.state.data,t,this.options);return F(this,be,$e).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){F(this,be,$e).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=l(this,ie)?.promise;return l(this,ie)?.cancel(t),n?n.then(G).catch(G):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return l(this,Rt)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>me(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Wt||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>Oe(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!wr(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),l(this,ie)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),l(this,ie)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),l(this,Ce).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(l(this,ie)&&(l(this,Ct)||F(this,be,po).call(this)?l(this,ie).cancel({revert:!0}):l(this,ie).cancelRetry()),this.scheduleGc()),l(this,Ce).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||F(this,be,$e).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&l(this,ie)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(l(this,ie))return l(this,ie).continueRetry(),l(this,ie).promise}if(t&&this.setOptions(t),!this.options.queryFn){let c=this.observers.find(u=>u.options.queryFn);c&&this.setOptions(c.options)}let r=new AbortController,s=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(w(this,Ct,!0),r.signal)})},i=()=>{let c=Rr(this.options,n),d=(()=>{let f={client:l(this,Pt),queryKey:this.queryKey,meta:this.meta};return s(f),f})();return w(this,Ct,!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,Pt),state:this.state,fetchFn:i};return s(c),c})();this.options.behavior?.onFetch(a,this),w(this,Jt,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&F(this,be,$e).call(this,{type:"fetch",meta:a.fetchOptions?.meta}),w(this,ie,Cr({initialPromise:n?.initialPromise,fn:a.fetchFn,onCancel:c=>{c instanceof Pr&&c.revert&&this.setState({...l(this,Jt),fetchStatus:"idle"}),r.abort()},onFail:(c,u)=>{F(this,be,$e).call(this,{type:"failed",failureCount:c,error:u})},onPause:()=>{F(this,be,$e).call(this,{type:"pause"})},onContinue:()=>{F(this,be,$e).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0}));try{let c=await l(this,ie).start();if(c===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(c),l(this,Ce).config.onSuccess?.(c,this),l(this,Ce).config.onSettled?.(c,this.state.error,this),c}catch(c){if(c instanceof Pr){if(c.silent)return l(this,ie).promise;if(c.revert){if(this.state.data===void 0)throw c;return this.state.data}}throw F(this,be,$e).call(this,{type:"error",error:c}),l(this,Ce).config.onError?.(c,this),l(this,Ce).config.onSettled?.(this.state.data,c,this),c}finally{this.scheduleGc()}}},Rt=new WeakMap,Jt=new WeakMap,Ce=new WeakMap,Pt=new WeakMap,ie=new WeakMap,jn=new WeakMap,Ct=new WeakMap,be=new WeakSet,po=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},$e=function(t){let n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...Os(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 w(this,Jt,t.manual?s:void 0),s;case"error":let i=t.error;return{...r,error:i,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),V.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),l(this,Ce).notify({query:this,type:"updated",action:t})})},lo);function Os(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Ms(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 uo(e){let t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var he,U,$n,de,Tt,Yt,We,at,Wn,Xt,Zt,Et,It,ct,en,j,Vn,Fs,qs,Qs,Ds,Us,Ns,Ks,yo,go,Bn=(go=class extends Pe{constructor(t,n){super();C(this,j);C(this,he);C(this,U);C(this,$n);C(this,de);C(this,Tt);C(this,Yt);C(this,We);C(this,at);C(this,Wn);C(this,Xt);C(this,Zt);C(this,Et);C(this,It);C(this,ct);C(this,en,new Set);this.options=n,w(this,he,t),w(this,at,null),w(this,We,Ln()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(l(this,U).addObserver(this),mo(l(this,U),this.options)?F(this,j,Vn).call(this):this.updateResult(),F(this,j,Ds).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ls(l(this,U),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ls(l(this,U),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,F(this,j,Us).call(this),F(this,j,Ns).call(this),l(this,U).removeObserver(this)}setOptions(t){let n=this.options,r=l(this,U);if(this.options=l(this,he).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof me(this.options.enabled,l(this,U))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");F(this,j,Ks).call(this),l(this,U).setOptions(this.options),n._defaulted&&!$t(this.options,n)&&l(this,he).getQueryCache().notify({type:"observerOptionsUpdated",query:l(this,U),observer:this});let s=this.hasListeners();s&&ho(l(this,U),r,this.options,n)&&F(this,j,Vn).call(this),this.updateResult(),s&&(l(this,U)!==r||me(this.options.enabled,l(this,U))!==me(n.enabled,l(this,U))||Oe(this.options.staleTime,l(this,U))!==Oe(n.staleTime,l(this,U)))&&F(this,j,Fs).call(this);let i=F(this,j,qs).call(this);s&&(l(this,U)!==r||me(this.options.enabled,l(this,U))!==me(n.enabled,l(this,U))||i!==l(this,ct))&&F(this,j,Qs).call(this,i)}getOptimisticResult(t){let n=l(this,he).getQueryCache().build(l(this,he),t),r=this.createResult(n,t);return Pl(this,r)&&(w(this,de,r),w(this,Yt,this.options),w(this,Tt,l(this,U).state)),r}getCurrentResult(){return l(this,de)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&l(this,We).status==="pending"&&l(this,We).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){l(this,en).add(t)}getCurrentQuery(){return l(this,U)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=l(this,he).defaultQueryOptions(t),r=l(this,he).getQueryCache().build(l(this,he),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return F(this,j,Vn).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),l(this,de)))}createResult(t,n){let r=l(this,U),s=this.options,i=l(this,de),o=l(this,Tt),a=l(this,Yt),u=t!==r?t.state:l(this,$n),{state:d}=t,f={...d},m=!1,p;if(n._optimisticResults){let A=this.hasListeners(),k=!A&&mo(t,n),I=A&&ho(t,r,n,s);(k||I)&&(f={...f,...Os(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,Zt)?.state.data,l(this,Zt)):n.placeholderData,A!==void 0&&(h="success",p=Kn(i?.data,A,n),m=!0)}if(n.select&&p!==void 0&&!y)if(i&&p===o?.data&&n.select===l(this,Wn))p=l(this,Xt);else try{w(this,Wn,n.select),p=n.select(p),p=Kn(i?.data,p,n),w(this,Xt,p),w(this,at,null)}catch(A){w(this,at,A)}l(this,at)&&(g=l(this,at),p=l(this,Xt),_=Date.now(),h="error");let b=f.fetchStatus==="fetching",T=h==="pending",E=h==="error",S=T&&b,q=p!==void 0,x={status:h,fetchStatus:f.fetchStatus,isPending:T,isSuccess:h==="success",isError:E,isInitialLoading:S,isLoading:S,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:b,isRefetching:b&&!T,isLoadingError:E&&!q,isPaused:f.fetchStatus==="paused",isPlaceholderData:m,isRefetchError:E&&q,isStale:js(t,n),refetch:this.refetch,promise:l(this,We),isEnabled:me(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let A=x.data!==void 0,k=x.status==="error"&&!A,I=N=>{k?N.reject(x.error):A&&N.resolve(x.data)},M=()=>{let N=w(this,We,x.promise=Ln());I(N)},Q=l(this,We);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=l(this,de),n=this.createResult(l(this,U),this.options);if(w(this,Tt,l(this,U).state),w(this,Yt,this.options),l(this,Tt).data!==void 0&&w(this,Zt,l(this,U)),$t(n,t))return;w(this,de,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!l(this,en).size)return!0;let o=new Set(i??l(this,en));return this.options.throwOnError&&o.add("error"),Object.keys(l(this,de)).some(a=>{let c=a;return l(this,de)[c]!==t[c]&&o.has(c)})};F(this,j,yo).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&F(this,j,Ds).call(this)}},he=new WeakMap,U=new WeakMap,$n=new WeakMap,de=new WeakMap,Tt=new WeakMap,Yt=new WeakMap,We=new WeakMap,at=new WeakMap,Wn=new WeakMap,Xt=new WeakMap,Zt=new WeakMap,Et=new WeakMap,It=new WeakMap,ct=new WeakMap,en=new WeakMap,j=new WeakSet,Vn=function(t){F(this,j,Ks).call(this);let n=l(this,U).fetch(this.options,t);return t?.throwOnError||(n=n.catch(G)),n},Fs=function(){F(this,j,Us).call(this);let t=Oe(this.options.staleTime,l(this,U));if(Ue.isServer()||l(this,de).isStale||!Un(t))return;let r=wr(l(this,de).dataUpdatedAt,t)+1;w(this,Et,Qe.setTimeout(()=>{l(this,de).isStale||this.updateResult()},r))},qs=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(l(this,U)):this.options.refetchInterval)??!1},Qs=function(t){F(this,j,Ns).call(this),w(this,ct,t),!(Ue.isServer()||me(this.options.enabled,l(this,U))===!1||!Un(l(this,ct))||l(this,ct)===0)&&w(this,It,Qe.setInterval(()=>{(this.options.refetchIntervalInBackground||Vt.isFocused())&&F(this,j,Vn).call(this)},l(this,ct)))},Ds=function(){F(this,j,Fs).call(this),F(this,j,Qs).call(this,F(this,j,qs).call(this))},Us=function(){l(this,Et)!==void 0&&(Qe.clearTimeout(l(this,Et)),w(this,Et,void 0))},Ns=function(){l(this,It)!==void 0&&(Qe.clearInterval(l(this,It)),w(this,It,void 0))},Ks=function(){let t=l(this,he).getQueryCache().build(l(this,he),this.options);if(t===l(this,U))return;let n=l(this,U);w(this,U,t),w(this,$n,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},yo=function(t){V.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(l(this,de))}),l(this,he).getQueryCache().notify({query:l(this,U),type:"observerResultsUpdated"})})},go);function Rl(e,t){return me(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function mo(e,t){return Rl(e,t)||e.state.data!==void 0&&Ls(e,t,t.refetchOnMount)}function Ls(e,t,n){if(me(t.enabled,e)!==!1&&Oe(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&js(e,t)}return!1}function ho(e,t,n,r){return(e!==t||me(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&js(e,n)}function js(e,t){return me(t.enabled,e)!==!1&&e.isStaleByTime(Oe(t.staleTime,e))}function Pl(e,t){return!$t(e.getCurrentResult(),t)}function tn(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=>{so(g,()=>t.signal,()=>d=!0)},m=Rr(t.options,t.fetchOptions),p=async(g,_,h)=>{if(d)return Promise.reject();if(_==null&&g.pages.length)return Promise.resolve(g);let b=(()=>{let q={client:t.client,queryKey:t.queryKey,pageParam:_,direction:h?"backward":"forward",meta:t.options.meta};return f(q),q})(),T=await m(b),{maxPages:E}=t.options,S=h?ro:no;return{pages:S(g.pages,T,E),pageParams:S(g.pageParams,_,E)}};if(s&&i.length){let g=s==="backward",_=g?_o:Vs,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:Vs(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 Vs(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 _o(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function vo(e,t){return t?Vs(e,t)!=null:!1}function bo(e,t){return!t||!e.getPreviousPageParam?!1:_o(e,t)!=null}var $s=class extends Bn{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:tn()})}getOptimisticResult(e){return e.behavior=tn(),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:vo(t,n.data),hasPreviousPage:bo(t,n.data),isFetchNextPageError:u,isFetchingNextPage:d,isFetchPreviousPageError:f,isFetchingPreviousPage:m,isRefetchError:a&&!u&&!f,isRefetching:i&&!d&&!m}}};var Hn,Ne,ue,At,Ke,ut,wo,So=(wo=class extends Tr{constructor(t){super();C(this,Ke);C(this,Hn);C(this,Ne);C(this,ue);C(this,At);w(this,Hn,t.client),this.mutationId=t.mutationId,w(this,ue,t.mutationCache),w(this,Ne,[]),this.state=t.state||Ws(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){l(this,Ne).includes(t)||(l(this,Ne).push(t),this.clearGcTimeout(),l(this,ue).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){w(this,Ne,l(this,Ne).filter(n=>n!==t)),this.scheduleGc(),l(this,ue).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){l(this,Ne).length||(this.state.status==="pending"?this.scheduleGc():l(this,ue).remove(this))}continue(){return l(this,At)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{F(this,Ke,ut).call(this,{type:"continue"})},r={client:l(this,Hn),meta:this.options.meta,mutationKey:this.options.mutationKey};w(this,At,Cr({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(o,a)=>{F(this,Ke,ut).call(this,{type:"failed",failureCount:o,error:a})},onPause:()=>{F(this,Ke,ut).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>l(this,ue).canRun(this)}));let s=this.state.status==="pending",i=!l(this,At).canStart();try{if(s)n();else{F(this,Ke,ut).call(this,{type:"pending",variables:t,isPaused:i}),l(this,ue).config.onMutate&&await l(this,ue).config.onMutate(t,this,r);let a=await this.options.onMutate?.(t,r);a!==this.state.context&&F(this,Ke,ut).call(this,{type:"pending",context:a,variables:t,isPaused:i})}let o=await l(this,At).start();return await l(this,ue).config.onSuccess?.(o,t,this.state.context,this,r),await this.options.onSuccess?.(o,t,this.state.context,r),await l(this,ue).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,Ke,ut).call(this,{type:"success",data:o}),o}catch(o){try{await l(this,ue).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,ue).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,Ke,ut).call(this,{type:"error",error:o}),o}finally{l(this,ue).runNext(this)}}},Hn=new WeakMap,Ne=new WeakMap,ue=new WeakMap,At=new WeakMap,Ke=new WeakSet,ut=function(t){let n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),V.batch(()=>{l(this,Ne).forEach(r=>{r.onMutationUpdate(t)}),l(this,ue).notify({mutation:this,type:"updated",action:t})})},wo);function Ws(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Be,Fe,Gn,xo,Ro=(xo=class extends Pe{constructor(t={}){super();C(this,Be);C(this,Fe);C(this,Gn);this.config=t,w(this,Be,new Set),w(this,Fe,new Map),w(this,Gn,0)}build(t,n,r){let s=new So({client:t,mutationCache:this,mutationId:++Dn(this,Gn)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){l(this,Be).add(t);let n=Er(t);if(typeof n=="string"){let r=l(this,Fe).get(n);r?r.push(t):l(this,Fe).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(l(this,Be).delete(t)){let n=Er(t);if(typeof n=="string"){let r=l(this,Fe).get(n);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&l(this,Fe).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=Er(t);if(typeof n=="string"){let s=l(this,Fe).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=Er(t);return typeof n=="string"?l(this,Fe).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){V.batch(()=>{l(this,Be).forEach(t=>{this.notify({type:"removed",mutation:t})}),l(this,Be).clear(),l(this,Fe).clear()})}getAll(){return Array.from(l(this,Be))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>xr(n,r))}findAll(t={}){return this.getAll().filter(n=>xr(t,n))}notify(t){V.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){let t=this.getAll().filter(n=>n.state.isPaused);return V.batch(()=>Promise.all(t.map(n=>n.continue().catch(G))))}},Be=new WeakMap,Fe=new WeakMap,Gn=new WeakMap,xo);function Er(e){return e.options.scope?.id}var He,lt,ge,Ge,ze,Ir,Bs,Po,Hs=(Po=class extends Pe{constructor(t,n){super();C(this,ze);C(this,He);C(this,lt);C(this,ge);C(this,Ge);w(this,He,t),this.setOptions(n),this.bindMethods(),F(this,ze,Ir).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let n=this.options;this.options=l(this,He).defaultMutationOptions(t),$t(this.options,n)||l(this,He).getMutationCache().notify({type:"observerOptionsUpdated",mutation:l(this,ge),observer:this}),n?.mutationKey&&this.options.mutationKey&&De(n.mutationKey)!==De(this.options.mutationKey)?this.reset():l(this,ge)?.state.status==="pending"&&l(this,ge).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||l(this,ge)?.removeObserver(this)}onMutationUpdate(t){F(this,ze,Ir).call(this),F(this,ze,Bs).call(this,t)}getCurrentResult(){return l(this,lt)}reset(){l(this,ge)?.removeObserver(this),w(this,ge,void 0),F(this,ze,Ir).call(this),F(this,ze,Bs).call(this)}mutate(t,n){return w(this,Ge,n),l(this,ge)?.removeObserver(this),w(this,ge,l(this,He).getMutationCache().build(l(this,He),this.options)),l(this,ge).addObserver(this),l(this,ge).execute(t)}},He=new WeakMap,lt=new WeakMap,ge=new WeakMap,Ge=new WeakMap,ze=new WeakSet,Ir=function(){let t=l(this,ge)?.state??Ws();w(this,lt,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},Bs=function(t){V.batch(()=>{if(l(this,Ge)&&this.hasListeners()){let n=l(this,lt).variables,r=l(this,lt).context,s={client:l(this,He),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{l(this,Ge).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{l(this,Ge).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{l(this,Ge).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{l(this,Ge).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(l(this,lt))})})},Po);var Le,Co,To=(Co=class extends Pe{constructor(t={}){super();C(this,Le);this.config=t,w(this,Le,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??Nn(s,n),o=this.get(i);return o||(o=new fo({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(o)),o}add(t){l(this,Le).has(t.queryHash)||(l(this,Le).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=l(this,Le).get(t.queryHash);n&&(t.destroy(),n===t&&l(this,Le).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){V.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return l(this,Le).get(t)}getAll(){return[...l(this,Le).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Sr(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>Sr(t,r)):n}notify(t){V.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){V.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){V.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Le=new WeakMap,Co);var z,dt,ft,nn,rn,pt,sn,on,Eo,Gs=(Eo=class{constructor(e={}){C(this,z);C(this,dt);C(this,ft);C(this,nn);C(this,rn);C(this,pt);C(this,sn);C(this,on);w(this,z,e.queryCache||new To),w(this,dt,e.mutationCache||new Ro),w(this,ft,e.defaultOptions||{}),w(this,nn,new Map),w(this,rn,new Map),w(this,pt,0)}mount(){Dn(this,pt)._++,l(this,pt)===1&&(w(this,sn,Vt.subscribe(async e=>{e&&(await this.resumePausedMutations(),l(this,z).onFocus())})),w(this,on,zt.subscribe(async e=>{e&&(await this.resumePausedMutations(),l(this,z).onOnline())})))}unmount(){var e,t;Dn(this,pt)._--,l(this,pt)===0&&((e=l(this,sn))==null||e.call(this),w(this,sn,void 0),(t=l(this,on))==null||t.call(this),w(this,on,void 0))}isFetching(e){return l(this,z).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return l(this,dt).findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return l(this,z).get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=l(this,z).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Oe(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return l(this,z).findAll(e).map(({queryKey:t,state:n})=>{let r=n.data;return[t,r]})}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=l(this,z).get(r.queryHash)?.state.data,o=eo(t,i);if(o!==void 0)return l(this,z).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return V.batch(()=>l(this,z).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return l(this,z).get(t.queryHash)?.state}removeQueries(e){let t=l(this,z);V.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=l(this,z);return V.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=V.batch(()=>l(this,z).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(G).catch(G)}invalidateQueries(e,t={}){return V.batch(()=>(l(this,z).findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=V.batch(()=>l(this,z).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(G)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(G)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=l(this,z).build(this,t);return n.isStaleByTime(Oe(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(G).catch(G)}fetchInfiniteQuery(e){return e.behavior=tn(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(G).catch(G)}ensureInfiniteQueryData(e){return e.behavior=tn(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return zt.isOnline()?l(this,dt).resumePausedMutations():Promise.resolve()}getQueryCache(){return l(this,z)}getMutationCache(){return l(this,dt)}getDefaultOptions(){return l(this,ft)}setDefaultOptions(e){w(this,ft,e)}setQueryDefaults(e,t){l(this,nn).set(De(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...l(this,nn).values()],n={};return t.forEach(r=>{St(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){l(this,rn).set(De(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...l(this,rn).values()],n={};return t.forEach(r=>{St(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...l(this,ft).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Nn(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===Wt&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...l(this,ft).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){l(this,z).clear(),l(this,dt).clear()}},z=new WeakMap,dt=new WeakMap,ft=new WeakMap,nn=new WeakMap,rn=new WeakMap,pt=new WeakMap,sn=new WeakMap,on=new WeakMap,Eo);var an=X(ce(),1),Ao=X(Ar(),1),zs=an.createContext(void 0),L=e=>{let t=an.useContext(zs);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},zn=({client:e,children:t})=>(an.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,Ao.jsx)(zs.Provider,{value:e,children:t}));var kr=X(ce(),1),ko=kr.createContext(!1),Mo=()=>kr.useContext(ko),Op=ko.Provider;var Jn=X(ce(),1),Cl=X(Ar(),1);function Tl(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var El=Jn.createContext(Tl()),Oo=()=>Jn.useContext(El);var Fo=X(ce(),1);var qo=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?Bt(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Qo=e=>{Fo.useEffect(()=>{e.clearReset()},[e])},Do=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||Bt(n,[e.error,r]));var Uo=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))}},No=(e,t)=>e.isLoading&&e.isFetching&&!t,Ko=(e,t)=>e?.suspense&&t.isPending,Js=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var mt=X(ce(),1);function Mr(e,t,n){let r=Mo(),s=Oo(),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",Uo(o),qo(o,s,a),Qo(s);let c=!i.getQueryCache().get(o.queryHash),[u]=mt.useState(()=>new t(i,o)),d=u.getOptimisticResult(o),f=!r&&e.subscribed!==!1;if(mt.useSyncExternalStore(mt.useCallback(m=>{let p=f?u.subscribe(V.batchCalls(m)):G;return u.updateResult(),p},[u,f]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),mt.useEffect(()=>{u.setOptions(o)},[o,u]),Ko(o,d))throw Js(o,u,s);if(Do({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()&&No(d,r)&&(c?Js(o,u,s):a?.promise)?.catch(G).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?d:u.trackResult(d)}function $(e,t){return Mr(e,Bn,t)}var Je=X(ce(),1);function Z(e,t){let n=L(t),[r]=Je.useState(()=>new Hs(n,e));Je.useEffect(()=>{r.setOptions(e)},[r,e]);let s=Je.useSyncExternalStore(Je.useCallback(o=>r.subscribe(V.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=Je.useCallback((o,a)=>{r.mutate(o,a).catch(G)},[r]);if(s.error&&Bt(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function Yn(e,t){return Mr(e,$s,t)}var Vo=X(jo(),1),Xn=typeof window<"u"&&window.__FSAOS_CONFIG__||{},kt=Array.isArray(Xn.sources)?Xn.sources:[],Il=Xn.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",Al=Xn.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",Te=Xn.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",B=(0,Vo.createClient)(Il,Al,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var Zn=null,Or=0,$o,ei,Fr=!1;$o=new Promise(e=>{ei=e});B.auth.onAuthStateChange((e,t)=>{t?.access_token?(Zn=t.access_token,Or=t.expires_at??Math.floor(Date.now()/1e3)+3600):(Zn=null,Or=0),Fr||(Fr=!0,ei())});setTimeout(()=>{Fr||(Fr=!0,ei())},5e3);function Wo(e,t){Zn=e,Or=t??Math.floor(Date.now()/1e3)+3600}function ti(){Zn=null,Or=0}async function Ye(){let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{};if(e.embedToken){if(typeof e.embedToken=="function")try{return await e.embedToken()??null}catch{return null}return e.embedToken}return await $o,Zn}var dn=null,fn=null,Bo=0,Ys=new Set,ni,er,pn=!1;ni=new Promise(e=>{er=e});function ri(){Bo++,Ys.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function Qr(e){let t=typeof e=="string"?e:e.path,n=dn!==t||fn?.id!==(typeof e=="string"?void 0:e.id);dn=t,fn=typeof e=="string"?null:e,typeof e!="string"&&!Mt.some(r=>r.id===e.id)&&(Mt=[...Mt,e],ai()),pn||(pn=!0,er()),n&&ri()}function mn(){return dn}function ye(){return fn}function si(){return Bo}function ii(e){return Ys.add(e),()=>{Ys.delete(e)}}function tr(){return ni}function oi(){return pn}var qr=null;function Ot(e,t={}){if(qr){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}qr=e,t.activate!==!1&&Qr(e)}function fe(){return qr}var Mt=[],Xs=new Set,Ho=0;function ai(){Ho++,Xs.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function Ee(){return Mt}function nr(){return Ho}function Dr(e){return Xs.add(e),()=>{Xs.delete(e)}}function Go(e,t){let n=JSON.stringify(Mt)!==JSON.stringify(e),r=dn!==t.path||fn?.id!==t.id;Mt=e,dn=t.path,fn=t,pn||(pn=!0,er()),n&&ai(),r&&ri()}var un=null,cn=null,ln=0,Zs=new Set,zo=0;function Jo(){zo++,Zs.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Session listener error:",t)}})}function oe(){return ln}function ci(){return zo}function Yo(e){return Zs.add(e),()=>{Zs.delete(e)}}async function Xe(){if(un)return un;if(cn)return cn;let e=ln;return cn=(async()=>{let t=Ft(),n=await Ye();if(e!==ln)throw new Error("Session changed during initialization");let r={};n&&(r.Authorization=`Bearer ${n}`);let s=await fetch(`${Te}/d/${t}/init`,{method:"GET",headers:r});if(!s.ok)throw new Error(`Session init failed: ${s.status} ${s.statusText}`);let i=await s.json();if(e!==ln)throw new Error("Session changed during initialization");let o=i.entry||i;return un={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},Jo(),un})().catch(t=>{throw e===ln&&(cn=null),t}),cn}function ht(){return un}function ui(){ln++,un=null,cn=null,dn=null,fn=null,qr=null,Mt=[],Jo()}var Xo=[];function re(e){Xo.push(e)}function hn(){ui(),ti(),er(),pn=!1,ni=new Promise(e=>{er=e}),ri(),ai();for(let e of Xo)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function Ft(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var Zo=Qr,H=mn,ee=si,we=ii,ea=tr,Ur=oi;var li=0,ta=!1,na=0;function ra(e){if(typeof e!="string")return;let t=Date.parse(e);Number.isNaN(t)||(li=t-Date.now(),ta=!0,na=Date.now())}function Nr(){return Date.now()+li}function sa(){return ta}function ia(){return li}function oa(){return na}function aa(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Nr()>=t}function ca(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Math.max(0,t-Nr())}var gn,Ie=new Map,qt=[],di=0,fi={foreground:0,normal:1,background:2},Kr=()=>performance.now(),pi=()=>new DOMException("Read cancelled","AbortError");function la(e={}){gn={concurrency:Math.max(1,Math.min(16,Math.floor(e.concurrency??6))),timeoutMs:Math.max(1e3,e.timeoutMs??15e3),onTiming:e.onTiming},jr()}function da(){for(let e of Ie.values()){e.controller.abort();for(let t of e.consumers)t.detach(),t.reject(pi());e.consumers.clear(),e.timer&&clearTimeout(e.timer)}Ie.clear(),qt.length=0}function fa(e,t){return e==="query"?!("materialize"in t):["read","list","search","resolve","resolve-items","get-channel-messages","list-memberships"].includes(e)}function Lr(e){return Array.isArray(e)?`[${e.map(Lr).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)}:${Lr(n)}`).join(",")}}`:JSON.stringify(e)}function pa(e,t,n,r){if(n.signal?.aborted)return Promise.reject(pi());if(!gn)return r(n.signal);let s=Ie.get(e);if(s)fi[n.priority??"normal"]<fi[s.priority]&&(s.priority=n.priority??"normal");else{s={key:e,method:t,priority:n.priority??"normal",queuedAt:Kr(),controller:new AbortController,consumers:new Set,run:r},Ie.set(e,s),qt.push(s);let a=s;s.timer=setTimeout(()=>{a.controller.abort();let c=new Error("The read timed out. Please retry.");c.name="TimeoutError";for(let u of a.consumers)u.detach(),u.reject(c);a.consumers.clear(),Ie.get(a.key)===a&&Ie.delete(a.key),ua(a)},gn.timeoutMs)}let i=s,o=new Promise((a,c)=>{let u=()=>{d.detach(),i.consumers.delete(d),c(pi()),i.consumers.size||(i.controller.abort(),Ie.get(i.key)===i&&Ie.delete(i.key),ua(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 jr(),o}function ua(e){let t=qt.indexOf(e);t>=0&&(qt.splice(t,1),Ie.get(e.key)===e&&Ie.delete(e.key),e.timer&&clearTimeout(e.timer)),jr()}function jr(){if(gn)for(;di<gn.concurrency&&qt.length;){let e=r=>fi[r.priority]-Math.floor((Kr()-r.queuedAt)/2e3);qt.sort((r,s)=>e(r)-e(s)||r.queuedAt-s.queuedAt);let t=qt.shift();if(!t.consumers.size)continue;di++,t.startedAt=Kr();let n="success";Promise.resolve().then(()=>t.run(t.controller.signal)).then(r=>{for(let s of t.consumers)s.detach(),s.resolve(r)},r=>{n=t.controller.signal.aborted?"aborted":"error";for(let s of t.consumers)s.detach(),s.reject(r)}).finally(()=>{t.timer&&clearTimeout(t.timer),t.consumers.clear(),Ie.get(t.key)===t&&Ie.delete(t.key),di--;try{gn?.onTiming?.({method:t.method,priority:t.priority,queueMs:Math.round(t.startedAt-t.queuedAt),requestMs:Math.round(Kr()-t.startedAt),outcome:n})}catch{}jr()})}}re(da);var kl=new Set(["list-memberships","init"]),Ae=class extends Error{constructor(n){let r=typeof n.payload?.error=="string"?n.payload.error.trim():"",s=typeof n.payload?.message=="string"?n.payload.message.trim():"",i=n.responseBody.trim()||`Gateway HTTP error: ${n.status} ${n.statusText}`.trim(),o=r&&s?`${r}: ${s}`:s||r||i;super(o);ne(this,"name","GatewayRequestError");ne(this,"method");ne(this,"status");ne(this,"statusText");ne(this,"payload");ne(this,"responseBody");this.method=n.method,this.status=n.status,this.statusText=n.statusText,this.payload=n.payload,this.responseBody=n.responseBody}};async function R(e,t={},n={}){let r=oe(),s=mn(),i=Ft(),o=`${Te}/d/${i}`,a={"Content-Type":"application/json"},c=await ma(Ye(),n.signal);if(r!==oe())throw new Error("Session changed before gateway request");if(c&&(a.Authorization=`Bearer ${c}`),!kl.has(e)&&!t._scope_path&&await ma(tr(),n.signal),r!==oe())throw new Error("Session changed before gateway request");let u={...t},d=ht();!u.domain_scope_id&&d?.scope_id&&(u.domain_scope_id=d.scope_id);let f=s??mn();!u._scope_path&&f&&(u._scope_path=f);let m=async p=>{if(r!==oe())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!==oe())throw new Error("Session changed during gateway request");let h=null;if(_)try{h=JSON.parse(_)}catch{}if(!g.ok||!h)throw new Ae({method:e,status:g.status,statusText:g.statusText,payload:h,responseBody:_});if(h.success===!1){let y=h.error||"",b=h.denied_by||h.error_type||"";throw b==="rule"||b==="access"||b==="entitlement"||y==="RULE_DENIED"||y==="ACCESS_DENIED"||y==="PERMISSION_DENIED"||y==="ENTITLEMENT_REQUIRED"?new rt(h):new Ae({method:e,status:g.status,statusText:g.statusText,payload:h,responseBody:_})}return h&&h.server_now!==void 0&&ra(h.server_now),h};return fa(e,u)?pa(Lr([r,i,c,e,u]),e,n,m):m(n.signal)}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 v=X(ce(),1),ed=X(ga(),1),td=X(Ar(),1);var ya=new WeakMap;function ke(e,t,n={}){let r=n.exact===!0,s=()=>e.invalidateQueries({queryKey:t,exact:r},{cancelRefetch:!1}),i=e.getQueryCache().findAll({queryKey:t,exact:r,fetchStatus:"fetching"}).flatMap(f=>f.promise?[f.promise]:[]);if(i.length===0)return s();let o=`${r?"=":"^"}${JSON.stringify(t)}`,a=ya.get(e);a||(a=new Map,ya.set(e,a));let c=a.get(o);if(c)return c;let u=a,d=Promise.allSettled(i).then(()=>(u.delete(o),s()));return u.set(o,d),d}function pe(e,t){return typeof e=="string"&&(e===t||e.startsWith(`${t}/`))}var Vr=new WeakMap,_a=e=>e.meta?.arrangementRealtime===!0;function Ze(e,t){let n=e.getQueryCache().find({queryKey:t,exact:!0});if(!n)return;let r=Vr.get(e);r||(r=new Map,Vr.set(e,r));let s=r.get(n.queryHash);s&&clearTimeout(s),r.set(n.queryHash,setTimeout(()=>{r.delete(n.queryHash),e.getQueryCache().get(n.queryHash)===n&&ke(e,t,{exact:!0})},250))}function va(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){if(!_a(n))continue;let r=n.state.data;if(n.meta?.personalSections===!0){(r?.item_path&&[t.path,t.old_path].some(i=>typeof i=="string"&&(i===r.item_path||i.startsWith(r.item_path+"/")))||r?.sections?.some(i=>i.entries?.some(o=>o.target?.id===t.item_id))||!r?.item_id&&t.item_type==="item_arrangement"&&t.name==="sidebar-sections")&&Ze(e,n.queryKey);continue}if(!r?.item_id)continue;let s=(i,o)=>!!(i&&t.item_id===i||o&&(t.path===o||t.old_path===o));(s(r.item_id,r.item_path)||t.parent_id===r.item_id||t.old_parent_id===r.item_id||[t.path,t.old_path].some(i=>typeof i=="string"&&i.slice(0,i.lastIndexOf("/"))===r.item_path)||r.resolved_children?.some(i=>s(i.id,i.symlink_path||i.path)||i.target&&s(i.target.id,i.target.path)))&&Ze(e,n.queryKey)}}function ba(e){for(let t of e.getQueryCache().getAll())_a(t)&&t.state.data!==void 0&&Ze(e,t.queryKey)}function wa(e){Vr.get(e)?.forEach(clearTimeout),Vr.delete(e)}var et=null;re(()=>{et&&(et.cancelQueries({queryKey:["vfs"]}),et.removeQueries({queryKey:["vfs"]}))});function Sa(e){if(et&&et!==e)throw new Error("[fsaos-gateway-sdk] setQueryClient() called after a QueryClient was already in use. Inject the host client before rendering or starting realtime subscriptions.");et=e}function O(){return et||(et=new Gs({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),et}var xa=new Proxy({},{get(e,t,n){let r=O(),s=r[t];return typeof s=="function"?s.bind(r):s}});var $r=new WeakMap;function mi(e){return e.meta?.infiniteItemsRealtime?.filter}function Ml(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 Ol(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 Fl(e,t,n){if(Ml(e,n))return!0;if(t.spaceIds!==void 0&&(!t.spaceIds.length||n.space_item_id!==void 0&&!t.spaceIds.includes(n.space_item_id)&&!t.spaceIds.includes(n.old_space_item_id)))return!1;let r=t.scope,s=typeof r=="string"&&r!=="__unscoped__",i=typeof n.path=="string"||typeof n.old_path=="string";if(s&&i&&!pe(n.path,r)&&!pe(n.old_path,r))return!1;if(n.item_type==="symlink"&&s&&i)return!0;let o=Ol(t);return n.item_type&&o&&!o.has(n.item_type)||t.parent_id&&n.parent_id!==void 0&&n.parent_id!==t.parent_id&&n.old_parent_id!==t.parent_id?!1:i||!!(t.parent_id&&n.parent_id===t.parent_id)}function Ra(e,t){let n=$r.get(e);n||(n=new Map,$r.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||!mi(t))&&ke(e,t.queryKey,{exact:!0})},500))}function Pa(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){let r=mi(n);r&&Fl(n,r,t)&&Ra(e,n)}}function Ca(e){for(let t of e.getQueryCache().getAll())mi(t)&&t.state.data!==void 0&&Ra(e,t)}function Ta(e){$r.get(e)?.forEach(clearTimeout),$r.delete(e)}var Wr=class extends Error{constructor(){super("The server did not confirm the selected-Space listing contract")}};function Ea(e,t){if(!Array.isArray(t)||t.some(n=>typeof n!="string")||JSON.stringify([...new Set(t)].sort())!==JSON.stringify(e))throw new Wr}function gt(e){return!e||e.spaceIds===void 0?e:{...e,spaceIds:[...new Set(e.spaceIds.map(t=>t.toLowerCase()))].sort(),...e.limit!==void 0?{limit:Math.max(1,Math.min(e.limit,500))}:{}}}function yn(e){return e instanceof Wr||e instanceof rt||e instanceof Ae&&(e.payload?.error==="SPACE_SELECTION_UNAVAILABLE"||e.payload?.error==="QUERY_PARAMS_INVALID"||e.status===401||e.status===403)}function ae(){return H()??"__unscoped__"}var P={all:()=>["vfs",ae()],item:e=>["vfs",ae(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",ae(),"children",e],allChildren:()=>["vfs",ae(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",ae(),"search",e,...t??[]],items:(e,t)=>["vfs",ae(),"items",e,JSON.stringify(gt(t??{}))],allItems:()=>["vfs",ae(),"items"],tree:(e,t)=>["vfs",ae(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",ae(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",ae(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",ae(),"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",ae(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",ae(),"channel-messages"],channels:e=>["vfs",ae(),"channels",e??"all"],allChannels:()=>["vfs",ae(),"channels"],notifications:(e,t)=>["vfs",ae(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",ae(),"notifications"],unreadCounts:()=>["vfs",ae(),"unread-counts"],memberships:e=>["memberships",e]};var ql=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function J(...e){ql&&console.log("[WS]",...e)}var D=null,_n=null,bn=null,rr=0,Ql=3e4,Ia=1e4,Sn=!1,Aa=!1,qa=3e4,Dl=qa*2+5e3,Br=0,Hr=null,ka=!1;function Ul(){ir(),Br=Date.now(),Hr=setInterval(()=>{if(D&&D.readyState===WebSocket.OPEN&&Date.now()-Br>Dl){J("ping: no inbound traffic for",Date.now()-Br,"ms \u2014 closing half-open socket");try{D.close(4e3,"liveness timeout")}catch{}return}nt({type:"ping"})},qa)}function ir(){Hr&&(clearInterval(Hr),Hr=null)}function Nl(){typeof document>"u"||(document.hidden?ir():sr()&&(J("Tab visible, reconnecting..."),Qt()))}function Kl(){ka||typeof document>"u"||(document.addEventListener("visibilitychange",Nl),ka=!0)}var Se={};function gi(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return!n||!r?n===r:r===n||r.startsWith(`${n}/`)}var wn=[],tt=new Map,vn=new Map,Me=new Map;function Ll(e){let t=vn.get(e);return t?Array.from(new Set(Array.from(t.values()).flatMap(n=>n.event_types))).sort():[]}function Ma(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):!1}function Oa(e){let t=Ll(e);if(t.length===0)return tt.delete(e),null;let n={scope_id:e,event_types:t};return tt.set(e,n),n}var je=new Map,yt=new Map,hi="disconnected",Gr=[];function zr(e){if(hi!==e){hi=e;for(let t of[...Gr])try{t(e)}catch{}}}function jl(e){je.set(e,"ready");let t=yt.get(e);if(t){yt.delete(e);for(let n of t)n()}}function Vl(){for(let e of je.keys())je.set(e,"disconnected")}function yi(e,t){je.set(e,"pending"),nt({type:"subscribe_path",path:e,event_types:t})}function $l(){return Object.keys(Se).some(t=>Se[t]&&Se[t].length>0)||wn.length>0}function sr(){return tt.size>0||Me.size>0}async function Qt(){if(!sr()){J("ensureConnection: no active subscriptions, skipping");return}if(D&&D.readyState===WebSocket.OPEN){J("ensureConnection: already open");return}if(_n)return J("ensureConnection: connection already in flight, waiting..."),_n;if(D){J("ensureConnection: killing stale WS in state",D.readyState);try{D.close()}catch{}D=null}return Sn=!1,_n=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=Te,n=await Ye();if(!n){J("ensureConnection: no token available, will retry"),Fa();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)+"..."),zr("connecting"),D=new WebSocket(i);let o=D;await new Promise((a,c)=>{if(!D)return c(new Error("WebSocket not created"));let u=setTimeout(()=>{if(D===o){if(J("ensureConnection: TIMEOUT after",Ia,"ms"),D&&D.readyState!==WebSocket.OPEN){try{D.close()}catch{}D=null}c(new Error("WebSocket connection timeout"))}},Ia);o.onopen=()=>{if(D!==o)return;clearTimeout(u),J("ensureConnection: CONNECTED");let d=Aa;Aa=!0,rr=0,zr("connected"),Wl(d),(typeof document>"u"||!document.hidden)&&Ul(),Kl(),a()},o.onmessage=d=>{D===o&&Bl(d.data)},o.onerror=()=>{J("ensureConnection: WS error event")},o.onclose=d=>{clearTimeout(u),D===o&&(J("ensureConnection: WS closed, code:",d.code,"reason:",d.reason),D=null,ir(),Vl(),zr("disconnected"),!Sn&&sr()&&Fa(),c(new Error(`WebSocket closed: ${d.code}`)))}})}catch(e){J("ensureConnection: failed -",e?.message||e)}finally{_n=null}})(),_n}function Fa(){if(bn||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,rr)+Math.random()*1e3,Ql);rr++,J("scheduleReconnect: attempt",rr,"in",Math.round(e),"ms"),bn=setTimeout(()=>{bn=null,sr()&&Qt()},e)}function Wl(e=!1){for(let t of tt.values())J("resubscribeAll: scope",t.scope_id),nt({type:"subscribe",scope_id:t.scope_id,event_types:t.event_types});for(let t of Me.values())J("resubscribeAll: path",t.path),yi(t.path,t.event_types);e&&Qa("reconnect")}function Qa(e){try{let t=O();Ca(t),ba(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 nt(e){D&&D.readyState===WebSocket.OPEN&&D.send(JSON.stringify(e))}function Bl(e){Br=Date.now();try{let t=JSON.parse(e);if(t.type==="subscribed_path"){typeof t.path=="string"&&jl(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"){Qa(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"&&(Pa(O(),r),va(O(),r)),typeof r.path=="string")for(let[s,i]of Object.entries(Se))s!=="*"&&gi(s,r.path)&&i.forEach(o=>o(r));Se["*"]&&Se["*"].forEach(s=>s(r));for(let s of wn)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function _i(){!$l()&&tt.size===0&&Me.size===0&&D&&(Sn=!0,ir(),D.close(),D=null,Sn=!1)}function Jr(e,t){return Se[e]||(Se[e]=[]),Se[e].push(t),Me.has(e)||(Me.set(e,{path:e,event_types:["token_stream"]}),D&&D.readyState===WebSocket.OPEN?yi(e,["token_stream"]):je.set(e,"pending")),Qt(),()=>{let n=Se[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete Se[e],Me.delete(e),je.delete(e),yt.delete(e),nt({type:"unsubscribe_path",path:e}))}_i()}}function se(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return wn.push(...s),sr()&&Qt(),()=>{for(let i of s){let o=wn.indexOf(i);o!==-1&&wn.splice(o,1)}_i()}}function xn(e,t=["vfs_change","ccm_change"]){let n=Symbol(e),r=Array.from(new Set(t)).sort();if(r.length===0)return()=>{};let s=vn.get(e)??new Map,i=tt.get(e)?.event_types;s.set(n,{event_types:r}),vn.set(e,s);let o=Oa(e);if(!o)return()=>{};J("subscribeToScope:",e,o.event_types),D&&D.readyState===WebSocket.OPEN&&!Ma(i,o.event_types)&&nt({type:"subscribe",scope_id:e,event_types:o.event_types}),Qt();let a=!0;return()=>{if(!a)return;a=!1;let c=vn.get(e);if(!c?.delete(n))return;let u=tt.get(e)?.event_types;if(c.size===0)vn.delete(e),tt.delete(e),nt({type:"unsubscribe",scope_id:e});else{let d=Oa(e);d&&D&&D.readyState===WebSocket.OPEN&&!Ma(u,d.event_types)&&nt({type:"subscribe",scope_id:e,event_types:d.event_types})}_i()}}function Da(e,t,n={}){nt({type:"emit",scope_id:e,event_type:t,payload:n})}function vi(){J("disconnectSSE: tearing down"),Ta(O()),wa(O()),Sn=!0,ir(),D&&(D.close(),D=null),bn&&(clearTimeout(bn),bn=null),_n=null,Sn=!1,rr=0;for(let e of Object.keys(Se))delete Se[e];wn.length=0,tt.clear(),vn.clear(),Me.clear(),je.clear(),yt.clear(),zr("disconnected")}function Ua(){nt({type:"ping"})}function Na(e){return Me.has(e)?je.get(e)??"pending":"unsubscribed"}function Ka(e,t=5e3){return Me.has(e)?je.get(e)==="ready"&&D&&D.readyState===WebSocket.OPEN?Promise.resolve(!0):(Qt(),new Promise(n=>{let r=!1,s=yt.get(e)??[],i=()=>{r||(r=!0,clearTimeout(o),n(!0))};s.push(i),yt.set(e,s);let o=setTimeout(()=>{if(r)return;r=!0;let a=yt.get(e);if(a){let c=a.indexOf(i);c!==-1&&a.splice(c,1),a.length===0&&yt.delete(e)}n(!1)},t)})):Promise.resolve(!1)}function La(e){let t=Me.get(e);if(!t){J("resubscribePath: no active subscription for",e);return}D&&D.readyState===WebSocket.OPEN?(J("resubscribePath: re-sending frame for",e),yi(t.path,t.event_types)):(je.set(e,"pending"),Qt())}function Yr(e){Gr.push(e);try{e(hi)}catch{}return()=>{let t=Gr.indexOf(e);t!==-1&&Gr.splice(t,1)}}re(vi);function ja(){return new Date().toISOString()}function Va(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function _e(e){let t=e.path||e.item_path||"",n=t.split("/");n.pop();let r=n.join("/"),s=e.type_data||{};return s.allowed_parent_types&&!s.accepts&&(s.accepts=s.allowed_parent_types),delete s.allowed_parent_types,{id:e.id||e.item_id||"",name:e.name||e.item_name||"",item_type:e.item_type||"unknown",path:t,parent_path:r,is_active:e.is_active!==!1,has_children:e.has_children??!1,created_at:e.created_at||ja(),updated_at:e.updated_at||ja(),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 ar(e){return(e.content?.items||e.items||[]).map(_e)}async function Zr(e){try{let t=await R("read",{id:e});if(t.item_name||t.item_path){let r=_e(t);return r.path&&O().setQueryData(P.item(r.path),r),r}let n=t.item;if(n){let r=_e(n);return r.path&&O().setQueryData(P.item(r.path),r),r}return null}catch{return null}}async function cr(e){try{let t=await R("read",{path:e});if(t.item_name||t.item_path)return _e(t);let n=t.item;return n?_e(n):null}catch{return null}}async function ur(e){try{let t=await R("list",{path:e,limit:200}),n=ar(t);for(let r of n)O().setQueryData(P.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function $a(e,t){let{items:n}=await Pn({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 es(e,t,n){try{let r=await R("list",{path:e,limit:t,offset:n}),s=ar(r);for(let i of s)O().setQueryData(P.item(i.path),i);return{items:s,total_hint:r.total??r.content?.total??s.length}}catch(r){return console.error(`[gateway] Failed to fetch children page of ${e}:`,r),{items:[],total_hint:0}}}async function ts(e){let n=await R("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 ns(e){try{let t=await R("edges",{item_id:e}),n=t.outgoing||[],r=t.incoming||[],s=[];for(let i of n)s.push({id:i.edge_id||Va(),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||Va(),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 rs(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 R("tree",s),o=ar(i);for(let a of o)O().setQueryData(P.item(a.path),a);return o}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function ss(e,t=50,n=0){try{let r=await R("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 lr(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;try{let i=await R("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 is(e,t=50,n=0){return lr(e,{limit:t,offset:n})}async function os(e,t,n){try{let r={scope_id:e};t?.length&&(r.item_types=t),n&&(r.limit=n);let s=await R("member-focus",r),i=ar(s);for(let o of i)O().setQueryData(P.item(o.path),o);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${e}:`,r),[]}}async function as(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 R("open",n);return{item_id:s.item_id,item_path:s.item_path,item_name:s.item_name,item_type:s.item_type,render:s.render,compatible_components:s.compatible_components??[],content:s.content,metadata:s.metadata,instructions:s.instructions}}function Rn(e){return!!e&&(!!e.type||Array.isArray(e.any_of)&&e.any_of.length>0)}function Hl(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 Gl=["catalog","parent_only","internal"];function Wa(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"&&Gl.includes(e.discovery)&&(s.discovery=e.discovery);let i=r(e);if(Object.keys(i.fields).length&&(s.fields=i.fields),Object.keys(i.field_in).length&&(s.field_in=i.field_in),Array.isArray(e.any_of)){let o=[];for(let a of e.any_of){if(!a||typeof a!="object"||Array.isArray(a))continue;let c=a,u={};typeof c.item_type=="string"&&c.item_type&&(u.item_type=c.item_type);let d=r(c);Object.keys(d.fields).length&&(u.fields=d.fields),Object.keys(d.field_in).length&&(u.field_in=d.field_in),Object.keys(u).length&&o.push(u)}o.length&&(s.any_of=o)}return Rn(s)?{...s,...t}:null}async function Pn(e,t={}){if(e=gt(e),e.spaceIds?.length===0)return{items:[],total_hint:0};let n={};e.type&&(n.item_type=e.type),e.scope&&(n.scope_path=e.scope);let r={};if(e.spaceIds!==void 0&&(r.space_ids=e.spaceIds),e.name&&(r.name=e.name),e.tag&&(r.tag=e.tag),e.parent_id&&(r.parent_id=e.parent_id),e.sort_by&&(r.sort_by=e.sort_by),e.sort_dir&&(r.sort_dir=e.sort_dir),e.offset!=null&&(r.offset=e.offset),e.fields)for(let[s,i]of Object.entries(e.fields))r[`field.${s}`]=String(i);if(e.field_in)for(let[s,i]of Object.entries(e.field_in))r[`field_in.${s}`]=i.map(String);e.discovery&&(r.discovery=e.discovery),e.any_of?.length&&(r.any_of=e.any_of.map(Hl)),Object.keys(r).length>0&&(n.filters=r),e.limit!=null&&(n.limit=e.limit);try{let s=await R("query",n,t);e.spaceIds!==void 0&&Ea(e.spaceIds,s.selected_space_ids??s.content?.selected_space_ids);let i=ar(s);for(let o of i)O().setQueryData(P.item(o.path),o);return{items:i,total_hint:s.total??s.content?.total??i.length}}catch(s){if(t.signal?.aborted||s instanceof Error&&s.name==="AbortError"||(console.error(`[gateway] Failed to fetch items of type ${e.type??"(any_of)"}:`,s),t.throwOnError||e.spaceIds!==void 0))throw s;return{items:[],total_hint:0}}}function zl(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 Ba(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:zl(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 or(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 Ha(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await R("get-channel-messages",n),i=s.messages||s.content?.items||s.items||[];return or(i)}catch(n){throw console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),n}}async function cs(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await R("get-channel-messages",n),i=s.messages||[],o=or(i),a=Ba(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:or(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 dr(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 R("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=Ba(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:or(i),activityMessages:or(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 Xr(e){O().invalidateQueries({queryKey:P.children(e)})}function bi(e){O().invalidateQueries({queryKey:P.item(e)})}function Ga(e,t){bi(e),Xr(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&Xr(r)}function za(e){let t=e+"/";O().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function Ja(){O().invalidateQueries({queryKey:P.all()})}function Ya(e){O().invalidateQueries({queryKey:P.types(e)})}function Xa(e,t){e?O().invalidateQueries({queryKey:P.channelMessages(e,t)}):O().invalidateQueries({queryKey:P.allChannelMessages()})}function Za(e,t){e&&t?O().invalidateQueries({queryKey:P.openEnvelope(e,t)}):e?O().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):O().invalidateQueries({queryKey:P.allOpenEnvelopes()})}function Ve(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}async function us(){return((await R("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 Cn=new Map,fr=null,ls=null,_t=new Map,ec=250;function Dt(e){if(fr){Tn(e);return}Tn(e),fr=se("vfs_change",t=>Jl(t)),ls=se("ccm_change",t=>Yl(t))}function Tn(e){if(Cn.has(e))return;let t=xn(e,["vfs_change","ccm_change"]);Cn.set(e,t)}function ds(e){let t=Cn.get(e);t&&(t(),Cn.delete(e))}function wi(){for(let[,e]of Cn)e();Cn.clear(),fr&&(fr(),fr=null),ls&&(ls(),ls=null),_t.forEach(e=>clearTimeout(e)),_t.clear()}re(wi);function Jl(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=_t.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{_t.delete(s),Xl(n,t,e,s)},ec);_t.set(s,o)}function Yl(e){if(!e||typeof e!="object")return;let t=e.source_item_id||e.source_id,n=e.target_item_id||e.target_id;if(!(e.edge_type!=null||t!=null||n!=null)||!t&&!n||e.item_type==="message")return;let s=`ccm:${t??""}:${n??""}`,i=_t.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{_t.delete(s),t&&O().invalidateQueries({queryKey:P.edges(t)}),n&&O().invalidateQueries({queryKey:P.edges(n)})},ec);_t.set(s,o)}function Xl(e,t,n,r){if((e||"").toUpperCase()==="DELETE")O().removeQueries({queryKey:P.item(t)}),O().removeQueries({queryKey:P.children(t)}),O().removeQueries({queryKey:P.tree(t)});else if(n.item_id)try{let i={id:n.item_id,path:n.path,name:n.name,item_type:n.item_type,parent_id:n.parent_id,scope_item_id:n.scope_item_id},o=_e(i);o&&o.id&&O().setQueryData(P.item(t),o)}catch{}O().invalidateQueries({queryKey:P.children(r)}),O().invalidateQueries({predicate:i=>{let o=i.queryKey;if(o[0]!=="vfs"||o[1]!=="tree")return!1;let a=o[2];return t.startsWith(a+"/")||t===a}}),n.item_id&&O().invalidateQueries({queryKey:P.itemById(n.item_id)})}var En=null;re(()=>{En=null});function vt(e){if(e!==En||e.generation!==oe())throw new Error("Workspace session changed")}function Zl(e){return e instanceof Ae&&e.payload?.error==="item_not_found"}function pr(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 mr(e){let t=fe();if(!t)throw new Error("Elect a home account before loading mounts");return[t,...e.filter((n,r)=>n.id!==t.id&&e.findIndex(s=>s.id===n.id)===r)]}function tc(e,t){return JSON.stringify({mounts:e.map(n=>n.id),last_anchor:t.id})}async function nc(e,t,n){vt(e);let r=tc(t,n);if(e.saved===r)return;let s=JSON.parse(r);await R(e.exists?"update":"create",e.exists?{_scope_path:e.scope,path:e.path,type_data:s}:{_scope_path:e.scope,parent_path:e.path.slice(0,e.path.lastIndexOf("/")),name:"mounts",item_type:"file",type_data:s}),vt(e),e.exists=!0,e.saved=r}function rc(e,t){let n=Ee();Dt(fe().id);for(let r of n)e.some(s=>s.id===r.id)||ds(r.id);for(let r of e)Tn(r.id);Go(e,t)}async function Ut(e,t,n={}){let r=fe();if(!r)throw new Error("Elect a home account before loading mounts");let s=`${e}/settings/mounts`;if(En&&En.path!==s)throw new Error("Reset the session before changing the mount declaration owner");let i=En??(En={generation:oe(),path:s,scope:r.path,resolve:t,exists:!1,ready:!1,saved:null,queue:Promise.resolve()});return vt(i),i.loading?i.loading:i.ready?Ee():(i.resolve=t,i.loading=(async()=>{let o=null;try{let d=await R("read",{path:s,_scope_path:i.scope});if(vt(i),o=d.type_data??d.item?.type_data,!o||!Array.isArray(o.mounts)||!o.mounts.every(f=>typeof f=="string"))throw new Error("Invalid saved mount declaration");i.exists=!0}catch(d){if(vt(i),!Zl(d))throw d;i.exists=!1}let a=n.initialAnchor?pr(i,n.initialAnchor):r,c=mr(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=tc(c,u):n.initialAnchor&&await nc(i,c,u),vt(i),i.ready=!0,rc(c,u),c})().finally(()=>{i.loading=void 0}),i.loading)}function fs(e){let t=En;if(!t?.ready)return Promise.reject(new Error("Workspace mounts are not loaded"));let n=t.queue.then(async()=>{vt(t);let{refs:r,anchor:s}=e(t);await nc(t,r,s),vt(t),rc(r,s)});return t.queue=n.catch(()=>{}),n}function Si(e){return fs(t=>({refs:mr([...Ee(),pr(t,e)]),anchor:ye()}))}function sc(e){return fs(()=>{if(e===fe().id)throw new Error("The home account cannot be unmounted");let t=mr(Ee().filter(r=>r.id!==e)),n=t.find(r=>r.id===ye()?.id)??t.find(r=>r.kind==="space")??fe();return{refs:t,anchor:n}})}function hr(e){return fs(t=>{let n=pr(t,e);return{refs:mr([...Ee(),n]),anchor:n}})}function ps(e,t){return fs(n=>{let r=mr(e.map(i=>pr(n,i))),s=pr(n,t);if(!r.some(i=>i.id===s.id))throw new Error("Selected mount must be in the working set");return{refs:r,anchor:s}})}function ms(e){if(typeof e.path!="string")return!1;let t=[...Ee().map(n=>n.path),ye()?.path].filter(n=>!!n);return!t.length&&H()&&t.push(H()),t.some(n=>pe(e.path,n))}function xi(e,t,n,r){if(!["message","card"].includes(e?.item_type)||!pe(e.path,t))return!1;if(!n){let s=e.path.slice(t.length).replace(/^\//,""),i=s?s.split("/").length:0;return e.item_type==="message"?i===1:i===1||i===2}return e.item_id===n||e.parent_id===n?!0:r.some(s=>{if(e.item_id===s.id||e.parent_id===s.id)return!0;let i=s.id===n?s.path:s.parent_message_id===n?s.path.slice(0,s.path.lastIndexOf("/")):void 0;return!!i&&pe(e.path,i)})}var ic=new WeakMap;function oc(e,t,n){let r=ic.get(e);r||(r=new Map,ic.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 E=d;d=!1;let S=[...f],q=new Set(m);m.clear(),f.clear();try{if(E)await ke(e,t,{exact:!0});else{let x=(await Promise.allSettled(S.map(async A=>{let k=e.getQueryCache().find({queryKey:t,exact:!0});if(!k)return;let I=await R("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=_e(I.item??I);if(M.id!==A||M.item_type!=="channel")return;let Q=p().find(xe=>xe.id===A);if(!Q)return;let N=n({...M}),W={...Q,path:N.path,name:N.name,displayName:N.displayName,messageCount:N.messageCount,aiMode:N.aiMode,activeAgentIds:N.activeAgentIds,isPrivate:N.isPrivate,isDm:N.isDm,autoPilot:N.autoPilot,isArchived:N.isArchived,updatedAt:N.updatedAt};q.has(A)&&(Q.name!==W.name||Q.displayName!==W.displayName||Q.path!==W.path)&&(d=!0),e.setQueryData(t,xe=>xe?.map(te=>te.id===A?W:te))}))).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=E=>p().some(S=>S.id===E.item_id||S.path===E.path)?!0:ms(E),y=E=>{if(!h(E))return;let S=String(E.action??"").toLowerCase();if(["insert","delete","rename","move"].includes(S))d=!0;else if(S==="update"){let q=p().find(K=>K.id===E.item_id||K.path===E.path);q&&(f.add(q.id),m.add(q.id))}(d||f.size)&&g()},b=E=>{let S=p().find(q=>q.id===E.parent_id);S&&(f.add(S.id),g())},T=["vfs_change","ccm_change"].flatMap(E=>[se(E,y,S=>S.item_type==="channel"),se(E,b,S=>S.item_type==="message")]);i={users:0,stop:()=>{a=!0,c&&clearTimeout(c),T.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 Y(){return(0,v.useSyncExternalStore)(we,ee,ee)}function fc(){return Y(),Ur()}function pc(e){return Y(),$({queryKey:P.item(e),queryFn:()=>cr(e),enabled:!!e,staleTime:1/0})}function mc(e){return Y(),$({queryKey:P.itemById(e),queryFn:()=>Zr(e),enabled:!!e,staleTime:1/0})}function Pi(e){return Y(),$({queryKey:P.children(e),queryFn:()=>ur(e),enabled:!!e})}function hc(e){let t=Pi(e);return{...t,children:t.data??[]}}function gc(e,t=1){return Y(),$({queryKey:P.tree(e,t),queryFn:()=>rs(e,t),enabled:!!e})}function yc(e,t){return Y(),$({queryKey:P.search(e,t),queryFn:async()=>{let n={query:e};t?.length&&(n.item_types=t);let r=await R("search",n);return(r.content?.items||r.items||r.results||[]).map(_e)},enabled:!!e&&e.length>0})}function _c(e){Y();let t=(0,v.useMemo)(()=>e,[JSON.stringify(e)]);return $({queryKey:["vfs",H()??"__unscoped__","resolve",JSON.stringify(t??{})],queryFn:async()=>await R("resolve",t),enabled:!!t?.query&&t.query.length>0})}function vc(e){Y();let t=gt(e),n=(0,v.useMemo)(()=>t,[JSON.stringify(t)]),r=$({queryKey:P.items(n?.type??"",n),queryFn:({signal:s})=>Pn(n,{signal:s,throwOnError:!0}),enabled:Rn(n),...n?.spaceIds!==void 0?{retry:(s,i)=>!yn(i)&&au(s,i)}:{},select:s=>s.items});return n?.spaceIds!==void 0&&yn(r.error)?{...r,data:void 0}:r}function Ci(e,t={}){let n=Y(),{realtime:r=!1}=t,s=gt(e),i=s?.limit??20,o=(0,v.useMemo)(()=>s,[JSON.stringify(s)]),a=(0,v.useMemo)(()=>["vfs",H()??"__unscoped__","infinite-items",o?.type??"",JSON.stringify(o??{})],[n,o]),c=Yn({queryKey:a,queryFn:async({pageParam:f=0,signal:m})=>Pn({...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:Rn(o),...o?.spaceIds!==void 0?{retry:(f,m)=>!yn(m)&&au(f,m)}:{},staleTime:r?1/0:t.staleTime,meta:r&&o?{infiniteItemsRealtime:{filter:o}}:{}}),u=(0,v.useMemo)(()=>{if(o?.spaceIds!==void 0&&yn(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&&yn(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 ac(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 nd(e,t){if(e.is_active===!1||e.item_type!==t.type||!pe(e.path,t.scope)||t.parent_id&&e.parent_id!==t.parent_id)return!1;let n=e.type_data??{};for(let[r,s]of Object.entries(t.fields??{})){let i=n[r];if(typeof s=="string"&&s.endsWith("*")){if(typeof i!="string"||!i.startsWith(s.slice(0,-1)))return!1}else if(i!==s)return!1}for(let[r,s]of Object.entries(t.field_in??{}))if(!s.includes(n[r]))return!1;return!0}function bc(e,t={}){let n=ac(e),r=Ci(e,n?{realtime:!1,staleTime:3e4}:{realtime:!0}),s=L(),i=JSON.stringify([H(),gt(e)]),[o,a]=(0,v.useState)(()=>({identity:i,upserts:{},deleted:new Set})),c=o.identity===i?o:{identity:i,upserts:{},deleted:new Set},u=(0,v.useMemo)(()=>{if(!n)return r.allItems;let p=Object.values(c.upserts),g=new Set(p.map(b=>b.id)),_=[...p,...r.allItems.filter(b=>!g.has(b.id))].filter(b=>!c.deleted.has(b.path)),h=e.sort_by??"updated_at",y=e.sort_dir==="asc"?1:-1;return _.sort((b,T)=>y*String(b[h]??"").localeCompare(String(T[h]??"")))},[n,r.allItems,c,e?.sort_by,e?.sort_dir]),d=(0,v.useRef)(u);d.current=u;let f=(0,v.useRef)(t.shouldReadUpdate);f.current=t.shouldReadUpdate;let m=(0,v.useRef)(r.refetch);return m.current=r.refetch,(0,v.useEffect)(()=>{if(!ac(e))return;let p=e,g=!1,_=!1,h=!1,y=0,b=new Map,T=()=>{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=b.get("__reconcile__");A&&clearTimeout(A),b.set("__reconcile__",setTimeout(()=>{b.delete("__reconcile__"),T()},250))},S=x=>{let A=b.get(x);A&&clearTimeout(A),b.set(x,setTimeout(()=>{b.delete(x),s.fetchQuery({queryKey:P.item(x),queryFn:()=>cr(x),staleTime:0}).then(k=>{if(!g){if(!k||!nd(k,p)){let I=d.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))},q=se("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),I=!!k;if(!(!pe(A,p.scope)&&!pe(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&&pe(A,p.scope)){y++,S(A);return}if(x.action==="insert")y++,S(A);else if(x.action==="move")y++,S(A);else if(x.action==="update"){if(!f.current?.(x,d.current))return;y++,S(A)}else x.action==="delete"&&E(k?.path??x.old_path??A)}}),K=Yr(x=>{if(x!=="connected"){_&&(h=!0);return}_=!0,h&&(h=!1,T())});return()=>{g=!0,q(),K(),b.forEach(clearTimeout)}},[s,i]),{...r,allItems:u}}function wc(e){Y();let t=20,n=Yn({queryKey:["vfs",H()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>es(e,t,s),initialPageParam:0,getNextPageParam:(s,i,o)=>{if(!(s.items.length<t))return o+s.items.length},enabled:!!e});return{allItems:(0,v.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 Sc(e){return Y(),$({queryKey:P.edges(e),queryFn:()=>ns(e),enabled:!!e})}function hs(e){return Y(),$({queryKey:P.types(e),queryFn:()=>ts(e)})}function xc(e,t){let n=hs(t);return{...n,data:n.data?.get(e)??void 0}}function Rc(e,t){Y();let n=(0,v.useMemo)(()=>t?.arguments,[JSON.stringify(t?.arguments)]),r=t?.mode,s=t?.strategy,i=t?.width;return $({queryKey:[...P.openEnvelope(e,s),i],queryFn:async()=>{let o=await as(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 cc={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 Pc(e){let t=hs(e),n=t.data??new Map;return(0,v.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(cc).map(([p,g])=>({key:p,label:g})),getEdgeTypeLabel:p=>cc[p]??p.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function Cc(e,t,n){return Y(),$({queryKey:P.memberFocus(e),queryFn:()=>os(e,t,n),enabled:!!e})}function Tc(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return $({queryKey:P.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>lr(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function Ec(e,t=50,n=0){return $({queryKey:P.itemHistory(e,String(t),String(n)),queryFn:()=>is(e,t,n),enabled:!!e})}function Ic(e,t=50,n=0){return Y(),$({queryKey:P.recentActivity(e,String(t),String(n)),queryFn:()=>ss(e,t,n),enabled:!!e})}function Ac(){let[e,t]=(0,v.useState)(null),[n,r]=(0,v.useState)(!0),[s,i]=(0,v.useState)(null);return(0,v.useEffect)(()=>{let o=!1;return Xe().then(a=>{if(!o){let c=typeof window<"u"&&window.__FSAOS_CONFIG__||{};t({path:a.scope_path,scope_id:a.scope_id,fractal_id:a.fractal_id,instance_name:a.instance_name,display_name:a.display_name,componentPath:c.componentPath||"",isEmbed:!!c.embedToken}),r(!1)}}).catch(a=>{o||(i(a instanceof Error?a:new Error(String(a))),r(!1))}),()=>{o=!0}},[]),{data:e,loading:n,error:s}}var rd=[];function uc(){if(typeof window>"u")return!1;let e=window.__FSAOS_CONFIG__?.embedToken;return typeof e=="function"||typeof e=="string"&&e.length>0}function sd(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 kc(){let{user:e}=gs(),t=(0,v.useSyncExternalStore)(Yo,ci,ci),n=ht()?.principal_id??null,r=(0,v.useRef)(null),[s,i]=(0,v.useState)(null),[o,a]=(0,v.useState)(null);(0,v.useEffect)(()=>{if(n){a(null);return}if(!e?.id&&!uc()){a(null);return}let b=!1;return Xe().then(T=>{b||T.principal_id||a(new Error("Memberships require an authenticated principal"))}).catch(T=>{b||a(T instanceof Error?T:new Error(String(T)))}),()=>{b=!0}},[n,e?.id,t]);let c=$({queryKey:P.memberships(n??"anonymous"),queryFn:us,enabled:!!n,staleTime:1e3*60*2}),u=c.data??rd,d=(0,v.useMemo)(()=>u.filter(b=>b.isAccount!==!1&&!b.isSpace),[u]),f=(0,v.useMemo)(()=>{let b=new Set(d.map(E=>E.accountId)),T=E=>!E.subordinateTo||!b.has(E.subordinateTo);return[...d].sort((E,S)=>Number(T(S))-Number(T(E)))},[d]),m=(0,v.useSyncExternalStore)(we,ee,ee),p=(0,v.useMemo)(()=>{let b=ye();return b?u.find(T=>T.accountId===b.id)??null:null},[m,u]),g=(0,v.useMemo)(()=>sd(d),[d]);(0,v.useEffect)(()=>{if(!n){r.current=null;return}if(r.current!==n)if(i(null),f.length===1){let b=f[0];fe()||Ot(Ve(b)),Dt(b.accountId),b.personalSpacePath&&Ut(b.personalSpacePath,T=>{let E=u.find(S=>S.accountId===T);return E?Ve(E):null}).catch(i),r.current=n}else f.length>1&&(r.current=n)},[n,f,u]);let _=(0,v.useCallback)(async b=>{let T=u.find(q=>q.path===b);if(!T)throw new Error("Account membership is unavailable");let E=Ve(T);fe()||Ot(E);let S=u.find(q=>q.accountId===fe()?.id);if(!S?.personalSpacePath)throw new Error("The home membership has no mount declaration location");await Ut(S.personalSpacePath,q=>{let K=u.find(x=>x.accountId===q);return K?Ve(K):null}),await hr(E),i(null),Dt(T.accountId)},[u]),h=(0,v.useCallback)(async b=>{let T=u.find(E=>E.path===b);if(!T)throw new Error("Scope membership is unavailable");await Si(Ve(T))},[u]),y=(!!e?.id||uc())&&!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 Mc(){Y();let e=(0,v.useSyncExternalStore)(Dr,nr,nr),t=(0,v.useMemo)(()=>Ee(),[e]),n=ye(),r=(0,v.useMemo)(()=>t.filter(i=>i.kind==="space"&&(n?.kind==="account"||i.id===n?.id)),[t,n]),s=(0,v.useMemo)(()=>r.map(i=>i.id).sort(),[r]);return{mounts:t,selectedSpaces:r,readSpaceIds:s,homeAnchor:fe(),anchor:n,setAnchor:hr,replaceMounts:ps,mount:Si,unmount:sc}}function gs(){let[e,t]=(0,v.useState)(null),[n,r]=(0,v.useState)(null),[s,i]=(0,v.useState)(!0),o=(0,v.useRef)(null);(0,v.useEffect)(()=>{B.auth.getSession().then(({data:p,error:g})=>{if(g){console.warn("[useAuth] getSession error, clearing stale session:",g.message),B.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),B.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:m}}=B.auth.onAuthStateChange((p,g)=>{if(p==="TOKEN_REFRESHED"&&!g){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),B.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,v.useCallback)(async m=>m.provider?B.auth.signInWithOAuth({provider:m.provider,options:m.redirectTo?{redirectTo:m.redirectTo}:{redirectTo:window.location.href}}):B.auth.signInWithPassword({email:m.email,password:m.password}),[]),c=(0,v.useCallback)(async m=>B.auth.signUp({email:m.email,password:m.password,options:{data:m.metadata||{}}}),[]),u=(0,v.useCallback)(async()=>{await B.auth.signOut(),hn(),O().clear()},[]),d=(0,v.useCallback)(async m=>{let{error:p}=await B.auth.resetPasswordForEmail(m);if(p)throw p},[]),f=(0,v.useCallback)(async(m,p)=>{let{error:g}=await B.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 Oc(e){let[t,n]=(0,v.useState)(null),[r,s]=(0,v.useState)(!1),[i,o]=(0,v.useState)(null);return(0,v.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),R("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 gr={},lc={};re(()=>{for(let e of Object.keys(gr))delete gr[e]});var Fc=null;function qc(e){Fc=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function id(e){switch(e){case"react":return typeof window<"u"&&window.React||v.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||ed;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}:td;case"@fsaos/gateway":case"@fsaos/react":return typeof window<"u"&&window.__FSAOS_GATEWAY__||Fc||{};case"@fsaos/ui":return typeof window<"u"&&window.__FSAOS_UI__||{};case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}function od(e,t){return e.replace(/^(\s*)(:root|body)(\s*[{,])/gm,(n,r,s,i)=>`${r}.${t}${i}`)}async function ad(e,t){if(!lc[e])try{let n=await fetch(e);if(!n.ok)return;let r=await n.text();if(!r.trim()||r.includes("No CSS bundle for this component"))return;t&&!r.includes(`.fsaos-c-${t}`)&&(r=od(r,`fsaos-c-${t}`));let s=document.createElement("style");s.setAttribute("data-fsaos-component-css",e),t&&s.setAttribute("data-fsaos-component-id",t),s.textContent=r,document.head.appendChild(s),lc[e]=s}catch{}}function cd(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)(id),o=t??i;return o?o.default||o:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function Ti(e){let[t,n]=(0,v.useState)(null),[r,s]=(0,v.useState)(!0),[i,o]=(0,v.useState)(null);return(0,v.useEffect)(()=>{if(!e)return;let a=!1;s(!0),o(null);let u=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{try{let d=1,f=e+"@v1",m=u+e+"/__bundle.js";try{let y=await fetch(u+e+"/__meta",{cache:"no-store"});y.ok&&(d=(await y.json()).version||1,f=e+"@v"+d,m=u+e+"/__bundle.v"+d+".js")}catch{m=u+e+"/__bundle.js?v="+Date.now()}if(a)return;if(gr[f]){n(()=>gr[f]),s(!1);return}let p=await fetch(m);if(!p.ok)throw new Error(`Failed to fetch bundle: ${p.status} ${p.statusText} (${m})`);let g=await p.text();if(a)return;let _=m.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");ad(_).catch(()=>{});let h=cd(g);if(!h)throw new Error("Bundle did not export a component. Expected window.__FSAOS_COMPONENT__ (FSAOS build) or a __FSAOS_REGISTER__(Component) call.");if(typeof h!="function")throw new Error(`Bundle export is not a React component (got ${typeof h})`);gr[f]=h,a||(n(()=>h),s(!1))}catch(d){a||(o(d instanceof Error?d:new Error(String(d))),s(!1))}})(),()=>{a=!0}},[e]),{Component:t,loading:r,error:i}}var ud=["--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 Qc(){return{data:(0,v.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let t={},n=getComputedStyle(document.documentElement);return ud.forEach(r=>{t[r]=n.getPropertyValue(r).trim()}),{tokens:t}},[]),loading:!1,error:null}}function Dc(e,t){return{data:{allowed:!0},loading:!1,error:null}}function Uc(e,t){let n={};return(t||[]).forEach(r=>{n[r]=!0}),{data:n,loading:!1,error:null}}var le=null,In=null,Ri=new Set;function ld(){Ri.forEach(e=>e())}re(()=>{le=null,In=null});async function Nc(e){let t={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null},n=ht()?.principal_id??null;if(n){if(le&&le.principalId===n){let{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}=le;return{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}}return{...t,principalId:n}}let r=e;if(!r){let{data:s}=await B.auth.getSession();r=s?.session?.user?.id}if(!r)return t;if(le&&le.authUserId===r){let{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}=le;return{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}}return In||(In=(async()=>{try{let{data:s,error:i}=await B.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 B.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 le={authUserId:r,...c},c}finally{In=null}})(),In)}async function Kc(e){return(await Nc(e)).principalId}function Lc(){let e=gs(),t=e.user,n=le?.authUserId===t?.id?le:null,[r,s]=(0,v.useState)(n),i=(0,v.useRef)(null);return(0,v.useEffect)(()=>{let o=()=>{let a=le;a&&a.authUserId===t?.id&&s({principalId:a.principalId,displayName:a.displayName,createdAt:a.createdAt,metadata:a.metadata,vfsPath:a.vfsPath})};return Ri.add(o),()=>{Ri.delete(o)}},[t?.id]),(0,v.useEffect)(()=>{if(!t?.id){s(null),i.current=null;return}i.current===t.id&&r?.principalId!=null||(i.current=t.id,Nc(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 jc(){return{data:null,loading:!1,error:null}}function Vc(e){let{path:t,...n}=e,r=Ti(t),s=r.Component,{loading:i,error:o}=r;return i?(0,v.createElement)("div",{className:"fsaos-loading"},""):o?(0,v.createElement)("div",{className:"fsaos-error"},"Failed to load component"):s?(0,v.createElement)(s,n):null}function $c(e){return e.children}function Wc(e){let t=Y(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=e,o=i!==void 0?i&&!!n:!!n,a=(0,v.useMemo)(()=>P.channelMessages(n??"",r),[n,r,t]),c=L(),u=(0,v.useRef)(null),d=$({queryKey:a,queryFn:()=>cs(n,r),enabled:o});(0,v.useEffect)(()=>{if(!s||!o)return;let _=se("vfs_change",()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{ke(c,a,{exact:!0})},500)},h=>{let y=c.getQueryData(a);return xi(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,v.useMemo)(()=>m.filter(_=>_.reply_count>0),[m]),breakouts:(0,v.useMemo)(()=>m.filter(_=>_.member_count>0),[m]),isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,refetch:d.refetch}}function Bc(e){Y();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=Yn({queryKey:[...P.channelMessages(t||"",n),"infinite",r,"latest-first",...o?["conversations"]:[],...a?["transcript"]:[]],queryFn:async({pageParam:y})=>dr(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 b=y.messages[y.messages.length-1]?.seq;return b==null?void 0:{after_seq:b}},getNextPageParam:y=>{if(y.messages.length<r)return;let b=y.messages[0]?.seq;return b==null?void 0:{before_seq:b}},enabled:u}),f=(0,v.useMemo)(()=>{if(!d.data?.pages)return[];let y=new Set,b=[];for(let T of d.data.pages)for(let E of T.messages)y.has(E.id)||(y.add(E.id),b.push(E));return b.sort((T,E)=>T.seq-E.seq)},[d.data?.pages]),{messageCards:m,siblingCards:p}=(0,v.useMemo)(()=>{let y=new Map,b=[];if(!d.data?.pages)return{messageCards:y,siblingCards:b};let T=new Set;for(let E of d.data.pages){for(let[S,q]of E.messageCards)for(let K of q){if(T.has(K.id))continue;T.add(K.id);let x=y.get(S)||[];x.push(K),y.set(S,x)}for(let S of E.siblingCards)T.has(S.id)||(T.add(S.id),b.push(S))}return{messageCards:y,siblingCards:b}},[d.data?.pages]),g=L(),_=(0,v.useRef)(null),h=(0,v.useMemo)(()=>[...P.channelMessages(t||"",n),"infinite",r,"latest-first",...o?["conversations"]:[],...a?["transcript"]:[]],[t,n,r,o,a]);return(0,v.useEffect)(()=>{if(!s||!t||!u)return;let y=()=>void ke(g,h,{exact:!0}),b=!1,T=!1,E=!1,S=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 dr(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,N=M[Q],W=new Set(N.messages.map(Re=>Re.id)),xe=k.messages.filter(Re=>!W.has(Re.id)),te=[...N.messages,...xe].sort((Re,Ps)=>Re.seq-Ps.seq),bt=new Map(N.messageCards);for(let[Re,Ps]of k.messageCards){let Wi=bt.get(Re)||[],al=new Set(Wi.map(Cs=>Cs.id)),cl=Ps.filter(Cs=>!al.has(Cs.id));bt.set(Re,[...Wi,...cl])}let sl=new Set(N.siblingCards.map(Re=>Re.id)),il=k.siblingCards.filter(Re=>!sl.has(Re.id)),ol=[...N.siblingCards,...il];return M[Q]={...N,activityMessages:k.activityMessages??[],messages:te,messageCards:bt,siblingCards:ol},{...I,pages:M}})}catch(k){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",k),y()}},q=async()=>{if(b){T=!0;return}b=!0;try{do T=!1,await S();while(T&&!E)}finally{b=!1}},K=se("vfs_change",()=>{_.current&&clearTimeout(_.current),_.current=setTimeout(()=>{q()},500)},x=>(o||a)&&x?.item_type==="message"&&(g.getQueryData(h)?.pages??[]).some(A=>A.messages.some(k=>k.id===x.parent_id))||xi(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: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 Hc=["open","active","strict","hand_raise"];function dd(e){return e==="open"||e==="active"||e==="strict"||e==="hand_raise"?e:e==="on"||e==="auto"?"active":"strict"}function fd(e){if(Array.isArray(e))return e.filter(t=>typeof t=="string")}function dc(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:dd(t.ai_mode),activeAgentIds:fd(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 ys(e={}){let t=Y(),{realtime:n=!0,enabled:r=!0,includeArchived:s=!1}=e,i=L(),o=(0,v.useMemo)(()=>P.channels("all"),[t]),a=$({queryKey:o,queryFn:async()=>((await R("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(dc),enabled:r});return(0,v.useEffect)(()=>{if(!(!n||!r))return oc(i,o,dc)},[n,r,o,i]),{channels:(0,v.useMemo)(()=>(a.data??[]).filter(u=>s||!u.isArchived),[a.data,s]),isLoading:a.isLoading,isFetching:a.isFetching,error:a.error,refetch:a.refetch}}function Gc(e={}){let t=ys(e),n=(0,v.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function zc(e={}){let t=ys(e),n=(0,v.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function Ei(e={}){let t=Y(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=e,o=L(),a=(0,v.useRef)(null),c=(0,v.useMemo)(()=>P.notifications(n,r),[n,r,t]),u=$({queryKey:c,queryFn:async()=>{let f={limit:r};return n==="unread"&&(f.filter="unread"),(await R("get-notifications",f)).notifications||[]},enabled:i});return(0,v.useEffect)(()=>{if(!s||!i)return;let f=["vfs_change","ccm_change"].map(m=>se(m,()=>{a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{o.invalidateQueries({queryKey:c})},2e3)},p=>p.item_type==="notification"&&ms(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 Jc(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:o,error:a,refetch:c}=Ei({filter:"unread",limit:200,realtime:n,enabled:r}),u=(0,v.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,v.useMemo)(()=>{let p=0;return u.forEach(g=>{p+=g}),p},[u]),{dmUnread:f,channelUnread:m}=(0,v.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 Yc(){let e=L();return Z({mutationFn:t=>R("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:P.children(r)})}})}function Xc(){let e=L();return Z({mutationFn:t=>R("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 Zc(){return Z({mutationFn:e=>R("update-principal",e),onSuccess:(e,t)=>{if(!le)return;let n=e&&typeof e=="object"&&e.metadata?e.metadata:{...le.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}:{}};le={...le,displayName:typeof t.display_name=="string"?t.display_name:le.displayName,metadata:n},ld()}})}function eu(){let e=L();return Z({mutationFn:t=>R("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 tu(){let e=L();return Z({mutationFn:t=>R("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 nu(){let e=L();return Z({mutationFn:t=>R("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 ru(e,t){let n=L(),{optimistic:r,...s}=t??{};return Z({mutationFn:i=>R(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 su(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,v.useRef)(s),c=(0,v.useRef)(i);(0,v.useEffect)(()=>{a.current=s,c.current=i},[s,i]),(0,v.useEffect)(()=>o?se(r,d=>a.current(d),c.current?d=>c.current(d):void 0):void 0,[r,o])}function iu(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:o=500}=e,a=L(),c=(0,v.useRef)(s);c.current=s;let u=(0,v.useRef)(null),d=$({queryKey:t,queryFn:n,enabled:i});return(0,v.useEffect)(()=>{if(!i)return;let f=se(r,()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{ke(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 An(e){Y();let t=H(),n=(0,v.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 R("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,v.useMemo)(()=>a?.resolved_children??[],[a]),u=a?.resolution_level??null,d=(0,v.useMemo)(()=>{let p=(a?.type_data??null)?.order;return Array.isArray(p)?p:null},[a]),f=(0,v.useCallback)(m=>{if(!d||!m?.length)return m??[];let p=y=>y.id??y.name??"",g=new Map(d.map((y,b)=>[y,b])),_=[],h=[];for(let y of m)(g.has(p(y))?_:h).push(y);return _.sort((y,b)=>g.get(p(y))-g.get(p(b))),[..._,...h]},[d]);return{...o,arrangement:a,resolvedChildren:c,resolutionLevel:u,order:d,sourceScopeId:a?.scope_item_id??null,arrangementQueryKey:i,applyTo:f}}function ou(e){let{origin:t,originField:n,fallbackUrl:r,mintError:s,scopeId:i,scopePath:o}=e,a=Y(),c=ht(),u=i??c?.scope_id??null,d=(0,v.useMemo)(()=>{if(!t)return null;let S="/accounts/",q=t.indexOf(S);if(q===-1)return null;let K=t.indexOf("/",q+S.length);return K===-1?t:t.slice(0,K)},[t]),f=o??d??c?.scope_path??null,m=n?.trim()||null,p=`${a}
4
4
  ${u??""}
5
5
  ${f??""}
6
6
  ${m??""}
7
- ${t??""}`,[g,_]=(0,v.useState)(null),h=(0,v.useRef)({key:p,found:null,earlyContentPaths:new Set}),y=g?.key===p?g:null;(0,v.useLayoutEffect)(()=>{h.current={key:p,found:y,earlyContentPaths:new Set}},[p]);let b=$({queryKey:["vfs",f??"__unscoped__","minted-asset",m??"",t??""],queryFn:async()=>{let S=await x("query",{scope_path:f,filters:{[`field.${m}`]:t},limit:1}),Q=S.content?.items??S.items??[],K=Q[0]?_e(Q[0]):null;if(!K)return null;let I=(await cr(K.path)).some(M=>M.item_type==="file"&&!!M.type_data?.file_ref);return{asset:K,hasBytes:I}},enabled:!!(t&&f&&m&&!s),refetchInterval:S=>h.current.key===p&&h.current.found?.hasBytes||S.state.data?.hasBytes?!1:1500});(0,v.useEffect)(()=>{let S=b.data;if(!S||h.current.key!==p)return;let Q=h.current.found,K={key:p,itemId:S.asset.id,itemPath:S.asset.path,displayName:typeof S.asset.type_data?.display_name=="string"?S.asset.type_data.display_name:S.asset.name,hasBytes:S.hasBytes||!!(Q?.itemId===S.asset.id&&Q.hasBytes)};h.current.found=K,_(K)},[b.data,p]);let T=!!(t&&u)&&!s&&!y?.hasBytes;return(0,v.useEffect)(()=>{if(!(!T||!u))return Sn(u,["asset.materialized","content.written"])},[T,u]),(0,v.useEffect)(()=>{if(!T||!t||!u)return;let S=p,Q=A=>A?.payload??A,K=A=>{let U=Q(A)?.scope_id??A?.scope_id;return typeof U=="string"?U:void 0},R=A=>{let U=Q(A)?.item_path??A?.item_path;return typeof U=="string"&&U?U:void 0},I=(A,k)=>{let U=k.replace(/\/+$/,"");return A===U||A.startsWith(`${U}/`)},M=[re("asset.materialized",A=>{if(h.current.key!==S)return;let k=Q(A);if(typeof k?.item_id!="string"||!k.item_id)return;let U=h.current.found,F=typeof k.item_path=="string"?k.item_path:void 0,le=!!k.has_bytes||!!(F&&Array.from(h.current.earlyContentPaths).some(qe=>I(qe,F)))||!!(U&&U.itemId===k.item_id&&U.hasBytes),H={key:S,itemId:k.item_id,itemPath:F,displayName:typeof k.display_name=="string"?k.display_name:void 0,hasBytes:le};h.current.found=H,_(H)},A=>{let k=K(A);return(!k||k===u)&&Q(A)?.origin===t}),re("content.written",A=>{if(h.current.key!==S)return;let k=R(A);if(!k)return;let U=h.current.found;if(!U?.itemPath||!I(k,U.itemPath)){if(h.current.earlyContentPaths.add(k),h.current.earlyContentPaths.size>128){let le=h.current.earlyContentPaths.values().next().value;le&&h.current.earlyContentPaths.delete(le)}return}if(U.hasBytes)return;let F={...U,hasBytes:!0};h.current.found=F,_(F)},A=>{let k=K(A);return(!k||k===u)&&!!R(A)})];return()=>M.forEach(A=>A())},[T,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 au(e,t){let n=O().getDefaultOptions().queries?.retry??1;return typeof n=="function"?n(e,t):n===!0||typeof n=="number"&&e<n}function cu(e,t){let n=(0,An.useSyncExternalStore)(we,ee,ee),r=ye(),s=B(),i=r?.kind==="space",o=In(i&&s?{key:e,scope_id:r.id}:null),a=(0,An.useMemo)(()=>{let 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,b)=>h(b)-h(y)),[..._,...p.filter(y=>g.has(y.id))]},[e,t,o.applyTo,o.order]),c=L(),u=(0,An.useRef)(!1),d=!!(i&&!o.error&&o.arrangement?.item_id&&o.resolutionLevel==="member"&&o.arrangement.write_target_id===o.arrangement.item_id),f=Z({mutationFn:async p=>{let g=await x("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,_)=>Ze(c,_.queryKey)});async function m(p){if(!d||!s||n!==ee()||B()!==s)throw new Error("Personal order is not available in this Space");if(u.current)throw new Error("An order change is already being saved");let g=t.map(S=>S.id);if(p.length!==g.length||new Set(p).size!==g.length||g.some(S=>!p.includes(S)))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(S=>S.id);if(p.every((S,Q)=>h[Q]===S))return;let y=new Set(g),b=0,E=[...(o.order??[]).map(S=>y.has(S)?p[b++]:S),...p.slice(b)];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: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 Ii=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,fd=/^[A-Za-z_:][A-Za-z0-9_:.-]{0,127}$/,uu=new Map,lu=new Map,kn=class extends Error{constructor(n,r,s,i){super(n);te(this,"code");te(this,"status");te(this,"eventId");this.name="InteractionTrackingError",this.code=r,this.status=s,this.eventId=i}};function Ut(e){let t=e?At.find(n=>n.id===e):At.find(n=>n.default===!0)??(At.length===1?At[0]:void 0);if(!t)throw new TypeError("No unambiguous source is declared for this release");if(!t.id||!Number.isInteger(t.version)||t.version<1)throw new TypeError("The release source declaration is invalid");return t}function ys(e,t){let n=t.adapters?.find(r=>r.type===e);if(!n)throw new TypeError(`The source does not declare a ${e} adapter`);return n}function pd(e){return e.length>0&&e.length<=128&&!/[\u0000-\u001f\u007f]/.test(e)}function md(e,t){if(!pd(t)||!e.observations?.includes(t))throw new TypeError("The observation is not declared by this release source")}function Ai(e){if(!(typeof window>"u"||e.storage==="memory"))try{return e.storage==="session"?window.sessionStorage:window.localStorage}catch{return}}function hd(e){try{let t=Ai(e)?.getItem(e.key)??void 0;return t&&Ii.test(t)?t:void 0}catch{return}}function du(e,t){try{Ai(e)?.setItem(e.key,t)}catch{}}function fu(e){let t=e.identity?.visitor;if(!t?.key)throw new TypeError("The source visitor identity policy is invalid");let n=hd(t)??uu.get(e.id);if(n)return n;let r=crypto.randomUUID();return uu.set(e.id,r),du(t,r),r}function pu(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=Ai(n)?.getItem(n.key);r=u?JSON.parse(u):void 0}catch{r=void 0}let s=lu.get(e.id),i=r&&typeof r.id=="string"&&Ii.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 lu.set(e.id,c),du(n,JSON.stringify(c)),c.id}function gd(e,t){let n=e.source_keys?.query;if(!Array.isArray(n)||n.length===0)return;let r;try{r=new URL(t)}catch{return}let s=e.source_keys?.max_value_length,i=Number.isInteger(s)?Math.min(Math.max(s??1,1),4096):512,o=Object.fromEntries(n.flatMap(a=>{if(typeof a!="string"||a.length===0||a.length>128)return[];let c=r.searchParams.get(a);return c?[[a,c.slice(0,i)]]:[]}));return Object.keys(o).length>0?o:void 0}async function Nt(e,t={},n={}){let r=Ut(n.source);if(md(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??fu(r),o=n.sessionId??pu(r);if(![s,i,o].every(h=>Ii.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=gd(r,a),f=d?{...t,source_keys:d}:t,m=Ot(),p=`${Ce.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 mu(e={},t={}){let n=Ut(t.source),r=ys("page_view",n),s=typeof document>"u"||!r.title_property?{}:{[r.title_property]:document.title.slice(0,512)};return Nt(r.observation,{...s,...e},{...t,source:n.id})}function hu(e,t={},n={}){if(!e||e.length>128)throw new TypeError("actionId is invalid");let r=Ut(n.source),s=ys("declared_action",r),i=s.id_property?{[s.id_property]:e}:{};return Nt(s.observation,{...t,...i},{...n,source:r.id})}function gu(){try{let e=Ut();return ys("form_receipt",e),{visitor_id:fu(e),session_id:pu(e),source:e.id}}catch{return}}function yd(e,t={}){let n=Ut(t.source),r=ys("form_receipt",n);return Nt(r.observation,e,{...t,source:n.id})}async function _d(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 yu(e,t,n,r,s){let i=At.filter(o=>o.adapters?.some(a=>a.type==="form_receipt"));await Promise.allSettled(i.map(async o=>{let a=o.id===r?.source;return yd(e,{source:o.id,eventId:a?t:await _d(t,o.id),pageUrl:n,signal:s,keepalive:!0,...a?{visitorId:r.visitor_id,sessionId:r.session_id}:{}})}))}var gr;function _s(e={}){if(typeof window>"u"||typeof document>"u")return()=>{};if(gr)return gr;if(window.__FSAOS_CONFIG__?.tracking?.enabled===!1)return()=>{};let t;try{t=e.source?[Ut(e.source)]:At.map(m=>Ut(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)}:{};Nt(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(!_||!fd.test(_))continue;let h=m.target.closest(`[${_}]`);if(!h)continue;let y=h.getAttribute(_)?.trim();if(!y||y.length>128)continue;let b={};g.id_property&&(b[g.id_property]=y),g.element_property&&(b[g.element_property]=h.tagName.toLowerCase()),Nt(g.observation,b,{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),gr=()=>{window.removeEventListener("popstate",i),window.removeEventListener("pageshow",i),document.removeEventListener("click",o,{capture:!0}),d&&(window.history.pushState=a,window.history.replaceState=c),gr=void 0},gr}var Mn;ne(()=>{Mn=void 0});function vs(e){if(Mn)return Mn.accountPath!==e.accountPath?Promise.reject(new Error("Reset the session before changing accounts")):Mn.promise;let t=ie(),n=()=>{if(t!==ie())throw new Error("Workspace session changed")},r=(async()=>{let s=await Xe();if(n(),!s.principal_id)throw new Error("Workspace initialization requires an authenticated principal");let i=await O().fetchQuery({queryKey:P.memberships(s.principal_id),queryFn:cs,staleTime:12e4,retry:!1});n();let o=i.find(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=Ve(o),u=Ve(a),d=fe();if(d&&d.id!==c.id)throw new Error("Reset the session before changing accounts");return d||Mt(c,{activate:!1}),await Dt(o.personalSpacePath,f=>{let m=i.find(p=>p.accountId===f&&(p.isAccount||p.isSpace));return m?Ve(m):null},{initialAnchor:u}),n(),{home:c,defaultSpace:u,memberships:i}})().catch(s=>{throw t===ie()&&(Mn=void 0),s});return Mn={accountPath:e.accountPath,promise:r},r}var Kt,_r,yr;ne(()=>{_r?.(),_r=void 0,Kt=void 0,yr=void 0});function _u(e={}){if(Kt)return e.workspace&&e.workspace.accountPath!==yr?Promise.reject(new Error("Initialize workspace through initializeWorkspace, or dispose the existing runtime first")):Kt;yr=e.workspace?.accountPath;let t=ie();return Kt=(async()=>{let n=e.tracking??!0,r=n===!1?()=>{}:_s(typeof n=="object"?n:{});_r=r;try{let s=e.session===!1?null:await Xe(),i=e.workspace?await vs(e.workspace):void 0;if(t!==ie())throw new Error("Session changed during initialization");let o=!1;return{session:s,workspace:i,dispose(){o||(o=!0,r(),t===ie()&&(Kt=void 0,yr=void 0,_r=void 0))}}}catch(s){throw r(),t===ie()&&(Kt=void 0,yr=void 0,_r=void 0),s}})(),Kt}async function ki(e){try{return await x("execution-control-transition",e)}catch(t){if(!(t instanceof Ie)||t.status<500)throw t;return await new Promise(n=>setTimeout(n,250)),x("execution-control-transition",e)}}function Mi(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 vu(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 ki({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 Mi(i?{...s,state:i}:s)}async function bu(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 ki({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 Mi(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 ki({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 Mi(i?{...s,outcome:i}:s)}var vd=/^[a-z][a-z0-9_-]{0,63}$/,bd=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,On=class extends Error{constructor(n,r,s,i){super(n);te(this,"code");te(this,"status");te(this,"fillId");this.name="FormSubmissionError",this.code=r,this.status=s,this.fillId=i}};async function Su(e,t,n={}){if(!vd.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(!bd.test(r))throw new TypeError("fillId must be a UUID");let s=Ot(),i=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!i)throw new TypeError("pageUrl is required outside a browser");let o=`${Ce.replace(/\/+$/,"")}/d/${encodeURIComponent(s)}/actions/${encodeURIComponent(e)}`,a=gu(),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 On(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 On(f?.message||f?.error||`Form submission failed (${u.status})`,f?.error||"FORM_SUBMISSION_FAILED",u.status,r)}return await yu({fill_id:r,action_id:e,release_id:d.release_id},r,i,a,n.signal),d}var Oi=X(ae(),1),Pu=X(xu(),1);function Cu(e){return x("read",{path:e})}function Tu(e,t){return x("list",{path:e,...t})}function Eu(e){return x("create",e)}function Iu(e){return x("update",e)}function Au(e){return x("create",e)}function ku(e,t){let r=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return x("tools/call",{name:e,instance_path:r,...t||{}})}function Mu(e,t,n){return x("signal",{target_id:e,event_name:t,payload:n||{}})}function Ou(e){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+e}var Fu={signIn:e=>e.provider?W.auth.signInWithOAuth({provider:e.provider,options:{redirectTo:e.redirectTo||window.location.href}}):W.auth.signInWithPassword({email:e.email,password:e.password}),signUp:e=>W.auth.signUp({email:e.email,password:e.password,options:{data:e.metadata||{}}}),signOut:async()=>{await W.auth.signOut(),mn(),O().clear()},getSession:()=>W.auth.getSession().then(e=>e.data.session),getUser:()=>W.auth.getUser().then(e=>e.data.user),onAuthStateChange:e=>{let{data:{subscription:t}}=W.auth.onAuthStateChange((n,r)=>{e({event:n,session:r,user:r?.user??null})});return()=>t?.unsubscribe()},resetPassword:e=>W.auth.resetPasswordForEmail(e),signInWithMagicLink:(e,t)=>W.auth.signInWithOtp({email:e,options:{emailRedirectTo:t||window.location.href}})};function qu(){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,Pu.createRoot)(e).render((0,Oi.createElement)(Gn,{client:O()},(0,Oi.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 Qu(){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 Fi(e){return x("invite-member",e)}function qi(e){return x("accept-invite",e)}function Qi(e){let t={};return e.role&&(t.role=e.role),x("link",{source_id:e.chat_id,target_id:e.member_id,edge_type:"has_member",context:t})}function Di(e){return x("create-agent",e)}function Ui(e){return!e.input_request_id&&!e.input_request?Promise.reject(new Error("answerInput needs input_request_id or the input_request object read from the step.")):x("todo-control",{action:"answer_input",...e})}function Du(){return Z({mutationFn:Fi})}function Uu(){let e=L();return Z({mutationFn:qi,onSuccess:()=>{e.invalidateQueries({queryKey:["memberships"]})}})}function Nu(){let e=L();return Z({mutationFn:Qi,onSuccess:(t,n)=>{e.invalidateQueries({queryKey:P.edges(n.chat_id)}),e.invalidateQueries({queryKey:P.edges(n.member_id)})}})}function Ku(){let e=L();return Z({mutationFn:Di,onSuccess:()=>{e.invalidateQueries({queryKey:["memberships"]})}})}function Lu(){let e=L();return Z({mutationFn:Ui,onSuccess:(t,n)=>{e.invalidateQueries({queryKey:P.itemById(n.step_id)})}})}function wd(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Sd(e,t){return t&&t.length>0?"select":e==="boolean"?"toggle":e==="integer"||e==="number"?"range":e==="string"?"text":"none"}function Rd(e,t){return!(e==="object"||e==="array")}function xd(e){return["string","number","integer","boolean"].includes(e)}function Pd(e){return e!=="object"&&e!=="array"}function ju(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=Rd(c,u),f=xd(c),m=Sd(c,u);i.push({key:o,label:a.title||wd(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 Ni(e){let t=e.default_data||{},n=e.field_defaults||{},r=ju(e.input_schema,!0,t,n),s=ju(e.system_schema,!1,t,n),i=[...r,...s],o=i.filter(u=>Pd(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 Vu(e){return{field:"updated_at",direction:"desc"}}function $u(e){let t=Ni(e),n=new Set(e.input_schema?.required||[]);return t.form_fields.filter(r=>n.has(r.key)||r.default_value===void 0)}var ve=X(ae(),1);var Cd=0;function Td(){return`upload_${Date.now()}_${++Cd}`}async function Wu(e,t,n,r){let s=t.name||(e instanceof File?e.name:`file-${Date.now()}`),i=e.type||"application/octet-stream",o=t.itemType||"file",a={parent_path:t.parentPath,item_type:o,name:s,type_data:{...t.typeData||{},file_source:{type:"upload",content_type:i}}};t.cardParentPath&&(a.card_parent_path=t.cardParentPath);let u=await x("create",a);if(!u.id)throw new Error(u.error||u.message||"Failed to create file item");let d=u.id,f=u.path;if(u.storage_completed&&u.file_ref)return{itemId:d,itemPath:f,fileRef:u.file_ref};let m=u.storage_key,p=u.upload_token,g=u.storage_worker_url||"https://fsaos-storage.radns.workers.dev";if(!m)throw new Error("Gateway returned no storage_key \u2014 file_source may not be supported for this item type");await Ed(g,m,p,e,i,n,r);let _=await Bu(d,m,i);return{itemId:d,itemPath:f,fileRef:_}}function Ed(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 Bu(e,t,n){let r=await Ye(),s=await fetch(`${Ce}/storage/upload-complete`,{method:"POST",headers:{"Content-Type":"application/json",...r?{Authorization:`Bearer ${r}`}:{}},body:JSON.stringify({item_id:e,storage_key:t,content_type:n})});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Upload confirmation failed: HTTP ${s.status} \u2014 ${o.slice(0,300)}`)}let i=await s.json();if(!i.success)throw new Error(i.error||i.message||"Upload confirmation rejected");return i.file_ref}function Hu(){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(b=>b.id===_?{...b,...h}:b))},[]),i=(0,ve.useCallback)(_=>{t(h=>[...h,_])},[]),o=(0,ve.useCallback)(async(_,h,y,b,T)=>{let E=y.name||h.name,S=h.type||"application/octet-stream",Q=y.itemType||"file",K=T?.itemId||null,R=T?.itemPath||null,I=T?.storageKey||null,M=T?.uploadToken||null,A=T?.storageWorkerUrl||null;try{if(!b||b==="create"){s(_,{status:"creating",error:null,_failedAt:null});let F=await x("create",{parent_path:y.parentPath,item_type:Q,name:E,type_data:{...y.typeData||{},file_source:{type:"upload",content_type:S}}});if(!F.id)throw Object.assign(new Error(F.error||F.message||"Failed to create file item"),{_step:"create"});if(K=F.id,R=F.path,s(_,{itemId:K,itemPath:R}),F.storage_completed&&F.file_ref){s(_,{status:"complete",progress:100,fileRef:F.file_ref}),n.invalidateQueries({queryKey:P.children(y.parentPath)});return}if(I=F.storage_key,M=F.upload_token||"",A=F.storage_worker_url||"https://fsaos-storage.radns.workers.dev",s(_,{_storageKey:I,_uploadToken:M,_storageWorkerUrl:A}),!I)throw Object.assign(new Error("Gateway returned no storage_key"),{_step:"create"})}(!b||b==="create"||b==="upload")&&(s(_,{status:"uploading",progress:0,error:null,_failedAt:null}),await new Promise((F,le)=>{let H=new XMLHttpRequest;s(_,{_xhr:H}),H.open("PUT",`${A}/upload`),H.setRequestHeader("X-Storage-Key",I),H.setRequestHeader("Content-Type",S),M&&H.setRequestHeader("X-Upload-Token",M),H.upload.onprogress=qe=>{qe.lengthComputable&&s(_,{progress:Math.round(qe.loaded/qe.total*100)})},H.onload=()=>{H.status>=200&&H.status<300?F():le(Object.assign(new Error(`Storage upload failed: HTTP ${H.status}`),{_step:"upload"}))},H.onerror=()=>le(Object.assign(new Error("Storage upload network error"),{_step:"upload"})),H.ontimeout=()=>le(Object.assign(new Error("Storage upload timed out"),{_step:"upload"})),H.send(h)}),s(_,{progress:100,_xhr:null})),s(_,{status:"confirming",error:null,_failedAt:null});let k=await Bu(K,I,S);s(_,{status:"complete",fileRef:k}),n.invalidateQueries({queryKey:P.children(y.parentPath)})}catch(k){let U=k?.message||String(k),F=k?._step||"create";s(_,{status:"error",error:U,_failedAt:F,_xhr:null})}},[s,n]),a=(0,ve.useCallback)((_,h)=>{let y=Td();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(T=>T.id===_);if(!h||h.status!=="error")return;let y=h._failedAt||"create",b=h._storageKey&&h.itemId?{storageKey:h._storageKey,uploadToken:h._uploadToken||"",storageWorkerUrl:h._storageWorkerUrl||"https://fsaos-storage.radns.workers.dev",itemId:h.itemId,itemPath:h.itemPath||""}:void 0;o(_,h.file,h.options,y,b)},[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:b,_failedAt:T,...E})=>E);return{upload:a,uploadMultiple:c,uploads:g,retryUpload:u,cancelUpload:d,removeUpload:f,clearCompleted:m,isUploading:p}}var Gu=X(ae(),1);async function Ki(e,t){return await x("resolve-items",{context_id:e,item_type:t})}function zu(e,t){return(0,Gu.useSyncExternalStore)(we,ee,ee),$({queryKey:["vfs",B()??"__unscoped__","resolved-items",e??"",t],queryFn:()=>Ki(e,t),enabled:!!(e&&t)})}var Fe=X(ae(),1);function bs(e,t){let n={artifacts:new Map,timeline:[]},r=new Map;function s(o){if(!o.action?.startsWith("artifact_"))return;let 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 zr(e,s)}function Ju(e,t=!0){let[n,r]=(0,Fe.useState)(new Map),[s,i]=(0,Fe.useState)([]),o=(0,Fe.useRef)({artifacts:new Map,timeline:[]});(0,Fe.useEffect)(()=>!e||!t?void 0:bs(e,f=>{o.current=f,r(new Map(f.artifacts)),i([...f.timeline])}),[e,t]);let a=(0,Fe.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 Yu(e,t=!0){let[n,r]=(0,Fe.useState)([]);(0,Fe.useEffect)(()=>!e||!t?void 0:bs(e,o=>{r([...o.timeline])}),[e,t]);let s=n.length>0?n[n.length-1]:null;return{timeline:n,latestActivity:s}}var ws=X(ae(),1);function Id(e,t,n,r){return["vfs","timeline-history",e,t??"__all__",n??500,r??0]}async function Li(e,t){let n=`${e}/datasets/agent-events`,r=t?.limit??500,s=t?.offset??0,i={limit:r,offset:s,sort:[{key:"seq",direction:"asc"}]};t?.turnId&&(i.filters=[{key:"turn_id",operator:"eq",value:t.turnId}]);try{let a=(await x("open",{path:n,mode:"extract",strategy:"rows",arguments:i}))?.content;return a?(a.rows??a.items??a.data??[]).map(Ad).sort((u,d)=>u.seq-d.seq):[]}catch(o){if(o?.status===404||o?.message?.includes("not found"))return[];throw o}}function Xu(e,t){let{turnId:n,limit:r=500,offset:s=0,enabled:i=!0,debounceMs:o=300}=t??{},a=e?`${e}/datasets/agent-events`:null,c=L(),u=(0,ws.useRef)(null),d=a?Id(a,n,r,s):["vfs","timeline-history","__disabled__"],f=$({queryKey:d,queryFn:()=>Li(e,{turnId:n,limit:r,offset:s}),enabled:!!e&&i});return(0,ws.useEffect)(()=>{if(!a||!i)return;let m=re("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 Ad(e){return{turn_id:String(e.turn_id??""),seq:Number(e.seq??0),kind:String(e.kind??""),status:String(e.status??""),title:String(e.title??""),tool_name:e.tool_name!=null?String(e.tool_name):void 0,tool_id:e.tool_id!=null?String(e.tool_id):void 0,evidence_uri:e.evidence_uri!=null?String(e.evidence_uri):void 0,artifact_item_uri:e.artifact_item_uri!=null?String(e.artifact_item_uri):void 0,preview:e.preview!=null?String(e.preview):void 0,duration_ms:e.duration_ms!=null?Number(e.duration_ms):void 0,started_at:String(e.started_at??""),completed_at:e.completed_at!=null?String(e.completed_at):void 0,error_type:e.error_type!=null?String(e.error_type):void 0,meta:e.meta!=null?e.meta:void 0}}var Ss=X(ae(),1);function Zu(){(0,Ss.useSyncExternalStore)(we,ee,ee);let e=B(),t=ye(),n=In(e?{key:"pinned",...t?{scope_id:t.id}:{}}:null),r=L(),s=n.resolvedChildren,i=!!(!n.error&&n.arrangement?.item_id&&n.resolutionLevel==="member"&&n.arrangement.write_target_id===n.arrangement.item_id),o=Z({mutationFn:async c=>{let u,d={_scope_path:c.scopePath};if(c.operation==="pin"?u=await x("create",{...d,parent_id:c.arrangementId,name:`pin-${c.target.id}`,item_type:"symlink",type_data:{target_item_id:c.target.id,target_type:c.target.item_type}}):c.operation==="unpin"?u=await x("delete",{...d,id:c.entry.id}):u=await x("update",{...d,id:c.arrangementId,type_data:{order:c.ids}}),u?.success===!1)throw new Error(u.error||"Pins could not be saved");return u},onSettled:(c,u,d)=>Ze(r,d.queryKey)}),a=(0,Ss.useCallback)(c=>!i||!e||B()!==e?Promise.reject(new Error("Personal pins are not available in this context")):c.operation==="unpin"&&!s.some(u=>u.id===c.entry.id)?Promise.reject(new Error("Pin is outside this arrangement")):c.operation==="reorder"&&(new Set(c.ids).size!==s.length||c.ids.length!==s.length||s.some(u=>!c.ids.includes(u.id)))?Promise.reject(new Error("Order must include each pin exactly once")):c.operation==="pin"&&s.some(u=>u.symlink_type_data?.target_item_id===c.target.id)?Promise.resolve(null):o.mutateAsync({...c,scopePath:e,arrangementId:n.arrangement.item_id,arrangementPath:n.arrangement.item_path,queryKey:n.arrangementQueryKey}),[i,e,s,n.arrangement,n.arrangementQueryKey,o.mutateAsync]);return{entries:s,isLoading:n.isLoading,error:n.error,refetch:n.refetch,ready:i,isSaving:o.isPending,saveError:o.error,isPinned:c=>s.some(u=>u.symlink_type_data?.target_item_id===c),pin:c=>a({operation:"pin",target:c}),unpin:c=>{let u=s.find(d=>d.symlink_type_data?.target_item_id===c||d.id===c);return u?a({operation:"unpin",entry:u}):Promise.resolve(null)},reorder:c=>a({operation:"reorder",ids:c})}}var Rs=X(ae(),1);var vr=(e,t,n)=>["vfs",e,"personal-sections",t,n];function ji(e,t){return e&&e.item_id===t.item_id&&e.version>t.version?e:t}async function Vi(e,t,n,r){let s=await x("personal-sections",{...r,context_item_id:t,collection:n,_scope_path:e});if(!s||s.success===!1)throw new Error(s?.message||s?.error||"Sections could not be saved");if(!Array.isArray(s.sections)||s.context_item_id!==t||s.collection!==n)throw new Error("Invalid sections response");return s}async function el(e,t){let n=await Vi(e.scopePath,e.contextId,e.collection,{operation:"assign",section_id:e.sectionId,target_id:t}),r=O();return r.setQueryData(vr(e.scopePath,e.contextId,e.collection),s=>ji(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"&&Ze(e,n.queryKey)}function nl(e,t){let n=(0,Rs.useSyncExternalStore)(we,ee,ee),r=B(),s=L(),i=vr(r,e,t),o=$({queryKey:i,enabled:!!r&&!!e,queryFn:()=>Vi(r,e,t,{operation:"list"}),staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0,personalSections:!0},structuralSharing:(f,m)=>ji(f,m)}),a=(0,Rs.useRef)(!1),c=Z({mutationFn:async f=>{let m=await Vi(f.scope,f.context,f.collection,{...f.change,...f.change.operation.startsWith("reorder")?{expected_version:f.version}:{}});return s.setQueryData(vr(f.scope,f.context,f.collection),p=>ji(p,m)),m},onSettled:(f,m,p)=>tl(s,p.scope)});async function u(f){if(!r||!e||n!==ee()||B()!==r||!o.data||o.error)throw new Error("Select the Space again before changing sections");if(a.current)throw new Error("A section change is still being saved");a.current=!0;try{return await c.mutateAsync({change: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}`}}qc($i);return hl($i);})();
7
+ ${t??""}`,[g,_]=(0,v.useState)(null),h=(0,v.useRef)({key:p,found:null,earlyContentPaths:new Set}),y=g?.key===p?g:null;(0,v.useLayoutEffect)(()=>{h.current={key:p,found:y,earlyContentPaths:new Set}},[p]);let b=$({queryKey:["vfs",f??"__unscoped__","minted-asset",m??"",t??""],queryFn:async()=>{let S=await R("query",{scope_path:f,filters:{[`field.${m}`]:t},limit:1}),q=S.content?.items??S.items??[],K=q[0]?_e(q[0]):null;if(!K)return null;let A=(await ur(K.path)).some(k=>k.item_type==="file"&&!!k.type_data?.file_ref);return{asset:K,hasBytes:A}},enabled:!!(t&&f&&m&&!s),refetchInterval:S=>h.current.key===p&&h.current.found?.hasBytes||S.state.data?.hasBytes?!1:1500});(0,v.useEffect)(()=>{let S=b.data;if(!S||h.current.key!==p)return;let q=h.current.found,K={key:p,itemId:S.asset.id,itemPath:S.asset.path,displayName:typeof S.asset.type_data?.display_name=="string"?S.asset.type_data.display_name:S.asset.name,hasBytes:S.hasBytes||!!(q?.itemId===S.asset.id&&q.hasBytes)};h.current.found=K,_(K)},[b.data,p]);let T=!!(t&&u)&&!s&&!y?.hasBytes;return(0,v.useEffect)(()=>{if(!(!T||!u))return xn(u,["asset.materialized","content.written"])},[T,u]),(0,v.useEffect)(()=>{if(!T||!t||!u)return;let S=p,q=I=>I?.payload??I,K=I=>{let Q=q(I)?.scope_id??I?.scope_id;return typeof Q=="string"?Q:void 0},x=I=>{let Q=q(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=[se("asset.materialized",I=>{if(h.current.key!==S)return;let M=q(I);if(typeof M?.item_id!="string"||!M.item_id)return;let Q=h.current.found,N=typeof M.item_path=="string"?M.item_path:void 0,W=!!M.has_bytes||!!(N&&Array.from(h.current.earlyContentPaths).some(te=>A(te,N)))||!!(Q&&Q.itemId===M.item_id&&Q.hasBytes),xe={key:S,itemId:M.item_id,itemPath:N,displayName:typeof M.display_name=="string"?M.display_name:void 0,hasBytes:W};h.current.found=xe,_(xe)},I=>{let M=K(I);return(!M||M===u)&&q(I)?.origin===t}),se("content.written",I=>{if(h.current.key!==S)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 W=h.current.earlyContentPaths.values().next().value;W&&h.current.earlyContentPaths.delete(W)}return}if(Q.hasBytes)return;let N={...Q,hasBytes:!0};h.current.found=N,_(N)},I=>{let M=K(I);return(!M||M===u)&&!!x(I)})];return()=>k.forEach(I=>I())},[T,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 au(e,t){let n=O().getDefaultOptions().queries?.retry??1;return typeof n=="function"?n(e,t):n===!0||typeof n=="number"&&e<n}function cu(e,t){let n=(0,kn.useSyncExternalStore)(we,ee,ee),r=ye(),s=H(),i=r?.kind==="space",o=An(i&&s?{key:e,scope_id:r.id}:null),a=(0,kn.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,b)=>h(b)-h(y)),[..._,...p.filter(y=>g.has(y.id))]},[e,t,o.applyTo,o.order]),c=L(),u=(0,kn.useRef)(!1),d=!!(i&&!o.error&&o.arrangement?.item_id&&o.resolutionLevel==="member"&&o.arrangement.write_target_id===o.arrangement.item_id),f=Z({mutationFn:async p=>{let g=await R("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,_)=>Ze(c,_.queryKey)});async function m(p){if(!d||!s||n!==ee()||H()!==s)throw new Error("Personal order is not available in this Space");if(u.current)throw new Error("An order change is already being saved");let g=t.map(S=>S.id);if(p.length!==g.length||new Set(p).size!==g.length||g.some(S=>!p.includes(S)))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(S=>S.id);if(p.every((S,q)=>h[q]===S))return;let y=new Set(g),b=0,E=[...(o.order??[]).map(S=>y.has(S)?p[b++]:S),...p.slice(b)];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: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 Ii=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,pd=/^[A-Za-z_:][A-Za-z0-9_:.-]{0,127}$/,uu=new Map,lu=new Map,Mn=class extends Error{constructor(n,r,s,i){super(n);ne(this,"code");ne(this,"status");ne(this,"eventId");this.name="InteractionTrackingError",this.code=r,this.status=s,this.eventId=i}};function Nt(e){let t=e?kt.find(n=>n.id===e):kt.find(n=>n.default===!0)??(kt.length===1?kt[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 _s(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 md(e){return e.length>0&&e.length<=128&&!/[\u0000-\u001f\u007f]/.test(e)}function hd(e,t){if(!md(t)||!e.observations?.includes(t))throw new TypeError("The observation is not declared by this release source")}function Ai(e){if(!(typeof window>"u"||e.storage==="memory"))try{return e.storage==="session"?window.sessionStorage:window.localStorage}catch{return}}function gd(e){try{let t=Ai(e)?.getItem(e.key)??void 0;return t&&Ii.test(t)?t:void 0}catch{return}}function du(e,t){try{Ai(e)?.setItem(e.key,t)}catch{}}function fu(e){let t=e.identity?.visitor;if(!t?.key)throw new TypeError("The source visitor identity policy is invalid");let n=gd(t)??uu.get(e.id);if(n)return n;let r=crypto.randomUUID();return uu.set(e.id,r),du(t,r),r}function pu(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=Ai(n)?.getItem(n.key);r=u?JSON.parse(u):void 0}catch{r=void 0}let s=lu.get(e.id),i=r&&typeof r.id=="string"&&Ii.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 lu.set(e.id,c),du(n,JSON.stringify(c)),c.id}function yd(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 Kt(e,t={},n={}){let r=Nt(n.source);if(hd(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??fu(r),o=n.sessionId??pu(r);if(![s,i,o].every(h=>Ii.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=yd(r,a),f=d?{...t,source_keys:d}:t,m=Ft(),p=`${Te.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 Mn(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 Mn(h?.message||h?.error||`Observation transport failed (${g.status})`,h?.error||"OBSERVATION_TRANSPORT_FAILED",g.status,s)}return _}function mu(e={},t={}){let n=Nt(t.source),r=_s("page_view",n),s=typeof document>"u"||!r.title_property?{}:{[r.title_property]:document.title.slice(0,512)};return Kt(r.observation,{...s,...e},{...t,source:n.id})}function hu(e,t={},n={}){if(!e||e.length>128)throw new TypeError("actionId is invalid");let r=Nt(n.source),s=_s("declared_action",r),i=s.id_property?{[s.id_property]:e}:{};return Kt(s.observation,{...t,...i},{...n,source:r.id})}function gu(){try{let e=Nt();return _s("form_receipt",e),{visitor_id:fu(e),session_id:pu(e),source:e.id}}catch{return}}function _d(e,t={}){let n=Nt(t.source),r=_s("form_receipt",n);return Kt(r.observation,e,{...t,source:n.id})}async function vd(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 yu(e,t,n,r,s){let i=kt.filter(o=>o.adapters?.some(a=>a.type==="form_receipt"));await Promise.allSettled(i.map(async o=>{let a=o.id===r?.source;return _d(e,{source:o.id,eventId:a?t:await vd(t,o.id),pageUrl:n,signal:s,keepalive:!0,...a?{visitorId:r.visitor_id,sessionId:r.session_id}:{}})}))}var yr;function vs(e={}){if(typeof window>"u"||typeof document>"u")return()=>{};if(yr)return yr;if(window.__FSAOS_CONFIG__?.tracking?.enabled===!1)return()=>{};let t;try{t=e.source?[Nt(e.source)]:kt.map(m=>Nt(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)}:{};Kt(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(!_||!pd.test(_))continue;let h=m.target.closest(`[${_}]`);if(!h)continue;let y=h.getAttribute(_)?.trim();if(!y||y.length>128)continue;let b={};g.id_property&&(b[g.id_property]=y),g.element_property&&(b[g.element_property]=h.tagName.toLowerCase()),Kt(g.observation,b,{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),yr=()=>{window.removeEventListener("popstate",i),window.removeEventListener("pageshow",i),document.removeEventListener("click",o,{capture:!0}),d&&(window.history.pushState=a,window.history.replaceState=c),yr=void 0},yr}var On;re(()=>{On=void 0});function bs(e){if(On)return On.accountPath!==e.accountPath?Promise.reject(new Error("Reset the session before changing accounts")):On.promise;let t=oe(),n=()=>{if(t!==oe())throw new Error("Workspace session changed")},r=(async()=>{let s=await Xe();if(n(),!s.principal_id)throw new Error("Workspace initialization requires an authenticated principal");let i=await O().fetchQuery({queryKey:P.memberships(s.principal_id),queryFn:us,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=Ve(o),u=Ve(a),d=fe();if(d&&d.id!==c.id)throw new Error("Reset the session before changing accounts");return d||Ot(c,{activate:!1}),await Ut(o.personalSpacePath,f=>{let m=i.find(p=>p.accountId===f&&(p.isAccount||p.isSpace));return m?Ve(m):null},{initialAnchor:u}),n(),{home:c,defaultSpace:u,memberships:i}})().catch(s=>{throw t===oe()&&(On=void 0),s});return On={accountPath:e.accountPath,promise:r},r}var Lt,vr,_r;re(()=>{vr?.(),vr=void 0,Lt=void 0,_r=void 0});function _u(e={}){if(Lt)return e.workspace&&e.workspace.accountPath!==_r?Promise.reject(new Error("Initialize workspace through initializeWorkspace, or dispose the existing runtime first")):Lt;_r=e.workspace?.accountPath;let t=oe();return Lt=(async()=>{let n=e.tracking??!0,r=n===!1?()=>{}:vs(typeof n=="object"?n:{});vr=r;try{let s=e.session===!1?null:await Xe(),i=e.workspace?await bs(e.workspace):void 0;if(t!==oe())throw new Error("Session changed during initialization");let o=!1;return{session:s,workspace:i,dispose(){o||(o=!0,r(),t===oe()&&(Lt=void 0,_r=void 0,vr=void 0))}}}catch(s){throw r(),t===oe()&&(Lt=void 0,_r=void 0,vr=void 0),s}})(),Lt}async function ki(e){try{return await R("execution-control-transition",e)}catch(t){if(!(t instanceof Ae)||t.status<500)throw t;return await new Promise(n=>setTimeout(n,250)),R("execution-control-transition",e)}}function Mi(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 vu(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 ki({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 Mi(i?{...s,state:i}:s)}async function bu(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 ki({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 Mi(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 ki({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 Mi(i?{...s,outcome:i}:s)}var bd=/^[a-z][a-z0-9_-]{0,63}$/,wd=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Fn=class extends Error{constructor(n,r,s,i){super(n);ne(this,"code");ne(this,"status");ne(this,"fillId");this.name="FormSubmissionError",this.code=r,this.status=s,this.fillId=i}};async function Su(e,t,n={}){if(!bd.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(!wd.test(r))throw new TypeError("fillId must be a UUID");let s=Ft(),i=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!i)throw new TypeError("pageUrl is required outside a browser");let o=`${Te.replace(/\/+$/,"")}/d/${encodeURIComponent(s)}/actions/${encodeURIComponent(e)}`,a=gu(),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 Fn(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 Fn(f?.message||f?.error||`Form submission failed (${u.status})`,f?.error||"FORM_SUBMISSION_FAILED",u.status,r)}return await yu({fill_id:r,action_id:e,release_id:d.release_id},r,i,a,n.signal),d}var Oi=X(ce(),1),Pu=X(Ru(),1);function Cu(e){return R("read",{path:e})}function Tu(e,t){return R("list",{path:e,...t})}function Eu(e){return R("create",e)}function Iu(e){return R("update",e)}function Au(e){return R("create",e)}function ku(e,t){let r=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return R("tools/call",{name:e,instance_path:r,...t||{}})}function Mu(e,t,n){return R("signal",{target_id:e,event_name:t,payload:n||{}})}function Ou(e){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+e}var Fu={signIn:e=>e.provider?B.auth.signInWithOAuth({provider:e.provider,options:{redirectTo:e.redirectTo||window.location.href}}):B.auth.signInWithPassword({email:e.email,password:e.password}),signUp:e=>B.auth.signUp({email:e.email,password:e.password,options:{data:e.metadata||{}}}),signOut:async()=>{await B.auth.signOut(),hn(),O().clear()},getSession:()=>B.auth.getSession().then(e=>e.data.session),getUser:()=>B.auth.getUser().then(e=>e.data.user),onAuthStateChange:e=>{let{data:{subscription:t}}=B.auth.onAuthStateChange((n,r)=>{e({event:n,session:r,user:r?.user??null})});return()=>t?.unsubscribe()},resetPassword:e=>B.auth.resetPasswordForEmail(e),signInWithMagicLink:(e,t)=>B.auth.signInWithOtp({email:e,options:{emailRedirectTo:t||window.location.href}})};function qu(){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,Pu.createRoot)(e).render((0,Oi.createElement)(zn,{client:O()},(0,Oi.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 Qu(){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 Fi(e){return R("invite-member",e)}function qi(e){return R("accept-invite",e)}function Qi(e){let t={};return e.role&&(t.role=e.role),R("link",{source_id:e.chat_id,target_id:e.member_id,edge_type:"has_member",context:t})}function Di(e){return R("create-agent",e)}function Ui(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.")):R("todo-control",{action:"answer_input",...e})}function Du(){return Z({mutationFn:Fi})}function Uu(){let e=L();return Z({mutationFn:qi,onSuccess:()=>{e.invalidateQueries({queryKey:["memberships"]})}})}function Nu(){let e=L();return Z({mutationFn:Qi,onSuccess:(t,n)=>{e.invalidateQueries({queryKey:P.edges(n.chat_id)}),e.invalidateQueries({queryKey:P.edges(n.member_id)})}})}function Ku(){let e=L();return Z({mutationFn:Di,onSuccess:()=>{e.invalidateQueries({queryKey:["memberships"]})}})}function Lu(){let e=L();return Z({mutationFn:Ui,onSuccess:(t,n)=>{e.invalidateQueries({queryKey:P.itemById(n.step_id)})}})}function Sd(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function xd(e,t){return t&&t.length>0?"select":e==="boolean"?"toggle":e==="integer"||e==="number"?"range":e==="string"?"text":"none"}function Rd(e,t){return!(e==="object"||e==="array")}function Pd(e){return["string","number","integer","boolean"].includes(e)}function Cd(e){return e!=="object"&&e!=="array"}function ju(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=Rd(c,u),f=Pd(c),m=xd(c,u);i.push({key:o,label:a.title||Sd(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 Ni(e){let t=e.default_data||{},n=e.field_defaults||{},r=ju(e.input_schema,!0,t,n),s=ju(e.system_schema,!1,t,n),i=[...r,...s],o=i.filter(u=>Cd(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 Vu(e){return{field:"updated_at",direction:"desc"}}function $u(e){let t=Ni(e),n=new Set(e.input_schema?.required||[]);return t.form_fields.filter(r=>n.has(r.key)||r.default_value===void 0)}var ve=X(ce(),1);function Wu(){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 Bu(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"?Wu():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 R("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 Td(h,g,_,e,i,n,r);let y=await Hu(m,g,i);return{itemId:m,itemPath:p,fileRef:y}}function Td(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 Hu(e,t,n){let r=await Ye(),s=await fetch(`${Te}/storage/upload-complete`,{method:"POST",headers:{"Content-Type":"application/json",...r?{Authorization:`Bearer ${r}`}:{}},body:JSON.stringify({item_id:e,storage_key:t,content_type:n})});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Upload confirmation failed: HTTP ${s.status} \u2014 ${o.slice(0,300)}`)}let i=await s.json();if(!i.success)throw new Error(i.error||i.message||"Upload confirmation rejected");return i.file_ref}function Gu(){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(b=>b.id===_?{...b,...h}:b))},[]),i=(0,ve.useCallback)(_=>{t(h=>[...h,_])},[]),o=(0,ve.useCallback)(async(_,h,y,b,T)=>{let E=y.name||h.name,S=h.type||"application/octet-stream",q=y.itemType||"file",K=y.collisionPolicy||"keep_both",x=T?.itemId||null,A=T?.itemPath||null,k=T?.storageKey||null,I=T?.uploadToken||null,M=T?.storageWorkerUrl||null;try{if(!b||b==="create"){s(_,{status:"creating",error:null,_failedAt:null});let W=await R("create",{parent_path:y.parentPath,item_type:q,name:E,type_data:{...y.typeData||{},file_source:{type:"upload",content_type:S,collision_policy:K,...K==="keep_both"?{upload_id:_}:{}}}});if(!W.id)throw Object.assign(new Error(W.error||W.message||"Failed to create file item"),{_step:"create"});if(x=W.id,A=W.path,s(_,{itemId:x,itemPath:A}),W.storage_completed&&W.file_ref){s(_,{status:"complete",progress:100,fileRef:W.file_ref}),n.invalidateQueries({queryKey:P.children(y.parentPath)});return}if(k=W.storage_key,I=W.upload_token||"",M=W.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"})}(!b||b==="create"||b==="upload")&&(s(_,{status:"uploading",progress:0,error:null,_failedAt:null}),await new Promise((W,xe)=>{let te=new XMLHttpRequest;s(_,{_xhr:te}),te.open("PUT",`${M}/upload`),te.setRequestHeader("X-Storage-Key",k),te.setRequestHeader("Content-Type",S),I&&te.setRequestHeader("X-Upload-Token",I),te.upload.onprogress=bt=>{bt.lengthComputable&&s(_,{progress:Math.round(bt.loaded/bt.total*100)})},te.onload=()=>{te.status>=200&&te.status<300?W():xe(Object.assign(new Error(`Storage upload failed: HTTP ${te.status}`),{_step:"upload"}))},te.onerror=()=>xe(Object.assign(new Error("Storage upload network error"),{_step:"upload"})),te.ontimeout=()=>xe(Object.assign(new Error("Storage upload timed out"),{_step:"upload"})),te.send(h)}),s(_,{progress:100,_xhr:null})),s(_,{status:"confirming",error:null,_failedAt:null});let Q=await Hu(x,k,S);s(_,{status:"complete",fileRef:Q}),n.invalidateQueries({queryKey:P.children(y.parentPath)})}catch(Q){let N=Q?.message||String(Q),W=Q?._step||"create";s(_,{status:"error",error:N,_failedAt:W,_xhr:null})}},[s,n]),a=(0,ve.useCallback)((_,h)=>{let y=Wu();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(T=>T.id===_);if(!h||h.status!=="error")return;let y=h._failedAt||"create",b=h._storageKey&&h.itemId?{storageKey:h._storageKey,uploadToken:h._uploadToken||"",storageWorkerUrl:h._storageWorkerUrl||"https://fsaos-storage.radns.workers.dev",itemId:h.itemId,itemPath:h.itemPath||""}:void 0;o(_,h.file,h.options,y,b)},[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:b,_failedAt:T,...E})=>E);return{upload:a,uploadMultiple:c,uploads:g,retryUpload:u,cancelUpload:d,removeUpload:f,clearCompleted:m,isUploading:p}}var zu=X(ce(),1);async function Ki(e,t){return await R("resolve-items",{context_id:e,item_type:t})}function Ju(e,t){return(0,zu.useSyncExternalStore)(we,ee,ee),$({queryKey:["vfs",H()??"__unscoped__","resolved-items",e??"",t],queryFn:()=>Ki(e,t),enabled:!!(e&&t)})}var qe=X(ce(),1);function ws(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 Jr(e,s)}function Yu(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:ws(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(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 Xu(e,t=!0){let[n,r]=(0,qe.useState)([]);(0,qe.useEffect)(()=>!e||!t?void 0:ws(e,o=>{r([...o.timeline])}),[e,t]);let s=n.length>0?n[n.length-1]:null;return{timeline:n,latestActivity:s}}var Ss=X(ce(),1);function Ed(e,t,n,r){return["vfs","timeline-history",e,t??"__all__",n??500,r??0]}async function Li(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 R("open",{path:n,mode:"extract",strategy:"rows",arguments:i}))?.content;return a?(a.rows??a.items??a.data??[]).map(Id).sort((u,d)=>u.seq-d.seq):[]}catch(o){if(o?.status===404||o?.message?.includes("not found"))return[];throw o}}function Zu(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,Ss.useRef)(null),d=a?Ed(a,n,r,s):["vfs","timeline-history","__disabled__"],f=$({queryKey:d,queryFn:()=>Li(e,{turnId:n,limit:r,offset:s}),enabled:!!e&&i});return(0,Ss.useEffect)(()=>{if(!a||!i)return;let m=se("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 Id(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 xs=X(ce(),1);function el(){(0,xs.useSyncExternalStore)(we,ee,ee);let e=H(),t=ye(),n=An(e?{key:"pinned",...t?{scope_id:t.id}:{}}:null),r=L(),s=n.resolvedChildren,i=!!(!n.error&&n.arrangement?.item_id&&n.resolutionLevel==="member"&&n.arrangement.write_target_id===n.arrangement.item_id),o=Z({mutationFn:async c=>{let u,d={_scope_path:c.scopePath};if(c.operation==="pin"?u=await R("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 R("delete",{...d,id:c.entry.id}):u=await R("update",{...d,id:c.arrangementId,type_data:{order:c.ids}}),u?.success===!1)throw new Error(u.error||"Pins could not be saved");return u},onSettled:(c,u,d)=>Ze(r,d.queryKey)}),a=(0,xs.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 Rs=X(ce(),1);var br=(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 Vi(e,t,n,r){let s=await R("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 tl(e,t){let n=await Vi(e.scopePath,e.contextId,e.collection,{operation:"assign",section_id:e.sectionId,target_id:t}),r=O();return r.setQueryData(br(e.scopePath,e.contextId,e.collection),s=>ji(s,n)),nl(r,e.scopePath),n}function nl(e,t){for(let n of e.getQueryCache().getAll())n.queryKey[0]==="vfs"&&n.queryKey[1]===t&&n.queryKey[2]==="personal-sections"&&Ze(e,n.queryKey)}function rl(e,t){let n=(0,Rs.useSyncExternalStore)(we,ee,ee),r=H(),s=L(),i=br(r,e,t),o=$({queryKey:i,enabled:!!r&&!!e,queryFn:()=>Vi(r,e,t,{operation:"list"}),staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0,personalSections:!0},structuralSharing:(f,m)=>ji(f,m)}),a=(0,Rs.useRef)(!1),c=Z({mutationFn:async f=>{let m=await Vi(f.scope,f.context,f.collection,{...f.change,...f.change.operation.startsWith("reorder")?{expected_version:f.version}:{}});return s.setQueryData(br(f.scope,f.context,f.collection),p=>ji(p,m)),m},onSettled:(f,m,p)=>nl(s,p.scope)});async function u(f){if(!r||!e||n!==ee()||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}`}}qc($i);return gl($i);})();
8
8
 
9
9
  /* ── Auto-setup: require shim + mount + backward compat globals ── */
10
10
  (function() {