@dmrlzz/davecode 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ChatApp-RQZ2IZFQ.js → ChatApp-C23NVTME.js} +6 -6
- package/dist/{account-FY6THFLW.js → account-GG7UFSNY.js} +3 -3
- package/dist/{accounts-ZV3KMLC5.js → accounts-IPOGUMHF.js} +5 -5
- package/dist/{budget-OUOEMMOM.js → budget-7QJGPYPF.js} +4 -4
- package/dist/{chat-OHVP4BS3.js → chat-3K2KXS3E.js} +8 -8
- package/dist/{chunk-FFB2QA5I.js → chunk-3BTE76UD.js} +2 -2
- package/dist/{chunk-L7NEDOA3.js → chunk-4FE2YV5U.js} +2 -2
- package/dist/{chunk-TP3ORSHY.js → chunk-FKGZERYB.js} +157 -9
- package/dist/chunk-FKGZERYB.js.map +1 -0
- package/dist/{chunk-2MM5WT5J.js → chunk-JBX6J74G.js} +3 -3
- package/dist/{chunk-2P5DJWIJ.js → chunk-KEURMO75.js} +4 -4
- package/dist/{chunk-NKRI6SYR.js → chunk-LK2K73DC.js} +2 -2
- package/dist/{chunk-2XGDILCW.js → chunk-NBQIMB43.js} +2422 -1599
- package/dist/chunk-NBQIMB43.js.map +1 -0
- package/dist/{chunk-HL4RIXPM.js → chunk-PGZPSJS7.js} +3 -3
- package/dist/{chunk-U5CI774J.js → chunk-U42YONUN.js} +3 -3
- package/dist/{config-ZLO3YOUX.js → config-BFEQFGAR.js} +3 -3
- package/dist/dashboard/assets/Accounts-CUMFzGls.js +1 -0
- package/dist/dashboard/assets/{Callout-CqdcH6dC.js → Callout-DDtTG_BA.js} +1 -1
- package/dist/dashboard/assets/Goals-CBGiTkcP.js +1 -0
- package/dist/dashboard/assets/{Library-DnCIb76j.js → Library-CKWa3h0E.js} +1 -1
- package/dist/dashboard/assets/{Panes-DBqKYuaE.js → Panes-ziAz-CZa.js} +4 -4
- package/dist/dashboard/assets/RoutesPage-D2iW-KhM.js +4 -0
- package/dist/dashboard/assets/Runner-4e79FB1J.js +1 -0
- package/dist/dashboard/assets/Settings-CSae84S0.js +1 -0
- package/dist/dashboard/assets/Tasks-CnbZ5PvX.js +2 -0
- package/dist/dashboard/assets/Traffic-B12xKOUm.js +1 -0
- package/dist/dashboard/assets/Workspace-CMPHlw4f.js +1 -0
- package/dist/dashboard/assets/chevron-down-DT349Fth.js +1 -0
- package/dist/dashboard/assets/external-link-DCIUScea.js +1 -0
- package/dist/dashboard/assets/format-C7Q-B9fI.js +112 -0
- package/dist/dashboard/assets/index-4RIBvhr9.css +2 -0
- package/dist/dashboard/assets/index-z8TlFwRe.js +50 -0
- package/dist/dashboard/assets/{task-errors-DK4-900l.js → task-errors-3F3vbQ7k.js} +1 -1
- package/dist/dashboard/assets/x-UBQsC1rW.js +1 -0
- package/dist/dashboard/index.html +4 -3
- package/dist/{dist-56V3DLJ4.js → dist-VTC5E7Z5.js} +34 -2
- package/dist/{doctor-DUOKUSJL.js → doctor-JLFYQ3EP.js} +3 -3
- package/dist/{goal-WG37XHUY.js → goal-JM7QYTL2.js} +4 -4
- package/dist/index.js +32 -32
- package/dist/{init-WW4XPFMM.js → init-6K4EGMTV.js} +3 -3
- package/dist/{orchestrate-7YQDBS3E.js → orchestrate-QC5P6IUZ.js} +4 -4
- package/dist/{run-QB4SGPEC.js → run-ABQNQ722.js} +3 -3
- package/dist/runtime.js +2 -2
- package/dist/{start-U4RL377T.js → start-MSO7TGBX.js} +3 -3
- package/dist/{status-GHVMGZI5.js → status-U6C4LUCM.js} +4 -4
- package/dist/{tasks-VTBJ4B2G.js → tasks-HEVT67YM.js} +4 -4
- package/package.json +4 -4
- package/dist/chunk-2XGDILCW.js.map +0 -1
- package/dist/chunk-TP3ORSHY.js.map +0 -1
- package/dist/dashboard/assets/Accounts-CIhOt9FH.js +0 -1
- package/dist/dashboard/assets/Goals-CITP2GqG.js +0 -1
- package/dist/dashboard/assets/RoutesPage-BNVmKhyU.js +0 -4
- package/dist/dashboard/assets/Runner-KR35ZWUE.js +0 -1
- package/dist/dashboard/assets/Settings-B5qE-a5O.js +0 -1
- package/dist/dashboard/assets/Tasks-bJLfNJmS.js +0 -2
- package/dist/dashboard/assets/Traffic-CGfilrRx.js +0 -1
- package/dist/dashboard/assets/Workspace-Dc3cvct_.js +0 -1
- package/dist/dashboard/assets/format-328qIBHX.js +0 -111
- package/dist/dashboard/assets/index-C-bwzlsl.js +0 -50
- package/dist/dashboard/assets/index-D9FCfPmM.css +0 -2
- /package/dist/{ChatApp-RQZ2IZFQ.js.map → ChatApp-C23NVTME.js.map} +0 -0
- /package/dist/{account-FY6THFLW.js.map → account-GG7UFSNY.js.map} +0 -0
- /package/dist/{accounts-ZV3KMLC5.js.map → accounts-IPOGUMHF.js.map} +0 -0
- /package/dist/{budget-OUOEMMOM.js.map → budget-7QJGPYPF.js.map} +0 -0
- /package/dist/{chat-OHVP4BS3.js.map → chat-3K2KXS3E.js.map} +0 -0
- /package/dist/{chunk-FFB2QA5I.js.map → chunk-3BTE76UD.js.map} +0 -0
- /package/dist/{chunk-L7NEDOA3.js.map → chunk-4FE2YV5U.js.map} +0 -0
- /package/dist/{chunk-2MM5WT5J.js.map → chunk-JBX6J74G.js.map} +0 -0
- /package/dist/{chunk-2P5DJWIJ.js.map → chunk-KEURMO75.js.map} +0 -0
- /package/dist/{chunk-NKRI6SYR.js.map → chunk-LK2K73DC.js.map} +0 -0
- /package/dist/{chunk-HL4RIXPM.js.map → chunk-PGZPSJS7.js.map} +0 -0
- /package/dist/{chunk-U5CI774J.js.map → chunk-U42YONUN.js.map} +0 -0
- /package/dist/{config-ZLO3YOUX.js.map → config-BFEQFGAR.js.map} +0 -0
- /package/dist/{dist-56V3DLJ4.js.map → dist-VTC5E7Z5.js.map} +0 -0
- /package/dist/{doctor-DUOKUSJL.js.map → doctor-JLFYQ3EP.js.map} +0 -0
- /package/dist/{goal-WG37XHUY.js.map → goal-JM7QYTL2.js.map} +0 -0
- /package/dist/{init-WW4XPFMM.js.map → init-6K4EGMTV.js.map} +0 -0
- /package/dist/{orchestrate-7YQDBS3E.js.map → orchestrate-QC5P6IUZ.js.map} +0 -0
- /package/dist/{run-QB4SGPEC.js.map → run-ABQNQ722.js.map} +0 -0
- /package/dist/{start-U4RL377T.js.map → start-MSO7TGBX.js.map} +0 -0
- /package/dist/{status-GHVMGZI5.js.map → status-U6C4LUCM.js.map} +0 -0
- /package/dist/{tasks-VTBJ4B2G.js.map → tasks-HEVT67YM.js.map} +0 -0
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import{i as e,n as t,o as n,r}from"./cn-BwE4cei0.js";var i=n(e(),1),a=r(),o=i.createContext(void 0),s=e=>{let t=i.useContext(o);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},c=({client:e,children:t})=>(i.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,a.jsx)(o.Provider,{value:e,children:t})),l={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},u=new class{#e=l;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 d(e){setTimeout(e,0)}var f=typeof window>`u`||`Deno`in globalThis;function p(){}function m(e,t){return typeof e==`function`?e(t):e}function h(e){return typeof e==`number`&&e>=0&&e!==1/0}function g(e,t){return Math.max(e+(t||0)-Date.now(),0)}function _(e,t){return typeof e==`function`?e(t):e}function v(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==b(o,t.options))return!1}else if(!ee(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 y(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(x(t.options.mutationKey)!==x(a))return!1}else if(!ee(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function b(e,t){return(t?.queryKeyHashFn||x)(e)}function x(e){return JSON.stringify(e,(e,t)=>ae(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function ee(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(!ee(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!ee(e[r],t[r]))return!1;return!0}return!1}var te=Object.prototype.hasOwnProperty;function ne(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=ie(e)&&ie(t);if(!r&&!(ae(e)&&ae(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:te.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=ne(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function re(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 ie(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function ae(e){if(!oe(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!(!oe(r)||!r.hasOwnProperty(`isPrototypeOf`)||t!==Object.prototype)}function oe(e){return Object.prototype.toString.call(e)===`[object Object]`}function se(e){return new Promise(t=>{u.setTimeout(t,e)})}function ce(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:ne(e,t)}function le(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function ue(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var de=Symbol();function fe(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===de?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function pe(e,t){return typeof e==`function`?e(...t):!!e}function me(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 he=()=>f,ge=()=>he(),_e=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(){}},ve=new class extends _e{#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`}},ye=d;function be(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=ye,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 xe=be(),Se=new class extends _e{#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 Ce(e){return Math.min(1e3*2**e,3e4)}function we(e){return(e??`online`)!==`online`||Se.isOnline()}var Te=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function Ee(e){let t=!1,n=0,r,i=`pending`,a,o,s=new Promise((e,t)=>{a=e,o=t});s.catch(p);let c=()=>i!==`pending`,l=t=>{if(!c()){let n=new Te(t);g(n),e.onCancel?.(n)}},u=()=>{t=!0},d=()=>{t=!1},f=()=>ve.isFocused()&&(e.networkMode===`always`||Se.isOnline())&&e.canRun(),m=()=>we(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??(ge()?0:3),a=e.retryDelay??Ce,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),se(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:m,start:()=>(m()?v():_(m).then(v),s)}}var De=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),h(this.gcTime)&&(this.#e=u.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(ge()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(u.clearTimeout(this.#e),this.#e=void 0)}};function Oe(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=>{me(e,()=>t.signal,()=>n=!0)},u=fe(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?ue:le;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?Ae:ke,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]:ke(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 ke(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 Ae(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var je=class extends De{#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=Pe(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=Pe(this.options);e.data!==void 0&&(this.setState(Ne(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=ce(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(p).catch(p):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=>_(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===de||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>_(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:!g(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=fe(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`?Oe(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=Ee({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof Te&&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 Te){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,...Me(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...Ne(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),xe.batch(()=>{this.observers.slice().forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function Me(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:we(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function Ne(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function Pe(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var Fe=class extends _e{#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),Le(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Re(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Re(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 _(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&&!re(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&ze(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),r&&(this.#t!==n||_(this.options.enabled,this.#t)!==_(t.enabled,this.#t)||_(this.options.staleTime,this.#t)!==_(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||_(this.options.enabled,this.#t)!==_(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 re(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(p)),t}#h(e){return!ge()&&_(this.options.enabled,this.#t)!==!1&&h(e)}#g(){this.#b();let e=_(this.options.staleTime,this.#t);if(this.#r.isStale||!this.#h(e))return;let t=g(this.#r.dataUpdatedAt,e)+1;this.#u=u.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return _(this.options.refetchInterval,this.#t)??!1}#v(e){this.#x(),this.#f=e,this.#f!==0&&this.#h(this.#f)&&(this.#d=u.setInterval(()=>{(this.options.refetchIntervalInBackground||ve.isFocused())&&this.#m()},this.#f))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#u!==void 0&&(u.clearTimeout(this.#u),this.#u=void 0)}#x(){this.#d!==void 0&&(u.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&&Le(e,t),o=i&&ze(e,n,t,r);(a||o)&&(l={...l,...Me(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=ce(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=ce(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`,v=m===`pending`,y=m===`error`,b=v&&g,x=d!==void 0;return{status:m,fetchStatus:l.fetchStatus,isPending:v,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&&!v,isLoadingError:y&&!x,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:y&&x,isStale:Be(e,t),refetch:this.refetch,isEnabled:_(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),re(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||this.options.throwOnError&&this.#r.error!==e.error)return!0;for(let t of n??this.#p)if(this.#r[t]!==e[t])return!0;return!1})();xe.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 Ie(e,t){return _(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||_(t.retryOnMount,e)!==!1)}function Le(e,t){return Ie(e,t)||e.state.data!==void 0&&Re(e,t,t.refetchOnMount)}function Re(e,t,n){if(_(t.enabled,e)!==!1&&_(t.staleTime,e)!==`static`){let r=_(n,e);return r===`always`||r!==!1&&Be(e,t)}return!1}function ze(e,t,n,r){return(e!==t||_(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&Be(e,n)}function Be(e,t){return _(t.enabled,e)!==!1&&e.isStaleByTime(_(t.staleTime,e))}var Ve=class extends De{#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||He(),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=Ee({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),xe.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function He(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var Ue=class extends _e{#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),re(this.options,t)||this.#e.getMutationCache().notify({type:`observerOptionsUpdated`,mutation:this.#n,observer:this}),t?.mutationKey&&this.options.mutationKey&&x(t.mutationKey)!==x(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??He();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){xe.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)})})}},We=i.createContext(!1),Ge=()=>i.useContext(We);We.Provider;function Ke(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var qe=i.createContext(Ke()),Je=()=>i.useContext(qe),Ye=(e,t,n)=>{let r=n?.state.status===`error`&&typeof e.throwOnError==`function`?pe(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||r)&&(t.isReset()||(e.retryOnMount=!1))},Xe=e=>{i.useEffect(()=>{e.clearReset()},[e])},Ze=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||pe(n,[e.error,r])),Qe=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))}},$e=(e,t)=>e?.suspense&&t.isPending,et=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function tt(e,t,n){let r=Ge(),a=Je(),o=s(n),c=o.defaultQueryOptions(e),l=o.getQueryCache().get(c.queryHash),u=e.subscribed!==!1;c._optimisticResults=r?`isRestoring`:u?`optimistic`:void 0,Qe(c),Ye(c,a,l),Xe(a);let[d]=i.useState(()=>new t(o,c)),f=d.getOptimisticResult(c),m=!r&&u;if(i.useSyncExternalStore(i.useCallback(e=>{let t=m?d.subscribe(xe.batchCalls(e)):p;return d.updateResult(),t},[d,m]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),i.useEffect(()=>{d.setOptions(c)},[c,d]),$e(c,f))throw et(c,d,a);if(Ze({result:f,errorResetBoundary:a,throwOnError:c.throwOnError,query:l,suspense:c.suspense}))throw f.error;return c.notifyOnChangeProps?f:d.trackResult(f)}function S(e,t){return tt(e,Fe,t)}function C(e,t){let n=s(t),[r]=i.useState(()=>new Ue(n,e));i.useEffect(()=>{r.setOptions(e)},[r,e]);let a=i.useSyncExternalStore(i.useCallback(e=>r.subscribe(xe.batchCalls(e)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),o=i.useCallback((...e)=>{r.mutate(e[0],e[1]).catch(p)},[r]);if(a.error&&pe(r.options.throwOnError,[a.error]))throw a.error;return{...a,mutate:o,mutateAsync:a.mutate}}var nt={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`}]]};nt.node;var rt=t(nt),it={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`}]]};it.node;var at=t(it),ot={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`}]]};ot.node;var st=t(ot),ct={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`}]]};ct.node;var lt=t(ct),ut={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`}]]};ut.node;var dt=t(ut),ft={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`]};ft.node;var pt=t(ft),mt={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`]};mt.node;var ht=t(mt);function gt(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function _t(e,t=`|`){return e.map(e=>zt(e)).join(t)}function vt(e,t){return typeof t==`bigint`?t.toString():t}var yt=class{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;return e!==void 0&&(this._value=e(),this._getter=void 0),this._value}};function bt(e){return new yt(e)}function xt(e){return e==null}function St(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function Ct(e,t){let n=e/t,r=Math.round(n),i=4*2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}function wt(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Tt(e){let t=Object.getOwnPropertyDescriptor(e,`shape`);return t?.get?t.get.raw:t?.value}function w(e){return Tt(e._zod.def)??e._zod.def.shape}function Et(e,t,n){Object.defineProperty(e,t,{get(){let e=n();return wt(this,t,e),e},enumerable:!0,configurable:!0})}function Dt(e,t,n){t in e?wt(e,t,n):e[t]=n}function Ot(e,t,n,r){let i=w(t);for(let a of n){let n=Object.getOwnPropertyDescriptor(i,a);n.enumerable&&(n.get?Et(e,a,()=>{let e=t._zod.def.shape[a];return r?r(e,a):e}):Dt(e,a,r?r(n.value,a):n.value))}}function kt(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?Et(e,n,()=>t[n]):Dt(e,n,r.value))}}function T(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function At(e){return JSON.stringify(e)}function jt(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}var Mt=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function Nt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Pt=bt(()=>{if(M.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function Ft(e){if(Nt(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return Nt(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function It(e){return Ft(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var Lt=new Set([`string`,`number`,`symbol`]);function Rt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function E(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function D(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function zt(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function Bt(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`)}var Vt={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Ht={int64:[BigInt(`-9223372036854775808`),BigInt(`9223372036854775807`)],uint64:[BigInt(0),BigInt(`18446744073709551615`)]};function Ut(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);let i={};return Ot(i,e,Wt(e,t)),E(e,T(n,{shape:i,checks:[]}))}function Wt(e,t){let n=w(e),r=[];for(let e of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,e)?.enumerable)throw Error(`Unrecognized key: "${String(e)}"`);t[e]&&r.push(e)}return r}function Gt(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);let i=new Set(Wt(e,t)),a={};return Ot(a,e,Reflect.ownKeys(w(e)).filter(e=>!i.has(e))),E(e,T(n,{shape:a,checks:[]}))}function Kt(e,t){if(!Ft(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=w(e);for(let e of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return E(e,T(e._zod.def,{shape:qt(e,t)}))}function qt(e,t){let n={};return Ot(n,e,Reflect.ownKeys(w(e))),kt(n,t),n}function Jt(e,t){if(!Ft(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return E(e,T(e._zod.def,{shape:qt(e,t)}))}function Yt(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);let n={};return Ot(n,e,Reflect.ownKeys(w(e))),Ot(n,t,Reflect.ownKeys(w(t))),E(e,T(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function Xt(e,t,n,r=`partial`){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);let a=n?new Set(Wt(t,n)):void 0,o={};return Ot(o,t,Reflect.ownKeys(w(t)),e&&((t,n)=>a&&!a.has(n)?t:new e({type:`optional`,innerType:t}))),E(t,T(t._zod.def,{shape:o,checks:[]}))}function Zt(e,t,n){let r=n?new Set(Wt(t,n)):void 0,i={};return Ot(i,t,Reflect.ownKeys(w(t)),(t,n)=>r&&!r.has(n)?t:new e({type:`nonoptional`,innerType:t})),E(t,T(t._zod.def,{shape:i}))}function O(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Qt(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function $t(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function en(e){return typeof e==`string`?e:e?.message}function tn(e){let t=[];for(let n of e??[]){let e=n._zod.def;if(!/_(length|size)$|_equals$/.test(e.check))break;let r=e.maximum??e.length??e.size;r>=0&&t.push([r,n])}return t}function nn(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function rn(e,t,n){var r;let i=e.inst?._zod?.traits;i?.has(`$ZodType`)&&(i.has(`$ZodCheck`)?(r=e).schema??(r.schema=e.inst):e.schema=e.inst);let a=e.schema===e.inst?void 0:e.schema?._zod.def?.error,o=e.message?e.message:en(e.inst?._zod.def?.error?.(e))??en(a?.(e))??en(t?.error?.(e))??en(n.customError?.(e))??en(n.localeError?.(e))??`Invalid input`,s={};for(let t of Object.keys(e))t!==`inst`&&t!==`schema`&&t!==`continue`&&t!==`input`&&t!==`__proto__`&&(s[t]=e[t]);return s.path??=[],s.message=o,t?.reportInput&&(s.input=e.input),s}var an=/[\uD800-\uDBFF]/;function on(e){let t=e.length;if(!an.test(e))return t;let n=t;for(let r=0;r<t-1;r++)(e.charCodeAt(r)&64512)==55296&&(e.charCodeAt(r+1)&64512)==56320&&(n--,r++);return n}function sn(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function cn(e){let t=typeof e;switch(t){case`number`:return Number.isNaN(e)?`nan`:`number`;case`object`:{if(e===null)return`null`;if(Array.isArray(e))return`array`;let t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&`constructor`in t&&t.constructor)return t.constructor.name}}return t}function ln(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}function un(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):pn(e,n,r.value)}}function k(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function dn(e,t,n){return k(e,t,n,!1)}function fn(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return k(this,n,r(this))},set(e){k(this,n,e)}})}return t}function pn(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:k(this,t,n.bind(this))},set(e){k(this,t,e)}})}function mn(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}var hn,gn=!1,_n={configurable:!0,get(){gn=!0}};function A(e,t,n){let r=Object.getPrototypeOf(e._zod);t in r&&hn!==e._zod?hn=void 0:(hn=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,_n);let e=gn;gn=!1;try{let r=n(this);return gn?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),gn||=e,r}catch(n){throw delete this[t],gn||=e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}}))}function vn(e,t,n,r){let i=mn(e,t);i&&Object.defineProperty(i,t,{configurable:!0,get(){let e={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,e),e.value=n(this),Object.defineProperty(this,t,e),e.value},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:e})}})}var yn=`~constantCatch`;function bn(e){let t=()=>e;return t[yn]=!0,t}var xn,Sn={value:void 0,enumerable:!1},Cn=`captureStackTrace`in Error?Error:null;function wn(e){let t=Cn;if(t){let n=t.stackTraceLimit;if(typeof n==`number`){try{t.stackTraceLimit=0}catch{return Cn=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function j(e,t,n,r){let i={};function a(e){this.def=e,this.constr=d,this.traits=new Set}a.prototype=i;let o=n,s=o&&new WeakSet;function c(n,r){if(!n._zod){Sn.value=new a(r);try{Object.defineProperty(n,"_zod",Sn)}finally{Sn.value=void 0}}else if(n._zod.traits.has(e))return;if(n._zod.traits.add(e),t(n,r),s){let e=Object.getPrototypeOf(n),t=n._zod.constr.prototype,r=e;for(;r&&r!==t;)r=Object.getPrototypeOf(r);let i=r??e;s.has(i)||(s.add(i),un(i,o))}let i=d.prototype;for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&(e in n||(n[e]=i[e].bind(n)))}let l=r?.Parent??Object;class u extends l{}Object.defineProperty(u,"name",{value:e});function d(e){let t=r?.Parent?wn(u):this;c(t,e);let n=t._zod.deferred;if(n){for(let e of n)e();t._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(d,"init",{value:c}),Object.defineProperty(d,Symbol.hasInstance,{value:t=>r?.Parent&&t instanceof r.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(d,"name",{value:e}),d}var Tn=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},En=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(xn=globalThis).__zod_globalConfig??(xn.__zod_globalConfig={});var M=globalThis.__zod_globalConfig;function N(e){return e&&Object.assign(M,e),M}function Dn(){let e=this._zod;return e.message??=JSON.stringify(e.def,vt,2),e.message}function On(e){this._zod.message=e}var kn={get:Dn,set:On,enumerable:!0,configurable:!0},An={value:void 0,enumerable:!1},jn=new WeakSet([Object.prototype,Error.prototype]),Mn=j(`$ZodError`,(e,t)=>{e.name=`$ZodError`,An.value=t,Object.defineProperty(e,"issues",An),An.value=void 0,Object.defineProperty(e,"message",kn);let n=Object.getPrototypeOf(e);jn.has(n)||(jn.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let e=()=>this.message;return Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0})}}))});function Nn(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||(t===`__proto__`?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function Pn(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?Nn(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Fn(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i<e.length;){let n=e[i],o=i===e.length-1;if(n===`_errors`){o&&r._errors.push(t(a)),i++;continue}Object.prototype.hasOwnProperty.call(r,n)||Object.defineProperty(r,n,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let s=r[n];o&&s._errors.push(t(a)),r=s,i++}}}};return r(e),n}function In(e,t){return{callee:t?.callee??e,Err:t?.Err}}var Ln=e=>{let t=(n,r,i,a)=>{let o=i?{...i,async:!1}:{async:!1},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Tn;if(s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>rn(e,o,N())));throw Mt(n,a?.callee??t),n}return s.value};return t},Rn=e=>{let t=async(n,r,i,a)=>{let o=i?{...i,async:!0}:{async:!0},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>rn(e,o,N())));throw Mt(n,a?.callee??t),n}return s.value};return t},zn=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Tn;return a.issues.length?Bn(e,a.issues,i):{success:!0,data:a.value}};function Bn(e,t,n){let r;return{success:!1,get error(){return r||(r=new e(t.map(e=>rn(e,n,N()))),t=void 0,n=void 0),r},set error(e){r=e,t=void 0,n=void 0}}}var Vn=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?Bn(e,a.issues,i):{success:!0,data:a.value}},Hn=Symbol.for(`zod.compile.invalid`),Un=Symbol.for(`zod.compile.fallback`),Wn=((e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==Hn)return!0;if(r.definite===!0&&n===void 0)return!1}return Gn(e,t,n)});function Gn(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=e._zod.bag.fallbackRun,a;if(i?(r[Un]=!0,a=i({value:t,issues:[]},r)):a=e._zod.run({value:t,issues:[]},r),a instanceof Promise)throw new Tn;return a.issues.length===0}var Kn=async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},i=e._zod.run({value:t,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length===0},qn=e=>{let t=Ln(e),n=(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return t(e,r,o,In(n,a))};return n},Jn=e=>{let t=Ln(e),n=(e,r,i,a)=>t(e,r,i,In(n,a));return n},Yn=e=>{let t=Rn(e),n=async(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return await t(e,r,o,In(n,a))};return n},Xn=e=>{let t=Rn(e),n=async(e,r,i,a)=>await t(e,r,i,In(n,a));return n},Zn=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return zn(e)(t,n,i)},Qn=e=>(t,n,r)=>zn(e)(t,n,r),$n=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Vn(e)(t,n,i)},er=e=>async(t,n,r)=>Vn(e)(t,n,r),tr=/^[cC][0-9a-z]{6,}$/,nr=/^[0-9a-z]+$/,rr=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,ir=/^[0-9a-vA-V]{20}$/,ar=/^[A-Za-z0-9]{27}$/,or=/^[a-zA-Z0-9_-]{21}$/;function sr(e){return RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var cr=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,lr=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ur=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,dr=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,fr=`^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`;function pr(){return new RegExp(fr,`u`)}var mr=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,hr=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,gr=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,_r=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,vr=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,yr=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,br=/^https?$/,xr=/^\+[1-9]\d{6,14}$/,Sr=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;function Cr(e){return RegExp(`^${e}$`)}var wr=Cr(Sr);function Tr(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Er(e){return RegExp(`^${Tr(e)}$`)}function Dr(e){let t=[`Z`];e.offset&&t.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let n=`${Tr({precision:e.precision,seconds:!0})}(?:${t.join(`|`)})`,r=e.local?`${n}|${Tr({precision:e.precision})}`:n;return RegExp(`^${Sr}T(?:${r})$`)}var Or=/^[\s\S]{0,}$/,kr=/^-?\d+(?:\.\d+)?$/,Ar=/^(?:true|false)$/i,jr=/^[^A-Z]*$/,Mr=/^[^a-z]*$/,P=j(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Nr=e=>{let t=e.value;return!xt(t)&&t.length!==void 0},Pr={number:`number`,bigint:`bigint`,object:`date`},Fr=j(`$ZodCheckLessThan`,(e,t)=>{P.init(e,t);let n=Pr[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:Pr[typeof r.value]??n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ir=j(`$ZodCheckGreaterThan`,(e,t)=>{P.init(e,t);let n=Pr[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:Pr[typeof r.value]??n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Lr=j(`$ZodCheckMultipleOf`,(e,t)=>{P.init(e,t),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):Ct(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Rr=j(`$ZodCheckNumberFormat`,(e,t)=>{P.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Vt[t.format];e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),zr=j(`$ZodCheckMaxLength`,(e,t)=>{var n;P.init(e,t),(n=e._zod.def).when??(n.when=Nr),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>t.maximum?on(r):i)<=t.maximum)return;let a=sn(r);n.issues.push({origin:a,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Br=j(`$ZodCheckMinLength`,(e,t)=>{var n;P.init(e,t),(n=e._zod.def).when??(n.when=Nr),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>=t.minimum&&i<t.minimum*2?on(r):i)>=t.minimum)return;let a=sn(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Vr=j(`$ZodCheckLengthEquals`,(e,t)=>{var n;P.init(e,t),(n=e._zod.def).when??(n.when=Nr),e._zod.check=n=>{let r=n.value,i=r.length,a=typeof r==`string`&&i>=t.length&&i<=t.length*2?on(r):i;if(a===t.length)return;let o=sn(r),s=a>t.length;n.issues.push({origin:o,...s?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Hr=j(`$ZodCheckStringFormat`,(e,t)=>{var n,r;P.init(e,t),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Ur=j(`$ZodCheckRegex`,(e,t)=>{Hr.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Wr=j(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=jr,Hr.init(e,t)}),Gr=j(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=Mr,Hr.init(e,t)}),Kr=j(`$ZodCheckIncludes`,(e,t)=>{P.init(e,t);let n=Rt(t.includes);t.pattern=new RegExp(typeof t.position==`number`?`^.{${t.position},}${n}`:n),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),qr=j(`$ZodCheckStartsWith`,(e,t)=>{P.init(e,t);let n=RegExp(`^${Rt(t.prefix)}.*`);t.pattern??=n,e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Jr=j(`$ZodCheckEndsWith`,(e,t)=>{P.init(e,t);let n=RegExp(`.*${Rt(t.suffix)}$`);t.pattern??=n,e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Yr=j(`$ZodCheckOverwrite`,(e,t)=>{P.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),Xr=class{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{--this.indent}}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
|
|
2
|
+
`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.content??[``];return new e(...Object.keys(this.closed),`return function (${this.args.join(`, `)}) {\n${t.join(`
|
|
3
|
+
`)}\n};`)(...Object.values(this.closed))}},Zr={major:4,minor:6,patch:7},F=j(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Zr;let r=e._zod.def.checks,i=e._zod.traits.has(`$ZodCheck`)?[e,...r??[]]:r?.length?[...r]:[];for(let t of i)for(let n of t._zod.onattach)n(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(t,n,r)=>{if(t.memo)return t;let i=O(t),a;for(let o of n){if(o._zod.def.when){if(Qt(t)||!o._zod.def.when(t))continue}else if(i)continue;let n=t.issues.length,s=o._zod.check(t);if(s instanceof Promise&&r?.async===!1)throw new Tn;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,t.issues.length!==n&&(nn(t.issues,n,e),i||=O(t,n))});else{if(t.issues.length===n)continue;nn(t.issues,n,e),i||=O(t,n)}}return a?a.then(()=>t):t},n=(n,r,a)=>{if(O(n))return n.aborted=!0,n;let o=t(r,i,a);if(o instanceof Promise){if(a.async===!1)throw new Tn;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(r,a)=>{if(a.skipChecks)return e._zod.parse(r,a);if(a.direction===`backward`){let t=e._zod.parse({value:r.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,r,a)):n(t,r,a)}let o=e._zod.parse(r,a);if(o instanceof Promise){if(a.async===!1)throw new Tn;return o.then(e=>t(e,i,a))}return t(o,i,a)}}},{get"~standard"(){return dn(this,`~standard`,ei(this))},set"~standard"(e){k(this,`~standard`,e)}}),Qr=(e,t)=>e.issues.length?{issues:e.issues.map(e=>rn(e,t,N()))}:{value:e.value};async function $r(e,t){let n={async:!0};return Qr(await e._zod.run({value:t,issues:[]},n),n)}function ei(e){return{validate:t=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return Qr(r,n)}catch{}return $r(e,t)},vendor:`zod`,version:1}}var ti=j(`$ZodString`,(e,t)=>{F.init(e,t),e._zod.pattern=t.pattern??Or,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),I=j(`$ZodStringFormat`,(e,t)=>{Hr.init(e,t),ti.init(e,t)}),ni=j(`$ZodGUID`,(e,t)=>{t.pattern??=lr,I.init(e,t)}),ri=j(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=ur(e)}else t.pattern??=ur();I.init(e,t)}),ii=j(`$ZodEmail`,(e,t)=>{t.pattern??=dr,I.init(e,t)});function ai(e){try{return typeof URL<`u`&&typeof URL.canParse==`function`?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function oi(e,t){return!(`normalize`in t)&&!(`hostname`in t)&&!(`protocol`in t)?ai(e)||2:si(e,t)}function si(e,t){if(!t.normalize&&t.protocol?.source===br.source&&!/^https?:\/\//i.test(e))return 1;try{if(typeof URL<`u`){let t=URL;if(typeof t.parse==`function`)return t.parse(e)??2}return new URL(e)}catch{return 2}}var ci=/[\t\n\r]/g;function li(e){return e.replace(ci,``)}function ui(e,t){return t.lastIndex=0,t.test(e.hostname)}function di(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(`:`)?e.protocol.slice(0,-1):e.protocol)}var fi=j(`$ZodURL`,(e,t)=>{I.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=oi(r,t);if(i===1){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}if(i===2){n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort});return}if(i===!0){n.value=li(r);return}t.hostname&&!ui(i,t.hostname)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort}),t.protocol&&!di(i,t.protocol)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort}),n.value=t.normalize?i.href:li(r);return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),pi=j(`$ZodEmoji`,(e,t)=>{t.pattern??=pr(),I.init(e,t)}),mi=j(`$ZodNanoID`,(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??=t.length===void 0?or:sr(t.length),I.init(e,t)}),hi=j(`$ZodCUID`,(e,t)=>{t.pattern??=tr,I.init(e,t)}),gi=j(`$ZodCUID2`,(e,t)=>{t.pattern??=nr,I.init(e,t)}),_i=j(`$ZodULID`,(e,t)=>{t.pattern??=rr,I.init(e,t)}),vi=j(`$ZodXID`,(e,t)=>{t.pattern??=ir,I.init(e,t)}),yi=j(`$ZodKSUID`,(e,t)=>{t.pattern??=ar,I.init(e,t)}),bi=j(`$ZodISODateTime`,(e,t)=>{t.pattern??=Dr(t),I.init(e,t)}),xi=j(`$ZodISODate`,(e,t)=>{t.pattern??=wr,I.init(e,t)}),Si=j(`$ZodISOTime`,(e,t)=>{t.pattern??=Er(t),I.init(e,t)}),Ci=j(`$ZodISODuration`,(e,t)=>{t.pattern??=cr,I.init(e,t)}),wi=j(`$ZodIPv4`,(e,t)=>{t.pattern??=mr,I.init(e,t)}),Ti=/^[0-9a-fA-F:.]+$/;function Ei(e){return Ti.test(e)?ai(`http://[${e}]`):!1}var Di=j(`$ZodIPv6`,(e,t)=>{t.pattern??=hr,I.init(e,t),e._zod.check=n=>{Ei(n.value)||n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}),Oi=j(`$ZodCIDRv4`,(e,t)=>{t.pattern??=gr,I.init(e,t)});function ki(e){let t=e.split(`/`);if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let i=Number(r);return`${i}`!==r||i<0||i>128?!1:Ei(n)}var Ai=j(`$ZodCIDRv6`,(e,t)=>{t.pattern??=_r,I.init(e,t),e._zod.check=n=>{ki(n.value)||n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}});function ji(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var Mi=/^[0-9a-zA-Z+/]*={0,2}$/,Ni=j(`$ZodBase64`,(e,t)=>{t.pattern??=Mi,I.init(e,t),e._zod.check=n=>{ji(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}}),Pi=/^[A-Za-z0-9_-]*$/;function Fi(e){if(!Pi.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return ji(t.padEnd(Math.ceil(t.length/4)*4,`=`))}var Ii=j(`$ZodBase64URL`,(e,t)=>{t.pattern??=Pi,I.init(e,t),e._zod.check=n=>{Fi(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Li=j(`$ZodE164`,(e,t)=>{t.pattern??=xr,I.init(e,t)});function Ri(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}var zi=j(`$ZodJWT`,(e,t)=>{I.init(e,t),e._zod.check=n=>{Ri(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),Bi=j(`$ZodNumber`,(e,t)=>{F.init(e,t),e._zod.pattern=kr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:String(i):void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),Vi=j(`$ZodNumberFormat`,(e,t)=>{Rr.init(e,t),Bi.init(e,t)}),Hi=j(`$ZodBoolean`,(e,t)=>{F.init(e,t),e._zod.pattern=Ar,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),Ui=j(`$ZodUnknown`,(e,t)=>{F.init(e,t),e._zod.parse=e=>e}),Wi=j(`$ZodNever`,(e,t)=>{F.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function Gi(e,t){let n=tn(e._zod.def.checks);if(!n.length)return;let r=Math.min(...n.map(e=>e[0])),i=e._zod.parse;e._zod.parse=(n,a)=>{let o=t(n.value);if(o>r&&!a?.skipChecks&&a?.direction!==`backward`){for(let[t,r]of tn(e._zod.def.checks))if(o>t&&r._zod.def.when(n)){let t=n.issues.length;return r._zod.check(n),n.issues[t].continue=!1,nn(n.issues,t,e),n}}return i(n,a)}}var Ki=e=>Array.isArray(e)?e.length:-1;function qi(e,t,n){e.issues.length&&t.issues.push(...$t(n,e.issues)),t.value[n]=e.value}var Ji=j(`$ZodArray`,(e,t)=>{F.init(e,t);let n=M.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({expected:`array`,code:`invalid_type`,input:a,inst:e}),r;r.value=n?n.alloc(e,r,Array(a.length),i):Array(a.length);let o=[],s=i?.abortEarly;for(let e=0;e<a.length;e++){let n=a[e],c=t.element._zod.run({value:n,issues:[]},i);if(c instanceof Promise)o.push(c.then(t=>qi(t,r,e)));else if(qi(c,r,e),s&&c.issues.length!==0&&O(c))break}return o.length?Promise.all(o).then(()=>r):r},Gi(e,Ki)});function Yi(e,t,n,r,i,a){let o=n in r,s=a===`optional`;if(o||!s||i!==`optional`){if(e.issues.length){if(i!==void 0&&s&&!o)return;t.issues.push(...$t(n,e.issues))}!o&&i===void 0?e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]}):e.value===void 0?(o||i===`defaulted`&&!s)&&(t.value[n]=void 0):t.value[n]=e.value}}var Xi=[];function Zi(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:Xi,i=r.length?[...t,...r]:t;for(let t of i)if(!e.shape?.[t]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${String(t)}": expected a Zod schema`);let a=Bt(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function Qi(e,t,n,r,i,a,o){let s=[],c=i.keySet,l=i.catchall._zod,u=l.def.type,d=l.optin,f=l.optout,p=0;for(let i in t){if(o&&n.issues.length!==p){if(O(n,p))break;p=n.issues.length}if(c.has(i))continue;if(i===`__proto__`){u===`never`&&s.push(i);continue}if(u===`never`){s.push(i);continue}let a=l.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>Yi(e,n,i,t,d,f))):Yi(a,n,i,t,d,f)}return s.length&&n.issues.push({code:`unrecognized_keys`,keys:s,input:t,inst:a,continue:!0}),e.length?Promise.all(e).then(()=>n):n}var $i=j(`$ZodObject`,(e,t)=>{F.init(e,t);let n=Object.getOwnPropertyDescriptor(t,`shape`),r=n?.get?n.get.raw:t.shape??{};if(r){let e=()=>{let n={...r};return Object.defineProperty(t,"shape",{value:n}),e.raw=n,n};e.raw=r,Object.defineProperty(t,"shape",{get:e})}let i=bt(()=>Zi(t));A(e,`propValues`,e=>{let t=e.def.shape,n={};for(let e in t){let r=t[e]._zod;if(r.values){Object.prototype.hasOwnProperty.call(n,e)||wt(n,e,new Set);for(let t of r.values)n[e].add(t);r.optin!==void 0&&n[e].add(void 0)}}return n});let a=Nt,o=t.catchall,s,c=M.memoizer;c?.attach(e),e._zod.parse=(t,n)=>{s??=i.value;let r=t.value;if(!a(r))return t.issues.push({expected:`object`,code:`invalid_type`,input:r,inst:e}),t;t.value=c?c.alloc(e,t,{},n):{};let l=[],u=s.shape,d=n?.abortEarly,f=t.issues.length;for(let e of s.allKeys){if(d&&t.issues.length!==f){if(O(t,f))break;f=t.issues.length}if(e===`__proto__`)continue;let i=u[e],a=i._zod.optin,o=i._zod.optout,s=i._zod.run({value:r[e],issues:[]},n);s instanceof Promise?l.push(s.then(n=>Yi(n,t,e,r,a,o))):Yi(s,t,e,r,a,o)}return o?Qi(l,r,t,n,i.value,e,d===!0):l.length?Promise.all(l).then(()=>t):t}}),ea=j(`$ZodObjectJIT`,(e,t)=>{$i.init(e,t);let n=e._zod.parse,r=bt(()=>Zi(t)),i=M.memoizer,a=t=>{let n=r.value,a=n.symbolKeys,o=new Xr([`payload`,`ctx`],{shape:t,inst:e,memo:i,syms:a}),s=e=>`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`,c=(e,t)=>`
|
|
4
|
+
let ${e}_ab = false;
|
|
5
|
+
for (let i = 0; i < ${e}.issues.length; i++) {
|
|
6
|
+
const iss = ${e}.issues[i];
|
|
7
|
+
iss.path = iss.path ? [${t}, ...iss.path] : [${t}];
|
|
8
|
+
payload.issues.push(iss);
|
|
9
|
+
if (iss.continue !== true) ${e}_ab = true;
|
|
10
|
+
}
|
|
11
|
+
if (${e}_ab && ctx && ctx.abortEarly) {
|
|
12
|
+
payload.value = newResult;
|
|
13
|
+
return payload;
|
|
14
|
+
}`;o.write(`const input = payload.value;`);let l=Object.create(null),u=0;for(let e of n.allKeys)l[e]=`key_${u++}`;o.write(i?`const newResult = memo.alloc(inst, payload, {}, ctx);`:`const newResult = {};`);for(let e of n.allKeys){if(e===`__proto__`)continue;let n=l[e],r=typeof e==`symbol`?`syms[${a.indexOf(e)}]`:At(e),i=`${r} in input`,u=t[e],d=u?._zod?.optin,f=d!==void 0,p=u?._zod?.optout===`optional`;if(o.write(`const ${n} = ${s(r)};`),f&&p){let e=d===`optional`?`${n}_present`:`${n}.value !== undefined || ${n}_present`;o.write(`
|
|
15
|
+
const ${n}_present = ${i};
|
|
16
|
+
if (!${n}.issues.length || ${n}_present) {
|
|
17
|
+
if (${n}.issues.length) {${c(n,r)}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
if (${e}) {
|
|
21
|
+
newResult[${r}] = ${n}.value;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
`)}else f?(o.write(`
|
|
26
|
+
if (${n}.issues.length) {${c(n,r)}
|
|
27
|
+
}
|
|
28
|
+
`),d===`defaulted`?o.write(`newResult[${r}] = ${n}.value;`):o.write(`
|
|
29
|
+
if (${n}.value !== undefined || ${i}) {
|
|
30
|
+
newResult[${r}] = ${n}.value;
|
|
31
|
+
}
|
|
32
|
+
`)):o.write(`
|
|
33
|
+
const ${n}_present = ${i};
|
|
34
|
+
if (${n}.issues.length) {${c(n,r)}
|
|
35
|
+
}
|
|
36
|
+
if (!${n}_present && !${n}.issues.length) {
|
|
37
|
+
payload.issues.push({
|
|
38
|
+
code: "invalid_type",
|
|
39
|
+
expected: "nonoptional",
|
|
40
|
+
input: undefined,
|
|
41
|
+
path: [${r}]
|
|
42
|
+
});
|
|
43
|
+
if (ctx && ctx.abortEarly) {
|
|
44
|
+
payload.value = newResult;
|
|
45
|
+
return payload;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (${n}_present) {
|
|
50
|
+
newResult[${r}] = ${n}.value;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
`)}return o.write(`payload.value = newResult;`),o.write(`return payload;`),o.compile()},o,s=Nt,c=!M.jitless,l=c&&Pt.value,u=t.catchall,d;e._zod.parse=(i,f)=>{d??=r.value;let p=i.value;return s(p)?c&&l&&f?.async===!1&&f.jitless!==!0?(o||=a(t.shape),i=o(i,f),u?Qi([],p,i,f,d,e,f?.abortEarly===!0):i):n(i,f):(i.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),i)}});function ta(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!O(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>rn(e,r,N())))}),t)}var na=j(`$ZodUnion`,(e,t)=>{F.init(e,t),A(e,`optin`,e=>e.def.options.some(e=>e._zod.optin===`defaulted`)?`defaulted`:e.def.options.some(e=>e._zod.optin!==void 0)?`optional`:void 0),A(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),A(e,`values`,e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),A(e,`pattern`,e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return RegExp(`^(${t.map(e=>St(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>ta(t,r,e,i)):ta(o,r,e,i)}}),ra=j(`$ZodIntersection`,(e,t)=>{F.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>aa(e,t,n)):aa(e,i,a)}});function ia(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Ft(e)&&Ft(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=ia(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=ia(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function aa(e,t,n){let r=new Map,i,a=new Map,o=(e,t)=>{let n;if(e.code===`unrecognized_keys`&&!e.path?.length)i??=e,n=e.keys;else if(e.code===`invalid_key`&&e.origin===`record`&&e.path?.length===1){let t=String(e.path[0]);a.has(t)||a.set(t,e),n=[t]}else return!1;for(let e of n)r.has(e)||r.set(e,{}),r.get(e)[t]=!0;return!0};for(let n of t.issues)o(n,`l`)||e.issues.push(n);for(let t of n.issues)o(t,`r`)||e.issues.push(t);let s=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(s.length){let t=i?s.filter(e=>i.keys.includes(e)):[];t.length&&e.issues.push({...i,keys:t});for(let n of s)!t.includes(n)&&a.has(n)&&e.issues.push(a.get(n))}let c=ia(t.value,n.value);if(!c.valid){if(O(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var oa=j(`$ZodEnum`,(e,t)=>{F.init(e,t);let n=gt(t.entries),r=new Set(n);e._zod.values=r,A(e,`pattern`,e=>{let t=gt(e.def.entries).filter(e=>Lt.has(typeof e));return RegExp(t.length?`^(${t.map(e=>Rt(e.toString())).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),sa=j(`$ZodTransform`,(e,t)=>{F.init(e,t),e._zod.optin=`optional`,M.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new En(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new Tn;return n.value=i,n}});function ca(e,t){return e.value=t.issues.length?void 0:t.value,e}var la=j(`$ZodOptional`,(e,t)=>{F.init(e,t),A(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,A(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t,void 0]):void 0}),A(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${St(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(e.value===void 0){if(t.innerType._zod.optin!==`defaulted`)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>ca(e,t)):ca(e,r)}return t.innerType._zod.run(e,n)}}),ua=j(`$ZodExactOptional`,(e,t)=>{la.init(e,t),A(e,`values`,e=>e.def.innerType._zod.values),A(e,`pattern`,e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),da=j(`$ZodNullable`,(e,t)=>{F.init(e,t),A(e,`optin`,e=>e.def.innerType._zod.optin),A(e,`optout`,e=>e.def.innerType._zod.optout),A(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${St(t.source)}|null)$`):void 0}),A(e,`values`,e=>e.def.innerType._zod.values?new Set([...e.def.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),fa=j(`$ZodDefault`,(e,t)=>{F.init(e,t),e._zod.optin=`defaulted`,A(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>pa(e,t)):pa(r,t)}});function pa(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var ma=j(`$ZodPrefault`,(e,t)=>{F.init(e,t),e._zod.optin=`defaulted`,A(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),ha=j(`$ZodNonOptional`,(e,t)=>{F.init(e,t),A(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>ga(t,e)):ga(i,e)}});function ga(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}function _a(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>rn(e,r,N()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}var va=j(`$ZodCatch`,(e,t)=>{F.init(e,t),A(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),A(e,`optout`,e=>e.def.innerType._zod.optout),A(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(r=>_a(e,r,t,n)):_a(e,r,t,n)}}),ya=j(`$ZodPipe`,(e,t)=>{F.init(e,t),A(e,`values`,e=>e.def.in._zod.values),A(e,`optin`,e=>e.def.in._zod.optin),A(e,`optout`,e=>e.def.out._zod.optout),A(e,`propValues`,e=>e.def.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>ba(e,t.in,n)):ba(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>ba(e,t.out,n)):ba(r,t.out,n)}});function ba(e,t,n){return e.issues.some(e=>e.code!==`unrecognized_keys`)?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}var xa=j(`$ZodReadonly`,(e,t)=>{F.init(e,t),A(e,`propValues`,e=>e.def.innerType._zod.propValues),A(e,`values`,e=>e.def.innerType._zod.values),A(e,`optin`,e=>e.def.innerType?._zod?.optin),A(e,`optout`,e=>e.def.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Sa):Sa(r)}});function Sa(e){return e.memo||(e.value=Object.freeze(e.value)),e}var Ca=j(`$ZodCustom`,(e,t)=>{P.init(e,t),F.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>wa(t,n,r,e));wa(i,n,r,e)}});function wa(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(ln(e))}}var Ta=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}},Ea=`~memo`,Da=[];function Oa(e){return typeof e==`object`&&!!e}function ka(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}var Aa=new WeakMap,ja=0,Ma=1,Na=2;function Pa(e,t,n){let r=Aa.get(e);if(r!==void 0)return r?Na:ja;if(t.has(e))return Na;t.add(e);let i=ja,a=e=>{if(i!==Na&&e?._zod){let r=Pa(e,t,n);r>i&&(i=r)}},o=(e,r)=>{let i=ja;for(let a of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,a);if(r&&!o.enumerable)continue;let s=o.get?Ma:o.value?._zod?Pa(o.value,t,n):ja;s>i&&(i=s)}return i},s=e=>{e>i&&(i=e)},c=e._zod.def;switch(c.type){case`object`:{let e=Tt(c);s(e?o(e,!0):Ma),a(c.catchall);break}case`array`:a(c.element);break;case`tuple`:for(let e of c.items)a(e);a(c.rest);break;case`record`:case`map`:a(c.keyType),a(c.valueType);break;case`set`:a(c.valueType);break;case`union`:for(let e of c.options)a(e);break;case`intersection`:a(c.left),a(c.right);break;case`optional`:case`nullable`:case`default`:case`prefault`:case`catch`:case`readonly`:case`nonoptional`:case`promise`:case`success`:a(c.innerType);break;case`pipe`:a(c.in),a(c.out);break;case`function`:a(c.input),a(c.output);break;case`lazy`:{let r=c._cachedInner??(n?e._zod.innerType:void 0);s(r?Pa(r,t,!1):Ma);break}case`template_literal`:case`string`:case`number`:case`int`:case`boolean`:case`bigint`:case`symbol`:case`undefined`:case`null`:case`void`:case`never`:case`any`:case`unknown`:case`date`:case`nan`:case`enum`:case`literal`:case`file`:case`transform`:case`custom`:break;default:for(let e in c){let t=Object.getOwnPropertyDescriptor(c,e);if(!t||t.get)continue;let n=t.value;if(n&&typeof n==`object`){if(n._zod)a(n);else if(Array.isArray(n))for(let e of n)a(e)}}}return t.delete(e),Fa(e,i)}function Fa(e,t){return t!==Ma&&Aa.set(e,t===Na),t}function Ia(e,t){let n=e.buckets.get(t);return n||(n=new WeakMap,e.buckets.set(t,n)),n}var La,Ra=[],za={alloc(e,t,n){let r=La;if(!r)return n;La=void 0;let i={value:n,issues:null};return r.set(t.value,i),Ra.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,n=(e,n)=>{if(n.direction!==`backward`&&Va(n,e.value))throw new Ta;return t(e,n)};e._zod.parse=n,e._zod.run===t&&(e._zod.run=n)})},attach(e){var t;let n,r=!1,i,a;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,o=(s,c)=>{if(n===void 0){let i=Pa(e,new Set,!1);if(i===ja)return e._zod.parse=t,e._zod.run===o&&(e._zod.run=t),t(s,c);i===Na||r?n=!0:r=!0}let l=s.value;if(!Oa(l))return t(s,c);let u=c[Ea];u||(u={buckets:new WeakMap,backEdges:void 0},c[Ea]=u);let d;i===c?d=a:(d=Ia(u,e),i=c,a=d);let f=d.get(l);if(f)return s.value=f.value,f.issues?f.issues.length&&s.issues.push(...ka(f.issues)):(s.memo=!0,u.backEdges??(u.backEdges=new WeakSet),u.backEdges.add(f.value)),s;La=d;let p=Ra.length,m=t(s,c);La=void 0;let h=Ra.length>p?Ra.pop():void 0;return m instanceof Promise?m.then(e=>(h&&(h.issues=e.issues.length?ka(e.issues):Da),e)):(h&&(h.issues=m.issues.length?ka(m.issues):Da),m)};e._zod.parse=o,e._zod.run===t&&(e._zod.run=o)})}};function Ba(){return za}function Va(e,t){let n=e[Ea]?.backEdges;return n!==void 0&&Oa(t)&&n.has(t)}var Ha=()=>{let e={string:{unit:`characters`,verb:`to have`},file:{unit:`bytes`,verb:`to have`},array:{unit:`items`,verb:`to have`},set:{unit:`items`,verb:`to have`},map:{unit:`entries`,verb:`to have`}};function t(t){return e[t]??null}let n={regex:`input`,email:`email address`,url:`URL`,emoji:`emoji`,uuid:`UUID`,uuidv4:`UUIDv4`,uuidv6:`UUIDv6`,nanoid:`nanoid`,guid:`GUID`,cuid:`cuid`,cuid2:`cuid2`,ulid:`ULID`,xid:`XID`,ksuid:`KSUID`,datetime:`ISO datetime`,date:`ISO date`,time:`ISO time`,duration:`ISO duration`,ipv4:`IPv4 address`,ipv6:`IPv6 address`,mac:`MAC address`,cidrv4:`IPv4 range`,cidrv6:`IPv6 range`,base64:`base64-encoded string`,base64url:`base64url-encoded string`,json_string:`JSON string`,e164:`E.164 number`,currency_code:`currency code`,credit_card:`credit card number`,iban:`IBAN`,jwt:`JWT`,template_literal:`input`},r={nan:`NaN`};function i(e,t){return e===`number`&&typeof t==`number`&&!Number.isFinite(t)?String(t):r[e]??e}return e=>{switch(e.code){case`invalid_type`:return`Invalid input: expected ${i(e.expected)}, received ${i(cn(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${zt(e.values[0])}`:`Invalid option: expected one of ${_t(e.values,`|`)}`;case`too_big`:{let n=e.exact?`exactly `:e.inclusive?`<=`:`<`,r=t(e.origin);return r?`Too big: expected ${e.origin??`value`} to have ${n}${e.maximum.toString()} ${r.unit??`elements`}`:`Too big: expected ${e.origin??`value`} to be ${n}${e.maximum.toString()}`}case`too_small`:{let n=e.exact?`exactly `:e.inclusive?`>=`:`>`,r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case`invalid_format`:{let t=e;return t.format===`starts_with`?`Invalid string: must start with "${t.prefix}"`:t.format===`ends_with`?`Invalid string: must end with "${t.suffix}"`:t.format===`includes`?`Invalid string: must include "${t.includes}"`:t.format===`regex`?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case`not_multiple_of`:return`Invalid number: must be a multiple of ${e.divisor}`;case`unrecognized_keys`:return`Unrecognized key${e.keys.length>1?`s`:``}: ${_t(e.keys,`, `)}`;case`invalid_key`:return`Invalid key in ${e.origin}`;case`invalid_union`:return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(` | `)}`:e.inclusive===!1?`Invalid input: more than one option matched`:`Invalid input`;case`invalid_element`:return`Invalid value in ${e.origin}`;default:return`Invalid input`}}};function Ua(){return{localeError:Ha()}}var Wa,Ga=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Ka(){return new Ga}(Wa=globalThis).__zod_globalRegistry??(Wa.__zod_globalRegistry=Ka());var qa=globalThis.__zod_globalRegistry;function Ja(e){return e.checks&&=[...e.checks],e}function Ya(e,t){return new e(Ja({type:`string`,...D(t)}))}function Xa(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...D(t)})}function Za(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...D(t)})}function Qa(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...D(t)})}function $a(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...D(t)})}function eo(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...D(t)})}function to(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...D(t)})}function no(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...D(t)})}function ro(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...D(t)})}function io(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...D(t)})}function ao(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...D(t)})}function oo(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...D(t)})}function so(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...D(t)})}function co(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...D(t)})}function lo(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...D(t)})}function uo(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...D(t)})}function fo(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...D(t)})}function po(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...D(t)})}function mo(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...D(t)})}function ho(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...D(t)})}function go(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...D(t)})}function _o(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...D(t)})}function vo(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...D(t)})}function yo(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...D(t)})}function bo(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...D(t)})}function xo(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...D(t)})}function So(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...D(t)})}function Co(e,t){return new e(Ja({type:`number`,checks:[],...D(t)}))}function wo(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...D(t)})}function To(e,t){return new e({type:`boolean`,...D(t)})}function Eo(e){return new e({type:`unknown`})}function Do(e,t){return new e({type:`never`,...D(t)})}function Oo(e,t){return new Fr({check:`less_than`,...D(t),value:e,inclusive:!1})}function ko(e,t){return new Fr({check:`less_than`,...D(t),value:e,inclusive:!0})}function Ao(e,t){return new Ir({check:`greater_than`,...D(t),value:e,inclusive:!1})}function jo(e,t){return new Ir({check:`greater_than`,...D(t),value:e,inclusive:!0})}function Mo(e,t){return new Lr({check:`multiple_of`,...D(t),value:e})}function No(e,t){return new zr({check:`max_length`,...D(t),maximum:e})}function Po(e,t){return new Br({check:`min_length`,...D(t),minimum:e})}function Fo(e,t){return new Vr({check:`length_equals`,...D(t),length:e})}function Io(e,t){return new Ur({check:`string_format`,format:`regex`,...D(t),pattern:e})}function Lo(e){return new Wr({check:`string_format`,format:`lowercase`,...D(e)})}function Ro(e){return new Gr({check:`string_format`,format:`uppercase`,...D(e)})}function zo(e,t){return new Kr({check:`string_format`,format:`includes`,...D(t),includes:e})}function Bo(e,t){return new qr({check:`string_format`,format:`starts_with`,...D(t),prefix:e})}function Vo(e,t){return new Jr({check:`string_format`,format:`ends_with`,...D(t),suffix:e})}function Ho(e){return new Yr({check:`overwrite`,tx:e})}function Uo(e){return Ho(t=>t.normalize(e))}function Wo(){return Ho(e=>e.trim())}function Go(){return Ho(e=>e.toLowerCase())}function Ko(){return Ho(e=>e.toUpperCase())}function qo(){return Ho(e=>jt(e))}function Jo(e,t,n){return new e({type:`array`,element:t,...D(n)})}function Yo(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...D(n)})}function Xo(e,t){let n=Zo(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(ln(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,`input`in r||(r.input=t.value),r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(ln(r))}},e(t.value,t)),t);return n}function Zo(e,t){let n=new P({check:`custom`,...D(t)});return n._zod.check=e,n}function Qo(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&wt(e,t,n[t]);return e}function $o(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??qa,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,intersections:[],deferred:[],external:e?.external??void 0}}function es(e,t,n,r,i){let a=typeof t.unrepresentable==`function`?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(a===`any`)return!1;if(a===void 0||a===`throw`)throw Error(i);return Object.assign(n,a),!0}function L(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,L(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Qo(o.schema,c),t.io===`input`&&R(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function ts(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function ns(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${ts(a)}`}}let i=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:`#`};let a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+ts(a)}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
|
|
54
|
+
|
|
55
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0])a(n);else{if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}(e.metadataRegistry.get(n[0])?.id||r.cycle||r.count>1&&e.reused===`ref`)&&a(n)}}e.external&&(e.sharedDefsExtractedFor=e.external)}function rs(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;rs(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var is=new Set([`type`,`properties`,`required`,`additionalProperties`]),as=[`oneOf`,`anyOf`];function os(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function ss(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!is.has(e))return null;t.push(n)}let n={},r=new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??os(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}wt(n,r,e.length===1?e[0]:ss(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=os(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function cs(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of is)if(t in e)return;let n=t.filter(e=>as.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=ss(t);else{let e=n[0],i=as.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>ss([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,Qo(e,r))}function ls(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Qo(i,s),Qo(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())rs(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])cs(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Qo(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,wt(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:ds(t,`input`,e.processors),output:ds(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function R(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return R(r.element,n);if(r.type===`set`)return R(r.valueType,n);if(r.type===`lazy`)return R(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return R(r.innerType,n);if(r.type===`intersection`)return R(r.left,n)||R(r.right,n);if(r.type===`record`||r.type===`map`)return R(r.keyType,n)||R(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:R(r.in,n)||R(r.out,n);if(r.type===`object`){for(let e in r.shape)if(R(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(R(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(R(e,n))return!0;return!!(r.rest&&R(r.rest,n))}return!1}var us=(e,t={})=>n=>{let r=$o({...n,processors:t});return L(e,r),ns(r,e),ls(r,e)},ds=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=$o({...i??{},target:a,io:t,processors:n});return L(e,o),ns(o,e),ls(o,e)},fs=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},ps=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},ms=(e,t)=>{fs(e,`minimum`,t),ps(e,`maximum`,t)},hs=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},gs=(e,t)=>{e.patterns??=new Set,e.patterns.add(t)},_s=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},vs=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},ys=(e,t)=>fs(e,`minimum`,t.minimum),bs=(e,t)=>ps(e,`maximum`,t.maximum),xs=e=>(t,n)=>{vs(t,n.format);let[r,i]=e[n.format];fs(t,`minimum`,r),ps(t,`maximum`,i)},Ss={greater_than:(e,t)=>fs(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>ps(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>hs(e,t.value),number_format:xs(Vt),bigint_format:xs(Ht),min_length:ys,max_length:bs,length_equals:(e,t)=>ms(e,t.length),min_size:ys,max_size:bs,size_equals:(e,t)=>ms(e,t.size),string_format:(e,t)=>{vs(e,t.format),t.pattern&&gs(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>_s(e,t.mime)};function z(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)Ss[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&fs(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&fs(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&ps(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&ps(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&hs(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&_s(t,i.mime);for(let e of i.patterns??[])gs(t,e);return t}var Cs={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},ws=new Map([[Mi,vr],[Pi,yr]]),Ts=e=>ws.get(e)??e,Es=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=z(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Cs[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(Ts);e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Ds=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=z(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):es(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...o]=n;a!==void 0&&(i.multipleOf=a),o.length&&(i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))])}},Os=(e,t,n,r)=>{n.type=`boolean`},ks=(e,t,n,r)=>{n.not={}},As=(e,t,n,r)=>{let i=e._zod.def,a=gt(i.entries);a.length===0?n.not={}:(a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a)},js=(e,t,n,r)=>{es(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},Ms=(e,t,n,r)=>{es(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},Ns=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=z(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=L(a.element,t,{...r,path:[...r.path,`items`]})};function Ps(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?Ps(t.out):t.type===`catch`?Ps(t.innerType):e._zod.optin}var Fs=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&es(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)wt(i.properties,e,L(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=[];for(let e of Object.keys(o)){let n=a.shape[e];(t.io===`input`?Ps(n)===void 0:n._zod.optout===void 0)&&s.push(e)}s.length>0&&(i.required=s),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=L(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Is=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>L(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Ls=(e,t,n,r)=>{let i=e._zod.def,a=L(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=L(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},Rs=(e,t,n,r)=>{let i=e._zod.def,a=L(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},zs=(e,t,n,r)=>{let i=e._zod.def;L(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Bs=Symbol();function Vs(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(es(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),Bs):JSON.parse(o)}var Hs=(e,t,n,r)=>{let i=e._zod.def;L(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=Vs(i.defaultValue,e,t,n,r);o!==Bs&&(n.default=o)},Us=(e,t,n,r)=>{let i=e._zod.def;L(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=Vs(i.defaultValue,e,t,n,r);o!==Bs&&(n._prefault=o)},Ws=(e,t,n,r)=>{let i=e._zod.def;L(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{es(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},Gs=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;L(o,t,r);let s=t.seen.get(e);s.ref=o},Ks=(e,t,n,r)=>{let i=e._zod.def;L(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},qs=(e,t,n,r)=>{let i=e._zod.def;L(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Js=new WeakSet([Object.prototype,Error.prototype]);function Ys(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}var B=j(`ZodError`,(e,t)=>{Mn.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);Js.has(n)||(Js.add(n),Ys(n,`format`,e=>t=>Fn(e,t)),Ys(n,`flatten`,e=>t=>Pn(e,t)),Ys(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,vt,2)}),Ys(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,vt,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),Xs=Ln(B),Zs=Rn(B),Qs=zn(B),$s=Vn(B),ec=qn(B),tc=Jn(B),nc=Yn(B),rc=Xn(B),ic=Zn(B),ac=Qn(B),oc=$n(B),sc=er(B);function cc(){M.localeError||N(Ua())}function lc(){M.memoizer||N({memoizer:Ba()})}var V=j(`ZodType`,(e,t)=>(cc(),F.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(T(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return E(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(yl(e,t))},superRefine(e,t){return this.check(bl(e,t))},overwrite(e){return this.check(Ho(e))},optional(){return tl(this)},exactOptional(){return rl(this)},nullable(){return al(this)},nullish(){return tl(al(this))},nonoptional(e){return dl(this,e)},array(){return G(this)},or(e){return Jc([this,e])},and(e){return Xc(this,e)},transform(e){return hl(this,$c(e))},default(e){return sl(this,e)},prefault(e){return ll(this,e)},catch(e){return pl(this,e)},pipe(e){return hl(this,e)},readonly(){return _l(this)},describe(e){let t=this.clone();return qa.add(t,{description:e}),t},meta(...e){if(e.length===0)return qa.get(this);let t=this.clone();return qa.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return dn(this,`~standard`,{...ei(this),jsonSchema:{input:ds(this,`input`),output:ds(this,`output`)}})},set"~standard"(e){k(this,`~standard`,e)},parse:function e(t,n){return Xs(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await Zs(this,t,n,{callee:e})},safeParse(e,t){return Qs(this,e,t)},async safeParseAsync(e,t){return $s(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){k(this,`spa`,e)},validate(e,t){return Wn(this,e,t)},validateAsync(e,t){return Kn(this,e,t)},encode:function e(t,n){return ec(this,t,n,{callee:e})},decode:function e(t,n){return tc(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await nc(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await rc(this,t,n,{callee:e})},safeEncode(e,t){return ic(this,e,t)},safeDecode(e,t){return ac(this,e,t)},async safeEncodeAsync(e,t){return oc(this,e,t)},async safeDecodeAsync(e,t){return sc(this,e,t)},toJSONSchema(e){return us(this,{})(e)},get description(){return qa.get(this)?.description},get _def(){return this._zod.def}}),uc=j(`_ZodString`,(e,t)=>{ti.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Es(e,t,n,r)},fn({format:e=>z(e).format??null,minLength:e=>z(e).minimum??null,maxLength:e=>z(e).maximum??null},{regex(...e){return this.check(Io(...e))},includes(...e){return this.check(zo(...e))},startsWith(...e){return this.check(Bo(...e))},endsWith(...e){return this.check(Vo(...e))},min(...e){return this.check(Po(...e))},max(...e){return this.check(No(...e))},length(...e){return this.check(Fo(...e))},nonempty(...e){return this.check(Po(1,...e))},lowercase(e){return this.check(Lo(e))},uppercase(e){return this.check(Ro(e))},trim(){return this.check(Wo())},normalize(...e){return this.check(Uo(...e))},toLowerCase(){return this.check(Go())},toUpperCase(){return this.check(Ko())},slugify(){return this.check(qo())}})),dc=j(`ZodString`,(e,t)=>{ti.init(e,t),uc.init(e,t)},{email(e){return this.check(Xa(gc,e))},url(e){return this.check(no(yc,e))},jwt(e){return this.check(vo(Pc,e))},emoji(e){return this.check(ro(bc,e))},guid(e){return this.check(Za(_c,e))},uuid(e){return this.check(Qa(vc,e))},uuidv4(e){return this.check($a(vc,e))},uuidv6(e){return this.check(eo(vc,e))},uuidv7(e){return this.check(to(vc,e))},nanoid(e){return this.check(io(xc,e))},cuid(e){return this.check(ao(Sc,e))},cuid2(e){return this.check(oo(Cc,e))},ulid(e){return this.check(so(wc,e))},base64(e){return this.check(ho(jc,e))},base64url(e){return this.check(go(Mc,e))},xid(e){return this.check(co(Tc,e))},ksuid(e){return this.check(lo(Ec,e))},ipv4(e){return this.check(uo(Dc,e))},ipv6(e){return this.check(fo(Oc,e))},cidrv4(e){return this.check(po(kc,e))},cidrv6(e){return this.check(mo(Ac,e))},e164(e){return this.check(_o(Nc,e))},datetime(e){return this.check(yo(fc,e))},date(e){return this.check(bo(pc,e))},time(e){return this.check(xo(mc,e))},duration(e){return this.check(So(hc,e))}});function H(e){return Ya(dc,e)}var U=j(`ZodStringFormat`,(e,t)=>{I.init(e,t),uc.init(e,t)}),fc=j(`ZodISODateTime`,(e,t)=>{bi.init(e,t),U.init(e,t)}),pc=j(`ZodISODate`,(e,t)=>{xi.init(e,t),U.init(e,t)}),mc=j(`ZodISOTime`,(e,t)=>{Si.init(e,t),U.init(e,t)}),hc=j(`ZodISODuration`,(e,t)=>{Ci.init(e,t),U.init(e,t)}),gc=j(`ZodEmail`,(e,t)=>{ii.init(e,t),U.init(e,t)}),_c=j(`ZodGUID`,(e,t)=>{ni.init(e,t),U.init(e,t)}),vc=j(`ZodUUID`,(e,t)=>{ri.init(e,t),U.init(e,t)}),yc=j(`ZodURL`,(e,t)=>{fi.init(e,t),U.init(e,t)}),bc=j(`ZodEmoji`,(e,t)=>{pi.init(e,t),U.init(e,t)}),xc=j(`ZodNanoID`,(e,t)=>{mi.init(e,t),U.init(e,t)}),Sc=j(`ZodCUID`,(e,t)=>{hi.init(e,t),U.init(e,t)}),Cc=j(`ZodCUID2`,(e,t)=>{gi.init(e,t),U.init(e,t)}),wc=j(`ZodULID`,(e,t)=>{_i.init(e,t),U.init(e,t)}),Tc=j(`ZodXID`,(e,t)=>{vi.init(e,t),U.init(e,t)}),Ec=j(`ZodKSUID`,(e,t)=>{yi.init(e,t),U.init(e,t)}),Dc=j(`ZodIPv4`,(e,t)=>{wi.init(e,t),U.init(e,t)}),Oc=j(`ZodIPv6`,(e,t)=>{Di.init(e,t),U.init(e,t)}),kc=j(`ZodCIDRv4`,(e,t)=>{Oi.init(e,t),U.init(e,t)}),Ac=j(`ZodCIDRv6`,(e,t)=>{Ai.init(e,t),U.init(e,t)}),jc=j(`ZodBase64`,(e,t)=>{Ni.init(e,t),U.init(e,t)}),Mc=j(`ZodBase64URL`,(e,t)=>{Ii.init(e,t),U.init(e,t)}),Nc=j(`ZodE164`,(e,t)=>{Li.init(e,t),U.init(e,t)}),Pc=j(`ZodJWT`,(e,t)=>{zi.init(e,t),U.init(e,t)}),Fc=j(`ZodNumber`,(e,t)=>{Bi.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ds(e,t,n,r),e.isFinite=!0},fn({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=z(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=z(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=z(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>z(e).format??null},{gt(e,t){return this.check(Ao(e,t))},gte(e,t){return this.check(jo(e,t))},min(e,t){return this.check(jo(e,t))},lt(e,t){return this.check(Oo(e,t))},lte(e,t){return this.check(ko(e,t))},max(e,t){return this.check(ko(e,t))},int(e){return this.check(Rc(e))},safe(e){return this.check(Rc(e))},positive(e){return this.check(Ao(0,e))},nonnegative(e){return this.check(jo(0,e))},negative(e){return this.check(Oo(0,e))},nonpositive(e){return this.check(ko(0,e))},multipleOf(e,t){return this.check(Mo(e,t))},step(e,t){return this.check(Mo(e,t))},finite(){return this}}));function Ic(e){return Co(Fc,e)}var Lc=j(`ZodNumberFormat`,(e,t)=>{Vi.init(e,t),Fc.init(e,t)});function Rc(e){return wo(Lc,e)}var zc=j(`ZodBoolean`,(e,t)=>{Hi.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Os(e,t,n,r)});function W(e){return To(zc,e)}var Bc=j(`ZodUnknown`,(e,t)=>{Ui.init(e,t),V.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function Vc(){return Eo(Bc)}var Hc=j(`ZodNever`,(e,t)=>{Wi.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ks(e,t,n,r)});function Uc(e){return Do(Hc,e)}var Wc=j(`ZodArray`,(e,t)=>{lc(),Ji.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ns(e,t,n,r),e.element=t.element},{min(e,t){return this.check(Po(e,t))},nonempty(e){return this.check(Po(1,e))},max(e,t){return this.check(No(e,t))},length(e,t){return this.check(Fo(e,t))},unwrap(){return this.element}});function G(e,t){return Jo(Wc,e,t)}var Gc=j(`ZodObject`,(e,t)=>{lc(),ea.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fs(e,t,n,r),vn(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return q(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(T(this._zod.def,{catchall:e}))},passthrough(){return this.clone(T(this._zod.def,{catchall:Vc()}))},loose(){return this.clone(T(this._zod.def,{catchall:Vc()}))},strict(){return this.clone(T(this._zod.def,{catchall:Uc()}))},strip(){return this.clone(T(this._zod.def,{catchall:void 0}))},extend(e){return Kt(this,e)},safeExtend(e){return Jt(this,e)},merge(e){return Yt(this,e)},pick(e){return Ut(this,e)},omit(e){return Gt(this,e)},partial(...e){return Xt(el,this,e[0])},exactPartial(...e){return Xt(nl,this,e[0],`exactPartial`)},required(...e){return Zt(ul,this,e[0])}});function K(e,t){return new Gc({type:`object`,shape:e??{},...D(t)})}function Kc(e,t){return new Gc({type:`object`,shape:e,catchall:Vc(),...D(t)})}var qc=j(`ZodUnion`,(e,t)=>{na.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Is(e,t,n,r),e.options=t.options});function Jc(e,t){return new qc({type:`union`,options:e,...D(t)})}var Yc=j(`ZodIntersection`,(e,t)=>{ra.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ls(e,t,n,r)});function Xc(e,t){return new Yc({type:`intersection`,left:e,right:t})}var Zc=j(`ZodEnum`,(e,t)=>{oa.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>As(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new Zc({...t,checks:[],...D(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new Zc({...t,checks:[],...D(r),entries:i})}});function q(e,t){return new Zc({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...D(t)})}var Qc=j(`ZodTransform`,(e,t)=>{lc(),sa.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ms(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new En(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(ln(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(ln(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function $c(e){return new Qc({type:`transform`,transform:e})}var el=j(`ZodOptional`,(e,t)=>{la.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function tl(e){return new el({type:`optional`,innerType:e})}var nl=j(`ZodExactOptional`,(e,t)=>{ua.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function rl(e){return new nl({type:`optional`,innerType:e})}var il=j(`ZodNullable`,(e,t)=>{da.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function al(e){return new il({type:`nullable`,innerType:e})}var ol=j(`ZodDefault`,(e,t)=>{fa.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Hs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function sl(e,t){return new ol({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():It(t)}})}var cl=j(`ZodPrefault`,(e,t)=>{ma.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Us(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ll(e,t){return new cl({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():It(t)}})}var ul=j(`ZodNonOptional`,(e,t)=>{ha.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function dl(e,t){return new ul({type:`nonoptional`,innerType:e,...D(t)})}var fl=j(`ZodCatch`,(e,t)=>{va.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ws(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function pl(e,t){return new fl({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:bn(t)})}var ml=j(`ZodPipe`,(e,t)=>{ya.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gs(e,t,n,r),e.in=t.in,e.out=t.out});function hl(e,t){return new ml({type:`pipe`,in:e,out:t})}var gl=j(`ZodReadonly`,(e,t)=>{xa.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ks(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function _l(e){return new gl({type:`readonly`,innerType:e})}var vl=j(`ZodCustom`,(e,t)=>{Ca.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>js(e,t,n,r)});function yl(e,t={}){return Yo(vl,e,t)}function bl(e,t){return Xo(e,t)}var xl={gatewayUrl:`davecode.gatewayUrl`,token:`davecode.token`,theme:`davecode.theme`,dataMode:`davecode.dataMode`,sidebarCollapsed:`davecode.sidebarCollapsed`};function Sl(e){try{return window.localStorage.getItem(e)}catch{return null}}function Cl(e,t){try{t===``?window.localStorage.removeItem(e):window.localStorage.setItem(e,t)}catch{}}function wl(){let e=Sl(xl.theme),t=Sl(xl.dataMode);return{gatewayUrl:Sl(xl.gatewayUrl)??``,token:Sl(xl.token)??``,theme:e===`light`||e===`system`?e:`dark`,dataMode:t===`live`||t===`mock`?t:`auto`,sidebarCollapsed:Sl(xl.sidebarCollapsed)===`1`}}var Tl=typeof window>`u`?Dl():wl(),El=new Set;function Dl(){return{gatewayUrl:``,token:``,theme:`dark`,dataMode:`auto`,sidebarCollapsed:!1}}function Ol(){return Tl}function kl(e){Tl={...Tl,...e};for(let[t,n]of Object.entries(e)){let e=xl[t];t===`sidebarCollapsed`?Cl(e,n?`1`:``):t===`theme`?Cl(e,String(n)):Cl(e,String(n??``))}for(let e of El)e()}function Al(e){return El.add(e),()=>El.delete(e)}function jl(){return(0,i.useSyncExternalStore)(Al,Ol,Ol)}function Ml(){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 Nl(e){return e===`system`?window.matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`:e}function Pl(e){let t=()=>{document.documentElement.dataset.theme=Nl(e)};if(t(),e!==`system`)return()=>{};let n=window.matchMedia(`(prefers-color-scheme: light)`);return n.addEventListener(`change`,t),()=>n.removeEventListener(`change`,t)}var Fl=[`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`,`orchestrator.run`,`orchestrator.output`,`log`];function Il(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 Ll(e){try{let t=JSON.parse(e);if(t&&typeof t==`object`&&typeof t.type==`string`)return t}catch{}return null}function Rl(e,t){let n=null,r,i=0,a=!1,o,s=e=>t.onStatus?.({...e,attempt:i,lastEventAt:o}),c=e=>{let n=Ll(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 Fl)n.addEventListener(e,c);n.onerror=()=>{if(n?.close(),n=null,a)return;i+=1;let e=Il(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 J=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&&!zl.has(this.code)}},zl=new Set([`network`,`bad_response`,`gateway_unreachable`]);function Bl(e){return e instanceof J}function Vl(e,t){return`${e.replace(/\/+$/,``)}${t}`}function Hl({baseUrl:e,token:t}){async function n(n,r,i){let a={Accept:`application/json`};t&&(a.Authorization=`Bearer ${t}`),(i!==void 0||n!==`GET`)&&(a[`Content-Type`]=`application/json`);let o;try{o=await fetch(Vl(e,r),{method:n,headers:a,body:i===void 0?void 0:JSON.stringify(i)})}catch(e){throw new J(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 J(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 J(o.status,`gateway_unreachable`,`Gateway unreachable (proxy answered ${o.status})`):new J(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=>Rl(Vl(e,`/api/events${t?`?token=${encodeURIComponent(t)}`:``}`),n)}}function Ul(e){return Bl(e)?e.status===401?`Unauthorized: set the gateway token in Settings.`:e.message:e instanceof Error?e.message:String(e)}function Wl(e){return e.type===`request.started`||e.type===`request.completed`||e.type===`request.failed`||e.type===`router.failover`}function Gl(e,t,n=``){return{requestId:e,model:n,startedTs:t,updatedTs:t,attempts:[],outcome:`pending`,failovers:0,exhausted:!1}}function Kl(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 ql=2e3;function Jl(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)<=ql)return a}return-1}function Yl(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 Xl(e,t){let n=e??Gl(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,Kl(r.attempts,t.accountId)===-1&&Jl(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=Kl(r.attempts,t.accountId);e===-1&&(e=Jl(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=Kl(r.attempts,t.accountId);e===-1&&(e=Jl(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=Yl(r),r}function Zl(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 Ql(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 $l(e){let t=e.attempts[e.attempts.length-1];if(t?.endedTs)return t.endedTs-e.startedTs}function eu(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 tu=600,nu=400,ru=3e3,iu=4e3;function au(e){return Math.floor(e/6e4)*6e4}function ou(e){return JSON.stringify(e)}var su=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=ou(e);if(this.seen.has(t))return!1;if(this.seen.add(t),this.seenOrder.push(t),this.seenOrder.length>iu){let e=this.seenOrder.shift();e&&this.seen.delete(e)}return this.pending.push(e),this.schedule(),!0}seedRecords(e){for(let t of Zl(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(Wl(t)&&this.chainIndex.set(t.requestId,Xl(this.chainIndex.get(t.requestId),t)),t.type===`request.completed`){let e=au(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>nu){for(let e of i.slice(nu))this.chainIndex.delete(e.requestId);i=i.slice(0,nu)}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>tu?t.slice(-600):t,chains:i,logs:n.length>ru?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))}},cu=864e5,lu=[`1m`,`5h`,`24h`],uu={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}},du=e=>new Date(e).toISOString().slice(0,10);function fu(e,t){let n=uu[e];if(n)return{...n.info,paidAt:du(t-n.paidDaysAgo*cu),renewsAt:du(t+n.renewsInDays*cu)}}function pu(e,t,n){let r=null,i;for(let e of lu){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)/cu))}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 mu(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(`
|
|
56
|
+
`)}function hu(e,t,n){let r=e.map(e=>pu(e,t(e),n));return{generatedAt:new Date(n).toISOString(),accounts:r,context:mu(r,n)}}var gu={anthropic:{kind:`anthropic`,label:`Anthropic API`,icon:rt,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:st,auth:`api-key`,blurb:`GPT models with an OpenAI API key.`,secretLabel:`API key`,secretPlaceholder:`sk-…`},gemini:{kind:`gemini`,label:`Gemini API`,icon:dt,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:lt,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:ht,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:ht,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:pt,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:pt,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:at,auth:`browser`,blurb:`Drives a Gemini web session through a dedicated Chromium profile.`,experimental:!0,subscription:!0}},_u=[`anthropic`,`openai`,`gemini`,`openai-compatible`,`claude-cli`,`codex-cli`,`antigravity-cli`,`gemini-cli`,`gemini-web`];function vu(e){return gu[e]??{...gu[`openai-compatible`],kind:e,label:e}}var yu=new Set([`acc_claude_pro`]),bu=6e3;function xu(e){let{auth:t}=vu(e.provider);return t===`cli`?`cli-login`:t===`browser`?`browser`:`api-key`}function Su(e,t,n){let r=xu(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 Cu=e=>e,wu=[{account:{id:`acc_claude_pro`,provider:`claude-cli`,label:`Claude Pro — personal`,enabled:!0,priority:10,weight:3,limits:Cu({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:Cu({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:Cu({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:Cu({requestsDaily:100}),config:{profile:`~/.davecode/profiles/acc_gemini_web`}},curve5h:{from:0,to:0},curve24h:{from:0,to:0},latency:[2400,14],failRate:.05}],Tu=[{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`}]}],Eu=[[`auto`,.62],[`fast`,.24],[`reasoning`,.06],[`local`,.08]],Y=(e,t)=>new Date(t-e*6e4).toISOString();function Du(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:Y(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:Y(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:Y(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:Y(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:Y(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:Y(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:Y(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:Y(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:Y(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 Ou(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
|
|
57
|
+
|
|
58
|
+
_Last updated: ${new Date(t).toISOString().slice(0,10)} by the autonomous runner_
|
|
59
|
+
|
|
60
|
+
## Current focus
|
|
61
|
+
|
|
62
|
+
${r?`**${r.id}**: ${r.title}. Branch \`${r.branch??`davecode/task-${r.id}`}\`.`:`Idle: no unblocked tasks.`}
|
|
63
|
+
|
|
64
|
+
## Done
|
|
65
|
+
|
|
66
|
+
${n.map(e=>`- [x] \`${e.id}\` ${e.title}`).join(`
|
|
67
|
+
`)}
|
|
68
|
+
|
|
69
|
+
## Blockers
|
|
70
|
+
|
|
71
|
+
${i.length?i.map(e=>`- \`${e.id}\` failed after ${e.attempts??3} attempts. ${e.notes??``}`).join(`
|
|
72
|
+
`):`None.`}
|
|
73
|
+
|
|
74
|
+
## Next up
|
|
75
|
+
|
|
76
|
+
1. \`p1-gateway\` once the router merges.
|
|
77
|
+
2. \`p4-runner\` (needs \`p2-router\` and \`p3-brain\`).
|
|
78
|
+
3. Decide the Codex CLI auth flow so \`release-0.1.0\` is unblocked.
|
|
79
|
+
|
|
80
|
+
## Decisions log
|
|
81
|
+
|
|
82
|
+
| Date | Decision |
|
|
83
|
+
| :--- | :------- |
|
|
84
|
+
| 2026-10-06 | Node ≥ 22.12 + pnpm monorepo; \`better-sqlite3\`; Fastify; Ink TUI + Vite/React dashboard |
|
|
85
|
+
| 2026-10-06 | ToS-sensitive features ship behind \`experimental.*\` flags, off by default |
|
|
86
|
+
| 2026-10-06 | Judge defaults to deterministic checks (free) |
|
|
87
|
+
`}var ku=`# DaveCode: architecture
|
|
88
|
+
|
|
89
|
+
DaveCode is a **local-first** engine with two jobs: an OpenAI-compatible **gateway** with
|
|
90
|
+
quota-aware routing and hot failover, and an **autonomous runner** that walks a task DAG.
|
|
91
|
+
|
|
92
|
+
## Packages
|
|
93
|
+
|
|
94
|
+
| Package | Responsibility |
|
|
95
|
+
| :------ | :------------- |
|
|
96
|
+
| \`@davecode/core\` | Contracts, storage, identity, quotas, providers, router, brain, runner |
|
|
97
|
+
| \`@davecode/server\` | Fastify gateway: \`/v1\`, \`/api\`, SSE, serves the dashboard |
|
|
98
|
+
| \`davecode\` | CLI and Ink TUI |
|
|
99
|
+
| \`@davecode/ui\` | This dashboard |
|
|
100
|
+
|
|
101
|
+
## Routing
|
|
102
|
+
|
|
103
|
+
1. Resolve candidates from the route, provider prefix or bare model.
|
|
104
|
+
2. Drop disabled, cooling-down or saturated accounts.
|
|
105
|
+
3. Score: priority, then weight × headroom. Backpressure above **85 %**, shift above **90 %**.
|
|
106
|
+
4. On \`rate_limit\`, \`unavailable\`, \`timeout\`… cool down and fail over before the first byte.
|
|
107
|
+
`,Au=new Set([`planned`,`succeeded`,`failed`,`cancelled`,`budget_exhausted`]),ju=[{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.`}],Mu={maxRounds:4,maxTasks:12,maxTokens:1e6},Nu=1800;function Pu(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 Fu=class{host;list=[];constructor(e){this.host=e}seed(e){let t=t=>new Date(e-t*6e4).toISOString(),n=`goal_5e1d0c2a9b77`,r=Pu(`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:{...Mu,tokensUsed:38420},roles:ju,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 J(400,`invalid_body`,`objective: must not be empty`);let n=this.list.find(e=>!Au.has(e.status));if(n)throw new J(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??Mu.maxRounds,Mu.maxRounds),maxTasks:Math.min(e.maxTasks??Mu.maxTasks,Mu.maxTasks),maxTokens:Math.min(e.maxTokens??Mu.maxTokens,Mu.maxTokens),tokensUsed:0},roles:ju,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(Nu,()=>this.plan(i)),i}cancel(e){let t=this.list.find(t=>t.id===e);if(!t)throw new J(404,`not_found`,`unknown goal "${e}"`);if(Au.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=>!Au.has(e.status));if(t)throw new J(409,`busy`,`goal ${t.id} is still running; cancel it first`);let n=this.list.find(t=>t.id===e);if(!n)throw new J(404,`not_found`,`unknown goal "${e}"`);if(n.status!==`planned`)throw new J(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(Nu,()=>this.step(n)),n}artifact(e,t){let n=this.list.find(t=>t.id===e);if(!n)throw new J(404,`not_found`,`unknown goal "${e}"`);let r=n.tasks.find(e=>e.id===t);if(!r?.artifact)throw new J(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(`
|
|
108
|
+
`)}}plan(e){Au.has(e.status)||(e.tasks=Pu(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(Nu,()=>this.step(e))))}step(e){if(Au.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`?Nu*3:Nu,()=>this.step(e))):(e.status=`reviewing`,this.update(e),this.log(e,`info`,`reviewing round ${e.round}`,`reviewer`),this.host.later(Nu,()=>{Au.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}:{}})}},Iu=/^[a-z0-9][a-z0-9-]*$/,Lu=0,Ru=e=>`${e}-${++Lu}`;function zu(e=`anthropic`){return{key:Ru(`t`),provider:e,model:``,accountId:``}}function Bu(e=``){return{key:Ru(`r`),name:e,description:``,targets:[zu()]}}function Vu(e,t){let n=e.map(e=>({key:Ru(`r`),name:e.name,description:e.description??``,targets:e.targets.map(e=>({key:Ru(`t`),provider:e.provider,model:e.model,accountId:e.accountId??``}))}));return{routes:n,defaultKey:n.find(e=>e.name===t)?.key??null}}function Hu(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 Uu(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 Wu(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 Gu(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?Iu.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 Ku(e,t,n){return JSON.stringify(Hu(e))!==JSON.stringify(qu(t,n))}function qu(e,t){return Hu(Vu(e,t))}var Ju=/^[a-z0-9]+(?:[-_.][a-z0-9]+)*$/;function Yu(e,t){return e?Ju.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 Xu(e){return e.toLowerCase().normalize(`NFKD`).replace(/[̀-ͯ]/g,``).replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,48).replace(/-+$/g,``)}function Zu(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 Qu={PENDING:[`IN_PROGRESS`],IN_PROGRESS:[`SUCCESS`,`FAILED`,`PENDING`],FAILED:[`PENDING`],SUCCESS:[`PENDING`]};function $u(e,t){return e===t||Qu[e].includes(t)}function ed(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 td(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 nd(e,t){if(t===void 0)return[...e];let n=td(e,t);return e.filter(e=>e.id!==t&&!n.has(e.id))}function rd(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 id(){return{id:``,title:``,description:``,acceptance:``,priority:``,notes:``,dependsOn:[]}}function ad(e){return{id:e.id,title:e.title,description:e.description??``,acceptance:(e.acceptance??[]).join(`
|
|
109
|
+
`),priority:e.priority===void 0?``:String(e.priority),notes:e.notes??``,dependsOn:[...e.dependsOn]}}function od(e){return e.split(/\r?\n/).map(e=>e.replace(/^\s*(?:[-*]|\d+[.)])\s+/,``).trim()).filter(Boolean)}function sd(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 cd(e,t,n){let r={};if(n===void 0){let n=Yu(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=sd(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=rd(t,a,e.dependsOn);n&&(r.dependsOn=`Would create a dependency cycle: ${n.join(` → `)}.`)}}return r}function ld(e){let t=e.description.trim(),n=od(e.acceptance),{value:r}=sd(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 ud=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]);function dd(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=od(t.acceptance);ud(o,e.acceptance??[])||(n.acceptance=o.length>0?o:null);let{value:s}=sd(t.priority);return s!==e.priority&&(n.priority=s??null),ud(t.dependsOn,e.dependsOn)||(n.dependsOn=t.dependsOn),n}function fd(e){return Object.keys(e).length===0}var X=6e4,pd=.85,md=.9,hd=4;function gd(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 _d={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`]},vd={"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`]},yd={"p2-router":1,"p1-gateway":0,"p4-runner":2,"p5-cli":1},bd=class{mode=`mock`;rng;clock;t0;opts;seeds=new Map;accounts=[];records=[];taskList;routeList=structuredClone(Tu);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(yu);constructor(e={}){this.rng=gd(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 wu){this.seeds.set(e.account.id,e);let t=fu(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=Du(this.t0),this.runnerStatus={state:`implementing`,taskId:`p2-router`,repairCycle:1,startedAt:new Date(this.t0-4.2*X).toISOString()},this.generateHistory(),this.opts.runnerAvailable&&this.seedRunnerHistory(),this.goalSim=new Fu({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 J(400,`invalid_body`,`label: must not be empty`);if(e.provider===`gemini-web`&&!this.opts.geminiWeb)throw new J(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 hu(this.accounts,t=>this.accountUsage(t,e),e)})}connection(e){return this.respond(()=>Su(this.findAccount(e),this.loggedIn.has(e),this.clock()))}connect(e){return this.respond(()=>{let t=Su(this.findAccount(e),this.loggedIn.has(e),this.clock());if(t.method!==`cli-login`)throw new J(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(bu,()=>{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(!Iu.test(e.name))throw new J(400,`invalid_body`,`${r}.name: route names are lowercase kebab-case`);if(t.has(e.name))throw new J(400,`invalid_body`,`${r}.name: duplicate route name "${e.name}"`);if(t.add(e.name),e.targets.length===0)throw new J(400,`invalid_body`,`${r}.targets: at least one target is required`);e.targets.forEach((t,n)=>{if(!t.model.trim())throw new J(400,`invalid_body`,`${r}.targets.${n}.model: required`);if(t.accountId&&!this.accounts.some(e=>e.id===t.accountId))throw new J(400,`unknown_account`,`route "${e.name}" pins unknown account "${t.accountId}"`)})}),e.defaultRoute!==void 0&&!t.has(e.defaultRoute))throw new J(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(!Ju.test(e.id))throw new J(400,`invalid_body`,`id: must be lowercase kebab-case or snake_case`);if(!e.title.trim())throw new J(400,`invalid_body`,`title: required`);if(this.taskList.some(t=>t.id===e.id))throw new J(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 J(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(!$u(n.status,t.status))throw new J(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 J(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 J(409,`has_dependents`,`cannot delete "${e}": ${n.map(e=>`"${e}"`).join(`, `)} depend on it`,{dependents:n});if(t.status===`IN_PROGRESS`)throw new J(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 J(400,`self_dependency`,`task "${e}" depends on itself`);if(!this.taskList.some(e=>e.id===n))throw new J(400,`unknown_dependency`,`task "${e}" depends on unknown task "${n}"`)}let n=rd(this.taskList,e,t);if(n)throw new J(400,`cycle`,`dependency cycle: ${n.join(` → `)}`,{cycle:n})}brain(){return this.respond(()=>({state:Ou(this.taskList,this.clock()),architecture:ku}))}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/X,n=11+4*Math.sin(t/9)+2.5*Math.sin(t/3.3);return Math.max(3,n)}scheduleRequest(){let e=X/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]=_d[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<hd?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 Eu){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>=md?.12:t>=pd?.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>=md?p+=.5:f>=pd&&(p+=.16),r||(p*=.8),this.rng()<p){let n=e.provider===`openai-compatible`?`timeout`:f>=pd||this.rng()<.7?`rate_limit`:`unavailable`;return{account:e,target:t,ok:!1,errorKind:n,status:_d[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*X,t=this.t0-6*X;for(let n=e;n<this.t0;n+=X){let e=n>this.t0-24*X&&n<this.t0-18*X?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()*X;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<=hd;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]=_d[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-X&&n.ts<=t),i=this.records.filter(n=>n.accountId===e.id&&n.ts>t-60*X),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>=md?2:+(n>=pd);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:_d.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*X/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 J(501,`goals_unavailable`,`Goal mode is not available; start the gateway inside a project (davecode init)`)}assertRunner(){if(!this.opts.runnerAvailable)throw new J(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 J(404,`task_not_found`,`unknown task "${e}"`);if(t.status!==`PENDING`)throw new J(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 J(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=vd[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<(yd[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 ${vd[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*X;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 J(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())}},xd;function Sd(){if(!xd){let e=typeof window>`u`?new URLSearchParams:new URLSearchParams(window.location.search||window.location.hash.split(`?`)[1]);xd=new bd({runnerAvailable:e.get(`runner`)!==`off`,geminiWeb:e.get(`geminiWeb`)===`1`})}return xd}var Cd=[`claude`,`codex`,`agy`],wd=`plan`,Td=q([`claude`,`codex`,`agy`]),Ed=K({agent:Td,available:W()}),Dd=Kc({id:H(),title:H(),agent:Td,status:q([`pending`,`running`,`done`,`failed`,`conflict`,`cancelled`,`skipped`]),dependsOn:G(H()).default([])}),Od=Kc({id:H(),objective:H(),status:q([`planning`,`running`,`done`,`failed`,`cancelled`]),agents:G(Td).default([]),tasks:G(Dd).default([]),createdAt:H(),updatedAt:H()}),kd=Jc([K({run:Od}),Od]);function Ad(e){let t=kd.safeParse(e);if(!t.success)throw new J(0,`bad_response`,`Unexpected orchestrator response.`);return`run`in t.data?t.data.run:t.data}function jd(e,t){return`${e.replace(/\/+$/,``)}${t}`}function Md(e,t=!1){return{Accept:`application/json`,...e?{Authorization:`Bearer ${e}`}:{},...t?{"Content-Type":`application/json`}:{}}}async function Nd(e,t,n,r,i){let a;try{a=await fetch(jd(e,`/api/orchestrator${r}`),{method:n,headers:Md(t,n===`POST`),cache:`no-store`,...i===void 0?{}:{body:JSON.stringify(i)}})}catch(e){throw new J(0,`network`,`Gateway unreachable: ${e.message}`)}if(a.status===204)return;let o=await a.text(),s;try{s=o?JSON.parse(o):void 0}catch{throw new J(a.status,`bad_response`,`Unexpected orchestrator response.`)}if(!a.ok){let e=s?.error;throw new J(a.status,e?.code??`http_${a.status}`,e?.message??`The orchestrator request failed (${a.status}).`)}return s}async function Pd(e,t){try{let n=K({agents:G(Ed)}).safeParse(await Nd(e,t,`GET`,`/agents`));return n.success?n.data.agents:null}catch{return null}}async function Fd(e,t){let n=K({runs:G(Od)}).safeParse(await Nd(e,t,`GET`,`/runs`));if(!n.success)throw new J(0,`bad_response`,`Unexpected orchestrator response.`);return n.data.runs}async function Id(e,t,n){return Ad(await Nd(e,t,`GET`,`/runs/${encodeURIComponent(n)}`))}async function Ld(e,t,n){return Ad(await Nd(e,t,`POST`,`/runs`,n))}async function Rd(e,t,n){try{return await Nd(e,t,`POST`,`/runs/${encodeURIComponent(n)}/cancel`),!0}catch(e){if(e instanceof J&&e.status===409&&e.code===`not_active`)return!1;throw e}}async function zd(e,t,n){return Ad(await Nd(e,t,`POST`,`/runs/${encodeURIComponent(n)}/apply`))}var Bd={runs:{},outputs:{}};function Vd(e,t){return`${e}\u0000${t}`}function Hd(e){return e.type===`orchestrator.run`||e.type===`orchestrator.output`}var Ud={lines:[],open:!1,next:0};function Wd(e,t){let n=e.lines.slice(),{open:r,next:i}=e,a=t.text.replace(/\r\n?/g,`
|
|
110
|
+
`);if(t.kind===`text`){if(a===``)return e;let t=a.split(`
|
|
111
|
+
`),o=t.at(-1)===``;o&&t.pop(),t.forEach((e,t)=>{let a=n.at(-1);t===0&&r&&a?n[n.length-1]={...a,text:a.text+e}:n.push({id:i++,kind:`text`,text:e})}),r=!o}else{let e=a.replace(/\n+$/,``);e!==``&&n.push({id:i++,kind:t.kind,text:e}),r=!1}return{lines:n.length>500?n.slice(-500):n,open:r,next:i}}function Gd(e,t){if(t.type===`orchestrator.run`){let n=t.run;return!n||typeof n.id!=`string`?e:{...e,runs:{...e.runs,[n.id]:n}}}if(t.type===`orchestrator.output`){let{runId:n,taskId:r,output:i}=t;if(typeof n!=`string`||typeof r!=`string`||!i||typeof i.text!=`string`)return e;let a=Vd(n,r),o=Wd(e.outputs[a]??Ud,i);return{...e,outputs:{...e.outputs,[a]:o}}}return e}function Kd(e,t){let n=e.runs;for(let r of t){let t=n[r.id];t&&t.updatedAt>r.updatedAt||(n===e.runs&&(n={...e.runs}),n[r.id]=r)}return n===e.runs?e:{...e,runs:n}}function qd(e){return Object.values(e.runs).sort((e,t)=>e.createdAt===t.createdAt?e.id<t.id?1:-1:e.createdAt<t.createdAt?1:-1)}function Jd(e,t,n,r=[]){return e.outputs[Vd(t,n)]?.lines??r}var Yd=class{flushMs;state=Bd;pending=[];timer;listeners=new Set;constructor(e=100){this.flushMs=e}getState=()=>this.state;subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));ingest(e){this.pending.push(e),this.timer===void 0&&(this.timer=setTimeout(()=>{this.timer=void 0,this.flush()},this.flushMs))}upsert(e){this.flush(),this.set(Kd(this.state,[e]))}hydrate(e){this.flush(),this.set(Kd(this.state,e))}flush(){if(this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0),this.pending.length===0)return;let e=this.pending;this.pending=[],this.set(e.reduce(Gd,this.state))}dispose(){this.timer!==void 0&&clearTimeout(this.timer),this.timer=void 0}set(e){if(e!==this.state){this.state=e;for(let e of this.listeners)e()}}};function Xd(e){return e.status===`planning`||e.status===`running`}function Zd(e){return e.status===`done`&&!e.appliedAt&&!!e.integrationBranch}function Qd(e){return!!e?.some(e=>e.available)}function $d(e){return Cd.filter(t=>e?.some(e=>e.agent===t&&e.available))}function ef(e,t){let n=e.includes(t);return Cd.filter(r=>r===t?!n:e.includes(r))}function tf(e,t,n,r){let i=e.trim(),a=$d(n),o=a.filter(e=>t.includes(e));if(!i||o.length===0)return null;let s=r&&a.includes(r)?r:void 0;return{objective:i,agents:o,...s?{planner:s}:{}}}function nf(e){return e.status===`planning`?`running`:e.tasks.length>0?`done`:e.status===`cancelled`?`cancelled`:e.status===`failed`?`failed`:`done`}function rf(e){return e.status===`planning`||e.tasks.length===0?wd:(e.tasks.find(e=>e.status===`running`)??e.tasks.find(e=>e.status===`failed`||e.status===`conflict`)??e.tasks[0])?.id??`plan`}function af(e,t){if(!e.startedAt)return;let n=Date.parse(e.startedAt);if(Number.isNaN(n))return;let r=e.finishedAt?Date.parse(e.finishedAt):t;return Math.max(0,(Number.isNaN(r)?t:r)-n)}function of(e,t){let n=Date.parse(e.createdAt);if(Number.isNaN(n))return;if(e.status===`planning`)return Math.max(0,t-n);let r=e.tasks.map(e=>e.startedAt?Date.parse(e.startedAt):NaN).filter(e=>!Number.isNaN(e)).sort((e,t)=>e-t)[0]??Date.parse(e.updatedAt);return Number.isNaN(r)?void 0:Math.max(0,r-n)}var sf={planning:`planning`,running:`running`,done:`done`,failed:`failed`,cancelled:`cancelled`},cf={pending:`waiting`,running:`running`,done:`done`,failed:`failed`,conflict:`conflict`,cancelled:`cancelled`,skipped:`skipped`},lf=(0,i.createContext)(null),uf=15e3;function df(e){return Ml()?{mode:`mock`,reason:`forced`}:e===`mock`?{mode:`mock`,reason:`setting`}:e===`live`?{mode:`live`,reason:null}:{mode:`probing`,reason:null}}function ff({children:e}){let t=jl(),n=s(),[r,o]=(0,i.useState)(()=>df(t.dataMode)),[c,l]=(0,i.useState)(),[u,d]=(0,i.useState)(0),[f,p]=(0,i.useState)({state:`connecting`,attempt:0}),[m,h]=(0,i.useState)(!1);(0,i.useEffect)(()=>{o(df(t.dataMode))},[t.dataMode]);let g=(0,i.useMemo)(()=>Hl({baseUrl:t.gatewayUrl,token:t.token}),[t.gatewayUrl,t.token]);(0,i.useEffect)(()=>{if(Ml()||t.dataMode!==`auto`)return;let e=!1,n,r=async()=>{try{if(await g.health(),e)return;h(!1),l(void 0),o({mode:`live`,reason:null})}catch(t){if(e)return;if(Bl(t)&&t.reachable){h(t.status===401),o({mode:`live`,reason:null});return}l(t instanceof Error?t.message:String(t)),o({mode:`mock`,reason:`unreachable`}),n=window.setTimeout(r,uf)}};return r(),()=>{e=!0,window.clearTimeout(n)}},[g,t.dataMode,u]);let _=r.mode===`mock`?Sd():g,v=r.mode===`mock`?`mock`:`live:${t.gatewayUrl}:${t.token?`auth`:`anon`}`,y=(0,i.useMemo)(()=>new su,[v]),b=(0,i.useMemo)(()=>new Yd,[v]);(0,i.useEffect)(()=>{if(r.mode===`probing`)return;p({state:r.mode===`mock`?`mock`:`connecting`,attempt:0});let e=_.subscribe({onEvent:e=>{Hd(e)?b.ingest(e):y.ingest(e)&&vf(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(),b.dispose()}},[_,y,b,n,v,r.mode]);let x=(0,i.useMemo)(()=>({client:_,sourceKey:v,live:y,orchestrator:b,connection:{mode:r.mode,reason:r.reason,stream:f,probeError:c,unauthorized:m},retry:()=>{d(e=>e+1),n.invalidateQueries()}}),[_,v,y,b,r,f,c,m,n]);return(0,a.jsx)(lf.Provider,{value:x,children:e})}function Z(){let e=(0,i.useContext)(lf);if(!e)throw Error(`useData must be used inside <DataProvider>`);return e}function pf(){let{live:e}=Z();return(0,i.useSyncExternalStore)(e.subscribe,e.getState,e.getState)}var mf=[];function hf(e,t){let{orchestrator:n}=Z(),r=()=>Jd(n.getState(),e,t,mf);return(0,i.useSyncExternalStore)(n.subscribe,r,r)}function gf(){let{orchestrator:e}=Z(),t=()=>e.getState().runs;return(0,i.useSyncExternalStore)(e.subscribe,t,t)}function Q(e,...t){return[`dc`,e,...t]}function _f(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 vf(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&&_f(e,n.goal))}}var yf=Kc({path:H(),status:q([`added`,`modified`,`deleted`,`renamed`,`untracked`]),additions:Ic(),deletions:Ic(),binary:W()}),bf=Kc({id:H(),label:H(),isolated:W(),path:H(),files:G(yf),additions:Ic(),deletions:Ic(),dirty:W(),ahead:Ic(),unpushed:Ic(),hasRemote:W()}),xf=K({patch:H(),truncated:W()}),Sf=K({message:H(),title:H(),body:H(),by:q([`davecode`,`claude`,`codex`,`agy`])}),Cf=Kc({ok:W(),steps:G(K({phase:q([`branch`,`commit`,`push`,`pr`]),ok:W(),detail:H()})),workspace:bf});function wf(e,t){let n=e.safeParse(t);if(!n.success)throw new J(0,`bad_response`,`Unexpected changes response.`);return n.data}async function Tf(e,t,n,r,i){let a;try{a=await fetch(`${e.replace(/\/+$/,``)}/api/changes${r}`,{method:n,headers:{Accept:`application/json`,...t?{Authorization:`Bearer ${t}`}:{},...n===`GET`?{}:{"Content-Type":`application/json`}},cache:`no-store`,...i===void 0?{}:{body:JSON.stringify(i)}})}catch(e){throw new J(0,`network`,`Gateway unreachable: ${e.message}`)}if(a.status===204)return;let o=await a.text(),s;try{s=o?JSON.parse(o):void 0}catch{throw new J(a.status,`bad_response`,`Unexpected changes response.`)}if(!a.ok){let e=s?.error;throw new J(a.status,e?.code??`http_${a.status}`,e?.message??`The changes request failed (${a.status}).`)}return s}var Ef=e=>`/workspaces/${encodeURIComponent(e)}`;async function Df(e,t){try{let n=await Tf(e,t,`GET`,`/workspaces`);return wf(K({workspaces:G(bf)}),n).workspaces}catch(e){if(e instanceof J&&e.status===404)return null;throw e}}async function Of(e,t,n){return wf(bf,await Tf(e,t,`POST`,`/workspaces`,{label:n}))}async function kf(e,t,n,r){let i=r===void 0?``:`?path=${encodeURIComponent(r)}`;return wf(xf,await Tf(e,t,`GET`,`${Ef(n)}/diff${i}`))}async function Af(e,t,n,r){let i=r&&r!==`davecode`?{agent:r}:{};return wf(Sf,await Tf(e,t,`POST`,`${Ef(n)}/suggest`,i))}async function jf(e,t,n,r){return wf(Cf,await Tf(e,t,`POST`,`${Ef(n)}/ship`,r))}async function Mf(e,t,n,r){return wf(bf,await Tf(e,t,`POST`,`${Ef(n)}/merge`,r?{message:r}:{}))}async function Nf(e,t,n,r){await Tf(e,t,`DELETE`,`${Ef(n)}${r?`?deleteBranch=true`:``}`)}var Pf=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@(.*)$/;function Ff(e){return e.replace(/^"?[ab]\//,``).replace(/"$/,``)}function If(e){let t=[],n,r,i=0,a=0;for(let o of e.split(`
|
|
112
|
+
`)){let e=o.replace(/\r$/,``);if(e.startsWith(`diff --git `)){let i=/^diff --git (?:"?a\/(.+?)"?) (?:"?b\/(.+?)"?)$/.exec(e);n={path:i?.[2]??e.slice(11),binary:!1,hunks:[]};let a=i?.[1];a&&a!==n.path&&(n.oldPath=a),t.push(n),r=void 0;continue}if(!n)continue;let s=Pf.exec(e);s?(i=Number(s[1]),a=Number(s[2]),r={header:e,lines:[]},n.hunks.push(r)):r?e.startsWith(`+`)?r.lines.push({kind:`add`,text:e.slice(1),newNo:a++}):e.startsWith(`-`)?r.lines.push({kind:`del`,text:e.slice(1),oldNo:i++}):e.startsWith(`\\`)?r.lines.push({kind:`note`,text:e.slice(1).trim()}):e.startsWith(` `)&&r.lines.push({kind:`ctx`,text:e.slice(1),oldNo:i++,newNo:a++}):e.startsWith(`Binary files `)||e===`GIT binary patch`?n.binary=!0:e.startsWith(`rename from `)?n.oldPath=e.slice(12):e.startsWith(`+++ `)&&e!==`+++ /dev/null`&&(n.path=Ff(e.slice(4)))}return t}var Lf={added:`A`,modified:`M`,deleted:`D`,renamed:`R`,untracked:`U`},Rf={commit:`Commit`,commit_push:`Commit & push`,commit_push_pr:`Commit, push & open PR`};function zf(e){return e.hasRemote?`commit_push_pr`:`commit`}function Bf(e){return e.hasRemote?[`commit`,`commit_push`,`commit_push_pr`]:[`commit`]}function Vf(e,t,n){let r=t.message.trim(),i={};return n&&r&&(i.message=r),e!==`commit`&&(i.push=!0),e===`commit_push_pr`&&(i.pr={title:t.title.trim()||r,body:t.body,draft:t.draft}),i}function Hf(e,t,n,r){let i=n.trim().length>0;return t===`commit`?e.dirty&&i:e.dirty&&!i||t===`commit_push_pr`&&!(r.trim()||n.trim())?!1:e.dirty||e.unpushed>0||t===`commit_push_pr`}function Uf(e){return e.files.length===0?``:`+${e.additions} −${e.deletions}`}function Wf(e){return e?e.startsWith(`davecode/`)?e.slice(9):e:`detached`}function Gf(e){return(e??[]).reduce((e,t)=>e+t.files.length,0)}function Kf(){let{client:e,sourceKey:t}=Z();return S({queryKey:Q(t,`health`),queryFn:()=>e.health(),refetchInterval:3e4})}function qf(){let{client:e,sourceKey:t}=Z();return S({queryKey:Q(t,`accounts`),queryFn:()=>e.listAccounts(),refetchInterval:6e4})}function Jf(){let{client:e,sourceKey:t}=Z();return S({queryKey:Q(t,`usage`),queryFn:()=>e.usage(),refetchInterval:3e4})}function Yf(){let{client:e,sourceKey:t}=Z();return S({queryKey:Q(t,`budget`),queryFn:()=>e.budget(),refetchInterval:3e4})}function Xf(e,t=!1){let{client:n,sourceKey:r}=Z();return S({queryKey:Q(r,`connection`,e),queryFn:()=>n.connection(e),refetchInterval:t?3e3:!1,staleTime:15e3})}function Zf(){let{client:e,sourceKey:t}=Z(),n=s();return C({mutationFn:t=>e.connect(t),onSuccess:(e,r)=>n.setQueryData(Q(t,`connection`,r),e.connection)})}function Qf(e=60,t=60){let{client:n,sourceKey:r}=Z();return S({queryKey:Q(r,`timeseries`,e,t),queryFn:()=>n.timeseries(e,t),refetchInterval:6e4})}function $f(){let{client:e,sourceKey:t}=Z();return S({queryKey:Q(t,`routes`),queryFn:()=>e.routes()})}function ep(){let{client:e,sourceKey:t}=Z();return S({queryKey:Q(t,`models`),queryFn:()=>e.models()})}function tp(){let{client:e,sourceKey:t}=Z();return S({queryKey:Q(t,`tasks`),queryFn:()=>e.tasks(),refetchInterval:6e4})}function np(){let{client:e,sourceKey:t}=Z();return S({queryKey:Q(t,`brain`),queryFn:()=>e.brain(),refetchInterval:6e4})}function rp(){let{client:e,sourceKey:t}=Z();return S({queryKey:Q(t,`runner`),queryFn:()=>e.runner(),refetchInterval:15e3,retry:(e,t)=>t.status!==501&&e<2})}function ip(){let{sourceKey:e}=Z(),t=s(),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 ap(){let{client:e}=Z(),t=ip();return C({mutationFn:t=>e.createAccount(t),onSuccess:e=>t.upsert(e),onSettled:()=>t.invalidate()})}function op(){let{client:e,sourceKey:t}=Z(),n=s(),r=ip();return C({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 sp(){let{client:e}=Z(),t=ip();return C({mutationFn:t=>e.deleteAccount(t),onSuccess:(e,n)=>t.remove(n),onSettled:()=>t.invalidate()})}function cp(){let{sourceKey:e}=Z(),t=s(),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 lp(){let{client:e}=Z(),t=cp();return C({mutationFn:t=>e.createTask(t),onSuccess:e=>t.upsert(e),onSettled:()=>t.invalidate()})}function up(){let{client:e}=Z(),t=cp();return C({mutationFn:({id:t,patch:n})=>e.updateTask(t,n),onSuccess:e=>t.upsert(e),onSettled:()=>t.invalidate()})}function dp(){let{client:e}=Z(),t=cp();return C({mutationFn:t=>e.deleteTask(t),onSuccess:(e,n)=>t.remove(n),onSettled:()=>t.invalidate()})}function fp(){let{client:e,sourceKey:t}=Z(),n=s();return C({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 pp(){let{client:e,sourceKey:t}=Z(),n=s();return C({mutationFn:t=>e.runnerAction(t),onSuccess:e=>n.setQueryData(Q(t,`runner`),e)})}function mp(){let{client:e,sourceKey:t}=Z();return S({queryKey:Q(t,`goals`),queryFn:()=>e.goals(),refetchInterval:6e4,retry:(e,t)=>t.status!==501&&e<2})}function hp(){let{sourceKey:e}=Z(),t=s();return n=>t.setQueryData(Q(e,`goals`),e=>_f(e,n))}function gp(){let{client:e}=Z(),t=hp();return C({mutationFn:t=>e.startGoal(t),onSuccess:e=>t(e)})}function _p(){let{client:e}=Z(),t=hp();return C({mutationFn:t=>e.executeGoal(t),onSuccess:e=>t(e)})}function vp(e,t){let{client:n,sourceKey:r}=Z();return S({queryKey:Q(r,`goal-artifact`,e??``,t??``),queryFn:()=>n.goalArtifact(e,t),enabled:!!(e&&t),staleTime:6e4})}function yp(){let{client:e}=Z(),t=hp();return C({mutationFn:t=>e.cancelGoal(t),onSuccess:e=>t(e)})}function bp(){let{client:e,sourceKey:t}=Z(),n=s();return C({mutationFn:t=>e.runnerAction(`start`,{taskId:t}),onSuccess:e=>n.setQueryData(Q(t,`runner`),e)})}function $(){let e=jl();return{base:e.gatewayUrl.replace(/\/+$/,``),token:e.token}}function xp(){let{sourceKey:e,connection:t}=Z(),{base:n,token:r}=$();return S({queryKey:Q(e,`orchestrator`,`agents`),queryFn:()=>Pd(n,r),enabled:t.mode===`live`,staleTime:6e4,refetchInterval:12e4,retry:!1})}function Sp(e){let{sourceKey:t,connection:n,orchestrator:r}=Z(),{base:a,token:o}=$(),s=S({queryKey:Q(t,`orchestrator`,`runs`),queryFn:()=>Fd(a,o),enabled:e&&n.mode===`live`,retry:!1});(0,i.useEffect)(()=>{s.data&&r.hydrate(s.data)},[s.data,r]);let c=n.stream.state===`open`,{refetch:l}=s;return(0,i.useEffect)(()=>{c&&e&&l()},[c,e,l]),s}function Cp(){let{orchestrator:e}=Z(),{base:t,token:n}=$();return C({mutationFn:e=>Ld(t,n,e),onSuccess:t=>e.upsert(t)})}function wp(){let{orchestrator:e}=Z(),{base:t,token:n}=$();return C({mutationFn:async e=>(await Rd(t,n,e),Id(t,n,e).catch(()=>void 0)),onSuccess:t=>{t&&e.upsert(t)}})}function Tp(){let{orchestrator:e}=Z(),{base:t,token:n}=$();return C({mutationFn:e=>zd(t,n,e),onSuccess:t=>e.upsert(t)})}function Ep(e){let{sourceKey:t,connection:n}=Z(),{base:r,token:i}=$();return S({queryKey:Q(t,`changes`,`workspaces`),queryFn:()=>Df(r,i),enabled:e&&n.mode===`live`,refetchInterval:4e3,refetchIntervalInBackground:!1,retry:!1})}function Dp(e,t,n){let{sourceKey:r,connection:i}=Z(),{base:a,token:o}=$();return S({queryKey:Q(r,`changes`,`diff`,e??``,t??``,n),queryFn:()=>kf(a,o,e??`main`,t),enabled:e!==void 0&&i.mode===`live`,placeholderData:e=>e,retry:!1})}function Op(e){let{sourceKey:t}=Z(),{base:n,token:r}=$(),i=s();return C({mutationFn:t=>e(n,r,t),onSettled:()=>i.invalidateQueries({queryKey:Q(t,`changes`)})})}var kp=()=>Op((e,t,n)=>Of(e,t,n)),Ap=()=>Op((e,t,n)=>jf(e,t,n.id,n.ship)),jp=()=>Op((e,t,n)=>Mf(e,t,n.id,n.message)),Mp=()=>Op((e,t,n)=>Nf(e,t,n.id,n.deleteBranch));function Np(){let{base:e,token:t}=$();return C({mutationFn:n=>Af(e,t,n.id,n.agent)})}var Pp=new Intl.NumberFormat(`en`,{notation:`compact`,maximumFractionDigits:1}),Fp=new Intl.NumberFormat(`en`);function Ip(e){return Number.isFinite(e)?Pp.format(e):`—`}function Lp(e){return Number.isFinite(e)?Fp.format(Math.round(e)):`—`}function Rp(e,t=0){return Number.isFinite(e)?`${(e*100).toFixed(t)}%`:`—`}function zp(e){return Number.isFinite(e)?e<1e3?`${Math.round(e)} ms`:`${(e/1e3).toFixed(e<1e4?2:1)} s`:`—`}function Bp(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 Vp(e){let t=Math.max(0,Math.ceil(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,`0`)}`}function Hp(e,t=!1){let n=new Date(e),r=`${Gp(n.getHours())}:${Gp(n.getMinutes())}:${Gp(n.getSeconds())}`;return t?`${r}.${String(n.getMilliseconds()).padStart(3,`0`)}`:r}function Up(e){let t=new Date(e);return`${Gp(t.getHours())}:${Gp(t.getMinutes())}`}function Wp(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 Gp(e){return String(e).padStart(2,`0`)}function Kp(e,t=8){return(e.includes(`_`)?e.slice(e.indexOf(`_`)+1):e).slice(0,t)}export{zf as $,Ml as $t,jp as A,dd as At,gp as B,Vu as Bt,kp as C,_ as Cn,af as Ct,vp as D,ad as Dt,_p as E,s as En,nd as Et,$f as F,Ku as Ft,op as G,$l as Gt,Np as H,Gu as Ht,bp as I,Uu as It,Jf as J,Hl as Jt,fp as K,Ql as Kt,rp as L,Bu as Lt,xp as M,ed as Mt,Sp as N,Zu as Nt,mp as O,id as Ot,Mp as P,cd as Pt,Gf as Q,Ol as Qt,pp as R,zu as Rt,lp as S,ee as Sn,tf as St,dp as T,c as Tn,ld as Tt,tp as U,_u as Ut,Cp as V,Hu as Vt,Qf as W,vu as Wt,Rf as X,Bl as Xt,Lf as Y,Ul as Yt,Hf as Z,Pl as Zt,Dp as _,x as _n,Xd as _t,Up as a,W as an,ff as at,Xf as b,v as bn,nf as bt,Rp as c,pt as cn,hf as ct,qf as d,je as dn,wd as dt,Nl as en,Uf as et,Tp as f,Se as fn,sf as ft,wp as g,m as gn,rf as gt,yp as h,_e as hn,Zd as ht,Bp as i,G as in,Wf as it,ep as j,Xu as jt,Kf as k,fd as kt,Wp as l,S as ln,gf as lt,Yf as m,ve as mn,$d as mt,Ip as n,jl as nn,Bf as nt,Lp as o,K as on,Z as ot,np as p,xe as pn,cf as pt,up as q,eu as qt,Vp as r,q as rn,Vf as rt,zp as s,H as sn,pf as st,Hp as t,kl as tn,If as tt,Kp as u,Ve as un,Cd as ut,Ep as v,b as vn,Qd as vt,sp as w,de as wn,ef as wt,ap as x,p as xn,qd as xt,Zf as y,y as yn,of as yt,Ap as z,Wu as zt};
|