@dmrlzz/davecode 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ChatApp-BO7QMBWD.js → ChatApp-CJBICQGA.js} +6 -6
- package/dist/{account-UGNLJPQ4.js → account-QWDPJWAA.js} +3 -3
- package/dist/{accounts-NM7IWP53.js → accounts-IQMR72FC.js} +5 -5
- package/dist/{budget-INAW6FXD.js → budget-XANOUVWO.js} +4 -4
- package/dist/{chat-U4QJQ7M6.js → chat-KDDRNC5V.js} +8 -8
- package/dist/{chunk-CWBVNS3L.js → chunk-44AFJL2X.js} +4 -4
- package/dist/{chunk-MOK5D3XJ.js → chunk-AZKACMME.js} +2 -2
- package/dist/{chunk-DZ2FDABF.js → chunk-FYPMA55O.js} +2 -2
- package/dist/{chunk-3Q2KCXLN.js → chunk-HSBJDV3O.js} +2 -2
- package/dist/{chunk-3Q2KCXLN.js.map → chunk-HSBJDV3O.js.map} +1 -1
- package/dist/{chunk-ROIUTNQV.js → chunk-JLATEHS7.js} +2 -2
- package/dist/{chunk-GZJ6JSO7.js → chunk-PGAJIGUF.js} +3 -3
- package/dist/{chunk-GHDOUII5.js → chunk-W7GPBEBZ.js} +2 -2
- package/dist/{chunk-Z6NQDJEN.js → chunk-WQ7MEWDF.js} +3 -3
- package/dist/{config-YEAPBMBX.js → config-YTUPIYZT.js} +3 -3
- package/dist/dashboard/assets/Accounts-cq8RLMoI.js +1 -0
- package/dist/dashboard/assets/{Badge-CGY6DgGx.js → Badge-Z4RBdO9j.js} +2 -2
- package/dist/dashboard/assets/Callout-w8BTYh4k.js +1 -0
- package/dist/dashboard/assets/Field-Cmpgg_1z.js +1 -0
- package/dist/dashboard/assets/Goals-Bw02to72.js +1 -0
- package/dist/dashboard/assets/Library-DK7mlpRb.js +1 -0
- package/dist/dashboard/assets/{Markdown-Xhao3sgL.js → Markdown-DCZ4Awcc.js} +2 -2
- package/dist/dashboard/assets/Panes-_KTf8pbZ.js +8 -0
- package/dist/dashboard/assets/Panes-kHJ-D0s7.css +1 -0
- package/dist/dashboard/assets/RoutesPage-QV0oPRW9.js +4 -0
- package/dist/dashboard/assets/Runner-CkHBLQl0.js +1 -0
- package/dist/dashboard/assets/Settings-BLz2gTBR.js +1 -0
- package/dist/dashboard/assets/Switch-DPYlLseH.js +1 -0
- package/dist/dashboard/assets/Tasks-BiUQSTpt.js +2 -0
- package/dist/dashboard/assets/Traffic-BVfBuC70.js +1 -0
- package/dist/dashboard/assets/Workspace-CJTgiiU5.js +1 -0
- package/dist/dashboard/assets/arrow-up-DjhzZprp.js +1 -0
- package/dist/dashboard/assets/cn-BwE4cei0.js +1 -0
- package/dist/dashboard/assets/forms-DVIUAxAc.js +1 -0
- package/dist/dashboard/assets/index-BDBa5cb0.js +104 -0
- package/dist/dashboard/assets/index-BEmBgsbP.css +2 -0
- package/dist/dashboard/assets/task-errors-Daqwi0ue.js +1 -0
- package/dist/dashboard/assets/trash-BTuDcSaQ.js +1 -0
- package/dist/dashboard/index.html +4 -4
- package/dist/{dist-RRQGUBL3.js → dist-37VQSHHA.js} +2 -2
- package/dist/{doctor-MQYK44S2.js → doctor-PYUQRRCB.js} +3 -3
- package/dist/{goal-6NUX4AIT.js → goal-SXZUDUCL.js} +3 -3
- package/dist/index.js +31 -31
- package/dist/{init-AXYIWAB3.js → init-Z2AFQEEP.js} +3 -3
- package/dist/{run-QRTLHFB3.js → run-AOS7L3RT.js} +3 -3
- package/dist/runtime.js +2 -2
- package/dist/{start-O5I5TSO2.js → start-CEPXKZUE.js} +3 -3
- package/dist/{status-LEA3RVUX.js → status-WNJ3GGKU.js} +4 -4
- package/dist/{tasks-XOTVICVZ.js → tasks-TFUTUMWB.js} +4 -4
- package/package.json +4 -4
- package/dist/dashboard/assets/Accounts-CeVyX4a3.js +0 -1
- package/dist/dashboard/assets/Callout-DauCk_cW.js +0 -1
- package/dist/dashboard/assets/Field-OXMnT9Tb.js +0 -1
- package/dist/dashboard/assets/Goals-DH-KDh8M.js +0 -1
- package/dist/dashboard/assets/Library-C15szLjZ.js +0 -1
- package/dist/dashboard/assets/Panel-Du40pM7n.js +0 -1
- package/dist/dashboard/assets/RoutesPage-Cj1OelGO.js +0 -4
- package/dist/dashboard/assets/Runner-BK1-ZF7h.js +0 -1
- package/dist/dashboard/assets/Settings-C1nzQQhe.js +0 -1
- package/dist/dashboard/assets/Switch-bwtIJ00H.js +0 -1
- package/dist/dashboard/assets/Tasks-x4s8IiPG.js +0 -2
- package/dist/dashboard/assets/Traffic-CV7TaTid.js +0 -1
- package/dist/dashboard/assets/Workspace-DAL-MBc0.js +0 -1
- package/dist/dashboard/assets/arrow-up-goM9r-I9.js +0 -1
- package/dist/dashboard/assets/forms-DtpfI65-.js +0 -1
- package/dist/dashboard/assets/index-BCi-Vuvh.js +0 -104
- package/dist/dashboard/assets/index-CcJFhc98.css +0 -2
- package/dist/dashboard/assets/task-errors-B2pgjUGN.js +0 -1
- package/dist/dashboard/assets/trash-BVojETtF.js +0 -1
- /package/dist/{ChatApp-BO7QMBWD.js.map → ChatApp-CJBICQGA.js.map} +0 -0
- /package/dist/{account-UGNLJPQ4.js.map → account-QWDPJWAA.js.map} +0 -0
- /package/dist/{accounts-NM7IWP53.js.map → accounts-IQMR72FC.js.map} +0 -0
- /package/dist/{budget-INAW6FXD.js.map → budget-XANOUVWO.js.map} +0 -0
- /package/dist/{chat-U4QJQ7M6.js.map → chat-KDDRNC5V.js.map} +0 -0
- /package/dist/{chunk-CWBVNS3L.js.map → chunk-44AFJL2X.js.map} +0 -0
- /package/dist/{chunk-MOK5D3XJ.js.map → chunk-AZKACMME.js.map} +0 -0
- /package/dist/{chunk-DZ2FDABF.js.map → chunk-FYPMA55O.js.map} +0 -0
- /package/dist/{chunk-ROIUTNQV.js.map → chunk-JLATEHS7.js.map} +0 -0
- /package/dist/{chunk-GZJ6JSO7.js.map → chunk-PGAJIGUF.js.map} +0 -0
- /package/dist/{chunk-GHDOUII5.js.map → chunk-W7GPBEBZ.js.map} +0 -0
- /package/dist/{chunk-Z6NQDJEN.js.map → chunk-WQ7MEWDF.js.map} +0 -0
- /package/dist/{config-YEAPBMBX.js.map → config-YTUPIYZT.js.map} +0 -0
- /package/dist/{dist-RRQGUBL3.js.map → dist-37VQSHHA.js.map} +0 -0
- /package/dist/{doctor-MQYK44S2.js.map → doctor-PYUQRRCB.js.map} +0 -0
- /package/dist/{goal-6NUX4AIT.js.map → goal-SXZUDUCL.js.map} +0 -0
- /package/dist/{init-AXYIWAB3.js.map → init-Z2AFQEEP.js.map} +0 -0
- /package/dist/{run-QRTLHFB3.js.map → run-AOS7L3RT.js.map} +0 -0
- /package/dist/{start-O5I5TSO2.js.map → start-CEPXKZUE.js.map} +0 -0
- /package/dist/{status-LEA3RVUX.js.map → status-WNJ3GGKU.js.map} +0 -0
- /package/dist/{tasks-XOTVICVZ.js.map → tasks-TFUTUMWB.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as e,c as t,o as n,s as r,u as i}from"./Panel-Du40pM7n.js";var a=i(t(),1),o=r(),s=a.createContext(void 0),c=e=>{let t=a.useContext(s);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},l=({client:e,children:t})=>(a.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,o.jsx)(s.Provider,{value:e,children:t})),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){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 b(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)=>T(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function C(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)&&Array.isArray(t)){if(t.length>e.length)return!1;for(let n=0;n<t.length;n++)if(!C(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!C(e[r],t[r]))return!1;return!0}return!1}var ee=Object.prototype.hasOwnProperty;function te(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=ne(e)&&ne(t);if(!r&&!(T(e)&&T(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:ee.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 w(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 ne(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function T(e){if(!re(e))return!1;let t=Object.getPrototypeOf(e),n=t?.constructor;if(n===void 0)return!0;if(typeof n!=`function`)return!1;let r=n.prototype;return!(!re(r)||!r.hasOwnProperty(`isPrototypeOf`)||t!==Object.prototype)}function re(e){return Object.prototype.toString.call(e)===`[object Object]`}function ie(e){return new Promise(t=>{d.setTimeout(t,e)})}function E(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:te(e,t)}function ae(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function oe(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var D=Symbol();function se(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===D?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function ce(e,t){return typeof e==`function`?e(...t):!!e}function le(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0})),i)}),e}var ue=()=>p,de=()=>ue(),O=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(){}},fe=new class extends O{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&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`}},pe=f;function me(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=pe,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 k=me(),he=new class extends O{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&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 ge(e){return Math.min(1e3*2**e,3e4)}function _e(e){return(e??`online`)!==`online`||he.isOnline()}var ve=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function ye(e){let t=!1,n=0,r,i=`pending`,a,o,s=new Promise((e,t)=>{a=e,o=t});s.catch(m);let c=()=>i!==`pending`,l=t=>{if(!c()){let n=new ve(t);g(n),e.onCancel?.(n)}},u=()=>{t=!0},d=()=>{t=!1},f=()=>fe.isFocused()&&(e.networkMode===`always`||he.isOnline())&&e.canRun(),p=()=>_e(e.networkMode)&&e.canRun(),h=e=>{c()||(r?.(),i=`resolved`,a(e))},g=e=>{c()||(r?.(),i=`rejected`,o(e))},_=t=>new Promise(n=>{r=e=>{(c()||t())&&n(e)},e.onPause?.()}).then(()=>{r=void 0,c()||e.onContinue?.()}),v=()=>{if(c())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(h).catch(r=>{if(c())return;let i=e.retry??(de()?0:3),a=e.retryDelay??ge,o=typeof a==`function`?a(n,r):a,s=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);t||!s?g(r):(n++,e.onFail?.(n,r),ie(o).then(()=>f()?void 0:_(f)).then(()=>{t?g(r):v()}))})};return{promise:s,status:()=>i,cancel:l,continue:()=>(r?.(),s),cancelRetry:u,continueRetry:d,canStart:p,start:()=>(p()?v():_(p).then(v),s)}}var be=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??(de()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(d.clearTimeout(this.#e),this.#e=void 0)}};function xe(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=>{le(e,()=>t.signal,()=>n=!0)},u=se(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})(),o=await u(a),{maxPages:s}=t.options,c=i?oe:ae;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?Ce:Se,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]===void 0?r.initialPageParam:o[0]:Se(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(c<t)}return s};t.fetchFn=t.options.persister?()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function Se(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 Ce(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var we=class extends be{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=De(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=De(this.options);e.data!==void 0&&(this.setState(Ee(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=E(this.state.data,e,this.options);return this.#c({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#c({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(m).catch(m):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>v(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===D||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>v(e.options.staleTime,this)===`static`)}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.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){let t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#a&&(this.#s||this.state.fetchStatus===`paused`&&this.state.status===`pending`?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#c({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.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.#s=!0,n.signal)})},i=()=>{let e=se(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!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.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?xe(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#c({type:`fetch`,meta:a.fetchOptions?.meta});let o=this.#a=ye({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof ve&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#c({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#c({type:`pause`})},onContinue:()=>{this.#c({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await o.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof ve){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#c({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.#a===o&&(this.#a=void 0),this.scheduleGc()}}#c(e){let t=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,...Te(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...Ee(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=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=t(this.state),k.batch(()=>{this.observers.slice().forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function Te(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:_e(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function Ee(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function De(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 Oe=class extends O{#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#o=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Ae(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return A(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return A(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 v(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&&!w(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&je(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),r&&(this.#t!==n||v(this.options.enabled,this.#t)!==v(t.enabled,this.#t)||v(this.options.staleTime,this.#t)!==v(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||v(this.options.enabled,this.#t)!==v(t.enabled,this.#t)||i!==this.#f)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return w(this.getCurrentResult(),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),Reflect.get(e,n))})}trackProp(e){this.#p.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),r=()=>{},i,a=new Promise(e=>{i=e,r=this.#e.getQueryCache().subscribe(i=>{i.type===`updated`&&i.query.queryHash===n.queryHash&&n.state.data!==void 0&&(r(),e(this.createResult(n,t)))})});return Promise.race([n.fetch(t).then(()=>{let e=this.createResult(n,t);return i?.(e),e}).finally(()=>{r()}),a])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#m(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(m)),t}#h(e){return!de()&&v(this.options.enabled,this.#t)!==!1&&g(e)}#g(){this.#b();let e=v(this.options.staleTime,this.#t);if(this.#r.isStale||!this.#h(e))return;let t=_(this.#r.dataUpdatedAt,e)+1;this.#u=d.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return v(this.options.refetchInterval,this.#t)??!1}#v(e){this.#x(),this.#f=e,this.#f!==0&&this.#h(this.#f)&&(this.#d=d.setInterval(()=>{(this.options.refetchIntervalInBackground||fe.isFocused())&&this.#m()},this.#f))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#u!==void 0&&(d.clearTimeout(this.#u),this.#u=void 0)}#x(){this.#d!==void 0&&(d.clearInterval(this.#d),this.#d=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&&Ae(e,t),o=i&&je(e,n,t,r);(a||o)&&(l={...l,...Te(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.#l?.state.data,this.#l):t.placeholderData,e!==void 0&&(m=`success`,d=E(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h){if(i&&d===a?.data&&t.select===this.#s)d=this.#c;else try{this.#s=t.select,d=t.select(d),d=E(i?.data,d,t),this.#c=d,this.#o=null}catch(e){this.#o=e}}else d===void 0&&(this.#o=null);this.#o&&(f=this.#o,d=this.#c,p=Date.now(),m=`error`,u=!1);let g=l.fetchStatus===`fetching`,_=m===`pending`,y=m===`error`,b=_&&g,x=d!==void 0;return{status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:y,isInitialLoading:b,isLoading:b,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:y&&!x,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:y&&x,isStale:j(e,t),refetch:this.refetch,isEnabled:v(t.enabled,e)!==!1}}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);if(this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#l=this.#t),w(t,e))return;this.#r=t;let n=(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#p.size)return!0;let r=new Set(n??this.#p);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)})})();k.batch(()=>{n&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}#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()}};function ke(e,t){return v(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||v(t.retryOnMount,e)!==!1)}function Ae(e,t){return ke(e,t)||e.state.data!==void 0&&A(e,t,t.refetchOnMount)}function A(e,t,n){if(v(t.enabled,e)!==!1&&v(t.staleTime,e)!==`static`){let r=v(n,e);return r===`always`||r!==!1&&j(e,t)}return!1}function je(e,t,n,r){return(e!==t||v(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&j(e,n)}function j(e,t){return v(t.enabled,e)!==!1&&e.isStaleByTime(v(t.staleTime,e))}var Me=class extends be{#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||Ne(),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.state.status===`pending`?this.execute(this.state.variables):Promise.resolve())}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},r=this.#r=ye({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)}),i=this.state.status===`pending`,a=!r.canStart();try{if(i)t();else{this.#i({type:`pending`,variables:e,isPaused:a}),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:a})}let o=await r.start();return await this.#n.config.onSuccess?.(o,e,this.state.context,this,n),await this.options.onSuccess?.(o,e,this.state.context,n),await this.#n.config.onSettled?.(o,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(o,null,e,this.state.context,n),this.#i({type:`success`,data:o}),o}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.#r===r&&(this.#r=void 0),this.#n.runNext(this)}}#i(e){let t=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=t(this.state),k.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function Ne(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var Pe=class extends O{#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),w(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)}onSubscribe(){this.listeners.size===1&&this.#n&&(this.#n.addObserver(this),this.#i())}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??Ne();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){k.batch(()=>{let t=this.#r;if(t&&this.hasListeners()){let n=this.#t.variables,r=this.#t.context,i={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type===`success`){try{t.onSuccess?.(e.data,n,r,i)}catch(e){Promise.reject(e)}try{t.onSettled?.(e.data,null,n,r,i)}catch(e){Promise.reject(e)}}else if(e?.type===`error`){try{t.onError?.(e.error,n,r,i)}catch(e){Promise.reject(e)}try{t.onSettled?.(void 0,e.error,n,r,i)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}},Fe=a.createContext(!1),Ie=()=>a.useContext(Fe);Fe.Provider;function Le(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Re=a.createContext(Le()),ze=()=>a.useContext(Re),Be=(e,t,n)=>{let r=n?.state.status===`error`&&typeof e.throwOnError==`function`?ce(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||r)&&(t.isReset()||(e.retryOnMount=!1))},Ve=e=>{a.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||ce(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?.suspense&&t.isPending,Ge=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Ke(e,t,n){let r=Ie(),i=ze(),o=c(n),s=o.defaultQueryOptions(e),l=o.getQueryCache().get(s.queryHash),u=e.subscribed!==!1;s._optimisticResults=r?`isRestoring`:u?`optimistic`:void 0,Ue(s),Be(s,i,l),Ve(i);let[d]=a.useState(()=>new t(o,s)),f=d.getOptimisticResult(s),p=!r&&u;if(a.useSyncExternalStore(a.useCallback(e=>{let t=p?d.subscribe(k.batchCalls(e)):m;return d.updateResult(),t},[d,p]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),a.useEffect(()=>{d.setOptions(s)},[s,d]),We(s,f))throw Ge(s,d,i);if(He({result:f,errorResetBoundary:i,throwOnError:s.throwOnError,query:l,suspense:s.suspense}))throw f.error;return s.notifyOnChangeProps?f:d.trackResult(f)}function M(e,t){return Ke(e,Oe,t)}function N(e,t){let n=c(t),[r]=a.useState(()=>new Pe(n,e));a.useEffect(()=>{r.setOptions(e)},[r,e]);let i=a.useSyncExternalStore(a.useCallback(e=>r.subscribe(k.batchCalls(e)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),o=a.useCallback((...e)=>{r.mutate(e[0],e[1]).catch(m)},[r]);if(i.error&&ce(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:o,mutateAsync:i.mutate}}var qe={name:`asterisk`,size:24,node:[[`path`,{d:`M12 5v14`,key:`s699le`}],[`path`,{d:`m18.065 8.496-12.125 7`,key:`1h26g9`}],[`path`,{d:`m5.94 8.504 12.125 7`,key:`k77sdm`}]]};qe.node;var Je=n(qe),Ye={name:`globe`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20`,key:`13o1zl`}],[`path`,{d:`M2 12h20`,key:`9i4pu4`}]]};Ye.node;var Xe=n(Ye),Ze={name:`hexagon`,size:24,node:[[`path`,{d:`M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z`,key:`yt0hxn`}]]};Ze.node;var Qe=n(Ze),$e={name:`server`,size:24,node:[[`rect`,{width:`20`,height:`8`,x:`2`,y:`2`,rx:`2`,ry:`2`,key:`ngkwjq`}],[`rect`,{width:`20`,height:`8`,x:`2`,y:`14`,rx:`2`,ry:`2`,key:`iecqi9`}],[`line`,{x1:`6`,x2:`6.01`,y1:`6`,y2:`6`,key:`16zg32`}],[`line`,{x1:`6`,x2:`6.01`,y1:`18`,y2:`18`,key:`nzw8ys`}]]};$e.node;var et=n($e),tt={name:`sparkle`,size:24,node:[[`path`,{d:`M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z`,key:`1s2grr`}]]};tt.node;var nt=n(tt),rt={name:`sparkles`,size:24,node:[[`path`,{d:`M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z`,key:`1s2grr`}],[`path`,{d:`M20 2v4`,key:`1rf3ol`}],[`path`,{d:`M22 4h-4`,key:`gwowj6`}],[`circle`,{cx:`4`,cy:`20`,r:`2`,key:`6kqj1y`}]],aliases:[`stars`]};rt.node;var it=n(rt),at={name:`square-terminal`,size:24,node:[[`path`,{d:`m7 11 2-2-2-2`,key:`1lz0vl`}],[`path`,{d:`M11 13h4`,key:`1p7l4v`}],[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,ry:`2`,key:`1m3agn`}]],aliases:[`terminal-square`]};at.node;var ot=n(at),P={gatewayUrl:`davecode.gatewayUrl`,token:`davecode.token`,theme:`davecode.theme`,dataMode:`davecode.dataMode`,sidebarCollapsed:`davecode.sidebarCollapsed`};function F(e){try{return window.localStorage.getItem(e)}catch{return null}}function I(e,t){try{t===``?window.localStorage.removeItem(e):window.localStorage.setItem(e,t)}catch{}}function st(){let e=F(P.theme),t=F(P.dataMode);return{gatewayUrl:F(P.gatewayUrl)??``,token:F(P.token)??``,theme:e===`light`||e===`system`?e:`dark`,dataMode:t===`live`||t===`mock`?t:`auto`,sidebarCollapsed:F(P.sidebarCollapsed)===`1`}}var L=typeof window>`u`?ct():st(),R=new Set;function ct(){return{gatewayUrl:``,token:``,theme:`dark`,dataMode:`auto`,sidebarCollapsed:!1}}function z(){return L}function lt(e){L={...L,...e};for(let[t,n]of Object.entries(e)){let e=P[t];t===`sidebarCollapsed`?I(e,n?`1`:``):t===`theme`?I(e,String(n)):I(e,String(n??``))}for(let e of R)e()}function ut(e){return R.add(e),()=>R.delete(e)}function dt(){return(0,a.useSyncExternalStore)(ut,z,z)}function ft(){if(typeof window>`u`)return!1;let e=new URLSearchParams(window.location.search).get(`mock`),t=window.location.hash.split(`?`)[1]??``,n=new URLSearchParams(t).get(`mock`);return e===`1`||n===`1`}function pt(e){return e===`system`?window.matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`:e}function mt(e){let t=()=>{document.documentElement.dataset.theme=pt(e)};if(t(),e!==`system`)return()=>{};let n=window.matchMedia(`(prefers-color-scheme: light)`);return n.addEventListener(`change`,t),()=>n.removeEventListener(`change`,t)}var ht=[`request.started`,`request.completed`,`request.failed`,`router.failover`,`account.updated`,`account.removed`,`quota.updated`,`task.updated`,`task.removed`,`runner.status`,`runner.log`,`goal.updated`,`goal.log`,`log`];function gt(e,t=Math.random){let n=Math.min(3e4,1e3*2**Math.max(0,e-1)),r=n*.2*(t()*2-1);return Math.round(n+r)}function _t(e){try{let t=JSON.parse(e);if(t&&typeof t==`object`&&typeof t.type==`string`)return t}catch{}return null}function vt(e,t){let n=null,r,i=0,a=!1,o,s=e=>t.onStatus?.({...e,attempt:i,lastEventAt:o}),c=e=>{let n=_t(e.data);n&&(o=Date.now(),t.onEvent(n))},l=()=>{if(!a){s({state:i===0?`connecting`:`reconnecting`}),n=new EventSource(e),n.onopen=()=>{i=0,o=Date.now(),s({state:`open`})},n.onmessage=c;for(let e of ht)n.addEventListener(e,c);n.onerror=()=>{if(n?.close(),n=null,a)return;i+=1;let e=gt(i);s({state:`reconnecting`,retryAt:Date.now()+e}),r=window.setTimeout(l,e)}}};return l(),()=>{a=!0,window.clearTimeout(r),n?.close(),n=null}}var B=class extends Error{status;code;cycle;dependents;constructor(e,t,n,r={}){super(n),this.name=`ApiError`,this.status=e,this.code=t,r.cycle&&(this.cycle=r.cycle),r.dependents&&(this.dependents=r.dependents)}get reachable(){return this.status>0&&!yt.has(this.code)}},yt=new Set([`network`,`bad_response`,`gateway_unreachable`]);function bt(e){return e instanceof B}function xt(e,t){return`${e.replace(/\/+$/,``)}${t}`}function St({baseUrl:e,token:t}){async function n(n,r,i){let a={Accept:`application/json`};t&&(a.Authorization=`Bearer ${t}`),i!==void 0&&(a[`Content-Type`]=`application/json`);let o;try{o=await fetch(xt(e,r),{method:n,headers:a,body:i===void 0?void 0:JSON.stringify(i)})}catch(e){throw new B(0,`network`,`Gateway unreachable: ${e.message}`)}if(o.status===204)return;let s=await o.text(),c;try{c=s?JSON.parse(s):void 0}catch{throw new B(o.ok?0:o.status,`bad_response`,`Unexpected non-JSON response from ${r}`)}if(!o.ok){let e=c?.error;throw!e&&o.status>=502&&o.status<=504?new B(o.status,`gateway_unreachable`,`Gateway unreachable (proxy answered ${o.status})`):new B(o.status,e?.code??`http_${o.status}`,e?.message??`${n} ${r} failed with ${o.status}`,{...e?.cycle&&{cycle:e.cycle},...e?.dependents&&{dependents:e.dependents}})}return c}let r=e=>n(`GET`,e);return{mode:`live`,health:()=>r(`/api/health`),listAccounts:async()=>(await r(`/api/accounts`)).accounts,createAccount:async e=>(await n(`POST`,`/api/accounts`,e)).account,updateAccount:async(e,t)=>(await n(`PATCH`,`/api/accounts/${encodeURIComponent(e)}`,t)).account,deleteAccount:e=>n(`DELETE`,`/api/accounts/${encodeURIComponent(e)}`),usage:async()=>(await r(`/api/usage`)).usage,budget:async()=>(await r(`/api/budget`)).budget,connection:async e=>(await r(`/api/accounts/${encodeURIComponent(e)}/connection`)).connection,connect:async e=>(await n(`POST`,`/api/accounts/${encodeURIComponent(e)}/connect`,{})).connect,timeseries:async(e=60,t=60)=>(await r(`/api/usage/timeseries?minutes=${e}&bucketSec=${t}`)).buckets,requests:async(e=100)=>(await r(`/api/requests?limit=${e}`)).requests,routes:()=>r(`/api/routes`),updateRoutes:e=>n(`PUT`,`/api/routes`,e),tasks:()=>r(`/api/tasks`),createTask:async e=>(await n(`POST`,`/api/tasks`,e)).task,updateTask:async(e,t)=>(await n(`PATCH`,`/api/tasks/${encodeURIComponent(e)}`,t)).task,deleteTask:e=>n(`DELETE`,`/api/tasks/${encodeURIComponent(e)}`),brain:()=>r(`/api/brain`),runner:async()=>(await r(`/api/runner`)).status,runnerAction:async(e,t)=>(await n(`POST`,`/api/runner/${e}`,e===`start`&&t?.taskId?{taskId:t.taskId}:void 0)).status,logs:async(e=200)=>(await r(`/api/logs?limit=${e}`)).events,goals:async()=>(await r(`/api/goals`)).goals,startGoal:async e=>(await n(`POST`,`/api/goals`,e)).goal,executeGoal:async e=>(await n(`POST`,`/api/goals/${encodeURIComponent(e)}/execute`)).goal,goalArtifact:async(e,t)=>(await r(`/api/goals/${encodeURIComponent(e)}/artifacts/${encodeURIComponent(t)}`)).artifact,cancelGoal:async e=>(await n(`POST`,`/api/goals/${encodeURIComponent(e)}/cancel`)).goal,models:async()=>(await r(`/v1/models`)).data,subscribe:n=>vt(xt(e,`/api/events${t?`?token=${encodeURIComponent(t)}`:``}`),n)}}function Ct(e){return bt(e)?e.status===401?`Unauthorized: set the gateway token in Settings.`:e.message:e instanceof Error?e.message:String(e)}function wt(e){return e.type===`request.started`||e.type===`request.completed`||e.type===`request.failed`||e.type===`router.failover`}function Tt(e,t,n=``){return{requestId:e,model:n,startedTs:t,updatedTs:t,attempts:[],outcome:`pending`,failovers:0,exhausted:!1}}function Et(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if(r&&r.accountId===t&&r.outcome===`pending`)return n}return-1}var Dt=2e3;function Ot(e,t,n,r,i){for(let a=e.length-1;a>=0;a--){let o=e[a];if(!o||o.accountId!==t||i&&o.outcome!==i)continue;let s=o[r];if(s!==void 0&&Math.abs(s-n)<=Dt)return a}return-1}function kt(e){let t=e.attempts[e.attempts.length-1];return t?t.outcome===`success`?`success`:t.outcome===`pending`?`pending`:e.exhausted?`failed`:e.failovers>=e.attempts.length?`pending`:`failed`:`pending`}function At(e,t){let n=e??Tt(t.requestId,t.ts),r={...n,attempts:n.attempts.map(e=>({...e})),startedTs:Math.min(n.startedTs,t.ts),updatedTs:Math.max(n.updatedTs,t.ts)};switch(t.type){case`request.started`:r.model||=t.model,Et(r.attempts,t.accountId)===-1&&Ot(r.attempts,t.accountId,t.ts,`startedTs`)===-1&&r.attempts.push({accountId:t.accountId,provider:t.provider,startedTs:t.ts,outcome:`pending`});break;case`request.completed`:{r.model||=t.model;let e=Et(r.attempts,t.accountId);e===-1&&(e=Ot(r.attempts,t.accountId,t.ts,`endedTs`,`success`)),e===-1&&(r.attempts.push({accountId:t.accountId,provider:t.provider,startedTs:t.ts-t.latencyMs,outcome:`pending`}),e=r.attempts.length-1);let n=r.attempts[e];n&&(n.outcome=`success`,n.endedTs=t.ts,n.latencyMs=t.latencyMs,n.promptTokens=t.promptTokens,n.completionTokens=t.completionTokens),r.startedTs=Math.min(r.startedTs,t.ts-t.latencyMs);break}case`request.failed`:{let e=Et(r.attempts,t.accountId);e===-1&&(e=Ot(r.attempts,t.accountId,t.ts,`endedTs`,`failed`)),e===-1&&(r.attempts.push({accountId:t.accountId,provider:t.provider,startedTs:t.ts,outcome:`pending`}),e=r.attempts.length-1);let n=r.attempts[e];if(n){let e=n.outcome===`pending`;n.outcome=`failed`,n.endedTs=e?t.ts:n.endedTs??t.ts,n.latencyMs=n.latencyMs??t.ts-n.startedTs,n.errorKind=t.error.kind,n.errorStatus=t.error.status,n.errorMessage=t.error.message}break}case`router.failover`:{t.toAccountId===null&&(r.exhausted=!0);let e=!1;for(let n=r.attempts.length-1;n>=0;n--){let i=r.attempts[n];if(i&&i.accountId===t.fromAccountId){e=!0,i.failedOver||(i.failedOver=!0,r.failovers+=1),i.errorKind??=t.reason,i.outcome===`pending`&&(i.outcome=`failed`,i.endedTs=t.ts);break}}e||(r.failovers+=1);break}}return r.outcome=kt(r),r}function jt(e){let t=new Map;for(let n of e){let e=t.get(n.requestId);e?e.push(n):t.set(n.requestId,[n])}let n=[];for(let[e,r]of t){r.sort((e,t)=>e.ts-t.ts);let t=r[0];if(!t)continue;let i=r.map((e,t)=>({accountId:e.accountId,provider:e.provider,startedTs:e.ts-e.latencyMs,endedTs:e.ts,outcome:e.status===`success`?`success`:`failed`,latencyMs:e.latencyMs,promptTokens:e.promptTokens,completionTokens:e.completionTokens,errorKind:e.errorKind??(e.status===`rate_limited`?`rate_limit`:void 0),errorStatus:e.status===`rate_limited`?429:void 0,failedOver:t<r.length-1})),a=i[i.length-1];n.push({requestId:e,model:t.model,startedTs:i[0]?.startedTs??t.ts,updatedTs:a?.endedTs??t.ts,attempts:i,outcome:a?.outcome===`success`?`success`:`failed`,failovers:Math.max(0,i.length-1),exhausted:a?.outcome!==`success`})}return n.sort((e,t)=>t.startedTs-e.startedTs)}function Mt(e){let t=0,n=0;for(let r of e.attempts)t+=r.promptTokens??0,n+=r.completionTokens??0;return{prompt:t,completion:n}}function Nt(e){let t=e.attempts[e.attempts.length-1];if(t?.endedTs)return t.endedTs-e.startedTs}function Pt(e){if(e.errorStatus)return String(e.errorStatus);switch(e.errorKind){case`rate_limit`:return`429`;case`quota_exhausted`:return`quota`;case`unavailable`:return`503`;case`timeout`:return`timeout`;case`network`:return`network`;case`auth`:return`401`;case`context_length`:return`ctx`;case`bad_request`:return`400`;default:return`error`}}var Ft=600,It=400,Lt=3e3,Rt=4e3;function zt(e){return Math.floor(e/6e4)*6e4}function Bt(e){return JSON.stringify(e)}var Vt=class{flushMs;state={events:[],chains:[],logs:[],minutes:[],failoverTs:[]};chainIndex=new Map;seen=new Set;seenOrder=[];listeners=new Set;dirty=!1;flushTimer;pending=[];failovers=new Map;logSeq=0;constructor(e=200){this.flushMs=e}getState=()=>this.state;subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));ingest(e){let t=Bt(e);if(this.seen.has(t))return!1;if(this.seen.add(t),this.seenOrder.push(t),this.seenOrder.length>Rt){let e=this.seenOrder.shift();e&&this.seen.delete(e)}return this.pending.push(e),this.schedule(),!0}seedRecords(e){for(let t of jt(e))this.chainIndex.has(t.requestId)||this.chainIndex.set(t.requestId,t),t.attempts.slice(0,-1).forEach(e=>{this.failovers.set(`${t.requestId}:${e.accountId}`,e.endedTs??t.startedTs)});this.dirty=!0,this.schedule()}flush(){if(this.flushTimer!==void 0&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.pending.length===0&&!this.dirty)return;let e=this.pending;this.pending=[],this.dirty=!1;let t=this.state.events.concat(e),n=this.state.logs.slice(),r=new Map(this.state.minutes.map(e=>[e.ts,{...e}]));for(let t of e)if(wt(t)&&this.chainIndex.set(t.requestId,At(this.chainIndex.get(t.requestId),t)),t.type===`request.completed`){let e=zt(t.ts),n=r.get(e)??{ts:e,tokens:0,requests:0};n.tokens+=t.promptTokens+t.completionTokens,n.requests+=1,r.set(e,n)}else t.type===`router.failover`?this.failovers.set(`${t.requestId}:${t.fromAccountId}`,t.ts):t.type===`runner.log`?n.push({key:`l${this.logSeq++}`,ts:t.ts,level:t.level,message:t.message,source:`runner`,taskId:t.taskId}):t.type===`log`&&n.push({key:`l${this.logSeq++}`,ts:t.ts,level:t.level,message:t.message,source:`gateway`,scope:t.scope});let i=[...this.chainIndex.values()].sort((e,t)=>t.startedTs-e.startedTs);if(i.length>It){for(let e of i.slice(It))this.chainIndex.delete(e.requestId);i=i.slice(0,It)}n.sort((e,t)=>e.ts-t.ts);let a=Date.now()-36e5;for(let[e,t]of this.failovers)t<a&&this.failovers.delete(e);this.state={events:t.length>Ft?t.slice(-600):t,chains:i,logs:n.length>Lt?n.slice(-3e3):n,minutes:[...r.values()].sort((e,t)=>e.ts-t.ts).slice(-90),failoverTs:[...this.failovers.values()].sort((e,t)=>e-t)};for(let e of this.listeners)e()}clearLogs(){this.state={...this.state,logs:[]};for(let e of this.listeners)e()}dispose(){this.flushTimer!==void 0&&clearTimeout(this.flushTimer),this.flushTimer=void 0}schedule(){this.flushTimer===void 0&&(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flush()},this.flushMs))}},Ht=864e5,Ut=[`1m`,`5h`,`24h`],Wt={acc_claude_pro:{info:{plan:`Claude Pro`,price:{amount:20,currency:`USD`,period:`month`}},paidDaysAgo:21,renewsInDays:9},acc_anthropic_work:{info:{plan:`API — Build tier 2`,price:{amount:250,currency:`USD`,period:`month`},notes:`Prepaid credits, topped up monthly`},paidDaysAgo:12,renewsInDays:18},acc_openai_team:{info:{plan:`ChatGPT Team`,price:{amount:300,currency:`USD`,period:`year`}},paidDaysAgo:340,renewsInDays:2}},Gt=e=>new Date(e).toISOString().slice(0,10);function Kt(e,t){let n=Wt[e];if(n)return{...n.info,paidAt:Gt(t-n.paidDaysAgo*Ht),renewsAt:Gt(t+n.renewsInDays*Ht)}}function qt(e,t,n){let r=null,i;for(let e of Ut){let n=t.windows[e];if(n.tokenLimit===void 0&&n.requestLimit===void 0)continue;let a=Math.max(0,1-n.utilization);(r===null||a<r)&&(r=a,i=e)}let a={accountId:e.id,label:e.label,provider:e.provider,enabled:e.enabled,remaining:r,usage:t,available:e.enabled&&e.status===`active`&&(r??1)>0};if(i&&(a.tightestWindow=i),e.subscription){a.subscription=e.subscription;let t=e.subscription.renewsAt?Date.parse(e.subscription.renewsAt):NaN;Number.isNaN(t)||(a.renewsInDays=Math.ceil((t-n)/Ht))}return a.available||(a.unavailableReason=e.enabled?e.status===`cooldown`?`cooling down`:e.status===`error`?`credentials rejected (fix the account)`:`local quota limit reached`:`disabled`),a}function Jt(e,t){let n=e.filter(e=>e.enabled);if(n.length===0)return``;let r=[`ACCOUNT BUDGET (${`${new Date(t).toISOString().slice(0,16).replace(`T`,` `)} UTC`}; ${n.filter(e=>e.available).length} of ${n.length} accounts available).`,`The router already avoids exhausted accounts. When budget is scarce, keep prompts and outputs short and prefer fewer, larger steps.`];for(let e of n){let t=[];e.subscription?.plan&&t.push(e.subscription.plan);let n=e.subscription?.price;n&&t.push(`${n.amount} ${n.currency}/${n.period}`),e.renewsInDays!==void 0&&t.push(`renews in ${e.renewsInDays}d`);let i=`- ${e.label} [${e.provider}]${t.length?` (${t.join(`, `)})`:``}`,a=e.available?e.remaining===null?`no known limit`:`${Math.round(e.remaining*100)}% left (${e.tightestWindow} window)`:`unavailable: ${e.unavailableReason}`;r.push(`${i}: ${a}`)}return r.join(`
|
|
1
|
+
import{i as e,n as t,o as n,r,t as i}from"./cn-BwE4cei0.js";var a=n(e(),1),o=r(),s=a.createContext(void 0),c=e=>{let t=a.useContext(s);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},l=({client:e,children:t})=>(a.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,o.jsx)(s.Provider,{value:e,children:t})),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){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 b(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)=>T(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function C(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)&&Array.isArray(t)){if(t.length>e.length)return!1;for(let n=0;n<t.length;n++)if(!C(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!C(e[r],t[r]))return!1;return!0}return!1}var ee=Object.prototype.hasOwnProperty;function te(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=ne(e)&&ne(t);if(!r&&!(T(e)&&T(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:ee.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 w(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 ne(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function T(e){if(!re(e))return!1;let t=Object.getPrototypeOf(e),n=t?.constructor;if(n===void 0)return!0;if(typeof n!=`function`)return!1;let r=n.prototype;return!(!re(r)||!r.hasOwnProperty(`isPrototypeOf`)||t!==Object.prototype)}function re(e){return Object.prototype.toString.call(e)===`[object Object]`}function ie(e){return new Promise(t=>{d.setTimeout(t,e)})}function E(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:te(e,t)}function ae(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function oe(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var D=Symbol();function se(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===D?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function ce(e,t){return typeof e==`function`?e(...t):!!e}function le(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0})),i)}),e}var ue=()=>p,de=()=>ue(),O=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(){}},fe=new class extends O{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&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`}},pe=f;function me(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=pe,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 k=me(),he=new class extends O{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&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 ge(e){return Math.min(1e3*2**e,3e4)}function _e(e){return(e??`online`)!==`online`||he.isOnline()}var ve=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function ye(e){let t=!1,n=0,r,i=`pending`,a,o,s=new Promise((e,t)=>{a=e,o=t});s.catch(m);let c=()=>i!==`pending`,l=t=>{if(!c()){let n=new ve(t);g(n),e.onCancel?.(n)}},u=()=>{t=!0},d=()=>{t=!1},f=()=>fe.isFocused()&&(e.networkMode===`always`||he.isOnline())&&e.canRun(),p=()=>_e(e.networkMode)&&e.canRun(),h=e=>{c()||(r?.(),i=`resolved`,a(e))},g=e=>{c()||(r?.(),i=`rejected`,o(e))},_=t=>new Promise(n=>{r=e=>{(c()||t())&&n(e)},e.onPause?.()}).then(()=>{r=void 0,c()||e.onContinue?.()}),v=()=>{if(c())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(h).catch(r=>{if(c())return;let i=e.retry??(de()?0:3),a=e.retryDelay??ge,o=typeof a==`function`?a(n,r):a,s=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);t||!s?g(r):(n++,e.onFail?.(n,r),ie(o).then(()=>f()?void 0:_(f)).then(()=>{t?g(r):v()}))})};return{promise:s,status:()=>i,cancel:l,continue:()=>(r?.(),s),cancelRetry:u,continueRetry:d,canStart:p,start:()=>(p()?v():_(p).then(v),s)}}var be=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??(de()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(d.clearTimeout(this.#e),this.#e=void 0)}};function xe(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=>{le(e,()=>t.signal,()=>n=!0)},u=se(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})(),o=await u(a),{maxPages:s}=t.options,c=i?oe:ae;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?Ce:Se,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]===void 0?r.initialPageParam:o[0]:Se(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(c<t)}return s};t.fetchFn=t.options.persister?()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function Se(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 Ce(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var we=class extends be{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=De(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=De(this.options);e.data!==void 0&&(this.setState(Ee(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=E(this.state.data,e,this.options);return this.#c({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#c({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(m).catch(m):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>v(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===D||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>v(e.options.staleTime,this)===`static`)}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.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){let t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#a&&(this.#s||this.state.fetchStatus===`paused`&&this.state.status===`pending`?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#c({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.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.#s=!0,n.signal)})},i=()=>{let e=se(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!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.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?xe(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#c({type:`fetch`,meta:a.fetchOptions?.meta});let o=this.#a=ye({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof ve&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#c({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#c({type:`pause`})},onContinue:()=>{this.#c({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await o.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof ve){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#c({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.#a===o&&(this.#a=void 0),this.scheduleGc()}}#c(e){let t=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,...Te(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...Ee(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=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=t(this.state),k.batch(()=>{this.observers.slice().forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function Te(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:_e(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function Ee(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function De(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 Oe=class extends O{#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#o=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Ae(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return A(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return A(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 v(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&&!w(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&je(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),r&&(this.#t!==n||v(this.options.enabled,this.#t)!==v(t.enabled,this.#t)||v(this.options.staleTime,this.#t)!==v(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||v(this.options.enabled,this.#t)!==v(t.enabled,this.#t)||i!==this.#f)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return w(this.getCurrentResult(),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),Reflect.get(e,n))})}trackProp(e){this.#p.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),r=()=>{},i,a=new Promise(e=>{i=e,r=this.#e.getQueryCache().subscribe(i=>{i.type===`updated`&&i.query.queryHash===n.queryHash&&n.state.data!==void 0&&(r(),e(this.createResult(n,t)))})});return Promise.race([n.fetch(t).then(()=>{let e=this.createResult(n,t);return i?.(e),e}).finally(()=>{r()}),a])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#m(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(m)),t}#h(e){return!de()&&v(this.options.enabled,this.#t)!==!1&&g(e)}#g(){this.#b();let e=v(this.options.staleTime,this.#t);if(this.#r.isStale||!this.#h(e))return;let t=_(this.#r.dataUpdatedAt,e)+1;this.#u=d.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return v(this.options.refetchInterval,this.#t)??!1}#v(e){this.#x(),this.#f=e,this.#f!==0&&this.#h(this.#f)&&(this.#d=d.setInterval(()=>{(this.options.refetchIntervalInBackground||fe.isFocused())&&this.#m()},this.#f))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#u!==void 0&&(d.clearTimeout(this.#u),this.#u=void 0)}#x(){this.#d!==void 0&&(d.clearInterval(this.#d),this.#d=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&&Ae(e,t),o=i&&je(e,n,t,r);(a||o)&&(l={...l,...Te(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.#l?.state.data,this.#l):t.placeholderData,e!==void 0&&(m=`success`,d=E(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h){if(i&&d===a?.data&&t.select===this.#s)d=this.#c;else try{this.#s=t.select,d=t.select(d),d=E(i?.data,d,t),this.#c=d,this.#o=null}catch(e){this.#o=e}}else d===void 0&&(this.#o=null);this.#o&&(f=this.#o,d=this.#c,p=Date.now(),m=`error`,u=!1);let g=l.fetchStatus===`fetching`,_=m===`pending`,y=m===`error`,b=_&&g,x=d!==void 0;return{status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:y,isInitialLoading:b,isLoading:b,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:y&&!x,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:y&&x,isStale:j(e,t),refetch:this.refetch,isEnabled:v(t.enabled,e)!==!1}}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);if(this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#l=this.#t),w(t,e))return;this.#r=t;let n=(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#p.size)return!0;let r=new Set(n??this.#p);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)})})();k.batch(()=>{n&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}#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()}};function ke(e,t){return v(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||v(t.retryOnMount,e)!==!1)}function Ae(e,t){return ke(e,t)||e.state.data!==void 0&&A(e,t,t.refetchOnMount)}function A(e,t,n){if(v(t.enabled,e)!==!1&&v(t.staleTime,e)!==`static`){let r=v(n,e);return r===`always`||r!==!1&&j(e,t)}return!1}function je(e,t,n,r){return(e!==t||v(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&j(e,n)}function j(e,t){return v(t.enabled,e)!==!1&&e.isStaleByTime(v(t.staleTime,e))}var Me=class extends be{#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||Ne(),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.state.status===`pending`?this.execute(this.state.variables):Promise.resolve())}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},r=this.#r=ye({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)}),i=this.state.status===`pending`,a=!r.canStart();try{if(i)t();else{this.#i({type:`pending`,variables:e,isPaused:a}),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:a})}let o=await r.start();return await this.#n.config.onSuccess?.(o,e,this.state.context,this,n),await this.options.onSuccess?.(o,e,this.state.context,n),await this.#n.config.onSettled?.(o,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(o,null,e,this.state.context,n),this.#i({type:`success`,data:o}),o}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.#r===r&&(this.#r=void 0),this.#n.runNext(this)}}#i(e){let t=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=t(this.state),k.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function Ne(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var Pe=class extends O{#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),w(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)}onSubscribe(){this.listeners.size===1&&this.#n&&(this.#n.addObserver(this),this.#i())}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??Ne();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){k.batch(()=>{let t=this.#r;if(t&&this.hasListeners()){let n=this.#t.variables,r=this.#t.context,i={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type===`success`){try{t.onSuccess?.(e.data,n,r,i)}catch(e){Promise.reject(e)}try{t.onSettled?.(e.data,null,n,r,i)}catch(e){Promise.reject(e)}}else if(e?.type===`error`){try{t.onError?.(e.error,n,r,i)}catch(e){Promise.reject(e)}try{t.onSettled?.(void 0,e.error,n,r,i)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}},Fe=a.createContext(!1),Ie=()=>a.useContext(Fe);Fe.Provider;function Le(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Re=a.createContext(Le()),ze=()=>a.useContext(Re),Be=(e,t,n)=>{let r=n?.state.status===`error`&&typeof e.throwOnError==`function`?ce(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||r)&&(t.isReset()||(e.retryOnMount=!1))},Ve=e=>{a.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||ce(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?.suspense&&t.isPending,Ge=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Ke(e,t,n){let r=Ie(),i=ze(),o=c(n),s=o.defaultQueryOptions(e),l=o.getQueryCache().get(s.queryHash),u=e.subscribed!==!1;s._optimisticResults=r?`isRestoring`:u?`optimistic`:void 0,Ue(s),Be(s,i,l),Ve(i);let[d]=a.useState(()=>new t(o,s)),f=d.getOptimisticResult(s),p=!r&&u;if(a.useSyncExternalStore(a.useCallback(e=>{let t=p?d.subscribe(k.batchCalls(e)):m;return d.updateResult(),t},[d,p]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),a.useEffect(()=>{d.setOptions(s)},[s,d]),We(s,f))throw Ge(s,d,i);if(He({result:f,errorResetBoundary:i,throwOnError:s.throwOnError,query:l,suspense:s.suspense}))throw f.error;return s.notifyOnChangeProps?f:d.trackResult(f)}function M(e,t){return Ke(e,Oe,t)}function N(e,t){let n=c(t),[r]=a.useState(()=>new Pe(n,e));a.useEffect(()=>{r.setOptions(e)},[r,e]);let i=a.useSyncExternalStore(a.useCallback(e=>r.subscribe(k.batchCalls(e)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),o=a.useCallback((...e)=>{r.mutate(e[0],e[1]).catch(m)},[r]);if(i.error&&ce(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:o,mutateAsync:i.mutate}}var qe={name:`asterisk`,size:24,node:[[`path`,{d:`M12 5v14`,key:`s699le`}],[`path`,{d:`m18.065 8.496-12.125 7`,key:`1h26g9`}],[`path`,{d:`m5.94 8.504 12.125 7`,key:`k77sdm`}]]};qe.node;var Je=t(qe),Ye={name:`globe`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20`,key:`13o1zl`}],[`path`,{d:`M2 12h20`,key:`9i4pu4`}]]};Ye.node;var Xe=t(Ye),Ze={name:`hexagon`,size:24,node:[[`path`,{d:`M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z`,key:`yt0hxn`}]]};Ze.node;var Qe=t(Ze),$e={name:`server`,size:24,node:[[`rect`,{width:`20`,height:`8`,x:`2`,y:`2`,rx:`2`,ry:`2`,key:`ngkwjq`}],[`rect`,{width:`20`,height:`8`,x:`2`,y:`14`,rx:`2`,ry:`2`,key:`iecqi9`}],[`line`,{x1:`6`,x2:`6.01`,y1:`6`,y2:`6`,key:`16zg32`}],[`line`,{x1:`6`,x2:`6.01`,y1:`18`,y2:`18`,key:`nzw8ys`}]]};$e.node;var et=t($e),tt={name:`sparkle`,size:24,node:[[`path`,{d:`M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z`,key:`1s2grr`}]]};tt.node;var nt=t(tt),rt={name:`sparkles`,size:24,node:[[`path`,{d:`M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z`,key:`1s2grr`}],[`path`,{d:`M20 2v4`,key:`1rf3ol`}],[`path`,{d:`M22 4h-4`,key:`gwowj6`}],[`circle`,{cx:`4`,cy:`20`,r:`2`,key:`6kqj1y`}]],aliases:[`stars`]};rt.node;var it=t(rt),at={name:`square-terminal`,size:24,node:[[`path`,{d:`m7 11 2-2-2-2`,key:`1lz0vl`}],[`path`,{d:`M11 13h4`,key:`1p7l4v`}],[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,ry:`2`,key:`1m3agn`}]],aliases:[`terminal-square`]};at.node;var ot=t(at),P={gatewayUrl:`davecode.gatewayUrl`,token:`davecode.token`,theme:`davecode.theme`,dataMode:`davecode.dataMode`,sidebarCollapsed:`davecode.sidebarCollapsed`};function F(e){try{return window.localStorage.getItem(e)}catch{return null}}function I(e,t){try{t===``?window.localStorage.removeItem(e):window.localStorage.setItem(e,t)}catch{}}function st(){let e=F(P.theme),t=F(P.dataMode);return{gatewayUrl:F(P.gatewayUrl)??``,token:F(P.token)??``,theme:e===`light`||e===`system`?e:`dark`,dataMode:t===`live`||t===`mock`?t:`auto`,sidebarCollapsed:F(P.sidebarCollapsed)===`1`}}var L=typeof window>`u`?ct():st(),R=new Set;function ct(){return{gatewayUrl:``,token:``,theme:`dark`,dataMode:`auto`,sidebarCollapsed:!1}}function z(){return L}function lt(e){L={...L,...e};for(let[t,n]of Object.entries(e)){let e=P[t];t===`sidebarCollapsed`?I(e,n?`1`:``):t===`theme`?I(e,String(n)):I(e,String(n??``))}for(let e of R)e()}function ut(e){return R.add(e),()=>R.delete(e)}function dt(){return(0,a.useSyncExternalStore)(ut,z,z)}function ft(){if(typeof window>`u`)return!1;let e=new URLSearchParams(window.location.search).get(`mock`),t=window.location.hash.split(`?`)[1]??``,n=new URLSearchParams(t).get(`mock`);return e===`1`||n===`1`}function pt(e){return e===`system`?window.matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`:e}function mt(e){let t=()=>{document.documentElement.dataset.theme=pt(e)};if(t(),e!==`system`)return()=>{};let n=window.matchMedia(`(prefers-color-scheme: light)`);return n.addEventListener(`change`,t),()=>n.removeEventListener(`change`,t)}var ht=[`request.started`,`request.completed`,`request.failed`,`router.failover`,`account.updated`,`account.removed`,`quota.updated`,`task.updated`,`task.removed`,`runner.status`,`runner.log`,`goal.updated`,`goal.log`,`log`];function gt(e,t=Math.random){let n=Math.min(3e4,1e3*2**Math.max(0,e-1)),r=n*.2*(t()*2-1);return Math.round(n+r)}function _t(e){try{let t=JSON.parse(e);if(t&&typeof t==`object`&&typeof t.type==`string`)return t}catch{}return null}function vt(e,t){let n=null,r,i=0,a=!1,o,s=e=>t.onStatus?.({...e,attempt:i,lastEventAt:o}),c=e=>{let n=_t(e.data);n&&(o=Date.now(),t.onEvent(n))},l=()=>{if(!a){s({state:i===0?`connecting`:`reconnecting`}),n=new EventSource(e),n.onopen=()=>{i=0,o=Date.now(),s({state:`open`})},n.onmessage=c;for(let e of ht)n.addEventListener(e,c);n.onerror=()=>{if(n?.close(),n=null,a)return;i+=1;let e=gt(i);s({state:`reconnecting`,retryAt:Date.now()+e}),r=window.setTimeout(l,e)}}};return l(),()=>{a=!0,window.clearTimeout(r),n?.close(),n=null}}var B=class extends Error{status;code;cycle;dependents;constructor(e,t,n,r={}){super(n),this.name=`ApiError`,this.status=e,this.code=t,r.cycle&&(this.cycle=r.cycle),r.dependents&&(this.dependents=r.dependents)}get reachable(){return this.status>0&&!yt.has(this.code)}},yt=new Set([`network`,`bad_response`,`gateway_unreachable`]);function bt(e){return e instanceof B}function xt(e,t){return`${e.replace(/\/+$/,``)}${t}`}function St({baseUrl:e,token:t}){async function n(n,r,i){let a={Accept:`application/json`};t&&(a.Authorization=`Bearer ${t}`),i!==void 0&&(a[`Content-Type`]=`application/json`);let o;try{o=await fetch(xt(e,r),{method:n,headers:a,body:i===void 0?void 0:JSON.stringify(i)})}catch(e){throw new B(0,`network`,`Gateway unreachable: ${e.message}`)}if(o.status===204)return;let s=await o.text(),c;try{c=s?JSON.parse(s):void 0}catch{throw new B(o.ok?0:o.status,`bad_response`,`Unexpected non-JSON response from ${r}`)}if(!o.ok){let e=c?.error;throw!e&&o.status>=502&&o.status<=504?new B(o.status,`gateway_unreachable`,`Gateway unreachable (proxy answered ${o.status})`):new B(o.status,e?.code??`http_${o.status}`,e?.message??`${n} ${r} failed with ${o.status}`,{...e?.cycle&&{cycle:e.cycle},...e?.dependents&&{dependents:e.dependents}})}return c}let r=e=>n(`GET`,e);return{mode:`live`,health:()=>r(`/api/health`),listAccounts:async()=>(await r(`/api/accounts`)).accounts,createAccount:async e=>(await n(`POST`,`/api/accounts`,e)).account,updateAccount:async(e,t)=>(await n(`PATCH`,`/api/accounts/${encodeURIComponent(e)}`,t)).account,deleteAccount:e=>n(`DELETE`,`/api/accounts/${encodeURIComponent(e)}`),usage:async()=>(await r(`/api/usage`)).usage,budget:async()=>(await r(`/api/budget`)).budget,connection:async e=>(await r(`/api/accounts/${encodeURIComponent(e)}/connection`)).connection,connect:async e=>(await n(`POST`,`/api/accounts/${encodeURIComponent(e)}/connect`,{})).connect,timeseries:async(e=60,t=60)=>(await r(`/api/usage/timeseries?minutes=${e}&bucketSec=${t}`)).buckets,requests:async(e=100)=>(await r(`/api/requests?limit=${e}`)).requests,routes:()=>r(`/api/routes`),updateRoutes:e=>n(`PUT`,`/api/routes`,e),tasks:()=>r(`/api/tasks`),createTask:async e=>(await n(`POST`,`/api/tasks`,e)).task,updateTask:async(e,t)=>(await n(`PATCH`,`/api/tasks/${encodeURIComponent(e)}`,t)).task,deleteTask:e=>n(`DELETE`,`/api/tasks/${encodeURIComponent(e)}`),brain:()=>r(`/api/brain`),runner:async()=>(await r(`/api/runner`)).status,runnerAction:async(e,t)=>(await n(`POST`,`/api/runner/${e}`,e===`start`&&t?.taskId?{taskId:t.taskId}:void 0)).status,logs:async(e=200)=>(await r(`/api/logs?limit=${e}`)).events,goals:async()=>(await r(`/api/goals`)).goals,startGoal:async e=>(await n(`POST`,`/api/goals`,e)).goal,executeGoal:async e=>(await n(`POST`,`/api/goals/${encodeURIComponent(e)}/execute`)).goal,goalArtifact:async(e,t)=>(await r(`/api/goals/${encodeURIComponent(e)}/artifacts/${encodeURIComponent(t)}`)).artifact,cancelGoal:async e=>(await n(`POST`,`/api/goals/${encodeURIComponent(e)}/cancel`)).goal,models:async()=>(await r(`/v1/models`)).data,subscribe:n=>vt(xt(e,`/api/events${t?`?token=${encodeURIComponent(t)}`:``}`),n)}}function Ct(e){return bt(e)?e.status===401?`Unauthorized: set the gateway token in Settings.`:e.message:e instanceof Error?e.message:String(e)}function wt(e){return e.type===`request.started`||e.type===`request.completed`||e.type===`request.failed`||e.type===`router.failover`}function Tt(e,t,n=``){return{requestId:e,model:n,startedTs:t,updatedTs:t,attempts:[],outcome:`pending`,failovers:0,exhausted:!1}}function Et(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if(r&&r.accountId===t&&r.outcome===`pending`)return n}return-1}var Dt=2e3;function Ot(e,t,n,r,i){for(let a=e.length-1;a>=0;a--){let o=e[a];if(!o||o.accountId!==t||i&&o.outcome!==i)continue;let s=o[r];if(s!==void 0&&Math.abs(s-n)<=Dt)return a}return-1}function kt(e){let t=e.attempts[e.attempts.length-1];return t?t.outcome===`success`?`success`:t.outcome===`pending`?`pending`:e.exhausted?`failed`:e.failovers>=e.attempts.length?`pending`:`failed`:`pending`}function At(e,t){let n=e??Tt(t.requestId,t.ts),r={...n,attempts:n.attempts.map(e=>({...e})),startedTs:Math.min(n.startedTs,t.ts),updatedTs:Math.max(n.updatedTs,t.ts)};switch(t.type){case`request.started`:r.model||=t.model,Et(r.attempts,t.accountId)===-1&&Ot(r.attempts,t.accountId,t.ts,`startedTs`)===-1&&r.attempts.push({accountId:t.accountId,provider:t.provider,startedTs:t.ts,outcome:`pending`});break;case`request.completed`:{r.model||=t.model;let e=Et(r.attempts,t.accountId);e===-1&&(e=Ot(r.attempts,t.accountId,t.ts,`endedTs`,`success`)),e===-1&&(r.attempts.push({accountId:t.accountId,provider:t.provider,startedTs:t.ts-t.latencyMs,outcome:`pending`}),e=r.attempts.length-1);let n=r.attempts[e];n&&(n.outcome=`success`,n.endedTs=t.ts,n.latencyMs=t.latencyMs,n.promptTokens=t.promptTokens,n.completionTokens=t.completionTokens),r.startedTs=Math.min(r.startedTs,t.ts-t.latencyMs);break}case`request.failed`:{let e=Et(r.attempts,t.accountId);e===-1&&(e=Ot(r.attempts,t.accountId,t.ts,`endedTs`,`failed`)),e===-1&&(r.attempts.push({accountId:t.accountId,provider:t.provider,startedTs:t.ts,outcome:`pending`}),e=r.attempts.length-1);let n=r.attempts[e];if(n){let e=n.outcome===`pending`;n.outcome=`failed`,n.endedTs=e?t.ts:n.endedTs??t.ts,n.latencyMs=n.latencyMs??t.ts-n.startedTs,n.errorKind=t.error.kind,n.errorStatus=t.error.status,n.errorMessage=t.error.message}break}case`router.failover`:{t.toAccountId===null&&(r.exhausted=!0);let e=!1;for(let n=r.attempts.length-1;n>=0;n--){let i=r.attempts[n];if(i&&i.accountId===t.fromAccountId){e=!0,i.failedOver||(i.failedOver=!0,r.failovers+=1),i.errorKind??=t.reason,i.outcome===`pending`&&(i.outcome=`failed`,i.endedTs=t.ts);break}}e||(r.failovers+=1);break}}return r.outcome=kt(r),r}function jt(e){let t=new Map;for(let n of e){let e=t.get(n.requestId);e?e.push(n):t.set(n.requestId,[n])}let n=[];for(let[e,r]of t){r.sort((e,t)=>e.ts-t.ts);let t=r[0];if(!t)continue;let i=r.map((e,t)=>({accountId:e.accountId,provider:e.provider,startedTs:e.ts-e.latencyMs,endedTs:e.ts,outcome:e.status===`success`?`success`:`failed`,latencyMs:e.latencyMs,promptTokens:e.promptTokens,completionTokens:e.completionTokens,errorKind:e.errorKind??(e.status===`rate_limited`?`rate_limit`:void 0),errorStatus:e.status===`rate_limited`?429:void 0,failedOver:t<r.length-1})),a=i[i.length-1];n.push({requestId:e,model:t.model,startedTs:i[0]?.startedTs??t.ts,updatedTs:a?.endedTs??t.ts,attempts:i,outcome:a?.outcome===`success`?`success`:`failed`,failovers:Math.max(0,i.length-1),exhausted:a?.outcome!==`success`})}return n.sort((e,t)=>t.startedTs-e.startedTs)}function Mt(e){let t=0,n=0;for(let r of e.attempts)t+=r.promptTokens??0,n+=r.completionTokens??0;return{prompt:t,completion:n}}function Nt(e){let t=e.attempts[e.attempts.length-1];if(t?.endedTs)return t.endedTs-e.startedTs}function Pt(e){if(e.errorStatus)return String(e.errorStatus);switch(e.errorKind){case`rate_limit`:return`429`;case`quota_exhausted`:return`quota`;case`unavailable`:return`503`;case`timeout`:return`timeout`;case`network`:return`network`;case`auth`:return`401`;case`context_length`:return`ctx`;case`bad_request`:return`400`;default:return`error`}}var Ft=600,It=400,Lt=3e3,Rt=4e3;function zt(e){return Math.floor(e/6e4)*6e4}function Bt(e){return JSON.stringify(e)}var Vt=class{flushMs;state={events:[],chains:[],logs:[],minutes:[],failoverTs:[]};chainIndex=new Map;seen=new Set;seenOrder=[];listeners=new Set;dirty=!1;flushTimer;pending=[];failovers=new Map;logSeq=0;constructor(e=200){this.flushMs=e}getState=()=>this.state;subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));ingest(e){let t=Bt(e);if(this.seen.has(t))return!1;if(this.seen.add(t),this.seenOrder.push(t),this.seenOrder.length>Rt){let e=this.seenOrder.shift();e&&this.seen.delete(e)}return this.pending.push(e),this.schedule(),!0}seedRecords(e){for(let t of jt(e))this.chainIndex.has(t.requestId)||this.chainIndex.set(t.requestId,t),t.attempts.slice(0,-1).forEach(e=>{this.failovers.set(`${t.requestId}:${e.accountId}`,e.endedTs??t.startedTs)});this.dirty=!0,this.schedule()}flush(){if(this.flushTimer!==void 0&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.pending.length===0&&!this.dirty)return;let e=this.pending;this.pending=[],this.dirty=!1;let t=this.state.events.concat(e),n=this.state.logs.slice(),r=new Map(this.state.minutes.map(e=>[e.ts,{...e}]));for(let t of e)if(wt(t)&&this.chainIndex.set(t.requestId,At(this.chainIndex.get(t.requestId),t)),t.type===`request.completed`){let e=zt(t.ts),n=r.get(e)??{ts:e,tokens:0,requests:0};n.tokens+=t.promptTokens+t.completionTokens,n.requests+=1,r.set(e,n)}else t.type===`router.failover`?this.failovers.set(`${t.requestId}:${t.fromAccountId}`,t.ts):t.type===`runner.log`?n.push({key:`l${this.logSeq++}`,ts:t.ts,level:t.level,message:t.message,source:`runner`,taskId:t.taskId}):t.type===`log`&&n.push({key:`l${this.logSeq++}`,ts:t.ts,level:t.level,message:t.message,source:`gateway`,scope:t.scope});let i=[...this.chainIndex.values()].sort((e,t)=>t.startedTs-e.startedTs);if(i.length>It){for(let e of i.slice(It))this.chainIndex.delete(e.requestId);i=i.slice(0,It)}n.sort((e,t)=>e.ts-t.ts);let a=Date.now()-36e5;for(let[e,t]of this.failovers)t<a&&this.failovers.delete(e);this.state={events:t.length>Ft?t.slice(-600):t,chains:i,logs:n.length>Lt?n.slice(-3e3):n,minutes:[...r.values()].sort((e,t)=>e.ts-t.ts).slice(-90),failoverTs:[...this.failovers.values()].sort((e,t)=>e-t)};for(let e of this.listeners)e()}clearLogs(){this.state={...this.state,logs:[]};for(let e of this.listeners)e()}dispose(){this.flushTimer!==void 0&&clearTimeout(this.flushTimer),this.flushTimer=void 0}schedule(){this.flushTimer===void 0&&(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flush()},this.flushMs))}},Ht=864e5,Ut=[`1m`,`5h`,`24h`],Wt={acc_claude_pro:{info:{plan:`Claude Pro`,price:{amount:20,currency:`USD`,period:`month`}},paidDaysAgo:21,renewsInDays:9},acc_anthropic_work:{info:{plan:`API — Build tier 2`,price:{amount:250,currency:`USD`,period:`month`},notes:`Prepaid credits, topped up monthly`},paidDaysAgo:12,renewsInDays:18},acc_openai_team:{info:{plan:`ChatGPT Team`,price:{amount:300,currency:`USD`,period:`year`}},paidDaysAgo:340,renewsInDays:2}},Gt=e=>new Date(e).toISOString().slice(0,10);function Kt(e,t){let n=Wt[e];if(n)return{...n.info,paidAt:Gt(t-n.paidDaysAgo*Ht),renewsAt:Gt(t+n.renewsInDays*Ht)}}function qt(e,t,n){let r=null,i;for(let e of Ut){let n=t.windows[e];if(n.tokenLimit===void 0&&n.requestLimit===void 0)continue;let a=Math.max(0,1-n.utilization);(r===null||a<r)&&(r=a,i=e)}let a={accountId:e.id,label:e.label,provider:e.provider,enabled:e.enabled,remaining:r,usage:t,available:e.enabled&&e.status===`active`&&(r??1)>0};if(i&&(a.tightestWindow=i),e.subscription){a.subscription=e.subscription;let t=e.subscription.renewsAt?Date.parse(e.subscription.renewsAt):NaN;Number.isNaN(t)||(a.renewsInDays=Math.ceil((t-n)/Ht))}return a.available||(a.unavailableReason=e.enabled?e.status===`cooldown`?`cooling down`:e.status===`error`?`credentials rejected (fix the account)`:`local quota limit reached`:`disabled`),a}function Jt(e,t){let n=e.filter(e=>e.enabled);if(n.length===0)return``;let r=[`ACCOUNT BUDGET (${`${new Date(t).toISOString().slice(0,16).replace(`T`,` `)} UTC`}; ${n.filter(e=>e.available).length} of ${n.length} accounts available).`,`The router already avoids exhausted accounts. When budget is scarce, keep prompts and outputs short and prefer fewer, larger steps.`];for(let e of n){let t=[];e.subscription?.plan&&t.push(e.subscription.plan);let n=e.subscription?.price;n&&t.push(`${n.amount} ${n.currency}/${n.period}`),e.renewsInDays!==void 0&&t.push(`renews in ${e.renewsInDays}d`);let i=`- ${e.label} [${e.provider}]${t.length?` (${t.join(`, `)})`:``}`,a=e.available?e.remaining===null?`no known limit`:`${Math.round(e.remaining*100)}% left (${e.tightestWindow} window)`:`unavailable: ${e.unavailableReason}`;r.push(`${i}: ${a}`)}return r.join(`
|
|
2
2
|
`)}function Yt(e,t,n){let r=e.map(e=>qt(e,t(e),n));return{generatedAt:new Date(n).toISOString(),accounts:r,context:Jt(r,n)}}var Xt={anthropic:{kind:`anthropic`,label:`Anthropic API`,icon:Je,auth:`api-key`,blurb:`Claude models through the Messages API with an API key.`,secretLabel:`API key`,secretPlaceholder:`sk-ant-…`},openai:{kind:`openai`,label:`OpenAI API`,icon:Qe,auth:`api-key`,blurb:`GPT models with an OpenAI API key.`,secretLabel:`API key`,secretPlaceholder:`sk-…`},gemini:{kind:`gemini`,label:`Gemini API`,icon:nt,auth:`api-key`,blurb:`Google Gemini through AI Studio or Vertex with an API key.`,secretLabel:`API key`,secretPlaceholder:`AIza…`},"openai-compatible":{kind:`openai-compatible`,label:`OpenAI-compatible`,icon:et,auth:`optional-key`,blurb:`OpenRouter and other providers using the OpenAI-compatible API.`,secretLabel:`API key (optional)`,secretPlaceholder:`Leave empty for local servers`},"claude-cli":{kind:`claude-cli`,label:`Claude Code CLI`,icon:ot,auth:`cli`,blurb:`Your Claude login, isolated in its own CLAUDE_CONFIG_DIR sandbox.`,subscription:!0},"codex-cli":{kind:`codex-cli`,label:`Codex CLI`,icon:ot,auth:`cli`,blurb:`Your ChatGPT/OpenAI login, isolated in its own CODEX_HOME sandbox.`,subscription:!0},"gemini-cli":{kind:`gemini-cli`,label:`Gemini CLI`,icon:it,auth:`cli`,blurb:`Your Google login (Login with Google), isolated in its own GEMINI_CLI_HOME sandbox.`,subscription:!0},"antigravity-cli":{kind:`antigravity-cli`,label:`Antigravity`,icon:it,auth:`cli`,blurb:`Your Google sign-in in the Antigravity CLI (agy), shared by this machine.`,subscription:!0},"gemini-web":{kind:`gemini-web`,label:`Gemini web`,icon:Xe,auth:`browser`,blurb:`Drives a Gemini web session through a dedicated Chromium profile.`,experimental:!0,subscription:!0}},Zt=[`anthropic`,`openai`,`gemini`,`openai-compatible`,`claude-cli`,`codex-cli`,`antigravity-cli`,`gemini-cli`,`gemini-web`];function Qt(e){return Xt[e]??{...Xt[`openai-compatible`],kind:e,label:e}}var $t=new Set([`acc_claude_pro`]),en=6e3;function tn(e){let{auth:t}=Qt(e.provider);return t===`cli`?`cli-login`:t===`browser`?`browser`:`api-key`}function nn(e,t,n){let r=tn(e),i={accountId:e.id,provider:e.provider,method:r,checkedAt:new Date(n).toISOString()};return r===`browser`?{...i,status:`unknown`,detail:`Signed in through its own Chromium profile; checking would mean opening the browser.`}:r===`api-key`?e.hasSecret===!1&&e.provider!==`openai-compatible`?{...i,status:`not_connected`,detail:`No API key stored. Add one to connect this account.`}:{...i,status:`connected`,detail:`API key stored in the encrypted keyring.`}:{...i,loginCommand:`davecode accounts login ${e.id}`,...t?{status:`connected`,detail:`The vendor CLI reports a login for this account.`}:{status:`not_connected`,detail:`No login in this account’s sandbox yet.`}}}var V=e=>e,rn=[{account:{id:`acc_claude_pro`,provider:`claude-cli`,label:`Claude Pro — personal`,enabled:!0,priority:10,weight:3,limits:V({tpm:6e4,tokens5h:3e6,requests5h:900,tokensDaily:9e6}),config:{binary:`claude`,sandbox:`~/.davecode/sandboxes/acc_claude_pro`}},curve5h:{from:.79,to:.935},curve24h:{from:.54,to:.63},latency:[900,11],failRate:.02},{account:{id:`acc_anthropic_work`,provider:`anthropic`,label:`Anthropic API — work`,enabled:!0,priority:20,weight:2,limits:V({tpm:12e4,rpm:50,tokens5h:6e6,tokensDaily:2e7}),config:{models:[`claude-sonnet-5-5`,`claude-opus-5-5`,`claude-haiku-5`]}},curve5h:{from:.48,to:.64},curve24h:{from:.36,to:.44},latency:[650,9],failRate:.015},{account:{id:`acc_openai_team`,provider:`openai`,label:`OpenAI — team`,enabled:!0,priority:30,weight:1,limits:V({tpm:9e4,rpm:60,tokens5h:5e6,tokensDaily:15e6}),config:{models:[`gpt-5.5`,`gpt-5.5-mini`,`gpt-5.5-pro`]}},curve5h:{from:.27,to:.36},curve24h:{from:.2,to:.26},latency:[520,8],failRate:.012},{account:{id:`acc_openrouter`,provider:`openai-compatible`,label:`OpenRouter`,enabled:!0,priority:50,weight:1,limits:{},config:{baseUrl:`https://openrouter.ai/api/v1`,models:[`openrouter/auto`]}},curve5h:{from:0,to:0},curve24h:{from:0,to:0},latency:[380,22],failRate:.01},{account:{id:`acc_gemini_web`,provider:`gemini-web`,label:`Gemini web — experimental`,enabled:!1,status:`disabled`,priority:90,weight:1,limits:V({requestsDaily:100}),config:{profile:`~/.davecode/profiles/acc_gemini_web`}},curve5h:{from:0,to:0},curve24h:{from:0,to:0},latency:[2400,14],failRate:.05}],an=[{name:`auto`,description:`Subscription first, then API keys, then the local model.`,targets:[{provider:`claude-cli`,model:`claude-sonnet-5-5`,accountId:`acc_claude_pro`},{provider:`anthropic`,model:`claude-sonnet-5-5`},{provider:`openai`,model:`gpt-5.5`},{provider:`openai-compatible`,model:`openrouter/auto`}]},{name:`fast`,description:`Low-latency completions for autocomplete and quick edits.`,targets:[{provider:`openai`,model:`gpt-5.5-mini`},{provider:`anthropic`,model:`claude-haiku-5`},{provider:`openai-compatible`,model:`llama4:scout`}]},{name:`reasoning`,description:`Planning and hard debugging. Expensive; used by the runner for repairs.`,targets:[{provider:`anthropic`,model:`claude-opus-5-5`},{provider:`openai`,model:`gpt-5.5-pro`}]},{name:`local`,description:`Never leaves the machine.`,targets:[{provider:`openai-compatible`,model:`openrouter/auto`,accountId:`acc_openrouter`}]}],on=[[`auto`,.62],[`fast`,.24],[`reasoning`,.06],[`local`,.08]],H=(e,t)=>new Date(t-e*6e4).toISOString();function sn(e){return[{id:`foundation`,title:`Monorepo foundation, shared contracts and OSS docs`,status:`SUCCESS`,dependsOn:[],priority:100,attempts:1,branch:`davecode/task-foundation`,acceptance:[`pnpm lint, typecheck, test and build pass`,`Contracts documented in docs/API.md`],updatedAt:H(1560,e)},{id:`p1-storage`,title:`SQLite storage (WAL), migrations and repositories`,description:`accounts, secrets, sessions, token_usage and audit_logs tables with typed repositories.`,status:`SUCCESS`,dependsOn:[`foundation`],priority:90,attempts:1,branch:`davecode/task-p1-storage`,acceptance:[`Migrations are idempotent`,`WAL mode enabled`,`Repositories covered by tests`],updatedAt:H(1200,e)},{id:`p1-config`,title:`Layered config loader (defaults, global, project, env)`,status:`SUCCESS`,dependsOn:[`foundation`],priority:90,attempts:2,branch:`davecode/task-p1-config`,acceptance:[`Later layers win`,`Invalid config reports the zod path`],notes:`First attempt merged env vars before the project file; fixed in repair cycle 1.`,updatedAt:H(1140,e)},{id:`p1-identity`,title:`Encrypted keyring, sandbox manager and Chromium profile manager`,status:`SUCCESS`,dependsOn:[`p1-storage`],priority:90,attempts:1,branch:`davecode/task-p1-identity`,acceptance:[`Secrets are AES-256-GCM encrypted at rest`,`master.key created with 0600 permissions`,`Each CLI account gets its own CLAUDE_CONFIG_DIR / CODEX_HOME`],updatedAt:H(840,e)},{id:`p2-quota`,title:`Sliding-window quota engine (1m, 5h, 24h) and SQLite-backed tracker`,status:`SUCCESS`,dependsOn:[`p1-storage`],priority:80,attempts:1,branch:`davecode/task-p2-quota`,acceptance:[`Windows slide, never reset on the hour`,`Utilization = max(tokens, requests) ratio`],updatedAt:H(540,e)},{id:`p2-providers`,title:`Provider adapters: anthropic, openai, gemini, openai-compatible, claude-cli`,status:`SUCCESS`,dependsOn:[`p1-identity`],priority:80,attempts:2,branch:`davecode/task-p2-providers`,acceptance:[`Upstream errors mapped to ProviderError kinds`,`Streaming and non-streaming paths`],updatedAt:H(360,e)},{id:`p2-codex-cli`,title:`Codex CLI adapter isolated via CODEX_HOME`,status:`FAILED`,dependsOn:[`p2-providers`],priority:70,attempts:3,branch:`davecode/task-p2-codex-cli`,acceptance:[`codex exec runs inside the account sandbox`,`Usage parsed from the JSON event stream`],notes:"Failed after 3 repair cycles: `codex exec --json` exits 2 under a fresh CODEX_HOME on Windows (no login prompt in non-TTY mode). Needs a human decision on the auth flow.",updatedAt:H(240,e)},{id:`p3-brain`,title:`Global and project brain managers, task graph DAG resolver with cycle detection`,status:`SUCCESS`,dependsOn:[`foundation`],priority:70,attempts:1,branch:`davecode/task-p3-brain`,acceptance:[`Unknown dependencies rejected`,`Cycles rejected with the offending path`],updatedAt:H(480,e)},{id:`p2-router`,title:`Router with balancing, backpressure, cooldowns and hot failover`,description:`Score candidates by priority, then weight × headroom. Smooth backpressure above 85 %, shift above 90 % of the 5 h quota, fail over before the first byte.`,status:`IN_PROGRESS`,dependsOn:[`p2-quota`,`p2-providers`,`p1-config`],priority:80,attempts:2,branch:`davecode/task-p2-router`,acceptance:[`Never routes to an account in cooldown`,`Weight is smoothly reduced above backpressureThreshold`,`Failover honours Retry-After and routing.maxFailovers`,`Emits router.failover for every hop`],notes:`Repair cycle 1: two vitest assertions failed on Retry-After parsing (HTTP-date form).`,updatedAt:H(3,e)},{id:`p1-gateway`,title:`Fastify gateway: /v1 OpenAI-compatible proxy, /api REST, SSE events`,status:`PENDING`,dependsOn:[`p2-router`],priority:75,acceptance:[`Implements docs/API.md exactly`,`SSE heartbeat every 15 s`,`Serves packages/ui/dist`]},{id:`p4-runner`,title:`Autonomous runner: state machine, validator, repair cycles, git flow`,status:`PENDING`,dependsOn:[`p2-router`,`p3-brain`],priority:60,acceptance:[`At most 3 repair cycles`,`Only merges after lint, typecheck and tests pass`]},{id:`p5-cli`,title:`CLI commands and Ink TUI`,status:`PENDING`,dependsOn:[`p1-gateway`,`p4-runner`],priority:40,acceptance:[`davecode start | status | add-account | run`,`TUI mirrors the dashboard overview`]},{id:`release-0.1.0`,title:`Integration tests, docs polish and v0.1.0 release`,status:`PENDING`,dependsOn:[`p5-cli`,`p2-codex-cli`],priority:10,acceptance:[`End-to-end failover test against two fake upstreams`,`npm publish dry-run passes`]}]}function cn(e,t){let n=e.filter(e=>e.status===`SUCCESS`),r=e.find(e=>e.status===`IN_PROGRESS`),i=e.filter(e=>e.status===`FAILED`);return`# DaveCode: project state
|
|
3
3
|
|
|
4
4
|
_Last updated: ${new Date(t).toISOString().slice(0,10)} by the autonomous runner_
|
|
@@ -52,4 +52,4 @@ quota-aware routing and hot failover, and an **autonomous runner** that walks a
|
|
|
52
52
|
4. On \`rate_limit\`, \`unavailable\`, \`timeout\`… cool down and fail over before the first byte.
|
|
53
53
|
`,U=new Set([`planned`,`succeeded`,`failed`,`cancelled`,`budget_exhausted`]),un=[{id:`planner`,description:`Breaks the objective into a plan and success criteria.`},{id:`researcher`,description:`Analyses markets, users, competitors and options.`},{id:`implementer`,description:`Writes and changes code (through the autonomous runner).`},{id:`reviewer`,description:`Critically reviews other outputs for gaps and risks.`},{id:`writer`,description:`Positioning, marketing copy, docs and drafts of messages.`}],W={maxRounds:4,maxTasks:12,maxTokens:1e6},G=1800;function dn(e){let t=/\b(page|site|app|api|endpoint|feature|build|implement|code)\b/i.test(e),n=[{id:`research`,title:`Map the audience and alternatives`,role:`researcher`,kind:`artifact`,dependsOn:[]},{id:`positioning`,title:`Write the positioning and key messages`,role:`writer`,kind:`artifact`,dependsOn:[`research`]}];return t&&n.push({id:`implement`,title:`Implement the change behind the objective`,role:`implementer`,kind:`code`,dependsOn:[`positioning`]}),n.push({id:`launch-copy`,title:`Write the launch copy`,role:`writer`,kind:`artifact`,dependsOn:[`positioning`]},{id:`outreach`,title:`Draft: Email the first 20 prospects`,role:`writer`,kind:`artifact`,dependsOn:[`launch-copy`]}),n}var fn=class{host;list=[];constructor(e){this.host=e}seed(e){let t=t=>new Date(e-t*6e4).toISOString(),n=`goal_5e1d0c2a9b77`,r=dn(`Prepare the v0.2 launch messaging`).map(e=>({...e,status:`SUCCESS`,round:1,attempts:1,artifact:`.davecode/goals/${n}/${e.id}.md`,notes:`Wrote .davecode/goals/${n}/${e.id}.md`,...e.id===`outreach`?{description:`DaveCode never performs outbound actions.`}:{}}));this.list.push({id:n,objective:`Prepare the v0.2 launch messaging`,status:`succeeded`,round:1,limits:{...W,tokensUsed:38420},roles:un,tasks:r,summary:"Positioning, launch copy and a prospect email draft are ready in `.davecode/goals/`. A human still has to review and send the email.",createdAt:t(140),updatedAt:t(118),finishedAt:t(118)})}all(){return[...this.list].sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}start(e){let t=e.objective?.trim()??``;if(!t)throw new B(400,`invalid_body`,`objective: must not be empty`);let n=this.list.find(e=>!U.has(e.status));if(n)throw new B(409,`busy`,`goal ${n.id} is still running; cancel it first`);let r=new Date(this.host.now()).toISOString(),i={id:this.host.nextId(`goal`),objective:t,status:`planning`,round:1,limits:{maxRounds:Math.min(e.maxRounds??W.maxRounds,W.maxRounds),maxTasks:Math.min(e.maxTasks??W.maxTasks,W.maxTasks),maxTokens:Math.min(e.maxTokens??W.maxTokens,W.maxTokens),tokensUsed:0},roles:un,tasks:[],createdAt:r,updatedAt:r,...e.dryRun?{dryRun:!0}:{}};return this.list.push(i),this.update(i),this.log(i,`info`,`planning: ${t}`,`planner`),this.host.later(G,()=>this.plan(i)),i}cancel(e){let t=this.list.find(t=>t.id===e);if(!t)throw new B(404,`not_found`,`unknown goal "${e}"`);if(U.has(t.status))return t;for(let e of t.tasks)e.status===`IN_PROGRESS`&&(e.status=`PENDING`);return this.finish(t,`cancelled`),t}execute(e){let t=this.list.find(e=>!U.has(e.status));if(t)throw new B(409,`busy`,`goal ${t.id} is still running; cancel it first`);let n=this.list.find(t=>t.id===e);if(!n)throw new B(404,`not_found`,`unknown goal "${e}"`);if(n.status!==`planned`)throw new B(400,`invalid`,`goal "${e}" is ${n.status}; only a planned goal can be executed`);return delete n.dryRun,delete n.finishedAt,delete n.lastError,n.status=`running`,this.update(n),this.log(n,`info`,`executing planned goal (${n.tasks.length} task(s))`,`planner`),this.host.later(G,()=>this.step(n)),n}artifact(e,t){let n=this.list.find(t=>t.id===e);if(!n)throw new B(404,`not_found`,`unknown goal "${e}"`);let r=n.tasks.find(e=>e.id===t);if(!r?.artifact)throw new B(404,`not_found`,`task "${t}" has no artifact in goal "${e}"`);return{taskId:r.id,path:r.artifact,content:[`# ${r.title}`,``,`- **Goal:** ${n.objective}`,`- **Role:** \`${r.role}\` (round ${r.round})`,``,`## Summary`,``,r.id===`outreach`?`Draft email prepared for human review. DaveCode never sends outbound messages or takes external actions automatically.`:`Completed deliverable for **${r.title.toLowerCase()}** based on repository state and quota-aware routing.`].join(`
|
|
54
54
|
`)}}plan(e){U.has(e.status)||(e.tasks=dn(e.objective).slice(0,e.limits.maxTasks).map(e=>({...e,status:`PENDING`,round:1,attempts:0})),e.summary=`${e.tasks.length} tasks: research first, then positioning and copy; outbound steps stay drafts.`,this.spend(e,2400),this.log(e,`info`,`planned ${e.tasks.length} task(s)`,`planner`),e.dryRun?this.finish(e,`planned`):(e.status=`running`,this.update(e),this.host.later(G,()=>this.step(e))))}step(e){if(U.has(e.status))return;let t=e.tasks.find(e=>e.status===`IN_PROGRESS`);t&&(t.status=`SUCCESS`,t.kind===`code`?(t.runnerTaskId=`goal-${e.id.slice(-6)}-${t.id}`,t.notes=`Merged into main after lint, typecheck and tests passed.`):(t.artifact=`.davecode/goals/${e.id}/${t.id}.md`,t.notes=`Wrote ${t.artifact}`),delete e.activeTaskId,this.spend(e,t.kind===`code`?42e3:5e3+Math.round(Math.random()*4e3)),this.log(e,`info`,`${t.id}: SUCCESS`,t.role,t.id));let n=new Set(e.tasks.filter(e=>e.status===`SUCCESS`).map(e=>e.id)),r=e.tasks.find(e=>e.status===`PENDING`&&e.dependsOn.every(e=>n.has(e)));r?(r.status=`IN_PROGRESS`,r.attempts+=1,e.activeTaskId=r.id,this.update(e),this.log(e,`info`,`${r.title} (attempt ${r.attempts})`,r.role,r.id),this.host.later(r.kind===`code`?G*3:G,()=>this.step(e))):(e.status=`reviewing`,this.update(e),this.log(e,`info`,`reviewing round ${e.round}`,`reviewer`),this.host.later(G,()=>{U.has(e.status)||(this.spend(e,3100),e.summary=`Every task succeeded. The outreach email is a draft in the goal folder: review it and send it yourself.`,this.finish(e,`succeeded`))}))}spend(e,t){e.limits.tokensUsed+=t}finish(e,t){delete e.activeTaskId,e.status=t,e.finishedAt=new Date(this.host.now()).toISOString(),this.update(e),this.log(e,t===`succeeded`||t===`planned`?`info`:`warn`,`goal ${t} (${e.limits.tokensUsed} tokens)`)}update(e){e.updatedAt=new Date(this.host.now()).toISOString(),this.host.emit({type:`goal.updated`,goal:structuredClone(e)})}log(e,t,n,r,i){this.host.emit({type:`goal.log`,goalId:e.id,level:t,message:n,...r?{role:r}:{},...i?{taskId:i}:{}})}},pn=/^[a-z0-9][a-z0-9-]*$/,mn=0,K=e=>`${e}-${++mn}`;function hn(e=`anthropic`){return{key:K(`t`),provider:e,model:``,accountId:``}}function gn(e=``){return{key:K(`r`),name:e,description:``,targets:[hn()]}}function _n(e,t){let n=e.map(e=>({key:K(`r`),name:e.name,description:e.description??``,targets:e.targets.map(e=>({key:K(`t`),provider:e.provider,model:e.model,accountId:e.accountId??``}))}));return{routes:n,defaultKey:n.find(e=>e.name===t)?.key??null}}function vn(e){let t=e.routes.map(e=>{let t=e.description.trim();return{name:e.name.trim(),...t&&{description:t},targets:e.targets.map(e=>({provider:e.provider,model:e.model.trim(),...e.accountId&&{accountId:e.accountId}}))}}),n=e.routes.find(t=>t.key===e.defaultKey);return{routes:t,...n&&{defaultRoute:n.name.trim()}}}function yn(e,t,n){let r=[...e];if(t<0||t>=r.length)return r;let i=Math.max(0,Math.min(r.length-1,n));if(i===t)return r;let[a]=r.splice(t,1);return r.splice(i,0,a),r}function bn(e){let t=new Set(e.map(e=>e.name));for(let n=e.length+1;;n++)if(!t.has(`route-${n}`))return`route-${n}`}function xn(e,t=[]){let n={},r=new Map;for(let t of e.routes){let e=t.name.trim();r.set(e,(r.get(e)??0)+1)}let i=!0;for(let a of e.routes){let e={target:{}},o=a.name.trim();o?pn.test(o)?(r.get(o)??0)>1&&(e.name=`Another route already uses this name.`):e.name=`Lowercase letters, digits and hyphens only, starting with a letter or digit.`:e.name=`Give the route a name.`,a.targets.length===0&&(e.targets=`Add at least one target.`);for(let n of a.targets){let r={};if(n.model.trim()||(r.model=`Enter a model id.`),n.accountId){let e=t.find(e=>e.id===n.accountId);e?e.provider!==n.provider&&(r.accountId=`The pinned account belongs to a different provider.`):r.accountId=`This account no longer exists.`}(r.model||r.accountId)&&(e.target[n.key]=r)}(e.name||e.targets||Object.keys(e.target).length>0)&&(i=!1),n[a.key]=e}let a;return e.routes.length>0&&!e.routes.some(t=>t.key===e.defaultKey)&&(a=`Pick the default route.`,i=!1),{byRoute:n,...a&&{defaultRoute:a},valid:i}}function Sn(e,t,n){return JSON.stringify(vn(e))!==JSON.stringify(Cn(t,n))}function Cn(e,t){return vn(_n(e,t))}var wn=/^[a-z0-9]+(?:[-_.][a-z0-9]+)*$/;function Tn(e,t){return e?wn.test(e)?t.some(t=>t.id===e)?`A task with the id "${e}" already exists.`:null:`Use lowercase letters, digits and - _ . (for example build-api).`:`Give the task an id.`}function En(e){return e.toLowerCase().normalize(`NFKD`).replace(/[̀-ͯ]/g,``).replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,48).replace(/-+$/g,``)}function Dn(e,t){let n=e||`task`,r=new Set(t.map(e=>e.id));if(!r.has(n))return n;for(let e=2;;e++){let t=`${n}-${e}`;if(!r.has(t))return t}}var On={PENDING:[`IN_PROGRESS`],IN_PROGRESS:[`SUCCESS`,`FAILED`,`PENDING`],FAILED:[`PENDING`],SUCCESS:[`PENDING`]};function kn(e,t){return e===t||On[e].includes(t)}function An(e){switch(e){case`PENDING`:return[{to:`IN_PROGRESS`,label:`Start`,variant:`secondary`}];case`IN_PROGRESS`:return[{to:`SUCCESS`,label:`Mark done`,variant:`primary`},{to:`FAILED`,label:`Mark failed`,variant:`secondary`},{to:`PENDING`,label:`Reopen`,variant:`secondary`}];case`FAILED`:case`SUCCESS`:return[{to:`PENDING`,label:`Reopen`,variant:`secondary`}]}}function jn(e,t){let n=new Set,r=[t];for(;r.length>0;){let t=r.pop();for(let i of e)i.dependsOn.includes(t)&&!n.has(i.id)&&(n.add(i.id),r.push(i.id))}return n}function Mn(e,t){if(t===void 0)return[...e];let n=jn(e,t);return e.filter(e=>e.id!==t&&!n.has(e.id))}function Nn(e,t,n){let r=new Map(e.map(e=>[e.id,e.dependsOn]));r.set(t,n);let i=new Set,a=(e,n)=>{for(let o of r.get(e)??[]){if(o===t)return[...n,t];if(i.has(o))continue;i.add(o);let e=a(o,[...n,o]);if(e)return e}return null};return a(t,[t])}function Pn(){return{id:``,title:``,description:``,acceptance:``,priority:``,notes:``,dependsOn:[]}}function Fn(e){return{id:e.id,title:e.title,description:e.description??``,acceptance:(e.acceptance??[]).join(`
|
|
55
|
-
`),priority:e.priority===void 0?``:String(e.priority),notes:e.notes??``,dependsOn:[...e.dependsOn]}}function In(e){return e.split(/\r?\n/).map(e=>e.replace(/^\s*(?:[-*]|\d+[.)])\s+/,``).trim()).filter(Boolean)}function q(e){let t=e.trim();if(!t)return{};let n=Number(t);return Number.isFinite(n)?{value:n}:{error:`Priority must be a number.`}}function Ln(e,t,n){let r={};if(n===void 0){let n=Tn(e.id.trim(),t);n&&(r.id=n)}e.title.trim()?e.title.trim().length>300&&(r.title=`Keep the title under 300 characters.`):r.title=`Give the task a title.`;let i=q(e.priority);i.error&&(r.priority=i.error);let a=n??e.id.trim();if(e.dependsOn.includes(a))r.dependsOn=`A task cannot depend on itself.`;else{let n=e.dependsOn.find(e=>!t.some(t=>t.id===e));if(n)r.dependsOn=`Unknown task "${n}".`;else if(a){let n=Nn(t,a,e.dependsOn);n&&(r.dependsOn=`Would create a dependency cycle: ${n.join(` → `)}.`)}}return r}function Rn(e){let t=e.description.trim(),n=In(e.acceptance),{value:r}=q(e.priority);return{id:e.id.trim(),title:e.title.trim(),...t&&{description:t},...e.dependsOn.length>0&&{dependsOn:e.dependsOn},...r!==void 0&&{priority:r},...n.length>0&&{acceptance:n}}}var zn=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]);function Bn(e,t){let n={},r=t.title.trim();r!==e.title&&(n.title=r);let i=t.description.trim();i!==(e.description??``)&&(n.description=i||null);let a=t.notes.trim();a!==(e.notes??``)&&(n.notes=a||null);let o=In(t.acceptance);zn(o,e.acceptance??[])||(n.acceptance=o.length>0?o:null);let{value:s}=q(t.priority);return s!==e.priority&&(n.priority=s??null),zn(t.dependsOn,e.dependsOn)||(n.dependsOn=t.dependsOn),n}function Vn(e){return Object.keys(e).length===0}var J=6e4,Y=.85,Hn=.9,Un=4;function Wn(e){let t=e>>>0;return()=>{t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}}var X={rate_limit:[429,`Rate limited by upstream (Retry-After: 45)`],quota_exhausted:[429,`5h usage window exhausted for this account`],unavailable:[503,`Upstream overloaded, try again shortly`],timeout:[504,`Upstream did not answer within 60s`]},Gn={"p2-router":[`packages/core/src/router/select.ts`,`packages/core/src/router/failover.ts`,`packages/core/src/router/circuit-breaker.ts`,`packages/core/src/router/select.test.ts`],"p1-gateway":[`packages/server/src/app.ts`,`packages/server/src/routes/v1.ts`,`packages/server/src/routes/api.ts`,`packages/server/src/sse.ts`],"p4-runner":[`packages/core/src/autonomous/runner.ts`,`packages/core/src/autonomous/validator.ts`,`packages/core/src/autonomous/git.ts`,`packages/core/src/autonomous/runner.test.ts`],"p5-cli":[`packages/cli/src/commands/start.ts`,`packages/cli/src/commands/run.ts`,`packages/cli/src/tui/App.tsx`]},Kn={"p2-router":1,"p1-gateway":0,"p4-runner":2,"p5-cli":1},qn=class{mode=`mock`;rng;clock;t0;opts;seeds=new Map;accounts=[];records=[];taskList;routeList=structuredClone(an);defaultRoute=`auto`;runnerStatus;buffer=[];subscribers=new Set;timers=new Set;running=!1;stopGrace;seq=0;runnerQueue=[];runnerTimer;runnerPending;initialResumed=!1;pausedFrom;pressureLogged=new Map;goalSim;loggedIn=new Set($t);constructor(e={}){this.rng=Wn(e.seed??3665739998),this.clock=e.now??Date.now,this.opts={runnerAvailable:e.runnerAvailable??!0,geminiWeb:e.geminiWeb??!1,latency:e.latency??!0},this.t0=this.clock();for(let e of rn){this.seeds.set(e.account.id,e);let t=Kt(e.account.id,this.t0);this.accounts.push({...e.account,...t&&{subscription:t},status:e.account.status??`active`,createdAt:new Date(this.t0-10368e5).toISOString(),updatedAt:new Date(this.t0-36e5).toISOString()})}this.taskList=sn(this.t0),this.runnerStatus={state:`implementing`,taskId:`p2-router`,repairCycle:1,startedAt:new Date(this.t0-4.2*J).toISOString()},this.generateHistory(),this.opts.runnerAvailable&&this.seedRunnerHistory(),this.goalSim=new fn({now:()=>this.clock(),emit:e=>this.emit(e),later:(e,t)=>this.later(e,t),nextId:e=>this.nextId(e)}),this.goalSim.seed(this.t0)}health(){return this.respond(()=>({status:`ok`,version:`0.2.0`,uptimeSec:Math.round((this.clock()-this.t0)/1e3)+10800+1020,experimental:{geminiWeb:this.opts.geminiWeb,multiAccountRotation:!1}}))}listAccounts(){return this.respond(()=>this.accounts)}createAccount(e){return this.respond(()=>{if(!e.label?.trim())throw new B(400,`invalid_body`,`label: must not be empty`);if(e.provider===`gemini-web`&&!this.opts.geminiWeb)throw new B(400,`experimental_disabled`,`gemini-web requires experimental.geminiWeb = true in config.json`);let t=new Date(this.clock()).toISOString(),n={id:`acc_${e.provider.replace(/[^a-z]/g,``)}_${Math.floor(this.rng()*1e6).toString(36)}`,provider:e.provider,label:e.label.trim(),enabled:!0,priority:e.priority??100,weight:e.weight??1,limits:e.limits??{},config:e.config??{},...e.subscription&&{subscription:e.subscription},status:`active`,createdAt:t,updatedAt:t};return this.accounts.push(n),this.seeds.set(n.id,{account:n,curve5h:{from:0,to:.05},curve24h:{from:0,to:.02},latency:[700,10],failRate:.01}),this.emit({type:`account.updated`,account:n}),this.log(`info`,`accounts`,`Account ${n.id} (${n.provider}) added`),n})}updateAccount(e,t){return this.respond(()=>{let n=this.findAccount(e),r=t.enabled??n.enabled,i={...n,...t.label!==void 0&&{label:t.label},...t.priority!==void 0&&{priority:t.priority},...t.weight!==void 0&&{weight:t.weight},...t.limits!==void 0&&{limits:t.limits},...t.config!==void 0&&{config:t.config},...t.subscription&&{subscription:t.subscription},enabled:r,status:r?n.status===`disabled`?`active`:n.status:`disabled`,updatedAt:new Date(this.clock()).toISOString()};return r||delete i.cooldownUntil,t.subscription===null&&delete i.subscription,this.replaceAccount(i),i})}deleteAccount(e){return this.respond(()=>{this.findAccount(e),this.accounts=this.accounts.filter(t=>t.id!==e),this.emit({type:`account.removed`,accountId:e})})}usage(){return this.respond(()=>this.accounts.map(e=>this.accountUsage(e,this.clock())))}budget(){return this.respond(()=>{let e=this.clock();return Yt(this.accounts,t=>this.accountUsage(t,e),e)})}connection(e){return this.respond(()=>nn(this.findAccount(e),this.loggedIn.has(e),this.clock()))}connect(e){return this.respond(()=>{let t=nn(this.findAccount(e),this.loggedIn.has(e),this.clock());if(t.method!==`cli-login`)throw new B(400,`not_cli_login`,`This account connects with an API key: set it in the account settings`);let n=`davecode accounts login ${e}`;return t.status!==`connected`&&this.later(en,()=>{this.loggedIn.add(e),this.log(`info`,`accounts`,`Account ${e} signed in through the vendor CLI`)}),this.log(`info`,`accounts`,`Opened the official sign-in for ${e}`),{connection:t,launched:!0,command:n,message:`A terminal opened on the gateway machine with the official sign-in. Finish it there; this page updates when the login is detected.`}})}timeseries(e=60,t=60){return this.respond(()=>this.buildTimeseries(e,t))}requests(e=100){return this.respond(()=>this.records.slice(-e).reverse())}routes(){return this.respond(()=>({defaultRoute:this.defaultRoute,routes:this.routeList}))}updateRoutes(e){return this.respond(()=>{let t=new Set;if(e.routes.forEach((e,n)=>{let r=`routes.${n}`;if(!pn.test(e.name))throw new B(400,`invalid_body`,`${r}.name: route names are lowercase kebab-case`);if(t.has(e.name))throw new B(400,`invalid_body`,`${r}.name: duplicate route name "${e.name}"`);if(t.add(e.name),e.targets.length===0)throw new B(400,`invalid_body`,`${r}.targets: at least one target is required`);e.targets.forEach((t,n)=>{if(!t.model.trim())throw new B(400,`invalid_body`,`${r}.targets.${n}.model: required`);if(t.accountId&&!this.accounts.some(e=>e.id===t.accountId))throw new B(400,`unknown_account`,`route "${e.name}" pins unknown account "${t.accountId}"`)})}),e.defaultRoute!==void 0&&!t.has(e.defaultRoute))throw new B(400,`invalid_body`,`defaultRoute: "${e.defaultRoute}" is not one of the routes`);return this.routeList=structuredClone(e.routes),e.defaultRoute!==void 0&&(this.defaultRoute=e.defaultRoute),this.log(`info`,`config`,`Routes updated (${this.routeList.length}); saved to ~/.davecode/config.json`),{defaultRoute:this.defaultRoute,routes:this.routeList,shadowedByProject:!1}})}tasks(){return this.respond(()=>({project:{root:`C:/Users/dev/code/DaveCode`,name:`DaveCode`},graph:{version:1,tasks:this.taskList}}))}createTask(e){return this.respond(()=>{if(!wn.test(e.id))throw new B(400,`invalid_body`,`id: must be lowercase kebab-case or snake_case`);if(!e.title.trim())throw new B(400,`invalid_body`,`title: required`);if(this.taskList.some(t=>t.id===e.id))throw new B(409,`duplicate_id`,`duplicate task id "${e.id}"`);this.assertDependencies(e.id,e.dependsOn??[]);let t=new Date(this.clock()).toISOString(),n={id:e.id,title:e.title.trim(),status:`PENDING`,dependsOn:[...e.dependsOn??[]],...e.description!==void 0&&{description:e.description},...e.priority!==void 0&&{priority:e.priority},...e.acceptance!==void 0&&{acceptance:e.acceptance},createdAt:t,updatedAt:t};return this.taskList=[...this.taskList,n],this.emit({type:`task.updated`,task:n}),n})}updateTask(e,t){return this.respond(()=>{let n=this.taskList.find(t=>t.id===e);if(!n)throw new B(404,`not_found`,`unknown task "${e}"`);let r={...n};t.title!==void 0&&(r.title=t.title.trim()),t.dependsOn!==void 0&&(this.assertDependencies(e,t.dependsOn),r.dependsOn=[...t.dependsOn]);for(let e of[`description`,`priority`,`acceptance`,`notes`]){let n=t[e];n===null?delete r[e]:n!==void 0&&Object.assign(r,{[e]:n})}if(t.status!==void 0&&t.status!==n.status){if(!kn(n.status,t.status))throw new B(409,`invalid_transition`,`task "${e}": cannot move ${n.status} → ${t.status}`);r.status=t.status,t.status===`IN_PROGRESS`&&(r.attempts=(n.attempts??0)+1)}return this.commitTask(r),this.taskList.find(t=>t.id===e)})}deleteTask(e){return this.respond(()=>{let t=this.taskList.find(t=>t.id===e);if(!t)throw new B(404,`not_found`,`unknown task "${e}"`);let n=this.taskList.filter(t=>t.dependsOn.includes(e)).map(e=>e.id);if(n.length>0)throw new B(409,`has_dependents`,`cannot delete "${e}": ${n.map(e=>`"${e}"`).join(`, `)} depend on it`,{dependents:n});if(t.status===`IN_PROGRESS`)throw new B(409,`task_in_progress`,`cannot delete "${e}" while it is IN_PROGRESS; reopen it first`);this.taskList=this.taskList.filter(t=>t.id!==e),this.emit({type:`task.removed`,taskId:e})})}assertDependencies(e,t){for(let n of t){if(n===e)throw new B(400,`self_dependency`,`task "${e}" depends on itself`);if(!this.taskList.some(e=>e.id===n))throw new B(400,`unknown_dependency`,`task "${e}" depends on unknown task "${n}"`)}let n=Nn(this.taskList,e,t);if(n)throw new B(400,`cycle`,`dependency cycle: ${n.join(` → `)}`,{cycle:n})}brain(){return this.respond(()=>({state:cn(this.taskList,this.clock()),architecture:ln}))}runner(){return this.respond(()=>(this.assertRunner(),this.runnerStatus))}runnerAction(e,t={}){return this.respond(()=>{this.assertRunner();let n=this.runnerStatus.state;if(e===`start`&&t.taskId!==void 0&&n!==`paused`&&this.assertRunnable(t.taskId),e===`pause`)n!==`paused`&&n!==`idle`&&n!==`stopped`&&(this.pausedFrom=n,this.haltRunner(),this.setRunner({...this.runnerStatus,state:`paused`}),this.runnerLog(`warn`,`Paused by user. The current step resumes where it left off.`));else if(e===`start`)n===`paused`?(this.setRunner({...this.runnerStatus,state:this.pausedFrom??`selecting`}),this.pausedFrom=void 0,this.runnerLog(`info`,`Resumed by user.`),this.pumpRunner()):(n===`idle`||n===`stopped`||n===`error`)&&(this.runnerLog(`info`,`Runner started.`),this.runnerQueue=[],this.enqueueSelect(0,t.taskId),this.pumpRunner());else if(e===`stop`){this.haltRunner(),this.runnerQueue=[];let e=this.runnerStatus.taskId;if(e){let t=this.taskList.find(t=>t.id===e);t&&t.status===`IN_PROGRESS`&&this.commitTask({...t,status:`PENDING`,notes:`Run stopped by user; branch kept.`})}this.setRunner({state:`stopped`}),this.runnerLog(`warn`,`Stopped by user. Work in progress stays on its task branch.`)}return this.runnerStatus})}logs(e=200){return this.respond(()=>this.buffer.slice(-e))}goals(){return this.respond(()=>(this.assertGoals(),this.goalSim.all()))}startGoal(e){return this.respond(()=>(this.assertGoals(),this.goalSim.start(e)))}executeGoal(e){return this.respond(()=>(this.assertGoals(),this.goalSim.execute(e)))}goalArtifact(e,t){return this.respond(()=>(this.assertGoals(),this.goalSim.artifact(e,t)))}cancelGoal(e){return this.respond(()=>(this.assertGoals(),this.goalSim.cancel(e)))}models(){return this.respond(()=>{let e=Math.floor(this.t0/1e3),t=[];for(let n of this.accounts.filter(e=>e.enabled))for(let r of this.modelsFor(n))t.push({id:`${n.provider}/${r}`,object:`model`,created:e,owned_by:n.provider});for(let n of this.routeList)t.push({id:`davecode/${n.name}`,object:`model`,created:e,owned_by:`davecode`});return t})}subscribe(e){this.subscribers.add(e),e.onStatus?.({state:`mock`,attempt:0,lastEventAt:this.clock()});let t=this.buffer.slice(-500);return queueMicrotask(()=>{if(this.subscribers.has(e))for(let n of t)e.onEvent(n)}),this.stopGrace&&=(clearTimeout(this.stopGrace),void 0),this.start(),()=>{this.subscribers.delete(e),this.subscribers.size===0&&(this.stopGrace=setTimeout(()=>this.stop(),1e3))}}start(){this.running||(this.running=!0,this.scheduleRequest(),this.every(5e3,()=>{for(let e of this.accounts)e.enabled&&this.emit({type:`quota.updated`,usage:this.accountUsage(e,this.clock())});this.checkPressure()}),this.opts.runnerAvailable&&(!this.initialResumed&&this.runnerStatus.state===`implementing`&&(this.initialResumed=!0,this.resumeInitialTask()),this.runnerStatus.state!==`paused`&&this.pumpRunner()))}stop(){this.running=!1;for(let e of this.timers)clearTimeout(e);this.timers.clear(),this.haltRunner()}later(e,t){let n=setTimeout(()=>{this.timers.delete(n),this.running&&t()},e);this.timers.add(n)}every(e,t){let n=()=>{t(),this.later(e,n)};this.later(e,n)}rate(e){let t=e/J,n=11+4*Math.sin(t/9)+2.5*Math.sin(t/3.3);return Math.max(3,n)}scheduleRequest(){let e=J/this.rate(this.clock()),t=Math.min(e*3,-Math.log(1-this.rng())*e);this.later(Math.max(250,t),()=>{this.runLiveRequest(),this.scheduleRequest()})}runLiveRequest(){let e=this.planRequest(this.clock(),!0);if(!e)return;let t=this.nextId(`req`),{candidates:n}=e,r=e=>{let i=n[e];if(!i)return;let{account:a,target:o}=i;this.emit({type:`request.started`,requestId:t,model:o.model,accountId:a.id,provider:a.provider});let s=this.rollAttempt(a,o,this.clock(),!0);this.later(s.latencyMs,()=>{let i=this.clock();if(this.pushRecord(t,s,i),s.ok){this.emit({type:`request.completed`,requestId:t,model:o.model,accountId:a.id,provider:a.provider,promptTokens:s.promptTokens,completionTokens:s.completionTokens,latencyMs:s.latencyMs}),this.emit({type:`quota.updated`,usage:this.accountUsage(a,i)});return}let c=s.errorKind??`unknown`,[l,u]=X[c]??[500,`Upstream error`];this.emit({type:`request.failed`,requestId:t,accountId:a.id,provider:a.provider,error:{kind:c,message:u,status:l}}),(c===`rate_limit`||c===`quota_exhausted`||c===`unavailable`)&&this.startCooldown(a,c===`unavailable`?20:45);let d=e+1<n.length&&e<Un?n[e+1]:void 0;this.emit({type:`router.failover`,requestId:t,fromAccountId:a.id,toAccountId:d?.account.id??null,reason:c}),d&&this.later(20+this.rng()*40,()=>r(e+1))})};r(0)}pickRoute(){let e=this.rng();for(let[t,n]of on){if(e<n)return t;e-=n}return`auto`}candidatesFor(e,t){return this.accounts.filter(n=>!n.enabled||n.status===`disabled`||n.status===`error`||t&&n.status===`cooldown`?!1:e.accountId?n.id===e.accountId:n.provider===e.provider?this.modelsFor(n).includes(e.model)||this.modelsFor(n).length===0:!1)}planRequest(e,t){let n=this.routeList.find(e=>e.name===this.pickRoute())??this.routeList[0];if(!n)return null;let r=[];if(n.targets.forEach((n,i)=>{for(let a of this.candidatesFor(n,t)){let t=this.util5h(a,e),o=t>=Hn?.12:t>=Y?.45:1,s=[5,3,1.4,.7][i]??.5;r.push({account:a,target:n,weight:s*a.weight*o})}}),r.length===0)return null;let i=r.reduce((e,t)=>e+t.weight,0),a=this.rng()*i,o=0;for(let e=0;e<r.length;e++)if(a-=r[e]?.weight??0,a<=0){o=e;break}let s=r[o];if(!s)return null;let c=r.filter((e,t)=>t!==o&&r[t]?.account.id!==s.account.id);return{model:s.target.model,candidates:[s,...c].map(({account:e,target:t})=>({account:e,target:t}))}}rollAttempt(e,t,n,r){let i=this.seeds.get(e.id),[a,o]=i?.latency??[700,10],s=t.model.includes(`mini`)||t.model.includes(`haiku`)||t.model.includes(`scout`),c=t.model.includes(`opus`)||t.model.includes(`pro`),l=Math.round((s?900:2400)*Math.exp(this.rng()*1.6)),u=Math.round((s?80:c?700:300)*Math.exp(this.rng()*1.1)),d=Math.round((a+u*o*(s?.35:.6))*(.75+this.rng()*.5)),f=this.util5h(e,n),p=i?.failRate??.01;if(f>=Hn?p+=.5:f>=Y&&(p+=.16),r||(p*=.8),this.rng()<p){let n=e.provider===`openai-compatible`?`timeout`:f>=Y||this.rng()<.7?`rate_limit`:`unavailable`;return{account:e,target:t,ok:!1,errorKind:n,status:X[n]?.[0],latencyMs:Math.round(n===`timeout`?6e3+this.rng()*2e3:180+this.rng()*400),promptTokens:0,completionTokens:0}}return{account:e,target:t,ok:!0,latencyMs:d,promptTokens:l,completionTokens:u}}pushRecord(e,t,n){this.records.push({id:this.nextId(`use`),requestId:e,accountId:t.account.id,provider:t.account.provider,model:t.target.model,promptTokens:t.promptTokens,completionTokens:t.completionTokens,latencyMs:t.latencyMs,status:t.ok?`success`:t.errorKind===`rate_limit`?`rate_limited`:`error`,...t.errorKind&&{errorKind:t.errorKind},ts:n});let r=this.clock()-72e5;(this.records.length>4e3||(this.records[0]?.ts??r)<r)&&(this.records=this.records.filter(e=>e.ts>=r).slice(-4e3))}generateHistory(){let e=this.t0-62*J,t=this.t0-6*J;for(let n=e;n<this.t0;n+=J){let e=n>this.t0-24*J&&n<this.t0-18*J?7:0,r=Math.round(this.rate(n)+e+(this.rng()-.5)*4);for(let e=0;e<r;e++){let e=n+this.rng()*J;if(e>=this.t0)continue;let r=this.planRequest(e,!1);if(!r)continue;let i=this.nextId(`req`),a=e;for(let n=0;n<r.candidates.length&&n<=Un;n++){let o=r.candidates[n];if(!o)break;let s=this.rollAttempt(o.account,o.target,a,!1),c=a+s.latencyMs;if(c>=this.t0||(this.pushRecord(i,s,c),e>=t&&this.bufferChainEvents(i,s,a,c,r.candidates[n+1]?.account),a=c+25,s.ok))break}}}this.records.sort((e,t)=>e.ts-t.ts),this.buffer.sort((e,t)=>e.ts-t.ts)}bufferChainEvents(e,t,n,r,i){let a={requestId:e,accountId:t.account.id,provider:t.account.provider};if(this.buffer.push({type:`request.started`,...a,model:t.target.model,ts:n}),t.ok){this.buffer.push({type:`request.completed`,...a,model:t.target.model,promptTokens:t.promptTokens,completionTokens:t.completionTokens,latencyMs:t.latencyMs,ts:r});return}let o=t.errorKind??`unknown`,[s,c]=X[o]??[500,`Upstream error`];this.buffer.push({type:`request.failed`,...a,error:{kind:o,message:c,status:s},ts:r}),this.buffer.push({type:`router.failover`,requestId:e,fromAccountId:t.account.id,toAccountId:i?.id??null,reason:o,ts:r+1})}curve(e,t){let n=Math.max(0,t-this.t0)/1e3,r=1-Math.exp(-(n+20)/260),i=Math.sin(t/23e3)*.004;return Math.max(0,e.from+(e.to-e.from)*r+(e.to>0?i:0))}util5h(e,t){let n=this.seeds.get(e.id);return!n||!e.limits.tokens5h&&!e.limits.requests5h?0:this.curve(n.curve5h,t)}accountUsage(e,t){let n=this.seeds.get(e.id),r=this.records.filter(n=>n.accountId===e.id&&n.ts>t-J&&n.ts<=t),i=this.records.filter(n=>n.accountId===e.id&&n.ts>t-60*J),a=e=>e.reduce((e,t)=>e+t.promptTokens+t.completionTokens,0),o=e.limits,s=a(r),c={window:`1m`,tokens:s,requests:r.length,...o.tpm!==void 0&&{tokenLimit:o.tpm},...o.rpm!==void 0&&{requestLimit:o.rpm},utilization:Math.max(o.tpm?s/o.tpm:0,o.rpm?r.length/o.rpm:0)},l=(e,n,r,o,s)=>{if(!n&&!r)return{window:e,tokens:Math.round(a(i)*s),requests:Math.round(i.length*s),utilization:0};let c=o?this.curve(o,t):0;return{window:e,tokens:Math.round(c*(n??a(i)*s*2)),requests:Math.round(r?c*.92*r:i.length*s),...n!==void 0&&{tokenLimit:n},...r!==void 0&&{requestLimit:r},utilization:c}};return{accountId:e.id,windows:{"1m":c,"5h":l(`5h`,o.tokens5h,o.requests5h,n?.curve5h,3.4),"24h":l(`24h`,o.tokensDaily,o.requestsDaily,n?.curve24h,9.5)}}}checkPressure(){let e=this.clock();for(let t of this.accounts){let n=this.util5h(t,e),r=n>=Hn?2:+(n>=Y);r>(this.pressureLogged.get(t.id)??0)&&(this.pressureLogged.set(t.id,r),r===1?this.log(`info`,`router`,`Backpressure: ${t.id} at ${(n*100).toFixed(0)}% of its 5h window; weight smoothed down`):this.log(`warn`,`router`,`Quota shift: ${t.id} above 90% of its 5h window; routing to alternates`))}}startCooldown(e,t){let n=this.accounts.find(t=>t.id===e.id);if(!n||n.status===`cooldown`)return;let r=this.clock()+t*1e3;this.replaceAccount({...n,status:`cooldown`,cooldownUntil:new Date(r).toISOString(),lastError:X.rate_limit?.[1],updatedAt:new Date(this.clock()).toISOString()}),this.log(`warn`,`router`,`${e.id} cooling down for ${t}s after upstream ${t>30?429:503}`),this.later(t*1e3,()=>{let t=this.accounts.find(t=>t.id===e.id);if(t?.status!==`cooldown`)return;let{cooldownUntil:n,...r}=t;this.replaceAccount({...r,status:`active`,updatedAt:new Date(this.clock()).toISOString()}),this.log(`info`,`router`,`${e.id} back in rotation`)})}buildTimeseries(e,t){let n=Math.max(1,t)*1e3,r=this.clock(),i=Math.floor(r/n)*n,a=i-(Math.ceil(e*J/n)-1)*n,o=[];for(let e=a;e<=i;e+=n)o.push({ts:e,tokens:0,requests:0,byAccount:{}});for(let e of this.records){if(e.ts<a||e.ts>r||e.status!==`success`)continue;let t=o[Math.floor((e.ts-a)/n)];if(!t)continue;let i=e.promptTokens+e.completionTokens;t.tokens+=i,t.requests+=1;let s=t.byAccount[e.accountId]??{tokens:0,requests:0};s.tokens+=i,s.requests+=1,t.byAccount[e.accountId]=s}return o}assertGoals(){if(!this.opts.runnerAvailable)throw new B(501,`goals_unavailable`,`Goal mode is not available; start the gateway inside a project (davecode init)`)}assertRunner(){if(!this.opts.runnerAvailable)throw new B(501,`runner_unavailable`,`The autonomous runner is not available in this gateway (started with --no-runner).`)}setRunner(e){this.runnerStatus=e,this.emit({type:`runner.status`,status:e})}runnerLog(e,t,n){let r=this.runnerStatus.taskId,i={type:`runner.log`,level:e,message:t,...r&&{taskId:r},ts:n??this.clock()};n===void 0?this.emit(i):this.buffer.push(i)}haltRunner(){this.runnerTimer&&clearTimeout(this.runnerTimer),this.runnerTimer=void 0,this.runnerPending&&this.runnerQueue.unshift(this.runnerPending),this.runnerPending=void 0}pumpRunner(){if(this.runnerTimer||!this.running)return;let e=this.runnerQueue.shift();e&&(this.runnerPending=e,this.runnerTimer=setTimeout(()=>{this.runnerTimer=void 0,this.runnerPending=void 0,e.run(),this.pumpRunner()},e.delay))}q(e,t){this.runnerQueue.push({delay:e,run:t})}commitTask(e){let t={...e,updatedAt:new Date(this.clock()).toISOString()};this.taskList=this.taskList.map(n=>n.id===e.id?t:n),this.emit({type:`task.updated`,task:t})}nextTask(){let e=new Set(this.taskList.filter(e=>e.status===`SUCCESS`).map(e=>e.id));return this.taskList.filter(t=>t.status===`PENDING`&&t.dependsOn.every(t=>e.has(t))).sort((e,t)=>(t.priority??0)-(e.priority??0))[0]}assertRunnable(e){let t=this.taskList.find(t=>t.id===e);if(!t)throw new B(404,`task_not_found`,`unknown task "${e}"`);if(t.status!==`PENDING`)throw new B(409,`task_not_runnable`,`task "${e}" is ${t.status}; only PENDING tasks can run`);let n=t.dependsOn.filter(e=>this.taskList.find(t=>t.id===e)?.status!==`SUCCESS`);if(n.length>0)throw new B(409,`task_blocked`,`task "${e}" is blocked by unfinished dependencies: ${n.map(e=>`"${e}"`).join(`, `)}`)}enqueueSelect(e,t){this.q(e,()=>{this.setRunner({state:`selecting`,startedAt:new Date(this.clock()).toISOString()}),this.runnerLog(`info`,`Scanning TASK_GRAPH.json for unblocked tasks…`)}),this.q(1100,()=>{let e=this.taskList.find(e=>e.id===t&&e.status===`PENDING`&&e.dependsOn.every(e=>this.taskList.find(t=>t.id===e)?.status===`SUCCESS`))??this.nextTask();if(e)this.commitTask({...e,status:`IN_PROGRESS`,attempts:(e.attempts??0)+1}),this.setRunner({state:`preparing`,taskId:e.id,repairCycle:0,startedAt:new Date(this.clock()).toISOString()}),this.runnerLog(`info`,`Selected ${e.id} (priority ${e.priority??0}): ${e.title}`),this.enqueueTask(e.id,0);else{let e=this.taskList.filter(e=>e.status===`PENDING`).length;this.runnerLog(`warn`,e?`No unblocked tasks: ${e} pending task(s) wait on a FAILED dependency (p2-codex-cli).`:`Task graph complete. Nothing left to do.`),this.setRunner({state:`idle`})}})}enqueueTask(e,t){t===0&&(this.q(900,()=>this.runnerLog(`info`,`$ git switch -c davecode/task-${e} main`)),this.q(1200,()=>this.runnerLog(`debug`,`Injected brain: STATE.md (2.3 KB), ARCHITECTURE.md (4.9 KB), 4 global preferences`))),this.enqueueImplement(e,t)}enqueueImplement(e,t){let n=Gn[e]??[`src/index.ts`];this.q(1e3,()=>{this.setRunner({...this.runnerStatus,state:`implementing`,taskId:e,repairCycle:t}),this.runnerLog(`info`,`→ davecode/auto · claude-sonnet-5-5 via acc_claude_pro (${(8+this.rng()*9).toFixed(1)}K in)`)}),n.forEach((e,t)=>{this.q(1400+this.rng()*1600,()=>{t===0&&this.runnerLog(`debug`,`read ${n[n.length-1]??e}`);let r=Math.round(20+this.rng()*160),i=Math.round(this.rng()*30);this.runnerLog(`info`,`edit ${e} (+${r} −${i})`)})}),this.enqueueValidate(e,t)}enqueueValidate(e,t){let n=t<(Kn[e]??0);if(this.q(1500,()=>{this.setRunner({...this.runnerStatus,state:`validating`}),this.runnerLog(`info`,`$ pnpm lint`)}),this.q(1100,()=>this.runnerLog(`info`,`✓ lint passed (${(.6+this.rng()).toFixed(1)}s)`)),this.q(400,()=>this.runnerLog(`info`,`$ pnpm typecheck`)),this.q(2200,()=>this.runnerLog(`info`,`✓ typecheck passed (${(4+this.rng()*3).toFixed(1)}s)`)),this.q(400,()=>this.runnerLog(`info`,`$ pnpm test`)),n){if(this.q(2600,()=>{this.runnerLog(`error`,`✗ 2 failed, 211 passed (8.1s)`),this.runnerLog(`error`,` FAIL ${Gn[e]?.at(-1)??`test`} > honours Retry-After given as an HTTP-date`)}),t+1>=3){this.q(900,()=>{let t=this.taskList.find(t=>t.id===e);t&&this.commitTask({...t,status:`FAILED`,notes:`Failed after 3 repair cycles.`}),this.runnerLog(`error`,`${e} FAILED after 3 repair cycles; branch kept for review.`)}),this.enqueueSelect(2e3);return}this.q(900,()=>{this.setRunner({...this.runnerStatus,state:`repairing`,repairCycle:t+1}),this.runnerLog(`warn`,`Repair cycle ${t+1}/3: feeding 2 failing assertions and stderr back to the model`)}),this.q(1600,()=>this.runnerLog(`info`,`→ davecode/reasoning · claude-opus-5-5 via acc_anthropic_work`)),this.enqueueImplement(e,t+1)}else this.q(2800,()=>this.runnerLog(`info`,`✓ ${200+Math.round(this.rng()*40)} tests passed (8.4s)`)),this.q(900,()=>{this.setRunner({...this.runnerStatus,state:`merging`}),this.runnerLog(`info`,`$ git merge --no-ff davecode/task-${e} → main`)}),this.q(1400,()=>{let t=this.taskList.find(t=>t.id===e);t&&this.commitTask({...t,status:`SUCCESS`,notes:void 0}),this.runnerLog(`info`,`✓ ${e} merged. STATE.md updated.`)}),this.enqueueSelect(2500)}resumeInitialTask(){this.q(1500,()=>this.runnerLog(`info`,`edit packages/core/src/router/failover.ts (+34 −9)`)),this.q(2200,()=>this.runnerLog(`info`,`edit packages/core/src/router/select.test.ts (+12 −2)`)),this.enqueueValidate(`p2-router`,1)}seedRunnerHistory(){let e=e=>this.t0-e*J;for(let[t,n,r]of[[4.3,`info`,`Scanning TASK_GRAPH.json for unblocked tasks…`],[4.25,`info`,`Selected p2-router (priority 80): Router with balancing, backpressure, cooldowns and hot failover`],[4.2,`info`,`$ git switch -c davecode/task-p2-router main`],[4.15,`debug`,`Injected brain: STATE.md (2.3 KB), ARCHITECTURE.md (4.9 KB), 4 global preferences`],[4.1,`info`,`→ davecode/auto · claude-sonnet-5-5 via acc_claude_pro (14.2K in)`],[3.9,`info`,`edit packages/core/src/router/select.ts (+142 −8)`],[3.7,`info`,`edit packages/core/src/router/failover.ts (+96 −0)`],[3.5,`info`,`edit packages/core/src/router/circuit-breaker.ts (+61 −0)`],[3.3,`info`,`edit packages/core/src/router/select.test.ts (+188 −0)`],[3.1,`info`,`$ pnpm lint`],[3.05,`info`,`✓ lint passed (1.1s)`],[3,`info`,`$ pnpm typecheck`],[2.9,`info`,`✓ typecheck passed (5.8s)`],[2.85,`info`,`$ pnpm test`],[2.7,`error`,`✗ 2 failed, 209 passed (8.3s)`],[2.69,`error`,` FAIL packages/core/src/router/select.test.ts > honours Retry-After given as an HTTP-date`],[2.6,`warn`,`Repair cycle 1/3: feeding 2 failing assertions and stderr back to the model`],[2.5,`info`,`→ davecode/reasoning · claude-opus-5-5 via acc_anthropic_work`],[2,`info`,`edit packages/core/src/router/failover.ts (+21 −6)`]])this.buffer.push({type:`runner.log`,level:n,message:r,taskId:`p2-router`,ts:e(t)});this.buffer.push({type:`runner.status`,status:{...this.runnerStatus},ts:e(2.4)}),this.buffer.push({type:`log`,level:`info`,scope:`gateway`,message:`Listening on http://127.0.0.1:4040 (dashboard at /)`,ts:e(5.5)}),this.buffer.sort((e,t)=>e.ts-t.ts)}emit(e){let t={...e,ts:e.ts??this.clock()};this.buffer.push(t),this.buffer.length>800&&this.buffer.splice(0,this.buffer.length-800);for(let e of this.subscribers)e.onEvent(t)}log(e,t,n){this.emit({type:`log`,level:e,scope:t,message:n})}nextId(e){this.seq+=1;let t=()=>Math.floor(this.rng()*16777215).toString(16).padStart(6,`0`);return`${e}_${t()}${t()}${this.seq.toString(36)}`}modelsFor(e){let t=e.config.models;return Array.isArray(t)?t.filter(e=>typeof e==`string`):e.provider===`claude-cli`?[`claude-sonnet-5-5`,`claude-opus-5-5`]:e.provider===`gemini-web`?[`gemini-3-pro`]:[]}findAccount(e){let t=this.accounts.find(t=>t.id===e);if(!t)throw new B(404,`not_found`,`Account ${e} not found`);return t}replaceAccount(e){this.accounts=this.accounts.map(t=>t.id===e.id?e:t),this.emit({type:`account.updated`,account:e})}async respond(e){return this.opts.latency&&await new Promise(e=>setTimeout(e,90+Math.random()*220)),structuredClone(e())}},Jn;function Yn(){if(!Jn){let e=typeof window>`u`?new URLSearchParams:new URLSearchParams(window.location.search||window.location.hash.split(`?`)[1]);Jn=new qn({runnerAvailable:e.get(`runner`)!==`off`,geminiWeb:e.get(`geminiWeb`)===`1`})}return Jn}var Xn=(0,a.createContext)(null),Zn=15e3;function Qn(e){return ft()?{mode:`mock`,reason:`forced`}:e===`mock`?{mode:`mock`,reason:`setting`}:e===`live`?{mode:`live`,reason:null}:{mode:`probing`,reason:null}}function $n({children:e}){let t=dt(),n=c(),[r,i]=(0,a.useState)(()=>Qn(t.dataMode)),[s,l]=(0,a.useState)(),[u,d]=(0,a.useState)(0),[f,p]=(0,a.useState)({state:`connecting`,attempt:0}),[m,h]=(0,a.useState)(!1);(0,a.useEffect)(()=>{i(Qn(t.dataMode))},[t.dataMode]);let g=(0,a.useMemo)(()=>St({baseUrl:t.gatewayUrl,token:t.token}),[t.gatewayUrl,t.token]);(0,a.useEffect)(()=>{if(ft()||t.dataMode!==`auto`)return;let e=!1,n,r=async()=>{try{if(await g.health(),e)return;h(!1),l(void 0),i({mode:`live`,reason:null})}catch(t){if(e)return;if(bt(t)&&t.reachable){h(t.status===401),i({mode:`live`,reason:null});return}l(t instanceof Error?t.message:String(t)),i({mode:`mock`,reason:`unreachable`}),n=window.setTimeout(r,Zn)}};return r(),()=>{e=!0,window.clearTimeout(n)}},[g,t.dataMode,u]);let _=r.mode===`mock`?Yn():g,v=r.mode===`mock`?`mock`:`live:${t.gatewayUrl}:${t.token?`auth`:`anon`}`,y=(0,a.useMemo)(()=>new Vt,[v]);(0,a.useEffect)(()=>{if(r.mode===`probing`)return;p({state:r.mode===`mock`?`mock`:`connecting`,attempt:0});let e=_.subscribe({onEvent:e=>{y.ingest(e)&&nr(n,v,e)},onStatus:e=>p(e)});return _.requests(200).then(e=>y.seedRecords(e)).catch(()=>{}),_.logs(500).then(e=>{for(let t of e)y.ingest(t)}).catch(()=>{}),()=>{e(),y.dispose()}},[_,y,n,v,r.mode]);let b=(0,a.useMemo)(()=>({client:_,sourceKey:v,live:y,connection:{mode:r.mode,reason:r.reason,stream:f,probeError:s,unauthorized:m},retry:()=>{d(e=>e+1),n.invalidateQueries()}}),[_,v,y,r,f,s,m,n]);return(0,o.jsx)(Xn.Provider,{value:b,children:e})}function Z(){let e=(0,a.useContext)(Xn);if(!e)throw Error(`useData must be used inside <DataProvider>`);return e}function er(){let{live:e}=Z();return(0,a.useSyncExternalStore)(e.subscribe,e.getState,e.getState)}function Q(e,...t){return[`dc`,e,...t]}function tr(e,t){if(!e)return[t];let n=e.findIndex(e=>e.id===t.id);if(n===-1)return[t,...e];let r=e.slice();return r[n]=t,r}function nr(e,t,n){switch(n.type){case`account.updated`:e.setQueryData(Q(t,`accounts`),e=>{if(!e)return e;let t=e.findIndex(e=>e.id===n.account.id);if(t===-1)return[...e,n.account];let r=e.slice();return r[t]=n.account,r});break;case`account.removed`:e.setQueryData(Q(t,`accounts`),e=>e?.filter(e=>e.id!==n.accountId)),e.setQueryData(Q(t,`usage`),e=>e?.filter(e=>e.accountId!==n.accountId));break;case`quota.updated`:e.setQueryData(Q(t,`usage`),e=>{if(!e)return e;let t=e.findIndex(e=>e.accountId===n.usage.accountId);if(t===-1)return[...e,n.usage];let r=e.slice();return r[t]=n.usage,r});break;case`task.updated`:e.setQueryData(Q(t,`tasks`),e=>{if(!e)return e;let t=e.graph.tasks.slice(),r=t.findIndex(e=>e.id===n.task.id);return r===-1?t.push(n.task):t[r]=n.task,{...e,graph:{...e.graph,tasks:t}}});break;case`task.removed`:e.setQueryData(Q(t,`tasks`),e=>e&&{...e,graph:{...e.graph,tasks:e.graph.tasks.filter(e=>e.id!==n.taskId)}});break;case`runner.status`:e.setQueryData(Q(t,`runner`),n.status);break;case`goal.updated`:e.setQueryData(Q(t,`goals`),e=>e&&tr(e,n.goal))}}function rr(){let{client:e,sourceKey:t}=Z();return M({queryKey:Q(t,`health`),queryFn:()=>e.health(),refetchInterval:3e4})}function ir(){let{client:e,sourceKey:t}=Z();return M({queryKey:Q(t,`accounts`),queryFn:()=>e.listAccounts(),refetchInterval:6e4})}function ar(){let{client:e,sourceKey:t}=Z();return M({queryKey:Q(t,`usage`),queryFn:()=>e.usage(),refetchInterval:3e4})}function or(){let{client:e,sourceKey:t}=Z();return M({queryKey:Q(t,`budget`),queryFn:()=>e.budget(),refetchInterval:3e4})}function sr(e,t=!1){let{client:n,sourceKey:r}=Z();return M({queryKey:Q(r,`connection`,e),queryFn:()=>n.connection(e),refetchInterval:t?3e3:!1,staleTime:15e3})}function cr(){let{client:e,sourceKey:t}=Z(),n=c();return N({mutationFn:t=>e.connect(t),onSuccess:(e,r)=>n.setQueryData(Q(t,`connection`,r),e.connection)})}function lr(e=60,t=60){let{client:n,sourceKey:r}=Z();return M({queryKey:Q(r,`timeseries`,e,t),queryFn:()=>n.timeseries(e,t),refetchInterval:6e4})}function ur(){let{client:e,sourceKey:t}=Z();return M({queryKey:Q(t,`routes`),queryFn:()=>e.routes()})}function dr(){let{client:e,sourceKey:t}=Z();return M({queryKey:Q(t,`models`),queryFn:()=>e.models()})}function fr(){let{client:e,sourceKey:t}=Z();return M({queryKey:Q(t,`tasks`),queryFn:()=>e.tasks(),refetchInterval:6e4})}function pr(){let{client:e,sourceKey:t}=Z();return M({queryKey:Q(t,`brain`),queryFn:()=>e.brain(),refetchInterval:6e4})}function mr(){let{client:e,sourceKey:t}=Z();return M({queryKey:Q(t,`runner`),queryFn:()=>e.runner(),refetchInterval:15e3,retry:(e,t)=>t.status!==501&&e<2})}function hr(){let{sourceKey:e}=Z(),t=c(),n=Q(e,`accounts`);return{upsert:e=>t.setQueryData(n,t=>{if(!t)return[e];let n=t.findIndex(t=>t.id===e.id);if(n===-1)return[...t,e];let r=t.slice();return r[n]=e,r}),remove:e=>t.setQueryData(n,t=>t?.filter(t=>t.id!==e)),invalidate:()=>{t.invalidateQueries({queryKey:n}),t.invalidateQueries({queryKey:Q(e,`usage`)}),t.invalidateQueries({queryKey:Q(e,`budget`)})}}}function gr(){let{client:e}=Z(),t=hr();return N({mutationFn:t=>e.createAccount(t),onSuccess:e=>t.upsert(e),onSettled:()=>t.invalidate()})}function _r(){let{client:e,sourceKey:t}=Z(),n=c(),r=hr();return N({mutationFn:({id:t,patch:n})=>e.updateAccount(t,n),onMutate:async({id:e,patch:r})=>{let i=Q(t,`accounts`);await n.cancelQueries({queryKey:i});let a=n.getQueryData(i);return a&&r.enabled!==void 0&&n.setQueryData(i,a.map(t=>t.id===e?{...t,enabled:r.enabled,status:r.enabled?`active`:`disabled`}:t)),{prev:a}},onError:(e,r,i)=>{i?.prev&&n.setQueryData(Q(t,`accounts`),i.prev)},onSuccess:e=>r.upsert(e),onSettled:()=>n.invalidateQueries({queryKey:Q(t,`budget`)})})}function vr(){let{client:e}=Z(),t=hr();return N({mutationFn:t=>e.deleteAccount(t),onSuccess:(e,n)=>t.remove(n),onSettled:()=>t.invalidate()})}function yr(){let{sourceKey:e}=Z(),t=c(),n=Q(e,`tasks`);return{upsert:e=>t.setQueryData(n,t=>{if(!t)return t;let n=t.graph.tasks.slice(),r=n.findIndex(t=>t.id===e.id);return r===-1?n.push(e):n[r]=e,{...t,graph:{...t.graph,tasks:n}}}),remove:e=>t.setQueryData(n,t=>t&&{...t,graph:{...t.graph,tasks:t.graph.tasks.filter(t=>t.id!==e)}}),invalidate:()=>{t.invalidateQueries({queryKey:n}),t.invalidateQueries({queryKey:Q(e,`brain`)})}}}function br(){let{client:e}=Z(),t=yr();return N({mutationFn:t=>e.createTask(t),onSuccess:e=>t.upsert(e),onSettled:()=>t.invalidate()})}function xr(){let{client:e}=Z(),t=yr();return N({mutationFn:({id:t,patch:n})=>e.updateTask(t,n),onSuccess:e=>t.upsert(e),onSettled:()=>t.invalidate()})}function Sr(){let{client:e}=Z(),t=yr();return N({mutationFn:t=>e.deleteTask(t),onSuccess:(e,n)=>t.remove(n),onSettled:()=>t.invalidate()})}function Cr(){let{client:e,sourceKey:t}=Z(),n=c();return N({mutationFn:t=>e.updateRoutes(t),onSuccess:({defaultRoute:e,routes:r})=>{n.setQueryData(Q(t,`routes`),{defaultRoute:e,routes:r}),n.invalidateQueries({queryKey:Q(t,`models`)})}})}function wr(){let{client:e,sourceKey:t}=Z(),n=c();return N({mutationFn:t=>e.runnerAction(t),onSuccess:e=>n.setQueryData(Q(t,`runner`),e)})}function Tr(){let{client:e,sourceKey:t}=Z();return M({queryKey:Q(t,`goals`),queryFn:()=>e.goals(),refetchInterval:6e4,retry:(e,t)=>t.status!==501&&e<2})}function Er(){let{sourceKey:e}=Z(),t=c();return n=>t.setQueryData(Q(e,`goals`),e=>tr(e,n))}function Dr(){let{client:e}=Z(),t=Er();return N({mutationFn:t=>e.startGoal(t),onSuccess:e=>t(e)})}function Or(){let{client:e}=Z(),t=Er();return N({mutationFn:t=>e.executeGoal(t),onSuccess:e=>t(e)})}function kr(e,t){let{client:n,sourceKey:r}=Z();return M({queryKey:Q(r,`goal-artifact`,e??``,t??``),queryFn:()=>n.goalArtifact(e,t),enabled:!!(e&&t),staleTime:6e4})}function Ar(){let{client:e}=Z(),t=Er();return N({mutationFn:t=>e.cancelGoal(t),onSuccess:e=>t(e)})}function jr(){let{client:e,sourceKey:t}=Z(),n=c();return N({mutationFn:t=>e.runnerAction(`start`,{taskId:t}),onSuccess:e=>n.setQueryData(Q(t,`runner`),e)})}var Mr=new Intl.NumberFormat(`en`,{notation:`compact`,maximumFractionDigits:1}),Nr=new Intl.NumberFormat(`en`);function Pr(e){return Number.isFinite(e)?Mr.format(e):`—`}function Fr(e){return Number.isFinite(e)?Nr.format(Math.round(e)):`—`}function Ir(e,t=0){return Number.isFinite(e)?`${(e*100).toFixed(t)}%`:`—`}function Lr(e){return Number.isFinite(e)?e<1e3?`${Math.round(e)} ms`:`${(e/1e3).toFixed(e<1e4?2:1)} s`:`—`}function Rr(e){let t=Math.max(0,Math.floor(e));if(t<60)return`${t}s`;let n=Math.floor(t/60);if(n<60)return`${n}m ${String(t%60).padStart(2,`0`)}s`;let r=Math.floor(n/60);return r<24?`${r}h ${String(n%60).padStart(2,`0`)}m`:`${Math.floor(r/24)}d ${r%24}h`}function zr(e){let t=Math.max(0,Math.ceil(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,`0`)}`}function Br(e,t=!1){let n=new Date(e),r=`${$(n.getHours())}:${$(n.getMinutes())}:${$(n.getSeconds())}`;return t?`${r}.${String(n.getMilliseconds()).padStart(3,`0`)}`:r}function Vr(e){let t=new Date(e);return`${$(t.getHours())}:${$(t.getMinutes())}`}function Hr(e,t=Date.now()){let n=Math.round((t-e)/1e3);return n<5?`just now`:n<60?`${n}s ago`:n<3600?`${Math.floor(n/60)}m ago`:n<86400?`${Math.floor(n/3600)}h ago`:new Date(e).toLocaleDateString()}function $(e){return String(e).padStart(2,`0`)}function Ur(e,t=8){return(e.includes(`_`)?e.slice(e.indexOf(`_`)+1):e).slice(0,t)}var Wr={neutral:`bg-hover text-fg-2 border-line-strong`,accent:`bg-accent-soft text-accent-text border-accent/25`,ok:`bg-ok-soft text-ok border-ok/25`,warn:`bg-warn-soft text-warn border-warn/25`,err:`bg-err-soft text-err border-err/25`,info:`bg-info-soft text-info border-info/25`},Gr={neutral:`bg-muted`,accent:`bg-accent`,ok:`bg-ok`,warn:`bg-warn`,err:`bg-err`,info:`bg-info`};function Kr({tone:t=`neutral`,dot:n,pulse:r,mono:i,className:a,children:s}){return(0,o.jsxs)(`span`,{className:e(`inline-flex h-5 shrink-0 items-center gap-1.5 rounded border px-1.5 text-2xs font-medium whitespace-nowrap`,i&&`font-mono`,Wr[t],a),children:[n&&(0,o.jsx)(qr,{tone:t,pulse:r}),s]})}function qr({tone:t=`neutral`,pulse:n,className:r}){return(0,o.jsx)(`span`,{"aria-hidden":!0,className:e(`inline-block size-1.5 shrink-0 rounded-full`,Gr[t],n&&`animate-pulse-dot`,n&&Jr[t],r)})}var Jr={neutral:`text-muted/60`,accent:`text-accent/60`,ok:`text-ok/60`,warn:`text-warn/60`,err:`text-err/60`,info:`text-info/60`};export{yn as $,mr as A,b as At,Z as B,Or as C,he as Ct,dr as D,h as Dt,rr as E,O as Et,_r as F,D as Ft,Pn as G,Rn as H,Cr as I,l as It,En as J,Vn as K,xr as L,c as Lt,Dr as M,m as Mt,fr as N,C as Nt,ur as O,S as Ot,lr as P,v as Pt,Sn as Q,ar as R,Sr as S,we as St,Tr as T,fe as Tt,Mn as U,er as V,Fn as W,Dn as X,An as Y,Ln as Z,cr as _,pt as _t,zr as a,xn as at,br as b,M as bt,Fr as c,Nt as ct,Hr as d,St as dt,gn as et,Ur as f,Ct as ft,Ar as g,ft as gt,or as h,z as ht,Pr as i,vn as it,wr as j,y as jt,jr as k,x as kt,Lr as l,Mt as lt,pr as m,mt,qr as n,bn as nt,Rr as o,Zt as ot,ir as p,bt as pt,Bn as q,Br as r,_n as rt,Vr as s,Qt as st,Kr as t,hn as tt,Ir as u,Pt as ut,sr as v,lt as vt,kr as w,k as wt,vr as x,Me as xt,gr as y,dt as yt,$n as z};
|
|
55
|
+
`),priority:e.priority===void 0?``:String(e.priority),notes:e.notes??``,dependsOn:[...e.dependsOn]}}function In(e){return e.split(/\r?\n/).map(e=>e.replace(/^\s*(?:[-*]|\d+[.)])\s+/,``).trim()).filter(Boolean)}function q(e){let t=e.trim();if(!t)return{};let n=Number(t);return Number.isFinite(n)?{value:n}:{error:`Priority must be a number.`}}function Ln(e,t,n){let r={};if(n===void 0){let n=Tn(e.id.trim(),t);n&&(r.id=n)}e.title.trim()?e.title.trim().length>300&&(r.title=`Keep the title under 300 characters.`):r.title=`Give the task a title.`;let i=q(e.priority);i.error&&(r.priority=i.error);let a=n??e.id.trim();if(e.dependsOn.includes(a))r.dependsOn=`A task cannot depend on itself.`;else{let n=e.dependsOn.find(e=>!t.some(t=>t.id===e));if(n)r.dependsOn=`Unknown task "${n}".`;else if(a){let n=Nn(t,a,e.dependsOn);n&&(r.dependsOn=`Would create a dependency cycle: ${n.join(` → `)}.`)}}return r}function Rn(e){let t=e.description.trim(),n=In(e.acceptance),{value:r}=q(e.priority);return{id:e.id.trim(),title:e.title.trim(),...t&&{description:t},...e.dependsOn.length>0&&{dependsOn:e.dependsOn},...r!==void 0&&{priority:r},...n.length>0&&{acceptance:n}}}var zn=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]);function Bn(e,t){let n={},r=t.title.trim();r!==e.title&&(n.title=r);let i=t.description.trim();i!==(e.description??``)&&(n.description=i||null);let a=t.notes.trim();a!==(e.notes??``)&&(n.notes=a||null);let o=In(t.acceptance);zn(o,e.acceptance??[])||(n.acceptance=o.length>0?o:null);let{value:s}=q(t.priority);return s!==e.priority&&(n.priority=s??null),zn(t.dependsOn,e.dependsOn)||(n.dependsOn=t.dependsOn),n}function Vn(e){return Object.keys(e).length===0}var J=6e4,Y=.85,Hn=.9,Un=4;function Wn(e){let t=e>>>0;return()=>{t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}}var X={rate_limit:[429,`Rate limited by upstream (Retry-After: 45)`],quota_exhausted:[429,`5h usage window exhausted for this account`],unavailable:[503,`Upstream overloaded, try again shortly`],timeout:[504,`Upstream did not answer within 60s`]},Gn={"p2-router":[`packages/core/src/router/select.ts`,`packages/core/src/router/failover.ts`,`packages/core/src/router/circuit-breaker.ts`,`packages/core/src/router/select.test.ts`],"p1-gateway":[`packages/server/src/app.ts`,`packages/server/src/routes/v1.ts`,`packages/server/src/routes/api.ts`,`packages/server/src/sse.ts`],"p4-runner":[`packages/core/src/autonomous/runner.ts`,`packages/core/src/autonomous/validator.ts`,`packages/core/src/autonomous/git.ts`,`packages/core/src/autonomous/runner.test.ts`],"p5-cli":[`packages/cli/src/commands/start.ts`,`packages/cli/src/commands/run.ts`,`packages/cli/src/tui/App.tsx`]},Kn={"p2-router":1,"p1-gateway":0,"p4-runner":2,"p5-cli":1},qn=class{mode=`mock`;rng;clock;t0;opts;seeds=new Map;accounts=[];records=[];taskList;routeList=structuredClone(an);defaultRoute=`auto`;runnerStatus;buffer=[];subscribers=new Set;timers=new Set;running=!1;stopGrace;seq=0;runnerQueue=[];runnerTimer;runnerPending;initialResumed=!1;pausedFrom;pressureLogged=new Map;goalSim;loggedIn=new Set($t);constructor(e={}){this.rng=Wn(e.seed??3665739998),this.clock=e.now??Date.now,this.opts={runnerAvailable:e.runnerAvailable??!0,geminiWeb:e.geminiWeb??!1,latency:e.latency??!0},this.t0=this.clock();for(let e of rn){this.seeds.set(e.account.id,e);let t=Kt(e.account.id,this.t0);this.accounts.push({...e.account,...t&&{subscription:t},status:e.account.status??`active`,createdAt:new Date(this.t0-10368e5).toISOString(),updatedAt:new Date(this.t0-36e5).toISOString()})}this.taskList=sn(this.t0),this.runnerStatus={state:`implementing`,taskId:`p2-router`,repairCycle:1,startedAt:new Date(this.t0-4.2*J).toISOString()},this.generateHistory(),this.opts.runnerAvailable&&this.seedRunnerHistory(),this.goalSim=new fn({now:()=>this.clock(),emit:e=>this.emit(e),later:(e,t)=>this.later(e,t),nextId:e=>this.nextId(e)}),this.goalSim.seed(this.t0)}health(){return this.respond(()=>({status:`ok`,version:`0.2.0`,uptimeSec:Math.round((this.clock()-this.t0)/1e3)+10800+1020,experimental:{geminiWeb:this.opts.geminiWeb,multiAccountRotation:!1}}))}listAccounts(){return this.respond(()=>this.accounts)}createAccount(e){return this.respond(()=>{if(!e.label?.trim())throw new B(400,`invalid_body`,`label: must not be empty`);if(e.provider===`gemini-web`&&!this.opts.geminiWeb)throw new B(400,`experimental_disabled`,`gemini-web requires experimental.geminiWeb = true in config.json`);let t=new Date(this.clock()).toISOString(),n={id:`acc_${e.provider.replace(/[^a-z]/g,``)}_${Math.floor(this.rng()*1e6).toString(36)}`,provider:e.provider,label:e.label.trim(),enabled:!0,priority:e.priority??100,weight:e.weight??1,limits:e.limits??{},config:e.config??{},...e.subscription&&{subscription:e.subscription},status:`active`,createdAt:t,updatedAt:t};return this.accounts.push(n),this.seeds.set(n.id,{account:n,curve5h:{from:0,to:.05},curve24h:{from:0,to:.02},latency:[700,10],failRate:.01}),this.emit({type:`account.updated`,account:n}),this.log(`info`,`accounts`,`Account ${n.id} (${n.provider}) added`),n})}updateAccount(e,t){return this.respond(()=>{let n=this.findAccount(e),r=t.enabled??n.enabled,i={...n,...t.label!==void 0&&{label:t.label},...t.priority!==void 0&&{priority:t.priority},...t.weight!==void 0&&{weight:t.weight},...t.limits!==void 0&&{limits:t.limits},...t.config!==void 0&&{config:t.config},...t.subscription&&{subscription:t.subscription},enabled:r,status:r?n.status===`disabled`?`active`:n.status:`disabled`,updatedAt:new Date(this.clock()).toISOString()};return r||delete i.cooldownUntil,t.subscription===null&&delete i.subscription,this.replaceAccount(i),i})}deleteAccount(e){return this.respond(()=>{this.findAccount(e),this.accounts=this.accounts.filter(t=>t.id!==e),this.emit({type:`account.removed`,accountId:e})})}usage(){return this.respond(()=>this.accounts.map(e=>this.accountUsage(e,this.clock())))}budget(){return this.respond(()=>{let e=this.clock();return Yt(this.accounts,t=>this.accountUsage(t,e),e)})}connection(e){return this.respond(()=>nn(this.findAccount(e),this.loggedIn.has(e),this.clock()))}connect(e){return this.respond(()=>{let t=nn(this.findAccount(e),this.loggedIn.has(e),this.clock());if(t.method!==`cli-login`)throw new B(400,`not_cli_login`,`This account connects with an API key: set it in the account settings`);let n=`davecode accounts login ${e}`;return t.status!==`connected`&&this.later(en,()=>{this.loggedIn.add(e),this.log(`info`,`accounts`,`Account ${e} signed in through the vendor CLI`)}),this.log(`info`,`accounts`,`Opened the official sign-in for ${e}`),{connection:t,launched:!0,command:n,message:`A terminal opened on the gateway machine with the official sign-in. Finish it there; this page updates when the login is detected.`}})}timeseries(e=60,t=60){return this.respond(()=>this.buildTimeseries(e,t))}requests(e=100){return this.respond(()=>this.records.slice(-e).reverse())}routes(){return this.respond(()=>({defaultRoute:this.defaultRoute,routes:this.routeList}))}updateRoutes(e){return this.respond(()=>{let t=new Set;if(e.routes.forEach((e,n)=>{let r=`routes.${n}`;if(!pn.test(e.name))throw new B(400,`invalid_body`,`${r}.name: route names are lowercase kebab-case`);if(t.has(e.name))throw new B(400,`invalid_body`,`${r}.name: duplicate route name "${e.name}"`);if(t.add(e.name),e.targets.length===0)throw new B(400,`invalid_body`,`${r}.targets: at least one target is required`);e.targets.forEach((t,n)=>{if(!t.model.trim())throw new B(400,`invalid_body`,`${r}.targets.${n}.model: required`);if(t.accountId&&!this.accounts.some(e=>e.id===t.accountId))throw new B(400,`unknown_account`,`route "${e.name}" pins unknown account "${t.accountId}"`)})}),e.defaultRoute!==void 0&&!t.has(e.defaultRoute))throw new B(400,`invalid_body`,`defaultRoute: "${e.defaultRoute}" is not one of the routes`);return this.routeList=structuredClone(e.routes),e.defaultRoute!==void 0&&(this.defaultRoute=e.defaultRoute),this.log(`info`,`config`,`Routes updated (${this.routeList.length}); saved to ~/.davecode/config.json`),{defaultRoute:this.defaultRoute,routes:this.routeList,shadowedByProject:!1}})}tasks(){return this.respond(()=>({project:{root:`C:/Users/dev/code/DaveCode`,name:`DaveCode`},graph:{version:1,tasks:this.taskList}}))}createTask(e){return this.respond(()=>{if(!wn.test(e.id))throw new B(400,`invalid_body`,`id: must be lowercase kebab-case or snake_case`);if(!e.title.trim())throw new B(400,`invalid_body`,`title: required`);if(this.taskList.some(t=>t.id===e.id))throw new B(409,`duplicate_id`,`duplicate task id "${e.id}"`);this.assertDependencies(e.id,e.dependsOn??[]);let t=new Date(this.clock()).toISOString(),n={id:e.id,title:e.title.trim(),status:`PENDING`,dependsOn:[...e.dependsOn??[]],...e.description!==void 0&&{description:e.description},...e.priority!==void 0&&{priority:e.priority},...e.acceptance!==void 0&&{acceptance:e.acceptance},createdAt:t,updatedAt:t};return this.taskList=[...this.taskList,n],this.emit({type:`task.updated`,task:n}),n})}updateTask(e,t){return this.respond(()=>{let n=this.taskList.find(t=>t.id===e);if(!n)throw new B(404,`not_found`,`unknown task "${e}"`);let r={...n};t.title!==void 0&&(r.title=t.title.trim()),t.dependsOn!==void 0&&(this.assertDependencies(e,t.dependsOn),r.dependsOn=[...t.dependsOn]);for(let e of[`description`,`priority`,`acceptance`,`notes`]){let n=t[e];n===null?delete r[e]:n!==void 0&&Object.assign(r,{[e]:n})}if(t.status!==void 0&&t.status!==n.status){if(!kn(n.status,t.status))throw new B(409,`invalid_transition`,`task "${e}": cannot move ${n.status} → ${t.status}`);r.status=t.status,t.status===`IN_PROGRESS`&&(r.attempts=(n.attempts??0)+1)}return this.commitTask(r),this.taskList.find(t=>t.id===e)})}deleteTask(e){return this.respond(()=>{let t=this.taskList.find(t=>t.id===e);if(!t)throw new B(404,`not_found`,`unknown task "${e}"`);let n=this.taskList.filter(t=>t.dependsOn.includes(e)).map(e=>e.id);if(n.length>0)throw new B(409,`has_dependents`,`cannot delete "${e}": ${n.map(e=>`"${e}"`).join(`, `)} depend on it`,{dependents:n});if(t.status===`IN_PROGRESS`)throw new B(409,`task_in_progress`,`cannot delete "${e}" while it is IN_PROGRESS; reopen it first`);this.taskList=this.taskList.filter(t=>t.id!==e),this.emit({type:`task.removed`,taskId:e})})}assertDependencies(e,t){for(let n of t){if(n===e)throw new B(400,`self_dependency`,`task "${e}" depends on itself`);if(!this.taskList.some(e=>e.id===n))throw new B(400,`unknown_dependency`,`task "${e}" depends on unknown task "${n}"`)}let n=Nn(this.taskList,e,t);if(n)throw new B(400,`cycle`,`dependency cycle: ${n.join(` → `)}`,{cycle:n})}brain(){return this.respond(()=>({state:cn(this.taskList,this.clock()),architecture:ln}))}runner(){return this.respond(()=>(this.assertRunner(),this.runnerStatus))}runnerAction(e,t={}){return this.respond(()=>{this.assertRunner();let n=this.runnerStatus.state;if(e===`start`&&t.taskId!==void 0&&n!==`paused`&&this.assertRunnable(t.taskId),e===`pause`)n!==`paused`&&n!==`idle`&&n!==`stopped`&&(this.pausedFrom=n,this.haltRunner(),this.setRunner({...this.runnerStatus,state:`paused`}),this.runnerLog(`warn`,`Paused by user. The current step resumes where it left off.`));else if(e===`start`)n===`paused`?(this.setRunner({...this.runnerStatus,state:this.pausedFrom??`selecting`}),this.pausedFrom=void 0,this.runnerLog(`info`,`Resumed by user.`),this.pumpRunner()):(n===`idle`||n===`stopped`||n===`error`)&&(this.runnerLog(`info`,`Runner started.`),this.runnerQueue=[],this.enqueueSelect(0,t.taskId),this.pumpRunner());else if(e===`stop`){this.haltRunner(),this.runnerQueue=[];let e=this.runnerStatus.taskId;if(e){let t=this.taskList.find(t=>t.id===e);t&&t.status===`IN_PROGRESS`&&this.commitTask({...t,status:`PENDING`,notes:`Run stopped by user; branch kept.`})}this.setRunner({state:`stopped`}),this.runnerLog(`warn`,`Stopped by user. Work in progress stays on its task branch.`)}return this.runnerStatus})}logs(e=200){return this.respond(()=>this.buffer.slice(-e))}goals(){return this.respond(()=>(this.assertGoals(),this.goalSim.all()))}startGoal(e){return this.respond(()=>(this.assertGoals(),this.goalSim.start(e)))}executeGoal(e){return this.respond(()=>(this.assertGoals(),this.goalSim.execute(e)))}goalArtifact(e,t){return this.respond(()=>(this.assertGoals(),this.goalSim.artifact(e,t)))}cancelGoal(e){return this.respond(()=>(this.assertGoals(),this.goalSim.cancel(e)))}models(){return this.respond(()=>{let e=Math.floor(this.t0/1e3),t=[];for(let n of this.accounts.filter(e=>e.enabled))for(let r of this.modelsFor(n))t.push({id:`${n.provider}/${r}`,object:`model`,created:e,owned_by:n.provider});for(let n of this.routeList)t.push({id:`davecode/${n.name}`,object:`model`,created:e,owned_by:`davecode`});return t})}subscribe(e){this.subscribers.add(e),e.onStatus?.({state:`mock`,attempt:0,lastEventAt:this.clock()});let t=this.buffer.slice(-500);return queueMicrotask(()=>{if(this.subscribers.has(e))for(let n of t)e.onEvent(n)}),this.stopGrace&&=(clearTimeout(this.stopGrace),void 0),this.start(),()=>{this.subscribers.delete(e),this.subscribers.size===0&&(this.stopGrace=setTimeout(()=>this.stop(),1e3))}}start(){this.running||(this.running=!0,this.scheduleRequest(),this.every(5e3,()=>{for(let e of this.accounts)e.enabled&&this.emit({type:`quota.updated`,usage:this.accountUsage(e,this.clock())});this.checkPressure()}),this.opts.runnerAvailable&&(!this.initialResumed&&this.runnerStatus.state===`implementing`&&(this.initialResumed=!0,this.resumeInitialTask()),this.runnerStatus.state!==`paused`&&this.pumpRunner()))}stop(){this.running=!1;for(let e of this.timers)clearTimeout(e);this.timers.clear(),this.haltRunner()}later(e,t){let n=setTimeout(()=>{this.timers.delete(n),this.running&&t()},e);this.timers.add(n)}every(e,t){let n=()=>{t(),this.later(e,n)};this.later(e,n)}rate(e){let t=e/J,n=11+4*Math.sin(t/9)+2.5*Math.sin(t/3.3);return Math.max(3,n)}scheduleRequest(){let e=J/this.rate(this.clock()),t=Math.min(e*3,-Math.log(1-this.rng())*e);this.later(Math.max(250,t),()=>{this.runLiveRequest(),this.scheduleRequest()})}runLiveRequest(){let e=this.planRequest(this.clock(),!0);if(!e)return;let t=this.nextId(`req`),{candidates:n}=e,r=e=>{let i=n[e];if(!i)return;let{account:a,target:o}=i;this.emit({type:`request.started`,requestId:t,model:o.model,accountId:a.id,provider:a.provider});let s=this.rollAttempt(a,o,this.clock(),!0);this.later(s.latencyMs,()=>{let i=this.clock();if(this.pushRecord(t,s,i),s.ok){this.emit({type:`request.completed`,requestId:t,model:o.model,accountId:a.id,provider:a.provider,promptTokens:s.promptTokens,completionTokens:s.completionTokens,latencyMs:s.latencyMs}),this.emit({type:`quota.updated`,usage:this.accountUsage(a,i)});return}let c=s.errorKind??`unknown`,[l,u]=X[c]??[500,`Upstream error`];this.emit({type:`request.failed`,requestId:t,accountId:a.id,provider:a.provider,error:{kind:c,message:u,status:l}}),(c===`rate_limit`||c===`quota_exhausted`||c===`unavailable`)&&this.startCooldown(a,c===`unavailable`?20:45);let d=e+1<n.length&&e<Un?n[e+1]:void 0;this.emit({type:`router.failover`,requestId:t,fromAccountId:a.id,toAccountId:d?.account.id??null,reason:c}),d&&this.later(20+this.rng()*40,()=>r(e+1))})};r(0)}pickRoute(){let e=this.rng();for(let[t,n]of on){if(e<n)return t;e-=n}return`auto`}candidatesFor(e,t){return this.accounts.filter(n=>!n.enabled||n.status===`disabled`||n.status===`error`||t&&n.status===`cooldown`?!1:e.accountId?n.id===e.accountId:n.provider===e.provider?this.modelsFor(n).includes(e.model)||this.modelsFor(n).length===0:!1)}planRequest(e,t){let n=this.routeList.find(e=>e.name===this.pickRoute())??this.routeList[0];if(!n)return null;let r=[];if(n.targets.forEach((n,i)=>{for(let a of this.candidatesFor(n,t)){let t=this.util5h(a,e),o=t>=Hn?.12:t>=Y?.45:1,s=[5,3,1.4,.7][i]??.5;r.push({account:a,target:n,weight:s*a.weight*o})}}),r.length===0)return null;let i=r.reduce((e,t)=>e+t.weight,0),a=this.rng()*i,o=0;for(let e=0;e<r.length;e++)if(a-=r[e]?.weight??0,a<=0){o=e;break}let s=r[o];if(!s)return null;let c=r.filter((e,t)=>t!==o&&r[t]?.account.id!==s.account.id);return{model:s.target.model,candidates:[s,...c].map(({account:e,target:t})=>({account:e,target:t}))}}rollAttempt(e,t,n,r){let i=this.seeds.get(e.id),[a,o]=i?.latency??[700,10],s=t.model.includes(`mini`)||t.model.includes(`haiku`)||t.model.includes(`scout`),c=t.model.includes(`opus`)||t.model.includes(`pro`),l=Math.round((s?900:2400)*Math.exp(this.rng()*1.6)),u=Math.round((s?80:c?700:300)*Math.exp(this.rng()*1.1)),d=Math.round((a+u*o*(s?.35:.6))*(.75+this.rng()*.5)),f=this.util5h(e,n),p=i?.failRate??.01;if(f>=Hn?p+=.5:f>=Y&&(p+=.16),r||(p*=.8),this.rng()<p){let n=e.provider===`openai-compatible`?`timeout`:f>=Y||this.rng()<.7?`rate_limit`:`unavailable`;return{account:e,target:t,ok:!1,errorKind:n,status:X[n]?.[0],latencyMs:Math.round(n===`timeout`?6e3+this.rng()*2e3:180+this.rng()*400),promptTokens:0,completionTokens:0}}return{account:e,target:t,ok:!0,latencyMs:d,promptTokens:l,completionTokens:u}}pushRecord(e,t,n){this.records.push({id:this.nextId(`use`),requestId:e,accountId:t.account.id,provider:t.account.provider,model:t.target.model,promptTokens:t.promptTokens,completionTokens:t.completionTokens,latencyMs:t.latencyMs,status:t.ok?`success`:t.errorKind===`rate_limit`?`rate_limited`:`error`,...t.errorKind&&{errorKind:t.errorKind},ts:n});let r=this.clock()-72e5;(this.records.length>4e3||(this.records[0]?.ts??r)<r)&&(this.records=this.records.filter(e=>e.ts>=r).slice(-4e3))}generateHistory(){let e=this.t0-62*J,t=this.t0-6*J;for(let n=e;n<this.t0;n+=J){let e=n>this.t0-24*J&&n<this.t0-18*J?7:0,r=Math.round(this.rate(n)+e+(this.rng()-.5)*4);for(let e=0;e<r;e++){let e=n+this.rng()*J;if(e>=this.t0)continue;let r=this.planRequest(e,!1);if(!r)continue;let i=this.nextId(`req`),a=e;for(let n=0;n<r.candidates.length&&n<=Un;n++){let o=r.candidates[n];if(!o)break;let s=this.rollAttempt(o.account,o.target,a,!1),c=a+s.latencyMs;if(c>=this.t0||(this.pushRecord(i,s,c),e>=t&&this.bufferChainEvents(i,s,a,c,r.candidates[n+1]?.account),a=c+25,s.ok))break}}}this.records.sort((e,t)=>e.ts-t.ts),this.buffer.sort((e,t)=>e.ts-t.ts)}bufferChainEvents(e,t,n,r,i){let a={requestId:e,accountId:t.account.id,provider:t.account.provider};if(this.buffer.push({type:`request.started`,...a,model:t.target.model,ts:n}),t.ok){this.buffer.push({type:`request.completed`,...a,model:t.target.model,promptTokens:t.promptTokens,completionTokens:t.completionTokens,latencyMs:t.latencyMs,ts:r});return}let o=t.errorKind??`unknown`,[s,c]=X[o]??[500,`Upstream error`];this.buffer.push({type:`request.failed`,...a,error:{kind:o,message:c,status:s},ts:r}),this.buffer.push({type:`router.failover`,requestId:e,fromAccountId:t.account.id,toAccountId:i?.id??null,reason:o,ts:r+1})}curve(e,t){let n=Math.max(0,t-this.t0)/1e3,r=1-Math.exp(-(n+20)/260),i=Math.sin(t/23e3)*.004;return Math.max(0,e.from+(e.to-e.from)*r+(e.to>0?i:0))}util5h(e,t){let n=this.seeds.get(e.id);return!n||!e.limits.tokens5h&&!e.limits.requests5h?0:this.curve(n.curve5h,t)}accountUsage(e,t){let n=this.seeds.get(e.id),r=this.records.filter(n=>n.accountId===e.id&&n.ts>t-J&&n.ts<=t),i=this.records.filter(n=>n.accountId===e.id&&n.ts>t-60*J),a=e=>e.reduce((e,t)=>e+t.promptTokens+t.completionTokens,0),o=e.limits,s=a(r),c={window:`1m`,tokens:s,requests:r.length,...o.tpm!==void 0&&{tokenLimit:o.tpm},...o.rpm!==void 0&&{requestLimit:o.rpm},utilization:Math.max(o.tpm?s/o.tpm:0,o.rpm?r.length/o.rpm:0)},l=(e,n,r,o,s)=>{if(!n&&!r)return{window:e,tokens:Math.round(a(i)*s),requests:Math.round(i.length*s),utilization:0};let c=o?this.curve(o,t):0;return{window:e,tokens:Math.round(c*(n??a(i)*s*2)),requests:Math.round(r?c*.92*r:i.length*s),...n!==void 0&&{tokenLimit:n},...r!==void 0&&{requestLimit:r},utilization:c}};return{accountId:e.id,windows:{"1m":c,"5h":l(`5h`,o.tokens5h,o.requests5h,n?.curve5h,3.4),"24h":l(`24h`,o.tokensDaily,o.requestsDaily,n?.curve24h,9.5)}}}checkPressure(){let e=this.clock();for(let t of this.accounts){let n=this.util5h(t,e),r=n>=Hn?2:+(n>=Y);r>(this.pressureLogged.get(t.id)??0)&&(this.pressureLogged.set(t.id,r),r===1?this.log(`info`,`router`,`Backpressure: ${t.id} at ${(n*100).toFixed(0)}% of its 5h window; weight smoothed down`):this.log(`warn`,`router`,`Quota shift: ${t.id} above 90% of its 5h window; routing to alternates`))}}startCooldown(e,t){let n=this.accounts.find(t=>t.id===e.id);if(!n||n.status===`cooldown`)return;let r=this.clock()+t*1e3;this.replaceAccount({...n,status:`cooldown`,cooldownUntil:new Date(r).toISOString(),lastError:X.rate_limit?.[1],updatedAt:new Date(this.clock()).toISOString()}),this.log(`warn`,`router`,`${e.id} cooling down for ${t}s after upstream ${t>30?429:503}`),this.later(t*1e3,()=>{let t=this.accounts.find(t=>t.id===e.id);if(t?.status!==`cooldown`)return;let{cooldownUntil:n,...r}=t;this.replaceAccount({...r,status:`active`,updatedAt:new Date(this.clock()).toISOString()}),this.log(`info`,`router`,`${e.id} back in rotation`)})}buildTimeseries(e,t){let n=Math.max(1,t)*1e3,r=this.clock(),i=Math.floor(r/n)*n,a=i-(Math.ceil(e*J/n)-1)*n,o=[];for(let e=a;e<=i;e+=n)o.push({ts:e,tokens:0,requests:0,byAccount:{}});for(let e of this.records){if(e.ts<a||e.ts>r||e.status!==`success`)continue;let t=o[Math.floor((e.ts-a)/n)];if(!t)continue;let i=e.promptTokens+e.completionTokens;t.tokens+=i,t.requests+=1;let s=t.byAccount[e.accountId]??{tokens:0,requests:0};s.tokens+=i,s.requests+=1,t.byAccount[e.accountId]=s}return o}assertGoals(){if(!this.opts.runnerAvailable)throw new B(501,`goals_unavailable`,`Goal mode is not available; start the gateway inside a project (davecode init)`)}assertRunner(){if(!this.opts.runnerAvailable)throw new B(501,`runner_unavailable`,`The autonomous runner is not available in this gateway (started with --no-runner).`)}setRunner(e){this.runnerStatus=e,this.emit({type:`runner.status`,status:e})}runnerLog(e,t,n){let r=this.runnerStatus.taskId,i={type:`runner.log`,level:e,message:t,...r&&{taskId:r},ts:n??this.clock()};n===void 0?this.emit(i):this.buffer.push(i)}haltRunner(){this.runnerTimer&&clearTimeout(this.runnerTimer),this.runnerTimer=void 0,this.runnerPending&&this.runnerQueue.unshift(this.runnerPending),this.runnerPending=void 0}pumpRunner(){if(this.runnerTimer||!this.running)return;let e=this.runnerQueue.shift();e&&(this.runnerPending=e,this.runnerTimer=setTimeout(()=>{this.runnerTimer=void 0,this.runnerPending=void 0,e.run(),this.pumpRunner()},e.delay))}q(e,t){this.runnerQueue.push({delay:e,run:t})}commitTask(e){let t={...e,updatedAt:new Date(this.clock()).toISOString()};this.taskList=this.taskList.map(n=>n.id===e.id?t:n),this.emit({type:`task.updated`,task:t})}nextTask(){let e=new Set(this.taskList.filter(e=>e.status===`SUCCESS`).map(e=>e.id));return this.taskList.filter(t=>t.status===`PENDING`&&t.dependsOn.every(t=>e.has(t))).sort((e,t)=>(t.priority??0)-(e.priority??0))[0]}assertRunnable(e){let t=this.taskList.find(t=>t.id===e);if(!t)throw new B(404,`task_not_found`,`unknown task "${e}"`);if(t.status!==`PENDING`)throw new B(409,`task_not_runnable`,`task "${e}" is ${t.status}; only PENDING tasks can run`);let n=t.dependsOn.filter(e=>this.taskList.find(t=>t.id===e)?.status!==`SUCCESS`);if(n.length>0)throw new B(409,`task_blocked`,`task "${e}" is blocked by unfinished dependencies: ${n.map(e=>`"${e}"`).join(`, `)}`)}enqueueSelect(e,t){this.q(e,()=>{this.setRunner({state:`selecting`,startedAt:new Date(this.clock()).toISOString()}),this.runnerLog(`info`,`Scanning TASK_GRAPH.json for unblocked tasks…`)}),this.q(1100,()=>{let e=this.taskList.find(e=>e.id===t&&e.status===`PENDING`&&e.dependsOn.every(e=>this.taskList.find(t=>t.id===e)?.status===`SUCCESS`))??this.nextTask();if(e)this.commitTask({...e,status:`IN_PROGRESS`,attempts:(e.attempts??0)+1}),this.setRunner({state:`preparing`,taskId:e.id,repairCycle:0,startedAt:new Date(this.clock()).toISOString()}),this.runnerLog(`info`,`Selected ${e.id} (priority ${e.priority??0}): ${e.title}`),this.enqueueTask(e.id,0);else{let e=this.taskList.filter(e=>e.status===`PENDING`).length;this.runnerLog(`warn`,e?`No unblocked tasks: ${e} pending task(s) wait on a FAILED dependency (p2-codex-cli).`:`Task graph complete. Nothing left to do.`),this.setRunner({state:`idle`})}})}enqueueTask(e,t){t===0&&(this.q(900,()=>this.runnerLog(`info`,`$ git switch -c davecode/task-${e} main`)),this.q(1200,()=>this.runnerLog(`debug`,`Injected brain: STATE.md (2.3 KB), ARCHITECTURE.md (4.9 KB), 4 global preferences`))),this.enqueueImplement(e,t)}enqueueImplement(e,t){let n=Gn[e]??[`src/index.ts`];this.q(1e3,()=>{this.setRunner({...this.runnerStatus,state:`implementing`,taskId:e,repairCycle:t}),this.runnerLog(`info`,`→ davecode/auto · claude-sonnet-5-5 via acc_claude_pro (${(8+this.rng()*9).toFixed(1)}K in)`)}),n.forEach((e,t)=>{this.q(1400+this.rng()*1600,()=>{t===0&&this.runnerLog(`debug`,`read ${n[n.length-1]??e}`);let r=Math.round(20+this.rng()*160),i=Math.round(this.rng()*30);this.runnerLog(`info`,`edit ${e} (+${r} −${i})`)})}),this.enqueueValidate(e,t)}enqueueValidate(e,t){let n=t<(Kn[e]??0);if(this.q(1500,()=>{this.setRunner({...this.runnerStatus,state:`validating`}),this.runnerLog(`info`,`$ pnpm lint`)}),this.q(1100,()=>this.runnerLog(`info`,`✓ lint passed (${(.6+this.rng()).toFixed(1)}s)`)),this.q(400,()=>this.runnerLog(`info`,`$ pnpm typecheck`)),this.q(2200,()=>this.runnerLog(`info`,`✓ typecheck passed (${(4+this.rng()*3).toFixed(1)}s)`)),this.q(400,()=>this.runnerLog(`info`,`$ pnpm test`)),n){if(this.q(2600,()=>{this.runnerLog(`error`,`✗ 2 failed, 211 passed (8.1s)`),this.runnerLog(`error`,` FAIL ${Gn[e]?.at(-1)??`test`} > honours Retry-After given as an HTTP-date`)}),t+1>=3){this.q(900,()=>{let t=this.taskList.find(t=>t.id===e);t&&this.commitTask({...t,status:`FAILED`,notes:`Failed after 3 repair cycles.`}),this.runnerLog(`error`,`${e} FAILED after 3 repair cycles; branch kept for review.`)}),this.enqueueSelect(2e3);return}this.q(900,()=>{this.setRunner({...this.runnerStatus,state:`repairing`,repairCycle:t+1}),this.runnerLog(`warn`,`Repair cycle ${t+1}/3: feeding 2 failing assertions and stderr back to the model`)}),this.q(1600,()=>this.runnerLog(`info`,`→ davecode/reasoning · claude-opus-5-5 via acc_anthropic_work`)),this.enqueueImplement(e,t+1)}else this.q(2800,()=>this.runnerLog(`info`,`✓ ${200+Math.round(this.rng()*40)} tests passed (8.4s)`)),this.q(900,()=>{this.setRunner({...this.runnerStatus,state:`merging`}),this.runnerLog(`info`,`$ git merge --no-ff davecode/task-${e} → main`)}),this.q(1400,()=>{let t=this.taskList.find(t=>t.id===e);t&&this.commitTask({...t,status:`SUCCESS`,notes:void 0}),this.runnerLog(`info`,`✓ ${e} merged. STATE.md updated.`)}),this.enqueueSelect(2500)}resumeInitialTask(){this.q(1500,()=>this.runnerLog(`info`,`edit packages/core/src/router/failover.ts (+34 −9)`)),this.q(2200,()=>this.runnerLog(`info`,`edit packages/core/src/router/select.test.ts (+12 −2)`)),this.enqueueValidate(`p2-router`,1)}seedRunnerHistory(){let e=e=>this.t0-e*J;for(let[t,n,r]of[[4.3,`info`,`Scanning TASK_GRAPH.json for unblocked tasks…`],[4.25,`info`,`Selected p2-router (priority 80): Router with balancing, backpressure, cooldowns and hot failover`],[4.2,`info`,`$ git switch -c davecode/task-p2-router main`],[4.15,`debug`,`Injected brain: STATE.md (2.3 KB), ARCHITECTURE.md (4.9 KB), 4 global preferences`],[4.1,`info`,`→ davecode/auto · claude-sonnet-5-5 via acc_claude_pro (14.2K in)`],[3.9,`info`,`edit packages/core/src/router/select.ts (+142 −8)`],[3.7,`info`,`edit packages/core/src/router/failover.ts (+96 −0)`],[3.5,`info`,`edit packages/core/src/router/circuit-breaker.ts (+61 −0)`],[3.3,`info`,`edit packages/core/src/router/select.test.ts (+188 −0)`],[3.1,`info`,`$ pnpm lint`],[3.05,`info`,`✓ lint passed (1.1s)`],[3,`info`,`$ pnpm typecheck`],[2.9,`info`,`✓ typecheck passed (5.8s)`],[2.85,`info`,`$ pnpm test`],[2.7,`error`,`✗ 2 failed, 209 passed (8.3s)`],[2.69,`error`,` FAIL packages/core/src/router/select.test.ts > honours Retry-After given as an HTTP-date`],[2.6,`warn`,`Repair cycle 1/3: feeding 2 failing assertions and stderr back to the model`],[2.5,`info`,`→ davecode/reasoning · claude-opus-5-5 via acc_anthropic_work`],[2,`info`,`edit packages/core/src/router/failover.ts (+21 −6)`]])this.buffer.push({type:`runner.log`,level:n,message:r,taskId:`p2-router`,ts:e(t)});this.buffer.push({type:`runner.status`,status:{...this.runnerStatus},ts:e(2.4)}),this.buffer.push({type:`log`,level:`info`,scope:`gateway`,message:`Listening on http://127.0.0.1:4040 (dashboard at /)`,ts:e(5.5)}),this.buffer.sort((e,t)=>e.ts-t.ts)}emit(e){let t={...e,ts:e.ts??this.clock()};this.buffer.push(t),this.buffer.length>800&&this.buffer.splice(0,this.buffer.length-800);for(let e of this.subscribers)e.onEvent(t)}log(e,t,n){this.emit({type:`log`,level:e,scope:t,message:n})}nextId(e){this.seq+=1;let t=()=>Math.floor(this.rng()*16777215).toString(16).padStart(6,`0`);return`${e}_${t()}${t()}${this.seq.toString(36)}`}modelsFor(e){let t=e.config.models;return Array.isArray(t)?t.filter(e=>typeof e==`string`):e.provider===`claude-cli`?[`claude-sonnet-5-5`,`claude-opus-5-5`]:e.provider===`gemini-web`?[`gemini-3-pro`]:[]}findAccount(e){let t=this.accounts.find(t=>t.id===e);if(!t)throw new B(404,`not_found`,`Account ${e} not found`);return t}replaceAccount(e){this.accounts=this.accounts.map(t=>t.id===e.id?e:t),this.emit({type:`account.updated`,account:e})}async respond(e){return this.opts.latency&&await new Promise(e=>setTimeout(e,90+Math.random()*220)),structuredClone(e())}},Jn;function Yn(){if(!Jn){let e=typeof window>`u`?new URLSearchParams:new URLSearchParams(window.location.search||window.location.hash.split(`?`)[1]);Jn=new qn({runnerAvailable:e.get(`runner`)!==`off`,geminiWeb:e.get(`geminiWeb`)===`1`})}return Jn}var Xn=(0,a.createContext)(null),Zn=15e3;function Qn(e){return ft()?{mode:`mock`,reason:`forced`}:e===`mock`?{mode:`mock`,reason:`setting`}:e===`live`?{mode:`live`,reason:null}:{mode:`probing`,reason:null}}function $n({children:e}){let t=dt(),n=c(),[r,i]=(0,a.useState)(()=>Qn(t.dataMode)),[s,l]=(0,a.useState)(),[u,d]=(0,a.useState)(0),[f,p]=(0,a.useState)({state:`connecting`,attempt:0}),[m,h]=(0,a.useState)(!1);(0,a.useEffect)(()=>{i(Qn(t.dataMode))},[t.dataMode]);let g=(0,a.useMemo)(()=>St({baseUrl:t.gatewayUrl,token:t.token}),[t.gatewayUrl,t.token]);(0,a.useEffect)(()=>{if(ft()||t.dataMode!==`auto`)return;let e=!1,n,r=async()=>{try{if(await g.health(),e)return;h(!1),l(void 0),i({mode:`live`,reason:null})}catch(t){if(e)return;if(bt(t)&&t.reachable){h(t.status===401),i({mode:`live`,reason:null});return}l(t instanceof Error?t.message:String(t)),i({mode:`mock`,reason:`unreachable`}),n=window.setTimeout(r,Zn)}};return r(),()=>{e=!0,window.clearTimeout(n)}},[g,t.dataMode,u]);let _=r.mode===`mock`?Yn():g,v=r.mode===`mock`?`mock`:`live:${t.gatewayUrl}:${t.token?`auth`:`anon`}`,y=(0,a.useMemo)(()=>new Vt,[v]);(0,a.useEffect)(()=>{if(r.mode===`probing`)return;p({state:r.mode===`mock`?`mock`:`connecting`,attempt:0});let e=_.subscribe({onEvent:e=>{y.ingest(e)&&nr(n,v,e)},onStatus:e=>p(e)});return _.requests(200).then(e=>y.seedRecords(e)).catch(()=>{}),_.logs(500).then(e=>{for(let t of e)y.ingest(t)}).catch(()=>{}),()=>{e(),y.dispose()}},[_,y,n,v,r.mode]);let b=(0,a.useMemo)(()=>({client:_,sourceKey:v,live:y,connection:{mode:r.mode,reason:r.reason,stream:f,probeError:s,unauthorized:m},retry:()=>{d(e=>e+1),n.invalidateQueries()}}),[_,v,y,r,f,s,m,n]);return(0,o.jsx)(Xn.Provider,{value:b,children:e})}function Z(){let e=(0,a.useContext)(Xn);if(!e)throw Error(`useData must be used inside <DataProvider>`);return e}function er(){let{live:e}=Z();return(0,a.useSyncExternalStore)(e.subscribe,e.getState,e.getState)}function Q(e,...t){return[`dc`,e,...t]}function tr(e,t){if(!e)return[t];let n=e.findIndex(e=>e.id===t.id);if(n===-1)return[t,...e];let r=e.slice();return r[n]=t,r}function nr(e,t,n){switch(n.type){case`account.updated`:e.setQueryData(Q(t,`accounts`),e=>{if(!e)return e;let t=e.findIndex(e=>e.id===n.account.id);if(t===-1)return[...e,n.account];let r=e.slice();return r[t]=n.account,r});break;case`account.removed`:e.setQueryData(Q(t,`accounts`),e=>e?.filter(e=>e.id!==n.accountId)),e.setQueryData(Q(t,`usage`),e=>e?.filter(e=>e.accountId!==n.accountId));break;case`quota.updated`:e.setQueryData(Q(t,`usage`),e=>{if(!e)return e;let t=e.findIndex(e=>e.accountId===n.usage.accountId);if(t===-1)return[...e,n.usage];let r=e.slice();return r[t]=n.usage,r});break;case`task.updated`:e.setQueryData(Q(t,`tasks`),e=>{if(!e)return e;let t=e.graph.tasks.slice(),r=t.findIndex(e=>e.id===n.task.id);return r===-1?t.push(n.task):t[r]=n.task,{...e,graph:{...e.graph,tasks:t}}});break;case`task.removed`:e.setQueryData(Q(t,`tasks`),e=>e&&{...e,graph:{...e.graph,tasks:e.graph.tasks.filter(e=>e.id!==n.taskId)}});break;case`runner.status`:e.setQueryData(Q(t,`runner`),n.status);break;case`goal.updated`:e.setQueryData(Q(t,`goals`),e=>e&&tr(e,n.goal))}}function rr(){let{client:e,sourceKey:t}=Z();return M({queryKey:Q(t,`health`),queryFn:()=>e.health(),refetchInterval:3e4})}function ir(){let{client:e,sourceKey:t}=Z();return M({queryKey:Q(t,`accounts`),queryFn:()=>e.listAccounts(),refetchInterval:6e4})}function ar(){let{client:e,sourceKey:t}=Z();return M({queryKey:Q(t,`usage`),queryFn:()=>e.usage(),refetchInterval:3e4})}function or(){let{client:e,sourceKey:t}=Z();return M({queryKey:Q(t,`budget`),queryFn:()=>e.budget(),refetchInterval:3e4})}function sr(e,t=!1){let{client:n,sourceKey:r}=Z();return M({queryKey:Q(r,`connection`,e),queryFn:()=>n.connection(e),refetchInterval:t?3e3:!1,staleTime:15e3})}function cr(){let{client:e,sourceKey:t}=Z(),n=c();return N({mutationFn:t=>e.connect(t),onSuccess:(e,r)=>n.setQueryData(Q(t,`connection`,r),e.connection)})}function lr(e=60,t=60){let{client:n,sourceKey:r}=Z();return M({queryKey:Q(r,`timeseries`,e,t),queryFn:()=>n.timeseries(e,t),refetchInterval:6e4})}function ur(){let{client:e,sourceKey:t}=Z();return M({queryKey:Q(t,`routes`),queryFn:()=>e.routes()})}function dr(){let{client:e,sourceKey:t}=Z();return M({queryKey:Q(t,`models`),queryFn:()=>e.models()})}function fr(){let{client:e,sourceKey:t}=Z();return M({queryKey:Q(t,`tasks`),queryFn:()=>e.tasks(),refetchInterval:6e4})}function pr(){let{client:e,sourceKey:t}=Z();return M({queryKey:Q(t,`brain`),queryFn:()=>e.brain(),refetchInterval:6e4})}function mr(){let{client:e,sourceKey:t}=Z();return M({queryKey:Q(t,`runner`),queryFn:()=>e.runner(),refetchInterval:15e3,retry:(e,t)=>t.status!==501&&e<2})}function hr(){let{sourceKey:e}=Z(),t=c(),n=Q(e,`accounts`);return{upsert:e=>t.setQueryData(n,t=>{if(!t)return[e];let n=t.findIndex(t=>t.id===e.id);if(n===-1)return[...t,e];let r=t.slice();return r[n]=e,r}),remove:e=>t.setQueryData(n,t=>t?.filter(t=>t.id!==e)),invalidate:()=>{t.invalidateQueries({queryKey:n}),t.invalidateQueries({queryKey:Q(e,`usage`)}),t.invalidateQueries({queryKey:Q(e,`budget`)})}}}function gr(){let{client:e}=Z(),t=hr();return N({mutationFn:t=>e.createAccount(t),onSuccess:e=>t.upsert(e),onSettled:()=>t.invalidate()})}function _r(){let{client:e,sourceKey:t}=Z(),n=c(),r=hr();return N({mutationFn:({id:t,patch:n})=>e.updateAccount(t,n),onMutate:async({id:e,patch:r})=>{let i=Q(t,`accounts`);await n.cancelQueries({queryKey:i});let a=n.getQueryData(i);return a&&r.enabled!==void 0&&n.setQueryData(i,a.map(t=>t.id===e?{...t,enabled:r.enabled,status:r.enabled?`active`:`disabled`}:t)),{prev:a}},onError:(e,r,i)=>{i?.prev&&n.setQueryData(Q(t,`accounts`),i.prev)},onSuccess:e=>r.upsert(e),onSettled:()=>n.invalidateQueries({queryKey:Q(t,`budget`)})})}function vr(){let{client:e}=Z(),t=hr();return N({mutationFn:t=>e.deleteAccount(t),onSuccess:(e,n)=>t.remove(n),onSettled:()=>t.invalidate()})}function yr(){let{sourceKey:e}=Z(),t=c(),n=Q(e,`tasks`);return{upsert:e=>t.setQueryData(n,t=>{if(!t)return t;let n=t.graph.tasks.slice(),r=n.findIndex(t=>t.id===e.id);return r===-1?n.push(e):n[r]=e,{...t,graph:{...t.graph,tasks:n}}}),remove:e=>t.setQueryData(n,t=>t&&{...t,graph:{...t.graph,tasks:t.graph.tasks.filter(t=>t.id!==e)}}),invalidate:()=>{t.invalidateQueries({queryKey:n}),t.invalidateQueries({queryKey:Q(e,`brain`)})}}}function br(){let{client:e}=Z(),t=yr();return N({mutationFn:t=>e.createTask(t),onSuccess:e=>t.upsert(e),onSettled:()=>t.invalidate()})}function xr(){let{client:e}=Z(),t=yr();return N({mutationFn:({id:t,patch:n})=>e.updateTask(t,n),onSuccess:e=>t.upsert(e),onSettled:()=>t.invalidate()})}function Sr(){let{client:e}=Z(),t=yr();return N({mutationFn:t=>e.deleteTask(t),onSuccess:(e,n)=>t.remove(n),onSettled:()=>t.invalidate()})}function Cr(){let{client:e,sourceKey:t}=Z(),n=c();return N({mutationFn:t=>e.updateRoutes(t),onSuccess:({defaultRoute:e,routes:r})=>{n.setQueryData(Q(t,`routes`),{defaultRoute:e,routes:r}),n.invalidateQueries({queryKey:Q(t,`models`)})}})}function wr(){let{client:e,sourceKey:t}=Z(),n=c();return N({mutationFn:t=>e.runnerAction(t),onSuccess:e=>n.setQueryData(Q(t,`runner`),e)})}function Tr(){let{client:e,sourceKey:t}=Z();return M({queryKey:Q(t,`goals`),queryFn:()=>e.goals(),refetchInterval:6e4,retry:(e,t)=>t.status!==501&&e<2})}function Er(){let{sourceKey:e}=Z(),t=c();return n=>t.setQueryData(Q(e,`goals`),e=>tr(e,n))}function Dr(){let{client:e}=Z(),t=Er();return N({mutationFn:t=>e.startGoal(t),onSuccess:e=>t(e)})}function Or(){let{client:e}=Z(),t=Er();return N({mutationFn:t=>e.executeGoal(t),onSuccess:e=>t(e)})}function kr(e,t){let{client:n,sourceKey:r}=Z();return M({queryKey:Q(r,`goal-artifact`,e??``,t??``),queryFn:()=>n.goalArtifact(e,t),enabled:!!(e&&t),staleTime:6e4})}function Ar(){let{client:e}=Z(),t=Er();return N({mutationFn:t=>e.cancelGoal(t),onSuccess:e=>t(e)})}function jr(){let{client:e,sourceKey:t}=Z(),n=c();return N({mutationFn:t=>e.runnerAction(`start`,{taskId:t}),onSuccess:e=>n.setQueryData(Q(t,`runner`),e)})}var Mr=new Intl.NumberFormat(`en`,{notation:`compact`,maximumFractionDigits:1}),Nr=new Intl.NumberFormat(`en`);function Pr(e){return Number.isFinite(e)?Mr.format(e):`—`}function Fr(e){return Number.isFinite(e)?Nr.format(Math.round(e)):`—`}function Ir(e,t=0){return Number.isFinite(e)?`${(e*100).toFixed(t)}%`:`—`}function Lr(e){return Number.isFinite(e)?e<1e3?`${Math.round(e)} ms`:`${(e/1e3).toFixed(e<1e4?2:1)} s`:`—`}function Rr(e){let t=Math.max(0,Math.floor(e));if(t<60)return`${t}s`;let n=Math.floor(t/60);if(n<60)return`${n}m ${String(t%60).padStart(2,`0`)}s`;let r=Math.floor(n/60);return r<24?`${r}h ${String(n%60).padStart(2,`0`)}m`:`${Math.floor(r/24)}d ${r%24}h`}function zr(e){let t=Math.max(0,Math.ceil(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,`0`)}`}function Br(e,t=!1){let n=new Date(e),r=`${$(n.getHours())}:${$(n.getMinutes())}:${$(n.getSeconds())}`;return t?`${r}.${String(n.getMilliseconds()).padStart(3,`0`)}`:r}function Vr(e){let t=new Date(e);return`${$(t.getHours())}:${$(t.getMinutes())}`}function Hr(e,t=Date.now()){let n=Math.round((t-e)/1e3);return n<5?`just now`:n<60?`${n}s ago`:n<3600?`${Math.floor(n/60)}m ago`:n<86400?`${Math.floor(n/3600)}h ago`:new Date(e).toLocaleDateString()}function $(e){return String(e).padStart(2,`0`)}function Ur(e,t=8){return(e.includes(`_`)?e.slice(e.indexOf(`_`)+1):e).slice(0,t)}var Wr={neutral:`bg-hover text-fg-2 border-line-strong`,accent:`bg-accent-soft text-accent-text border-accent/25`,ok:`bg-ok-soft text-ok border-ok/25`,warn:`bg-warn-soft text-warn border-warn/25`,err:`bg-err-soft text-err border-err/25`,info:`bg-info-soft text-info border-info/25`},Gr={neutral:`bg-muted`,accent:`bg-accent`,ok:`bg-ok`,warn:`bg-warn`,err:`bg-err`,info:`bg-info`};function Kr({tone:e=`neutral`,dot:t,pulse:n,mono:r,className:a,children:s}){return(0,o.jsxs)(`span`,{className:i(`inline-flex h-5 shrink-0 items-center gap-1.5 rounded border px-1.5 text-2xs font-medium whitespace-nowrap`,r&&`font-mono`,Wr[e],a),children:[t&&(0,o.jsx)(qr,{tone:e,pulse:n}),s]})}function qr({tone:e=`neutral`,pulse:t,className:n}){return(0,o.jsx)(`span`,{"aria-hidden":!0,className:i(`inline-block size-1.5 shrink-0 rounded-full`,Gr[e],t&&`animate-pulse-dot`,t&&Jr[e],n)})}var Jr={neutral:`text-muted/60`,accent:`text-accent/60`,ok:`text-ok/60`,warn:`text-warn/60`,err:`text-err/60`,info:`text-info/60`};export{yn as $,mr as A,b as At,Z as B,Or as C,he as Ct,dr as D,h as Dt,rr as E,O as Et,_r as F,D as Ft,Pn as G,Rn as H,Cr as I,l as It,En as J,Vn as K,xr as L,c as Lt,Dr as M,m as Mt,fr as N,C as Nt,ur as O,S as Ot,lr as P,v as Pt,Sn as Q,ar as R,Sr as S,we as St,Tr as T,fe as Tt,Mn as U,er as V,Fn as W,Dn as X,An as Y,Ln as Z,cr as _,pt as _t,zr as a,xn as at,br as b,M as bt,Fr as c,Nt as ct,Hr as d,St as dt,gn as et,Ur as f,Ct as ft,Ar as g,ft as gt,or as h,z as ht,Pr as i,vn as it,wr as j,y as jt,jr as k,x as kt,Lr as l,Mt as lt,pr as m,mt,qr as n,bn as nt,Rr as o,Zt as ot,ir as p,bt as pt,Bn as q,Br as r,_n as rt,Vr as s,Qt as st,Kr as t,hn as tt,Ir as u,Pt as ut,sr as v,lt as vt,kr as w,k as wt,vr as x,Me as xt,gr as y,dt as yt,$n as z};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e,r as t,t as n}from"./cn-BwE4cei0.js";import{M as r,W as i}from"./index-BDBa5cb0.js";var a={name:`octagon-alert`,size:24,node:[[`path`,{d:`M12 16h.01`,key:`1drbdi`}],[`path`,{d:`M12 8v4`,key:`1got3b`}],[`path`,{d:`M15.312 2a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586l-4.688-4.688A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2z`,key:`1fd625`}]],aliases:[`alert-octagon`]};a.node;var o=e(a),s=t(),c={info:{box:`border-info/25 bg-info-soft [&_svg]:text-info`,icon:i},warn:{box:`border-warn/30 bg-warn-soft [&_svg]:text-warn`,icon:r},err:{box:`border-err/30 bg-err-soft [&_svg]:text-err`,icon:o}};function l({tone:e=`info`,title:t,children:r,action:i,className:a}){let{box:o,icon:l}=c[e];return(0,s.jsxs)(`div`,{role:e===`info`?`note`:`alert`,className:n(`flex gap-2.5 rounded-md border px-3 py-2.5 text-[12px] leading-5`,o,a),children:[(0,s.jsx)(l,{"aria-hidden":!0,className:`mt-0.5 size-3.5 shrink-0`,strokeWidth:1.75}),(0,s.jsxs)(`div`,{className:`min-w-0 flex-1 text-fg-2`,children:[t&&(0,s.jsx)(`p`,{className:`font-medium text-fg`,children:t}),r]}),i&&(0,s.jsx)(`div`,{className:`shrink-0 self-center`,children:i})]})}export{l as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{i as e,o as t,r as n,t as r}from"./cn-BwE4cei0.js";var i=t(e(),1),a=n(),o=`h-8 w-full min-w-0 rounded-md border border-line-strong bg-bg px-2.5 text-[13px] text-fg placeholder:text-faint transition-[border-color,box-shadow] duration-150 ease-snappy hover:border-faint/70 focus-visible:border-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/25 disabled:opacity-50 aria-invalid:border-err`,s=(0,i.forwardRef)(function({className:e,...t},n){return(0,a.jsx)(`input`,{ref:n,className:r(o,e),...t})}),c=(0,i.forwardRef)(function({className:e,rows:t=3,...n},i){return(0,a.jsx)(`textarea`,{ref:i,rows:t,className:r(o,`h-auto min-h-16 resize-y py-1.5 leading-5`,e),...n})}),l=(0,i.forwardRef)(function({className:e,children:t,...n},i){return(0,a.jsx)(`select`,{ref:i,className:r(o,`cursor-pointer pr-7`,e),...n,children:t})});function u({label:e,hint:t,error:n,required:o,className:s,children:c}){let l=(0,i.useId)(),u=`${l}-hint`,d=`${l}-error`,f=[t?u:null,n?d:null].filter(Boolean).join(` `);return(0,a.jsxs)(`div`,{className:r(`flex flex-col gap-1.5`,s),children:[(0,a.jsxs)(`label`,{htmlFor:l,className:`text-[12px] font-medium text-fg-2`,children:[e,o&&(0,a.jsx)(`span`,{"aria-hidden":!0,className:`ml-0.5 text-accent-text`,children:`*`})]}),c({id:l,describedBy:f||void 0,invalid:!!n}),t&&!n&&(0,a.jsx)(`p`,{id:u,className:`text-[12px] leading-4 text-muted`,children:t}),n&&(0,a.jsx)(`p`,{id:d,role:`alert`,className:`text-[12px] leading-4 text-err`,children:n})]})}export{c as i,s as n,l as r,u as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{i as e,n as t,o as n,r,t as i}from"./cn-BwE4cei0.js";import{C as a,M as o,T as s,V as c,d as l,ft as u,g as d,i as f,pt as p,r as m,t as h,w as g}from"./Badge-Z4RBdO9j.js";import{n as _,t as v}from"./Switch-DPYlLseH.js";import{n as y,t as b}from"./Markdown-DCZ4Awcc.js";import{t as x}from"./Callout-w8BTYh4k.js";import{B as S,C,F as w,N as T,d as E,i as D,m as O,n as k,p as A,r as j,s as M,u as N,w as P,y as F}from"./index-BDBa5cb0.js";import{i as I,n as L,t as R}from"./Field-Cmpgg_1z.js";var z={name:`chevron-down`,size:24,node:[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]};z.node;var B=t(z),V={name:`shield-check`,size:24,node:[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`,key:`oel41y`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]};V.node;var H=t(V),U=n(e(),1),W=r(),G={planning:`info`,running:`info`,reviewing:`info`,planned:`accent`,succeeded:`ok`,failed:`err`,cancelled:`neutral`,budget_exhausted:`warn`},K={planning:`planning`,running:`running`,reviewing:`reviewing`,planned:`planned (dry run)`,succeeded:`succeeded`,failed:`failed`,cancelled:`cancelled`,budget_exhausted:`out of budget`},q=new Set([`planning`,`running`,`reviewing`]);function J(e){return q.has(e.status)}function Y(e){let t=Number(e);return e.trim()&&Number.isInteger(t)&&t>0?t:void 0}function X(){let e=s(),[t,n]=(0,U.useState)(),r=p(e.error)&&e.error.status===501,a=e.data??[],o=a.find(e=>e.id===t)??a[0],c=a.find(J);return(0,W.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,W.jsx)(k,{title:`Goals`,description:`Give the agent team an objective: a planner splits it into tasks, role agents execute them, a reviewer re-plans until it is done or the budget runs out.`}),r?(0,W.jsxs)(x,{tone:`warn`,title:`Goal mode unavailable`,children:[(0,W.jsxs)(`p`,{children:[`This gateway answered `,(0,W.jsx)(`code`,{className:`font-mono text-fg`,children:`501 goals_unavailable`}),`: it was started outside a project. Start it inside a repository with a project brain, or run a goal from the terminal:`]}),(0,W.jsx)(A,{command:`davecode goal "<objective>"`,className:`mt-2 max-w-sm`})]}):(0,W.jsx)(Z,{busy:c?.id,onStarted:e=>n(e.id)}),e.isError&&!r&&(0,W.jsx)(x,{tone:`err`,title:`Could not load goals`,children:u(e.error)}),!r&&(0,W.jsxs)(`div`,{className:`grid grid-cols-1 gap-4 xl:grid-cols-[320px_minmax(0,1fr)]`,children:[(0,W.jsxs)(j,{"aria-labelledby":`goal-list-title`,className:`xl:self-start`,children:[(0,W.jsx)(D,{id:`goal-list-title`,title:`History`,meta:a.length?`${a.length} goal${a.length===1?``:`s`}`:void 0}),e.isPending?(0,W.jsx)(N,{rows:4,className:`p-3`}):a.length===0?(0,W.jsx)(M,{icon:T,title:`No goals yet`,description:`Describe an objective above, or try a dry run to see the plan first.`}):(0,W.jsx)(`ul`,{className:`flex flex-col p-1.5`,"aria-label":`Goals`,children:a.map(e=>{let t=e.tasks.filter(e=>e.status===`SUCCESS`).length,r=e.id===o?.id;return(0,W.jsx)(`li`,{children:(0,W.jsxs)(`button`,{type:`button`,"aria-current":r?`true`:void 0,onClick:()=>n(e.id),className:i(`flex w-full flex-col gap-1 rounded-md px-2.5 py-2 text-left transition-colors duration-150`,r?`bg-hover`:`hover:bg-hover/60`),children:[(0,W.jsx)(`span`,{className:`line-clamp-2 text-[13px] leading-5 text-fg`,children:e.objective}),(0,W.jsxs)(`span`,{className:`flex items-center gap-2 text-2xs text-muted`,children:[(0,W.jsx)(h,{tone:G[e.status],dot:!0,pulse:J(e),children:K[e.status]}),(0,W.jsxs)(`span`,{className:`tnum`,children:[t,`/`,e.tasks.length,` tasks`]}),(0,W.jsx)(`span`,{className:`ml-auto`,children:l(Date.parse(e.createdAt))})]})]})},e.id)})})]}),o?(0,W.jsx)($,{goal:o}):null]})]})}function Z({busy:e,onStarted:t}){let n=o(),[r,i]=(0,U.useState)(``),[a,s]=(0,U.useState)(``),[c,l]=(0,U.useState)(``),[d,f]=(0,U.useState)(``),[m,h]=(0,U.useState)(!1),[g,_]=(0,U.useState)(null);return(0,W.jsxs)(j,{"aria-labelledby":`new-goal-title`,children:[(0,W.jsx)(D,{id:`new-goal-title`,title:`New goal`,meta:(0,W.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[(0,W.jsx)(H,{"aria-hidden":!0,className:`size-3.5 text-ok`,strokeWidth:1.75}),`Never emails, posts, pays or signs up: those become drafts`]})}),(0,W.jsxs)(`form`,{onSubmit:e=>{if(e.preventDefault(),!r.trim()){_(`Describe what the team should achieve.`);return}_(null);let o={objective:r.trim()},s=Y(a),l=Y(c),f=Y(d);s&&(o.maxRounds=s),l&&(o.maxTasks=l),f&&(o.maxTokens=f),m&&(o.dryRun=!0),n.mutate(o,{onSuccess:e=>{C({tone:`info`,title:m?`Planning (dry run)`:`Goal started`,description:e.objective}),i(``),t(e)},onError:e=>C({tone:`err`,title:`Could not start the goal`,description:p(e)&&e.code===`busy`?`${e.message}. Goals and the runner take turns on the working tree.`:u(e)})})},className:`flex flex-col gap-3 p-4`,children:[(0,W.jsx)(R,{label:`Objective`,required:!0,error:g,children:({id:e,describedBy:t,invalid:n})=>(0,W.jsx)(I,{id:e,"aria-describedby":t,"aria-invalid":n,rows:2,maxLength:4e3,placeholder:`e.g. Write positioning and landing-page copy for this project, then add a /pricing page`,value:r,onChange:e=>i(e.target.value)})}),(0,W.jsxs)(`div`,{className:`flex flex-wrap items-end gap-3`,children:[(0,W.jsx)(R,{label:`Max rounds`,className:`w-28`,children:({id:e})=>(0,W.jsx)(L,{id:e,inputMode:`numeric`,placeholder:`4`,value:a,onChange:e=>s(e.target.value)})}),(0,W.jsx)(R,{label:`Max tasks`,className:`w-28`,children:({id:e})=>(0,W.jsx)(L,{id:e,inputMode:`numeric`,placeholder:`12`,value:c,onChange:e=>l(e.target.value)})}),(0,W.jsx)(R,{label:`Token budget`,className:`w-36`,children:({id:e})=>(0,W.jsx)(L,{id:e,inputMode:`numeric`,placeholder:`1000000`,value:d,onChange:e=>f(e.target.value)})}),(0,W.jsxs)(`span`,{className:`flex h-8 items-center gap-2 text-[12px] text-fg-2`,children:[(0,W.jsx)(v,{checked:m,onChange:h,label:`Dry run`}),`Dry run (plan only)`]}),(0,W.jsx)(P,{type:`submit`,variant:`primary`,icon:S,className:`ml-auto`,loading:n.isPending,disabled:n.isPending||!!e&&!m,title:e&&!m?`Goal ${e} is still running`:void 0,children:m?`Plan`:`Start goal`})]})]})]})}function Q({label:e,value:t,max:n,format:r=String}){let a=n>0?Math.min(100,t/n*100):0;return(0,W.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-1.5`,children:[(0,W.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2 text-[12px]`,children:[(0,W.jsx)(`span`,{className:`text-muted`,children:e}),(0,W.jsxs)(`span`,{className:`tnum font-mono text-fg`,children:[r(t),(0,W.jsxs)(`span`,{className:`text-muted`,children:[` / `,r(n)]})]})]}),(0,W.jsx)(`div`,{className:`h-1.5 overflow-hidden rounded-full bg-track`,"aria-hidden":!0,children:(0,W.jsx)(`div`,{className:i(`h-full rounded-full transition-[width] duration-500 ease-snappy`,a>=90?`bg-warn`:`bg-accent`),style:{width:`${a}%`}})})]})}function $({goal:e}){let t=d(),n=a(),r=c(),[o,s]=(0,U.useState)(!1),[l,p]=(0,U.useState)(),g=J(e),v=e.tasks.filter(e=>e.status===`SUCCESS`).length,x=r.events.filter(t=>t.type===`goal.log`&&t.goalId===e.id),T=()=>t.mutate(e.id,{onSuccess:e=>C({tone:`info`,title:`Goal ${e.status}`,description:e.objective}),onError:e=>C({tone:`err`,title:`Could not cancel`,description:u(e)})});return(0,W.jsxs)(j,{"aria-labelledby":`goal-detail-title`,className:`min-w-0`,children:[(0,W.jsx)(D,{id:`goal-detail-title`,title:(0,W.jsx)(`span`,{className:`font-mono text-2xs text-muted`,children:e.id}),meta:(0,W.jsx)(h,{tone:G[e.status],dot:!0,pulse:g,children:K[e.status]}),actions:(0,W.jsxs)(W.Fragment,{children:[e.status===`planned`&&(0,W.jsx)(P,{size:`sm`,variant:`primary`,icon:S,loading:n.isPending,onClick:()=>n.mutate(e.id,{onSuccess:e=>C({tone:`info`,title:`Executing planned goal`,description:e.objective}),onError:e=>C({tone:`err`,title:`Could not execute plan`,description:u(e)})}),children:`Execute plan`}),g&&(0,W.jsx)(P,{size:`sm`,variant:`danger`,icon:w,loading:t.isPending,onClick:()=>s(!0),children:`Cancel`})]})}),(0,W.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,W.jsx)(`p`,{className:`text-[15px] leading-6 font-medium text-fg`,children:e.objective}),(0,W.jsxs)(`div`,{className:`flex flex-wrap gap-x-6 gap-y-3`,children:[(0,W.jsx)(Q,{label:`Rounds`,value:e.round,max:e.limits.maxRounds}),(0,W.jsx)(Q,{label:`Tasks done`,value:v,max:Math.max(e.tasks.length,1)}),(0,W.jsx)(Q,{label:`Tokens`,value:e.limits.tokensUsed,max:e.limits.maxTokens,format:f})]}),e.lastError&&(0,W.jsx)(`p`,{className:`rounded-md border border-err/30 bg-err-soft p-2 font-mono text-2xs text-err`,children:e.lastError}),(0,W.jsx)(`section`,{"aria-label":`Tasks`,className:`flex flex-col`,children:e.tasks.length===0?(0,W.jsx)(`p`,{className:`text-[12px] text-muted`,children:g?`The planner is drafting the task graph…`:`No tasks were planned.`}):(0,W.jsx)(`ol`,{className:`flex flex-col divide-y divide-line rounded-md border border-line`,children:e.tasks.map(t=>(0,W.jsxs)(`li`,{className:i(`flex flex-col gap-1.5 px-3 py-2.5`,t.id===e.activeTaskId&&`bg-accent-soft/40`),children:[(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,W.jsx)(F,{status:t.status}),(0,W.jsx)(`span`,{className:`font-mono text-2xs text-muted`,children:t.id}),(0,W.jsx)(`span`,{className:`min-w-0 flex-1 text-[13px] text-fg`,children:t.title}),(0,W.jsx)(h,{mono:!0,children:t.role}),(0,W.jsx)(h,{tone:t.kind===`code`?`accent`:`neutral`,mono:!0,children:t.kind}),t.round>1&&(0,W.jsxs)(h,{mono:!0,children:[`round `,t.round]})]}),t.dependsOn.length>0&&(0,W.jsxs)(`p`,{className:`text-2xs text-muted`,children:[`after `,t.dependsOn.join(`, `)]}),t.artifact&&(0,W.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-1.5 font-mono text-2xs text-fg-2`,children:[(0,W.jsxs)(`button`,{type:`button`,onClick:()=>p(e=>e===t.id?void 0:t.id),"aria-expanded":l===t.id,className:`inline-flex items-center gap-1 rounded px-1 py-0.5 text-fg-2 transition-colors hover:bg-hover hover:text-fg`,children:[l===t.id?(0,W.jsx)(B,{"aria-hidden":!0,className:`size-3.5 text-muted`}):(0,W.jsx)(_,{"aria-hidden":!0,className:`size-3.5 text-muted`}),(0,W.jsx)(y,{"aria-hidden":!0,className:`size-3.5 text-muted`,strokeWidth:1.75}),(0,W.jsx)(`span`,{className:`truncate`,children:t.artifact})]}),(0,W.jsx)(O,{value:t.artifact,label:`Copy path`})]}),l===t.id&&(0,W.jsx)(ee,{goalId:e.id,taskId:t.id})]}),t.status===`FAILED`&&t.notes&&(0,W.jsx)(`p`,{className:`line-clamp-3 font-mono text-2xs text-err`,children:t.notes})]},t.id))})}),e.summary&&(0,W.jsx)(`section`,{"aria-label":`Summary`,className:`rounded-md border border-line bg-raised/40 p-3`,children:(0,W.jsx)(b,{source:e.summary,className:`text-[13px]`})}),(0,W.jsx)(`section`,{"aria-label":`Goal log`,className:`term max-h-64 overflow-auto rounded-md border border-line bg-term py-2 font-mono text-[12px] leading-[1.6]`,children:x.length===0?(0,W.jsx)(`p`,{className:`px-3 text-muted`,children:g?`Waiting for agent output…`:`No live log for this goal in this session.`}):x.map(e=>(0,W.jsxs)(`div`,{className:`flex gap-3 px-3`,children:[(0,W.jsx)(`span`,{className:`tnum shrink-0 text-faint select-none`,children:m(e.ts)}),(0,W.jsx)(`span`,{className:`w-20 shrink-0 truncate text-info`,children:e.role??`goal`}),(0,W.jsx)(`span`,{className:i(`min-w-0 break-words`,e.level===`error`?`text-err`:e.level===`warn`?`text-warn`:`text-fg-2`),children:e.message})]},`${e.ts}-${e.message}`))})]}),(0,W.jsx)(E,{open:o,onClose:()=>s(!1),title:`Cancel this goal?`,description:`The agent in flight is stopped. Finished artifacts and merged code stay; an interrupted code task keeps its partial work on its branch.`,footer:(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(P,{variant:`ghost`,onClick:()=>s(!1),children:`Keep going`}),(0,W.jsx)(P,{variant:`danger`,icon:w,onClick:()=>{s(!1),T()},children:`Cancel goal`})]}),children:(0,W.jsx)(`p`,{className:`text-[12px] text-muted`,children:e.objective})})]})}function ee({goalId:e,taskId:t}){let n=g(e,t);return n.isPending?(0,W.jsx)(N,{rows:3,className:`p-2`}):n.isError?(0,W.jsx)(`p`,{className:`rounded-md border border-err/30 bg-err-soft p-2 font-mono text-2xs text-err`,children:u(n.error)}):(0,W.jsxs)(`div`,{className:`rounded-md border border-line bg-raised/50 p-3`,children:[(0,W.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2 border-b border-line pb-1.5`,children:[(0,W.jsx)(`span`,{className:`font-mono text-2xs text-muted`,children:n.data.path}),(0,W.jsx)(O,{value:n.data.content,label:`Copy markdown`})]}),(0,W.jsx)(b,{source:n.data.content,className:`text-[13px]`})]})}export{$ as GoalDetail,X as Goals,J as isActiveGoal,B as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{i as e,o as t,r as n}from"./cn-BwE4cei0.js";import{D as r,I as i,X as a,Y as o,n as s,w as c}from"./index-BDBa5cb0.js";import{n as l}from"./Field-Cmpgg_1z.js";var u=t(e(),1),d=[{id:`ponytail`,name:`Ponytail`,kind:`Guidance`,url:`https://github.com/DietrichGebert/ponytail`,description:`Reuse what exists and keep implementations small. Useful for avoiding unnecessary code; it does not supply an art direction.`,access:`Repository; review license before reuse`},{id:`anti-slop`,name:`Anti Slop`,kind:`Guidance`,url:`https://github.com/miqdadbadjuber/anti-slop`,description:`Review recurring generic patterns in interface design, copy and generated code.`,access:`Repository; review license before reuse`},{id:`impeccable`,name:`Impeccable`,kind:`Guidance`,url:`https://github.com/pbakaus/impeccable`,description:`Design guidance for defining a product direction and refining the finished interface.`,access:`Repository; review license before reuse`},{id:`anti-ui-slop`,name:`Anti UI Slop`,kind:`Guidance`,url:`https://github.com/tuanphung2005/anti-ui-slop`,description:`A separate UI-focused ruleset. Compare its constraints with your brief rather than combining conflicting rules.`,access:`Repository; review license before reuse`},{id:`shadcn`,name:`shadcn/ui`,kind:`Components`,url:`https://github.com/shadcn-ui/ui`,description:`Own and adapt the component source. Start from accessible building blocks and make them fit your identity.`,access:`MIT component library`},{id:`radix`,name:`Radix Primitives`,kind:`Components`,url:`https://github.com/radix-ui/primitives`,description:`Accessible interaction primitives for dialogs, menus and other complex interface behaviors.`,access:`MIT component library`},{id:`motion`,name:`Motion`,kind:`Components`,url:`https://github.com/motiondivision/motion`,description:`Animation for React and JavaScript. Use motion to explain a change, with a reduced-motion alternative.`,access:`MIT library; optional paid products are separate`},{id:`r3f`,name:`React Three Fiber`,kind:`Components`,url:`https://github.com/pmndrs/react-three-fiber`,description:`A React renderer for Three.js. Consider it when a real 3D experience serves the idea.`,access:`MIT library; assets have their own licenses`},{id:`awwwards`,name:`Awwwards`,kind:`Inspiration`,url:`https://www.awwwards.com/`,description:`Explore expressive websites and the studios behind them. Study composition and interaction, then create your own interpretation.`,access:`Reference gallery; artwork is not licensed for copying`},{id:`siteinspire`,name:`Siteinspire`,kind:`Inspiration`,url:`https://www.siteinspire.com/`,description:`Find references by style, type and subject instead of starting from the same SaaS template.`,access:`Reference gallery; artwork is not licensed for copying`},{id:`freight`,name:`Studio Freight`,kind:`Inspiration`,url:`https://studiofreight.com/`,description:`A studio reference for thoughtful digital identity and web experiences.`,access:`Studio portfolio; reference only`},{id:`hf`,name:`Hugging Face Spaces`,kind:`AI tools`,url:`https://huggingface.co/spaces`,description:`Discover interactive AI demos. Check each Space, model license and compute requirements before using it in your project.`,access:`Availability, model licenses and costs vary`}];function f(e){return`Help me create a distinctive interface for this project. Use ${e.name} (${e.url}) as a reference if you can access it. Its purpose: ${e.description}\n\nFirst identify the audience, intended outcome and existing design system. Propose a specific visual direction and a short design brief: typography, palette, composition, imagery, interaction and mobile behavior. Preserve the project stack, cover loading/empty/error states, and verify the rendered result. Use references as inspiration and respect their licenses. Do not claim to have read, installed or connected a resource without checking. Explain any external dependency before adding it.`}var p=n(),m=[`All`,`Guidance`,`Components`,`Inspiration`,`AI tools`];function h(){let[e,t]=(0,u.useState)(`All`),[n,h]=(0,u.useState)(``),g=d.filter(t=>(e===`All`||t.kind===e)&&`${t.name} ${t.description}`.toLowerCase().includes(n.toLowerCase()));return(0,p.jsxs)(`div`,{className:`flex flex-col gap-6`,children:[(0,p.jsx)(s,{title:`Creative library`,description:`Find a direction before you build. A curated starting point for people with ideas, with guidance, components and real design references.`}),(0,p.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,p.jsx)(`fieldset`,{className:`flex flex-wrap gap-1`,"aria-label":`Resource category`,children:m.map(n=>(0,p.jsx)(c,{variant:n===e?`primary`:`ghost`,onClick:()=>t(n),"aria-pressed":n===e,children:n},n))}),(0,p.jsxs)(`label`,{htmlFor:`creative-search`,className:`relative ml-auto w-full max-w-xs`,children:[(0,p.jsx)(`span`,{className:`sr-only`,children:`Find a creative resource`}),(0,p.jsx)(i,{"aria-hidden":!0,className:`absolute top-2.5 left-2.5 size-3.5 text-muted`}),(0,p.jsx)(l,{id:`creative-search`,value:n,onChange:e=>h(e.target.value),placeholder:`Find a resource…`,className:`pl-8`})]})]}),(0,p.jsx)(`div`,{className:`grid gap-x-8 md:grid-cols-2 xl:grid-cols-3`,children:g.map(e=>(0,p.jsxs)(`article`,{className:`flex flex-col items-start border-t border-line py-6`,children:[(0,p.jsx)(`p`,{className:`text-[12px] text-accent-text`,children:e.kind}),(0,p.jsx)(`h2`,{className:`mt-3 text-[21px] font-medium tracking-tight text-fg`,children:e.name}),(0,p.jsx)(`p`,{className:`mt-3 max-w-sm flex-1 text-[13px] leading-6 text-muted`,children:e.description}),(0,p.jsx)(`p`,{className:`mt-4 text-[11px] leading-5 text-muted`,children:e.access}),(0,p.jsxs)(`div`,{className:`mt-4 flex flex-wrap items-center gap-4`,children:[(0,p.jsx)(c,{size:`sm`,onClick:()=>r(`/?brief=${encodeURIComponent(f(e))}`),children:`Use in a goal`}),(0,p.jsxs)(`a`,{href:e.url,target:`_blank`,rel:`noreferrer`,className:`inline-flex items-center gap-1 text-[12px] text-fg-2 hover:text-fg`,children:[`Visit source`,(0,p.jsx)(a,{"aria-hidden":!0,className:`size-3`})]})]})]},e.id))}),g.length===0&&(0,p.jsx)(`p`,{role:`status`,className:`py-8 text-[13px] text-muted`,children:`No resources match. Try another name or category.`}),(0,p.jsxs)(`div`,{className:`flex gap-3 border-t border-line pt-5 text-[12px] leading-6 text-muted`,children:[(0,p.jsx)(o,{"aria-hidden":!0,className:`mt-1 size-4 shrink-0`}),(0,p.jsx)(`p`,{children:`These are curated references, not installed plugins. “Use in a goal” prepares a brief for your agent; it does not run code, fetch a site or connect an account. DaveCode includes its own design-quality guidance by default. Third-party resources keep their own licenses and access requirements.`})]})]})}export{h as Library};
|