@ai4b-team/fsaos-gateway-sdk 3.34.1 → 3.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,10 @@
1
- /* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-10-01T23:32:38.921Z */
2
- "use strict";var __FSAOS_GATEWAY__=(()=>{var zc=Object.create;var hn=Object.defineProperty;var Jc=Object.getOwnPropertyDescriptor;var Yc=Object.getOwnPropertyNames;var Xc=Object.getPrototypeOf,Zc=Object.prototype.hasOwnProperty;var si=e=>{throw TypeError(e)};var eu=(e,t,n)=>t in e?hn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var gn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),tu=(e,t)=>{for(var n in t)hn(e,n,{get:t[n],enumerable:!0})},ii=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Yc(t))!Zc.call(e,s)&&s!==n&&hn(e,s,{get:()=>t[s],enumerable:!(r=Jc(t,s))||r.enumerable});return e};var J=(e,t,n)=>(n=e!=null?zc(Xc(e)):{},ii(t||!e||!e.__esModule?hn(n,"default",{value:e,enumerable:!0}):n,e)),nu=e=>ii(hn({},"__esModule",{value:!0}),e);var Y=(e,t,n)=>eu(e,typeof t!="symbol"?t+"":t,n),Xr=(e,t,n)=>t.has(e)||si("Cannot "+n);var u=(e,t,n)=>(Xr(e,t,"read from private field"),n?n.call(e):t.get(e)),w=(e,t,n)=>t.has(e)?si("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),b=(e,t,n,r)=>(Xr(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),x=(e,t,n)=>(Xr(e,t,"access private method"),n);var yn=(e,t,n,r)=>({set _(s){b(e,t,s,n)},get _(){return u(e,t,r)}});var oe=gn((yl,oi)=>{oi.exports=React});var ur=gn((hf,Ki)=>{Ki.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var Zi=gn((Hf,Xi)=>{Xi.exports={createClient:window.supabase.createClient}});var wo=gn((rp,bo)=>{bo.exports=ReactDOM});var bc=gn((ym,vc)=>{vc.exports=ReactDOM});var ni={};tu(ni,{ComponentRenderer:()=>La,EnforcementDeniedError:()=>Ct,FormSubmissionError:()=>mn,GatewayRequestError:()=>ot,InteractionTrackingError:()=>dn,KernelProvider:()=>ja,QueryClientProvider:()=>In,auth:()=>Ac,awaitAnchorReady:()=>Dn,awaitScopeReady:()=>lo,callTool:()=>Tc,cancelQueuedTurn:()=>yc,cancelTurn:()=>hc,clearCachedToken:()=>Cs,clearSession:()=>Os,createItem:()=>Pc,disconnectSSE:()=>Ns,disposeVfsRealtimeWs:()=>Lr,electHomeAnchor:()=>Un,emitEvent:()=>Ko,fetchChannelMessages:()=>Yo,fetchChannelMessagesPage:()=>Wn,fetchChannelMessagesWithCards:()=>Ur,fetchEdgesForItem:()=>Or,fetchItemHistory:()=>qr,fetchItemVersions:()=>Hn,fetchItems:()=>on,fetchMemberFocus:()=>Qr,fetchOpenEnvelope:()=>Dr,fetchRecentActivity:()=>Fr,fetchResolvedItems:()=>ei,fetchTimelineHistory:()=>ti,fetchTurnQueueEntries:()=>Go,fetchTypeDefinitions:()=>kr,fetchVfsChildren:()=>Vn,fetchVfsChildrenPage:()=>Ar,fetchVfsItem:()=>Ir,fetchVfsItemById:()=>Er,fetchVfsTree:()=>Mr,gatewayCall:()=>R,getAccessToken:()=>je,getAnchor:()=>Qn,getAnchorRef:()=>Pe,getAnchorVersion:()=>Es,getAssetUrl:()=>Ic,getDefaultSort:()=>Fc,getHomeAnchor:()=>it,getMountVersion:()=>Kn,getMounts:()=>Wt,getPathSubscriptionState:()=>jo,getQueryClient:()=>T,getRequiredFormFields:()=>qc,getScope:()=>te,getScopeVersion:()=>ne,getServerClockOffsetMs:()=>go,getServerClockSyncedAt:()=>yo,getSessionEntry:()=>wt,hasServerClock:()=>ho,initSession:()=>Gt,initVfsRealtimeWs:()=>zn,initializeFsaos:()=>mc,interpretSchema:()=>Zs,invalidateAllVfs:()=>ea,invalidateChannelMessages:()=>na,invalidateChildren:()=>Tr,invalidateItem:()=>Ls,invalidateOpenEnvelope:()=>ra,invalidatePathAndParent:()=>Xo,invalidateSubtree:()=>Zo,invalidateTypes:()=>ta,isAnchorReady:()=>As,isChannelPath:()=>at,isListableItemsFilter:()=>sn,isScopeReady:()=>_r,itemsFilterFromQueryFilter:()=>zo,listChildren:()=>Rc,mount:()=>kc,mountRealtimeScope:()=>Jn,normalizeItem:()=>we,onConnectionStateChange:()=>Vo,pathSubscriptionMatches:()=>Qs,ping:()=>Lo,pushChanges:()=>xc,queryClient:()=>Eo,readItem:()=>Sc,refreshQuery:()=>$e,registerCleanup:()=>Be,resetAllSdkState:()=>zt,resolvePrincipalId:()=>Ua,resubscribePath:()=>$o,serverDeadlinePassed:()=>_o,serverMsUntil:()=>vo,serverNow:()=>vr,setAnchor:()=>st,setCachedToken:()=>no,setQueryClient:()=>To,setScope:()=>uo,setupRequireShim:()=>Oc,signal:()=>Ec,startTracking:()=>Hr,steerTurn:()=>gc,submitForm:()=>_c,subscribeAnchor:()=>Is,subscribeArtifactStream:()=>Wr,subscribeMounts:()=>yr,subscribeScope:()=>Ce,subscribeToEvents:()=>re,subscribeToPath:()=>xr,subscribeToScope:()=>rn,trackAction:()=>dc,trackEvent:()=>Pt,trackPageView:()=>lc,unmountRealtimeScope:()=>aa,updateItem:()=>Cc,uploadFile:()=>Qc,useAccounts:()=>Ia,useAgentTimeline:()=>jc,useAllChannels:()=>$r,useArrangement:()=>un,useArtifactStream:()=>Lc,useAsset:()=>ka,useAuth:()=>Br,useChannelMessages:()=>Ba,useChannels:()=>Va,useChildren:()=>pa,useComponent:()=>Hs,useCreate:()=>Ga,useDelete:()=>Ya,useDmChannels:()=>Ha,useEdges:()=>ba,useEventStream:()=>tc,useFileUpload:()=>Uc,useInfiniteChannelMessages:()=>$a,useInfiniteChildren:()=>va,useInfiniteItems:()=>_a,useItem:()=>da,useItemById:()=>fa,useItemHistory:()=>xa,useItemVersions:()=>Ca,useItems:()=>ya,useLink:()=>Za,useList:()=>Vs,useMemberFocus:()=>Pa,useMintedAsset:()=>rc,useMounts:()=>Aa,useMove:()=>Xa,useMutation:()=>ec,useNotifications:()=>Ws,useOpen:()=>Sa,usePermission:()=>qa,usePermissions:()=>Qa,usePersonalItemOrder:()=>sc,usePinnedItems:()=>$c,usePrincipal:()=>Na,useRealtimeQuery:()=>nc,useRecentActivity:()=>Ta,useResolve:()=>ga,useResolvedItems:()=>Kc,useScope:()=>Ea,useScopeReady:()=>la,useSearch:()=>ha,useTheme:()=>Fa,useTimelineHistory:()=>Bc,useTool:()=>Ka,useTree:()=>ma,useType:()=>wa,useTypeHelpers:()=>Ra,useTypes:()=>jr,useUnreadCounts:()=>Wa,useUpdate:()=>za,useUpdatePrincipal:()=>Ja,vfsKeys:()=>S,waitForPathReady:()=>Bo});var Ct=class e extends Error{constructor(n){let r=n.message||e.fallbackMessage(n);super(r);Y(this,"name","EnforcementDeniedError");Y(this,"deniedBy");Y(this,"ruleKey");Y(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 ln=J(oe(),1);var ge=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 dt,We,xt,ai,ru=(ai=class extends ge{constructor(){super();w(this,dt);w(this,We);w(this,xt);b(this,xt,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){u(this,We)||this.setEventListener(u(this,xt))}onUnsubscribe(){var t;this.hasListeners()||((t=u(this,We))==null||t.call(this),b(this,We,void 0))}setEventListener(t){var n;b(this,xt,t),(n=u(this,We))==null||n.call(this),b(this,We,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){u(this,dt)!==t&&(b(this,dt,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof u(this,dt)=="boolean"?u(this,dt):globalThis.document?.visibilityState!=="hidden"}},dt=new WeakMap,We=new WeakMap,xt=new WeakMap,ai),Tt=new ru;var su={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Ge,Zr,ci,iu=(ci=class{constructor(){w(this,Ge,su);w(this,Zr,!1)}setTimeoutProvider(e){b(this,Ge,e)}setTimeout(e,t){return u(this,Ge).setTimeout(e,t)}clearTimeout(e){u(this,Ge).clearTimeout(e)}setInterval(e,t){return u(this,Ge).setInterval(e,t)}clearInterval(e){u(this,Ge).clearInterval(e)}},Ge=new WeakMap,Zr=new WeakMap,ci),Ee=new iu;function ui(e){setTimeout(e,0)}var ts=typeof window>"u"||"Deno"in globalThis;function V(){}function fi(e,t){return typeof e=="function"?e(t):e}function _n(e){return typeof e=="number"&&e>=0&&e!==1/0}function er(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Se(e,t){return typeof e=="function"?e(t):e}function ce(e,t){return typeof e=="function"?e(t):e}function tr(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:o,stale:a}=e;if(o){if(r){if(t.queryHash!==vn(o,t.options))return!1}else if(!ft(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 nr(e,t){let{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Ie(t.options.mutationKey)!==Ie(i))return!1}else if(!ft(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function vn(e,t){return(t?.queryKeyHashFn||Ie)(e)}function Ie(e){return JSON.stringify(e,(t,n)=>es(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function ft(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>ft(e[n],t[n])):!1}var ou=Object.prototype.hasOwnProperty;function ns(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=li(e)&&li(t);if(!r&&!(es(e)&&es(t)))return t;let i=(r?e:Object.keys(e)).length,o=r?t:Object.keys(t),a=o.length,c=r?new Array(a):{},l=0;for(let d=0;d<a;d++){let m=r?d:o[d],f=e[m],p=t[m];if(f===p){c[m]=f,(r?d<i:ou.call(e,m))&&l++;continue}if(f===null||p===null||typeof f!="object"||typeof p!="object"){c[m]=p;continue}let y=ns(f,p,n+1);c[m]=y,y===f&&l++}return i===a&&l===i?e:c}function Et(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 li(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function es(e){if(!di(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!di(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function di(e){return Object.prototype.toString.call(e)==="[object Object]"}function pi(e){return new Promise(t=>{Ee.setTimeout(t,e)})}function bn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?ns(e,t):t}function mi(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function hi(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var It=Symbol();function rr(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===It?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function At(e,t){return typeof e=="function"?e(...t):!!e}function gi(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 Ae=(()=>{let e=()=>ts;return{isServer(){return e()},setIsServer(t){e=t}}})();function wn(){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 yi=ui;function au(){let e=[],t=0,n=a=>{a()},r=a=>{a()},s=yi,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 U=au();var kt,ze,Ot,_i,cu=(_i=class extends ge{constructor(){super();w(this,kt,!0);w(this,ze);w(this,Ot);b(this,Ot,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(){u(this,ze)||this.setEventListener(u(this,Ot))}onUnsubscribe(){var t;this.hasListeners()||((t=u(this,ze))==null||t.call(this),b(this,ze,void 0))}setEventListener(t){var n;b(this,Ot,t),(n=u(this,ze))==null||n.call(this),b(this,ze,t(this.setOnline.bind(this)))}setOnline(t){u(this,kt)!==t&&(b(this,kt,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return u(this,kt)}},kt=new WeakMap,ze=new WeakMap,Ot=new WeakMap,_i),Mt=new cu;function uu(e){return Math.min(1e3*2**e,3e4)}function rs(e){return(e??"online")==="online"?Mt.isOnline():!0}var sr=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function ir(e){let t=!1,n=0,r,s=wn(),i=()=>s.status!=="pending",o=g=>{if(!i()){let h=new sr(g);f(h),e.onCancel?.(h)}},a=()=>{t=!0},c=()=>{t=!1},l=()=>Tt.isFocused()&&(e.networkMode==="always"||Mt.isOnline())&&e.canRun(),d=()=>rs(e.networkMode)&&e.canRun(),m=g=>{i()||(r?.(),s.resolve(g))},f=g=>{i()||(r?.(),s.reject(g))},p=()=>new Promise(g=>{r=h=>{(i()||l())&&g(h)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),y=()=>{if(i())return;let g,h=n===0?e.initialPromise:void 0;try{g=h??e.fn()}catch(v){g=Promise.reject(v)}Promise.resolve(g).then(m).catch(v=>{if(i())return;let P=e.retry??(Ae.isServer()?0:3),M=e.retryDelay??uu,X=typeof M=="function"?M(n,v):M,C=P===!0||typeof P=="number"&&n<P||typeof P=="function"&&P(n,v);if(t||!C){f(v);return}n++,e.onFail?.(n,v),pi(X).then(()=>l()?void 0:p()).then(()=>{t?f(v):y()})})};return{promise:s,status:()=>s.status,cancel:o,continue:()=>(r?.(),s),cancelRetry:a,continueRetry:c,canStart:d,start:()=>(d()?y():p().then(y),s)}}var pt,vi,or=(vi=class{constructor(){w(this,pt)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),_n(this.gcTime)&&b(this,pt,Ee.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ae.isServer()?1/0:5*60*1e3))}clearGcTimeout(){u(this,pt)!==void 0&&(Ee.clearTimeout(u(this,pt)),b(this,pt,void 0))}},pt=new WeakMap,vi);var mt,Ft,ye,ht,Z,Sn,gt,fe,Pi,qe,Si,Ri=(Si=class extends or{constructor(t){super();w(this,fe);w(this,mt);w(this,Ft);w(this,ye);w(this,ht);w(this,Z);w(this,Sn);w(this,gt);b(this,gt,!1),b(this,Sn,t.defaultOptions),this.setOptions(t.options),this.observers=[],b(this,ht,t.client),b(this,ye,u(this,ht).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,b(this,mt,wi(this.options)),this.state=t.state??u(this,mt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return u(this,Z)?.promise}setOptions(t){if(this.options={...u(this,Sn),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=wi(this.options);n.data!==void 0&&(this.setState(bi(n.data,n.dataUpdatedAt)),b(this,mt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&u(this,ye).remove(this)}setData(t,n){let r=bn(this.state.data,t,this.options);return x(this,fe,qe).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){x(this,fe,qe).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=u(this,Z)?.promise;return u(this,Z)?.cancel(t),n?n.then(V).catch(V):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return u(this,mt)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>ce(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===It||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>Se(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:!er(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),u(this,Z)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),u(this,Z)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),u(this,ye).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(u(this,Z)&&(u(this,gt)||x(this,fe,Pi).call(this)?u(this,Z).cancel({revert:!0}):u(this,Z).cancelRetry()),this.scheduleGc()),u(this,ye).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||x(this,fe,qe).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&u(this,Z)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(u(this,Z))return u(this,Z).continueRetry(),u(this,Z).promise}if(t&&this.setOptions(t),!this.options.queryFn){let c=this.observers.find(l=>l.options.queryFn);c&&this.setOptions(c.options)}let r=new AbortController,s=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(b(this,gt,!0),r.signal)})},i=()=>{let c=rr(this.options,n),d=(()=>{let m={client:u(this,ht),queryKey:this.queryKey,meta:this.meta};return s(m),m})();return b(this,gt,!1),this.options.persister?this.options.persister(c,d,this):c(d)},a=(()=>{let c={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:u(this,ht),state:this.state,fetchFn:i};return s(c),c})();this.options.behavior?.onFetch(a,this),b(this,Ft,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&x(this,fe,qe).call(this,{type:"fetch",meta:a.fetchOptions?.meta}),b(this,Z,ir({initialPromise:n?.initialPromise,fn:a.fetchFn,onCancel:c=>{c instanceof sr&&c.revert&&this.setState({...u(this,Ft),fetchStatus:"idle"}),r.abort()},onFail:(c,l)=>{x(this,fe,qe).call(this,{type:"failed",failureCount:c,error:l})},onPause:()=>{x(this,fe,qe).call(this,{type:"pause"})},onContinue:()=>{x(this,fe,qe).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0}));try{let c=await u(this,Z).start();if(c===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(c),u(this,ye).config.onSuccess?.(c,this),u(this,ye).config.onSettled?.(c,this.state.error,this),c}catch(c){if(c instanceof sr){if(c.silent)return u(this,Z).promise;if(c.revert){if(this.state.data===void 0)throw c;return this.state.data}}throw x(this,fe,qe).call(this,{type:"error",error:c}),u(this,ye).config.onError?.(c,this),u(this,ye).config.onSettled?.(this.state.data,c,this),c}finally{this.scheduleGc()}}},mt=new WeakMap,Ft=new WeakMap,ye=new WeakMap,ht=new WeakMap,Z=new WeakMap,Sn=new WeakMap,gt=new WeakMap,fe=new WeakSet,Pi=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},qe=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,...ss(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...bi(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return b(this,Ft,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),U.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),u(this,ye).notify({query:this,type:"updated",action:t})})},Si);function ss(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:rs(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function bi(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function wi(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 ue,k,Pn,ae,yt,qt,Qe,Je,Cn,Qt,Dt,_t,vt,Ye,Ut,q,Rn,is,os,as,cs,us,ls,ds,Ei,Ti,xn=(Ti=class extends ge{constructor(t,n){super();w(this,q);w(this,ue);w(this,k);w(this,Pn);w(this,ae);w(this,yt);w(this,qt);w(this,Qe);w(this,Je);w(this,Cn);w(this,Qt);w(this,Dt);w(this,_t);w(this,vt);w(this,Ye);w(this,Ut,new Set);this.options=n,b(this,ue,t),b(this,Je,null),b(this,Qe,wn()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(u(this,k).addObserver(this),Ci(u(this,k),this.options)?x(this,q,Rn).call(this):this.updateResult(),x(this,q,cs).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return fs(u(this,k),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return fs(u(this,k),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,x(this,q,us).call(this),x(this,q,ls).call(this),u(this,k).removeObserver(this)}setOptions(t){let n=this.options,r=u(this,k);if(this.options=u(this,ue).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof ce(this.options.enabled,u(this,k))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");x(this,q,ds).call(this),u(this,k).setOptions(this.options),n._defaulted&&!Et(this.options,n)&&u(this,ue).getQueryCache().notify({type:"observerOptionsUpdated",query:u(this,k),observer:this});let s=this.hasListeners();s&&xi(u(this,k),r,this.options,n)&&x(this,q,Rn).call(this),this.updateResult(),s&&(u(this,k)!==r||ce(this.options.enabled,u(this,k))!==ce(n.enabled,u(this,k))||Se(this.options.staleTime,u(this,k))!==Se(n.staleTime,u(this,k)))&&x(this,q,is).call(this);let i=x(this,q,os).call(this);s&&(u(this,k)!==r||ce(this.options.enabled,u(this,k))!==ce(n.enabled,u(this,k))||i!==u(this,Ye))&&x(this,q,as).call(this,i)}getOptimisticResult(t){let n=u(this,ue).getQueryCache().build(u(this,ue),t),r=this.createResult(n,t);return du(this,r)&&(b(this,ae,r),b(this,qt,this.options),b(this,yt,u(this,k).state)),r}getCurrentResult(){return u(this,ae)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&u(this,Qe).status==="pending"&&u(this,Qe).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){u(this,Ut).add(t)}getCurrentQuery(){return u(this,k)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=u(this,ue).defaultQueryOptions(t),r=u(this,ue).getQueryCache().build(u(this,ue),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return x(this,q,Rn).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),u(this,ae)))}createResult(t,n){let r=u(this,k),s=this.options,i=u(this,ae),o=u(this,yt),a=u(this,qt),l=t!==r?t.state:u(this,Pn),{state:d}=t,m={...d},f=!1,p;if(n._optimisticResults){let O=this.hasListeners(),$=!O&&Ci(t,n),A=O&&xi(t,r,n,s);($||A)&&(m={...m,...ss(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(m.fetchStatus="idle")}let{error:y,errorUpdatedAt:g,status:h}=m;p=m.data;let v=!1;if(n.placeholderData!==void 0&&p===void 0&&h==="pending"){let O;i?.isPlaceholderData&&n.placeholderData===a?.placeholderData?(O=i.data,v=!0):O=typeof n.placeholderData=="function"?n.placeholderData(u(this,Dt)?.state.data,u(this,Dt)):n.placeholderData,O!==void 0&&(h="success",p=bn(i?.data,O,n),f=!0)}if(n.select&&p!==void 0&&!v)if(i&&p===o?.data&&n.select===u(this,Cn))p=u(this,Qt);else try{b(this,Cn,n.select),p=n.select(p),p=bn(i?.data,p,n),b(this,Qt,p),b(this,Je,null)}catch(O){b(this,Je,O)}u(this,Je)&&(y=u(this,Je),p=u(this,Qt),g=Date.now(),h="error");let P=m.fetchStatus==="fetching",M=h==="pending",X=h==="error",C=M&&P,F=p!==void 0,N={status:h,fetchStatus:m.fetchStatus,isPending:M,isSuccess:h==="success",isError:X,isInitialLoading:C,isLoading:C,data:p,dataUpdatedAt:m.dataUpdatedAt,error:y,errorUpdatedAt:g,failureCount:m.fetchFailureCount,failureReason:m.fetchFailureReason,errorUpdateCount:m.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:m.dataUpdateCount>l.dataUpdateCount||m.errorUpdateCount>l.errorUpdateCount,isFetching:P,isRefetching:P&&!M,isLoadingError:X&&!F,isPaused:m.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:X&&F,isStale:ps(t,n),refetch:this.refetch,promise:u(this,Qe),isEnabled:ce(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let O=N.data!==void 0,$=N.status==="error"&&!O,A=D=>{$?D.reject(N.error):O&&D.resolve(N.data)},I=()=>{let D=b(this,Qe,N.promise=wn());A(D)},Q=u(this,Qe);switch(Q.status){case"pending":t.queryHash===r.queryHash&&A(Q);break;case"fulfilled":($||N.data!==Q.value)&&I();break;case"rejected":(!$||N.error!==Q.reason)&&I();break}}return N}updateResult(){let t=u(this,ae),n=this.createResult(u(this,k),this.options);if(b(this,yt,u(this,k).state),b(this,qt,this.options),u(this,yt).data!==void 0&&b(this,Dt,u(this,k)),Et(n,t))return;b(this,ae,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!u(this,Ut).size)return!0;let o=new Set(i??u(this,Ut));return this.options.throwOnError&&o.add("error"),Object.keys(u(this,ae)).some(a=>{let c=a;return u(this,ae)[c]!==t[c]&&o.has(c)})};x(this,q,Ei).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&x(this,q,cs).call(this)}},ue=new WeakMap,k=new WeakMap,Pn=new WeakMap,ae=new WeakMap,yt=new WeakMap,qt=new WeakMap,Qe=new WeakMap,Je=new WeakMap,Cn=new WeakMap,Qt=new WeakMap,Dt=new WeakMap,_t=new WeakMap,vt=new WeakMap,Ye=new WeakMap,Ut=new WeakMap,q=new WeakSet,Rn=function(t){x(this,q,ds).call(this);let n=u(this,k).fetch(this.options,t);return t?.throwOnError||(n=n.catch(V)),n},is=function(){x(this,q,us).call(this);let t=Se(this.options.staleTime,u(this,k));if(Ae.isServer()||u(this,ae).isStale||!_n(t))return;let r=er(u(this,ae).dataUpdatedAt,t)+1;b(this,_t,Ee.setTimeout(()=>{u(this,ae).isStale||this.updateResult()},r))},os=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(u(this,k)):this.options.refetchInterval)??!1},as=function(t){x(this,q,ls).call(this),b(this,Ye,t),!(Ae.isServer()||ce(this.options.enabled,u(this,k))===!1||!_n(u(this,Ye))||u(this,Ye)===0)&&b(this,vt,Ee.setInterval(()=>{(this.options.refetchIntervalInBackground||Tt.isFocused())&&x(this,q,Rn).call(this)},u(this,Ye)))},cs=function(){x(this,q,is).call(this),x(this,q,as).call(this,x(this,q,os).call(this))},us=function(){u(this,_t)!==void 0&&(Ee.clearTimeout(u(this,_t)),b(this,_t,void 0))},ls=function(){u(this,vt)!==void 0&&(Ee.clearInterval(u(this,vt)),b(this,vt,void 0))},ds=function(){let t=u(this,ue).getQueryCache().build(u(this,ue),this.options);if(t===u(this,k))return;let n=u(this,k);b(this,k,t),b(this,Pn,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},Ei=function(t){U.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(u(this,ae))}),u(this,ue).getQueryCache().notify({query:u(this,k),type:"observerResultsUpdated"})})},Ti);function lu(e,t){return ce(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Ci(e,t){return lu(e,t)||e.state.data!==void 0&&fs(e,t,t.refetchOnMount)}function fs(e,t,n){if(ce(t.enabled,e)!==!1&&Se(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&ps(e,t)}return!1}function xi(e,t,n,r){return(e!==t||ce(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&ps(e,n)}function ps(e,t){return ce(t.enabled,e)!==!1&&e.isStaleByTime(Se(t.staleTime,e))}function du(e,t){return!Et(e.getCurrentResult(),t)}function Nt(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,l=async()=>{let d=!1,m=y=>{gi(y,()=>t.signal,()=>d=!0)},f=rr(t.options,t.fetchOptions),p=async(y,g,h)=>{if(d)return Promise.reject();if(g==null&&y.pages.length)return Promise.resolve(y);let P=(()=>{let F={client:t.client,queryKey:t.queryKey,pageParam:g,direction:h?"backward":"forward",meta:t.options.meta};return m(F),F})(),M=await f(P),{maxPages:X}=t.options,C=h?hi:mi;return{pages:C(y.pages,M,X),pageParams:C(y.pageParams,g,X)}};if(s&&i.length){let y=s==="backward",g=y?Ii:ms,h={pages:i,pageParams:o},v=g(r,h);a=await p(h,v,y)}else{let y=e??i.length;do{let g=c===0?o[0]??r.initialPageParam:ms(r,a);if(c>0&&g==null)break;a=await p(a,g),c++}while(c<y)}return a};t.options.persister?t.fetchFn=()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=l}}}function ms(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 Ii(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function Ai(e,t){return t?ms(e,t)!=null:!1}function ki(e,t){return!t||!e.getPreviousPageParam?!1:Ii(e,t)!=null}var hs=class extends xn{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:Nt()})}getOptimisticResult(e){return e.behavior=Nt(),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,l=o&&c==="forward",d=s&&c==="forward",m=o&&c==="backward",f=s&&c==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Ai(t,n.data),hasPreviousPage:ki(t,n.data),isFetchNextPageError:l,isFetchingNextPage:d,isFetchPreviousPageError:m,isFetchingPreviousPage:f,isRefetchError:a&&!l&&!m,isRefetching:i&&!d&&!f}}};var Tn,ke,se,bt,Oe,Xe,Oi,Mi=(Oi=class extends or{constructor(t){super();w(this,Oe);w(this,Tn);w(this,ke);w(this,se);w(this,bt);b(this,Tn,t.client),this.mutationId=t.mutationId,b(this,se,t.mutationCache),b(this,ke,[]),this.state=t.state||gs(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){u(this,ke).includes(t)||(u(this,ke).push(t),this.clearGcTimeout(),u(this,se).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){b(this,ke,u(this,ke).filter(n=>n!==t)),this.scheduleGc(),u(this,se).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){u(this,ke).length||(this.state.status==="pending"?this.scheduleGc():u(this,se).remove(this))}continue(){return u(this,bt)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{x(this,Oe,Xe).call(this,{type:"continue"})},r={client:u(this,Tn),meta:this.options.meta,mutationKey:this.options.mutationKey};b(this,bt,ir({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(o,a)=>{x(this,Oe,Xe).call(this,{type:"failed",failureCount:o,error:a})},onPause:()=>{x(this,Oe,Xe).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>u(this,se).canRun(this)}));let s=this.state.status==="pending",i=!u(this,bt).canStart();try{if(s)n();else{x(this,Oe,Xe).call(this,{type:"pending",variables:t,isPaused:i}),u(this,se).config.onMutate&&await u(this,se).config.onMutate(t,this,r);let a=await this.options.onMutate?.(t,r);a!==this.state.context&&x(this,Oe,Xe).call(this,{type:"pending",context:a,variables:t,isPaused:i})}let o=await u(this,bt).start();return await u(this,se).config.onSuccess?.(o,t,this.state.context,this,r),await this.options.onSuccess?.(o,t,this.state.context,r),await u(this,se).config.onSettled?.(o,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(o,null,t,this.state.context,r),x(this,Oe,Xe).call(this,{type:"success",data:o}),o}catch(o){try{await u(this,se).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 u(this,se).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 x(this,Oe,Xe).call(this,{type:"error",error:o}),o}finally{u(this,se).runNext(this)}}},Tn=new WeakMap,ke=new WeakMap,se=new WeakMap,bt=new WeakMap,Oe=new WeakSet,Xe=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),U.batch(()=>{u(this,ke).forEach(r=>{r.onMutationUpdate(t)}),u(this,se).notify({mutation:this,type:"updated",action:t})})},Oi);function gs(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var De,Re,En,Fi,qi=(Fi=class extends ge{constructor(t={}){super();w(this,De);w(this,Re);w(this,En);this.config=t,b(this,De,new Set),b(this,Re,new Map),b(this,En,0)}build(t,n,r){let s=new Mi({client:t,mutationCache:this,mutationId:++yn(this,En)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){u(this,De).add(t);let n=ar(t);if(typeof n=="string"){let r=u(this,Re).get(n);r?r.push(t):u(this,Re).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(u(this,De).delete(t)){let n=ar(t);if(typeof n=="string"){let r=u(this,Re).get(n);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&u(this,Re).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=ar(t);if(typeof n=="string"){let s=u(this,Re).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=ar(t);return typeof n=="string"?u(this,Re).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){U.batch(()=>{u(this,De).forEach(t=>{this.notify({type:"removed",mutation:t})}),u(this,De).clear(),u(this,Re).clear()})}getAll(){return Array.from(u(this,De))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>nr(n,r))}findAll(t={}){return this.getAll().filter(n=>nr(t,n))}notify(t){U.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){let t=this.getAll().filter(n=>n.state.isPaused);return U.batch(()=>Promise.all(t.map(n=>n.continue().catch(V))))}},De=new WeakMap,Re=new WeakMap,En=new WeakMap,Fi);function ar(e){return e.options.scope?.id}var Ue,Ze,le,Ne,Ke,cr,ys,Qi,_s=(Qi=class extends ge{constructor(t,n){super();w(this,Ke);w(this,Ue);w(this,Ze);w(this,le);w(this,Ne);b(this,Ue,t),this.setOptions(n),this.bindMethods(),x(this,Ke,cr).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let n=this.options;this.options=u(this,Ue).defaultMutationOptions(t),Et(this.options,n)||u(this,Ue).getMutationCache().notify({type:"observerOptionsUpdated",mutation:u(this,le),observer:this}),n?.mutationKey&&this.options.mutationKey&&Ie(n.mutationKey)!==Ie(this.options.mutationKey)?this.reset():u(this,le)?.state.status==="pending"&&u(this,le).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||u(this,le)?.removeObserver(this)}onMutationUpdate(t){x(this,Ke,cr).call(this),x(this,Ke,ys).call(this,t)}getCurrentResult(){return u(this,Ze)}reset(){u(this,le)?.removeObserver(this),b(this,le,void 0),x(this,Ke,cr).call(this),x(this,Ke,ys).call(this)}mutate(t,n){return b(this,Ne,n),u(this,le)?.removeObserver(this),b(this,le,u(this,Ue).getMutationCache().build(u(this,Ue),this.options)),u(this,le).addObserver(this),u(this,le).execute(t)}},Ue=new WeakMap,Ze=new WeakMap,le=new WeakMap,Ne=new WeakMap,Ke=new WeakSet,cr=function(){let t=u(this,le)?.state??gs();b(this,Ze,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},ys=function(t){U.batch(()=>{if(u(this,Ne)&&this.hasListeners()){let n=u(this,Ze).variables,r=u(this,Ze).context,s={client:u(this,Ue),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{u(this,Ne).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{u(this,Ne).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{u(this,Ne).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{u(this,Ne).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(u(this,Ze))})})},Qi);var Me,Di,Ui=(Di=class extends ge{constructor(t={}){super();w(this,Me);this.config=t,b(this,Me,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??vn(s,n),o=this.get(i);return o||(o=new Ri({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(o)),o}add(t){u(this,Me).has(t.queryHash)||(u(this,Me).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=u(this,Me).get(t.queryHash);n&&(t.destroy(),n===t&&u(this,Me).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){U.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return u(this,Me).get(t)}getAll(){return[...u(this,Me).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>tr(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>tr(t,r)):n}notify(t){U.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){U.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){U.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Me=new WeakMap,Di);var H,et,tt,Kt,Lt,nt,jt,Bt,Ni,vs=(Ni=class{constructor(e={}){w(this,H);w(this,et);w(this,tt);w(this,Kt);w(this,Lt);w(this,nt);w(this,jt);w(this,Bt);b(this,H,e.queryCache||new Ui),b(this,et,e.mutationCache||new qi),b(this,tt,e.defaultOptions||{}),b(this,Kt,new Map),b(this,Lt,new Map),b(this,nt,0)}mount(){yn(this,nt)._++,u(this,nt)===1&&(b(this,jt,Tt.subscribe(async e=>{e&&(await this.resumePausedMutations(),u(this,H).onFocus())})),b(this,Bt,Mt.subscribe(async e=>{e&&(await this.resumePausedMutations(),u(this,H).onOnline())})))}unmount(){var e,t;yn(this,nt)._--,u(this,nt)===0&&((e=u(this,jt))==null||e.call(this),b(this,jt,void 0),(t=u(this,Bt))==null||t.call(this),b(this,Bt,void 0))}isFetching(e){return u(this,H).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return u(this,et).findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return u(this,H).get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=u(this,H).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Se(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return u(this,H).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=u(this,H).get(r.queryHash)?.state.data,o=fi(t,i);if(o!==void 0)return u(this,H).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return U.batch(()=>u(this,H).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return u(this,H).get(t.queryHash)?.state}removeQueries(e){let t=u(this,H);U.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=u(this,H);return U.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=U.batch(()=>u(this,H).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(V).catch(V)}invalidateQueries(e,t={}){return U.batch(()=>(u(this,H).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=U.batch(()=>u(this,H).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(V)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(V)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=u(this,H).build(this,t);return n.isStaleByTime(Se(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(V).catch(V)}fetchInfiniteQuery(e){return e.behavior=Nt(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(V).catch(V)}ensureInfiniteQueryData(e){return e.behavior=Nt(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Mt.isOnline()?u(this,et).resumePausedMutations():Promise.resolve()}getQueryCache(){return u(this,H)}getMutationCache(){return u(this,et)}getDefaultOptions(){return u(this,tt)}setDefaultOptions(e){b(this,tt,e)}setQueryDefaults(e,t){u(this,Kt).set(Ie(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...u(this,Kt).values()],n={};return t.forEach(r=>{ft(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){u(this,Lt).set(Ie(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...u(this,Lt).values()],n={};return t.forEach(r=>{ft(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...u(this,tt).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=vn(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===It&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...u(this,tt).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){u(this,H).clear(),u(this,et).clear()}},H=new WeakMap,et=new WeakMap,tt=new WeakMap,Kt=new WeakMap,Lt=new WeakMap,nt=new WeakMap,jt=new WeakMap,Bt=new WeakMap,Ni);var $t=J(oe(),1),Li=J(ur(),1),bs=$t.createContext(void 0),j=e=>{let t=$t.useContext(bs);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},In=({client:e,children:t})=>($t.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,Li.jsx)(bs.Provider,{value:e,children:t}));var lr=J(oe(),1),ji=lr.createContext(!1),Bi=()=>lr.useContext(ji),yf=ji.Provider;var An=J(oe(),1),fu=J(ur(),1);function pu(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var mu=An.createContext(pu()),$i=()=>An.useContext(mu);var Vi=J(oe(),1);var Hi=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?At(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Wi=e=>{Vi.useEffect(()=>{e.clearReset()},[e])},Gi=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||At(n,[e.error,r]));var zi=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))}},Ji=(e,t)=>e.isLoading&&e.isFetching&&!t,Yi=(e,t)=>e?.suspense&&t.isPending,ws=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var rt=J(oe(),1);function dr(e,t,n){let r=Bi(),s=$i(),i=j(n),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let a=i.getQueryCache().get(o.queryHash);o._optimisticResults=r?"isRestoring":"optimistic",zi(o),Hi(o,s,a),Wi(s);let c=!i.getQueryCache().get(o.queryHash),[l]=rt.useState(()=>new t(i,o)),d=l.getOptimisticResult(o),m=!r&&e.subscribed!==!1;if(rt.useSyncExternalStore(rt.useCallback(f=>{let p=m?l.subscribe(U.batchCalls(f)):V;return l.updateResult(),p},[l,m]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),rt.useEffect(()=>{l.setOptions(o)},[o,l]),Yi(o,d))throw ws(o,l,s);if(Gi({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&&!Ae.isServer()&&Ji(d,r)&&(c?ws(o,l,s):a?.promise)?.catch(V).finally(()=>{l.updateResult()}),o.notifyOnChangeProps?d:l.trackResult(d)}function K(e,t){return dr(e,xn,t)}var Le=J(oe(),1);function pe(e,t){let n=j(t),[r]=Le.useState(()=>new _s(n,e));Le.useEffect(()=>{r.setOptions(e)},[r,e]);let s=Le.useSyncExternalStore(Le.useCallback(o=>r.subscribe(U.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=Le.useCallback((o,a)=>{r.mutate(o,a).catch(V)},[r]);if(s.error&&At(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function kn(e,t){return dr(e,hs,t)}var eo=J(Zi(),1),On=typeof window<"u"&&window.__FSAOS_CONFIG__||{},Mn=Array.isArray(On.sources)?On.sources:[],hu=On.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",gu=On.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",_e=On.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",L=(0,eo.createClient)(hu,gu,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var qn=null,fr=0,to,Ps,pr=!1;to=new Promise(e=>{Ps=e});L.auth.onAuthStateChange((e,t)=>{t?.access_token?(qn=t.access_token,fr=t.expires_at??Math.floor(Date.now()/1e3)+3600):(qn=null,fr=0),pr||(pr=!0,Ps())});setTimeout(()=>{pr||(pr=!0,Ps())},5e3);function no(e,t){qn=e,fr=t??Math.floor(Date.now()/1e3)+3600}function Cs(){qn=null,fr=0}async function je(){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 to,qn}var mr=null,gr=null,ro=0,Ss=new Set,xs,Ts,hr=!1;xs=new Promise(e=>{Ts=e});function so(){ro++,Ss.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function st(e){let t=typeof e=="string"?e:e.path,n=mr!==t;mr=t,gr=typeof e=="string"?null:e,typeof e!="string"&&!ve.some(r=>r.id===e.id)&&(ve=[...ve,e],Nn()),hr||(hr=!0,Ts()),n&&so()}function Qn(){return mr}function Pe(){return gr}function Es(){return ro}function Is(e){return Ss.add(e),()=>{Ss.delete(e)}}function Dn(){return xs}function As(){return hr}var Ht=null;function Un(e){if(Ht){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}Ht=e,st(e)}function it(){return Ht}var ve=[],Rs=new Set,io=0;function Nn(){io++,Rs.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function Wt(){return ve}function Kn(){return io}function yr(e){return Rs.add(e),()=>{Rs.delete(e)}}function ks(e){ve=e,Nn()}function oo(e){ve.some(t=>t.id===e.id)||(ve=[...ve,e],Nn())}function ao(e){ve.find(n=>n.id===e)&&(ve=ve.filter(n=>n.id!==e),Nn(),gr?.id===e&&Ht&&st(Ht))}var Vt=null,Fn=null;async function Gt(){return Vt||Fn||(Fn=(async()=>{let e=St(),t=await je(),n={};t&&(n.Authorization=`Bearer ${t}`);let r=await fetch(`${_e}/d/${e}/init`,{method:"GET",headers:n});if(!r.ok)throw new Error(`Session init failed: ${r.status} ${r.statusText}`);let s=await r.json(),i=s.entry||s;return Vt={scope_id:i.scope_id,scope_path:i.scope_path,instance_path:i.instance_path||"/root",fractal_id:i.fractal_id||null,instance_name:i.instance_name||null,display_name:i.scope_display_name||i.display_name||null,principal_id:i.principal_id||null},Vt})(),Fn)}function wt(){return Vt}function Os(){Vt=null,Fn=null,mr=null,gr=null,Ht=null,ve=[]}var co=[];function Be(e){co.push(e)}function zt(){Os(),Cs(),hr=!1,xs=new Promise(e=>{Ts=e}),so(),Nn();for(let e of co)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function St(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var uo=st,te=Qn,ne=Es,Ce=Is,lo=Dn,_r=As;var Ms=0,fo=!1,po=0;function mo(e){if(typeof e!="string")return;let t=Date.parse(e);Number.isNaN(t)||(Ms=t-Date.now(),fo=!0,po=Date.now())}function vr(){return Date.now()+Ms}function ho(){return fo}function go(){return Ms}function yo(){return po}function _o(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:vr()>=t}function vo(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Math.max(0,t-vr())}var yu=new Set(["list-memberships","init"]),ot=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);Y(this,"name","GatewayRequestError");Y(this,"method");Y(this,"status");Y(this,"statusText");Y(this,"payload");Y(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={}){let n=St(),r=`${_e}/d/${n}`,s={"Content-Type":"application/json"},i=await je();i&&(s.Authorization=`Bearer ${i}`),!yu.has(e)&&!t._scope_path&&await Dn();let o={...t},a=wt();!o.domain_scope_id&&a?.scope_id&&(o.domain_scope_id=a.scope_id);let c=Qn();!o._scope_path&&c&&(o._scope_path=c);let l=await fetch(r,{method:"POST",headers:s,body:JSON.stringify({method:e,params:o})}),d=await l.text(),m=null;if(d)try{m=JSON.parse(d)}catch{}if(!l.ok||!m)throw new ot({method:e,status:l.status,statusText:l.statusText,payload:m,responseBody:d});if(m.success===!1){let f=m.error||"",p=m.denied_by||m.error_type||"";throw p==="rule"||p==="access"||p==="entitlement"||f==="RULE_DENIED"||f==="ACCESS_DENIED"||f==="PERMISSION_DENIED"||f==="ENTITLEMENT_REQUIRED"?new Ct(m):new ot({method:e,status:l.status,statusText:l.statusText,payload:m,responseBody:d})}return m&&m.server_now!==void 0&&mo(m.server_now),m}var _=J(oe(),1),Ku=J(wo(),1),Lu=J(ur(),1);var So=new WeakMap;function $e(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(m=>m.promise?[m.promise]:[]);if(i.length===0)return s();let o=`${r?"=":"^"}${JSON.stringify(t)}`,a=So.get(e);a||(a=new Map,So.set(e,a));let c=a.get(o);if(c)return c;let l=a,d=Promise.allSettled(i).then(()=>(l.delete(o),s()));return l.set(o,d),d}function at(e,t){return typeof e=="string"&&(e===t||e.startsWith(`${t}/`))}var br=new WeakMap,Ro=e=>e.meta?.arrangementRealtime===!0;function Jt(e,t){let n=e.getQueryCache().find({queryKey:t,exact:!0});if(!n)return;let r=br.get(e);r||(r=new Map,br.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&&$e(e,t,{exact:!0})},250))}function Po(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){if(!Ro(n))continue;let r=n.state.data;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)))&&Jt(e,n.queryKey)}}function Co(e){for(let t of e.getQueryCache().getAll())Ro(t)&&t.state.data!==void 0&&Jt(e,t.queryKey)}function xo(e){br.get(e)?.forEach(clearTimeout),br.delete(e)}var Yt=null;function To(e){if(Yt&&Yt!==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.");Yt=e}function T(){return Yt||(Yt=new vs({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),Yt}var Eo=new Proxy({},{get(e,t,n){let r=T(),s=r[t];return typeof s=="function"?s.bind(r):s}});var wr=new WeakMap;function Fs(e){return e.meta?.infiniteItemsRealtime?.filter}function _u(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 vu(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 bu(e,t,n){if(_u(e,n))return!0;let r=t.scope,s=typeof r=="string"&&r!=="__unscoped__",i=typeof n.path=="string"||typeof n.old_path=="string";if(s&&i&&!at(n.path,r)&&!at(n.old_path,r))return!1;if(n.item_type==="symlink"&&s&&i)return!0;let o=vu(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 Io(e,t){let n=wr.get(e);n||(n=new Map,wr.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||!Fs(t))&&$e(e,t.queryKey,{exact:!0})},500))}function Ao(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){let r=Fs(n);r&&bu(n,r,t)&&Io(e,n)}}function ko(e){for(let t of e.getQueryCache().getAll())Fs(t)&&t.state.data!==void 0&&Io(e,t)}function Oo(e){wr.get(e)?.forEach(clearTimeout),wr.delete(e)}function ee(){return te()??"__unscoped__"}var S={all:()=>["vfs",ee()],item:e=>["vfs",ee(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",ee(),"children",e],allChildren:()=>["vfs",ee(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",ee(),"search",e,...t??[]],items:(e,t)=>["vfs",ee(),"items",e,JSON.stringify(t??{})],allItems:()=>["vfs",ee(),"items"],tree:(e,t)=>["vfs",ee(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",ee(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",ee(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",ee(),"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",ee(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",ee(),"channel-messages"],channels:e=>["vfs",ee(),"channels",e??"all"],allChannels:()=>["vfs",ee(),"channels"],notifications:(e,t)=>["vfs",ee(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",ee(),"notifications"],unreadCounts:()=>["vfs",ee(),"unread-counts"],memberships:e=>["memberships",e]};var wu=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function W(...e){wu&&console.log("[WS]",...e)}var E=null,Xt=null,en=null,Ln=0,Su=3e4,Mo=1e4,nn=!1,Fo=!1,No=3e4,Ru=No*2+5e3,Sr=0,Rr=null,qo=!1;function Pu(){Bn(),Sr=Date.now(),Rr=setInterval(()=>{if(E&&E.readyState===WebSocket.OPEN&&Date.now()-Sr>Ru){W("ping: no inbound traffic for",Date.now()-Sr,"ms \u2014 closing half-open socket");try{E.close(4e3,"liveness timeout")}catch{}return}He({type:"ping"})},No)}function Bn(){Rr&&(clearInterval(Rr),Rr=null)}function Cu(){typeof document>"u"||(document.hidden?Bn():jn()&&(W("Tab visible, reconnecting..."),Rt()))}function xu(){qo||typeof document>"u"||(document.addEventListener("visibilitychange",Cu),qo=!0)}var me={};function Qs(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return!n||!r?n===r:r===n||r.startsWith(`${n}/`)}var tn=[],Ve=new Map,Zt=new Map,be=new Map;function Tu(e){let t=Zt.get(e);return t?Array.from(new Set(Array.from(t.values()).flatMap(n=>n.event_types))).sort():[]}function Qo(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):!1}function Do(e){let t=Tu(e);if(t.length===0)return Ve.delete(e),null;let n={scope_id:e,event_types:t};return Ve.set(e,n),n}var Fe=new Map,ct=new Map,qs="disconnected",Pr=[];function Cr(e){if(qs!==e){qs=e;for(let t of[...Pr])try{t(e)}catch{}}}function Eu(e){Fe.set(e,"ready");let t=ct.get(e);if(t){ct.delete(e);for(let n of t)n()}}function Iu(){for(let e of Fe.keys())Fe.set(e,"disconnected")}function Ds(e,t){Fe.set(e,"pending"),He({type:"subscribe_path",path:e,event_types:t})}function Au(){return Object.keys(me).some(t=>me[t]&&me[t].length>0)||tn.length>0}function jn(){return Ve.size>0||be.size>0}async function Rt(){if(!jn()){W("ensureConnection: no active subscriptions, skipping");return}if(E&&E.readyState===WebSocket.OPEN){W("ensureConnection: already open");return}if(Xt)return W("ensureConnection: connection already in flight, waiting..."),Xt;if(E){W("ensureConnection: killing stale WS in state",E.readyState);try{E.close()}catch{}E=null}return nn=!1,Xt=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=_e,n=await je();if(!n){W("ensureConnection: no token available, will retry"),Uo();return}let r=t.startsWith("https")?"wss":"ws",s=t.replace(/^https?:\/\//,""),i=`${r}://${s}/ws`;i+=`?token=${encodeURIComponent(n)}`,W("ensureConnection: opening WS to",i.substring(0,50)+"..."),Cr("connecting"),E=new WebSocket(i);let o=E;await new Promise((a,c)=>{if(!E)return c(new Error("WebSocket not created"));let l=setTimeout(()=>{if(E===o){if(W("ensureConnection: TIMEOUT after",Mo,"ms"),E&&E.readyState!==WebSocket.OPEN){try{E.close()}catch{}E=null}c(new Error("WebSocket connection timeout"))}},Mo);o.onopen=()=>{if(E!==o)return;clearTimeout(l),W("ensureConnection: CONNECTED");let d=Fo;Fo=!0,Ln=0,Cr("connected"),ku(d),(typeof document>"u"||!document.hidden)&&Pu(),xu(),a()},o.onmessage=d=>{E===o&&Ou(d.data)},o.onerror=()=>{W("ensureConnection: WS error event")},o.onclose=d=>{clearTimeout(l),E===o&&(W("ensureConnection: WS closed, code:",d.code,"reason:",d.reason),E=null,Bn(),Iu(),Cr("disconnected"),!nn&&jn()&&Uo(),c(new Error(`WebSocket closed: ${d.code}`)))}})}catch(e){W("ensureConnection: failed -",e?.message||e)}finally{Xt=null}})(),Xt}function Uo(){if(en||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,Ln)+Math.random()*1e3,Su);Ln++,W("scheduleReconnect: attempt",Ln,"in",Math.round(e),"ms"),en=setTimeout(()=>{en=null,jn()&&Rt()},e)}function ku(e=!1){for(let t of Ve.values())W("resubscribeAll: scope",t.scope_id),He({type:"subscribe",scope_id:t.scope_id,event_types:t.event_types});for(let t of be.values())W("resubscribeAll: path",t.path),Ds(t.path,t.event_types);if(e)try{let t=T();ko(t),Co(t);for(let n of be.values())t.invalidateQueries({queryKey:S.item(n.path)}),t.invalidateQueries({queryKey:S.children(n.path)});W("resubscribeAll: invalidated",be.size,"paths after reconnect")}catch(t){W("resubscribeAll: cache invalidation skipped",t)}}function He(e){E&&E.readyState===WebSocket.OPEN&&E.send(JSON.stringify(e))}function Ou(e){Sr=Date.now();try{let t=JSON.parse(e);if(t.type==="subscribed_path"){typeof t.path=="string"&&Eu(t.path);return}if(t.type==="subscribed"||t.type==="unsubscribed"||t.type==="unsubscribed_path"||t.type==="pong")return;if(t.type==="error"){console.warn("[WS] Server error:",t.message);return}if(t.type==="event"||t.event_type){let n=t.event_type||"message",r=t.data||t;if(n==="vfs_change"&&(Ao(T(),r),Po(T(),r)),typeof r.path=="string")for(let[s,i]of Object.entries(me))s!=="*"&&Qs(s,r.path)&&i.forEach(o=>o(r));me["*"]&&me["*"].forEach(s=>s(r));for(let s of tn)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function Us(){!Au()&&Ve.size===0&&be.size===0&&E&&(nn=!0,Bn(),E.close(),E=null,nn=!1)}function xr(e,t){return me[e]||(me[e]=[]),me[e].push(t),be.has(e)||(be.set(e,{path:e,event_types:["token_stream"]}),E&&E.readyState===WebSocket.OPEN?Ds(e,["token_stream"]):Fe.set(e,"pending")),Rt(),()=>{let n=me[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete me[e],be.delete(e),Fe.delete(e),ct.delete(e),He({type:"unsubscribe_path",path:e}))}Us()}}function re(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return tn.push(...s),jn()&&Rt(),()=>{for(let i of s){let o=tn.indexOf(i);o!==-1&&tn.splice(o,1)}Us()}}function rn(e,t=["vfs_change","ccm_change"]){let n=Symbol(e),r=Array.from(new Set(t)).sort();if(r.length===0)return()=>{};let s=Zt.get(e)??new Map,i=Ve.get(e)?.event_types;s.set(n,{event_types:r}),Zt.set(e,s);let o=Do(e);if(!o)return()=>{};W("subscribeToScope:",e,o.event_types),E&&E.readyState===WebSocket.OPEN&&!Qo(i,o.event_types)&&He({type:"subscribe",scope_id:e,event_types:o.event_types}),Rt();let a=!0;return()=>{if(!a)return;a=!1;let c=Zt.get(e);if(!c?.delete(n))return;let l=Ve.get(e)?.event_types;if(c.size===0)Zt.delete(e),Ve.delete(e),He({type:"unsubscribe",scope_id:e});else{let d=Do(e);d&&E&&E.readyState===WebSocket.OPEN&&!Qo(l,d.event_types)&&He({type:"subscribe",scope_id:e,event_types:d.event_types})}Us()}}function Ko(e,t,n={}){He({type:"emit",scope_id:e,event_type:t,payload:n})}function Ns(){W("disconnectSSE: tearing down"),Oo(T()),xo(T()),nn=!0,Bn(),E&&(E.close(),E=null),en&&(clearTimeout(en),en=null),Xt=null,nn=!1,Ln=0;for(let e of Object.keys(me))delete me[e];tn.length=0,Ve.clear(),Zt.clear(),be.clear(),Fe.clear(),ct.clear(),Cr("disconnected")}function Lo(){He({type:"ping"})}function jo(e){return be.has(e)?Fe.get(e)??"pending":"unsubscribed"}function Bo(e,t=5e3){return be.has(e)?Fe.get(e)==="ready"&&E&&E.readyState===WebSocket.OPEN?Promise.resolve(!0):(Rt(),new Promise(n=>{let r=!1,s=ct.get(e)??[],i=()=>{r||(r=!0,clearTimeout(o),n(!0))};s.push(i),ct.set(e,s);let o=setTimeout(()=>{if(r)return;r=!0;let a=ct.get(e);if(a){let c=a.indexOf(i);c!==-1&&a.splice(c,1),a.length===0&&ct.delete(e)}n(!1)},t)})):Promise.resolve(!1)}function $o(e){let t=be.get(e);if(!t){W("resubscribePath: no active subscription for",e);return}E&&E.readyState===WebSocket.OPEN?(W("resubscribePath: re-sending frame for",e),Ds(t.path,t.event_types)):(Fe.set(e,"pending"),Rt())}function Vo(e){Pr.push(e);try{e(qs)}catch{}return()=>{let t=Pr.indexOf(e);t!==-1&&Pr.splice(t,1)}}Be(Ns);function Ho(){return new Date().toISOString()}function Wo(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function we(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||Ho(),updated_at:e.updated_at||Ho(),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 $n(e){return(e.content?.items||e.items||[]).map(we)}async function Er(e){try{let t=await R("read",{id:e});if(t.item_name||t.item_path){let r=we(t);return r.path&&T().setQueryData(S.item(r.path),r),r}let n=t.item;if(n){let r=we(n);return r.path&&T().setQueryData(S.item(r.path),r),r}return null}catch{return null}}async function Ir(e){try{let t=await R("read",{path:e});if(t.item_name||t.item_path)return we(t);let n=t.item;return n?we(n):null}catch{return null}}async function Vn(e){try{let t=await R("list",{path:e,limit:200}),n=$n(t);for(let r of n)T().setQueryData(S.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function Go(e,t){let{items:n}=await on({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 Ar(e,t,n){try{let r=await R("list",{path:e,limit:t,offset:n}),s=$n(r);for(let i of s)T().setQueryData(S.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 kr(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 Or(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||Wo(),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||Wo(),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 Mr(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=$n(i);for(let a of o)T().setQueryData(S.item(a.path),a);return o}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function Fr(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 Hn(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 qr(e,t=50,n=0){return Hn(e,{limit:t,offset:n})}async function Qr(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=$n(s);for(let o of i)T().setQueryData(S.item(o.path),o);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${e}:`,r),[]}}async function Dr(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 sn(e){return!!e&&(!!e.type||Array.isArray(e.any_of)&&e.any_of.length>0)}function Mu(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 Fu=["catalog","parent_only","internal"];function zo(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[l,d]of Object.entries(o))l.startsWith("field.")&&l.length>6&&n(d)?a[l.slice(6)]=d:l.startsWith("field_in.")&&l.length>9&&Array.isArray(d)&&(c[l.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"&&Fu.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,l={};typeof c.item_type=="string"&&c.item_type&&(l.item_type=c.item_type);let d=r(c);Object.keys(d.fields).length&&(l.fields=d.fields),Object.keys(d.field_in).length&&(l.field_in=d.field_in),Object.keys(l).length&&o.push(l)}o.length&&(s.any_of=o)}return sn(s)?{...s,...t}:null}async function on(e,t={}){let n={};e.type&&(n.item_type=e.type),e.scope&&(n.scope_path=e.scope);let r={};if(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(Mu)),Object.keys(r).length>0&&(n.filters=r),e.limit!=null&&(n.limit=e.limit);try{let s=await R("query",n),i=$n(s);for(let o of i)T().setQueryData(S.item(o.path),o);return{items:i,total_hint:s.total??s.content?.total??i.length}}catch(s){if(console.error(`[gateway] Failed to fetch items of type ${e.type??"(any_of)"}:`,s),t.throwOnError)throw s;return{items:[],total_hint:0}}}function qu(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 Jo(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:qu(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 Ks(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,reply_count:n.reply_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 Yo(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 Ks(i)}catch(n){return console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),[]}}async function Ur(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=Ks(i),a=Jo(i),c=new Map,l=[];for(let d of a)if(d.parentMessagePath){let m=c.get(d.parentMessagePath)||[];m.push(d),c.set(d.parentMessagePath,m)}else l.push(d);return{messages:o,messageCards:c,siblingCards:l,mode:s.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages with cards for ${e}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}async function Wn(e,t){try{let n={channel_path:e};t?.parentMessageId&&(n.parent_message_id=t.parentMessageId),t?.limit&&(n.limit=t.limit),t?.before_seq!=null&&(n.before_seq=t.before_seq),t?.after_seq!=null&&(n.after_seq=t.after_seq);let s=await R("get-channel-messages",n),i=s.messages||[],o=Jo(i),a=new Map,c=[];for(let l of o)if(l.parentMessagePath){let d=a.get(l.parentMessagePath)||[];d.push(l),a.set(l.parentMessagePath,d)}else c.push(l);return{messages:Ks(i),messageCards:a,siblingCards:c,mode:s.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages page for ${e}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}function Tr(e){T().invalidateQueries({queryKey:S.children(e)})}function Ls(e){T().invalidateQueries({queryKey:S.item(e)})}function Xo(e,t){Ls(e),Tr(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&Tr(r)}function Zo(e){let t=e+"/";T().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function ea(){T().invalidateQueries({queryKey:S.all()})}function ta(e){T().invalidateQueries({queryKey:S.types(e)})}function na(e,t){e?T().invalidateQueries({queryKey:S.channelMessages(e,t)}):T().invalidateQueries({queryKey:S.allChannelMessages()})}function ra(e,t){e&&t?T().invalidateQueries({queryKey:S.openEnvelope(e,t)}):e?T().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):T().invalidateQueries({queryKey:S.allOpenEnvelopes()})}function Qu(e){return`${e}/settings/mounts`}var Gn=null;async function js(e,t){Gn=Qu(e);try{let s=((await R("read",{path:Gn}))?.item?.type_data?.mounts??[]).map(t).filter(o=>o!==null),i=it();return i&&!s.some(o=>o.id===i.id)&&s.unshift(i),ks(s),s}catch{let n=it(),r=n?[n]:[];return ks(r),r}}async function sa(){if(!Gn)return;let e=Wt().map(n=>n.id),t=Pe()?.id??null;try{await R("update",{path:Gn,type_data:{mounts:e,last_anchor:t}})}catch{try{let r=Gn.split("/").slice(0,-1).join("/");await R("create",{parent_path:r,name:"mounts",item_type:"file",type_data:{mounts:e,last_anchor:t}})}catch(r){console.warn("[SDK] mount declaration persist failed:",r)}}}async function Bs(e){oo(e),await sa()}async function ia(e){ao(e),await sa()}var an=new Map,Nr=null,Kr=null,ut=new Map,oa=250;function zn(e){Lr(),Jn(e),Nr=re("vfs_change",t=>Du(t)),Kr=re("ccm_change",t=>Uu(t))}function Jn(e){if(an.has(e))return;let t=rn(e,["vfs_change","ccm_change"]);an.set(e,t)}function aa(e){let t=an.get(e);t&&(t(),an.delete(e))}function Lr(){for(let[,e]of an)e();an.clear(),Nr&&(Nr(),Nr=null),Kr&&(Kr(),Kr=null),ut.forEach(e=>clearTimeout(e)),ut.clear()}Be(Lr);function Du(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=ut.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{ut.delete(s),Nu(n,t,e,s)},oa);ut.set(s,o)}function Uu(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))return;let s=`ccm:${t??""}:${n??""}`,i=ut.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{ut.delete(s),t&&T().invalidateQueries({queryKey:S.edges(t)}),n&&T().invalidateQueries({queryKey:S.edges(n)}),!t&&!n&&T().invalidateQueries({predicate:a=>a.queryKey[0]==="vfs"&&a.queryKey[1]==="edges"})},oa);ut.set(s,o)}function Nu(e,t,n,r){if((e||"").toUpperCase()==="DELETE")T().removeQueries({queryKey:S.item(t)}),T().removeQueries({queryKey:S.children(t)}),T().removeQueries({queryKey:S.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=we(i);o&&o.id&&T().setQueryData(S.item(t),o)}catch{}T().invalidateQueries({queryKey:S.children(r)}),T().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&&T().invalidateQueries({queryKey:S.itemById(n.item_id)})}function G(){return(0,_.useSyncExternalStore)(Ce,ne,ne)}function la(){return G(),_r()}function da(e){return G(),K({queryKey:S.item(e),queryFn:()=>Ir(e),enabled:!!e,staleTime:1/0})}function fa(e){return G(),K({queryKey:S.itemById(e),queryFn:()=>Er(e),enabled:!!e,staleTime:1/0})}function Vs(e){return G(),K({queryKey:S.children(e),queryFn:()=>Vn(e),enabled:!!e})}function pa(e){let t=Vs(e);return{...t,children:t.data??[]}}function ma(e,t=1){return G(),K({queryKey:S.tree(e,t),queryFn:()=>Mr(e,t),enabled:!!e})}function ha(e,t){return G(),K({queryKey:S.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(we)},enabled:!!e&&e.length>0})}function ga(e){G();let t=(0,_.useMemo)(()=>e,[JSON.stringify(e)]);return K({queryKey:["vfs",te()??"__unscoped__","resolve",JSON.stringify(t??{})],queryFn:async()=>await R("resolve",t),enabled:!!t?.query&&t.query.length>0})}function ya(e){G();let t=(0,_.useMemo)(()=>e,[JSON.stringify(e)]);return K({queryKey:S.items(t?.type??"",t),queryFn:()=>on(t),enabled:sn(t),select:n=>n.items})}function _a(e,t={}){let n=G(),{realtime:r=!1}=t,s=e?.limit??20,i=(0,_.useMemo)(()=>e,[JSON.stringify(e)]),o=(0,_.useMemo)(()=>["vfs",te()??"__unscoped__","infinite-items",i?.type??"",JSON.stringify(i??{})],[n,i]),a=kn({queryKey:o,queryFn:async({pageParam:l=0})=>on({...i,limit:s,offset:l},{throwOnError:!0}),initialPageParam:0,getNextPageParam:(l,d,m)=>{if(!(l.items.length<s))return m+l.items.length},enabled:sn(i),staleTime:r?1/0:void 0,meta:r&&i?{infiniteItemsRealtime:{filter:i}}:{}});return{allItems:(0,_.useMemo)(()=>{if(!a.data?.pages)return[];let l=new Set,d=[];for(let m of a.data.pages)for(let f of m.items)f.id&&!l.has(f.id)&&(l.add(f.id),d.push(f));return d},[a.data?.pages]),refetch:a.refetch,fetchNextPage:a.fetchNextPage,isFetchingNextPage:a.isFetchingNextPage,isExhausted:!a.hasNextPage,isLoading:a.isLoading,isFetching:a.isFetching,error:a.error,totalHint:a.data?.pages?.[0]?.total_hint}}function va(e){G();let t=20,n=kn({queryKey:["vfs",te()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>Ar(e,t,s),initialPageParam:0,getNextPageParam:(s,i,o)=>{if(!(s.items.length<t))return o+s.items.length},enabled:!!e});return{allItems:(0,_.useMemo)(()=>{if(!n.data?.pages)return[];let s=new Set,i=[];for(let o of n.data.pages)for(let a of o.items)a.id&&!s.has(a.id)&&(s.add(a.id),i.push(a));return i},[n.data?.pages]),fetchNextPage:n.fetchNextPage,isFetchingNextPage:n.isFetchingNextPage,isExhausted:!n.hasNextPage,isLoading:n.isLoading,isFetching:n.isFetching,error:n.error,totalHint:n.data?.pages?.[0]?.total_hint}}function ba(e){return G(),K({queryKey:S.edges(e),queryFn:()=>Or(e),enabled:!!e})}function jr(e){return G(),K({queryKey:S.types(e),queryFn:()=>kr(e)})}function wa(e,t){let n=jr(t);return{...n,data:n.data?.get(e)??void 0}}function Sa(e,t){G();let n=(0,_.useMemo)(()=>t?.arguments,[JSON.stringify(t?.arguments)]),r=t?.mode,s=t?.strategy,i=t?.width;return K({queryKey:[...S.openEnvelope(e,s),i],queryFn:async()=>{let o=await Dr(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 ca={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 Ra(e){let t=jr(e),n=t.data??new Map;return(0,_.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(ca).map(([p,y])=>({key:p,label:y})),getEdgeTypeLabel:p=>ca[p]??p.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function Pa(e,t,n){return G(),K({queryKey:S.memberFocus(e),queryFn:()=>Qr(e,t,n),enabled:!!e})}function Ca(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return K({queryKey:S.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>Hn(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function xa(e,t=50,n=0){return K({queryKey:S.itemHistory(e,String(t),String(n)),queryFn:()=>qr(e,t,n),enabled:!!e})}function Ta(e,t=50,n=0){return G(),K({queryKey:S.recentActivity(e,String(t),String(n)),queryFn:()=>Fr(e,t,n),enabled:!!e})}function Ea(){let[e,t]=(0,_.useState)(null),[n,r]=(0,_.useState)(!0),[s,i]=(0,_.useState)(null);return(0,_.useEffect)(()=>{let o=!1;return Gt().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 ju=[];function Yn(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}function Ia(){let{user:e}=Br(),t=(0,_.useRef)(!1),n=K({queryKey:S.memberships(e?.id??"anonymous"),queryFn:async()=>((await R("list-memberships",{})).memberships||[]).map(f=>({accountId:f.account_id,path:f.account_path,name:f.account_name,role:f.role||"member",typeData:f.account_type_data||{},joinedAt:f.joined_at,via:f.via,placement:f.placement,subordinateTo:f.subordinate_to??null,cascadeAnchorId:f.cascade_anchor_id??null,isAccount:f.is_account??void 0,isSpace:f.is_space??void 0,isOwner:f.is_owner??void 0,billingResponsible:f.billing_responsible??void 0,grantedVia:f.granted_via??null,grantedUnderAccountId:f.granted_under_account_id??null,personalSpaceId:f.personal_space_id??null,personalSpacePath:f.personal_space_path??null})),enabled:!!e?.id,staleTime:1e3*60*2}),r=n.data??ju,s=(0,_.useMemo)(()=>r.filter(d=>d.isAccount!==!1&&!d.isSpace),[r]),i=(0,_.useMemo)(()=>{let d=new Set(s.map(f=>f.accountId)),m=f=>!f.subordinateTo||!d.has(f.subordinateTo);return[...s].sort((f,p)=>Number(m(p))-Number(m(f)))},[s]),o=(0,_.useSyncExternalStore)(Ce,ne,ne),a=(0,_.useMemo)(()=>{let d=Pe();return d?r.find(m=>m.accountId===d.id)??null:null},[o,r]);(0,_.useEffect)(()=>{if(!e?.id){t.current=!1;return}if(!t.current)if(i.length===1){let d=i[0];Un(Yn(d)),zn(d.accountId),d.personalSpacePath&&js(d.personalSpacePath,m=>{let f=r.find(p=>p.accountId===m);return f?Yn(f):null}).catch(()=>{}),t.current=!0}else i.length>1&&(t.current=!0)},[e?.id,i,r]);let c=(0,_.useCallback)(d=>{let m=r.find(p=>p.path===d);if(!m)return;let f=Yn(m);it()?st(f):(Un(f),m.personalSpacePath&&js(m.personalSpacePath,p=>{let y=r.find(g=>g.accountId===p);return y?Yn(y):null}).catch(()=>{})),zn(m.accountId)},[r]),l=(0,_.useCallback)(d=>{let m=r.find(f=>f.path===d);m&&(Bs(Yn(m)).catch(()=>{}),Jn(d))},[r]);return{accounts:i,allMemberships:r,currentAccount:a,mountedScope:null,switchAccount:c,mountScope:l,loading:n.isLoading,error:n.error}}function Aa(){let e=(0,_.useSyncExternalStore)(yr,Kn,Kn);return{mounts:(0,_.useMemo)(()=>Wt(),[e]),homeAnchor:it(),anchor:Pe(),setAnchor:st,mount:Bs,unmount:ia}}function Br(){let[e,t]=(0,_.useState)(null),[n,r]=(0,_.useState)(null),[s,i]=(0,_.useState)(!0),o=(0,_.useRef)(null);(0,_.useEffect)(()=>{L.auth.getSession().then(({data:p,error:y})=>{if(y){console.warn("[useAuth] getSession error, clearing stale session:",y.message),L.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),L.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:f}}=L.auth.onAuthStateChange((p,y)=>{if(p==="TOKEN_REFRESHED"&&!y){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),L.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(y),t(y?.user??null),i(!1)});return o.current=f,()=>{f?.unsubscribe()}},[]);let a=(0,_.useCallback)(async f=>f.provider?L.auth.signInWithOAuth({provider:f.provider,options:f.redirectTo?{redirectTo:f.redirectTo}:{redirectTo:window.location.href}}):L.auth.signInWithPassword({email:f.email,password:f.password}),[]),c=(0,_.useCallback)(async f=>L.auth.signUp({email:f.email,password:f.password,options:{data:f.metadata||{}}}),[]),l=(0,_.useCallback)(async()=>{await L.auth.signOut(),zt(),T().clear()},[]),d=(0,_.useCallback)(async f=>{let{error:p}=await L.auth.resetPasswordForEmail(f);if(p)throw p},[]),m=(0,_.useCallback)(async(f,p)=>{let{error:y}=await L.auth.signInWithOtp({email:f,options:p?{emailRedirectTo:p}:{emailRedirectTo:window.location.href}});if(y)throw y},[]);return{user:e,session:n,loading:s,signIn:a,signUp:c,signOut:l,resetPassword:d,signInWithMagicLink:m}}function ka(e){let[t,n]=(0,_.useState)(null),[r,s]=(0,_.useState)(!1),[i,o]=(0,_.useState)(null);return(0,_.useEffect)(()=>{if(!e){n(null),s(!1);return}if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e))s(!0),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 l=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";n({url:l+e}),s(!1)}},[e]),{data:t,loading:r,error:i}}var Xn={},ua={};Be(()=>{for(let e of Object.keys(Xn))delete Xn[e]});var Oa=null;function Ma(e){Oa=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function Bu(e){switch(e){case"react":return typeof window<"u"&&window.React||_.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||Ku;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}:Lu;case"@fsaos/gateway":case"@fsaos/react":return typeof window<"u"&&window.__FSAOS_GATEWAY__||Oa||{};case"@fsaos/ui":return typeof window<"u"&&window.__FSAOS_UI__||{};case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}function $u(e,t){return e.replace(/^(\s*)(:root|body)(\s*[{,])/gm,(n,r,s,i)=>`${r}.${t}${i}`)}async function Vu(e,t){if(!ua[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=$u(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),ua[e]=s}catch{}}function Hu(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)(Bu),o=t??i;return o?o.default||o:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function Hs(e){let[t,n]=(0,_.useState)(null),[r,s]=(0,_.useState)(!0),[i,o]=(0,_.useState)(null);return(0,_.useEffect)(()=>{if(!e)return;let a=!1;s(!0),o(null);let l=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{try{let d=1,m=e+"@v1",f=l+e+"/__bundle.js";try{let v=await fetch(l+e+"/__meta",{cache:"no-store"});v.ok&&(d=(await v.json()).version||1,m=e+"@v"+d,f=l+e+"/__bundle.v"+d+".js")}catch{f=l+e+"/__bundle.js?v="+Date.now()}if(a)return;if(Xn[m]){n(()=>Xn[m]),s(!1);return}let p=await fetch(f);if(!p.ok)throw new Error(`Failed to fetch bundle: ${p.status} ${p.statusText} (${f})`);let y=await p.text();if(a)return;let g=f.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");Vu(g).catch(()=>{});let h=Hu(y);if(!h)throw new Error("Bundle did not export a component. Expected window.__FSAOS_COMPONENT__ (FSAOS build) or a __FSAOS_REGISTER__(Component) call.");if(typeof h!="function")throw new Error(`Bundle export is not a React component (got ${typeof h})`);Xn[m]=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 Wu=["--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 Fa(){return{data:(0,_.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let t={},n=getComputedStyle(document.documentElement);return Wu.forEach(r=>{t[r]=n.getPropertyValue(r).trim()}),{tokens:t}},[]),loading:!1,error:null}}function qa(e,t){return{data:{allowed:!0},loading:!1,error:null}}function Qa(e,t){let n={};return(t||[]).forEach(r=>{n[r]=!0}),{data:n,loading:!1,error:null}}var ie=null,cn=null,$s=new Set;function Gu(){$s.forEach(e=>e())}Be(()=>{ie=null,cn=null});async function Da(e){let t={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null},n=wt()?.principal_id??null;if(n){if(ie&&ie.principalId===n){let{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}=ie;return{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}}return{...t,principalId:n}}let r=e;if(!r){let{data:s}=await L.auth.getSession();r=s?.session?.user?.id}if(!r)return t;if(ie&&ie.authUserId===r){let{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}=ie;return{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}}return cn||(cn=(async()=>{try{let{data:s,error:i}=await L.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:l}=await L.from("os_items").select("path").eq("owner_principal_id",o).eq("item_type","principal").eq("is_active",!0).like("path","/root/principals/%"),d=(l??[]).map(m=>m.path);a=d.find(m=>m.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 ie={authUserId:r,...c},c}finally{cn=null}})(),cn)}async function Ua(e){return(await Da(e)).principalId}function Na(){let e=Br(),t=e.user,n=ie?.authUserId===t?.id?ie:null,[r,s]=(0,_.useState)(n),i=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let o=()=>{let a=ie;a&&a.authUserId===t?.id&&s({principalId:a.principalId,displayName:a.displayName,createdAt:a.createdAt,metadata:a.metadata,vfsPath:a.vfsPath})};return $s.add(o),()=>{$s.delete(o)}},[t?.id]),(0,_.useEffect)(()=>{if(!t?.id){s(null),i.current=null;return}i.current===t.id&&r?.principalId!=null||(i.current=t.id,Da(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 Ka(){return{data:null,loading:!1,error:null}}function La(e){let{path:t,...n}=e,r=Hs(t),s=r.Component,{loading:i,error:o}=r;return i?(0,_.createElement)("div",{className:"fsaos-loading"},""):o?(0,_.createElement)("div",{className:"fsaos-error"},"Failed to load component"):s?(0,_.createElement)(s,n):null}function ja(e){return e.children}function Ba(e){let t=G(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=e,o=i!==void 0?i&&!!n:!!n,a=(0,_.useMemo)(()=>S.channelMessages(n??"",r),[n,r,t]),c=j(),l=(0,_.useRef)(null),d=K({queryKey:a,queryFn:()=>Ur(n,r),enabled:o});(0,_.useEffect)(()=>{if(!s||!o)return;let g=re("vfs_change",()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{$e(c,a,{exact:!0})},500)},h=>(h.item_type==="message"||h.item_type==="card")&&at(h.path,n));return()=>{g(),l.current&&clearTimeout(l.current)}},[s,o,n,a,c]);let m=d.data,f=m?.messages??[],p=m?.messageCards??new Map,y=m?.siblingCards??[];return{messages:f,messageCards:p,siblingCards:y,threads:(0,_.useMemo)(()=>f.filter(g=>g.reply_count>0),[f]),isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,refetch:d.refetch}}function $a(e){G();let{channelPath:t,parentMessageId:n,limit:r=50,realtime:s=!0,enabled:i=!0}=e,o=!!n,a=i&&!!t,c=kn({queryKey:[...S.channelMessages(t||"",n),"infinite",r],queryFn:async({pageParam:g})=>Wn(t,{parentMessageId:n,limit:r,before_seq:o?void 0:g,after_seq:o?g:void 0}),initialPageParam:void 0,getNextPageParam:g=>!o||g.messages.length<r?void 0:g.messages[g.messages.length-1]?.seq,getPreviousPageParam:g=>o||g.messages.length<r?void 0:g.messages[0]?.seq,enabled:a}),l=(0,_.useMemo)(()=>{if(!c.data?.pages)return[];let g=new Set,h=[];for(let v of c.data.pages)for(let P of v.messages)g.has(P.id)||(g.add(P.id),h.push(P));return h.sort((v,P)=>v.seq-P.seq)},[c.data?.pages]),{messageCards:d,siblingCards:m}=(0,_.useMemo)(()=>{let g=new Map,h=[];if(!c.data?.pages)return{messageCards:g,siblingCards:h};let v=new Set;for(let P of c.data.pages){for(let[M,X]of P.messageCards)for(let C of X){if(v.has(C.id))continue;v.add(C.id);let F=g.get(M)||[];F.push(C),g.set(M,F)}for(let M of P.siblingCards)v.has(M.id)||(v.add(M.id),h.push(M))}return{messageCards:g,siblingCards:h}},[c.data?.pages]),f=j(),p=(0,_.useRef)(null),y=(0,_.useMemo)(()=>[...S.channelMessages(t||"",n),"infinite",r],[t,n,r]);return(0,_.useEffect)(()=>{if(!s||!t||!a)return;let g=()=>void $e(f,y,{exact:!0}),h=!1,v=!1,P=!1,M=async()=>{let F=f.getQueryData(y);if(!F?.pages?.length){g();return}let B=0;for(let N of F.pages)for(let O of N.messages)O.seq>B&&(B=O.seq);if(B===0){g();return}try{let N=await Wn(t,{parentMessageId:n,limit:r,after_seq:B});if(N.messages.length===0&&N.siblingCards.length===0){g();return}if(N.messages.length>0){let O=Math.min(...N.messages.map($=>$.seq));if(O>B+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${B}, minNewSeq=${O}. Triggering full refetch.`),g();return}}f.setQueryData(y,O=>{if(!O)return O;let $=[...O.pages],A=$.length-1,I=$[A],Q=new Set(I.messages.map(he=>he.id)),D=N.messages.filter(he=>!Q.has(he.id)),Te=[...I.messages,...D].sort((he,Jr)=>he.seq-Jr.seq),z=new Map(I.messageCards);for(let[he,Jr]of N.messageCards){let ri=z.get(he)||[],Wc=new Set(ri.map(Yr=>Yr.id)),Gc=Jr.filter(Yr=>!Wc.has(Yr.id));z.set(he,[...ri,...Gc])}let lt=new Set(I.siblingCards.map(he=>he.id)),Vc=N.siblingCards.filter(he=>!lt.has(he.id)),Hc=[...I.siblingCards,...Vc];return $[A]={...I,messages:Te,messageCards:z,siblingCards:Hc},{...O,pages:$}})}catch(N){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",N),g()}},X=async()=>{if(h){v=!0;return}h=!0;try{do v=!1,await M();while(v&&!P)}finally{h=!1}},C=re("vfs_change",()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{X()},500)},F=>(F.item_type==="message"||F.item_type==="card")&&at(F.path,t));return()=>{P=!0,C(),p.current&&clearTimeout(p.current)}},[s,t,a,y,f,n,r]),{messages:l,messageCards:d,siblingCards:m,threads:l.filter(g=>g.reply_count>0),isLoading:c.isLoading,isFetching:c.isFetching,error:c.error,refetch:c.refetch,hasPreviousPage:c.hasPreviousPage??!1,fetchPreviousPage:c.fetchPreviousPage,isFetchingPreviousPage:c.isFetchingPreviousPage??!1,hasNextPage:c.hasNextPage??!1,fetchNextPage:c.fetchNextPage,isFetchingNextPage:c.isFetchingNextPage??!1}}function zu(e){return e==="on"||e==="auto"?"on":"off"}function Ju(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:zu(t.ai_mode),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}}function $r(e={}){let t=G(),{realtime:n=!0,enabled:r=!0}=e,s=j(),i=(0,_.useRef)(null),o=(0,_.useMemo)(()=>S.channels("all"),[t]),a=K({queryKey:o,queryFn:async()=>((await R("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(Ju),enabled:r});return(0,_.useEffect)(()=>{if(!n||!r)return;let l=re("vfs_change",()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{s.invalidateQueries({queryKey:o})},1e3)},m=>m.item_type==="channel"||m.item_type==="message"),d=re("ccm_change",()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{s.invalidateQueries({queryKey:o})},1e3)},m=>m.item_type==="channel"||m.item_type==="message");return()=>{l(),d(),i.current&&clearTimeout(i.current)}},[n,r,o,s]),{channels:a.data??[],isLoading:a.isLoading,isFetching:a.isFetching,error:a.error,refetch:a.refetch}}function Va(e={}){let t=$r(e),n=(0,_.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function Ha(e={}){let t=$r(e),n=(0,_.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function Ws(e={}){let t=G(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=e,o=j(),a=(0,_.useRef)(null),c=(0,_.useMemo)(()=>S.notifications(n,r),[n,r,t]),l=K({queryKey:c,queryFn:async()=>{let m={limit:r};return n==="unread"&&(m.filter="unread"),(await R("get-notifications",m)).notifications||[]},enabled:i});return(0,_.useEffect)(()=>{if(!s||!i)return;let m=["vfs_change","ccm_change"].map(f=>re(f,()=>{a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{o.invalidateQueries({queryKey:c})},2e3)},p=>p.item_type==="notification"||p.item_type==="message"));return()=>{m.forEach(f=>f()),a.current&&clearTimeout(a.current)}},[s,i,c,o]),{notifications:l.data??[],isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function Wa(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:o,error:a,refetch:c}=Ws({filter:"unread",limit:200,realtime:n,enabled:r}),l=(0,_.useMemo)(()=>{let p=new Map;for(let y of s)y.is_unread&&y.channel_id&&p.set(y.channel_id,(p.get(y.channel_id)||0)+1);return p},[s]),d=(0,_.useMemo)(()=>{let p=0;return l.forEach(y=>{p+=y}),p},[l]),{dmUnread:m,channelUnread:f}=(0,_.useMemo)(()=>{if(!t)return{dmUnread:0,channelUnread:0};let p=new Set(t.filter(h=>h.isDm).map(h=>h.id)),y=0,g=0;return l.forEach((h,v)=>{p.has(v)?y+=h:g+=h}),{dmUnread:y,channelUnread:g}},[t,l]);return{unreadByChannel:l,totalUnread:d,dmUnread:m,channelUnread:f,isLoading:i,isFetching:o,error:a,refetch:c}}function Ga(){let e=j();return pe({mutationFn:t=>R("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:S.children(r)})}})}function za(){let e=j();return pe({mutationFn:t=>R("update",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.invalidateQueries({queryKey:S.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:S.children(i)})}}})}function Ja(){return pe({mutationFn:e=>R("update-principal",e),onSuccess:(e,t)=>{if(!ie)return;let n=e&&typeof e=="object"&&e.metadata?e.metadata:{...ie.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}:{}};ie={...ie,displayName:typeof t.display_name=="string"?t.display_name:ie.displayName,metadata:n},Gu()}})}function Ya(){let e=j();return pe({mutationFn:t=>R("delete",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.removeQueries({queryKey:S.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:S.children(i)})}}})}function Xa(){let e=j();return pe({mutationFn:t=>R("move",t),onSuccess:(t,n)=>{let r=n.path,s=n.new_parent_path;if(r){e.invalidateQueries({queryKey:S.item(r)});let i=r.split("/");i.pop();let o=i.join("/");o&&e.invalidateQueries({queryKey:S.children(o)})}s&&e.invalidateQueries({queryKey:S.children(s)})}})}function Za(){let e=j();return pe({mutationFn:t=>R("link",t),onSuccess:(t,n)=>{let r=n.source_id,s=n.target_id;r&&e.invalidateQueries({queryKey:S.edges(r)}),s&&e.invalidateQueries({queryKey:S.edges(s)})}})}function ec(e,t){let n=j(),{optimistic:r,...s}=t??{};return pe({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 tc(e,t,n){let r,s,i,o=!0;if(typeof e=="string")r=e,s=t,i=n;else{s=e;let l=t;r=l.eventType,i=l.filter,o=l.enabled??!0}let a=(0,_.useRef)(s),c=(0,_.useRef)(i);(0,_.useEffect)(()=>{a.current=s,c.current=i},[s,i]),(0,_.useEffect)(()=>o?re(r,d=>a.current(d),c.current?d=>c.current(d):void 0):void 0,[r,o])}function nc(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:o=500}=e,a=j(),c=(0,_.useRef)(null),l=K({queryKey:t,queryFn:n,enabled:i});return(0,_.useEffect)(()=>{if(!i)return;let d=re(r,()=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{a.invalidateQueries({queryKey:t})},o)},s);return()=>{d(),c.current&&clearTimeout(c.current)}},[r,i,o,a,JSON.stringify(t)]),l}function un(e){G();let t=te(),n=(0,_.useMemo)(()=>e?typeof e=="string"?{path:e}:e:null,[typeof e=="string"?e:JSON.stringify(e)]),r=!!t&&!!n&&!!(n.key||n.path||n.item_id),s=n?.key??n?.path??n?.item_id??"",i=["vfs",t??"__unscoped__","arrangement",s,n?.scope_id??""],o=K({queryKey:i,staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0},queryFn:async()=>{if(!n)return null;let f=await R("resolve-arrangement",{...n,_scope_path:t});if(f?.success===!1)throw new Error(f?.error||"Arrangement could not be loaded");return f??null},enabled:r}),a=o.data??null,c=(0,_.useMemo)(()=>a?.resolved_children??[],[a]),l=a?.resolution_level??null,d=(0,_.useMemo)(()=>{let p=(a?.type_data??null)?.order;return Array.isArray(p)?p:null},[a]),m=(0,_.useCallback)(f=>{if(!d||!f?.length)return f??[];let p=v=>v.id??v.name??"",y=new Map(d.map((v,P)=>[v,P])),g=[],h=[];for(let v of f)(y.has(p(v))?g:h).push(v);return g.sort((v,P)=>y.get(p(v))-y.get(p(P))),[...g,...h]},[d]);return{...o,arrangement:a,resolvedChildren:c,resolutionLevel:l,order:d,sourceScopeId:a?.scope_item_id??null,arrangementQueryKey:i,applyTo:m}}function rc(e){let{origin:t,originField:n,fallbackUrl:r,mintError:s,scopeId:i,scopePath:o}=e,a=G(),c=wt(),l=i??c?.scope_id??null,d=(0,_.useMemo)(()=>{if(!t)return null;let C="/accounts/",F=t.indexOf(C);if(F===-1)return null;let B=t.indexOf("/",F+C.length);return B===-1?t:t.slice(0,B)},[t]),m=o??d??c?.scope_path??null,f=n?.trim()||null,p=`${a}
1
+ /* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-10-03T22:17:01.334Z */
2
+ "use strict";var __FSAOS_GATEWAY__=(()=>{var fu=Object.create;var An=Object.defineProperty;var pu=Object.getOwnPropertyDescriptor;var mu=Object.getOwnPropertyNames;var hu=Object.getPrototypeOf,gu=Object.prototype.hasOwnProperty;var wi=e=>{throw TypeError(e)};var yu=(e,t,n)=>t in e?An(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var kn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),_u=(e,t)=>{for(var n in t)An(e,n,{get:t[n],enumerable:!0})},Si=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of mu(t))!gu.call(e,s)&&s!==n&&An(e,s,{get:()=>t[s],enumerable:!(r=pu(t,s))||r.enumerable});return e};var J=(e,t,n)=>(n=e!=null?fu(hu(e)):{},Si(t||!e||!e.__esModule?An(n,"default",{value:e,enumerable:!0}):n,e)),vu=e=>Si(An({},"__esModule",{value:!0}),e);var Y=(e,t,n)=>yu(e,typeof t!="symbol"?t+"":t,n),hs=(e,t,n)=>t.has(e)||wi("Cannot "+n);var u=(e,t,n)=>(hs(e,t,"read from private field"),n?n.call(e):t.get(e)),w=(e,t,n)=>t.has(e)?wi("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),b=(e,t,n,r)=>(hs(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),T=(e,t,n)=>(hs(e,t,"access private method"),n);var Mn=(e,t,n,r)=>({set _(s){b(e,t,s,n)},get _(){return u(e,t,r)}});var ce=kn((Fl,Ri)=>{Ri.exports=React});var Rr=kn((Mf,ro)=>{ro.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var yo=kn((up,go)=>{go.exports={createClient:window.supabase.createClient}});var Qo=kn((bp,qo)=>{qo.exports=ReactDOM});var Dc=kn((eh,Qc)=>{Qc.exports=ReactDOM});var vi={};_u(vi,{ComponentRenderer:()=>sc,EnforcementDeniedError:()=>Xe,FormSubmissionError:()=>In,GatewayRequestError:()=>Re,InteractionTrackingError:()=>Cn,KernelProvider:()=>ic,QueryClientProvider:()=>Bn,auth:()=>$c,awaitAnchorReady:()=>Yn,awaitScopeReady:()=>Co,callTool:()=>Bc,cancelQueuedTurn:()=>Fc,cancelTurn:()=>Mc,clearCachedToken:()=>js,clearSession:()=>zs,createItem:()=>Lc,disconnectSSE:()=>ni,disposeVfsRealtimeWs:()=>ii,electHomeAnchor:()=>Tt,emitEvent:()=>na,fetchChannelMessages:()=>pa,fetchChannelMessagesPage:()=>ir,fetchChannelMessagesWithCards:()=>Xr,fetchEdgesForItem:()=>Hr,fetchItemHistory:()=>zr,fetchItemVersions:()=>sr,fetchItems:()=>vn,fetchMemberFocus:()=>Jr,fetchOpenEnvelope:()=>Yr,fetchRecentActivity:()=>Gr,fetchResolvedItems:()=>yi,fetchTimelineHistory:()=>_i,fetchTurnQueueEntries:()=>la,fetchTypeDefinitions:()=>Vr,fetchVfsChildren:()=>rr,fetchVfsChildrenPage:()=>Br,fetchVfsItem:()=>Wr,fetchVfsItemById:()=>jr,fetchVfsTree:()=>$r,gatewayCall:()=>R,getAccessToken:()=>$e,getAnchor:()=>cn,getAnchorRef:()=>Se,getAnchorVersion:()=>Vs,getAssetUrl:()=>Hc,getDefaultSort:()=>Yc,getHomeAnchor:()=>le,getMountVersion:()=>Xn,getMounts:()=>De,getPathSubscriptionState:()=>sa,getQueryClient:()=>C,getRequiredFormFields:()=>Xc,getScope:()=>re,getScopeVersion:()=>se,getServerClockOffsetMs:()=>ko,getServerClockSyncedAt:()=>Mo,getSessionEntry:()=>Et,hasServerClock:()=>Ao,initSession:()=>lt,initVfsRealtimeWs:()=>Mt,initializeFsaos:()=>kc,initializeWorkspace:()=>us,interpretSchema:()=>gi,invalidateAllVfs:()=>ga,invalidateChannelMessages:()=>_a,invalidateChildren:()=>Lr,invalidateItem:()=>si,invalidateOpenEnvelope:()=>va,invalidatePathAndParent:()=>ma,invalidateSubtree:()=>ha,invalidateTypes:()=>ya,isAnchorReady:()=>$s,isChannelPath:()=>dt,isListableItemsFilter:()=>_n,isScopeReady:()=>kr,itemsFilterFromQueryFilter:()=>da,listChildren:()=>Kc,loadMounts:()=>Ot,mount:()=>Gc,mountRealtimeScope:()=>wn,normalizeItem:()=>Pe,onConnectionStateChange:()=>aa,pathSubscriptionMatches:()=>Zs,ping:()=>ra,pushChanges:()=>Wc,queryClient:()=>Wo,readItem:()=>Nc,refreshQuery:()=>Ge,registerCleanup:()=>ne,replaceMounts:()=>rs,resetAllSdkState:()=>un,resolvePrincipalId:()=>tc,resubscribePath:()=>oa,selectMount:()=>ur,serverDeadlinePassed:()=>Oo,serverMsUntil:()=>Fo,serverNow:()=>Mr,setAnchor:()=>Ir,setCachedToken:()=>bo,setQueryClient:()=>jo,setScope:()=>Po,setupRequireShim:()=>zc,signal:()=>Vc,startTracking:()=>cs,steerTurn:()=>Oc,submitForm:()=>qc,subscribeAnchor:()=>Hs,subscribeArtifactStream:()=>ls,subscribeMounts:()=>Ar,subscribeScope:()=>Ee,subscribeToEvents:()=>ie,subscribeToPath:()=>Kr,subscribeToScope:()=>yn,trackAction:()=>Ec,trackEvent:()=>Ft,trackPageView:()=>Tc,unmountRealtimeScope:()=>ts,updateItem:()=>jc,uploadFile:()=>Zc,useAccounts:()=>Ha,useAgentTimeline:()=>iu,useAllChannels:()=>os,useArrangement:()=>xn,useArtifactStream:()=>su,useAsset:()=>Ga,useAuth:()=>is,useChannelMessages:()=>oc,useChannels:()=>cc,useChildren:()=>Aa,useComponent:()=>ui,useCreate:()=>dc,useDelete:()=>mc,useDmChannels:()=>uc,useEdges:()=>Da,useEventStream:()=>_c,useFileUpload:()=>tu,useInfiniteChannelMessages:()=>ac,useInfiniteChildren:()=>Qa,useInfiniteItems:()=>qa,useItem:()=>Ea,useItemById:()=>Ia,useItemHistory:()=>Wa,useItemVersions:()=>ja,useItems:()=>Fa,useLink:()=>gc,useList:()=>ci,useMemberFocus:()=>La,useMintedAsset:()=>bc,useMounts:()=>$a,useMove:()=>hc,useMutation:()=>yc,useNotifications:()=>li,useOpen:()=>Na,usePermission:()=>Xa,usePermissions:()=>Za,usePersonalItemOrder:()=>wc,usePinnedItems:()=>au,usePrincipal:()=>nc,useRealtimeQuery:()=>vc,useRecentActivity:()=>Ba,useResolve:()=>Oa,useResolvedItems:()=>ru,useScope:()=>Va,useScopeReady:()=>Ta,useSearch:()=>Ma,useTheme:()=>Ya,useTimelineHistory:()=>ou,useTool:()=>rc,useTree:()=>ka,useType:()=>Ua,useTypeHelpers:()=>Ka,useTypes:()=>ss,useUnreadCounts:()=>lc,useUpdate:()=>fc,useUpdatePrincipal:()=>pc,vfsKeys:()=>S,waitForPathReady:()=>ia});var Xe=class e extends Error{constructor(n){let r=n.message||e.fallbackMessage(n);super(r);Y(this,"name","EnforcementDeniedError");Y(this,"deniedBy");Y(this,"ruleKey");Y(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 Pn=J(ce(),1);var ve=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 gt,Ze,Qt,xi,bu=(xi=class extends ve{constructor(){super();w(this,gt);w(this,Ze);w(this,Qt);b(this,Qt,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){u(this,Ze)||this.setEventListener(u(this,Qt))}onUnsubscribe(){var t;this.hasListeners()||((t=u(this,Ze))==null||t.call(this),b(this,Ze,void 0))}setEventListener(t){var n;b(this,Qt,t),(n=u(this,Ze))==null||n.call(this),b(this,Ze,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){u(this,gt)!==t&&(b(this,gt,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof u(this,gt)=="boolean"?u(this,gt):globalThis.document?.visibilityState!=="hidden"}},gt=new WeakMap,Ze=new WeakMap,Qt=new WeakMap,xi),Dt=new bu;var wu={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},et,gs,Pi,Su=(Pi=class{constructor(){w(this,et,wu);w(this,gs,!1)}setTimeoutProvider(e){b(this,et,e)}setTimeout(e,t){return u(this,et).setTimeout(e,t)}clearTimeout(e){u(this,et).clearTimeout(e)}setInterval(e,t){return u(this,et).setInterval(e,t)}clearInterval(e){u(this,et).clearInterval(e)}},et=new WeakMap,gs=new WeakMap,Pi),ke=new Su;function Ci(e){setTimeout(e,0)}var _s=typeof window>"u"||"Deno"in globalThis;function V(){}function Ii(e,t){return typeof e=="function"?e(t):e}function On(e){return typeof e=="number"&&e>=0&&e!==1/0}function mr(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Ce(e,t){return typeof e=="function"?e(t):e}function de(e,t){return typeof e=="function"?e(t):e}function hr(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:o,stale:c}=e;if(o){if(r){if(t.queryHash!==Fn(o,t.options))return!1}else if(!yt(t.queryKey,o))return!1}if(n!=="all"){let a=t.isActive();if(n==="active"&&!a||n==="inactive"&&a)return!1}return!(typeof c=="boolean"&&t.isStale()!==c||s&&s!==t.state.fetchStatus||i&&!i(t))}function gr(e,t){let{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Me(t.options.mutationKey)!==Me(i))return!1}else if(!yt(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function Fn(e,t){return(t?.queryKeyHashFn||Me)(e)}function Me(e){return JSON.stringify(e,(t,n)=>ys(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function yt(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>yt(e[n],t[n])):!1}var Ru=Object.prototype.hasOwnProperty;function vs(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=Ti(e)&&Ti(t);if(!r&&!(ys(e)&&ys(t)))return t;let i=(r?e:Object.keys(e)).length,o=r?t:Object.keys(t),c=o.length,a=r?new Array(c):{},l=0;for(let d=0;d<c;d++){let p=r?d:o[d],m=e[p],f=t[p];if(m===f){a[p]=m,(r?d<i:Ru.call(e,p))&&l++;continue}if(m===null||f===null||typeof m!="object"||typeof f!="object"){a[p]=f;continue}let y=vs(m,f,n+1);a[p]=y,y===m&&l++}return i===c&&l===i?e:a}function Ut(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 Ti(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function ys(e){if(!Ei(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Ei(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Ei(e){return Object.prototype.toString.call(e)==="[object Object]"}function Ai(e){return new Promise(t=>{ke.setTimeout(t,e)})}function qn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?vs(e,t):t}function ki(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function Mi(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Nt=Symbol();function yr(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Nt?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Kt(e,t){return typeof e=="function"?e(...t):!!e}function Oi(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 Oe=(()=>{let e=()=>_s;return{isServer(){return e()},setIsServer(t){e=t}}})();function Qn(){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 Fi=Ci;function xu(){let e=[],t=0,n=c=>{c()},r=c=>{c()},s=Fi,i=c=>{t?e.push(c):s(()=>{n(c)})},o=()=>{let c=e;e=[],c.length&&s(()=>{r(()=>{c.forEach(a=>{n(a)})})})};return{batch:c=>{let a;t++;try{a=c()}finally{t--,t||o()}return a},batchCalls:c=>(...a)=>{i(()=>{c(...a)})},schedule:i,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{r=c},setScheduler:c=>{s=c}}}var U=xu();var Lt,tt,jt,qi,Pu=(qi=class extends ve{constructor(){super();w(this,Lt,!0);w(this,tt);w(this,jt);b(this,jt,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(){u(this,tt)||this.setEventListener(u(this,jt))}onUnsubscribe(){var t;this.hasListeners()||((t=u(this,tt))==null||t.call(this),b(this,tt,void 0))}setEventListener(t){var n;b(this,jt,t),(n=u(this,tt))==null||n.call(this),b(this,tt,t(this.setOnline.bind(this)))}setOnline(t){u(this,Lt)!==t&&(b(this,Lt,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return u(this,Lt)}},Lt=new WeakMap,tt=new WeakMap,jt=new WeakMap,qi),Wt=new Pu;function Cu(e){return Math.min(1e3*2**e,3e4)}function bs(e){return(e??"online")==="online"?Wt.isOnline():!0}var _r=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function vr(e){let t=!1,n=0,r,s=Qn(),i=()=>s.status!=="pending",o=h=>{if(!i()){let g=new _r(h);m(g),e.onCancel?.(g)}},c=()=>{t=!0},a=()=>{t=!1},l=()=>Dt.isFocused()&&(e.networkMode==="always"||Wt.isOnline())&&e.canRun(),d=()=>bs(e.networkMode)&&e.canRun(),p=h=>{i()||(r?.(),s.resolve(h))},m=h=>{i()||(r?.(),s.reject(h))},f=()=>new Promise(h=>{r=g=>{(i()||l())&&h(g)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),y=()=>{if(i())return;let h,g=n===0?e.initialPromise:void 0;try{h=g??e.fn()}catch(v){h=Promise.reject(v)}Promise.resolve(h).then(p).catch(v=>{if(i())return;let x=e.retry??(Oe.isServer()?0:3),O=e.retryDelay??Cu,X=typeof O=="function"?O(n,v):O,P=x===!0||typeof x=="number"&&n<x||typeof x=="function"&&x(n,v);if(t||!P){m(v);return}n++,e.onFail?.(n,v),Ai(X).then(()=>l()?void 0:f()).then(()=>{t?m(v):y()})})};return{promise:s,status:()=>s.status,cancel:o,continue:()=>(r?.(),s),cancelRetry:c,continueRetry:a,canStart:d,start:()=>(d()?y():f().then(y),s)}}var _t,Qi,br=(Qi=class{constructor(){w(this,_t)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),On(this.gcTime)&&b(this,_t,ke.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Oe.isServer()?1/0:5*60*1e3))}clearGcTimeout(){u(this,_t)!==void 0&&(ke.clearTimeout(u(this,_t)),b(this,_t,void 0))}},_t=new WeakMap,Qi);var vt,Bt,be,bt,Z,Dn,wt,he,Li,Ke,Ni,Ki=(Ni=class extends br{constructor(t){super();w(this,he);w(this,vt);w(this,Bt);w(this,be);w(this,bt);w(this,Z);w(this,Dn);w(this,wt);b(this,wt,!1),b(this,Dn,t.defaultOptions),this.setOptions(t.options),this.observers=[],b(this,bt,t.client),b(this,be,u(this,bt).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,b(this,vt,Ui(this.options)),this.state=t.state??u(this,vt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return u(this,Z)?.promise}setOptions(t){if(this.options={...u(this,Dn),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=Ui(this.options);n.data!==void 0&&(this.setState(Di(n.data,n.dataUpdatedAt)),b(this,vt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&u(this,be).remove(this)}setData(t,n){let r=qn(this.state.data,t,this.options);return T(this,he,Ke).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){T(this,he,Ke).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=u(this,Z)?.promise;return u(this,Z)?.cancel(t),n?n.then(V).catch(V):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return u(this,vt)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>de(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Nt||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>Ce(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!mr(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),u(this,Z)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),u(this,Z)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),u(this,be).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(u(this,Z)&&(u(this,wt)||T(this,he,Li).call(this)?u(this,Z).cancel({revert:!0}):u(this,Z).cancelRetry()),this.scheduleGc()),u(this,be).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||T(this,he,Ke).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&u(this,Z)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(u(this,Z))return u(this,Z).continueRetry(),u(this,Z).promise}if(t&&this.setOptions(t),!this.options.queryFn){let a=this.observers.find(l=>l.options.queryFn);a&&this.setOptions(a.options)}let r=new AbortController,s=a=>{Object.defineProperty(a,"signal",{enumerable:!0,get:()=>(b(this,wt,!0),r.signal)})},i=()=>{let a=yr(this.options,n),d=(()=>{let p={client:u(this,bt),queryKey:this.queryKey,meta:this.meta};return s(p),p})();return b(this,wt,!1),this.options.persister?this.options.persister(a,d,this):a(d)},c=(()=>{let a={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:u(this,bt),state:this.state,fetchFn:i};return s(a),a})();this.options.behavior?.onFetch(c,this),b(this,Bt,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==c.fetchOptions?.meta)&&T(this,he,Ke).call(this,{type:"fetch",meta:c.fetchOptions?.meta}),b(this,Z,vr({initialPromise:n?.initialPromise,fn:c.fetchFn,onCancel:a=>{a instanceof _r&&a.revert&&this.setState({...u(this,Bt),fetchStatus:"idle"}),r.abort()},onFail:(a,l)=>{T(this,he,Ke).call(this,{type:"failed",failureCount:a,error:l})},onPause:()=>{T(this,he,Ke).call(this,{type:"pause"})},onContinue:()=>{T(this,he,Ke).call(this,{type:"continue"})},retry:c.options.retry,retryDelay:c.options.retryDelay,networkMode:c.options.networkMode,canRun:()=>!0}));try{let a=await u(this,Z).start();if(a===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(a),u(this,be).config.onSuccess?.(a,this),u(this,be).config.onSettled?.(a,this.state.error,this),a}catch(a){if(a instanceof _r){if(a.silent)return u(this,Z).promise;if(a.revert){if(this.state.data===void 0)throw a;return this.state.data}}throw T(this,he,Ke).call(this,{type:"error",error:a}),u(this,be).config.onError?.(a,this),u(this,be).config.onSettled?.(this.state.data,a,this),a}finally{this.scheduleGc()}}},vt=new WeakMap,Bt=new WeakMap,be=new WeakMap,bt=new WeakMap,Z=new WeakMap,Dn=new WeakMap,wt=new WeakMap,he=new WeakSet,Li=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},Ke=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,...ws(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...Di(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return b(this,Bt,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),U.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),u(this,be).notify({query:this,type:"updated",action:t})})},Ni);function ws(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:bs(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Di(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Ui(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 fe,k,Nn,ue,St,Vt,Le,nt,Kn,Ht,$t,Rt,xt,rt,Gt,q,Un,Ss,Rs,xs,Ps,Cs,Ts,Es,Vi,Bi,Ln=(Bi=class extends ve{constructor(t,n){super();w(this,q);w(this,fe);w(this,k);w(this,Nn);w(this,ue);w(this,St);w(this,Vt);w(this,Le);w(this,nt);w(this,Kn);w(this,Ht);w(this,$t);w(this,Rt);w(this,xt);w(this,rt);w(this,Gt,new Set);this.options=n,b(this,fe,t),b(this,nt,null),b(this,Le,Qn()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(u(this,k).addObserver(this),ji(u(this,k),this.options)?T(this,q,Un).call(this):this.updateResult(),T(this,q,Ps).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Is(u(this,k),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Is(u(this,k),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,T(this,q,Cs).call(this),T(this,q,Ts).call(this),u(this,k).removeObserver(this)}setOptions(t){let n=this.options,r=u(this,k);if(this.options=u(this,fe).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof de(this.options.enabled,u(this,k))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");T(this,q,Es).call(this),u(this,k).setOptions(this.options),n._defaulted&&!Ut(this.options,n)&&u(this,fe).getQueryCache().notify({type:"observerOptionsUpdated",query:u(this,k),observer:this});let s=this.hasListeners();s&&Wi(u(this,k),r,this.options,n)&&T(this,q,Un).call(this),this.updateResult(),s&&(u(this,k)!==r||de(this.options.enabled,u(this,k))!==de(n.enabled,u(this,k))||Ce(this.options.staleTime,u(this,k))!==Ce(n.staleTime,u(this,k)))&&T(this,q,Ss).call(this);let i=T(this,q,Rs).call(this);s&&(u(this,k)!==r||de(this.options.enabled,u(this,k))!==de(n.enabled,u(this,k))||i!==u(this,rt))&&T(this,q,xs).call(this,i)}getOptimisticResult(t){let n=u(this,fe).getQueryCache().build(u(this,fe),t),r=this.createResult(n,t);return Eu(this,r)&&(b(this,ue,r),b(this,Vt,this.options),b(this,St,u(this,k).state)),r}getCurrentResult(){return u(this,ue)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&u(this,Le).status==="pending"&&u(this,Le).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){u(this,Gt).add(t)}getCurrentQuery(){return u(this,k)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=u(this,fe).defaultQueryOptions(t),r=u(this,fe).getQueryCache().build(u(this,fe),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return T(this,q,Un).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),u(this,ue)))}createResult(t,n){let r=u(this,k),s=this.options,i=u(this,ue),o=u(this,St),c=u(this,Vt),l=t!==r?t.state:u(this,Nn),{state:d}=t,p={...d},m=!1,f;if(n._optimisticResults){let M=this.hasListeners(),B=!M&&ji(t,n),A=M&&Wi(t,r,n,s);(B||A)&&(p={...p,...ws(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(p.fetchStatus="idle")}let{error:y,errorUpdatedAt:h,status:g}=p;f=p.data;let v=!1;if(n.placeholderData!==void 0&&f===void 0&&g==="pending"){let M;i?.isPlaceholderData&&n.placeholderData===c?.placeholderData?(M=i.data,v=!0):M=typeof n.placeholderData=="function"?n.placeholderData(u(this,$t)?.state.data,u(this,$t)):n.placeholderData,M!==void 0&&(g="success",f=qn(i?.data,M,n),m=!0)}if(n.select&&f!==void 0&&!v)if(i&&f===o?.data&&n.select===u(this,Kn))f=u(this,Ht);else try{b(this,Kn,n.select),f=n.select(f),f=qn(i?.data,f,n),b(this,Ht,f),b(this,nt,null)}catch(M){b(this,nt,M)}u(this,nt)&&(y=u(this,nt),f=u(this,Ht),h=Date.now(),g="error");let x=p.fetchStatus==="fetching",O=g==="pending",X=g==="error",P=O&&x,F=f!==void 0,N={status:g,fetchStatus:p.fetchStatus,isPending:O,isSuccess:g==="success",isError:X,isInitialLoading:P,isLoading:P,data:f,dataUpdatedAt:p.dataUpdatedAt,error:y,errorUpdatedAt:h,failureCount:p.fetchFailureCount,failureReason:p.fetchFailureReason,errorUpdateCount:p.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:p.dataUpdateCount>l.dataUpdateCount||p.errorUpdateCount>l.errorUpdateCount,isFetching:x,isRefetching:x&&!O,isLoadingError:X&&!F,isPaused:p.fetchStatus==="paused",isPlaceholderData:m,isRefetchError:X&&F,isStale:As(t,n),refetch:this.refetch,promise:u(this,Le),isEnabled:de(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let M=N.data!==void 0,B=N.status==="error"&&!M,A=D=>{B?D.reject(N.error):M&&D.resolve(N.data)},I=()=>{let D=b(this,Le,N.promise=Qn());A(D)},Q=u(this,Le);switch(Q.status){case"pending":t.queryHash===r.queryHash&&A(Q);break;case"fulfilled":(B||N.data!==Q.value)&&I();break;case"rejected":(!B||N.error!==Q.reason)&&I();break}}return N}updateResult(){let t=u(this,ue),n=this.createResult(u(this,k),this.options);if(b(this,St,u(this,k).state),b(this,Vt,this.options),u(this,St).data!==void 0&&b(this,$t,u(this,k)),Ut(n,t))return;b(this,ue,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!u(this,Gt).size)return!0;let o=new Set(i??u(this,Gt));return this.options.throwOnError&&o.add("error"),Object.keys(u(this,ue)).some(c=>{let a=c;return u(this,ue)[a]!==t[a]&&o.has(a)})};T(this,q,Vi).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&T(this,q,Ps).call(this)}},fe=new WeakMap,k=new WeakMap,Nn=new WeakMap,ue=new WeakMap,St=new WeakMap,Vt=new WeakMap,Le=new WeakMap,nt=new WeakMap,Kn=new WeakMap,Ht=new WeakMap,$t=new WeakMap,Rt=new WeakMap,xt=new WeakMap,rt=new WeakMap,Gt=new WeakMap,q=new WeakSet,Un=function(t){T(this,q,Es).call(this);let n=u(this,k).fetch(this.options,t);return t?.throwOnError||(n=n.catch(V)),n},Ss=function(){T(this,q,Cs).call(this);let t=Ce(this.options.staleTime,u(this,k));if(Oe.isServer()||u(this,ue).isStale||!On(t))return;let r=mr(u(this,ue).dataUpdatedAt,t)+1;b(this,Rt,ke.setTimeout(()=>{u(this,ue).isStale||this.updateResult()},r))},Rs=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(u(this,k)):this.options.refetchInterval)??!1},xs=function(t){T(this,q,Ts).call(this),b(this,rt,t),!(Oe.isServer()||de(this.options.enabled,u(this,k))===!1||!On(u(this,rt))||u(this,rt)===0)&&b(this,xt,ke.setInterval(()=>{(this.options.refetchIntervalInBackground||Dt.isFocused())&&T(this,q,Un).call(this)},u(this,rt)))},Ps=function(){T(this,q,Ss).call(this),T(this,q,xs).call(this,T(this,q,Rs).call(this))},Cs=function(){u(this,Rt)!==void 0&&(ke.clearTimeout(u(this,Rt)),b(this,Rt,void 0))},Ts=function(){u(this,xt)!==void 0&&(ke.clearInterval(u(this,xt)),b(this,xt,void 0))},Es=function(){let t=u(this,fe).getQueryCache().build(u(this,fe),this.options);if(t===u(this,k))return;let n=u(this,k);b(this,k,t),b(this,Nn,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},Vi=function(t){U.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(u(this,ue))}),u(this,fe).getQueryCache().notify({query:u(this,k),type:"observerResultsUpdated"})})},Bi);function Tu(e,t){return de(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function ji(e,t){return Tu(e,t)||e.state.data!==void 0&&Is(e,t,t.refetchOnMount)}function Is(e,t,n){if(de(t.enabled,e)!==!1&&Ce(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&As(e,t)}return!1}function Wi(e,t,n,r){return(e!==t||de(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&As(e,n)}function As(e,t){return de(t.enabled,e)!==!1&&e.isStaleByTime(Ce(t.staleTime,e))}function Eu(e,t){return!Ut(e.getCurrentResult(),t)}function zt(e){return{onFetch:(t,n)=>{let r=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],o=t.state.data?.pageParams||[],c={pages:[],pageParams:[]},a=0,l=async()=>{let d=!1,p=y=>{Oi(y,()=>t.signal,()=>d=!0)},m=yr(t.options,t.fetchOptions),f=async(y,h,g)=>{if(d)return Promise.reject();if(h==null&&y.pages.length)return Promise.resolve(y);let x=(()=>{let F={client:t.client,queryKey:t.queryKey,pageParam:h,direction:g?"backward":"forward",meta:t.options.meta};return p(F),F})(),O=await m(x),{maxPages:X}=t.options,P=g?Mi:ki;return{pages:P(y.pages,O,X),pageParams:P(y.pageParams,h,X)}};if(s&&i.length){let y=s==="backward",h=y?Hi:ks,g={pages:i,pageParams:o},v=h(r,g);c=await f(g,v,y)}else{let y=e??i.length;do{let h=a===0?o[0]??r.initialPageParam:ks(r,c);if(a>0&&h==null)break;c=await f(c,h),a++}while(a<y)}return c};t.options.persister?t.fetchFn=()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=l}}}function ks(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 Hi(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function $i(e,t){return t?ks(e,t)!=null:!1}function Gi(e,t){return!t||!e.getPreviousPageParam?!1:Hi(e,t)!=null}var Ms=class extends Ln{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:zt()})}getOptimisticResult(e){return e.behavior=zt(),super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){let{state:n}=e,r=super.createResult(e,t),{isFetching:s,isRefetching:i,isError:o,isRefetchError:c}=r,a=n.fetchMeta?.fetchMore?.direction,l=o&&a==="forward",d=s&&a==="forward",p=o&&a==="backward",m=s&&a==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:$i(t,n.data),hasPreviousPage:Gi(t,n.data),isFetchNextPageError:l,isFetchingNextPage:d,isFetchPreviousPageError:p,isFetchingPreviousPage:m,isRefetchError:c&&!l&&!p,isRefetching:i&&!d&&!m}}};var jn,Fe,oe,Pt,qe,st,zi,Ji=(zi=class extends br{constructor(t){super();w(this,qe);w(this,jn);w(this,Fe);w(this,oe);w(this,Pt);b(this,jn,t.client),this.mutationId=t.mutationId,b(this,oe,t.mutationCache),b(this,Fe,[]),this.state=t.state||Os(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){u(this,Fe).includes(t)||(u(this,Fe).push(t),this.clearGcTimeout(),u(this,oe).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){b(this,Fe,u(this,Fe).filter(n=>n!==t)),this.scheduleGc(),u(this,oe).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){u(this,Fe).length||(this.state.status==="pending"?this.scheduleGc():u(this,oe).remove(this))}continue(){return u(this,Pt)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{T(this,qe,st).call(this,{type:"continue"})},r={client:u(this,jn),meta:this.options.meta,mutationKey:this.options.mutationKey};b(this,Pt,vr({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(o,c)=>{T(this,qe,st).call(this,{type:"failed",failureCount:o,error:c})},onPause:()=>{T(this,qe,st).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>u(this,oe).canRun(this)}));let s=this.state.status==="pending",i=!u(this,Pt).canStart();try{if(s)n();else{T(this,qe,st).call(this,{type:"pending",variables:t,isPaused:i}),u(this,oe).config.onMutate&&await u(this,oe).config.onMutate(t,this,r);let c=await this.options.onMutate?.(t,r);c!==this.state.context&&T(this,qe,st).call(this,{type:"pending",context:c,variables:t,isPaused:i})}let o=await u(this,Pt).start();return await u(this,oe).config.onSuccess?.(o,t,this.state.context,this,r),await this.options.onSuccess?.(o,t,this.state.context,r),await u(this,oe).config.onSettled?.(o,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(o,null,t,this.state.context,r),T(this,qe,st).call(this,{type:"success",data:o}),o}catch(o){try{await u(this,oe).config.onError?.(o,t,this.state.context,this,r)}catch(c){Promise.reject(c)}try{await this.options.onError?.(o,t,this.state.context,r)}catch(c){Promise.reject(c)}try{await u(this,oe).config.onSettled?.(void 0,o,this.state.variables,this.state.context,this,r)}catch(c){Promise.reject(c)}try{await this.options.onSettled?.(void 0,o,t,this.state.context,r)}catch(c){Promise.reject(c)}throw T(this,qe,st).call(this,{type:"error",error:o}),o}finally{u(this,oe).runNext(this)}}},jn=new WeakMap,Fe=new WeakMap,oe=new WeakMap,Pt=new WeakMap,qe=new WeakSet,st=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),U.batch(()=>{u(this,Fe).forEach(r=>{r.onMutationUpdate(t)}),u(this,oe).notify({mutation:this,type:"updated",action:t})})},zi);function Os(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var je,Te,Wn,Yi,Xi=(Yi=class extends ve{constructor(t={}){super();w(this,je);w(this,Te);w(this,Wn);this.config=t,b(this,je,new Set),b(this,Te,new Map),b(this,Wn,0)}build(t,n,r){let s=new Ji({client:t,mutationCache:this,mutationId:++Mn(this,Wn)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){u(this,je).add(t);let n=wr(t);if(typeof n=="string"){let r=u(this,Te).get(n);r?r.push(t):u(this,Te).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(u(this,je).delete(t)){let n=wr(t);if(typeof n=="string"){let r=u(this,Te).get(n);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&u(this,Te).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=wr(t);if(typeof n=="string"){let s=u(this,Te).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=wr(t);return typeof n=="string"?u(this,Te).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){U.batch(()=>{u(this,je).forEach(t=>{this.notify({type:"removed",mutation:t})}),u(this,je).clear(),u(this,Te).clear()})}getAll(){return Array.from(u(this,je))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>gr(n,r))}findAll(t={}){return this.getAll().filter(n=>gr(t,n))}notify(t){U.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){let t=this.getAll().filter(n=>n.state.isPaused);return U.batch(()=>Promise.all(t.map(n=>n.continue().catch(V))))}},je=new WeakMap,Te=new WeakMap,Wn=new WeakMap,Yi);function wr(e){return e.options.scope?.id}var We,it,pe,Be,Ve,Sr,Fs,Zi,qs=(Zi=class extends ve{constructor(t,n){super();w(this,Ve);w(this,We);w(this,it);w(this,pe);w(this,Be);b(this,We,t),this.setOptions(n),this.bindMethods(),T(this,Ve,Sr).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let n=this.options;this.options=u(this,We).defaultMutationOptions(t),Ut(this.options,n)||u(this,We).getMutationCache().notify({type:"observerOptionsUpdated",mutation:u(this,pe),observer:this}),n?.mutationKey&&this.options.mutationKey&&Me(n.mutationKey)!==Me(this.options.mutationKey)?this.reset():u(this,pe)?.state.status==="pending"&&u(this,pe).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||u(this,pe)?.removeObserver(this)}onMutationUpdate(t){T(this,Ve,Sr).call(this),T(this,Ve,Fs).call(this,t)}getCurrentResult(){return u(this,it)}reset(){u(this,pe)?.removeObserver(this),b(this,pe,void 0),T(this,Ve,Sr).call(this),T(this,Ve,Fs).call(this)}mutate(t,n){return b(this,Be,n),u(this,pe)?.removeObserver(this),b(this,pe,u(this,We).getMutationCache().build(u(this,We),this.options)),u(this,pe).addObserver(this),u(this,pe).execute(t)}},We=new WeakMap,it=new WeakMap,pe=new WeakMap,Be=new WeakMap,Ve=new WeakSet,Sr=function(){let t=u(this,pe)?.state??Os();b(this,it,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},Fs=function(t){U.batch(()=>{if(u(this,Be)&&this.hasListeners()){let n=u(this,it).variables,r=u(this,it).context,s={client:u(this,We),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{u(this,Be).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{u(this,Be).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{u(this,Be).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{u(this,Be).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(u(this,it))})})},Zi);var Qe,eo,to=(eo=class extends ve{constructor(t={}){super();w(this,Qe);this.config=t,b(this,Qe,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??Fn(s,n),o=this.get(i);return o||(o=new Ki({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(o)),o}add(t){u(this,Qe).has(t.queryHash)||(u(this,Qe).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=u(this,Qe).get(t.queryHash);n&&(t.destroy(),n===t&&u(this,Qe).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){U.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return u(this,Qe).get(t)}getAll(){return[...u(this,Qe).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>hr(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>hr(t,r)):n}notify(t){U.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){U.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){U.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Qe=new WeakMap,eo);var H,ot,at,Jt,Yt,ct,Xt,Zt,no,Qs=(no=class{constructor(e={}){w(this,H);w(this,ot);w(this,at);w(this,Jt);w(this,Yt);w(this,ct);w(this,Xt);w(this,Zt);b(this,H,e.queryCache||new to),b(this,ot,e.mutationCache||new Xi),b(this,at,e.defaultOptions||{}),b(this,Jt,new Map),b(this,Yt,new Map),b(this,ct,0)}mount(){Mn(this,ct)._++,u(this,ct)===1&&(b(this,Xt,Dt.subscribe(async e=>{e&&(await this.resumePausedMutations(),u(this,H).onFocus())})),b(this,Zt,Wt.subscribe(async e=>{e&&(await this.resumePausedMutations(),u(this,H).onOnline())})))}unmount(){var e,t;Mn(this,ct)._--,u(this,ct)===0&&((e=u(this,Xt))==null||e.call(this),b(this,Xt,void 0),(t=u(this,Zt))==null||t.call(this),b(this,Zt,void 0))}isFetching(e){return u(this,H).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return u(this,ot).findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return u(this,H).get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=u(this,H).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Ce(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return u(this,H).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=u(this,H).get(r.queryHash)?.state.data,o=Ii(t,i);if(o!==void 0)return u(this,H).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return U.batch(()=>u(this,H).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return u(this,H).get(t.queryHash)?.state}removeQueries(e){let t=u(this,H);U.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=u(this,H);return U.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=U.batch(()=>u(this,H).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(V).catch(V)}invalidateQueries(e,t={}){return U.batch(()=>(u(this,H).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=U.batch(()=>u(this,H).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(V)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(V)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=u(this,H).build(this,t);return n.isStaleByTime(Ce(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(V).catch(V)}fetchInfiniteQuery(e){return e.behavior=zt(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(V).catch(V)}ensureInfiniteQueryData(e){return e.behavior=zt(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Wt.isOnline()?u(this,ot).resumePausedMutations():Promise.resolve()}getQueryCache(){return u(this,H)}getMutationCache(){return u(this,ot)}getDefaultOptions(){return u(this,at)}setDefaultOptions(e){b(this,at,e)}setQueryDefaults(e,t){u(this,Jt).set(Me(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...u(this,Jt).values()],n={};return t.forEach(r=>{yt(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){u(this,Yt).set(Me(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...u(this,Yt).values()],n={};return t.forEach(r=>{yt(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...u(this,at).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Fn(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===Nt&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...u(this,at).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){u(this,H).clear(),u(this,ot).clear()}},H=new WeakMap,ot=new WeakMap,at=new WeakMap,Jt=new WeakMap,Yt=new WeakMap,ct=new WeakMap,Xt=new WeakMap,Zt=new WeakMap,no);var en=J(ce(),1),so=J(Rr(),1),Ds=en.createContext(void 0),j=e=>{let t=en.useContext(Ds);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Bn=({client:e,children:t})=>(en.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,so.jsx)(Ds.Provider,{value:e,children:t}));var xr=J(ce(),1),io=xr.createContext(!1),oo=()=>xr.useContext(io),Ff=io.Provider;var Vn=J(ce(),1),Iu=J(Rr(),1);function Au(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var ku=Vn.createContext(Au()),ao=()=>Vn.useContext(ku);var co=J(ce(),1);var uo=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?Kt(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},lo=e=>{co.useEffect(()=>{e.clearReset()},[e])},fo=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||Kt(n,[e.error,r]));var po=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))}},mo=(e,t)=>e.isLoading&&e.isFetching&&!t,ho=(e,t)=>e?.suspense&&t.isPending,Us=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var ut=J(ce(),1);function Pr(e,t,n){let r=oo(),s=ao(),i=j(n),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let c=i.getQueryCache().get(o.queryHash);o._optimisticResults=r?"isRestoring":"optimistic",po(o),uo(o,s,c),lo(s);let a=!i.getQueryCache().get(o.queryHash),[l]=ut.useState(()=>new t(i,o)),d=l.getOptimisticResult(o),p=!r&&e.subscribed!==!1;if(ut.useSyncExternalStore(ut.useCallback(m=>{let f=p?l.subscribe(U.batchCalls(m)):V;return l.updateResult(),f},[l,p]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),ut.useEffect(()=>{l.setOptions(o)},[o,l]),ho(o,d))throw Us(o,l,s);if(fo({result:d,errorResetBoundary:s,throwOnError:o.throwOnError,query:c,suspense:o.suspense}))throw d.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(o,d),o.experimental_prefetchInRender&&!Oe.isServer()&&mo(d,r)&&(a?Us(o,l,s):c?.promise)?.catch(V).finally(()=>{l.updateResult()}),o.notifyOnChangeProps?d:l.trackResult(d)}function K(e,t){return Pr(e,Ln,t)}var He=J(ce(),1);function ge(e,t){let n=j(t),[r]=He.useState(()=>new qs(n,e));He.useEffect(()=>{r.setOptions(e)},[r,e]);let s=He.useSyncExternalStore(He.useCallback(o=>r.subscribe(U.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=He.useCallback((o,c)=>{r.mutate(o,c).catch(V)},[r]);if(s.error&&Kt(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function Hn(e,t){return Pr(e,Ms,t)}var _o=J(yo(),1),$n=typeof window<"u"&&window.__FSAOS_CONFIG__||{},Gn=Array.isArray($n.sources)?$n.sources:[],Mu=$n.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",Ou=$n.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",we=$n.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",L=(0,_o.createClient)(Mu,Ou,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var zn=null,Cr=0,vo,Ls,Tr=!1;vo=new Promise(e=>{Ls=e});L.auth.onAuthStateChange((e,t)=>{t?.access_token?(zn=t.access_token,Cr=t.expires_at??Math.floor(Date.now()/1e3)+3600):(zn=null,Cr=0),Tr||(Tr=!0,Ls())});setTimeout(()=>{Tr||(Tr=!0,Ls())},5e3);function bo(e,t){zn=e,Cr=t??Math.floor(Date.now()/1e3)+3600}function js(){zn=null,Cr=0}async function $e(){let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{};if(e.embedToken){if(typeof e.embedToken=="function")try{return await e.embedToken()??null}catch{return null}return e.embedToken}return await vo,zn}var sn=null,on=null,wo=0,Ns=new Set,Ws,Jn,an=!1;Ws=new Promise(e=>{Jn=e});function Bs(){wo++,Ns.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function Ir(e){let t=typeof e=="string"?e:e.path,n=sn!==t||on?.id!==(typeof e=="string"?void 0:e.id);sn=t,on=typeof e=="string"?null:e,typeof e!="string"&&!Ct.some(r=>r.id===e.id)&&(Ct=[...Ct,e],Gs()),an||(an=!0,Jn()),n&&Bs()}function cn(){return sn}function Se(){return on}function Vs(){return wo}function Hs(e){return Ns.add(e),()=>{Ns.delete(e)}}function Yn(){return Ws}function $s(){return an}var Er=null;function Tt(e,t={}){if(Er){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}Er=e,t.activate!==!1&&Ir(e)}function le(){return Er}var Ct=[],Ks=new Set,So=0;function Gs(){So++,Ks.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function De(){return Ct}function Xn(){return So}function Ar(e){return Ks.add(e),()=>{Ks.delete(e)}}function Ro(e,t){let n=JSON.stringify(Ct)!==JSON.stringify(e),r=sn!==t.path||on?.id!==t.id;Ct=e,sn=t.path,on=t,an||(an=!0,Jn()),n&&Gs(),r&&Bs()}var nn=null,tn=null,rn=0;function te(){return rn}async function lt(){if(nn)return nn;if(tn)return tn;let e=rn;return tn=(async()=>{let t=It(),n=await $e();if(e!==rn)throw new Error("Session changed during initialization");let r={};n&&(r.Authorization=`Bearer ${n}`);let s=await fetch(`${we}/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!==rn)throw new Error("Session changed during initialization");let o=i.entry||i;return nn={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},nn})().catch(t=>{throw e===rn&&(tn=null),t}),tn}function Et(){return nn}function zs(){rn++,nn=null,tn=null,sn=null,on=null,Er=null,Ct=[]}var xo=[];function ne(e){xo.push(e)}function un(){zs(),js(),Jn(),an=!1,Ws=new Promise(e=>{Jn=e}),Bs(),Gs();for(let e of xo)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function It(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var Po=Ir,re=cn,se=Vs,Ee=Hs,Co=Yn,kr=$s;var Js=0,To=!1,Eo=0;function Io(e){if(typeof e!="string")return;let t=Date.parse(e);Number.isNaN(t)||(Js=t-Date.now(),To=!0,Eo=Date.now())}function Mr(){return Date.now()+Js}function Ao(){return To}function ko(){return Js}function Mo(){return Eo}function Oo(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Mr()>=t}function Fo(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Math.max(0,t-Mr())}var Fu=new Set(["list-memberships","init"]),Re=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);Y(this,"name","GatewayRequestError");Y(this,"method");Y(this,"status");Y(this,"statusText");Y(this,"payload");Y(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={}){let n=te(),r=cn(),s=It(),i=`${we}/d/${s}`,o={"Content-Type":"application/json"},c=await $e();if(n!==te())throw new Error("Session changed before gateway request");if(c&&(o.Authorization=`Bearer ${c}`),!Fu.has(e)&&!t._scope_path&&await Yn(),n!==te())throw new Error("Session changed before gateway request");let a={...t},l=Et();!a.domain_scope_id&&l?.scope_id&&(a.domain_scope_id=l.scope_id);let d=r??cn();!a._scope_path&&d&&(a._scope_path=d);let p=await fetch(i,{method:"POST",headers:o,body:JSON.stringify({method:e,params:a})}),m=await p.text();if(n!==te())throw new Error("Session changed during gateway request");let f=null;if(m)try{f=JSON.parse(m)}catch{}if(!p.ok||!f)throw new Re({method:e,status:p.status,statusText:p.statusText,payload:f,responseBody:m});if(f.success===!1){let y=f.error||"",h=f.denied_by||f.error_type||"";throw h==="rule"||h==="access"||h==="entitlement"||y==="RULE_DENIED"||y==="ACCESS_DENIED"||y==="PERMISSION_DENIED"||y==="ENTITLEMENT_REQUIRED"?new Xe(f):new Re({method:e,status:p.status,statusText:p.statusText,payload:f,responseBody:m})}return f&&f.server_now!==void 0&&Io(f.server_now),f}var _=J(ce(),1),rl=J(Qo(),1),sl=J(Rr(),1);var Do=new WeakMap;function Ge(e,t,n={}){let r=n.exact===!0,s=()=>e.invalidateQueries({queryKey:t,exact:r},{cancelRefetch:!1}),i=e.getQueryCache().findAll({queryKey:t,exact:r,fetchStatus:"fetching"}).flatMap(p=>p.promise?[p.promise]:[]);if(i.length===0)return s();let o=`${r?"=":"^"}${JSON.stringify(t)}`,c=Do.get(e);c||(c=new Map,Do.set(e,c));let a=c.get(o);if(a)return a;let l=c,d=Promise.allSettled(i).then(()=>(l.delete(o),s()));return l.set(o,d),d}function dt(e,t){return typeof e=="string"&&(e===t||e.startsWith(`${t}/`))}var Or=new WeakMap,Uo=e=>e.meta?.arrangementRealtime===!0;function ln(e,t){let n=e.getQueryCache().find({queryKey:t,exact:!0});if(!n)return;let r=Or.get(e);r||(r=new Map,Or.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&&Ge(e,t,{exact:!0})},250))}function No(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){if(!Uo(n))continue;let r=n.state.data;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)))&&ln(e,n.queryKey)}}function Ko(e){for(let t of e.getQueryCache().getAll())Uo(t)&&t.state.data!==void 0&&ln(e,t.queryKey)}function Lo(e){Or.get(e)?.forEach(clearTimeout),Or.delete(e)}var ze=null;ne(()=>{ze&&(ze.cancelQueries({queryKey:["vfs"]}),ze.removeQueries({queryKey:["vfs"]}))});function jo(e){if(ze&&ze!==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.");ze=e}function C(){return ze||(ze=new Qs({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),ze}var Wo=new Proxy({},{get(e,t,n){let r=C(),s=r[t];return typeof s=="function"?s.bind(r):s}});var Fr=new WeakMap;function Ys(e){return e.meta?.infiniteItemsRealtime?.filter}function qu(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 Qu(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 Du(e,t,n){if(qu(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&&!dt(n.path,r)&&!dt(n.old_path,r))return!1;if(n.item_type==="symlink"&&s&&i)return!0;let o=Qu(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 Bo(e,t){let n=Fr.get(e);n||(n=new Map,Fr.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||!Ys(t))&&Ge(e,t.queryKey,{exact:!0})},500))}function Vo(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){let r=Ys(n);r&&Du(n,r,t)&&Bo(e,n)}}function Ho(e){for(let t of e.getQueryCache().getAll())Ys(t)&&t.state.data!==void 0&&Bo(e,t)}function $o(e){Fr.get(e)?.forEach(clearTimeout),Fr.delete(e)}var qr=class extends Error{constructor(){super("The server did not confirm the selected-Space listing contract")}};function Go(e,t){if(!Array.isArray(t)||t.some(n=>typeof n!="string")||JSON.stringify([...new Set(t)].sort())!==JSON.stringify(e))throw new qr}function At(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 dn(e){return e instanceof qr||e instanceof Xe||e instanceof Re&&(e.payload?.error==="SPACE_SELECTION_UNAVAILABLE"||e.payload?.error==="QUERY_PARAMS_INVALID"||e.status===401||e.status===403)}function ee(){return re()??"__unscoped__"}var S={all:()=>["vfs",ee()],item:e=>["vfs",ee(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",ee(),"children",e],allChildren:()=>["vfs",ee(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",ee(),"search",e,...t??[]],items:(e,t)=>["vfs",ee(),"items",e,JSON.stringify(At(t??{}))],allItems:()=>["vfs",ee(),"items"],tree:(e,t)=>["vfs",ee(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",ee(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",ee(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",ee(),"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",ee(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",ee(),"channel-messages"],channels:e=>["vfs",ee(),"channels",e??"all"],allChannels:()=>["vfs",ee(),"channels"],notifications:(e,t)=>["vfs",ee(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",ee(),"notifications"],unreadCounts:()=>["vfs",ee(),"unread-counts"],memberships:e=>["memberships",e]};var Uu=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function $(...e){Uu&&console.log("[WS]",...e)}var E=null,fn=null,mn=null,Zn=0,Nu=3e4,zo=1e4,gn=!1,Jo=!1,ta=3e4,Ku=ta*2+5e3,Qr=0,Dr=null,Yo=!1;function Lu(){tr(),Qr=Date.now(),Dr=setInterval(()=>{if(E&&E.readyState===WebSocket.OPEN&&Date.now()-Qr>Ku){$("ping: no inbound traffic for",Date.now()-Qr,"ms \u2014 closing half-open socket");try{E.close(4e3,"liveness timeout")}catch{}return}Ye({type:"ping"})},ta)}function tr(){Dr&&(clearInterval(Dr),Dr=null)}function ju(){typeof document>"u"||(document.hidden?tr():er()&&($("Tab visible, reconnecting..."),kt()))}function Wu(){Yo||typeof document>"u"||(document.addEventListener("visibilitychange",ju),Yo=!0)}var ye={};function Zs(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return!n||!r?n===r:r===n||r.startsWith(`${n}/`)}var hn=[],Je=new Map,pn=new Map,xe=new Map;function Bu(e){let t=pn.get(e);return t?Array.from(new Set(Array.from(t.values()).flatMap(n=>n.event_types))).sort():[]}function Xo(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):!1}function Zo(e){let t=Bu(e);if(t.length===0)return Je.delete(e),null;let n={scope_id:e,event_types:t};return Je.set(e,n),n}var Ue=new Map,ft=new Map,Xs="disconnected",Ur=[];function Nr(e){if(Xs!==e){Xs=e;for(let t of[...Ur])try{t(e)}catch{}}}function Vu(e){Ue.set(e,"ready");let t=ft.get(e);if(t){ft.delete(e);for(let n of t)n()}}function Hu(){for(let e of Ue.keys())Ue.set(e,"disconnected")}function ei(e,t){Ue.set(e,"pending"),Ye({type:"subscribe_path",path:e,event_types:t})}function $u(){return Object.keys(ye).some(t=>ye[t]&&ye[t].length>0)||hn.length>0}function er(){return Je.size>0||xe.size>0}async function kt(){if(!er()){$("ensureConnection: no active subscriptions, skipping");return}if(E&&E.readyState===WebSocket.OPEN){$("ensureConnection: already open");return}if(fn)return $("ensureConnection: connection already in flight, waiting..."),fn;if(E){$("ensureConnection: killing stale WS in state",E.readyState);try{E.close()}catch{}E=null}return gn=!1,fn=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=we,n=await $e();if(!n){$("ensureConnection: no token available, will retry"),ea();return}let r=t.startsWith("https")?"wss":"ws",s=t.replace(/^https?:\/\//,""),i=`${r}://${s}/ws`;i+=`?token=${encodeURIComponent(n)}`,$("ensureConnection: opening WS to",i.substring(0,50)+"..."),Nr("connecting"),E=new WebSocket(i);let o=E;await new Promise((c,a)=>{if(!E)return a(new Error("WebSocket not created"));let l=setTimeout(()=>{if(E===o){if($("ensureConnection: TIMEOUT after",zo,"ms"),E&&E.readyState!==WebSocket.OPEN){try{E.close()}catch{}E=null}a(new Error("WebSocket connection timeout"))}},zo);o.onopen=()=>{if(E!==o)return;clearTimeout(l),$("ensureConnection: CONNECTED");let d=Jo;Jo=!0,Zn=0,Nr("connected"),Gu(d),(typeof document>"u"||!document.hidden)&&Lu(),Wu(),c()},o.onmessage=d=>{E===o&&zu(d.data)},o.onerror=()=>{$("ensureConnection: WS error event")},o.onclose=d=>{clearTimeout(l),E===o&&($("ensureConnection: WS closed, code:",d.code,"reason:",d.reason),E=null,tr(),Hu(),Nr("disconnected"),!gn&&er()&&ea(),a(new Error(`WebSocket closed: ${d.code}`)))}})}catch(e){$("ensureConnection: failed -",e?.message||e)}finally{fn=null}})(),fn}function ea(){if(mn||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,Zn)+Math.random()*1e3,Nu);Zn++,$("scheduleReconnect: attempt",Zn,"in",Math.round(e),"ms"),mn=setTimeout(()=>{mn=null,er()&&kt()},e)}function Gu(e=!1){for(let t of Je.values())$("resubscribeAll: scope",t.scope_id),Ye({type:"subscribe",scope_id:t.scope_id,event_types:t.event_types});for(let t of xe.values())$("resubscribeAll: path",t.path),ei(t.path,t.event_types);if(e)try{let t=C();Ho(t),Ko(t);for(let n of xe.values())t.invalidateQueries({queryKey:S.item(n.path)}),t.invalidateQueries({queryKey:S.children(n.path)});$("resubscribeAll: invalidated",xe.size,"paths after reconnect")}catch(t){$("resubscribeAll: cache invalidation skipped",t)}}function Ye(e){E&&E.readyState===WebSocket.OPEN&&E.send(JSON.stringify(e))}function zu(e){Qr=Date.now();try{let t=JSON.parse(e);if(t.type==="subscribed_path"){typeof t.path=="string"&&Vu(t.path);return}if(t.type==="subscribed"||t.type==="unsubscribed"||t.type==="unsubscribed_path"||t.type==="pong")return;if(t.type==="error"){console.warn("[WS] Server error:",t.message);return}if(t.type==="event"||t.event_type){let n=t.event_type||"message",r=t.data||t;if(n==="vfs_change"&&(Vo(C(),r),No(C(),r)),typeof r.path=="string")for(let[s,i]of Object.entries(ye))s!=="*"&&Zs(s,r.path)&&i.forEach(o=>o(r));ye["*"]&&ye["*"].forEach(s=>s(r));for(let s of hn)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function ti(){!$u()&&Je.size===0&&xe.size===0&&E&&(gn=!0,tr(),E.close(),E=null,gn=!1)}function Kr(e,t){return ye[e]||(ye[e]=[]),ye[e].push(t),xe.has(e)||(xe.set(e,{path:e,event_types:["token_stream"]}),E&&E.readyState===WebSocket.OPEN?ei(e,["token_stream"]):Ue.set(e,"pending")),kt(),()=>{let n=ye[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete ye[e],xe.delete(e),Ue.delete(e),ft.delete(e),Ye({type:"unsubscribe_path",path:e}))}ti()}}function ie(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return hn.push(...s),er()&&kt(),()=>{for(let i of s){let o=hn.indexOf(i);o!==-1&&hn.splice(o,1)}ti()}}function yn(e,t=["vfs_change","ccm_change"]){let n=Symbol(e),r=Array.from(new Set(t)).sort();if(r.length===0)return()=>{};let s=pn.get(e)??new Map,i=Je.get(e)?.event_types;s.set(n,{event_types:r}),pn.set(e,s);let o=Zo(e);if(!o)return()=>{};$("subscribeToScope:",e,o.event_types),E&&E.readyState===WebSocket.OPEN&&!Xo(i,o.event_types)&&Ye({type:"subscribe",scope_id:e,event_types:o.event_types}),kt();let c=!0;return()=>{if(!c)return;c=!1;let a=pn.get(e);if(!a?.delete(n))return;let l=Je.get(e)?.event_types;if(a.size===0)pn.delete(e),Je.delete(e),Ye({type:"unsubscribe",scope_id:e});else{let d=Zo(e);d&&E&&E.readyState===WebSocket.OPEN&&!Xo(l,d.event_types)&&Ye({type:"subscribe",scope_id:e,event_types:d.event_types})}ti()}}function na(e,t,n={}){Ye({type:"emit",scope_id:e,event_type:t,payload:n})}function ni(){$("disconnectSSE: tearing down"),$o(C()),Lo(C()),gn=!0,tr(),E&&(E.close(),E=null),mn&&(clearTimeout(mn),mn=null),fn=null,gn=!1,Zn=0;for(let e of Object.keys(ye))delete ye[e];hn.length=0,Je.clear(),pn.clear(),xe.clear(),Ue.clear(),ft.clear(),Nr("disconnected")}function ra(){Ye({type:"ping"})}function sa(e){return xe.has(e)?Ue.get(e)??"pending":"unsubscribed"}function ia(e,t=5e3){return xe.has(e)?Ue.get(e)==="ready"&&E&&E.readyState===WebSocket.OPEN?Promise.resolve(!0):(kt(),new Promise(n=>{let r=!1,s=ft.get(e)??[],i=()=>{r||(r=!0,clearTimeout(o),n(!0))};s.push(i),ft.set(e,s);let o=setTimeout(()=>{if(r)return;r=!0;let c=ft.get(e);if(c){let a=c.indexOf(i);a!==-1&&c.splice(a,1),c.length===0&&ft.delete(e)}n(!1)},t)})):Promise.resolve(!1)}function oa(e){let t=xe.get(e);if(!t){$("resubscribePath: no active subscription for",e);return}E&&E.readyState===WebSocket.OPEN?($("resubscribePath: re-sending frame for",e),ei(t.path,t.event_types)):(Ue.set(e,"pending"),kt())}function aa(e){Ur.push(e);try{e(Xs)}catch{}return()=>{let t=Ur.indexOf(e);t!==-1&&Ur.splice(t,1)}}ne(ni);function ca(){return new Date().toISOString()}function ua(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function Pe(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||ca(),updated_at:e.updated_at||ca(),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 nr(e){return(e.content?.items||e.items||[]).map(Pe)}async function jr(e){try{let t=await R("read",{id:e});if(t.item_name||t.item_path){let r=Pe(t);return r.path&&C().setQueryData(S.item(r.path),r),r}let n=t.item;if(n){let r=Pe(n);return r.path&&C().setQueryData(S.item(r.path),r),r}return null}catch{return null}}async function Wr(e){try{let t=await R("read",{path:e});if(t.item_name||t.item_path)return Pe(t);let n=t.item;return n?Pe(n):null}catch{return null}}async function rr(e){try{let t=await R("list",{path:e,limit:200}),n=nr(t);for(let r of n)C().setQueryData(S.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function la(e,t){let{items:n}=await vn({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 Br(e,t,n){try{let r=await R("list",{path:e,limit:t,offset:n}),s=nr(r);for(let i of s)C().setQueryData(S.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 Vr(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,c=i.type_data;!o||!c||s.set(o,{type_key:o,display_name:c.display_name||o,display_name_plural:c.display_name_plural||o+"s",icon:c.icon||"File",color:c.color||"gray",description:c.description||"",input_schema:c.input_schema||{},system_schema:c.system_schema||{},json_schema:c.input_schema||c.json_schema||{},default_data:c.default_data||{},field_defaults:c.field_defaults||{},renderer_config:c.renderer_config||{},is_system:c.is_system??!1,is_active:c.is_active??!0,is_container:c.is_container??!1,is_scope:c.is_scope??!1,render_mode:c.render_mode||"none",placement_mode:c.placement_mode,direct_parent_types:c.direct_parent_types,allowed_parent_types:c.allowed_parent_types,governed_create:c.governed_create,create_method:c.create_method,dedup:c.dedup,edges:c.edges,events:c.events})}return s}async function Hr(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||ua(),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||ua(),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 $r(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=nr(i);for(let c of o)C().setQueryData(S.item(c.path),c);return o}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function Gr(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 sr(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 zr(e,t=50,n=0){return sr(e,{limit:t,offset:n})}async function Jr(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=nr(s);for(let o of i)C().setQueryData(S.item(o.path),o);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${e}:`,r),[]}}async function Yr(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 _n(e){return!!e&&(!!e.type||Array.isArray(e.any_of)&&e.any_of.length>0)}function Ju(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 Yu=["catalog","parent_only","internal"];function da(e,t={}){if(!e||typeof e!="object")return null;let n=o=>typeof o=="string"||typeof o=="number"||typeof o=="boolean",r=o=>{let c={},a={};for(let[l,d]of Object.entries(o))l.startsWith("field.")&&l.length>6&&n(d)?c[l.slice(6)]=d:l.startsWith("field_in.")&&l.length>9&&Array.isArray(d)&&(a[l.slice(9)]=d.filter(n));return{fields:c,field_in:a}},s={};typeof e.type=="string"&&e.type&&(s.type=e.type),typeof e.sort_by=="string"&&(s.sort_by=e.sort_by),(e.sort_dir==="asc"||e.sort_dir==="desc")&&(s.sort_dir=e.sort_dir),typeof e.name=="string"&&e.name&&(s.name=e.name),typeof e.tag=="string"&&e.tag&&(s.tag=e.tag),typeof e.discovery=="string"&&Yu.includes(e.discovery)&&(s.discovery=e.discovery);let i=r(e);if(Object.keys(i.fields).length&&(s.fields=i.fields),Object.keys(i.field_in).length&&(s.field_in=i.field_in),Array.isArray(e.any_of)){let o=[];for(let c of e.any_of){if(!c||typeof c!="object"||Array.isArray(c))continue;let a=c,l={};typeof a.item_type=="string"&&a.item_type&&(l.item_type=a.item_type);let d=r(a);Object.keys(d.fields).length&&(l.fields=d.fields),Object.keys(d.field_in).length&&(l.field_in=d.field_in),Object.keys(l).length&&o.push(l)}o.length&&(s.any_of=o)}return _n(s)?{...s,...t}:null}async function vn(e,t={}){if(e=At(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(Ju)),Object.keys(r).length>0&&(n.filters=r),e.limit!=null&&(n.limit=e.limit);try{let s=await R("query",n);e.spaceIds!==void 0&&Go(e.spaceIds,s.selected_space_ids??s.content?.selected_space_ids);let i=nr(s);for(let o of i)C().setQueryData(S.item(o.path),o);return{items:i,total_hint:s.total??s.content?.total??i.length}}catch(s){if(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 Xu(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 fa(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:Xu(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 ri(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,reply_count:n.reply_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 pa(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 ri(i)}catch(n){return console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),[]}}async function Xr(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=ri(i),c=fa(i),a=new Map,l=[];for(let d of c)if(d.parentMessagePath){let p=a.get(d.parentMessagePath)||[];p.push(d),a.set(d.parentMessagePath,p)}else l.push(d);return{messages:o,messageCards:a,siblingCards:l,mode:s.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages with cards for ${e}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}async function ir(e,t){try{let n={channel_path:e};t?.parentMessageId&&(n.parent_message_id=t.parentMessageId),t?.limit&&(n.limit=t.limit),t?.before_seq!=null&&(n.before_seq=t.before_seq),t?.after_seq!=null&&(n.after_seq=t.after_seq);let s=await R("get-channel-messages",n),i=s.messages||[],o=fa(i),c=new Map,a=[];for(let l of o)if(l.parentMessagePath){let d=c.get(l.parentMessagePath)||[];d.push(l),c.set(l.parentMessagePath,d)}else a.push(l);return{messages:ri(i),messageCards:c,siblingCards:a,mode:s.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages page for ${e}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}function Lr(e){C().invalidateQueries({queryKey:S.children(e)})}function si(e){C().invalidateQueries({queryKey:S.item(e)})}function ma(e,t){si(e),Lr(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&Lr(r)}function ha(e){let t=e+"/";C().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function ga(){C().invalidateQueries({queryKey:S.all()})}function ya(e){C().invalidateQueries({queryKey:S.types(e)})}function _a(e,t){e?C().invalidateQueries({queryKey:S.channelMessages(e,t)}):C().invalidateQueries({queryKey:S.allChannelMessages()})}function va(e,t){e&&t?C().invalidateQueries({queryKey:S.openEnvelope(e,t)}):e?C().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):C().invalidateQueries({queryKey:S.allOpenEnvelopes()})}function Ne(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}async function Zr(){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 bn=new Map,or=null,es=null,pt=new Map,ba=250;function Mt(e){if(or){wn(e);return}wn(e),or=ie("vfs_change",t=>Zu(t)),es=ie("ccm_change",t=>el(t))}function wn(e){if(bn.has(e))return;let t=yn(e,["vfs_change","ccm_change"]);bn.set(e,t)}function ts(e){let t=bn.get(e);t&&(t(),bn.delete(e))}function ii(){for(let[,e]of bn)e();bn.clear(),or&&(or(),or=null),es&&(es(),es=null),pt.forEach(e=>clearTimeout(e)),pt.clear()}ne(ii);function Zu(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=pt.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{pt.delete(s),tl(n,t,e,s)},ba);pt.set(s,o)}function el(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))return;let s=`ccm:${t??""}:${n??""}`,i=pt.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{pt.delete(s),t&&C().invalidateQueries({queryKey:S.edges(t)}),n&&C().invalidateQueries({queryKey:S.edges(n)}),!t&&!n&&C().invalidateQueries({predicate:c=>c.queryKey[0]==="vfs"&&c.queryKey[1]==="edges"})},ba);pt.set(s,o)}function tl(e,t,n,r){if((e||"").toUpperCase()==="DELETE")C().removeQueries({queryKey:S.item(t)}),C().removeQueries({queryKey:S.children(t)}),C().removeQueries({queryKey:S.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=Pe(i);o&&o.id&&C().setQueryData(S.item(t),o)}catch{}C().invalidateQueries({queryKey:S.children(r)}),C().invalidateQueries({predicate:i=>{let o=i.queryKey;if(o[0]!=="vfs"||o[1]!=="tree")return!1;let c=o[2];return t.startsWith(c+"/")||t===c}}),n.item_id&&C().invalidateQueries({queryKey:S.itemById(n.item_id)})}var Sn=null;ne(()=>{Sn=null});function mt(e){if(e!==Sn||e.generation!==te())throw new Error("Workspace session changed")}function nl(e){return e instanceof Re&&e.payload?.error==="item_not_found"}function ar(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 cr(e){let t=le();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 wa(e,t){return JSON.stringify({mounts:e.map(n=>n.id),last_anchor:t.id})}async function Sa(e,t,n){mt(e);let r=wa(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}),mt(e),e.exists=!0,e.saved=r}function Ra(e,t){let n=De();Mt(le().id);for(let r of n)e.some(s=>s.id===r.id)||ts(r.id);for(let r of e)wn(r.id);Ro(e,t)}async function Ot(e,t,n={}){let r=le();if(!r)throw new Error("Elect a home account before loading mounts");let s=`${e}/settings/mounts`;if(Sn&&Sn.path!==s)throw new Error("Reset the session before changing the mount declaration owner");let i=Sn??(Sn={generation:te(),path:s,scope:r.path,resolve:t,exists:!1,ready:!1,saved:null,queue:Promise.resolve()});return mt(i),i.loading?i.loading:i.ready?De():(i.resolve=t,i.loading=(async()=>{let o=null;try{let d=await R("read",{path:s,_scope_path:i.scope});if(mt(i),o=d.type_data??d.item?.type_data,!o||!Array.isArray(o.mounts)||!o.mounts.every(p=>typeof p=="string"))throw new Error("Invalid saved mount declaration");i.exists=!0}catch(d){if(mt(i),!nl(d))throw d;i.exists=!1}let c=n.initialAnchor?ar(i,n.initialAnchor):r,a=cr(o?o.mounts.map(t).filter(d=>d!==null):[c]),l=o?a.find(d=>d.id===o.last_anchor)??a.find(d=>d.kind==="space")??r:c;return o?i.saved=wa(a,l):n.initialAnchor&&await Sa(i,a,l),mt(i),i.ready=!0,Ra(a,l),a})().finally(()=>{i.loading=void 0}),i.loading)}function ns(e){let t=Sn;if(!t?.ready)return Promise.reject(new Error("Workspace mounts are not loaded"));let n=t.queue.then(async()=>{mt(t);let{refs:r,anchor:s}=e(t);await Sa(t,r,s),mt(t),Ra(r,s)});return t.queue=n.catch(()=>{}),n}function oi(e){return ns(t=>({refs:cr([...De(),ar(t,e)]),anchor:Se()}))}function xa(e){return ns(()=>{if(e===le().id)throw new Error("The home account cannot be unmounted");let t=cr(De().filter(r=>r.id!==e)),n=t.find(r=>r.id===Se()?.id)??t.find(r=>r.kind==="space")??le();return{refs:t,anchor:n}})}function ur(e){return ns(t=>{let n=ar(t,e);return{refs:cr([...De(),n]),anchor:n}})}function rs(e,t){return ns(n=>{let r=cr(e.map(i=>ar(n,i))),s=ar(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 G(){return(0,_.useSyncExternalStore)(Ee,se,se)}function Ta(){return G(),kr()}function Ea(e){return G(),K({queryKey:S.item(e),queryFn:()=>Wr(e),enabled:!!e,staleTime:1/0})}function Ia(e){return G(),K({queryKey:S.itemById(e),queryFn:()=>jr(e),enabled:!!e,staleTime:1/0})}function ci(e){return G(),K({queryKey:S.children(e),queryFn:()=>rr(e),enabled:!!e})}function Aa(e){let t=ci(e);return{...t,children:t.data??[]}}function ka(e,t=1){return G(),K({queryKey:S.tree(e,t),queryFn:()=>$r(e,t),enabled:!!e})}function Ma(e,t){return G(),K({queryKey:S.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(Pe)},enabled:!!e&&e.length>0})}function Oa(e){G();let t=(0,_.useMemo)(()=>e,[JSON.stringify(e)]);return K({queryKey:["vfs",re()??"__unscoped__","resolve",JSON.stringify(t??{})],queryFn:async()=>await R("resolve",t),enabled:!!t?.query&&t.query.length>0})}function Fa(e){G();let t=At(e),n=(0,_.useMemo)(()=>t,[JSON.stringify(t)]),r=K({queryKey:S.items(n?.type??"",n),queryFn:()=>vn(n),enabled:_n(n),...n?.spaceIds!==void 0?{retry:(s,i)=>!dn(i)&&s<1}:{},select:s=>s.items});return n?.spaceIds!==void 0&&dn(r.error)?{...r,data:void 0}:r}function qa(e,t={}){let n=G(),{realtime:r=!1}=t,s=At(e),i=s?.limit??20,o=(0,_.useMemo)(()=>s,[JSON.stringify(s)]),c=(0,_.useMemo)(()=>["vfs",re()??"__unscoped__","infinite-items",o?.type??"",JSON.stringify(o??{})],[n,o]),a=Hn({queryKey:c,queryFn:async({pageParam:p=0})=>vn({...o,limit:i,offset:p},{throwOnError:!0}),initialPageParam:0,getNextPageParam:(p,m,f)=>{if(!(o?.spaceIds!==void 0&&p.total_hint!==void 0&&f+p.items.length>=p.total_hint)&&!(p.items.length<i))return f+p.items.length},enabled:_n(o),...o?.spaceIds!==void 0?{retry:(p,m)=>!dn(m)&&p<1}:{},staleTime:r?1/0:void 0,meta:r&&o?{infiniteItemsRealtime:{filter:o}}:{}}),l=(0,_.useMemo)(()=>{if(o?.spaceIds!==void 0&&dn(a.error))return[];if(!a.data?.pages)return[];let p=new Set,m=[];for(let f of a.data.pages)for(let y of f.items)y.id&&!p.has(y.id)&&(p.add(y.id),m.push(y));return m},[a.data?.pages,a.error,o]),d=o?.spaceIds!==void 0&&dn(a.error);return{allItems:l,refetch:a.refetch,fetchNextPage:a.fetchNextPage,isFetchingNextPage:a.isFetchingNextPage,isExhausted:d||!a.hasNextPage,isLoading:a.isLoading,isFetching:a.isFetching,error:a.error,totalHint:d?void 0:a.data?.pages?.[0]?.total_hint}}function Qa(e){G();let t=20,n=Hn({queryKey:["vfs",re()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>Br(e,t,s),initialPageParam:0,getNextPageParam:(s,i,o)=>{if(!(s.items.length<t))return o+s.items.length},enabled:!!e});return{allItems:(0,_.useMemo)(()=>{if(!n.data?.pages)return[];let s=new Set,i=[];for(let o of n.data.pages)for(let c of o.items)c.id&&!s.has(c.id)&&(s.add(c.id),i.push(c));return i},[n.data?.pages]),fetchNextPage:n.fetchNextPage,isFetchingNextPage:n.isFetchingNextPage,isExhausted:!n.hasNextPage,isLoading:n.isLoading,isFetching:n.isFetching,error:n.error,totalHint:n.data?.pages?.[0]?.total_hint}}function Da(e){return G(),K({queryKey:S.edges(e),queryFn:()=>Hr(e),enabled:!!e})}function ss(e){return G(),K({queryKey:S.types(e),queryFn:()=>Vr(e)})}function Ua(e,t){let n=ss(t);return{...n,data:n.data?.get(e)??void 0}}function Na(e,t){G();let n=(0,_.useMemo)(()=>t?.arguments,[JSON.stringify(t?.arguments)]),r=t?.mode,s=t?.strategy,i=t?.width;return K({queryKey:[...S.openEnvelope(e,s),i],queryFn:async()=>{let o=await Yr(e,{mode:r,strategy:s,arguments:n});if(i&&o.render?.props?.url){let c=o.render.props.url,a=c.includes("?")?"&":"?";o.render.props.url=`${c}${a}w=${i}`}return o},enabled:!!e})}var Pa={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 Ka(e){let t=ss(e),n=t.data??new Map;return(0,_.useMemo)(()=>({canHaveChildren:f=>n.get(f.item_type)?.is_container??!1,isScope:f=>n.get(f.item_type)?.is_scope??!1,isScopeType:f=>n.get(f)?.is_scope??!1,isContainerType:f=>n.get(f)?.is_container??!1,getTypeDefinition:f=>n.get(f),getTypeColor:f=>n.get(f)?.color??"gray",getTypeIcon:f=>n.get(f)?.icon??"File",getTypeDisplayName:f=>n.get(f)?.display_name??f,getKnownEdgeTypes:()=>Object.entries(Pa).map(([f,y])=>({key:f,label:y})),getEdgeTypeLabel:f=>Pa[f]??f.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function La(e,t,n){return G(),K({queryKey:S.memberFocus(e),queryFn:()=>Jr(e,t,n),enabled:!!e})}function ja(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return K({queryKey:S.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>sr(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function Wa(e,t=50,n=0){return K({queryKey:S.itemHistory(e,String(t),String(n)),queryFn:()=>zr(e,t,n),enabled:!!e})}function Ba(e,t=50,n=0){return G(),K({queryKey:S.recentActivity(e,String(t),String(n)),queryFn:()=>Gr(e,t,n),enabled:!!e})}function Va(){let[e,t]=(0,_.useState)(null),[n,r]=(0,_.useState)(!0),[s,i]=(0,_.useState)(null);return(0,_.useEffect)(()=>{let o=!1;return lt().then(c=>{if(!o){let a=typeof window<"u"&&window.__FSAOS_CONFIG__||{};t({path:c.scope_path,scope_id:c.scope_id,fractal_id:c.fractal_id,instance_name:c.instance_name,display_name:c.display_name,componentPath:a.componentPath||"",isEmbed:!!a.embedToken}),r(!1)}}).catch(c=>{o||(i(c instanceof Error?c:new Error(String(c))),r(!1))}),()=>{o=!0}},[]),{data:e,loading:n,error:s}}var il=[];function Ha(){let{user:e}=is(),t=(0,_.useRef)(null),[n,r]=(0,_.useState)(null),s=K({queryKey:S.memberships(e?.id??"anonymous"),queryFn:Zr,enabled:!!e?.id,staleTime:1e3*60*2}),i=s.data??il,o=(0,_.useMemo)(()=>i.filter(m=>m.isAccount!==!1&&!m.isSpace),[i]),c=(0,_.useMemo)(()=>{let m=new Set(o.map(y=>y.accountId)),f=y=>!y.subordinateTo||!m.has(y.subordinateTo);return[...o].sort((y,h)=>Number(f(h))-Number(f(y)))},[o]),a=(0,_.useSyncExternalStore)(Ee,se,se),l=(0,_.useMemo)(()=>{let m=Se();return m?i.find(f=>f.accountId===m.id)??null:null},[a,i]);(0,_.useEffect)(()=>{if(!e?.id){t.current=null;return}if(t.current!==e.id)if(r(null),c.length===1){let m=c[0];le()||Tt(Ne(m)),Mt(m.accountId),m.personalSpacePath&&Ot(m.personalSpacePath,f=>{let y=i.find(h=>h.accountId===f);return y?Ne(y):null}).catch(r),t.current=e.id}else c.length>1&&(t.current=e.id)},[e?.id,c,i]);let d=(0,_.useCallback)(async m=>{let f=i.find(g=>g.path===m);if(!f)throw new Error("Account membership is unavailable");let y=Ne(f);le()||Tt(y);let h=i.find(g=>g.accountId===le()?.id);if(!h?.personalSpacePath)throw new Error("The home membership has no mount declaration location");await Ot(h.personalSpacePath,g=>{let v=i.find(x=>x.accountId===g);return v?Ne(v):null}),await ur(y),r(null),Mt(f.accountId)},[i]),p=(0,_.useCallback)(async m=>{let f=i.find(y=>y.path===m);if(!f)throw new Error("Scope membership is unavailable");await oi(Ne(f))},[i]);return{accounts:c,allMemberships:i,currentAccount:l,mountedScope:null,switchAccount:d,mountScope:p,loading:s.isLoading,error:s.error??n}}function $a(){G();let e=(0,_.useSyncExternalStore)(Ar,Xn,Xn),t=(0,_.useMemo)(()=>De(),[e]),n=Se(),r=(0,_.useMemo)(()=>t.filter(i=>i.kind==="space"&&(n?.kind==="account"||i.id===n?.id)),[t,n]),s=(0,_.useMemo)(()=>r.map(i=>i.id).sort(),[r]);return{mounts:t,selectedSpaces:r,readSpaceIds:s,homeAnchor:le(),anchor:n,setAnchor:ur,replaceMounts:rs,mount:oi,unmount:xa}}function is(){let[e,t]=(0,_.useState)(null),[n,r]=(0,_.useState)(null),[s,i]=(0,_.useState)(!0),o=(0,_.useRef)(null);(0,_.useEffect)(()=>{L.auth.getSession().then(({data:f,error:y})=>{if(y){console.warn("[useAuth] getSession error, clearing stale session:",y.message),L.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(f?.session??null),t(f?.session?.user??null),i(!1)}).catch(f=>{console.warn("[useAuth] getSession threw, clearing stale session:",f?.message),L.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:m}}=L.auth.onAuthStateChange((f,y)=>{if(f==="TOKEN_REFRESHED"&&!y){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),L.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(y),t(y?.user??null),i(!1)});return o.current=m,()=>{m?.unsubscribe()}},[]);let c=(0,_.useCallback)(async m=>m.provider?L.auth.signInWithOAuth({provider:m.provider,options:m.redirectTo?{redirectTo:m.redirectTo}:{redirectTo:window.location.href}}):L.auth.signInWithPassword({email:m.email,password:m.password}),[]),a=(0,_.useCallback)(async m=>L.auth.signUp({email:m.email,password:m.password,options:{data:m.metadata||{}}}),[]),l=(0,_.useCallback)(async()=>{await L.auth.signOut(),un(),C().clear()},[]),d=(0,_.useCallback)(async m=>{let{error:f}=await L.auth.resetPasswordForEmail(m);if(f)throw f},[]),p=(0,_.useCallback)(async(m,f)=>{let{error:y}=await L.auth.signInWithOtp({email:m,options:f?{emailRedirectTo:f}:{emailRedirectTo:window.location.href}});if(y)throw y},[]);return{user:e,session:n,loading:s,signIn:c,signUp:a,signOut:l,resetPassword:d,signInWithMagicLink:p}}function Ga(e){let[t,n]=(0,_.useState)(null),[r,s]=(0,_.useState)(!1),[i,o]=(0,_.useState)(null);return(0,_.useEffect)(()=>{if(!e){n(null),s(!1);return}if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e))s(!0),R("resolve-asset",{asset_id:e}).then(a=>{a.success&&a.public_url?n({url:a.public_url,id:a.asset_id,name:a.name,mimeType:a.mime_type,width:a.width,height:a.height,sizeBytes:a.size_bytes}):o(new Error(a.error||"Asset not found")),s(!1)}).catch(a=>{o(a instanceof Error?a:new Error(String(a))),s(!1)});else{let l=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";n({url:l+e}),s(!1)}},[e]),{data:t,loading:r,error:i}}var lr={},Ca={};ne(()=>{for(let e of Object.keys(lr))delete lr[e]});var za=null;function Ja(e){za=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function ol(e){switch(e){case"react":return typeof window<"u"&&window.React||_.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||rl;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}:sl;case"@fsaos/gateway":case"@fsaos/react":return typeof window<"u"&&window.__FSAOS_GATEWAY__||za||{};case"@fsaos/ui":return typeof window<"u"&&window.__FSAOS_UI__||{};case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}function al(e,t){return e.replace(/^(\s*)(:root|body)(\s*[{,])/gm,(n,r,s,i)=>`${r}.${t}${i}`)}async function cl(e,t){if(!Ca[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=al(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),Ca[e]=s}catch{}}function ul(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)(ol),o=t??i;return o?o.default||o:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function ui(e){let[t,n]=(0,_.useState)(null),[r,s]=(0,_.useState)(!0),[i,o]=(0,_.useState)(null);return(0,_.useEffect)(()=>{if(!e)return;let c=!1;s(!0),o(null);let l=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{try{let d=1,p=e+"@v1",m=l+e+"/__bundle.js";try{let v=await fetch(l+e+"/__meta",{cache:"no-store"});v.ok&&(d=(await v.json()).version||1,p=e+"@v"+d,m=l+e+"/__bundle.v"+d+".js")}catch{m=l+e+"/__bundle.js?v="+Date.now()}if(c)return;if(lr[p]){n(()=>lr[p]),s(!1);return}let f=await fetch(m);if(!f.ok)throw new Error(`Failed to fetch bundle: ${f.status} ${f.statusText} (${m})`);let y=await f.text();if(c)return;let h=m.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");cl(h).catch(()=>{});let g=ul(y);if(!g)throw new Error("Bundle did not export a component. Expected window.__FSAOS_COMPONENT__ (FSAOS build) or a __FSAOS_REGISTER__(Component) call.");if(typeof g!="function")throw new Error(`Bundle export is not a React component (got ${typeof g})`);lr[p]=g,c||(n(()=>g),s(!1))}catch(d){c||(o(d instanceof Error?d:new Error(String(d))),s(!1))}})(),()=>{c=!0}},[e]),{Component:t,loading:r,error:i}}var ll=["--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 Ya(){return{data:(0,_.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let t={},n=getComputedStyle(document.documentElement);return ll.forEach(r=>{t[r]=n.getPropertyValue(r).trim()}),{tokens:t}},[]),loading:!1,error:null}}function Xa(e,t){return{data:{allowed:!0},loading:!1,error:null}}function Za(e,t){let n={};return(t||[]).forEach(r=>{n[r]=!0}),{data:n,loading:!1,error:null}}var ae=null,Rn=null,ai=new Set;function dl(){ai.forEach(e=>e())}ne(()=>{ae=null,Rn=null});async function ec(e){let t={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null},n=Et()?.principal_id??null;if(n){if(ae&&ae.principalId===n){let{principalId:s,displayName:i,createdAt:o,metadata:c,vfsPath:a}=ae;return{principalId:s,displayName:i,createdAt:o,metadata:c,vfsPath:a}}return{...t,principalId:n}}let r=e;if(!r){let{data:s}=await L.auth.getSession();r=s?.session?.user?.id}if(!r)return t;if(ae&&ae.authUserId===r){let{principalId:s,displayName:i,createdAt:o,metadata:c,vfsPath:a}=ae;return{principalId:s,displayName:i,createdAt:o,metadata:c,vfsPath:a}}return Rn||(Rn=(async()=>{try{let{data:s,error:i}=await L.from("os_principals").select("id, display_name, created_at, metadata").eq("auth_user_id",r).eq("principal_type","user").maybeSingle();if(i)return console.warn("[SDK] Could not resolve principal:",i.message),t;let o=s?.id??null,c=null;if(o){let{data:l}=await L.from("os_items").select("path").eq("owner_principal_id",o).eq("item_type","principal").eq("is_active",!0).like("path","/root/principals/%"),d=(l??[]).map(p=>p.path);c=d.find(p=>p.split("/").length===4)??d[0]??null}let a={principalId:o,displayName:s?.display_name??null,createdAt:s?.created_at??null,metadata:s?.metadata??null,vfsPath:c};return ae={authUserId:r,...a},a}finally{Rn=null}})(),Rn)}async function tc(e){return(await ec(e)).principalId}function nc(){let e=is(),t=e.user,n=ae?.authUserId===t?.id?ae:null,[r,s]=(0,_.useState)(n),i=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let o=()=>{let c=ae;c&&c.authUserId===t?.id&&s({principalId:c.principalId,displayName:c.displayName,createdAt:c.createdAt,metadata:c.metadata,vfsPath:c.vfsPath})};return ai.add(o),()=>{ai.delete(o)}},[t?.id]),(0,_.useEffect)(()=>{if(!t?.id){s(null),i.current=null;return}i.current===t.id&&r?.principalId!=null||(i.current=t.id,ec(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 rc(){return{data:null,loading:!1,error:null}}function sc(e){let{path:t,...n}=e,r=ui(t),s=r.Component,{loading:i,error:o}=r;return i?(0,_.createElement)("div",{className:"fsaos-loading"},""):o?(0,_.createElement)("div",{className:"fsaos-error"},"Failed to load component"):s?(0,_.createElement)(s,n):null}function ic(e){return e.children}function oc(e){let t=G(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=e,o=i!==void 0?i&&!!n:!!n,c=(0,_.useMemo)(()=>S.channelMessages(n??"",r),[n,r,t]),a=j(),l=(0,_.useRef)(null),d=K({queryKey:c,queryFn:()=>Xr(n,r),enabled:o});(0,_.useEffect)(()=>{if(!s||!o)return;let h=ie("vfs_change",()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{Ge(a,c,{exact:!0})},500)},g=>(g.item_type==="message"||g.item_type==="card")&&dt(g.path,n));return()=>{h(),l.current&&clearTimeout(l.current)}},[s,o,n,c,a]);let p=d.data,m=p?.messages??[],f=p?.messageCards??new Map,y=p?.siblingCards??[];return{messages:m,messageCards:f,siblingCards:y,threads:(0,_.useMemo)(()=>m.filter(h=>h.reply_count>0),[m]),isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,refetch:d.refetch}}function ac(e){G();let{channelPath:t,parentMessageId:n,limit:r=50,realtime:s=!0,enabled:i=!0}=e,o=!!n,c=i&&!!t,a=Hn({queryKey:[...S.channelMessages(t||"",n),"infinite",r],queryFn:async({pageParam:h})=>ir(t,{parentMessageId:n,limit:r,before_seq:o?void 0:h,after_seq:o?h:void 0}),initialPageParam:void 0,getNextPageParam:h=>!o||h.messages.length<r?void 0:h.messages[h.messages.length-1]?.seq,getPreviousPageParam:h=>o||h.messages.length<r?void 0:h.messages[0]?.seq,enabled:c}),l=(0,_.useMemo)(()=>{if(!a.data?.pages)return[];let h=new Set,g=[];for(let v of a.data.pages)for(let x of v.messages)h.has(x.id)||(h.add(x.id),g.push(x));return g.sort((v,x)=>v.seq-x.seq)},[a.data?.pages]),{messageCards:d,siblingCards:p}=(0,_.useMemo)(()=>{let h=new Map,g=[];if(!a.data?.pages)return{messageCards:h,siblingCards:g};let v=new Set;for(let x of a.data.pages){for(let[O,X]of x.messageCards)for(let P of X){if(v.has(P.id))continue;v.add(P.id);let F=h.get(O)||[];F.push(P),h.set(O,F)}for(let O of x.siblingCards)v.has(O.id)||(v.add(O.id),g.push(O))}return{messageCards:h,siblingCards:g}},[a.data?.pages]),m=j(),f=(0,_.useRef)(null),y=(0,_.useMemo)(()=>[...S.channelMessages(t||"",n),"infinite",r],[t,n,r]);return(0,_.useEffect)(()=>{if(!s||!t||!c)return;let h=()=>void Ge(m,y,{exact:!0}),g=!1,v=!1,x=!1,O=async()=>{let F=m.getQueryData(y);if(!F?.pages?.length){h();return}let W=0;for(let N of F.pages)for(let M of N.messages)M.seq>W&&(W=M.seq);if(W===0){h();return}try{let N=await ir(t,{parentMessageId:n,limit:r,after_seq:W});if(N.messages.length===0&&N.siblingCards.length===0){h();return}if(N.messages.length>0){let M=Math.min(...N.messages.map(B=>B.seq));if(M>W+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${W}, minNewSeq=${M}. Triggering full refetch.`),h();return}}m.setQueryData(y,M=>{if(!M)return M;let B=[...M.pages],A=B.length-1,I=B[A],Q=new Set(I.messages.map(_e=>_e.id)),D=N.messages.filter(_e=>!Q.has(_e.id)),Ae=[...I.messages,...D].sort((_e,ps)=>_e.seq-ps.seq),z=new Map(I.messageCards);for(let[_e,ps]of N.messageCards){let bi=z.get(_e)||[],lu=new Set(bi.map(ms=>ms.id)),du=ps.filter(ms=>!lu.has(ms.id));z.set(_e,[...bi,...du])}let ht=new Set(I.siblingCards.map(_e=>_e.id)),cu=N.siblingCards.filter(_e=>!ht.has(_e.id)),uu=[...I.siblingCards,...cu];return B[A]={...I,messages:Ae,messageCards:z,siblingCards:uu},{...M,pages:B}})}catch(N){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",N),h()}},X=async()=>{if(g){v=!0;return}g=!0;try{do v=!1,await O();while(v&&!x)}finally{g=!1}},P=ie("vfs_change",()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{X()},500)},F=>(F.item_type==="message"||F.item_type==="card")&&dt(F.path,t));return()=>{x=!0,P(),f.current&&clearTimeout(f.current)}},[s,t,c,y,m,n,r]),{messages:l,messageCards:d,siblingCards:p,threads:l.filter(h=>h.reply_count>0),isLoading:a.isLoading,isFetching:a.isFetching,error:a.error,refetch:a.refetch,hasPreviousPage:a.hasPreviousPage??!1,fetchPreviousPage:a.fetchPreviousPage,isFetchingPreviousPage:a.isFetchingPreviousPage??!1,hasNextPage:a.hasNextPage??!1,fetchNextPage:a.fetchNextPage,isFetchingNextPage:a.isFetchingNextPage??!1}}function fl(e){return e==="on"||e==="auto"?"on":"off"}function pl(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:fl(t.ai_mode),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}}function os(e={}){let t=G(),{realtime:n=!0,enabled:r=!0}=e,s=j(),i=(0,_.useRef)(null),o=(0,_.useMemo)(()=>S.channels("all"),[t]),c=K({queryKey:o,queryFn:async()=>((await R("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(pl),enabled:r});return(0,_.useEffect)(()=>{if(!n||!r)return;let l=ie("vfs_change",()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{s.invalidateQueries({queryKey:o})},1e3)},p=>p.item_type==="channel"||p.item_type==="message"),d=ie("ccm_change",()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{s.invalidateQueries({queryKey:o})},1e3)},p=>p.item_type==="channel"||p.item_type==="message");return()=>{l(),d(),i.current&&clearTimeout(i.current)}},[n,r,o,s]),{channels:c.data??[],isLoading:c.isLoading,isFetching:c.isFetching,error:c.error,refetch:c.refetch}}function cc(e={}){let t=os(e),n=(0,_.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function uc(e={}){let t=os(e),n=(0,_.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function li(e={}){let t=G(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=e,o=j(),c=(0,_.useRef)(null),a=(0,_.useMemo)(()=>S.notifications(n,r),[n,r,t]),l=K({queryKey:a,queryFn:async()=>{let p={limit:r};return n==="unread"&&(p.filter="unread"),(await R("get-notifications",p)).notifications||[]},enabled:i});return(0,_.useEffect)(()=>{if(!s||!i)return;let p=["vfs_change","ccm_change"].map(m=>ie(m,()=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{o.invalidateQueries({queryKey:a})},2e3)},f=>f.item_type==="notification"||f.item_type==="message"));return()=>{p.forEach(m=>m()),c.current&&clearTimeout(c.current)}},[s,i,a,o]),{notifications:l.data??[],isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function lc(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:o,error:c,refetch:a}=li({filter:"unread",limit:200,realtime:n,enabled:r}),l=(0,_.useMemo)(()=>{let f=new Map;for(let y of s)y.is_unread&&y.channel_id&&f.set(y.channel_id,(f.get(y.channel_id)||0)+1);return f},[s]),d=(0,_.useMemo)(()=>{let f=0;return l.forEach(y=>{f+=y}),f},[l]),{dmUnread:p,channelUnread:m}=(0,_.useMemo)(()=>{if(!t)return{dmUnread:0,channelUnread:0};let f=new Set(t.filter(g=>g.isDm).map(g=>g.id)),y=0,h=0;return l.forEach((g,v)=>{f.has(v)?y+=g:h+=g}),{dmUnread:y,channelUnread:h}},[t,l]);return{unreadByChannel:l,totalUnread:d,dmUnread:p,channelUnread:m,isLoading:i,isFetching:o,error:c,refetch:a}}function dc(){let e=j();return ge({mutationFn:t=>R("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:S.children(r)})}})}function fc(){let e=j();return ge({mutationFn:t=>R("update",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.invalidateQueries({queryKey:S.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:S.children(i)})}}})}function pc(){return ge({mutationFn:e=>R("update-principal",e),onSuccess:(e,t)=>{if(!ae)return;let n=e&&typeof e=="object"&&e.metadata?e.metadata:{...ae.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}:{}};ae={...ae,displayName:typeof t.display_name=="string"?t.display_name:ae.displayName,metadata:n},dl()}})}function mc(){let e=j();return ge({mutationFn:t=>R("delete",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.removeQueries({queryKey:S.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:S.children(i)})}}})}function hc(){let e=j();return ge({mutationFn:t=>R("move",t),onSuccess:(t,n)=>{let r=n.path,s=n.new_parent_path;if(r){e.invalidateQueries({queryKey:S.item(r)});let i=r.split("/");i.pop();let o=i.join("/");o&&e.invalidateQueries({queryKey:S.children(o)})}s&&e.invalidateQueries({queryKey:S.children(s)})}})}function gc(){let e=j();return ge({mutationFn:t=>R("link",t),onSuccess:(t,n)=>{let r=n.source_id,s=n.target_id;r&&e.invalidateQueries({queryKey:S.edges(r)}),s&&e.invalidateQueries({queryKey:S.edges(s)})}})}function yc(e,t){let n=j(),{optimistic:r,...s}=t??{};return ge({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,c=>r.update(c,i)),{previous:o}}:void 0,onError:(i,o,c)=>{r&&c?.previous!==void 0&&n.setQueryData(r.queryKey,c.previous),s.onError?.(i)},onSuccess:s.onSuccess,onSettled:r?()=>{n.invalidateQueries({queryKey:r.queryKey})}:void 0})}function _c(e,t,n){let r,s,i,o=!0;if(typeof e=="string")r=e,s=t,i=n;else{s=e;let l=t;r=l.eventType,i=l.filter,o=l.enabled??!0}let c=(0,_.useRef)(s),a=(0,_.useRef)(i);(0,_.useEffect)(()=>{c.current=s,a.current=i},[s,i]),(0,_.useEffect)(()=>o?ie(r,d=>c.current(d),a.current?d=>a.current(d):void 0):void 0,[r,o])}function vc(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:o=500}=e,c=j(),a=(0,_.useRef)(null),l=K({queryKey:t,queryFn:n,enabled:i});return(0,_.useEffect)(()=>{if(!i)return;let d=ie(r,()=>{a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{c.invalidateQueries({queryKey:t})},o)},s);return()=>{d(),a.current&&clearTimeout(a.current)}},[r,i,o,c,JSON.stringify(t)]),l}function xn(e){G();let t=re(),n=(0,_.useMemo)(()=>e?typeof e=="string"?{path:e}:e:null,[typeof e=="string"?e:JSON.stringify(e)]),r=!!t&&!!n&&!!(n.key||n.path||n.item_id),s=n?.key??n?.path??n?.item_id??"",i=["vfs",t??"__unscoped__","arrangement",s,n?.scope_id??""],o=K({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}),c=o.data??null,a=(0,_.useMemo)(()=>c?.resolved_children??[],[c]),l=c?.resolution_level??null,d=(0,_.useMemo)(()=>{let f=(c?.type_data??null)?.order;return Array.isArray(f)?f:null},[c]),p=(0,_.useCallback)(m=>{if(!d||!m?.length)return m??[];let f=v=>v.id??v.name??"",y=new Map(d.map((v,x)=>[v,x])),h=[],g=[];for(let v of m)(y.has(f(v))?h:g).push(v);return h.sort((v,x)=>y.get(f(v))-y.get(f(x))),[...h,...g]},[d]);return{...o,arrangement:c,resolvedChildren:a,resolutionLevel:l,order:d,sourceScopeId:c?.scope_item_id??null,arrangementQueryKey:i,applyTo:p}}function bc(e){let{origin:t,originField:n,fallbackUrl:r,mintError:s,scopeId:i,scopePath:o}=e,c=G(),a=Et(),l=i??a?.scope_id??null,d=(0,_.useMemo)(()=>{if(!t)return null;let P="/accounts/",F=t.indexOf(P);if(F===-1)return null;let W=t.indexOf("/",F+P.length);return W===-1?t:t.slice(0,W)},[t]),p=o??d??a?.scope_path??null,m=n?.trim()||null,f=`${c}
4
4
  ${l??""}
5
+ ${p??""}
5
6
  ${m??""}
6
- ${f??""}
7
- ${t??""}`,[y,g]=(0,_.useState)(null),h=(0,_.useRef)({key:p,found:null,earlyContentPaths:new Set}),v=y?.key===p?y:null;(0,_.useLayoutEffect)(()=>{h.current={key:p,found:v,earlyContentPaths:new Set}},[p]);let P=K({queryKey:["vfs",m??"__unscoped__","minted-asset",f??"",t??""],queryFn:async()=>{let C=await R("query",{scope_path:m,filters:{[`field.${f}`]:t},limit:1}),F=C.content?.items??C.items??[],B=F[0]?we(F[0]):null;if(!B)return null;let O=(await Vn(B.path)).some($=>$.item_type==="file"&&!!$.type_data?.file_ref);return{asset:B,hasBytes:O}},enabled:!!(t&&m&&f&&!s),refetchInterval:C=>h.current.key===p&&h.current.found?.hasBytes||C.state.data?.hasBytes?!1:1500});(0,_.useEffect)(()=>{let C=P.data;if(!C||h.current.key!==p)return;let F=h.current.found,B={key:p,itemId:C.asset.id,itemPath:C.asset.path,displayName:typeof C.asset.type_data?.display_name=="string"?C.asset.type_data.display_name:C.asset.name,hasBytes:C.hasBytes||!!(F?.itemId===C.asset.id&&F.hasBytes)};h.current.found=B,g(B)},[P.data,p]);let M=!!(t&&l)&&!s&&!v?.hasBytes;return(0,_.useEffect)(()=>{if(!(!M||!l))return rn(l,["asset.materialized","content.written"])},[M,l]),(0,_.useEffect)(()=>{if(!M||!t||!l)return;let C=p,F=A=>A?.payload??A,B=A=>{let Q=F(A)?.scope_id??A?.scope_id;return typeof Q=="string"?Q:void 0},N=A=>{let Q=F(A)?.item_path??A?.item_path;return typeof Q=="string"&&Q?Q:void 0},O=(A,I)=>{let Q=I.replace(/\/+$/,"");return A===Q||A.startsWith(`${Q}/`)},$=[re("asset.materialized",A=>{if(h.current.key!==C)return;let I=F(A);if(typeof I?.item_id!="string"||!I.item_id)return;let Q=h.current.found,D=typeof I.item_path=="string"?I.item_path:void 0,Te=!!I.has_bytes||!!(D&&Array.from(h.current.earlyContentPaths).some(lt=>O(lt,D)))||!!(Q&&Q.itemId===I.item_id&&Q.hasBytes),z={key:C,itemId:I.item_id,itemPath:D,displayName:typeof I.display_name=="string"?I.display_name:void 0,hasBytes:Te};h.current.found=z,g(z)},A=>{let I=B(A);return(!I||I===l)&&F(A)?.origin===t}),re("content.written",A=>{if(h.current.key!==C)return;let I=N(A);if(!I)return;let Q=h.current.found;if(!Q?.itemPath||!O(I,Q.itemPath)){if(h.current.earlyContentPaths.add(I),h.current.earlyContentPaths.size>128){let Te=h.current.earlyContentPaths.values().next().value;Te&&h.current.earlyContentPaths.delete(Te)}return}if(Q.hasBytes)return;let D={...Q,hasBytes:!0};h.current.found=D,g(D)},A=>{let I=B(A);return(!I||I===l)&&!!N(A)})];return()=>$.forEach(A=>A())},[M,t,l,p]),{state:s?"failed":t?v?v.hasBytes?"ready":"materializing":"pending":"idle",itemId:v?.itemId,itemPath:v?.itemPath,displayName:v?.displayName,fallbackUrl:r??void 0,error:s??void 0}}function sc(e,t){let n=(0,ln.useSyncExternalStore)(Ce,ne,ne),r=Pe(),s=te(),i=r?.kind==="space",o=un(i&&s?{key:e,scope_id:r.id}:null),a=(0,ln.useMemo)(()=>{let p=o.applyTo([...t]);if(e!=="channel-order")return p;let y=new Set(o.order??[]),g=p.filter(v=>!y.has(v.id)),h=v=>Date.parse(v.createdAt??"")||0;return g.sort((v,P)=>h(P)-h(v)),[...g,...p.filter(v=>y.has(v.id))]},[e,t,o.applyTo,o.order]),c=j(),l=(0,ln.useRef)(!1),d=!!(i&&!o.error&&o.arrangement?.item_id&&o.resolutionLevel==="member"&&o.arrangement.write_target_id===o.arrangement.item_id),m=pe({mutationFn:async p=>{let y=await R("update",{_scope_path:p.scopePath,id:p.arrangementId,type_data:{order:p.ids}});if(y?.success===!1)throw new Error(y.error||"Order could not be saved");return y},onSettled:(p,y,g)=>Jt(c,g.queryKey)});async function f(p){if(!d||!s||n!==ne()||te()!==s)throw new Error("Personal order is not available in this Space");if(l.current)throw new Error("An order change is already being saved");let y=t.map(C=>C.id);if(p.length!==y.length||new Set(p).size!==y.length||y.some(C=>!p.includes(C)))throw new Error("Order must include each displayed item exactly once");let g=c.getQueryData(o.arrangementQueryKey);if(g?.item_id!==o.arrangement.item_id||JSON.stringify(g?.type_data?.order??[])!==JSON.stringify(o.order??[]))throw new Error("The saved order changed. Try dragging again");let h=a.map(C=>C.id);if(p.every((C,F)=>h[F]===C))return;let v=new Set(y),P=0,X=[...(o.order??[]).map(C=>v.has(C)?p[P++]:C),...p.slice(P)];l.current=!0;try{return await m.mutateAsync({ids:X,scopePath:s,arrangementId:o.arrangement.item_id,queryKey:o.arrangementQueryKey})}finally{l.current=!1}}return{items:a,ready:d,supported:i,contextKey:`${n}:${s}:${e}`,isLoading:i&&o.isLoading,error:o.error,refetch:o.refetch,isSaving:m.isPending,saveError:m.error,reorder:f}}var Gs=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Yu=/^[A-Za-z_:][A-Za-z0-9_:.-]{0,127}$/,ic=new Map,oc=new Map,dn=class extends Error{constructor(n,r,s,i){super(n);Y(this,"code");Y(this,"status");Y(this,"eventId");this.name="InteractionTrackingError",this.code=r,this.status=s,this.eventId=i}};function fn(e){let t=e?Mn.find(n=>n.id===e):Mn.find(n=>n.default===!0)??(Mn.length===1?Mn[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 Vr(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 Xu(e){return e.length>0&&e.length<=128&&!/[\u0000-\u001f\u007f]/.test(e)}function Zu(e,t){if(!Xu(t)||!e.observations?.includes(t))throw new TypeError("The observation is not declared by this release source")}function zs(e){if(!(typeof window>"u"||e.storage==="memory"))try{return e.storage==="session"?window.sessionStorage:window.localStorage}catch{return}}function el(e){try{let t=zs(e)?.getItem(e.key)??void 0;return t&&Gs.test(t)?t:void 0}catch{return}}function ac(e,t){try{zs(e)?.setItem(e.key,t)}catch{}}function cc(e){let t=e.identity?.visitor;if(!t?.key)throw new TypeError("The source visitor identity policy is invalid");let n=el(t)??ic.get(e.id);if(n)return n;let r=crypto.randomUUID();return ic.set(e.id,r),ac(t,r),r}function uc(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 l=zs(n)?.getItem(n.key);r=l?JSON.parse(l):void 0}catch{r=void 0}let s=oc.get(e.id),i=r&&typeof r.id=="string"&&Gs.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 oc.set(e.id,c),ac(n,JSON.stringify(c)),c.id}function tl(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 Pt(e,t={},n={}){let r=fn(n.source);if(Zu(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??cc(r),o=n.sessionId??uc(r);if(![s,i,o].every(h=>Gs.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 l=n.referrer??(typeof document<"u"&&document.referrer||void 0),d=tl(r,a),m=d?{...t,source_keys:d}:t,f=St(),p=`${_e.replace(/\/+$/,"")}/d/${encodeURIComponent(f)}/interactions`,y;try{y=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:l,events:[{id:s,event_type:e,occurred_at:c,properties:m}]}),signal:n.signal,credentials:"omit",keepalive:n.keepalive??!1})}catch(h){throw new dn(h instanceof Error?h.message:"Observation transport network error","OBSERVATION_NETWORK_ERROR",0,s)}let g=null;try{g=await y.json()}catch{}if(!y.ok||g?.success!==!0){let h=g;throw new dn(h?.message||h?.error||`Observation transport failed (${y.status})`,h?.error||"OBSERVATION_TRANSPORT_FAILED",y.status,s)}return g}function lc(e={},t={}){let n=fn(t.source),r=Vr("page_view",n),s=typeof document>"u"||!r.title_property?{}:{[r.title_property]:document.title.slice(0,512)};return Pt(r.observation,{...s,...e},{...t,source:n.id})}function dc(e,t={},n={}){if(!e||e.length>128)throw new TypeError("actionId is invalid");let r=fn(n.source),s=Vr("declared_action",r),i=s.id_property?{[s.id_property]:e}:{};return Pt(s.observation,{...t,...i},{...n,source:r.id})}function fc(){try{let e=fn();return Vr("form_receipt",e),{visitor_id:cc(e),session_id:uc(e),source:e.id}}catch{return}}function pc(e,t={}){let n=fn(t.source),r=Vr("form_receipt",n);return Pt(r.observation,e,{...t,source:n.id})}var Zn;function Hr(e={}){if(typeof window>"u"||typeof document>"u")return()=>{};if(Zn)return Zn;if(window.__FSAOS_CONFIG__?.tracking?.enabled===!1)return()=>{};let t;try{t=fn(e.source)}catch{return()=>{}}let n=e.pageViews===!1?[]:t.adapters.filter(f=>f.type==="page_view"),r=e.declaredActions===!1?[]:t.adapters.filter(f=>f.type==="declared_action"),s="",i=()=>{if(window.location.href!==s){s=window.location.href;for(let f of n){let p=f.title_property?{[f.title_property]:document.title.slice(0,512)}:{};Pt(f.observation,p,{source:t.id,keepalive:!0}).catch(()=>{})}}},o=f=>{if(f.target instanceof Element)for(let p of r){let y=p.attribute;if(!y||!Yu.test(y))continue;let g=f.target.closest(`[${y}]`);if(!g)continue;let h=g.getAttribute(y)?.trim();if(!h||h.length>128)continue;let v={};p.id_property&&(v[p.id_property]=h),p.element_property&&(v[p.element_property]=g.tagName.toLowerCase()),Pt(p.observation,v,{source:t.id,keepalive:!0}).catch(()=>{})}},a=window.history.pushState,c=window.history.replaceState,l=()=>queueMicrotask(i),d=n.some(f=>f.history===!0),m=n.some(f=>f.pageshow===!0);return d&&(window.history.pushState=function(...p){a.apply(this,p),l()},window.history.replaceState=function(...p){c.apply(this,p),l()},window.addEventListener("popstate",i)),m&&window.addEventListener("pageshow",i),r.length>0&&document.addEventListener("click",o,{capture:!0}),n.length>0&&queueMicrotask(i),Zn=()=>{window.removeEventListener("popstate",i),window.removeEventListener("pageshow",i),document.removeEventListener("click",o,{capture:!0}),d&&(window.history.pushState=a,window.history.replaceState=c),Zn=void 0},Zn}var pn;function mc(e={}){return pn||(pn=(async()=>{let t=e.tracking??!0,n=t===!1?()=>{}:Hr(typeof t=="object"?t:{});try{let r=e.session===!1?null:await Gt(),s=!1;return{session:r,dispose(){s||(s=!0,n(),pn=void 0)}}}catch(r){throw n(),pn=void 0,r}})(),pn)}async function Js(e){try{return await R("execution-control-transition",e)}catch(t){if(!(t instanceof ot)||t.status<500)throw t;return await new Promise(n=>setTimeout(n,250)),R("execution-control-transition",e)}}function Ys(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 hc(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 Js({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 Ys(i?{...s,state:i}:s)}async function gc(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 Js({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 Ys(a?{...o,state:a}:o)}async function yc(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 Js({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 Ys(i?{...s,outcome:i}:s)}var nl=/^[a-z][a-z0-9_-]{0,63}$/,rl=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,mn=class extends Error{constructor(n,r,s,i){super(n);Y(this,"code");Y(this,"status");Y(this,"fillId");this.name="FormSubmissionError",this.code=r,this.status=s,this.fillId=i}};async function _c(e,t,n={}){if(!nl.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(!rl.test(r))throw new TypeError("fillId must be a UUID");let s=St(),i=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!i)throw new TypeError("pageUrl is required outside a browser");let o=`${_e.replace(/\/+$/,"")}/d/${encodeURIComponent(s)}/actions/${encodeURIComponent(e)}`,a=fc(),c=a?{visitor_id:a.visitor_id,session_id:a.session_id}:void 0,l;try{l=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(m){throw new mn(m instanceof Error?m.message:"Form submission network error","FORM_NETWORK_ERROR",0,r)}let d=null;try{d=await l.json()}catch{}if(!l.ok||d?.success!==!0){let m=d;throw new mn(m?.message||m?.error||`Form submission failed (${l.status})`,m?.error||"FORM_SUBMISSION_FAILED",l.status,r)}try{await pc({fill_id:r,action_id:e,release_id:d.release_id},{eventId:r,pageUrl:i,signal:n.signal,keepalive:!0,...a?{source:a.source,visitorId:a.visitor_id,sessionId:a.session_id}:{}})}catch{}return d}var Xs=J(oe(),1),wc=J(bc(),1);function Sc(e){return R("read",{path:e})}function Rc(e,t){return R("list",{path:e,...t})}function Pc(e){return R("create",e)}function Cc(e){return R("update",e)}function xc(e){return R("create",e)}function Tc(e,t){let r=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return R("tools/call",{name:e,instance_path:r,...t||{}})}function Ec(e,t,n){return R("signal",{target_id:e,event_name:t,payload:n||{}})}function Ic(e){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+e}var Ac={signIn:e=>e.provider?L.auth.signInWithOAuth({provider:e.provider,options:{redirectTo:e.redirectTo||window.location.href}}):L.auth.signInWithPassword({email:e.email,password:e.password}),signUp:e=>L.auth.signUp({email:e.email,password:e.password,options:{data:e.metadata||{}}}),signOut:async()=>{await L.auth.signOut(),zt(),T().clear()},getSession:()=>L.auth.getSession().then(e=>e.data.session),getUser:()=>L.auth.getUser().then(e=>e.data.user),onAuthStateChange:e=>{let{data:{subscription:t}}=L.auth.onAuthStateChange((n,r)=>{e({event:n,session:r,user:r?.user??null})});return()=>t?.unsubscribe()},resetPassword:e=>L.auth.resetPasswordForEmail(e),signInWithMagicLink:(e,t)=>L.auth.signInWithOtp({email:e,options:{emailRedirectTo:t||window.location.href}})};function kc(){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,wc.createRoot)(e).render((0,Xs.createElement)(In,{client:T()},(0,Xs.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 Oc(){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 sl(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function il(e,t){return t&&t.length>0?"select":e==="boolean"?"toggle":e==="integer"||e==="number"?"range":e==="string"?"text":"none"}function ol(e,t){return!(e==="object"||e==="array")}function al(e){return["string","number","integer","boolean"].includes(e)}function cl(e){return e!=="object"&&e!=="array"}function Mc(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",l=a.enum,d=ol(c,l),m=al(c),f=il(c,l);i.push({key:o,label:a.title||sl(o),type:c,description:a.description,enum_values:l,default_value:n[o]??r[o]??a.default,editable:t,filterable:d,sortable:m,filter_widget:f})}return i}function Zs(e){let t=e.default_data||{},n=e.field_defaults||{},r=Mc(e.input_schema,!0,t,n),s=Mc(e.system_schema,!1,t,n),i=[...r,...s],o=i.filter(l=>cl(l.type)),a=i.filter(l=>l.filterable),c=i.filter(l=>l.sortable);return{fields:i,columns:o,filterable:a,sortable:c,form_fields:r,system_fields:s}}function Fc(e){return{field:"updated_at",direction:"desc"}}function qc(e){let t=Zs(e),n=new Set(e.input_schema?.required||[]);return t.form_fields.filter(r=>n.has(r.key)||r.default_value===void 0)}var de=J(oe(),1);var ul=0;function ll(){return`upload_${Date.now()}_${++ul}`}async function Qc(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 l=await R("create",a);if(!l.id)throw new Error(l.error||l.message||"Failed to create file item");let d=l.id,m=l.path;if(l.storage_completed&&l.file_ref)return{itemId:d,itemPath:m,fileRef:l.file_ref};let f=l.storage_key,p=l.upload_token,y=l.storage_worker_url||"https://fsaos-storage.radns.workers.dev";if(!f)throw new Error("Gateway returned no storage_key \u2014 file_source may not be supported for this item type");await dl(y,f,p,e,i,n,r);let g=await Dc(d,f,i);return{itemId:d,itemPath:m,fileRef:g}}function dl(e,t,n,r,s,i,o){return new Promise((a,c)=>{let l=new XMLHttpRequest;if(l.open("PUT",`${e}/upload`),l.setRequestHeader("X-Storage-Key",t),l.setRequestHeader("Content-Type",s),n&&l.setRequestHeader("X-Upload-Token",n),l.upload.onprogress=d=>{d.lengthComputable&&i&&i(Math.round(d.loaded/d.total*100))},l.onload=()=>{l.status>=200&&l.status<300?a():c(new Error(`Storage upload failed: HTTP ${l.status} \u2014 ${l.responseText?.slice(0,300)}`))},l.onerror=()=>c(new Error("Storage upload network error")),l.ontimeout=()=>c(new Error("Storage upload timed out")),o){if(o.aborted){c(new Error("Upload cancelled"));return}o.addEventListener("abort",()=>{l.abort(),c(new Error("Upload cancelled"))})}l.send(r)})}async function Dc(e,t,n){let r=await je(),s=await fetch(`${_e}/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 Uc(){let[e,t]=(0,de.useState)([]),n=j(),r=(0,de.useRef)(e);r.current=e;let s=(0,de.useCallback)((g,h)=>{t(v=>v.map(P=>P.id===g?{...P,...h}:P))},[]),i=(0,de.useCallback)(g=>{t(h=>[...h,g])},[]),o=(0,de.useCallback)(async(g,h,v,P,M)=>{let X=v.name||h.name,C=h.type||"application/octet-stream",F=v.itemType||"file",B=M?.itemId||null,N=M?.itemPath||null,O=M?.storageKey||null,$=M?.uploadToken||null,A=M?.storageWorkerUrl||null;try{if(!P||P==="create"){s(g,{status:"creating",error:null,_failedAt:null});let D=await R("create",{parent_path:v.parentPath,item_type:F,name:X,type_data:{...v.typeData||{},file_source:{type:"upload",content_type:C}}});if(!D.id)throw Object.assign(new Error(D.error||D.message||"Failed to create file item"),{_step:"create"});if(B=D.id,N=D.path,s(g,{itemId:B,itemPath:N}),D.storage_completed&&D.file_ref){s(g,{status:"complete",progress:100,fileRef:D.file_ref}),n.invalidateQueries({queryKey:S.children(v.parentPath)});return}if(O=D.storage_key,$=D.upload_token||"",A=D.storage_worker_url||"https://fsaos-storage.radns.workers.dev",s(g,{_storageKey:O,_uploadToken:$,_storageWorkerUrl:A}),!O)throw Object.assign(new Error("Gateway returned no storage_key"),{_step:"create"})}(!P||P==="create"||P==="upload")&&(s(g,{status:"uploading",progress:0,error:null,_failedAt:null}),await new Promise((D,Te)=>{let z=new XMLHttpRequest;s(g,{_xhr:z}),z.open("PUT",`${A}/upload`),z.setRequestHeader("X-Storage-Key",O),z.setRequestHeader("Content-Type",C),$&&z.setRequestHeader("X-Upload-Token",$),z.upload.onprogress=lt=>{lt.lengthComputable&&s(g,{progress:Math.round(lt.loaded/lt.total*100)})},z.onload=()=>{z.status>=200&&z.status<300?D():Te(Object.assign(new Error(`Storage upload failed: HTTP ${z.status}`),{_step:"upload"}))},z.onerror=()=>Te(Object.assign(new Error("Storage upload network error"),{_step:"upload"})),z.ontimeout=()=>Te(Object.assign(new Error("Storage upload timed out"),{_step:"upload"})),z.send(h)}),s(g,{progress:100,_xhr:null})),s(g,{status:"confirming",error:null,_failedAt:null});let I=await Dc(B,O,C);s(g,{status:"complete",fileRef:I}),n.invalidateQueries({queryKey:S.children(v.parentPath)})}catch(I){let Q=I?.message||String(I),D=I?._step||"create";s(g,{status:"error",error:Q,_failedAt:D,_xhr:null})}},[s,n]),a=(0,de.useCallback)((g,h)=>{let v=ll();i({id:v,file:g,status:"creating",progress:0,error:null,itemId:null,itemPath:null,fileRef:null,options:h,_storageKey:null,_uploadToken:null,_storageWorkerUrl:null,_xhr:null,_failedAt:null}),o(v,g,h)},[i,o]),c=(0,de.useCallback)((g,h)=>{for(let v of g)a(v,h)},[a]),l=(0,de.useCallback)(g=>{let h=r.current.find(M=>M.id===g);if(!h||h.status!=="error")return;let v=h._failedAt||"create",P=h._storageKey&&h.itemId?{storageKey:h._storageKey,uploadToken:h._uploadToken||"",storageWorkerUrl:h._storageWorkerUrl||"https://fsaos-storage.radns.workers.dev",itemId:h.itemId,itemPath:h.itemPath||""}:void 0;o(g,h.file,h.options,v,P)},[o]),d=(0,de.useCallback)(g=>{let h=r.current.find(v=>v.id===g);h&&(h._xhr&&h._xhr.abort(),s(g,{status:"error",error:"Cancelled",_xhr:null,_failedAt:null}))},[s]),m=(0,de.useCallback)(g=>{t(h=>h.filter(v=>v.id!==g))},[]),f=(0,de.useCallback)(()=>{t(g=>g.filter(h=>h.status!=="complete"))},[]),p=e.some(g=>g.status==="creating"||g.status==="uploading"||g.status==="confirming"),y=e.map(({_storageKey:g,_uploadToken:h,_storageWorkerUrl:v,_xhr:P,_failedAt:M,...X})=>X);return{upload:a,uploadMultiple:c,uploads:y,retryUpload:l,cancelUpload:d,removeUpload:m,clearCompleted:f,isUploading:p}}var Nc=J(oe(),1);async function ei(e,t){return await R("resolve-items",{context_id:e,item_type:t})}function Kc(e,t){return(0,Nc.useSyncExternalStore)(Ce,ne,ne),K({queryKey:["vfs",te()??"__unscoped__","resolved-items",e??"",t],queryFn:()=>ei(e,t),enabled:!!(e&&t)})}var xe=J(oe(),1);function Wr(e,t){let n={artifacts:new Map,timeline:[]},r=new Map;function s(o){if(!o.action?.startsWith("artifact_"))return;let c,l=o.name;if(typeof l=="string"&&l.startsWith("{"))try{c=JSON.parse(l)}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 m=r.get(c.tool_id);n.timeline[m].artifact_ids.push(c.artifact_id)}else{let m=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,m)}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 m=r.get(c.tool_id);if(m!==void 0){let f=n.timeline[m];c.status==="executing"?f.status="executing":c.status==="completed"?(f.status="completed",f.completed_at=Date.now()):c.status==="failed"&&(f.status="failed",f.completed_at=Date.now()),c.target_uri&&!f.target_uri&&(f.target_uri=c.target_uri)}break}}t(n)}return xr(e,s)}function Lc(e,t=!0){let[n,r]=(0,xe.useState)(new Map),[s,i]=(0,xe.useState)([]),o=(0,xe.useRef)({artifacts:new Map,timeline:[]});(0,xe.useEffect)(()=>!e||!t?void 0:Wr(e,m=>{o.current=m,r(new Map(m.artifacts)),i([...m.timeline])}),[e,t]);let a=(0,xe.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,l=Array.from(n.values()).filter(d=>d.surface_type==="activity"&&(d.status==="streaming"||d.status==="executing"));return{artifacts:n,timeline:s,activeEditor:c,activeActivities:l,reset:a}}function jc(e,t=!0){let[n,r]=(0,xe.useState)([]);(0,xe.useEffect)(()=>!e||!t?void 0:Wr(e,o=>{r([...o.timeline])}),[e,t]);let s=n.length>0?n[n.length-1]:null;return{timeline:n,latestActivity:s}}var Gr=J(oe(),1);function fl(e,t,n,r){return["vfs","timeline-history",e,t??"__all__",n??500,r??0]}async function ti(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(pl).sort((l,d)=>l.seq-d.seq):[]}catch(o){if(o?.status===404||o?.message?.includes("not found"))return[];throw o}}function Bc(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=j(),l=(0,Gr.useRef)(null),d=a?fl(a,n,r,s):["vfs","timeline-history","__disabled__"],m=K({queryKey:d,queryFn:()=>ti(e,{turnId:n,limit:r,offset:s}),enabled:!!e&&i});return(0,Gr.useEffect)(()=>{if(!a||!i)return;let f=re("vfs_change",()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{c.invalidateQueries({queryKey:d})},o)},p=>{let y=p?.path;return y?y===a||y.startsWith(a+"/"):!1});return()=>{f(),l.current&&clearTimeout(l.current)}},[a,i,o,c,JSON.stringify(d)]),{events:m.data??[],isLoading:m.isLoading,error:m.error,isFetching:m.isFetching,refetch:()=>{m.refetch()}}}function pl(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 zr=J(oe(),1);function $c(){(0,zr.useSyncExternalStore)(Ce,ne,ne);let e=te(),t=Pe(),n=un(e?{key:"pinned",...t?{scope_id:t.id}:{}}:null),r=j(),s=n.resolvedChildren,i=!!(!n.error&&n.arrangement?.item_id&&n.resolutionLevel==="member"&&n.arrangement.write_target_id===n.arrangement.item_id),o=pe({mutationFn:async c=>{let l,d={_scope_path:c.scopePath};if(c.operation==="pin"?l=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"?l=await R("delete",{...d,id:c.entry.id}):l=await R("update",{...d,id:c.arrangementId,type_data:{order:c.ids}}),l?.success===!1)throw new Error(l.error||"Pins could not be saved");return l},onSettled:(c,l,d)=>Jt(r,d.queryKey)}),a=(0,zr.useCallback)(c=>!i||!e||te()!==e?Promise.reject(new Error("Personal pins are not available in this context")):c.operation==="unpin"&&!s.some(l=>l.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(l=>!c.ids.includes(l.id)))?Promise.reject(new Error("Order must include each pin exactly once")):c.operation==="pin"&&s.some(l=>l.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(l=>l.symlink_type_data?.target_item_id===c),pin:c=>a({operation:"pin",target:c}),unpin:c=>{let l=s.find(d=>d.symlink_type_data?.target_item_id===c||d.id===c);return l?a({operation:"unpin",entry:l}):Promise.resolve(null)},reorder:c=>a({operation:"reorder",ids:c})}}Ma(ni);return nu(ni);})();
7
+ ${t??""}`,[y,h]=(0,_.useState)(null),g=(0,_.useRef)({key:f,found:null,earlyContentPaths:new Set}),v=y?.key===f?y:null;(0,_.useLayoutEffect)(()=>{g.current={key:f,found:v,earlyContentPaths:new Set}},[f]);let x=K({queryKey:["vfs",p??"__unscoped__","minted-asset",m??"",t??""],queryFn:async()=>{let P=await R("query",{scope_path:p,filters:{[`field.${m}`]:t},limit:1}),F=P.content?.items??P.items??[],W=F[0]?Pe(F[0]):null;if(!W)return null;let M=(await rr(W.path)).some(B=>B.item_type==="file"&&!!B.type_data?.file_ref);return{asset:W,hasBytes:M}},enabled:!!(t&&p&&m&&!s),refetchInterval:P=>g.current.key===f&&g.current.found?.hasBytes||P.state.data?.hasBytes?!1:1500});(0,_.useEffect)(()=>{let P=x.data;if(!P||g.current.key!==f)return;let F=g.current.found,W={key:f,itemId:P.asset.id,itemPath:P.asset.path,displayName:typeof P.asset.type_data?.display_name=="string"?P.asset.type_data.display_name:P.asset.name,hasBytes:P.hasBytes||!!(F?.itemId===P.asset.id&&F.hasBytes)};g.current.found=W,h(W)},[x.data,f]);let O=!!(t&&l)&&!s&&!v?.hasBytes;return(0,_.useEffect)(()=>{if(!(!O||!l))return yn(l,["asset.materialized","content.written"])},[O,l]),(0,_.useEffect)(()=>{if(!O||!t||!l)return;let P=f,F=A=>A?.payload??A,W=A=>{let Q=F(A)?.scope_id??A?.scope_id;return typeof Q=="string"?Q:void 0},N=A=>{let Q=F(A)?.item_path??A?.item_path;return typeof Q=="string"&&Q?Q:void 0},M=(A,I)=>{let Q=I.replace(/\/+$/,"");return A===Q||A.startsWith(`${Q}/`)},B=[ie("asset.materialized",A=>{if(g.current.key!==P)return;let I=F(A);if(typeof I?.item_id!="string"||!I.item_id)return;let Q=g.current.found,D=typeof I.item_path=="string"?I.item_path:void 0,Ae=!!I.has_bytes||!!(D&&Array.from(g.current.earlyContentPaths).some(ht=>M(ht,D)))||!!(Q&&Q.itemId===I.item_id&&Q.hasBytes),z={key:P,itemId:I.item_id,itemPath:D,displayName:typeof I.display_name=="string"?I.display_name:void 0,hasBytes:Ae};g.current.found=z,h(z)},A=>{let I=W(A);return(!I||I===l)&&F(A)?.origin===t}),ie("content.written",A=>{if(g.current.key!==P)return;let I=N(A);if(!I)return;let Q=g.current.found;if(!Q?.itemPath||!M(I,Q.itemPath)){if(g.current.earlyContentPaths.add(I),g.current.earlyContentPaths.size>128){let Ae=g.current.earlyContentPaths.values().next().value;Ae&&g.current.earlyContentPaths.delete(Ae)}return}if(Q.hasBytes)return;let D={...Q,hasBytes:!0};g.current.found=D,h(D)},A=>{let I=W(A);return(!I||I===l)&&!!N(A)})];return()=>B.forEach(A=>A())},[O,t,l,f]),{state:s?"failed":t?v?v.hasBytes?"ready":"materializing":"pending":"idle",itemId:v?.itemId,itemPath:v?.itemPath,displayName:v?.displayName,fallbackUrl:r??void 0,error:s??void 0}}function wc(e,t){let n=(0,Pn.useSyncExternalStore)(Ee,se,se),r=Se(),s=re(),i=r?.kind==="space",o=xn(i&&s?{key:e,scope_id:r.id}:null),c=(0,Pn.useMemo)(()=>{let f=o.applyTo([...t]);if(e!=="channel-order")return f;let y=new Set(o.order??[]),h=f.filter(v=>!y.has(v.id)),g=v=>Date.parse(v.createdAt??"")||0;return h.sort((v,x)=>g(x)-g(v)),[...h,...f.filter(v=>y.has(v.id))]},[e,t,o.applyTo,o.order]),a=j(),l=(0,Pn.useRef)(!1),d=!!(i&&!o.error&&o.arrangement?.item_id&&o.resolutionLevel==="member"&&o.arrangement.write_target_id===o.arrangement.item_id),p=ge({mutationFn:async f=>{let y=await R("update",{_scope_path:f.scopePath,id:f.arrangementId,type_data:{order:f.ids}});if(y?.success===!1)throw new Error(y.error||"Order could not be saved");return y},onSettled:(f,y,h)=>ln(a,h.queryKey)});async function m(f){if(!d||!s||n!==se()||re()!==s)throw new Error("Personal order is not available in this Space");if(l.current)throw new Error("An order change is already being saved");let y=t.map(P=>P.id);if(f.length!==y.length||new Set(f).size!==y.length||y.some(P=>!f.includes(P)))throw new Error("Order must include each displayed item exactly once");let h=a.getQueryData(o.arrangementQueryKey);if(h?.item_id!==o.arrangement.item_id||JSON.stringify(h?.type_data?.order??[])!==JSON.stringify(o.order??[]))throw new Error("The saved order changed. Try dragging again");let g=c.map(P=>P.id);if(f.every((P,F)=>g[F]===P))return;let v=new Set(y),x=0,X=[...(o.order??[]).map(P=>v.has(P)?f[x++]:P),...f.slice(x)];l.current=!0;try{return await p.mutateAsync({ids:X,scopePath:s,arrangementId:o.arrangement.item_id,queryKey:o.arrangementQueryKey})}finally{l.current=!1}}return{items:c,ready:d,supported:i,contextKey:`${n}:${s}:${e}`,isLoading:i&&o.isLoading,error:o.error,refetch:o.refetch,isSaving:p.isPending,saveError:p.error,reorder:m}}var di=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,ml=/^[A-Za-z_:][A-Za-z0-9_:.-]{0,127}$/,Sc=new Map,Rc=new Map,Cn=class extends Error{constructor(n,r,s,i){super(n);Y(this,"code");Y(this,"status");Y(this,"eventId");this.name="InteractionTrackingError",this.code=r,this.status=s,this.eventId=i}};function Tn(e){let t=e?Gn.find(n=>n.id===e):Gn.find(n=>n.default===!0)??(Gn.length===1?Gn[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 as(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 hl(e){return e.length>0&&e.length<=128&&!/[\u0000-\u001f\u007f]/.test(e)}function gl(e,t){if(!hl(t)||!e.observations?.includes(t))throw new TypeError("The observation is not declared by this release source")}function fi(e){if(!(typeof window>"u"||e.storage==="memory"))try{return e.storage==="session"?window.sessionStorage:window.localStorage}catch{return}}function yl(e){try{let t=fi(e)?.getItem(e.key)??void 0;return t&&di.test(t)?t:void 0}catch{return}}function xc(e,t){try{fi(e)?.setItem(e.key,t)}catch{}}function Pc(e){let t=e.identity?.visitor;if(!t?.key)throw new TypeError("The source visitor identity policy is invalid");let n=yl(t)??Sc.get(e.id);if(n)return n;let r=crypto.randomUUID();return Sc.set(e.id,r),xc(t,r),r}function Cc(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 l=fi(n)?.getItem(n.key);r=l?JSON.parse(l):void 0}catch{r=void 0}let s=Rc.get(e.id),i=r&&typeof r.id=="string"&&di.test(r.id)&&typeof r.lastSeenAt=="number"?{id:r.id,lastSeenAt:r.lastSeenAt}:s,o=n.idle_seconds*1e3,a=i&&t-i.lastSeenAt>=0&&t-i.lastSeenAt<o?{id:i.id,lastSeenAt:t}:{id:crypto.randomUUID(),lastSeenAt:t};return Rc.set(e.id,a),xc(n,JSON.stringify(a)),a.id}function _l(e,t){let n=e.source_keys?.query;if(!Array.isArray(n)||n.length===0)return;let r;try{r=new URL(t)}catch{return}let s=e.source_keys?.max_value_length,i=Number.isInteger(s)?Math.min(Math.max(s??1,1),4096):512,o=Object.fromEntries(n.flatMap(c=>{if(typeof c!="string"||c.length===0||c.length>128)return[];let a=r.searchParams.get(c);return a?[[c,a.slice(0,i)]]:[]}));return Object.keys(o).length>0?o:void 0}async function Ft(e,t={},n={}){let r=Tn(n.source);if(gl(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??Pc(r),o=n.sessionId??Cc(r);if(![s,i,o].every(g=>di.test(g)))throw new TypeError("event, visitor, and session IDs must be UUIDs");let c=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!c)throw new TypeError("pageUrl is required outside a browser");let a=n.occurredAt??new Date().toISOString();if(Number.isNaN(Date.parse(a)))throw new TypeError("occurredAt is invalid");let l=n.referrer??(typeof document<"u"&&document.referrer||void 0),d=_l(r,c),p=d?{...t,source_keys:d}:t,m=It(),f=`${we.replace(/\/+$/,"")}/d/${encodeURIComponent(m)}/interactions`,y;try{y=await fetch(f,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({source:r.id,page_url:c,visitor_id:i,session_id:o,referrer:l,events:[{id:s,event_type:e,occurred_at:a,properties:p}]}),signal:n.signal,credentials:"omit",keepalive:n.keepalive??!1})}catch(g){throw new Cn(g instanceof Error?g.message:"Observation transport network error","OBSERVATION_NETWORK_ERROR",0,s)}let h=null;try{h=await y.json()}catch{}if(!y.ok||h?.success!==!0){let g=h;throw new Cn(g?.message||g?.error||`Observation transport failed (${y.status})`,g?.error||"OBSERVATION_TRANSPORT_FAILED",y.status,s)}return h}function Tc(e={},t={}){let n=Tn(t.source),r=as("page_view",n),s=typeof document>"u"||!r.title_property?{}:{[r.title_property]:document.title.slice(0,512)};return Ft(r.observation,{...s,...e},{...t,source:n.id})}function Ec(e,t={},n={}){if(!e||e.length>128)throw new TypeError("actionId is invalid");let r=Tn(n.source),s=as("declared_action",r),i=s.id_property?{[s.id_property]:e}:{};return Ft(s.observation,{...t,...i},{...n,source:r.id})}function Ic(){try{let e=Tn();return as("form_receipt",e),{visitor_id:Pc(e),session_id:Cc(e),source:e.id}}catch{return}}function Ac(e,t={}){let n=Tn(t.source),r=as("form_receipt",n);return Ft(r.observation,e,{...t,source:n.id})}var dr;function cs(e={}){if(typeof window>"u"||typeof document>"u")return()=>{};if(dr)return dr;if(window.__FSAOS_CONFIG__?.tracking?.enabled===!1)return()=>{};let t;try{t=Tn(e.source)}catch{return()=>{}}let n=e.pageViews===!1?[]:t.adapters.filter(m=>m.type==="page_view"),r=e.declaredActions===!1?[]:t.adapters.filter(m=>m.type==="declared_action"),s="",i=()=>{if(window.location.href!==s){s=window.location.href;for(let m of n){let f=m.title_property?{[m.title_property]:document.title.slice(0,512)}:{};Ft(m.observation,f,{source:t.id,keepalive:!0}).catch(()=>{})}}},o=m=>{if(m.target instanceof Element)for(let f of r){let y=f.attribute;if(!y||!ml.test(y))continue;let h=m.target.closest(`[${y}]`);if(!h)continue;let g=h.getAttribute(y)?.trim();if(!g||g.length>128)continue;let v={};f.id_property&&(v[f.id_property]=g),f.element_property&&(v[f.element_property]=h.tagName.toLowerCase()),Ft(f.observation,v,{source:t.id,keepalive:!0}).catch(()=>{})}},c=window.history.pushState,a=window.history.replaceState,l=()=>queueMicrotask(i),d=n.some(m=>m.history===!0),p=n.some(m=>m.pageshow===!0);return d&&(window.history.pushState=function(...f){c.apply(this,f),l()},window.history.replaceState=function(...f){a.apply(this,f),l()},window.addEventListener("popstate",i)),p&&window.addEventListener("pageshow",i),r.length>0&&document.addEventListener("click",o,{capture:!0}),n.length>0&&queueMicrotask(i),dr=()=>{window.removeEventListener("popstate",i),window.removeEventListener("pageshow",i),document.removeEventListener("click",o,{capture:!0}),d&&(window.history.pushState=c,window.history.replaceState=a),dr=void 0},dr}var En;ne(()=>{En=void 0});function us(e){if(En)return En.accountPath!==e.accountPath?Promise.reject(new Error("Reset the session before changing accounts")):En.promise;let t=te(),n=()=>{if(t!==te())throw new Error("Workspace session changed")},r=(async()=>{let s=await lt();if(n(),!s.principal_id)throw new Error("Workspace initialization requires an authenticated principal");let i=await C().fetchQuery({queryKey:S.memberships(s.principal_id),queryFn:Zr,staleTime:12e4,retry:!1});n();let o=i.find(p=>p.path===e.accountPath&&p.isAccount&&!p.isSpace);if(!o)throw new Error("Authenticated account membership is unavailable");let c=i.find(p=>p.isSpace&&p.accountId===o.personalSpaceId&&p.path===o.personalSpacePath);if(!c||!o.personalSpacePath)throw new Error("A provisioned default Space membership is required");let a=Ne(o),l=Ne(c),d=le();if(d&&d.id!==a.id)throw new Error("Reset the session before changing accounts");return d||Tt(a,{activate:!1}),await Ot(o.personalSpacePath,p=>{let m=i.find(f=>f.accountId===p&&(f.isAccount||f.isSpace));return m?Ne(m):null},{initialAnchor:l}),n(),{home:a,defaultSpace:l,memberships:i}})().catch(s=>{throw t===te()&&(En=void 0),s});return En={accountPath:e.accountPath,promise:r},r}var qt,pr,fr;ne(()=>{pr?.(),pr=void 0,qt=void 0,fr=void 0});function kc(e={}){if(qt)return e.workspace&&e.workspace.accountPath!==fr?Promise.reject(new Error("Initialize workspace through initializeWorkspace, or dispose the existing runtime first")):qt;fr=e.workspace?.accountPath;let t=te();return qt=(async()=>{let n=e.tracking??!0,r=n===!1?()=>{}:cs(typeof n=="object"?n:{});pr=r;try{let s=e.session===!1?null:await lt(),i=e.workspace?await us(e.workspace):void 0;if(t!==te())throw new Error("Session changed during initialization");let o=!1;return{session:s,workspace:i,dispose(){o||(o=!0,r(),t===te()&&(qt=void 0,fr=void 0,pr=void 0))}}}catch(s){throw r(),t===te()&&(qt=void 0,fr=void 0,pr=void 0),s}})(),qt}async function pi(e){try{return await R("execution-control-transition",e)}catch(t){if(!(t instanceof Re)||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 Mc(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 pi({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 Oc(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 pi({op:"request",command:"steer",delivery:"immediate",request_message_id:r,selected_queue_entry_id:s,idempotency_key:i,...n.scopePath?{_scope_path:n.scopePath}:{}}),c=o.outcome??o.state??o.status;return mi(c?{...o,state:c}:o)}async function Fc(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 pi({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 vl=/^[a-z][a-z0-9_-]{0,63}$/,bl=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,In=class extends Error{constructor(n,r,s,i){super(n);Y(this,"code");Y(this,"status");Y(this,"fillId");this.name="FormSubmissionError",this.code=r,this.status=s,this.fillId=i}};async function qc(e,t,n={}){if(!vl.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(!bl.test(r))throw new TypeError("fillId must be a UUID");let s=It(),i=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!i)throw new TypeError("pageUrl is required outside a browser");let o=`${we.replace(/\/+$/,"")}/d/${encodeURIComponent(s)}/actions/${encodeURIComponent(e)}`,c=Ic(),a=c?{visitor_id:c.visitor_id,session_id:c.session_id}:void 0,l;try{l=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({fill_id:r,page_url:i,fields:t,...a?{attribution:a}:{}}),signal:n.signal,credentials:"omit"})}catch(p){throw new In(p instanceof Error?p.message:"Form submission network error","FORM_NETWORK_ERROR",0,r)}let d=null;try{d=await l.json()}catch{}if(!l.ok||d?.success!==!0){let p=d;throw new In(p?.message||p?.error||`Form submission failed (${l.status})`,p?.error||"FORM_SUBMISSION_FAILED",l.status,r)}try{await Ac({fill_id:r,action_id:e,release_id:d.release_id},{eventId:r,pageUrl:i,signal:n.signal,keepalive:!0,...c?{source:c.source,visitorId:c.visitor_id,sessionId:c.session_id}:{}})}catch{}return d}var hi=J(ce(),1),Uc=J(Dc(),1);function Nc(e){return R("read",{path:e})}function Kc(e,t){return R("list",{path:e,...t})}function Lc(e){return R("create",e)}function jc(e){return R("update",e)}function Wc(e){return R("create",e)}function Bc(e,t){let r=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return R("tools/call",{name:e,instance_path:r,...t||{}})}function Vc(e,t,n){return R("signal",{target_id:e,event_name:t,payload:n||{}})}function Hc(e){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+e}var $c={signIn:e=>e.provider?L.auth.signInWithOAuth({provider:e.provider,options:{redirectTo:e.redirectTo||window.location.href}}):L.auth.signInWithPassword({email:e.email,password:e.password}),signUp:e=>L.auth.signUp({email:e.email,password:e.password,options:{data:e.metadata||{}}}),signOut:async()=>{await L.auth.signOut(),un(),C().clear()},getSession:()=>L.auth.getSession().then(e=>e.data.session),getUser:()=>L.auth.getUser().then(e=>e.data.user),onAuthStateChange:e=>{let{data:{subscription:t}}=L.auth.onAuthStateChange((n,r)=>{e({event:n,session:r,user:r?.user??null})});return()=>t?.unsubscribe()},resetPassword:e=>L.auth.resetPasswordForEmail(e),signInWithMagicLink:(e,t)=>L.auth.signInWithOtp({email:e,options:{emailRedirectTo:t||window.location.href}})};function Gc(){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,Uc.createRoot)(e).render((0,hi.createElement)(Bn,{client:C()},(0,hi.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 zc(){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 wl(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Sl(e,t){return t&&t.length>0?"select":e==="boolean"?"toggle":e==="integer"||e==="number"?"range":e==="string"?"text":"none"}function Rl(e,t){return!(e==="object"||e==="array")}function xl(e){return["string","number","integer","boolean"].includes(e)}function Pl(e){return e!=="object"&&e!=="array"}function Jc(e,t,n,r){let s=e?.properties;if(!s||typeof s!="object")return[];let i=[];for(let[o,c]of Object.entries(s)){let a=c.type||"string",l=c.enum,d=Rl(a,l),p=xl(a),m=Sl(a,l);i.push({key:o,label:c.title||wl(o),type:a,description:c.description,enum_values:l,default_value:n[o]??r[o]??c.default,editable:t,filterable:d,sortable:p,filter_widget:m})}return i}function gi(e){let t=e.default_data||{},n=e.field_defaults||{},r=Jc(e.input_schema,!0,t,n),s=Jc(e.system_schema,!1,t,n),i=[...r,...s],o=i.filter(l=>Pl(l.type)),c=i.filter(l=>l.filterable),a=i.filter(l=>l.sortable);return{fields:i,columns:o,filterable:c,sortable:a,form_fields:r,system_fields:s}}function Yc(e){return{field:"updated_at",direction:"desc"}}function Xc(e){let t=gi(e),n=new Set(e.input_schema?.required||[]);return t.form_fields.filter(r=>n.has(r.key)||r.default_value===void 0)}var me=J(ce(),1);var Cl=0;function Tl(){return`upload_${Date.now()}_${++Cl}`}async function Zc(e,t,n,r){let s=t.name||(e instanceof File?e.name:`file-${Date.now()}`),i=e.type||"application/octet-stream",o=t.itemType||"file",c={parent_path:t.parentPath,item_type:o,name:s,type_data:{...t.typeData||{},file_source:{type:"upload",content_type:i}}};t.cardParentPath&&(c.card_parent_path=t.cardParentPath);let l=await R("create",c);if(!l.id)throw new Error(l.error||l.message||"Failed to create file item");let d=l.id,p=l.path;if(l.storage_completed&&l.file_ref)return{itemId:d,itemPath:p,fileRef:l.file_ref};let m=l.storage_key,f=l.upload_token,y=l.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 El(y,m,f,e,i,n,r);let h=await eu(d,m,i);return{itemId:d,itemPath:p,fileRef:h}}function El(e,t,n,r,s,i,o){return new Promise((c,a)=>{let l=new XMLHttpRequest;if(l.open("PUT",`${e}/upload`),l.setRequestHeader("X-Storage-Key",t),l.setRequestHeader("Content-Type",s),n&&l.setRequestHeader("X-Upload-Token",n),l.upload.onprogress=d=>{d.lengthComputable&&i&&i(Math.round(d.loaded/d.total*100))},l.onload=()=>{l.status>=200&&l.status<300?c():a(new Error(`Storage upload failed: HTTP ${l.status} \u2014 ${l.responseText?.slice(0,300)}`))},l.onerror=()=>a(new Error("Storage upload network error")),l.ontimeout=()=>a(new Error("Storage upload timed out")),o){if(o.aborted){a(new Error("Upload cancelled"));return}o.addEventListener("abort",()=>{l.abort(),a(new Error("Upload cancelled"))})}l.send(r)})}async function eu(e,t,n){let r=await $e(),s=await fetch(`${we}/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 tu(){let[e,t]=(0,me.useState)([]),n=j(),r=(0,me.useRef)(e);r.current=e;let s=(0,me.useCallback)((h,g)=>{t(v=>v.map(x=>x.id===h?{...x,...g}:x))},[]),i=(0,me.useCallback)(h=>{t(g=>[...g,h])},[]),o=(0,me.useCallback)(async(h,g,v,x,O)=>{let X=v.name||g.name,P=g.type||"application/octet-stream",F=v.itemType||"file",W=O?.itemId||null,N=O?.itemPath||null,M=O?.storageKey||null,B=O?.uploadToken||null,A=O?.storageWorkerUrl||null;try{if(!x||x==="create"){s(h,{status:"creating",error:null,_failedAt:null});let D=await R("create",{parent_path:v.parentPath,item_type:F,name:X,type_data:{...v.typeData||{},file_source:{type:"upload",content_type:P}}});if(!D.id)throw Object.assign(new Error(D.error||D.message||"Failed to create file item"),{_step:"create"});if(W=D.id,N=D.path,s(h,{itemId:W,itemPath:N}),D.storage_completed&&D.file_ref){s(h,{status:"complete",progress:100,fileRef:D.file_ref}),n.invalidateQueries({queryKey:S.children(v.parentPath)});return}if(M=D.storage_key,B=D.upload_token||"",A=D.storage_worker_url||"https://fsaos-storage.radns.workers.dev",s(h,{_storageKey:M,_uploadToken:B,_storageWorkerUrl:A}),!M)throw Object.assign(new Error("Gateway returned no storage_key"),{_step:"create"})}(!x||x==="create"||x==="upload")&&(s(h,{status:"uploading",progress:0,error:null,_failedAt:null}),await new Promise((D,Ae)=>{let z=new XMLHttpRequest;s(h,{_xhr:z}),z.open("PUT",`${A}/upload`),z.setRequestHeader("X-Storage-Key",M),z.setRequestHeader("Content-Type",P),B&&z.setRequestHeader("X-Upload-Token",B),z.upload.onprogress=ht=>{ht.lengthComputable&&s(h,{progress:Math.round(ht.loaded/ht.total*100)})},z.onload=()=>{z.status>=200&&z.status<300?D():Ae(Object.assign(new Error(`Storage upload failed: HTTP ${z.status}`),{_step:"upload"}))},z.onerror=()=>Ae(Object.assign(new Error("Storage upload network error"),{_step:"upload"})),z.ontimeout=()=>Ae(Object.assign(new Error("Storage upload timed out"),{_step:"upload"})),z.send(g)}),s(h,{progress:100,_xhr:null})),s(h,{status:"confirming",error:null,_failedAt:null});let I=await eu(W,M,P);s(h,{status:"complete",fileRef:I}),n.invalidateQueries({queryKey:S.children(v.parentPath)})}catch(I){let Q=I?.message||String(I),D=I?._step||"create";s(h,{status:"error",error:Q,_failedAt:D,_xhr:null})}},[s,n]),c=(0,me.useCallback)((h,g)=>{let v=Tl();i({id:v,file:h,status:"creating",progress:0,error:null,itemId:null,itemPath:null,fileRef:null,options:g,_storageKey:null,_uploadToken:null,_storageWorkerUrl:null,_xhr:null,_failedAt:null}),o(v,h,g)},[i,o]),a=(0,me.useCallback)((h,g)=>{for(let v of h)c(v,g)},[c]),l=(0,me.useCallback)(h=>{let g=r.current.find(O=>O.id===h);if(!g||g.status!=="error")return;let v=g._failedAt||"create",x=g._storageKey&&g.itemId?{storageKey:g._storageKey,uploadToken:g._uploadToken||"",storageWorkerUrl:g._storageWorkerUrl||"https://fsaos-storage.radns.workers.dev",itemId:g.itemId,itemPath:g.itemPath||""}:void 0;o(h,g.file,g.options,v,x)},[o]),d=(0,me.useCallback)(h=>{let g=r.current.find(v=>v.id===h);g&&(g._xhr&&g._xhr.abort(),s(h,{status:"error",error:"Cancelled",_xhr:null,_failedAt:null}))},[s]),p=(0,me.useCallback)(h=>{t(g=>g.filter(v=>v.id!==h))},[]),m=(0,me.useCallback)(()=>{t(h=>h.filter(g=>g.status!=="complete"))},[]),f=e.some(h=>h.status==="creating"||h.status==="uploading"||h.status==="confirming"),y=e.map(({_storageKey:h,_uploadToken:g,_storageWorkerUrl:v,_xhr:x,_failedAt:O,...X})=>X);return{upload:c,uploadMultiple:a,uploads:y,retryUpload:l,cancelUpload:d,removeUpload:p,clearCompleted:m,isUploading:f}}var nu=J(ce(),1);async function yi(e,t){return await R("resolve-items",{context_id:e,item_type:t})}function ru(e,t){return(0,nu.useSyncExternalStore)(Ee,se,se),K({queryKey:["vfs",re()??"__unscoped__","resolved-items",e??"",t],queryFn:()=>yi(e,t),enabled:!!(e&&t)})}var Ie=J(ce(),1);function ls(e,t){let n={artifacts:new Map,timeline:[]},r=new Map;function s(o){if(!o.action?.startsWith("artifact_"))return;let a,l=o.name;if(typeof l=="string"&&l.startsWith("{"))try{a=JSON.parse(l)}catch{return}else if(o.artifact_id)a=o;else return;switch(a.type){case"artifact_opened":{let d=Date.now();if(n.artifacts.set(a.artifact_id,{artifact_id:a.artifact_id,surface_type:a.surface_type,tool_id:a.tool_id,tool_name:a.tool_name,target_uri:a.target_uri,status:"streaming",content:"",total_chars:0,delta_count:0,artifact_item_uri:null,evidence_uri:null,meta:a.meta,started_at:d,completed_at:null}),r.has(a.tool_id)){let p=r.get(a.tool_id);n.timeline[p].artifact_ids.push(a.artifact_id)}else{let p=n.timeline.length;n.timeline.push({tool_id:a.tool_id,tool_name:a.tool_name,status:"started",target_uri:a.target_uri,started_at:d,completed_at:null,artifact_ids:[a.artifact_id]}),r.set(a.tool_id,p)}break}case"artifact_delta":{let d=n.artifacts.get(a.artifact_id);d&&(d.content+=a.content_delta,d.total_chars+=a.content_delta.length,d.delta_count+=1,a.target_uri&&!d.target_uri&&(d.target_uri=a.target_uri));break}case"artifact_done":{let d=n.artifacts.get(a.artifact_id);d&&(d.status=a.status,d.total_chars=a.total_chars,d.artifact_item_uri=a.artifact_item_uri,d.evidence_uri=a.evidence_uri,a.target_uri&&(d.target_uri=a.target_uri),(a.status==="completed"||a.status==="failed")&&(d.completed_at=Date.now()));let p=r.get(a.tool_id);if(p!==void 0){let m=n.timeline[p];a.status==="executing"?m.status="executing":a.status==="completed"?(m.status="completed",m.completed_at=Date.now()):a.status==="failed"&&(m.status="failed",m.completed_at=Date.now()),a.target_uri&&!m.target_uri&&(m.target_uri=a.target_uri)}break}}t(n)}return Kr(e,s)}function su(e,t=!0){let[n,r]=(0,Ie.useState)(new Map),[s,i]=(0,Ie.useState)([]),o=(0,Ie.useRef)({artifacts:new Map,timeline:[]});(0,Ie.useEffect)(()=>!e||!t?void 0:ls(e,p=>{o.current=p,r(new Map(p.artifacts)),i([...p.timeline])}),[e,t]);let c=(0,Ie.useCallback)(()=>{r(new Map),i([]),o.current={artifacts:new Map,timeline:[]}},[]),a=Array.from(n.values()).find(d=>d.surface_type==="file_editor"&&d.status==="streaming")??null,l=Array.from(n.values()).filter(d=>d.surface_type==="activity"&&(d.status==="streaming"||d.status==="executing"));return{artifacts:n,timeline:s,activeEditor:a,activeActivities:l,reset:c}}function iu(e,t=!0){let[n,r]=(0,Ie.useState)([]);(0,Ie.useEffect)(()=>!e||!t?void 0:ls(e,o=>{r([...o.timeline])}),[e,t]);let s=n.length>0?n[n.length-1]:null;return{timeline:n,latestActivity:s}}var ds=J(ce(),1);function Il(e,t,n,r){return["vfs","timeline-history",e,t??"__all__",n??500,r??0]}async function _i(e,t){let n=`${e}/datasets/agent-events`,r=t?.limit??500,s=t?.offset??0,i={limit:r,offset:s,sort:[{key:"seq",direction:"asc"}]};t?.turnId&&(i.filters=[{key:"turn_id",operator:"eq",value:t.turnId}]);try{let c=(await R("open",{path:n,mode:"extract",strategy:"rows",arguments:i}))?.content;return c?(c.rows??c.items??c.data??[]).map(Al).sort((l,d)=>l.seq-d.seq):[]}catch(o){if(o?.status===404||o?.message?.includes("not found"))return[];throw o}}function ou(e,t){let{turnId:n,limit:r=500,offset:s=0,enabled:i=!0,debounceMs:o=300}=t??{},c=e?`${e}/datasets/agent-events`:null,a=j(),l=(0,ds.useRef)(null),d=c?Il(c,n,r,s):["vfs","timeline-history","__disabled__"],p=K({queryKey:d,queryFn:()=>_i(e,{turnId:n,limit:r,offset:s}),enabled:!!e&&i});return(0,ds.useEffect)(()=>{if(!c||!i)return;let m=ie("vfs_change",()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{a.invalidateQueries({queryKey:d})},o)},f=>{let y=f?.path;return y?y===c||y.startsWith(c+"/"):!1});return()=>{m(),l.current&&clearTimeout(l.current)}},[c,i,o,a,JSON.stringify(d)]),{events:p.data??[],isLoading:p.isLoading,error:p.error,isFetching:p.isFetching,refetch:()=>{p.refetch()}}}function Al(e){return{turn_id:String(e.turn_id??""),seq:Number(e.seq??0),kind:String(e.kind??""),status:String(e.status??""),title:String(e.title??""),tool_name:e.tool_name!=null?String(e.tool_name):void 0,tool_id:e.tool_id!=null?String(e.tool_id):void 0,evidence_uri:e.evidence_uri!=null?String(e.evidence_uri):void 0,artifact_item_uri:e.artifact_item_uri!=null?String(e.artifact_item_uri):void 0,preview:e.preview!=null?String(e.preview):void 0,duration_ms:e.duration_ms!=null?Number(e.duration_ms):void 0,started_at:String(e.started_at??""),completed_at:e.completed_at!=null?String(e.completed_at):void 0,error_type:e.error_type!=null?String(e.error_type):void 0,meta:e.meta!=null?e.meta:void 0}}var fs=J(ce(),1);function au(){(0,fs.useSyncExternalStore)(Ee,se,se);let e=re(),t=Se(),n=xn(e?{key:"pinned",...t?{scope_id:t.id}:{}}:null),r=j(),s=n.resolvedChildren,i=!!(!n.error&&n.arrangement?.item_id&&n.resolutionLevel==="member"&&n.arrangement.write_target_id===n.arrangement.item_id),o=ge({mutationFn:async a=>{let l,d={_scope_path:a.scopePath};if(a.operation==="pin"?l=await R("create",{...d,parent_id:a.arrangementId,name:`pin-${a.target.id}`,item_type:"symlink",type_data:{target_item_id:a.target.id,target_type:a.target.item_type}}):a.operation==="unpin"?l=await R("delete",{...d,id:a.entry.id}):l=await R("update",{...d,id:a.arrangementId,type_data:{order:a.ids}}),l?.success===!1)throw new Error(l.error||"Pins could not be saved");return l},onSettled:(a,l,d)=>ln(r,d.queryKey)}),c=(0,fs.useCallback)(a=>!i||!e||re()!==e?Promise.reject(new Error("Personal pins are not available in this context")):a.operation==="unpin"&&!s.some(l=>l.id===a.entry.id)?Promise.reject(new Error("Pin is outside this arrangement")):a.operation==="reorder"&&(new Set(a.ids).size!==s.length||a.ids.length!==s.length||s.some(l=>!a.ids.includes(l.id)))?Promise.reject(new Error("Order must include each pin exactly once")):a.operation==="pin"&&s.some(l=>l.symlink_type_data?.target_item_id===a.target.id)?Promise.resolve(null):o.mutateAsync({...a,scopePath:e,arrangementId:n.arrangement.item_id,arrangementPath:n.arrangement.item_path,queryKey:n.arrangementQueryKey}),[i,e,s,n.arrangement,n.arrangementQueryKey,o.mutateAsync]);return{entries:s,isLoading:n.isLoading,error:n.error,refetch:n.refetch,ready:i,isSaving:o.isPending,saveError:o.error,isPinned:a=>s.some(l=>l.symlink_type_data?.target_item_id===a),pin:a=>c({operation:"pin",target:a}),unpin:a=>{let l=s.find(d=>d.symlink_type_data?.target_item_id===a||d.id===a);return l?c({operation:"unpin",entry:l}):Promise.resolve(null)},reorder:a=>c({operation:"reorder",ids:a})}}Ja(vi);return vu(vi);})();
8
8
 
9
9
  /* ── Auto-setup: require shim + mount + backward compat globals ── */
10
10
  (function() {