@ai4b-team/fsaos-gateway-sdk 5.6.2 → 5.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,10 @@
1
- /* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-11-16T02:47:59.382Z */
2
- "use strict";var __FSAOS_GATEWAY__=(()=>{var Yl=Object.create;var Zn=Object.defineProperty;var Xl=Object.getOwnPropertyDescriptor;var Zl=Object.getOwnPropertyNames;var ed=Object.getPrototypeOf,td=Object.prototype.hasOwnProperty;var yo=e=>{throw TypeError(e)};var nd=(e,t,n)=>t in e?Zn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var er=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),_o=(e,t)=>{for(var n in t)Zn(e,n,{get:t[n],enumerable:!0})},vo=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Zl(t))!td.call(e,s)&&s!==n&&Zn(e,s,{get:()=>t[s],enumerable:!(r=Xl(t,s))||r.enumerable});return e};var ne=(e,t,n)=>(n=e!=null?Yl(ed(e)):{},vo(t||!e||!e.__esModule?Zn(n,"default",{value:e,enumerable:!0}):n,e)),rd=e=>vo(Zn({},"__esModule",{value:!0}),e);var X=(e,t,n)=>nd(e,typeof t!="symbol"?t+"":t,n),Vs=(e,t,n)=>t.has(e)||yo("Cannot "+n);var p=(e,t,n)=>(Vs(e,t,"read from private field"),n?n.call(e):t.get(e)),M=(e,t,n)=>t.has(e)?yo("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),P=(e,t,n,r)=>(Vs(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),q=(e,t,n)=>(Vs(e,t,"access private method"),n);var tr=(e,t,n,r)=>({set _(s){P(e,t,s,n)},get _(){return p(e,t,r)}});var fe=er((ef,bo)=>{bo.exports=React});var Gr=er((Xm,ea)=>{ea.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var fa=er((Tg,pa)=>{pa.exports={createClient:window.supabase.createClient}});var ja=er(($g,Ha)=>{Ha.exports=ReactDOM});var ml=er((n_,fl)=>{fl.exports=ReactDOM});var go={};_o(go,{CHANNEL_AI_MODES:()=>Nu,ComponentRenderer:()=>Mu,EnforcementDeniedError:()=>Ke,FormSubmissionError:()=>Xn,GatewayRequestError:()=>Se,HostSessionUnavailableError:()=>$t,InteractionTrackingError:()=>Jn,KernelProvider:()=>ku,QueryClientProvider:()=>fr,acceptInvitation:()=>Dp,acceptInvite:()=>so,answerInput:()=>ao,assignPersonalSection:()=>Wl,auth:()=>Rl,awaitAnchorReady:()=>yr,awaitScopeReady:()=>Ca,callTool:()=>wl,cancelInvitation:()=>Kp,cancelQueuedTurn:()=>dl,cancelTurn:()=>ul,clearCachedToken:()=>vi,clearSession:()=>Ei,configureGatewayReads:()=>Qa,connectHostSession:()=>Ea,createAgent:()=>oo,createInvitation:()=>Np,createItem:()=>_l,disconnectSSE:()=>Ui,disposeVfsRealtimeWs:()=>Li,electHomeAnchor:()=>Vt,emitEvent:()=>lc,fetchChannelMessages:()=>xc,fetchChannelMessagesPage:()=>Xt,fetchChannelMessagesWithCards:()=>Ps,fetchEdgesForItem:()=>bs,fetchItemHistory:()=>xs,fetchItemVersions:()=>Pr,fetchItems:()=>Yt,fetchMemberFocus:()=>Rs,fetchMessageReplies:()=>Cs,fetchMessageReplyContexts:()=>wc,fetchOpenEnvelope:()=>Er,fetchRecentActivity:()=>Ss,fetchResolvedItems:()=>lo,fetchTimelineHistory:()=>po,fetchTurnQueueEntries:()=>yc,fetchTypeDefinitions:()=>vs,fetchVfsChildren:()=>Cr,fetchVfsChildrenPage:()=>_s,fetchVfsItem:()=>Rr,fetchVfsItemById:()=>xr,fetchVfsTree:()=>ws,gatewayCall:()=>R,getAccessToken:()=>at,getAnchor:()=>Rt,getAnchorRef:()=>ye,getAnchorVersion:()=>Si,getAssetUrl:()=>xl,getDefaultSort:()=>Ol,getHomeAnchor:()=>we,getInvitation:()=>Qp,getMountVersion:()=>_r,getMounts:()=>qe,getPathSubscriptionState:()=>pc,getQueryClient:()=>Q,getRequiredFormFields:()=>Fl,getScope:()=>z,getScopeVersion:()=>G,getServerClockOffsetMs:()=>ka,getServerClockSyncedAt:()=>Oa,getSessionEntry:()=>Ct,hasServerClock:()=>Ma,initSession:()=>ct,initVfsRealtimeWs:()=>Zt,initializeFsaos:()=>al,initializeWorkspace:()=>Us,interpretSchema:()=>co,invalidateAllVfs:()=>Pc,invalidateChannelMessages:()=>Ic,invalidateChildren:()=>ys,invalidateItem:()=>Ki,invalidateOpenEnvelope:()=>Tc,invalidatePathAndParent:()=>Rc,invalidateSubtree:()=>Cc,invalidateTypes:()=>Ec,inviteMember:()=>ro,isAnchorReady:()=>Ri,isChannelPath:()=>de,isListableItemsFilter:()=>jn,isScopeReady:()=>ts,itemsFilterFromQueryFilter:()=>_c,listChildren:()=>yl,listInvitations:()=>Hp,loadMounts:()=>en,loadPublishedBundle:()=>xu,mount:()=>Cl,mountRealtimeScope:()=>Vn,normalizeItem:()=>De,onConnectionStateChange:()=>hs,pathSubscriptionMatches:()=>Ni,personalSectionsKey:()=>Dr,ping:()=>dc,pushChanges:()=>bl,queryClient:()=>Ja,readItem:()=>hl,refreshQuery:()=>le,registerCleanup:()=>oe,rejectInvitation:()=>Up,replaceMounts:()=>Ms,resendInvitation:()=>Lp,resetAllSdkState:()=>On,resolvePrincipalId:()=>Tu,resubscribePath:()=>mc,seatMember:()=>io,selectMount:()=>kr,sendMessage:()=>bc,serveHostSession:()=>cl,serverDeadlinePassed:()=>Fa,serverMsUntil:()=>qa,serverNow:()=>ss,setAnchor:()=>kn,setCachedToken:()=>ha,setQueryClient:()=>za,setScope:()=>Ra,setupRequireShim:()=>Pl,signal:()=>Sl,startTracking:()=>Ds,steerTurn:()=>ll,submitForm:()=>pl,subscribeAnchor:()=>xi,subscribeArtifactStream:()=>Ks,subscribeMounts:()=>es,subscribeScope:()=>Ie,subscribeToEvents:()=>J,subscribeToPath:()=>gs,subscribeToScope:()=>Ln,trackAction:()=>sl,trackEvent:()=>nn,trackPageView:()=>rl,unmountRealtimeScope:()=>Ts,updateItem:()=>vl,uploadFile:()=>Ql,useAcceptInvite:()=>Il,useAccounts:()=>mu,useAgentTimeline:()=>jl,useAllChannels:()=>Ns,useAnswerInput:()=>Ml,useArrangement:()=>zn,useArtifactStream:()=>Hl,useAsset:()=>hu,useAuth:()=>qs,useChannelMessages:()=>Ou,useChannels:()=>Qu,useChildren:()=>Xc,useComponent:()=>Ji,useCreate:()=>Ku,useCreateAgent:()=>Al,useDelete:()=>ju,useDmChannels:()=>Du,useEdges:()=>iu,useEventStream:()=>$u,useFileUpload:()=>Ul,useIncrementalItems:()=>ru,useInfiniteChannelMessages:()=>qu,useInfiniteChildren:()=>su,useInfiniteItems:()=>zi,useInviteMember:()=>El,useItem:()=>Jc,useItemById:()=>Yc,useItemHistory:()=>du,useItemVersions:()=>lu,useItems:()=>nu,useLink:()=>Vu,useList:()=>Gi,useMemberFocus:()=>uu,useMessageReplies:()=>Fu,useMintedAsset:()=>zu,useMounts:()=>gu,useMove:()=>Bu,useMutation:()=>Wu,useNotifications:()=>Yi,useOpen:()=>au,usePermission:()=>Pu,usePermissions:()=>Eu,usePersonalItemOrder:()=>Yu,usePersonalSections:()=>Gl,usePinnedItems:()=>Vl,usePrincipal:()=>Au,usePublishedComponent:()=>Ru,useRealtimeQuery:()=>Gu,useRecentActivity:()=>pu,useResolve:()=>tu,useResolvedItems:()=>Ll,useScope:()=>fu,useScopeReady:()=>zc,useSearch:()=>eu,useSeatMember:()=>Tl,useTheme:()=>Cu,useTimelineHistory:()=>Bl,useTree:()=>Zc,useType:()=>ou,useTypeHelpers:()=>cu,useTypes:()=>Fs,useUnreadCounts:()=>Uu,useUpdate:()=>Lu,useUpdatePrincipal:()=>Hu,vfsKeys:()=>I,waitForPathReady:()=>fc});var Ke=class e extends Error{constructor(n){let r=n.message||e.fallbackMessage(n);super(r);X(this,"name","EnforcementDeniedError");X(this,"deniedBy");X(this,"ruleKey");X(this,"displayName");X(this,"payload");this.payload=n,this.deniedBy=n.denied_by||n.error_type||n.error||"unknown";let s=n.enforcement;this.ruleKey=s?.rule_key??void 0,this.displayName=s?.display_name??void 0}static fallbackMessage(n){let r=n.error||"",s=n.denied_by||"";return s==="rule"||r==="RULE_DENIED"?"This feature is not enabled for this workspace.":s==="entitlement"||r==="ENTITLEMENT_REQUIRED"?"This feature requires a plan upgrade.":s==="access"||r==="ACCESS_DENIED"||r==="PERMISSION_DENIED"?"You don't have permission to do this.":"This action is not allowed."}get isRuleDenial(){return this.deniedBy==="rule"||this.deniedBy==="RULE_DENIED"}get isAccessDenial(){return this.deniedBy==="access"||this.deniedBy==="ACCESS_DENIED"}get isEntitlementDenial(){return this.deniedBy==="entitlement"||this.deniedBy==="ENTITLEMENT_REQUIRED"}};var Mt=ne(fe(),1);var ke=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 Ot,ft,sn,wo,sd=(wo=class extends ke{constructor(){super();M(this,Ot);M(this,ft);M(this,sn);P(this,sn,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){p(this,ft)||this.setEventListener(p(this,sn))}onUnsubscribe(){var t;this.hasListeners()||((t=p(this,ft))==null||t.call(this),P(this,ft,void 0))}setEventListener(t){var n;P(this,sn,t),(n=p(this,ft))==null||n.call(this),P(this,ft,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){p(this,Ot)!==t&&(P(this,Ot,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof p(this,Ot)=="boolean"?p(this,Ot):globalThis.document?.visibilityState!=="hidden"}},Ot=new WeakMap,ft=new WeakMap,sn=new WeakMap,wo),on=new sd;var id={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},mt,Ws,So,od=(So=class{constructor(){M(this,mt,id);M(this,Ws,!1)}setTimeoutProvider(e){P(this,mt,e)}setTimeout(e,t){return p(this,mt).setTimeout(e,t)}clearTimeout(e){p(this,mt).clearTimeout(e)}setInterval(e,t){return p(this,mt).setInterval(e,t)}clearInterval(e){p(this,mt).clearInterval(e)}},mt=new WeakMap,Ws=new WeakMap,So),Be=new od;function xo(e){setTimeout(e,0)}var Gs=typeof window>"u"||"Deno"in globalThis;function re(){}function Po(e,t){return typeof e=="function"?e(t):e}function nr(e){return typeof e=="number"&&e>=0&&e!==1/0}function Ur(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Le(e,t){return typeof e=="function"?e(t):e}function Re(e,t){return typeof e=="function"?e(t):e}function Kr(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:o,stale:a}=e;if(o){if(r){if(t.queryHash!==rr(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 Lr(e,t){let{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Ve(t.options.mutationKey)!==Ve(i))return!1}else if(!Ft(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function rr(e,t){return(t?.queryKeyHashFn||Ve)(e)}function Ve(e){return JSON.stringify(e,(t,n)=>$s(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 ad=Object.prototype.hasOwnProperty;function zs(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=Ro(e)&&Ro(t);if(!r&&!($s(e)&&$s(t)))return t;let i=(r?e:Object.keys(e)).length,o=r?t:Object.keys(t),a=o.length,c=r?new Array(a):{},u=0;for(let l=0;l<a;l++){let d=r?l:o[l],h=e[d],f=t[d];if(h===f){c[d]=h,(r?l<i:ad.call(e,d))&&u++;continue}if(h===null||f===null||typeof h!="object"||typeof f!="object"){c[d]=f;continue}let m=zs(h,f,n+1);c[d]=m,m===h&&u++}return i===a&&u===i?e:c}function an(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 Ro(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function $s(e){if(!Co(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Co(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Co(e){return Object.prototype.toString.call(e)==="[object Object]"}function Eo(e){return new Promise(t=>{Be.setTimeout(t,e)})}function sr(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?zs(e,t):t}function Io(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function To(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var cn=Symbol();function Hr(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===cn?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function un(e,t){return typeof e=="function"?e(...t):!!e}function Ao(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 We=(()=>{let e=()=>Gs;return{isServer(){return e()},setIsServer(t){e=t}}})();function ir(){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 Mo=xo;function cd(){let e=[],t=0,n=a=>{a()},r=a=>{a()},s=Mo,i=a=>{t?e.push(a):s(()=>{n(a)})},o=()=>{let a=e;e=[],a.length&&s(()=>{r(()=>{a.forEach(c=>{n(c)})})})};return{batch:a=>{let c;t++;try{c=a()}finally{t--,t||o()}return c},batchCalls:a=>(...c)=>{i(()=>{a(...c)})},schedule:i,setNotifyFunction:a=>{n=a},setBatchNotifyFunction:a=>{r=a},setScheduler:a=>{s=a}}}var V=cd();var ln,gt,dn,ko,ud=(ko=class extends ke{constructor(){super();M(this,ln,!0);M(this,gt);M(this,dn);P(this,dn,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(){p(this,gt)||this.setEventListener(p(this,dn))}onUnsubscribe(){var t;this.hasListeners()||((t=p(this,gt))==null||t.call(this),P(this,gt,void 0))}setEventListener(t){var n;P(this,dn,t),(n=p(this,gt))==null||n.call(this),P(this,gt,t(this.setOnline.bind(this)))}setOnline(t){p(this,ln)!==t&&(P(this,ln,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return p(this,ln)}},ln=new WeakMap,gt=new WeakMap,dn=new WeakMap,ko),pn=new ud;function ld(e){return Math.min(1e3*2**e,3e4)}function Js(e){return(e??"online")==="online"?pn.isOnline():!0}var jr=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Br(e){let t=!1,n=0,r,s=ir(),i=()=>s.status!=="pending",o=v=>{if(!i()){let g=new jr(v);h(g),e.onCancel?.(g)}},a=()=>{t=!0},c=()=>{t=!1},u=()=>on.isFocused()&&(e.networkMode==="always"||pn.isOnline())&&e.canRun(),l=()=>Js(e.networkMode)&&e.canRun(),d=v=>{i()||(r?.(),s.resolve(v))},h=v=>{i()||(r?.(),s.reject(v))},f=()=>new Promise(v=>{r=g=>{(i()||u())&&v(g)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),m=()=>{if(i())return;let v,g=n===0?e.initialPromise:void 0;try{v=g??e.fn()}catch(w){v=Promise.reject(w)}Promise.resolve(v).then(d).catch(w=>{if(i())return;let y=e.retry??(We.isServer()?0:3),_=e.retryDelay??ld,S=typeof _=="function"?_(n,w):_,x=y===!0||typeof y=="number"&&n<y||typeof y=="function"&&y(n,w);if(t||!x){h(w);return}n++,e.onFail?.(n,w),Eo(S).then(()=>u()?void 0:f()).then(()=>{t?h(w):m()})})};return{promise:s,status:()=>s.status,cancel:o,continue:()=>(r?.(),s),cancelRetry:a,continueRetry:c,canStart:l,start:()=>(l()?m():f().then(m),s)}}var qt,Oo,Vr=(Oo=class{constructor(){M(this,qt)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),nr(this.gcTime)&&P(this,qt,Be.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(We.isServer()?1/0:5*60*1e3))}clearGcTimeout(){p(this,qt)!==void 0&&(Be.clearTimeout(p(this,qt)),P(this,qt,void 0))}},qt=new WeakMap,Oo);var Nt,fn,Oe,Qt,ue,or,Dt,Ee,Do,Ze,No,Qo=(No=class extends Vr{constructor(t){super();M(this,Ee);M(this,Nt);M(this,fn);M(this,Oe);M(this,Qt);M(this,ue);M(this,or);M(this,Dt);P(this,Dt,!1),P(this,or,t.defaultOptions),this.setOptions(t.options),this.observers=[],P(this,Qt,t.client),P(this,Oe,p(this,Qt).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,P(this,Nt,qo(this.options)),this.state=t.state??p(this,Nt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return p(this,ue)?.promise}setOptions(t){if(this.options={...p(this,or),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=qo(this.options);n.data!==void 0&&(this.setState(Fo(n.data,n.dataUpdatedAt)),P(this,Nt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&p(this,Oe).remove(this)}setData(t,n){let r=sr(this.state.data,t,this.options);return q(this,Ee,Ze).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){q(this,Ee,Ze).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=p(this,ue)?.promise;return p(this,ue)?.cancel(t),n?n.then(re).catch(re):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return p(this,Nt)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>Re(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===cn||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>Le(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:!Ur(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),p(this,ue)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),p(this,ue)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),p(this,Oe).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(p(this,ue)&&(p(this,Dt)||q(this,Ee,Do).call(this)?p(this,ue).cancel({revert:!0}):p(this,ue).cancelRetry()),this.scheduleGc()),p(this,Oe).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||q(this,Ee,Ze).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&p(this,ue)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(p(this,ue))return p(this,ue).continueRetry(),p(this,ue).promise}if(t&&this.setOptions(t),!this.options.queryFn){let c=this.observers.find(u=>u.options.queryFn);c&&this.setOptions(c.options)}let r=new AbortController,s=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(P(this,Dt,!0),r.signal)})},i=()=>{let c=Hr(this.options,n),l=(()=>{let d={client:p(this,Qt),queryKey:this.queryKey,meta:this.meta};return s(d),d})();return P(this,Dt,!1),this.options.persister?this.options.persister(c,l,this):c(l)},a=(()=>{let c={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:p(this,Qt),state:this.state,fetchFn:i};return s(c),c})();this.options.behavior?.onFetch(a,this),P(this,fn,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&q(this,Ee,Ze).call(this,{type:"fetch",meta:a.fetchOptions?.meta}),P(this,ue,Br({initialPromise:n?.initialPromise,fn:a.fetchFn,onCancel:c=>{c instanceof jr&&c.revert&&this.setState({...p(this,fn),fetchStatus:"idle"}),r.abort()},onFail:(c,u)=>{q(this,Ee,Ze).call(this,{type:"failed",failureCount:c,error:u})},onPause:()=>{q(this,Ee,Ze).call(this,{type:"pause"})},onContinue:()=>{q(this,Ee,Ze).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0}));try{let c=await p(this,ue).start();if(c===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(c),p(this,Oe).config.onSuccess?.(c,this),p(this,Oe).config.onSettled?.(c,this.state.error,this),c}catch(c){if(c instanceof jr){if(c.silent)return p(this,ue).promise;if(c.revert){if(this.state.data===void 0)throw c;return this.state.data}}throw q(this,Ee,Ze).call(this,{type:"error",error:c}),p(this,Oe).config.onError?.(c,this),p(this,Oe).config.onSettled?.(this.state.data,c,this),c}finally{this.scheduleGc()}}},Nt=new WeakMap,fn=new WeakMap,Oe=new WeakMap,Qt=new WeakMap,ue=new WeakMap,or=new WeakMap,Dt=new WeakMap,Ee=new WeakSet,Do=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},Ze=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,...Ys(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...Fo(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return P(this,fn,t.manual?s:void 0),s;case"error":let i=t.error;return{...r,error:i,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),V.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),p(this,Oe).notify({query:this,type:"updated",action:t})})},No);function Ys(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Js(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Fo(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function qo(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 Ce,K,cr,be,Ut,mn,et,ht,ur,gn,hn,Kt,Lt,yt,yn,B,ar,Xs,Zs,ei,ti,ni,ri,si,Ho,Lo,lr=(Lo=class extends ke{constructor(t,n){super();M(this,B);M(this,Ce);M(this,K);M(this,cr);M(this,be);M(this,Ut);M(this,mn);M(this,et);M(this,ht);M(this,ur);M(this,gn);M(this,hn);M(this,Kt);M(this,Lt);M(this,yt);M(this,yn,new Set);this.options=n,P(this,Ce,t),P(this,ht,null),P(this,et,ir()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(p(this,K).addObserver(this),Uo(p(this,K),this.options)?q(this,B,ar).call(this):this.updateResult(),q(this,B,ti).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return ii(p(this,K),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return ii(p(this,K),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,q(this,B,ni).call(this),q(this,B,ri).call(this),p(this,K).removeObserver(this)}setOptions(t){let n=this.options,r=p(this,K);if(this.options=p(this,Ce).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Re(this.options.enabled,p(this,K))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");q(this,B,si).call(this),p(this,K).setOptions(this.options),n._defaulted&&!an(this.options,n)&&p(this,Ce).getQueryCache().notify({type:"observerOptionsUpdated",query:p(this,K),observer:this});let s=this.hasListeners();s&&Ko(p(this,K),r,this.options,n)&&q(this,B,ar).call(this),this.updateResult(),s&&(p(this,K)!==r||Re(this.options.enabled,p(this,K))!==Re(n.enabled,p(this,K))||Le(this.options.staleTime,p(this,K))!==Le(n.staleTime,p(this,K)))&&q(this,B,Xs).call(this);let i=q(this,B,Zs).call(this);s&&(p(this,K)!==r||Re(this.options.enabled,p(this,K))!==Re(n.enabled,p(this,K))||i!==p(this,yt))&&q(this,B,ei).call(this,i)}getOptimisticResult(t){let n=p(this,Ce).getQueryCache().build(p(this,Ce),t),r=this.createResult(n,t);return pd(this,r)&&(P(this,be,r),P(this,mn,this.options),P(this,Ut,p(this,K).state)),r}getCurrentResult(){return p(this,be)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&p(this,et).status==="pending"&&p(this,et).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){p(this,yn).add(t)}getCurrentQuery(){return p(this,K)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=p(this,Ce).defaultQueryOptions(t),r=p(this,Ce).getQueryCache().build(p(this,Ce),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return q(this,B,ar).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),p(this,be)))}createResult(t,n){let r=p(this,K),s=this.options,i=p(this,be),o=p(this,Ut),a=p(this,mn),u=t!==r?t.state:p(this,cr),{state:l}=t,d={...l},h=!1,f;if(n._optimisticResults){let O=this.hasListeners(),T=!O&&Uo(t,n),E=O&&Ko(t,r,n,s);(T||E)&&(d={...d,...Ys(l.data,t.options)}),n._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:m,errorUpdatedAt:v,status:g}=d;f=d.data;let w=!1;if(n.placeholderData!==void 0&&f===void 0&&g==="pending"){let O;i?.isPlaceholderData&&n.placeholderData===a?.placeholderData?(O=i.data,w=!0):O=typeof n.placeholderData=="function"?n.placeholderData(p(this,hn)?.state.data,p(this,hn)):n.placeholderData,O!==void 0&&(g="success",f=sr(i?.data,O,n),h=!0)}if(n.select&&f!==void 0&&!w)if(i&&f===o?.data&&n.select===p(this,ur))f=p(this,gn);else try{P(this,ur,n.select),f=n.select(f),f=sr(i?.data,f,n),P(this,gn,f),P(this,ht,null)}catch(O){P(this,ht,O)}p(this,ht)&&(m=p(this,ht),f=p(this,gn),v=Date.now(),g="error");let y=d.fetchStatus==="fetching",_=g==="pending",S=g==="error",x=_&&y,k=f!==void 0,C={status:g,fetchStatus:d.fetchStatus,isPending:_,isSuccess:g==="success",isError:S,isInitialLoading:x,isLoading:x,data:f,dataUpdatedAt:d.dataUpdatedAt,error:m,errorUpdatedAt:v,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:d.dataUpdateCount>u.dataUpdateCount||d.errorUpdateCount>u.errorUpdateCount,isFetching:y,isRefetching:y&&!_,isLoadingError:S&&!k,isPaused:d.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:S&&k,isStale:oi(t,n),refetch:this.refetch,promise:p(this,et),isEnabled:Re(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let O=C.data!==void 0,T=C.status==="error"&&!O,E=U=>{T?U.reject(C.error):O&&U.resolve(C.data)},A=()=>{let U=P(this,et,C.promise=ir());E(U)},F=p(this,et);switch(F.status){case"pending":t.queryHash===r.queryHash&&E(F);break;case"fulfilled":(T||C.data!==F.value)&&A();break;case"rejected":(!T||C.error!==F.reason)&&A();break}}return C}updateResult(){let t=p(this,be),n=this.createResult(p(this,K),this.options);if(P(this,Ut,p(this,K).state),P(this,mn,this.options),p(this,Ut).data!==void 0&&P(this,hn,p(this,K)),an(n,t))return;P(this,be,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!p(this,yn).size)return!0;let o=new Set(i??p(this,yn));return this.options.throwOnError&&o.add("error"),Object.keys(p(this,be)).some(a=>{let c=a;return p(this,be)[c]!==t[c]&&o.has(c)})};q(this,B,Ho).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&q(this,B,ti).call(this)}},Ce=new WeakMap,K=new WeakMap,cr=new WeakMap,be=new WeakMap,Ut=new WeakMap,mn=new WeakMap,et=new WeakMap,ht=new WeakMap,ur=new WeakMap,gn=new WeakMap,hn=new WeakMap,Kt=new WeakMap,Lt=new WeakMap,yt=new WeakMap,yn=new WeakMap,B=new WeakSet,ar=function(t){q(this,B,si).call(this);let n=p(this,K).fetch(this.options,t);return t?.throwOnError||(n=n.catch(re)),n},Xs=function(){q(this,B,ni).call(this);let t=Le(this.options.staleTime,p(this,K));if(We.isServer()||p(this,be).isStale||!nr(t))return;let r=Ur(p(this,be).dataUpdatedAt,t)+1;P(this,Kt,Be.setTimeout(()=>{p(this,be).isStale||this.updateResult()},r))},Zs=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(p(this,K)):this.options.refetchInterval)??!1},ei=function(t){q(this,B,ri).call(this),P(this,yt,t),!(We.isServer()||Re(this.options.enabled,p(this,K))===!1||!nr(p(this,yt))||p(this,yt)===0)&&P(this,Lt,Be.setInterval(()=>{(this.options.refetchIntervalInBackground||on.isFocused())&&q(this,B,ar).call(this)},p(this,yt)))},ti=function(){q(this,B,Xs).call(this),q(this,B,ei).call(this,q(this,B,Zs).call(this))},ni=function(){p(this,Kt)!==void 0&&(Be.clearTimeout(p(this,Kt)),P(this,Kt,void 0))},ri=function(){p(this,Lt)!==void 0&&(Be.clearInterval(p(this,Lt)),P(this,Lt,void 0))},si=function(){let t=p(this,Ce).getQueryCache().build(p(this,Ce),this.options);if(t===p(this,K))return;let n=p(this,K);P(this,K,t),P(this,cr,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},Ho=function(t){V.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(p(this,be))}),p(this,Ce).getQueryCache().notify({query:p(this,K),type:"observerResultsUpdated"})})},Lo);function dd(e,t){return Re(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Uo(e,t){return dd(e,t)||e.state.data!==void 0&&ii(e,t,t.refetchOnMount)}function ii(e,t,n){if(Re(t.enabled,e)!==!1&&Le(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&oi(e,t)}return!1}function Ko(e,t,n,r){return(e!==t||Re(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&oi(e,n)}function oi(e,t){return Re(t.enabled,e)!==!1&&e.isStaleByTime(Le(t.staleTime,e))}function pd(e,t){return!an(e.getCurrentResult(),t)}function _n(e){return{onFetch:(t,n)=>{let r=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],o=t.state.data?.pageParams||[],a={pages:[],pageParams:[]},c=0,u=async()=>{let l=!1,d=m=>{Ao(m,()=>t.signal,()=>l=!0)},h=Hr(t.options,t.fetchOptions),f=async(m,v,g)=>{if(l)return Promise.reject();if(v==null&&m.pages.length)return Promise.resolve(m);let y=(()=>{let k={client:t.client,queryKey:t.queryKey,pageParam:v,direction:g?"backward":"forward",meta:t.options.meta};return d(k),k})(),_=await h(y),{maxPages:S}=t.options,x=g?To:Io;return{pages:x(m.pages,_,S),pageParams:x(m.pageParams,v,S)}};if(s&&i.length){let m=s==="backward",v=m?jo:ai,g={pages:i,pageParams:o},w=v(r,g);a=await f(g,w,m)}else{let m=e??i.length;do{let v=c===0?o[0]??r.initialPageParam:ai(r,a);if(c>0&&v==null)break;a=await f(a,v),c++}while(c<m)}return a};t.options.persister?t.fetchFn=()=>t.options.persister?.(u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=u}}}function ai(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 jo(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function Bo(e,t){return t?ai(e,t)!=null:!1}function Vo(e,t){return!t||!e.getPreviousPageParam?!1:jo(e,t)!=null}var ci=class extends lr{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:_n()})}getOptimisticResult(e){return e.behavior=_n(),super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){let{state:n}=e,r=super.createResult(e,t),{isFetching:s,isRefetching:i,isError:o,isRefetchError:a}=r,c=n.fetchMeta?.fetchMore?.direction,u=o&&c==="forward",l=s&&c==="forward",d=o&&c==="backward",h=s&&c==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Bo(t,n.data),hasPreviousPage:Vo(t,n.data),isFetchNextPageError:u,isFetchingNextPage:l,isFetchPreviousPageError:d,isFetchingPreviousPage:h,isRefetchError:a&&!u&&!d,isRefetching:i&&!l&&!h}}};var dr,$e,he,Ht,Ge,_t,Wo,$o=(Wo=class extends Vr{constructor(t){super();M(this,Ge);M(this,dr);M(this,$e);M(this,he);M(this,Ht);P(this,dr,t.client),this.mutationId=t.mutationId,P(this,he,t.mutationCache),P(this,$e,[]),this.state=t.state||ui(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){p(this,$e).includes(t)||(p(this,$e).push(t),this.clearGcTimeout(),p(this,he).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){P(this,$e,p(this,$e).filter(n=>n!==t)),this.scheduleGc(),p(this,he).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){p(this,$e).length||(this.state.status==="pending"?this.scheduleGc():p(this,he).remove(this))}continue(){return p(this,Ht)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{q(this,Ge,_t).call(this,{type:"continue"})},r={client:p(this,dr),meta:this.options.meta,mutationKey:this.options.mutationKey};P(this,Ht,Br({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(o,a)=>{q(this,Ge,_t).call(this,{type:"failed",failureCount:o,error:a})},onPause:()=>{q(this,Ge,_t).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>p(this,he).canRun(this)}));let s=this.state.status==="pending",i=!p(this,Ht).canStart();try{if(s)n();else{q(this,Ge,_t).call(this,{type:"pending",variables:t,isPaused:i}),p(this,he).config.onMutate&&await p(this,he).config.onMutate(t,this,r);let a=await this.options.onMutate?.(t,r);a!==this.state.context&&q(this,Ge,_t).call(this,{type:"pending",context:a,variables:t,isPaused:i})}let o=await p(this,Ht).start();return await p(this,he).config.onSuccess?.(o,t,this.state.context,this,r),await this.options.onSuccess?.(o,t,this.state.context,r),await p(this,he).config.onSettled?.(o,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(o,null,t,this.state.context,r),q(this,Ge,_t).call(this,{type:"success",data:o}),o}catch(o){try{await p(this,he).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 p(this,he).config.onSettled?.(void 0,o,this.state.variables,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onSettled?.(void 0,o,t,this.state.context,r)}catch(a){Promise.reject(a)}throw q(this,Ge,_t).call(this,{type:"error",error:o}),o}finally{p(this,he).runNext(this)}}},dr=new WeakMap,$e=new WeakMap,he=new WeakMap,Ht=new WeakMap,Ge=new WeakSet,_t=function(t){let n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),V.batch(()=>{p(this,$e).forEach(r=>{r.onMutationUpdate(t)}),p(this,he).notify({mutation:this,type:"updated",action:t})})},Wo);function ui(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var tt,He,pr,Go,zo=(Go=class extends ke{constructor(t={}){super();M(this,tt);M(this,He);M(this,pr);this.config=t,P(this,tt,new Set),P(this,He,new Map),P(this,pr,0)}build(t,n,r){let s=new $o({client:t,mutationCache:this,mutationId:++tr(this,pr)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){p(this,tt).add(t);let n=Wr(t);if(typeof n=="string"){let r=p(this,He).get(n);r?r.push(t):p(this,He).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(p(this,tt).delete(t)){let n=Wr(t);if(typeof n=="string"){let r=p(this,He).get(n);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&p(this,He).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=Wr(t);if(typeof n=="string"){let s=p(this,He).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"?p(this,He).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){V.batch(()=>{p(this,tt).forEach(t=>{this.notify({type:"removed",mutation:t})}),p(this,tt).clear(),p(this,He).clear()})}getAll(){return Array.from(p(this,tt))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Lr(n,r))}findAll(t={}){return this.getAll().filter(n=>Lr(t,n))}notify(t){V.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){let t=this.getAll().filter(n=>n.state.isPaused);return V.batch(()=>Promise.all(t.map(n=>n.continue().catch(re))))}},tt=new WeakMap,He=new WeakMap,pr=new WeakMap,Go);function Wr(e){return e.options.scope?.id}var nt,vt,Pe,rt,st,$r,li,Jo,di=(Jo=class extends ke{constructor(t,n){super();M(this,st);M(this,nt);M(this,vt);M(this,Pe);M(this,rt);P(this,nt,t),this.setOptions(n),this.bindMethods(),q(this,st,$r).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let n=this.options;this.options=p(this,nt).defaultMutationOptions(t),an(this.options,n)||p(this,nt).getMutationCache().notify({type:"observerOptionsUpdated",mutation:p(this,Pe),observer:this}),n?.mutationKey&&this.options.mutationKey&&Ve(n.mutationKey)!==Ve(this.options.mutationKey)?this.reset():p(this,Pe)?.state.status==="pending"&&p(this,Pe).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||p(this,Pe)?.removeObserver(this)}onMutationUpdate(t){q(this,st,$r).call(this),q(this,st,li).call(this,t)}getCurrentResult(){return p(this,vt)}reset(){p(this,Pe)?.removeObserver(this),P(this,Pe,void 0),q(this,st,$r).call(this),q(this,st,li).call(this)}mutate(t,n){return P(this,rt,n),p(this,Pe)?.removeObserver(this),P(this,Pe,p(this,nt).getMutationCache().build(p(this,nt),this.options)),p(this,Pe).addObserver(this),p(this,Pe).execute(t)}},nt=new WeakMap,vt=new WeakMap,Pe=new WeakMap,rt=new WeakMap,st=new WeakSet,$r=function(){let t=p(this,Pe)?.state??ui();P(this,vt,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},li=function(t){V.batch(()=>{if(p(this,rt)&&this.hasListeners()){let n=p(this,vt).variables,r=p(this,vt).context,s={client:p(this,nt),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{p(this,rt).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{p(this,rt).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{p(this,rt).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{p(this,rt).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(p(this,vt))})})},Jo);var ze,Yo,Xo=(Yo=class extends ke{constructor(t={}){super();M(this,ze);this.config=t,P(this,ze,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??rr(s,n),o=this.get(i);return o||(o=new Qo({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(o)),o}add(t){p(this,ze).has(t.queryHash)||(p(this,ze).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=p(this,ze).get(t.queryHash);n&&(t.destroy(),n===t&&p(this,ze).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){V.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return p(this,ze).get(t)}getAll(){return[...p(this,ze).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Kr(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>Kr(t,r)):n}notify(t){V.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){V.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){V.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},ze=new WeakMap,Yo);var se,bt,wt,vn,bn,St,wn,Sn,Zo,pi=(Zo=class{constructor(e={}){M(this,se);M(this,bt);M(this,wt);M(this,vn);M(this,bn);M(this,St);M(this,wn);M(this,Sn);P(this,se,e.queryCache||new Xo),P(this,bt,e.mutationCache||new zo),P(this,wt,e.defaultOptions||{}),P(this,vn,new Map),P(this,bn,new Map),P(this,St,0)}mount(){tr(this,St)._++,p(this,St)===1&&(P(this,wn,on.subscribe(async e=>{e&&(await this.resumePausedMutations(),p(this,se).onFocus())})),P(this,Sn,pn.subscribe(async e=>{e&&(await this.resumePausedMutations(),p(this,se).onOnline())})))}unmount(){var e,t;tr(this,St)._--,p(this,St)===0&&((e=p(this,wn))==null||e.call(this),P(this,wn,void 0),(t=p(this,Sn))==null||t.call(this),P(this,Sn,void 0))}isFetching(e){return p(this,se).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return p(this,bt).findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return p(this,se).get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=p(this,se).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Le(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return p(this,se).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=p(this,se).get(r.queryHash)?.state.data,o=Po(t,i);if(o!==void 0)return p(this,se).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return V.batch(()=>p(this,se).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return p(this,se).get(t.queryHash)?.state}removeQueries(e){let t=p(this,se);V.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=p(this,se);return V.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=V.batch(()=>p(this,se).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(re).catch(re)}invalidateQueries(e,t={}){return V.batch(()=>(p(this,se).findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=V.batch(()=>p(this,se).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(re)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(re)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=p(this,se).build(this,t);return n.isStaleByTime(Le(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(re).catch(re)}fetchInfiniteQuery(e){return e.behavior=_n(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(re).catch(re)}ensureInfiniteQueryData(e){return e.behavior=_n(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return pn.isOnline()?p(this,bt).resumePausedMutations():Promise.resolve()}getQueryCache(){return p(this,se)}getMutationCache(){return p(this,bt)}getDefaultOptions(){return p(this,wt)}setDefaultOptions(e){P(this,wt,e)}setQueryDefaults(e,t){p(this,vn).set(Ve(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...p(this,vn).values()],n={};return t.forEach(r=>{Ft(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){p(this,bn).set(Ve(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...p(this,bn).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={...p(this,wt).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=rr(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===cn&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...p(this,wt).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){p(this,se).clear(),p(this,bt).clear()}},se=new WeakMap,bt=new WeakMap,wt=new WeakMap,vn=new WeakMap,bn=new WeakMap,St=new WeakMap,wn=new WeakMap,Sn=new WeakMap,Zo);var xn=ne(fe(),1),ta=ne(Gr(),1),fi=xn.createContext(void 0),L=e=>{let t=xn.useContext(fi);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},fr=({client:e,children:t})=>(xn.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,ta.jsx)(fi.Provider,{value:e,children:t}));var zr=ne(fe(),1),na=zr.createContext(!1),ra=()=>zr.useContext(na),eg=na.Provider;var mr=ne(fe(),1),fd=ne(Gr(),1);function md(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var gd=mr.createContext(md()),sa=()=>mr.useContext(gd);var ia=ne(fe(),1);var oa=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?un(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},aa=e=>{ia.useEffect(()=>{e.clearReset()},[e])},ca=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||un(n,[e.error,r]));var ua=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))}},la=(e,t)=>e.isLoading&&e.isFetching&&!t,da=(e,t)=>e?.suspense&&t.isPending,mi=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var xt=ne(fe(),1);function Jr(e,t,n){let r=ra(),s=sa(),i=L(n),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let a=i.getQueryCache().get(o.queryHash);o._optimisticResults=r?"isRestoring":"optimistic",ua(o),oa(o,s,a),aa(s);let c=!i.getQueryCache().get(o.queryHash),[u]=xt.useState(()=>new t(i,o)),l=u.getOptimisticResult(o),d=!r&&e.subscribed!==!1;if(xt.useSyncExternalStore(xt.useCallback(h=>{let f=d?u.subscribe(V.batchCalls(h)):re;return u.updateResult(),f},[u,d]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),xt.useEffect(()=>{u.setOptions(o)},[o,u]),da(o,l))throw mi(o,u,s);if(ca({result:l,errorResetBoundary:s,throwOnError:o.throwOnError,query:a,suspense:o.suspense}))throw l.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(o,l),o.experimental_prefetchInRender&&!We.isServer()&&la(l,r)&&(c?mi(o,u,s):a?.promise)?.catch(re).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?l:u.trackResult(l)}function W(e,t){return Jr(e,lr,t)}var it=ne(fe(),1);function ie(e,t){let n=L(t),[r]=it.useState(()=>new di(n,e));it.useEffect(()=>{r.setOptions(e)},[r,e]);let s=it.useSyncExternalStore(it.useCallback(o=>r.subscribe(V.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=it.useCallback((o,a)=>{r.mutate(o,a).catch(re)},[r]);if(s.error&&un(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function Rn(e,t){return Jr(e,ci,t)}var ma=ne(fa(),1),Cn=typeof window<"u"&&window.__FSAOS_CONFIG__||{},jt=Array.isArray(Cn.sources)?Cn.sources:[],ot=Cn.hostSession===!0,hd=Cn.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",yd=Cn.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",Fe=Cn.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",$=(0,ma.createClient)(hd,yd,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var gr=null,Yr=0,ga,_i,Xr=!1;ga=new Promise(e=>{_i=e});$.auth.onAuthStateChange((e,t)=>{t?.access_token?(gr=t.access_token,Yr=t.expires_at??Math.floor(Date.now()/1e3)+3600):(gr=null,Yr=0),Xr||(Xr=!0,_i())});setTimeout(()=>{Xr||(Xr=!0,_i())},5e3);function ha(e,t){gr=e,Yr=t??Math.floor(Date.now()/1e3)+3600}function vi(){gr=null,Yr=0}async function at(){let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{};if(ot)return null;if(e.embedToken){if(typeof e.embedToken=="function")try{return await e.embedToken()??null}catch{return null}return e.embedToken}return await ga,gr}var Tn=null,An=null,ya=0,gi=new Set,bi,hr,Mn=!1;bi=new Promise(e=>{hr=e});function wi(){ya++,gi.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function kn(e){let t=typeof e=="string"?e:e.path,n=Tn!==t||An?.id!==(typeof e=="string"?void 0:e.id);Tn=t,An=typeof e=="string"?null:e,typeof e!="string"&&!Bt.some(r=>r.id===e.id)&&(Bt=[...Bt,e],Ci()),Mn||(Mn=!0,hr()),n&&wi()}function Rt(){return Tn}function ye(){return An}function Si(){return ya}function xi(e){return gi.add(e),()=>{gi.delete(e)}}function yr(){return bi}function Ri(){return Mn}var Zr=null;function Vt(e,t={}){if(Zr){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}Zr=e,t.activate!==!1&&kn(e)}function we(){return Zr}var Bt=[],hi=new Set,_a=0;function Ci(){_a++,hi.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function qe(){return Bt}function _r(){return _a}function es(e){return hi.add(e),()=>{hi.delete(e)}}function va(e,t){let n=JSON.stringify(Bt)!==JSON.stringify(e),r=Tn!==t.path||An?.id!==t.id;Bt=e,Tn=t.path,An=t,Mn||(Mn=!0,hr()),n&&Ci(),r&&wi()}var En=null,Pn=null,In=0,yi=new Set,ba=0;function wa(){ba++,yi.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Session listener error:",t)}})}function Z(){return In}function Pi(){return ba}function Sa(e){return yi.add(e),()=>{yi.delete(e)}}async function ct(){if(En)return En;if(Pn)return Pn;let e=In;return Pn=(async()=>{let t=Wt(),n=await at();if(e!==In)throw new Error("Session changed during initialization");let r={};n&&(r.Authorization=`Bearer ${n}`);let s=await fetch(`${Fe}/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!==In)throw new Error("Session changed during initialization");let o=i.entry||i;return En={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},wa(),En})().catch(t=>{throw e===In&&(Pn=null),t}),Pn}function Ct(){return En}function Ei(){In++,En=null,Pn=null,Tn=null,An=null,Zr=null,Bt=[],wa()}var xa=[];function oe(e){xa.push(e)}function On(){Ei(),vi(),hr(),Mn=!1,bi=new Promise(e=>{hr=e}),wi(),Ci();for(let e of xa)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function Wt(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var Ra=kn,z=Rt,G=Si,Ie=xi,Ca=yr,ts=Ri;var Gt="host-session",_d=5e3;function Ii(e){return typeof e=="object"&&e!==null&&e.fsaos===Gt&&typeof e.kind=="string"}var $t=class extends Error{constructor(){super(...arguments);X(this,"name","HostSessionUnavailableError")}},ns=null,vd=0,rs=new Map;function Pa(){return ns||(ns=new Promise((e,t)=>{if(!ot){t(new $t("This page was not started with hostSession."));return}if(typeof window>"u"||!window.parent||window.parent===window){t(new $t("This page is signed in only inside the app that frames it. Open it from there."));return}let n=window.parent,r=null,s=setTimeout(()=>{r===null&&(window.removeEventListener("message",i),t(new $t("The window around this page did not sign it in. Open it from the app that owns it.")))},_d);function i(o){if(o.source!==n||!Ii(o.data))return;let a=o.data;if(r===null){if(a.kind!=="welcome")return;r=o.origin,clearTimeout(s),a.anchor&&kn(a.anchor),e({host:n,origin:r,item:a.item??null});return}if(o.origin!==r||a.kind!=="result")return;let c=rs.get(a.id);c&&(rs.delete(a.id),c.resolve(a.ok?{ok:!0,response:a.response}:{ok:!1,error:a.error}))}window.addEventListener("message",i),n.postMessage({fsaos:Gt,kind:"hello"},"*")}),ns)}async function Ea(){let{item:e}=await Pa();return{item:e}}async function Ia(e,t,n){if(n?.aborted)throw new DOMException("Read cancelled","AbortError");let{host:r,origin:s}=await Pa();if(n?.aborted)throw new DOMException("Read cancelled","AbortError");let i=JSON.parse(JSON.stringify(t??{}));return new Promise((o,a)=>{let c=`${Date.now().toString(36)}-${(++vd).toString(36)}`,u=()=>{rs.delete(c),a(new DOMException("Read cancelled","AbortError"))};rs.set(c,{resolve:l=>{n?.removeEventListener("abort",u),o(l)}}),n?.addEventListener("abort",u,{once:!0}),r.postMessage({fsaos:Gt,kind:"call",id:c,method:e,params:i},s)})}var Ti=0,Ta=!1,Aa=0;function Ai(e){if(typeof e!="string")return;let t=Date.parse(e);Number.isNaN(t)||(Ti=t-Date.now(),Ta=!0,Aa=Date.now())}function ss(){return Date.now()+Ti}function Ma(){return Ta}function ka(){return Ti}function Oa(){return Aa}function Fa(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:ss()>=t}function qa(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Math.max(0,t-ss())}var Fn,Ne=new Map,zt=[],Mi=0,ki={foreground:0,normal:1,background:2},is=()=>performance.now(),Oi=()=>new DOMException("Read cancelled","AbortError");function Qa(e={}){Fn={concurrency:Math.max(1,Math.min(16,Math.floor(e.concurrency??6))),timeoutMs:Math.max(1e3,e.timeoutMs??15e3),onTiming:e.onTiming},as()}function Da(){for(let e of Ne.values()){e.controller.abort();for(let t of e.consumers)t.detach(),t.reject(Oi());e.consumers.clear(),e.timer&&clearTimeout(e.timer)}Ne.clear(),zt.length=0}function Ua(e,t){return e==="query"?!("materialize"in t):["read","list","search","resolve","resolve-items","get-channel-messages","list-memberships","message-replies"].includes(e)}function os(e){return Array.isArray(e)?`[${e.map(os).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${os(n)}`).join(",")}}`:JSON.stringify(e)}function Ka(e,t,n,r){if(n.signal?.aborted)return Promise.reject(Oi());if(!Fn)return r(n.signal);let s=Ne.get(e);if(s)ki[n.priority??"normal"]<ki[s.priority]&&(s.priority=n.priority??"normal");else{s={key:e,method:t,priority:n.priority??"normal",queuedAt:is(),controller:new AbortController,consumers:new Set,run:r},Ne.set(e,s),zt.push(s);let a=s;s.timer=setTimeout(()=>{a.controller.abort();let c=new Error("The read timed out. Please retry.");c.name="TimeoutError";for(let u of a.consumers)u.detach(),u.reject(c);a.consumers.clear(),Ne.get(a.key)===a&&Ne.delete(a.key),Na(a)},Fn.timeoutMs)}let i=s,o=new Promise((a,c)=>{let u=()=>{l.detach(),i.consumers.delete(l),c(Oi()),i.consumers.size||(i.controller.abort(),Ne.get(i.key)===i&&Ne.delete(i.key),Na(i))},l={resolve:d=>a(structuredClone(d)),reject:c,detach:()=>n.signal?.removeEventListener("abort",u)};i.consumers.add(l),n.signal?.addEventListener("abort",u,{once:!0})});return as(),o}function Na(e){let t=zt.indexOf(e);t>=0&&(zt.splice(t,1),Ne.get(e.key)===e&&Ne.delete(e.key),e.timer&&clearTimeout(e.timer)),as()}function as(){if(Fn)for(;Mi<Fn.concurrency&&zt.length;){let e=r=>ki[r.priority]-Math.floor((is()-r.queuedAt)/2e3);zt.sort((r,s)=>e(r)-e(s)||r.queuedAt-s.queuedAt);let t=zt.shift();if(!t.consumers.size)continue;Mi++,t.startedAt=is();let n="success";Promise.resolve().then(()=>t.run(t.controller.signal)).then(r=>{for(let s of t.consumers)s.detach(),s.resolve(r)},r=>{n=t.controller.signal.aborted?"aborted":"error";for(let s of t.consumers)s.detach(),s.reject(r)}).finally(()=>{t.timer&&clearTimeout(t.timer),t.consumers.clear(),Ne.get(t.key)===t&&Ne.delete(t.key),Mi--;try{Fn?.onTiming?.({method:t.method,priority:t.priority,queueMs:Math.round(t.startedAt-t.queuedAt),requestMs:Math.round(is()-t.startedAt),outcome:n})}catch{}as()})}}oe(Da);var bd=new Set(["list-memberships","init"]),Se=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);X(this,"name","GatewayRequestError");X(this,"method");X(this,"status");X(this,"statusText");X(this,"payload");X(this,"responseBody");this.method=n.method,this.status=n.status,this.statusText=n.statusText,this.payload=n.payload,this.responseBody=n.responseBody}};async function R(e,t={},n={}){if(ot)return wd(e,t,n);let r=Z(),s=Rt(),i=Wt(),o=`${Fe}/d/${i}`,a={"Content-Type":"application/json"},c=await La(at(),n.signal);if(r!==Z())throw new Error("Session changed before gateway request");if(c&&(a.Authorization=`Bearer ${c}`),!bd.has(e)&&!t._scope_path&&await La(yr(),n.signal),r!==Z())throw new Error("Session changed before gateway request");let u={...t},l=Ct();!u.domain_scope_id&&l?.scope_id&&(u.domain_scope_id=l.scope_id);let d=s??Rt();!u._scope_path&&d&&(u._scope_path=d);let h=async f=>{if(r!==Z())throw new Error("Session changed before queued gateway request");let m=await fetch(o,{method:"POST",signal:f,headers:a,body:JSON.stringify({method:e,params:u})}),v=await m.text();if(r!==Z())throw new Error("Session changed during gateway request");let g=null;if(v)try{g=JSON.parse(v)}catch{}if(!m.ok||!g)throw new Se({method:e,status:m.status,statusText:m.statusText,payload:g,responseBody:v});if(g.success===!1){let w=g.error||"",y=g.denied_by||g.error_type||"";throw y==="rule"||y==="access"||y==="entitlement"||w==="RULE_DENIED"||w==="ACCESS_DENIED"||w==="PERMISSION_DENIED"||w==="ENTITLEMENT_REQUIRED"?new Ke(g):new Se({method:e,status:m.status,statusText:m.statusText,payload:g,responseBody:v})}return g&&g.server_now!==void 0&&Ai(g.server_now),g};return Ua(e,u)?Ka(os([r,i,c,e,u]),e,n,h):h(n.signal)}async function wd(e,t,n){let r=await Ia(e,t,n.signal);if(r.ok){let o=r.response?.server_now;return o!==void 0&&Ai(o),r.response}let s=r.error;if(s.kind==="denied")throw new Ke(s.payload);if(s.kind==="gateway")throw new Se({method:s.method,status:s.status,statusText:s.statusText,payload:s.payload,responseBody:s.responseBody});let i=new Error(s.message);throw i.name=s.name,i}function La(e,t){return t?t.aborted?Promise.reject(new DOMException("Read cancelled","AbortError")):new Promise((n,r)=>{let s=()=>r(new DOMException("Read cancelled","AbortError"));t.addEventListener("abort",s,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",s))}):e}var b=ne(fe(),1),pp=ne(ja(),1),fp=ne(Gr(),1);var Ba=new WeakMap;function le(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(d=>d.promise?[d.promise]:[]);if(i.length===0)return s();let o=`${r?"=":"^"}${JSON.stringify(t)}`,a=Ba.get(e);a||(a=new Map,Ba.set(e,a));let c=a.get(o);if(c)return c;let u=a,l=Promise.allSettled(i).then(()=>(u.delete(o),s()));return u.set(o,l),l}function de(e,t){return typeof e=="string"&&(e===t||e.startsWith(`${t}/`))}var cs=new WeakMap,Va=e=>e.meta?.arrangementRealtime===!0;function ut(e,t){let n=e.getQueryCache().find({queryKey:t,exact:!0});if(!n)return;let r=cs.get(e);r||(r=new Map,cs.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&&le(e,t,{exact:!0})},250))}function Wa(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){if(!Va(n))continue;let r=n.state.data;if(n.meta?.personalSections===!0){(r?.item_path&&[t.path,t.old_path].some(i=>typeof i=="string"&&(i===r.item_path||i.startsWith(r.item_path+"/")))||r?.sections?.some(i=>i.entries?.some(o=>o.target?.id===t.item_id))||!r?.item_id&&t.item_type==="item_arrangement"&&t.name==="sidebar-sections")&&ut(e,n.queryKey);continue}if(!r?.item_id)continue;let s=(i,o)=>!!(i&&t.item_id===i||o&&(t.path===o||t.old_path===o));(s(r.item_id,r.item_path)||t.parent_id===r.item_id||t.old_parent_id===r.item_id||[t.path,t.old_path].some(i=>typeof i=="string"&&i.slice(0,i.lastIndexOf("/"))===r.item_path)||r.resolved_children?.some(i=>s(i.id,i.symlink_path||i.path)||i.target&&s(i.target.id,i.target.path)))&&ut(e,n.queryKey)}}function $a(e){for(let t of e.getQueryCache().getAll())Va(t)&&t.state.data!==void 0&&ut(e,t.queryKey)}function Ga(e){cs.get(e)?.forEach(clearTimeout),cs.delete(e)}var lt=null;oe(()=>{lt&&(lt.cancelQueries({queryKey:["vfs"]}),lt.removeQueries({queryKey:["vfs"]}))});function za(e){if(lt&&lt!==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.");lt=e}function Q(){return lt||(lt=new pi({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),lt}var Ja=new Proxy({},{get(e,t,n){let r=Q(),s=r[t];return typeof s=="function"?s.bind(r):s}});var us=new WeakMap;function Fi(e){return e.meta?.infiniteItemsRealtime?.filter}function Sd(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 xd(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 Rd(e,t,n){if(Sd(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&&!de(n.path,r)&&!de(n.old_path,r))return!1;if(n.item_type==="symlink"&&s&&i)return!0;let o=xd(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 Ya(e,t){let n=us.get(e);n||(n=new Map,us.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||!Fi(t))&&le(e,t.queryKey,{exact:!0})},500))}function Xa(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){let r=Fi(n);r&&Rd(n,r,t)&&Ya(e,n)}}function Za(e){for(let t of e.getQueryCache().getAll())Fi(t)&&t.state.data!==void 0&&Ya(e,t)}function ec(e){us.get(e)?.forEach(clearTimeout),us.delete(e)}var ls=class extends Error{constructor(){super("The server did not confirm the selected-Space listing contract")}};function tc(e,t){if(!Array.isArray(t)||t.some(n=>typeof n!="string")||JSON.stringify([...new Set(t)].sort())!==JSON.stringify(e))throw new ls}function Pt(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 qn(e){return e instanceof ls||e instanceof Ke||e instanceof Se&&(e.payload?.error==="SPACE_SELECTION_UNAVAILABLE"||e.payload?.error==="QUERY_PARAMS_INVALID"||e.status===401||e.status===403)}function ae(){return z()??"__unscoped__"}var I={all:()=>["vfs",ae()],item:e=>["vfs",ae(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",ae(),"children",e],allChildren:()=>["vfs",ae(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",ae(),"search",e,...t??[]],items:(e,t)=>["vfs",ae(),"items",e,JSON.stringify(Pt(t??{}))],allItems:()=>["vfs",ae(),"items"],tree:(e,t)=>["vfs",ae(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",ae(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",ae(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",ae(),"get-activity-feed",e,t,n],itemVersions:(e,t,n,r)=>["vfs","item-versions",e,t,n,r],itemHistory:(e,t,n)=>["vfs","item-history",e,t,n],channelMessages:(e,t)=>["vfs",ae(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",ae(),"channel-messages"],channels:e=>["vfs",ae(),"channels",e??"all"],messageReplies:(e,t,n,r=25)=>["vfs",ae(),"channel-messages",e,n??"__top__","contextual-replies",t,r],allChannels:()=>["vfs",ae(),"channels"],notifications:(e,t)=>["vfs",ae(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",ae(),"notifications"],unreadCounts:()=>["vfs",ae(),"unread-counts"],memberships:e=>["memberships",e]};var Cd=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function ee(...e){Cd&&console.log("[WS]",...e)}var D=null,Nn=null,Dn=null,vr=0,Pd=3e4,nc=1e4,Kn=!1,rc=!1,cc=3e4,Ed=cc*2+5e3,ds=0,ps=null,sc=!1;function Id(){wr(),ds=Date.now(),ps=setInterval(()=>{if(D&&D.readyState===WebSocket.OPEN&&Date.now()-ds>Ed){ee("ping: no inbound traffic for",Date.now()-ds,"ms \u2014 closing half-open socket");try{D.close(4e3,"liveness timeout")}catch{}return}pt({type:"ping"})},cc)}function wr(){ps&&(clearInterval(ps),ps=null)}function Td(){typeof document>"u"||(document.hidden?wr():br()&&(ee("Tab visible, reconnecting..."),Jt()))}function Ad(){sc||typeof document>"u"||(document.addEventListener("visibilitychange",Td),sc=!0)}var Te={};function Ni(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return!n||!r?n===r:r===n||r.startsWith(`${n}/`)}var Un=[],dt=new Map,Qn=new Map,Qe=new Map;function Md(e){let t=Qn.get(e);return t?Array.from(new Set(Array.from(t.values()).flatMap(n=>n.event_types))).sort():[]}function ic(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):!1}function oc(e){let t=Md(e);if(t.length===0)return dt.delete(e),null;let n={scope_id:e,event_types:t};return dt.set(e,n),n}var Je=new Map,Et=new Map,qi="disconnected",fs=[];function ms(e){if(qi!==e){qi=e;for(let t of[...fs])try{t(e)}catch{}}}function kd(e){Je.set(e,"ready");let t=Et.get(e);if(t){Et.delete(e);for(let n of t)n()}}function Od(){for(let e of Je.keys())Je.set(e,"disconnected")}function Qi(e,t){Je.set(e,"pending"),pt({type:"subscribe_path",path:e,event_types:t})}function Fd(){return Object.keys(Te).some(t=>Te[t]&&Te[t].length>0)||Un.length>0}function br(){return dt.size>0||Qe.size>0}async function Jt(){if(ot){ee("ensureConnection: the host holds the session, no realtime connection");return}if(!br()){ee("ensureConnection: no active subscriptions, skipping");return}if(D&&D.readyState===WebSocket.OPEN){ee("ensureConnection: already open");return}if(Nn)return ee("ensureConnection: connection already in flight, waiting..."),Nn;if(D){ee("ensureConnection: killing stale WS in state",D.readyState);try{D.close()}catch{}D=null}return Kn=!1,Nn=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=Fe,n=await at();if(!n){ee("ensureConnection: no token available, will retry"),ac();return}let r=t.startsWith("https")?"wss":"ws",s=t.replace(/^https?:\/\//,""),i=`${r}://${s}/ws`;i+=`?token=${encodeURIComponent(n)}`,ee("ensureConnection: opening WS to",i.substring(0,50)+"..."),ms("connecting"),D=new WebSocket(i);let o=D;await new Promise((a,c)=>{if(!D)return c(new Error("WebSocket not created"));let u=setTimeout(()=>{if(D===o){if(ee("ensureConnection: TIMEOUT after",nc,"ms"),D&&D.readyState!==WebSocket.OPEN){try{D.close()}catch{}D=null}c(new Error("WebSocket connection timeout"))}},nc);o.onopen=()=>{if(D!==o)return;clearTimeout(u),ee("ensureConnection: CONNECTED");let l=rc;rc=!0,vr=0,ms("connected"),qd(l),(typeof document>"u"||!document.hidden)&&Id(),Ad(),a()},o.onmessage=l=>{D===o&&Nd(l.data)},o.onerror=()=>{ee("ensureConnection: WS error event")},o.onclose=l=>{clearTimeout(u),D===o&&(ee("ensureConnection: WS closed, code:",l.code,"reason:",l.reason),D=null,wr(),Od(),ms("disconnected"),!Kn&&br()&&ac(),c(new Error(`WebSocket closed: ${l.code}`)))}})}catch(e){ee("ensureConnection: failed -",e?.message||e)}finally{Nn=null}})(),Nn}function ac(){if(Dn||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,vr)+Math.random()*1e3,Pd);vr++,ee("scheduleReconnect: attempt",vr,"in",Math.round(e),"ms"),Dn=setTimeout(()=>{Dn=null,br()&&Jt()},e)}function qd(e=!1){for(let t of dt.values())ee("resubscribeAll: scope",t.scope_id),pt({type:"subscribe",scope_id:t.scope_id,event_types:t.event_types});for(let t of Qe.values())ee("resubscribeAll: path",t.path),Qi(t.path,t.event_types);e&&uc("reconnect")}function uc(e){try{let t=Q();Za(t),$a(t);for(let n of Qe.values())t.invalidateQueries({queryKey:I.item(n.path)}),t.invalidateQueries({queryKey:I.children(n.path)});t.invalidateQueries({queryKey:I.allChannelMessages()}),ee("catchUpAfterGap:",e,"- invalidated",Qe.size,"paths and the transcripts on screen")}catch(t){ee("catchUpAfterGap: cache invalidation skipped",t)}}function pt(e){D&&D.readyState===WebSocket.OPEN&&D.send(JSON.stringify(e))}function Nd(e){ds=Date.now();try{let t=JSON.parse(e);if(t.type==="subscribed_path"){typeof t.path=="string"&&kd(t.path);return}if(t.type==="subscribed"||t.type==="unsubscribed"||t.type==="unsubscribed_path"||t.type==="pong")return;if(t.type==="error"){console.warn("[WS] Server error:",t.message);return}if(t.type==="resync"){uc(typeof t.reason=="string"?t.reason:"resync");return}if(t.type==="event"||t.event_type){let n=t.event_type||"message",r=t.data||t;if(n==="vfs_change"&&(Xa(Q(),r),Wa(Q(),r)),typeof r.path=="string")for(let[s,i]of Object.entries(Te))s!=="*"&&Ni(s,r.path)&&i.forEach(o=>o(r));Te["*"]&&Te["*"].forEach(s=>s(r));for(let s of Un)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function Di(){!Fd()&&dt.size===0&&Qe.size===0&&D&&(Kn=!0,wr(),D.close(),D=null,Kn=!1)}function gs(e,t){return Te[e]||(Te[e]=[]),Te[e].push(t),Qe.has(e)||(Qe.set(e,{path:e,event_types:["token_stream"]}),D&&D.readyState===WebSocket.OPEN?Qi(e,["token_stream"]):Je.set(e,"pending")),Jt(),()=>{let n=Te[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete Te[e],Qe.delete(e),Je.delete(e),Et.delete(e),pt({type:"unsubscribe_path",path:e}))}Di()}}function J(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return Un.push(...s),br()&&Jt(),()=>{for(let i of s){let o=Un.indexOf(i);o!==-1&&Un.splice(o,1)}Di()}}function Ln(e,t=["vfs_change","ccm_change"]){let n=Symbol(e),r=Array.from(new Set(t)).sort();if(r.length===0)return()=>{};let s=Qn.get(e)??new Map,i=dt.get(e)?.event_types;s.set(n,{event_types:r}),Qn.set(e,s);let o=oc(e);if(!o)return()=>{};ee("subscribeToScope:",e,o.event_types),D&&D.readyState===WebSocket.OPEN&&!ic(i,o.event_types)&&pt({type:"subscribe",scope_id:e,event_types:o.event_types}),Jt();let a=!0;return()=>{if(!a)return;a=!1;let c=Qn.get(e);if(!c?.delete(n))return;let u=dt.get(e)?.event_types;if(c.size===0)Qn.delete(e),dt.delete(e),pt({type:"unsubscribe",scope_id:e});else{let l=oc(e);l&&D&&D.readyState===WebSocket.OPEN&&!ic(u,l.event_types)&&pt({type:"subscribe",scope_id:e,event_types:l.event_types})}Di()}}function lc(e,t,n={}){pt({type:"emit",scope_id:e,event_type:t,payload:n})}function Ui(){ee("disconnectSSE: tearing down"),ec(Q()),Ga(Q()),Kn=!0,wr(),D&&(D.close(),D=null),Dn&&(clearTimeout(Dn),Dn=null),Nn=null,Kn=!1,vr=0;for(let e of Object.keys(Te))delete Te[e];Un.length=0,dt.clear(),Qn.clear(),Qe.clear(),Je.clear(),Et.clear(),ms("disconnected")}function dc(){pt({type:"ping"})}function pc(e){return Qe.has(e)?Je.get(e)??"pending":"unsubscribed"}function fc(e,t=5e3){return!Qe.has(e)||ot?Promise.resolve(!1):Je.get(e)==="ready"&&D&&D.readyState===WebSocket.OPEN?Promise.resolve(!0):(Jt(),new Promise(n=>{let r=!1,s=Et.get(e)??[],i=()=>{r||(r=!0,clearTimeout(o),n(!0))};s.push(i),Et.set(e,s);let o=setTimeout(()=>{if(r)return;r=!0;let a=Et.get(e);if(a){let c=a.indexOf(i);c!==-1&&a.splice(c,1),a.length===0&&Et.delete(e)}n(!1)},t)}))}function mc(e){let t=Qe.get(e);if(!t){ee("resubscribePath: no active subscription for",e);return}D&&D.readyState===WebSocket.OPEN?(ee("resubscribePath: re-sending frame for",e),Qi(t.path,t.event_types)):(Je.set(e,"pending"),Jt())}function hs(e){fs.push(e);try{e(qi)}catch{}return()=>{let t=fs.indexOf(e);t!==-1&&fs.splice(t,1)}}oe(Ui);function gc(){return new Date().toISOString()}function hc(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function De(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||gc(),updated_at:e.updated_at||gc(),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 Sr(e){return(e.content?.items||e.items||[]).map(De)}async function xr(e){try{let t=await R("read",{id:e});if(t.item_name||t.item_path){let r=De(t);return r.path&&Q().setQueryData(I.item(r.path),r),r}let n=t.item;if(n){let r=De(n);return r.path&&Q().setQueryData(I.item(r.path),r),r}return null}catch{return null}}async function Rr(e){try{let t=await R("read",{path:e});if(t.item_name||t.item_path)return De(t);let n=t.item;return n?De(n):null}catch{return null}}async function Cr(e){try{let t=await R("list",{path:e,limit:200}),n=Sr(t);for(let r of n)Q().setQueryData(I.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function yc(e,t){let{items:n}=await Yt({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 _s(e,t,n){try{let r=await R("list",{path:e,limit:t,offset:n}),s=Sr(r);for(let i of s)Q().setQueryData(I.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 vs(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 bs(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||hc(),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||hc(),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 ws(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=Sr(i);for(let a of o)Q().setQueryData(I.item(a.path),a);return o}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function Ss(e,t=50,n=0){try{let r=await R("get-activity-feed",{scope_path:e,limit:t,offset:n});return r.content?.items||r.items||r.entries||[]}catch(r){return console.error(`[gateway] Failed to fetch recent activity for ${e}:`,r),[]}}async function Pr(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 xs(e,t=50,n=0){return Pr(e,{limit:t,offset:n})}async function Rs(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=Sr(s);for(let o of i)Q().setQueryData(I.item(o.path),o);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${e}:`,r),[]}}async function Er(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 jn(e){return!!e&&(!!e.type||Array.isArray(e.any_of)&&e.any_of.length>0)}function Qd(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 Dd=["catalog","parent_only","internal"];function _c(e,t={}){if(!e||typeof e!="object")return null;let n=o=>typeof o=="string"||typeof o=="number"||typeof o=="boolean",r=o=>{let a={},c={};for(let[u,l]of Object.entries(o))u.startsWith("field.")&&u.length>6&&n(l)?a[u.slice(6)]=l:u.startsWith("field_in.")&&u.length>9&&Array.isArray(l)&&(c[u.slice(9)]=l.filter(n));return{fields:a,field_in:c}},s={};typeof e.type=="string"&&e.type&&(s.type=e.type),typeof e.sort_by=="string"&&(s.sort_by=e.sort_by),(e.sort_dir==="asc"||e.sort_dir==="desc")&&(s.sort_dir=e.sort_dir),typeof e.name=="string"&&e.name&&(s.name=e.name),typeof e.tag=="string"&&e.tag&&(s.tag=e.tag),typeof e.discovery=="string"&&Dd.includes(e.discovery)&&(s.discovery=e.discovery);let i=r(e);if(Object.keys(i.fields).length&&(s.fields=i.fields),Object.keys(i.field_in).length&&(s.field_in=i.field_in),Array.isArray(e.any_of)){let o=[];for(let a of e.any_of){if(!a||typeof a!="object"||Array.isArray(a))continue;let c=a,u={};typeof c.item_type=="string"&&c.item_type&&(u.item_type=c.item_type);let l=r(c);Object.keys(l.fields).length&&(u.fields=l.fields),Object.keys(l.field_in).length&&(u.field_in=l.field_in),Object.keys(u).length&&o.push(u)}o.length&&(s.any_of=o)}return jn(s)?{...s,...t}:null}async function Yt(e,t={}){if(e=Pt(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(Qd)),Object.keys(r).length>0&&(n.filters=r),e.limit!=null&&(n.limit=e.limit);try{let s=await R("query",n,t);e.spaceIds!==void 0&&tc(e.spaceIds,s.selected_space_ids??s.content?.selected_space_ids);let i=Sr(s);for(let o of i)Q().setQueryData(I.item(o.path),o);return{items:i,total_hint:s.total??s.content?.total??i.length}}catch(s){if(t.signal?.aborted||s instanceof Error&&s.name==="AbortError"||(console.error(`[gateway] Failed to fetch items of type ${e.type??"(any_of)"}:`,s),t.throwOnError||e.spaceIds!==void 0))throw s;return{items:[],total_hint:0}}}function vc(e){if(!e||typeof e!="object")return;let t=e;if(t.state==="unavailable")return{state:"unavailable"};if(!(t.state!=="available"||typeof t.message_id!="string"||typeof t.path!="string"||typeof t.excerpt!="string"))return{state:"available",message_id:t.message_id,path:t.path,role:typeof t.role=="string"?t.role:void 0,sender_principal_id:typeof t.sender_principal_id=="string"?t.sender_principal_id:void 0,sender_display_name:typeof t.sender_display_name=="string"?t.sender_display_name:void 0,excerpt:t.excerpt,truncated:t.truncated===!0}}async function bc(e){if(!e.channel_id&&!e.channel_path)throw new Error("A message requires a channel.");let t=e.reply_to_message_id!==void 0;if(t&&(typeof e.reply_to_message_id!="string"||!e.reply_to_message_id.trim()))throw new Error("A contextual reply requires a target message ID.");if(t&&(e.conversation_mode==="new_thread"||e.hand_off_to))throw new Error("A contextual reply stays in the current conversation.");return await R(t?"reply-message":"send-message",e)}async function wc(e,t){let n=new Set(e),r=[...n];if(!r.length)return{};if(r.length>200)throw new Error("Reply context supports at most 200 messages per batch.");let i=(await R("message-replies",{operation:"context",message_ids:r},t)).replies;if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid reply-context response.");return Object.fromEntries(Object.entries(i).flatMap(([o,a])=>{let c=vc(a);return c&&n.has(o)?[[o,c]]:[]}))}async function Cs(e,t={},n){let r=t.limit??25;if(!Number.isInteger(r)||r<1||r>100)throw new Error("Reply page size must be between 1 and 100.");let s=await R("message-replies",{operation:"list",message_id:e,limit:r,...t.cursor?{cursor:t.cursor}:{},...t.conversationRootId?{conversation_root_id:t.conversationRootId}:{}},n);if(!Array.isArray(s.messages))throw new Error("Invalid reply-list response.");let i=s.next_cursor;if(i&&(typeof i.updated_at!="string"||typeof i.edge_id!="string"))throw new Error("Invalid reply-list cursor.");let o=new Map(Hn(s.messages).map(a=>[a.id,a]));return{messages:s.messages.flatMap(a=>{let c=o.get(a.id);return c?[c]:[]}),next_cursor:i??null}}function Ud(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 Sc(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:Ud(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 Hn(e){return e.filter(t=>t.item_type==="message").map(t=>{let n=t.type_data||{},r="user";n.role==="assistant"?r="assistant":n.role==="system"&&(r="system");let s=n.metadata||{};return{id:t.id||"",path:t.path||"",content:n.message||n.content||"",created_at:t.created_at||"",role:r,status:typeof n.status=="string"?n.status:void 0,delivery_state:typeof n.delivery_state=="string"?n.delivery_state:void 0,cognition_event_id:typeof n.cognition_event_id=="string"?n.cognition_event_id:void 0,seq:n.seq||0,principal_id:n.principal_id,member_id:typeof n.member_id=="string"?n.member_id:void 0,sender_display_name:typeof n.sender_display_name=="string"?n.sender_display_name:void 0,sender_is_ai:typeof n.sender_is_ai=="boolean"?n.sender_is_ai:void 0,sender_role_display_name:typeof n.sender_role_display_name=="string"?n.sender_role_display_name:void 0,reply_count:n.reply_count||0,member_count:n.member_count||0,parent_message_id:n.parent_message_id,reply_to:vc(t.reply_to),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 xc(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 Hn(i)}catch(n){throw console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),n}}async function Ps(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await R("get-channel-messages",n),i=s.messages||[],o=Hn(i),a=Sc(i),c=new Map,u=[];for(let l of a)if(l.parentMessagePath){let d=c.get(l.parentMessagePath)||[];d.push(l),c.set(l.parentMessagePath,d)}else u.push(l);return{messages:o,activityMessages:Hn(s.activity_messages||[]),messageCards:c,siblingCards:u,mode:s.mode||"top_level"}}catch(n){throw console.error(`[gateway] Failed to fetch channel messages with cards for ${e}:`,n),n}}async function Xt(e,t){try{let n={channel_path:e};t?.parentMessageId&&(n.parent_message_id=t.parentMessageId),t?.conversationsOnly&&(n.conversations_only=!0),t?.transcriptOnly&&(n.transcript_only=!0),t?.limit&&(n.limit=t.limit),t?.before_seq!=null&&(n.before_seq=t.before_seq),t?.after_seq!=null&&(n.after_seq=t.after_seq);let s=await R("get-channel-messages",n);if(t?.conversationsOnly&&s.conversations_only!==!0)throw new Error("This server does not support conversation history lists yet. Update the message reader.");if(t?.transcriptOnly&&s.transcript_only!==!0)throw new Error("This server does not support channel transcript pages yet. Update the message reader.");let i=s.messages||[],o=Sc(i),a=new Map,c=[];for(let u of o)if(u.parentMessagePath){let l=a.get(u.parentMessagePath)||[];l.push(u),a.set(u.parentMessagePath,l)}else c.push(u);return{messages:Hn(i),activityMessages:Hn(s.activity_messages||[]),messageCards:a,siblingCards:c,mode:s.mode||"top_level"}}catch(n){throw console.error(`[gateway] Failed to fetch channel messages page for ${e}:`,n),n}}function ys(e){Q().invalidateQueries({queryKey:I.children(e)})}function Ki(e){Q().invalidateQueries({queryKey:I.item(e)})}function Rc(e,t){Ki(e),ys(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&ys(r)}function Cc(e){let t=e+"/";Q().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function Pc(){Q().invalidateQueries({queryKey:I.all()})}function Ec(e){Q().invalidateQueries({queryKey:I.types(e)})}function Ic(e,t){e?Q().invalidateQueries({queryKey:I.channelMessages(e,t)}):Q().invalidateQueries({queryKey:I.allChannelMessages()})}function Tc(e,t){e&&t?Q().invalidateQueries({queryKey:I.openEnvelope(e,t)}):e?Q().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):Q().invalidateQueries({queryKey:I.allOpenEnvelopes()})}function Ye(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}async function Es(){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,invitationAccepted:n.invitation_accepted===!0,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,Tr=null,Is=null,It=new Map,Ac=250,Ir=new Map;function Zt(e){if(Tr){Vn(e);return}Vn(e),Tr=J("vfs_change",t=>Kd(t)),Is=J("ccm_change",t=>Ld(t))}function Vn(e){if(Bn.has(e))return;let t=Ln(e,["vfs_change","ccm_change"]);Bn.set(e,t)}function Ts(e){let t=Bn.get(e);t&&(t(),Bn.delete(e))}function Li(){for(let[,e]of Bn)e();Bn.clear(),Tr&&(Tr(),Tr=null),Is&&(Is(),Is=null),It.forEach(e=>clearTimeout(e)),It.clear(),Ir.clear()}oe(Li);function Kd(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=Ir.get(s);i||(i=new Map,Ir.set(s,i)),i.set(t,{action:n,itemId:typeof e.item_id=="string"?e.item_id:void 0});let o=It.get(s);o&&clearTimeout(o);let a=setTimeout(()=>{It.delete(s);let c=Ir.get(s);Ir.delete(s),c&&Hd(s,c)},Ac);It.set(s,a)}function Ld(e){if(!e||typeof e!="object")return;let t=e.source_item_id||e.source_id,n=e.target_item_id||e.target_id;if(!(e.edge_type!=null||t!=null||n!=null)||!t&&!n||e.item_type==="message")return;let s=`ccm:${t??""}:${n??""}`,i=It.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{It.delete(s),t&&Q().invalidateQueries({queryKey:I.edges(t)}),n&&Q().invalidateQueries({queryKey:I.edges(n)})},Ac);It.set(s,o)}function Hd(e,t){let n=Q();for(let[s,i]of t)(i.action||"").toUpperCase()==="DELETE"?(n.removeQueries({queryKey:I.item(s)}),n.removeQueries({queryKey:I.children(s)}),n.removeQueries({queryKey:I.tree(s)})):le(n,I.item(s),{exact:!0}),i.itemId&&n.invalidateQueries({queryKey:I.itemById(i.itemId)});n.invalidateQueries({queryKey:I.children(e)});let r=[...t.keys()];n.invalidateQueries({predicate:s=>{let i=s.queryKey;if(i[0]!=="vfs"||i[1]!=="tree")return!1;let o=i[2];return r.some(a=>a.startsWith(o+"/")||a===o)}})}var Wn=null;oe(()=>{Wn=null});function Tt(e){if(e!==Wn||e.generation!==Z())throw new Error("Workspace session changed")}function jd(e){return e instanceof Se&&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 Mr(e){let t=we();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 Mc(e,t){return JSON.stringify({mounts:e.map(n=>n.id),last_anchor:t.id})}async function kc(e,t,n){Tt(e);let r=Mc(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}),Tt(e),e.exists=!0,e.saved=r}function Oc(e,t){let n=qe();Zt(we().id);for(let r of n)e.some(s=>s.id===r.id)||Ts(r.id);for(let r of e)Vn(r.id);va(e,t)}async function en(e,t,n={}){let r=we();if(!r)throw new Error("Elect a home account before loading mounts");let s=`${e}/settings/mounts`;if(Wn&&Wn.path!==s)throw new Error("Reset the session before changing the mount declaration owner");let i=Wn??(Wn={generation:Z(),path:s,scope:r.path,resolve:t,exists:!1,ready:!1,saved:null,queue:Promise.resolve()});return Tt(i),i.resolve=t,i.loading?i.loading:i.ready?qe():(i.loading=(async()=>{let o=null;try{let l=await R("read",{path:s,_scope_path:i.scope});if(Tt(i),o=l.type_data??l.item?.type_data,!o||!Array.isArray(o.mounts)||!o.mounts.every(d=>typeof d=="string"))throw new Error("Invalid saved mount declaration");i.exists=!0}catch(l){if(Tt(i),!jd(l))throw l;i.exists=!1}let a=n.initialAnchor?Ar(i,n.initialAnchor):r,c=Mr(o?o.mounts.map(l=>i.resolve(l)).filter(l=>l!==null):[a]),u=o?c.find(l=>l.id===o.last_anchor)??c.find(l=>l.kind==="space")??r:a;return o?i.saved=Mc(c,u):n.initialAnchor&&await kc(i,c,u),Tt(i),i.ready=!0,Oc(c,u),c})().finally(()=>{i.loading=void 0}),i.loading)}function As(e){let t=Wn;if(!t?.ready)return Promise.reject(new Error("Workspace mounts are not loaded"));let n=t.queue.then(async()=>{Tt(t);let{refs:r,anchor:s}=e(t);await kc(t,r,s),Tt(t),Oc(r,s)});return t.queue=n.catch(()=>{}),n}function Hi(e){return As(t=>({refs:Mr([...qe(),Ar(t,e)]),anchor:ye()}))}function Fc(e){return As(()=>{if(e===we().id)throw new Error("The home account cannot be unmounted");let t=Mr(qe().filter(r=>r.id!==e)),n=t.find(r=>r.id===ye()?.id)??t.find(r=>r.kind==="space")??we();return{refs:t,anchor:n}})}function kr(e){return As(t=>{let n=Ar(t,e);return{refs:Mr([...qe(),n]),anchor:n}})}function Ms(e,t){return As(n=>{let r=Mr(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}})}var ji={};_o(ji,{Badge:()=>zd,Breadcrumbs:()=>op,Button:()=>Yd,Card:()=>Gd,DataView:()=>Zd,Detail:()=>np,Empty:()=>Xd,FilePreview:()=>up,Form:()=>tp,Grid:()=>Wd,Image:()=>ap,Link:()=>sp,Page:()=>Bd,Router:()=>rp,Sidebar:()=>$d,Spinner:()=>Jd,Stack:()=>Vd,Table:()=>ep,Tabs:()=>ip,Video:()=>cp});var Y=ne(fe(),1);function qc(){return(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||""}function Bd(e){return(0,Y.createElement)("div",{style:{minHeight:"100vh",display:"flex",flexDirection:"column"},className:e.className||""},e.children)}function Vd(e){let t=e.direction||"vertical";return(0,Y.createElement)("div",{style:{display:"flex",flexDirection:t==="horizontal"?"row":"column",gap:e.gap||"0.5rem",padding:e.padding||"0",alignItems:e.align||"stretch",justifyContent:e.justify||"flex-start",flex:e.flex||"initial"},className:e.className||""},e.children)}function Wd(e){return(0,Y.createElement)("div",{style:{display:"grid",gridTemplateColumns:"repeat("+(e.columns||3)+", 1fr)",gap:e.gap||"1rem",padding:e.padding||"0"},className:e.className||""},e.children)}function $d(e){return(0,Y.createElement)("div",{style:{display:"flex",flexDirection:"row",minHeight:"100vh"},className:e.className||""},e.children)}function Gd(e){return(0,Y.createElement)("div",{style:{border:"1px solid var(--color-border, #e5e7eb)",borderRadius:"var(--border-radius, 0.5rem)",padding:e.padding||"1rem",background:"var(--color-surface, #fff)"},className:e.className||"",onClick:e.onClick},e.children)}function zd(e){return(0,Y.createElement)("span",{style:{display:"inline-flex",alignItems:"center",padding:"0.125rem 0.5rem",fontSize:"0.75rem",fontWeight:"500",borderRadius:"9999px",background:e.color||"#e5e7eb",color:e.textColor||"#374151"},className:e.className||""},e.children||e.label)}function Jd(e){let t=e.size||"1.5rem";return(0,Y.createElement)("div",{style:{width:t,height:t,border:"2px solid #e5e7eb",borderTopColor:"var(--color-primary, #3b82f6)",borderRadius:"50%",animation:"fsaos-spin 0.6s linear infinite"}})}function Yd(e){return(0,Y.createElement)("button",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:"0.5rem 1rem",fontSize:"0.875rem",fontWeight:"500",borderRadius:"var(--border-radius, 0.375rem)",border:e.variant==="outline"?"1px solid var(--color-border, #d1d5db)":"none",background:e.variant==="outline"||e.variant==="ghost"?"transparent":"var(--color-primary, #3b82f6)",color:e.variant==="outline"||e.variant==="ghost"?"var(--color-text, #1a1a1a)":"#fff",cursor:e.disabled?"not-allowed":"pointer",opacity:e.disabled?"0.5":"1",gap:"0.5rem"},className:e.className||"",onClick:e.onClick,disabled:e.disabled},e.children||e.label)}function Xd(e){return(0,Y.createElement)("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"3rem",color:"var(--color-text-secondary, #6b7280)",textAlign:"center"}},e.icon?(0,Y.createElement)("div",{style:{fontSize:"2rem",marginBottom:"0.5rem"}},e.icon):null,(0,Y.createElement)("div",{style:{fontWeight:500,marginBottom:"0.25rem"}},e.title||e.message||e.children||"No items"),e.description?(0,Y.createElement)("div",{style:{fontSize:"0.875rem",opacity:.7}},e.description):null)}function Zd(e){return(0,Y.createElement)("div",{className:e.className||""},e.children)}function ep(e){return(0,Y.createElement)("table",{className:e.className||""},e.children)}function tp(e){return(0,Y.createElement)("form",{className:e.className||"",onSubmit:e.onSubmit},e.children)}function np(e){return(0,Y.createElement)("div",{className:e.className||""},e.children)}function rp(e){return(0,Y.createElement)("div",null,e.children)}function sp(e){return(0,Y.createElement)("a",{href:e.href||e.to,className:e.className||"",onClick:e.onClick},e.children)}function ip(e){return(0,Y.createElement)("div",{className:e.className||""},e.children)}function op(e){return(0,Y.createElement)("nav",{className:e.className||""},e.children)}function ap(e){return(0,Y.createElement)("img",{src:e.src||(e.path?qc()+e.path:""),alt:e.alt||"",className:e.className||"",style:e.style})}function cp(e){return(0,Y.createElement)("video",{src:e.src||(e.path?qc()+e.path:""),controls:!0,className:e.className||""})}function up(e){return(0,Y.createElement)("div",{className:e.className||""},e.children||"File preview")}function ks(e){if(typeof e.path!="string")return!1;let t=[...qe().map(n=>n.path),ye()?.path].filter(n=>!!n);return!t.length&&z()&&t.push(z()),t.some(n=>de(e.path,n))}function $n(e,t,n,r){if(!["message","card"].includes(e?.item_type)||!de(e.path,t))return!1;if(!n){let s=e.path.slice(t.length).replace(/^\//,""),i=s?s.split("/").length:0;return e.item_type==="message"?i===1:i===1||i===2}return e.item_id===n||e.parent_id===n?!0:r.some(s=>{if(e.item_id===s.id||e.parent_id===s.id)return!0;let i=s.id===n?s.path:s.parent_message_id===n?s.path.slice(0,s.path.lastIndexOf("/")):void 0;return!!i&&de(e.path,i)})}var Nc=new WeakMap,Bi=e=>e.slice(0,e.lastIndexOf("/")),Vi=e=>e.action?.toLowerCase();function Qc(e,t){return e.item_type==="message"&&Vi(e)==="insert"&&Bi(e.path)===t&&!e.old_path}function lp(e,t,n){return e.messages.filter(r=>t.has(r.id)||n.has(r.path))}function dp(e,t,n,r){let s=e.pages.slice(),i=new Map(n?.messages.map(u=>[u.id,u]));for(let[u,l]of t){let d=s[u],h=new Set(l.map(m=>m.id)),f=new Map(d.messageCards);for(let m of l){f.delete(m.path);let v=i.get(m.id),g=v&&n?.messageCards.get(v.path);v&&g?.length&&f.set(v.path,g)}s[u]={...d,messages:d.messages.flatMap(m=>{if(!h.has(m.id))return[m];let v=i.get(m.id);return v?[v]:[]}),messageCards:f}}let o=r??n,a=s[0],c=new Map(a.messageCards);for(let u of a.activityMessages??[])c.delete(u.path);for(let u of[...o.activityMessages??[],...r?.messages??[]]){let l=o.messageCards.get(u.path);l?.length&&c.set(u.path,l)}return s[0]={...a,messages:r?[...a.messages,...r.messages]:a.messages,activityMessages:o.activityMessages,siblingCards:o.siblingCards,messageCards:c},{...e,pages:s}}function Dc(e,t,n,r){let s=Nc.get(e);s||(s=new Map,Nc.set(e,s));let i=JSON.stringify(t),o=s.get(i);if(!o){let c,u=!1,l=!1,d=new Map,h=()=>e.getQueryData(t),f=()=>e.getQueryCache().find({queryKey:t,exact:!0}),m=()=>le(e,t,{exact:!0}),v=(_,S)=>Xt(n,{transcriptOnly:!0,limit:r,after_seq:_,before_seq:S}),g=()=>{l||u||c||!d.size||(c=setTimeout(()=>{c=void 0,w()},500))},w=async()=>{u=!0;let _=[...d.values()];d.clear();let S=f();try{if(S?.state.fetchStatus==="fetching"&&await S.promise?.catch(()=>{}),l||S!==f())return;let x=h();if(!x?.pages.length){await m();return}let k=new Set,N=new Set,C=new Set,O=!1;for(let H of _){if(Qc(H,n)){O=!0;continue}H.inserted&&(O=!0),H.item_type==="message"&&Bi(H.path)===n&&!H.inserted&&Vi(H)!=="delete"&&C.add(H.path),H.item_id&&k.add(H.item_id),H.parent_id&&k.add(H.parent_id);for(let me of[H.path,H.old_path])me&&de(me,n)&&(N.add(me),N.add(Bi(me)))}let T=new Map,E=1/0,A=0;(k.size||N.size)&&x.pages.forEach((H,me)=>{let ve=lp(H,k,N);ve.length&&T.set(me,ve);for(let Ue of ve)C.delete(Ue.path),E=Math.min(E,Ue.seq),A=Math.max(A,Ue.seq)});for(let H of x.pages[0].activityMessages??[])C.delete(H.path);if(C.size){await m();return}if(T.size&&(!Number.isSafeInteger(E)||E<1||!Number.isSafeInteger(A+1))){await m();return}let F=x.pages.find(H=>H.messages.length)?.messages.at(-1)?.seq??0,[U,j]=await Promise.all([T.size?v(E-1,A+1):void 0,O||!T.size?v(F):void 0]);if(l||S!==f())return;let Me=h();if(S?.state.fetchStatus==="fetching"||x.pages.some((H,me)=>Me?.pages[me]!==H)||U&&U.messages.length>=r&&(U.messages.at(-1)?.seq??0)<A||j&&j.messages.length>=r){await m();return}e.setQueryData(t,H=>H&&dp(H,T,U,j))}catch{!l&&S===f()&&await m()}finally{u=!1,g()}},y=J("vfs_change",_=>{let S=_.item_id??_.path,x=d.get(S);d.set(S,x&&(x.inserted||Qc(x,n))&&Vi(_)==="update"&&x.path===_.path?{..._,inserted:!0}:_),g()},_=>$n(_,n,void 0,[])||!!_.old_path&&$n({..._,path:_.old_path},n,void 0,[])||_.item_type==="message"&&!!_.parent_id&&de(_.path,n)&&!!h()?.pages.some(S=>S.messages.some(x=>x.id===_.parent_id)));o={users:0,stop:()=>{l=!0,y(),c&&clearTimeout(c),d.clear()}},s.set(i,o)}o.users++;let a=!1;return()=>{a||(a=!0,--o.users===0&&(o.stop(),s.delete(i)))}}var Uc=new WeakMap;function Kc(e,t,n){let r=Uc.get(e);r||(r=new Map,Uc.set(e,r));let s=JSON.stringify(t),i=r.get(s);if(!i){let a=!1,c,u=!1,l=!1,d=new Set,h=new Set,f=()=>e.getQueryData(t)??[],m=()=>{a||u||c||(c=setTimeout(()=>{c=void 0,v()},250))},v=async()=>{if(a)return;u=!0;let S=l;l=!1;let x=[...d],k=new Set(h);h.clear(),d.clear();try{if(S)await le(e,t,{exact:!0});else{let C=(await Promise.allSettled(x.map(async O=>{let T=e.getQueryCache().find({queryKey:t,exact:!0});if(!T)return;let E=await R("read",{id:O});if(E.success===!1)throw new Error("Channel refresh failed");if(a||!T||e.getQueryCache().find({queryKey:t,exact:!0})!==T)return;let A=De(E.item??E);if(A.id!==O||A.item_type!=="channel")return;let F=f().find(Me=>Me.id===O);if(!F)return;let U=n({...A}),j={...F,path:U.path,name:U.name,displayName:U.displayName,messageCount:U.messageCount,aiMode:U.aiMode,activeAgentIds:U.activeAgentIds,isPrivate:U.isPrivate,isDm:U.isDm,autoPilot:U.autoPilot,isArchived:U.isArchived,updatedAt:U.updatedAt};k.has(O)&&(F.name!==j.name||F.displayName!==j.displayName||F.path!==j.path)&&(l=!0),e.setQueryData(t,Me=>Me?.map(H=>H.id===O?j:H))}))).find(O=>O.status==="rejected");if(C?.status==="rejected")throw C.reason}}catch(N){console.warn("[channels] refresh failed",N)}finally{u=!1,(l||d.size)&&m()}},g=S=>f().some(x=>x.id===S.item_id||x.path===S.path)?!0:ks(S),w=S=>{if(!g(S))return;let x=String(S.action??"").toLowerCase();if(["insert","delete","rename","move"].includes(x))l=!0;else if(x==="update"){let k=f().find(N=>N.id===S.item_id||N.path===S.path);k&&(d.add(k.id),h.add(k.id))}(l||d.size)&&m()},y=S=>{let x=f().find(k=>k.id===S.parent_id);x&&(d.add(x.id),m())},_=["vfs_change","ccm_change"].flatMap(S=>[J(S,w,x=>x.item_type==="channel"),J(S,y,x=>x.item_type==="message")]);i={users:0,stop:()=>{a=!0,c&&clearTimeout(c),_.forEach(S=>S())}},r.set(s,i)}i.users++;let o=!1;return()=>{o||(o=!0,--i.users===0&&(i.stop(),r.delete(s)))}}var Lc=new WeakMap;function Hc(e,t,n){let r=Lc.get(e);r||(r=new Map,Lc.set(e,r));let s=JSON.stringify(t),i=r.get(s);if(!i){let a,c=()=>{a||(a=setTimeout(()=>{a=void 0,le(e,t,{exact:!0})},250))},u=[J("ccm_change",c,l=>l.edge_type==="replies_to"&&(l.target_item_id??l.target_id)===n),J("vfs_change",c,l=>{let d=l.item_id??l.id;return d?d===n?!0:e.getQueryData(t)?.pages.some(f=>f.messages.some(m=>m.id===d))??!1:!1})];i={users:0,stop:()=>{a&&clearTimeout(a),u.forEach(l=>l())}},r.set(s,i)}i.users++;let o=!1;return()=>{o||(o=!0,--i.users===0&&(i.stop(),r.delete(s)))}}function te(){return(0,b.useSyncExternalStore)(Ie,G,G)}function zc(){return te(),ts()}function Jc(e){return te(),W({queryKey:I.item(e),queryFn:()=>Rr(e),enabled:!!e,staleTime:1/0})}function Yc(e){return te(),W({queryKey:I.itemById(e),queryFn:()=>xr(e),enabled:!!e,staleTime:1/0})}function Gi(e){return te(),W({queryKey:I.children(e),queryFn:()=>Cr(e),enabled:!!e})}function Xc(e){let t=Gi(e);return{...t,children:t.data??[]}}function Zc(e,t=1){return te(),W({queryKey:I.tree(e,t),queryFn:()=>ws(e,t),enabled:!!e})}function eu(e,t){return te(),W({queryKey:I.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(De)},enabled:!!e&&e.length>0})}function tu(e){te();let t=(0,b.useMemo)(()=>e,[JSON.stringify(e)]);return W({queryKey:["vfs",z()??"__unscoped__","resolve",JSON.stringify(t??{})],queryFn:async()=>await R("resolve",t),enabled:!!t?.query&&t.query.length>0})}function nu(e){te();let t=Pt(e),n=(0,b.useMemo)(()=>t,[JSON.stringify(t)]),r=W({queryKey:I.items(n?.type??"",n),queryFn:({signal:s})=>Yt(n,{signal:s,throwOnError:!0}),enabled:jn(n),...n?.spaceIds!==void 0?{retry:(s,i)=>!qn(i)&&Ju(s,i)}:{},select:s=>s.items});return n?.spaceIds!==void 0&&qn(r.error)?{...r,data:void 0}:r}function zi(e,t={}){let n=te(),{realtime:r=!1}=t,s=Pt(e),i=s?.limit??20,o=(0,b.useMemo)(()=>s,[JSON.stringify(s)]),a=(0,b.useMemo)(()=>["vfs",z()??"__unscoped__","infinite-items",o?.type??"",JSON.stringify(o??{})],[n,o]),c=Rn({queryKey:a,queryFn:async({pageParam:d=0,signal:h})=>Yt({...o,limit:i,offset:d},{throwOnError:!0,signal:h,priority:t.priority}),initialPageParam:0,getNextPageParam:(d,h,f)=>{if(!(o?.spaceIds!==void 0&&d.total_hint!==void 0&&f+d.items.length>=d.total_hint)&&!(d.items.length<i))return f+d.items.length},enabled:jn(o),...o?.spaceIds!==void 0?{retry:(d,h)=>!qn(h)&&Ju(d,h)}:{},staleTime:r?1/0:t.staleTime,meta:r&&o?{infiniteItemsRealtime:{filter:o}}:{}}),u=(0,b.useMemo)(()=>{if(o?.spaceIds!==void 0&&qn(c.error))return[];if(!c.data?.pages)return[];let d=new Set,h=[];for(let f of c.data.pages)for(let m of f.items)m.id&&!d.has(m.id)&&(d.add(m.id),h.push(m));return h},[c.data?.pages,c.error,o]),l=o?.spaceIds!==void 0&&qn(c.error);return{allItems:u,refetch:c.refetch,fetchNextPage:c.fetchNextPage,isFetchingNextPage:c.isFetchingNextPage,isExhausted:l||!c.hasNextPage,isLoading:c.isLoading,isFetching:c.isFetching,error:c.error,totalHint:l?void 0:c.data?.pages?.[0]?.total_hint}}function jc(e){return!!e?.type&&!!e.scope&&e.sort_by==="created_at"&&!e.offset&&!e.spaceIds&&!e.any_of&&!e.name&&!e.tag&&!e.discovery}function mp(e,t){if(e.is_active===!1||e.item_type!==t.type||!de(e.path,t.scope)||t.parent_id&&e.parent_id!==t.parent_id)return!1;let n=e.type_data??{};for(let[r,s]of Object.entries(t.fields??{})){let i=n[r];if(typeof s=="string"&&s.endsWith("*")){if(typeof i!="string"||!i.startsWith(s.slice(0,-1)))return!1}else if(i!==s)return!1}for(let[r,s]of Object.entries(t.field_in??{}))if(!s.includes(n[r]))return!1;return!0}function ru(e,t={}){let n=jc(e),r=zi(e,n?{realtime:!1,staleTime:3e4}:{realtime:!0}),s=L(),i=JSON.stringify([z(),Pt(e)]),[o,a]=(0,b.useState)(()=>({identity:i,upserts:{},deleted:new Set})),c=o.identity===i?o:{identity:i,upserts:{},deleted:new Set},u=(0,b.useMemo)(()=>{if(!n)return r.allItems;let f=Object.values(c.upserts),m=new Set(f.map(y=>y.id)),v=[...f,...r.allItems.filter(y=>!m.has(y.id))].filter(y=>!c.deleted.has(y.path)),g=e.sort_by??"updated_at",w=e.sort_dir==="asc"?1:-1;return v.sort((y,_)=>w*String(y[g]??"").localeCompare(String(_[g]??"")))},[n,r.allItems,c,e?.sort_by,e?.sort_dir]),l=(0,b.useRef)(u);l.current=u;let d=(0,b.useRef)(t.shouldReadUpdate);d.current=t.shouldReadUpdate;let h=(0,b.useRef)(r.refetch);return h.current=r.refetch,(0,b.useEffect)(()=>{if(!jc(e))return;let f=e,m=!1,v=!1,g=!1,w=0,y=new Map,_=()=>{let C=w;h.current().then(O=>{!m&&!O.isError&&w===C&&a({identity:i,upserts:{},deleted:new Set})})},S=C=>{w++,a(T=>{let E=T.identity===i?T:{identity:i,upserts:{},deleted:new Set},A={...E.upserts};return delete A[C],{identity:i,upserts:A,deleted:new Set(E.deleted).add(C)}});let O=y.get("__reconcile__");O&&clearTimeout(O),y.set("__reconcile__",setTimeout(()=>{y.delete("__reconcile__"),_()},250))},x=C=>{let O=y.get(C);O&&clearTimeout(O),y.set(C,setTimeout(()=>{y.delete(C),s.fetchQuery({queryKey:I.item(C),queryFn:()=>Rr(C),staleTime:0}).then(T=>{if(!m){if(!T||!mp(T,f)){let E=l.current.find(A=>A.path===C||A.id===T?.id);E&&S(E.path);return}a(E=>{let A=E.identity===i?E:{identity:i,upserts:{},deleted:new Set},F=new Set(A.deleted);return F.delete(C),{identity:i,upserts:{...A.upserts,[C]:T},deleted:F}})}}).catch(T=>console.warn("[useIncrementalItems] item read failed:",T))},250))},k=J("vfs_change",C=>{if(!C||typeof C.path!="string"&&typeof C.old_path!="string")return;let O=typeof C.path=="string"?C.path:C.old_path,T=l.current.find(A=>A.path===O||A.path===C.old_path||C.item_id&&A.id===C.item_id),E=!!T;if(!(!de(O,f.scope)&&!de(C.old_path,f.scope)&&!E)&&!(C.item_type&&C.item_type!==f.type&&!E)&&!(f.parent_id&&C.parent_id&&C.parent_id!==f.parent_id&&!E)){if(T&&(O!==T.path||C.old_path&&C.old_path!==O||C.parent_id&&C.parent_id!==T.parent_id||C.item_type&&C.item_type!==f.type)){S(T.path);return}if(!T&&C.old_path&&C.old_path!==O&&de(O,f.scope)){w++,x(O);return}if(C.action==="insert")w++,x(O);else if(C.action==="move")w++,x(O);else if(C.action==="update"){if(!d.current?.(C,l.current))return;w++,x(O)}else C.action==="delete"&&S(T?.path??C.old_path??O)}}),N=hs(C=>{if(C!=="connected"){v&&(g=!0);return}v=!0,g&&(g=!1,_())});return()=>{m=!0,k(),N(),y.forEach(clearTimeout)}},[s,i]),{...r,allItems:u}}function su(e){te();let t=20,n=Rn({queryKey:["vfs",z()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>_s(e,t,s),initialPageParam:0,getNextPageParam:(s,i,o)=>{if(!(s.items.length<t))return o+s.items.length},enabled:!!e});return{allItems:(0,b.useMemo)(()=>{if(!n.data?.pages)return[];let s=new Set,i=[];for(let o of n.data.pages)for(let a of o.items)a.id&&!s.has(a.id)&&(s.add(a.id),i.push(a));return i},[n.data?.pages]),fetchNextPage:n.fetchNextPage,isFetchingNextPage:n.isFetchingNextPage,isExhausted:!n.hasNextPage,isLoading:n.isLoading,isFetching:n.isFetching,error:n.error,totalHint:n.data?.pages?.[0]?.total_hint}}function iu(e){return te(),W({queryKey:I.edges(e),queryFn:()=>bs(e),enabled:!!e})}function Fs(e){return te(),W({queryKey:I.types(e),queryFn:()=>vs(e)})}function ou(e,t){let n=Fs(t);return{...n,data:n.data?.get(e)??void 0}}function au(e,t){te();let n=(0,b.useMemo)(()=>t?.arguments,[JSON.stringify(t?.arguments)]),r=t?.mode,s=t?.strategy,i=t?.width;return W({queryKey:[...I.openEnvelope(e,s),i],queryFn:async()=>{let o=await Er(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 Bc={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 cu(e){let t=Fs(e),n=t.data??new Map;return(0,b.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(Bc).map(([f,m])=>({key:f,label:m})),getEdgeTypeLabel:f=>Bc[f]??f.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function uu(e,t,n){return te(),W({queryKey:I.memberFocus(e),queryFn:()=>Rs(e,t,n),enabled:!!e})}function lu(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return W({queryKey:I.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>Pr(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function du(e,t=50,n=0){return W({queryKey:I.itemHistory(e,String(t),String(n)),queryFn:()=>xs(e,t,n),enabled:!!e})}function pu(e,t=50,n=0){return te(),W({queryKey:I.recentActivity(e,String(t),String(n)),queryFn:()=>Ss(e,t,n),enabled:!!e})}function fu(){let[e,t]=(0,b.useState)(null),[n,r]=(0,b.useState)(!0),[s,i]=(0,b.useState)(null);return(0,b.useEffect)(()=>{let o=!1;return ct().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 gp=[];function Vc(){if(typeof window>"u")return!1;let e=window.__FSAOS_CONFIG__?.embedToken;return typeof e=="function"||typeof e=="string"&&e.length>0}function hp(e){return e.filter(t=>t.placement==="switcher_entry").map(t=>({account:t,mountables:e.filter(n=>n.placement!=="switcher_entry"&&n.subordinateTo===t.accountId)}))}function mu(){let{user:e}=qs(),t=(0,b.useSyncExternalStore)(Sa,Pi,Pi),n=Ct()?.principal_id??null,r=(0,b.useRef)(null),[s,i]=(0,b.useState)(null),[o,a]=(0,b.useState)(null);(0,b.useEffect)(()=>{if(n){a(null);return}if(!e?.id&&!Vc()){a(null);return}let y=!1;return ct().then(_=>{y||_.principal_id||a(new Error("Memberships require an authenticated principal"))}).catch(_=>{y||a(_ instanceof Error?_:new Error(String(_)))}),()=>{y=!0}},[n,e?.id,t]);let c=W({queryKey:I.memberships(n??"anonymous"),queryFn:Es,enabled:!!n,staleTime:1e3*60*2}),u=c.data??gp,l=(0,b.useMemo)(()=>u.filter(y=>y.isAccount!==!1&&!y.isSpace),[u]),d=(0,b.useMemo)(()=>{let y=new Set(l.map(S=>S.accountId)),_=S=>!S.subordinateTo||!y.has(S.subordinateTo);return[...l].sort((S,x)=>Number(_(x))-Number(_(S)))},[l]),h=(0,b.useSyncExternalStore)(Ie,G,G),f=(0,b.useMemo)(()=>{let y=ye();return y?u.find(_=>_.accountId===y.id)??null:null},[h,u]),m=(0,b.useMemo)(()=>hp(l),[l]);(0,b.useEffect)(()=>{if(!n){r.current=null;return}if(r.current!==n)if(i(null),d.length===1){let y=d[0];we()||Vt(Ye(y)),Zt(y.accountId),y.personalSpacePath&&en(y.personalSpacePath,_=>{let S=u.find(x=>x.accountId===_);return S?Ye(S):null}).catch(i),r.current=n}else d.length>1&&(r.current=n)},[n,d,u]);let v=(0,b.useCallback)(async y=>{let _=u.find(k=>k.path===y);if(!_)throw new Error("Account membership is unavailable");let S=Ye(_);we()||Vt(S);let x=u.find(k=>k.accountId===we()?.id);if(!x?.personalSpacePath)throw new Error("The home membership has no mount declaration location");await en(x.personalSpacePath,k=>{let N=u.find(C=>C.accountId===k);return N?Ye(N):null}),await kr(S),i(null),Zt(_.accountId)},[u]),g=(0,b.useCallback)(async y=>{let _=u.find(S=>S.path===y);if(!_)throw new Error("Scope membership is unavailable");await Hi(Ye(_))},[u]),w=(!!e?.id||Vc())&&!n&&!o;return{accounts:d,switcherAccounts:m,allMemberships:u,currentAccount:f,mountedScope:null,switchAccount:v,mountScope:g,loading:w||c.isLoading,error:o??c.error??s}}function gu(){te();let e=(0,b.useSyncExternalStore)(es,_r,_r),t=(0,b.useMemo)(()=>qe(),[e]),n=ye(),r=(0,b.useMemo)(()=>t.filter(i=>i.kind==="space"&&(n?.kind==="account"||i.id===n?.id)),[t,n]),s=(0,b.useMemo)(()=>r.map(i=>i.id).sort(),[r]);return{mounts:t,selectedSpaces:r,readSpaceIds:s,homeAnchor:we(),anchor:n,setAnchor:kr,replaceMounts:Ms,mount:Hi,unmount:Fc}}function qs(){let[e,t]=(0,b.useState)(null),[n,r]=(0,b.useState)(null),[s,i]=(0,b.useState)(!0),o=(0,b.useRef)(null);(0,b.useEffect)(()=>{$.auth.getSession().then(({data:f,error:m})=>{if(m){console.warn("[useAuth] getSession error, clearing stale session:",m.message),$.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),$.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:h}}=$.auth.onAuthStateChange((f,m)=>{if(f==="TOKEN_REFRESHED"&&!m){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),$.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(m),t(m?.user??null),i(!1)});return o.current=h,()=>{h?.unsubscribe()}},[]);let a=(0,b.useCallback)(async h=>h.provider?$.auth.signInWithOAuth({provider:h.provider,options:h.redirectTo?{redirectTo:h.redirectTo}:{redirectTo:window.location.href}}):$.auth.signInWithPassword({email:h.email,password:h.password}),[]),c=(0,b.useCallback)(async h=>$.auth.signUp({email:h.email,password:h.password,options:{data:h.metadata||{}}}),[]),u=(0,b.useCallback)(async()=>{await $.auth.signOut(),On(),Q().clear()},[]),l=(0,b.useCallback)(async h=>{let{error:f}=await $.auth.resetPasswordForEmail(h);if(f)throw f},[]),d=(0,b.useCallback)(async(h,f)=>{let{error:m}=await $.auth.signInWithOtp({email:h,options:f?{emailRedirectTo:f}:{emailRedirectTo:window.location.href}});if(m)throw m},[]);return{user:e,session:n,loading:s,signIn:a,signUp:c,signOut:u,resetPassword:l,signInWithMagicLink:d}}function hu(e){let[t,n]=(0,b.useState)(null),[r,s]=(0,b.useState)(!1),[i,o]=(0,b.useState)(null);return(0,b.useEffect)(()=>{if(!e){n(null),s(!1);return}if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e))s(!0),R("resolve-asset",{asset_id:e}).then(c=>{c.success&&c.public_url?n({url:c.public_url,id:c.asset_id,name:c.name,mimeType:c.mime_type,width:c.width,height:c.height,sizeBytes:c.size_bytes}):o(new Error(c.error||"Asset not found")),s(!1)}).catch(c=>{o(c instanceof Error?c:new Error(String(c))),s(!1)});else{let u=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";n({url:u+e}),s(!1)}},[e]),{data:t,loading:r,error:i}}var Os={};oe(()=>{for(let e of Object.keys(Os))delete Os[e]});var yu=null;function _u(e){yu=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function yp(e){switch(e){case"react":return typeof window<"u"&&window.React||b.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||pp;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}:fp;case"@fsaos/gateway":case"@fsaos/react":case"@ai4b-team/fsaos-gateway-sdk":return typeof window<"u"&&window.__FSAOS_GATEWAY__||yu||{};case"@fsaos/ui":case"@ai4b-team/fsaos-gateway-sdk/ui":return typeof window<"u"&&window.__FSAOS_UI__||ji;case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}var Fr={};async function _p(e){try{let t=await fetch(e);if(!t.ok)return null;let n=await t.text();return!n.trim()||n.includes("No CSS bundle for this component")?null:n}catch{return null}}async function vu(e,t=()=>_p(e)){let n=Fr[e];n||(n=Fr[e]={users:0,text:t(),style:null}),n.users+=1;let r=await n.text;if(Fr[e]!==n||n.users===0||n.style||!r||typeof document>"u")return;let s=document.createElement("style");s.setAttribute("data-fsaos-component-css",e),s.textContent=r,document.head.appendChild(s),n.style=s}function Xe(e){let t=Fr[e];t&&(t.users-=1,!(t.users>0)&&(t.style?.remove(),delete Fr[e]))}function bu(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)(yp),o=t??i;return o?o.default||o:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function Ji(e,t){let[n,r]=(0,b.useState)(null),[s,i]=(0,b.useState)(!0),[o,a]=(0,b.useState)(null),c=(0,b.useRef)(null),u=Number.isSafeInteger(t?.version)&&t.version>0?t.version:null;return(0,b.useEffect)(()=>{if(!e)return;let l=!1;a(null),c.current?.path!==e&&(c.current?.cssUrl&&Xe(c.current.cssUrl),c.current=null,r(null),i(!0));let h=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{let f=null;try{let m=1,v=e+"@v1",g=h+e+"/__bundle.js";if(u!==null)m=u,v=e+"@v"+m,g=h+e+"/__bundle.v"+m+".js";else try{let x=await fetch(h+e+"/__meta",{cache:"no-store"});x.ok&&(m=(await x.json()).version||1,v=e+"@v"+m,g=h+e+"/__bundle.v"+m+".js")}catch{g=h+e+"/__bundle.js?v="+Date.now()}if(l)return;let w=g.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");f=w;let y=vu(w),_=Os[v];if(!_){let x=await fetch(g);if(!x.ok)throw new Error(`Failed to fetch bundle: ${x.status} ${x.statusText} (${g})`);let k=await x.text();if(_=bu(k),!_)throw new Error("Bundle did not export a component. Expected window.__FSAOS_COMPONENT__ (FSAOS build) or a __FSAOS_REGISTER__(Component) call.");if(typeof _!="function")throw new Error(`Bundle export is not a React component (got ${typeof _})`);Os[v]=_}if(await y,l){Xe(w);return}let S=c.current?.cssUrl??null;c.current={path:e,cssUrl:w},f=null,r(()=>_),i(!1),S&&Xe(S)}catch(m){f&&Xe(f),l||(a(m instanceof Error?m:new Error(String(m))),i(!1))}})(),()=>{l=!0}},[e,u]),(0,b.useEffect)(()=>()=>{c.current?.cssUrl&&Xe(c.current.cssUrl),c.current=null},[]),{Component:n,loading:s,error:o}}var vp=/^embed\/bundle-[A-Za-z0-9_-]+\.js$/,bp=/^embed\/bundle-[A-Za-z0-9_-]+\.css$/;function Wc(e,t,n){let r=Object.keys(e).filter(o=>t.test(o));if(r.length>1)throw new Error(`The published release has more than one in-app ${n}.`);let s=r[0];if(!s)return null;let i=At(e[s]).sha256;return typeof i=="string"&&i?{path:s,sha256:i}:null}var Or=new Map,Wi=new Map;oe(()=>{Or.clear(),Wi.clear()});function At(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function wu(e){let t=At(At(e.type_data).published),n=t.published_release_item_id,r=t.published_version;return typeof n!="string"||!n||typeof r!="number"||!Number.isSafeInteger(r)||r<1?null:{releaseItemId:n,version:r}}async function $c(e,t,n){let r=await Er(e.path,{mode:"render"}),s=At(At(r.render).props).url;if(typeof s!="string"||!s)throw new Error(`The published ${n} could not be opened.`);let i=await fetch(s);if(!i.ok)throw new Error(`Failed to read the published ${n}: ${i.status} ${i.statusText}`.trim());let o=await i.arrayBuffer();if(Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",o))).map(c=>c.toString(16).padStart(2,"0")).join("")!==t)throw new Error(`The published ${n} does not match the bytes its release sealed.`);return new TextDecoder().decode(o)}async function wp(e,t,n){let r=await xr(t);if(!r)throw new Error("The published release could not be read.");let s=At(r.type_data);if(r.item_type!=="revdev_release"||s.component_item_id!==e||s.status!=="committed"||Number(s.version)!==n)throw new Error("This component's live version does not match its release record.");let i=At(s.artifacts),o=Wc(i,vp,"script");if(!o)return{status:"no_in_app_version",releaseItemId:t,version:n};let a=Wc(i,bp,"stylesheet"),c=a?[o.path,a.path]:[o.path],u=s.build_item_id;if(typeof u!="string"||!u)throw new Error("The published release names no build.");let{items:l}=await Yt({type:"file",parent_id:u,field_in:{package_path:c},limit:c.length},{throwOnError:!0}),d=g=>l.find(w=>At(w.type_data).package_path===g),h=d(o.path),f=a?d(a.path):void 0;if(!h||a&&!f)throw new Error("The published release's in-app files could not be found in its build.");let[m,v]=await Promise.all([$c(h,o.sha256,"script"),f&&a?$c(f,a.sha256,"stylesheet"):Promise.resolve(null)]);return{status:"ready",releaseItemId:t,version:n,script:m,stylesheet:v?.trim()?v:null}}function Su(e,t,n){let r=Or.get(t);return r||(r=wp(e,t,n),Or.set(t,r),r.catch(()=>{Or.get(t)===r&&Or.delete(t)})),r}function xu(e){let t=wu(e);return!e.id||!t?Promise.resolve({status:"unpublished"}):Su(e.id,t.releaseItemId,t.version)}function Ru(e){let[t,n]=(0,b.useState)(null),[r,s]=(0,b.useState)("loading"),[i,o]=(0,b.useState)(null),a=(0,b.useRef)(null),c=e!=null,u=e?.id||null,l=e?wu(e):null,d=l?.releaseItemId??null,h=l?.version??null;return(0,b.useEffect)(()=>{if(!c)return;let f=()=>{a.current?.cssKey&&Xe(a.current.cssKey),a.current=null,n(null)};if(!u||!d||h===null){f(),o(null),s("unpublished");return}let m=!1;return o(null),a.current&&a.current.componentId!==u&&f(),a.current||s("loading"),(async()=>{let v=null;try{let g=await Su(u,d,h);if(m)return;if(g.status!=="ready"){f(),s(g.status);return}let w=Wi.get(d);if(!w){if(w=bu(g.script),!w)throw new Error("The published script did not hand over a component. Expected a __FSAOS_REGISTER__(Component) call or window.__FSAOS_COMPONENT__.");if(typeof w!="function")throw new Error(`The published script handed over something that is not a React component (${typeof w}).`);Wi.set(d,w)}let y=g.stylesheet?`release:${d}`:null;if(y&&(v=y,await vu(y,async()=>g.stylesheet)),m){v&&Xe(v);return}let _=a.current?.cssKey??null;a.current={componentId:u,releaseItemId:d,cssKey:y},v=null,n({Component:w,version:h}),s("ready"),_&&Xe(_)}catch(g){if(v&&Xe(v),m)return;o(g instanceof Error?g:new Error(String(g))),a.current||s("error")}})(),()=>{m=!0}},[c,u,d,h]),(0,b.useEffect)(()=>()=>{a.current?.cssKey&&Xe(a.current.cssKey),a.current=null},[]),{Component:t?.Component??null,status:r,error:i,version:t?.version??null}}var Sp=["--color-primary","--color-secondary","--color-background","--color-surface","--color-text","--color-text-secondary","--color-border","--color-accent","--color-success","--color-warning","--color-error","--font-family-heading","--font-family-body","--border-radius","--spacing-unit"];function Cu(){return{data:(0,b.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let t={},n=getComputedStyle(document.documentElement);return Sp.forEach(r=>{t[r]=n.getPropertyValue(r).trim()}),{tokens:t}},[]),loading:!1,error:null}}function Pu(e,t){return{data:{allowed:!0},loading:!1,error:null}}function Eu(e,t){let n={};return(t||[]).forEach(r=>{n[r]=!0}),{data:n,loading:!1,error:null}}var _e=null,Gn=null,$i=new Set;function xp(){$i.forEach(e=>e())}oe(()=>{_e=null,Gn=null});async function Iu(e){let t={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null},n=Ct()?.principal_id??null;if(n){if(_e&&_e.principalId===n){let{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}=_e;return{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}}return{...t,principalId:n}}let r=e;if(!r){let{data:s}=await $.auth.getSession();r=s?.session?.user?.id}if(!r)return t;if(_e&&_e.authUserId===r){let{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}=_e;return{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}}return Gn||(Gn=(async()=>{try{let{data:s,error:i}=await $.from("os_principals").select("id, display_name, created_at, metadata").eq("auth_user_id",r).eq("principal_type","user").maybeSingle();if(i)return console.warn("[SDK] Could not resolve principal:",i.message),t;let o=s?.id??null,a=null;if(o){let{data:u}=await $.from("os_items").select("path").eq("owner_principal_id",o).eq("item_type","principal").eq("is_active",!0).like("path","/root/principals/%"),l=(u??[]).map(d=>d.path);a=l.find(d=>d.split("/").length===4)??l[0]??null}let c={principalId:o,displayName:s?.display_name??null,createdAt:s?.created_at??null,metadata:s?.metadata??null,vfsPath:a};return _e={authUserId:r,...c},c}finally{Gn=null}})(),Gn)}async function Tu(e){return(await Iu(e)).principalId}function Au(){let e=qs(),t=e.user,n=_e?.authUserId===t?.id?_e:null,[r,s]=(0,b.useState)(n),i=(0,b.useRef)(null);return(0,b.useEffect)(()=>{let o=()=>{let a=_e;a&&a.authUserId===t?.id&&s({principalId:a.principalId,displayName:a.displayName,createdAt:a.createdAt,metadata:a.metadata,vfsPath:a.vfsPath})};return $i.add(o),()=>{$i.delete(o)}},[t?.id]),(0,b.useEffect)(()=>{if(!t?.id){s(null),i.current=null;return}i.current===t.id&&r?.principalId!=null||(i.current=t.id,Iu(t.id).then(o=>{s(o)}))},[t?.id]),e.loading?{data:null,loading:!0,error:null}:t?{data:{id:t.id,principalId:r?.principalId??null,email:t.email,display_name:r?.displayName??void 0,created_at:r?.createdAt??void 0,vfs_path:r?.vfsPath??void 0,role:t.role||t.app_metadata?.role||"user",authenticated:!0,metadata:r?.metadata??t.user_metadata??{}},loading:!1,error:null}:{data:{id:"anonymous",principalId:null,role:"viewer",authenticated:!1},loading:!1,error:null}}function Mu(e){let{path:t,...n}=e,r=Ji(t),s=r.Component,{loading:i,error:o}=r;return i?(0,b.createElement)("div",{className:"fsaos-loading"},""):o?(0,b.createElement)("div",{className:"fsaos-error"},"Failed to load component"):s?(0,b.createElement)(s,n):null}function ku(e){return e.children}function Ou(e){let t=te(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=e,o=i!==void 0?i&&!!n:!!n,a=(0,b.useMemo)(()=>I.channelMessages(n??"",r),[n,r,t]),c=L(),u=(0,b.useRef)(null),l=W({queryKey:a,queryFn:()=>Ps(n,r),enabled:o});(0,b.useEffect)(()=>{if(!s||!o)return;let v=J("vfs_change",()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{le(c,a,{exact:!0})},500)},g=>{let w=c.getQueryData(a);return $n(g,n,r,[...w?.messages??[],...w?.activityMessages??[]])});return()=>{v(),u.current&&clearTimeout(u.current)}},[s,o,n,r,a,c]);let d=l.data,h=d?.messages??[],f=d?.messageCards??new Map,m=d?.siblingCards??[];return{messages:h,activityMessages:d?.activityMessages??[],messageCards:f,siblingCards:m,threads:(0,b.useMemo)(()=>h.filter(v=>v.reply_count>0),[h]),breakouts:(0,b.useMemo)(()=>h.filter(v=>v.member_count>0),[h]),isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function Fu(e){let t=te(),{channelPath:n,messageId:r,conversationRootId:s,enabled:i=!0,realtime:o=!0,limit:a=25}=e,c=i&&!!n&&!!r,u=(0,b.useMemo)(()=>I.messageReplies(n??"",r,s,a),[n,r,s,a,t]),l=L(),d=Rn({queryKey:u,queryFn:({pageParam:f})=>Cs(r,{limit:a,conversationRootId:s,cursor:f}),initialPageParam:void 0,getNextPageParam:f=>f.next_cursor??void 0,enabled:c,staleTime:1/0,refetchOnMount:"always",refetchOnWindowFocus:!1,retry:!1});(0,b.useEffect)(()=>c&&o?Hc(l,u,r):void 0,[c,o,l,u,r]);let h=(0,b.useMemo)(()=>{if(!c||d.isError)return[];let f=new Set;return(d.data?.pages??[]).flatMap(m=>m.messages).filter(m=>f.has(m.id)?!1:(f.add(m.id),!0))},[c,d.data,d.isError]);return{...d,messages:h}}function qu(e){let t=te(),{channelPath:n,parentMessageId:r,limit:s=50,realtime:i=!0,enabled:o=!0,conversationsOnly:a=!1,transcriptOnly:c=!1}=e,u=!!r,l=o&&!!n,d=Rn({queryKey:[...I.channelMessages(n||"",r),"infinite",s,"latest-first",...a?["conversations"]:[],...c?["transcript"]:[]],queryFn:async({pageParam:y})=>{let _=await Xt(n,{parentMessageId:r,limit:s,conversationsOnly:a,transcriptOnly:c,before_seq:y?.before_seq,after_seq:y?.after_seq});return c&&_.messages.length>=s?{..._,olderBefore:_.messages[0]?.seq}:_},initialPageParam:void 0,getPreviousPageParam:y=>{if(!u||y.messages.length<s)return;let _=y.messages[y.messages.length-1]?.seq;return _==null?void 0:{after_seq:_}},getNextPageParam:y=>{if(c)return y.olderBefore==null?void 0:{before_seq:y.olderBefore};if(y.messages.length<s)return;let _=y.messages[0]?.seq;return _==null?void 0:{before_seq:_}},enabled:l}),h=(0,b.useMemo)(()=>{if(!d.data?.pages)return[];let y=new Set,_=[];for(let S of d.data.pages)for(let x of S.messages)y.has(x.id)||(y.add(x.id),_.push(x));return _.sort((S,x)=>S.seq-x.seq)},[d.data?.pages]),{messageCards:f,siblingCards:m}=(0,b.useMemo)(()=>{let y=new Map,_=[];if(!d.data?.pages)return{messageCards:y,siblingCards:_};let S=new Set;for(let[x,k]of d.data.pages.entries()){let N=c&&x>0?new Set(k.messages.map(C=>C.path)):null;for(let[C,O]of k.messageCards)if(!(N&&!N.has(C)))for(let T of O){if(S.has(T.id))continue;S.add(T.id);let E=y.get(C)||[];E.push(T),y.set(C,E)}if(!(c&&x>0))for(let C of k.siblingCards)S.has(C.id)||(S.add(C.id),_.push(C))}return{messageCards:y,siblingCards:_}},[d.data?.pages,c]),v=L(),g=(0,b.useRef)(null),w=(0,b.useMemo)(()=>[...I.channelMessages(n||"",r),"infinite",s,"latest-first",...a?["conversations"]:[],...c?["transcript"]:[]],[n,r,s,a,c,t]);return(0,b.useEffect)(()=>{if(!i||!n||!l)return;if(c)return Dc(v,w,n,s);let y=()=>void le(v,w,{exact:!0}),_=!1,S=!1,x=!1,k=async()=>{if(a){y();return}let O=v.getQueryData(w);if(!O?.pages?.length){y();return}let T=0;for(let E of O.pages)for(let A of E.messages)A.seq>T&&(T=A.seq);if(T===0){y();return}try{let E=await Xt(n,{parentMessageId:r,limit:s,after_seq:T});if(E.messages.length===0&&E.siblingCards.length===0){y();return}if(E.messages.length>0){let A=Math.min(...E.messages.map(F=>F.seq));if(A>T+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${T}, minNewSeq=${A}. Triggering full refetch.`),y();return}}v.setQueryData(w,A=>{if(!A)return A;let F=[...A.pages],U=0,j=F[U],Me=new Set(j.messages.map(ge=>ge.id)),H=E.messages.filter(ge=>!Me.has(ge.id)),me=[...j.messages,...H].sort((ge,js)=>ge.seq-js.seq),ve=new Map(j.messageCards);for(let[ge,js]of E.messageCards){let ho=ve.get(ge)||[],zl=new Set(ho.map(Bs=>Bs.id)),Jl=js.filter(Bs=>!zl.has(Bs.id));ve.set(ge,[...ho,...Jl])}let Ue=new Set(j.siblingCards.map(ge=>ge.id)),ce=E.siblingCards.filter(ge=>!Ue.has(ge.id)),pe=[...j.siblingCards,...ce];return F[U]={...j,activityMessages:E.activityMessages??[],messages:me,messageCards:ve,siblingCards:pe},{...A,pages:F}})}catch(E){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",E),y()}},N=async()=>{if(_){S=!0;return}_=!0;try{do S=!1,await k();while(S&&!x)}finally{_=!1}},C=J("vfs_change",()=>{g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{N()},500)},O=>a&&O?.item_type==="message"&&(v.getQueryData(w)?.pages??[]).some(T=>T.messages.some(E=>E.id===O.parent_id))||$n(O,n,r,v.getQueryData(w)?.pages.flatMap(T=>T.messages)??[]));return()=>{x=!0,C(),g.current&&clearTimeout(g.current)}},[i,n,l,w,v,r,s,a,c]),{messages:h,activityMessages:d.data?.pages[0]?.activityMessages??[],messageCards:f,siblingCards:m,threads:h.filter(y=>y.reply_count>0),breakouts:h.filter(y=>y.member_count>0),isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,refetch:d.refetch,hasPreviousPage:d.hasNextPage??!1,fetchPreviousPage:d.fetchNextPage,isFetchingPreviousPage:d.isFetchingNextPage??!1,hasNextPage:d.hasPreviousPage??!1,fetchNextPage:d.fetchPreviousPage,isFetchingNextPage:d.isFetchingPreviousPage??!1}}var Nu=["open","active","strict","hand_raise"];function Rp(e){return e==="open"||e==="active"||e==="strict"||e==="hand_raise"?e:e==="on"||e==="auto"?"active":"strict"}function Cp(e){if(Array.isArray(e))return e.filter(t=>typeof t=="string")}function Gc(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:Rp(t.ai_mode),activeAgentIds:Cp(t.active_agent_ids),isPrivate:t.is_private||!1,isDm:t.is_dm||!1,messageCount:t.message_count||0,createdAt:e.created_at||"",updatedAt:e.updated_at||"",chatScopePath:r.context_path||"",contextId:e.scope_item_id||"",contextPath:r.context_path||"",contextType:r.context_type||"",contextName:r.context_name||"",contextDisplayName:r.context_name||"",contextPrincipalId:void 0,accountId:e.account_item_id||"",accountPath:"",accountDisplayName:"",memberRole:n.member_role||"member",memberPath:"",modePath:"",autoPilot:t.auto_pilot||!1,isArchived:t.is_archived===!0}}function Ns(e={}){let t=te(),{realtime:n=!0,enabled:r=!0,includeArchived:s=!1}=e,i=L(),o=(0,b.useMemo)(()=>I.channels("all"),[t]),a=W({queryKey:o,queryFn:async()=>((await R("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(Gc),enabled:r});return(0,b.useEffect)(()=>{if(!(!n||!r))return Kc(i,o,Gc)},[n,r,o,i]),{channels:(0,b.useMemo)(()=>(a.data??[]).filter(u=>s||!u.isArchived),[a.data,s]),isLoading:a.isLoading,isFetching:a.isFetching,error:a.error,refetch:a.refetch}}function Qu(e={}){let t=Ns(e),n=(0,b.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function Du(e={}){let t=Ns(e),n=(0,b.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function Yi(e={}){let t=te(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=e,o=L(),a=(0,b.useRef)(null),c=(0,b.useMemo)(()=>I.notifications(n,r),[n,r,t]),u=W({queryKey:c,queryFn:async()=>{let d={limit:r};return n==="unread"&&(d.filter="unread"),(await R("get-notifications",d)).notifications||[]},enabled:i});return(0,b.useEffect)(()=>{if(!s||!i)return;let d=["vfs_change","ccm_change"].map(h=>J(h,()=>{a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{o.invalidateQueries({queryKey:c})},2e3)},f=>f.item_type==="notification"&&ks(f)));return()=>{d.forEach(h=>h()),a.current&&clearTimeout(a.current)}},[s,i,c,o]),{notifications:u.data??[],isLoading:u.isLoading,isFetching:u.isFetching,error:u.error,refetch:u.refetch}}function Uu(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:o,error:a,refetch:c}=Yi({filter:"unread",limit:200,realtime:n,enabled:r}),u=(0,b.useMemo)(()=>{let f=new Map;for(let m of s)m.is_unread&&m.channel_id&&f.set(m.channel_id,(f.get(m.channel_id)||0)+1);return f},[s]),l=(0,b.useMemo)(()=>{let f=0;return u.forEach(m=>{f+=m}),f},[u]),{dmUnread:d,channelUnread:h}=(0,b.useMemo)(()=>{if(!t)return{dmUnread:0,channelUnread:0};let f=new Set(t.filter(g=>g.isDm).map(g=>g.id)),m=0,v=0;return u.forEach((g,w)=>{f.has(w)?m+=g:v+=g}),{dmUnread:m,channelUnread:v}},[t,u]);return{unreadByChannel:u,totalUnread:l,dmUnread:d,channelUnread:h,isLoading:i,isFetching:o,error:a,refetch:c}}function Ku(){let e=L();return ie({mutationFn:t=>R("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:I.children(r)})}})}function Lu(){let e=L();return ie({mutationFn:t=>R("update",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.invalidateQueries({queryKey:I.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:I.children(i)})}}})}function Hu(){return ie({mutationFn:e=>R("update-principal",e),onSuccess:(e,t)=>{if(!_e)return;let n=e&&typeof e=="object"&&e.metadata?e.metadata:{..._e.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}:{}};_e={..._e,displayName:typeof t.display_name=="string"?t.display_name:_e.displayName,metadata:n},xp()}})}function ju(){let e=L();return ie({mutationFn:t=>R("delete",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.removeQueries({queryKey:I.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:I.children(i)})}}})}function Bu(){let e=L();return ie({mutationFn:t=>R("move",t),onSuccess:(t,n)=>{let r=n.path,s=n.new_parent_path;if(r){e.invalidateQueries({queryKey:I.item(r)});let i=r.split("/");i.pop();let o=i.join("/");o&&e.invalidateQueries({queryKey:I.children(o)})}s&&e.invalidateQueries({queryKey:I.children(s)})}})}function Vu(){let e=L();return ie({mutationFn:t=>R("link",t),onSuccess:(t,n)=>{let r=n.source_id,s=n.target_id;r&&e.invalidateQueries({queryKey:I.edges(r)}),s&&e.invalidateQueries({queryKey:I.edges(s)})}})}function Wu(e,t){let n=L(),{optimistic:r,...s}=t??{};return ie({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 $u(e,t,n){let r,s,i,o=!0;if(typeof e=="string")r=e,s=t,i=n;else{s=e;let u=t;r=u.eventType,i=u.filter,o=u.enabled??!0}let a=(0,b.useRef)(s),c=(0,b.useRef)(i);(0,b.useEffect)(()=>{a.current=s,c.current=i},[s,i]),(0,b.useEffect)(()=>o?J(r,l=>a.current(l),c.current?l=>c.current(l):void 0):void 0,[r,o])}function Gu(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:o=500}=e,a=L(),c=(0,b.useRef)(s);c.current=s;let u=(0,b.useRef)(null),l=W({queryKey:t,queryFn:n,enabled:i});return(0,b.useEffect)(()=>{if(!i)return;let d=J(r,()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{le(a,t,{exact:!0})},o)},h=>c.current?.(h)??!0);return()=>{d(),u.current&&clearTimeout(u.current)}},[r,i,o,a,JSON.stringify(t)]),l}function zn(e){te();let t=z(),n=(0,b.useMemo)(()=>e?typeof e=="string"?{path:e}:e:null,[typeof e=="string"?e:JSON.stringify(e)]),r=n?._scope_path??t,s=!!t&&!!r&&!!n&&!!(n.key||n.path||n.item_id),i=n?.key??n?.path??n?.item_id??"",o=["vfs",r??"__unscoped__","arrangement",i,n?.scope_id??""],a=W({queryKey:o,staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0},queryFn:async()=>{if(!n)return null;let f=await R("resolve-arrangement",{...n,_scope_path:r});if(f?.success===!1)throw new Error(f?.error||"Arrangement could not be loaded");return f??null},enabled:s}),c=a.data??null,u=(0,b.useMemo)(()=>c?.resolved_children??[],[c]),l=c?.resolution_level??null,d=(0,b.useMemo)(()=>{let m=(c?.type_data??null)?.order;return Array.isArray(m)?m:null},[c]),h=(0,b.useCallback)(f=>{if(!d||!f?.length)return f??[];let m=y=>y.id??y.name??"",v=new Map(d.map((y,_)=>[y,_])),g=[],w=[];for(let y of f)(v.has(m(y))?g:w).push(y);return g.sort((y,_)=>v.get(m(y))-v.get(m(_))),[...g,...w]},[d]);return{...a,arrangement:c,resolvedChildren:u,resolutionLevel:l,order:d,sourceScopeId:c?.scope_item_id??null,arrangementQueryKey:o,applyTo:h}}function zu(e){let{origin:t,originField:n,fallbackUrl:r,mintError:s,scopeId:i,scopePath:o}=e,a=te(),c=Ct(),u=i??c?.scope_id??null,l=(0,b.useMemo)(()=>{if(!t)return null;let x="/accounts/",k=t.indexOf(x);if(k===-1)return null;let N=t.indexOf("/",k+x.length);return N===-1?t:t.slice(0,N)},[t]),d=o??l??c?.scope_path??null,h=n?.trim()||null,f=`${a}
1
+ /* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-11-16T03:22:12.555Z */
2
+ "use strict";var __FSAOS_GATEWAY__=(()=>{var td=Object.create;var Zn=Object.defineProperty;var nd=Object.getOwnPropertyDescriptor;var rd=Object.getOwnPropertyNames;var sd=Object.getPrototypeOf,id=Object.prototype.hasOwnProperty;var yo=e=>{throw TypeError(e)};var od=(e,t,n)=>t in e?Zn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var er=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),_o=(e,t)=>{for(var n in t)Zn(e,n,{get:t[n],enumerable:!0})},vo=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of rd(t))!id.call(e,s)&&s!==n&&Zn(e,s,{get:()=>t[s],enumerable:!(r=nd(t,s))||r.enumerable});return e};var ne=(e,t,n)=>(n=e!=null?td(sd(e)):{},vo(t||!e||!e.__esModule?Zn(n,"default",{value:e,enumerable:!0}):n,e)),ad=e=>vo(Zn({},"__esModule",{value:!0}),e);var X=(e,t,n)=>od(e,typeof t!="symbol"?t+"":t,n),Vs=(e,t,n)=>t.has(e)||yo("Cannot "+n);var p=(e,t,n)=>(Vs(e,t,"read from private field"),n?n.call(e):t.get(e)),k=(e,t,n)=>t.has(e)?yo("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),C=(e,t,n,r)=>(Vs(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),q=(e,t,n)=>(Vs(e,t,"access private method"),n);var tr=(e,t,n,r)=>({set _(s){C(e,t,s,n)},get _(){return p(e,t,r)}});var fe=er((sf,bo)=>{bo.exports=React});var Gr=er((ng,ea)=>{ea.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var fa=er((Og,pa)=>{pa.exports={createClient:window.supabase.createClient}});var Ha=er((Yg,ja)=>{ja.exports=ReactDOM});var _l=er((c_,yl)=>{yl.exports=ReactDOM});var go={};_o(go,{CHANNEL_AI_MODES:()=>Nu,ComponentRenderer:()=>ku,EnforcementDeniedError:()=>Ke,FormSubmissionError:()=>Xn,GatewayRequestError:()=>Se,HostSessionUnavailableError:()=>$t,InteractionTrackingError:()=>Jn,KernelProvider:()=>Mu,QueryClientProvider:()=>fr,acceptInvitation:()=>jp,acceptInvite:()=>so,answerInput:()=>ao,assignPersonalSection:()=>Jl,auth:()=>Il,awaitAnchorReady:()=>yr,awaitScopeReady:()=>Pa,callTool:()=>Pl,cancelInvitation:()=>Bp,cancelQueuedTurn:()=>dl,cancelTurn:()=>ul,clearCachedToken:()=>vi,clearSession:()=>Ei,configureGatewayReads:()=>Qa,connectHostSession:()=>Ea,createAgent:()=>oo,createInvitation:()=>Kp,createItem:()=>Sl,disconnectSSE:()=>Ui,disposeVfsRealtimeWs:()=>Li,electHomeAnchor:()=>Vt,emitEvent:()=>lc,fetchChannelMessages:()=>xc,fetchChannelMessagesPage:()=>Xt,fetchChannelMessagesWithCards:()=>Cs,fetchEdgesForItem:()=>bs,fetchItemHistory:()=>xs,fetchItemVersions:()=>Cr,fetchItems:()=>Yt,fetchMemberFocus:()=>Rs,fetchMessageReplies:()=>Ps,fetchMessageReplyContexts:()=>wc,fetchOpenEnvelope:()=>Er,fetchRecentActivity:()=>Ss,fetchResolvedItems:()=>lo,fetchTimelineHistory:()=>po,fetchTurnQueueEntries:()=>yc,fetchTypeDefinitions:()=>vs,fetchVfsChildren:()=>Pr,fetchVfsChildrenPage:()=>_s,fetchVfsItem:()=>Rr,fetchVfsItemById:()=>xr,fetchVfsTree:()=>ws,filePurchaseNextUrl:()=>hl,funnelCheckoutLink:()=>gl,gatewayCall:()=>R,getAccessToken:()=>at,getAnchor:()=>Rt,getAnchorRef:()=>ye,getAnchorVersion:()=>Si,getAssetUrl:()=>El,getDefaultSort:()=>Ql,getFilePurchase:()=>ml,getHomeAnchor:()=>we,getInvitation:()=>Lp,getMountVersion:()=>_r,getMounts:()=>qe,getPathSubscriptionState:()=>pc,getQueryClient:()=>Q,getRequiredFormFields:()=>Dl,getScope:()=>z,getScopeVersion:()=>G,getServerClockOffsetMs:()=>Ma,getServerClockSyncedAt:()=>Oa,getSessionEntry:()=>Pt,hasServerClock:()=>ka,initSession:()=>ct,initVfsRealtimeWs:()=>Zt,initializeFsaos:()=>al,initializeWorkspace:()=>Us,interpretSchema:()=>co,invalidateAllVfs:()=>Cc,invalidateChannelMessages:()=>Ic,invalidateChildren:()=>ys,invalidateItem:()=>Ki,invalidateOpenEnvelope:()=>Tc,invalidatePathAndParent:()=>Rc,invalidateSubtree:()=>Pc,invalidateTypes:()=>Ec,inviteMember:()=>ro,isAnchorReady:()=>Ri,isChannelPath:()=>de,isListableItemsFilter:()=>Hn,isScopeReady:()=>ts,itemsFilterFromQueryFilter:()=>_c,listChildren:()=>wl,listInvitations:()=>Wp,loadMounts:()=>en,loadPublishedBundle:()=>xu,mount:()=>Tl,mountRealtimeScope:()=>Vn,normalizeItem:()=>De,onConnectionStateChange:()=>hs,pathSubscriptionMatches:()=>Ni,personalSectionsKey:()=>Dr,ping:()=>dc,pushChanges:()=>Rl,queryClient:()=>Ja,readItem:()=>bl,refreshQuery:()=>le,registerCleanup:()=>oe,rejectInvitation:()=>Hp,replaceMounts:()=>ks,resendInvitation:()=>Vp,resetAllSdkState:()=>On,resolvePrincipalId:()=>Tu,resubscribePath:()=>mc,seatMember:()=>io,selectMount:()=>Mr,sendMessage:()=>bc,serveHostSession:()=>cl,serverDeadlinePassed:()=>Fa,serverMsUntil:()=>qa,serverNow:()=>ss,setAnchor:()=>Mn,setCachedToken:()=>ha,setQueryClient:()=>za,setScope:()=>Ra,setupRequireShim:()=>Al,signal:()=>Cl,startFileCheckout:()=>fl,startTracking:()=>Ds,steerTurn:()=>ll,submitForm:()=>pl,subscribeAnchor:()=>xi,subscribeArtifactStream:()=>Ks,subscribeMounts:()=>es,subscribeScope:()=>Ie,subscribeToEvents:()=>J,subscribeToPath:()=>gs,subscribeToScope:()=>Ln,trackAction:()=>sl,trackEvent:()=>nn,trackPageView:()=>rl,unmountRealtimeScope:()=>Ts,updateItem:()=>xl,uploadFile:()=>Ll,useAcceptInvite:()=>Ml,useAccounts:()=>mu,useAgentTimeline:()=>$l,useAllChannels:()=>Ns,useAnswerInput:()=>ql,useArrangement:()=>zn,useArtifactStream:()=>Wl,useAsset:()=>hu,useAuth:()=>qs,useChannelMessages:()=>Ou,useChannels:()=>Qu,useChildren:()=>Xc,useComponent:()=>Ji,useCreate:()=>Ku,useCreateAgent:()=>Fl,useDelete:()=>Hu,useDmChannels:()=>Du,useEdges:()=>iu,useEventStream:()=>$u,useFileUpload:()=>Hl,useIncrementalItems:()=>ru,useInfiniteChannelMessages:()=>qu,useInfiniteChildren:()=>su,useInfiniteItems:()=>zi,useInviteMember:()=>kl,useItem:()=>Jc,useItemById:()=>Yc,useItemHistory:()=>du,useItemVersions:()=>lu,useItems:()=>nu,useLink:()=>Vu,useList:()=>Gi,useMemberFocus:()=>uu,useMessageReplies:()=>Fu,useMintedAsset:()=>zu,useMounts:()=>gu,useMove:()=>Bu,useMutation:()=>Wu,useNotifications:()=>Yi,useOpen:()=>au,usePermission:()=>Cu,usePermissions:()=>Eu,usePersonalItemOrder:()=>Yu,usePersonalSections:()=>Xl,usePinnedItems:()=>zl,usePrincipal:()=>Au,usePublishedComponent:()=>Ru,useRealtimeQuery:()=>Gu,useRecentActivity:()=>pu,useResolve:()=>tu,useResolvedItems:()=>Vl,useScope:()=>fu,useScopeReady:()=>zc,useSearch:()=>eu,useSeatMember:()=>Ol,useTheme:()=>Pu,useTimelineHistory:()=>Gl,useTree:()=>Zc,useType:()=>ou,useTypeHelpers:()=>cu,useTypes:()=>Fs,useUnreadCounts:()=>Uu,useUpdate:()=>Lu,useUpdatePrincipal:()=>ju,vfsKeys:()=>I,waitForPathReady:()=>fc});var Ke=class e extends Error{constructor(n){let r=n.message||e.fallbackMessage(n);super(r);X(this,"name","EnforcementDeniedError");X(this,"deniedBy");X(this,"ruleKey");X(this,"displayName");X(this,"payload");this.payload=n,this.deniedBy=n.denied_by||n.error_type||n.error||"unknown";let s=n.enforcement;this.ruleKey=s?.rule_key??void 0,this.displayName=s?.display_name??void 0}static fallbackMessage(n){let r=n.error||"",s=n.denied_by||"";return s==="rule"||r==="RULE_DENIED"?"This feature is not enabled for this workspace.":s==="entitlement"||r==="ENTITLEMENT_REQUIRED"?"This feature requires a plan upgrade.":s==="access"||r==="ACCESS_DENIED"||r==="PERMISSION_DENIED"?"You don't have permission to do this.":"This action is not allowed."}get isRuleDenial(){return this.deniedBy==="rule"||this.deniedBy==="RULE_DENIED"}get isAccessDenial(){return this.deniedBy==="access"||this.deniedBy==="ACCESS_DENIED"}get isEntitlementDenial(){return this.deniedBy==="entitlement"||this.deniedBy==="ENTITLEMENT_REQUIRED"}};var kt=ne(fe(),1);var Me=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 Ot,ft,sn,wo,cd=(wo=class extends Me{constructor(){super();k(this,Ot);k(this,ft);k(this,sn);C(this,sn,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){p(this,ft)||this.setEventListener(p(this,sn))}onUnsubscribe(){var t;this.hasListeners()||((t=p(this,ft))==null||t.call(this),C(this,ft,void 0))}setEventListener(t){var n;C(this,sn,t),(n=p(this,ft))==null||n.call(this),C(this,ft,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){p(this,Ot)!==t&&(C(this,Ot,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof p(this,Ot)=="boolean"?p(this,Ot):globalThis.document?.visibilityState!=="hidden"}},Ot=new WeakMap,ft=new WeakMap,sn=new WeakMap,wo),on=new cd;var ud={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},mt,Ws,So,ld=(So=class{constructor(){k(this,mt,ud);k(this,Ws,!1)}setTimeoutProvider(e){C(this,mt,e)}setTimeout(e,t){return p(this,mt).setTimeout(e,t)}clearTimeout(e){p(this,mt).clearTimeout(e)}setInterval(e,t){return p(this,mt).setInterval(e,t)}clearInterval(e){p(this,mt).clearInterval(e)}},mt=new WeakMap,Ws=new WeakMap,So),Be=new ld;function xo(e){setTimeout(e,0)}var Gs=typeof window>"u"||"Deno"in globalThis;function re(){}function Co(e,t){return typeof e=="function"?e(t):e}function nr(e){return typeof e=="number"&&e>=0&&e!==1/0}function Ur(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Le(e,t){return typeof e=="function"?e(t):e}function Re(e,t){return typeof e=="function"?e(t):e}function Kr(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:o,stale:a}=e;if(o){if(r){if(t.queryHash!==rr(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 Lr(e,t){let{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Ve(t.options.mutationKey)!==Ve(i))return!1}else if(!Ft(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function rr(e,t){return(t?.queryKeyHashFn||Ve)(e)}function Ve(e){return JSON.stringify(e,(t,n)=>$s(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 dd=Object.prototype.hasOwnProperty;function zs(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=Ro(e)&&Ro(t);if(!r&&!($s(e)&&$s(t)))return t;let i=(r?e:Object.keys(e)).length,o=r?t:Object.keys(t),a=o.length,c=r?new Array(a):{},u=0;for(let l=0;l<a;l++){let d=r?l:o[l],h=e[d],f=t[d];if(h===f){c[d]=h,(r?l<i:dd.call(e,d))&&u++;continue}if(h===null||f===null||typeof h!="object"||typeof f!="object"){c[d]=f;continue}let m=zs(h,f,n+1);c[d]=m,m===h&&u++}return i===a&&u===i?e:c}function an(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 Ro(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function $s(e){if(!Po(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Po(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Po(e){return Object.prototype.toString.call(e)==="[object Object]"}function Eo(e){return new Promise(t=>{Be.setTimeout(t,e)})}function sr(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?zs(e,t):t}function Io(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function To(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var cn=Symbol();function jr(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===cn?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function un(e,t){return typeof e=="function"?e(...t):!!e}function Ao(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 We=(()=>{let e=()=>Gs;return{isServer(){return e()},setIsServer(t){e=t}}})();function ir(){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 ko=xo;function pd(){let e=[],t=0,n=a=>{a()},r=a=>{a()},s=ko,i=a=>{t?e.push(a):s(()=>{n(a)})},o=()=>{let a=e;e=[],a.length&&s(()=>{r(()=>{a.forEach(c=>{n(c)})})})};return{batch:a=>{let c;t++;try{c=a()}finally{t--,t||o()}return c},batchCalls:a=>(...c)=>{i(()=>{a(...c)})},schedule:i,setNotifyFunction:a=>{n=a},setBatchNotifyFunction:a=>{r=a},setScheduler:a=>{s=a}}}var V=pd();var ln,gt,dn,Mo,fd=(Mo=class extends Me{constructor(){super();k(this,ln,!0);k(this,gt);k(this,dn);C(this,dn,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(){p(this,gt)||this.setEventListener(p(this,dn))}onUnsubscribe(){var t;this.hasListeners()||((t=p(this,gt))==null||t.call(this),C(this,gt,void 0))}setEventListener(t){var n;C(this,dn,t),(n=p(this,gt))==null||n.call(this),C(this,gt,t(this.setOnline.bind(this)))}setOnline(t){p(this,ln)!==t&&(C(this,ln,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return p(this,ln)}},ln=new WeakMap,gt=new WeakMap,dn=new WeakMap,Mo),pn=new fd;function md(e){return Math.min(1e3*2**e,3e4)}function Js(e){return(e??"online")==="online"?pn.isOnline():!0}var Hr=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Br(e){let t=!1,n=0,r,s=ir(),i=()=>s.status!=="pending",o=v=>{if(!i()){let g=new Hr(v);h(g),e.onCancel?.(g)}},a=()=>{t=!0},c=()=>{t=!1},u=()=>on.isFocused()&&(e.networkMode==="always"||pn.isOnline())&&e.canRun(),l=()=>Js(e.networkMode)&&e.canRun(),d=v=>{i()||(r?.(),s.resolve(v))},h=v=>{i()||(r?.(),s.reject(v))},f=()=>new Promise(v=>{r=g=>{(i()||u())&&v(g)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),m=()=>{if(i())return;let v,g=n===0?e.initialPromise:void 0;try{v=g??e.fn()}catch(w){v=Promise.reject(w)}Promise.resolve(v).then(d).catch(w=>{if(i())return;let y=e.retry??(We.isServer()?0:3),_=e.retryDelay??md,S=typeof _=="function"?_(n,w):_,x=y===!0||typeof y=="number"&&n<y||typeof y=="function"&&y(n,w);if(t||!x){h(w);return}n++,e.onFail?.(n,w),Eo(S).then(()=>u()?void 0:f()).then(()=>{t?h(w):m()})})};return{promise:s,status:()=>s.status,cancel:o,continue:()=>(r?.(),s),cancelRetry:a,continueRetry:c,canStart:l,start:()=>(l()?m():f().then(m),s)}}var qt,Oo,Vr=(Oo=class{constructor(){k(this,qt)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),nr(this.gcTime)&&C(this,qt,Be.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(We.isServer()?1/0:5*60*1e3))}clearGcTimeout(){p(this,qt)!==void 0&&(Be.clearTimeout(p(this,qt)),C(this,qt,void 0))}},qt=new WeakMap,Oo);var Nt,fn,Oe,Qt,ue,or,Dt,Ee,Do,Ze,No,Qo=(No=class extends Vr{constructor(t){super();k(this,Ee);k(this,Nt);k(this,fn);k(this,Oe);k(this,Qt);k(this,ue);k(this,or);k(this,Dt);C(this,Dt,!1),C(this,or,t.defaultOptions),this.setOptions(t.options),this.observers=[],C(this,Qt,t.client),C(this,Oe,p(this,Qt).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,C(this,Nt,qo(this.options)),this.state=t.state??p(this,Nt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return p(this,ue)?.promise}setOptions(t){if(this.options={...p(this,or),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=qo(this.options);n.data!==void 0&&(this.setState(Fo(n.data,n.dataUpdatedAt)),C(this,Nt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&p(this,Oe).remove(this)}setData(t,n){let r=sr(this.state.data,t,this.options);return q(this,Ee,Ze).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){q(this,Ee,Ze).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=p(this,ue)?.promise;return p(this,ue)?.cancel(t),n?n.then(re).catch(re):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return p(this,Nt)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>Re(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===cn||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>Le(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:!Ur(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),p(this,ue)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),p(this,ue)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),p(this,Oe).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(p(this,ue)&&(p(this,Dt)||q(this,Ee,Do).call(this)?p(this,ue).cancel({revert:!0}):p(this,ue).cancelRetry()),this.scheduleGc()),p(this,Oe).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||q(this,Ee,Ze).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&p(this,ue)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(p(this,ue))return p(this,ue).continueRetry(),p(this,ue).promise}if(t&&this.setOptions(t),!this.options.queryFn){let c=this.observers.find(u=>u.options.queryFn);c&&this.setOptions(c.options)}let r=new AbortController,s=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(C(this,Dt,!0),r.signal)})},i=()=>{let c=jr(this.options,n),l=(()=>{let d={client:p(this,Qt),queryKey:this.queryKey,meta:this.meta};return s(d),d})();return C(this,Dt,!1),this.options.persister?this.options.persister(c,l,this):c(l)},a=(()=>{let c={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:p(this,Qt),state:this.state,fetchFn:i};return s(c),c})();this.options.behavior?.onFetch(a,this),C(this,fn,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&q(this,Ee,Ze).call(this,{type:"fetch",meta:a.fetchOptions?.meta}),C(this,ue,Br({initialPromise:n?.initialPromise,fn:a.fetchFn,onCancel:c=>{c instanceof Hr&&c.revert&&this.setState({...p(this,fn),fetchStatus:"idle"}),r.abort()},onFail:(c,u)=>{q(this,Ee,Ze).call(this,{type:"failed",failureCount:c,error:u})},onPause:()=>{q(this,Ee,Ze).call(this,{type:"pause"})},onContinue:()=>{q(this,Ee,Ze).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0}));try{let c=await p(this,ue).start();if(c===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(c),p(this,Oe).config.onSuccess?.(c,this),p(this,Oe).config.onSettled?.(c,this.state.error,this),c}catch(c){if(c instanceof Hr){if(c.silent)return p(this,ue).promise;if(c.revert){if(this.state.data===void 0)throw c;return this.state.data}}throw q(this,Ee,Ze).call(this,{type:"error",error:c}),p(this,Oe).config.onError?.(c,this),p(this,Oe).config.onSettled?.(this.state.data,c,this),c}finally{this.scheduleGc()}}},Nt=new WeakMap,fn=new WeakMap,Oe=new WeakMap,Qt=new WeakMap,ue=new WeakMap,or=new WeakMap,Dt=new WeakMap,Ee=new WeakSet,Do=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},Ze=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,...Ys(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...Fo(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return C(this,fn,t.manual?s:void 0),s;case"error":let i=t.error;return{...r,error:i,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),V.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),p(this,Oe).notify({query:this,type:"updated",action:t})})},No);function Ys(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Js(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Fo(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function qo(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 Pe,K,cr,be,Ut,mn,et,ht,ur,gn,hn,Kt,Lt,yt,yn,B,ar,Xs,Zs,ei,ti,ni,ri,si,jo,Lo,lr=(Lo=class extends Me{constructor(t,n){super();k(this,B);k(this,Pe);k(this,K);k(this,cr);k(this,be);k(this,Ut);k(this,mn);k(this,et);k(this,ht);k(this,ur);k(this,gn);k(this,hn);k(this,Kt);k(this,Lt);k(this,yt);k(this,yn,new Set);this.options=n,C(this,Pe,t),C(this,ht,null),C(this,et,ir()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(p(this,K).addObserver(this),Uo(p(this,K),this.options)?q(this,B,ar).call(this):this.updateResult(),q(this,B,ti).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return ii(p(this,K),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return ii(p(this,K),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,q(this,B,ni).call(this),q(this,B,ri).call(this),p(this,K).removeObserver(this)}setOptions(t){let n=this.options,r=p(this,K);if(this.options=p(this,Pe).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Re(this.options.enabled,p(this,K))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");q(this,B,si).call(this),p(this,K).setOptions(this.options),n._defaulted&&!an(this.options,n)&&p(this,Pe).getQueryCache().notify({type:"observerOptionsUpdated",query:p(this,K),observer:this});let s=this.hasListeners();s&&Ko(p(this,K),r,this.options,n)&&q(this,B,ar).call(this),this.updateResult(),s&&(p(this,K)!==r||Re(this.options.enabled,p(this,K))!==Re(n.enabled,p(this,K))||Le(this.options.staleTime,p(this,K))!==Le(n.staleTime,p(this,K)))&&q(this,B,Xs).call(this);let i=q(this,B,Zs).call(this);s&&(p(this,K)!==r||Re(this.options.enabled,p(this,K))!==Re(n.enabled,p(this,K))||i!==p(this,yt))&&q(this,B,ei).call(this,i)}getOptimisticResult(t){let n=p(this,Pe).getQueryCache().build(p(this,Pe),t),r=this.createResult(n,t);return hd(this,r)&&(C(this,be,r),C(this,mn,this.options),C(this,Ut,p(this,K).state)),r}getCurrentResult(){return p(this,be)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&p(this,et).status==="pending"&&p(this,et).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){p(this,yn).add(t)}getCurrentQuery(){return p(this,K)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=p(this,Pe).defaultQueryOptions(t),r=p(this,Pe).getQueryCache().build(p(this,Pe),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return q(this,B,ar).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),p(this,be)))}createResult(t,n){let r=p(this,K),s=this.options,i=p(this,be),o=p(this,Ut),a=p(this,mn),u=t!==r?t.state:p(this,cr),{state:l}=t,d={...l},h=!1,f;if(n._optimisticResults){let O=this.hasListeners(),T=!O&&Uo(t,n),E=O&&Ko(t,r,n,s);(T||E)&&(d={...d,...Ys(l.data,t.options)}),n._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:m,errorUpdatedAt:v,status:g}=d;f=d.data;let w=!1;if(n.placeholderData!==void 0&&f===void 0&&g==="pending"){let O;i?.isPlaceholderData&&n.placeholderData===a?.placeholderData?(O=i.data,w=!0):O=typeof n.placeholderData=="function"?n.placeholderData(p(this,hn)?.state.data,p(this,hn)):n.placeholderData,O!==void 0&&(g="success",f=sr(i?.data,O,n),h=!0)}if(n.select&&f!==void 0&&!w)if(i&&f===o?.data&&n.select===p(this,ur))f=p(this,gn);else try{C(this,ur,n.select),f=n.select(f),f=sr(i?.data,f,n),C(this,gn,f),C(this,ht,null)}catch(O){C(this,ht,O)}p(this,ht)&&(m=p(this,ht),f=p(this,gn),v=Date.now(),g="error");let y=d.fetchStatus==="fetching",_=g==="pending",S=g==="error",x=_&&y,M=f!==void 0,P={status:g,fetchStatus:d.fetchStatus,isPending:_,isSuccess:g==="success",isError:S,isInitialLoading:x,isLoading:x,data:f,dataUpdatedAt:d.dataUpdatedAt,error:m,errorUpdatedAt:v,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:d.dataUpdateCount>u.dataUpdateCount||d.errorUpdateCount>u.errorUpdateCount,isFetching:y,isRefetching:y&&!_,isLoadingError:S&&!M,isPaused:d.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:S&&M,isStale:oi(t,n),refetch:this.refetch,promise:p(this,et),isEnabled:Re(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let O=P.data!==void 0,T=P.status==="error"&&!O,E=U=>{T?U.reject(P.error):O&&U.resolve(P.data)},A=()=>{let U=C(this,et,P.promise=ir());E(U)},F=p(this,et);switch(F.status){case"pending":t.queryHash===r.queryHash&&E(F);break;case"fulfilled":(T||P.data!==F.value)&&A();break;case"rejected":(!T||P.error!==F.reason)&&A();break}}return P}updateResult(){let t=p(this,be),n=this.createResult(p(this,K),this.options);if(C(this,Ut,p(this,K).state),C(this,mn,this.options),p(this,Ut).data!==void 0&&C(this,hn,p(this,K)),an(n,t))return;C(this,be,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!p(this,yn).size)return!0;let o=new Set(i??p(this,yn));return this.options.throwOnError&&o.add("error"),Object.keys(p(this,be)).some(a=>{let c=a;return p(this,be)[c]!==t[c]&&o.has(c)})};q(this,B,jo).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&q(this,B,ti).call(this)}},Pe=new WeakMap,K=new WeakMap,cr=new WeakMap,be=new WeakMap,Ut=new WeakMap,mn=new WeakMap,et=new WeakMap,ht=new WeakMap,ur=new WeakMap,gn=new WeakMap,hn=new WeakMap,Kt=new WeakMap,Lt=new WeakMap,yt=new WeakMap,yn=new WeakMap,B=new WeakSet,ar=function(t){q(this,B,si).call(this);let n=p(this,K).fetch(this.options,t);return t?.throwOnError||(n=n.catch(re)),n},Xs=function(){q(this,B,ni).call(this);let t=Le(this.options.staleTime,p(this,K));if(We.isServer()||p(this,be).isStale||!nr(t))return;let r=Ur(p(this,be).dataUpdatedAt,t)+1;C(this,Kt,Be.setTimeout(()=>{p(this,be).isStale||this.updateResult()},r))},Zs=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(p(this,K)):this.options.refetchInterval)??!1},ei=function(t){q(this,B,ri).call(this),C(this,yt,t),!(We.isServer()||Re(this.options.enabled,p(this,K))===!1||!nr(p(this,yt))||p(this,yt)===0)&&C(this,Lt,Be.setInterval(()=>{(this.options.refetchIntervalInBackground||on.isFocused())&&q(this,B,ar).call(this)},p(this,yt)))},ti=function(){q(this,B,Xs).call(this),q(this,B,ei).call(this,q(this,B,Zs).call(this))},ni=function(){p(this,Kt)!==void 0&&(Be.clearTimeout(p(this,Kt)),C(this,Kt,void 0))},ri=function(){p(this,Lt)!==void 0&&(Be.clearInterval(p(this,Lt)),C(this,Lt,void 0))},si=function(){let t=p(this,Pe).getQueryCache().build(p(this,Pe),this.options);if(t===p(this,K))return;let n=p(this,K);C(this,K,t),C(this,cr,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},jo=function(t){V.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(p(this,be))}),p(this,Pe).getQueryCache().notify({query:p(this,K),type:"observerResultsUpdated"})})},Lo);function gd(e,t){return Re(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Uo(e,t){return gd(e,t)||e.state.data!==void 0&&ii(e,t,t.refetchOnMount)}function ii(e,t,n){if(Re(t.enabled,e)!==!1&&Le(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&oi(e,t)}return!1}function Ko(e,t,n,r){return(e!==t||Re(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&oi(e,n)}function oi(e,t){return Re(t.enabled,e)!==!1&&e.isStaleByTime(Le(t.staleTime,e))}function hd(e,t){return!an(e.getCurrentResult(),t)}function _n(e){return{onFetch:(t,n)=>{let r=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],o=t.state.data?.pageParams||[],a={pages:[],pageParams:[]},c=0,u=async()=>{let l=!1,d=m=>{Ao(m,()=>t.signal,()=>l=!0)},h=jr(t.options,t.fetchOptions),f=async(m,v,g)=>{if(l)return Promise.reject();if(v==null&&m.pages.length)return Promise.resolve(m);let y=(()=>{let M={client:t.client,queryKey:t.queryKey,pageParam:v,direction:g?"backward":"forward",meta:t.options.meta};return d(M),M})(),_=await h(y),{maxPages:S}=t.options,x=g?To:Io;return{pages:x(m.pages,_,S),pageParams:x(m.pageParams,v,S)}};if(s&&i.length){let m=s==="backward",v=m?Ho:ai,g={pages:i,pageParams:o},w=v(r,g);a=await f(g,w,m)}else{let m=e??i.length;do{let v=c===0?o[0]??r.initialPageParam:ai(r,a);if(c>0&&v==null)break;a=await f(a,v),c++}while(c<m)}return a};t.options.persister?t.fetchFn=()=>t.options.persister?.(u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=u}}}function ai(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 Ho(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function Bo(e,t){return t?ai(e,t)!=null:!1}function Vo(e,t){return!t||!e.getPreviousPageParam?!1:Ho(e,t)!=null}var ci=class extends lr{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:_n()})}getOptimisticResult(e){return e.behavior=_n(),super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){let{state:n}=e,r=super.createResult(e,t),{isFetching:s,isRefetching:i,isError:o,isRefetchError:a}=r,c=n.fetchMeta?.fetchMore?.direction,u=o&&c==="forward",l=s&&c==="forward",d=o&&c==="backward",h=s&&c==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Bo(t,n.data),hasPreviousPage:Vo(t,n.data),isFetchNextPageError:u,isFetchingNextPage:l,isFetchPreviousPageError:d,isFetchingPreviousPage:h,isRefetchError:a&&!u&&!d,isRefetching:i&&!l&&!h}}};var dr,$e,he,jt,Ge,_t,Wo,$o=(Wo=class extends Vr{constructor(t){super();k(this,Ge);k(this,dr);k(this,$e);k(this,he);k(this,jt);C(this,dr,t.client),this.mutationId=t.mutationId,C(this,he,t.mutationCache),C(this,$e,[]),this.state=t.state||ui(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){p(this,$e).includes(t)||(p(this,$e).push(t),this.clearGcTimeout(),p(this,he).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){C(this,$e,p(this,$e).filter(n=>n!==t)),this.scheduleGc(),p(this,he).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){p(this,$e).length||(this.state.status==="pending"?this.scheduleGc():p(this,he).remove(this))}continue(){return p(this,jt)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{q(this,Ge,_t).call(this,{type:"continue"})},r={client:p(this,dr),meta:this.options.meta,mutationKey:this.options.mutationKey};C(this,jt,Br({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(o,a)=>{q(this,Ge,_t).call(this,{type:"failed",failureCount:o,error:a})},onPause:()=>{q(this,Ge,_t).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>p(this,he).canRun(this)}));let s=this.state.status==="pending",i=!p(this,jt).canStart();try{if(s)n();else{q(this,Ge,_t).call(this,{type:"pending",variables:t,isPaused:i}),p(this,he).config.onMutate&&await p(this,he).config.onMutate(t,this,r);let a=await this.options.onMutate?.(t,r);a!==this.state.context&&q(this,Ge,_t).call(this,{type:"pending",context:a,variables:t,isPaused:i})}let o=await p(this,jt).start();return await p(this,he).config.onSuccess?.(o,t,this.state.context,this,r),await this.options.onSuccess?.(o,t,this.state.context,r),await p(this,he).config.onSettled?.(o,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(o,null,t,this.state.context,r),q(this,Ge,_t).call(this,{type:"success",data:o}),o}catch(o){try{await p(this,he).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 p(this,he).config.onSettled?.(void 0,o,this.state.variables,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onSettled?.(void 0,o,t,this.state.context,r)}catch(a){Promise.reject(a)}throw q(this,Ge,_t).call(this,{type:"error",error:o}),o}finally{p(this,he).runNext(this)}}},dr=new WeakMap,$e=new WeakMap,he=new WeakMap,jt=new WeakMap,Ge=new WeakSet,_t=function(t){let n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),V.batch(()=>{p(this,$e).forEach(r=>{r.onMutationUpdate(t)}),p(this,he).notify({mutation:this,type:"updated",action:t})})},Wo);function ui(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var tt,je,pr,Go,zo=(Go=class extends Me{constructor(t={}){super();k(this,tt);k(this,je);k(this,pr);this.config=t,C(this,tt,new Set),C(this,je,new Map),C(this,pr,0)}build(t,n,r){let s=new $o({client:t,mutationCache:this,mutationId:++tr(this,pr)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){p(this,tt).add(t);let n=Wr(t);if(typeof n=="string"){let r=p(this,je).get(n);r?r.push(t):p(this,je).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(p(this,tt).delete(t)){let n=Wr(t);if(typeof n=="string"){let r=p(this,je).get(n);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&p(this,je).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=Wr(t);if(typeof n=="string"){let s=p(this,je).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"?p(this,je).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){V.batch(()=>{p(this,tt).forEach(t=>{this.notify({type:"removed",mutation:t})}),p(this,tt).clear(),p(this,je).clear()})}getAll(){return Array.from(p(this,tt))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Lr(n,r))}findAll(t={}){return this.getAll().filter(n=>Lr(t,n))}notify(t){V.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){let t=this.getAll().filter(n=>n.state.isPaused);return V.batch(()=>Promise.all(t.map(n=>n.continue().catch(re))))}},tt=new WeakMap,je=new WeakMap,pr=new WeakMap,Go);function Wr(e){return e.options.scope?.id}var nt,vt,Ce,rt,st,$r,li,Jo,di=(Jo=class extends Me{constructor(t,n){super();k(this,st);k(this,nt);k(this,vt);k(this,Ce);k(this,rt);C(this,nt,t),this.setOptions(n),this.bindMethods(),q(this,st,$r).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let n=this.options;this.options=p(this,nt).defaultMutationOptions(t),an(this.options,n)||p(this,nt).getMutationCache().notify({type:"observerOptionsUpdated",mutation:p(this,Ce),observer:this}),n?.mutationKey&&this.options.mutationKey&&Ve(n.mutationKey)!==Ve(this.options.mutationKey)?this.reset():p(this,Ce)?.state.status==="pending"&&p(this,Ce).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||p(this,Ce)?.removeObserver(this)}onMutationUpdate(t){q(this,st,$r).call(this),q(this,st,li).call(this,t)}getCurrentResult(){return p(this,vt)}reset(){p(this,Ce)?.removeObserver(this),C(this,Ce,void 0),q(this,st,$r).call(this),q(this,st,li).call(this)}mutate(t,n){return C(this,rt,n),p(this,Ce)?.removeObserver(this),C(this,Ce,p(this,nt).getMutationCache().build(p(this,nt),this.options)),p(this,Ce).addObserver(this),p(this,Ce).execute(t)}},nt=new WeakMap,vt=new WeakMap,Ce=new WeakMap,rt=new WeakMap,st=new WeakSet,$r=function(){let t=p(this,Ce)?.state??ui();C(this,vt,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},li=function(t){V.batch(()=>{if(p(this,rt)&&this.hasListeners()){let n=p(this,vt).variables,r=p(this,vt).context,s={client:p(this,nt),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{p(this,rt).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{p(this,rt).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{p(this,rt).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{p(this,rt).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(p(this,vt))})})},Jo);var ze,Yo,Xo=(Yo=class extends Me{constructor(t={}){super();k(this,ze);this.config=t,C(this,ze,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??rr(s,n),o=this.get(i);return o||(o=new Qo({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(o)),o}add(t){p(this,ze).has(t.queryHash)||(p(this,ze).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=p(this,ze).get(t.queryHash);n&&(t.destroy(),n===t&&p(this,ze).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){V.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return p(this,ze).get(t)}getAll(){return[...p(this,ze).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Kr(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>Kr(t,r)):n}notify(t){V.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){V.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){V.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},ze=new WeakMap,Yo);var se,bt,wt,vn,bn,St,wn,Sn,Zo,pi=(Zo=class{constructor(e={}){k(this,se);k(this,bt);k(this,wt);k(this,vn);k(this,bn);k(this,St);k(this,wn);k(this,Sn);C(this,se,e.queryCache||new Xo),C(this,bt,e.mutationCache||new zo),C(this,wt,e.defaultOptions||{}),C(this,vn,new Map),C(this,bn,new Map),C(this,St,0)}mount(){tr(this,St)._++,p(this,St)===1&&(C(this,wn,on.subscribe(async e=>{e&&(await this.resumePausedMutations(),p(this,se).onFocus())})),C(this,Sn,pn.subscribe(async e=>{e&&(await this.resumePausedMutations(),p(this,se).onOnline())})))}unmount(){var e,t;tr(this,St)._--,p(this,St)===0&&((e=p(this,wn))==null||e.call(this),C(this,wn,void 0),(t=p(this,Sn))==null||t.call(this),C(this,Sn,void 0))}isFetching(e){return p(this,se).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return p(this,bt).findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return p(this,se).get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=p(this,se).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Le(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return p(this,se).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=p(this,se).get(r.queryHash)?.state.data,o=Co(t,i);if(o!==void 0)return p(this,se).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return V.batch(()=>p(this,se).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return p(this,se).get(t.queryHash)?.state}removeQueries(e){let t=p(this,se);V.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=p(this,se);return V.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=V.batch(()=>p(this,se).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(re).catch(re)}invalidateQueries(e,t={}){return V.batch(()=>(p(this,se).findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=V.batch(()=>p(this,se).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(re)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(re)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=p(this,se).build(this,t);return n.isStaleByTime(Le(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(re).catch(re)}fetchInfiniteQuery(e){return e.behavior=_n(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(re).catch(re)}ensureInfiniteQueryData(e){return e.behavior=_n(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return pn.isOnline()?p(this,bt).resumePausedMutations():Promise.resolve()}getQueryCache(){return p(this,se)}getMutationCache(){return p(this,bt)}getDefaultOptions(){return p(this,wt)}setDefaultOptions(e){C(this,wt,e)}setQueryDefaults(e,t){p(this,vn).set(Ve(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...p(this,vn).values()],n={};return t.forEach(r=>{Ft(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){p(this,bn).set(Ve(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...p(this,bn).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={...p(this,wt).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=rr(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===cn&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...p(this,wt).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){p(this,se).clear(),p(this,bt).clear()}},se=new WeakMap,bt=new WeakMap,wt=new WeakMap,vn=new WeakMap,bn=new WeakMap,St=new WeakMap,wn=new WeakMap,Sn=new WeakMap,Zo);var xn=ne(fe(),1),ta=ne(Gr(),1),fi=xn.createContext(void 0),L=e=>{let t=xn.useContext(fi);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},fr=({client:e,children:t})=>(xn.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,ta.jsx)(fi.Provider,{value:e,children:t}));var zr=ne(fe(),1),na=zr.createContext(!1),ra=()=>zr.useContext(na),sg=na.Provider;var mr=ne(fe(),1),yd=ne(Gr(),1);function _d(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var vd=mr.createContext(_d()),sa=()=>mr.useContext(vd);var ia=ne(fe(),1);var oa=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?un(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},aa=e=>{ia.useEffect(()=>{e.clearReset()},[e])},ca=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||un(n,[e.error,r]));var ua=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))}},la=(e,t)=>e.isLoading&&e.isFetching&&!t,da=(e,t)=>e?.suspense&&t.isPending,mi=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var xt=ne(fe(),1);function Jr(e,t,n){let r=ra(),s=sa(),i=L(n),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let a=i.getQueryCache().get(o.queryHash);o._optimisticResults=r?"isRestoring":"optimistic",ua(o),oa(o,s,a),aa(s);let c=!i.getQueryCache().get(o.queryHash),[u]=xt.useState(()=>new t(i,o)),l=u.getOptimisticResult(o),d=!r&&e.subscribed!==!1;if(xt.useSyncExternalStore(xt.useCallback(h=>{let f=d?u.subscribe(V.batchCalls(h)):re;return u.updateResult(),f},[u,d]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),xt.useEffect(()=>{u.setOptions(o)},[o,u]),da(o,l))throw mi(o,u,s);if(ca({result:l,errorResetBoundary:s,throwOnError:o.throwOnError,query:a,suspense:o.suspense}))throw l.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(o,l),o.experimental_prefetchInRender&&!We.isServer()&&la(l,r)&&(c?mi(o,u,s):a?.promise)?.catch(re).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?l:u.trackResult(l)}function W(e,t){return Jr(e,lr,t)}var it=ne(fe(),1);function ie(e,t){let n=L(t),[r]=it.useState(()=>new di(n,e));it.useEffect(()=>{r.setOptions(e)},[r,e]);let s=it.useSyncExternalStore(it.useCallback(o=>r.subscribe(V.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=it.useCallback((o,a)=>{r.mutate(o,a).catch(re)},[r]);if(s.error&&un(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function Rn(e,t){return Jr(e,ci,t)}var ma=ne(fa(),1),Pn=typeof window<"u"&&window.__FSAOS_CONFIG__||{},Ht=Array.isArray(Pn.sources)?Pn.sources:[],ot=Pn.hostSession===!0,bd=Pn.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",wd=Pn.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",Fe=Pn.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",$=(0,ma.createClient)(bd,wd,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var gr=null,Yr=0,ga,_i,Xr=!1;ga=new Promise(e=>{_i=e});$.auth.onAuthStateChange((e,t)=>{t?.access_token?(gr=t.access_token,Yr=t.expires_at??Math.floor(Date.now()/1e3)+3600):(gr=null,Yr=0),Xr||(Xr=!0,_i())});setTimeout(()=>{Xr||(Xr=!0,_i())},5e3);function ha(e,t){gr=e,Yr=t??Math.floor(Date.now()/1e3)+3600}function vi(){gr=null,Yr=0}async function at(){let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{};if(ot)return null;if(e.embedToken){if(typeof e.embedToken=="function")try{return await e.embedToken()??null}catch{return null}return e.embedToken}return await ga,gr}var Tn=null,An=null,ya=0,gi=new Set,bi,hr,kn=!1;bi=new Promise(e=>{hr=e});function wi(){ya++,gi.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function Mn(e){let t=typeof e=="string"?e:e.path,n=Tn!==t||An?.id!==(typeof e=="string"?void 0:e.id);Tn=t,An=typeof e=="string"?null:e,typeof e!="string"&&!Bt.some(r=>r.id===e.id)&&(Bt=[...Bt,e],Pi()),kn||(kn=!0,hr()),n&&wi()}function Rt(){return Tn}function ye(){return An}function Si(){return ya}function xi(e){return gi.add(e),()=>{gi.delete(e)}}function yr(){return bi}function Ri(){return kn}var Zr=null;function Vt(e,t={}){if(Zr){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}Zr=e,t.activate!==!1&&Mn(e)}function we(){return Zr}var Bt=[],hi=new Set,_a=0;function Pi(){_a++,hi.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function qe(){return Bt}function _r(){return _a}function es(e){return hi.add(e),()=>{hi.delete(e)}}function va(e,t){let n=JSON.stringify(Bt)!==JSON.stringify(e),r=Tn!==t.path||An?.id!==t.id;Bt=e,Tn=t.path,An=t,kn||(kn=!0,hr()),n&&Pi(),r&&wi()}var En=null,Cn=null,In=0,yi=new Set,ba=0;function wa(){ba++,yi.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Session listener error:",t)}})}function Z(){return In}function Ci(){return ba}function Sa(e){return yi.add(e),()=>{yi.delete(e)}}async function ct(){if(En)return En;if(Cn)return Cn;let e=In;return Cn=(async()=>{let t=Wt(),n=await at();if(e!==In)throw new Error("Session changed during initialization");let r={};n&&(r.Authorization=`Bearer ${n}`);let s=await fetch(`${Fe}/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!==In)throw new Error("Session changed during initialization");let o=i.entry||i;return En={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},wa(),En})().catch(t=>{throw e===In&&(Cn=null),t}),Cn}function Pt(){return En}function Ei(){In++,En=null,Cn=null,Tn=null,An=null,Zr=null,Bt=[],wa()}var xa=[];function oe(e){xa.push(e)}function On(){Ei(),vi(),hr(),kn=!1,bi=new Promise(e=>{hr=e}),wi(),Pi();for(let e of xa)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function Wt(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var Ra=Mn,z=Rt,G=Si,Ie=xi,Pa=yr,ts=Ri;var Gt="host-session",Sd=5e3;function Ii(e){return typeof e=="object"&&e!==null&&e.fsaos===Gt&&typeof e.kind=="string"}var $t=class extends Error{constructor(){super(...arguments);X(this,"name","HostSessionUnavailableError")}},ns=null,xd=0,rs=new Map;function Ca(){return ns||(ns=new Promise((e,t)=>{if(!ot){t(new $t("This page was not started with hostSession."));return}if(typeof window>"u"||!window.parent||window.parent===window){t(new $t("This page is signed in only inside the app that frames it. Open it from there."));return}let n=window.parent,r=null,s=setTimeout(()=>{r===null&&(window.removeEventListener("message",i),t(new $t("The window around this page did not sign it in. Open it from the app that owns it.")))},Sd);function i(o){if(o.source!==n||!Ii(o.data))return;let a=o.data;if(r===null){if(a.kind!=="welcome")return;r=o.origin,clearTimeout(s),a.anchor&&Mn(a.anchor),e({host:n,origin:r,item:a.item??null});return}if(o.origin!==r||a.kind!=="result")return;let c=rs.get(a.id);c&&(rs.delete(a.id),c.resolve(a.ok?{ok:!0,response:a.response}:{ok:!1,error:a.error}))}window.addEventListener("message",i),n.postMessage({fsaos:Gt,kind:"hello"},"*")}),ns)}async function Ea(){let{item:e}=await Ca();return{item:e}}async function Ia(e,t,n){if(n?.aborted)throw new DOMException("Read cancelled","AbortError");let{host:r,origin:s}=await Ca();if(n?.aborted)throw new DOMException("Read cancelled","AbortError");let i=JSON.parse(JSON.stringify(t??{}));return new Promise((o,a)=>{let c=`${Date.now().toString(36)}-${(++xd).toString(36)}`,u=()=>{rs.delete(c),a(new DOMException("Read cancelled","AbortError"))};rs.set(c,{resolve:l=>{n?.removeEventListener("abort",u),o(l)}}),n?.addEventListener("abort",u,{once:!0}),r.postMessage({fsaos:Gt,kind:"call",id:c,method:e,params:i},s)})}var Ti=0,Ta=!1,Aa=0;function Ai(e){if(typeof e!="string")return;let t=Date.parse(e);Number.isNaN(t)||(Ti=t-Date.now(),Ta=!0,Aa=Date.now())}function ss(){return Date.now()+Ti}function ka(){return Ta}function Ma(){return Ti}function Oa(){return Aa}function Fa(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:ss()>=t}function qa(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Math.max(0,t-ss())}var Fn,Ne=new Map,zt=[],ki=0,Mi={foreground:0,normal:1,background:2},is=()=>performance.now(),Oi=()=>new DOMException("Read cancelled","AbortError");function Qa(e={}){Fn={concurrency:Math.max(1,Math.min(16,Math.floor(e.concurrency??6))),timeoutMs:Math.max(1e3,e.timeoutMs??15e3),onTiming:e.onTiming},as()}function Da(){for(let e of Ne.values()){e.controller.abort();for(let t of e.consumers)t.detach(),t.reject(Oi());e.consumers.clear(),e.timer&&clearTimeout(e.timer)}Ne.clear(),zt.length=0}function Ua(e,t){return e==="query"?!("materialize"in t):["read","list","search","resolve","resolve-items","get-channel-messages","list-memberships","message-replies"].includes(e)}function os(e){return Array.isArray(e)?`[${e.map(os).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${os(n)}`).join(",")}}`:JSON.stringify(e)}function Ka(e,t,n,r){if(n.signal?.aborted)return Promise.reject(Oi());if(!Fn)return r(n.signal);let s=Ne.get(e);if(s)Mi[n.priority??"normal"]<Mi[s.priority]&&(s.priority=n.priority??"normal");else{s={key:e,method:t,priority:n.priority??"normal",queuedAt:is(),controller:new AbortController,consumers:new Set,run:r},Ne.set(e,s),zt.push(s);let a=s;s.timer=setTimeout(()=>{a.controller.abort();let c=new Error("The read timed out. Please retry.");c.name="TimeoutError";for(let u of a.consumers)u.detach(),u.reject(c);a.consumers.clear(),Ne.get(a.key)===a&&Ne.delete(a.key),Na(a)},Fn.timeoutMs)}let i=s,o=new Promise((a,c)=>{let u=()=>{l.detach(),i.consumers.delete(l),c(Oi()),i.consumers.size||(i.controller.abort(),Ne.get(i.key)===i&&Ne.delete(i.key),Na(i))},l={resolve:d=>a(structuredClone(d)),reject:c,detach:()=>n.signal?.removeEventListener("abort",u)};i.consumers.add(l),n.signal?.addEventListener("abort",u,{once:!0})});return as(),o}function Na(e){let t=zt.indexOf(e);t>=0&&(zt.splice(t,1),Ne.get(e.key)===e&&Ne.delete(e.key),e.timer&&clearTimeout(e.timer)),as()}function as(){if(Fn)for(;ki<Fn.concurrency&&zt.length;){let e=r=>Mi[r.priority]-Math.floor((is()-r.queuedAt)/2e3);zt.sort((r,s)=>e(r)-e(s)||r.queuedAt-s.queuedAt);let t=zt.shift();if(!t.consumers.size)continue;ki++,t.startedAt=is();let n="success";Promise.resolve().then(()=>t.run(t.controller.signal)).then(r=>{for(let s of t.consumers)s.detach(),s.resolve(r)},r=>{n=t.controller.signal.aborted?"aborted":"error";for(let s of t.consumers)s.detach(),s.reject(r)}).finally(()=>{t.timer&&clearTimeout(t.timer),t.consumers.clear(),Ne.get(t.key)===t&&Ne.delete(t.key),ki--;try{Fn?.onTiming?.({method:t.method,priority:t.priority,queueMs:Math.round(t.startedAt-t.queuedAt),requestMs:Math.round(is()-t.startedAt),outcome:n})}catch{}as()})}}oe(Da);var Rd=new Set(["list-memberships","init"]),Se=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);X(this,"name","GatewayRequestError");X(this,"method");X(this,"status");X(this,"statusText");X(this,"payload");X(this,"responseBody");this.method=n.method,this.status=n.status,this.statusText=n.statusText,this.payload=n.payload,this.responseBody=n.responseBody}};async function R(e,t={},n={}){if(ot)return Pd(e,t,n);let r=Z(),s=Rt(),i=Wt(),o=`${Fe}/d/${i}`,a={"Content-Type":"application/json"},c=await La(at(),n.signal);if(r!==Z())throw new Error("Session changed before gateway request");if(c&&(a.Authorization=`Bearer ${c}`),!Rd.has(e)&&!t._scope_path&&await La(yr(),n.signal),r!==Z())throw new Error("Session changed before gateway request");let u={...t},l=Pt();!u.domain_scope_id&&l?.scope_id&&(u.domain_scope_id=l.scope_id);let d=s??Rt();!u._scope_path&&d&&(u._scope_path=d);let h=async f=>{if(r!==Z())throw new Error("Session changed before queued gateway request");let m=await fetch(o,{method:"POST",signal:f,headers:a,body:JSON.stringify({method:e,params:u})}),v=await m.text();if(r!==Z())throw new Error("Session changed during gateway request");let g=null;if(v)try{g=JSON.parse(v)}catch{}if(!m.ok||!g)throw new Se({method:e,status:m.status,statusText:m.statusText,payload:g,responseBody:v});if(g.success===!1){let w=g.error||"",y=g.denied_by||g.error_type||"";throw y==="rule"||y==="access"||y==="entitlement"||w==="RULE_DENIED"||w==="ACCESS_DENIED"||w==="PERMISSION_DENIED"||w==="ENTITLEMENT_REQUIRED"?new Ke(g):new Se({method:e,status:m.status,statusText:m.statusText,payload:g,responseBody:v})}return g&&g.server_now!==void 0&&Ai(g.server_now),g};return Ua(e,u)?Ka(os([r,i,c,e,u]),e,n,h):h(n.signal)}async function Pd(e,t,n){let r=await Ia(e,t,n.signal);if(r.ok){let o=r.response?.server_now;return o!==void 0&&Ai(o),r.response}let s=r.error;if(s.kind==="denied")throw new Ke(s.payload);if(s.kind==="gateway")throw new Se({method:s.method,status:s.status,statusText:s.statusText,payload:s.payload,responseBody:s.responseBody});let i=new Error(s.message);throw i.name=s.name,i}function La(e,t){return t?t.aborted?Promise.reject(new DOMException("Read cancelled","AbortError")):new Promise((n,r)=>{let s=()=>r(new DOMException("Read cancelled","AbortError"));t.addEventListener("abort",s,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",s))}):e}var b=ne(fe(),1),hp=ne(Ha(),1),yp=ne(Gr(),1);var Ba=new WeakMap;function le(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(d=>d.promise?[d.promise]:[]);if(i.length===0)return s();let o=`${r?"=":"^"}${JSON.stringify(t)}`,a=Ba.get(e);a||(a=new Map,Ba.set(e,a));let c=a.get(o);if(c)return c;let u=a,l=Promise.allSettled(i).then(()=>(u.delete(o),s()));return u.set(o,l),l}function de(e,t){return typeof e=="string"&&(e===t||e.startsWith(`${t}/`))}var cs=new WeakMap,Va=e=>e.meta?.arrangementRealtime===!0;function ut(e,t){let n=e.getQueryCache().find({queryKey:t,exact:!0});if(!n)return;let r=cs.get(e);r||(r=new Map,cs.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&&le(e,t,{exact:!0})},250))}function Wa(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){if(!Va(n))continue;let r=n.state.data;if(n.meta?.personalSections===!0){(r?.item_path&&[t.path,t.old_path].some(i=>typeof i=="string"&&(i===r.item_path||i.startsWith(r.item_path+"/")))||r?.sections?.some(i=>i.entries?.some(o=>o.target?.id===t.item_id))||!r?.item_id&&t.item_type==="item_arrangement"&&t.name==="sidebar-sections")&&ut(e,n.queryKey);continue}if(!r?.item_id)continue;let s=(i,o)=>!!(i&&t.item_id===i||o&&(t.path===o||t.old_path===o));(s(r.item_id,r.item_path)||t.parent_id===r.item_id||t.old_parent_id===r.item_id||[t.path,t.old_path].some(i=>typeof i=="string"&&i.slice(0,i.lastIndexOf("/"))===r.item_path)||r.resolved_children?.some(i=>s(i.id,i.symlink_path||i.path)||i.target&&s(i.target.id,i.target.path)))&&ut(e,n.queryKey)}}function $a(e){for(let t of e.getQueryCache().getAll())Va(t)&&t.state.data!==void 0&&ut(e,t.queryKey)}function Ga(e){cs.get(e)?.forEach(clearTimeout),cs.delete(e)}var lt=null;oe(()=>{lt&&(lt.cancelQueries({queryKey:["vfs"]}),lt.removeQueries({queryKey:["vfs"]}))});function za(e){if(lt&&lt!==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.");lt=e}function Q(){return lt||(lt=new pi({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),lt}var Ja=new Proxy({},{get(e,t,n){let r=Q(),s=r[t];return typeof s=="function"?s.bind(r):s}});var us=new WeakMap;function Fi(e){return e.meta?.infiniteItemsRealtime?.filter}function Cd(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 Ed(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 Id(e,t,n){if(Cd(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&&!de(n.path,r)&&!de(n.old_path,r))return!1;if(n.item_type==="symlink"&&s&&i)return!0;let o=Ed(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 Ya(e,t){let n=us.get(e);n||(n=new Map,us.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||!Fi(t))&&le(e,t.queryKey,{exact:!0})},500))}function Xa(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){let r=Fi(n);r&&Id(n,r,t)&&Ya(e,n)}}function Za(e){for(let t of e.getQueryCache().getAll())Fi(t)&&t.state.data!==void 0&&Ya(e,t)}function ec(e){us.get(e)?.forEach(clearTimeout),us.delete(e)}var ls=class extends Error{constructor(){super("The server did not confirm the selected-Space listing contract")}};function tc(e,t){if(!Array.isArray(t)||t.some(n=>typeof n!="string")||JSON.stringify([...new Set(t)].sort())!==JSON.stringify(e))throw new ls}function Ct(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 qn(e){return e instanceof ls||e instanceof Ke||e instanceof Se&&(e.payload?.error==="SPACE_SELECTION_UNAVAILABLE"||e.payload?.error==="QUERY_PARAMS_INVALID"||e.status===401||e.status===403)}function ae(){return z()??"__unscoped__"}var I={all:()=>["vfs",ae()],item:e=>["vfs",ae(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",ae(),"children",e],allChildren:()=>["vfs",ae(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",ae(),"search",e,...t??[]],items:(e,t)=>["vfs",ae(),"items",e,JSON.stringify(Ct(t??{}))],allItems:()=>["vfs",ae(),"items"],tree:(e,t)=>["vfs",ae(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",ae(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",ae(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",ae(),"get-activity-feed",e,t,n],itemVersions:(e,t,n,r)=>["vfs","item-versions",e,t,n,r],itemHistory:(e,t,n)=>["vfs","item-history",e,t,n],channelMessages:(e,t)=>["vfs",ae(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",ae(),"channel-messages"],channels:e=>["vfs",ae(),"channels",e??"all"],messageReplies:(e,t,n,r=25)=>["vfs",ae(),"channel-messages",e,n??"__top__","contextual-replies",t,r],allChannels:()=>["vfs",ae(),"channels"],notifications:(e,t)=>["vfs",ae(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",ae(),"notifications"],unreadCounts:()=>["vfs",ae(),"unread-counts"],memberships:e=>["memberships",e]};var Td=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function ee(...e){Td&&console.log("[WS]",...e)}var D=null,Nn=null,Dn=null,vr=0,Ad=3e4,nc=1e4,Kn=!1,rc=!1,cc=3e4,kd=cc*2+5e3,ds=0,ps=null,sc=!1;function Md(){wr(),ds=Date.now(),ps=setInterval(()=>{if(D&&D.readyState===WebSocket.OPEN&&Date.now()-ds>kd){ee("ping: no inbound traffic for",Date.now()-ds,"ms \u2014 closing half-open socket");try{D.close(4e3,"liveness timeout")}catch{}return}pt({type:"ping"})},cc)}function wr(){ps&&(clearInterval(ps),ps=null)}function Od(){typeof document>"u"||(document.hidden?wr():br()&&(ee("Tab visible, reconnecting..."),Jt()))}function Fd(){sc||typeof document>"u"||(document.addEventListener("visibilitychange",Od),sc=!0)}var Te={};function Ni(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return!n||!r?n===r:r===n||r.startsWith(`${n}/`)}var Un=[],dt=new Map,Qn=new Map,Qe=new Map;function qd(e){let t=Qn.get(e);return t?Array.from(new Set(Array.from(t.values()).flatMap(n=>n.event_types))).sort():[]}function ic(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):!1}function oc(e){let t=qd(e);if(t.length===0)return dt.delete(e),null;let n={scope_id:e,event_types:t};return dt.set(e,n),n}var Je=new Map,Et=new Map,qi="disconnected",fs=[];function ms(e){if(qi!==e){qi=e;for(let t of[...fs])try{t(e)}catch{}}}function Nd(e){Je.set(e,"ready");let t=Et.get(e);if(t){Et.delete(e);for(let n of t)n()}}function Qd(){for(let e of Je.keys())Je.set(e,"disconnected")}function Qi(e,t){Je.set(e,"pending"),pt({type:"subscribe_path",path:e,event_types:t})}function Dd(){return Object.keys(Te).some(t=>Te[t]&&Te[t].length>0)||Un.length>0}function br(){return dt.size>0||Qe.size>0}async function Jt(){if(ot){ee("ensureConnection: the host holds the session, no realtime connection");return}if(!br()){ee("ensureConnection: no active subscriptions, skipping");return}if(D&&D.readyState===WebSocket.OPEN){ee("ensureConnection: already open");return}if(Nn)return ee("ensureConnection: connection already in flight, waiting..."),Nn;if(D){ee("ensureConnection: killing stale WS in state",D.readyState);try{D.close()}catch{}D=null}return Kn=!1,Nn=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=Fe,n=await at();if(!n){ee("ensureConnection: no token available, will retry"),ac();return}let r=t.startsWith("https")?"wss":"ws",s=t.replace(/^https?:\/\//,""),i=`${r}://${s}/ws`;i+=`?token=${encodeURIComponent(n)}`,ee("ensureConnection: opening WS to",i.substring(0,50)+"..."),ms("connecting"),D=new WebSocket(i);let o=D;await new Promise((a,c)=>{if(!D)return c(new Error("WebSocket not created"));let u=setTimeout(()=>{if(D===o){if(ee("ensureConnection: TIMEOUT after",nc,"ms"),D&&D.readyState!==WebSocket.OPEN){try{D.close()}catch{}D=null}c(new Error("WebSocket connection timeout"))}},nc);o.onopen=()=>{if(D!==o)return;clearTimeout(u),ee("ensureConnection: CONNECTED");let l=rc;rc=!0,vr=0,ms("connected"),Ud(l),(typeof document>"u"||!document.hidden)&&Md(),Fd(),a()},o.onmessage=l=>{D===o&&Kd(l.data)},o.onerror=()=>{ee("ensureConnection: WS error event")},o.onclose=l=>{clearTimeout(u),D===o&&(ee("ensureConnection: WS closed, code:",l.code,"reason:",l.reason),D=null,wr(),Qd(),ms("disconnected"),!Kn&&br()&&ac(),c(new Error(`WebSocket closed: ${l.code}`)))}})}catch(e){ee("ensureConnection: failed -",e?.message||e)}finally{Nn=null}})(),Nn}function ac(){if(Dn||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,vr)+Math.random()*1e3,Ad);vr++,ee("scheduleReconnect: attempt",vr,"in",Math.round(e),"ms"),Dn=setTimeout(()=>{Dn=null,br()&&Jt()},e)}function Ud(e=!1){for(let t of dt.values())ee("resubscribeAll: scope",t.scope_id),pt({type:"subscribe",scope_id:t.scope_id,event_types:t.event_types});for(let t of Qe.values())ee("resubscribeAll: path",t.path),Qi(t.path,t.event_types);e&&uc("reconnect")}function uc(e){try{let t=Q();Za(t),$a(t);for(let n of Qe.values())t.invalidateQueries({queryKey:I.item(n.path)}),t.invalidateQueries({queryKey:I.children(n.path)});t.invalidateQueries({queryKey:I.allChannelMessages()}),ee("catchUpAfterGap:",e,"- invalidated",Qe.size,"paths and the transcripts on screen")}catch(t){ee("catchUpAfterGap: cache invalidation skipped",t)}}function pt(e){D&&D.readyState===WebSocket.OPEN&&D.send(JSON.stringify(e))}function Kd(e){ds=Date.now();try{let t=JSON.parse(e);if(t.type==="subscribed_path"){typeof t.path=="string"&&Nd(t.path);return}if(t.type==="subscribed"||t.type==="unsubscribed"||t.type==="unsubscribed_path"||t.type==="pong")return;if(t.type==="error"){console.warn("[WS] Server error:",t.message);return}if(t.type==="resync"){uc(typeof t.reason=="string"?t.reason:"resync");return}if(t.type==="event"||t.event_type){let n=t.event_type||"message",r=t.data||t;if(n==="vfs_change"&&(Xa(Q(),r),Wa(Q(),r)),typeof r.path=="string")for(let[s,i]of Object.entries(Te))s!=="*"&&Ni(s,r.path)&&i.forEach(o=>o(r));Te["*"]&&Te["*"].forEach(s=>s(r));for(let s of Un)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function Di(){!Dd()&&dt.size===0&&Qe.size===0&&D&&(Kn=!0,wr(),D.close(),D=null,Kn=!1)}function gs(e,t){return Te[e]||(Te[e]=[]),Te[e].push(t),Qe.has(e)||(Qe.set(e,{path:e,event_types:["token_stream"]}),D&&D.readyState===WebSocket.OPEN?Qi(e,["token_stream"]):Je.set(e,"pending")),Jt(),()=>{let n=Te[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete Te[e],Qe.delete(e),Je.delete(e),Et.delete(e),pt({type:"unsubscribe_path",path:e}))}Di()}}function J(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return Un.push(...s),br()&&Jt(),()=>{for(let i of s){let o=Un.indexOf(i);o!==-1&&Un.splice(o,1)}Di()}}function Ln(e,t=["vfs_change","ccm_change"]){let n=Symbol(e),r=Array.from(new Set(t)).sort();if(r.length===0)return()=>{};let s=Qn.get(e)??new Map,i=dt.get(e)?.event_types;s.set(n,{event_types:r}),Qn.set(e,s);let o=oc(e);if(!o)return()=>{};ee("subscribeToScope:",e,o.event_types),D&&D.readyState===WebSocket.OPEN&&!ic(i,o.event_types)&&pt({type:"subscribe",scope_id:e,event_types:o.event_types}),Jt();let a=!0;return()=>{if(!a)return;a=!1;let c=Qn.get(e);if(!c?.delete(n))return;let u=dt.get(e)?.event_types;if(c.size===0)Qn.delete(e),dt.delete(e),pt({type:"unsubscribe",scope_id:e});else{let l=oc(e);l&&D&&D.readyState===WebSocket.OPEN&&!ic(u,l.event_types)&&pt({type:"subscribe",scope_id:e,event_types:l.event_types})}Di()}}function lc(e,t,n={}){pt({type:"emit",scope_id:e,event_type:t,payload:n})}function Ui(){ee("disconnectSSE: tearing down"),ec(Q()),Ga(Q()),Kn=!0,wr(),D&&(D.close(),D=null),Dn&&(clearTimeout(Dn),Dn=null),Nn=null,Kn=!1,vr=0;for(let e of Object.keys(Te))delete Te[e];Un.length=0,dt.clear(),Qn.clear(),Qe.clear(),Je.clear(),Et.clear(),ms("disconnected")}function dc(){pt({type:"ping"})}function pc(e){return Qe.has(e)?Je.get(e)??"pending":"unsubscribed"}function fc(e,t=5e3){return!Qe.has(e)||ot?Promise.resolve(!1):Je.get(e)==="ready"&&D&&D.readyState===WebSocket.OPEN?Promise.resolve(!0):(Jt(),new Promise(n=>{let r=!1,s=Et.get(e)??[],i=()=>{r||(r=!0,clearTimeout(o),n(!0))};s.push(i),Et.set(e,s);let o=setTimeout(()=>{if(r)return;r=!0;let a=Et.get(e);if(a){let c=a.indexOf(i);c!==-1&&a.splice(c,1),a.length===0&&Et.delete(e)}n(!1)},t)}))}function mc(e){let t=Qe.get(e);if(!t){ee("resubscribePath: no active subscription for",e);return}D&&D.readyState===WebSocket.OPEN?(ee("resubscribePath: re-sending frame for",e),Qi(t.path,t.event_types)):(Je.set(e,"pending"),Jt())}function hs(e){fs.push(e);try{e(qi)}catch{}return()=>{let t=fs.indexOf(e);t!==-1&&fs.splice(t,1)}}oe(Ui);function gc(){return new Date().toISOString()}function hc(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function De(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||gc(),updated_at:e.updated_at||gc(),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 Sr(e){return(e.content?.items||e.items||[]).map(De)}async function xr(e){try{let t=await R("read",{id:e});if(t.item_name||t.item_path){let r=De(t);return r.path&&Q().setQueryData(I.item(r.path),r),r}let n=t.item;if(n){let r=De(n);return r.path&&Q().setQueryData(I.item(r.path),r),r}return null}catch{return null}}async function Rr(e){try{let t=await R("read",{path:e});if(t.item_name||t.item_path)return De(t);let n=t.item;return n?De(n):null}catch{return null}}async function Pr(e){try{let t=await R("list",{path:e,limit:200}),n=Sr(t);for(let r of n)Q().setQueryData(I.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function yc(e,t){let{items:n}=await Yt({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 _s(e,t,n){try{let r=await R("list",{path:e,limit:t,offset:n}),s=Sr(r);for(let i of s)Q().setQueryData(I.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 vs(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 bs(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||hc(),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||hc(),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 ws(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=Sr(i);for(let a of o)Q().setQueryData(I.item(a.path),a);return o}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function Ss(e,t=50,n=0){try{let r=await R("get-activity-feed",{scope_path:e,limit:t,offset:n});return r.content?.items||r.items||r.entries||[]}catch(r){return console.error(`[gateway] Failed to fetch recent activity for ${e}:`,r),[]}}async function Cr(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 xs(e,t=50,n=0){return Cr(e,{limit:t,offset:n})}async function Rs(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=Sr(s);for(let o of i)Q().setQueryData(I.item(o.path),o);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${e}:`,r),[]}}async function Er(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 Hn(e){return!!e&&(!!e.type||Array.isArray(e.any_of)&&e.any_of.length>0)}function Ld(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 jd=["catalog","parent_only","internal"];function _c(e,t={}){if(!e||typeof e!="object")return null;let n=o=>typeof o=="string"||typeof o=="number"||typeof o=="boolean",r=o=>{let a={},c={};for(let[u,l]of Object.entries(o))u.startsWith("field.")&&u.length>6&&n(l)?a[u.slice(6)]=l:u.startsWith("field_in.")&&u.length>9&&Array.isArray(l)&&(c[u.slice(9)]=l.filter(n));return{fields:a,field_in:c}},s={};typeof e.type=="string"&&e.type&&(s.type=e.type),typeof e.sort_by=="string"&&(s.sort_by=e.sort_by),(e.sort_dir==="asc"||e.sort_dir==="desc")&&(s.sort_dir=e.sort_dir),typeof e.name=="string"&&e.name&&(s.name=e.name),typeof e.tag=="string"&&e.tag&&(s.tag=e.tag),typeof e.discovery=="string"&&jd.includes(e.discovery)&&(s.discovery=e.discovery);let i=r(e);if(Object.keys(i.fields).length&&(s.fields=i.fields),Object.keys(i.field_in).length&&(s.field_in=i.field_in),Array.isArray(e.any_of)){let o=[];for(let a of e.any_of){if(!a||typeof a!="object"||Array.isArray(a))continue;let c=a,u={};typeof c.item_type=="string"&&c.item_type&&(u.item_type=c.item_type);let l=r(c);Object.keys(l.fields).length&&(u.fields=l.fields),Object.keys(l.field_in).length&&(u.field_in=l.field_in),Object.keys(u).length&&o.push(u)}o.length&&(s.any_of=o)}return Hn(s)?{...s,...t}:null}async function Yt(e,t={}){if(e=Ct(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(Ld)),Object.keys(r).length>0&&(n.filters=r),e.limit!=null&&(n.limit=e.limit);try{let s=await R("query",n,t);e.spaceIds!==void 0&&tc(e.spaceIds,s.selected_space_ids??s.content?.selected_space_ids);let i=Sr(s);for(let o of i)Q().setQueryData(I.item(o.path),o);return{items:i,total_hint:s.total??s.content?.total??i.length}}catch(s){if(t.signal?.aborted||s instanceof Error&&s.name==="AbortError"||(console.error(`[gateway] Failed to fetch items of type ${e.type??"(any_of)"}:`,s),t.throwOnError||e.spaceIds!==void 0))throw s;return{items:[],total_hint:0}}}function vc(e){if(!e||typeof e!="object")return;let t=e;if(t.state==="unavailable")return{state:"unavailable"};if(!(t.state!=="available"||typeof t.message_id!="string"||typeof t.path!="string"||typeof t.excerpt!="string"))return{state:"available",message_id:t.message_id,path:t.path,role:typeof t.role=="string"?t.role:void 0,sender_principal_id:typeof t.sender_principal_id=="string"?t.sender_principal_id:void 0,sender_display_name:typeof t.sender_display_name=="string"?t.sender_display_name:void 0,excerpt:t.excerpt,truncated:t.truncated===!0}}async function bc(e){if(!e.channel_id&&!e.channel_path)throw new Error("A message requires a channel.");let t=e.reply_to_message_id!==void 0;if(t&&(typeof e.reply_to_message_id!="string"||!e.reply_to_message_id.trim()))throw new Error("A contextual reply requires a target message ID.");if(t&&(e.conversation_mode==="new_thread"||e.hand_off_to))throw new Error("A contextual reply stays in the current conversation.");return await R(t?"reply-message":"send-message",e)}async function wc(e,t){let n=new Set(e),r=[...n];if(!r.length)return{};if(r.length>200)throw new Error("Reply context supports at most 200 messages per batch.");let i=(await R("message-replies",{operation:"context",message_ids:r},t)).replies;if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid reply-context response.");return Object.fromEntries(Object.entries(i).flatMap(([o,a])=>{let c=vc(a);return c&&n.has(o)?[[o,c]]:[]}))}async function Ps(e,t={},n){let r=t.limit??25;if(!Number.isInteger(r)||r<1||r>100)throw new Error("Reply page size must be between 1 and 100.");let s=await R("message-replies",{operation:"list",message_id:e,limit:r,...t.cursor?{cursor:t.cursor}:{},...t.conversationRootId?{conversation_root_id:t.conversationRootId}:{}},n);if(!Array.isArray(s.messages))throw new Error("Invalid reply-list response.");let i=s.next_cursor;if(i&&(typeof i.updated_at!="string"||typeof i.edge_id!="string"))throw new Error("Invalid reply-list cursor.");let o=new Map(jn(s.messages).map(a=>[a.id,a]));return{messages:s.messages.flatMap(a=>{let c=o.get(a.id);return c?[c]:[]}),next_cursor:i??null}}function Hd(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 Sc(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:Hd(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 jn(e){return e.filter(t=>t.item_type==="message").map(t=>{let n=t.type_data||{},r="user";n.role==="assistant"?r="assistant":n.role==="system"&&(r="system");let s=n.metadata||{};return{id:t.id||"",path:t.path||"",content:n.message||n.content||"",created_at:t.created_at||"",role:r,status:typeof n.status=="string"?n.status:void 0,delivery_state:typeof n.delivery_state=="string"?n.delivery_state:void 0,cognition_event_id:typeof n.cognition_event_id=="string"?n.cognition_event_id:void 0,seq:n.seq||0,principal_id:n.principal_id,member_id:typeof n.member_id=="string"?n.member_id:void 0,sender_display_name:typeof n.sender_display_name=="string"?n.sender_display_name:void 0,sender_is_ai:typeof n.sender_is_ai=="boolean"?n.sender_is_ai:void 0,sender_role_display_name:typeof n.sender_role_display_name=="string"?n.sender_role_display_name:void 0,reply_count:n.reply_count||0,member_count:n.member_count||0,parent_message_id:n.parent_message_id,reply_to:vc(t.reply_to),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 xc(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 jn(i)}catch(n){throw console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),n}}async function Cs(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await R("get-channel-messages",n),i=s.messages||[],o=jn(i),a=Sc(i),c=new Map,u=[];for(let l of a)if(l.parentMessagePath){let d=c.get(l.parentMessagePath)||[];d.push(l),c.set(l.parentMessagePath,d)}else u.push(l);return{messages:o,activityMessages:jn(s.activity_messages||[]),messageCards:c,siblingCards:u,mode:s.mode||"top_level"}}catch(n){throw console.error(`[gateway] Failed to fetch channel messages with cards for ${e}:`,n),n}}async function Xt(e,t){try{let n={channel_path:e};t?.parentMessageId&&(n.parent_message_id=t.parentMessageId),t?.conversationsOnly&&(n.conversations_only=!0),t?.transcriptOnly&&(n.transcript_only=!0),t?.limit&&(n.limit=t.limit),t?.before_seq!=null&&(n.before_seq=t.before_seq),t?.after_seq!=null&&(n.after_seq=t.after_seq);let s=await R("get-channel-messages",n);if(t?.conversationsOnly&&s.conversations_only!==!0)throw new Error("This server does not support conversation history lists yet. Update the message reader.");if(t?.transcriptOnly&&s.transcript_only!==!0)throw new Error("This server does not support channel transcript pages yet. Update the message reader.");let i=s.messages||[],o=Sc(i),a=new Map,c=[];for(let u of o)if(u.parentMessagePath){let l=a.get(u.parentMessagePath)||[];l.push(u),a.set(u.parentMessagePath,l)}else c.push(u);return{messages:jn(i),activityMessages:jn(s.activity_messages||[]),messageCards:a,siblingCards:c,mode:s.mode||"top_level"}}catch(n){throw console.error(`[gateway] Failed to fetch channel messages page for ${e}:`,n),n}}function ys(e){Q().invalidateQueries({queryKey:I.children(e)})}function Ki(e){Q().invalidateQueries({queryKey:I.item(e)})}function Rc(e,t){Ki(e),ys(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&ys(r)}function Pc(e){let t=e+"/";Q().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function Cc(){Q().invalidateQueries({queryKey:I.all()})}function Ec(e){Q().invalidateQueries({queryKey:I.types(e)})}function Ic(e,t){e?Q().invalidateQueries({queryKey:I.channelMessages(e,t)}):Q().invalidateQueries({queryKey:I.allChannelMessages()})}function Tc(e,t){e&&t?Q().invalidateQueries({queryKey:I.openEnvelope(e,t)}):e?Q().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):Q().invalidateQueries({queryKey:I.allOpenEnvelopes()})}function Ye(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}async function Es(){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,invitationAccepted:n.invitation_accepted===!0,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,Tr=null,Is=null,It=new Map,Ac=250,Ir=new Map;function Zt(e){if(Tr){Vn(e);return}Vn(e),Tr=J("vfs_change",t=>Bd(t)),Is=J("ccm_change",t=>Vd(t))}function Vn(e){if(Bn.has(e))return;let t=Ln(e,["vfs_change","ccm_change"]);Bn.set(e,t)}function Ts(e){let t=Bn.get(e);t&&(t(),Bn.delete(e))}function Li(){for(let[,e]of Bn)e();Bn.clear(),Tr&&(Tr(),Tr=null),Is&&(Is(),Is=null),It.forEach(e=>clearTimeout(e)),It.clear(),Ir.clear()}oe(Li);function Bd(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=Ir.get(s);i||(i=new Map,Ir.set(s,i)),i.set(t,{action:n,itemId:typeof e.item_id=="string"?e.item_id:void 0});let o=It.get(s);o&&clearTimeout(o);let a=setTimeout(()=>{It.delete(s);let c=Ir.get(s);Ir.delete(s),c&&Wd(s,c)},Ac);It.set(s,a)}function Vd(e){if(!e||typeof e!="object")return;let t=e.source_item_id||e.source_id,n=e.target_item_id||e.target_id;if(!(e.edge_type!=null||t!=null||n!=null)||!t&&!n||e.item_type==="message")return;let s=`ccm:${t??""}:${n??""}`,i=It.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{It.delete(s),t&&Q().invalidateQueries({queryKey:I.edges(t)}),n&&Q().invalidateQueries({queryKey:I.edges(n)})},Ac);It.set(s,o)}function Wd(e,t){let n=Q();for(let[s,i]of t)(i.action||"").toUpperCase()==="DELETE"?(n.removeQueries({queryKey:I.item(s)}),n.removeQueries({queryKey:I.children(s)}),n.removeQueries({queryKey:I.tree(s)})):le(n,I.item(s),{exact:!0}),i.itemId&&n.invalidateQueries({queryKey:I.itemById(i.itemId)});n.invalidateQueries({queryKey:I.children(e)});let r=[...t.keys()];n.invalidateQueries({predicate:s=>{let i=s.queryKey;if(i[0]!=="vfs"||i[1]!=="tree")return!1;let o=i[2];return r.some(a=>a.startsWith(o+"/")||a===o)}})}var Wn=null;oe(()=>{Wn=null});function Tt(e){if(e!==Wn||e.generation!==Z())throw new Error("Workspace session changed")}function $d(e){return e instanceof Se&&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 kr(e){let t=we();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 kc(e,t){return JSON.stringify({mounts:e.map(n=>n.id),last_anchor:t.id})}async function Mc(e,t,n){Tt(e);let r=kc(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}),Tt(e),e.exists=!0,e.saved=r}function Oc(e,t){let n=qe();Zt(we().id);for(let r of n)e.some(s=>s.id===r.id)||Ts(r.id);for(let r of e)Vn(r.id);va(e,t)}async function en(e,t,n={}){let r=we();if(!r)throw new Error("Elect a home account before loading mounts");let s=`${e}/settings/mounts`;if(Wn&&Wn.path!==s)throw new Error("Reset the session before changing the mount declaration owner");let i=Wn??(Wn={generation:Z(),path:s,scope:r.path,resolve:t,exists:!1,ready:!1,saved:null,queue:Promise.resolve()});return Tt(i),i.resolve=t,i.loading?i.loading:i.ready?qe():(i.loading=(async()=>{let o=null;try{let l=await R("read",{path:s,_scope_path:i.scope});if(Tt(i),o=l.type_data??l.item?.type_data,!o||!Array.isArray(o.mounts)||!o.mounts.every(d=>typeof d=="string"))throw new Error("Invalid saved mount declaration");i.exists=!0}catch(l){if(Tt(i),!$d(l))throw l;i.exists=!1}let a=n.initialAnchor?Ar(i,n.initialAnchor):r,c=kr(o?o.mounts.map(l=>i.resolve(l)).filter(l=>l!==null):[a]),u=o?c.find(l=>l.id===o.last_anchor)??c.find(l=>l.kind==="space")??r:a;return o?i.saved=kc(c,u):n.initialAnchor&&await Mc(i,c,u),Tt(i),i.ready=!0,Oc(c,u),c})().finally(()=>{i.loading=void 0}),i.loading)}function As(e){let t=Wn;if(!t?.ready)return Promise.reject(new Error("Workspace mounts are not loaded"));let n=t.queue.then(async()=>{Tt(t);let{refs:r,anchor:s}=e(t);await Mc(t,r,s),Tt(t),Oc(r,s)});return t.queue=n.catch(()=>{}),n}function ji(e){return As(t=>({refs:kr([...qe(),Ar(t,e)]),anchor:ye()}))}function Fc(e){return As(()=>{if(e===we().id)throw new Error("The home account cannot be unmounted");let t=kr(qe().filter(r=>r.id!==e)),n=t.find(r=>r.id===ye()?.id)??t.find(r=>r.kind==="space")??we();return{refs:t,anchor:n}})}function Mr(e){return As(t=>{let n=Ar(t,e);return{refs:kr([...qe(),n]),anchor:n}})}function ks(e,t){return As(n=>{let r=kr(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}})}var Hi={};_o(Hi,{Badge:()=>Zd,Breadcrumbs:()=>lp,Button:()=>tp,Card:()=>Xd,DataView:()=>rp,Detail:()=>op,Empty:()=>np,FilePreview:()=>fp,Form:()=>ip,Grid:()=>Jd,Image:()=>dp,Link:()=>cp,Page:()=>Gd,Router:()=>ap,Sidebar:()=>Yd,Spinner:()=>ep,Stack:()=>zd,Table:()=>sp,Tabs:()=>up,Video:()=>pp});var Y=ne(fe(),1);function qc(){return(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||""}function Gd(e){return(0,Y.createElement)("div",{style:{minHeight:"100vh",display:"flex",flexDirection:"column"},className:e.className||""},e.children)}function zd(e){let t=e.direction||"vertical";return(0,Y.createElement)("div",{style:{display:"flex",flexDirection:t==="horizontal"?"row":"column",gap:e.gap||"0.5rem",padding:e.padding||"0",alignItems:e.align||"stretch",justifyContent:e.justify||"flex-start",flex:e.flex||"initial"},className:e.className||""},e.children)}function Jd(e){return(0,Y.createElement)("div",{style:{display:"grid",gridTemplateColumns:"repeat("+(e.columns||3)+", 1fr)",gap:e.gap||"1rem",padding:e.padding||"0"},className:e.className||""},e.children)}function Yd(e){return(0,Y.createElement)("div",{style:{display:"flex",flexDirection:"row",minHeight:"100vh"},className:e.className||""},e.children)}function Xd(e){return(0,Y.createElement)("div",{style:{border:"1px solid var(--color-border, #e5e7eb)",borderRadius:"var(--border-radius, 0.5rem)",padding:e.padding||"1rem",background:"var(--color-surface, #fff)"},className:e.className||"",onClick:e.onClick},e.children)}function Zd(e){return(0,Y.createElement)("span",{style:{display:"inline-flex",alignItems:"center",padding:"0.125rem 0.5rem",fontSize:"0.75rem",fontWeight:"500",borderRadius:"9999px",background:e.color||"#e5e7eb",color:e.textColor||"#374151"},className:e.className||""},e.children||e.label)}function ep(e){let t=e.size||"1.5rem";return(0,Y.createElement)("div",{style:{width:t,height:t,border:"2px solid #e5e7eb",borderTopColor:"var(--color-primary, #3b82f6)",borderRadius:"50%",animation:"fsaos-spin 0.6s linear infinite"}})}function tp(e){return(0,Y.createElement)("button",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:"0.5rem 1rem",fontSize:"0.875rem",fontWeight:"500",borderRadius:"var(--border-radius, 0.375rem)",border:e.variant==="outline"?"1px solid var(--color-border, #d1d5db)":"none",background:e.variant==="outline"||e.variant==="ghost"?"transparent":"var(--color-primary, #3b82f6)",color:e.variant==="outline"||e.variant==="ghost"?"var(--color-text, #1a1a1a)":"#fff",cursor:e.disabled?"not-allowed":"pointer",opacity:e.disabled?"0.5":"1",gap:"0.5rem"},className:e.className||"",onClick:e.onClick,disabled:e.disabled},e.children||e.label)}function np(e){return(0,Y.createElement)("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"3rem",color:"var(--color-text-secondary, #6b7280)",textAlign:"center"}},e.icon?(0,Y.createElement)("div",{style:{fontSize:"2rem",marginBottom:"0.5rem"}},e.icon):null,(0,Y.createElement)("div",{style:{fontWeight:500,marginBottom:"0.25rem"}},e.title||e.message||e.children||"No items"),e.description?(0,Y.createElement)("div",{style:{fontSize:"0.875rem",opacity:.7}},e.description):null)}function rp(e){return(0,Y.createElement)("div",{className:e.className||""},e.children)}function sp(e){return(0,Y.createElement)("table",{className:e.className||""},e.children)}function ip(e){return(0,Y.createElement)("form",{className:e.className||"",onSubmit:e.onSubmit},e.children)}function op(e){return(0,Y.createElement)("div",{className:e.className||""},e.children)}function ap(e){return(0,Y.createElement)("div",null,e.children)}function cp(e){return(0,Y.createElement)("a",{href:e.href||e.to,className:e.className||"",onClick:e.onClick},e.children)}function up(e){return(0,Y.createElement)("div",{className:e.className||""},e.children)}function lp(e){return(0,Y.createElement)("nav",{className:e.className||""},e.children)}function dp(e){return(0,Y.createElement)("img",{src:e.src||(e.path?qc()+e.path:""),alt:e.alt||"",className:e.className||"",style:e.style})}function pp(e){return(0,Y.createElement)("video",{src:e.src||(e.path?qc()+e.path:""),controls:!0,className:e.className||""})}function fp(e){return(0,Y.createElement)("div",{className:e.className||""},e.children||"File preview")}function Ms(e){if(typeof e.path!="string")return!1;let t=[...qe().map(n=>n.path),ye()?.path].filter(n=>!!n);return!t.length&&z()&&t.push(z()),t.some(n=>de(e.path,n))}function $n(e,t,n,r){if(!["message","card"].includes(e?.item_type)||!de(e.path,t))return!1;if(!n){let s=e.path.slice(t.length).replace(/^\//,""),i=s?s.split("/").length:0;return e.item_type==="message"?i===1:i===1||i===2}return e.item_id===n||e.parent_id===n?!0:r.some(s=>{if(e.item_id===s.id||e.parent_id===s.id)return!0;let i=s.id===n?s.path:s.parent_message_id===n?s.path.slice(0,s.path.lastIndexOf("/")):void 0;return!!i&&de(e.path,i)})}var Nc=new WeakMap,Bi=e=>e.slice(0,e.lastIndexOf("/")),Vi=e=>e.action?.toLowerCase();function Qc(e,t){return e.item_type==="message"&&Vi(e)==="insert"&&Bi(e.path)===t&&!e.old_path}function mp(e,t,n){return e.messages.filter(r=>t.has(r.id)||n.has(r.path))}function gp(e,t,n,r){let s=e.pages.slice(),i=new Map(n?.messages.map(u=>[u.id,u]));for(let[u,l]of t){let d=s[u],h=new Set(l.map(m=>m.id)),f=new Map(d.messageCards);for(let m of l){f.delete(m.path);let v=i.get(m.id),g=v&&n?.messageCards.get(v.path);v&&g?.length&&f.set(v.path,g)}s[u]={...d,messages:d.messages.flatMap(m=>{if(!h.has(m.id))return[m];let v=i.get(m.id);return v?[v]:[]}),messageCards:f}}let o=r??n,a=s[0],c=new Map(a.messageCards);for(let u of a.activityMessages??[])c.delete(u.path);for(let u of[...o.activityMessages??[],...r?.messages??[]]){let l=o.messageCards.get(u.path);l?.length&&c.set(u.path,l)}return s[0]={...a,messages:r?[...a.messages,...r.messages]:a.messages,activityMessages:o.activityMessages,siblingCards:o.siblingCards,messageCards:c},{...e,pages:s}}function Dc(e,t,n,r){let s=Nc.get(e);s||(s=new Map,Nc.set(e,s));let i=JSON.stringify(t),o=s.get(i);if(!o){let c,u=!1,l=!1,d=new Map,h=()=>e.getQueryData(t),f=()=>e.getQueryCache().find({queryKey:t,exact:!0}),m=()=>le(e,t,{exact:!0}),v=(_,S)=>Xt(n,{transcriptOnly:!0,limit:r,after_seq:_,before_seq:S}),g=()=>{l||u||c||!d.size||(c=setTimeout(()=>{c=void 0,w()},500))},w=async()=>{u=!0;let _=[...d.values()];d.clear();let S=f();try{if(S?.state.fetchStatus==="fetching"&&await S.promise?.catch(()=>{}),l||S!==f())return;let x=h();if(!x?.pages.length){await m();return}let M=new Set,N=new Set,P=new Set,O=!1;for(let j of _){if(Qc(j,n)){O=!0;continue}j.inserted&&(O=!0),j.item_type==="message"&&Bi(j.path)===n&&!j.inserted&&Vi(j)!=="delete"&&P.add(j.path),j.item_id&&M.add(j.item_id),j.parent_id&&M.add(j.parent_id);for(let me of[j.path,j.old_path])me&&de(me,n)&&(N.add(me),N.add(Bi(me)))}let T=new Map,E=1/0,A=0;(M.size||N.size)&&x.pages.forEach((j,me)=>{let ve=mp(j,M,N);ve.length&&T.set(me,ve);for(let Ue of ve)P.delete(Ue.path),E=Math.min(E,Ue.seq),A=Math.max(A,Ue.seq)});for(let j of x.pages[0].activityMessages??[])P.delete(j.path);if(P.size){await m();return}if(T.size&&(!Number.isSafeInteger(E)||E<1||!Number.isSafeInteger(A+1))){await m();return}let F=x.pages.find(j=>j.messages.length)?.messages.at(-1)?.seq??0,[U,H]=await Promise.all([T.size?v(E-1,A+1):void 0,O||!T.size?v(F):void 0]);if(l||S!==f())return;let ke=h();if(S?.state.fetchStatus==="fetching"||x.pages.some((j,me)=>ke?.pages[me]!==j)||U&&U.messages.length>=r&&(U.messages.at(-1)?.seq??0)<A||H&&H.messages.length>=r){await m();return}e.setQueryData(t,j=>j&&gp(j,T,U,H))}catch{!l&&S===f()&&await m()}finally{u=!1,g()}},y=J("vfs_change",_=>{let S=_.item_id??_.path,x=d.get(S);d.set(S,x&&(x.inserted||Qc(x,n))&&Vi(_)==="update"&&x.path===_.path?{..._,inserted:!0}:_),g()},_=>$n(_,n,void 0,[])||!!_.old_path&&$n({..._,path:_.old_path},n,void 0,[])||_.item_type==="message"&&!!_.parent_id&&de(_.path,n)&&!!h()?.pages.some(S=>S.messages.some(x=>x.id===_.parent_id)));o={users:0,stop:()=>{l=!0,y(),c&&clearTimeout(c),d.clear()}},s.set(i,o)}o.users++;let a=!1;return()=>{a||(a=!0,--o.users===0&&(o.stop(),s.delete(i)))}}var Uc=new WeakMap;function Kc(e,t,n){let r=Uc.get(e);r||(r=new Map,Uc.set(e,r));let s=JSON.stringify(t),i=r.get(s);if(!i){let a=!1,c,u=!1,l=!1,d=new Set,h=new Set,f=()=>e.getQueryData(t)??[],m=()=>{a||u||c||(c=setTimeout(()=>{c=void 0,v()},250))},v=async()=>{if(a)return;u=!0;let S=l;l=!1;let x=[...d],M=new Set(h);h.clear(),d.clear();try{if(S)await le(e,t,{exact:!0});else{let P=(await Promise.allSettled(x.map(async O=>{let T=e.getQueryCache().find({queryKey:t,exact:!0});if(!T)return;let E=await R("read",{id:O});if(E.success===!1)throw new Error("Channel refresh failed");if(a||!T||e.getQueryCache().find({queryKey:t,exact:!0})!==T)return;let A=De(E.item??E);if(A.id!==O||A.item_type!=="channel")return;let F=f().find(ke=>ke.id===O);if(!F)return;let U=n({...A}),H={...F,path:U.path,name:U.name,displayName:U.displayName,messageCount:U.messageCount,aiMode:U.aiMode,activeAgentIds:U.activeAgentIds,isPrivate:U.isPrivate,isDm:U.isDm,autoPilot:U.autoPilot,isArchived:U.isArchived,updatedAt:U.updatedAt};M.has(O)&&(F.name!==H.name||F.displayName!==H.displayName||F.path!==H.path)&&(l=!0),e.setQueryData(t,ke=>ke?.map(j=>j.id===O?H:j))}))).find(O=>O.status==="rejected");if(P?.status==="rejected")throw P.reason}}catch(N){console.warn("[channels] refresh failed",N)}finally{u=!1,(l||d.size)&&m()}},g=S=>f().some(x=>x.id===S.item_id||x.path===S.path)?!0:Ms(S),w=S=>{if(!g(S))return;let x=String(S.action??"").toLowerCase();if(["insert","delete","rename","move"].includes(x))l=!0;else if(x==="update"){let M=f().find(N=>N.id===S.item_id||N.path===S.path);M&&(d.add(M.id),h.add(M.id))}(l||d.size)&&m()},y=S=>{let x=f().find(M=>M.id===S.parent_id);x&&(d.add(x.id),m())},_=["vfs_change","ccm_change"].flatMap(S=>[J(S,w,x=>x.item_type==="channel"),J(S,y,x=>x.item_type==="message")]);i={users:0,stop:()=>{a=!0,c&&clearTimeout(c),_.forEach(S=>S())}},r.set(s,i)}i.users++;let o=!1;return()=>{o||(o=!0,--i.users===0&&(i.stop(),r.delete(s)))}}var Lc=new WeakMap;function jc(e,t,n){let r=Lc.get(e);r||(r=new Map,Lc.set(e,r));let s=JSON.stringify(t),i=r.get(s);if(!i){let a,c=()=>{a||(a=setTimeout(()=>{a=void 0,le(e,t,{exact:!0})},250))},u=[J("ccm_change",c,l=>l.edge_type==="replies_to"&&(l.target_item_id??l.target_id)===n),J("vfs_change",c,l=>{let d=l.item_id??l.id;return d?d===n?!0:e.getQueryData(t)?.pages.some(f=>f.messages.some(m=>m.id===d))??!1:!1})];i={users:0,stop:()=>{a&&clearTimeout(a),u.forEach(l=>l())}},r.set(s,i)}i.users++;let o=!1;return()=>{o||(o=!0,--i.users===0&&(i.stop(),r.delete(s)))}}function te(){return(0,b.useSyncExternalStore)(Ie,G,G)}function zc(){return te(),ts()}function Jc(e){return te(),W({queryKey:I.item(e),queryFn:()=>Rr(e),enabled:!!e,staleTime:1/0})}function Yc(e){return te(),W({queryKey:I.itemById(e),queryFn:()=>xr(e),enabled:!!e,staleTime:1/0})}function Gi(e){return te(),W({queryKey:I.children(e),queryFn:()=>Pr(e),enabled:!!e})}function Xc(e){let t=Gi(e);return{...t,children:t.data??[]}}function Zc(e,t=1){return te(),W({queryKey:I.tree(e,t),queryFn:()=>ws(e,t),enabled:!!e})}function eu(e,t){return te(),W({queryKey:I.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(De)},enabled:!!e&&e.length>0})}function tu(e){te();let t=(0,b.useMemo)(()=>e,[JSON.stringify(e)]);return W({queryKey:["vfs",z()??"__unscoped__","resolve",JSON.stringify(t??{})],queryFn:async()=>await R("resolve",t),enabled:!!t?.query&&t.query.length>0})}function nu(e){te();let t=Ct(e),n=(0,b.useMemo)(()=>t,[JSON.stringify(t)]),r=W({queryKey:I.items(n?.type??"",n),queryFn:({signal:s})=>Yt(n,{signal:s,throwOnError:!0}),enabled:Hn(n),...n?.spaceIds!==void 0?{retry:(s,i)=>!qn(i)&&Ju(s,i)}:{},select:s=>s.items});return n?.spaceIds!==void 0&&qn(r.error)?{...r,data:void 0}:r}function zi(e,t={}){let n=te(),{realtime:r=!1}=t,s=Ct(e),i=s?.limit??20,o=(0,b.useMemo)(()=>s,[JSON.stringify(s)]),a=(0,b.useMemo)(()=>["vfs",z()??"__unscoped__","infinite-items",o?.type??"",JSON.stringify(o??{})],[n,o]),c=Rn({queryKey:a,queryFn:async({pageParam:d=0,signal:h})=>Yt({...o,limit:i,offset:d},{throwOnError:!0,signal:h,priority:t.priority}),initialPageParam:0,getNextPageParam:(d,h,f)=>{if(!(o?.spaceIds!==void 0&&d.total_hint!==void 0&&f+d.items.length>=d.total_hint)&&!(d.items.length<i))return f+d.items.length},enabled:Hn(o),...o?.spaceIds!==void 0?{retry:(d,h)=>!qn(h)&&Ju(d,h)}:{},staleTime:r?1/0:t.staleTime,meta:r&&o?{infiniteItemsRealtime:{filter:o}}:{}}),u=(0,b.useMemo)(()=>{if(o?.spaceIds!==void 0&&qn(c.error))return[];if(!c.data?.pages)return[];let d=new Set,h=[];for(let f of c.data.pages)for(let m of f.items)m.id&&!d.has(m.id)&&(d.add(m.id),h.push(m));return h},[c.data?.pages,c.error,o]),l=o?.spaceIds!==void 0&&qn(c.error);return{allItems:u,refetch:c.refetch,fetchNextPage:c.fetchNextPage,isFetchingNextPage:c.isFetchingNextPage,isExhausted:l||!c.hasNextPage,isLoading:c.isLoading,isFetching:c.isFetching,error:c.error,totalHint:l?void 0:c.data?.pages?.[0]?.total_hint}}function Hc(e){return!!e?.type&&!!e.scope&&e.sort_by==="created_at"&&!e.offset&&!e.spaceIds&&!e.any_of&&!e.name&&!e.tag&&!e.discovery}function _p(e,t){if(e.is_active===!1||e.item_type!==t.type||!de(e.path,t.scope)||t.parent_id&&e.parent_id!==t.parent_id)return!1;let n=e.type_data??{};for(let[r,s]of Object.entries(t.fields??{})){let i=n[r];if(typeof s=="string"&&s.endsWith("*")){if(typeof i!="string"||!i.startsWith(s.slice(0,-1)))return!1}else if(i!==s)return!1}for(let[r,s]of Object.entries(t.field_in??{}))if(!s.includes(n[r]))return!1;return!0}function ru(e,t={}){let n=Hc(e),r=zi(e,n?{realtime:!1,staleTime:3e4}:{realtime:!0}),s=L(),i=JSON.stringify([z(),Ct(e)]),[o,a]=(0,b.useState)(()=>({identity:i,upserts:{},deleted:new Set})),c=o.identity===i?o:{identity:i,upserts:{},deleted:new Set},u=(0,b.useMemo)(()=>{if(!n)return r.allItems;let f=Object.values(c.upserts),m=new Set(f.map(y=>y.id)),v=[...f,...r.allItems.filter(y=>!m.has(y.id))].filter(y=>!c.deleted.has(y.path)),g=e.sort_by??"updated_at",w=e.sort_dir==="asc"?1:-1;return v.sort((y,_)=>w*String(y[g]??"").localeCompare(String(_[g]??"")))},[n,r.allItems,c,e?.sort_by,e?.sort_dir]),l=(0,b.useRef)(u);l.current=u;let d=(0,b.useRef)(t.shouldReadUpdate);d.current=t.shouldReadUpdate;let h=(0,b.useRef)(r.refetch);return h.current=r.refetch,(0,b.useEffect)(()=>{if(!Hc(e))return;let f=e,m=!1,v=!1,g=!1,w=0,y=new Map,_=()=>{let P=w;h.current().then(O=>{!m&&!O.isError&&w===P&&a({identity:i,upserts:{},deleted:new Set})})},S=P=>{w++,a(T=>{let E=T.identity===i?T:{identity:i,upserts:{},deleted:new Set},A={...E.upserts};return delete A[P],{identity:i,upserts:A,deleted:new Set(E.deleted).add(P)}});let O=y.get("__reconcile__");O&&clearTimeout(O),y.set("__reconcile__",setTimeout(()=>{y.delete("__reconcile__"),_()},250))},x=P=>{let O=y.get(P);O&&clearTimeout(O),y.set(P,setTimeout(()=>{y.delete(P),s.fetchQuery({queryKey:I.item(P),queryFn:()=>Rr(P),staleTime:0}).then(T=>{if(!m){if(!T||!_p(T,f)){let E=l.current.find(A=>A.path===P||A.id===T?.id);E&&S(E.path);return}a(E=>{let A=E.identity===i?E:{identity:i,upserts:{},deleted:new Set},F=new Set(A.deleted);return F.delete(P),{identity:i,upserts:{...A.upserts,[P]:T},deleted:F}})}}).catch(T=>console.warn("[useIncrementalItems] item read failed:",T))},250))},M=J("vfs_change",P=>{if(!P||typeof P.path!="string"&&typeof P.old_path!="string")return;let O=typeof P.path=="string"?P.path:P.old_path,T=l.current.find(A=>A.path===O||A.path===P.old_path||P.item_id&&A.id===P.item_id),E=!!T;if(!(!de(O,f.scope)&&!de(P.old_path,f.scope)&&!E)&&!(P.item_type&&P.item_type!==f.type&&!E)&&!(f.parent_id&&P.parent_id&&P.parent_id!==f.parent_id&&!E)){if(T&&(O!==T.path||P.old_path&&P.old_path!==O||P.parent_id&&P.parent_id!==T.parent_id||P.item_type&&P.item_type!==f.type)){S(T.path);return}if(!T&&P.old_path&&P.old_path!==O&&de(O,f.scope)){w++,x(O);return}if(P.action==="insert")w++,x(O);else if(P.action==="move")w++,x(O);else if(P.action==="update"){if(!d.current?.(P,l.current))return;w++,x(O)}else P.action==="delete"&&S(T?.path??P.old_path??O)}}),N=hs(P=>{if(P!=="connected"){v&&(g=!0);return}v=!0,g&&(g=!1,_())});return()=>{m=!0,M(),N(),y.forEach(clearTimeout)}},[s,i]),{...r,allItems:u}}function su(e){te();let t=20,n=Rn({queryKey:["vfs",z()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>_s(e,t,s),initialPageParam:0,getNextPageParam:(s,i,o)=>{if(!(s.items.length<t))return o+s.items.length},enabled:!!e});return{allItems:(0,b.useMemo)(()=>{if(!n.data?.pages)return[];let s=new Set,i=[];for(let o of n.data.pages)for(let a of o.items)a.id&&!s.has(a.id)&&(s.add(a.id),i.push(a));return i},[n.data?.pages]),fetchNextPage:n.fetchNextPage,isFetchingNextPage:n.isFetchingNextPage,isExhausted:!n.hasNextPage,isLoading:n.isLoading,isFetching:n.isFetching,error:n.error,totalHint:n.data?.pages?.[0]?.total_hint}}function iu(e){return te(),W({queryKey:I.edges(e),queryFn:()=>bs(e),enabled:!!e})}function Fs(e){return te(),W({queryKey:I.types(e),queryFn:()=>vs(e)})}function ou(e,t){let n=Fs(t);return{...n,data:n.data?.get(e)??void 0}}function au(e,t){te();let n=(0,b.useMemo)(()=>t?.arguments,[JSON.stringify(t?.arguments)]),r=t?.mode,s=t?.strategy,i=t?.width;return W({queryKey:[...I.openEnvelope(e,s),i],queryFn:async()=>{let o=await Er(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 Bc={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 cu(e){let t=Fs(e),n=t.data??new Map;return(0,b.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(Bc).map(([f,m])=>({key:f,label:m})),getEdgeTypeLabel:f=>Bc[f]??f.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function uu(e,t,n){return te(),W({queryKey:I.memberFocus(e),queryFn:()=>Rs(e,t,n),enabled:!!e})}function lu(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return W({queryKey:I.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>Cr(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function du(e,t=50,n=0){return W({queryKey:I.itemHistory(e,String(t),String(n)),queryFn:()=>xs(e,t,n),enabled:!!e})}function pu(e,t=50,n=0){return te(),W({queryKey:I.recentActivity(e,String(t),String(n)),queryFn:()=>Ss(e,t,n),enabled:!!e})}function fu(){let[e,t]=(0,b.useState)(null),[n,r]=(0,b.useState)(!0),[s,i]=(0,b.useState)(null);return(0,b.useEffect)(()=>{let o=!1;return ct().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 vp=[];function Vc(){if(typeof window>"u")return!1;let e=window.__FSAOS_CONFIG__?.embedToken;return typeof e=="function"||typeof e=="string"&&e.length>0}function bp(e){return e.filter(t=>t.placement==="switcher_entry").map(t=>({account:t,mountables:e.filter(n=>n.placement!=="switcher_entry"&&n.subordinateTo===t.accountId)}))}function mu(){let{user:e}=qs(),t=(0,b.useSyncExternalStore)(Sa,Ci,Ci),n=Pt()?.principal_id??null,r=(0,b.useRef)(null),[s,i]=(0,b.useState)(null),[o,a]=(0,b.useState)(null);(0,b.useEffect)(()=>{if(n){a(null);return}if(!e?.id&&!Vc()){a(null);return}let y=!1;return ct().then(_=>{y||_.principal_id||a(new Error("Memberships require an authenticated principal"))}).catch(_=>{y||a(_ instanceof Error?_:new Error(String(_)))}),()=>{y=!0}},[n,e?.id,t]);let c=W({queryKey:I.memberships(n??"anonymous"),queryFn:Es,enabled:!!n,staleTime:1e3*60*2}),u=c.data??vp,l=(0,b.useMemo)(()=>u.filter(y=>y.isAccount!==!1&&!y.isSpace),[u]),d=(0,b.useMemo)(()=>{let y=new Set(l.map(S=>S.accountId)),_=S=>!S.subordinateTo||!y.has(S.subordinateTo);return[...l].sort((S,x)=>Number(_(x))-Number(_(S)))},[l]),h=(0,b.useSyncExternalStore)(Ie,G,G),f=(0,b.useMemo)(()=>{let y=ye();return y?u.find(_=>_.accountId===y.id)??null:null},[h,u]),m=(0,b.useMemo)(()=>bp(l),[l]);(0,b.useEffect)(()=>{if(!n){r.current=null;return}if(r.current!==n)if(i(null),d.length===1){let y=d[0];we()||Vt(Ye(y)),Zt(y.accountId),y.personalSpacePath&&en(y.personalSpacePath,_=>{let S=u.find(x=>x.accountId===_);return S?Ye(S):null}).catch(i),r.current=n}else d.length>1&&(r.current=n)},[n,d,u]);let v=(0,b.useCallback)(async y=>{let _=u.find(M=>M.path===y);if(!_)throw new Error("Account membership is unavailable");let S=Ye(_);we()||Vt(S);let x=u.find(M=>M.accountId===we()?.id);if(!x?.personalSpacePath)throw new Error("The home membership has no mount declaration location");await en(x.personalSpacePath,M=>{let N=u.find(P=>P.accountId===M);return N?Ye(N):null}),await Mr(S),i(null),Zt(_.accountId)},[u]),g=(0,b.useCallback)(async y=>{let _=u.find(S=>S.path===y);if(!_)throw new Error("Scope membership is unavailable");await ji(Ye(_))},[u]),w=(!!e?.id||Vc())&&!n&&!o;return{accounts:d,switcherAccounts:m,allMemberships:u,currentAccount:f,mountedScope:null,switchAccount:v,mountScope:g,loading:w||c.isLoading,error:o??c.error??s}}function gu(){te();let e=(0,b.useSyncExternalStore)(es,_r,_r),t=(0,b.useMemo)(()=>qe(),[e]),n=ye(),r=(0,b.useMemo)(()=>t.filter(i=>i.kind==="space"&&(n?.kind==="account"||i.id===n?.id)),[t,n]),s=(0,b.useMemo)(()=>r.map(i=>i.id).sort(),[r]);return{mounts:t,selectedSpaces:r,readSpaceIds:s,homeAnchor:we(),anchor:n,setAnchor:Mr,replaceMounts:ks,mount:ji,unmount:Fc}}function qs(){let[e,t]=(0,b.useState)(null),[n,r]=(0,b.useState)(null),[s,i]=(0,b.useState)(!0),o=(0,b.useRef)(null);(0,b.useEffect)(()=>{$.auth.getSession().then(({data:f,error:m})=>{if(m){console.warn("[useAuth] getSession error, clearing stale session:",m.message),$.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),$.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:h}}=$.auth.onAuthStateChange((f,m)=>{if(f==="TOKEN_REFRESHED"&&!m){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),$.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(m),t(m?.user??null),i(!1)});return o.current=h,()=>{h?.unsubscribe()}},[]);let a=(0,b.useCallback)(async h=>h.provider?$.auth.signInWithOAuth({provider:h.provider,options:h.redirectTo?{redirectTo:h.redirectTo}:{redirectTo:window.location.href}}):$.auth.signInWithPassword({email:h.email,password:h.password}),[]),c=(0,b.useCallback)(async h=>$.auth.signUp({email:h.email,password:h.password,options:{data:h.metadata||{}}}),[]),u=(0,b.useCallback)(async()=>{await $.auth.signOut(),On(),Q().clear()},[]),l=(0,b.useCallback)(async h=>{let{error:f}=await $.auth.resetPasswordForEmail(h);if(f)throw f},[]),d=(0,b.useCallback)(async(h,f)=>{let{error:m}=await $.auth.signInWithOtp({email:h,options:f?{emailRedirectTo:f}:{emailRedirectTo:window.location.href}});if(m)throw m},[]);return{user:e,session:n,loading:s,signIn:a,signUp:c,signOut:u,resetPassword:l,signInWithMagicLink:d}}function hu(e){let[t,n]=(0,b.useState)(null),[r,s]=(0,b.useState)(!1),[i,o]=(0,b.useState)(null);return(0,b.useEffect)(()=>{if(!e){n(null),s(!1);return}if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e))s(!0),R("resolve-asset",{asset_id:e}).then(c=>{c.success&&c.public_url?n({url:c.public_url,id:c.asset_id,name:c.name,mimeType:c.mime_type,width:c.width,height:c.height,sizeBytes:c.size_bytes}):o(new Error(c.error||"Asset not found")),s(!1)}).catch(c=>{o(c instanceof Error?c:new Error(String(c))),s(!1)});else{let u=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";n({url:u+e}),s(!1)}},[e]),{data:t,loading:r,error:i}}var Os={};oe(()=>{for(let e of Object.keys(Os))delete Os[e]});var yu=null;function _u(e){yu=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function wp(e){switch(e){case"react":return typeof window<"u"&&window.React||b.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||hp;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}:yp;case"@fsaos/gateway":case"@fsaos/react":case"@ai4b-team/fsaos-gateway-sdk":return typeof window<"u"&&window.__FSAOS_GATEWAY__||yu||{};case"@fsaos/ui":case"@ai4b-team/fsaos-gateway-sdk/ui":return typeof window<"u"&&window.__FSAOS_UI__||Hi;case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}var Fr={};async function Sp(e){try{let t=await fetch(e);if(!t.ok)return null;let n=await t.text();return!n.trim()||n.includes("No CSS bundle for this component")?null:n}catch{return null}}async function vu(e,t=()=>Sp(e)){let n=Fr[e];n||(n=Fr[e]={users:0,text:t(),style:null}),n.users+=1;let r=await n.text;if(Fr[e]!==n||n.users===0||n.style||!r||typeof document>"u")return;let s=document.createElement("style");s.setAttribute("data-fsaos-component-css",e),s.textContent=r,document.head.appendChild(s),n.style=s}function Xe(e){let t=Fr[e];t&&(t.users-=1,!(t.users>0)&&(t.style?.remove(),delete Fr[e]))}function bu(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)(wp),o=t??i;return o?o.default||o:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function Ji(e,t){let[n,r]=(0,b.useState)(null),[s,i]=(0,b.useState)(!0),[o,a]=(0,b.useState)(null),c=(0,b.useRef)(null),u=Number.isSafeInteger(t?.version)&&t.version>0?t.version:null;return(0,b.useEffect)(()=>{if(!e)return;let l=!1;a(null),c.current?.path!==e&&(c.current?.cssUrl&&Xe(c.current.cssUrl),c.current=null,r(null),i(!0));let h=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{let f=null;try{let m=1,v=e+"@v1",g=h+e+"/__bundle.js";if(u!==null)m=u,v=e+"@v"+m,g=h+e+"/__bundle.v"+m+".js";else try{let x=await fetch(h+e+"/__meta",{cache:"no-store"});x.ok&&(m=(await x.json()).version||1,v=e+"@v"+m,g=h+e+"/__bundle.v"+m+".js")}catch{g=h+e+"/__bundle.js?v="+Date.now()}if(l)return;let w=g.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");f=w;let y=vu(w),_=Os[v];if(!_){let x=await fetch(g);if(!x.ok)throw new Error(`Failed to fetch bundle: ${x.status} ${x.statusText} (${g})`);let M=await x.text();if(_=bu(M),!_)throw new Error("Bundle did not export a component. Expected window.__FSAOS_COMPONENT__ (FSAOS build) or a __FSAOS_REGISTER__(Component) call.");if(typeof _!="function")throw new Error(`Bundle export is not a React component (got ${typeof _})`);Os[v]=_}if(await y,l){Xe(w);return}let S=c.current?.cssUrl??null;c.current={path:e,cssUrl:w},f=null,r(()=>_),i(!1),S&&Xe(S)}catch(m){f&&Xe(f),l||(a(m instanceof Error?m:new Error(String(m))),i(!1))}})(),()=>{l=!0}},[e,u]),(0,b.useEffect)(()=>()=>{c.current?.cssUrl&&Xe(c.current.cssUrl),c.current=null},[]),{Component:n,loading:s,error:o}}var xp=/^embed\/bundle-[A-Za-z0-9_-]+\.js$/,Rp=/^embed\/bundle-[A-Za-z0-9_-]+\.css$/;function Wc(e,t,n){let r=Object.keys(e).filter(o=>t.test(o));if(r.length>1)throw new Error(`The published release has more than one in-app ${n}.`);let s=r[0];if(!s)return null;let i=At(e[s]).sha256;return typeof i=="string"&&i?{path:s,sha256:i}:null}var Or=new Map,Wi=new Map;oe(()=>{Or.clear(),Wi.clear()});function At(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function wu(e){let t=At(At(e.type_data).published),n=t.published_release_item_id,r=t.published_version;return typeof n!="string"||!n||typeof r!="number"||!Number.isSafeInteger(r)||r<1?null:{releaseItemId:n,version:r}}async function $c(e,t,n){let r=await Er(e.path,{mode:"render"}),s=At(At(r.render).props).url;if(typeof s!="string"||!s)throw new Error(`The published ${n} could not be opened.`);let i=await fetch(s);if(!i.ok)throw new Error(`Failed to read the published ${n}: ${i.status} ${i.statusText}`.trim());let o=await i.arrayBuffer();if(Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",o))).map(c=>c.toString(16).padStart(2,"0")).join("")!==t)throw new Error(`The published ${n} does not match the bytes its release sealed.`);return new TextDecoder().decode(o)}async function Pp(e,t,n){let r=await xr(t);if(!r)throw new Error("The published release could not be read.");let s=At(r.type_data);if(r.item_type!=="revdev_release"||s.component_item_id!==e||s.status!=="committed"||Number(s.version)!==n)throw new Error("This component's live version does not match its release record.");let i=At(s.artifacts),o=Wc(i,xp,"script");if(!o)return{status:"no_in_app_version",releaseItemId:t,version:n};let a=Wc(i,Rp,"stylesheet"),c=a?[o.path,a.path]:[o.path],u=s.build_item_id;if(typeof u!="string"||!u)throw new Error("The published release names no build.");let{items:l}=await Yt({type:"file",parent_id:u,field_in:{package_path:c},limit:c.length},{throwOnError:!0}),d=g=>l.find(w=>At(w.type_data).package_path===g),h=d(o.path),f=a?d(a.path):void 0;if(!h||a&&!f)throw new Error("The published release's in-app files could not be found in its build.");let[m,v]=await Promise.all([$c(h,o.sha256,"script"),f&&a?$c(f,a.sha256,"stylesheet"):Promise.resolve(null)]);return{status:"ready",releaseItemId:t,version:n,script:m,stylesheet:v?.trim()?v:null}}function Su(e,t,n){let r=Or.get(t);return r||(r=Pp(e,t,n),Or.set(t,r),r.catch(()=>{Or.get(t)===r&&Or.delete(t)})),r}function xu(e){let t=wu(e);return!e.id||!t?Promise.resolve({status:"unpublished"}):Su(e.id,t.releaseItemId,t.version)}function Ru(e){let[t,n]=(0,b.useState)(null),[r,s]=(0,b.useState)("loading"),[i,o]=(0,b.useState)(null),a=(0,b.useRef)(null),c=e!=null,u=e?.id||null,l=e?wu(e):null,d=l?.releaseItemId??null,h=l?.version??null;return(0,b.useEffect)(()=>{if(!c)return;let f=()=>{a.current?.cssKey&&Xe(a.current.cssKey),a.current=null,n(null)};if(!u||!d||h===null){f(),o(null),s("unpublished");return}let m=!1;return o(null),a.current&&a.current.componentId!==u&&f(),a.current||s("loading"),(async()=>{let v=null;try{let g=await Su(u,d,h);if(m)return;if(g.status!=="ready"){f(),s(g.status);return}let w=Wi.get(d);if(!w){if(w=bu(g.script),!w)throw new Error("The published script did not hand over a component. Expected a __FSAOS_REGISTER__(Component) call or window.__FSAOS_COMPONENT__.");if(typeof w!="function")throw new Error(`The published script handed over something that is not a React component (${typeof w}).`);Wi.set(d,w)}let y=g.stylesheet?`release:${d}`:null;if(y&&(v=y,await vu(y,async()=>g.stylesheet)),m){v&&Xe(v);return}let _=a.current?.cssKey??null;a.current={componentId:u,releaseItemId:d,cssKey:y},v=null,n({Component:w,version:h}),s("ready"),_&&Xe(_)}catch(g){if(v&&Xe(v),m)return;o(g instanceof Error?g:new Error(String(g))),a.current||s("error")}})(),()=>{m=!0}},[c,u,d,h]),(0,b.useEffect)(()=>()=>{a.current?.cssKey&&Xe(a.current.cssKey),a.current=null},[]),{Component:t?.Component??null,status:r,error:i,version:t?.version??null}}var Cp=["--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 Pu(){return{data:(0,b.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let t={},n=getComputedStyle(document.documentElement);return Cp.forEach(r=>{t[r]=n.getPropertyValue(r).trim()}),{tokens:t}},[]),loading:!1,error:null}}function Cu(e,t){return{data:{allowed:!0},loading:!1,error:null}}function Eu(e,t){let n={};return(t||[]).forEach(r=>{n[r]=!0}),{data:n,loading:!1,error:null}}var _e=null,Gn=null,$i=new Set;function Ep(){$i.forEach(e=>e())}oe(()=>{_e=null,Gn=null});async function Iu(e){let t={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null},n=Pt()?.principal_id??null;if(n){if(_e&&_e.principalId===n){let{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}=_e;return{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}}return{...t,principalId:n}}let r=e;if(!r){let{data:s}=await $.auth.getSession();r=s?.session?.user?.id}if(!r)return t;if(_e&&_e.authUserId===r){let{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}=_e;return{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}}return Gn||(Gn=(async()=>{try{let{data:s,error:i}=await $.from("os_principals").select("id, display_name, created_at, metadata").eq("auth_user_id",r).eq("principal_type","user").maybeSingle();if(i)return console.warn("[SDK] Could not resolve principal:",i.message),t;let o=s?.id??null,a=null;if(o){let{data:u}=await $.from("os_items").select("path").eq("owner_principal_id",o).eq("item_type","principal").eq("is_active",!0).like("path","/root/principals/%"),l=(u??[]).map(d=>d.path);a=l.find(d=>d.split("/").length===4)??l[0]??null}let c={principalId:o,displayName:s?.display_name??null,createdAt:s?.created_at??null,metadata:s?.metadata??null,vfsPath:a};return _e={authUserId:r,...c},c}finally{Gn=null}})(),Gn)}async function Tu(e){return(await Iu(e)).principalId}function Au(){let e=qs(),t=e.user,n=_e?.authUserId===t?.id?_e:null,[r,s]=(0,b.useState)(n),i=(0,b.useRef)(null);return(0,b.useEffect)(()=>{let o=()=>{let a=_e;a&&a.authUserId===t?.id&&s({principalId:a.principalId,displayName:a.displayName,createdAt:a.createdAt,metadata:a.metadata,vfsPath:a.vfsPath})};return $i.add(o),()=>{$i.delete(o)}},[t?.id]),(0,b.useEffect)(()=>{if(!t?.id){s(null),i.current=null;return}i.current===t.id&&r?.principalId!=null||(i.current=t.id,Iu(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 ku(e){let{path:t,...n}=e,r=Ji(t),s=r.Component,{loading:i,error:o}=r;return i?(0,b.createElement)("div",{className:"fsaos-loading"},""):o?(0,b.createElement)("div",{className:"fsaos-error"},"Failed to load component"):s?(0,b.createElement)(s,n):null}function Mu(e){return e.children}function Ou(e){let t=te(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=e,o=i!==void 0?i&&!!n:!!n,a=(0,b.useMemo)(()=>I.channelMessages(n??"",r),[n,r,t]),c=L(),u=(0,b.useRef)(null),l=W({queryKey:a,queryFn:()=>Cs(n,r),enabled:o});(0,b.useEffect)(()=>{if(!s||!o)return;let v=J("vfs_change",()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{le(c,a,{exact:!0})},500)},g=>{let w=c.getQueryData(a);return $n(g,n,r,[...w?.messages??[],...w?.activityMessages??[]])});return()=>{v(),u.current&&clearTimeout(u.current)}},[s,o,n,r,a,c]);let d=l.data,h=d?.messages??[],f=d?.messageCards??new Map,m=d?.siblingCards??[];return{messages:h,activityMessages:d?.activityMessages??[],messageCards:f,siblingCards:m,threads:(0,b.useMemo)(()=>h.filter(v=>v.reply_count>0),[h]),breakouts:(0,b.useMemo)(()=>h.filter(v=>v.member_count>0),[h]),isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function Fu(e){let t=te(),{channelPath:n,messageId:r,conversationRootId:s,enabled:i=!0,realtime:o=!0,limit:a=25}=e,c=i&&!!n&&!!r,u=(0,b.useMemo)(()=>I.messageReplies(n??"",r,s,a),[n,r,s,a,t]),l=L(),d=Rn({queryKey:u,queryFn:({pageParam:f})=>Ps(r,{limit:a,conversationRootId:s,cursor:f}),initialPageParam:void 0,getNextPageParam:f=>f.next_cursor??void 0,enabled:c,staleTime:1/0,refetchOnMount:"always",refetchOnWindowFocus:!1,retry:!1});(0,b.useEffect)(()=>c&&o?jc(l,u,r):void 0,[c,o,l,u,r]);let h=(0,b.useMemo)(()=>{if(!c||d.isError)return[];let f=new Set;return(d.data?.pages??[]).flatMap(m=>m.messages).filter(m=>f.has(m.id)?!1:(f.add(m.id),!0))},[c,d.data,d.isError]);return{...d,messages:h}}function qu(e){let t=te(),{channelPath:n,parentMessageId:r,limit:s=50,realtime:i=!0,enabled:o=!0,conversationsOnly:a=!1,transcriptOnly:c=!1}=e,u=!!r,l=o&&!!n,d=Rn({queryKey:[...I.channelMessages(n||"",r),"infinite",s,"latest-first",...a?["conversations"]:[],...c?["transcript"]:[]],queryFn:async({pageParam:y})=>{let _=await Xt(n,{parentMessageId:r,limit:s,conversationsOnly:a,transcriptOnly:c,before_seq:y?.before_seq,after_seq:y?.after_seq});return c&&_.messages.length>=s?{..._,olderBefore:_.messages[0]?.seq}:_},initialPageParam:void 0,getPreviousPageParam:y=>{if(!u||y.messages.length<s)return;let _=y.messages[y.messages.length-1]?.seq;return _==null?void 0:{after_seq:_}},getNextPageParam:y=>{if(c)return y.olderBefore==null?void 0:{before_seq:y.olderBefore};if(y.messages.length<s)return;let _=y.messages[0]?.seq;return _==null?void 0:{before_seq:_}},enabled:l}),h=(0,b.useMemo)(()=>{if(!d.data?.pages)return[];let y=new Set,_=[];for(let S of d.data.pages)for(let x of S.messages)y.has(x.id)||(y.add(x.id),_.push(x));return _.sort((S,x)=>S.seq-x.seq)},[d.data?.pages]),{messageCards:f,siblingCards:m}=(0,b.useMemo)(()=>{let y=new Map,_=[];if(!d.data?.pages)return{messageCards:y,siblingCards:_};let S=new Set;for(let[x,M]of d.data.pages.entries()){let N=c&&x>0?new Set(M.messages.map(P=>P.path)):null;for(let[P,O]of M.messageCards)if(!(N&&!N.has(P)))for(let T of O){if(S.has(T.id))continue;S.add(T.id);let E=y.get(P)||[];E.push(T),y.set(P,E)}if(!(c&&x>0))for(let P of M.siblingCards)S.has(P.id)||(S.add(P.id),_.push(P))}return{messageCards:y,siblingCards:_}},[d.data?.pages,c]),v=L(),g=(0,b.useRef)(null),w=(0,b.useMemo)(()=>[...I.channelMessages(n||"",r),"infinite",s,"latest-first",...a?["conversations"]:[],...c?["transcript"]:[]],[n,r,s,a,c,t]);return(0,b.useEffect)(()=>{if(!i||!n||!l)return;if(c)return Dc(v,w,n,s);let y=()=>void le(v,w,{exact:!0}),_=!1,S=!1,x=!1,M=async()=>{if(a){y();return}let O=v.getQueryData(w);if(!O?.pages?.length){y();return}let T=0;for(let E of O.pages)for(let A of E.messages)A.seq>T&&(T=A.seq);if(T===0){y();return}try{let E=await Xt(n,{parentMessageId:r,limit:s,after_seq:T});if(E.messages.length===0&&E.siblingCards.length===0){y();return}if(E.messages.length>0){let A=Math.min(...E.messages.map(F=>F.seq));if(A>T+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${T}, minNewSeq=${A}. Triggering full refetch.`),y();return}}v.setQueryData(w,A=>{if(!A)return A;let F=[...A.pages],U=0,H=F[U],ke=new Set(H.messages.map(ge=>ge.id)),j=E.messages.filter(ge=>!ke.has(ge.id)),me=[...H.messages,...j].sort((ge,Hs)=>ge.seq-Hs.seq),ve=new Map(H.messageCards);for(let[ge,Hs]of E.messageCards){let ho=ve.get(ge)||[],Zl=new Set(ho.map(Bs=>Bs.id)),ed=Hs.filter(Bs=>!Zl.has(Bs.id));ve.set(ge,[...ho,...ed])}let Ue=new Set(H.siblingCards.map(ge=>ge.id)),ce=E.siblingCards.filter(ge=>!Ue.has(ge.id)),pe=[...H.siblingCards,...ce];return F[U]={...H,activityMessages:E.activityMessages??[],messages:me,messageCards:ve,siblingCards:pe},{...A,pages:F}})}catch(E){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",E),y()}},N=async()=>{if(_){S=!0;return}_=!0;try{do S=!1,await M();while(S&&!x)}finally{_=!1}},P=J("vfs_change",()=>{g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{N()},500)},O=>a&&O?.item_type==="message"&&(v.getQueryData(w)?.pages??[]).some(T=>T.messages.some(E=>E.id===O.parent_id))||$n(O,n,r,v.getQueryData(w)?.pages.flatMap(T=>T.messages)??[]));return()=>{x=!0,P(),g.current&&clearTimeout(g.current)}},[i,n,l,w,v,r,s,a,c]),{messages:h,activityMessages:d.data?.pages[0]?.activityMessages??[],messageCards:f,siblingCards:m,threads:h.filter(y=>y.reply_count>0),breakouts:h.filter(y=>y.member_count>0),isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,refetch:d.refetch,hasPreviousPage:d.hasNextPage??!1,fetchPreviousPage:d.fetchNextPage,isFetchingPreviousPage:d.isFetchingNextPage??!1,hasNextPage:d.hasPreviousPage??!1,fetchNextPage:d.fetchPreviousPage,isFetchingNextPage:d.isFetchingPreviousPage??!1}}var Nu=["open","active","strict","hand_raise"];function Ip(e){return e==="open"||e==="active"||e==="strict"||e==="hand_raise"?e:e==="on"||e==="auto"?"active":"strict"}function Tp(e){if(Array.isArray(e))return e.filter(t=>typeof t=="string")}function Gc(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:Ip(t.ai_mode),activeAgentIds:Tp(t.active_agent_ids),isPrivate:t.is_private||!1,isDm:t.is_dm||!1,messageCount:t.message_count||0,createdAt:e.created_at||"",updatedAt:e.updated_at||"",chatScopePath:r.context_path||"",contextId:e.scope_item_id||"",contextPath:r.context_path||"",contextType:r.context_type||"",contextName:r.context_name||"",contextDisplayName:r.context_name||"",contextPrincipalId:void 0,accountId:e.account_item_id||"",accountPath:"",accountDisplayName:"",memberRole:n.member_role||"member",memberPath:"",modePath:"",autoPilot:t.auto_pilot||!1,isArchived:t.is_archived===!0}}function Ns(e={}){let t=te(),{realtime:n=!0,enabled:r=!0,includeArchived:s=!1}=e,i=L(),o=(0,b.useMemo)(()=>I.channels("all"),[t]),a=W({queryKey:o,queryFn:async()=>((await R("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(Gc),enabled:r});return(0,b.useEffect)(()=>{if(!(!n||!r))return Kc(i,o,Gc)},[n,r,o,i]),{channels:(0,b.useMemo)(()=>(a.data??[]).filter(u=>s||!u.isArchived),[a.data,s]),isLoading:a.isLoading,isFetching:a.isFetching,error:a.error,refetch:a.refetch}}function Qu(e={}){let t=Ns(e),n=(0,b.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function Du(e={}){let t=Ns(e),n=(0,b.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function Yi(e={}){let t=te(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=e,o=L(),a=(0,b.useRef)(null),c=(0,b.useMemo)(()=>I.notifications(n,r),[n,r,t]),u=W({queryKey:c,queryFn:async()=>{let d={limit:r};return n==="unread"&&(d.filter="unread"),(await R("get-notifications",d)).notifications||[]},enabled:i});return(0,b.useEffect)(()=>{if(!s||!i)return;let d=["vfs_change","ccm_change"].map(h=>J(h,()=>{a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{o.invalidateQueries({queryKey:c})},2e3)},f=>f.item_type==="notification"&&Ms(f)));return()=>{d.forEach(h=>h()),a.current&&clearTimeout(a.current)}},[s,i,c,o]),{notifications:u.data??[],isLoading:u.isLoading,isFetching:u.isFetching,error:u.error,refetch:u.refetch}}function Uu(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:o,error:a,refetch:c}=Yi({filter:"unread",limit:200,realtime:n,enabled:r}),u=(0,b.useMemo)(()=>{let f=new Map;for(let m of s)m.is_unread&&m.channel_id&&f.set(m.channel_id,(f.get(m.channel_id)||0)+1);return f},[s]),l=(0,b.useMemo)(()=>{let f=0;return u.forEach(m=>{f+=m}),f},[u]),{dmUnread:d,channelUnread:h}=(0,b.useMemo)(()=>{if(!t)return{dmUnread:0,channelUnread:0};let f=new Set(t.filter(g=>g.isDm).map(g=>g.id)),m=0,v=0;return u.forEach((g,w)=>{f.has(w)?m+=g:v+=g}),{dmUnread:m,channelUnread:v}},[t,u]);return{unreadByChannel:u,totalUnread:l,dmUnread:d,channelUnread:h,isLoading:i,isFetching:o,error:a,refetch:c}}function Ku(){let e=L();return ie({mutationFn:t=>R("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:I.children(r)})}})}function Lu(){let e=L();return ie({mutationFn:t=>R("update",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.invalidateQueries({queryKey:I.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:I.children(i)})}}})}function ju(){return ie({mutationFn:e=>R("update-principal",e),onSuccess:(e,t)=>{if(!_e)return;let n=e&&typeof e=="object"&&e.metadata?e.metadata:{..._e.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}:{}};_e={..._e,displayName:typeof t.display_name=="string"?t.display_name:_e.displayName,metadata:n},Ep()}})}function Hu(){let e=L();return ie({mutationFn:t=>R("delete",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.removeQueries({queryKey:I.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:I.children(i)})}}})}function Bu(){let e=L();return ie({mutationFn:t=>R("move",t),onSuccess:(t,n)=>{let r=n.path,s=n.new_parent_path;if(r){e.invalidateQueries({queryKey:I.item(r)});let i=r.split("/");i.pop();let o=i.join("/");o&&e.invalidateQueries({queryKey:I.children(o)})}s&&e.invalidateQueries({queryKey:I.children(s)})}})}function Vu(){let e=L();return ie({mutationFn:t=>R("link",t),onSuccess:(t,n)=>{let r=n.source_id,s=n.target_id;r&&e.invalidateQueries({queryKey:I.edges(r)}),s&&e.invalidateQueries({queryKey:I.edges(s)})}})}function Wu(e,t){let n=L(),{optimistic:r,...s}=t??{};return ie({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 $u(e,t,n){let r,s,i,o=!0;if(typeof e=="string")r=e,s=t,i=n;else{s=e;let u=t;r=u.eventType,i=u.filter,o=u.enabled??!0}let a=(0,b.useRef)(s),c=(0,b.useRef)(i);(0,b.useEffect)(()=>{a.current=s,c.current=i},[s,i]),(0,b.useEffect)(()=>o?J(r,l=>a.current(l),c.current?l=>c.current(l):void 0):void 0,[r,o])}function Gu(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:o=500}=e,a=L(),c=(0,b.useRef)(s);c.current=s;let u=(0,b.useRef)(null),l=W({queryKey:t,queryFn:n,enabled:i});return(0,b.useEffect)(()=>{if(!i)return;let d=J(r,()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{le(a,t,{exact:!0})},o)},h=>c.current?.(h)??!0);return()=>{d(),u.current&&clearTimeout(u.current)}},[r,i,o,a,JSON.stringify(t)]),l}function zn(e){te();let t=z(),n=(0,b.useMemo)(()=>e?typeof e=="string"?{path:e}:e:null,[typeof e=="string"?e:JSON.stringify(e)]),r=n?._scope_path??t,s=!!t&&!!r&&!!n&&!!(n.key||n.path||n.item_id),i=n?.key??n?.path??n?.item_id??"",o=["vfs",r??"__unscoped__","arrangement",i,n?.scope_id??""],a=W({queryKey:o,staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0},queryFn:async()=>{if(!n)return null;let f=await R("resolve-arrangement",{...n,_scope_path:r});if(f?.success===!1)throw new Error(f?.error||"Arrangement could not be loaded");return f??null},enabled:s}),c=a.data??null,u=(0,b.useMemo)(()=>c?.resolved_children??[],[c]),l=c?.resolution_level??null,d=(0,b.useMemo)(()=>{let m=(c?.type_data??null)?.order;return Array.isArray(m)?m:null},[c]),h=(0,b.useCallback)(f=>{if(!d||!f?.length)return f??[];let m=y=>y.id??y.name??"",v=new Map(d.map((y,_)=>[y,_])),g=[],w=[];for(let y of f)(v.has(m(y))?g:w).push(y);return g.sort((y,_)=>v.get(m(y))-v.get(m(_))),[...g,...w]},[d]);return{...a,arrangement:c,resolvedChildren:u,resolutionLevel:l,order:d,sourceScopeId:c?.scope_item_id??null,arrangementQueryKey:o,applyTo:h}}function zu(e){let{origin:t,originField:n,fallbackUrl:r,mintError:s,scopeId:i,scopePath:o}=e,a=te(),c=Pt(),u=i??c?.scope_id??null,l=(0,b.useMemo)(()=>{if(!t)return null;let x="/accounts/",M=t.indexOf(x);if(M===-1)return null;let N=t.indexOf("/",M+x.length);return N===-1?t:t.slice(0,N)},[t]),d=o??l??c?.scope_path??null,h=n?.trim()||null,f=`${a}
4
4
  ${u??""}
5
5
  ${d??""}
6
6
  ${h??""}
7
- ${t??""}`,[m,v]=(0,b.useState)(null),g=(0,b.useRef)({key:f,found:null,earlyContentPaths:new Set}),w=m?.key===f?m:null;(0,b.useLayoutEffect)(()=>{g.current={key:f,found:w,earlyContentPaths:new Set}},[f]);let y=W({queryKey:["vfs",d??"__unscoped__","minted-asset",h??"",t??""],queryFn:async()=>{let x=await R("query",{scope_path:d,filters:{[`field.${h}`]:t},limit:1}),k=x.content?.items??x.items??[],N=k[0]?De(k[0]):null;if(!N)return null;let O=(await Cr(N.path)).some(T=>T.item_type==="file"&&!!T.type_data?.file_ref);return{asset:N,hasBytes:O}},enabled:!!(t&&d&&h&&!s),refetchInterval:x=>g.current.key===f&&g.current.found?.hasBytes||x.state.data?.hasBytes?!1:1500});(0,b.useEffect)(()=>{let x=y.data;if(!x||g.current.key!==f)return;let k=g.current.found,N={key:f,itemId:x.asset.id,itemPath:x.asset.path,displayName:typeof x.asset.type_data?.display_name=="string"?x.asset.type_data.display_name:x.asset.name,hasBytes:x.hasBytes||!!(k?.itemId===x.asset.id&&k.hasBytes)};g.current.found=N,v(N)},[y.data,f]);let _=!!(t&&u)&&!s&&!w?.hasBytes;return(0,b.useEffect)(()=>{if(!(!_||!u))return Ln(u,["asset.materialized","content.written"])},[_,u]),(0,b.useEffect)(()=>{if(!_||!t||!u)return;let x=f,k=E=>E?.payload??E,N=E=>{let F=k(E)?.scope_id??E?.scope_id;return typeof F=="string"?F:void 0},C=E=>{let F=k(E)?.item_path??E?.item_path;return typeof F=="string"&&F?F:void 0},O=(E,A)=>{let F=A.replace(/\/+$/,"");return E===F||E.startsWith(`${F}/`)},T=[J("asset.materialized",E=>{if(g.current.key!==x)return;let A=k(E);if(typeof A?.item_id!="string"||!A.item_id)return;let F=g.current.found,U=typeof A.item_path=="string"?A.item_path:void 0,j=!!A.has_bytes||!!(U&&Array.from(g.current.earlyContentPaths).some(H=>O(H,U)))||!!(F&&F.itemId===A.item_id&&F.hasBytes),Me={key:x,itemId:A.item_id,itemPath:U,displayName:typeof A.display_name=="string"?A.display_name:void 0,hasBytes:j};g.current.found=Me,v(Me)},E=>{let A=N(E);return(!A||A===u)&&k(E)?.origin===t}),J("content.written",E=>{if(g.current.key!==x)return;let A=C(E);if(!A)return;let F=g.current.found;if(!F?.itemPath||!O(A,F.itemPath)){if(g.current.earlyContentPaths.add(A),g.current.earlyContentPaths.size>128){let j=g.current.earlyContentPaths.values().next().value;j&&g.current.earlyContentPaths.delete(j)}return}if(F.hasBytes)return;let U={...F,hasBytes:!0};g.current.found=U,v(U)},E=>{let A=N(E);return(!A||A===u)&&!!C(E)})];return()=>T.forEach(E=>E())},[_,t,u,f]),{state:s?"failed":t?w?w.hasBytes?"ready":"materializing":"pending":"idle",itemId:w?.itemId,itemPath:w?.itemPath,displayName:w?.displayName,fallbackUrl:r??void 0,error:s??void 0}}function Ju(e,t){let n=Q().getDefaultOptions().queries?.retry??1;return typeof n=="function"?n(e,t):n===!0||typeof n=="number"&&e<n}function Yu(e,t,n){let r=(0,Mt.useSyncExternalStore)(Ie,G,G),s=ye(),i=z(),o=n?.path??i,a=n?.id??s?.id,c=!!(n?.id&&n.path)||s?.kind==="space",u=(0,Mt.useMemo)(()=>({}),[r,i,o,a]),l=(0,Mt.useRef)(u);l.current=u;let d=zn(c&&o?{key:e,scope_id:a,_scope_path:o}:null),h=(0,Mt.useMemo)(()=>{let y=d.applyTo([...t]);if(e!=="channel-order")return y;let _=new Set(d.order??[]),S=y.filter(k=>!_.has(k.id)),x=k=>Date.parse(k.createdAt??"")||0;return S.sort((k,N)=>x(N)-x(k)),[...S,...y.filter(k=>_.has(k.id))]},[e,t,d.applyTo,d.order]),f=L(),m=(0,Mt.useRef)(!1),v=!!(c&&!d.error&&d.arrangement?.item_id&&d.resolutionLevel==="member"&&d.arrangement.write_target_id===d.arrangement.item_id),g=ie({mutationFn:async y=>{let _=await R("update",{_scope_path:y.scopePath,id:y.arrangementId,type_data:{order:y.ids}});if(_?.success===!1)throw new Error(_.error||"Order could not be saved");return _},onSettled:(y,_,S)=>ut(f,S.queryKey)});async function w(y){if(!v||!o||u!==l.current||r!==G()||z()!==i)throw new Error("Personal order is not available in this Space");if(m.current)throw new Error("An order change is already being saved");let _=t.map(T=>T.id);if(y.length!==_.length||new Set(y).size!==_.length||_.some(T=>!y.includes(T)))throw new Error("Order must include each displayed item exactly once");let S=f.getQueryData(d.arrangementQueryKey);if(S?.item_id!==d.arrangement.item_id||JSON.stringify(S?.type_data?.order??[])!==JSON.stringify(d.order??[]))throw new Error("The saved order changed. Try dragging again");let x=h.map(T=>T.id);if(y.every((T,E)=>x[E]===T))return;let k=new Set(_),N=0,O=[...(d.order??[]).map(T=>k.has(T)?y[N++]:T),...y.slice(N)];m.current=!0;try{return await g.mutateAsync({ids:O,scopePath:o,arrangementId:d.arrangement.item_id,queryKey:d.arrangementQueryKey})}finally{m.current=!1}}return{items:h,ready:v,supported:c,contextKey:`${r}:${o}:${e}`,isLoading:c&&d.isLoading,error:d.error,refetch:d.refetch,isSaving:g.isPending,saveError:g.error,reorder:w}}var Xi=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Pp=/^[A-Za-z_:][A-Za-z0-9_:.-]{0,127}$/,Xu=new Map,Zu=new Map,Jn=class extends Error{constructor(n,r,s,i){super(n);X(this,"code");X(this,"status");X(this,"eventId");this.name="InteractionTrackingError",this.code=r,this.status=s,this.eventId=i}};function tn(e){let t=e?jt.find(n=>n.id===e):jt.find(n=>n.default===!0)??(jt.length===1?jt[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 Qs(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 Ep(e){return e.length>0&&e.length<=128&&!/[\u0000-\u001f\u007f]/.test(e)}function Ip(e,t){if(!Ep(t)||!e.observations?.includes(t))throw new TypeError("The observation is not declared by this release source")}function Zi(e){if(!(typeof window>"u"||e.storage==="memory"))try{return e.storage==="session"?window.sessionStorage:window.localStorage}catch{return}}function Tp(e){try{let t=Zi(e)?.getItem(e.key)??void 0;return t&&Xi.test(t)?t:void 0}catch{return}}function el(e,t){try{Zi(e)?.setItem(e.key,t)}catch{}}function tl(e){let t=e.identity?.visitor;if(!t?.key)throw new TypeError("The source visitor identity policy is invalid");let n=Tp(t)??Xu.get(e.id);if(n)return n;let r=crypto.randomUUID();return Xu.set(e.id,r),el(t,r),r}function nl(e,t=Date.now()){let n=e.identity?.session;if(!n?.key||!Number.isInteger(n.idle_seconds)||n.idle_seconds<1)throw new TypeError("The source session identity policy is invalid");let r;try{let u=Zi(n)?.getItem(n.key);r=u?JSON.parse(u):void 0}catch{r=void 0}let s=Zu.get(e.id),i=r&&typeof r.id=="string"&&Xi.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 Zu.set(e.id,c),el(n,JSON.stringify(c)),c.id}function Ap(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 nn(e,t={},n={}){let r=tn(n.source);if(Ip(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??tl(r),o=n.sessionId??nl(r);if(![s,i,o].every(g=>Xi.test(g)))throw new TypeError("event, visitor, and session IDs must be UUIDs");let a=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!a)throw new TypeError("pageUrl is required outside a browser");let c=n.occurredAt??new Date().toISOString();if(Number.isNaN(Date.parse(c)))throw new TypeError("occurredAt is invalid");let u=n.referrer??(typeof document<"u"&&document.referrer||void 0),l=Ap(r,a),d=l?{...t,source_keys:l}:t,h=Wt(),f=`${Fe.replace(/\/+$/,"")}/d/${encodeURIComponent(h)}/interactions`,m;try{m=await fetch(f,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({source:r.id,page_url:a,visitor_id:i,session_id:o,referrer:u,events:[{id:s,event_type:e,occurred_at:c,properties:d}]}),signal:n.signal,credentials:"omit",keepalive:n.keepalive??!1})}catch(g){throw new Jn(g instanceof Error?g.message:"Observation transport network error","OBSERVATION_NETWORK_ERROR",0,s)}let v=null;try{v=await m.json()}catch{}if(!m.ok||v?.success!==!0){let g=v;throw new Jn(g?.message||g?.error||`Observation transport failed (${m.status})`,g?.error||"OBSERVATION_TRANSPORT_FAILED",m.status,s)}return v}function rl(e={},t={}){let n=tn(t.source),r=Qs("page_view",n),s=typeof document>"u"||!r.title_property?{}:{[r.title_property]:document.title.slice(0,512)};return nn(r.observation,{...s,...e},{...t,source:n.id})}function sl(e,t={},n={}){if(!e||e.length>128)throw new TypeError("actionId is invalid");let r=tn(n.source),s=Qs("declared_action",r),i=s.id_property?{[s.id_property]:e}:{};return nn(s.observation,{...t,...i},{...n,source:r.id})}function il(){try{let e=tn();return Qs("form_receipt",e),{visitor_id:tl(e),session_id:nl(e),source:e.id}}catch{return}}function Mp(e,t={}){let n=tn(t.source),r=Qs("form_receipt",n);return nn(r.observation,e,{...t,source:n.id})}async function kp(e,t){let r=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${e}\0${t}`))).slice(0,16);r[6]=r[6]&15|80,r[8]=r[8]&63|128;let s=Array.from(r,i=>i.toString(16).padStart(2,"0")).join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}async function ol(e,t,n,r,s){let i=jt.filter(o=>o.adapters?.some(a=>a.type==="form_receipt"));await Promise.allSettled(i.map(async o=>{let a=o.id===r?.source;return Mp(e,{source:o.id,eventId:a?t:await kp(t,o.id),pageUrl:n,signal:s,keepalive:!0,...a?{visitorId:r.visitor_id,sessionId:r.session_id}:{}})}))}var qr;function Ds(e={}){if(typeof window>"u"||typeof document>"u")return()=>{};if(qr)return qr;if(window.__FSAOS_CONFIG__?.tracking?.enabled===!1)return()=>{};let t;try{t=e.source?[tn(e.source)]:jt.map(h=>tn(h.id))}catch{return()=>{}}if(t.length===0)return()=>{};let n=e.pageViews===!1?[]:t.flatMap(h=>h.adapters.filter(f=>f.type==="page_view").map(f=>({source:h,adapter:f}))),r=e.declaredActions===!1?[]:t.flatMap(h=>h.adapters.filter(f=>f.type==="declared_action").map(f=>({source:h,adapter:f}))),s="",i=()=>{if(window.location.href!==s){s=window.location.href;for(let{source:h,adapter:f}of n){let m=f.title_property?{[f.title_property]:document.title.slice(0,512)}:{};nn(f.observation,m,{source:h.id,keepalive:!0}).catch(()=>{})}}},o=h=>{if(h.target instanceof Element)for(let{source:f,adapter:m}of r){let v=m.attribute;if(!v||!Pp.test(v))continue;let g=h.target.closest(`[${v}]`);if(!g)continue;let w=g.getAttribute(v)?.trim();if(!w||w.length>128)continue;let y={};m.id_property&&(y[m.id_property]=w),m.element_property&&(y[m.element_property]=g.tagName.toLowerCase()),nn(m.observation,y,{source:f.id,keepalive:!0}).catch(()=>{})}},a=window.history.pushState,c=window.history.replaceState,u=()=>queueMicrotask(i),l=n.some(({adapter:h})=>h.history===!0),d=n.some(({adapter:h})=>h.pageshow===!0);return l&&(window.history.pushState=function(...f){a.apply(this,f),u()},window.history.replaceState=function(...f){c.apply(this,f),u()},window.addEventListener("popstate",i)),d&&window.addEventListener("pageshow",i),r.length>0&&document.addEventListener("click",o,{capture:!0}),n.length>0&&queueMicrotask(i),qr=()=>{window.removeEventListener("popstate",i),window.removeEventListener("pageshow",i),document.removeEventListener("click",o,{capture:!0}),l&&(window.history.pushState=a,window.history.replaceState=c),qr=void 0},qr}var Yn;oe(()=>{Yn=void 0});function Us(e){if(Yn)return Yn.accountPath!==e.accountPath?Promise.reject(new Error("Reset the session before changing accounts")):Yn.promise;let t=Z(),n=()=>{if(t!==Z())throw new Error("Workspace session changed")},r=(async()=>{let s=await ct();if(n(),!s.principal_id)throw new Error("Workspace initialization requires an authenticated principal");let i=await Q().fetchQuery({queryKey:I.memberships(s.principal_id),queryFn:Es,staleTime:12e4,retry:!1});n();let o=i.find(d=>d.path===e.accountPath&&d.isAccount&&!d.isSpace);if(!o)throw new Error("Authenticated account membership is unavailable");let a=i.find(d=>d.isSpace&&d.accountId===o.personalSpaceId&&d.path===o.personalSpacePath);if(!a||!o.personalSpacePath)throw new Error("A provisioned default Space membership is required");let c=Ye(o),u=Ye(a),l=we();if(l&&l.id!==c.id)throw new Error("Reset the session before changing accounts");return l||Vt(c,{activate:!1}),await en(o.personalSpacePath,d=>{let h=i.find(f=>f.accountId===d&&(f.isAccount||f.isSpace));return h?Ye(h):null},{initialAnchor:u}),n(),{home:c,defaultSpace:u,memberships:i}})().catch(s=>{throw t===Z()&&(Yn=void 0),s});return Yn={accountPath:e.accountPath,promise:r},r}var rn,Qr,Nr;oe(()=>{Qr?.(),Qr=void 0,rn=void 0,Nr=void 0});function al(e={}){if(rn)return e.workspace&&e.workspace.accountPath!==Nr?Promise.reject(new Error("Initialize workspace through initializeWorkspace, or dispose the existing runtime first")):rn;Nr=e.workspace?.accountPath;let t=Z();return rn=(async()=>{let n=e.tracking??!0,r=n===!1?()=>{}:Ds(typeof n=="object"?n:{});Qr=r;try{let s=e.session===!1?null:await ct(),i=e.workspace?await Us(e.workspace):void 0;if(t!==Z())throw new Error("Session changed during initialization");let o=!1;return{session:s,workspace:i,dispose(){o||(o=!0,r(),t===Z()&&(rn=void 0,Nr=void 0,Qr=void 0))}}}catch(s){throw r(),t===Z()&&(rn=void 0,Nr=void 0,Qr=void 0),s}})(),rn}function Op(e){return e instanceof Ke?{kind:"denied",payload:e.payload}:e instanceof Se?{kind:"gateway",method:e.method,status:e.status,statusText:e.statusText,payload:e.payload,responseBody:e.responseBody}:e instanceof Error?{kind:"other",name:e.name,message:e.message}:{kind:"other",name:"Error",message:String(e)}}function cl(e){let t=(s,i)=>{s.postMessage(i,e.origin)},n=!0,r=s=>{if(s.origin!==e.origin)return;let i=e.frame();if(!i||s.source!==i||!Ii(s.data))return;let o=s.data;if(o.kind==="hello"){t(i,{fsaos:Gt,kind:"welcome",anchor:ye()??Rt(),item:e.item?.()??null});return}if(o.kind!=="call"||typeof o.id!="string"||typeof o.method!="string")return;let{id:a,method:c,params:u}=o;R(c,u&&typeof u=="object"?u:{}).then(l=>{n&&t(i,{fsaos:Gt,kind:"result",id:a,ok:!0,response:l})},l=>{n&&t(i,{fsaos:Gt,kind:"result",id:a,ok:!1,error:Op(l)})})};return window.addEventListener("message",r),()=>{n=!1,window.removeEventListener("message",r)}}async function eo(e){try{return await R("execution-control-transition",e)}catch(t){if(!(t instanceof Se)||t.status<500)throw t;return await new Promise(n=>setTimeout(n,250)),R("execution-control-transition",e)}}function to(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 ul(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 eo({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 to(i?{...s,state:i}:s)}async function ll(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 eo({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 to(a?{...o,state:a}:o)}async function dl(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 eo({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 to(i?{...s,outcome:i}:s)}var Fp=/^[a-z][a-z0-9_-]{0,63}$/,qp=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Xn=class extends Error{constructor(n,r,s,i){super(n);X(this,"code");X(this,"status");X(this,"fillId");this.name="FormSubmissionError",this.code=r,this.status=s,this.fillId=i}};async function pl(e,t,n={}){if(!Fp.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(!qp.test(r))throw new TypeError("fillId must be a UUID");let s=Wt(),i=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!i)throw new TypeError("pageUrl is required outside a browser");let o=`${Fe.replace(/\/+$/,"")}/d/${encodeURIComponent(s)}/actions/${encodeURIComponent(e)}`,a=il(),c=a?{visitor_id:a.visitor_id,session_id:a.session_id}:void 0,u;try{u=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({fill_id:r,page_url:i,fields:t,...c?{attribution:c}:{}}),signal:n.signal,credentials:"omit"})}catch(d){throw new Xn(d instanceof Error?d.message:"Form submission network error","FORM_NETWORK_ERROR",0,r)}let l=null;try{l=await u.json()}catch{}if(!u.ok||l?.success!==!0){let d=l;throw new Xn(d?.message||d?.error||`Form submission failed (${u.status})`,d?.error||"FORM_SUBMISSION_FAILED",u.status,r)}return await ol({fill_id:r,action_id:e,release_id:l.release_id},r,i,a,n.signal),l}var no=ne(fe(),1),gl=ne(ml(),1);function hl(e){return R("read",{path:e})}function yl(e,t){return R("list",{path:e,...t})}function _l(e){return R("create",e)}function vl(e){return R("update",e)}function bl(e){return R("create",e)}function wl(e,t){let r=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return R("tools/call",{name:e,instance_path:r,...t||{}})}function Sl(e,t,n){return R("signal",{target_id:e,event_name:t,payload:n||{}})}function xl(e){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+e}var Rl={signIn:e=>e.provider?$.auth.signInWithOAuth({provider:e.provider,options:{redirectTo:e.redirectTo||window.location.href}}):$.auth.signInWithPassword({email:e.email,password:e.password}),signUp:e=>$.auth.signUp({email:e.email,password:e.password,options:{data:e.metadata||{}}}),signOut:async()=>{await $.auth.signOut(),On(),Q().clear()},getSession:()=>$.auth.getSession().then(e=>e.data.session),getUser:()=>$.auth.getUser().then(e=>e.data.user),onAuthStateChange:e=>{let{data:{subscription:t}}=$.auth.onAuthStateChange((n,r)=>{e({event:n,session:r,user:r?.user??null})});return()=>t?.unsubscribe()},resetPassword:e=>$.auth.resetPasswordForEmail(e),signInWithMagicLink:(e,t)=>$.auth.signInWithOtp({email:e,options:{emailRedirectTo:t||window.location.href}})};function Cl(){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,gl.createRoot)(e).render((0,no.createElement)(fr,{client:Q()},(0,no.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 Pl(){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}var Np=e=>R("create-invitation",{...e}),Qp=e=>R("get-invitation",{invitation_id:e}),Dp=e=>R("accept-invite",{invitation_id:e}),Up=e=>R("reject-invite",{invitation_id:e}),Kp=e=>R("cancel-invite",{invitation_id:e}),Lp=(e,t)=>R("resend-invite",{invitation_id:e,request_id:t}),Hp=(e,t)=>R("list-invitations",{account_id:e,...t?{after:t}:{}});function ro(e){return R("invite-member",e)}function so(e){return R("accept-invite",e)}function io(e){let t={};return e.role&&(t.role=e.role),R("link",{source_id:e.chat_id,target_id:e.member_id,edge_type:"has_member",context:t})}function oo(e){return R("create-agent",e)}function ao(e){return!e.input_request_id&&!e.input_request?Promise.reject(new Error("answerInput needs input_request_id or the input_request object read from the step.")):R("todo-control",{action:"answer_input",...e})}function El(){return ie({mutationFn:ro})}function Il(){let e=L();return ie({mutationFn:so,onSuccess:()=>{e.invalidateQueries({queryKey:["memberships"]})}})}function Tl(){let e=L();return ie({mutationFn:io,onSuccess:(t,n)=>{e.invalidateQueries({queryKey:I.edges(n.chat_id)}),e.invalidateQueries({queryKey:I.edges(n.member_id)})}})}function Al(){let e=L();return ie({mutationFn:oo,onSuccess:()=>{e.invalidateQueries({queryKey:["memberships"]})}})}function Ml(){let e=L();return ie({mutationFn:ao,onSuccess:(t,n)=>{e.invalidateQueries({queryKey:I.itemById(n.step_id)})}})}function jp(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Bp(e,t){return t&&t.length>0?"select":e==="boolean"?"toggle":e==="integer"||e==="number"?"range":e==="string"?"text":"none"}function Vp(e,t){return!(e==="object"||e==="array")}function Wp(e){return["string","number","integer","boolean"].includes(e)}function $p(e){return e!=="object"&&e!=="array"}function kl(e,t,n,r){let s=e?.properties;if(!s||typeof s!="object")return[];let i=[];for(let[o,a]of Object.entries(s)){let c=a.type||"string",u=a.enum,l=Vp(c,u),d=Wp(c),h=Bp(c,u);i.push({key:o,label:a.title||jp(o),type:c,description:a.description,enum_values:u,default_value:n[o]??r[o]??a.default,editable:t,filterable:l,sortable:d,filter_widget:h})}return i}function co(e){let t=e.default_data||{},n=e.field_defaults||{},r=kl(e.input_schema,!0,t,n),s=kl(e.system_schema,!1,t,n),i=[...r,...s],o=i.filter(u=>$p(u.type)),a=i.filter(u=>u.filterable),c=i.filter(u=>u.sortable);return{fields:i,columns:o,filterable:a,sortable:c,form_fields:r,system_fields:s}}function Ol(e){return{field:"updated_at",direction:"desc"}}function Fl(e){let t=co(e),n=new Set(e.input_schema?.required||[]);return t.form_fields.filter(r=>n.has(r.key)||r.default_value===void 0)}var xe=ne(fe(),1);var ql=Promise.resolve();function Ae(e){if(e?.aborted)throw new Error("Upload cancelled")}async function uo(e,t){if(Ae(t),e.size>16777216||!globalThis.crypto?.subtle)return{};let n=ql.then(async()=>{Ae(t);let r=await e.arrayBuffer();Ae(t);let s=await globalThis.crypto.subtle.digest("SHA-256",r);return Ae(t),{expected_sha256:Array.from(new Uint8Array(s),i=>i.toString(16).padStart(2,"0")).join(""),expected_size_bytes:e.size}});return ql=n.catch(()=>{}),n}function Nl(){if(globalThis.crypto?.randomUUID)return globalThis.crypto.randomUUID();let e=new Uint8Array(16);if(globalThis.crypto?.getRandomValues){globalThis.crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,n=>n.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let n=Math.floor(Math.random()*16);return(t==="x"?n:n&3|8).toString(16)})}async function Ql(e,t,n,r){let s=t.name||(e instanceof File?e.name:`file-${Date.now()}`),i=e.type||"application/octet-stream",o=t.itemType||"file",a=t.collisionPolicy||"keep_both",c=a==="keep_both"?Nl():void 0,u=G(),l=Z(),d=await uo(e,r);if(Ae(r),u!==G()||l!==Z())throw new Error("The account or Space changed while preparing the upload. Start it again.");let h={parent_path:t.parentPath,item_type:o,name:s,type_data:{...t.typeData||{},file_source:{type:"upload",content_type:i,collision_policy:a,...c?{upload_id:c}:{},...d}}};t.cardParentPath&&(h.card_parent_path=t.cardParentPath);let f=await R("create",h);Ae(r);let m=f;if(!m.id)throw new Error(m.error||m.message||"Failed to create file item");let v=m.id,g=m.path;if(m.storage_completed&&m.file_ref)return{itemId:v,itemPath:g,fileRef:m.file_ref};let w=m.storage_key,y=m.upload_token,_=m.storage_worker_url||"https://fsaos-storage.radns.workers.dev";if(!w)throw new Error("Gateway returned no storage_key \u2014 file_source may not be supported for this item type");await Gp(_,w,y,e,i,n,r),Ae(r);let S=await Dl(v,w,i,y,d.expected_sha256,e.size);return{itemId:v,itemPath:g,fileRef:S}}function Gp(e,t,n,r,s,i,o){return new Promise((a,c)=>{let u=new XMLHttpRequest;if(u.open("PUT",`${e}/upload`),u.setRequestHeader("X-Storage-Key",t),u.setRequestHeader("Content-Type",s),n&&u.setRequestHeader("X-Upload-Token",n),u.upload.onprogress=l=>{l.lengthComputable&&i&&i(Math.round(l.loaded/l.total*100))},u.onload=()=>{u.status>=200&&u.status<300?a():c(new Error(`Storage upload failed: HTTP ${u.status} \u2014 ${u.responseText?.slice(0,300)}`))},u.onerror=()=>c(new Error("Storage upload network error")),u.ontimeout=()=>c(new Error("Storage upload timed out")),u.onabort=()=>c(new Error("Upload cancelled")),o){if(o.aborted){c(new Error("Upload cancelled"));return}o.addEventListener("abort",()=>{u.abort(),c(new Error("Upload cancelled"))})}u.send(r)})}async function Dl(e,t,n,r,s,i){let o=await at(),a=await fetch(`${Fe}/storage/upload-complete`,{method:"POST",headers:{"Content-Type":"application/json",...o?{Authorization:`Bearer ${o}`}:{}},body:JSON.stringify({item_id:e,storage_key:t,content_type:n,...r?{upload_token:r}:{},...s?{hash:s}:{}})});if(!a.ok){let u=await a.text().catch(()=>"");throw new Error(`Upload confirmation failed: HTTP ${a.status} \u2014 ${u.slice(0,300)}`)}let c=await a.json();if(!c.success)throw new Error(c.error||c.message||"Upload confirmation rejected");if(s&&(c.file_ref?.content_sha256!==s||c.file_ref?.size_bytes!==i||c.file_ref?.content_type!==n))throw new Error("Stored file did not confirm the expected checksum, size and type");return c.file_ref}function Ul(){let[e,t]=(0,xe.useState)([]),n=L(),r=(0,xe.useRef)(e);r.current=e;let s=(0,xe.useRef)(new Map),i=(0,xe.useCallback)((g,w)=>{t(y=>y.map(_=>_.id===g?{..._,...w}:_))},[]),o=(0,xe.useCallback)(g=>{t(w=>[...w,g])},[]),a=(0,xe.useCallback)(async(g,w,y,_,S)=>{let x=y.name||w.name,k=w.type||"application/octet-stream",N=y.itemType||"file",C=y.collisionPolicy||"keep_both",O=S?.itemId||null,T=S?.itemPath||null,E=S?.storageKey||null,A=S?.uploadToken||null,F=S?.storageWorkerUrl||null,U=S?.contentSha256||void 0,j=new AbortController,Me=G(),H=Z();s.current.get(g)?.abort(),s.current.set(g,j);try{if(!_||_==="create"){i(g,{status:"creating",error:null,_failedAt:null});let ve=await uo(w,j.signal);if(Ae(j.signal),Me!==G()||H!==Z())throw new Error("The account or Space changed while preparing the upload. Start it again.");U=ve.expected_sha256;let Ue=await R("create",{parent_path:y.parentPath,item_type:N,name:x,type_data:{...y.typeData||{},file_source:{type:"upload",content_type:k,collision_policy:C,...C==="keep_both"?{upload_id:g}:{},...ve}}});Ae(j.signal);let ce=Ue;if(!ce.id)throw Object.assign(new Error(ce.error||ce.message||"Failed to create file item"),{_step:"create"});if(O=ce.id,T=ce.path,i(g,{itemId:O,itemPath:T}),ce.storage_completed&&ce.file_ref){i(g,{status:"complete",progress:100,fileRef:ce.file_ref}),n.invalidateQueries({queryKey:I.children(y.parentPath)});return}if(E=ce.storage_key,A=ce.upload_token||"",F=ce.storage_worker_url||"https://fsaos-storage.radns.workers.dev",i(g,{_storageKey:E,_uploadToken:A,_storageWorkerUrl:F,_contentSha256:U||null}),!E)throw Object.assign(new Error("Gateway returned no storage_key"),{_step:"create"})}(!_||_==="create"||_==="upload")&&(i(g,{status:"uploading",progress:0,error:null,_failedAt:null}),await new Promise((Ue,ce)=>{let pe=new XMLHttpRequest;i(g,{_xhr:pe}),pe.open("PUT",`${F}/upload`),pe.setRequestHeader("X-Storage-Key",E),pe.setRequestHeader("Content-Type",k),A&&pe.setRequestHeader("X-Upload-Token",A),pe.upload.onprogress=ge=>{ge.lengthComputable&&i(g,{progress:Math.round(ge.loaded/ge.total*100)})},pe.onload=()=>{pe.status>=200&&pe.status<300?Ue():ce(Object.assign(new Error(`Storage upload failed: HTTP ${pe.status}`),{_step:"upload"}))},pe.onerror=()=>ce(Object.assign(new Error("Storage upload network error"),{_step:"upload"})),pe.ontimeout=()=>ce(Object.assign(new Error("Storage upload timed out"),{_step:"upload"})),pe.onabort=()=>ce(Object.assign(new Error("Upload cancelled"),{_step:"upload"})),j.signal.addEventListener("abort",()=>pe.abort(),{once:!0}),Ae(j.signal),pe.send(w)}),Ae(j.signal),i(g,{progress:100,_xhr:null})),i(g,{status:"confirming",error:null,_failedAt:null});let me=await Dl(O,E,k,A||"",U,w.size).catch(ve=>{throw Object.assign(ve,{_step:"confirm"})});Ae(j.signal),i(g,{status:"complete",fileRef:me}),n.invalidateQueries({queryKey:I.children(y.parentPath)})}catch(me){if(s.current.get(g)!==j)return;let ve=me?.message||String(me),Ue=me?._step||"create";i(g,{status:"error",error:ve,_failedAt:Ue,_xhr:null})}finally{s.current.get(g)===j&&s.current.delete(g)}},[i,n]),c=(0,xe.useCallback)((g,w)=>{let y=Nl();o({id:y,file:g,status:"creating",progress:0,error:null,itemId:null,itemPath:null,fileRef:null,options:w,_storageKey:null,_uploadToken:null,_storageWorkerUrl:null,_contentSha256:null,_xhr:null,_failedAt:null}),a(y,g,w)},[o,a]),u=(0,xe.useCallback)((g,w)=>{for(let y of g)c(y,w)},[c]),l=(0,xe.useCallback)(g=>{let w=r.current.find(S=>S.id===g);if(!w||w.status!=="error")return;let y=w._failedAt||"create",_=w._storageKey&&w.itemId?{storageKey:w._storageKey,uploadToken:w._uploadToken||"",storageWorkerUrl:w._storageWorkerUrl||"https://fsaos-storage.radns.workers.dev",itemId:w.itemId,itemPath:w.itemPath||"",contentSha256:w._contentSha256}:void 0;a(g,w.file,w.options,y,_)},[a]),d=(0,xe.useCallback)(g=>{s.current.get(g)?.abort();let w=r.current.find(y=>y.id===g);w&&(w._xhr&&w._xhr.abort(),i(g,{status:"error",error:"Cancelled",_xhr:null,_failedAt:null}))},[i]),h=(0,xe.useCallback)(g=>{s.current.get(g)?.abort(),s.current.delete(g),t(w=>w.filter(y=>y.id!==g))},[]),f=(0,xe.useCallback)(()=>{t(g=>g.filter(w=>w.status!=="complete"))},[]),m=e.some(g=>g.status==="creating"||g.status==="uploading"||g.status==="confirming"),v=e.map(({_storageKey:g,_uploadToken:w,_storageWorkerUrl:y,_contentSha256:_,_xhr:S,_failedAt:x,...k})=>k);return{upload:c,uploadMultiple:u,uploads:v,retryUpload:l,cancelUpload:d,removeUpload:h,clearCompleted:f,isUploading:m}}var Kl=ne(fe(),1);async function lo(e,t){return await R("resolve-items",{context_id:e,item_type:t})}function Ll(e,t){return(0,Kl.useSyncExternalStore)(Ie,G,G),W({queryKey:["vfs",z()??"__unscoped__","resolved-items",e??"",t],queryFn:()=>lo(e,t),enabled:!!(e&&t)})}var je=ne(fe(),1);function Ks(e,t){let n={artifacts:new Map,timeline:[]},r=new Map;function s(o){if(!o.action?.startsWith("artifact_"))return;let c,u=o.name;if(typeof u=="string"&&u.startsWith("{"))try{c=JSON.parse(u)}catch{return}else if(o.artifact_id)c=o;else return;switch(c.type){case"artifact_opened":{let l=Date.now();if(n.artifacts.set(c.artifact_id,{artifact_id:c.artifact_id,surface_type:c.surface_type,tool_id:c.tool_id,tool_name:c.tool_name,target_uri:c.target_uri,status:"streaming",content:"",total_chars:0,delta_count:0,artifact_item_uri:null,evidence_uri:null,meta:c.meta,started_at:l,completed_at:null}),r.has(c.tool_id)){let d=r.get(c.tool_id);n.timeline[d].artifact_ids.push(c.artifact_id)}else{let d=n.timeline.length;n.timeline.push({tool_id:c.tool_id,tool_name:c.tool_name,status:"started",target_uri:c.target_uri,started_at:l,completed_at:null,artifact_ids:[c.artifact_id]}),r.set(c.tool_id,d)}break}case"artifact_delta":{let l=n.artifacts.get(c.artifact_id);l&&(l.content+=c.content_delta,l.total_chars+=c.content_delta.length,l.delta_count+=1,c.target_uri&&!l.target_uri&&(l.target_uri=c.target_uri));break}case"artifact_done":{let l=n.artifacts.get(c.artifact_id);l&&(l.status=c.status,l.total_chars=c.total_chars,l.artifact_item_uri=c.artifact_item_uri,l.evidence_uri=c.evidence_uri,c.target_uri&&(l.target_uri=c.target_uri),(c.status==="completed"||c.status==="failed")&&(l.completed_at=Date.now()));let d=r.get(c.tool_id);if(d!==void 0){let h=n.timeline[d];c.status==="executing"?h.status="executing":c.status==="completed"?(h.status="completed",h.completed_at=Date.now()):c.status==="failed"&&(h.status="failed",h.completed_at=Date.now()),c.target_uri&&!h.target_uri&&(h.target_uri=c.target_uri)}break}}t(n)}return gs(e,s)}function Hl(e,t=!0){let[n,r]=(0,je.useState)(new Map),[s,i]=(0,je.useState)([]),o=(0,je.useRef)({artifacts:new Map,timeline:[]});(0,je.useEffect)(()=>!e||!t?void 0:Ks(e,d=>{o.current=d,r(new Map(d.artifacts)),i([...d.timeline])}),[e,t]);let a=(0,je.useCallback)(()=>{r(new Map),i([]),o.current={artifacts:new Map,timeline:[]}},[]),c=Array.from(n.values()).find(l=>l.surface_type==="file_editor"&&l.status==="streaming")??null,u=Array.from(n.values()).filter(l=>l.surface_type==="activity"&&(l.status==="streaming"||l.status==="executing"));return{artifacts:n,timeline:s,activeEditor:c,activeActivities:u,reset:a}}function jl(e,t=!0){let[n,r]=(0,je.useState)([]);(0,je.useEffect)(()=>!e||!t?void 0:Ks(e,o=>{r([...o.timeline])}),[e,t]);let s=n.length>0?n[n.length-1]:null;return{timeline:n,latestActivity:s}}var Ls=ne(fe(),1);function zp(e,t,n,r){return["vfs","timeline-history",e,t??"__all__",n??500,r??0]}async function po(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(Jp).sort((u,l)=>u.seq-l.seq):[]}catch(o){if(o?.status===404||o?.message?.includes("not found"))return[];throw o}}function Bl(e,t){let{turnId:n,limit:r=500,offset:s=0,enabled:i=!0,debounceMs:o=300}=t??{},a=e?`${e}/datasets/agent-events`:null,c=L(),u=(0,Ls.useRef)(null),l=a?zp(a,n,r,s):["vfs","timeline-history","__disabled__"],d=W({queryKey:l,queryFn:()=>po(e,{turnId:n,limit:r,offset:s}),enabled:!!e&&i});return(0,Ls.useEffect)(()=>{if(!a||!i)return;let h=J("vfs_change",()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{c.invalidateQueries({queryKey:l})},o)},f=>{let m=f?.path;return m?m===a&&f.item_type==="dataset":!1});return()=>{h(),u.current&&clearTimeout(u.current)}},[a,i,o,c,JSON.stringify(l)]),{events:d.data??[],isLoading:d.isLoading,error:d.error,isFetching:d.isFetching,refetch:()=>{d.refetch()}}}function Jp(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 kt=ne(fe(),1);function Vl(e){let t=(0,kt.useSyncExternalStore)(Ie,G,G),n=z(),r=e?.path??n,s=ye(),i=e?.id??s?.id,o=(0,kt.useMemo)(()=>({}),[t,n,r,i]),a=(0,kt.useRef)(o);a.current=o;let c=zn(r?{key:"pinned",scope_id:i,_scope_path:r}:null),u=L(),l=c.resolvedChildren,d=!!(!c.error&&c.arrangement?.item_id&&c.resolutionLevel==="member"&&c.arrangement.write_target_id===c.arrangement.item_id),h=ie({mutationFn:async m=>{let v,g={_scope_path:m.scopePath};if(m.operation==="pin"?v=await R("create",{...g,parent_id:m.arrangementId,name:`pin-${m.target.id}`,item_type:"symlink",type_data:{target_item_id:m.target.id,target_type:m.target.item_type}}):m.operation==="unpin"?v=await R("delete",{...g,id:m.entry.id}):v=await R("update",{...g,id:m.arrangementId,type_data:{order:m.ids}}),v?.success===!1)throw new Error(v.error||"Pins could not be saved");return v},onSettled:(m,v,g)=>ut(u,g.queryKey)}),f=(0,kt.useCallback)(m=>!d||!r||a.current!==o||t!==G()||z()!==n?Promise.reject(new Error("Personal pins are not available in this context")):m.operation==="unpin"&&!l.some(v=>v.id===m.entry.id)?Promise.reject(new Error("Pin is outside this arrangement")):m.operation==="reorder"&&(new Set(m.ids).size!==l.length||m.ids.length!==l.length||l.some(v=>!m.ids.includes(v.id)))?Promise.reject(new Error("Order must include each pin exactly once")):m.operation==="pin"&&l.some(v=>v.symlink_type_data?.target_item_id===m.target.id)?Promise.resolve(null):h.mutateAsync({...m,scopePath:r,arrangementId:c.arrangement.item_id,arrangementPath:c.arrangement.item_path,queryKey:c.arrangementQueryKey}),[d,t,n,r,o,l,c.arrangement,c.arrangementQueryKey,h.mutateAsync]);return{entries:l,isLoading:c.isLoading,error:c.error,refetch:c.refetch,ready:d,isSaving:h.isPending,saveError:h.error,isPinned:m=>l.some(v=>v.symlink_type_data?.target_item_id===m),pin:m=>f({operation:"pin",target:m}),unpin:m=>{let v=l.find(g=>g.symlink_type_data?.target_item_id===m||g.id===m);return v?f({operation:"unpin",entry:v}):Promise.resolve(null)},reorder:m=>f({operation:"reorder",ids:m})}}var Hs=ne(fe(),1);var Dr=(e,t,n)=>["vfs",e,"personal-sections",t,n];function fo(e,t){return e&&e.item_id===t.item_id&&e.version>t.version?e:t}async function mo(e,t,n,r){let s=await R("personal-sections",{...r,context_item_id:t,collection:n,_scope_path:e});if(!s||s.success===!1)throw new Error(s?.message||s?.error||"Sections could not be saved");if(!Array.isArray(s.sections)||s.context_item_id!==t||s.collection!==n)throw new Error("Invalid sections response");return s}async function Wl(e,t){let n=await mo(e.scopePath,e.contextId,e.collection,{operation:"assign",section_id:e.sectionId,target_id:t}),r=Q();return r.setQueryData(Dr(e.scopePath,e.contextId,e.collection),s=>fo(s,n)),$l(r,e.scopePath),n}function $l(e,t){for(let n of e.getQueryCache().getAll())n.queryKey[0]==="vfs"&&n.queryKey[1]===t&&n.queryKey[2]==="personal-sections"&&ut(e,n.queryKey)}function Gl(e,t){let n=(0,Hs.useSyncExternalStore)(Ie,G,G),r=z(),s=L(),i=Dr(r,e,t),o=W({queryKey:i,enabled:!!r&&!!e,queryFn:()=>mo(r,e,t,{operation:"list"}),staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0,personalSections:!0},structuralSharing:(d,h)=>fo(d,h)}),a=(0,Hs.useRef)(!1),c=ie({mutationFn:async d=>{let h=await mo(d.scope,d.context,d.collection,{...d.change,...d.change.operation.startsWith("reorder")?{expected_version:d.version}:{}});return s.setQueryData(Dr(d.scope,d.context,d.collection),f=>fo(f,h)),h},onSettled:(d,h,f)=>$l(s,f.scope)});async function u(d){if(!r||!e||n!==G()||z()!==r||!o.data||o.error)throw new Error("Select the Space again before changing sections");if(a.current)throw new Error("A section change is still being saved");a.current=!0;try{return await c.mutateAsync({change:d,scope:r,context:e,collection:t,version:o.data.version})}finally{a.current=!1}}function l(d){if(!r||!e||!o.data?.sections.some(h=>h.id===d))throw new Error("Section is unavailable");return{scopePath:r,contextId:e,collection:t,sectionId:d}}return{sections:o.data?.sections??[],ready:!!o.data&&!o.error,isLoading:o.isLoading,error:o.error,refetch:o.refetch,isSaving:c.isPending,change:u,destination:l,contextKey:`${n}:${r}:${e}:${t}`}}_u(go);return rd(go);})();
7
+ ${t??""}`,[m,v]=(0,b.useState)(null),g=(0,b.useRef)({key:f,found:null,earlyContentPaths:new Set}),w=m?.key===f?m:null;(0,b.useLayoutEffect)(()=>{g.current={key:f,found:w,earlyContentPaths:new Set}},[f]);let y=W({queryKey:["vfs",d??"__unscoped__","minted-asset",h??"",t??""],queryFn:async()=>{let x=await R("query",{scope_path:d,filters:{[`field.${h}`]:t},limit:1}),M=x.content?.items??x.items??[],N=M[0]?De(M[0]):null;if(!N)return null;let O=(await Pr(N.path)).some(T=>T.item_type==="file"&&!!T.type_data?.file_ref);return{asset:N,hasBytes:O}},enabled:!!(t&&d&&h&&!s),refetchInterval:x=>g.current.key===f&&g.current.found?.hasBytes||x.state.data?.hasBytes?!1:1500});(0,b.useEffect)(()=>{let x=y.data;if(!x||g.current.key!==f)return;let M=g.current.found,N={key:f,itemId:x.asset.id,itemPath:x.asset.path,displayName:typeof x.asset.type_data?.display_name=="string"?x.asset.type_data.display_name:x.asset.name,hasBytes:x.hasBytes||!!(M?.itemId===x.asset.id&&M.hasBytes)};g.current.found=N,v(N)},[y.data,f]);let _=!!(t&&u)&&!s&&!w?.hasBytes;return(0,b.useEffect)(()=>{if(!(!_||!u))return Ln(u,["asset.materialized","content.written"])},[_,u]),(0,b.useEffect)(()=>{if(!_||!t||!u)return;let x=f,M=E=>E?.payload??E,N=E=>{let F=M(E)?.scope_id??E?.scope_id;return typeof F=="string"?F:void 0},P=E=>{let F=M(E)?.item_path??E?.item_path;return typeof F=="string"&&F?F:void 0},O=(E,A)=>{let F=A.replace(/\/+$/,"");return E===F||E.startsWith(`${F}/`)},T=[J("asset.materialized",E=>{if(g.current.key!==x)return;let A=M(E);if(typeof A?.item_id!="string"||!A.item_id)return;let F=g.current.found,U=typeof A.item_path=="string"?A.item_path:void 0,H=!!A.has_bytes||!!(U&&Array.from(g.current.earlyContentPaths).some(j=>O(j,U)))||!!(F&&F.itemId===A.item_id&&F.hasBytes),ke={key:x,itemId:A.item_id,itemPath:U,displayName:typeof A.display_name=="string"?A.display_name:void 0,hasBytes:H};g.current.found=ke,v(ke)},E=>{let A=N(E);return(!A||A===u)&&M(E)?.origin===t}),J("content.written",E=>{if(g.current.key!==x)return;let A=P(E);if(!A)return;let F=g.current.found;if(!F?.itemPath||!O(A,F.itemPath)){if(g.current.earlyContentPaths.add(A),g.current.earlyContentPaths.size>128){let H=g.current.earlyContentPaths.values().next().value;H&&g.current.earlyContentPaths.delete(H)}return}if(F.hasBytes)return;let U={...F,hasBytes:!0};g.current.found=U,v(U)},E=>{let A=N(E);return(!A||A===u)&&!!P(E)})];return()=>T.forEach(E=>E())},[_,t,u,f]),{state:s?"failed":t?w?w.hasBytes?"ready":"materializing":"pending":"idle",itemId:w?.itemId,itemPath:w?.itemPath,displayName:w?.displayName,fallbackUrl:r??void 0,error:s??void 0}}function Ju(e,t){let n=Q().getDefaultOptions().queries?.retry??1;return typeof n=="function"?n(e,t):n===!0||typeof n=="number"&&e<n}function Yu(e,t,n){let r=(0,kt.useSyncExternalStore)(Ie,G,G),s=ye(),i=z(),o=n?.path??i,a=n?.id??s?.id,c=!!(n?.id&&n.path)||s?.kind==="space",u=(0,kt.useMemo)(()=>({}),[r,i,o,a]),l=(0,kt.useRef)(u);l.current=u;let d=zn(c&&o?{key:e,scope_id:a,_scope_path:o}:null),h=(0,kt.useMemo)(()=>{let y=d.applyTo([...t]);if(e!=="channel-order")return y;let _=new Set(d.order??[]),S=y.filter(M=>!_.has(M.id)),x=M=>Date.parse(M.createdAt??"")||0;return S.sort((M,N)=>x(N)-x(M)),[...S,...y.filter(M=>_.has(M.id))]},[e,t,d.applyTo,d.order]),f=L(),m=(0,kt.useRef)(!1),v=!!(c&&!d.error&&d.arrangement?.item_id&&d.resolutionLevel==="member"&&d.arrangement.write_target_id===d.arrangement.item_id),g=ie({mutationFn:async y=>{let _=await R("update",{_scope_path:y.scopePath,id:y.arrangementId,type_data:{order:y.ids}});if(_?.success===!1)throw new Error(_.error||"Order could not be saved");return _},onSettled:(y,_,S)=>ut(f,S.queryKey)});async function w(y){if(!v||!o||u!==l.current||r!==G()||z()!==i)throw new Error("Personal order is not available in this Space");if(m.current)throw new Error("An order change is already being saved");let _=t.map(T=>T.id);if(y.length!==_.length||new Set(y).size!==_.length||_.some(T=>!y.includes(T)))throw new Error("Order must include each displayed item exactly once");let S=f.getQueryData(d.arrangementQueryKey);if(S?.item_id!==d.arrangement.item_id||JSON.stringify(S?.type_data?.order??[])!==JSON.stringify(d.order??[]))throw new Error("The saved order changed. Try dragging again");let x=h.map(T=>T.id);if(y.every((T,E)=>x[E]===T))return;let M=new Set(_),N=0,O=[...(d.order??[]).map(T=>M.has(T)?y[N++]:T),...y.slice(N)];m.current=!0;try{return await g.mutateAsync({ids:O,scopePath:o,arrangementId:d.arrangement.item_id,queryKey:d.arrangementQueryKey})}finally{m.current=!1}}return{items:h,ready:v,supported:c,contextKey:`${r}:${o}:${e}`,isLoading:c&&d.isLoading,error:d.error,refetch:d.refetch,isSaving:g.isPending,saveError:g.error,reorder:w}}var Xi=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Ap=/^[A-Za-z_:][A-Za-z0-9_:.-]{0,127}$/,Xu=new Map,Zu=new Map,Jn=class extends Error{constructor(n,r,s,i){super(n);X(this,"code");X(this,"status");X(this,"eventId");this.name="InteractionTrackingError",this.code=r,this.status=s,this.eventId=i}};function tn(e){let t=e?Ht.find(n=>n.id===e):Ht.find(n=>n.default===!0)??(Ht.length===1?Ht[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 Qs(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 kp(e){return e.length>0&&e.length<=128&&!/[\u0000-\u001f\u007f]/.test(e)}function Mp(e,t){if(!kp(t)||!e.observations?.includes(t))throw new TypeError("The observation is not declared by this release source")}function Zi(e){if(!(typeof window>"u"||e.storage==="memory"))try{return e.storage==="session"?window.sessionStorage:window.localStorage}catch{return}}function Op(e){try{let t=Zi(e)?.getItem(e.key)??void 0;return t&&Xi.test(t)?t:void 0}catch{return}}function el(e,t){try{Zi(e)?.setItem(e.key,t)}catch{}}function tl(e){let t=e.identity?.visitor;if(!t?.key)throw new TypeError("The source visitor identity policy is invalid");let n=Op(t)??Xu.get(e.id);if(n)return n;let r=crypto.randomUUID();return Xu.set(e.id,r),el(t,r),r}function nl(e,t=Date.now()){let n=e.identity?.session;if(!n?.key||!Number.isInteger(n.idle_seconds)||n.idle_seconds<1)throw new TypeError("The source session identity policy is invalid");let r;try{let u=Zi(n)?.getItem(n.key);r=u?JSON.parse(u):void 0}catch{r=void 0}let s=Zu.get(e.id),i=r&&typeof r.id=="string"&&Xi.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 Zu.set(e.id,c),el(n,JSON.stringify(c)),c.id}function Fp(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 nn(e,t={},n={}){let r=tn(n.source);if(Mp(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??tl(r),o=n.sessionId??nl(r);if(![s,i,o].every(g=>Xi.test(g)))throw new TypeError("event, visitor, and session IDs must be UUIDs");let a=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!a)throw new TypeError("pageUrl is required outside a browser");let c=n.occurredAt??new Date().toISOString();if(Number.isNaN(Date.parse(c)))throw new TypeError("occurredAt is invalid");let u=n.referrer??(typeof document<"u"&&document.referrer||void 0),l=Fp(r,a),d=l?{...t,source_keys:l}:t,h=Wt(),f=`${Fe.replace(/\/+$/,"")}/d/${encodeURIComponent(h)}/interactions`,m;try{m=await fetch(f,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({source:r.id,page_url:a,visitor_id:i,session_id:o,referrer:u,events:[{id:s,event_type:e,occurred_at:c,properties:d}]}),signal:n.signal,credentials:"omit",keepalive:n.keepalive??!1})}catch(g){throw new Jn(g instanceof Error?g.message:"Observation transport network error","OBSERVATION_NETWORK_ERROR",0,s)}let v=null;try{v=await m.json()}catch{}if(!m.ok||v?.success!==!0){let g=v;throw new Jn(g?.message||g?.error||`Observation transport failed (${m.status})`,g?.error||"OBSERVATION_TRANSPORT_FAILED",m.status,s)}return v}function rl(e={},t={}){let n=tn(t.source),r=Qs("page_view",n),s=typeof document>"u"||!r.title_property?{}:{[r.title_property]:document.title.slice(0,512)};return nn(r.observation,{...s,...e},{...t,source:n.id})}function sl(e,t={},n={}){if(!e||e.length>128)throw new TypeError("actionId is invalid");let r=tn(n.source),s=Qs("declared_action",r),i=s.id_property?{[s.id_property]:e}:{};return nn(s.observation,{...t,...i},{...n,source:r.id})}function il(){try{let e=tn();return Qs("form_receipt",e),{visitor_id:tl(e),session_id:nl(e),source:e.id}}catch{return}}function qp(e,t={}){let n=tn(t.source),r=Qs("form_receipt",n);return nn(r.observation,e,{...t,source:n.id})}async function Np(e,t){let r=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${e}\0${t}`))).slice(0,16);r[6]=r[6]&15|80,r[8]=r[8]&63|128;let s=Array.from(r,i=>i.toString(16).padStart(2,"0")).join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}async function ol(e,t,n,r,s){let i=Ht.filter(o=>o.adapters?.some(a=>a.type==="form_receipt"));await Promise.allSettled(i.map(async o=>{let a=o.id===r?.source;return qp(e,{source:o.id,eventId:a?t:await Np(t,o.id),pageUrl:n,signal:s,keepalive:!0,...a?{visitorId:r.visitor_id,sessionId:r.session_id}:{}})}))}var qr;function Ds(e={}){if(typeof window>"u"||typeof document>"u")return()=>{};if(qr)return qr;if(window.__FSAOS_CONFIG__?.tracking?.enabled===!1)return()=>{};let t;try{t=e.source?[tn(e.source)]:Ht.map(h=>tn(h.id))}catch{return()=>{}}if(t.length===0)return()=>{};let n=e.pageViews===!1?[]:t.flatMap(h=>h.adapters.filter(f=>f.type==="page_view").map(f=>({source:h,adapter:f}))),r=e.declaredActions===!1?[]:t.flatMap(h=>h.adapters.filter(f=>f.type==="declared_action").map(f=>({source:h,adapter:f}))),s="",i=()=>{if(window.location.href!==s){s=window.location.href;for(let{source:h,adapter:f}of n){let m=f.title_property?{[f.title_property]:document.title.slice(0,512)}:{};nn(f.observation,m,{source:h.id,keepalive:!0}).catch(()=>{})}}},o=h=>{if(h.target instanceof Element)for(let{source:f,adapter:m}of r){let v=m.attribute;if(!v||!Ap.test(v))continue;let g=h.target.closest(`[${v}]`);if(!g)continue;let w=g.getAttribute(v)?.trim();if(!w||w.length>128)continue;let y={};m.id_property&&(y[m.id_property]=w),m.element_property&&(y[m.element_property]=g.tagName.toLowerCase()),nn(m.observation,y,{source:f.id,keepalive:!0}).catch(()=>{})}},a=window.history.pushState,c=window.history.replaceState,u=()=>queueMicrotask(i),l=n.some(({adapter:h})=>h.history===!0),d=n.some(({adapter:h})=>h.pageshow===!0);return l&&(window.history.pushState=function(...f){a.apply(this,f),u()},window.history.replaceState=function(...f){c.apply(this,f),u()},window.addEventListener("popstate",i)),d&&window.addEventListener("pageshow",i),r.length>0&&document.addEventListener("click",o,{capture:!0}),n.length>0&&queueMicrotask(i),qr=()=>{window.removeEventListener("popstate",i),window.removeEventListener("pageshow",i),document.removeEventListener("click",o,{capture:!0}),l&&(window.history.pushState=a,window.history.replaceState=c),qr=void 0},qr}var Yn;oe(()=>{Yn=void 0});function Us(e){if(Yn)return Yn.accountPath!==e.accountPath?Promise.reject(new Error("Reset the session before changing accounts")):Yn.promise;let t=Z(),n=()=>{if(t!==Z())throw new Error("Workspace session changed")},r=(async()=>{let s=await ct();if(n(),!s.principal_id)throw new Error("Workspace initialization requires an authenticated principal");let i=await Q().fetchQuery({queryKey:I.memberships(s.principal_id),queryFn:Es,staleTime:12e4,retry:!1});n();let o=i.find(d=>d.path===e.accountPath&&d.isAccount&&!d.isSpace);if(!o)throw new Error("Authenticated account membership is unavailable");let a=i.find(d=>d.isSpace&&d.accountId===o.personalSpaceId&&d.path===o.personalSpacePath);if(!a||!o.personalSpacePath)throw new Error("A provisioned default Space membership is required");let c=Ye(o),u=Ye(a),l=we();if(l&&l.id!==c.id)throw new Error("Reset the session before changing accounts");return l||Vt(c,{activate:!1}),await en(o.personalSpacePath,d=>{let h=i.find(f=>f.accountId===d&&(f.isAccount||f.isSpace));return h?Ye(h):null},{initialAnchor:u}),n(),{home:c,defaultSpace:u,memberships:i}})().catch(s=>{throw t===Z()&&(Yn=void 0),s});return Yn={accountPath:e.accountPath,promise:r},r}var rn,Qr,Nr;oe(()=>{Qr?.(),Qr=void 0,rn=void 0,Nr=void 0});function al(e={}){if(rn)return e.workspace&&e.workspace.accountPath!==Nr?Promise.reject(new Error("Initialize workspace through initializeWorkspace, or dispose the existing runtime first")):rn;Nr=e.workspace?.accountPath;let t=Z();return rn=(async()=>{let n=e.tracking??!0,r=n===!1?()=>{}:Ds(typeof n=="object"?n:{});Qr=r;try{let s=e.session===!1?null:await ct(),i=e.workspace?await Us(e.workspace):void 0;if(t!==Z())throw new Error("Session changed during initialization");let o=!1;return{session:s,workspace:i,dispose(){o||(o=!0,r(),t===Z()&&(rn=void 0,Nr=void 0,Qr=void 0))}}}catch(s){throw r(),t===Z()&&(rn=void 0,Nr=void 0,Qr=void 0),s}})(),rn}function Qp(e){return e instanceof Ke?{kind:"denied",payload:e.payload}:e instanceof Se?{kind:"gateway",method:e.method,status:e.status,statusText:e.statusText,payload:e.payload,responseBody:e.responseBody}:e instanceof Error?{kind:"other",name:e.name,message:e.message}:{kind:"other",name:"Error",message:String(e)}}function cl(e){let t=(s,i)=>{s.postMessage(i,e.origin)},n=!0,r=s=>{if(s.origin!==e.origin)return;let i=e.frame();if(!i||s.source!==i||!Ii(s.data))return;let o=s.data;if(o.kind==="hello"){t(i,{fsaos:Gt,kind:"welcome",anchor:ye()??Rt(),item:e.item?.()??null});return}if(o.kind!=="call"||typeof o.id!="string"||typeof o.method!="string")return;let{id:a,method:c,params:u}=o;R(c,u&&typeof u=="object"?u:{}).then(l=>{n&&t(i,{fsaos:Gt,kind:"result",id:a,ok:!0,response:l})},l=>{n&&t(i,{fsaos:Gt,kind:"result",id:a,ok:!1,error:Qp(l)})})};return window.addEventListener("message",r),()=>{n=!1,window.removeEventListener("message",r)}}async function eo(e){try{return await R("execution-control-transition",e)}catch(t){if(!(t instanceof Se)||t.status<500)throw t;return await new Promise(n=>setTimeout(n,250)),R("execution-control-transition",e)}}function to(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 ul(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 eo({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 to(i?{...s,state:i}:s)}async function ll(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 eo({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 to(a?{...o,state:a}:o)}async function dl(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 eo({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 to(i?{...s,outcome:i}:s)}var Dp=/^[a-z][a-z0-9_-]{0,63}$/,Up=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Xn=class extends Error{constructor(n,r,s,i){super(n);X(this,"code");X(this,"status");X(this,"fillId");this.name="FormSubmissionError",this.code=r,this.status=s,this.fillId=i}};async function pl(e,t,n={}){if(!Dp.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(!Up.test(r))throw new TypeError("fillId must be a UUID");let s=Wt(),i=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!i)throw new TypeError("pageUrl is required outside a browser");let o=`${Fe.replace(/\/+$/,"")}/d/${encodeURIComponent(s)}/actions/${encodeURIComponent(e)}`,a=il(),c=a?{visitor_id:a.visitor_id,session_id:a.session_id}:void 0,u;try{u=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({fill_id:r,page_url:i,fields:t,...c?{attribution:c}:{}}),signal:n.signal,credentials:"omit"})}catch(d){throw new Xn(d instanceof Error?d.message:"Form submission network error","FORM_NETWORK_ERROR",0,r)}let l=null;try{l=await u.json()}catch{}if(!u.ok||l?.success!==!0){let d=l;throw new Xn(d?.message||d?.error||`Form submission failed (${u.status})`,d?.error||"FORM_SUBMISSION_FAILED",u.status,r)}return await ol({fill_id:r,action_id:e,release_id:l.release_id},r,i,a,n.signal),l}async function fl(e){return R("commerce-file-sale",{action:"checkout",product_id:e.productId,expected_product_revision_id:e.productRevisionId,destination_id:e.destinationId,request_key:e.requestKey,_scope_path:e.scopePath,...e.journey?{journey:e.journey}:{}})}async function ml(e,t){return R("commerce-file-sale",{action:"get",license_id:e,_scope_path:t})}function gl(e){let t=new URL(e.hostOrigin);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&t.hostname==="127.0.0.1")||t.username||t.password||t.search||t.hash||t.pathname!=="/")throw new TypeError("hostOrigin must be an HTTPS origin or the local 127.0.0.1 app");let n=new URL(e.pageUrl??window.location.href);if(n.protocol!=="https:"||n.username||n.password||n.hash||n.port)throw new TypeError("The funnel must be a published HTTPS page");let r=new URL("/v2/revven",t);return r.search=new URLSearchParams({surface:"library",offer:e.productId,sale_page:n.href,sale_action:e.capabilityId}).toString(),r.href}function hl(e){if(e.success!==!0||e.state!=="ready"||!e.item_id||!e.file_id||!e.journey?.next_url)return null;let t=new URL(e.journey.next_url),n=new URL(e.journey.return_url);if(t.protocol!=="https:"||n.protocol!=="https:"||t.origin!==n.origin||t.username||t.password||t.hash||t.searchParams.getAll("funnel_id").length!==1||t.searchParams.get("funnel_id")!==e.journey.funnel_id)throw new Error("The purchase destination could not be verified");return t.href}var no=ne(fe(),1),vl=ne(_l(),1);function bl(e){return R("read",{path:e})}function wl(e,t){return R("list",{path:e,...t})}function Sl(e){return R("create",e)}function xl(e){return R("update",e)}function Rl(e){return R("create",e)}function Pl(e,t){let r=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return R("tools/call",{name:e,instance_path:r,...t||{}})}function Cl(e,t,n){return R("signal",{target_id:e,event_name:t,payload:n||{}})}function El(e){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+e}var Il={signIn:e=>e.provider?$.auth.signInWithOAuth({provider:e.provider,options:{redirectTo:e.redirectTo||window.location.href}}):$.auth.signInWithPassword({email:e.email,password:e.password}),signUp:e=>$.auth.signUp({email:e.email,password:e.password,options:{data:e.metadata||{}}}),signOut:async()=>{await $.auth.signOut(),On(),Q().clear()},getSession:()=>$.auth.getSession().then(e=>e.data.session),getUser:()=>$.auth.getUser().then(e=>e.data.user),onAuthStateChange:e=>{let{data:{subscription:t}}=$.auth.onAuthStateChange((n,r)=>{e({event:n,session:r,user:r?.user??null})});return()=>t?.unsubscribe()},resetPassword:e=>$.auth.resetPasswordForEmail(e),signInWithMagicLink:(e,t)=>$.auth.signInWithOtp({email:e,options:{emailRedirectTo:t||window.location.href}})};function Tl(){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,vl.createRoot)(e).render((0,no.createElement)(fr,{client:Q()},(0,no.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 Al(){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}var Kp=e=>R("create-invitation",{...e}),Lp=e=>R("get-invitation",{invitation_id:e}),jp=e=>R("accept-invite",{invitation_id:e}),Hp=e=>R("reject-invite",{invitation_id:e}),Bp=e=>R("cancel-invite",{invitation_id:e}),Vp=(e,t)=>R("resend-invite",{invitation_id:e,request_id:t}),Wp=(e,t)=>R("list-invitations",{account_id:e,...t?{after:t}:{}});function ro(e){return R("invite-member",e)}function so(e){return R("accept-invite",e)}function io(e){let t={};return e.role&&(t.role=e.role),R("link",{source_id:e.chat_id,target_id:e.member_id,edge_type:"has_member",context:t})}function oo(e){return R("create-agent",e)}function ao(e){return!e.input_request_id&&!e.input_request?Promise.reject(new Error("answerInput needs input_request_id or the input_request object read from the step.")):R("todo-control",{action:"answer_input",...e})}function kl(){return ie({mutationFn:ro})}function Ml(){let e=L();return ie({mutationFn:so,onSuccess:()=>{e.invalidateQueries({queryKey:["memberships"]})}})}function Ol(){let e=L();return ie({mutationFn:io,onSuccess:(t,n)=>{e.invalidateQueries({queryKey:I.edges(n.chat_id)}),e.invalidateQueries({queryKey:I.edges(n.member_id)})}})}function Fl(){let e=L();return ie({mutationFn:oo,onSuccess:()=>{e.invalidateQueries({queryKey:["memberships"]})}})}function ql(){let e=L();return ie({mutationFn:ao,onSuccess:(t,n)=>{e.invalidateQueries({queryKey:I.itemById(n.step_id)})}})}function $p(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Gp(e,t){return t&&t.length>0?"select":e==="boolean"?"toggle":e==="integer"||e==="number"?"range":e==="string"?"text":"none"}function zp(e,t){return!(e==="object"||e==="array")}function Jp(e){return["string","number","integer","boolean"].includes(e)}function Yp(e){return e!=="object"&&e!=="array"}function Nl(e,t,n,r){let s=e?.properties;if(!s||typeof s!="object")return[];let i=[];for(let[o,a]of Object.entries(s)){let c=a.type||"string",u=a.enum,l=zp(c,u),d=Jp(c),h=Gp(c,u);i.push({key:o,label:a.title||$p(o),type:c,description:a.description,enum_values:u,default_value:n[o]??r[o]??a.default,editable:t,filterable:l,sortable:d,filter_widget:h})}return i}function co(e){let t=e.default_data||{},n=e.field_defaults||{},r=Nl(e.input_schema,!0,t,n),s=Nl(e.system_schema,!1,t,n),i=[...r,...s],o=i.filter(u=>Yp(u.type)),a=i.filter(u=>u.filterable),c=i.filter(u=>u.sortable);return{fields:i,columns:o,filterable:a,sortable:c,form_fields:r,system_fields:s}}function Ql(e){return{field:"updated_at",direction:"desc"}}function Dl(e){let t=co(e),n=new Set(e.input_schema?.required||[]);return t.form_fields.filter(r=>n.has(r.key)||r.default_value===void 0)}var xe=ne(fe(),1);var Ul=Promise.resolve();function Ae(e){if(e?.aborted)throw new Error("Upload cancelled")}async function uo(e,t){if(Ae(t),e.size>16777216||!globalThis.crypto?.subtle)return{};let n=Ul.then(async()=>{Ae(t);let r=await e.arrayBuffer();Ae(t);let s=await globalThis.crypto.subtle.digest("SHA-256",r);return Ae(t),{expected_sha256:Array.from(new Uint8Array(s),i=>i.toString(16).padStart(2,"0")).join(""),expected_size_bytes:e.size}});return Ul=n.catch(()=>{}),n}function Kl(){if(globalThis.crypto?.randomUUID)return globalThis.crypto.randomUUID();let e=new Uint8Array(16);if(globalThis.crypto?.getRandomValues){globalThis.crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,n=>n.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let n=Math.floor(Math.random()*16);return(t==="x"?n:n&3|8).toString(16)})}async function Ll(e,t,n,r){let s=t.name||(e instanceof File?e.name:`file-${Date.now()}`),i=e.type||"application/octet-stream",o=t.itemType||"file",a=t.collisionPolicy||"keep_both",c=a==="keep_both"?Kl():void 0,u=G(),l=Z(),d=await uo(e,r);if(Ae(r),u!==G()||l!==Z())throw new Error("The account or Space changed while preparing the upload. Start it again.");let h={parent_path:t.parentPath,item_type:o,name:s,type_data:{...t.typeData||{},file_source:{type:"upload",content_type:i,collision_policy:a,...c?{upload_id:c}:{},...d}}};t.cardParentPath&&(h.card_parent_path=t.cardParentPath);let f=await R("create",h);Ae(r);let m=f;if(!m.id)throw new Error(m.error||m.message||"Failed to create file item");let v=m.id,g=m.path;if(m.storage_completed&&m.file_ref)return{itemId:v,itemPath:g,fileRef:m.file_ref};let w=m.storage_key,y=m.upload_token,_=m.storage_worker_url||"https://fsaos-storage.radns.workers.dev";if(!w)throw new Error("Gateway returned no storage_key \u2014 file_source may not be supported for this item type");await Xp(_,w,y,e,i,n,r),Ae(r);let S=await jl(v,w,i,y,d.expected_sha256,e.size);return{itemId:v,itemPath:g,fileRef:S}}function Xp(e,t,n,r,s,i,o){return new Promise((a,c)=>{let u=new XMLHttpRequest;if(u.open("PUT",`${e}/upload`),u.setRequestHeader("X-Storage-Key",t),u.setRequestHeader("Content-Type",s),n&&u.setRequestHeader("X-Upload-Token",n),u.upload.onprogress=l=>{l.lengthComputable&&i&&i(Math.round(l.loaded/l.total*100))},u.onload=()=>{u.status>=200&&u.status<300?a():c(new Error(`Storage upload failed: HTTP ${u.status} \u2014 ${u.responseText?.slice(0,300)}`))},u.onerror=()=>c(new Error("Storage upload network error")),u.ontimeout=()=>c(new Error("Storage upload timed out")),u.onabort=()=>c(new Error("Upload cancelled")),o){if(o.aborted){c(new Error("Upload cancelled"));return}o.addEventListener("abort",()=>{u.abort(),c(new Error("Upload cancelled"))})}u.send(r)})}async function jl(e,t,n,r,s,i){let o=await at(),a=await fetch(`${Fe}/storage/upload-complete`,{method:"POST",headers:{"Content-Type":"application/json",...o?{Authorization:`Bearer ${o}`}:{}},body:JSON.stringify({item_id:e,storage_key:t,content_type:n,...r?{upload_token:r}:{},...s?{hash:s}:{}})});if(!a.ok){let u=await a.text().catch(()=>"");throw new Error(`Upload confirmation failed: HTTP ${a.status} \u2014 ${u.slice(0,300)}`)}let c=await a.json();if(!c.success)throw new Error(c.error||c.message||"Upload confirmation rejected");if(s&&(c.file_ref?.content_sha256!==s||c.file_ref?.size_bytes!==i||c.file_ref?.content_type!==n))throw new Error("Stored file did not confirm the expected checksum, size and type");return c.file_ref}function Hl(){let[e,t]=(0,xe.useState)([]),n=L(),r=(0,xe.useRef)(e);r.current=e;let s=(0,xe.useRef)(new Map),i=(0,xe.useCallback)((g,w)=>{t(y=>y.map(_=>_.id===g?{..._,...w}:_))},[]),o=(0,xe.useCallback)(g=>{t(w=>[...w,g])},[]),a=(0,xe.useCallback)(async(g,w,y,_,S)=>{let x=y.name||w.name,M=w.type||"application/octet-stream",N=y.itemType||"file",P=y.collisionPolicy||"keep_both",O=S?.itemId||null,T=S?.itemPath||null,E=S?.storageKey||null,A=S?.uploadToken||null,F=S?.storageWorkerUrl||null,U=S?.contentSha256||void 0,H=new AbortController,ke=G(),j=Z();s.current.get(g)?.abort(),s.current.set(g,H);try{if(!_||_==="create"){i(g,{status:"creating",error:null,_failedAt:null});let ve=await uo(w,H.signal);if(Ae(H.signal),ke!==G()||j!==Z())throw new Error("The account or Space changed while preparing the upload. Start it again.");U=ve.expected_sha256;let Ue=await R("create",{parent_path:y.parentPath,item_type:N,name:x,type_data:{...y.typeData||{},file_source:{type:"upload",content_type:M,collision_policy:P,...P==="keep_both"?{upload_id:g}:{},...ve}}});Ae(H.signal);let ce=Ue;if(!ce.id)throw Object.assign(new Error(ce.error||ce.message||"Failed to create file item"),{_step:"create"});if(O=ce.id,T=ce.path,i(g,{itemId:O,itemPath:T}),ce.storage_completed&&ce.file_ref){i(g,{status:"complete",progress:100,fileRef:ce.file_ref}),n.invalidateQueries({queryKey:I.children(y.parentPath)});return}if(E=ce.storage_key,A=ce.upload_token||"",F=ce.storage_worker_url||"https://fsaos-storage.radns.workers.dev",i(g,{_storageKey:E,_uploadToken:A,_storageWorkerUrl:F,_contentSha256:U||null}),!E)throw Object.assign(new Error("Gateway returned no storage_key"),{_step:"create"})}(!_||_==="create"||_==="upload")&&(i(g,{status:"uploading",progress:0,error:null,_failedAt:null}),await new Promise((Ue,ce)=>{let pe=new XMLHttpRequest;i(g,{_xhr:pe}),pe.open("PUT",`${F}/upload`),pe.setRequestHeader("X-Storage-Key",E),pe.setRequestHeader("Content-Type",M),A&&pe.setRequestHeader("X-Upload-Token",A),pe.upload.onprogress=ge=>{ge.lengthComputable&&i(g,{progress:Math.round(ge.loaded/ge.total*100)})},pe.onload=()=>{pe.status>=200&&pe.status<300?Ue():ce(Object.assign(new Error(`Storage upload failed: HTTP ${pe.status}`),{_step:"upload"}))},pe.onerror=()=>ce(Object.assign(new Error("Storage upload network error"),{_step:"upload"})),pe.ontimeout=()=>ce(Object.assign(new Error("Storage upload timed out"),{_step:"upload"})),pe.onabort=()=>ce(Object.assign(new Error("Upload cancelled"),{_step:"upload"})),H.signal.addEventListener("abort",()=>pe.abort(),{once:!0}),Ae(H.signal),pe.send(w)}),Ae(H.signal),i(g,{progress:100,_xhr:null})),i(g,{status:"confirming",error:null,_failedAt:null});let me=await jl(O,E,M,A||"",U,w.size).catch(ve=>{throw Object.assign(ve,{_step:"confirm"})});Ae(H.signal),i(g,{status:"complete",fileRef:me}),n.invalidateQueries({queryKey:I.children(y.parentPath)})}catch(me){if(s.current.get(g)!==H)return;let ve=me?.message||String(me),Ue=me?._step||"create";i(g,{status:"error",error:ve,_failedAt:Ue,_xhr:null})}finally{s.current.get(g)===H&&s.current.delete(g)}},[i,n]),c=(0,xe.useCallback)((g,w)=>{let y=Kl();o({id:y,file:g,status:"creating",progress:0,error:null,itemId:null,itemPath:null,fileRef:null,options:w,_storageKey:null,_uploadToken:null,_storageWorkerUrl:null,_contentSha256:null,_xhr:null,_failedAt:null}),a(y,g,w)},[o,a]),u=(0,xe.useCallback)((g,w)=>{for(let y of g)c(y,w)},[c]),l=(0,xe.useCallback)(g=>{let w=r.current.find(S=>S.id===g);if(!w||w.status!=="error")return;let y=w._failedAt||"create",_=w._storageKey&&w.itemId?{storageKey:w._storageKey,uploadToken:w._uploadToken||"",storageWorkerUrl:w._storageWorkerUrl||"https://fsaos-storage.radns.workers.dev",itemId:w.itemId,itemPath:w.itemPath||"",contentSha256:w._contentSha256}:void 0;a(g,w.file,w.options,y,_)},[a]),d=(0,xe.useCallback)(g=>{s.current.get(g)?.abort();let w=r.current.find(y=>y.id===g);w&&(w._xhr&&w._xhr.abort(),i(g,{status:"error",error:"Cancelled",_xhr:null,_failedAt:null}))},[i]),h=(0,xe.useCallback)(g=>{s.current.get(g)?.abort(),s.current.delete(g),t(w=>w.filter(y=>y.id!==g))},[]),f=(0,xe.useCallback)(()=>{t(g=>g.filter(w=>w.status!=="complete"))},[]),m=e.some(g=>g.status==="creating"||g.status==="uploading"||g.status==="confirming"),v=e.map(({_storageKey:g,_uploadToken:w,_storageWorkerUrl:y,_contentSha256:_,_xhr:S,_failedAt:x,...M})=>M);return{upload:c,uploadMultiple:u,uploads:v,retryUpload:l,cancelUpload:d,removeUpload:h,clearCompleted:f,isUploading:m}}var Bl=ne(fe(),1);async function lo(e,t){return await R("resolve-items",{context_id:e,item_type:t})}function Vl(e,t){return(0,Bl.useSyncExternalStore)(Ie,G,G),W({queryKey:["vfs",z()??"__unscoped__","resolved-items",e??"",t],queryFn:()=>lo(e,t),enabled:!!(e&&t)})}var He=ne(fe(),1);function Ks(e,t){let n={artifacts:new Map,timeline:[]},r=new Map;function s(o){if(!o.action?.startsWith("artifact_"))return;let c,u=o.name;if(typeof u=="string"&&u.startsWith("{"))try{c=JSON.parse(u)}catch{return}else if(o.artifact_id)c=o;else return;switch(c.type){case"artifact_opened":{let l=Date.now();if(n.artifacts.set(c.artifact_id,{artifact_id:c.artifact_id,surface_type:c.surface_type,tool_id:c.tool_id,tool_name:c.tool_name,target_uri:c.target_uri,status:"streaming",content:"",total_chars:0,delta_count:0,artifact_item_uri:null,evidence_uri:null,meta:c.meta,started_at:l,completed_at:null}),r.has(c.tool_id)){let d=r.get(c.tool_id);n.timeline[d].artifact_ids.push(c.artifact_id)}else{let d=n.timeline.length;n.timeline.push({tool_id:c.tool_id,tool_name:c.tool_name,status:"started",target_uri:c.target_uri,started_at:l,completed_at:null,artifact_ids:[c.artifact_id]}),r.set(c.tool_id,d)}break}case"artifact_delta":{let l=n.artifacts.get(c.artifact_id);l&&(l.content+=c.content_delta,l.total_chars+=c.content_delta.length,l.delta_count+=1,c.target_uri&&!l.target_uri&&(l.target_uri=c.target_uri));break}case"artifact_done":{let l=n.artifacts.get(c.artifact_id);l&&(l.status=c.status,l.total_chars=c.total_chars,l.artifact_item_uri=c.artifact_item_uri,l.evidence_uri=c.evidence_uri,c.target_uri&&(l.target_uri=c.target_uri),(c.status==="completed"||c.status==="failed")&&(l.completed_at=Date.now()));let d=r.get(c.tool_id);if(d!==void 0){let h=n.timeline[d];c.status==="executing"?h.status="executing":c.status==="completed"?(h.status="completed",h.completed_at=Date.now()):c.status==="failed"&&(h.status="failed",h.completed_at=Date.now()),c.target_uri&&!h.target_uri&&(h.target_uri=c.target_uri)}break}}t(n)}return gs(e,s)}function Wl(e,t=!0){let[n,r]=(0,He.useState)(new Map),[s,i]=(0,He.useState)([]),o=(0,He.useRef)({artifacts:new Map,timeline:[]});(0,He.useEffect)(()=>!e||!t?void 0:Ks(e,d=>{o.current=d,r(new Map(d.artifacts)),i([...d.timeline])}),[e,t]);let a=(0,He.useCallback)(()=>{r(new Map),i([]),o.current={artifacts:new Map,timeline:[]}},[]),c=Array.from(n.values()).find(l=>l.surface_type==="file_editor"&&l.status==="streaming")??null,u=Array.from(n.values()).filter(l=>l.surface_type==="activity"&&(l.status==="streaming"||l.status==="executing"));return{artifacts:n,timeline:s,activeEditor:c,activeActivities:u,reset:a}}function $l(e,t=!0){let[n,r]=(0,He.useState)([]);(0,He.useEffect)(()=>!e||!t?void 0:Ks(e,o=>{r([...o.timeline])}),[e,t]);let s=n.length>0?n[n.length-1]:null;return{timeline:n,latestActivity:s}}var Ls=ne(fe(),1);function Zp(e,t,n,r){return["vfs","timeline-history",e,t??"__all__",n??500,r??0]}async function po(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(ef).sort((u,l)=>u.seq-l.seq):[]}catch(o){if(o?.status===404||o?.message?.includes("not found"))return[];throw o}}function Gl(e,t){let{turnId:n,limit:r=500,offset:s=0,enabled:i=!0,debounceMs:o=300}=t??{},a=e?`${e}/datasets/agent-events`:null,c=L(),u=(0,Ls.useRef)(null),l=a?Zp(a,n,r,s):["vfs","timeline-history","__disabled__"],d=W({queryKey:l,queryFn:()=>po(e,{turnId:n,limit:r,offset:s}),enabled:!!e&&i});return(0,Ls.useEffect)(()=>{if(!a||!i)return;let h=J("vfs_change",()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{c.invalidateQueries({queryKey:l})},o)},f=>{let m=f?.path;return m?m===a&&f.item_type==="dataset":!1});return()=>{h(),u.current&&clearTimeout(u.current)}},[a,i,o,c,JSON.stringify(l)]),{events:d.data??[],isLoading:d.isLoading,error:d.error,isFetching:d.isFetching,refetch:()=>{d.refetch()}}}function ef(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 Mt=ne(fe(),1);function zl(e){let t=(0,Mt.useSyncExternalStore)(Ie,G,G),n=z(),r=e?.path??n,s=ye(),i=e?.id??s?.id,o=(0,Mt.useMemo)(()=>({}),[t,n,r,i]),a=(0,Mt.useRef)(o);a.current=o;let c=zn(r?{key:"pinned",scope_id:i,_scope_path:r}:null),u=L(),l=c.resolvedChildren,d=!!(!c.error&&c.arrangement?.item_id&&c.resolutionLevel==="member"&&c.arrangement.write_target_id===c.arrangement.item_id),h=ie({mutationFn:async m=>{let v,g={_scope_path:m.scopePath};if(m.operation==="pin"?v=await R("create",{...g,parent_id:m.arrangementId,name:`pin-${m.target.id}`,item_type:"symlink",type_data:{target_item_id:m.target.id,target_type:m.target.item_type}}):m.operation==="unpin"?v=await R("delete",{...g,id:m.entry.id}):v=await R("update",{...g,id:m.arrangementId,type_data:{order:m.ids}}),v?.success===!1)throw new Error(v.error||"Pins could not be saved");return v},onSettled:(m,v,g)=>ut(u,g.queryKey)}),f=(0,Mt.useCallback)(m=>!d||!r||a.current!==o||t!==G()||z()!==n?Promise.reject(new Error("Personal pins are not available in this context")):m.operation==="unpin"&&!l.some(v=>v.id===m.entry.id)?Promise.reject(new Error("Pin is outside this arrangement")):m.operation==="reorder"&&(new Set(m.ids).size!==l.length||m.ids.length!==l.length||l.some(v=>!m.ids.includes(v.id)))?Promise.reject(new Error("Order must include each pin exactly once")):m.operation==="pin"&&l.some(v=>v.symlink_type_data?.target_item_id===m.target.id)?Promise.resolve(null):h.mutateAsync({...m,scopePath:r,arrangementId:c.arrangement.item_id,arrangementPath:c.arrangement.item_path,queryKey:c.arrangementQueryKey}),[d,t,n,r,o,l,c.arrangement,c.arrangementQueryKey,h.mutateAsync]);return{entries:l,isLoading:c.isLoading,error:c.error,refetch:c.refetch,ready:d,isSaving:h.isPending,saveError:h.error,isPinned:m=>l.some(v=>v.symlink_type_data?.target_item_id===m),pin:m=>f({operation:"pin",target:m}),unpin:m=>{let v=l.find(g=>g.symlink_type_data?.target_item_id===m||g.id===m);return v?f({operation:"unpin",entry:v}):Promise.resolve(null)},reorder:m=>f({operation:"reorder",ids:m})}}var js=ne(fe(),1);var Dr=(e,t,n)=>["vfs",e,"personal-sections",t,n];function fo(e,t){return e&&e.item_id===t.item_id&&e.version>t.version?e:t}async function mo(e,t,n,r){let s=await R("personal-sections",{...r,context_item_id:t,collection:n,_scope_path:e});if(!s||s.success===!1)throw new Error(s?.message||s?.error||"Sections could not be saved");if(!Array.isArray(s.sections)||s.context_item_id!==t||s.collection!==n)throw new Error("Invalid sections response");return s}async function Jl(e,t){let n=await mo(e.scopePath,e.contextId,e.collection,{operation:"assign",section_id:e.sectionId,target_id:t}),r=Q();return r.setQueryData(Dr(e.scopePath,e.contextId,e.collection),s=>fo(s,n)),Yl(r,e.scopePath),n}function Yl(e,t){for(let n of e.getQueryCache().getAll())n.queryKey[0]==="vfs"&&n.queryKey[1]===t&&n.queryKey[2]==="personal-sections"&&ut(e,n.queryKey)}function Xl(e,t){let n=(0,js.useSyncExternalStore)(Ie,G,G),r=z(),s=L(),i=Dr(r,e,t),o=W({queryKey:i,enabled:!!r&&!!e,queryFn:()=>mo(r,e,t,{operation:"list"}),staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0,personalSections:!0},structuralSharing:(d,h)=>fo(d,h)}),a=(0,js.useRef)(!1),c=ie({mutationFn:async d=>{let h=await mo(d.scope,d.context,d.collection,{...d.change,...d.change.operation.startsWith("reorder")?{expected_version:d.version}:{}});return s.setQueryData(Dr(d.scope,d.context,d.collection),f=>fo(f,h)),h},onSettled:(d,h,f)=>Yl(s,f.scope)});async function u(d){if(!r||!e||n!==G()||z()!==r||!o.data||o.error)throw new Error("Select the Space again before changing sections");if(a.current)throw new Error("A section change is still being saved");a.current=!0;try{return await c.mutateAsync({change:d,scope:r,context:e,collection:t,version:o.data.version})}finally{a.current=!1}}function l(d){if(!r||!e||!o.data?.sections.some(h=>h.id===d))throw new Error("Section is unavailable");return{scopePath:r,contextId:e,collection:t,sectionId:d}}return{sections:o.data?.sections??[],ready:!!o.data&&!o.error,isLoading:o.isLoading,error:o.error,refetch:o.refetch,isSaving:c.isPending,change:u,destination:l,contextKey:`${n}:${r}:${e}:${t}`}}_u(go);return ad(go);})();
8
8
 
9
9
  /* ── Auto-setup: require shim + mount + backward compat globals ── */
10
10
  (function() {