@nextclaw/ui 0.13.10-beta.1 → 0.13.11

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.
Files changed (77) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/dist/assets/{api-DhI2lb1f.js → api-DmxQnm30.js} +7 -7
  3. package/dist/assets/{app-presenter-provider-BFbrQp8q.js → app-presenter-provider-CDSjiqfE.js} +2 -2
  4. package/dist/assets/arrow-left-Dd45Mvr1.js +1 -0
  5. package/dist/assets/channels-list-page-bkKDqaO5.js +8 -0
  6. package/dist/assets/chat-page-YKdeGoVx.js +105 -0
  7. package/dist/assets/{config-split-page-bO0K6uQv.js → config-split-page-CdJEkWxv.js} +1 -1
  8. package/dist/assets/{confirm-dialog-DXRWJ5uB.js → confirm-dialog-BWRNsRgb.js} +1 -1
  9. package/dist/assets/{desktop-update-config-DPk5V1Nl.js → desktop-update-config-CLXdVz9r.js} +1 -1
  10. package/dist/assets/{dist-T6rf86Nf.js → dist-CyWdaJvr.js} +1 -1
  11. package/dist/assets/{dist-DQoV-62W.js → dist-DzM2ZEVN.js} +1 -1
  12. package/dist/assets/doc-browser-D5FJcAyz.js +1 -0
  13. package/dist/assets/{doc-browser-CTFB6ACN.js → doc-browser-DewXa6oX.js} +1 -1
  14. package/dist/assets/{doc-browser-context-CP2tI-Br.js → doc-browser-context-CpL2m4Sp.js} +1 -1
  15. package/dist/assets/{ellipsis-B7CbNPNr.js → ellipsis-BDgTYNDX.js} +1 -1
  16. package/dist/assets/{es2015-BSPOGpH4.js → es2015-WqekV0OK.js} +1 -1
  17. package/dist/assets/{external-link-CefT35zP.js → external-link-BLjo8z2a.js} +1 -1
  18. package/dist/assets/{index-DZoXsgdz.js → index-DKflQCOL.js} +15 -15
  19. package/dist/assets/index-Q891JiF_.css +1 -0
  20. package/dist/assets/{key-round-BpM3GZn4.js → key-round-Du8x3sWa.js} +1 -1
  21. package/dist/assets/{loader-circle-_edjOFsw.js → loader-circle-Dz4FssYC.js} +1 -1
  22. package/dist/assets/{mcp-marketplace-page-WAgpy0hp.js → mcp-marketplace-page-BaBuHB2L.js} +2 -2
  23. package/dist/assets/mcp-marketplace-page-ooEvG_bB.js +1 -0
  24. package/dist/assets/{model-config-CixioI5U.js → model-config-B-qg70S4.js} +1 -1
  25. package/dist/assets/{notice-card-BLklZuEa.js → notice-card-3a7FmAz-.js} +1 -1
  26. package/dist/assets/play-BziM-Y34.js +1 -0
  27. package/dist/assets/plus-DrpyArC8.js +1 -0
  28. package/dist/assets/{popover-D_pJfOlM.js → popover-BlJLguiZ.js} +1 -1
  29. package/dist/assets/{provider-scoped-model-input-BbWqk2yz.js → provider-scoped-model-input-BgPTQa8H.js} +1 -1
  30. package/dist/assets/providers-list-cBeeslbc.js +1 -0
  31. package/dist/assets/{react-Bl8iJUcF.js → react-BVjl1ZaK.js} +1 -1
  32. package/dist/assets/{refresh-cw-CqfS1EhK.js → refresh-cw-DFR87zei.js} +1 -1
  33. package/dist/assets/remote-DjhVMpVd.js +1 -0
  34. package/dist/assets/rotate-cw-DMBnsYKm.js +1 -0
  35. package/dist/assets/{runtime-config-page-ByvKO6Yn.js → runtime-config-page-DYH2ejUI.js} +1 -1
  36. package/dist/assets/{save-CQERCODg.js → save-BDmIlHvN.js} +1 -1
  37. package/dist/assets/search-CjHGYvTI.js +1 -0
  38. package/dist/assets/{search-config-Cl2_NgFY.js → search-config-BRsrQ4zK.js} +1 -1
  39. package/dist/assets/{secrets-config-BkR72J4g.js → secrets-config-eYdx5_AW.js} +2 -2
  40. package/dist/assets/{status-dot-DY0xUUvK.js → status-dot-SVPjIyG5.js} +1 -1
  41. package/dist/assets/{tabs-C77i1w90.js → tabs-Czd2mj6z.js} +1 -1
  42. package/dist/assets/{tabs-custom-CFpR54-m.js → tabs-custom-Ix4nkp2h.js} +1 -1
  43. package/dist/assets/{tag-chip-Kib_ljle.js → tag-chip-Cdwb3JSH.js} +1 -1
  44. package/dist/assets/{tooltip-fs7VQG7d.js → tooltip-CKGxLGnG.js} +1 -1
  45. package/dist/assets/{trash-2-Bb8mTTLl.js → trash-2-yLA8BEcE.js} +1 -1
  46. package/dist/assets/x-dpDISboO.js +1 -0
  47. package/dist/index.html +25 -25
  48. package/package.json +8 -8
  49. package/src/features/chat/components/chat-session-workspace-panel-nav.tsx +86 -64
  50. package/src/features/chat/components/chat-session-workspace-panel.tsx +14 -25
  51. package/src/features/chat/components/conversation/chat-conversation-panel.test.tsx +3 -3
  52. package/src/features/panel-apps/components/panel-app-toolbar.test.tsx +24 -0
  53. package/src/features/panel-apps/components/panel-app-toolbar.tsx +11 -2
  54. package/src/features/panel-apps/utils/panel-app-doc-browser.utils.tsx +2 -1
  55. package/src/shared/components/cron-config.tsx +367 -91
  56. package/src/shared/hooks/use-config.ts +2 -2
  57. package/src/shared/lib/api/ncp-session-query-cache.utils.test.ts +35 -0
  58. package/src/shared/lib/api/ncp-session-query-cache.utils.ts +9 -1
  59. package/src/shared/lib/api/utils/ncp-session.utils.ts +2 -2
  60. package/src/shared/lib/cron/cron-job-view.utils.ts +124 -6
  61. package/src/shared/lib/i18n/README.md +7 -0
  62. package/src/shared/lib/i18n/cron-labels.utils.ts +32 -0
  63. package/src/shared/lib/i18n/index.ts +2 -25
  64. package/vite.config.ts +8 -0
  65. package/dist/assets/arrow-left-CI0Ocu9p.js +0 -1
  66. package/dist/assets/channels-list-page-B6CvmU9T.js +0 -8
  67. package/dist/assets/chat-page-Ch4ShlKB.js +0 -105
  68. package/dist/assets/doc-browser-yi02ASOL.js +0 -1
  69. package/dist/assets/index-CevK3jug.css +0 -1
  70. package/dist/assets/mcp-marketplace-page-9maf_9fL.js +0 -1
  71. package/dist/assets/play-DD0bg50i.js +0 -1
  72. package/dist/assets/plus-zZ2GC_AJ.js +0 -1
  73. package/dist/assets/providers-list-C_JOSjYd.js +0 -1
  74. package/dist/assets/remote-qtmzkte2.js +0 -1
  75. package/dist/assets/rotate-cw-C7EvaSlb.js +0 -1
  76. package/dist/assets/search-C0b2yzmt.js +0 -1
  77. package/dist/assets/x-BV4iiea8.js +0 -1
@@ -1,13 +1,13 @@
1
- import{d as e,g as t,h as n,i as r,m as i,p as a,t as o,v as s,y as c}from"./react-Bl8iJUcF.js";var l=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(){}},u={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},d=new class{#e=u;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function f(e){setTimeout(e,0)}var p=typeof window>`u`||`Deno`in globalThis;function m(){}function h(e,t){return typeof e==`function`?e(t):e}function g(e){return typeof e==`number`&&e>=0&&e!==1/0}function _(e,t){return Math.max(e+(t||0)-Date.now(),0)}function v(e,t){return typeof e==`function`?e(t):e}function y(e,t){return typeof e==`function`?e(t):e}function b(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==x(o,t.options))return!1}else if(!C(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function ee(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(S(t.options.mutationKey)!==S(a))return!1}else if(!C(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function x(e,t){return(t?.queryKeyHashFn||S)(e)}function S(e){return JSON.stringify(e,(e,t)=>D(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function C(e,t){return e===t?!0:typeof e==typeof t&&e&&t&&typeof e==`object`&&typeof t==`object`?Object.keys(t).every(n=>C(e[n],t[n])):!1}var w=Object.prototype.hasOwnProperty;function te(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=E(e)&&E(t);if(!r&&!(D(e)&&D(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:w.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=te(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function T(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function E(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function D(e){if(!ne(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!ne(n)||!n.hasOwnProperty(`isPrototypeOf`)||Object.getPrototypeOf(e)!==Object.prototype)}function ne(e){return Object.prototype.toString.call(e)===`[object Object]`}function re(e){return new Promise(t=>{d.setTimeout(t,e)})}function O(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:te(e,t)}function k(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function ie(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var A=Symbol();function j(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===A?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function M(e,t){return typeof e==`function`?e(...t):!!e}function ae(e,t,n){let r=!1,i;return Object.defineProperty(e,`signal`,{enumerable:!0,get:()=>(i??=t(),r?i:(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0}),i))}),e}var oe=new class extends l{#e;#t;#n;constructor(){super(),this.#n=e=>{if(!p&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}};function se(){let e,t,n=new Promise((n,r)=>{e=n,t=r});n.status=`pending`,n.catch(()=>{});function r(e){Object.assign(n,e),delete n.resolve,delete n.reject}return n.resolve=t=>{r({status:`fulfilled`,value:t}),e(t)},n.reject=e=>{r({status:`rejected`,reason:e}),t(e)},n}var ce=f;function le(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=ce,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var N=le(),ue=new class extends l{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(!p&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function de(e){return Math.min(1e3*2**e,3e4)}function fe(e){return(e??`online`)===`online`?ue.isOnline():!0}var pe=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function P(e){let t=!1,n=0,r,i=se(),a=()=>i.status!==`pending`,o=t=>{if(!a()){let n=new pe(t);f(n),e.onCancel?.(n)}},s=()=>{t=!0},c=()=>{t=!1},l=()=>oe.isFocused()&&(e.networkMode===`always`||ue.isOnline())&&e.canRun(),u=()=>fe(e.networkMode)&&e.canRun(),d=e=>{a()||(r?.(),i.resolve(e))},f=e=>{a()||(r?.(),i.reject(e))},m=()=>new Promise(t=>{r=e=>{(a()||l())&&t(e)},e.onPause?.()}).then(()=>{r=void 0,a()||e.onContinue?.()}),h=()=>{if(a())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(d).catch(r=>{if(a())return;let i=e.retry??(p?0:3),o=e.retryDelay??de,s=typeof o==`function`?o(n,r):o,c=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);if(t||!c){f(r);return}n++,e.onFail?.(n,r),re(s).then(()=>l()?void 0:m()).then(()=>{t?f(r):h()})})};return{promise:i,status:()=>i.status,cancel:o,continue:()=>(r?.(),i),cancelRetry:s,continueRetry:c,canStart:u,start:()=>(u()?h():m().then(h),i)}}var me=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),g(this.gcTime)&&(this.#e=d.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(p?1/0:300*1e3))}clearGcTimeout(){this.#e&&=(d.clearTimeout(this.#e),void 0)}},he=class extends me{#e;#t;#n;#r;#i;#a;#o;constructor(e){super(),this.#o=!1,this.#a=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#r=e.client,this.#n=this.#r.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#e=ge(this.options),this.state=e.state??this.#e,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#i?.promise}setOptions(e){if(this.options={...this.#a,...e},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=ge(this.options);e.data!==void 0&&(this.setState(I(e.data,e.dataUpdatedAt)),this.#e=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#n.remove(this)}setData(e,t){let n=O(this.state.data,e,this.options);return this.#s({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#s({type:`setState`,state:e,setStateOptions:t})}cancel(e){let t=this.#i?.promise;return this.#i?.cancel(e),t?t.then(m).catch(m):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#e)}isActive(){return this.observers.some(e=>y(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===A||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>v(e.options.staleTime,this)===`static`):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!_(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#i?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#i?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#i&&(this.#o?this.#i.cancel({revert:!0}):this.#i.cancelRetry()),this.scheduleGc()),this.#n.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#s({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#i?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#i)return this.#i.continueRetry(),this.#i.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,`signal`,{enumerable:!0,get:()=>(this.#o=!0,n.signal)})},i=()=>{let e=j(this.options,t),n=(()=>{let e={client:this.#r,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#o=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#r,state:this.state,fetchFn:i};return r(e),e})();this.options.behavior?.onFetch(a,this),this.#t=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#s({type:`fetch`,meta:a.fetchOptions?.meta}),this.#i=P({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof pe&&e.revert&&this.setState({...this.#t,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#s({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#s({type:`pause`})},onContinue:()=>{this.#s({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await this.#i.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#n.config.onSuccess?.(e,this),this.#n.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof pe){if(e.silent)return this.#i.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#s({type:`error`,error:e}),this.#n.config.onError?.(e,this),this.#n.config.onSettled?.(this.state.data,e,this),e}finally{this.scheduleGc()}}#s(e){this.state=(t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...F(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...I(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#t=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}})(this.state),N.batch(()=>{this.observers.forEach(e=>{e.onQueryUpdate()}),this.#n.notify({query:this,type:`updated`,action:e})})}};function F(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:fe(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function I(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function ge(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=class extends l{constructor(e,t){super(),this.options=t,this.#e=e,this.#s=null,this.#o=se(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),ye(this.#t,this.options)?this.#h():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return be(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return be(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof y(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#S(),this.#t.setOptions(this.options),t._defaulted&&!T(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&xe(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||y(this.options.enabled,this.#t)!==y(t.enabled,this.#t)||v(this.options.staleTime,this.#t)!==v(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||y(this.options.enabled,this.#t)!==y(t.enabled,this.#t)||i!==this.#p)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return Se(this,n)&&(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),n===`promise`&&(this.trackProp(`data`),!this.options.experimental_prefetchInRender&&this.#o.status===`pending`&&this.#o.reject(Error(`experimental_prefetchInRender feature flag is not enabled`))),Reflect.get(e,n))})}trackProp(e){this.#m.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(m)),t}#g(){this.#b();let e=v(this.options.staleTime,this.#t);if(p||this.#r.isStale||!g(e))return;let t=_(this.#r.dataUpdatedAt,e)+1;this.#d=d.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return(typeof this.options.refetchInterval==`function`?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#v(e){this.#x(),this.#p=e,!(p||y(this.options.enabled,this.#t)===!1||!g(this.#p)||this.#p===0)&&(this.#f=d.setInterval(()=>{(this.options.refetchIntervalInBackground||oe.isFocused())&&this.#h()},this.#p))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#d&&=(d.clearTimeout(this.#d),void 0)}#x(){this.#f&&=(d.clearInterval(this.#f),void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&ye(e,t),o=i&&xe(e,n,t,r);(a||o)&&(l={...l,...F(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#u?.state.data,this.#u):t.placeholderData,e!==void 0&&(m=`success`,d=O(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h)if(i&&d===a?.data&&t.select===this.#c)d=this.#l;else try{this.#c=t.select,d=t.select(d),d=O(i?.data,d,t),this.#l=d,this.#s=null}catch(e){this.#s=e}this.#s&&(f=this.#s,d=this.#l,p=Date.now(),m=`error`);let g=l.fetchStatus===`fetching`,_=m===`pending`,v=m===`error`,b=_&&g,ee=d!==void 0,x={status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:v,isInitialLoading:b,isLoading:b,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:l.dataUpdateCount>0||l.errorUpdateCount>0,isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:v&&!ee,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:v&&ee,isStale:L(e,t),refetch:this.refetch,promise:this.#o,isEnabled:y(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){let t=x.data!==void 0,r=x.status===`error`&&!t,i=e=>{r?e.reject(x.error):t&&e.resolve(x.data)},a=()=>{i(this.#o=x.promise=se())},o=this.#o;switch(o.status){case`pending`:e.queryHash===n.queryHash&&i(o);break;case`fulfilled`:(r||x.data!==o.value)&&a();break;case`rejected`:(!r||x.error!==o.reason)&&a();break}}return x}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#u=this.#t),!T(t,e)&&(this.#r=t,this.#C({listeners:(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#m.size)return!0;let r=new Set(n??this.#m);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})()}))}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}#C(e){N.batch(()=>{e.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}};function ve(e,t){return y(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status===`error`&&t.retryOnMount===!1)}function ye(e,t){return ve(e,t)||e.state.data!==void 0&&be(e,t,t.refetchOnMount)}function be(e,t,n){if(y(t.enabled,e)!==!1&&v(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&L(e,t)}return!1}function xe(e,t,n,r){return(e!==t||y(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&L(e,n)}function L(e,t){return y(t.enabled,e)!==!1&&e.isStaleByTime(v(t.staleTime,e))}function Se(e,t){return!T(e.getCurrentResult(),t)}function R(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{ae(e,()=>t.signal,()=>n=!0)},u=j(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject();if(r==null&&e.pages.length)return Promise.resolve(e);let a=await u((()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})()),{maxPages:o}=t.options,s=i?ie:k;return{pages:s(e.pages,a,o),pageParams:s(e.pageParams,r,o)}};if(i&&a.length){let e=i===`backward`,t=e?we:Ce,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]??r.initialPageParam:Ce(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(c<t)}return s};t.options.persister?t.fetchFn=()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=l}}}function Ce(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 we(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function Te(e,t){return t?Ce(e,t)!=null:!1}function Ee(e,t){return!t||!e.getPreviousPageParam?!1:we(e,t)!=null}var De=class extends me{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||Oe(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:`observerRemoved`,mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status===`pending`?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??this.execute(this.state.variables)}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#r=P({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(Error(`No mutationFn found`)),onFail:(e,t)=>{this.#i({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#i({type:`pause`})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});let r=this.state.status===`pending`,i=!this.#r.canStart();try{if(r)t();else{this.#i({type:`pending`,variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);let t=await this.options.onMutate?.(e,n);t!==this.state.context&&this.#i({type:`pending`,context:t,variables:e,isPaused:i})}let a=await this.#r.start();return await this.#n.config.onSuccess?.(a,e,this.state.context,this,n),await this.options.onSuccess?.(a,e,this.state.context,n),await this.#n.config.onSettled?.(a,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(a,null,e,this.state.context,n),this.#i({type:`success`,data:a}),a}catch(t){try{await this.#n.config.onError?.(t,e,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,n)}catch(e){Promise.reject(e)}try{await this.#n.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,n)}catch(e){Promise.reject(e)}throw this.#i({type:`error`,error:t}),t}finally{this.#n.runNext(this)}}#i(e){this.state=(t=>{switch(e.type){case`failed`:return{...t,failureCount:e.failureCount,failureReason:e.error};case`pause`:return{...t,isPaused:!0};case`continue`:return{...t,isPaused:!1};case`pending`:return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:`pending`,variables:e.variables,submittedAt:Date.now()};case`success`:return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:!1};case`error`:return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:`error`}}})(this.state),N.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function Oe(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var z=class extends l{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){let r=new De({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);let t=ke(e);if(typeof t==`string`){let n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:`added`,mutation:e})}remove(e){if(this.#e.delete(e)){let t=ke(e);if(typeof t==`string`){let n=this.#t.get(t);if(n)if(n.length>1){let t=n.indexOf(e);t!==-1&&n.splice(t,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:`removed`,mutation:e})}canRun(e){let t=ke(e);if(typeof t==`string`){let n=this.#t.get(t)?.find(e=>e.state.status===`pending`);return!n||n===e}else return!0}runNext(e){let t=ke(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){N.batch(()=>{this.#e.forEach(e=>{this.notify({type:`removed`,mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>ee(t,e))}findAll(e={}){return this.getAll().filter(t=>ee(e,t))}notify(e){N.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return N.batch(()=>Promise.all(e.map(e=>e.continue().catch(m))))}};function ke(e){return e.options.scope?.id}var Ae=class extends l{#e;#t=void 0;#n;#r;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let t=this.options;this.options=this.#e.defaultMutationOptions(e),T(this.options,t)||this.#e.getMutationCache().notify({type:`observerOptionsUpdated`,mutation:this.#n,observer:this}),t?.mutationKey&&this.options.mutationKey&&S(t.mutationKey)!==S(this.options.mutationKey)?this.reset():this.#n?.state.status===`pending`&&this.#n.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#a(e)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#i(),this.#a()}mutate(e,t){return this.#r=t,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(e)}#i(){let e=this.#n?.state??Oe();this.#t={...e,isPending:e.status===`pending`,isSuccess:e.status===`success`,isError:e.status===`error`,isIdle:e.status===`idle`,mutate:this.mutate,reset:this.reset}}#a(e){N.batch(()=>{if(this.#r&&this.hasListeners()){let t=this.#t.variables,n=this.#t.context,r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type===`success`){try{this.#r.onSuccess?.(e.data,t,n,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(e.data,null,t,n,r)}catch(e){Promise.reject(e)}}else if(e?.type===`error`){try{this.#r.onError?.(e.error,t,n,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(void 0,e.error,t,n,r)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}},je=class extends l{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){let r=t.queryKey,i=t.queryHash??x(r,t),a=this.get(i);return a||(a=new he({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:`added`,query:e}))}remove(e){let t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){N.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>b(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>b(e,t)):t}notify(e){N.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){N.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){N.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Me=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new je,this.#t=e.mutationCache||new z,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=oe.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=ue.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:`fetching`}).length}isMutating(e){return this.#t.findAll({...e,status:`pending`}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(v(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(r.queryHash)?.state.data,a=h(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return N.batch(()=>this.#e.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;N.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return N.batch(()=>(n.findAll(e).forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=N.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(m).catch(m)}invalidateQueries(e,t={}){return N.batch(()=>(this.#e.findAll(e).forEach(e=>{e.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=N.batch(()=>this.#e.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(m)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(m)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(v(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(m).catch(m)}fetchInfiniteQuery(e){return e.behavior=R(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(m).catch(m)}ensureInfiniteQueryData(e){return e.behavior=R(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return ue.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(S(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{C(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(S(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{C(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||=x(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===A&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},B=c(t(),1),V=i(),Ne=B.createContext(void 0),H=e=>{let t=B.useContext(Ne);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},Pe=({client:e,children:t})=>(B.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,V.jsx)(Ne.Provider,{value:e,children:t})),Fe=B.createContext(!1),Ie=()=>B.useContext(Fe);Fe.Provider;function Le(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Re=B.createContext(Le()),ze=()=>B.useContext(Re),Be=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?M(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Ve=e=>{B.useEffect(()=>{e.clearReset()},[e])},He=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||M(n,[e.error,r])),Ue=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},We=(e,t)=>e.isLoading&&e.isFetching&&!t,Ge=(e,t)=>e?.suspense&&t.isPending,Ke=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function qe(e,t,n){let r=Ie(),i=ze(),a=H(n),o=a.defaultQueryOptions(e);a.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let s=a.getQueryCache().get(o.queryHash);o._optimisticResults=r?`isRestoring`:`optimistic`,Ue(o),Be(o,i,s),Ve(i);let c=!a.getQueryCache().get(o.queryHash),[l]=B.useState(()=>new t(a,o)),u=l.getOptimisticResult(o),d=!r&&e.subscribed!==!1;if(B.useSyncExternalStore(B.useCallback(e=>{let t=d?l.subscribe(N.batchCalls(e)):m;return l.updateResult(),t},[l,d]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),B.useEffect(()=>{l.setOptions(o)},[o,l]),Ge(o,u))throw Ke(o,l,i);if(He({result:u,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw u.error;return a.getDefaultOptions().queries?._experimental_afterQuery?.(o,u),o.experimental_prefetchInRender&&!p&&We(u,r)&&(c?Ke(o,l,i):s?.promise)?.catch(m).finally(()=>{l.updateResult()}),o.notifyOnChangeProps?u:l.trackResult(u)}function Je(e,t){return qe(e,_e,t)}function Ye(e,t){let n=H(t),[r]=B.useState(()=>new Ae(n,e));B.useEffect(()=>{r.setOptions(e)},[r,e]);let i=B.useSyncExternalStore(B.useCallback(e=>r.subscribe(N.batchCalls(e)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=B.useCallback((e,t)=>{r.mutate(e,t).catch(m)},[r]);if(i.error&&M(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}var Xe=c(n(),1),Ze=e=>{switch(e){case`success`:return et;case`info`:return nt;case`warning`:return tt;case`error`:return rt;default:return null}},Qe=Array(12).fill(0),$e=({visible:e,className:t})=>B.createElement(`div`,{className:[`sonner-loading-wrapper`,t].filter(Boolean).join(` `),"data-visible":e},B.createElement(`div`,{className:`sonner-spinner`},Qe.map((e,t)=>B.createElement(`div`,{className:`sonner-loading-bar`,key:`spinner-bar-${t}`})))),et=B.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},B.createElement(`path`,{fillRule:`evenodd`,d:`M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z`,clipRule:`evenodd`})),tt=B.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 24 24`,fill:`currentColor`,height:`20`,width:`20`},B.createElement(`path`,{fillRule:`evenodd`,d:`M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z`,clipRule:`evenodd`})),nt=B.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},B.createElement(`path`,{fillRule:`evenodd`,d:`M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z`,clipRule:`evenodd`})),rt=B.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},B.createElement(`path`,{fillRule:`evenodd`,d:`M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z`,clipRule:`evenodd`})),it=B.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`},B.createElement(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),B.createElement(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})),at=()=>{let[e,t]=B.useState(document.hidden);return B.useEffect(()=>{let e=()=>{t(document.hidden)};return document.addEventListener(`visibilitychange`,e),()=>window.removeEventListener(`visibilitychange`,e)},[]),e},ot=1,U=new class{constructor(){this.subscribe=e=>(this.subscribers.push(e),()=>{let t=this.subscribers.indexOf(e);this.subscribers.splice(t,1)}),this.publish=e=>{this.subscribers.forEach(t=>t(e))},this.addToast=e=>{this.publish(e),this.toasts=[...this.toasts,e]},this.create=e=>{let{message:t,...n}=e,r=typeof e?.id==`number`||e.id?.length>0?e.id:ot++,i=this.toasts.find(e=>e.id===r),a=e.dismissible===void 0?!0:e.dismissible;return this.dismissedToasts.has(r)&&this.dismissedToasts.delete(r),i?this.toasts=this.toasts.map(n=>n.id===r?(this.publish({...n,...e,id:r,title:t}),{...n,...e,id:r,dismissible:a,title:t}):n):this.addToast({title:t,...n,dismissible:a,id:r}),r},this.dismiss=e=>(this.dismissedToasts.add(e),e||this.toasts.forEach(e=>{this.subscribers.forEach(t=>t({id:e.id,dismiss:!0}))}),this.subscribers.forEach(t=>t({id:e,dismiss:!0})),e),this.message=(e,t)=>this.create({...t,message:e}),this.error=(e,t)=>this.create({...t,message:e,type:`error`}),this.success=(e,t)=>this.create({...t,type:`success`,message:e}),this.info=(e,t)=>this.create({...t,type:`info`,message:e}),this.warning=(e,t)=>this.create({...t,type:`warning`,message:e}),this.loading=(e,t)=>this.create({...t,type:`loading`,message:e}),this.promise=(e,t)=>{if(!t)return;let n;t.loading!==void 0&&(n=this.create({...t,promise:e,type:`loading`,message:t.loading,description:typeof t.description==`function`?void 0:t.description}));let r=e instanceof Promise?e:e(),i=n!==void 0,a,o=r.then(async e=>{if(a=[`resolve`,e],B.isValidElement(e))i=!1,this.create({id:n,type:`default`,message:e});else if(ct(e)&&!e.ok){i=!1;let r=typeof t.error==`function`?await t.error(`HTTP error! status: ${e.status}`):t.error,a=typeof t.description==`function`?await t.description(`HTTP error! status: ${e.status}`):t.description;this.create({id:n,type:`error`,message:r,description:a})}else if(t.success!==void 0){i=!1;let r=typeof t.success==`function`?await t.success(e):t.success,a=typeof t.description==`function`?await t.description(e):t.description;this.create({id:n,type:`success`,message:r,description:a})}}).catch(async e=>{if(a=[`reject`,e],t.error!==void 0){i=!1;let r=typeof t.error==`function`?await t.error(e):t.error,a=typeof t.description==`function`?await t.description(e):t.description;this.create({id:n,type:`error`,message:r,description:a})}}).finally(()=>{var e;i&&(this.dismiss(n),n=void 0),(e=t.finally)==null||e.call(t)}),s=()=>new Promise((e,t)=>o.then(()=>a[0]===`reject`?t(a[1]):e(a[1])).catch(t));return typeof n!=`string`&&typeof n!=`number`?{unwrap:s}:Object.assign(n,{unwrap:s})},this.custom=(e,t)=>{let n=t?.id||ot++;return this.create({jsx:e(n),id:n,...t}),n},this.getActiveToasts=()=>this.toasts.filter(e=>!this.dismissedToasts.has(e.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},st=(e,t)=>{let n=t?.id||ot++;return U.addToast({title:e,...t,id:n}),n},ct=e=>e&&typeof e==`object`&&`ok`in e&&typeof e.ok==`boolean`&&`status`in e&&typeof e.status==`number`,W=Object.assign(st,{success:U.success,info:U.info,warning:U.warning,error:U.error,custom:U.custom,message:U.message,promise:U.promise,dismiss:U.dismiss,loading:U.loading},{getHistory:()=>U.toasts,getToasts:()=>U.getActiveToasts()});function lt(e,{insertAt:t}={}){if(!e||typeof document>`u`)return;let n=document.head||document.getElementsByTagName(`head`)[0],r=document.createElement(`style`);r.type=`text/css`,t===`top`&&n.firstChild?n.insertBefore(r,n.firstChild):n.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}lt(`:where(html[dir="ltr"]),:where([data-sonner-toaster][dir="ltr"]){--toast-icon-margin-start: -3px;--toast-icon-margin-end: 4px;--toast-svg-margin-start: -1px;--toast-svg-margin-end: 0px;--toast-button-margin-start: auto;--toast-button-margin-end: 0;--toast-close-button-start: 0;--toast-close-button-end: unset;--toast-close-button-transform: translate(-35%, -35%)}:where(html[dir="rtl"]),:where([data-sonner-toaster][dir="rtl"]){--toast-icon-margin-start: 4px;--toast-icon-margin-end: -3px;--toast-svg-margin-start: 0px;--toast-svg-margin-end: -1px;--toast-button-margin-start: 0;--toast-button-margin-end: auto;--toast-close-button-start: unset;--toast-close-button-end: 0;--toast-close-button-transform: translate(35%, -35%)}:where([data-sonner-toaster]){position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1: hsl(0, 0%, 99%);--gray2: hsl(0, 0%, 97.3%);--gray3: hsl(0, 0%, 95.1%);--gray4: hsl(0, 0%, 93%);--gray5: hsl(0, 0%, 90.9%);--gray6: hsl(0, 0%, 88.7%);--gray7: hsl(0, 0%, 85.8%);--gray8: hsl(0, 0%, 78%);--gray9: hsl(0, 0%, 56.1%);--gray10: hsl(0, 0%, 52.3%);--gray11: hsl(0, 0%, 43.5%);--gray12: hsl(0, 0%, 9%);--border-radius: 8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:none;z-index:999999999;transition:transform .4s ease}:where([data-sonner-toaster][data-lifted="true"]){transform:translateY(-10px)}@media (hover: none) and (pointer: coarse){:where([data-sonner-toaster][data-lifted="true"]){transform:none}}:where([data-sonner-toaster][data-x-position="right"]){right:var(--offset-right)}:where([data-sonner-toaster][data-x-position="left"]){left:var(--offset-left)}:where([data-sonner-toaster][data-x-position="center"]){left:50%;transform:translate(-50%)}:where([data-sonner-toaster][data-y-position="top"]){top:var(--offset-top)}:where([data-sonner-toaster][data-y-position="bottom"]){bottom:var(--offset-bottom)}:where([data-sonner-toast]){--y: translateY(100%);--lift-amount: calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);filter:blur(0);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:none;overflow-wrap:anywhere}:where([data-sonner-toast][data-styled="true"]){padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px #0000001a;width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}:where([data-sonner-toast]:focus-visible){box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast][data-y-position="top"]){top:0;--y: translateY(-100%);--lift: 1;--lift-amount: calc(1 * var(--gap))}:where([data-sonner-toast][data-y-position="bottom"]){bottom:0;--y: translateY(100%);--lift: -1;--lift-amount: calc(var(--lift) * var(--gap))}:where([data-sonner-toast]) :where([data-description]){font-weight:400;line-height:1.4;color:inherit}:where([data-sonner-toast]) :where([data-title]){font-weight:500;line-height:1.5;color:inherit}:where([data-sonner-toast]) :where([data-icon]){display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}:where([data-sonner-toast][data-promise="true"]) :where([data-icon])>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}:where([data-sonner-toast]) :where([data-icon])>*{flex-shrink:0}:where([data-sonner-toast]) :where([data-icon]) svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}:where([data-sonner-toast]) :where([data-content]){display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;cursor:pointer;outline:none;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}:where([data-sonner-toast]) :where([data-button]):focus-visible{box-shadow:0 0 0 2px #0006}:where([data-sonner-toast]) :where([data-button]):first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}:where([data-sonner-toast]) :where([data-cancel]){color:var(--normal-text);background:rgba(0,0,0,.08)}:where([data-sonner-toast][data-theme="dark"]) :where([data-cancel]){background:rgba(255,255,255,.3)}:where([data-sonner-toast]) :where([data-close-button]){position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast] [data-close-button]{background:var(--gray1)}:where([data-sonner-toast]) :where([data-close-button]):focus-visible{box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast]) :where([data-disabled="true"]){cursor:not-allowed}:where([data-sonner-toast]):hover :where([data-close-button]):hover{background:var(--gray2);border-color:var(--gray5)}:where([data-sonner-toast][data-swiping="true"]):before{content:"";position:absolute;left:-50%;right:-50%;height:100%;z-index:-1}:where([data-sonner-toast][data-y-position="top"][data-swiping="true"]):before{bottom:50%;transform:scaleY(3) translateY(50%)}:where([data-sonner-toast][data-y-position="bottom"][data-swiping="true"]):before{top:50%;transform:scaleY(3) translateY(-50%)}:where([data-sonner-toast][data-swiping="false"][data-removed="true"]):before{content:"";position:absolute;inset:0;transform:scaleY(2)}:where([data-sonner-toast]):after{content:"";position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}:where([data-sonner-toast][data-mounted="true"]){--y: translateY(0);opacity:1}:where([data-sonner-toast][data-expanded="false"][data-front="false"]){--scale: var(--toasts-before) * .05 + 1;--y: translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}:where([data-sonner-toast])>*{transition:opacity .4s}:where([data-sonner-toast][data-expanded="false"][data-front="false"][data-styled="true"])>*{opacity:0}:where([data-sonner-toast][data-visible="false"]){opacity:0;pointer-events:none}:where([data-sonner-toast][data-mounted="true"][data-expanded="true"]){--y: translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}:where([data-sonner-toast][data-removed="true"][data-front="true"][data-swipe-out="false"]){--y: translateY(calc(var(--lift) * -100%));opacity:0}:where([data-sonner-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="true"]){--y: translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}:where([data-sonner-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="false"]){--y: translateY(40%);opacity:0;transition:transform .5s,opacity .2s}:where([data-sonner-toast][data-removed="true"][data-front="false"]):before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y, 0px)) translate(var(--swipe-amount-x, 0px));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{0%{transform:var(--y) translate(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translate(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{0%{transform:var(--y) translate(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translate(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{0%{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{0%{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width: 600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-theme=light]{--normal-bg: #fff;--normal-border: var(--gray4);--normal-text: var(--gray12);--success-bg: hsl(143, 85%, 96%);--success-border: hsl(145, 92%, 91%);--success-text: hsl(140, 100%, 27%);--info-bg: hsl(208, 100%, 97%);--info-border: hsl(221, 91%, 91%);--info-text: hsl(210, 92%, 45%);--warning-bg: hsl(49, 100%, 97%);--warning-border: hsl(49, 91%, 91%);--warning-text: hsl(31, 92%, 45%);--error-bg: hsl(359, 100%, 97%);--error-border: hsl(359, 100%, 94%);--error-text: hsl(360, 100%, 45%)}[data-sonner-toaster][data-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg: #000;--normal-border: hsl(0, 0%, 20%);--normal-text: var(--gray1)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg: #fff;--normal-border: var(--gray3);--normal-text: var(--gray12)}[data-sonner-toaster][data-theme=dark]{--normal-bg: #000;--normal-bg-hover: hsl(0, 0%, 12%);--normal-border: hsl(0, 0%, 20%);--normal-border-hover: hsl(0, 0%, 25%);--normal-text: var(--gray1);--success-bg: hsl(150, 100%, 6%);--success-border: hsl(147, 100%, 12%);--success-text: hsl(150, 86%, 65%);--info-bg: hsl(215, 100%, 6%);--info-border: hsl(223, 100%, 12%);--info-text: hsl(216, 87%, 65%);--warning-bg: hsl(64, 100%, 6%);--warning-border: hsl(60, 100%, 12%);--warning-text: hsl(46, 87%, 65%);--error-bg: hsl(358, 76%, 10%);--error-border: hsl(357, 89%, 16%);--error-text: hsl(358, 100%, 81%)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success],[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info],[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning],[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error],[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size: 16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:nth-child(1){animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}to{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}to{opacity:.15}}@media (prefers-reduced-motion){[data-sonner-toast],[data-sonner-toast]>*,.sonner-loading-bar{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}
2
- `);function ut(e){return e.label!==void 0}var dt=3,ft=`32px`,pt=`16px`,mt=4e3,ht=356,gt=14,_t=20,vt=200;function G(...e){return e.filter(Boolean).join(` `)}function yt(e){let[t,n]=e.split(`-`),r=[];return t&&r.push(t),n&&r.push(n),r}var bt=e=>{let{invert:t,toast:n,unstyled:r,interacting:i,setHeights:a,visibleToasts:o,heights:s,index:c,toasts:l,expanded:u,removeToast:d,defaultRichColors:f,closeButton:p,style:m,cancelButtonStyle:h,actionButtonStyle:g,className:_=``,descriptionClassName:v=``,duration:y,position:b,gap:ee,loadingIcon:x,expandByDefault:S,classNames:C,icons:w,closeButtonAriaLabel:te=`Close toast`,pauseWhenPageIsHidden:T}=e,[E,D]=B.useState(null),[ne,re]=B.useState(null),[O,k]=B.useState(!1),[ie,A]=B.useState(!1),[j,M]=B.useState(!1),[ae,oe]=B.useState(!1),[se,ce]=B.useState(!1),[le,N]=B.useState(0),[ue,de]=B.useState(0),fe=B.useRef(n.duration||y||mt),pe=B.useRef(null),P=B.useRef(null),me=c===0,he=c+1<=o,F=n.type,I=n.dismissible!==!1,ge=n.className||``,_e=n.descriptionClassName||``,ve=B.useMemo(()=>s.findIndex(e=>e.toastId===n.id)||0,[s,n.id]),ye=B.useMemo(()=>n.closeButton??p,[n.closeButton,p]),be=B.useMemo(()=>n.duration||y||mt,[n.duration,y]),xe=B.useRef(0),L=B.useRef(0),Se=B.useRef(0),R=B.useRef(null),[Ce,we]=b.split(`-`),Te=B.useMemo(()=>s.reduce((e,t,n)=>n>=ve?e:e+t.height,0),[s,ve]),Ee=at(),De=n.invert||t,Oe=F===`loading`;L.current=B.useMemo(()=>ve*ee+Te,[ve,Te]),B.useEffect(()=>{fe.current=be},[be]),B.useEffect(()=>{k(!0)},[]),B.useEffect(()=>{let e=P.current;if(e){let t=e.getBoundingClientRect().height;return de(t),a(e=>[{toastId:n.id,height:t,position:n.position},...e]),()=>a(e=>e.filter(e=>e.toastId!==n.id))}},[a,n.id]),B.useLayoutEffect(()=>{if(!O)return;let e=P.current,t=e.style.height;e.style.height=`auto`;let r=e.getBoundingClientRect().height;e.style.height=t,de(r),a(e=>e.find(e=>e.toastId===n.id)?e.map(e=>e.toastId===n.id?{...e,height:r}:e):[{toastId:n.id,height:r,position:n.position},...e])},[O,n.title,n.description,a,n.id]);let z=B.useCallback(()=>{A(!0),N(L.current),a(e=>e.filter(e=>e.toastId!==n.id)),setTimeout(()=>{d(n)},vt)},[n,d,a,L]);B.useEffect(()=>{if(n.promise&&F===`loading`||n.duration===1/0||n.type===`loading`)return;let e;return u||i||T&&Ee?(()=>{if(Se.current<xe.current){let e=new Date().getTime()-xe.current;fe.current-=e}Se.current=new Date().getTime()})():fe.current!==1/0&&(xe.current=new Date().getTime(),e=setTimeout(()=>{var e;(e=n.onAutoClose)==null||e.call(n,n),z()},fe.current)),()=>clearTimeout(e)},[u,i,n,F,T,Ee,z]),B.useEffect(()=>{n.delete&&z()},[z,n.delete]);function ke(){return w!=null&&w.loading?B.createElement(`div`,{className:G(C?.loader,n?.classNames?.loader,`sonner-loader`),"data-visible":F===`loading`},w.loading):x?B.createElement(`div`,{className:G(C?.loader,n?.classNames?.loader,`sonner-loader`),"data-visible":F===`loading`},x):B.createElement($e,{className:G(C?.loader,n?.classNames?.loader),visible:F===`loading`})}return B.createElement(`li`,{tabIndex:0,ref:P,className:G(_,ge,C?.toast,n?.classNames?.toast,C?.default,C?.[F],n?.classNames?.[F]),"data-sonner-toast":``,"data-rich-colors":n.richColors??f,"data-styled":!(n.jsx||n.unstyled||r),"data-mounted":O,"data-promise":!!n.promise,"data-swiped":se,"data-removed":ie,"data-visible":he,"data-y-position":Ce,"data-x-position":we,"data-index":c,"data-front":me,"data-swiping":j,"data-dismissible":I,"data-type":F,"data-invert":De,"data-swipe-out":ae,"data-swipe-direction":ne,"data-expanded":!!(u||S&&O),style:{"--index":c,"--toasts-before":c,"--z-index":l.length-c,"--offset":`${ie?le:L.current}px`,"--initial-height":S?`auto`:`${ue}px`,...m,...n.style},onDragEnd:()=>{M(!1),D(null),R.current=null},onPointerDown:e=>{Oe||!I||(pe.current=new Date,N(L.current),e.target.setPointerCapture(e.pointerId),e.target.tagName!==`BUTTON`&&(M(!0),R.current={x:e.clientX,y:e.clientY}))},onPointerUp:()=>{var e;if(ae||!I)return;R.current=null;let t=Number(P.current?.style.getPropertyValue(`--swipe-amount-x`).replace(`px`,``)||0),r=Number(P.current?.style.getPropertyValue(`--swipe-amount-y`).replace(`px`,``)||0),i=new Date().getTime()-pe.current?.getTime(),a=E===`x`?t:r,o=Math.abs(a)/i;if(Math.abs(a)>=_t||o>.11){N(L.current),(e=n.onDismiss)==null||e.call(n,n),re(E===`x`?t>0?`right`:`left`:r>0?`down`:`up`),z(),oe(!0),ce(!1);return}M(!1),D(null)},onPointerMove:t=>{var n,r;if(!R.current||!I||window.getSelection()?.toString().length>0)return;let i=t.clientY-R.current.y,a=t.clientX-R.current.x,o=e.swipeDirections??yt(b);!E&&(Math.abs(a)>1||Math.abs(i)>1)&&D(Math.abs(a)>Math.abs(i)?`x`:`y`);let s={x:0,y:0};E===`y`?(o.includes(`top`)||o.includes(`bottom`))&&(o.includes(`top`)&&i<0||o.includes(`bottom`)&&i>0)&&(s.y=i):E===`x`&&(o.includes(`left`)||o.includes(`right`))&&(o.includes(`left`)&&a<0||o.includes(`right`)&&a>0)&&(s.x=a),(Math.abs(s.x)>0||Math.abs(s.y)>0)&&ce(!0),(n=P.current)==null||n.style.setProperty(`--swipe-amount-x`,`${s.x}px`),(r=P.current)==null||r.style.setProperty(`--swipe-amount-y`,`${s.y}px`)}},ye&&!n.jsx?B.createElement(`button`,{"aria-label":te,"data-disabled":Oe,"data-close-button":!0,onClick:Oe||!I?()=>{}:()=>{var e;z(),(e=n.onDismiss)==null||e.call(n,n)},className:G(C?.closeButton,n?.classNames?.closeButton)},w?.close??it):null,n.jsx||(0,B.isValidElement)(n.title)?n.jsx?n.jsx:typeof n.title==`function`?n.title():n.title:B.createElement(B.Fragment,null,F||n.icon||n.promise?B.createElement(`div`,{"data-icon":``,className:G(C?.icon,n?.classNames?.icon)},n.promise||n.type===`loading`&&!n.icon?n.icon||ke():null,n.type===`loading`?null:n.icon||w?.[F]||Ze(F)):null,B.createElement(`div`,{"data-content":``,className:G(C?.content,n?.classNames?.content)},B.createElement(`div`,{"data-title":``,className:G(C?.title,n?.classNames?.title)},typeof n.title==`function`?n.title():n.title),n.description?B.createElement(`div`,{"data-description":``,className:G(v,_e,C?.description,n?.classNames?.description)},typeof n.description==`function`?n.description():n.description):null),(0,B.isValidElement)(n.cancel)?n.cancel:n.cancel&&ut(n.cancel)?B.createElement(`button`,{"data-button":!0,"data-cancel":!0,style:n.cancelButtonStyle||h,onClick:e=>{var t,r;ut(n.cancel)&&I&&((r=(t=n.cancel).onClick)==null||r.call(t,e),z())},className:G(C?.cancelButton,n?.classNames?.cancelButton)},n.cancel.label):null,(0,B.isValidElement)(n.action)?n.action:n.action&&ut(n.action)?B.createElement(`button`,{"data-button":!0,"data-action":!0,style:n.actionButtonStyle||g,onClick:e=>{var t,r;ut(n.action)&&((r=(t=n.action).onClick)==null||r.call(t,e),!e.defaultPrevented&&z())},className:G(C?.actionButton,n?.classNames?.actionButton)},n.action.label):null))};function xt(){if(typeof window>`u`||typeof document>`u`)return`ltr`;let e=document.documentElement.getAttribute(`dir`);return e===`auto`||!e?window.getComputedStyle(document.documentElement).direction:e}function St(e,t){let n={};return[e,t].forEach((e,t)=>{let r=t===1,i=r?`--mobile-offset`:`--offset`,a=r?pt:ft;function o(e){[`top`,`right`,`bottom`,`left`].forEach(t=>{n[`${i}-${t}`]=typeof e==`number`?`${e}px`:e})}typeof e==`number`||typeof e==`string`?o(e):typeof e==`object`?[`top`,`right`,`bottom`,`left`].forEach(t=>{e[t]===void 0?n[`${i}-${t}`]=a:n[`${i}-${t}`]=typeof e[t]==`number`?`${e[t]}px`:e[t]}):o(a)}),n}var Ct=(0,B.forwardRef)(function(e,t){let{invert:n,position:r=`bottom-right`,hotkey:i=[`altKey`,`KeyT`],expand:a,closeButton:o,className:s,offset:c,mobileOffset:l,theme:u=`light`,richColors:d,duration:f,style:p,visibleToasts:m=dt,toastOptions:h,dir:g=xt(),gap:_=gt,loadingIcon:v,icons:y,containerAriaLabel:b=`Notifications`,pauseWhenPageIsHidden:ee}=e,[x,S]=B.useState([]),C=B.useMemo(()=>Array.from(new Set([r].concat(x.filter(e=>e.position).map(e=>e.position)))),[x,r]),[w,te]=B.useState([]),[T,E]=B.useState(!1),[D,ne]=B.useState(!1),[re,O]=B.useState(u===`system`?typeof window<`u`&&window.matchMedia&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`:u),k=B.useRef(null),ie=i.join(`+`).replace(/Key/g,``).replace(/Digit/g,``),A=B.useRef(null),j=B.useRef(!1),M=B.useCallback(e=>{S(t=>{var n;return(n=t.find(t=>t.id===e.id))!=null&&n.delete||U.dismiss(e.id),t.filter(({id:t})=>t!==e.id)})},[]);return B.useEffect(()=>U.subscribe(e=>{if(e.dismiss){S(t=>t.map(t=>t.id===e.id?{...t,delete:!0}:t));return}setTimeout(()=>{Xe.flushSync(()=>{S(t=>{let n=t.findIndex(t=>t.id===e.id);return n===-1?[e,...t]:[...t.slice(0,n),{...t[n],...e},...t.slice(n+1)]})})})}),[]),B.useEffect(()=>{if(u!==`system`){O(u);return}if(u===`system`&&(window.matchMedia&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?O(`dark`):O(`light`)),typeof window>`u`)return;let e=window.matchMedia(`(prefers-color-scheme: dark)`);try{e.addEventListener(`change`,({matches:e})=>{O(e?`dark`:`light`)})}catch{e.addListener(({matches:e})=>{try{O(e?`dark`:`light`)}catch(e){console.error(e)}})}},[u]),B.useEffect(()=>{x.length<=1&&E(!1)},[x]),B.useEffect(()=>{let e=e=>{var t,n;i.every(t=>e[t]||e.code===t)&&(E(!0),(t=k.current)==null||t.focus()),e.code===`Escape`&&(document.activeElement===k.current||(n=k.current)!=null&&n.contains(document.activeElement))&&E(!1)};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[i]),B.useEffect(()=>{if(k.current)return()=>{A.current&&(A.current.focus({preventScroll:!0}),A.current=null,j.current=!1)}},[k.current]),B.createElement(`section`,{ref:t,"aria-label":`${b} ${ie}`,tabIndex:-1,"aria-live":`polite`,"aria-relevant":`additions text`,"aria-atomic":`false`,suppressHydrationWarning:!0},C.map((t,r)=>{let[i,u]=t.split(`-`);return x.length?B.createElement(`ol`,{key:t,dir:g===`auto`?xt():g,tabIndex:-1,ref:k,className:s,"data-sonner-toaster":!0,"data-theme":re,"data-y-position":i,"data-lifted":T&&x.length>1&&!a,"data-x-position":u,style:{"--front-toast-height":`${w[0]?.height||0}px`,"--width":`${ht}px`,"--gap":`${_}px`,...p,...St(c,l)},onBlur:e=>{j.current&&!e.currentTarget.contains(e.relatedTarget)&&(j.current=!1,A.current&&=(A.current.focus({preventScroll:!0}),null))},onFocus:e=>{e.target instanceof HTMLElement&&e.target.dataset.dismissible===`false`||j.current||(j.current=!0,A.current=e.relatedTarget)},onMouseEnter:()=>E(!0),onMouseMove:()=>E(!0),onMouseLeave:()=>{D||E(!1)},onDragEnd:()=>E(!1),onPointerDown:e=>{e.target instanceof HTMLElement&&e.target.dataset.dismissible===`false`||ne(!0)},onPointerUp:()=>ne(!1)},x.filter(e=>!e.position&&r===0||e.position===t).map((r,i)=>B.createElement(bt,{key:r.id,icons:y,index:i,toast:r,defaultRichColors:d,duration:h?.duration??f,className:h?.className,descriptionClassName:h?.descriptionClassName,invert:n,visibleToasts:m,closeButton:h?.closeButton??o,interacting:D,position:t,style:h?.style,unstyled:h?.unstyled,classNames:h?.classNames,cancelButtonStyle:h?.cancelButtonStyle,actionButtonStyle:h?.actionButtonStyle,removeToast:M,toasts:x.filter(e=>e.position==r.position),heights:w.filter(e=>e.position==r.position),setHeights:te,expandByDefault:a,gap:_,loadingIcon:v,expanded:T,pauseWhenPageIsHidden:ee,swipeDirections:e.swipeDirections}))):null}))}),wt=new Me({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!0}}}),Tt=e=>typeof e==`boolean`?`${e}`:e===0?`0`:e,Et=a,Dt=(e,t)=>n=>{if(t?.variants==null)return Et(e,n?.class,n?.className);let{variants:r,defaultVariants:i}=t,a=Object.keys(r).map(e=>{let t=n?.[e],a=i?.[e];if(t===null)return null;let o=Tt(t)||Tt(a);return r[e][o]}),o=n&&Object.entries(n).reduce((e,t)=>{let[n,r]=t;return r===void 0||(e[n]=r),e},{});return Et(e,a,t?.compoundVariants?.reduce((e,t)=>{let{class:n,className:r,...a}=t;return Object.entries(a).every(e=>{let[t,n]=e;return Array.isArray(n)?n.includes({...i,...o}[t]):{...i,...o}[t]===n})?[...e,n,r]:e},[]),n?.class,n?.className)},Ot=Dt(`inline-flex items-center justify-center whitespace-nowrap rounded-full text-sm font-medium ring-offset-background transition-colors duration-fast focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50`,{variants:{variant:{default:`bg-primary text-primary-foreground hover:bg-primary-600 active:bg-primary-700 shadow-sm`,destructive:`bg-destructive text-destructive-foreground hover:bg-destructive/90`,outline:`border border-gray-200 bg-white hover:bg-gray-50 hover:text-gray-800 text-gray-600`,secondary:`bg-gray-100 text-gray-700 hover:bg-gray-200/80`,ghost:`hover:bg-gray-100/80 hover:text-gray-800`,link:`text-primary underline-offset-4 hover:underline`,primary:`bg-primary text-primary-foreground hover:bg-primary-600 active:bg-primary-700 shadow-sm`,subtle:`bg-gray-100 text-gray-600 hover:bg-gray-200/80`,"primary-outline":`border border-primary/30 text-primary hover:bg-primary hover:text-primary-foreground`},size:{default:`h-9 px-4 py-2`,sm:`h-8 px-3 text-xs`,lg:`h-11 px-5 text-[14px]`,xl:`h-12 px-6 text-[15px]`,icon:`h-9 w-9`}},defaultVariants:{variant:`default`,size:`default`}}),kt=B.forwardRef(({className:t,variant:n,size:r,...i},a)=>(0,V.jsx)(`button`,{className:e(Ot({variant:n,size:r,className:t})),ref:a,...i}));kt.displayName=`Button`;var K=B.forwardRef(({className:t,type:n,...r},i)=>(0,V.jsx)(`input`,{type:n,className:e(`flex h-9 w-full rounded-xl border border-gray-200/80 bg-white px-3.5 py-2 text-sm text-gray-900 file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-gray-300 placeholder:font-normal focus:outline-none focus:ring-1 focus:ring-primary/40 focus:border-primary/40 transition-colors disabled:cursor-not-allowed disabled:opacity-50`,t),ref:i,...r}));K.displayName=`Input`;var At=B.forwardRef(({className:t,...n},r)=>(0,V.jsx)(`label`,{ref:r,className:e(`text-sm font-medium leading-none text-gray-700 peer-disabled:cursor-not-allowed peer-disabled:opacity-70`,t),...n}));At.displayName=`Label`;function jt({children:t,fullHeight:n=!1,className:r}){return(0,V.jsx)(`div`,{className:e(`animate-fade-in`,n?`h-[calc(100vh-80px)] w-full flex flex-col`:`pb-16`,r),children:t})}function Mt({title:t,description:n,actions:r,className:i}){return(0,V.jsxs)(`div`,{className:e(`flex items-center justify-between mb-6 shrink-0`,i),children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`h2`,{className:`text-xl font-semibold text-gray-900`,children:t}),n&&(0,V.jsx)(`p`,{className:`text-sm text-gray-500 mt-1`,children:n})]}),r&&(0,V.jsx)(`div`,{className:`flex items-center gap-2 shrink-0`,children:r})]})}var Nt=B.forwardRef(({className:t,hover:n=!0,...r},i)=>(0,V.jsx)(`div`,{ref:i,className:e(`rounded-2xl border border-gray-200/50 bg-white text-card-foreground shadow-card transition-all duration-base`,n&&`hover:shadow-card-hover hover:border-gray-200`,t),...r}));Nt.displayName=`Card`;var Pt=B.forwardRef(({className:t,...n},r)=>(0,V.jsx)(`div`,{ref:r,className:e(`flex flex-col space-y-1.5 p-6`,t),...n}));Pt.displayName=`CardHeader`;var Ft=B.forwardRef(({className:t,...n},r)=>(0,V.jsx)(`h3`,{ref:r,className:e(`text-[15px] font-semibold leading-tight tracking-tight text-gray-900`,t),...n}));Ft.displayName=`CardTitle`;var It=B.forwardRef(({className:t,...n},r)=>(0,V.jsx)(`p`,{ref:r,className:e(`text-[13px] text-gray-400 leading-relaxed`,t),...n}));It.displayName=`CardDescription`;var Lt=B.forwardRef(({className:t,...n},r)=>(0,V.jsx)(`div`,{ref:r,className:e(`p-6 pt-0`,t),...n}));Lt.displayName=`CardContent`;var Rt=B.forwardRef(({className:t,...n},r)=>(0,V.jsx)(`div`,{ref:r,className:e(`flex items-center justify-between p-6 pt-0`,t),...n}));Rt.displayName=`CardFooter`;function q(e){let t=e.trim();if(!t)throw Error(`typed key id is required`);return{id:t}}function zt(e){return typeof e==`string`?e.trim():e.id}var Bt=class{listeners=new Map;globalListeners=new Set;listenerCount=0;onFirstSubscriber;onListenerError;onNoSubscribers;constructor(e={}){this.onFirstSubscriber=e.onFirstSubscriber,this.onListenerError=e.onListenerError,this.onNoSubscribers=e.onNoSubscribers}emit=(e,t,n={})=>{let r={type:zt(e),payload:t,...n.emittedAt?{emittedAt:n.emittedAt}:{},...n.source?{source:n.source}:{}};this.emitEnvelope(r)};emitEnvelope=e=>{let t=this.listeners.get(e.type);if(t)for(let n of t)this.safeInvokeListener(e,n);if(this.globalListeners.size!==0)for(let t of this.globalListeners)this.safeInvokeGlobalListener(e,t)};on=(e,t)=>{let n=zt(e),r=this.listeners.get(n)??new Set,i=t,a=!r.has(i);return r.add(i),this.listeners.set(n,r),a&&this.registerSubscriber(),()=>{this.off(e,t)}};off=(e,t)=>{let n=zt(e),r=this.listeners.get(n);if(!r)return;let i=r.delete(t);r.size===0&&this.listeners.delete(n),i&&this.unregisterSubscriber()};once=(e,t)=>{let n=this.on(e,(e,r)=>{n(),t(e,r)});return n};subscribeAll=e=>{let t=!this.globalListeners.has(e);return this.globalListeners.add(e),t&&this.registerSubscriber(),()=>{this.globalListeners.delete(e)&&this.unregisterSubscriber()}};registerSubscriber=()=>{this.listenerCount+=1,this.listenerCount===1&&this.onFirstSubscriber?.()};unregisterSubscriber=()=>{this.listenerCount=Math.max(0,this.listenerCount-1),this.listenerCount===0&&this.onNoSubscribers?.()};safeInvokeListener=(e,t)=>{try{t(e.payload,e)}catch(t){this.onListenerError?.({type:e.type,payload:e.payload,error:t})}};safeInvokeGlobalListener=(e,t)=>{try{t(e)}catch(t){this.onListenerError?.({type:e.type,payload:e.payload,error:t})}}};function J(e){return q(e)}var Vt={configUpdated:J(`config.updated`),channelConfigApplyStatus:J(`channel.config.apply-status`),sessionUpdated:J(`session.updated`),sessionRunStatus:J(`session.run-status`),sessionMetadataChanged:J(`session.metadata.changed`),ncpEvent:J(`ncp.event`),sessionSummaryUpsert:J(`session.summary.upsert`),sessionSummaryDelete:J(`session.summary.delete`),configReloadStarted:J(`config.reload.started`),configReloadFinished:J(`config.reload.finished`),error:J(`error`),connectionOpen:J(`connection.open`),connectionClose:J(`connection.close`),connectionError:J(`connection.error`),runtimeUpdateSnapshot:J(`runtime.update.snapshot`)};q(`extension.channel.config.get`),q(`extension.channel.message.submit`),q(`extension.channel.command.list`),q(`extension.channel.command.execute`),q(`extension.response`),q(`agent-run.send`),q(`agent-run.abort`),q(`agent-run.session-message.request`);function Ht(e){let t=e.trim().replace(/\/+$/,``);if(!t)throw Error(`NextClaw client baseUrl is required.`);return t}function Ut(e,t){return`${Ht(e)}${t.startsWith(`/`)?t:`/${t}`}`}function Wt(e,t){if(!t)return e;let n=typeof t==`string`?t:t.toString();return n?`${e}${e.includes(`?`)?`&`:`?`}${n}`:e}function Gt(e,t){let n=new URL(Ut(e,t));return n.protocol===`https:`?n.protocol=`wss:`:n.protocol===`http:`&&(n.protocol=`ws:`),n.toString()}function Kt(e){let t=e.split(/\r?\n/),n=`message`,r=[];for(let e of t){if(e.startsWith(`event:`)){n=e.slice(6).trim();continue}e.startsWith(`data:`)&&r.push(e.slice(5).trimStart())}return r.length===0?null:{event:n,data:r.join(`
3
- `)}}function qt(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&`type`in t?t:null}catch{return null}}var Jt=class{baseUrl;defaultHeaders;fetchImpl;transport;constructor(e,t){this.requestService=e;let{baseUrl:n,fetchImpl:r,headers:i,token:a,transport:o}=t;this.baseUrl=n,this.fetchImpl=r??fetch,this.transport=o,this.defaultHeaders={Accept:`application/json`,...i??{},...a?{Authorization:`Bearer ${a}`}:{}}}send=async e=>await this.requestService.post(`/api/agent-runs/send`,e);abort=async e=>await this.requestService.post(`/api/agent-runs/abort`,e);stream=(e,t,n={})=>{if(this.transport)throw Error(`Agent run streaming requires the HTTP fetch transport.`);let r=new AbortController,i=()=>r.abort(n.signal?.reason);return n.signal?.addEventListener(`abort`,i,{once:!0}),this.consumeStream(e,t,r.signal,n.onError).finally(()=>{n.signal?.removeEventListener(`abort`,i)}),{close:()=>{r.abort(),n.signal?.removeEventListener(`abort`,i)}}};consumeStream=async(e,t,n,r)=>{try{let r=new URL(Ut(this.baseUrl,`/api/agent-runs/stream`));r.searchParams.set(`sessionId`,e.sessionId);let i=await this.fetchImpl(r.toString(),{method:`GET`,headers:{...this.defaultHeaders,Accept:`text/event-stream`},signal:n});if(!i.ok)throw Error(`Agent run stream failed with HTTP ${i.status}.`);if(!i.body)throw Error(`Agent run stream response has no body.`);await this.readEventStream(i.body,t,n)}catch(e){if(n.aborted)return;r?.(e)}};readEventStream=async(e,t,n)=>{let r=e.getReader(),i=new TextDecoder,a=``;try{for(;!n.aborted;){let{done:e,value:n}=await r.read();if(e)break;a+=i.decode(n,{stream:!0}),a=this.drainFrames(a,t)}a+=i.decode(),this.drainFrames(`${a}\n\n`,t)}finally{r.releaseLock()}};drainFrames=(e,t)=>{let n=e.replaceAll(`\r
1
+ import{d as e,g as t,h as n,i as r,m as i,p as a,t as o,v as s,y as c}from"./react-BVjl1ZaK.js";var l=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(){}},u={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},d=new class{#e=u;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function f(e){setTimeout(e,0)}var p=typeof window>`u`||`Deno`in globalThis;function m(){}function h(e,t){return typeof e==`function`?e(t):e}function g(e){return typeof e==`number`&&e>=0&&e!==1/0}function _(e,t){return Math.max(e+(t||0)-Date.now(),0)}function v(e,t){return typeof e==`function`?e(t):e}function y(e,t){return typeof e==`function`?e(t):e}function b(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==x(o,t.options))return!1}else if(!C(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function ee(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(S(t.options.mutationKey)!==S(a))return!1}else if(!C(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function x(e,t){return(t?.queryKeyHashFn||S)(e)}function S(e){return JSON.stringify(e,(e,t)=>D(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function C(e,t){return e===t?!0:typeof e==typeof t&&e&&t&&typeof e==`object`&&typeof t==`object`?Object.keys(t).every(n=>C(e[n],t[n])):!1}var w=Object.prototype.hasOwnProperty;function te(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=E(e)&&E(t);if(!r&&!(D(e)&&D(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:w.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=te(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function T(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function E(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function D(e){if(!ne(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!ne(n)||!n.hasOwnProperty(`isPrototypeOf`)||Object.getPrototypeOf(e)!==Object.prototype)}function ne(e){return Object.prototype.toString.call(e)===`[object Object]`}function re(e){return new Promise(t=>{d.setTimeout(t,e)})}function O(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:te(e,t)}function k(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function ie(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var A=Symbol();function j(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===A?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function M(e,t){return typeof e==`function`?e(...t):!!e}function ae(e,t,n){let r=!1,i;return Object.defineProperty(e,`signal`,{enumerable:!0,get:()=>(i??=t(),r?i:(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0}),i))}),e}var oe=new class extends l{#e;#t;#n;constructor(){super(),this.#n=e=>{if(!p&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}};function se(){let e,t,n=new Promise((n,r)=>{e=n,t=r});n.status=`pending`,n.catch(()=>{});function r(e){Object.assign(n,e),delete n.resolve,delete n.reject}return n.resolve=t=>{r({status:`fulfilled`,value:t}),e(t)},n.reject=e=>{r({status:`rejected`,reason:e}),t(e)},n}var ce=f;function le(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=ce,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var N=le(),ue=new class extends l{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(!p&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function de(e){return Math.min(1e3*2**e,3e4)}function fe(e){return(e??`online`)===`online`?ue.isOnline():!0}var pe=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function P(e){let t=!1,n=0,r,i=se(),a=()=>i.status!==`pending`,o=t=>{if(!a()){let n=new pe(t);f(n),e.onCancel?.(n)}},s=()=>{t=!0},c=()=>{t=!1},l=()=>oe.isFocused()&&(e.networkMode===`always`||ue.isOnline())&&e.canRun(),u=()=>fe(e.networkMode)&&e.canRun(),d=e=>{a()||(r?.(),i.resolve(e))},f=e=>{a()||(r?.(),i.reject(e))},m=()=>new Promise(t=>{r=e=>{(a()||l())&&t(e)},e.onPause?.()}).then(()=>{r=void 0,a()||e.onContinue?.()}),h=()=>{if(a())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(d).catch(r=>{if(a())return;let i=e.retry??(p?0:3),o=e.retryDelay??de,s=typeof o==`function`?o(n,r):o,c=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);if(t||!c){f(r);return}n++,e.onFail?.(n,r),re(s).then(()=>l()?void 0:m()).then(()=>{t?f(r):h()})})};return{promise:i,status:()=>i.status,cancel:o,continue:()=>(r?.(),i),cancelRetry:s,continueRetry:c,canStart:u,start:()=>(u()?h():m().then(h),i)}}var me=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),g(this.gcTime)&&(this.#e=d.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(p?1/0:300*1e3))}clearGcTimeout(){this.#e&&=(d.clearTimeout(this.#e),void 0)}},he=class extends me{#e;#t;#n;#r;#i;#a;#o;constructor(e){super(),this.#o=!1,this.#a=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#r=e.client,this.#n=this.#r.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#e=ge(this.options),this.state=e.state??this.#e,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#i?.promise}setOptions(e){if(this.options={...this.#a,...e},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=ge(this.options);e.data!==void 0&&(this.setState(I(e.data,e.dataUpdatedAt)),this.#e=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#n.remove(this)}setData(e,t){let n=O(this.state.data,e,this.options);return this.#s({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#s({type:`setState`,state:e,setStateOptions:t})}cancel(e){let t=this.#i?.promise;return this.#i?.cancel(e),t?t.then(m).catch(m):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#e)}isActive(){return this.observers.some(e=>y(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===A||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>v(e.options.staleTime,this)===`static`):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!_(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#i?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#i?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#i&&(this.#o?this.#i.cancel({revert:!0}):this.#i.cancelRetry()),this.scheduleGc()),this.#n.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#s({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#i?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#i)return this.#i.continueRetry(),this.#i.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,`signal`,{enumerable:!0,get:()=>(this.#o=!0,n.signal)})},i=()=>{let e=j(this.options,t),n=(()=>{let e={client:this.#r,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#o=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#r,state:this.state,fetchFn:i};return r(e),e})();this.options.behavior?.onFetch(a,this),this.#t=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#s({type:`fetch`,meta:a.fetchOptions?.meta}),this.#i=P({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof pe&&e.revert&&this.setState({...this.#t,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#s({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#s({type:`pause`})},onContinue:()=>{this.#s({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await this.#i.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#n.config.onSuccess?.(e,this),this.#n.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof pe){if(e.silent)return this.#i.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#s({type:`error`,error:e}),this.#n.config.onError?.(e,this),this.#n.config.onSettled?.(this.state.data,e,this),e}finally{this.scheduleGc()}}#s(e){this.state=(t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...F(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...I(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#t=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}})(this.state),N.batch(()=>{this.observers.forEach(e=>{e.onQueryUpdate()}),this.#n.notify({query:this,type:`updated`,action:e})})}};function F(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:fe(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function I(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function ge(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=class extends l{constructor(e,t){super(),this.options=t,this.#e=e,this.#s=null,this.#o=se(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),ye(this.#t,this.options)?this.#h():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return be(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return be(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof y(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#S(),this.#t.setOptions(this.options),t._defaulted&&!T(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&xe(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||y(this.options.enabled,this.#t)!==y(t.enabled,this.#t)||v(this.options.staleTime,this.#t)!==v(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||y(this.options.enabled,this.#t)!==y(t.enabled,this.#t)||i!==this.#p)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return Se(this,n)&&(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),n===`promise`&&(this.trackProp(`data`),!this.options.experimental_prefetchInRender&&this.#o.status===`pending`&&this.#o.reject(Error(`experimental_prefetchInRender feature flag is not enabled`))),Reflect.get(e,n))})}trackProp(e){this.#m.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(m)),t}#g(){this.#b();let e=v(this.options.staleTime,this.#t);if(p||this.#r.isStale||!g(e))return;let t=_(this.#r.dataUpdatedAt,e)+1;this.#d=d.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return(typeof this.options.refetchInterval==`function`?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#v(e){this.#x(),this.#p=e,!(p||y(this.options.enabled,this.#t)===!1||!g(this.#p)||this.#p===0)&&(this.#f=d.setInterval(()=>{(this.options.refetchIntervalInBackground||oe.isFocused())&&this.#h()},this.#p))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#d&&=(d.clearTimeout(this.#d),void 0)}#x(){this.#f&&=(d.clearInterval(this.#f),void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&ye(e,t),o=i&&xe(e,n,t,r);(a||o)&&(l={...l,...F(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#u?.state.data,this.#u):t.placeholderData,e!==void 0&&(m=`success`,d=O(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h)if(i&&d===a?.data&&t.select===this.#c)d=this.#l;else try{this.#c=t.select,d=t.select(d),d=O(i?.data,d,t),this.#l=d,this.#s=null}catch(e){this.#s=e}this.#s&&(f=this.#s,d=this.#l,p=Date.now(),m=`error`);let g=l.fetchStatus===`fetching`,_=m===`pending`,v=m===`error`,b=_&&g,ee=d!==void 0,x={status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:v,isInitialLoading:b,isLoading:b,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:l.dataUpdateCount>0||l.errorUpdateCount>0,isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:v&&!ee,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:v&&ee,isStale:L(e,t),refetch:this.refetch,promise:this.#o,isEnabled:y(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){let t=x.data!==void 0,r=x.status===`error`&&!t,i=e=>{r?e.reject(x.error):t&&e.resolve(x.data)},a=()=>{i(this.#o=x.promise=se())},o=this.#o;switch(o.status){case`pending`:e.queryHash===n.queryHash&&i(o);break;case`fulfilled`:(r||x.data!==o.value)&&a();break;case`rejected`:(!r||x.error!==o.reason)&&a();break}}return x}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#u=this.#t),!T(t,e)&&(this.#r=t,this.#C({listeners:(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#m.size)return!0;let r=new Set(n??this.#m);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})()}))}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}#C(e){N.batch(()=>{e.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}};function ve(e,t){return y(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status===`error`&&t.retryOnMount===!1)}function ye(e,t){return ve(e,t)||e.state.data!==void 0&&be(e,t,t.refetchOnMount)}function be(e,t,n){if(y(t.enabled,e)!==!1&&v(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&L(e,t)}return!1}function xe(e,t,n,r){return(e!==t||y(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&L(e,n)}function L(e,t){return y(t.enabled,e)!==!1&&e.isStaleByTime(v(t.staleTime,e))}function Se(e,t){return!T(e.getCurrentResult(),t)}function R(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{ae(e,()=>t.signal,()=>n=!0)},u=j(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject();if(r==null&&e.pages.length)return Promise.resolve(e);let a=await u((()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})()),{maxPages:o}=t.options,s=i?ie:k;return{pages:s(e.pages,a,o),pageParams:s(e.pageParams,r,o)}};if(i&&a.length){let e=i===`backward`,t=e?we:Ce,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]??r.initialPageParam:Ce(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(c<t)}return s};t.options.persister?t.fetchFn=()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=l}}}function Ce(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 we(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function Te(e,t){return t?Ce(e,t)!=null:!1}function Ee(e,t){return!t||!e.getPreviousPageParam?!1:we(e,t)!=null}var De=class extends me{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||Oe(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:`observerRemoved`,mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status===`pending`?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??this.execute(this.state.variables)}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#r=P({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(Error(`No mutationFn found`)),onFail:(e,t)=>{this.#i({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#i({type:`pause`})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});let r=this.state.status===`pending`,i=!this.#r.canStart();try{if(r)t();else{this.#i({type:`pending`,variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);let t=await this.options.onMutate?.(e,n);t!==this.state.context&&this.#i({type:`pending`,context:t,variables:e,isPaused:i})}let a=await this.#r.start();return await this.#n.config.onSuccess?.(a,e,this.state.context,this,n),await this.options.onSuccess?.(a,e,this.state.context,n),await this.#n.config.onSettled?.(a,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(a,null,e,this.state.context,n),this.#i({type:`success`,data:a}),a}catch(t){try{await this.#n.config.onError?.(t,e,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,n)}catch(e){Promise.reject(e)}try{await this.#n.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,n)}catch(e){Promise.reject(e)}throw this.#i({type:`error`,error:t}),t}finally{this.#n.runNext(this)}}#i(e){this.state=(t=>{switch(e.type){case`failed`:return{...t,failureCount:e.failureCount,failureReason:e.error};case`pause`:return{...t,isPaused:!0};case`continue`:return{...t,isPaused:!1};case`pending`:return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:`pending`,variables:e.variables,submittedAt:Date.now()};case`success`:return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:!1};case`error`:return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:`error`}}})(this.state),N.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function Oe(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var z=class extends l{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){let r=new De({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);let t=ke(e);if(typeof t==`string`){let n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:`added`,mutation:e})}remove(e){if(this.#e.delete(e)){let t=ke(e);if(typeof t==`string`){let n=this.#t.get(t);if(n)if(n.length>1){let t=n.indexOf(e);t!==-1&&n.splice(t,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:`removed`,mutation:e})}canRun(e){let t=ke(e);if(typeof t==`string`){let n=this.#t.get(t)?.find(e=>e.state.status===`pending`);return!n||n===e}else return!0}runNext(e){let t=ke(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){N.batch(()=>{this.#e.forEach(e=>{this.notify({type:`removed`,mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>ee(t,e))}findAll(e={}){return this.getAll().filter(t=>ee(e,t))}notify(e){N.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return N.batch(()=>Promise.all(e.map(e=>e.continue().catch(m))))}};function ke(e){return e.options.scope?.id}var Ae=class extends l{#e;#t=void 0;#n;#r;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let t=this.options;this.options=this.#e.defaultMutationOptions(e),T(this.options,t)||this.#e.getMutationCache().notify({type:`observerOptionsUpdated`,mutation:this.#n,observer:this}),t?.mutationKey&&this.options.mutationKey&&S(t.mutationKey)!==S(this.options.mutationKey)?this.reset():this.#n?.state.status===`pending`&&this.#n.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#a(e)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#i(),this.#a()}mutate(e,t){return this.#r=t,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(e)}#i(){let e=this.#n?.state??Oe();this.#t={...e,isPending:e.status===`pending`,isSuccess:e.status===`success`,isError:e.status===`error`,isIdle:e.status===`idle`,mutate:this.mutate,reset:this.reset}}#a(e){N.batch(()=>{if(this.#r&&this.hasListeners()){let t=this.#t.variables,n=this.#t.context,r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type===`success`){try{this.#r.onSuccess?.(e.data,t,n,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(e.data,null,t,n,r)}catch(e){Promise.reject(e)}}else if(e?.type===`error`){try{this.#r.onError?.(e.error,t,n,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(void 0,e.error,t,n,r)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}},je=class extends l{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){let r=t.queryKey,i=t.queryHash??x(r,t),a=this.get(i);return a||(a=new he({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:`added`,query:e}))}remove(e){let t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){N.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>b(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>b(e,t)):t}notify(e){N.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){N.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){N.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Me=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new je,this.#t=e.mutationCache||new z,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=oe.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=ue.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:`fetching`}).length}isMutating(e){return this.#t.findAll({...e,status:`pending`}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(v(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(r.queryHash)?.state.data,a=h(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return N.batch(()=>this.#e.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;N.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return N.batch(()=>(n.findAll(e).forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=N.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(m).catch(m)}invalidateQueries(e,t={}){return N.batch(()=>(this.#e.findAll(e).forEach(e=>{e.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=N.batch(()=>this.#e.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(m)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(m)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(v(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(m).catch(m)}fetchInfiniteQuery(e){return e.behavior=R(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(m).catch(m)}ensureInfiniteQueryData(e){return e.behavior=R(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return ue.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(S(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{C(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(S(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{C(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||=x(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===A&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},B=c(t(),1),V=i(),Ne=B.createContext(void 0),H=e=>{let t=B.useContext(Ne);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},Pe=({client:e,children:t})=>(B.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,V.jsx)(Ne.Provider,{value:e,children:t})),Fe=B.createContext(!1),Ie=()=>B.useContext(Fe);Fe.Provider;function Le(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Re=B.createContext(Le()),ze=()=>B.useContext(Re),Be=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?M(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Ve=e=>{B.useEffect(()=>{e.clearReset()},[e])},He=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||M(n,[e.error,r])),Ue=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},We=(e,t)=>e.isLoading&&e.isFetching&&!t,Ge=(e,t)=>e?.suspense&&t.isPending,Ke=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function qe(e,t,n){let r=Ie(),i=ze(),a=H(n),o=a.defaultQueryOptions(e);a.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let s=a.getQueryCache().get(o.queryHash);o._optimisticResults=r?`isRestoring`:`optimistic`,Ue(o),Be(o,i,s),Ve(i);let c=!a.getQueryCache().get(o.queryHash),[l]=B.useState(()=>new t(a,o)),u=l.getOptimisticResult(o),d=!r&&e.subscribed!==!1;if(B.useSyncExternalStore(B.useCallback(e=>{let t=d?l.subscribe(N.batchCalls(e)):m;return l.updateResult(),t},[l,d]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),B.useEffect(()=>{l.setOptions(o)},[o,l]),Ge(o,u))throw Ke(o,l,i);if(He({result:u,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw u.error;return a.getDefaultOptions().queries?._experimental_afterQuery?.(o,u),o.experimental_prefetchInRender&&!p&&We(u,r)&&(c?Ke(o,l,i):s?.promise)?.catch(m).finally(()=>{l.updateResult()}),o.notifyOnChangeProps?u:l.trackResult(u)}function Je(e,t){return qe(e,_e,t)}function Ye(e,t){let n=H(t),[r]=B.useState(()=>new Ae(n,e));B.useEffect(()=>{r.setOptions(e)},[r,e]);let i=B.useSyncExternalStore(B.useCallback(e=>r.subscribe(N.batchCalls(e)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=B.useCallback((e,t)=>{r.mutate(e,t).catch(m)},[r]);if(i.error&&M(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}var Xe=c(n(),1),Ze=e=>{switch(e){case`success`:return et;case`info`:return nt;case`warning`:return tt;case`error`:return rt;default:return null}},Qe=Array(12).fill(0),$e=({visible:e,className:t})=>B.createElement(`div`,{className:[`sonner-loading-wrapper`,t].filter(Boolean).join(` `),"data-visible":e},B.createElement(`div`,{className:`sonner-spinner`},Qe.map((e,t)=>B.createElement(`div`,{className:`sonner-loading-bar`,key:`spinner-bar-${t}`})))),et=B.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},B.createElement(`path`,{fillRule:`evenodd`,d:`M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z`,clipRule:`evenodd`})),tt=B.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 24 24`,fill:`currentColor`,height:`20`,width:`20`},B.createElement(`path`,{fillRule:`evenodd`,d:`M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z`,clipRule:`evenodd`})),nt=B.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},B.createElement(`path`,{fillRule:`evenodd`,d:`M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z`,clipRule:`evenodd`})),rt=B.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},B.createElement(`path`,{fillRule:`evenodd`,d:`M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z`,clipRule:`evenodd`})),it=B.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`},B.createElement(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),B.createElement(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})),at=()=>{let[e,t]=B.useState(document.hidden);return B.useEffect(()=>{let e=()=>{t(document.hidden)};return document.addEventListener(`visibilitychange`,e),()=>window.removeEventListener(`visibilitychange`,e)},[]),e},ot=1,U=new class{constructor(){this.subscribe=e=>(this.subscribers.push(e),()=>{let t=this.subscribers.indexOf(e);this.subscribers.splice(t,1)}),this.publish=e=>{this.subscribers.forEach(t=>t(e))},this.addToast=e=>{this.publish(e),this.toasts=[...this.toasts,e]},this.create=e=>{let{message:t,...n}=e,r=typeof e?.id==`number`||e.id?.length>0?e.id:ot++,i=this.toasts.find(e=>e.id===r),a=e.dismissible===void 0?!0:e.dismissible;return this.dismissedToasts.has(r)&&this.dismissedToasts.delete(r),i?this.toasts=this.toasts.map(n=>n.id===r?(this.publish({...n,...e,id:r,title:t}),{...n,...e,id:r,dismissible:a,title:t}):n):this.addToast({title:t,...n,dismissible:a,id:r}),r},this.dismiss=e=>(this.dismissedToasts.add(e),e||this.toasts.forEach(e=>{this.subscribers.forEach(t=>t({id:e.id,dismiss:!0}))}),this.subscribers.forEach(t=>t({id:e,dismiss:!0})),e),this.message=(e,t)=>this.create({...t,message:e}),this.error=(e,t)=>this.create({...t,message:e,type:`error`}),this.success=(e,t)=>this.create({...t,type:`success`,message:e}),this.info=(e,t)=>this.create({...t,type:`info`,message:e}),this.warning=(e,t)=>this.create({...t,type:`warning`,message:e}),this.loading=(e,t)=>this.create({...t,type:`loading`,message:e}),this.promise=(e,t)=>{if(!t)return;let n;t.loading!==void 0&&(n=this.create({...t,promise:e,type:`loading`,message:t.loading,description:typeof t.description==`function`?void 0:t.description}));let r=e instanceof Promise?e:e(),i=n!==void 0,a,o=r.then(async e=>{if(a=[`resolve`,e],B.isValidElement(e))i=!1,this.create({id:n,type:`default`,message:e});else if(ct(e)&&!e.ok){i=!1;let r=typeof t.error==`function`?await t.error(`HTTP error! status: ${e.status}`):t.error,a=typeof t.description==`function`?await t.description(`HTTP error! status: ${e.status}`):t.description;this.create({id:n,type:`error`,message:r,description:a})}else if(t.success!==void 0){i=!1;let r=typeof t.success==`function`?await t.success(e):t.success,a=typeof t.description==`function`?await t.description(e):t.description;this.create({id:n,type:`success`,message:r,description:a})}}).catch(async e=>{if(a=[`reject`,e],t.error!==void 0){i=!1;let r=typeof t.error==`function`?await t.error(e):t.error,a=typeof t.description==`function`?await t.description(e):t.description;this.create({id:n,type:`error`,message:r,description:a})}}).finally(()=>{var e;i&&(this.dismiss(n),n=void 0),(e=t.finally)==null||e.call(t)}),s=()=>new Promise((e,t)=>o.then(()=>a[0]===`reject`?t(a[1]):e(a[1])).catch(t));return typeof n!=`string`&&typeof n!=`number`?{unwrap:s}:Object.assign(n,{unwrap:s})},this.custom=(e,t)=>{let n=t?.id||ot++;return this.create({jsx:e(n),id:n,...t}),n},this.getActiveToasts=()=>this.toasts.filter(e=>!this.dismissedToasts.has(e.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},st=(e,t)=>{let n=t?.id||ot++;return U.addToast({title:e,...t,id:n}),n},ct=e=>e&&typeof e==`object`&&`ok`in e&&typeof e.ok==`boolean`&&`status`in e&&typeof e.status==`number`,W=Object.assign(st,{success:U.success,info:U.info,warning:U.warning,error:U.error,custom:U.custom,message:U.message,promise:U.promise,dismiss:U.dismiss,loading:U.loading},{getHistory:()=>U.toasts,getToasts:()=>U.getActiveToasts()});function lt(e,{insertAt:t}={}){if(!e||typeof document>`u`)return;let n=document.head||document.getElementsByTagName(`head`)[0],r=document.createElement(`style`);r.type=`text/css`,t===`top`&&n.firstChild?n.insertBefore(r,n.firstChild):n.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}lt(`:where(html[dir="ltr"]),:where([data-sonner-toaster][dir="ltr"]){--toast-icon-margin-start: -3px;--toast-icon-margin-end: 4px;--toast-svg-margin-start: -1px;--toast-svg-margin-end: 0px;--toast-button-margin-start: auto;--toast-button-margin-end: 0;--toast-close-button-start: 0;--toast-close-button-end: unset;--toast-close-button-transform: translate(-35%, -35%)}:where(html[dir="rtl"]),:where([data-sonner-toaster][dir="rtl"]){--toast-icon-margin-start: 4px;--toast-icon-margin-end: -3px;--toast-svg-margin-start: 0px;--toast-svg-margin-end: -1px;--toast-button-margin-start: 0;--toast-button-margin-end: auto;--toast-close-button-start: unset;--toast-close-button-end: 0;--toast-close-button-transform: translate(35%, -35%)}:where([data-sonner-toaster]){position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1: hsl(0, 0%, 99%);--gray2: hsl(0, 0%, 97.3%);--gray3: hsl(0, 0%, 95.1%);--gray4: hsl(0, 0%, 93%);--gray5: hsl(0, 0%, 90.9%);--gray6: hsl(0, 0%, 88.7%);--gray7: hsl(0, 0%, 85.8%);--gray8: hsl(0, 0%, 78%);--gray9: hsl(0, 0%, 56.1%);--gray10: hsl(0, 0%, 52.3%);--gray11: hsl(0, 0%, 43.5%);--gray12: hsl(0, 0%, 9%);--border-radius: 8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:none;z-index:999999999;transition:transform .4s ease}:where([data-sonner-toaster][data-lifted="true"]){transform:translateY(-10px)}@media (hover: none) and (pointer: coarse){:where([data-sonner-toaster][data-lifted="true"]){transform:none}}:where([data-sonner-toaster][data-x-position="right"]){right:var(--offset-right)}:where([data-sonner-toaster][data-x-position="left"]){left:var(--offset-left)}:where([data-sonner-toaster][data-x-position="center"]){left:50%;transform:translate(-50%)}:where([data-sonner-toaster][data-y-position="top"]){top:var(--offset-top)}:where([data-sonner-toaster][data-y-position="bottom"]){bottom:var(--offset-bottom)}:where([data-sonner-toast]){--y: translateY(100%);--lift-amount: calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);filter:blur(0);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:none;overflow-wrap:anywhere}:where([data-sonner-toast][data-styled="true"]){padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px #0000001a;width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}:where([data-sonner-toast]:focus-visible){box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast][data-y-position="top"]){top:0;--y: translateY(-100%);--lift: 1;--lift-amount: calc(1 * var(--gap))}:where([data-sonner-toast][data-y-position="bottom"]){bottom:0;--y: translateY(100%);--lift: -1;--lift-amount: calc(var(--lift) * var(--gap))}:where([data-sonner-toast]) :where([data-description]){font-weight:400;line-height:1.4;color:inherit}:where([data-sonner-toast]) :where([data-title]){font-weight:500;line-height:1.5;color:inherit}:where([data-sonner-toast]) :where([data-icon]){display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}:where([data-sonner-toast][data-promise="true"]) :where([data-icon])>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}:where([data-sonner-toast]) :where([data-icon])>*{flex-shrink:0}:where([data-sonner-toast]) :where([data-icon]) svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}:where([data-sonner-toast]) :where([data-content]){display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;cursor:pointer;outline:none;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}:where([data-sonner-toast]) :where([data-button]):focus-visible{box-shadow:0 0 0 2px #0006}:where([data-sonner-toast]) :where([data-button]):first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}:where([data-sonner-toast]) :where([data-cancel]){color:var(--normal-text);background:rgba(0,0,0,.08)}:where([data-sonner-toast][data-theme="dark"]) :where([data-cancel]){background:rgba(255,255,255,.3)}:where([data-sonner-toast]) :where([data-close-button]){position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast] [data-close-button]{background:var(--gray1)}:where([data-sonner-toast]) :where([data-close-button]):focus-visible{box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast]) :where([data-disabled="true"]){cursor:not-allowed}:where([data-sonner-toast]):hover :where([data-close-button]):hover{background:var(--gray2);border-color:var(--gray5)}:where([data-sonner-toast][data-swiping="true"]):before{content:"";position:absolute;left:-50%;right:-50%;height:100%;z-index:-1}:where([data-sonner-toast][data-y-position="top"][data-swiping="true"]):before{bottom:50%;transform:scaleY(3) translateY(50%)}:where([data-sonner-toast][data-y-position="bottom"][data-swiping="true"]):before{top:50%;transform:scaleY(3) translateY(-50%)}:where([data-sonner-toast][data-swiping="false"][data-removed="true"]):before{content:"";position:absolute;inset:0;transform:scaleY(2)}:where([data-sonner-toast]):after{content:"";position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}:where([data-sonner-toast][data-mounted="true"]){--y: translateY(0);opacity:1}:where([data-sonner-toast][data-expanded="false"][data-front="false"]){--scale: var(--toasts-before) * .05 + 1;--y: translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}:where([data-sonner-toast])>*{transition:opacity .4s}:where([data-sonner-toast][data-expanded="false"][data-front="false"][data-styled="true"])>*{opacity:0}:where([data-sonner-toast][data-visible="false"]){opacity:0;pointer-events:none}:where([data-sonner-toast][data-mounted="true"][data-expanded="true"]){--y: translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}:where([data-sonner-toast][data-removed="true"][data-front="true"][data-swipe-out="false"]){--y: translateY(calc(var(--lift) * -100%));opacity:0}:where([data-sonner-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="true"]){--y: translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}:where([data-sonner-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="false"]){--y: translateY(40%);opacity:0;transition:transform .5s,opacity .2s}:where([data-sonner-toast][data-removed="true"][data-front="false"]):before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y, 0px)) translate(var(--swipe-amount-x, 0px));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{0%{transform:var(--y) translate(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translate(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{0%{transform:var(--y) translate(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translate(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{0%{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{0%{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width: 600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-theme=light]{--normal-bg: #fff;--normal-border: var(--gray4);--normal-text: var(--gray12);--success-bg: hsl(143, 85%, 96%);--success-border: hsl(145, 92%, 91%);--success-text: hsl(140, 100%, 27%);--info-bg: hsl(208, 100%, 97%);--info-border: hsl(221, 91%, 91%);--info-text: hsl(210, 92%, 45%);--warning-bg: hsl(49, 100%, 97%);--warning-border: hsl(49, 91%, 91%);--warning-text: hsl(31, 92%, 45%);--error-bg: hsl(359, 100%, 97%);--error-border: hsl(359, 100%, 94%);--error-text: hsl(360, 100%, 45%)}[data-sonner-toaster][data-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg: #000;--normal-border: hsl(0, 0%, 20%);--normal-text: var(--gray1)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg: #fff;--normal-border: var(--gray3);--normal-text: var(--gray12)}[data-sonner-toaster][data-theme=dark]{--normal-bg: #000;--normal-bg-hover: hsl(0, 0%, 12%);--normal-border: hsl(0, 0%, 20%);--normal-border-hover: hsl(0, 0%, 25%);--normal-text: var(--gray1);--success-bg: hsl(150, 100%, 6%);--success-border: hsl(147, 100%, 12%);--success-text: hsl(150, 86%, 65%);--info-bg: hsl(215, 100%, 6%);--info-border: hsl(223, 100%, 12%);--info-text: hsl(216, 87%, 65%);--warning-bg: hsl(64, 100%, 6%);--warning-border: hsl(60, 100%, 12%);--warning-text: hsl(46, 87%, 65%);--error-bg: hsl(358, 76%, 10%);--error-border: hsl(357, 89%, 16%);--error-text: hsl(358, 100%, 81%)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success],[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info],[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning],[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error],[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size: 16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:nth-child(1){animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}to{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}to{opacity:.15}}@media (prefers-reduced-motion){[data-sonner-toast],[data-sonner-toast]>*,.sonner-loading-bar{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}
2
+ `);function ut(e){return e.label!==void 0}var dt=3,ft=`32px`,pt=`16px`,mt=4e3,ht=356,gt=14,_t=20,vt=200;function G(...e){return e.filter(Boolean).join(` `)}function yt(e){let[t,n]=e.split(`-`),r=[];return t&&r.push(t),n&&r.push(n),r}var bt=e=>{let{invert:t,toast:n,unstyled:r,interacting:i,setHeights:a,visibleToasts:o,heights:s,index:c,toasts:l,expanded:u,removeToast:d,defaultRichColors:f,closeButton:p,style:m,cancelButtonStyle:h,actionButtonStyle:g,className:_=``,descriptionClassName:v=``,duration:y,position:b,gap:ee,loadingIcon:x,expandByDefault:S,classNames:C,icons:w,closeButtonAriaLabel:te=`Close toast`,pauseWhenPageIsHidden:T}=e,[E,D]=B.useState(null),[ne,re]=B.useState(null),[O,k]=B.useState(!1),[ie,A]=B.useState(!1),[j,M]=B.useState(!1),[ae,oe]=B.useState(!1),[se,ce]=B.useState(!1),[le,N]=B.useState(0),[ue,de]=B.useState(0),fe=B.useRef(n.duration||y||mt),pe=B.useRef(null),P=B.useRef(null),me=c===0,he=c+1<=o,F=n.type,I=n.dismissible!==!1,ge=n.className||``,_e=n.descriptionClassName||``,ve=B.useMemo(()=>s.findIndex(e=>e.toastId===n.id)||0,[s,n.id]),ye=B.useMemo(()=>n.closeButton??p,[n.closeButton,p]),be=B.useMemo(()=>n.duration||y||mt,[n.duration,y]),xe=B.useRef(0),L=B.useRef(0),Se=B.useRef(0),R=B.useRef(null),[Ce,we]=b.split(`-`),Te=B.useMemo(()=>s.reduce((e,t,n)=>n>=ve?e:e+t.height,0),[s,ve]),Ee=at(),De=n.invert||t,Oe=F===`loading`;L.current=B.useMemo(()=>ve*ee+Te,[ve,Te]),B.useEffect(()=>{fe.current=be},[be]),B.useEffect(()=>{k(!0)},[]),B.useEffect(()=>{let e=P.current;if(e){let t=e.getBoundingClientRect().height;return de(t),a(e=>[{toastId:n.id,height:t,position:n.position},...e]),()=>a(e=>e.filter(e=>e.toastId!==n.id))}},[a,n.id]),B.useLayoutEffect(()=>{if(!O)return;let e=P.current,t=e.style.height;e.style.height=`auto`;let r=e.getBoundingClientRect().height;e.style.height=t,de(r),a(e=>e.find(e=>e.toastId===n.id)?e.map(e=>e.toastId===n.id?{...e,height:r}:e):[{toastId:n.id,height:r,position:n.position},...e])},[O,n.title,n.description,a,n.id]);let z=B.useCallback(()=>{A(!0),N(L.current),a(e=>e.filter(e=>e.toastId!==n.id)),setTimeout(()=>{d(n)},vt)},[n,d,a,L]);B.useEffect(()=>{if(n.promise&&F===`loading`||n.duration===1/0||n.type===`loading`)return;let e;return u||i||T&&Ee?(()=>{if(Se.current<xe.current){let e=new Date().getTime()-xe.current;fe.current-=e}Se.current=new Date().getTime()})():fe.current!==1/0&&(xe.current=new Date().getTime(),e=setTimeout(()=>{var e;(e=n.onAutoClose)==null||e.call(n,n),z()},fe.current)),()=>clearTimeout(e)},[u,i,n,F,T,Ee,z]),B.useEffect(()=>{n.delete&&z()},[z,n.delete]);function ke(){return w!=null&&w.loading?B.createElement(`div`,{className:G(C?.loader,n?.classNames?.loader,`sonner-loader`),"data-visible":F===`loading`},w.loading):x?B.createElement(`div`,{className:G(C?.loader,n?.classNames?.loader,`sonner-loader`),"data-visible":F===`loading`},x):B.createElement($e,{className:G(C?.loader,n?.classNames?.loader),visible:F===`loading`})}return B.createElement(`li`,{tabIndex:0,ref:P,className:G(_,ge,C?.toast,n?.classNames?.toast,C?.default,C?.[F],n?.classNames?.[F]),"data-sonner-toast":``,"data-rich-colors":n.richColors??f,"data-styled":!(n.jsx||n.unstyled||r),"data-mounted":O,"data-promise":!!n.promise,"data-swiped":se,"data-removed":ie,"data-visible":he,"data-y-position":Ce,"data-x-position":we,"data-index":c,"data-front":me,"data-swiping":j,"data-dismissible":I,"data-type":F,"data-invert":De,"data-swipe-out":ae,"data-swipe-direction":ne,"data-expanded":!!(u||S&&O),style:{"--index":c,"--toasts-before":c,"--z-index":l.length-c,"--offset":`${ie?le:L.current}px`,"--initial-height":S?`auto`:`${ue}px`,...m,...n.style},onDragEnd:()=>{M(!1),D(null),R.current=null},onPointerDown:e=>{Oe||!I||(pe.current=new Date,N(L.current),e.target.setPointerCapture(e.pointerId),e.target.tagName!==`BUTTON`&&(M(!0),R.current={x:e.clientX,y:e.clientY}))},onPointerUp:()=>{var e;if(ae||!I)return;R.current=null;let t=Number(P.current?.style.getPropertyValue(`--swipe-amount-x`).replace(`px`,``)||0),r=Number(P.current?.style.getPropertyValue(`--swipe-amount-y`).replace(`px`,``)||0),i=new Date().getTime()-pe.current?.getTime(),a=E===`x`?t:r,o=Math.abs(a)/i;if(Math.abs(a)>=_t||o>.11){N(L.current),(e=n.onDismiss)==null||e.call(n,n),re(E===`x`?t>0?`right`:`left`:r>0?`down`:`up`),z(),oe(!0),ce(!1);return}M(!1),D(null)},onPointerMove:t=>{var n,r;if(!R.current||!I||window.getSelection()?.toString().length>0)return;let i=t.clientY-R.current.y,a=t.clientX-R.current.x,o=e.swipeDirections??yt(b);!E&&(Math.abs(a)>1||Math.abs(i)>1)&&D(Math.abs(a)>Math.abs(i)?`x`:`y`);let s={x:0,y:0};E===`y`?(o.includes(`top`)||o.includes(`bottom`))&&(o.includes(`top`)&&i<0||o.includes(`bottom`)&&i>0)&&(s.y=i):E===`x`&&(o.includes(`left`)||o.includes(`right`))&&(o.includes(`left`)&&a<0||o.includes(`right`)&&a>0)&&(s.x=a),(Math.abs(s.x)>0||Math.abs(s.y)>0)&&ce(!0),(n=P.current)==null||n.style.setProperty(`--swipe-amount-x`,`${s.x}px`),(r=P.current)==null||r.style.setProperty(`--swipe-amount-y`,`${s.y}px`)}},ye&&!n.jsx?B.createElement(`button`,{"aria-label":te,"data-disabled":Oe,"data-close-button":!0,onClick:Oe||!I?()=>{}:()=>{var e;z(),(e=n.onDismiss)==null||e.call(n,n)},className:G(C?.closeButton,n?.classNames?.closeButton)},w?.close??it):null,n.jsx||(0,B.isValidElement)(n.title)?n.jsx?n.jsx:typeof n.title==`function`?n.title():n.title:B.createElement(B.Fragment,null,F||n.icon||n.promise?B.createElement(`div`,{"data-icon":``,className:G(C?.icon,n?.classNames?.icon)},n.promise||n.type===`loading`&&!n.icon?n.icon||ke():null,n.type===`loading`?null:n.icon||w?.[F]||Ze(F)):null,B.createElement(`div`,{"data-content":``,className:G(C?.content,n?.classNames?.content)},B.createElement(`div`,{"data-title":``,className:G(C?.title,n?.classNames?.title)},typeof n.title==`function`?n.title():n.title),n.description?B.createElement(`div`,{"data-description":``,className:G(v,_e,C?.description,n?.classNames?.description)},typeof n.description==`function`?n.description():n.description):null),(0,B.isValidElement)(n.cancel)?n.cancel:n.cancel&&ut(n.cancel)?B.createElement(`button`,{"data-button":!0,"data-cancel":!0,style:n.cancelButtonStyle||h,onClick:e=>{var t,r;ut(n.cancel)&&I&&((r=(t=n.cancel).onClick)==null||r.call(t,e),z())},className:G(C?.cancelButton,n?.classNames?.cancelButton)},n.cancel.label):null,(0,B.isValidElement)(n.action)?n.action:n.action&&ut(n.action)?B.createElement(`button`,{"data-button":!0,"data-action":!0,style:n.actionButtonStyle||g,onClick:e=>{var t,r;ut(n.action)&&((r=(t=n.action).onClick)==null||r.call(t,e),!e.defaultPrevented&&z())},className:G(C?.actionButton,n?.classNames?.actionButton)},n.action.label):null))};function xt(){if(typeof window>`u`||typeof document>`u`)return`ltr`;let e=document.documentElement.getAttribute(`dir`);return e===`auto`||!e?window.getComputedStyle(document.documentElement).direction:e}function St(e,t){let n={};return[e,t].forEach((e,t)=>{let r=t===1,i=r?`--mobile-offset`:`--offset`,a=r?pt:ft;function o(e){[`top`,`right`,`bottom`,`left`].forEach(t=>{n[`${i}-${t}`]=typeof e==`number`?`${e}px`:e})}typeof e==`number`||typeof e==`string`?o(e):typeof e==`object`?[`top`,`right`,`bottom`,`left`].forEach(t=>{e[t]===void 0?n[`${i}-${t}`]=a:n[`${i}-${t}`]=typeof e[t]==`number`?`${e[t]}px`:e[t]}):o(a)}),n}var Ct=(0,B.forwardRef)(function(e,t){let{invert:n,position:r=`bottom-right`,hotkey:i=[`altKey`,`KeyT`],expand:a,closeButton:o,className:s,offset:c,mobileOffset:l,theme:u=`light`,richColors:d,duration:f,style:p,visibleToasts:m=dt,toastOptions:h,dir:g=xt(),gap:_=gt,loadingIcon:v,icons:y,containerAriaLabel:b=`Notifications`,pauseWhenPageIsHidden:ee}=e,[x,S]=B.useState([]),C=B.useMemo(()=>Array.from(new Set([r].concat(x.filter(e=>e.position).map(e=>e.position)))),[x,r]),[w,te]=B.useState([]),[T,E]=B.useState(!1),[D,ne]=B.useState(!1),[re,O]=B.useState(u===`system`?typeof window<`u`&&window.matchMedia&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`:u),k=B.useRef(null),ie=i.join(`+`).replace(/Key/g,``).replace(/Digit/g,``),A=B.useRef(null),j=B.useRef(!1),M=B.useCallback(e=>{S(t=>{var n;return(n=t.find(t=>t.id===e.id))!=null&&n.delete||U.dismiss(e.id),t.filter(({id:t})=>t!==e.id)})},[]);return B.useEffect(()=>U.subscribe(e=>{if(e.dismiss){S(t=>t.map(t=>t.id===e.id?{...t,delete:!0}:t));return}setTimeout(()=>{Xe.flushSync(()=>{S(t=>{let n=t.findIndex(t=>t.id===e.id);return n===-1?[e,...t]:[...t.slice(0,n),{...t[n],...e},...t.slice(n+1)]})})})}),[]),B.useEffect(()=>{if(u!==`system`){O(u);return}if(u===`system`&&(window.matchMedia&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?O(`dark`):O(`light`)),typeof window>`u`)return;let e=window.matchMedia(`(prefers-color-scheme: dark)`);try{e.addEventListener(`change`,({matches:e})=>{O(e?`dark`:`light`)})}catch{e.addListener(({matches:e})=>{try{O(e?`dark`:`light`)}catch(e){console.error(e)}})}},[u]),B.useEffect(()=>{x.length<=1&&E(!1)},[x]),B.useEffect(()=>{let e=e=>{var t,n;i.every(t=>e[t]||e.code===t)&&(E(!0),(t=k.current)==null||t.focus()),e.code===`Escape`&&(document.activeElement===k.current||(n=k.current)!=null&&n.contains(document.activeElement))&&E(!1)};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[i]),B.useEffect(()=>{if(k.current)return()=>{A.current&&(A.current.focus({preventScroll:!0}),A.current=null,j.current=!1)}},[k.current]),B.createElement(`section`,{ref:t,"aria-label":`${b} ${ie}`,tabIndex:-1,"aria-live":`polite`,"aria-relevant":`additions text`,"aria-atomic":`false`,suppressHydrationWarning:!0},C.map((t,r)=>{let[i,u]=t.split(`-`);return x.length?B.createElement(`ol`,{key:t,dir:g===`auto`?xt():g,tabIndex:-1,ref:k,className:s,"data-sonner-toaster":!0,"data-theme":re,"data-y-position":i,"data-lifted":T&&x.length>1&&!a,"data-x-position":u,style:{"--front-toast-height":`${w[0]?.height||0}px`,"--width":`${ht}px`,"--gap":`${_}px`,...p,...St(c,l)},onBlur:e=>{j.current&&!e.currentTarget.contains(e.relatedTarget)&&(j.current=!1,A.current&&=(A.current.focus({preventScroll:!0}),null))},onFocus:e=>{e.target instanceof HTMLElement&&e.target.dataset.dismissible===`false`||j.current||(j.current=!0,A.current=e.relatedTarget)},onMouseEnter:()=>E(!0),onMouseMove:()=>E(!0),onMouseLeave:()=>{D||E(!1)},onDragEnd:()=>E(!1),onPointerDown:e=>{e.target instanceof HTMLElement&&e.target.dataset.dismissible===`false`||ne(!0)},onPointerUp:()=>ne(!1)},x.filter(e=>!e.position&&r===0||e.position===t).map((r,i)=>B.createElement(bt,{key:r.id,icons:y,index:i,toast:r,defaultRichColors:d,duration:h?.duration??f,className:h?.className,descriptionClassName:h?.descriptionClassName,invert:n,visibleToasts:m,closeButton:h?.closeButton??o,interacting:D,position:t,style:h?.style,unstyled:h?.unstyled,classNames:h?.classNames,cancelButtonStyle:h?.cancelButtonStyle,actionButtonStyle:h?.actionButtonStyle,removeToast:M,toasts:x.filter(e=>e.position==r.position),heights:w.filter(e=>e.position==r.position),setHeights:te,expandByDefault:a,gap:_,loadingIcon:v,expanded:T,pauseWhenPageIsHidden:ee,swipeDirections:e.swipeDirections}))):null}))}),wt=new Me({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!0}}}),Tt=e=>typeof e==`boolean`?`${e}`:e===0?`0`:e,Et=a,Dt=(e,t)=>n=>{if(t?.variants==null)return Et(e,n?.class,n?.className);let{variants:r,defaultVariants:i}=t,a=Object.keys(r).map(e=>{let t=n?.[e],a=i?.[e];if(t===null)return null;let o=Tt(t)||Tt(a);return r[e][o]}),o=n&&Object.entries(n).reduce((e,t)=>{let[n,r]=t;return r===void 0||(e[n]=r),e},{});return Et(e,a,t?.compoundVariants?.reduce((e,t)=>{let{class:n,className:r,...a}=t;return Object.entries(a).every(e=>{let[t,n]=e;return Array.isArray(n)?n.includes({...i,...o}[t]):{...i,...o}[t]===n})?[...e,n,r]:e},[]),n?.class,n?.className)},Ot=Dt(`inline-flex items-center justify-center whitespace-nowrap rounded-full text-sm font-medium ring-offset-background transition-colors duration-fast focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50`,{variants:{variant:{default:`bg-primary text-primary-foreground hover:bg-primary-600 active:bg-primary-700 shadow-sm`,destructive:`bg-destructive text-destructive-foreground hover:bg-destructive/90`,outline:`border border-gray-200 bg-white hover:bg-gray-50 hover:text-gray-800 text-gray-600`,secondary:`bg-gray-100 text-gray-700 hover:bg-gray-200/80`,ghost:`hover:bg-gray-100/80 hover:text-gray-800`,link:`text-primary underline-offset-4 hover:underline`,primary:`bg-primary text-primary-foreground hover:bg-primary-600 active:bg-primary-700 shadow-sm`,subtle:`bg-gray-100 text-gray-600 hover:bg-gray-200/80`,"primary-outline":`border border-primary/30 text-primary hover:bg-primary hover:text-primary-foreground`},size:{default:`h-9 px-4 py-2`,sm:`h-8 px-3 text-xs`,lg:`h-11 px-5 text-[14px]`,xl:`h-12 px-6 text-[15px]`,icon:`h-9 w-9`}},defaultVariants:{variant:`default`,size:`default`}}),kt=B.forwardRef(({className:t,variant:n,size:r,...i},a)=>(0,V.jsx)(`button`,{className:e(Ot({variant:n,size:r,className:t})),ref:a,...i}));kt.displayName=`Button`;var K=B.forwardRef(({className:t,type:n,...r},i)=>(0,V.jsx)(`input`,{type:n,className:e(`flex h-9 w-full rounded-xl border border-gray-200/80 bg-white px-3.5 py-2 text-sm text-gray-900 file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-gray-300 placeholder:font-normal focus:outline-none focus:ring-1 focus:ring-primary/40 focus:border-primary/40 transition-colors disabled:cursor-not-allowed disabled:opacity-50`,t),ref:i,...r}));K.displayName=`Input`;var At=B.forwardRef(({className:t,...n},r)=>(0,V.jsx)(`label`,{ref:r,className:e(`text-sm font-medium leading-none text-gray-700 peer-disabled:cursor-not-allowed peer-disabled:opacity-70`,t),...n}));At.displayName=`Label`;function jt({children:t,fullHeight:n=!1,className:r}){return(0,V.jsx)(`div`,{className:e(`animate-fade-in`,n?`h-[calc(100vh-80px)] w-full flex flex-col`:`pb-16`,r),children:t})}function Mt({title:t,description:n,actions:r,className:i}){return(0,V.jsxs)(`div`,{className:e(`flex items-center justify-between mb-6 shrink-0`,i),children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`h2`,{className:`text-xl font-semibold text-gray-900`,children:t}),n&&(0,V.jsx)(`p`,{className:`text-sm text-gray-500 mt-1`,children:n})]}),r&&(0,V.jsx)(`div`,{className:`flex items-center gap-2 shrink-0`,children:r})]})}var Nt=B.forwardRef(({className:t,hover:n=!0,...r},i)=>(0,V.jsx)(`div`,{ref:i,className:e(`rounded-2xl border border-gray-200/50 bg-white text-card-foreground shadow-card transition-all duration-base`,n&&`hover:shadow-card-hover hover:border-gray-200`,t),...r}));Nt.displayName=`Card`;var Pt=B.forwardRef(({className:t,...n},r)=>(0,V.jsx)(`div`,{ref:r,className:e(`flex flex-col space-y-1.5 p-6`,t),...n}));Pt.displayName=`CardHeader`;var Ft=B.forwardRef(({className:t,...n},r)=>(0,V.jsx)(`h3`,{ref:r,className:e(`text-[15px] font-semibold leading-tight tracking-tight text-gray-900`,t),...n}));Ft.displayName=`CardTitle`;var It=B.forwardRef(({className:t,...n},r)=>(0,V.jsx)(`p`,{ref:r,className:e(`text-[13px] text-gray-400 leading-relaxed`,t),...n}));It.displayName=`CardDescription`;var Lt=B.forwardRef(({className:t,...n},r)=>(0,V.jsx)(`div`,{ref:r,className:e(`p-6 pt-0`,t),...n}));Lt.displayName=`CardContent`;var Rt=B.forwardRef(({className:t,...n},r)=>(0,V.jsx)(`div`,{ref:r,className:e(`flex items-center justify-between p-6 pt-0`,t),...n}));Rt.displayName=`CardFooter`;function q(e){let t=e.trim();if(!t)throw Error(`typed key id is required`);return{id:t}}function zt(e){return typeof e==`string`?e.trim():e.id}var Bt=class{listeners=new Map;globalListeners=new Set;listenerCount=0;onFirstSubscriber;onListenerError;onNoSubscribers;constructor(e={}){this.onFirstSubscriber=e.onFirstSubscriber,this.onListenerError=e.onListenerError,this.onNoSubscribers=e.onNoSubscribers}emit=(e,t,n={})=>{let r={type:zt(e),payload:t,...n.emittedAt?{emittedAt:n.emittedAt}:{},...n.source?{source:n.source}:{}};this.emitEnvelope(r)};emitEnvelope=e=>{let t=this.listeners.get(e.type);if(t)for(let n of t)this.safeInvokeListener(e,n);if(this.globalListeners.size!==0)for(let t of this.globalListeners)this.safeInvokeGlobalListener(e,t)};on=(e,t)=>{let n=zt(e),r=this.listeners.get(n)??new Set,i=t,a=!r.has(i);return r.add(i),this.listeners.set(n,r),a&&this.registerSubscriber(),()=>{this.off(e,t)}};off=(e,t)=>{let n=zt(e),r=this.listeners.get(n);if(!r)return;let i=r.delete(t);r.size===0&&this.listeners.delete(n),i&&this.unregisterSubscriber()};once=(e,t)=>{let n=this.on(e,(e,r)=>{n(),t(e,r)});return n};subscribeAll=e=>{let t=!this.globalListeners.has(e);return this.globalListeners.add(e),t&&this.registerSubscriber(),()=>{this.globalListeners.delete(e)&&this.unregisterSubscriber()}};registerSubscriber=()=>{this.listenerCount+=1,this.listenerCount===1&&this.onFirstSubscriber?.()};unregisterSubscriber=()=>{this.listenerCount=Math.max(0,this.listenerCount-1),this.listenerCount===0&&this.onNoSubscribers?.()};safeInvokeListener=(e,t)=>{try{t(e.payload,e)}catch(t){this.onListenerError?.({type:e.type,payload:e.payload,error:t})}};safeInvokeGlobalListener=(e,t)=>{try{t(e)}catch(t){this.onListenerError?.({type:e.type,payload:e.payload,error:t})}}};function J(e){return q(e)}var Vt={configUpdated:J(`config.updated`),channelConfigApplyStatus:J(`channel.config.apply-status`),sessionUpdated:J(`session.updated`),sessionRunStatus:J(`session.run-status`),sessionMetadataChanged:J(`session.metadata.changed`),ncpEvent:J(`ncp.event`),sessionSummaryUpsert:J(`session.summary.upsert`),sessionSummaryDelete:J(`session.summary.delete`),configReloadStarted:J(`config.reload.started`),configReloadFinished:J(`config.reload.finished`),error:J(`error`),connectionOpen:J(`connection.open`),connectionClose:J(`connection.close`),connectionError:J(`connection.error`),runtimeUpdateSnapshot:J(`runtime.update.snapshot`)};q(`extension.channel.config.get`),q(`extension.channel.message.submit`),q(`extension.channel.command.list`),q(`extension.channel.command.execute`),q(`extension.response`),q(`agent-run.send`),q(`agent-run.abort`),q(`agent-run.session-message.request`);function Ht(e){let t=e.trim().replace(/\/+$/,``);if(!t)throw Error(`NextClaw client baseUrl is required.`);return t}function Ut(e,t){return`${Ht(e)}${t.startsWith(`/`)?t:`/${t}`}`}function Wt(e,t){if(!t)return e;let n=typeof t==`string`?t:t.toString();return n?`${e}${e.includes(`?`)?`&`:`?`}${n}`:e}function Gt(e,t){let n=new URL(Ut(e,t));return n.protocol===`https:`?n.protocol=`wss:`:n.protocol===`http:`&&(n.protocol=`ws:`),n.toString()}function Kt(e){let t=e??globalThis.fetch;if(typeof t!=`function`)throw Error(`NextClaw fetch transport is not available in this environment.`);return((e,n)=>t.call(globalThis,e,n))}function qt(e){let t=e.split(/\r?\n/),n=`message`,r=[];for(let e of t){if(e.startsWith(`event:`)){n=e.slice(6).trim();continue}e.startsWith(`data:`)&&r.push(e.slice(5).trimStart())}return r.length===0?null:{event:n,data:r.join(`
3
+ `)}}function Jt(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&`type`in t?t:null}catch{return null}}var Yt=class{baseUrl;defaultHeaders;fetchImpl;transport;constructor(e,t){this.requestService=e;let{baseUrl:n,fetchImpl:r,headers:i,token:a,transport:o}=t;this.baseUrl=n,this.fetchImpl=Kt(r),this.transport=o,this.defaultHeaders={Accept:`application/json`,...i??{},...a?{Authorization:`Bearer ${a}`}:{}}}send=async e=>await this.requestService.post(`/api/agent-runs/send`,e);abort=async e=>await this.requestService.post(`/api/agent-runs/abort`,e);stream=(e,t,n={})=>{if(this.transport)throw Error(`Agent run streaming requires the HTTP fetch transport.`);let r=new AbortController,i=()=>r.abort(n.signal?.reason);return n.signal?.addEventListener(`abort`,i,{once:!0}),this.consumeStream(e,t,r.signal,n.onError).finally(()=>{n.signal?.removeEventListener(`abort`,i)}),{close:()=>{r.abort(),n.signal?.removeEventListener(`abort`,i)}}};consumeStream=async(e,t,n,r)=>{try{let r=new URL(Ut(this.baseUrl,`/api/agent-runs/stream`));r.searchParams.set(`sessionId`,e.sessionId);let i=await this.fetchImpl(r.toString(),{method:`GET`,headers:{...this.defaultHeaders,Accept:`text/event-stream`},signal:n});if(!i.ok)throw Error(`Agent run stream failed with HTTP ${i.status}.`);if(!i.body)throw Error(`Agent run stream response has no body.`);await this.readEventStream(i.body,t,n)}catch(e){if(n.aborted)return;r?.(e)}};readEventStream=async(e,t,n)=>{let r=e.getReader(),i=new TextDecoder,a=``;try{for(;!n.aborted;){let{done:e,value:n}=await r.read();if(e)break;a+=i.decode(n,{stream:!0}),a=this.drainFrames(a,t)}a+=i.decode(),this.drainFrames(`${a}\n\n`,t)}finally{r.releaseLock()}};drainFrames=(e,t)=>{let n=e.replaceAll(`\r
4
4
  `,`
5
5
  `).split(`
6
6
 
7
- `),r=n.pop()??``;for(let e of n){let n=Kt(e);if(n?.event!==`ncp-event`)continue;let r=qt(n.data);r&&t(r)}return r}},Yt=class{constructor(e,t){this.requestService=e,this.baseUrl=t}list=async()=>(await this.requestService.get(`/api/agents`)).agents;create=async e=>await this.requestService.post(`/api/agents`,e);update=async(e,t)=>await this.requestService.put(`/api/agents/${encodeURIComponent(e)}`,t);delete=async e=>await this.requestService.delete(`/api/agents/${encodeURIComponent(e)}`);resolveAvatarUrl=e=>Ut(this.baseUrl,`/api/agents/${encodeURIComponent(e)}/avatar`)},Xt=class{constructor(e){this.requestService=e}fetchMeta=async()=>await this.requestService.get(`/api/app/meta`);fetchBootstrapStatus=async(e={})=>await this.requestService.get(`/api/runtime/bootstrap-status`,e)},Zt=class{constructor(e){this.requestService=e}fetchStatus=async(e={})=>await this.requestService.get(`/api/auth/status`,{...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}});setup=async e=>await this.requestService.post(`/api/auth/setup`,e);login=async e=>await this.requestService.post(`/api/auth/login`,e);logout=async()=>await this.requestService.post(`/api/auth/logout`,{});updatePassword=async e=>await this.requestService.put(`/api/auth/password`,e);updateEnabled=async e=>await this.requestService.put(`/api/auth/enabled`,e)},Qt=class{constructor(e){this.requestService=e}start=async(e,t={})=>await this.requestService.post(`/api/config/channels/${encodeURIComponent(e)}/auth/start`,t);poll=async(e,t)=>await this.requestService.post(`/api/config/channels/${encodeURIComponent(e)}/auth/poll`,t);connect=async(e,t)=>await this.requestService.post(`/api/config/channels/${encodeURIComponent(e)}/auth/connect`,t)},$t=class{constructor(e){this.requestService=e}fetch=async()=>await this.requestService.get(`/api/config`);fetchMeta=async()=>await this.requestService.get(`/api/config/meta`);fetchSchema=async()=>await this.requestService.get(`/api/config/schema`);updateModel=async e=>await this.requestService.put(`/api/config/model`,e);updateSearch=async e=>await this.requestService.put(`/api/config/search`,e);updateChannel=async(e,t)=>await this.requestService.put(`/api/config/channels/${encodeURIComponent(e)}`,t);updateRuntime=async e=>await this.requestService.put(`/api/config/runtime`,e);updateSecrets=async e=>await this.requestService.put(`/api/config/secrets`,e);executeAction=async(e,t={})=>await this.requestService.post(`/api/config/actions/${encodeURIComponent(e)}/execute`,t);fetchChatSessionTypes=async()=>await this.requestService.get(`/api/ncp/session-types`);fetchCronJobs=async(e={})=>await this.requestService.get(`/api/cron`,{query:e.all?{all:`1`}:void 0});deleteCronJob=async e=>await this.requestService.delete(`/api/cron/${encodeURIComponent(e)}`);setCronJobEnabled=async(e,t)=>await this.requestService.put(`/api/cron/${encodeURIComponent(e)}/enable`,t);runCronJob=async(e,t={})=>await this.requestService.post(`/api/cron/${encodeURIComponent(e)}/run`,t)},en=class{constructor(e){this.requestService=e}fetchItems=async e=>await this.requestService.get(`${tn(e.type)}/items`,{query:nn(e)});fetchItem=async(e,t)=>await this.requestService.get(`${tn(t)}/items/${encodeURIComponent(e)}`);fetchSkillContent=async e=>await this.requestService.get(`/api/marketplace/skills/items/${encodeURIComponent(e)}/content`);fetchRecommendations=async(e,t={})=>await this.requestService.get(`${tn(e)}/recommendations`,{query:{...t.scene?.trim()?{scene:t.scene.trim()}:{},...typeof t.limit==`number`&&Number.isFinite(t.limit)?{limit:Math.max(1,Math.trunc(t.limit))}:{}}});fetchSkillScenes=async()=>await this.requestService.get(`/api/marketplace/skills/scenes`);install=async e=>await this.requestService.post(`${tn(rn(e.type))}/install`,e);fetchInstalled=async e=>await this.requestService.get(`${tn(e)}/installed`);manage=async e=>await this.requestService.post(`${tn(rn(e.type))}/manage`,e)};function tn(e){return e===`skill`?`/api/marketplace/skills`:`/api/marketplace/mcp`}function nn(e){let{page:t,pageSize:n,q:r,scene:i,sort:a,tag:o}=e,s={};return r?.trim()&&(s.q=r.trim()),o?.trim()&&(s.tag=o.trim()),i?.trim()&&(s.scene=i.trim()),a&&(s.sort=a),typeof t==`number`&&Number.isFinite(t)&&(s.page=Math.max(1,Math.trunc(t))),typeof n==`number`&&Number.isFinite(n)&&(s.pageSize=Math.max(1,Math.trunc(n))),Object.keys(s).length>0?s:void 0}function rn(e){if(!e)throw Error(`Marketplace request type is required.`);return e}var an=class{constructor(e){this.requestService=e}fetchItems=async(e={})=>await this.requestService.get(`/api/marketplace/mcp/items`,{query:on(e)});fetchInstalled=async()=>await this.requestService.get(`/api/marketplace/mcp/installed`);fetchItem=async e=>await this.requestService.get(`/api/marketplace/mcp/items/${encodeURIComponent(e)}`);fetchContent=async e=>await this.requestService.get(`/api/marketplace/mcp/items/${encodeURIComponent(e)}/content`);fetchRecommendations=async(e={})=>await this.requestService.get(`/api/marketplace/mcp/recommendations`,{query:{...e.scene?.trim()?{scene:e.scene.trim()}:{},...typeof e.limit==`number`&&Number.isFinite(e.limit)?{limit:Math.max(1,Math.trunc(e.limit))}:{}}});install=async e=>await this.requestService.post(`/api/marketplace/mcp/install`,e);manage=async e=>await this.requestService.post(`/api/marketplace/mcp/manage`,e);doctor=async e=>await this.requestService.post(`/api/marketplace/mcp/doctor`,{name:e})};function on(e){let{page:t,pageSize:n,q:r,sort:i,tag:a}=e,o={};return r?.trim()&&(o.q=r.trim()),a?.trim()&&(o.tag=a.trim()),i&&(o.sort=i),typeof t==`number`&&Number.isFinite(t)&&(o.page=Math.max(1,Math.trunc(t))),typeof n==`number`&&Number.isFinite(n)&&(o.pageSize=Math.max(1,Math.trunc(n))),Object.keys(o).length>0?o:void 0}var sn=`x-nextclaw-panel-bridge-session`;function cn(e){return e?{[sn]:e}:void 0}var ln=class{constructor(e){this.requestService=e}listPanelApps=async()=>await this.requestService.get(`/api/panel-apps`);updatePanelAppPreferences=async(e,t)=>await this.requestService.request(`/api/panel-apps/${encodeURIComponent(e)}/preferences`,{method:`PATCH`,body:t});recordPanelAppOpened=async e=>await this.requestService.post(`/api/panel-apps/${encodeURIComponent(e)}/open`);deletePanelApp=async e=>await this.requestService.delete(`/api/panel-apps/${encodeURIComponent(e)}`);createBridgeSession=async e=>await this.requestService.post(`/api/panel-app-bridge-sessions`,e);deleteBridgeSession=async e=>await this.requestService.delete(`/api/panel-app-bridge-sessions/${encodeURIComponent(e)}`);grantClient=async e=>await this.requestService.post(`/api/panel-app-client-grants/${encodeURIComponent(e)}`,{});revokeClient=async e=>await this.requestService.delete(`/api/panel-app-client-grants/${encodeURIComponent(e)}`);sendAgentMessage=async(e,t={})=>await this.requestService.post(`/api/panel-app-agent/send`,e,{headers:cn(t.bridgeSessionToken)});generateAgentObject=async(e,t={})=>await this.requestService.post(`/api/panel-app-agent/generate-object`,e,{headers:cn(t.bridgeSessionToken)});grantAgentCapability=async(e,t={})=>await this.requestService.post(`/api/panel-app-agent-capabilities/${encodeURIComponent(e)}/grant`,{},{headers:cn(t.bridgeSessionToken)})},un=class{constructor(e){this.requestService=e}list=async()=>await this.requestService.get(`/api/providers`);listTemplates=async()=>await this.requestService.get(`/api/provider-templates`);update=async(e,t)=>await this.requestService.put(`/api/providers/${encodeURIComponent(e)}`,t);create=async(e={})=>await this.requestService.post(`/api/providers`,e);delete=async e=>await this.requestService.delete(`/api/providers/${encodeURIComponent(e)}`);testConnection=async(e,t)=>await this.requestService.post(`/api/providers/${encodeURIComponent(e)}/test`,t);startAuth=async(e,t={})=>await this.requestService.post(`/api/providers/${encodeURIComponent(e)}/auth/start`,t);pollAuth=async(e,t)=>await this.requestService.post(`/api/providers/${encodeURIComponent(e)}/auth/poll`,t);importAuthFromCli=async e=>await this.requestService.post(`/api/providers/${encodeURIComponent(e)}/auth/import-cli`,{})},dn=class{baseUrl;transport;webSocketFactory;constructor(e){this.options=e,this.baseUrl=e.baseUrl,this.transport=e.transport,this.webSocketFactory=e.webSocketFactory}subscribe=(e,t={})=>{if(this.transport?.subscribe){let t=this.transport.subscribe(e);return{close:()=>{t()}}}let n=null,r=null,i=!1,a=Math.max(200,t.reconnectDelayMs??1e3),o=()=>{r!==null&&(clearTimeout(r),r=null)},s=t=>{e(t)},c=()=>{try{n=this.createSocket(Gt(this.baseUrl,`/ws`))}catch(e){t.onError?.(e),i||(r=setTimeout(c,a));return}n.onopen=()=>{s({type:`connection.open`})},n.onmessage=e=>{let t=this.parseEvent(e.data);t&&s(t)},n.onerror=e=>{t.onError?.(e),s({type:`connection.error`,payload:{message:`WebSocket error`}})},n.onclose=()=>{s({type:`connection.close`}),n=null,i||(o(),r=setTimeout(c,a))}};return c(),{close:()=>{i=!0,o(),n?.close(),n=null}}};createSocket=e=>{if(this.webSocketFactory)return this.webSocketFactory(e);if(typeof globalThis.WebSocket!=`function`)throw Error(`WebSocket is unavailable. Provide webSocketFactory when creating the client.`);return new globalThis.WebSocket(e)};parseEvent=e=>{if(typeof e!=`string`)return null;try{let t=JSON.parse(e);return t&&typeof t==`object`&&`type`in t?t:null}catch{return null}}},fn=class{constructor(e){this.requestService=e}fetchStatus=async()=>await this.requestService.get(`/api/remote/status`);fetchDoctor=async()=>await this.requestService.get(`/api/remote/doctor`);login=async e=>await this.requestService.post(`/api/remote/login`,e);startBrowserAuth=async(e={})=>await this.requestService.post(`/api/remote/auth/start`,e);pollBrowserAuth=async e=>await this.requestService.post(`/api/remote/auth/poll`,e);logout=async()=>await this.requestService.post(`/api/remote/logout`,{});updateAccountProfile=async e=>await this.requestService.put(`/api/remote/account/profile`,e);updateSettings=async e=>await this.requestService.put(`/api/remote/settings`,e);controlService=async e=>await this.requestService.post(`/api/remote/service/${e}`,{})},Y=class extends Error{status;code;details;constructor(e){let{code:t,details:n,message:r,status:i}=e;super(r),this.name=`NextClawClientError`,this.status=i,this.code=t,this.details=n}};function pn(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function mn(e,t){return pn(e)?e[t]:void 0}var hn=class{baseUrl;fetchImpl;requestTimeoutMs;defaultHeaders;transport;constructor(e){this.options=e;let{baseUrl:t,fetchImpl:n,headers:r,requestTimeoutMs:i,token:a}=e;this.baseUrl=t,this.fetchImpl=n??fetch,this.requestTimeoutMs=Math.max(1e3,i??15e3),this.transport=e.transport,this.defaultHeaders={Accept:`application/json`,...r??{},...a?{Authorization:`Bearer ${a}`}:{}}}request=async(e,t={})=>{let{body:n,headers:r,method:i,query:a,signal:o,timeoutMs:s}=t;if(this.transport)return await this.requestWithTransport(e,t);let c=new AbortController,l=Math.max(1e3,s??this.requestTimeoutMs),u=this.bindAbortSignal(c,o),d=setTimeout(()=>c.abort(),l),f={...this.defaultHeaders,...r??{}},p=this.normalizeRequestBody(n,f);try{let t=await this.fetchImpl(Ut(this.baseUrl,Wt(e,this.serializeQuery(a))),{method:i??`GET`,headers:f,body:p,signal:c.signal}),n=await t.json();if(!t.ok){let e=this.extractApiError(n);throw new Y({message:e.message,status:t.status,code:e.code,details:e.details})}if(!this.isApiResponse(n))throw new Y({message:`Unexpected NextClaw API response shape.`,status:t.status});if(!n.ok)throw new Y({message:n.error.message,status:t.status,code:n.error.code,details:n.error.details});return n.data}catch(e){throw e instanceof Y?e:e instanceof Error&&e.name===`AbortError`?new Y({message:`NextClaw API request timed out after ${l}ms.`}):new Y({message:e instanceof Error?e.message:`NextClaw API request failed.`})}finally{o?.removeEventListener(`abort`,u),clearTimeout(d)}};bindAbortSignal=(e,t)=>{let n=()=>e.abort(t?.reason);return t?t.aborted?(e.abort(t.reason),n):(t.addEventListener(`abort`,n,{once:!0}),n):n};requestWithTransport=async(e,t)=>{let{body:n,headers:r,method:i,query:a,signal:o,timeoutMs:s}=t,{transport:c}=this;if(!c)throw new Y({message:`NextClaw transport is not configured.`});try{return await c.request({method:i??`GET`,path:e,...n===void 0?{}:{body:n},...a?{query:a}:{},...r?{headers:r}:{},...o?{signal:o}:{},...s===void 0?{}:{timeoutMs:s}})}catch(e){if(e instanceof Y)throw e;let t=mn(e,`code`),n=mn(e,`details`),r=mn(e,`status`);throw new Y({message:e instanceof Error?e.message:`NextClaw API request failed.`,code:typeof t==`string`?t:void 0,details:pn(n)?n:void 0,status:typeof r==`number`?r:void 0})}};get=async(e,t={})=>await this.request(e,{...t,method:`GET`});post=async(e,t,n={})=>await this.request(e,{...n,method:`POST`,...t===void 0?{}:{body:t}});put=async(e,t,n={})=>await this.request(e,{...n,method:`PUT`,...t===void 0?{}:{body:t}});delete=async(e,t={})=>await this.request(e,{...t,method:`DELETE`});upload=async(e,t,n={})=>{let{headers:r,signal:i,timeoutMs:a}=n;if(this.transport?.upload)return await this.transport.upload({path:e,formData:t,...r?{headers:r}:{},...i?{signal:i}:{},...a===void 0?{}:{timeoutMs:a}});let o=new AbortController,s=Math.max(1e3,a??this.requestTimeoutMs),c=()=>o.abort(i?.reason);i&&(i.aborted?o.abort(i.reason):i.addEventListener(`abort`,c,{once:!0}));let l=setTimeout(()=>o.abort(),s);try{let n=await this.fetchImpl(Ut(this.baseUrl,e),{method:`POST`,headers:{Accept:`application/json`,...gn(this.options.token)??{},...this.options.headers??{},...r??{}},body:t,signal:o.signal}),i=await n.json();if(!n.ok){let e=this.extractApiError(i);throw new Y({message:e.message,status:n.status,code:e.code,details:e.details})}if(!this.isApiResponse(i)||!i.ok)throw new Y({message:`Unexpected NextClaw upload response shape.`,status:n.status});return i.data}catch(e){throw e instanceof Y?e:e instanceof Error&&e.name===`AbortError`?new Y({message:`NextClaw API upload timed out after ${s}ms.`}):new Y({message:e instanceof Error?e.message:`NextClaw API upload failed.`})}finally{i?.removeEventListener(`abort`,c),clearTimeout(l)}};isApiResponse=e=>typeof e==`object`&&!!e&&`ok`in e;extractApiError=e=>{if(this.isApiResponse(e)&&!e.ok)return e.error;if(typeof e==`object`&&e&&`message`in e){let t=e;return{code:typeof t.code==`string`?t.code:`HTTP_ERROR`,message:typeof t.message==`string`?t.message:`NextClaw API request failed.`,details:t.details!==null&&typeof t.details==`object`?t.details:void 0}}return{code:`HTTP_ERROR`,message:`NextClaw API request failed.`}};normalizeRequestBody=(e,t)=>{if(e!==void 0)return e instanceof FormData||e instanceof URLSearchParams||e instanceof Blob||e instanceof ArrayBuffer?e:typeof e==`string`?(!(`Content-Type`in t)&&!(`content-type`in t)&&(t[`Content-Type`]=`application/json`),e):(!(`Content-Type`in t)&&!(`content-type`in t)&&(t[`Content-Type`]=`application/json`),JSON.stringify(e))};serializeQuery=e=>{if(!e)return;if(e instanceof URLSearchParams)return e;let t=new URLSearchParams;for(let[n,r]of Object.entries(e)){let e=Array.isArray(r)?r:[r];for(let r of e)r!=null&&t.append(n,String(r))}return t}};function gn(e){return e?{Authorization:`Bearer ${e}`}:null}var _n=class{constructor(e){this.requestService=e}fetch=async()=>await this.requestService.get(`/api/runtime/control`);startService=async()=>await this.requestService.post(`/api/runtime/control/start-service`,{});restartService=async()=>await this.requestService.post(`/api/runtime/control/restart-service`,{});stopService=async()=>await this.requestService.post(`/api/runtime/control/stop-service`,{})},vn=class{constructor(e){this.requestService=e}fetch=async()=>await this.requestService.get(`/api/runtime/update`);check=async()=>await this.requestService.post(`/api/runtime/update/check`,{});download=async()=>await this.requestService.post(`/api/runtime/update/download`,{});apply=async()=>await this.requestService.post(`/api/runtime/update/apply`,{});updatePreferences=async e=>await this.requestService.put(`/api/runtime/update/preferences`,e);updateChannel=async e=>await this.requestService.put(`/api/runtime/update/channel`,{channel:e})},yn=class{constructor(e){this.requestService=e}browse=async e=>{let t=typeof e?.path==`string`?e.path.trim():``;return await this.requestService.get(`/api/server-paths/browse`,{query:{...t?{path:t}:{},...e?.includeFiles?{includeFiles:`1`}:{}}})};read=async e=>{let t=e.path.trim(),n=typeof e.basePath==`string`?e.basePath.trim():``;return await this.requestService.get(`/api/server-paths/read`,{query:{path:t,...n?{basePath:n}:{}}})}},bn=`x-nextclaw-panel-bridge-session`;function xn(e){return e?{[bn]:e}:void 0}var Sn=class{constructor(e){this.requestService=e}listServiceApps=async()=>await this.requestService.get(`/api/service-apps`);getServiceApp=async e=>await this.requestService.get(`/api/service-apps/${encodeURIComponent(e)}`);restartServiceApp=async e=>await this.requestService.post(`/api/service-apps/${encodeURIComponent(e)}/restart`);deleteServiceApp=async e=>await this.requestService.delete(`/api/service-apps/${encodeURIComponent(e)}`);listServiceActions=async(e={})=>{let t=e.appId?`?${new URLSearchParams({appId:e.appId}).toString()}`:``;return await this.requestService.get(`/api/service-actions${t}`,{headers:xn(e.bridgeSessionToken)})};discoverServiceAppActions=async e=>await this.requestService.post(`/api/service-apps/${encodeURIComponent(e)}/actions/discover`,{});invokeServiceAction=async(e,t,n={})=>await this.requestService.post(`/api/service-actions/${encodeURIComponent(e)}/invoke`,{input:t??{}},{headers:xn(n.bridgeSessionToken)});grantServiceAction=async(e,t={})=>await this.requestService.post(`/api/service-actions/${encodeURIComponent(e)}/grant`,{},{headers:xn(t.bridgeSessionToken)});grantServiceActions=async(e,t={})=>await this.requestService.post(`/api/service-action-grants`,{actionIds:e},{headers:xn(t.bridgeSessionToken)});listServiceActionGrants=async()=>await this.requestService.get(`/api/service-action-grants`);revokeServiceAction=async(e,t={})=>await this.requestService.delete(`/api/service-actions/${encodeURIComponent(e)}/grant`,{headers:xn(t.bridgeSessionToken)});revokeServiceActionGrant=async e=>{let t=new URLSearchParams({surface:e.caller.surface,appId:e.caller.appId});return await this.requestService.delete(`/api/service-action-grants/${encodeURIComponent(e.actionId)}?${t.toString()}`)}},Cn=class{constructor(e,t){this.requestService=e,this.eventBus=t}list=async e=>{let t=new URLSearchParams;return typeof e?.limit==`number`&&Number.isFinite(e.limit)&&t.set(`limit`,String(Math.max(1,Math.trunc(e.limit)))),await this.requestService.get(`/api/ncp/sessions`,{...t.size>0?{query:t}:{}})};get=async e=>await this.requestService.get(`/api/ncp/sessions/${encodeURIComponent(e)}`);listMessages=async(e,t=200)=>await this.requestService.get(`/api/ncp/sessions/${encodeURIComponent(e)}/messages`,{query:{limit:Math.max(1,Math.trunc(t))}});listSkills=async(e,t)=>await this.requestService.get(`/api/ncp/sessions/${encodeURIComponent(e)}/skills`,{query:t?.projectRoot?.trim()?{projectRoot:t.projectRoot.trim()}:void 0});update=async(e,t)=>await this.requestService.put(`/api/ncp/sessions/${encodeURIComponent(e)}`,t);delete=async e=>await this.requestService.delete(`/api/ncp/sessions/${encodeURIComponent(e)}`);uploadAssets=async e=>{let t=new FormData;for(let n of e)t.append(`files`,n);return await this.requestService.upload(`/api/ncp/assets`,t)};subscribe=(e,t={})=>({close:this.eventBus.subscribeAll(t=>{e(t)})})},wn=class{baseUrl;agentRuns;app;agents;auth;channelAuth;config;eventBus;marketplace;mcpMarketplace;panelApps;providers;realtime;remote;runtimeControl;runtimeUpdate;serverPaths;serviceApps;sessions;constructor(e){this.baseUrl=Ht(e.baseUrl);let t={...e,baseUrl:this.baseUrl},n=new hn(t);this.realtime=new dn(t);let r=null;this.eventBus=new Bt({onFirstSubscriber:()=>{r??=this.realtime.subscribe(e=>{this.eventBus.emitEnvelope({type:e.type,payload:`payload`in e?e.payload:void 0,emittedAt:`emittedAt`in e?e.emittedAt:new Date().toISOString(),source:`source`in e?e.source:`realtime`})})},onNoSubscribers:()=>{r?.close(),r=null}}),this.agentRuns=new Jt(n,t),this.app=new Xt(n),this.agents=new Yt(n,this.baseUrl),this.auth=new Zt(n),this.channelAuth=new Qt(n),this.config=new $t(n),this.marketplace=new en(n),this.mcpMarketplace=new an(n),this.panelApps=new ln(n),this.providers=new un(n),this.remote=new fn(n),this.runtimeControl=new _n(n),this.runtimeUpdate=new vn(n),this.serverPaths=new yn(n),this.serviceApps=new Sn(n),this.sessions=new Cn(n,this.eventBus)}},Tn=`http://127.0.0.1:55667`,En=(()=>{let e=(void 0)?.trim();return e?e.replace(/\/$/,``):typeof window<`u`&&window.location?.origin?window.location.origin:Tn})(),Dn={"Use this page to manage the local NextClaw service. Closing the browser does not stop the service.":`runtimeControlManagedLocalMessage`,"This page is served by the running local service. Closing the browser does not stop it.":`runtimeControlManagedLocalHint`,"This page is served by the running local service.":`runtimeControlManagedLocalHintShort`,"This page is already hosted by the running local service.":`runtimeControlStartUnavailableHosted`,"App restart is only available in the desktop shell.":`runtimeControlRestartAppDesktopOnly`,"The local service is not running.":`runtimeControlServiceNotRunning`,"The local service is already stopped.":`runtimeControlServiceAlreadyStopped`,"Managed service started.":`runtimeControlManagedServiceStarted`,"Managed service start scheduled.":`runtimeControlManagedServiceStartScheduled`,"Restart scheduled. This page may disconnect for a few seconds.":`runtimeControlRestartScheduled`,"Stop scheduled. This page will disconnect shortly.":`runtimeControlStopScheduled`,"runtime healthy":`runtimeControlHealthy`};function On(e){return e.activeSystemAction?`service-transitioning`:e.lifecyclePhase}function kn(e){return e===`ready`?`connected`:e===`startup-failed`||e===`stalled`?`disconnected`:`connecting`}function An(e){let t=On(e);return{...e,phase:t,connectionStatus:kn(t)}}function jn(e){return e===`start-service`?`starting-service`:e===`stop-service`?`stopping-service`:e===`restart-service`?`restarting-service`:`restarting-app`}function Mn(e){return e===`start-service`?`starting`:e===`stop-service`?`stopping`:e===`restart-service`?`restarting`:null}function X(e){if(!e)return null;let t=Dn[e.trim()];return t?r(t):e}function Nn(e){let{action:t,message:n}=e;return{action:t,lifecycle:jn(t),serviceState:Mn(t),message:n}}function Pn(e){if(e.runtimeControlError)return{tone:`inactive`,title:r(`runtimeControlLoadFailed`),description:e.runtimeControlError,reasonLines:[],actionLabel:null,isBusy:!1};if(!e.runtimeControlView)return{tone:`inactive`,title:r(`runtimeStatusLoadingTitle`),description:r(`runtimeStatusLoadingDescription`),reasonLines:[],actionLabel:null,isBusy:!!e.activeSystemAction};if(e.activeSystemAction)return{tone:`attention`,title:r(`runtimeControlTitle`),description:X(e.activeSystemAction.message)||X(e.runtimeControlView.message)||r(`runtimeControlDescription`),reasonLines:[],actionLabel:null,isBusy:!0};let t=e.runtimeControlView;return t.pendingRestart?{tone:`attention`,title:r(`runtimeStatusPendingRestartTitle`),description:r(`runtimeStatusPendingRestartDescription`),reasonLines:t.pendingRestart.changedPaths.length>0?t.pendingRestart.changedPaths.map(e=>r(`runtimeStatusPendingRestartReasonItem`).replace(`{path}`,e)):[t.pendingRestart.message],actionLabel:t.canRestartService.available?r(`runtimeStatusRestartAction`):null,isBusy:!1}:{tone:t.lifecycle===`healthy`?`healthy`:`inactive`,title:r(`runtimeStatusHealthyTitle`),description:r(`runtimeStatusHealthyDescription`),reasonLines:[],actionLabel:null,isBusy:!1}}function Fn(e){let t=e.activeSystemAction,n=e.runtimeControlView;return{controlView:n,visibleLifecycle:t?.lifecycle??n?.lifecycle??`healthy`,visibleServiceState:t?.serviceState??n?.serviceState??`unknown`,visibleMessage:X(t?.message)||X(e.lastSystemActionError)||X(n?.message)||r(`runtimeControlDescription`),busyAction:t?.action??null,busy:!!t,pendingRestart:n?.pendingRestart??null,errorMessage:X(e.lastSystemActionError)||X(e.runtimeControlError)||null}}var In={lifecyclePhase:`cold-starting`,hasReachedReady:!1,lastReadyAt:null,recoveryStartedAt:null,bootstrapStatus:null,lastError:null,lastTransportError:null,runtimeControlView:null,runtimeControlError:null,activeSystemAction:null,lastSystemActionError:null},Ln=o(e=>({state:In,patchState:t=>e(e=>({state:{...e.state,...t}}))}));function Rn(e){if(e.length===0)throw Error(`AdaptiveCadence requires at least one stage.`);for(let t of e)if(t.delaysMs.length===0)throw Error(`AdaptiveCadence stage requires at least one delay.`)}var zn=class{constructor(e){this.options=e,this.attempt=0,this.startedAt=null,this.lastFailureAt=null,this.lastSuccessAt=null,this.manualTriggerPending=!1,this.completed=!1,this.recordFailure=()=>{let e=this.clock();this.completed=!1,this.manualTriggerPending=!1,this.startedAt=this.startedAt??e,this.lastFailureAt=e,this.attempt+=1},this.recordSuccess=()=>{this.lastSuccessAt=this.clock(),this.attempt=0,this.startedAt=null,this.lastFailureAt=null,this.manualTriggerPending=!1,this.completed=!0},this.reset=()=>{this.attempt=0,this.startedAt=null,this.lastFailureAt=null,this.lastSuccessAt=null,this.manualTriggerPending=!1,this.completed=!1},this.requestManualTrigger=()=>{this.completed=!1,this.manualTriggerPending=!0},this.hasManualTrigger=()=>this.manualTriggerPending,this.getNextDelay=(e={})=>{if(this.manualTriggerPending)return e.consumeManualTrigger&&(this.manualTriggerPending=!1),this.options.manualTriggerDelayMs;if(this.completed)return this.options.successDelayMs;if(this.startedAt===null)return this.options.idleDelayMs;let t=this.resolveStage(this.clock()-this.startedAt);return t.delaysMs[Math.min(this.attempt-1,t.delaysMs.length-1)]},this.getSnapshot=()=>({attempt:this.attempt,startedAt:this.startedAt,lastFailureAt:this.lastFailureAt,lastSuccessAt:this.lastSuccessAt,manualTriggerPending:this.manualTriggerPending,completed:this.completed}),this.resolveStage=e=>this.options.stages.find(t=>t.untilElapsedMs===void 0||e<t.untilElapsedMs)??this.options.stages[this.options.stages.length-1],Rn(e.stages),this.clock=e.clock??(()=>Date.now())}},Bn=3e4,Vn={idleDelayMs:1e3,manualTriggerDelayMs:0,successDelayMs:!1,stages:[{untilElapsedMs:3e4,delaysMs:[500,1e3,2e3,4e3,5e3]},{untilElapsedMs:5*6e4,delaysMs:[1e4,15e3,3e4]},{delaysMs:[6e4]}]};function Hn(e){return e instanceof Error?e.message:String(e??``)}function Un(e){return e&&(e.ncpAgent.error?.trim()||e.lastError?.trim())||null}function Wn(e){return r(e===`start-service`?`runtimeControlStartingServiceHelp`:e===`restart-service`?`runtimeControlRestartingServiceHelp`:e===`stop-service`?`runtimeControlStoppingServiceHelp`:`runtimeControlRestartingAppHelp`)}var Z=new class{constructor(){this.recoveryTimeoutId=null,this.runtimeBootstrapProbeCadence=new zn(Vn),this.getRuntimeBootstrapPollInterval=e=>{let{lifecyclePhase:t,activeSystemAction:n}=this.getState(),r=t===`recovering`||t===`stalled`||n?.lifecycle===`recovering`;return this.runtimeBootstrapProbeCadence.hasManualTrigger()?this.runtimeBootstrapProbeCadence.getNextDelay({consumeManualTrigger:!0}):!r&&e?.ncpAgent.state===`ready`?!1:this.runtimeBootstrapProbeCadence.getNextDelay({consumeManualTrigger:!0})},this.getRuntimeControl=async()=>this.decorateForCurrentEnvironment(await fa()),this.reportBootstrapStatus=e=>{let t=this.getState(),n=Un(e);if(e.ncpAgent.state===`ready`){this.transitionToReady(e);return}if(!t.hasReachedReady){if(e.ncpAgent.state===`error`||e.phase===`error`){this.transitionToStartupFailed(n,e);return}this.transitionToColdStarting(e);return}this.transitionToRecovering(n,e)},this.reportBootstrapQueryError=e=>{let t=Hn(e).trim();if(t&&!this.reportTransportFailure(t)){if(this.getState().hasReachedReady){this.transitionToRecovering(t);return}this.transitionToStartupFailed(t)}},this.reportTransportFailure=e=>{let t=Hn(e).trim();return Ur(t)?this.getState().hasReachedReady?(this.transitionToRecovering(t),!0):(this.runtimeBootstrapProbeCadence.recordFailure(),this.patchState({lastTransportError:t}),!0):!1},this.handleConnectionInterrupted=e=>{let t=this.getState(),n=e?.trim()||null;if(!t.hasReachedReady){this.runtimeBootstrapProbeCadence.recordFailure(),n&&this.patchState({lastTransportError:n});return}this.transitionToRecovering(n)},this.handleConnectionRestored=()=>{let e=this.getState();e.bootstrapStatus?.ncpAgent.state===`ready`&&this.transitionToReady(e.bootstrapStatus)},this.reportRuntimeControlView=e=>{this.patchState({runtimeControlView:e,runtimeControlError:null})},this.reportRuntimeControlError=e=>{let t=Hn(e).trim();t&&this.patchState({runtimeControlError:t})},this.runRuntimeControlAction=async e=>{this.patchState({activeSystemAction:Nn({action:e,message:Wn(e)}),lastSystemActionError:null});try{let t=await this.executeRuntimeControlAction(e);if(e===`restart-app`)return t;if(e===`stop-service`)return await this.refreshRuntimeControlView(),this.clearActiveSystemAction(),t;this.patchState({activeSystemAction:{action:e,lifecycle:`recovering`,serviceState:null,message:r(`runtimeControlRecoveringHelp`)}}),this.runtimeBootstrapProbeCadence.requestManualTrigger();let n=await this.waitForRecovery();return this.syncRuntimeControlQueryCache(n),this.reportRuntimeControlView(n),this.clearActiveSystemAction(),t}catch(t){let n=t instanceof Error?t.message:r(`runtimeControlActionFailed`);throw this.patchState({activeSystemAction:{action:e,lifecycle:`failed`,serviceState:e===`stop-service`?`running`:e===`restart-app`?null:`unknown`,message:n},lastSystemActionError:n}),t}},this.getStatusView=()=>An(this.getState()),this.requestRuntimeBootstrapProbeNow=()=>{this.runtimeBootstrapProbeCadence.requestManualTrigger(),wt.refetchQueries({queryKey:[`runtime-bootstrap-status`]})},this.resetForTests=()=>{this.clearRecoveryTimeout(),this.runtimeBootstrapProbeCadence.reset(),Ln.setState({state:In})},this.getState=()=>Ln.getState().state,this.patchState=e=>{Ln.getState().patchState(e)},this.transitionToColdStarting=e=>{this.runtimeBootstrapProbeCadence.recordFailure(),this.clearRecoveryTimeout(),this.patchState({lifecyclePhase:`cold-starting`,recoveryStartedAt:null,bootstrapStatus:e,lastError:null})},this.transitionToStartupFailed=(e,t)=>{this.runtimeBootstrapProbeCadence.recordFailure(),this.clearRecoveryTimeout(),this.patchState({lifecyclePhase:`startup-failed`,recoveryStartedAt:null,bootstrapStatus:t??this.getState().bootstrapStatus,lastError:e})},this.transitionToRecovering=(e,t)=>{this.runtimeBootstrapProbeCadence.recordFailure();let n=this.getState();if(!n.hasReachedReady){this.patchState({lastTransportError:e?.trim()||n.lastTransportError});return}n.lifecyclePhase!==`recovering`&&n.lifecyclePhase!==`stalled`&&(this.clearRecoveryTimeout(),this.recoveryTimeoutId=window.setTimeout(()=>{this.recoveryTimeoutId=null,this.getState().lifecyclePhase===`recovering`&&this.patchState({lifecyclePhase:`stalled`})},Bn)),this.patchState({lifecyclePhase:n.lifecyclePhase===`stalled`?`stalled`:`recovering`,recoveryStartedAt:n.recoveryStartedAt??Date.now(),bootstrapStatus:t??n.bootstrapStatus,lastError:e?.trim()||n.lastError,lastTransportError:e?.trim()||n.lastTransportError})},this.transitionToReady=e=>{this.runtimeBootstrapProbeCadence.recordSuccess();let t=this.getState(),n=t.lifecyclePhase===`recovering`||t.lifecyclePhase===`stalled`;this.clearRecoveryTimeout(),this.patchState({lifecyclePhase:`ready`,hasReachedReady:!0,lastReadyAt:Date.now(),recoveryStartedAt:null,bootstrapStatus:e,lastError:null,lastTransportError:null}),n&&wt.refetchQueries({type:`active`})},this.executeRuntimeControlAction=async e=>{let t=this.getDesktopBridge();if(e===`restart-service`&&t&&typeof t.restartService==`function`){let e=await t.restartService();return{accepted:e.accepted,action:`restart-service`,lifecycle:e.lifecycle,message:e.message}}if(e===`start-service`)return await pa();if(e===`stop-service`)return await ha();if(e===`restart-app`){if(!t||typeof t.restartApp!=`function`)throw Error(r(`runtimeRestartAppUnavailable`));let e=await t.restartApp();return{accepted:e.accepted,action:`restart-app`,lifecycle:e.lifecycle,message:e.message}}return await ma()},this.waitForRecovery=async()=>{let e=Date.now()+25e3,t=null;for(;Date.now()<e;)try{return await this.getRuntimeControl()}catch(e){t=e,await new Promise(e=>{window.setTimeout(e,1500)})}throw t instanceof Error?t:Error(r(`runtimeRecoveryTimedOut`))},this.refreshRuntimeControlView=async()=>{try{let e=await this.getRuntimeControl();this.syncRuntimeControlQueryCache(e),this.reportRuntimeControlView(e)}catch(e){this.reportRuntimeControlError(e)}},this.syncRuntimeControlQueryCache=e=>{wt.setQueryData([`runtime-control`],e)},this.clearActiveSystemAction=()=>{this.patchState({activeSystemAction:null,lastSystemActionError:null})},this.clearRecoveryTimeout=()=>{this.recoveryTimeoutId!==null&&(window.clearTimeout(this.recoveryTimeoutId),this.recoveryTimeoutId=null)},this.decorateForCurrentEnvironment=e=>{let t=this.getDesktopBridge();return!t||typeof t.restartApp!=`function`?e:{...e,environment:`desktop-embedded`,serviceState:`running`,canStartService:{available:!1,requiresConfirmation:!1,impact:`none`},canStopService:{available:!1,requiresConfirmation:!0,impact:`brief-ui-disconnect`},canRestartApp:{available:!0,requiresConfirmation:!0,impact:`full-app-relaunch`},ownerLabel:r(`runtimeControlEnvironmentDesktop`),managementHint:r(`runtimeControlDesktopServiceHint`)}},this.getDesktopBridge=()=>typeof window>`u`?null:window.nextclawDesktop??null}};function Gn(){let e=Je({queryKey:[`runtime-bootstrap-status`],queryFn:()=>oi({timeoutMs:5e3}),refetchInterval:e=>Z.getRuntimeBootstrapPollInterval(e.state.data),retry:!1}),t=Je({queryKey:[`runtime-control`],queryFn:async()=>await Z.getRuntimeControl(),staleTime:5e3});(0,B.useEffect)(()=>{e.data&&Z.reportBootstrapStatus(e.data)},[e.data]),(0,B.useEffect)(()=>{e.error&&Z.reportBootstrapQueryError(e.error)},[e.error]),(0,B.useEffect)(()=>{t.data&&Z.reportRuntimeControlView(t.data)},[t.data]),(0,B.useEffect)(()=>{t.error&&Z.reportRuntimeControlError(t.error)},[t.error])}function Kn(){return An(Ln(e=>e.state))}function qn(){return Pn(Ln(e=>e.state))}function Jn(){return Fn(Ln(e=>e.state))}var Q=o(()=>({supported:!1,initialized:!1,busyAction:null,snapshot:null})),Yn=class{constructor(e){this.desktopApi=e,this.kind=`desktop-bridge`,this.subscribe=e=>this.desktopApi.onUpdateStateChanged(e),this.getState=async()=>await this.desktopApi.getUpdateState(),this.checkForUpdates=async()=>await this.desktopApi.checkForUpdates(),this.downloadUpdate=async()=>await this.desktopApi.downloadUpdate(),this.applyDownloadedUpdate=async()=>await this.desktopApi.applyDownloadedUpdate(),this.updatePreferences=async e=>await this.desktopApi.updatePreferences(e),this.updateChannel=async e=>await this.desktopApi.updateChannel(e)}},Xn=class{constructor(){this.kind=`runtime-host`,this.getState=async()=>await ga(),this.checkForUpdates=async()=>await _a(),this.downloadUpdate=async()=>await va(),this.applyDownloadedUpdate=async()=>await ya(),this.updatePreferences=async e=>await ba(e),this.updateChannel=async e=>await xa(e)}},Zn=new class{constructor(){this.unsubscribe=null,this.subscriptionCount=0,this.source=null,this.start=async()=>{this.subscriptionCount+=1;let e=this.resolveSource();if(this.source=e,!e){Q.setState({supported:!1,initialized:!0,snapshot:null});return}e.kind===`desktop-bridge`&&!this.unsubscribe&&(this.unsubscribe=e.subscribe(e=>{Q.setState({supported:!0,initialized:!0,snapshot:e})})),Q.setState({supported:!0,initialized:!1});try{let t=await e.getState();Q.setState({supported:!0,initialized:!0,snapshot:t})}catch(t){if(e.kind===`runtime-host`&&this.isUnsupportedError(t)){Q.setState({supported:!1,initialized:!0,snapshot:null});return}Q.setState({supported:!0,initialized:!0}),W.error(`${r(`runtimeUpdatesLoadFailed`)}: ${this.getErrorMessage(t)}`)}},this.stop=()=>{this.subscriptionCount=Math.max(0,this.subscriptionCount-1),!(this.subscriptionCount>0)&&(this.unsubscribe?.(),this.unsubscribe=null,this.source=null)},this.reportSnapshot=e=>{this.source?.kind!==`desktop-bridge`&&Q.setState({supported:!0,initialized:!0,snapshot:e})},this.refreshAfterRealtimeReconnect=async()=>{this.source?.kind===`runtime-host`&&await this.refreshSnapshot()},this.checkForUpdates=async()=>{let e;try{e=await this.runSnapshotCommand(`checking`,r(`runtimeUpdatesCheckFailed`),async e=>await e.checkForUpdates())}catch{return}if(e.status===`up-to-date`){W.success(r(`runtimeUpdatesAlreadyLatest`));return}if(e.status===`update-available`){W.success(r(`runtimeUpdatesAvailable`).replace(`{version}`,e.availableVersion??r(`runtimeUpdatesUnknownVersion`)));return}e.status===`downloaded`&&W.success(r(`runtimeUpdatesReadyToApply`))},this.downloadUpdate=async()=>{try{await this.runSnapshotCommand(`downloading`,r(`runtimeUpdatesDownloadFailed`),async e=>await e.downloadUpdate())}catch{return}},this.applyDownloadedUpdate=async()=>{try{await this.runSnapshotCommand(`applying`,r(`runtimeUpdatesApplyFailed`),async e=>await e.applyDownloadedUpdate())}catch{return}},this.updatePreferences=async e=>{try{await this.runSnapshotCommand(`saving-preferences`,r(`runtimeUpdatesPreferencesFailed`),async t=>await t.updatePreferences(e))}catch{return}},this.updateChannel=async e=>{if(Q.getState().snapshot?.channel===e)return;let t;try{t=await this.runSnapshotCommand(`switching-channel`,r(`runtimeUpdatesChannelChangeFailed`),async t=>await t.updateChannel(e))}catch{return}if(t.status===`update-available`&&t.availableVersion){W.success(r(`runtimeUpdatesChannelChangedWithUpdate`).replace(`{channel}`,this.getChannelLabel(e)).replace(`{version}`,t.availableVersion));return}W.success(r(`runtimeUpdatesChannelChanged`).replace(`{channel}`,this.getChannelLabel(e)))},this.refreshSnapshot=async()=>{if(!(!this.source||this.source.kind!==`runtime-host`))try{let e=await this.source.getState();Q.setState({supported:!0,initialized:!0,snapshot:e})}catch{}},this.runSnapshotCommand=async(e,t,n)=>{let i=this.source??this.resolveSource();if(!i)throw Error(r(`runtimeUpdatesUnavailableDescription`));this.source=i,Q.setState({busyAction:e});try{let e=await n(i);return Q.setState({snapshot:e}),e}catch(e){throw W.error(`${t}: ${this.getErrorMessage(e)}`),e}finally{Q.setState({busyAction:null})}},this.resolveSource=()=>{let e=this.getDesktopApi();return e?new Yn(e):new Xn},this.getDesktopApi=()=>typeof window>`u`?null:window.nextclawDesktop??null,this.isUnsupportedError=e=>{let t=this.getErrorMessage(e).toLowerCase();return t.includes(`404`)||t.includes(`not found`)||t.includes(`endpoint not found`)},this.getErrorMessage=e=>e instanceof Error?e.message:r(`error`),this.getChannelLabel=e=>r(e===`beta`?`desktopUpdatesChannelBeta`:`desktopUpdatesChannelStable`)}},Qn=B.forwardRef(({className:t,checked:n=!1,onCheckedChange:r,thumbClassName:i,...a},o)=>(0,V.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":n,ref:o,className:e(`peer inline-flex h-[22px] w-10 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors duration-fast focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-white disabled:cursor-not-allowed disabled:opacity-50`,n?`bg-primary`:`bg-gray-200/80 hover:bg-gray-300/80`,t),onClick:()=>r?.(!n),...a,children:(0,V.jsx)(`span`,{"data-state":n?`checked`:`unchecked`,className:e(`pointer-events-none block h-5 w-5 rounded-full bg-white shadow-md ring-0 transition-transform duration-fast`,n?`translate-x-5`:`translate-x-0`,i)})}));Qn.displayName=`Switch`;var $n={maxRetries:8,startupTimeoutMs:2e3,settledTimeoutMs:5e3,retryBaseDelayMs:500,retryMaxDelayMs:3e3};function er(e){return e instanceof Error?Ur(e.message):!1}function tr(e,t){return e>=$n.maxRetries?!1:er(t)}function nr(e){return Math.min($n.retryMaxDelayMs,$n.retryBaseDelayMs*2**Math.max(0,e-1))}function rr(){let[e,t]=(0,B.useState)(!1),n=Je({queryKey:[`auth-status`],queryFn:()=>$r({timeoutMs:e?$n.settledTimeoutMs:$n.startupTimeoutMs}),staleTime:5e3,retry:tr,retryDelay:nr});return(0,B.useEffect)(()=>{n.isSuccess&&!e&&t(!0)},[e,n.isSuccess]),n}function ir(e){return Promise.all([e.invalidateQueries({queryKey:[`auth-status`]}),e.invalidateQueries({queryKey:[`app-meta`]}),e.invalidateQueries({queryKey:[`config`]}),e.invalidateQueries({queryKey:[`config-meta`]}),e.invalidateQueries({queryKey:[`config-schema`]}),e.invalidateQueries({queryKey:[`sessions`]}),e.invalidateQueries({queryKey:[`session-history`]}),e.invalidateQueries({queryKey:[`chat-runs`]}),e.invalidateQueries({queryKey:[`cron-jobs`]})])}function ar(){let e=H();return Ye({mutationFn:ei,onSuccess:async()=>{await ir(e),W.success(r(`authSetupSuccess`))},onError:e=>{W.error(`${r(`authActionFailed`)}: ${e.message}`)}})}function or(){let e=H();return Ye({mutationFn:ti,onSuccess:async()=>{await ir(e),W.success(r(`authLoginSuccess`))},onError:e=>{W.error(`${r(`authActionFailed`)}: ${e.message}`)}})}function sr(){let e=H();return Ye({mutationFn:ni,onSuccess:async()=>{await ir(e),W.success(r(`authLogoutSuccess`))},onError:e=>{W.error(`${r(`authActionFailed`)}: ${e.message}`)}})}function cr(){let e=H();return Ye({mutationFn:ri,onSuccess:async()=>{await ir(e),W.success(r(`authPasswordUpdated`))},onError:e=>{W.error(`${r(`authActionFailed`)}: ${e.message}`)}})}function lr(){let e=H();return Ye({mutationFn:ii,onSuccess:async(t,n)=>{await ir(e),W.success(n.enabled?r(`authEnabledSuccess`):r(`authDisabledSuccess`))},onError:e=>{W.error(`${r(`authActionFailed`)}: ${e.message}`)}})}var ur=8;function dr(e){return e.trim().length>=ur}function fr(e,t){return e===t?!0:(W.error(r(`authPasswordMismatch`)),!1)}function pr({children:e,contentClassName:t=`space-y-6`}){return(0,V.jsxs)(Nt,{children:[(0,V.jsxs)(Pt,{children:[(0,V.jsx)(Ft,{children:r(`authSecurityTitle`)}),(0,V.jsx)(It,{children:r(`authSecurityDescription`)})]}),(0,V.jsx)(Lt,{className:t,children:e})]})}function mr(e){return(0,V.jsxs)(pr,{contentClassName:`space-y-5`,children:[(0,V.jsxs)(`div`,{className:`rounded-xl border border-dashed border-gray-200 bg-gray-50/70 p-4`,children:[(0,V.jsx)(`p`,{className:`text-sm font-medium text-gray-900`,children:r(`authSetupTitle`)}),(0,V.jsx)(`p`,{className:`mt-1 text-sm text-gray-500`,children:r(`authSetupDescription`)})]}),(0,V.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,V.jsxs)(`div`,{className:`space-y-2`,children:[(0,V.jsx)(At,{htmlFor:`auth-setup-username`,children:r(`authUsername`)}),(0,V.jsx)(K,{id:`auth-setup-username`,value:e.setupUsername,onChange:t=>e.setSetupUsername(t.target.value),placeholder:r(`authUsernamePlaceholder`)})]}),(0,V.jsxs)(`div`,{className:`space-y-2`,children:[(0,V.jsx)(At,{htmlFor:`auth-setup-password`,children:r(`authPassword`)}),(0,V.jsx)(K,{id:`auth-setup-password`,type:`password`,value:e.setupPassword,onChange:t=>e.setSetupPassword(t.target.value),placeholder:r(`authPasswordPlaceholder`)})]})]}),(0,V.jsxs)(`div`,{className:`space-y-2`,children:[(0,V.jsx)(At,{htmlFor:`auth-setup-confirm`,children:r(`authConfirmPassword`)}),(0,V.jsx)(K,{id:`auth-setup-confirm`,type:`password`,value:e.setupConfirmPassword,onChange:t=>e.setSetupConfirmPassword(t.target.value),placeholder:r(`authConfirmPasswordPlaceholder`)}),(0,V.jsx)(`p`,{className:`text-xs text-gray-500`,children:r(`authPasswordMinLengthHint`)})]}),(0,V.jsx)(kt,{type:`button`,disabled:!e.canSubmitSetup,onClick:()=>void e.onSubmit(),children:e.isPending?r(`authSettingUp`):r(`authSetupAction`)})]})}function hr(e){return(0,V.jsxs)(pr,{children:[(0,V.jsxs)(`div`,{className:`rounded-xl border border-gray-200 p-4`,children:[(0,V.jsxs)(`div`,{className:`flex flex-col gap-4 md:flex-row md:items-start md:justify-between`,children:[(0,V.jsxs)(`div`,{className:`space-y-1`,children:[(0,V.jsx)(`p`,{className:`text-sm font-medium text-gray-900`,children:r(`authStatusLabel`)}),(0,V.jsx)(`p`,{className:`text-sm text-gray-600`,children:r(`authStatusConfiguredUser`).replace(`{username}`,e.username??``)}),(0,V.jsx)(`p`,{className:`text-xs text-gray-500`,children:r(`authUsernameFixedHelp`)})]}),(0,V.jsx)(`span`,{className:`inline-flex items-center rounded-full bg-gray-100 px-3 py-1 text-xs font-medium text-gray-700`,children:e.enabled?r(`enabled`):r(`disabled`)})]}),(0,V.jsxs)(`div`,{className:`mt-4 flex flex-col gap-4 border-t border-gray-200 pt-4 md:flex-row md:items-center md:justify-between`,children:[(0,V.jsxs)(`div`,{className:`space-y-1`,children:[(0,V.jsx)(`p`,{className:`text-sm font-medium text-gray-900`,children:r(`authEnableLabel`)}),(0,V.jsx)(`p`,{className:`text-xs text-gray-500`,children:e.enabled?r(`authEnableOnHelp`):r(`authEnableOffHelp`)})]}),(0,V.jsx)(Qn,{checked:e.enabled,disabled:e.isUpdatingEnabled,onCheckedChange:t=>{e.onEnabledChange(t)}})]})]}),(0,V.jsxs)(`div`,{className:`rounded-xl border border-gray-200 p-4 space-y-4`,children:[(0,V.jsxs)(`div`,{className:`space-y-1`,children:[(0,V.jsx)(`p`,{className:`text-sm font-medium text-gray-900`,children:r(`authPasswordSectionTitle`)}),(0,V.jsx)(`p`,{className:`text-xs text-gray-500`,children:r(`authPasswordSectionDescription`)})]}),(0,V.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,V.jsxs)(`div`,{className:`space-y-2`,children:[(0,V.jsx)(At,{htmlFor:`auth-password-next`,children:r(`authPassword`)}),(0,V.jsx)(K,{id:`auth-password-next`,type:`password`,value:e.nextPassword,onChange:t=>e.setNextPassword(t.target.value),placeholder:r(`authPasswordPlaceholder`)})]}),(0,V.jsxs)(`div`,{className:`space-y-2`,children:[(0,V.jsx)(At,{htmlFor:`auth-password-confirm`,children:r(`authConfirmPassword`)}),(0,V.jsx)(K,{id:`auth-password-confirm`,type:`password`,value:e.nextConfirmPassword,onChange:t=>e.setNextConfirmPassword(t.target.value),placeholder:r(`authConfirmPasswordPlaceholder`)})]})]}),(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,V.jsx)(kt,{type:`button`,disabled:!e.canUpdatePassword,onClick:()=>void e.onPasswordUpdate(),children:e.isUpdatingPassword?r(`authPasswordUpdating`):r(`authPasswordAction`)}),e.enabled&&e.authenticated?(0,V.jsx)(kt,{type:`button`,variant:`outline`,disabled:e.isLoggingOut,onClick:()=>void e.onLogout(),children:e.isLoggingOut?r(`authLoggingOut`):r(`authLogoutAction`)}):null]}),(0,V.jsx)(`p`,{className:`text-xs text-gray-500`,children:r(`authSessionMemoryNotice`)})]})]})}function gr(){let e=rr(),t=ar(),n=lr(),i=cr(),a=sr(),[o,s]=(0,B.useState)(``),[c,l]=(0,B.useState)(``),[u,d]=(0,B.useState)(``),[f,p]=(0,B.useState)(``),[m,h]=(0,B.useState)(``),g=e.data,_=o.trim().length>0&&dr(c)&&c===u&&!t.isPending,v=dr(f)&&f===m&&!i.isPending;return e.isLoading&&!g?(0,V.jsx)(pr,{contentClassName:`text-sm text-gray-500`,children:r(`loading`)}):e.isError||!g?(0,V.jsxs)(pr,{contentClassName:`space-y-4`,children:[(0,V.jsx)(`p`,{className:`text-sm text-gray-500`,children:r(`authStatusLoadFailed`)}),(0,V.jsx)(kt,{variant:`outline`,onClick:()=>void e.refetch(),children:r(`authRetryStatus`)})]}):g.configured?(0,V.jsx)(hr,{authenticated:g.authenticated,enabled:g.enabled,username:g.username,nextPassword:f,setNextPassword:p,nextConfirmPassword:m,setNextConfirmPassword:h,canUpdatePassword:v,isUpdatingEnabled:n.isPending,isUpdatingPassword:i.isPending,isLoggingOut:a.isPending,onEnabledChange:async e=>{try{await n.mutateAsync({enabled:e})}catch{}},onPasswordUpdate:async()=>{if(fr(f,m))try{await i.mutateAsync({password:f}),p(``),h(``)}catch{}},onLogout:async()=>{try{await a.mutateAsync()}catch{}}}):(0,V.jsx)(mr,{setupUsername:o,setSetupUsername:s,setupPassword:c,setSetupPassword:l,setupConfirmPassword:u,setSetupConfirmPassword:d,canSubmitSetup:_,isPending:t.isPending,onSubmit:async()=>{if(fr(c,u))try{await t.mutateAsync({username:o.trim(),password:c}),l(``),d(``)}catch{}}})}var _r=s({SecurityConfig:()=>vr});function vr(){return(0,V.jsxs)(jt,{className:`space-y-6`,children:[(0,V.jsx)(Mt,{title:r(`authSecurityTitle`),description:r(`authSecurityDescription`)}),(0,V.jsx)(gr,{})]})}function yr(e){return e.replace(/\s+/g,` `).trim().slice(0,200)}function br(e,t){if(t===404&&e.startsWith(`/api/providers/`)&&e.endsWith(`/test`))return`Provider test endpoint is missing. This usually means nextclaw runtime version is outdated.`;if(t===401||t===403)return`Authentication failed. Check apiKey and custom headers.`;if(t===429)return`Rate limited by upstream provider. Retry later or switch model/provider.`;if(t>=500)return`Upstream service error. Retry later and inspect server logs if it persists.`}function xr(e){if(e instanceof Error){let t=e.name?.trim()||`Error`,n=e.message?.trim()||`Unknown error`;return{summary:`${t}: ${n}`,details:{errorName:t,errorMessage:n,...e.stack?.trim()?{errorStack:e.stack.trim()}:{}}}}return{summary:String(e??`Unknown error`),details:{errorName:`NonError`,errorMessage:String(e??`Unknown error`)}}}async function Sr(e,t,n={}){let r=`${e}${t}`,i=(n.method||`GET`).toUpperCase(),a;try{let e=new Headers(n.headers);!(n.body instanceof FormData)&&!e.has(`Content-Type`)&&e.set(`Content-Type`,`application/json`),a=await fetch(r,{credentials:`include`,headers:e,...n})}catch(e){let n=xr(e);return Z.reportTransportFailure(n.summary),{ok:!1,error:{code:`NETWORK_ERROR`,message:`Fetch failed on ${i} ${t} | ${n.summary}`,details:{method:i,endpoint:t,url:r,...n.details}}}}let o=await a.text(),s=null;if(o)try{s=JSON.parse(o)}catch{}if(!s){let e=o?yr(o):``,n=br(t,a.status),s=[`Non-JSON response (${a.status} ${a.statusText}) on ${i} ${t}`];return e&&s.push(`body=${e}`),n&&s.push(`hint=${n}`),{ok:!1,error:{code:`INVALID_RESPONSE`,message:s.join(` | `),details:{status:a.status,statusText:a.statusText,method:i,endpoint:t,url:r,bodySnippet:e||void 0,hint:n}}}}return a.ok,s}function Cr(e){let t=e.split(`
7
+ `),r=n.pop()??``;for(let e of n){let n=qt(e);if(n?.event!==`ncp-event`)continue;let r=Jt(n.data);r&&t(r)}return r}},Xt=class{constructor(e,t){this.requestService=e,this.baseUrl=t}list=async()=>(await this.requestService.get(`/api/agents`)).agents;create=async e=>await this.requestService.post(`/api/agents`,e);update=async(e,t)=>await this.requestService.put(`/api/agents/${encodeURIComponent(e)}`,t);delete=async e=>await this.requestService.delete(`/api/agents/${encodeURIComponent(e)}`);resolveAvatarUrl=e=>Ut(this.baseUrl,`/api/agents/${encodeURIComponent(e)}/avatar`)},Zt=class{constructor(e){this.requestService=e}fetchMeta=async()=>await this.requestService.get(`/api/app/meta`);fetchBootstrapStatus=async(e={})=>await this.requestService.get(`/api/runtime/bootstrap-status`,e)},Qt=class{constructor(e){this.requestService=e}fetchStatus=async(e={})=>await this.requestService.get(`/api/auth/status`,{...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}});setup=async e=>await this.requestService.post(`/api/auth/setup`,e);login=async e=>await this.requestService.post(`/api/auth/login`,e);logout=async()=>await this.requestService.post(`/api/auth/logout`,{});updatePassword=async e=>await this.requestService.put(`/api/auth/password`,e);updateEnabled=async e=>await this.requestService.put(`/api/auth/enabled`,e)},$t=class{constructor(e){this.requestService=e}start=async(e,t={})=>await this.requestService.post(`/api/config/channels/${encodeURIComponent(e)}/auth/start`,t);poll=async(e,t)=>await this.requestService.post(`/api/config/channels/${encodeURIComponent(e)}/auth/poll`,t);connect=async(e,t)=>await this.requestService.post(`/api/config/channels/${encodeURIComponent(e)}/auth/connect`,t)},en=class{constructor(e){this.requestService=e}fetch=async()=>await this.requestService.get(`/api/config`);fetchMeta=async()=>await this.requestService.get(`/api/config/meta`);fetchSchema=async()=>await this.requestService.get(`/api/config/schema`);updateModel=async e=>await this.requestService.put(`/api/config/model`,e);updateSearch=async e=>await this.requestService.put(`/api/config/search`,e);updateChannel=async(e,t)=>await this.requestService.put(`/api/config/channels/${encodeURIComponent(e)}`,t);updateRuntime=async e=>await this.requestService.put(`/api/config/runtime`,e);updateSecrets=async e=>await this.requestService.put(`/api/config/secrets`,e);executeAction=async(e,t={})=>await this.requestService.post(`/api/config/actions/${encodeURIComponent(e)}/execute`,t);fetchChatSessionTypes=async()=>await this.requestService.get(`/api/ncp/session-types`);fetchCronJobs=async(e={})=>await this.requestService.get(`/api/cron`,{query:e.all?{all:`1`}:void 0});deleteCronJob=async e=>await this.requestService.delete(`/api/cron/${encodeURIComponent(e)}`);setCronJobEnabled=async(e,t)=>await this.requestService.put(`/api/cron/${encodeURIComponent(e)}/enable`,t);runCronJob=async(e,t={})=>await this.requestService.post(`/api/cron/${encodeURIComponent(e)}/run`,t)},tn=class{constructor(e){this.requestService=e}fetchItems=async e=>await this.requestService.get(`${nn(e.type)}/items`,{query:rn(e)});fetchItem=async(e,t)=>await this.requestService.get(`${nn(t)}/items/${encodeURIComponent(e)}`);fetchSkillContent=async e=>await this.requestService.get(`/api/marketplace/skills/items/${encodeURIComponent(e)}/content`);fetchRecommendations=async(e,t={})=>await this.requestService.get(`${nn(e)}/recommendations`,{query:{...t.scene?.trim()?{scene:t.scene.trim()}:{},...typeof t.limit==`number`&&Number.isFinite(t.limit)?{limit:Math.max(1,Math.trunc(t.limit))}:{}}});fetchSkillScenes=async()=>await this.requestService.get(`/api/marketplace/skills/scenes`);install=async e=>await this.requestService.post(`${nn(an(e.type))}/install`,e);fetchInstalled=async e=>await this.requestService.get(`${nn(e)}/installed`);manage=async e=>await this.requestService.post(`${nn(an(e.type))}/manage`,e)};function nn(e){return e===`skill`?`/api/marketplace/skills`:`/api/marketplace/mcp`}function rn(e){let{page:t,pageSize:n,q:r,scene:i,sort:a,tag:o}=e,s={};return r?.trim()&&(s.q=r.trim()),o?.trim()&&(s.tag=o.trim()),i?.trim()&&(s.scene=i.trim()),a&&(s.sort=a),typeof t==`number`&&Number.isFinite(t)&&(s.page=Math.max(1,Math.trunc(t))),typeof n==`number`&&Number.isFinite(n)&&(s.pageSize=Math.max(1,Math.trunc(n))),Object.keys(s).length>0?s:void 0}function an(e){if(!e)throw Error(`Marketplace request type is required.`);return e}var on=class{constructor(e){this.requestService=e}fetchItems=async(e={})=>await this.requestService.get(`/api/marketplace/mcp/items`,{query:sn(e)});fetchInstalled=async()=>await this.requestService.get(`/api/marketplace/mcp/installed`);fetchItem=async e=>await this.requestService.get(`/api/marketplace/mcp/items/${encodeURIComponent(e)}`);fetchContent=async e=>await this.requestService.get(`/api/marketplace/mcp/items/${encodeURIComponent(e)}/content`);fetchRecommendations=async(e={})=>await this.requestService.get(`/api/marketplace/mcp/recommendations`,{query:{...e.scene?.trim()?{scene:e.scene.trim()}:{},...typeof e.limit==`number`&&Number.isFinite(e.limit)?{limit:Math.max(1,Math.trunc(e.limit))}:{}}});install=async e=>await this.requestService.post(`/api/marketplace/mcp/install`,e);manage=async e=>await this.requestService.post(`/api/marketplace/mcp/manage`,e);doctor=async e=>await this.requestService.post(`/api/marketplace/mcp/doctor`,{name:e})};function sn(e){let{page:t,pageSize:n,q:r,sort:i,tag:a}=e,o={};return r?.trim()&&(o.q=r.trim()),a?.trim()&&(o.tag=a.trim()),i&&(o.sort=i),typeof t==`number`&&Number.isFinite(t)&&(o.page=Math.max(1,Math.trunc(t))),typeof n==`number`&&Number.isFinite(n)&&(o.pageSize=Math.max(1,Math.trunc(n))),Object.keys(o).length>0?o:void 0}var cn=`x-nextclaw-panel-bridge-session`;function ln(e){return e?{[cn]:e}:void 0}var un=class{constructor(e){this.requestService=e}listPanelApps=async()=>await this.requestService.get(`/api/panel-apps`);updatePanelAppPreferences=async(e,t)=>await this.requestService.request(`/api/panel-apps/${encodeURIComponent(e)}/preferences`,{method:`PATCH`,body:t});recordPanelAppOpened=async e=>await this.requestService.post(`/api/panel-apps/${encodeURIComponent(e)}/open`);deletePanelApp=async e=>await this.requestService.delete(`/api/panel-apps/${encodeURIComponent(e)}`);createBridgeSession=async e=>await this.requestService.post(`/api/panel-app-bridge-sessions`,e);deleteBridgeSession=async e=>await this.requestService.delete(`/api/panel-app-bridge-sessions/${encodeURIComponent(e)}`);grantClient=async e=>await this.requestService.post(`/api/panel-app-client-grants/${encodeURIComponent(e)}`,{});revokeClient=async e=>await this.requestService.delete(`/api/panel-app-client-grants/${encodeURIComponent(e)}`);sendAgentMessage=async(e,t={})=>await this.requestService.post(`/api/panel-app-agent/send`,e,{headers:ln(t.bridgeSessionToken)});generateAgentObject=async(e,t={})=>await this.requestService.post(`/api/panel-app-agent/generate-object`,e,{headers:ln(t.bridgeSessionToken)});grantAgentCapability=async(e,t={})=>await this.requestService.post(`/api/panel-app-agent-capabilities/${encodeURIComponent(e)}/grant`,{},{headers:ln(t.bridgeSessionToken)})},dn=class{constructor(e){this.requestService=e}list=async()=>await this.requestService.get(`/api/providers`);listTemplates=async()=>await this.requestService.get(`/api/provider-templates`);update=async(e,t)=>await this.requestService.put(`/api/providers/${encodeURIComponent(e)}`,t);create=async(e={})=>await this.requestService.post(`/api/providers`,e);delete=async e=>await this.requestService.delete(`/api/providers/${encodeURIComponent(e)}`);testConnection=async(e,t)=>await this.requestService.post(`/api/providers/${encodeURIComponent(e)}/test`,t);startAuth=async(e,t={})=>await this.requestService.post(`/api/providers/${encodeURIComponent(e)}/auth/start`,t);pollAuth=async(e,t)=>await this.requestService.post(`/api/providers/${encodeURIComponent(e)}/auth/poll`,t);importAuthFromCli=async e=>await this.requestService.post(`/api/providers/${encodeURIComponent(e)}/auth/import-cli`,{})},fn=class{baseUrl;transport;webSocketFactory;constructor(e){this.options=e,this.baseUrl=e.baseUrl,this.transport=e.transport,this.webSocketFactory=e.webSocketFactory}subscribe=(e,t={})=>{if(this.transport?.subscribe){let t=this.transport.subscribe(e);return{close:()=>{t()}}}let n=null,r=null,i=!1,a=Math.max(200,t.reconnectDelayMs??1e3),o=()=>{r!==null&&(clearTimeout(r),r=null)},s=t=>{e(t)},c=()=>{try{n=this.createSocket(Gt(this.baseUrl,`/ws`))}catch(e){t.onError?.(e),i||(r=setTimeout(c,a));return}n.onopen=()=>{s({type:`connection.open`})},n.onmessage=e=>{let t=this.parseEvent(e.data);t&&s(t)},n.onerror=e=>{t.onError?.(e),s({type:`connection.error`,payload:{message:`WebSocket error`}})},n.onclose=()=>{s({type:`connection.close`}),n=null,i||(o(),r=setTimeout(c,a))}};return c(),{close:()=>{i=!0,o(),n?.close(),n=null}}};createSocket=e=>{if(this.webSocketFactory)return this.webSocketFactory(e);if(typeof globalThis.WebSocket!=`function`)throw Error(`WebSocket is unavailable. Provide webSocketFactory when creating the client.`);return new globalThis.WebSocket(e)};parseEvent=e=>{if(typeof e!=`string`)return null;try{let t=JSON.parse(e);return t&&typeof t==`object`&&`type`in t?t:null}catch{return null}}},pn=class{constructor(e){this.requestService=e}fetchStatus=async()=>await this.requestService.get(`/api/remote/status`);fetchDoctor=async()=>await this.requestService.get(`/api/remote/doctor`);login=async e=>await this.requestService.post(`/api/remote/login`,e);startBrowserAuth=async(e={})=>await this.requestService.post(`/api/remote/auth/start`,e);pollBrowserAuth=async e=>await this.requestService.post(`/api/remote/auth/poll`,e);logout=async()=>await this.requestService.post(`/api/remote/logout`,{});updateAccountProfile=async e=>await this.requestService.put(`/api/remote/account/profile`,e);updateSettings=async e=>await this.requestService.put(`/api/remote/settings`,e);controlService=async e=>await this.requestService.post(`/api/remote/service/${e}`,{})},Y=class extends Error{status;code;details;constructor(e){let{code:t,details:n,message:r,status:i}=e;super(r),this.name=`NextClawClientError`,this.status=i,this.code=t,this.details=n}};function mn(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function hn(e,t){return mn(e)?e[t]:void 0}var gn=class{baseUrl;fetchImpl;requestTimeoutMs;defaultHeaders;transport;constructor(e){this.options=e;let{baseUrl:t,fetchImpl:n,headers:r,requestTimeoutMs:i,token:a}=e;this.baseUrl=t,this.fetchImpl=Kt(n),this.requestTimeoutMs=Math.max(1e3,i??15e3),this.transport=e.transport,this.defaultHeaders={Accept:`application/json`,...r??{},...a?{Authorization:`Bearer ${a}`}:{}}}request=async(e,t={})=>{let{body:n,headers:r,method:i,query:a,signal:o,timeoutMs:s}=t;if(this.transport)return await this.requestWithTransport(e,t);let c=new AbortController,l=Math.max(1e3,s??this.requestTimeoutMs),u=this.bindAbortSignal(c,o),d=setTimeout(()=>c.abort(),l),f={...this.defaultHeaders,...r??{}},p=this.normalizeRequestBody(n,f);try{let t=await this.fetchImpl(Ut(this.baseUrl,Wt(e,this.serializeQuery(a))),{method:i??`GET`,headers:f,body:p,signal:c.signal}),n=await t.json();if(!t.ok){let e=this.extractApiError(n);throw new Y({message:e.message,status:t.status,code:e.code,details:e.details})}if(!this.isApiResponse(n))throw new Y({message:`Unexpected NextClaw API response shape.`,status:t.status});if(!n.ok)throw new Y({message:n.error.message,status:t.status,code:n.error.code,details:n.error.details});return n.data}catch(e){throw e instanceof Y?e:e instanceof Error&&e.name===`AbortError`?new Y({message:`NextClaw API request timed out after ${l}ms.`}):new Y({message:e instanceof Error?e.message:`NextClaw API request failed.`})}finally{o?.removeEventListener(`abort`,u),clearTimeout(d)}};bindAbortSignal=(e,t)=>{let n=()=>e.abort(t?.reason);return t?t.aborted?(e.abort(t.reason),n):(t.addEventListener(`abort`,n,{once:!0}),n):n};requestWithTransport=async(e,t)=>{let{body:n,headers:r,method:i,query:a,signal:o,timeoutMs:s}=t,{transport:c}=this;if(!c)throw new Y({message:`NextClaw transport is not configured.`});try{return await c.request({method:i??`GET`,path:e,...n===void 0?{}:{body:n},...a?{query:a}:{},...r?{headers:r}:{},...o?{signal:o}:{},...s===void 0?{}:{timeoutMs:s}})}catch(e){if(e instanceof Y)throw e;let t=hn(e,`code`),n=hn(e,`details`),r=hn(e,`status`);throw new Y({message:e instanceof Error?e.message:`NextClaw API request failed.`,code:typeof t==`string`?t:void 0,details:mn(n)?n:void 0,status:typeof r==`number`?r:void 0})}};get=async(e,t={})=>await this.request(e,{...t,method:`GET`});post=async(e,t,n={})=>await this.request(e,{...n,method:`POST`,...t===void 0?{}:{body:t}});put=async(e,t,n={})=>await this.request(e,{...n,method:`PUT`,...t===void 0?{}:{body:t}});delete=async(e,t={})=>await this.request(e,{...t,method:`DELETE`});upload=async(e,t,n={})=>{let{headers:r,signal:i,timeoutMs:a}=n;if(this.transport?.upload)return await this.transport.upload({path:e,formData:t,...r?{headers:r}:{},...i?{signal:i}:{},...a===void 0?{}:{timeoutMs:a}});let o=new AbortController,s=Math.max(1e3,a??this.requestTimeoutMs),c=()=>o.abort(i?.reason);i&&(i.aborted?o.abort(i.reason):i.addEventListener(`abort`,c,{once:!0}));let l=setTimeout(()=>o.abort(),s);try{let n=await this.fetchImpl(Ut(this.baseUrl,e),{method:`POST`,headers:{Accept:`application/json`,..._n(this.options.token)??{},...this.options.headers??{},...r??{}},body:t,signal:o.signal}),i=await n.json();if(!n.ok){let e=this.extractApiError(i);throw new Y({message:e.message,status:n.status,code:e.code,details:e.details})}if(!this.isApiResponse(i)||!i.ok)throw new Y({message:`Unexpected NextClaw upload response shape.`,status:n.status});return i.data}catch(e){throw e instanceof Y?e:e instanceof Error&&e.name===`AbortError`?new Y({message:`NextClaw API upload timed out after ${s}ms.`}):new Y({message:e instanceof Error?e.message:`NextClaw API upload failed.`})}finally{i?.removeEventListener(`abort`,c),clearTimeout(l)}};isApiResponse=e=>typeof e==`object`&&!!e&&`ok`in e;extractApiError=e=>{if(this.isApiResponse(e)&&!e.ok)return e.error;if(typeof e==`object`&&e&&`message`in e){let t=e;return{code:typeof t.code==`string`?t.code:`HTTP_ERROR`,message:typeof t.message==`string`?t.message:`NextClaw API request failed.`,details:t.details!==null&&typeof t.details==`object`?t.details:void 0}}return{code:`HTTP_ERROR`,message:`NextClaw API request failed.`}};normalizeRequestBody=(e,t)=>{if(e!==void 0)return e instanceof FormData||e instanceof URLSearchParams||e instanceof Blob||e instanceof ArrayBuffer?e:typeof e==`string`?(!(`Content-Type`in t)&&!(`content-type`in t)&&(t[`Content-Type`]=`application/json`),e):(!(`Content-Type`in t)&&!(`content-type`in t)&&(t[`Content-Type`]=`application/json`),JSON.stringify(e))};serializeQuery=e=>{if(!e)return;if(e instanceof URLSearchParams)return e;let t=new URLSearchParams;for(let[n,r]of Object.entries(e)){let e=Array.isArray(r)?r:[r];for(let r of e)r!=null&&t.append(n,String(r))}return t}};function _n(e){return e?{Authorization:`Bearer ${e}`}:null}var vn=class{constructor(e){this.requestService=e}fetch=async()=>await this.requestService.get(`/api/runtime/control`);startService=async()=>await this.requestService.post(`/api/runtime/control/start-service`,{});restartService=async()=>await this.requestService.post(`/api/runtime/control/restart-service`,{});stopService=async()=>await this.requestService.post(`/api/runtime/control/stop-service`,{})},yn=class{constructor(e){this.requestService=e}fetch=async()=>await this.requestService.get(`/api/runtime/update`);check=async()=>await this.requestService.post(`/api/runtime/update/check`,{});download=async()=>await this.requestService.post(`/api/runtime/update/download`,{});apply=async()=>await this.requestService.post(`/api/runtime/update/apply`,{});updatePreferences=async e=>await this.requestService.put(`/api/runtime/update/preferences`,e);updateChannel=async e=>await this.requestService.put(`/api/runtime/update/channel`,{channel:e})},bn=class{constructor(e){this.requestService=e}browse=async e=>{let t=typeof e?.path==`string`?e.path.trim():``;return await this.requestService.get(`/api/server-paths/browse`,{query:{...t?{path:t}:{},...e?.includeFiles?{includeFiles:`1`}:{}}})};read=async e=>{let t=e.path.trim(),n=typeof e.basePath==`string`?e.basePath.trim():``;return await this.requestService.get(`/api/server-paths/read`,{query:{path:t,...n?{basePath:n}:{}}})}},xn=`x-nextclaw-panel-bridge-session`;function Sn(e){return e?{[xn]:e}:void 0}var Cn=class{constructor(e){this.requestService=e}listServiceApps=async()=>await this.requestService.get(`/api/service-apps`);getServiceApp=async e=>await this.requestService.get(`/api/service-apps/${encodeURIComponent(e)}`);restartServiceApp=async e=>await this.requestService.post(`/api/service-apps/${encodeURIComponent(e)}/restart`);deleteServiceApp=async e=>await this.requestService.delete(`/api/service-apps/${encodeURIComponent(e)}`);listServiceActions=async(e={})=>{let t=e.appId?`?${new URLSearchParams({appId:e.appId}).toString()}`:``;return await this.requestService.get(`/api/service-actions${t}`,{headers:Sn(e.bridgeSessionToken)})};discoverServiceAppActions=async e=>await this.requestService.post(`/api/service-apps/${encodeURIComponent(e)}/actions/discover`,{});invokeServiceAction=async(e,t,n={})=>await this.requestService.post(`/api/service-actions/${encodeURIComponent(e)}/invoke`,{input:t??{}},{headers:Sn(n.bridgeSessionToken)});grantServiceAction=async(e,t={})=>await this.requestService.post(`/api/service-actions/${encodeURIComponent(e)}/grant`,{},{headers:Sn(t.bridgeSessionToken)});grantServiceActions=async(e,t={})=>await this.requestService.post(`/api/service-action-grants`,{actionIds:e},{headers:Sn(t.bridgeSessionToken)});listServiceActionGrants=async()=>await this.requestService.get(`/api/service-action-grants`);revokeServiceAction=async(e,t={})=>await this.requestService.delete(`/api/service-actions/${encodeURIComponent(e)}/grant`,{headers:Sn(t.bridgeSessionToken)});revokeServiceActionGrant=async e=>{let t=new URLSearchParams({surface:e.caller.surface,appId:e.caller.appId});return await this.requestService.delete(`/api/service-action-grants/${encodeURIComponent(e.actionId)}?${t.toString()}`)}},wn=class{constructor(e,t){this.requestService=e,this.eventBus=t}list=async e=>{let{limit:t,peerId:n}=e??{},r=new URLSearchParams;typeof t==`number`&&Number.isFinite(t)&&r.set(`limit`,String(Math.max(1,Math.trunc(t))));let i=n?.trim();return i&&r.set(`peerId`,i),await this.requestService.get(`/api/ncp/sessions`,{...r.size>0?{query:r}:{}})};get=async e=>await this.requestService.get(`/api/ncp/sessions/${encodeURIComponent(e)}`);listMessages=async(e,t=200)=>await this.requestService.get(`/api/ncp/sessions/${encodeURIComponent(e)}/messages`,{query:{limit:Math.max(1,Math.trunc(t))}});listSkills=async(e,t)=>await this.requestService.get(`/api/ncp/sessions/${encodeURIComponent(e)}/skills`,{query:t?.projectRoot?.trim()?{projectRoot:t.projectRoot.trim()}:void 0});update=async(e,t)=>await this.requestService.put(`/api/ncp/sessions/${encodeURIComponent(e)}`,t);delete=async e=>await this.requestService.delete(`/api/ncp/sessions/${encodeURIComponent(e)}`);uploadAssets=async e=>{let t=new FormData;for(let n of e)t.append(`files`,n);return await this.requestService.upload(`/api/ncp/assets`,t)};subscribe=(e,t={})=>({close:this.eventBus.subscribeAll(t=>{e(t)})})},Tn=class{baseUrl;agentRuns;app;agents;auth;channelAuth;config;eventBus;marketplace;mcpMarketplace;panelApps;providers;realtime;remote;runtimeControl;runtimeUpdate;serverPaths;serviceApps;sessions;constructor(e){this.baseUrl=Ht(e.baseUrl);let t={...e,baseUrl:this.baseUrl},n=new gn(t);this.realtime=new fn(t);let r=null;this.eventBus=new Bt({onFirstSubscriber:()=>{r??=this.realtime.subscribe(e=>{this.eventBus.emitEnvelope({type:e.type,payload:`payload`in e?e.payload:void 0,emittedAt:`emittedAt`in e?e.emittedAt:new Date().toISOString(),source:`source`in e?e.source:`realtime`})})},onNoSubscribers:()=>{r?.close(),r=null}}),this.agentRuns=new Yt(n,t),this.app=new Zt(n),this.agents=new Xt(n,this.baseUrl),this.auth=new Qt(n),this.channelAuth=new $t(n),this.config=new en(n),this.marketplace=new tn(n),this.mcpMarketplace=new on(n),this.panelApps=new un(n),this.providers=new dn(n),this.remote=new pn(n),this.runtimeControl=new vn(n),this.runtimeUpdate=new yn(n),this.serverPaths=new bn(n),this.serviceApps=new Cn(n),this.sessions=new wn(n,this.eventBus)}},En=`http://127.0.0.1:55667`,Dn=(()=>{let e=(void 0)?.trim();return e?e.replace(/\/$/,``):typeof window<`u`&&window.location?.origin?window.location.origin:En})(),On={"Use this page to manage the local NextClaw service. Closing the browser does not stop the service.":`runtimeControlManagedLocalMessage`,"This page is served by the running local service. Closing the browser does not stop it.":`runtimeControlManagedLocalHint`,"This page is served by the running local service.":`runtimeControlManagedLocalHintShort`,"This page is already hosted by the running local service.":`runtimeControlStartUnavailableHosted`,"App restart is only available in the desktop shell.":`runtimeControlRestartAppDesktopOnly`,"The local service is not running.":`runtimeControlServiceNotRunning`,"The local service is already stopped.":`runtimeControlServiceAlreadyStopped`,"Managed service started.":`runtimeControlManagedServiceStarted`,"Managed service start scheduled.":`runtimeControlManagedServiceStartScheduled`,"Restart scheduled. This page may disconnect for a few seconds.":`runtimeControlRestartScheduled`,"Stop scheduled. This page will disconnect shortly.":`runtimeControlStopScheduled`,"runtime healthy":`runtimeControlHealthy`};function kn(e){return e.activeSystemAction?`service-transitioning`:e.lifecyclePhase}function An(e){return e===`ready`?`connected`:e===`startup-failed`||e===`stalled`?`disconnected`:`connecting`}function jn(e){let t=kn(e);return{...e,phase:t,connectionStatus:An(t)}}function Mn(e){return e===`start-service`?`starting-service`:e===`stop-service`?`stopping-service`:e===`restart-service`?`restarting-service`:`restarting-app`}function Nn(e){return e===`start-service`?`starting`:e===`stop-service`?`stopping`:e===`restart-service`?`restarting`:null}function X(e){if(!e)return null;let t=On[e.trim()];return t?r(t):e}function Pn(e){let{action:t,message:n}=e;return{action:t,lifecycle:Mn(t),serviceState:Nn(t),message:n}}function Fn(e){if(e.runtimeControlError)return{tone:`inactive`,title:r(`runtimeControlLoadFailed`),description:e.runtimeControlError,reasonLines:[],actionLabel:null,isBusy:!1};if(!e.runtimeControlView)return{tone:`inactive`,title:r(`runtimeStatusLoadingTitle`),description:r(`runtimeStatusLoadingDescription`),reasonLines:[],actionLabel:null,isBusy:!!e.activeSystemAction};if(e.activeSystemAction)return{tone:`attention`,title:r(`runtimeControlTitle`),description:X(e.activeSystemAction.message)||X(e.runtimeControlView.message)||r(`runtimeControlDescription`),reasonLines:[],actionLabel:null,isBusy:!0};let t=e.runtimeControlView;return t.pendingRestart?{tone:`attention`,title:r(`runtimeStatusPendingRestartTitle`),description:r(`runtimeStatusPendingRestartDescription`),reasonLines:t.pendingRestart.changedPaths.length>0?t.pendingRestart.changedPaths.map(e=>r(`runtimeStatusPendingRestartReasonItem`).replace(`{path}`,e)):[t.pendingRestart.message],actionLabel:t.canRestartService.available?r(`runtimeStatusRestartAction`):null,isBusy:!1}:{tone:t.lifecycle===`healthy`?`healthy`:`inactive`,title:r(`runtimeStatusHealthyTitle`),description:r(`runtimeStatusHealthyDescription`),reasonLines:[],actionLabel:null,isBusy:!1}}function In(e){let t=e.activeSystemAction,n=e.runtimeControlView;return{controlView:n,visibleLifecycle:t?.lifecycle??n?.lifecycle??`healthy`,visibleServiceState:t?.serviceState??n?.serviceState??`unknown`,visibleMessage:X(t?.message)||X(e.lastSystemActionError)||X(n?.message)||r(`runtimeControlDescription`),busyAction:t?.action??null,busy:!!t,pendingRestart:n?.pendingRestart??null,errorMessage:X(e.lastSystemActionError)||X(e.runtimeControlError)||null}}var Ln={lifecyclePhase:`cold-starting`,hasReachedReady:!1,lastReadyAt:null,recoveryStartedAt:null,bootstrapStatus:null,lastError:null,lastTransportError:null,runtimeControlView:null,runtimeControlError:null,activeSystemAction:null,lastSystemActionError:null},Rn=o(e=>({state:Ln,patchState:t=>e(e=>({state:{...e.state,...t}}))}));function zn(e){if(e.length===0)throw Error(`AdaptiveCadence requires at least one stage.`);for(let t of e)if(t.delaysMs.length===0)throw Error(`AdaptiveCadence stage requires at least one delay.`)}var Bn=class{constructor(e){this.options=e,this.attempt=0,this.startedAt=null,this.lastFailureAt=null,this.lastSuccessAt=null,this.manualTriggerPending=!1,this.completed=!1,this.recordFailure=()=>{let e=this.clock();this.completed=!1,this.manualTriggerPending=!1,this.startedAt=this.startedAt??e,this.lastFailureAt=e,this.attempt+=1},this.recordSuccess=()=>{this.lastSuccessAt=this.clock(),this.attempt=0,this.startedAt=null,this.lastFailureAt=null,this.manualTriggerPending=!1,this.completed=!0},this.reset=()=>{this.attempt=0,this.startedAt=null,this.lastFailureAt=null,this.lastSuccessAt=null,this.manualTriggerPending=!1,this.completed=!1},this.requestManualTrigger=()=>{this.completed=!1,this.manualTriggerPending=!0},this.hasManualTrigger=()=>this.manualTriggerPending,this.getNextDelay=(e={})=>{if(this.manualTriggerPending)return e.consumeManualTrigger&&(this.manualTriggerPending=!1),this.options.manualTriggerDelayMs;if(this.completed)return this.options.successDelayMs;if(this.startedAt===null)return this.options.idleDelayMs;let t=this.resolveStage(this.clock()-this.startedAt);return t.delaysMs[Math.min(this.attempt-1,t.delaysMs.length-1)]},this.getSnapshot=()=>({attempt:this.attempt,startedAt:this.startedAt,lastFailureAt:this.lastFailureAt,lastSuccessAt:this.lastSuccessAt,manualTriggerPending:this.manualTriggerPending,completed:this.completed}),this.resolveStage=e=>this.options.stages.find(t=>t.untilElapsedMs===void 0||e<t.untilElapsedMs)??this.options.stages[this.options.stages.length-1],zn(e.stages),this.clock=e.clock??(()=>Date.now())}},Vn=3e4,Hn={idleDelayMs:1e3,manualTriggerDelayMs:0,successDelayMs:!1,stages:[{untilElapsedMs:3e4,delaysMs:[500,1e3,2e3,4e3,5e3]},{untilElapsedMs:5*6e4,delaysMs:[1e4,15e3,3e4]},{delaysMs:[6e4]}]};function Un(e){return e instanceof Error?e.message:String(e??``)}function Wn(e){return e&&(e.ncpAgent.error?.trim()||e.lastError?.trim())||null}function Gn(e){return r(e===`start-service`?`runtimeControlStartingServiceHelp`:e===`restart-service`?`runtimeControlRestartingServiceHelp`:e===`stop-service`?`runtimeControlStoppingServiceHelp`:`runtimeControlRestartingAppHelp`)}var Z=new class{constructor(){this.recoveryTimeoutId=null,this.runtimeBootstrapProbeCadence=new Bn(Hn),this.getRuntimeBootstrapPollInterval=e=>{let{lifecyclePhase:t,activeSystemAction:n}=this.getState(),r=t===`recovering`||t===`stalled`||n?.lifecycle===`recovering`;return this.runtimeBootstrapProbeCadence.hasManualTrigger()?this.runtimeBootstrapProbeCadence.getNextDelay({consumeManualTrigger:!0}):!r&&e?.ncpAgent.state===`ready`?!1:this.runtimeBootstrapProbeCadence.getNextDelay({consumeManualTrigger:!0})},this.getRuntimeControl=async()=>this.decorateForCurrentEnvironment(await ma()),this.reportBootstrapStatus=e=>{let t=this.getState(),n=Wn(e);if(e.ncpAgent.state===`ready`){this.transitionToReady(e);return}if(!t.hasReachedReady){if(e.ncpAgent.state===`error`||e.phase===`error`){this.transitionToStartupFailed(n,e);return}this.transitionToColdStarting(e);return}this.transitionToRecovering(n,e)},this.reportBootstrapQueryError=e=>{let t=Un(e).trim();if(t&&!this.reportTransportFailure(t)){if(this.getState().hasReachedReady){this.transitionToRecovering(t);return}this.transitionToStartupFailed(t)}},this.reportTransportFailure=e=>{let t=Un(e).trim();return Wr(t)?this.getState().hasReachedReady?(this.transitionToRecovering(t),!0):(this.runtimeBootstrapProbeCadence.recordFailure(),this.patchState({lastTransportError:t}),!0):!1},this.handleConnectionInterrupted=e=>{let t=this.getState(),n=e?.trim()||null;if(!t.hasReachedReady){this.runtimeBootstrapProbeCadence.recordFailure(),n&&this.patchState({lastTransportError:n});return}this.transitionToRecovering(n)},this.handleConnectionRestored=()=>{let e=this.getState();e.bootstrapStatus?.ncpAgent.state===`ready`&&this.transitionToReady(e.bootstrapStatus)},this.reportRuntimeControlView=e=>{this.patchState({runtimeControlView:e,runtimeControlError:null})},this.reportRuntimeControlError=e=>{let t=Un(e).trim();t&&this.patchState({runtimeControlError:t})},this.runRuntimeControlAction=async e=>{this.patchState({activeSystemAction:Pn({action:e,message:Gn(e)}),lastSystemActionError:null});try{let t=await this.executeRuntimeControlAction(e);if(e===`restart-app`)return t;if(e===`stop-service`)return await this.refreshRuntimeControlView(),this.clearActiveSystemAction(),t;this.patchState({activeSystemAction:{action:e,lifecycle:`recovering`,serviceState:null,message:r(`runtimeControlRecoveringHelp`)}}),this.runtimeBootstrapProbeCadence.requestManualTrigger();let n=await this.waitForRecovery();return this.syncRuntimeControlQueryCache(n),this.reportRuntimeControlView(n),this.clearActiveSystemAction(),t}catch(t){let n=t instanceof Error?t.message:r(`runtimeControlActionFailed`);throw this.patchState({activeSystemAction:{action:e,lifecycle:`failed`,serviceState:e===`stop-service`?`running`:e===`restart-app`?null:`unknown`,message:n},lastSystemActionError:n}),t}},this.getStatusView=()=>jn(this.getState()),this.requestRuntimeBootstrapProbeNow=()=>{this.runtimeBootstrapProbeCadence.requestManualTrigger(),wt.refetchQueries({queryKey:[`runtime-bootstrap-status`]})},this.resetForTests=()=>{this.clearRecoveryTimeout(),this.runtimeBootstrapProbeCadence.reset(),Rn.setState({state:Ln})},this.getState=()=>Rn.getState().state,this.patchState=e=>{Rn.getState().patchState(e)},this.transitionToColdStarting=e=>{this.runtimeBootstrapProbeCadence.recordFailure(),this.clearRecoveryTimeout(),this.patchState({lifecyclePhase:`cold-starting`,recoveryStartedAt:null,bootstrapStatus:e,lastError:null})},this.transitionToStartupFailed=(e,t)=>{this.runtimeBootstrapProbeCadence.recordFailure(),this.clearRecoveryTimeout(),this.patchState({lifecyclePhase:`startup-failed`,recoveryStartedAt:null,bootstrapStatus:t??this.getState().bootstrapStatus,lastError:e})},this.transitionToRecovering=(e,t)=>{this.runtimeBootstrapProbeCadence.recordFailure();let n=this.getState();if(!n.hasReachedReady){this.patchState({lastTransportError:e?.trim()||n.lastTransportError});return}n.lifecyclePhase!==`recovering`&&n.lifecyclePhase!==`stalled`&&(this.clearRecoveryTimeout(),this.recoveryTimeoutId=window.setTimeout(()=>{this.recoveryTimeoutId=null,this.getState().lifecyclePhase===`recovering`&&this.patchState({lifecyclePhase:`stalled`})},Vn)),this.patchState({lifecyclePhase:n.lifecyclePhase===`stalled`?`stalled`:`recovering`,recoveryStartedAt:n.recoveryStartedAt??Date.now(),bootstrapStatus:t??n.bootstrapStatus,lastError:e?.trim()||n.lastError,lastTransportError:e?.trim()||n.lastTransportError})},this.transitionToReady=e=>{this.runtimeBootstrapProbeCadence.recordSuccess();let t=this.getState(),n=t.lifecyclePhase===`recovering`||t.lifecyclePhase===`stalled`;this.clearRecoveryTimeout(),this.patchState({lifecyclePhase:`ready`,hasReachedReady:!0,lastReadyAt:Date.now(),recoveryStartedAt:null,bootstrapStatus:e,lastError:null,lastTransportError:null}),n&&wt.refetchQueries({type:`active`})},this.executeRuntimeControlAction=async e=>{let t=this.getDesktopBridge();if(e===`restart-service`&&t&&typeof t.restartService==`function`){let e=await t.restartService();return{accepted:e.accepted,action:`restart-service`,lifecycle:e.lifecycle,message:e.message}}if(e===`start-service`)return await ha();if(e===`stop-service`)return await _a();if(e===`restart-app`){if(!t||typeof t.restartApp!=`function`)throw Error(r(`runtimeRestartAppUnavailable`));let e=await t.restartApp();return{accepted:e.accepted,action:`restart-app`,lifecycle:e.lifecycle,message:e.message}}return await ga()},this.waitForRecovery=async()=>{let e=Date.now()+25e3,t=null;for(;Date.now()<e;)try{return await this.getRuntimeControl()}catch(e){t=e,await new Promise(e=>{window.setTimeout(e,1500)})}throw t instanceof Error?t:Error(r(`runtimeRecoveryTimedOut`))},this.refreshRuntimeControlView=async()=>{try{let e=await this.getRuntimeControl();this.syncRuntimeControlQueryCache(e),this.reportRuntimeControlView(e)}catch(e){this.reportRuntimeControlError(e)}},this.syncRuntimeControlQueryCache=e=>{wt.setQueryData([`runtime-control`],e)},this.clearActiveSystemAction=()=>{this.patchState({activeSystemAction:null,lastSystemActionError:null})},this.clearRecoveryTimeout=()=>{this.recoveryTimeoutId!==null&&(window.clearTimeout(this.recoveryTimeoutId),this.recoveryTimeoutId=null)},this.decorateForCurrentEnvironment=e=>{let t=this.getDesktopBridge();return!t||typeof t.restartApp!=`function`?e:{...e,environment:`desktop-embedded`,serviceState:`running`,canStartService:{available:!1,requiresConfirmation:!1,impact:`none`},canStopService:{available:!1,requiresConfirmation:!0,impact:`brief-ui-disconnect`},canRestartApp:{available:!0,requiresConfirmation:!0,impact:`full-app-relaunch`},ownerLabel:r(`runtimeControlEnvironmentDesktop`),managementHint:r(`runtimeControlDesktopServiceHint`)}},this.getDesktopBridge=()=>typeof window>`u`?null:window.nextclawDesktop??null}};function Kn(){let e=Je({queryKey:[`runtime-bootstrap-status`],queryFn:()=>si({timeoutMs:5e3}),refetchInterval:e=>Z.getRuntimeBootstrapPollInterval(e.state.data),retry:!1}),t=Je({queryKey:[`runtime-control`],queryFn:async()=>await Z.getRuntimeControl(),staleTime:5e3});(0,B.useEffect)(()=>{e.data&&Z.reportBootstrapStatus(e.data)},[e.data]),(0,B.useEffect)(()=>{e.error&&Z.reportBootstrapQueryError(e.error)},[e.error]),(0,B.useEffect)(()=>{t.data&&Z.reportRuntimeControlView(t.data)},[t.data]),(0,B.useEffect)(()=>{t.error&&Z.reportRuntimeControlError(t.error)},[t.error])}function qn(){return jn(Rn(e=>e.state))}function Jn(){return Fn(Rn(e=>e.state))}function Yn(){return In(Rn(e=>e.state))}var Q=o(()=>({supported:!1,initialized:!1,busyAction:null,snapshot:null})),Xn=class{constructor(e){this.desktopApi=e,this.kind=`desktop-bridge`,this.subscribe=e=>this.desktopApi.onUpdateStateChanged(e),this.getState=async()=>await this.desktopApi.getUpdateState(),this.checkForUpdates=async()=>await this.desktopApi.checkForUpdates(),this.downloadUpdate=async()=>await this.desktopApi.downloadUpdate(),this.applyDownloadedUpdate=async()=>await this.desktopApi.applyDownloadedUpdate(),this.updatePreferences=async e=>await this.desktopApi.updatePreferences(e),this.updateChannel=async e=>await this.desktopApi.updateChannel(e)}},Zn=class{constructor(){this.kind=`runtime-host`,this.getState=async()=>await va(),this.checkForUpdates=async()=>await ya(),this.downloadUpdate=async()=>await ba(),this.applyDownloadedUpdate=async()=>await xa(),this.updatePreferences=async e=>await Sa(e),this.updateChannel=async e=>await Ca(e)}},Qn=new class{constructor(){this.unsubscribe=null,this.subscriptionCount=0,this.source=null,this.start=async()=>{this.subscriptionCount+=1;let e=this.resolveSource();if(this.source=e,!e){Q.setState({supported:!1,initialized:!0,snapshot:null});return}e.kind===`desktop-bridge`&&!this.unsubscribe&&(this.unsubscribe=e.subscribe(e=>{Q.setState({supported:!0,initialized:!0,snapshot:e})})),Q.setState({supported:!0,initialized:!1});try{let t=await e.getState();Q.setState({supported:!0,initialized:!0,snapshot:t})}catch(t){if(e.kind===`runtime-host`&&this.isUnsupportedError(t)){Q.setState({supported:!1,initialized:!0,snapshot:null});return}Q.setState({supported:!0,initialized:!0}),W.error(`${r(`runtimeUpdatesLoadFailed`)}: ${this.getErrorMessage(t)}`)}},this.stop=()=>{this.subscriptionCount=Math.max(0,this.subscriptionCount-1),!(this.subscriptionCount>0)&&(this.unsubscribe?.(),this.unsubscribe=null,this.source=null)},this.reportSnapshot=e=>{this.source?.kind!==`desktop-bridge`&&Q.setState({supported:!0,initialized:!0,snapshot:e})},this.refreshAfterRealtimeReconnect=async()=>{this.source?.kind===`runtime-host`&&await this.refreshSnapshot()},this.checkForUpdates=async()=>{let e;try{e=await this.runSnapshotCommand(`checking`,r(`runtimeUpdatesCheckFailed`),async e=>await e.checkForUpdates())}catch{return}if(e.status===`up-to-date`){W.success(r(`runtimeUpdatesAlreadyLatest`));return}if(e.status===`update-available`){W.success(r(`runtimeUpdatesAvailable`).replace(`{version}`,e.availableVersion??r(`runtimeUpdatesUnknownVersion`)));return}e.status===`downloaded`&&W.success(r(`runtimeUpdatesReadyToApply`))},this.downloadUpdate=async()=>{try{await this.runSnapshotCommand(`downloading`,r(`runtimeUpdatesDownloadFailed`),async e=>await e.downloadUpdate())}catch{return}},this.applyDownloadedUpdate=async()=>{try{await this.runSnapshotCommand(`applying`,r(`runtimeUpdatesApplyFailed`),async e=>await e.applyDownloadedUpdate())}catch{return}},this.updatePreferences=async e=>{try{await this.runSnapshotCommand(`saving-preferences`,r(`runtimeUpdatesPreferencesFailed`),async t=>await t.updatePreferences(e))}catch{return}},this.updateChannel=async e=>{if(Q.getState().snapshot?.channel===e)return;let t;try{t=await this.runSnapshotCommand(`switching-channel`,r(`runtimeUpdatesChannelChangeFailed`),async t=>await t.updateChannel(e))}catch{return}if(t.status===`update-available`&&t.availableVersion){W.success(r(`runtimeUpdatesChannelChangedWithUpdate`).replace(`{channel}`,this.getChannelLabel(e)).replace(`{version}`,t.availableVersion));return}W.success(r(`runtimeUpdatesChannelChanged`).replace(`{channel}`,this.getChannelLabel(e)))},this.refreshSnapshot=async()=>{if(!(!this.source||this.source.kind!==`runtime-host`))try{let e=await this.source.getState();Q.setState({supported:!0,initialized:!0,snapshot:e})}catch{}},this.runSnapshotCommand=async(e,t,n)=>{let i=this.source??this.resolveSource();if(!i)throw Error(r(`runtimeUpdatesUnavailableDescription`));this.source=i,Q.setState({busyAction:e});try{let e=await n(i);return Q.setState({snapshot:e}),e}catch(e){throw W.error(`${t}: ${this.getErrorMessage(e)}`),e}finally{Q.setState({busyAction:null})}},this.resolveSource=()=>{let e=this.getDesktopApi();return e?new Xn(e):new Zn},this.getDesktopApi=()=>typeof window>`u`?null:window.nextclawDesktop??null,this.isUnsupportedError=e=>{let t=this.getErrorMessage(e).toLowerCase();return t.includes(`404`)||t.includes(`not found`)||t.includes(`endpoint not found`)},this.getErrorMessage=e=>e instanceof Error?e.message:r(`error`),this.getChannelLabel=e=>r(e===`beta`?`desktopUpdatesChannelBeta`:`desktopUpdatesChannelStable`)}},$n=B.forwardRef(({className:t,checked:n=!1,onCheckedChange:r,thumbClassName:i,...a},o)=>(0,V.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":n,ref:o,className:e(`peer inline-flex h-[22px] w-10 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors duration-fast focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-white disabled:cursor-not-allowed disabled:opacity-50`,n?`bg-primary`:`bg-gray-200/80 hover:bg-gray-300/80`,t),onClick:()=>r?.(!n),...a,children:(0,V.jsx)(`span`,{"data-state":n?`checked`:`unchecked`,className:e(`pointer-events-none block h-5 w-5 rounded-full bg-white shadow-md ring-0 transition-transform duration-fast`,n?`translate-x-5`:`translate-x-0`,i)})}));$n.displayName=`Switch`;var er={maxRetries:8,startupTimeoutMs:2e3,settledTimeoutMs:5e3,retryBaseDelayMs:500,retryMaxDelayMs:3e3};function tr(e){return e instanceof Error?Wr(e.message):!1}function nr(e,t){return e>=er.maxRetries?!1:tr(t)}function rr(e){return Math.min(er.retryMaxDelayMs,er.retryBaseDelayMs*2**Math.max(0,e-1))}function ir(){let[e,t]=(0,B.useState)(!1),n=Je({queryKey:[`auth-status`],queryFn:()=>ei({timeoutMs:e?er.settledTimeoutMs:er.startupTimeoutMs}),staleTime:5e3,retry:nr,retryDelay:rr});return(0,B.useEffect)(()=>{n.isSuccess&&!e&&t(!0)},[e,n.isSuccess]),n}function ar(e){return Promise.all([e.invalidateQueries({queryKey:[`auth-status`]}),e.invalidateQueries({queryKey:[`app-meta`]}),e.invalidateQueries({queryKey:[`config`]}),e.invalidateQueries({queryKey:[`config-meta`]}),e.invalidateQueries({queryKey:[`config-schema`]}),e.invalidateQueries({queryKey:[`sessions`]}),e.invalidateQueries({queryKey:[`session-history`]}),e.invalidateQueries({queryKey:[`chat-runs`]}),e.invalidateQueries({queryKey:[`cron-jobs`]})])}function or(){let e=H();return Ye({mutationFn:ti,onSuccess:async()=>{await ar(e),W.success(r(`authSetupSuccess`))},onError:e=>{W.error(`${r(`authActionFailed`)}: ${e.message}`)}})}function sr(){let e=H();return Ye({mutationFn:ni,onSuccess:async()=>{await ar(e),W.success(r(`authLoginSuccess`))},onError:e=>{W.error(`${r(`authActionFailed`)}: ${e.message}`)}})}function cr(){let e=H();return Ye({mutationFn:ri,onSuccess:async()=>{await ar(e),W.success(r(`authLogoutSuccess`))},onError:e=>{W.error(`${r(`authActionFailed`)}: ${e.message}`)}})}function lr(){let e=H();return Ye({mutationFn:ii,onSuccess:async()=>{await ar(e),W.success(r(`authPasswordUpdated`))},onError:e=>{W.error(`${r(`authActionFailed`)}: ${e.message}`)}})}function ur(){let e=H();return Ye({mutationFn:ai,onSuccess:async(t,n)=>{await ar(e),W.success(n.enabled?r(`authEnabledSuccess`):r(`authDisabledSuccess`))},onError:e=>{W.error(`${r(`authActionFailed`)}: ${e.message}`)}})}var dr=8;function fr(e){return e.trim().length>=dr}function pr(e,t){return e===t?!0:(W.error(r(`authPasswordMismatch`)),!1)}function mr({children:e,contentClassName:t=`space-y-6`}){return(0,V.jsxs)(Nt,{children:[(0,V.jsxs)(Pt,{children:[(0,V.jsx)(Ft,{children:r(`authSecurityTitle`)}),(0,V.jsx)(It,{children:r(`authSecurityDescription`)})]}),(0,V.jsx)(Lt,{className:t,children:e})]})}function hr(e){return(0,V.jsxs)(mr,{contentClassName:`space-y-5`,children:[(0,V.jsxs)(`div`,{className:`rounded-xl border border-dashed border-gray-200 bg-gray-50/70 p-4`,children:[(0,V.jsx)(`p`,{className:`text-sm font-medium text-gray-900`,children:r(`authSetupTitle`)}),(0,V.jsx)(`p`,{className:`mt-1 text-sm text-gray-500`,children:r(`authSetupDescription`)})]}),(0,V.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,V.jsxs)(`div`,{className:`space-y-2`,children:[(0,V.jsx)(At,{htmlFor:`auth-setup-username`,children:r(`authUsername`)}),(0,V.jsx)(K,{id:`auth-setup-username`,value:e.setupUsername,onChange:t=>e.setSetupUsername(t.target.value),placeholder:r(`authUsernamePlaceholder`)})]}),(0,V.jsxs)(`div`,{className:`space-y-2`,children:[(0,V.jsx)(At,{htmlFor:`auth-setup-password`,children:r(`authPassword`)}),(0,V.jsx)(K,{id:`auth-setup-password`,type:`password`,value:e.setupPassword,onChange:t=>e.setSetupPassword(t.target.value),placeholder:r(`authPasswordPlaceholder`)})]})]}),(0,V.jsxs)(`div`,{className:`space-y-2`,children:[(0,V.jsx)(At,{htmlFor:`auth-setup-confirm`,children:r(`authConfirmPassword`)}),(0,V.jsx)(K,{id:`auth-setup-confirm`,type:`password`,value:e.setupConfirmPassword,onChange:t=>e.setSetupConfirmPassword(t.target.value),placeholder:r(`authConfirmPasswordPlaceholder`)}),(0,V.jsx)(`p`,{className:`text-xs text-gray-500`,children:r(`authPasswordMinLengthHint`)})]}),(0,V.jsx)(kt,{type:`button`,disabled:!e.canSubmitSetup,onClick:()=>void e.onSubmit(),children:e.isPending?r(`authSettingUp`):r(`authSetupAction`)})]})}function gr(e){return(0,V.jsxs)(mr,{children:[(0,V.jsxs)(`div`,{className:`rounded-xl border border-gray-200 p-4`,children:[(0,V.jsxs)(`div`,{className:`flex flex-col gap-4 md:flex-row md:items-start md:justify-between`,children:[(0,V.jsxs)(`div`,{className:`space-y-1`,children:[(0,V.jsx)(`p`,{className:`text-sm font-medium text-gray-900`,children:r(`authStatusLabel`)}),(0,V.jsx)(`p`,{className:`text-sm text-gray-600`,children:r(`authStatusConfiguredUser`).replace(`{username}`,e.username??``)}),(0,V.jsx)(`p`,{className:`text-xs text-gray-500`,children:r(`authUsernameFixedHelp`)})]}),(0,V.jsx)(`span`,{className:`inline-flex items-center rounded-full bg-gray-100 px-3 py-1 text-xs font-medium text-gray-700`,children:e.enabled?r(`enabled`):r(`disabled`)})]}),(0,V.jsxs)(`div`,{className:`mt-4 flex flex-col gap-4 border-t border-gray-200 pt-4 md:flex-row md:items-center md:justify-between`,children:[(0,V.jsxs)(`div`,{className:`space-y-1`,children:[(0,V.jsx)(`p`,{className:`text-sm font-medium text-gray-900`,children:r(`authEnableLabel`)}),(0,V.jsx)(`p`,{className:`text-xs text-gray-500`,children:e.enabled?r(`authEnableOnHelp`):r(`authEnableOffHelp`)})]}),(0,V.jsx)($n,{checked:e.enabled,disabled:e.isUpdatingEnabled,onCheckedChange:t=>{e.onEnabledChange(t)}})]})]}),(0,V.jsxs)(`div`,{className:`rounded-xl border border-gray-200 p-4 space-y-4`,children:[(0,V.jsxs)(`div`,{className:`space-y-1`,children:[(0,V.jsx)(`p`,{className:`text-sm font-medium text-gray-900`,children:r(`authPasswordSectionTitle`)}),(0,V.jsx)(`p`,{className:`text-xs text-gray-500`,children:r(`authPasswordSectionDescription`)})]}),(0,V.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,V.jsxs)(`div`,{className:`space-y-2`,children:[(0,V.jsx)(At,{htmlFor:`auth-password-next`,children:r(`authPassword`)}),(0,V.jsx)(K,{id:`auth-password-next`,type:`password`,value:e.nextPassword,onChange:t=>e.setNextPassword(t.target.value),placeholder:r(`authPasswordPlaceholder`)})]}),(0,V.jsxs)(`div`,{className:`space-y-2`,children:[(0,V.jsx)(At,{htmlFor:`auth-password-confirm`,children:r(`authConfirmPassword`)}),(0,V.jsx)(K,{id:`auth-password-confirm`,type:`password`,value:e.nextConfirmPassword,onChange:t=>e.setNextConfirmPassword(t.target.value),placeholder:r(`authConfirmPasswordPlaceholder`)})]})]}),(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,V.jsx)(kt,{type:`button`,disabled:!e.canUpdatePassword,onClick:()=>void e.onPasswordUpdate(),children:e.isUpdatingPassword?r(`authPasswordUpdating`):r(`authPasswordAction`)}),e.enabled&&e.authenticated?(0,V.jsx)(kt,{type:`button`,variant:`outline`,disabled:e.isLoggingOut,onClick:()=>void e.onLogout(),children:e.isLoggingOut?r(`authLoggingOut`):r(`authLogoutAction`)}):null]}),(0,V.jsx)(`p`,{className:`text-xs text-gray-500`,children:r(`authSessionMemoryNotice`)})]})]})}function _r(){let e=ir(),t=or(),n=ur(),i=lr(),a=cr(),[o,s]=(0,B.useState)(``),[c,l]=(0,B.useState)(``),[u,d]=(0,B.useState)(``),[f,p]=(0,B.useState)(``),[m,h]=(0,B.useState)(``),g=e.data,_=o.trim().length>0&&fr(c)&&c===u&&!t.isPending,v=fr(f)&&f===m&&!i.isPending;return e.isLoading&&!g?(0,V.jsx)(mr,{contentClassName:`text-sm text-gray-500`,children:r(`loading`)}):e.isError||!g?(0,V.jsxs)(mr,{contentClassName:`space-y-4`,children:[(0,V.jsx)(`p`,{className:`text-sm text-gray-500`,children:r(`authStatusLoadFailed`)}),(0,V.jsx)(kt,{variant:`outline`,onClick:()=>void e.refetch(),children:r(`authRetryStatus`)})]}):g.configured?(0,V.jsx)(gr,{authenticated:g.authenticated,enabled:g.enabled,username:g.username,nextPassword:f,setNextPassword:p,nextConfirmPassword:m,setNextConfirmPassword:h,canUpdatePassword:v,isUpdatingEnabled:n.isPending,isUpdatingPassword:i.isPending,isLoggingOut:a.isPending,onEnabledChange:async e=>{try{await n.mutateAsync({enabled:e})}catch{}},onPasswordUpdate:async()=>{if(pr(f,m))try{await i.mutateAsync({password:f}),p(``),h(``)}catch{}},onLogout:async()=>{try{await a.mutateAsync()}catch{}}}):(0,V.jsx)(hr,{setupUsername:o,setSetupUsername:s,setupPassword:c,setSetupPassword:l,setupConfirmPassword:u,setSetupConfirmPassword:d,canSubmitSetup:_,isPending:t.isPending,onSubmit:async()=>{if(pr(c,u))try{await t.mutateAsync({username:o.trim(),password:c}),l(``),d(``)}catch{}}})}var vr=s({SecurityConfig:()=>yr});function yr(){return(0,V.jsxs)(jt,{className:`space-y-6`,children:[(0,V.jsx)(Mt,{title:r(`authSecurityTitle`),description:r(`authSecurityDescription`)}),(0,V.jsx)(_r,{})]})}function br(e){return e.replace(/\s+/g,` `).trim().slice(0,200)}function xr(e,t){if(t===404&&e.startsWith(`/api/providers/`)&&e.endsWith(`/test`))return`Provider test endpoint is missing. This usually means nextclaw runtime version is outdated.`;if(t===401||t===403)return`Authentication failed. Check apiKey and custom headers.`;if(t===429)return`Rate limited by upstream provider. Retry later or switch model/provider.`;if(t>=500)return`Upstream service error. Retry later and inspect server logs if it persists.`}function Sr(e){if(e instanceof Error){let t=e.name?.trim()||`Error`,n=e.message?.trim()||`Unknown error`;return{summary:`${t}: ${n}`,details:{errorName:t,errorMessage:n,...e.stack?.trim()?{errorStack:e.stack.trim()}:{}}}}return{summary:String(e??`Unknown error`),details:{errorName:`NonError`,errorMessage:String(e??`Unknown error`)}}}async function Cr(e,t,n={}){let r=`${e}${t}`,i=(n.method||`GET`).toUpperCase(),a;try{let e=new Headers(n.headers);!(n.body instanceof FormData)&&!e.has(`Content-Type`)&&e.set(`Content-Type`,`application/json`),a=await fetch(r,{credentials:`include`,headers:e,...n})}catch(e){let n=Sr(e);return Z.reportTransportFailure(n.summary),{ok:!1,error:{code:`NETWORK_ERROR`,message:`Fetch failed on ${i} ${t} | ${n.summary}`,details:{method:i,endpoint:t,url:r,...n.details}}}}let o=await a.text(),s=null;if(o)try{s=JSON.parse(o)}catch{}if(!s){let e=o?br(o):``,n=xr(t,a.status),s=[`Non-JSON response (${a.status} ${a.statusText}) on ${i} ${t}`];return e&&s.push(`body=${e}`),n&&s.push(`hint=${n}`),{ok:!1,error:{code:`INVALID_RESPONSE`,message:s.join(` | `),details:{status:a.status,statusText:a.statusText,method:i,endpoint:t,url:r,bodySnippet:e||void 0,hint:n}}}}return a.ok,s}function wr(e){let t=e.split(`
8
8
  `),n=``,r=[];for(let e of t){let t=e.trimEnd();if(!(!t||t.startsWith(`:`))){if(t.startsWith(`event:`)){n=t.slice(6).trim();continue}t.startsWith(`data:`)&&r.push(t.slice(5).trimStart())}}if(!n)return null;let i,a=r.join(`
9
- `);if(a)try{i=JSON.parse(a)}catch{i=a}return{name:n,payload:i}}function wr(e,t,n){let r=Cr(e);r&&(r.name===`final`&&n(r.payload),t(r))}function Tr(e,t,n){let r=e,i=r.indexOf(`
9
+ `);if(a)try{i=JSON.parse(a)}catch{i=a}return{name:n,payload:i}}function Tr(e,t,n){let r=wr(e);r&&(r.name===`final`&&n(r.payload),t(r))}function Er(e,t,n){let r=e,i=r.indexOf(`
10
10
 
11
- `);for(;i!==-1;)wr(r.slice(0,i),t,n),r=r.slice(i+2),i=r.indexOf(`
11
+ `);for(;i!==-1;)Tr(r.slice(0,i),t,n),r=r.slice(i+2),i=r.indexOf(`
12
12
 
13
- `);return r}async function Er(e,t){let n=e.body?.getReader();if(!n)throw Error(`SSE response body unavailable`);let r=new TextDecoder,i=``,a;try{for(;;){let{value:e,done:o}=await n.read();if(o)break;i+=r.decode(e,{stream:!0}),i=Tr(i,t,e=>{a=e})}i.trim()&&wr(i,t,e=>{a=e})}finally{n.releaseLock()}return a}function Dr(e,t){let n=e.replace(/\/$/,``);try{let e=new URL(n,window.location.origin);return`${e.protocol===`https:`?`wss:`:e.protocol===`http:`?`ws:`:e.protocol}//${e.host}${t}`}catch{return n.startsWith(`wss://`)||n.startsWith(`ws://`)?`${n}${t}`:n.startsWith(`https://`)?`${n.replace(/^https:/,`wss:`)}${t}`:n.startsWith(`http://`)?`${n.replace(/^http:/,`ws:`)}${t}`:`${n}${t}`}}function Or(e,t){if(!e.ok){let n=Error(e.error?.message||t);return n.code=e.error?.code,n.details=e.error?.details,n}return Error(t)}function kr(e){if(e instanceof Error){let t=e.name?.trim(),n=e.message?.trim();return t&&n?`${t}: ${n}`:n||t||`Unknown error`}return String(e??`Unknown error`)}function Ar(e,t){let n=Error(e);return t!==void 0&&(n.cause=t),n}var jr=class{constructor(e){this.wsUrl=e,this.socket=null,this.reconnectTimer=null,this.manualClose=!1,this.subscribers=new Set,this.subscribe=e=>(this.subscribers.add(e),this.subscribers.size===1?this.connect():this.socket?.readyState===WebSocket.OPEN&&e({type:`connection.open`,payload:{}}),()=>{this.subscribers.delete(e),this.subscribers.size===0&&this.disconnect()}),this.emit=e=>{for(let t of this.subscribers)t(e)},this.connect=()=>{if(this.socket&&(this.socket.readyState===WebSocket.CONNECTING||this.socket.readyState===WebSocket.OPEN))return;this.manualClose=!1;let e=new WebSocket(this.wsUrl);this.socket=e,e.onopen=()=>{this.emit({type:`connection.open`,payload:{}})},e.onmessage=e=>{try{let t=JSON.parse(String(e.data??``));this.emit(t)}catch(e){console.error(`Failed to parse websocket message:`,e)}},e.onerror=()=>{this.emit({type:`connection.error`,payload:{message:`websocket error`}})},e.onclose=()=>{this.emit({type:`connection.close`,payload:{}}),this.socket=null,!this.manualClose&&this.subscribers.size>0&&this.scheduleReconnect()}},this.scheduleReconnect=()=>{this.reconnectTimer===null&&(this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=null,this.connect()},3e3))},this.disconnect=()=>{this.manualClose=!0,this.reconnectTimer!==null&&(window.clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.socket?.close(),this.socket=null}}},Mr=class{constructor(e={}){this.options=e,this.request=async e=>{let t=Number.isFinite(e.timeoutMs)&&(e.timeoutMs??0)>0?Math.trunc(e.timeoutMs):null,n=t?new AbortController:null,r=t?window.setTimeout(()=>n?.abort(`Request timed out after ${t}ms: ${e.method} ${e.path}`),t):null,i=Nr(e.body);try{let t=await Sr(this.apiBase,e.path,{method:e.method,...i===void 0?{}:{body:i},...e.headers?{headers:e.headers}:{},signal:n?.signal??e.signal});if(!t.ok)throw Or(t,`Request failed for ${e.method} ${e.path}`);return t.data}catch(t){if(n?.signal.aborted){let{reason:t}=n.signal;throw Error(typeof t==`string`&&t.trim()?t:`Request timed out: ${e.method} ${e.path}`)}throw t instanceof Error?t:Ar(`Request failed for ${e.method} ${e.path} | ${kr(t)}`,t)}finally{r!==null&&window.clearTimeout(r)}},this.openStream=e=>{let t=new AbortController,n=()=>t.abort();return e.signal&&(e.signal.aborted?n():e.signal.addEventListener(`abort`,n,{once:!0})),{finished:(async()=>{let r;try{r=await fetch(`${this.apiBase}${e.path}`,{method:e.method,credentials:`include`,headers:{"Content-Type":`application/json`,Accept:`text/event-stream`},...e.body===void 0?{}:{body:JSON.stringify(e.body)},signal:t.signal})}catch(t){throw Z.reportTransportFailure(kr(t)),Ar(`Stream request failed for ${e.method} ${e.path} | ${kr(t)}`,t)}if(!r.ok){let t=(await r.text()).trim();throw Error(t?`Stream request failed for ${e.method} ${e.path} | HTTP ${r.status} | ${t}`:`Stream request failed for ${e.method} ${e.path} | HTTP ${r.status}`)}try{return await Er(r,e.onEvent)}finally{e.signal?.removeEventListener(`abort`,n)}})(),cancel:()=>t.abort()}},this.subscribe=e=>this.realtimeGateway.subscribe(e),this.apiBase=e.apiBase??((void 0)?.trim().replace(/\/$/,``)||(typeof window<`u`?window.location.origin:`http://127.0.0.1:55667`)),this.realtimeGateway=new jr(Dr(this.apiBase,e.wsPath??`/ws`))}};function Nr(e){if(e!==void 0)return e instanceof FormData||e instanceof URLSearchParams||e instanceof Blob||e instanceof ArrayBuffer||typeof e==`string`?e:JSON.stringify(e)}function Pr(e,t,n){if(typeof e==`object`&&e&&`ok`in e){let r=e;if(r.ok===!1&&r.error?.message){let e=Error(r.error.message);return e.code=r.error.code,e.details=r.error.details,e.status=t,e}if(r.ok===!0)return Error(n)}return typeof e==`string`&&e.trim()?Error(e.trim()):Error(`${n} (${t})`)}function Fr(e){if(typeof e==`object`&&e&&`ok`in e){let t=e;if(t.ok===!1){let e=Error(t.error?.message??`Remote request failed.`);throw e.code=t.error?.code,e.details=t.error?.details,e}if(t.ok===!0)return t.data}return e}function Ir(e){return`${e}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}var Lr=15e3,Rr=class{constructor(e,t=(void 0)?.trim().replace(/\/$/,``)||(typeof window<`u`?window.location.origin:`http://127.0.0.1:55667`)){this.runtime=e,this.apiBase=t,this.socket=null,this.connectPromise=null,this.connectTimeoutId=null,this.reconnectTimer=null,this.manualClose=!1,this.subscribers=new Set,this.pendingRequests=new Map,this.pendingStreams=new Map,this.request=async e=>{await this.ensureSocket();let t=Ir(`req`),n=Number.isFinite(e.timeoutMs)&&(e.timeoutMs??0)>0?Math.trunc(e.timeoutMs):Lr;return await new Promise((r,i)=>{let a=window.setTimeout(()=>{this.pendingRequests.delete(t),i(Error(`Timed out waiting for remote request response after ${n}ms: ${e.method} ${e.path}`))},n);this.pendingRequests.set(t,{resolve:e=>r(e),reject:i,timeoutId:a}),this.send({type:`request`,id:t,target:{method:e.method,path:e.path,...e.headers?{headers:e.headers}:{},...e.body===void 0?{}:{body:e.body}}})})},this.openStream=e=>{let t=Ir(`stream`),n=!1,r=e=>{n||(n=!0,a(e))},i,a,o=new Promise((e,t)=>{i=e,a=t}),s=()=>{this.pendingStreams.delete(t),!n&&(n=!0,this.send({type:`stream.cancel`,streamId:t}),a(Error(`stream cancelled`)))};this.pendingStreams.set(t,{onEvent:e.onEvent,finalResult:void 0,resolve:e=>{n||(n=!0,i(e))},reject:e=>{n||(n=!0,a(e))}});let c=()=>s();return e.signal&&(e.signal.aborted?s():e.signal.addEventListener(`abort`,c,{once:!0})),this.ensureSocket().then(()=>{n||this.send({type:`stream.open`,streamId:t,target:{method:e.method,path:e.path,...e.body===void 0?{}:{body:e.body}}})}).catch(e=>{this.pendingStreams.delete(t),r(e instanceof Error?e:Error(String(e)))}),{finished:o.finally(()=>{e.signal?.removeEventListener(`abort`,c),this.pendingStreams.delete(t)}),cancel:s}},this.subscribe=e=>(this.subscribers.add(e),this.ensureSocket().catch(t=>{e({type:`connection.error`,payload:{message:t instanceof Error?t.message:String(t)}})}),()=>{this.subscribers.delete(e)}),this.emit=e=>{for(let t of this.subscribers)t(e)},this.send=e=>{if(!this.socket||this.socket.readyState!==WebSocket.OPEN)throw Error(`Remote transport websocket is not connected.`);this.socket.send(JSON.stringify(e))},this.ensureSocket=async()=>{if(this.socket?.readyState===WebSocket.OPEN&&this.connectPromise===null)return;if(this.connectPromise)return await this.connectPromise;let e=Dr(this.apiBase,this.runtime.wsPath);this.manualClose=!1,this.connectPromise=new Promise((t,n)=>{let r=new WebSocket(e);this.socket=r;let i=!1,a=()=>{this.connectTimeoutId!==null&&(window.clearTimeout(this.connectTimeoutId),this.connectTimeoutId=null)};this.connectTimeoutId=window.setTimeout(()=>{this.connectTimeoutId=null,n(Error(`Timed out waiting for remote transport websocket.`)),r.close()},8e3),r.onopen=()=>{i=!0,a(),this.connectPromise=null,t(),this.emit({type:`connection.open`,payload:{}})},r.onmessage=e=>{try{let t=JSON.parse(String(e.data??``));if(t.type===`connection.ready`)return;this.handleFrame(t)}catch(e){console.error(`Failed to parse remote websocket frame:`,e)}},r.onerror=()=>{this.emit({type:`connection.error`,payload:{message:`remote websocket error`}})},r.onclose=()=>{a();let e=this.connectPromise!==null;this.socket=null,this.connectPromise=null,this.failPendingWork(Error(`Remote transport connection closed.`)),this.emit({type:`connection.close`,payload:{}}),e&&!i&&n(Error(`Remote transport connection closed before ready.`)),!this.manualClose&&this.subscribers.size>0&&this.scheduleReconnect()}});let{connectPromise:t}=this;return await t},this.scheduleReconnect=()=>{this.reconnectTimer===null&&(this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=null,this.ensureSocket().catch(()=>void 0)},3e3))},this.failPendingWork=e=>{for(let t of this.pendingRequests.values())window.clearTimeout(t.timeoutId),t.reject(e);this.pendingRequests.clear();for(let t of this.pendingStreams.values())t.reject(e);this.pendingStreams.clear()},this.handleFrame=e=>{if(e.type===`response`||e.type===`request.error`){this.handleRequestFrame(e);return}if(e.type===`stream.event`||e.type===`stream.end`||e.type===`stream.error`){this.handleStreamFrame(e);return}if(e.type===`event`){this.emit(e.event);return}e.type===`connection.error`&&this.emit({type:`connection.error`,payload:{message:e.message}})},this.handleRequestFrame=e=>{let t=this.pendingRequests.get(e.id);if(t){if(this.pendingRequests.delete(e.id),window.clearTimeout(t.timeoutId),e.type===`request.error`){t.reject(Error(e.message));return}if(e.status>=400){t.reject(Pr(e.body,e.status,`Remote request failed.`));return}try{t.resolve(Fr(e.body))}catch(e){t.reject(e instanceof Error?e:Error(String(e)))}}},this.handleStreamFrame=e=>{let t=this.pendingStreams.get(e.streamId);if(t){if(e.type===`stream.event`){try{e.event===`final`&&(t.finalResult=e.payload),t.onEvent({name:e.event,payload:e.payload})}catch(n){this.pendingStreams.delete(e.streamId),t.reject(n instanceof Error?n:Error(String(n)))}return}if(this.pendingStreams.delete(e.streamId),e.type===`stream.end`){t.resolve(t.finalResult);return}t.reject(Error(e.message))}}}},zr=`/_remote/runtime`,Br={mode:`remote`,protocolVersion:1,wsPath:`/_remote/ws`};async function Vr(e){let t=`${e.replace(/\/$/,``)}${zr}`,n;try{n=await fetch(t,{method:`GET`,credentials:`include`,cache:`no-store`})}catch{return new Mr({apiBase:e})}if(n.status===404)return new Mr({apiBase:e});if(!(n.headers.get(`content-type`)?.toLowerCase()??``).includes(`application/json`))return n.status>=400?new Rr(Br,e):new Mr({apiBase:e});let r=null;try{r=await n.json()}catch{return n.status>=400?new Rr(Br,e):new Mr({apiBase:e})}return n.ok&&r.ok&&r.data?.mode===`remote`?new Rr(r.data,e):n.status>=400?new Rr(Br,e):new Mr({apiBase:e})}var Hr=new class{constructor(e=(void 0)?.trim().replace(/\/$/,``)||(typeof window<`u`?window.location.origin:`http://127.0.0.1:55667`)){this.apiBase=e,this.transportPromise=null,this.getTransport=async()=>(this.transportPromise||=Vr(this.apiBase),await this.transportPromise),this.request=async e=>await(await this.getTransport()).request(e),this.openStream=e=>{let t=null,n,r,i=new Promise((e,t)=>{n=e,r=t});return this.getTransport().then(i=>{t=i.openStream(e),t.finished.then(n).catch(e=>{r(e instanceof Error?e:Error(String(e)))})}).catch(e=>{r(e instanceof Error?e:Error(String(e)))}),{finished:i,cancel:()=>t?.cancel()}},this.subscribe=e=>{let t=()=>{},n=!0;return this.getTransport().then(r=>{n&&(t=r.subscribe(e))}).catch(t=>{e({type:`connection.error`,payload:{message:t instanceof Error?t.message:String(t)}})}),()=>{n=!1,t()}}}};function Ur(e){let t=e.trim().toLowerCase();return t?[`failed to fetch`,`networkerror`,`network request failed`,`load failed`,`request timed out`,`timed out waiting for remote request response`,`remote transport connection closed`,`websocket error`,`fetch failed on `,`stream request failed for `,`ncp fetch failed for `].some(e=>t.includes(e)):!1}var $=new wn({baseUrl:En,transport:{request:async({body:e,headers:t,method:n,path:r,query:i,signal:a,timeoutMs:o})=>await Hr.request({method:n,path:Gr(r,Wr(i)),...e===void 0?{}:{body:e},...t?{headers:t}:{},...a?{signal:a}:{},...o===void 0?{}:{timeoutMs:o}}),upload:async({formData:e,headers:t,path:n,signal:r})=>{let i=await fetch(`${En}${n}`,{method:`POST`,body:e,credentials:`include`,...t?{headers:t}:{},...r?{signal:r}:{}}),a=await i.json();if(!i.ok||!a.ok)throw Error(Kr(a,`Upload failed for ${n}`));return a.data},subscribe:e=>Hr.subscribe(e)}});function Wr(e){if(!e)return;if(e instanceof URLSearchParams)return e;let t=new URLSearchParams;for(let[n,r]of Object.entries(e)){let e=Array.isArray(r)?r:[r];for(let r of e)r!=null&&t.append(n,String(r))}return t}function Gr(e,t){let n=t?.toString();return n?`${e}${e.includes(`?`)?`&`:`?`}${n}`:e}function Kr(e,t){return e.ok?t:e.error.message}async function qr(){return{agents:await $.agents.list()}}async function Jr(e,t){return await $.agents.update(e,t)}async function Yr(e){return await $.agents.delete(e)}async function Xr(e,t={}){return await $.channelAuth.start(e,t)}async function Zr(e,t){return await $.channelAuth.poll(e,t)}async function Qr(e,t){return await $.channelAuth.connect(e,t)}async function $r(e={}){return await $.auth.fetchStatus({timeoutMs:e.timeoutMs??5e3})}async function ei(e){return await $.auth.setup(e)}async function ti(e){return await $.auth.login(e)}async function ni(){return await $.auth.logout()}async function ri(e){return await $.auth.updatePassword(e)}async function ii(e){return await $.auth.updateEnabled(e)}async function ai(){return await $.app.fetchMeta()}async function oi(e={}){return await $.app.fetchBootstrapStatus(e)}async function si(){return await $.config.fetch()}async function ci(){return await $.config.fetchMeta()}async function li(){return await $.providers.list()}async function ui(){return await $.providers.listTemplates()}async function di(){return await $.config.fetchSchema()}async function fi(e){return await $.config.updateModel(e)}async function pi(e){return await $.config.updateSearch(e)}async function mi(e,t){return await $.providers.update(e,t)}async function hi(e={}){return await $.providers.create(e)}async function gi(e){return await $.providers.delete(e)}async function _i(e,t){return await $.providers.testConnection(e,t)}async function vi(e,t={}){return await $.providers.startAuth(e,t)}async function yi(e,t){return await $.providers.pollAuth(e,t)}async function bi(e){return await $.providers.importAuthFromCli(e)}async function xi(e,t){return await $.config.updateChannel(e,t)}async function Si(e){return await $.config.updateRuntime(e)}async function Ci(e){return await $.config.updateSecrets(e)}async function wi(e,t){return await $.config.executeAction(e,t)}async function Ti(){return await $.config.fetchChatSessionTypes()}async function Ei(e){return await $.config.fetchCronJobs(e)}async function Di(e){return await $.config.deleteCronJob(e)}async function Oi(e,t){return await $.config.setCronJobEnabled(e,t)}async function ki(e,t){return await $.config.runCronJob(e,t)}async function Ai(e){return await $.marketplace.fetchItems(e)}async function ji(e){return await $.marketplace.fetchSkillContent(e)}async function Mi(){return await $.marketplace.fetchSkillScenes()}async function Ni(e){return await $.marketplace.install(e)}async function Pi(e){return await $.marketplace.fetchInstalled(e)}async function Fi(e){return await $.marketplace.manage(e)}async function Ii(e){return await $.mcpMarketplace.fetchItems(e)}async function Li(){return await $.mcpMarketplace.fetchInstalled()}async function Ri(e){return await $.mcpMarketplace.fetchContent(e)}async function zi(e){return await $.mcpMarketplace.install({type:`mcp`,...e})}async function Bi(e){return await $.mcpMarketplace.manage({type:`mcp`,...e})}async function Vi(e){return await $.mcpMarketplace.doctor(e)}async function Hi(e){return(await $.sessions.uploadAssets(e)).assets.map(e=>({id:e.id,name:e.name,mimeType:e.mimeType,sizeBytes:e.sizeBytes,assetUri:e.assetUri,url:e.url}))}async function Ui(e){return await $.sessions.list(e)}async function Wi(e,t=200){return await $.sessions.listMessages(e,t)}async function Gi(e,t){return await $.sessions.listSkills(e,t)}async function Ki(e,t){return await $.sessions.update(e,t)}async function qi(e){return await $.sessions.delete(e)}function Ji(e){return e.lastMessageAt??e.createdAt??e.updatedAt}function Yi(e){return[...e].sort((e,t)=>Ji(t).localeCompare(Ji(e)))}function Xi(e,t){let n=t.updatedAt.localeCompare(e.updatedAt);return n===0?e.status===t.status||t.status===`idle`:n>0}function Zi(e,t){if(!e)return e;let n=e.sessions.findIndex(e=>e.sessionId===t.sessionId),r=Yi(n>=0?e.sessions.map((e,r)=>r===n&&Xi(e,t)?{...t,status:e.status===`running`&&t.status===`idle`?`running`:t.status}:e):[...e.sessions,t]);return{...e,sessions:r,total:r.length}}function Qi(e,t){if(!e)return e;let n=t.trim();if(!n)return e;let r=e.sessions.filter(e=>e.sessionId!==n);return r.length===e.sessions.length?e:{...e,sessions:r,total:r.length}}function $i(e,t){e?.setQueriesData({queryKey:[`ncp-sessions`]},e=>Zi(e,t))}function ea(e,t){if(!e)return e;let n=t.sessionKey.trim();if(!n)return e;let r=!1,i=e.sessions.map(e=>e.sessionId!==n||e.status===t.status?e:(r=!0,{...e,status:t.status}));return r?{...e,sessions:i}:e}function ta(e,t){e?.setQueriesData({queryKey:[`ncp-sessions`]},e=>ea(e,t))}function na(e,t){e?.setQueriesData({queryKey:[`ncp-sessions`]},e=>Qi(e,t))}function ra(e,t){if(t.type===`session.run-status`){ta(e,t.payload);return}if(t.type===`session.summary.upsert`){$i(e,t.payload.summary);return}na(e,t.payload.sessionKey)}async function ia(){return await $.remote.fetchStatus()}async function aa(){return await $.remote.fetchDoctor()}async function oa(e){return await $.remote.startBrowserAuth(e)}async function sa(e){return await $.remote.pollBrowserAuth(e)}async function ca(){return await $.remote.logout()}async function la(e){return await $.remote.updateAccountProfile(e)}async function ua(e){return await $.remote.updateSettings(e)}async function da(e){return await $.remote.controlService(e)}async function fa(){return await $.runtimeControl.fetch()}async function pa(){return await $.runtimeControl.startService()}async function ma(){return await $.runtimeControl.restartService()}async function ha(){return await $.runtimeControl.stopService()}async function ga(){return await $.runtimeUpdate.fetch()}async function _a(){return await $.runtimeUpdate.check()}async function va(){return await $.runtimeUpdate.download()}async function ya(){return await $.runtimeUpdate.apply()}async function ba(e){return await $.runtimeUpdate.updatePreferences(e)}async function xa(e){return await $.runtimeUpdate.updateChannel(e)}async function Sa(e){return await $.serverPaths.browse(e)}async function Ca(e){return await $.serverPaths.read(e)}export{Si as $,Te as $t,Ni as A,Ft as At,Ei as B,Ye as Bt,Ii as C,En as Ct,Ai as D,Lt as Dt,Pi as E,Nt as Et,wi as F,kt as Ft,yi as G,Ge as Gt,ui as H,qe as Ht,ai as I,Dt as It,vi as J,Ve as Jt,ki as K,Be as Kt,si as L,wt as Lt,hi as M,jt as Mt,Di as N,At as Nt,ji as O,It as Ot,gi as P,K as Pt,mi as Q,H as Qt,ci as R,Ct as Rt,Li as S,X as St,Bi as T,Vt as Tt,li as U,Ue as Ut,Ti as V,Je as Vt,bi as W,Ke as Wt,xi as X,Ie as Xt,_i as Y,ze as Yt,fi as Z,Pe as Zt,Ui as _,Jn as _t,ia as a,te as an,Yr as at,Vi as b,Gn as bt,oa as c,$ as ct,ra as d,er as dt,Ee as en,pi as et,na as f,rr as ft,Gi as g,Q as gt,Wi as h,Zn as ht,aa as i,m as in,Xr as it,Fi as j,Mt as jt,Mi as k,Pt as kt,la as l,Ur as lt,qi as m,Qn as mt,Ca as n,_e as nn,Qr as nt,ca as o,T as on,qr as ot,$i as p,or as pt,Oi as q,He as qt,da as r,N as rn,Zr as rt,sa as s,l as sn,Jr as st,Sa as t,R as tn,Ci as tt,ua as u,_r as ut,Ki as v,qn as vt,zi as w,Y as wt,Ri as x,Z as xt,Hi as y,Kn as yt,di as z,W as zt};
13
+ `);return r}async function Dr(e,t){let n=e.body?.getReader();if(!n)throw Error(`SSE response body unavailable`);let r=new TextDecoder,i=``,a;try{for(;;){let{value:e,done:o}=await n.read();if(o)break;i+=r.decode(e,{stream:!0}),i=Er(i,t,e=>{a=e})}i.trim()&&Tr(i,t,e=>{a=e})}finally{n.releaseLock()}return a}function Or(e,t){let n=e.replace(/\/$/,``);try{let e=new URL(n,window.location.origin);return`${e.protocol===`https:`?`wss:`:e.protocol===`http:`?`ws:`:e.protocol}//${e.host}${t}`}catch{return n.startsWith(`wss://`)||n.startsWith(`ws://`)?`${n}${t}`:n.startsWith(`https://`)?`${n.replace(/^https:/,`wss:`)}${t}`:n.startsWith(`http://`)?`${n.replace(/^http:/,`ws:`)}${t}`:`${n}${t}`}}function kr(e,t){if(!e.ok){let n=Error(e.error?.message||t);return n.code=e.error?.code,n.details=e.error?.details,n}return Error(t)}function Ar(e){if(e instanceof Error){let t=e.name?.trim(),n=e.message?.trim();return t&&n?`${t}: ${n}`:n||t||`Unknown error`}return String(e??`Unknown error`)}function jr(e,t){let n=Error(e);return t!==void 0&&(n.cause=t),n}var Mr=class{constructor(e){this.wsUrl=e,this.socket=null,this.reconnectTimer=null,this.manualClose=!1,this.subscribers=new Set,this.subscribe=e=>(this.subscribers.add(e),this.subscribers.size===1?this.connect():this.socket?.readyState===WebSocket.OPEN&&e({type:`connection.open`,payload:{}}),()=>{this.subscribers.delete(e),this.subscribers.size===0&&this.disconnect()}),this.emit=e=>{for(let t of this.subscribers)t(e)},this.connect=()=>{if(this.socket&&(this.socket.readyState===WebSocket.CONNECTING||this.socket.readyState===WebSocket.OPEN))return;this.manualClose=!1;let e=new WebSocket(this.wsUrl);this.socket=e,e.onopen=()=>{this.emit({type:`connection.open`,payload:{}})},e.onmessage=e=>{try{let t=JSON.parse(String(e.data??``));this.emit(t)}catch(e){console.error(`Failed to parse websocket message:`,e)}},e.onerror=()=>{this.emit({type:`connection.error`,payload:{message:`websocket error`}})},e.onclose=()=>{this.emit({type:`connection.close`,payload:{}}),this.socket=null,!this.manualClose&&this.subscribers.size>0&&this.scheduleReconnect()}},this.scheduleReconnect=()=>{this.reconnectTimer===null&&(this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=null,this.connect()},3e3))},this.disconnect=()=>{this.manualClose=!0,this.reconnectTimer!==null&&(window.clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.socket?.close(),this.socket=null}}},Nr=class{constructor(e={}){this.options=e,this.request=async e=>{let t=Number.isFinite(e.timeoutMs)&&(e.timeoutMs??0)>0?Math.trunc(e.timeoutMs):null,n=t?new AbortController:null,r=t?window.setTimeout(()=>n?.abort(`Request timed out after ${t}ms: ${e.method} ${e.path}`),t):null,i=Pr(e.body);try{let t=await Cr(this.apiBase,e.path,{method:e.method,...i===void 0?{}:{body:i},...e.headers?{headers:e.headers}:{},signal:n?.signal??e.signal});if(!t.ok)throw kr(t,`Request failed for ${e.method} ${e.path}`);return t.data}catch(t){if(n?.signal.aborted){let{reason:t}=n.signal;throw Error(typeof t==`string`&&t.trim()?t:`Request timed out: ${e.method} ${e.path}`)}throw t instanceof Error?t:jr(`Request failed for ${e.method} ${e.path} | ${Ar(t)}`,t)}finally{r!==null&&window.clearTimeout(r)}},this.openStream=e=>{let t=new AbortController,n=()=>t.abort();return e.signal&&(e.signal.aborted?n():e.signal.addEventListener(`abort`,n,{once:!0})),{finished:(async()=>{let r;try{r=await fetch(`${this.apiBase}${e.path}`,{method:e.method,credentials:`include`,headers:{"Content-Type":`application/json`,Accept:`text/event-stream`},...e.body===void 0?{}:{body:JSON.stringify(e.body)},signal:t.signal})}catch(t){throw Z.reportTransportFailure(Ar(t)),jr(`Stream request failed for ${e.method} ${e.path} | ${Ar(t)}`,t)}if(!r.ok){let t=(await r.text()).trim();throw Error(t?`Stream request failed for ${e.method} ${e.path} | HTTP ${r.status} | ${t}`:`Stream request failed for ${e.method} ${e.path} | HTTP ${r.status}`)}try{return await Dr(r,e.onEvent)}finally{e.signal?.removeEventListener(`abort`,n)}})(),cancel:()=>t.abort()}},this.subscribe=e=>this.realtimeGateway.subscribe(e),this.apiBase=e.apiBase??((void 0)?.trim().replace(/\/$/,``)||(typeof window<`u`?window.location.origin:`http://127.0.0.1:55667`)),this.realtimeGateway=new Mr(Or(this.apiBase,e.wsPath??`/ws`))}};function Pr(e){if(e!==void 0)return e instanceof FormData||e instanceof URLSearchParams||e instanceof Blob||e instanceof ArrayBuffer||typeof e==`string`?e:JSON.stringify(e)}function Fr(e,t,n){if(typeof e==`object`&&e&&`ok`in e){let r=e;if(r.ok===!1&&r.error?.message){let e=Error(r.error.message);return e.code=r.error.code,e.details=r.error.details,e.status=t,e}if(r.ok===!0)return Error(n)}return typeof e==`string`&&e.trim()?Error(e.trim()):Error(`${n} (${t})`)}function Ir(e){if(typeof e==`object`&&e&&`ok`in e){let t=e;if(t.ok===!1){let e=Error(t.error?.message??`Remote request failed.`);throw e.code=t.error?.code,e.details=t.error?.details,e}if(t.ok===!0)return t.data}return e}function Lr(e){return`${e}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}var Rr=15e3,zr=class{constructor(e,t=(void 0)?.trim().replace(/\/$/,``)||(typeof window<`u`?window.location.origin:`http://127.0.0.1:55667`)){this.runtime=e,this.apiBase=t,this.socket=null,this.connectPromise=null,this.connectTimeoutId=null,this.reconnectTimer=null,this.manualClose=!1,this.subscribers=new Set,this.pendingRequests=new Map,this.pendingStreams=new Map,this.request=async e=>{await this.ensureSocket();let t=Lr(`req`),n=Number.isFinite(e.timeoutMs)&&(e.timeoutMs??0)>0?Math.trunc(e.timeoutMs):Rr;return await new Promise((r,i)=>{let a=window.setTimeout(()=>{this.pendingRequests.delete(t),i(Error(`Timed out waiting for remote request response after ${n}ms: ${e.method} ${e.path}`))},n);this.pendingRequests.set(t,{resolve:e=>r(e),reject:i,timeoutId:a}),this.send({type:`request`,id:t,target:{method:e.method,path:e.path,...e.headers?{headers:e.headers}:{},...e.body===void 0?{}:{body:e.body}}})})},this.openStream=e=>{let t=Lr(`stream`),n=!1,r=e=>{n||(n=!0,a(e))},i,a,o=new Promise((e,t)=>{i=e,a=t}),s=()=>{this.pendingStreams.delete(t),!n&&(n=!0,this.send({type:`stream.cancel`,streamId:t}),a(Error(`stream cancelled`)))};this.pendingStreams.set(t,{onEvent:e.onEvent,finalResult:void 0,resolve:e=>{n||(n=!0,i(e))},reject:e=>{n||(n=!0,a(e))}});let c=()=>s();return e.signal&&(e.signal.aborted?s():e.signal.addEventListener(`abort`,c,{once:!0})),this.ensureSocket().then(()=>{n||this.send({type:`stream.open`,streamId:t,target:{method:e.method,path:e.path,...e.body===void 0?{}:{body:e.body}}})}).catch(e=>{this.pendingStreams.delete(t),r(e instanceof Error?e:Error(String(e)))}),{finished:o.finally(()=>{e.signal?.removeEventListener(`abort`,c),this.pendingStreams.delete(t)}),cancel:s}},this.subscribe=e=>(this.subscribers.add(e),this.ensureSocket().catch(t=>{e({type:`connection.error`,payload:{message:t instanceof Error?t.message:String(t)}})}),()=>{this.subscribers.delete(e)}),this.emit=e=>{for(let t of this.subscribers)t(e)},this.send=e=>{if(!this.socket||this.socket.readyState!==WebSocket.OPEN)throw Error(`Remote transport websocket is not connected.`);this.socket.send(JSON.stringify(e))},this.ensureSocket=async()=>{if(this.socket?.readyState===WebSocket.OPEN&&this.connectPromise===null)return;if(this.connectPromise)return await this.connectPromise;let e=Or(this.apiBase,this.runtime.wsPath);this.manualClose=!1,this.connectPromise=new Promise((t,n)=>{let r=new WebSocket(e);this.socket=r;let i=!1,a=()=>{this.connectTimeoutId!==null&&(window.clearTimeout(this.connectTimeoutId),this.connectTimeoutId=null)};this.connectTimeoutId=window.setTimeout(()=>{this.connectTimeoutId=null,n(Error(`Timed out waiting for remote transport websocket.`)),r.close()},8e3),r.onopen=()=>{i=!0,a(),this.connectPromise=null,t(),this.emit({type:`connection.open`,payload:{}})},r.onmessage=e=>{try{let t=JSON.parse(String(e.data??``));if(t.type===`connection.ready`)return;this.handleFrame(t)}catch(e){console.error(`Failed to parse remote websocket frame:`,e)}},r.onerror=()=>{this.emit({type:`connection.error`,payload:{message:`remote websocket error`}})},r.onclose=()=>{a();let e=this.connectPromise!==null;this.socket=null,this.connectPromise=null,this.failPendingWork(Error(`Remote transport connection closed.`)),this.emit({type:`connection.close`,payload:{}}),e&&!i&&n(Error(`Remote transport connection closed before ready.`)),!this.manualClose&&this.subscribers.size>0&&this.scheduleReconnect()}});let{connectPromise:t}=this;return await t},this.scheduleReconnect=()=>{this.reconnectTimer===null&&(this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=null,this.ensureSocket().catch(()=>void 0)},3e3))},this.failPendingWork=e=>{for(let t of this.pendingRequests.values())window.clearTimeout(t.timeoutId),t.reject(e);this.pendingRequests.clear();for(let t of this.pendingStreams.values())t.reject(e);this.pendingStreams.clear()},this.handleFrame=e=>{if(e.type===`response`||e.type===`request.error`){this.handleRequestFrame(e);return}if(e.type===`stream.event`||e.type===`stream.end`||e.type===`stream.error`){this.handleStreamFrame(e);return}if(e.type===`event`){this.emit(e.event);return}e.type===`connection.error`&&this.emit({type:`connection.error`,payload:{message:e.message}})},this.handleRequestFrame=e=>{let t=this.pendingRequests.get(e.id);if(t){if(this.pendingRequests.delete(e.id),window.clearTimeout(t.timeoutId),e.type===`request.error`){t.reject(Error(e.message));return}if(e.status>=400){t.reject(Fr(e.body,e.status,`Remote request failed.`));return}try{t.resolve(Ir(e.body))}catch(e){t.reject(e instanceof Error?e:Error(String(e)))}}},this.handleStreamFrame=e=>{let t=this.pendingStreams.get(e.streamId);if(t){if(e.type===`stream.event`){try{e.event===`final`&&(t.finalResult=e.payload),t.onEvent({name:e.event,payload:e.payload})}catch(n){this.pendingStreams.delete(e.streamId),t.reject(n instanceof Error?n:Error(String(n)))}return}if(this.pendingStreams.delete(e.streamId),e.type===`stream.end`){t.resolve(t.finalResult);return}t.reject(Error(e.message))}}}},Br=`/_remote/runtime`,Vr={mode:`remote`,protocolVersion:1,wsPath:`/_remote/ws`};async function Hr(e){let t=`${e.replace(/\/$/,``)}${Br}`,n;try{n=await fetch(t,{method:`GET`,credentials:`include`,cache:`no-store`})}catch{return new Nr({apiBase:e})}if(n.status===404)return new Nr({apiBase:e});if(!(n.headers.get(`content-type`)?.toLowerCase()??``).includes(`application/json`))return n.status>=400?new zr(Vr,e):new Nr({apiBase:e});let r=null;try{r=await n.json()}catch{return n.status>=400?new zr(Vr,e):new Nr({apiBase:e})}return n.ok&&r.ok&&r.data?.mode===`remote`?new zr(r.data,e):n.status>=400?new zr(Vr,e):new Nr({apiBase:e})}var Ur=new class{constructor(e=(void 0)?.trim().replace(/\/$/,``)||(typeof window<`u`?window.location.origin:`http://127.0.0.1:55667`)){this.apiBase=e,this.transportPromise=null,this.getTransport=async()=>(this.transportPromise||=Hr(this.apiBase),await this.transportPromise),this.request=async e=>await(await this.getTransport()).request(e),this.openStream=e=>{let t=null,n,r,i=new Promise((e,t)=>{n=e,r=t});return this.getTransport().then(i=>{t=i.openStream(e),t.finished.then(n).catch(e=>{r(e instanceof Error?e:Error(String(e)))})}).catch(e=>{r(e instanceof Error?e:Error(String(e)))}),{finished:i,cancel:()=>t?.cancel()}},this.subscribe=e=>{let t=()=>{},n=!0;return this.getTransport().then(r=>{n&&(t=r.subscribe(e))}).catch(t=>{e({type:`connection.error`,payload:{message:t instanceof Error?t.message:String(t)}})}),()=>{n=!1,t()}}}};function Wr(e){let t=e.trim().toLowerCase();return t?[`failed to fetch`,`networkerror`,`network request failed`,`load failed`,`request timed out`,`timed out waiting for remote request response`,`remote transport connection closed`,`websocket error`,`fetch failed on `,`stream request failed for `,`ncp fetch failed for `].some(e=>t.includes(e)):!1}var $=new Tn({baseUrl:Dn,transport:{request:async({body:e,headers:t,method:n,path:r,query:i,signal:a,timeoutMs:o})=>await Ur.request({method:n,path:Kr(r,Gr(i)),...e===void 0?{}:{body:e},...t?{headers:t}:{},...a?{signal:a}:{},...o===void 0?{}:{timeoutMs:o}}),upload:async({formData:e,headers:t,path:n,signal:r})=>{let i=await fetch(`${Dn}${n}`,{method:`POST`,body:e,credentials:`include`,...t?{headers:t}:{},...r?{signal:r}:{}}),a=await i.json();if(!i.ok||!a.ok)throw Error(qr(a,`Upload failed for ${n}`));return a.data},subscribe:e=>Ur.subscribe(e)}});function Gr(e){if(!e)return;if(e instanceof URLSearchParams)return e;let t=new URLSearchParams;for(let[n,r]of Object.entries(e)){let e=Array.isArray(r)?r:[r];for(let r of e)r!=null&&t.append(n,String(r))}return t}function Kr(e,t){let n=t?.toString();return n?`${e}${e.includes(`?`)?`&`:`?`}${n}`:e}function qr(e,t){return e.ok?t:e.error.message}async function Jr(){return{agents:await $.agents.list()}}async function Yr(e,t){return await $.agents.update(e,t)}async function Xr(e){return await $.agents.delete(e)}async function Zr(e,t={}){return await $.channelAuth.start(e,t)}async function Qr(e,t){return await $.channelAuth.poll(e,t)}async function $r(e,t){return await $.channelAuth.connect(e,t)}async function ei(e={}){return await $.auth.fetchStatus({timeoutMs:e.timeoutMs??5e3})}async function ti(e){return await $.auth.setup(e)}async function ni(e){return await $.auth.login(e)}async function ri(){return await $.auth.logout()}async function ii(e){return await $.auth.updatePassword(e)}async function ai(e){return await $.auth.updateEnabled(e)}async function oi(){return await $.app.fetchMeta()}async function si(e={}){return await $.app.fetchBootstrapStatus(e)}async function ci(){return await $.config.fetch()}async function li(){return await $.config.fetchMeta()}async function ui(){return await $.providers.list()}async function di(){return await $.providers.listTemplates()}async function fi(){return await $.config.fetchSchema()}async function pi(e){return await $.config.updateModel(e)}async function mi(e){return await $.config.updateSearch(e)}async function hi(e,t){return await $.providers.update(e,t)}async function gi(e={}){return await $.providers.create(e)}async function _i(e){return await $.providers.delete(e)}async function vi(e,t){return await $.providers.testConnection(e,t)}async function yi(e,t={}){return await $.providers.startAuth(e,t)}async function bi(e,t){return await $.providers.pollAuth(e,t)}async function xi(e){return await $.providers.importAuthFromCli(e)}async function Si(e,t){return await $.config.updateChannel(e,t)}async function Ci(e){return await $.config.updateRuntime(e)}async function wi(e){return await $.config.updateSecrets(e)}async function Ti(e,t){return await $.config.executeAction(e,t)}async function Ei(){return await $.config.fetchChatSessionTypes()}async function Di(e){return await $.config.fetchCronJobs(e)}async function Oi(e){return await $.config.deleteCronJob(e)}async function ki(e,t){return await $.config.setCronJobEnabled(e,t)}async function Ai(e,t){return await $.config.runCronJob(e,t)}async function ji(e){return await $.marketplace.fetchItems(e)}async function Mi(e){return await $.marketplace.fetchSkillContent(e)}async function Ni(){return await $.marketplace.fetchSkillScenes()}async function Pi(e){return await $.marketplace.install(e)}async function Fi(e){return await $.marketplace.fetchInstalled(e)}async function Ii(e){return await $.marketplace.manage(e)}async function Li(e){return await $.mcpMarketplace.fetchItems(e)}async function Ri(){return await $.mcpMarketplace.fetchInstalled()}async function zi(e){return await $.mcpMarketplace.fetchContent(e)}async function Bi(e){return await $.mcpMarketplace.install({type:`mcp`,...e})}async function Vi(e){return await $.mcpMarketplace.manage({type:`mcp`,...e})}async function Hi(e){return await $.mcpMarketplace.doctor(e)}async function Ui(e){return(await $.sessions.uploadAssets(e)).assets.map(e=>({id:e.id,name:e.name,mimeType:e.mimeType,sizeBytes:e.sizeBytes,assetUri:e.assetUri,url:e.url}))}async function Wi(e){return await $.sessions.list(e)}async function Gi(e,t=200){return await $.sessions.listMessages(e,t)}async function Ki(e,t){return await $.sessions.listSkills(e,t)}async function qi(e,t){return await $.sessions.update(e,t)}async function Ji(e){return await $.sessions.delete(e)}function Yi(e){return e.lastMessageAt??e.createdAt??e.updatedAt}function Xi(e){return[...e].sort((e,t)=>Yi(t).localeCompare(Yi(e)))}function Zi(e,t){let n=t.updatedAt.localeCompare(e.updatedAt);return n===0?e.status===t.status||t.status===`idle`:n>0}function Qi(e,t){if(e[0]!==`ncp-sessions`)return!1;let n=typeof e[2]==`string`?e[2].trim():``;return!n||t.peerId===n}function $i(e,t){if(!e)return e;let n=e.sessions.findIndex(e=>e.sessionId===t.sessionId),r=Xi(n>=0?e.sessions.map((e,r)=>r===n&&Zi(e,t)?{...t,status:e.status===`running`&&t.status===`idle`?`running`:t.status}:e):[...e.sessions,t]);return{...e,sessions:r,total:r.length}}function ea(e,t){if(!e)return e;let n=t.trim();if(!n)return e;let r=e.sessions.filter(e=>e.sessionId!==n);return r.length===e.sessions.length?e:{...e,sessions:r,total:r.length}}function ta(e,t){e?.setQueriesData({predicate:e=>Qi(e.queryKey,t)},e=>$i(e,t))}function na(e,t){if(!e)return e;let n=t.sessionKey.trim();if(!n)return e;let r=!1,i=e.sessions.map(e=>e.sessionId!==n||e.status===t.status?e:(r=!0,{...e,status:t.status}));return r?{...e,sessions:i}:e}function ra(e,t){e?.setQueriesData({queryKey:[`ncp-sessions`]},e=>na(e,t))}function ia(e,t){e?.setQueriesData({queryKey:[`ncp-sessions`]},e=>ea(e,t))}function aa(e,t){if(t.type===`session.run-status`){ra(e,t.payload);return}if(t.type===`session.summary.upsert`){ta(e,t.payload.summary);return}ia(e,t.payload.sessionKey)}async function oa(){return await $.remote.fetchStatus()}async function sa(){return await $.remote.fetchDoctor()}async function ca(e){return await $.remote.startBrowserAuth(e)}async function la(e){return await $.remote.pollBrowserAuth(e)}async function ua(){return await $.remote.logout()}async function da(e){return await $.remote.updateAccountProfile(e)}async function fa(e){return await $.remote.updateSettings(e)}async function pa(e){return await $.remote.controlService(e)}async function ma(){return await $.runtimeControl.fetch()}async function ha(){return await $.runtimeControl.startService()}async function ga(){return await $.runtimeControl.restartService()}async function _a(){return await $.runtimeControl.stopService()}async function va(){return await $.runtimeUpdate.fetch()}async function ya(){return await $.runtimeUpdate.check()}async function ba(){return await $.runtimeUpdate.download()}async function xa(){return await $.runtimeUpdate.apply()}async function Sa(e){return await $.runtimeUpdate.updatePreferences(e)}async function Ca(e){return await $.runtimeUpdate.updateChannel(e)}async function wa(e){return await $.serverPaths.browse(e)}async function Ta(e){return await $.serverPaths.read(e)}export{Ci as $,Te as $t,Pi as A,Ft as At,Di as B,Ye as Bt,Li as C,Dn as Ct,ji as D,Lt as Dt,Fi as E,Nt as Et,Ti as F,kt as Ft,bi as G,Ge as Gt,di as H,qe as Ht,oi as I,Dt as It,yi as J,Ve as Jt,Ai as K,Be as Kt,ci as L,wt as Lt,gi as M,jt as Mt,Oi as N,At as Nt,Mi as O,It as Ot,_i as P,K as Pt,hi as Q,H as Qt,li as R,Ct as Rt,Ri as S,X as St,Vi as T,Vt as Tt,ui as U,Ue as Ut,Ei as V,Je as Vt,xi as W,Ke as Wt,Si as X,Ie as Xt,vi as Y,ze as Yt,pi as Z,Pe as Zt,Wi as _,Yn as _t,oa as a,te as an,Xr as at,Hi as b,Kn as bt,ca as c,$ as ct,aa as d,tr as dt,Ee as en,mi as et,ia as f,ir as ft,Ki as g,Q as gt,Gi as h,Qn as ht,sa as i,m as in,Zr as it,Ii as j,Mt as jt,Ni as k,Pt as kt,da as l,Wr as lt,Ji as m,$n as mt,Ta as n,_e as nn,$r as nt,ua as o,T as on,Jr as ot,ta as p,sr as pt,ki as q,He as qt,pa as r,N as rn,Qr as rt,la as s,l as sn,Yr as st,wa as t,R as tn,wi as tt,fa as u,vr as ut,qi as v,Jn as vt,Bi as w,Y as wt,zi as x,Z as xt,Ui as y,qn as yt,fi as z,W as zt};