@ai4b-team/fsaos-gateway-sdk 5.5.0 → 5.5.2

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-15T02:30:26.016Z */
2
- "use strict";var __FSAOS_GATEWAY__=(()=>{var ql=Object.create;var Bn=Object.defineProperty;var Nl=Object.getOwnPropertyDescriptor;var Ql=Object.getOwnPropertyNames;var Dl=Object.getPrototypeOf,Ul=Object.prototype.hasOwnProperty;var ao=e=>{throw TypeError(e)};var Kl=(e,t,n)=>t in e?Bn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var $n=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),co=(e,t)=>{for(var n in t)Bn(e,n,{get:t[n],enumerable:!0})},uo=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ql(t))!Ul.call(e,s)&&s!==n&&Bn(e,s,{get:()=>t[s],enumerable:!(r=Nl(t,s))||r.enumerable});return e};var Y=(e,t,n)=>(n=e!=null?ql(Dl(e)):{},uo(t||!e||!e.__esModule?Bn(n,"default",{value:e,enumerable:!0}):n,e)),Ll=e=>uo(Bn({},"__esModule",{value:!0}),e);var z=(e,t,n)=>Kl(e,typeof t!="symbol"?t+"":t,n),Ds=(e,t,n)=>t.has(e)||ao("Cannot "+n);var d=(e,t,n)=>(Ds(e,t,"read from private field"),n?n.call(e):t.get(e)),I=(e,t,n)=>t.has(e)?ao("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),S=(e,t,n,r)=>(Ds(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),F=(e,t,n)=>(Ds(e,t,"access private method"),n);var Vn=(e,t,n,r)=>({set _(s){S(e,t,s,n)},get _(){return d(e,t,r)}});var ue=$n((Qf,lo)=>{lo.exports=React});var Hr=$n((Fm,$o)=>{$o.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var sa=$n((dg,ra)=>{ra.exports={createClient:window.supabase.createClient}});var Fa=$n((Tg,Oa)=>{Oa.exports=ReactDOM});var Ju=$n((Iy,zu)=>{zu.exports=ReactDOM});var io={};co(io,{CHANNEL_AI_MODES:()=>_u,ComponentRenderer:()=>mu,EnforcementDeniedError:()=>Fe,FormSubmissionError:()=>jn,GatewayRequestError:()=>ge,HostSessionUnavailableError:()=>Ht,InteractionTrackingError:()=>Ln,KernelProvider:()=>gu,QueryClientProvider:()=>sr,acceptInvitation:()=>wf,acceptInvite:()=>Ji,answerInput:()=>Xi,assignPersonalSection:()=>El,auth:()=>ol,awaitAnchorReady:()=>ur,awaitScopeReady:()=>ha,callTool:()=>rl,cancelInvitation:()=>xf,cancelQueuedTurn:()=>Wu,cancelTurn:()=>$u,clearCachedToken:()=>fi,clearSession:()=>bi,configureGatewayReads:()=>Ia,connectHostSession:()=>_a,createAgent:()=>Zi,createInvitation:()=>vf,createItem:()=>el,disconnectSSE:()=>Mi,disposeVfsRealtimeWs:()=>Fi,electHomeAnchor:()=>Kt,emitEvent:()=>tc,fetchChannelMessages:()=>dc,fetchChannelMessagesPage:()=>wr,fetchChannelMessagesWithCards:()=>vs,fetchEdgesForItem:()=>ms,fetchItemHistory:()=>ys,fetchItemVersions:()=>vr,fetchItems:()=>Vt,fetchMemberFocus:()=>_s,fetchOpenEnvelope:()=>br,fetchRecentActivity:()=>hs,fetchResolvedItems:()=>to,fetchTimelineHistory:()=>no,fetchTurnQueueEntries:()=>cc,fetchTypeDefinitions:()=>ps,fetchVfsChildren:()=>_r,fetchVfsChildrenPage:()=>fs,fetchVfsItem:()=>yr,fetchVfsItemById:()=>hr,fetchVfsTree:()=>gs,gatewayCall:()=>x,getAccessToken:()=>tt,getAnchor:()=>_t,getAnchorRef:()=>de,getAnchorVersion:()=>gi,getAssetUrl:()=>il,getDefaultSort:()=>gl,getHomeAnchor:()=>me,getInvitation:()=>bf,getMountVersion:()=>lr,getMounts:()=>Ae,getPathSubscriptionState:()=>rc,getQueryClient:()=>N,getRequiredFormFields:()=>hl,getScope:()=>W,getScopeVersion:()=>ee,getServerClockOffsetMs:()=>xa,getServerClockSyncedAt:()=>Ra,getSessionEntry:()=>vt,hasServerClock:()=>Sa,initSession:()=>nt,initVfsRealtimeWs:()=>Wt,initializeFsaos:()=>ju,initializeWorkspace:()=>Ms,interpretSchema:()=>eo,invalidateAllVfs:()=>mc,invalidateChannelMessages:()=>hc,invalidateChildren:()=>ds,invalidateItem:()=>Oi,invalidateOpenEnvelope:()=>yc,invalidatePathAndParent:()=>fc,invalidateSubtree:()=>pc,invalidateTypes:()=>gc,inviteMember:()=>zi,isAnchorReady:()=>yi,isChannelPath:()=>he,isListableItemsFilter:()=>qn,isScopeReady:()=>zr,itemsFilterFromQueryFilter:()=>uc,listChildren:()=>Xu,listInvitations:()=>Pf,loadMounts:()=>Gt,loadPublishedBundle:()=>ou,mount:()=>al,mountRealtimeScope:()=>Qn,normalizeItem:()=>Oe,onConnectionStateChange:()=>ls,pathSubscriptionMatches:()=>Ti,personalSectionsKey:()=>Mr,ping:()=>nc,pushChanges:()=>nl,queryClient:()=>La,readItem:()=>Zu,refreshQuery:()=>be,registerCleanup:()=>se,rejectInvitation:()=>Sf,replaceMounts:()=>Rs,resendInvitation:()=>Rf,resetAllSdkState:()=>Cn,resolvePrincipalId:()=>fu,resubscribePath:()=>ic,seatMember:()=>Yi,selectMount:()=>Cr,serveHostSession:()=>Bu,serverDeadlinePassed:()=>Pa,serverMsUntil:()=>Ca,serverNow:()=>Zr,setAnchor:()=>Pn,setCachedToken:()=>aa,setQueryClient:()=>Ka,setScope:()=>ga,setupRequireShim:()=>cl,signal:()=>sl,startTracking:()=>ks,steerTurn:()=>Vu,submitForm:()=>Gu,subscribeAnchor:()=>hi,subscribeArtifactStream:()=>Os,subscribeMounts:()=>Gr,subscribeScope:()=>xe,subscribeToEvents:()=>ie,subscribeToPath:()=>us,subscribeToScope:()=>Fn,trackAction:()=>Ku,trackEvent:()=>Jt,trackPageView:()=>Uu,unmountRealtimeScope:()=>Ss,updateItem:()=>tl,uploadFile:()=>_l,useAcceptInvite:()=>ll,useAccounts:()=>Yc,useAgentTimeline:()=>Rl,useAllChannels:()=>Ts,useAnswerInput:()=>pl,useArrangement:()=>Kn,useArtifactStream:()=>xl,useAsset:()=>Xc,useAuth:()=>Is,useChannelMessages:()=>hu,useChannels:()=>vu,useChildren:()=>qc,useComponent:()=>Hi,useCreate:()=>Su,useCreateAgent:()=>fl,useDelete:()=>Pu,useDmChannels:()=>bu,useEdges:()=>Hc,useEventStream:()=>Tu,useFileUpload:()=>bl,useIncrementalItems:()=>Kc,useInfiniteChannelMessages:()=>yu,useInfiniteChildren:()=>Lc,useInfiniteItems:()=>Li,useInviteMember:()=>ul,useItem:()=>Oc,useItemById:()=>Fc,useItemHistory:()=>Gc,useItemVersions:()=>Wc,useItems:()=>Uc,useLink:()=>Eu,useList:()=>Ki,useMemberFocus:()=>Vc,useMintedAsset:()=>ku,useMounts:()=>Zc,useMove:()=>Cu,useMutation:()=>Iu,useNotifications:()=>ji,useOpen:()=>Bc,usePermission:()=>uu,usePermissions:()=>lu,usePersonalItemOrder:()=>Ou,usePersonalSections:()=>Tl,usePinnedItems:()=>Cl,usePrincipal:()=>pu,usePublishedComponent:()=>au,useRealtimeQuery:()=>Au,useRecentActivity:()=>zc,useResolve:()=>Dc,useResolvedItems:()=>Sl,useScope:()=>Jc,useScopeReady:()=>Mc,useSearch:()=>Qc,useSeatMember:()=>dl,useTheme:()=>cu,useTimelineHistory:()=>Pl,useTree:()=>Nc,useType:()=>jc,useTypeHelpers:()=>$c,useTypes:()=>Es,useUnreadCounts:()=>wu,useUpdate:()=>xu,useUpdatePrincipal:()=>Ru,vfsKeys:()=>E,waitForPathReady:()=>sc});var Fe=class e extends Error{constructor(n){let r=n.message||e.fallbackMessage(n);super(r);z(this,"name","EnforcementDeniedError");z(this,"deniedBy");z(this,"ruleKey");z(this,"displayName");z(this,"payload");this.payload=n,this.deniedBy=n.denied_by||n.error_type||n.error||"unknown";let s=n.enforcement;this.ruleKey=s?.rule_key??void 0,this.displayName=s?.display_name??void 0}static fallbackMessage(n){let r=n.error||"",s=n.denied_by||"";return s==="rule"||r==="RULE_DENIED"?"This feature is not enabled for this workspace.":s==="entitlement"||r==="ENTITLEMENT_REQUIRED"?"This feature requires a plan upgrade.":s==="access"||r==="ACCESS_DENIED"||r==="PERMISSION_DENIED"?"You don't have permission to do this.":"This action is not allowed."}get isRuleDenial(){return this.deniedBy==="rule"||this.deniedBy==="RULE_DENIED"}get isAccessDenial(){return this.deniedBy==="access"||this.deniedBy==="ACCESS_DENIED"}get isEntitlementDenial(){return this.deniedBy==="entitlement"||this.deniedBy==="ENTITLEMENT_REQUIRED"}};var Pt=Y(ue(),1);var Ee=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var It,at,Zt,fo,Hl=(fo=class extends Ee{constructor(){super();I(this,It);I(this,at);I(this,Zt);S(this,Zt,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){d(this,at)||this.setEventListener(d(this,Zt))}onUnsubscribe(){var t;this.hasListeners()||((t=d(this,at))==null||t.call(this),S(this,at,void 0))}setEventListener(t){var n;S(this,Zt,t),(n=d(this,at))==null||n.call(this),S(this,at,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){d(this,It)!==t&&(S(this,It,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof d(this,It)=="boolean"?d(this,It):globalThis.document?.visibilityState!=="hidden"}},It=new WeakMap,at=new WeakMap,Zt=new WeakMap,fo),Xt=new Hl;var jl={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},ct,Us,po,Bl=(po=class{constructor(){I(this,ct,jl);I(this,Us,!1)}setTimeoutProvider(e){S(this,ct,e)}setTimeout(e,t){return d(this,ct).setTimeout(e,t)}clearTimeout(e){d(this,ct).clearTimeout(e)}setInterval(e,t){return d(this,ct).setInterval(e,t)}clearInterval(e){d(this,ct).clearInterval(e)}},ct=new WeakMap,Us=new WeakMap,po),De=new Bl;function mo(e){setTimeout(e,0)}var Ls=typeof window>"u"||"Deno"in globalThis;function Z(){}function yo(e,t){return typeof e=="function"?e(t):e}function Wn(e){return typeof e=="number"&&e>=0&&e!==1/0}function Or(e,t){return Math.max(e+(t||0)-Date.now(),0)}function qe(e,t){return typeof e=="function"?e(t):e}function ye(e,t){return typeof e=="function"?e(t):e}function Fr(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:o,stale:a}=e;if(o){if(r){if(t.queryHash!==Gn(o,t.options))return!1}else if(!Tt(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 qr(e,t){let{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Ue(t.options.mutationKey)!==Ue(i))return!1}else if(!Tt(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function Gn(e,t){return(t?.queryKeyHashFn||Ue)(e)}function Ue(e){return JSON.stringify(e,(t,n)=>Ks(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function Tt(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>Tt(e[n],t[n])):!1}var $l=Object.prototype.hasOwnProperty;function Hs(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=go(e)&&go(t);if(!r&&!(Ks(e)&&Ks(t)))return t;let i=(r?e:Object.keys(e)).length,o=r?t:Object.keys(t),a=o.length,c=r?new Array(a):{},u=0;for(let l=0;l<a;l++){let f=r?l:o[l],h=e[f],p=t[f];if(h===p){c[f]=h,(r?l<i:$l.call(e,f))&&u++;continue}if(h===null||p===null||typeof h!="object"||typeof p!="object"){c[f]=p;continue}let m=Hs(h,p,n+1);c[f]=m,m===h&&u++}return i===a&&u===i?e:c}function en(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 go(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Ks(e){if(!ho(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!ho(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function ho(e){return Object.prototype.toString.call(e)==="[object Object]"}function _o(e){return new Promise(t=>{De.setTimeout(t,e)})}function zn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Hs(e,t):t}function vo(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function bo(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var tn=Symbol();function Nr(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===tn?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function nn(e,t){return typeof e=="function"?e(...t):!!e}function wo(e,t,n){let r=!1,s;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(s??(s=t()),r||(r=!0,s.aborted?n():s.addEventListener("abort",n,{once:!0})),s)}),e}var Ke=(()=>{let e=()=>Ls;return{isServer(){return e()},setIsServer(t){e=t}}})();function Jn(){let e,t,n=new Promise((s,i)=>{e=s,t=i});n.status="pending",n.catch(()=>{});function r(s){Object.assign(n,s),delete n.resolve,delete n.reject}return n.resolve=s=>{r({status:"fulfilled",value:s}),e(s)},n.reject=s=>{r({status:"rejected",reason:s}),t(s)},n}var So=mo;function Vl(){let e=[],t=0,n=a=>{a()},r=a=>{a()},s=So,i=a=>{t?e.push(a):s(()=>{n(a)})},o=()=>{let a=e;e=[],a.length&&s(()=>{r(()=>{a.forEach(c=>{n(c)})})})};return{batch:a=>{let c;t++;try{c=a()}finally{t--,t||o()}return c},batchCalls:a=>(...c)=>{i(()=>{a(...c)})},schedule:i,setNotifyFunction:a=>{n=a},setBatchNotifyFunction:a=>{r=a},setScheduler:a=>{s=a}}}var j=Vl();var rn,ut,sn,xo,Wl=(xo=class extends Ee{constructor(){super();I(this,rn,!0);I(this,ut);I(this,sn);S(this,sn,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){d(this,ut)||this.setEventListener(d(this,sn))}onUnsubscribe(){var t;this.hasListeners()||((t=d(this,ut))==null||t.call(this),S(this,ut,void 0))}setEventListener(t){var n;S(this,sn,t),(n=d(this,ut))==null||n.call(this),S(this,ut,t(this.setOnline.bind(this)))}setOnline(t){d(this,rn)!==t&&(S(this,rn,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return d(this,rn)}},rn=new WeakMap,ut=new WeakMap,sn=new WeakMap,xo),on=new Wl;function Gl(e){return Math.min(1e3*2**e,3e4)}function js(e){return(e??"online")==="online"?on.isOnline():!0}var Qr=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Dr(e){let t=!1,n=0,r,s=Jn(),i=()=>s.status!=="pending",o=y=>{if(!i()){let g=new Qr(y);h(g),e.onCancel?.(g)}},a=()=>{t=!0},c=()=>{t=!1},u=()=>Xt.isFocused()&&(e.networkMode==="always"||on.isOnline())&&e.canRun(),l=()=>js(e.networkMode)&&e.canRun(),f=y=>{i()||(r?.(),s.resolve(y))},h=y=>{i()||(r?.(),s.reject(y))},p=()=>new Promise(y=>{r=g=>{(i()||u())&&y(g)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),m=()=>{if(i())return;let y,g=n===0?e.initialPromise:void 0;try{y=g??e.fn()}catch(v){y=Promise.reject(v)}Promise.resolve(y).then(f).catch(v=>{if(i())return;let _=e.retry??(Ke.isServer()?0:3),w=e.retryDelay??Gl,C=typeof w=="function"?w(n,v):w,R=_===!0||typeof _=="number"&&n<_||typeof _=="function"&&_(n,v);if(t||!R){h(v);return}n++,e.onFail?.(n,v),_o(C).then(()=>u()?void 0:p()).then(()=>{t?h(v):m()})})};return{promise:s,status:()=>s.status,cancel:o,continue:()=>(r?.(),s),cancelRetry:a,continueRetry:c,canStart:l,start:()=>(l()?m():p().then(m),s)}}var At,Ro,Ur=(Ro=class{constructor(){I(this,At)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Wn(this.gcTime)&&S(this,At,De.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ke.isServer()?1/0:5*60*1e3))}clearGcTimeout(){d(this,At)!==void 0&&(De.clearTimeout(d(this,At)),S(this,At,void 0))}},At=new WeakMap,Ro);var kt,an,Ie,Mt,oe,Yn,Ot,Se,To,We,Eo,Io=(Eo=class extends Ur{constructor(t){super();I(this,Se);I(this,kt);I(this,an);I(this,Ie);I(this,Mt);I(this,oe);I(this,Yn);I(this,Ot);S(this,Ot,!1),S(this,Yn,t.defaultOptions),this.setOptions(t.options),this.observers=[],S(this,Mt,t.client),S(this,Ie,d(this,Mt).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,S(this,kt,Co(this.options)),this.state=t.state??d(this,kt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return d(this,oe)?.promise}setOptions(t){if(this.options={...d(this,Yn),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=Co(this.options);n.data!==void 0&&(this.setState(Po(n.data,n.dataUpdatedAt)),S(this,kt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&d(this,Ie).remove(this)}setData(t,n){let r=zn(this.state.data,t,this.options);return F(this,Se,We).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){F(this,Se,We).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=d(this,oe)?.promise;return d(this,oe)?.cancel(t),n?n.then(Z).catch(Z):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return d(this,kt)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>ye(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===tn||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>qe(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!Or(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),d(this,oe)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),d(this,oe)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),d(this,Ie).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(d(this,oe)&&(d(this,Ot)||F(this,Se,To).call(this)?d(this,oe).cancel({revert:!0}):d(this,oe).cancelRetry()),this.scheduleGc()),d(this,Ie).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||F(this,Se,We).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&d(this,oe)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(d(this,oe))return d(this,oe).continueRetry(),d(this,oe).promise}if(t&&this.setOptions(t),!this.options.queryFn){let c=this.observers.find(u=>u.options.queryFn);c&&this.setOptions(c.options)}let r=new AbortController,s=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(S(this,Ot,!0),r.signal)})},i=()=>{let c=Nr(this.options,n),l=(()=>{let f={client:d(this,Mt),queryKey:this.queryKey,meta:this.meta};return s(f),f})();return S(this,Ot,!1),this.options.persister?this.options.persister(c,l,this):c(l)},a=(()=>{let c={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:d(this,Mt),state:this.state,fetchFn:i};return s(c),c})();this.options.behavior?.onFetch(a,this),S(this,an,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&F(this,Se,We).call(this,{type:"fetch",meta:a.fetchOptions?.meta}),S(this,oe,Dr({initialPromise:n?.initialPromise,fn:a.fetchFn,onCancel:c=>{c instanceof Qr&&c.revert&&this.setState({...d(this,an),fetchStatus:"idle"}),r.abort()},onFail:(c,u)=>{F(this,Se,We).call(this,{type:"failed",failureCount:c,error:u})},onPause:()=>{F(this,Se,We).call(this,{type:"pause"})},onContinue:()=>{F(this,Se,We).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0}));try{let c=await d(this,oe).start();if(c===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(c),d(this,Ie).config.onSuccess?.(c,this),d(this,Ie).config.onSettled?.(c,this.state.error,this),c}catch(c){if(c instanceof Qr){if(c.silent)return d(this,oe).promise;if(c.revert){if(this.state.data===void 0)throw c;return this.state.data}}throw F(this,Se,We).call(this,{type:"error",error:c}),d(this,Ie).config.onError?.(c,this),d(this,Ie).config.onSettled?.(this.state.data,c,this),c}finally{this.scheduleGc()}}},kt=new WeakMap,an=new WeakMap,Ie=new WeakMap,Mt=new WeakMap,oe=new WeakMap,Yn=new WeakMap,Ot=new WeakMap,Se=new WeakSet,To=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},We=function(t){let n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...Bs(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...Po(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return S(this,an,t.manual?s:void 0),s;case"error":let i=t.error;return{...r,error:i,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),j.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),d(this,Ie).notify({query:this,type:"updated",action:t})})},Eo);function Bs(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:js(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Po(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Co(e){let t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var _e,U,Xn,pe,Ft,cn,Ge,lt,er,un,ln,qt,Nt,dt,dn,H,Zn,$s,Vs,Ws,Gs,zs,Js,Ys,Oo,Mo,tr=(Mo=class extends Ee{constructor(t,n){super();I(this,H);I(this,_e);I(this,U);I(this,Xn);I(this,pe);I(this,Ft);I(this,cn);I(this,Ge);I(this,lt);I(this,er);I(this,un);I(this,ln);I(this,qt);I(this,Nt);I(this,dt);I(this,dn,new Set);this.options=n,S(this,_e,t),S(this,lt,null),S(this,Ge,Jn()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(d(this,U).addObserver(this),Ao(d(this,U),this.options)?F(this,H,Zn).call(this):this.updateResult(),F(this,H,Gs).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Zs(d(this,U),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Zs(d(this,U),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,F(this,H,zs).call(this),F(this,H,Js).call(this),d(this,U).removeObserver(this)}setOptions(t){let n=this.options,r=d(this,U);if(this.options=d(this,_e).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof ye(this.options.enabled,d(this,U))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");F(this,H,Ys).call(this),d(this,U).setOptions(this.options),n._defaulted&&!en(this.options,n)&&d(this,_e).getQueryCache().notify({type:"observerOptionsUpdated",query:d(this,U),observer:this});let s=this.hasListeners();s&&ko(d(this,U),r,this.options,n)&&F(this,H,Zn).call(this),this.updateResult(),s&&(d(this,U)!==r||ye(this.options.enabled,d(this,U))!==ye(n.enabled,d(this,U))||qe(this.options.staleTime,d(this,U))!==qe(n.staleTime,d(this,U)))&&F(this,H,$s).call(this);let i=F(this,H,Vs).call(this);s&&(d(this,U)!==r||ye(this.options.enabled,d(this,U))!==ye(n.enabled,d(this,U))||i!==d(this,dt))&&F(this,H,Ws).call(this,i)}getOptimisticResult(t){let n=d(this,_e).getQueryCache().build(d(this,_e),t),r=this.createResult(n,t);return Jl(this,r)&&(S(this,pe,r),S(this,cn,this.options),S(this,Ft,d(this,U).state)),r}getCurrentResult(){return d(this,pe)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&d(this,Ge).status==="pending"&&d(this,Ge).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){d(this,dn).add(t)}getCurrentQuery(){return d(this,U)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=d(this,_e).defaultQueryOptions(t),r=d(this,_e).getQueryCache().build(d(this,_e),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return F(this,H,Zn).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),d(this,pe)))}createResult(t,n){let r=d(this,U),s=this.options,i=d(this,pe),o=d(this,Ft),a=d(this,cn),u=t!==r?t.state:d(this,Xn),{state:l}=t,f={...l},h=!1,p;if(n._optimisticResults){let k=this.hasListeners(),T=!k&&Ao(t,n),A=k&&ko(t,r,n,s);(T||A)&&(f={...f,...Bs(l.data,t.options)}),n._optimisticResults==="isRestoring"&&(f.fetchStatus="idle")}let{error:m,errorUpdatedAt:y,status:g}=f;p=f.data;let v=!1;if(n.placeholderData!==void 0&&p===void 0&&g==="pending"){let k;i?.isPlaceholderData&&n.placeholderData===a?.placeholderData?(k=i.data,v=!0):k=typeof n.placeholderData=="function"?n.placeholderData(d(this,ln)?.state.data,d(this,ln)):n.placeholderData,k!==void 0&&(g="success",p=zn(i?.data,k,n),h=!0)}if(n.select&&p!==void 0&&!v)if(i&&p===o?.data&&n.select===d(this,er))p=d(this,un);else try{S(this,er,n.select),p=n.select(p),p=zn(i?.data,p,n),S(this,un,p),S(this,lt,null)}catch(k){S(this,lt,k)}d(this,lt)&&(m=d(this,lt),p=d(this,un),y=Date.now(),g="error");let _=f.fetchStatus==="fetching",w=g==="pending",C=g==="error",R=w&&_,M=p!==void 0,P={status:g,fetchStatus:f.fetchStatus,isPending:w,isSuccess:g==="success",isError:C,isInitialLoading:R,isLoading:R,data:p,dataUpdatedAt:f.dataUpdatedAt,error:m,errorUpdatedAt:y,failureCount:f.fetchFailureCount,failureReason:f.fetchFailureReason,errorUpdateCount:f.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:f.dataUpdateCount>u.dataUpdateCount||f.errorUpdateCount>u.errorUpdateCount,isFetching:_,isRefetching:_&&!w,isLoadingError:C&&!M,isPaused:f.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:C&&M,isStale:Xs(t,n),refetch:this.refetch,promise:d(this,Ge),isEnabled:ye(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let k=P.data!==void 0,T=P.status==="error"&&!k,A=K=>{T?K.reject(P.error):k&&K.resolve(P.data)},O=()=>{let K=S(this,Ge,P.promise=Jn());A(K)},q=d(this,Ge);switch(q.status){case"pending":t.queryHash===r.queryHash&&A(q);break;case"fulfilled":(T||P.data!==q.value)&&O();break;case"rejected":(!T||P.error!==q.reason)&&O();break}}return P}updateResult(){let t=d(this,pe),n=this.createResult(d(this,U),this.options);if(S(this,Ft,d(this,U).state),S(this,cn,this.options),d(this,Ft).data!==void 0&&S(this,ln,d(this,U)),en(n,t))return;S(this,pe,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!d(this,dn).size)return!0;let o=new Set(i??d(this,dn));return this.options.throwOnError&&o.add("error"),Object.keys(d(this,pe)).some(a=>{let c=a;return d(this,pe)[c]!==t[c]&&o.has(c)})};F(this,H,Oo).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&F(this,H,Gs).call(this)}},_e=new WeakMap,U=new WeakMap,Xn=new WeakMap,pe=new WeakMap,Ft=new WeakMap,cn=new WeakMap,Ge=new WeakMap,lt=new WeakMap,er=new WeakMap,un=new WeakMap,ln=new WeakMap,qt=new WeakMap,Nt=new WeakMap,dt=new WeakMap,dn=new WeakMap,H=new WeakSet,Zn=function(t){F(this,H,Ys).call(this);let n=d(this,U).fetch(this.options,t);return t?.throwOnError||(n=n.catch(Z)),n},$s=function(){F(this,H,zs).call(this);let t=qe(this.options.staleTime,d(this,U));if(Ke.isServer()||d(this,pe).isStale||!Wn(t))return;let r=Or(d(this,pe).dataUpdatedAt,t)+1;S(this,qt,De.setTimeout(()=>{d(this,pe).isStale||this.updateResult()},r))},Vs=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(d(this,U)):this.options.refetchInterval)??!1},Ws=function(t){F(this,H,Js).call(this),S(this,dt,t),!(Ke.isServer()||ye(this.options.enabled,d(this,U))===!1||!Wn(d(this,dt))||d(this,dt)===0)&&S(this,Nt,De.setInterval(()=>{(this.options.refetchIntervalInBackground||Xt.isFocused())&&F(this,H,Zn).call(this)},d(this,dt)))},Gs=function(){F(this,H,$s).call(this),F(this,H,Ws).call(this,F(this,H,Vs).call(this))},zs=function(){d(this,qt)!==void 0&&(De.clearTimeout(d(this,qt)),S(this,qt,void 0))},Js=function(){d(this,Nt)!==void 0&&(De.clearInterval(d(this,Nt)),S(this,Nt,void 0))},Ys=function(){let t=d(this,_e).getQueryCache().build(d(this,_e),this.options);if(t===d(this,U))return;let n=d(this,U);S(this,U,t),S(this,Xn,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},Oo=function(t){j.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(d(this,pe))}),d(this,_e).getQueryCache().notify({query:d(this,U),type:"observerResultsUpdated"})})},Mo);function zl(e,t){return ye(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Ao(e,t){return zl(e,t)||e.state.data!==void 0&&Zs(e,t,t.refetchOnMount)}function Zs(e,t,n){if(ye(t.enabled,e)!==!1&&qe(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Xs(e,t)}return!1}function ko(e,t,n,r){return(e!==t||ye(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Xs(e,n)}function Xs(e,t){return ye(t.enabled,e)!==!1&&e.isStaleByTime(qe(t.staleTime,e))}function Jl(e,t){return!en(e.getCurrentResult(),t)}function fn(e){return{onFetch:(t,n)=>{let r=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],o=t.state.data?.pageParams||[],a={pages:[],pageParams:[]},c=0,u=async()=>{let l=!1,f=m=>{wo(m,()=>t.signal,()=>l=!0)},h=Nr(t.options,t.fetchOptions),p=async(m,y,g)=>{if(l)return Promise.reject();if(y==null&&m.pages.length)return Promise.resolve(m);let _=(()=>{let M={client:t.client,queryKey:t.queryKey,pageParam:y,direction:g?"backward":"forward",meta:t.options.meta};return f(M),M})(),w=await h(_),{maxPages:C}=t.options,R=g?bo:vo;return{pages:R(m.pages,w,C),pageParams:R(m.pageParams,y,C)}};if(s&&i.length){let m=s==="backward",y=m?Fo:ei,g={pages:i,pageParams:o},v=y(r,g);a=await p(g,v,m)}else{let m=e??i.length;do{let y=c===0?o[0]??r.initialPageParam:ei(r,a);if(c>0&&y==null)break;a=await p(a,y),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 ei(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function Fo(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function qo(e,t){return t?ei(e,t)!=null:!1}function No(e,t){return!t||!e.getPreviousPageParam?!1:Fo(e,t)!=null}var ti=class extends tr{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:fn()})}getOptimisticResult(e){return e.behavior=fn(),super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){let{state:n}=e,r=super.createResult(e,t),{isFetching:s,isRefetching:i,isError:o,isRefetchError:a}=r,c=n.fetchMeta?.fetchMore?.direction,u=o&&c==="forward",l=s&&c==="forward",f=o&&c==="backward",h=s&&c==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:qo(t,n.data),hasPreviousPage:No(t,n.data),isFetchNextPageError:u,isFetchingNextPage:l,isFetchPreviousPageError:f,isFetchingPreviousPage:h,isRefetchError:a&&!u&&!f,isRefetching:i&&!l&&!h}}};var nr,Le,le,Qt,He,ft,Qo,Do=(Qo=class extends Ur{constructor(t){super();I(this,He);I(this,nr);I(this,Le);I(this,le);I(this,Qt);S(this,nr,t.client),this.mutationId=t.mutationId,S(this,le,t.mutationCache),S(this,Le,[]),this.state=t.state||ni(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){d(this,Le).includes(t)||(d(this,Le).push(t),this.clearGcTimeout(),d(this,le).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){S(this,Le,d(this,Le).filter(n=>n!==t)),this.scheduleGc(),d(this,le).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){d(this,Le).length||(this.state.status==="pending"?this.scheduleGc():d(this,le).remove(this))}continue(){return d(this,Qt)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{F(this,He,ft).call(this,{type:"continue"})},r={client:d(this,nr),meta:this.options.meta,mutationKey:this.options.mutationKey};S(this,Qt,Dr({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(o,a)=>{F(this,He,ft).call(this,{type:"failed",failureCount:o,error:a})},onPause:()=>{F(this,He,ft).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>d(this,le).canRun(this)}));let s=this.state.status==="pending",i=!d(this,Qt).canStart();try{if(s)n();else{F(this,He,ft).call(this,{type:"pending",variables:t,isPaused:i}),d(this,le).config.onMutate&&await d(this,le).config.onMutate(t,this,r);let a=await this.options.onMutate?.(t,r);a!==this.state.context&&F(this,He,ft).call(this,{type:"pending",context:a,variables:t,isPaused:i})}let o=await d(this,Qt).start();return await d(this,le).config.onSuccess?.(o,t,this.state.context,this,r),await this.options.onSuccess?.(o,t,this.state.context,r),await d(this,le).config.onSettled?.(o,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(o,null,t,this.state.context,r),F(this,He,ft).call(this,{type:"success",data:o}),o}catch(o){try{await d(this,le).config.onError?.(o,t,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onError?.(o,t,this.state.context,r)}catch(a){Promise.reject(a)}try{await d(this,le).config.onSettled?.(void 0,o,this.state.variables,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onSettled?.(void 0,o,t,this.state.context,r)}catch(a){Promise.reject(a)}throw F(this,He,ft).call(this,{type:"error",error:o}),o}finally{d(this,le).runNext(this)}}},nr=new WeakMap,Le=new WeakMap,le=new WeakMap,Qt=new WeakMap,He=new WeakSet,ft=function(t){let n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),j.batch(()=>{d(this,Le).forEach(r=>{r.onMutationUpdate(t)}),d(this,le).notify({mutation:this,type:"updated",action:t})})},Qo);function ni(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var ze,Ne,rr,Uo,Ko=(Uo=class extends Ee{constructor(t={}){super();I(this,ze);I(this,Ne);I(this,rr);this.config=t,S(this,ze,new Set),S(this,Ne,new Map),S(this,rr,0)}build(t,n,r){let s=new Do({client:t,mutationCache:this,mutationId:++Vn(this,rr)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){d(this,ze).add(t);let n=Kr(t);if(typeof n=="string"){let r=d(this,Ne).get(n);r?r.push(t):d(this,Ne).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(d(this,ze).delete(t)){let n=Kr(t);if(typeof n=="string"){let r=d(this,Ne).get(n);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&d(this,Ne).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=Kr(t);if(typeof n=="string"){let s=d(this,Ne).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=Kr(t);return typeof n=="string"?d(this,Ne).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){j.batch(()=>{d(this,ze).forEach(t=>{this.notify({type:"removed",mutation:t})}),d(this,ze).clear(),d(this,Ne).clear()})}getAll(){return Array.from(d(this,ze))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>qr(n,r))}findAll(t={}){return this.getAll().filter(n=>qr(t,n))}notify(t){j.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){let t=this.getAll().filter(n=>n.state.isPaused);return j.batch(()=>Promise.all(t.map(n=>n.continue().catch(Z))))}},ze=new WeakMap,Ne=new WeakMap,rr=new WeakMap,Uo);function Kr(e){return e.options.scope?.id}var Je,pt,ve,Ye,Ze,Lr,ri,Lo,si=(Lo=class extends Ee{constructor(t,n){super();I(this,Ze);I(this,Je);I(this,pt);I(this,ve);I(this,Ye);S(this,Je,t),this.setOptions(n),this.bindMethods(),F(this,Ze,Lr).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let n=this.options;this.options=d(this,Je).defaultMutationOptions(t),en(this.options,n)||d(this,Je).getMutationCache().notify({type:"observerOptionsUpdated",mutation:d(this,ve),observer:this}),n?.mutationKey&&this.options.mutationKey&&Ue(n.mutationKey)!==Ue(this.options.mutationKey)?this.reset():d(this,ve)?.state.status==="pending"&&d(this,ve).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||d(this,ve)?.removeObserver(this)}onMutationUpdate(t){F(this,Ze,Lr).call(this),F(this,Ze,ri).call(this,t)}getCurrentResult(){return d(this,pt)}reset(){d(this,ve)?.removeObserver(this),S(this,ve,void 0),F(this,Ze,Lr).call(this),F(this,Ze,ri).call(this)}mutate(t,n){return S(this,Ye,n),d(this,ve)?.removeObserver(this),S(this,ve,d(this,Je).getMutationCache().build(d(this,Je),this.options)),d(this,ve).addObserver(this),d(this,ve).execute(t)}},Je=new WeakMap,pt=new WeakMap,ve=new WeakMap,Ye=new WeakMap,Ze=new WeakSet,Lr=function(){let t=d(this,ve)?.state??ni();S(this,pt,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},ri=function(t){j.batch(()=>{if(d(this,Ye)&&this.hasListeners()){let n=d(this,pt).variables,r=d(this,pt).context,s={client:d(this,Je),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{d(this,Ye).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{d(this,Ye).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{d(this,Ye).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{d(this,Ye).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(d(this,pt))})})},Lo);var je,Ho,jo=(Ho=class extends Ee{constructor(t={}){super();I(this,je);this.config=t,S(this,je,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??Gn(s,n),o=this.get(i);return o||(o=new Io({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(o)),o}add(t){d(this,je).has(t.queryHash)||(d(this,je).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=d(this,je).get(t.queryHash);n&&(t.destroy(),n===t&&d(this,je).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){j.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return d(this,je).get(t)}getAll(){return[...d(this,je).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Fr(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>Fr(t,r)):n}notify(t){j.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){j.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){j.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},je=new WeakMap,Ho);var X,mt,gt,pn,mn,ht,gn,hn,Bo,ii=(Bo=class{constructor(e={}){I(this,X);I(this,mt);I(this,gt);I(this,pn);I(this,mn);I(this,ht);I(this,gn);I(this,hn);S(this,X,e.queryCache||new jo),S(this,mt,e.mutationCache||new Ko),S(this,gt,e.defaultOptions||{}),S(this,pn,new Map),S(this,mn,new Map),S(this,ht,0)}mount(){Vn(this,ht)._++,d(this,ht)===1&&(S(this,gn,Xt.subscribe(async e=>{e&&(await this.resumePausedMutations(),d(this,X).onFocus())})),S(this,hn,on.subscribe(async e=>{e&&(await this.resumePausedMutations(),d(this,X).onOnline())})))}unmount(){var e,t;Vn(this,ht)._--,d(this,ht)===0&&((e=d(this,gn))==null||e.call(this),S(this,gn,void 0),(t=d(this,hn))==null||t.call(this),S(this,hn,void 0))}isFetching(e){return d(this,X).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return d(this,mt).findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return d(this,X).get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=d(this,X).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(qe(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return d(this,X).findAll(e).map(({queryKey:t,state:n})=>{let r=n.data;return[t,r]})}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=d(this,X).get(r.queryHash)?.state.data,o=yo(t,i);if(o!==void 0)return d(this,X).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return j.batch(()=>d(this,X).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return d(this,X).get(t.queryHash)?.state}removeQueries(e){let t=d(this,X);j.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=d(this,X);return j.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=j.batch(()=>d(this,X).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(Z).catch(Z)}invalidateQueries(e,t={}){return j.batch(()=>(d(this,X).findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=j.batch(()=>d(this,X).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(Z)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Z)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=d(this,X).build(this,t);return n.isStaleByTime(qe(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Z).catch(Z)}fetchInfiniteQuery(e){return e.behavior=fn(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Z).catch(Z)}ensureInfiniteQueryData(e){return e.behavior=fn(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return on.isOnline()?d(this,mt).resumePausedMutations():Promise.resolve()}getQueryCache(){return d(this,X)}getMutationCache(){return d(this,mt)}getDefaultOptions(){return d(this,gt)}setDefaultOptions(e){S(this,gt,e)}setQueryDefaults(e,t){d(this,pn).set(Ue(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...d(this,pn).values()],n={};return t.forEach(r=>{Tt(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){d(this,mn).set(Ue(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...d(this,mn).values()],n={};return t.forEach(r=>{Tt(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...d(this,gt).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Gn(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===tn&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...d(this,gt).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){d(this,X).clear(),d(this,mt).clear()}},X=new WeakMap,mt=new WeakMap,gt=new WeakMap,pn=new WeakMap,mn=new WeakMap,ht=new WeakMap,gn=new WeakMap,hn=new WeakMap,Bo);var yn=Y(ue(),1),Vo=Y(Hr(),1),oi=yn.createContext(void 0),L=e=>{let t=yn.useContext(oi);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},sr=({client:e,children:t})=>(yn.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,Vo.jsx)(oi.Provider,{value:e,children:t}));var jr=Y(ue(),1),Wo=jr.createContext(!1),Go=()=>jr.useContext(Wo),Nm=Wo.Provider;var ir=Y(ue(),1),Yl=Y(Hr(),1);function Zl(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Xl=ir.createContext(Zl()),zo=()=>ir.useContext(Xl);var Jo=Y(ue(),1);var Yo=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?nn(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Zo=e=>{Jo.useEffect(()=>{e.clearReset()},[e])},Xo=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||nn(n,[e.error,r]));var ea=e=>{if(e.suspense){let n=s=>s==="static"?s:Math.max(s??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...s)=>n(r(...s)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},ta=(e,t)=>e.isLoading&&e.isFetching&&!t,na=(e,t)=>e?.suspense&&t.isPending,ai=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var yt=Y(ue(),1);function Br(e,t,n){let r=Go(),s=zo(),i=L(n),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let a=i.getQueryCache().get(o.queryHash);o._optimisticResults=r?"isRestoring":"optimistic",ea(o),Yo(o,s,a),Zo(s);let c=!i.getQueryCache().get(o.queryHash),[u]=yt.useState(()=>new t(i,o)),l=u.getOptimisticResult(o),f=!r&&e.subscribed!==!1;if(yt.useSyncExternalStore(yt.useCallback(h=>{let p=f?u.subscribe(j.batchCalls(h)):Z;return u.updateResult(),p},[u,f]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),yt.useEffect(()=>{u.setOptions(o)},[o,u]),na(o,l))throw ai(o,u,s);if(Xo({result:l,errorResetBoundary:s,throwOnError:o.throwOnError,query:a,suspense:o.suspense}))throw l.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(o,l),o.experimental_prefetchInRender&&!Ke.isServer()&&ta(l,r)&&(c?ai(o,u,s):a?.promise)?.catch(Z).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?l:u.trackResult(l)}function B(e,t){return Br(e,tr,t)}var Xe=Y(ue(),1);function ne(e,t){let n=L(t),[r]=Xe.useState(()=>new si(n,e));Xe.useEffect(()=>{r.setOptions(e)},[r,e]);let s=Xe.useSyncExternalStore(Xe.useCallback(o=>r.subscribe(j.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=Xe.useCallback((o,a)=>{r.mutate(o,a).catch(Z)},[r]);if(s.error&&nn(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function or(e,t){return Br(e,ti,t)}var ia=Y(sa(),1),_n=typeof window<"u"&&window.__FSAOS_CONFIG__||{},Dt=Array.isArray(_n.sources)?_n.sources:[],et=_n.hostSession===!0,ed=_n.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",td=_n.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",Te=_n.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",V=(0,ia.createClient)(ed,td,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var ar=null,$r=0,oa,di,Vr=!1;oa=new Promise(e=>{di=e});V.auth.onAuthStateChange((e,t)=>{t?.access_token?(ar=t.access_token,$r=t.expires_at??Math.floor(Date.now()/1e3)+3600):(ar=null,$r=0),Vr||(Vr=!0,di())});setTimeout(()=>{Vr||(Vr=!0,di())},5e3);function aa(e,t){ar=e,$r=t??Math.floor(Date.now()/1e3)+3600}function fi(){ar=null,$r=0}async function tt(){let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{};if(et)return null;if(e.embedToken){if(typeof e.embedToken=="function")try{return await e.embedToken()??null}catch{return null}return e.embedToken}return await oa,ar}var Sn=null,xn=null,ca=0,ci=new Set,pi,cr,Rn=!1;pi=new Promise(e=>{cr=e});function mi(){ca++,ci.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function Pn(e){let t=typeof e=="string"?e:e.path,n=Sn!==t||xn?.id!==(typeof e=="string"?void 0:e.id);Sn=t,xn=typeof e=="string"?null:e,typeof e!="string"&&!Ut.some(r=>r.id===e.id)&&(Ut=[...Ut,e],_i()),Rn||(Rn=!0,cr()),n&&mi()}function _t(){return Sn}function de(){return xn}function gi(){return ca}function hi(e){return ci.add(e),()=>{ci.delete(e)}}function ur(){return pi}function yi(){return Rn}var Wr=null;function Kt(e,t={}){if(Wr){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}Wr=e,t.activate!==!1&&Pn(e)}function me(){return Wr}var Ut=[],ui=new Set,ua=0;function _i(){ua++,ui.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function Ae(){return Ut}function lr(){return ua}function Gr(e){return ui.add(e),()=>{ui.delete(e)}}function la(e,t){let n=JSON.stringify(Ut)!==JSON.stringify(e),r=Sn!==t.path||xn?.id!==t.id;Ut=e,Sn=t.path,xn=t,Rn||(Rn=!0,cr()),n&&_i(),r&&mi()}var bn=null,vn=null,wn=0,li=new Set,da=0;function fa(){da++,li.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Session listener error:",t)}})}function ae(){return wn}function vi(){return da}function pa(e){return li.add(e),()=>{li.delete(e)}}async function nt(){if(bn)return bn;if(vn)return vn;let e=wn;return vn=(async()=>{let t=Lt(),n=await tt();if(e!==wn)throw new Error("Session changed during initialization");let r={};n&&(r.Authorization=`Bearer ${n}`);let s=await fetch(`${Te}/d/${t}/init`,{method:"GET",headers:r});if(!s.ok)throw new Error(`Session init failed: ${s.status} ${s.statusText}`);let i=await s.json();if(e!==wn)throw new Error("Session changed during initialization");let o=i.entry||i;return bn={scope_id:o.scope_id,scope_path:o.scope_path,instance_path:o.instance_path||"/root",fractal_id:o.fractal_id||null,instance_name:o.instance_name||null,display_name:o.scope_display_name||o.display_name||null,principal_id:o.principal_id||null},fa(),bn})().catch(t=>{throw e===wn&&(vn=null),t}),vn}function vt(){return bn}function bi(){wn++,bn=null,vn=null,Sn=null,xn=null,Wr=null,Ut=[],fa()}var ma=[];function se(e){ma.push(e)}function Cn(){bi(),fi(),cr(),Rn=!1,pi=new Promise(e=>{cr=e}),mi(),_i();for(let e of ma)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function Lt(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var ga=Pn,W=_t,ee=gi,xe=hi,ha=ur,zr=yi;var jt="host-session",nd=5e3;function wi(e){return typeof e=="object"&&e!==null&&e.fsaos===jt&&typeof e.kind=="string"}var Ht=class extends Error{constructor(){super(...arguments);z(this,"name","HostSessionUnavailableError")}},Jr=null,rd=0,Yr=new Map;function ya(){return Jr||(Jr=new Promise((e,t)=>{if(!et){t(new Ht("This page was not started with hostSession."));return}if(typeof window>"u"||!window.parent||window.parent===window){t(new Ht("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 Ht("The window around this page did not sign it in. Open it from the app that owns it.")))},nd);function i(o){if(o.source!==n||!wi(o.data))return;let a=o.data;if(r===null){if(a.kind!=="welcome")return;r=o.origin,clearTimeout(s),a.anchor&&Pn(a.anchor),e({host:n,origin:r,item:a.item??null});return}if(o.origin!==r||a.kind!=="result")return;let c=Yr.get(a.id);c&&(Yr.delete(a.id),c.resolve(a.ok?{ok:!0,response:a.response}:{ok:!1,error:a.error}))}window.addEventListener("message",i),n.postMessage({fsaos:jt,kind:"hello"},"*")}),Jr)}async function _a(){let{item:e}=await ya();return{item:e}}async function va(e,t,n){if(n?.aborted)throw new DOMException("Read cancelled","AbortError");let{host:r,origin:s}=await ya();if(n?.aborted)throw new DOMException("Read cancelled","AbortError");let i=JSON.parse(JSON.stringify(t??{}));return new Promise((o,a)=>{let c=`${Date.now().toString(36)}-${(++rd).toString(36)}`,u=()=>{Yr.delete(c),a(new DOMException("Read cancelled","AbortError"))};Yr.set(c,{resolve:l=>{n?.removeEventListener("abort",u),o(l)}}),n?.addEventListener("abort",u,{once:!0}),r.postMessage({fsaos:jt,kind:"call",id:c,method:e,params:i},s)})}var Si=0,ba=!1,wa=0;function xi(e){if(typeof e!="string")return;let t=Date.parse(e);Number.isNaN(t)||(Si=t-Date.now(),ba=!0,wa=Date.now())}function Zr(){return Date.now()+Si}function Sa(){return ba}function xa(){return Si}function Ra(){return wa}function Pa(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Zr()>=t}function Ca(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Math.max(0,t-Zr())}var En,ke=new Map,Bt=[],Ri=0,Pi={foreground:0,normal:1,background:2},Xr=()=>performance.now(),Ci=()=>new DOMException("Read cancelled","AbortError");function Ia(e={}){En={concurrency:Math.max(1,Math.min(16,Math.floor(e.concurrency??6))),timeoutMs:Math.max(1e3,e.timeoutMs??15e3),onTiming:e.onTiming},ts()}function Ta(){for(let e of ke.values()){e.controller.abort();for(let t of e.consumers)t.detach(),t.reject(Ci());e.consumers.clear(),e.timer&&clearTimeout(e.timer)}ke.clear(),Bt.length=0}function Aa(e,t){return e==="query"?!("materialize"in t):["read","list","search","resolve","resolve-items","get-channel-messages","list-memberships"].includes(e)}function es(e){return Array.isArray(e)?`[${e.map(es).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)}:${es(n)}`).join(",")}}`:JSON.stringify(e)}function ka(e,t,n,r){if(n.signal?.aborted)return Promise.reject(Ci());if(!En)return r(n.signal);let s=ke.get(e);if(s)Pi[n.priority??"normal"]<Pi[s.priority]&&(s.priority=n.priority??"normal");else{s={key:e,method:t,priority:n.priority??"normal",queuedAt:Xr(),controller:new AbortController,consumers:new Set,run:r},ke.set(e,s),Bt.push(s);let a=s;s.timer=setTimeout(()=>{a.controller.abort();let c=new Error("The read timed out. Please retry.");c.name="TimeoutError";for(let u of a.consumers)u.detach(),u.reject(c);a.consumers.clear(),ke.get(a.key)===a&&ke.delete(a.key),Ea(a)},En.timeoutMs)}let i=s,o=new Promise((a,c)=>{let u=()=>{l.detach(),i.consumers.delete(l),c(Ci()),i.consumers.size||(i.controller.abort(),ke.get(i.key)===i&&ke.delete(i.key),Ea(i))},l={resolve:f=>a(structuredClone(f)),reject:c,detach:()=>n.signal?.removeEventListener("abort",u)};i.consumers.add(l),n.signal?.addEventListener("abort",u,{once:!0})});return ts(),o}function Ea(e){let t=Bt.indexOf(e);t>=0&&(Bt.splice(t,1),ke.get(e.key)===e&&ke.delete(e.key),e.timer&&clearTimeout(e.timer)),ts()}function ts(){if(En)for(;Ri<En.concurrency&&Bt.length;){let e=r=>Pi[r.priority]-Math.floor((Xr()-r.queuedAt)/2e3);Bt.sort((r,s)=>e(r)-e(s)||r.queuedAt-s.queuedAt);let t=Bt.shift();if(!t.consumers.size)continue;Ri++,t.startedAt=Xr();let n="success";Promise.resolve().then(()=>t.run(t.controller.signal)).then(r=>{for(let s of t.consumers)s.detach(),s.resolve(r)},r=>{n=t.controller.signal.aborted?"aborted":"error";for(let s of t.consumers)s.detach(),s.reject(r)}).finally(()=>{t.timer&&clearTimeout(t.timer),t.consumers.clear(),ke.get(t.key)===t&&ke.delete(t.key),Ri--;try{En?.onTiming?.({method:t.method,priority:t.priority,queueMs:Math.round(t.startedAt-t.queuedAt),requestMs:Math.round(Xr()-t.startedAt),outcome:n})}catch{}ts()})}}se(Ta);var sd=new Set(["list-memberships","init"]),ge=class extends Error{constructor(n){let r=typeof n.payload?.error=="string"?n.payload.error.trim():"",s=typeof n.payload?.message=="string"?n.payload.message.trim():"",i=n.responseBody.trim()||`Gateway HTTP error: ${n.status} ${n.statusText}`.trim(),o=r&&s?`${r}: ${s}`:s||r||i;super(o);z(this,"name","GatewayRequestError");z(this,"method");z(this,"status");z(this,"statusText");z(this,"payload");z(this,"responseBody");this.method=n.method,this.status=n.status,this.statusText=n.statusText,this.payload=n.payload,this.responseBody=n.responseBody}};async function x(e,t={},n={}){if(et)return id(e,t,n);let r=ae(),s=_t(),i=Lt(),o=`${Te}/d/${i}`,a={"Content-Type":"application/json"},c=await Ma(tt(),n.signal);if(r!==ae())throw new Error("Session changed before gateway request");if(c&&(a.Authorization=`Bearer ${c}`),!sd.has(e)&&!t._scope_path&&await Ma(ur(),n.signal),r!==ae())throw new Error("Session changed before gateway request");let u={...t},l=vt();!u.domain_scope_id&&l?.scope_id&&(u.domain_scope_id=l.scope_id);let f=s??_t();!u._scope_path&&f&&(u._scope_path=f);let h=async p=>{if(r!==ae())throw new Error("Session changed before queued gateway request");let m=await fetch(o,{method:"POST",signal:p,headers:a,body:JSON.stringify({method:e,params:u})}),y=await m.text();if(r!==ae())throw new Error("Session changed during gateway request");let g=null;if(y)try{g=JSON.parse(y)}catch{}if(!m.ok||!g)throw new ge({method:e,status:m.status,statusText:m.statusText,payload:g,responseBody:y});if(g.success===!1){let v=g.error||"",_=g.denied_by||g.error_type||"";throw _==="rule"||_==="access"||_==="entitlement"||v==="RULE_DENIED"||v==="ACCESS_DENIED"||v==="PERMISSION_DENIED"||v==="ENTITLEMENT_REQUIRED"?new Fe(g):new ge({method:e,status:m.status,statusText:m.statusText,payload:g,responseBody:y})}return g&&g.server_now!==void 0&&xi(g.server_now),g};return Aa(e,u)?ka(es([r,i,c,e,u]),e,n,h):h(n.signal)}async function id(e,t,n){let r=await va(e,t,n.signal);if(r.ok){let o=r.response?.server_now;return o!==void 0&&xi(o),r.response}let s=r.error;if(s.kind==="denied")throw new Fe(s.payload);if(s.kind==="gateway")throw new ge({method:s.method,status:s.status,statusText:s.statusText,payload:s.payload,responseBody:s.responseBody});let i=new Error(s.message);throw i.name=s.name,i}function Ma(e,t){return t?t.aborted?Promise.reject(new DOMException("Read cancelled","AbortError")):new Promise((n,r)=>{let s=()=>r(new DOMException("Read cancelled","AbortError"));t.addEventListener("abort",s,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",s))}):e}var b=Y(ue(),1),Gd=Y(Fa(),1),zd=Y(Hr(),1);var qa=new WeakMap;function be(e,t,n={}){let r=n.exact===!0,s=()=>e.invalidateQueries({queryKey:t,exact:r},{cancelRefetch:!1}),i=e.getQueryCache().findAll({queryKey:t,exact:r,fetchStatus:"fetching"}).flatMap(f=>f.promise?[f.promise]:[]);if(i.length===0)return s();let o=`${r?"=":"^"}${JSON.stringify(t)}`,a=qa.get(e);a||(a=new Map,qa.set(e,a));let c=a.get(o);if(c)return c;let u=a,l=Promise.allSettled(i).then(()=>(u.delete(o),s()));return u.set(o,l),l}function he(e,t){return typeof e=="string"&&(e===t||e.startsWith(`${t}/`))}var ns=new WeakMap,Na=e=>e.meta?.arrangementRealtime===!0;function rt(e,t){let n=e.getQueryCache().find({queryKey:t,exact:!0});if(!n)return;let r=ns.get(e);r||(r=new Map,ns.set(e,r));let s=r.get(n.queryHash);s&&clearTimeout(s),r.set(n.queryHash,setTimeout(()=>{r.delete(n.queryHash),e.getQueryCache().get(n.queryHash)===n&&be(e,t,{exact:!0})},250))}function Qa(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){if(!Na(n))continue;let r=n.state.data;if(n.meta?.personalSections===!0){(r?.item_path&&[t.path,t.old_path].some(i=>typeof i=="string"&&(i===r.item_path||i.startsWith(r.item_path+"/")))||r?.sections?.some(i=>i.entries?.some(o=>o.target?.id===t.item_id))||!r?.item_id&&t.item_type==="item_arrangement"&&t.name==="sidebar-sections")&&rt(e,n.queryKey);continue}if(!r?.item_id)continue;let s=(i,o)=>!!(i&&t.item_id===i||o&&(t.path===o||t.old_path===o));(s(r.item_id,r.item_path)||t.parent_id===r.item_id||t.old_parent_id===r.item_id||[t.path,t.old_path].some(i=>typeof i=="string"&&i.slice(0,i.lastIndexOf("/"))===r.item_path)||r.resolved_children?.some(i=>s(i.id,i.symlink_path||i.path)||i.target&&s(i.target.id,i.target.path)))&&rt(e,n.queryKey)}}function Da(e){for(let t of e.getQueryCache().getAll())Na(t)&&t.state.data!==void 0&&rt(e,t.queryKey)}function Ua(e){ns.get(e)?.forEach(clearTimeout),ns.delete(e)}var st=null;se(()=>{st&&(st.cancelQueries({queryKey:["vfs"]}),st.removeQueries({queryKey:["vfs"]}))});function Ka(e){if(st&&st!==e)throw new Error("[fsaos-gateway-sdk] setQueryClient() called after a QueryClient was already in use. Inject the host client before rendering or starting realtime subscriptions.");st=e}function N(){return st||(st=new ii({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),st}var La=new Proxy({},{get(e,t,n){let r=N(),s=r[t];return typeof s=="function"?s.bind(r):s}});var rs=new WeakMap;function Ei(e){return e.meta?.infiniteItemsRealtime?.filter}function od(e,t){return e.state.data?.pages?.some(r=>r.items?.some(s=>t.item_id&&s.id===t.item_id||t.path&&s.path===t.path||t.old_path&&s.path===t.old_path))??!1}function ad(e){if(e.type)return new Set([e.type]);if(!e.any_of?.length)return null;let t=new Set;for(let n of e.any_of){if(!n.item_type)return null;t.add(n.item_type)}return t}function cd(e,t,n){if(od(e,n))return!0;if(t.spaceIds!==void 0&&(!t.spaceIds.length||n.space_item_id!==void 0&&!t.spaceIds.includes(n.space_item_id)&&!t.spaceIds.includes(n.old_space_item_id)))return!1;let r=t.scope,s=typeof r=="string"&&r!=="__unscoped__",i=typeof n.path=="string"||typeof n.old_path=="string";if(s&&i&&!he(n.path,r)&&!he(n.old_path,r))return!1;if(n.item_type==="symlink"&&s&&i)return!0;let o=ad(t);return n.item_type&&o&&!o.has(n.item_type)||t.parent_id&&n.parent_id!==void 0&&n.parent_id!==t.parent_id&&n.old_parent_id!==t.parent_id?!1:i||!!(t.parent_id&&n.parent_id===t.parent_id)}function Ha(e,t){let n=rs.get(e);n||(n=new Map,rs.set(e,n));let r=n.get(t.queryHash);r&&clearTimeout(r),n.set(t.queryHash,setTimeout(()=>{n.delete(t.queryHash),!(e.getQueryCache().get(t.queryHash)!==t||!Ei(t))&&be(e,t.queryKey,{exact:!0})},500))}function ja(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){let r=Ei(n);r&&cd(n,r,t)&&Ha(e,n)}}function Ba(e){for(let t of e.getQueryCache().getAll())Ei(t)&&t.state.data!==void 0&&Ha(e,t)}function $a(e){rs.get(e)?.forEach(clearTimeout),rs.delete(e)}var ss=class extends Error{constructor(){super("The server did not confirm the selected-Space listing contract")}};function Va(e,t){if(!Array.isArray(t)||t.some(n=>typeof n!="string")||JSON.stringify([...new Set(t)].sort())!==JSON.stringify(e))throw new ss}function bt(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 In(e){return e instanceof ss||e instanceof Fe||e instanceof ge&&(e.payload?.error==="SPACE_SELECTION_UNAVAILABLE"||e.payload?.error==="QUERY_PARAMS_INVALID"||e.status===401||e.status===403)}function ce(){return W()??"__unscoped__"}var E={all:()=>["vfs",ce()],item:e=>["vfs",ce(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",ce(),"children",e],allChildren:()=>["vfs",ce(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",ce(),"search",e,...t??[]],items:(e,t)=>["vfs",ce(),"items",e,JSON.stringify(bt(t??{}))],allItems:()=>["vfs",ce(),"items"],tree:(e,t)=>["vfs",ce(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",ce(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",ce(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",ce(),"get-activity-feed",e,t,n],itemVersions:(e,t,n,r)=>["vfs","item-versions",e,t,n,r],itemHistory:(e,t,n)=>["vfs","item-history",e,t,n],channelMessages:(e,t)=>["vfs",ce(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",ce(),"channel-messages"],channels:e=>["vfs",ce(),"channels",e??"all"],allChannels:()=>["vfs",ce(),"channels"],notifications:(e,t)=>["vfs",ce(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",ce(),"notifications"],unreadCounts:()=>["vfs",ce(),"unread-counts"],memberships:e=>["memberships",e]};var ud=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function J(...e){ud&&console.log("[WS]",...e)}var Q=null,Tn=null,kn=null,dr=0,ld=3e4,Wa=1e4,On=!1,Ga=!1,Xa=3e4,dd=Xa*2+5e3,is=0,os=null,za=!1;function fd(){pr(),is=Date.now(),os=setInterval(()=>{if(Q&&Q.readyState===WebSocket.OPEN&&Date.now()-is>dd){J("ping: no inbound traffic for",Date.now()-is,"ms \u2014 closing half-open socket");try{Q.close(4e3,"liveness timeout")}catch{}return}ot({type:"ping"})},Xa)}function pr(){os&&(clearInterval(os),os=null)}function pd(){typeof document>"u"||(document.hidden?pr():fr()&&(J("Tab visible, reconnecting..."),$t()))}function md(){za||typeof document>"u"||(document.addEventListener("visibilitychange",pd),za=!0)}var Re={};function Ti(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return!n||!r?n===r:r===n||r.startsWith(`${n}/`)}var Mn=[],it=new Map,An=new Map,Me=new Map;function gd(e){let t=An.get(e);return t?Array.from(new Set(Array.from(t.values()).flatMap(n=>n.event_types))).sort():[]}function Ja(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):!1}function Ya(e){let t=gd(e);if(t.length===0)return it.delete(e),null;let n={scope_id:e,event_types:t};return it.set(e,n),n}var Be=new Map,wt=new Map,Ii="disconnected",as=[];function cs(e){if(Ii!==e){Ii=e;for(let t of[...as])try{t(e)}catch{}}}function hd(e){Be.set(e,"ready");let t=wt.get(e);if(t){wt.delete(e);for(let n of t)n()}}function yd(){for(let e of Be.keys())Be.set(e,"disconnected")}function Ai(e,t){Be.set(e,"pending"),ot({type:"subscribe_path",path:e,event_types:t})}function _d(){return Object.keys(Re).some(t=>Re[t]&&Re[t].length>0)||Mn.length>0}function fr(){return it.size>0||Me.size>0}async function $t(){if(et){J("ensureConnection: the host holds the session, no realtime connection");return}if(!fr()){J("ensureConnection: no active subscriptions, skipping");return}if(Q&&Q.readyState===WebSocket.OPEN){J("ensureConnection: already open");return}if(Tn)return J("ensureConnection: connection already in flight, waiting..."),Tn;if(Q){J("ensureConnection: killing stale WS in state",Q.readyState);try{Q.close()}catch{}Q=null}return On=!1,Tn=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=Te,n=await tt();if(!n){J("ensureConnection: no token available, will retry"),Za();return}let r=t.startsWith("https")?"wss":"ws",s=t.replace(/^https?:\/\//,""),i=`${r}://${s}/ws`;i+=`?token=${encodeURIComponent(n)}`,J("ensureConnection: opening WS to",i.substring(0,50)+"..."),cs("connecting"),Q=new WebSocket(i);let o=Q;await new Promise((a,c)=>{if(!Q)return c(new Error("WebSocket not created"));let u=setTimeout(()=>{if(Q===o){if(J("ensureConnection: TIMEOUT after",Wa,"ms"),Q&&Q.readyState!==WebSocket.OPEN){try{Q.close()}catch{}Q=null}c(new Error("WebSocket connection timeout"))}},Wa);o.onopen=()=>{if(Q!==o)return;clearTimeout(u),J("ensureConnection: CONNECTED");let l=Ga;Ga=!0,dr=0,cs("connected"),vd(l),(typeof document>"u"||!document.hidden)&&fd(),md(),a()},o.onmessage=l=>{Q===o&&bd(l.data)},o.onerror=()=>{J("ensureConnection: WS error event")},o.onclose=l=>{clearTimeout(u),Q===o&&(J("ensureConnection: WS closed, code:",l.code,"reason:",l.reason),Q=null,pr(),yd(),cs("disconnected"),!On&&fr()&&Za(),c(new Error(`WebSocket closed: ${l.code}`)))}})}catch(e){J("ensureConnection: failed -",e?.message||e)}finally{Tn=null}})(),Tn}function Za(){if(kn||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,dr)+Math.random()*1e3,ld);dr++,J("scheduleReconnect: attempt",dr,"in",Math.round(e),"ms"),kn=setTimeout(()=>{kn=null,fr()&&$t()},e)}function vd(e=!1){for(let t of it.values())J("resubscribeAll: scope",t.scope_id),ot({type:"subscribe",scope_id:t.scope_id,event_types:t.event_types});for(let t of Me.values())J("resubscribeAll: path",t.path),Ai(t.path,t.event_types);e&&ec("reconnect")}function ec(e){try{let t=N();Ba(t),Da(t);for(let n of Me.values())t.invalidateQueries({queryKey:E.item(n.path)}),t.invalidateQueries({queryKey:E.children(n.path)});t.invalidateQueries({queryKey:E.allChannelMessages()}),J("catchUpAfterGap:",e,"- invalidated",Me.size,"paths and the transcripts on screen")}catch(t){J("catchUpAfterGap: cache invalidation skipped",t)}}function ot(e){Q&&Q.readyState===WebSocket.OPEN&&Q.send(JSON.stringify(e))}function bd(e){is=Date.now();try{let t=JSON.parse(e);if(t.type==="subscribed_path"){typeof t.path=="string"&&hd(t.path);return}if(t.type==="subscribed"||t.type==="unsubscribed"||t.type==="unsubscribed_path"||t.type==="pong")return;if(t.type==="error"){console.warn("[WS] Server error:",t.message);return}if(t.type==="resync"){ec(typeof t.reason=="string"?t.reason:"resync");return}if(t.type==="event"||t.event_type){let n=t.event_type||"message",r=t.data||t;if(n==="vfs_change"&&(ja(N(),r),Qa(N(),r)),typeof r.path=="string")for(let[s,i]of Object.entries(Re))s!=="*"&&Ti(s,r.path)&&i.forEach(o=>o(r));Re["*"]&&Re["*"].forEach(s=>s(r));for(let s of Mn)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function ki(){!_d()&&it.size===0&&Me.size===0&&Q&&(On=!0,pr(),Q.close(),Q=null,On=!1)}function us(e,t){return Re[e]||(Re[e]=[]),Re[e].push(t),Me.has(e)||(Me.set(e,{path:e,event_types:["token_stream"]}),Q&&Q.readyState===WebSocket.OPEN?Ai(e,["token_stream"]):Be.set(e,"pending")),$t(),()=>{let n=Re[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete Re[e],Me.delete(e),Be.delete(e),wt.delete(e),ot({type:"unsubscribe_path",path:e}))}ki()}}function ie(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return Mn.push(...s),fr()&&$t(),()=>{for(let i of s){let o=Mn.indexOf(i);o!==-1&&Mn.splice(o,1)}ki()}}function Fn(e,t=["vfs_change","ccm_change"]){let n=Symbol(e),r=Array.from(new Set(t)).sort();if(r.length===0)return()=>{};let s=An.get(e)??new Map,i=it.get(e)?.event_types;s.set(n,{event_types:r}),An.set(e,s);let o=Ya(e);if(!o)return()=>{};J("subscribeToScope:",e,o.event_types),Q&&Q.readyState===WebSocket.OPEN&&!Ja(i,o.event_types)&&ot({type:"subscribe",scope_id:e,event_types:o.event_types}),$t();let a=!0;return()=>{if(!a)return;a=!1;let c=An.get(e);if(!c?.delete(n))return;let u=it.get(e)?.event_types;if(c.size===0)An.delete(e),it.delete(e),ot({type:"unsubscribe",scope_id:e});else{let l=Ya(e);l&&Q&&Q.readyState===WebSocket.OPEN&&!Ja(u,l.event_types)&&ot({type:"subscribe",scope_id:e,event_types:l.event_types})}ki()}}function tc(e,t,n={}){ot({type:"emit",scope_id:e,event_type:t,payload:n})}function Mi(){J("disconnectSSE: tearing down"),$a(N()),Ua(N()),On=!0,pr(),Q&&(Q.close(),Q=null),kn&&(clearTimeout(kn),kn=null),Tn=null,On=!1,dr=0;for(let e of Object.keys(Re))delete Re[e];Mn.length=0,it.clear(),An.clear(),Me.clear(),Be.clear(),wt.clear(),cs("disconnected")}function nc(){ot({type:"ping"})}function rc(e){return Me.has(e)?Be.get(e)??"pending":"unsubscribed"}function sc(e,t=5e3){return!Me.has(e)||et?Promise.resolve(!1):Be.get(e)==="ready"&&Q&&Q.readyState===WebSocket.OPEN?Promise.resolve(!0):($t(),new Promise(n=>{let r=!1,s=wt.get(e)??[],i=()=>{r||(r=!0,clearTimeout(o),n(!0))};s.push(i),wt.set(e,s);let o=setTimeout(()=>{if(r)return;r=!0;let a=wt.get(e);if(a){let c=a.indexOf(i);c!==-1&&a.splice(c,1),a.length===0&&wt.delete(e)}n(!1)},t)}))}function ic(e){let t=Me.get(e);if(!t){J("resubscribePath: no active subscription for",e);return}Q&&Q.readyState===WebSocket.OPEN?(J("resubscribePath: re-sending frame for",e),Ai(t.path,t.event_types)):(Be.set(e,"pending"),$t())}function ls(e){as.push(e);try{e(Ii)}catch{}return()=>{let t=as.indexOf(e);t!==-1&&as.splice(t,1)}}se(Mi);function oc(){return new Date().toISOString()}function ac(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function Oe(e){let t=e.path||e.item_path||"",n=t.split("/");n.pop();let r=n.join("/"),s=e.type_data||{};return s.allowed_parent_types&&!s.accepts&&(s.accepts=s.allowed_parent_types),delete s.allowed_parent_types,{id:e.id||e.item_id||"",name:e.name||e.item_name||"",item_type:e.item_type||"unknown",path:t,parent_path:r,is_active:e.is_active!==!1,has_children:e.has_children??!1,created_at:e.created_at||oc(),updated_at:e.updated_at||oc(),visibility:e.visibility,type_data:s,scope_item_id:e.scope_item_id,fractal_id:e.fractal_id,parent_instance_id:e.parent_instance_id,owner_principal_id:e.owner_principal_id,created_by_principal_id:e.created_by_principal_id,parent_id:e.parent_id,space_item_id:e.space_item_id,account_item_id:e.account_item_id}}function gr(e){return(e.content?.items||e.items||[]).map(Oe)}async function hr(e){try{let t=await x("read",{id:e});if(t.item_name||t.item_path){let r=Oe(t);return r.path&&N().setQueryData(E.item(r.path),r),r}let n=t.item;if(n){let r=Oe(n);return r.path&&N().setQueryData(E.item(r.path),r),r}return null}catch{return null}}async function yr(e){try{let t=await x("read",{path:e});if(t.item_name||t.item_path)return Oe(t);let n=t.item;return n?Oe(n):null}catch{return null}}async function _r(e){try{let t=await x("list",{path:e,limit:200}),n=gr(t);for(let r of n)N().setQueryData(E.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function cc(e,t){let{items:n}=await Vt({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 fs(e,t,n){try{let r=await x("list",{path:e,limit:t,offset:n}),s=gr(r);for(let i of s)N().setQueryData(E.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 ps(e){let n=await x("types-list",e?{scope_id:e}:{}),r=n.content?.items||n.items||[],s=new Map;for(let i of r){let o=i.name,a=i.type_data;!o||!a||s.set(o,{type_key:o,display_name:a.display_name||o,display_name_plural:a.display_name_plural||o+"s",icon:a.icon||"File",color:a.color||"gray",description:a.description||"",input_schema:a.input_schema||{},system_schema:a.system_schema||{},json_schema:a.input_schema||a.json_schema||{},default_data:a.default_data||{},field_defaults:a.field_defaults||{},renderer_config:a.renderer_config||{},is_system:a.is_system??!1,is_active:a.is_active??!0,is_container:a.is_container??!1,is_scope:a.is_scope??!1,render_mode:a.render_mode||"none",placement_mode:a.placement_mode,direct_parent_types:a.direct_parent_types,allowed_parent_types:a.allowed_parent_types,governed_create:a.governed_create,create_method:a.create_method,dedup:a.dedup,edges:a.edges,events:a.events})}return s}async function ms(e){try{let t=await x("edges",{item_id:e}),n=t.outgoing||[],r=t.incoming||[],s=[];for(let i of n)s.push({id:i.edge_id||ac(),source_item_id:e,target_item_id:i.target_id||"",edge_type:i.edge_type||"",weight:i.weight??1,context:i.context||{},is_active:!0,is_bidirectional:i.is_bidirectional});for(let i of r)s.push({id:i.edge_id||ac(),source_item_id:i.source_id||"",target_item_id:e,edge_type:i.edge_type||"",weight:i.weight??1,context:i.context||{},is_active:!0,is_bidirectional:i.is_bidirectional});return s}catch(t){return console.warn(`[gateway] Failed to fetch edges for ${e}:`,t),[]}}async function gs(e,t=1,n,r){try{let s={path:e,max_depth:t>0?t:999};n?.length&&(s.item_types=n),r&&(s.limit=r);let i=await x("tree",s),o=gr(i);for(let a of o)N().setQueryData(E.item(a.path),a);return o}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function hs(e,t=50,n=0){try{let r=await x("get-activity-feed",{scope_path:e,limit:t,offset:n});return r.content?.items||r.items||r.entries||[]}catch(r){return console.error(`[gateway] Failed to fetch recent activity for ${e}:`,r),[]}}async function vr(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;try{let i=await x("item-versions",{id:e,limit:n,offset:r,include_snapshots:s});return{versions:i.content?.items||i.versions||[],total:i.total??0}}catch(i){return console.error(`[gateway] Failed to fetch item versions for ${e}:`,i),{versions:[],total:0}}}async function ys(e,t=50,n=0){return vr(e,{limit:t,offset:n})}async function _s(e,t,n){try{let r={scope_id:e};t?.length&&(r.item_types=t),n&&(r.limit=n);let s=await x("member-focus",r),i=gr(s);for(let o of i)N().setQueryData(E.item(o.path),o);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${e}:`,r),[]}}async function br(e,t){let n={path:e};t?.mode&&(n.mode=t.mode),t?.strategy&&(n.strategy=t.strategy),t?.arguments&&(n.arguments=t.arguments);let s=await x("open",n);return{item_id:s.item_id,item_path:s.item_path,item_name:s.item_name,item_type:s.item_type,render:s.render,compatible_components:s.compatible_components??[],content:s.content,metadata:s.metadata,instructions:s.instructions}}function qn(e){return!!e&&(!!e.type||Array.isArray(e.any_of)&&e.any_of.length>0)}function wd(e){let t={};e.item_type&&(t.item_type=e.item_type);for(let[n,r]of Object.entries(e.fields??{}))t[`field.${n}`]=String(r);for(let[n,r]of Object.entries(e.field_in??{}))t[`field_in.${n}`]=r.map(String);return t}var Sd=["catalog","parent_only","internal"];function uc(e,t={}){if(!e||typeof e!="object")return null;let n=o=>typeof o=="string"||typeof o=="number"||typeof o=="boolean",r=o=>{let a={},c={};for(let[u,l]of Object.entries(o))u.startsWith("field.")&&u.length>6&&n(l)?a[u.slice(6)]=l:u.startsWith("field_in.")&&u.length>9&&Array.isArray(l)&&(c[u.slice(9)]=l.filter(n));return{fields:a,field_in:c}},s={};typeof e.type=="string"&&e.type&&(s.type=e.type),typeof e.sort_by=="string"&&(s.sort_by=e.sort_by),(e.sort_dir==="asc"||e.sort_dir==="desc")&&(s.sort_dir=e.sort_dir),typeof e.name=="string"&&e.name&&(s.name=e.name),typeof e.tag=="string"&&e.tag&&(s.tag=e.tag),typeof e.discovery=="string"&&Sd.includes(e.discovery)&&(s.discovery=e.discovery);let i=r(e);if(Object.keys(i.fields).length&&(s.fields=i.fields),Object.keys(i.field_in).length&&(s.field_in=i.field_in),Array.isArray(e.any_of)){let o=[];for(let a of e.any_of){if(!a||typeof a!="object"||Array.isArray(a))continue;let c=a,u={};typeof c.item_type=="string"&&c.item_type&&(u.item_type=c.item_type);let l=r(c);Object.keys(l.fields).length&&(u.fields=l.fields),Object.keys(l.field_in).length&&(u.field_in=l.field_in),Object.keys(u).length&&o.push(u)}o.length&&(s.any_of=o)}return qn(s)?{...s,...t}:null}async function Vt(e,t={}){if(e=bt(e),e.spaceIds?.length===0)return{items:[],total_hint:0};let n={};e.type&&(n.item_type=e.type),e.scope&&(n.scope_path=e.scope);let r={};if(e.spaceIds!==void 0&&(r.space_ids=e.spaceIds),e.name&&(r.name=e.name),e.tag&&(r.tag=e.tag),e.parent_id&&(r.parent_id=e.parent_id),e.sort_by&&(r.sort_by=e.sort_by),e.sort_dir&&(r.sort_dir=e.sort_dir),e.offset!=null&&(r.offset=e.offset),e.fields)for(let[s,i]of Object.entries(e.fields))r[`field.${s}`]=String(i);if(e.field_in)for(let[s,i]of Object.entries(e.field_in))r[`field_in.${s}`]=i.map(String);e.discovery&&(r.discovery=e.discovery),e.any_of?.length&&(r.any_of=e.any_of.map(wd)),Object.keys(r).length>0&&(n.filters=r),e.limit!=null&&(n.limit=e.limit);try{let s=await x("query",n,t);e.spaceIds!==void 0&&Va(e.spaceIds,s.selected_space_ids??s.content?.selected_space_ids);let i=gr(s);for(let o of i)N().setQueryData(E.item(o.path),o);return{items:i,total_hint:s.total??s.content?.total??i.length}}catch(s){if(t.signal?.aborted||s instanceof Error&&s.name==="AbortError"||(console.error(`[gateway] Failed to fetch items of type ${e.type??"(any_of)"}:`,s),t.throwOnError||e.spaceIds!==void 0))throw s;return{items:[],total_hint:0}}}function xd(e){if(!e||typeof e!="object")return;let t=e;if(t.version!==1||typeof t.work_id!="string"||!t.work_id)return;let n=r=>{let s=t[r];return typeof s=="string"&&s?s:void 0};return{version:1,workId:t.work_id,threadRootId:n("thread_root_id"),requestMessageId:n("request_message_id"),replyMessageId:n("reply_message_id"),replyMessagePath:n("reply_message_path"),todoListId:n("todo_list_id"),todoListPath:n("todo_list_path"),stepId:n("step_id"),stepPath:n("step_path"),runId:n("run_id"),parentRunId:n("parent_run_id"),toolCallId:n("tool_call_id"),traceId:n("trace_id")}}function lc(e){return e.filter(t=>t.item_type==="card").map(t=>{let n=t.type_data||{},r=n.payload||{};return{id:t.id||"",path:t.path||"",name:t.name||(t.path||"").split("/").pop()||"",createdAt:t.created_at||"",action:n.action||"created",targetId:n.target_id||void 0,targetPath:n.target_path||"",targetDisplayName:n.target_display_name||"",targetDescription:n.target_description||"",targetItemType:n.target_item_type||"",toolId:(t.name||"").startsWith("card-")?(t.name||"").substring(5):void 0,parentMessagePath:t.parent_message_path||void 0,visibility:n.visibility||"private",openWith:r.open_with||void 0,hostBundled:r.host_bundled===!0?!0:void 0,bundleExport:r.bundle_export||void 0,launchArguments:r.launch_arguments||void 0,requiresUserAttention:r.requires_user_attention===!0?!0:void 0,origin:xd(n.origin),presentationRole:r.presentation_role==="user-request"?"user-request":r.presentation_role==="output"?"output":void 0}}).sort((t,n)=>t.createdAt.localeCompare(n.createdAt))}function mr(e){return e.filter(t=>t.item_type==="message").map(t=>{let n=t.type_data||{},r="user";n.role==="assistant"?r="assistant":n.role==="system"&&(r="system");let s=n.metadata||{};return{id:t.id||"",path:t.path||"",content:n.message||n.content||"",created_at:t.created_at||"",role:r,status:typeof n.status=="string"?n.status:void 0,delivery_state:typeof n.delivery_state=="string"?n.delivery_state:void 0,cognition_event_id:typeof n.cognition_event_id=="string"?n.cognition_event_id:void 0,seq:n.seq||0,principal_id:n.principal_id,member_id:typeof n.member_id=="string"?n.member_id:void 0,reply_count:n.reply_count||0,member_count:n.member_count||0,parent_message_id:n.parent_message_id,intent_card:s.intent_card,metadata:Object.keys(s).length>0?s:void 0,thread_summary:Array.isArray(n.thread_summary)&&n.thread_summary.length>0?n.thread_summary:void 0}}).sort((t,n)=>t.seq-n.seq)}async function dc(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await x("get-channel-messages",n),i=s.messages||s.content?.items||s.items||[];return mr(i)}catch(n){throw console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),n}}async function vs(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await x("get-channel-messages",n),i=s.messages||[],o=mr(i),a=lc(i),c=new Map,u=[];for(let l of a)if(l.parentMessagePath){let f=c.get(l.parentMessagePath)||[];f.push(l),c.set(l.parentMessagePath,f)}else u.push(l);return{messages:o,activityMessages:mr(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 wr(e,t){try{let n={channel_path:e};t?.parentMessageId&&(n.parent_message_id=t.parentMessageId),t?.conversationsOnly&&(n.conversations_only=!0),t?.transcriptOnly&&(n.transcript_only=!0),t?.limit&&(n.limit=t.limit),t?.before_seq!=null&&(n.before_seq=t.before_seq),t?.after_seq!=null&&(n.after_seq=t.after_seq);let s=await x("get-channel-messages",n);if(t?.conversationsOnly&&s.conversations_only!==!0)throw new Error("This server does not support conversation history lists yet. Update the message reader.");if(t?.transcriptOnly&&s.transcript_only!==!0)throw new Error("This server does not support channel transcript pages yet. Update the message reader.");let i=s.messages||[],o=lc(i),a=new Map,c=[];for(let u of o)if(u.parentMessagePath){let l=a.get(u.parentMessagePath)||[];l.push(u),a.set(u.parentMessagePath,l)}else c.push(u);return{messages:mr(i),activityMessages:mr(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 ds(e){N().invalidateQueries({queryKey:E.children(e)})}function Oi(e){N().invalidateQueries({queryKey:E.item(e)})}function fc(e,t){Oi(e),ds(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&ds(r)}function pc(e){let t=e+"/";N().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function mc(){N().invalidateQueries({queryKey:E.all()})}function gc(e){N().invalidateQueries({queryKey:E.types(e)})}function hc(e,t){e?N().invalidateQueries({queryKey:E.channelMessages(e,t)}):N().invalidateQueries({queryKey:E.allChannelMessages()})}function yc(e,t){e&&t?N().invalidateQueries({queryKey:E.openEnvelope(e,t)}):e?N().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):N().invalidateQueries({queryKey:E.allOpenEnvelopes()})}function $e(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}async function bs(){return((await x("list-memberships",{})).memberships||[]).map(n=>({accountId:n.account_id,path:n.account_path,name:n.account_name,role:n.role||"member",typeData:n.account_type_data||{},joinedAt:n.joined_at,via:n.via,placement:n.placement,subordinateTo:n.subordinate_to??null,cascadeAnchorId:n.cascade_anchor_id??null,isAccount:n.is_account??void 0,isSpace:n.is_space??void 0,isOwner:n.is_owner??void 0,billingResponsible:n.billing_responsible??void 0,grantedVia:n.granted_via??null,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 Nn=new Map,xr=null,ws=null,St=new Map,_c=250,Sr=new Map;function Wt(e){if(xr){Qn(e);return}Qn(e),xr=ie("vfs_change",t=>Rd(t)),ws=ie("ccm_change",t=>Pd(t))}function Qn(e){if(Nn.has(e))return;let t=Fn(e,["vfs_change","ccm_change"]);Nn.set(e,t)}function Ss(e){let t=Nn.get(e);t&&(t(),Nn.delete(e))}function Fi(){for(let[,e]of Nn)e();Nn.clear(),xr&&(xr(),xr=null),ws&&(ws(),ws=null),St.forEach(e=>clearTimeout(e)),St.clear(),Sr.clear()}se(Fi);function Rd(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=Sr.get(s);i||(i=new Map,Sr.set(s,i)),i.set(t,{action:n,itemId:typeof e.item_id=="string"?e.item_id:void 0});let o=St.get(s);o&&clearTimeout(o);let a=setTimeout(()=>{St.delete(s);let c=Sr.get(s);Sr.delete(s),c&&Cd(s,c)},_c);St.set(s,a)}function Pd(e){if(!e||typeof e!="object")return;let t=e.source_item_id||e.source_id,n=e.target_item_id||e.target_id;if(!(e.edge_type!=null||t!=null||n!=null)||!t&&!n||e.item_type==="message")return;let s=`ccm:${t??""}:${n??""}`,i=St.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{St.delete(s),t&&N().invalidateQueries({queryKey:E.edges(t)}),n&&N().invalidateQueries({queryKey:E.edges(n)})},_c);St.set(s,o)}function Cd(e,t){let n=N();for(let[s,i]of t)(i.action||"").toUpperCase()==="DELETE"?(n.removeQueries({queryKey:E.item(s)}),n.removeQueries({queryKey:E.children(s)}),n.removeQueries({queryKey:E.tree(s)})):be(n,E.item(s),{exact:!0}),i.itemId&&n.invalidateQueries({queryKey:E.itemById(i.itemId)});n.invalidateQueries({queryKey:E.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 Dn=null;se(()=>{Dn=null});function xt(e){if(e!==Dn||e.generation!==ae())throw new Error("Workspace session changed")}function Ed(e){return e instanceof ge&&e.payload?.error==="item_not_found"}function Rr(e,t){let n=e.resolve(t.id);if(!n||n.path!==t.path||n.kind!==t.kind)throw new Error("Mount is not an available membership");return n}function Pr(e){let t=me();if(!t)throw new Error("Elect a home account before loading mounts");return[t,...e.filter((n,r)=>n.id!==t.id&&e.findIndex(s=>s.id===n.id)===r)]}function vc(e,t){return JSON.stringify({mounts:e.map(n=>n.id),last_anchor:t.id})}async function bc(e,t,n){xt(e);let r=vc(t,n);if(e.saved===r)return;let s=JSON.parse(r);await x(e.exists?"update":"create",e.exists?{_scope_path:e.scope,path:e.path,type_data:s}:{_scope_path:e.scope,parent_path:e.path.slice(0,e.path.lastIndexOf("/")),name:"mounts",item_type:"file",type_data:s}),xt(e),e.exists=!0,e.saved=r}function wc(e,t){let n=Ae();Wt(me().id);for(let r of n)e.some(s=>s.id===r.id)||Ss(r.id);for(let r of e)Qn(r.id);la(e,t)}async function Gt(e,t,n={}){let r=me();if(!r)throw new Error("Elect a home account before loading mounts");let s=`${e}/settings/mounts`;if(Dn&&Dn.path!==s)throw new Error("Reset the session before changing the mount declaration owner");let i=Dn??(Dn={generation:ae(),path:s,scope:r.path,resolve:t,exists:!1,ready:!1,saved:null,queue:Promise.resolve()});return xt(i),i.resolve=t,i.loading?i.loading:i.ready?Ae():(i.loading=(async()=>{let o=null;try{let l=await x("read",{path:s,_scope_path:i.scope});if(xt(i),o=l.type_data??l.item?.type_data,!o||!Array.isArray(o.mounts)||!o.mounts.every(f=>typeof f=="string"))throw new Error("Invalid saved mount declaration");i.exists=!0}catch(l){if(xt(i),!Ed(l))throw l;i.exists=!1}let a=n.initialAnchor?Rr(i,n.initialAnchor):r,c=Pr(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=vc(c,u):n.initialAnchor&&await bc(i,c,u),xt(i),i.ready=!0,wc(c,u),c})().finally(()=>{i.loading=void 0}),i.loading)}function xs(e){let t=Dn;if(!t?.ready)return Promise.reject(new Error("Workspace mounts are not loaded"));let n=t.queue.then(async()=>{xt(t);let{refs:r,anchor:s}=e(t);await bc(t,r,s),xt(t),wc(r,s)});return t.queue=n.catch(()=>{}),n}function qi(e){return xs(t=>({refs:Pr([...Ae(),Rr(t,e)]),anchor:de()}))}function Sc(e){return xs(()=>{if(e===me().id)throw new Error("The home account cannot be unmounted");let t=Pr(Ae().filter(r=>r.id!==e)),n=t.find(r=>r.id===de()?.id)??t.find(r=>r.kind==="space")??me();return{refs:t,anchor:n}})}function Cr(e){return xs(t=>{let n=Rr(t,e);return{refs:Pr([...Ae(),n]),anchor:n}})}function Rs(e,t){return xs(n=>{let r=Pr(e.map(i=>Rr(n,i))),s=Rr(n,t);if(!r.some(i=>i.id===s.id))throw new Error("Selected mount must be in the working set");return{refs:r,anchor:s}})}var Ni={};co(Ni,{Badge:()=>Od,Breadcrumbs:()=>Bd,Button:()=>qd,Card:()=>Md,DataView:()=>Qd,Detail:()=>Kd,Empty:()=>Nd,FilePreview:()=>Wd,Form:()=>Ud,Grid:()=>Ad,Image:()=>$d,Link:()=>Hd,Page:()=>Id,Router:()=>Ld,Sidebar:()=>kd,Spinner:()=>Fd,Stack:()=>Td,Table:()=>Dd,Tabs:()=>jd,Video:()=>Vd});var G=Y(ue(),1);function xc(){return(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||""}function Id(e){return(0,G.createElement)("div",{style:{minHeight:"100vh",display:"flex",flexDirection:"column"},className:e.className||""},e.children)}function Td(e){let t=e.direction||"vertical";return(0,G.createElement)("div",{style:{display:"flex",flexDirection:t==="horizontal"?"row":"column",gap:e.gap||"0.5rem",padding:e.padding||"0",alignItems:e.align||"stretch",justifyContent:e.justify||"flex-start",flex:e.flex||"initial"},className:e.className||""},e.children)}function Ad(e){return(0,G.createElement)("div",{style:{display:"grid",gridTemplateColumns:"repeat("+(e.columns||3)+", 1fr)",gap:e.gap||"1rem",padding:e.padding||"0"},className:e.className||""},e.children)}function kd(e){return(0,G.createElement)("div",{style:{display:"flex",flexDirection:"row",minHeight:"100vh"},className:e.className||""},e.children)}function Md(e){return(0,G.createElement)("div",{style:{border:"1px solid var(--color-border, #e5e7eb)",borderRadius:"var(--border-radius, 0.5rem)",padding:e.padding||"1rem",background:"var(--color-surface, #fff)"},className:e.className||"",onClick:e.onClick},e.children)}function Od(e){return(0,G.createElement)("span",{style:{display:"inline-flex",alignItems:"center",padding:"0.125rem 0.5rem",fontSize:"0.75rem",fontWeight:"500",borderRadius:"9999px",background:e.color||"#e5e7eb",color:e.textColor||"#374151"},className:e.className||""},e.children||e.label)}function Fd(e){let t=e.size||"1.5rem";return(0,G.createElement)("div",{style:{width:t,height:t,border:"2px solid #e5e7eb",borderTopColor:"var(--color-primary, #3b82f6)",borderRadius:"50%",animation:"fsaos-spin 0.6s linear infinite"}})}function qd(e){return(0,G.createElement)("button",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:"0.5rem 1rem",fontSize:"0.875rem",fontWeight:"500",borderRadius:"var(--border-radius, 0.375rem)",border:e.variant==="outline"?"1px solid var(--color-border, #d1d5db)":"none",background:e.variant==="outline"||e.variant==="ghost"?"transparent":"var(--color-primary, #3b82f6)",color:e.variant==="outline"||e.variant==="ghost"?"var(--color-text, #1a1a1a)":"#fff",cursor:e.disabled?"not-allowed":"pointer",opacity:e.disabled?"0.5":"1",gap:"0.5rem"},className:e.className||"",onClick:e.onClick,disabled:e.disabled},e.children||e.label)}function Nd(e){return(0,G.createElement)("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"3rem",color:"var(--color-text-secondary, #6b7280)",textAlign:"center"}},e.icon?(0,G.createElement)("div",{style:{fontSize:"2rem",marginBottom:"0.5rem"}},e.icon):null,(0,G.createElement)("div",{style:{fontWeight:500,marginBottom:"0.25rem"}},e.title||e.message||e.children||"No items"),e.description?(0,G.createElement)("div",{style:{fontSize:"0.875rem",opacity:.7}},e.description):null)}function Qd(e){return(0,G.createElement)("div",{className:e.className||""},e.children)}function Dd(e){return(0,G.createElement)("table",{className:e.className||""},e.children)}function Ud(e){return(0,G.createElement)("form",{className:e.className||"",onSubmit:e.onSubmit},e.children)}function Kd(e){return(0,G.createElement)("div",{className:e.className||""},e.children)}function Ld(e){return(0,G.createElement)("div",null,e.children)}function Hd(e){return(0,G.createElement)("a",{href:e.href||e.to,className:e.className||"",onClick:e.onClick},e.children)}function jd(e){return(0,G.createElement)("div",{className:e.className||""},e.children)}function Bd(e){return(0,G.createElement)("nav",{className:e.className||""},e.children)}function $d(e){return(0,G.createElement)("img",{src:e.src||(e.path?xc()+e.path:""),alt:e.alt||"",className:e.className||"",style:e.style})}function Vd(e){return(0,G.createElement)("video",{src:e.src||(e.path?xc()+e.path:""),controls:!0,className:e.className||""})}function Wd(e){return(0,G.createElement)("div",{className:e.className||""},e.children||"File preview")}function Ps(e){if(typeof e.path!="string")return!1;let t=[...Ae().map(n=>n.path),de()?.path].filter(n=>!!n);return!t.length&&W()&&t.push(W()),t.some(n=>he(e.path,n))}function Qi(e,t,n,r){if(!["message","card"].includes(e?.item_type)||!he(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&&he(e.path,i)})}var Rc=new WeakMap;function Pc(e,t,n){let r=Rc.get(e);r||(r=new Map,Rc.set(e,r));let s=JSON.stringify(t),i=r.get(s);if(!i){let a=!1,c,u=!1,l=!1,f=new Set,h=new Set,p=()=>e.getQueryData(t)??[],m=()=>{a||u||c||(c=setTimeout(()=>{c=void 0,y()},250))},y=async()=>{if(a)return;u=!0;let C=l;l=!1;let R=[...f],M=new Set(h);h.clear(),f.clear();try{if(C)await be(e,t,{exact:!0});else{let P=(await Promise.allSettled(R.map(async k=>{let T=e.getQueryCache().find({queryKey:t,exact:!0});if(!T)return;let A=await x("read",{id:k});if(A.success===!1)throw new Error("Channel refresh failed");if(a||!T||e.getQueryCache().find({queryKey:t,exact:!0})!==T)return;let O=Oe(A.item??A);if(O.id!==k||O.item_type!=="channel")return;let q=p().find(Pe=>Pe.id===k);if(!q)return;let K=n({...O}),$={...q,path:K.path,name:K.name,displayName:K.displayName,messageCount:K.messageCount,aiMode:K.aiMode,activeAgentIds:K.activeAgentIds,isPrivate:K.isPrivate,isDm:K.isDm,autoPilot:K.autoPilot,isArchived:K.isArchived,updatedAt:K.updatedAt};M.has(k)&&(q.name!==$.name||q.displayName!==$.displayName||q.path!==$.path)&&(l=!0),e.setQueryData(t,Pe=>Pe?.map(re=>re.id===k?$:re))}))).find(k=>k.status==="rejected");if(P?.status==="rejected")throw P.reason}}catch(D){console.warn("[channels] refresh failed",D)}finally{u=!1,(l||f.size)&&m()}},g=C=>p().some(R=>R.id===C.item_id||R.path===C.path)?!0:Ps(C),v=C=>{if(!g(C))return;let R=String(C.action??"").toLowerCase();if(["insert","delete","rename","move"].includes(R))l=!0;else if(R==="update"){let M=p().find(D=>D.id===C.item_id||D.path===C.path);M&&(f.add(M.id),h.add(M.id))}(l||f.size)&&m()},_=C=>{let R=p().find(M=>M.id===C.parent_id);R&&(f.add(R.id),m())},w=["vfs_change","ccm_change"].flatMap(C=>[ie(C,v,R=>R.item_type==="channel"),ie(C,_,R=>R.item_type==="message")]);i={users:0,stop:()=>{a=!0,c&&clearTimeout(c),w.forEach(C=>C())}},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)(xe,ee,ee)}function Mc(){return te(),zr()}function Oc(e){return te(),B({queryKey:E.item(e),queryFn:()=>yr(e),enabled:!!e,staleTime:1/0})}function Fc(e){return te(),B({queryKey:E.itemById(e),queryFn:()=>hr(e),enabled:!!e,staleTime:1/0})}function Ki(e){return te(),B({queryKey:E.children(e),queryFn:()=>_r(e),enabled:!!e})}function qc(e){let t=Ki(e);return{...t,children:t.data??[]}}function Nc(e,t=1){return te(),B({queryKey:E.tree(e,t),queryFn:()=>gs(e,t),enabled:!!e})}function Qc(e,t){return te(),B({queryKey:E.search(e,t),queryFn:async()=>{let n={query:e};t?.length&&(n.item_types=t);let r=await x("search",n);return(r.content?.items||r.items||r.results||[]).map(Oe)},enabled:!!e&&e.length>0})}function Dc(e){te();let t=(0,b.useMemo)(()=>e,[JSON.stringify(e)]);return B({queryKey:["vfs",W()??"__unscoped__","resolve",JSON.stringify(t??{})],queryFn:async()=>await x("resolve",t),enabled:!!t?.query&&t.query.length>0})}function Uc(e){te();let t=bt(e),n=(0,b.useMemo)(()=>t,[JSON.stringify(t)]),r=B({queryKey:E.items(n?.type??"",n),queryFn:({signal:s})=>Vt(n,{signal:s,throwOnError:!0}),enabled:qn(n),...n?.spaceIds!==void 0?{retry:(s,i)=>!In(i)&&Mu(s,i)}:{},select:s=>s.items});return n?.spaceIds!==void 0&&In(r.error)?{...r,data:void 0}:r}function Li(e,t={}){let n=te(),{realtime:r=!1}=t,s=bt(e),i=s?.limit??20,o=(0,b.useMemo)(()=>s,[JSON.stringify(s)]),a=(0,b.useMemo)(()=>["vfs",W()??"__unscoped__","infinite-items",o?.type??"",JSON.stringify(o??{})],[n,o]),c=or({queryKey:a,queryFn:async({pageParam:f=0,signal:h})=>Vt({...o,limit:i,offset:f},{throwOnError:!0,signal:h,priority:t.priority}),initialPageParam:0,getNextPageParam:(f,h,p)=>{if(!(o?.spaceIds!==void 0&&f.total_hint!==void 0&&p+f.items.length>=f.total_hint)&&!(f.items.length<i))return p+f.items.length},enabled:qn(o),...o?.spaceIds!==void 0?{retry:(f,h)=>!In(h)&&Mu(f,h)}:{},staleTime:r?1/0:t.staleTime,meta:r&&o?{infiniteItemsRealtime:{filter:o}}:{}}),u=(0,b.useMemo)(()=>{if(o?.spaceIds!==void 0&&In(c.error))return[];if(!c.data?.pages)return[];let f=new Set,h=[];for(let p of c.data.pages)for(let m of p.items)m.id&&!f.has(m.id)&&(f.add(m.id),h.push(m));return h},[c.data?.pages,c.error,o]),l=o?.spaceIds!==void 0&&In(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 Cc(e){return!!e?.type&&!!e.scope&&e.sort_by==="created_at"&&!e.offset&&!e.spaceIds&&!e.any_of&&!e.name&&!e.tag&&!e.discovery}function Jd(e,t){if(e.is_active===!1||e.item_type!==t.type||!he(e.path,t.scope)||t.parent_id&&e.parent_id!==t.parent_id)return!1;let n=e.type_data??{};for(let[r,s]of Object.entries(t.fields??{})){let i=n[r];if(typeof s=="string"&&s.endsWith("*")){if(typeof i!="string"||!i.startsWith(s.slice(0,-1)))return!1}else if(i!==s)return!1}for(let[r,s]of Object.entries(t.field_in??{}))if(!s.includes(n[r]))return!1;return!0}function Kc(e,t={}){let n=Cc(e),r=Li(e,n?{realtime:!1,staleTime:3e4}:{realtime:!0}),s=L(),i=JSON.stringify([W(),bt(e)]),[o,a]=(0,b.useState)(()=>({identity:i,upserts:{},deleted:new Set})),c=o.identity===i?o:{identity:i,upserts:{},deleted:new Set},u=(0,b.useMemo)(()=>{if(!n)return r.allItems;let p=Object.values(c.upserts),m=new Set(p.map(_=>_.id)),y=[...p,...r.allItems.filter(_=>!m.has(_.id))].filter(_=>!c.deleted.has(_.path)),g=e.sort_by??"updated_at",v=e.sort_dir==="asc"?1:-1;return y.sort((_,w)=>v*String(_[g]??"").localeCompare(String(w[g]??"")))},[n,r.allItems,c,e?.sort_by,e?.sort_dir]),l=(0,b.useRef)(u);l.current=u;let f=(0,b.useRef)(t.shouldReadUpdate);f.current=t.shouldReadUpdate;let h=(0,b.useRef)(r.refetch);return h.current=r.refetch,(0,b.useEffect)(()=>{if(!Cc(e))return;let p=e,m=!1,y=!1,g=!1,v=0,_=new Map,w=()=>{let P=v;h.current().then(k=>{!m&&!k.isError&&v===P&&a({identity:i,upserts:{},deleted:new Set})})},C=P=>{v++,a(T=>{let A=T.identity===i?T:{identity:i,upserts:{},deleted:new Set},O={...A.upserts};return delete O[P],{identity:i,upserts:O,deleted:new Set(A.deleted).add(P)}});let k=_.get("__reconcile__");k&&clearTimeout(k),_.set("__reconcile__",setTimeout(()=>{_.delete("__reconcile__"),w()},250))},R=P=>{let k=_.get(P);k&&clearTimeout(k),_.set(P,setTimeout(()=>{_.delete(P),s.fetchQuery({queryKey:E.item(P),queryFn:()=>yr(P),staleTime:0}).then(T=>{if(!m){if(!T||!Jd(T,p)){let A=l.current.find(O=>O.path===P||O.id===T?.id);A&&C(A.path);return}a(A=>{let O=A.identity===i?A:{identity:i,upserts:{},deleted:new Set},q=new Set(O.deleted);return q.delete(P),{identity:i,upserts:{...O.upserts,[P]:T},deleted:q}})}}).catch(T=>console.warn("[useIncrementalItems] item read failed:",T))},250))},M=ie("vfs_change",P=>{if(!P||typeof P.path!="string"&&typeof P.old_path!="string")return;let k=typeof P.path=="string"?P.path:P.old_path,T=l.current.find(O=>O.path===k||O.path===P.old_path||P.item_id&&O.id===P.item_id),A=!!T;if(!(!he(k,p.scope)&&!he(P.old_path,p.scope)&&!A)&&!(P.item_type&&P.item_type!==p.type&&!A)&&!(p.parent_id&&P.parent_id&&P.parent_id!==p.parent_id&&!A)){if(T&&(k!==T.path||P.old_path&&P.old_path!==k||P.parent_id&&P.parent_id!==T.parent_id||P.item_type&&P.item_type!==p.type)){C(T.path);return}if(!T&&P.old_path&&P.old_path!==k&&he(k,p.scope)){v++,R(k);return}if(P.action==="insert")v++,R(k);else if(P.action==="move")v++,R(k);else if(P.action==="update"){if(!f.current?.(P,l.current))return;v++,R(k)}else P.action==="delete"&&C(T?.path??P.old_path??k)}}),D=ls(P=>{if(P!=="connected"){y&&(g=!0);return}y=!0,g&&(g=!1,w())});return()=>{m=!0,M(),D(),_.forEach(clearTimeout)}},[s,i]),{...r,allItems:u}}function Lc(e){te();let t=20,n=or({queryKey:["vfs",W()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>fs(e,t,s),initialPageParam:0,getNextPageParam:(s,i,o)=>{if(!(s.items.length<t))return o+s.items.length},enabled:!!e});return{allItems:(0,b.useMemo)(()=>{if(!n.data?.pages)return[];let s=new Set,i=[];for(let o of n.data.pages)for(let a of o.items)a.id&&!s.has(a.id)&&(s.add(a.id),i.push(a));return i},[n.data?.pages]),fetchNextPage:n.fetchNextPage,isFetchingNextPage:n.isFetchingNextPage,isExhausted:!n.hasNextPage,isLoading:n.isLoading,isFetching:n.isFetching,error:n.error,totalHint:n.data?.pages?.[0]?.total_hint}}function Hc(e){return te(),B({queryKey:E.edges(e),queryFn:()=>ms(e),enabled:!!e})}function Es(e){return te(),B({queryKey:E.types(e),queryFn:()=>ps(e)})}function jc(e,t){let n=Es(t);return{...n,data:n.data?.get(e)??void 0}}function Bc(e,t){te();let n=(0,b.useMemo)(()=>t?.arguments,[JSON.stringify(t?.arguments)]),r=t?.mode,s=t?.strategy,i=t?.width;return B({queryKey:[...E.openEnvelope(e,s),i],queryFn:async()=>{let o=await br(e,{mode:r,strategy:s,arguments:n});if(i&&o.render?.props?.url){let a=o.render.props.url,c=a.includes("?")?"&":"?";o.render.props.url=`${a}${c}w=${i}`}return o},enabled:!!e})}var Ec={related_to:"Related To",depends_on:"Depends On",blocks:"Blocks",parent_of:"Parent Of",child_of:"Child Of",references:"References",implements:"Implements",extends:"Extends",contains:"Contains",belongs_to:"Belongs To",created_by:"Created By",assigned_to:"Assigned To",tagged_with:"Tagged With",linked_to:"Linked To"};function $c(e){let t=Es(e),n=t.data??new Map;return(0,b.useMemo)(()=>({canHaveChildren:p=>n.get(p.item_type)?.is_container??!1,isScope:p=>n.get(p.item_type)?.is_scope??!1,isScopeType:p=>n.get(p)?.is_scope??!1,isContainerType:p=>n.get(p)?.is_container??!1,getTypeDefinition:p=>n.get(p),getTypeColor:p=>n.get(p)?.color??"gray",getTypeIcon:p=>n.get(p)?.icon??"File",getTypeDisplayName:p=>n.get(p)?.display_name??p,getKnownEdgeTypes:()=>Object.entries(Ec).map(([p,m])=>({key:p,label:m})),getEdgeTypeLabel:p=>Ec[p]??p.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function Vc(e,t,n){return te(),B({queryKey:E.memberFocus(e),queryFn:()=>_s(e,t,n),enabled:!!e})}function Wc(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return B({queryKey:E.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>vr(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function Gc(e,t=50,n=0){return B({queryKey:E.itemHistory(e,String(t),String(n)),queryFn:()=>ys(e,t,n),enabled:!!e})}function zc(e,t=50,n=0){return te(),B({queryKey:E.recentActivity(e,String(t),String(n)),queryFn:()=>hs(e,t,n),enabled:!!e})}function Jc(){let[e,t]=(0,b.useState)(null),[n,r]=(0,b.useState)(!0),[s,i]=(0,b.useState)(null);return(0,b.useEffect)(()=>{let o=!1;return nt().then(a=>{if(!o){let c=typeof window<"u"&&window.__FSAOS_CONFIG__||{};t({path:a.scope_path,scope_id:a.scope_id,fractal_id:a.fractal_id,instance_name:a.instance_name,display_name:a.display_name,componentPath:c.componentPath||"",isEmbed:!!c.embedToken}),r(!1)}}).catch(a=>{o||(i(a instanceof Error?a:new Error(String(a))),r(!1))}),()=>{o=!0}},[]),{data:e,loading:n,error:s}}var Yd=[];function Ic(){if(typeof window>"u")return!1;let e=window.__FSAOS_CONFIG__?.embedToken;return typeof e=="function"||typeof e=="string"&&e.length>0}function Zd(e){return e.filter(t=>t.placement==="switcher_entry").map(t=>({account:t,mountables:e.filter(n=>n.placement!=="switcher_entry"&&n.subordinateTo===t.accountId)}))}function Yc(){let{user:e}=Is(),t=(0,b.useSyncExternalStore)(pa,vi,vi),n=vt()?.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&&!Ic()){a(null);return}let _=!1;return nt().then(w=>{_||w.principal_id||a(new Error("Memberships require an authenticated principal"))}).catch(w=>{_||a(w instanceof Error?w:new Error(String(w)))}),()=>{_=!0}},[n,e?.id,t]);let c=B({queryKey:E.memberships(n??"anonymous"),queryFn:bs,enabled:!!n,staleTime:1e3*60*2}),u=c.data??Yd,l=(0,b.useMemo)(()=>u.filter(_=>_.isAccount!==!1&&!_.isSpace),[u]),f=(0,b.useMemo)(()=>{let _=new Set(l.map(C=>C.accountId)),w=C=>!C.subordinateTo||!_.has(C.subordinateTo);return[...l].sort((C,R)=>Number(w(R))-Number(w(C)))},[l]),h=(0,b.useSyncExternalStore)(xe,ee,ee),p=(0,b.useMemo)(()=>{let _=de();return _?u.find(w=>w.accountId===_.id)??null:null},[h,u]),m=(0,b.useMemo)(()=>Zd(l),[l]);(0,b.useEffect)(()=>{if(!n){r.current=null;return}if(r.current!==n)if(i(null),f.length===1){let _=f[0];me()||Kt($e(_)),Wt(_.accountId),_.personalSpacePath&&Gt(_.personalSpacePath,w=>{let C=u.find(R=>R.accountId===w);return C?$e(C):null}).catch(i),r.current=n}else f.length>1&&(r.current=n)},[n,f,u]);let y=(0,b.useCallback)(async _=>{let w=u.find(M=>M.path===_);if(!w)throw new Error("Account membership is unavailable");let C=$e(w);me()||Kt(C);let R=u.find(M=>M.accountId===me()?.id);if(!R?.personalSpacePath)throw new Error("The home membership has no mount declaration location");await Gt(R.personalSpacePath,M=>{let D=u.find(P=>P.accountId===M);return D?$e(D):null}),await Cr(C),i(null),Wt(w.accountId)},[u]),g=(0,b.useCallback)(async _=>{let w=u.find(C=>C.path===_);if(!w)throw new Error("Scope membership is unavailable");await qi($e(w))},[u]),v=(!!e?.id||Ic())&&!n&&!o;return{accounts:f,switcherAccounts:m,allMemberships:u,currentAccount:p,mountedScope:null,switchAccount:y,mountScope:g,loading:v||c.isLoading,error:o??c.error??s}}function Zc(){te();let e=(0,b.useSyncExternalStore)(Gr,lr,lr),t=(0,b.useMemo)(()=>Ae(),[e]),n=de(),r=(0,b.useMemo)(()=>t.filter(i=>i.kind==="space"&&(n?.kind==="account"||i.id===n?.id)),[t,n]),s=(0,b.useMemo)(()=>r.map(i=>i.id).sort(),[r]);return{mounts:t,selectedSpaces:r,readSpaceIds:s,homeAnchor:me(),anchor:n,setAnchor:Cr,replaceMounts:Rs,mount:qi,unmount:Sc}}function Is(){let[e,t]=(0,b.useState)(null),[n,r]=(0,b.useState)(null),[s,i]=(0,b.useState)(!0),o=(0,b.useRef)(null);(0,b.useEffect)(()=>{V.auth.getSession().then(({data:p,error:m})=>{if(m){console.warn("[useAuth] getSession error, clearing stale session:",m.message),V.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(p?.session??null),t(p?.session?.user??null),i(!1)}).catch(p=>{console.warn("[useAuth] getSession threw, clearing stale session:",p?.message),V.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:h}}=V.auth.onAuthStateChange((p,m)=>{if(p==="TOKEN_REFRESHED"&&!m){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),V.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?V.auth.signInWithOAuth({provider:h.provider,options:h.redirectTo?{redirectTo:h.redirectTo}:{redirectTo:window.location.href}}):V.auth.signInWithPassword({email:h.email,password:h.password}),[]),c=(0,b.useCallback)(async h=>V.auth.signUp({email:h.email,password:h.password,options:{data:h.metadata||{}}}),[]),u=(0,b.useCallback)(async()=>{await V.auth.signOut(),Cn(),N().clear()},[]),l=(0,b.useCallback)(async h=>{let{error:p}=await V.auth.resetPasswordForEmail(h);if(p)throw p},[]),f=(0,b.useCallback)(async(h,p)=>{let{error:m}=await V.auth.signInWithOtp({email:h,options:p?{emailRedirectTo:p}:{emailRedirectTo:window.location.href}});if(m)throw m},[]);return{user:e,session:n,loading:s,signIn:a,signUp:c,signOut:u,resetPassword:l,signInWithMagicLink:f}}function Xc(e){let[t,n]=(0,b.useState)(null),[r,s]=(0,b.useState)(!1),[i,o]=(0,b.useState)(null);return(0,b.useEffect)(()=>{if(!e){n(null),s(!1);return}if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e))s(!0),x("resolve-asset",{asset_id:e}).then(c=>{c.success&&c.public_url?n({url:c.public_url,id:c.asset_id,name:c.name,mimeType:c.mime_type,width:c.width,height:c.height,sizeBytes:c.size_bytes}):o(new Error(c.error||"Asset not found")),s(!1)}).catch(c=>{o(c instanceof Error?c:new Error(String(c))),s(!1)});else{let u=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";n({url:u+e}),s(!1)}},[e]),{data:t,loading:r,error:i}}var Cs={};se(()=>{for(let e of Object.keys(Cs))delete Cs[e]});var eu=null;function tu(e){eu=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function Xd(e){switch(e){case"react":return typeof window<"u"&&window.React||b.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||Gd;case"react/jsx-runtime":case"react/jsx-dev-runtime":return typeof window<"u"&&window.React?{jsx:window.React.createElement,jsxs:window.React.createElement,Fragment:window.React.Fragment}:zd;case"@fsaos/gateway":case"@fsaos/react":case"@ai4b-team/fsaos-gateway-sdk":return typeof window<"u"&&window.__FSAOS_GATEWAY__||eu||{};case"@fsaos/ui":case"@ai4b-team/fsaos-gateway-sdk/ui":return typeof window<"u"&&window.__FSAOS_UI__||Ni;case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}var Ir={};async function ef(e){try{let t=await fetch(e);if(!t.ok)return null;let n=await t.text();return!n.trim()||n.includes("No CSS bundle for this component")?null:n}catch{return null}}async function nu(e,t=()=>ef(e)){let n=Ir[e];n||(n=Ir[e]={users:0,text:t(),style:null}),n.users+=1;let r=await n.text;if(Ir[e]!==n||n.users===0||n.style||!r||typeof document>"u")return;let s=document.createElement("style");s.setAttribute("data-fsaos-component-css",e),s.textContent=r,document.head.appendChild(s),n.style=s}function Ve(e){let t=Ir[e];t&&(t.users-=1,!(t.users>0)&&(t.style?.remove(),delete Ir[e]))}function ru(e){let t=null,n=window.__FSAOS_REGISTER__;window.__FSAOS_REGISTER__=r=>{t=r};try{let r=["var require = arguments[0];",e,"return window.__FSAOS_COMPONENT__;"].join(`
3
- `),i=new Function(r)(Xd),o=t??i;return o?o.default||o:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function Hi(e,t){let[n,r]=(0,b.useState)(null),[s,i]=(0,b.useState)(!0),[o,a]=(0,b.useState)(null),c=(0,b.useRef)(null),u=Number.isSafeInteger(t?.version)&&t.version>0?t.version:null;return(0,b.useEffect)(()=>{if(!e)return;let l=!1;a(null),c.current?.path!==e&&(c.current?.cssUrl&&Ve(c.current.cssUrl),c.current=null,r(null),i(!0));let h=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{let p=null;try{let m=1,y=e+"@v1",g=h+e+"/__bundle.js";if(u!==null)m=u,y=e+"@v"+m,g=h+e+"/__bundle.v"+m+".js";else try{let R=await fetch(h+e+"/__meta",{cache:"no-store"});R.ok&&(m=(await R.json()).version||1,y=e+"@v"+m,g=h+e+"/__bundle.v"+m+".js")}catch{g=h+e+"/__bundle.js?v="+Date.now()}if(l)return;let v=g.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");p=v;let _=nu(v),w=Cs[y];if(!w){let R=await fetch(g);if(!R.ok)throw new Error(`Failed to fetch bundle: ${R.status} ${R.statusText} (${g})`);let M=await R.text();if(w=ru(M),!w)throw new Error("Bundle did not export a component. Expected window.__FSAOS_COMPONENT__ (FSAOS build) or a __FSAOS_REGISTER__(Component) call.");if(typeof w!="function")throw new Error(`Bundle export is not a React component (got ${typeof w})`);Cs[y]=w}if(await _,l){Ve(v);return}let C=c.current?.cssUrl??null;c.current={path:e,cssUrl:v},p=null,r(()=>w),i(!1),C&&Ve(C)}catch(m){p&&Ve(p),l||(a(m instanceof Error?m:new Error(String(m))),i(!1))}})(),()=>{l=!0}},[e,u]),(0,b.useEffect)(()=>()=>{c.current?.cssUrl&&Ve(c.current.cssUrl),c.current=null},[]),{Component:n,loading:s,error:o}}var tf=/^embed\/bundle-[A-Za-z0-9_-]+\.js$/,nf=/^embed\/bundle-[A-Za-z0-9_-]+\.css$/;function Tc(e,t,n){let r=Object.keys(e).filter(o=>t.test(o));if(r.length>1)throw new Error(`The published release has more than one in-app ${n}.`);let s=r[0];if(!s)return null;let i=Rt(e[s]).sha256;return typeof i=="string"&&i?{path:s,sha256:i}:null}var Er=new Map,Di=new Map;se(()=>{Er.clear(),Di.clear()});function Rt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function su(e){let t=Rt(Rt(e.type_data).published),n=t.published_release_item_id,r=t.published_version;return typeof n!="string"||!n||typeof r!="number"||!Number.isSafeInteger(r)||r<1?null:{releaseItemId:n,version:r}}async function Ac(e,t,n){let r=await br(e.path,{mode:"render"}),s=Rt(Rt(r.render).props).url;if(typeof s!="string"||!s)throw new Error(`The published ${n} could not be opened.`);let i=await fetch(s);if(!i.ok)throw new Error(`Failed to read the published ${n}: ${i.status} ${i.statusText}`.trim());let o=await i.arrayBuffer();if(Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",o))).map(c=>c.toString(16).padStart(2,"0")).join("")!==t)throw new Error(`The published ${n} does not match the bytes its release sealed.`);return new TextDecoder().decode(o)}async function rf(e,t,n){let r=await hr(t);if(!r)throw new Error("The published release could not be read.");let s=Rt(r.type_data);if(r.item_type!=="revdev_release"||s.component_item_id!==e||s.status!=="committed"||Number(s.version)!==n)throw new Error("This component's live version does not match its release record.");let i=Rt(s.artifacts),o=Tc(i,tf,"script");if(!o)return{status:"no_in_app_version",releaseItemId:t,version:n};let a=Tc(i,nf,"stylesheet"),c=a?[o.path,a.path]:[o.path],u=s.build_item_id;if(typeof u!="string"||!u)throw new Error("The published release names no build.");let{items:l}=await Vt({type:"file",parent_id:u,field_in:{package_path:c},limit:c.length},{throwOnError:!0}),f=g=>l.find(v=>Rt(v.type_data).package_path===g),h=f(o.path),p=a?f(a.path):void 0;if(!h||a&&!p)throw new Error("The published release's in-app files could not be found in its build.");let[m,y]=await Promise.all([Ac(h,o.sha256,"script"),p&&a?Ac(p,a.sha256,"stylesheet"):Promise.resolve(null)]);return{status:"ready",releaseItemId:t,version:n,script:m,stylesheet:y?.trim()?y:null}}function iu(e,t,n){let r=Er.get(t);return r||(r=rf(e,t,n),Er.set(t,r),r.catch(()=>{Er.get(t)===r&&Er.delete(t)})),r}function ou(e){let t=su(e);return!e.id||!t?Promise.resolve({status:"unpublished"}):iu(e.id,t.releaseItemId,t.version)}function au(e){let[t,n]=(0,b.useState)(null),[r,s]=(0,b.useState)("loading"),[i,o]=(0,b.useState)(null),a=(0,b.useRef)(null),c=e!=null,u=e?.id||null,l=e?su(e):null,f=l?.releaseItemId??null,h=l?.version??null;return(0,b.useEffect)(()=>{if(!c)return;let p=()=>{a.current?.cssKey&&Ve(a.current.cssKey),a.current=null,n(null)};if(!u||!f||h===null){p(),o(null),s("unpublished");return}let m=!1;return o(null),a.current&&a.current.componentId!==u&&p(),a.current||s("loading"),(async()=>{let y=null;try{let g=await iu(u,f,h);if(m)return;if(g.status!=="ready"){p(),s(g.status);return}let v=Di.get(f);if(!v){if(v=ru(g.script),!v)throw new Error("The published script did not hand over a component. Expected a __FSAOS_REGISTER__(Component) call or window.__FSAOS_COMPONENT__.");if(typeof v!="function")throw new Error(`The published script handed over something that is not a React component (${typeof v}).`);Di.set(f,v)}let _=g.stylesheet?`release:${f}`:null;if(_&&(y=_,await nu(_,async()=>g.stylesheet)),m){y&&Ve(y);return}let w=a.current?.cssKey??null;a.current={componentId:u,releaseItemId:f,cssKey:_},y=null,n({Component:v,version:h}),s("ready"),w&&Ve(w)}catch(g){if(y&&Ve(y),m)return;o(g instanceof Error?g:new Error(String(g))),a.current||s("error")}})(),()=>{m=!0}},[c,u,f,h]),(0,b.useEffect)(()=>()=>{a.current?.cssKey&&Ve(a.current.cssKey),a.current=null},[]),{Component:t?.Component??null,status:r,error:i,version:t?.version??null}}var sf=["--color-primary","--color-secondary","--color-background","--color-surface","--color-text","--color-text-secondary","--color-border","--color-accent","--color-success","--color-warning","--color-error","--font-family-heading","--font-family-body","--border-radius","--spacing-unit"];function cu(){return{data:(0,b.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let t={},n=getComputedStyle(document.documentElement);return sf.forEach(r=>{t[r]=n.getPropertyValue(r).trim()}),{tokens:t}},[]),loading:!1,error:null}}function uu(e,t){return{data:{allowed:!0},loading:!1,error:null}}function lu(e,t){let n={};return(t||[]).forEach(r=>{n[r]=!0}),{data:n,loading:!1,error:null}}var fe=null,Un=null,Ui=new Set;function of(){Ui.forEach(e=>e())}se(()=>{fe=null,Un=null});async function du(e){let t={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null},n=vt()?.principal_id??null;if(n){if(fe&&fe.principalId===n){let{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}=fe;return{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}}return{...t,principalId:n}}let r=e;if(!r){let{data:s}=await V.auth.getSession();r=s?.session?.user?.id}if(!r)return t;if(fe&&fe.authUserId===r){let{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}=fe;return{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}}return Un||(Un=(async()=>{try{let{data:s,error:i}=await V.from("os_principals").select("id, display_name, created_at, metadata").eq("auth_user_id",r).eq("principal_type","user").maybeSingle();if(i)return console.warn("[SDK] Could not resolve principal:",i.message),t;let o=s?.id??null,a=null;if(o){let{data:u}=await V.from("os_items").select("path").eq("owner_principal_id",o).eq("item_type","principal").eq("is_active",!0).like("path","/root/principals/%"),l=(u??[]).map(f=>f.path);a=l.find(f=>f.split("/").length===4)??l[0]??null}let c={principalId:o,displayName:s?.display_name??null,createdAt:s?.created_at??null,metadata:s?.metadata??null,vfsPath:a};return fe={authUserId:r,...c},c}finally{Un=null}})(),Un)}async function fu(e){return(await du(e)).principalId}function pu(){let e=Is(),t=e.user,n=fe?.authUserId===t?.id?fe:null,[r,s]=(0,b.useState)(n),i=(0,b.useRef)(null);return(0,b.useEffect)(()=>{let o=()=>{let a=fe;a&&a.authUserId===t?.id&&s({principalId:a.principalId,displayName:a.displayName,createdAt:a.createdAt,metadata:a.metadata,vfsPath:a.vfsPath})};return Ui.add(o),()=>{Ui.delete(o)}},[t?.id]),(0,b.useEffect)(()=>{if(!t?.id){s(null),i.current=null;return}i.current===t.id&&r?.principalId!=null||(i.current=t.id,du(t.id).then(o=>{s(o)}))},[t?.id]),e.loading?{data:null,loading:!0,error:null}:t?{data:{id:t.id,principalId:r?.principalId??null,email:t.email,display_name:r?.displayName??void 0,created_at:r?.createdAt??void 0,vfs_path:r?.vfsPath??void 0,role:t.role||t.app_metadata?.role||"user",authenticated:!0,metadata:r?.metadata??t.user_metadata??{}},loading:!1,error:null}:{data:{id:"anonymous",principalId:null,role:"viewer",authenticated:!1},loading:!1,error:null}}function mu(e){let{path:t,...n}=e,r=Hi(t),s=r.Component,{loading:i,error:o}=r;return i?(0,b.createElement)("div",{className:"fsaos-loading"},""):o?(0,b.createElement)("div",{className:"fsaos-error"},"Failed to load component"):s?(0,b.createElement)(s,n):null}function gu(e){return e.children}function hu(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)(()=>E.channelMessages(n??"",r),[n,r,t]),c=L(),u=(0,b.useRef)(null),l=B({queryKey:a,queryFn:()=>vs(n,r),enabled:o});(0,b.useEffect)(()=>{if(!s||!o)return;let y=ie("vfs_change",()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{be(c,a,{exact:!0})},500)},g=>{let v=c.getQueryData(a);return Qi(g,n,r,[...v?.messages??[],...v?.activityMessages??[]])});return()=>{y(),u.current&&clearTimeout(u.current)}},[s,o,n,r,a,c]);let f=l.data,h=f?.messages??[],p=f?.messageCards??new Map,m=f?.siblingCards??[];return{messages:h,activityMessages:f?.activityMessages??[],messageCards:p,siblingCards:m,threads:(0,b.useMemo)(()=>h.filter(y=>y.reply_count>0),[h]),breakouts:(0,b.useMemo)(()=>h.filter(y=>y.member_count>0),[h]),isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function yu(e){te();let{channelPath:t,parentMessageId:n,limit:r=50,realtime:s=!0,enabled:i=!0,conversationsOnly:o=!1,transcriptOnly:a=!1}=e,c=!!n,u=i&&!!t,l=or({queryKey:[...E.channelMessages(t||"",n),"infinite",r,"latest-first",...o?["conversations"]:[],...a?["transcript"]:[]],queryFn:async({pageParam:v})=>wr(t,{parentMessageId:n,limit:r,conversationsOnly:o,transcriptOnly:a,before_seq:v?.before_seq,after_seq:v?.after_seq}),initialPageParam:void 0,getPreviousPageParam:v=>{if(!c||v.messages.length<r)return;let _=v.messages[v.messages.length-1]?.seq;return _==null?void 0:{after_seq:_}},getNextPageParam:v=>{if(v.messages.length<r)return;let _=v.messages[0]?.seq;return _==null?void 0:{before_seq:_}},enabled:u}),f=(0,b.useMemo)(()=>{if(!l.data?.pages)return[];let v=new Set,_=[];for(let w of l.data.pages)for(let C of w.messages)v.has(C.id)||(v.add(C.id),_.push(C));return _.sort((w,C)=>w.seq-C.seq)},[l.data?.pages]),{messageCards:h,siblingCards:p}=(0,b.useMemo)(()=>{let v=new Map,_=[];if(!l.data?.pages)return{messageCards:v,siblingCards:_};let w=new Set;for(let C of l.data.pages){for(let[R,M]of C.messageCards)for(let D of M){if(w.has(D.id))continue;w.add(D.id);let P=v.get(R)||[];P.push(D),v.set(R,P)}for(let R of C.siblingCards)w.has(R.id)||(w.add(R.id),_.push(R))}return{messageCards:v,siblingCards:_}},[l.data?.pages]),m=L(),y=(0,b.useRef)(null),g=(0,b.useMemo)(()=>[...E.channelMessages(t||"",n),"infinite",r,"latest-first",...o?["conversations"]:[],...a?["transcript"]:[]],[t,n,r,o,a]);return(0,b.useEffect)(()=>{if(!s||!t||!u)return;let v=()=>void be(m,g,{exact:!0}),_=!1,w=!1,C=!1,R=async()=>{if(o||a){v();return}let P=m.getQueryData(g);if(!P?.pages?.length){v();return}let k=0;for(let T of P.pages)for(let A of T.messages)A.seq>k&&(k=A.seq);if(k===0){v();return}try{let T=await wr(t,{parentMessageId:n,limit:r,after_seq:k});if(T.messages.length===0&&T.siblingCards.length===0){v();return}if(T.messages.length>0){let A=Math.min(...T.messages.map(O=>O.seq));if(A>k+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${k}, minNewSeq=${A}. Triggering full refetch.`),v();return}}m.setQueryData(g,A=>{if(!A)return A;let O=[...A.pages],q=0,K=O[q],$=new Set(K.messages.map(Ce=>Ce.id)),Pe=T.messages.filter(Ce=>!$.has(Ce.id)),re=[...K.messages,...Pe].sort((Ce,Ns)=>Ce.seq-Ns.seq),Et=new Map(K.messageCards);for(let[Ce,Ns]of T.messageCards){let oo=Et.get(Ce)||[],Ol=new Set(oo.map(Qs=>Qs.id)),Fl=Ns.filter(Qs=>!Ol.has(Qs.id));Et.set(Ce,[...oo,...Fl])}let Al=new Set(K.siblingCards.map(Ce=>Ce.id)),kl=T.siblingCards.filter(Ce=>!Al.has(Ce.id)),Ml=[...K.siblingCards,...kl];return O[q]={...K,activityMessages:T.activityMessages??[],messages:re,messageCards:Et,siblingCards:Ml},{...A,pages:O}})}catch(T){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",T),v()}},M=async()=>{if(_){w=!0;return}_=!0;try{do w=!1,await R();while(w&&!C)}finally{_=!1}},D=ie("vfs_change",()=>{y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{M()},500)},P=>(o||a)&&P?.item_type==="message"&&(m.getQueryData(g)?.pages??[]).some(k=>k.messages.some(T=>T.id===P.parent_id))||Qi(P,t,n,m.getQueryData(g)?.pages.flatMap(k=>k.messages)??[]));return()=>{C=!0,D(),y.current&&clearTimeout(y.current)}},[s,t,u,g,m,n,r,o,a]),{messages:f,activityMessages:l.data?.pages[0]?.activityMessages??[],messageCards:h,siblingCards:p,threads:f.filter(v=>v.reply_count>0),breakouts:f.filter(v=>v.member_count>0),isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch,hasPreviousPage:l.hasNextPage??!1,fetchPreviousPage:l.fetchNextPage,isFetchingPreviousPage:l.isFetchingNextPage??!1,hasNextPage:l.hasPreviousPage??!1,fetchNextPage:l.fetchPreviousPage,isFetchingNextPage:l.isFetchingPreviousPage??!1}}var _u=["open","active","strict","hand_raise"];function af(e){return e==="open"||e==="active"||e==="strict"||e==="hand_raise"?e:e==="on"||e==="auto"?"active":"strict"}function cf(e){if(Array.isArray(e))return e.filter(t=>typeof t=="string")}function kc(e){let t=e.type_data||{},n=e._reader||{},r=n.context_lineage||{};return{id:e.id||"",path:e.path||"",name:e.name||"",displayName:t.display_name||e.name||"",aiMode:af(t.ai_mode),activeAgentIds:cf(t.active_agent_ids),isPrivate:t.is_private||!1,isDm:t.is_dm||!1,messageCount:t.message_count||0,createdAt:e.created_at||"",updatedAt:e.updated_at||"",chatScopePath:r.context_path||"",contextId:e.scope_item_id||"",contextPath:r.context_path||"",contextType:r.context_type||"",contextName:r.context_name||"",contextDisplayName:r.context_name||"",contextPrincipalId:void 0,accountId:e.account_item_id||"",accountPath:"",accountDisplayName:"",memberRole:n.member_role||"member",memberPath:"",modePath:"",autoPilot:t.auto_pilot||!1,isArchived:t.is_archived===!0}}function Ts(e={}){let t=te(),{realtime:n=!0,enabled:r=!0,includeArchived:s=!1}=e,i=L(),o=(0,b.useMemo)(()=>E.channels("all"),[t]),a=B({queryKey:o,queryFn:async()=>((await x("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(kc),enabled:r});return(0,b.useEffect)(()=>{if(!(!n||!r))return Pc(i,o,kc)},[n,r,o,i]),{channels:(0,b.useMemo)(()=>(a.data??[]).filter(u=>s||!u.isArchived),[a.data,s]),isLoading:a.isLoading,isFetching:a.isFetching,error:a.error,refetch:a.refetch}}function vu(e={}){let t=Ts(e),n=(0,b.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function bu(e={}){let t=Ts(e),n=(0,b.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function ji(e={}){let t=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)(()=>E.notifications(n,r),[n,r,t]),u=B({queryKey:c,queryFn:async()=>{let f={limit:r};return n==="unread"&&(f.filter="unread"),(await x("get-notifications",f)).notifications||[]},enabled:i});return(0,b.useEffect)(()=>{if(!s||!i)return;let f=["vfs_change","ccm_change"].map(h=>ie(h,()=>{a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{o.invalidateQueries({queryKey:c})},2e3)},p=>p.item_type==="notification"&&Ps(p)));return()=>{f.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 wu(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:o,error:a,refetch:c}=ji({filter:"unread",limit:200,realtime:n,enabled:r}),u=(0,b.useMemo)(()=>{let p=new Map;for(let m of s)m.is_unread&&m.channel_id&&p.set(m.channel_id,(p.get(m.channel_id)||0)+1);return p},[s]),l=(0,b.useMemo)(()=>{let p=0;return u.forEach(m=>{p+=m}),p},[u]),{dmUnread:f,channelUnread:h}=(0,b.useMemo)(()=>{if(!t)return{dmUnread:0,channelUnread:0};let p=new Set(t.filter(g=>g.isDm).map(g=>g.id)),m=0,y=0;return u.forEach((g,v)=>{p.has(v)?m+=g:y+=g}),{dmUnread:m,channelUnread:y}},[t,u]);return{unreadByChannel:u,totalUnread:l,dmUnread:f,channelUnread:h,isLoading:i,isFetching:o,error:a,refetch:c}}function Su(){let e=L();return ne({mutationFn:t=>x("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:E.children(r)})}})}function xu(){let e=L();return ne({mutationFn:t=>x("update",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.invalidateQueries({queryKey:E.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:E.children(i)})}}})}function Ru(){return ne({mutationFn:e=>x("update-principal",e),onSuccess:(e,t)=>{if(!fe)return;let n=e&&typeof e=="object"&&e.metadata?e.metadata:{...fe.metadata??{},...typeof t.language=="string"?{language:t.language}:{},...typeof t.timezone=="string"?{timezone:t.timezone}:{},..."avatar_file_id"in t?{avatar_file_id:t.avatar_file_id}:{}};fe={...fe,displayName:typeof t.display_name=="string"?t.display_name:fe.displayName,metadata:n},of()}})}function Pu(){let e=L();return ne({mutationFn:t=>x("delete",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.removeQueries({queryKey:E.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:E.children(i)})}}})}function Cu(){let e=L();return ne({mutationFn:t=>x("move",t),onSuccess:(t,n)=>{let r=n.path,s=n.new_parent_path;if(r){e.invalidateQueries({queryKey:E.item(r)});let i=r.split("/");i.pop();let o=i.join("/");o&&e.invalidateQueries({queryKey:E.children(o)})}s&&e.invalidateQueries({queryKey:E.children(s)})}})}function Eu(){let e=L();return ne({mutationFn:t=>x("link",t),onSuccess:(t,n)=>{let r=n.source_id,s=n.target_id;r&&e.invalidateQueries({queryKey:E.edges(r)}),s&&e.invalidateQueries({queryKey:E.edges(s)})}})}function Iu(e,t){let n=L(),{optimistic:r,...s}=t??{};return ne({mutationFn:i=>x(e,i),onMutate:r?async i=>{await n.cancelQueries({queryKey:r.queryKey});let o=n.getQueryData(r.queryKey);return n.setQueryData(r.queryKey,a=>r.update(a,i)),{previous:o}}:void 0,onError:(i,o,a)=>{r&&a?.previous!==void 0&&n.setQueryData(r.queryKey,a.previous),s.onError?.(i)},onSuccess:s.onSuccess,onSettled:r?()=>{n.invalidateQueries({queryKey:r.queryKey})}:void 0})}function Tu(e,t,n){let r,s,i,o=!0;if(typeof e=="string")r=e,s=t,i=n;else{s=e;let u=t;r=u.eventType,i=u.filter,o=u.enabled??!0}let a=(0,b.useRef)(s),c=(0,b.useRef)(i);(0,b.useEffect)(()=>{a.current=s,c.current=i},[s,i]),(0,b.useEffect)(()=>o?ie(r,l=>a.current(l),c.current?l=>c.current(l):void 0):void 0,[r,o])}function Au(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:o=500}=e,a=L(),c=(0,b.useRef)(s);c.current=s;let u=(0,b.useRef)(null),l=B({queryKey:t,queryFn:n,enabled:i});return(0,b.useEffect)(()=>{if(!i)return;let f=ie(r,()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{be(a,t,{exact:!0})},o)},h=>c.current?.(h)??!0);return()=>{f(),u.current&&clearTimeout(u.current)}},[r,i,o,a,JSON.stringify(t)]),l}function Kn(e){te();let t=W(),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=B({queryKey:o,staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0},queryFn:async()=>{if(!n)return null;let p=await x("resolve-arrangement",{...n,_scope_path:r});if(p?.success===!1)throw new Error(p?.error||"Arrangement could not be loaded");return p??null},enabled:s}),c=a.data??null,u=(0,b.useMemo)(()=>c?.resolved_children??[],[c]),l=c?.resolution_level??null,f=(0,b.useMemo)(()=>{let m=(c?.type_data??null)?.order;return Array.isArray(m)?m:null},[c]),h=(0,b.useCallback)(p=>{if(!f||!p?.length)return p??[];let m=_=>_.id??_.name??"",y=new Map(f.map((_,w)=>[_,w])),g=[],v=[];for(let _ of p)(y.has(m(_))?g:v).push(_);return g.sort((_,w)=>y.get(m(_))-y.get(m(w))),[...g,...v]},[f]);return{...a,arrangement:c,resolvedChildren:u,resolutionLevel:l,order:f,sourceScopeId:c?.scope_item_id??null,arrangementQueryKey:o,applyTo:h}}function ku(e){let{origin:t,originField:n,fallbackUrl:r,mintError:s,scopeId:i,scopePath:o}=e,a=te(),c=vt(),u=i??c?.scope_id??null,l=(0,b.useMemo)(()=>{if(!t)return null;let R="/accounts/",M=t.indexOf(R);if(M===-1)return null;let D=t.indexOf("/",M+R.length);return D===-1?t:t.slice(0,D)},[t]),f=o??l??c?.scope_path??null,h=n?.trim()||null,p=`${a}
1
+ /* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-11-15T22:46:38.497Z */
2
+ "use strict";var __FSAOS_GATEWAY__=(()=>{var Dl=Object.create;var zn=Object.defineProperty;var Ul=Object.getOwnPropertyDescriptor;var Kl=Object.getOwnPropertyNames;var Ll=Object.getPrototypeOf,Hl=Object.prototype.hasOwnProperty;var fo=e=>{throw TypeError(e)};var jl=(e,t,n)=>t in e?zn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Jn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),mo=(e,t)=>{for(var n in t)zn(e,n,{get:t[n],enumerable:!0})},go=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Kl(t))!Hl.call(e,s)&&s!==n&&zn(e,s,{get:()=>t[s],enumerable:!(r=Ul(t,s))||r.enumerable});return e};var ee=(e,t,n)=>(n=e!=null?Dl(Ll(e)):{},go(t||!e||!e.__esModule?zn(n,"default",{value:e,enumerable:!0}):n,e)),Bl=e=>go(zn({},"__esModule",{value:!0}),e);var J=(e,t,n)=>jl(e,typeof t!="symbol"?t+"":t,n),Hs=(e,t,n)=>t.has(e)||fo("Cannot "+n);var d=(e,t,n)=>(Hs(e,t,"read from private field"),n?n.call(e):t.get(e)),I=(e,t,n)=>t.has(e)?fo("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),S=(e,t,n,r)=>(Hs(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),F=(e,t,n)=>(Hs(e,t,"access private method"),n);var Yn=(e,t,n,r)=>({set _(s){S(e,t,s,n)},get _(){return d(e,t,r)}});var le=Jn((Up,ho)=>{ho.exports=React});var Wr=Jn((Qm,Jo)=>{Jo.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var ua=Jn((mg,ca)=>{ca.exports={createClient:window.supabase.createClient}});var Ua=Jn((Mg,Da)=>{Da.exports=ReactDOM});var tl=Jn((ky,el)=>{el.exports=ReactDOM});var lo={};mo(lo,{CHANNEL_AI_MODES:()=>xu,ComponentRenderer:()=>vu,EnforcementDeniedError:()=>Fe,FormSubmissionError:()=>Gn,GatewayRequestError:()=>he,HostSessionUnavailableError:()=>Wt,InteractionTrackingError:()=>$n,KernelProvider:()=>bu,QueryClientProvider:()=>ur,acceptInvitation:()=>xp,acceptInvite:()=>eo,answerInput:()=>ro,assignPersonalSection:()=>Ol,auth:()=>dl,awaitAnchorReady:()=>mr,awaitScopeReady:()=>wa,callTool:()=>cl,cancelInvitation:()=>Pp,cancelQueuedTurn:()=>Xu,cancelTurn:()=>Ju,clearCachedToken:()=>hi,clearSession:()=>Ri,configureGatewayReads:()=>Oa,connectHostSession:()=>xa,createAgent:()=>no,createInvitation:()=>wp,createItem:()=>il,disconnectSSE:()=>Ni,disposeVfsRealtimeWs:()=>Di,electHomeAnchor:()=>Vt,emitEvent:()=>oc,fetchChannelMessages:()=>hc,fetchChannelMessagesPage:()=>Cr,fetchChannelMessagesWithCards:()=>Rs,fetchEdgesForItem:()=>vs,fetchItemHistory:()=>Ss,fetchItemVersions:()=>Rr,fetchItems:()=>Yt,fetchMemberFocus:()=>xs,fetchOpenEnvelope:()=>Pr,fetchRecentActivity:()=>ws,fetchResolvedItems:()=>oo,fetchTimelineHistory:()=>ao,fetchTurnQueueEntries:()=>fc,fetchTypeDefinitions:()=>_s,fetchVfsChildren:()=>xr,fetchVfsChildrenPage:()=>ys,fetchVfsItem:()=>Sr,fetchVfsItemById:()=>wr,fetchVfsTree:()=>bs,gatewayCall:()=>x,getAccessToken:()=>st,getAnchor:()=>St,getAnchorRef:()=>pe,getAnchorVersion:()=>vi,getAssetUrl:()=>ll,getDefaultSort:()=>bl,getHomeAnchor:()=>ge,getInvitation:()=>Sp,getMountVersion:()=>gr,getMounts:()=>Ae,getPathSubscriptionState:()=>cc,getQueryClient:()=>q,getRequiredFormFields:()=>wl,getScope:()=>G,getScopeVersion:()=>W,getServerClockOffsetMs:()=>Ia,getServerClockSyncedAt:()=>Ta,getSessionEntry:()=>xt,hasServerClock:()=>Ea,initSession:()=>it,initVfsRealtimeWs:()=>Xt,initializeFsaos:()=>Gu,initializeWorkspace:()=>Qs,interpretSchema:()=>so,invalidateAllVfs:()=>vc,invalidateChannelMessages:()=>wc,invalidateChildren:()=>hs,invalidateItem:()=>Qi,invalidateOpenEnvelope:()=>Sc,invalidatePathAndParent:()=>yc,invalidateSubtree:()=>_c,invalidateTypes:()=>bc,inviteMember:()=>Zi,isAnchorReady:()=>wi,isChannelPath:()=>ye,isListableItemsFilter:()=>Kn,isScopeReady:()=>es,itemsFilterFromQueryFilter:()=>mc,listChildren:()=>sl,listInvitations:()=>Ep,loadMounts:()=>Zt,loadPublishedBundle:()=>du,mount:()=>pl,mountRealtimeScope:()=>Hn,normalizeItem:()=>Oe,onConnectionStateChange:()=>gs,pathSubscriptionMatches:()=>Oi,personalSectionsKey:()=>Qr,ping:()=>ac,pushChanges:()=>al,queryClient:()=>$a,readItem:()=>rl,refreshQuery:()=>Se,registerCleanup:()=>ie,rejectInvitation:()=>Rp,replaceMounts:()=>Ts,resendInvitation:()=>Cp,resetAllSdkState:()=>kn,resolvePrincipalId:()=>yu,resubscribePath:()=>lc,seatMember:()=>to,selectMount:()=>kr,serveHostSession:()=>zu,serverDeadlinePassed:()=>Aa,serverMsUntil:()=>ka,serverNow:()=>rs,setAnchor:()=>An,setCachedToken:()=>pa,setQueryClient:()=>Va,setScope:()=>ba,setupRequireShim:()=>fl,signal:()=>ul,startTracking:()=>Ns,steerTurn:()=>Yu,submitForm:()=>Zu,subscribeAnchor:()=>bi,subscribeArtifactStream:()=>Ds,subscribeMounts:()=>Zr,subscribeScope:()=>Re,subscribeToEvents:()=>oe,subscribeToPath:()=>ms,subscribeToScope:()=>Un,trackAction:()=>Vu,trackEvent:()=>tn,trackPageView:()=>Bu,unmountRealtimeScope:()=>Es,updateItem:()=>ol,uploadFile:()=>Rl,useAcceptInvite:()=>gl,useAccounts:()=>nu,useAgentTimeline:()=>Al,useAllChannels:()=>Fs,useAnswerInput:()=>_l,useArrangement:()=>Vn,useArtifactStream:()=>Tl,useAsset:()=>su,useAuth:()=>Os,useChannelMessages:()=>wu,useChannels:()=>Ru,useChildren:()=>Kc,useComponent:()=>$i,useCreate:()=>Eu,useCreateAgent:()=>yl,useDelete:()=>Au,useDmChannels:()=>Pu,useEdges:()=>Wc,useEventStream:()=>Fu,useFileUpload:()=>Cl,useIncrementalItems:()=>Vc,useInfiniteChannelMessages:()=>Su,useInfiniteChildren:()=>$c,useInfiniteItems:()=>Vi,useInviteMember:()=>ml,useItem:()=>Dc,useItemById:()=>Uc,useItemHistory:()=>Zc,useItemVersions:()=>Xc,useItems:()=>Bc,useLink:()=>Mu,useList:()=>Bi,useMemberFocus:()=>Yc,useMintedAsset:()=>Nu,useMounts:()=>ru,useMove:()=>ku,useMutation:()=>Ou,useNotifications:()=>Wi,useOpen:()=>zc,usePermission:()=>mu,usePermissions:()=>gu,usePersonalItemOrder:()=>Du,usePersonalSections:()=>ql,usePinnedItems:()=>Ml,usePrincipal:()=>_u,usePublishedComponent:()=>pu,useRealtimeQuery:()=>qu,useRecentActivity:()=>eu,useResolve:()=>jc,useResolvedItems:()=>Il,useScope:()=>tu,useScopeReady:()=>Qc,useSearch:()=>Hc,useSeatMember:()=>hl,useTheme:()=>fu,useTimelineHistory:()=>kl,useTree:()=>Lc,useType:()=>Gc,useTypeHelpers:()=>Jc,useTypes:()=>Ms,useUnreadCounts:()=>Cu,useUpdate:()=>Iu,useUpdatePrincipal:()=>Tu,vfsKeys:()=>E,waitForPathReady:()=>uc});var Fe=class e extends Error{constructor(n){let r=n.message||e.fallbackMessage(n);super(r);J(this,"name","EnforcementDeniedError");J(this,"deniedBy");J(this,"ruleKey");J(this,"displayName");J(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 Tt=ee(le(),1);var Ee=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var Ot,dt,rn,yo,Vl=(yo=class extends Ee{constructor(){super();I(this,Ot);I(this,dt);I(this,rn);S(this,rn,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){d(this,dt)||this.setEventListener(d(this,rn))}onUnsubscribe(){var t;this.hasListeners()||((t=d(this,dt))==null||t.call(this),S(this,dt,void 0))}setEventListener(t){var n;S(this,rn,t),(n=d(this,dt))==null||n.call(this),S(this,dt,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){d(this,Ot)!==t&&(S(this,Ot,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof d(this,Ot)=="boolean"?d(this,Ot):globalThis.document?.visibilityState!=="hidden"}},Ot=new WeakMap,dt=new WeakMap,rn=new WeakMap,yo),sn=new Vl;var $l={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},pt,js,_o,Wl=(_o=class{constructor(){I(this,pt,$l);I(this,js,!1)}setTimeoutProvider(e){S(this,pt,e)}setTimeout(e,t){return d(this,pt).setTimeout(e,t)}clearTimeout(e){d(this,pt).clearTimeout(e)}setInterval(e,t){return d(this,pt).setInterval(e,t)}clearInterval(e){d(this,pt).clearInterval(e)}},pt=new WeakMap,js=new WeakMap,_o),Ue=new Wl;function vo(e){setTimeout(e,0)}var Vs=typeof window>"u"||"Deno"in globalThis;function te(){}function So(e,t){return typeof e=="function"?e(t):e}function Xn(e){return typeof e=="number"&&e>=0&&e!==1/0}function Dr(e,t){return Math.max(e+(t||0)-Date.now(),0)}function qe(e,t){return typeof e=="function"?e(t):e}function ve(e,t){return typeof e=="function"?e(t):e}function Ur(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:o,stale:a}=e;if(o){if(r){if(t.queryHash!==Zn(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 Kr(e,t){let{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Ke(t.options.mutationKey)!==Ke(i))return!1}else if(!Ft(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function Zn(e,t){return(t?.queryKeyHashFn||Ke)(e)}function Ke(e){return JSON.stringify(e,(t,n)=>Bs(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 Gl=Object.prototype.hasOwnProperty;function $s(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=bo(e)&&bo(t);if(!r&&!(Bs(e)&&Bs(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 p=r?l:o[l],h=e[p],f=t[p];if(h===f){c[p]=h,(r?l<i:Gl.call(e,p))&&u++;continue}if(h===null||f===null||typeof h!="object"||typeof f!="object"){c[p]=f;continue}let m=$s(h,f,n+1);c[p]=m,m===h&&u++}return i===a&&u===i?e:c}function on(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 bo(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Bs(e){if(!wo(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!wo(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function wo(e){return Object.prototype.toString.call(e)==="[object Object]"}function xo(e){return new Promise(t=>{Ue.setTimeout(t,e)})}function er(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?$s(e,t):t}function Ro(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function Po(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var an=Symbol();function Lr(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===an?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function cn(e,t){return typeof e=="function"?e(...t):!!e}function Co(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 Le=(()=>{let e=()=>Vs;return{isServer(){return e()},setIsServer(t){e=t}}})();function tr(){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 Eo=vo;function zl(){let e=[],t=0,n=a=>{a()},r=a=>{a()},s=Eo,i=a=>{t?e.push(a):s(()=>{n(a)})},o=()=>{let a=e;e=[],a.length&&s(()=>{r(()=>{a.forEach(c=>{n(c)})})})};return{batch:a=>{let c;t++;try{c=a()}finally{t--,t||o()}return c},batchCalls:a=>(...c)=>{i(()=>{a(...c)})},schedule:i,setNotifyFunction:a=>{n=a},setBatchNotifyFunction:a=>{r=a},setScheduler:a=>{s=a}}}var j=zl();var un,ft,ln,Io,Jl=(Io=class extends Ee{constructor(){super();I(this,un,!0);I(this,ft);I(this,ln);S(this,ln,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){d(this,ft)||this.setEventListener(d(this,ln))}onUnsubscribe(){var t;this.hasListeners()||((t=d(this,ft))==null||t.call(this),S(this,ft,void 0))}setEventListener(t){var n;S(this,ln,t),(n=d(this,ft))==null||n.call(this),S(this,ft,t(this.setOnline.bind(this)))}setOnline(t){d(this,un)!==t&&(S(this,un,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return d(this,un)}},un=new WeakMap,ft=new WeakMap,ln=new WeakMap,Io),dn=new Jl;function Yl(e){return Math.min(1e3*2**e,3e4)}function Ws(e){return(e??"online")==="online"?dn.isOnline():!0}var Hr=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function jr(e){let t=!1,n=0,r,s=tr(),i=()=>s.status!=="pending",o=b=>{if(!i()){let g=new Hr(b);h(g),e.onCancel?.(g)}},a=()=>{t=!0},c=()=>{t=!1},u=()=>sn.isFocused()&&(e.networkMode==="always"||dn.isOnline())&&e.canRun(),l=()=>Ws(e.networkMode)&&e.canRun(),p=b=>{i()||(r?.(),s.resolve(b))},h=b=>{i()||(r?.(),s.reject(b))},f=()=>new Promise(b=>{r=g=>{(i()||u())&&b(g)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),m=()=>{if(i())return;let b,g=n===0?e.initialPromise:void 0;try{b=g??e.fn()}catch(y){b=Promise.reject(y)}Promise.resolve(b).then(p).catch(y=>{if(i())return;let _=e.retry??(Le.isServer()?0:3),w=e.retryDelay??Yl,R=typeof w=="function"?w(n,y):w,P=_===!0||typeof _=="number"&&n<_||typeof _=="function"&&_(n,y);if(t||!P){h(y);return}n++,e.onFail?.(n,y),xo(R).then(()=>u()?void 0:f()).then(()=>{t?h(y):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,To,Br=(To=class{constructor(){I(this,qt)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Xn(this.gcTime)&&S(this,qt,Ue.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Le.isServer()?1/0:5*60*1e3))}clearGcTimeout(){d(this,qt)!==void 0&&(Ue.clearTimeout(d(this,qt)),S(this,qt,void 0))}},qt=new WeakMap,To);var Nt,pn,Ie,Qt,ce,nr,Dt,xe,Fo,Je,Mo,Oo=(Mo=class extends Br{constructor(t){super();I(this,xe);I(this,Nt);I(this,pn);I(this,Ie);I(this,Qt);I(this,ce);I(this,nr);I(this,Dt);S(this,Dt,!1),S(this,nr,t.defaultOptions),this.setOptions(t.options),this.observers=[],S(this,Qt,t.client),S(this,Ie,d(this,Qt).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,S(this,Nt,ko(this.options)),this.state=t.state??d(this,Nt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return d(this,ce)?.promise}setOptions(t){if(this.options={...d(this,nr),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=ko(this.options);n.data!==void 0&&(this.setState(Ao(n.data,n.dataUpdatedAt)),S(this,Nt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&d(this,Ie).remove(this)}setData(t,n){let r=er(this.state.data,t,this.options);return F(this,xe,Je).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){F(this,xe,Je).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=d(this,ce)?.promise;return d(this,ce)?.cancel(t),n?n.then(te).catch(te):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return d(this,Nt)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>ve(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===an||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>qe(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!Dr(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),d(this,ce)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),d(this,ce)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),d(this,Ie).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(d(this,ce)&&(d(this,Dt)||F(this,xe,Fo).call(this)?d(this,ce).cancel({revert:!0}):d(this,ce).cancelRetry()),this.scheduleGc()),d(this,Ie).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||F(this,xe,Je).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&d(this,ce)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(d(this,ce))return d(this,ce).continueRetry(),d(this,ce).promise}if(t&&this.setOptions(t),!this.options.queryFn){let c=this.observers.find(u=>u.options.queryFn);c&&this.setOptions(c.options)}let r=new AbortController,s=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(S(this,Dt,!0),r.signal)})},i=()=>{let c=Lr(this.options,n),l=(()=>{let p={client:d(this,Qt),queryKey:this.queryKey,meta:this.meta};return s(p),p})();return S(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:d(this,Qt),state:this.state,fetchFn:i};return s(c),c})();this.options.behavior?.onFetch(a,this),S(this,pn,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&F(this,xe,Je).call(this,{type:"fetch",meta:a.fetchOptions?.meta}),S(this,ce,jr({initialPromise:n?.initialPromise,fn:a.fetchFn,onCancel:c=>{c instanceof Hr&&c.revert&&this.setState({...d(this,pn),fetchStatus:"idle"}),r.abort()},onFail:(c,u)=>{F(this,xe,Je).call(this,{type:"failed",failureCount:c,error:u})},onPause:()=>{F(this,xe,Je).call(this,{type:"pause"})},onContinue:()=>{F(this,xe,Je).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0}));try{let c=await d(this,ce).start();if(c===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(c),d(this,Ie).config.onSuccess?.(c,this),d(this,Ie).config.onSettled?.(c,this.state.error,this),c}catch(c){if(c instanceof Hr){if(c.silent)return d(this,ce).promise;if(c.revert){if(this.state.data===void 0)throw c;return this.state.data}}throw F(this,xe,Je).call(this,{type:"error",error:c}),d(this,Ie).config.onError?.(c,this),d(this,Ie).config.onSettled?.(this.state.data,c,this),c}finally{this.scheduleGc()}}},Nt=new WeakMap,pn=new WeakMap,Ie=new WeakMap,Qt=new WeakMap,ce=new WeakMap,nr=new WeakMap,Dt=new WeakMap,xe=new WeakSet,Fo=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},Je=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,...Gs(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...Ao(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return S(this,pn,t.manual?s:void 0),s;case"error":let i=t.error;return{...r,error:i,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),j.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),d(this,Ie).notify({query:this,type:"updated",action:t})})},Mo);function Gs(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Ws(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Ao(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function ko(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 be,U,sr,me,Ut,fn,Ye,mt,ir,mn,gn,Kt,Lt,gt,hn,H,rr,zs,Js,Ys,Xs,Zs,ei,ti,Do,Qo,or=(Qo=class extends Ee{constructor(t,n){super();I(this,H);I(this,be);I(this,U);I(this,sr);I(this,me);I(this,Ut);I(this,fn);I(this,Ye);I(this,mt);I(this,ir);I(this,mn);I(this,gn);I(this,Kt);I(this,Lt);I(this,gt);I(this,hn,new Set);this.options=n,S(this,be,t),S(this,mt,null),S(this,Ye,tr()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(d(this,U).addObserver(this),qo(d(this,U),this.options)?F(this,H,rr).call(this):this.updateResult(),F(this,H,Xs).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return ni(d(this,U),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return ni(d(this,U),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,F(this,H,Zs).call(this),F(this,H,ei).call(this),d(this,U).removeObserver(this)}setOptions(t){let n=this.options,r=d(this,U);if(this.options=d(this,be).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof ve(this.options.enabled,d(this,U))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");F(this,H,ti).call(this),d(this,U).setOptions(this.options),n._defaulted&&!on(this.options,n)&&d(this,be).getQueryCache().notify({type:"observerOptionsUpdated",query:d(this,U),observer:this});let s=this.hasListeners();s&&No(d(this,U),r,this.options,n)&&F(this,H,rr).call(this),this.updateResult(),s&&(d(this,U)!==r||ve(this.options.enabled,d(this,U))!==ve(n.enabled,d(this,U))||qe(this.options.staleTime,d(this,U))!==qe(n.staleTime,d(this,U)))&&F(this,H,zs).call(this);let i=F(this,H,Js).call(this);s&&(d(this,U)!==r||ve(this.options.enabled,d(this,U))!==ve(n.enabled,d(this,U))||i!==d(this,gt))&&F(this,H,Ys).call(this,i)}getOptimisticResult(t){let n=d(this,be).getQueryCache().build(d(this,be),t),r=this.createResult(n,t);return Zl(this,r)&&(S(this,me,r),S(this,fn,this.options),S(this,Ut,d(this,U).state)),r}getCurrentResult(){return d(this,me)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&d(this,Ye).status==="pending"&&d(this,Ye).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){d(this,hn).add(t)}getCurrentQuery(){return d(this,U)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=d(this,be).defaultQueryOptions(t),r=d(this,be).getQueryCache().build(d(this,be),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return F(this,H,rr).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),d(this,me)))}createResult(t,n){let r=d(this,U),s=this.options,i=d(this,me),o=d(this,Ut),a=d(this,fn),u=t!==r?t.state:d(this,sr),{state:l}=t,p={...l},h=!1,f;if(n._optimisticResults){let A=this.hasListeners(),k=!A&&qo(t,n),T=A&&No(t,r,n,s);(k||T)&&(p={...p,...Gs(l.data,t.options)}),n._optimisticResults==="isRestoring"&&(p.fetchStatus="idle")}let{error:m,errorUpdatedAt:b,status:g}=p;f=p.data;let y=!1;if(n.placeholderData!==void 0&&f===void 0&&g==="pending"){let A;i?.isPlaceholderData&&n.placeholderData===a?.placeholderData?(A=i.data,y=!0):A=typeof n.placeholderData=="function"?n.placeholderData(d(this,gn)?.state.data,d(this,gn)):n.placeholderData,A!==void 0&&(g="success",f=er(i?.data,A,n),h=!0)}if(n.select&&f!==void 0&&!y)if(i&&f===o?.data&&n.select===d(this,ir))f=d(this,mn);else try{S(this,ir,n.select),f=n.select(f),f=er(i?.data,f,n),S(this,mn,f),S(this,mt,null)}catch(A){S(this,mt,A)}d(this,mt)&&(m=d(this,mt),f=d(this,mn),b=Date.now(),g="error");let _=p.fetchStatus==="fetching",w=g==="pending",R=g==="error",P=w&&_,M=f!==void 0,C={status:g,fetchStatus:p.fetchStatus,isPending:w,isSuccess:g==="success",isError:R,isInitialLoading:P,isLoading:P,data:f,dataUpdatedAt:p.dataUpdatedAt,error:m,errorUpdatedAt:b,failureCount:p.fetchFailureCount,failureReason:p.fetchFailureReason,errorUpdateCount:p.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:p.dataUpdateCount>u.dataUpdateCount||p.errorUpdateCount>u.errorUpdateCount,isFetching:_,isRefetching:_&&!w,isLoadingError:R&&!M,isPaused:p.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:R&&M,isStale:ri(t,n),refetch:this.refetch,promise:d(this,Ye),isEnabled:ve(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let A=C.data!==void 0,k=C.status==="error"&&!A,T=K=>{k?K.reject(C.error):A&&K.resolve(C.data)},O=()=>{let K=S(this,Ye,C.promise=tr());T(K)},Q=d(this,Ye);switch(Q.status){case"pending":t.queryHash===r.queryHash&&T(Q);break;case"fulfilled":(k||C.data!==Q.value)&&O();break;case"rejected":(!k||C.error!==Q.reason)&&O();break}}return C}updateResult(){let t=d(this,me),n=this.createResult(d(this,U),this.options);if(S(this,Ut,d(this,U).state),S(this,fn,this.options),d(this,Ut).data!==void 0&&S(this,gn,d(this,U)),on(n,t))return;S(this,me,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!d(this,hn).size)return!0;let o=new Set(i??d(this,hn));return this.options.throwOnError&&o.add("error"),Object.keys(d(this,me)).some(a=>{let c=a;return d(this,me)[c]!==t[c]&&o.has(c)})};F(this,H,Do).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&F(this,H,Xs).call(this)}},be=new WeakMap,U=new WeakMap,sr=new WeakMap,me=new WeakMap,Ut=new WeakMap,fn=new WeakMap,Ye=new WeakMap,mt=new WeakMap,ir=new WeakMap,mn=new WeakMap,gn=new WeakMap,Kt=new WeakMap,Lt=new WeakMap,gt=new WeakMap,hn=new WeakMap,H=new WeakSet,rr=function(t){F(this,H,ti).call(this);let n=d(this,U).fetch(this.options,t);return t?.throwOnError||(n=n.catch(te)),n},zs=function(){F(this,H,Zs).call(this);let t=qe(this.options.staleTime,d(this,U));if(Le.isServer()||d(this,me).isStale||!Xn(t))return;let r=Dr(d(this,me).dataUpdatedAt,t)+1;S(this,Kt,Ue.setTimeout(()=>{d(this,me).isStale||this.updateResult()},r))},Js=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(d(this,U)):this.options.refetchInterval)??!1},Ys=function(t){F(this,H,ei).call(this),S(this,gt,t),!(Le.isServer()||ve(this.options.enabled,d(this,U))===!1||!Xn(d(this,gt))||d(this,gt)===0)&&S(this,Lt,Ue.setInterval(()=>{(this.options.refetchIntervalInBackground||sn.isFocused())&&F(this,H,rr).call(this)},d(this,gt)))},Xs=function(){F(this,H,zs).call(this),F(this,H,Ys).call(this,F(this,H,Js).call(this))},Zs=function(){d(this,Kt)!==void 0&&(Ue.clearTimeout(d(this,Kt)),S(this,Kt,void 0))},ei=function(){d(this,Lt)!==void 0&&(Ue.clearInterval(d(this,Lt)),S(this,Lt,void 0))},ti=function(){let t=d(this,be).getQueryCache().build(d(this,be),this.options);if(t===d(this,U))return;let n=d(this,U);S(this,U,t),S(this,sr,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},Do=function(t){j.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(d(this,me))}),d(this,be).getQueryCache().notify({query:d(this,U),type:"observerResultsUpdated"})})},Qo);function Xl(e,t){return ve(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function qo(e,t){return Xl(e,t)||e.state.data!==void 0&&ni(e,t,t.refetchOnMount)}function ni(e,t,n){if(ve(t.enabled,e)!==!1&&qe(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&ri(e,t)}return!1}function No(e,t,n,r){return(e!==t||ve(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&ri(e,n)}function ri(e,t){return ve(t.enabled,e)!==!1&&e.isStaleByTime(qe(t.staleTime,e))}function Zl(e,t){return!on(e.getCurrentResult(),t)}function yn(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,p=m=>{Co(m,()=>t.signal,()=>l=!0)},h=Lr(t.options,t.fetchOptions),f=async(m,b,g)=>{if(l)return Promise.reject();if(b==null&&m.pages.length)return Promise.resolve(m);let _=(()=>{let M={client:t.client,queryKey:t.queryKey,pageParam:b,direction:g?"backward":"forward",meta:t.options.meta};return p(M),M})(),w=await h(_),{maxPages:R}=t.options,P=g?Po:Ro;return{pages:P(m.pages,w,R),pageParams:P(m.pageParams,b,R)}};if(s&&i.length){let m=s==="backward",b=m?Uo:si,g={pages:i,pageParams:o},y=b(r,g);a=await f(g,y,m)}else{let m=e??i.length;do{let b=c===0?o[0]??r.initialPageParam:si(r,a);if(c>0&&b==null)break;a=await f(a,b),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 si(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 Uo(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function Ko(e,t){return t?si(e,t)!=null:!1}function Lo(e,t){return!t||!e.getPreviousPageParam?!1:Uo(e,t)!=null}var ii=class extends or{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:yn()})}getOptimisticResult(e){return e.behavior=yn(),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",p=o&&c==="backward",h=s&&c==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Ko(t,n.data),hasPreviousPage:Lo(t,n.data),isFetchNextPageError:u,isFetchingNextPage:l,isFetchPreviousPageError:p,isFetchingPreviousPage:h,isRefetchError:a&&!u&&!p,isRefetching:i&&!l&&!h}}};var ar,He,de,Ht,je,ht,Ho,jo=(Ho=class extends Br{constructor(t){super();I(this,je);I(this,ar);I(this,He);I(this,de);I(this,Ht);S(this,ar,t.client),this.mutationId=t.mutationId,S(this,de,t.mutationCache),S(this,He,[]),this.state=t.state||oi(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){d(this,He).includes(t)||(d(this,He).push(t),this.clearGcTimeout(),d(this,de).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){S(this,He,d(this,He).filter(n=>n!==t)),this.scheduleGc(),d(this,de).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){d(this,He).length||(this.state.status==="pending"?this.scheduleGc():d(this,de).remove(this))}continue(){return d(this,Ht)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{F(this,je,ht).call(this,{type:"continue"})},r={client:d(this,ar),meta:this.options.meta,mutationKey:this.options.mutationKey};S(this,Ht,jr({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(o,a)=>{F(this,je,ht).call(this,{type:"failed",failureCount:o,error:a})},onPause:()=>{F(this,je,ht).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>d(this,de).canRun(this)}));let s=this.state.status==="pending",i=!d(this,Ht).canStart();try{if(s)n();else{F(this,je,ht).call(this,{type:"pending",variables:t,isPaused:i}),d(this,de).config.onMutate&&await d(this,de).config.onMutate(t,this,r);let a=await this.options.onMutate?.(t,r);a!==this.state.context&&F(this,je,ht).call(this,{type:"pending",context:a,variables:t,isPaused:i})}let o=await d(this,Ht).start();return await d(this,de).config.onSuccess?.(o,t,this.state.context,this,r),await this.options.onSuccess?.(o,t,this.state.context,r),await d(this,de).config.onSettled?.(o,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(o,null,t,this.state.context,r),F(this,je,ht).call(this,{type:"success",data:o}),o}catch(o){try{await d(this,de).config.onError?.(o,t,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onError?.(o,t,this.state.context,r)}catch(a){Promise.reject(a)}try{await d(this,de).config.onSettled?.(void 0,o,this.state.variables,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onSettled?.(void 0,o,t,this.state.context,r)}catch(a){Promise.reject(a)}throw F(this,je,ht).call(this,{type:"error",error:o}),o}finally{d(this,de).runNext(this)}}},ar=new WeakMap,He=new WeakMap,de=new WeakMap,Ht=new WeakMap,je=new WeakSet,ht=function(t){let n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),j.batch(()=>{d(this,He).forEach(r=>{r.onMutationUpdate(t)}),d(this,de).notify({mutation:this,type:"updated",action:t})})},Ho);function oi(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Xe,Ne,cr,Bo,Vo=(Bo=class extends Ee{constructor(t={}){super();I(this,Xe);I(this,Ne);I(this,cr);this.config=t,S(this,Xe,new Set),S(this,Ne,new Map),S(this,cr,0)}build(t,n,r){let s=new jo({client:t,mutationCache:this,mutationId:++Yn(this,cr)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){d(this,Xe).add(t);let n=Vr(t);if(typeof n=="string"){let r=d(this,Ne).get(n);r?r.push(t):d(this,Ne).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(d(this,Xe).delete(t)){let n=Vr(t);if(typeof n=="string"){let r=d(this,Ne).get(n);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&d(this,Ne).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=Vr(t);if(typeof n=="string"){let s=d(this,Ne).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=Vr(t);return typeof n=="string"?d(this,Ne).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){j.batch(()=>{d(this,Xe).forEach(t=>{this.notify({type:"removed",mutation:t})}),d(this,Xe).clear(),d(this,Ne).clear()})}getAll(){return Array.from(d(this,Xe))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Kr(n,r))}findAll(t={}){return this.getAll().filter(n=>Kr(t,n))}notify(t){j.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){let t=this.getAll().filter(n=>n.state.isPaused);return j.batch(()=>Promise.all(t.map(n=>n.continue().catch(te))))}},Xe=new WeakMap,Ne=new WeakMap,cr=new WeakMap,Bo);function Vr(e){return e.options.scope?.id}var Ze,yt,we,et,tt,$r,ai,$o,ci=($o=class extends Ee{constructor(t,n){super();I(this,tt);I(this,Ze);I(this,yt);I(this,we);I(this,et);S(this,Ze,t),this.setOptions(n),this.bindMethods(),F(this,tt,$r).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let n=this.options;this.options=d(this,Ze).defaultMutationOptions(t),on(this.options,n)||d(this,Ze).getMutationCache().notify({type:"observerOptionsUpdated",mutation:d(this,we),observer:this}),n?.mutationKey&&this.options.mutationKey&&Ke(n.mutationKey)!==Ke(this.options.mutationKey)?this.reset():d(this,we)?.state.status==="pending"&&d(this,we).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||d(this,we)?.removeObserver(this)}onMutationUpdate(t){F(this,tt,$r).call(this),F(this,tt,ai).call(this,t)}getCurrentResult(){return d(this,yt)}reset(){d(this,we)?.removeObserver(this),S(this,we,void 0),F(this,tt,$r).call(this),F(this,tt,ai).call(this)}mutate(t,n){return S(this,et,n),d(this,we)?.removeObserver(this),S(this,we,d(this,Ze).getMutationCache().build(d(this,Ze),this.options)),d(this,we).addObserver(this),d(this,we).execute(t)}},Ze=new WeakMap,yt=new WeakMap,we=new WeakMap,et=new WeakMap,tt=new WeakSet,$r=function(){let t=d(this,we)?.state??oi();S(this,yt,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},ai=function(t){j.batch(()=>{if(d(this,et)&&this.hasListeners()){let n=d(this,yt).variables,r=d(this,yt).context,s={client:d(this,Ze),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{d(this,et).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{d(this,et).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{d(this,et).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{d(this,et).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(d(this,yt))})})},$o);var Be,Wo,Go=(Wo=class extends Ee{constructor(t={}){super();I(this,Be);this.config=t,S(this,Be,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??Zn(s,n),o=this.get(i);return o||(o=new Oo({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(o)),o}add(t){d(this,Be).has(t.queryHash)||(d(this,Be).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=d(this,Be).get(t.queryHash);n&&(t.destroy(),n===t&&d(this,Be).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){j.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return d(this,Be).get(t)}getAll(){return[...d(this,Be).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Ur(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>Ur(t,r)):n}notify(t){j.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){j.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){j.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Be=new WeakMap,Wo);var ne,_t,vt,_n,vn,bt,bn,wn,zo,ui=(zo=class{constructor(e={}){I(this,ne);I(this,_t);I(this,vt);I(this,_n);I(this,vn);I(this,bt);I(this,bn);I(this,wn);S(this,ne,e.queryCache||new Go),S(this,_t,e.mutationCache||new Vo),S(this,vt,e.defaultOptions||{}),S(this,_n,new Map),S(this,vn,new Map),S(this,bt,0)}mount(){Yn(this,bt)._++,d(this,bt)===1&&(S(this,bn,sn.subscribe(async e=>{e&&(await this.resumePausedMutations(),d(this,ne).onFocus())})),S(this,wn,dn.subscribe(async e=>{e&&(await this.resumePausedMutations(),d(this,ne).onOnline())})))}unmount(){var e,t;Yn(this,bt)._--,d(this,bt)===0&&((e=d(this,bn))==null||e.call(this),S(this,bn,void 0),(t=d(this,wn))==null||t.call(this),S(this,wn,void 0))}isFetching(e){return d(this,ne).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return d(this,_t).findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return d(this,ne).get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=d(this,ne).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(qe(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return d(this,ne).findAll(e).map(({queryKey:t,state:n})=>{let r=n.data;return[t,r]})}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=d(this,ne).get(r.queryHash)?.state.data,o=So(t,i);if(o!==void 0)return d(this,ne).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return j.batch(()=>d(this,ne).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return d(this,ne).get(t.queryHash)?.state}removeQueries(e){let t=d(this,ne);j.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=d(this,ne);return j.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=j.batch(()=>d(this,ne).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(te).catch(te)}invalidateQueries(e,t={}){return j.batch(()=>(d(this,ne).findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=j.batch(()=>d(this,ne).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(te)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(te)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=d(this,ne).build(this,t);return n.isStaleByTime(qe(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(te).catch(te)}fetchInfiniteQuery(e){return e.behavior=yn(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(te).catch(te)}ensureInfiniteQueryData(e){return e.behavior=yn(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return dn.isOnline()?d(this,_t).resumePausedMutations():Promise.resolve()}getQueryCache(){return d(this,ne)}getMutationCache(){return d(this,_t)}getDefaultOptions(){return d(this,vt)}setDefaultOptions(e){S(this,vt,e)}setQueryDefaults(e,t){d(this,_n).set(Ke(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...d(this,_n).values()],n={};return t.forEach(r=>{Ft(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){d(this,vn).set(Ke(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...d(this,vn).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={...d(this,vt).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Zn(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===an&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...d(this,vt).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){d(this,ne).clear(),d(this,_t).clear()}},ne=new WeakMap,_t=new WeakMap,vt=new WeakMap,_n=new WeakMap,vn=new WeakMap,bt=new WeakMap,bn=new WeakMap,wn=new WeakMap,zo);var Sn=ee(le(),1),Yo=ee(Wr(),1),li=Sn.createContext(void 0),L=e=>{let t=Sn.useContext(li);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},ur=({client:e,children:t})=>(Sn.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,Yo.jsx)(li.Provider,{value:e,children:t}));var Gr=ee(le(),1),Xo=Gr.createContext(!1),Zo=()=>Gr.useContext(Xo),Um=Xo.Provider;var lr=ee(le(),1),ed=ee(Wr(),1);function td(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var nd=lr.createContext(td()),ea=()=>lr.useContext(nd);var ta=ee(le(),1);var na=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?cn(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},ra=e=>{ta.useEffect(()=>{e.clearReset()},[e])},sa=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||cn(n,[e.error,r]));var ia=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))}},oa=(e,t)=>e.isLoading&&e.isFetching&&!t,aa=(e,t)=>e?.suspense&&t.isPending,di=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var wt=ee(le(),1);function zr(e,t,n){let r=Zo(),s=ea(),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",ia(o),na(o,s,a),ra(s);let c=!i.getQueryCache().get(o.queryHash),[u]=wt.useState(()=>new t(i,o)),l=u.getOptimisticResult(o),p=!r&&e.subscribed!==!1;if(wt.useSyncExternalStore(wt.useCallback(h=>{let f=p?u.subscribe(j.batchCalls(h)):te;return u.updateResult(),f},[u,p]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),wt.useEffect(()=>{u.setOptions(o)},[o,u]),aa(o,l))throw di(o,u,s);if(sa({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&&!Le.isServer()&&oa(l,r)&&(c?di(o,u,s):a?.promise)?.catch(te).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?l:u.trackResult(l)}function B(e,t){return zr(e,or,t)}var nt=ee(le(),1);function se(e,t){let n=L(t),[r]=nt.useState(()=>new ci(n,e));nt.useEffect(()=>{r.setOptions(e)},[r,e]);let s=nt.useSyncExternalStore(nt.useCallback(o=>r.subscribe(j.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=nt.useCallback((o,a)=>{r.mutate(o,a).catch(te)},[r]);if(s.error&&cn(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function dr(e,t){return zr(e,ii,t)}var la=ee(ua(),1),xn=typeof window<"u"&&window.__FSAOS_CONFIG__||{},jt=Array.isArray(xn.sources)?xn.sources:[],rt=xn.hostSession===!0,rd=xn.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",sd=xn.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",Te=xn.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",$=(0,la.createClient)(rd,sd,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var pr=null,Jr=0,da,gi,Yr=!1;da=new Promise(e=>{gi=e});$.auth.onAuthStateChange((e,t)=>{t?.access_token?(pr=t.access_token,Jr=t.expires_at??Math.floor(Date.now()/1e3)+3600):(pr=null,Jr=0),Yr||(Yr=!0,gi())});setTimeout(()=>{Yr||(Yr=!0,gi())},5e3);function pa(e,t){pr=e,Jr=t??Math.floor(Date.now()/1e3)+3600}function hi(){pr=null,Jr=0}async function st(){let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{};if(rt)return null;if(e.embedToken){if(typeof e.embedToken=="function")try{return await e.embedToken()??null}catch{return null}return e.embedToken}return await da,pr}var En=null,In=null,fa=0,pi=new Set,yi,fr,Tn=!1;yi=new Promise(e=>{fr=e});function _i(){fa++,pi.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function An(e){let t=typeof e=="string"?e:e.path,n=En!==t||In?.id!==(typeof e=="string"?void 0:e.id);En=t,In=typeof e=="string"?null:e,typeof e!="string"&&!Bt.some(r=>r.id===e.id)&&(Bt=[...Bt,e],Si()),Tn||(Tn=!0,fr()),n&&_i()}function St(){return En}function pe(){return In}function vi(){return fa}function bi(e){return pi.add(e),()=>{pi.delete(e)}}function mr(){return yi}function wi(){return Tn}var Xr=null;function Vt(e,t={}){if(Xr){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}Xr=e,t.activate!==!1&&An(e)}function ge(){return Xr}var Bt=[],fi=new Set,ma=0;function Si(){ma++,fi.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function Ae(){return Bt}function gr(){return ma}function Zr(e){return fi.add(e),()=>{fi.delete(e)}}function ga(e,t){let n=JSON.stringify(Bt)!==JSON.stringify(e),r=En!==t.path||In?.id!==t.id;Bt=e,En=t.path,In=t,Tn||(Tn=!0,fr()),n&&Si(),r&&_i()}var Pn=null,Rn=null,Cn=0,mi=new Set,ha=0;function ya(){ha++,mi.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Session listener error:",t)}})}function Y(){return Cn}function xi(){return ha}function _a(e){return mi.add(e),()=>{mi.delete(e)}}async function it(){if(Pn)return Pn;if(Rn)return Rn;let e=Cn;return Rn=(async()=>{let t=$t(),n=await st();if(e!==Cn)throw new Error("Session changed during initialization");let r={};n&&(r.Authorization=`Bearer ${n}`);let s=await fetch(`${Te}/d/${t}/init`,{method:"GET",headers:r});if(!s.ok)throw new Error(`Session init failed: ${s.status} ${s.statusText}`);let i=await s.json();if(e!==Cn)throw new Error("Session changed during initialization");let o=i.entry||i;return Pn={scope_id:o.scope_id,scope_path:o.scope_path,instance_path:o.instance_path||"/root",fractal_id:o.fractal_id||null,instance_name:o.instance_name||null,display_name:o.scope_display_name||o.display_name||null,principal_id:o.principal_id||null},ya(),Pn})().catch(t=>{throw e===Cn&&(Rn=null),t}),Rn}function xt(){return Pn}function Ri(){Cn++,Pn=null,Rn=null,En=null,In=null,Xr=null,Bt=[],ya()}var va=[];function ie(e){va.push(e)}function kn(){Ri(),hi(),fr(),Tn=!1,yi=new Promise(e=>{fr=e}),_i(),Si();for(let e of va)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function $t(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var ba=An,G=St,W=vi,Re=bi,wa=mr,es=wi;var Gt="host-session",id=5e3;function Pi(e){return typeof e=="object"&&e!==null&&e.fsaos===Gt&&typeof e.kind=="string"}var Wt=class extends Error{constructor(){super(...arguments);J(this,"name","HostSessionUnavailableError")}},ts=null,od=0,ns=new Map;function Sa(){return ts||(ts=new Promise((e,t)=>{if(!rt){t(new Wt("This page was not started with hostSession."));return}if(typeof window>"u"||!window.parent||window.parent===window){t(new Wt("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 Wt("The window around this page did not sign it in. Open it from the app that owns it.")))},id);function i(o){if(o.source!==n||!Pi(o.data))return;let a=o.data;if(r===null){if(a.kind!=="welcome")return;r=o.origin,clearTimeout(s),a.anchor&&An(a.anchor),e({host:n,origin:r,item:a.item??null});return}if(o.origin!==r||a.kind!=="result")return;let c=ns.get(a.id);c&&(ns.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"},"*")}),ts)}async function xa(){let{item:e}=await Sa();return{item:e}}async function Ra(e,t,n){if(n?.aborted)throw new DOMException("Read cancelled","AbortError");let{host:r,origin:s}=await Sa();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)}-${(++od).toString(36)}`,u=()=>{ns.delete(c),a(new DOMException("Read cancelled","AbortError"))};ns.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 Ci=0,Pa=!1,Ca=0;function Ei(e){if(typeof e!="string")return;let t=Date.parse(e);Number.isNaN(t)||(Ci=t-Date.now(),Pa=!0,Ca=Date.now())}function rs(){return Date.now()+Ci}function Ea(){return Pa}function Ia(){return Ci}function Ta(){return Ca}function Aa(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:rs()>=t}function ka(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Math.max(0,t-rs())}var Mn,ke=new Map,zt=[],Ii=0,Ti={foreground:0,normal:1,background:2},ss=()=>performance.now(),Ai=()=>new DOMException("Read cancelled","AbortError");function Oa(e={}){Mn={concurrency:Math.max(1,Math.min(16,Math.floor(e.concurrency??6))),timeoutMs:Math.max(1e3,e.timeoutMs??15e3),onTiming:e.onTiming},os()}function Fa(){for(let e of ke.values()){e.controller.abort();for(let t of e.consumers)t.detach(),t.reject(Ai());e.consumers.clear(),e.timer&&clearTimeout(e.timer)}ke.clear(),zt.length=0}function qa(e,t){return e==="query"?!("materialize"in t):["read","list","search","resolve","resolve-items","get-channel-messages","list-memberships"].includes(e)}function is(e){return Array.isArray(e)?`[${e.map(is).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)}:${is(n)}`).join(",")}}`:JSON.stringify(e)}function Na(e,t,n,r){if(n.signal?.aborted)return Promise.reject(Ai());if(!Mn)return r(n.signal);let s=ke.get(e);if(s)Ti[n.priority??"normal"]<Ti[s.priority]&&(s.priority=n.priority??"normal");else{s={key:e,method:t,priority:n.priority??"normal",queuedAt:ss(),controller:new AbortController,consumers:new Set,run:r},ke.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(),ke.get(a.key)===a&&ke.delete(a.key),Ma(a)},Mn.timeoutMs)}let i=s,o=new Promise((a,c)=>{let u=()=>{l.detach(),i.consumers.delete(l),c(Ai()),i.consumers.size||(i.controller.abort(),ke.get(i.key)===i&&ke.delete(i.key),Ma(i))},l={resolve:p=>a(structuredClone(p)),reject:c,detach:()=>n.signal?.removeEventListener("abort",u)};i.consumers.add(l),n.signal?.addEventListener("abort",u,{once:!0})});return os(),o}function Ma(e){let t=zt.indexOf(e);t>=0&&(zt.splice(t,1),ke.get(e.key)===e&&ke.delete(e.key),e.timer&&clearTimeout(e.timer)),os()}function os(){if(Mn)for(;Ii<Mn.concurrency&&zt.length;){let e=r=>Ti[r.priority]-Math.floor((ss()-r.queuedAt)/2e3);zt.sort((r,s)=>e(r)-e(s)||r.queuedAt-s.queuedAt);let t=zt.shift();if(!t.consumers.size)continue;Ii++,t.startedAt=ss();let n="success";Promise.resolve().then(()=>t.run(t.controller.signal)).then(r=>{for(let s of t.consumers)s.detach(),s.resolve(r)},r=>{n=t.controller.signal.aborted?"aborted":"error";for(let s of t.consumers)s.detach(),s.reject(r)}).finally(()=>{t.timer&&clearTimeout(t.timer),t.consumers.clear(),ke.get(t.key)===t&&ke.delete(t.key),Ii--;try{Mn?.onTiming?.({method:t.method,priority:t.priority,queueMs:Math.round(t.startedAt-t.queuedAt),requestMs:Math.round(ss()-t.startedAt),outcome:n})}catch{}os()})}}ie(Fa);var ad=new Set(["list-memberships","init"]),he=class extends Error{constructor(n){let r=typeof n.payload?.error=="string"?n.payload.error.trim():"",s=typeof n.payload?.message=="string"?n.payload.message.trim():"",i=n.responseBody.trim()||`Gateway HTTP error: ${n.status} ${n.statusText}`.trim(),o=r&&s?`${r}: ${s}`:s||r||i;super(o);J(this,"name","GatewayRequestError");J(this,"method");J(this,"status");J(this,"statusText");J(this,"payload");J(this,"responseBody");this.method=n.method,this.status=n.status,this.statusText=n.statusText,this.payload=n.payload,this.responseBody=n.responseBody}};async function x(e,t={},n={}){if(rt)return cd(e,t,n);let r=Y(),s=St(),i=$t(),o=`${Te}/d/${i}`,a={"Content-Type":"application/json"},c=await Qa(st(),n.signal);if(r!==Y())throw new Error("Session changed before gateway request");if(c&&(a.Authorization=`Bearer ${c}`),!ad.has(e)&&!t._scope_path&&await Qa(mr(),n.signal),r!==Y())throw new Error("Session changed before gateway request");let u={...t},l=xt();!u.domain_scope_id&&l?.scope_id&&(u.domain_scope_id=l.scope_id);let p=s??St();!u._scope_path&&p&&(u._scope_path=p);let h=async f=>{if(r!==Y())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})}),b=await m.text();if(r!==Y())throw new Error("Session changed during gateway request");let g=null;if(b)try{g=JSON.parse(b)}catch{}if(!m.ok||!g)throw new he({method:e,status:m.status,statusText:m.statusText,payload:g,responseBody:b});if(g.success===!1){let y=g.error||"",_=g.denied_by||g.error_type||"";throw _==="rule"||_==="access"||_==="entitlement"||y==="RULE_DENIED"||y==="ACCESS_DENIED"||y==="PERMISSION_DENIED"||y==="ENTITLEMENT_REQUIRED"?new Fe(g):new he({method:e,status:m.status,statusText:m.statusText,payload:g,responseBody:b})}return g&&g.server_now!==void 0&&Ei(g.server_now),g};return qa(e,u)?Na(is([r,i,c,e,u]),e,n,h):h(n.signal)}async function cd(e,t,n){let r=await Ra(e,t,n.signal);if(r.ok){let o=r.response?.server_now;return o!==void 0&&Ei(o),r.response}let s=r.error;if(s.kind==="denied")throw new Fe(s.payload);if(s.kind==="gateway")throw new he({method:s.method,status:s.status,statusText:s.statusText,payload:s.payload,responseBody:s.responseBody});let i=new Error(s.message);throw i.name=s.name,i}function Qa(e,t){return t?t.aborted?Promise.reject(new DOMException("Read cancelled","AbortError")):new Promise((n,r)=>{let s=()=>r(new DOMException("Read cancelled","AbortError"));t.addEventListener("abort",s,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",s))}):e}var v=ee(le(),1),Yd=ee(Ua(),1),Xd=ee(Wr(),1);var Ka=new WeakMap;function Se(e,t,n={}){let r=n.exact===!0,s=()=>e.invalidateQueries({queryKey:t,exact:r},{cancelRefetch:!1}),i=e.getQueryCache().findAll({queryKey:t,exact:r,fetchStatus:"fetching"}).flatMap(p=>p.promise?[p.promise]:[]);if(i.length===0)return s();let o=`${r?"=":"^"}${JSON.stringify(t)}`,a=Ka.get(e);a||(a=new Map,Ka.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 ye(e,t){return typeof e=="string"&&(e===t||e.startsWith(`${t}/`))}var as=new WeakMap,La=e=>e.meta?.arrangementRealtime===!0;function ot(e,t){let n=e.getQueryCache().find({queryKey:t,exact:!0});if(!n)return;let r=as.get(e);r||(r=new Map,as.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&&Se(e,t,{exact:!0})},250))}function Ha(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){if(!La(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")&&ot(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)))&&ot(e,n.queryKey)}}function ja(e){for(let t of e.getQueryCache().getAll())La(t)&&t.state.data!==void 0&&ot(e,t.queryKey)}function Ba(e){as.get(e)?.forEach(clearTimeout),as.delete(e)}var at=null;ie(()=>{at&&(at.cancelQueries({queryKey:["vfs"]}),at.removeQueries({queryKey:["vfs"]}))});function Va(e){if(at&&at!==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.");at=e}function q(){return at||(at=new ui({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),at}var $a=new Proxy({},{get(e,t,n){let r=q(),s=r[t];return typeof s=="function"?s.bind(r):s}});var cs=new WeakMap;function ki(e){return e.meta?.infiniteItemsRealtime?.filter}function ud(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 ld(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 dd(e,t,n){if(ud(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&&!ye(n.path,r)&&!ye(n.old_path,r))return!1;if(n.item_type==="symlink"&&s&&i)return!0;let o=ld(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 Wa(e,t){let n=cs.get(e);n||(n=new Map,cs.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||!ki(t))&&Se(e,t.queryKey,{exact:!0})},500))}function Ga(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){let r=ki(n);r&&dd(n,r,t)&&Wa(e,n)}}function za(e){for(let t of e.getQueryCache().getAll())ki(t)&&t.state.data!==void 0&&Wa(e,t)}function Ja(e){cs.get(e)?.forEach(clearTimeout),cs.delete(e)}var us=class extends Error{constructor(){super("The server did not confirm the selected-Space listing contract")}};function Ya(e,t){if(!Array.isArray(t)||t.some(n=>typeof n!="string")||JSON.stringify([...new Set(t)].sort())!==JSON.stringify(e))throw new us}function Rt(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 On(e){return e instanceof us||e instanceof Fe||e instanceof he&&(e.payload?.error==="SPACE_SELECTION_UNAVAILABLE"||e.payload?.error==="QUERY_PARAMS_INVALID"||e.status===401||e.status===403)}function ue(){return G()??"__unscoped__"}var E={all:()=>["vfs",ue()],item:e=>["vfs",ue(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",ue(),"children",e],allChildren:()=>["vfs",ue(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",ue(),"search",e,...t??[]],items:(e,t)=>["vfs",ue(),"items",e,JSON.stringify(Rt(t??{}))],allItems:()=>["vfs",ue(),"items"],tree:(e,t)=>["vfs",ue(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",ue(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",ue(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",ue(),"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",ue(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",ue(),"channel-messages"],channels:e=>["vfs",ue(),"channels",e??"all"],allChannels:()=>["vfs",ue(),"channels"],notifications:(e,t)=>["vfs",ue(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",ue(),"notifications"],unreadCounts:()=>["vfs",ue(),"unread-counts"],memberships:e=>["memberships",e]};var pd=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function X(...e){pd&&console.log("[WS]",...e)}var N=null,Fn=null,Nn=null,hr=0,fd=3e4,Xa=1e4,Dn=!1,Za=!1,sc=3e4,md=sc*2+5e3,ls=0,ds=null,ec=!1;function gd(){_r(),ls=Date.now(),ds=setInterval(()=>{if(N&&N.readyState===WebSocket.OPEN&&Date.now()-ls>md){X("ping: no inbound traffic for",Date.now()-ls,"ms \u2014 closing half-open socket");try{N.close(4e3,"liveness timeout")}catch{}return}ut({type:"ping"})},sc)}function _r(){ds&&(clearInterval(ds),ds=null)}function hd(){typeof document>"u"||(document.hidden?_r():yr()&&(X("Tab visible, reconnecting..."),Jt()))}function yd(){ec||typeof document>"u"||(document.addEventListener("visibilitychange",hd),ec=!0)}var Pe={};function Oi(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return!n||!r?n===r:r===n||r.startsWith(`${n}/`)}var Qn=[],ct=new Map,qn=new Map,Me=new Map;function _d(e){let t=qn.get(e);return t?Array.from(new Set(Array.from(t.values()).flatMap(n=>n.event_types))).sort():[]}function tc(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):!1}function nc(e){let t=_d(e);if(t.length===0)return ct.delete(e),null;let n={scope_id:e,event_types:t};return ct.set(e,n),n}var Ve=new Map,Pt=new Map,Mi="disconnected",ps=[];function fs(e){if(Mi!==e){Mi=e;for(let t of[...ps])try{t(e)}catch{}}}function vd(e){Ve.set(e,"ready");let t=Pt.get(e);if(t){Pt.delete(e);for(let n of t)n()}}function bd(){for(let e of Ve.keys())Ve.set(e,"disconnected")}function Fi(e,t){Ve.set(e,"pending"),ut({type:"subscribe_path",path:e,event_types:t})}function wd(){return Object.keys(Pe).some(t=>Pe[t]&&Pe[t].length>0)||Qn.length>0}function yr(){return ct.size>0||Me.size>0}async function Jt(){if(rt){X("ensureConnection: the host holds the session, no realtime connection");return}if(!yr()){X("ensureConnection: no active subscriptions, skipping");return}if(N&&N.readyState===WebSocket.OPEN){X("ensureConnection: already open");return}if(Fn)return X("ensureConnection: connection already in flight, waiting..."),Fn;if(N){X("ensureConnection: killing stale WS in state",N.readyState);try{N.close()}catch{}N=null}return Dn=!1,Fn=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=Te,n=await st();if(!n){X("ensureConnection: no token available, will retry"),rc();return}let r=t.startsWith("https")?"wss":"ws",s=t.replace(/^https?:\/\//,""),i=`${r}://${s}/ws`;i+=`?token=${encodeURIComponent(n)}`,X("ensureConnection: opening WS to",i.substring(0,50)+"..."),fs("connecting"),N=new WebSocket(i);let o=N;await new Promise((a,c)=>{if(!N)return c(new Error("WebSocket not created"));let u=setTimeout(()=>{if(N===o){if(X("ensureConnection: TIMEOUT after",Xa,"ms"),N&&N.readyState!==WebSocket.OPEN){try{N.close()}catch{}N=null}c(new Error("WebSocket connection timeout"))}},Xa);o.onopen=()=>{if(N!==o)return;clearTimeout(u),X("ensureConnection: CONNECTED");let l=Za;Za=!0,hr=0,fs("connected"),Sd(l),(typeof document>"u"||!document.hidden)&&gd(),yd(),a()},o.onmessage=l=>{N===o&&xd(l.data)},o.onerror=()=>{X("ensureConnection: WS error event")},o.onclose=l=>{clearTimeout(u),N===o&&(X("ensureConnection: WS closed, code:",l.code,"reason:",l.reason),N=null,_r(),bd(),fs("disconnected"),!Dn&&yr()&&rc(),c(new Error(`WebSocket closed: ${l.code}`)))}})}catch(e){X("ensureConnection: failed -",e?.message||e)}finally{Fn=null}})(),Fn}function rc(){if(Nn||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,hr)+Math.random()*1e3,fd);hr++,X("scheduleReconnect: attempt",hr,"in",Math.round(e),"ms"),Nn=setTimeout(()=>{Nn=null,yr()&&Jt()},e)}function Sd(e=!1){for(let t of ct.values())X("resubscribeAll: scope",t.scope_id),ut({type:"subscribe",scope_id:t.scope_id,event_types:t.event_types});for(let t of Me.values())X("resubscribeAll: path",t.path),Fi(t.path,t.event_types);e&&ic("reconnect")}function ic(e){try{let t=q();za(t),ja(t);for(let n of Me.values())t.invalidateQueries({queryKey:E.item(n.path)}),t.invalidateQueries({queryKey:E.children(n.path)});t.invalidateQueries({queryKey:E.allChannelMessages()}),X("catchUpAfterGap:",e,"- invalidated",Me.size,"paths and the transcripts on screen")}catch(t){X("catchUpAfterGap: cache invalidation skipped",t)}}function ut(e){N&&N.readyState===WebSocket.OPEN&&N.send(JSON.stringify(e))}function xd(e){ls=Date.now();try{let t=JSON.parse(e);if(t.type==="subscribed_path"){typeof t.path=="string"&&vd(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"){ic(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"&&(Ga(q(),r),Ha(q(),r)),typeof r.path=="string")for(let[s,i]of Object.entries(Pe))s!=="*"&&Oi(s,r.path)&&i.forEach(o=>o(r));Pe["*"]&&Pe["*"].forEach(s=>s(r));for(let s of Qn)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function qi(){!wd()&&ct.size===0&&Me.size===0&&N&&(Dn=!0,_r(),N.close(),N=null,Dn=!1)}function ms(e,t){return Pe[e]||(Pe[e]=[]),Pe[e].push(t),Me.has(e)||(Me.set(e,{path:e,event_types:["token_stream"]}),N&&N.readyState===WebSocket.OPEN?Fi(e,["token_stream"]):Ve.set(e,"pending")),Jt(),()=>{let n=Pe[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete Pe[e],Me.delete(e),Ve.delete(e),Pt.delete(e),ut({type:"unsubscribe_path",path:e}))}qi()}}function oe(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return Qn.push(...s),yr()&&Jt(),()=>{for(let i of s){let o=Qn.indexOf(i);o!==-1&&Qn.splice(o,1)}qi()}}function Un(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=ct.get(e)?.event_types;s.set(n,{event_types:r}),qn.set(e,s);let o=nc(e);if(!o)return()=>{};X("subscribeToScope:",e,o.event_types),N&&N.readyState===WebSocket.OPEN&&!tc(i,o.event_types)&&ut({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=ct.get(e)?.event_types;if(c.size===0)qn.delete(e),ct.delete(e),ut({type:"unsubscribe",scope_id:e});else{let l=nc(e);l&&N&&N.readyState===WebSocket.OPEN&&!tc(u,l.event_types)&&ut({type:"subscribe",scope_id:e,event_types:l.event_types})}qi()}}function oc(e,t,n={}){ut({type:"emit",scope_id:e,event_type:t,payload:n})}function Ni(){X("disconnectSSE: tearing down"),Ja(q()),Ba(q()),Dn=!0,_r(),N&&(N.close(),N=null),Nn&&(clearTimeout(Nn),Nn=null),Fn=null,Dn=!1,hr=0;for(let e of Object.keys(Pe))delete Pe[e];Qn.length=0,ct.clear(),qn.clear(),Me.clear(),Ve.clear(),Pt.clear(),fs("disconnected")}function ac(){ut({type:"ping"})}function cc(e){return Me.has(e)?Ve.get(e)??"pending":"unsubscribed"}function uc(e,t=5e3){return!Me.has(e)||rt?Promise.resolve(!1):Ve.get(e)==="ready"&&N&&N.readyState===WebSocket.OPEN?Promise.resolve(!0):(Jt(),new Promise(n=>{let r=!1,s=Pt.get(e)??[],i=()=>{r||(r=!0,clearTimeout(o),n(!0))};s.push(i),Pt.set(e,s);let o=setTimeout(()=>{if(r)return;r=!0;let a=Pt.get(e);if(a){let c=a.indexOf(i);c!==-1&&a.splice(c,1),a.length===0&&Pt.delete(e)}n(!1)},t)}))}function lc(e){let t=Me.get(e);if(!t){X("resubscribePath: no active subscription for",e);return}N&&N.readyState===WebSocket.OPEN?(X("resubscribePath: re-sending frame for",e),Fi(t.path,t.event_types)):(Ve.set(e,"pending"),Jt())}function gs(e){ps.push(e);try{e(Mi)}catch{}return()=>{let t=ps.indexOf(e);t!==-1&&ps.splice(t,1)}}ie(Ni);function dc(){return new Date().toISOString()}function pc(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function Oe(e){let t=e.path||e.item_path||"",n=t.split("/");n.pop();let r=n.join("/"),s=e.type_data||{};return s.allowed_parent_types&&!s.accepts&&(s.accepts=s.allowed_parent_types),delete s.allowed_parent_types,{id:e.id||e.item_id||"",name:e.name||e.item_name||"",item_type:e.item_type||"unknown",path:t,parent_path:r,is_active:e.is_active!==!1,has_children:e.has_children??!1,created_at:e.created_at||dc(),updated_at:e.updated_at||dc(),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 br(e){return(e.content?.items||e.items||[]).map(Oe)}async function wr(e){try{let t=await x("read",{id:e});if(t.item_name||t.item_path){let r=Oe(t);return r.path&&q().setQueryData(E.item(r.path),r),r}let n=t.item;if(n){let r=Oe(n);return r.path&&q().setQueryData(E.item(r.path),r),r}return null}catch{return null}}async function Sr(e){try{let t=await x("read",{path:e});if(t.item_name||t.item_path)return Oe(t);let n=t.item;return n?Oe(n):null}catch{return null}}async function xr(e){try{let t=await x("list",{path:e,limit:200}),n=br(t);for(let r of n)q().setQueryData(E.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function fc(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 ys(e,t,n){try{let r=await x("list",{path:e,limit:t,offset:n}),s=br(r);for(let i of s)q().setQueryData(E.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 _s(e){let n=await x("types-list",e?{scope_id:e}:{}),r=n.content?.items||n.items||[],s=new Map;for(let i of r){let o=i.name,a=i.type_data;!o||!a||s.set(o,{type_key:o,display_name:a.display_name||o,display_name_plural:a.display_name_plural||o+"s",icon:a.icon||"File",color:a.color||"gray",description:a.description||"",input_schema:a.input_schema||{},system_schema:a.system_schema||{},json_schema:a.input_schema||a.json_schema||{},default_data:a.default_data||{},field_defaults:a.field_defaults||{},renderer_config:a.renderer_config||{},is_system:a.is_system??!1,is_active:a.is_active??!0,is_container:a.is_container??!1,is_scope:a.is_scope??!1,render_mode:a.render_mode||"none",placement_mode:a.placement_mode,direct_parent_types:a.direct_parent_types,allowed_parent_types:a.allowed_parent_types,governed_create:a.governed_create,create_method:a.create_method,dedup:a.dedup,edges:a.edges,events:a.events})}return s}async function vs(e){try{let t=await x("edges",{item_id:e}),n=t.outgoing||[],r=t.incoming||[],s=[];for(let i of n)s.push({id:i.edge_id||pc(),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||pc(),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 bs(e,t=1,n,r){try{let s={path:e,max_depth:t>0?t:999};n?.length&&(s.item_types=n),r&&(s.limit=r);let i=await x("tree",s),o=br(i);for(let a of o)q().setQueryData(E.item(a.path),a);return o}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function ws(e,t=50,n=0){try{let r=await x("get-activity-feed",{scope_path:e,limit:t,offset:n});return r.content?.items||r.items||r.entries||[]}catch(r){return console.error(`[gateway] Failed to fetch recent activity for ${e}:`,r),[]}}async function Rr(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;try{let i=await x("item-versions",{id:e,limit:n,offset:r,include_snapshots:s});return{versions:i.content?.items||i.versions||[],total:i.total??0}}catch(i){return console.error(`[gateway] Failed to fetch item versions for ${e}:`,i),{versions:[],total:0}}}async function Ss(e,t=50,n=0){return Rr(e,{limit:t,offset:n})}async function xs(e,t,n){try{let r={scope_id:e};t?.length&&(r.item_types=t),n&&(r.limit=n);let s=await x("member-focus",r),i=br(s);for(let o of i)q().setQueryData(E.item(o.path),o);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${e}:`,r),[]}}async function Pr(e,t){let n={path:e};t?.mode&&(n.mode=t.mode),t?.strategy&&(n.strategy=t.strategy),t?.arguments&&(n.arguments=t.arguments);let s=await x("open",n);return{item_id:s.item_id,item_path:s.item_path,item_name:s.item_name,item_type:s.item_type,render:s.render,compatible_components:s.compatible_components??[],content:s.content,metadata:s.metadata,instructions:s.instructions}}function Kn(e){return!!e&&(!!e.type||Array.isArray(e.any_of)&&e.any_of.length>0)}function Rd(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 Pd=["catalog","parent_only","internal"];function mc(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"&&Pd.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 Kn(s)?{...s,...t}:null}async function Yt(e,t={}){if(e=Rt(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(Rd)),Object.keys(r).length>0&&(n.filters=r),e.limit!=null&&(n.limit=e.limit);try{let s=await x("query",n,t);e.spaceIds!==void 0&&Ya(e.spaceIds,s.selected_space_ids??s.content?.selected_space_ids);let i=br(s);for(let o of i)q().setQueryData(E.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 Cd(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 gc(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:Cd(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 vr(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,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 hc(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await x("get-channel-messages",n),i=s.messages||s.content?.items||s.items||[];return vr(i)}catch(n){throw console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),n}}async function Rs(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await x("get-channel-messages",n),i=s.messages||[],o=vr(i),a=gc(i),c=new Map,u=[];for(let l of a)if(l.parentMessagePath){let p=c.get(l.parentMessagePath)||[];p.push(l),c.set(l.parentMessagePath,p)}else u.push(l);return{messages:o,activityMessages:vr(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 Cr(e,t){try{let n={channel_path:e};t?.parentMessageId&&(n.parent_message_id=t.parentMessageId),t?.conversationsOnly&&(n.conversations_only=!0),t?.transcriptOnly&&(n.transcript_only=!0),t?.limit&&(n.limit=t.limit),t?.before_seq!=null&&(n.before_seq=t.before_seq),t?.after_seq!=null&&(n.after_seq=t.after_seq);let s=await x("get-channel-messages",n);if(t?.conversationsOnly&&s.conversations_only!==!0)throw new Error("This server does not support conversation history lists yet. Update the message reader.");if(t?.transcriptOnly&&s.transcript_only!==!0)throw new Error("This server does not support channel transcript pages yet. Update the message reader.");let i=s.messages||[],o=gc(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:vr(i),activityMessages:vr(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 hs(e){q().invalidateQueries({queryKey:E.children(e)})}function Qi(e){q().invalidateQueries({queryKey:E.item(e)})}function yc(e,t){Qi(e),hs(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&hs(r)}function _c(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 vc(){q().invalidateQueries({queryKey:E.all()})}function bc(e){q().invalidateQueries({queryKey:E.types(e)})}function wc(e,t){e?q().invalidateQueries({queryKey:E.channelMessages(e,t)}):q().invalidateQueries({queryKey:E.allChannelMessages()})}function Sc(e,t){e&&t?q().invalidateQueries({queryKey:E.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:E.allOpenEnvelopes()})}function $e(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}async function Ps(){return((await x("list-memberships",{})).memberships||[]).map(n=>({accountId:n.account_id,path:n.account_path,name:n.account_name,role:n.role||"member",typeData:n.account_type_data||{},joinedAt:n.joined_at,via:n.via,placement:n.placement,subordinateTo:n.subordinate_to??null,cascadeAnchorId:n.cascade_anchor_id??null,isAccount:n.is_account??void 0,isSpace:n.is_space??void 0,isOwner:n.is_owner??void 0,billingResponsible:n.billing_responsible??void 0,grantedVia:n.granted_via??null,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 Ln=new Map,Ir=null,Cs=null,Ct=new Map,xc=250,Er=new Map;function Xt(e){if(Ir){Hn(e);return}Hn(e),Ir=oe("vfs_change",t=>Ed(t)),Cs=oe("ccm_change",t=>Id(t))}function Hn(e){if(Ln.has(e))return;let t=Un(e,["vfs_change","ccm_change"]);Ln.set(e,t)}function Es(e){let t=Ln.get(e);t&&(t(),Ln.delete(e))}function Di(){for(let[,e]of Ln)e();Ln.clear(),Ir&&(Ir(),Ir=null),Cs&&(Cs(),Cs=null),Ct.forEach(e=>clearTimeout(e)),Ct.clear(),Er.clear()}ie(Di);function Ed(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=Er.get(s);i||(i=new Map,Er.set(s,i)),i.set(t,{action:n,itemId:typeof e.item_id=="string"?e.item_id:void 0});let o=Ct.get(s);o&&clearTimeout(o);let a=setTimeout(()=>{Ct.delete(s);let c=Er.get(s);Er.delete(s),c&&Td(s,c)},xc);Ct.set(s,a)}function Id(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=Ct.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{Ct.delete(s),t&&q().invalidateQueries({queryKey:E.edges(t)}),n&&q().invalidateQueries({queryKey:E.edges(n)})},xc);Ct.set(s,o)}function Td(e,t){let n=q();for(let[s,i]of t)(i.action||"").toUpperCase()==="DELETE"?(n.removeQueries({queryKey:E.item(s)}),n.removeQueries({queryKey:E.children(s)}),n.removeQueries({queryKey:E.tree(s)})):Se(n,E.item(s),{exact:!0}),i.itemId&&n.invalidateQueries({queryKey:E.itemById(i.itemId)});n.invalidateQueries({queryKey:E.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 jn=null;ie(()=>{jn=null});function Et(e){if(e!==jn||e.generation!==Y())throw new Error("Workspace session changed")}function Ad(e){return e instanceof he&&e.payload?.error==="item_not_found"}function Tr(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 Ar(e){let t=ge();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 Rc(e,t){return JSON.stringify({mounts:e.map(n=>n.id),last_anchor:t.id})}async function Pc(e,t,n){Et(e);let r=Rc(t,n);if(e.saved===r)return;let s=JSON.parse(r);await x(e.exists?"update":"create",e.exists?{_scope_path:e.scope,path:e.path,type_data:s}:{_scope_path:e.scope,parent_path:e.path.slice(0,e.path.lastIndexOf("/")),name:"mounts",item_type:"file",type_data:s}),Et(e),e.exists=!0,e.saved=r}function Cc(e,t){let n=Ae();Xt(ge().id);for(let r of n)e.some(s=>s.id===r.id)||Es(r.id);for(let r of e)Hn(r.id);ga(e,t)}async function Zt(e,t,n={}){let r=ge();if(!r)throw new Error("Elect a home account before loading mounts");let s=`${e}/settings/mounts`;if(jn&&jn.path!==s)throw new Error("Reset the session before changing the mount declaration owner");let i=jn??(jn={generation:Y(),path:s,scope:r.path,resolve:t,exists:!1,ready:!1,saved:null,queue:Promise.resolve()});return Et(i),i.resolve=t,i.loading?i.loading:i.ready?Ae():(i.loading=(async()=>{let o=null;try{let l=await x("read",{path:s,_scope_path:i.scope});if(Et(i),o=l.type_data??l.item?.type_data,!o||!Array.isArray(o.mounts)||!o.mounts.every(p=>typeof p=="string"))throw new Error("Invalid saved mount declaration");i.exists=!0}catch(l){if(Et(i),!Ad(l))throw l;i.exists=!1}let a=n.initialAnchor?Tr(i,n.initialAnchor):r,c=Ar(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=Rc(c,u):n.initialAnchor&&await Pc(i,c,u),Et(i),i.ready=!0,Cc(c,u),c})().finally(()=>{i.loading=void 0}),i.loading)}function Is(e){let t=jn;if(!t?.ready)return Promise.reject(new Error("Workspace mounts are not loaded"));let n=t.queue.then(async()=>{Et(t);let{refs:r,anchor:s}=e(t);await Pc(t,r,s),Et(t),Cc(r,s)});return t.queue=n.catch(()=>{}),n}function Ui(e){return Is(t=>({refs:Ar([...Ae(),Tr(t,e)]),anchor:pe()}))}function Ec(e){return Is(()=>{if(e===ge().id)throw new Error("The home account cannot be unmounted");let t=Ar(Ae().filter(r=>r.id!==e)),n=t.find(r=>r.id===pe()?.id)??t.find(r=>r.kind==="space")??ge();return{refs:t,anchor:n}})}function kr(e){return Is(t=>{let n=Tr(t,e);return{refs:Ar([...Ae(),n]),anchor:n}})}function Ts(e,t){return Is(n=>{let r=Ar(e.map(i=>Tr(n,i))),s=Tr(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 Ki={};mo(Ki,{Badge:()=>Nd,Breadcrumbs:()=>Wd,Button:()=>Dd,Card:()=>qd,DataView:()=>Kd,Detail:()=>jd,Empty:()=>Ud,FilePreview:()=>Jd,Form:()=>Hd,Grid:()=>Od,Image:()=>Gd,Link:()=>Vd,Page:()=>kd,Router:()=>Bd,Sidebar:()=>Fd,Spinner:()=>Qd,Stack:()=>Md,Table:()=>Ld,Tabs:()=>$d,Video:()=>zd});var z=ee(le(),1);function Ic(){return(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||""}function kd(e){return(0,z.createElement)("div",{style:{minHeight:"100vh",display:"flex",flexDirection:"column"},className:e.className||""},e.children)}function Md(e){let t=e.direction||"vertical";return(0,z.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 Od(e){return(0,z.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 Fd(e){return(0,z.createElement)("div",{style:{display:"flex",flexDirection:"row",minHeight:"100vh"},className:e.className||""},e.children)}function qd(e){return(0,z.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 Nd(e){return(0,z.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 Qd(e){let t=e.size||"1.5rem";return(0,z.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 Dd(e){return(0,z.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 Ud(e){return(0,z.createElement)("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"3rem",color:"var(--color-text-secondary, #6b7280)",textAlign:"center"}},e.icon?(0,z.createElement)("div",{style:{fontSize:"2rem",marginBottom:"0.5rem"}},e.icon):null,(0,z.createElement)("div",{style:{fontWeight:500,marginBottom:"0.25rem"}},e.title||e.message||e.children||"No items"),e.description?(0,z.createElement)("div",{style:{fontSize:"0.875rem",opacity:.7}},e.description):null)}function Kd(e){return(0,z.createElement)("div",{className:e.className||""},e.children)}function Ld(e){return(0,z.createElement)("table",{className:e.className||""},e.children)}function Hd(e){return(0,z.createElement)("form",{className:e.className||"",onSubmit:e.onSubmit},e.children)}function jd(e){return(0,z.createElement)("div",{className:e.className||""},e.children)}function Bd(e){return(0,z.createElement)("div",null,e.children)}function Vd(e){return(0,z.createElement)("a",{href:e.href||e.to,className:e.className||"",onClick:e.onClick},e.children)}function $d(e){return(0,z.createElement)("div",{className:e.className||""},e.children)}function Wd(e){return(0,z.createElement)("nav",{className:e.className||""},e.children)}function Gd(e){return(0,z.createElement)("img",{src:e.src||(e.path?Ic()+e.path:""),alt:e.alt||"",className:e.className||"",style:e.style})}function zd(e){return(0,z.createElement)("video",{src:e.src||(e.path?Ic()+e.path:""),controls:!0,className:e.className||""})}function Jd(e){return(0,z.createElement)("div",{className:e.className||""},e.children||"File preview")}function As(e){if(typeof e.path!="string")return!1;let t=[...Ae().map(n=>n.path),pe()?.path].filter(n=>!!n);return!t.length&&G()&&t.push(G()),t.some(n=>ye(e.path,n))}function Li(e,t,n,r){if(!["message","card"].includes(e?.item_type)||!ye(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&&ye(e.path,i)})}var Tc=new WeakMap;function Ac(e,t,n){let r=Tc.get(e);r||(r=new Map,Tc.set(e,r));let s=JSON.stringify(t),i=r.get(s);if(!i){let a=!1,c,u=!1,l=!1,p=new Set,h=new Set,f=()=>e.getQueryData(t)??[],m=()=>{a||u||c||(c=setTimeout(()=>{c=void 0,b()},250))},b=async()=>{if(a)return;u=!0;let R=l;l=!1;let P=[...p],M=new Set(h);h.clear(),p.clear();try{if(R)await Se(e,t,{exact:!0});else{let C=(await Promise.allSettled(P.map(async A=>{let k=e.getQueryCache().find({queryKey:t,exact:!0});if(!k)return;let T=await x("read",{id:A});if(T.success===!1)throw new Error("Channel refresh failed");if(a||!k||e.getQueryCache().find({queryKey:t,exact:!0})!==k)return;let O=Oe(T.item??T);if(O.id!==A||O.item_type!=="channel")return;let Q=f().find(De=>De.id===A);if(!Q)return;let K=n({...O}),Z={...Q,path:K.path,name:K.name,displayName:K.displayName,messageCount:K.messageCount,aiMode:K.aiMode,activeAgentIds:K.activeAgentIds,isPrivate:K.isPrivate,isDm:K.isDm,autoPilot:K.autoPilot,isArchived:K.isArchived,updatedAt:K.updatedAt};M.has(A)&&(Q.name!==Z.name||Q.displayName!==Z.displayName||Q.path!==Z.path)&&(l=!0),e.setQueryData(t,De=>De?.map(lt=>lt.id===A?Z:lt))}))).find(A=>A.status==="rejected");if(C?.status==="rejected")throw C.reason}}catch(D){console.warn("[channels] refresh failed",D)}finally{u=!1,(l||p.size)&&m()}},g=R=>f().some(P=>P.id===R.item_id||P.path===R.path)?!0:As(R),y=R=>{if(!g(R))return;let P=String(R.action??"").toLowerCase();if(["insert","delete","rename","move"].includes(P))l=!0;else if(P==="update"){let M=f().find(D=>D.id===R.item_id||D.path===R.path);M&&(p.add(M.id),h.add(M.id))}(l||p.size)&&m()},_=R=>{let P=f().find(M=>M.id===R.parent_id);P&&(p.add(P.id),m())},w=["vfs_change","ccm_change"].flatMap(R=>[oe(R,y,P=>P.item_type==="channel"),oe(R,_,P=>P.item_type==="message")]);i={users:0,stop:()=>{a=!0,c&&clearTimeout(c),w.forEach(R=>R())}},r.set(s,i)}i.users++;let o=!1;return()=>{o||(o=!0,--i.users===0&&(i.stop(),r.delete(s)))}}function re(){return(0,v.useSyncExternalStore)(Re,W,W)}function Qc(){return re(),es()}function Dc(e){return re(),B({queryKey:E.item(e),queryFn:()=>Sr(e),enabled:!!e,staleTime:1/0})}function Uc(e){return re(),B({queryKey:E.itemById(e),queryFn:()=>wr(e),enabled:!!e,staleTime:1/0})}function Bi(e){return re(),B({queryKey:E.children(e),queryFn:()=>xr(e),enabled:!!e})}function Kc(e){let t=Bi(e);return{...t,children:t.data??[]}}function Lc(e,t=1){return re(),B({queryKey:E.tree(e,t),queryFn:()=>bs(e,t),enabled:!!e})}function Hc(e,t){return re(),B({queryKey:E.search(e,t),queryFn:async()=>{let n={query:e};t?.length&&(n.item_types=t);let r=await x("search",n);return(r.content?.items||r.items||r.results||[]).map(Oe)},enabled:!!e&&e.length>0})}function jc(e){re();let t=(0,v.useMemo)(()=>e,[JSON.stringify(e)]);return B({queryKey:["vfs",G()??"__unscoped__","resolve",JSON.stringify(t??{})],queryFn:async()=>await x("resolve",t),enabled:!!t?.query&&t.query.length>0})}function Bc(e){re();let t=Rt(e),n=(0,v.useMemo)(()=>t,[JSON.stringify(t)]),r=B({queryKey:E.items(n?.type??"",n),queryFn:({signal:s})=>Yt(n,{signal:s,throwOnError:!0}),enabled:Kn(n),...n?.spaceIds!==void 0?{retry:(s,i)=>!On(i)&&Qu(s,i)}:{},select:s=>s.items});return n?.spaceIds!==void 0&&On(r.error)?{...r,data:void 0}:r}function Vi(e,t={}){let n=re(),{realtime:r=!1}=t,s=Rt(e),i=s?.limit??20,o=(0,v.useMemo)(()=>s,[JSON.stringify(s)]),a=(0,v.useMemo)(()=>["vfs",G()??"__unscoped__","infinite-items",o?.type??"",JSON.stringify(o??{})],[n,o]),c=dr({queryKey:a,queryFn:async({pageParam:p=0,signal:h})=>Yt({...o,limit:i,offset:p},{throwOnError:!0,signal:h,priority:t.priority}),initialPageParam:0,getNextPageParam:(p,h,f)=>{if(!(o?.spaceIds!==void 0&&p.total_hint!==void 0&&f+p.items.length>=p.total_hint)&&!(p.items.length<i))return f+p.items.length},enabled:Kn(o),...o?.spaceIds!==void 0?{retry:(p,h)=>!On(h)&&Qu(p,h)}:{},staleTime:r?1/0:t.staleTime,meta:r&&o?{infiniteItemsRealtime:{filter:o}}:{}}),u=(0,v.useMemo)(()=>{if(o?.spaceIds!==void 0&&On(c.error))return[];if(!c.data?.pages)return[];let p=new Set,h=[];for(let f of c.data.pages)for(let m of f.items)m.id&&!p.has(m.id)&&(p.add(m.id),h.push(m));return h},[c.data?.pages,c.error,o]),l=o?.spaceIds!==void 0&&On(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 kc(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 Zd(e,t){if(e.is_active===!1||e.item_type!==t.type||!ye(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 Vc(e,t={}){let n=kc(e),r=Vi(e,n?{realtime:!1,staleTime:3e4}:{realtime:!0}),s=L(),i=JSON.stringify([G(),Rt(e)]),[o,a]=(0,v.useState)(()=>({identity:i,upserts:{},deleted:new Set})),c=o.identity===i?o:{identity:i,upserts:{},deleted:new Set},u=(0,v.useMemo)(()=>{if(!n)return r.allItems;let f=Object.values(c.upserts),m=new Set(f.map(_=>_.id)),b=[...f,...r.allItems.filter(_=>!m.has(_.id))].filter(_=>!c.deleted.has(_.path)),g=e.sort_by??"updated_at",y=e.sort_dir==="asc"?1:-1;return b.sort((_,w)=>y*String(_[g]??"").localeCompare(String(w[g]??"")))},[n,r.allItems,c,e?.sort_by,e?.sort_dir]),l=(0,v.useRef)(u);l.current=u;let p=(0,v.useRef)(t.shouldReadUpdate);p.current=t.shouldReadUpdate;let h=(0,v.useRef)(r.refetch);return h.current=r.refetch,(0,v.useEffect)(()=>{if(!kc(e))return;let f=e,m=!1,b=!1,g=!1,y=0,_=new Map,w=()=>{let C=y;h.current().then(A=>{!m&&!A.isError&&y===C&&a({identity:i,upserts:{},deleted:new Set})})},R=C=>{y++,a(k=>{let T=k.identity===i?k:{identity:i,upserts:{},deleted:new Set},O={...T.upserts};return delete O[C],{identity:i,upserts:O,deleted:new Set(T.deleted).add(C)}});let A=_.get("__reconcile__");A&&clearTimeout(A),_.set("__reconcile__",setTimeout(()=>{_.delete("__reconcile__"),w()},250))},P=C=>{let A=_.get(C);A&&clearTimeout(A),_.set(C,setTimeout(()=>{_.delete(C),s.fetchQuery({queryKey:E.item(C),queryFn:()=>Sr(C),staleTime:0}).then(k=>{if(!m){if(!k||!Zd(k,f)){let T=l.current.find(O=>O.path===C||O.id===k?.id);T&&R(T.path);return}a(T=>{let O=T.identity===i?T:{identity:i,upserts:{},deleted:new Set},Q=new Set(O.deleted);return Q.delete(C),{identity:i,upserts:{...O.upserts,[C]:k},deleted:Q}})}}).catch(k=>console.warn("[useIncrementalItems] item read failed:",k))},250))},M=oe("vfs_change",C=>{if(!C||typeof C.path!="string"&&typeof C.old_path!="string")return;let A=typeof C.path=="string"?C.path:C.old_path,k=l.current.find(O=>O.path===A||O.path===C.old_path||C.item_id&&O.id===C.item_id),T=!!k;if(!(!ye(A,f.scope)&&!ye(C.old_path,f.scope)&&!T)&&!(C.item_type&&C.item_type!==f.type&&!T)&&!(f.parent_id&&C.parent_id&&C.parent_id!==f.parent_id&&!T)){if(k&&(A!==k.path||C.old_path&&C.old_path!==A||C.parent_id&&C.parent_id!==k.parent_id||C.item_type&&C.item_type!==f.type)){R(k.path);return}if(!k&&C.old_path&&C.old_path!==A&&ye(A,f.scope)){y++,P(A);return}if(C.action==="insert")y++,P(A);else if(C.action==="move")y++,P(A);else if(C.action==="update"){if(!p.current?.(C,l.current))return;y++,P(A)}else C.action==="delete"&&R(k?.path??C.old_path??A)}}),D=gs(C=>{if(C!=="connected"){b&&(g=!0);return}b=!0,g&&(g=!1,w())});return()=>{m=!0,M(),D(),_.forEach(clearTimeout)}},[s,i]),{...r,allItems:u}}function $c(e){re();let t=20,n=dr({queryKey:["vfs",G()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>ys(e,t,s),initialPageParam:0,getNextPageParam:(s,i,o)=>{if(!(s.items.length<t))return o+s.items.length},enabled:!!e});return{allItems:(0,v.useMemo)(()=>{if(!n.data?.pages)return[];let s=new Set,i=[];for(let o of n.data.pages)for(let a of o.items)a.id&&!s.has(a.id)&&(s.add(a.id),i.push(a));return i},[n.data?.pages]),fetchNextPage:n.fetchNextPage,isFetchingNextPage:n.isFetchingNextPage,isExhausted:!n.hasNextPage,isLoading:n.isLoading,isFetching:n.isFetching,error:n.error,totalHint:n.data?.pages?.[0]?.total_hint}}function Wc(e){return re(),B({queryKey:E.edges(e),queryFn:()=>vs(e),enabled:!!e})}function Ms(e){return re(),B({queryKey:E.types(e),queryFn:()=>_s(e)})}function Gc(e,t){let n=Ms(t);return{...n,data:n.data?.get(e)??void 0}}function zc(e,t){re();let n=(0,v.useMemo)(()=>t?.arguments,[JSON.stringify(t?.arguments)]),r=t?.mode,s=t?.strategy,i=t?.width;return B({queryKey:[...E.openEnvelope(e,s),i],queryFn:async()=>{let o=await Pr(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 Mc={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 Jc(e){let t=Ms(e),n=t.data??new Map;return(0,v.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(Mc).map(([f,m])=>({key:f,label:m})),getEdgeTypeLabel:f=>Mc[f]??f.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function Yc(e,t,n){return re(),B({queryKey:E.memberFocus(e),queryFn:()=>xs(e,t,n),enabled:!!e})}function Xc(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return B({queryKey:E.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>Rr(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function Zc(e,t=50,n=0){return B({queryKey:E.itemHistory(e,String(t),String(n)),queryFn:()=>Ss(e,t,n),enabled:!!e})}function eu(e,t=50,n=0){return re(),B({queryKey:E.recentActivity(e,String(t),String(n)),queryFn:()=>ws(e,t,n),enabled:!!e})}function tu(){let[e,t]=(0,v.useState)(null),[n,r]=(0,v.useState)(!0),[s,i]=(0,v.useState)(null);return(0,v.useEffect)(()=>{let o=!1;return it().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 ep=[];function Oc(){if(typeof window>"u")return!1;let e=window.__FSAOS_CONFIG__?.embedToken;return typeof e=="function"||typeof e=="string"&&e.length>0}function tp(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 nu(){let{user:e}=Os(),t=(0,v.useSyncExternalStore)(_a,xi,xi),n=xt()?.principal_id??null,r=(0,v.useRef)(null),[s,i]=(0,v.useState)(null),[o,a]=(0,v.useState)(null);(0,v.useEffect)(()=>{if(n){a(null);return}if(!e?.id&&!Oc()){a(null);return}let _=!1;return it().then(w=>{_||w.principal_id||a(new Error("Memberships require an authenticated principal"))}).catch(w=>{_||a(w instanceof Error?w:new Error(String(w)))}),()=>{_=!0}},[n,e?.id,t]);let c=B({queryKey:E.memberships(n??"anonymous"),queryFn:Ps,enabled:!!n,staleTime:1e3*60*2}),u=c.data??ep,l=(0,v.useMemo)(()=>u.filter(_=>_.isAccount!==!1&&!_.isSpace),[u]),p=(0,v.useMemo)(()=>{let _=new Set(l.map(R=>R.accountId)),w=R=>!R.subordinateTo||!_.has(R.subordinateTo);return[...l].sort((R,P)=>Number(w(P))-Number(w(R)))},[l]),h=(0,v.useSyncExternalStore)(Re,W,W),f=(0,v.useMemo)(()=>{let _=pe();return _?u.find(w=>w.accountId===_.id)??null:null},[h,u]),m=(0,v.useMemo)(()=>tp(l),[l]);(0,v.useEffect)(()=>{if(!n){r.current=null;return}if(r.current!==n)if(i(null),p.length===1){let _=p[0];ge()||Vt($e(_)),Xt(_.accountId),_.personalSpacePath&&Zt(_.personalSpacePath,w=>{let R=u.find(P=>P.accountId===w);return R?$e(R):null}).catch(i),r.current=n}else p.length>1&&(r.current=n)},[n,p,u]);let b=(0,v.useCallback)(async _=>{let w=u.find(M=>M.path===_);if(!w)throw new Error("Account membership is unavailable");let R=$e(w);ge()||Vt(R);let P=u.find(M=>M.accountId===ge()?.id);if(!P?.personalSpacePath)throw new Error("The home membership has no mount declaration location");await Zt(P.personalSpacePath,M=>{let D=u.find(C=>C.accountId===M);return D?$e(D):null}),await kr(R),i(null),Xt(w.accountId)},[u]),g=(0,v.useCallback)(async _=>{let w=u.find(R=>R.path===_);if(!w)throw new Error("Scope membership is unavailable");await Ui($e(w))},[u]),y=(!!e?.id||Oc())&&!n&&!o;return{accounts:p,switcherAccounts:m,allMemberships:u,currentAccount:f,mountedScope:null,switchAccount:b,mountScope:g,loading:y||c.isLoading,error:o??c.error??s}}function ru(){re();let e=(0,v.useSyncExternalStore)(Zr,gr,gr),t=(0,v.useMemo)(()=>Ae(),[e]),n=pe(),r=(0,v.useMemo)(()=>t.filter(i=>i.kind==="space"&&(n?.kind==="account"||i.id===n?.id)),[t,n]),s=(0,v.useMemo)(()=>r.map(i=>i.id).sort(),[r]);return{mounts:t,selectedSpaces:r,readSpaceIds:s,homeAnchor:ge(),anchor:n,setAnchor:kr,replaceMounts:Ts,mount:Ui,unmount:Ec}}function Os(){let[e,t]=(0,v.useState)(null),[n,r]=(0,v.useState)(null),[s,i]=(0,v.useState)(!0),o=(0,v.useRef)(null);(0,v.useEffect)(()=>{$.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,v.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,v.useCallback)(async h=>$.auth.signUp({email:h.email,password:h.password,options:{data:h.metadata||{}}}),[]),u=(0,v.useCallback)(async()=>{await $.auth.signOut(),kn(),q().clear()},[]),l=(0,v.useCallback)(async h=>{let{error:f}=await $.auth.resetPasswordForEmail(h);if(f)throw f},[]),p=(0,v.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:p}}function su(e){let[t,n]=(0,v.useState)(null),[r,s]=(0,v.useState)(!1),[i,o]=(0,v.useState)(null);return(0,v.useEffect)(()=>{if(!e){n(null),s(!1);return}if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e))s(!0),x("resolve-asset",{asset_id:e}).then(c=>{c.success&&c.public_url?n({url:c.public_url,id:c.asset_id,name:c.name,mimeType:c.mime_type,width:c.width,height:c.height,sizeBytes:c.size_bytes}):o(new Error(c.error||"Asset not found")),s(!1)}).catch(c=>{o(c instanceof Error?c:new Error(String(c))),s(!1)});else{let u=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";n({url:u+e}),s(!1)}},[e]),{data:t,loading:r,error:i}}var ks={};ie(()=>{for(let e of Object.keys(ks))delete ks[e]});var iu=null;function ou(e){iu=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function np(e){switch(e){case"react":return typeof window<"u"&&window.React||v.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||Yd;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}:Xd;case"@fsaos/gateway":case"@fsaos/react":case"@ai4b-team/fsaos-gateway-sdk":return typeof window<"u"&&window.__FSAOS_GATEWAY__||iu||{};case"@fsaos/ui":case"@ai4b-team/fsaos-gateway-sdk/ui":return typeof window<"u"&&window.__FSAOS_UI__||Ki;case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}var Or={};async function rp(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 au(e,t=()=>rp(e)){let n=Or[e];n||(n=Or[e]={users:0,text:t(),style:null}),n.users+=1;let r=await n.text;if(Or[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 We(e){let t=Or[e];t&&(t.users-=1,!(t.users>0)&&(t.style?.remove(),delete Or[e]))}function cu(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)(np),o=t??i;return o?o.default||o:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function $i(e,t){let[n,r]=(0,v.useState)(null),[s,i]=(0,v.useState)(!0),[o,a]=(0,v.useState)(null),c=(0,v.useRef)(null),u=Number.isSafeInteger(t?.version)&&t.version>0?t.version:null;return(0,v.useEffect)(()=>{if(!e)return;let l=!1;a(null),c.current?.path!==e&&(c.current?.cssUrl&&We(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,b=e+"@v1",g=h+e+"/__bundle.js";if(u!==null)m=u,b=e+"@v"+m,g=h+e+"/__bundle.v"+m+".js";else try{let P=await fetch(h+e+"/__meta",{cache:"no-store"});P.ok&&(m=(await P.json()).version||1,b=e+"@v"+m,g=h+e+"/__bundle.v"+m+".js")}catch{g=h+e+"/__bundle.js?v="+Date.now()}if(l)return;let y=g.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");f=y;let _=au(y),w=ks[b];if(!w){let P=await fetch(g);if(!P.ok)throw new Error(`Failed to fetch bundle: ${P.status} ${P.statusText} (${g})`);let M=await P.text();if(w=cu(M),!w)throw new Error("Bundle did not export a component. Expected window.__FSAOS_COMPONENT__ (FSAOS build) or a __FSAOS_REGISTER__(Component) call.");if(typeof w!="function")throw new Error(`Bundle export is not a React component (got ${typeof w})`);ks[b]=w}if(await _,l){We(y);return}let R=c.current?.cssUrl??null;c.current={path:e,cssUrl:y},f=null,r(()=>w),i(!1),R&&We(R)}catch(m){f&&We(f),l||(a(m instanceof Error?m:new Error(String(m))),i(!1))}})(),()=>{l=!0}},[e,u]),(0,v.useEffect)(()=>()=>{c.current?.cssUrl&&We(c.current.cssUrl),c.current=null},[]),{Component:n,loading:s,error:o}}var sp=/^embed\/bundle-[A-Za-z0-9_-]+\.js$/,ip=/^embed\/bundle-[A-Za-z0-9_-]+\.css$/;function Fc(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=It(e[s]).sha256;return typeof i=="string"&&i?{path:s,sha256:i}:null}var Mr=new Map,Hi=new Map;ie(()=>{Mr.clear(),Hi.clear()});function It(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function uu(e){let t=It(It(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 qc(e,t,n){let r=await Pr(e.path,{mode:"render"}),s=It(It(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 op(e,t,n){let r=await wr(t);if(!r)throw new Error("The published release could not be read.");let s=It(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=It(s.artifacts),o=Fc(i,sp,"script");if(!o)return{status:"no_in_app_version",releaseItemId:t,version:n};let a=Fc(i,ip,"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}),p=g=>l.find(y=>It(y.type_data).package_path===g),h=p(o.path),f=a?p(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,b]=await Promise.all([qc(h,o.sha256,"script"),f&&a?qc(f,a.sha256,"stylesheet"):Promise.resolve(null)]);return{status:"ready",releaseItemId:t,version:n,script:m,stylesheet:b?.trim()?b:null}}function lu(e,t,n){let r=Mr.get(t);return r||(r=op(e,t,n),Mr.set(t,r),r.catch(()=>{Mr.get(t)===r&&Mr.delete(t)})),r}function du(e){let t=uu(e);return!e.id||!t?Promise.resolve({status:"unpublished"}):lu(e.id,t.releaseItemId,t.version)}function pu(e){let[t,n]=(0,v.useState)(null),[r,s]=(0,v.useState)("loading"),[i,o]=(0,v.useState)(null),a=(0,v.useRef)(null),c=e!=null,u=e?.id||null,l=e?uu(e):null,p=l?.releaseItemId??null,h=l?.version??null;return(0,v.useEffect)(()=>{if(!c)return;let f=()=>{a.current?.cssKey&&We(a.current.cssKey),a.current=null,n(null)};if(!u||!p||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 b=null;try{let g=await lu(u,p,h);if(m)return;if(g.status!=="ready"){f(),s(g.status);return}let y=Hi.get(p);if(!y){if(y=cu(g.script),!y)throw new Error("The published script did not hand over a component. Expected a __FSAOS_REGISTER__(Component) call or window.__FSAOS_COMPONENT__.");if(typeof y!="function")throw new Error(`The published script handed over something that is not a React component (${typeof y}).`);Hi.set(p,y)}let _=g.stylesheet?`release:${p}`:null;if(_&&(b=_,await au(_,async()=>g.stylesheet)),m){b&&We(b);return}let w=a.current?.cssKey??null;a.current={componentId:u,releaseItemId:p,cssKey:_},b=null,n({Component:y,version:h}),s("ready"),w&&We(w)}catch(g){if(b&&We(b),m)return;o(g instanceof Error?g:new Error(String(g))),a.current||s("error")}})(),()=>{m=!0}},[c,u,p,h]),(0,v.useEffect)(()=>()=>{a.current?.cssKey&&We(a.current.cssKey),a.current=null},[]),{Component:t?.Component??null,status:r,error:i,version:t?.version??null}}var ap=["--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 fu(){return{data:(0,v.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let t={},n=getComputedStyle(document.documentElement);return ap.forEach(r=>{t[r]=n.getPropertyValue(r).trim()}),{tokens:t}},[]),loading:!1,error:null}}function mu(e,t){return{data:{allowed:!0},loading:!1,error:null}}function gu(e,t){let n={};return(t||[]).forEach(r=>{n[r]=!0}),{data:n,loading:!1,error:null}}var fe=null,Bn=null,ji=new Set;function cp(){ji.forEach(e=>e())}ie(()=>{fe=null,Bn=null});async function hu(e){let t={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null},n=xt()?.principal_id??null;if(n){if(fe&&fe.principalId===n){let{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}=fe;return{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}}return{...t,principalId:n}}let r=e;if(!r){let{data:s}=await $.auth.getSession();r=s?.session?.user?.id}if(!r)return t;if(fe&&fe.authUserId===r){let{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}=fe;return{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}}return Bn||(Bn=(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(p=>p.path);a=l.find(p=>p.split("/").length===4)??l[0]??null}let c={principalId:o,displayName:s?.display_name??null,createdAt:s?.created_at??null,metadata:s?.metadata??null,vfsPath:a};return fe={authUserId:r,...c},c}finally{Bn=null}})(),Bn)}async function yu(e){return(await hu(e)).principalId}function _u(){let e=Os(),t=e.user,n=fe?.authUserId===t?.id?fe:null,[r,s]=(0,v.useState)(n),i=(0,v.useRef)(null);return(0,v.useEffect)(()=>{let o=()=>{let a=fe;a&&a.authUserId===t?.id&&s({principalId:a.principalId,displayName:a.displayName,createdAt:a.createdAt,metadata:a.metadata,vfsPath:a.vfsPath})};return ji.add(o),()=>{ji.delete(o)}},[t?.id]),(0,v.useEffect)(()=>{if(!t?.id){s(null),i.current=null;return}i.current===t.id&&r?.principalId!=null||(i.current=t.id,hu(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 vu(e){let{path:t,...n}=e,r=$i(t),s=r.Component,{loading:i,error:o}=r;return i?(0,v.createElement)("div",{className:"fsaos-loading"},""):o?(0,v.createElement)("div",{className:"fsaos-error"},"Failed to load component"):s?(0,v.createElement)(s,n):null}function bu(e){return e.children}function wu(e){let t=re(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=e,o=i!==void 0?i&&!!n:!!n,a=(0,v.useMemo)(()=>E.channelMessages(n??"",r),[n,r,t]),c=L(),u=(0,v.useRef)(null),l=B({queryKey:a,queryFn:()=>Rs(n,r),enabled:o});(0,v.useEffect)(()=>{if(!s||!o)return;let b=oe("vfs_change",()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{Se(c,a,{exact:!0})},500)},g=>{let y=c.getQueryData(a);return Li(g,n,r,[...y?.messages??[],...y?.activityMessages??[]])});return()=>{b(),u.current&&clearTimeout(u.current)}},[s,o,n,r,a,c]);let p=l.data,h=p?.messages??[],f=p?.messageCards??new Map,m=p?.siblingCards??[];return{messages:h,activityMessages:p?.activityMessages??[],messageCards:f,siblingCards:m,threads:(0,v.useMemo)(()=>h.filter(b=>b.reply_count>0),[h]),breakouts:(0,v.useMemo)(()=>h.filter(b=>b.member_count>0),[h]),isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function Su(e){re();let{channelPath:t,parentMessageId:n,limit:r=50,realtime:s=!0,enabled:i=!0,conversationsOnly:o=!1,transcriptOnly:a=!1}=e,c=!!n,u=i&&!!t,l=dr({queryKey:[...E.channelMessages(t||"",n),"infinite",r,"latest-first",...o?["conversations"]:[],...a?["transcript"]:[]],queryFn:async({pageParam:y})=>Cr(t,{parentMessageId:n,limit:r,conversationsOnly:o,transcriptOnly:a,before_seq:y?.before_seq,after_seq:y?.after_seq}),initialPageParam:void 0,getPreviousPageParam:y=>{if(!c||y.messages.length<r)return;let _=y.messages[y.messages.length-1]?.seq;return _==null?void 0:{after_seq:_}},getNextPageParam:y=>{if(y.messages.length<r)return;let _=y.messages[0]?.seq;return _==null?void 0:{before_seq:_}},enabled:u}),p=(0,v.useMemo)(()=>{if(!l.data?.pages)return[];let y=new Set,_=[];for(let w of l.data.pages)for(let R of w.messages)y.has(R.id)||(y.add(R.id),_.push(R));return _.sort((w,R)=>w.seq-R.seq)},[l.data?.pages]),{messageCards:h,siblingCards:f}=(0,v.useMemo)(()=>{let y=new Map,_=[];if(!l.data?.pages)return{messageCards:y,siblingCards:_};let w=new Set;for(let R of l.data.pages){for(let[P,M]of R.messageCards)for(let D of M){if(w.has(D.id))continue;w.add(D.id);let C=y.get(P)||[];C.push(D),y.set(P,C)}for(let P of R.siblingCards)w.has(P.id)||(w.add(P.id),_.push(P))}return{messageCards:y,siblingCards:_}},[l.data?.pages]),m=L(),b=(0,v.useRef)(null),g=(0,v.useMemo)(()=>[...E.channelMessages(t||"",n),"infinite",r,"latest-first",...o?["conversations"]:[],...a?["transcript"]:[]],[t,n,r,o,a]);return(0,v.useEffect)(()=>{if(!s||!t||!u)return;let y=()=>void Se(m,g,{exact:!0}),_=!1,w=!1,R=!1,P=async()=>{if(o||a){y();return}let C=m.getQueryData(g);if(!C?.pages?.length){y();return}let A=0;for(let k of C.pages)for(let T of k.messages)T.seq>A&&(A=T.seq);if(A===0){y();return}try{let k=await Cr(t,{parentMessageId:n,limit:r,after_seq:A});if(k.messages.length===0&&k.siblingCards.length===0){y();return}if(k.messages.length>0){let T=Math.min(...k.messages.map(O=>O.seq));if(T>A+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${A}, minNewSeq=${T}. Triggering full refetch.`),y();return}}m.setQueryData(g,T=>{if(!T)return T;let O=[...T.pages],Q=0,K=O[Q],Z=new Set(K.messages.map(V=>V.id)),De=k.messages.filter(V=>!Z.has(V.id)),lt=[...K.messages,...De].sort((V,Mt)=>V.seq-Mt.seq),Ge=new Map(K.messageCards);for(let[V,Mt]of k.messageCards){let po=Ge.get(V)||[],Nl=new Set(po.map(Ls=>Ls.id)),Ql=Mt.filter(Ls=>!Nl.has(Ls.id));Ge.set(V,[...po,...Ql])}let ze=new Set(K.siblingCards.map(V=>V.id)),kt=k.siblingCards.filter(V=>!ze.has(V.id)),ae=[...K.siblingCards,...kt];return O[Q]={...K,activityMessages:k.activityMessages??[],messages:lt,messageCards:Ge,siblingCards:ae},{...T,pages:O}})}catch(k){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",k),y()}},M=async()=>{if(_){w=!0;return}_=!0;try{do w=!1,await P();while(w&&!R)}finally{_=!1}},D=oe("vfs_change",()=>{b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{M()},500)},C=>(o||a)&&C?.item_type==="message"&&(m.getQueryData(g)?.pages??[]).some(A=>A.messages.some(k=>k.id===C.parent_id))||Li(C,t,n,m.getQueryData(g)?.pages.flatMap(A=>A.messages)??[]));return()=>{R=!0,D(),b.current&&clearTimeout(b.current)}},[s,t,u,g,m,n,r,o,a]),{messages:p,activityMessages:l.data?.pages[0]?.activityMessages??[],messageCards:h,siblingCards:f,threads:p.filter(y=>y.reply_count>0),breakouts:p.filter(y=>y.member_count>0),isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch,hasPreviousPage:l.hasNextPage??!1,fetchPreviousPage:l.fetchNextPage,isFetchingPreviousPage:l.isFetchingNextPage??!1,hasNextPage:l.hasPreviousPage??!1,fetchNextPage:l.fetchPreviousPage,isFetchingNextPage:l.isFetchingPreviousPage??!1}}var xu=["open","active","strict","hand_raise"];function up(e){return e==="open"||e==="active"||e==="strict"||e==="hand_raise"?e:e==="on"||e==="auto"?"active":"strict"}function lp(e){if(Array.isArray(e))return e.filter(t=>typeof t=="string")}function Nc(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:up(t.ai_mode),activeAgentIds:lp(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 Fs(e={}){let t=re(),{realtime:n=!0,enabled:r=!0,includeArchived:s=!1}=e,i=L(),o=(0,v.useMemo)(()=>E.channels("all"),[t]),a=B({queryKey:o,queryFn:async()=>((await x("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(Nc),enabled:r});return(0,v.useEffect)(()=>{if(!(!n||!r))return Ac(i,o,Nc)},[n,r,o,i]),{channels:(0,v.useMemo)(()=>(a.data??[]).filter(u=>s||!u.isArchived),[a.data,s]),isLoading:a.isLoading,isFetching:a.isFetching,error:a.error,refetch:a.refetch}}function Ru(e={}){let t=Fs(e),n=(0,v.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function Pu(e={}){let t=Fs(e),n=(0,v.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function Wi(e={}){let t=re(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=e,o=L(),a=(0,v.useRef)(null),c=(0,v.useMemo)(()=>E.notifications(n,r),[n,r,t]),u=B({queryKey:c,queryFn:async()=>{let p={limit:r};return n==="unread"&&(p.filter="unread"),(await x("get-notifications",p)).notifications||[]},enabled:i});return(0,v.useEffect)(()=>{if(!s||!i)return;let p=["vfs_change","ccm_change"].map(h=>oe(h,()=>{a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{o.invalidateQueries({queryKey:c})},2e3)},f=>f.item_type==="notification"&&As(f)));return()=>{p.forEach(h=>h()),a.current&&clearTimeout(a.current)}},[s,i,c,o]),{notifications:u.data??[],isLoading:u.isLoading,isFetching:u.isFetching,error:u.error,refetch:u.refetch}}function Cu(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:o,error:a,refetch:c}=Wi({filter:"unread",limit:200,realtime:n,enabled:r}),u=(0,v.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,v.useMemo)(()=>{let f=0;return u.forEach(m=>{f+=m}),f},[u]),{dmUnread:p,channelUnread:h}=(0,v.useMemo)(()=>{if(!t)return{dmUnread:0,channelUnread:0};let f=new Set(t.filter(g=>g.isDm).map(g=>g.id)),m=0,b=0;return u.forEach((g,y)=>{f.has(y)?m+=g:b+=g}),{dmUnread:m,channelUnread:b}},[t,u]);return{unreadByChannel:u,totalUnread:l,dmUnread:p,channelUnread:h,isLoading:i,isFetching:o,error:a,refetch:c}}function Eu(){let e=L();return se({mutationFn:t=>x("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:E.children(r)})}})}function Iu(){let e=L();return se({mutationFn:t=>x("update",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.invalidateQueries({queryKey:E.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:E.children(i)})}}})}function Tu(){return se({mutationFn:e=>x("update-principal",e),onSuccess:(e,t)=>{if(!fe)return;let n=e&&typeof e=="object"&&e.metadata?e.metadata:{...fe.metadata??{},...typeof t.language=="string"?{language:t.language}:{},...typeof t.timezone=="string"?{timezone:t.timezone}:{},..."avatar_file_id"in t?{avatar_file_id:t.avatar_file_id}:{}};fe={...fe,displayName:typeof t.display_name=="string"?t.display_name:fe.displayName,metadata:n},cp()}})}function Au(){let e=L();return se({mutationFn:t=>x("delete",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.removeQueries({queryKey:E.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:E.children(i)})}}})}function ku(){let e=L();return se({mutationFn:t=>x("move",t),onSuccess:(t,n)=>{let r=n.path,s=n.new_parent_path;if(r){e.invalidateQueries({queryKey:E.item(r)});let i=r.split("/");i.pop();let o=i.join("/");o&&e.invalidateQueries({queryKey:E.children(o)})}s&&e.invalidateQueries({queryKey:E.children(s)})}})}function Mu(){let e=L();return se({mutationFn:t=>x("link",t),onSuccess:(t,n)=>{let r=n.source_id,s=n.target_id;r&&e.invalidateQueries({queryKey:E.edges(r)}),s&&e.invalidateQueries({queryKey:E.edges(s)})}})}function Ou(e,t){let n=L(),{optimistic:r,...s}=t??{};return se({mutationFn:i=>x(e,i),onMutate:r?async i=>{await n.cancelQueries({queryKey:r.queryKey});let o=n.getQueryData(r.queryKey);return n.setQueryData(r.queryKey,a=>r.update(a,i)),{previous:o}}:void 0,onError:(i,o,a)=>{r&&a?.previous!==void 0&&n.setQueryData(r.queryKey,a.previous),s.onError?.(i)},onSuccess:s.onSuccess,onSettled:r?()=>{n.invalidateQueries({queryKey:r.queryKey})}:void 0})}function Fu(e,t,n){let r,s,i,o=!0;if(typeof e=="string")r=e,s=t,i=n;else{s=e;let u=t;r=u.eventType,i=u.filter,o=u.enabled??!0}let a=(0,v.useRef)(s),c=(0,v.useRef)(i);(0,v.useEffect)(()=>{a.current=s,c.current=i},[s,i]),(0,v.useEffect)(()=>o?oe(r,l=>a.current(l),c.current?l=>c.current(l):void 0):void 0,[r,o])}function qu(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:o=500}=e,a=L(),c=(0,v.useRef)(s);c.current=s;let u=(0,v.useRef)(null),l=B({queryKey:t,queryFn:n,enabled:i});return(0,v.useEffect)(()=>{if(!i)return;let p=oe(r,()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{Se(a,t,{exact:!0})},o)},h=>c.current?.(h)??!0);return()=>{p(),u.current&&clearTimeout(u.current)}},[r,i,o,a,JSON.stringify(t)]),l}function Vn(e){re();let t=G(),n=(0,v.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=B({queryKey:o,staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0},queryFn:async()=>{if(!n)return null;let f=await x("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,v.useMemo)(()=>c?.resolved_children??[],[c]),l=c?.resolution_level??null,p=(0,v.useMemo)(()=>{let m=(c?.type_data??null)?.order;return Array.isArray(m)?m:null},[c]),h=(0,v.useCallback)(f=>{if(!p||!f?.length)return f??[];let m=_=>_.id??_.name??"",b=new Map(p.map((_,w)=>[_,w])),g=[],y=[];for(let _ of f)(b.has(m(_))?g:y).push(_);return g.sort((_,w)=>b.get(m(_))-b.get(m(w))),[...g,...y]},[p]);return{...a,arrangement:c,resolvedChildren:u,resolutionLevel:l,order:p,sourceScopeId:c?.scope_item_id??null,arrangementQueryKey:o,applyTo:h}}function Nu(e){let{origin:t,originField:n,fallbackUrl:r,mintError:s,scopeId:i,scopePath:o}=e,a=re(),c=xt(),u=i??c?.scope_id??null,l=(0,v.useMemo)(()=>{if(!t)return null;let P="/accounts/",M=t.indexOf(P);if(M===-1)return null;let D=t.indexOf("/",M+P.length);return D===-1?t:t.slice(0,D)},[t]),p=o??l??c?.scope_path??null,h=n?.trim()||null,f=`${a}
4
4
  ${u??""}
5
- ${f??""}
5
+ ${p??""}
6
6
  ${h??""}
7
- ${t??""}`,[m,y]=(0,b.useState)(null),g=(0,b.useRef)({key:p,found:null,earlyContentPaths:new Set}),v=m?.key===p?m:null;(0,b.useLayoutEffect)(()=>{g.current={key:p,found:v,earlyContentPaths:new Set}},[p]);let _=B({queryKey:["vfs",f??"__unscoped__","minted-asset",h??"",t??""],queryFn:async()=>{let R=await x("query",{scope_path:f,filters:{[`field.${h}`]:t},limit:1}),M=R.content?.items??R.items??[],D=M[0]?Oe(M[0]):null;if(!D)return null;let k=(await _r(D.path)).some(T=>T.item_type==="file"&&!!T.type_data?.file_ref);return{asset:D,hasBytes:k}},enabled:!!(t&&f&&h&&!s),refetchInterval:R=>g.current.key===p&&g.current.found?.hasBytes||R.state.data?.hasBytes?!1:1500});(0,b.useEffect)(()=>{let R=_.data;if(!R||g.current.key!==p)return;let M=g.current.found,D={key:p,itemId:R.asset.id,itemPath:R.asset.path,displayName:typeof R.asset.type_data?.display_name=="string"?R.asset.type_data.display_name:R.asset.name,hasBytes:R.hasBytes||!!(M?.itemId===R.asset.id&&M.hasBytes)};g.current.found=D,y(D)},[_.data,p]);let w=!!(t&&u)&&!s&&!v?.hasBytes;return(0,b.useEffect)(()=>{if(!(!w||!u))return Fn(u,["asset.materialized","content.written"])},[w,u]),(0,b.useEffect)(()=>{if(!w||!t||!u)return;let R=p,M=A=>A?.payload??A,D=A=>{let q=M(A)?.scope_id??A?.scope_id;return typeof q=="string"?q:void 0},P=A=>{let q=M(A)?.item_path??A?.item_path;return typeof q=="string"&&q?q:void 0},k=(A,O)=>{let q=O.replace(/\/+$/,"");return A===q||A.startsWith(`${q}/`)},T=[ie("asset.materialized",A=>{if(g.current.key!==R)return;let O=M(A);if(typeof O?.item_id!="string"||!O.item_id)return;let q=g.current.found,K=typeof O.item_path=="string"?O.item_path:void 0,$=!!O.has_bytes||!!(K&&Array.from(g.current.earlyContentPaths).some(re=>k(re,K)))||!!(q&&q.itemId===O.item_id&&q.hasBytes),Pe={key:R,itemId:O.item_id,itemPath:K,displayName:typeof O.display_name=="string"?O.display_name:void 0,hasBytes:$};g.current.found=Pe,y(Pe)},A=>{let O=D(A);return(!O||O===u)&&M(A)?.origin===t}),ie("content.written",A=>{if(g.current.key!==R)return;let O=P(A);if(!O)return;let q=g.current.found;if(!q?.itemPath||!k(O,q.itemPath)){if(g.current.earlyContentPaths.add(O),g.current.earlyContentPaths.size>128){let $=g.current.earlyContentPaths.values().next().value;$&&g.current.earlyContentPaths.delete($)}return}if(q.hasBytes)return;let K={...q,hasBytes:!0};g.current.found=K,y(K)},A=>{let O=D(A);return(!O||O===u)&&!!P(A)})];return()=>T.forEach(A=>A())},[w,t,u,p]),{state:s?"failed":t?v?v.hasBytes?"ready":"materializing":"pending":"idle",itemId:v?.itemId,itemPath:v?.itemPath,displayName:v?.displayName,fallbackUrl:r??void 0,error:s??void 0}}function Mu(e,t){let n=N().getDefaultOptions().queries?.retry??1;return typeof n=="function"?n(e,t):n===!0||typeof n=="number"&&e<n}function Ou(e,t,n){let r=(0,Pt.useSyncExternalStore)(xe,ee,ee),s=de(),i=W(),o=n?.path??i,a=n?.id??s?.id,c=!!(n?.id&&n.path)||s?.kind==="space",u=(0,Pt.useMemo)(()=>({}),[r,i,o,a]),l=(0,Pt.useRef)(u);l.current=u;let f=Kn(c&&o?{key:e,scope_id:a,_scope_path:o}:null),h=(0,Pt.useMemo)(()=>{let _=f.applyTo([...t]);if(e!=="channel-order")return _;let w=new Set(f.order??[]),C=_.filter(M=>!w.has(M.id)),R=M=>Date.parse(M.createdAt??"")||0;return C.sort((M,D)=>R(D)-R(M)),[...C,..._.filter(M=>w.has(M.id))]},[e,t,f.applyTo,f.order]),p=L(),m=(0,Pt.useRef)(!1),y=!!(c&&!f.error&&f.arrangement?.item_id&&f.resolutionLevel==="member"&&f.arrangement.write_target_id===f.arrangement.item_id),g=ne({mutationFn:async _=>{let w=await x("update",{_scope_path:_.scopePath,id:_.arrangementId,type_data:{order:_.ids}});if(w?.success===!1)throw new Error(w.error||"Order could not be saved");return w},onSettled:(_,w,C)=>rt(p,C.queryKey)});async function v(_){if(!y||!o||u!==l.current||r!==ee()||W()!==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 w=t.map(T=>T.id);if(_.length!==w.length||new Set(_).size!==w.length||w.some(T=>!_.includes(T)))throw new Error("Order must include each displayed item exactly once");let C=p.getQueryData(f.arrangementQueryKey);if(C?.item_id!==f.arrangement.item_id||JSON.stringify(C?.type_data?.order??[])!==JSON.stringify(f.order??[]))throw new Error("The saved order changed. Try dragging again");let R=h.map(T=>T.id);if(_.every((T,A)=>R[A]===T))return;let M=new Set(w),D=0,k=[...(f.order??[]).map(T=>M.has(T)?_[D++]:T),..._.slice(D)];m.current=!0;try{return await g.mutateAsync({ids:k,scopePath:o,arrangementId:f.arrangement.item_id,queryKey:f.arrangementQueryKey})}finally{m.current=!1}}return{items:h,ready:y,supported:c,contextKey:`${r}:${o}:${e}`,isLoading:c&&f.isLoading,error:f.error,refetch:f.refetch,isSaving:g.isPending,saveError:g.error,reorder:v}}var Bi=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,uf=/^[A-Za-z_:][A-Za-z0-9_:.-]{0,127}$/,Fu=new Map,qu=new Map,Ln=class extends Error{constructor(n,r,s,i){super(n);z(this,"code");z(this,"status");z(this,"eventId");this.name="InteractionTrackingError",this.code=r,this.status=s,this.eventId=i}};function zt(e){let t=e?Dt.find(n=>n.id===e):Dt.find(n=>n.default===!0)??(Dt.length===1?Dt[0]:void 0);if(!t)throw new TypeError("No unambiguous source is declared for this release");if(!t.id||!Number.isInteger(t.version)||t.version<1)throw new TypeError("The release source declaration is invalid");return t}function As(e,t){let n=t.adapters?.find(r=>r.type===e);if(!n)throw new TypeError(`The source does not declare a ${e} adapter`);return n}function lf(e){return e.length>0&&e.length<=128&&!/[\u0000-\u001f\u007f]/.test(e)}function df(e,t){if(!lf(t)||!e.observations?.includes(t))throw new TypeError("The observation is not declared by this release source")}function $i(e){if(!(typeof window>"u"||e.storage==="memory"))try{return e.storage==="session"?window.sessionStorage:window.localStorage}catch{return}}function ff(e){try{let t=$i(e)?.getItem(e.key)??void 0;return t&&Bi.test(t)?t:void 0}catch{return}}function Nu(e,t){try{$i(e)?.setItem(e.key,t)}catch{}}function Qu(e){let t=e.identity?.visitor;if(!t?.key)throw new TypeError("The source visitor identity policy is invalid");let n=ff(t)??Fu.get(e.id);if(n)return n;let r=crypto.randomUUID();return Fu.set(e.id,r),Nu(t,r),r}function Du(e,t=Date.now()){let n=e.identity?.session;if(!n?.key||!Number.isInteger(n.idle_seconds)||n.idle_seconds<1)throw new TypeError("The source session identity policy is invalid");let r;try{let u=$i(n)?.getItem(n.key);r=u?JSON.parse(u):void 0}catch{r=void 0}let s=qu.get(e.id),i=r&&typeof r.id=="string"&&Bi.test(r.id)&&typeof r.lastSeenAt=="number"?{id:r.id,lastSeenAt:r.lastSeenAt}:s,o=n.idle_seconds*1e3,c=i&&t-i.lastSeenAt>=0&&t-i.lastSeenAt<o?{id:i.id,lastSeenAt:t}:{id:crypto.randomUUID(),lastSeenAt:t};return qu.set(e.id,c),Nu(n,JSON.stringify(c)),c.id}function pf(e,t){let n=e.source_keys?.query;if(!Array.isArray(n)||n.length===0)return;let r;try{r=new URL(t)}catch{return}let s=e.source_keys?.max_value_length,i=Number.isInteger(s)?Math.min(Math.max(s??1,1),4096):512,o=Object.fromEntries(n.flatMap(a=>{if(typeof a!="string"||a.length===0||a.length>128)return[];let c=r.searchParams.get(a);return c?[[a,c.slice(0,i)]]:[]}));return Object.keys(o).length>0?o:void 0}async function Jt(e,t={},n={}){let r=zt(n.source);if(df(r,e),!t||typeof t!="object"||Array.isArray(t))throw new TypeError("properties must be an object");let s=n.eventId??crypto.randomUUID(),i=n.visitorId??Qu(r),o=n.sessionId??Du(r);if(![s,i,o].every(g=>Bi.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=pf(r,a),f=l?{...t,source_keys:l}:t,h=Lt(),p=`${Te.replace(/\/+$/,"")}/d/${encodeURIComponent(h)}/interactions`,m;try{m=await fetch(p,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({source:r.id,page_url:a,visitor_id:i,session_id:o,referrer:u,events:[{id:s,event_type:e,occurred_at:c,properties:f}]}),signal:n.signal,credentials:"omit",keepalive:n.keepalive??!1})}catch(g){throw new Ln(g instanceof Error?g.message:"Observation transport network error","OBSERVATION_NETWORK_ERROR",0,s)}let y=null;try{y=await m.json()}catch{}if(!m.ok||y?.success!==!0){let g=y;throw new Ln(g?.message||g?.error||`Observation transport failed (${m.status})`,g?.error||"OBSERVATION_TRANSPORT_FAILED",m.status,s)}return y}function Uu(e={},t={}){let n=zt(t.source),r=As("page_view",n),s=typeof document>"u"||!r.title_property?{}:{[r.title_property]:document.title.slice(0,512)};return Jt(r.observation,{...s,...e},{...t,source:n.id})}function Ku(e,t={},n={}){if(!e||e.length>128)throw new TypeError("actionId is invalid");let r=zt(n.source),s=As("declared_action",r),i=s.id_property?{[s.id_property]:e}:{};return Jt(s.observation,{...t,...i},{...n,source:r.id})}function Lu(){try{let e=zt();return As("form_receipt",e),{visitor_id:Qu(e),session_id:Du(e),source:e.id}}catch{return}}function mf(e,t={}){let n=zt(t.source),r=As("form_receipt",n);return Jt(r.observation,e,{...t,source:n.id})}async function gf(e,t){let r=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${e}\0${t}`))).slice(0,16);r[6]=r[6]&15|80,r[8]=r[8]&63|128;let s=Array.from(r,i=>i.toString(16).padStart(2,"0")).join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}async function Hu(e,t,n,r,s){let i=Dt.filter(o=>o.adapters?.some(a=>a.type==="form_receipt"));await Promise.allSettled(i.map(async o=>{let a=o.id===r?.source;return mf(e,{source:o.id,eventId:a?t:await gf(t,o.id),pageUrl:n,signal:s,keepalive:!0,...a?{visitorId:r.visitor_id,sessionId:r.session_id}:{}})}))}var Tr;function ks(e={}){if(typeof window>"u"||typeof document>"u")return()=>{};if(Tr)return Tr;if(window.__FSAOS_CONFIG__?.tracking?.enabled===!1)return()=>{};let t;try{t=e.source?[zt(e.source)]:Dt.map(h=>zt(h.id))}catch{return()=>{}}if(t.length===0)return()=>{};let n=e.pageViews===!1?[]:t.flatMap(h=>h.adapters.filter(p=>p.type==="page_view").map(p=>({source:h,adapter:p}))),r=e.declaredActions===!1?[]:t.flatMap(h=>h.adapters.filter(p=>p.type==="declared_action").map(p=>({source:h,adapter:p}))),s="",i=()=>{if(window.location.href!==s){s=window.location.href;for(let{source:h,adapter:p}of n){let m=p.title_property?{[p.title_property]:document.title.slice(0,512)}:{};Jt(p.observation,m,{source:h.id,keepalive:!0}).catch(()=>{})}}},o=h=>{if(h.target instanceof Element)for(let{source:p,adapter:m}of r){let y=m.attribute;if(!y||!uf.test(y))continue;let g=h.target.closest(`[${y}]`);if(!g)continue;let v=g.getAttribute(y)?.trim();if(!v||v.length>128)continue;let _={};m.id_property&&(_[m.id_property]=v),m.element_property&&(_[m.element_property]=g.tagName.toLowerCase()),Jt(m.observation,_,{source:p.id,keepalive:!0}).catch(()=>{})}},a=window.history.pushState,c=window.history.replaceState,u=()=>queueMicrotask(i),l=n.some(({adapter:h})=>h.history===!0),f=n.some(({adapter:h})=>h.pageshow===!0);return l&&(window.history.pushState=function(...p){a.apply(this,p),u()},window.history.replaceState=function(...p){c.apply(this,p),u()},window.addEventListener("popstate",i)),f&&window.addEventListener("pageshow",i),r.length>0&&document.addEventListener("click",o,{capture:!0}),n.length>0&&queueMicrotask(i),Tr=()=>{window.removeEventListener("popstate",i),window.removeEventListener("pageshow",i),document.removeEventListener("click",o,{capture:!0}),l&&(window.history.pushState=a,window.history.replaceState=c),Tr=void 0},Tr}var Hn;se(()=>{Hn=void 0});function Ms(e){if(Hn)return Hn.accountPath!==e.accountPath?Promise.reject(new Error("Reset the session before changing accounts")):Hn.promise;let t=ae(),n=()=>{if(t!==ae())throw new Error("Workspace session changed")},r=(async()=>{let s=await nt();if(n(),!s.principal_id)throw new Error("Workspace initialization requires an authenticated principal");let i=await N().fetchQuery({queryKey:E.memberships(s.principal_id),queryFn:bs,staleTime:12e4,retry:!1});n();let o=i.find(f=>f.path===e.accountPath&&f.isAccount&&!f.isSpace);if(!o)throw new Error("Authenticated account membership is unavailable");let a=i.find(f=>f.isSpace&&f.accountId===o.personalSpaceId&&f.path===o.personalSpacePath);if(!a||!o.personalSpacePath)throw new Error("A provisioned default Space membership is required");let c=$e(o),u=$e(a),l=me();if(l&&l.id!==c.id)throw new Error("Reset the session before changing accounts");return l||Kt(c,{activate:!1}),await Gt(o.personalSpacePath,f=>{let h=i.find(p=>p.accountId===f&&(p.isAccount||p.isSpace));return h?$e(h):null},{initialAnchor:u}),n(),{home:c,defaultSpace:u,memberships:i}})().catch(s=>{throw t===ae()&&(Hn=void 0),s});return Hn={accountPath:e.accountPath,promise:r},r}var Yt,kr,Ar;se(()=>{kr?.(),kr=void 0,Yt=void 0,Ar=void 0});function ju(e={}){if(Yt)return e.workspace&&e.workspace.accountPath!==Ar?Promise.reject(new Error("Initialize workspace through initializeWorkspace, or dispose the existing runtime first")):Yt;Ar=e.workspace?.accountPath;let t=ae();return Yt=(async()=>{let n=e.tracking??!0,r=n===!1?()=>{}:ks(typeof n=="object"?n:{});kr=r;try{let s=e.session===!1?null:await nt(),i=e.workspace?await Ms(e.workspace):void 0;if(t!==ae())throw new Error("Session changed during initialization");let o=!1;return{session:s,workspace:i,dispose(){o||(o=!0,r(),t===ae()&&(Yt=void 0,Ar=void 0,kr=void 0))}}}catch(s){throw r(),t===ae()&&(Yt=void 0,Ar=void 0,kr=void 0),s}})(),Yt}function hf(e){return e instanceof Fe?{kind:"denied",payload:e.payload}:e instanceof ge?{kind:"gateway",method:e.method,status:e.status,statusText:e.statusText,payload:e.payload,responseBody:e.responseBody}:e instanceof Error?{kind:"other",name:e.name,message:e.message}:{kind:"other",name:"Error",message:String(e)}}function Bu(e){let t=(s,i)=>{s.postMessage(i,e.origin)},n=!0,r=s=>{if(s.origin!==e.origin)return;let i=e.frame();if(!i||s.source!==i||!wi(s.data))return;let o=s.data;if(o.kind==="hello"){t(i,{fsaos:jt,kind:"welcome",anchor:de()??_t(),item:e.item?.()??null});return}if(o.kind!=="call"||typeof o.id!="string"||typeof o.method!="string")return;let{id:a,method:c,params:u}=o;x(c,u&&typeof u=="object"?u:{}).then(l=>{n&&t(i,{fsaos:jt,kind:"result",id:a,ok:!0,response:l})},l=>{n&&t(i,{fsaos:jt,kind:"result",id:a,ok:!1,error:hf(l)})})};return window.addEventListener("message",r),()=>{n=!1,window.removeEventListener("message",r)}}async function Vi(e){try{return await x("execution-control-transition",e)}catch(t){if(!(t instanceof ge)||t.status<500)throw t;return await new Promise(n=>setTimeout(n,250)),x("execution-control-transition",e)}}function Wi(e){let t=e.conversation_anchor_item_id??e.conversation_root_id;return t?{...e,conversation_anchor_item_id:t,conversation_root_id:e.conversation_root_id??t}:e}async function $u(e,t={}){let n=e.trim();if(!n)throw new TypeError("cancelTurn requires a request message id");let r=(t.idempotencyKey??`cancel:${n}`).trim();if(!r)throw new TypeError("cancelTurn requires a non-empty idempotency key");if(r.length>128)throw new TypeError("cancelTurn idempotency key must be 128 characters or fewer");let s=await Vi({op:"request",command:"cancel",delivery:"immediate",request_message_id:n,idempotency_key:r,...t.scopePath?{_scope_path:t.scopePath}:{}}),i=s.outcome??s.state??s.status;return Wi(i?{...s,state:i}:s)}async function Vu(e,t,n={}){let r=e.trim(),s=t.trim();if(!r)throw new TypeError("steerTurn requires an active request message id");if(!s)throw new TypeError("steerTurn requires a selected queue entry id");if(r===s)throw new TypeError("steerTurn cannot target the active request message");let i=(n.idempotencyKey??`steer:${r}:${s}`).trim();if(!i)throw new TypeError("steerTurn requires a non-empty idempotency key");if(i.length>128)throw new TypeError("steerTurn idempotency key must be 128 characters or fewer");let o=await Vi({op:"request",command:"steer",delivery:"immediate",request_message_id:r,selected_queue_entry_id:s,idempotency_key:i,...n.scopePath?{_scope_path:n.scopePath}:{}}),a=o.outcome??o.state??o.status;return Wi(a?{...o,state:a}:o)}async function Wu(e,t={}){let n=e.trim();if(!n)throw new TypeError("cancelQueuedTurn requires a queue entry id");let r=(t.idempotencyKey??`cancel-queue:${n}`).trim();if(!r)throw new TypeError("cancelQueuedTurn requires a non-empty idempotency key");if(r.length>128)throw new TypeError("cancelQueuedTurn idempotency key must be 128 characters or fewer");let s=await Vi({op:"cancel_queue_entry",queue_entry_id:n,idempotency_key:r,...t.scopePath?{_scope_path:t.scopePath}:{}}),i=s.outcome??s.state??s.status;return Wi(i?{...s,outcome:i}:s)}var yf=/^[a-z][a-z0-9_-]{0,63}$/,_f=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,jn=class extends Error{constructor(n,r,s,i){super(n);z(this,"code");z(this,"status");z(this,"fillId");this.name="FormSubmissionError",this.code=r,this.status=s,this.fillId=i}};async function Gu(e,t,n={}){if(!yf.test(e))throw new TypeError("capabilityId is invalid");if(!t||typeof t!="object"||Array.isArray(t))throw new TypeError("fields must be an object");let r=n.fillId??crypto.randomUUID();if(!_f.test(r))throw new TypeError("fillId must be a UUID");let s=Lt(),i=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!i)throw new TypeError("pageUrl is required outside a browser");let o=`${Te.replace(/\/+$/,"")}/d/${encodeURIComponent(s)}/actions/${encodeURIComponent(e)}`,a=Lu(),c=a?{visitor_id:a.visitor_id,session_id:a.session_id}:void 0,u;try{u=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({fill_id:r,page_url:i,fields:t,...c?{attribution:c}:{}}),signal:n.signal,credentials:"omit"})}catch(f){throw new jn(f instanceof Error?f.message:"Form submission network error","FORM_NETWORK_ERROR",0,r)}let l=null;try{l=await u.json()}catch{}if(!u.ok||l?.success!==!0){let f=l;throw new jn(f?.message||f?.error||`Form submission failed (${u.status})`,f?.error||"FORM_SUBMISSION_FAILED",u.status,r)}return await Hu({fill_id:r,action_id:e,release_id:l.release_id},r,i,a,n.signal),l}var Gi=Y(ue(),1),Yu=Y(Ju(),1);function Zu(e){return x("read",{path:e})}function Xu(e,t){return x("list",{path:e,...t})}function el(e){return x("create",e)}function tl(e){return x("update",e)}function nl(e){return x("create",e)}function rl(e,t){let r=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return x("tools/call",{name:e,instance_path:r,...t||{}})}function sl(e,t,n){return x("signal",{target_id:e,event_name:t,payload:n||{}})}function il(e){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+e}var ol={signIn:e=>e.provider?V.auth.signInWithOAuth({provider:e.provider,options:{redirectTo:e.redirectTo||window.location.href}}):V.auth.signInWithPassword({email:e.email,password:e.password}),signUp:e=>V.auth.signUp({email:e.email,password:e.password,options:{data:e.metadata||{}}}),signOut:async()=>{await V.auth.signOut(),Cn(),N().clear()},getSession:()=>V.auth.getSession().then(e=>e.data.session),getUser:()=>V.auth.getUser().then(e=>e.data.user),onAuthStateChange:e=>{let{data:{subscription:t}}=V.auth.onAuthStateChange((n,r)=>{e({event:n,session:r,user:r?.user??null})});return()=>t?.unsubscribe()},resetPassword:e=>V.auth.resetPasswordForEmail(e),signInWithMagicLink:(e,t)=>V.auth.signInWithOtp({email:e,options:{emailRedirectTo:t||window.location.href}})};function al(){let e=document.getElementById("root");if(e)try{let t=window.__FSAOS_COMPONENT__;if(!t){e.innerHTML='<div style="padding:2rem;color:#ef4444;font-family:system-ui"><h2>Component Error</h2><pre>No component found. The bundle may have failed to load.</pre></div>';return}let n=t.default||t,r=window.__FSAOS_ITEM_DATA__||null,s=r?{item:r,...r}:{};(0,Yu.createRoot)(e).render((0,Gi.createElement)(sr,{client:N()},(0,Gi.createElement)(n,s)))}catch(t){console.error("[FSAOS] Failed to mount root component:",t),e.innerHTML='<div style="padding:2rem;color:#ef4444;font-family:system-ui"><h2>Component Error</h2><pre>'+(t.message||t)+"</pre></div>"}}function cl(){let e=window.React,t=window.ReactDOM,n=window.__FSAOS_GATEWAY__,r=window.__FSAOS_UI__;if(!n){console.error("[FSAOS] Cannot set up require shim: __FSAOS_GATEWAY__ not found");return}let s={react:e,"react-dom":t,"react-dom/client":t,"react/jsx-runtime":{jsx:e?.createElement,jsxs:e?.createElement,Fragment:e?.Fragment},"@fsaos/kernel":n,"@fsaos/react":n,"@fsaos/gateway":n,"@fsaos/ui":r||{}};window.require=function(o){if(s[o])return s[o];throw new Error("[FSAOS] Module not found: "+o)},window.__FSAOS_MOUNT__=n.mount}var vf=e=>x("create-invitation",{...e}),bf=e=>x("get-invitation",{invitation_id:e}),wf=e=>x("accept-invite",{invitation_id:e}),Sf=e=>x("reject-invite",{invitation_id:e}),xf=e=>x("cancel-invite",{invitation_id:e}),Rf=(e,t)=>x("resend-invite",{invitation_id:e,request_id:t}),Pf=(e,t)=>x("list-invitations",{account_id:e,...t?{after:t}:{}});function zi(e){return x("invite-member",e)}function Ji(e){return x("accept-invite",e)}function Yi(e){let t={};return e.role&&(t.role=e.role),x("link",{source_id:e.chat_id,target_id:e.member_id,edge_type:"has_member",context:t})}function Zi(e){return x("create-agent",e)}function Xi(e){return!e.input_request_id&&!e.input_request?Promise.reject(new Error("answerInput needs input_request_id or the input_request object read from the step.")):x("todo-control",{action:"answer_input",...e})}function ul(){return ne({mutationFn:zi})}function ll(){let e=L();return ne({mutationFn:Ji,onSuccess:()=>{e.invalidateQueries({queryKey:["memberships"]})}})}function dl(){let e=L();return ne({mutationFn:Yi,onSuccess:(t,n)=>{e.invalidateQueries({queryKey:E.edges(n.chat_id)}),e.invalidateQueries({queryKey:E.edges(n.member_id)})}})}function fl(){let e=L();return ne({mutationFn:Zi,onSuccess:()=>{e.invalidateQueries({queryKey:["memberships"]})}})}function pl(){let e=L();return ne({mutationFn:Xi,onSuccess:(t,n)=>{e.invalidateQueries({queryKey:E.itemById(n.step_id)})}})}function Cf(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Ef(e,t){return t&&t.length>0?"select":e==="boolean"?"toggle":e==="integer"||e==="number"?"range":e==="string"?"text":"none"}function If(e,t){return!(e==="object"||e==="array")}function Tf(e){return["string","number","integer","boolean"].includes(e)}function Af(e){return e!=="object"&&e!=="array"}function ml(e,t,n,r){let s=e?.properties;if(!s||typeof s!="object")return[];let i=[];for(let[o,a]of Object.entries(s)){let c=a.type||"string",u=a.enum,l=If(c,u),f=Tf(c),h=Ef(c,u);i.push({key:o,label:a.title||Cf(o),type:c,description:a.description,enum_values:u,default_value:n[o]??r[o]??a.default,editable:t,filterable:l,sortable:f,filter_widget:h})}return i}function eo(e){let t=e.default_data||{},n=e.field_defaults||{},r=ml(e.input_schema,!0,t,n),s=ml(e.system_schema,!1,t,n),i=[...r,...s],o=i.filter(u=>Af(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 gl(e){return{field:"updated_at",direction:"desc"}}function hl(e){let t=eo(e),n=new Set(e.input_schema?.required||[]);return t.form_fields.filter(r=>n.has(r.key)||r.default_value===void 0)}var we=Y(ue(),1);function yl(){if(globalThis.crypto?.randomUUID)return globalThis.crypto.randomUUID();let e=new Uint8Array(16);if(globalThis.crypto?.getRandomValues){globalThis.crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,n=>n.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let n=Math.floor(Math.random()*16);return(t==="x"?n:n&3|8).toString(16)})}async function _l(e,t,n,r){let s=t.name||(e instanceof File?e.name:`file-${Date.now()}`),i=e.type||"application/octet-stream",o=t.itemType||"file",a=t.collisionPolicy||"keep_both",c=a==="keep_both"?yl():void 0,u={parent_path:t.parentPath,item_type:o,name:s,type_data:{...t.typeData||{},file_source:{type:"upload",content_type:i,collision_policy:a,...c?{upload_id:c}:{}}}};t.cardParentPath&&(u.card_parent_path=t.cardParentPath);let f=await x("create",u);if(!f.id)throw new Error(f.error||f.message||"Failed to create file item");let h=f.id,p=f.path;if(f.storage_completed&&f.file_ref)return{itemId:h,itemPath:p,fileRef:f.file_ref};let m=f.storage_key,y=f.upload_token,g=f.storage_worker_url||"https://fsaos-storage.radns.workers.dev";if(!m)throw new Error("Gateway returned no storage_key \u2014 file_source may not be supported for this item type");await kf(g,m,y,e,i,n,r);let v=await vl(h,m,i);return{itemId:h,itemPath:p,fileRef:v}}function kf(e,t,n,r,s,i,o){return new Promise((a,c)=>{let u=new XMLHttpRequest;if(u.open("PUT",`${e}/upload`),u.setRequestHeader("X-Storage-Key",t),u.setRequestHeader("Content-Type",s),n&&u.setRequestHeader("X-Upload-Token",n),u.upload.onprogress=l=>{l.lengthComputable&&i&&i(Math.round(l.loaded/l.total*100))},u.onload=()=>{u.status>=200&&u.status<300?a():c(new Error(`Storage upload failed: HTTP ${u.status} \u2014 ${u.responseText?.slice(0,300)}`))},u.onerror=()=>c(new Error("Storage upload network error")),u.ontimeout=()=>c(new Error("Storage upload timed out")),o){if(o.aborted){c(new Error("Upload cancelled"));return}o.addEventListener("abort",()=>{u.abort(),c(new Error("Upload cancelled"))})}u.send(r)})}async function vl(e,t,n){let r=await tt(),s=await fetch(`${Te}/storage/upload-complete`,{method:"POST",headers:{"Content-Type":"application/json",...r?{Authorization:`Bearer ${r}`}:{}},body:JSON.stringify({item_id:e,storage_key:t,content_type:n})});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Upload confirmation failed: HTTP ${s.status} \u2014 ${o.slice(0,300)}`)}let i=await s.json();if(!i.success)throw new Error(i.error||i.message||"Upload confirmation rejected");return i.file_ref}function bl(){let[e,t]=(0,we.useState)([]),n=L(),r=(0,we.useRef)(e);r.current=e;let s=(0,we.useCallback)((y,g)=>{t(v=>v.map(_=>_.id===y?{..._,...g}:_))},[]),i=(0,we.useCallback)(y=>{t(g=>[...g,y])},[]),o=(0,we.useCallback)(async(y,g,v,_,w)=>{let C=v.name||g.name,R=g.type||"application/octet-stream",M=v.itemType||"file",D=v.collisionPolicy||"keep_both",P=w?.itemId||null,k=w?.itemPath||null,T=w?.storageKey||null,A=w?.uploadToken||null,O=w?.storageWorkerUrl||null;try{if(!_||_==="create"){s(y,{status:"creating",error:null,_failedAt:null});let $=await x("create",{parent_path:v.parentPath,item_type:M,name:C,type_data:{...v.typeData||{},file_source:{type:"upload",content_type:R,collision_policy:D,...D==="keep_both"?{upload_id:y}:{}}}});if(!$.id)throw Object.assign(new Error($.error||$.message||"Failed to create file item"),{_step:"create"});if(P=$.id,k=$.path,s(y,{itemId:P,itemPath:k}),$.storage_completed&&$.file_ref){s(y,{status:"complete",progress:100,fileRef:$.file_ref}),n.invalidateQueries({queryKey:E.children(v.parentPath)});return}if(T=$.storage_key,A=$.upload_token||"",O=$.storage_worker_url||"https://fsaos-storage.radns.workers.dev",s(y,{_storageKey:T,_uploadToken:A,_storageWorkerUrl:O}),!T)throw Object.assign(new Error("Gateway returned no storage_key"),{_step:"create"})}(!_||_==="create"||_==="upload")&&(s(y,{status:"uploading",progress:0,error:null,_failedAt:null}),await new Promise(($,Pe)=>{let re=new XMLHttpRequest;s(y,{_xhr:re}),re.open("PUT",`${O}/upload`),re.setRequestHeader("X-Storage-Key",T),re.setRequestHeader("Content-Type",R),A&&re.setRequestHeader("X-Upload-Token",A),re.upload.onprogress=Et=>{Et.lengthComputable&&s(y,{progress:Math.round(Et.loaded/Et.total*100)})},re.onload=()=>{re.status>=200&&re.status<300?$():Pe(Object.assign(new Error(`Storage upload failed: HTTP ${re.status}`),{_step:"upload"}))},re.onerror=()=>Pe(Object.assign(new Error("Storage upload network error"),{_step:"upload"})),re.ontimeout=()=>Pe(Object.assign(new Error("Storage upload timed out"),{_step:"upload"})),re.send(g)}),s(y,{progress:100,_xhr:null})),s(y,{status:"confirming",error:null,_failedAt:null});let q=await vl(P,T,R);s(y,{status:"complete",fileRef:q}),n.invalidateQueries({queryKey:E.children(v.parentPath)})}catch(q){let K=q?.message||String(q),$=q?._step||"create";s(y,{status:"error",error:K,_failedAt:$,_xhr:null})}},[s,n]),a=(0,we.useCallback)((y,g)=>{let v=yl();i({id:v,file:y,status:"creating",progress:0,error:null,itemId:null,itemPath:null,fileRef:null,options:g,_storageKey:null,_uploadToken:null,_storageWorkerUrl:null,_xhr:null,_failedAt:null}),o(v,y,g)},[i,o]),c=(0,we.useCallback)((y,g)=>{for(let v of y)a(v,g)},[a]),u=(0,we.useCallback)(y=>{let g=r.current.find(w=>w.id===y);if(!g||g.status!=="error")return;let v=g._failedAt||"create",_=g._storageKey&&g.itemId?{storageKey:g._storageKey,uploadToken:g._uploadToken||"",storageWorkerUrl:g._storageWorkerUrl||"https://fsaos-storage.radns.workers.dev",itemId:g.itemId,itemPath:g.itemPath||""}:void 0;o(y,g.file,g.options,v,_)},[o]),l=(0,we.useCallback)(y=>{let g=r.current.find(v=>v.id===y);g&&(g._xhr&&g._xhr.abort(),s(y,{status:"error",error:"Cancelled",_xhr:null,_failedAt:null}))},[s]),f=(0,we.useCallback)(y=>{t(g=>g.filter(v=>v.id!==y))},[]),h=(0,we.useCallback)(()=>{t(y=>y.filter(g=>g.status!=="complete"))},[]),p=e.some(y=>y.status==="creating"||y.status==="uploading"||y.status==="confirming"),m=e.map(({_storageKey:y,_uploadToken:g,_storageWorkerUrl:v,_xhr:_,_failedAt:w,...C})=>C);return{upload:a,uploadMultiple:c,uploads:m,retryUpload:u,cancelUpload:l,removeUpload:f,clearCompleted:h,isUploading:p}}var wl=Y(ue(),1);async function to(e,t){return await x("resolve-items",{context_id:e,item_type:t})}function Sl(e,t){return(0,wl.useSyncExternalStore)(xe,ee,ee),B({queryKey:["vfs",W()??"__unscoped__","resolved-items",e??"",t],queryFn:()=>to(e,t),enabled:!!(e&&t)})}var Qe=Y(ue(),1);function Os(e,t){let n={artifacts:new Map,timeline:[]},r=new Map;function s(o){if(!o.action?.startsWith("artifact_"))return;let c,u=o.name;if(typeof u=="string"&&u.startsWith("{"))try{c=JSON.parse(u)}catch{return}else if(o.artifact_id)c=o;else return;switch(c.type){case"artifact_opened":{let l=Date.now();if(n.artifacts.set(c.artifact_id,{artifact_id:c.artifact_id,surface_type:c.surface_type,tool_id:c.tool_id,tool_name:c.tool_name,target_uri:c.target_uri,status:"streaming",content:"",total_chars:0,delta_count:0,artifact_item_uri:null,evidence_uri:null,meta:c.meta,started_at:l,completed_at:null}),r.has(c.tool_id)){let f=r.get(c.tool_id);n.timeline[f].artifact_ids.push(c.artifact_id)}else{let f=n.timeline.length;n.timeline.push({tool_id:c.tool_id,tool_name:c.tool_name,status:"started",target_uri:c.target_uri,started_at:l,completed_at:null,artifact_ids:[c.artifact_id]}),r.set(c.tool_id,f)}break}case"artifact_delta":{let l=n.artifacts.get(c.artifact_id);l&&(l.content+=c.content_delta,l.total_chars+=c.content_delta.length,l.delta_count+=1,c.target_uri&&!l.target_uri&&(l.target_uri=c.target_uri));break}case"artifact_done":{let l=n.artifacts.get(c.artifact_id);l&&(l.status=c.status,l.total_chars=c.total_chars,l.artifact_item_uri=c.artifact_item_uri,l.evidence_uri=c.evidence_uri,c.target_uri&&(l.target_uri=c.target_uri),(c.status==="completed"||c.status==="failed")&&(l.completed_at=Date.now()));let f=r.get(c.tool_id);if(f!==void 0){let h=n.timeline[f];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 us(e,s)}function xl(e,t=!0){let[n,r]=(0,Qe.useState)(new Map),[s,i]=(0,Qe.useState)([]),o=(0,Qe.useRef)({artifacts:new Map,timeline:[]});(0,Qe.useEffect)(()=>!e||!t?void 0:Os(e,f=>{o.current=f,r(new Map(f.artifacts)),i([...f.timeline])}),[e,t]);let a=(0,Qe.useCallback)(()=>{r(new Map),i([]),o.current={artifacts:new Map,timeline:[]}},[]),c=Array.from(n.values()).find(l=>l.surface_type==="file_editor"&&l.status==="streaming")??null,u=Array.from(n.values()).filter(l=>l.surface_type==="activity"&&(l.status==="streaming"||l.status==="executing"));return{artifacts:n,timeline:s,activeEditor:c,activeActivities:u,reset:a}}function Rl(e,t=!0){let[n,r]=(0,Qe.useState)([]);(0,Qe.useEffect)(()=>!e||!t?void 0:Os(e,o=>{r([...o.timeline])}),[e,t]);let s=n.length>0?n[n.length-1]:null;return{timeline:n,latestActivity:s}}var Fs=Y(ue(),1);function Mf(e,t,n,r){return["vfs","timeline-history",e,t??"__all__",n??500,r??0]}async function no(e,t){let n=`${e}/datasets/agent-events`,r=t?.limit??500,s=t?.offset??0,i={limit:r,offset:s,sort:[{key:"seq",direction:"asc"}]};t?.turnId&&(i.filters=[{key:"turn_id",operator:"eq",value:t.turnId}]);try{let a=(await x("open",{path:n,mode:"extract",strategy:"rows",arguments:i}))?.content;return a?(a.rows??a.items??a.data??[]).map(Of).sort((u,l)=>u.seq-l.seq):[]}catch(o){if(o?.status===404||o?.message?.includes("not found"))return[];throw o}}function Pl(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,Fs.useRef)(null),l=a?Mf(a,n,r,s):["vfs","timeline-history","__disabled__"],f=B({queryKey:l,queryFn:()=>no(e,{turnId:n,limit:r,offset:s}),enabled:!!e&&i});return(0,Fs.useEffect)(()=>{if(!a||!i)return;let h=ie("vfs_change",()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{c.invalidateQueries({queryKey:l})},o)},p=>{let m=p?.path;return m?m===a&&p.item_type==="dataset":!1});return()=>{h(),u.current&&clearTimeout(u.current)}},[a,i,o,c,JSON.stringify(l)]),{events:f.data??[],isLoading:f.isLoading,error:f.error,isFetching:f.isFetching,refetch:()=>{f.refetch()}}}function Of(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 Ct=Y(ue(),1);function Cl(e){let t=(0,Ct.useSyncExternalStore)(xe,ee,ee),n=W(),r=e?.path??n,s=de(),i=e?.id??s?.id,o=(0,Ct.useMemo)(()=>({}),[t,n,r,i]),a=(0,Ct.useRef)(o);a.current=o;let c=Kn(r?{key:"pinned",scope_id:i,_scope_path:r}:null),u=L(),l=c.resolvedChildren,f=!!(!c.error&&c.arrangement?.item_id&&c.resolutionLevel==="member"&&c.arrangement.write_target_id===c.arrangement.item_id),h=ne({mutationFn:async m=>{let y,g={_scope_path:m.scopePath};if(m.operation==="pin"?y=await x("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"?y=await x("delete",{...g,id:m.entry.id}):y=await x("update",{...g,id:m.arrangementId,type_data:{order:m.ids}}),y?.success===!1)throw new Error(y.error||"Pins could not be saved");return y},onSettled:(m,y,g)=>rt(u,g.queryKey)}),p=(0,Ct.useCallback)(m=>!f||!r||a.current!==o||t!==ee()||W()!==n?Promise.reject(new Error("Personal pins are not available in this context")):m.operation==="unpin"&&!l.some(y=>y.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(y=>!m.ids.includes(y.id)))?Promise.reject(new Error("Order must include each pin exactly once")):m.operation==="pin"&&l.some(y=>y.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}),[f,t,n,r,o,l,c.arrangement,c.arrangementQueryKey,h.mutateAsync]);return{entries:l,isLoading:c.isLoading,error:c.error,refetch:c.refetch,ready:f,isSaving:h.isPending,saveError:h.error,isPinned:m=>l.some(y=>y.symlink_type_data?.target_item_id===m),pin:m=>p({operation:"pin",target:m}),unpin:m=>{let y=l.find(g=>g.symlink_type_data?.target_item_id===m||g.id===m);return y?p({operation:"unpin",entry:y}):Promise.resolve(null)},reorder:m=>p({operation:"reorder",ids:m})}}var qs=Y(ue(),1);var Mr=(e,t,n)=>["vfs",e,"personal-sections",t,n];function ro(e,t){return e&&e.item_id===t.item_id&&e.version>t.version?e:t}async function so(e,t,n,r){let s=await x("personal-sections",{...r,context_item_id:t,collection:n,_scope_path:e});if(!s||s.success===!1)throw new Error(s?.message||s?.error||"Sections could not be saved");if(!Array.isArray(s.sections)||s.context_item_id!==t||s.collection!==n)throw new Error("Invalid sections response");return s}async function El(e,t){let n=await so(e.scopePath,e.contextId,e.collection,{operation:"assign",section_id:e.sectionId,target_id:t}),r=N();return r.setQueryData(Mr(e.scopePath,e.contextId,e.collection),s=>ro(s,n)),Il(r,e.scopePath),n}function Il(e,t){for(let n of e.getQueryCache().getAll())n.queryKey[0]==="vfs"&&n.queryKey[1]===t&&n.queryKey[2]==="personal-sections"&&rt(e,n.queryKey)}function Tl(e,t){let n=(0,qs.useSyncExternalStore)(xe,ee,ee),r=W(),s=L(),i=Mr(r,e,t),o=B({queryKey:i,enabled:!!r&&!!e,queryFn:()=>so(r,e,t,{operation:"list"}),staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0,personalSections:!0},structuralSharing:(f,h)=>ro(f,h)}),a=(0,qs.useRef)(!1),c=ne({mutationFn:async f=>{let h=await so(f.scope,f.context,f.collection,{...f.change,...f.change.operation.startsWith("reorder")?{expected_version:f.version}:{}});return s.setQueryData(Mr(f.scope,f.context,f.collection),p=>ro(p,h)),h},onSettled:(f,h,p)=>Il(s,p.scope)});async function u(f){if(!r||!e||n!==ee()||W()!==r||!o.data||o.error)throw new Error("Select the Space again before changing sections");if(a.current)throw new Error("A section change is still being saved");a.current=!0;try{return await c.mutateAsync({change:f,scope:r,context:e,collection:t,version:o.data.version})}finally{a.current=!1}}function l(f){if(!r||!e||!o.data?.sections.some(h=>h.id===f))throw new Error("Section is unavailable");return{scopePath:r,contextId:e,collection:t,sectionId:f}}return{sections:o.data?.sections??[],ready:!!o.data&&!o.error,isLoading:o.isLoading,error:o.error,refetch:o.refetch,isSaving:c.isPending,change:u,destination:l,contextKey:`${n}:${r}:${e}:${t}`}}tu(io);return Ll(io);})();
7
+ ${t??""}`,[m,b]=(0,v.useState)(null),g=(0,v.useRef)({key:f,found:null,earlyContentPaths:new Set}),y=m?.key===f?m:null;(0,v.useLayoutEffect)(()=>{g.current={key:f,found:y,earlyContentPaths:new Set}},[f]);let _=B({queryKey:["vfs",p??"__unscoped__","minted-asset",h??"",t??""],queryFn:async()=>{let P=await x("query",{scope_path:p,filters:{[`field.${h}`]:t},limit:1}),M=P.content?.items??P.items??[],D=M[0]?Oe(M[0]):null;if(!D)return null;let A=(await xr(D.path)).some(k=>k.item_type==="file"&&!!k.type_data?.file_ref);return{asset:D,hasBytes:A}},enabled:!!(t&&p&&h&&!s),refetchInterval:P=>g.current.key===f&&g.current.found?.hasBytes||P.state.data?.hasBytes?!1:1500});(0,v.useEffect)(()=>{let P=_.data;if(!P||g.current.key!==f)return;let M=g.current.found,D={key:f,itemId:P.asset.id,itemPath:P.asset.path,displayName:typeof P.asset.type_data?.display_name=="string"?P.asset.type_data.display_name:P.asset.name,hasBytes:P.hasBytes||!!(M?.itemId===P.asset.id&&M.hasBytes)};g.current.found=D,b(D)},[_.data,f]);let w=!!(t&&u)&&!s&&!y?.hasBytes;return(0,v.useEffect)(()=>{if(!(!w||!u))return Un(u,["asset.materialized","content.written"])},[w,u]),(0,v.useEffect)(()=>{if(!w||!t||!u)return;let P=f,M=T=>T?.payload??T,D=T=>{let Q=M(T)?.scope_id??T?.scope_id;return typeof Q=="string"?Q:void 0},C=T=>{let Q=M(T)?.item_path??T?.item_path;return typeof Q=="string"&&Q?Q:void 0},A=(T,O)=>{let Q=O.replace(/\/+$/,"");return T===Q||T.startsWith(`${Q}/`)},k=[oe("asset.materialized",T=>{if(g.current.key!==P)return;let O=M(T);if(typeof O?.item_id!="string"||!O.item_id)return;let Q=g.current.found,K=typeof O.item_path=="string"?O.item_path:void 0,Z=!!O.has_bytes||!!(K&&Array.from(g.current.earlyContentPaths).some(lt=>A(lt,K)))||!!(Q&&Q.itemId===O.item_id&&Q.hasBytes),De={key:P,itemId:O.item_id,itemPath:K,displayName:typeof O.display_name=="string"?O.display_name:void 0,hasBytes:Z};g.current.found=De,b(De)},T=>{let O=D(T);return(!O||O===u)&&M(T)?.origin===t}),oe("content.written",T=>{if(g.current.key!==P)return;let O=C(T);if(!O)return;let Q=g.current.found;if(!Q?.itemPath||!A(O,Q.itemPath)){if(g.current.earlyContentPaths.add(O),g.current.earlyContentPaths.size>128){let Z=g.current.earlyContentPaths.values().next().value;Z&&g.current.earlyContentPaths.delete(Z)}return}if(Q.hasBytes)return;let K={...Q,hasBytes:!0};g.current.found=K,b(K)},T=>{let O=D(T);return(!O||O===u)&&!!C(T)})];return()=>k.forEach(T=>T())},[w,t,u,f]),{state:s?"failed":t?y?y.hasBytes?"ready":"materializing":"pending":"idle",itemId:y?.itemId,itemPath:y?.itemPath,displayName:y?.displayName,fallbackUrl:r??void 0,error:s??void 0}}function Qu(e,t){let n=q().getDefaultOptions().queries?.retry??1;return typeof n=="function"?n(e,t):n===!0||typeof n=="number"&&e<n}function Du(e,t,n){let r=(0,Tt.useSyncExternalStore)(Re,W,W),s=pe(),i=G(),o=n?.path??i,a=n?.id??s?.id,c=!!(n?.id&&n.path)||s?.kind==="space",u=(0,Tt.useMemo)(()=>({}),[r,i,o,a]),l=(0,Tt.useRef)(u);l.current=u;let p=Vn(c&&o?{key:e,scope_id:a,_scope_path:o}:null),h=(0,Tt.useMemo)(()=>{let _=p.applyTo([...t]);if(e!=="channel-order")return _;let w=new Set(p.order??[]),R=_.filter(M=>!w.has(M.id)),P=M=>Date.parse(M.createdAt??"")||0;return R.sort((M,D)=>P(D)-P(M)),[...R,..._.filter(M=>w.has(M.id))]},[e,t,p.applyTo,p.order]),f=L(),m=(0,Tt.useRef)(!1),b=!!(c&&!p.error&&p.arrangement?.item_id&&p.resolutionLevel==="member"&&p.arrangement.write_target_id===p.arrangement.item_id),g=se({mutationFn:async _=>{let w=await x("update",{_scope_path:_.scopePath,id:_.arrangementId,type_data:{order:_.ids}});if(w?.success===!1)throw new Error(w.error||"Order could not be saved");return w},onSettled:(_,w,R)=>ot(f,R.queryKey)});async function y(_){if(!b||!o||u!==l.current||r!==W()||G()!==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 w=t.map(k=>k.id);if(_.length!==w.length||new Set(_).size!==w.length||w.some(k=>!_.includes(k)))throw new Error("Order must include each displayed item exactly once");let R=f.getQueryData(p.arrangementQueryKey);if(R?.item_id!==p.arrangement.item_id||JSON.stringify(R?.type_data?.order??[])!==JSON.stringify(p.order??[]))throw new Error("The saved order changed. Try dragging again");let P=h.map(k=>k.id);if(_.every((k,T)=>P[T]===k))return;let M=new Set(w),D=0,A=[...(p.order??[]).map(k=>M.has(k)?_[D++]:k),..._.slice(D)];m.current=!0;try{return await g.mutateAsync({ids:A,scopePath:o,arrangementId:p.arrangement.item_id,queryKey:p.arrangementQueryKey})}finally{m.current=!1}}return{items:h,ready:b,supported:c,contextKey:`${r}:${o}:${e}`,isLoading:c&&p.isLoading,error:p.error,refetch:p.refetch,isSaving:g.isPending,saveError:g.error,reorder:y}}var Gi=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,dp=/^[A-Za-z_:][A-Za-z0-9_:.-]{0,127}$/,Uu=new Map,Ku=new Map,$n=class extends Error{constructor(n,r,s,i){super(n);J(this,"code");J(this,"status");J(this,"eventId");this.name="InteractionTrackingError",this.code=r,this.status=s,this.eventId=i}};function en(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 pp(e){return e.length>0&&e.length<=128&&!/[\u0000-\u001f\u007f]/.test(e)}function fp(e,t){if(!pp(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 mp(e){try{let t=zi(e)?.getItem(e.key)??void 0;return t&&Gi.test(t)?t:void 0}catch{return}}function Lu(e,t){try{zi(e)?.setItem(e.key,t)}catch{}}function Hu(e){let t=e.identity?.visitor;if(!t?.key)throw new TypeError("The source visitor identity policy is invalid");let n=mp(t)??Uu.get(e.id);if(n)return n;let r=crypto.randomUUID();return Uu.set(e.id,r),Lu(t,r),r}function ju(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=Ku.get(e.id),i=r&&typeof r.id=="string"&&Gi.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 Ku.set(e.id,c),Lu(n,JSON.stringify(c)),c.id}function gp(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 tn(e,t={},n={}){let r=en(n.source);if(fp(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??Hu(r),o=n.sessionId??ju(r);if(![s,i,o].every(g=>Gi.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=gp(r,a),p=l?{...t,source_keys:l}:t,h=$t(),f=`${Te.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:p}]}),signal:n.signal,credentials:"omit",keepalive:n.keepalive??!1})}catch(g){throw new $n(g instanceof Error?g.message:"Observation transport network error","OBSERVATION_NETWORK_ERROR",0,s)}let b=null;try{b=await m.json()}catch{}if(!m.ok||b?.success!==!0){let g=b;throw new $n(g?.message||g?.error||`Observation transport failed (${m.status})`,g?.error||"OBSERVATION_TRANSPORT_FAILED",m.status,s)}return b}function Bu(e={},t={}){let n=en(t.source),r=qs("page_view",n),s=typeof document>"u"||!r.title_property?{}:{[r.title_property]:document.title.slice(0,512)};return tn(r.observation,{...s,...e},{...t,source:n.id})}function Vu(e,t={},n={}){if(!e||e.length>128)throw new TypeError("actionId is invalid");let r=en(n.source),s=qs("declared_action",r),i=s.id_property?{[s.id_property]:e}:{};return tn(s.observation,{...t,...i},{...n,source:r.id})}function $u(){try{let e=en();return qs("form_receipt",e),{visitor_id:Hu(e),session_id:ju(e),source:e.id}}catch{return}}function hp(e,t={}){let n=en(t.source),r=qs("form_receipt",n);return tn(r.observation,e,{...t,source:n.id})}async function yp(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 Wu(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 hp(e,{source:o.id,eventId:a?t:await yp(t,o.id),pageUrl:n,signal:s,keepalive:!0,...a?{visitorId:r.visitor_id,sessionId:r.session_id}:{}})}))}var Fr;function Ns(e={}){if(typeof window>"u"||typeof document>"u")return()=>{};if(Fr)return Fr;if(window.__FSAOS_CONFIG__?.tracking?.enabled===!1)return()=>{};let t;try{t=e.source?[en(e.source)]:jt.map(h=>en(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)}:{};tn(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 b=m.attribute;if(!b||!dp.test(b))continue;let g=h.target.closest(`[${b}]`);if(!g)continue;let y=g.getAttribute(b)?.trim();if(!y||y.length>128)continue;let _={};m.id_property&&(_[m.id_property]=y),m.element_property&&(_[m.element_property]=g.tagName.toLowerCase()),tn(m.observation,_,{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),p=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)),p&&window.addEventListener("pageshow",i),r.length>0&&document.addEventListener("click",o,{capture:!0}),n.length>0&&queueMicrotask(i),Fr=()=>{window.removeEventListener("popstate",i),window.removeEventListener("pageshow",i),document.removeEventListener("click",o,{capture:!0}),l&&(window.history.pushState=a,window.history.replaceState=c),Fr=void 0},Fr}var Wn;ie(()=>{Wn=void 0});function Qs(e){if(Wn)return Wn.accountPath!==e.accountPath?Promise.reject(new Error("Reset the session before changing accounts")):Wn.promise;let t=Y(),n=()=>{if(t!==Y())throw new Error("Workspace session changed")},r=(async()=>{let s=await it();if(n(),!s.principal_id)throw new Error("Workspace initialization requires an authenticated principal");let i=await q().fetchQuery({queryKey:E.memberships(s.principal_id),queryFn:Ps,staleTime:12e4,retry:!1});n();let o=i.find(p=>p.path===e.accountPath&&p.isAccount&&!p.isSpace);if(!o)throw new Error("Authenticated account membership is unavailable");let a=i.find(p=>p.isSpace&&p.accountId===o.personalSpaceId&&p.path===o.personalSpacePath);if(!a||!o.personalSpacePath)throw new Error("A provisioned default Space membership is required");let c=$e(o),u=$e(a),l=ge();if(l&&l.id!==c.id)throw new Error("Reset the session before changing accounts");return l||Vt(c,{activate:!1}),await Zt(o.personalSpacePath,p=>{let h=i.find(f=>f.accountId===p&&(f.isAccount||f.isSpace));return h?$e(h):null},{initialAnchor:u}),n(),{home:c,defaultSpace:u,memberships:i}})().catch(s=>{throw t===Y()&&(Wn=void 0),s});return Wn={accountPath:e.accountPath,promise:r},r}var nn,Nr,qr;ie(()=>{Nr?.(),Nr=void 0,nn=void 0,qr=void 0});function Gu(e={}){if(nn)return e.workspace&&e.workspace.accountPath!==qr?Promise.reject(new Error("Initialize workspace through initializeWorkspace, or dispose the existing runtime first")):nn;qr=e.workspace?.accountPath;let t=Y();return nn=(async()=>{let n=e.tracking??!0,r=n===!1?()=>{}:Ns(typeof n=="object"?n:{});Nr=r;try{let s=e.session===!1?null:await it(),i=e.workspace?await Qs(e.workspace):void 0;if(t!==Y())throw new Error("Session changed during initialization");let o=!1;return{session:s,workspace:i,dispose(){o||(o=!0,r(),t===Y()&&(nn=void 0,qr=void 0,Nr=void 0))}}}catch(s){throw r(),t===Y()&&(nn=void 0,qr=void 0,Nr=void 0),s}})(),nn}function _p(e){return e instanceof Fe?{kind:"denied",payload:e.payload}:e instanceof he?{kind:"gateway",method:e.method,status:e.status,statusText:e.statusText,payload:e.payload,responseBody:e.responseBody}:e instanceof Error?{kind:"other",name:e.name,message:e.message}:{kind:"other",name:"Error",message:String(e)}}function zu(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||!Pi(s.data))return;let o=s.data;if(o.kind==="hello"){t(i,{fsaos:Gt,kind:"welcome",anchor:pe()??St(),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;x(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:_p(l)})})};return window.addEventListener("message",r),()=>{n=!1,window.removeEventListener("message",r)}}async function Ji(e){try{return await x("execution-control-transition",e)}catch(t){if(!(t instanceof he)||t.status<500)throw t;return await new Promise(n=>setTimeout(n,250)),x("execution-control-transition",e)}}function Yi(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 Ju(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 Ji({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 Yi(i?{...s,state:i}:s)}async function Yu(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 Ji({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 Yi(a?{...o,state:a}:o)}async function Xu(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 Ji({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 Yi(i?{...s,outcome:i}:s)}var vp=/^[a-z][a-z0-9_-]{0,63}$/,bp=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Gn=class extends Error{constructor(n,r,s,i){super(n);J(this,"code");J(this,"status");J(this,"fillId");this.name="FormSubmissionError",this.code=r,this.status=s,this.fillId=i}};async function Zu(e,t,n={}){if(!vp.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(!bp.test(r))throw new TypeError("fillId must be a UUID");let s=$t(),i=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!i)throw new TypeError("pageUrl is required outside a browser");let o=`${Te.replace(/\/+$/,"")}/d/${encodeURIComponent(s)}/actions/${encodeURIComponent(e)}`,a=$u(),c=a?{visitor_id:a.visitor_id,session_id:a.session_id}:void 0,u;try{u=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({fill_id:r,page_url:i,fields:t,...c?{attribution:c}:{}}),signal:n.signal,credentials:"omit"})}catch(p){throw new Gn(p instanceof Error?p.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 p=l;throw new Gn(p?.message||p?.error||`Form submission failed (${u.status})`,p?.error||"FORM_SUBMISSION_FAILED",u.status,r)}return await Wu({fill_id:r,action_id:e,release_id:l.release_id},r,i,a,n.signal),l}var Xi=ee(le(),1),nl=ee(tl(),1);function rl(e){return x("read",{path:e})}function sl(e,t){return x("list",{path:e,...t})}function il(e){return x("create",e)}function ol(e){return x("update",e)}function al(e){return x("create",e)}function cl(e,t){let r=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return x("tools/call",{name:e,instance_path:r,...t||{}})}function ul(e,t,n){return x("signal",{target_id:e,event_name:t,payload:n||{}})}function ll(e){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+e}var dl={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(),kn(),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 pl(){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,nl.createRoot)(e).render((0,Xi.createElement)(ur,{client:q()},(0,Xi.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 fl(){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 wp=e=>x("create-invitation",{...e}),Sp=e=>x("get-invitation",{invitation_id:e}),xp=e=>x("accept-invite",{invitation_id:e}),Rp=e=>x("reject-invite",{invitation_id:e}),Pp=e=>x("cancel-invite",{invitation_id:e}),Cp=(e,t)=>x("resend-invite",{invitation_id:e,request_id:t}),Ep=(e,t)=>x("list-invitations",{account_id:e,...t?{after:t}:{}});function Zi(e){return x("invite-member",e)}function eo(e){return x("accept-invite",e)}function to(e){let t={};return e.role&&(t.role=e.role),x("link",{source_id:e.chat_id,target_id:e.member_id,edge_type:"has_member",context:t})}function no(e){return x("create-agent",e)}function ro(e){return!e.input_request_id&&!e.input_request?Promise.reject(new Error("answerInput needs input_request_id or the input_request object read from the step.")):x("todo-control",{action:"answer_input",...e})}function ml(){return se({mutationFn:Zi})}function gl(){let e=L();return se({mutationFn:eo,onSuccess:()=>{e.invalidateQueries({queryKey:["memberships"]})}})}function hl(){let e=L();return se({mutationFn:to,onSuccess:(t,n)=>{e.invalidateQueries({queryKey:E.edges(n.chat_id)}),e.invalidateQueries({queryKey:E.edges(n.member_id)})}})}function yl(){let e=L();return se({mutationFn:no,onSuccess:()=>{e.invalidateQueries({queryKey:["memberships"]})}})}function _l(){let e=L();return se({mutationFn:ro,onSuccess:(t,n)=>{e.invalidateQueries({queryKey:E.itemById(n.step_id)})}})}function Ip(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Tp(e,t){return t&&t.length>0?"select":e==="boolean"?"toggle":e==="integer"||e==="number"?"range":e==="string"?"text":"none"}function Ap(e,t){return!(e==="object"||e==="array")}function kp(e){return["string","number","integer","boolean"].includes(e)}function Mp(e){return e!=="object"&&e!=="array"}function vl(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=Ap(c,u),p=kp(c),h=Tp(c,u);i.push({key:o,label:a.title||Ip(o),type:c,description:a.description,enum_values:u,default_value:n[o]??r[o]??a.default,editable:t,filterable:l,sortable:p,filter_widget:h})}return i}function so(e){let t=e.default_data||{},n=e.field_defaults||{},r=vl(e.input_schema,!0,t,n),s=vl(e.system_schema,!1,t,n),i=[...r,...s],o=i.filter(u=>Mp(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 bl(e){return{field:"updated_at",direction:"desc"}}function wl(e){let t=so(e),n=new Set(e.input_schema?.required||[]);return t.form_fields.filter(r=>n.has(r.key)||r.default_value===void 0)}var _e=ee(le(),1);var Sl=Promise.resolve();function Ce(e){if(e?.aborted)throw new Error("Upload cancelled")}async function io(e,t){if(Ce(t),e.size>16777216||!globalThis.crypto?.subtle)return{};let n=Sl.then(async()=>{Ce(t);let r=await e.arrayBuffer();Ce(t);let s=await globalThis.crypto.subtle.digest("SHA-256",r);return Ce(t),{expected_sha256:Array.from(new Uint8Array(s),i=>i.toString(16).padStart(2,"0")).join(""),expected_size_bytes:e.size}});return Sl=n.catch(()=>{}),n}function xl(){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 Rl(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"?xl():void 0,u=W(),l=Y(),p=await io(e,r);if(Ce(r),u!==W()||l!==Y())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}:{},...p}}};t.cardParentPath&&(h.card_parent_path=t.cardParentPath);let f=await x("create",h);Ce(r);let m=f;if(!m.id)throw new Error(m.error||m.message||"Failed to create file item");let b=m.id,g=m.path;if(m.storage_completed&&m.file_ref)return{itemId:b,itemPath:g,fileRef:m.file_ref};let y=m.storage_key,_=m.upload_token,w=m.storage_worker_url||"https://fsaos-storage.radns.workers.dev";if(!y)throw new Error("Gateway returned no storage_key \u2014 file_source may not be supported for this item type");await Op(w,y,_,e,i,n,r),Ce(r);let R=await Pl(b,y,i,_,p.expected_sha256,e.size);return{itemId:b,itemPath:g,fileRef:R}}function Op(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 Pl(e,t,n,r,s,i){let o=await st(),a=await fetch(`${Te}/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 Cl(){let[e,t]=(0,_e.useState)([]),n=L(),r=(0,_e.useRef)(e);r.current=e;let s=(0,_e.useRef)(new Map),i=(0,_e.useCallback)((g,y)=>{t(_=>_.map(w=>w.id===g?{...w,...y}:w))},[]),o=(0,_e.useCallback)(g=>{t(y=>[...y,g])},[]),a=(0,_e.useCallback)(async(g,y,_,w,R)=>{let P=_.name||y.name,M=y.type||"application/octet-stream",D=_.itemType||"file",C=_.collisionPolicy||"keep_both",A=R?.itemId||null,k=R?.itemPath||null,T=R?.storageKey||null,O=R?.uploadToken||null,Q=R?.storageWorkerUrl||null,K=R?.contentSha256||void 0,Z=new AbortController,De=W(),lt=Y();s.current.get(g)?.abort(),s.current.set(g,Z);try{if(!w||w==="create"){i(g,{status:"creating",error:null,_failedAt:null});let ze=await io(y,Z.signal);if(Ce(Z.signal),De!==W()||lt!==Y())throw new Error("The account or Space changed while preparing the upload. Start it again.");K=ze.expected_sha256;let kt=await x("create",{parent_path:_.parentPath,item_type:D,name:P,type_data:{..._.typeData||{},file_source:{type:"upload",content_type:M,collision_policy:C,...C==="keep_both"?{upload_id:g}:{},...ze}}});Ce(Z.signal);let ae=kt;if(!ae.id)throw Object.assign(new Error(ae.error||ae.message||"Failed to create file item"),{_step:"create"});if(A=ae.id,k=ae.path,i(g,{itemId:A,itemPath:k}),ae.storage_completed&&ae.file_ref){i(g,{status:"complete",progress:100,fileRef:ae.file_ref}),n.invalidateQueries({queryKey:E.children(_.parentPath)});return}if(T=ae.storage_key,O=ae.upload_token||"",Q=ae.storage_worker_url||"https://fsaos-storage.radns.workers.dev",i(g,{_storageKey:T,_uploadToken:O,_storageWorkerUrl:Q,_contentSha256:K||null}),!T)throw Object.assign(new Error("Gateway returned no storage_key"),{_step:"create"})}(!w||w==="create"||w==="upload")&&(i(g,{status:"uploading",progress:0,error:null,_failedAt:null}),await new Promise((kt,ae)=>{let V=new XMLHttpRequest;i(g,{_xhr:V}),V.open("PUT",`${Q}/upload`),V.setRequestHeader("X-Storage-Key",T),V.setRequestHeader("Content-Type",M),O&&V.setRequestHeader("X-Upload-Token",O),V.upload.onprogress=Mt=>{Mt.lengthComputable&&i(g,{progress:Math.round(Mt.loaded/Mt.total*100)})},V.onload=()=>{V.status>=200&&V.status<300?kt():ae(Object.assign(new Error(`Storage upload failed: HTTP ${V.status}`),{_step:"upload"}))},V.onerror=()=>ae(Object.assign(new Error("Storage upload network error"),{_step:"upload"})),V.ontimeout=()=>ae(Object.assign(new Error("Storage upload timed out"),{_step:"upload"})),V.onabort=()=>ae(Object.assign(new Error("Upload cancelled"),{_step:"upload"})),Z.signal.addEventListener("abort",()=>V.abort(),{once:!0}),Ce(Z.signal),V.send(y)}),Ce(Z.signal),i(g,{progress:100,_xhr:null})),i(g,{status:"confirming",error:null,_failedAt:null});let Ge=await Pl(A,T,M,O||"",K,y.size).catch(ze=>{throw Object.assign(ze,{_step:"confirm"})});Ce(Z.signal),i(g,{status:"complete",fileRef:Ge}),n.invalidateQueries({queryKey:E.children(_.parentPath)})}catch(Ge){if(s.current.get(g)!==Z)return;let ze=Ge?.message||String(Ge),kt=Ge?._step||"create";i(g,{status:"error",error:ze,_failedAt:kt,_xhr:null})}finally{s.current.get(g)===Z&&s.current.delete(g)}},[i,n]),c=(0,_e.useCallback)((g,y)=>{let _=xl();o({id:_,file:g,status:"creating",progress:0,error:null,itemId:null,itemPath:null,fileRef:null,options:y,_storageKey:null,_uploadToken:null,_storageWorkerUrl:null,_contentSha256:null,_xhr:null,_failedAt:null}),a(_,g,y)},[o,a]),u=(0,_e.useCallback)((g,y)=>{for(let _ of g)c(_,y)},[c]),l=(0,_e.useCallback)(g=>{let y=r.current.find(R=>R.id===g);if(!y||y.status!=="error")return;let _=y._failedAt||"create",w=y._storageKey&&y.itemId?{storageKey:y._storageKey,uploadToken:y._uploadToken||"",storageWorkerUrl:y._storageWorkerUrl||"https://fsaos-storage.radns.workers.dev",itemId:y.itemId,itemPath:y.itemPath||"",contentSha256:y._contentSha256}:void 0;a(g,y.file,y.options,_,w)},[a]),p=(0,_e.useCallback)(g=>{s.current.get(g)?.abort();let y=r.current.find(_=>_.id===g);y&&(y._xhr&&y._xhr.abort(),i(g,{status:"error",error:"Cancelled",_xhr:null,_failedAt:null}))},[i]),h=(0,_e.useCallback)(g=>{s.current.get(g)?.abort(),s.current.delete(g),t(y=>y.filter(_=>_.id!==g))},[]),f=(0,_e.useCallback)(()=>{t(g=>g.filter(y=>y.status!=="complete"))},[]),m=e.some(g=>g.status==="creating"||g.status==="uploading"||g.status==="confirming"),b=e.map(({_storageKey:g,_uploadToken:y,_storageWorkerUrl:_,_contentSha256:w,_xhr:R,_failedAt:P,...M})=>M);return{upload:c,uploadMultiple:u,uploads:b,retryUpload:l,cancelUpload:p,removeUpload:h,clearCompleted:f,isUploading:m}}var El=ee(le(),1);async function oo(e,t){return await x("resolve-items",{context_id:e,item_type:t})}function Il(e,t){return(0,El.useSyncExternalStore)(Re,W,W),B({queryKey:["vfs",G()??"__unscoped__","resolved-items",e??"",t],queryFn:()=>oo(e,t),enabled:!!(e&&t)})}var Qe=ee(le(),1);function Ds(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 p=r.get(c.tool_id);n.timeline[p].artifact_ids.push(c.artifact_id)}else{let p=n.timeline.length;n.timeline.push({tool_id:c.tool_id,tool_name:c.tool_name,status:"started",target_uri:c.target_uri,started_at:l,completed_at:null,artifact_ids:[c.artifact_id]}),r.set(c.tool_id,p)}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 p=r.get(c.tool_id);if(p!==void 0){let h=n.timeline[p];c.status==="executing"?h.status="executing":c.status==="completed"?(h.status="completed",h.completed_at=Date.now()):c.status==="failed"&&(h.status="failed",h.completed_at=Date.now()),c.target_uri&&!h.target_uri&&(h.target_uri=c.target_uri)}break}}t(n)}return ms(e,s)}function Tl(e,t=!0){let[n,r]=(0,Qe.useState)(new Map),[s,i]=(0,Qe.useState)([]),o=(0,Qe.useRef)({artifacts:new Map,timeline:[]});(0,Qe.useEffect)(()=>!e||!t?void 0:Ds(e,p=>{o.current=p,r(new Map(p.artifacts)),i([...p.timeline])}),[e,t]);let a=(0,Qe.useCallback)(()=>{r(new Map),i([]),o.current={artifacts:new Map,timeline:[]}},[]),c=Array.from(n.values()).find(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 Al(e,t=!0){let[n,r]=(0,Qe.useState)([]);(0,Qe.useEffect)(()=>!e||!t?void 0:Ds(e,o=>{r([...o.timeline])}),[e,t]);let s=n.length>0?n[n.length-1]:null;return{timeline:n,latestActivity:s}}var Us=ee(le(),1);function Fp(e,t,n,r){return["vfs","timeline-history",e,t??"__all__",n??500,r??0]}async function ao(e,t){let n=`${e}/datasets/agent-events`,r=t?.limit??500,s=t?.offset??0,i={limit:r,offset:s,sort:[{key:"seq",direction:"asc"}]};t?.turnId&&(i.filters=[{key:"turn_id",operator:"eq",value:t.turnId}]);try{let a=(await x("open",{path:n,mode:"extract",strategy:"rows",arguments:i}))?.content;return a?(a.rows??a.items??a.data??[]).map(qp).sort((u,l)=>u.seq-l.seq):[]}catch(o){if(o?.status===404||o?.message?.includes("not found"))return[];throw o}}function kl(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,Us.useRef)(null),l=a?Fp(a,n,r,s):["vfs","timeline-history","__disabled__"],p=B({queryKey:l,queryFn:()=>ao(e,{turnId:n,limit:r,offset:s}),enabled:!!e&&i});return(0,Us.useEffect)(()=>{if(!a||!i)return;let h=oe("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:p.data??[],isLoading:p.isLoading,error:p.error,isFetching:p.isFetching,refetch:()=>{p.refetch()}}}function qp(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 At=ee(le(),1);function Ml(e){let t=(0,At.useSyncExternalStore)(Re,W,W),n=G(),r=e?.path??n,s=pe(),i=e?.id??s?.id,o=(0,At.useMemo)(()=>({}),[t,n,r,i]),a=(0,At.useRef)(o);a.current=o;let c=Vn(r?{key:"pinned",scope_id:i,_scope_path:r}:null),u=L(),l=c.resolvedChildren,p=!!(!c.error&&c.arrangement?.item_id&&c.resolutionLevel==="member"&&c.arrangement.write_target_id===c.arrangement.item_id),h=se({mutationFn:async m=>{let b,g={_scope_path:m.scopePath};if(m.operation==="pin"?b=await x("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"?b=await x("delete",{...g,id:m.entry.id}):b=await x("update",{...g,id:m.arrangementId,type_data:{order:m.ids}}),b?.success===!1)throw new Error(b.error||"Pins could not be saved");return b},onSettled:(m,b,g)=>ot(u,g.queryKey)}),f=(0,At.useCallback)(m=>!p||!r||a.current!==o||t!==W()||G()!==n?Promise.reject(new Error("Personal pins are not available in this context")):m.operation==="unpin"&&!l.some(b=>b.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(b=>!m.ids.includes(b.id)))?Promise.reject(new Error("Order must include each pin exactly once")):m.operation==="pin"&&l.some(b=>b.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}),[p,t,n,r,o,l,c.arrangement,c.arrangementQueryKey,h.mutateAsync]);return{entries:l,isLoading:c.isLoading,error:c.error,refetch:c.refetch,ready:p,isSaving:h.isPending,saveError:h.error,isPinned:m=>l.some(b=>b.symlink_type_data?.target_item_id===m),pin:m=>f({operation:"pin",target:m}),unpin:m=>{let b=l.find(g=>g.symlink_type_data?.target_item_id===m||g.id===m);return b?f({operation:"unpin",entry:b}):Promise.resolve(null)},reorder:m=>f({operation:"reorder",ids:m})}}var Ks=ee(le(),1);var Qr=(e,t,n)=>["vfs",e,"personal-sections",t,n];function co(e,t){return e&&e.item_id===t.item_id&&e.version>t.version?e:t}async function uo(e,t,n,r){let s=await x("personal-sections",{...r,context_item_id:t,collection:n,_scope_path:e});if(!s||s.success===!1)throw new Error(s?.message||s?.error||"Sections could not be saved");if(!Array.isArray(s.sections)||s.context_item_id!==t||s.collection!==n)throw new Error("Invalid sections response");return s}async function Ol(e,t){let n=await uo(e.scopePath,e.contextId,e.collection,{operation:"assign",section_id:e.sectionId,target_id:t}),r=q();return r.setQueryData(Qr(e.scopePath,e.contextId,e.collection),s=>co(s,n)),Fl(r,e.scopePath),n}function Fl(e,t){for(let n of e.getQueryCache().getAll())n.queryKey[0]==="vfs"&&n.queryKey[1]===t&&n.queryKey[2]==="personal-sections"&&ot(e,n.queryKey)}function ql(e,t){let n=(0,Ks.useSyncExternalStore)(Re,W,W),r=G(),s=L(),i=Qr(r,e,t),o=B({queryKey:i,enabled:!!r&&!!e,queryFn:()=>uo(r,e,t,{operation:"list"}),staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0,personalSections:!0},structuralSharing:(p,h)=>co(p,h)}),a=(0,Ks.useRef)(!1),c=se({mutationFn:async p=>{let h=await uo(p.scope,p.context,p.collection,{...p.change,...p.change.operation.startsWith("reorder")?{expected_version:p.version}:{}});return s.setQueryData(Qr(p.scope,p.context,p.collection),f=>co(f,h)),h},onSettled:(p,h,f)=>Fl(s,f.scope)});async function u(p){if(!r||!e||n!==W()||G()!==r||!o.data||o.error)throw new Error("Select the Space again before changing sections");if(a.current)throw new Error("A section change is still being saved");a.current=!0;try{return await c.mutateAsync({change:p,scope:r,context:e,collection:t,version:o.data.version})}finally{a.current=!1}}function l(p){if(!r||!e||!o.data?.sections.some(h=>h.id===p))throw new Error("Section is unavailable");return{scopePath:r,contextId:e,collection:t,sectionId:p}}return{sections:o.data?.sections??[],ready:!!o.data&&!o.error,isLoading:o.isLoading,error:o.error,refetch:o.refetch,isSaving:c.isPending,change:u,destination:l,contextKey:`${n}:${r}:${e}:${t}`}}ou(lo);return Bl(lo);})();
8
8
 
9
9
  /* ── Auto-setup: require shim + mount + backward compat globals ── */
10
10
  (function() {