@agentprojectcontext/apx 1.75.0 → 1.76.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/package.json +1 -1
- package/src/core/runtime-skills/apx-task/SKILL.md +4 -0
- package/src/core/stores/tasks.js +70 -1
- package/src/host/daemon/api/tasks.js +36 -15
- package/src/interfaces/cli/commands/task.js +44 -13
- package/src/interfaces/cli/index.js +7 -1
- package/src/interfaces/web/dist/assets/{index-CXeqTvfy.js → index-Bjlk9ttU.js} +5 -5
- package/src/interfaces/web/dist/assets/index-Bjlk9ttU.js.map +1 -0
- package/src/interfaces/web/dist/index.html +1 -1
- package/src/interfaces/web/src/i18n/en.ts +1 -0
- package/src/interfaces/web/src/i18n/es.ts +1 -0
- package/src/interfaces/web/src/lib/api/tasks.ts +6 -2
- package/src/interfaces/web/src/screens/base/GlobalTasksTab.tsx +21 -3
- package/src/interfaces/web/dist/assets/index-CXeqTvfy.js.map +0 -1
|
@@ -758,7 +758,7 @@ Please change the parent <Route path="${k}"> to <Route path="${k==="/"?"*":`${k}
|
|
|
758
758
|
*
|
|
759
759
|
* This source code is licensed under the MIT license found in the
|
|
760
760
|
* LICENSE file in the root directory of this source tree.
|
|
761
|
-
*/var Zj;function _O(){if(Zj)return lh;Zj=1;var e=Yc(),t=uC();function a(g,h){return g===h&&(g!==0||1/g===1/h)||g!==g&&h!==h}var o=typeof Object.is=="function"?Object.is:a,l=t.useSyncExternalStore,c=e.useRef,d=e.useEffect,f=e.useMemo,m=e.useDebugValue;return lh.useSyncExternalStoreWithSelector=function(g,h,b,_,j){var E=c(null);if(E.current===null){var y={hasValue:!1,value:null};E.current=y}else y=E.current;E=f(function(){function N(T){if(!w){if(w=!0,S=T,T=_(T),j!==void 0&&y.hasValue){var z=y.value;if(j(z,T))return R=z}return R=T}if(z=R,o(S,T))return z;var M=_(T);return j!==void 0&&j(z,M)?(S=T,z):(S=T,R=M)}var w=!1,S,R,A=b===void 0?null:b;return[function(){return N(h())},A===null?void 0:function(){return N(A())}]},[h,b,_,j]);var k=l(g,E[0],E[1]);return d(function(){y.hasValue=!0,y.value=k},[k]),m(k),k},lh}var Jj;function vO(){return Jj||(Jj=1,oh.exports=_O()),oh.exports}var yO=vO();const jO=Yb(19),kO=jO?SO:CO;function tt(e,t,a,o,l){return kO(e,t,a,o,l)}function wO(e,t,a,o,l){const c=x.useCallback(()=>t(e.getSnapshot(),a,o,l),[e,t,a,o,l]);return Uc.useSyncExternalStore(e.subscribe,c,c)}l4({before(e){e.syncIndex=0,e.didInitialize||(e.syncTick=1,e.syncHooks=[],e.didChangeStore=!0,e.getSnapshot=()=>{let t=!1;for(let a=0;a<e.syncHooks.length;a+=1){const o=e.syncHooks[a],l=o.selector(o.store.state,o.a1,o.a2,o.a3);Object.is(o.value,l)||(t=!0,o.value=l)}return t&&(e.syncTick+=1),e.syncTick})},after(e){e.syncHooks.length>0&&(e.didChangeStore&&(e.didChangeStore=!1,e.subscribe=t=>{const a=new Set;for(const l of e.syncHooks)a.add(l.store);const o=[];for(const l of a)o.push(l.subscribe(t));return()=>{for(const l of o)l()}}),Uc.useSyncExternalStore(e.subscribe,e.getSnapshot,e.getSnapshot))}});function SO(e,t,a,o,l){const c=o4();if(!c)return wO(e,t,a,o,l);const d=c.syncIndex;c.syncIndex+=1;let f;return c.didInitialize?(f=c.syncHooks[d],(f.store!==e||f.selector!==t||!Object.is(f.a1,a)||!Object.is(f.a2,o)||!Object.is(f.a3,l))&&(f.store!==e&&(c.didChangeStore=!0),f.store=e,f.selector=t,f.a1=a,f.a2=o,f.a3=l,f.value=t(e.getSnapshot(),a,o,l))):(f={store:e,selector:t,a1:a,a2:o,a3:l,value:t(e.getSnapshot(),a,o,l)},c.syncHooks.push(f)),f.value}function CO(e,t,a,o,l){return yO.useSyncExternalStoreWithSelector(e.subscribe,e.getSnapshot,e.getSnapshot,c=>t(c,a,o,l))}class NO{constructor(t){this.state=t,this.listeners=new Set,this.updateTick=0}subscribe=t=>(this.listeners.add(t),()=>{this.listeners.delete(t)});getSnapshot=()=>this.state;setState(t){if(this.state===t)return;this.state=t,this.updateTick+=1;const a=this.updateTick;for(const o of this.listeners){if(a!==this.updateTick)return;o(t)}}update(t){for(const a in t)if(!Object.is(this.state[a],t[a])){this.setState({...this.state,...t});return}}set(t,a){Object.is(this.state[t],a)||this.setState({...this.state,[t]:a})}notifyAll(){const t={...this.state};this.setState(t)}use(t,a,o,l){return tt(this,t,a,o,l)}}class nu extends NO{constructor(t,a={},o){super(t),this.context=a,this.selectors=o}useSyncedValue(t,a){x.useDebugValue(t);const o=this;Pe(()=>{o.state[t]!==a&&o.set(t,a)},[o,t,a])}useSyncedValueWithCleanup(t,a){const o=this;Pe(()=>(o.state[t]!==a&&o.set(t,a),()=>{o.set(t,void 0)}),[o,t,a])}useSyncedValues(t){const a=this,o=Object.values(t);Pe(()=>{a.update(t)},[a,...o])}useControlledProp(t,a){x.useDebugValue(t);const o=this,l=a!==void 0;Pe(()=>{l&&!Object.is(o.state[t],a)&&o.setState({...o.state,[t]:a})},[o,t,a,l])}select(t,a,o,l){const c=this.selectors[t];return c(this.state,a,o,l)}useState(t,a,o,l){return x.useDebugValue(t),tt(this,this.selectors[t],a,o,l)}useContextCallback(t,a){x.useDebugValue(t);const o=He(a??Nn);this.context[t]=o}useStateSetter(t){const a=x.useRef(void 0);return a.current===void 0&&(a.current=o=>{this.set(t,o)}),a.current}observe(t,a){let o;typeof t=="function"?o=t:o=this.selectors[t];let l=o(this.state);return a(l,l,this),this.subscribe(c=>{const d=o(c);if(!Object.is(l,d)){const f=l;l=d,a(d,f,this)}})}}const EO={open:e=>e.open,transitionStatus:e=>e.transitionStatus,domReferenceElement:e=>e.domReferenceElement,referenceElement:e=>e.positionReference??e.referenceElement,floatingElement:e=>e.floatingElement,floatingId:e=>e.floatingId};class up extends nu{constructor(t){const{syncOnly:a,nested:o,onOpenChange:l,triggerElements:c,...d}=t;super({...d,positionReference:d.referenceElement,domReferenceElement:d.referenceElement},{onOpenChange:l,dataRef:{current:{}},events:WS(),nested:o,triggerElements:c},EO),this.syncOnly=a}syncOpenEvent=(t,a)=>{(!t||!this.state.open||a!=null&&b4(a))&&(this.context.dataRef.current.openEvent=t?a:void 0)};dispatchOpenChange=(t,a)=>{this.syncOpenEvent(t,a.event);const o={open:t,reason:a.reason,nativeEvent:a.event,nested:this.context.nested,triggerElement:a.trigger};this.context.events.emit("openchange",o)};setOpen=(t,a)=>{if(this.syncOnly){this.context.onOpenChange?.(t,a);return}this.dispatchOpenChange(t,a),this.context.onOpenChange?.(t,a)}}function dC(e){const{popupStore:t,treatPopupAsFloatingElement:a=!1,floatingRootContext:o,floatingId:l,nested:c,onOpenChange:d}=e,f=t.useState("open"),m=t.useState("activeTriggerElement"),g=t.useState(a?"popupElement":"positionerElement"),h=t.context.triggerElements,b=d,_=x.useRef(null);o===void 0&&_.current===null&&(_.current=new up({open:f,transitionStatus:void 0,referenceElement:m,floatingElement:g,triggerElements:h,onOpenChange:b,floatingId:l,syncOnly:!0,nested:c}));const j=o??_.current;return t.useSyncedValue("floatingId",l),Pe(()=>{const E={open:f,floatingId:l,referenceElement:m,floatingElement:g};bt(m)&&(E.domReferenceElement=m),j.state.positionReference===j.state.referenceElement&&(E.positionReference=m),j.update(E)},[f,l,m,g,j]),j.context.onOpenChange=b,j.context.nested=c,j}function hi(e,t=!1,a=!1){const[o,l]=x.useState(e&&t?"idle":void 0),[c,d]=x.useState(e);return e&&!c&&(d(!0),l("starting")),!e&&c&&o!=="ending"&&!a&&l("ending"),!e&&!c&&o==="ending"&&l(void 0),Pe(()=>{if(!e&&c&&o!=="ending"&&a){const f=ga.request(()=>{l("ending")});return()=>{ga.cancel(f)}}},[e,c,o,a]),Pe(()=>{if(!e||t)return;const f=ga.request(()=>{l(void 0)});return()=>{ga.cancel(f)}},[t,e]),Pe(()=>{if(!e||!t)return;e&&c&&o!=="idle"&&l("starting");const f=ga.request(()=>{l("idle")});return()=>{ga.cancel(f)}},[t,e,c,o]),{mounted:c,setMounted:d,transitionStatus:o}}function fC(e,t=!1){const a=Jl();return He((o,l=null)=>{a.cancel();const c=Xa(e);if(c==null)return;const d=c,f=()=>{Gs.flushSync(o)};if(typeof d.getAnimations!="function"||globalThis.BASE_UI_ANIMATIONS_DISABLED){o();return}function m(){Promise.all(d.getAnimations().map(g=>g.finished)).then(()=>{l?.aborted||f()},()=>{if(l?.aborted)return;if(d.getAnimations().some(h=>h.pending||h.playState!=="finished")){m();return}f()})}if(t){const g="data-starting-style";if(!d.hasAttribute(g)){a.request(m);return}const h=new MutationObserver(()=>{d.hasAttribute(g)||(h.disconnect(),m())});h.observe(d,{attributes:!0,attributeFilter:[g]}),l?.addEventListener("abort",()=>h.disconnect(),{once:!0});return}a.request(m)})}function Ca(e){const{enabled:t=!0,open:a,ref:o,onComplete:l}=e,c=He(l),d=fC(o,a);x.useEffect(()=>{if(!t)return;const f=new AbortController;return d(c,f.signal),()=>{f.abort()}},[t,a,c,d])}const dp={tabIndex:-1,[hx]:""};function RO(e){return t=>t==="touch"?e.current:!0}function pC(e,t=!1){const a=Oo(),o=eo()!=null,l=Hn(()=>e(a,o)).current;return dC({popupStore:l,treatPopupAsFloatingElement:t,floatingRootContext:l.state.floatingRootContext,floatingId:a,nested:o,onOpenChange:l.setOpen}),l}function t_({handle:e,store:t}){return Pe(()=>e.attachStore(t),[e,t]),null}function TO(e,t){const a=x.useRef(null),o=x.useRef(null);return x.useCallback(l=>{if(e===void 0)return;let c=!1;if(a.current!==null){const d=a.current,f=o.current,m=t.context.triggerElements.getById(d);f&&m===f&&(t.context.triggerElements.delete(d),c=!0),a.current=null,o.current=null}if(l!==null&&(a.current=e,o.current=l,t.context.triggerElements.add(e,l),c=!0),c){const d=t.context.triggerElements.size;t.select("open")&&t.state.triggerCount!==d&&t.set("triggerCount",d)}},[t,e])}function n_(e,t,a,o=!1){t?e.preventUnmountingOnClose=!1:o&&(e.preventUnmountingOnClose=!0);const l=a?.id??null;(l||t)&&(e.activeTriggerId=l,e.activeTriggerElement=a??null)}function mC(e){let t=!1;return e.preventUnmountOnClose=()=>{t=!0},()=>t}function AO(e,t,a,o={}){const l=a.reason,c=l===En,d=t&&l===Vl,f=!t&&(l===gi||l===op),m=mC(a);if(e.context.onOpenChange?.(t,a),a.isCanceled)return;o.onBeforeDispatch?.(),e.state.floatingRootContext.dispatchOpenChange(t,a);const g=()=>{const h={...o.extraState,open:t};d?h.instantType="focus":f?h.instantType="dismiss":c&&(h.instantType=void 0),n_(h,t,a.trigger,m()),e.update(h)};c?Gs.flushSync(g):g()}function gC(e,t,a,o){const l=a.useState("isMountedByTrigger",e),c=TO(e,a),d=He(m=>{const g=a.select("open"),h=a.select("activeTriggerId");if(h===e){a.update({activeTriggerElement:m,...g?o:null});return}h==null&&g&&a.update({activeTriggerId:e,activeTriggerElement:m,...o})}),f=x.useCallback(m=>{c(m),m&&d(m)},[c,d]);return Pe(()=>{l&&a.update({activeTriggerElement:t.current,...o})},[l,a,t,...Object.values(o)]),{registerTrigger:f,isMountedByThisTrigger:l}}function s_(e,t={}){const{closeOnActiveTriggerUnmount:a=!1}=t,o=x.useRef(null),l=e.useState("open"),c=e.useState("triggerCount"),d=e.useState("activeTriggerId"),f=e.useState("activeTriggerElement");Pe(()=>{if(!l){o.current=null,e.state.triggerCount!==0&&e.set("triggerCount",0);return}const m=e.context.triggerElements.size,g={};e.state.triggerCount!==m&&(g.triggerCount=m);const h=e.select("activeTriggerId");let b=null;if(h){const _=e.context.triggerElements.getById(h);if(_)o.current=h,_!==e.state.activeTriggerElement&&(g.activeTriggerElement=_);else{for(const[j,E]of e.context.triggerElements.entries())if(E===e.state.activeTriggerElement){g.activeTriggerId=j,g.activeTriggerElement=E,o.current=j;break}g.activeTriggerId===void 0&&(o.current===h?b=h:o.current=null)}}else o.current=null;if(!b&&!h&&m===1){const _=e.context.triggerElements.entries().next();if(!_.done){const[j,E]=_.value;g.activeTriggerId=j,g.activeTriggerElement=E,o.current=j}}(g.triggerCount!==void 0||g.activeTriggerId!==void 0||g.activeTriggerElement!==void 0)&&e.update(g),b&&a&&queueMicrotask(()=>{if(e.select("open")&&e.select("activeTriggerId")===b&&!e.context.triggerElements.getById(b)){const _=rt(ka);e.setOpen(!1,_),_.isCanceled||e.update({activeTriggerId:null,activeTriggerElement:null})}})},[l,e,c,d,f,a])}function a_(e,t,a){const{mounted:o,setMounted:l,transitionStatus:c}=hi(e),d=t.useState("preventUnmountingOnClose"),f=e?!1:d;t.useSyncedValues({mounted:o,transitionStatus:c,preventUnmountingOnClose:f});const m=He(()=>{l(!1),t.update({activeTriggerId:null,activeTriggerElement:null,mounted:!1,preventUnmountingOnClose:!1}),a?.(),t.context.onOpenChangeComplete?.(!1)});return Ca({enabled:o&&!e&&!f,open:e,ref:t.context.popupRef,onComplete(){e||m()}}),{forceUnmount:m,transitionStatus:c}}function r_(e,t){e.useSyncedValues(t),Pe(()=>()=>{e.update({activeTriggerProps:sn,inactiveTriggerProps:sn,popupProps:sn})},[e])}function MO(e,t){Pe(()=>{!t&&e.state.openMethod!==null&&e.set("openMethod",null)},[t,e]),Pe(()=>()=>{e.state.openMethod!==null&&e.set("openMethod",null)},[e])}class su{constructor(){this.idMap=new Map}add(t,a){this.idMap.set(t,a)}delete(t){this.idMap.delete(t)}hasElement(t){for(const a of this.idMap.values())if(a===t)return!0;return!1}hasMatchingElement(t){for(const a of this.idMap.values())if(t(a))return!0;return!1}getById(t){return this.idMap.get(t)}entries(){return this.idMap.entries()}elements(){return this.idMap.values()}get size(){return this.idMap.size}}function zO(){return new up({open:!1,transitionStatus:void 0,floatingElement:null,referenceElement:null,triggerElements:new su,floatingId:void 0,syncOnly:!1,nested:!1,onOpenChange:void 0})}function o_(){return{open:!1,openProp:void 0,mounted:!1,transitionStatus:void 0,floatingRootContext:zO(),floatingId:void 0,triggerCount:0,preventUnmountingOnClose:!1,payload:void 0,activeTriggerId:null,activeTriggerElement:null,triggerIdProp:void 0,popupElement:null,positionerElement:null,activeTriggerProps:sn,inactiveTriggerProps:sn,popupProps:sn}}function hC(e,t,a=!1){return new up({open:!1,transitionStatus:void 0,floatingElement:null,referenceElement:null,triggerElements:e,floatingId:t,syncOnly:!0,nested:a,onOpenChange:void 0})}const Tc=e=>e.triggerIdProp??e.activeTriggerId,l_=e=>e.openProp??e.open,ek=e=>(e.popupElement?.id??e.floatingId)||void 0;function xC(e,t){return t!==void 0&&l_(e)&&Tc(e)===t}function OO(e,t){return xC(e,t)?!0:t!==void 0&&l_(e)&&Tc(e)==null&&e.triggerCount===1}const i_={open:l_,mounted:e=>e.mounted,transitionStatus:e=>e.transitionStatus,floatingRootContext:e=>e.floatingRootContext,triggerCount:e=>e.triggerCount,preventUnmountingOnClose:e=>e.preventUnmountingOnClose,payload:e=>e.payload,activeTriggerId:Tc,activeTriggerElement:e=>e.mounted?e.activeTriggerElement:null,popupId:ek,isTriggerActive:(e,t)=>t!==void 0&&Tc(e)===t,isOpenedByTrigger:(e,t)=>xC(e,t),isMountedByTrigger:(e,t)=>t!==void 0&&Tc(e)===t&&e.mounted,triggerProps:(e,t)=>t?e.activeTriggerProps:e.inactiveTriggerProps,triggerPopupId:(e,t)=>OO(e,t)?ek(e):void 0,popupProps:e=>e.popupProps,popupElement:e=>e.popupElement,positionerElement:e=>e.positionerElement};function bC(e){const t=x.useCallback(o=>e===void 0?Nn:e.subscribeStore(o),[e]),a=x.useCallback(()=>e===void 0?void 0:e.store,[e]);return Uc.useSyncExternalStore(t,a,()=>e?.serverStore)}function DO(e){const{open:t=!1,onOpenChange:a,elements:o={}}=e,l=Oo(),c=eo()!=null,d=Hn(()=>new up({open:t,transitionStatus:void 0,onOpenChange:a,referenceElement:o.reference??null,floatingElement:o.floating??null,triggerElements:new su,floatingId:l,syncOnly:!1,nested:c})).current;return Pe(()=>{const f={open:t,floatingId:l};o.reference!==void 0&&(f.referenceElement=o.reference,f.domReferenceElement=bt(o.reference)?o.reference:null),o.floating!==void 0&&(f.floatingElement=o.floating),d.update(f)},[t,l,o.reference,o.floating,d]),d.context.onOpenChange=a,d.context.nested=c,d}function PO(e){return LO(e,e.rootContext)}function LO(e,t){const{nodeId:a,externalTree:o}=e,l=t.useState("referenceElement"),c=t.useState("floatingElement"),d=t.useState("domReferenceElement"),f=t.useState("open"),m=t.useState("floatingId"),[g,h]=x.useState(null),[b,_]=x.useState(void 0),[j,E]=x.useState(void 0),y=x.useRef(null),k=to(o),N=x.useMemo(()=>({reference:l,floating:c,domReference:d}),[l,c,d]),w=fO({...e,elements:{...N,...g&&{reference:g}}}),S=bt(b)?b:null,R=j===void 0?t.state.floatingElement:j;t.useSyncedValue("referenceElement",b??null),t.useSyncedValue("domReferenceElement",b===void 0?d:S),t.useSyncedValue("floatingElement",R);const A=x.useCallback(B=>{const D=bt(B)?{getBoundingClientRect:()=>B.getBoundingClientRect(),getClientRects:()=>B.getClientRects(),contextElement:B}:B;h(D),w.refs.setReference(D)},[w.refs]),T=x.useCallback(B=>{(bt(B)||B===null)&&(y.current=B,_(B)),(bt(w.refs.reference.current)||w.refs.reference.current===null||B!==null&&!bt(B))&&w.refs.setReference(B)},[w.refs,_]),z=x.useCallback(B=>{E(B),w.refs.setFloating(B)},[w.refs]),M=x.useMemo(()=>({...w.refs,setReference:T,setFloating:z,setPositionReference:A,domReference:y}),[w.refs,T,z,A]),L=x.useMemo(()=>({...w.elements,domReference:d}),[w.elements,d]),P=x.useMemo(()=>({...w,dataRef:t.context.dataRef,open:f,onOpenChange:t.setOpen,events:t.context.events,floatingId:m,refs:M,elements:L,nodeId:a,rootStore:t}),[w,M,L,a,t,f,m]);return Pe(()=>{d&&(y.current=d)},[d]),Pe(()=>{t.context.dataRef.current.floatingContext=P;const B=k?.nodesRef.current.find(D=>D.id===a);B&&(B.context=P)}),x.useMemo(()=>({...w,context:P,refs:M,elements:L,rootStore:t}),[w,M,L,P,t])}const ih=Ab&&ir;function _C(e,t={}){const{enabled:a=!0,delay:o}=t,l="rootStore"in e?e.rootStore:e,{events:c,dataRef:d}=l.context,f=x.useRef(!1),m=x.useRef(null),g=x.useRef(!0),h=Rn();x.useEffect(()=>{const _=l.select("domReferenceElement");if(!a)return;const j=Jt(_);function E(){const N=l.select("domReferenceElement");!l.select("open")&&Gt(N)&&N===Kn(vt(N))&&(f.current=!0)}function y(){g.current=!0}function k(){g.current=!1}return _a(xt(j,"blur",E),ih&&xt(j,"keydown",y,!0),ih&&xt(j,"pointerdown",k,!0))},[l,a]),x.useEffect(()=>{if(!a)return;function _(j){if(j.reason===gi||j.reason===op){const E=l.select("domReferenceElement");bt(E)&&(m.current=E,f.current=!0)}}return c.on("openchange",_),()=>{c.off("openchange",_)}},[c,a,l]);const b=x.useMemo(()=>{function _(){f.current=!1,m.current=null}return{onMouseLeave(){_()},onFocus(j){const E=j.currentTarget;if(f.current){if(m.current===E)return;_()}const y=qn(j.nativeEvent);if(bt(y)){if(ih&&!j.relatedTarget){if(!g.current&&!ap(y))return}else if(!S4(y))return}const k=pf(j.relatedTarget,l.context.triggerElements),{nativeEvent:N,currentTarget:w}=j,S=typeof o=="function"?o():o;if(l.select("open")&&k||S===0||S===void 0){l.setOpen(!0,rt(Vl,N,w));return}h.start(S,()=>{f.current||l.setOpen(!0,rt(Vl,N,w))})},onBlur(j){_();const E=j.relatedTarget,y=j.nativeEvent,k=bt(E)&&E.hasAttribute($c("focus-guard"))&&E.getAttribute("data-type")==="outside";h.start(0,()=>{const N=l.select("domReferenceElement"),w=Kn(vt(N));!E&&w===N||Ze(d.current.floatingContext?.refs.floating.current,w)||Ze(N,w)||k||pf(E??w,l.context.triggerElements)||l.setOpen(!1,rt(Vl,y))})}}},[d,o,l,h]);return x.useMemo(()=>a?{reference:b,trigger:b}:{},[a,b])}class c_{constructor(){this.pointerType=void 0,this.interactedInside=!1,this.handler=void 0,this.blockMouseMove=!0,this.performedPointerEventsMutation=!1,this.pointerEventsScopeElement=null,this.pointerEventsReferenceElement=null,this.pointerEventsFloatingElement=null,this.restTimeoutPending=!1,this.openChangeTimeout=new ta,this.restTimeout=new ta,this.handleCloseOptions=void 0}static create(){return new c_}dispose=()=>{this.openChangeTimeout.clear(),this.restTimeout.clear()};disposeEffect=()=>this.dispose}const yf=new WeakMap;function jf(e){if(!e.performedPointerEventsMutation)return;const t=e.pointerEventsScopeElement;t&&yf.get(t)===e&&(e.pointerEventsScopeElement?.style.removeProperty("pointer-events"),e.pointerEventsReferenceElement?.style.removeProperty("pointer-events"),e.pointerEventsFloatingElement?.style.removeProperty("pointer-events"),yf.delete(t)),e.performedPointerEventsMutation=!1,e.pointerEventsScopeElement=null,e.pointerEventsReferenceElement=null,e.pointerEventsFloatingElement=null}function vC(e,t){const{scopeElement:a,referenceElement:o,floatingElement:l}=t,c=yf.get(a);c&&c!==e&&jf(c),jf(e),e.performedPointerEventsMutation=!0,e.pointerEventsScopeElement=a,e.pointerEventsReferenceElement=o,e.pointerEventsFloatingElement=l,yf.set(a,e),a.style.pointerEvents="none",o.style.pointerEvents="auto",l.style.pointerEvents="auto"}function u_(e){const t=e.context.dataRef.current,a=Hn(()=>t.hoverInteractionState??c_.create()).current;return t.hoverInteractionState||(t.hoverInteractionState=a),Tb(t.hoverInteractionState.disposeEffect),t.hoverInteractionState}function yC(e,t={}){const{enabled:a=!0,closeDelay:o=0,nodeId:l}=t,c="rootStore"in e?e.rootStore:e,d=c.useState("open"),f=c.useState("floatingElement"),m=c.useState("domReferenceElement"),{dataRef:g}=c.context,h=to(),b=eo(),_=u_(c),j=Rn(),E=He(()=>vS(g.current.openEvent?.type,_.interactedInside)),y=He(()=>N4(g.current.openEvent?.type)),k=He(()=>{jf(_)});Pe(()=>{d||(_.pointerType=void 0,_.restTimeoutPending=!1,_.interactedInside=!1,k())},[d,_,k]),x.useEffect(()=>k,[k]),Pe(()=>{if(a&&d&&_.handleCloseOptions?.blockPointerEvents&&y()&&bt(m)&&f){const N=m,w=f,S=vt(f),R=h?.nodesRef.current.find(M=>M.id===b)?.context?.elements.floating;R&&(R.style.pointerEvents="");const A=_.pointerEventsScopeElement!==w?_.pointerEventsScopeElement:null,T=R!==w?R:null,z=_.handleCloseOptions?.getScope?.()??A??T??N.closest("[data-rootownerid]")??S.body;return vC(_,{scopeElement:z,referenceElement:N,floatingElement:w}),()=>{k()}}},[a,d,m,f,_,y,h,b,k]),x.useEffect(()=>{if(!a)return;function N(){return!!(h&&b&&Qr(h.nodesRef.current,b).length>0)}function w(M){const L=Kr(o,"close",_.pointerType),P=()=>{c.setOpen(!1,rt(En,M)),h?.events.emit("floating.closed",M)};L?_.openChangeTimeout.start(L,P):(_.openChangeTimeout.clear(),P())}function S(M){const L=qn(M);if(!w4(L)){_.interactedInside=!1;return}_.interactedInside=L?.closest("[aria-haspopup]")!=null}function R(){_.openChangeTimeout.clear(),j.clear(),h?.events.off("floating.closed",T),k()}function A(M){if(N()&&h){h.events.on("floating.closed",T);return}if(pf(M.relatedTarget,c.context.triggerElements))return;const L=g.current.floatingContext?.nodeId??l,P=M.relatedTarget;if(!(h&&L&&bt(P)&&Qr(h.nodesRef.current,L,!1).some(D=>Ze(D.context?.elements.floating,P)))){if(_.handler){_.handler(M);return}k(),y()&&!E()&&w(M)}}function T(M){!h||!b||N()||j.start(0,()=>{h.events.off("floating.closed",T),c.setOpen(!1,rt(En,M)),h.events.emit("floating.closed",M)})}const z=f;return _a(z&&xt(z,"mouseenter",R),z&&xt(z,"mouseleave",A),z&&xt(z,"pointerdown",S,!0),()=>{h?.events.off("floating.closed",T)})},[a,f,c,g,o,l,y,E,k,_,h,b,j])}const IO={current:null};function jC(e,t={}){const{enabled:a=!0,delay:o=0,handleClose:l=null,mouseOnly:c=!1,restMs:d=0,move:f=!0,triggerElementRef:m=IO,externalTree:g,isActiveTrigger:h=!0,getHandleCloseContext:b,isClosing:_,shouldOpen:j,guardStaleOpen:E=!1}=t,y="rootStore"in e?e.rootStore:e,{dataRef:k,events:N}=y.context,w=to(g),S=u_(y),R=x.useRef(!1),A=mn(l),T=mn(o),z=mn(d),M=mn(a),L=mn(j),P=mn(_),B=He(()=>vS(k.current.openEvent?.type,S.interactedInside)),D=He(()=>L.current?.()!==!1),$=He((U,V,X)=>{const Q=y.context.triggerElements;if(Q.hasElement(V))return!U||!Ze(U,V);if(!bt(X))return!1;const W=X;return Q.hasMatchingElement(I=>Ze(I,W))&&(!U||!Ze(U,W))}),q=He(()=>{if(!S.handler)return;vt(y.select("domReferenceElement")).removeEventListener("mousemove",S.handler),S.handler=void 0}),G=He(()=>{jf(S)});return h&&(S.handleCloseOptions=A.current?.__options),x.useEffect(()=>q,[q]),x.useEffect(()=>{if(!a)return;function U(V){V.open?R.current=!1:(R.current=V.reason===En,q(),S.openChangeTimeout.clear(),S.restTimeout.clear(),S.blockMouseMove=!0,S.restTimeoutPending=!1)}return N.on("openchange",U),()=>{N.off("openchange",U)}},[a,N,S,q]),x.useEffect(()=>{if(!a)return;function U(K,ee=!0){const F=Kr(T.current,"close",S.pointerType);F?S.openChangeTimeout.start(F,()=>{y.setOpen(!1,rt(En,K)),w?.events.emit("floating.closed",K)}):ee&&(S.openChangeTimeout.clear(),y.setOpen(!1,rt(En,K)),w?.events.emit("floating.closed",K))}const V=m.current??(h?y.select("domReferenceElement"):null);if(!bt(V))return;function X(K){if(S.openChangeTimeout.clear(),S.blockMouseMove=!1,c&&!Hr(S.pointerType))return;const ee=Sj(z.current),F=Kr(T.current,"open",S.pointerType),ne=qn(K),Z=K.currentTarget??null,fe=y.select("domReferenceElement");let Y=Z;if(bt(ne)&&!y.context.triggerElements.hasElement(ne)){for(const Oe of y.context.triggerElements.elements())if(Ze(Oe,ne)){Y=Oe;break}}bt(Z)&&bt(fe)&&!y.context.triggerElements.hasElement(Z)&&Ze(Z,fe)&&(Y=fe);const oe=Y==null?!1:$(fe,Y,ne),ve=y.select("open"),le=P.current?.()??y.select("transitionStatus")==="ending",xe=!ve&&le&&R.current,ke=!oe&&bt(Y)&&bt(fe)&&Ze(fe,Y)&&xe,Re=ee>0&&!F,Ae=oe&&(ve||xe)||ke,Ie=!ve||oe;if(Ae){D()&&y.setOpen(!0,rt(En,K,Y));return}Re||(F?S.openChangeTimeout.start(F,()=>{Ie&&D()&&y.setOpen(!0,rt(En,K,Y))}):Ie&&D()&&y.setOpen(!0,rt(En,K,Y)))}function Q(K){if(B()){G();return}q();const ee=y.select("domReferenceElement"),F=vt(ee);S.restTimeout.clear(),S.restTimeoutPending=!1;const ne=k.current.floatingContext??b?.();if(pf(K.relatedTarget,y.context.triggerElements))return;if(A.current&&ne){y.select("open")||S.openChangeTimeout.clear();const fe=m.current;S.handler=A.current({...ne,tree:w,x:K.clientX,y:K.clientY,onClose(){G(),q(),M.current&&!B()&&fe===y.select("domReferenceElement")&&U(K,!0)}}),F.addEventListener("mousemove",S.handler),S.handler(K);return}(S.pointerType==="touch"?!Ze(y.select("floatingElement"),K.relatedTarget):!0)&&U(K)}function W(K){Ze(V,K.relatedTarget)||(S.openChangeTimeout.clear(),S.restTimeout.clear(),S.restTimeoutPending=!1)}const I=E?xt(V,"mouseout",W):void 0;return f?_a(xt(V,"mousemove",X,{once:!0}),xt(V,"mouseenter",X),xt(V,"mouseleave",Q),I):_a(xt(V,"mouseenter",X),xt(V,"mouseleave",Q),I)},[q,G,k,T,y,a,A,S,h,$,B,c,f,z,m,w,M,b,P,D,E]),x.useMemo(()=>{if(!a)return;function U(V){S.pointerType=V.pointerType}return{onPointerDown:U,onPointerEnter:U,onMouseMove(V){const{nativeEvent:X}=V,Q=V.currentTarget,W=y.select("domReferenceElement"),I=y.select("open"),K=$(W,Q,V.target);if(c&&!Hr(S.pointerType))return;if(I&&K&&S.handleCloseOptions?.blockPointerEvents){const ne=y.select("floatingElement");if(ne){const Z=S.handleCloseOptions?.getScope?.()??Q.ownerDocument.body;vC(S,{scopeElement:Z,referenceElement:Q,floatingElement:ne})}}const ee=Sj(z.current);if(I&&!K||ee===0||!K&&S.restTimeoutPending&&V.movementX**2+V.movementY**2<2)return;S.restTimeout.clear();function F(){if(S.restTimeoutPending=!1,B())return;const ne=y.select("open");!S.blockMouseMove&&(!ne||K)&&D()&&y.setOpen(!0,rt(En,X,Q))}S.pointerType==="touch"?Gs.flushSync(()=>{F()}):K&&I?F():(S.restTimeoutPending=!0,S.restTimeout.start(ee,F))}}},[a,S,B,$,c,y,z,D])}const BO="Escape";function tk(e){return ir&&e.movementX===0&&e.movementY===0}function fp(e,t,a){switch(e){case"vertical":return t;case"horizontal":return a;default:return t||a}}function Rd(e,t){return fp(t,e===_S||e===Ib,e===np||e===sp)}function ch(e,t,a){return fp(t,e===Ib,a?e===np:e===sp)||e==="Enter"||e===" "||e===""}function $O(e,t,a){return fp(t,a?e===np:e===sp,e===Ib)}function UO(e,t,a,o){const l=a?e===sp:e===np,c=e===_S;return t==="both"||t==="horizontal"&&o?e===BO:fp(t,l,c)}function kC(e,t){const{listRef:a,activeIndex:o,onNavigate:l=()=>{},enabled:c=!0,selectedIndex:d=null,allowEscape:f=!1,loopFocus:m=!1,nested:g=!1,rtl:h=!1,virtual:b=!1,focusItemOnOpen:_="auto",focusItemOnHover:j=!0,openOnArrowKeyDown:E=!0,disabledIndices:y=void 0,orientation:k="vertical",parentOrientation:N,id:w,resetOnPointerLeave:S=!0,externalTree:R,grid:A}=t,T=A!=null,z="rootStore"in e?e.rootStore:e,M=z.useState("open"),L=z.useState("floatingElement"),P=z.useState("domReferenceElement"),B=z.context.dataRef,D=mf(L),$=xx(P),q=mn(D),G=eo(),U=to(R),V=x.useRef(_),X=x.useRef(d??-1),Q=x.useRef(null),W=x.useRef(!0),I=He(me=>{l(X.current===-1?null:X.current,me)}),K=x.useRef(!!L),ee=x.useRef(M),F=x.useRef(!1),ne=x.useRef(!1),Z=x.useRef(null),fe=mn(y),Y=mn(M),oe=mn(d),ve=mn(S),le=Jl(),xe=Jl(),ke=He(()=>{function me(Ce){b?U?.events.emit("virtualfocus",Ce):Z.current=tf(Ce,{sync:F.current,preventScroll:!0})}const de=a.current[X.current],Le=ne.current;de&&me(de),(F.current?Ce=>Ce():Ce=>le.request(Ce))(()=>{const Ce=a.current[X.current]||de;if(!Ce)return;de||me(Ce),Ne&&(Le||!W.current)&&Ce.scrollIntoView?.({block:"nearest",inline:"nearest"})})});Pe(()=>{B.current.orientation=k},[B,k]),Pe(()=>{c&&(M&&L?(X.current=d??-1,V.current&&d!=null&&(ne.current=!0,I())):K.current&&(X.current=-1,I()))},[c,M,L,d,I]),Pe(()=>{if(c){if(!M){F.current=!1;return}if(L)if(o==null){if(F.current=!1,oe.current!=null)return;if(K.current&&(X.current=-1,ke()),(!ee.current||!K.current)&&V.current&&(Q.current!=null||V.current===!0&&Q.current==null)){let me=0;const de=()=>{a.current[0]==null?(me<2&&(me?ye=>xe.request(ye):queueMicrotask)(de),me+=1):(X.current=Q.current==null||ch(Q.current,k,h)||g?ef(a):vx(a),Q.current=null,I())};de()}}else Rc(a.current,o)||(X.current=o,ke(),ne.current=!1)}},[c,M,L,o,oe,g,a,k,h,I,ke,xe]),Pe(()=>{if(!c||L||!U||b||!K.current)return;const me=U.nodesRef.current,de=me.find(Ce=>Ce.id===G)?.context?.elements.floating,Le=Kn(vt(P??de??null)),ye=me.some(Ce=>Ce.context&&Ze(Ce.context.elements.floating,Le));de&&!ye&&W.current&&de.focus({preventScroll:!0})},[c,L,P,U,G,b]),Pe(()=>{ee.current=M,K.current=!!L}),Pe(()=>{M||(Q.current=null,V.current=_)},[M,_]);const Re=o!=null,Ae=He(me=>{if(!Y.current)return;const de=a.current.indexOf(me.currentTarget);de!==-1&&(X.current!==de||o!==de)&&(X.current=de,I(me))}),Ie=He(()=>N??U?.nodesRef.current.find(me=>me.id===G)?.context?.dataRef?.current.orientation),Oe=He(()=>ef(a,fe.current)),Te=He(me=>{if(W.current=!1,F.current=!0,me.which===229||!Y.current&&me.currentTarget===q.current)return;if(g&&UO(me.key,k,h,T)){Rd(me.key,Ie())||pa(me),z.setOpen(!1,rt(bx,me.nativeEvent)),Gt(P)&&(b?U?.events.emit("virtualfocus",P):P.focus());return}const de=X.current,Le=ef(a,y),ye=vx(a,y);if($||(me.key==="Home"&&(pa(me),X.current=Le,I(me)),me.key==="End"&&(pa(me),X.current=ye,I(me))),A!=null){const Ce=A(me,X.current,a,k,m,h,y,Le,ye);if(Ce!=null&&(X.current=Ce,I(me)),k==="both")return}if(Rd(me.key,k)){if(pa(me),M&&!b&&Kn(me.currentTarget.ownerDocument)===me.currentTarget){X.current=ch(me.key,k,h)?Le:ye,I(me);return}ch(me.key,k,h)?m?de>=ye?f&&de!==a.current.length?X.current=-1:(F.current=!1,X.current=Le):X.current=Qa(a.current,{startingIndex:de,disabledIndices:y}):X.current=Math.min(ye,Qa(a.current,{startingIndex:de,disabledIndices:y})):m?de<=Le?f&&de!==-1?X.current=a.current.length:(F.current=!1,X.current=ye):X.current=Qa(a.current,{startingIndex:de,decrement:!0,disabledIndices:y}):X.current=Math.max(Le,Qa(a.current,{startingIndex:de,decrement:!0,disabledIndices:y})),Rc(a.current,X.current)&&(X.current=-1),I(me)}}),Ne=x.useMemo(()=>({onFocus(de){F.current=!0,Ae(de)},onClick:({currentTarget:de})=>de.focus({preventScroll:!0}),onMouseMove(de){tk(de)||(F.current=!0,ne.current=!1,j&&Ae(de))},onPointerLeave(de){if(!Y.current||!W.current||de.pointerType==="touch")return;F.current=!0;const Le=de.relatedTarget;if(!(!j||a.current.includes(Le))&&ve.current&&(Z.current?.(),Z.current=null,X.current=-1,I(de),!b)){const ye=q.current,Ce=Kn(vt(ye));ye&&Ze(ye,Ce)&&ye.focus({preventScroll:!0})}}}),[Ae,Y,q,j,a,I,ve,b]),Me=x.useMemo(()=>b&&M&&Re&&{"aria-activedescendant":`${w}-${o}`},[b,M,Re,w,o]),De=x.useMemo(()=>({"aria-orientation":k==="both"?void 0:k,...$?{}:Me,onKeyDown(me){if(me.key==="Tab"&&me.shiftKey&&M&&!b){const de=qn(me.nativeEvent);if(de&&!Ze(q.current,de))return;pa(me),z.setOpen(!1,rt(zo,me.nativeEvent)),Gt(P)&&P.focus();return}Te(me)},onPointerMove(me){tk(me)||(W.current=!0)}}),[Me,Te,q,k,$,z,M,b,P]),Ue=x.useMemo(()=>{function me(ye){z.setOpen(!0,rt(bx,ye.nativeEvent,ye.currentTarget))}function de(ye){_==="auto"&&zb(ye.nativeEvent)&&(V.current=!b)}function Le(ye){V.current=_,_==="auto"&&Ob(ye.nativeEvent)&&(V.current=!0)}return{onKeyDown(ye){const Ce=z.select("open");W.current=!1;const Qe=ye.key.startsWith("Arrow"),Ge=$O(ye.key,Ie(),h),lt=Rd(ye.key,k),Tt=(g?Ge:lt)||ye.key==="Enter"||ye.key.trim()==="";if(b&&Ce)return Te(ye);if(!(!Ce&&!E&&Qe)){if(Tt){const _t=Rd(ye.key,Ie());Q.current=g&&_t?null:ye.key}if(g){Ge&&(pa(ye),Ce?(X.current=Oe(),I(ye)):me(ye));return}lt&&(oe.current!=null&&(X.current=oe.current),pa(ye),!Ce&&E?me(ye):Te(ye),Ce&&I(ye))}},onFocus(ye){z.select("open")&&!b&&(X.current=-1,I(ye))},onPointerDown:Le,onPointerEnter:Le,onMouseDown:de,onClick:de}},[Te,_,Oe,g,I,z,E,k,Ie,h,oe,b]),Xe=x.useMemo(()=>({...Me,...Ue}),[Me,Ue]);return x.useMemo(()=>c?{reference:Xe,floating:De,item:Ne,trigger:Ue}:{},[c,Xe,De,Ue,Ne])}function wC(e,t){const{listRef:a,elementsRef:o,activeIndex:l,onMatch:c,disabledIndices:d,onTyping:f,enabled:m=!0,resetMs:g=750,selectedIndex:h=null}=t,b="rootStore"in e?e.rootStore:e,_=b.useState("open"),j=Rn(),E=x.useRef(""),y=x.useRef(h??l??-1),k=x.useRef(null),N=He(R=>{function A(q){return o?.current[q]}function T(q){const G=A(q);return G&&!lp(G)||G?.matches(":disabled")?!1:d==null||!xf(ja,q,d)}function z(q,G,U=0){if(q.length===0)return-1;const V=(U%q.length+q.length)%q.length,X=G.toLowerCase();for(let Q=0;Q<q.length;Q+=1){const W=(V+Q)%q.length;if(!(!q[W]?.toLowerCase().startsWith(X)||!T(W)))return W}return-1}const M=a.current;if(E.current.length>0&&R.key===" "&&(pa(R),f?.(!0)),E.current.length>0&&E.current[0]!==" "&&z(M,E.current)===-1&&R.key!==" "&&f?.(!1),M==null||R.key.length!==1||R.ctrlKey||R.metaKey||R.altKey)return;_&&R.key!==" "&&(pa(R),f?.(!0));const L=E.current==="";L&&(y.current=h??l??-1),M.every((q,G)=>q&&T(G)?q[0]?.toLowerCase()!==q[1]?.toLowerCase():!0)&&E.current===R.key&&(E.current="",y.current=k.current),E.current+=R.key,j.start(g,()=>{E.current="",y.current=k.current,f?.(!1)});const D=((L?h??l??-1:y.current)??0)+1,$=z(M,E.current,D);$!==-1?(c?.($),k.current=$):R.key!==" "&&(E.current="",f?.(!1))}),w=He(R=>{const A=R.relatedTarget,T=b.select("domReferenceElement"),z=b.select("floatingElement");Ze(T,A)||Ze(z,A)||(j.clear(),E.current="",y.current=k.current,f?.(!1))});Pe(()=>{!_&&h!==null||(j.clear(),k.current=null,E.current!==""&&(E.current=""))},[_,h,j]);const S=x.useMemo(()=>({onKeyDown:N,onBlur:w}),[N,w]);return x.useMemo(()=>m?{reference:S,floating:S}:{},[m,S])}const nk=.1,qO=nk*nk,Vt=.5;function Td(e,t,a,o,l,c){return o>=t!=c>=t&&e<=(l-a)*(t-o)/(c-o)+a}function Ad(e,t,a,o,l,c,d,f,m,g){let h=!1;return Td(e,t,a,o,l,c)&&(h=!h),Td(e,t,l,c,d,f)&&(h=!h),Td(e,t,d,f,m,g)&&(h=!h),Td(e,t,m,g,a,o)&&(h=!h),h}function HO(e,t,a){return e>=a.x&&e<=a.x+a.width&&t>=a.y&&t<=a.y+a.height}function Md(e,t,a,o,l,c){const d=Math.min(a,l),f=Math.max(a,l),m=Math.min(o,c),g=Math.max(o,c);return e>=d&&e<=f&&t>=m&&t<=g}function SC(e={}){const{blockPointerEvents:t=!1}=e,a=new ta,o=({x:l,y:c,placement:d,elements:f,onClose:m,nodeId:g,tree:h})=>{const b=d?.split("-")[0];let _=!1,j=null,E=null,y=typeof performance<"u"?performance.now():0;function k(w,S){const R=performance.now(),A=R-y;if(j===null||E===null||A===0)return j=w,E=S,y=R,!1;const T=w-j,z=S-E,M=T*T+z*z,L=A*A*qO;return j=w,E=S,y=R,M<L}function N(){a.clear(),m()}return function(S){a.clear();const R=f.domReference,A=f.floating;if(!R||!A||b==null||l==null||c==null)return;const{clientX:T,clientY:z}=S,M=qn(S),L=S.type==="mouseleave",P=Ze(A,M),B=Ze(R,M);if(P&&(_=!0,!L))return;if(B&&(_=!1,!L)){_=!0;return}if(L&&bt(S.relatedTarget)&&Ze(A,S.relatedTarget))return;function D(){return!!(h&&Qr(h.nodesRef.current,g).length>0)}function $(){D()||N()}if(D())return;const q=R.getBoundingClientRect(),G=A.getBoundingClientRect(),U=l>G.right-G.width/2,V=c>G.bottom-G.height/2,X=G.width>q.width,Q=G.height>q.height,W=(X?q:G).left,I=(X?q:G).right,K=(Q?q:G).top,ee=(Q?q:G).bottom;if(b==="top"&&c>=q.bottom-1||b==="bottom"&&c<=q.top+1||b==="left"&&l>=q.right-1||b==="right"&&l<=q.left+1){$();return}let F=!1;switch(b){case"top":F=Md(T,z,W,q.top+1,I,G.bottom-1);break;case"bottom":F=Md(T,z,W,G.top+1,I,q.bottom-1);break;case"left":F=Md(T,z,G.right-1,ee,q.left+1,K);break;case"right":F=Md(T,z,q.right-1,ee,G.left+1,K);break}if(F)return;if(_&&!HO(T,z,q)){$();return}if(!L&&k(T,z)){$();return}let ne=!1;switch(b){case"top":{const Z=X?Vt/2:Vt*4,fe=X||U?l+Z:l-Z,Y=X?l-Z:U?l+Z:l-Z,oe=c+Vt+1,ve=U||X?G.bottom-Vt:G.top,le=U?X?G.bottom-Vt:G.top:G.bottom-Vt;ne=Ad(T,z,fe,oe,Y,oe,G.left,ve,G.right,le);break}case"bottom":{const Z=X?Vt/2:Vt*4,fe=X||U?l+Z:l-Z,Y=X?l-Z:U?l+Z:l-Z,oe=c-Vt,ve=U||X?G.top+Vt:G.bottom,le=U?X?G.top+Vt:G.bottom:G.top+Vt;ne=Ad(T,z,fe,oe,Y,oe,G.left,ve,G.right,le);break}case"left":{const Z=Q?Vt/2:Vt*4,fe=Q||V?c+Z:c-Z,Y=Q?c-Z:V?c+Z:c-Z,oe=l+Vt+1,ve=V||Q?G.right-Vt:G.left,le=V?Q?G.right-Vt:G.left:G.right-Vt;ne=Ad(T,z,ve,G.top,le,G.bottom,oe,fe,oe,Y);break}case"right":{const Z=Q?Vt/2:Vt*4,fe=Q||V?c+Z:c-Z,Y=Q?c-Z:V?c+Z:c-Z,oe=l-Vt,ve=V||Q?G.left+Vt:G.right,le=V?Q?G.left+Vt:G.right:G.left+Vt;ne=Ad(T,z,oe,fe,oe,Y,ve,G.top,le,G.bottom);break}}ne?_||a.start(40,$):$()}};return o.__options={...e,blockPointerEvents:t},o}const VO={...i_,disabled:e=>e.disabled,instantType:e=>e.instantType,isInstantPhase:e=>e.isInstantPhase,trackCursorAxis:e=>e.trackCursorAxis,disableHoverablePopup:e=>e.disableHoverablePopup,lastOpenChangeReason:e=>e.openChangeReason,closeOnClick:e=>e.closeOnClick,closeDelay:e=>e.closeDelay,adaptiveOrigin:e=>e.adaptiveOrigin};class FO extends nu{constructor(t,a,o){const l=new su;super(GO(t,l,a,o),YO(l),VO)}setOpen=(t,a)=>{AO(this,t,a,{extraState:{openChangeReason:a.reason}})};cancelPendingOpen(t){this.state.floatingRootContext.dispatchOpenChange(!1,rt(gi,t))}}function GO(e,t,a,o=!1){const l={...o_(),disabled:!1,instantType:void 0,isInstantPhase:!1,trackCursorAxis:"none",disableHoverablePopup:!1,openChangeReason:null,closeOnClick:!0,closeDelay:0,adaptiveOrigin:void 0,...e};return l.floatingRootContext=hC(t,a,o),l}function YO(e){return{popupRef:x.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerElements:e}}const KO=Rb(function(t){const{disabled:a=!1,defaultOpen:o=!1,open:l,disableHoverablePopup:c=!1,trackCursorAxis:d="none",actionsRef:f,onOpenChange:m,onOpenChangeComplete:g,handle:h,triggerId:b,defaultTriggerId:_=null,children:j}=t,E=pC((B,D)=>new FO({open:o,openProp:l,activeTriggerId:_,triggerIdProp:b},B,D));E.useControlledProp("openProp",l),E.useControlledProp("triggerIdProp",b),E.useContextCallback("onOpenChange",m),E.useContextCallback("onOpenChangeComplete",g);const y=E.useState("open"),k=!a&&y,N=E.useState("activeTriggerId"),w=E.useState("mounted"),S=E.useState("payload");E.useSyncedValues({trackCursorAxis:d,disableHoverablePopup:c,disabled:a}),s_(E,{closeOnActiveTriggerUnmount:!0});const{forceUnmount:R,transitionStatus:A}=a_(k,E),T=E.useState("isInstantPhase"),z=E.useState("instantType"),M=E.useState("lastOpenChangeReason"),L=x.useRef(null);Pe(()=>{y&&a&&E.setOpen(!1,rt(jS))},[y,a,E]),Pe(()=>{A==="ending"&&M===ka||A!=="ending"&&T?(z!=="delay"&&(L.current=z),E.set("instantType","delay")):L.current!==null&&(E.set("instantType",L.current),L.current=null)},[A,T,M,z,E]),Pe(()=>{k&&N==null&&E.set("payload",void 0)},[E,N,k]),x.useImperativeHandle(f,()=>({unmount:R,close:()=>E.setOpen(!1,rt(Bb))}),[R,E]);const P=k||w||!a&&d!=="none";return n.jsxs(hS.Provider,{value:E,children:[h&&n.jsx(t_,{handle:h,store:E}),P&&n.jsx(XO,{store:E,disabled:a,trackCursorAxis:d}),typeof j=="function"?j({payload:S}):j]})});function XO({store:e,disabled:t,trackCursorAxis:a}){const o=e.useState("floatingRootContext"),l=ip(o,{enabled:!t,referencePress:()=>e.select("closeOnClick")}),c=Az(o,{enabled:!t&&a!=="none",axis:a==="none"?void 0:a}),d=x.useMemo(()=>Ss(c.reference,l.reference),[c.reference,l.reference]);return r_(e,{activeTriggerProps:d,inactiveTriggerProps:d,popupProps:l.floating??sn}),null}let sk=(function(e){return e.startingStyle="data-starting-style",e.endingStyle="data-ending-style",e})({});const QO={"data-starting-style":""},WO={"data-ending-style":""},Ho={transitionStatus(e){return e==="starting"?QO:e==="ending"?WO:null}};(function(e){return e.open="data-open",e.closed="data-closed",e[e.startingStyle=sk.startingStyle]="startingStyle",e[e.endingStyle=sk.endingStyle]="endingStyle",e.anchorHidden="data-anchor-hidden",e.side="data-side",e.align="data-align",e})({});const ZO={"data-popup-open":""},JO={"data-popup-open":"","data-pressed":""},e6={"data-open":""},t6={"data-closed":""},n6={"data-anchor-hidden":""},CC={open(e){return e?ZO:null}},wx={open(e){return e?JO:null}},au={open(e){return e?e6:t6},anchorHidden(e){return e?n6:null}},d_={...au,...Ho};function ra(e){return Oo(e,"base-ui")}const NC=x.createContext(void 0);function s6(){return x.useContext(NC)}const ak=600,EC="data-base-ui-tooltip-trigger";function rk(e){if("composedPath"in e){const a=e.composedPath();for(let o=0;o<a.length;o+=1){const l=a[o];if(bt(l))return l}}const t=e.target;return bt(t)?t:null}function a6(e){let t=e;for(;t;){const a=t.closest(`[${EC}]`);if(a)return a;const o=t.getRootNode();t="host"in o&&bt(o.host)?o.host:null}return null}const r6=gS(function(t,a){const{render:o,className:l,style:c,handle:d,payload:f,disabled:m,delay:g,closeOnClick:h=!0,closeDelay:b,id:_,...j}=t,E=Jc(!0),k=bC(d)??E;if(!k)throw new Error(gn(82));const N=ra(_),w=k.useState("isTriggerActive",N),S=k.useState("isOpenedByTrigger",N),R=k.useState("floatingRootContext"),A=x.useRef(null),T=g??ak,z=b??0,{registerTrigger:M,isMountedByThisTrigger:L}=gC(N,A,k,{payload:f,closeOnClick:h,closeDelay:z}),P=s6(),{delayRef:B,isInstantPhase:D,hasProvider:$}=M4(R,{open:S}),q=u_(R);k.useSyncedValue("isInstantPhase",D);const G=k.useState("disabled"),U=m??G,V=mn(U),X=k.useState("trackCursorAxis"),Q=k.useState("disableHoverablePopup"),W=x.useRef(!1),I=Rn(),K=x.useRef(void 0);function ee(){return $?Kr(B.current,"open")===0?0:g??P??ak:T}function F(ke){const Re=A.current;if(!Re||!ke)return!1;const Ae=a6(ke);return Ae!==null&&Ae!==Re&&Ze(Re,Ae)}function ne(ke){const Re=F(ke);return W.current=Re,Re&&(q.openChangeTimeout.clear(),q.restTimeout.clear(),q.restTimeoutPending=!1,I.clear()),Re}const Z=jC(R,{enabled:!U,mouseOnly:!0,move:!1,handleClose:!Q&&X!=="both"?SC():null,restMs:ee,delay(){return b==null&&$?{close:Kr(B.current,"close")}:{close:z}},triggerElementRef:A,isActiveTrigger:w,isClosing:()=>k.select("transitionStatus")==="ending",shouldOpen(){return!W.current}}),fe=_C(R,{enabled:!U}).reference,Y=ke=>{const Re=W.current,Ae=rk(ke),Ie=ne(Ae),Oe=A.current,Te=Oe&&Ae&&Ze(Oe,Ae);if(Ie&&k.select("open")&&k.select("lastOpenChangeReason")===En){k.setOpen(!1,rt(En,ke));return}if(Re&&!Ie&&Te&&!V.current&&!k.select("open")&&Oe&&Hr(K.current)){const Ne=()=>{!W.current&&!V.current&&!k.select("open")&&k.setOpen(!0,rt(En,ke,Oe))},Me=ee();Me===0?(I.clear(),Ne()):I.start(Me,Ne)}},oe=k.useState("triggerProps",L);return Et("button",t,{state:{open:S},ref:[a,M,A],props:[Z,fe,L||X!=="none"?oe:void 0,{onMouseOver(ke){Y(ke.nativeEvent)},onFocus(ke){F(rk(ke.nativeEvent))&&ke.preventBaseUIHandler()},onMouseLeave(){W.current=!1,I.clear(),K.current=void 0},onPointerEnter(ke){K.current=ke.pointerType},onPointerDown(ke){K.current=ke.pointerType,k.set("closeOnClick",h),h&&!k.select("open")&&k.cancelPendingOpen(ke.nativeEvent)},onClick(ke){h&&!k.select("open")&&k.cancelPendingOpen(ke.nativeEvent)},id:N,"data-trigger-disabled":U?"":void 0,[EC]:U?void 0:""},j],stateAttributesMapping:CC})}),RC=x.createContext(void 0);function o6(){const e=x.useContext(RC);if(e===void 0)throw new Error(gn(70));return e}const l6=x.forwardRef(function(t,a){const{children:o,container:l,className:c,render:d,style:f,...m}=t,{node:g,subtree:h}=QS({container:l,ref:a,componentProps:t,elementProps:m});return!h&&!g?null:n.jsxs(x.Fragment,{children:[h,g&&Gs.createPortal(o,g)]})}),i6=x.forwardRef(function(t,a){const{keepMounted:o=!1,...l}=t;return Jc().useState("mounted")||o?n.jsx(RC.Provider,{value:o,children:n.jsx(l6,{ref:a,...l})}):null}),TC=x.createContext(void 0);function AC(){const e=x.useContext(TC);if(e===void 0)throw new Error(gn(71));return e}const c6=x.createContext(void 0);function pp(){return x.useContext(c6)?.direction??"ltr"}const u6=e=>({name:"arrow",options:e,async fn(t){const{x:a,y:o,placement:l,rects:c,platform:d,elements:f,middlewareData:m}=t,{element:g,padding:h=0,offsetParent:b="real"}=Xr(e,t)||{};if(g==null)return{};const _=RS(h),j={x:a,y:o},E=Vb(l),y=Hb(E),k=await d.getDimensions(g),N=E==="y",w=N?"top":"left",S=N?"bottom":"right",R=N?"clientHeight":"clientWidth",A=c.reference[y]+c.reference[E]-j[E]-c.floating[y],T=j[E]-c.reference[E],z=b==="real"?await d.getOffsetParent?.(g):f.floating;let M=f.floating[R]||c.floating[y];(!M||!await d.isElement?.(z))&&(M=f.floating[R]||c.floating[y]);const L=A/2-T/2,P=M/2-k[y]/2-1,B=Math.min(_[w],P),D=Math.min(_[S],P),$=B,q=M-k[y]-D,G=M/2-k[y]/2+L,U=ES($,G,q),V=!m.arrow&&Jr(l)!=null&&G!==U&&c.reference[y]/2-(G<$?B:D)-k[y]/2<0,X=V?G<$?G-$:G-q:0;return{[E]:j[E]+X,data:{[E]:U,centerOffset:G-U-X,...V&&{alignmentOffset:X}},reset:V}}}),d6=(e,t)=>({...u6(e),options:[e,t]}),f6={name:"hide",async fn(e){const{width:t,height:a,x:o,y:l}=e.rects.reference,c=t===0&&a===0&&o===0&&l===0,d=await e.platform.detectOverflow(e,{elementContext:"reference"});return{data:{referenceHidden:d.top-a>=0||d.right-t>=0||d.bottom-a>=0||d.left-t>=0||c}}}},p6={sideX:"left",sideY:"top"},ok="--available-width",lk="--available-height";function MC(e,t,a){const o=e==="inline-start"||e==="inline-end";return{top:"top",right:o?a?"inline-start":"inline-end":"right",bottom:"bottom",left:o?a?"inline-end":"inline-start":"left"}[t]}function ik(e,t,a){const{rects:o,placement:l}=e;return{side:MC(t,Vs(l),a),align:Jr(l)||"center",anchor:{width:o.reference.width,height:o.reference.height},positioner:{width:o.floating.width,height:o.floating.height}}}function f_(e){return m6(e,PO)}function m6(e,t){const{anchor:a,positionMethod:o="absolute",side:l="bottom",sideOffset:c=0,align:d="center",alignOffset:f=0,collisionBoundary:m,collisionPadding:g=5,sticky:h=!1,arrowPadding:b=5,disableAnchorTracking:_=!1,inline:j,keepMounted:E=!1,floatingRootContext:y,mounted:k,collisionAvoidance:N,shift:w,nodeId:S,adaptiveOrigin:R,lazyFlip:A=!1,externalTree:T}=e,[z,M]=x.useState(null);!k&&z!==null&&M(null);const L=N.side||"flip",P=N.align||"flip",B=N.fallbackAxisSide||"end",D=w?.crossAxis??!1,$=w?.rootBoundary,q=typeof a=="function"?a:void 0,G=He(q),U=q?G:a,V=mn(a),X=mn(k),W=pp()==="rtl",I=z||{top:"top",right:"right",bottom:"bottom",left:"left","inline-end":W?"left":"right","inline-start":W?"right":"left"}[l],K=d==="center"?I:`${I}-${d}`;let ee=g;typeof ee=="number"?ee={top:ee,right:ee,bottom:ee,left:ee}:ee&&(ee={top:ee.top||0,right:ee.right||0,bottom:ee.bottom||0,left:ee.left||0});const F=1,ne=l==="bottom"?F:0,Z=l==="top"?F:0,fe=l==="right"?F:0,Y=l==="left"?F:0,oe={boundary:m==="clipping-ancestors"?"clippingAncestors":m,padding:ee},ve=x.useRef(null),le=mn(c),xe=mn(f),ke=typeof c!="function"?c:0,Re=typeof f!="function"?f:0,Ae=[];j&&Ae.push(j),Ae.push(pO(ot=>{const Pt=ik(ot,l,W),on=typeof le.current=="function"?le.current(Pt):le.current,Yt=typeof xe.current=="function"?xe.current(Pt):xe.current;return{mainAxis:on,crossAxis:Yt,alignmentAxis:Yt}},[ke,Re,W,l]));const Ie=P==="none"&&L!=="shift",Oe=!Ie&&(h||D||L==="shift"),Te=L==="none"?null:hO({...oe,padding:{top:ee.top+F+ne,right:ee.right+F+Y,bottom:ee.bottom+F+Z,left:ee.left+F+fe},mainAxis:!D&&L==="flip",crossAxis:P==="flip"?"alignment":!1,fallbackAxisSideDirection:B}),Ne=Ie?null:mO({...oe,rootBoundary:$,mainAxis:P!=="none",crossAxis:Oe,limiter:h||D?void 0:gO(ot=>{if(!ve.current)return{};const{width:Pt,height:on}=ve.current.getBoundingClientRect(),Yt=Hs(Vs(ot.placement)),Fn=Yt==="y"?Pt:on,Tn=Yt==="y"?ee.left+ee.right:ee.top+ee.bottom;return{offset:Fn/2+Tn/2}})},[oe,h,D,$,ee,P]);L==="shift"||P==="shift"||d==="center"?Ae.push(Ne,Te):Ae.push(Te,Ne),Ae.push(xO({...oe,apply({elements:{floating:ot},availableWidth:Pt,availableHeight:on,rects:Yt}){if(!X.current)return;const Fn=ot.style;Fn.setProperty(ok,`${Pt}px`),Fn.setProperty(lk,`${on}px`);const Tn=Jt(ot).devicePixelRatio||1,{x:as,y:dn,width:hs,height:Rs}=Yt.reference,oa=(Math.round((as+hs)*Tn)-Math.round(as*Tn))/Tn,ht=(Math.round((dn+Rs)*Tn)-Math.round(dn*Tn))/Tn;Fn.setProperty("--anchor-width",`${oa}px`),Fn.setProperty("--anchor-height",`${ht}px`)}}),d6(ot=>({element:ve.current||vt(ot.elements.floating).createElement("div"),padding:b,offsetParent:"floating"}),[b]),{name:"transformOrigin",fn(ot){const{elements:Pt,middlewareData:on,placement:Yt,rects:Fn,y:Tn}=ot,as=Vs(Yt),dn=Hs(as),hs=ve.current,Rs=on.arrow?.x||0,oa=on.arrow?.y||0,ht=hs?.clientWidth||0,$t=hs?.clientHeight||0,Ln=Rs+ht/2,rs=oa+$t/2,xs=Math.abs(on.shift?.y||0),An=Fn.reference.height/2,Wt=typeof c=="function"?c(ik(ot,l,W)):c,vn=xs>Wt,la={top:`${Ln}px calc(100% + ${Wt}px)`,bottom:`${Ln}px ${-Wt}px`,left:`calc(100% + ${Wt}px) ${rs}px`,right:`${-Wt}px ${rs}px`}[as],dr=`${Ln}px ${Fn.reference.y+An-Tn}px`;return Pt.floating.style.setProperty("--transform-origin",Oe&&dn==="y"&&vn?dr:la),{}}},f6,R),Pe(()=>{!k&&y&&y.update({referenceElement:null,floatingElement:null,domReferenceElement:null,positionReference:null})},[k,y]);const Me=x.useMemo(()=>({elementResize:!_&&typeof ResizeObserver<"u",layoutShift:!_&&typeof IntersectionObserver<"u"}),[_]),{refs:De,elements:Ue,x:Xe,y:me,middlewareData:de,update:Le,placement:ye,context:Ce,isPositioned:Qe,floatingStyles:Ge}=t({rootContext:y,open:E?k:void 0,placement:K,middleware:Ae,strategy:o,whileElementsMounted:E?void 0:(...ot)=>Kj(...ot,Me),nodeId:S,externalTree:T}),{sideX:lt,sideY:Tt}=de.adaptiveOrigin||p6,_t=Qe?o:"fixed",Ct=x.useMemo(()=>{let ot;return Qe?R?ot={position:_t,[lt]:Xe,[Tt]:me}:ot={...Ge,position:_t}:ot={position:_t,top:0,left:0},ot[ok]="100vw",ot[lk]="100vh",Qe||(ot.opacity=0),ot},[R,_t,lt,Xe,Tt,me,Ge,Qe]),je=x.useRef(null);Pe(()=>{if(!k)return;const ot=V.current,Pt=typeof ot=="function"?ot():ot,Yt=(ck(Pt)?Pt.current:Pt)||null||null;Yt!==je.current&&(De.setPositionReference(Yt),je.current=Yt)},[k,De,U,V]),x.useEffect(()=>{if(!k)return;const ot=V.current;typeof ot!="function"&&ck(ot)&&ot.current!==je.current&&(De.setPositionReference(ot.current),je.current=ot.current)},[k,De,U,V]),x.useEffect(()=>{if(E&&k&&Ue.reference&&Ue.floating)return Kj(Ue.reference,Ue.floating,Le,Me)},[E,k,Ue,Le,Me]);const ze=Vs(ye),Ye=MC(l,ze,W),We=Jr(ye)||"center",dt=!!de.hide?.referenceHidden;Pe(()=>{A&&k&&Qe&&ze!==I&&M(ze)},[A,k,Qe,ze,I]);const Rt=x.useMemo(()=>({position:"absolute",top:de.arrow?.y,left:de.arrow?.x}),[de.arrow]),Qt=de.arrow?.centerOffset!==0;return x.useMemo(()=>({positionerStyles:Ct,arrowStyles:Rt,arrowRef:ve,arrowUncentered:Qt,side:Ye,align:We,physicalSide:ze,anchorHidden:dt,refs:De,context:Ce,isPositioned:Qe,update:Le}),[Ct,Rt,ve,Qt,Ye,We,ze,dt,De,Ce,Qe,Le])}function ck(e){return e!=null&&"current"in e}function mp(e){return e==="starting"?jz:sn}function p_(e,t,{styles:a,transitionStatus:o,props:l,refs:c,hidden:d,inert:f=!1}){const m={...a};return f&&(m.pointerEvents="none"),Et("div",e,{state:t,ref:c,props:[{role:"presentation",hidden:d,style:m},mp(o),l],stateAttributesMapping:au})}const g6=x.forwardRef(function(t,a){const{render:o,className:l,anchor:c,positionMethod:d="absolute",side:f="top",align:m="center",sideOffset:g=0,alignOffset:h=0,collisionBoundary:b="clipping-ancestors",collisionPadding:_=5,arrowPadding:j=5,sticky:E=!1,disableAnchorTracking:y=!1,collisionAvoidance:k=YS,style:N,...w}=t,S=Jc(),R=o6(),A=S.useState("open"),T=S.useState("mounted"),z=S.useState("trackCursorAxis"),M=S.useState("disableHoverablePopup"),L=S.useState("floatingRootContext"),P=S.useState("instantType"),B=S.useState("transitionStatus"),D=S.useState("adaptiveOrigin"),$=f_({anchor:c,positionMethod:d,floatingRootContext:L,mounted:T,side:f,sideOffset:g,align:m,alignOffset:h,collisionBoundary:b,collisionPadding:_,sticky:E,arrowPadding:j,disableAnchorTracking:y,keepMounted:R,collisionAvoidance:k,adaptiveOrigin:D}),q=x.useMemo(()=>({open:A,side:$.side,align:$.align,anchorHidden:$.anchorHidden,instant:z!=="none"?"tracking-cursor":P}),[A,$.side,$.align,$.anchorHidden,z,P]),G=p_(t,q,{styles:$.positionerStyles,transitionStatus:B,props:w,refs:[a,S.useStateSetter("positionerElement")],hidden:!T,inert:!A||z==="both"||M});return n.jsx(TC.Provider,{value:$,children:G})}),h6=x.forwardRef(function(t,a){const{render:o,className:l,style:c,...d}=t,f=Jc(),{side:m,align:g}=AC(),h=f.useState("open"),b=f.useState("instantType"),_=f.useState("transitionStatus"),j=f.useState("popupProps"),E=f.useState("floatingRootContext"),y=f.useState("disabled"),k=f.useState("closeDelay");Ca({open:h,ref:f.context.popupRef,onComplete(){h&&f.context.onOpenChangeComplete?.(!0)}}),yC(E,{enabled:!y,closeDelay:k});const N=f.useStateSetter("popupElement");return Et("div",t,{state:{open:h,side:m,align:g,instant:b,transitionStatus:_},ref:[a,f.context.popupRef,N],props:[dp,j,mp(_),d],stateAttributesMapping:d_})}),x6=x.forwardRef(function(t,a){const{render:o,className:l,style:c,...d}=t,f=Jc(),{arrowRef:m,side:g,align:h,arrowUncentered:b,arrowStyles:_}=AC(),j=f.useState("open"),E=f.useState("instantType");return Et("div",t,{state:{open:j,side:g,align:h,uncentered:b,instant:E},ref:[a,m],props:[{style:_,"aria-hidden":!0},d],stateAttributesMapping:au})}),b6=function(t){const{delay:a,closeDelay:o,timeout:l=400}=t,c=x.useMemo(()=>({open:a,close:o}),[a,o]);return n.jsx(NC.Provider,{value:a,children:n.jsx(A4,{delay:c,timeoutMs:l,children:t.children})})};function gp(e){return Yb(19)?e:e?"true":void 0}function _6(e){const[t,a]=x.useState({current:e,previous:null});return Object.is(e,t.current)||a({current:e,previous:t.current}),t.previous}function St(...e){return mS(Pc(e))}function v6({delay:e=0,...t}){return n.jsx(b6,{"data-slot":"tooltip-provider",delay:e,...t})}function m_({...e}){return n.jsx(KO,{"data-slot":"tooltip",...e})}function g_({...e}){return n.jsx(r6,{"data-slot":"tooltip-trigger",...e})}function h_({className:e,side:t="top",sideOffset:a=4,align:o="center",alignOffset:l=0,children:c,...d}){return n.jsx(i6,{children:n.jsx(g6,{align:o,alignOffset:l,side:t,sideOffset:a,className:"isolate z-50",children:n.jsxs(h6,{"data-slot":"tooltip-content",className:St("z-50 inline-flex w-fit max-w-xs origin-(--transform-origin) items-center gap-1.5 rounded-md bg-foreground px-3 py-1.5 text-xs text-background has-data-[slot=kbd]:pr-1.5 data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 **:data-[slot=kbd]:relative **:data-[slot=kbd]:isolate **:data-[slot=kbd]:z-50 **:data-[slot=kbd]:rounded-sm data-[state=delayed-open]:animate-in data-[state=delayed-open]:fade-in-0 data-[state=delayed-open]:zoom-in-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",e),...d,children:[c,n.jsx(x6,{className:"z-50 size-2.5 translate-y-[calc(-50%-2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground data-[side=bottom]:top-1 data-[side=inline-end]:top-1/2! data-[side=inline-end]:-left-1 data-[side=inline-end]:-translate-y-1/2 data-[side=inline-start]:top-1/2! data-[side=inline-start]:-right-1 data-[side=inline-start]:-translate-y-1/2 data-[side=left]:top-1/2! data-[side=left]:-right-1 data-[side=left]:-translate-y-1/2 data-[side=right]:top-1/2! data-[side=right]:-left-1 data-[side=right]:-translate-y-1/2 data-[side=top]:-bottom-2.5"})]})})})}function Ml({label:e,active:t,onClick:a,isAdd:o,isSettings:l,isDefault:c,icon:d,title:f,testId:m}){const g=e.trim()||"·",{initials:h,subLabel:b}=zC(g),_=o||l?"indigo":OC(g),j=b&&!o&&!l&&!c;return n.jsxs(m_,{children:[n.jsx(g_,{render:n.jsxs("button",{type:"button",onClick:a,"data-testid":m,className:"group relative flex w-full cursor-pointer flex-col items-center gap-1",children:[n.jsx("span",{className:ge("flex size-10 items-center justify-center rounded-xl text-sm font-bold transition-all",t&&"ring-2 ring-foreground ring-offset-2 ring-offset-card",o&&"border border-dashed border-muted-fg/50 bg-transparent text-muted-fg hover:bg-accent/60 hover:text-foreground",l&&"bg-muted text-muted-fg hover:bg-accent hover:text-foreground",c&&"overflow-hidden bg-muted",!o&&!l&&!c&&t&&w6(_),!o&&!l&&!c&&!t&&k6(_)),children:d??h}),j&&n.jsx("span",{className:"block max-w-[3.6rem] truncate text-[9px] leading-tight text-muted-fg group-hover:text-foreground",children:b})]})}),n.jsx(h_,{side:"right",children:f||e})]})}function zC(e){const t=e.trim().replace(/[_\-.]+/g," ").replace(/\s+/g," ");if(!t)return{initials:"·",subLabel:null};const a=t.split(" ");if(a.length>=2)return{initials:(a[0][0]+a[1][0]).toUpperCase(),subLabel:y6(t)};const o=a[0];return o.length<=4?{initials:o[0].toUpperCase(),subLabel:o}:{initials:o[0].toUpperCase(),subLabel:o.slice(0,4)+"…"}}function y6(e){return e.length>6?e.slice(0,5)+"…":e}function OC(e){let t=0;for(let a=0;a<e.length;a++)t=t*31+e.charCodeAt(a)|0;return _j[Math.abs(t)%_j.length]}const DC={sky:"bg-sky-500/15 text-sky-300 hover:bg-sky-500/25",violet:"bg-violet-500/15 text-violet-300 hover:bg-violet-500/25",emerald:"bg-emerald-500/15 text-emerald-300 hover:bg-emerald-500/25",amber:"bg-amber-500/15 text-amber-300 hover:bg-amber-500/25",rose:"bg-rose-500/15 text-rose-300 hover:bg-rose-500/25",indigo:"bg-indigo-500/15 text-indigo-300 hover:bg-indigo-500/25",teal:"bg-teal-500/15 text-teal-300 hover:bg-teal-500/25",fuchsia:"bg-fuchsia-500/15 text-fuchsia-300 hover:bg-fuchsia-500/25"},j6={sky:"bg-sky-500/30 text-sky-100",violet:"bg-violet-500/30 text-violet-100",emerald:"bg-emerald-500/30 text-emerald-100",amber:"bg-amber-500/30 text-amber-100",rose:"bg-rose-500/30 text-rose-100",indigo:"bg-indigo-500/30 text-indigo-100",teal:"bg-teal-500/30 text-teal-100",fuchsia:"bg-fuchsia-500/30 text-fuchsia-100"};function k6(e){return DC[e]}function w6(e){return j6[e]}function S6(e){const{initials:t}=zC(e);return{initials:t,idleClass:DC[OC(e)]}}function qe({content:e,side:t="top",children:a}){return e?n.jsxs(m_,{children:[n.jsx(g_,{render:a}),n.jsx(h_,{side:t,children:e})]}):a}const PC=x.createContext(void 0);function x_(e){const t=x.useContext(PC);if(t===void 0&&!e)throw new Error(gn(33));return t}const LC=x.createContext(void 0);function Vo(e){const t=x.useContext(LC);if(t===void 0&&!e)throw new Error(gn(36));return t}const C6=x.createContext(void 0);function b_(e=!0){const t=x.useContext(C6);if(t===void 0&&!e)throw new Error(gn(25));return t}function ni({controlled:e,default:t,name:a,state:o="value"}){const{current:l}=x.useRef(e!==void 0),[c,d]=x.useState(t),f=l?e:c,m=x.useCallback(g=>{l||d(g)},[]);return[f,m]}const IC=x.createContext(void 0);function hp(e=!1){const t=x.useContext(IC);if(t===void 0&&!e)throw new Error(gn(16));return t}function N6(e){const{focusableWhenDisabled:t,disabled:a,composite:o=!1,tabIndex:l=0,isNativeButton:c}=e,d=o&&t!==!1,f=o&&t===!1;return{props:x.useMemo(()=>{const g={onKeyDown(h){a&&t&&h.key!=="Tab"&&h.preventDefault()}};return o||(g.tabIndex=l,!c&&a&&(g.tabIndex=t?l:-1)),(c&&(t||d)||!c&&a)&&(g["aria-disabled"]=a),c&&(!t||f)&&(g.disabled=a),g},[o,a,t,d,f,c,l])}}function Ac(e,t,{detail:a=0}={}){e.dispatchEvent(new(Jt(e)).PointerEvent("click",{bubbles:!0,cancelable:!0,composed:!0,detail:a,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,altKey:t.altKey,metaKey:t.metaKey}))}function no(e={}){const{disabled:t=!1,focusableWhenDisabled:a,tabIndex:o=0,native:l=!0,composite:c}=e,d=x.useRef(null),f=hp(!0),m=c??f!==void 0,{props:g}=N6({focusableWhenDisabled:a,disabled:t,composite:m,tabIndex:o,isNativeButton:l}),h=x.useCallback(()=>{const j=d.current;uh(j)&&m&&t&&g.disabled===void 0&&j.disabled&&(j.disabled=!1)},[t,g.disabled,m]);Pe(h,[h]);const b=x.useCallback((j={})=>{const{onClick:E,onMouseDown:y,onKeyUp:k,onKeyDown:N,onPointerDown:w,...S}=j;return Ss({onClick(R){if(t){R.preventDefault();return}E?.(R)},onMouseDown(R){t||y?.(R)},onKeyDown(R){if(t||(_f(R),N?.(R),R.baseUIHandlerPrevented))return;const A=R.target===R.currentTarget,T=R.currentTarget,z=uh(T),M=!l&&E6(T),L=A&&(l?z:!M),P=R.key==="Enter",B=R.key===" ",D=T.getAttribute("role"),$=D?.startsWith("menuitem")||D==="option"||D==="gridcell";if(A&&m&&B){if(R.defaultPrevented&&$)return;R.preventDefault(),(!l||z)&&(R.preventBaseUIHandler(),Ac(T,R));return}if(!L||l||!B&&!P){A&&M&&B&&R.preventDefault();return}R.defaultPrevented||(R.preventDefault(),P&&(R.preventBaseUIHandler(),Ac(T,R)))},onKeyUp(R){if(!t){if(_f(R),k?.(R),R.target===R.currentTarget&&l&&m&&uh(R.currentTarget)&&R.key===" "){R.preventDefault();return}R.baseUIHandlerPrevented||R.target===R.currentTarget&&!l&&!m&&!R.defaultPrevented&&R.key===" "&&(R.preventBaseUIHandler(),Ac(R.currentTarget,R))}},onPointerDown(R){if(t){R.preventDefault();return}w?.(R)}},l?{type:"button"}:{role:"button"},g,S)},[t,g,m,l]),_=He(j=>{d.current=j,h()});return{getButtonProps:b,buttonRef:_}}function uh(e){return Gt(e)&&e.tagName==="BUTTON"}function E6(e){return Gt(e)&&e.tagName==="A"&&!!e.href}function R6(e){const{closeOnClick:t,highlighted:a,id:o,nodeId:l,store:c,typingRef:d,itemRef:f,itemMetadata:m}=e,{events:g}=c.useState("floatingTreeRoot"),h=c.useState("open"),b=b_(!0),_=b!==void 0;return x.useMemo(()=>({id:o,role:"menuitem",tabIndex:h&&a?0:-1,onKeyDown(j){j.key===" "&&d?.current&&j.preventDefault()},onMouseMove(j){l&&g.emit("itemhover",{nodeId:l,target:j.currentTarget})},onClick(j){t&&g.emit("close",{domEvent:j,reason:Fl})},onMouseUp(j){if(b){const E=b.initialCursorPointRef.current;if(b.initialCursorPointRef.current=null,_&&E&&Math.abs(j.clientX-E.x)<=1&&Math.abs(j.clientY-E.y)<=1||_&&!Ab&&j.button===2)return}f.current&&c.context.allowMouseUpTriggerRef.current&&(!_||j.button===2)&&m.type==="regular-item"&&Ac(f.current,j,{detail:1})}}),[t,a,o,g,l,h,c,d,f,b,_,m])}const BC={type:"regular-item"};function $C(e){const{closeOnClick:t,disabled:a,highlighted:o,id:l,store:c,typingRef:d=c.context.typingRef,nativeButton:f,itemMetadata:m,nodeId:g}=e,h=x.useRef(null),{getButtonProps:b,buttonRef:_}=no({disabled:a,focusableWhenDisabled:!0,native:f,composite:!0}),j=R6({closeOnClick:t,highlighted:o,id:l,nodeId:g,store:c,typingRef:d,itemRef:h,itemMetadata:m}),E=x.useCallback(k=>Ss(j,{onMouseEnter(){m.type==="submenu-trigger"&&m.setActive()}},k,b),[j,b,m]),y=rr(h,_);return x.useMemo(()=>({getItemProps:E,itemRef:y}),[E,y])}const UC=x.createContext({register:()=>{},unregister:()=>{},subscribeMapChange:()=>()=>{},nextIndexRef:{current:0}});function T6(){return x.useContext(UC)}function ru(e={}){const{guess:t,label:a,metadata:o,textRef:l,index:c}=e,{register:d,unregister:f,subscribeMapChange:m,nextIndexRef:g}=T6(),h=x.useRef(-1),[b,_]=x.useState(c==null&&t?()=>{if(h.current===-1){const k=g.current;g.current+=1,h.current=k}return h.current}:-1),j=c??b,E=x.useRef(null),y=x.useCallback(k=>{const N=E.current;N&&f(N),E.current=k,k&&d(k,{metadata:o??null,index:c??null,label:a,textRef:l})},[c,d,f,o,a,l]);return Pe(()=>{if(c==null)return m(k=>{const N=E.current?k.get(E.current)?.index:null;N!=null&&_(N)})},[c,m]),{ref:y,index:j}}let uk=(function(e){return e.checked="data-checked",e.unchecked="data-unchecked",e.disabled="data-disabled",e.highlighted="data-highlighted",e})({});const qC={checked(e){return e?{[uk.checked]:""}:{[uk.unchecked]:""}},...Ho},A6=x.createContext(void 0),M6=x.forwardRef(function(t,a){const{render:o,className:l,id:c,label:d,nativeButton:f=!1,disabled:m=!1,closeOnClick:g=!0,style:h,...b}=t,_=ru({guess:!0,label:d}),j=x_(!0),E=ra(c),{store:y}=Vo(),k=y.useState("disabled"),N=m||k,w=y.useState("isActive",_.index),S=y.useState("itemProps"),{getItemProps:R,itemRef:A}=$C({closeOnClick:g,disabled:N,highlighted:w,id:E,store:y,nativeButton:f,nodeId:j?.context.nodeId,itemMetadata:BC});return Et("div",t,{state:{disabled:N,highlighted:w},props:[S,b,R],ref:[A,a,_.ref]})}),z6=x.createContext(void 0);function HC(e){return x.useContext(z6)}const Sx="ArrowUp",Cx="ArrowDown",Nx="ArrowLeft",Ex="ArrowRight",Rx="Home",Tx="End",xp=new Set([Sx,Cx,Nx,Ex,Rx,Tx]),O6="Shift",D6=[O6,"Control","Alt","Meta"];function P6(e){return Gt(e)&&e.tagName==="INPUT"}function dk(e){return!!(P6(e)&&e.selectionStart!=null||Gt(e)&&e.tagName==="TEXTAREA")}function fk(e,t,a,o){if(!e||!t||!t.scrollTo)return;let l=e.scrollLeft,c=e.scrollTop;const d=e.clientWidth<e.scrollWidth,f=e.clientHeight<e.scrollHeight;if(d&&o!=="vertical"){const m=pk(e,t,"left"),g=zd(e),h=zd(t);a==="ltr"&&(m+t.offsetWidth+h.scrollMarginRight>e.scrollLeft+e.clientWidth-g.scrollPaddingRight?l=m+t.offsetWidth+h.scrollMarginRight-e.clientWidth+g.scrollPaddingRight:m-h.scrollMarginLeft<e.scrollLeft+g.scrollPaddingLeft&&(l=m-h.scrollMarginLeft-g.scrollPaddingLeft)),a==="rtl"&&(m-h.scrollMarginLeft<e.scrollLeft+g.scrollPaddingLeft?l=m-h.scrollMarginLeft-g.scrollPaddingLeft:m+t.offsetWidth+h.scrollMarginRight>e.scrollLeft+e.clientWidth-g.scrollPaddingRight&&(l=m+t.offsetWidth+h.scrollMarginRight-e.clientWidth+g.scrollPaddingRight))}if(f&&o!=="horizontal"){const m=pk(e,t,"top"),g=zd(e),h=zd(t);m-h.scrollMarginTop<e.scrollTop+g.scrollPaddingTop?c=m-h.scrollMarginTop-g.scrollPaddingTop:m+t.offsetHeight+h.scrollMarginBottom>e.scrollTop+e.clientHeight-g.scrollPaddingBottom&&(c=m+t.offsetHeight+h.scrollMarginBottom-e.clientHeight+g.scrollPaddingBottom)}e.scrollTo({left:l,top:c,behavior:"auto"})}function pk(e,t,a){const o=a==="left"?"offsetLeft":"offsetTop";let l=0;for(;t.offsetParent&&(l+=t[o],t.offsetParent!==e);)t=t.offsetParent;return l}function zd(e){const t=getComputedStyle(e);return{scrollMarginTop:parseFloat(t.scrollMarginTop)||0,scrollMarginRight:parseFloat(t.scrollMarginRight)||0,scrollMarginBottom:parseFloat(t.scrollMarginBottom)||0,scrollMarginLeft:parseFloat(t.scrollMarginLeft)||0,scrollPaddingTop:parseFloat(t.scrollPaddingTop)||0,scrollPaddingRight:parseFloat(t.scrollPaddingRight)||0,scrollPaddingBottom:parseFloat(t.scrollPaddingBottom)||0,scrollPaddingLeft:parseFloat(t.scrollPaddingLeft)||0}}const L6=x.forwardRef(function(t,a){const{render:o,className:l,style:c,finalFocus:d,...f}=t,{store:m}=Vo(),{side:g,align:h}=x_(),b=HC()!=null,_=m.useState("open"),j=m.useState("transitionStatus"),E=m.useState("popupProps"),y=m.useState("mounted"),k=m.useState("instantType"),N=m.useState("activeTriggerElement"),w=m.useState("parent"),S=m.useState("lastOpenChangeReason"),R=m.useState("rootId"),A=m.useState("floatingRootContext"),T=m.useState("floatingTreeRoot"),z=m.useState("closeDelay"),M=m.useState("hoverEnabled"),L=m.useState("disabled"),P=m.useState("openMethod"),B=w.type==="context-menu";Ca({open:_,ref:m.context.popupRef,onComplete(){_&&m.context.onOpenChangeComplete?.(!0)}}),x.useEffect(()=>{function U(V){m.setOpen(!1,rt(V.reason,V.domEvent))}return T.events.on("close",U),()=>{T.events.off("close",U)}},[T.events,m]),yC(A,{enabled:M&&!L&&!B&&w.type!=="menubar",closeDelay:z});const D=m.useStateSetter("popupElement"),$={transitionStatus:j,side:g,align:h,open:_,nested:w.type==="menu",instant:k},q=Et("div",t,{state:$,ref:[a,m.context.popupRef,D],stateAttributesMapping:d_,props:[E,{onKeyDown(U){b&&xp.has(U.key)&&U.stopPropagation()}},mp(j),f,{"data-rootownerid":R}]});let G=w.type===void 0||B;return(N||w.type==="menubar"&&S!==rp)&&(G=!0),n.jsx(Jb,{context:A,openInteractionType:P,modal:B,disabled:!y,returnFocus:d===void 0?G:d,initialFocus:w.type!=="menu",restoreFocus:!0,externalTree:w.type!=="menubar"?T:void 0,previousFocusableElement:N,nextFocusableElement:w.type===void 0?m.context.triggerFocusTargetRef:void 0,beforeContentFocusGuardRef:w.type===void 0?m.context.beforeContentFocusGuardRef:void 0,children:q})}),VC=x.createContext(void 0);function I6(){const e=x.useContext(VC);if(e===void 0)throw new Error(gn(32));return e}const B6=x.forwardRef(function(t,a){const{keepMounted:o=!1,...l}=t,{store:c}=Vo();return c.useState("mounted")||o?n.jsx(VC.Provider,{value:o,children:n.jsx(Qb,{ref:a,...l})}):null});function bp(e){const{children:t,elementsRef:a,labelsRef:o,onMapChange:l}=e,c=He(l),[,d]=x.useState(!1),f=Hn(U6).current,m=Hn($6).current,g=x.useRef(0),h=x.useRef(!0),b=x.useRef([]),_=x.useRef(null),j=He(()=>{h.current||(h.current=!0,d(A=>!A))}),E=He((A,T)=>{m.set(A,T),j()}),y=He(A=>{m.delete(A),j()}),k=He(A=>{const T=new Map;return a.current.length=0,o&&(o.current.length=0),A.forEach(z=>{T.set(z.element,{...z.registration.metadata??{},index:z.index}),a.current[z.index]=z.element,o&&(o.current[z.index]=z.registration.label!==void 0?z.registration.label:z.registration.textRef?.current?.textContent??z.element.textContent)}),g.current=a.current.length,T});function N(A){if(_.current?.disconnect(),_.current=null,typeof MutationObserver!="function"||A.length<2)return;const T=new MutationObserver(M=>{if(!V6(M))return;let L=null;for(const P of A)if(P.isConnected){if(L&&FC(L,P)>0){T.disconnect(),j();return}L=P}});_.current=T;const z=new Set;for(let M=1;M<A.length;M+=1){const L=H6(A[M-1],A[M]);L&&z.add(L)}z.forEach(M=>T.observe(M,{childList:!0}))}const w=He(()=>{const[A,T]=q6(m),z=k(A);N(T),b.current=A,h.current=!1,f.forEach(M=>M(z)),c(z)});Pe(()=>(h.current||k(b.current),()=>{a.current=[],o&&(o.current=[])}),[a,o,k]),Pe(()=>{h.current&&w()}),Pe(()=>()=>{_.current?.disconnect(),h.current=!0},[]);const S=He(A=>(f.add(A),()=>{f.delete(A)})),R=x.useMemo(()=>({register:E,unregister:y,subscribeMapChange:S,nextIndexRef:g}),[E,y,S,g]);return n.jsx(UC.Provider,{value:R,children:t})}function $6(){return new Map}function U6(){return new Set}function q6(e){const t=new Set,a=[],o=[];e.forEach((c,d)=>{if(!d.isConnected)return;const f=c.index,m={index:f??-1,element:d,registration:c};f===null?o.push(m):f>=0&&(t.add(f),a.push(m))});let l=0;return o.sort((c,d)=>FC(c.element,d.element)),o.forEach(c=>{for(;t.has(l);)l+=1;c.index=l,a.push(c),l+=1}),t.size>0&&a.sort((c,d)=>c.index-d.index),[a,o.map(c=>c.element)]}function H6(e,t){let a=e.parentElement;for(;a&&!a.contains(t);)a=a.parentElement;return a}function V6(e){for(const t of e)for(let a=0;a<t.removedNodes.length;a+=1)if(t.removedNodes[a].isConnected)return!0;return!1}function FC(e,t){return e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1}const __=x.forwardRef(function(t,a){const{cutout:o,...l}=t;let c;if(o){const d=o.getBoundingClientRect();c=`polygon(0% 0%,100% 0%,100% 100%,0% 100%,0% 0%,${d.left}px ${d.top}px,${d.left}px ${d.bottom}px,${d.right}px ${d.bottom}px,${d.right}px ${d.top}px,${d.left}px ${d.top}px)`}return n.jsx("div",{ref:a,role:"presentation","data-base-ui-inert":"",...l,style:{position:"fixed",inset:0,userSelect:"none",WebkitUserSelect:"none",clipPath:c}})});let mk={},gk={},hk="";function _p(e,t){return eu(e)?e:t}function xk(e,t,a){return/hidden|clip/.test(e.getComputedStyle(_p(t,a)).overflowY)}function F6(e){if(typeof document>"u")return!1;const t=vt(e);return Jt(t).innerWidth-t.documentElement.clientWidth>0}function G6(e){if(!(typeof CSS<"u"&&CSS.supports&&CSS.supports("scrollbar-gutter","stable"))||typeof document>"u")return!1;const a=vt(e),o=a.documentElement,l=a.body,c=_p(o,l),d=c.style.overflowY,f=o.style.scrollbarGutter;o.style.scrollbarGutter="stable",c.style.overflowY="scroll";const m=c.offsetWidth;c.style.overflowY="hidden";const g=c.offsetWidth;return c.style.overflowY=d,o.style.scrollbarGutter=f,m===g}function Y6(e){const t=vt(e),a=t.documentElement,o=t.body,l=_p(a,o),c={overflowY:l.style.overflowY,overflowX:l.style.overflowX};return Object.assign(l.style,{overflowY:"hidden",overflowX:"hidden"}),()=>{Object.assign(l.style,c)}}function K6(e){const t=vt(e),a=t.documentElement,o=t.body,l=Jt(a);let c=0,d=0,f=!1;const m=ga.create();if(ir&&(l.visualViewport?.scale??1)!==1)return()=>{};function g(){const j=l.getComputedStyle(a),E=l.getComputedStyle(o),N=(j.scrollbarGutter||"").includes("both-edges")?"stable both-edges":"stable";c=a.scrollTop,d=a.scrollLeft,mk={scrollbarGutter:a.style.scrollbarGutter,overflowY:a.style.overflowY,overflowX:a.style.overflowX},hk=a.style.scrollBehavior,gk={position:o.style.position,height:o.style.height,width:o.style.width,boxSizing:o.style.boxSizing,overflowY:o.style.overflowY,overflowX:o.style.overflowX,scrollBehavior:o.style.scrollBehavior};const w=a.scrollHeight>a.clientHeight,S=a.scrollWidth>a.clientWidth,R=j.overflowY==="scroll"||E.overflowY==="scroll",A=j.overflowX==="scroll"||E.overflowX==="scroll",T=Math.max(0,l.innerWidth-o.clientWidth),z=Math.max(0,l.innerHeight-o.clientHeight),M=parseFloat(E.marginTop)+parseFloat(E.marginBottom),L=parseFloat(E.marginLeft)+parseFloat(E.marginRight),P=_p(a,o);if(f=G6(e),f){a.style.scrollbarGutter=N,P.style.overflowY="hidden",P.style.overflowX="hidden";return}Object.assign(a.style,{scrollbarGutter:N,overflowY:"hidden",overflowX:"hidden"}),(w||R)&&(a.style.overflowY="scroll"),(S||A)&&(a.style.overflowX="scroll"),Object.assign(o.style,{position:"relative",height:M||z?`calc(100dvh - ${M+z}px)`:"100dvh",width:L||T?`calc(100vw - ${L+T}px)`:"100vw",boxSizing:"border-box",overflowY:"hidden",overflowX:"hidden",scrollBehavior:"unset"}),o.scrollTop=c,o.scrollLeft=d,a.setAttribute("data-base-ui-scroll-locked",""),a.style.scrollBehavior="unset"}function h(){Object.assign(a.style,mk),Object.assign(o.style,gk),f||(a.scrollTop=c,a.scrollLeft=d,a.removeAttribute("data-base-ui-scroll-locked"),a.style.scrollBehavior=hk)}function b(){h(),m.request(g)}g();const _=xt(l,"resize",b);return()=>{m.cancel(),h(),typeof l.removeEventListener=="function"&&_()}}class X6{lockCount=0;restore=null;timeoutLock=ta.create();timeoutUnlock=ta.create();acquire(t){return this.lockCount+=1,this.lockCount===1&&this.restore===null&&this.timeoutLock.start(0,()=>this.lock(t)),this.release}release=()=>{this.lockCount-=1,this.lockCount===0&&this.restore&&this.timeoutUnlock.start(0,this.unlock)};unlock=()=>{this.lockCount===0&&this.restore&&(this.restore?.(),this.restore=null)};lock(t){if(this.lockCount===0||this.restore!==null)return;const a=vt(t),o=a.documentElement,l=a.body,c=Jt(o);if(xk(c,o,l)){const f=new c.MutationObserver(()=>{xk(c,o,l)||(f.disconnect(),this.restore=null,this.lock(t))}),m={attributes:!0};f.observe(o,m),f.observe(l,m),this.restore=()=>f.disconnect();return}const d=Zf||!F6(t);this.restore=d?Y6(t):K6(t)}}const Q6=new X6;function GC(e=!0,t=null){Pe(()=>{if(e)return Q6.acquire(t)},[e,t])}const W6=20;function YC(e,t,a,o){const[l,c]=x.useState(!1);Pe(()=>{if(!e||!t||a==null){c(!1);return}const d=vt(a).documentElement.clientWidth,f=a.offsetWidth;c(d>0&&f>0&&f>=d-W6)},[e,t,a]),GC(e&&(!t||l),o)}const Z6=x.forwardRef(function(t,a){const{anchor:o,positionMethod:l="absolute",className:c,render:d,side:f,align:m,sideOffset:g=0,alignOffset:h=0,collisionBoundary:b="clipping-ancestors",collisionPadding:_=5,arrowPadding:j=5,sticky:E=!1,disableAnchorTracking:y=!1,collisionAvoidance:k=GS,style:N,...w}=t,{store:S}=Vo(),R=I6(),A=b_(!0),T=S.useState("parent"),z=S.useState("floatingRootContext"),M=S.useState("floatingTreeRoot"),L=S.useState("mounted"),P=S.useState("open"),B=S.useState("modal"),D=S.useState("openMethod"),$=S.useState("activeTriggerElement"),q=S.useState("transitionStatus"),G=S.useState("positionerElement"),U=S.useState("instantType"),V=S.useState("adaptiveOrigin"),X=S.useState("lastOpenChangeReason"),Q=S.useState("floatingNodeId"),W=S.useState("floatingParentNodeId"),I=z.useState("domReferenceElement"),K=x.useRef(null),ee=fC(G);let F=o,ne=g,Z=h,fe=m,Y=k;T.type==="context-menu"&&(F=o??T.context?.anchor,fe=fe??"start",!f&&fe!=="center"&&(Z=t.alignOffset??2,ne=t.sideOffset??-5));let oe=f,ve=fe;T.type==="menu"?(oe=oe??"inline-end",ve=ve??"start",Y=t.collisionAvoidance??YS):T.type==="menubar"&&(oe=oe??(T.context.orientation==="vertical"?"inline-end":"bottom"),ve=ve??"start");const le=T.type==="context-menu",xe=f_({anchor:F,floatingRootContext:z,positionMethod:A?"fixed":l,mounted:L,side:oe,sideOffset:ne,align:ve,alignOffset:Z,arrowPadding:le?0:j,collisionBoundary:b,collisionPadding:_,sticky:E,nodeId:Q,keepMounted:R,disableAnchorTracking:y,collisionAvoidance:Y,shift:le?{crossAxis:!("side"in Y&&Y.side==="flip"),rootBoundary:"layoutViewport"}:void 0,externalTree:M,adaptiveOrigin:V});x.useEffect(()=>{function Me(De){De.open&&(De.parentNodeId===Q&&S.set("hoverEnabled",!1),De.nodeId!==Q&&De.parentNodeId===S.select("floatingParentNodeId")&&S.setOpen(!1,rt(yc)))}return M.events.on("menuopenchange",Me),()=>{M.events.off("menuopenchange",Me)}},[S,M.events,Q]),x.useEffect(()=>{if(S.select("floatingParentNodeId")==null)return;function Me(De){if(De.open||De.nodeId!==S.select("floatingParentNodeId"))return;const Ue=De.reason??yc;S.setOpen(!1,rt(Ue))}return M.events.on("menuopenchange",Me),()=>{M.events.off("menuopenchange",Me)}},[M.events,S]);const ke=Rn();x.useEffect(()=>{P||ke.clear()},[P,ke]),x.useEffect(()=>{function Me(De){if(!(!P||De.nodeId!==S.select("floatingParentNodeId")))if(De.target&&$&&$!==De.target){const Ue=S.select("closeDelay");Ue>0?ke.isStarted()||ke.start(Ue,()=>{S.setOpen(!1,rt(yc))}):S.setOpen(!1,rt(yc))}else ke.clear()}return M.events.on("itemhover",Me),()=>{M.events.off("itemhover",Me)}},[M.events,P,$,S,ke]),x.useEffect(()=>{const Me={open:P,nodeId:Q,parentNodeId:W,reason:S.select("lastOpenChangeReason")};M.events.emit("menuopenchange",Me)},[M.events,P,S,Q,W]),Pe(()=>{const Me=I,De=K.current;if(Me&&(K.current=Me),De&&Me&&Me!==De){S.set("instantType",void 0);const Ue=new AbortController;return ee(()=>{S.set("instantType","trigger-change")},Ue.signal),()=>{Ue.abort()}}},[I,ee,S]);const Re={open:P,side:xe.side,align:xe.align,anchorHidden:xe.anchorHidden,nested:T.type==="menu",instant:U},Ae=T.type==="menubar"&&T.context.modal;YC(P&&(Ae||B&&X!==En),D==="touch",G,$);const Oe=p_(t,Re,{styles:xe.positionerStyles,transitionStatus:q,props:w,refs:[a,S.useStateSetter("positionerElement")],hidden:!L,inert:!P}),Te=L&&T.type!=="menu"&&(T.type!=="menubar"&&B&&X!==En||T.type==="menubar"&&T.context.modal);let Ne=null;return T.type==="menubar"?Ne=T.context.contentElement:T.type===void 0&&(Ne=$),n.jsxs(PC.Provider,{value:xe,children:[Te&&n.jsx(__,{ref:T.type==="context-menu"||T.type==="nested-context-menu"?T.context.internalBackdropRef:null,inert:gp(!P),cutout:Ne}),n.jsx(Cz,{id:Q,children:n.jsx(bp,{elementsRef:S.context.itemDomElements,labelsRef:S.context.itemLabels,children:Oe})})]})}),KC=x.createContext(void 0);function J6(){const e=x.useContext(KC);if(e===void 0)throw new Error(gn(34));return e}const eD=x.memo(x.forwardRef(function(t,a){const{render:o,className:l,value:c,defaultValue:d,onValueChange:f,disabled:m=!1,style:g,"aria-labelledby":h,...b}=t,[_,j]=x.useState(void 0),[E,y]=ni({controlled:c,default:d,name:"MenuRadioGroup"}),k=He((R,A)=>{f?.(R,A),!A.isCanceled&&y(R)}),w=Et("div",t,{state:{disabled:m},ref:a,props:{role:"group","aria-labelledby":h??_,"aria-disabled":m||void 0,...b}}),S=x.useMemo(()=>({value:E,setValue:k,disabled:m}),[E,k,m]);return n.jsx(A6.Provider,{value:j,children:n.jsx(KC.Provider,{value:S,children:w})})})),XC=x.createContext(void 0);function tD(){const e=x.useContext(XC);if(e===void 0)throw new Error(gn(35));return e}const nD=x.forwardRef(function(t,a){const{render:o,className:l,id:c,label:d,nativeButton:f=!1,disabled:m=!1,closeOnClick:g=!1,value:h,style:b,..._}=t,j=ru({guess:!0,label:d}),E=x_(!0),y=ra(c),{store:k}=Vo(),N=k.useState("isActive",j.index),w=k.useState("itemProps"),{value:S,setValue:R,disabled:A}=J6(),T=k.useState("disabled"),z=m||A||T,M=S===h,{getItemProps:L,itemRef:P}=$C({closeOnClick:g,disabled:z,highlighted:N,id:y,store:k,nativeButton:f,nodeId:E?.context.nodeId,itemMetadata:BC}),B=x.useMemo(()=>({disabled:z,highlighted:N,checked:M}),[z,N,M]);function D(q){const G=rt(Fl,q.nativeEvent,void 0,{preventUnmountOnClose:Nn});R(h,G)}const $=Et("div",t,{state:B,stateAttributesMapping:qC,props:[w,{role:"menuitemradio","aria-checked":M,onClick:D},_,L],ref:[P,a,j.ref]});return n.jsx(XC.Provider,{value:B,children:$})}),sD=x.forwardRef(function(t,a){const{render:o,className:l,style:c,keepMounted:d=!1,...f}=t,m=tD(),g=x.useRef(null),{transitionStatus:h,mounted:b,setMounted:_}=hi(m.checked);Ca({open:m.checked,ref:g,onComplete(){m.checked||_(!1)}});const j={checked:m.checked,disabled:m.disabled,highlighted:m.highlighted,transitionStatus:h};return Et("span",t,{state:j,stateAttributesMapping:qC,ref:[a,g],props:{"aria-hidden":!0,...f},enabled:d||b})}),aD=x.createContext(null);function QC(e){return x.useContext(aD)}function rD(e){const t=x.useRef(""),a=x.useCallback(l=>{l.defaultPrevented||(t.current=l.pointerType,e(l,l.pointerType))},[e]);return{onClick:x.useCallback(l=>{if(l.detail===0){e(l,"keyboard");return}"pointerType"in l?e(l,l.pointerType):e(l,t.current),t.current=""},[e]),onPointerDown:a}}function v_(e,t){const a=x.useRef(e),o=He(t);Pe(()=>{a.current!==e&&o(a.current),a.current=e},[e,o])}function oD(e,t){const a=He((c,d)=>{(typeof e=="function"?e():e)||t(d||(Zf?"touch":""))}),{onClick:o,onPointerDown:l}=rD(a);return x.useMemo(()=>({onClick:o,onPointerDown:l}),[o,l])}function WC(e){const[t,a]=x.useState(null),o=oD(e,a);return v_(e,l=>{l&&!e&&a(null)}),x.useMemo(()=>({openMethod:t,triggerProps:o}),[t,o])}const lD={...i_,disabled:e=>e.parent.type==="menubar"&&e.parent.context.disabled||e.disabled,modal:e=>(e.parent.type===void 0||e.parent.type==="context-menu")&&(e.modal??!0),openMethod:e=>e.openMethod,allowMouseEnter:e=>e.allowMouseEnter,highlightItemOnHover:e=>e.highlightItemOnHover,parent:e=>e.parent,rootId:e=>e.parent.type==="menu"?e.parent.store.select("rootId"):e.parent.type!==void 0?e.parent.context.rootId:e.rootId,activeIndex:e=>e.activeIndex,isActive:(e,t)=>e.activeIndex===t,hoverEnabled:e=>e.hoverEnabled,instantType:e=>e.instantType,lastOpenChangeReason:e=>e.openChangeReason,floatingTreeRoot:e=>e.parent.type==="menu"?e.parent.store.select("floatingTreeRoot"):e.floatingTreeRoot,floatingNodeId:e=>e.floatingNodeId,floatingParentNodeId:e=>e.floatingParentNodeId,itemProps:e=>e.itemProps,closeDelay:e=>e.closeDelay,adaptiveOrigin:e=>e.adaptiveOrigin,keyboardEventRelay:e=>{if(e.keyboardEventRelay)return e.keyboardEventRelay;if(e.parent.type==="menu")return e.parent.store.select("keyboardEventRelay")}};class iD extends nu{constructor(t){super({...uD(),...t},cD(),lD),this.unsubscribeParentListener=this.observe("parent",a=>{if(this.unsubscribeParentListener?.(),a.type==="menu"){let o=a.store.select("rootId"),l=a.store.select("floatingTreeRoot"),c=a.store.select("keyboardEventRelay");this.unsubscribeParentListener=a.store.subscribe(()=>{const d=a.store.select("rootId"),f=a.store.select("floatingTreeRoot"),m=a.store.select("keyboardEventRelay");o===d&&l===f&&c===m||(o=d,l=f,c=m,this.notifyAll())}),this.context.allowMouseUpTriggerRef=a.store.context.allowMouseUpTriggerRef;return}a.type!==void 0&&(this.context.allowMouseUpTriggerRef=a.context.allowMouseUpTriggerRef),this.unsubscribeParentListener=null})}setOpen(t,a){this.state.floatingRootContext.context.events.emit("setOpen",{open:t,eventDetails:a})}unsubscribeParentListener=null}function cD(){return{positionerRef:x.createRef(),popupRef:x.createRef(),typingRef:{current:!1},itemDomElements:{current:[]},itemLabels:{current:[]},allowMouseUpTriggerRef:{current:!1},triggerFocusTargetRef:x.createRef(),beforeContentFocusGuardRef:x.createRef(),onOpenChangeComplete:void 0,triggerElements:new su}}function uD(){return{...o_(),disabled:!1,modal:!0,openMethod:null,allowMouseEnter:!1,highlightItemOnHover:!0,parent:{type:void 0},rootId:void 0,activeIndex:null,hoverEnabled:!0,instantType:void 0,openChangeReason:null,floatingTreeRoot:new Wb,floatingNodeId:void 0,floatingParentNodeId:null,itemProps:sn,keyboardEventRelay:void 0,closeDelay:0,adaptiveOrigin:void 0}}const dD=x.createContext(void 0);function fD(){return x.useContext(dD)}const pD=Rb(function(t){const{children:a,open:o,onOpenChange:l,onOpenChangeComplete:c,defaultOpen:d=!1,disabled:f=!1,modal:m,loopFocus:g=!0,orientation:h="vertical",actionsRef:b,closeParentOnEsc:_=!1,handle:j,triggerId:E,defaultTriggerId:y=null,highlightItemOnHover:k=!0}=t,N=b_(!0),w=Vo(!0),S=QC(!0),R=fD(),A=x.useMemo(()=>R&&w?{type:"menu",store:w.store}:S?{type:"menubar",context:S}:N&&!w?{type:"context-menu",context:N}:{type:void 0},[N,w,S,R]),T=mD({open:d,openProp:o,activeTriggerId:y,triggerIdProp:E,parent:A});T.useControlledProp("openProp",o),T.useControlledProp("triggerIdProp",E),T.useContextCallback("onOpenChangeComplete",c);const z=Oo(),M=Oo(),L=T.useState("floatingTreeRoot"),P=eC(L),B=eo(),D=T.useState("open"),$=T.useState("activeTriggerElement"),q=T.useState("positionerElement"),G=T.useState("hoverEnabled"),U=T.useState("disabled"),V=T.useState("lastOpenChangeReason"),X=T.useState("parent"),Q=T.useState("activeIndex"),W=T.useState("payload"),I=T.useState("floatingParentNodeId"),K=x.useRef(null),ee=x.useRef(X.type!=="context-menu"),F=Rn(),ne=x.useRef(!0),Z=Rn(),fe=I!=null,{openMethod:Y,triggerProps:oe}=WC(D);T.useSyncedValues({disabled:f,highlightItemOnHover:k,modal:X.type===void 0?m:void 0,openMethod:Y,rootId:z}),s_(T);const{forceUnmount:ve}=a_(D,T,()=>{T.set("allowMouseEnter",!1)});Pe(()=>{N&&!w?T.update({parent:{type:"context-menu",context:N},floatingNodeId:P,floatingParentNodeId:B}):w&&T.update({floatingNodeId:P,floatingParentNodeId:B})},[N,w,P,B,T]),x.useEffect(()=>{if(D||(K.current=null),X.type==="context-menu"){if(!D){F.clear(),ee.current=!1;return}F.start(500,()=>{ee.current=!0})}},[F,D,X.type]),Pe(()=>{!D&&!G&&T.set("hoverEnabled",!0)},[D,G,T]);const le=He((Ce,Qe)=>{const Ge=Qe.reason;if(!Ce&&!T.select("open")||D===Ce&&Qe.trigger===$&&V===Ge)return;const lt=mC(Qe);if(!Ce&&Qe.trigger==null&&(Qe.trigger=$??void 0),l?.(Ce,Qe),Qe.isCanceled)return;T.state.floatingRootContext.dispatchOpenChange(Ce,Qe);const Tt=Qe.event;if(Ce===!1&&Tt?.type==="click"&&Tt.pointerType==="touch"&&!ne.current)return;Ce&&Ge===Vl?(ne.current=!1,Z.start(300,()=>{ne.current=!0})):(ne.current=!0,Z.clear());const _t=(Ge===gi||Ge===Fl)&&Tt.detail===0,Ct=!Ce&&(Ge===op||Ge==null),je={open:Ce,openChangeReason:Ge};K.current=Qe.event,n_(je,Ce,Qe.trigger,lt()),T.update(je),X.type==="menubar"&&(Ge===Vl||Ge===zo||Ge===En||Ge===bx||Ge===yc)?T.set("instantType","group"):_t||Ct?T.set("instantType",_t?"click":"dismiss"):T.set("instantType",void 0)}),xe=dC({popupStore:T,floatingId:M,nested:B!=null,onOpenChange:le}),ke=xe.context.events;Pe(()=>{const Ce=({open:Qe,eventDetails:Ge})=>le(Qe,Ge);return ke.on("setOpen",Ce),()=>{ke?.off("setOpen",Ce)}},[ke,le]);const Re=x.useCallback(()=>{T.setOpen(!1,rt(Bb))},[T]);x.useImperativeHandle(b,()=>({unmount:ve,close:Re}),[ve,Re]);let Ae;X.type==="context-menu"&&(Ae=X.context),x.useImperativeHandle(Ae?.positionerRef,()=>q,[q]),x.useImperativeHandle(Ae?.actionsRef,()=>({setOpen:le}),[le]);const Ie=ip(xe,{enabled:!U,bubbles:{escapeKey:_&&X.type==="menu"},outsidePress(){return X.type!=="context-menu"||K.current?.type==="contextmenu"?!0:ee.current},externalTree:fe?L:void 0}),Oe=pp(),Te=x.useCallback(Ce=>{T.select("activeIndex")!==Ce&&T.set("activeIndex",Ce)},[T]),Ne=kC(xe,{enabled:!U,listRef:T.context.itemDomElements,activeIndex:Q,nested:X.type!==void 0,loopFocus:g,orientation:h,parentOrientation:X.type==="menubar"?X.context.orientation:void 0,rtl:Oe==="rtl",disabledIndices:ja,onNavigate:Te,openOnArrowKeyDown:X.type!=="context-menu",externalTree:fe?L:void 0,focusItemOnHover:k}),Me=x.useCallback(Ce=>{T.context.typingRef.current=Ce},[T]),De=wC(xe,{enabled:!U,listRef:T.context.itemLabels,elementsRef:T.context.itemDomElements,activeIndex:Q,resetMs:vz,onMatch:Ce=>{D&&Ce!==Q&&T.set("activeIndex",Ce)},onTyping:Me}),Ue=x.useMemo(()=>{const Ce=Ss(De.reference,Ne.reference,Ie.reference,{onMouseMove(){T.set("allowMouseEnter",!0)}},oe);return Ce["aria-haspopup"]="menu",Ce["aria-expanded"]=D,Ce},[T,De.reference,Ne.reference,Ie.reference,oe,D]),Xe=x.useMemo(()=>{const Ce=Ss(Ne.trigger,Ie.trigger,oe);return Ce["aria-haspopup"]="menu",Ce["aria-expanded"]=!1,Ce},[Ne.trigger,Ie.trigger,oe]),me=x.useMemo(()=>Ss(dp,{id:M,role:"menu","aria-labelledby":$?.id,onMouseMove(){T.set("allowMouseEnter",!0),X.type==="menu"&&T.set("hoverEnabled",!1)},onClick(){T.select("hoverEnabled")&&T.set("hoverEnabled",!1)},onKeyDown(Ce){const Qe=T.select("keyboardEventRelay");Qe&&!Ce.isPropagationStopped()&&Qe(Ce)}},De.floating,Ne.floating,Ie.floating),[$,M,X.type,T,De.floating,Ne.floating,Ie.floating]),de=Ne.item??sn;r_(T,{floatingRootContext:xe,activeTriggerProps:Ue,inactiveTriggerProps:Xe,popupProps:me,itemProps:de});const Le=x.useMemo(()=>({store:T,parent:A}),[T,A]),ye=n.jsxs(LC.Provider,{value:Le,children:[j&&n.jsx(t_,{handle:j,store:T}),typeof a=="function"?a({payload:W}):a]});return X.type===void 0||X.type==="context-menu"?n.jsx(Nz,{externalTree:L,children:ye}):ye});function mD(e){return Hn(()=>new iD(e)).current}const Od=5;function ZC(e,t){const a=gD(t);return e.clientX>=a.left-Od&&e.clientX<=a.right+Od&&e.clientY>=a.top-Od&&e.clientY<=a.bottom+Od}function gD(e){const t=e.getBoundingClientRect(),a=Jt(e);if(Mb)return t;const o=a.getComputedStyle(e,"::before"),l=a.getComputedStyle(e,"::after");if(!(o.content!=="none"||l.content!=="none"))return t;const d=parseFloat(o.width)||0,f=parseFloat(o.height)||0,m=parseFloat(l.width)||0,g=parseFloat(l.height)||0,h=Math.max(t.width,d,m),b=Math.max(t.height,f,g),_=h-t.width,j=b-t.height;return{left:t.left-_/2,right:t.right+_/2,top:t.top-j/2,bottom:t.bottom+j/2}}function JC(e={}){const{highlightItemOnHover:t,highlightedIndex:a,onHighlightedIndexChange:o}=hp(),{ref:l,index:c}=ru(e),d=a===c,f=x.useRef(null),m=rr(l,f);return{compositeProps:{tabIndex:d?0:-1,onFocus(){o(c)},onMouseMove(){const h=f.current;if(!t||!h)return;const b=h.hasAttribute("disabled")||h.ariaDisabled==="true";!d&&!b&&h.focus()}},compositeRef:m,index:c}}function hD(e){const{render:t,className:a,style:o,state:l=sn,props:c=ja,refs:d=ja,metadata:f,stateAttributesMapping:m,tag:g="div",...h}=e,{compositeProps:b,compositeRef:_}=JC({metadata:f});return Et(g,e,{state:l,ref:[_,...d],props:[b,...c,h],stateAttributesMapping:m})}function eN(e){if(Gt(e)&&e.hasAttribute("data-rootownerid"))return e.getAttribute("data-rootownerid");if(!Ja(e))return eN(ar(e))}function xD(e,t){const a=x.useRef(null);function o(c){Gs.flushSync(()=>{e.setOpen(!1,rt(zo,c.nativeEvent,c.currentTarget))}),nz(a.current)?.focus()}function l(c){const d=e.select("positionerElement");if(d&&Gl(c,d))e.context.beforeContentFocusGuardRef.current?.focus();else{Gs.flushSync(()=>{e.setOpen(!1,rt(zo,c.nativeEvent,c.currentTarget))});let f=tz(e.context.triggerFocusTargetRef.current||t.current);for(;f!==null&&Ze(d,f);){const m=f;if(f=Gb(f),f===m)break}f?.focus()}}return{preFocusGuardRef:a,handlePreFocusGuardFocus:o,handleFocusTargetFocus:l}}function bD(e){const{enabled:t=!0,mouseDownAction:a,open:o}=e,l=x.useRef(!1);return x.useMemo(()=>t?{onMouseDown:c=>{(a==="open"&&!o||a==="close"&&o)&&(l.current=!0,vt(c.currentTarget).addEventListener("click",()=>{l.current=!1},{once:!0}))},onClick:c=>{l.current&&(l.current=!1,c.preventBaseUIHandler())}}:sn,[t,a,o])}const _D=gS(function(t,a){const{render:o,className:l,style:c,disabled:d=!1,nativeButton:f=!0,id:m,openOnHover:g,delay:h=100,closeDelay:b=0,handle:_,payload:j,...E}=t,y=Vo(!0),N=bC(_)??y?.store;if(!N)throw new Error(gn(85));const w=ra(m),S=N.useState("isTriggerActive",w),R=N.useState("floatingRootContext"),A=N.useState("isOpenedByTrigger",w),T=N.useState("triggerPopupId",w),z=x.useRef(null),M=yD(),L=hp(!0),P=to(),B=x.useMemo(()=>P??new Wb,[P]),D=eC(B),$=eo(),{registerTrigger:q,isMountedByThisTrigger:G}=gC(w,z,N,{payload:j,closeDelay:b,parent:M,floatingTreeRoot:B,floatingNodeId:D,floatingParentNodeId:$,keyboardEventRelay:L?.relayKeyboardEvent}),U=M.type==="menubar",V=N.useState("disabled"),X=d||V||U&&M.context.disabled,{getButtonProps:Q,buttonRef:W}=no({disabled:X,native:f});x.useEffect(()=>{!A&&M.type===void 0&&(N.context.allowMouseUpTriggerRef.current=!1)},[N,A,M.type]);const I=x.useRef(null),K=Rn(),ee=He(Me=>{if(!I.current)return;K.clear(),N.context.allowMouseUpTriggerRef.current=!1;const De=Me.target;Ze(I.current,De)||Ze(N.select("positionerElement"),De)||De===I.current||De!=null&&eN(De)===N.select("rootId")||ZC(Me,I.current)||B.events.emit("close",{domEvent:Me,reason:yS})});x.useEffect(()=>{A&&N.select("lastOpenChangeReason")===En&&vt(I.current).addEventListener("mouseup",ee,{once:!0})},[A,ee,N]);const F=U&&M.context.hasSubmenuOpen,Z=jC(R,{enabled:(g??F)&&!X&&(!U||F&&!G),handleClose:SC({blockPointerEvents:!U}),mouseOnly:!0,move:!1,restMs:M.type===void 0?h:void 0,delay:{close:b},triggerElementRef:z,externalTree:B,isActiveTrigger:S,isClosing:()=>N.select("transitionStatus")==="ending"}),fe=vD(A,N.select("lastOpenChangeReason")),Y=tC(R,{enabled:!X,event:A&&U?"click":"mousedown",toggle:!0,ignoreMouse:!1,stickIfOpen:M.type===void 0?fe:!1}),oe=_C(R,{enabled:!X&&F}),ve=bD({open:A,enabled:U,mouseDownAction:"open"}),le=x.useMemo(()=>Ss(oe.reference,Y.reference),[oe.reference,Y.reference]),xe=N.useState("triggerProps",G),{preFocusGuardRef:ke,handlePreFocusGuardFocus:Re,handleFocusTargetFocus:Ae}=xD(N,z),Ie={disabled:X,open:A},Oe=[I,a,W,q,z],Te=[le,Z??sn,xe,{"aria-haspopup":"menu","aria-controls":T,id:w,onMouseDown:Me=>{if(N.select("open"))return;K.start(200,()=>{N.context.allowMouseUpTriggerRef.current=!0}),vt(Me.currentTarget).addEventListener("mouseup",ee,{once:!0})}},U?{role:"menuitem"}:{},ve,E,Q],Ne=Et("button",t,{enabled:!U,stateAttributesMapping:wx,state:Ie,ref:Oe,props:Te});return U?n.jsx(hD,{tag:"button",render:o,className:l,style:c,state:Ie,refs:Oe,props:Te,stateAttributesMapping:wx}):A?n.jsxs(x.Fragment,{children:[n.jsx(ei,{ref:ke,onFocus:Re},`${w}-pre-focus-guard`),n.jsx(x.Fragment,{children:Ne},w),n.jsx(ei,{ref:N.context.triggerFocusTargetRef,onFocus:Ae},`${w}-post-focus-guard`)]}):n.jsx(x.Fragment,{children:Ne},w)});function vD(e,t){const a=Rn(),[o,l]=x.useState(!1);return Pe(()=>{e&&t===En?(l(!0),a.start(yz,()=>{l(!1)})):e||(a.clear(),l(!1))},[e,t,a]),o}function yD(){const e=QC();return x.useMemo(()=>e?{type:"menubar",context:e}:{type:void 0},[e])}function tN(e){return e==null||e.hasAttribute("disabled")||e.getAttribute("aria-disabled")==="true"}function y_({...e}){return n.jsx(pD,{"data-slot":"dropdown-menu",...e})}function j_({...e}){return n.jsx(_D,{"data-slot":"dropdown-menu-trigger",...e})}function k_({align:e="start",alignOffset:t=0,side:a="bottom",sideOffset:o=4,className:l,...c}){return n.jsx(B6,{children:n.jsx(Z6,{className:"isolate z-50 outline-none",align:e,alignOffset:t,side:a,sideOffset:o,children:n.jsx(L6,{"data-slot":"dropdown-menu-content",className:St("z-50 max-h-(--available-height) w-(--anchor-width) min-w-32 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:overflow-hidden data-closed:fade-out-0 data-closed:zoom-out-95",l),...c})})})}function sf({className:e,inset:t,variant:a="default",...o}){return n.jsx(M6,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":a,className:St("group/dropdown-menu-item relative flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive",e),...o})}function jD({...e}){return n.jsx(eD,{"data-slot":"dropdown-menu-radio-group",...e})}function kD({className:e,children:t,inset:a,...o}){return n.jsxs(nD,{"data-slot":"dropdown-menu-radio-item","data-inset":a,className:St("relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...o,children:[n.jsx("span",{className:"pointer-events-none absolute right-2 flex items-center justify-center","data-slot":"dropdown-menu-radio-item-indicator",children:n.jsx(sD,{children:n.jsx(Yr,{})})}),t]})}const wD={common:{loading:"Cargando…",saving:"Guardando…",cancel:"Cancelar",save:"Guardar",delete:"Borrar",edit:"Editar",create:"Crear",add:"Agregar",remove:"Quitar",reload:"Recargar",shutdown:"Apagar",enabled:"Habilitado",disabled:"Deshabilitado",enable:"Habilitar",disable:"Deshabilitar",open:"Abrir",close:"Cerrar",confirm:"Confirmar",optional:"(opcional)",none:"—",none_yet:"Todavía no hay nada.",error_generic:"Algo salió mal.",search:"Buscar",new:"Nuevo",restore:"Restaurar",show:"Mostrar",hide:"Ocultar",copy:"Copiar",run:"Ejecutar",refresh:"Refrescar",view_all:"Ver todo",saved:"Guardado.",deleted:"Eliminado.",pager_prev:"Anterior",pager_next:"Siguiente",pager_page:"Página {page} de {total}",pager_range:"{from}–{to} de {total}",pager_per_page:"Por página"},daemon:{connecting:"Conectando con el daemon…",unreachable:"No pude llegar al daemon en localhost:7430.",unreachable_hint:"Arrancá APX con `apx daemon start` y refrescá.",version:"Versión",uptime:"Uptime",status:"Status",running:"running",down:"down",reload_hint:"POST /admin/reload — relee ~/.apx/config.json sin reiniciar.",shutdown_confirm:"¿Apagar el daemon? Las próximas requests fallarán hasta levantarlo de nuevo.",shutdown_done:"Daemon detenido."},pairing:{title:"Vincular este equipo",subtitle:"Estás entrando desde fuera de esta máquina. Por seguridad, vinculá este navegador con un código de pairing.",steps_title:"Cómo obtener el código",step_1:"En la PC donde corre APX, abrí una terminal.",step_2:"Ejecutá `apx pair` (o escaneá el QR con APX Deck).",step_3:"Copiá el código que aparece debajo del QR y pegalo acá.",code_label:"Código de pairing",code_ph:"p. ej. 7f3a1c9e-…",label_label:"Nombre de este equipo",label_ph:"p. ej. Notebook del living",submit:"Vincular",linking:"Vinculando…",success:"Equipo vinculado ✓",err_required:"Pegá el código de pairing.",err_expired:"El código expiró. Volvé a correr `apx pair` y probá de nuevo.",err_unknown:"Código desconocido o ya usado. Generá uno nuevo con `apx pair`.",err_generic:"No se pudo vincular. Revisá el código e intentá otra vez.",revoke_hint:"Podés revocar este equipo cuando quieras desde Settings o con `apx pair revoke`."},nav:{apx_admin:"APX",settings:"Settings",project:"Proyecto",add_project:"Agregar proyecto",all_projects:"Todos los proyectos",more_projects:"{count} más",collapse_projects:"Ocultar proyectos",expand_projects:"Mostrar proyectos",modules:{voice:"Voces",desktop:"Escritorio",deck:"Deck",code:"Code",web:"Web"}},topbar:{breadcrumb_root:"APX",breadcrumb_settings:"APX › Settings",breadcrumb_project:"APX › Proyecto",breadcrumb_base:"Base",breadcrumb_projects:"Proyectos",light:"Cambiar a claro",dark:"Cambiar a oscuro",lang_toggle:"Idioma"},admin:{title:"APX",subtitle:"Panel general. Configuración global, canales y proyectos.",engines_title:"Engines",engines_subtitle:"Adaptadores LLM disponibles. Las API keys viven en ~/.apx/config.json.",telegram_title:"Telegram",telegram_subtitle:"Canales configurados. Cada uno puede estar pineado a un proyecto.",telegram_polling_on:"Polling activo",telegram_polling_off:"Deshabilitado",telegram_add_channel:"Canal",telegram_send_test:"Probar",telegram_send_test_title:"Enviar a",telegram_default_message:"Mensaje de prueba desde el panel de APX ✅",projects_title:"Proyectos registrados",projects_subtitle:"Click en un proyecto para abrir su panel.",unregister:"Desregistrar",unregister_confirm:"¿Quitar {label} de APX? La carpeta no se borra; sólo se desregistra.",reload_success:"Config recargada.",telegram_polling_started:"Polling iniciado.",telegram_polling_stopped:"Polling detenido.",telegram_channel_removed:"Canal eliminado.",agents_badge:"agents",engine_badge:"sí",engine_badge_no:"no",base_label:"Base"},add_project:{title:"Agregar proyecto",subtitle:"APX indexará .apc/, agents y AGENTS.md en esa carpeta.",path_label:"Ruta absoluta",path_hint:"Equivalente a apx project add /ruta/al/proyecto",path_placeholder:"/Volumes/SSDT7Shield/proyectos_varios/mi-proyecto",register:"Registrar",path_required:"Ruta requerida.",registered:"Proyecto #{id} registrado.",search_btn:"Buscar",picker_prompt:"Elegí la carpeta del proyecto",browser_unavailable:"Explorador no disponible hasta reiniciar daemon. Pegá ruta manual.",no_folders:"Sin carpetas."},settings:{title:"Settings",subtitle:"Preferencias del panel + diagnóstico del daemon local.",appearance:"Apariencia",light_mode:"Claro",dark_mode:"Oscuro",system_mode:"Sistema",language:"Idioma",daemon:"Daemon",daemon_sub:"Estado del proceso local que sirve esta web y orquesta los agentes.",engines:"Engines disponibles",engines_sub:"Adaptadores LLM compilados con el daemon.",token:"Token para esta sesión",token_sub:"Si esta web no logró auto-cargar el token, pegalo acá.",token_active:"(ya hay token activo)",token_paste:"Pegá el bearer del daemon",token_saved:"Token guardado.",devices:"Dispositivos pareados",devices_sub:"GET /pair/list. Revocar invalida ese bearer en el daemon.",devices_empty:"No hay clientes pareados todavía.",devices_revoke_confirm:"Revocar cliente {id}?",devices_revoke_success:"Cliente revocado.",devices_pair_btn:"Vincular dispositivo",devices_pair_title:"Vincular dispositivo",devices_pair_desc:"Escaneá el QR con la cámara del celu para entrar directo, o pegá el código en la otra PC.",devices_pair_scan:"Escaneá con la cámara del teléfono — te abre la web ya vinculada.",devices_pair_code:"O pegá este código en la pantalla de pairing:",devices_pair_url:"URL de acceso",devices_pair_link:"O copiá este link y abrilo en el otro dispositivo (entra solo):",devices_pair_copy:"Copiar",devices_pair_copied:"Link copiado al portapapeles.",devices_pair_copied_code:"Código copiado.",devices_pair_expires:"Expira en {s}s",devices_pair_expired:"El código expiró.",devices_pair_regen:"Generar otro",devices_pair_waiting:"Esperando que el dispositivo confirme…",devices_pair_done:"Dispositivo vinculado ✓",devices_pair_localhost_only:"Solo se pueden generar códigos desde la PC del daemon (localhost).",devices_last_seen:"visto:",devices_never:"nunca",devices_revoke:"Revocar",account_section:"Cuenta",agents_section:"Agentes & modelos",channels_section:"Canales & dispositivos",modules_section:"Módulos",advanced_section:"Avanzado",tabs:{identity:"Identidad",super_agent:"Super-agente",profile:"Perfil del agente",engines:"Engines & modelos",telegram:"Telegram",devices:"Dispositivos",advanced:"Avanzado"},profile:{title:"Perfil del agente",subtitle:"Un oficio instalable para el super-agente: qué hace con su día y cuándo te habla. Distinto del nombre del agente (eso está en Identidad).",vanilla_hint:"No hay ningún perfil activo. APX se comporta exactamente como siempre — el prompt del super-agente es idéntico al de una instalación limpia.",none_available:"No hay perfiles disponibles todavía.",active:"activo",activate:"Activar",replace_active:"Reemplazar el activo",deactivate:"Desactivar",deactivate_title:"¿Desactivar el perfil?",deactivate_confirm:"APX vuelve a vanilla. Las rutinas del perfil se deshabilitan pero no se borran, y tu configuración, tareas y memoria quedan intactas: volver a activarlo restaura todo.",activated:"Perfil activo",deactivated:"Perfil desactivado — APX está en vanilla",token_cost:"Costo de prompt",over_budget:"excede su presupuesto declarado",settings_title:"Configuración del perfil",settings_subtitle:"Los valores en blanco toman el default del paquete. Cambiar un horario reprograma la rutina de verdad.",saved:"Configuración guardada",saved_with_routines:"Configuración guardada y rutinas reprogramadas",doctor_title:"Diagnóstico",doctor_clean:"Todo en orden.",preview_title:"Bloque de prompt",preview_subtitle:"Exactamente lo que recibe el modelo, con tus valores ya sustituidos.",preview_empty:"(vacío)"},identity:{title:"Identidad",subtitle:"Datos del usuario. Configuración del agente va en Super-agente.",agent_name:"Nombre del agente",owner_name:"Tu nombre",personality:"Personalidad",owner_context:"Contexto del dueño",owner_context_hint:"Quién sos, en qué trabajás, qué le interesa al agente saber de vos.",language:"Idioma preferido",timezone:"Timezone (IANA)",timezone_hint:"Detectado automáticamente — buscá para cambiar.",saved:"Identidad guardada."},super_agent:{title:"Super-agente",subtitle:"Personalidad, modelo, prompt y modos del super-agente.",personality:"Personalidad",model:"Modelo activo",model_hint:"Ej: anthropic:claude-sonnet-4.5, ollama:gemma2:9b",permission_mode:"Permission mode",system:"Prompt extra (system)",system_hint:"Texto que se prepende al system prompt base.",system_ph:"(Vacío = se usa el prompt base de core/agent/prompts/super-agent-base.md)",fallback_title:"Fallback chain",fallback_hint:"Si el modelo activo falla, prueba estos en orden.",fallback_add:"Agregar modelo a la cadena",saved:"Super-agente guardado.",enabled_label:"Super-agente habilitado",model_active:"Modelo activo (router)",model_configure:"Configurar en Modelos",behavior_subtitle:"Comportamiento del super-agente. El modelo y la cadena de fallback se configuran en el Router de modelos."},engines_keys:{title:"API keys de modelos",subtitle:"Cada engine guarda su key en ~/.apx/config.json. Los valores ya seteados muestran sufijo seguro.",ollama_url:"Ollama URL",ollama_hint:"Por defecto: http://127.0.0.1:11434",key_label:"API key",key_placeholder:"(no seteada)",clear:"Borrar key",saved:"Key guardada.",cleared:"Key borrada."},telegram_global:{title:"Telegram (default)",subtitle:"Canal default — los proyectos pueden overridear con su propio canal.",bot_token:"Bot token",chat_id:"Chat ID por defecto",poll_interval:"Poll interval (ms)",respond_with_engine:"Respond with engine",enabled:"Polling habilitado",saved:"Telegram guardado."},advanced:{title:"Avanzado",subtitle:"Editor raw del ~/.apx/config.json. Los secretos se ven *** set *** pero podés escribir uno nuevo.",write:"Aplicar cambios",written:"Config aplicada y daemon recargado.",reload_success:"Config recargada."}},project:{not_found:"Roby no encontró el proyecto {pid}: quizás se desregistró o el ID es incorrecto.",rebuild:"Rebuild context",rebuild_done:"Rebuild OK.",unregister_confirm:"¿Desregistrar {label}? La carpeta no se borra.",unregistered:"Desregistrado.",base_subtitle:"Espacio general · super-agente",danger:{title:"Zona peligrosa",subtitle:"Acciones que afectan el registro del proyecto en APX. No tocan archivos del repo.",rebuild_desc:"Re-escanea .apc/, MCPs y agents y regenera el contexto del super-agente para este proyecto.",unregister_desc:"Quita el proyecto del registry de APX. La carpeta del disco se mantiene intacta.",rebuild_confirm_title:"Rebuild context",rebuild_confirm_desc:"Regenerar contexto de {label}.",rebuild_long:"Vuelve a leer la config APC, lista MCPs y agents disponibles, y reconstruye el system prompt del super-agente. Es seguro de correr — no borra nada. Usalo después de tocar .apc/ a mano o si los cambios no se reflejan.",unregister_confirm_title:"Desregistrar proyecto",unregister_long:"El proyecto deja de aparecer en `apx`. Los archivos del disco (.apc/, código, todo) se mantienen. Podés volver a registrarlo con `apx project register <path>`."},nav:{overview:"Overview",chat:"Chat",config:"Config",telegram:"Telegram",agents:"Agents",routines:"Rutinas",tasks:"Tasks",mcps:"MCPs",artifacts:"Artifacts",vars:"Variables",logs:"Logs",memories:"Memorias",structure:"Estructura",docs:"Docs",files:"Archivos"},sections:{workspace:"Workspace",content:"Contenido",automation:"Automatización",knowledge:"Conversaciones",config:"Config"},overview:{tasks_open:"Tasks abiertas",routines:"Rutinas",routines_active:"Rutinas activas",agents:"Agents",mcps:"MCPs",artifacts:"Artifacts",chat:"Chat (super-agent)",chat_value:"abrir",roster:"Equipo",no_agents:"Todavía no hay agentes.",orchestrators:"Orquestadores",specialists:"Especialistas",recent_tasks:"Tasks recientes",no_activity:"No hay tasks abiertas.",brain_title:"Cerebro del equipo",brain_desc:"El mapa completo de agentes — los orquestadores en el núcleo y sus especialistas en racimo alrededor. Clic en un nodo para abrirlo.",brain_core:"Equipo"},artifacts:{title:"Artifacts",subtitle:"Scripts y archivos reutilizables guardados en el proyecto. Los crean los agentes; podés verlos, ejecutarlos, renombrarlos o eliminarlos."},chat:{title:"Chat con agente",subtitle:"Chat directo con el agente del proyecto.",live_title:"Chat con {agent}",superagent_title:"Chat con {persona}",superagent_subtitle:"Chat con {persona} — el super-agente APX. Puede usar tools (proyectos, tasks, mcps, agentes).",loaded_subtitle:"Conversación cargada con {slug}. Lo que mandes se agrega a este chat.",thread_subtitle:"Historial con {persona} en {channel}. Si respondés acá, la conversación sigue desde la web.",empty:"Mandá un mensaje para arrancar la conversación.",placeholder:"Escribí algo y enter para enviar (shift+enter = nueva línea)",send:"Enviar",stop:"Stop",new_session:"Nueva sesión",delete:"Borrar",delete_confirm_title:"Borrar chat",delete_confirm_desc:"Esta acción no se puede deshacer. Se elimina para siempre el historial de este chat.",deleted:"Chat borrado.",meta_created:"Creado {date} · {channel}",meta_new:"Chat nuevo · {channel}",copy:"copiar",copied:"Copiado.",stopped_marker:" [detenido]",create_agent:"Crear agente",create_agent_title:"Crear agente",create_agent_desc:"Necesario para iniciar chat en proyecto.",role_label:"rol",model_label:"modelo",model_hint:"ej. openai:gpt-5, groq:llama-3.3-70b-versatile",master_label:"Agente master",list:{title:"Chats",new:"Nuevo",search:"Buscar chats…",all_agents:"Todos los agentes",empty:"No hay conversaciones todavía. Arrancá una desde la derecha.",count:"{n} en total",pick_agent:"Elegí un agente"}},tasks:{title:"Tasks (TODOs)",subtitle:"Append-only JSONL en ~/.apx/projects/<id>/tasks/.",add:"agregar",add_label:"Nueva task",add_placeholder:"ej. revisar bug del scroll",empty:"No hay tasks {state}.",empty_open:"No hay tasks abiertas.",created:"Task creada.",create_error:"no pude crear la task",done:"✓ done",drop:"✗ drop",reopen:"↻ reopen",due:"vence",via:"via",aria_done:"marcar done",aria_drop:"descartar task",aria_reopen:"reabrir task"},global_tasks:{title:"Tasks (todos los proyectos)",subtitle:"Tareas agregadas de todos los proyectos registrados.",empty:"Sin tasks.",due:"vence",go_project:"Ir al proyecto"},routines:{title:"Heartbeats / Routines",subtitle:"Cron, every:Nm, once:ISO. Cada rutina dispara un agente o un shell.",empty:"Sin rutinas. Creá una arriba.",new:"nueva",new_btn:"Nueva",delete_confirm:"Borrar rutina {name}?",delete_confirm_body:"Esta acción no se puede deshacer.",saved:"Rutina guardada.",paused:"pausada",next_run:"próxima:",last_run:"última:",enabled_hint:"Activa · corre según el intervalo",disabled_hint:"Pausada · solo con el botón Run",enabled_label:"Habilitada",new_title:"Nueva rutina",edit_title:"Editar {name}",dialog_desc:"Se guarda en .apc/routines.json. La rutina corre mientras el daemon está activo.",name_field:"Nombre (name)",name_no_edit:"No se puede cambiar al editar.",kind_field:"Acción (kind)",schedule_field:"Intervalo (schedule)",schedule_hint:"Elegí un preset o escribilo a mano. Manual = solo corre con el botón Run.",vars_title:"Variables disponibles",what_happens:"Qué va a pasar",list_title:"Rutinas",detail_empty:"Elegí una rutina de la lista.",edit_btn:"Editar",edit_hint:"Abrir el editor: tipo, intervalo, prompt, pre/post y variables.",block_pre:"Pre-commands",block_post:"Post-commands",block_prompt:"Prompt",block_text:"Texto",block_command:"Comando",block_empty:"(vacío)",runs_title:"Ejecuciones",runs_empty:"Sin ejecuciones todavía.",runs_close:"Cerrar",runs_no_detail:"Sin más detalle.",runs_output:"Salida",status_ok:"ok",status_error:"error",status_skipped:"salteada",agent_field:"Agente (spec.agent)",agent_hint:"Quién ejecuta la rutina.",agent_loading:"cargando…",agent_pick:"— elegí un agente —",prompt_exec:"Prompt (spec.prompt)",prompt_exec_ph:"qué pendiente hay para hoy?",prompt_super:"Prompt (spec.prompt)",prompt_super_ph:"resumí el estado del proyecto",pre_field:"Pre-commands (pre_commands)",pre_hint:"Shell ANTES del prompt. Uno por línea.",post_field:"Post-commands (post_commands)",post_hint:"Shell DESPUÉS del prompt. Uno por línea.",tg_channel:"Canal (spec.channel)",tg_chat_id:"Chat ID (spec.chat_id)",tg_text:"Mensaje de Telegram (spec.text)",tg_text_hint:"Mensaje fijo a enviar. No usa modelo.",shell_field:"Comando (spec.command)",shell_hint:"Corre tal cual en el shell. Sin prompt ni pre/post.",hb_channel:"Canal (spec.channel)",hb_message:"Mensaje (spec.message)",name_required:"name requerido",save_error:"save falló",run_error:"run falló",toggle_error:"toggle falló",delete_error:"delete falló",run_success:"{name} disparada.",run_confirm:"¿Ejecutar la rutina {name} ahora?",run_confirm_body:"Corre la acción una vez, sin esperar al horario.",running:"Ejecutando…",delete_success:"borrada."},agents:{title:"Agents",subtitle:"Definidos en .apc/agents/<slug>.md.",subtitle_full:"Definidos en .apc/agents/<slug>.md. La memoria runtime vive en ~/.apx/projects/<id>/agents/<slug>/.",empty:"Sin agents. Agregá uno con <code>apx agent add</code> o el botón.",empty_text:"Sin agents. Agregá uno con `apx agent add` o el botón de arriba.",new:"Agente",created:"Agent {slug} creado.",slug_invalid:"slug debe matchear /^[a-z][a-z0-9_-]*$/",hierarchy:"Jerarquía",list_view:"Lista",import:"Importar",chat:"Chat",view:"Ver",orchestrator:"Orquestador",new_title:"Nuevo agent",new_desc:"POST /projects/:pid/agents — escribe .apc/agents/<slug>.md.",slug_label:"slug",slug_ph:"cody",role_label:"role (opcional)",role_ph:"code refactor",model_label:"model (opcional)",model_hint:"ej. ollama:gemma2:9b, openai:gpt-4o-mini",lang_label:"language (opcional)",desc_label:"description (opcional)",desc_ph:"Qué hace este agente…",skills_label:"skills (coma)",skills_ph:"skill-a, skill-b",tools_label:"tools (coma)",tools_ph:"tool-a, tool-b",parent_label:"reporta a (parent, opcional)",parent_hint:"Subagente de un orquestador.",none_parent:"— ninguno —",master_label:"Orquestador (master)",create_success:"Agent {slug} creado.",create_error:"create falló",import_title:"Importar del vault",import_desc:"Plantillas en ~/.apx/agents. Se registran en este proyecto (.apc/agents/<slug>.md).",import_empty:"Sin plantillas en el vault.",import_success:"Importado: {slug}",import_already:"ya está",import_btn:"Importar"},agent_detail:{not_found:"Agente no encontrado.",chat_btn:"Chat con {slug}",reports_to:"↳ reporta a",no_threads:"Sin threads.",no_activity:"Sin actividad registrada.",threads_recent:"Threads recientes",subagents:"Subagentes",subagents_desc:"Agentes que reportan a este orquestador.",config_title:"Configuración del agente",type_label:"Tipología (type)",area_label:"Área",area_hint:"ej. operaciones, marketing",area_ph:"operaciones",role_label:"Role",parent_label:"Reporta a (parent)",none_parent:"— ninguno —",model_label:"Modelo base",model_hint:"Vacío = usa el modelo del Router (default). Setealo solo para forzar un modelo a este agente.",model_ph:"(vacío = router default)",skills_label:"Skills (coma)",bio_label:"Bio / descripción",system_label:"System prompt",system_hint:"Define personalidad y comportamiento (cuerpo del AGENT.md).",master_label:"Orquestador (master)",delete_btn:"Borrar agente",save_btn:"Guardar cambios",delete_confirm:'Borrar el agente "{slug}"? Se elimina .apc/agents/{slug}.md y sus datos runtime locales.',update_success:"Agente actualizado.",delete_success:"Agente borrado.",tools_hint:"Qué tools puede usar el agente. Tocá para activar/desactivar; o editá la lista abajo.",tools_custom_ph:"lista (coma): echo, http_fetch",memory_title:"Memoria del agente",memory_empty:"(memoria vacía)",memory_saved:"Memoria guardada.",records_title:"Records",records_desc:"Log de actividad del agente (mensajes/acciones). Lo más nuevo primero.",sleep_title:"Sleep / Heartbeat",sleep_desc:"Estado de ejecución del agente, derivado de sus rutinas.",sleep_deep:"Deep sleep · sin heartbeat",sleep_deep_desc:"Este agente no tiene ninguna rutina que lo dispare. No se ejecuta de forma autónoma; solo responde cuando lo invocás (chat / tarea).",brain_title:"Brain",brain_desc:"Grafo de relaciones reales del agente: memoria, threads, tasks, heartbeats y jerarquía. (primera versión — lo refinamos)",brain_empty:"Aún no hay relaciones para graficar (sin memoria, threads, tasks ni rutinas).",msgs_count:"msgs"},mcps:{title:"MCP servers",subtitle:"3 scopes: Runtime > Shared > Global. Conflictos arriba si los hay.",empty:"Sin MCPs configurados.",new:"MCP",delete_confirm:"Borrar MCP {name} de scope {scope}?",conflicts:"⚠ Conflictos: {names}",conflict_detail:"{name} está definido en {winner} y {loser}. Se usa {winner}; {loser} queda ignorado.",new_title:"Nuevo MCP",edit_title:"Editar MCP",new_desc:"Se guarda según el scope elegido. Los valores con ${var.X} se resuelven al arrancar el MCP.",scope_label:"Scope",scope_runtime:"Runtime",scope_shared:"Shared",scope_global:"Global",source_runtime:"Runtime",source_apc:"APC / Shared",source_claude:"Claude",source_codex:"Codex",source_cursor:"Cursor",source_vscode:"VS Code",source_roo:"Roo",source_gemini:"Gemini",scope_runtime_desc:"Solo este proyecto · con secrets · no se commitea (~/.apx/projects/<id>/mcps.json)",scope_shared_desc:"Solo este proyecto · committeable · sin secrets (.apc/mcps.json)",scope_global_desc:"Todos los proyectos de esta máquina (~/.apx/mcps.json)",transport_stdio:"stdio",transport_http:"HTTP",transport_stdio_desc:"Proceso local — `command` + args",transport_http_desc:"Endpoint remoto — URL + headers",transport_label:"Transport",name_label:"Nombre",name_ph:"my-mcp",cmd_label:"Comando",cmd_ph:"npx",args_label:"Args",args_hint_tokens:"Una entrada por argumento. Usá el botón + para insertar variables.",env_label:"Env",env_hint_tokens:"Pares clave/valor. Los valores aceptan ${var.NOMBRE} (botón + a la derecha).",env_empty:"Sin variables de entorno.",url_label:"URL",url_ph:"https://example.com/v2/mcp",headers_label:"Headers",headers_hint:"Pares clave/valor — típicamente Authorization: Bearer ${var.TOKEN}.",headers_empty:"Sin headers.",enabled_label:"Habilitado",add_btn:"Agregar",save_btn:"Guardar",add_arg:"Agregar arg",edit_btn:"Editar",test_btn:"Probar",logs_btn:"Logs",testing:"Probando…",test_ok:"OK · {n} tools disponibles",tools_count:"{n} tools",logs_title:"Logs · {name}",logs_empty:"Sin logs todavía. Arrancá el MCP llamando un tool o probando.",logs_events:"Eventos recientes",logs_stderr:"stderr (últimos 4KB)",logs_panel_title:"Live logs",logs_panel_pick:"elegí un MCP",logs_panel_hint:"Click un MCP de la lista para ver lo que está pasando en vivo.",logs_panel_idle:"Sin actividad. Apretá Probar para arrancarlo.",name_required:"Nombre requerido",removed:"eliminado",added:"MCP agregado.",updated:"MCP actualizado."},vars:{title:"Variables",subtitle_project:"Reemplazan ${var.NOMBRE} al cargar MCPs y plantillas. Las del proyecto ganan sobre las globales. Se guardan fuera del repo (~/.apx/, chmod 0600).",subtitle_base:"Variables globales — disponibles para todos los proyectos. Se guardan en ~/.apx/vars.json (chmod 0600).",empty:"Sin variables todavía.",new:"Variable",new_title:"Nueva variable",edit_title:"Editar variable",new_desc:"Se referencia como ${var.NOMBRE} en cualquier campo que soporte interpolación.",reveal_all:"Mostrar valores",reveal:"Mostrar",hide:"Ocultar",filter_label:"Mostrar:",filter_all:"Todas",filter_project:"Sólo proyecto",filter_global:"Sólo globales",scope_label:"Scope",scope_project:"proyecto",scope_project_desc:"Sólo este proyecto. Pisa la global con mismo nombre.",scope_global:"global",scope_global_desc:"Disponible en todos los proyectos.",name_label:"Nombre",name_hint:"Mayúsculas, dígitos y _. P. ej.: MY_API_KEY, GITHUB_TOKEN.",value_label:"Valor",value_hint:"Se guarda en disco con permisos 0600. Nunca se commitea.",value_edit_ph:"(dejá vacío para no cambiarlo… aún no soportado, pegá el valor de nuevo)",add_btn:"Agregar",save_btn:"Guardar",edit_btn:"Editar",delete_btn:"Borrar",delete_confirm:"¿Borrar {name} ({scope})?",removed:"Variable eliminada.",added:"Variable agregada.",updated:"Variable actualizada.",name_required:"Nombre requerido.",value_required:"Valor requerido."},threads:{title:"Chats",subtitle:"Conversaciones por agent (vacío = ningún log persistido todavía).",no_agents:"No hay agents. Las conversaciones requieren un agent configurado.",pick:"Elegí un agent para ver sus conversaciones.",empty:"No hay conversaciones para {slug}.",conversation_title:"Conversación {id}",messages:"mensajes",via:"via"},config:{title:"Config rápida",subtitle:"Override del proyecto. Se escribe en {path}.",model:"super_agent.model",model_hint:"ej. anthropic:claude-sonnet-4.5, ollama:gemma2:9b",perm:"super_agent.permission_mode",route:"route_to_agent",route_hint:"Slug del agent que atiende por defecto en este proyecto.",use_global:"(usa global)",saved:"Guardado.",nothing:"Nada para guardar.",raw_title:"Config (JSON crudo)",raw_subtitle:"Pegá el objeto entero — equivale a PUT del archivo.",raw_save:"Reemplazar config",raw_done:"Config sobrescrita.",effective:"Effective config (read-only)",effective_sub:"Lo que ve realmente el daemon (global ⊕ override).",section_title:"Config proyecto",section_desc:"APC metadata y overrides separados. General APX vive en Settings > Config.",effective_read:"Lectura: global APX + override proyecto.",save_project:".apc/project.json guardado.",save_override:".apc/config.json guardado.",save_fields_success:"Overrides guardados.",save_meta_success:"Project metadata guardado.",no_data:"Sin datos.",tab_settings:"Settings",tab_project:"Project"},telegram:{title:"Canal de Telegram (override)",subtitle:"Si seteás un canal acá, los mensajes generados por este proyecto se mandan ahí en lugar del default.",use_default:"Usar el canal default",bot_token:"Bot token (override)",chat_id:"Chat ID (override)",saved:"Override guardado.",cleared:"Override eliminado — vuelve al default.",override_active:"override activo",channel_badge:"Canal {name}",no_override:"Sin override. Los mensajes de este proyecto van al canal default.",respond_engine:"Responder con engine",route_agent:"route_to_agent",route_hint:"Slug del agent que atiende (vacío = super-agent).",bot_hint_none:"Si vacío, hereda del default."},memories:{sidebar_title:"Memorias",general_group:"General",general_item:"Memoria del proyecto",project_title:"Memoria del proyecto",project_desc:"Hechos durables a nivel proyecto. .apc/memory.md — la leen los agentes y el super-agente.",project_ph:`# Memoria del proyecto
|
|
761
|
+
*/var Zj;function _O(){if(Zj)return lh;Zj=1;var e=Yc(),t=uC();function a(g,h){return g===h&&(g!==0||1/g===1/h)||g!==g&&h!==h}var o=typeof Object.is=="function"?Object.is:a,l=t.useSyncExternalStore,c=e.useRef,d=e.useEffect,f=e.useMemo,m=e.useDebugValue;return lh.useSyncExternalStoreWithSelector=function(g,h,b,_,j){var E=c(null);if(E.current===null){var y={hasValue:!1,value:null};E.current=y}else y=E.current;E=f(function(){function N(T){if(!w){if(w=!0,S=T,T=_(T),j!==void 0&&y.hasValue){var z=y.value;if(j(z,T))return R=z}return R=T}if(z=R,o(S,T))return z;var M=_(T);return j!==void 0&&j(z,M)?(S=T,z):(S=T,R=M)}var w=!1,S,R,A=b===void 0?null:b;return[function(){return N(h())},A===null?void 0:function(){return N(A())}]},[h,b,_,j]);var k=l(g,E[0],E[1]);return d(function(){y.hasValue=!0,y.value=k},[k]),m(k),k},lh}var Jj;function vO(){return Jj||(Jj=1,oh.exports=_O()),oh.exports}var yO=vO();const jO=Yb(19),kO=jO?SO:CO;function tt(e,t,a,o,l){return kO(e,t,a,o,l)}function wO(e,t,a,o,l){const c=x.useCallback(()=>t(e.getSnapshot(),a,o,l),[e,t,a,o,l]);return Uc.useSyncExternalStore(e.subscribe,c,c)}l4({before(e){e.syncIndex=0,e.didInitialize||(e.syncTick=1,e.syncHooks=[],e.didChangeStore=!0,e.getSnapshot=()=>{let t=!1;for(let a=0;a<e.syncHooks.length;a+=1){const o=e.syncHooks[a],l=o.selector(o.store.state,o.a1,o.a2,o.a3);Object.is(o.value,l)||(t=!0,o.value=l)}return t&&(e.syncTick+=1),e.syncTick})},after(e){e.syncHooks.length>0&&(e.didChangeStore&&(e.didChangeStore=!1,e.subscribe=t=>{const a=new Set;for(const l of e.syncHooks)a.add(l.store);const o=[];for(const l of a)o.push(l.subscribe(t));return()=>{for(const l of o)l()}}),Uc.useSyncExternalStore(e.subscribe,e.getSnapshot,e.getSnapshot))}});function SO(e,t,a,o,l){const c=o4();if(!c)return wO(e,t,a,o,l);const d=c.syncIndex;c.syncIndex+=1;let f;return c.didInitialize?(f=c.syncHooks[d],(f.store!==e||f.selector!==t||!Object.is(f.a1,a)||!Object.is(f.a2,o)||!Object.is(f.a3,l))&&(f.store!==e&&(c.didChangeStore=!0),f.store=e,f.selector=t,f.a1=a,f.a2=o,f.a3=l,f.value=t(e.getSnapshot(),a,o,l))):(f={store:e,selector:t,a1:a,a2:o,a3:l,value:t(e.getSnapshot(),a,o,l)},c.syncHooks.push(f)),f.value}function CO(e,t,a,o,l){return yO.useSyncExternalStoreWithSelector(e.subscribe,e.getSnapshot,e.getSnapshot,c=>t(c,a,o,l))}class NO{constructor(t){this.state=t,this.listeners=new Set,this.updateTick=0}subscribe=t=>(this.listeners.add(t),()=>{this.listeners.delete(t)});getSnapshot=()=>this.state;setState(t){if(this.state===t)return;this.state=t,this.updateTick+=1;const a=this.updateTick;for(const o of this.listeners){if(a!==this.updateTick)return;o(t)}}update(t){for(const a in t)if(!Object.is(this.state[a],t[a])){this.setState({...this.state,...t});return}}set(t,a){Object.is(this.state[t],a)||this.setState({...this.state,[t]:a})}notifyAll(){const t={...this.state};this.setState(t)}use(t,a,o,l){return tt(this,t,a,o,l)}}class nu extends NO{constructor(t,a={},o){super(t),this.context=a,this.selectors=o}useSyncedValue(t,a){x.useDebugValue(t);const o=this;Pe(()=>{o.state[t]!==a&&o.set(t,a)},[o,t,a])}useSyncedValueWithCleanup(t,a){const o=this;Pe(()=>(o.state[t]!==a&&o.set(t,a),()=>{o.set(t,void 0)}),[o,t,a])}useSyncedValues(t){const a=this,o=Object.values(t);Pe(()=>{a.update(t)},[a,...o])}useControlledProp(t,a){x.useDebugValue(t);const o=this,l=a!==void 0;Pe(()=>{l&&!Object.is(o.state[t],a)&&o.setState({...o.state,[t]:a})},[o,t,a,l])}select(t,a,o,l){const c=this.selectors[t];return c(this.state,a,o,l)}useState(t,a,o,l){return x.useDebugValue(t),tt(this,this.selectors[t],a,o,l)}useContextCallback(t,a){x.useDebugValue(t);const o=He(a??Nn);this.context[t]=o}useStateSetter(t){const a=x.useRef(void 0);return a.current===void 0&&(a.current=o=>{this.set(t,o)}),a.current}observe(t,a){let o;typeof t=="function"?o=t:o=this.selectors[t];let l=o(this.state);return a(l,l,this),this.subscribe(c=>{const d=o(c);if(!Object.is(l,d)){const f=l;l=d,a(d,f,this)}})}}const EO={open:e=>e.open,transitionStatus:e=>e.transitionStatus,domReferenceElement:e=>e.domReferenceElement,referenceElement:e=>e.positionReference??e.referenceElement,floatingElement:e=>e.floatingElement,floatingId:e=>e.floatingId};class up extends nu{constructor(t){const{syncOnly:a,nested:o,onOpenChange:l,triggerElements:c,...d}=t;super({...d,positionReference:d.referenceElement,domReferenceElement:d.referenceElement},{onOpenChange:l,dataRef:{current:{}},events:WS(),nested:o,triggerElements:c},EO),this.syncOnly=a}syncOpenEvent=(t,a)=>{(!t||!this.state.open||a!=null&&b4(a))&&(this.context.dataRef.current.openEvent=t?a:void 0)};dispatchOpenChange=(t,a)=>{this.syncOpenEvent(t,a.event);const o={open:t,reason:a.reason,nativeEvent:a.event,nested:this.context.nested,triggerElement:a.trigger};this.context.events.emit("openchange",o)};setOpen=(t,a)=>{if(this.syncOnly){this.context.onOpenChange?.(t,a);return}this.dispatchOpenChange(t,a),this.context.onOpenChange?.(t,a)}}function dC(e){const{popupStore:t,treatPopupAsFloatingElement:a=!1,floatingRootContext:o,floatingId:l,nested:c,onOpenChange:d}=e,f=t.useState("open"),m=t.useState("activeTriggerElement"),g=t.useState(a?"popupElement":"positionerElement"),h=t.context.triggerElements,b=d,_=x.useRef(null);o===void 0&&_.current===null&&(_.current=new up({open:f,transitionStatus:void 0,referenceElement:m,floatingElement:g,triggerElements:h,onOpenChange:b,floatingId:l,syncOnly:!0,nested:c}));const j=o??_.current;return t.useSyncedValue("floatingId",l),Pe(()=>{const E={open:f,floatingId:l,referenceElement:m,floatingElement:g};bt(m)&&(E.domReferenceElement=m),j.state.positionReference===j.state.referenceElement&&(E.positionReference=m),j.update(E)},[f,l,m,g,j]),j.context.onOpenChange=b,j.context.nested=c,j}function hi(e,t=!1,a=!1){const[o,l]=x.useState(e&&t?"idle":void 0),[c,d]=x.useState(e);return e&&!c&&(d(!0),l("starting")),!e&&c&&o!=="ending"&&!a&&l("ending"),!e&&!c&&o==="ending"&&l(void 0),Pe(()=>{if(!e&&c&&o!=="ending"&&a){const f=ga.request(()=>{l("ending")});return()=>{ga.cancel(f)}}},[e,c,o,a]),Pe(()=>{if(!e||t)return;const f=ga.request(()=>{l(void 0)});return()=>{ga.cancel(f)}},[t,e]),Pe(()=>{if(!e||!t)return;e&&c&&o!=="idle"&&l("starting");const f=ga.request(()=>{l("idle")});return()=>{ga.cancel(f)}},[t,e,c,o]),{mounted:c,setMounted:d,transitionStatus:o}}function fC(e,t=!1){const a=Jl();return He((o,l=null)=>{a.cancel();const c=Xa(e);if(c==null)return;const d=c,f=()=>{Gs.flushSync(o)};if(typeof d.getAnimations!="function"||globalThis.BASE_UI_ANIMATIONS_DISABLED){o();return}function m(){Promise.all(d.getAnimations().map(g=>g.finished)).then(()=>{l?.aborted||f()},()=>{if(l?.aborted)return;if(d.getAnimations().some(h=>h.pending||h.playState!=="finished")){m();return}f()})}if(t){const g="data-starting-style";if(!d.hasAttribute(g)){a.request(m);return}const h=new MutationObserver(()=>{d.hasAttribute(g)||(h.disconnect(),m())});h.observe(d,{attributes:!0,attributeFilter:[g]}),l?.addEventListener("abort",()=>h.disconnect(),{once:!0});return}a.request(m)})}function Ca(e){const{enabled:t=!0,open:a,ref:o,onComplete:l}=e,c=He(l),d=fC(o,a);x.useEffect(()=>{if(!t)return;const f=new AbortController;return d(c,f.signal),()=>{f.abort()}},[t,a,c,d])}const dp={tabIndex:-1,[hx]:""};function RO(e){return t=>t==="touch"?e.current:!0}function pC(e,t=!1){const a=Oo(),o=eo()!=null,l=Hn(()=>e(a,o)).current;return dC({popupStore:l,treatPopupAsFloatingElement:t,floatingRootContext:l.state.floatingRootContext,floatingId:a,nested:o,onOpenChange:l.setOpen}),l}function t_({handle:e,store:t}){return Pe(()=>e.attachStore(t),[e,t]),null}function TO(e,t){const a=x.useRef(null),o=x.useRef(null);return x.useCallback(l=>{if(e===void 0)return;let c=!1;if(a.current!==null){const d=a.current,f=o.current,m=t.context.triggerElements.getById(d);f&&m===f&&(t.context.triggerElements.delete(d),c=!0),a.current=null,o.current=null}if(l!==null&&(a.current=e,o.current=l,t.context.triggerElements.add(e,l),c=!0),c){const d=t.context.triggerElements.size;t.select("open")&&t.state.triggerCount!==d&&t.set("triggerCount",d)}},[t,e])}function n_(e,t,a,o=!1){t?e.preventUnmountingOnClose=!1:o&&(e.preventUnmountingOnClose=!0);const l=a?.id??null;(l||t)&&(e.activeTriggerId=l,e.activeTriggerElement=a??null)}function mC(e){let t=!1;return e.preventUnmountOnClose=()=>{t=!0},()=>t}function AO(e,t,a,o={}){const l=a.reason,c=l===En,d=t&&l===Vl,f=!t&&(l===gi||l===op),m=mC(a);if(e.context.onOpenChange?.(t,a),a.isCanceled)return;o.onBeforeDispatch?.(),e.state.floatingRootContext.dispatchOpenChange(t,a);const g=()=>{const h={...o.extraState,open:t};d?h.instantType="focus":f?h.instantType="dismiss":c&&(h.instantType=void 0),n_(h,t,a.trigger,m()),e.update(h)};c?Gs.flushSync(g):g()}function gC(e,t,a,o){const l=a.useState("isMountedByTrigger",e),c=TO(e,a),d=He(m=>{const g=a.select("open"),h=a.select("activeTriggerId");if(h===e){a.update({activeTriggerElement:m,...g?o:null});return}h==null&&g&&a.update({activeTriggerId:e,activeTriggerElement:m,...o})}),f=x.useCallback(m=>{c(m),m&&d(m)},[c,d]);return Pe(()=>{l&&a.update({activeTriggerElement:t.current,...o})},[l,a,t,...Object.values(o)]),{registerTrigger:f,isMountedByThisTrigger:l}}function s_(e,t={}){const{closeOnActiveTriggerUnmount:a=!1}=t,o=x.useRef(null),l=e.useState("open"),c=e.useState("triggerCount"),d=e.useState("activeTriggerId"),f=e.useState("activeTriggerElement");Pe(()=>{if(!l){o.current=null,e.state.triggerCount!==0&&e.set("triggerCount",0);return}const m=e.context.triggerElements.size,g={};e.state.triggerCount!==m&&(g.triggerCount=m);const h=e.select("activeTriggerId");let b=null;if(h){const _=e.context.triggerElements.getById(h);if(_)o.current=h,_!==e.state.activeTriggerElement&&(g.activeTriggerElement=_);else{for(const[j,E]of e.context.triggerElements.entries())if(E===e.state.activeTriggerElement){g.activeTriggerId=j,g.activeTriggerElement=E,o.current=j;break}g.activeTriggerId===void 0&&(o.current===h?b=h:o.current=null)}}else o.current=null;if(!b&&!h&&m===1){const _=e.context.triggerElements.entries().next();if(!_.done){const[j,E]=_.value;g.activeTriggerId=j,g.activeTriggerElement=E,o.current=j}}(g.triggerCount!==void 0||g.activeTriggerId!==void 0||g.activeTriggerElement!==void 0)&&e.update(g),b&&a&&queueMicrotask(()=>{if(e.select("open")&&e.select("activeTriggerId")===b&&!e.context.triggerElements.getById(b)){const _=rt(ka);e.setOpen(!1,_),_.isCanceled||e.update({activeTriggerId:null,activeTriggerElement:null})}})},[l,e,c,d,f,a])}function a_(e,t,a){const{mounted:o,setMounted:l,transitionStatus:c}=hi(e),d=t.useState("preventUnmountingOnClose"),f=e?!1:d;t.useSyncedValues({mounted:o,transitionStatus:c,preventUnmountingOnClose:f});const m=He(()=>{l(!1),t.update({activeTriggerId:null,activeTriggerElement:null,mounted:!1,preventUnmountingOnClose:!1}),a?.(),t.context.onOpenChangeComplete?.(!1)});return Ca({enabled:o&&!e&&!f,open:e,ref:t.context.popupRef,onComplete(){e||m()}}),{forceUnmount:m,transitionStatus:c}}function r_(e,t){e.useSyncedValues(t),Pe(()=>()=>{e.update({activeTriggerProps:sn,inactiveTriggerProps:sn,popupProps:sn})},[e])}function MO(e,t){Pe(()=>{!t&&e.state.openMethod!==null&&e.set("openMethod",null)},[t,e]),Pe(()=>()=>{e.state.openMethod!==null&&e.set("openMethod",null)},[e])}class su{constructor(){this.idMap=new Map}add(t,a){this.idMap.set(t,a)}delete(t){this.idMap.delete(t)}hasElement(t){for(const a of this.idMap.values())if(a===t)return!0;return!1}hasMatchingElement(t){for(const a of this.idMap.values())if(t(a))return!0;return!1}getById(t){return this.idMap.get(t)}entries(){return this.idMap.entries()}elements(){return this.idMap.values()}get size(){return this.idMap.size}}function zO(){return new up({open:!1,transitionStatus:void 0,floatingElement:null,referenceElement:null,triggerElements:new su,floatingId:void 0,syncOnly:!1,nested:!1,onOpenChange:void 0})}function o_(){return{open:!1,openProp:void 0,mounted:!1,transitionStatus:void 0,floatingRootContext:zO(),floatingId:void 0,triggerCount:0,preventUnmountingOnClose:!1,payload:void 0,activeTriggerId:null,activeTriggerElement:null,triggerIdProp:void 0,popupElement:null,positionerElement:null,activeTriggerProps:sn,inactiveTriggerProps:sn,popupProps:sn}}function hC(e,t,a=!1){return new up({open:!1,transitionStatus:void 0,floatingElement:null,referenceElement:null,triggerElements:e,floatingId:t,syncOnly:!0,nested:a,onOpenChange:void 0})}const Tc=e=>e.triggerIdProp??e.activeTriggerId,l_=e=>e.openProp??e.open,ek=e=>(e.popupElement?.id??e.floatingId)||void 0;function xC(e,t){return t!==void 0&&l_(e)&&Tc(e)===t}function OO(e,t){return xC(e,t)?!0:t!==void 0&&l_(e)&&Tc(e)==null&&e.triggerCount===1}const i_={open:l_,mounted:e=>e.mounted,transitionStatus:e=>e.transitionStatus,floatingRootContext:e=>e.floatingRootContext,triggerCount:e=>e.triggerCount,preventUnmountingOnClose:e=>e.preventUnmountingOnClose,payload:e=>e.payload,activeTriggerId:Tc,activeTriggerElement:e=>e.mounted?e.activeTriggerElement:null,popupId:ek,isTriggerActive:(e,t)=>t!==void 0&&Tc(e)===t,isOpenedByTrigger:(e,t)=>xC(e,t),isMountedByTrigger:(e,t)=>t!==void 0&&Tc(e)===t&&e.mounted,triggerProps:(e,t)=>t?e.activeTriggerProps:e.inactiveTriggerProps,triggerPopupId:(e,t)=>OO(e,t)?ek(e):void 0,popupProps:e=>e.popupProps,popupElement:e=>e.popupElement,positionerElement:e=>e.positionerElement};function bC(e){const t=x.useCallback(o=>e===void 0?Nn:e.subscribeStore(o),[e]),a=x.useCallback(()=>e===void 0?void 0:e.store,[e]);return Uc.useSyncExternalStore(t,a,()=>e?.serverStore)}function DO(e){const{open:t=!1,onOpenChange:a,elements:o={}}=e,l=Oo(),c=eo()!=null,d=Hn(()=>new up({open:t,transitionStatus:void 0,onOpenChange:a,referenceElement:o.reference??null,floatingElement:o.floating??null,triggerElements:new su,floatingId:l,syncOnly:!1,nested:c})).current;return Pe(()=>{const f={open:t,floatingId:l};o.reference!==void 0&&(f.referenceElement=o.reference,f.domReferenceElement=bt(o.reference)?o.reference:null),o.floating!==void 0&&(f.floatingElement=o.floating),d.update(f)},[t,l,o.reference,o.floating,d]),d.context.onOpenChange=a,d.context.nested=c,d}function PO(e){return LO(e,e.rootContext)}function LO(e,t){const{nodeId:a,externalTree:o}=e,l=t.useState("referenceElement"),c=t.useState("floatingElement"),d=t.useState("domReferenceElement"),f=t.useState("open"),m=t.useState("floatingId"),[g,h]=x.useState(null),[b,_]=x.useState(void 0),[j,E]=x.useState(void 0),y=x.useRef(null),k=to(o),N=x.useMemo(()=>({reference:l,floating:c,domReference:d}),[l,c,d]),w=fO({...e,elements:{...N,...g&&{reference:g}}}),S=bt(b)?b:null,R=j===void 0?t.state.floatingElement:j;t.useSyncedValue("referenceElement",b??null),t.useSyncedValue("domReferenceElement",b===void 0?d:S),t.useSyncedValue("floatingElement",R);const A=x.useCallback(B=>{const D=bt(B)?{getBoundingClientRect:()=>B.getBoundingClientRect(),getClientRects:()=>B.getClientRects(),contextElement:B}:B;h(D),w.refs.setReference(D)},[w.refs]),T=x.useCallback(B=>{(bt(B)||B===null)&&(y.current=B,_(B)),(bt(w.refs.reference.current)||w.refs.reference.current===null||B!==null&&!bt(B))&&w.refs.setReference(B)},[w.refs,_]),z=x.useCallback(B=>{E(B),w.refs.setFloating(B)},[w.refs]),M=x.useMemo(()=>({...w.refs,setReference:T,setFloating:z,setPositionReference:A,domReference:y}),[w.refs,T,z,A]),L=x.useMemo(()=>({...w.elements,domReference:d}),[w.elements,d]),P=x.useMemo(()=>({...w,dataRef:t.context.dataRef,open:f,onOpenChange:t.setOpen,events:t.context.events,floatingId:m,refs:M,elements:L,nodeId:a,rootStore:t}),[w,M,L,a,t,f,m]);return Pe(()=>{d&&(y.current=d)},[d]),Pe(()=>{t.context.dataRef.current.floatingContext=P;const B=k?.nodesRef.current.find(D=>D.id===a);B&&(B.context=P)}),x.useMemo(()=>({...w,context:P,refs:M,elements:L,rootStore:t}),[w,M,L,P,t])}const ih=Ab&&ir;function _C(e,t={}){const{enabled:a=!0,delay:o}=t,l="rootStore"in e?e.rootStore:e,{events:c,dataRef:d}=l.context,f=x.useRef(!1),m=x.useRef(null),g=x.useRef(!0),h=Rn();x.useEffect(()=>{const _=l.select("domReferenceElement");if(!a)return;const j=Jt(_);function E(){const N=l.select("domReferenceElement");!l.select("open")&&Gt(N)&&N===Kn(vt(N))&&(f.current=!0)}function y(){g.current=!0}function k(){g.current=!1}return _a(xt(j,"blur",E),ih&&xt(j,"keydown",y,!0),ih&&xt(j,"pointerdown",k,!0))},[l,a]),x.useEffect(()=>{if(!a)return;function _(j){if(j.reason===gi||j.reason===op){const E=l.select("domReferenceElement");bt(E)&&(m.current=E,f.current=!0)}}return c.on("openchange",_),()=>{c.off("openchange",_)}},[c,a,l]);const b=x.useMemo(()=>{function _(){f.current=!1,m.current=null}return{onMouseLeave(){_()},onFocus(j){const E=j.currentTarget;if(f.current){if(m.current===E)return;_()}const y=qn(j.nativeEvent);if(bt(y)){if(ih&&!j.relatedTarget){if(!g.current&&!ap(y))return}else if(!S4(y))return}const k=pf(j.relatedTarget,l.context.triggerElements),{nativeEvent:N,currentTarget:w}=j,S=typeof o=="function"?o():o;if(l.select("open")&&k||S===0||S===void 0){l.setOpen(!0,rt(Vl,N,w));return}h.start(S,()=>{f.current||l.setOpen(!0,rt(Vl,N,w))})},onBlur(j){_();const E=j.relatedTarget,y=j.nativeEvent,k=bt(E)&&E.hasAttribute($c("focus-guard"))&&E.getAttribute("data-type")==="outside";h.start(0,()=>{const N=l.select("domReferenceElement"),w=Kn(vt(N));!E&&w===N||Ze(d.current.floatingContext?.refs.floating.current,w)||Ze(N,w)||k||pf(E??w,l.context.triggerElements)||l.setOpen(!1,rt(Vl,y))})}}},[d,o,l,h]);return x.useMemo(()=>a?{reference:b,trigger:b}:{},[a,b])}class c_{constructor(){this.pointerType=void 0,this.interactedInside=!1,this.handler=void 0,this.blockMouseMove=!0,this.performedPointerEventsMutation=!1,this.pointerEventsScopeElement=null,this.pointerEventsReferenceElement=null,this.pointerEventsFloatingElement=null,this.restTimeoutPending=!1,this.openChangeTimeout=new ta,this.restTimeout=new ta,this.handleCloseOptions=void 0}static create(){return new c_}dispose=()=>{this.openChangeTimeout.clear(),this.restTimeout.clear()};disposeEffect=()=>this.dispose}const yf=new WeakMap;function jf(e){if(!e.performedPointerEventsMutation)return;const t=e.pointerEventsScopeElement;t&&yf.get(t)===e&&(e.pointerEventsScopeElement?.style.removeProperty("pointer-events"),e.pointerEventsReferenceElement?.style.removeProperty("pointer-events"),e.pointerEventsFloatingElement?.style.removeProperty("pointer-events"),yf.delete(t)),e.performedPointerEventsMutation=!1,e.pointerEventsScopeElement=null,e.pointerEventsReferenceElement=null,e.pointerEventsFloatingElement=null}function vC(e,t){const{scopeElement:a,referenceElement:o,floatingElement:l}=t,c=yf.get(a);c&&c!==e&&jf(c),jf(e),e.performedPointerEventsMutation=!0,e.pointerEventsScopeElement=a,e.pointerEventsReferenceElement=o,e.pointerEventsFloatingElement=l,yf.set(a,e),a.style.pointerEvents="none",o.style.pointerEvents="auto",l.style.pointerEvents="auto"}function u_(e){const t=e.context.dataRef.current,a=Hn(()=>t.hoverInteractionState??c_.create()).current;return t.hoverInteractionState||(t.hoverInteractionState=a),Tb(t.hoverInteractionState.disposeEffect),t.hoverInteractionState}function yC(e,t={}){const{enabled:a=!0,closeDelay:o=0,nodeId:l}=t,c="rootStore"in e?e.rootStore:e,d=c.useState("open"),f=c.useState("floatingElement"),m=c.useState("domReferenceElement"),{dataRef:g}=c.context,h=to(),b=eo(),_=u_(c),j=Rn(),E=He(()=>vS(g.current.openEvent?.type,_.interactedInside)),y=He(()=>N4(g.current.openEvent?.type)),k=He(()=>{jf(_)});Pe(()=>{d||(_.pointerType=void 0,_.restTimeoutPending=!1,_.interactedInside=!1,k())},[d,_,k]),x.useEffect(()=>k,[k]),Pe(()=>{if(a&&d&&_.handleCloseOptions?.blockPointerEvents&&y()&&bt(m)&&f){const N=m,w=f,S=vt(f),R=h?.nodesRef.current.find(M=>M.id===b)?.context?.elements.floating;R&&(R.style.pointerEvents="");const A=_.pointerEventsScopeElement!==w?_.pointerEventsScopeElement:null,T=R!==w?R:null,z=_.handleCloseOptions?.getScope?.()??A??T??N.closest("[data-rootownerid]")??S.body;return vC(_,{scopeElement:z,referenceElement:N,floatingElement:w}),()=>{k()}}},[a,d,m,f,_,y,h,b,k]),x.useEffect(()=>{if(!a)return;function N(){return!!(h&&b&&Qr(h.nodesRef.current,b).length>0)}function w(M){const L=Kr(o,"close",_.pointerType),P=()=>{c.setOpen(!1,rt(En,M)),h?.events.emit("floating.closed",M)};L?_.openChangeTimeout.start(L,P):(_.openChangeTimeout.clear(),P())}function S(M){const L=qn(M);if(!w4(L)){_.interactedInside=!1;return}_.interactedInside=L?.closest("[aria-haspopup]")!=null}function R(){_.openChangeTimeout.clear(),j.clear(),h?.events.off("floating.closed",T),k()}function A(M){if(N()&&h){h.events.on("floating.closed",T);return}if(pf(M.relatedTarget,c.context.triggerElements))return;const L=g.current.floatingContext?.nodeId??l,P=M.relatedTarget;if(!(h&&L&&bt(P)&&Qr(h.nodesRef.current,L,!1).some(D=>Ze(D.context?.elements.floating,P)))){if(_.handler){_.handler(M);return}k(),y()&&!E()&&w(M)}}function T(M){!h||!b||N()||j.start(0,()=>{h.events.off("floating.closed",T),c.setOpen(!1,rt(En,M)),h.events.emit("floating.closed",M)})}const z=f;return _a(z&&xt(z,"mouseenter",R),z&&xt(z,"mouseleave",A),z&&xt(z,"pointerdown",S,!0),()=>{h?.events.off("floating.closed",T)})},[a,f,c,g,o,l,y,E,k,_,h,b,j])}const IO={current:null};function jC(e,t={}){const{enabled:a=!0,delay:o=0,handleClose:l=null,mouseOnly:c=!1,restMs:d=0,move:f=!0,triggerElementRef:m=IO,externalTree:g,isActiveTrigger:h=!0,getHandleCloseContext:b,isClosing:_,shouldOpen:j,guardStaleOpen:E=!1}=t,y="rootStore"in e?e.rootStore:e,{dataRef:k,events:N}=y.context,w=to(g),S=u_(y),R=x.useRef(!1),A=mn(l),T=mn(o),z=mn(d),M=mn(a),L=mn(j),P=mn(_),B=He(()=>vS(k.current.openEvent?.type,S.interactedInside)),D=He(()=>L.current?.()!==!1),$=He((U,V,X)=>{const Q=y.context.triggerElements;if(Q.hasElement(V))return!U||!Ze(U,V);if(!bt(X))return!1;const W=X;return Q.hasMatchingElement(I=>Ze(I,W))&&(!U||!Ze(U,W))}),q=He(()=>{if(!S.handler)return;vt(y.select("domReferenceElement")).removeEventListener("mousemove",S.handler),S.handler=void 0}),G=He(()=>{jf(S)});return h&&(S.handleCloseOptions=A.current?.__options),x.useEffect(()=>q,[q]),x.useEffect(()=>{if(!a)return;function U(V){V.open?R.current=!1:(R.current=V.reason===En,q(),S.openChangeTimeout.clear(),S.restTimeout.clear(),S.blockMouseMove=!0,S.restTimeoutPending=!1)}return N.on("openchange",U),()=>{N.off("openchange",U)}},[a,N,S,q]),x.useEffect(()=>{if(!a)return;function U(K,ee=!0){const F=Kr(T.current,"close",S.pointerType);F?S.openChangeTimeout.start(F,()=>{y.setOpen(!1,rt(En,K)),w?.events.emit("floating.closed",K)}):ee&&(S.openChangeTimeout.clear(),y.setOpen(!1,rt(En,K)),w?.events.emit("floating.closed",K))}const V=m.current??(h?y.select("domReferenceElement"):null);if(!bt(V))return;function X(K){if(S.openChangeTimeout.clear(),S.blockMouseMove=!1,c&&!Hr(S.pointerType))return;const ee=Sj(z.current),F=Kr(T.current,"open",S.pointerType),ne=qn(K),Z=K.currentTarget??null,fe=y.select("domReferenceElement");let Y=Z;if(bt(ne)&&!y.context.triggerElements.hasElement(ne)){for(const Oe of y.context.triggerElements.elements())if(Ze(Oe,ne)){Y=Oe;break}}bt(Z)&&bt(fe)&&!y.context.triggerElements.hasElement(Z)&&Ze(Z,fe)&&(Y=fe);const oe=Y==null?!1:$(fe,Y,ne),ve=y.select("open"),le=P.current?.()??y.select("transitionStatus")==="ending",xe=!ve&&le&&R.current,ke=!oe&&bt(Y)&&bt(fe)&&Ze(fe,Y)&&xe,Re=ee>0&&!F,Ae=oe&&(ve||xe)||ke,Ie=!ve||oe;if(Ae){D()&&y.setOpen(!0,rt(En,K,Y));return}Re||(F?S.openChangeTimeout.start(F,()=>{Ie&&D()&&y.setOpen(!0,rt(En,K,Y))}):Ie&&D()&&y.setOpen(!0,rt(En,K,Y)))}function Q(K){if(B()){G();return}q();const ee=y.select("domReferenceElement"),F=vt(ee);S.restTimeout.clear(),S.restTimeoutPending=!1;const ne=k.current.floatingContext??b?.();if(pf(K.relatedTarget,y.context.triggerElements))return;if(A.current&&ne){y.select("open")||S.openChangeTimeout.clear();const fe=m.current;S.handler=A.current({...ne,tree:w,x:K.clientX,y:K.clientY,onClose(){G(),q(),M.current&&!B()&&fe===y.select("domReferenceElement")&&U(K,!0)}}),F.addEventListener("mousemove",S.handler),S.handler(K);return}(S.pointerType==="touch"?!Ze(y.select("floatingElement"),K.relatedTarget):!0)&&U(K)}function W(K){Ze(V,K.relatedTarget)||(S.openChangeTimeout.clear(),S.restTimeout.clear(),S.restTimeoutPending=!1)}const I=E?xt(V,"mouseout",W):void 0;return f?_a(xt(V,"mousemove",X,{once:!0}),xt(V,"mouseenter",X),xt(V,"mouseleave",Q),I):_a(xt(V,"mouseenter",X),xt(V,"mouseleave",Q),I)},[q,G,k,T,y,a,A,S,h,$,B,c,f,z,m,w,M,b,P,D,E]),x.useMemo(()=>{if(!a)return;function U(V){S.pointerType=V.pointerType}return{onPointerDown:U,onPointerEnter:U,onMouseMove(V){const{nativeEvent:X}=V,Q=V.currentTarget,W=y.select("domReferenceElement"),I=y.select("open"),K=$(W,Q,V.target);if(c&&!Hr(S.pointerType))return;if(I&&K&&S.handleCloseOptions?.blockPointerEvents){const ne=y.select("floatingElement");if(ne){const Z=S.handleCloseOptions?.getScope?.()??Q.ownerDocument.body;vC(S,{scopeElement:Z,referenceElement:Q,floatingElement:ne})}}const ee=Sj(z.current);if(I&&!K||ee===0||!K&&S.restTimeoutPending&&V.movementX**2+V.movementY**2<2)return;S.restTimeout.clear();function F(){if(S.restTimeoutPending=!1,B())return;const ne=y.select("open");!S.blockMouseMove&&(!ne||K)&&D()&&y.setOpen(!0,rt(En,X,Q))}S.pointerType==="touch"?Gs.flushSync(()=>{F()}):K&&I?F():(S.restTimeoutPending=!0,S.restTimeout.start(ee,F))}}},[a,S,B,$,c,y,z,D])}const BO="Escape";function tk(e){return ir&&e.movementX===0&&e.movementY===0}function fp(e,t,a){switch(e){case"vertical":return t;case"horizontal":return a;default:return t||a}}function Rd(e,t){return fp(t,e===_S||e===Ib,e===np||e===sp)}function ch(e,t,a){return fp(t,e===Ib,a?e===np:e===sp)||e==="Enter"||e===" "||e===""}function $O(e,t,a){return fp(t,a?e===np:e===sp,e===Ib)}function UO(e,t,a,o){const l=a?e===sp:e===np,c=e===_S;return t==="both"||t==="horizontal"&&o?e===BO:fp(t,l,c)}function kC(e,t){const{listRef:a,activeIndex:o,onNavigate:l=()=>{},enabled:c=!0,selectedIndex:d=null,allowEscape:f=!1,loopFocus:m=!1,nested:g=!1,rtl:h=!1,virtual:b=!1,focusItemOnOpen:_="auto",focusItemOnHover:j=!0,openOnArrowKeyDown:E=!0,disabledIndices:y=void 0,orientation:k="vertical",parentOrientation:N,id:w,resetOnPointerLeave:S=!0,externalTree:R,grid:A}=t,T=A!=null,z="rootStore"in e?e.rootStore:e,M=z.useState("open"),L=z.useState("floatingElement"),P=z.useState("domReferenceElement"),B=z.context.dataRef,D=mf(L),$=xx(P),q=mn(D),G=eo(),U=to(R),V=x.useRef(_),X=x.useRef(d??-1),Q=x.useRef(null),W=x.useRef(!0),I=He(me=>{l(X.current===-1?null:X.current,me)}),K=x.useRef(!!L),ee=x.useRef(M),F=x.useRef(!1),ne=x.useRef(!1),Z=x.useRef(null),fe=mn(y),Y=mn(M),oe=mn(d),ve=mn(S),le=Jl(),xe=Jl(),ke=He(()=>{function me(Ce){b?U?.events.emit("virtualfocus",Ce):Z.current=tf(Ce,{sync:F.current,preventScroll:!0})}const de=a.current[X.current],Le=ne.current;de&&me(de),(F.current?Ce=>Ce():Ce=>le.request(Ce))(()=>{const Ce=a.current[X.current]||de;if(!Ce)return;de||me(Ce),Ne&&(Le||!W.current)&&Ce.scrollIntoView?.({block:"nearest",inline:"nearest"})})});Pe(()=>{B.current.orientation=k},[B,k]),Pe(()=>{c&&(M&&L?(X.current=d??-1,V.current&&d!=null&&(ne.current=!0,I())):K.current&&(X.current=-1,I()))},[c,M,L,d,I]),Pe(()=>{if(c){if(!M){F.current=!1;return}if(L)if(o==null){if(F.current=!1,oe.current!=null)return;if(K.current&&(X.current=-1,ke()),(!ee.current||!K.current)&&V.current&&(Q.current!=null||V.current===!0&&Q.current==null)){let me=0;const de=()=>{a.current[0]==null?(me<2&&(me?ye=>xe.request(ye):queueMicrotask)(de),me+=1):(X.current=Q.current==null||ch(Q.current,k,h)||g?ef(a):vx(a),Q.current=null,I())};de()}}else Rc(a.current,o)||(X.current=o,ke(),ne.current=!1)}},[c,M,L,o,oe,g,a,k,h,I,ke,xe]),Pe(()=>{if(!c||L||!U||b||!K.current)return;const me=U.nodesRef.current,de=me.find(Ce=>Ce.id===G)?.context?.elements.floating,Le=Kn(vt(P??de??null)),ye=me.some(Ce=>Ce.context&&Ze(Ce.context.elements.floating,Le));de&&!ye&&W.current&&de.focus({preventScroll:!0})},[c,L,P,U,G,b]),Pe(()=>{ee.current=M,K.current=!!L}),Pe(()=>{M||(Q.current=null,V.current=_)},[M,_]);const Re=o!=null,Ae=He(me=>{if(!Y.current)return;const de=a.current.indexOf(me.currentTarget);de!==-1&&(X.current!==de||o!==de)&&(X.current=de,I(me))}),Ie=He(()=>N??U?.nodesRef.current.find(me=>me.id===G)?.context?.dataRef?.current.orientation),Oe=He(()=>ef(a,fe.current)),Te=He(me=>{if(W.current=!1,F.current=!0,me.which===229||!Y.current&&me.currentTarget===q.current)return;if(g&&UO(me.key,k,h,T)){Rd(me.key,Ie())||pa(me),z.setOpen(!1,rt(bx,me.nativeEvent)),Gt(P)&&(b?U?.events.emit("virtualfocus",P):P.focus());return}const de=X.current,Le=ef(a,y),ye=vx(a,y);if($||(me.key==="Home"&&(pa(me),X.current=Le,I(me)),me.key==="End"&&(pa(me),X.current=ye,I(me))),A!=null){const Ce=A(me,X.current,a,k,m,h,y,Le,ye);if(Ce!=null&&(X.current=Ce,I(me)),k==="both")return}if(Rd(me.key,k)){if(pa(me),M&&!b&&Kn(me.currentTarget.ownerDocument)===me.currentTarget){X.current=ch(me.key,k,h)?Le:ye,I(me);return}ch(me.key,k,h)?m?de>=ye?f&&de!==a.current.length?X.current=-1:(F.current=!1,X.current=Le):X.current=Qa(a.current,{startingIndex:de,disabledIndices:y}):X.current=Math.min(ye,Qa(a.current,{startingIndex:de,disabledIndices:y})):m?de<=Le?f&&de!==-1?X.current=a.current.length:(F.current=!1,X.current=ye):X.current=Qa(a.current,{startingIndex:de,decrement:!0,disabledIndices:y}):X.current=Math.max(Le,Qa(a.current,{startingIndex:de,decrement:!0,disabledIndices:y})),Rc(a.current,X.current)&&(X.current=-1),I(me)}}),Ne=x.useMemo(()=>({onFocus(de){F.current=!0,Ae(de)},onClick:({currentTarget:de})=>de.focus({preventScroll:!0}),onMouseMove(de){tk(de)||(F.current=!0,ne.current=!1,j&&Ae(de))},onPointerLeave(de){if(!Y.current||!W.current||de.pointerType==="touch")return;F.current=!0;const Le=de.relatedTarget;if(!(!j||a.current.includes(Le))&&ve.current&&(Z.current?.(),Z.current=null,X.current=-1,I(de),!b)){const ye=q.current,Ce=Kn(vt(ye));ye&&Ze(ye,Ce)&&ye.focus({preventScroll:!0})}}}),[Ae,Y,q,j,a,I,ve,b]),Me=x.useMemo(()=>b&&M&&Re&&{"aria-activedescendant":`${w}-${o}`},[b,M,Re,w,o]),De=x.useMemo(()=>({"aria-orientation":k==="both"?void 0:k,...$?{}:Me,onKeyDown(me){if(me.key==="Tab"&&me.shiftKey&&M&&!b){const de=qn(me.nativeEvent);if(de&&!Ze(q.current,de))return;pa(me),z.setOpen(!1,rt(zo,me.nativeEvent)),Gt(P)&&P.focus();return}Te(me)},onPointerMove(me){tk(me)||(W.current=!0)}}),[Me,Te,q,k,$,z,M,b,P]),Ue=x.useMemo(()=>{function me(ye){z.setOpen(!0,rt(bx,ye.nativeEvent,ye.currentTarget))}function de(ye){_==="auto"&&zb(ye.nativeEvent)&&(V.current=!b)}function Le(ye){V.current=_,_==="auto"&&Ob(ye.nativeEvent)&&(V.current=!0)}return{onKeyDown(ye){const Ce=z.select("open");W.current=!1;const Qe=ye.key.startsWith("Arrow"),Ge=$O(ye.key,Ie(),h),lt=Rd(ye.key,k),Tt=(g?Ge:lt)||ye.key==="Enter"||ye.key.trim()==="";if(b&&Ce)return Te(ye);if(!(!Ce&&!E&&Qe)){if(Tt){const _t=Rd(ye.key,Ie());Q.current=g&&_t?null:ye.key}if(g){Ge&&(pa(ye),Ce?(X.current=Oe(),I(ye)):me(ye));return}lt&&(oe.current!=null&&(X.current=oe.current),pa(ye),!Ce&&E?me(ye):Te(ye),Ce&&I(ye))}},onFocus(ye){z.select("open")&&!b&&(X.current=-1,I(ye))},onPointerDown:Le,onPointerEnter:Le,onMouseDown:de,onClick:de}},[Te,_,Oe,g,I,z,E,k,Ie,h,oe,b]),Xe=x.useMemo(()=>({...Me,...Ue}),[Me,Ue]);return x.useMemo(()=>c?{reference:Xe,floating:De,item:Ne,trigger:Ue}:{},[c,Xe,De,Ue,Ne])}function wC(e,t){const{listRef:a,elementsRef:o,activeIndex:l,onMatch:c,disabledIndices:d,onTyping:f,enabled:m=!0,resetMs:g=750,selectedIndex:h=null}=t,b="rootStore"in e?e.rootStore:e,_=b.useState("open"),j=Rn(),E=x.useRef(""),y=x.useRef(h??l??-1),k=x.useRef(null),N=He(R=>{function A(q){return o?.current[q]}function T(q){const G=A(q);return G&&!lp(G)||G?.matches(":disabled")?!1:d==null||!xf(ja,q,d)}function z(q,G,U=0){if(q.length===0)return-1;const V=(U%q.length+q.length)%q.length,X=G.toLowerCase();for(let Q=0;Q<q.length;Q+=1){const W=(V+Q)%q.length;if(!(!q[W]?.toLowerCase().startsWith(X)||!T(W)))return W}return-1}const M=a.current;if(E.current.length>0&&R.key===" "&&(pa(R),f?.(!0)),E.current.length>0&&E.current[0]!==" "&&z(M,E.current)===-1&&R.key!==" "&&f?.(!1),M==null||R.key.length!==1||R.ctrlKey||R.metaKey||R.altKey)return;_&&R.key!==" "&&(pa(R),f?.(!0));const L=E.current==="";L&&(y.current=h??l??-1),M.every((q,G)=>q&&T(G)?q[0]?.toLowerCase()!==q[1]?.toLowerCase():!0)&&E.current===R.key&&(E.current="",y.current=k.current),E.current+=R.key,j.start(g,()=>{E.current="",y.current=k.current,f?.(!1)});const D=((L?h??l??-1:y.current)??0)+1,$=z(M,E.current,D);$!==-1?(c?.($),k.current=$):R.key!==" "&&(E.current="",f?.(!1))}),w=He(R=>{const A=R.relatedTarget,T=b.select("domReferenceElement"),z=b.select("floatingElement");Ze(T,A)||Ze(z,A)||(j.clear(),E.current="",y.current=k.current,f?.(!1))});Pe(()=>{!_&&h!==null||(j.clear(),k.current=null,E.current!==""&&(E.current=""))},[_,h,j]);const S=x.useMemo(()=>({onKeyDown:N,onBlur:w}),[N,w]);return x.useMemo(()=>m?{reference:S,floating:S}:{},[m,S])}const nk=.1,qO=nk*nk,Vt=.5;function Td(e,t,a,o,l,c){return o>=t!=c>=t&&e<=(l-a)*(t-o)/(c-o)+a}function Ad(e,t,a,o,l,c,d,f,m,g){let h=!1;return Td(e,t,a,o,l,c)&&(h=!h),Td(e,t,l,c,d,f)&&(h=!h),Td(e,t,d,f,m,g)&&(h=!h),Td(e,t,m,g,a,o)&&(h=!h),h}function HO(e,t,a){return e>=a.x&&e<=a.x+a.width&&t>=a.y&&t<=a.y+a.height}function Md(e,t,a,o,l,c){const d=Math.min(a,l),f=Math.max(a,l),m=Math.min(o,c),g=Math.max(o,c);return e>=d&&e<=f&&t>=m&&t<=g}function SC(e={}){const{blockPointerEvents:t=!1}=e,a=new ta,o=({x:l,y:c,placement:d,elements:f,onClose:m,nodeId:g,tree:h})=>{const b=d?.split("-")[0];let _=!1,j=null,E=null,y=typeof performance<"u"?performance.now():0;function k(w,S){const R=performance.now(),A=R-y;if(j===null||E===null||A===0)return j=w,E=S,y=R,!1;const T=w-j,z=S-E,M=T*T+z*z,L=A*A*qO;return j=w,E=S,y=R,M<L}function N(){a.clear(),m()}return function(S){a.clear();const R=f.domReference,A=f.floating;if(!R||!A||b==null||l==null||c==null)return;const{clientX:T,clientY:z}=S,M=qn(S),L=S.type==="mouseleave",P=Ze(A,M),B=Ze(R,M);if(P&&(_=!0,!L))return;if(B&&(_=!1,!L)){_=!0;return}if(L&&bt(S.relatedTarget)&&Ze(A,S.relatedTarget))return;function D(){return!!(h&&Qr(h.nodesRef.current,g).length>0)}function $(){D()||N()}if(D())return;const q=R.getBoundingClientRect(),G=A.getBoundingClientRect(),U=l>G.right-G.width/2,V=c>G.bottom-G.height/2,X=G.width>q.width,Q=G.height>q.height,W=(X?q:G).left,I=(X?q:G).right,K=(Q?q:G).top,ee=(Q?q:G).bottom;if(b==="top"&&c>=q.bottom-1||b==="bottom"&&c<=q.top+1||b==="left"&&l>=q.right-1||b==="right"&&l<=q.left+1){$();return}let F=!1;switch(b){case"top":F=Md(T,z,W,q.top+1,I,G.bottom-1);break;case"bottom":F=Md(T,z,W,G.top+1,I,q.bottom-1);break;case"left":F=Md(T,z,G.right-1,ee,q.left+1,K);break;case"right":F=Md(T,z,q.right-1,ee,G.left+1,K);break}if(F)return;if(_&&!HO(T,z,q)){$();return}if(!L&&k(T,z)){$();return}let ne=!1;switch(b){case"top":{const Z=X?Vt/2:Vt*4,fe=X||U?l+Z:l-Z,Y=X?l-Z:U?l+Z:l-Z,oe=c+Vt+1,ve=U||X?G.bottom-Vt:G.top,le=U?X?G.bottom-Vt:G.top:G.bottom-Vt;ne=Ad(T,z,fe,oe,Y,oe,G.left,ve,G.right,le);break}case"bottom":{const Z=X?Vt/2:Vt*4,fe=X||U?l+Z:l-Z,Y=X?l-Z:U?l+Z:l-Z,oe=c-Vt,ve=U||X?G.top+Vt:G.bottom,le=U?X?G.top+Vt:G.bottom:G.top+Vt;ne=Ad(T,z,fe,oe,Y,oe,G.left,ve,G.right,le);break}case"left":{const Z=Q?Vt/2:Vt*4,fe=Q||V?c+Z:c-Z,Y=Q?c-Z:V?c+Z:c-Z,oe=l+Vt+1,ve=V||Q?G.right-Vt:G.left,le=V?Q?G.right-Vt:G.left:G.right-Vt;ne=Ad(T,z,ve,G.top,le,G.bottom,oe,fe,oe,Y);break}case"right":{const Z=Q?Vt/2:Vt*4,fe=Q||V?c+Z:c-Z,Y=Q?c-Z:V?c+Z:c-Z,oe=l-Vt,ve=V||Q?G.left+Vt:G.right,le=V?Q?G.left+Vt:G.right:G.left+Vt;ne=Ad(T,z,oe,fe,oe,Y,ve,G.top,le,G.bottom);break}}ne?_||a.start(40,$):$()}};return o.__options={...e,blockPointerEvents:t},o}const VO={...i_,disabled:e=>e.disabled,instantType:e=>e.instantType,isInstantPhase:e=>e.isInstantPhase,trackCursorAxis:e=>e.trackCursorAxis,disableHoverablePopup:e=>e.disableHoverablePopup,lastOpenChangeReason:e=>e.openChangeReason,closeOnClick:e=>e.closeOnClick,closeDelay:e=>e.closeDelay,adaptiveOrigin:e=>e.adaptiveOrigin};class FO extends nu{constructor(t,a,o){const l=new su;super(GO(t,l,a,o),YO(l),VO)}setOpen=(t,a)=>{AO(this,t,a,{extraState:{openChangeReason:a.reason}})};cancelPendingOpen(t){this.state.floatingRootContext.dispatchOpenChange(!1,rt(gi,t))}}function GO(e,t,a,o=!1){const l={...o_(),disabled:!1,instantType:void 0,isInstantPhase:!1,trackCursorAxis:"none",disableHoverablePopup:!1,openChangeReason:null,closeOnClick:!0,closeDelay:0,adaptiveOrigin:void 0,...e};return l.floatingRootContext=hC(t,a,o),l}function YO(e){return{popupRef:x.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerElements:e}}const KO=Rb(function(t){const{disabled:a=!1,defaultOpen:o=!1,open:l,disableHoverablePopup:c=!1,trackCursorAxis:d="none",actionsRef:f,onOpenChange:m,onOpenChangeComplete:g,handle:h,triggerId:b,defaultTriggerId:_=null,children:j}=t,E=pC((B,D)=>new FO({open:o,openProp:l,activeTriggerId:_,triggerIdProp:b},B,D));E.useControlledProp("openProp",l),E.useControlledProp("triggerIdProp",b),E.useContextCallback("onOpenChange",m),E.useContextCallback("onOpenChangeComplete",g);const y=E.useState("open"),k=!a&&y,N=E.useState("activeTriggerId"),w=E.useState("mounted"),S=E.useState("payload");E.useSyncedValues({trackCursorAxis:d,disableHoverablePopup:c,disabled:a}),s_(E,{closeOnActiveTriggerUnmount:!0});const{forceUnmount:R,transitionStatus:A}=a_(k,E),T=E.useState("isInstantPhase"),z=E.useState("instantType"),M=E.useState("lastOpenChangeReason"),L=x.useRef(null);Pe(()=>{y&&a&&E.setOpen(!1,rt(jS))},[y,a,E]),Pe(()=>{A==="ending"&&M===ka||A!=="ending"&&T?(z!=="delay"&&(L.current=z),E.set("instantType","delay")):L.current!==null&&(E.set("instantType",L.current),L.current=null)},[A,T,M,z,E]),Pe(()=>{k&&N==null&&E.set("payload",void 0)},[E,N,k]),x.useImperativeHandle(f,()=>({unmount:R,close:()=>E.setOpen(!1,rt(Bb))}),[R,E]);const P=k||w||!a&&d!=="none";return n.jsxs(hS.Provider,{value:E,children:[h&&n.jsx(t_,{handle:h,store:E}),P&&n.jsx(XO,{store:E,disabled:a,trackCursorAxis:d}),typeof j=="function"?j({payload:S}):j]})});function XO({store:e,disabled:t,trackCursorAxis:a}){const o=e.useState("floatingRootContext"),l=ip(o,{enabled:!t,referencePress:()=>e.select("closeOnClick")}),c=Az(o,{enabled:!t&&a!=="none",axis:a==="none"?void 0:a}),d=x.useMemo(()=>Ss(c.reference,l.reference),[c.reference,l.reference]);return r_(e,{activeTriggerProps:d,inactiveTriggerProps:d,popupProps:l.floating??sn}),null}let sk=(function(e){return e.startingStyle="data-starting-style",e.endingStyle="data-ending-style",e})({});const QO={"data-starting-style":""},WO={"data-ending-style":""},Ho={transitionStatus(e){return e==="starting"?QO:e==="ending"?WO:null}};(function(e){return e.open="data-open",e.closed="data-closed",e[e.startingStyle=sk.startingStyle]="startingStyle",e[e.endingStyle=sk.endingStyle]="endingStyle",e.anchorHidden="data-anchor-hidden",e.side="data-side",e.align="data-align",e})({});const ZO={"data-popup-open":""},JO={"data-popup-open":"","data-pressed":""},e6={"data-open":""},t6={"data-closed":""},n6={"data-anchor-hidden":""},CC={open(e){return e?ZO:null}},wx={open(e){return e?JO:null}},au={open(e){return e?e6:t6},anchorHidden(e){return e?n6:null}},d_={...au,...Ho};function ra(e){return Oo(e,"base-ui")}const NC=x.createContext(void 0);function s6(){return x.useContext(NC)}const ak=600,EC="data-base-ui-tooltip-trigger";function rk(e){if("composedPath"in e){const a=e.composedPath();for(let o=0;o<a.length;o+=1){const l=a[o];if(bt(l))return l}}const t=e.target;return bt(t)?t:null}function a6(e){let t=e;for(;t;){const a=t.closest(`[${EC}]`);if(a)return a;const o=t.getRootNode();t="host"in o&&bt(o.host)?o.host:null}return null}const r6=gS(function(t,a){const{render:o,className:l,style:c,handle:d,payload:f,disabled:m,delay:g,closeOnClick:h=!0,closeDelay:b,id:_,...j}=t,E=Jc(!0),k=bC(d)??E;if(!k)throw new Error(gn(82));const N=ra(_),w=k.useState("isTriggerActive",N),S=k.useState("isOpenedByTrigger",N),R=k.useState("floatingRootContext"),A=x.useRef(null),T=g??ak,z=b??0,{registerTrigger:M,isMountedByThisTrigger:L}=gC(N,A,k,{payload:f,closeOnClick:h,closeDelay:z}),P=s6(),{delayRef:B,isInstantPhase:D,hasProvider:$}=M4(R,{open:S}),q=u_(R);k.useSyncedValue("isInstantPhase",D);const G=k.useState("disabled"),U=m??G,V=mn(U),X=k.useState("trackCursorAxis"),Q=k.useState("disableHoverablePopup"),W=x.useRef(!1),I=Rn(),K=x.useRef(void 0);function ee(){return $?Kr(B.current,"open")===0?0:g??P??ak:T}function F(ke){const Re=A.current;if(!Re||!ke)return!1;const Ae=a6(ke);return Ae!==null&&Ae!==Re&&Ze(Re,Ae)}function ne(ke){const Re=F(ke);return W.current=Re,Re&&(q.openChangeTimeout.clear(),q.restTimeout.clear(),q.restTimeoutPending=!1,I.clear()),Re}const Z=jC(R,{enabled:!U,mouseOnly:!0,move:!1,handleClose:!Q&&X!=="both"?SC():null,restMs:ee,delay(){return b==null&&$?{close:Kr(B.current,"close")}:{close:z}},triggerElementRef:A,isActiveTrigger:w,isClosing:()=>k.select("transitionStatus")==="ending",shouldOpen(){return!W.current}}),fe=_C(R,{enabled:!U}).reference,Y=ke=>{const Re=W.current,Ae=rk(ke),Ie=ne(Ae),Oe=A.current,Te=Oe&&Ae&&Ze(Oe,Ae);if(Ie&&k.select("open")&&k.select("lastOpenChangeReason")===En){k.setOpen(!1,rt(En,ke));return}if(Re&&!Ie&&Te&&!V.current&&!k.select("open")&&Oe&&Hr(K.current)){const Ne=()=>{!W.current&&!V.current&&!k.select("open")&&k.setOpen(!0,rt(En,ke,Oe))},Me=ee();Me===0?(I.clear(),Ne()):I.start(Me,Ne)}},oe=k.useState("triggerProps",L);return Et("button",t,{state:{open:S},ref:[a,M,A],props:[Z,fe,L||X!=="none"?oe:void 0,{onMouseOver(ke){Y(ke.nativeEvent)},onFocus(ke){F(rk(ke.nativeEvent))&&ke.preventBaseUIHandler()},onMouseLeave(){W.current=!1,I.clear(),K.current=void 0},onPointerEnter(ke){K.current=ke.pointerType},onPointerDown(ke){K.current=ke.pointerType,k.set("closeOnClick",h),h&&!k.select("open")&&k.cancelPendingOpen(ke.nativeEvent)},onClick(ke){h&&!k.select("open")&&k.cancelPendingOpen(ke.nativeEvent)},id:N,"data-trigger-disabled":U?"":void 0,[EC]:U?void 0:""},j],stateAttributesMapping:CC})}),RC=x.createContext(void 0);function o6(){const e=x.useContext(RC);if(e===void 0)throw new Error(gn(70));return e}const l6=x.forwardRef(function(t,a){const{children:o,container:l,className:c,render:d,style:f,...m}=t,{node:g,subtree:h}=QS({container:l,ref:a,componentProps:t,elementProps:m});return!h&&!g?null:n.jsxs(x.Fragment,{children:[h,g&&Gs.createPortal(o,g)]})}),i6=x.forwardRef(function(t,a){const{keepMounted:o=!1,...l}=t;return Jc().useState("mounted")||o?n.jsx(RC.Provider,{value:o,children:n.jsx(l6,{ref:a,...l})}):null}),TC=x.createContext(void 0);function AC(){const e=x.useContext(TC);if(e===void 0)throw new Error(gn(71));return e}const c6=x.createContext(void 0);function pp(){return x.useContext(c6)?.direction??"ltr"}const u6=e=>({name:"arrow",options:e,async fn(t){const{x:a,y:o,placement:l,rects:c,platform:d,elements:f,middlewareData:m}=t,{element:g,padding:h=0,offsetParent:b="real"}=Xr(e,t)||{};if(g==null)return{};const _=RS(h),j={x:a,y:o},E=Vb(l),y=Hb(E),k=await d.getDimensions(g),N=E==="y",w=N?"top":"left",S=N?"bottom":"right",R=N?"clientHeight":"clientWidth",A=c.reference[y]+c.reference[E]-j[E]-c.floating[y],T=j[E]-c.reference[E],z=b==="real"?await d.getOffsetParent?.(g):f.floating;let M=f.floating[R]||c.floating[y];(!M||!await d.isElement?.(z))&&(M=f.floating[R]||c.floating[y]);const L=A/2-T/2,P=M/2-k[y]/2-1,B=Math.min(_[w],P),D=Math.min(_[S],P),$=B,q=M-k[y]-D,G=M/2-k[y]/2+L,U=ES($,G,q),V=!m.arrow&&Jr(l)!=null&&G!==U&&c.reference[y]/2-(G<$?B:D)-k[y]/2<0,X=V?G<$?G-$:G-q:0;return{[E]:j[E]+X,data:{[E]:U,centerOffset:G-U-X,...V&&{alignmentOffset:X}},reset:V}}}),d6=(e,t)=>({...u6(e),options:[e,t]}),f6={name:"hide",async fn(e){const{width:t,height:a,x:o,y:l}=e.rects.reference,c=t===0&&a===0&&o===0&&l===0,d=await e.platform.detectOverflow(e,{elementContext:"reference"});return{data:{referenceHidden:d.top-a>=0||d.right-t>=0||d.bottom-a>=0||d.left-t>=0||c}}}},p6={sideX:"left",sideY:"top"},ok="--available-width",lk="--available-height";function MC(e,t,a){const o=e==="inline-start"||e==="inline-end";return{top:"top",right:o?a?"inline-start":"inline-end":"right",bottom:"bottom",left:o?a?"inline-end":"inline-start":"left"}[t]}function ik(e,t,a){const{rects:o,placement:l}=e;return{side:MC(t,Vs(l),a),align:Jr(l)||"center",anchor:{width:o.reference.width,height:o.reference.height},positioner:{width:o.floating.width,height:o.floating.height}}}function f_(e){return m6(e,PO)}function m6(e,t){const{anchor:a,positionMethod:o="absolute",side:l="bottom",sideOffset:c=0,align:d="center",alignOffset:f=0,collisionBoundary:m,collisionPadding:g=5,sticky:h=!1,arrowPadding:b=5,disableAnchorTracking:_=!1,inline:j,keepMounted:E=!1,floatingRootContext:y,mounted:k,collisionAvoidance:N,shift:w,nodeId:S,adaptiveOrigin:R,lazyFlip:A=!1,externalTree:T}=e,[z,M]=x.useState(null);!k&&z!==null&&M(null);const L=N.side||"flip",P=N.align||"flip",B=N.fallbackAxisSide||"end",D=w?.crossAxis??!1,$=w?.rootBoundary,q=typeof a=="function"?a:void 0,G=He(q),U=q?G:a,V=mn(a),X=mn(k),W=pp()==="rtl",I=z||{top:"top",right:"right",bottom:"bottom",left:"left","inline-end":W?"left":"right","inline-start":W?"right":"left"}[l],K=d==="center"?I:`${I}-${d}`;let ee=g;typeof ee=="number"?ee={top:ee,right:ee,bottom:ee,left:ee}:ee&&(ee={top:ee.top||0,right:ee.right||0,bottom:ee.bottom||0,left:ee.left||0});const F=1,ne=l==="bottom"?F:0,Z=l==="top"?F:0,fe=l==="right"?F:0,Y=l==="left"?F:0,oe={boundary:m==="clipping-ancestors"?"clippingAncestors":m,padding:ee},ve=x.useRef(null),le=mn(c),xe=mn(f),ke=typeof c!="function"?c:0,Re=typeof f!="function"?f:0,Ae=[];j&&Ae.push(j),Ae.push(pO(ot=>{const Pt=ik(ot,l,W),on=typeof le.current=="function"?le.current(Pt):le.current,Yt=typeof xe.current=="function"?xe.current(Pt):xe.current;return{mainAxis:on,crossAxis:Yt,alignmentAxis:Yt}},[ke,Re,W,l]));const Ie=P==="none"&&L!=="shift",Oe=!Ie&&(h||D||L==="shift"),Te=L==="none"?null:hO({...oe,padding:{top:ee.top+F+ne,right:ee.right+F+Y,bottom:ee.bottom+F+Z,left:ee.left+F+fe},mainAxis:!D&&L==="flip",crossAxis:P==="flip"?"alignment":!1,fallbackAxisSideDirection:B}),Ne=Ie?null:mO({...oe,rootBoundary:$,mainAxis:P!=="none",crossAxis:Oe,limiter:h||D?void 0:gO(ot=>{if(!ve.current)return{};const{width:Pt,height:on}=ve.current.getBoundingClientRect(),Yt=Hs(Vs(ot.placement)),Fn=Yt==="y"?Pt:on,Tn=Yt==="y"?ee.left+ee.right:ee.top+ee.bottom;return{offset:Fn/2+Tn/2}})},[oe,h,D,$,ee,P]);L==="shift"||P==="shift"||d==="center"?Ae.push(Ne,Te):Ae.push(Te,Ne),Ae.push(xO({...oe,apply({elements:{floating:ot},availableWidth:Pt,availableHeight:on,rects:Yt}){if(!X.current)return;const Fn=ot.style;Fn.setProperty(ok,`${Pt}px`),Fn.setProperty(lk,`${on}px`);const Tn=Jt(ot).devicePixelRatio||1,{x:as,y:dn,width:hs,height:Rs}=Yt.reference,oa=(Math.round((as+hs)*Tn)-Math.round(as*Tn))/Tn,ht=(Math.round((dn+Rs)*Tn)-Math.round(dn*Tn))/Tn;Fn.setProperty("--anchor-width",`${oa}px`),Fn.setProperty("--anchor-height",`${ht}px`)}}),d6(ot=>({element:ve.current||vt(ot.elements.floating).createElement("div"),padding:b,offsetParent:"floating"}),[b]),{name:"transformOrigin",fn(ot){const{elements:Pt,middlewareData:on,placement:Yt,rects:Fn,y:Tn}=ot,as=Vs(Yt),dn=Hs(as),hs=ve.current,Rs=on.arrow?.x||0,oa=on.arrow?.y||0,ht=hs?.clientWidth||0,$t=hs?.clientHeight||0,Ln=Rs+ht/2,rs=oa+$t/2,xs=Math.abs(on.shift?.y||0),An=Fn.reference.height/2,Wt=typeof c=="function"?c(ik(ot,l,W)):c,vn=xs>Wt,la={top:`${Ln}px calc(100% + ${Wt}px)`,bottom:`${Ln}px ${-Wt}px`,left:`calc(100% + ${Wt}px) ${rs}px`,right:`${-Wt}px ${rs}px`}[as],dr=`${Ln}px ${Fn.reference.y+An-Tn}px`;return Pt.floating.style.setProperty("--transform-origin",Oe&&dn==="y"&&vn?dr:la),{}}},f6,R),Pe(()=>{!k&&y&&y.update({referenceElement:null,floatingElement:null,domReferenceElement:null,positionReference:null})},[k,y]);const Me=x.useMemo(()=>({elementResize:!_&&typeof ResizeObserver<"u",layoutShift:!_&&typeof IntersectionObserver<"u"}),[_]),{refs:De,elements:Ue,x:Xe,y:me,middlewareData:de,update:Le,placement:ye,context:Ce,isPositioned:Qe,floatingStyles:Ge}=t({rootContext:y,open:E?k:void 0,placement:K,middleware:Ae,strategy:o,whileElementsMounted:E?void 0:(...ot)=>Kj(...ot,Me),nodeId:S,externalTree:T}),{sideX:lt,sideY:Tt}=de.adaptiveOrigin||p6,_t=Qe?o:"fixed",Ct=x.useMemo(()=>{let ot;return Qe?R?ot={position:_t,[lt]:Xe,[Tt]:me}:ot={...Ge,position:_t}:ot={position:_t,top:0,left:0},ot[ok]="100vw",ot[lk]="100vh",Qe||(ot.opacity=0),ot},[R,_t,lt,Xe,Tt,me,Ge,Qe]),je=x.useRef(null);Pe(()=>{if(!k)return;const ot=V.current,Pt=typeof ot=="function"?ot():ot,Yt=(ck(Pt)?Pt.current:Pt)||null||null;Yt!==je.current&&(De.setPositionReference(Yt),je.current=Yt)},[k,De,U,V]),x.useEffect(()=>{if(!k)return;const ot=V.current;typeof ot!="function"&&ck(ot)&&ot.current!==je.current&&(De.setPositionReference(ot.current),je.current=ot.current)},[k,De,U,V]),x.useEffect(()=>{if(E&&k&&Ue.reference&&Ue.floating)return Kj(Ue.reference,Ue.floating,Le,Me)},[E,k,Ue,Le,Me]);const ze=Vs(ye),Ye=MC(l,ze,W),We=Jr(ye)||"center",dt=!!de.hide?.referenceHidden;Pe(()=>{A&&k&&Qe&&ze!==I&&M(ze)},[A,k,Qe,ze,I]);const Rt=x.useMemo(()=>({position:"absolute",top:de.arrow?.y,left:de.arrow?.x}),[de.arrow]),Qt=de.arrow?.centerOffset!==0;return x.useMemo(()=>({positionerStyles:Ct,arrowStyles:Rt,arrowRef:ve,arrowUncentered:Qt,side:Ye,align:We,physicalSide:ze,anchorHidden:dt,refs:De,context:Ce,isPositioned:Qe,update:Le}),[Ct,Rt,ve,Qt,Ye,We,ze,dt,De,Ce,Qe,Le])}function ck(e){return e!=null&&"current"in e}function mp(e){return e==="starting"?jz:sn}function p_(e,t,{styles:a,transitionStatus:o,props:l,refs:c,hidden:d,inert:f=!1}){const m={...a};return f&&(m.pointerEvents="none"),Et("div",e,{state:t,ref:c,props:[{role:"presentation",hidden:d,style:m},mp(o),l],stateAttributesMapping:au})}const g6=x.forwardRef(function(t,a){const{render:o,className:l,anchor:c,positionMethod:d="absolute",side:f="top",align:m="center",sideOffset:g=0,alignOffset:h=0,collisionBoundary:b="clipping-ancestors",collisionPadding:_=5,arrowPadding:j=5,sticky:E=!1,disableAnchorTracking:y=!1,collisionAvoidance:k=YS,style:N,...w}=t,S=Jc(),R=o6(),A=S.useState("open"),T=S.useState("mounted"),z=S.useState("trackCursorAxis"),M=S.useState("disableHoverablePopup"),L=S.useState("floatingRootContext"),P=S.useState("instantType"),B=S.useState("transitionStatus"),D=S.useState("adaptiveOrigin"),$=f_({anchor:c,positionMethod:d,floatingRootContext:L,mounted:T,side:f,sideOffset:g,align:m,alignOffset:h,collisionBoundary:b,collisionPadding:_,sticky:E,arrowPadding:j,disableAnchorTracking:y,keepMounted:R,collisionAvoidance:k,adaptiveOrigin:D}),q=x.useMemo(()=>({open:A,side:$.side,align:$.align,anchorHidden:$.anchorHidden,instant:z!=="none"?"tracking-cursor":P}),[A,$.side,$.align,$.anchorHidden,z,P]),G=p_(t,q,{styles:$.positionerStyles,transitionStatus:B,props:w,refs:[a,S.useStateSetter("positionerElement")],hidden:!T,inert:!A||z==="both"||M});return n.jsx(TC.Provider,{value:$,children:G})}),h6=x.forwardRef(function(t,a){const{render:o,className:l,style:c,...d}=t,f=Jc(),{side:m,align:g}=AC(),h=f.useState("open"),b=f.useState("instantType"),_=f.useState("transitionStatus"),j=f.useState("popupProps"),E=f.useState("floatingRootContext"),y=f.useState("disabled"),k=f.useState("closeDelay");Ca({open:h,ref:f.context.popupRef,onComplete(){h&&f.context.onOpenChangeComplete?.(!0)}}),yC(E,{enabled:!y,closeDelay:k});const N=f.useStateSetter("popupElement");return Et("div",t,{state:{open:h,side:m,align:g,instant:b,transitionStatus:_},ref:[a,f.context.popupRef,N],props:[dp,j,mp(_),d],stateAttributesMapping:d_})}),x6=x.forwardRef(function(t,a){const{render:o,className:l,style:c,...d}=t,f=Jc(),{arrowRef:m,side:g,align:h,arrowUncentered:b,arrowStyles:_}=AC(),j=f.useState("open"),E=f.useState("instantType");return Et("div",t,{state:{open:j,side:g,align:h,uncentered:b,instant:E},ref:[a,m],props:[{style:_,"aria-hidden":!0},d],stateAttributesMapping:au})}),b6=function(t){const{delay:a,closeDelay:o,timeout:l=400}=t,c=x.useMemo(()=>({open:a,close:o}),[a,o]);return n.jsx(NC.Provider,{value:a,children:n.jsx(A4,{delay:c,timeoutMs:l,children:t.children})})};function gp(e){return Yb(19)?e:e?"true":void 0}function _6(e){const[t,a]=x.useState({current:e,previous:null});return Object.is(e,t.current)||a({current:e,previous:t.current}),t.previous}function St(...e){return mS(Pc(e))}function v6({delay:e=0,...t}){return n.jsx(b6,{"data-slot":"tooltip-provider",delay:e,...t})}function m_({...e}){return n.jsx(KO,{"data-slot":"tooltip",...e})}function g_({...e}){return n.jsx(r6,{"data-slot":"tooltip-trigger",...e})}function h_({className:e,side:t="top",sideOffset:a=4,align:o="center",alignOffset:l=0,children:c,...d}){return n.jsx(i6,{children:n.jsx(g6,{align:o,alignOffset:l,side:t,sideOffset:a,className:"isolate z-50",children:n.jsxs(h6,{"data-slot":"tooltip-content",className:St("z-50 inline-flex w-fit max-w-xs origin-(--transform-origin) items-center gap-1.5 rounded-md bg-foreground px-3 py-1.5 text-xs text-background has-data-[slot=kbd]:pr-1.5 data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 **:data-[slot=kbd]:relative **:data-[slot=kbd]:isolate **:data-[slot=kbd]:z-50 **:data-[slot=kbd]:rounded-sm data-[state=delayed-open]:animate-in data-[state=delayed-open]:fade-in-0 data-[state=delayed-open]:zoom-in-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",e),...d,children:[c,n.jsx(x6,{className:"z-50 size-2.5 translate-y-[calc(-50%-2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground data-[side=bottom]:top-1 data-[side=inline-end]:top-1/2! data-[side=inline-end]:-left-1 data-[side=inline-end]:-translate-y-1/2 data-[side=inline-start]:top-1/2! data-[side=inline-start]:-right-1 data-[side=inline-start]:-translate-y-1/2 data-[side=left]:top-1/2! data-[side=left]:-right-1 data-[side=left]:-translate-y-1/2 data-[side=right]:top-1/2! data-[side=right]:-left-1 data-[side=right]:-translate-y-1/2 data-[side=top]:-bottom-2.5"})]})})})}function Ml({label:e,active:t,onClick:a,isAdd:o,isSettings:l,isDefault:c,icon:d,title:f,testId:m}){const g=e.trim()||"·",{initials:h,subLabel:b}=zC(g),_=o||l?"indigo":OC(g),j=b&&!o&&!l&&!c;return n.jsxs(m_,{children:[n.jsx(g_,{render:n.jsxs("button",{type:"button",onClick:a,"data-testid":m,className:"group relative flex w-full cursor-pointer flex-col items-center gap-1",children:[n.jsx("span",{className:ge("flex size-10 items-center justify-center rounded-xl text-sm font-bold transition-all",t&&"ring-2 ring-foreground ring-offset-2 ring-offset-card",o&&"border border-dashed border-muted-fg/50 bg-transparent text-muted-fg hover:bg-accent/60 hover:text-foreground",l&&"bg-muted text-muted-fg hover:bg-accent hover:text-foreground",c&&"overflow-hidden bg-muted",!o&&!l&&!c&&t&&w6(_),!o&&!l&&!c&&!t&&k6(_)),children:d??h}),j&&n.jsx("span",{className:"block max-w-[3.6rem] truncate text-[9px] leading-tight text-muted-fg group-hover:text-foreground",children:b})]})}),n.jsx(h_,{side:"right",children:f||e})]})}function zC(e){const t=e.trim().replace(/[_\-.]+/g," ").replace(/\s+/g," ");if(!t)return{initials:"·",subLabel:null};const a=t.split(" ");if(a.length>=2)return{initials:(a[0][0]+a[1][0]).toUpperCase(),subLabel:y6(t)};const o=a[0];return o.length<=4?{initials:o[0].toUpperCase(),subLabel:o}:{initials:o[0].toUpperCase(),subLabel:o.slice(0,4)+"…"}}function y6(e){return e.length>6?e.slice(0,5)+"…":e}function OC(e){let t=0;for(let a=0;a<e.length;a++)t=t*31+e.charCodeAt(a)|0;return _j[Math.abs(t)%_j.length]}const DC={sky:"bg-sky-500/15 text-sky-300 hover:bg-sky-500/25",violet:"bg-violet-500/15 text-violet-300 hover:bg-violet-500/25",emerald:"bg-emerald-500/15 text-emerald-300 hover:bg-emerald-500/25",amber:"bg-amber-500/15 text-amber-300 hover:bg-amber-500/25",rose:"bg-rose-500/15 text-rose-300 hover:bg-rose-500/25",indigo:"bg-indigo-500/15 text-indigo-300 hover:bg-indigo-500/25",teal:"bg-teal-500/15 text-teal-300 hover:bg-teal-500/25",fuchsia:"bg-fuchsia-500/15 text-fuchsia-300 hover:bg-fuchsia-500/25"},j6={sky:"bg-sky-500/30 text-sky-100",violet:"bg-violet-500/30 text-violet-100",emerald:"bg-emerald-500/30 text-emerald-100",amber:"bg-amber-500/30 text-amber-100",rose:"bg-rose-500/30 text-rose-100",indigo:"bg-indigo-500/30 text-indigo-100",teal:"bg-teal-500/30 text-teal-100",fuchsia:"bg-fuchsia-500/30 text-fuchsia-100"};function k6(e){return DC[e]}function w6(e){return j6[e]}function S6(e){const{initials:t}=zC(e);return{initials:t,idleClass:DC[OC(e)]}}function qe({content:e,side:t="top",children:a}){return e?n.jsxs(m_,{children:[n.jsx(g_,{render:a}),n.jsx(h_,{side:t,children:e})]}):a}const PC=x.createContext(void 0);function x_(e){const t=x.useContext(PC);if(t===void 0&&!e)throw new Error(gn(33));return t}const LC=x.createContext(void 0);function Vo(e){const t=x.useContext(LC);if(t===void 0&&!e)throw new Error(gn(36));return t}const C6=x.createContext(void 0);function b_(e=!0){const t=x.useContext(C6);if(t===void 0&&!e)throw new Error(gn(25));return t}function ni({controlled:e,default:t,name:a,state:o="value"}){const{current:l}=x.useRef(e!==void 0),[c,d]=x.useState(t),f=l?e:c,m=x.useCallback(g=>{l||d(g)},[]);return[f,m]}const IC=x.createContext(void 0);function hp(e=!1){const t=x.useContext(IC);if(t===void 0&&!e)throw new Error(gn(16));return t}function N6(e){const{focusableWhenDisabled:t,disabled:a,composite:o=!1,tabIndex:l=0,isNativeButton:c}=e,d=o&&t!==!1,f=o&&t===!1;return{props:x.useMemo(()=>{const g={onKeyDown(h){a&&t&&h.key!=="Tab"&&h.preventDefault()}};return o||(g.tabIndex=l,!c&&a&&(g.tabIndex=t?l:-1)),(c&&(t||d)||!c&&a)&&(g["aria-disabled"]=a),c&&(!t||f)&&(g.disabled=a),g},[o,a,t,d,f,c,l])}}function Ac(e,t,{detail:a=0}={}){e.dispatchEvent(new(Jt(e)).PointerEvent("click",{bubbles:!0,cancelable:!0,composed:!0,detail:a,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,altKey:t.altKey,metaKey:t.metaKey}))}function no(e={}){const{disabled:t=!1,focusableWhenDisabled:a,tabIndex:o=0,native:l=!0,composite:c}=e,d=x.useRef(null),f=hp(!0),m=c??f!==void 0,{props:g}=N6({focusableWhenDisabled:a,disabled:t,composite:m,tabIndex:o,isNativeButton:l}),h=x.useCallback(()=>{const j=d.current;uh(j)&&m&&t&&g.disabled===void 0&&j.disabled&&(j.disabled=!1)},[t,g.disabled,m]);Pe(h,[h]);const b=x.useCallback((j={})=>{const{onClick:E,onMouseDown:y,onKeyUp:k,onKeyDown:N,onPointerDown:w,...S}=j;return Ss({onClick(R){if(t){R.preventDefault();return}E?.(R)},onMouseDown(R){t||y?.(R)},onKeyDown(R){if(t||(_f(R),N?.(R),R.baseUIHandlerPrevented))return;const A=R.target===R.currentTarget,T=R.currentTarget,z=uh(T),M=!l&&E6(T),L=A&&(l?z:!M),P=R.key==="Enter",B=R.key===" ",D=T.getAttribute("role"),$=D?.startsWith("menuitem")||D==="option"||D==="gridcell";if(A&&m&&B){if(R.defaultPrevented&&$)return;R.preventDefault(),(!l||z)&&(R.preventBaseUIHandler(),Ac(T,R));return}if(!L||l||!B&&!P){A&&M&&B&&R.preventDefault();return}R.defaultPrevented||(R.preventDefault(),P&&(R.preventBaseUIHandler(),Ac(T,R)))},onKeyUp(R){if(!t){if(_f(R),k?.(R),R.target===R.currentTarget&&l&&m&&uh(R.currentTarget)&&R.key===" "){R.preventDefault();return}R.baseUIHandlerPrevented||R.target===R.currentTarget&&!l&&!m&&!R.defaultPrevented&&R.key===" "&&(R.preventBaseUIHandler(),Ac(R.currentTarget,R))}},onPointerDown(R){if(t){R.preventDefault();return}w?.(R)}},l?{type:"button"}:{role:"button"},g,S)},[t,g,m,l]),_=He(j=>{d.current=j,h()});return{getButtonProps:b,buttonRef:_}}function uh(e){return Gt(e)&&e.tagName==="BUTTON"}function E6(e){return Gt(e)&&e.tagName==="A"&&!!e.href}function R6(e){const{closeOnClick:t,highlighted:a,id:o,nodeId:l,store:c,typingRef:d,itemRef:f,itemMetadata:m}=e,{events:g}=c.useState("floatingTreeRoot"),h=c.useState("open"),b=b_(!0),_=b!==void 0;return x.useMemo(()=>({id:o,role:"menuitem",tabIndex:h&&a?0:-1,onKeyDown(j){j.key===" "&&d?.current&&j.preventDefault()},onMouseMove(j){l&&g.emit("itemhover",{nodeId:l,target:j.currentTarget})},onClick(j){t&&g.emit("close",{domEvent:j,reason:Fl})},onMouseUp(j){if(b){const E=b.initialCursorPointRef.current;if(b.initialCursorPointRef.current=null,_&&E&&Math.abs(j.clientX-E.x)<=1&&Math.abs(j.clientY-E.y)<=1||_&&!Ab&&j.button===2)return}f.current&&c.context.allowMouseUpTriggerRef.current&&(!_||j.button===2)&&m.type==="regular-item"&&Ac(f.current,j,{detail:1})}}),[t,a,o,g,l,h,c,d,f,b,_,m])}const BC={type:"regular-item"};function $C(e){const{closeOnClick:t,disabled:a,highlighted:o,id:l,store:c,typingRef:d=c.context.typingRef,nativeButton:f,itemMetadata:m,nodeId:g}=e,h=x.useRef(null),{getButtonProps:b,buttonRef:_}=no({disabled:a,focusableWhenDisabled:!0,native:f,composite:!0}),j=R6({closeOnClick:t,highlighted:o,id:l,nodeId:g,store:c,typingRef:d,itemRef:h,itemMetadata:m}),E=x.useCallback(k=>Ss(j,{onMouseEnter(){m.type==="submenu-trigger"&&m.setActive()}},k,b),[j,b,m]),y=rr(h,_);return x.useMemo(()=>({getItemProps:E,itemRef:y}),[E,y])}const UC=x.createContext({register:()=>{},unregister:()=>{},subscribeMapChange:()=>()=>{},nextIndexRef:{current:0}});function T6(){return x.useContext(UC)}function ru(e={}){const{guess:t,label:a,metadata:o,textRef:l,index:c}=e,{register:d,unregister:f,subscribeMapChange:m,nextIndexRef:g}=T6(),h=x.useRef(-1),[b,_]=x.useState(c==null&&t?()=>{if(h.current===-1){const k=g.current;g.current+=1,h.current=k}return h.current}:-1),j=c??b,E=x.useRef(null),y=x.useCallback(k=>{const N=E.current;N&&f(N),E.current=k,k&&d(k,{metadata:o??null,index:c??null,label:a,textRef:l})},[c,d,f,o,a,l]);return Pe(()=>{if(c==null)return m(k=>{const N=E.current?k.get(E.current)?.index:null;N!=null&&_(N)})},[c,m]),{ref:y,index:j}}let uk=(function(e){return e.checked="data-checked",e.unchecked="data-unchecked",e.disabled="data-disabled",e.highlighted="data-highlighted",e})({});const qC={checked(e){return e?{[uk.checked]:""}:{[uk.unchecked]:""}},...Ho},A6=x.createContext(void 0),M6=x.forwardRef(function(t,a){const{render:o,className:l,id:c,label:d,nativeButton:f=!1,disabled:m=!1,closeOnClick:g=!0,style:h,...b}=t,_=ru({guess:!0,label:d}),j=x_(!0),E=ra(c),{store:y}=Vo(),k=y.useState("disabled"),N=m||k,w=y.useState("isActive",_.index),S=y.useState("itemProps"),{getItemProps:R,itemRef:A}=$C({closeOnClick:g,disabled:N,highlighted:w,id:E,store:y,nativeButton:f,nodeId:j?.context.nodeId,itemMetadata:BC});return Et("div",t,{state:{disabled:N,highlighted:w},props:[S,b,R],ref:[A,a,_.ref]})}),z6=x.createContext(void 0);function HC(e){return x.useContext(z6)}const Sx="ArrowUp",Cx="ArrowDown",Nx="ArrowLeft",Ex="ArrowRight",Rx="Home",Tx="End",xp=new Set([Sx,Cx,Nx,Ex,Rx,Tx]),O6="Shift",D6=[O6,"Control","Alt","Meta"];function P6(e){return Gt(e)&&e.tagName==="INPUT"}function dk(e){return!!(P6(e)&&e.selectionStart!=null||Gt(e)&&e.tagName==="TEXTAREA")}function fk(e,t,a,o){if(!e||!t||!t.scrollTo)return;let l=e.scrollLeft,c=e.scrollTop;const d=e.clientWidth<e.scrollWidth,f=e.clientHeight<e.scrollHeight;if(d&&o!=="vertical"){const m=pk(e,t,"left"),g=zd(e),h=zd(t);a==="ltr"&&(m+t.offsetWidth+h.scrollMarginRight>e.scrollLeft+e.clientWidth-g.scrollPaddingRight?l=m+t.offsetWidth+h.scrollMarginRight-e.clientWidth+g.scrollPaddingRight:m-h.scrollMarginLeft<e.scrollLeft+g.scrollPaddingLeft&&(l=m-h.scrollMarginLeft-g.scrollPaddingLeft)),a==="rtl"&&(m-h.scrollMarginLeft<e.scrollLeft+g.scrollPaddingLeft?l=m-h.scrollMarginLeft-g.scrollPaddingLeft:m+t.offsetWidth+h.scrollMarginRight>e.scrollLeft+e.clientWidth-g.scrollPaddingRight&&(l=m+t.offsetWidth+h.scrollMarginRight-e.clientWidth+g.scrollPaddingRight))}if(f&&o!=="horizontal"){const m=pk(e,t,"top"),g=zd(e),h=zd(t);m-h.scrollMarginTop<e.scrollTop+g.scrollPaddingTop?c=m-h.scrollMarginTop-g.scrollPaddingTop:m+t.offsetHeight+h.scrollMarginBottom>e.scrollTop+e.clientHeight-g.scrollPaddingBottom&&(c=m+t.offsetHeight+h.scrollMarginBottom-e.clientHeight+g.scrollPaddingBottom)}e.scrollTo({left:l,top:c,behavior:"auto"})}function pk(e,t,a){const o=a==="left"?"offsetLeft":"offsetTop";let l=0;for(;t.offsetParent&&(l+=t[o],t.offsetParent!==e);)t=t.offsetParent;return l}function zd(e){const t=getComputedStyle(e);return{scrollMarginTop:parseFloat(t.scrollMarginTop)||0,scrollMarginRight:parseFloat(t.scrollMarginRight)||0,scrollMarginBottom:parseFloat(t.scrollMarginBottom)||0,scrollMarginLeft:parseFloat(t.scrollMarginLeft)||0,scrollPaddingTop:parseFloat(t.scrollPaddingTop)||0,scrollPaddingRight:parseFloat(t.scrollPaddingRight)||0,scrollPaddingBottom:parseFloat(t.scrollPaddingBottom)||0,scrollPaddingLeft:parseFloat(t.scrollPaddingLeft)||0}}const L6=x.forwardRef(function(t,a){const{render:o,className:l,style:c,finalFocus:d,...f}=t,{store:m}=Vo(),{side:g,align:h}=x_(),b=HC()!=null,_=m.useState("open"),j=m.useState("transitionStatus"),E=m.useState("popupProps"),y=m.useState("mounted"),k=m.useState("instantType"),N=m.useState("activeTriggerElement"),w=m.useState("parent"),S=m.useState("lastOpenChangeReason"),R=m.useState("rootId"),A=m.useState("floatingRootContext"),T=m.useState("floatingTreeRoot"),z=m.useState("closeDelay"),M=m.useState("hoverEnabled"),L=m.useState("disabled"),P=m.useState("openMethod"),B=w.type==="context-menu";Ca({open:_,ref:m.context.popupRef,onComplete(){_&&m.context.onOpenChangeComplete?.(!0)}}),x.useEffect(()=>{function U(V){m.setOpen(!1,rt(V.reason,V.domEvent))}return T.events.on("close",U),()=>{T.events.off("close",U)}},[T.events,m]),yC(A,{enabled:M&&!L&&!B&&w.type!=="menubar",closeDelay:z});const D=m.useStateSetter("popupElement"),$={transitionStatus:j,side:g,align:h,open:_,nested:w.type==="menu",instant:k},q=Et("div",t,{state:$,ref:[a,m.context.popupRef,D],stateAttributesMapping:d_,props:[E,{onKeyDown(U){b&&xp.has(U.key)&&U.stopPropagation()}},mp(j),f,{"data-rootownerid":R}]});let G=w.type===void 0||B;return(N||w.type==="menubar"&&S!==rp)&&(G=!0),n.jsx(Jb,{context:A,openInteractionType:P,modal:B,disabled:!y,returnFocus:d===void 0?G:d,initialFocus:w.type!=="menu",restoreFocus:!0,externalTree:w.type!=="menubar"?T:void 0,previousFocusableElement:N,nextFocusableElement:w.type===void 0?m.context.triggerFocusTargetRef:void 0,beforeContentFocusGuardRef:w.type===void 0?m.context.beforeContentFocusGuardRef:void 0,children:q})}),VC=x.createContext(void 0);function I6(){const e=x.useContext(VC);if(e===void 0)throw new Error(gn(32));return e}const B6=x.forwardRef(function(t,a){const{keepMounted:o=!1,...l}=t,{store:c}=Vo();return c.useState("mounted")||o?n.jsx(VC.Provider,{value:o,children:n.jsx(Qb,{ref:a,...l})}):null});function bp(e){const{children:t,elementsRef:a,labelsRef:o,onMapChange:l}=e,c=He(l),[,d]=x.useState(!1),f=Hn(U6).current,m=Hn($6).current,g=x.useRef(0),h=x.useRef(!0),b=x.useRef([]),_=x.useRef(null),j=He(()=>{h.current||(h.current=!0,d(A=>!A))}),E=He((A,T)=>{m.set(A,T),j()}),y=He(A=>{m.delete(A),j()}),k=He(A=>{const T=new Map;return a.current.length=0,o&&(o.current.length=0),A.forEach(z=>{T.set(z.element,{...z.registration.metadata??{},index:z.index}),a.current[z.index]=z.element,o&&(o.current[z.index]=z.registration.label!==void 0?z.registration.label:z.registration.textRef?.current?.textContent??z.element.textContent)}),g.current=a.current.length,T});function N(A){if(_.current?.disconnect(),_.current=null,typeof MutationObserver!="function"||A.length<2)return;const T=new MutationObserver(M=>{if(!V6(M))return;let L=null;for(const P of A)if(P.isConnected){if(L&&FC(L,P)>0){T.disconnect(),j();return}L=P}});_.current=T;const z=new Set;for(let M=1;M<A.length;M+=1){const L=H6(A[M-1],A[M]);L&&z.add(L)}z.forEach(M=>T.observe(M,{childList:!0}))}const w=He(()=>{const[A,T]=q6(m),z=k(A);N(T),b.current=A,h.current=!1,f.forEach(M=>M(z)),c(z)});Pe(()=>(h.current||k(b.current),()=>{a.current=[],o&&(o.current=[])}),[a,o,k]),Pe(()=>{h.current&&w()}),Pe(()=>()=>{_.current?.disconnect(),h.current=!0},[]);const S=He(A=>(f.add(A),()=>{f.delete(A)})),R=x.useMemo(()=>({register:E,unregister:y,subscribeMapChange:S,nextIndexRef:g}),[E,y,S,g]);return n.jsx(UC.Provider,{value:R,children:t})}function $6(){return new Map}function U6(){return new Set}function q6(e){const t=new Set,a=[],o=[];e.forEach((c,d)=>{if(!d.isConnected)return;const f=c.index,m={index:f??-1,element:d,registration:c};f===null?o.push(m):f>=0&&(t.add(f),a.push(m))});let l=0;return o.sort((c,d)=>FC(c.element,d.element)),o.forEach(c=>{for(;t.has(l);)l+=1;c.index=l,a.push(c),l+=1}),t.size>0&&a.sort((c,d)=>c.index-d.index),[a,o.map(c=>c.element)]}function H6(e,t){let a=e.parentElement;for(;a&&!a.contains(t);)a=a.parentElement;return a}function V6(e){for(const t of e)for(let a=0;a<t.removedNodes.length;a+=1)if(t.removedNodes[a].isConnected)return!0;return!1}function FC(e,t){return e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1}const __=x.forwardRef(function(t,a){const{cutout:o,...l}=t;let c;if(o){const d=o.getBoundingClientRect();c=`polygon(0% 0%,100% 0%,100% 100%,0% 100%,0% 0%,${d.left}px ${d.top}px,${d.left}px ${d.bottom}px,${d.right}px ${d.bottom}px,${d.right}px ${d.top}px,${d.left}px ${d.top}px)`}return n.jsx("div",{ref:a,role:"presentation","data-base-ui-inert":"",...l,style:{position:"fixed",inset:0,userSelect:"none",WebkitUserSelect:"none",clipPath:c}})});let mk={},gk={},hk="";function _p(e,t){return eu(e)?e:t}function xk(e,t,a){return/hidden|clip/.test(e.getComputedStyle(_p(t,a)).overflowY)}function F6(e){if(typeof document>"u")return!1;const t=vt(e);return Jt(t).innerWidth-t.documentElement.clientWidth>0}function G6(e){if(!(typeof CSS<"u"&&CSS.supports&&CSS.supports("scrollbar-gutter","stable"))||typeof document>"u")return!1;const a=vt(e),o=a.documentElement,l=a.body,c=_p(o,l),d=c.style.overflowY,f=o.style.scrollbarGutter;o.style.scrollbarGutter="stable",c.style.overflowY="scroll";const m=c.offsetWidth;c.style.overflowY="hidden";const g=c.offsetWidth;return c.style.overflowY=d,o.style.scrollbarGutter=f,m===g}function Y6(e){const t=vt(e),a=t.documentElement,o=t.body,l=_p(a,o),c={overflowY:l.style.overflowY,overflowX:l.style.overflowX};return Object.assign(l.style,{overflowY:"hidden",overflowX:"hidden"}),()=>{Object.assign(l.style,c)}}function K6(e){const t=vt(e),a=t.documentElement,o=t.body,l=Jt(a);let c=0,d=0,f=!1;const m=ga.create();if(ir&&(l.visualViewport?.scale??1)!==1)return()=>{};function g(){const j=l.getComputedStyle(a),E=l.getComputedStyle(o),N=(j.scrollbarGutter||"").includes("both-edges")?"stable both-edges":"stable";c=a.scrollTop,d=a.scrollLeft,mk={scrollbarGutter:a.style.scrollbarGutter,overflowY:a.style.overflowY,overflowX:a.style.overflowX},hk=a.style.scrollBehavior,gk={position:o.style.position,height:o.style.height,width:o.style.width,boxSizing:o.style.boxSizing,overflowY:o.style.overflowY,overflowX:o.style.overflowX,scrollBehavior:o.style.scrollBehavior};const w=a.scrollHeight>a.clientHeight,S=a.scrollWidth>a.clientWidth,R=j.overflowY==="scroll"||E.overflowY==="scroll",A=j.overflowX==="scroll"||E.overflowX==="scroll",T=Math.max(0,l.innerWidth-o.clientWidth),z=Math.max(0,l.innerHeight-o.clientHeight),M=parseFloat(E.marginTop)+parseFloat(E.marginBottom),L=parseFloat(E.marginLeft)+parseFloat(E.marginRight),P=_p(a,o);if(f=G6(e),f){a.style.scrollbarGutter=N,P.style.overflowY="hidden",P.style.overflowX="hidden";return}Object.assign(a.style,{scrollbarGutter:N,overflowY:"hidden",overflowX:"hidden"}),(w||R)&&(a.style.overflowY="scroll"),(S||A)&&(a.style.overflowX="scroll"),Object.assign(o.style,{position:"relative",height:M||z?`calc(100dvh - ${M+z}px)`:"100dvh",width:L||T?`calc(100vw - ${L+T}px)`:"100vw",boxSizing:"border-box",overflowY:"hidden",overflowX:"hidden",scrollBehavior:"unset"}),o.scrollTop=c,o.scrollLeft=d,a.setAttribute("data-base-ui-scroll-locked",""),a.style.scrollBehavior="unset"}function h(){Object.assign(a.style,mk),Object.assign(o.style,gk),f||(a.scrollTop=c,a.scrollLeft=d,a.removeAttribute("data-base-ui-scroll-locked"),a.style.scrollBehavior=hk)}function b(){h(),m.request(g)}g();const _=xt(l,"resize",b);return()=>{m.cancel(),h(),typeof l.removeEventListener=="function"&&_()}}class X6{lockCount=0;restore=null;timeoutLock=ta.create();timeoutUnlock=ta.create();acquire(t){return this.lockCount+=1,this.lockCount===1&&this.restore===null&&this.timeoutLock.start(0,()=>this.lock(t)),this.release}release=()=>{this.lockCount-=1,this.lockCount===0&&this.restore&&this.timeoutUnlock.start(0,this.unlock)};unlock=()=>{this.lockCount===0&&this.restore&&(this.restore?.(),this.restore=null)};lock(t){if(this.lockCount===0||this.restore!==null)return;const a=vt(t),o=a.documentElement,l=a.body,c=Jt(o);if(xk(c,o,l)){const f=new c.MutationObserver(()=>{xk(c,o,l)||(f.disconnect(),this.restore=null,this.lock(t))}),m={attributes:!0};f.observe(o,m),f.observe(l,m),this.restore=()=>f.disconnect();return}const d=Zf||!F6(t);this.restore=d?Y6(t):K6(t)}}const Q6=new X6;function GC(e=!0,t=null){Pe(()=>{if(e)return Q6.acquire(t)},[e,t])}const W6=20;function YC(e,t,a,o){const[l,c]=x.useState(!1);Pe(()=>{if(!e||!t||a==null){c(!1);return}const d=vt(a).documentElement.clientWidth,f=a.offsetWidth;c(d>0&&f>0&&f>=d-W6)},[e,t,a]),GC(e&&(!t||l),o)}const Z6=x.forwardRef(function(t,a){const{anchor:o,positionMethod:l="absolute",className:c,render:d,side:f,align:m,sideOffset:g=0,alignOffset:h=0,collisionBoundary:b="clipping-ancestors",collisionPadding:_=5,arrowPadding:j=5,sticky:E=!1,disableAnchorTracking:y=!1,collisionAvoidance:k=GS,style:N,...w}=t,{store:S}=Vo(),R=I6(),A=b_(!0),T=S.useState("parent"),z=S.useState("floatingRootContext"),M=S.useState("floatingTreeRoot"),L=S.useState("mounted"),P=S.useState("open"),B=S.useState("modal"),D=S.useState("openMethod"),$=S.useState("activeTriggerElement"),q=S.useState("transitionStatus"),G=S.useState("positionerElement"),U=S.useState("instantType"),V=S.useState("adaptiveOrigin"),X=S.useState("lastOpenChangeReason"),Q=S.useState("floatingNodeId"),W=S.useState("floatingParentNodeId"),I=z.useState("domReferenceElement"),K=x.useRef(null),ee=fC(G);let F=o,ne=g,Z=h,fe=m,Y=k;T.type==="context-menu"&&(F=o??T.context?.anchor,fe=fe??"start",!f&&fe!=="center"&&(Z=t.alignOffset??2,ne=t.sideOffset??-5));let oe=f,ve=fe;T.type==="menu"?(oe=oe??"inline-end",ve=ve??"start",Y=t.collisionAvoidance??YS):T.type==="menubar"&&(oe=oe??(T.context.orientation==="vertical"?"inline-end":"bottom"),ve=ve??"start");const le=T.type==="context-menu",xe=f_({anchor:F,floatingRootContext:z,positionMethod:A?"fixed":l,mounted:L,side:oe,sideOffset:ne,align:ve,alignOffset:Z,arrowPadding:le?0:j,collisionBoundary:b,collisionPadding:_,sticky:E,nodeId:Q,keepMounted:R,disableAnchorTracking:y,collisionAvoidance:Y,shift:le?{crossAxis:!("side"in Y&&Y.side==="flip"),rootBoundary:"layoutViewport"}:void 0,externalTree:M,adaptiveOrigin:V});x.useEffect(()=>{function Me(De){De.open&&(De.parentNodeId===Q&&S.set("hoverEnabled",!1),De.nodeId!==Q&&De.parentNodeId===S.select("floatingParentNodeId")&&S.setOpen(!1,rt(yc)))}return M.events.on("menuopenchange",Me),()=>{M.events.off("menuopenchange",Me)}},[S,M.events,Q]),x.useEffect(()=>{if(S.select("floatingParentNodeId")==null)return;function Me(De){if(De.open||De.nodeId!==S.select("floatingParentNodeId"))return;const Ue=De.reason??yc;S.setOpen(!1,rt(Ue))}return M.events.on("menuopenchange",Me),()=>{M.events.off("menuopenchange",Me)}},[M.events,S]);const ke=Rn();x.useEffect(()=>{P||ke.clear()},[P,ke]),x.useEffect(()=>{function Me(De){if(!(!P||De.nodeId!==S.select("floatingParentNodeId")))if(De.target&&$&&$!==De.target){const Ue=S.select("closeDelay");Ue>0?ke.isStarted()||ke.start(Ue,()=>{S.setOpen(!1,rt(yc))}):S.setOpen(!1,rt(yc))}else ke.clear()}return M.events.on("itemhover",Me),()=>{M.events.off("itemhover",Me)}},[M.events,P,$,S,ke]),x.useEffect(()=>{const Me={open:P,nodeId:Q,parentNodeId:W,reason:S.select("lastOpenChangeReason")};M.events.emit("menuopenchange",Me)},[M.events,P,S,Q,W]),Pe(()=>{const Me=I,De=K.current;if(Me&&(K.current=Me),De&&Me&&Me!==De){S.set("instantType",void 0);const Ue=new AbortController;return ee(()=>{S.set("instantType","trigger-change")},Ue.signal),()=>{Ue.abort()}}},[I,ee,S]);const Re={open:P,side:xe.side,align:xe.align,anchorHidden:xe.anchorHidden,nested:T.type==="menu",instant:U},Ae=T.type==="menubar"&&T.context.modal;YC(P&&(Ae||B&&X!==En),D==="touch",G,$);const Oe=p_(t,Re,{styles:xe.positionerStyles,transitionStatus:q,props:w,refs:[a,S.useStateSetter("positionerElement")],hidden:!L,inert:!P}),Te=L&&T.type!=="menu"&&(T.type!=="menubar"&&B&&X!==En||T.type==="menubar"&&T.context.modal);let Ne=null;return T.type==="menubar"?Ne=T.context.contentElement:T.type===void 0&&(Ne=$),n.jsxs(PC.Provider,{value:xe,children:[Te&&n.jsx(__,{ref:T.type==="context-menu"||T.type==="nested-context-menu"?T.context.internalBackdropRef:null,inert:gp(!P),cutout:Ne}),n.jsx(Cz,{id:Q,children:n.jsx(bp,{elementsRef:S.context.itemDomElements,labelsRef:S.context.itemLabels,children:Oe})})]})}),KC=x.createContext(void 0);function J6(){const e=x.useContext(KC);if(e===void 0)throw new Error(gn(34));return e}const eD=x.memo(x.forwardRef(function(t,a){const{render:o,className:l,value:c,defaultValue:d,onValueChange:f,disabled:m=!1,style:g,"aria-labelledby":h,...b}=t,[_,j]=x.useState(void 0),[E,y]=ni({controlled:c,default:d,name:"MenuRadioGroup"}),k=He((R,A)=>{f?.(R,A),!A.isCanceled&&y(R)}),w=Et("div",t,{state:{disabled:m},ref:a,props:{role:"group","aria-labelledby":h??_,"aria-disabled":m||void 0,...b}}),S=x.useMemo(()=>({value:E,setValue:k,disabled:m}),[E,k,m]);return n.jsx(A6.Provider,{value:j,children:n.jsx(KC.Provider,{value:S,children:w})})})),XC=x.createContext(void 0);function tD(){const e=x.useContext(XC);if(e===void 0)throw new Error(gn(35));return e}const nD=x.forwardRef(function(t,a){const{render:o,className:l,id:c,label:d,nativeButton:f=!1,disabled:m=!1,closeOnClick:g=!1,value:h,style:b,..._}=t,j=ru({guess:!0,label:d}),E=x_(!0),y=ra(c),{store:k}=Vo(),N=k.useState("isActive",j.index),w=k.useState("itemProps"),{value:S,setValue:R,disabled:A}=J6(),T=k.useState("disabled"),z=m||A||T,M=S===h,{getItemProps:L,itemRef:P}=$C({closeOnClick:g,disabled:z,highlighted:N,id:y,store:k,nativeButton:f,nodeId:E?.context.nodeId,itemMetadata:BC}),B=x.useMemo(()=>({disabled:z,highlighted:N,checked:M}),[z,N,M]);function D(q){const G=rt(Fl,q.nativeEvent,void 0,{preventUnmountOnClose:Nn});R(h,G)}const $=Et("div",t,{state:B,stateAttributesMapping:qC,props:[w,{role:"menuitemradio","aria-checked":M,onClick:D},_,L],ref:[P,a,j.ref]});return n.jsx(XC.Provider,{value:B,children:$})}),sD=x.forwardRef(function(t,a){const{render:o,className:l,style:c,keepMounted:d=!1,...f}=t,m=tD(),g=x.useRef(null),{transitionStatus:h,mounted:b,setMounted:_}=hi(m.checked);Ca({open:m.checked,ref:g,onComplete(){m.checked||_(!1)}});const j={checked:m.checked,disabled:m.disabled,highlighted:m.highlighted,transitionStatus:h};return Et("span",t,{state:j,stateAttributesMapping:qC,ref:[a,g],props:{"aria-hidden":!0,...f},enabled:d||b})}),aD=x.createContext(null);function QC(e){return x.useContext(aD)}function rD(e){const t=x.useRef(""),a=x.useCallback(l=>{l.defaultPrevented||(t.current=l.pointerType,e(l,l.pointerType))},[e]);return{onClick:x.useCallback(l=>{if(l.detail===0){e(l,"keyboard");return}"pointerType"in l?e(l,l.pointerType):e(l,t.current),t.current=""},[e]),onPointerDown:a}}function v_(e,t){const a=x.useRef(e),o=He(t);Pe(()=>{a.current!==e&&o(a.current),a.current=e},[e,o])}function oD(e,t){const a=He((c,d)=>{(typeof e=="function"?e():e)||t(d||(Zf?"touch":""))}),{onClick:o,onPointerDown:l}=rD(a);return x.useMemo(()=>({onClick:o,onPointerDown:l}),[o,l])}function WC(e){const[t,a]=x.useState(null),o=oD(e,a);return v_(e,l=>{l&&!e&&a(null)}),x.useMemo(()=>({openMethod:t,triggerProps:o}),[t,o])}const lD={...i_,disabled:e=>e.parent.type==="menubar"&&e.parent.context.disabled||e.disabled,modal:e=>(e.parent.type===void 0||e.parent.type==="context-menu")&&(e.modal??!0),openMethod:e=>e.openMethod,allowMouseEnter:e=>e.allowMouseEnter,highlightItemOnHover:e=>e.highlightItemOnHover,parent:e=>e.parent,rootId:e=>e.parent.type==="menu"?e.parent.store.select("rootId"):e.parent.type!==void 0?e.parent.context.rootId:e.rootId,activeIndex:e=>e.activeIndex,isActive:(e,t)=>e.activeIndex===t,hoverEnabled:e=>e.hoverEnabled,instantType:e=>e.instantType,lastOpenChangeReason:e=>e.openChangeReason,floatingTreeRoot:e=>e.parent.type==="menu"?e.parent.store.select("floatingTreeRoot"):e.floatingTreeRoot,floatingNodeId:e=>e.floatingNodeId,floatingParentNodeId:e=>e.floatingParentNodeId,itemProps:e=>e.itemProps,closeDelay:e=>e.closeDelay,adaptiveOrigin:e=>e.adaptiveOrigin,keyboardEventRelay:e=>{if(e.keyboardEventRelay)return e.keyboardEventRelay;if(e.parent.type==="menu")return e.parent.store.select("keyboardEventRelay")}};class iD extends nu{constructor(t){super({...uD(),...t},cD(),lD),this.unsubscribeParentListener=this.observe("parent",a=>{if(this.unsubscribeParentListener?.(),a.type==="menu"){let o=a.store.select("rootId"),l=a.store.select("floatingTreeRoot"),c=a.store.select("keyboardEventRelay");this.unsubscribeParentListener=a.store.subscribe(()=>{const d=a.store.select("rootId"),f=a.store.select("floatingTreeRoot"),m=a.store.select("keyboardEventRelay");o===d&&l===f&&c===m||(o=d,l=f,c=m,this.notifyAll())}),this.context.allowMouseUpTriggerRef=a.store.context.allowMouseUpTriggerRef;return}a.type!==void 0&&(this.context.allowMouseUpTriggerRef=a.context.allowMouseUpTriggerRef),this.unsubscribeParentListener=null})}setOpen(t,a){this.state.floatingRootContext.context.events.emit("setOpen",{open:t,eventDetails:a})}unsubscribeParentListener=null}function cD(){return{positionerRef:x.createRef(),popupRef:x.createRef(),typingRef:{current:!1},itemDomElements:{current:[]},itemLabels:{current:[]},allowMouseUpTriggerRef:{current:!1},triggerFocusTargetRef:x.createRef(),beforeContentFocusGuardRef:x.createRef(),onOpenChangeComplete:void 0,triggerElements:new su}}function uD(){return{...o_(),disabled:!1,modal:!0,openMethod:null,allowMouseEnter:!1,highlightItemOnHover:!0,parent:{type:void 0},rootId:void 0,activeIndex:null,hoverEnabled:!0,instantType:void 0,openChangeReason:null,floatingTreeRoot:new Wb,floatingNodeId:void 0,floatingParentNodeId:null,itemProps:sn,keyboardEventRelay:void 0,closeDelay:0,adaptiveOrigin:void 0}}const dD=x.createContext(void 0);function fD(){return x.useContext(dD)}const pD=Rb(function(t){const{children:a,open:o,onOpenChange:l,onOpenChangeComplete:c,defaultOpen:d=!1,disabled:f=!1,modal:m,loopFocus:g=!0,orientation:h="vertical",actionsRef:b,closeParentOnEsc:_=!1,handle:j,triggerId:E,defaultTriggerId:y=null,highlightItemOnHover:k=!0}=t,N=b_(!0),w=Vo(!0),S=QC(!0),R=fD(),A=x.useMemo(()=>R&&w?{type:"menu",store:w.store}:S?{type:"menubar",context:S}:N&&!w?{type:"context-menu",context:N}:{type:void 0},[N,w,S,R]),T=mD({open:d,openProp:o,activeTriggerId:y,triggerIdProp:E,parent:A});T.useControlledProp("openProp",o),T.useControlledProp("triggerIdProp",E),T.useContextCallback("onOpenChangeComplete",c);const z=Oo(),M=Oo(),L=T.useState("floatingTreeRoot"),P=eC(L),B=eo(),D=T.useState("open"),$=T.useState("activeTriggerElement"),q=T.useState("positionerElement"),G=T.useState("hoverEnabled"),U=T.useState("disabled"),V=T.useState("lastOpenChangeReason"),X=T.useState("parent"),Q=T.useState("activeIndex"),W=T.useState("payload"),I=T.useState("floatingParentNodeId"),K=x.useRef(null),ee=x.useRef(X.type!=="context-menu"),F=Rn(),ne=x.useRef(!0),Z=Rn(),fe=I!=null,{openMethod:Y,triggerProps:oe}=WC(D);T.useSyncedValues({disabled:f,highlightItemOnHover:k,modal:X.type===void 0?m:void 0,openMethod:Y,rootId:z}),s_(T);const{forceUnmount:ve}=a_(D,T,()=>{T.set("allowMouseEnter",!1)});Pe(()=>{N&&!w?T.update({parent:{type:"context-menu",context:N},floatingNodeId:P,floatingParentNodeId:B}):w&&T.update({floatingNodeId:P,floatingParentNodeId:B})},[N,w,P,B,T]),x.useEffect(()=>{if(D||(K.current=null),X.type==="context-menu"){if(!D){F.clear(),ee.current=!1;return}F.start(500,()=>{ee.current=!0})}},[F,D,X.type]),Pe(()=>{!D&&!G&&T.set("hoverEnabled",!0)},[D,G,T]);const le=He((Ce,Qe)=>{const Ge=Qe.reason;if(!Ce&&!T.select("open")||D===Ce&&Qe.trigger===$&&V===Ge)return;const lt=mC(Qe);if(!Ce&&Qe.trigger==null&&(Qe.trigger=$??void 0),l?.(Ce,Qe),Qe.isCanceled)return;T.state.floatingRootContext.dispatchOpenChange(Ce,Qe);const Tt=Qe.event;if(Ce===!1&&Tt?.type==="click"&&Tt.pointerType==="touch"&&!ne.current)return;Ce&&Ge===Vl?(ne.current=!1,Z.start(300,()=>{ne.current=!0})):(ne.current=!0,Z.clear());const _t=(Ge===gi||Ge===Fl)&&Tt.detail===0,Ct=!Ce&&(Ge===op||Ge==null),je={open:Ce,openChangeReason:Ge};K.current=Qe.event,n_(je,Ce,Qe.trigger,lt()),T.update(je),X.type==="menubar"&&(Ge===Vl||Ge===zo||Ge===En||Ge===bx||Ge===yc)?T.set("instantType","group"):_t||Ct?T.set("instantType",_t?"click":"dismiss"):T.set("instantType",void 0)}),xe=dC({popupStore:T,floatingId:M,nested:B!=null,onOpenChange:le}),ke=xe.context.events;Pe(()=>{const Ce=({open:Qe,eventDetails:Ge})=>le(Qe,Ge);return ke.on("setOpen",Ce),()=>{ke?.off("setOpen",Ce)}},[ke,le]);const Re=x.useCallback(()=>{T.setOpen(!1,rt(Bb))},[T]);x.useImperativeHandle(b,()=>({unmount:ve,close:Re}),[ve,Re]);let Ae;X.type==="context-menu"&&(Ae=X.context),x.useImperativeHandle(Ae?.positionerRef,()=>q,[q]),x.useImperativeHandle(Ae?.actionsRef,()=>({setOpen:le}),[le]);const Ie=ip(xe,{enabled:!U,bubbles:{escapeKey:_&&X.type==="menu"},outsidePress(){return X.type!=="context-menu"||K.current?.type==="contextmenu"?!0:ee.current},externalTree:fe?L:void 0}),Oe=pp(),Te=x.useCallback(Ce=>{T.select("activeIndex")!==Ce&&T.set("activeIndex",Ce)},[T]),Ne=kC(xe,{enabled:!U,listRef:T.context.itemDomElements,activeIndex:Q,nested:X.type!==void 0,loopFocus:g,orientation:h,parentOrientation:X.type==="menubar"?X.context.orientation:void 0,rtl:Oe==="rtl",disabledIndices:ja,onNavigate:Te,openOnArrowKeyDown:X.type!=="context-menu",externalTree:fe?L:void 0,focusItemOnHover:k}),Me=x.useCallback(Ce=>{T.context.typingRef.current=Ce},[T]),De=wC(xe,{enabled:!U,listRef:T.context.itemLabels,elementsRef:T.context.itemDomElements,activeIndex:Q,resetMs:vz,onMatch:Ce=>{D&&Ce!==Q&&T.set("activeIndex",Ce)},onTyping:Me}),Ue=x.useMemo(()=>{const Ce=Ss(De.reference,Ne.reference,Ie.reference,{onMouseMove(){T.set("allowMouseEnter",!0)}},oe);return Ce["aria-haspopup"]="menu",Ce["aria-expanded"]=D,Ce},[T,De.reference,Ne.reference,Ie.reference,oe,D]),Xe=x.useMemo(()=>{const Ce=Ss(Ne.trigger,Ie.trigger,oe);return Ce["aria-haspopup"]="menu",Ce["aria-expanded"]=!1,Ce},[Ne.trigger,Ie.trigger,oe]),me=x.useMemo(()=>Ss(dp,{id:M,role:"menu","aria-labelledby":$?.id,onMouseMove(){T.set("allowMouseEnter",!0),X.type==="menu"&&T.set("hoverEnabled",!1)},onClick(){T.select("hoverEnabled")&&T.set("hoverEnabled",!1)},onKeyDown(Ce){const Qe=T.select("keyboardEventRelay");Qe&&!Ce.isPropagationStopped()&&Qe(Ce)}},De.floating,Ne.floating,Ie.floating),[$,M,X.type,T,De.floating,Ne.floating,Ie.floating]),de=Ne.item??sn;r_(T,{floatingRootContext:xe,activeTriggerProps:Ue,inactiveTriggerProps:Xe,popupProps:me,itemProps:de});const Le=x.useMemo(()=>({store:T,parent:A}),[T,A]),ye=n.jsxs(LC.Provider,{value:Le,children:[j&&n.jsx(t_,{handle:j,store:T}),typeof a=="function"?a({payload:W}):a]});return X.type===void 0||X.type==="context-menu"?n.jsx(Nz,{externalTree:L,children:ye}):ye});function mD(e){return Hn(()=>new iD(e)).current}const Od=5;function ZC(e,t){const a=gD(t);return e.clientX>=a.left-Od&&e.clientX<=a.right+Od&&e.clientY>=a.top-Od&&e.clientY<=a.bottom+Od}function gD(e){const t=e.getBoundingClientRect(),a=Jt(e);if(Mb)return t;const o=a.getComputedStyle(e,"::before"),l=a.getComputedStyle(e,"::after");if(!(o.content!=="none"||l.content!=="none"))return t;const d=parseFloat(o.width)||0,f=parseFloat(o.height)||0,m=parseFloat(l.width)||0,g=parseFloat(l.height)||0,h=Math.max(t.width,d,m),b=Math.max(t.height,f,g),_=h-t.width,j=b-t.height;return{left:t.left-_/2,right:t.right+_/2,top:t.top-j/2,bottom:t.bottom+j/2}}function JC(e={}){const{highlightItemOnHover:t,highlightedIndex:a,onHighlightedIndexChange:o}=hp(),{ref:l,index:c}=ru(e),d=a===c,f=x.useRef(null),m=rr(l,f);return{compositeProps:{tabIndex:d?0:-1,onFocus(){o(c)},onMouseMove(){const h=f.current;if(!t||!h)return;const b=h.hasAttribute("disabled")||h.ariaDisabled==="true";!d&&!b&&h.focus()}},compositeRef:m,index:c}}function hD(e){const{render:t,className:a,style:o,state:l=sn,props:c=ja,refs:d=ja,metadata:f,stateAttributesMapping:m,tag:g="div",...h}=e,{compositeProps:b,compositeRef:_}=JC({metadata:f});return Et(g,e,{state:l,ref:[_,...d],props:[b,...c,h],stateAttributesMapping:m})}function eN(e){if(Gt(e)&&e.hasAttribute("data-rootownerid"))return e.getAttribute("data-rootownerid");if(!Ja(e))return eN(ar(e))}function xD(e,t){const a=x.useRef(null);function o(c){Gs.flushSync(()=>{e.setOpen(!1,rt(zo,c.nativeEvent,c.currentTarget))}),nz(a.current)?.focus()}function l(c){const d=e.select("positionerElement");if(d&&Gl(c,d))e.context.beforeContentFocusGuardRef.current?.focus();else{Gs.flushSync(()=>{e.setOpen(!1,rt(zo,c.nativeEvent,c.currentTarget))});let f=tz(e.context.triggerFocusTargetRef.current||t.current);for(;f!==null&&Ze(d,f);){const m=f;if(f=Gb(f),f===m)break}f?.focus()}}return{preFocusGuardRef:a,handlePreFocusGuardFocus:o,handleFocusTargetFocus:l}}function bD(e){const{enabled:t=!0,mouseDownAction:a,open:o}=e,l=x.useRef(!1);return x.useMemo(()=>t?{onMouseDown:c=>{(a==="open"&&!o||a==="close"&&o)&&(l.current=!0,vt(c.currentTarget).addEventListener("click",()=>{l.current=!1},{once:!0}))},onClick:c=>{l.current&&(l.current=!1,c.preventBaseUIHandler())}}:sn,[t,a,o])}const _D=gS(function(t,a){const{render:o,className:l,style:c,disabled:d=!1,nativeButton:f=!0,id:m,openOnHover:g,delay:h=100,closeDelay:b=0,handle:_,payload:j,...E}=t,y=Vo(!0),N=bC(_)??y?.store;if(!N)throw new Error(gn(85));const w=ra(m),S=N.useState("isTriggerActive",w),R=N.useState("floatingRootContext"),A=N.useState("isOpenedByTrigger",w),T=N.useState("triggerPopupId",w),z=x.useRef(null),M=yD(),L=hp(!0),P=to(),B=x.useMemo(()=>P??new Wb,[P]),D=eC(B),$=eo(),{registerTrigger:q,isMountedByThisTrigger:G}=gC(w,z,N,{payload:j,closeDelay:b,parent:M,floatingTreeRoot:B,floatingNodeId:D,floatingParentNodeId:$,keyboardEventRelay:L?.relayKeyboardEvent}),U=M.type==="menubar",V=N.useState("disabled"),X=d||V||U&&M.context.disabled,{getButtonProps:Q,buttonRef:W}=no({disabled:X,native:f});x.useEffect(()=>{!A&&M.type===void 0&&(N.context.allowMouseUpTriggerRef.current=!1)},[N,A,M.type]);const I=x.useRef(null),K=Rn(),ee=He(Me=>{if(!I.current)return;K.clear(),N.context.allowMouseUpTriggerRef.current=!1;const De=Me.target;Ze(I.current,De)||Ze(N.select("positionerElement"),De)||De===I.current||De!=null&&eN(De)===N.select("rootId")||ZC(Me,I.current)||B.events.emit("close",{domEvent:Me,reason:yS})});x.useEffect(()=>{A&&N.select("lastOpenChangeReason")===En&&vt(I.current).addEventListener("mouseup",ee,{once:!0})},[A,ee,N]);const F=U&&M.context.hasSubmenuOpen,Z=jC(R,{enabled:(g??F)&&!X&&(!U||F&&!G),handleClose:SC({blockPointerEvents:!U}),mouseOnly:!0,move:!1,restMs:M.type===void 0?h:void 0,delay:{close:b},triggerElementRef:z,externalTree:B,isActiveTrigger:S,isClosing:()=>N.select("transitionStatus")==="ending"}),fe=vD(A,N.select("lastOpenChangeReason")),Y=tC(R,{enabled:!X,event:A&&U?"click":"mousedown",toggle:!0,ignoreMouse:!1,stickIfOpen:M.type===void 0?fe:!1}),oe=_C(R,{enabled:!X&&F}),ve=bD({open:A,enabled:U,mouseDownAction:"open"}),le=x.useMemo(()=>Ss(oe.reference,Y.reference),[oe.reference,Y.reference]),xe=N.useState("triggerProps",G),{preFocusGuardRef:ke,handlePreFocusGuardFocus:Re,handleFocusTargetFocus:Ae}=xD(N,z),Ie={disabled:X,open:A},Oe=[I,a,W,q,z],Te=[le,Z??sn,xe,{"aria-haspopup":"menu","aria-controls":T,id:w,onMouseDown:Me=>{if(N.select("open"))return;K.start(200,()=>{N.context.allowMouseUpTriggerRef.current=!0}),vt(Me.currentTarget).addEventListener("mouseup",ee,{once:!0})}},U?{role:"menuitem"}:{},ve,E,Q],Ne=Et("button",t,{enabled:!U,stateAttributesMapping:wx,state:Ie,ref:Oe,props:Te});return U?n.jsx(hD,{tag:"button",render:o,className:l,style:c,state:Ie,refs:Oe,props:Te,stateAttributesMapping:wx}):A?n.jsxs(x.Fragment,{children:[n.jsx(ei,{ref:ke,onFocus:Re},`${w}-pre-focus-guard`),n.jsx(x.Fragment,{children:Ne},w),n.jsx(ei,{ref:N.context.triggerFocusTargetRef,onFocus:Ae},`${w}-post-focus-guard`)]}):n.jsx(x.Fragment,{children:Ne},w)});function vD(e,t){const a=Rn(),[o,l]=x.useState(!1);return Pe(()=>{e&&t===En?(l(!0),a.start(yz,()=>{l(!1)})):e||(a.clear(),l(!1))},[e,t,a]),o}function yD(){const e=QC();return x.useMemo(()=>e?{type:"menubar",context:e}:{type:void 0},[e])}function tN(e){return e==null||e.hasAttribute("disabled")||e.getAttribute("aria-disabled")==="true"}function y_({...e}){return n.jsx(pD,{"data-slot":"dropdown-menu",...e})}function j_({...e}){return n.jsx(_D,{"data-slot":"dropdown-menu-trigger",...e})}function k_({align:e="start",alignOffset:t=0,side:a="bottom",sideOffset:o=4,className:l,...c}){return n.jsx(B6,{children:n.jsx(Z6,{className:"isolate z-50 outline-none",align:e,alignOffset:t,side:a,sideOffset:o,children:n.jsx(L6,{"data-slot":"dropdown-menu-content",className:St("z-50 max-h-(--available-height) w-(--anchor-width) min-w-32 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:overflow-hidden data-closed:fade-out-0 data-closed:zoom-out-95",l),...c})})})}function sf({className:e,inset:t,variant:a="default",...o}){return n.jsx(M6,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":a,className:St("group/dropdown-menu-item relative flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive",e),...o})}function jD({...e}){return n.jsx(eD,{"data-slot":"dropdown-menu-radio-group",...e})}function kD({className:e,children:t,inset:a,...o}){return n.jsxs(nD,{"data-slot":"dropdown-menu-radio-item","data-inset":a,className:St("relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...o,children:[n.jsx("span",{className:"pointer-events-none absolute right-2 flex items-center justify-center","data-slot":"dropdown-menu-radio-item-indicator",children:n.jsx(sD,{children:n.jsx(Yr,{})})}),t]})}const wD={common:{loading:"Cargando…",saving:"Guardando…",cancel:"Cancelar",save:"Guardar",delete:"Borrar",edit:"Editar",create:"Crear",add:"Agregar",remove:"Quitar",reload:"Recargar",shutdown:"Apagar",enabled:"Habilitado",disabled:"Deshabilitado",enable:"Habilitar",disable:"Deshabilitar",open:"Abrir",close:"Cerrar",confirm:"Confirmar",optional:"(opcional)",none:"—",none_yet:"Todavía no hay nada.",error_generic:"Algo salió mal.",search:"Buscar",new:"Nuevo",restore:"Restaurar",show:"Mostrar",hide:"Ocultar",copy:"Copiar",run:"Ejecutar",refresh:"Refrescar",view_all:"Ver todo",saved:"Guardado.",deleted:"Eliminado.",pager_prev:"Anterior",pager_next:"Siguiente",pager_page:"Página {page} de {total}",pager_range:"{from}–{to} de {total}",pager_per_page:"Por página"},daemon:{connecting:"Conectando con el daemon…",unreachable:"No pude llegar al daemon en localhost:7430.",unreachable_hint:"Arrancá APX con `apx daemon start` y refrescá.",version:"Versión",uptime:"Uptime",status:"Status",running:"running",down:"down",reload_hint:"POST /admin/reload — relee ~/.apx/config.json sin reiniciar.",shutdown_confirm:"¿Apagar el daemon? Las próximas requests fallarán hasta levantarlo de nuevo.",shutdown_done:"Daemon detenido."},pairing:{title:"Vincular este equipo",subtitle:"Estás entrando desde fuera de esta máquina. Por seguridad, vinculá este navegador con un código de pairing.",steps_title:"Cómo obtener el código",step_1:"En la PC donde corre APX, abrí una terminal.",step_2:"Ejecutá `apx pair` (o escaneá el QR con APX Deck).",step_3:"Copiá el código que aparece debajo del QR y pegalo acá.",code_label:"Código de pairing",code_ph:"p. ej. 7f3a1c9e-…",label_label:"Nombre de este equipo",label_ph:"p. ej. Notebook del living",submit:"Vincular",linking:"Vinculando…",success:"Equipo vinculado ✓",err_required:"Pegá el código de pairing.",err_expired:"El código expiró. Volvé a correr `apx pair` y probá de nuevo.",err_unknown:"Código desconocido o ya usado. Generá uno nuevo con `apx pair`.",err_generic:"No se pudo vincular. Revisá el código e intentá otra vez.",revoke_hint:"Podés revocar este equipo cuando quieras desde Settings o con `apx pair revoke`."},nav:{apx_admin:"APX",settings:"Settings",project:"Proyecto",add_project:"Agregar proyecto",all_projects:"Todos los proyectos",more_projects:"{count} más",collapse_projects:"Ocultar proyectos",expand_projects:"Mostrar proyectos",modules:{voice:"Voces",desktop:"Escritorio",deck:"Deck",code:"Code",web:"Web"}},topbar:{breadcrumb_root:"APX",breadcrumb_settings:"APX › Settings",breadcrumb_project:"APX › Proyecto",breadcrumb_base:"Base",breadcrumb_projects:"Proyectos",light:"Cambiar a claro",dark:"Cambiar a oscuro",lang_toggle:"Idioma"},admin:{title:"APX",subtitle:"Panel general. Configuración global, canales y proyectos.",engines_title:"Engines",engines_subtitle:"Adaptadores LLM disponibles. Las API keys viven en ~/.apx/config.json.",telegram_title:"Telegram",telegram_subtitle:"Canales configurados. Cada uno puede estar pineado a un proyecto.",telegram_polling_on:"Polling activo",telegram_polling_off:"Deshabilitado",telegram_add_channel:"Canal",telegram_send_test:"Probar",telegram_send_test_title:"Enviar a",telegram_default_message:"Mensaje de prueba desde el panel de APX ✅",projects_title:"Proyectos registrados",projects_subtitle:"Click en un proyecto para abrir su panel.",unregister:"Desregistrar",unregister_confirm:"¿Quitar {label} de APX? La carpeta no se borra; sólo se desregistra.",reload_success:"Config recargada.",telegram_polling_started:"Polling iniciado.",telegram_polling_stopped:"Polling detenido.",telegram_channel_removed:"Canal eliminado.",agents_badge:"agents",engine_badge:"sí",engine_badge_no:"no",base_label:"Base"},add_project:{title:"Agregar proyecto",subtitle:"APX indexará .apc/, agents y AGENTS.md en esa carpeta.",path_label:"Ruta absoluta",path_hint:"Equivalente a apx project add /ruta/al/proyecto",path_placeholder:"/Volumes/SSDT7Shield/proyectos_varios/mi-proyecto",register:"Registrar",path_required:"Ruta requerida.",registered:"Proyecto #{id} registrado.",search_btn:"Buscar",picker_prompt:"Elegí la carpeta del proyecto",browser_unavailable:"Explorador no disponible hasta reiniciar daemon. Pegá ruta manual.",no_folders:"Sin carpetas."},settings:{title:"Settings",subtitle:"Preferencias del panel + diagnóstico del daemon local.",appearance:"Apariencia",light_mode:"Claro",dark_mode:"Oscuro",system_mode:"Sistema",language:"Idioma",daemon:"Daemon",daemon_sub:"Estado del proceso local que sirve esta web y orquesta los agentes.",engines:"Engines disponibles",engines_sub:"Adaptadores LLM compilados con el daemon.",token:"Token para esta sesión",token_sub:"Si esta web no logró auto-cargar el token, pegalo acá.",token_active:"(ya hay token activo)",token_paste:"Pegá el bearer del daemon",token_saved:"Token guardado.",devices:"Dispositivos pareados",devices_sub:"GET /pair/list. Revocar invalida ese bearer en el daemon.",devices_empty:"No hay clientes pareados todavía.",devices_revoke_confirm:"Revocar cliente {id}?",devices_revoke_success:"Cliente revocado.",devices_pair_btn:"Vincular dispositivo",devices_pair_title:"Vincular dispositivo",devices_pair_desc:"Escaneá el QR con la cámara del celu para entrar directo, o pegá el código en la otra PC.",devices_pair_scan:"Escaneá con la cámara del teléfono — te abre la web ya vinculada.",devices_pair_code:"O pegá este código en la pantalla de pairing:",devices_pair_url:"URL de acceso",devices_pair_link:"O copiá este link y abrilo en el otro dispositivo (entra solo):",devices_pair_copy:"Copiar",devices_pair_copied:"Link copiado al portapapeles.",devices_pair_copied_code:"Código copiado.",devices_pair_expires:"Expira en {s}s",devices_pair_expired:"El código expiró.",devices_pair_regen:"Generar otro",devices_pair_waiting:"Esperando que el dispositivo confirme…",devices_pair_done:"Dispositivo vinculado ✓",devices_pair_localhost_only:"Solo se pueden generar códigos desde la PC del daemon (localhost).",devices_last_seen:"visto:",devices_never:"nunca",devices_revoke:"Revocar",account_section:"Cuenta",agents_section:"Agentes & modelos",channels_section:"Canales & dispositivos",modules_section:"Módulos",advanced_section:"Avanzado",tabs:{identity:"Identidad",super_agent:"Super-agente",profile:"Perfil del agente",engines:"Engines & modelos",telegram:"Telegram",devices:"Dispositivos",advanced:"Avanzado"},profile:{title:"Perfil del agente",subtitle:"Un oficio instalable para el super-agente: qué hace con su día y cuándo te habla. Distinto del nombre del agente (eso está en Identidad).",vanilla_hint:"No hay ningún perfil activo. APX se comporta exactamente como siempre — el prompt del super-agente es idéntico al de una instalación limpia.",none_available:"No hay perfiles disponibles todavía.",active:"activo",activate:"Activar",replace_active:"Reemplazar el activo",deactivate:"Desactivar",deactivate_title:"¿Desactivar el perfil?",deactivate_confirm:"APX vuelve a vanilla. Las rutinas del perfil se deshabilitan pero no se borran, y tu configuración, tareas y memoria quedan intactas: volver a activarlo restaura todo.",activated:"Perfil activo",deactivated:"Perfil desactivado — APX está en vanilla",token_cost:"Costo de prompt",over_budget:"excede su presupuesto declarado",settings_title:"Configuración del perfil",settings_subtitle:"Los valores en blanco toman el default del paquete. Cambiar un horario reprograma la rutina de verdad.",saved:"Configuración guardada",saved_with_routines:"Configuración guardada y rutinas reprogramadas",doctor_title:"Diagnóstico",doctor_clean:"Todo en orden.",preview_title:"Bloque de prompt",preview_subtitle:"Exactamente lo que recibe el modelo, con tus valores ya sustituidos.",preview_empty:"(vacío)"},identity:{title:"Identidad",subtitle:"Datos del usuario. Configuración del agente va en Super-agente.",agent_name:"Nombre del agente",owner_name:"Tu nombre",personality:"Personalidad",owner_context:"Contexto del dueño",owner_context_hint:"Quién sos, en qué trabajás, qué le interesa al agente saber de vos.",language:"Idioma preferido",timezone:"Timezone (IANA)",timezone_hint:"Detectado automáticamente — buscá para cambiar.",saved:"Identidad guardada."},super_agent:{title:"Super-agente",subtitle:"Personalidad, modelo, prompt y modos del super-agente.",personality:"Personalidad",model:"Modelo activo",model_hint:"Ej: anthropic:claude-sonnet-4.5, ollama:gemma2:9b",permission_mode:"Permission mode",system:"Prompt extra (system)",system_hint:"Texto que se prepende al system prompt base.",system_ph:"(Vacío = se usa el prompt base de core/agent/prompts/super-agent-base.md)",fallback_title:"Fallback chain",fallback_hint:"Si el modelo activo falla, prueba estos en orden.",fallback_add:"Agregar modelo a la cadena",saved:"Super-agente guardado.",enabled_label:"Super-agente habilitado",model_active:"Modelo activo (router)",model_configure:"Configurar en Modelos",behavior_subtitle:"Comportamiento del super-agente. El modelo y la cadena de fallback se configuran en el Router de modelos."},engines_keys:{title:"API keys de modelos",subtitle:"Cada engine guarda su key en ~/.apx/config.json. Los valores ya seteados muestran sufijo seguro.",ollama_url:"Ollama URL",ollama_hint:"Por defecto: http://127.0.0.1:11434",key_label:"API key",key_placeholder:"(no seteada)",clear:"Borrar key",saved:"Key guardada.",cleared:"Key borrada."},telegram_global:{title:"Telegram (default)",subtitle:"Canal default — los proyectos pueden overridear con su propio canal.",bot_token:"Bot token",chat_id:"Chat ID por defecto",poll_interval:"Poll interval (ms)",respond_with_engine:"Respond with engine",enabled:"Polling habilitado",saved:"Telegram guardado."},advanced:{title:"Avanzado",subtitle:"Editor raw del ~/.apx/config.json. Los secretos se ven *** set *** pero podés escribir uno nuevo.",write:"Aplicar cambios",written:"Config aplicada y daemon recargado.",reload_success:"Config recargada."}},project:{not_found:"Roby no encontró el proyecto {pid}: quizás se desregistró o el ID es incorrecto.",rebuild:"Rebuild context",rebuild_done:"Rebuild OK.",unregister_confirm:"¿Desregistrar {label}? La carpeta no se borra.",unregistered:"Desregistrado.",base_subtitle:"Espacio general · super-agente",danger:{title:"Zona peligrosa",subtitle:"Acciones que afectan el registro del proyecto en APX. No tocan archivos del repo.",rebuild_desc:"Re-escanea .apc/, MCPs y agents y regenera el contexto del super-agente para este proyecto.",unregister_desc:"Quita el proyecto del registry de APX. La carpeta del disco se mantiene intacta.",rebuild_confirm_title:"Rebuild context",rebuild_confirm_desc:"Regenerar contexto de {label}.",rebuild_long:"Vuelve a leer la config APC, lista MCPs y agents disponibles, y reconstruye el system prompt del super-agente. Es seguro de correr — no borra nada. Usalo después de tocar .apc/ a mano o si los cambios no se reflejan.",unregister_confirm_title:"Desregistrar proyecto",unregister_long:"El proyecto deja de aparecer en `apx`. Los archivos del disco (.apc/, código, todo) se mantienen. Podés volver a registrarlo con `apx project register <path>`."},nav:{overview:"Overview",chat:"Chat",config:"Config",telegram:"Telegram",agents:"Agents",routines:"Rutinas",tasks:"Tasks",mcps:"MCPs",artifacts:"Artifacts",vars:"Variables",logs:"Logs",memories:"Memorias",structure:"Estructura",docs:"Docs",files:"Archivos"},sections:{workspace:"Workspace",content:"Contenido",automation:"Automatización",knowledge:"Conversaciones",config:"Config"},overview:{tasks_open:"Tasks abiertas",routines:"Rutinas",routines_active:"Rutinas activas",agents:"Agents",mcps:"MCPs",artifacts:"Artifacts",chat:"Chat (super-agent)",chat_value:"abrir",roster:"Equipo",no_agents:"Todavía no hay agentes.",orchestrators:"Orquestadores",specialists:"Especialistas",recent_tasks:"Tasks recientes",no_activity:"No hay tasks abiertas.",brain_title:"Cerebro del equipo",brain_desc:"El mapa completo de agentes — los orquestadores en el núcleo y sus especialistas en racimo alrededor. Clic en un nodo para abrirlo.",brain_core:"Equipo"},artifacts:{title:"Artifacts",subtitle:"Scripts y archivos reutilizables guardados en el proyecto. Los crean los agentes; podés verlos, ejecutarlos, renombrarlos o eliminarlos."},chat:{title:"Chat con agente",subtitle:"Chat directo con el agente del proyecto.",live_title:"Chat con {agent}",superagent_title:"Chat con {persona}",superagent_subtitle:"Chat con {persona} — el super-agente APX. Puede usar tools (proyectos, tasks, mcps, agentes).",loaded_subtitle:"Conversación cargada con {slug}. Lo que mandes se agrega a este chat.",thread_subtitle:"Historial con {persona} en {channel}. Si respondés acá, la conversación sigue desde la web.",empty:"Mandá un mensaje para arrancar la conversación.",placeholder:"Escribí algo y enter para enviar (shift+enter = nueva línea)",send:"Enviar",stop:"Stop",new_session:"Nueva sesión",delete:"Borrar",delete_confirm_title:"Borrar chat",delete_confirm_desc:"Esta acción no se puede deshacer. Se elimina para siempre el historial de este chat.",deleted:"Chat borrado.",meta_created:"Creado {date} · {channel}",meta_new:"Chat nuevo · {channel}",copy:"copiar",copied:"Copiado.",stopped_marker:" [detenido]",create_agent:"Crear agente",create_agent_title:"Crear agente",create_agent_desc:"Necesario para iniciar chat en proyecto.",role_label:"rol",model_label:"modelo",model_hint:"ej. openai:gpt-5, groq:llama-3.3-70b-versatile",master_label:"Agente master",list:{title:"Chats",new:"Nuevo",search:"Buscar chats…",all_agents:"Todos los agentes",empty:"No hay conversaciones todavía. Arrancá una desde la derecha.",count:"{n} en total",pick_agent:"Elegí un agente"}},tasks:{title:"Tasks (TODOs)",subtitle:"Append-only JSONL en ~/.apx/projects/<id>/tasks/.",add:"agregar",add_label:"Nueva task",add_placeholder:"ej. revisar bug del scroll",empty:"No hay tasks {state}.",empty_open:"No hay tasks abiertas.",created:"Task creada.",create_error:"no pude crear la task",done:"✓ done",drop:"✗ drop",reopen:"↻ reopen",due:"vence",via:"via",aria_done:"marcar done",aria_drop:"descartar task",aria_reopen:"reabrir task"},global_tasks:{any_status:"cualquier estado",title:"Tasks (todos los proyectos)",subtitle:"Tareas agregadas de todos los proyectos registrados.",empty:"Sin tasks.",due:"vence",go_project:"Ir al proyecto"},routines:{title:"Heartbeats / Routines",subtitle:"Cron, every:Nm, once:ISO. Cada rutina dispara un agente o un shell.",empty:"Sin rutinas. Creá una arriba.",new:"nueva",new_btn:"Nueva",delete_confirm:"Borrar rutina {name}?",delete_confirm_body:"Esta acción no se puede deshacer.",saved:"Rutina guardada.",paused:"pausada",next_run:"próxima:",last_run:"última:",enabled_hint:"Activa · corre según el intervalo",disabled_hint:"Pausada · solo con el botón Run",enabled_label:"Habilitada",new_title:"Nueva rutina",edit_title:"Editar {name}",dialog_desc:"Se guarda en .apc/routines.json. La rutina corre mientras el daemon está activo.",name_field:"Nombre (name)",name_no_edit:"No se puede cambiar al editar.",kind_field:"Acción (kind)",schedule_field:"Intervalo (schedule)",schedule_hint:"Elegí un preset o escribilo a mano. Manual = solo corre con el botón Run.",vars_title:"Variables disponibles",what_happens:"Qué va a pasar",list_title:"Rutinas",detail_empty:"Elegí una rutina de la lista.",edit_btn:"Editar",edit_hint:"Abrir el editor: tipo, intervalo, prompt, pre/post y variables.",block_pre:"Pre-commands",block_post:"Post-commands",block_prompt:"Prompt",block_text:"Texto",block_command:"Comando",block_empty:"(vacío)",runs_title:"Ejecuciones",runs_empty:"Sin ejecuciones todavía.",runs_close:"Cerrar",runs_no_detail:"Sin más detalle.",runs_output:"Salida",status_ok:"ok",status_error:"error",status_skipped:"salteada",agent_field:"Agente (spec.agent)",agent_hint:"Quién ejecuta la rutina.",agent_loading:"cargando…",agent_pick:"— elegí un agente —",prompt_exec:"Prompt (spec.prompt)",prompt_exec_ph:"qué pendiente hay para hoy?",prompt_super:"Prompt (spec.prompt)",prompt_super_ph:"resumí el estado del proyecto",pre_field:"Pre-commands (pre_commands)",pre_hint:"Shell ANTES del prompt. Uno por línea.",post_field:"Post-commands (post_commands)",post_hint:"Shell DESPUÉS del prompt. Uno por línea.",tg_channel:"Canal (spec.channel)",tg_chat_id:"Chat ID (spec.chat_id)",tg_text:"Mensaje de Telegram (spec.text)",tg_text_hint:"Mensaje fijo a enviar. No usa modelo.",shell_field:"Comando (spec.command)",shell_hint:"Corre tal cual en el shell. Sin prompt ni pre/post.",hb_channel:"Canal (spec.channel)",hb_message:"Mensaje (spec.message)",name_required:"name requerido",save_error:"save falló",run_error:"run falló",toggle_error:"toggle falló",delete_error:"delete falló",run_success:"{name} disparada.",run_confirm:"¿Ejecutar la rutina {name} ahora?",run_confirm_body:"Corre la acción una vez, sin esperar al horario.",running:"Ejecutando…",delete_success:"borrada."},agents:{title:"Agents",subtitle:"Definidos en .apc/agents/<slug>.md.",subtitle_full:"Definidos en .apc/agents/<slug>.md. La memoria runtime vive en ~/.apx/projects/<id>/agents/<slug>/.",empty:"Sin agents. Agregá uno con <code>apx agent add</code> o el botón.",empty_text:"Sin agents. Agregá uno con `apx agent add` o el botón de arriba.",new:"Agente",created:"Agent {slug} creado.",slug_invalid:"slug debe matchear /^[a-z][a-z0-9_-]*$/",hierarchy:"Jerarquía",list_view:"Lista",import:"Importar",chat:"Chat",view:"Ver",orchestrator:"Orquestador",new_title:"Nuevo agent",new_desc:"POST /projects/:pid/agents — escribe .apc/agents/<slug>.md.",slug_label:"slug",slug_ph:"cody",role_label:"role (opcional)",role_ph:"code refactor",model_label:"model (opcional)",model_hint:"ej. ollama:gemma2:9b, openai:gpt-4o-mini",lang_label:"language (opcional)",desc_label:"description (opcional)",desc_ph:"Qué hace este agente…",skills_label:"skills (coma)",skills_ph:"skill-a, skill-b",tools_label:"tools (coma)",tools_ph:"tool-a, tool-b",parent_label:"reporta a (parent, opcional)",parent_hint:"Subagente de un orquestador.",none_parent:"— ninguno —",master_label:"Orquestador (master)",create_success:"Agent {slug} creado.",create_error:"create falló",import_title:"Importar del vault",import_desc:"Plantillas en ~/.apx/agents. Se registran en este proyecto (.apc/agents/<slug>.md).",import_empty:"Sin plantillas en el vault.",import_success:"Importado: {slug}",import_already:"ya está",import_btn:"Importar"},agent_detail:{not_found:"Agente no encontrado.",chat_btn:"Chat con {slug}",reports_to:"↳ reporta a",no_threads:"Sin threads.",no_activity:"Sin actividad registrada.",threads_recent:"Threads recientes",subagents:"Subagentes",subagents_desc:"Agentes que reportan a este orquestador.",config_title:"Configuración del agente",type_label:"Tipología (type)",area_label:"Área",area_hint:"ej. operaciones, marketing",area_ph:"operaciones",role_label:"Role",parent_label:"Reporta a (parent)",none_parent:"— ninguno —",model_label:"Modelo base",model_hint:"Vacío = usa el modelo del Router (default). Setealo solo para forzar un modelo a este agente.",model_ph:"(vacío = router default)",skills_label:"Skills (coma)",bio_label:"Bio / descripción",system_label:"System prompt",system_hint:"Define personalidad y comportamiento (cuerpo del AGENT.md).",master_label:"Orquestador (master)",delete_btn:"Borrar agente",save_btn:"Guardar cambios",delete_confirm:'Borrar el agente "{slug}"? Se elimina .apc/agents/{slug}.md y sus datos runtime locales.',update_success:"Agente actualizado.",delete_success:"Agente borrado.",tools_hint:"Qué tools puede usar el agente. Tocá para activar/desactivar; o editá la lista abajo.",tools_custom_ph:"lista (coma): echo, http_fetch",memory_title:"Memoria del agente",memory_empty:"(memoria vacía)",memory_saved:"Memoria guardada.",records_title:"Records",records_desc:"Log de actividad del agente (mensajes/acciones). Lo más nuevo primero.",sleep_title:"Sleep / Heartbeat",sleep_desc:"Estado de ejecución del agente, derivado de sus rutinas.",sleep_deep:"Deep sleep · sin heartbeat",sleep_deep_desc:"Este agente no tiene ninguna rutina que lo dispare. No se ejecuta de forma autónoma; solo responde cuando lo invocás (chat / tarea).",brain_title:"Brain",brain_desc:"Grafo de relaciones reales del agente: memoria, threads, tasks, heartbeats y jerarquía. (primera versión — lo refinamos)",brain_empty:"Aún no hay relaciones para graficar (sin memoria, threads, tasks ni rutinas).",msgs_count:"msgs"},mcps:{title:"MCP servers",subtitle:"3 scopes: Runtime > Shared > Global. Conflictos arriba si los hay.",empty:"Sin MCPs configurados.",new:"MCP",delete_confirm:"Borrar MCP {name} de scope {scope}?",conflicts:"⚠ Conflictos: {names}",conflict_detail:"{name} está definido en {winner} y {loser}. Se usa {winner}; {loser} queda ignorado.",new_title:"Nuevo MCP",edit_title:"Editar MCP",new_desc:"Se guarda según el scope elegido. Los valores con ${var.X} se resuelven al arrancar el MCP.",scope_label:"Scope",scope_runtime:"Runtime",scope_shared:"Shared",scope_global:"Global",source_runtime:"Runtime",source_apc:"APC / Shared",source_claude:"Claude",source_codex:"Codex",source_cursor:"Cursor",source_vscode:"VS Code",source_roo:"Roo",source_gemini:"Gemini",scope_runtime_desc:"Solo este proyecto · con secrets · no se commitea (~/.apx/projects/<id>/mcps.json)",scope_shared_desc:"Solo este proyecto · committeable · sin secrets (.apc/mcps.json)",scope_global_desc:"Todos los proyectos de esta máquina (~/.apx/mcps.json)",transport_stdio:"stdio",transport_http:"HTTP",transport_stdio_desc:"Proceso local — `command` + args",transport_http_desc:"Endpoint remoto — URL + headers",transport_label:"Transport",name_label:"Nombre",name_ph:"my-mcp",cmd_label:"Comando",cmd_ph:"npx",args_label:"Args",args_hint_tokens:"Una entrada por argumento. Usá el botón + para insertar variables.",env_label:"Env",env_hint_tokens:"Pares clave/valor. Los valores aceptan ${var.NOMBRE} (botón + a la derecha).",env_empty:"Sin variables de entorno.",url_label:"URL",url_ph:"https://example.com/v2/mcp",headers_label:"Headers",headers_hint:"Pares clave/valor — típicamente Authorization: Bearer ${var.TOKEN}.",headers_empty:"Sin headers.",enabled_label:"Habilitado",add_btn:"Agregar",save_btn:"Guardar",add_arg:"Agregar arg",edit_btn:"Editar",test_btn:"Probar",logs_btn:"Logs",testing:"Probando…",test_ok:"OK · {n} tools disponibles",tools_count:"{n} tools",logs_title:"Logs · {name}",logs_empty:"Sin logs todavía. Arrancá el MCP llamando un tool o probando.",logs_events:"Eventos recientes",logs_stderr:"stderr (últimos 4KB)",logs_panel_title:"Live logs",logs_panel_pick:"elegí un MCP",logs_panel_hint:"Click un MCP de la lista para ver lo que está pasando en vivo.",logs_panel_idle:"Sin actividad. Apretá Probar para arrancarlo.",name_required:"Nombre requerido",removed:"eliminado",added:"MCP agregado.",updated:"MCP actualizado."},vars:{title:"Variables",subtitle_project:"Reemplazan ${var.NOMBRE} al cargar MCPs y plantillas. Las del proyecto ganan sobre las globales. Se guardan fuera del repo (~/.apx/, chmod 0600).",subtitle_base:"Variables globales — disponibles para todos los proyectos. Se guardan en ~/.apx/vars.json (chmod 0600).",empty:"Sin variables todavía.",new:"Variable",new_title:"Nueva variable",edit_title:"Editar variable",new_desc:"Se referencia como ${var.NOMBRE} en cualquier campo que soporte interpolación.",reveal_all:"Mostrar valores",reveal:"Mostrar",hide:"Ocultar",filter_label:"Mostrar:",filter_all:"Todas",filter_project:"Sólo proyecto",filter_global:"Sólo globales",scope_label:"Scope",scope_project:"proyecto",scope_project_desc:"Sólo este proyecto. Pisa la global con mismo nombre.",scope_global:"global",scope_global_desc:"Disponible en todos los proyectos.",name_label:"Nombre",name_hint:"Mayúsculas, dígitos y _. P. ej.: MY_API_KEY, GITHUB_TOKEN.",value_label:"Valor",value_hint:"Se guarda en disco con permisos 0600. Nunca se commitea.",value_edit_ph:"(dejá vacío para no cambiarlo… aún no soportado, pegá el valor de nuevo)",add_btn:"Agregar",save_btn:"Guardar",edit_btn:"Editar",delete_btn:"Borrar",delete_confirm:"¿Borrar {name} ({scope})?",removed:"Variable eliminada.",added:"Variable agregada.",updated:"Variable actualizada.",name_required:"Nombre requerido.",value_required:"Valor requerido."},threads:{title:"Chats",subtitle:"Conversaciones por agent (vacío = ningún log persistido todavía).",no_agents:"No hay agents. Las conversaciones requieren un agent configurado.",pick:"Elegí un agent para ver sus conversaciones.",empty:"No hay conversaciones para {slug}.",conversation_title:"Conversación {id}",messages:"mensajes",via:"via"},config:{title:"Config rápida",subtitle:"Override del proyecto. Se escribe en {path}.",model:"super_agent.model",model_hint:"ej. anthropic:claude-sonnet-4.5, ollama:gemma2:9b",perm:"super_agent.permission_mode",route:"route_to_agent",route_hint:"Slug del agent que atiende por defecto en este proyecto.",use_global:"(usa global)",saved:"Guardado.",nothing:"Nada para guardar.",raw_title:"Config (JSON crudo)",raw_subtitle:"Pegá el objeto entero — equivale a PUT del archivo.",raw_save:"Reemplazar config",raw_done:"Config sobrescrita.",effective:"Effective config (read-only)",effective_sub:"Lo que ve realmente el daemon (global ⊕ override).",section_title:"Config proyecto",section_desc:"APC metadata y overrides separados. General APX vive en Settings > Config.",effective_read:"Lectura: global APX + override proyecto.",save_project:".apc/project.json guardado.",save_override:".apc/config.json guardado.",save_fields_success:"Overrides guardados.",save_meta_success:"Project metadata guardado.",no_data:"Sin datos.",tab_settings:"Settings",tab_project:"Project"},telegram:{title:"Canal de Telegram (override)",subtitle:"Si seteás un canal acá, los mensajes generados por este proyecto se mandan ahí en lugar del default.",use_default:"Usar el canal default",bot_token:"Bot token (override)",chat_id:"Chat ID (override)",saved:"Override guardado.",cleared:"Override eliminado — vuelve al default.",override_active:"override activo",channel_badge:"Canal {name}",no_override:"Sin override. Los mensajes de este proyecto van al canal default.",respond_engine:"Responder con engine",route_agent:"route_to_agent",route_hint:"Slug del agent que atiende (vacío = super-agent).",bot_hint_none:"Si vacío, hereda del default."},memories:{sidebar_title:"Memorias",general_group:"General",general_item:"Memoria del proyecto",project_title:"Memoria del proyecto",project_desc:"Hechos durables a nivel proyecto. .apc/memory.md — la leen los agentes y el super-agente.",project_ph:`# Memoria del proyecto
|
|
762
762
|
|
|
763
763
|
Hechos estables que cualquier agente debería saber…`,agents_title:"Memorias de agentes",agents_desc:"Memoria individual por agente. ~/.apx/projects/<id>/agents/<slug>/memory.md",no_agents:"Sin agentes en este proyecto.",saved:"Memoria guardada.",empty:"(memoria vacía)",chars:"chars · Markdown",save_btn:"Guardar"}},base:{title:"Base",subtitle:"Espacio general · super-agente",nav_general:"General",nav_activity:"Actividad",nav_system:"Sistema",workspaces_title:"Workspaces",workspaces_desc:"Todos los proyectos registrados en APX.",workspaces_new:"Nuevo proyecto",workspaces_empty:"Sin proyectos. Agregá uno con el botón de arriba.",sessions_title:"Sessions",sessions_desc:"Sesiones de todos los engines (apx · claude · codex), más nuevas primero.",sessions_desc_scoped:"Sesiones en la carpeta de este proyecto ({path}), todos los engines, más nuevas primero.",sessions_all:"Todos los engines",sessions_empty:"Sin sesiones.",sessions_error:"No pude leer las sesiones: {msg}",sessions_search_ph:"Buscar sesiones…",sessions_deep:"Profundo",sessions_deep_tip:"También busca dentro de los transcripts (más lento)",sessions_clear:"Limpiar filtros",sessions_refresh:"Refrescar lista",sessions_no_match:"Ninguna sesión coincide con «{q}».",sessions_act_cmd:"Copiar comando apx",sessions_act_ask:"Pedir a {name} que continúe",sessions_act_folder:"Abrir carpeta",sessions_act_path:"Copiar ruta",sessions_cmd_copied:"Comando copiado — pegalo en tu terminal",sessions_path_copied:"Ruta copiada",sessions_copy_failed:"No se pudo copiar",sessions_no_folder:"Esta sesión no tiene carpeta",sessions_no_path:"Esta sesión no tiene ruta",sessions_folder_failed:"No se pudo abrir la carpeta: {msg}",defaults_title:"Agent defaults",defaults_desc:"Plantillas globales del vault. Las bundled vienen con APX y siempre están; las que crees o edites quedan en ~/.apx/agents y se superponen. Importalas a un proyecto desde Agents › Importar.",defaults_show_removed:"Mostrar removidos",defaults_new:"Nuevo",defaults_empty:"Sin plantillas en el vault.",defaults_hide:"Ocultar",defaults_restore:"Restaurar",defaults_edit:"Editar",defaults_remove:"Ocultar",defaults_delete:"Borrar",defaults_tombstone_msg:'Ocultar el default "{slug}"? Es bundled — quedá tombstoneado y lo recuperás con Restaurar.',defaults_delete_msg:'Borrar el template "{slug}"?',defaults_hidden:"Ocultado.",defaults_deleted:"Borrado.",defaults_restored:"Restaurado.",defaults_new_title:"Nuevo template",defaults_new_desc:"POST /agents/vault — se guarda en ~/.apx/agents/<slug>.md",defaults_edit_title:'Editar "{slug}"',defaults_bundled_desc:"Es un default bundled. Al guardar se hace copy-on-write a ~/.apx/agents/<slug>.md (queda como override).",defaults_user_desc:"PATCH /agents/vault/:slug — edita el archivo en ~/.apx/agents.",defaults_master_label:"Agente master",defaults_slug_invalid:"slug inválido (debe matchear /^[a-z][a-z0-9_-]*$/)",defaults_created:'Template "{slug}" creado.',defaults_saved:'Template "{slug}" guardado.'},logs:{title:"Logs",desc_global:"Actividad del daemon (canales globales: telegram, direct…). ~/.apx/messages/<channel>/.",desc_project:"Actividad del proyecto. ~/.apx/projects/<id>/messages/.",filter_channel:"filtrar canal (ej. telegram)",filter_dir:"dirección",all_directions:"Todas las direcciones",in:"Entrada (in)",out:"Salida (out)",filter_type:"tipo",all_types:"Todos los tipos",search_text:"buscar en el texto…",count_of:"de",no_activity:"Sin actividad.",no_activity_ch:'Sin actividad en el canal "{ch}".',error:"No pude leer los mensajes: {msg}",show_more:"ver más",show_less:"ver menos",daemon_errors:"Errores del daemon (~/.apx/logs/errors.jsonl)",no_errors:"Sin errores registrados. 🎉"},telegram_contacts:{title:"Contactos de Telegram",desc:"Quién le escribe a los bots. El rol define qué herramientas puede usar; un invitado no tiene permisos hasta que le asignes un rol.",empty:"Todavía no hay contactos — se registran solos cuando alguien escribe a un bot.",owner_badge:"dueño",assign_role:"Asignar rol",owner_hint:"Es dueño de un canal — cambialo desde el canal",removed:"Contacto eliminado.",delete_confirm:"¿Borrar el contacto {name}?",last_seen:"visto:",tools_all:"tools: todas",tools_none:"tools: ninguna",tools_label:"tools:"},telegram_channels:{title:"Canales",desc:"Cada canal es un bot que el daemon polea. Acá podés añadir/quitar canales, cambiar el agente que contesta, el proyecto al que pertenece y su dueño.",new_btn:"Nuevo canal",empty:"Todavía no hay canales — agregá el primero.",removed:"Canal eliminado.",delete_confirm:"¿Borrar el canal {name}?",no_owner:"sin dueño (se reclama al primer DM)",owner_label:"dueño:"},telegram_channel_dialog:{new_title:"Nuevo canal de Telegram",edit_title:"Editar canal: {name}",name_label:"name (slug interno)",token_label:"bot_token",chat_id:"chat_id",project_label:"project",project_hint:"Slug o id del proyecto al que pinear este canal (opcional).",route_label:"route_to_agent",route_hint:"Agente que contesta; vacío = super-agent APX.",owner_label:"owner_user_id",owner_hint:"user_id de Telegram del dueño de este canal. Override del rol global a 'owner' acá. Si lo dejás vacío, el primer mensaje privado lo reclama.",owner_ph:"889721252",respond_label:"Responder con engine (no echo)",name_required:"name requerido",saved:"Canal guardado."},telegram_send_dialog:{title:"Enviar a {name}",default_msg:"Mensaje de prueba desde el panel de APX ✅"},telegram_roles:{title:"Roles",desc:"Cada rol define qué herramientas del super-agent puede usar quien lo tenga asignado. 'owner' siempre = todas; 'guest' siempre = ninguna (solo chat).",empty:"No hay roles definidos.",tools_all:"todas las herramientas",tools_none:"ninguna herramienta",builtin:"built-in",delete_confirm:'¿Borrar el rol "{name}"?',removed:"Rol eliminado.",saved:'Rol "{name}" guardado.',name_required:"Nombre requerido.",builtin_error:'"{name}" es un rol built-in.',new_title:"Nuevo rol o reemplazar uno custom",name_label:"Nombre",name_ph:"editor",tools_label:"Tools (separadas por coma)",tools_hint:"Vacío = ninguna. Ejemplos: call_agent, list_tasks, create_task.",tools_ph:"call_agent, list_tasks",full_access:"Acceso total (todas las tools)",save_btn:"Guardar rol",delete_btn:"Borrar"},superagent:{title:"{persona}",badge:"super-agent · APX",desc:"Conversación rápida con tu super-agente. Tiene acceso a tools (proyectos, tasks, mcps, agentes); para un hilo más largo y persistente, abrí Chats.",empty:"Mandale un mensaje a {persona} para arrancar.",thinking:"{persona} está pensando…",talk:"Hablar con {persona}",new_chat:"Nuevo chat",placeholder:"Escribí y enter para enviar (shift+enter = nueva línea)…"},not_found:{title:"404",message:"Roby se perdió: esta página no existe o se movió.",home:"Volver al inicio"},ask_panel:{answers_header:"Respuestas",other:"Otro",other_placeholder:"Escribí tu propia respuesta acá",text_placeholder:"Escribí tu respuesta…",back:"Atrás",skip:"Omitir",next:"Siguiente",submit:"Enviar",status_waiting:"Esperando respuesta…",status_received:"Respuestas recibidas"},code_module:{title:"Code",badge:"super-agent",desc:"Sesiones de código estilo OpenCode. Elegí un proyecto, abrí una sesión y pedile que lea, planifique, edite o ejecute.",no_projects:"No hay proyectos registrados. Registrá uno con `apx project add` para usar Code.",sessions:"Sesiones",new_session:"Nueva sesión",untitled:"Nueva sesión",no_sessions:"Todavía no hay sesiones — creá una para empezar a codear.",pick_project:"Elegí un proyecto para ver sus sesiones.",rename:"Renombrar",delete:"Eliminar",delete_confirm:"¿Eliminar esta sesión? Se borra la transcripción; tus archivos quedan intactos.",empty_chat:"Mandá una instrucción de código para arrancar.",placeholder:"Pedí un cambio… (enter envía, shift+enter = nueva línea)",mode_build:"Build",mode_plan:"Plan",mode_build_hint:"Build — edita archivos y ejecuta comandos",mode_plan_hint:"Plan — solo lectura, propone cambios sin tocar archivos",tab_context:"Contexto",tab_changes:"Cambios",tab_artifacts:"Artifacts",artifacts_none:"Todavía no hay artifacts. Pedile al agente que cree un script en `artifacts/<nombre>`.",artifacts_count:"{n} artifact(s)",artifacts_copy_path:"Copiar path",artifacts_run:"Run",artifacts_run_hint:"Para ejecutarlo desde la terminal:",artifacts_delete:"Eliminar",artifacts_delete_confirm:"¿Eliminar este artifact? El archivo se borra del disco.",ctx_model:"Modelo",ctx_tokens:"Tokens",ctx_input:"Entrada",ctx_output:"Salida",ctx_messages:"Mensajes",ctx_breakdown:"Desglose de contexto",ctx_none:"Sin uso todavía — mandá un turno para ver tokens.",seg_system:"Sistema",seg_user:"Usuario",seg_assistant:"Asistente",seg_tool:"Tools",seg_other:"Otro",changes_none:"Todavía no hay cambios en esta sesión.",changes_no_git:"Los cambios necesitan un repo git. Este proyecto no lo es.",changes_files:"{n} archivo(s) cambiados",stopped:"[detenido]",close:"Cerrar",reload:"Recargar",discard_changes:"Descartar cambios",save_shortcut_hint:"Guardar (Cmd/Ctrl+S)",artifacts_rename:"Renombrar",artifacts_view:"Ver contenido",artifacts_edit:"Editar contenido",artifacts_preview:"Previsualizar",artifacts_preview_hint:"Abrir una previsualización en vivo en una pestaña local",artifacts_share:"Compartir",artifacts_share_hint:"Crear una URL pública por túnel para compartir esta preview",artifacts_stop_preview:"Detener preview",artifacts_preview_local:"Preview local",artifacts_preview_public:"URL pública",artifacts_copy_url:"Copiar URL",artifacts_preview_started:"Preview activa en {url}",tree_collapse_all:"Colapsar todo",terminal_clear:"Limpiar",terminal_close:"Cerrar terminal"},desktop_screen:{status_title:"Estado",autostart_title:"Arranque automático",shortcut_title:"Atajo de teclado",appearance_title:"Apariencia",activation_title:"Activación + transcripción",last_conv_title:"Última conversación",open_config:"Configuración"},voice_screen:{providers_title:"Proveedores de voz (TTS)",test_title:"Probar voz",stt_title:"Transcripción (STT)",configure_provider:"Configurar {name}"},deck_screen:{widgets_title:"Widgets",context_title:"Contexto APX",reload_manifest:"Recargar manifest",widget_native:"Widget nativo APX",widget_external:"Widget externo",preview_badge:"Vista previa",preview_title:"Deck — Próximamente",preview_body:"El módulo Deck todavía está en desarrollo y no fue lanzado aún. Lo volveremos a activar cuando Deck salga en una versión estable. Por ahora todo acá es de solo lectura y no se guardará ningún cambio."},memory_panel:{embeddings_title:"Embeddings (RAG)",embeddings_desc:"Modelo que vectoriza el historial de todos los canales para la memoria relevante. Igual que TTS/STT: elegí un proveedor y un modelo. 'Automático' prueba local primero y cae a offline si no hay nada disponible.",provider_label:"Proveedor",provider_hint:"Ollama es local y gratis. Gemini/OpenAI usan la API key de su sección en Modelos (o la de abajo).",mode_label:"Modo de selección",mode_hint:"Cadena cae al siguiente si uno falla; Único usa exactamente el proveedor elegido.",available:"disponible",unavailable:"no disp.",test_btn:"Probar embedding",reindex_btn:"Reindexar memoria",test_ok:"Embedding OK con {embedder}",test_failed:"Test falló: {msg}",reindexed:"Reindexado: {indexed} chunks (limpiados {cleared}).",reindex_failed:"Reindex falló: {msg}",save_failed:"No se pudo guardar: {msg}",provider_auto:"Automático (cadena: Ollama → Gemini → OpenAI → offline)",provider_ollama:"Ollama — local, sin API key (nomic-embed-text)",provider_gemini:"Gemini — free tier con key (text-embedding-004)",provider_openai:"OpenAI — text-embedding-3-small (cloud)",provider_tf:"Offline (term-frequency, sin modelo — degradado)",mode_chain:"Cadena (fallback automático)",mode_single:"Único (usa solo el elegido)",ollama_title:"Ollama (local)",ollama_desc:"Sin API key. Corre nomic-embed-text en tu Ollama local o cloud.",model_label:"Modelo",base_url_label:"Base URL",ollama_base_url_hint:"Vacío usa engines.ollama.base_url (default http://localhost:11434).",openai_title:"OpenAI",openai_desc:"text-embedding-3-small (1536 dims) u otro modelo compatible.",api_key_label:"API key",openai_key_hint:"Vacío reusa engines.openai.api_key. Dejalo en blanco para mantener la guardada.",gemini_title:"Gemini",gemini_desc:"text-embedding-004 (768 dims). Free tier con API key de Google.",gemini_key_hint:"Vacío reusa engines.gemini.api_key.",compaction_title:"Compactación de historial",compaction_desc:"Cuando un chat supera el umbral de turnos, los más viejos se resumen con un LLM liviano (local) y se guardan como [RESUMEN COMPACTADO], manteniendo el contexto acotado. Corre fuera del hot-path: el turno actual usa el resumen que ya exista.",threshold_label:"Umbral de compactación",threshold_hint:"Compactar una vez que el chat supera estos turnos (por defecto 60).",keep_recent_label:"Turnos recientes a preservar",keep_recent_hint:"Turnos verbatim que NUNCA se compactan (por defecto 40). Debe ser menor al umbral.",compact_model_label:"Modelo de compactación",compact_model_hint:"LLM liviano para resumir. Ideal uno local (Ollama) para no gastar. Formato proveedor:modelo.",compact_fallback_label:"Modelo de fallback",compact_fallback_hint:"Se usa si el de compactación falla. Vacío cae al modelo del super-agente.",compact_fallback_ph:"(vacío → modelo del super-agente)"},router_panel:{title:"Router de modelos",description:"Un único router general (sin casos por tarea). Elegí un proveedor y un modelo; si el activo falla, prueba la cadena de fallback en orden.",badge_default:"default",no_providers:"Agregá un proveedor abajo para poder elegir modelos.",active_model_label:"Modelo activo (default)",active_model_hint:"Proveedor + modelo. Se guarda como proveedor:modelo.",fallback_title:"Cadena de fallback",fallback_desc:"Si el modelo activo falla, prueba estos en orden. Click en uno para editarlo.",fallback_empty:"Sin fallback configurado.",add_to_chain:"Agregar a la cadena",done:"listo",save:"Guardar router",saved:"Guardado",saved_toast:"Router guardado.",provider_ph:"— proveedor —",provider_not_found:"⚠ {name} (no encontrado)",provider_not_configured:'El proveedor "{name}" no está configurado.'},routing_panel:{title:"Ruteo por contenido",description:"Elegí un modelo distinto por mensaje según su contenido (imagen, tamaño, canal, keywords). Aparte de la cadena de fallback de arriba.",signal_on:"Ruteo por contenido: ON ({n} reglas)",signal_on_empty:"Ruteo por contenido: ON (todavía sin reglas)",signal_off:"Ruteo por contenido: OFF",how_it_works:"¿Cómo funciona?",enable_label:"Activar ruteo por contenido",rules_title:"Reglas de ruteo",rules_desc:"Se evalúan de arriba hacia abajo; gana la primera regla que cumpla todas sus condiciones.",rules_empty:"Todavía sin reglas. Agregá algunas en el editor.",edit_rules:"Editar reglas (JSON)",hide_editor:"Ocultar editor",editor_label:"Reglas (array JSON)",json_hint:"Array de { model, when }. Claves de when: has_image, min_prompt_chars, max_prompt_chars, min_context_chars, channels[], keywords[]. when vacío = matchea todos los mensajes.",json_error:"JSON inválido: {msg}",json_not_array:"Las reglas tienen que ser un array JSON.",insert_example:"Insertar un ejemplo",when_any:"cualquier mensaje",when_image:"tiene imagen",when_no_image:"sin imagen",when_min_prompt:"prompt ≥ {n} chars",when_max_prompt:"prompt ≤ {n} chars",when_min_context:"contexto ≥ {n} chars",when_channels:"canales: {list}",when_keywords:"keywords: {list}",helper:"El ruteo elige un modelo por mensaje (imagen, tamaño, canal, keywords). Se compone con el failover: un modelo ruteado que esté caído cae por la cadena. Un override de modelo explícito por request siempre gana.",save:"Guardar ruteo",saved:"Guardado",saved_toast:"Ruteo por contenido guardado.",confirm_title:"¿Aplicar los cambios de ruteo?",confirm_body:"Esto cambia qué modelo atiende cada mensaje. El failover sigue aplicando si un modelo ruteado está caído.",confirm_on:"El ruteo por contenido va a quedar ON con {n} reglas.",confirm_off:"El ruteo por contenido va a quedar OFF (cada mensaje usa el router default).",confirm_apply:"Aplicar",cancel:"Cancelar"},engines_panel:{title:"Proveedores",new_btn:"Nuevo proveedor",description:"Proveedores LLM (API). Cada provider usa un engine/adapter (openai, ollama, …) con su key y URL.",empty:"Sin providers. Agregá uno con el botón de arriba.",add_card:"Agregar provider",saved:"Provider guardado.",saved_json:"Provider guardado (JSON).",deleted:"Provider borrado.",delete_confirm:"¿Borrar provider {name}?"},providers_modal:{new_title:"Nuevo proveedor",edit_title:"Editar {name}",description:"Proveedor LLM. El motor (engine) define qué adapter usa (openai, ollama, …).",list_models_hint:"Listar los modelos reales del proveedor",toggle_active:"Activo · click para desactivar",toggle_inactive:"Inactivo · click para activar",delete:"Borrar",custom:"Custom",json_mode:"JSON",form_mode:"Volver al formulario",json_label:"Config del provider (JSON)",json_hint:"Se guarda como engines.{slug} en config.json",json_help:"Debe ser un objeto JSON válido con al menos engine. El slug se toma del formulario.",name_label:"Nombre",name_ph:"Mi provider",engine_label:"Motor (engine)",base_url_label:"URL base (base_url)",base_url_hint:"Se completa sola al elegir un proveedor.",base_url_ph:"https://api.openai.com/v1",api_key_label:"API key",api_key_hint_existing:"Dejá en blanco para mantener la actual.",api_key_hint_env:"Se guarda como secreto. Env sugerida: {env}",api_key_hint:"Se guarda como secreto.",api_key_set:"…{suffix} (ya seteada)",model_label:"Modelo por defecto",load_models:"Cargar modelos",max_tokens_label:"Máx. tokens (max_tokens)",temperature_label:"Temperatura: {value}",pricing_summary:"Análisis de tokens / pricing (opcional)",context_limit_label:"Límite de contexto (tokens)",price_input:"$ entrada / 1M",price_output:"$ salida / 1M",price_cache_read:"$ cache read / 1M",price_cache_write:"$ cache write / 1M",model_limits_label:"Límites de contexto por modelo (JSON)",active_label:"Activo (los agentes pueden usarlo)",err_slug_required:"Slug requerido.",err_slug_required_form:"Slug requerido (en el formulario).",err_slug_exists:'Ya existe un provider "{slug}".',err_model_limits_json:"Límites de contexto por modelo: JSON inválido.",err_json_invalid:"JSON inválido: revisá la sintaxis.",err_json_object:"El JSON debe ser un objeto con la config del provider.",err_engine_missing:'Falta "engine" (ej. "anthropic", "ollama").',err_save:"Error al guardar.",err_no_models:"Sin modelos. ¿Key/URL correctas?",err_list_models:"No se pudo listar modelos."},providers_card:{active:"Activo",off:"Off",model:"Modelo",base_url:"Base URL",api_key:"API key",key_set:"✓ seteada",temp:"Temp",price_io:"$ in/out (1M)"},chat_ui:{copy:"Copiar",stop:"Detener",send:"Enviar",pick_model:"Elegir modelo (o Auto)",insert_variable:"Insertar variable",ctx_files:"archivos",ctx_actors:"{n} agentes/modelos",ctx_turns:"{n} turnos"},sidebar_ui:{toggle:"Mostrar/ocultar sidebar"},models_ui:{invalid_hint:"Modelo/proveedor no disponible"},global_config:{title:"Config APX"},agent_detail_extra:{skills_title:"Skills & tools"},voice_ui:{api_key_label:"API key",api_key_set:"…{suffix} (ya seteada)",api_key_keep_hint:"Dejá en blanco para mantener la actual.",api_key_secret_hint:"Se guarda como secreto. Env: {env}",api_key_reuse_hint:"Si lo dejás vacío, reusa {engine}. Env: {env}",err_save:"Error al guardar.",model_label:"Modelo",voice_label:"Voz",format_label:"Formato",output_format_label:"Formato de salida",voice_id_label:"Voice ID",voice_id_hint:"Voice id de ElevenLabs (vacío = default).",gemini_model_hint:"El TTS de Gemini todavía está en preview.",base_url_label:"Base URL (opcional)",base_url_hint:"Endpoint compatible con OpenAI. Vacío = OpenAI. Apuntalo a un servidor local (ej. un daemon QVox / Qwen3-TTS) para usar ese en su lugar.",openai_model_hint:"tts-1 / tts-1-hd para OpenAI. Dejalo vacío para que un servidor custom elija.",openai_voice_hint:"Preset de OpenAI (alloy…) o preset de tu servidor custom (ej. custom). Vacío = default del servidor.",openai_style_hint:"Voz base / instruct, usada por endpoints custom (la persona que se mantiene en todo el audio). El tts-1 de OpenAI la ignora.",style_label:"Estilo (cómo debería hablar)",style_hint:"Instrucción en lenguaje natural. Vacío = sin estilo. Ej.: 'hablá en un tono alegre y pausado'.",style_ph:"hablá en un tono alegre y enérgico",temperature_label:"Temperatura (opcional)",temperature_hint:"Temperatura de sampleo para endpoints custom. Vacío = default del servidor.",emotions_short:"Emociones",emotions_label:"Tags de emoción inline",emotions_hint:"Cuando hable este motor, deja que el agente meta tags tipo [happy]/[whisper] en las respuestas de voz para darles color. Activalo solo si este motor entiende los tags (ej. un endpoint QVox/Qwen3-TTS) — si no, se quitan antes de sintetizar.",emotions_tags_label:"Tags permitidos",emotions_tags_hint:"Separados por coma. Vacío = el set por defecto.",piper_bin_label:"Binario (bin)",piper_bin_hint:"Ruta o nombre del CLI de piper (PATH).",piper_model_label:"Modelo (.onnx)",piper_model_hint:"Ruta absoluta al modelo de voz de piper.",piper_speaker_label:"Speaker (opcional)",piper_speaker_hint:"Speaker id para modelos multi-voz.",mock_desc:"El engine mock genera un WAV de prueba en silencio. No tiene parámetros: sirve como fallback garantizado cuando no hay ningún otro engine configurado.",selection_mode:"Modo de selección",mode_chain_desc:"Cadena con fallback: usa el primer engine disponible siguiendo el orden de abajo.",mode_single_desc:"Solo engine default: siempre usa el elegido; el resto queda configurado para otros usos.",mode_chain_btn:"Cadena (router)",mode_single_btn:"Solo engine default",move_up:"Subir",move_down:"Bajar",badge_local:"local",badge_available:"disponible",badge_unavailable:"configurado, no disponible",badge_not_configured:"sin configurar",badge_default:"default",badge_custom:"custom",set_as_default:"Usar como default",configure:"Configurar",remove:"Quitar",remove_confirm:"¿Quitar este proveedor custom?",add_provider:"Agregar proveedor",new_provider:"Nuevo proveedor",custom_note:"Endpoint custom compatible con OpenAI.",custom_desc:"Cualquier endpoint de voz compatible con OpenAI (ej. un servidor local QVox / Qwen3-TTS).",label_label:"Nombre",label_hint:"Nombre para mostrar de este proveedor.",base_url_req_label:"Base URL",base_url_req_hint:"Requerido. El endpoint compatible con OpenAI, ej. http://127.0.0.1:5111/v1",api_key_optional_hint:"Opcional — solo si tu servidor pide key.",advanced:"Avanzado",custom_model_hint:"Opcional. La mayoría de los servidores locales lo ignoran (ej. QVox).",custom_voice_hint:"Opcional. Un preset que entienda tu servidor (ej. custom). Vacío = default del servidor.",custom_optional_ph:"(opcional)",stt_engine_label:"Engine de transcripción",stt_engine_hint:"Local usa faster-whisper (requiere python3 + faster-whisper). OpenAI usa la key de engines.openai.",stt_model_label:"Modelo local (whisper)",stt_model_hint:"Más grande = más preciso y más lento.",stt_language_label:"Idioma",stt_language_hint:'Para español, elegir "Español" mejora la precisión.',stt_provider_auto:"Automático (local, después remoto)",stt_provider_local:"Local — faster-whisper (offline)",stt_provider_openai:"OpenAI — Whisper-1 (cloud)",stt_provider_custom:"Custom — server OpenAI-compatible",stt_openai_model_label:"Modelo OpenAI",stt_openai_model_hint:"Por defecto whisper-1.",stt_custom_baseurl_label:"URL base (OpenAI-compatible)",stt_custom_baseurl_hint:"Ej: http://localhost:8000/v1 (mlx-audio en Metal) o http://192.168.1.50:9000/v1 (Radeon/NVIDIA en la red).",stt_custom_model_label:"Modelo",stt_custom_model_hint:"Ej: mlx-community/whisper-large-v3-turbo o large-v3.",stt_custom_key_hint:"Opcional — la mayoría de los servers locales no requieren key.",stt_hw_label:"Hardware detectado",stt_hw_recommended:"Recomendado",stt_hw_limited:"aceleración GPU limitada, se usa CPU",stt_backend_label:"Aceleración / Motor",stt_backend_hint:"Auto elige según tu hardware. Metal corre en la GPU (mlx); CPU usa faster-whisper.",stt_backend_auto:"Automático (recomendado)",stt_model_needs_download:"Falta descargar (~{size}). Hay que bajar el modelo para usar este motor.",lang_auto:"Detección automática",lang_es:"Español",lang_en:"Inglés",lang_pt:"Portugués",lang_fr:"Francés",lang_it:"Italiano",lang_de:"Alemán",test_default_text:"Hola, soy APX. Esto es una prueba de voz.",test_default_engine:"Default ({name})",test_default_chain:"Default (cadena)",test_unavailable_suffix:" · no disponible",test_empty_error:"Escribí algo para decir.",test_synth_error:"No se pudo sintetizar.",test_engine_label:"Engine",test_engine_hint:"Override del default para probar.",test_style_label:"Estilo (solo Gemini)",test_style_hint:"Cómo debería hablar. Vacío = sin estilo.",test_text_label:"Texto a decir",test_text_ph:"Escribí lo que querés que diga…",say_this:"Decir esto",stop:"Detener",replay:"Repetir",engine_result:"Engine",providers_desc:"Engines de síntesis, en orden de fallback. El estado lo reporta el daemon en vivo. Agregá tus propios endpoints compatibles con OpenAI.",providers_load_error:"No pude cargar los proveedores: {msg}",test_desc:"Elegí con qué engine sintetizar y, si aplica, cómo debería hablar.",stt_desc:"Engine de speech-to-text que usan el deck, Telegram y la CLI al escuchar.",toast_default_engine:"Engine default: {id}.",toast_mode_chain:"Modo: cadena con fallback.",toast_mode_single:"Modo: solo engine default.",toast_config_saved:"Configuración de voz guardada.",toast_provider_removed:"Proveedor eliminado.",err_label_required:"Falta el nombre.",err_base_url_required:"Falta la base URL.",toast_transcription_updated:"Transcripción actualizada."},telegram_ui:{channel_dialog_desc:"POST /telegram/channels (upsert) — PATCH /telegram/channels/:name (parcial).",bot_token_hint:"Token de BotFather. Se guarda en ~/.apx/config.json.",bot_token_hint_short:"Token de BotFather.",secret_set_replace:"(seteado — escribí para reemplazar)",secret_already_set:"(ya seteado)",empty_keep:"— vacío = mantener",message_sent:"Mensaje enviado.",message_label:"Texto",send_chat_id:"chat_id: {id}",default_apx:"APX por defecto",yes:"sí",no:"no",user_id_fallback:"user_id {id}",role_assigned:"{name} → {role}"},agents_form:{emoji:"Emoji",area:"Área",role:"Rol",no_role:"— sin rol —",autonomy:"Autonomía",autonomy_hint:"Cuánto puede hacer el agente sin pedir confirmación.",auto_total:"Total",auto_automatico:"Auto",auto_permiso:"Permiso"},structure:{title:"Estructura",subtitle:"Áreas y roles de la empresa. Las áreas agrupan agentes; los roles definen su función.",info:"Las áreas son agrupaciones opcionales. Los roles definen la función de un agente y pueden pertenecer a un área.",empty:"Todavía no hay áreas ni roles. Creá el primero arriba.",new_area:"Nueva área",new_role:"Nuevo rol",edit_area:"Editar área",edit_role:"Editar rol",create_area:"Crear área",create_role:"Crear rol",name:"Nombre",slug:"Slug",goal:"Objetivo",goal_hint:"Para qué existe esta área (opcional).",area:"Área",description:"Descripción",no_area:"— sin área —",roles:"Roles",add_role:"rol",no_roles:"sin roles",general_roles:"Roles generales",delete_area:"Borrar área",delete_role:"Borrar rol",delete_area_desc:'¿Borrar el área "{name}"? Sus roles quedan sin área, no se eliminan.',delete_role_desc:'¿Borrar el rol "{name}"?'},files:{docs_label:"Docs",files_label:"Archivos",new_doc:"Nuevo documento",new_doc_hint:"Podés usar carpetas: cases/onboarding/spec.md",empty:"No hay archivos.",docs_empty:"Todavía no hay documentación. Creá el primer documento.",truncated:"Listado recortado (demasiados archivos).",select_prompt:"Elegí un archivo para verlo.",save:"Guardar",saved:"Guardado.",deleted:"Eliminado.",created:"Documento creado.",edit:"Editar",preview:"Preview",discard:"Descartar",no_preview:"No hay preview para este archivo.",too_large:"Archivo demasiado grande para mostrar.",path_label:"Ruta del archivo",path_example:"ej. cases/onboarding/spec.md",create:"Crear"},tasks:{state_open:"abiertas",state_done:"hechas",state_dropped:"descartadas",status_pending:"pendiente",status_running:"corriendo",status_in_review:"en revisión",status_blocked:"bloqueada",done_label:"hecha",dropped_label:"descartada",detail_title:"Detalle de task",field_title:"Título",field_prompt:"Prompt",field_status:"Estado",field_agent:"Agente",field_creator:"Creada por",field_source:"Origen",field_created:"Creada",field_updated:"Actualizada",field_done:"Completada",prompt_ph:"Descripción / prompt de la task…",toggle_prompt:"Prompt",view_thread:"Ver conversación",mark_done:"Completar"},agents_ui:{model_router_default:"modelo: default del router",slug_kebab_hint:"kebab-case, ej. reviewer, my-agent, content-writer",comma_separated:"separadas por coma",body_hint:"markdown — extiende el system prompt del agente",source_user:"user",source_override:"override",source_bundled:"bundled",tab_explorer:"Explorador",type_none:"— sin tipo —",type_orchestrator:"Orquestador",type_orchestrator_desc:"Coordina el equipo y delega.",type_specialist:"Especialista",type_specialist_desc:"Experto en el dominio; corre tareas.",type_assistant:"Asistente",type_assistant_desc:"Ayudante conversacional.",type_worker:"Worker",type_worker_desc:"Corre tareas autónomas.",type_monitor:"Monitor",type_monitor_desc:"Vigila el estado y reporta.",stat_threads:"Threads",stat_records:"Records",stat_tasks:"Tasks",stat_heartbeats:"Heartbeats",uncategorized:"Sin categoría",brain_zoom_in:"Acercar",brain_zoom_out:"Alejar",brain_fit:"Ajustar a la vista",brain_fullscreen:"Pantalla completa",brain_exit_fs:"Salir de pantalla completa",brain_pan_hint:"scroll para zoom · arrastrá el fondo para mover",brain_expand:"Expandir cerebros",brain_collapse:"Colapsar",brain_open:"Abrir",brain_part_of:"Parte de",brain_branches:"Ramas",config_def_desc:"definición (frontmatter + system prompt).",memory_durable_desc:"hechos durables que el agente recuerda.",running:"running",paused:"pausada",last_error:"última: error",field_tick:"Tick",field_next_tick:"Próximo tick",field_last_tick:"Último tick",field_last_run:"Última corrida",tools_label:"Tools",kind_agent:"agente",kind_memory:"memoria",kind_thread:"thread",kind_task:"task",kind_routine:"rutina",kind_hierarchy:"jerarquía",nodes_drag_hint:"{n} nodos · arrastrá para reordenar",kind_exec_agent:"Agente del proyecto",kind_exec_agent_desc:"Corre un agente del proyecto con un prompt. Vos elegís cuál.",kind_super_agent:"Super-agente",kind_super_agent_desc:"Llama al super-agente APX con un prompt.",kind_telegram:"Telegram",kind_telegram_desc:"Manda un mensaje fijo a un canal de Telegram. Sin modelo ni agente.",kind_shell:"Shell",kind_shell_desc:"Corre un comando shell. Sin prompt ni pre/post — el comando es la acción.",kind_heartbeat:"Heartbeat",kind_heartbeat_desc:"No hace nada salvo escribir una línea en los logs cada vez que corre. Sirve para confirmar que el scheduler está vivo. Si no sabés si lo necesitás, no lo uses.",unit_seconds:"segundos",unit_minutes:"minutos",unit_hours:"horas",unit_days:"días",every_n_unit:"cada {n} {unit}",every_v:"cada {v}",preset_every_10m:"cada 10 min",preset_hourly:"cada hora",preset_daily_9am:"diario 9am",preset_weekdays_9am:"días hábiles 9am",preset_manual:"Manual",var_pre_output_prompt:"Salida de texto de los pre-commands. Se reemplaza dentro del prompt/texto antes de enviarlo. Útil para inyectar datos frescos (clima, una API) en la instrucción.",var_llm_output:"Respuesta final del agente o super-agente. Disponible en los post-commands como variable de entorno. Ej: reenviarla por Telegram.",var_status:"Resultado de la acción: ok o error. Disponible en los post-commands para decidir qué hacer después.",var_skipped:"Vale 1 si la acción se salteó (por skip_prompt_on), 0 si corrió. Disponible en los post-commands.",var_pre_output:"Salida completa de los pre-commands, como variable de entorno en los post-commands (hasta 32k).",var_pre_output_file:"Ruta a un archivo temporal con la salida de los pre-commands. Para salidas grandes que no convienen como variable.",var_pre_exit:"Código de salida del último pre-command (0 = ok). Disponible en los post-commands.",var_routine:"Nombre de esta rutina. Disponible como variable de entorno en los comandos.",summary_runs_agent:'Corre el agente "{agent}"',summary_runs_agent_none:"Corre un agente (todavía no elegiste cuál)",summary_super_agent:"Llama al super-agente",summary_telegram:'Manda Telegram a "{channel}"',summary_runs_cmd:"Corre: {cmd}",summary_shell:"Corre un comando shell",summary_heartbeat:"Deja un heartbeat en los logs",action_agent_answers:'El agente "{agent}" responde el prompt',action_agent_pick_answers:"El agente (elegí uno) responde el prompt",action_super_answers:"El super-agente responde el prompt",action_telegram_channel:'Manda Telegram al canal "{channel}"',action_runs_shell:"Corre el comando shell",step_pre:"Pre",step_post:"Post",last_label:"última:",tg_chat_id_ph:"(usa el del canal)",tg_text_ph:"mensaje a enviar",hb_message_ph:"sigo vivo",arg_placeholder:"--flag o valor",remove_arg:"quitar arg",super_agent_label:"{persona} (super-agente)",super_agent_badge:"super-agente"},modules_ui:{desktop_pos_left:"Izquierda",desktop_pos_center:"Centro",desktop_pos_right:"Derecha",desktop_theme_system:"Sistema",desktop_theme_light:"Claro",desktop_theme_dark:"Oscuro",desktop_status_desc:"La ventana se abre desde la terminal o por arranque automático.",desktop_running:"Corriendo",desktop_stopped:"Detenida",desktop_refresh:"refrescar",desktop_start:"Iniciar",desktop_stop:"Detener",desktop_restart:"Reiniciar",desktop_restart_hint:"Recarga la ventana abierta para aplicar ya los cambios de config (tema, posición).",desktop_restart_done:"Reiniciando la ventana — aplicando la última config.",desktop_restart_none:"No hay ninguna ventana de desktop conectada.",desktop_start_done:"Ventana de desktop iniciada.",desktop_start_already:"La ventana de desktop ya estaba corriendo.",desktop_stop_done:"Ventana de desktop detenida.",desktop_stop_none:"No había ninguna ventana de desktop corriendo.",desktop_from_terminal:"Desde la terminal:",desktop_autostart_desc:"Abre la ventana al iniciar sesión. Equivale a `apx desktop install` (no requiere sudo).",desktop_platform:"plataforma: {platform}",desktop_shortcut_desc:"Atajo global que muestra/oculta la ventana y empieza a escuchar.",desktop_accelerator:"Acelerador",desktop_accelerator_hint:"Hacé clic en el campo y apretá tu combinación de teclas. Reiniciá la ventana para aplicar.",desktop_shortcut_record:"Hacé clic para definir un atajo",desktop_shortcut_recording:"Apretá tu combinación…",desktop_shortcut_change:"clic para cambiar",desktop_shortcut_esc:"Esc para cancelar",desktop_shortcut_saved:"Atajo guardado. Reiniciá la ventana (apx desktop stop && start) para aplicarlo.",desktop_autostart_on:"Arranque automático habilitado para el próximo inicio de sesión.",desktop_autostart_off:"Arranque automático deshabilitado.",desktop_appearance_desc:"Tema de la ventana y posición en la pantalla.",desktop_theme:"Tema",desktop_restart_apply:"Reiniciá la ventana para aplicar.",desktop_theme_set:"Tema: {value}.",desktop_position:"Posición",desktop_position_hint:'"izquierda" / "centro" / "derecha" del borde superior.',desktop_position_set:"Posición: {value}.",desktop_activation_desc:"El plugin del daemon procesa los mensajes. El STT se configura en Voces.",desktop_enabled_toast:"Escritorio habilitado.",desktop_disabled_toast:"Escritorio deshabilitado.",desktop_plugin_on:"Plugin habilitado (responde mensajes)",desktop_plugin_off:"Plugin deshabilitado",desktop_stt_engine:"Motor de speech-to-text:",desktop_stt_engine_suffix:"(whisper local, idioma, modelo).",desktop_last_conv_desc:"El último intercambio con el agente desde la ventana flotante.",desktop_no_messages:"Todavía no hay mensajes. Mandá algo a la ventana de escritorio para que aparezca acá.",desktop_you:"Vos",desktop_roby:"Roby",desktop_empty_msg:"(vacío)",deck_widget_enabled:"Widget {id} habilitado.",deck_widget_disabled:"Widget {id} deshabilitado.",deck_save_error:"Error al guardar",deck_loading_manifest:"Cargando manifest…",deck_manifest_error:"Error al cargar el manifest.",deck_widgets_summary:"{count} widgets · {enabled} externos habilitados",deck_loading_manifest_full:"Cargando el manifest del Deck…",deck_manifest_load_failed:"No se pudo cargar el manifest del Deck.",deck_retry:"Reintentar",deck_no_widgets:"No hay widgets en el manifest.",deck_context_desc:"Información que el Deck ve desde el daemon.",deck_active_project:"Proyecto activo:",deck_none:"ninguno",deck_registered_projects:"Proyectos registrados:",deck_active_plugins:"Plugins activos:",deck_daemon_active:"activo · {uptime}",deck_daemon_started:"iniciado",deck_safety_no_shell:"sin shell directo",deck_safety_no_arbitrary:"comandos arbitrarios bloqueados",deck_safety_confirm:"las acciones peligrosas requieren confirmación",code_copied:"Copiado.",code_saved:"Guardado.",code_file_empty:"(vacío)",code_file_error:"Error: {msg}",code_stream_error:"error",code_super_agent:"super-agent",code_super_agent_desc:"Agente principal con todas las tools",code_chat_tab:"Chat",code_panel_sessions:"Lista de sesiones",code_panel_tree:"Árbol de archivos",code_panel_terminal:"Terminal",code_panel_context:"Panel de contexto",code_ctx_auto:"auto",code_ctx_mode:"Modo",code_ctx_agent:"Agente",code_ctx_msgs_value:"{user} usuario · {assistant} asistente",code_ctx_tokens_total:"Tokens Total",code_ctx_created:"Creado",code_ctx_activity:"Actividad",code_project_fallback:"proyecto {id}",code_pick_project_ph:"Elegí un proyecto…",code_artifact_exit_ok:"exit 0 — {ms}ms",code_artifact_exit_fail:"exit {code}{timeout}",code_artifact_timeout_suffix:" (timeout)",code_artifact_view_short:"Ver",code_artifact_edit_short:"Editar",code_artifact_exit_badge:"exit {code}",code_artifact_timeout:"timeout",code_artifact_truncated:"truncado"},settings_ui:{bearer_label:"Bearer",global_config_desc:"Config general en ~/.apx/config.json. Editable por tabs; el JSON queda separado.",global_json_desc:"Los secretos redacted no se sobrescriben.",save_json:"Guardar JSON",expand_menu:"Expandir menú",collapse_menu:"Colapsar menú",documentation:"Documentación",kind_personal:"Personal",kind_company:"Empresa",kind_app:"App",kind_software:"Software",kind_default:"Default",kind_other:"Otro",base_menu_view:"Vista del menú Base (workspace general).",coming_soon:"Próximamente",inspector_title:"Skill Inspector (RAG por turno)",inspector_desc:"Función experimental. Cuando está activa, el agente NO recibe la lista completa de skills en su prompt; en cada mensaje un RAG local decide qué skill(s) cargar — el cuerpo completo si hay match fuerte, una sugerencia si es medio, nada si no aplica. Se reevalúa en cada turno: una skill que dejó de ser relevante desaparece del contexto.",enable_inspector:"Habilitar inspector",enable_inspector_hint:"Off = comportamiento clásico (lista de slugs + sugerencia pasiva). On = el RAG decide por turno.",on:"On",off:"Off",index_count:"Índice: {n} skills",not_indexed:"sin indexar",dim:"dim {dim}",updated_at:"actualizado {date}",reindex:"Reindexar",reindex_forced:"Reindexar (forzado)",embedder_source:"El embedder viene de Memoria (RAG). Local con Ollama, u offline si no hay proveedor configurado.",thresholds_title:"Umbrales y límites",thresholds_desc:"Ajustá qué tan agresivo es el inspector. Subir los umbrales = menos falsos positivos pero más riesgo de perderte una skill; bajarlos = al revés.",test_title:"Probar (dry-run)",test_desc:"Escribí un mensaje como lo haría un usuario y mirá qué skills cargaría/sugeriría el inspector — sin llamar al modelo. Fuerza el inspector aunque esté apagado arriba.",test_placeholder:"ej.: necesito crear un video promocional con voz en off",test_btn:"Probar",jit_empty_index:"JIT (índice vacío)",loaded_label:"Cargadas:",suggested_label:"Sugeridas:",could_not_save:"No se pudo guardar: {msg}",indexed_with:"Indexado con {embedder} (dim {dim}): +{added} ~{refreshed} -{removed}.",index_failed:"Falló el indexado: {msg}",dry_run_failed:"Falló el dry-run: {msg}",knob_load_threshold:"Umbral de carga",knob_load_threshold_hint:"Similaridad mínima para inyectar el CUERPO de la skill (alto = más estricto).",knob_hint_threshold:"Umbral de sugerencia",knob_hint_threshold_hint:"Similaridad mínima para solo SUGERIR la skill (así el agente la carga si quiere).",knob_margin:"Margen sobre la 2da",knob_margin_hint:"La primera tiene que superar a la segunda por este margen para cargar su cuerpo (evita empates flojos).",knob_max_loaded:"Máx. cuerpos cargados",knob_max_loaded_hint:"Cuántas skills se inyectan completas por turno.",knob_max_hints:"Máx. sugerencias",knob_max_hints_hint:"Cuántas skills extra se nombran como sugerencia.",knob_prompt_floor:"Largo mínimo del prompt",knob_prompt_floor_hint:"Los mensajes más cortos que esto se ignoran (evita 'ok', 'hola').",knob_body_char_cap:"Tope de chars del cuerpo",knob_body_char_cap_hint:"Recorta los cuerpos largos para que no inflen el contexto.",cfg_overrides_label:"Overrides",cfg_overrides_desc:".apc/config.json. Solo valores específicos del proyecto; vacío hereda del global/effective.",cfg_route_to_agent:"Route to agent",cfg_super_agent_model:"Modelo del super-agente",cfg_permission_mode:"Permission mode",cfg_extra_prompt:"Prompt extra",cfg_telegram_label:"Telegram",cfg_chat_id:"Chat ID",cfg_bot_token:"Bot token",cfg_respond_with_engine:"Responder con engine",cfg_engines_label:"Engines",cfg_ollama_url:"Ollama URL",cfg_anthropic_key:"Anthropic API key",cfg_openai_key:"OpenAI API key",cfg_groq_key:"Groq API key",cfg_openrouter_key:"OpenRouter API key",cfg_gemini_key:"Gemini API key",cfg_project_label:"Proyecto",cfg_project_desc:".apc/project.json. Metadata APC portable; sin secretos, sin runtime.",cfg_name:"Nombre",cfg_version:"Versión",cfg_apc_spec:"APC spec",cfg_apx_install:"Estado de instalación APX",cfg_apx_storage_id:"ID de storage APX"},skills_page:{title:"Skills",desc:"Activá o desactivá qué skills carga cada agente. Elegí el scope: el super-agent (global) o un proyecto puntual.",list_title:"Skills instaladas",list_desc:"Las privadas de APX están siempre activas y no se pueden tocar.",scope_label:"Scope",scope_super_agent:"Super-agent (global)",scope_hint:"El super-agent usa el scope global. Cada proyecto puede sobrescribir skills de forma independiente.",count_label:"{n} skills · {on} activas",empty:"No hay skills. Creá una abajo o instalá con la CLI.",source_builtin:"APX",source_global:"Global",source_project:"Proyecto",private_badge:"Privada",private_hint:"Skill interna de APX — siempre activa, no se puede desactivar ni borrar.",overridden_badge:"Override",inherited_hint:"Heredada del global",reset_to_global:"Volver al global",on:"activa",off:"inactiva",toggle_failed:"No se pudo cambiar el estado: {msg}",add_title:"Agregar skill",add_desc:"Crea una skill de usuario en ~/.apx/skills/<slug>/SKILL.md. Queda disponible para todos los scopes.",add_slug_label:"Slug",add_slug_ph:"mi-skill",add_desc_label:"Descripción",add_desc_ph:"Una línea que explique cuándo usarla",add_body_label:"Cuerpo (Markdown)",add_body_ph:`# Mi skill
|
|
764
764
|
|
|
@@ -770,7 +770,7 @@ Copiá el token completo — empieza con "1/..." y tiene un ":" en el medio.
|
|
|
770
770
|
Pegalo en el campo de abajo.`}}},github:{connected:{user_login:"Conectado como",user_name:"Nombre"},fields:{token:{label:"Personal Access Token",help_label:"¿Cómo obtener el token?",help_steps:`Abrí github.com/settings/tokens.
|
|
771
771
|
Generá un token (classic o fine-grained) con scope "repo".
|
|
772
772
|
Copiá el token — empieza con ghp_ o github_pat_.
|
|
773
|
-
Pegalo en el campo de abajo.`}}},obsidian:{connected:{vault_path:"Vault",vault_name:"Nombre",note_count:"Notas"},fields:{vault_path:{label:"Ruta del Vault"},auto_mcp:{label:"Registrar MCP de Obsidian",hint:"Agrega un MCP 'obsidian' apuntando a este vault, en este scope."},memory_sync:{label:"Sincronizar memoria de APX",hint:"Habilita el respaldo de la memoria de APX en el vault; luego usá el botón de abajo."}},actions:{sync_memory:"Sincronizar memoria",sync_memory_done:"Sincronizados {count} archivo(s) · {changed} cambiados"}}}},SD={common:{loading:"Loading…",saving:"Saving…",cancel:"Cancel",save:"Save",delete:"Delete",edit:"Edit",create:"Create",add:"Add",remove:"Remove",reload:"Reload",shutdown:"Shut down",enabled:"Enabled",disabled:"Disabled",enable:"Enable",disable:"Disable",open:"Open",close:"Close",confirm:"Confirm",optional:"(optional)",none:"—",none_yet:"Nothing here yet.",error_generic:"Something went wrong.",search:"Search",new:"New",restore:"Restore",show:"Show",hide:"Hide",copy:"Copy",run:"Run",refresh:"Refresh",view_all:"View all",saved:"Saved.",deleted:"Deleted.",pager_prev:"Previous",pager_next:"Next",pager_page:"Page {page} of {total}",pager_range:"{from}–{to} of {total}",pager_per_page:"Per page"},daemon:{connecting:"Connecting to the daemon…",unreachable:"Could not reach the daemon at localhost:7430.",unreachable_hint:"Start APX with `apx daemon start` and refresh.",version:"Version",uptime:"Uptime",status:"Status",running:"running",down:"down",reload_hint:"POST /admin/reload — reloads ~/.apx/config.json without restarting.",shutdown_confirm:"Shut down the daemon? Upcoming requests will fail until it restarts.",shutdown_done:"Daemon stopped."},pairing:{title:"Pair this device",subtitle:"You are connecting from outside this machine. For security, pair this browser with a pairing code.",steps_title:"How to get the code",step_1:"On the PC where APX is running, open a terminal.",step_2:"Run `apx pair` (or scan the QR with APX Deck).",step_3:"Copy the code shown below the QR and paste it here.",code_label:"Pairing code",code_ph:"e.g. 7f3a1c9e-…",label_label:"Device name",label_ph:"e.g. Living room laptop",submit:"Pair",linking:"Pairing…",success:"Device paired ✓",err_required:"Paste the pairing code.",err_expired:"The code expired. Run `apx pair` again and try again.",err_unknown:"Unknown or already-used code. Generate a new one with `apx pair`.",err_generic:"Could not pair. Check the code and try again.",revoke_hint:"You can revoke this device at any time from Settings or with `apx pair revoke`."},nav:{apx_admin:"APX",settings:"Settings",project:"Project",add_project:"Add project",all_projects:"All projects",more_projects:"{count} more",collapse_projects:"Hide projects",expand_projects:"Show projects",modules:{voice:"Voices",desktop:"Desktop",deck:"Deck",code:"Code",web:"Web"}},topbar:{breadcrumb_root:"APX",breadcrumb_settings:"APX › Settings",breadcrumb_project:"APX › Project",breadcrumb_base:"Base",breadcrumb_projects:"Projects",light:"Switch to light",dark:"Switch to dark",lang_toggle:"Language"},admin:{title:"APX",subtitle:"Admin panel. Global config, channels and projects.",engines_title:"Engines",engines_subtitle:"Available LLM adapters. API keys live in ~/.apx/config.json.",telegram_title:"Telegram",telegram_subtitle:"Configured channels. Each one can be pinned to a project.",telegram_polling_on:"Polling active",telegram_polling_off:"Disabled",telegram_add_channel:"Channel",telegram_send_test:"Test",telegram_send_test_title:"Send to",telegram_default_message:"Test message from APX panel ✅",projects_title:"Registered projects",projects_subtitle:"Click a project to open its panel.",unregister:"Unregister",unregister_confirm:"Remove {label} from APX? The folder is not deleted; only unregistered.",reload_success:"Config reloaded.",telegram_polling_started:"Polling started.",telegram_polling_stopped:"Polling stopped.",telegram_channel_removed:"Channel deleted.",agents_badge:"agents",engine_badge:"yes",engine_badge_no:"no",base_label:"Base"},add_project:{title:"Add project",subtitle:"APX will index .apc/, agents and AGENTS.md in that folder.",path_label:"Absolute path",path_hint:"Equivalent to apx project add /path/to/project",path_placeholder:"/path/to/my-project",register:"Register",path_required:"Path required.",registered:"Project #{id} registered.",search_btn:"Browse",picker_prompt:"Pick the project folder",browser_unavailable:"Browser unavailable until daemon restarts. Paste path manually.",no_folders:"No folders."},settings:{title:"Settings",subtitle:"Panel preferences + local daemon diagnostics.",appearance:"Appearance",light_mode:"Light",dark_mode:"Dark",system_mode:"System",language:"Language",daemon:"Daemon",daemon_sub:"Status of the local process that serves this web and orchestrates agents.",engines:"Available engines",engines_sub:"LLM adapters compiled with the daemon.",token:"Session token",token_sub:"If this web could not auto-load the token, paste it here.",token_active:"(token already active)",token_paste:"Paste daemon bearer",token_saved:"Token saved.",devices:"Paired devices",devices_sub:"GET /pair/list. Revoking invalidates that bearer on the daemon.",devices_empty:"No paired clients yet.",devices_revoke_confirm:"Revoke client {id}?",devices_revoke_success:"Client revoked.",devices_pair_btn:"Pair device",devices_pair_title:"Pair device",devices_pair_desc:"Scan the QR with your phone camera to open the web already paired, or paste the code on another PC.",devices_pair_scan:"Scan with your phone camera — opens the web already paired.",devices_pair_code:"Or paste this code on the pairing screen:",devices_pair_url:"Access URL",devices_pair_link:"Or copy this link and open it on the other device (enters automatically):",devices_pair_copy:"Copy",devices_pair_copied:"Link copied to clipboard.",devices_pair_copied_code:"Code copied.",devices_pair_expires:"Expires in {s}s",devices_pair_expired:"The code expired.",devices_pair_regen:"Generate another",devices_pair_waiting:"Waiting for device to confirm…",devices_pair_done:"Device paired ✓",devices_pair_localhost_only:"Codes can only be generated from the daemon's PC (localhost).",devices_last_seen:"seen:",devices_never:"never",devices_revoke:"Revoke",account_section:"Account",agents_section:"Agents & models",channels_section:"Channels & devices",modules_section:"Modules",advanced_section:"Advanced",tabs:{identity:"Identity",super_agent:"Super-agent",profile:"Agent profile",engines:"Engines & models",telegram:"Telegram",devices:"Devices",advanced:"Advanced"},profile:{title:"Agent profile",subtitle:"An installable line of work for the super-agent: what it does with its day and when it speaks to you. Distinct from the agent's name (that lives under Identity).",vanilla_hint:"No profile is active. APX behaves exactly as it always has — the super-agent prompt is identical to a clean install.",none_available:"No profiles available yet.",active:"active",activate:"Activate",replace_active:"Replace the active one",deactivate:"Deactivate",deactivate_title:"Deactivate the profile?",deactivate_confirm:"APX goes back to vanilla. The profile's routines are disabled but not deleted, and your settings, tasks and memory are untouched — activating it again restores everything.",activated:"Profile active",deactivated:"Profile off — APX is back to vanilla",token_cost:"Prompt cost",over_budget:"over its declared budget",settings_title:"Profile settings",settings_subtitle:"Blank fields fall back to the package default. Changing a time really reschedules the routine.",saved:"Settings saved",saved_with_routines:"Settings saved and routines rescheduled",doctor_title:"Doctor",doctor_clean:"All good.",preview_title:"Prompt block",preview_subtitle:"Exactly what reaches the model, with your values substituted.",preview_empty:"(empty)"},identity:{title:"Identity",subtitle:"User data. Agent configuration goes in Super-agent.",agent_name:"Agent name",owner_name:"Your name",personality:"Personality",owner_context:"Owner context",owner_context_hint:"Who you are, what you work on, what the agent should know about you.",language:"Preferred language",timezone:"Timezone (IANA)",timezone_hint:"Auto-detected — search to change.",saved:"Identity saved."},super_agent:{title:"Super-agent",subtitle:"Personality, model, prompt and modes of the super-agent.",personality:"Personality",model:"Active model",model_hint:"E.g.: anthropic:claude-sonnet-4.5, ollama:gemma2:9b",permission_mode:"Permission mode",system:"Extra prompt (system)",system_hint:"Text prepended to the base system prompt.",system_ph:"(Empty = the base prompt from core/agent/prompts/super-agent-base.md is used)",fallback_title:"Fallback chain",fallback_hint:"If the active model fails, these are tried in order.",fallback_add:"Add model to chain",saved:"Super-agent saved.",enabled_label:"Super-agent enabled",model_active:"Active model (router)",model_configure:"Configure in Models",behavior_subtitle:"Super-agent behavior. Model and fallback chain are configured in the Model Router."},engines_keys:{title:"Model API keys",subtitle:"Each engine stores its key in ~/.apx/config.json. Already-set values show a safe suffix.",ollama_url:"Ollama URL",ollama_hint:"Default: http://127.0.0.1:11434",key_label:"API key",key_placeholder:"(not set)",clear:"Clear key",saved:"Key saved.",cleared:"Key cleared."},telegram_global:{title:"Telegram (default)",subtitle:"Default channel — projects can override with their own channel.",bot_token:"Bot token",chat_id:"Default chat ID",poll_interval:"Poll interval (ms)",respond_with_engine:"Respond with engine",enabled:"Polling enabled",saved:"Telegram saved."},advanced:{title:"Advanced",subtitle:"Raw editor for ~/.apx/config.json. Secrets show as *** set *** but you can write a new one.",write:"Apply changes",written:"Config applied and daemon reloaded.",reload_success:"Config reloaded."}},project:{not_found:"Roby couldn't find project {pid}: it may have been unregistered, or the ID is wrong.",rebuild:"Rebuild context",rebuild_done:"Rebuild OK.",unregister_confirm:"Unregister {label}? The folder is not deleted.",unregistered:"Unregistered.",base_subtitle:"General workspace · super-agent",danger:{title:"Danger zone",subtitle:"Actions that affect APX's project registry. They do not touch repo files.",rebuild_desc:"Re-scans .apc/, MCPs and agents and regenerates the super-agent context for this project.",unregister_desc:"Removes the project from APX's registry. The folder on disk stays intact.",rebuild_confirm_title:"Rebuild context",rebuild_confirm_desc:"Regenerate context for {label}.",rebuild_long:"Re-reads APC config, lists available MCPs and agents, and rebuilds the super-agent system prompt. Safe to run — nothing is deleted. Use it after editing .apc/ by hand or if changes are not being picked up.",unregister_confirm_title:"Unregister project",unregister_long:"The project disappears from `apx`. Files on disk (.apc/, code, everything) stay. You can re-register it with `apx project register <path>`."},nav:{overview:"Overview",chat:"Chat",config:"Config",telegram:"Telegram",agents:"Agents",routines:"Routines",tasks:"Tasks",mcps:"MCPs",artifacts:"Artifacts",vars:"Variables",logs:"Logs",memories:"Memories",structure:"Structure",docs:"Docs",files:"Files"},sections:{workspace:"Workspace",content:"Content",automation:"Automation",knowledge:"Conversations",config:"Config"},overview:{tasks_open:"Open tasks",routines:"Routines",routines_active:"Active routines",agents:"Agents",mcps:"MCPs",artifacts:"Artifacts",chat:"Chat (super-agent)",chat_value:"open",roster:"Team",no_agents:"No agents yet.",orchestrators:"Orchestrators",specialists:"Specialists",recent_tasks:"Recent tasks",no_activity:"No open tasks.",brain_title:"Team brain",brain_desc:"The whole agent map — orchestrators at the core, their specialists clustered around them. Click a node to open it.",brain_core:"Team"},artifacts:{title:"Artifacts",subtitle:"Reusable scripts and files stored under the project. Agents create them; you can view, run, rename or delete them."},chat:{title:"Chat with agent",subtitle:"Direct conversations with project agents. The super-agent does not intervene.",live_title:"Chat with {agent}",superagent_title:"Chat with {persona}",superagent_subtitle:"Chat with {persona} — the APX super-agent. Can use tools (projects, tasks, mcps, agents).",loaded_subtitle:"Loaded conversation with {slug}. Sending will append to this thread.",thread_subtitle:"History with {persona} on {channel}. Replying here continues the conversation from the web.",empty:"Send a message to start the conversation.",placeholder:"Type something and press enter to send (shift+enter = new line)",send:"Send",stop:"Stop",new_session:"New session",delete:"Delete",delete_confirm_title:"Delete chat",delete_confirm_desc:"This can't be undone. This chat's history will be permanently deleted.",deleted:"Chat deleted.",meta_created:"Created {date} · {channel}",meta_new:"New chat · {channel}",copy:"copy",copied:"Copied.",stopped_marker:" [stopped]",create_agent:"Create agent",create_agent_title:"Create agent",create_agent_desc:"Required to start a chat in this project.",role_label:"role",model_label:"model",model_hint:"e.g. openai:gpt-5, groq:llama-3.3-70b-versatile",master_label:"Master agent",list:{title:"Chats",new:"New",search:"Search chats…",all_agents:"All agents",empty:"No conversations yet. Start one from the right.",count:"{n} total",pick_agent:"Pick an agent"}},tasks:{title:"Tasks (TODOs)",subtitle:"Append-only JSONL in ~/.apx/projects/<id>/tasks/.",add:"add",add_label:"New task",add_placeholder:"e.g. fix scroll bug",empty:"No {state} tasks.",empty_open:"No open tasks.",created:"Task created.",create_error:"could not create task",done:"✓ done",drop:"✗ drop",reopen:"↻ reopen",due:"due",via:"via",aria_done:"mark done",aria_drop:"discard task",aria_reopen:"reopen task"},global_tasks:{title:"Tasks (all projects)",subtitle:"Aggregated tasks from all registered projects.",empty:"No tasks.",due:"due",go_project:"Go to project"},routines:{title:"Heartbeats / Routines",subtitle:"Cron, every:Nm, once:ISO. Each routine fires an agent or a shell.",empty:"No routines. Create one above.",new:"new",new_btn:"New",delete_confirm:"Delete routine {name}?",delete_confirm_body:"This can't be undone.",saved:"Routine saved.",paused:"paused",next_run:"next:",last_run:"last:",enabled_hint:"Active · runs on schedule",disabled_hint:"Paused · only via Run button",enabled_label:"Enabled",new_title:"New routine",edit_title:"Edit {name}",dialog_desc:"Saved in .apc/routines.json. The routine runs while the daemon is active.",name_field:"Name",name_no_edit:"Cannot be changed when editing.",kind_field:"Action (kind)",schedule_field:"Interval (schedule)",schedule_hint:"Choose a preset or type manually. Manual = only runs via Run button.",vars_title:"Available variables",what_happens:"What will happen",list_title:"Routines",detail_empty:"Pick a routine from the list.",edit_btn:"Edit",edit_hint:"Open the editor: kind, schedule, prompt, pre/post and variables.",block_pre:"Pre-commands",block_post:"Post-commands",block_prompt:"Prompt",block_text:"Text",block_command:"Command",block_empty:"(empty)",runs_title:"Executions",runs_empty:"No executions yet.",runs_close:"Close",runs_no_detail:"No further detail.",runs_output:"Output",status_ok:"ok",status_error:"error",status_skipped:"skipped",agent_field:"Agent (spec.agent)",agent_hint:"Who executes the routine.",agent_loading:"loading…",agent_pick:"— pick an agent —",prompt_exec:"Prompt (spec.prompt)",prompt_exec_ph:"what is pending for today?",prompt_super:"Prompt (spec.prompt)",prompt_super_ph:"summarize the project status",pre_field:"Pre-commands (pre_commands)",pre_hint:"Shell BEFORE the prompt. One per line.",post_field:"Post-commands (post_commands)",post_hint:"Shell AFTER the prompt. One per line.",tg_channel:"Channel (spec.channel)",tg_chat_id:"Chat ID (spec.chat_id)",tg_text:"Telegram Message (spec.text)",tg_text_hint:"Fixed message to send. Does not use a model.",shell_field:"Command (spec.command)",shell_hint:"Runs as-is in the shell. No prompt, no pre/post.",hb_channel:"Channel (spec.channel)",hb_message:"Message (spec.message)",name_required:"name required",save_error:"save failed",run_error:"run failed",toggle_error:"toggle failed",delete_error:"delete failed",run_success:"{name} fired.",run_confirm:"Run routine {name} now?",run_confirm_body:"Runs the action once, regardless of the schedule.",running:"Running…",delete_success:"deleted."},agents:{title:"Agents",subtitle:"Defined in .apc/agents/<slug>.md.",subtitle_full:"Defined in .apc/agents/<slug>.md. Runtime memory lives under ~/.apx/projects/<id>/agents/<slug>/.",empty:"No agents. Add one with <code>apx agent add</code> or the button.",empty_text:"No agents. Add one with `apx agent add` or the button above.",new:"Agent",created:"Agent {slug} created.",slug_invalid:"slug must match /^[a-z][a-z0-9_-]*$/",hierarchy:"Hierarchy",list_view:"List",import:"Import",chat:"Chat",view:"View",orchestrator:"Orchestrator",new_title:"New agent",new_desc:"POST /projects/:pid/agents — writes .apc/agents/<slug>.md.",slug_label:"slug",slug_ph:"cody",role_label:"role (optional)",role_ph:"code refactor",model_label:"model (optional)",model_hint:"e.g. ollama:gemma2:9b, openai:gpt-4o-mini",lang_label:"language (optional)",desc_label:"description (optional)",desc_ph:"What does this agent do…",skills_label:"skills (comma)",skills_ph:"skill-a, skill-b",tools_label:"tools (comma)",tools_ph:"tool-a, tool-b",parent_label:"reports to (parent, optional)",parent_hint:"Sub-agent of an orchestrator.",none_parent:"— none —",master_label:"Orchestrator (master)",create_success:"Agent {slug} created.",create_error:"create failed",import_title:"Import from vault",import_desc:"Templates in ~/.apx/agents. Registered in this project (.apc/agents/<slug>.md).",import_empty:"No templates in the vault.",import_success:"Imported: {slug}",import_already:"already here",import_btn:"Import"},agent_detail:{not_found:"Agent not found.",chat_btn:"Chat with {slug}",reports_to:"↳ reports to",no_threads:"No threads.",no_activity:"No recorded activity.",threads_recent:"Recent threads",subagents:"Sub-agents",subagents_desc:"Agents that report to this orchestrator.",config_title:"Agent configuration",type_label:"Type",area_label:"Area",area_hint:"e.g. operations, marketing",area_ph:"operations",role_label:"Role",parent_label:"Reports to (parent)",none_parent:"— none —",model_label:"Base model",model_hint:"Empty = uses the Router model (default). Set only to force a model for this agent.",model_ph:"(empty = router default)",skills_label:"Skills (comma)",bio_label:"Bio / description",system_label:"System prompt",system_hint:"Defines personality and behavior (body of AGENT.md).",master_label:"Orchestrator (master)",delete_btn:"Delete agent",save_btn:"Save changes",delete_confirm:'Delete agent "{slug}"? Removes .apc/agents/{slug}.md and local runtime data.',update_success:"Agent updated.",delete_success:"Agent deleted.",tools_hint:"Which tools this agent can use. Tap to toggle; or edit the list below.",tools_custom_ph:"list (comma): echo, http_fetch",memory_title:"Agent memory",memory_empty:"(empty memory)",memory_saved:"Memory saved.",records_title:"Records",records_desc:"Agent activity log (messages/actions). Newest first.",sleep_title:"Sleep / Heartbeat",sleep_desc:"Agent execution status, derived from its routines.",sleep_deep:"Deep sleep · no heartbeat",sleep_deep_desc:"This agent has no routine that triggers it. It does not run autonomously; it only responds when invoked (chat / task).",brain_title:"Brain",brain_desc:"Real relationship graph of the agent: memory, threads, tasks, heartbeats and hierarchy. (first version — will be refined)",brain_empty:"No relationships to graph yet (no memory, threads, tasks or routines).",msgs_count:"msgs"},mcps:{title:"MCP servers",subtitle:"3 scopes: runtime > shared > global. Conflicts shown above if any.",empty:"No MCPs configured.",new:"MCP",delete_confirm:"Delete MCP {name} from scope {scope}?",conflicts:"⚠ Conflicts: {names}",conflict_detail:"{name} is defined in {winner} and {loser}. APX uses {winner}; {loser} is ignored.",new_title:"New MCP",new_desc:"POST /projects/:pid/mcps?scope=…",scope_label:"Scope",transport_label:"Transport",name_label:"Name",name_ph:"filesystem",cmd_label:"Command",cmd_ph:"npx",args_label:"Args",args_hint:"space-separated",args_ph:"-y @modelcontextprotocol/server-filesystem /tmp",env_label:"Env (JSON, optional)",url_label:"URL",url_ph:"https://example.com/mcp",enabled_label:"Enabled",add_btn:"Add",name_required:"name required",env_invalid:"env must be valid JSON",removed:"removed",added:"MCP added.",updated:"MCP updated.",edit_title:"Edit MCP",save_btn:"Save",add_arg:"Add arg",edit_btn:"Edit",test_btn:"Test",logs_btn:"Logs",testing:"Testing…",test_ok:"OK · {n} tools available",tools_count:"{n} tools",logs_title:"Logs · {name}",logs_empty:"No logs yet. Start the MCP by calling a tool or running Test.",logs_events:"Recent events",logs_stderr:"stderr (last 4KB)",logs_panel_title:"Live logs",logs_panel_pick:"pick an MCP",logs_panel_hint:"Click an MCP in the list to see what's happening live.",logs_panel_idle:"No activity. Hit Test to spin it up.",scope_runtime:"Runtime",scope_shared:"Shared",scope_global:"Global",source_runtime:"Runtime",source_apc:"APC / Shared",source_claude:"Claude",source_codex:"Codex",source_cursor:"Cursor",source_vscode:"VS Code",source_roo:"Roo",source_gemini:"Gemini",scope_runtime_desc:"This project only · with secrets · not committed (~/.apx/projects/<id>/mcps.json)",scope_shared_desc:"This project only · committeable · no secrets (.apc/mcps.json)",scope_global_desc:"All projects on this machine (~/.apx/mcps.json)",transport_stdio:"stdio",transport_http:"HTTP",transport_stdio_desc:"Local process — `command` + args",transport_http_desc:"Remote endpoint — URL + headers",args_hint_tokens:"One entry per arg. Use the + button to insert a variable.",env_hint_tokens:"Key/value pairs. Values accept ${var.NAME} (+ button on the right).",env_empty:"No env vars.",headers_label:"Headers",headers_hint:"Key/value pairs — typically Authorization: Bearer ${var.TOKEN}.",headers_empty:"No headers."},vars:{title:"Variables",subtitle_project:"Replace ${var.NAME} when loading MCPs and templates. Project vars beat globals. Stored outside the repo (~/.apx/, chmod 0600).",subtitle_base:"Global variables — available to every project. Stored in ~/.apx/vars.json (chmod 0600).",empty:"No variables yet.",new:"Variable",new_title:"New variable",edit_title:"Edit variable",new_desc:"Referenced as ${var.NAME} in any field that supports interpolation.",reveal_all:"Show values",reveal:"Show",hide:"Hide",filter_label:"Show:",filter_all:"All",filter_project:"Project only",filter_global:"Globals only",scope_label:"Scope",scope_project:"project",scope_project_desc:"This project only. Beats the global with the same name.",scope_global:"global",scope_global_desc:"Available to every project.",name_label:"Name",name_hint:"Uppercase, digits and _. E.g. MY_API_KEY, GITHUB_TOKEN.",value_label:"Value",value_hint:"Stored on disk with 0600 perms. Never committed.",value_edit_ph:"(leave empty to keep current… not yet supported, paste the value again)",add_btn:"Add",save_btn:"Save",edit_btn:"Edit",delete_btn:"Delete",delete_confirm:"Delete {name} ({scope})?",removed:"Variable removed.",added:"Variable added.",updated:"Variable updated.",name_required:"Name required.",value_required:"Value required."},threads:{title:"Chats",subtitle:"Conversations per agent (empty = no logs persisted yet).",no_agents:"No agents. Conversations require a configured agent.",pick:"Pick an agent to view its conversations.",empty:"No conversations for {slug}.",conversation_title:"Conversation {id}",messages:"messages",via:"via"},config:{title:"Quick config",subtitle:"Project override. Written to {path}.",model:"super_agent.model",model_hint:"e.g. anthropic:claude-sonnet-4.5, ollama:gemma2:9b",perm:"super_agent.permission_mode",route:"route_to_agent",route_hint:"Slug of the agent that handles this project by default.",use_global:"(uses global)",saved:"Saved.",nothing:"Nothing to save.",raw_title:"Config (raw JSON)",raw_subtitle:"Paste the entire object — equivalent to PUT the file.",raw_save:"Replace config",raw_done:"Config overwritten.",effective:"Effective config (read-only)",effective_sub:"What the daemon actually sees (global ⊕ override).",section_title:"Project config",section_desc:"APC metadata and overrides separated. General APX lives in Settings > Config.",effective_read:"Read: global APX + project override.",save_project:".apc/project.json saved.",save_override:".apc/config.json saved.",save_fields_success:"Overrides saved.",save_meta_success:"Project metadata saved.",no_data:"No data.",tab_settings:"Settings",tab_project:"Project"},telegram:{title:"Telegram channel (override)",subtitle:"If you set a channel here, messages from this project go there instead of the default.",use_default:"Use default channel",bot_token:"Bot token (override)",chat_id:"Chat ID (override)",saved:"Override saved.",cleared:"Override removed — falls back to default.",override_active:"override active",channel_badge:"Channel {name}",no_override:"No override. Messages from this project go to the default channel.",respond_engine:"Respond with engine",route_agent:"route_to_agent",route_hint:"Slug of the agent that handles messages (empty = super-agent).",bot_hint_none:"If empty, inherits from default."},memories:{sidebar_title:"Memories",general_group:"General",general_item:"Project memory",project_title:"Project memory",project_desc:"Durable facts at the project level. .apc/memory.md — read by agents and the super-agent.",project_ph:`# Project Memory
|
|
773
|
+
Pegalo en el campo de abajo.`}}},obsidian:{connected:{vault_path:"Vault",vault_name:"Nombre",note_count:"Notas"},fields:{vault_path:{label:"Ruta del Vault"},auto_mcp:{label:"Registrar MCP de Obsidian",hint:"Agrega un MCP 'obsidian' apuntando a este vault, en este scope."},memory_sync:{label:"Sincronizar memoria de APX",hint:"Habilita el respaldo de la memoria de APX en el vault; luego usá el botón de abajo."}},actions:{sync_memory:"Sincronizar memoria",sync_memory_done:"Sincronizados {count} archivo(s) · {changed} cambiados"}}}},SD={common:{loading:"Loading…",saving:"Saving…",cancel:"Cancel",save:"Save",delete:"Delete",edit:"Edit",create:"Create",add:"Add",remove:"Remove",reload:"Reload",shutdown:"Shut down",enabled:"Enabled",disabled:"Disabled",enable:"Enable",disable:"Disable",open:"Open",close:"Close",confirm:"Confirm",optional:"(optional)",none:"—",none_yet:"Nothing here yet.",error_generic:"Something went wrong.",search:"Search",new:"New",restore:"Restore",show:"Show",hide:"Hide",copy:"Copy",run:"Run",refresh:"Refresh",view_all:"View all",saved:"Saved.",deleted:"Deleted.",pager_prev:"Previous",pager_next:"Next",pager_page:"Page {page} of {total}",pager_range:"{from}–{to} of {total}",pager_per_page:"Per page"},daemon:{connecting:"Connecting to the daemon…",unreachable:"Could not reach the daemon at localhost:7430.",unreachable_hint:"Start APX with `apx daemon start` and refresh.",version:"Version",uptime:"Uptime",status:"Status",running:"running",down:"down",reload_hint:"POST /admin/reload — reloads ~/.apx/config.json without restarting.",shutdown_confirm:"Shut down the daemon? Upcoming requests will fail until it restarts.",shutdown_done:"Daemon stopped."},pairing:{title:"Pair this device",subtitle:"You are connecting from outside this machine. For security, pair this browser with a pairing code.",steps_title:"How to get the code",step_1:"On the PC where APX is running, open a terminal.",step_2:"Run `apx pair` (or scan the QR with APX Deck).",step_3:"Copy the code shown below the QR and paste it here.",code_label:"Pairing code",code_ph:"e.g. 7f3a1c9e-…",label_label:"Device name",label_ph:"e.g. Living room laptop",submit:"Pair",linking:"Pairing…",success:"Device paired ✓",err_required:"Paste the pairing code.",err_expired:"The code expired. Run `apx pair` again and try again.",err_unknown:"Unknown or already-used code. Generate a new one with `apx pair`.",err_generic:"Could not pair. Check the code and try again.",revoke_hint:"You can revoke this device at any time from Settings or with `apx pair revoke`."},nav:{apx_admin:"APX",settings:"Settings",project:"Project",add_project:"Add project",all_projects:"All projects",more_projects:"{count} more",collapse_projects:"Hide projects",expand_projects:"Show projects",modules:{voice:"Voices",desktop:"Desktop",deck:"Deck",code:"Code",web:"Web"}},topbar:{breadcrumb_root:"APX",breadcrumb_settings:"APX › Settings",breadcrumb_project:"APX › Project",breadcrumb_base:"Base",breadcrumb_projects:"Projects",light:"Switch to light",dark:"Switch to dark",lang_toggle:"Language"},admin:{title:"APX",subtitle:"Admin panel. Global config, channels and projects.",engines_title:"Engines",engines_subtitle:"Available LLM adapters. API keys live in ~/.apx/config.json.",telegram_title:"Telegram",telegram_subtitle:"Configured channels. Each one can be pinned to a project.",telegram_polling_on:"Polling active",telegram_polling_off:"Disabled",telegram_add_channel:"Channel",telegram_send_test:"Test",telegram_send_test_title:"Send to",telegram_default_message:"Test message from APX panel ✅",projects_title:"Registered projects",projects_subtitle:"Click a project to open its panel.",unregister:"Unregister",unregister_confirm:"Remove {label} from APX? The folder is not deleted; only unregistered.",reload_success:"Config reloaded.",telegram_polling_started:"Polling started.",telegram_polling_stopped:"Polling stopped.",telegram_channel_removed:"Channel deleted.",agents_badge:"agents",engine_badge:"yes",engine_badge_no:"no",base_label:"Base"},add_project:{title:"Add project",subtitle:"APX will index .apc/, agents and AGENTS.md in that folder.",path_label:"Absolute path",path_hint:"Equivalent to apx project add /path/to/project",path_placeholder:"/path/to/my-project",register:"Register",path_required:"Path required.",registered:"Project #{id} registered.",search_btn:"Browse",picker_prompt:"Pick the project folder",browser_unavailable:"Browser unavailable until daemon restarts. Paste path manually.",no_folders:"No folders."},settings:{title:"Settings",subtitle:"Panel preferences + local daemon diagnostics.",appearance:"Appearance",light_mode:"Light",dark_mode:"Dark",system_mode:"System",language:"Language",daemon:"Daemon",daemon_sub:"Status of the local process that serves this web and orchestrates agents.",engines:"Available engines",engines_sub:"LLM adapters compiled with the daemon.",token:"Session token",token_sub:"If this web could not auto-load the token, paste it here.",token_active:"(token already active)",token_paste:"Paste daemon bearer",token_saved:"Token saved.",devices:"Paired devices",devices_sub:"GET /pair/list. Revoking invalidates that bearer on the daemon.",devices_empty:"No paired clients yet.",devices_revoke_confirm:"Revoke client {id}?",devices_revoke_success:"Client revoked.",devices_pair_btn:"Pair device",devices_pair_title:"Pair device",devices_pair_desc:"Scan the QR with your phone camera to open the web already paired, or paste the code on another PC.",devices_pair_scan:"Scan with your phone camera — opens the web already paired.",devices_pair_code:"Or paste this code on the pairing screen:",devices_pair_url:"Access URL",devices_pair_link:"Or copy this link and open it on the other device (enters automatically):",devices_pair_copy:"Copy",devices_pair_copied:"Link copied to clipboard.",devices_pair_copied_code:"Code copied.",devices_pair_expires:"Expires in {s}s",devices_pair_expired:"The code expired.",devices_pair_regen:"Generate another",devices_pair_waiting:"Waiting for device to confirm…",devices_pair_done:"Device paired ✓",devices_pair_localhost_only:"Codes can only be generated from the daemon's PC (localhost).",devices_last_seen:"seen:",devices_never:"never",devices_revoke:"Revoke",account_section:"Account",agents_section:"Agents & models",channels_section:"Channels & devices",modules_section:"Modules",advanced_section:"Advanced",tabs:{identity:"Identity",super_agent:"Super-agent",profile:"Agent profile",engines:"Engines & models",telegram:"Telegram",devices:"Devices",advanced:"Advanced"},profile:{title:"Agent profile",subtitle:"An installable line of work for the super-agent: what it does with its day and when it speaks to you. Distinct from the agent's name (that lives under Identity).",vanilla_hint:"No profile is active. APX behaves exactly as it always has — the super-agent prompt is identical to a clean install.",none_available:"No profiles available yet.",active:"active",activate:"Activate",replace_active:"Replace the active one",deactivate:"Deactivate",deactivate_title:"Deactivate the profile?",deactivate_confirm:"APX goes back to vanilla. The profile's routines are disabled but not deleted, and your settings, tasks and memory are untouched — activating it again restores everything.",activated:"Profile active",deactivated:"Profile off — APX is back to vanilla",token_cost:"Prompt cost",over_budget:"over its declared budget",settings_title:"Profile settings",settings_subtitle:"Blank fields fall back to the package default. Changing a time really reschedules the routine.",saved:"Settings saved",saved_with_routines:"Settings saved and routines rescheduled",doctor_title:"Doctor",doctor_clean:"All good.",preview_title:"Prompt block",preview_subtitle:"Exactly what reaches the model, with your values substituted.",preview_empty:"(empty)"},identity:{title:"Identity",subtitle:"User data. Agent configuration goes in Super-agent.",agent_name:"Agent name",owner_name:"Your name",personality:"Personality",owner_context:"Owner context",owner_context_hint:"Who you are, what you work on, what the agent should know about you.",language:"Preferred language",timezone:"Timezone (IANA)",timezone_hint:"Auto-detected — search to change.",saved:"Identity saved."},super_agent:{title:"Super-agent",subtitle:"Personality, model, prompt and modes of the super-agent.",personality:"Personality",model:"Active model",model_hint:"E.g.: anthropic:claude-sonnet-4.5, ollama:gemma2:9b",permission_mode:"Permission mode",system:"Extra prompt (system)",system_hint:"Text prepended to the base system prompt.",system_ph:"(Empty = the base prompt from core/agent/prompts/super-agent-base.md is used)",fallback_title:"Fallback chain",fallback_hint:"If the active model fails, these are tried in order.",fallback_add:"Add model to chain",saved:"Super-agent saved.",enabled_label:"Super-agent enabled",model_active:"Active model (router)",model_configure:"Configure in Models",behavior_subtitle:"Super-agent behavior. Model and fallback chain are configured in the Model Router."},engines_keys:{title:"Model API keys",subtitle:"Each engine stores its key in ~/.apx/config.json. Already-set values show a safe suffix.",ollama_url:"Ollama URL",ollama_hint:"Default: http://127.0.0.1:11434",key_label:"API key",key_placeholder:"(not set)",clear:"Clear key",saved:"Key saved.",cleared:"Key cleared."},telegram_global:{title:"Telegram (default)",subtitle:"Default channel — projects can override with their own channel.",bot_token:"Bot token",chat_id:"Default chat ID",poll_interval:"Poll interval (ms)",respond_with_engine:"Respond with engine",enabled:"Polling enabled",saved:"Telegram saved."},advanced:{title:"Advanced",subtitle:"Raw editor for ~/.apx/config.json. Secrets show as *** set *** but you can write a new one.",write:"Apply changes",written:"Config applied and daemon reloaded.",reload_success:"Config reloaded."}},project:{not_found:"Roby couldn't find project {pid}: it may have been unregistered, or the ID is wrong.",rebuild:"Rebuild context",rebuild_done:"Rebuild OK.",unregister_confirm:"Unregister {label}? The folder is not deleted.",unregistered:"Unregistered.",base_subtitle:"General workspace · super-agent",danger:{title:"Danger zone",subtitle:"Actions that affect APX's project registry. They do not touch repo files.",rebuild_desc:"Re-scans .apc/, MCPs and agents and regenerates the super-agent context for this project.",unregister_desc:"Removes the project from APX's registry. The folder on disk stays intact.",rebuild_confirm_title:"Rebuild context",rebuild_confirm_desc:"Regenerate context for {label}.",rebuild_long:"Re-reads APC config, lists available MCPs and agents, and rebuilds the super-agent system prompt. Safe to run — nothing is deleted. Use it after editing .apc/ by hand or if changes are not being picked up.",unregister_confirm_title:"Unregister project",unregister_long:"The project disappears from `apx`. Files on disk (.apc/, code, everything) stay. You can re-register it with `apx project register <path>`."},nav:{overview:"Overview",chat:"Chat",config:"Config",telegram:"Telegram",agents:"Agents",routines:"Routines",tasks:"Tasks",mcps:"MCPs",artifacts:"Artifacts",vars:"Variables",logs:"Logs",memories:"Memories",structure:"Structure",docs:"Docs",files:"Files"},sections:{workspace:"Workspace",content:"Content",automation:"Automation",knowledge:"Conversations",config:"Config"},overview:{tasks_open:"Open tasks",routines:"Routines",routines_active:"Active routines",agents:"Agents",mcps:"MCPs",artifacts:"Artifacts",chat:"Chat (super-agent)",chat_value:"open",roster:"Team",no_agents:"No agents yet.",orchestrators:"Orchestrators",specialists:"Specialists",recent_tasks:"Recent tasks",no_activity:"No open tasks.",brain_title:"Team brain",brain_desc:"The whole agent map — orchestrators at the core, their specialists clustered around them. Click a node to open it.",brain_core:"Team"},artifacts:{title:"Artifacts",subtitle:"Reusable scripts and files stored under the project. Agents create them; you can view, run, rename or delete them."},chat:{title:"Chat with agent",subtitle:"Direct conversations with project agents. The super-agent does not intervene.",live_title:"Chat with {agent}",superagent_title:"Chat with {persona}",superagent_subtitle:"Chat with {persona} — the APX super-agent. Can use tools (projects, tasks, mcps, agents).",loaded_subtitle:"Loaded conversation with {slug}. Sending will append to this thread.",thread_subtitle:"History with {persona} on {channel}. Replying here continues the conversation from the web.",empty:"Send a message to start the conversation.",placeholder:"Type something and press enter to send (shift+enter = new line)",send:"Send",stop:"Stop",new_session:"New session",delete:"Delete",delete_confirm_title:"Delete chat",delete_confirm_desc:"This can't be undone. This chat's history will be permanently deleted.",deleted:"Chat deleted.",meta_created:"Created {date} · {channel}",meta_new:"New chat · {channel}",copy:"copy",copied:"Copied.",stopped_marker:" [stopped]",create_agent:"Create agent",create_agent_title:"Create agent",create_agent_desc:"Required to start a chat in this project.",role_label:"role",model_label:"model",model_hint:"e.g. openai:gpt-5, groq:llama-3.3-70b-versatile",master_label:"Master agent",list:{title:"Chats",new:"New",search:"Search chats…",all_agents:"All agents",empty:"No conversations yet. Start one from the right.",count:"{n} total",pick_agent:"Pick an agent"}},tasks:{title:"Tasks (TODOs)",subtitle:"Append-only JSONL in ~/.apx/projects/<id>/tasks/.",add:"add",add_label:"New task",add_placeholder:"e.g. fix scroll bug",empty:"No {state} tasks.",empty_open:"No open tasks.",created:"Task created.",create_error:"could not create task",done:"✓ done",drop:"✗ drop",reopen:"↻ reopen",due:"due",via:"via",aria_done:"mark done",aria_drop:"discard task",aria_reopen:"reopen task"},global_tasks:{any_status:"any status",title:"Tasks (all projects)",subtitle:"Aggregated tasks from all registered projects.",empty:"No tasks.",due:"due",go_project:"Go to project"},routines:{title:"Heartbeats / Routines",subtitle:"Cron, every:Nm, once:ISO. Each routine fires an agent or a shell.",empty:"No routines. Create one above.",new:"new",new_btn:"New",delete_confirm:"Delete routine {name}?",delete_confirm_body:"This can't be undone.",saved:"Routine saved.",paused:"paused",next_run:"next:",last_run:"last:",enabled_hint:"Active · runs on schedule",disabled_hint:"Paused · only via Run button",enabled_label:"Enabled",new_title:"New routine",edit_title:"Edit {name}",dialog_desc:"Saved in .apc/routines.json. The routine runs while the daemon is active.",name_field:"Name",name_no_edit:"Cannot be changed when editing.",kind_field:"Action (kind)",schedule_field:"Interval (schedule)",schedule_hint:"Choose a preset or type manually. Manual = only runs via Run button.",vars_title:"Available variables",what_happens:"What will happen",list_title:"Routines",detail_empty:"Pick a routine from the list.",edit_btn:"Edit",edit_hint:"Open the editor: kind, schedule, prompt, pre/post and variables.",block_pre:"Pre-commands",block_post:"Post-commands",block_prompt:"Prompt",block_text:"Text",block_command:"Command",block_empty:"(empty)",runs_title:"Executions",runs_empty:"No executions yet.",runs_close:"Close",runs_no_detail:"No further detail.",runs_output:"Output",status_ok:"ok",status_error:"error",status_skipped:"skipped",agent_field:"Agent (spec.agent)",agent_hint:"Who executes the routine.",agent_loading:"loading…",agent_pick:"— pick an agent —",prompt_exec:"Prompt (spec.prompt)",prompt_exec_ph:"what is pending for today?",prompt_super:"Prompt (spec.prompt)",prompt_super_ph:"summarize the project status",pre_field:"Pre-commands (pre_commands)",pre_hint:"Shell BEFORE the prompt. One per line.",post_field:"Post-commands (post_commands)",post_hint:"Shell AFTER the prompt. One per line.",tg_channel:"Channel (spec.channel)",tg_chat_id:"Chat ID (spec.chat_id)",tg_text:"Telegram Message (spec.text)",tg_text_hint:"Fixed message to send. Does not use a model.",shell_field:"Command (spec.command)",shell_hint:"Runs as-is in the shell. No prompt, no pre/post.",hb_channel:"Channel (spec.channel)",hb_message:"Message (spec.message)",name_required:"name required",save_error:"save failed",run_error:"run failed",toggle_error:"toggle failed",delete_error:"delete failed",run_success:"{name} fired.",run_confirm:"Run routine {name} now?",run_confirm_body:"Runs the action once, regardless of the schedule.",running:"Running…",delete_success:"deleted."},agents:{title:"Agents",subtitle:"Defined in .apc/agents/<slug>.md.",subtitle_full:"Defined in .apc/agents/<slug>.md. Runtime memory lives under ~/.apx/projects/<id>/agents/<slug>/.",empty:"No agents. Add one with <code>apx agent add</code> or the button.",empty_text:"No agents. Add one with `apx agent add` or the button above.",new:"Agent",created:"Agent {slug} created.",slug_invalid:"slug must match /^[a-z][a-z0-9_-]*$/",hierarchy:"Hierarchy",list_view:"List",import:"Import",chat:"Chat",view:"View",orchestrator:"Orchestrator",new_title:"New agent",new_desc:"POST /projects/:pid/agents — writes .apc/agents/<slug>.md.",slug_label:"slug",slug_ph:"cody",role_label:"role (optional)",role_ph:"code refactor",model_label:"model (optional)",model_hint:"e.g. ollama:gemma2:9b, openai:gpt-4o-mini",lang_label:"language (optional)",desc_label:"description (optional)",desc_ph:"What does this agent do…",skills_label:"skills (comma)",skills_ph:"skill-a, skill-b",tools_label:"tools (comma)",tools_ph:"tool-a, tool-b",parent_label:"reports to (parent, optional)",parent_hint:"Sub-agent of an orchestrator.",none_parent:"— none —",master_label:"Orchestrator (master)",create_success:"Agent {slug} created.",create_error:"create failed",import_title:"Import from vault",import_desc:"Templates in ~/.apx/agents. Registered in this project (.apc/agents/<slug>.md).",import_empty:"No templates in the vault.",import_success:"Imported: {slug}",import_already:"already here",import_btn:"Import"},agent_detail:{not_found:"Agent not found.",chat_btn:"Chat with {slug}",reports_to:"↳ reports to",no_threads:"No threads.",no_activity:"No recorded activity.",threads_recent:"Recent threads",subagents:"Sub-agents",subagents_desc:"Agents that report to this orchestrator.",config_title:"Agent configuration",type_label:"Type",area_label:"Area",area_hint:"e.g. operations, marketing",area_ph:"operations",role_label:"Role",parent_label:"Reports to (parent)",none_parent:"— none —",model_label:"Base model",model_hint:"Empty = uses the Router model (default). Set only to force a model for this agent.",model_ph:"(empty = router default)",skills_label:"Skills (comma)",bio_label:"Bio / description",system_label:"System prompt",system_hint:"Defines personality and behavior (body of AGENT.md).",master_label:"Orchestrator (master)",delete_btn:"Delete agent",save_btn:"Save changes",delete_confirm:'Delete agent "{slug}"? Removes .apc/agents/{slug}.md and local runtime data.',update_success:"Agent updated.",delete_success:"Agent deleted.",tools_hint:"Which tools this agent can use. Tap to toggle; or edit the list below.",tools_custom_ph:"list (comma): echo, http_fetch",memory_title:"Agent memory",memory_empty:"(empty memory)",memory_saved:"Memory saved.",records_title:"Records",records_desc:"Agent activity log (messages/actions). Newest first.",sleep_title:"Sleep / Heartbeat",sleep_desc:"Agent execution status, derived from its routines.",sleep_deep:"Deep sleep · no heartbeat",sleep_deep_desc:"This agent has no routine that triggers it. It does not run autonomously; it only responds when invoked (chat / task).",brain_title:"Brain",brain_desc:"Real relationship graph of the agent: memory, threads, tasks, heartbeats and hierarchy. (first version — will be refined)",brain_empty:"No relationships to graph yet (no memory, threads, tasks or routines).",msgs_count:"msgs"},mcps:{title:"MCP servers",subtitle:"3 scopes: runtime > shared > global. Conflicts shown above if any.",empty:"No MCPs configured.",new:"MCP",delete_confirm:"Delete MCP {name} from scope {scope}?",conflicts:"⚠ Conflicts: {names}",conflict_detail:"{name} is defined in {winner} and {loser}. APX uses {winner}; {loser} is ignored.",new_title:"New MCP",new_desc:"POST /projects/:pid/mcps?scope=…",scope_label:"Scope",transport_label:"Transport",name_label:"Name",name_ph:"filesystem",cmd_label:"Command",cmd_ph:"npx",args_label:"Args",args_hint:"space-separated",args_ph:"-y @modelcontextprotocol/server-filesystem /tmp",env_label:"Env (JSON, optional)",url_label:"URL",url_ph:"https://example.com/mcp",enabled_label:"Enabled",add_btn:"Add",name_required:"name required",env_invalid:"env must be valid JSON",removed:"removed",added:"MCP added.",updated:"MCP updated.",edit_title:"Edit MCP",save_btn:"Save",add_arg:"Add arg",edit_btn:"Edit",test_btn:"Test",logs_btn:"Logs",testing:"Testing…",test_ok:"OK · {n} tools available",tools_count:"{n} tools",logs_title:"Logs · {name}",logs_empty:"No logs yet. Start the MCP by calling a tool or running Test.",logs_events:"Recent events",logs_stderr:"stderr (last 4KB)",logs_panel_title:"Live logs",logs_panel_pick:"pick an MCP",logs_panel_hint:"Click an MCP in the list to see what's happening live.",logs_panel_idle:"No activity. Hit Test to spin it up.",scope_runtime:"Runtime",scope_shared:"Shared",scope_global:"Global",source_runtime:"Runtime",source_apc:"APC / Shared",source_claude:"Claude",source_codex:"Codex",source_cursor:"Cursor",source_vscode:"VS Code",source_roo:"Roo",source_gemini:"Gemini",scope_runtime_desc:"This project only · with secrets · not committed (~/.apx/projects/<id>/mcps.json)",scope_shared_desc:"This project only · committeable · no secrets (.apc/mcps.json)",scope_global_desc:"All projects on this machine (~/.apx/mcps.json)",transport_stdio:"stdio",transport_http:"HTTP",transport_stdio_desc:"Local process — `command` + args",transport_http_desc:"Remote endpoint — URL + headers",args_hint_tokens:"One entry per arg. Use the + button to insert a variable.",env_hint_tokens:"Key/value pairs. Values accept ${var.NAME} (+ button on the right).",env_empty:"No env vars.",headers_label:"Headers",headers_hint:"Key/value pairs — typically Authorization: Bearer ${var.TOKEN}.",headers_empty:"No headers."},vars:{title:"Variables",subtitle_project:"Replace ${var.NAME} when loading MCPs and templates. Project vars beat globals. Stored outside the repo (~/.apx/, chmod 0600).",subtitle_base:"Global variables — available to every project. Stored in ~/.apx/vars.json (chmod 0600).",empty:"No variables yet.",new:"Variable",new_title:"New variable",edit_title:"Edit variable",new_desc:"Referenced as ${var.NAME} in any field that supports interpolation.",reveal_all:"Show values",reveal:"Show",hide:"Hide",filter_label:"Show:",filter_all:"All",filter_project:"Project only",filter_global:"Globals only",scope_label:"Scope",scope_project:"project",scope_project_desc:"This project only. Beats the global with the same name.",scope_global:"global",scope_global_desc:"Available to every project.",name_label:"Name",name_hint:"Uppercase, digits and _. E.g. MY_API_KEY, GITHUB_TOKEN.",value_label:"Value",value_hint:"Stored on disk with 0600 perms. Never committed.",value_edit_ph:"(leave empty to keep current… not yet supported, paste the value again)",add_btn:"Add",save_btn:"Save",edit_btn:"Edit",delete_btn:"Delete",delete_confirm:"Delete {name} ({scope})?",removed:"Variable removed.",added:"Variable added.",updated:"Variable updated.",name_required:"Name required.",value_required:"Value required."},threads:{title:"Chats",subtitle:"Conversations per agent (empty = no logs persisted yet).",no_agents:"No agents. Conversations require a configured agent.",pick:"Pick an agent to view its conversations.",empty:"No conversations for {slug}.",conversation_title:"Conversation {id}",messages:"messages",via:"via"},config:{title:"Quick config",subtitle:"Project override. Written to {path}.",model:"super_agent.model",model_hint:"e.g. anthropic:claude-sonnet-4.5, ollama:gemma2:9b",perm:"super_agent.permission_mode",route:"route_to_agent",route_hint:"Slug of the agent that handles this project by default.",use_global:"(uses global)",saved:"Saved.",nothing:"Nothing to save.",raw_title:"Config (raw JSON)",raw_subtitle:"Paste the entire object — equivalent to PUT the file.",raw_save:"Replace config",raw_done:"Config overwritten.",effective:"Effective config (read-only)",effective_sub:"What the daemon actually sees (global ⊕ override).",section_title:"Project config",section_desc:"APC metadata and overrides separated. General APX lives in Settings > Config.",effective_read:"Read: global APX + project override.",save_project:".apc/project.json saved.",save_override:".apc/config.json saved.",save_fields_success:"Overrides saved.",save_meta_success:"Project metadata saved.",no_data:"No data.",tab_settings:"Settings",tab_project:"Project"},telegram:{title:"Telegram channel (override)",subtitle:"If you set a channel here, messages from this project go there instead of the default.",use_default:"Use default channel",bot_token:"Bot token (override)",chat_id:"Chat ID (override)",saved:"Override saved.",cleared:"Override removed — falls back to default.",override_active:"override active",channel_badge:"Channel {name}",no_override:"No override. Messages from this project go to the default channel.",respond_engine:"Respond with engine",route_agent:"route_to_agent",route_hint:"Slug of the agent that handles messages (empty = super-agent).",bot_hint_none:"If empty, inherits from default."},memories:{sidebar_title:"Memories",general_group:"General",general_item:"Project memory",project_title:"Project memory",project_desc:"Durable facts at the project level. .apc/memory.md — read by agents and the super-agent.",project_ph:`# Project Memory
|
|
774
774
|
|
|
775
775
|
Stable facts that any agent should know…`,agents_title:"Agent memories",agents_desc:"Individual memory per agent. ~/.apx/projects/<id>/agents/<slug>/memory.md",no_agents:"No agents in this project.",saved:"Memory saved.",empty:"(empty memory)",chars:"chars · Markdown",save_btn:"Save"}},base:{title:"Base",subtitle:"General workspace · super-agent",nav_general:"General",nav_activity:"Activity",nav_system:"System",workspaces_title:"Workspaces",workspaces_desc:"All projects registered in APX.",workspaces_new:"New project",workspaces_empty:"No projects. Add one with the button above.",sessions_title:"Sessions",sessions_desc:"Sessions from all engines (apx · claude · codex), newest first.",sessions_desc_scoped:"Sessions in this project's folder ({path}), all engines, newest first.",sessions_all:"All engines",sessions_empty:"No sessions.",sessions_error:"Could not read sessions: {msg}",sessions_search_ph:"Search sessions…",sessions_deep:"Deep",sessions_deep_tip:"Also search inside transcripts (slower)",sessions_clear:"Clear filters",sessions_refresh:"Refresh list",sessions_no_match:"No sessions match “{q}”.",sessions_act_cmd:"Copy apx command",sessions_act_ask:"Ask {name} to continue",sessions_act_folder:"Open folder",sessions_act_path:"Copy path",sessions_cmd_copied:"Command copied — paste it in your terminal",sessions_path_copied:"Path copied",sessions_copy_failed:"Could not copy",sessions_no_folder:"This session has no folder",sessions_no_path:"This session has no path",sessions_folder_failed:"Could not open folder: {msg}",defaults_title:"Agent defaults",defaults_desc:"Global vault templates. Bundled ones come with APX and are always present; ones you create or edit go in ~/.apx/agents and override. Import them into a project from Agents › Import.",defaults_show_removed:"Show removed",defaults_new:"New",defaults_empty:"No templates in the vault.",defaults_hide:"Hide",defaults_restore:"Restore",defaults_edit:"Edit",defaults_remove:"Hide",defaults_delete:"Delete",defaults_tombstone_msg:`Hide the default "{slug}"? It's bundled — tombstoned and recoverable with Restore.`,defaults_delete_msg:'Delete the template "{slug}"?',defaults_hidden:"Hidden.",defaults_deleted:"Deleted.",defaults_restored:"Restored.",defaults_new_title:"New template",defaults_new_desc:"POST /agents/vault — saved to ~/.apx/agents/<slug>.md",defaults_edit_title:'Edit "{slug}"',defaults_bundled_desc:"This is a bundled default. Saving does a copy-on-write to ~/.apx/agents/<slug>.md (becomes an override).",defaults_user_desc:"PATCH /agents/vault/:slug — edits the file in ~/.apx/agents.",defaults_master_label:"Master agent",defaults_slug_invalid:"invalid slug (must match /^[a-z][a-z0-9_-]*$/)",defaults_created:'Template "{slug}" created.',defaults_saved:'Template "{slug}" saved.'},logs:{title:"Logs",desc_global:"Daemon activity (global channels: telegram, direct…). ~/.apx/messages/<channel>/.",desc_project:"Project activity. ~/.apx/projects/<id>/messages/.",filter_channel:"filter channel (e.g. telegram)",filter_dir:"direction",all_directions:"All directions",in:"Incoming (in)",out:"Outgoing (out)",filter_type:"type",all_types:"All types",search_text:"search text…",count_of:"of",no_activity:"No activity.",no_activity_ch:'No activity in channel "{ch}".',error:"Could not read messages: {msg}",show_more:"show more",show_less:"show less",daemon_errors:"Daemon errors (~/.apx/logs/errors.jsonl)",no_errors:"No errors recorded. 🎉"},telegram_contacts:{title:"Telegram contacts",desc:"Who writes to the bots. The role defines which tools they can use; a guest has no permissions until you assign a role.",empty:"No contacts yet — they register automatically when someone writes to a bot.",owner_badge:"owner",assign_role:"Assign role",owner_hint:"Channel owner — change it from the channel",removed:"Contact deleted.",delete_confirm:"Delete contact {name}?",last_seen:"seen:",tools_all:"tools: all",tools_none:"tools: none",tools_label:"tools:"},telegram_channels:{title:"Channels",desc:"Each channel is a bot the daemon polls. Here you can add/remove channels, change the answering agent, the project it belongs to and its owner.",new_btn:"New channel",empty:"No channels yet — add the first one.",removed:"Channel deleted.",delete_confirm:"Delete channel {name}?",no_owner:"no owner (claimed on first DM)",owner_label:"owner:"},telegram_channel_dialog:{new_title:"New Telegram channel",edit_title:"Edit channel: {name}",name_label:"name (internal slug)",token_label:"bot_token",chat_id:"chat_id",project_label:"project",project_hint:"Slug or id of the project to pin this channel to (optional).",route_label:"route_to_agent",route_hint:"Answering agent; empty = APX super-agent.",owner_label:"owner_user_id",owner_hint:"Telegram user_id of the channel owner. Overrides global role to 'owner' here. Leave empty — first private message claims it.",owner_ph:"889721252",respond_label:"Respond with engine (not echo)",name_required:"name required",saved:"Channel saved."},telegram_send_dialog:{title:"Send to {name}",default_msg:"Test message from APX panel ✅"},telegram_roles:{title:"Roles",desc:"Each role defines which super-agent tools the assigned user can invoke. 'owner' always = all; 'guest' always = none (chat only).",empty:"No roles defined.",tools_all:"all tools",tools_none:"no tools",builtin:"built-in",delete_confirm:'Delete role "{name}"?',removed:"Role deleted.",saved:'Role "{name}" saved.',name_required:"Name required.",builtin_error:'"{name}" is a built-in role.',new_title:"New role or replace a custom one",name_label:"Name",name_ph:"editor",tools_label:"Tools (comma-separated)",tools_hint:"Empty = none. Examples: call_agent, list_tasks, create_task.",tools_ph:"call_agent, list_tasks",full_access:"Full access (all tools)",save_btn:"Save role",delete_btn:"Delete"},superagent:{title:"{persona}",badge:"super-agent · APX",desc:"Quick chat with your super-agent. Has access to tools (projects, tasks, mcps, agents); for a longer persistent thread, open Chats.",empty:"Send {persona} a message to get started.",thinking:"{persona} is thinking…",talk:"Talk to {persona}",new_chat:"New chat",placeholder:"Type and press enter to send (shift+enter = new line)…"},not_found:{title:"404",message:"Roby got lost: this page doesn't exist or has moved.",home:"Back to home"},ask_panel:{answers_header:"Answers",other:"Other",other_placeholder:"Write your own answer here",text_placeholder:"Type your answer…",back:"Back",skip:"Skip",next:"Next",submit:"Send",status_waiting:"Waiting for your answer…",status_received:"Answers received"},code_module:{title:"Code",badge:"super-agent",desc:"OpenCode-style coding sessions. Pick a project, open a session, and ask it to read, plan, edit or run.",no_projects:"No registered projects. Register one with `apx project add` to use Code.",sessions:"Sessions",new_session:"New session",untitled:"New session",no_sessions:"No sessions yet — create one to start coding.",pick_project:"Pick a project to see its sessions.",rename:"Rename",delete:"Delete",delete_confirm:"Delete this session? The transcript is removed; your files are untouched.",empty_chat:"Send a coding instruction to get started.",placeholder:"Ask for a change… (enter sends, shift+enter = new line)",mode_build:"Build",mode_plan:"Plan",mode_build_hint:"Build — edits files and runs commands",mode_plan_hint:"Plan — read-only, proposes changes without touching files",tab_context:"Context",tab_changes:"Changes",tab_artifacts:"Artifacts",artifacts_none:"No artifacts yet. Ask the agent to create a script under `artifacts/<name>`.",artifacts_count:"{n} artifact(s)",artifacts_copy_path:"Copy path",artifacts_run:"Run",artifacts_run_hint:"Run it from your terminal:",artifacts_delete:"Delete",artifacts_delete_confirm:"Delete this artifact? The file will be removed from disk.",ctx_model:"Model",ctx_tokens:"Tokens",ctx_input:"Input",ctx_output:"Output",ctx_messages:"Messages",ctx_breakdown:"Context breakdown",ctx_none:"No usage yet — send a turn to see tokens.",seg_system:"System",seg_user:"User",seg_assistant:"Assistant",seg_tool:"Tools",seg_other:"Other",changes_none:"No changes in this session yet.",changes_no_git:"Changes need a git repository. This project isn't one.",changes_files:"{n} file(s) changed",stopped:"[stopped]",close:"Close",reload:"Reload",discard_changes:"Discard changes",save_shortcut_hint:"Save (Cmd/Ctrl+S)",artifacts_rename:"Rename",artifacts_view:"View contents",artifacts_edit:"Edit contents",artifacts_preview:"Preview",artifacts_preview_hint:"Open a live preview in a local browser tab",artifacts_share:"Share",artifacts_share_hint:"Create a public tunnel URL to share this preview",artifacts_stop_preview:"Stop preview",artifacts_preview_local:"Local preview",artifacts_preview_public:"Public URL",artifacts_copy_url:"Copy URL",artifacts_preview_started:"Preview running at {url}",tree_collapse_all:"Collapse all",terminal_clear:"Clear",terminal_close:"Close terminal"},desktop_screen:{status_title:"Status",autostart_title:"Auto-start",shortcut_title:"Keyboard shortcut",appearance_title:"Appearance",activation_title:"Activation + transcription",last_conv_title:"Last conversation",open_config:"Configuration"},voice_screen:{providers_title:"Voice providers (TTS)",test_title:"Test voice",stt_title:"Transcription (STT)",configure_provider:"Configure {name}"},deck_screen:{widgets_title:"Widgets",context_title:"APX context",reload_manifest:"Reload manifest",widget_native:"Native APX widget",widget_external:"External widget",preview_badge:"Preview",preview_title:"Deck — Coming soon",preview_body:"The Deck module is still in development and not released yet. We'll re-enable it once Deck ships in a stable release. For now everything here is read-only and no changes will be saved."},memory_panel:{embeddings_title:"Embeddings (RAG)",embeddings_desc:"Model that vectorizes the history of all channels for relevant memory. Just like TTS/STT: pick a provider and model. 'Automatic' tries local first and falls back to offline if nothing is available.",provider_label:"Provider",provider_hint:"Ollama is local and free. Gemini/OpenAI use the API key from their section in Models (or the one below).",mode_label:"Selection mode",mode_hint:"Chain falls back to the next if one fails; Single uses exactly the chosen provider.",available:"available",unavailable:"unavail.",test_btn:"Test embedding",reindex_btn:"Reindex memory",test_ok:"Embedding OK with {embedder}",test_failed:"Test failed: {msg}",reindexed:"Reindexed: {indexed} chunks (cleared {cleared}).",reindex_failed:"Reindex failed: {msg}",save_failed:"Could not save: {msg}",provider_auto:"Automatic (chain: Ollama → Gemini → OpenAI → offline)",provider_ollama:"Ollama — local, no API key (nomic-embed-text)",provider_gemini:"Gemini — free tier with key (text-embedding-004)",provider_openai:"OpenAI — text-embedding-3-small (cloud)",provider_tf:"Offline (term-frequency, no model — degraded)",mode_chain:"Chain (automatic fallback)",mode_single:"Single (uses only the chosen one)",ollama_title:"Ollama (local)",ollama_desc:"No API key. Runs nomic-embed-text on your local or cloud Ollama.",model_label:"Model",base_url_label:"Base URL",ollama_base_url_hint:"Empty uses engines.ollama.base_url (default http://localhost:11434).",openai_title:"OpenAI",openai_desc:"text-embedding-3-small (1536 dims) or another compatible model.",api_key_label:"API key",openai_key_hint:"Empty reuses engines.openai.api_key. Leave it blank to keep the saved one.",gemini_title:"Gemini",gemini_desc:"text-embedding-004 (768 dims). Free tier with a Google API key.",gemini_key_hint:"Empty reuses engines.gemini.api_key.",compaction_title:"History compaction",compaction_desc:"When a chat exceeds the turn threshold, the oldest turns are summarized with a lightweight (local) LLM and saved as [COMPACTED SUMMARY], keeping context bounded. Runs off the hot-path: the current turn uses whatever summary already exists.",threshold_label:"Compaction threshold",threshold_hint:"Compact once the chat exceeds these turns (default 60).",keep_recent_label:"Recent turns to preserve",keep_recent_hint:"Verbatim turns that are NEVER compacted (default 40). Must be lower than the threshold.",compact_model_label:"Compaction model",compact_model_hint:"Lightweight LLM for summarizing. Ideally a local one (Ollama) to avoid cost. Format provider:model.",compact_fallback_label:"Fallback model",compact_fallback_hint:"Used if the compaction one fails. Empty falls back to the super-agent model.",compact_fallback_ph:"(empty → super-agent model)"},router_panel:{title:"Model router",description:"A single general router (no per-task cases). Pick a provider and model; if the active one fails, it tries the fallback chain in order.",badge_default:"default",no_providers:"Add a provider below to be able to pick models.",active_model_label:"Active model (default)",active_model_hint:"Provider + model. Saved as provider:model.",fallback_title:"Fallback chain",fallback_desc:"If the active model fails, it tries these in order. Click one to edit it.",fallback_empty:"No fallback configured.",add_to_chain:"Add to the chain",done:"done",save:"Save router",saved:"Saved",saved_toast:"Router saved.",provider_ph:"— provider —",provider_not_found:"⚠ {name} (not found)",provider_not_configured:'The provider "{name}" is not configured.'},routing_panel:{title:"Content routing",description:"Prefer a different model per message based on its content (image, size, channel, keywords). Separate from the fallback chain above.",signal_on:"Content routing: ON ({n} rules)",signal_on_empty:"Content routing: ON (no rules yet)",signal_off:"Content routing: OFF",how_it_works:"How does it work?",enable_label:"Enable content routing",rules_title:"Routing rules",rules_desc:"Evaluated top to bottom; the first rule whose conditions all match wins.",rules_empty:"No rules yet. Add some in the editor.",edit_rules:"Edit rules (JSON)",hide_editor:"Hide editor",editor_label:"Rules (JSON array)",json_hint:"Array of { model, when }. when keys: has_image, min_prompt_chars, max_prompt_chars, min_context_chars, channels[], keywords[]. Empty when = matches every message.",json_error:"Invalid JSON: {msg}",json_not_array:"The rules must be a JSON array.",insert_example:"Insert an example",when_any:"any message",when_image:"has image",when_no_image:"no image",when_min_prompt:"prompt ≥ {n} chars",when_max_prompt:"prompt ≤ {n} chars",when_min_context:"context ≥ {n} chars",when_channels:"channels: {list}",when_keywords:"keywords: {list}",helper:"Routing picks a model per message (image, size, channel, keywords). It composes with failover: a routed model that is down falls back down the chain. An explicit per-request model override always wins.",save:"Save routing",saved:"Saved",saved_toast:"Content routing saved.",confirm_title:"Apply routing changes?",confirm_body:"This changes which model handles each message. Failover still applies if a routed model is down.",confirm_on:"Content routing will be ON with {n} rules.",confirm_off:"Content routing will be OFF (every message uses the default router).",confirm_apply:"Apply",cancel:"Cancel"},engines_panel:{title:"Providers",new_btn:"New provider",description:"LLM providers (API). Each provider uses an engine/adapter (openai, ollama, …) with its key and URL.",empty:"No providers. Add one with the button above.",add_card:"Add provider",saved:"Provider saved.",saved_json:"Provider saved (JSON).",deleted:"Provider deleted.",delete_confirm:"Delete provider {name}?"},providers_modal:{new_title:"New provider",edit_title:"Edit {name}",description:"LLM provider. The engine defines which adapter it uses (openai, ollama, …).",list_models_hint:"List the provider's actual models",toggle_active:"Active · click to deactivate",toggle_inactive:"Inactive · click to activate",delete:"Delete",custom:"Custom",json_mode:"JSON",form_mode:"Back to form",json_label:"Provider config (JSON)",json_hint:"Saved as engines.{slug} in config.json",json_help:"Must be a valid JSON object with at least engine. The slug is taken from the form.",name_label:"Name",name_ph:"My provider",engine_label:"Engine",base_url_label:"Base URL (base_url)",base_url_hint:"Auto-filled when you pick a provider.",base_url_ph:"https://api.openai.com/v1",api_key_label:"API key",api_key_hint_existing:"Leave blank to keep the current one.",api_key_hint_env:"Stored as a secret. Suggested env: {env}",api_key_hint:"Stored as a secret.",api_key_set:"…{suffix} (already set)",model_label:"Default model",load_models:"Load models",max_tokens_label:"Max tokens (max_tokens)",temperature_label:"Temperature: {value}",pricing_summary:"Token analysis / pricing (optional)",context_limit_label:"Context limit (tokens)",price_input:"$ input / 1M",price_output:"$ output / 1M",price_cache_read:"$ cache read / 1M",price_cache_write:"$ cache write / 1M",model_limits_label:"Per-model context limits (JSON)",active_label:"Active (agents can use it)",err_slug_required:"Slug required.",err_slug_required_form:"Slug required (in the form).",err_slug_exists:'A provider "{slug}" already exists.',err_model_limits_json:"Per-model context limits: invalid JSON.",err_json_invalid:"Invalid JSON: check the syntax.",err_json_object:"The JSON must be an object with the provider config.",err_engine_missing:'Missing "engine" (e.g. "anthropic", "ollama").',err_save:"Error saving.",err_no_models:"No models. Correct key/URL?",err_list_models:"Could not list models."},providers_card:{active:"Active",off:"Off",model:"Model",base_url:"Base URL",api_key:"API key",key_set:"✓ set",temp:"Temp",price_io:"$ in/out (1M)"},chat_ui:{copy:"Copy",stop:"Stop",send:"Send",pick_model:"Pick model (or Auto)",insert_variable:"Insert variable",ctx_files:"files",ctx_actors:"{n} agents/models",ctx_turns:"{n} turns"},sidebar_ui:{toggle:"Toggle sidebar"},models_ui:{invalid_hint:"Model/provider unavailable"},global_config:{title:"APX config"},agent_detail_extra:{skills_title:"Skills & tools"},voice_ui:{api_key_label:"API key",api_key_set:"…{suffix} (already set)",api_key_keep_hint:"Leave blank to keep the current one.",api_key_secret_hint:"Stored as a secret. Env: {env}",api_key_reuse_hint:"Reuses {engine} if left blank. Env: {env}",err_save:"Error while saving.",model_label:"Model",voice_label:"Voice",format_label:"Format",output_format_label:"Output format",voice_id_label:"Voice ID",voice_id_hint:"ElevenLabs voice id (empty = default).",gemini_model_hint:"Gemini TTS is still in preview.",base_url_label:"Base URL (optional)",base_url_hint:"OpenAI-compatible endpoint. Empty = OpenAI. Point it at a local server (e.g. a QVox / Qwen3-TTS daemon) to use that instead.",openai_model_hint:"tts-1 / tts-1-hd for OpenAI. Leave blank to let a custom server pick.",openai_voice_hint:"OpenAI preset (alloy…) or a custom server's preset (e.g. custom). Empty = server default.",openai_style_hint:"Base voice / instruct, used by custom endpoints (the persona kept across the audio). Ignored by stock OpenAI tts-1.",style_label:"Style (how it should speak)",style_hint:"Natural-language instruction. Empty = no style. E.g.: 'speak in a cheerful, unhurried tone'.",style_ph:"speak in a cheerful, energetic tone",temperature_label:"Temperature (optional)",temperature_hint:"Sampling temperature for custom endpoints. Empty = server default.",emotions_short:"Emotions",emotions_label:"Inline emotion tags",emotions_hint:"When this engine speaks, let the agent drop [happy]/[whisper]-style tags into voice replies to color the delivery. Only enable it if this engine understands the tags (e.g. a QVox/Qwen3-TTS endpoint) — otherwise they're stripped before synthesis.",emotions_tags_label:"Allowed tags",emotions_tags_hint:"Comma-separated. Empty = the default set.",piper_bin_label:"Binary (bin)",piper_bin_hint:"Path or name of the piper CLI (PATH).",piper_model_label:"Model (.onnx)",piper_model_hint:"Absolute path to the piper voice model.",piper_speaker_label:"Speaker (optional)",piper_speaker_hint:"Speaker id for multi-voice models.",mock_desc:"The mock engine generates a silent test WAV. It has no parameters: it serves as a guaranteed fallback when no other engine is configured.",selection_mode:"Selection mode",mode_chain_desc:"Chain with fallback: uses the first available engine following the order below.",mode_single_desc:"Default engine only: always uses the chosen one; the rest stay configured for other purposes.",mode_chain_btn:"Chain (router)",mode_single_btn:"Default engine only",move_up:"Move up",move_down:"Move down",badge_local:"local",badge_available:"available",badge_unavailable:"configured, unavailable",badge_not_configured:"not configured",badge_default:"default",badge_custom:"custom",set_as_default:"Set as default",configure:"Configure",remove:"Remove",remove_confirm:"Remove this custom provider?",add_provider:"Add provider",new_provider:"New provider",custom_note:"Custom OpenAI-compatible endpoint.",custom_desc:"Any OpenAI-compatible speech endpoint (e.g. a local QVox / Qwen3-TTS server).",label_label:"Name",label_hint:"Display name for this provider.",base_url_req_label:"Base URL",base_url_req_hint:"Required. The OpenAI-compatible endpoint, e.g. http://127.0.0.1:5111/v1",api_key_optional_hint:"Optional — only if your server requires a key.",advanced:"Advanced",custom_model_hint:"Optional. Most local servers ignore it (e.g. QVox).",custom_voice_hint:"Optional. A preset your server understands (e.g. custom). Empty = server default.",custom_optional_ph:"(optional)",stt_engine_label:"Transcription engine",stt_engine_hint:"Local uses faster-whisper (requires python3 + faster-whisper). OpenAI uses the engines.openai key.",stt_model_label:"Local model (whisper)",stt_model_hint:"Bigger = more accurate and slower.",stt_language_label:"Language",stt_language_hint:'For Spanish, setting "Spanish" improves accuracy.',stt_provider_auto:"Automatic (local, then remote)",stt_provider_local:"Local — faster-whisper (offline)",stt_provider_openai:"OpenAI — Whisper-1 (cloud)",stt_provider_custom:"Custom — OpenAI-compatible server",stt_openai_model_label:"OpenAI model",stt_openai_model_hint:"Defaults to whisper-1.",stt_custom_baseurl_label:"Base URL (OpenAI-compatible)",stt_custom_baseurl_hint:"e.g. http://localhost:8000/v1 (mlx-audio on Metal) or http://192.168.1.50:9000/v1 (Radeon/NVIDIA on the LAN).",stt_custom_model_label:"Model",stt_custom_model_hint:"e.g. mlx-community/whisper-large-v3-turbo or large-v3.",stt_custom_key_hint:"Optional — most local servers need no key.",stt_hw_label:"Detected hardware",stt_hw_recommended:"Recommended",stt_hw_limited:"limited GPU acceleration, using CPU",stt_backend_label:"Acceleration / Engine",stt_backend_hint:"Auto adapts to your hardware. Metal runs on the GPU (mlx); CPU uses faster-whisper.",stt_backend_auto:"Automatic (recommended)",stt_model_needs_download:"Not downloaded (~{size}). The model must be downloaded to use this engine.",lang_auto:"Auto-detect",lang_es:"Spanish",lang_en:"English",lang_pt:"Portuguese",lang_fr:"French",lang_it:"Italian",lang_de:"German",test_default_text:"Hi, I'm APX. This is a voice test.",test_default_engine:"Default ({name})",test_default_chain:"Default (chain)",test_unavailable_suffix:" · unavailable",test_empty_error:"Type something to say.",test_synth_error:"Could not synthesize.",test_engine_label:"Engine",test_engine_hint:"Override the default for testing.",test_style_label:"Style (Gemini only)",test_style_hint:"How it should speak. Empty = no style.",test_text_label:"Text to say",test_text_ph:"Type what you want it to say…",say_this:"Say this",stop:"Stop",replay:"Replay",engine_result:"Engine",providers_desc:"Synthesis engines, in fallback order. Status is reported live by the daemon. Add your own OpenAI-compatible endpoints.",providers_load_error:"Could not load providers: {msg}",test_desc:"Pick which engine to synthesize with and, if applicable, how it should speak.",stt_desc:"Speech-to-text engine used by the deck, Telegram, and the CLI when listening.",toast_default_engine:"Default engine: {id}.",toast_mode_chain:"Mode: chain with fallback.",toast_mode_single:"Mode: default engine only.",toast_config_saved:"Voice configuration saved.",toast_provider_removed:"Provider removed.",err_label_required:"A name is required.",err_base_url_required:"A base URL is required.",toast_transcription_updated:"Transcription updated."},telegram_ui:{channel_dialog_desc:"POST /telegram/channels (upsert) — PATCH /telegram/channels/:name (partial).",bot_token_hint:"BotFather token. Stored in ~/.apx/config.json.",bot_token_hint_short:"BotFather token.",secret_set_replace:"(set — type to replace)",secret_already_set:"(already set)",empty_keep:"— empty = keep",message_sent:"Message sent.",message_label:"Text",send_chat_id:"chat_id: {id}",default_apx:"default APX",yes:"yes",no:"no",user_id_fallback:"user_id {id}",role_assigned:"{name} → {role}"},agents_form:{emoji:"Emoji",area:"Area",role:"Role",no_role:"— no role —",autonomy:"Autonomy",autonomy_hint:"How much the agent can do without asking for confirmation.",auto_total:"Total",auto_automatico:"Auto",auto_permiso:"Permission"},structure:{title:"Structure",subtitle:"Company areas and roles. Areas group agents; roles define their function.",info:"Areas are optional groupings. Roles define an agent's function and may belong to an area.",empty:"No areas or roles yet. Create the first one above.",new_area:"New area",new_role:"New role",edit_area:"Edit area",edit_role:"Edit role",create_area:"Create area",create_role:"Create role",name:"Name",slug:"Slug",goal:"Goal",goal_hint:"What this area exists for (optional).",area:"Area",description:"Description",no_area:"— no area —",roles:"Roles",add_role:"role",no_roles:"no roles",general_roles:"General roles",delete_area:"Delete area",delete_role:"Delete role",delete_area_desc:'Delete area "{name}"? Its roles are detached, not deleted.',delete_role_desc:'Delete role "{name}"?'},files:{docs_label:"Docs",files_label:"Files",new_doc:"New document",new_doc_hint:"Folders allowed: cases/onboarding/spec.md",empty:"No files.",docs_empty:"No documentation yet. Create the first document.",truncated:"Listing truncated (too many files).",select_prompt:"Pick a file to view it.",save:"Save",saved:"Saved.",deleted:"Deleted.",created:"Document created.",edit:"Edit",preview:"Preview",discard:"Discard",no_preview:"No preview for this file.",too_large:"File too large to display.",path_label:"File path",path_example:"e.g. cases/onboarding/spec.md",create:"Create"},tasks:{state_open:"open",state_done:"done",state_dropped:"dropped",status_pending:"pending",status_running:"running",status_in_review:"in review",status_blocked:"blocked",done_label:"done",dropped_label:"dropped",detail_title:"Task detail",field_title:"Title",field_prompt:"Prompt",field_status:"Status",field_agent:"Agent",field_creator:"Created by",field_source:"Source",field_created:"Created",field_updated:"Updated",field_done:"Completed",prompt_ph:"Task description / prompt…",toggle_prompt:"Prompt",view_thread:"View thread",mark_done:"Complete"},agents_ui:{model_router_default:"model: router default",slug_kebab_hint:"kebab-case, e.g. reviewer, my-agent, content-writer",comma_separated:"comma-separated",body_hint:"markdown — extends the agent's system prompt",source_user:"user",source_override:"override",source_bundled:"bundled",tab_explorer:"Explorer",type_none:"— no type —",type_orchestrator:"Orchestrator",type_orchestrator_desc:"Coordinates the team and delegates.",type_specialist:"Specialist",type_specialist_desc:"Domain expert; runs tasks.",type_assistant:"Assistant",type_assistant_desc:"Conversational helper.",type_worker:"Worker",type_worker_desc:"Runs autonomous tasks.",type_monitor:"Monitor",type_monitor_desc:"Watches state and reports.",stat_threads:"Threads",stat_records:"Records",stat_tasks:"Tasks",stat_heartbeats:"Heartbeats",uncategorized:"Uncategorized",brain_zoom_in:"Zoom in",brain_zoom_out:"Zoom out",brain_fit:"Fit to view",brain_fullscreen:"Fullscreen",brain_exit_fs:"Exit fullscreen",brain_pan_hint:"scroll to zoom · drag background to pan",brain_expand:"Expand brains",brain_collapse:"Collapse",brain_open:"Open",brain_part_of:"Part of",brain_branches:"Branches",config_def_desc:"definition (frontmatter + system prompt).",memory_durable_desc:"durable facts the agent remembers.",running:"running",paused:"paused",last_error:"last: error",field_tick:"Tick",field_next_tick:"Next tick",field_last_tick:"Last tick",field_last_run:"Last run",tools_label:"Tools",kind_agent:"agent",kind_memory:"memory",kind_thread:"thread",kind_task:"task",kind_routine:"routine",kind_hierarchy:"hierarchy",nodes_drag_hint:"{n} nodes · drag to rearrange",kind_exec_agent:"Project agent",kind_exec_agent_desc:"Runs a project agent with a prompt. You pick which one.",kind_super_agent:"Super-agent",kind_super_agent_desc:"Calls the APX super-agent with a prompt.",kind_telegram:"Telegram",kind_telegram_desc:"Sends a fixed message to a Telegram channel. No model or agent.",kind_shell:"Shell",kind_shell_desc:"Runs a shell command. No prompt or pre/post — the command is the action.",kind_heartbeat:"Heartbeat",kind_heartbeat_desc:"Does nothing except write a line to the logs each time it runs. Useful to confirm the scheduler is alive. If you don't know whether you need it, don't use it.",unit_seconds:"seconds",unit_minutes:"minutes",unit_hours:"hours",unit_days:"days",every_n_unit:"every {n} {unit}",every_v:"every {v}",preset_every_10m:"every 10 min",preset_hourly:"hourly",preset_daily_9am:"daily 9am",preset_weekdays_9am:"weekdays 9am",preset_manual:"Manual",var_pre_output_prompt:"Text output of the pre-commands. Replaced inside the prompt/text before it is sent. Use it to inject fresh data (weather, an API) into the instruction.",var_llm_output:"Final answer from the agent or super-agent. Available in the post-commands as an env var — e.g. forward it via Telegram.",var_status:"Action result: ok or error. Available in the post-commands to branch on what happened.",var_skipped:"1 if the action was skipped (via skip_prompt_on), 0 if it ran. Available in the post-commands.",var_pre_output:"Full pre-commands output, as an env var in the post-commands (up to 32k).",var_pre_output_file:"Path to a temp file with the pre-commands output. For large outputs not suited to an env var.",var_pre_exit:"Exit code of the last pre-command (0 = ok). Available in the post-commands.",var_routine:"Name of this routine. Available as an env var in the commands.",summary_runs_agent:'Runs the agent "{agent}"',summary_runs_agent_none:"Runs an agent (none chosen yet)",summary_super_agent:"Calls the super-agent",summary_telegram:'Sends Telegram to "{channel}"',summary_runs_cmd:"Runs: {cmd}",summary_shell:"Runs a shell command",summary_heartbeat:"Leaves a heartbeat in the logs",action_agent_answers:'Agent "{agent}" answers the prompt',action_agent_pick_answers:"Agent (pick one) answers the prompt",action_super_answers:"The super-agent answers the prompt",action_telegram_channel:'Sends Telegram to channel "{channel}"',action_runs_shell:"Runs the shell command",step_pre:"Pre",step_post:"Post",last_label:"last:",tg_chat_id_ph:"(uses the channel's)",tg_text_ph:"message to send",hb_message_ph:"still alive",arg_placeholder:"--flag or value",remove_arg:"remove arg",super_agent_label:"{persona} (super-agent)",super_agent_badge:"super-agent"},modules_ui:{desktop_pos_left:"Left",desktop_pos_center:"Center",desktop_pos_right:"Right",desktop_theme_system:"System",desktop_theme_light:"Light",desktop_theme_dark:"Dark",desktop_status_desc:"The window launches from the terminal or via autostart.",desktop_running:"Running",desktop_stopped:"Stopped",desktop_refresh:"refresh",desktop_start:"Start",desktop_stop:"Stop",desktop_restart:"Restart",desktop_restart_hint:"Reload the open window so config changes (theme, position) apply now.",desktop_restart_done:"Restarting the window — applying the latest config.",desktop_restart_none:"No desktop window is connected.",desktop_start_done:"Desktop window launched.",desktop_start_already:"Desktop window is already running.",desktop_stop_done:"Desktop window stopped.",desktop_stop_none:"No desktop window was running.",desktop_from_terminal:"From terminal:",desktop_autostart_desc:"Launches the window at user login. Equivalent to `apx desktop install` (no sudo required).",desktop_platform:"platform: {platform}",desktop_shortcut_desc:"Global hotkey that shows/hides the window and starts listening.",desktop_accelerator:"Accelerator",desktop_accelerator_hint:"Click the field and press your key combo. Restart the window to apply.",desktop_shortcut_record:"Click to set a shortcut",desktop_shortcut_recording:"Press your combo…",desktop_shortcut_change:"click to change",desktop_shortcut_esc:"Esc to cancel",desktop_shortcut_saved:"Shortcut saved. Restart the window (apx desktop stop && start) to apply it.",desktop_autostart_on:"Autostart enabled for the next login.",desktop_autostart_off:"Autostart disabled.",desktop_appearance_desc:"Window theme and position on the screen.",desktop_theme:"Theme",desktop_restart_apply:"Restart the window to apply.",desktop_theme_set:"Theme: {value}.",desktop_position:"Position",desktop_position_hint:'"left" / "center" / "right" of the top edge.',desktop_position_set:"Position: {value}.",desktop_activation_desc:"The daemon plugin processes the messages. STT is configured in Voices.",desktop_enabled_toast:"Desktop enabled.",desktop_disabled_toast:"Desktop disabled.",desktop_plugin_on:"Plugin enabled (replies to messages)",desktop_plugin_off:"Plugin disabled",desktop_stt_engine:"Speech-to-text engine:",desktop_stt_engine_suffix:"(local whisper, language, model).",desktop_last_conv_desc:"The latest exchange with the agent from the floating window.",desktop_no_messages:"No messages yet. Send something to the desktop window for it to appear here.",desktop_you:"You",desktop_roby:"Roby",desktop_empty_msg:"(empty)",deck_widget_enabled:"Widget {id} enabled.",deck_widget_disabled:"Widget {id} disabled.",deck_save_error:"Error while saving",deck_loading_manifest:"Loading manifest…",deck_manifest_error:"Error loading the manifest.",deck_widgets_summary:"{count} widgets · {enabled} external enabled",deck_loading_manifest_full:"Loading the Deck manifest…",deck_manifest_load_failed:"Could not load the Deck manifest.",deck_retry:"Retry",deck_no_widgets:"No widgets in the manifest.",deck_context_desc:"Information the Deck sees from the daemon.",deck_active_project:"Active project:",deck_none:"none",deck_registered_projects:"Registered projects:",deck_active_plugins:"Active plugins:",deck_daemon_active:"active · {uptime}",deck_daemon_started:"started",deck_safety_no_shell:"no direct shell",deck_safety_no_arbitrary:"arbitrary commands blocked",deck_safety_confirm:"dangerous actions require confirmation",code_copied:"Copied.",code_saved:"Saved.",code_file_empty:"(empty)",code_file_error:"Error: {msg}",code_stream_error:"error",code_super_agent:"super-agent",code_super_agent_desc:"Main agent with all tools",code_chat_tab:"Chat",code_panel_sessions:"Session list",code_panel_tree:"File tree",code_panel_terminal:"Terminal",code_panel_context:"Context panel",code_ctx_auto:"auto",code_ctx_mode:"Mode",code_ctx_agent:"Agent",code_ctx_msgs_value:"{user} user · {assistant} assistant",code_ctx_tokens_total:"Total Tokens",code_ctx_created:"Created",code_ctx_activity:"Activity",code_project_fallback:"project {id}",code_pick_project_ph:"Pick a project…",code_artifact_exit_ok:"exit 0 — {ms}ms",code_artifact_exit_fail:"exit {code}{timeout}",code_artifact_timeout_suffix:" (timeout)",code_artifact_view_short:"View",code_artifact_edit_short:"Edit",code_artifact_exit_badge:"exit {code}",code_artifact_timeout:"timeout",code_artifact_truncated:"truncated"},settings_ui:{bearer_label:"Bearer",global_config_desc:"General config in ~/.apx/config.json. Editable by tabs; JSON stays separate.",global_json_desc:"Redacted secrets are not overwritten.",save_json:"Save JSON",expand_menu:"Expand menu",collapse_menu:"Collapse menu",documentation:"Documentation",kind_personal:"Personal",kind_company:"Company",kind_app:"App",kind_software:"Software",kind_default:"Default",kind_other:"Other",base_menu_view:"Base menu view (general workspace).",coming_soon:"Coming soon",inspector_title:"Skill Inspector (per-turn RAG)",inspector_desc:"Experimental feature. When active, the agent does NOT receive the full skill list in its prompt; on each message a local RAG decides which skill(s) to load — the full body on a strong match, a suggestion on a medium match, nothing if it doesn't apply. It is re-evaluated every turn: a skill that stopped being relevant disappears from the context.",enable_inspector:"Enable inspector",enable_inspector_hint:"Off = classic behavior (slug list + passive suggestion). On = the RAG decides per turn.",on:"On",off:"Off",index_count:"Index: {n} skills",not_indexed:"not indexed",dim:"dim {dim}",updated_at:"updated {date}",reindex:"Reindex",reindex_forced:"Reindex (forced)",embedder_source:"The embedder comes from Memory (RAG). Local with Ollama, or offline if no provider is set.",thresholds_title:"Thresholds and limits",thresholds_desc:"Tune how aggressive the inspector is. Raising the thresholds = fewer false positives but more risk of missing a skill; lowering them = the opposite.",test_title:"Test (dry-run)",test_desc:"Type a message the way a user would and see which skills the inspector would load/suggest — without calling the model. Forces the inspector on even if it's off above.",test_placeholder:"e.g.: I need to create a promo video with voiceover",test_btn:"Test",jit_empty_index:"JIT (empty index)",loaded_label:"Loaded:",suggested_label:"Suggested:",could_not_save:"Could not save: {msg}",indexed_with:"Indexed with {embedder} (dim {dim}): +{added} ~{refreshed} -{removed}.",index_failed:"Index failed: {msg}",dry_run_failed:"Dry-run failed: {msg}",knob_load_threshold:"Load threshold",knob_load_threshold_hint:"Minimum similarity to inject the skill's BODY (high = stricter).",knob_hint_threshold:"Hint threshold",knob_hint_threshold_hint:"Minimum similarity to only SUGGEST the skill (so the agent loads it if it wants).",knob_margin:"Margin over the 2nd",knob_margin_hint:"The top must beat the second by this margin to load its body (avoids weak ties).",knob_max_loaded:"Max. loaded bodies",knob_max_loaded_hint:"How many skills are injected in full per turn.",knob_max_hints:"Max. hints",knob_max_hints_hint:"How many extra skills are named as a suggestion.",knob_prompt_floor:"Minimum prompt length",knob_prompt_floor_hint:"Messages shorter than this are ignored (avoids 'ok', 'hi').",knob_body_char_cap:"Body char cap",knob_body_char_cap_hint:"Trims long skill bodies so they don't bloat the context.",cfg_overrides_label:"Overrides",cfg_overrides_desc:".apc/config.json. Only project-specific values; empty inherits global/effective.",cfg_route_to_agent:"Route to agent",cfg_super_agent_model:"Super-agent model",cfg_permission_mode:"Permission mode",cfg_extra_prompt:"Extra prompt",cfg_telegram_label:"Telegram",cfg_chat_id:"Chat ID",cfg_bot_token:"Bot token",cfg_respond_with_engine:"Respond with engine",cfg_engines_label:"Engines",cfg_ollama_url:"Ollama URL",cfg_anthropic_key:"Anthropic API key",cfg_openai_key:"OpenAI API key",cfg_groq_key:"Groq API key",cfg_openrouter_key:"OpenRouter API key",cfg_gemini_key:"Gemini API key",cfg_project_label:"Project",cfg_project_desc:".apc/project.json. Portable APC metadata; no secrets, no runtime.",cfg_name:"Name",cfg_version:"Version",cfg_apc_spec:"APC spec",cfg_apx_install:"APX install state",cfg_apx_storage_id:"APX storage id"},skills_page:{title:"Skills",desc:"Turn skills on or off per agent. Pick a scope: the super-agent (global) or a specific project.",list_title:"Installed skills",list_desc:"APX's private skills are always active and can't be changed.",scope_label:"Scope",scope_super_agent:"Super-agent (global)",scope_hint:"The super-agent uses the global scope. Each project can override skills independently.",count_label:"{n} skills · {on} on",empty:"No skills yet. Create one below or install via the CLI.",source_builtin:"APX",source_global:"Global",source_project:"Project",private_badge:"Private",private_hint:"Built-in APX skill — always active, can't be disabled or deleted.",overridden_badge:"Override",inherited_hint:"Inherited from global",reset_to_global:"Reset to global",on:"on",off:"off",toggle_failed:"Could not change state: {msg}",add_title:"Add a skill",add_desc:"Creates a user skill at ~/.apx/skills/<slug>/SKILL.md. Available across all scopes.",add_slug_label:"Slug",add_slug_ph:"my-skill",add_desc_label:"Description",add_desc_ph:"One line describing when to use it",add_body_label:"Body (Markdown)",add_body_ph:`# My skill
|
|
776
776
|
|
|
@@ -784,8 +784,8 @@ Generate a token (classic or fine-grained) with the "repo" scope.
|
|
|
784
784
|
Copy the token — it starts with ghp_ or github_pat_.
|
|
785
785
|
Paste it in the field below.`}}},obsidian:{connected:{vault_path:"Vault",vault_name:"Name",note_count:"Notes"},fields:{vault_path:{label:"Vault path"},auto_mcp:{label:"Auto-register Obsidian MCP",hint:"Adds an 'obsidian' MCP server pointing at this vault, in this scope."},memory_sync:{label:"Sync APX memory",hint:"Enable mirroring APX memory into the vault, then use the button below."}},actions:{sync_memory:"Sync memory now",sync_memory_done:"Synced {count} file(s) · {changed} changed"}}}},w_={es:wD,en:SD};function CD(){try{const e=localStorage.getItem(On.language);if(e&&e in w_)return e}catch{}return"en"}let vp=CD();function nN(e){vp=e;try{localStorage.setItem(On.language,e)}catch{}}const sN=[{value:"es",label:"Español"},{value:"en",label:"English"}];function S_(){return vp}function ND(e){const t=w_[vp],a=e.split(".");let o=t;for(const l of a)if(o&&typeof o=="object"&&l in o)o=o[l];else return;return typeof o=="string"?o:void 0}function ED(e,t){return t?e.replace(/\{(\w+)\}/g,(a,o)=>o in t?String(t[o]):`{${o}}`):e}function RD(e){const t=ND(e);if(t!==void 0)return t;if(vp!=="es"){const a=w_.es,o=e.split(".");let l=a;for(const c of o)if(l&&typeof l=="object"&&c in l)l=l[c];else return;return typeof l=="string"?l:void 0}}function u(e,t){const a=RD(e);return a===void 0?e:ED(a,t)}function C_(e){const[t,a]=x.useState(!1);x.useEffect(()=>{try{a(localStorage.getItem(e)==="true")}catch{}},[e]);const o=x.useCallback(()=>a(l=>{const c=!l;try{localStorage.setItem(e,String(c))}catch{}return c}),[e]);return{collapsed:t,toggle:o}}function TD({collapsed:e,onToggle:t}){return n.jsx(qe,{content:u(e?"settings_ui.expand_menu":"settings_ui.collapse_menu"),side:"bottom",children:n.jsx("button",{type:"button",onClick:t,"aria-label":u(e?"settings_ui.expand_menu":"settings_ui.collapse_menu"),className:"flex size-7 shrink-0 items-center justify-center rounded-md text-muted-fg transition-colors hover:bg-accent hover:text-foreground",children:n.jsx(aS,{className:ge("size-4 transition-transform",e&&"rotate-180")})})})}function AD({sections:e,active:t,onChange:a,collapsed:o=!1}){return n.jsx("nav",{className:ge("hidden md:flex shrink-0 flex-col gap-1 py-3 transition-all",o?"w-12 items-center px-1":"w-44 px-2"),children:e.map((l,c)=>n.jsxs("div",{className:ge("w-full",c>0&&"mt-2"),children:[!o&&l.title&&n.jsx("p",{className:"mb-1 px-2 text-[9px] font-semibold uppercase tracking-wider text-muted-fg/70",children:l.title}),n.jsx("div",{className:"space-y-0.5",children:l.items.map(({key:d,label:f,icon:m,badge:g,mark:h})=>{const b=t===d,_=n.jsxs("button",{type:"button",onClick:()=>a(d),"data-testid":`tabnav-${d||"index"}`,className:ge("relative flex cursor-pointer items-center rounded-lg transition-colors",o?"size-9 justify-center":"w-full gap-2 px-2.5 py-1.5",b?"bg-accent text-accent-fg":"text-muted-fg hover:bg-accent/60 hover:text-foreground"),children:[n.jsx(m,{className:"size-4 shrink-0"}),o&&h&&n.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 flex items-center justify-center rounded-full bg-card",children:h}),!o&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"flex-1 truncate text-left text-xs",children:f}),h&&n.jsx("span",{className:"flex shrink-0 items-center",children:h}),g!==void 0&&n.jsx("span",{className:"rounded-full bg-muted px-1.5 text-[9px] text-muted-fg",children:g})]})]});return o?n.jsx(qe,{content:f,side:"right",children:_},d):n.jsx(x.Fragment,{children:_},d)})})]},c))})}var bk=Object.prototype.hasOwnProperty;function Ax(e,t){var a,o;if(e===t)return!0;if(e&&t&&(a=e.constructor)===t.constructor){if(a===Date)return e.getTime()===t.getTime();if(a===RegExp)return e.toString()===t.toString();if(a===Array){if((o=e.length)===t.length)for(;o--&&Ax(e[o],t[o]););return o===-1}if(!a||typeof e=="object"){o=0;for(a in e)if(bk.call(e,a)&&++o&&!bk.call(t,a)||!(a in t)||!Ax(e[a],t[a]))return!1;return Object.keys(t).length===o}}return e!==e&&t!==t}const aN=0,rN=1,oN=2,_k=3,lN=4,ha=new WeakMap,Wa=()=>{},Zt=Wa(),Mx=Object,it=e=>e===Zt,xa=e=>typeof e=="function",nr=(e,t)=>({...e,...t}),zx=e=>xa(e.then),dh={},Dd={},N_="undefined",ou=typeof window!=N_,Ox=typeof document!=N_,MD=ou&&"Deno"in window,zD=()=>ou&&typeof window.requestAnimationFrame!=N_,iN=(e,t)=>{const a=ha.get(e);return[()=>!it(t)&&e.get(t)||dh,o=>{if(!it(t)){const l=e.get(t);t in Dd||(Dd[t]=l),a[5](t,nr(l,o),l||dh)}},a[6],()=>!it(t)&&t in Dd?Dd[t]:!it(t)&&e.get(t)||dh]};let Dx=!0;const OD=()=>Dx,[Px,Lx]=ou&&window.addEventListener?[window.addEventListener.bind(window),window.removeEventListener.bind(window)]:[Wa,Wa],DD=()=>{const e=Ox&&document.visibilityState;return it(e)||e!=="hidden"},PD=e=>(Ox&&document.addEventListener("visibilitychange",e),Px("focus",e),()=>{Ox&&document.removeEventListener("visibilitychange",e),Lx("focus",e)}),LD=e=>{const t=()=>{Dx=!0,e()},a=()=>{Dx=!1};return Px("online",t),Px("offline",a),()=>{Lx("online",t),Lx("offline",a)}},ID={isOnline:OD,isVisible:DD},BD={initFocus:PD,initReconnect:LD},vk=!Kc.useId,To=!ou||MD,$D=e=>zD()?window.requestAnimationFrame(e):setTimeout(e,1),pc=To?x.useEffect:x.useLayoutEffect,fh=typeof navigator<"u"&&navigator.connection,yk=!To&&fh&&(["slow-2g","2g"].includes(fh.effectiveType)||fh.saveData),Pd=new WeakMap,UD=e=>Mx.prototype.toString.call(e),ph=(e,t)=>e===`[object ${t}]`;let qD=0;const Ix=e=>{const t=typeof e,a=UD(e),o=ph(a,"Date"),l=ph(a,"RegExp"),c=ph(a,"Object");let d,f;if(Mx(e)===e&&!o&&!l){if(d=Pd.get(e),d)return d;if(d=++qD+"~",Pd.set(e,d),Array.isArray(e)){for(d="@",f=0;f<e.length;f++)d+=Ix(e[f])+",";Pd.set(e,d)}if(c){d="#";const m=Mx.keys(e).sort();for(;!it(f=m.pop());)it(e[f])||(d+=f+":"+Ix(e[f])+",");Pd.set(e,d)}}else d=o?e.toJSON():t=="symbol"?e.toString():t=="string"?JSON.stringify(e):""+e;return d},E_=e=>{if(xa(e))try{e=e()}catch{e=""}const t=e;return e=typeof e=="string"?e:(Array.isArray(e)?e.length:e)?Ix(e):"",[e,t]};let HD=0;const kf=()=>++HD;async function cN(...e){const[t,a,o,l]=e,c=nr({populateCache:!0,throwOnError:!0},typeof l=="boolean"?{revalidate:l}:l||{});let d=c.populateCache;const f=c.rollbackOnError;let m=c.optimisticData;const g=_=>typeof f=="function"?f(_):f!==!1,h=c.throwOnError;if(xa(a)){const _=a,j=[],E=t.keys();for(const y of E)!/^\$(inf|sub)\$/.test(y)&&_(t.get(y)._k)&&j.push(y);return Promise.all(j.map(b))}return b(a);async function b(_){const[j]=E_(_);if(!j)return;const[E,y]=iN(t,j),[k,N,w,S]=ha.get(t),R=()=>{const q=k[j];return(xa(c.revalidate)?c.revalidate(E().data,_):c.revalidate!==!1)&&(delete w[j],delete S[j],q&&q[0])?q[0](oN).then(()=>E().data):E().data};if(e.length<3)return R();let A=o,T,z=!1;const M=kf();N[j]=[M,0];const L=!it(m),P=E(),B=P.data,D=P._c,$=it(D)?B:D;if(L&&(m=xa(m)?m($,B):m,y({data:m,_c:$})),xa(A))try{A=A($)}catch(q){T=q,z=!0}if(A&&zx(A))if(A=await A.catch(q=>{T=q,z=!0}),M!==N[j][0]){if(z)throw T;return A}else z&&L&&g(T)&&(d=!0,y({data:$,_c:Zt}));if(d&&!z)if(xa(d)){const q=d(A,$);y({data:q,error:Zt,_c:Zt})}else y({data:A,error:Zt,_c:Zt});if(N[j][1]=kf(),Promise.resolve(R()).then(()=>{y({_c:Zt})}),z){if(h)throw T;return}return A}}const jk=(e,t)=>{for(const a in e)e[a][0]&&e[a][0](t)},VD=(e,t)=>{if(!ha.has(e)){const o=nr(BD,t),l=Object.create(null),c=cN.bind(Zt,e);let d=Wa;const f=Object.create(null),m=(_,j)=>{const E=f[_]||[];return f[_]=E,E.push(j),()=>{const y=E.indexOf(j);y>=0&&(E[y]=E[E.length-1],E.pop())}},g=(_,j,E)=>{e.set(_,j);const y=f[_];if(y)for(const k of y)k(j,E)},h=_=>{const j=ha.get(e),[,E,y,k]=j,N=kf();j[8]++;for(const R in y)delete y[R];for(const R in k)delete k[R];for(const R in E)E[R]=[N,N];const w={};for(const R of[...e.keys()]){const A=e.get(R);e.delete(R);const T=f[R];if(T)for(const z of T)z(w,A)}const S=!_||_.revalidate!==!1;for(const R in l){const A=l[R];for(let T=0;T<A.length;T++)A[T](lN,{revalidate:S&&!T})}},b=()=>{if(!ha.has(e)&&(ha.set(e,[l,Object.create(null),Object.create(null),Object.create(null),c,g,m,h,0]),!To)){const _=o.initFocus(setTimeout.bind(Zt,jk.bind(Zt,l,aN))),j=o.initReconnect(setTimeout.bind(Zt,jk.bind(Zt,l,rN)));d=()=>{_&&_(),j&&j(),ha.delete(e)}}};return b(),[e,c,b,d,h]}const a=ha.get(e);return[e,a[4],Zt,Zt,a[7]]},FD=(e,t,a,o,l)=>{const c=a.errorRetryCount,d=l.retryCount,f=~~((Math.random()+.5)*(1<<(d<8?d:8)))*a.errorRetryInterval;!it(c)&&d>c||setTimeout(o,f,l)},GD=Ax,[uN,wf,,,YD]=VD(new Map),KD=nr({onLoadingSlow:Wa,onSuccess:Wa,onError:Wa,onErrorRetry:FD,onDiscarded:Wa,revalidateOnFocus:!0,revalidateOnReconnect:!0,revalidateIfStale:!0,shouldRetryOnError:!0,errorRetryInterval:yk?1e4:5e3,focusThrottleInterval:5*1e3,dedupingInterval:2*1e3,loadingTimeout:yk?5e3:3e3,compare:GD,isPaused:()=>!1,cache:uN,mutate:wf,unload:YD,fallback:{}},ID),XD=(e,t)=>{const a=nr(e,t);if(t){const{use:o,fallback:l,cacheData:c}=e,{use:d,fallback:f,cacheData:m}=t;o&&d&&(a.use=o.concat(d)),l&&f&&(a.fallback=nr(l,f)),c&&m&&(a.cacheData=nr(c,m))}return a},QD=x.createContext({}),WD="$inf$",dN=ou&&window.__SWR_DEVTOOLS_USE__,ZD=dN?window.__SWR_DEVTOOLS_USE__:[],JD=()=>{dN&&(window.__SWR_DEVTOOLS_REACT__=Kc)},eP=e=>xa(e[1])?[e[0],e[1],e[2]||{}]:[e[0],null,(e[1]===null?e[2]:e[1])||{}],fN=()=>{const e=x.useContext(QD);return x.useMemo(()=>nr(KD,e),[e])},tP=e=>(t,a,o)=>e(t,a&&((...c)=>{const[d]=E_(t),[,,,f]=ha.get(uN);if(d.startsWith(WD))return a(...c);const m=f[d];return it(m)?a(...c):(delete f[d],m)}),o),nP=ZD.concat(tP),sP=e=>function(...a){const o=fN(),[l,c,d]=eP(a),f=XD(o,d);let m=e;const{use:g}=f,h=(g||[]).concat(nP);for(let b=h.length;b--;)m=h[b](m);return m(l,c||f.fetcher||null,f)},aP=(e,t,a)=>{const o=t[e]||(t[e]=[]);return o.push(a),()=>{const l=o.indexOf(a);l>=0&&(o[l]=o[o.length-1],o.pop())}};JD();const Ld=Kc.use||(e=>{switch(e.status){case"pending":throw e;case"fulfilled":return e.value;case"rejected":throw e.reason;default:throw e.status="pending",e.then(t=>{e.status="fulfilled",e.value=t},t=>{e.status="rejected",e.reason=t}),e}}),mh={dedupe:!0},kk=(e,t,a)=>{var o;return t?((o=e.get(t))==null?void 0:o.has(a))===!0:!1},gh=(e,t,a)=>{if(!t)return;let o=e.get(t);o||(o=new Set,e.set(t,o)),o.add(a)},rP=({value:e,getCacheData:t,canCommit:a,setCache:o})=>{const l=c=>{a()&&it(t())&&o(c)};Promise.resolve(e).then(c=>{l({data:c,error:Zt})},c=>{l({error:c})})},Sf=Promise.resolve(Zt);Sf.status="fulfilled";Sf.value=Zt;const oP=()=>Wa,lP=(e,t,a)=>{const{cache:o,compare:l,suspense:c,fallbackData:d,revalidateOnMount:f,revalidateIfStale:m,refreshInterval:g,refreshWhenHidden:h,refreshWhenOffline:b,keepPreviousData:_,strictServerPrefetchWarning:j}=a,[E,y,k,N]=ha.get(o),[w,S]=E_(e),R=x.useRef(!1),A=x.useRef(!1),T=x.useRef(w),z=x.useRef(t),M=x.useRef(a),L=()=>M.current,P=()=>L().isVisible()&&L().isOnline(),[B,D,$,q]=iN(o,w),G=x.useRef({}).current,U=it(d)?it(a.fallback)?Zt:a.fallback[w]:d,V=a.cacheData,X=w?V?.[w]:Zt,Q=w?N[w]:Zt,W=it(Q)&&!it(X),I=W?X:Q,K=(de,Le)=>{for(const ye in G){const Ce=ye;if(Ce==="data"){if(!l(de[Ce],Le[Ce])&&(!it(de[Ce])||!l(Re,Le[Ce])))return!1}else if(Le[Ce]!==de[Ce])return!1}return!0},ee=!R.current,F=x.useMemo(()=>{const de=B(),Le=q(),ye=lt=>{const Tt=nr(lt);return delete Tt._k,(()=>{if(!w||!t||L().isPaused())return!1;if(ee&&!it(f))return f;const Ct=it(U)?Tt.data:U;return c&&W&&it(Ct)?!1:it(Ct)||m})()?{isValidating:!0,isLoading:!0,...Tt}:Tt},Ce=ye(de),Qe=de===Le?Ce:ye(Le);let Ge=Ce;return[()=>{const lt=ye(B());return K(lt,Ge)?(Ge.data=lt.data,Ge.isLoading=lt.isLoading,Ge.isValidating=lt.isValidating,Ge.error=lt.error,Ge):(Ge=lt,lt)},()=>Qe]},[o,w]),ne=Uc.useSyncExternalStore(x.useCallback(de=>$(w,(Le,ye)=>{K(ye,Le)||de()}),[o,w]),F[0],F[1]),Z=E[w]&&E[w].length>0,fe=ne.data;let Y=it(fe)?U&&zx(U)?Ld(U):U:fe;const oe=ne.error,ve=x.useRef(Y),le=x.useRef(Zt);let xe=le.current;xe||(xe=new WeakMap,le.current=xe);const ke=x.useRef(null);let Re=_?it(fe)?it(ve.current)?Y:ve.current:fe:Y;const Ae=w&&it(Y),Ie=x.useRef(null);!To&&Uc.useSyncExternalStore(oP,()=>(Ie.current=!1,Ie),()=>(Ie.current=!0,Ie));const Oe=Ie.current;j&&Oe&&!c&&Ae&&console.warn(`Missing pre-initiated data for serialized key "${w}" during server-side rendering. Data fetching should be initiated on the server and provided to SWR via fallback data. You can set "strictServerPrefetchWarning: false" to disable this warning.`);const Te=!w||!t||L().isPaused()||Z&&!it(oe)?!1:ee&&!it(f)?f:c&&W&&Ae?!1:c?it(Y)?!1:m:it(Y)||m,Ne=ee&&Te,Me=it(ne.isValidating)?Ne:ne.isValidating,De=it(ne.isLoading)?Ne:ne.isLoading,Ue=x.useCallback(async de=>{const Le=z.current;if(!w||!Le||A.current||L().isPaused())return!1;let ye,Ce,Qe=!0;const Ge=de||{},lt=!k[w]||!Ge.dedupe,Tt=W&&!kk(xe,V,w)&&!it(I)&&it(B().data),_t=()=>vk?!A.current&&w===T.current&&R.current:w===T.current,Ct={isValidating:!1,isLoading:!1},je=()=>{D(Ct)},ze=()=>{const We=k[w];We&&We[1]===Ce&&delete k[w]},Ye={isValidating:!0};it(B().data)&&(Ye.isLoading=!0);try{if(lt&&(D(Ye),a.loadingTimeout&&it(B().data)&&setTimeout(()=>{Qe&&_t()&&L().onLoadingSlow(w,a)},a.loadingTimeout),Tt&&gh(xe,V,w),k[w]=[Tt?I:Le(S),kf()],Tt&&N[w]&&delete N[w]),[ye,Ce]=k[w],ye=await ye,lt&&setTimeout(ze,a.dedupingInterval),!k[w]||k[w][1]!==Ce)return lt&&_t()&&L().onDiscarded(w),!1;Ct.error=Zt;const We=y[w];if(!it(We)&&(Ce<=We[0]||Ce<=We[1]||We[1]===0))return je(),lt&&_t()&&L().onDiscarded(w),!1;const dt=B().data;Ct.data=l(dt,ye)?dt:ye,lt&&_t()&&L().onSuccess(ye,w,a)}catch(We){ze();const dt=L(),{shouldRetryOnError:Rt}=dt;dt.isPaused()||(Ct.error=We,lt&&_t()&&(dt.onError(We,w,dt),(Rt===!0||xa(Rt)&&Rt(We))&&(!L().revalidateOnFocus||!L().revalidateOnReconnect||P())&&dt.onErrorRetry(We,w,dt,Qt=>{const ot=E[w];ot&&ot[0]&&ot[0](_k,Qt)},{retryCount:(Ge.retryCount||0)+1,dedupe:!0})))}return Qe=!1,je(),!0},[w,o]),Xe=x.useCallback((...de)=>cN(o,T.current,...de),[]);if(pc(()=>{const de=ke.current;de&&(ke.current=null,gh(xe,de.cacheData,de.key),it(B().data)&&D({data:de.data,error:Zt,_k:de._k}),N[de.key]&&delete N[de.key])}),pc(()=>{z.current=t,M.current=a,it(fe)||(ve.current=fe)}),pc(()=>{if(t||!W||it(I)||kk(xe,V,w)||!it(B().data))return;gh(xe,V,w);const de=y[w];rP({value:I,getCacheData:()=>B().data,canCommit:()=>!A.current&&w===T.current&&y[w]===de,setCache:Le=>D({...Le,_k:S})})}),pc(()=>{if(!w)return;const de=Ue.bind(Zt,mh);let Le=0;L().revalidateOnFocus&&(Le=Date.now()+L().focusThrottleInterval);const Ce=aP(w,E,(Qe,Ge={})=>{if(Qe==aN){const lt=Date.now();L().revalidateOnFocus&<>Le&&P()&&(Le=lt+L().focusThrottleInterval,de())}else if(Qe==rN)L().revalidateOnReconnect&&P()&&de();else{if(Qe==oN)return Ue();if(Qe==_k)return Ue(Ge);if(Qe==lN&&(ve.current=Zt,Ge.revalidate))return Ue()}});return A.current=!1,T.current=w,R.current=!0,D({_k:S}),Te&&(k[w]||(it(Y)||To?de():$D(de))),()=>{A.current=!0,Ce()}},[w]),pc(()=>{let de;function Le(){const Ce=xa(g)?g(B().data):g;Ce&&de!==-1&&(de=setTimeout(ye,Ce))}function ye(){!B().error&&(h||L().isVisible())&&(b||L().isOnline())?Ue(mh).then(Le):Le()}return Le(),()=>{de&&(clearTimeout(de),de=-1)}},[g,h,b,w]),x.useDebugValue(Re),c){if(!vk&&To&&Ae&&it(I))throw new Error("Fallback data is required when using Suspense in SSR.");Ae&&(z.current=t,M.current=a,A.current=!1);const de=!it(I)&&Ae;let Le=Zt;if(de&&W)Le=I&&zx(I)?Ld(I):I,Y=Le,Re=Le,To||(ke.current={data:Le,_k:S,key:w,cacheData:V});else{const Ce=de?Xe(I):Sf;Ld(Ce)}if(!it(oe)&&Ae)throw oe;const ye=Ae&&it(Le)?Ue(mh):Sf;!it(Re)&&Ae&&(ye.status="fulfilled",ye.value=!0),Ld(ye)}return{mutate:Xe,get data(){return G.data=!0,Re},get error(){return G.error=!0,oe},get isValidating(){return G.isValidating=!0,Me},get isLoading(){return G.isLoading=!0,De}}},Be=sP(lP);let si=null;function Ro(e){si=e}function R_(){return si}class lu extends Error{status;body;constructor(t,a,o){super(a),this.status=t,this.body=o}}async function mc(e,t,a,o={}){const l={"content-type":"application/json",...si?{authorization:`Bearer ${si}`}:{},...o.headers||{}},c=await fetch(t,{...o,method:e,headers:l,body:a!==void 0?JSON.stringify(a):void 0});if(!c.ok){let d="",f=null;try{f=await c.json(),d=f?.error||JSON.stringify(f)}catch{d=await c.text()}throw new lu(c.status,`${e} ${t} → ${c.status}: ${d}`,f)}if(c.status!==204)return await c.json()}function Bl(e){const t=e;if(Array.isArray(e))return{items:e,total:e.length};if(t&&Array.isArray(t.data)){const a=t.data;return{items:a,total:typeof t.meta?.total=="number"?t.meta.total:a.length}}if(t&&Array.isArray(t.sessions)){const a=t.sessions;return{items:a,total:a.length}}return{items:[],total:0}}const se={get:e=>mc("GET",e),post:(e,t)=>mc("POST",e,t),put:(e,t)=>mc("PUT",e,t),patch:(e,t)=>mc("PATCH",e,t),del:e=>mc("DELETE",e)};async function pN(e,t,a,o){const l=await fetch(e,{method:"POST",signal:o,headers:{"content-type":"application/json",...si?{authorization:`Bearer ${si}`}:{}},body:JSON.stringify(t)});if(!l.ok||!l.body){const m=await l.text().catch(()=>"");throw new lu(l.status,`POST ${e} → ${l.status}: ${m||"stream failed"}`)}const c=l.body.getReader(),d=new TextDecoder("utf-8");let f="";for(;;){const{value:m,done:g}=await c.read();if(g)break;f+=d.decode(m,{stream:!0});let h=f.indexOf(`
|
|
786
786
|
`);for(;h>=0;){const b=f.slice(0,h).trim();if(f=f.slice(h+1),b)try{a(JSON.parse(b))}catch{}h=f.indexOf(`
|
|
787
|
-
`)}}if(f.trim())try{a(JSON.parse(f.trim()))}catch{}}const iP={get:()=>se.get("/health")},Zn={list:()=>se.get("/projects"),register:e=>se.post("/projects",{path:e}),remove:e=>se.del(`/projects/${encodeURIComponent(e)}`),rebuild:e=>se.post(`/projects/${encodeURIComponent(e)}/rebuild`),config:{show:e=>se.get(`/projects/${e}/config`),set:(e,t)=>se.patch(`/projects/${e}/config`,{set:t}),unset:(e,t)=>se.patch(`/projects/${e}/config`,{unset:t}),put:(e,t)=>se.put(`/projects/${e}/config`,t)},apcProject:{set:(e,t,a)=>se.patch(`/projects/${e}/apc-project`,{set:t,unset:a}),put:(e,t)=>se.put(`/projects/${e}/apc-project`,t)},memory:{get:e=>se.get(`/projects/${e}/memory`),put:(e,t)=>se.put(`/projects/${e}/memory`,{body:t})}},an={list:(e,t)=>se.get(`/projects/${e}/agents${t?.stats?"?stats=1":""}`),get:(e,t)=>se.get(`/projects/${e}/agents/${t}`),create:(e,t)=>se.post(`/projects/${e}/agents`,t),update:(e,t,a)=>se.patch(`/projects/${e}/agents/${encodeURIComponent(t)}`,a),remove:(e,t)=>se.del(`/projects/${e}/agents/${encodeURIComponent(t)}`),chat:(e,t,a)=>se.post(`/projects/${e}/agents/${encodeURIComponent(t)}/chat`,a),memory:{get:(e,t)=>se.get(`/projects/${e}/agents/${t}/memory`),put:(e,t,a)=>se.put(`/projects/${e}/agents/${t}/memory`,{body:a})},vault:e=>se.get(e?.includeRemoved?"/agents/vault?include_removed=1":"/agents/vault"),vaultCreate:(e,t={},a="")=>se.post("/agents/vault",{slug:e,fields:t,body:a}),vaultPatch:(e,t)=>se.patch(`/agents/vault/${encodeURIComponent(e)}`,t),vaultRemove:e=>se.del(`/agents/vault/${encodeURIComponent(e)}`),vaultRestore:e=>se.post(`/agents/vault/${encodeURIComponent(e)}/restore`),import:(e,t)=>se.post(`/projects/${e}/agents/import`,{slug:t})},Wr={list:(e,t)=>se.get(`/projects/${e}/agents/${t}/conversations`),get:(e,t,a)=>se.get(`/projects/${e}/agents/${t}/conversations/${a}`),threads:e=>se.get(`/projects/${e}/super-agent/threads`),thread:(e,t,a)=>se.get(`/projects/${e}/super-agent/threads/${t}/${a}`),remove:(e,t,a)=>se.del(`/projects/${e}/agents/${t}/conversations/${a}`),removeThread:(e,t,a)=>se.del(`/projects/${e}/super-agent/threads/${t}/${a}`),compact:(e,t,a)=>se.post(a?`/projects/${e}/agents/${t}/conversations/${a}/compact`:`/projects/${e}/agents/${t}/compact`,{})},Br={list:e=>se.get(`/projects/${e}/routines`),get:(e,t)=>se.get(`/projects/${e}/routines/${t}`),run:(e,t)=>se.post(`/projects/${e}/routines/${t}/run`),enable:(e,t)=>se.post(`/projects/${e}/routines/${t}/enable`),disable:(e,t)=>se.post(`/projects/${e}/routines/${t}/disable`),upsert:(e,t)=>se.post(`/projects/${e}/routines`,t),remove:(e,t)=>se.del(`/projects/${e}/routines/${encodeURIComponent(t)}`)},Qn={list:(e,t="open")=>se.get(`/projects/${e}/tasks?state=${t}`).then(a=>Bl(a).items),global:(e="open")=>se.get(`/tasks?state=${e}`).then(t=>Bl(t).items),listPage:(e,{state:t,limit:a,offset:o})=>se.get(`/projects/${e}/tasks?state=${t}&limit=${a}&offset=${o}`).then(l=>Bl(l)),globalPage:({state:e,limit:t,offset:a})=>se.get(`/tasks?state=${e}&limit=${t}&offset=${a}`).then(o=>Bl(o)),get:(e,t)=>se.get(`/projects/${e}/tasks/${t}`),add:(e,t)=>se.post(`/projects/${e}/tasks`,t),patch:(e,t,a)=>se.patch(`/projects/${e}/tasks/${t}`,{patch:a}),status:(e,t,a)=>se.post(`/projects/${e}/tasks/${t}/status`,{status:a}),done:(e,t)=>se.post(`/projects/${e}/tasks/${t}/done`),drop:(e,t)=>se.post(`/projects/${e}/tasks/${t}/drop`),reopen:(e,t)=>se.post(`/projects/${e}/tasks/${t}/reopen`),summary:e=>se.get(`/projects/${e}/tasks-summary`)},$r={list:e=>se.get(`/projects/${e}/mcps`),check:e=>se.get(`/projects/${e}/mcps/check`),add:(e,t,a)=>se.post(`/projects/${e}/mcps?scope=${t}`,a),remove:(e,t,a="shared")=>se.del(`/projects/${e}/mcps/${encodeURIComponent(t)}?scope=${a}`),test:(e,t)=>se.post(`/projects/${e}/mcps/${encodeURIComponent(t)}/test`,{}),logs:(e,t)=>se.get(`/projects/${e}/mcps/${encodeURIComponent(t)}/logs`)},ko=e=>`?scope=${e}`,Yn={catalog:e=>se.get(`/projects/${e}/integrations/catalog`),list:(e,t="project")=>se.get(`/projects/${e}/integrations${ko(t)}`),status:(e,t,a="project")=>se.get(`/projects/${e}/integrations/${t}${ko(a)}`),configure:(e,t,a,o)=>se.post(`/projects/${e}/integrations/${t}/configure${ko(a)}`,o),validate:(e,t,a="project")=>se.post(`/projects/${e}/integrations/${t}/validate${ko(a)}`,{}),deactivate:(e,t,a="project")=>se.post(`/projects/${e}/integrations/${t}/deactivate${ko(a)}`,{}),action:(e,t,a,o="project")=>se.post(`/projects/${e}/integrations/${t}/action/${a}${ko(o)}`,{}),remove:(e,t,a="project")=>se.del(`/projects/${e}/integrations/${t}${ko(a)}`),asanaConfigure:(e,t,a)=>Yn.configure(e,"asana",t,{personal_access_token:a.personalAccessToken,workspace_gid:a.workspaceGid}),asanaValidate:(e,t)=>Yn.validate(e,"asana",t),asanaWorkspaces:(e,t)=>Yn.action(e,"asana","workspaces",t)},qc={list:(e,t={})=>se.get(`/projects/${e}/vars${t.reveal?"?reveal=1":""}`),get:(e,t,a={})=>se.get(`/projects/${e}/vars/${encodeURIComponent(t)}${a.reveal?"?reveal=1":""}`),upsert:(e,t)=>se.post(`/projects/${e}/vars`,t),remove:(e,t,a="project")=>se.del(`/projects/${e}/vars/${encodeURIComponent(t)}?scope=${a}`)},hh=e=>{const t=new URLSearchParams;for(const[o,l]of Object.entries(e))l!==void 0&&l!==""&&t.set(o,String(l));const a=t.toString();return a?`?${a}`:""},Cf={global:(e={})=>se.get(`/messages/global${hh(e)}`),project:(e,t={})=>se.get(`/projects/${e}/messages${hh(t)}`),search:(e,t,a=50)=>se.get(`/projects/${e}/messages/search${hh({q:t,limit:a})}`)},cP={global:e=>se.get(`/sessions${e?`?engine=${encodeURIComponent(e)}`:""}`).then(t=>({sessions:Bl(t).items})),page:({engine:e,q:t,deep:a,cwd:o,limit:l,offset:c})=>{const d=new URLSearchParams({limit:String(l),offset:String(c)});return e&&d.set("engine",e),t?.trim()&&d.set("q",t.trim()),a&&d.set("deep","1"),o?.trim()&&d.set("cwd",o.trim()),se.get(`/sessions?${d.toString()}`).then(f=>Bl(f))}},uP={list:()=>se.get("/tools")},Dn={channels:{list:()=>se.get("/telegram/channels"),upsert:e=>se.post("/telegram/channels",e),patch:(e,t)=>se.patch(`/telegram/channels/${e}`,t),remove:e=>se.del(`/telegram/channels/${encodeURIComponent(e)}`)},contacts:{list:()=>se.get("/telegram/contacts"),patch:(e,t)=>se.patch(`/telegram/contacts/${encodeURIComponent(String(e))}`,t),remove:e=>se.del(`/telegram/contacts/${encodeURIComponent(String(e))}`)},roles:{list:()=>se.get("/telegram/roles"),set:(e,t)=>se.put(`/telegram/roles/${encodeURIComponent(e)}`,{tools:t}),remove:e=>se.del(`/telegram/roles/${encodeURIComponent(e)}`)},status:()=>se.get("/telegram/status"),start:()=>se.post("/telegram/start"),stop:()=>se.post("/telegram/stop"),send:e=>se.post("/telegram/send",e)},Hc={list:()=>se.get("/engines"),presets:()=>se.get("/engines/presets"),models:e=>se.post("/engines/models",e)},dP=Object.freeze(Object.defineProperty({__proto__:null,Engines:Hc},Symbol.toStringTag,{value:"Module"})),ai={reload:()=>se.post("/admin/reload"),shutdown:()=>se.post("/admin/shutdown"),config:{get:()=>se.get("/admin/config"),patch:e=>se.patch("/admin/config",e)},superAgent:()=>se.get("/admin/super-agent"),logs:(e="errors",t=200)=>se.get(`/admin/logs?file=${e}&limit=${t}`)},ri={list:()=>se.get("/pair/list"),revoke:e=>se.del(`/pair/revoke/${encodeURIComponent(e)}`),init:()=>se.post("/pair/init",{}),status:e=>se.get(`/pair/status/${encodeURIComponent(e)}`),confirm:e=>se.post("/pair/confirm",e)},wk={get:()=>se.get("/identity"),patch:e=>se.patch("/identity",e)},mN={send:(e,t)=>se.post(`/projects/${e}/super-agent/chat`,t),stream:(e,t,a,o)=>pN(`/projects/${e}/super-agent/chat/stream`,t,a,o),summarize:e=>se.post("/super-agent/summarize",e)},Nf={dirs:e=>se.get(`/admin/fs/dirs?path=${encodeURIComponent(e)}`),pickDir:e=>se.get(`/admin/fs/pick-dir${e?`?prompt=${encodeURIComponent(e)}`:""}`)},fP=["alloy","echo","fable","onyx","nova","shimmer"],pP=["Kore","Puck","Charon","Fenrir","Aoede"],mP=["eleven_multilingual_v2","eleven_turbo_v2_5","eleven_flash_v2_5"],gP=["tts-1","tts-1-hd"],hP=["happy","sad","excited","angry","calm","whisper","shout","laugh","cry","narrator","neutral"],xP=["tiny","base","small","medium","large-v2","large-v3","large-v3-turbo"],Ef={piper:{name:"Piper",note:"Local, offline (CLI + .onnx model). No API key.",local:!0},elevenlabs:{name:"ElevenLabs",note:"Cloud, multilingual. Requires an API key."},openai:{name:"OpenAI",note:"Cloud (tts-1 / tts-1-hd) or any OpenAI-compatible endpoint (set a base URL for a local server, e.g. QVox)."},gemini:{name:"Gemini",note:"Cloud (preview). Uses your Gemini key."},mock:{name:"Mock",note:"Silent test engine. Always available as a fallback.",local:!0}};async function bP(e){const t=R_(),a=await fetch(`/voice/tts?path=${encodeURIComponent(e)}`,{headers:t?{authorization:`Bearer ${t}`}:{}});if(!a.ok){const l=await a.text().catch(()=>"");throw new Error(`No se pudo leer el audio (${a.status}): ${l.slice(0,160)}`)}const o=await a.blob();return URL.createObjectURL(o)}const Rf={providers:()=>se.get("/tts/providers"),sttHardware:()=>se.get("/transcribe/hardware"),sttModels:e=>se.get(`/transcribe/models?backend=${e}`),say:e=>se.post("/tts/say",e),turn:e=>se.post("/voice/turn",e)},gN={manifest:()=>se.get("/deck/manifest"),setWidget:(e,t)=>se.patch(`/deck/widgets/${encodeURIComponent(e)}`,t),exec:e=>se.post("/deck/exec",e)},wo=e=>`/projects/${e}/code/sessions`,Ya={sessions:{list:e=>se.get(wo(e)).then(t=>t.sessions),get:(e,t)=>se.get(`${wo(e)}/${t}`),create:(e,t={})=>se.post(wo(e),t),update:(e,t,a)=>se.patch(`${wo(e)}/${t}`,a),remove:(e,t)=>se.del(`${wo(e)}/${t}`)},changes:(e,t)=>se.get(`${wo(e)}/${t}/changes`),stream:(e,t,a,o,l)=>pN(`${wo(e)}/${t}/chat/stream`,a,o,l)},Ws={list:e=>se.get(`/projects/${encodeURIComponent(e)}/artifacts`),read:(e,t)=>se.get(`/projects/${encodeURIComponent(e)}/artifacts/${encodeURIComponent(t)}`),run:(e,t,a=[])=>se.post(`/projects/${encodeURIComponent(e)}/artifacts/${encodeURIComponent(t)}/run`,{args:a}),remove:(e,t)=>se.del(`/projects/${encodeURIComponent(e)}/artifacts/${encodeURIComponent(t)}`),write:(e,t,a)=>se.patch(`/projects/${encodeURIComponent(e)}/artifacts/${encodeURIComponent(t)}`,{content:a}),rename:(e,t,a)=>se.patch(`/projects/${encodeURIComponent(e)}/artifacts/${encodeURIComponent(t)}`,{newName:a}),preview:(e,t,a=!0)=>se.post(`/projects/${encodeURIComponent(e)}/artifacts/${encodeURIComponent(t)}/preview`,{watch:a}),previews:e=>se.get(`/projects/${encodeURIComponent(e)}/previews`),stopPreview:e=>se.del(`/previews/${encodeURIComponent(e)}`),openTunnel:(e,t)=>se.post(`/previews/${encodeURIComponent(e)}/tunnel`,{provider:t}),closeTunnel:e=>se.del(`/previews/${encodeURIComponent(e)}/tunnel`)},Us={list:e=>{const t=new URLSearchParams;e&&(t.set("project_path",e),t.set("scope",e));const a=t.toString();return se.get(a?`/skills?${a}`:"/skills")},detail:(e,t)=>{const a=t?`?project_path=${encodeURIComponent(t)}`:"";return se.get(`/skills/${encodeURIComponent(e)}/detail${a}`)},setEnabled:e=>se.put("/skills/enabled",e),create:e=>se.post("/skills",e),importZip:e=>se.post("/skills/import/zip",e),importRepo:e=>se.post("/skills/import/repo",e),remove:(e,t)=>{const a=t?`?project_path=${encodeURIComponent(t)}`:"";return se.del(`/skills/${encodeURIComponent(e)}${a}`)},inspector:()=>se.get("/skills/inspector"),updateInspector:e=>se.put("/skills/inspector",e),index:(e={})=>se.post("/skills/index",e),inspect:(e,t)=>se.post("/skills/inspect",{prompt:e,project_path:t})},Vr={get:e=>se.get(`/projects/${e}/organization`),createArea:(e,t)=>se.post(`/projects/${e}/organization/areas`,t),updateArea:(e,t,a)=>se.patch(`/projects/${e}/organization/areas/${encodeURIComponent(t)}`,a),removeArea:(e,t)=>se.del(`/projects/${e}/organization/areas/${encodeURIComponent(t)}`),createRole:(e,t)=>se.post(`/projects/${e}/organization/roles`,t),updateRole:(e,t,a)=>se.patch(`/projects/${e}/organization/roles/${encodeURIComponent(t)}`,a),removeRole:(e,t)=>se.del(`/projects/${e}/organization/roles/${encodeURIComponent(t)}`)},kc={tree:(e,t="project")=>se.get(`/projects/${e}/fs/tree?scope=${t}`),read:(e,t,a="project")=>se.get(`/projects/${e}/fs/file?scope=${a}&path=${encodeURIComponent(t)}`),write:(e,t,a,o="project")=>se.put(`/projects/${e}/fs/file`,{scope:o,path:t,content:a}),mkdir:(e,t,a="project")=>se.post(`/projects/${e}/fs/dir`,{scope:a,path:t}),remove:(e,t,a="project")=>se.del(`/projects/${e}/fs/entry?scope=${a}&path=${encodeURIComponent(t)}`)};function iu(){const{data:e,error:t,isLoading:a,mutate:o}=Be("/projects",()=>Zn.list(),{refreshInterval:Qf.projects});return{projects:(e||[]).slice().sort((c,d)=>{const f=Number(c.id),m=Number(d.id);return f===0&&m!==0?-1:m===0&&f!==0?1:f-m}),error:t,isLoading:a,mutate:o}}function cu(e){const{projects:t,isLoading:a,mutate:o}=iu();return{project:t.find(c=>String(c.id)===e)??null,isLoading:a,mutate:o}}function T_(){const{data:e,error:t,isLoading:a,mutate:o}=Be("/identity",()=>wk.get());return{identity:e||{},error:t,isLoading:a,mutate:o,save:async c=>{const d=await wk.patch(c);return await o(d,{revalidate:!1}),d}}}function yp(){const{identity:e}=T_();return e?.agent_name?.trim()||"APX"}function _P(){return[{id:"desktop",label:u("nav.modules.desktop"),href:"/m/desktop",icon:vb},{id:"code",label:u("nav.modules.code"),href:"/m/code",icon:ya}]}function vP(e,t,a){const[o,l]=x.useState(t);return x.useLayoutEffect(()=>{const c=e.current;if(!c||!a)return;const d=()=>{const m=getComputedStyle(c),g=(parseFloat(m.paddingTop)||0)+(parseFloat(m.paddingBottom)||0),h=c.clientHeight-g;if(h<=0)return;const b=parseFloat(m.rowGap)||12,j=(c.querySelector("[data-rail-probe]")?.offsetHeight??56)+b,y=Math.max(0,Math.floor((h+b)/j))-1;l(y>=t?t:Math.max(0,y-1))};d();const f=new ResizeObserver(d);return f.observe(c),()=>f.disconnect()},[e,t,a]),a?Math.min(o,t):t}function Sk({projects:e,label:t,sublabel:a,icon:o,tooltip:l,header:c,active:d,testId:f,onSelect:m,isActive:g}){return n.jsxs(y_,{children:[n.jsxs(j_,{"data-testid":f,title:l,"aria-label":l,className:"group flex w-full cursor-pointer flex-col items-center gap-1",children:[n.jsx("span",{className:ge("flex size-10 items-center justify-center rounded-xl text-xs font-bold transition-all","bg-muted/40 text-muted-fg hover:bg-accent hover:text-foreground",d&&"ring-2 ring-foreground ring-offset-2 ring-offset-card"),children:o??t}),a&&n.jsx("span",{className:"block max-w-[3.6rem] truncate text-[9px] leading-tight text-muted-fg group-hover:text-foreground",children:a})]}),n.jsxs(k_,{side:"right",align:"start",sideOffset:8,className:"max-h-[70vh] w-64",children:[n.jsx("div",{className:"px-1.5 py-1 text-xs font-medium text-muted-foreground",children:c}),e.map(h=>{const b=h.name||h.path.split("/").pop()||String(h.id),_=`/p/${h.id}`,{initials:j,idleClass:E}=S6(b);return n.jsxs(sf,{"data-testid":`project-menu-item-${h.id}`,onClick:()=>m(_),className:ge(g(_)&&"bg-accent/60 text-foreground"),children:[n.jsx("span",{className:ge("flex size-6 shrink-0 items-center justify-center rounded-md text-[10px] font-bold",E),children:j}),n.jsx("span",{className:"truncate",children:b})]},h.id)})]})]})}function yP({onSelect:e,onOpenRoby:t,onOpenAddProject:a}){const{projects:o,isLoading:l}=iu(),c=ns(),d=_P(),f=yp(),m=x.useRef(null),{collapsed:g,toggle:h}=C_(On.sidebarCollapsed+".projects"),b=w=>c.pathname===w||c.pathname.startsWith(`${w}/`),_=o.find(w=>String(w.id)==="0"),j=o.filter(w=>String(w.id)!=="0").sort((w,S)=>Number(S.id)-Number(w.id)),E=vP(m,j.length,!g&&j.length>0),y=j.slice(0,E),k=j.slice(E),N=k.some(w=>b(`/p/${w.id}`));return n.jsxs("aside",{className:"flex h-full w-20 flex-col items-center gap-3 overflow-hidden bg-transparent py-3",children:[n.jsx(qe,{content:u("nav.apx_admin"),side:"right",children:n.jsx("button",{type:"button",onClick:()=>e("/"),"data-testid":"nav-home",className:"mb-2 cursor-pointer",children:n.jsx(EM,{size:36})})}),l&&n.jsx("div",{className:"size-10 animate-pulse rounded-xl bg-muted"}),_&&n.jsx(Ml,{label:u("base.title"),testId:"project-avatar-0",title:u("base.subtitle"),active:b("/p/0"),isDefault:!0,icon:n.jsx("img",{src:"/modules/superagent.png",alt:u("base.title"),className:"size-7 object-contain",draggable:!1}),onClick:()=>e("/p/0")}),d.map(w=>n.jsx(Ml,{label:w.label,testId:`module-avatar-${w.id}`,title:w.label,active:b(w.href),icon:n.jsx(w.icon,{size:18}),onClick:()=>e(w.href)},w.id)),n.jsxs("div",{className:"flex min-h-0 w-full flex-1 flex-col items-center gap-3",children:[j.length>0&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"my-0.5 h-px w-8 rounded-full bg-border"}),n.jsx(qe,{content:u(g?"nav.expand_projects":"nav.collapse_projects"),side:"right",children:n.jsx("button",{type:"button",onClick:h,"data-testid":"nav-toggle-projects","aria-label":u(g?"nav.expand_projects":"nav.collapse_projects"),"aria-expanded":!g,className:"flex h-5 w-8 cursor-pointer items-center justify-center rounded-md text-muted-fg transition-colors hover:bg-accent hover:text-foreground",children:n.jsx(ms,{className:ge("size-3.5 transition-transform",g&&"-rotate-90")})})})]}),n.jsxs("div",{ref:m,className:"flex min-h-0 w-full flex-1 flex-col items-center gap-3 overflow-hidden py-1.5",children:[j.length>0&&g&&n.jsx(Sk,{projects:j,icon:n.jsx(HA,{size:18}),sublabel:String(j.length),tooltip:u("nav.all_projects"),header:u("nav.all_projects"),active:j.some(w=>b(`/p/${w.id}`)),testId:"nav-projects-folder",onSelect:e,isActive:b}),j.length>0&&!g&&n.jsxs(n.Fragment,{children:[n.jsx("div",{"data-rail-probe":!0,"aria-hidden":!0,className:"invisible absolute w-full",children:n.jsx(Ml,{label:"Ag",active:!1,onClick:()=>{}})}),y.map(w=>{const S=w.name||w.path.split("/").pop()||String(w.id),R=`/p/${w.id}`;return n.jsx("div",{"data-rail-item":!0,className:"w-full",children:n.jsx(Ml,{label:S,testId:`project-avatar-${w.id}`,title:`${S} — ${w.path}`,active:b(R),onClick:()=>e(R)})},w.id)}),k.length>0&&n.jsx(Sk,{projects:k,label:`+${k.length}`,tooltip:u("nav.more_projects",{count:k.length}),header:u("nav.more_projects",{count:k.length}),active:N,testId:"nav-projects-overflow",onSelect:e,isActive:b})]}),n.jsx(Ml,{label:u("nav.add_project"),isAdd:!0,testId:"nav-add-project",icon:n.jsx(Dt,{size:18}),active:!1,onClick:()=>a?a():e("/?action=add-project"),title:u("nav.add_project")})]})]}),n.jsx(Ml,{label:u("nav.settings"),isSettings:!0,testId:"nav-settings",icon:n.jsx(Xf,{size:16}),active:c.pathname==="/settings"||c.pathname.startsWith("/settings/"),onClick:()=>e("/settings"),title:u("nav.settings")}),n.jsx(qe,{content:u("settings_ui.documentation"),side:"right",children:n.jsx("a",{href:"https://agentprojectcontext.github.io/apx/docs/",target:"_blank",rel:"noopener noreferrer","data-testid":"nav-docs","aria-label":u("settings_ui.documentation"),className:"flex size-10 items-center justify-center rounded-xl border border-border/60 bg-muted/30 text-muted-fg transition-colors hover:bg-accent hover:text-foreground",children:n.jsx(_A,{size:18})})}),n.jsx(qe,{content:u("superagent.talk",{persona:f}),side:"right",children:n.jsx("button",{type:"button",onClick:t,"data-testid":"nav-roby","aria-label":u("superagent.talk",{persona:f}),className:"flex size-10 items-center justify-center rounded-xl border border-border/60 bg-muted/30 text-muted-fg transition-colors hover:bg-accent hover:text-foreground",children:n.jsx(rn,{size:18})})})]})}function hN(e){switch(e){case"personal":return u("settings_ui.kind_personal");case"company":return u("settings_ui.kind_company");case"app":return u("settings_ui.kind_app");case"software":return u("settings_ui.kind_software");case"default":return u("settings_ui.kind_default");case"other":return u("settings_ui.kind_other");default:return u("nav.project")}}function Ve({title:e,description:t,action:a,className:o,children:l,fullHeight:c}){return n.jsxs("section",{className:ge("rounded-xl border border-border bg-card p-5",c&&"flex h-full min-h-0 flex-col",o),children:[n.jsxs("header",{className:ge("mb-4 flex items-start justify-between gap-4",c&&"shrink-0"),children:[n.jsxs("div",{children:[n.jsx("h2",{className:"text-lg font-semibold tracking-tight",children:e}),t&&n.jsx("p",{className:"mt-0.5 text-sm text-muted-fg",children:t})]}),a]}),n.jsx("div",{className:ge(c&&"flex min-h-0 flex-1 flex-col"),children:l})]})}function Ck({children:e}){return n.jsx("kbd",{className:"rounded border border-border bg-muted px-1.5 py-0.5 font-mono text-[10px] uppercase tracking-wide text-muted-fg",children:e})}function uu({ok:e}){return n.jsx("span",{className:ge("inline-block size-2 rounded-full",e===null?"bg-muted-fg":e?"bg-emerald-500":"bg-red-500")})}const jP=x.forwardRef(function(t,a){const{render:o,className:l,disabled:c=!1,focusableWhenDisabled:d=!1,nativeButton:f=!0,style:m,...g}=t,{getButtonProps:h,buttonRef:b}=no({disabled:c,focusableWhenDisabled:d,native:f});return Et("button",t,{state:{disabled:c},ref:[a,b],props:[g,h]})}),Nk=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,Ek=Pc,A_=(e,t)=>a=>{var o;if(t?.variants==null)return Ek(e,a?.class,a?.className);const{variants:l,defaultVariants:c}=t,d=Object.keys(l).map(g=>{const h=a?.[g],b=c?.[g];if(h===null)return null;const _=Nk(h)||Nk(b);return l[g][_]}),f=a&&Object.entries(a).reduce((g,h)=>{let[b,_]=h;return _===void 0||(g[b]=_),g},{}),m=t==null||(o=t.compoundVariants)===null||o===void 0?void 0:o.reduce((g,h)=>{let{class:b,className:_,...j}=h;return Object.entries(j).every(E=>{let[y,k]=E;return Array.isArray(k)?k.includes({...c,...f}[y]):{...c,...f}[y]===k})?[...g,b,_]:g},[]);return Ek(e,d,m,a?.class,a?.className)},kP=A_("group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants:{variant:{default:"bg-primary text-primary-foreground [a]:hover:bg-primary/80",outline:"border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80 aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",ghost:"hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",destructive:"bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",xs:"h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",sm:"h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",lg:"h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",icon:"size-8","icon-xs":"size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3","icon-sm":"size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg","icon-lg":"size-9"}},defaultVariants:{variant:"default",size:"default"}});function or({className:e,variant:t="default",size:a="default",...o}){return n.jsx(jP,{"data-slot":"button",className:St(kP({variant:t,size:a,className:e})),...o})}const wP={badInput:!1,customError:!1,patternMismatch:!1,rangeOverflow:!1,rangeUnderflow:!1,stepMismatch:!1,tooLong:!1,tooShort:!1,typeMismatch:!1,valid:null,valueMissing:!1},SP={valid:null,touched:!1,dirty:!1,filled:!1,focused:!1},CP={disabled:!1,...SP},M_={valid(e){return e===null?null:e?{"data-valid":""}:{"data-invalid":""}}},NP={invalid:void 0,name:void 0,validityData:{state:wP,errors:[],error:"",value:"",initialValue:null},setValidityData:Nn,disabled:void 0,setTouched:Nn,setDirty:Nn,setFilled:Nn,setFocused:Nn,validationMode:"onSubmit",shouldValidateOnChange:()=>!1,state:CP,registerFieldControl:Nn,validation:{getValidationProps:(e,t=sn)=>t,inputRef:{current:null},registeredInputs:new Map,registerInput:Nn,getInputControl:()=>null,commit:async()=>{},change:Nn}},EP=x.createContext(NP);function du(e=!0){const t=x.useContext(EP);if(t.setValidityData===Nn&&!e)throw new Error(gn(28));return t}const RP=x.createContext({elementRef:{current:null},formRef:{current:{fields:new Map}},errors:{},clearErrors:Nn,validationMode:"onSubmit",submitAttemptedRef:{current:!1}});function z_(){return x.useContext(RP)}const TP=x.createContext({controlId:void 0,registerControlId:Nn,labelId:void 0,setLabelId:Nn,messageIds:[],setMessageIds:Nn,getDescriptionProps:e=>e});function jp(){return x.useContext(TP)}function AP(e,t,a,o=!0,l){const[c,d]=x.useState(),f=ra(l?`${l}-label`:void 0),m=e??t??c;return Pe(()=>{const g=e||t||!o?void 0:MP(a.current,f);c!==g&&d(g)}),m}function MP(e,t){const a=zP(e);if(a)return!a.id&&t&&(a.id=t),a.id||void 0}function zP(e){if(!e)return;const t=e.parentElement;if(t&&t.tagName==="LABEL")return t;const a=e.id;if(a){const l=e.nextElementSibling;if(l&&l.htmlFor===a)return l}const o=e.labels;return o&&o[0]}function kp(e={}){const{id:t,implicit:a=!1,controlRef:o}=e,{controlId:l,registerControlId:c}=jp(),d=ra(t),f=a?l:void 0,m=Hn(()=>Symbol()),g=x.useRef(!1),h=x.useRef(t!=null),b=He(()=>{!g.current||c===Nn||(g.current=!1,c(m.current,void 0))});return Pe(()=>{if(c===Nn)return;let _;if(a){const j=o?.current;bt(j)&&j.closest("label")!=null?_=t??null:_=f??d}else if(t!=null)h.current=!0,_=t;else if(h.current)_=d;else{b();return}if(_===void 0){b();return}g.current=!0,c(m.current,_)},[t,o,f,c,a,d,m,b]),x.useEffect(()=>b,[b]),l??d}function O_(e,t,a,o,l=!0,c){const{registerFieldControl:d}=du(),f=Hn(()=>Symbol());Pe(()=>{const m=f.current;if(!l){d(m,void 0);return}d(m,{controlRef:e,getValue:o,id:t,name:c,value:a})},[e,l,o,t,c,d,f,a]),Pe(()=>{const m=f.current;return()=>{d(m,void 0)}},[d,f])}const OP=x.forwardRef(function(t,a){const{render:o,className:l,id:c,name:d,value:f,disabled:m=!1,onValueChange:g,defaultValue:h,autoFocus:b=!1,style:_,...j}=t,{state:E,name:y,disabled:k,setTouched:N,setDirty:w,validityData:S,setFocused:R,setFilled:A,validationMode:T,validation:z}=du(),{clearErrors:M}=z_(),L=k||m,P=y??d,B={...E,disabled:L},{labelId:D}=jp(),$=kp({id:c});Pe(()=>{const W=f!=null;z.inputRef.current?.value||W&&f!==""?A(!0):W&&f===""&&A(!1)},[z.inputRef,A,f]);const q=x.useRef(null);Pe(()=>{b&&q.current===Kn(vt(q.current))&&R(!0)},[b,R]);const[G]=ni({controlled:f,default:h,name:"FieldControl",state:"value"}),U=f!==void 0,V=U?G:void 0,X=He(()=>z.inputRef.current?.value);return O_(z.inputRef,$,V,X,!L,d),Et("input",t,{ref:[a,q],state:B,props:[{id:$,disabled:L,name:P,ref:z.inputRef,"aria-labelledby":D,autoFocus:b,...U?{value:V}:{defaultValue:h},onChange(W){const I=W.currentTarget.value;g?.(I,rt(ka,W.nativeEvent)),w(I!==(S.initialValue??"")),A(I!==""),W.nativeEvent.defaultPrevented||(M(P),z.change(I))},onFocus(){R(!0)},onBlur(W){N(!0),R(!1),T==="onBlur"&&z.commit(W.currentTarget.value)},onKeyDown(W){W.currentTarget.tagName==="INPUT"&&W.key==="Enter"&&(N(!0),z.commit(W.currentTarget.value))}},j,W=>z.getValidationProps(L,W)],stateAttributesMapping:M_})}),DP=x.forwardRef(function(t,a){return n.jsx(OP,{ref:a,...t})});function PP({className:e,type:t,...a}){return n.jsx(DP,{type:t,"data-slot":"input",className:St("h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",e),...a})}function LP({className:e,...t}){return n.jsx("textarea",{"data-slot":"textarea",className:St("flex field-sizing-content min-h-16 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-base transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",e),...t})}function IP(e){return Et(e.defaultTagName??"div",e,e)}const BP=A_("group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",{variants:{variant:{default:"bg-primary text-primary-foreground [a]:hover:bg-primary/80",secondary:"bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",destructive:"bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20",outline:"border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",ghost:"hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",link:"text-primary underline-offset-4 hover:underline"}},defaultVariants:{variant:"default"}});function $P({className:e,variant:t="default",render:a,...o}){return IP({defaultTagName:"span",props:Ss({className:St(BP({variant:t}),e)},o),render:a,state:{slot:"badge",variant:t}})}const xN=x.createContext(void 0);function UP(){const e=x.useContext(xN);if(e===void 0)throw new Error(gn(63));return e}const bN={...M_,checked(e){return e?{"data-checked":""}:{"data-unchecked":""}}},qP=x.forwardRef(function(t,a){const{checked:o,className:l,defaultChecked:c,"aria-labelledby":d,form:f,id:m,inputRef:g,name:h,nativeButton:b=!1,onCheckedChange:_,readOnly:j=!1,required:E=!1,disabled:y=!1,render:k,uncheckedValue:N,value:w,style:S,...R}=t,{clearErrors:A}=z_(),{state:T,setTouched:z,setDirty:M,validityData:L,setFilled:P,setFocused:B,validationMode:D,disabled:$,name:q,validation:G}=du(),{labelId:U}=jp(),V=$||y,X=q??h,Q=x.useRef(null),W=rr(Q,g,G.inputRef),I=x.useRef(null),K=ra(),ee=kp({id:m,implicit:!1,controlRef:I}),F=b?void 0:ee,[ne,Z]=ni({controlled:o,default:!!c,name:"Switch",state:"checked"});O_(I,K,ne,void 0,!V,h),Pe(()=>{Q.current&&P(Q.current.checked)},[P]),v_(ne,()=>{A(X),M(ne!==L.initialValue),P(ne),G.change(ne)});const{getButtonProps:fe,buttonRef:Y}=no({disabled:V,native:b}),oe=AP(d,U,Q,!b,F),ve={id:b?ee:K,role:"switch","aria-checked":ne,"aria-readonly":j||void 0,"aria-required":E||void 0,"aria-labelledby":oe,onFocus(){V||B(!0)},onBlur(){const Re=Q.current;!Re||V||(z(!0),B(!1),D==="onBlur"&&G.commit(Re.checked))},onClick(Re){if(j||V)return;Re.preventDefault();const Ae=Q.current;Ae&&Ac(Ae,Re)}},le={...G.getValidationProps(V),checked:ne,disabled:V,form:f,id:F,name:X,required:E,style:X?NS:Ub,tabIndex:-1,type:"checkbox","aria-hidden":!0,ref:W,onChange(Re){if(Re.nativeEvent.defaultPrevented)return;if(j){Re.preventDefault();return}const Ae=Re.currentTarget.checked,Ie=rt(ka,Re.nativeEvent);_?.(Ae,Ie),!Ie.isCanceled&&Z(Ae)},onClick(Re){Re.stopPropagation()},onFocus(){I.current?.focus()},...w!==void 0?{value:w}:sn},xe=x.useMemo(()=>({...T,checked:ne,disabled:V,readOnly:j,required:E}),[T,ne,V,j,E]),ke=Et("span",t,{state:xe,ref:[a,I,Y],props:[ve,R,fe,Re=>G.getValidationProps(V,Re)],stateAttributesMapping:bN});return n.jsxs(xN.Provider,{value:xe,children:[ke,!ne&&X&&N!==void 0&&n.jsx("input",{type:"hidden",form:f,name:X,value:N,disabled:V}),n.jsx("input",{...le,suppressHydrationWarning:!0})]})}),HP=x.forwardRef(function(t,a){const{render:o,className:l,style:c,...d}=t,f=UP();return Et("span",t,{state:f,ref:a,stateAttributesMapping:bN,props:d})});function VP({className:e,size:t="default",...a}){return n.jsx(qP,{"data-slot":"switch","data-size":t,className:St("peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:bg-primary data-unchecked:bg-input dark:data-unchecked:bg-input/80 data-disabled:cursor-not-allowed data-disabled:opacity-50",e),...a,children:n.jsx(HP,{"data-slot":"switch-thumb",className:"pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 group-data-[size=default]/switch:data-checked:translate-x-[calc(100%-2px)] group-data-[size=sm]/switch:data-checked:translate-x-[calc(100%-2px)] dark:data-checked:bg-primary-foreground group-data-[size=default]/switch:data-unchecked:translate-x-0 group-data-[size=sm]/switch:data-unchecked:translate-x-0 dark:data-unchecked:bg-foreground"})})}function FP({className:e,...t}){return n.jsx(Js,{role:"status","aria-label":"Loading",className:St("size-4 animate-spin",e),...t})}const _N=x.createContext(void 0);function Fo(e){const t=x.useContext(_N);if(!e&&t===void 0)throw new Error(gn(27));return t}const vN=x.forwardRef(function(t,a){const{render:o,className:l,style:c,forceRender:d=!1,...f}=t,m=Fo(),g=m.useState("open"),h=m.useState("nested"),b=m.useState("mounted"),_=m.useState("transitionStatus");return Et("div",t,{state:{open:g,transitionStatus:_},ref:[m.context.backdropRef,a],stateAttributesMapping:d_,props:[{role:"presentation",hidden:!b,style:{userSelect:"none",WebkitUserSelect:"none"}},f],enabled:d||!h})}),wp=x.forwardRef(function(t,a){const{render:o,className:l,style:c,disabled:d=!1,nativeButton:f=!0,...m}=t,g=Fo(),h=g.useState("open"),{getButtonProps:b,buttonRef:_}=no({disabled:d,native:f}),j={disabled:d};function E(y){h&&g.setOpen(!1,rt(E4,y.nativeEvent))}return Et("button",t,{state:j,ref:[a,_],props:[{onClick:E},m,b]})}),yN=x.forwardRef(function(t,a){const{render:o,className:l,style:c,id:d,...f}=t,m=Fo(),g=ra(d);return m.useSyncedValueWithCleanup("descriptionElementId",g),Et("p",t,{ref:a,props:[{id:g},f]})}),jN=x.createContext(void 0);function GP(){const e=x.useContext(jN);if(e===void 0)throw new Error(gn(26));return e}const YP={...au,...Ho,nestedDialogOpen(e){return e?{"data-nested-dialog-open":""}:null}},kN=x.forwardRef(function(t,a){const{render:o,className:l,style:c,finalFocus:d,initialFocus:f,...m}=t,g=Fo(),h=g.useState("descriptionElementId"),b=g.useState("disablePointerDismissal"),_=g.useState("floatingRootContext"),j=g.useState("popupProps"),E=g.useState("modal"),y=g.useState("mounted"),k=g.useState("nested"),N=g.useState("nestedOpenDialogCount"),w=g.useState("open"),S=g.useState("openMethod"),R=g.useState("titleElementId"),A=g.useState("transitionStatus"),T=g.useState("role"),z=_.useState("floatingId");GP(),Ca({open:w,ref:g.context.popupRef,onComplete(){w&&g.context.onOpenChangeComplete?.(!0)}});const M=f===void 0?RO(g.context.popupRef):f,L=N>0,P=g.useStateSetter("popupElement"),D=Et("div",t,{state:{open:w,nested:k,transitionStatus:A,nestedDialogOpen:L},props:[j,{id:z,"aria-labelledby":R,"aria-describedby":h,role:T,...dp,hidden:!y,onKeyDown($){xp.has($.key)&&$.stopPropagation()},style:{"--nested-dialogs":N}},m],ref:[a,g.context.popupRef,P],stateAttributesMapping:YP});return n.jsx(Jb,{context:_,openInteractionType:S,disabled:!y,closeOnFocusOut:!b,initialFocus:M,returnFocus:d,modal:E!==!1,restoreFocus:"popup",children:D})}),wN=x.forwardRef(function(t,a){const{keepMounted:o=!1,...l}=t,c=Fo(),d=c.useState("mounted"),f=c.useState("modal"),m=c.useState("open");return d||o?n.jsx(jN.Provider,{value:o,children:n.jsxs(Qb,{ref:a,...l,children:[d&&f===!0&&n.jsx(__,{ref:c.context.internalBackdropRef,inert:gp(!m)}),t.children]})}):null});function KP({store:e,parentContext:t,isDrawer:a}){const o=e.useState("open"),l=e.useState("disablePointerDismissal"),c=e.useState("modal"),d=e.useState("popupElement"),f=e.useState("floatingRootContext"),[m,g]=x.useState(0),[h,b]=x.useState(0),_=m===0,j=ip(f,{outsidePressEvent(){return e.context.internalBackdropRef.current||e.context.backdropRef.current?"intentional":{mouse:c==="trap-focus"?"sloppy":"intentional",touch:"sloppy"}},outsidePress(E){if(!e.context.outsidePressEnabledRef.current||"button"in E&&E.button!==0)return!1;if("touches"in E){if(E.type==="touchend"){if(E.changedTouches.length!==1||E.touches.length!==0)return!1}else if(E.touches.length!==1)return!1}const y=qn(E);if(_&&!l){if(c){const k=e.context.internalBackdropRef.current,N=e.context.backdropRef.current;return k||N?k===y||N===y||Ze(y,d)&&!y?.hasAttribute("data-base-ui-portal"):!0}return!0}return!1},escapeKey:_});return GC(o&&c===!0,d),e.useContextCallback("onNestedDialogOpen",(E,y)=>{g(E),b(y)}),Pe(()=>(t?.onNestedDialogOpen&&(o?t.onNestedDialogOpen(m+1,h+(a?1:0)):t.onNestedDialogOpen(0,0)),()=>{t?.onNestedDialogOpen&&o&&t.onNestedDialogOpen(0,0)}),[a,o,m,h,t]),r_(e,{activeTriggerProps:j.reference,inactiveTriggerProps:j.trigger,popupProps:j.floating,nestedOpenDialogCount:m,nestedOpenDrawerCount:h}),null}const XP={...i_,modal:e=>e.modal,nested:e=>e.nested,nestedOpenDialogCount:e=>e.nestedOpenDialogCount,nestedOpenDrawerCount:e=>e.nestedOpenDrawerCount,disablePointerDismissal:e=>e.disablePointerDismissal,openMethod:e=>e.openMethod,descriptionElementId:e=>e.descriptionElementId,titleElementId:e=>e.titleElementId,viewportElement:e=>e.viewportElement,role:e=>e.role};class QP extends nu{constructor(t,a,o){const l=new su,c=WP(t,l,a,o);super(c,ZP(l),XP)}setOpen=(t,a)=>{if(a.preventUnmountOnClose=()=>{this.set("preventUnmountingOnClose",!0)},!t&&a.trigger==null&&this.state.activeTriggerId!=null&&(a.trigger=this.state.activeTriggerElement??void 0),this.context.onOpenChange?.(t,a),a.isCanceled)return;this.state.floatingRootContext.dispatchOpenChange(t,a);const o={open:t};n_(o,t,a.trigger),this.update(o)}}function WP(e,t,a,o=!1){const l={...o_(),modal:!0,disablePointerDismissal:!1,viewportElement:null,descriptionElementId:void 0,titleElementId:void 0,openMethod:null,nested:!1,nestedOpenDialogCount:0,nestedOpenDrawerCount:0,role:"dialog",...e};return l.floatingRootContext=hC(t,a,o),l}function ZP(e){return{popupRef:x.createRef(),backdropRef:x.createRef(),internalBackdropRef:x.createRef(),outsidePressEnabledRef:{current:!0},triggerElements:e,onOpenChange:void 0,onOpenChangeComplete:void 0}}function JP(e,t){const{children:a,open:o,defaultOpen:l=!1,onOpenChange:c,onOpenChangeComplete:d,disablePointerDismissal:f=!1,modal:m=!0,actionsRef:g,handle:h,triggerId:b,defaultTriggerId:_=null}=t,j=e==="drawer",E=m,y=f,k="dialog",N=Fo(!0),w=N!=null,S={modal:E,disablePointerDismissal:y,nested:w,role:k},R=pC((P,B)=>new QP({open:l,openProp:o,activeTriggerId:_,triggerIdProp:b,...S},P,B),!0);R.useControlledProp("openProp",o),R.useControlledProp("triggerIdProp",b),R.useSyncedValues(S),R.useContextCallback("onOpenChange",c),R.useContextCallback("onOpenChangeComplete",d);const A=R.useState("open"),T=R.useState("mounted"),z=R.useState("payload");MO(R,A),s_(R);const{forceUnmount:M}=a_(A,R);x.useImperativeHandle(g,()=>({unmount:M,close:()=>R.setOpen(!1,rt(Bb))}),[M,R]);const L=A||T;return n.jsxs(_N.Provider,{value:R,children:[h&&n.jsx(t_,{handle:h,store:R}),L&&n.jsx(KP,{store:R,parentContext:N?.context,isDrawer:j}),typeof a=="function"?a({payload:z}):a]})}function SN(e){return JP("dialog",e)}const CN=x.forwardRef(function(t,a){const{render:o,className:l,style:c,id:d,...f}=t,m=Fo(),g=ra(d);return m.useSyncedValueWithCleanup("titleElementId",g),Et("h2",t,{ref:a,props:[{id:g},f]})});function Bx({...e}){return n.jsx(SN,{"data-slot":"dialog",...e})}function eL({...e}){return n.jsx(wN,{"data-slot":"dialog-portal",...e})}function tL({...e}){return n.jsx(wp,{"data-slot":"dialog-close",...e})}function nL({className:e,...t}){return n.jsx(vN,{"data-slot":"dialog-overlay",className:St("fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",e),...t})}function $x({className:e,children:t,showCloseButton:a=!0,...o}){return n.jsxs(eL,{children:[n.jsx(nL,{}),n.jsxs(kN,{"data-slot":"dialog-content",className:St("fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",e),...o,children:[t,a&&n.jsxs(wp,{"data-slot":"dialog-close",render:n.jsx(or,{variant:"ghost",className:"absolute top-2 right-2",size:"icon-sm"}),children:[n.jsx(gs,{}),n.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function Ux({className:e,...t}){return n.jsx("div",{"data-slot":"dialog-header",className:St("flex flex-col gap-2",e),...t})}function Rk({className:e,showCloseButton:t=!1,children:a,...o}){return n.jsxs("div",{"data-slot":"dialog-footer",className:St("-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",e),...o,children:[a,t&&n.jsx(wp,{render:n.jsx(or,{variant:"outline"}),children:"Close"})]})}function qx({className:e,...t}){return n.jsx(CN,{"data-slot":"dialog-title",className:St("font-heading text-base leading-none font-medium",e),...t})}function sL({className:e,...t}){return n.jsx(yN,{"data-slot":"dialog-description",className:St("text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",e),...t})}const aL={primary:"default",secondary:"outline",ghost:"ghost",destructive:"destructive"},rL={sm:"sm",md:"default"};function re({variant:e="secondary",size:t="md",loading:a,className:o,children:l,disabled:c,type:d="button",...f}){return n.jsxs(or,{type:d,variant:aL[e],size:rL[t],disabled:c||a,className:o,...f,children:[a?n.jsx(bn,{size:14}):null,l]})}function Ee(e){return n.jsx(PP,{...e})}function un(e){return n.jsx(LP,{...e})}function oL(e){return n.jsx("select",{...e,className:ge("h-8 w-full rounded-lg border border-input bg-transparent px-2.5 text-sm outline-none transition-colors focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50",e.className)})}function ie({label:e,hint:t,badge:a,children:o}){return n.jsxs("div",{className:"block space-y-1",children:[n.jsxs("span",{className:"flex items-center gap-1.5 text-xs font-medium text-muted-foreground",children:[e,a&&n.jsx("span",{className:"rounded bg-muted px-1 py-0.5 text-[9px] font-semibold uppercase tracking-wide text-muted-foreground",children:a})]}),o,t&&n.jsx("span",{className:"block text-[11px] text-muted-foreground/70",children:t})]})}function Bt({checked:e,onChange:t,label:a,disabled:o}){return n.jsxs("label",{className:ge("inline-flex items-center gap-2",o&&"opacity-50"),children:[n.jsx(VP,{checked:e,onCheckedChange:t,disabled:o}),a&&n.jsx("span",{className:"text-sm",children:a})]})}function $e({children:e,tone:t="muted",className:a}){const o=t==="danger"?"destructive":t==="muted"?"secondary":"outline",l={muted:"",danger:"",success:"text-emerald-400 border-emerald-500/30",warning:"text-amber-400 border-amber-500/30",info:"text-sky-400 border-sky-500/30"};return n.jsx($P,{variant:o,className:ge("rounded-md",l[t],a),children:e})}function Xt({open:e,onClose:t,title:a,description:o,children:l,footer:c,size:d="md"}){const f={sm:"sm:max-w-md",md:"sm:max-w-lg",lg:"sm:max-w-2xl",xl:"sm:max-w-4xl"};return n.jsx(Bx,{open:e,onOpenChange:m=>{m||t()},children:n.jsxs($x,{className:ge("flex max-h-[88vh] w-full flex-col gap-0 p-0",f[d]),children:[(a||o)&&n.jsxs(Ux,{className:"shrink-0 border-b border-border px-5 py-4 pr-12",children:[a&&n.jsx(qx,{children:a}),o&&n.jsx(sL,{children:o})]}),n.jsx("div",{className:"min-h-0 flex-1 overflow-auto px-5 py-4",children:l}),c&&n.jsx("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border px-5 py-4",children:c})]})})}function bn({size:e=14}){return n.jsx(FP,{style:{width:e,height:e}})}function ft({children:e}){return n.jsx("div",{className:"rounded-lg border border-dashed border-border bg-muted/20 px-4 py-6 text-center text-sm text-muted-foreground",children:e})}function st({label:e="Cargando…"}){return n.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[n.jsx(bn,{})," ",e]})}const NN=x.createContext(null);let lL=1;function iL({children:e}){const[t,a]=x.useState([]),o=x.useCallback((c,d)=>{const f=lL++;a(m=>[...m,{id:f,kind:c,message:d}]),setTimeout(()=>{a(m=>m.filter(g=>g.id!==f))},4500)},[]),l=x.useMemo(()=>({show:o,success:c=>o("success",c),error:c=>o("error",c),info:c=>o("info",c)}),[o]);return x.useEffect(()=>(window.__apxToast=l,()=>{delete window.__apxToast}),[l]),n.jsxs(NN.Provider,{value:l,children:[e,n.jsx("div",{className:"pointer-events-none fixed bottom-4 right-4 z-[100] flex w-80 max-w-[calc(100vw-2rem)] flex-col gap-2",children:t.map(c=>n.jsx("div",{className:ge("pointer-events-auto overflow-hidden rounded-lg border bg-card px-3 py-2 text-sm shadow-lg",c.kind==="success"&&"border-emerald-500/40",c.kind==="error"&&"border-destructive/60",c.kind==="info"&&"border-border"),children:n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("span",{className:ge("mt-1 size-2 shrink-0 rounded-full",c.kind==="success"&&"bg-emerald-500",c.kind==="error"&&"bg-destructive",c.kind==="info"&&"bg-sky-500")}),n.jsx("span",{className:"flex-1 break-words",children:c.message})]})},c.id))})]})}function Je(){const e=x.useContext(NN);if(!e)throw new Error("useToast must be used inside <ToastProvider>");return e}function EN(){const{data:e,error:t,isLoading:a}=Be("/health",()=>iP.get(),{refreshInterval:Qf.health});return{health:e,error:t,isLoading:a,isUp:!t&&!!e}}function cL(){const{data:e,error:t,isLoading:a,mutate:o}=Be("/engines",()=>Hc.list());return{engines:e?.engines||[],error:t,isLoading:a,mutate:o}}function uL(){const{data:e,error:t,isLoading:a,mutate:o}=Be("/telegram/status",()=>Dn.status(),{refreshInterval:Qf.telegramStatus});return{status:e,error:t,isLoading:a,mutate:o}}function D_(){const{data:e,error:t,isLoading:a,mutate:o}=Be("/telegram/channels",()=>Dn.channels.list());return{channels:e?.channels||[],error:t,isLoading:a,mutate:o}}function P_(){const{data:e,error:t,isLoading:a,mutate:o}=Be("/telegram/contacts",()=>Dn.contacts.list());return{contacts:e?.contacts||[],roles:e?.roles||{},channelOwners:e?.channel_owners||[],error:t,isLoading:a,mutate:o}}function ps(e){return typeof e=="string"&&e.startsWith("*** set ***")}function Fr(e,t="(no seteada)"){return ps(e)?e:t}function Po(e){if(typeof e!="string")return null;const t=e.match(/\(\.\.\.([^)]+)\)/);return t?t[1]:null}function RN({channel:e,onClose:t,onSaved:a}){const o=Je(),[l,c]=x.useState(!1),[d,f]=x.useState({name:""});x.useEffect(()=>{f(e?{...e,bot_token:""}:{name:""})},[e?.name]);const m=async()=>{if(!d.name?.trim()){o.error(u("telegram_channel_dialog.name_required"));return}c(!0);try{e&&e.name!==""&&e?.name===d.name?await Dn.channels.patch(e.name,d):await Dn.channels.upsert(d),o.success(u("telegram_channel_dialog.saved")),a()}catch(g){o.error(g.message)}finally{c(!1)}};return n.jsx(Xt,{open:!!e,onClose:t,title:e?.name?u("telegram_channel_dialog.edit_title",{name:e.name}):u("telegram_channel_dialog.new_title"),description:u("telegram_ui.channel_dialog_desc"),footer:n.jsxs(n.Fragment,{children:[n.jsx(re,{variant:"ghost",onClick:t,disabled:l,children:u("common.cancel")}),n.jsx(re,{variant:"primary",onClick:m,loading:l,children:u("common.save")})]}),children:n.jsxs("div",{className:"space-y-3",children:[n.jsx(ie,{label:u("telegram_channel_dialog.name_label"),children:n.jsx(Ee,{value:d.name,onChange:g=>f({...d,name:g.target.value}),disabled:!!e?.name})}),n.jsx(ie,{label:u("telegram_channel_dialog.token_label"),hint:e?.bot_token?Fr(e.bot_token):u("telegram_ui.bot_token_hint"),children:n.jsx(Ee,{type:"password",value:d.bot_token||"",onChange:g=>f({...d,bot_token:g.target.value}),placeholder:e?.bot_token?Fr(e.bot_token):""})}),n.jsx(ie,{label:u("telegram_channel_dialog.chat_id"),children:n.jsx(Ee,{value:d.chat_id||"",onChange:g=>f({...d,chat_id:g.target.value})})}),n.jsx(ie,{label:u("telegram_channel_dialog.project_label"),hint:u("telegram_channel_dialog.project_hint"),children:n.jsx(Ee,{value:d.project||"",onChange:g=>f({...d,project:g.target.value})})}),n.jsx(ie,{label:u("telegram_channel_dialog.route_label"),hint:u("telegram_channel_dialog.route_hint"),children:n.jsx(Ee,{value:d.route_to_agent||"",onChange:g=>f({...d,route_to_agent:g.target.value})})}),n.jsx(ie,{label:u("telegram_channel_dialog.owner_label"),hint:u("telegram_channel_dialog.owner_hint"),children:n.jsx(Ee,{value:d.owner_user_id!=null?String(d.owner_user_id):"",onChange:g=>{const h=g.target.value.trim();f({...d,owner_user_id:h===""?void 0:/^\d+$/.test(h)?Number(h):h})},placeholder:"889721252"})}),n.jsx(Bt,{checked:!!d.respond_with_engine,onChange:g=>f({...d,respond_with_engine:g}),label:u("telegram_channel_dialog.respond_label")})]})})}function TN({channel:e,onClose:t}){const a=Je(),[o,l]=x.useState(u("admin.telegram_default_message")),[c,d]=x.useState(!1),f=async()=>{if(!(!o.trim()||!e)){d(!0);try{await Dn.send({text:o,channel:e.name}),a.success(u("telegram_ui.message_sent")),t()}catch(m){a.error(m.message)}finally{d(!1)}}};return n.jsx(Xt,{open:!!e,onClose:t,title:e?u("telegram_send_dialog.title",{name:e.name}):"",description:e?u("telegram_ui.send_chat_id",{id:e.chat_id||"—"}):"",footer:n.jsxs(n.Fragment,{children:[n.jsx(re,{variant:"ghost",onClick:t,disabled:c,children:u("common.cancel")}),n.jsx(re,{variant:"primary",onClick:f,loading:c,children:u("chat_ui.send")})]}),children:n.jsx(ie,{label:u("telegram_ui.message_label"),children:n.jsx(un,{rows:4,value:o,onChange:m=>l(m.target.value)})})})}function AN({bare:e=!1}){const t=Je(),{contacts:a,roles:o,channelOwners:l,isLoading:c,mutate:d}=P_(),f=new Set(l.filter(_=>_.owner_user_id!=null).map(_=>String(_.owner_user_id))),m=Array.from(new Set(["owner","guest",...Object.keys(o)])),g=async(_,j)=>{try{await Dn.contacts.patch(_.user_id,{role:j}),t.success(u("telegram_ui.role_assigned",{name:_.name||_.user_id,role:j})),d()}catch(E){t.error(E.message)}},h=async _=>{if(confirm(u("telegram_contacts.delete_confirm",{name:_.name||String(_.user_id)})))try{await Dn.contacts.remove(_.user_id),t.success(u("telegram_contacts.removed")),d()}catch(j){t.error(j.message)}},b=n.jsxs(n.Fragment,{children:[c&&n.jsx(st,{}),!c&&a.length===0&&n.jsx(ft,{children:u("telegram_contacts.empty")}),a.length>0&&n.jsx("ul",{className:"space-y-2 text-sm",children:a.map(_=>{const j=f.has(String(_.user_id)),E=j?"owner":_.role||"guest";return n.jsxs("li",{className:"rounded-md border border-border bg-muted/30 px-3 py-2",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("span",{className:"font-medium",children:_.name||"—"}),_.username&&n.jsxs("span",{className:"ml-2 text-xs text-muted-fg",children:["@",_.username]}),j&&n.jsx($e,{tone:"success",children:u("telegram_contacts.owner_badge")})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(qe,{content:u(j?"telegram_contacts.owner_hint":"telegram_contacts.assign_role"),children:n.jsx(oL,{value:E,disabled:j,onChange:y=>g(_,y.target.value),children:m.map(y=>n.jsx("option",{value:y,children:y},y))})}),n.jsx(re,{size:"sm",variant:"destructive",onClick:()=>h(_),children:u("common.delete")})]})]}),n.jsxs("div",{className:"mt-1 grid grid-cols-3 gap-2 text-xs text-muted-fg",children:[n.jsxs("span",{children:["user_id: ",String(_.user_id)]}),n.jsxs("span",{children:[u("telegram_contacts.last_seen")," ",_.last_seen?_.last_seen.slice(0,10):"—"]}),n.jsx("span",{children:dL(o[E])})]})]},String(_.user_id))})})]});return e?b:n.jsx(Ve,{title:u("telegram_contacts.title"),description:u("telegram_contacts.desc"),children:b})}function dL(e){return!e||e.tools===void 0?"":e.tools==="*"?u("telegram_contacts.tools_all"):Array.isArray(e.tools)?e.tools.length?`${u("telegram_contacts.tools_label")} ${e.tools.join(", ")}`:u("telegram_contacts.tools_none"):""}function fL(){const e=Pn(),[t,a]=Uo(),o=Je(),{health:l,isUp:c}=EN(),{projects:d,isLoading:f,mutate:m}=iu(),{engines:g,isLoading:h}=cL(),{status:b,mutate:_}=uL(),{channels:j,isLoading:E,mutate:y}=D_(),[k,N]=x.useState(null),[w,S]=x.useState(null),R=async()=>{try{await ai.reload(),o.success(u("admin.reload_success"))}catch(M){o.error(M.message)}},A=async()=>{try{b?.enabled?(await Dn.stop(),o.info(u("admin.telegram_polling_stopped"))):(await Dn.start(),o.success(u("admin.telegram_polling_started"))),_()}catch(M){o.error(M.message)}},T=async M=>{if(confirm(u("telegram_channels.delete_confirm",{name:M})))try{await Dn.channels.remove(M),o.success(u("admin.telegram_channel_removed")),y()}catch(L){o.error(L.message)}},z=async(M,L)=>{if(confirm(u("admin.unregister_confirm",{label:L})))try{await Zn.remove(M),o.success(u("project.unregistered")),m()}catch(P){o.error(P.message)}};return n.jsxs("div",{className:"mx-auto max-w-5xl space-y-6 p-6","data-testid":"screen-admin",children:[n.jsxs("header",{className:"flex items-end justify-between",children:[n.jsxs("div",{children:[n.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:u("admin.title")}),n.jsx("p",{className:"text-sm text-muted-fg",children:u("admin.subtitle")})]}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx(qe,{content:u("daemon.reload_hint"),children:n.jsxs(re,{size:"sm",onClick:R,children:[u("common.reload")," config"]})}),n.jsxs(re,{size:"sm",variant:"primary",onClick:()=>{const M=new URLSearchParams(t);M.set("action","add-project"),a(M)},children:[n.jsx(Dt,{size:14})," ",u("nav.project")]})]})]}),n.jsx(Ve,{title:u("daemon.version"),children:n.jsxs("div",{className:"grid grid-cols-3 gap-3 text-sm",children:[n.jsx(xh,{label:u("daemon.version"),value:l?.version||"—"}),n.jsx(xh,{label:u("daemon.uptime"),value:l?`${l.uptime_s}s`:"—"}),n.jsx(xh,{label:u("daemon.status"),value:u(c?"daemon.running":"daemon.down"),ok:c})]})}),n.jsxs(Ve,{title:u("admin.engines_title"),description:u("admin.engines_subtitle"),children:[h&&n.jsx(st,{}),n.jsx("div",{className:"flex flex-wrap gap-1.5",children:g.map(M=>n.jsx($e,{tone:"info",children:M},M))})]}),n.jsxs(Ve,{title:u("admin.telegram_title"),description:u("admin.telegram_subtitle"),action:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Bt,{checked:!!b?.enabled,onChange:A,label:b?.enabled?u("admin.telegram_polling_on"):u("admin.telegram_polling_off")}),n.jsxs(re,{size:"sm",onClick:()=>N({name:""}),children:[n.jsx(Dt,{size:14})," ",u("admin.telegram_add_channel")]})]}),children:[E&&n.jsx(st,{}),j.length===0&&n.jsx(ft,{children:u("common.none_yet")}),n.jsx("ul",{className:"space-y-2 text-sm",children:j.map(M=>n.jsxs("li",{className:"rounded-md border border-border bg-muted/30 px-3 py-2",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("span",{className:"font-medium",children:M.name}),n.jsxs("div",{className:"flex items-center gap-2",children:[M.project&&n.jsxs($e,{tone:"success",children:["project = ",M.project]}),n.jsxs(re,{size:"sm",variant:"ghost",onClick:()=>S(M),children:[n.jsx(Sa,{size:13})," ",u("admin.telegram_send_test")]}),n.jsx(re,{size:"sm",variant:"secondary",onClick:()=>N(M),children:u("common.edit")}),n.jsx(re,{size:"sm",variant:"destructive",onClick:()=>T(M.name),children:u("common.delete")})]})]}),n.jsxs("div",{className:"mt-1 grid grid-cols-3 gap-2 text-xs text-muted-fg",children:[n.jsxs("span",{children:["chat_id: ",M.chat_id||"—"]}),n.jsxs("span",{children:["route_to_agent: ",M.route_to_agent||"default APX"]}),n.jsxs("span",{children:["engine: ",M.respond_with_engine?u("admin.engine_badge"):u("admin.engine_badge_no")]})]})]},M.name))})]}),n.jsx(AN,{}),n.jsxs(Ve,{title:u("admin.projects_title"),description:u("admin.projects_subtitle"),children:[f&&n.jsx(st,{}),n.jsx("ul",{className:"divide-y divide-border",children:d.map(M=>n.jsxs("li",{className:"flex items-center gap-3 py-2",children:[n.jsxs("span",{className:"w-10 font-mono text-xs text-muted-fg",children:["#",M.id]}),n.jsxs("button",{type:"button",className:"flex-1 text-left hover:underline",onClick:()=>e(`/p/${M.id}`),children:[n.jsx("span",{className:"font-medium",children:M.name||M.path.split("/").pop()}),n.jsx("span",{className:"ml-2 text-xs text-muted-fg",children:M.path})]}),n.jsxs($e,{children:[M.agents??0," ",u("admin.agents_badge")]}),Number(M.id)!==0&&n.jsx(re,{size:"sm",variant:"destructive",onClick:()=>z(String(M.id),M.name||M.path),children:u("admin.unregister")})]},M.id))})]}),n.jsx(RN,{channel:k,onClose:()=>N(null),onSaved:()=>{N(null),y()}}),n.jsx(TN,{channel:w,onClose:()=>S(null)})]})}function xh({label:e,value:t,ok:a}){return n.jsxs("div",{className:"rounded-md border border-border bg-muted/30 p-3",children:[n.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-fg",children:e}),n.jsxs("div",{className:"mt-1 flex items-center gap-2 text-base font-medium",children:[a!==void 0&&n.jsx(uu,{ok:a}),n.jsx("span",{children:t})]})]})}const MN=x.createContext(null),zN=x.createContext(null),ON=x.createContext(""),DN=x.createContext(null),PN=x.createContext(null),LN=x.createContext(null);function pL({children:e}){const[t,a]=x.useState(null),[o,l]=x.useState(""),[c,d]=x.useState(null);return n.jsx(zN.Provider,{value:a,children:n.jsx(MN.Provider,{value:t,children:n.jsx(DN.Provider,{value:l,children:n.jsx(ON.Provider,{value:o,children:n.jsx(LN.Provider,{value:d,children:n.jsx(PN.Provider,{value:c,children:e})})})})})})}function mL(){return x.useContext(MN)}function gL(e,t){const a=x.useContext(zN);x.useEffect(()=>(a?.({collapsed:e,toggle:t}),()=>a?.(null)),[e,t,a])}function hL(){return x.useContext(ON)}function xL(e){const t=x.useContext(DN);x.useEffect(()=>(t?.(e),()=>t?.("")),[e,t])}function bL(){return x.useContext(PN)}function _L(e){const t=x.useContext(LN);x.useEffect(()=>(t?.(e),()=>t?.(null)),[e,t])}function IN({sections:e,active:t,onChange:a,collapsed:o,onToggleCollapse:l,actions:c,contentClassName:d,testId:f,children:m}){return gL(o,l),n.jsxs("div",{className:"flex h-full",children:[n.jsx(AD,{sections:e,active:t,onChange:a,collapsed:o}),n.jsxs("div",{className:"flex min-w-0 flex-1 flex-col overflow-hidden",children:[c?n.jsx("div",{className:"flex shrink-0 items-center justify-end gap-2 px-6 pt-3",children:c}):null,n.jsx("div",{className:ge("flex-1 min-h-0 overflow-y-auto",d),"data-testid":f,children:m})]})]})}function vL({className:e}){return n.jsx("svg",{className:e,viewBox:"0 0 24 24",fill:"currentColor",children:n.jsx("path",{d:"M18.833 9.637a4.167 4.167 0 1 1 0 8.333 4.167 4.167 0 0 1 0-8.333zm-13.666 0a4.167 4.167 0 1 1 0 8.333 4.167 4.167 0 0 1 0-8.333zM12 2a4.167 4.167 0 1 1 0 8.333A4.167 4.167 0 0 1 12 2z"})})}function BN({className:e}){return n.jsx("svg",{className:e,viewBox:"0 0 24 24",fill:"currentColor",children:n.jsx("path",{d:"M19.355 18.538a68.967 68.959 0 0 0 1.858-2.954.81.81 0 0 0-.062-.9c-.516-.685-1.504-2.075-2.042-3.362-.553-1.321-.636-3.375-.64-4.377a1.707 1.707 0 0 0-.358-1.05l-3.198-4.064a3.744 3.744 0 0 1-.076.543c-.106.503-.307 1.004-.536 1.5-.134.29-.29.6-.446.914l-.31.626c-.516 1.068-.997 2.227-1.132 3.59-.124 1.26.046 2.73.815 4.481.128.011.257.025.386.044a6.363 6.363 0 0 1 3.326 1.505c.916.79 1.744 1.922 2.415 3.5zM8.199 22.569c.073.012.146.02.22.02.78.024 2.095.092 3.16.29.87.16 2.593.64 4.01 1.055 1.083.316 2.198-.548 2.355-1.664.114-.814.33-1.735.725-2.58l-.01.005c-.67-1.87-1.522-3.078-2.416-3.849a5.295 5.295 0 0 0-2.778-1.257c-1.54-.216-2.952.19-3.84.45.532 2.218.368 4.829-1.425 7.531zM5.533 9.938c-.023.1-.056.197-.098.29L2.82 16.059a1.602 1.602 0 0 0 .313 1.772l4.116 4.24c2.103-3.101 1.796-6.02.836-8.3-.728-1.73-1.832-3.081-2.55-3.831zM9.32 14.01c.615-.183 1.606-.465 2.745-.534-.683-1.725-.848-3.233-.716-4.577.154-1.552.7-2.847 1.235-3.95.113-.235.223-.454.328-.664.149-.297.288-.577.419-.86.217-.47.379-.885.46-1.27.08-.38.08-.72-.014-1.043-.095-.325-.297-.675-.68-1.06a1.6 1.6 0 0 0-1.475.36l-4.95 4.452a1.602 1.602 0 0 0-.513.952l-.427 2.83c.672.59 2.328 2.316 3.335 4.711.09.21.175.43.253.653z"})})}function yL({className:e}){return n.jsx("svg",{className:e,viewBox:"0 0 24 24",fill:"currentColor",children:n.jsx("path",{d:"M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"})})}const Tk={happy:{eyes:["◕","◕"],mouth:"‿"},wave:{eyes:["◕","◕"],mouth:"▽",top:"·"},confused:{eyes:["◑","◐"],mouth:"o",top:"?"},sad:{eyes:["╥","╥"],mouth:"◠"},excited:{eyes:["★","★"],mouth:"▽",top:"✦"},sleeping:{eyes:["−","−"],mouth:"‿",top:"z z"}};function $N({mood:e="happy",className:t}){const a=Tk[e]??Tk.happy,[o,l]=a.eyes,c="text-emerald-700 dark:text-emerald-600/70";return n.jsxs("div",{"aria-hidden":!0,className:St("select-none whitespace-pre font-mono leading-none text-emerald-400",t),children:[a.top&&n.jsx("div",{children:n.jsx("span",{className:c,children:` ${a.top}`})}),n.jsx("div",{children:" ▄███████▄"}),n.jsxs("div",{children:[" █ ",n.jsx("span",{className:c,children:"██"})," ",n.jsx("span",{className:c,children:"██"})," █"]}),n.jsx("div",{children:` █ ${o} ${l} █`}),n.jsx("div",{children:` █ ${a.mouth} █`}),n.jsx("div",{children:" ▀███████▀"})]})}function UN({mood:e="confused",title:t,titleClassName:a,message:o,action:l,className:c,testId:d}){return n.jsx("div",{className:St("grid h-full place-items-center p-8",c),"data-testid":d,children:n.jsxs("div",{className:"flex flex-col items-center text-center",children:[n.jsx($N,{mood:e,className:"mb-6 text-sm"}),t!=null&&n.jsx("div",{className:St("font-mono font-semibold leading-none tracking-tight text-foreground",a),children:t}),o!=null&&n.jsx("p",{className:"mt-4 max-w-sm text-sm text-muted-fg",children:o}),l&&n.jsx("div",{className:"mt-6",children:l})]})})}const L_={pending:{labelKey:"tasks.status_pending",color:"text-amber-500",dot:"bg-amber-400",Icon:NA},running:{labelKey:"tasks.status_running",color:"text-sky-500",dot:"bg-sky-400",Icon:Js,spin:!0},in_review:{labelKey:"tasks.status_in_review",color:"text-violet-500",dot:"bg-violet-400",Icon:G2},blocked:{labelKey:"tasks.status_blocked",color:"text-slate-400",dot:"bg-slate-400",Icon:EA}},qN=["pending","running","in_review","blocked"];function Tf(e){return e.state==="done"?"done":e.state==="dropped"?"dropped":e.status??"pending"}function I_(e){return u(L_[e].labelKey)}function Af({status:e,className:t}){if(e==="done")return n.jsx(Hf,{className:ge("size-4 text-emerald-500",t)});if(e==="dropped")return n.jsx(F2,{className:ge("size-4 text-muted-foreground",t)});const a=L_[e];return n.jsx(a.Icon,{className:ge("size-4",a.color,a.spin&&"animate-spin",t)})}function B_({status:e}){const t=e==="done"?u("tasks.done_label"):e==="dropped"?u("tasks.dropped_label"):I_(e),a=e==="done"?"text-emerald-500 border-emerald-500/30":e==="dropped"?"text-muted-foreground border-border":`${L_[e].color} border-current/30`;return n.jsxs("span",{className:ge("inline-flex items-center gap-1 rounded-md border px-1.5 py-0.5 text-[10px] font-medium capitalize",a),children:[n.jsx(Af,{status:e,className:"size-3"}),t]})}function jL(e,t){var a,o=1;e==null&&(e=0),t==null&&(t=0);function l(){var c,d=a.length,f,m=0,g=0;for(c=0;c<d;++c)f=a[c],m+=f.x,g+=f.y;for(m=(m/d-e)*o,g=(g/d-t)*o,c=0;c<d;++c)f=a[c],f.x-=m,f.y-=g}return l.initialize=function(c){a=c},l.x=function(c){return arguments.length?(e=+c,l):e},l.y=function(c){return arguments.length?(t=+c,l):t},l.strength=function(c){return arguments.length?(o=+c,l):o},l}function kL(e){const t=+this._x.call(null,e),a=+this._y.call(null,e);return HN(this.cover(t,a),t,a,e)}function HN(e,t,a,o){if(isNaN(t)||isNaN(a))return e;var l,c=e._root,d={data:o},f=e._x0,m=e._y0,g=e._x1,h=e._y1,b,_,j,E,y,k,N,w;if(!c)return e._root=d,e;for(;c.length;)if((y=t>=(b=(f+g)/2))?f=b:g=b,(k=a>=(_=(m+h)/2))?m=_:h=_,l=c,!(c=c[N=k<<1|y]))return l[N]=d,e;if(j=+e._x.call(null,c.data),E=+e._y.call(null,c.data),t===j&&a===E)return d.next=c,l?l[N]=d:e._root=d,e;do l=l?l[N]=new Array(4):e._root=new Array(4),(y=t>=(b=(f+g)/2))?f=b:g=b,(k=a>=(_=(m+h)/2))?m=_:h=_;while((N=k<<1|y)===(w=(E>=_)<<1|j>=b));return l[w]=c,l[N]=d,e}function wL(e){var t,a,o=e.length,l,c,d=new Array(o),f=new Array(o),m=1/0,g=1/0,h=-1/0,b=-1/0;for(a=0;a<o;++a)isNaN(l=+this._x.call(null,t=e[a]))||isNaN(c=+this._y.call(null,t))||(d[a]=l,f[a]=c,l<m&&(m=l),l>h&&(h=l),c<g&&(g=c),c>b&&(b=c));if(m>h||g>b)return this;for(this.cover(m,g).cover(h,b),a=0;a<o;++a)HN(this,d[a],f[a],e[a]);return this}function SL(e,t){if(isNaN(e=+e)||isNaN(t=+t))return this;var a=this._x0,o=this._y0,l=this._x1,c=this._y1;if(isNaN(a))l=(a=Math.floor(e))+1,c=(o=Math.floor(t))+1;else{for(var d=l-a||1,f=this._root,m,g;a>e||e>=l||o>t||t>=c;)switch(g=(t<o)<<1|e<a,m=new Array(4),m[g]=f,f=m,d*=2,g){case 0:l=a+d,c=o+d;break;case 1:a=l-d,c=o+d;break;case 2:l=a+d,o=c-d;break;case 3:a=l-d,o=c-d;break}this._root&&this._root.length&&(this._root=f)}return this._x0=a,this._y0=o,this._x1=l,this._y1=c,this}function CL(){var e=[];return this.visit(function(t){if(!t.length)do e.push(t.data);while(t=t.next)}),e}function NL(e){return arguments.length?this.cover(+e[0][0],+e[0][1]).cover(+e[1][0],+e[1][1]):isNaN(this._x0)?void 0:[[this._x0,this._y0],[this._x1,this._y1]]}function Jn(e,t,a,o,l){this.node=e,this.x0=t,this.y0=a,this.x1=o,this.y1=l}function EL(e,t,a){var o,l=this._x0,c=this._y0,d,f,m,g,h=this._x1,b=this._y1,_=[],j=this._root,E,y;for(j&&_.push(new Jn(j,l,c,h,b)),a==null?a=1/0:(l=e-a,c=t-a,h=e+a,b=t+a,a*=a);E=_.pop();)if(!(!(j=E.node)||(d=E.x0)>h||(f=E.y0)>b||(m=E.x1)<l||(g=E.y1)<c))if(j.length){var k=(d+m)/2,N=(f+g)/2;_.push(new Jn(j[3],k,N,m,g),new Jn(j[2],d,N,k,g),new Jn(j[1],k,f,m,N),new Jn(j[0],d,f,k,N)),(y=(t>=N)<<1|e>=k)&&(E=_[_.length-1],_[_.length-1]=_[_.length-1-y],_[_.length-1-y]=E)}else{var w=e-+this._x.call(null,j.data),S=t-+this._y.call(null,j.data),R=w*w+S*S;if(R<a){var A=Math.sqrt(a=R);l=e-A,c=t-A,h=e+A,b=t+A,o=j.data}}return o}function RL(e){if(isNaN(h=+this._x.call(null,e))||isNaN(b=+this._y.call(null,e)))return this;var t,a=this._root,o,l,c,d=this._x0,f=this._y0,m=this._x1,g=this._y1,h,b,_,j,E,y,k,N;if(!a)return this;if(a.length)for(;;){if((E=h>=(_=(d+m)/2))?d=_:m=_,(y=b>=(j=(f+g)/2))?f=j:g=j,t=a,!(a=a[k=y<<1|E]))return this;if(!a.length)break;(t[k+1&3]||t[k+2&3]||t[k+3&3])&&(o=t,N=k)}for(;a.data!==e;)if(l=a,!(a=a.next))return this;return(c=a.next)&&delete a.next,l?(c?l.next=c:delete l.next,this):t?(c?t[k]=c:delete t[k],(a=t[0]||t[1]||t[2]||t[3])&&a===(t[3]||t[2]||t[1]||t[0])&&!a.length&&(o?o[N]=a:this._root=a),this):(this._root=c,this)}function TL(e){for(var t=0,a=e.length;t<a;++t)this.remove(e[t]);return this}function AL(){return this._root}function ML(){var e=0;return this.visit(function(t){if(!t.length)do++e;while(t=t.next)}),e}function zL(e){var t=[],a,o=this._root,l,c,d,f,m;for(o&&t.push(new Jn(o,this._x0,this._y0,this._x1,this._y1));a=t.pop();)if(!e(o=a.node,c=a.x0,d=a.y0,f=a.x1,m=a.y1)&&o.length){var g=(c+f)/2,h=(d+m)/2;(l=o[3])&&t.push(new Jn(l,g,h,f,m)),(l=o[2])&&t.push(new Jn(l,c,h,g,m)),(l=o[1])&&t.push(new Jn(l,g,d,f,h)),(l=o[0])&&t.push(new Jn(l,c,d,g,h))}return this}function OL(e){var t=[],a=[],o;for(this._root&&t.push(new Jn(this._root,this._x0,this._y0,this._x1,this._y1));o=t.pop();){var l=o.node;if(l.length){var c,d=o.x0,f=o.y0,m=o.x1,g=o.y1,h=(d+m)/2,b=(f+g)/2;(c=l[0])&&t.push(new Jn(c,d,f,h,b)),(c=l[1])&&t.push(new Jn(c,h,f,m,b)),(c=l[2])&&t.push(new Jn(c,d,b,h,g)),(c=l[3])&&t.push(new Jn(c,h,b,m,g))}a.push(o)}for(;o=a.pop();)e(o.node,o.x0,o.y0,o.x1,o.y1);return this}function DL(e){return e[0]}function PL(e){return arguments.length?(this._x=e,this):this._x}function LL(e){return e[1]}function IL(e){return arguments.length?(this._y=e,this):this._y}function $_(e,t,a){var o=new U_(t??DL,a??LL,NaN,NaN,NaN,NaN);return e==null?o:o.addAll(e)}function U_(e,t,a,o,l,c){this._x=e,this._y=t,this._x0=a,this._y0=o,this._x1=l,this._y1=c,this._root=void 0}function Ak(e){for(var t={data:e.data},a=t;e=e.next;)a=a.next={data:e.data};return t}var ss=$_.prototype=U_.prototype;ss.copy=function(){var e=new U_(this._x,this._y,this._x0,this._y0,this._x1,this._y1),t=this._root,a,o;if(!t)return e;if(!t.length)return e._root=Ak(t),e;for(a=[{source:t,target:e._root=new Array(4)}];t=a.pop();)for(var l=0;l<4;++l)(o=t.source[l])&&(o.length?a.push({source:o,target:t.target[l]=new Array(4)}):t.target[l]=Ak(o));return e};ss.add=kL;ss.addAll=wL;ss.cover=SL;ss.data=CL;ss.extent=NL;ss.find=EL;ss.remove=RL;ss.removeAll=TL;ss.root=AL;ss.size=ML;ss.visit=zL;ss.visitAfter=OL;ss.x=PL;ss.y=IL;function es(e){return function(){return e}}function qr(e){return(e()-.5)*1e-6}function BL(e){return e.x+e.vx}function $L(e){return e.y+e.vy}function UL(e){var t,a,o,l=1,c=1;typeof e!="function"&&(e=es(e==null?1:+e));function d(){for(var g,h=t.length,b,_,j,E,y,k,N=0;N<c;++N)for(b=$_(t,BL,$L).visitAfter(f),g=0;g<h;++g)_=t[g],y=a[_.index],k=y*y,j=_.x+_.vx,E=_.y+_.vy,b.visit(w);function w(S,R,A,T,z){var M=S.data,L=S.r,P=y+L;if(M){if(M.index>_.index){var B=j-M.x-M.vx,D=E-M.y-M.vy,$=B*B+D*D;$<P*P&&(B===0&&(B=qr(o),$+=B*B),D===0&&(D=qr(o),$+=D*D),$=(P-($=Math.sqrt($)))/$*l,_.vx+=(B*=$)*(P=(L*=L)/(k+L)),_.vy+=(D*=$)*P,M.vx-=B*(P=1-P),M.vy-=D*P)}return}return R>j+P||T<j-P||A>E+P||z<E-P}}function f(g){if(g.data)return g.r=a[g.data.index];for(var h=g.r=0;h<4;++h)g[h]&&g[h].r>g.r&&(g.r=g[h].r)}function m(){if(t){var g,h=t.length,b;for(a=new Array(h),g=0;g<h;++g)b=t[g],a[b.index]=+e(b,g,t)}}return d.initialize=function(g,h){t=g,o=h,m()},d.iterations=function(g){return arguments.length?(c=+g,d):c},d.strength=function(g){return arguments.length?(l=+g,d):l},d.radius=function(g){return arguments.length?(e=typeof g=="function"?g:es(+g),m(),d):e},d}function qL(e){return e.index}function Mk(e,t){var a=e.get(t);if(!a)throw new Error("node not found: "+t);return a}function HL(e){var t=qL,a=b,o,l=es(30),c,d,f,m,g,h=1;e==null&&(e=[]);function b(k){return 1/Math.min(f[k.source.index],f[k.target.index])}function _(k){for(var N=0,w=e.length;N<h;++N)for(var S=0,R,A,T,z,M,L,P;S<w;++S)R=e[S],A=R.source,T=R.target,z=T.x+T.vx-A.x-A.vx||qr(g),M=T.y+T.vy-A.y-A.vy||qr(g),L=Math.sqrt(z*z+M*M),L=(L-c[S])/L*k*o[S],z*=L,M*=L,T.vx-=z*(P=m[S]),T.vy-=M*P,A.vx+=z*(P=1-P),A.vy+=M*P}function j(){if(d){var k,N=d.length,w=e.length,S=new Map(d.map((A,T)=>[t(A,T,d),A])),R;for(k=0,f=new Array(N);k<w;++k)R=e[k],R.index=k,typeof R.source!="object"&&(R.source=Mk(S,R.source)),typeof R.target!="object"&&(R.target=Mk(S,R.target)),f[R.source.index]=(f[R.source.index]||0)+1,f[R.target.index]=(f[R.target.index]||0)+1;for(k=0,m=new Array(w);k<w;++k)R=e[k],m[k]=f[R.source.index]/(f[R.source.index]+f[R.target.index]);o=new Array(w),E(),c=new Array(w),y()}}function E(){if(d)for(var k=0,N=e.length;k<N;++k)o[k]=+a(e[k],k,e)}function y(){if(d)for(var k=0,N=e.length;k<N;++k)c[k]=+l(e[k],k,e)}return _.initialize=function(k,N){d=k,g=N,j()},_.links=function(k){return arguments.length?(e=k,j(),_):e},_.id=function(k){return arguments.length?(t=k,_):t},_.iterations=function(k){return arguments.length?(h=+k,_):h},_.strength=function(k){return arguments.length?(a=typeof k=="function"?k:es(+k),E(),_):a},_.distance=function(k){return arguments.length?(l=typeof k=="function"?k:es(+k),y(),_):l},_}var VL={value:()=>{}};function VN(){for(var e=0,t=arguments.length,a={},o;e<t;++e){if(!(o=arguments[e]+"")||o in a||/[\s.]/.test(o))throw new Error("illegal type: "+o);a[o]=[]}return new af(a)}function af(e){this._=e}function FL(e,t){return e.trim().split(/^|\s+/).map(function(a){var o="",l=a.indexOf(".");if(l>=0&&(o=a.slice(l+1),a=a.slice(0,l)),a&&!t.hasOwnProperty(a))throw new Error("unknown type: "+a);return{type:a,name:o}})}af.prototype=VN.prototype={constructor:af,on:function(e,t){var a=this._,o=FL(e+"",a),l,c=-1,d=o.length;if(arguments.length<2){for(;++c<d;)if((l=(e=o[c]).type)&&(l=GL(a[l],e.name)))return l;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++c<d;)if(l=(e=o[c]).type)a[l]=zk(a[l],e.name,t);else if(t==null)for(l in a)a[l]=zk(a[l],e.name,null);return this},copy:function(){var e={},t=this._;for(var a in t)e[a]=t[a].slice();return new af(e)},call:function(e,t){if((l=arguments.length-2)>0)for(var a=new Array(l),o=0,l,c;o<l;++o)a[o]=arguments[o+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(c=this._[e],o=0,l=c.length;o<l;++o)c[o].value.apply(t,a)},apply:function(e,t,a){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var o=this._[e],l=0,c=o.length;l<c;++l)o[l].value.apply(t,a)}};function GL(e,t){for(var a=0,o=e.length,l;a<o;++a)if((l=e[a]).name===t)return l.value}function zk(e,t,a){for(var o=0,l=e.length;o<l;++o)if(e[o].name===t){e[o]=VL,e=e.slice(0,o).concat(e.slice(o+1));break}return a!=null&&e.push({name:t,value:a}),e}var oi=0,wc=0,gc=0,FN=1e3,Mf,Sc,zf=0,Lo=0,Sp=0,Vc=typeof performance=="object"&&performance.now?performance:Date,GN=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function YN(){return Lo||(GN(YL),Lo=Vc.now()+Sp)}function YL(){Lo=0}function Hx(){this._call=this._time=this._next=null}Hx.prototype=KN.prototype={constructor:Hx,restart:function(e,t,a){if(typeof e!="function")throw new TypeError("callback is not a function");a=(a==null?YN():+a)+(t==null?0:+t),!this._next&&Sc!==this&&(Sc?Sc._next=this:Mf=this,Sc=this),this._call=e,this._time=a,Vx()},stop:function(){this._call&&(this._call=null,this._time=1/0,Vx())}};function KN(e,t,a){var o=new Hx;return o.restart(e,t,a),o}function KL(){YN(),++oi;for(var e=Mf,t;e;)(t=Lo-e._time)>=0&&e._call.call(void 0,t),e=e._next;--oi}function Ok(){Lo=(zf=Vc.now())+Sp,oi=wc=0;try{KL()}finally{oi=0,QL(),Lo=0}}function XL(){var e=Vc.now(),t=e-zf;t>FN&&(Sp-=t,zf=e)}function QL(){for(var e,t=Mf,a,o=1/0;t;)t._call?(o>t._time&&(o=t._time),e=t,t=t._next):(a=t._next,t._next=null,t=e?e._next=a:Mf=a);Sc=e,Vx(o)}function Vx(e){if(!oi){wc&&(wc=clearTimeout(wc));var t=e-Lo;t>24?(e<1/0&&(wc=setTimeout(Ok,e-Vc.now()-Sp)),gc&&(gc=clearInterval(gc))):(gc||(zf=Vc.now(),gc=setInterval(XL,FN)),oi=1,GN(Ok))}}const WL=1664525,ZL=1013904223,Dk=4294967296;function JL(){let e=1;return()=>(e=(WL*e+ZL)%Dk)/Dk}function e8(e){return e.x}function t8(e){return e.y}var n8=10,s8=Math.PI*(3-Math.sqrt(5));function a8(e){var t,a=1,o=.001,l=1-Math.pow(o,1/300),c=0,d=.6,f=new Map,m=KN(b),g=VN("tick","end"),h=JL();e==null&&(e=[]);function b(){_(),g.call("tick",t),a<o&&(m.stop(),g.call("end",t))}function _(y){var k,N=e.length,w;y===void 0&&(y=1);for(var S=0;S<y;++S)for(a+=(c-a)*l,f.forEach(function(R){R(a)}),k=0;k<N;++k)w=e[k],w.fx==null?w.x+=w.vx*=d:(w.x=w.fx,w.vx=0),w.fy==null?w.y+=w.vy*=d:(w.y=w.fy,w.vy=0);return t}function j(){for(var y=0,k=e.length,N;y<k;++y){if(N=e[y],N.index=y,N.fx!=null&&(N.x=N.fx),N.fy!=null&&(N.y=N.fy),isNaN(N.x)||isNaN(N.y)){var w=n8*Math.sqrt(.5+y),S=y*s8;N.x=w*Math.cos(S),N.y=w*Math.sin(S)}(isNaN(N.vx)||isNaN(N.vy))&&(N.vx=N.vy=0)}}function E(y){return y.initialize&&y.initialize(e,h),y}return j(),t={tick:_,restart:function(){return m.restart(b),t},stop:function(){return m.stop(),t},nodes:function(y){return arguments.length?(e=y,j(),f.forEach(E),t):e},alpha:function(y){return arguments.length?(a=+y,t):a},alphaMin:function(y){return arguments.length?(o=+y,t):o},alphaDecay:function(y){return arguments.length?(l=+y,t):+l},alphaTarget:function(y){return arguments.length?(c=+y,t):c},velocityDecay:function(y){return arguments.length?(d=1-y,t):1-d},randomSource:function(y){return arguments.length?(h=y,f.forEach(E),t):h},force:function(y,k){return arguments.length>1?(k==null?f.delete(y):f.set(y,E(k)),t):f.get(y)},find:function(y,k,N){var w=0,S=e.length,R,A,T,z,M;for(N==null?N=1/0:N*=N,w=0;w<S;++w)z=e[w],R=y-z.x,A=k-z.y,T=R*R+A*A,T<N&&(M=z,N=T);return M},on:function(y,k){return arguments.length>1?(g.on(y,k),t):g.on(y)}}}function r8(){var e,t,a,o,l=es(-30),c,d=1,f=1/0,m=.81;function g(j){var E,y=e.length,k=$_(e,e8,t8).visitAfter(b);for(o=j,E=0;E<y;++E)t=e[E],k.visit(_)}function h(){if(e){var j,E=e.length,y;for(c=new Array(E),j=0;j<E;++j)y=e[j],c[y.index]=+l(y,j,e)}}function b(j){var E=0,y,k,N=0,w,S,R;if(j.length){for(w=S=R=0;R<4;++R)(y=j[R])&&(k=Math.abs(y.value))&&(E+=y.value,N+=k,w+=k*y.x,S+=k*y.y);j.x=w/N,j.y=S/N}else{y=j,y.x=y.data.x,y.y=y.data.y;do E+=c[y.data.index];while(y=y.next)}j.value=E}function _(j,E,y,k){if(!j.value)return!0;var N=j.x-t.x,w=j.y-t.y,S=k-E,R=N*N+w*w;if(S*S/m<R)return R<f&&(N===0&&(N=qr(a),R+=N*N),w===0&&(w=qr(a),R+=w*w),R<d&&(R=Math.sqrt(d*R)),t.vx+=N*j.value*o/R,t.vy+=w*j.value*o/R),!0;if(j.length||R>=f)return;(j.data!==t||j.next)&&(N===0&&(N=qr(a),R+=N*N),w===0&&(w=qr(a),R+=w*w),R<d&&(R=Math.sqrt(d*R)));do j.data!==t&&(S=c[j.data.index]*o/R,t.vx+=N*S,t.vy+=w*S);while(j=j.next)}return g.initialize=function(j,E){e=j,a=E,h()},g.strength=function(j){return arguments.length?(l=typeof j=="function"?j:es(+j),h(),g):l},g.distanceMin=function(j){return arguments.length?(d=j*j,g):Math.sqrt(d)},g.distanceMax=function(j){return arguments.length?(f=j*j,g):Math.sqrt(f)},g.theta=function(j){return arguments.length?(m=j*j,g):Math.sqrt(m)},g}function o8(e){var t=es(.1),a,o,l;typeof e!="function"&&(e=es(e==null?0:+e));function c(f){for(var m=0,g=a.length,h;m<g;++m)h=a[m],h.vx+=(l[m]-h.x)*o[m]*f}function d(){if(a){var f,m=a.length;for(o=new Array(m),l=new Array(m),f=0;f<m;++f)o[f]=isNaN(l[f]=+e(a[f],f,a))?0:+t(a[f],f,a)}}return c.initialize=function(f){a=f,d()},c.strength=function(f){return arguments.length?(t=typeof f=="function"?f:es(+f),d(),c):t},c.x=function(f){return arguments.length?(e=typeof f=="function"?f:es(+f),d(),c):e},c}function l8(e){var t=es(.1),a,o,l;typeof e!="function"&&(e=es(e==null?0:+e));function c(f){for(var m=0,g=a.length,h;m<g;++m)h=a[m],h.vy+=(l[m]-h.y)*o[m]*f}function d(){if(a){var f,m=a.length;for(o=new Array(m),l=new Array(m),f=0;f<m;++f)o[f]=isNaN(l[f]=+e(a[f],f,a))?0:+t(a[f],f,a)}}return c.initialize=function(f){a=f,d()},c.strength=function(f){return arguments.length?(t=typeof f=="function"?f:es(+f),d(),c):t},c.y=function(f){return arguments.length?(e=typeof f=="function"?f:es(+f),d(),c):e},c}const $s={agent:"#a78bfa",memory:"#38bdf8",thread:"#34d399",task:"#fbbf24",routine:"#f472b6",agentlink:"#c084fc",hub:"#94a3b8"};function Pk(e){return{agent:u("agents_ui.kind_agent"),memory:u("agents_ui.kind_memory"),thread:u("agents_ui.kind_thread"),task:u("agents_ui.kind_task"),routine:u("agents_ui.kind_routine"),agentlink:u("agents_ui.kind_hierarchy")}[e]??e}const Lk={core:24,hub:12,leaf:6},Lr=e=>e.role??"leaf",Ik=(e,t,a)=>Math.max(t,Math.min(a,e)),Bk=e=>{const t=new Map;for(const a of e)t.set(a.id,a);return[...t.values()]},i8=(e,t=26)=>e.length>t?`${e.slice(0,t)}…`:e;function XN({nodes:e,edges:t,height:a=520,onNodeClick:o,toolbar:l}){const d=Math.round(1e3*a/760),f=x.useRef(null),m=x.useRef(null),g=x.useRef(null),h=x.useRef([]),b=x.useRef([]),_=x.useRef(null),j=x.useRef(null),E=x.useRef(null),y=x.useRef(!1),k=x.useRef({tx:0,ty:0,k:1}),N=x.useRef(()=>{}),[,w]=x.useState(0),[S,R]=x.useState(null),[A,T]=x.useState(!1),z=1e3/2,M=d/2,L=()=>w(Y=>Y+1),P=e.length>44;x.useEffect(()=>{const Y=Math.min(1e3,d)*.3,oe=e.filter(Te=>Lr(Te)==="hub"),ve=new Map;oe.forEach((Te,Ne)=>ve.set(Te.id,Ne/Math.max(1,oe.length)*Math.PI*2-Math.PI/2));const le=e.map((Te,Ne)=>{const Me=Lr(Te);if(Me==="core")return{...Te,x:z,y:M,fx:z,fy:M};const De=ve.get(Te.id)??Ne/Math.max(1,e.length)*Math.PI*2,Ue=Me==="hub"?Y:Y*1.7;return{...Te,x:z+Math.cos(De)*Ue,y:M+Math.sin(De)*Ue}}),xe=new Map(le.map(Te=>[Te.id,Te])),ke=t.map(Te=>({source:xe.get(Te.source),target:xe.get(Te.target)})).filter(Te=>!!Te.source&&!!Te.target);h.current=le,b.current=ke,L();const Re=Te=>{const Ne=Lr(Te.source),Me=Lr(Te.target);return Ne==="core"||Me==="core"?170:Ne==="hub"&&Me==="hub"?130:58},Ae=Te=>{const Ne=Lr(Te);return Ne==="core"?-700:Ne==="hub"?-360:-90},Ie=a8(le).force("link",HL(ke).distance(Re).strength(.5)).force("charge",r8().strength(Ae)).force("center",jL(z,M).strength(.03)).force("x",o8(z).strength(.02)).force("y",l8(M).strength(.02)).force("collide",UL(Te=>Lk[Lr(Te)]+8)).alphaDecay(.025).on("tick",L);g.current=Ie;const Oe=setTimeout(()=>N.current(),1400);return()=>{clearTimeout(Oe),Ie.stop()}},[e,t,a]);const B=(Y,oe)=>{const ve=m.current.getBoundingClientRect();return{x:(Y-ve.left)/ve.width*1e3,y:(oe-ve.top)/ve.height*d}},D=(Y,oe,ve)=>{const le=k.current,xe=Ik(le.k*ve,.25,8);k.current={k:xe,tx:Y-(Y-le.tx)*(xe/le.k),ty:oe-(oe-le.ty)*(xe/le.k)},L()};N.current=()=>{const Y=h.current.filter(Ne=>Ne.x!=null&&Ne.y!=null);if(!Y.length)return;let oe=1/0,ve=1/0,le=-1/0,xe=-1/0;for(const Ne of Y)oe=Math.min(oe,Ne.x),ve=Math.min(ve,Ne.y),le=Math.max(le,Ne.x),xe=Math.max(xe,Ne.y);const ke=60,Re=Math.max(1,le-oe),Ae=Math.max(1,xe-ve),Ie=Ik(Math.min((1e3-ke*2)/Re,(d-ke*2)/Ae),.25,2.5),Oe=(oe+le)/2,Te=(ve+xe)/2;k.current={k:Ie,tx:1e3/2-Oe*Ie,ty:d/2-Te*Ie},L()},x.useEffect(()=>{const Y=m.current;if(!Y)return;const oe=ve=>{ve.preventDefault();const le=B(ve.clientX,ve.clientY);D(le.x,le.y,ve.deltaY>0?.9:1.1)};return Y.addEventListener("wheel",oe,{passive:!1}),()=>Y.removeEventListener("wheel",oe)},[]),x.useEffect(()=>{if(!A)return;const Y=oe=>{oe.key==="Escape"&&T(!1)};return window.addEventListener("keydown",Y),()=>window.removeEventListener("keydown",Y)},[A]);const $=(Y,oe)=>{const ve=B(Y,oe),le=k.current;return{x:(ve.x-le.tx)/le.k,y:(ve.y-le.ty)/le.k}},q=Y=>oe=>{Lr(Y)!=="core"&&(oe.stopPropagation(),_.current=Y,E.current={x:oe.clientX,y:oe.clientY},y.current=!1,oe.target.setPointerCapture?.(oe.pointerId),g.current?.alphaTarget(.3).restart())},G=Y=>{j.current={x:Y.clientX,y:Y.clientY},Y.currentTarget.setPointerCapture?.(Y.pointerId)},U=Y=>{if(_.current){const oe=E.current;oe&&!y.current&&Math.hypot(Y.clientX-oe.x,Y.clientY-oe.y)>4&&(y.current=!0);const ve=$(Y.clientX,Y.clientY);_.current.fx=ve.x,_.current.fy=ve.y;return}if(j.current){const oe=m.current.getBoundingClientRect();k.current.tx+=(Y.clientX-j.current.x)/oe.width*1e3,k.current.ty+=(Y.clientY-j.current.y)/oe.height*d,j.current={x:Y.clientX,y:Y.clientY},L()}},V=()=>{const Y=_.current;Y&&(Y.fx=null,Y.fy=null),_.current=null,j.current=null,g.current?.alphaTarget(0)},X=Y=>()=>{y.current||ee(Y)},Q=h.current,W=b.current,I=k.current,K=[...new Set(e.map(Y=>Y.kind))].filter(Y=>Y!=="agent"&&Y!=="hub"),ee=Y=>{R(Y),o?.(Y)},F=S?Bk(W.filter(Y=>Y.target.id===S.id).map(Y=>Y.source)):[],ne=S?Bk(W.filter(Y=>Y.source.id===S.id).map(Y=>Y.target)):[],Z=S?.detail&&S.detail.trim()!==S.label.trim()?S.detail:null,fe=({onClick:Y,title:oe,children:ve})=>n.jsx("button",{type:"button",title:oe,onClick:Y,className:"grid size-7 place-items-center rounded-md border border-border bg-card/80 text-muted-fg backdrop-blur hover:text-foreground",children:ve});return n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{ref:f,className:A?"fixed inset-0 z-[60] flex flex-col gap-3 bg-background p-4":"relative",children:[n.jsxs("div",{className:"relative min-h-0 flex-1 overflow-hidden rounded-xl border border-border bg-gradient-to-b from-background to-muted/20",children:[n.jsxs("div",{className:"absolute right-2 top-2 z-10 flex items-center gap-1.5",children:[l,n.jsx(fe,{onClick:()=>D(z,M,1.2),title:u("agents_ui.brain_zoom_in"),children:n.jsx(Dt,{size:14})}),n.jsx(fe,{onClick:()=>D(z,M,.83),title:u("agents_ui.brain_zoom_out"),children:n.jsx(aM,{size:14})}),n.jsx(fe,{onClick:()=>N.current(),title:u("agents_ui.brain_fit"),children:n.jsx(VA,{size:14})}),n.jsx(fe,{onClick:()=>T(Y=>!Y),title:u(A?"agents_ui.brain_exit_fs":"agents_ui.brain_fullscreen"),children:A?n.jsx(sM,{size:14}):n.jsx(nM,{size:14})})]}),n.jsxs("svg",{ref:m,viewBox:`0 0 1000 ${d}`,preserveAspectRatio:"xMidYMid meet",style:A?{height:"100%",width:"100%"}:{height:a},className:"w-full touch-none select-none",onPointerMove:U,onPointerUp:V,onPointerLeave:V,children:[n.jsxs("defs",{children:[n.jsxs("filter",{id:"brain-glow",x:"-80%",y:"-80%",width:"260%",height:"260%",children:[n.jsx("feGaussianBlur",{stdDeviation:"3",result:"blur"}),n.jsxs("feMerge",{children:[n.jsx("feMergeNode",{in:"blur"}),n.jsx("feMergeNode",{in:"SourceGraphic"})]})]}),n.jsxs("radialGradient",{id:"brain-core",cx:"50%",cy:"50%",r:"50%",children:[n.jsx("stop",{offset:"0%",stopColor:$s.agent,stopOpacity:"0.9"}),n.jsx("stop",{offset:"55%",stopColor:$s.agent,stopOpacity:"0.35"}),n.jsx("stop",{offset:"100%",stopColor:$s.agent,stopOpacity:"0"})]}),n.jsxs("radialGradient",{id:"brain-bg",cx:"50%",cy:"50%",r:"60%",children:[n.jsx("stop",{offset:"0%",stopColor:$s.agent,stopOpacity:"0.10"}),n.jsx("stop",{offset:"100%",stopColor:$s.agent,stopOpacity:"0"})]})]}),n.jsx("rect",{x:0,y:0,width:1e3,height:d,fill:"url(#brain-bg)",onPointerDown:G,className:"cursor-grab active:cursor-grabbing"}),n.jsxs("g",{transform:`translate(${I.tx},${I.ty}) scale(${I.k})`,children:[W.map((Y,oe)=>{const ve=$s[Y.target.kind==="hub"?Y.source.kind:Y.target.kind],le=1.4+oe%5*.35;return n.jsxs("g",{children:[n.jsx("line",{x1:Y.source.x,y1:Y.source.y,x2:Y.target.x,y2:Y.target.y,stroke:ve,strokeOpacity:.16,strokeWidth:1.4}),n.jsx("line",{x1:Y.target.x,y1:Y.target.y,x2:Y.source.x,y2:Y.source.y,stroke:ve,strokeOpacity:.5,strokeWidth:2,strokeLinecap:"round",strokeDasharray:"1 14",children:n.jsx("animate",{attributeName:"stroke-dashoffset",values:"15;0",dur:`${le}s`,repeatCount:"indefinite"})})]},oe)}),Q.map((Y,oe)=>{const ve=Lr(Y),le=$s[Y.kind];if(ve==="core"){const Te=Y.emoji&&Y.emoji.trim()||Y.label.slice(0,2).toUpperCase();return n.jsxs("g",{transform:`translate(${Y.x},${Y.y})`,children:[n.jsxs("circle",{r:54,fill:"url(#brain-core)",children:[n.jsx("animate",{attributeName:"r",values:"50;58;50",dur:"4s",repeatCount:"indefinite"}),n.jsx("animate",{attributeName:"opacity",values:"0.85;1;0.85",dur:"4s",repeatCount:"indefinite"})]}),n.jsxs("circle",{r:26,fill:"none",stroke:$s.agent,strokeWidth:1.5,opacity:.5,children:[n.jsx("animate",{attributeName:"r",values:"26;48",dur:"3.2s",repeatCount:"indefinite"}),n.jsx("animate",{attributeName:"opacity",values:"0.5;0",dur:"3.2s",repeatCount:"indefinite"})]}),n.jsx("circle",{r:24,fill:$s.agent,filter:"url(#brain-glow)"}),n.jsx("circle",{r:24,fill:"none",stroke:"#ffffff",strokeOpacity:.35,strokeWidth:1}),n.jsx("text",{textAnchor:"middle",dominantBaseline:"central",fontSize:Te.length<=2?20:11,fontWeight:700,fill:"#1a1030",children:Te.length>8?Te.slice(0,8):Te})]},Y.id)}const xe=S?.id===Y.id,ke=Lk[ve]+(xe?3:0),Re=2.4+oe%6*.4,Ae=`${oe%6*.3}s`,Ie=ve==="hub",Oe=Ie||xe||!P;return n.jsxs("g",{transform:`translate(${Y.x},${Y.y})`,className:"cursor-grab active:cursor-grabbing",onPointerDown:q(Y),onClick:X(Y),children:[n.jsxs("circle",{r:ke,fill:le,filter:"url(#brain-glow)",opacity:.3,children:[n.jsx("animate",{attributeName:"r",values:`${ke};${ke+6};${ke}`,dur:`${Re}s`,begin:Ae,repeatCount:"indefinite"}),n.jsx("animate",{attributeName:"opacity",values:"0.32;0.08;0.32",dur:`${Re}s`,begin:Ae,repeatCount:"indefinite"})]}),n.jsx("circle",{r:ke,fill:le,fillOpacity:xe?1:.95,stroke:xe?"#fff":"#ffffff",strokeOpacity:xe?1:.25,strokeWidth:xe?2:1}),Y.emoji&&Ie&&n.jsx("text",{textAnchor:"middle",dominantBaseline:"central",fontSize:11,style:{pointerEvents:"none"},children:Y.emoji}),Oe&&n.jsx("text",{x:ke+4,y:4,fontSize:Ie?11:10,className:Ie?"fill-foreground font-medium":"fill-foreground/80",style:{pointerEvents:"none"},children:Y.label.length>22?`${Y.label.slice(0,22)}…`:Y.label})]},Y.id)})]})]})]}),n.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-[11px] text-muted-fg",children:[K.map(Y=>n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx("span",{className:"size-2 rounded-full",style:{background:$s[Y]}})," ",Pk(Y)]},Y)),n.jsxs("span",{className:"ml-auto",children:[u("agents_ui.brain_pan_hint")," · ",u("agents_ui.nodes_drag_hint",{n:String(e.length)})]})]})]}),S&&n.jsxs("div",{className:"space-y-2.5 rounded-lg border border-border bg-card p-3 text-xs",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("span",{className:"size-2.5 rounded-full",style:{background:$s[S.kind]}}),S.emoji&&n.jsx("span",{className:"text-sm leading-none",children:S.emoji}),n.jsx("span",{className:"text-[13px] font-semibold",children:S.label}),n.jsx("span",{className:"rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-muted-fg",children:Pk(S.kind)}),S.relation&&n.jsxs("span",{className:"text-muted-fg",children:["· ",S.relation]}),n.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[S.slug&&o&&n.jsx("button",{type:"button",onClick:()=>o(S),className:"text-primary hover:underline",children:u("agents_ui.brain_open")}),n.jsx("button",{type:"button",onClick:()=>R(null),className:"text-muted-fg hover:text-foreground",children:"✕"})]})]}),Z&&n.jsx("p",{className:"whitespace-pre-wrap text-muted-fg",children:Z}),F.length>0&&n.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[n.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted-fg/70",children:u("agents_ui.brain_part_of")}),F.map(Y=>n.jsx($k,{node:Y,onClick:()=>R(Y)},Y.id))]}),ne.length>0&&n.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[n.jsxs("span",{className:"text-[10px] uppercase tracking-wide text-muted-fg/70",children:[u("agents_ui.brain_branches")," · ",ne.length]}),ne.map(Y=>n.jsx($k,{node:Y,onClick:()=>R(Y)},Y.id))]})]})]})}function $k({node:e,onClick:t}){return n.jsxs("button",{type:"button",onClick:t,className:"inline-flex max-w-[220px] items-center gap-1 rounded-md border border-border bg-muted/40 px-1.5 py-0.5 text-[11px] hover:border-muted-fg/50 hover:bg-muted",children:[n.jsx("span",{className:"size-1.5 shrink-0 rounded-full",style:{background:$s[e.kind]}}),e.emoji&&n.jsx("span",{className:"leading-none",children:e.emoji}),n.jsx("span",{className:"truncate",children:i8(e.label,28)})]})}function Uk({pid:e}){const t=Pn(),a=Be(`/projects/${e}/tasks?state=open`,()=>Qn.list(e),{refreshInterval:2e4}),o=Be(`/projects/${e}/tasks-summary`,()=>Qn.summary(e),{refreshInterval:2e4}),l=Be(`/projects/${e}/routines`,()=>Br.list(e)),c=Be(`/projects/${e}/agents`,()=>an.list(e)),d=Be(`/projects/${e}/mcps`,()=>$r.list(e)),f=Be(`/projects/${e}/artifacts`,()=>Ws.list(e)),m=c.data??[],g=m.filter(y=>y.is_master||y.type==="orchestrator"),h=m.filter(y=>!(y.is_master||y.type==="orchestrator")),b=c8(m),_=b.some(y=>y.area),j=(l.data??[]).filter(y=>y.enabled).length,E=[...a.data??[]].sort((y,k)=>(k.created_at||"").localeCompare(y.created_at||"")).slice(0,6);return n.jsxs("div",{className:"space-y-6",children:[n.jsxs("div",{className:"grid grid-cols-2 gap-4 md:grid-cols-4",children:[n.jsx(So,{title:u("project.overview.agents"),value:m.length,href:`/p/${e}/agents`,icon:rn}),n.jsx(So,{title:u("project.overview.tasks_open"),value:o.data?.open??a.data?.length??"…",href:`/p/${e}/tasks`,icon:pi}),n.jsx(So,{title:u("project.overview.routines_active"),value:j,href:`/p/${e}/routines`,icon:Mo}),n.jsx(So,{title:u("project.overview.artifacts"),value:f.data?.length??"…",href:`/p/${e}/artifacts`,icon:gb})]}),o.data&&n.jsx("div",{className:"flex flex-wrap gap-2",children:qN.map(y=>n.jsxs(df,{to:`/p/${e}/tasks`,className:"flex items-center gap-1.5 rounded-lg border border-border bg-card px-3 py-1.5 text-xs hover:bg-accent/40",children:[n.jsx(Af,{status:y,className:"size-3.5"}),n.jsx("span",{className:"capitalize text-muted-foreground",children:I_(y)}),n.jsx("span",{className:"font-semibold",children:o.data.status?.[y]??0})]},y))}),n.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[n.jsx(Ve,{title:u("project.overview.roster"),className:"!p-4",children:m.length===0?n.jsx("p",{className:"text-sm text-muted-fg",children:u("project.overview.no_agents")}):_?n.jsx("div",{className:"space-y-3",children:b.map(y=>n.jsx(bh,{label:y.area||u("agents_ui.uncategorized"),icon:db,agents:y.agents,pid:e,navigate:t},y.area??"__none"))}):n.jsxs("div",{className:"space-y-3",children:[g.length>0&&n.jsx(bh,{label:u("project.overview.orchestrators"),icon:va,agents:g,pid:e,navigate:t}),h.length>0&&n.jsx(bh,{label:u("project.overview.specialists"),icon:rn,agents:h,pid:e,navigate:t})]})}),n.jsx(Ve,{title:u("project.overview.recent_tasks"),className:"!p-4",action:n.jsx(df,{to:`/p/${e}/tasks`,className:"text-xs text-sky-500 hover:text-sky-400",children:u("common.view_all")}),children:E.length===0?n.jsxs("p",{className:"flex items-center gap-2 text-sm text-muted-fg",children:[n.jsx(qf,{className:"size-4"}),u("project.overview.no_activity")]}):n.jsx("ul",{className:"space-y-1.5",children:E.map(y=>n.jsx("li",{children:n.jsxs("button",{type:"button",onClick:()=>t(`/p/${e}/tasks?task=${y.id}`),className:"flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left hover:bg-accent/40",children:[n.jsx(Af,{status:Tf(y),className:"size-3.5 shrink-0"}),n.jsx("span",{className:"min-w-0 flex-1 truncate text-sm",children:y.title}),n.jsx(B_,{status:Tf(y)})]})},y.id))})})]}),n.jsxs("div",{className:"grid grid-cols-2 gap-4 md:grid-cols-3",children:[n.jsx(So,{title:u("project.overview.chat"),value:u("project.overview.chat_value"),href:`/p/${e}/chat`,icon:Gf}),n.jsx(So,{title:u("project.overview.mcps"),value:d.data?.length??"…",href:`/p/${e}/mcps`,icon:Yf}),n.jsx(So,{title:u("project.overview.routines"),value:l.data?.length??"…",href:`/p/${e}/routines`,icon:Mo})]}),m.length>0&&n.jsx(Ve,{title:u("project.overview.brain_title"),description:u("project.overview.brain_desc"),className:"!p-4",children:n.jsx(d8,{pid:e,agents:m,routines:l.data??[],navigate:t})})]})}function c8(e){const t=new Map;for(const a of e){const o=a.area||null;t.has(o)||t.set(o,[]),t.get(o).push(a)}return[...t.entries()].sort(([a],[o])=>a===null?1:o===null?-1:a.localeCompare(o)).map(([a,o])=>({area:a,agents:o}))}function u8(e){return e.split(`
|
|
788
|
-
`).map(t=>t.replace(/^[-*#>\s]+/,"").trim()).filter(t=>t.length>2&&!t.startsWith("```")).slice(0,5)}function d8({pid:e,agents:t,routines:a,navigate:o}){const[l,c]=x.useState(!1),d=Be(l?`/team-brain/${e}/${t.map(b=>b.slug).join(",")}`:null,async()=>{const b=await Qn.list(e,"all"),_=await Promise.all(t.map(async j=>{const[E,y]=await Promise.all([an.get(e,j.slug).catch(()=>null),Wr.list(e,j.slug).catch(()=>[])]);return[j.slug,{memory:E?.memory||"",threads:(y||[]).slice(0,4).map(k=>({title:k.title||k.filename,id:k.id}))}]}));return{tasks:b,perAgent:Object.fromEntries(_)}}),f=l&&!!d.data,{nodes:m,edges:g}=x.useMemo(()=>{const b=[],_=[],j="__root";b.push({id:j,label:u("project.overview.brain_core"),kind:"agent",role:"core",emoji:"🧠"});const E=new Set(t.map(k=>k.slug)),y=k=>t.some(N=>N.parent===k);for(const k of t){const N=!!k.is_master||k.type==="orchestrator";b.push({id:k.slug,label:k.slug,slug:k.slug,kind:N?"agent":"agentlink",role:f||N||y(k.slug)?"hub":"leaf",emoji:k.emoji||void 0,relation:k.role||u(N?"project.agents.orchestrator":"project.overview.specialists"),detail:k.description||void 0})}for(const k of t){const N=k.parent&&E.has(k.parent)?k.parent:j;_.push({source:N,target:k.slug})}if(f&&d.data){const{tasks:k,perAgent:N}=d.data,w=(S,R,A,T,z)=>{b.push({id:S,label:R,kind:A,detail:z}),_.push({source:T,target:S})};for(const S of t){const R=N[S.slug];u8(R?.memory||"").forEach((A,T)=>w(`${S.slug}:m${T}`,A,"memory",S.slug,A)),(R?.threads||[]).forEach((A,T)=>w(`${S.slug}:th${T}`,A.title,"thread",S.slug)),k.filter(A=>A.agent===S.slug).slice(0,4).forEach((A,T)=>w(`${S.slug}:ts${T}`,A.title,"task",S.slug,A.body||void 0)),a.filter(A=>A.spec?.agent===S.slug).slice(0,2).forEach((A,T)=>w(`${S.slug}:rt${T}`,A.name,"routine",S.slug,`schedule: ${A.schedule}`))}}return{nodes:b,edges:_}},[t,a,f,d.data]),h=n.jsxs("button",{type:"button",onClick:()=>c(b=>!b),className:ge("inline-flex items-center gap-1.5 rounded-md border px-2 py-1 text-[11px] font-medium backdrop-blur transition-colors",l?"border-primary/40 bg-primary/15 text-foreground":"border-border bg-card/80 text-muted-fg hover:text-foreground"),children:[n.jsx(Dc,{className:ge("size-3.5",d.isLoading&&"animate-pulse")}),u(l?"agents_ui.brain_collapse":"agents_ui.brain_expand")]});return n.jsx(XN,{nodes:m,edges:g,height:620,toolbar:h,onNodeClick:b=>{b.slug&&o(`/p/${e}/agents/${b.slug}`)}})}function bh({label:e,icon:t,agents:a,pid:o,navigate:l}){return n.jsxs("div",{children:[n.jsxs("div",{className:"mb-1.5 flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground",children:[n.jsx(t,{className:"size-3.5"}),e," (",a.length,")"]}),n.jsx("div",{className:"flex flex-wrap gap-1.5",children:a.map(c=>n.jsxs("button",{type:"button",onClick:()=>l(`/p/${o}/agents/${c.slug}`),className:ge("inline-flex items-center gap-1.5 rounded-lg border border-border bg-card px-2 py-1 text-xs hover:border-muted-fg/50"),children:[n.jsx("span",{className:"text-sm leading-none",children:c.emoji||"🤖"}),n.jsx("span",{className:"truncate",children:c.slug}),c.role&&n.jsxs("span",{className:"truncate text-[10px] text-muted-fg",children:["· ",c.role]})]},c.slug))})]})}function So({title:e,value:t,href:a,icon:o}){return n.jsxs(df,{to:a,className:"flex items-center gap-3 rounded-xl border border-border bg-card p-4 hover:bg-accent/40",children:[n.jsx("span",{className:"grid size-10 place-items-center rounded-lg bg-muted text-muted-fg",children:n.jsx(o,{size:20})}),n.jsxs("div",{children:[n.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-fg",children:e}),n.jsx("div",{className:"text-2xl font-semibold",children:t})]})]})}function f8(){const e=Pn(),{projects:t,isLoading:a}=iu();return n.jsxs(Ve,{title:u("base.workspaces_title"),description:u("base.workspaces_desc"),action:n.jsxs(re,{size:"sm",variant:"primary",onClick:()=>e("/p/0/workspaces?action=add-project"),children:[n.jsx(Dt,{size:14})," ",u("base.workspaces_new")]}),children:[a&&n.jsx(st,{}),!a&&t.length===0&&n.jsx(ft,{children:u("base.workspaces_empty")}),n.jsx("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3",children:t.map(o=>{const l=String(o.id)==="0",c=l?u("base.title"):o.name||o.path.split("/").pop()||String(o.id);return n.jsxs("button",{type:"button",onClick:()=>e(`/p/${o.id}`),className:"flex cursor-pointer flex-col gap-2 rounded-xl border border-border bg-card p-4 text-left transition-colors hover:border-muted-fg/50",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Q2,{className:"size-4 text-muted-fg"}),n.jsx("span",{className:"truncate text-sm font-semibold",children:c}),n.jsx($e,{tone:l?"success":"info",children:l?u("base.title"):hN(o.kind)})]}),n.jsx("p",{className:"truncate font-mono text-[10px] text-muted-fg",children:o.path})]},o.id)})})]})}function p8(e){const t=x.useRef(!0);t.current&&(t.current=!1,e())}const QN=x.createContext(null);function Na(){const e=x.useContext(QN);if(e===null)throw new Error(gn(60));return e}const m8=(e,t)=>Object.is(e,t);function li(e,t,a){return e==null||t==null?Object.is(e,t):a(e,t)}function rf(e,t,a){return!e||e.length===0?-1:e.findIndex(o=>o===void 0?!1:li(o,t,a))}function g8(e,t,a){return e.filter(o=>!li(t,o,a))}function Fx(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function WN(e){return e!=null&&e.length>0&&typeof e[0]=="object"&&e[0]!=null&&"items"in e[0]}function h8(e){if(!Array.isArray(e))return e!=null&&"null"in e;const t=e;if(WN(t)){for(const a of t)for(const o of a.items)if(o&&o.value==null&&o.label!=null)return!0;return!1}for(const a of t)if(a&&a.value==null&&a.label!=null)return!0;return!1}function ZN(e,t){if(t&&e!=null)return t(e)??"";if(e&&typeof e=="object"){if("label"in e&&e.label!=null)return String(e.label);if("value"in e)return String(e.value)}return Fx(e)}function Ll(e,t){return t&&e!=null?t(e)??"":e&&typeof e=="object"&&"value"in e&&"label"in e?Fx(e.value):Fx(e)}function JN(e,t,a){function o(){return ZN(e,a)}if(a&&e!=null)return a(e);if(e&&typeof e=="object"&&"label"in e&&e.label!=null)return e.label;if(t&&!Array.isArray(t))return t[e]??o();if(Array.isArray(t)){const l=t,c=WN(l)?l.flatMap(d=>d.items):l;if(e==null||typeof e!="object"){const d=c.find(f=>f.value===e);return d&&d.label!=null?d.label:o()}if("value"in e){const d=c.find(f=>f&&f.value===e.value);if(d&&d.label!=null)return d.label}}return o()}function x8(e,t,a){return e.reduce((o,l,c)=>(c>0&&o.push(", "),o.push(n.jsx(x.Fragment,{children:JN(l,t,a)},c)),o),[])}const nt={id:e=>e.id,labelId:e=>e.labelId,modal:e=>e.modal,items:e=>e.items,itemToStringLabel:e=>e.itemToStringLabel,isItemEqualToValue:e=>e.isItemEqualToValue,value:e=>e.value,hasSelectedValue:e=>{const{value:t,multiple:a,itemToStringValue:o}=e;return t==null?!1:a&&Array.isArray(t)?t.length>0:Ll(t,o)!==""},hasNullItemLabel:(e,t)=>t?h8(e.items):!1,open:e=>e.open,mounted:e=>e.mounted,forceMount:e=>e.forceMount,transitionStatus:e=>e.transitionStatus,openMethod:e=>e.openMethod,activeIndex:e=>e.activeIndex,selectedIndex:e=>e.selectedIndex,isActive:(e,t)=>e.activeIndex===t,isSelected:(e,t)=>{const a=e.isItemEqualToValue,o=e.value;return e.multiple?Array.isArray(o)&&o.some(l=>li(t,l,a)):li(t,o,a)},isSelectedByFocus:(e,t)=>e.selectedIndex===t,popupProps:e=>e.popupProps,triggerProps:e=>e.triggerProps,triggerElement:e=>e.triggerElement,positionerElement:e=>e.positionerElement,listElement:e=>e.listElement,popupSide:e=>e.popupSide,scrollUpArrowVisible:e=>e.scrollUpArrowVisible,scrollDownArrowVisible:e=>e.scrollDownArrowVisible,hasScrollArrows:e=>e.hasScrollArrows};function b8(e,t,a=(o,l)=>o===l){return e.length===t.length&&e.every((o,l)=>a(o,t[l]))}function Cc(e,t=Number.MIN_SAFE_INTEGER,a=Number.MAX_SAFE_INTEGER){return Math.max(t,Math.min(e,a))}const Zs=1;function q_(e,t){return Math.max(0,e-t)}function Of(e,t){if(t<=0)return 0;const a=Cc(e,0,t),o=a,l=t-a,c=o<=Zs,d=l<=Zs;return c&&d?o<=l?0:t:c?0:d?t:a}function _8(e){const{id:t,value:a,defaultValue:o=null,onValueChange:l,open:c,defaultOpen:d=!1,onOpenChange:f,name:m,form:g,autoComplete:h,disabled:b=!1,readOnly:_=!1,required:j=!1,modal:E=!0,actionsRef:y,inputRef:k,onOpenChangeComplete:N,items:w,multiple:S=!1,itemToStringLabel:R,itemToStringValue:A,isItemEqualToValue:T=m8,highlightItemOnHover:z=!0,children:M}=e,{clearErrors:L}=z_(),{setDirty:P,setTouched:B,setFocused:D,validityData:$,setFilled:q,name:G,disabled:U,validation:V,validationMode:X}=du(),Q=kp({id:t}),W=U||b,I=G??m,[K,ee]=ni({controlled:a,default:S?o??ja:o,name:"Select",state:"value"}),[F,ne]=ni({controlled:c,default:d,name:"Select",state:"open"}),Z=x.useRef([]),fe=x.useRef([]),Y=x.useRef(null),oe=x.useRef(null),ve=x.useRef(0),le=x.useRef(null),xe=x.useRef([]),ke=x.useRef(!1),Re=x.useRef(null),Ae=x.useRef(null),Ie=x.useRef({allowSelectedMouseUp:!1,allowUnselectedMouseUp:!1,dragY:0}),Oe=x.useRef(!1),{mounted:Te,setMounted:Ne,transitionStatus:Me}=hi(F),{openMethod:De,triggerProps:Ue}=WC(F),Xe=Hn(()=>new nu({id:Q,labelId:void 0,modal:E,multiple:S,itemToStringLabel:R,itemToStringValue:A,isItemEqualToValue:T,value:K,open:F,mounted:Te,transitionStatus:Me,items:w,forceMount:!1,openMethod:null,activeIndex:null,selectedIndex:null,popupProps:{},triggerProps:{},triggerElement:null,positionerElement:null,listElement:null,popupSide:null,scrollUpArrowVisible:!1,scrollDownArrowVisible:!1,hasScrollArrows:!1})).current,me=tt(Xe,nt.activeIndex),de=tt(Xe,nt.selectedIndex),Le=tt(Xe,nt.triggerElement),ye=tt(Xe,nt.positionerElement),Ce=_6(De),Qe=De??Ce,Ge=x.useMemo(()=>S?"":Ll(K,A),[S,K,A]),lt=x.useMemo(()=>S&&Array.isArray(K)?K.map(ht=>Ll(ht,A)):Ll(K,A),[S,K,A]),Tt=mn(Le),_t=He(()=>lt);O_(Tt,Q,K,_t,!W,m);const Ct=x.useRef(K),je=S?Array.isArray(K)&&K.length>0:K!=null&&Ge!=="";Pe(()=>{q(je)},[je,q]),Pe(function(){let $t=K,Ln=!1;if(S){const An=Array.isArray(K)?K:[];Ln=An.length===0,$t=An[An.length-1]}const rs=Ln?-1:rf(xe.current,$t,T),xs=rs===-1?null:rs;xs===null&&(Ae.current=null),!F&&Xe.set("selectedIndex",xs)},[S,F,K,T,Xe]);function ze(ht){const $t=$.initialValue;return Array.isArray(ht)&&Array.isArray($t)?!b8(ht,$t,(Ln,rs)=>li(Ln,rs,T)):ht!==$t}v_(K,()=>{L(I),P(ze(K)),V.change(K)});const Ye=He((ht,$t)=>{f?.(ht,$t),!$t.isCanceled&&(ne(ht),!ht&&($t.reason===zo||$t.reason===rp)&&(B(!0),D(!1),X==="onBlur"&&V.commit(K)))}),We=He(()=>{Ne(!1),Xe.update({activeIndex:null,openMethod:null,scrollUpArrowVisible:!1,scrollDownArrowVisible:!1}),N?.(!1)});Ca({enabled:!y,open:F,ref:Y,onComplete(){F||We()}}),x.useImperativeHandle(y,()=>({unmount:We}),[We]);const dt=He((ht,$t)=>{l?.(ht,$t),!$t.isCanceled&&ee(ht)}),Rt=He(ht=>{const $t=q_(ht.scrollHeight,ht.clientHeight),Ln=Of(ht.scrollTop,$t),rs=Ln>0,xs=Ln<$t;Xe.set("scrollUpArrowVisible",rs),Xe.set("scrollDownArrowVisible",xs)}),Qt=DO({open:F,onOpenChange:Ye,elements:{reference:Le,floating:ye}}),ot=tC(Qt,{enabled:!_&&!W,event:"mousedown"}),Pt=ip(Qt),on=kC(Qt,{enabled:!_&&!W,listRef:Z,activeIndex:me,selectedIndex:de,disabledIndices:ja,onNavigate(ht){ht===null&&!F||Xe.set("activeIndex",ht)},focusItemOnHover:z}),Yt=wC(Qt,{enabled:!_&&!W&&(F||!S),listRef:fe,activeIndex:me,selectedIndex:de,disabledIndices:ht=>tN(Z.current[ht]),onMatch(ht){F?Xe.set("activeIndex",ht):dt(xe.current[ht],rt(ka))},onTyping(ht){ke.current=ht}}),Fn=x.useMemo(()=>Ss(Yt.reference,on.reference,Pt.reference,ot.reference,Ue),[ot.reference,Yt.reference,on.reference,Pt.reference,Ue]),Tn=x.useMemo(()=>Ss(dp,Yt.floating,on.floating,Pt.floating),[Yt.floating,on.floating,Pt.floating]),as=on.item??sn;p8(()=>{Xe.update({popupProps:Tn,triggerProps:Fn})}),Xe.useSyncedValues({id:Q,modal:E,multiple:S,value:K,open:F,mounted:Te,transitionStatus:Me,popupProps:Tn,triggerProps:Fn,items:w,itemToStringLabel:R,itemToStringValue:A,isItemEqualToValue:T,openMethod:Qe});const dn=x.useMemo(()=>({store:Xe,floatingContext:Qt,required:j,disabled:W,readOnly:_,multiple:S,highlightItemOnHover:z,setValue:dt,setOpen:Ye,listRef:Z,popupRef:Y,scrollHandlerRef:oe,handleScrollArrowVisibility:Rt,scrollArrowsMountedCountRef:ve,itemProps:as,valueRef:le,valuesRef:xe,labelsRef:fe,typingRef:ke,selectionRef:Ie,firstItemTextRef:Re,selectedItemTextRef:Ae,validation:V,onOpenChangeComplete:N,alignItemWithTriggerActiveRef:Oe,initialValueRef:Ct}),[Xe,Qt,j,W,_,S,z,dt,Ye,as,V,N,Rt]),hs=rr(k,V.inputRef),Rs=S?void 0:I,oa=x.useMemo(()=>!S||!Array.isArray(K)||!I?null:K.map(ht=>{const $t=Ll(ht,A);return n.jsx("input",{type:"hidden",form:g,name:I,value:$t,disabled:W},$t)}),[S,K,g,I,A,W]);return n.jsxs(QN.Provider,{value:dn,children:[M,n.jsx("input",{...V.getValidationProps(W,{onFocus(){Xe.state.triggerElement?.focus({focusVisible:!0})},onChange(ht){if(ht.nativeEvent.defaultPrevented||W||_)return;const $t=ht.currentTarget.value,Ln=rt(ka,ht.nativeEvent);function rs(){if(S)return;const xs=$t.toLowerCase();let An=xe.current.findIndex(vn=>Ll(vn,A).toLowerCase()===xs||ZN(vn,R).toLowerCase()===xs);An===-1&&(An=xe.current.findIndex((vn,la)=>{const dr=fe.current[la];return dr!=null&&dr.toLowerCase()===xs}));const Wt=xe.current[An];Wt!=null&&dt(Wt,Ln)}Xe.set("forceMount",!0),queueMicrotask(rs)}}),id:Q&&Rs==null?`${Q}-hidden-input`:void 0,form:g,name:Rs,autoComplete:h,value:Ge,disabled:W,required:j&&!(S&&je),readOnly:_,ref:hs,style:I?NS:Ub,tabIndex:-1,"aria-hidden":!0,suppressHydrationWarning:!0}),oa]})}function v8(e,t){return e??t}const y8=400,j8={...wx,...M_,popupSide:e=>e?{"data-popup-side":e}:null,value:()=>null},k8=x.forwardRef(function(t,a){const{render:o,className:l,id:c,disabled:d=!1,nativeButton:f=!0,style:m,...g}=t,{setTouched:h,setFocused:b,validationMode:_,state:j,disabled:E}=du(),{labelId:y}=jp(),{store:k,setOpen:N,selectionRef:w,validation:S,readOnly:R,required:A,alignItemWithTriggerActiveRef:T,disabled:z}=Na(),M=E||z||d,L=tt(k,nt.open),P=tt(k,nt.mounted),B=tt(k,nt.value),D=tt(k,nt.triggerProps),$=tt(k,nt.positionerElement),q=tt(k,nt.listElement),G=tt(k,nt.popupSide),U=tt(k,nt.id),V=tt(k,nt.labelId),X=tt(k,nt.hasSelectedValue),Q=P&&$?G:null,W=c??U,I=v8(y,V);kp({id:W});const K=mn($),ee=x.useRef(null),{getButtonProps:F,buttonRef:ne}=no({disabled:M,native:f}),Z=k.useStateSetter("triggerElement"),fe=Rn(),Y=Rn(),oe=Rn();x.useEffect(()=>{if(L)return oe.start(y8,()=>{w.current.allowUnselectedMouseUp=!0,w.current.allowSelectedMouseUp=!0}),()=>{oe.clear()};w.current={allowSelectedMouseUp:!1,allowUnselectedMouseUp:!1,dragY:0},Y.clear()},[L,w,Y,oe]);const ve=Ss(D,{id:W,role:"combobox","aria-expanded":L,"aria-haspopup":"listbox","aria-controls":L?q?.id??mf($)?.id:void 0,"aria-labelledby":I,"aria-readonly":R||void 0,"aria-required":A||void 0,tabIndex:M?-1:0,onFocus(ke){b(!0),L&&T.current&&N(!1,rt(ka,ke.nativeEvent)),fe.start(0,()=>{k.set("forceMount",!0)})},onBlur(ke){Ze($,ke.relatedTarget)||(h(!0),b(!1),_==="onBlur"&&S.commit(B))},onMouseDown(ke){if(L)return;const Re=vt(ke.currentTarget);function Ae(Ie){if(!ee.current)return;const Oe=Ie.target;Ze(ee.current,Oe)||Ze(K.current,Oe)||ZC(Ie,ee.current)||N(!1,rt(yS,Ie))}Y.start(0,()=>{Re.addEventListener("mouseup",Ae,{once:!0})})}},g,F),le=S.getValidationProps(M,ve);le.role="combobox";const xe={...j,open:L,disabled:M,value:B,readOnly:R,popupSide:Q,placeholder:!X};return Et("button",t,{ref:[a,ee,ne,Z],state:xe,stateAttributesMapping:j8,props:le})}),w8={value:()=>null},S8=x.forwardRef(function(t,a){const{className:o,render:l,children:c,placeholder:d,style:f,...m}=t,{store:g,valueRef:h}=Na(),b=tt(g,nt.value),_=tt(g,nt.items),j=tt(g,nt.itemToStringLabel),E=tt(g,nt.hasSelectedValue),y=!E&&d!=null&&c==null,k=tt(g,nt.hasNullItemLabel,y),N={value:b,placeholder:!E};let w=null;return typeof c=="function"?w=c(b):c!=null?w=c:y&&!k?w=d:Array.isArray(b)?w=x8(b,_,j):w=JN(b,_,j),Et("span",t,{state:N,ref:[a,h],props:[{children:w},m],stateAttributesMapping:w8})}),C8=x.forwardRef(function(t,a){const{render:o,className:l,style:c,...d}=t,{store:f}=Na(),g={open:tt(f,nt.open)};return Et("span",t,{state:g,ref:a,props:[{"aria-hidden":!0,children:"▼"},d],stateAttributesMapping:CC})}),N8=x.forwardRef(function(t,a){const{store:o}=Na(),l=tt(o,nt.mounted),c=tt(o,nt.forceMount);return l||c?n.jsx(Qb,{ref:a,...t}):null}),eE=x.createContext(void 0);function H_(){const e=x.useContext(eE);if(!e)throw new Error(gn(59));return e}function Df(e,t){e&&Object.assign(e.style,t)}const tE={position:"relative",maxHeight:"100%",overflowX:"hidden",overflowY:"auto"},E8={position:"fixed"},R8=x.forwardRef(function(t,a){const{anchor:o,className:l,render:c,positionMethod:d,side:f,align:m,sideOffset:g,alignOffset:h,collisionBoundary:b="clipping-ancestors",collisionPadding:_,arrowPadding:j,sticky:E,disableAnchorTracking:y,alignItemWithTrigger:k=!0,collisionAvoidance:N=GS,style:w,...S}=t,{store:R,listRef:A,labelsRef:T,alignItemWithTriggerActiveRef:z,selectedItemTextRef:M,valuesRef:L,initialValueRef:P,popupRef:B,setValue:D,floatingContext:$}=Na(),q=tt(R,nt.open),G=tt(R,nt.mounted),U=tt(R,nt.modal),V=tt(R,nt.value),X=tt(R,nt.openMethod),Q=tt(R,nt.positionerElement),W=tt(R,nt.triggerElement),I=tt(R,nt.isItemEqualToValue),K=tt(R,nt.transitionStatus),ee=x.useRef(null),F=x.useRef(null),[ne,Z]=x.useState(k),fe=G&&ne&&X!=="touch";!G&&ne!==k&&Z(k),x.useImperativeHandle(z,()=>fe),YC((fe||U)&&q,X==="touch",Q,W);const Y=f_({anchor:o,floatingRootContext:$,positionMethod:d,mounted:G,side:f,sideOffset:g,align:m,alignOffset:h,arrowPadding:j,collisionBoundary:b,collisionPadding:_,sticky:E,disableAnchorTracking:y??fe,collisionAvoidance:N,keepMounted:!0}),oe=fe?"none":Y.side,ve=fe?E8:Y.positionerStyles,le={open:q,side:oe,align:Y.align,anchorHidden:Y.anchorHidden};Pe(()=>{R.set("popupSide",Y.side)},[R,Y.side]);const xe=R.useStateSetter("positionerElement"),ke=p_(t,le,{styles:ve,transitionStatus:K,props:S,refs:[a,xe],hidden:!G,inert:!q}),Re=x.useRef(0),Ae=He(Oe=>{if(L.current.length===0)return;const Te=Re.current;if(Re.current=Oe.size,Oe.size===Te)return;const Ne=rt(ka);if(Te!==0&&!R.state.multiple&&V!==null&&rf(L.current,V,I)===-1){const De=P.current,Xe=De!=null&&rf(L.current,De,I)!==-1?De:null;D(Xe,Ne),Xe===null&&(R.set("selectedIndex",null),M.current=null)}if(Te!==0&&R.state.multiple&&Array.isArray(V)){const Me=V.filter(De=>rf(L.current,De,I)!==-1);Me.length!==V.length&&(D(Me,Ne),Me.length===0&&(R.set("selectedIndex",null),M.current=null))}if(q&&fe){R.update({scrollUpArrowVisible:!1,scrollDownArrowVisible:!1});const Me={height:""};Df(Q,Me),Df(B.current,Me)}}),Ie=x.useMemo(()=>({...Y,side:oe,alignItemWithTriggerActive:fe,setControlledAlignItemWithTrigger:Z,scrollUpArrowRef:ee,scrollDownArrowRef:F}),[Y,oe,fe,Z]);return n.jsx(bp,{elementsRef:A,labelsRef:T,onMapChange:Ae,children:n.jsxs(eE.Provider,{value:Ie,children:[G&&U&&n.jsx(__,{inert:gp(!q),cutout:W}),ke]})})}),Id="base-ui-disable-scrollbar",Gx={className:Id,getElement(e){return n.jsx("style",{nonce:e,href:Id,precedence:"base-ui:low",children:`.${Id}{scrollbar-width:none}.${Id}::-webkit-scrollbar{display:none}`})}},T8=x.createContext(void 0),A8={disableStyleElements:!1};function M8(){return x.useContext(T8)??A8}const z8={...au,...Ho},O8=x.forwardRef(function(t,a){const{render:o,className:l,style:c,finalFocus:d,...f}=t,{store:m,popupRef:g,onOpenChangeComplete:h,setOpen:b,valueRef:_,firstItemTextRef:j,selectedItemTextRef:E,multiple:y,handleScrollArrowVisibility:k,scrollHandlerRef:N,listRef:w,highlightItemOnHover:S,floatingContext:R}=Na(),{side:A,align:T,alignItemWithTriggerActive:z,isPositioned:M,setControlledAlignItemWithTrigger:L}=H_(),P=HC()!=null,B=pp(),{nonce:D,disableStyleElements:$}=M8(),q=tt(m,nt.id),G=tt(m,nt.open),U=tt(m,nt.openMethod),V=tt(m,nt.mounted),X=tt(m,nt.popupProps),Q=tt(m,nt.transitionStatus),W=tt(m,nt.triggerElement),I=tt(m,nt.positionerElement),K=tt(m,nt.listElement),ee=x.useRef(!1),F=x.useRef(!1),ne=x.useRef({}),Z=Jl(),fe=He(le=>{if(!I||!g.current||!F.current)return;const xe=I.style.top==="0px",ke=I.style.bottom==="0px";if(ee.current||!z||!xe&&!ke){k(le);return}const Re=Hk(I),Ae=Nc(I.getBoundingClientRect().height,"y",Re),Ie=vt(I),Oe=Jt(I),Te=Oe.getComputedStyle(I),Ne=parseFloat(Te.marginTop),Me=parseFloat(Te.marginBottom),De=qk(Oe.getComputedStyle(g.current)),Ue=Math.min(Ie.documentElement.clientHeight-Ne-Me,De),Xe=le.scrollTop,me=Bd(le);let de=null;const Le=Ge=>{I.style.height=`${Ge}px`},ye=xe?me-Xe:Xe,Ce=Math.min(Ae+ye,Ue);if(ye<=Zs){const Ge=Cc(ye,0,Ue-Ae);Ge>0&&Le(Ae+Ge),le.scrollTop=xe?me:0,Ue-(Ae+Ge)<=Zs&&(ee.current=!0),k(le);return}if(Ue-Ce>Zs)de=xe?1/0:0;else if(ke&&Xe<me){const Ge=Ae+ye-Ue;de=Xe-(ye-Ge)}const Qe=Math.ceil(Ce);if(Qe!==0&&Le(Qe),de!=null){const Ge=Cc(de,0,Bd(le));Math.abs(le.scrollTop-Ge)>Zs&&(le.scrollTop=Ge)}Qe>=Ue-Zs&&(ee.current=!0),k(le)});x.useImperativeHandle(N,()=>fe,[fe]),Ca({open:G,ref:g,onComplete(){G&&h?.(!0)}});const Y={open:G,transitionStatus:Q,side:A,align:T};Pe(()=>{!I||!g.current||Object.keys(ne.current).length||(ne.current={top:I.style.top||"0",left:I.style.left||"0",right:I.style.right,height:I.style.height,bottom:I.style.bottom,minHeight:I.style.minHeight,maxHeight:I.style.maxHeight,marginTop:I.style.marginTop,marginBottom:I.style.marginBottom})},[g,I]),Pe(()=>{G||z||(F.current=!1,ee.current=!1,Df(I,ne.current))},[G,z,I,g]),Pe(()=>{const le=g.current;if(!G||!W||!I||!le||z&&!M||m.state.transitionStatus==="ending")return;if(F.current=!0,le.style.removeProperty("--transform-origin"),!z){Z.request(()=>k(K||le));return}const xe=D8(le);try{let ke=E.current;ke?.isConnected||(ke=!nt.hasSelectedValue(m.state)&&j.current?.isConnected?j.current:null);const Re=_.current,Ae=Jt(I),Ie=Ae.getComputedStyle(I),Oe=Ae.getComputedStyle(le),Te=vt(W),Ne=Hk(W),Me=$d(W.getBoundingClientRect(),Ne),De=$d(I.getBoundingClientRect(),Ne),Ue=Me.height,Xe=K||le,me=Xe.scrollHeight,de=parseFloat(Oe.borderBottomWidth),Le=parseFloat(Ie.marginTop)||10,ye=parseFloat(Ie.marginBottom)||10,Ce=parseFloat(Ie.minHeight)||100,Qe=qk(Oe),Ge=5,lt=5,Tt=20,_t=Te.documentElement.clientHeight-Le-ye,Ct=Te.documentElement.clientWidth,je=_t-Me.bottom+Ue;let ze,Ye=B==="rtl"?Me.right-De.width:Me.left,We=0;if(ke&&Re){const dn=$d(Re.getBoundingClientRect(),Ne);ze=$d(ke.getBoundingClientRect(),Ne),Ye=De.left+(B==="rtl"?dn.right-ze.right:dn.left-ze.left);const hs=dn.top-Me.top+dn.height/2;We=ze.top-De.top+ze.height/2-hs}const dt=je+We+ye+de;let Rt=Math.min(_t,dt);const Qt=_t-Le-ye,ot=dt-Rt,Pt=Ct-lt;I.style.left=`${Cc(Ye,Ge,Pt-De.width)}px`,I.style.height=`${Rt}px`,I.style.maxHeight="none",I.style.marginTop=`${Le}px`,I.style.marginBottom=`${ye}px`,le.style.height="100%";const on=Bd(Xe),Yt=ot>=on-Zs;Yt&&(Rt=Math.min(_t,De.height)-(ot-on));const Fn=Me.top<Tt||Me.bottom>_t-Tt||Math.ceil(Rt)+Zs<Math.min(me,Ce),Tn=(Ae.visualViewport?.scale??1)!==1&&ir;if(Fn||Tn){Df(I,ne.current),L(!1);return}const as=Math.max(Ce,Rt);if(Yt){const dn=Math.max(0,_t-dt);I.style.top=De.height>=Qt?"0":`${dn}px`,I.style.height=`${Rt}px`,Xe.scrollTop=Bd(Xe)}else I.style.bottom="0",Xe.scrollTop=ot;if(ze){const dn=De.top,hs=De.height,Rs=ze.top+ze.height/2,oa=Cc(hs>0?(Rs-dn)/hs*100:50,0,100);le.style.setProperty("--transform-origin",`50% ${oa}%`)}(as===_t||Rt>=Qe)&&(ee.current=!0),k(Xe),S&&m.state.selectedIndex===null&&m.state.activeIndex===null&&w.current[0]!=null&&m.set("activeIndex",0)}finally{xe()}},[m,G,I,W,_,j,E,g,k,z,L,Z,K,w,S,B,M]),x.useEffect(()=>{if(!z||!I||!G)return;const le=Jt(I);function xe(ke){b(!1,rt(R4,ke))}return xt(le,"resize",xe)},[b,z,I,G]);const oe={...K?{role:"presentation","aria-orientation":void 0}:{role:"listbox","aria-multiselectable":y||void 0,id:`${q}-list`},onKeyDown(le){P&&xp.has(le.key)&&le.stopPropagation()},onScroll(le){K||fe(le.currentTarget)},...z&&{style:K?{height:"100%"}:tE},className:!K&&z?Gx.className:void 0},ve=Et("div",t,{ref:[a,g],state:Y,stateAttributesMapping:z8,props:[X,oe,mp(Q),f]});return n.jsxs(x.Fragment,{children:[!$&&Gx.getElement(D),n.jsx(Jb,{context:R,modal:!1,disabled:!V,openInteractionType:U,returnFocus:d,restoreFocus:!0,children:ve})]})});function qk(e){const t=e.maxHeight;return t.endsWith("px")&&parseFloat(t)||1/0}function Bd(e){return q_(e.scrollHeight,e.clientHeight)}function Hk(e){return lC.getScale(e)}function Nc(e,t,a){return e/a[t]}function $d(e,t){return Bc({x:Nc(e.x,"x",t),y:Nc(e.y,"y",t),width:Nc(e.width,"x",t),height:Nc(e.height,"y",t)})}const Vk=[["transform","none"],["scale","1"],["translate","0 0"]];function D8(e){const{style:t}=e,a={};for(const[o,l]of Vk)a[o]=t.getPropertyValue(o),t.setProperty(o,l,"important");return()=>{for(const[o]of Vk){const l=a[o];l?t.setProperty(o,l):t.removeProperty(o)}}}const P8=x.forwardRef(function(t,a){const{render:o,className:l,style:c,...d}=t,{store:f,scrollHandlerRef:m,multiple:g}=Na(),{alignItemWithTriggerActive:h}=H_(),b=tt(f,nt.hasScrollArrows),_=tt(f,nt.openMethod),E={id:`${tt(f,nt.id)}-list`,role:"listbox","aria-multiselectable":g||void 0,onScroll(k){m.current?.(k.currentTarget)},...h&&{style:tE},className:b&&_!=="touch"?Gx.className:void 0},y=f.useStateSetter("listElement");return Et("div",t,{ref:[a,y],props:[E,d]})}),nE=x.createContext(void 0);function V_(){const e=x.useContext(nE);if(!e)throw new Error(gn(57));return e}const L8=x.memo(x.forwardRef(function(t,a){const{render:o,className:l,style:c,value:d=null,label:f,disabled:m=!1,nativeButton:g=!1,...h}=t,b=x.useRef(null),_=ru({guess:!0,label:f,textRef:b}),{store:j,itemProps:E,setOpen:y,setValue:k,selectionRef:N,typingRef:w,valuesRef:S,multiple:R,selectedItemTextRef:A,disabled:T,readOnly:z}=Na(),M=T||m,L=tt(j,nt.isActive,_.index),P=tt(j,nt.open),B=tt(j,nt.isSelected,d),D=tt(j,nt.isSelectedByFocus,_.index),$=tt(j,nt.isItemEqualToValue),q=_.index,G=x.useRef(null);Pe(()=>{const Z=S.current;return Z[q]=d,()=>{delete Z[q]}},[q,d,S]),Pe(()=>{const Z=j.state.value;let fe=Z;R&&Array.isArray(Z)&&(fe=Z.length>0?Z[Z.length-1]:void 0),fe!==void 0&&li(d,fe,$)&&(j.set("selectedIndex",q),b.current&&(A.current=b.current))},[q,R,$,j,d,A]);const U=x.useRef("mouse"),V=x.useRef(!1),{getButtonProps:X,buttonRef:Q}=no({disabled:M,focusableWhenDisabled:!0,native:g,composite:!0}),W={disabled:M,selected:B,highlighted:L};function I(Z){if(T||z)return;const fe=j.state.value;if(R){const Y=Array.isArray(fe)?fe:[],oe=B?g8(Y,d,$):[...Y,d];k(oe,rt(Fl,Z))}else k(d,rt(Fl,Z)),y(!1,rt(Fl,Z))}function K(){N.current.dragY=0}const ee={role:"option","aria-selected":B,tabIndex:P&&L?0:-1,onKeyDown(Z){j.set("activeIndex",q),Z.key===" "&&w.current&&Z.preventDefault()},onClick(Z){const fe=U.current!=="touch",Y=Z.nativeEvent.pointerType,oe=fe&&zb(Z.nativeEvent)&&(Y!==void 0||L),ve=fe&&!oe&&!V.current;V.current=!1,!(M||ve)&&I(Z.nativeEvent)},onPointerEnter(Z){U.current=Z.pointerType},onPointerMove(Z){if(Z.pointerType==="mouse"&&Z.buttons===1){const fe=N.current;fe.dragY+=Z.movementY,fe.dragY**2>=64&&(fe.allowUnselectedMouseUp=!0)}},onPointerDown(Z){U.current=Z.pointerType,V.current=!0,K()},onMouseUp(){if(K(),M||U.current==="touch"||V.current)return;const Z=!N.current.allowSelectedMouseUp&&B,fe=!N.current.allowUnselectedMouseUp&&!B;Z||fe||(V.current=!0,G.current?.click(),V.current=!1)}},F=Et("div",t,{ref:[Q,a,_.ref,G],state:W,props:[E,ee,h,X]}),ne=x.useMemo(()=>({selected:B,index:q,textRef:b,selectedByFocus:D}),[B,q,b,D]);return n.jsx(nE.Provider,{value:ne,children:F})})),I8=x.forwardRef(function(t,a){const{selected:o}=V_();return t.keepMounted||o?n.jsx(B8,{...t,ref:a}):null}),B8=x.memo(x.forwardRef((e,t)=>{const{render:a,className:o,style:l,keepMounted:c,...d}=e,{selected:f}=V_(),m=x.useRef(null),{transitionStatus:g,setMounted:h}=hi(f),_=Et("span",e,{ref:[t,m],state:{selected:f,transitionStatus:g},props:[{"aria-hidden":!0,children:"✔️"},d],stateAttributesMapping:Ho});return Ca({open:f,ref:m,onComplete(){f||h(!1)}}),_})),$8=x.memo(x.forwardRef(function(t,a){const{index:o,textRef:l,selectedByFocus:c}=V_(),{firstItemTextRef:d,selectedItemTextRef:f}=Na(),{render:m,className:g,style:h,...b}=t,_=x.useCallback(E=>{E&&(o===0&&(d.current=E),c&&(f.current=E))},[d,f,o,c]);return Et("div",t,{ref:[_,a,l],props:b})})),sE=x.forwardRef(function(t,a){const{render:o,className:l,style:c,direction:d,keepMounted:f,...m}=t,g=d==="up",{store:h,popupRef:b,listRef:_,handleScrollArrowVisibility:j,scrollArrowsMountedCountRef:E}=Na(),{side:y,scrollDownArrowRef:k,scrollUpArrowRef:N}=H_(),w=g?nt.scrollUpArrowVisible:nt.scrollDownArrowVisible,S=tt(h,w),R=tt(h,nt.openMethod),A=S&&R!=="touch",T=Rn(),z=g?N:k,{mounted:M,transitionStatus:L,setMounted:P}=hi(A);Pe(()=>(E.current+=1,h.set("hasScrollArrows",!0),()=>{E.current=Math.max(0,E.current-1),E.current===0&&h.set("hasScrollArrows",!1)}),[h,E]),Ca({open:A,ref:z,onComplete(){A||P(!1)}});const $=Et("div",t,{ref:[a,z],state:{direction:d,visible:A,side:y,transitionStatus:L},props:[{"aria-hidden":!0,children:g?"▲":"▼",style:{position:"absolute"},onMouseMove(G){if(G.movementX===0&&G.movementY===0||T.isStarted())return;h.set("activeIndex",null);function U(){const V=h.state.listElement??b.current;if(!V)return;h.set("activeIndex",null),j(V);const X=q_(V.scrollHeight,V.clientHeight),Q=Of(V.scrollTop,X),W=Q===(g?0:X),I=_.current;if(Q!==V.scrollTop&&(V.scrollTop=Q),W){T.clear();return}if(I.length>0){const K=z.current?.offsetHeight||0;V.scrollTop=U8(I,g,Q,V.clientHeight,K,X)}T.start(40,U)}T.start(40,U)},onMouseLeave(){T.clear()}},m],stateAttributesMapping:Ho});return M||f?$:null});function U8(e,t,a,o,l,c){if(t){let h=0;const b=a+l-Zs;for(let E=0;E<e.length;E+=1){const y=e[E];if(y&&y.offsetTop>=b){h=E;break}}const _=Math.max(0,h-1),j=e[_];return _<h&&j?Of(j.offsetTop-l,c):0}let d=e.length-1;const f=a+o-l+Zs;for(let h=0;h<e.length;h+=1){const b=e[h];if(b&&b.offsetTop+b.offsetHeight>f){d=Math.max(0,h-1);break}}const m=Math.min(e.length-1,d+1),g=e[m];return m>d&&g?Of(g.offsetTop+g.offsetHeight-o+l,c):c}const q8=x.forwardRef(function(t,a){return n.jsx(sE,{...t,ref:a,direction:"down"})}),H8=x.forwardRef(function(t,a){return n.jsx(sE,{...t,ref:a,direction:"up"})}),V8=_8;function F8({className:e,...t}){return n.jsx(S8,{"data-slot":"select-value",className:St("flex flex-1 text-left",e),...t})}function G8({className:e,size:t="default",children:a,...o}){return n.jsxs(k8,{"data-slot":"select-trigger","data-size":t,className:St("flex w-fit items-center justify-between gap-1.5 rounded-lg border border-input bg-transparent py-2 pr-2 pl-2.5 text-sm whitespace-nowrap transition-colors outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-8 data-[size=sm]:h-7 data-[size=sm]:rounded-[min(var(--radius-md),10px)] *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...o,children:[a,n.jsx(C8,{render:n.jsx(ms,{className:"pointer-events-none size-4 text-muted-foreground"})})]})}function Y8({className:e,children:t,side:a="bottom",sideOffset:o=4,align:l="center",alignOffset:c=0,alignItemWithTrigger:d=!0,...f}){return n.jsx(N8,{children:n.jsx(R8,{side:a,sideOffset:o,align:l,alignOffset:c,alignItemWithTrigger:d,className:"isolate z-50",children:n.jsxs(O8,{"data-slot":"select-content","data-align-trigger":d,className:St("relative isolate z-50 max-h-(--available-height) w-(--anchor-width) min-w-36 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",e),...f,children:[n.jsx(X8,{}),n.jsx(P8,{children:t}),n.jsx(Q8,{})]})})})}function K8({className:e,children:t,...a}){return n.jsxs(L8,{"data-slot":"select-item",className:St("relative flex w-full cursor-default items-center gap-2 rounded-md py-2 pr-8 pl-2.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",e),...a,children:[n.jsx($8,{className:"flex min-w-0 flex-1 gap-2 overflow-hidden whitespace-nowrap",children:t}),n.jsx(I8,{render:n.jsx("span",{className:"pointer-events-none absolute right-2 flex size-4 items-center justify-center"}),children:n.jsx(Yr,{className:"pointer-events-none"})})]})}function X8({className:e,...t}){return n.jsx(H8,{"data-slot":"select-scroll-up-button",className:St("top-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",e),...t,children:n.jsx(fb,{})})}function Q8({className:e,...t}){return n.jsx(q8,{"data-slot":"select-scroll-down-button",className:St("bottom-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",e),...t,children:n.jsx(ms,{})})}function ct({value:e,onChange:t,options:a,placeholder:o="— elegir —",disabled:l,className:c,showIcon:d=!1}){return n.jsxs(V8,{value:e,onValueChange:f=>t(f??""),disabled:l,children:[n.jsx(G8,{className:ge("h-9 w-full",c),children:n.jsx(F8,{placeholder:o,children:f=>{const m=a.find(h=>h.value===f),g=d?m?.icon:void 0;return n.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[g&&n.jsx(g,{className:"size-3.5 shrink-0"}),n.jsx("span",{className:"truncate",children:m?.label??f})]})}})}),n.jsx(Y8,{side:"bottom",sideOffset:6,align:"start",alignItemWithTrigger:!1,className:"w-[var(--anchor-width)] p-1.5",children:a.map(f=>{const m=f.icon;return n.jsx(K8,{value:f.value,disabled:f.disabled,children:n.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[m?n.jsx(m,{className:"size-4 shrink-0 text-muted-fg"}):null,f.description?n.jsxs("span",{className:"flex min-w-0 flex-col leading-tight",children:[n.jsx("span",{className:"truncate font-medium",children:f.label}),n.jsx("span",{className:"truncate text-[11px] text-muted-fg",children:f.description})]}):n.jsx("span",{className:"truncate",children:f.label})]})},f.value)})})]})}const Fk=320;function W8(e){const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString(void 0,{month:"short",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"})}function Z8(e){return e.agent_slug||e.actor_id||e.author||e.actor_kind||"—"}function J8(e){const t=e.meta?.model;return typeof t=="string"&&t?t:null}function eI(e){const t=e.meta?.usage;if(!t||typeof t!="object")return null;const a=(t.input_tokens||0)+(t.output_tokens||0);return a>0?a:null}function tI({m:e}){const[t,a]=x.useState(!1),o=(e.body?.length||0)>Fk,l=!o||t?e.body:`${e.body.slice(0,Fk)}…`,c=J8(e),d=eI(e);return n.jsxs("li",{className:"flex items-start gap-3 rounded-md border border-border bg-muted/30 px-3 py-2",children:[n.jsx("span",{className:"mt-0.5 shrink-0",children:e.direction==="in"?n.jsx(q2,{size:14,className:"text-blue-400"}):n.jsx(V2,{size:14,className:"text-emerald-400"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-fg",children:[n.jsx("span",{className:"font-mono",children:W8(e.ts)}),n.jsx($e,{tone:"info",children:e.channel}),e.type&&n.jsx($e,{children:e.type}),n.jsx("span",{className:"font-medium text-foreground",children:Z8(e)}),c&&n.jsx("span",{className:"font-mono text-[11px] text-sky-400/90",children:c}),d!==null&&n.jsxs("span",{className:"font-mono text-[11px]",children:[d," tok"]})]}),e.body&&n.jsx("p",{className:"mt-1 whitespace-pre-wrap break-words text-xs",children:l}),o&&n.jsx("button",{type:"button",onClick:()=>a(f=>!f),className:"mt-1 text-[11px] font-medium text-sky-400 hover:underline",children:u(t?"logs.show_less":"logs.show_more")})]})]})}function nI(){const[e,t]=x.useState(!1),a=Be(e?"/admin/logs?errors":null,()=>ai.logs("errors",200)),o=a.data?.entries||[];return n.jsxs("details",{className:"mb-3 rounded-lg border border-border bg-muted/20",onToggle:l=>t(l.target.open),children:[n.jsxs("summary",{className:"cursor-pointer px-3 py-2 text-xs font-medium text-muted-fg",children:[u("logs.daemon_errors"),o.length?` · ${o.length}`:""]}),n.jsxs("div",{className:"border-t border-border p-3",children:[a.isLoading&&n.jsx(st,{}),e&&!a.isLoading&&o.length===0&&n.jsx("p",{className:"text-xs text-muted-fg",children:u("logs.no_errors")}),n.jsx("ul",{className:"space-y-1",children:o.map((l,c)=>n.jsxs("li",{className:"rounded-md bg-card px-2 py-1 text-[11px]",children:[n.jsxs("div",{className:"flex items-center gap-2 text-muted-fg",children:[typeof l.ts=="string"&&n.jsx("span",{className:"font-mono",children:new Date(l.ts).toLocaleString()}),typeof l.level=="string"&&n.jsx("span",{className:"text-destructive",children:l.level})]}),n.jsx("p",{className:"whitespace-pre-wrap break-words font-mono",children:String(l.msg??l.message??l.error??l.raw??JSON.stringify(l)).slice(0,500)})]},c))})]})]})}function sI({pid:e}){const t=!e||String(e)==="0",[a,o]=x.useState(""),[l,c]=x.useState(""),[d,f]=x.useState(""),[m,g]=x.useState(""),h=a.trim()||void 0,b=t?`/messages/global?channel=${h??""}`:`/projects/${e}/messages?channel=${h??""}`,_=Be(b,()=>t?Cf.global({channel:h,limit:300}):Cf.project(e,{channel:h,limit:300})),j=x.useMemo(()=>[..._.data||[]].sort((k,N)=>(N.ts||"").localeCompare(k.ts||"")),[_.data]),E=x.useMemo(()=>Array.from(new Set(j.map(k=>k.type).filter(Boolean))),[j]),y=x.useMemo(()=>j.filter(k=>!(l&&k.direction!==l||d&&k.type!==d||m&&!(k.body||"").toLowerCase().includes(m.toLowerCase()))),[j,l,d,m]);return n.jsxs(Ve,{title:u("logs.title"),description:u(t?"logs.desc_global":"logs.desc_project"),action:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Ee,{placeholder:u("logs.filter_channel"),value:a,onChange:k=>o(k.target.value),className:"w-44"}),n.jsx(re,{size:"sm",variant:"secondary",onClick:()=>_.mutate(),children:n.jsx(Cs,{size:13})})]}),children:[t&&n.jsx(nI,{}),n.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2",children:[n.jsx("div",{className:"w-36",children:n.jsx(ct,{value:l,onChange:c,placeholder:u("logs.filter_dir"),options:[{value:"",label:u("logs.all_directions")},{value:"in",label:u("logs.in")},{value:"out",label:u("logs.out")}]})}),n.jsx("div",{className:"w-40",children:n.jsx(ct,{value:d,onChange:f,placeholder:u("logs.filter_type"),options:[{value:"",label:u("logs.all_types")},...E.map(k=>({value:k,label:k}))]})}),n.jsx(Ee,{placeholder:u("logs.search_text"),value:m,onChange:k=>g(k.target.value),className:"w-56"}),n.jsxs("span",{className:"text-[11px] text-muted-fg",children:[y.length," ",u("logs.count_of")," ",j.length]})]}),_.isLoading&&n.jsx(st,{}),_.error&&n.jsx(ft,{children:u("logs.error",{msg:_.error.message})}),!_.isLoading&&!_.error&&y.length===0&&n.jsx(ft,{children:h?u("logs.no_activity_ch",{ch:h}):u("logs.no_activity")}),n.jsx("ul",{className:"space-y-1 text-sm",children:y.map((k,N)=>n.jsx(tI,{m:k},`${k.ts}-${N}`))})]})}function aE({value:e,onChange:t,options:a,placeholder:o=u("shared_ui.model_combobox_ph"),invalid:l,invalidHint:c,className:d}){const[f,m]=x.useState(!1),[g,h]=x.useState(e),b=x.useRef(null),_=x.useRef(null),[j,E]=x.useState(null);x.useEffect(()=>{h(e)},[e]),x.useLayoutEffect(()=>{if(!f)return;const S=()=>{const R=b.current;if(!R)return;const A=R.getBoundingClientRect();E({top:A.bottom+4,left:A.left,width:A.width})};return S(),window.addEventListener("scroll",S,!0),window.addEventListener("resize",S),()=>{window.removeEventListener("scroll",S,!0),window.removeEventListener("resize",S)}},[f]),x.useEffect(()=>{if(!f)return;const S=R=>{const A=R.target;b.current?.contains(A)||_.current?.contains(A)||m(!1)};return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[f]);const y=g.trim().toLowerCase(),N=y&&!(g===e)?a.filter(S=>S.toLowerCase().includes(y)):a,w=S=>{t(S),h(S),m(!1)};return n.jsxs("div",{ref:b,className:ge("relative",d),children:[n.jsxs("div",{className:ge("flex items-center gap-1 rounded-lg border bg-background px-2.5 transition-colors focus-within:border-ring focus-within:ring-1 focus-within:ring-ring",l?"border-amber-500/60":"border-border"),children:[l&&n.jsx(qe,{content:c||u("models_ui.invalid_hint"),children:n.jsx("span",{children:n.jsx(wb,{className:"size-3.5 shrink-0 text-amber-400"})})}),n.jsx("input",{value:g,placeholder:o,onChange:S=>{h(S.target.value),t(S.target.value),m(!0)},onFocus:()=>m(!0),className:"w-full bg-transparent py-1.5 text-sm outline-none placeholder:text-muted-fg/60"}),n.jsx("button",{type:"button",tabIndex:-1,onClick:()=>m(S=>!S),className:"shrink-0 text-muted-fg hover:text-foreground",children:n.jsx(ms,{className:"size-4"})})]}),f&&N.length>0&&j&&Gs.createPortal(n.jsx("ul",{ref:_,style:{position:"fixed",top:j.top,left:j.left,width:j.width},className:"z-[1000] max-h-56 overflow-y-auto rounded-lg border border-border bg-popover p-1 shadow-md ring-1 ring-foreground/10",children:N.map(S=>n.jsx("li",{children:n.jsx("button",{type:"button",onMouseDown:R=>{R.preventDefault(),w(S)},className:ge("flex w-full items-center rounded-md px-2 py-1 text-left text-sm hover:bg-accent hover:text-accent-fg",S===e&&"bg-accent/50"),children:n.jsx("span",{className:"truncate font-mono text-xs",children:S})})},S))}),document.body)]})}function ur(){const{data:e,error:t,isLoading:a,mutate:o}=Be("/admin/config",()=>ai.config.get()),l=async(c,d)=>{const f=await ai.config.patch({set:c,unset:d});return await o({config:f.config},{revalidate:!1}),f.config};return{config:e?.config||{},error:t,isLoading:a,mutate:o,patch:l}}function rE(){const{data:e,error:t,isLoading:a,mutate:o}=Be("/admin/super-agent",()=>ai.superAgent());return{superAgent:e,error:t,isLoading:a,mutate:o}}const aI="modulepreload",rI=function(e){return"/"+e},Gk={},oI=function(t,a,o){let l=Promise.resolve();if(a&&a.length>0){let d=function(g){return Promise.all(g.map(h=>Promise.resolve(h).then(b=>({status:"fulfilled",value:b}),b=>({status:"rejected",reason:b}))))};document.getElementsByTagName("link");const f=document.querySelector("meta[property=csp-nonce]"),m=f?.nonce||f?.getAttribute("nonce");l=d(a.map(g=>{if(g=rI(g),g in Gk)return;Gk[g]=!0;const h=g.endsWith(".css"),b=h?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${g}"]${b}`))return;const _=document.createElement("link");if(_.rel=h?"stylesheet":aI,h||(_.as="script"),_.crossOrigin="",_.href=g,m&&_.setAttribute("nonce",m),document.head.appendChild(_),h)return new Promise((j,E)=>{_.addEventListener("load",j),_.addEventListener("error",()=>E(new Error(`Unable to preload CSS for ${g}`)))})}))}function c(d){const f=new Event("vite:preloadError",{cancelable:!0});if(f.payload=d,window.dispatchEvent(f),!f.defaultPrevented)throw d}return l.then(d=>{for(const f of d||[])f.status==="rejected"&&c(f.reason);return t().catch(c)})},lI={anthropic:"from-orange-600 to-amber-600",openai:"from-emerald-600 to-teal-600",gemini:"from-blue-600 to-indigo-600",groq:"from-cyan-600 to-teal-600",openrouter:"from-violet-600 to-indigo-600",ollama:"from-amber-600 to-orange-600",azure:"from-blue-600 to-cyan-600",mock:"from-slate-600 to-gray-600",custom:"from-slate-600 to-gray-600"},iI={anthropic:"bg-orange-500/20 text-orange-300 border border-orange-500/40",openai:"bg-emerald-500/20 text-emerald-300 border border-emerald-500/40",gemini:"bg-blue-500/20 text-blue-300 border border-blue-500/40",groq:"bg-cyan-500/20 text-cyan-300 border border-cyan-500/40",openrouter:"bg-violet-500/20 text-violet-300 border border-violet-500/40",ollama:"bg-amber-500/20 text-amber-300 border border-amber-500/40",azure:"bg-blue-500/20 text-blue-300 border border-blue-500/40",mock:"bg-slate-500/20 text-slate-300 border border-slate-500/40",custom:"bg-slate-500/20 text-slate-300 border border-slate-500/40"},Mc=[{value:"anthropic",label:"Anthropic"},{value:"openai",label:"OpenAI-compatible"},{value:"gemini",label:"Gemini"},{value:"groq",label:"Groq"},{value:"openrouter",label:"OpenRouter"},{value:"ollama",label:"Ollama"},{value:"azure",label:"Azure OpenAI"},{value:"mock",label:"Mock (test)"},{value:"custom",label:"Custom"}];function _h(e,t){return t&&t in e?e[t]:e.custom}const Pf={anthropic:sa,openai:rn,gemini:FA,groq:pi,openrouter:Zc,ollama:rS,azure:TA,mock:cx,custom:aa},Za={anthropic:{base_url:"",default_model:"claude-sonnet-5",api_key_env:"ANTHROPIC_API_KEY",known_models:["claude-opus-4-8","claude-sonnet-5","claude-haiku-4-5","claude-fable-5"]},openai:{base_url:"https://api.openai.com/v1",default_model:"gpt-5.4-mini",api_key_env:"OPENAI_API_KEY",known_models:["gpt-5.5","gpt-5.4-mini","gpt-5.4-nano","gpt-5.1","gpt-4.1-mini"]},gemini:{base_url:"https://generativelanguage.googleapis.com/v1beta/openai",default_model:"gemini-2.5-flash",api_key_env:"GEMINI_API_KEY",known_models:["gemini-3.5-flash","gemini-3.1-pro-preview","gemini-2.5-pro","gemini-2.5-flash","gemini-2.5-flash-lite"]},groq:{base_url:"https://api.groq.com/openai/v1",default_model:"openai/gpt-oss-20b",api_key_env:"GROQ_API_KEY",known_models:["openai/gpt-oss-120b","openai/gpt-oss-20b","qwen/qwen3.6-27b","groq/compound","groq/compound-mini","whisper-large-v3-turbo"]},openrouter:{base_url:"https://openrouter.ai/api/v1",default_model:"openrouter/auto",api_key_env:"OPENROUTER_API_KEY",known_models:["openrouter/auto","openrouter/free","anthropic/claude-sonnet-5","openai/gpt-5.4-mini","google/gemini-2.5-flash"]},ollama:{base_url:"http://127.0.0.1:11434",default_model:"gemma2:9b",api_key_env:"",known_models:[]},azure:{base_url:"",default_model:"",api_key_env:"AZURE_OPENAI_API_KEY",known_models:[]},mock:{base_url:"",default_model:"mock",api_key_env:"",known_models:["mock"]},custom:{base_url:"",default_model:"",api_key_env:"",known_models:[]}};let Yk=!1;async function cI(){if(!Yk)try{const{Engines:e}=await oI(async()=>{const{Engines:a}=await Promise.resolve().then(()=>dP);return{Engines:a}},[]),{presets:t}=await e.presets();for(const[a,o]of Object.entries(t||{}))a in Za&&o&&Object.assign(Za[a],o);Yk=!0}catch{}}function oE(e){const t=e.indexOf(":");return t<0?{provider:e,model:""}:{provider:e.slice(0,t),model:e.slice(t+1)}}function vh({value:e,onChange:t,providers:a}){const{provider:o,model:l}=oE(e),c=a.find(h=>h.slug===o),d=!!o&&!c,f=x.useMemo(()=>{const h=c?Za[c.engine]?.known_models||[]:[];return Array.from(new Set([...c?.default_model?[c.default_model]:[],...h]))},[c]),m=h=>{const b=a.find(j=>j.slug===h),_=b?.default_model||Za[b?.engine]?.default_model||"";t(_?`${h}:${_}`:`${h}:`)},g=h=>t(`${o}:${h}`);return n.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[n.jsx(ct,{value:o,onChange:m,placeholder:d?u("router_panel.provider_not_found",{name:o}):u("router_panel.provider_ph"),options:a.map(h=>({value:h.slug,label:h.slug,icon:Pf[h.engine]}))}),n.jsx(aE,{value:l,onChange:g,options:f,invalid:d,invalidHint:u("router_panel.provider_not_configured",{name:o})})]})}function uI(){const e=Je(),{superAgent:t,isLoading:a,mutate:o}=rE(),{config:l,patch:c}=ur(),[d,f]=x.useState(""),[m,g]=x.useState([]),[h,b]=x.useState(""),[_,j]=x.useState(null),[E,y]=x.useState(!1),[k,N]=x.useState({model:"",fallback:[]});x.useEffect(()=>{if(!t)return;const P=t.model_fallback?.models||[],B=Array.isArray(P)?P:[];f(t.model||""),g(B),N({model:t.model||"",fallback:B})},[t]);const w=x.useMemo(()=>{const P=l.engines||{};return Object.entries(P).map(([B,D])=>({slug:B,engine:D?.engine||B,default_model:D?.default_model||Za[D?.engine||B]?.default_model}))},[l.engines]),S=P=>{const{provider:B}=oE(P);return w.some(D=>D.slug===B)};if(a||!t)return n.jsx(st,{});const R=d!==k.model||JSON.stringify(m)!==JSON.stringify(k.fallback),A=async()=>{y(!0);try{await c({"super_agent.model":d,"super_agent.model_fallback.enabled":m.length>0,"super_agent.model_fallback.models":m}),e.success(u("router_panel.saved_toast")),N({model:d,fallback:m}),o()}catch(P){e.error(P.message)}finally{y(!1)}},T=()=>{const P=h.trim().replace(/:$/,"");!P||!P.includes(":")||m.includes(P)||(g([...m,P]),b(""))},z=(P,B)=>{const D=[...m];D[P]=B,g(D)},M=P=>{g(m.filter((B,D)=>D!==P)),_===P&&j(null)},L=(P,B)=>{const D=P+B;if(D<0||D>=m.length)return;const $=[...m];[$[P],$[D]]=[$[D],$[P]],g($)};return n.jsx(Ve,{title:u("router_panel.title"),description:u("router_panel.description"),children:n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-2 rounded-lg border border-border bg-muted/20 p-3",children:[n.jsxs($e,{tone:"success",children:[n.jsx(Zc,{size:11})," ",u("router_panel.badge_default")]}),n.jsx("span",{className:`font-mono text-xs ${!S(d)&&d?"text-amber-400":""}`,children:d||"—"}),m.map(P=>n.jsxs("span",{className:"flex items-center gap-2 text-muted-fg",children:[n.jsx(H2,{size:12}),n.jsx("span",{className:`font-mono text-xs ${S(P)?"":"text-amber-400"}`,children:P})]},P))]}),w.length===0?n.jsx("p",{className:"text-xs text-muted-fg",children:u("router_panel.no_providers")}):n.jsx(ie,{label:u("router_panel.active_model_label"),hint:u("router_panel.active_model_hint"),children:n.jsx(vh,{value:d,onChange:f,providers:w})}),n.jsxs("div",{className:"rounded-lg border border-border bg-muted/20 p-3",children:[n.jsxs("div",{className:"mb-2",children:[n.jsx("div",{className:"text-sm font-medium",children:u("router_panel.fallback_title")}),n.jsx("div",{className:"text-xs text-muted-fg",children:u("router_panel.fallback_desc")})]}),n.jsxs("ul",{className:"mb-3 space-y-1",children:[m.map((P,B)=>{const D=!S(P),$=_===B;return n.jsx("li",{className:"rounded-md bg-card px-2 py-1.5 text-xs",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("span",{className:"w-6 text-muted-fg",children:["#",B+1]}),$?n.jsx("div",{className:"flex-1",children:n.jsx(vh,{value:P,onChange:q=>z(B,q),providers:w})}):n.jsxs("button",{type:"button",onClick:()=>j(B),className:"flex flex-1 items-center gap-1.5 text-left",children:[D&&n.jsx(wb,{size:12,className:"text-amber-400"}),n.jsx("span",{className:`font-mono ${D?"text-amber-400":""}`,children:P})]}),$?n.jsx(re,{size:"sm",variant:"secondary",onClick:()=>j(null),children:u("router_panel.done")}):n.jsx(re,{size:"sm",variant:"ghost",onClick:()=>j(B),children:n.jsx(wa,{size:12})}),n.jsx(re,{size:"sm",variant:"ghost",onClick:()=>L(B,-1),disabled:B===0,children:"↑"}),n.jsx(re,{size:"sm",variant:"ghost",onClick:()=>L(B,1),disabled:B===m.length-1,children:"↓"}),n.jsx(re,{size:"sm",variant:"destructive",onClick:()=>M(B),children:n.jsx(_n,{size:12})})]})},`${B}-${P}`)}),m.length===0&&n.jsx("li",{className:"text-xs text-muted-fg",children:u("router_panel.fallback_empty")})]}),w.length>0&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-xs text-muted-fg",children:u("router_panel.add_to_chain")}),n.jsx(vh,{value:h,onChange:b,providers:w}),n.jsxs(re,{size:"sm",variant:"secondary",onClick:T,disabled:!h.includes(":")||h.endsWith(":"),children:[n.jsx(Dt,{size:13})," ",u("router_panel.add_to_chain")]})]})]}),n.jsx(re,{variant:"primary",loading:E,disabled:!R,onClick:A,children:u(R?"router_panel.save":"router_panel.saved")})]})})}const dI=[{model:"openai:gpt-4o",when:{has_image:!0}},{model:"anthropic:claude-3-5-haiku",when:{max_prompt_chars:400}}];function fI({when:e}){const t=[];return!e||Object.keys(e).length===0?t.push({icon:n.jsx(Zr,{size:11}),label:u("routing_panel.when_any")}):(e.has_image===!0&&t.push({icon:n.jsx(ux,{size:11}),label:u("routing_panel.when_image")}),e.has_image===!1&&t.push({icon:n.jsx(ux,{size:11}),label:u("routing_panel.when_no_image")}),Number.isFinite(e.min_prompt_chars)&&t.push({icon:n.jsx(Yg,{size:11}),label:u("routing_panel.when_min_prompt",{n:String(e.min_prompt_chars)})}),Number.isFinite(e.max_prompt_chars)&&t.push({icon:n.jsx(Yg,{size:11}),label:u("routing_panel.when_max_prompt",{n:String(e.max_prompt_chars)})}),Number.isFinite(e.min_context_chars)&&t.push({icon:n.jsx(Yg,{size:11}),label:u("routing_panel.when_min_context",{n:String(e.min_context_chars)})}),Array.isArray(e.channels)&&e.channels.length>0&&t.push({icon:n.jsx(fM,{size:11}),label:u("routing_panel.when_channels",{list:e.channels.join(", ")})}),Array.isArray(e.keywords)&&e.keywords.length>0&&t.push({icon:n.jsx(KA,{size:11}),label:u("routing_panel.when_keywords",{list:e.keywords.join(", ")})})),n.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:t.map((a,o)=>n.jsxs("span",{className:"inline-flex items-center gap-1 rounded bg-muted px-1.5 py-0.5 text-[11px] text-muted-fg",children:[a.icon," ",a.label]},o))})}function pI(){const e=Je(),{config:t,isLoading:a,patch:o}=ur(),[l,c]=x.useState(!1),[d,f]=x.useState("[]"),[m,g]=x.useState(!1),[h,b]=x.useState(!1),[_,j]=x.useState(!1),[E,y]=x.useState({enabled:!1,rulesText:"[]"});x.useEffect(()=>{const M=t.super_agent?.routing||{},L=Array.isArray(M.rules)?M.rules:[],P=JSON.stringify(L,null,2);c(M.enabled===!0),f(P),y({enabled:M.enabled===!0,rulesText:P})},[t.super_agent?.routing]);const k=x.useMemo(()=>{try{const M=JSON.parse(d);return Array.isArray(M)?{rules:M,error:null}:{rules:[],error:u("routing_panel.json_not_array")}}catch(M){return{rules:[],error:u("routing_panel.json_error",{msg:M.message})}}},[d]);if(a)return n.jsx(st,{});const N=k.rules,w=N.length,S=k.error?d:JSON.stringify(N),R=(()=>{try{return JSON.stringify(JSON.parse(E.rulesText))}catch{return E.rulesText}})(),A=l!==E.enabled||S!==R,T=async()=>{if(!k.error){b(!0);try{await o({"super_agent.routing":{enabled:l,rules:N}}),e.success(u("routing_panel.saved_toast"));const M=JSON.stringify(N,null,2);f(M),y({enabled:l,rulesText:M})}catch(M){e.error(M.message)}finally{b(!1),j(!1)}}},z=l&&w>0;return n.jsxs("div",{"data-testid":"routing-panel",children:[n.jsx(Ve,{title:u("routing_panel.title"),description:u("routing_panel.description"),children:n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-2 rounded-lg border border-border bg-muted/20 p-3",children:[n.jsx("span",{"data-testid":"routing-signal",children:z?n.jsxs($e,{tone:"success",children:[n.jsx(Gg,{size:11})," ",u("routing_panel.signal_on",{n:String(w)})]}):l?n.jsxs($e,{tone:"warning",children:[n.jsx(Gg,{size:11})," ",u("routing_panel.signal_on_empty")]}):n.jsxs($e,{tone:"muted",children:[n.jsx(Gg,{size:11})," ",u("routing_panel.signal_off")]})}),n.jsx(qe,{content:u("routing_panel.helper"),children:n.jsx("span",{className:"text-xs text-muted-fg underline decoration-dotted underline-offset-2",children:u("routing_panel.how_it_works")})})]}),n.jsx(Bt,{checked:l,onChange:c,label:u("routing_panel.enable_label")}),n.jsxs("div",{className:"rounded-lg border border-border bg-muted/20 p-3",children:[n.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium",children:u("routing_panel.rules_title")}),n.jsx("div",{className:"text-xs text-muted-fg",children:u("routing_panel.rules_desc")})]}),n.jsx(re,{size:"sm",variant:"secondary",onClick:()=>g(M=>!M),children:u(m?"routing_panel.hide_editor":"routing_panel.edit_rules")})]}),n.jsxs("ul",{className:"space-y-1.5",children:[N.map((M,L)=>n.jsxs("li",{className:"rounded-md bg-card px-2.5 py-2 text-xs",children:[n.jsxs("div",{className:"mb-1 flex items-center gap-2",children:[n.jsxs("span",{className:"w-6 text-muted-fg",children:["#",L+1]}),n.jsx("span",{className:"font-mono text-[12px]",children:M.model||"—"})]}),n.jsx("div",{className:"pl-8",children:n.jsx(fI,{when:M.when})})]},L)),w===0&&!k.error&&n.jsx("li",{className:"text-xs text-muted-fg",children:u("routing_panel.rules_empty")})]})]}),m&&n.jsxs(ie,{label:u("routing_panel.editor_label"),hint:u("routing_panel.json_hint"),children:[n.jsx(un,{rows:10,className:"font-mono text-xs",value:d,onChange:M=>f(M.target.value),spellCheck:!1}),k.error?n.jsx("span",{className:"mt-1 block text-[11px] text-red-400",children:k.error}):n.jsx("button",{type:"button",className:"mt-1 text-[11px] text-muted-fg underline decoration-dotted underline-offset-2",onClick:()=>f(JSON.stringify(dI,null,2)),children:u("routing_panel.insert_example")})]}),n.jsx("p",{className:"text-[11px] leading-relaxed text-muted-fg",children:u("routing_panel.helper")}),n.jsx(re,{variant:"primary",loading:h,disabled:!A||!!k.error,onClick:()=>j(!0),children:u(A?"routing_panel.save":"routing_panel.saved")})]})}),n.jsx(Xt,{open:_,onClose:()=>j(!1),title:u("routing_panel.confirm_title"),description:u("routing_panel.confirm_body"),footer:n.jsxs(n.Fragment,{children:[n.jsx(re,{variant:"ghost",onClick:()=>j(!1),children:u("routing_panel.cancel")}),n.jsx(re,{variant:"primary",loading:h,onClick:T,children:u("routing_panel.confirm_apply")})]}),children:n.jsx("p",{className:"text-sm text-muted-fg",children:l?u("routing_panel.confirm_on",{n:String(w)}):u("routing_panel.confirm_off")})})]})}function mI({provider:e,onEdit:t,onDelete:a,onToggle:o}){const l=_h(lI,e.engine),c=_h(iI,e.engine),d=_h(Pf,e.engine),f=Mc.find(b=>b.value===e.engine)?.label||e.engine,m=typeof e.api_key=="string"&&e.api_key.length>0,g=Po(e.api_key),h=e.is_active!==!1;return n.jsxs("div",{className:"group flex h-full cursor-pointer flex-col gap-3 rounded-xl border border-border bg-card p-4 transition-colors hover:border-muted-fg/50",onClick:t,children:[n.jsxs("div",{className:"flex items-start gap-3",children:[n.jsx("div",{className:ge("flex size-10 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br",l),children:n.jsx(d,{className:"size-5 text-white"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("h3",{className:"truncate text-sm font-semibold",children:e.name||e.slug}),n.jsx("p",{className:"truncate font-mono text-[10px] text-muted-fg",children:e.slug}),n.jsxs("span",{className:ge("mt-1 inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-medium",c),children:[n.jsx(d,{className:"size-3"})," ",f]})]}),n.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[n.jsx(qe,{content:u(h?"providers_modal.toggle_active":"providers_modal.toggle_inactive"),children:n.jsxs("button",{type:"button",onClick:b=>{b.stopPropagation(),o()},className:ge("flex items-center gap-1 rounded-md border px-1.5 py-0.5 text-[10px] font-medium transition-colors",h?"border-emerald-500/40 text-emerald-400 hover:bg-emerald-500/10":"border-border text-muted-fg hover:text-foreground"),children:[n.jsx("span",{className:ge("size-1.5 rounded-full",h?"bg-emerald-400":"bg-muted-fg/40")}),u(h?"providers_card.active":"providers_card.off")]})}),n.jsx(qe,{content:u("providers_modal.delete"),children:n.jsx("button",{type:"button",onClick:b=>{b.stopPropagation(),a()},className:"rounded-md p-1 text-muted-fg hover:bg-destructive/10 hover:text-destructive",children:n.jsx(_n,{className:"size-3.5"})})})]})]}),n.jsxs("div",{className:"mt-auto space-y-1 text-xs",children:[n.jsx(hc,{label:u("providers_card.model"),value:e.default_model||"—",mono:!0}),e.base_url&&n.jsx(hc,{label:u("providers_card.base_url"),value:e.base_url,mono:!0,truncate:!0}),n.jsx(hc,{label:u("providers_card.api_key"),value:m?g?`…${g}`:u("providers_card.key_set"):"—",mono:!!g}),e.default_temperature!==void 0&&n.jsx(hc,{label:u("providers_card.temp"),value:e.default_temperature.toFixed(1)}),e.pricing?.input_per_million!==void 0&&n.jsx(hc,{label:u("providers_card.price_io"),value:`${e.pricing.input_per_million??0} / ${e.pricing.output_per_million??0}`})]})]})}function hc({label:e,value:t,mono:a,truncate:o}){return n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("span",{className:"text-muted-fg",children:e}),n.jsx("span",{className:ge("text-foreground",a&&"font-mono",o&&"max-w-[180px] truncate"),children:t})]})}const Kk={name:"",slug:"",engine:"anthropic",base_url:"",api_key_value:"",default_model:"",default_temperature:.7,default_max_tokens:4096,is_active:!0,context_limit_tokens:2e5,model_context_limits_json:"",p_input:"",p_output:"",p_cache_read:"",p_cache_write:""},gI=["anthropic","openai","gemini","groq","openrouter","ollama","custom"];function xc(e){return e.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Ud(e){if(e==null)return"";const t=Number(e);return Number.isFinite(t)?String(t):""}function hI(e){return{name:e.name||e.slug,slug:e.slug,engine:e.engine||"custom",base_url:e.base_url||"",api_key_value:"",default_model:e.default_model||"",default_temperature:e.default_temperature??.7,default_max_tokens:e.default_max_tokens??4096,is_active:e.is_active!==!1,context_limit_tokens:e.context_limit_tokens??2e5,model_context_limits_json:e.model_context_limits?JSON.stringify(e.model_context_limits,null,2):"",p_input:Ud(e.pricing?.input_per_million),p_output:Ud(e.pricing?.output_per_million),p_cache_read:Ud(e.pricing?.cache_read_per_million),p_cache_write:Ud(e.pricing?.cache_write_per_million)}}function xI({open:e,initial:t,existingSlugs:a,onClose:o,onSave:l}){const c=!!t,[d,f]=x.useState(Kk),[m,g]=x.useState(!1),[h,b]=x.useState(null),[_,j]=x.useState([]),[E,y]=x.useState(!1),[k,N]=x.useState(null),[w,S]=x.useState(!1),[R,A]=x.useState("");x.useEffect(()=>{if(!e)return;const Q=t?hI(t):Kk;f(Q),b(null),N(null),S(!1);const W=Za[Q.engine];j(W?.known_models||[])},[e,t]);const T=Q=>f(W=>({...W,...Q})),z=Q=>{const W=Za[Q];T({engine:Q,name:Q==="custom"?d.name:Mc.find(I=>I.value===Q)?.label||Q,slug:Q==="custom"?d.slug:Q,base_url:W.base_url,default_model:W.default_model}),j(W.known_models),N(null)},M=Q=>{const W=Za[Q];T({engine:Q,base_url:d.base_url||W.base_url,default_model:d.default_model||W.default_model}),j(W.known_models)},L=async()=>{y(!0),N(null);try{const Q=await Hc.models({engine:d.engine,slug:d.slug||xc(d.name),base_url:d.base_url||void 0,api_key:d.api_key_value||void 0});if(Q.error){N(Q.error);return}j(Q.models),Q.models.length===0&&N(u("providers_modal.err_no_models"))}catch(Q){N(Q.message||u("providers_modal.err_list_models"))}finally{y(!1)}},P=x.useMemo(()=>d.default_model&&!_.includes(d.default_model)?[d.default_model,..._]:_,[_,d.default_model]),B=()=>{const Q=(d.slug||xc(d.name)).trim();if(!Q)return b(u("providers_modal.err_slug_required")),null;if(!c&&a.includes(Q))return b(u("providers_modal.err_slug_exists",{slug:Q})),null;let W;if(d.model_context_limits_json.trim())try{const ee=JSON.parse(d.model_context_limits_json);if(!ee||typeof ee!="object"||Array.isArray(ee))throw new Error;W=ee}catch{return b(u("providers_modal.err_model_limits_json")),null}const K=[d.p_input,d.p_output,d.p_cache_read,d.p_cache_write].map(ee=>ee.trim()).some(Boolean)?{input_per_million:Number(d.p_input||0),output_per_million:Number(d.p_output||0),cache_read_per_million:Number(d.p_cache_read||0),cache_write_per_million:Number(d.p_cache_write||0)}:void 0;return{provider:{slug:Q,name:d.name.trim()||Q,engine:d.engine,base_url:d.base_url.trim()||void 0,default_model:d.default_model.trim()||void 0,default_temperature:d.default_temperature,default_max_tokens:d.default_max_tokens,is_active:d.is_active,context_limit_tokens:d.context_limit_tokens||void 0,model_context_limits:W,pricing:K},modelLimits:W}},D=()=>{const Q=B();if(!Q)return;const{provider:W}=Q,I={name:W.name,engine:W.engine,is_active:W.is_active!==!1,default_temperature:W.default_temperature,default_max_tokens:W.default_max_tokens};W.base_url&&(I.base_url=W.base_url),W.default_model&&(I.default_model=W.default_model),W.context_limit_tokens&&(I.context_limit_tokens=W.context_limit_tokens),W.model_context_limits&&(I.model_context_limits=W.model_context_limits),W.pricing&&(I.pricing=W.pricing),d.api_key_value.trim()&&(I.api_key=d.api_key_value.trim()),A(JSON.stringify(I,null,2)),b(null),S(!0)},$=async()=>{g(!0),b(null);try{if(w){const W=(d.slug||xc(d.name)).trim();if(!W){b(u("providers_modal.err_slug_required_form"));return}let I;try{I=JSON.parse(R)}catch{b(u("providers_modal.err_json_invalid"));return}if(!I||typeof I!="object"||Array.isArray(I)){b(u("providers_modal.err_json_object"));return}const K=I;if(!K.engine||typeof K.engine!="string"){b(u("providers_modal.err_engine_missing"));return}const ee={slug:W,name:typeof K.name=="string"?K.name:W,engine:String(K.engine),base_url:typeof K.base_url=="string"?K.base_url:void 0,default_model:typeof K.default_model=="string"?K.default_model:void 0,is_active:K.is_active!==!1};await l({provider:ee,raw:K,originalSlug:t?.slug}),o();return}const Q=B();if(!Q)return;await l({provider:Q.provider,apiKeyValue:d.api_key_value.trim()||void 0,originalSlug:t?.slug}),o()}catch(Q){b(Q.message||u("providers_modal.err_save"))}finally{g(!1)}},q=c&&ps(t?.api_key),G=Po(t?.api_key),U=q?u("providers_modal.api_key_set",{suffix:G??""}):"sk-…",V=d.engine==="ollama",X=Za[d.engine]?.api_key_env;return n.jsx(Xt,{open:e,onClose:o,title:c?u("providers_modal.edit_title",{name:t?.name||t?.slug||""}):u("providers_modal.new_title"),description:u("providers_modal.description"),size:"lg",footer:n.jsxs(n.Fragment,{children:[n.jsx(re,{variant:"ghost",onClick:o,disabled:m,children:u("common.cancel")}),n.jsx(re,{variant:"primary",onClick:$,loading:m,children:u(c?"common.save":"common.create")})]}),children:n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[c?n.jsx("span",{}):n.jsx("div",{className:"flex flex-wrap gap-1.5",children:gI.map(Q=>{const W=Pf[Q],I=Q==="custom"?u("providers_modal.custom"):Mc.find(ee=>ee.value===Q)?.label||Q,K=d.engine===Q;return n.jsxs("button",{type:"button",onClick:()=>z(Q),className:`flex items-center gap-1.5 rounded-lg border px-2.5 py-1 text-xs transition-colors ${K?"border-emerald-500/50 bg-emerald-500/10 text-emerald-400":"border-border text-muted-fg hover:border-muted-fg/60 hover:text-foreground"}`,children:[n.jsx(W,{className:"size-3.5"})," ",I]},Q)})}),n.jsxs("button",{type:"button",onClick:()=>w?S(!1):D(),className:`flex shrink-0 items-center gap-1.5 rounded-lg border px-2.5 py-1 text-xs transition-colors ${w?"border-sky-500/50 bg-sky-500/10 text-sky-400":"border-border text-muted-fg hover:text-foreground"}`,children:[n.jsx(yA,{className:"size-3.5"})," ",u(w?"providers_modal.form_mode":"providers_modal.json_mode")]})]}),w?n.jsxs("div",{className:"space-y-2",children:[n.jsx(ie,{label:u("providers_modal.json_label"),hint:u("providers_modal.json_hint",{slug:d.slug||xc(d.name)||"<slug>"}),children:n.jsx(un,{rows:14,className:"font-mono text-xs",value:R,onChange:Q=>A(Q.target.value),spellCheck:!1})}),n.jsx("p",{className:"text-[11px] text-muted-fg",children:u("providers_modal.json_help")})]}):n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsx(ie,{label:u("providers_modal.name_label"),children:n.jsx(Ee,{value:d.name,onChange:Q=>T({name:Q.target.value,slug:c?d.slug:xc(Q.target.value)}),placeholder:u("providers_modal.name_ph")})}),n.jsx(ie,{label:u("providers_modal.engine_label"),children:n.jsx(ct,{value:d.engine,onChange:Q=>M(Q),options:Mc.map(Q=>({value:Q.value,label:Q.label,icon:Pf[Q.value]}))})})]}),n.jsx(ie,{label:u("providers_modal.base_url_label"),hint:u("providers_modal.base_url_hint"),children:n.jsx(Ee,{value:d.base_url,onChange:Q=>T({base_url:Q.target.value}),placeholder:u("providers_modal.base_url_ph")})}),!V&&n.jsx(ie,{label:u("providers_modal.api_key_label"),hint:q?u("providers_modal.api_key_hint_existing"):X?u("providers_modal.api_key_hint_env",{env:X}):u("providers_modal.api_key_hint"),children:n.jsx(Ee,{type:"password",autoComplete:"new-password",value:d.api_key_value,onChange:Q=>T({api_key_value:Q.target.value}),placeholder:U})}),n.jsx(ie,{label:u("providers_modal.model_label"),children:n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx(aE,{value:d.default_model,onChange:Q=>T({default_model:Q}),options:P,className:"flex-1"}),n.jsx(qe,{content:u("providers_modal.list_models_hint"),children:n.jsxs(re,{size:"sm",variant:"secondary",onClick:L,disabled:E,"aria-label":u("providers_modal.list_models_hint"),children:[E?n.jsx(Js,{className:"size-3.5 animate-spin"}):n.jsx(Cs,{className:"size-3.5"}),u("providers_modal.load_models")]})})]}),k&&n.jsx("p",{className:"text-[11px] text-amber-400",children:k})]})}),n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsx(ie,{label:u("providers_modal.max_tokens_label"),children:n.jsx(Ee,{type:"number",min:256,step:256,value:d.default_max_tokens,onChange:Q=>T({default_max_tokens:parseInt(Q.target.value)||4096})})}),n.jsx(ie,{label:u("providers_modal.temperature_label",{value:d.default_temperature.toFixed(1)}),children:n.jsx("input",{type:"range",min:0,max:2,step:.1,value:d.default_temperature,onChange:Q=>T({default_temperature:parseFloat(Q.target.value)}),className:"mt-2 w-full accent-foreground"})})]}),n.jsxs("details",{className:"rounded-md border border-border bg-muted/20 p-3",children:[n.jsx("summary",{className:"cursor-pointer text-xs font-medium text-muted-fg",children:u("providers_modal.pricing_summary")}),n.jsxs("div",{className:"mt-3 space-y-3",children:[n.jsx(ie,{label:u("providers_modal.context_limit_label"),children:n.jsx(Ee,{type:"number",min:0,step:1024,value:d.context_limit_tokens,onChange:Q=>T({context_limit_tokens:parseInt(Q.target.value)||0})})}),n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsx(ie,{label:u("providers_modal.price_input"),children:n.jsx(Ee,{type:"number",min:0,step:1e-4,value:d.p_input,onChange:Q=>T({p_input:Q.target.value}),placeholder:"0.15"})}),n.jsx(ie,{label:u("providers_modal.price_output"),children:n.jsx(Ee,{type:"number",min:0,step:1e-4,value:d.p_output,onChange:Q=>T({p_output:Q.target.value}),placeholder:"0.60"})}),n.jsx(ie,{label:u("providers_modal.price_cache_read"),children:n.jsx(Ee,{type:"number",min:0,step:1e-4,value:d.p_cache_read,onChange:Q=>T({p_cache_read:Q.target.value}),placeholder:"0.03"})}),n.jsx(ie,{label:u("providers_modal.price_cache_write"),children:n.jsx(Ee,{type:"number",min:0,step:1e-4,value:d.p_cache_write,onChange:Q=>T({p_cache_write:Q.target.value}),placeholder:"0.00"})})]}),n.jsx(ie,{label:u("providers_modal.model_limits_label"),hint:'{"gpt-4o-mini":128000}',children:n.jsx(un,{rows:3,className:"font-mono text-xs",value:d.model_context_limits_json,onChange:Q=>T({model_context_limits_json:Q.target.value})})})]})]}),n.jsx(Bt,{checked:d.is_active,onChange:Q=>T({is_active:Q}),label:u("providers_modal.active_label")})]}),h&&n.jsx("div",{className:"rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:h})]})})}const bI=new Set(Mc.map(e=>e.value));function _I(e,t){const a=typeof t.engine=="string"&&t.engine||(bI.has(e)?e:"custom");return{slug:e,name:typeof t.name=="string"?t.name:void 0,engine:a,base_url:typeof t.base_url=="string"?t.base_url:void 0,api_key:typeof t.api_key=="string"?t.api_key:void 0,default_model:typeof t.default_model=="string"?t.default_model:void 0,default_temperature:typeof t.default_temperature=="number"?t.default_temperature:void 0,default_max_tokens:typeof t.default_max_tokens=="number"?t.default_max_tokens:void 0,is_active:typeof t.is_active=="boolean"?t.is_active:void 0,context_limit_tokens:typeof t.context_limit_tokens=="number"?t.context_limit_tokens:void 0,model_context_limits:t.model_context_limits||void 0,pricing:t.pricing||void 0}}function vI(){const e=Je(),{config:t,isLoading:a,patch:o,mutate:l}=ur(),[c,d]=x.useState(!1),[f,m]=x.useState(null);if(a)return n.jsx(st,{});const g=t.engines||{},h=Object.entries(g).map(([N,w])=>_I(N,w||{})),b=h.map(N=>N.slug),_=()=>{m(null),d(!0)},j=N=>{m(N),d(!0)},E=async({provider:N,apiKeyValue:w,raw:S})=>{if(S){await o({[`engines.${N.slug}`]:S}),e.success(u("engines_panel.saved_json")),l();return}const R=`engines.${N.slug}`,A={[`${R}.name`]:N.name,[`${R}.engine`]:N.engine,[`${R}.is_active`]:N.is_active!==!1,[`${R}.default_temperature`]:N.default_temperature,[`${R}.default_max_tokens`]:N.default_max_tokens},T=[],z=(M,L)=>{L===void 0||L===""?T.push(`${R}.${M}`):A[`${R}.${M}`]=L};z("base_url",N.base_url),z("default_model",N.default_model),z("context_limit_tokens",N.context_limit_tokens),z("pricing",N.pricing),z("model_context_limits",N.model_context_limits),w&&(A[`${R}.api_key`]=w),await o(A,T),e.success(u("engines_panel.saved")),l()},y=async N=>{try{await o({[`engines.${N.slug}.is_active`]:N.is_active===!1}),l()}catch(w){e.error(w.message)}},k=async N=>{if(confirm(u("engines_panel.delete_confirm",{name:N.name||N.slug})))try{await o(void 0,[`engines.${N.slug}`]),e.success(u("engines_panel.deleted")),l()}catch(w){e.error(w.message)}};return n.jsxs(Ve,{title:u("engines_panel.title"),description:u("engines_panel.description"),action:n.jsxs(re,{size:"sm",variant:"primary",onClick:_,children:[n.jsx(Dt,{size:14})," ",u("engines_panel.new_btn")]}),children:[h.length===0?n.jsx(ft,{children:u("engines_panel.empty")}):n.jsxs("div",{className:"grid grid-cols-1 items-stretch gap-3 sm:grid-cols-2 lg:grid-cols-3",children:[h.map(N=>n.jsx(mI,{provider:N,onEdit:()=>j(N),onDelete:()=>k(N),onToggle:()=>y(N)},N.slug)),n.jsxs("button",{type:"button",onClick:_,className:"flex min-h-[120px] flex-col items-center justify-center gap-2 rounded-xl border border-dashed border-border text-muted-fg transition-colors hover:border-muted-fg/60 hover:text-foreground",children:[n.jsx(Dt,{size:20}),n.jsx("span",{className:"text-sm font-medium",children:u("engines_panel.add_card")})]})]}),n.jsx(xI,{open:c,initial:f,existingSlugs:b,onClose:()=>{d(!1),m(null)},onSave:E})]})}function lE(){return n.jsxs("div",{className:"space-y-6",children:[n.jsx(uI,{}),n.jsx(pI,{}),n.jsx(vI,{})]})}function yI(){const e=Je(),[t,a]=x.useState(!1),l=Be(t?"/agents/vault?include_removed=1":"/agents/vault",()=>an.vault({includeRemoved:t})),c=l.data||[],[d,f]=x.useState(null),m=async h=>{const b=h.source!=="user",_=b?u("base.defaults_tombstone_msg",{slug:h.slug}):u("base.defaults_delete_msg",{slug:h.slug});if(confirm(_))try{await an.vaultRemove(h.slug),e.success(u(b?"base.defaults_hidden":"base.defaults_deleted")),l.mutate()}catch(j){e.error(j.message)}},g=async h=>{try{await an.vaultRestore(h),e.success(u("base.defaults_restored")),l.mutate()}catch(b){e.error(b.message)}};return n.jsxs(Ve,{title:u("base.defaults_title"),description:u("base.defaults_desc"),action:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Bt,{checked:t,onChange:a,label:u("base.defaults_show_removed")}),n.jsxs(re,{size:"sm",onClick:()=>f("new"),children:[n.jsx(Dt,{size:14})," ",u("base.defaults_new")]})]}),children:[l.isLoading&&n.jsx(st,{}),!l.isLoading&&c.length===0&&n.jsx(ft,{children:u("base.defaults_empty")}),n.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:c.map(h=>{const b=t&&h.tombstoned;return n.jsxs("div",{className:`flex flex-col gap-2 rounded-xl border bg-card p-4 ${b?"border-dashed border-border opacity-60":"border-border"}`,children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[n.jsx("div",{className:"flex size-9 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-slate-600 to-gray-600",children:h.is_master?n.jsx(va,{className:"size-4 text-white"}):n.jsx(rn,{className:"size-4 text-white"})}),n.jsx("span",{className:"truncate text-sm font-semibold",children:h.slug}),n.jsx(jI,{source:h.source})]}),n.jsx("div",{className:"flex shrink-0 items-center gap-0.5",children:b?n.jsx(yh,{label:u("base.defaults_restore"),onClick:()=>g(h.slug),variant:"secondary",children:n.jsx(fi,{size:13})}):n.jsxs(n.Fragment,{children:[n.jsx(yh,{label:u("base.defaults_edit"),onClick:()=>f(h),variant:"ghost",children:n.jsx(wa,{size:13})}),n.jsx(yh,{label:h.source==="user"?u("base.defaults_delete"):u("base.defaults_hide"),onClick:()=>m(h),variant:"ghost-destructive",children:n.jsx(_n,{size:13})})]})})]}),h.model?n.jsx($e,{tone:"info",children:h.model}):n.jsx("span",{className:"text-[10px] text-muted-fg",children:u("agents_ui.model_router_default")}),h.description&&n.jsx("p",{className:"line-clamp-3 text-xs text-muted-fg",children:h.description}),n.jsxs("div",{className:"flex flex-wrap gap-1",children:[h.role&&n.jsx($e,{children:h.role}),h.skills?.map(_=>n.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded bg-muted px-1 py-0.5 text-[9px] text-muted-fg",children:[n.jsx(sa,{size:9})," ",_]},_)),h.tools?.map(_=>n.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded bg-muted px-1 py-0.5 text-[9px] text-muted-fg",children:[n.jsx(aa,{size:9})," ",_]},_))]})]},h.slug)})}),d!==null&&n.jsx(kI,{agent:d==="new"?null:d,onClose:()=>f(null),onSaved:()=>{f(null),l.mutate()}})]})}function jI({source:e}){return e==="user"?n.jsx($e,{tone:"success",children:u("agents_ui.source_user")}):e==="user-override"?n.jsx($e,{tone:"warning",children:u("agents_ui.source_override")}):n.jsx($e,{tone:"muted",children:u("agents_ui.source_bundled")})}function yh({label:e,onClick:t,variant:a="ghost",children:o}){const l="inline-flex size-7 items-center justify-center rounded-md transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40",c={ghost:"text-muted-fg hover:bg-accent hover:text-accent-fg","ghost-destructive":"text-muted-fg hover:bg-destructive/15 hover:text-destructive",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80"};return n.jsxs(m_,{children:[n.jsx(g_,{render:n.jsx("button",{type:"button",onClick:t,"aria-label":e,className:`${l} ${c[a]}`,children:o})}),n.jsx(h_,{children:e})]})}function kI({agent:e,onClose:t,onSaved:a}){const o=Je(),[l,c]=x.useState(!1),d=!e,[f,m]=x.useState(e?.slug??""),[g,h]=x.useState(e?.role??""),[b,_]=x.useState(e?.model??""),[j,E]=x.useState(e?.description??""),[y,k]=x.useState(e?.language??"es"),[N,w]=x.useState((e?.skills??[]).join(", ")),[S,R]=x.useState((e?.tools??[]).join(", ")),[A,T]=x.useState(!!e?.is_master),[z,M]=x.useState(e?.body??""),L=async()=>{const P={role:g||void 0,model:b||void 0,description:j||void 0,language:y||void 0,skills:N,tools:S,is_master:A};c(!0);try{if(d){if(!/^[a-z][a-z0-9_-]*$/.test(f))throw new Error(u("base.defaults_slug_invalid"));await an.vaultCreate(f,P,z),o.success(u("base.defaults_created",{slug:f}))}else await an.vaultPatch(e.slug,{fields:P,body:z}),o.success(u("base.defaults_saved",{slug:e.slug}));a()}catch(B){o.error(B.message)}finally{c(!1)}};return n.jsx(Xt,{open:!0,onClose:t,title:d?u("base.defaults_new_title"):u("base.defaults_edit_title",{slug:e.slug}),description:d?u("base.defaults_new_desc"):e.source==="bundled"?u("base.defaults_bundled_desc"):u("base.defaults_user_desc"),size:"lg",footer:n.jsxs(n.Fragment,{children:[n.jsx(re,{variant:"ghost",onClick:t,disabled:l,children:u("common.cancel")}),n.jsx(re,{variant:"primary",onClick:L,loading:l,children:u("common.save")})]}),children:n.jsxs("div",{className:"space-y-3",children:[d&&n.jsx(ie,{label:"slug",hint:u("agents_ui.slug_kebab_hint"),children:n.jsx(Ee,{autoFocus:!0,value:f,onChange:P=>m(P.target.value),placeholder:"reviewer"})}),n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsx(ie,{label:"role",children:n.jsx(Ee,{value:g,onChange:P=>h(P.target.value),placeholder:"Code reviewer"})}),n.jsx(ie,{label:"model",children:n.jsx(Ee,{value:b,onChange:P=>_(P.target.value),placeholder:"openrouter:..."})}),n.jsx(ie,{label:"language",children:n.jsx(Ee,{value:y,onChange:P=>k(P.target.value),placeholder:"es"})}),n.jsx(ie,{label:"is_master",children:n.jsx("div",{className:"flex h-9 items-center",children:n.jsx(Bt,{checked:A,onChange:T,label:u("base.defaults_master_label")})})})]}),n.jsx(ie,{label:"description",children:n.jsx(Ee,{value:j,onChange:P=>E(P.target.value)})}),n.jsx(ie,{label:"skills",hint:u("agents_ui.comma_separated"),children:n.jsx(Ee,{value:N,onChange:P=>w(P.target.value),placeholder:"code-review, git"})}),n.jsx(ie,{label:"tools",hint:u("agents_ui.comma_separated"),children:n.jsx(Ee,{value:S,onChange:P=>R(P.target.value),placeholder:"read, write, run"})}),n.jsx(ie,{label:"body",hint:u("agents_ui.body_hint"),children:n.jsx(un,{value:z,onChange:P=>M(P.target.value),rows:10,placeholder:"# Mission\\n..."})})]})})}const wI=20,Xk=[10,20,50,100];function F_({key:e,fetchPage:t,resetKey:a,initialPageSize:o=wI,swr:l}){const[c,d]=x.useState(1),[f,m]=x.useState(o);x.useEffect(()=>{d(1)},[a]);const g=(c-1)*f,h=Be(e==null?null:[e,f,g],()=>t(f,g),{keepPreviousData:!0,...l}),b=h.data?.total??0,_=Math.max(1,Math.ceil(b/f)),j=Math.min(c,_);x.useEffect(()=>{c!==j&&d(j)},[c,j]);const E=b===0?0:g,y=Math.min(g+f,b);return{items:h.data?.items??[],isLoading:h.isLoading,error:h.error,mutate:h.mutate,page:j,pageCount:_,total:b,start:E,end:y,pageSize:f,setPage:d,setPageSize:k=>{m(k),d(1)}}}function SI({page:e,pageCount:t,total:a,start:o,end:l,pageSize:c,onPage:d,onPageSize:f}){return a<=Xk[0]?null:n.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-3 text-xs text-muted-fg",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("span",{className:"tabular-nums",children:u("common.pager_range",{from:o+1,to:l,total:a})}),n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx("span",{children:u("common.pager_per_page")}),n.jsx("div",{className:"w-[4.5rem]",children:n.jsx(ct,{value:String(c),onChange:m=>f(Number(m)),options:Xk.map(m=>({value:String(m),label:String(m)}))})})]})]}),n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx(re,{size:"sm",variant:"ghost",disabled:e<=1,onClick:()=>d(e-1),"aria-label":u("common.pager_prev"),children:n.jsx(wA,{size:14})}),n.jsx("span",{className:"px-1 tabular-nums",children:u("common.pager_page",{page:e,total:t})}),n.jsx(re,{size:"sm",variant:"ghost",disabled:e>=t,onClick:()=>d(e+1),"aria-label":u("common.pager_next"),children:n.jsx(Zr,{size:14})})]})]})}function G_({paged:e,fullHeight:t,className:a,children:o}){const l=n.jsx(SI,{page:e.page,pageCount:e.pageCount,total:e.total,start:e.start,end:e.end,pageSize:e.pageSize,onPage:e.setPage,onPageSize:e.setPageSize});return t?n.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",children:[n.jsx("div",{className:ge("min-h-0 flex-1 overflow-y-auto",a),children:o}),n.jsx("div",{className:"shrink-0",children:l})]}):n.jsxs("div",{className:a,children:[o,l]})}const CI={apx:"success",claude:"info",codex:"warning"};function NI({pid:e}={}){const t=Je(),a=yp(),o=!e||String(e)==="0",{project:l}=cu(o?"":e),c=o?void 0:l?.path||void 0,[d,f]=x.useState(""),[m,g]=x.useState(""),[h,b]=x.useState(""),[_,j]=x.useState(!1);x.useEffect(()=>{const R=setTimeout(()=>b(m.trim()),350);return()=>clearTimeout(R)},[m]);const E=F_({key:`/sessions?engine=${d}&q=${h}&deep=${_?1:0}&cwd=${c||""}`,fetchPage:(R,A)=>cP.page({engine:d||void 0,q:h||void 0,deep:_,cwd:c,limit:R,offset:A}),resetKey:`${d}|${h}|${_?1:0}|${c||""}`}),y=()=>{g(""),b(""),f(""),j(!1)},k=async R=>{try{await navigator.clipboard.writeText(`apx session resume ${R.id} --continue`),t.success(u("base.sessions_cmd_copied"))}catch{t.error(u("base.sessions_copy_failed"))}},N=R=>{const A=`Continue this session: ${R.id} (engine: ${R.engine}${R.title?`, title: "${R.title}"`:""}${R.cwd?`, folder: ${R.cwd}`:""}). With these instructions: `;window.dispatchEvent(new CustomEvent("apx:roby-prompt",{detail:{prompt:A}}))},w=async R=>{if(!R.cwd){t.error(u("base.sessions_no_folder"));return}try{await gN.exec({kind:"open_path",target:R.cwd})}catch(A){t.error(u("base.sessions_folder_failed",{msg:A.message}))}},S=async R=>{const A=R.path||R.cwd;if(!A){t.error(u("base.sessions_no_path"));return}try{await navigator.clipboard.writeText(A),t.success(u("base.sessions_path_copied"))}catch{t.error(u("base.sessions_copy_failed"))}};return n.jsxs(Ve,{fullHeight:!0,title:u("base.sessions_title"),description:o?u("base.sessions_desc"):u("base.sessions_desc_scoped",{path:c||"…"}),action:n.jsx(qe,{content:u("base.sessions_refresh"),children:n.jsx(re,{size:"sm",variant:"secondary",onClick:()=>E.mutate(),children:n.jsx(Cs,{size:13})})}),children:[n.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[n.jsxs("div",{className:"relative flex-1",children:[n.jsx(ql,{size:14,className:"pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-muted-fg"}),n.jsx(Ee,{className:"pl-8",placeholder:u("base.sessions_search_ph"),value:m,onChange:R=>g(R.target.value)})]}),n.jsx(qe,{content:u("base.sessions_deep_tip"),children:n.jsx(re,{size:"sm",variant:_?"primary":"secondary",onClick:()=>j(R=>!R),children:u("base.sessions_deep")})}),n.jsx("div",{className:"w-36",children:n.jsx(ct,{value:d,onChange:f,options:[{value:"",label:u("base.sessions_all")},{value:"apx",label:"apx"},{value:"claude",label:"claude"},{value:"codex",label:"codex"}]})}),n.jsx(qe,{content:u("base.sessions_clear"),children:n.jsx(re,{size:"sm",variant:"ghost",onClick:y,children:n.jsx(gs,{size:14})})})]}),E.isLoading&&n.jsx(st,{}),E.error&&n.jsx(ft,{children:u("base.sessions_error",{msg:E.error.message})}),!E.isLoading&&!E.error&&E.total===0&&n.jsx(ft,{children:h?u("base.sessions_no_match",{q:h}):u("base.sessions_empty")}),n.jsx(G_,{paged:E,fullHeight:!0,children:n.jsx("ul",{className:"space-y-1 text-sm",children:E.items.map((R,A)=>n.jsxs("li",{className:"group flex items-center gap-3 rounded-md border border-border bg-muted/30 px-3 py-2",children:[n.jsx($e,{tone:CI[R.engine]||"muted",children:R.engine}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("div",{className:"truncate",children:R.title||R.id}),n.jsxs("div",{className:"flex items-center gap-2 font-mono text-[10px] text-muted-fg",children:[n.jsx("span",{className:"shrink-0",children:R.id}),R.cwd&&n.jsxs("span",{className:"truncate",children:["· ",R.cwd]})]})]}),R.mtime>0&&n.jsx("span",{className:"shrink-0 text-[11px] text-muted-fg",children:new Date(R.mtime).toLocaleString()}),n.jsxs("div",{className:"flex shrink-0 items-center gap-0.5 opacity-60 transition-opacity group-hover:opacity-100",children:[n.jsx(qe,{content:u("base.sessions_act_cmd"),children:n.jsx(re,{size:"sm",variant:"ghost","aria-label":u("base.sessions_act_cmd"),onClick:()=>k(R),children:n.jsx(ya,{size:13})})}),n.jsx(qe,{content:u("base.sessions_act_ask",{name:a}),children:n.jsx(re,{size:"sm",variant:"ghost","aria-label":u("base.sessions_act_ask",{name:a}),onClick:()=>N(R),children:n.jsx(rn,{size:13})})}),n.jsx(qe,{content:u("base.sessions_act_folder"),children:n.jsx(re,{size:"sm",variant:"ghost","aria-label":u("base.sessions_act_folder"),onClick:()=>w(R),children:n.jsx(qo,{size:13})})}),n.jsx(qe,{content:u("base.sessions_act_path"),children:n.jsx(re,{size:"sm",variant:"ghost","aria-label":u("base.sessions_act_path"),onClick:()=>S(R),children:n.jsx(Ao,{size:13})})})]})]},`${R.engine}-${R.id}-${A}`))})})]})}function EI(){const e=Pn(),[t,a]=x.useState("open"),o=F_({key:`/tasks?state=${t}`,fetchPage:(l,c)=>Qn.globalPage({state:t,limit:l,offset:c}),resetKey:t});return n.jsxs(Ve,{fullHeight:!0,title:u("project.global_tasks.title"),description:u("project.global_tasks.subtitle"),action:n.jsx("div",{className:"flex gap-1",children:["open","done","dropped","all"].map(l=>n.jsx(re,{size:"sm",variant:t===l?"primary":"ghost",onClick:()=>a(l),children:l},l))}),children:[o.isLoading&&n.jsx(st,{}),!o.isLoading&&o.total===0&&n.jsx(ft,{children:u("project.global_tasks.empty")}),n.jsx(G_,{paged:o,fullHeight:!0,children:n.jsx("ul",{className:"space-y-2 text-sm",children:o.items.map(l=>n.jsxs("li",{className:"flex items-start gap-3 rounded-md border border-border bg-muted/30 px-3 py-2",children:[n.jsx("button",{type:"button",onClick:()=>e(`/p/${l.project_id}/tasks`),title:u("project.global_tasks.go_project"),children:n.jsx($e,{tone:"info",children:(l.project_name||"").split("/").pop()||l.project_id})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("div",{className:"font-medium",children:l.title}),n.jsxs("div",{className:"mt-0.5 flex flex-wrap items-center gap-2 text-xs text-muted-fg",children:[n.jsx("span",{children:l.state}),l.agent&&n.jsxs($e,{tone:"muted",children:["@",l.agent]}),l.tags?.map(c=>n.jsxs("span",{children:["#",c]},c)),l.due&&n.jsxs("span",{children:[u("project.global_tasks.due")," ",l.due]})]})]})]},`${l.project_id}-${l.id}`))})})]})}const iE=x.createContext(void 0);function Y_(){const e=x.useContext(iE);if(e===void 0)throw new Error(gn(64));return e}const Cp={tabActivationDirection:e=>({"data-activation-direction":e})},RI=x.forwardRef(function(t,a){const{className:o,defaultValue:l=0,onValueChange:c,orientation:d="horizontal",render:f,value:m,style:g,...h}=t,b=t.defaultValue!==void 0,_=x.useRef([]),[j,E]=x.useState(()=>new Map),[y,k]=ni({controlled:m,default:l,name:"Tabs",state:"value"}),N=m!==void 0,[w,S]=x.useState(()=>new Map),R=x.useRef(void 0),A=x.useCallback(Y=>Yx(w,Y),[w]),[T,z]=x.useState(()=>({previousValue:y,tabActivationDirection:"none"})),{previousValue:M,tabActivationDirection:L}=T;let P=L,B=!1;M!==y&&(P=Qk(M,y,d,w),B=M!=null&&y!=null&&A(y)==null);const D=B?M:y,$=M!==D||L!==P;Pe(()=>{$&&z({previousValue:D,tabActivationDirection:P})},[D,$,P]);const q=He((Y,oe)=>{const ve=Qk(y,Y,d,w);oe.activationDirection=ve,c?.(Y,oe),!oe.isCanceled&&k(Y)}),G=He((Y,oe)=>{c?.(Y,rt(oe,void 0,void 0,{activationDirection:"none"}))}),U=He((Y,oe)=>(E(ve=>{const le=new Map(ve);return le.set(Y,oe),le}),()=>{E(ve=>{if(ve.get(Y)!==oe)return ve;const le=new Map(ve);return le.delete(Y),le})})),V=x.useCallback(Y=>j.get(Y),[j]),X=x.useCallback(Y=>{for(const oe of w.values())if(Y===oe.value)return oe.id},[w]),Q=x.useMemo(()=>({getTabElementBySelectedValue:A,getTabIdByPanelValue:X,getTabPanelIdByValue:V,onValueChange:q,orientation:d,registerMountedTabPanel:U,setTabMap:S,tabActivationDirection:P,value:y}),[A,X,V,q,d,U,S,P,y]),W=x.useMemo(()=>{for(const Y of w.values())if(Y.value===y)return Y},[w,y]),I=x.useMemo(()=>{for(const Y of w.values())if(!Y.disabled)return Y.value},[w]),K=x.useRef(!b),ee=x.useRef(l),F=x.useRef(b),ne=x.useRef(!1);Pe(()=>{if(N)return;function Y(xe,ke){k(xe),z({previousValue:xe,tabActivationDirection:"none"}),G(xe,ke),K.current=!1}if(w.size===0){ne.current&&y!==null&&!R.current?.isConnected&&Y(null,Cj);return}ne.current=!0,R.current=w.keys().next().value;const oe=W?.disabled,ve=W==null&&y!==null;if(!oe&&y===ee.current&&(F.current=!1),F.current&&oe&&y===ee.current)return;const le=K.current;if(oe||ve){const xe=I??null;if(y===xe){K.current=!1;return}let ke=Cj;le?ke=Nj:oe&&(ke=jS),Y(xe,ke);return}le&&W!=null&&(G(y,Nj),K.current=!1)},[I,N,G,W,k,w,y]);const fe=Et("div",t,{state:{orientation:d,tabActivationDirection:P},ref:a,props:h,stateAttributesMapping:Cp});return n.jsx(iE.Provider,{value:Q,children:n.jsx(bp,{elementsRef:_,children:fe})})});function Yx(e,t){for(const[a,o]of e.entries())if(t===o.value)return a;return null}function Qk(e,t,a,o){if(e==null||t==null)return"none";const[l,c,d]=a==="horizontal"?["left","left","right"]:["top","up","down"],f=Yx(o,e),m=Yx(o,t);if(f==null||m==null)return f!==m&&(typeof e=="number"||typeof e=="string")&&typeof e==typeof t?t>e?d:c:"none";const g=f.getBoundingClientRect()[l],h=m.getBoundingClientRect()[l];return h<g?c:h>g?d:"none"}const cE="data-composite-item-active",uE=x.createContext(void 0);function TI(){const e=x.useContext(uE);if(e===void 0)throw new Error(gn(65));return e}const AI=x.forwardRef(function(t,a){const{className:o,disabled:l=!1,render:c,value:d,id:f,nativeButton:m=!0,style:g,...h}=t,{value:b,getTabPanelIdByValue:_,onValueChange:j,orientation:E,tabActivationDirection:y}=Y_(),{activateOnFocus:k,registerTabResizeObserverElement:N,tabsListElement:w}=TI(),{highlightedIndex:S,onHighlightedIndexChange:R}=hp(),A=ra(f),T=x.useMemo(()=>({disabled:l,id:A,value:d}),[l,A,d]),{compositeProps:z,compositeRef:M,index:L}=JC({metadata:T}),P=d===b,B=x.useRef(!1),D=x.useRef(null),$=He(ne=>{D.current?.(),D.current=ne?N(ne):null});Pe(()=>{if(B.current){B.current=!1;return}if(!(P&&L>-1&&S!==L))return;const ne=w;if(ne!=null){const Z=Kn(vt(ne));if(Z&&Ze(ne,Z))return}l||R(L)},[P,L,S,R,l,w]);const{getButtonProps:q,buttonRef:G}=no({disabled:l,native:m,focusableWhenDisabled:!0}),U=_(d),V=x.useRef(!1),X=x.useRef(!1);function Q(ne){j(d,rt(ka,ne.nativeEvent,void 0,{activationDirection:"none"}))}function W(ne){P||l||Q(ne)}function I(ne){P||l||k&&(!V.current||X.current)&&Q(ne)}function K(ne){if(P||l)return;V.current=!0,X.current=ne.button===0;const Z=vt(ne.currentTarget);function fe(){V.current=!1,X.current=!1,Z.removeEventListener("pointerup",fe),Z.removeEventListener("pointercancel",fe)}Z.addEventListener("pointerup",fe),Z.addEventListener("pointercancel",fe)}return Et("button",t,{state:{disabled:l,active:P,orientation:E,tabActivationDirection:y},ref:[a,G,M,$],props:[z,{role:"tab","aria-controls":U,"aria-selected":P,id:A,onClick:W,onFocus:I,onPointerDown:K,[cE]:P?"":void 0,onKeyDownCapture(){B.current=!0}},h,q],stateAttributesMapping:Cp})}),MI={...Cp,...Ho},zI=x.forwardRef(function(t,a){const{className:o,value:l,render:c,keepMounted:d=!1,style:f,...m}=t,{value:g,getTabIdByPanelValue:h,orientation:b,tabActivationDirection:_,registerMountedTabPanel:j}=Y_(),E=ra(),{ref:y,index:k}=ru(),N=l===g,{mounted:w,transitionStatus:S,setMounted:R}=hi(N),A=!w,T=h(l),z={hidden:A,orientation:b,tabActivationDirection:_,transitionStatus:S},M=x.useRef(null),L=Et("div",t,{state:z,ref:[a,y,M],props:[{"aria-labelledby":T,hidden:A,id:E,role:"tabpanel",tabIndex:N?0:-1,inert:gp(!N),"data-index":k},m],stateAttributesMapping:MI});return Ca({open:N,ref:M,onComplete(){N||R(!1)}}),Pe(()=>{if(!(E==null||A&&!d))return j(l,E)},[A,d,l,E,j]),d||w?L:null}),OI=[];function DI(e){const{loopFocus:t=!0,orientation:a="both",grid:o,onLoop:l,direction:c,highlightedIndex:d,onHighlightedIndexChange:f,rootRef:m,enableHomeAndEndKeys:g=!1,stopEventPropagation:h,disabledIndices:b,modifierKeys:_=OI}=e,[j,E]=x.useState(0),y=o!=null,k=x.useRef(null),N=rr(k,m),w=x.useRef([]),S=x.useRef(!1),R=d??j,A=He((P,B=!1)=>{if((f??E)(P),B){const D=w.current[P];fk(k.current,D,c,a)}}),T=He(P=>{if(P.size===0||S.current)return;S.current=!0;const B=Array.from(P.keys()),D=B.find(q=>q?.hasAttribute(cE))??null,$=D?P.get(D)?.index??-1:-1;if($!==-1)A($);else if(xf(B,R,b)){const q=Qa(B,{disabledIndices:b});Rc(B,q)||A(q)}fk(k.current,D,c,a)});Pe(()=>{if(b==null||d!=null||!S.current)return;const P=w.current;if(xf(P,R,b)){const B=Qa(P,{disabledIndices:b});Rc(P,B)||A(B)}},[b,d,R,w,A]);const z=He((P,B,D)=>l?l(P,B,D,w):D),M=He(P=>{const B=P.key===Rx||P.key===Tx;if(!xp.has(P.key)||!g&&B||PI(P,_)||!k.current)return;const $=c==="rtl",q=$?Nx:Ex,G=$?Ex:Nx,U=a==="vertical"?Cx:q,V=a==="vertical"?Sx:G,X=qn(P.nativeEvent);if(X!=null&&dk(X)&&!tN(X)){const F=X.selectionStart,ne=X.selectionEnd,Z=X.value;if(F==null||P.shiftKey||F!==ne||P.key!==V&&F<Z.length||P.key!==U&&F>0)return}let Q=R;const W=ef(w,b),I=vx(w,b);o!=null&&(Q=o({disabledIndices:b,elementsRef:w,event:P,highlightedIndex:R,loopFocus:t,maxIndex:I,minIndex:W,onLoop:z,orientation:a,rtl:$}));const K=a!=="vertical"&&P.key===q||a!=="horizontal"&&P.key===Cx,ee=a!=="vertical"&&P.key===G||a!=="horizontal"&&P.key===Sx;g&&(P.key===Rx?Q=W:P.key===Tx&&(Q=I)),Q===R&&(K||ee)&&(t&&Q===I&&K?(Q=W,l&&(Q=l(P,R,Q,w))):t&&Q===W&&ee?(Q=I,l&&(Q=l(P,R,Q,w))):Q=Qa(w.current,{startingIndex:Q,decrement:ee,disabledIndices:b})),Q!==R&&!Rc(w.current,Q)&&(h&&P.stopPropagation(),(y||B||K||ee)&&P.preventDefault(),A(Q,!0),queueMicrotask(()=>{w.current[Q]?.focus()}))});return{props:{ref:N,onFocus(P){const B=k.current,D=qn(P.nativeEvent);!B||D==null||!dk(D)||D.setSelectionRange(0,D.value.length)},onKeyDown:M},highlightedIndex:R,onHighlightedIndexChange:A,elementsRef:w,onMapChange:T,relayKeyboardEvent:M}}function PI(e,t){for(const a of D6)if(!t.includes(a)&&e.getModifierState(a))return!0;return!1}function LI(e){const{render:t,className:a,style:o,refs:l=ja,props:c=ja,state:d=sn,stateAttributesMapping:f,highlightedIndex:m,onHighlightedIndexChange:g,orientation:h,grid:b,loopFocus:_,onLoop:j,enableHomeAndEndKeys:E,onMapChange:y,stopEventPropagation:k=!0,rootRef:N,disabledIndices:w,modifierKeys:S,highlightItemOnHover:R=!1,tag:A="div",...T}=e,z=pp(),{props:M,highlightedIndex:L,onHighlightedIndexChange:P,elementsRef:B,onMapChange:D,relayKeyboardEvent:$}=DI({grid:b,loopFocus:_,onLoop:j,orientation:h,highlightedIndex:m,onHighlightedIndexChange:g,rootRef:N,stopEventPropagation:k,enableHomeAndEndKeys:E,direction:z,disabledIndices:w,modifierKeys:S}),q=Et(A,e,{state:d,ref:l,props:[M,...c,T],stateAttributesMapping:f}),G=x.useMemo(()=>({highlightedIndex:L,onHighlightedIndexChange:P,highlightItemOnHover:R,relayKeyboardEvent:$}),[L,P,R,$]);return n.jsx(IC.Provider,{value:G,children:n.jsx(bp,{elementsRef:B,onMapChange:U=>{y?.(U),D(U)},children:q})})}const II=x.forwardRef(function(t,a){const{activateOnFocus:o=!1,className:l,loopFocus:c=!0,render:d,style:f,...m}=t,{orientation:g,setTabMap:h,tabActivationDirection:b}=Y_(),[_,j]=x.useState(0),[E,y]=x.useState(null),k=x.useRef(new Set),N=x.useRef(new Set),w=x.useRef(null);Pe(()=>{if(typeof ResizeObserver>"u")return;const M=new ResizeObserver(()=>{k.current.forEach(L=>{L()})});return w.current=M,E&&M.observe(E),N.current.forEach(L=>{M.observe(L)}),()=>{M.disconnect(),w.current=null}},[E]);const S=He(M=>(k.current.add(M),()=>{k.current.delete(M)})),R=He(M=>(N.current.add(M),w.current?.observe(M),()=>{N.current.delete(M),w.current?.unobserve(M)})),A={orientation:g,tabActivationDirection:b},T={"aria-orientation":g==="vertical"?"vertical":void 0,role:"tablist"},z=x.useMemo(()=>({activateOnFocus:o,registerIndicatorUpdateListener:S,registerTabResizeObserverElement:R,tabsListElement:E}),[o,S,R,E]);return n.jsx(uE.Provider,{value:z,children:n.jsx(LI,{render:d,className:l,style:f,state:A,refs:[a,y],props:[T,m],stateAttributesMapping:Cp,highlightedIndex:_,enableHomeAndEndKeys:!0,loopFocus:c,orientation:g,onHighlightedIndexChange:j,onMapChange:h,disabledIndices:ja})})});function Np({className:e,...t}){return n.jsx(RI,{"data-slot":"tabs",className:St("flex flex-col gap-4",e),...t})}const BI=A_("inline-flex h-9 w-fit items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground data-[variant=line]:h-8 data-[variant=line]:gap-1 data-[variant=line]:rounded-none data-[variant=line]:bg-transparent data-[variant=line]:p-0",{variants:{variant:{default:"bg-muted",line:"gap-1 bg-transparent"}},defaultVariants:{variant:"default"}});function Ep({className:e,variant:t="default",...a}){return n.jsx(II,{"data-slot":"tabs-list","data-variant":t,className:St(BI({variant:t}),e),...a})}function qs({className:e,...t}){return n.jsx(AI,{"data-slot":"tabs-trigger",className:St("inline-flex h-7 items-center justify-center gap-1.5 rounded-md border border-transparent px-3 py-1 text-sm font-medium whitespace-nowrap text-muted-fg transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50 data-active:bg-background data-active:text-foreground data-active:shadow-sm dark:data-active:border-input dark:data-active:bg-input/30 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...t})}function fs({className:e,...t}){return n.jsx(zI,{"data-slot":"tabs-content",className:St("text-sm outline-none",e),...t})}function Wk(e,t){let a=e;for(const o of t.split(".")){if(!a||typeof a!="object"||Array.isArray(a))return;a=a[o]}return a}function K_(e,t=""){const a={};for(const[o,l]of Object.entries(e)){const c=t?`${t}.${o}`:o;l&&typeof l=="object"&&!Array.isArray(l)?Object.assign(a,K_(l,c)):a[c]=l}return a}function dE(e){const t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error("JSON debe ser objeto.");return t}function of({sections:e,source:t,placeholderSource:a,jsonTitle:o,jsonDescription:l,saveLabel:c=u("common.save"),onSaveFields:d,onSaveJson:f,busy:m,hideJson:g=!1}){const h=e[0]?.key||"json",[b,_]=x.useState({}),[j,E]=x.useState(""),[y,k]=x.useState("");x.useEffect(()=>{const A={};for(const T of e.flatMap(z=>z.fields))A[T.path]=Wk(t,T.path)??"";_(A),E(JSON.stringify(t||{},null,2)),k("")},[t,e]);const N=x.useMemo(()=>new Set(e.flatMap(A=>A.fields.map(T=>T.path))),[e]),w=async()=>{const A={},T=[];for(const z of e.flatMap(M=>M.fields)){const M=b[z.path];if(!ps(M)){if(M===""||M===void 0||M===null){T.push(z.path);continue}if(z.kind==="number"){const L=Number(M);Number.isFinite(L)&&(A[z.path]=L)}else A[z.path]=M}}await d(A,T.filter(z=>N.has(z)))},S=async()=>{k("");try{await f(dE(j))}catch(A){k(A.message)}},R=A=>n.jsxs("div",{className:"space-y-4",children:[A.description&&n.jsx("p",{className:"text-sm text-muted-fg",children:A.description}),n.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:A.fields.map(T=>n.jsx($I,{field:T,value:b[T.path],inherited:Wk(a,T.path),onChange:z=>_(M=>({...M,[T.path]:z}))},T.path))}),n.jsx(re,{variant:"primary",loading:m,onClick:w,children:c})]});return g&&e.length<=1?e[0]?R(e[0]):null:n.jsxs(Np,{defaultValue:h,className:"space-y-4",children:[n.jsxs(Ep,{className:"flex flex-wrap",children:[e.map(A=>n.jsx(qs,{value:A.key,children:A.label},A.key)),!g&&n.jsx(qs,{value:"json",children:"JSON"})]}),e.map(A=>n.jsx(fs,{value:A.key,children:R(A)},A.key)),!g&&n.jsx(fs,{value:"json",children:n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{children:[n.jsx("h3",{className:"text-sm font-medium",children:o}),l&&n.jsx("p",{className:"text-xs text-muted-fg",children:l})]}),n.jsx(un,{rows:18,className:"font-mono text-xs",value:j,onChange:A=>E(A.target.value)}),y&&n.jsx("p",{className:"text-xs text-destructive",children:y}),n.jsx(re,{variant:"primary",loading:m,onClick:S,children:u("settings_ui.save_json")})]})})]})}function $I({field:e,value:t,inherited:a,onChange:o}){const l=e.placeholder||Zk(a)||(ps(t)?Fr(t):""),c=e.hint||(a!==void 0?`Heredado: ${Zk(a)}`:void 0);return e.kind==="boolean"?n.jsx("div",{className:"flex items-end pb-1",children:n.jsx(Bt,{checked:t===!0,onChange:o,label:e.label})}):n.jsx(ie,{label:e.label,hint:c,children:e.kind==="select"?n.jsx(ct,{value:String(t||""),onChange:o,placeholder:l||"(sin override)",options:[{value:"",label:l||"(sin override)"},...(e.options||[]).map(d=>({value:String(d.value),label:d.label}))]}):e.kind==="textarea"?n.jsx(un,{rows:4,value:String(t||""),placeholder:l,onChange:d=>o(d.target.value)}):n.jsx(Ee,{type:e.kind==="password"?"password":e.kind==="number"?"number":"text",value:String(ps(t)?"":t||""),placeholder:e.kind==="password"&&ps(t)?Fr(t):e.kind==="password"&&ps(a)?Fr(a):l,onChange:d=>o(d.target.value)})})}function Zk(e){return e==null||e===""?"":ps(e)?Fr(e):Array.isArray(e)?e.join(", "):typeof e=="object"?JSON.stringify(e):String(e)}function UI(){return[{key:"routing",label:u("settings_ui.cfg_overrides_label"),description:u("settings_ui.cfg_overrides_desc"),fields:[{path:"route_to_agent",label:u("settings_ui.cfg_route_to_agent"),placeholder:"master"},{path:"super_agent.model",label:u("settings_ui.cfg_super_agent_model")},{path:"super_agent.permission_mode",label:u("settings_ui.cfg_permission_mode"),kind:"select",options:Cb.map(e=>({value:e,label:e}))},{path:"super_agent.system",label:u("settings_ui.cfg_extra_prompt"),kind:"textarea"}]}]}function qI(){return[{key:"engines",label:u("settings_ui.cfg_engines_label"),fields:[{path:"engines.ollama.base_url",label:u("settings_ui.cfg_ollama_url")},{path:"engines.anthropic.api_key",label:u("settings_ui.cfg_anthropic_key"),kind:"password"},{path:"engines.openai.api_key",label:u("settings_ui.cfg_openai_key"),kind:"password"},{path:"engines.groq.api_key",label:u("settings_ui.cfg_groq_key"),kind:"password"},{path:"engines.openrouter.api_key",label:u("settings_ui.cfg_openrouter_key"),kind:"password"},{path:"engines.gemini.api_key",label:u("settings_ui.cfg_gemini_key"),kind:"password"}]}]}function HI(){return[{key:"identity",label:u("settings_ui.cfg_project_label"),description:u("settings_ui.cfg_project_desc"),fields:[{path:"name",label:u("settings_ui.cfg_name")},{path:"version",label:u("settings_ui.cfg_version")},{path:"apf",label:u("settings_ui.cfg_apc_spec")},{path:"apx",label:u("settings_ui.cfg_apx_install")},{path:"apx_id",label:u("settings_ui.cfg_apx_storage_id")}]}]}function fE({pid:e}){const t=Je(),{project:a}=cu(e),{channels:o,isLoading:l,mutate:c}=D_(),d=String(e),f=a?.name||a?.path?.split("/").pop()||d,m=`proj-${d}`,g=o.find(z=>z.project===d||z.project===f||z.name===m),[h,b]=x.useState(!!g),[_,j]=x.useState(""),[E,y]=x.useState(""),[k,N]=x.useState(""),[w,S]=x.useState(!0),[R,A]=x.useState(!1);if(x.useEffect(()=>{g?(b(!0),j(""),y(g.chat_id||""),N(g.route_to_agent||""),S(g.respond_with_engine??!0)):(b(!1),j(""),y(""),N(""),S(!0))},[g?.name,g?.chat_id,g?.route_to_agent]),l)return n.jsx(st,{});const T=async()=>{A(!0);try{if(!h){g&&(await Dn.channels.remove(g.name),t.success(u("project.telegram.cleared"))),await c();return}const z={name:g?.name||m,project:d,chat_id:E,route_to_agent:k,respond_with_engine:w,..._?{bot_token:_}:{}};g?await Dn.channels.patch(g.name,z):await Dn.channels.upsert(z),t.success(u("project.telegram.saved")),await c(),j("")}catch(z){t.error(z.message)}finally{A(!1)}};return n.jsx(Ve,{title:u("project.telegram.title"),description:u("project.telegram.subtitle"),children:n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx(Bt,{checked:h,onChange:b,label:u(h?"project.telegram.override_active":"project.telegram.use_default")}),g&&n.jsx($e,{tone:"success",children:u("project.telegram.channel_badge",{name:g.name})})]}),h&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsx(ie,{label:u("project.telegram.bot_token"),hint:g?.bot_token?`${Fr(g.bot_token)} ${u("telegram_ui.empty_keep")}`:u("project.telegram.bot_hint_none"),children:n.jsx(Ee,{type:"password",value:_,onChange:z=>j(z.target.value),placeholder:g?.bot_token?Fr(g.bot_token):""})}),n.jsx(ie,{label:u("project.telegram.chat_id"),children:n.jsx(Ee,{value:E,onChange:z=>y(z.target.value)})}),n.jsx(ie,{label:u("project.telegram.route_agent"),hint:u("project.telegram.route_hint"),children:n.jsx(Ee,{value:k,onChange:z=>N(z.target.value)})})]}),n.jsx(Bt,{checked:w,onChange:S,label:u("project.telegram.respond_engine")})]}),n.jsx("div",{className:"pt-2",children:n.jsx(re,{variant:"primary",loading:R,onClick:T,children:u("common.save")})}),!h&&!g&&n.jsx(ft,{children:u("project.telegram.no_override")})]})})}function VI({pid:e}){const t=Je(),a=Pn(),{project:o,mutate:l}=cu(e),c=Be(`/projects/${e}/config`,()=>Zn.config.show(e)),d=String(e)==="0";if(c.isLoading)return n.jsx(st,{});if(!c.data)return n.jsx(ft,{children:u("project.config.no_data")});const f=async h=>{await Zn.apcProject.put(e,h),t.success(u("project.config.save_project")),c.mutate()},m=async h=>{await Zn.config.put(e,h),t.success(u("project.config.save_override")),c.mutate()},g=async(h,b)=>{await Zn.config.set(e,h),b.length&&await Zn.config.unset(e,b),t.success(u("project.config.save_fields_success")),c.mutate()};return n.jsxs("div",{className:"space-y-6",children:[n.jsx(Ve,{title:u("project.config.section_title"),description:u("project.config.section_desc"),children:n.jsxs(Np,{defaultValue:"settings",className:"space-y-4",children:[n.jsxs(Ep,{className:"flex flex-wrap",children:[n.jsx(qs,{value:"settings",children:u("project.config.tab_settings")}),n.jsx(qs,{value:"engines",children:u("settings_ui.cfg_engines_label")}),!d&&n.jsx(qs,{value:"telegram",children:u("project.nav.telegram")}),n.jsx(qs,{value:"project",children:u("project.config.tab_project")}),n.jsx(qs,{value:"json",children:"JSON"})]}),n.jsx(fs,{value:"settings",children:n.jsx(of,{sections:UI(),source:c.data.project_only,placeholderSource:c.data.effective,jsonTitle:c.data.project_config_path,onSaveFields:g,onSaveJson:m,hideJson:!0})}),n.jsx(fs,{value:"engines",children:n.jsx(of,{sections:qI(),source:c.data.project_only,placeholderSource:c.data.effective,jsonTitle:c.data.project_config_path,onSaveFields:g,onSaveJson:m,hideJson:!0})}),!d&&n.jsx(fs,{value:"telegram",children:n.jsx(fE,{pid:e})}),n.jsx(fs,{value:"project",children:n.jsx(of,{sections:HI(),source:c.data.apc_project||{},jsonTitle:c.data.project_json_path,onSaveFields:async(h,b)=>{await Zn.apcProject.set(e,GI(h),b),t.success(u("project.config.save_meta_success")),c.mutate()},onSaveJson:f,hideJson:!0})}),n.jsx(fs,{value:"json",children:n.jsxs("div",{className:"space-y-6",children:[n.jsx(Jk,{title:c.data.project_config_path,description:".apc/config.json — overrides del proyecto.",source:c.data.project_only,onSave:m}),n.jsx(Jk,{title:c.data.project_json_path,description:".apc/project.json — metadata APC portable.",source:c.data.apc_project||{},onSave:f}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-xs text-muted-fg",children:u("project.config.effective_read")}),n.jsx("pre",{className:"max-h-96 overflow-auto rounded-lg border border-border bg-muted/40 p-3 text-xs",children:JSON.stringify(c.data.effective,null,2)})]})]})})]})}),!d&&o?n.jsx(FI,{pid:e,label:o.name||o.path,onRebuilt:()=>c.mutate(),onUnregistered:()=>{l(),a("/")}}):null]})}function FI({pid:e,label:t,onRebuilt:a,onUnregistered:o}){const l=Je(),[c,d]=x.useState(null),[f,m]=x.useState(null),g=async()=>{d("rebuild");try{await Zn.rebuild(e),l.success(u("project.rebuild_done")),a()}catch(b){l.error(b.message)}finally{d(null),m(null)}},h=async()=>{d("unregister");try{await Zn.remove(e),l.success(u("project.unregistered")),o()}catch(b){l.error(b.message)}finally{d(null),m(null)}};return n.jsxs(n.Fragment,{children:[n.jsx(Ve,{title:u("project.danger.title"),description:u("project.danger.subtitle"),children:n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-md border border-border bg-muted/30 px-3 py-3",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"text-sm font-medium",children:u("project.rebuild")}),n.jsx("div",{className:"text-xs text-muted-fg",children:u("project.danger.rebuild_desc")})]}),n.jsxs(re,{size:"sm",variant:"secondary",onClick:()=>m("rebuild"),children:[n.jsx(Cs,{size:13})," ",u("project.rebuild")]})]}),n.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-md border border-red-500/40 bg-red-500/5 px-3 py-3",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"text-sm font-medium",children:u("admin.unregister")}),n.jsx("div",{className:"text-xs text-muted-fg",children:u("project.danger.unregister_desc")})]}),n.jsxs(re,{size:"sm",variant:"destructive",onClick:()=>m("unregister"),children:[n.jsx(_n,{size:13})," ",u("admin.unregister")]})]})]})}),n.jsx(Xt,{open:f==="rebuild",onClose:()=>c?null:m(null),title:u("project.danger.rebuild_confirm_title"),description:u("project.danger.rebuild_confirm_desc",{label:t}),size:"sm",footer:n.jsxs(n.Fragment,{children:[n.jsx(re,{variant:"ghost",onClick:()=>m(null),disabled:c!==null,children:u("common.cancel")}),n.jsx(re,{variant:"primary",onClick:g,loading:c==="rebuild",children:u("project.rebuild")})]}),children:n.jsx("p",{className:"text-sm text-muted-fg",children:u("project.danger.rebuild_long")})}),n.jsx(Xt,{open:f==="unregister",onClose:()=>c?null:m(null),title:u("project.danger.unregister_confirm_title"),description:u("project.unregister_confirm",{label:t}),size:"sm",footer:n.jsxs(n.Fragment,{children:[n.jsx(re,{variant:"ghost",onClick:()=>m(null),disabled:c!==null,children:u("common.cancel")}),n.jsx(re,{variant:"destructive",onClick:h,loading:c==="unregister",children:u("admin.unregister")})]}),children:n.jsx("p",{className:"text-sm text-muted-fg",children:u("project.danger.unregister_long")})})]})}function Jk({title:e,description:t,source:a,onSave:o}){const[l,c]=x.useState(""),[d,f]=x.useState(""),[m,g]=x.useState(!1);x.useEffect(()=>{c(JSON.stringify(a||{},null,2)),f("")},[a]);const h=async()=>{f(""),g(!0);try{await o(dE(l))}catch(b){f(b.message)}finally{g(!1)}};return n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{children:[n.jsx("h3",{className:"text-sm font-medium",children:e}),t&&n.jsx("p",{className:"text-xs text-muted-fg",children:t})]}),n.jsx(un,{rows:14,className:"font-mono text-xs",value:l,onChange:b=>c(b.target.value)}),d&&n.jsx("p",{className:"text-xs text-destructive",children:d}),n.jsx(re,{variant:"primary",loading:m,onClick:h,children:u("settings_ui.save_json")})]})}function GI(e){const t={};for(const[a,o]of Object.entries(K_(e)))ps(o)||(t[a]=o);return t}function Kl(e){return String(e||"").trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").replace(/-{2,}/g,"-")}function pE({open:e,onClose:t,pid:a,editing:o,onSaved:l}){const c=Je(),[d,f]=x.useState(""),[m,g]=x.useState(""),[h,b]=x.useState(""),[_,j]=x.useState(!1);x.useEffect(()=>{e&&(f(o?.name??""),g(o?.slug??""),b(o?.goal??""))},[e,o]);const E=async()=>{if(d.trim()){j(!0);try{o?await Vr.updateArea(a,o.slug,{name:d,goal:h}):await Vr.createArea(a,{name:d,slug:m||Kl(d),goal:h}),c.success(u("common.saved")),l(),t()}catch(y){c.error(y instanceof Error?y.message:String(y))}finally{j(!1)}}};return n.jsx(Xt,{open:e,onClose:t,title:u(o?"structure.edit_area":"structure.new_area"),footer:n.jsxs(n.Fragment,{children:[n.jsx(re,{variant:"ghost",onClick:t,children:u("common.cancel")}),n.jsx(re,{variant:"primary","data-testid":"area-create",onClick:()=>void E(),loading:_,disabled:!d.trim(),children:u(o?"common.save":"structure.create_area")})]}),children:n.jsxs("div",{className:"space-y-3",children:[n.jsx(ie,{label:u("structure.name"),children:n.jsx(Ee,{autoFocus:!0,"data-testid":"area-name",value:d,onChange:y=>{f(y.target.value),o||g(Kl(y.target.value))},placeholder:"Engineering"})}),!o&&n.jsx(ie,{label:u("structure.slug"),children:n.jsx(Ee,{value:m,onChange:y=>g(Kl(y.target.value)),className:"font-mono",placeholder:"engineering"})}),n.jsx(ie,{label:u("structure.goal"),hint:u("structure.goal_hint"),children:n.jsx(un,{value:h,onChange:y=>b(y.target.value),rows:2})})]})})}function mE({open:e,onClose:t,pid:a,areas:o,editing:l,presetArea:c,onSaved:d}){const f=Je(),[m,g]=x.useState(""),[h,b]=x.useState(""),[_,j]=x.useState(""),[E,y]=x.useState(""),[k,N]=x.useState(!1);x.useEffect(()=>{e&&(g(l?.name??""),b(l?.slug??""),j(l?.area??c??""),y(l?.description??""))},[e,l,c]);const w=async()=>{if(m.trim()){N(!0);try{l?await Vr.updateRole(a,l.slug,{name:m,area:_||null,description:E}):await Vr.createRole(a,{name:m,slug:h||Kl(m),area:_||null,description:E}),f.success(u("common.saved")),d(),t()}catch(R){f.error(R instanceof Error?R.message:String(R))}finally{N(!1)}}},S=[{value:"",label:u("structure.no_area")},...o.map(R=>({value:R.slug,label:R.name}))];return n.jsx(Xt,{open:e,onClose:t,title:u(l?"structure.edit_role":"structure.new_role"),footer:n.jsxs(n.Fragment,{children:[n.jsx(re,{variant:"ghost",onClick:t,children:u("common.cancel")}),n.jsx(re,{variant:"primary",onClick:()=>void w(),loading:k,disabled:!m.trim(),children:u(l?"common.save":"structure.create_role")})]}),children:n.jsxs("div",{className:"space-y-3",children:[n.jsx(ie,{label:u("structure.name"),children:n.jsx(Ee,{autoFocus:!0,value:m,onChange:R=>{g(R.target.value),l||b(Kl(R.target.value))},placeholder:"Tech Lead"})}),!l&&n.jsx(ie,{label:u("structure.slug"),children:n.jsx(Ee,{value:h,onChange:R=>b(Kl(R.target.value)),className:"font-mono",placeholder:"tech-lead"})}),n.jsx(ie,{label:u("structure.area"),children:n.jsx(ct,{value:_,onChange:j,options:S,placeholder:u("structure.no_area")})}),n.jsx(ie,{label:u("structure.description"),children:n.jsx(un,{value:E,onChange:R=>y(R.target.value),rows:2})})]})})}function gE({value:e,onChange:t}){return n.jsx(Ee,{value:e,onChange:a=>t([...a.target.value].slice(-2).join("")),className:"text-center text-lg",placeholder:"🤖","aria-label":u("agents_form.emoji")})}const YI=[{value:"total",labelKey:"auto_total"},{value:"automatico",labelKey:"auto_automatico"},{value:"permiso",labelKey:"auto_permiso"}];function hE({value:e,onChange:t}){return n.jsx("div",{className:"inline-flex w-full rounded-lg border border-border p-0.5",children:YI.map(a=>n.jsx("button",{type:"button",onClick:()=>t(a.value),className:ge("flex-1 rounded-md px-2 py-1 text-[12px] font-medium capitalize transition-colors",e===a.value?"bg-primary/15 text-foreground":"text-muted-foreground hover:text-foreground"),children:u(`agents_form.${a.labelKey}`)},a.value))})}function xE({pid:e,area:t,role:a,onArea:o,onRole:l}){const c=Be(`/projects/${e}/organization`,()=>Vr.get(e)),[d,f]=x.useState(!1),[m,g]=x.useState(!1),h=c.data?.areas??[],_=(c.data?.roles??[]).filter(y=>t?y.area===t||y.area===null:!0),j=[{value:"",label:u("structure.no_area")},...h.map(y=>({value:y.slug,label:y.name}))],E=[{value:"",label:u("agents_form.no_role")},..._.map(y=>({value:y.slug,label:y.name}))];return n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsx(ie,{label:u("agents_form.area"),children:n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx(ct,{value:t,onChange:y=>{o(y)},options:j,placeholder:u("structure.no_area"),className:"flex-1"}),n.jsx(ew,{label:u("structure.new_area"),onClick:()=>f(!0)})]})}),n.jsx(ie,{label:u("agents_form.role"),children:n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx(ct,{value:a,onChange:l,options:E,placeholder:u("agents_form.no_role"),className:"flex-1"}),n.jsx(ew,{label:u("structure.new_role"),onClick:()=>g(!0)})]})})]}),n.jsx(pE,{open:d,onClose:()=>f(!1),pid:e,onSaved:()=>void c.mutate()}),n.jsx(mE,{open:m,onClose:()=>g(!1),pid:e,areas:h,presetArea:t||null,onSaved:()=>void c.mutate()})]})}function ew({label:e,onClick:t}){return n.jsx("button",{type:"button",onClick:t,title:e,"aria-label":e,className:"flex size-9 shrink-0 items-center justify-center rounded-lg border border-border text-muted-foreground hover:bg-accent hover:text-foreground",children:n.jsx(Dt,{className:"size-4"})})}function bE({open:e,onClose:t,onConfirm:a,title:o,description:l,confirmLabel:c,destructive:d=!0}){const[f,m]=x.useState(!1),g=async()=>{m(!0);try{await a(),t()}finally{m(!1)}};return n.jsx(Xt,{open:e,onClose:t,title:o,footer:n.jsxs(n.Fragment,{children:[n.jsx(re,{variant:"ghost",onClick:t,disabled:f,children:u("common.cancel")}),n.jsx(re,{variant:d?"destructive":"primary",onClick:()=>void g(),loading:f,children:c??u("common.confirm")})]}),children:n.jsx("p",{className:"text-sm text-muted-foreground",children:l})})}function qd(e,t){const a=[],o=/(\*\*([^*]+)\*\*)|(\*([^*]+)\*)|(`([^`]+)`)|(\[([^\]]+)\]\(([^)]+)\))/g;let l=0,c,d=0;for(;c=o.exec(e);)c.index>l&&a.push(n.jsx(x.Fragment,{children:e.slice(l,c.index)},`${t}-t${d}`)),c[2]!==void 0?a.push(n.jsx("strong",{children:c[2]},`${t}-b${d}`)):c[4]!==void 0?a.push(n.jsx("em",{children:c[4]},`${t}-i${d}`)):c[6]!==void 0?a.push(n.jsx("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[0.85em]",children:c[6]},`${t}-c${d}`)):c[8]!==void 0&&a.push(n.jsx("a",{href:c[9],target:"_blank",rel:"noreferrer",className:"text-sky-500 underline underline-offset-2 hover:text-sky-400",children:c[8]},`${t}-l${d}`)),l=o.lastIndex,d+=1;return l<e.length&&a.push(n.jsx(x.Fragment,{children:e.slice(l)},`${t}-tend`)),a}function _E({content:e,className:t}){const a=e.replace(/\r\n/g,`
|
|
787
|
+
`)}}if(f.trim())try{a(JSON.parse(f.trim()))}catch{}}const iP={get:()=>se.get("/health")},Zn={list:()=>se.get("/projects"),register:e=>se.post("/projects",{path:e}),remove:e=>se.del(`/projects/${encodeURIComponent(e)}`),rebuild:e=>se.post(`/projects/${encodeURIComponent(e)}/rebuild`),config:{show:e=>se.get(`/projects/${e}/config`),set:(e,t)=>se.patch(`/projects/${e}/config`,{set:t}),unset:(e,t)=>se.patch(`/projects/${e}/config`,{unset:t}),put:(e,t)=>se.put(`/projects/${e}/config`,t)},apcProject:{set:(e,t,a)=>se.patch(`/projects/${e}/apc-project`,{set:t,unset:a}),put:(e,t)=>se.put(`/projects/${e}/apc-project`,t)},memory:{get:e=>se.get(`/projects/${e}/memory`),put:(e,t)=>se.put(`/projects/${e}/memory`,{body:t})}},an={list:(e,t)=>se.get(`/projects/${e}/agents${t?.stats?"?stats=1":""}`),get:(e,t)=>se.get(`/projects/${e}/agents/${t}`),create:(e,t)=>se.post(`/projects/${e}/agents`,t),update:(e,t,a)=>se.patch(`/projects/${e}/agents/${encodeURIComponent(t)}`,a),remove:(e,t)=>se.del(`/projects/${e}/agents/${encodeURIComponent(t)}`),chat:(e,t,a)=>se.post(`/projects/${e}/agents/${encodeURIComponent(t)}/chat`,a),memory:{get:(e,t)=>se.get(`/projects/${e}/agents/${t}/memory`),put:(e,t,a)=>se.put(`/projects/${e}/agents/${t}/memory`,{body:a})},vault:e=>se.get(e?.includeRemoved?"/agents/vault?include_removed=1":"/agents/vault"),vaultCreate:(e,t={},a="")=>se.post("/agents/vault",{slug:e,fields:t,body:a}),vaultPatch:(e,t)=>se.patch(`/agents/vault/${encodeURIComponent(e)}`,t),vaultRemove:e=>se.del(`/agents/vault/${encodeURIComponent(e)}`),vaultRestore:e=>se.post(`/agents/vault/${encodeURIComponent(e)}/restore`),import:(e,t)=>se.post(`/projects/${e}/agents/import`,{slug:t})},Wr={list:(e,t)=>se.get(`/projects/${e}/agents/${t}/conversations`),get:(e,t,a)=>se.get(`/projects/${e}/agents/${t}/conversations/${a}`),threads:e=>se.get(`/projects/${e}/super-agent/threads`),thread:(e,t,a)=>se.get(`/projects/${e}/super-agent/threads/${t}/${a}`),remove:(e,t,a)=>se.del(`/projects/${e}/agents/${t}/conversations/${a}`),removeThread:(e,t,a)=>se.del(`/projects/${e}/super-agent/threads/${t}/${a}`),compact:(e,t,a)=>se.post(a?`/projects/${e}/agents/${t}/conversations/${a}/compact`:`/projects/${e}/agents/${t}/compact`,{})},Br={list:e=>se.get(`/projects/${e}/routines`),get:(e,t)=>se.get(`/projects/${e}/routines/${t}`),run:(e,t)=>se.post(`/projects/${e}/routines/${t}/run`),enable:(e,t)=>se.post(`/projects/${e}/routines/${t}/enable`),disable:(e,t)=>se.post(`/projects/${e}/routines/${t}/disable`),upsert:(e,t)=>se.post(`/projects/${e}/routines`,t),remove:(e,t)=>se.del(`/projects/${e}/routines/${encodeURIComponent(t)}`)},Qn={list:(e,t="open")=>se.get(`/projects/${e}/tasks?state=${t}`).then(a=>Bl(a).items),global:(e="open")=>se.get(`/tasks?state=${e}`).then(t=>Bl(t).items),listPage:(e,{state:t,limit:a,offset:o})=>se.get(`/projects/${e}/tasks?state=${t}&limit=${a}&offset=${o}`).then(l=>Bl(l)),globalPage:({state:e,limit:t,offset:a,status:o})=>se.get(`/tasks?state=${e}&limit=${t}&offset=${a}`+(o?`&status=${o}`:"")).then(l=>Bl(l)),get:(e,t)=>se.get(`/projects/${e}/tasks/${t}`),add:(e,t)=>se.post(`/projects/${e}/tasks`,t),patch:(e,t,a)=>se.patch(`/projects/${e}/tasks/${t}`,{patch:a}),status:(e,t,a)=>se.post(`/projects/${e}/tasks/${t}/status`,{status:a}),done:(e,t)=>se.post(`/projects/${e}/tasks/${t}/done`),drop:(e,t)=>se.post(`/projects/${e}/tasks/${t}/drop`),reopen:(e,t)=>se.post(`/projects/${e}/tasks/${t}/reopen`),summary:e=>se.get(`/projects/${e}/tasks-summary`)},$r={list:e=>se.get(`/projects/${e}/mcps`),check:e=>se.get(`/projects/${e}/mcps/check`),add:(e,t,a)=>se.post(`/projects/${e}/mcps?scope=${t}`,a),remove:(e,t,a="shared")=>se.del(`/projects/${e}/mcps/${encodeURIComponent(t)}?scope=${a}`),test:(e,t)=>se.post(`/projects/${e}/mcps/${encodeURIComponent(t)}/test`,{}),logs:(e,t)=>se.get(`/projects/${e}/mcps/${encodeURIComponent(t)}/logs`)},ko=e=>`?scope=${e}`,Yn={catalog:e=>se.get(`/projects/${e}/integrations/catalog`),list:(e,t="project")=>se.get(`/projects/${e}/integrations${ko(t)}`),status:(e,t,a="project")=>se.get(`/projects/${e}/integrations/${t}${ko(a)}`),configure:(e,t,a,o)=>se.post(`/projects/${e}/integrations/${t}/configure${ko(a)}`,o),validate:(e,t,a="project")=>se.post(`/projects/${e}/integrations/${t}/validate${ko(a)}`,{}),deactivate:(e,t,a="project")=>se.post(`/projects/${e}/integrations/${t}/deactivate${ko(a)}`,{}),action:(e,t,a,o="project")=>se.post(`/projects/${e}/integrations/${t}/action/${a}${ko(o)}`,{}),remove:(e,t,a="project")=>se.del(`/projects/${e}/integrations/${t}${ko(a)}`),asanaConfigure:(e,t,a)=>Yn.configure(e,"asana",t,{personal_access_token:a.personalAccessToken,workspace_gid:a.workspaceGid}),asanaValidate:(e,t)=>Yn.validate(e,"asana",t),asanaWorkspaces:(e,t)=>Yn.action(e,"asana","workspaces",t)},qc={list:(e,t={})=>se.get(`/projects/${e}/vars${t.reveal?"?reveal=1":""}`),get:(e,t,a={})=>se.get(`/projects/${e}/vars/${encodeURIComponent(t)}${a.reveal?"?reveal=1":""}`),upsert:(e,t)=>se.post(`/projects/${e}/vars`,t),remove:(e,t,a="project")=>se.del(`/projects/${e}/vars/${encodeURIComponent(t)}?scope=${a}`)},hh=e=>{const t=new URLSearchParams;for(const[o,l]of Object.entries(e))l!==void 0&&l!==""&&t.set(o,String(l));const a=t.toString();return a?`?${a}`:""},Cf={global:(e={})=>se.get(`/messages/global${hh(e)}`),project:(e,t={})=>se.get(`/projects/${e}/messages${hh(t)}`),search:(e,t,a=50)=>se.get(`/projects/${e}/messages/search${hh({q:t,limit:a})}`)},cP={global:e=>se.get(`/sessions${e?`?engine=${encodeURIComponent(e)}`:""}`).then(t=>({sessions:Bl(t).items})),page:({engine:e,q:t,deep:a,cwd:o,limit:l,offset:c})=>{const d=new URLSearchParams({limit:String(l),offset:String(c)});return e&&d.set("engine",e),t?.trim()&&d.set("q",t.trim()),a&&d.set("deep","1"),o?.trim()&&d.set("cwd",o.trim()),se.get(`/sessions?${d.toString()}`).then(f=>Bl(f))}},uP={list:()=>se.get("/tools")},Dn={channels:{list:()=>se.get("/telegram/channels"),upsert:e=>se.post("/telegram/channels",e),patch:(e,t)=>se.patch(`/telegram/channels/${e}`,t),remove:e=>se.del(`/telegram/channels/${encodeURIComponent(e)}`)},contacts:{list:()=>se.get("/telegram/contacts"),patch:(e,t)=>se.patch(`/telegram/contacts/${encodeURIComponent(String(e))}`,t),remove:e=>se.del(`/telegram/contacts/${encodeURIComponent(String(e))}`)},roles:{list:()=>se.get("/telegram/roles"),set:(e,t)=>se.put(`/telegram/roles/${encodeURIComponent(e)}`,{tools:t}),remove:e=>se.del(`/telegram/roles/${encodeURIComponent(e)}`)},status:()=>se.get("/telegram/status"),start:()=>se.post("/telegram/start"),stop:()=>se.post("/telegram/stop"),send:e=>se.post("/telegram/send",e)},Hc={list:()=>se.get("/engines"),presets:()=>se.get("/engines/presets"),models:e=>se.post("/engines/models",e)},dP=Object.freeze(Object.defineProperty({__proto__:null,Engines:Hc},Symbol.toStringTag,{value:"Module"})),ai={reload:()=>se.post("/admin/reload"),shutdown:()=>se.post("/admin/shutdown"),config:{get:()=>se.get("/admin/config"),patch:e=>se.patch("/admin/config",e)},superAgent:()=>se.get("/admin/super-agent"),logs:(e="errors",t=200)=>se.get(`/admin/logs?file=${e}&limit=${t}`)},ri={list:()=>se.get("/pair/list"),revoke:e=>se.del(`/pair/revoke/${encodeURIComponent(e)}`),init:()=>se.post("/pair/init",{}),status:e=>se.get(`/pair/status/${encodeURIComponent(e)}`),confirm:e=>se.post("/pair/confirm",e)},wk={get:()=>se.get("/identity"),patch:e=>se.patch("/identity",e)},mN={send:(e,t)=>se.post(`/projects/${e}/super-agent/chat`,t),stream:(e,t,a,o)=>pN(`/projects/${e}/super-agent/chat/stream`,t,a,o),summarize:e=>se.post("/super-agent/summarize",e)},Nf={dirs:e=>se.get(`/admin/fs/dirs?path=${encodeURIComponent(e)}`),pickDir:e=>se.get(`/admin/fs/pick-dir${e?`?prompt=${encodeURIComponent(e)}`:""}`)},fP=["alloy","echo","fable","onyx","nova","shimmer"],pP=["Kore","Puck","Charon","Fenrir","Aoede"],mP=["eleven_multilingual_v2","eleven_turbo_v2_5","eleven_flash_v2_5"],gP=["tts-1","tts-1-hd"],hP=["happy","sad","excited","angry","calm","whisper","shout","laugh","cry","narrator","neutral"],xP=["tiny","base","small","medium","large-v2","large-v3","large-v3-turbo"],Ef={piper:{name:"Piper",note:"Local, offline (CLI + .onnx model). No API key.",local:!0},elevenlabs:{name:"ElevenLabs",note:"Cloud, multilingual. Requires an API key."},openai:{name:"OpenAI",note:"Cloud (tts-1 / tts-1-hd) or any OpenAI-compatible endpoint (set a base URL for a local server, e.g. QVox)."},gemini:{name:"Gemini",note:"Cloud (preview). Uses your Gemini key."},mock:{name:"Mock",note:"Silent test engine. Always available as a fallback.",local:!0}};async function bP(e){const t=R_(),a=await fetch(`/voice/tts?path=${encodeURIComponent(e)}`,{headers:t?{authorization:`Bearer ${t}`}:{}});if(!a.ok){const l=await a.text().catch(()=>"");throw new Error(`No se pudo leer el audio (${a.status}): ${l.slice(0,160)}`)}const o=await a.blob();return URL.createObjectURL(o)}const Rf={providers:()=>se.get("/tts/providers"),sttHardware:()=>se.get("/transcribe/hardware"),sttModels:e=>se.get(`/transcribe/models?backend=${e}`),say:e=>se.post("/tts/say",e),turn:e=>se.post("/voice/turn",e)},gN={manifest:()=>se.get("/deck/manifest"),setWidget:(e,t)=>se.patch(`/deck/widgets/${encodeURIComponent(e)}`,t),exec:e=>se.post("/deck/exec",e)},wo=e=>`/projects/${e}/code/sessions`,Ya={sessions:{list:e=>se.get(wo(e)).then(t=>t.sessions),get:(e,t)=>se.get(`${wo(e)}/${t}`),create:(e,t={})=>se.post(wo(e),t),update:(e,t,a)=>se.patch(`${wo(e)}/${t}`,a),remove:(e,t)=>se.del(`${wo(e)}/${t}`)},changes:(e,t)=>se.get(`${wo(e)}/${t}/changes`),stream:(e,t,a,o,l)=>pN(`${wo(e)}/${t}/chat/stream`,a,o,l)},Ws={list:e=>se.get(`/projects/${encodeURIComponent(e)}/artifacts`),read:(e,t)=>se.get(`/projects/${encodeURIComponent(e)}/artifacts/${encodeURIComponent(t)}`),run:(e,t,a=[])=>se.post(`/projects/${encodeURIComponent(e)}/artifacts/${encodeURIComponent(t)}/run`,{args:a}),remove:(e,t)=>se.del(`/projects/${encodeURIComponent(e)}/artifacts/${encodeURIComponent(t)}`),write:(e,t,a)=>se.patch(`/projects/${encodeURIComponent(e)}/artifacts/${encodeURIComponent(t)}`,{content:a}),rename:(e,t,a)=>se.patch(`/projects/${encodeURIComponent(e)}/artifacts/${encodeURIComponent(t)}`,{newName:a}),preview:(e,t,a=!0)=>se.post(`/projects/${encodeURIComponent(e)}/artifacts/${encodeURIComponent(t)}/preview`,{watch:a}),previews:e=>se.get(`/projects/${encodeURIComponent(e)}/previews`),stopPreview:e=>se.del(`/previews/${encodeURIComponent(e)}`),openTunnel:(e,t)=>se.post(`/previews/${encodeURIComponent(e)}/tunnel`,{provider:t}),closeTunnel:e=>se.del(`/previews/${encodeURIComponent(e)}/tunnel`)},Us={list:e=>{const t=new URLSearchParams;e&&(t.set("project_path",e),t.set("scope",e));const a=t.toString();return se.get(a?`/skills?${a}`:"/skills")},detail:(e,t)=>{const a=t?`?project_path=${encodeURIComponent(t)}`:"";return se.get(`/skills/${encodeURIComponent(e)}/detail${a}`)},setEnabled:e=>se.put("/skills/enabled",e),create:e=>se.post("/skills",e),importZip:e=>se.post("/skills/import/zip",e),importRepo:e=>se.post("/skills/import/repo",e),remove:(e,t)=>{const a=t?`?project_path=${encodeURIComponent(t)}`:"";return se.del(`/skills/${encodeURIComponent(e)}${a}`)},inspector:()=>se.get("/skills/inspector"),updateInspector:e=>se.put("/skills/inspector",e),index:(e={})=>se.post("/skills/index",e),inspect:(e,t)=>se.post("/skills/inspect",{prompt:e,project_path:t})},Vr={get:e=>se.get(`/projects/${e}/organization`),createArea:(e,t)=>se.post(`/projects/${e}/organization/areas`,t),updateArea:(e,t,a)=>se.patch(`/projects/${e}/organization/areas/${encodeURIComponent(t)}`,a),removeArea:(e,t)=>se.del(`/projects/${e}/organization/areas/${encodeURIComponent(t)}`),createRole:(e,t)=>se.post(`/projects/${e}/organization/roles`,t),updateRole:(e,t,a)=>se.patch(`/projects/${e}/organization/roles/${encodeURIComponent(t)}`,a),removeRole:(e,t)=>se.del(`/projects/${e}/organization/roles/${encodeURIComponent(t)}`)},kc={tree:(e,t="project")=>se.get(`/projects/${e}/fs/tree?scope=${t}`),read:(e,t,a="project")=>se.get(`/projects/${e}/fs/file?scope=${a}&path=${encodeURIComponent(t)}`),write:(e,t,a,o="project")=>se.put(`/projects/${e}/fs/file`,{scope:o,path:t,content:a}),mkdir:(e,t,a="project")=>se.post(`/projects/${e}/fs/dir`,{scope:a,path:t}),remove:(e,t,a="project")=>se.del(`/projects/${e}/fs/entry?scope=${a}&path=${encodeURIComponent(t)}`)};function iu(){const{data:e,error:t,isLoading:a,mutate:o}=Be("/projects",()=>Zn.list(),{refreshInterval:Qf.projects});return{projects:(e||[]).slice().sort((c,d)=>{const f=Number(c.id),m=Number(d.id);return f===0&&m!==0?-1:m===0&&f!==0?1:f-m}),error:t,isLoading:a,mutate:o}}function cu(e){const{projects:t,isLoading:a,mutate:o}=iu();return{project:t.find(c=>String(c.id)===e)??null,isLoading:a,mutate:o}}function T_(){const{data:e,error:t,isLoading:a,mutate:o}=Be("/identity",()=>wk.get());return{identity:e||{},error:t,isLoading:a,mutate:o,save:async c=>{const d=await wk.patch(c);return await o(d,{revalidate:!1}),d}}}function yp(){const{identity:e}=T_();return e?.agent_name?.trim()||"APX"}function _P(){return[{id:"desktop",label:u("nav.modules.desktop"),href:"/m/desktop",icon:vb},{id:"code",label:u("nav.modules.code"),href:"/m/code",icon:ya}]}function vP(e,t,a){const[o,l]=x.useState(t);return x.useLayoutEffect(()=>{const c=e.current;if(!c||!a)return;const d=()=>{const m=getComputedStyle(c),g=(parseFloat(m.paddingTop)||0)+(parseFloat(m.paddingBottom)||0),h=c.clientHeight-g;if(h<=0)return;const b=parseFloat(m.rowGap)||12,j=(c.querySelector("[data-rail-probe]")?.offsetHeight??56)+b,y=Math.max(0,Math.floor((h+b)/j))-1;l(y>=t?t:Math.max(0,y-1))};d();const f=new ResizeObserver(d);return f.observe(c),()=>f.disconnect()},[e,t,a]),a?Math.min(o,t):t}function Sk({projects:e,label:t,sublabel:a,icon:o,tooltip:l,header:c,active:d,testId:f,onSelect:m,isActive:g}){return n.jsxs(y_,{children:[n.jsxs(j_,{"data-testid":f,title:l,"aria-label":l,className:"group flex w-full cursor-pointer flex-col items-center gap-1",children:[n.jsx("span",{className:ge("flex size-10 items-center justify-center rounded-xl text-xs font-bold transition-all","bg-muted/40 text-muted-fg hover:bg-accent hover:text-foreground",d&&"ring-2 ring-foreground ring-offset-2 ring-offset-card"),children:o??t}),a&&n.jsx("span",{className:"block max-w-[3.6rem] truncate text-[9px] leading-tight text-muted-fg group-hover:text-foreground",children:a})]}),n.jsxs(k_,{side:"right",align:"start",sideOffset:8,className:"max-h-[70vh] w-64",children:[n.jsx("div",{className:"px-1.5 py-1 text-xs font-medium text-muted-foreground",children:c}),e.map(h=>{const b=h.name||h.path.split("/").pop()||String(h.id),_=`/p/${h.id}`,{initials:j,idleClass:E}=S6(b);return n.jsxs(sf,{"data-testid":`project-menu-item-${h.id}`,onClick:()=>m(_),className:ge(g(_)&&"bg-accent/60 text-foreground"),children:[n.jsx("span",{className:ge("flex size-6 shrink-0 items-center justify-center rounded-md text-[10px] font-bold",E),children:j}),n.jsx("span",{className:"truncate",children:b})]},h.id)})]})]})}function yP({onSelect:e,onOpenRoby:t,onOpenAddProject:a}){const{projects:o,isLoading:l}=iu(),c=ns(),d=_P(),f=yp(),m=x.useRef(null),{collapsed:g,toggle:h}=C_(On.sidebarCollapsed+".projects"),b=w=>c.pathname===w||c.pathname.startsWith(`${w}/`),_=o.find(w=>String(w.id)==="0"),j=o.filter(w=>String(w.id)!=="0").sort((w,S)=>Number(S.id)-Number(w.id)),E=vP(m,j.length,!g&&j.length>0),y=j.slice(0,E),k=j.slice(E),N=k.some(w=>b(`/p/${w.id}`));return n.jsxs("aside",{className:"flex h-full w-20 flex-col items-center gap-3 overflow-hidden bg-transparent py-3",children:[n.jsx(qe,{content:u("nav.apx_admin"),side:"right",children:n.jsx("button",{type:"button",onClick:()=>e("/"),"data-testid":"nav-home",className:"mb-2 cursor-pointer",children:n.jsx(EM,{size:36})})}),l&&n.jsx("div",{className:"size-10 animate-pulse rounded-xl bg-muted"}),_&&n.jsx(Ml,{label:u("base.title"),testId:"project-avatar-0",title:u("base.subtitle"),active:b("/p/0"),isDefault:!0,icon:n.jsx("img",{src:"/modules/superagent.png",alt:u("base.title"),className:"size-7 object-contain",draggable:!1}),onClick:()=>e("/p/0")}),d.map(w=>n.jsx(Ml,{label:w.label,testId:`module-avatar-${w.id}`,title:w.label,active:b(w.href),icon:n.jsx(w.icon,{size:18}),onClick:()=>e(w.href)},w.id)),n.jsxs("div",{className:"flex min-h-0 w-full flex-1 flex-col items-center gap-3",children:[j.length>0&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"my-0.5 h-px w-8 rounded-full bg-border"}),n.jsx(qe,{content:u(g?"nav.expand_projects":"nav.collapse_projects"),side:"right",children:n.jsx("button",{type:"button",onClick:h,"data-testid":"nav-toggle-projects","aria-label":u(g?"nav.expand_projects":"nav.collapse_projects"),"aria-expanded":!g,className:"flex h-5 w-8 cursor-pointer items-center justify-center rounded-md text-muted-fg transition-colors hover:bg-accent hover:text-foreground",children:n.jsx(ms,{className:ge("size-3.5 transition-transform",g&&"-rotate-90")})})})]}),n.jsxs("div",{ref:m,className:"flex min-h-0 w-full flex-1 flex-col items-center gap-3 overflow-hidden py-1.5",children:[j.length>0&&g&&n.jsx(Sk,{projects:j,icon:n.jsx(HA,{size:18}),sublabel:String(j.length),tooltip:u("nav.all_projects"),header:u("nav.all_projects"),active:j.some(w=>b(`/p/${w.id}`)),testId:"nav-projects-folder",onSelect:e,isActive:b}),j.length>0&&!g&&n.jsxs(n.Fragment,{children:[n.jsx("div",{"data-rail-probe":!0,"aria-hidden":!0,className:"invisible absolute w-full",children:n.jsx(Ml,{label:"Ag",active:!1,onClick:()=>{}})}),y.map(w=>{const S=w.name||w.path.split("/").pop()||String(w.id),R=`/p/${w.id}`;return n.jsx("div",{"data-rail-item":!0,className:"w-full",children:n.jsx(Ml,{label:S,testId:`project-avatar-${w.id}`,title:`${S} — ${w.path}`,active:b(R),onClick:()=>e(R)})},w.id)}),k.length>0&&n.jsx(Sk,{projects:k,label:`+${k.length}`,tooltip:u("nav.more_projects",{count:k.length}),header:u("nav.more_projects",{count:k.length}),active:N,testId:"nav-projects-overflow",onSelect:e,isActive:b})]}),n.jsx(Ml,{label:u("nav.add_project"),isAdd:!0,testId:"nav-add-project",icon:n.jsx(Dt,{size:18}),active:!1,onClick:()=>a?a():e("/?action=add-project"),title:u("nav.add_project")})]})]}),n.jsx(Ml,{label:u("nav.settings"),isSettings:!0,testId:"nav-settings",icon:n.jsx(Xf,{size:16}),active:c.pathname==="/settings"||c.pathname.startsWith("/settings/"),onClick:()=>e("/settings"),title:u("nav.settings")}),n.jsx(qe,{content:u("settings_ui.documentation"),side:"right",children:n.jsx("a",{href:"https://agentprojectcontext.github.io/apx/docs/",target:"_blank",rel:"noopener noreferrer","data-testid":"nav-docs","aria-label":u("settings_ui.documentation"),className:"flex size-10 items-center justify-center rounded-xl border border-border/60 bg-muted/30 text-muted-fg transition-colors hover:bg-accent hover:text-foreground",children:n.jsx(_A,{size:18})})}),n.jsx(qe,{content:u("superagent.talk",{persona:f}),side:"right",children:n.jsx("button",{type:"button",onClick:t,"data-testid":"nav-roby","aria-label":u("superagent.talk",{persona:f}),className:"flex size-10 items-center justify-center rounded-xl border border-border/60 bg-muted/30 text-muted-fg transition-colors hover:bg-accent hover:text-foreground",children:n.jsx(rn,{size:18})})})]})}function hN(e){switch(e){case"personal":return u("settings_ui.kind_personal");case"company":return u("settings_ui.kind_company");case"app":return u("settings_ui.kind_app");case"software":return u("settings_ui.kind_software");case"default":return u("settings_ui.kind_default");case"other":return u("settings_ui.kind_other");default:return u("nav.project")}}function Ve({title:e,description:t,action:a,className:o,children:l,fullHeight:c}){return n.jsxs("section",{className:ge("rounded-xl border border-border bg-card p-5",c&&"flex h-full min-h-0 flex-col",o),children:[n.jsxs("header",{className:ge("mb-4 flex items-start justify-between gap-4",c&&"shrink-0"),children:[n.jsxs("div",{children:[n.jsx("h2",{className:"text-lg font-semibold tracking-tight",children:e}),t&&n.jsx("p",{className:"mt-0.5 text-sm text-muted-fg",children:t})]}),a]}),n.jsx("div",{className:ge(c&&"flex min-h-0 flex-1 flex-col"),children:l})]})}function Ck({children:e}){return n.jsx("kbd",{className:"rounded border border-border bg-muted px-1.5 py-0.5 font-mono text-[10px] uppercase tracking-wide text-muted-fg",children:e})}function uu({ok:e}){return n.jsx("span",{className:ge("inline-block size-2 rounded-full",e===null?"bg-muted-fg":e?"bg-emerald-500":"bg-red-500")})}const jP=x.forwardRef(function(t,a){const{render:o,className:l,disabled:c=!1,focusableWhenDisabled:d=!1,nativeButton:f=!0,style:m,...g}=t,{getButtonProps:h,buttonRef:b}=no({disabled:c,focusableWhenDisabled:d,native:f});return Et("button",t,{state:{disabled:c},ref:[a,b],props:[g,h]})}),Nk=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,Ek=Pc,A_=(e,t)=>a=>{var o;if(t?.variants==null)return Ek(e,a?.class,a?.className);const{variants:l,defaultVariants:c}=t,d=Object.keys(l).map(g=>{const h=a?.[g],b=c?.[g];if(h===null)return null;const _=Nk(h)||Nk(b);return l[g][_]}),f=a&&Object.entries(a).reduce((g,h)=>{let[b,_]=h;return _===void 0||(g[b]=_),g},{}),m=t==null||(o=t.compoundVariants)===null||o===void 0?void 0:o.reduce((g,h)=>{let{class:b,className:_,...j}=h;return Object.entries(j).every(E=>{let[y,k]=E;return Array.isArray(k)?k.includes({...c,...f}[y]):{...c,...f}[y]===k})?[...g,b,_]:g},[]);return Ek(e,d,m,a?.class,a?.className)},kP=A_("group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants:{variant:{default:"bg-primary text-primary-foreground [a]:hover:bg-primary/80",outline:"border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80 aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",ghost:"hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",destructive:"bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",xs:"h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",sm:"h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",lg:"h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",icon:"size-8","icon-xs":"size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3","icon-sm":"size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg","icon-lg":"size-9"}},defaultVariants:{variant:"default",size:"default"}});function or({className:e,variant:t="default",size:a="default",...o}){return n.jsx(jP,{"data-slot":"button",className:St(kP({variant:t,size:a,className:e})),...o})}const wP={badInput:!1,customError:!1,patternMismatch:!1,rangeOverflow:!1,rangeUnderflow:!1,stepMismatch:!1,tooLong:!1,tooShort:!1,typeMismatch:!1,valid:null,valueMissing:!1},SP={valid:null,touched:!1,dirty:!1,filled:!1,focused:!1},CP={disabled:!1,...SP},M_={valid(e){return e===null?null:e?{"data-valid":""}:{"data-invalid":""}}},NP={invalid:void 0,name:void 0,validityData:{state:wP,errors:[],error:"",value:"",initialValue:null},setValidityData:Nn,disabled:void 0,setTouched:Nn,setDirty:Nn,setFilled:Nn,setFocused:Nn,validationMode:"onSubmit",shouldValidateOnChange:()=>!1,state:CP,registerFieldControl:Nn,validation:{getValidationProps:(e,t=sn)=>t,inputRef:{current:null},registeredInputs:new Map,registerInput:Nn,getInputControl:()=>null,commit:async()=>{},change:Nn}},EP=x.createContext(NP);function du(e=!0){const t=x.useContext(EP);if(t.setValidityData===Nn&&!e)throw new Error(gn(28));return t}const RP=x.createContext({elementRef:{current:null},formRef:{current:{fields:new Map}},errors:{},clearErrors:Nn,validationMode:"onSubmit",submitAttemptedRef:{current:!1}});function z_(){return x.useContext(RP)}const TP=x.createContext({controlId:void 0,registerControlId:Nn,labelId:void 0,setLabelId:Nn,messageIds:[],setMessageIds:Nn,getDescriptionProps:e=>e});function jp(){return x.useContext(TP)}function AP(e,t,a,o=!0,l){const[c,d]=x.useState(),f=ra(l?`${l}-label`:void 0),m=e??t??c;return Pe(()=>{const g=e||t||!o?void 0:MP(a.current,f);c!==g&&d(g)}),m}function MP(e,t){const a=zP(e);if(a)return!a.id&&t&&(a.id=t),a.id||void 0}function zP(e){if(!e)return;const t=e.parentElement;if(t&&t.tagName==="LABEL")return t;const a=e.id;if(a){const l=e.nextElementSibling;if(l&&l.htmlFor===a)return l}const o=e.labels;return o&&o[0]}function kp(e={}){const{id:t,implicit:a=!1,controlRef:o}=e,{controlId:l,registerControlId:c}=jp(),d=ra(t),f=a?l:void 0,m=Hn(()=>Symbol()),g=x.useRef(!1),h=x.useRef(t!=null),b=He(()=>{!g.current||c===Nn||(g.current=!1,c(m.current,void 0))});return Pe(()=>{if(c===Nn)return;let _;if(a){const j=o?.current;bt(j)&&j.closest("label")!=null?_=t??null:_=f??d}else if(t!=null)h.current=!0,_=t;else if(h.current)_=d;else{b();return}if(_===void 0){b();return}g.current=!0,c(m.current,_)},[t,o,f,c,a,d,m,b]),x.useEffect(()=>b,[b]),l??d}function O_(e,t,a,o,l=!0,c){const{registerFieldControl:d}=du(),f=Hn(()=>Symbol());Pe(()=>{const m=f.current;if(!l){d(m,void 0);return}d(m,{controlRef:e,getValue:o,id:t,name:c,value:a})},[e,l,o,t,c,d,f,a]),Pe(()=>{const m=f.current;return()=>{d(m,void 0)}},[d,f])}const OP=x.forwardRef(function(t,a){const{render:o,className:l,id:c,name:d,value:f,disabled:m=!1,onValueChange:g,defaultValue:h,autoFocus:b=!1,style:_,...j}=t,{state:E,name:y,disabled:k,setTouched:N,setDirty:w,validityData:S,setFocused:R,setFilled:A,validationMode:T,validation:z}=du(),{clearErrors:M}=z_(),L=k||m,P=y??d,B={...E,disabled:L},{labelId:D}=jp(),$=kp({id:c});Pe(()=>{const W=f!=null;z.inputRef.current?.value||W&&f!==""?A(!0):W&&f===""&&A(!1)},[z.inputRef,A,f]);const q=x.useRef(null);Pe(()=>{b&&q.current===Kn(vt(q.current))&&R(!0)},[b,R]);const[G]=ni({controlled:f,default:h,name:"FieldControl",state:"value"}),U=f!==void 0,V=U?G:void 0,X=He(()=>z.inputRef.current?.value);return O_(z.inputRef,$,V,X,!L,d),Et("input",t,{ref:[a,q],state:B,props:[{id:$,disabled:L,name:P,ref:z.inputRef,"aria-labelledby":D,autoFocus:b,...U?{value:V}:{defaultValue:h},onChange(W){const I=W.currentTarget.value;g?.(I,rt(ka,W.nativeEvent)),w(I!==(S.initialValue??"")),A(I!==""),W.nativeEvent.defaultPrevented||(M(P),z.change(I))},onFocus(){R(!0)},onBlur(W){N(!0),R(!1),T==="onBlur"&&z.commit(W.currentTarget.value)},onKeyDown(W){W.currentTarget.tagName==="INPUT"&&W.key==="Enter"&&(N(!0),z.commit(W.currentTarget.value))}},j,W=>z.getValidationProps(L,W)],stateAttributesMapping:M_})}),DP=x.forwardRef(function(t,a){return n.jsx(OP,{ref:a,...t})});function PP({className:e,type:t,...a}){return n.jsx(DP,{type:t,"data-slot":"input",className:St("h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",e),...a})}function LP({className:e,...t}){return n.jsx("textarea",{"data-slot":"textarea",className:St("flex field-sizing-content min-h-16 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-base transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",e),...t})}function IP(e){return Et(e.defaultTagName??"div",e,e)}const BP=A_("group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",{variants:{variant:{default:"bg-primary text-primary-foreground [a]:hover:bg-primary/80",secondary:"bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",destructive:"bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20",outline:"border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",ghost:"hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",link:"text-primary underline-offset-4 hover:underline"}},defaultVariants:{variant:"default"}});function $P({className:e,variant:t="default",render:a,...o}){return IP({defaultTagName:"span",props:Ss({className:St(BP({variant:t}),e)},o),render:a,state:{slot:"badge",variant:t}})}const xN=x.createContext(void 0);function UP(){const e=x.useContext(xN);if(e===void 0)throw new Error(gn(63));return e}const bN={...M_,checked(e){return e?{"data-checked":""}:{"data-unchecked":""}}},qP=x.forwardRef(function(t,a){const{checked:o,className:l,defaultChecked:c,"aria-labelledby":d,form:f,id:m,inputRef:g,name:h,nativeButton:b=!1,onCheckedChange:_,readOnly:j=!1,required:E=!1,disabled:y=!1,render:k,uncheckedValue:N,value:w,style:S,...R}=t,{clearErrors:A}=z_(),{state:T,setTouched:z,setDirty:M,validityData:L,setFilled:P,setFocused:B,validationMode:D,disabled:$,name:q,validation:G}=du(),{labelId:U}=jp(),V=$||y,X=q??h,Q=x.useRef(null),W=rr(Q,g,G.inputRef),I=x.useRef(null),K=ra(),ee=kp({id:m,implicit:!1,controlRef:I}),F=b?void 0:ee,[ne,Z]=ni({controlled:o,default:!!c,name:"Switch",state:"checked"});O_(I,K,ne,void 0,!V,h),Pe(()=>{Q.current&&P(Q.current.checked)},[P]),v_(ne,()=>{A(X),M(ne!==L.initialValue),P(ne),G.change(ne)});const{getButtonProps:fe,buttonRef:Y}=no({disabled:V,native:b}),oe=AP(d,U,Q,!b,F),ve={id:b?ee:K,role:"switch","aria-checked":ne,"aria-readonly":j||void 0,"aria-required":E||void 0,"aria-labelledby":oe,onFocus(){V||B(!0)},onBlur(){const Re=Q.current;!Re||V||(z(!0),B(!1),D==="onBlur"&&G.commit(Re.checked))},onClick(Re){if(j||V)return;Re.preventDefault();const Ae=Q.current;Ae&&Ac(Ae,Re)}},le={...G.getValidationProps(V),checked:ne,disabled:V,form:f,id:F,name:X,required:E,style:X?NS:Ub,tabIndex:-1,type:"checkbox","aria-hidden":!0,ref:W,onChange(Re){if(Re.nativeEvent.defaultPrevented)return;if(j){Re.preventDefault();return}const Ae=Re.currentTarget.checked,Ie=rt(ka,Re.nativeEvent);_?.(Ae,Ie),!Ie.isCanceled&&Z(Ae)},onClick(Re){Re.stopPropagation()},onFocus(){I.current?.focus()},...w!==void 0?{value:w}:sn},xe=x.useMemo(()=>({...T,checked:ne,disabled:V,readOnly:j,required:E}),[T,ne,V,j,E]),ke=Et("span",t,{state:xe,ref:[a,I,Y],props:[ve,R,fe,Re=>G.getValidationProps(V,Re)],stateAttributesMapping:bN});return n.jsxs(xN.Provider,{value:xe,children:[ke,!ne&&X&&N!==void 0&&n.jsx("input",{type:"hidden",form:f,name:X,value:N,disabled:V}),n.jsx("input",{...le,suppressHydrationWarning:!0})]})}),HP=x.forwardRef(function(t,a){const{render:o,className:l,style:c,...d}=t,f=UP();return Et("span",t,{state:f,ref:a,stateAttributesMapping:bN,props:d})});function VP({className:e,size:t="default",...a}){return n.jsx(qP,{"data-slot":"switch","data-size":t,className:St("peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:bg-primary data-unchecked:bg-input dark:data-unchecked:bg-input/80 data-disabled:cursor-not-allowed data-disabled:opacity-50",e),...a,children:n.jsx(HP,{"data-slot":"switch-thumb",className:"pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 group-data-[size=default]/switch:data-checked:translate-x-[calc(100%-2px)] group-data-[size=sm]/switch:data-checked:translate-x-[calc(100%-2px)] dark:data-checked:bg-primary-foreground group-data-[size=default]/switch:data-unchecked:translate-x-0 group-data-[size=sm]/switch:data-unchecked:translate-x-0 dark:data-unchecked:bg-foreground"})})}function FP({className:e,...t}){return n.jsx(Js,{role:"status","aria-label":"Loading",className:St("size-4 animate-spin",e),...t})}const _N=x.createContext(void 0);function Fo(e){const t=x.useContext(_N);if(!e&&t===void 0)throw new Error(gn(27));return t}const vN=x.forwardRef(function(t,a){const{render:o,className:l,style:c,forceRender:d=!1,...f}=t,m=Fo(),g=m.useState("open"),h=m.useState("nested"),b=m.useState("mounted"),_=m.useState("transitionStatus");return Et("div",t,{state:{open:g,transitionStatus:_},ref:[m.context.backdropRef,a],stateAttributesMapping:d_,props:[{role:"presentation",hidden:!b,style:{userSelect:"none",WebkitUserSelect:"none"}},f],enabled:d||!h})}),wp=x.forwardRef(function(t,a){const{render:o,className:l,style:c,disabled:d=!1,nativeButton:f=!0,...m}=t,g=Fo(),h=g.useState("open"),{getButtonProps:b,buttonRef:_}=no({disabled:d,native:f}),j={disabled:d};function E(y){h&&g.setOpen(!1,rt(E4,y.nativeEvent))}return Et("button",t,{state:j,ref:[a,_],props:[{onClick:E},m,b]})}),yN=x.forwardRef(function(t,a){const{render:o,className:l,style:c,id:d,...f}=t,m=Fo(),g=ra(d);return m.useSyncedValueWithCleanup("descriptionElementId",g),Et("p",t,{ref:a,props:[{id:g},f]})}),jN=x.createContext(void 0);function GP(){const e=x.useContext(jN);if(e===void 0)throw new Error(gn(26));return e}const YP={...au,...Ho,nestedDialogOpen(e){return e?{"data-nested-dialog-open":""}:null}},kN=x.forwardRef(function(t,a){const{render:o,className:l,style:c,finalFocus:d,initialFocus:f,...m}=t,g=Fo(),h=g.useState("descriptionElementId"),b=g.useState("disablePointerDismissal"),_=g.useState("floatingRootContext"),j=g.useState("popupProps"),E=g.useState("modal"),y=g.useState("mounted"),k=g.useState("nested"),N=g.useState("nestedOpenDialogCount"),w=g.useState("open"),S=g.useState("openMethod"),R=g.useState("titleElementId"),A=g.useState("transitionStatus"),T=g.useState("role"),z=_.useState("floatingId");GP(),Ca({open:w,ref:g.context.popupRef,onComplete(){w&&g.context.onOpenChangeComplete?.(!0)}});const M=f===void 0?RO(g.context.popupRef):f,L=N>0,P=g.useStateSetter("popupElement"),D=Et("div",t,{state:{open:w,nested:k,transitionStatus:A,nestedDialogOpen:L},props:[j,{id:z,"aria-labelledby":R,"aria-describedby":h,role:T,...dp,hidden:!y,onKeyDown($){xp.has($.key)&&$.stopPropagation()},style:{"--nested-dialogs":N}},m],ref:[a,g.context.popupRef,P],stateAttributesMapping:YP});return n.jsx(Jb,{context:_,openInteractionType:S,disabled:!y,closeOnFocusOut:!b,initialFocus:M,returnFocus:d,modal:E!==!1,restoreFocus:"popup",children:D})}),wN=x.forwardRef(function(t,a){const{keepMounted:o=!1,...l}=t,c=Fo(),d=c.useState("mounted"),f=c.useState("modal"),m=c.useState("open");return d||o?n.jsx(jN.Provider,{value:o,children:n.jsxs(Qb,{ref:a,...l,children:[d&&f===!0&&n.jsx(__,{ref:c.context.internalBackdropRef,inert:gp(!m)}),t.children]})}):null});function KP({store:e,parentContext:t,isDrawer:a}){const o=e.useState("open"),l=e.useState("disablePointerDismissal"),c=e.useState("modal"),d=e.useState("popupElement"),f=e.useState("floatingRootContext"),[m,g]=x.useState(0),[h,b]=x.useState(0),_=m===0,j=ip(f,{outsidePressEvent(){return e.context.internalBackdropRef.current||e.context.backdropRef.current?"intentional":{mouse:c==="trap-focus"?"sloppy":"intentional",touch:"sloppy"}},outsidePress(E){if(!e.context.outsidePressEnabledRef.current||"button"in E&&E.button!==0)return!1;if("touches"in E){if(E.type==="touchend"){if(E.changedTouches.length!==1||E.touches.length!==0)return!1}else if(E.touches.length!==1)return!1}const y=qn(E);if(_&&!l){if(c){const k=e.context.internalBackdropRef.current,N=e.context.backdropRef.current;return k||N?k===y||N===y||Ze(y,d)&&!y?.hasAttribute("data-base-ui-portal"):!0}return!0}return!1},escapeKey:_});return GC(o&&c===!0,d),e.useContextCallback("onNestedDialogOpen",(E,y)=>{g(E),b(y)}),Pe(()=>(t?.onNestedDialogOpen&&(o?t.onNestedDialogOpen(m+1,h+(a?1:0)):t.onNestedDialogOpen(0,0)),()=>{t?.onNestedDialogOpen&&o&&t.onNestedDialogOpen(0,0)}),[a,o,m,h,t]),r_(e,{activeTriggerProps:j.reference,inactiveTriggerProps:j.trigger,popupProps:j.floating,nestedOpenDialogCount:m,nestedOpenDrawerCount:h}),null}const XP={...i_,modal:e=>e.modal,nested:e=>e.nested,nestedOpenDialogCount:e=>e.nestedOpenDialogCount,nestedOpenDrawerCount:e=>e.nestedOpenDrawerCount,disablePointerDismissal:e=>e.disablePointerDismissal,openMethod:e=>e.openMethod,descriptionElementId:e=>e.descriptionElementId,titleElementId:e=>e.titleElementId,viewportElement:e=>e.viewportElement,role:e=>e.role};class QP extends nu{constructor(t,a,o){const l=new su,c=WP(t,l,a,o);super(c,ZP(l),XP)}setOpen=(t,a)=>{if(a.preventUnmountOnClose=()=>{this.set("preventUnmountingOnClose",!0)},!t&&a.trigger==null&&this.state.activeTriggerId!=null&&(a.trigger=this.state.activeTriggerElement??void 0),this.context.onOpenChange?.(t,a),a.isCanceled)return;this.state.floatingRootContext.dispatchOpenChange(t,a);const o={open:t};n_(o,t,a.trigger),this.update(o)}}function WP(e,t,a,o=!1){const l={...o_(),modal:!0,disablePointerDismissal:!1,viewportElement:null,descriptionElementId:void 0,titleElementId:void 0,openMethod:null,nested:!1,nestedOpenDialogCount:0,nestedOpenDrawerCount:0,role:"dialog",...e};return l.floatingRootContext=hC(t,a,o),l}function ZP(e){return{popupRef:x.createRef(),backdropRef:x.createRef(),internalBackdropRef:x.createRef(),outsidePressEnabledRef:{current:!0},triggerElements:e,onOpenChange:void 0,onOpenChangeComplete:void 0}}function JP(e,t){const{children:a,open:o,defaultOpen:l=!1,onOpenChange:c,onOpenChangeComplete:d,disablePointerDismissal:f=!1,modal:m=!0,actionsRef:g,handle:h,triggerId:b,defaultTriggerId:_=null}=t,j=e==="drawer",E=m,y=f,k="dialog",N=Fo(!0),w=N!=null,S={modal:E,disablePointerDismissal:y,nested:w,role:k},R=pC((P,B)=>new QP({open:l,openProp:o,activeTriggerId:_,triggerIdProp:b,...S},P,B),!0);R.useControlledProp("openProp",o),R.useControlledProp("triggerIdProp",b),R.useSyncedValues(S),R.useContextCallback("onOpenChange",c),R.useContextCallback("onOpenChangeComplete",d);const A=R.useState("open"),T=R.useState("mounted"),z=R.useState("payload");MO(R,A),s_(R);const{forceUnmount:M}=a_(A,R);x.useImperativeHandle(g,()=>({unmount:M,close:()=>R.setOpen(!1,rt(Bb))}),[M,R]);const L=A||T;return n.jsxs(_N.Provider,{value:R,children:[h&&n.jsx(t_,{handle:h,store:R}),L&&n.jsx(KP,{store:R,parentContext:N?.context,isDrawer:j}),typeof a=="function"?a({payload:z}):a]})}function SN(e){return JP("dialog",e)}const CN=x.forwardRef(function(t,a){const{render:o,className:l,style:c,id:d,...f}=t,m=Fo(),g=ra(d);return m.useSyncedValueWithCleanup("titleElementId",g),Et("h2",t,{ref:a,props:[{id:g},f]})});function Bx({...e}){return n.jsx(SN,{"data-slot":"dialog",...e})}function eL({...e}){return n.jsx(wN,{"data-slot":"dialog-portal",...e})}function tL({...e}){return n.jsx(wp,{"data-slot":"dialog-close",...e})}function nL({className:e,...t}){return n.jsx(vN,{"data-slot":"dialog-overlay",className:St("fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",e),...t})}function $x({className:e,children:t,showCloseButton:a=!0,...o}){return n.jsxs(eL,{children:[n.jsx(nL,{}),n.jsxs(kN,{"data-slot":"dialog-content",className:St("fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",e),...o,children:[t,a&&n.jsxs(wp,{"data-slot":"dialog-close",render:n.jsx(or,{variant:"ghost",className:"absolute top-2 right-2",size:"icon-sm"}),children:[n.jsx(gs,{}),n.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function Ux({className:e,...t}){return n.jsx("div",{"data-slot":"dialog-header",className:St("flex flex-col gap-2",e),...t})}function Rk({className:e,showCloseButton:t=!1,children:a,...o}){return n.jsxs("div",{"data-slot":"dialog-footer",className:St("-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",e),...o,children:[a,t&&n.jsx(wp,{render:n.jsx(or,{variant:"outline"}),children:"Close"})]})}function qx({className:e,...t}){return n.jsx(CN,{"data-slot":"dialog-title",className:St("font-heading text-base leading-none font-medium",e),...t})}function sL({className:e,...t}){return n.jsx(yN,{"data-slot":"dialog-description",className:St("text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",e),...t})}const aL={primary:"default",secondary:"outline",ghost:"ghost",destructive:"destructive"},rL={sm:"sm",md:"default"};function re({variant:e="secondary",size:t="md",loading:a,className:o,children:l,disabled:c,type:d="button",...f}){return n.jsxs(or,{type:d,variant:aL[e],size:rL[t],disabled:c||a,className:o,...f,children:[a?n.jsx(bn,{size:14}):null,l]})}function Ee(e){return n.jsx(PP,{...e})}function un(e){return n.jsx(LP,{...e})}function oL(e){return n.jsx("select",{...e,className:ge("h-8 w-full rounded-lg border border-input bg-transparent px-2.5 text-sm outline-none transition-colors focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50",e.className)})}function ie({label:e,hint:t,badge:a,children:o}){return n.jsxs("div",{className:"block space-y-1",children:[n.jsxs("span",{className:"flex items-center gap-1.5 text-xs font-medium text-muted-foreground",children:[e,a&&n.jsx("span",{className:"rounded bg-muted px-1 py-0.5 text-[9px] font-semibold uppercase tracking-wide text-muted-foreground",children:a})]}),o,t&&n.jsx("span",{className:"block text-[11px] text-muted-foreground/70",children:t})]})}function Bt({checked:e,onChange:t,label:a,disabled:o}){return n.jsxs("label",{className:ge("inline-flex items-center gap-2",o&&"opacity-50"),children:[n.jsx(VP,{checked:e,onCheckedChange:t,disabled:o}),a&&n.jsx("span",{className:"text-sm",children:a})]})}function $e({children:e,tone:t="muted",className:a}){const o=t==="danger"?"destructive":t==="muted"?"secondary":"outline",l={muted:"",danger:"",success:"text-emerald-400 border-emerald-500/30",warning:"text-amber-400 border-amber-500/30",info:"text-sky-400 border-sky-500/30"};return n.jsx($P,{variant:o,className:ge("rounded-md",l[t],a),children:e})}function Xt({open:e,onClose:t,title:a,description:o,children:l,footer:c,size:d="md"}){const f={sm:"sm:max-w-md",md:"sm:max-w-lg",lg:"sm:max-w-2xl",xl:"sm:max-w-4xl"};return n.jsx(Bx,{open:e,onOpenChange:m=>{m||t()},children:n.jsxs($x,{className:ge("flex max-h-[88vh] w-full flex-col gap-0 p-0",f[d]),children:[(a||o)&&n.jsxs(Ux,{className:"shrink-0 border-b border-border px-5 py-4 pr-12",children:[a&&n.jsx(qx,{children:a}),o&&n.jsx(sL,{children:o})]}),n.jsx("div",{className:"min-h-0 flex-1 overflow-auto px-5 py-4",children:l}),c&&n.jsx("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border px-5 py-4",children:c})]})})}function bn({size:e=14}){return n.jsx(FP,{style:{width:e,height:e}})}function ft({children:e}){return n.jsx("div",{className:"rounded-lg border border-dashed border-border bg-muted/20 px-4 py-6 text-center text-sm text-muted-foreground",children:e})}function st({label:e="Cargando…"}){return n.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[n.jsx(bn,{})," ",e]})}const NN=x.createContext(null);let lL=1;function iL({children:e}){const[t,a]=x.useState([]),o=x.useCallback((c,d)=>{const f=lL++;a(m=>[...m,{id:f,kind:c,message:d}]),setTimeout(()=>{a(m=>m.filter(g=>g.id!==f))},4500)},[]),l=x.useMemo(()=>({show:o,success:c=>o("success",c),error:c=>o("error",c),info:c=>o("info",c)}),[o]);return x.useEffect(()=>(window.__apxToast=l,()=>{delete window.__apxToast}),[l]),n.jsxs(NN.Provider,{value:l,children:[e,n.jsx("div",{className:"pointer-events-none fixed bottom-4 right-4 z-[100] flex w-80 max-w-[calc(100vw-2rem)] flex-col gap-2",children:t.map(c=>n.jsx("div",{className:ge("pointer-events-auto overflow-hidden rounded-lg border bg-card px-3 py-2 text-sm shadow-lg",c.kind==="success"&&"border-emerald-500/40",c.kind==="error"&&"border-destructive/60",c.kind==="info"&&"border-border"),children:n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("span",{className:ge("mt-1 size-2 shrink-0 rounded-full",c.kind==="success"&&"bg-emerald-500",c.kind==="error"&&"bg-destructive",c.kind==="info"&&"bg-sky-500")}),n.jsx("span",{className:"flex-1 break-words",children:c.message})]})},c.id))})]})}function Je(){const e=x.useContext(NN);if(!e)throw new Error("useToast must be used inside <ToastProvider>");return e}function EN(){const{data:e,error:t,isLoading:a}=Be("/health",()=>iP.get(),{refreshInterval:Qf.health});return{health:e,error:t,isLoading:a,isUp:!t&&!!e}}function cL(){const{data:e,error:t,isLoading:a,mutate:o}=Be("/engines",()=>Hc.list());return{engines:e?.engines||[],error:t,isLoading:a,mutate:o}}function uL(){const{data:e,error:t,isLoading:a,mutate:o}=Be("/telegram/status",()=>Dn.status(),{refreshInterval:Qf.telegramStatus});return{status:e,error:t,isLoading:a,mutate:o}}function D_(){const{data:e,error:t,isLoading:a,mutate:o}=Be("/telegram/channels",()=>Dn.channels.list());return{channels:e?.channels||[],error:t,isLoading:a,mutate:o}}function P_(){const{data:e,error:t,isLoading:a,mutate:o}=Be("/telegram/contacts",()=>Dn.contacts.list());return{contacts:e?.contacts||[],roles:e?.roles||{},channelOwners:e?.channel_owners||[],error:t,isLoading:a,mutate:o}}function ps(e){return typeof e=="string"&&e.startsWith("*** set ***")}function Fr(e,t="(no seteada)"){return ps(e)?e:t}function Po(e){if(typeof e!="string")return null;const t=e.match(/\(\.\.\.([^)]+)\)/);return t?t[1]:null}function RN({channel:e,onClose:t,onSaved:a}){const o=Je(),[l,c]=x.useState(!1),[d,f]=x.useState({name:""});x.useEffect(()=>{f(e?{...e,bot_token:""}:{name:""})},[e?.name]);const m=async()=>{if(!d.name?.trim()){o.error(u("telegram_channel_dialog.name_required"));return}c(!0);try{e&&e.name!==""&&e?.name===d.name?await Dn.channels.patch(e.name,d):await Dn.channels.upsert(d),o.success(u("telegram_channel_dialog.saved")),a()}catch(g){o.error(g.message)}finally{c(!1)}};return n.jsx(Xt,{open:!!e,onClose:t,title:e?.name?u("telegram_channel_dialog.edit_title",{name:e.name}):u("telegram_channel_dialog.new_title"),description:u("telegram_ui.channel_dialog_desc"),footer:n.jsxs(n.Fragment,{children:[n.jsx(re,{variant:"ghost",onClick:t,disabled:l,children:u("common.cancel")}),n.jsx(re,{variant:"primary",onClick:m,loading:l,children:u("common.save")})]}),children:n.jsxs("div",{className:"space-y-3",children:[n.jsx(ie,{label:u("telegram_channel_dialog.name_label"),children:n.jsx(Ee,{value:d.name,onChange:g=>f({...d,name:g.target.value}),disabled:!!e?.name})}),n.jsx(ie,{label:u("telegram_channel_dialog.token_label"),hint:e?.bot_token?Fr(e.bot_token):u("telegram_ui.bot_token_hint"),children:n.jsx(Ee,{type:"password",value:d.bot_token||"",onChange:g=>f({...d,bot_token:g.target.value}),placeholder:e?.bot_token?Fr(e.bot_token):""})}),n.jsx(ie,{label:u("telegram_channel_dialog.chat_id"),children:n.jsx(Ee,{value:d.chat_id||"",onChange:g=>f({...d,chat_id:g.target.value})})}),n.jsx(ie,{label:u("telegram_channel_dialog.project_label"),hint:u("telegram_channel_dialog.project_hint"),children:n.jsx(Ee,{value:d.project||"",onChange:g=>f({...d,project:g.target.value})})}),n.jsx(ie,{label:u("telegram_channel_dialog.route_label"),hint:u("telegram_channel_dialog.route_hint"),children:n.jsx(Ee,{value:d.route_to_agent||"",onChange:g=>f({...d,route_to_agent:g.target.value})})}),n.jsx(ie,{label:u("telegram_channel_dialog.owner_label"),hint:u("telegram_channel_dialog.owner_hint"),children:n.jsx(Ee,{value:d.owner_user_id!=null?String(d.owner_user_id):"",onChange:g=>{const h=g.target.value.trim();f({...d,owner_user_id:h===""?void 0:/^\d+$/.test(h)?Number(h):h})},placeholder:"889721252"})}),n.jsx(Bt,{checked:!!d.respond_with_engine,onChange:g=>f({...d,respond_with_engine:g}),label:u("telegram_channel_dialog.respond_label")})]})})}function TN({channel:e,onClose:t}){const a=Je(),[o,l]=x.useState(u("admin.telegram_default_message")),[c,d]=x.useState(!1),f=async()=>{if(!(!o.trim()||!e)){d(!0);try{await Dn.send({text:o,channel:e.name}),a.success(u("telegram_ui.message_sent")),t()}catch(m){a.error(m.message)}finally{d(!1)}}};return n.jsx(Xt,{open:!!e,onClose:t,title:e?u("telegram_send_dialog.title",{name:e.name}):"",description:e?u("telegram_ui.send_chat_id",{id:e.chat_id||"—"}):"",footer:n.jsxs(n.Fragment,{children:[n.jsx(re,{variant:"ghost",onClick:t,disabled:c,children:u("common.cancel")}),n.jsx(re,{variant:"primary",onClick:f,loading:c,children:u("chat_ui.send")})]}),children:n.jsx(ie,{label:u("telegram_ui.message_label"),children:n.jsx(un,{rows:4,value:o,onChange:m=>l(m.target.value)})})})}function AN({bare:e=!1}){const t=Je(),{contacts:a,roles:o,channelOwners:l,isLoading:c,mutate:d}=P_(),f=new Set(l.filter(_=>_.owner_user_id!=null).map(_=>String(_.owner_user_id))),m=Array.from(new Set(["owner","guest",...Object.keys(o)])),g=async(_,j)=>{try{await Dn.contacts.patch(_.user_id,{role:j}),t.success(u("telegram_ui.role_assigned",{name:_.name||_.user_id,role:j})),d()}catch(E){t.error(E.message)}},h=async _=>{if(confirm(u("telegram_contacts.delete_confirm",{name:_.name||String(_.user_id)})))try{await Dn.contacts.remove(_.user_id),t.success(u("telegram_contacts.removed")),d()}catch(j){t.error(j.message)}},b=n.jsxs(n.Fragment,{children:[c&&n.jsx(st,{}),!c&&a.length===0&&n.jsx(ft,{children:u("telegram_contacts.empty")}),a.length>0&&n.jsx("ul",{className:"space-y-2 text-sm",children:a.map(_=>{const j=f.has(String(_.user_id)),E=j?"owner":_.role||"guest";return n.jsxs("li",{className:"rounded-md border border-border bg-muted/30 px-3 py-2",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("span",{className:"font-medium",children:_.name||"—"}),_.username&&n.jsxs("span",{className:"ml-2 text-xs text-muted-fg",children:["@",_.username]}),j&&n.jsx($e,{tone:"success",children:u("telegram_contacts.owner_badge")})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(qe,{content:u(j?"telegram_contacts.owner_hint":"telegram_contacts.assign_role"),children:n.jsx(oL,{value:E,disabled:j,onChange:y=>g(_,y.target.value),children:m.map(y=>n.jsx("option",{value:y,children:y},y))})}),n.jsx(re,{size:"sm",variant:"destructive",onClick:()=>h(_),children:u("common.delete")})]})]}),n.jsxs("div",{className:"mt-1 grid grid-cols-3 gap-2 text-xs text-muted-fg",children:[n.jsxs("span",{children:["user_id: ",String(_.user_id)]}),n.jsxs("span",{children:[u("telegram_contacts.last_seen")," ",_.last_seen?_.last_seen.slice(0,10):"—"]}),n.jsx("span",{children:dL(o[E])})]})]},String(_.user_id))})})]});return e?b:n.jsx(Ve,{title:u("telegram_contacts.title"),description:u("telegram_contacts.desc"),children:b})}function dL(e){return!e||e.tools===void 0?"":e.tools==="*"?u("telegram_contacts.tools_all"):Array.isArray(e.tools)?e.tools.length?`${u("telegram_contacts.tools_label")} ${e.tools.join(", ")}`:u("telegram_contacts.tools_none"):""}function fL(){const e=Pn(),[t,a]=Uo(),o=Je(),{health:l,isUp:c}=EN(),{projects:d,isLoading:f,mutate:m}=iu(),{engines:g,isLoading:h}=cL(),{status:b,mutate:_}=uL(),{channels:j,isLoading:E,mutate:y}=D_(),[k,N]=x.useState(null),[w,S]=x.useState(null),R=async()=>{try{await ai.reload(),o.success(u("admin.reload_success"))}catch(M){o.error(M.message)}},A=async()=>{try{b?.enabled?(await Dn.stop(),o.info(u("admin.telegram_polling_stopped"))):(await Dn.start(),o.success(u("admin.telegram_polling_started"))),_()}catch(M){o.error(M.message)}},T=async M=>{if(confirm(u("telegram_channels.delete_confirm",{name:M})))try{await Dn.channels.remove(M),o.success(u("admin.telegram_channel_removed")),y()}catch(L){o.error(L.message)}},z=async(M,L)=>{if(confirm(u("admin.unregister_confirm",{label:L})))try{await Zn.remove(M),o.success(u("project.unregistered")),m()}catch(P){o.error(P.message)}};return n.jsxs("div",{className:"mx-auto max-w-5xl space-y-6 p-6","data-testid":"screen-admin",children:[n.jsxs("header",{className:"flex items-end justify-between",children:[n.jsxs("div",{children:[n.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:u("admin.title")}),n.jsx("p",{className:"text-sm text-muted-fg",children:u("admin.subtitle")})]}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx(qe,{content:u("daemon.reload_hint"),children:n.jsxs(re,{size:"sm",onClick:R,children:[u("common.reload")," config"]})}),n.jsxs(re,{size:"sm",variant:"primary",onClick:()=>{const M=new URLSearchParams(t);M.set("action","add-project"),a(M)},children:[n.jsx(Dt,{size:14})," ",u("nav.project")]})]})]}),n.jsx(Ve,{title:u("daemon.version"),children:n.jsxs("div",{className:"grid grid-cols-3 gap-3 text-sm",children:[n.jsx(xh,{label:u("daemon.version"),value:l?.version||"—"}),n.jsx(xh,{label:u("daemon.uptime"),value:l?`${l.uptime_s}s`:"—"}),n.jsx(xh,{label:u("daemon.status"),value:u(c?"daemon.running":"daemon.down"),ok:c})]})}),n.jsxs(Ve,{title:u("admin.engines_title"),description:u("admin.engines_subtitle"),children:[h&&n.jsx(st,{}),n.jsx("div",{className:"flex flex-wrap gap-1.5",children:g.map(M=>n.jsx($e,{tone:"info",children:M},M))})]}),n.jsxs(Ve,{title:u("admin.telegram_title"),description:u("admin.telegram_subtitle"),action:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Bt,{checked:!!b?.enabled,onChange:A,label:b?.enabled?u("admin.telegram_polling_on"):u("admin.telegram_polling_off")}),n.jsxs(re,{size:"sm",onClick:()=>N({name:""}),children:[n.jsx(Dt,{size:14})," ",u("admin.telegram_add_channel")]})]}),children:[E&&n.jsx(st,{}),j.length===0&&n.jsx(ft,{children:u("common.none_yet")}),n.jsx("ul",{className:"space-y-2 text-sm",children:j.map(M=>n.jsxs("li",{className:"rounded-md border border-border bg-muted/30 px-3 py-2",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("span",{className:"font-medium",children:M.name}),n.jsxs("div",{className:"flex items-center gap-2",children:[M.project&&n.jsxs($e,{tone:"success",children:["project = ",M.project]}),n.jsxs(re,{size:"sm",variant:"ghost",onClick:()=>S(M),children:[n.jsx(Sa,{size:13})," ",u("admin.telegram_send_test")]}),n.jsx(re,{size:"sm",variant:"secondary",onClick:()=>N(M),children:u("common.edit")}),n.jsx(re,{size:"sm",variant:"destructive",onClick:()=>T(M.name),children:u("common.delete")})]})]}),n.jsxs("div",{className:"mt-1 grid grid-cols-3 gap-2 text-xs text-muted-fg",children:[n.jsxs("span",{children:["chat_id: ",M.chat_id||"—"]}),n.jsxs("span",{children:["route_to_agent: ",M.route_to_agent||"default APX"]}),n.jsxs("span",{children:["engine: ",M.respond_with_engine?u("admin.engine_badge"):u("admin.engine_badge_no")]})]})]},M.name))})]}),n.jsx(AN,{}),n.jsxs(Ve,{title:u("admin.projects_title"),description:u("admin.projects_subtitle"),children:[f&&n.jsx(st,{}),n.jsx("ul",{className:"divide-y divide-border",children:d.map(M=>n.jsxs("li",{className:"flex items-center gap-3 py-2",children:[n.jsxs("span",{className:"w-10 font-mono text-xs text-muted-fg",children:["#",M.id]}),n.jsxs("button",{type:"button",className:"flex-1 text-left hover:underline",onClick:()=>e(`/p/${M.id}`),children:[n.jsx("span",{className:"font-medium",children:M.name||M.path.split("/").pop()}),n.jsx("span",{className:"ml-2 text-xs text-muted-fg",children:M.path})]}),n.jsxs($e,{children:[M.agents??0," ",u("admin.agents_badge")]}),Number(M.id)!==0&&n.jsx(re,{size:"sm",variant:"destructive",onClick:()=>z(String(M.id),M.name||M.path),children:u("admin.unregister")})]},M.id))})]}),n.jsx(RN,{channel:k,onClose:()=>N(null),onSaved:()=>{N(null),y()}}),n.jsx(TN,{channel:w,onClose:()=>S(null)})]})}function xh({label:e,value:t,ok:a}){return n.jsxs("div",{className:"rounded-md border border-border bg-muted/30 p-3",children:[n.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-fg",children:e}),n.jsxs("div",{className:"mt-1 flex items-center gap-2 text-base font-medium",children:[a!==void 0&&n.jsx(uu,{ok:a}),n.jsx("span",{children:t})]})]})}const MN=x.createContext(null),zN=x.createContext(null),ON=x.createContext(""),DN=x.createContext(null),PN=x.createContext(null),LN=x.createContext(null);function pL({children:e}){const[t,a]=x.useState(null),[o,l]=x.useState(""),[c,d]=x.useState(null);return n.jsx(zN.Provider,{value:a,children:n.jsx(MN.Provider,{value:t,children:n.jsx(DN.Provider,{value:l,children:n.jsx(ON.Provider,{value:o,children:n.jsx(LN.Provider,{value:d,children:n.jsx(PN.Provider,{value:c,children:e})})})})})})}function mL(){return x.useContext(MN)}function gL(e,t){const a=x.useContext(zN);x.useEffect(()=>(a?.({collapsed:e,toggle:t}),()=>a?.(null)),[e,t,a])}function hL(){return x.useContext(ON)}function xL(e){const t=x.useContext(DN);x.useEffect(()=>(t?.(e),()=>t?.("")),[e,t])}function bL(){return x.useContext(PN)}function _L(e){const t=x.useContext(LN);x.useEffect(()=>(t?.(e),()=>t?.(null)),[e,t])}function IN({sections:e,active:t,onChange:a,collapsed:o,onToggleCollapse:l,actions:c,contentClassName:d,testId:f,children:m}){return gL(o,l),n.jsxs("div",{className:"flex h-full",children:[n.jsx(AD,{sections:e,active:t,onChange:a,collapsed:o}),n.jsxs("div",{className:"flex min-w-0 flex-1 flex-col overflow-hidden",children:[c?n.jsx("div",{className:"flex shrink-0 items-center justify-end gap-2 px-6 pt-3",children:c}):null,n.jsx("div",{className:ge("flex-1 min-h-0 overflow-y-auto",d),"data-testid":f,children:m})]})]})}function vL({className:e}){return n.jsx("svg",{className:e,viewBox:"0 0 24 24",fill:"currentColor",children:n.jsx("path",{d:"M18.833 9.637a4.167 4.167 0 1 1 0 8.333 4.167 4.167 0 0 1 0-8.333zm-13.666 0a4.167 4.167 0 1 1 0 8.333 4.167 4.167 0 0 1 0-8.333zM12 2a4.167 4.167 0 1 1 0 8.333A4.167 4.167 0 0 1 12 2z"})})}function BN({className:e}){return n.jsx("svg",{className:e,viewBox:"0 0 24 24",fill:"currentColor",children:n.jsx("path",{d:"M19.355 18.538a68.967 68.959 0 0 0 1.858-2.954.81.81 0 0 0-.062-.9c-.516-.685-1.504-2.075-2.042-3.362-.553-1.321-.636-3.375-.64-4.377a1.707 1.707 0 0 0-.358-1.05l-3.198-4.064a3.744 3.744 0 0 1-.076.543c-.106.503-.307 1.004-.536 1.5-.134.29-.29.6-.446.914l-.31.626c-.516 1.068-.997 2.227-1.132 3.59-.124 1.26.046 2.73.815 4.481.128.011.257.025.386.044a6.363 6.363 0 0 1 3.326 1.505c.916.79 1.744 1.922 2.415 3.5zM8.199 22.569c.073.012.146.02.22.02.78.024 2.095.092 3.16.29.87.16 2.593.64 4.01 1.055 1.083.316 2.198-.548 2.355-1.664.114-.814.33-1.735.725-2.58l-.01.005c-.67-1.87-1.522-3.078-2.416-3.849a5.295 5.295 0 0 0-2.778-1.257c-1.54-.216-2.952.19-3.84.45.532 2.218.368 4.829-1.425 7.531zM5.533 9.938c-.023.1-.056.197-.098.29L2.82 16.059a1.602 1.602 0 0 0 .313 1.772l4.116 4.24c2.103-3.101 1.796-6.02.836-8.3-.728-1.73-1.832-3.081-2.55-3.831zM9.32 14.01c.615-.183 1.606-.465 2.745-.534-.683-1.725-.848-3.233-.716-4.577.154-1.552.7-2.847 1.235-3.95.113-.235.223-.454.328-.664.149-.297.288-.577.419-.86.217-.47.379-.885.46-1.27.08-.38.08-.72-.014-1.043-.095-.325-.297-.675-.68-1.06a1.6 1.6 0 0 0-1.475.36l-4.95 4.452a1.602 1.602 0 0 0-.513.952l-.427 2.83c.672.59 2.328 2.316 3.335 4.711.09.21.175.43.253.653z"})})}function yL({className:e}){return n.jsx("svg",{className:e,viewBox:"0 0 24 24",fill:"currentColor",children:n.jsx("path",{d:"M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"})})}const Tk={happy:{eyes:["◕","◕"],mouth:"‿"},wave:{eyes:["◕","◕"],mouth:"▽",top:"·"},confused:{eyes:["◑","◐"],mouth:"o",top:"?"},sad:{eyes:["╥","╥"],mouth:"◠"},excited:{eyes:["★","★"],mouth:"▽",top:"✦"},sleeping:{eyes:["−","−"],mouth:"‿",top:"z z"}};function $N({mood:e="happy",className:t}){const a=Tk[e]??Tk.happy,[o,l]=a.eyes,c="text-emerald-700 dark:text-emerald-600/70";return n.jsxs("div",{"aria-hidden":!0,className:St("select-none whitespace-pre font-mono leading-none text-emerald-400",t),children:[a.top&&n.jsx("div",{children:n.jsx("span",{className:c,children:` ${a.top}`})}),n.jsx("div",{children:" ▄███████▄"}),n.jsxs("div",{children:[" █ ",n.jsx("span",{className:c,children:"██"})," ",n.jsx("span",{className:c,children:"██"})," █"]}),n.jsx("div",{children:` █ ${o} ${l} █`}),n.jsx("div",{children:` █ ${a.mouth} █`}),n.jsx("div",{children:" ▀███████▀"})]})}function UN({mood:e="confused",title:t,titleClassName:a,message:o,action:l,className:c,testId:d}){return n.jsx("div",{className:St("grid h-full place-items-center p-8",c),"data-testid":d,children:n.jsxs("div",{className:"flex flex-col items-center text-center",children:[n.jsx($N,{mood:e,className:"mb-6 text-sm"}),t!=null&&n.jsx("div",{className:St("font-mono font-semibold leading-none tracking-tight text-foreground",a),children:t}),o!=null&&n.jsx("p",{className:"mt-4 max-w-sm text-sm text-muted-fg",children:o}),l&&n.jsx("div",{className:"mt-6",children:l})]})})}const L_={pending:{labelKey:"tasks.status_pending",color:"text-amber-500",dot:"bg-amber-400",Icon:NA},running:{labelKey:"tasks.status_running",color:"text-sky-500",dot:"bg-sky-400",Icon:Js,spin:!0},in_review:{labelKey:"tasks.status_in_review",color:"text-violet-500",dot:"bg-violet-400",Icon:G2},blocked:{labelKey:"tasks.status_blocked",color:"text-slate-400",dot:"bg-slate-400",Icon:EA}},qN=["pending","running","in_review","blocked"];function Tf(e){return e.state==="done"?"done":e.state==="dropped"?"dropped":e.status??"pending"}function I_(e){return u(L_[e].labelKey)}function Af({status:e,className:t}){if(e==="done")return n.jsx(Hf,{className:ge("size-4 text-emerald-500",t)});if(e==="dropped")return n.jsx(F2,{className:ge("size-4 text-muted-foreground",t)});const a=L_[e];return n.jsx(a.Icon,{className:ge("size-4",a.color,a.spin&&"animate-spin",t)})}function B_({status:e}){const t=e==="done"?u("tasks.done_label"):e==="dropped"?u("tasks.dropped_label"):I_(e),a=e==="done"?"text-emerald-500 border-emerald-500/30":e==="dropped"?"text-muted-foreground border-border":`${L_[e].color} border-current/30`;return n.jsxs("span",{className:ge("inline-flex items-center gap-1 rounded-md border px-1.5 py-0.5 text-[10px] font-medium capitalize",a),children:[n.jsx(Af,{status:e,className:"size-3"}),t]})}function jL(e,t){var a,o=1;e==null&&(e=0),t==null&&(t=0);function l(){var c,d=a.length,f,m=0,g=0;for(c=0;c<d;++c)f=a[c],m+=f.x,g+=f.y;for(m=(m/d-e)*o,g=(g/d-t)*o,c=0;c<d;++c)f=a[c],f.x-=m,f.y-=g}return l.initialize=function(c){a=c},l.x=function(c){return arguments.length?(e=+c,l):e},l.y=function(c){return arguments.length?(t=+c,l):t},l.strength=function(c){return arguments.length?(o=+c,l):o},l}function kL(e){const t=+this._x.call(null,e),a=+this._y.call(null,e);return HN(this.cover(t,a),t,a,e)}function HN(e,t,a,o){if(isNaN(t)||isNaN(a))return e;var l,c=e._root,d={data:o},f=e._x0,m=e._y0,g=e._x1,h=e._y1,b,_,j,E,y,k,N,w;if(!c)return e._root=d,e;for(;c.length;)if((y=t>=(b=(f+g)/2))?f=b:g=b,(k=a>=(_=(m+h)/2))?m=_:h=_,l=c,!(c=c[N=k<<1|y]))return l[N]=d,e;if(j=+e._x.call(null,c.data),E=+e._y.call(null,c.data),t===j&&a===E)return d.next=c,l?l[N]=d:e._root=d,e;do l=l?l[N]=new Array(4):e._root=new Array(4),(y=t>=(b=(f+g)/2))?f=b:g=b,(k=a>=(_=(m+h)/2))?m=_:h=_;while((N=k<<1|y)===(w=(E>=_)<<1|j>=b));return l[w]=c,l[N]=d,e}function wL(e){var t,a,o=e.length,l,c,d=new Array(o),f=new Array(o),m=1/0,g=1/0,h=-1/0,b=-1/0;for(a=0;a<o;++a)isNaN(l=+this._x.call(null,t=e[a]))||isNaN(c=+this._y.call(null,t))||(d[a]=l,f[a]=c,l<m&&(m=l),l>h&&(h=l),c<g&&(g=c),c>b&&(b=c));if(m>h||g>b)return this;for(this.cover(m,g).cover(h,b),a=0;a<o;++a)HN(this,d[a],f[a],e[a]);return this}function SL(e,t){if(isNaN(e=+e)||isNaN(t=+t))return this;var a=this._x0,o=this._y0,l=this._x1,c=this._y1;if(isNaN(a))l=(a=Math.floor(e))+1,c=(o=Math.floor(t))+1;else{for(var d=l-a||1,f=this._root,m,g;a>e||e>=l||o>t||t>=c;)switch(g=(t<o)<<1|e<a,m=new Array(4),m[g]=f,f=m,d*=2,g){case 0:l=a+d,c=o+d;break;case 1:a=l-d,c=o+d;break;case 2:l=a+d,o=c-d;break;case 3:a=l-d,o=c-d;break}this._root&&this._root.length&&(this._root=f)}return this._x0=a,this._y0=o,this._x1=l,this._y1=c,this}function CL(){var e=[];return this.visit(function(t){if(!t.length)do e.push(t.data);while(t=t.next)}),e}function NL(e){return arguments.length?this.cover(+e[0][0],+e[0][1]).cover(+e[1][0],+e[1][1]):isNaN(this._x0)?void 0:[[this._x0,this._y0],[this._x1,this._y1]]}function Jn(e,t,a,o,l){this.node=e,this.x0=t,this.y0=a,this.x1=o,this.y1=l}function EL(e,t,a){var o,l=this._x0,c=this._y0,d,f,m,g,h=this._x1,b=this._y1,_=[],j=this._root,E,y;for(j&&_.push(new Jn(j,l,c,h,b)),a==null?a=1/0:(l=e-a,c=t-a,h=e+a,b=t+a,a*=a);E=_.pop();)if(!(!(j=E.node)||(d=E.x0)>h||(f=E.y0)>b||(m=E.x1)<l||(g=E.y1)<c))if(j.length){var k=(d+m)/2,N=(f+g)/2;_.push(new Jn(j[3],k,N,m,g),new Jn(j[2],d,N,k,g),new Jn(j[1],k,f,m,N),new Jn(j[0],d,f,k,N)),(y=(t>=N)<<1|e>=k)&&(E=_[_.length-1],_[_.length-1]=_[_.length-1-y],_[_.length-1-y]=E)}else{var w=e-+this._x.call(null,j.data),S=t-+this._y.call(null,j.data),R=w*w+S*S;if(R<a){var A=Math.sqrt(a=R);l=e-A,c=t-A,h=e+A,b=t+A,o=j.data}}return o}function RL(e){if(isNaN(h=+this._x.call(null,e))||isNaN(b=+this._y.call(null,e)))return this;var t,a=this._root,o,l,c,d=this._x0,f=this._y0,m=this._x1,g=this._y1,h,b,_,j,E,y,k,N;if(!a)return this;if(a.length)for(;;){if((E=h>=(_=(d+m)/2))?d=_:m=_,(y=b>=(j=(f+g)/2))?f=j:g=j,t=a,!(a=a[k=y<<1|E]))return this;if(!a.length)break;(t[k+1&3]||t[k+2&3]||t[k+3&3])&&(o=t,N=k)}for(;a.data!==e;)if(l=a,!(a=a.next))return this;return(c=a.next)&&delete a.next,l?(c?l.next=c:delete l.next,this):t?(c?t[k]=c:delete t[k],(a=t[0]||t[1]||t[2]||t[3])&&a===(t[3]||t[2]||t[1]||t[0])&&!a.length&&(o?o[N]=a:this._root=a),this):(this._root=c,this)}function TL(e){for(var t=0,a=e.length;t<a;++t)this.remove(e[t]);return this}function AL(){return this._root}function ML(){var e=0;return this.visit(function(t){if(!t.length)do++e;while(t=t.next)}),e}function zL(e){var t=[],a,o=this._root,l,c,d,f,m;for(o&&t.push(new Jn(o,this._x0,this._y0,this._x1,this._y1));a=t.pop();)if(!e(o=a.node,c=a.x0,d=a.y0,f=a.x1,m=a.y1)&&o.length){var g=(c+f)/2,h=(d+m)/2;(l=o[3])&&t.push(new Jn(l,g,h,f,m)),(l=o[2])&&t.push(new Jn(l,c,h,g,m)),(l=o[1])&&t.push(new Jn(l,g,d,f,h)),(l=o[0])&&t.push(new Jn(l,c,d,g,h))}return this}function OL(e){var t=[],a=[],o;for(this._root&&t.push(new Jn(this._root,this._x0,this._y0,this._x1,this._y1));o=t.pop();){var l=o.node;if(l.length){var c,d=o.x0,f=o.y0,m=o.x1,g=o.y1,h=(d+m)/2,b=(f+g)/2;(c=l[0])&&t.push(new Jn(c,d,f,h,b)),(c=l[1])&&t.push(new Jn(c,h,f,m,b)),(c=l[2])&&t.push(new Jn(c,d,b,h,g)),(c=l[3])&&t.push(new Jn(c,h,b,m,g))}a.push(o)}for(;o=a.pop();)e(o.node,o.x0,o.y0,o.x1,o.y1);return this}function DL(e){return e[0]}function PL(e){return arguments.length?(this._x=e,this):this._x}function LL(e){return e[1]}function IL(e){return arguments.length?(this._y=e,this):this._y}function $_(e,t,a){var o=new U_(t??DL,a??LL,NaN,NaN,NaN,NaN);return e==null?o:o.addAll(e)}function U_(e,t,a,o,l,c){this._x=e,this._y=t,this._x0=a,this._y0=o,this._x1=l,this._y1=c,this._root=void 0}function Ak(e){for(var t={data:e.data},a=t;e=e.next;)a=a.next={data:e.data};return t}var ss=$_.prototype=U_.prototype;ss.copy=function(){var e=new U_(this._x,this._y,this._x0,this._y0,this._x1,this._y1),t=this._root,a,o;if(!t)return e;if(!t.length)return e._root=Ak(t),e;for(a=[{source:t,target:e._root=new Array(4)}];t=a.pop();)for(var l=0;l<4;++l)(o=t.source[l])&&(o.length?a.push({source:o,target:t.target[l]=new Array(4)}):t.target[l]=Ak(o));return e};ss.add=kL;ss.addAll=wL;ss.cover=SL;ss.data=CL;ss.extent=NL;ss.find=EL;ss.remove=RL;ss.removeAll=TL;ss.root=AL;ss.size=ML;ss.visit=zL;ss.visitAfter=OL;ss.x=PL;ss.y=IL;function es(e){return function(){return e}}function qr(e){return(e()-.5)*1e-6}function BL(e){return e.x+e.vx}function $L(e){return e.y+e.vy}function UL(e){var t,a,o,l=1,c=1;typeof e!="function"&&(e=es(e==null?1:+e));function d(){for(var g,h=t.length,b,_,j,E,y,k,N=0;N<c;++N)for(b=$_(t,BL,$L).visitAfter(f),g=0;g<h;++g)_=t[g],y=a[_.index],k=y*y,j=_.x+_.vx,E=_.y+_.vy,b.visit(w);function w(S,R,A,T,z){var M=S.data,L=S.r,P=y+L;if(M){if(M.index>_.index){var B=j-M.x-M.vx,D=E-M.y-M.vy,$=B*B+D*D;$<P*P&&(B===0&&(B=qr(o),$+=B*B),D===0&&(D=qr(o),$+=D*D),$=(P-($=Math.sqrt($)))/$*l,_.vx+=(B*=$)*(P=(L*=L)/(k+L)),_.vy+=(D*=$)*P,M.vx-=B*(P=1-P),M.vy-=D*P)}return}return R>j+P||T<j-P||A>E+P||z<E-P}}function f(g){if(g.data)return g.r=a[g.data.index];for(var h=g.r=0;h<4;++h)g[h]&&g[h].r>g.r&&(g.r=g[h].r)}function m(){if(t){var g,h=t.length,b;for(a=new Array(h),g=0;g<h;++g)b=t[g],a[b.index]=+e(b,g,t)}}return d.initialize=function(g,h){t=g,o=h,m()},d.iterations=function(g){return arguments.length?(c=+g,d):c},d.strength=function(g){return arguments.length?(l=+g,d):l},d.radius=function(g){return arguments.length?(e=typeof g=="function"?g:es(+g),m(),d):e},d}function qL(e){return e.index}function Mk(e,t){var a=e.get(t);if(!a)throw new Error("node not found: "+t);return a}function HL(e){var t=qL,a=b,o,l=es(30),c,d,f,m,g,h=1;e==null&&(e=[]);function b(k){return 1/Math.min(f[k.source.index],f[k.target.index])}function _(k){for(var N=0,w=e.length;N<h;++N)for(var S=0,R,A,T,z,M,L,P;S<w;++S)R=e[S],A=R.source,T=R.target,z=T.x+T.vx-A.x-A.vx||qr(g),M=T.y+T.vy-A.y-A.vy||qr(g),L=Math.sqrt(z*z+M*M),L=(L-c[S])/L*k*o[S],z*=L,M*=L,T.vx-=z*(P=m[S]),T.vy-=M*P,A.vx+=z*(P=1-P),A.vy+=M*P}function j(){if(d){var k,N=d.length,w=e.length,S=new Map(d.map((A,T)=>[t(A,T,d),A])),R;for(k=0,f=new Array(N);k<w;++k)R=e[k],R.index=k,typeof R.source!="object"&&(R.source=Mk(S,R.source)),typeof R.target!="object"&&(R.target=Mk(S,R.target)),f[R.source.index]=(f[R.source.index]||0)+1,f[R.target.index]=(f[R.target.index]||0)+1;for(k=0,m=new Array(w);k<w;++k)R=e[k],m[k]=f[R.source.index]/(f[R.source.index]+f[R.target.index]);o=new Array(w),E(),c=new Array(w),y()}}function E(){if(d)for(var k=0,N=e.length;k<N;++k)o[k]=+a(e[k],k,e)}function y(){if(d)for(var k=0,N=e.length;k<N;++k)c[k]=+l(e[k],k,e)}return _.initialize=function(k,N){d=k,g=N,j()},_.links=function(k){return arguments.length?(e=k,j(),_):e},_.id=function(k){return arguments.length?(t=k,_):t},_.iterations=function(k){return arguments.length?(h=+k,_):h},_.strength=function(k){return arguments.length?(a=typeof k=="function"?k:es(+k),E(),_):a},_.distance=function(k){return arguments.length?(l=typeof k=="function"?k:es(+k),y(),_):l},_}var VL={value:()=>{}};function VN(){for(var e=0,t=arguments.length,a={},o;e<t;++e){if(!(o=arguments[e]+"")||o in a||/[\s.]/.test(o))throw new Error("illegal type: "+o);a[o]=[]}return new af(a)}function af(e){this._=e}function FL(e,t){return e.trim().split(/^|\s+/).map(function(a){var o="",l=a.indexOf(".");if(l>=0&&(o=a.slice(l+1),a=a.slice(0,l)),a&&!t.hasOwnProperty(a))throw new Error("unknown type: "+a);return{type:a,name:o}})}af.prototype=VN.prototype={constructor:af,on:function(e,t){var a=this._,o=FL(e+"",a),l,c=-1,d=o.length;if(arguments.length<2){for(;++c<d;)if((l=(e=o[c]).type)&&(l=GL(a[l],e.name)))return l;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++c<d;)if(l=(e=o[c]).type)a[l]=zk(a[l],e.name,t);else if(t==null)for(l in a)a[l]=zk(a[l],e.name,null);return this},copy:function(){var e={},t=this._;for(var a in t)e[a]=t[a].slice();return new af(e)},call:function(e,t){if((l=arguments.length-2)>0)for(var a=new Array(l),o=0,l,c;o<l;++o)a[o]=arguments[o+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(c=this._[e],o=0,l=c.length;o<l;++o)c[o].value.apply(t,a)},apply:function(e,t,a){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var o=this._[e],l=0,c=o.length;l<c;++l)o[l].value.apply(t,a)}};function GL(e,t){for(var a=0,o=e.length,l;a<o;++a)if((l=e[a]).name===t)return l.value}function zk(e,t,a){for(var o=0,l=e.length;o<l;++o)if(e[o].name===t){e[o]=VL,e=e.slice(0,o).concat(e.slice(o+1));break}return a!=null&&e.push({name:t,value:a}),e}var oi=0,wc=0,gc=0,FN=1e3,Mf,Sc,zf=0,Lo=0,Sp=0,Vc=typeof performance=="object"&&performance.now?performance:Date,GN=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function YN(){return Lo||(GN(YL),Lo=Vc.now()+Sp)}function YL(){Lo=0}function Hx(){this._call=this._time=this._next=null}Hx.prototype=KN.prototype={constructor:Hx,restart:function(e,t,a){if(typeof e!="function")throw new TypeError("callback is not a function");a=(a==null?YN():+a)+(t==null?0:+t),!this._next&&Sc!==this&&(Sc?Sc._next=this:Mf=this,Sc=this),this._call=e,this._time=a,Vx()},stop:function(){this._call&&(this._call=null,this._time=1/0,Vx())}};function KN(e,t,a){var o=new Hx;return o.restart(e,t,a),o}function KL(){YN(),++oi;for(var e=Mf,t;e;)(t=Lo-e._time)>=0&&e._call.call(void 0,t),e=e._next;--oi}function Ok(){Lo=(zf=Vc.now())+Sp,oi=wc=0;try{KL()}finally{oi=0,QL(),Lo=0}}function XL(){var e=Vc.now(),t=e-zf;t>FN&&(Sp-=t,zf=e)}function QL(){for(var e,t=Mf,a,o=1/0;t;)t._call?(o>t._time&&(o=t._time),e=t,t=t._next):(a=t._next,t._next=null,t=e?e._next=a:Mf=a);Sc=e,Vx(o)}function Vx(e){if(!oi){wc&&(wc=clearTimeout(wc));var t=e-Lo;t>24?(e<1/0&&(wc=setTimeout(Ok,e-Vc.now()-Sp)),gc&&(gc=clearInterval(gc))):(gc||(zf=Vc.now(),gc=setInterval(XL,FN)),oi=1,GN(Ok))}}const WL=1664525,ZL=1013904223,Dk=4294967296;function JL(){let e=1;return()=>(e=(WL*e+ZL)%Dk)/Dk}function e8(e){return e.x}function t8(e){return e.y}var n8=10,s8=Math.PI*(3-Math.sqrt(5));function a8(e){var t,a=1,o=.001,l=1-Math.pow(o,1/300),c=0,d=.6,f=new Map,m=KN(b),g=VN("tick","end"),h=JL();e==null&&(e=[]);function b(){_(),g.call("tick",t),a<o&&(m.stop(),g.call("end",t))}function _(y){var k,N=e.length,w;y===void 0&&(y=1);for(var S=0;S<y;++S)for(a+=(c-a)*l,f.forEach(function(R){R(a)}),k=0;k<N;++k)w=e[k],w.fx==null?w.x+=w.vx*=d:(w.x=w.fx,w.vx=0),w.fy==null?w.y+=w.vy*=d:(w.y=w.fy,w.vy=0);return t}function j(){for(var y=0,k=e.length,N;y<k;++y){if(N=e[y],N.index=y,N.fx!=null&&(N.x=N.fx),N.fy!=null&&(N.y=N.fy),isNaN(N.x)||isNaN(N.y)){var w=n8*Math.sqrt(.5+y),S=y*s8;N.x=w*Math.cos(S),N.y=w*Math.sin(S)}(isNaN(N.vx)||isNaN(N.vy))&&(N.vx=N.vy=0)}}function E(y){return y.initialize&&y.initialize(e,h),y}return j(),t={tick:_,restart:function(){return m.restart(b),t},stop:function(){return m.stop(),t},nodes:function(y){return arguments.length?(e=y,j(),f.forEach(E),t):e},alpha:function(y){return arguments.length?(a=+y,t):a},alphaMin:function(y){return arguments.length?(o=+y,t):o},alphaDecay:function(y){return arguments.length?(l=+y,t):+l},alphaTarget:function(y){return arguments.length?(c=+y,t):c},velocityDecay:function(y){return arguments.length?(d=1-y,t):1-d},randomSource:function(y){return arguments.length?(h=y,f.forEach(E),t):h},force:function(y,k){return arguments.length>1?(k==null?f.delete(y):f.set(y,E(k)),t):f.get(y)},find:function(y,k,N){var w=0,S=e.length,R,A,T,z,M;for(N==null?N=1/0:N*=N,w=0;w<S;++w)z=e[w],R=y-z.x,A=k-z.y,T=R*R+A*A,T<N&&(M=z,N=T);return M},on:function(y,k){return arguments.length>1?(g.on(y,k),t):g.on(y)}}}function r8(){var e,t,a,o,l=es(-30),c,d=1,f=1/0,m=.81;function g(j){var E,y=e.length,k=$_(e,e8,t8).visitAfter(b);for(o=j,E=0;E<y;++E)t=e[E],k.visit(_)}function h(){if(e){var j,E=e.length,y;for(c=new Array(E),j=0;j<E;++j)y=e[j],c[y.index]=+l(y,j,e)}}function b(j){var E=0,y,k,N=0,w,S,R;if(j.length){for(w=S=R=0;R<4;++R)(y=j[R])&&(k=Math.abs(y.value))&&(E+=y.value,N+=k,w+=k*y.x,S+=k*y.y);j.x=w/N,j.y=S/N}else{y=j,y.x=y.data.x,y.y=y.data.y;do E+=c[y.data.index];while(y=y.next)}j.value=E}function _(j,E,y,k){if(!j.value)return!0;var N=j.x-t.x,w=j.y-t.y,S=k-E,R=N*N+w*w;if(S*S/m<R)return R<f&&(N===0&&(N=qr(a),R+=N*N),w===0&&(w=qr(a),R+=w*w),R<d&&(R=Math.sqrt(d*R)),t.vx+=N*j.value*o/R,t.vy+=w*j.value*o/R),!0;if(j.length||R>=f)return;(j.data!==t||j.next)&&(N===0&&(N=qr(a),R+=N*N),w===0&&(w=qr(a),R+=w*w),R<d&&(R=Math.sqrt(d*R)));do j.data!==t&&(S=c[j.data.index]*o/R,t.vx+=N*S,t.vy+=w*S);while(j=j.next)}return g.initialize=function(j,E){e=j,a=E,h()},g.strength=function(j){return arguments.length?(l=typeof j=="function"?j:es(+j),h(),g):l},g.distanceMin=function(j){return arguments.length?(d=j*j,g):Math.sqrt(d)},g.distanceMax=function(j){return arguments.length?(f=j*j,g):Math.sqrt(f)},g.theta=function(j){return arguments.length?(m=j*j,g):Math.sqrt(m)},g}function o8(e){var t=es(.1),a,o,l;typeof e!="function"&&(e=es(e==null?0:+e));function c(f){for(var m=0,g=a.length,h;m<g;++m)h=a[m],h.vx+=(l[m]-h.x)*o[m]*f}function d(){if(a){var f,m=a.length;for(o=new Array(m),l=new Array(m),f=0;f<m;++f)o[f]=isNaN(l[f]=+e(a[f],f,a))?0:+t(a[f],f,a)}}return c.initialize=function(f){a=f,d()},c.strength=function(f){return arguments.length?(t=typeof f=="function"?f:es(+f),d(),c):t},c.x=function(f){return arguments.length?(e=typeof f=="function"?f:es(+f),d(),c):e},c}function l8(e){var t=es(.1),a,o,l;typeof e!="function"&&(e=es(e==null?0:+e));function c(f){for(var m=0,g=a.length,h;m<g;++m)h=a[m],h.vy+=(l[m]-h.y)*o[m]*f}function d(){if(a){var f,m=a.length;for(o=new Array(m),l=new Array(m),f=0;f<m;++f)o[f]=isNaN(l[f]=+e(a[f],f,a))?0:+t(a[f],f,a)}}return c.initialize=function(f){a=f,d()},c.strength=function(f){return arguments.length?(t=typeof f=="function"?f:es(+f),d(),c):t},c.y=function(f){return arguments.length?(e=typeof f=="function"?f:es(+f),d(),c):e},c}const $s={agent:"#a78bfa",memory:"#38bdf8",thread:"#34d399",task:"#fbbf24",routine:"#f472b6",agentlink:"#c084fc",hub:"#94a3b8"};function Pk(e){return{agent:u("agents_ui.kind_agent"),memory:u("agents_ui.kind_memory"),thread:u("agents_ui.kind_thread"),task:u("agents_ui.kind_task"),routine:u("agents_ui.kind_routine"),agentlink:u("agents_ui.kind_hierarchy")}[e]??e}const Lk={core:24,hub:12,leaf:6},Lr=e=>e.role??"leaf",Ik=(e,t,a)=>Math.max(t,Math.min(a,e)),Bk=e=>{const t=new Map;for(const a of e)t.set(a.id,a);return[...t.values()]},i8=(e,t=26)=>e.length>t?`${e.slice(0,t)}…`:e;function XN({nodes:e,edges:t,height:a=520,onNodeClick:o,toolbar:l}){const d=Math.round(1e3*a/760),f=x.useRef(null),m=x.useRef(null),g=x.useRef(null),h=x.useRef([]),b=x.useRef([]),_=x.useRef(null),j=x.useRef(null),E=x.useRef(null),y=x.useRef(!1),k=x.useRef({tx:0,ty:0,k:1}),N=x.useRef(()=>{}),[,w]=x.useState(0),[S,R]=x.useState(null),[A,T]=x.useState(!1),z=1e3/2,M=d/2,L=()=>w(Y=>Y+1),P=e.length>44;x.useEffect(()=>{const Y=Math.min(1e3,d)*.3,oe=e.filter(Te=>Lr(Te)==="hub"),ve=new Map;oe.forEach((Te,Ne)=>ve.set(Te.id,Ne/Math.max(1,oe.length)*Math.PI*2-Math.PI/2));const le=e.map((Te,Ne)=>{const Me=Lr(Te);if(Me==="core")return{...Te,x:z,y:M,fx:z,fy:M};const De=ve.get(Te.id)??Ne/Math.max(1,e.length)*Math.PI*2,Ue=Me==="hub"?Y:Y*1.7;return{...Te,x:z+Math.cos(De)*Ue,y:M+Math.sin(De)*Ue}}),xe=new Map(le.map(Te=>[Te.id,Te])),ke=t.map(Te=>({source:xe.get(Te.source),target:xe.get(Te.target)})).filter(Te=>!!Te.source&&!!Te.target);h.current=le,b.current=ke,L();const Re=Te=>{const Ne=Lr(Te.source),Me=Lr(Te.target);return Ne==="core"||Me==="core"?170:Ne==="hub"&&Me==="hub"?130:58},Ae=Te=>{const Ne=Lr(Te);return Ne==="core"?-700:Ne==="hub"?-360:-90},Ie=a8(le).force("link",HL(ke).distance(Re).strength(.5)).force("charge",r8().strength(Ae)).force("center",jL(z,M).strength(.03)).force("x",o8(z).strength(.02)).force("y",l8(M).strength(.02)).force("collide",UL(Te=>Lk[Lr(Te)]+8)).alphaDecay(.025).on("tick",L);g.current=Ie;const Oe=setTimeout(()=>N.current(),1400);return()=>{clearTimeout(Oe),Ie.stop()}},[e,t,a]);const B=(Y,oe)=>{const ve=m.current.getBoundingClientRect();return{x:(Y-ve.left)/ve.width*1e3,y:(oe-ve.top)/ve.height*d}},D=(Y,oe,ve)=>{const le=k.current,xe=Ik(le.k*ve,.25,8);k.current={k:xe,tx:Y-(Y-le.tx)*(xe/le.k),ty:oe-(oe-le.ty)*(xe/le.k)},L()};N.current=()=>{const Y=h.current.filter(Ne=>Ne.x!=null&&Ne.y!=null);if(!Y.length)return;let oe=1/0,ve=1/0,le=-1/0,xe=-1/0;for(const Ne of Y)oe=Math.min(oe,Ne.x),ve=Math.min(ve,Ne.y),le=Math.max(le,Ne.x),xe=Math.max(xe,Ne.y);const ke=60,Re=Math.max(1,le-oe),Ae=Math.max(1,xe-ve),Ie=Ik(Math.min((1e3-ke*2)/Re,(d-ke*2)/Ae),.25,2.5),Oe=(oe+le)/2,Te=(ve+xe)/2;k.current={k:Ie,tx:1e3/2-Oe*Ie,ty:d/2-Te*Ie},L()},x.useEffect(()=>{const Y=m.current;if(!Y)return;const oe=ve=>{ve.preventDefault();const le=B(ve.clientX,ve.clientY);D(le.x,le.y,ve.deltaY>0?.9:1.1)};return Y.addEventListener("wheel",oe,{passive:!1}),()=>Y.removeEventListener("wheel",oe)},[]),x.useEffect(()=>{if(!A)return;const Y=oe=>{oe.key==="Escape"&&T(!1)};return window.addEventListener("keydown",Y),()=>window.removeEventListener("keydown",Y)},[A]);const $=(Y,oe)=>{const ve=B(Y,oe),le=k.current;return{x:(ve.x-le.tx)/le.k,y:(ve.y-le.ty)/le.k}},q=Y=>oe=>{Lr(Y)!=="core"&&(oe.stopPropagation(),_.current=Y,E.current={x:oe.clientX,y:oe.clientY},y.current=!1,oe.target.setPointerCapture?.(oe.pointerId),g.current?.alphaTarget(.3).restart())},G=Y=>{j.current={x:Y.clientX,y:Y.clientY},Y.currentTarget.setPointerCapture?.(Y.pointerId)},U=Y=>{if(_.current){const oe=E.current;oe&&!y.current&&Math.hypot(Y.clientX-oe.x,Y.clientY-oe.y)>4&&(y.current=!0);const ve=$(Y.clientX,Y.clientY);_.current.fx=ve.x,_.current.fy=ve.y;return}if(j.current){const oe=m.current.getBoundingClientRect();k.current.tx+=(Y.clientX-j.current.x)/oe.width*1e3,k.current.ty+=(Y.clientY-j.current.y)/oe.height*d,j.current={x:Y.clientX,y:Y.clientY},L()}},V=()=>{const Y=_.current;Y&&(Y.fx=null,Y.fy=null),_.current=null,j.current=null,g.current?.alphaTarget(0)},X=Y=>()=>{y.current||ee(Y)},Q=h.current,W=b.current,I=k.current,K=[...new Set(e.map(Y=>Y.kind))].filter(Y=>Y!=="agent"&&Y!=="hub"),ee=Y=>{R(Y),o?.(Y)},F=S?Bk(W.filter(Y=>Y.target.id===S.id).map(Y=>Y.source)):[],ne=S?Bk(W.filter(Y=>Y.source.id===S.id).map(Y=>Y.target)):[],Z=S?.detail&&S.detail.trim()!==S.label.trim()?S.detail:null,fe=({onClick:Y,title:oe,children:ve})=>n.jsx("button",{type:"button",title:oe,onClick:Y,className:"grid size-7 place-items-center rounded-md border border-border bg-card/80 text-muted-fg backdrop-blur hover:text-foreground",children:ve});return n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{ref:f,className:A?"fixed inset-0 z-[60] flex flex-col gap-3 bg-background p-4":"relative",children:[n.jsxs("div",{className:"relative min-h-0 flex-1 overflow-hidden rounded-xl border border-border bg-gradient-to-b from-background to-muted/20",children:[n.jsxs("div",{className:"absolute right-2 top-2 z-10 flex items-center gap-1.5",children:[l,n.jsx(fe,{onClick:()=>D(z,M,1.2),title:u("agents_ui.brain_zoom_in"),children:n.jsx(Dt,{size:14})}),n.jsx(fe,{onClick:()=>D(z,M,.83),title:u("agents_ui.brain_zoom_out"),children:n.jsx(aM,{size:14})}),n.jsx(fe,{onClick:()=>N.current(),title:u("agents_ui.brain_fit"),children:n.jsx(VA,{size:14})}),n.jsx(fe,{onClick:()=>T(Y=>!Y),title:u(A?"agents_ui.brain_exit_fs":"agents_ui.brain_fullscreen"),children:A?n.jsx(sM,{size:14}):n.jsx(nM,{size:14})})]}),n.jsxs("svg",{ref:m,viewBox:`0 0 1000 ${d}`,preserveAspectRatio:"xMidYMid meet",style:A?{height:"100%",width:"100%"}:{height:a},className:"w-full touch-none select-none",onPointerMove:U,onPointerUp:V,onPointerLeave:V,children:[n.jsxs("defs",{children:[n.jsxs("filter",{id:"brain-glow",x:"-80%",y:"-80%",width:"260%",height:"260%",children:[n.jsx("feGaussianBlur",{stdDeviation:"3",result:"blur"}),n.jsxs("feMerge",{children:[n.jsx("feMergeNode",{in:"blur"}),n.jsx("feMergeNode",{in:"SourceGraphic"})]})]}),n.jsxs("radialGradient",{id:"brain-core",cx:"50%",cy:"50%",r:"50%",children:[n.jsx("stop",{offset:"0%",stopColor:$s.agent,stopOpacity:"0.9"}),n.jsx("stop",{offset:"55%",stopColor:$s.agent,stopOpacity:"0.35"}),n.jsx("stop",{offset:"100%",stopColor:$s.agent,stopOpacity:"0"})]}),n.jsxs("radialGradient",{id:"brain-bg",cx:"50%",cy:"50%",r:"60%",children:[n.jsx("stop",{offset:"0%",stopColor:$s.agent,stopOpacity:"0.10"}),n.jsx("stop",{offset:"100%",stopColor:$s.agent,stopOpacity:"0"})]})]}),n.jsx("rect",{x:0,y:0,width:1e3,height:d,fill:"url(#brain-bg)",onPointerDown:G,className:"cursor-grab active:cursor-grabbing"}),n.jsxs("g",{transform:`translate(${I.tx},${I.ty}) scale(${I.k})`,children:[W.map((Y,oe)=>{const ve=$s[Y.target.kind==="hub"?Y.source.kind:Y.target.kind],le=1.4+oe%5*.35;return n.jsxs("g",{children:[n.jsx("line",{x1:Y.source.x,y1:Y.source.y,x2:Y.target.x,y2:Y.target.y,stroke:ve,strokeOpacity:.16,strokeWidth:1.4}),n.jsx("line",{x1:Y.target.x,y1:Y.target.y,x2:Y.source.x,y2:Y.source.y,stroke:ve,strokeOpacity:.5,strokeWidth:2,strokeLinecap:"round",strokeDasharray:"1 14",children:n.jsx("animate",{attributeName:"stroke-dashoffset",values:"15;0",dur:`${le}s`,repeatCount:"indefinite"})})]},oe)}),Q.map((Y,oe)=>{const ve=Lr(Y),le=$s[Y.kind];if(ve==="core"){const Te=Y.emoji&&Y.emoji.trim()||Y.label.slice(0,2).toUpperCase();return n.jsxs("g",{transform:`translate(${Y.x},${Y.y})`,children:[n.jsxs("circle",{r:54,fill:"url(#brain-core)",children:[n.jsx("animate",{attributeName:"r",values:"50;58;50",dur:"4s",repeatCount:"indefinite"}),n.jsx("animate",{attributeName:"opacity",values:"0.85;1;0.85",dur:"4s",repeatCount:"indefinite"})]}),n.jsxs("circle",{r:26,fill:"none",stroke:$s.agent,strokeWidth:1.5,opacity:.5,children:[n.jsx("animate",{attributeName:"r",values:"26;48",dur:"3.2s",repeatCount:"indefinite"}),n.jsx("animate",{attributeName:"opacity",values:"0.5;0",dur:"3.2s",repeatCount:"indefinite"})]}),n.jsx("circle",{r:24,fill:$s.agent,filter:"url(#brain-glow)"}),n.jsx("circle",{r:24,fill:"none",stroke:"#ffffff",strokeOpacity:.35,strokeWidth:1}),n.jsx("text",{textAnchor:"middle",dominantBaseline:"central",fontSize:Te.length<=2?20:11,fontWeight:700,fill:"#1a1030",children:Te.length>8?Te.slice(0,8):Te})]},Y.id)}const xe=S?.id===Y.id,ke=Lk[ve]+(xe?3:0),Re=2.4+oe%6*.4,Ae=`${oe%6*.3}s`,Ie=ve==="hub",Oe=Ie||xe||!P;return n.jsxs("g",{transform:`translate(${Y.x},${Y.y})`,className:"cursor-grab active:cursor-grabbing",onPointerDown:q(Y),onClick:X(Y),children:[n.jsxs("circle",{r:ke,fill:le,filter:"url(#brain-glow)",opacity:.3,children:[n.jsx("animate",{attributeName:"r",values:`${ke};${ke+6};${ke}`,dur:`${Re}s`,begin:Ae,repeatCount:"indefinite"}),n.jsx("animate",{attributeName:"opacity",values:"0.32;0.08;0.32",dur:`${Re}s`,begin:Ae,repeatCount:"indefinite"})]}),n.jsx("circle",{r:ke,fill:le,fillOpacity:xe?1:.95,stroke:xe?"#fff":"#ffffff",strokeOpacity:xe?1:.25,strokeWidth:xe?2:1}),Y.emoji&&Ie&&n.jsx("text",{textAnchor:"middle",dominantBaseline:"central",fontSize:11,style:{pointerEvents:"none"},children:Y.emoji}),Oe&&n.jsx("text",{x:ke+4,y:4,fontSize:Ie?11:10,className:Ie?"fill-foreground font-medium":"fill-foreground/80",style:{pointerEvents:"none"},children:Y.label.length>22?`${Y.label.slice(0,22)}…`:Y.label})]},Y.id)})]})]})]}),n.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-[11px] text-muted-fg",children:[K.map(Y=>n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx("span",{className:"size-2 rounded-full",style:{background:$s[Y]}})," ",Pk(Y)]},Y)),n.jsxs("span",{className:"ml-auto",children:[u("agents_ui.brain_pan_hint")," · ",u("agents_ui.nodes_drag_hint",{n:String(e.length)})]})]})]}),S&&n.jsxs("div",{className:"space-y-2.5 rounded-lg border border-border bg-card p-3 text-xs",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("span",{className:"size-2.5 rounded-full",style:{background:$s[S.kind]}}),S.emoji&&n.jsx("span",{className:"text-sm leading-none",children:S.emoji}),n.jsx("span",{className:"text-[13px] font-semibold",children:S.label}),n.jsx("span",{className:"rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-muted-fg",children:Pk(S.kind)}),S.relation&&n.jsxs("span",{className:"text-muted-fg",children:["· ",S.relation]}),n.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[S.slug&&o&&n.jsx("button",{type:"button",onClick:()=>o(S),className:"text-primary hover:underline",children:u("agents_ui.brain_open")}),n.jsx("button",{type:"button",onClick:()=>R(null),className:"text-muted-fg hover:text-foreground",children:"✕"})]})]}),Z&&n.jsx("p",{className:"whitespace-pre-wrap text-muted-fg",children:Z}),F.length>0&&n.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[n.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted-fg/70",children:u("agents_ui.brain_part_of")}),F.map(Y=>n.jsx($k,{node:Y,onClick:()=>R(Y)},Y.id))]}),ne.length>0&&n.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[n.jsxs("span",{className:"text-[10px] uppercase tracking-wide text-muted-fg/70",children:[u("agents_ui.brain_branches")," · ",ne.length]}),ne.map(Y=>n.jsx($k,{node:Y,onClick:()=>R(Y)},Y.id))]})]})]})}function $k({node:e,onClick:t}){return n.jsxs("button",{type:"button",onClick:t,className:"inline-flex max-w-[220px] items-center gap-1 rounded-md border border-border bg-muted/40 px-1.5 py-0.5 text-[11px] hover:border-muted-fg/50 hover:bg-muted",children:[n.jsx("span",{className:"size-1.5 shrink-0 rounded-full",style:{background:$s[e.kind]}}),e.emoji&&n.jsx("span",{className:"leading-none",children:e.emoji}),n.jsx("span",{className:"truncate",children:i8(e.label,28)})]})}function Uk({pid:e}){const t=Pn(),a=Be(`/projects/${e}/tasks?state=open`,()=>Qn.list(e),{refreshInterval:2e4}),o=Be(`/projects/${e}/tasks-summary`,()=>Qn.summary(e),{refreshInterval:2e4}),l=Be(`/projects/${e}/routines`,()=>Br.list(e)),c=Be(`/projects/${e}/agents`,()=>an.list(e)),d=Be(`/projects/${e}/mcps`,()=>$r.list(e)),f=Be(`/projects/${e}/artifacts`,()=>Ws.list(e)),m=c.data??[],g=m.filter(y=>y.is_master||y.type==="orchestrator"),h=m.filter(y=>!(y.is_master||y.type==="orchestrator")),b=c8(m),_=b.some(y=>y.area),j=(l.data??[]).filter(y=>y.enabled).length,E=[...a.data??[]].sort((y,k)=>(k.created_at||"").localeCompare(y.created_at||"")).slice(0,6);return n.jsxs("div",{className:"space-y-6",children:[n.jsxs("div",{className:"grid grid-cols-2 gap-4 md:grid-cols-4",children:[n.jsx(So,{title:u("project.overview.agents"),value:m.length,href:`/p/${e}/agents`,icon:rn}),n.jsx(So,{title:u("project.overview.tasks_open"),value:o.data?.open??a.data?.length??"…",href:`/p/${e}/tasks`,icon:pi}),n.jsx(So,{title:u("project.overview.routines_active"),value:j,href:`/p/${e}/routines`,icon:Mo}),n.jsx(So,{title:u("project.overview.artifacts"),value:f.data?.length??"…",href:`/p/${e}/artifacts`,icon:gb})]}),o.data&&n.jsx("div",{className:"flex flex-wrap gap-2",children:qN.map(y=>n.jsxs(df,{to:`/p/${e}/tasks`,className:"flex items-center gap-1.5 rounded-lg border border-border bg-card px-3 py-1.5 text-xs hover:bg-accent/40",children:[n.jsx(Af,{status:y,className:"size-3.5"}),n.jsx("span",{className:"capitalize text-muted-foreground",children:I_(y)}),n.jsx("span",{className:"font-semibold",children:o.data.status?.[y]??0})]},y))}),n.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[n.jsx(Ve,{title:u("project.overview.roster"),className:"!p-4",children:m.length===0?n.jsx("p",{className:"text-sm text-muted-fg",children:u("project.overview.no_agents")}):_?n.jsx("div",{className:"space-y-3",children:b.map(y=>n.jsx(bh,{label:y.area||u("agents_ui.uncategorized"),icon:db,agents:y.agents,pid:e,navigate:t},y.area??"__none"))}):n.jsxs("div",{className:"space-y-3",children:[g.length>0&&n.jsx(bh,{label:u("project.overview.orchestrators"),icon:va,agents:g,pid:e,navigate:t}),h.length>0&&n.jsx(bh,{label:u("project.overview.specialists"),icon:rn,agents:h,pid:e,navigate:t})]})}),n.jsx(Ve,{title:u("project.overview.recent_tasks"),className:"!p-4",action:n.jsx(df,{to:`/p/${e}/tasks`,className:"text-xs text-sky-500 hover:text-sky-400",children:u("common.view_all")}),children:E.length===0?n.jsxs("p",{className:"flex items-center gap-2 text-sm text-muted-fg",children:[n.jsx(qf,{className:"size-4"}),u("project.overview.no_activity")]}):n.jsx("ul",{className:"space-y-1.5",children:E.map(y=>n.jsx("li",{children:n.jsxs("button",{type:"button",onClick:()=>t(`/p/${e}/tasks?task=${y.id}`),className:"flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left hover:bg-accent/40",children:[n.jsx(Af,{status:Tf(y),className:"size-3.5 shrink-0"}),n.jsx("span",{className:"min-w-0 flex-1 truncate text-sm",children:y.title}),n.jsx(B_,{status:Tf(y)})]})},y.id))})})]}),n.jsxs("div",{className:"grid grid-cols-2 gap-4 md:grid-cols-3",children:[n.jsx(So,{title:u("project.overview.chat"),value:u("project.overview.chat_value"),href:`/p/${e}/chat`,icon:Gf}),n.jsx(So,{title:u("project.overview.mcps"),value:d.data?.length??"…",href:`/p/${e}/mcps`,icon:Yf}),n.jsx(So,{title:u("project.overview.routines"),value:l.data?.length??"…",href:`/p/${e}/routines`,icon:Mo})]}),m.length>0&&n.jsx(Ve,{title:u("project.overview.brain_title"),description:u("project.overview.brain_desc"),className:"!p-4",children:n.jsx(d8,{pid:e,agents:m,routines:l.data??[],navigate:t})})]})}function c8(e){const t=new Map;for(const a of e){const o=a.area||null;t.has(o)||t.set(o,[]),t.get(o).push(a)}return[...t.entries()].sort(([a],[o])=>a===null?1:o===null?-1:a.localeCompare(o)).map(([a,o])=>({area:a,agents:o}))}function u8(e){return e.split(`
|
|
788
|
+
`).map(t=>t.replace(/^[-*#>\s]+/,"").trim()).filter(t=>t.length>2&&!t.startsWith("```")).slice(0,5)}function d8({pid:e,agents:t,routines:a,navigate:o}){const[l,c]=x.useState(!1),d=Be(l?`/team-brain/${e}/${t.map(b=>b.slug).join(",")}`:null,async()=>{const b=await Qn.list(e,"all"),_=await Promise.all(t.map(async j=>{const[E,y]=await Promise.all([an.get(e,j.slug).catch(()=>null),Wr.list(e,j.slug).catch(()=>[])]);return[j.slug,{memory:E?.memory||"",threads:(y||[]).slice(0,4).map(k=>({title:k.title||k.filename,id:k.id}))}]}));return{tasks:b,perAgent:Object.fromEntries(_)}}),f=l&&!!d.data,{nodes:m,edges:g}=x.useMemo(()=>{const b=[],_=[],j="__root";b.push({id:j,label:u("project.overview.brain_core"),kind:"agent",role:"core",emoji:"🧠"});const E=new Set(t.map(k=>k.slug)),y=k=>t.some(N=>N.parent===k);for(const k of t){const N=!!k.is_master||k.type==="orchestrator";b.push({id:k.slug,label:k.slug,slug:k.slug,kind:N?"agent":"agentlink",role:f||N||y(k.slug)?"hub":"leaf",emoji:k.emoji||void 0,relation:k.role||u(N?"project.agents.orchestrator":"project.overview.specialists"),detail:k.description||void 0})}for(const k of t){const N=k.parent&&E.has(k.parent)?k.parent:j;_.push({source:N,target:k.slug})}if(f&&d.data){const{tasks:k,perAgent:N}=d.data,w=(S,R,A,T,z)=>{b.push({id:S,label:R,kind:A,detail:z}),_.push({source:T,target:S})};for(const S of t){const R=N[S.slug];u8(R?.memory||"").forEach((A,T)=>w(`${S.slug}:m${T}`,A,"memory",S.slug,A)),(R?.threads||[]).forEach((A,T)=>w(`${S.slug}:th${T}`,A.title,"thread",S.slug)),k.filter(A=>A.agent===S.slug).slice(0,4).forEach((A,T)=>w(`${S.slug}:ts${T}`,A.title,"task",S.slug,A.body||void 0)),a.filter(A=>A.spec?.agent===S.slug).slice(0,2).forEach((A,T)=>w(`${S.slug}:rt${T}`,A.name,"routine",S.slug,`schedule: ${A.schedule}`))}}return{nodes:b,edges:_}},[t,a,f,d.data]),h=n.jsxs("button",{type:"button",onClick:()=>c(b=>!b),className:ge("inline-flex items-center gap-1.5 rounded-md border px-2 py-1 text-[11px] font-medium backdrop-blur transition-colors",l?"border-primary/40 bg-primary/15 text-foreground":"border-border bg-card/80 text-muted-fg hover:text-foreground"),children:[n.jsx(Dc,{className:ge("size-3.5",d.isLoading&&"animate-pulse")}),u(l?"agents_ui.brain_collapse":"agents_ui.brain_expand")]});return n.jsx(XN,{nodes:m,edges:g,height:620,toolbar:h,onNodeClick:b=>{b.slug&&o(`/p/${e}/agents/${b.slug}`)}})}function bh({label:e,icon:t,agents:a,pid:o,navigate:l}){return n.jsxs("div",{children:[n.jsxs("div",{className:"mb-1.5 flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground",children:[n.jsx(t,{className:"size-3.5"}),e," (",a.length,")"]}),n.jsx("div",{className:"flex flex-wrap gap-1.5",children:a.map(c=>n.jsxs("button",{type:"button",onClick:()=>l(`/p/${o}/agents/${c.slug}`),className:ge("inline-flex items-center gap-1.5 rounded-lg border border-border bg-card px-2 py-1 text-xs hover:border-muted-fg/50"),children:[n.jsx("span",{className:"text-sm leading-none",children:c.emoji||"🤖"}),n.jsx("span",{className:"truncate",children:c.slug}),c.role&&n.jsxs("span",{className:"truncate text-[10px] text-muted-fg",children:["· ",c.role]})]},c.slug))})]})}function So({title:e,value:t,href:a,icon:o}){return n.jsxs(df,{to:a,className:"flex items-center gap-3 rounded-xl border border-border bg-card p-4 hover:bg-accent/40",children:[n.jsx("span",{className:"grid size-10 place-items-center rounded-lg bg-muted text-muted-fg",children:n.jsx(o,{size:20})}),n.jsxs("div",{children:[n.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-fg",children:e}),n.jsx("div",{className:"text-2xl font-semibold",children:t})]})]})}function f8(){const e=Pn(),{projects:t,isLoading:a}=iu();return n.jsxs(Ve,{title:u("base.workspaces_title"),description:u("base.workspaces_desc"),action:n.jsxs(re,{size:"sm",variant:"primary",onClick:()=>e("/p/0/workspaces?action=add-project"),children:[n.jsx(Dt,{size:14})," ",u("base.workspaces_new")]}),children:[a&&n.jsx(st,{}),!a&&t.length===0&&n.jsx(ft,{children:u("base.workspaces_empty")}),n.jsx("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3",children:t.map(o=>{const l=String(o.id)==="0",c=l?u("base.title"):o.name||o.path.split("/").pop()||String(o.id);return n.jsxs("button",{type:"button",onClick:()=>e(`/p/${o.id}`),className:"flex cursor-pointer flex-col gap-2 rounded-xl border border-border bg-card p-4 text-left transition-colors hover:border-muted-fg/50",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Q2,{className:"size-4 text-muted-fg"}),n.jsx("span",{className:"truncate text-sm font-semibold",children:c}),n.jsx($e,{tone:l?"success":"info",children:l?u("base.title"):hN(o.kind)})]}),n.jsx("p",{className:"truncate font-mono text-[10px] text-muted-fg",children:o.path})]},o.id)})})]})}function p8(e){const t=x.useRef(!0);t.current&&(t.current=!1,e())}const QN=x.createContext(null);function Na(){const e=x.useContext(QN);if(e===null)throw new Error(gn(60));return e}const m8=(e,t)=>Object.is(e,t);function li(e,t,a){return e==null||t==null?Object.is(e,t):a(e,t)}function rf(e,t,a){return!e||e.length===0?-1:e.findIndex(o=>o===void 0?!1:li(o,t,a))}function g8(e,t,a){return e.filter(o=>!li(t,o,a))}function Fx(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function WN(e){return e!=null&&e.length>0&&typeof e[0]=="object"&&e[0]!=null&&"items"in e[0]}function h8(e){if(!Array.isArray(e))return e!=null&&"null"in e;const t=e;if(WN(t)){for(const a of t)for(const o of a.items)if(o&&o.value==null&&o.label!=null)return!0;return!1}for(const a of t)if(a&&a.value==null&&a.label!=null)return!0;return!1}function ZN(e,t){if(t&&e!=null)return t(e)??"";if(e&&typeof e=="object"){if("label"in e&&e.label!=null)return String(e.label);if("value"in e)return String(e.value)}return Fx(e)}function Ll(e,t){return t&&e!=null?t(e)??"":e&&typeof e=="object"&&"value"in e&&"label"in e?Fx(e.value):Fx(e)}function JN(e,t,a){function o(){return ZN(e,a)}if(a&&e!=null)return a(e);if(e&&typeof e=="object"&&"label"in e&&e.label!=null)return e.label;if(t&&!Array.isArray(t))return t[e]??o();if(Array.isArray(t)){const l=t,c=WN(l)?l.flatMap(d=>d.items):l;if(e==null||typeof e!="object"){const d=c.find(f=>f.value===e);return d&&d.label!=null?d.label:o()}if("value"in e){const d=c.find(f=>f&&f.value===e.value);if(d&&d.label!=null)return d.label}}return o()}function x8(e,t,a){return e.reduce((o,l,c)=>(c>0&&o.push(", "),o.push(n.jsx(x.Fragment,{children:JN(l,t,a)},c)),o),[])}const nt={id:e=>e.id,labelId:e=>e.labelId,modal:e=>e.modal,items:e=>e.items,itemToStringLabel:e=>e.itemToStringLabel,isItemEqualToValue:e=>e.isItemEqualToValue,value:e=>e.value,hasSelectedValue:e=>{const{value:t,multiple:a,itemToStringValue:o}=e;return t==null?!1:a&&Array.isArray(t)?t.length>0:Ll(t,o)!==""},hasNullItemLabel:(e,t)=>t?h8(e.items):!1,open:e=>e.open,mounted:e=>e.mounted,forceMount:e=>e.forceMount,transitionStatus:e=>e.transitionStatus,openMethod:e=>e.openMethod,activeIndex:e=>e.activeIndex,selectedIndex:e=>e.selectedIndex,isActive:(e,t)=>e.activeIndex===t,isSelected:(e,t)=>{const a=e.isItemEqualToValue,o=e.value;return e.multiple?Array.isArray(o)&&o.some(l=>li(t,l,a)):li(t,o,a)},isSelectedByFocus:(e,t)=>e.selectedIndex===t,popupProps:e=>e.popupProps,triggerProps:e=>e.triggerProps,triggerElement:e=>e.triggerElement,positionerElement:e=>e.positionerElement,listElement:e=>e.listElement,popupSide:e=>e.popupSide,scrollUpArrowVisible:e=>e.scrollUpArrowVisible,scrollDownArrowVisible:e=>e.scrollDownArrowVisible,hasScrollArrows:e=>e.hasScrollArrows};function b8(e,t,a=(o,l)=>o===l){return e.length===t.length&&e.every((o,l)=>a(o,t[l]))}function Cc(e,t=Number.MIN_SAFE_INTEGER,a=Number.MAX_SAFE_INTEGER){return Math.max(t,Math.min(e,a))}const Zs=1;function q_(e,t){return Math.max(0,e-t)}function Of(e,t){if(t<=0)return 0;const a=Cc(e,0,t),o=a,l=t-a,c=o<=Zs,d=l<=Zs;return c&&d?o<=l?0:t:c?0:d?t:a}function _8(e){const{id:t,value:a,defaultValue:o=null,onValueChange:l,open:c,defaultOpen:d=!1,onOpenChange:f,name:m,form:g,autoComplete:h,disabled:b=!1,readOnly:_=!1,required:j=!1,modal:E=!0,actionsRef:y,inputRef:k,onOpenChangeComplete:N,items:w,multiple:S=!1,itemToStringLabel:R,itemToStringValue:A,isItemEqualToValue:T=m8,highlightItemOnHover:z=!0,children:M}=e,{clearErrors:L}=z_(),{setDirty:P,setTouched:B,setFocused:D,validityData:$,setFilled:q,name:G,disabled:U,validation:V,validationMode:X}=du(),Q=kp({id:t}),W=U||b,I=G??m,[K,ee]=ni({controlled:a,default:S?o??ja:o,name:"Select",state:"value"}),[F,ne]=ni({controlled:c,default:d,name:"Select",state:"open"}),Z=x.useRef([]),fe=x.useRef([]),Y=x.useRef(null),oe=x.useRef(null),ve=x.useRef(0),le=x.useRef(null),xe=x.useRef([]),ke=x.useRef(!1),Re=x.useRef(null),Ae=x.useRef(null),Ie=x.useRef({allowSelectedMouseUp:!1,allowUnselectedMouseUp:!1,dragY:0}),Oe=x.useRef(!1),{mounted:Te,setMounted:Ne,transitionStatus:Me}=hi(F),{openMethod:De,triggerProps:Ue}=WC(F),Xe=Hn(()=>new nu({id:Q,labelId:void 0,modal:E,multiple:S,itemToStringLabel:R,itemToStringValue:A,isItemEqualToValue:T,value:K,open:F,mounted:Te,transitionStatus:Me,items:w,forceMount:!1,openMethod:null,activeIndex:null,selectedIndex:null,popupProps:{},triggerProps:{},triggerElement:null,positionerElement:null,listElement:null,popupSide:null,scrollUpArrowVisible:!1,scrollDownArrowVisible:!1,hasScrollArrows:!1})).current,me=tt(Xe,nt.activeIndex),de=tt(Xe,nt.selectedIndex),Le=tt(Xe,nt.triggerElement),ye=tt(Xe,nt.positionerElement),Ce=_6(De),Qe=De??Ce,Ge=x.useMemo(()=>S?"":Ll(K,A),[S,K,A]),lt=x.useMemo(()=>S&&Array.isArray(K)?K.map(ht=>Ll(ht,A)):Ll(K,A),[S,K,A]),Tt=mn(Le),_t=He(()=>lt);O_(Tt,Q,K,_t,!W,m);const Ct=x.useRef(K),je=S?Array.isArray(K)&&K.length>0:K!=null&&Ge!=="";Pe(()=>{q(je)},[je,q]),Pe(function(){let $t=K,Ln=!1;if(S){const An=Array.isArray(K)?K:[];Ln=An.length===0,$t=An[An.length-1]}const rs=Ln?-1:rf(xe.current,$t,T),xs=rs===-1?null:rs;xs===null&&(Ae.current=null),!F&&Xe.set("selectedIndex",xs)},[S,F,K,T,Xe]);function ze(ht){const $t=$.initialValue;return Array.isArray(ht)&&Array.isArray($t)?!b8(ht,$t,(Ln,rs)=>li(Ln,rs,T)):ht!==$t}v_(K,()=>{L(I),P(ze(K)),V.change(K)});const Ye=He((ht,$t)=>{f?.(ht,$t),!$t.isCanceled&&(ne(ht),!ht&&($t.reason===zo||$t.reason===rp)&&(B(!0),D(!1),X==="onBlur"&&V.commit(K)))}),We=He(()=>{Ne(!1),Xe.update({activeIndex:null,openMethod:null,scrollUpArrowVisible:!1,scrollDownArrowVisible:!1}),N?.(!1)});Ca({enabled:!y,open:F,ref:Y,onComplete(){F||We()}}),x.useImperativeHandle(y,()=>({unmount:We}),[We]);const dt=He((ht,$t)=>{l?.(ht,$t),!$t.isCanceled&&ee(ht)}),Rt=He(ht=>{const $t=q_(ht.scrollHeight,ht.clientHeight),Ln=Of(ht.scrollTop,$t),rs=Ln>0,xs=Ln<$t;Xe.set("scrollUpArrowVisible",rs),Xe.set("scrollDownArrowVisible",xs)}),Qt=DO({open:F,onOpenChange:Ye,elements:{reference:Le,floating:ye}}),ot=tC(Qt,{enabled:!_&&!W,event:"mousedown"}),Pt=ip(Qt),on=kC(Qt,{enabled:!_&&!W,listRef:Z,activeIndex:me,selectedIndex:de,disabledIndices:ja,onNavigate(ht){ht===null&&!F||Xe.set("activeIndex",ht)},focusItemOnHover:z}),Yt=wC(Qt,{enabled:!_&&!W&&(F||!S),listRef:fe,activeIndex:me,selectedIndex:de,disabledIndices:ht=>tN(Z.current[ht]),onMatch(ht){F?Xe.set("activeIndex",ht):dt(xe.current[ht],rt(ka))},onTyping(ht){ke.current=ht}}),Fn=x.useMemo(()=>Ss(Yt.reference,on.reference,Pt.reference,ot.reference,Ue),[ot.reference,Yt.reference,on.reference,Pt.reference,Ue]),Tn=x.useMemo(()=>Ss(dp,Yt.floating,on.floating,Pt.floating),[Yt.floating,on.floating,Pt.floating]),as=on.item??sn;p8(()=>{Xe.update({popupProps:Tn,triggerProps:Fn})}),Xe.useSyncedValues({id:Q,modal:E,multiple:S,value:K,open:F,mounted:Te,transitionStatus:Me,popupProps:Tn,triggerProps:Fn,items:w,itemToStringLabel:R,itemToStringValue:A,isItemEqualToValue:T,openMethod:Qe});const dn=x.useMemo(()=>({store:Xe,floatingContext:Qt,required:j,disabled:W,readOnly:_,multiple:S,highlightItemOnHover:z,setValue:dt,setOpen:Ye,listRef:Z,popupRef:Y,scrollHandlerRef:oe,handleScrollArrowVisibility:Rt,scrollArrowsMountedCountRef:ve,itemProps:as,valueRef:le,valuesRef:xe,labelsRef:fe,typingRef:ke,selectionRef:Ie,firstItemTextRef:Re,selectedItemTextRef:Ae,validation:V,onOpenChangeComplete:N,alignItemWithTriggerActiveRef:Oe,initialValueRef:Ct}),[Xe,Qt,j,W,_,S,z,dt,Ye,as,V,N,Rt]),hs=rr(k,V.inputRef),Rs=S?void 0:I,oa=x.useMemo(()=>!S||!Array.isArray(K)||!I?null:K.map(ht=>{const $t=Ll(ht,A);return n.jsx("input",{type:"hidden",form:g,name:I,value:$t,disabled:W},$t)}),[S,K,g,I,A,W]);return n.jsxs(QN.Provider,{value:dn,children:[M,n.jsx("input",{...V.getValidationProps(W,{onFocus(){Xe.state.triggerElement?.focus({focusVisible:!0})},onChange(ht){if(ht.nativeEvent.defaultPrevented||W||_)return;const $t=ht.currentTarget.value,Ln=rt(ka,ht.nativeEvent);function rs(){if(S)return;const xs=$t.toLowerCase();let An=xe.current.findIndex(vn=>Ll(vn,A).toLowerCase()===xs||ZN(vn,R).toLowerCase()===xs);An===-1&&(An=xe.current.findIndex((vn,la)=>{const dr=fe.current[la];return dr!=null&&dr.toLowerCase()===xs}));const Wt=xe.current[An];Wt!=null&&dt(Wt,Ln)}Xe.set("forceMount",!0),queueMicrotask(rs)}}),id:Q&&Rs==null?`${Q}-hidden-input`:void 0,form:g,name:Rs,autoComplete:h,value:Ge,disabled:W,required:j&&!(S&&je),readOnly:_,ref:hs,style:I?NS:Ub,tabIndex:-1,"aria-hidden":!0,suppressHydrationWarning:!0}),oa]})}function v8(e,t){return e??t}const y8=400,j8={...wx,...M_,popupSide:e=>e?{"data-popup-side":e}:null,value:()=>null},k8=x.forwardRef(function(t,a){const{render:o,className:l,id:c,disabled:d=!1,nativeButton:f=!0,style:m,...g}=t,{setTouched:h,setFocused:b,validationMode:_,state:j,disabled:E}=du(),{labelId:y}=jp(),{store:k,setOpen:N,selectionRef:w,validation:S,readOnly:R,required:A,alignItemWithTriggerActiveRef:T,disabled:z}=Na(),M=E||z||d,L=tt(k,nt.open),P=tt(k,nt.mounted),B=tt(k,nt.value),D=tt(k,nt.triggerProps),$=tt(k,nt.positionerElement),q=tt(k,nt.listElement),G=tt(k,nt.popupSide),U=tt(k,nt.id),V=tt(k,nt.labelId),X=tt(k,nt.hasSelectedValue),Q=P&&$?G:null,W=c??U,I=v8(y,V);kp({id:W});const K=mn($),ee=x.useRef(null),{getButtonProps:F,buttonRef:ne}=no({disabled:M,native:f}),Z=k.useStateSetter("triggerElement"),fe=Rn(),Y=Rn(),oe=Rn();x.useEffect(()=>{if(L)return oe.start(y8,()=>{w.current.allowUnselectedMouseUp=!0,w.current.allowSelectedMouseUp=!0}),()=>{oe.clear()};w.current={allowSelectedMouseUp:!1,allowUnselectedMouseUp:!1,dragY:0},Y.clear()},[L,w,Y,oe]);const ve=Ss(D,{id:W,role:"combobox","aria-expanded":L,"aria-haspopup":"listbox","aria-controls":L?q?.id??mf($)?.id:void 0,"aria-labelledby":I,"aria-readonly":R||void 0,"aria-required":A||void 0,tabIndex:M?-1:0,onFocus(ke){b(!0),L&&T.current&&N(!1,rt(ka,ke.nativeEvent)),fe.start(0,()=>{k.set("forceMount",!0)})},onBlur(ke){Ze($,ke.relatedTarget)||(h(!0),b(!1),_==="onBlur"&&S.commit(B))},onMouseDown(ke){if(L)return;const Re=vt(ke.currentTarget);function Ae(Ie){if(!ee.current)return;const Oe=Ie.target;Ze(ee.current,Oe)||Ze(K.current,Oe)||ZC(Ie,ee.current)||N(!1,rt(yS,Ie))}Y.start(0,()=>{Re.addEventListener("mouseup",Ae,{once:!0})})}},g,F),le=S.getValidationProps(M,ve);le.role="combobox";const xe={...j,open:L,disabled:M,value:B,readOnly:R,popupSide:Q,placeholder:!X};return Et("button",t,{ref:[a,ee,ne,Z],state:xe,stateAttributesMapping:j8,props:le})}),w8={value:()=>null},S8=x.forwardRef(function(t,a){const{className:o,render:l,children:c,placeholder:d,style:f,...m}=t,{store:g,valueRef:h}=Na(),b=tt(g,nt.value),_=tt(g,nt.items),j=tt(g,nt.itemToStringLabel),E=tt(g,nt.hasSelectedValue),y=!E&&d!=null&&c==null,k=tt(g,nt.hasNullItemLabel,y),N={value:b,placeholder:!E};let w=null;return typeof c=="function"?w=c(b):c!=null?w=c:y&&!k?w=d:Array.isArray(b)?w=x8(b,_,j):w=JN(b,_,j),Et("span",t,{state:N,ref:[a,h],props:[{children:w},m],stateAttributesMapping:w8})}),C8=x.forwardRef(function(t,a){const{render:o,className:l,style:c,...d}=t,{store:f}=Na(),g={open:tt(f,nt.open)};return Et("span",t,{state:g,ref:a,props:[{"aria-hidden":!0,children:"▼"},d],stateAttributesMapping:CC})}),N8=x.forwardRef(function(t,a){const{store:o}=Na(),l=tt(o,nt.mounted),c=tt(o,nt.forceMount);return l||c?n.jsx(Qb,{ref:a,...t}):null}),eE=x.createContext(void 0);function H_(){const e=x.useContext(eE);if(!e)throw new Error(gn(59));return e}function Df(e,t){e&&Object.assign(e.style,t)}const tE={position:"relative",maxHeight:"100%",overflowX:"hidden",overflowY:"auto"},E8={position:"fixed"},R8=x.forwardRef(function(t,a){const{anchor:o,className:l,render:c,positionMethod:d,side:f,align:m,sideOffset:g,alignOffset:h,collisionBoundary:b="clipping-ancestors",collisionPadding:_,arrowPadding:j,sticky:E,disableAnchorTracking:y,alignItemWithTrigger:k=!0,collisionAvoidance:N=GS,style:w,...S}=t,{store:R,listRef:A,labelsRef:T,alignItemWithTriggerActiveRef:z,selectedItemTextRef:M,valuesRef:L,initialValueRef:P,popupRef:B,setValue:D,floatingContext:$}=Na(),q=tt(R,nt.open),G=tt(R,nt.mounted),U=tt(R,nt.modal),V=tt(R,nt.value),X=tt(R,nt.openMethod),Q=tt(R,nt.positionerElement),W=tt(R,nt.triggerElement),I=tt(R,nt.isItemEqualToValue),K=tt(R,nt.transitionStatus),ee=x.useRef(null),F=x.useRef(null),[ne,Z]=x.useState(k),fe=G&&ne&&X!=="touch";!G&&ne!==k&&Z(k),x.useImperativeHandle(z,()=>fe),YC((fe||U)&&q,X==="touch",Q,W);const Y=f_({anchor:o,floatingRootContext:$,positionMethod:d,mounted:G,side:f,sideOffset:g,align:m,alignOffset:h,arrowPadding:j,collisionBoundary:b,collisionPadding:_,sticky:E,disableAnchorTracking:y??fe,collisionAvoidance:N,keepMounted:!0}),oe=fe?"none":Y.side,ve=fe?E8:Y.positionerStyles,le={open:q,side:oe,align:Y.align,anchorHidden:Y.anchorHidden};Pe(()=>{R.set("popupSide",Y.side)},[R,Y.side]);const xe=R.useStateSetter("positionerElement"),ke=p_(t,le,{styles:ve,transitionStatus:K,props:S,refs:[a,xe],hidden:!G,inert:!q}),Re=x.useRef(0),Ae=He(Oe=>{if(L.current.length===0)return;const Te=Re.current;if(Re.current=Oe.size,Oe.size===Te)return;const Ne=rt(ka);if(Te!==0&&!R.state.multiple&&V!==null&&rf(L.current,V,I)===-1){const De=P.current,Xe=De!=null&&rf(L.current,De,I)!==-1?De:null;D(Xe,Ne),Xe===null&&(R.set("selectedIndex",null),M.current=null)}if(Te!==0&&R.state.multiple&&Array.isArray(V)){const Me=V.filter(De=>rf(L.current,De,I)!==-1);Me.length!==V.length&&(D(Me,Ne),Me.length===0&&(R.set("selectedIndex",null),M.current=null))}if(q&&fe){R.update({scrollUpArrowVisible:!1,scrollDownArrowVisible:!1});const Me={height:""};Df(Q,Me),Df(B.current,Me)}}),Ie=x.useMemo(()=>({...Y,side:oe,alignItemWithTriggerActive:fe,setControlledAlignItemWithTrigger:Z,scrollUpArrowRef:ee,scrollDownArrowRef:F}),[Y,oe,fe,Z]);return n.jsx(bp,{elementsRef:A,labelsRef:T,onMapChange:Ae,children:n.jsxs(eE.Provider,{value:Ie,children:[G&&U&&n.jsx(__,{inert:gp(!q),cutout:W}),ke]})})}),Id="base-ui-disable-scrollbar",Gx={className:Id,getElement(e){return n.jsx("style",{nonce:e,href:Id,precedence:"base-ui:low",children:`.${Id}{scrollbar-width:none}.${Id}::-webkit-scrollbar{display:none}`})}},T8=x.createContext(void 0),A8={disableStyleElements:!1};function M8(){return x.useContext(T8)??A8}const z8={...au,...Ho},O8=x.forwardRef(function(t,a){const{render:o,className:l,style:c,finalFocus:d,...f}=t,{store:m,popupRef:g,onOpenChangeComplete:h,setOpen:b,valueRef:_,firstItemTextRef:j,selectedItemTextRef:E,multiple:y,handleScrollArrowVisibility:k,scrollHandlerRef:N,listRef:w,highlightItemOnHover:S,floatingContext:R}=Na(),{side:A,align:T,alignItemWithTriggerActive:z,isPositioned:M,setControlledAlignItemWithTrigger:L}=H_(),P=HC()!=null,B=pp(),{nonce:D,disableStyleElements:$}=M8(),q=tt(m,nt.id),G=tt(m,nt.open),U=tt(m,nt.openMethod),V=tt(m,nt.mounted),X=tt(m,nt.popupProps),Q=tt(m,nt.transitionStatus),W=tt(m,nt.triggerElement),I=tt(m,nt.positionerElement),K=tt(m,nt.listElement),ee=x.useRef(!1),F=x.useRef(!1),ne=x.useRef({}),Z=Jl(),fe=He(le=>{if(!I||!g.current||!F.current)return;const xe=I.style.top==="0px",ke=I.style.bottom==="0px";if(ee.current||!z||!xe&&!ke){k(le);return}const Re=Hk(I),Ae=Nc(I.getBoundingClientRect().height,"y",Re),Ie=vt(I),Oe=Jt(I),Te=Oe.getComputedStyle(I),Ne=parseFloat(Te.marginTop),Me=parseFloat(Te.marginBottom),De=qk(Oe.getComputedStyle(g.current)),Ue=Math.min(Ie.documentElement.clientHeight-Ne-Me,De),Xe=le.scrollTop,me=Bd(le);let de=null;const Le=Ge=>{I.style.height=`${Ge}px`},ye=xe?me-Xe:Xe,Ce=Math.min(Ae+ye,Ue);if(ye<=Zs){const Ge=Cc(ye,0,Ue-Ae);Ge>0&&Le(Ae+Ge),le.scrollTop=xe?me:0,Ue-(Ae+Ge)<=Zs&&(ee.current=!0),k(le);return}if(Ue-Ce>Zs)de=xe?1/0:0;else if(ke&&Xe<me){const Ge=Ae+ye-Ue;de=Xe-(ye-Ge)}const Qe=Math.ceil(Ce);if(Qe!==0&&Le(Qe),de!=null){const Ge=Cc(de,0,Bd(le));Math.abs(le.scrollTop-Ge)>Zs&&(le.scrollTop=Ge)}Qe>=Ue-Zs&&(ee.current=!0),k(le)});x.useImperativeHandle(N,()=>fe,[fe]),Ca({open:G,ref:g,onComplete(){G&&h?.(!0)}});const Y={open:G,transitionStatus:Q,side:A,align:T};Pe(()=>{!I||!g.current||Object.keys(ne.current).length||(ne.current={top:I.style.top||"0",left:I.style.left||"0",right:I.style.right,height:I.style.height,bottom:I.style.bottom,minHeight:I.style.minHeight,maxHeight:I.style.maxHeight,marginTop:I.style.marginTop,marginBottom:I.style.marginBottom})},[g,I]),Pe(()=>{G||z||(F.current=!1,ee.current=!1,Df(I,ne.current))},[G,z,I,g]),Pe(()=>{const le=g.current;if(!G||!W||!I||!le||z&&!M||m.state.transitionStatus==="ending")return;if(F.current=!0,le.style.removeProperty("--transform-origin"),!z){Z.request(()=>k(K||le));return}const xe=D8(le);try{let ke=E.current;ke?.isConnected||(ke=!nt.hasSelectedValue(m.state)&&j.current?.isConnected?j.current:null);const Re=_.current,Ae=Jt(I),Ie=Ae.getComputedStyle(I),Oe=Ae.getComputedStyle(le),Te=vt(W),Ne=Hk(W),Me=$d(W.getBoundingClientRect(),Ne),De=$d(I.getBoundingClientRect(),Ne),Ue=Me.height,Xe=K||le,me=Xe.scrollHeight,de=parseFloat(Oe.borderBottomWidth),Le=parseFloat(Ie.marginTop)||10,ye=parseFloat(Ie.marginBottom)||10,Ce=parseFloat(Ie.minHeight)||100,Qe=qk(Oe),Ge=5,lt=5,Tt=20,_t=Te.documentElement.clientHeight-Le-ye,Ct=Te.documentElement.clientWidth,je=_t-Me.bottom+Ue;let ze,Ye=B==="rtl"?Me.right-De.width:Me.left,We=0;if(ke&&Re){const dn=$d(Re.getBoundingClientRect(),Ne);ze=$d(ke.getBoundingClientRect(),Ne),Ye=De.left+(B==="rtl"?dn.right-ze.right:dn.left-ze.left);const hs=dn.top-Me.top+dn.height/2;We=ze.top-De.top+ze.height/2-hs}const dt=je+We+ye+de;let Rt=Math.min(_t,dt);const Qt=_t-Le-ye,ot=dt-Rt,Pt=Ct-lt;I.style.left=`${Cc(Ye,Ge,Pt-De.width)}px`,I.style.height=`${Rt}px`,I.style.maxHeight="none",I.style.marginTop=`${Le}px`,I.style.marginBottom=`${ye}px`,le.style.height="100%";const on=Bd(Xe),Yt=ot>=on-Zs;Yt&&(Rt=Math.min(_t,De.height)-(ot-on));const Fn=Me.top<Tt||Me.bottom>_t-Tt||Math.ceil(Rt)+Zs<Math.min(me,Ce),Tn=(Ae.visualViewport?.scale??1)!==1&&ir;if(Fn||Tn){Df(I,ne.current),L(!1);return}const as=Math.max(Ce,Rt);if(Yt){const dn=Math.max(0,_t-dt);I.style.top=De.height>=Qt?"0":`${dn}px`,I.style.height=`${Rt}px`,Xe.scrollTop=Bd(Xe)}else I.style.bottom="0",Xe.scrollTop=ot;if(ze){const dn=De.top,hs=De.height,Rs=ze.top+ze.height/2,oa=Cc(hs>0?(Rs-dn)/hs*100:50,0,100);le.style.setProperty("--transform-origin",`50% ${oa}%`)}(as===_t||Rt>=Qe)&&(ee.current=!0),k(Xe),S&&m.state.selectedIndex===null&&m.state.activeIndex===null&&w.current[0]!=null&&m.set("activeIndex",0)}finally{xe()}},[m,G,I,W,_,j,E,g,k,z,L,Z,K,w,S,B,M]),x.useEffect(()=>{if(!z||!I||!G)return;const le=Jt(I);function xe(ke){b(!1,rt(R4,ke))}return xt(le,"resize",xe)},[b,z,I,G]);const oe={...K?{role:"presentation","aria-orientation":void 0}:{role:"listbox","aria-multiselectable":y||void 0,id:`${q}-list`},onKeyDown(le){P&&xp.has(le.key)&&le.stopPropagation()},onScroll(le){K||fe(le.currentTarget)},...z&&{style:K?{height:"100%"}:tE},className:!K&&z?Gx.className:void 0},ve=Et("div",t,{ref:[a,g],state:Y,stateAttributesMapping:z8,props:[X,oe,mp(Q),f]});return n.jsxs(x.Fragment,{children:[!$&&Gx.getElement(D),n.jsx(Jb,{context:R,modal:!1,disabled:!V,openInteractionType:U,returnFocus:d,restoreFocus:!0,children:ve})]})});function qk(e){const t=e.maxHeight;return t.endsWith("px")&&parseFloat(t)||1/0}function Bd(e){return q_(e.scrollHeight,e.clientHeight)}function Hk(e){return lC.getScale(e)}function Nc(e,t,a){return e/a[t]}function $d(e,t){return Bc({x:Nc(e.x,"x",t),y:Nc(e.y,"y",t),width:Nc(e.width,"x",t),height:Nc(e.height,"y",t)})}const Vk=[["transform","none"],["scale","1"],["translate","0 0"]];function D8(e){const{style:t}=e,a={};for(const[o,l]of Vk)a[o]=t.getPropertyValue(o),t.setProperty(o,l,"important");return()=>{for(const[o]of Vk){const l=a[o];l?t.setProperty(o,l):t.removeProperty(o)}}}const P8=x.forwardRef(function(t,a){const{render:o,className:l,style:c,...d}=t,{store:f,scrollHandlerRef:m,multiple:g}=Na(),{alignItemWithTriggerActive:h}=H_(),b=tt(f,nt.hasScrollArrows),_=tt(f,nt.openMethod),E={id:`${tt(f,nt.id)}-list`,role:"listbox","aria-multiselectable":g||void 0,onScroll(k){m.current?.(k.currentTarget)},...h&&{style:tE},className:b&&_!=="touch"?Gx.className:void 0},y=f.useStateSetter("listElement");return Et("div",t,{ref:[a,y],props:[E,d]})}),nE=x.createContext(void 0);function V_(){const e=x.useContext(nE);if(!e)throw new Error(gn(57));return e}const L8=x.memo(x.forwardRef(function(t,a){const{render:o,className:l,style:c,value:d=null,label:f,disabled:m=!1,nativeButton:g=!1,...h}=t,b=x.useRef(null),_=ru({guess:!0,label:f,textRef:b}),{store:j,itemProps:E,setOpen:y,setValue:k,selectionRef:N,typingRef:w,valuesRef:S,multiple:R,selectedItemTextRef:A,disabled:T,readOnly:z}=Na(),M=T||m,L=tt(j,nt.isActive,_.index),P=tt(j,nt.open),B=tt(j,nt.isSelected,d),D=tt(j,nt.isSelectedByFocus,_.index),$=tt(j,nt.isItemEqualToValue),q=_.index,G=x.useRef(null);Pe(()=>{const Z=S.current;return Z[q]=d,()=>{delete Z[q]}},[q,d,S]),Pe(()=>{const Z=j.state.value;let fe=Z;R&&Array.isArray(Z)&&(fe=Z.length>0?Z[Z.length-1]:void 0),fe!==void 0&&li(d,fe,$)&&(j.set("selectedIndex",q),b.current&&(A.current=b.current))},[q,R,$,j,d,A]);const U=x.useRef("mouse"),V=x.useRef(!1),{getButtonProps:X,buttonRef:Q}=no({disabled:M,focusableWhenDisabled:!0,native:g,composite:!0}),W={disabled:M,selected:B,highlighted:L};function I(Z){if(T||z)return;const fe=j.state.value;if(R){const Y=Array.isArray(fe)?fe:[],oe=B?g8(Y,d,$):[...Y,d];k(oe,rt(Fl,Z))}else k(d,rt(Fl,Z)),y(!1,rt(Fl,Z))}function K(){N.current.dragY=0}const ee={role:"option","aria-selected":B,tabIndex:P&&L?0:-1,onKeyDown(Z){j.set("activeIndex",q),Z.key===" "&&w.current&&Z.preventDefault()},onClick(Z){const fe=U.current!=="touch",Y=Z.nativeEvent.pointerType,oe=fe&&zb(Z.nativeEvent)&&(Y!==void 0||L),ve=fe&&!oe&&!V.current;V.current=!1,!(M||ve)&&I(Z.nativeEvent)},onPointerEnter(Z){U.current=Z.pointerType},onPointerMove(Z){if(Z.pointerType==="mouse"&&Z.buttons===1){const fe=N.current;fe.dragY+=Z.movementY,fe.dragY**2>=64&&(fe.allowUnselectedMouseUp=!0)}},onPointerDown(Z){U.current=Z.pointerType,V.current=!0,K()},onMouseUp(){if(K(),M||U.current==="touch"||V.current)return;const Z=!N.current.allowSelectedMouseUp&&B,fe=!N.current.allowUnselectedMouseUp&&!B;Z||fe||(V.current=!0,G.current?.click(),V.current=!1)}},F=Et("div",t,{ref:[Q,a,_.ref,G],state:W,props:[E,ee,h,X]}),ne=x.useMemo(()=>({selected:B,index:q,textRef:b,selectedByFocus:D}),[B,q,b,D]);return n.jsx(nE.Provider,{value:ne,children:F})})),I8=x.forwardRef(function(t,a){const{selected:o}=V_();return t.keepMounted||o?n.jsx(B8,{...t,ref:a}):null}),B8=x.memo(x.forwardRef((e,t)=>{const{render:a,className:o,style:l,keepMounted:c,...d}=e,{selected:f}=V_(),m=x.useRef(null),{transitionStatus:g,setMounted:h}=hi(f),_=Et("span",e,{ref:[t,m],state:{selected:f,transitionStatus:g},props:[{"aria-hidden":!0,children:"✔️"},d],stateAttributesMapping:Ho});return Ca({open:f,ref:m,onComplete(){f||h(!1)}}),_})),$8=x.memo(x.forwardRef(function(t,a){const{index:o,textRef:l,selectedByFocus:c}=V_(),{firstItemTextRef:d,selectedItemTextRef:f}=Na(),{render:m,className:g,style:h,...b}=t,_=x.useCallback(E=>{E&&(o===0&&(d.current=E),c&&(f.current=E))},[d,f,o,c]);return Et("div",t,{ref:[_,a,l],props:b})})),sE=x.forwardRef(function(t,a){const{render:o,className:l,style:c,direction:d,keepMounted:f,...m}=t,g=d==="up",{store:h,popupRef:b,listRef:_,handleScrollArrowVisibility:j,scrollArrowsMountedCountRef:E}=Na(),{side:y,scrollDownArrowRef:k,scrollUpArrowRef:N}=H_(),w=g?nt.scrollUpArrowVisible:nt.scrollDownArrowVisible,S=tt(h,w),R=tt(h,nt.openMethod),A=S&&R!=="touch",T=Rn(),z=g?N:k,{mounted:M,transitionStatus:L,setMounted:P}=hi(A);Pe(()=>(E.current+=1,h.set("hasScrollArrows",!0),()=>{E.current=Math.max(0,E.current-1),E.current===0&&h.set("hasScrollArrows",!1)}),[h,E]),Ca({open:A,ref:z,onComplete(){A||P(!1)}});const $=Et("div",t,{ref:[a,z],state:{direction:d,visible:A,side:y,transitionStatus:L},props:[{"aria-hidden":!0,children:g?"▲":"▼",style:{position:"absolute"},onMouseMove(G){if(G.movementX===0&&G.movementY===0||T.isStarted())return;h.set("activeIndex",null);function U(){const V=h.state.listElement??b.current;if(!V)return;h.set("activeIndex",null),j(V);const X=q_(V.scrollHeight,V.clientHeight),Q=Of(V.scrollTop,X),W=Q===(g?0:X),I=_.current;if(Q!==V.scrollTop&&(V.scrollTop=Q),W){T.clear();return}if(I.length>0){const K=z.current?.offsetHeight||0;V.scrollTop=U8(I,g,Q,V.clientHeight,K,X)}T.start(40,U)}T.start(40,U)},onMouseLeave(){T.clear()}},m],stateAttributesMapping:Ho});return M||f?$:null});function U8(e,t,a,o,l,c){if(t){let h=0;const b=a+l-Zs;for(let E=0;E<e.length;E+=1){const y=e[E];if(y&&y.offsetTop>=b){h=E;break}}const _=Math.max(0,h-1),j=e[_];return _<h&&j?Of(j.offsetTop-l,c):0}let d=e.length-1;const f=a+o-l+Zs;for(let h=0;h<e.length;h+=1){const b=e[h];if(b&&b.offsetTop+b.offsetHeight>f){d=Math.max(0,h-1);break}}const m=Math.min(e.length-1,d+1),g=e[m];return m>d&&g?Of(g.offsetTop+g.offsetHeight-o+l,c):c}const q8=x.forwardRef(function(t,a){return n.jsx(sE,{...t,ref:a,direction:"down"})}),H8=x.forwardRef(function(t,a){return n.jsx(sE,{...t,ref:a,direction:"up"})}),V8=_8;function F8({className:e,...t}){return n.jsx(S8,{"data-slot":"select-value",className:St("flex flex-1 text-left",e),...t})}function G8({className:e,size:t="default",children:a,...o}){return n.jsxs(k8,{"data-slot":"select-trigger","data-size":t,className:St("flex w-fit items-center justify-between gap-1.5 rounded-lg border border-input bg-transparent py-2 pr-2 pl-2.5 text-sm whitespace-nowrap transition-colors outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-8 data-[size=sm]:h-7 data-[size=sm]:rounded-[min(var(--radius-md),10px)] *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...o,children:[a,n.jsx(C8,{render:n.jsx(ms,{className:"pointer-events-none size-4 text-muted-foreground"})})]})}function Y8({className:e,children:t,side:a="bottom",sideOffset:o=4,align:l="center",alignOffset:c=0,alignItemWithTrigger:d=!0,...f}){return n.jsx(N8,{children:n.jsx(R8,{side:a,sideOffset:o,align:l,alignOffset:c,alignItemWithTrigger:d,className:"isolate z-50",children:n.jsxs(O8,{"data-slot":"select-content","data-align-trigger":d,className:St("relative isolate z-50 max-h-(--available-height) w-(--anchor-width) min-w-36 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",e),...f,children:[n.jsx(X8,{}),n.jsx(P8,{children:t}),n.jsx(Q8,{})]})})})}function K8({className:e,children:t,...a}){return n.jsxs(L8,{"data-slot":"select-item",className:St("relative flex w-full cursor-default items-center gap-2 rounded-md py-2 pr-8 pl-2.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",e),...a,children:[n.jsx($8,{className:"flex min-w-0 flex-1 gap-2 overflow-hidden whitespace-nowrap",children:t}),n.jsx(I8,{render:n.jsx("span",{className:"pointer-events-none absolute right-2 flex size-4 items-center justify-center"}),children:n.jsx(Yr,{className:"pointer-events-none"})})]})}function X8({className:e,...t}){return n.jsx(H8,{"data-slot":"select-scroll-up-button",className:St("top-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",e),...t,children:n.jsx(fb,{})})}function Q8({className:e,...t}){return n.jsx(q8,{"data-slot":"select-scroll-down-button",className:St("bottom-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",e),...t,children:n.jsx(ms,{})})}function ct({value:e,onChange:t,options:a,placeholder:o="— elegir —",disabled:l,className:c,showIcon:d=!1}){return n.jsxs(V8,{value:e,onValueChange:f=>t(f??""),disabled:l,children:[n.jsx(G8,{className:ge("h-9 w-full",c),children:n.jsx(F8,{placeholder:o,children:f=>{const m=a.find(h=>h.value===f),g=d?m?.icon:void 0;return n.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[g&&n.jsx(g,{className:"size-3.5 shrink-0"}),n.jsx("span",{className:"truncate",children:m?.label??f})]})}})}),n.jsx(Y8,{side:"bottom",sideOffset:6,align:"start",alignItemWithTrigger:!1,className:"w-[var(--anchor-width)] p-1.5",children:a.map(f=>{const m=f.icon;return n.jsx(K8,{value:f.value,disabled:f.disabled,children:n.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[m?n.jsx(m,{className:"size-4 shrink-0 text-muted-fg"}):null,f.description?n.jsxs("span",{className:"flex min-w-0 flex-col leading-tight",children:[n.jsx("span",{className:"truncate font-medium",children:f.label}),n.jsx("span",{className:"truncate text-[11px] text-muted-fg",children:f.description})]}):n.jsx("span",{className:"truncate",children:f.label})]})},f.value)})})]})}const Fk=320;function W8(e){const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString(void 0,{month:"short",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"})}function Z8(e){return e.agent_slug||e.actor_id||e.author||e.actor_kind||"—"}function J8(e){const t=e.meta?.model;return typeof t=="string"&&t?t:null}function eI(e){const t=e.meta?.usage;if(!t||typeof t!="object")return null;const a=(t.input_tokens||0)+(t.output_tokens||0);return a>0?a:null}function tI({m:e}){const[t,a]=x.useState(!1),o=(e.body?.length||0)>Fk,l=!o||t?e.body:`${e.body.slice(0,Fk)}…`,c=J8(e),d=eI(e);return n.jsxs("li",{className:"flex items-start gap-3 rounded-md border border-border bg-muted/30 px-3 py-2",children:[n.jsx("span",{className:"mt-0.5 shrink-0",children:e.direction==="in"?n.jsx(q2,{size:14,className:"text-blue-400"}):n.jsx(V2,{size:14,className:"text-emerald-400"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-fg",children:[n.jsx("span",{className:"font-mono",children:W8(e.ts)}),n.jsx($e,{tone:"info",children:e.channel}),e.type&&n.jsx($e,{children:e.type}),n.jsx("span",{className:"font-medium text-foreground",children:Z8(e)}),c&&n.jsx("span",{className:"font-mono text-[11px] text-sky-400/90",children:c}),d!==null&&n.jsxs("span",{className:"font-mono text-[11px]",children:[d," tok"]})]}),e.body&&n.jsx("p",{className:"mt-1 whitespace-pre-wrap break-words text-xs",children:l}),o&&n.jsx("button",{type:"button",onClick:()=>a(f=>!f),className:"mt-1 text-[11px] font-medium text-sky-400 hover:underline",children:u(t?"logs.show_less":"logs.show_more")})]})]})}function nI(){const[e,t]=x.useState(!1),a=Be(e?"/admin/logs?errors":null,()=>ai.logs("errors",200)),o=a.data?.entries||[];return n.jsxs("details",{className:"mb-3 rounded-lg border border-border bg-muted/20",onToggle:l=>t(l.target.open),children:[n.jsxs("summary",{className:"cursor-pointer px-3 py-2 text-xs font-medium text-muted-fg",children:[u("logs.daemon_errors"),o.length?` · ${o.length}`:""]}),n.jsxs("div",{className:"border-t border-border p-3",children:[a.isLoading&&n.jsx(st,{}),e&&!a.isLoading&&o.length===0&&n.jsx("p",{className:"text-xs text-muted-fg",children:u("logs.no_errors")}),n.jsx("ul",{className:"space-y-1",children:o.map((l,c)=>n.jsxs("li",{className:"rounded-md bg-card px-2 py-1 text-[11px]",children:[n.jsxs("div",{className:"flex items-center gap-2 text-muted-fg",children:[typeof l.ts=="string"&&n.jsx("span",{className:"font-mono",children:new Date(l.ts).toLocaleString()}),typeof l.level=="string"&&n.jsx("span",{className:"text-destructive",children:l.level})]}),n.jsx("p",{className:"whitespace-pre-wrap break-words font-mono",children:String(l.msg??l.message??l.error??l.raw??JSON.stringify(l)).slice(0,500)})]},c))})]})]})}function sI({pid:e}){const t=!e||String(e)==="0",[a,o]=x.useState(""),[l,c]=x.useState(""),[d,f]=x.useState(""),[m,g]=x.useState(""),h=a.trim()||void 0,b=t?`/messages/global?channel=${h??""}`:`/projects/${e}/messages?channel=${h??""}`,_=Be(b,()=>t?Cf.global({channel:h,limit:300}):Cf.project(e,{channel:h,limit:300})),j=x.useMemo(()=>[..._.data||[]].sort((k,N)=>(N.ts||"").localeCompare(k.ts||"")),[_.data]),E=x.useMemo(()=>Array.from(new Set(j.map(k=>k.type).filter(Boolean))),[j]),y=x.useMemo(()=>j.filter(k=>!(l&&k.direction!==l||d&&k.type!==d||m&&!(k.body||"").toLowerCase().includes(m.toLowerCase()))),[j,l,d,m]);return n.jsxs(Ve,{title:u("logs.title"),description:u(t?"logs.desc_global":"logs.desc_project"),action:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Ee,{placeholder:u("logs.filter_channel"),value:a,onChange:k=>o(k.target.value),className:"w-44"}),n.jsx(re,{size:"sm",variant:"secondary",onClick:()=>_.mutate(),children:n.jsx(Cs,{size:13})})]}),children:[t&&n.jsx(nI,{}),n.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2",children:[n.jsx("div",{className:"w-36",children:n.jsx(ct,{value:l,onChange:c,placeholder:u("logs.filter_dir"),options:[{value:"",label:u("logs.all_directions")},{value:"in",label:u("logs.in")},{value:"out",label:u("logs.out")}]})}),n.jsx("div",{className:"w-40",children:n.jsx(ct,{value:d,onChange:f,placeholder:u("logs.filter_type"),options:[{value:"",label:u("logs.all_types")},...E.map(k=>({value:k,label:k}))]})}),n.jsx(Ee,{placeholder:u("logs.search_text"),value:m,onChange:k=>g(k.target.value),className:"w-56"}),n.jsxs("span",{className:"text-[11px] text-muted-fg",children:[y.length," ",u("logs.count_of")," ",j.length]})]}),_.isLoading&&n.jsx(st,{}),_.error&&n.jsx(ft,{children:u("logs.error",{msg:_.error.message})}),!_.isLoading&&!_.error&&y.length===0&&n.jsx(ft,{children:h?u("logs.no_activity_ch",{ch:h}):u("logs.no_activity")}),n.jsx("ul",{className:"space-y-1 text-sm",children:y.map((k,N)=>n.jsx(tI,{m:k},`${k.ts}-${N}`))})]})}function aE({value:e,onChange:t,options:a,placeholder:o=u("shared_ui.model_combobox_ph"),invalid:l,invalidHint:c,className:d}){const[f,m]=x.useState(!1),[g,h]=x.useState(e),b=x.useRef(null),_=x.useRef(null),[j,E]=x.useState(null);x.useEffect(()=>{h(e)},[e]),x.useLayoutEffect(()=>{if(!f)return;const S=()=>{const R=b.current;if(!R)return;const A=R.getBoundingClientRect();E({top:A.bottom+4,left:A.left,width:A.width})};return S(),window.addEventListener("scroll",S,!0),window.addEventListener("resize",S),()=>{window.removeEventListener("scroll",S,!0),window.removeEventListener("resize",S)}},[f]),x.useEffect(()=>{if(!f)return;const S=R=>{const A=R.target;b.current?.contains(A)||_.current?.contains(A)||m(!1)};return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[f]);const y=g.trim().toLowerCase(),N=y&&!(g===e)?a.filter(S=>S.toLowerCase().includes(y)):a,w=S=>{t(S),h(S),m(!1)};return n.jsxs("div",{ref:b,className:ge("relative",d),children:[n.jsxs("div",{className:ge("flex items-center gap-1 rounded-lg border bg-background px-2.5 transition-colors focus-within:border-ring focus-within:ring-1 focus-within:ring-ring",l?"border-amber-500/60":"border-border"),children:[l&&n.jsx(qe,{content:c||u("models_ui.invalid_hint"),children:n.jsx("span",{children:n.jsx(wb,{className:"size-3.5 shrink-0 text-amber-400"})})}),n.jsx("input",{value:g,placeholder:o,onChange:S=>{h(S.target.value),t(S.target.value),m(!0)},onFocus:()=>m(!0),className:"w-full bg-transparent py-1.5 text-sm outline-none placeholder:text-muted-fg/60"}),n.jsx("button",{type:"button",tabIndex:-1,onClick:()=>m(S=>!S),className:"shrink-0 text-muted-fg hover:text-foreground",children:n.jsx(ms,{className:"size-4"})})]}),f&&N.length>0&&j&&Gs.createPortal(n.jsx("ul",{ref:_,style:{position:"fixed",top:j.top,left:j.left,width:j.width},className:"z-[1000] max-h-56 overflow-y-auto rounded-lg border border-border bg-popover p-1 shadow-md ring-1 ring-foreground/10",children:N.map(S=>n.jsx("li",{children:n.jsx("button",{type:"button",onMouseDown:R=>{R.preventDefault(),w(S)},className:ge("flex w-full items-center rounded-md px-2 py-1 text-left text-sm hover:bg-accent hover:text-accent-fg",S===e&&"bg-accent/50"),children:n.jsx("span",{className:"truncate font-mono text-xs",children:S})})},S))}),document.body)]})}function ur(){const{data:e,error:t,isLoading:a,mutate:o}=Be("/admin/config",()=>ai.config.get()),l=async(c,d)=>{const f=await ai.config.patch({set:c,unset:d});return await o({config:f.config},{revalidate:!1}),f.config};return{config:e?.config||{},error:t,isLoading:a,mutate:o,patch:l}}function rE(){const{data:e,error:t,isLoading:a,mutate:o}=Be("/admin/super-agent",()=>ai.superAgent());return{superAgent:e,error:t,isLoading:a,mutate:o}}const aI="modulepreload",rI=function(e){return"/"+e},Gk={},oI=function(t,a,o){let l=Promise.resolve();if(a&&a.length>0){let d=function(g){return Promise.all(g.map(h=>Promise.resolve(h).then(b=>({status:"fulfilled",value:b}),b=>({status:"rejected",reason:b}))))};document.getElementsByTagName("link");const f=document.querySelector("meta[property=csp-nonce]"),m=f?.nonce||f?.getAttribute("nonce");l=d(a.map(g=>{if(g=rI(g),g in Gk)return;Gk[g]=!0;const h=g.endsWith(".css"),b=h?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${g}"]${b}`))return;const _=document.createElement("link");if(_.rel=h?"stylesheet":aI,h||(_.as="script"),_.crossOrigin="",_.href=g,m&&_.setAttribute("nonce",m),document.head.appendChild(_),h)return new Promise((j,E)=>{_.addEventListener("load",j),_.addEventListener("error",()=>E(new Error(`Unable to preload CSS for ${g}`)))})}))}function c(d){const f=new Event("vite:preloadError",{cancelable:!0});if(f.payload=d,window.dispatchEvent(f),!f.defaultPrevented)throw d}return l.then(d=>{for(const f of d||[])f.status==="rejected"&&c(f.reason);return t().catch(c)})},lI={anthropic:"from-orange-600 to-amber-600",openai:"from-emerald-600 to-teal-600",gemini:"from-blue-600 to-indigo-600",groq:"from-cyan-600 to-teal-600",openrouter:"from-violet-600 to-indigo-600",ollama:"from-amber-600 to-orange-600",azure:"from-blue-600 to-cyan-600",mock:"from-slate-600 to-gray-600",custom:"from-slate-600 to-gray-600"},iI={anthropic:"bg-orange-500/20 text-orange-300 border border-orange-500/40",openai:"bg-emerald-500/20 text-emerald-300 border border-emerald-500/40",gemini:"bg-blue-500/20 text-blue-300 border border-blue-500/40",groq:"bg-cyan-500/20 text-cyan-300 border border-cyan-500/40",openrouter:"bg-violet-500/20 text-violet-300 border border-violet-500/40",ollama:"bg-amber-500/20 text-amber-300 border border-amber-500/40",azure:"bg-blue-500/20 text-blue-300 border border-blue-500/40",mock:"bg-slate-500/20 text-slate-300 border border-slate-500/40",custom:"bg-slate-500/20 text-slate-300 border border-slate-500/40"},Mc=[{value:"anthropic",label:"Anthropic"},{value:"openai",label:"OpenAI-compatible"},{value:"gemini",label:"Gemini"},{value:"groq",label:"Groq"},{value:"openrouter",label:"OpenRouter"},{value:"ollama",label:"Ollama"},{value:"azure",label:"Azure OpenAI"},{value:"mock",label:"Mock (test)"},{value:"custom",label:"Custom"}];function _h(e,t){return t&&t in e?e[t]:e.custom}const Pf={anthropic:sa,openai:rn,gemini:FA,groq:pi,openrouter:Zc,ollama:rS,azure:TA,mock:cx,custom:aa},Za={anthropic:{base_url:"",default_model:"claude-sonnet-5",api_key_env:"ANTHROPIC_API_KEY",known_models:["claude-opus-4-8","claude-sonnet-5","claude-haiku-4-5","claude-fable-5"]},openai:{base_url:"https://api.openai.com/v1",default_model:"gpt-5.4-mini",api_key_env:"OPENAI_API_KEY",known_models:["gpt-5.5","gpt-5.4-mini","gpt-5.4-nano","gpt-5.1","gpt-4.1-mini"]},gemini:{base_url:"https://generativelanguage.googleapis.com/v1beta/openai",default_model:"gemini-2.5-flash",api_key_env:"GEMINI_API_KEY",known_models:["gemini-3.5-flash","gemini-3.1-pro-preview","gemini-2.5-pro","gemini-2.5-flash","gemini-2.5-flash-lite"]},groq:{base_url:"https://api.groq.com/openai/v1",default_model:"openai/gpt-oss-20b",api_key_env:"GROQ_API_KEY",known_models:["openai/gpt-oss-120b","openai/gpt-oss-20b","qwen/qwen3.6-27b","groq/compound","groq/compound-mini","whisper-large-v3-turbo"]},openrouter:{base_url:"https://openrouter.ai/api/v1",default_model:"openrouter/auto",api_key_env:"OPENROUTER_API_KEY",known_models:["openrouter/auto","openrouter/free","anthropic/claude-sonnet-5","openai/gpt-5.4-mini","google/gemini-2.5-flash"]},ollama:{base_url:"http://127.0.0.1:11434",default_model:"gemma2:9b",api_key_env:"",known_models:[]},azure:{base_url:"",default_model:"",api_key_env:"AZURE_OPENAI_API_KEY",known_models:[]},mock:{base_url:"",default_model:"mock",api_key_env:"",known_models:["mock"]},custom:{base_url:"",default_model:"",api_key_env:"",known_models:[]}};let Yk=!1;async function cI(){if(!Yk)try{const{Engines:e}=await oI(async()=>{const{Engines:a}=await Promise.resolve().then(()=>dP);return{Engines:a}},[]),{presets:t}=await e.presets();for(const[a,o]of Object.entries(t||{}))a in Za&&o&&Object.assign(Za[a],o);Yk=!0}catch{}}function oE(e){const t=e.indexOf(":");return t<0?{provider:e,model:""}:{provider:e.slice(0,t),model:e.slice(t+1)}}function vh({value:e,onChange:t,providers:a}){const{provider:o,model:l}=oE(e),c=a.find(h=>h.slug===o),d=!!o&&!c,f=x.useMemo(()=>{const h=c?Za[c.engine]?.known_models||[]:[];return Array.from(new Set([...c?.default_model?[c.default_model]:[],...h]))},[c]),m=h=>{const b=a.find(j=>j.slug===h),_=b?.default_model||Za[b?.engine]?.default_model||"";t(_?`${h}:${_}`:`${h}:`)},g=h=>t(`${o}:${h}`);return n.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[n.jsx(ct,{value:o,onChange:m,placeholder:d?u("router_panel.provider_not_found",{name:o}):u("router_panel.provider_ph"),options:a.map(h=>({value:h.slug,label:h.slug,icon:Pf[h.engine]}))}),n.jsx(aE,{value:l,onChange:g,options:f,invalid:d,invalidHint:u("router_panel.provider_not_configured",{name:o})})]})}function uI(){const e=Je(),{superAgent:t,isLoading:a,mutate:o}=rE(),{config:l,patch:c}=ur(),[d,f]=x.useState(""),[m,g]=x.useState([]),[h,b]=x.useState(""),[_,j]=x.useState(null),[E,y]=x.useState(!1),[k,N]=x.useState({model:"",fallback:[]});x.useEffect(()=>{if(!t)return;const P=t.model_fallback?.models||[],B=Array.isArray(P)?P:[];f(t.model||""),g(B),N({model:t.model||"",fallback:B})},[t]);const w=x.useMemo(()=>{const P=l.engines||{};return Object.entries(P).map(([B,D])=>({slug:B,engine:D?.engine||B,default_model:D?.default_model||Za[D?.engine||B]?.default_model}))},[l.engines]),S=P=>{const{provider:B}=oE(P);return w.some(D=>D.slug===B)};if(a||!t)return n.jsx(st,{});const R=d!==k.model||JSON.stringify(m)!==JSON.stringify(k.fallback),A=async()=>{y(!0);try{await c({"super_agent.model":d,"super_agent.model_fallback.enabled":m.length>0,"super_agent.model_fallback.models":m}),e.success(u("router_panel.saved_toast")),N({model:d,fallback:m}),o()}catch(P){e.error(P.message)}finally{y(!1)}},T=()=>{const P=h.trim().replace(/:$/,"");!P||!P.includes(":")||m.includes(P)||(g([...m,P]),b(""))},z=(P,B)=>{const D=[...m];D[P]=B,g(D)},M=P=>{g(m.filter((B,D)=>D!==P)),_===P&&j(null)},L=(P,B)=>{const D=P+B;if(D<0||D>=m.length)return;const $=[...m];[$[P],$[D]]=[$[D],$[P]],g($)};return n.jsx(Ve,{title:u("router_panel.title"),description:u("router_panel.description"),children:n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-2 rounded-lg border border-border bg-muted/20 p-3",children:[n.jsxs($e,{tone:"success",children:[n.jsx(Zc,{size:11})," ",u("router_panel.badge_default")]}),n.jsx("span",{className:`font-mono text-xs ${!S(d)&&d?"text-amber-400":""}`,children:d||"—"}),m.map(P=>n.jsxs("span",{className:"flex items-center gap-2 text-muted-fg",children:[n.jsx(H2,{size:12}),n.jsx("span",{className:`font-mono text-xs ${S(P)?"":"text-amber-400"}`,children:P})]},P))]}),w.length===0?n.jsx("p",{className:"text-xs text-muted-fg",children:u("router_panel.no_providers")}):n.jsx(ie,{label:u("router_panel.active_model_label"),hint:u("router_panel.active_model_hint"),children:n.jsx(vh,{value:d,onChange:f,providers:w})}),n.jsxs("div",{className:"rounded-lg border border-border bg-muted/20 p-3",children:[n.jsxs("div",{className:"mb-2",children:[n.jsx("div",{className:"text-sm font-medium",children:u("router_panel.fallback_title")}),n.jsx("div",{className:"text-xs text-muted-fg",children:u("router_panel.fallback_desc")})]}),n.jsxs("ul",{className:"mb-3 space-y-1",children:[m.map((P,B)=>{const D=!S(P),$=_===B;return n.jsx("li",{className:"rounded-md bg-card px-2 py-1.5 text-xs",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("span",{className:"w-6 text-muted-fg",children:["#",B+1]}),$?n.jsx("div",{className:"flex-1",children:n.jsx(vh,{value:P,onChange:q=>z(B,q),providers:w})}):n.jsxs("button",{type:"button",onClick:()=>j(B),className:"flex flex-1 items-center gap-1.5 text-left",children:[D&&n.jsx(wb,{size:12,className:"text-amber-400"}),n.jsx("span",{className:`font-mono ${D?"text-amber-400":""}`,children:P})]}),$?n.jsx(re,{size:"sm",variant:"secondary",onClick:()=>j(null),children:u("router_panel.done")}):n.jsx(re,{size:"sm",variant:"ghost",onClick:()=>j(B),children:n.jsx(wa,{size:12})}),n.jsx(re,{size:"sm",variant:"ghost",onClick:()=>L(B,-1),disabled:B===0,children:"↑"}),n.jsx(re,{size:"sm",variant:"ghost",onClick:()=>L(B,1),disabled:B===m.length-1,children:"↓"}),n.jsx(re,{size:"sm",variant:"destructive",onClick:()=>M(B),children:n.jsx(_n,{size:12})})]})},`${B}-${P}`)}),m.length===0&&n.jsx("li",{className:"text-xs text-muted-fg",children:u("router_panel.fallback_empty")})]}),w.length>0&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-xs text-muted-fg",children:u("router_panel.add_to_chain")}),n.jsx(vh,{value:h,onChange:b,providers:w}),n.jsxs(re,{size:"sm",variant:"secondary",onClick:T,disabled:!h.includes(":")||h.endsWith(":"),children:[n.jsx(Dt,{size:13})," ",u("router_panel.add_to_chain")]})]})]}),n.jsx(re,{variant:"primary",loading:E,disabled:!R,onClick:A,children:u(R?"router_panel.save":"router_panel.saved")})]})})}const dI=[{model:"openai:gpt-4o",when:{has_image:!0}},{model:"anthropic:claude-3-5-haiku",when:{max_prompt_chars:400}}];function fI({when:e}){const t=[];return!e||Object.keys(e).length===0?t.push({icon:n.jsx(Zr,{size:11}),label:u("routing_panel.when_any")}):(e.has_image===!0&&t.push({icon:n.jsx(ux,{size:11}),label:u("routing_panel.when_image")}),e.has_image===!1&&t.push({icon:n.jsx(ux,{size:11}),label:u("routing_panel.when_no_image")}),Number.isFinite(e.min_prompt_chars)&&t.push({icon:n.jsx(Yg,{size:11}),label:u("routing_panel.when_min_prompt",{n:String(e.min_prompt_chars)})}),Number.isFinite(e.max_prompt_chars)&&t.push({icon:n.jsx(Yg,{size:11}),label:u("routing_panel.when_max_prompt",{n:String(e.max_prompt_chars)})}),Number.isFinite(e.min_context_chars)&&t.push({icon:n.jsx(Yg,{size:11}),label:u("routing_panel.when_min_context",{n:String(e.min_context_chars)})}),Array.isArray(e.channels)&&e.channels.length>0&&t.push({icon:n.jsx(fM,{size:11}),label:u("routing_panel.when_channels",{list:e.channels.join(", ")})}),Array.isArray(e.keywords)&&e.keywords.length>0&&t.push({icon:n.jsx(KA,{size:11}),label:u("routing_panel.when_keywords",{list:e.keywords.join(", ")})})),n.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:t.map((a,o)=>n.jsxs("span",{className:"inline-flex items-center gap-1 rounded bg-muted px-1.5 py-0.5 text-[11px] text-muted-fg",children:[a.icon," ",a.label]},o))})}function pI(){const e=Je(),{config:t,isLoading:a,patch:o}=ur(),[l,c]=x.useState(!1),[d,f]=x.useState("[]"),[m,g]=x.useState(!1),[h,b]=x.useState(!1),[_,j]=x.useState(!1),[E,y]=x.useState({enabled:!1,rulesText:"[]"});x.useEffect(()=>{const M=t.super_agent?.routing||{},L=Array.isArray(M.rules)?M.rules:[],P=JSON.stringify(L,null,2);c(M.enabled===!0),f(P),y({enabled:M.enabled===!0,rulesText:P})},[t.super_agent?.routing]);const k=x.useMemo(()=>{try{const M=JSON.parse(d);return Array.isArray(M)?{rules:M,error:null}:{rules:[],error:u("routing_panel.json_not_array")}}catch(M){return{rules:[],error:u("routing_panel.json_error",{msg:M.message})}}},[d]);if(a)return n.jsx(st,{});const N=k.rules,w=N.length,S=k.error?d:JSON.stringify(N),R=(()=>{try{return JSON.stringify(JSON.parse(E.rulesText))}catch{return E.rulesText}})(),A=l!==E.enabled||S!==R,T=async()=>{if(!k.error){b(!0);try{await o({"super_agent.routing":{enabled:l,rules:N}}),e.success(u("routing_panel.saved_toast"));const M=JSON.stringify(N,null,2);f(M),y({enabled:l,rulesText:M})}catch(M){e.error(M.message)}finally{b(!1),j(!1)}}},z=l&&w>0;return n.jsxs("div",{"data-testid":"routing-panel",children:[n.jsx(Ve,{title:u("routing_panel.title"),description:u("routing_panel.description"),children:n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-2 rounded-lg border border-border bg-muted/20 p-3",children:[n.jsx("span",{"data-testid":"routing-signal",children:z?n.jsxs($e,{tone:"success",children:[n.jsx(Gg,{size:11})," ",u("routing_panel.signal_on",{n:String(w)})]}):l?n.jsxs($e,{tone:"warning",children:[n.jsx(Gg,{size:11})," ",u("routing_panel.signal_on_empty")]}):n.jsxs($e,{tone:"muted",children:[n.jsx(Gg,{size:11})," ",u("routing_panel.signal_off")]})}),n.jsx(qe,{content:u("routing_panel.helper"),children:n.jsx("span",{className:"text-xs text-muted-fg underline decoration-dotted underline-offset-2",children:u("routing_panel.how_it_works")})})]}),n.jsx(Bt,{checked:l,onChange:c,label:u("routing_panel.enable_label")}),n.jsxs("div",{className:"rounded-lg border border-border bg-muted/20 p-3",children:[n.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium",children:u("routing_panel.rules_title")}),n.jsx("div",{className:"text-xs text-muted-fg",children:u("routing_panel.rules_desc")})]}),n.jsx(re,{size:"sm",variant:"secondary",onClick:()=>g(M=>!M),children:u(m?"routing_panel.hide_editor":"routing_panel.edit_rules")})]}),n.jsxs("ul",{className:"space-y-1.5",children:[N.map((M,L)=>n.jsxs("li",{className:"rounded-md bg-card px-2.5 py-2 text-xs",children:[n.jsxs("div",{className:"mb-1 flex items-center gap-2",children:[n.jsxs("span",{className:"w-6 text-muted-fg",children:["#",L+1]}),n.jsx("span",{className:"font-mono text-[12px]",children:M.model||"—"})]}),n.jsx("div",{className:"pl-8",children:n.jsx(fI,{when:M.when})})]},L)),w===0&&!k.error&&n.jsx("li",{className:"text-xs text-muted-fg",children:u("routing_panel.rules_empty")})]})]}),m&&n.jsxs(ie,{label:u("routing_panel.editor_label"),hint:u("routing_panel.json_hint"),children:[n.jsx(un,{rows:10,className:"font-mono text-xs",value:d,onChange:M=>f(M.target.value),spellCheck:!1}),k.error?n.jsx("span",{className:"mt-1 block text-[11px] text-red-400",children:k.error}):n.jsx("button",{type:"button",className:"mt-1 text-[11px] text-muted-fg underline decoration-dotted underline-offset-2",onClick:()=>f(JSON.stringify(dI,null,2)),children:u("routing_panel.insert_example")})]}),n.jsx("p",{className:"text-[11px] leading-relaxed text-muted-fg",children:u("routing_panel.helper")}),n.jsx(re,{variant:"primary",loading:h,disabled:!A||!!k.error,onClick:()=>j(!0),children:u(A?"routing_panel.save":"routing_panel.saved")})]})}),n.jsx(Xt,{open:_,onClose:()=>j(!1),title:u("routing_panel.confirm_title"),description:u("routing_panel.confirm_body"),footer:n.jsxs(n.Fragment,{children:[n.jsx(re,{variant:"ghost",onClick:()=>j(!1),children:u("routing_panel.cancel")}),n.jsx(re,{variant:"primary",loading:h,onClick:T,children:u("routing_panel.confirm_apply")})]}),children:n.jsx("p",{className:"text-sm text-muted-fg",children:l?u("routing_panel.confirm_on",{n:String(w)}):u("routing_panel.confirm_off")})})]})}function mI({provider:e,onEdit:t,onDelete:a,onToggle:o}){const l=_h(lI,e.engine),c=_h(iI,e.engine),d=_h(Pf,e.engine),f=Mc.find(b=>b.value===e.engine)?.label||e.engine,m=typeof e.api_key=="string"&&e.api_key.length>0,g=Po(e.api_key),h=e.is_active!==!1;return n.jsxs("div",{className:"group flex h-full cursor-pointer flex-col gap-3 rounded-xl border border-border bg-card p-4 transition-colors hover:border-muted-fg/50",onClick:t,children:[n.jsxs("div",{className:"flex items-start gap-3",children:[n.jsx("div",{className:ge("flex size-10 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br",l),children:n.jsx(d,{className:"size-5 text-white"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("h3",{className:"truncate text-sm font-semibold",children:e.name||e.slug}),n.jsx("p",{className:"truncate font-mono text-[10px] text-muted-fg",children:e.slug}),n.jsxs("span",{className:ge("mt-1 inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-medium",c),children:[n.jsx(d,{className:"size-3"})," ",f]})]}),n.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[n.jsx(qe,{content:u(h?"providers_modal.toggle_active":"providers_modal.toggle_inactive"),children:n.jsxs("button",{type:"button",onClick:b=>{b.stopPropagation(),o()},className:ge("flex items-center gap-1 rounded-md border px-1.5 py-0.5 text-[10px] font-medium transition-colors",h?"border-emerald-500/40 text-emerald-400 hover:bg-emerald-500/10":"border-border text-muted-fg hover:text-foreground"),children:[n.jsx("span",{className:ge("size-1.5 rounded-full",h?"bg-emerald-400":"bg-muted-fg/40")}),u(h?"providers_card.active":"providers_card.off")]})}),n.jsx(qe,{content:u("providers_modal.delete"),children:n.jsx("button",{type:"button",onClick:b=>{b.stopPropagation(),a()},className:"rounded-md p-1 text-muted-fg hover:bg-destructive/10 hover:text-destructive",children:n.jsx(_n,{className:"size-3.5"})})})]})]}),n.jsxs("div",{className:"mt-auto space-y-1 text-xs",children:[n.jsx(hc,{label:u("providers_card.model"),value:e.default_model||"—",mono:!0}),e.base_url&&n.jsx(hc,{label:u("providers_card.base_url"),value:e.base_url,mono:!0,truncate:!0}),n.jsx(hc,{label:u("providers_card.api_key"),value:m?g?`…${g}`:u("providers_card.key_set"):"—",mono:!!g}),e.default_temperature!==void 0&&n.jsx(hc,{label:u("providers_card.temp"),value:e.default_temperature.toFixed(1)}),e.pricing?.input_per_million!==void 0&&n.jsx(hc,{label:u("providers_card.price_io"),value:`${e.pricing.input_per_million??0} / ${e.pricing.output_per_million??0}`})]})]})}function hc({label:e,value:t,mono:a,truncate:o}){return n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("span",{className:"text-muted-fg",children:e}),n.jsx("span",{className:ge("text-foreground",a&&"font-mono",o&&"max-w-[180px] truncate"),children:t})]})}const Kk={name:"",slug:"",engine:"anthropic",base_url:"",api_key_value:"",default_model:"",default_temperature:.7,default_max_tokens:4096,is_active:!0,context_limit_tokens:2e5,model_context_limits_json:"",p_input:"",p_output:"",p_cache_read:"",p_cache_write:""},gI=["anthropic","openai","gemini","groq","openrouter","ollama","custom"];function xc(e){return e.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Ud(e){if(e==null)return"";const t=Number(e);return Number.isFinite(t)?String(t):""}function hI(e){return{name:e.name||e.slug,slug:e.slug,engine:e.engine||"custom",base_url:e.base_url||"",api_key_value:"",default_model:e.default_model||"",default_temperature:e.default_temperature??.7,default_max_tokens:e.default_max_tokens??4096,is_active:e.is_active!==!1,context_limit_tokens:e.context_limit_tokens??2e5,model_context_limits_json:e.model_context_limits?JSON.stringify(e.model_context_limits,null,2):"",p_input:Ud(e.pricing?.input_per_million),p_output:Ud(e.pricing?.output_per_million),p_cache_read:Ud(e.pricing?.cache_read_per_million),p_cache_write:Ud(e.pricing?.cache_write_per_million)}}function xI({open:e,initial:t,existingSlugs:a,onClose:o,onSave:l}){const c=!!t,[d,f]=x.useState(Kk),[m,g]=x.useState(!1),[h,b]=x.useState(null),[_,j]=x.useState([]),[E,y]=x.useState(!1),[k,N]=x.useState(null),[w,S]=x.useState(!1),[R,A]=x.useState("");x.useEffect(()=>{if(!e)return;const Q=t?hI(t):Kk;f(Q),b(null),N(null),S(!1);const W=Za[Q.engine];j(W?.known_models||[])},[e,t]);const T=Q=>f(W=>({...W,...Q})),z=Q=>{const W=Za[Q];T({engine:Q,name:Q==="custom"?d.name:Mc.find(I=>I.value===Q)?.label||Q,slug:Q==="custom"?d.slug:Q,base_url:W.base_url,default_model:W.default_model}),j(W.known_models),N(null)},M=Q=>{const W=Za[Q];T({engine:Q,base_url:d.base_url||W.base_url,default_model:d.default_model||W.default_model}),j(W.known_models)},L=async()=>{y(!0),N(null);try{const Q=await Hc.models({engine:d.engine,slug:d.slug||xc(d.name),base_url:d.base_url||void 0,api_key:d.api_key_value||void 0});if(Q.error){N(Q.error);return}j(Q.models),Q.models.length===0&&N(u("providers_modal.err_no_models"))}catch(Q){N(Q.message||u("providers_modal.err_list_models"))}finally{y(!1)}},P=x.useMemo(()=>d.default_model&&!_.includes(d.default_model)?[d.default_model,..._]:_,[_,d.default_model]),B=()=>{const Q=(d.slug||xc(d.name)).trim();if(!Q)return b(u("providers_modal.err_slug_required")),null;if(!c&&a.includes(Q))return b(u("providers_modal.err_slug_exists",{slug:Q})),null;let W;if(d.model_context_limits_json.trim())try{const ee=JSON.parse(d.model_context_limits_json);if(!ee||typeof ee!="object"||Array.isArray(ee))throw new Error;W=ee}catch{return b(u("providers_modal.err_model_limits_json")),null}const K=[d.p_input,d.p_output,d.p_cache_read,d.p_cache_write].map(ee=>ee.trim()).some(Boolean)?{input_per_million:Number(d.p_input||0),output_per_million:Number(d.p_output||0),cache_read_per_million:Number(d.p_cache_read||0),cache_write_per_million:Number(d.p_cache_write||0)}:void 0;return{provider:{slug:Q,name:d.name.trim()||Q,engine:d.engine,base_url:d.base_url.trim()||void 0,default_model:d.default_model.trim()||void 0,default_temperature:d.default_temperature,default_max_tokens:d.default_max_tokens,is_active:d.is_active,context_limit_tokens:d.context_limit_tokens||void 0,model_context_limits:W,pricing:K},modelLimits:W}},D=()=>{const Q=B();if(!Q)return;const{provider:W}=Q,I={name:W.name,engine:W.engine,is_active:W.is_active!==!1,default_temperature:W.default_temperature,default_max_tokens:W.default_max_tokens};W.base_url&&(I.base_url=W.base_url),W.default_model&&(I.default_model=W.default_model),W.context_limit_tokens&&(I.context_limit_tokens=W.context_limit_tokens),W.model_context_limits&&(I.model_context_limits=W.model_context_limits),W.pricing&&(I.pricing=W.pricing),d.api_key_value.trim()&&(I.api_key=d.api_key_value.trim()),A(JSON.stringify(I,null,2)),b(null),S(!0)},$=async()=>{g(!0),b(null);try{if(w){const W=(d.slug||xc(d.name)).trim();if(!W){b(u("providers_modal.err_slug_required_form"));return}let I;try{I=JSON.parse(R)}catch{b(u("providers_modal.err_json_invalid"));return}if(!I||typeof I!="object"||Array.isArray(I)){b(u("providers_modal.err_json_object"));return}const K=I;if(!K.engine||typeof K.engine!="string"){b(u("providers_modal.err_engine_missing"));return}const ee={slug:W,name:typeof K.name=="string"?K.name:W,engine:String(K.engine),base_url:typeof K.base_url=="string"?K.base_url:void 0,default_model:typeof K.default_model=="string"?K.default_model:void 0,is_active:K.is_active!==!1};await l({provider:ee,raw:K,originalSlug:t?.slug}),o();return}const Q=B();if(!Q)return;await l({provider:Q.provider,apiKeyValue:d.api_key_value.trim()||void 0,originalSlug:t?.slug}),o()}catch(Q){b(Q.message||u("providers_modal.err_save"))}finally{g(!1)}},q=c&&ps(t?.api_key),G=Po(t?.api_key),U=q?u("providers_modal.api_key_set",{suffix:G??""}):"sk-…",V=d.engine==="ollama",X=Za[d.engine]?.api_key_env;return n.jsx(Xt,{open:e,onClose:o,title:c?u("providers_modal.edit_title",{name:t?.name||t?.slug||""}):u("providers_modal.new_title"),description:u("providers_modal.description"),size:"lg",footer:n.jsxs(n.Fragment,{children:[n.jsx(re,{variant:"ghost",onClick:o,disabled:m,children:u("common.cancel")}),n.jsx(re,{variant:"primary",onClick:$,loading:m,children:u(c?"common.save":"common.create")})]}),children:n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[c?n.jsx("span",{}):n.jsx("div",{className:"flex flex-wrap gap-1.5",children:gI.map(Q=>{const W=Pf[Q],I=Q==="custom"?u("providers_modal.custom"):Mc.find(ee=>ee.value===Q)?.label||Q,K=d.engine===Q;return n.jsxs("button",{type:"button",onClick:()=>z(Q),className:`flex items-center gap-1.5 rounded-lg border px-2.5 py-1 text-xs transition-colors ${K?"border-emerald-500/50 bg-emerald-500/10 text-emerald-400":"border-border text-muted-fg hover:border-muted-fg/60 hover:text-foreground"}`,children:[n.jsx(W,{className:"size-3.5"})," ",I]},Q)})}),n.jsxs("button",{type:"button",onClick:()=>w?S(!1):D(),className:`flex shrink-0 items-center gap-1.5 rounded-lg border px-2.5 py-1 text-xs transition-colors ${w?"border-sky-500/50 bg-sky-500/10 text-sky-400":"border-border text-muted-fg hover:text-foreground"}`,children:[n.jsx(yA,{className:"size-3.5"})," ",u(w?"providers_modal.form_mode":"providers_modal.json_mode")]})]}),w?n.jsxs("div",{className:"space-y-2",children:[n.jsx(ie,{label:u("providers_modal.json_label"),hint:u("providers_modal.json_hint",{slug:d.slug||xc(d.name)||"<slug>"}),children:n.jsx(un,{rows:14,className:"font-mono text-xs",value:R,onChange:Q=>A(Q.target.value),spellCheck:!1})}),n.jsx("p",{className:"text-[11px] text-muted-fg",children:u("providers_modal.json_help")})]}):n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsx(ie,{label:u("providers_modal.name_label"),children:n.jsx(Ee,{value:d.name,onChange:Q=>T({name:Q.target.value,slug:c?d.slug:xc(Q.target.value)}),placeholder:u("providers_modal.name_ph")})}),n.jsx(ie,{label:u("providers_modal.engine_label"),children:n.jsx(ct,{value:d.engine,onChange:Q=>M(Q),options:Mc.map(Q=>({value:Q.value,label:Q.label,icon:Pf[Q.value]}))})})]}),n.jsx(ie,{label:u("providers_modal.base_url_label"),hint:u("providers_modal.base_url_hint"),children:n.jsx(Ee,{value:d.base_url,onChange:Q=>T({base_url:Q.target.value}),placeholder:u("providers_modal.base_url_ph")})}),!V&&n.jsx(ie,{label:u("providers_modal.api_key_label"),hint:q?u("providers_modal.api_key_hint_existing"):X?u("providers_modal.api_key_hint_env",{env:X}):u("providers_modal.api_key_hint"),children:n.jsx(Ee,{type:"password",autoComplete:"new-password",value:d.api_key_value,onChange:Q=>T({api_key_value:Q.target.value}),placeholder:U})}),n.jsx(ie,{label:u("providers_modal.model_label"),children:n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx(aE,{value:d.default_model,onChange:Q=>T({default_model:Q}),options:P,className:"flex-1"}),n.jsx(qe,{content:u("providers_modal.list_models_hint"),children:n.jsxs(re,{size:"sm",variant:"secondary",onClick:L,disabled:E,"aria-label":u("providers_modal.list_models_hint"),children:[E?n.jsx(Js,{className:"size-3.5 animate-spin"}):n.jsx(Cs,{className:"size-3.5"}),u("providers_modal.load_models")]})})]}),k&&n.jsx("p",{className:"text-[11px] text-amber-400",children:k})]})}),n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsx(ie,{label:u("providers_modal.max_tokens_label"),children:n.jsx(Ee,{type:"number",min:256,step:256,value:d.default_max_tokens,onChange:Q=>T({default_max_tokens:parseInt(Q.target.value)||4096})})}),n.jsx(ie,{label:u("providers_modal.temperature_label",{value:d.default_temperature.toFixed(1)}),children:n.jsx("input",{type:"range",min:0,max:2,step:.1,value:d.default_temperature,onChange:Q=>T({default_temperature:parseFloat(Q.target.value)}),className:"mt-2 w-full accent-foreground"})})]}),n.jsxs("details",{className:"rounded-md border border-border bg-muted/20 p-3",children:[n.jsx("summary",{className:"cursor-pointer text-xs font-medium text-muted-fg",children:u("providers_modal.pricing_summary")}),n.jsxs("div",{className:"mt-3 space-y-3",children:[n.jsx(ie,{label:u("providers_modal.context_limit_label"),children:n.jsx(Ee,{type:"number",min:0,step:1024,value:d.context_limit_tokens,onChange:Q=>T({context_limit_tokens:parseInt(Q.target.value)||0})})}),n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsx(ie,{label:u("providers_modal.price_input"),children:n.jsx(Ee,{type:"number",min:0,step:1e-4,value:d.p_input,onChange:Q=>T({p_input:Q.target.value}),placeholder:"0.15"})}),n.jsx(ie,{label:u("providers_modal.price_output"),children:n.jsx(Ee,{type:"number",min:0,step:1e-4,value:d.p_output,onChange:Q=>T({p_output:Q.target.value}),placeholder:"0.60"})}),n.jsx(ie,{label:u("providers_modal.price_cache_read"),children:n.jsx(Ee,{type:"number",min:0,step:1e-4,value:d.p_cache_read,onChange:Q=>T({p_cache_read:Q.target.value}),placeholder:"0.03"})}),n.jsx(ie,{label:u("providers_modal.price_cache_write"),children:n.jsx(Ee,{type:"number",min:0,step:1e-4,value:d.p_cache_write,onChange:Q=>T({p_cache_write:Q.target.value}),placeholder:"0.00"})})]}),n.jsx(ie,{label:u("providers_modal.model_limits_label"),hint:'{"gpt-4o-mini":128000}',children:n.jsx(un,{rows:3,className:"font-mono text-xs",value:d.model_context_limits_json,onChange:Q=>T({model_context_limits_json:Q.target.value})})})]})]}),n.jsx(Bt,{checked:d.is_active,onChange:Q=>T({is_active:Q}),label:u("providers_modal.active_label")})]}),h&&n.jsx("div",{className:"rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:h})]})})}const bI=new Set(Mc.map(e=>e.value));function _I(e,t){const a=typeof t.engine=="string"&&t.engine||(bI.has(e)?e:"custom");return{slug:e,name:typeof t.name=="string"?t.name:void 0,engine:a,base_url:typeof t.base_url=="string"?t.base_url:void 0,api_key:typeof t.api_key=="string"?t.api_key:void 0,default_model:typeof t.default_model=="string"?t.default_model:void 0,default_temperature:typeof t.default_temperature=="number"?t.default_temperature:void 0,default_max_tokens:typeof t.default_max_tokens=="number"?t.default_max_tokens:void 0,is_active:typeof t.is_active=="boolean"?t.is_active:void 0,context_limit_tokens:typeof t.context_limit_tokens=="number"?t.context_limit_tokens:void 0,model_context_limits:t.model_context_limits||void 0,pricing:t.pricing||void 0}}function vI(){const e=Je(),{config:t,isLoading:a,patch:o,mutate:l}=ur(),[c,d]=x.useState(!1),[f,m]=x.useState(null);if(a)return n.jsx(st,{});const g=t.engines||{},h=Object.entries(g).map(([N,w])=>_I(N,w||{})),b=h.map(N=>N.slug),_=()=>{m(null),d(!0)},j=N=>{m(N),d(!0)},E=async({provider:N,apiKeyValue:w,raw:S})=>{if(S){await o({[`engines.${N.slug}`]:S}),e.success(u("engines_panel.saved_json")),l();return}const R=`engines.${N.slug}`,A={[`${R}.name`]:N.name,[`${R}.engine`]:N.engine,[`${R}.is_active`]:N.is_active!==!1,[`${R}.default_temperature`]:N.default_temperature,[`${R}.default_max_tokens`]:N.default_max_tokens},T=[],z=(M,L)=>{L===void 0||L===""?T.push(`${R}.${M}`):A[`${R}.${M}`]=L};z("base_url",N.base_url),z("default_model",N.default_model),z("context_limit_tokens",N.context_limit_tokens),z("pricing",N.pricing),z("model_context_limits",N.model_context_limits),w&&(A[`${R}.api_key`]=w),await o(A,T),e.success(u("engines_panel.saved")),l()},y=async N=>{try{await o({[`engines.${N.slug}.is_active`]:N.is_active===!1}),l()}catch(w){e.error(w.message)}},k=async N=>{if(confirm(u("engines_panel.delete_confirm",{name:N.name||N.slug})))try{await o(void 0,[`engines.${N.slug}`]),e.success(u("engines_panel.deleted")),l()}catch(w){e.error(w.message)}};return n.jsxs(Ve,{title:u("engines_panel.title"),description:u("engines_panel.description"),action:n.jsxs(re,{size:"sm",variant:"primary",onClick:_,children:[n.jsx(Dt,{size:14})," ",u("engines_panel.new_btn")]}),children:[h.length===0?n.jsx(ft,{children:u("engines_panel.empty")}):n.jsxs("div",{className:"grid grid-cols-1 items-stretch gap-3 sm:grid-cols-2 lg:grid-cols-3",children:[h.map(N=>n.jsx(mI,{provider:N,onEdit:()=>j(N),onDelete:()=>k(N),onToggle:()=>y(N)},N.slug)),n.jsxs("button",{type:"button",onClick:_,className:"flex min-h-[120px] flex-col items-center justify-center gap-2 rounded-xl border border-dashed border-border text-muted-fg transition-colors hover:border-muted-fg/60 hover:text-foreground",children:[n.jsx(Dt,{size:20}),n.jsx("span",{className:"text-sm font-medium",children:u("engines_panel.add_card")})]})]}),n.jsx(xI,{open:c,initial:f,existingSlugs:b,onClose:()=>{d(!1),m(null)},onSave:E})]})}function lE(){return n.jsxs("div",{className:"space-y-6",children:[n.jsx(uI,{}),n.jsx(pI,{}),n.jsx(vI,{})]})}function yI(){const e=Je(),[t,a]=x.useState(!1),l=Be(t?"/agents/vault?include_removed=1":"/agents/vault",()=>an.vault({includeRemoved:t})),c=l.data||[],[d,f]=x.useState(null),m=async h=>{const b=h.source!=="user",_=b?u("base.defaults_tombstone_msg",{slug:h.slug}):u("base.defaults_delete_msg",{slug:h.slug});if(confirm(_))try{await an.vaultRemove(h.slug),e.success(u(b?"base.defaults_hidden":"base.defaults_deleted")),l.mutate()}catch(j){e.error(j.message)}},g=async h=>{try{await an.vaultRestore(h),e.success(u("base.defaults_restored")),l.mutate()}catch(b){e.error(b.message)}};return n.jsxs(Ve,{title:u("base.defaults_title"),description:u("base.defaults_desc"),action:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Bt,{checked:t,onChange:a,label:u("base.defaults_show_removed")}),n.jsxs(re,{size:"sm",onClick:()=>f("new"),children:[n.jsx(Dt,{size:14})," ",u("base.defaults_new")]})]}),children:[l.isLoading&&n.jsx(st,{}),!l.isLoading&&c.length===0&&n.jsx(ft,{children:u("base.defaults_empty")}),n.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:c.map(h=>{const b=t&&h.tombstoned;return n.jsxs("div",{className:`flex flex-col gap-2 rounded-xl border bg-card p-4 ${b?"border-dashed border-border opacity-60":"border-border"}`,children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[n.jsx("div",{className:"flex size-9 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-slate-600 to-gray-600",children:h.is_master?n.jsx(va,{className:"size-4 text-white"}):n.jsx(rn,{className:"size-4 text-white"})}),n.jsx("span",{className:"truncate text-sm font-semibold",children:h.slug}),n.jsx(jI,{source:h.source})]}),n.jsx("div",{className:"flex shrink-0 items-center gap-0.5",children:b?n.jsx(yh,{label:u("base.defaults_restore"),onClick:()=>g(h.slug),variant:"secondary",children:n.jsx(fi,{size:13})}):n.jsxs(n.Fragment,{children:[n.jsx(yh,{label:u("base.defaults_edit"),onClick:()=>f(h),variant:"ghost",children:n.jsx(wa,{size:13})}),n.jsx(yh,{label:h.source==="user"?u("base.defaults_delete"):u("base.defaults_hide"),onClick:()=>m(h),variant:"ghost-destructive",children:n.jsx(_n,{size:13})})]})})]}),h.model?n.jsx($e,{tone:"info",children:h.model}):n.jsx("span",{className:"text-[10px] text-muted-fg",children:u("agents_ui.model_router_default")}),h.description&&n.jsx("p",{className:"line-clamp-3 text-xs text-muted-fg",children:h.description}),n.jsxs("div",{className:"flex flex-wrap gap-1",children:[h.role&&n.jsx($e,{children:h.role}),h.skills?.map(_=>n.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded bg-muted px-1 py-0.5 text-[9px] text-muted-fg",children:[n.jsx(sa,{size:9})," ",_]},_)),h.tools?.map(_=>n.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded bg-muted px-1 py-0.5 text-[9px] text-muted-fg",children:[n.jsx(aa,{size:9})," ",_]},_))]})]},h.slug)})}),d!==null&&n.jsx(kI,{agent:d==="new"?null:d,onClose:()=>f(null),onSaved:()=>{f(null),l.mutate()}})]})}function jI({source:e}){return e==="user"?n.jsx($e,{tone:"success",children:u("agents_ui.source_user")}):e==="user-override"?n.jsx($e,{tone:"warning",children:u("agents_ui.source_override")}):n.jsx($e,{tone:"muted",children:u("agents_ui.source_bundled")})}function yh({label:e,onClick:t,variant:a="ghost",children:o}){const l="inline-flex size-7 items-center justify-center rounded-md transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40",c={ghost:"text-muted-fg hover:bg-accent hover:text-accent-fg","ghost-destructive":"text-muted-fg hover:bg-destructive/15 hover:text-destructive",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80"};return n.jsxs(m_,{children:[n.jsx(g_,{render:n.jsx("button",{type:"button",onClick:t,"aria-label":e,className:`${l} ${c[a]}`,children:o})}),n.jsx(h_,{children:e})]})}function kI({agent:e,onClose:t,onSaved:a}){const o=Je(),[l,c]=x.useState(!1),d=!e,[f,m]=x.useState(e?.slug??""),[g,h]=x.useState(e?.role??""),[b,_]=x.useState(e?.model??""),[j,E]=x.useState(e?.description??""),[y,k]=x.useState(e?.language??"es"),[N,w]=x.useState((e?.skills??[]).join(", ")),[S,R]=x.useState((e?.tools??[]).join(", ")),[A,T]=x.useState(!!e?.is_master),[z,M]=x.useState(e?.body??""),L=async()=>{const P={role:g||void 0,model:b||void 0,description:j||void 0,language:y||void 0,skills:N,tools:S,is_master:A};c(!0);try{if(d){if(!/^[a-z][a-z0-9_-]*$/.test(f))throw new Error(u("base.defaults_slug_invalid"));await an.vaultCreate(f,P,z),o.success(u("base.defaults_created",{slug:f}))}else await an.vaultPatch(e.slug,{fields:P,body:z}),o.success(u("base.defaults_saved",{slug:e.slug}));a()}catch(B){o.error(B.message)}finally{c(!1)}};return n.jsx(Xt,{open:!0,onClose:t,title:d?u("base.defaults_new_title"):u("base.defaults_edit_title",{slug:e.slug}),description:d?u("base.defaults_new_desc"):e.source==="bundled"?u("base.defaults_bundled_desc"):u("base.defaults_user_desc"),size:"lg",footer:n.jsxs(n.Fragment,{children:[n.jsx(re,{variant:"ghost",onClick:t,disabled:l,children:u("common.cancel")}),n.jsx(re,{variant:"primary",onClick:L,loading:l,children:u("common.save")})]}),children:n.jsxs("div",{className:"space-y-3",children:[d&&n.jsx(ie,{label:"slug",hint:u("agents_ui.slug_kebab_hint"),children:n.jsx(Ee,{autoFocus:!0,value:f,onChange:P=>m(P.target.value),placeholder:"reviewer"})}),n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsx(ie,{label:"role",children:n.jsx(Ee,{value:g,onChange:P=>h(P.target.value),placeholder:"Code reviewer"})}),n.jsx(ie,{label:"model",children:n.jsx(Ee,{value:b,onChange:P=>_(P.target.value),placeholder:"openrouter:..."})}),n.jsx(ie,{label:"language",children:n.jsx(Ee,{value:y,onChange:P=>k(P.target.value),placeholder:"es"})}),n.jsx(ie,{label:"is_master",children:n.jsx("div",{className:"flex h-9 items-center",children:n.jsx(Bt,{checked:A,onChange:T,label:u("base.defaults_master_label")})})})]}),n.jsx(ie,{label:"description",children:n.jsx(Ee,{value:j,onChange:P=>E(P.target.value)})}),n.jsx(ie,{label:"skills",hint:u("agents_ui.comma_separated"),children:n.jsx(Ee,{value:N,onChange:P=>w(P.target.value),placeholder:"code-review, git"})}),n.jsx(ie,{label:"tools",hint:u("agents_ui.comma_separated"),children:n.jsx(Ee,{value:S,onChange:P=>R(P.target.value),placeholder:"read, write, run"})}),n.jsx(ie,{label:"body",hint:u("agents_ui.body_hint"),children:n.jsx(un,{value:z,onChange:P=>M(P.target.value),rows:10,placeholder:"# Mission\\n..."})})]})})}const wI=20,Xk=[10,20,50,100];function F_({key:e,fetchPage:t,resetKey:a,initialPageSize:o=wI,swr:l}){const[c,d]=x.useState(1),[f,m]=x.useState(o);x.useEffect(()=>{d(1)},[a]);const g=(c-1)*f,h=Be(e==null?null:[e,f,g],()=>t(f,g),{keepPreviousData:!0,...l}),b=h.data?.total??0,_=Math.max(1,Math.ceil(b/f)),j=Math.min(c,_);x.useEffect(()=>{c!==j&&d(j)},[c,j]);const E=b===0?0:g,y=Math.min(g+f,b);return{items:h.data?.items??[],isLoading:h.isLoading,error:h.error,mutate:h.mutate,page:j,pageCount:_,total:b,start:E,end:y,pageSize:f,setPage:d,setPageSize:k=>{m(k),d(1)}}}function SI({page:e,pageCount:t,total:a,start:o,end:l,pageSize:c,onPage:d,onPageSize:f}){return a<=Xk[0]?null:n.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-3 text-xs text-muted-fg",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("span",{className:"tabular-nums",children:u("common.pager_range",{from:o+1,to:l,total:a})}),n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx("span",{children:u("common.pager_per_page")}),n.jsx("div",{className:"w-[4.5rem]",children:n.jsx(ct,{value:String(c),onChange:m=>f(Number(m)),options:Xk.map(m=>({value:String(m),label:String(m)}))})})]})]}),n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx(re,{size:"sm",variant:"ghost",disabled:e<=1,onClick:()=>d(e-1),"aria-label":u("common.pager_prev"),children:n.jsx(wA,{size:14})}),n.jsx("span",{className:"px-1 tabular-nums",children:u("common.pager_page",{page:e,total:t})}),n.jsx(re,{size:"sm",variant:"ghost",disabled:e>=t,onClick:()=>d(e+1),"aria-label":u("common.pager_next"),children:n.jsx(Zr,{size:14})})]})]})}function G_({paged:e,fullHeight:t,className:a,children:o}){const l=n.jsx(SI,{page:e.page,pageCount:e.pageCount,total:e.total,start:e.start,end:e.end,pageSize:e.pageSize,onPage:e.setPage,onPageSize:e.setPageSize});return t?n.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",children:[n.jsx("div",{className:ge("min-h-0 flex-1 overflow-y-auto",a),children:o}),n.jsx("div",{className:"shrink-0",children:l})]}):n.jsxs("div",{className:a,children:[o,l]})}const CI={apx:"success",claude:"info",codex:"warning"};function NI({pid:e}={}){const t=Je(),a=yp(),o=!e||String(e)==="0",{project:l}=cu(o?"":e),c=o?void 0:l?.path||void 0,[d,f]=x.useState(""),[m,g]=x.useState(""),[h,b]=x.useState(""),[_,j]=x.useState(!1);x.useEffect(()=>{const R=setTimeout(()=>b(m.trim()),350);return()=>clearTimeout(R)},[m]);const E=F_({key:`/sessions?engine=${d}&q=${h}&deep=${_?1:0}&cwd=${c||""}`,fetchPage:(R,A)=>cP.page({engine:d||void 0,q:h||void 0,deep:_,cwd:c,limit:R,offset:A}),resetKey:`${d}|${h}|${_?1:0}|${c||""}`}),y=()=>{g(""),b(""),f(""),j(!1)},k=async R=>{try{await navigator.clipboard.writeText(`apx session resume ${R.id} --continue`),t.success(u("base.sessions_cmd_copied"))}catch{t.error(u("base.sessions_copy_failed"))}},N=R=>{const A=`Continue this session: ${R.id} (engine: ${R.engine}${R.title?`, title: "${R.title}"`:""}${R.cwd?`, folder: ${R.cwd}`:""}). With these instructions: `;window.dispatchEvent(new CustomEvent("apx:roby-prompt",{detail:{prompt:A}}))},w=async R=>{if(!R.cwd){t.error(u("base.sessions_no_folder"));return}try{await gN.exec({kind:"open_path",target:R.cwd})}catch(A){t.error(u("base.sessions_folder_failed",{msg:A.message}))}},S=async R=>{const A=R.path||R.cwd;if(!A){t.error(u("base.sessions_no_path"));return}try{await navigator.clipboard.writeText(A),t.success(u("base.sessions_path_copied"))}catch{t.error(u("base.sessions_copy_failed"))}};return n.jsxs(Ve,{fullHeight:!0,title:u("base.sessions_title"),description:o?u("base.sessions_desc"):u("base.sessions_desc_scoped",{path:c||"…"}),action:n.jsx(qe,{content:u("base.sessions_refresh"),children:n.jsx(re,{size:"sm",variant:"secondary",onClick:()=>E.mutate(),children:n.jsx(Cs,{size:13})})}),children:[n.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[n.jsxs("div",{className:"relative flex-1",children:[n.jsx(ql,{size:14,className:"pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-muted-fg"}),n.jsx(Ee,{className:"pl-8",placeholder:u("base.sessions_search_ph"),value:m,onChange:R=>g(R.target.value)})]}),n.jsx(qe,{content:u("base.sessions_deep_tip"),children:n.jsx(re,{size:"sm",variant:_?"primary":"secondary",onClick:()=>j(R=>!R),children:u("base.sessions_deep")})}),n.jsx("div",{className:"w-36",children:n.jsx(ct,{value:d,onChange:f,options:[{value:"",label:u("base.sessions_all")},{value:"apx",label:"apx"},{value:"claude",label:"claude"},{value:"codex",label:"codex"}]})}),n.jsx(qe,{content:u("base.sessions_clear"),children:n.jsx(re,{size:"sm",variant:"ghost",onClick:y,children:n.jsx(gs,{size:14})})})]}),E.isLoading&&n.jsx(st,{}),E.error&&n.jsx(ft,{children:u("base.sessions_error",{msg:E.error.message})}),!E.isLoading&&!E.error&&E.total===0&&n.jsx(ft,{children:h?u("base.sessions_no_match",{q:h}):u("base.sessions_empty")}),n.jsx(G_,{paged:E,fullHeight:!0,children:n.jsx("ul",{className:"space-y-1 text-sm",children:E.items.map((R,A)=>n.jsxs("li",{className:"group flex items-center gap-3 rounded-md border border-border bg-muted/30 px-3 py-2",children:[n.jsx($e,{tone:CI[R.engine]||"muted",children:R.engine}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("div",{className:"truncate",children:R.title||R.id}),n.jsxs("div",{className:"flex items-center gap-2 font-mono text-[10px] text-muted-fg",children:[n.jsx("span",{className:"shrink-0",children:R.id}),R.cwd&&n.jsxs("span",{className:"truncate",children:["· ",R.cwd]})]})]}),R.mtime>0&&n.jsx("span",{className:"shrink-0 text-[11px] text-muted-fg",children:new Date(R.mtime).toLocaleString()}),n.jsxs("div",{className:"flex shrink-0 items-center gap-0.5 opacity-60 transition-opacity group-hover:opacity-100",children:[n.jsx(qe,{content:u("base.sessions_act_cmd"),children:n.jsx(re,{size:"sm",variant:"ghost","aria-label":u("base.sessions_act_cmd"),onClick:()=>k(R),children:n.jsx(ya,{size:13})})}),n.jsx(qe,{content:u("base.sessions_act_ask",{name:a}),children:n.jsx(re,{size:"sm",variant:"ghost","aria-label":u("base.sessions_act_ask",{name:a}),onClick:()=>N(R),children:n.jsx(rn,{size:13})})}),n.jsx(qe,{content:u("base.sessions_act_folder"),children:n.jsx(re,{size:"sm",variant:"ghost","aria-label":u("base.sessions_act_folder"),onClick:()=>w(R),children:n.jsx(qo,{size:13})})}),n.jsx(qe,{content:u("base.sessions_act_path"),children:n.jsx(re,{size:"sm",variant:"ghost","aria-label":u("base.sessions_act_path"),onClick:()=>S(R),children:n.jsx(Ao,{size:13})})})]})]},`${R.engine}-${R.id}-${A}`))})})]})}function EI(){const e=Pn(),[t,a]=x.useState("open"),[o,l]=x.useState(""),c=t==="open"?o:"",d=F_({key:`/tasks?state=${t}&status=${c}`,fetchPage:(f,m)=>Qn.globalPage({state:t,limit:f,offset:m,status:c}),resetKey:`${t}|${c}`});return n.jsxs(Ve,{fullHeight:!0,title:u("project.global_tasks.title"),description:u("project.global_tasks.subtitle"),action:n.jsx("div",{className:"flex gap-1",children:["open","done","dropped","all"].map(f=>n.jsx(re,{size:"sm",variant:t===f?"primary":"ghost",onClick:()=>a(f),children:f},f))}),children:[t==="open"?n.jsxs("div",{className:"mb-3 flex flex-wrap gap-1",children:[n.jsx(re,{size:"sm",variant:o===""?"primary":"ghost",onClick:()=>l(""),children:u("project.global_tasks.any_status")}),["pending","running","in_review","blocked"].map(f=>n.jsx(re,{size:"sm",variant:o===f?"primary":"ghost",onClick:()=>l(f),children:f.replace("_"," ")},f))]}):null,d.isLoading&&n.jsx(st,{}),!d.isLoading&&d.total===0&&n.jsx(ft,{children:u("project.global_tasks.empty")}),n.jsx(G_,{paged:d,fullHeight:!0,children:n.jsx("ul",{className:"space-y-2 text-sm",children:d.items.map(f=>n.jsxs("li",{className:"flex items-start gap-3 rounded-md border border-border bg-muted/30 px-3 py-2",children:[n.jsx("button",{type:"button",onClick:()=>e(`/p/${f.project_id}/tasks`),title:u("project.global_tasks.go_project"),children:n.jsx($e,{tone:"info",children:(f.project_name||"").split("/").pop()||f.project_id})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("div",{className:"font-medium",children:f.title}),n.jsxs("div",{className:"mt-0.5 flex flex-wrap items-center gap-2 text-xs text-muted-fg",children:[n.jsx("span",{children:f.state}),f.agent&&n.jsxs($e,{tone:"muted",children:["@",f.agent]}),f.tags?.map(m=>n.jsxs("span",{children:["#",m]},m)),f.due&&n.jsxs("span",{children:[u("project.global_tasks.due")," ",f.due]})]})]})]},`${f.project_id}-${f.id}`))})})]})}const iE=x.createContext(void 0);function Y_(){const e=x.useContext(iE);if(e===void 0)throw new Error(gn(64));return e}const Cp={tabActivationDirection:e=>({"data-activation-direction":e})},RI=x.forwardRef(function(t,a){const{className:o,defaultValue:l=0,onValueChange:c,orientation:d="horizontal",render:f,value:m,style:g,...h}=t,b=t.defaultValue!==void 0,_=x.useRef([]),[j,E]=x.useState(()=>new Map),[y,k]=ni({controlled:m,default:l,name:"Tabs",state:"value"}),N=m!==void 0,[w,S]=x.useState(()=>new Map),R=x.useRef(void 0),A=x.useCallback(Y=>Yx(w,Y),[w]),[T,z]=x.useState(()=>({previousValue:y,tabActivationDirection:"none"})),{previousValue:M,tabActivationDirection:L}=T;let P=L,B=!1;M!==y&&(P=Qk(M,y,d,w),B=M!=null&&y!=null&&A(y)==null);const D=B?M:y,$=M!==D||L!==P;Pe(()=>{$&&z({previousValue:D,tabActivationDirection:P})},[D,$,P]);const q=He((Y,oe)=>{const ve=Qk(y,Y,d,w);oe.activationDirection=ve,c?.(Y,oe),!oe.isCanceled&&k(Y)}),G=He((Y,oe)=>{c?.(Y,rt(oe,void 0,void 0,{activationDirection:"none"}))}),U=He((Y,oe)=>(E(ve=>{const le=new Map(ve);return le.set(Y,oe),le}),()=>{E(ve=>{if(ve.get(Y)!==oe)return ve;const le=new Map(ve);return le.delete(Y),le})})),V=x.useCallback(Y=>j.get(Y),[j]),X=x.useCallback(Y=>{for(const oe of w.values())if(Y===oe.value)return oe.id},[w]),Q=x.useMemo(()=>({getTabElementBySelectedValue:A,getTabIdByPanelValue:X,getTabPanelIdByValue:V,onValueChange:q,orientation:d,registerMountedTabPanel:U,setTabMap:S,tabActivationDirection:P,value:y}),[A,X,V,q,d,U,S,P,y]),W=x.useMemo(()=>{for(const Y of w.values())if(Y.value===y)return Y},[w,y]),I=x.useMemo(()=>{for(const Y of w.values())if(!Y.disabled)return Y.value},[w]),K=x.useRef(!b),ee=x.useRef(l),F=x.useRef(b),ne=x.useRef(!1);Pe(()=>{if(N)return;function Y(xe,ke){k(xe),z({previousValue:xe,tabActivationDirection:"none"}),G(xe,ke),K.current=!1}if(w.size===0){ne.current&&y!==null&&!R.current?.isConnected&&Y(null,Cj);return}ne.current=!0,R.current=w.keys().next().value;const oe=W?.disabled,ve=W==null&&y!==null;if(!oe&&y===ee.current&&(F.current=!1),F.current&&oe&&y===ee.current)return;const le=K.current;if(oe||ve){const xe=I??null;if(y===xe){K.current=!1;return}let ke=Cj;le?ke=Nj:oe&&(ke=jS),Y(xe,ke);return}le&&W!=null&&(G(y,Nj),K.current=!1)},[I,N,G,W,k,w,y]);const fe=Et("div",t,{state:{orientation:d,tabActivationDirection:P},ref:a,props:h,stateAttributesMapping:Cp});return n.jsx(iE.Provider,{value:Q,children:n.jsx(bp,{elementsRef:_,children:fe})})});function Yx(e,t){for(const[a,o]of e.entries())if(t===o.value)return a;return null}function Qk(e,t,a,o){if(e==null||t==null)return"none";const[l,c,d]=a==="horizontal"?["left","left","right"]:["top","up","down"],f=Yx(o,e),m=Yx(o,t);if(f==null||m==null)return f!==m&&(typeof e=="number"||typeof e=="string")&&typeof e==typeof t?t>e?d:c:"none";const g=f.getBoundingClientRect()[l],h=m.getBoundingClientRect()[l];return h<g?c:h>g?d:"none"}const cE="data-composite-item-active",uE=x.createContext(void 0);function TI(){const e=x.useContext(uE);if(e===void 0)throw new Error(gn(65));return e}const AI=x.forwardRef(function(t,a){const{className:o,disabled:l=!1,render:c,value:d,id:f,nativeButton:m=!0,style:g,...h}=t,{value:b,getTabPanelIdByValue:_,onValueChange:j,orientation:E,tabActivationDirection:y}=Y_(),{activateOnFocus:k,registerTabResizeObserverElement:N,tabsListElement:w}=TI(),{highlightedIndex:S,onHighlightedIndexChange:R}=hp(),A=ra(f),T=x.useMemo(()=>({disabled:l,id:A,value:d}),[l,A,d]),{compositeProps:z,compositeRef:M,index:L}=JC({metadata:T}),P=d===b,B=x.useRef(!1),D=x.useRef(null),$=He(ne=>{D.current?.(),D.current=ne?N(ne):null});Pe(()=>{if(B.current){B.current=!1;return}if(!(P&&L>-1&&S!==L))return;const ne=w;if(ne!=null){const Z=Kn(vt(ne));if(Z&&Ze(ne,Z))return}l||R(L)},[P,L,S,R,l,w]);const{getButtonProps:q,buttonRef:G}=no({disabled:l,native:m,focusableWhenDisabled:!0}),U=_(d),V=x.useRef(!1),X=x.useRef(!1);function Q(ne){j(d,rt(ka,ne.nativeEvent,void 0,{activationDirection:"none"}))}function W(ne){P||l||Q(ne)}function I(ne){P||l||k&&(!V.current||X.current)&&Q(ne)}function K(ne){if(P||l)return;V.current=!0,X.current=ne.button===0;const Z=vt(ne.currentTarget);function fe(){V.current=!1,X.current=!1,Z.removeEventListener("pointerup",fe),Z.removeEventListener("pointercancel",fe)}Z.addEventListener("pointerup",fe),Z.addEventListener("pointercancel",fe)}return Et("button",t,{state:{disabled:l,active:P,orientation:E,tabActivationDirection:y},ref:[a,G,M,$],props:[z,{role:"tab","aria-controls":U,"aria-selected":P,id:A,onClick:W,onFocus:I,onPointerDown:K,[cE]:P?"":void 0,onKeyDownCapture(){B.current=!0}},h,q],stateAttributesMapping:Cp})}),MI={...Cp,...Ho},zI=x.forwardRef(function(t,a){const{className:o,value:l,render:c,keepMounted:d=!1,style:f,...m}=t,{value:g,getTabIdByPanelValue:h,orientation:b,tabActivationDirection:_,registerMountedTabPanel:j}=Y_(),E=ra(),{ref:y,index:k}=ru(),N=l===g,{mounted:w,transitionStatus:S,setMounted:R}=hi(N),A=!w,T=h(l),z={hidden:A,orientation:b,tabActivationDirection:_,transitionStatus:S},M=x.useRef(null),L=Et("div",t,{state:z,ref:[a,y,M],props:[{"aria-labelledby":T,hidden:A,id:E,role:"tabpanel",tabIndex:N?0:-1,inert:gp(!N),"data-index":k},m],stateAttributesMapping:MI});return Ca({open:N,ref:M,onComplete(){N||R(!1)}}),Pe(()=>{if(!(E==null||A&&!d))return j(l,E)},[A,d,l,E,j]),d||w?L:null}),OI=[];function DI(e){const{loopFocus:t=!0,orientation:a="both",grid:o,onLoop:l,direction:c,highlightedIndex:d,onHighlightedIndexChange:f,rootRef:m,enableHomeAndEndKeys:g=!1,stopEventPropagation:h,disabledIndices:b,modifierKeys:_=OI}=e,[j,E]=x.useState(0),y=o!=null,k=x.useRef(null),N=rr(k,m),w=x.useRef([]),S=x.useRef(!1),R=d??j,A=He((P,B=!1)=>{if((f??E)(P),B){const D=w.current[P];fk(k.current,D,c,a)}}),T=He(P=>{if(P.size===0||S.current)return;S.current=!0;const B=Array.from(P.keys()),D=B.find(q=>q?.hasAttribute(cE))??null,$=D?P.get(D)?.index??-1:-1;if($!==-1)A($);else if(xf(B,R,b)){const q=Qa(B,{disabledIndices:b});Rc(B,q)||A(q)}fk(k.current,D,c,a)});Pe(()=>{if(b==null||d!=null||!S.current)return;const P=w.current;if(xf(P,R,b)){const B=Qa(P,{disabledIndices:b});Rc(P,B)||A(B)}},[b,d,R,w,A]);const z=He((P,B,D)=>l?l(P,B,D,w):D),M=He(P=>{const B=P.key===Rx||P.key===Tx;if(!xp.has(P.key)||!g&&B||PI(P,_)||!k.current)return;const $=c==="rtl",q=$?Nx:Ex,G=$?Ex:Nx,U=a==="vertical"?Cx:q,V=a==="vertical"?Sx:G,X=qn(P.nativeEvent);if(X!=null&&dk(X)&&!tN(X)){const F=X.selectionStart,ne=X.selectionEnd,Z=X.value;if(F==null||P.shiftKey||F!==ne||P.key!==V&&F<Z.length||P.key!==U&&F>0)return}let Q=R;const W=ef(w,b),I=vx(w,b);o!=null&&(Q=o({disabledIndices:b,elementsRef:w,event:P,highlightedIndex:R,loopFocus:t,maxIndex:I,minIndex:W,onLoop:z,orientation:a,rtl:$}));const K=a!=="vertical"&&P.key===q||a!=="horizontal"&&P.key===Cx,ee=a!=="vertical"&&P.key===G||a!=="horizontal"&&P.key===Sx;g&&(P.key===Rx?Q=W:P.key===Tx&&(Q=I)),Q===R&&(K||ee)&&(t&&Q===I&&K?(Q=W,l&&(Q=l(P,R,Q,w))):t&&Q===W&&ee?(Q=I,l&&(Q=l(P,R,Q,w))):Q=Qa(w.current,{startingIndex:Q,decrement:ee,disabledIndices:b})),Q!==R&&!Rc(w.current,Q)&&(h&&P.stopPropagation(),(y||B||K||ee)&&P.preventDefault(),A(Q,!0),queueMicrotask(()=>{w.current[Q]?.focus()}))});return{props:{ref:N,onFocus(P){const B=k.current,D=qn(P.nativeEvent);!B||D==null||!dk(D)||D.setSelectionRange(0,D.value.length)},onKeyDown:M},highlightedIndex:R,onHighlightedIndexChange:A,elementsRef:w,onMapChange:T,relayKeyboardEvent:M}}function PI(e,t){for(const a of D6)if(!t.includes(a)&&e.getModifierState(a))return!0;return!1}function LI(e){const{render:t,className:a,style:o,refs:l=ja,props:c=ja,state:d=sn,stateAttributesMapping:f,highlightedIndex:m,onHighlightedIndexChange:g,orientation:h,grid:b,loopFocus:_,onLoop:j,enableHomeAndEndKeys:E,onMapChange:y,stopEventPropagation:k=!0,rootRef:N,disabledIndices:w,modifierKeys:S,highlightItemOnHover:R=!1,tag:A="div",...T}=e,z=pp(),{props:M,highlightedIndex:L,onHighlightedIndexChange:P,elementsRef:B,onMapChange:D,relayKeyboardEvent:$}=DI({grid:b,loopFocus:_,onLoop:j,orientation:h,highlightedIndex:m,onHighlightedIndexChange:g,rootRef:N,stopEventPropagation:k,enableHomeAndEndKeys:E,direction:z,disabledIndices:w,modifierKeys:S}),q=Et(A,e,{state:d,ref:l,props:[M,...c,T],stateAttributesMapping:f}),G=x.useMemo(()=>({highlightedIndex:L,onHighlightedIndexChange:P,highlightItemOnHover:R,relayKeyboardEvent:$}),[L,P,R,$]);return n.jsx(IC.Provider,{value:G,children:n.jsx(bp,{elementsRef:B,onMapChange:U=>{y?.(U),D(U)},children:q})})}const II=x.forwardRef(function(t,a){const{activateOnFocus:o=!1,className:l,loopFocus:c=!0,render:d,style:f,...m}=t,{orientation:g,setTabMap:h,tabActivationDirection:b}=Y_(),[_,j]=x.useState(0),[E,y]=x.useState(null),k=x.useRef(new Set),N=x.useRef(new Set),w=x.useRef(null);Pe(()=>{if(typeof ResizeObserver>"u")return;const M=new ResizeObserver(()=>{k.current.forEach(L=>{L()})});return w.current=M,E&&M.observe(E),N.current.forEach(L=>{M.observe(L)}),()=>{M.disconnect(),w.current=null}},[E]);const S=He(M=>(k.current.add(M),()=>{k.current.delete(M)})),R=He(M=>(N.current.add(M),w.current?.observe(M),()=>{N.current.delete(M),w.current?.unobserve(M)})),A={orientation:g,tabActivationDirection:b},T={"aria-orientation":g==="vertical"?"vertical":void 0,role:"tablist"},z=x.useMemo(()=>({activateOnFocus:o,registerIndicatorUpdateListener:S,registerTabResizeObserverElement:R,tabsListElement:E}),[o,S,R,E]);return n.jsx(uE.Provider,{value:z,children:n.jsx(LI,{render:d,className:l,style:f,state:A,refs:[a,y],props:[T,m],stateAttributesMapping:Cp,highlightedIndex:_,enableHomeAndEndKeys:!0,loopFocus:c,orientation:g,onHighlightedIndexChange:j,onMapChange:h,disabledIndices:ja})})});function Np({className:e,...t}){return n.jsx(RI,{"data-slot":"tabs",className:St("flex flex-col gap-4",e),...t})}const BI=A_("inline-flex h-9 w-fit items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground data-[variant=line]:h-8 data-[variant=line]:gap-1 data-[variant=line]:rounded-none data-[variant=line]:bg-transparent data-[variant=line]:p-0",{variants:{variant:{default:"bg-muted",line:"gap-1 bg-transparent"}},defaultVariants:{variant:"default"}});function Ep({className:e,variant:t="default",...a}){return n.jsx(II,{"data-slot":"tabs-list","data-variant":t,className:St(BI({variant:t}),e),...a})}function qs({className:e,...t}){return n.jsx(AI,{"data-slot":"tabs-trigger",className:St("inline-flex h-7 items-center justify-center gap-1.5 rounded-md border border-transparent px-3 py-1 text-sm font-medium whitespace-nowrap text-muted-fg transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50 data-active:bg-background data-active:text-foreground data-active:shadow-sm dark:data-active:border-input dark:data-active:bg-input/30 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...t})}function fs({className:e,...t}){return n.jsx(zI,{"data-slot":"tabs-content",className:St("text-sm outline-none",e),...t})}function Wk(e,t){let a=e;for(const o of t.split(".")){if(!a||typeof a!="object"||Array.isArray(a))return;a=a[o]}return a}function K_(e,t=""){const a={};for(const[o,l]of Object.entries(e)){const c=t?`${t}.${o}`:o;l&&typeof l=="object"&&!Array.isArray(l)?Object.assign(a,K_(l,c)):a[c]=l}return a}function dE(e){const t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error("JSON debe ser objeto.");return t}function of({sections:e,source:t,placeholderSource:a,jsonTitle:o,jsonDescription:l,saveLabel:c=u("common.save"),onSaveFields:d,onSaveJson:f,busy:m,hideJson:g=!1}){const h=e[0]?.key||"json",[b,_]=x.useState({}),[j,E]=x.useState(""),[y,k]=x.useState("");x.useEffect(()=>{const A={};for(const T of e.flatMap(z=>z.fields))A[T.path]=Wk(t,T.path)??"";_(A),E(JSON.stringify(t||{},null,2)),k("")},[t,e]);const N=x.useMemo(()=>new Set(e.flatMap(A=>A.fields.map(T=>T.path))),[e]),w=async()=>{const A={},T=[];for(const z of e.flatMap(M=>M.fields)){const M=b[z.path];if(!ps(M)){if(M===""||M===void 0||M===null){T.push(z.path);continue}if(z.kind==="number"){const L=Number(M);Number.isFinite(L)&&(A[z.path]=L)}else A[z.path]=M}}await d(A,T.filter(z=>N.has(z)))},S=async()=>{k("");try{await f(dE(j))}catch(A){k(A.message)}},R=A=>n.jsxs("div",{className:"space-y-4",children:[A.description&&n.jsx("p",{className:"text-sm text-muted-fg",children:A.description}),n.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:A.fields.map(T=>n.jsx($I,{field:T,value:b[T.path],inherited:Wk(a,T.path),onChange:z=>_(M=>({...M,[T.path]:z}))},T.path))}),n.jsx(re,{variant:"primary",loading:m,onClick:w,children:c})]});return g&&e.length<=1?e[0]?R(e[0]):null:n.jsxs(Np,{defaultValue:h,className:"space-y-4",children:[n.jsxs(Ep,{className:"flex flex-wrap",children:[e.map(A=>n.jsx(qs,{value:A.key,children:A.label},A.key)),!g&&n.jsx(qs,{value:"json",children:"JSON"})]}),e.map(A=>n.jsx(fs,{value:A.key,children:R(A)},A.key)),!g&&n.jsx(fs,{value:"json",children:n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{children:[n.jsx("h3",{className:"text-sm font-medium",children:o}),l&&n.jsx("p",{className:"text-xs text-muted-fg",children:l})]}),n.jsx(un,{rows:18,className:"font-mono text-xs",value:j,onChange:A=>E(A.target.value)}),y&&n.jsx("p",{className:"text-xs text-destructive",children:y}),n.jsx(re,{variant:"primary",loading:m,onClick:S,children:u("settings_ui.save_json")})]})})]})}function $I({field:e,value:t,inherited:a,onChange:o}){const l=e.placeholder||Zk(a)||(ps(t)?Fr(t):""),c=e.hint||(a!==void 0?`Heredado: ${Zk(a)}`:void 0);return e.kind==="boolean"?n.jsx("div",{className:"flex items-end pb-1",children:n.jsx(Bt,{checked:t===!0,onChange:o,label:e.label})}):n.jsx(ie,{label:e.label,hint:c,children:e.kind==="select"?n.jsx(ct,{value:String(t||""),onChange:o,placeholder:l||"(sin override)",options:[{value:"",label:l||"(sin override)"},...(e.options||[]).map(d=>({value:String(d.value),label:d.label}))]}):e.kind==="textarea"?n.jsx(un,{rows:4,value:String(t||""),placeholder:l,onChange:d=>o(d.target.value)}):n.jsx(Ee,{type:e.kind==="password"?"password":e.kind==="number"?"number":"text",value:String(ps(t)?"":t||""),placeholder:e.kind==="password"&&ps(t)?Fr(t):e.kind==="password"&&ps(a)?Fr(a):l,onChange:d=>o(d.target.value)})})}function Zk(e){return e==null||e===""?"":ps(e)?Fr(e):Array.isArray(e)?e.join(", "):typeof e=="object"?JSON.stringify(e):String(e)}function UI(){return[{key:"routing",label:u("settings_ui.cfg_overrides_label"),description:u("settings_ui.cfg_overrides_desc"),fields:[{path:"route_to_agent",label:u("settings_ui.cfg_route_to_agent"),placeholder:"master"},{path:"super_agent.model",label:u("settings_ui.cfg_super_agent_model")},{path:"super_agent.permission_mode",label:u("settings_ui.cfg_permission_mode"),kind:"select",options:Cb.map(e=>({value:e,label:e}))},{path:"super_agent.system",label:u("settings_ui.cfg_extra_prompt"),kind:"textarea"}]}]}function qI(){return[{key:"engines",label:u("settings_ui.cfg_engines_label"),fields:[{path:"engines.ollama.base_url",label:u("settings_ui.cfg_ollama_url")},{path:"engines.anthropic.api_key",label:u("settings_ui.cfg_anthropic_key"),kind:"password"},{path:"engines.openai.api_key",label:u("settings_ui.cfg_openai_key"),kind:"password"},{path:"engines.groq.api_key",label:u("settings_ui.cfg_groq_key"),kind:"password"},{path:"engines.openrouter.api_key",label:u("settings_ui.cfg_openrouter_key"),kind:"password"},{path:"engines.gemini.api_key",label:u("settings_ui.cfg_gemini_key"),kind:"password"}]}]}function HI(){return[{key:"identity",label:u("settings_ui.cfg_project_label"),description:u("settings_ui.cfg_project_desc"),fields:[{path:"name",label:u("settings_ui.cfg_name")},{path:"version",label:u("settings_ui.cfg_version")},{path:"apf",label:u("settings_ui.cfg_apc_spec")},{path:"apx",label:u("settings_ui.cfg_apx_install")},{path:"apx_id",label:u("settings_ui.cfg_apx_storage_id")}]}]}function fE({pid:e}){const t=Je(),{project:a}=cu(e),{channels:o,isLoading:l,mutate:c}=D_(),d=String(e),f=a?.name||a?.path?.split("/").pop()||d,m=`proj-${d}`,g=o.find(z=>z.project===d||z.project===f||z.name===m),[h,b]=x.useState(!!g),[_,j]=x.useState(""),[E,y]=x.useState(""),[k,N]=x.useState(""),[w,S]=x.useState(!0),[R,A]=x.useState(!1);if(x.useEffect(()=>{g?(b(!0),j(""),y(g.chat_id||""),N(g.route_to_agent||""),S(g.respond_with_engine??!0)):(b(!1),j(""),y(""),N(""),S(!0))},[g?.name,g?.chat_id,g?.route_to_agent]),l)return n.jsx(st,{});const T=async()=>{A(!0);try{if(!h){g&&(await Dn.channels.remove(g.name),t.success(u("project.telegram.cleared"))),await c();return}const z={name:g?.name||m,project:d,chat_id:E,route_to_agent:k,respond_with_engine:w,..._?{bot_token:_}:{}};g?await Dn.channels.patch(g.name,z):await Dn.channels.upsert(z),t.success(u("project.telegram.saved")),await c(),j("")}catch(z){t.error(z.message)}finally{A(!1)}};return n.jsx(Ve,{title:u("project.telegram.title"),description:u("project.telegram.subtitle"),children:n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx(Bt,{checked:h,onChange:b,label:u(h?"project.telegram.override_active":"project.telegram.use_default")}),g&&n.jsx($e,{tone:"success",children:u("project.telegram.channel_badge",{name:g.name})})]}),h&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsx(ie,{label:u("project.telegram.bot_token"),hint:g?.bot_token?`${Fr(g.bot_token)} ${u("telegram_ui.empty_keep")}`:u("project.telegram.bot_hint_none"),children:n.jsx(Ee,{type:"password",value:_,onChange:z=>j(z.target.value),placeholder:g?.bot_token?Fr(g.bot_token):""})}),n.jsx(ie,{label:u("project.telegram.chat_id"),children:n.jsx(Ee,{value:E,onChange:z=>y(z.target.value)})}),n.jsx(ie,{label:u("project.telegram.route_agent"),hint:u("project.telegram.route_hint"),children:n.jsx(Ee,{value:k,onChange:z=>N(z.target.value)})})]}),n.jsx(Bt,{checked:w,onChange:S,label:u("project.telegram.respond_engine")})]}),n.jsx("div",{className:"pt-2",children:n.jsx(re,{variant:"primary",loading:R,onClick:T,children:u("common.save")})}),!h&&!g&&n.jsx(ft,{children:u("project.telegram.no_override")})]})})}function VI({pid:e}){const t=Je(),a=Pn(),{project:o,mutate:l}=cu(e),c=Be(`/projects/${e}/config`,()=>Zn.config.show(e)),d=String(e)==="0";if(c.isLoading)return n.jsx(st,{});if(!c.data)return n.jsx(ft,{children:u("project.config.no_data")});const f=async h=>{await Zn.apcProject.put(e,h),t.success(u("project.config.save_project")),c.mutate()},m=async h=>{await Zn.config.put(e,h),t.success(u("project.config.save_override")),c.mutate()},g=async(h,b)=>{await Zn.config.set(e,h),b.length&&await Zn.config.unset(e,b),t.success(u("project.config.save_fields_success")),c.mutate()};return n.jsxs("div",{className:"space-y-6",children:[n.jsx(Ve,{title:u("project.config.section_title"),description:u("project.config.section_desc"),children:n.jsxs(Np,{defaultValue:"settings",className:"space-y-4",children:[n.jsxs(Ep,{className:"flex flex-wrap",children:[n.jsx(qs,{value:"settings",children:u("project.config.tab_settings")}),n.jsx(qs,{value:"engines",children:u("settings_ui.cfg_engines_label")}),!d&&n.jsx(qs,{value:"telegram",children:u("project.nav.telegram")}),n.jsx(qs,{value:"project",children:u("project.config.tab_project")}),n.jsx(qs,{value:"json",children:"JSON"})]}),n.jsx(fs,{value:"settings",children:n.jsx(of,{sections:UI(),source:c.data.project_only,placeholderSource:c.data.effective,jsonTitle:c.data.project_config_path,onSaveFields:g,onSaveJson:m,hideJson:!0})}),n.jsx(fs,{value:"engines",children:n.jsx(of,{sections:qI(),source:c.data.project_only,placeholderSource:c.data.effective,jsonTitle:c.data.project_config_path,onSaveFields:g,onSaveJson:m,hideJson:!0})}),!d&&n.jsx(fs,{value:"telegram",children:n.jsx(fE,{pid:e})}),n.jsx(fs,{value:"project",children:n.jsx(of,{sections:HI(),source:c.data.apc_project||{},jsonTitle:c.data.project_json_path,onSaveFields:async(h,b)=>{await Zn.apcProject.set(e,GI(h),b),t.success(u("project.config.save_meta_success")),c.mutate()},onSaveJson:f,hideJson:!0})}),n.jsx(fs,{value:"json",children:n.jsxs("div",{className:"space-y-6",children:[n.jsx(Jk,{title:c.data.project_config_path,description:".apc/config.json — overrides del proyecto.",source:c.data.project_only,onSave:m}),n.jsx(Jk,{title:c.data.project_json_path,description:".apc/project.json — metadata APC portable.",source:c.data.apc_project||{},onSave:f}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-xs text-muted-fg",children:u("project.config.effective_read")}),n.jsx("pre",{className:"max-h-96 overflow-auto rounded-lg border border-border bg-muted/40 p-3 text-xs",children:JSON.stringify(c.data.effective,null,2)})]})]})})]})}),!d&&o?n.jsx(FI,{pid:e,label:o.name||o.path,onRebuilt:()=>c.mutate(),onUnregistered:()=>{l(),a("/")}}):null]})}function FI({pid:e,label:t,onRebuilt:a,onUnregistered:o}){const l=Je(),[c,d]=x.useState(null),[f,m]=x.useState(null),g=async()=>{d("rebuild");try{await Zn.rebuild(e),l.success(u("project.rebuild_done")),a()}catch(b){l.error(b.message)}finally{d(null),m(null)}},h=async()=>{d("unregister");try{await Zn.remove(e),l.success(u("project.unregistered")),o()}catch(b){l.error(b.message)}finally{d(null),m(null)}};return n.jsxs(n.Fragment,{children:[n.jsx(Ve,{title:u("project.danger.title"),description:u("project.danger.subtitle"),children:n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-md border border-border bg-muted/30 px-3 py-3",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"text-sm font-medium",children:u("project.rebuild")}),n.jsx("div",{className:"text-xs text-muted-fg",children:u("project.danger.rebuild_desc")})]}),n.jsxs(re,{size:"sm",variant:"secondary",onClick:()=>m("rebuild"),children:[n.jsx(Cs,{size:13})," ",u("project.rebuild")]})]}),n.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-md border border-red-500/40 bg-red-500/5 px-3 py-3",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"text-sm font-medium",children:u("admin.unregister")}),n.jsx("div",{className:"text-xs text-muted-fg",children:u("project.danger.unregister_desc")})]}),n.jsxs(re,{size:"sm",variant:"destructive",onClick:()=>m("unregister"),children:[n.jsx(_n,{size:13})," ",u("admin.unregister")]})]})]})}),n.jsx(Xt,{open:f==="rebuild",onClose:()=>c?null:m(null),title:u("project.danger.rebuild_confirm_title"),description:u("project.danger.rebuild_confirm_desc",{label:t}),size:"sm",footer:n.jsxs(n.Fragment,{children:[n.jsx(re,{variant:"ghost",onClick:()=>m(null),disabled:c!==null,children:u("common.cancel")}),n.jsx(re,{variant:"primary",onClick:g,loading:c==="rebuild",children:u("project.rebuild")})]}),children:n.jsx("p",{className:"text-sm text-muted-fg",children:u("project.danger.rebuild_long")})}),n.jsx(Xt,{open:f==="unregister",onClose:()=>c?null:m(null),title:u("project.danger.unregister_confirm_title"),description:u("project.unregister_confirm",{label:t}),size:"sm",footer:n.jsxs(n.Fragment,{children:[n.jsx(re,{variant:"ghost",onClick:()=>m(null),disabled:c!==null,children:u("common.cancel")}),n.jsx(re,{variant:"destructive",onClick:h,loading:c==="unregister",children:u("admin.unregister")})]}),children:n.jsx("p",{className:"text-sm text-muted-fg",children:u("project.danger.unregister_long")})})]})}function Jk({title:e,description:t,source:a,onSave:o}){const[l,c]=x.useState(""),[d,f]=x.useState(""),[m,g]=x.useState(!1);x.useEffect(()=>{c(JSON.stringify(a||{},null,2)),f("")},[a]);const h=async()=>{f(""),g(!0);try{await o(dE(l))}catch(b){f(b.message)}finally{g(!1)}};return n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{children:[n.jsx("h3",{className:"text-sm font-medium",children:e}),t&&n.jsx("p",{className:"text-xs text-muted-fg",children:t})]}),n.jsx(un,{rows:14,className:"font-mono text-xs",value:l,onChange:b=>c(b.target.value)}),d&&n.jsx("p",{className:"text-xs text-destructive",children:d}),n.jsx(re,{variant:"primary",loading:m,onClick:h,children:u("settings_ui.save_json")})]})}function GI(e){const t={};for(const[a,o]of Object.entries(K_(e)))ps(o)||(t[a]=o);return t}function Kl(e){return String(e||"").trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").replace(/-{2,}/g,"-")}function pE({open:e,onClose:t,pid:a,editing:o,onSaved:l}){const c=Je(),[d,f]=x.useState(""),[m,g]=x.useState(""),[h,b]=x.useState(""),[_,j]=x.useState(!1);x.useEffect(()=>{e&&(f(o?.name??""),g(o?.slug??""),b(o?.goal??""))},[e,o]);const E=async()=>{if(d.trim()){j(!0);try{o?await Vr.updateArea(a,o.slug,{name:d,goal:h}):await Vr.createArea(a,{name:d,slug:m||Kl(d),goal:h}),c.success(u("common.saved")),l(),t()}catch(y){c.error(y instanceof Error?y.message:String(y))}finally{j(!1)}}};return n.jsx(Xt,{open:e,onClose:t,title:u(o?"structure.edit_area":"structure.new_area"),footer:n.jsxs(n.Fragment,{children:[n.jsx(re,{variant:"ghost",onClick:t,children:u("common.cancel")}),n.jsx(re,{variant:"primary","data-testid":"area-create",onClick:()=>void E(),loading:_,disabled:!d.trim(),children:u(o?"common.save":"structure.create_area")})]}),children:n.jsxs("div",{className:"space-y-3",children:[n.jsx(ie,{label:u("structure.name"),children:n.jsx(Ee,{autoFocus:!0,"data-testid":"area-name",value:d,onChange:y=>{f(y.target.value),o||g(Kl(y.target.value))},placeholder:"Engineering"})}),!o&&n.jsx(ie,{label:u("structure.slug"),children:n.jsx(Ee,{value:m,onChange:y=>g(Kl(y.target.value)),className:"font-mono",placeholder:"engineering"})}),n.jsx(ie,{label:u("structure.goal"),hint:u("structure.goal_hint"),children:n.jsx(un,{value:h,onChange:y=>b(y.target.value),rows:2})})]})})}function mE({open:e,onClose:t,pid:a,areas:o,editing:l,presetArea:c,onSaved:d}){const f=Je(),[m,g]=x.useState(""),[h,b]=x.useState(""),[_,j]=x.useState(""),[E,y]=x.useState(""),[k,N]=x.useState(!1);x.useEffect(()=>{e&&(g(l?.name??""),b(l?.slug??""),j(l?.area??c??""),y(l?.description??""))},[e,l,c]);const w=async()=>{if(m.trim()){N(!0);try{l?await Vr.updateRole(a,l.slug,{name:m,area:_||null,description:E}):await Vr.createRole(a,{name:m,slug:h||Kl(m),area:_||null,description:E}),f.success(u("common.saved")),d(),t()}catch(R){f.error(R instanceof Error?R.message:String(R))}finally{N(!1)}}},S=[{value:"",label:u("structure.no_area")},...o.map(R=>({value:R.slug,label:R.name}))];return n.jsx(Xt,{open:e,onClose:t,title:u(l?"structure.edit_role":"structure.new_role"),footer:n.jsxs(n.Fragment,{children:[n.jsx(re,{variant:"ghost",onClick:t,children:u("common.cancel")}),n.jsx(re,{variant:"primary",onClick:()=>void w(),loading:k,disabled:!m.trim(),children:u(l?"common.save":"structure.create_role")})]}),children:n.jsxs("div",{className:"space-y-3",children:[n.jsx(ie,{label:u("structure.name"),children:n.jsx(Ee,{autoFocus:!0,value:m,onChange:R=>{g(R.target.value),l||b(Kl(R.target.value))},placeholder:"Tech Lead"})}),!l&&n.jsx(ie,{label:u("structure.slug"),children:n.jsx(Ee,{value:h,onChange:R=>b(Kl(R.target.value)),className:"font-mono",placeholder:"tech-lead"})}),n.jsx(ie,{label:u("structure.area"),children:n.jsx(ct,{value:_,onChange:j,options:S,placeholder:u("structure.no_area")})}),n.jsx(ie,{label:u("structure.description"),children:n.jsx(un,{value:E,onChange:R=>y(R.target.value),rows:2})})]})})}function gE({value:e,onChange:t}){return n.jsx(Ee,{value:e,onChange:a=>t([...a.target.value].slice(-2).join("")),className:"text-center text-lg",placeholder:"🤖","aria-label":u("agents_form.emoji")})}const YI=[{value:"total",labelKey:"auto_total"},{value:"automatico",labelKey:"auto_automatico"},{value:"permiso",labelKey:"auto_permiso"}];function hE({value:e,onChange:t}){return n.jsx("div",{className:"inline-flex w-full rounded-lg border border-border p-0.5",children:YI.map(a=>n.jsx("button",{type:"button",onClick:()=>t(a.value),className:ge("flex-1 rounded-md px-2 py-1 text-[12px] font-medium capitalize transition-colors",e===a.value?"bg-primary/15 text-foreground":"text-muted-foreground hover:text-foreground"),children:u(`agents_form.${a.labelKey}`)},a.value))})}function xE({pid:e,area:t,role:a,onArea:o,onRole:l}){const c=Be(`/projects/${e}/organization`,()=>Vr.get(e)),[d,f]=x.useState(!1),[m,g]=x.useState(!1),h=c.data?.areas??[],_=(c.data?.roles??[]).filter(y=>t?y.area===t||y.area===null:!0),j=[{value:"",label:u("structure.no_area")},...h.map(y=>({value:y.slug,label:y.name}))],E=[{value:"",label:u("agents_form.no_role")},..._.map(y=>({value:y.slug,label:y.name}))];return n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsx(ie,{label:u("agents_form.area"),children:n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx(ct,{value:t,onChange:y=>{o(y)},options:j,placeholder:u("structure.no_area"),className:"flex-1"}),n.jsx(ew,{label:u("structure.new_area"),onClick:()=>f(!0)})]})}),n.jsx(ie,{label:u("agents_form.role"),children:n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx(ct,{value:a,onChange:l,options:E,placeholder:u("agents_form.no_role"),className:"flex-1"}),n.jsx(ew,{label:u("structure.new_role"),onClick:()=>g(!0)})]})})]}),n.jsx(pE,{open:d,onClose:()=>f(!1),pid:e,onSaved:()=>void c.mutate()}),n.jsx(mE,{open:m,onClose:()=>g(!1),pid:e,areas:h,presetArea:t||null,onSaved:()=>void c.mutate()})]})}function ew({label:e,onClick:t}){return n.jsx("button",{type:"button",onClick:t,title:e,"aria-label":e,className:"flex size-9 shrink-0 items-center justify-center rounded-lg border border-border text-muted-foreground hover:bg-accent hover:text-foreground",children:n.jsx(Dt,{className:"size-4"})})}function bE({open:e,onClose:t,onConfirm:a,title:o,description:l,confirmLabel:c,destructive:d=!0}){const[f,m]=x.useState(!1),g=async()=>{m(!0);try{await a(),t()}finally{m(!1)}};return n.jsx(Xt,{open:e,onClose:t,title:o,footer:n.jsxs(n.Fragment,{children:[n.jsx(re,{variant:"ghost",onClick:t,disabled:f,children:u("common.cancel")}),n.jsx(re,{variant:d?"destructive":"primary",onClick:()=>void g(),loading:f,children:c??u("common.confirm")})]}),children:n.jsx("p",{className:"text-sm text-muted-foreground",children:l})})}function qd(e,t){const a=[],o=/(\*\*([^*]+)\*\*)|(\*([^*]+)\*)|(`([^`]+)`)|(\[([^\]]+)\]\(([^)]+)\))/g;let l=0,c,d=0;for(;c=o.exec(e);)c.index>l&&a.push(n.jsx(x.Fragment,{children:e.slice(l,c.index)},`${t}-t${d}`)),c[2]!==void 0?a.push(n.jsx("strong",{children:c[2]},`${t}-b${d}`)):c[4]!==void 0?a.push(n.jsx("em",{children:c[4]},`${t}-i${d}`)):c[6]!==void 0?a.push(n.jsx("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[0.85em]",children:c[6]},`${t}-c${d}`)):c[8]!==void 0&&a.push(n.jsx("a",{href:c[9],target:"_blank",rel:"noreferrer",className:"text-sky-500 underline underline-offset-2 hover:text-sky-400",children:c[8]},`${t}-l${d}`)),l=o.lastIndex,d+=1;return l<e.length&&a.push(n.jsx(x.Fragment,{children:e.slice(l)},`${t}-tend`)),a}function _E({content:e,className:t}){const a=e.replace(/\r\n/g,`
|
|
789
789
|
`).split(`
|
|
790
790
|
`),o=[];let l=0,c=0;const d=(f,m)=>{const g=m?"ol":"ul";o.push(n.jsx(g,{className:ge("my-2 space-y-1 pl-5",m?"list-decimal":"list-disc"),children:f.map((h,b)=>n.jsx("li",{children:qd(h,`li${c}-${b}`)},b))},`k${c++}`))};for(;l<a.length;){const f=a[l];if(/^```/.test(f.trim())){const h=[];for(l+=1;l<a.length&&!/^```/.test(a[l].trim());)h.push(a[l++]);l+=1,o.push(n.jsx("pre",{className:"my-2 overflow-x-auto rounded-lg bg-muted/60 p-3 font-mono text-[12px] leading-[1.6]",children:n.jsx("code",{children:h.join(`
|
|
791
791
|
`)})},`k${c++}`));continue}if(f.trim()===""){l+=1;continue}const m=f.match(/^(#{1,6})\s+(.*)$/);if(m){const h=m[1].length,b=["text-2xl","text-xl","text-lg","text-base","text-sm","text-sm"];o.push(n.jsx("div",{className:ge("mt-3 mb-1 font-semibold text-foreground",b[h-1]),children:qd(m[2],`h${c}`)},`k${c++}`)),l+=1;continue}if(/^(-{3,}|\*{3,}|_{3,})$/.test(f.trim())){o.push(n.jsx("hr",{className:"my-3 border-border"},`k${c++}`)),l+=1;continue}if(/^>\s?/.test(f)){const h=[];for(;l<a.length&&/^>\s?/.test(a[l]);)h.push(a[l++].replace(/^>\s?/,""));o.push(n.jsx("blockquote",{className:"my-2 border-l-2 border-border pl-3 text-muted-foreground",children:qd(h.join(" "),`q${c}`)},`k${c++}`));continue}if(/^\s*[-*+]\s+/.test(f)){const h=[];for(;l<a.length&&/^\s*[-*+]\s+/.test(a[l]);)h.push(a[l++].replace(/^\s*[-*+]\s+/,""));d(h,!1);continue}if(/^\s*\d+\.\s+/.test(f)){const h=[];for(;l<a.length&&/^\s*\d+\.\s+/.test(a[l]);)h.push(a[l++].replace(/^\s*\d+\.\s+/,""));d(h,!0);continue}const g=[];for(;l<a.length&&a[l].trim()!==""&&!/^(#{1,6})\s/.test(a[l])&&!/^```/.test(a[l].trim())&&!/^>\s?/.test(a[l])&&!/^\s*[-*+]\s+/.test(a[l])&&!/^\s*\d+\.\s+/.test(a[l]);)g.push(a[l++]);o.push(n.jsx("p",{className:"my-2 leading-relaxed",children:qd(g.join(" "),`p${c}`)},`k${c++}`))}return n.jsx("div",{className:ge("text-sm text-foreground/90",t),children:o})}function KI({value:e,onChange:t,showPreview:a=!1,placeholder:o,onSave:l,className:c}){return n.jsxs("div",{className:ge("flex min-h-0 flex-1",c),children:[n.jsx("textarea",{value:e,onChange:d=>t(d.target.value),onKeyDown:d=>{l&&(d.metaKey||d.ctrlKey)&&d.key==="s"&&(d.preventDefault(),l())},placeholder:o,spellCheck:!1,className:ge("min-h-0 resize-none bg-transparent p-4 font-mono text-[13px] leading-[1.7] text-foreground/90 outline-none",a?"w-1/2 border-r border-border":"w-full")}),a&&n.jsx("div",{className:"min-h-0 w-1/2 overflow-y-auto p-4",children:n.jsx(_E,{content:e})})]})}function Hd({onClick:e,active:t,disabled:a,children:o}){return n.jsx("button",{type:"button",onClick:e,disabled:a,className:ge("inline-flex items-center gap-1 rounded px-2 py-0.5 text-[11px] font-medium transition-colors disabled:opacity-40",t?"bg-primary/15 text-foreground":"text-muted-foreground hover:bg-accent hover:text-foreground"),children:o})}function XI({content:e}){return n.jsx("div",{className:"min-h-0 flex-1 overflow-auto",children:n.jsx("table",{className:"w-full border-collapse font-mono text-[12px] leading-[1.6]",children:n.jsx("tbody",{children:e.split(`
|
|
@@ -821,4 +821,4 @@ Minimum version required to store current data is: `+B+`.
|
|
|
821
821
|
`).map((b,_)=>n.jsxs("tr",{className:"hover:bg-accent/20",children:[n.jsx("td",{className:"w-12 select-none border-r border-border/30 px-3 py-0 text-right align-top text-[10px] text-muted-foreground/40","aria-hidden":"true",children:_+1}),n.jsx("td",{className:"px-4 py-0 align-top text-foreground/90 whitespace-pre",children:b||" "})]},_))})})})]})}function $U({pid:e,className:t,initCmd:a,onClose:o}){const[l,c]=x.useState([]),[d,f]=x.useState(""),[m,g]=x.useState(!1),[h,b]=x.useState([]),[_,j]=x.useState(-1),E=x.useRef(null),y=x.useRef(null);x.useEffect(()=>{E.current?.scrollIntoView({behavior:"smooth"})},[l]),x.useEffect(()=>{a&&(f(a),setTimeout(()=>y.current?.focus(),50))},[a]);const k=async w=>{const S=w.trim();if(S){b(R=>[S,...R.slice(0,49)]),j(-1),c(R=>[...R,{type:"cmd",text:`$ ${S}`}]),g(!0);try{const R=await se.post("/run",{cmd:S,project:e});R.stdout&&c(A=>[...A,{type:"out",text:R.stdout}]),R.stderr&&c(A=>[...A,{type:"err",text:R.stderr}])}catch(R){c(A=>[...A,{type:"err",text:String(R.message)}])}finally{g(!1)}}},N=w=>{if(w.key==="Enter")k(d),f("");else if(w.key==="ArrowUp"){w.preventDefault();const S=Math.min(_+1,h.length-1);j(S),f(h[S]??"")}else if(w.key==="ArrowDown"){w.preventDefault();const S=Math.max(_-1,-1);j(S),f(S===-1?"":h[S]??"")}};return n.jsxs("div",{className:ge("flex h-full min-h-0 flex-col bg-card/60",t),"data-testid":"code-terminal",children:[n.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-3 py-1",children:[n.jsx(ya,{className:"size-3 text-muted-foreground"}),n.jsx("span",{className:"flex-1 text-[11px] text-muted-foreground",children:"Terminal"}),n.jsx(qe,{content:u("code_module.terminal_clear"),children:n.jsx("button",{type:"button",onClick:()=>c([]),className:"rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground",children:n.jsx(LA,{className:"size-3"})})}),n.jsx(qe,{content:u("code_module.terminal_close"),children:n.jsx("button",{type:"button",onClick:()=>o?.(),className:"rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground",children:n.jsx(gs,{className:"size-3"})})})]}),n.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-3 py-1 font-mono text-[11px] leading-snug cursor-text",onClick:()=>y.current?.focus(),children:[l.map((w,S)=>n.jsx("div",{className:ge("whitespace-pre-wrap break-all",w.type==="cmd"&&"text-emerald-400",w.type==="err"&&"text-rose-400",w.type==="out"&&"text-foreground/90"),children:w.text},S)),n.jsx("div",{ref:E})]}),n.jsxs("div",{className:"flex shrink-0 items-center border-t border-border px-3 py-1",children:[n.jsx("span",{className:"mr-2 text-[11px] text-emerald-400 font-mono",children:"$"}),n.jsx("input",{ref:y,value:d,onChange:w=>f(w.target.value),onKeyDown:N,disabled:m,placeholder:m?"ejecutando…":"comando…",className:"flex-1 bg-transparent font-mono text-[11px] text-foreground outline-none placeholder:text-muted-foreground/50 disabled:opacity-50",spellCheck:!1,autoComplete:"off"})]})]})}const vc="super-agent";function ax(){return n.jsx(dv,{className:"relative z-10 w-px shrink-0 cursor-col-resize bg-border transition-colors hover:bg-primary/50 active:bg-primary/70"})}function UU(){return n.jsx(dv,{className:"relative z-10 h-px shrink-0 cursor-row-resize bg-border transition-colors hover:bg-primary/50 active:bg-primary/70"})}function qU(){const e=Je(),t=Be("/projects",()=>Zn.list()),a=x.useMemo(()=>t.data||[],[t.data]),[o,l]=x.useState(""),[c,d]=x.useState(null),[f,m]=x.useState(vc),[g,h]=x.useState([]),[b,_]=x.useState(""),[j,E]=x.useState(!1),[y,k]=x.useState(!0),[N,w]=x.useState(!0),[S,R]=x.useState(!1),[A,T]=x.useState(""),[z,M]=x.useState(!1),L=x.useRef(null),[P,B]=Uo(),D=x.useRef(!1),[$,q]=x.useState([]),[G,U]=x.useState("chat"),V=x.useCallback(je=>{R(!0),T(je)},[]);x.useEffect(()=>{!o&&a.length&&l(String(a[0].id))},[o,a]);const X=Be(o?["code-sessions",o]:null,()=>Ya.sessions.list(o)),Q=Be(o?["agents",o]:null,()=>an.list(o)),W=Be(o&&c?["code-session",o,c]:null,()=>Ya.sessions.get(o,c)),I=Be(o&&c?["code-changes",o,c]:null,()=>Ya.changes(o,c));x.useEffect(()=>{const je=X.data||[];!c&&je.length&&d(je[0].id),c&&je.length&&!je.some(ze=>ze.id===c)&&d(je[0]?.id??null)},[X.data,c]),x.useEffect(()=>{W.data&&m(W.data.agentSlug||vc)},[W.data]),x.useEffect(()=>{j||(W.data?h(W.data.messages||[]):c||h([]))},[W.data,c,j]),x.useEffect(()=>()=>L.current?.abort(),[]);const K=W.data,ee=K?.mode==="plan"?"plan":"build",F=K?.model||"",ne=je=>{je===o||j||(l(je),d(null),h([]))},Z=je=>{j||je===c||(d(je),h([]))},fe=async()=>{if(!(!o||j))try{const je=await Ya.sessions.create(o,{title:u("code_module.untitled"),agentSlug:f!==vc?f:null});await X.mutate(),d(je.id),h([])}catch(je){e.error(je.message)}},Y=async(je,ze)=>{const Ye=window.prompt(u("code_module.rename"),ze);if(!(!Ye||Ye===ze))try{await Ya.sessions.update(o,je,{title:Ye}),await X.mutate(),je===c&&await W.mutate()}catch(We){e.error(We.message)}},oe=async je=>{if(!j&&window.confirm(u("code_module.delete_confirm")))try{await Ya.sessions.remove(o,je),je===c&&(d(null),h([])),await X.mutate()}catch(ze){e.error(ze.message)}},ve=async je=>{if(m(je),!!c)try{await Ya.sessions.update(o,c,{agentSlug:je!==vc?je:null}),await Promise.all([W.mutate(),X.mutate()])}catch(ze){e.error(ze.message)}},le=x.useCallback(async je=>{if(c)try{await Ya.sessions.update(o,c,je),await Promise.all([W.mutate(),X.mutate()])}catch(ze){e.error(ze.message)}},[o,c,W,X,e]),xe=()=>{L.current?.abort(),E(!1)},ke=je=>h(ze=>{const Ye=[...ze],We=Ye[Ye.length-1];return We&&We.role==="assistant"&&(Ye[Ye.length-1]=je(We)),Ye}),Re=async je=>{const ze=(je??b).trim();if(!ze||j||!o||!c)return;const Ye=new Date().toISOString();h(Rt=>[...Rt,{role:"user",parts:[{kind:"text",text:ze}],ts:Ye},{role:"assistant",parts:[],ts:Ye,pending:!0}]),_(""),E(!0);const We=new AbortController;L.current=We;const dt=Rt=>{if(Rt.type==="error"){e.error(Rt.error||u("modules_ui.code_stream_error"));return}ke(Qt=>ev(Qt,Rt))};try{await Ya.stream(o,c,{prompt:ze},dt,We.signal),ke(Rt=>({...Rt,pending:!1}))}catch(Rt){We.signal.aborted?ke(Qt=>({...Qt,pending:!1,parts:[...Qt.parts,{kind:"text",text:u("code_module.stopped")}]})):(e.error(Rt.message),h(Qt=>Qt.filter((ot,Pt)=>Pt!==Qt.length-1)))}finally{L.current===We&&(L.current=null),E(!1),W.mutate(),X.mutate(),I.mutate()}},Ae=async je=>{try{await navigator.clipboard.writeText(je),e.info(u("modules_ui.code_copied"))}catch{}},Ie=x.useCallback(je=>{U(je),q(ze=>ze.some(Ye=>Ye.path===je)?ze:[...ze,{path:je,content:"",loading:!0}]),se.post("/run",{cmd:`cat "${je}"`,project:o}).then(ze=>{const Ye=ze.stdout||ze.stderr||u("modules_ui.code_file_empty");q(We=>We.map(dt=>dt.path===je?{...dt,content:Ye,loading:!1}:dt))}).catch(ze=>{q(Ye=>Ye.map(We=>We.path===je?{...We,content:u("modules_ui.code_file_error",{msg:ze.message}),loading:!1}:We))})},[o]),Oe=x.useCallback(je=>{q(ze=>ze.filter(Ye=>Ye.path!==je)),U(ze=>ze===je?"chat":ze)},[]),Te=x.useCallback(je=>{const ze=`artifacts/${je}`;U(ze),q(Ye=>Ye.some(We=>We.path===ze)?Ye:[...Ye,{path:ze,content:"",loading:!0,artifactName:je}]),Ws.read(o,je).then(Ye=>{q(We=>We.map(dt=>dt.path===ze?{...dt,content:Ye.content,loading:!1}:dt))}).catch(Ye=>{q(We=>We.map(dt=>dt.path===ze?{...dt,content:u("modules_ui.code_file_error",{msg:Ye.message}),loading:!1}:dt))})},[o]);x.useEffect(()=>{if(D.current)return;const je=P.get("pid"),ze=P.get("cmd"),Ye=P.get("edit");if(!(!je||!ze&&!Ye)){if(String(o)!==String(je)){l(String(je));return}D.current=!0,Ye&&Te(Ye),ze&&V(ze.endsWith(" ")?ze:ze+" "),B({},{replace:!0})}},[P,o,Te,V,B]);const Ne=x.useCallback(async(je,ze)=>{const Ye=$.find(We=>We.path===je);if(Ye?.artifactName)try{await Ws.write(o,Ye.artifactName,ze),q(We=>We.map(dt=>dt.path===je?{...dt,content:ze}:dt)),e.info(u("modules_ui.code_saved"))}catch(We){e.error(We.message)}},[$,o,e]),Me=!t.isLoading&&a.length>0,De=x.useMemo(()=>{const je=[{value:vc,label:u("modules_ui.code_super_agent"),icon:rn,description:u("modules_ui.code_super_agent_desc")}],ze=(Q.data||[]).map(Ye=>({value:Ye.slug,label:Ye.slug,icon:rn,description:Ye.description||Ye.role||void 0}));return[...je,...ze]},[Q.data]),Ue=x.useMemo(()=>g,[g]),Xe=x.useMemo(()=>X.data?.find(je=>je.id===c)?.title||"",[X.data,c]),me=x.useMemo(()=>a.find(je=>String(je.id)===o),[a,o]);xL(Xe);const[de,Le]=x.useState(null),ye=j?null:IE(g),Ce=ye&&ye.turnKey!==de,Qe=je=>{Re(je)},Ge=x.useCallback(()=>k(je=>!je),[]),lt=x.useCallback(()=>M(je=>!je),[]),Tt=x.useCallback(()=>R(je=>!je),[]),_t=x.useCallback(()=>w(je=>!je),[]),Ct=x.useMemo(()=>c?n.jsx("div",{className:"flex items-center gap-0.5",children:[{Icon:aS,open:y,toggle:Ge,title:u("modules_ui.code_panel_sessions")},{Icon:hb,open:z,toggle:lt,title:u("modules_ui.code_panel_tree")},{Icon:ya,open:S,toggle:Tt,title:u("modules_ui.code_panel_terminal")},{Icon:iM,open:N,toggle:_t,title:u("modules_ui.code_panel_context")}].map(({Icon:je,open:ze,toggle:Ye,title:We})=>n.jsx(qe,{content:We,children:n.jsx("button",{type:"button",onClick:Ye,"data-active":ze,className:"rounded p-1 text-muted-fg transition-colors hover:bg-accent hover:text-accent-fg data-[active=true]:bg-accent data-[active=true]:text-accent-fg",children:n.jsx(je,{className:"size-3.5"})})},We))}):null,[c,y,z,S,N,Ge,lt,Tt,_t]);return _L(Ct),n.jsx("div",{className:"flex h-full min-h-0 flex-col","data-testid":"screen-code",children:t.isLoading?n.jsx(st,{}):Me?n.jsxs(tb,{orientation:"vertical",id:"code-layout-v",className:"min-h-0 flex-1",children:[n.jsx(Eo,{id:"top",defaultSize:S?"55%":"100%",minSize:"20%",children:n.jsxs(tb,{orientation:"horizontal",id:"code-layout",className:"h-full",children:[y&&n.jsxs(n.Fragment,{children:[n.jsx(Eo,{id:"left",defaultSize:"14%",minSize:"8%",children:n.jsxs("aside",{className:"flex h-full flex-col",children:[n.jsx("div",{className:"shrink-0 border-b border-border p-2",children:n.jsx(jU,{projects:a,value:o,onChange:ne,disabled:j})}),n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:n.jsx(kU,{sessions:X.data||[],activeId:c,busy:j,onSelect:Z,onCreate:fe,onRename:Y,onDelete:oe})}),n.jsx("div",{className:"shrink-0 border-t border-border p-2",children:n.jsx(ct,{value:f,onChange:ve,options:De,disabled:j,showIcon:!0})})]})}),n.jsx(ax,{})]}),z&&n.jsxs(n.Fragment,{children:[n.jsx(Eo,{id:"tree",defaultSize:"13%",minSize:"8%",children:n.jsx("div",{className:"h-full",children:n.jsx(IU,{pid:o,projectPath:me?.path,onOpenFile:Ie})})}),n.jsx(ax,{})]}),n.jsx(Eo,{id:"main",defaultSize:"50%",minSize:"20%",children:n.jsxs("div",{className:"flex h-full flex-col",children:[$.length>0&&n.jsxs("div",{className:"flex shrink-0 items-center gap-0 overflow-x-auto border-b border-border",children:[n.jsxs("button",{type:"button",onClick:()=>U("chat"),"data-active":G==="chat",className:"flex shrink-0 items-center gap-1.5 border-r border-border px-3 py-2 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-accent/40 data-[active=true]:text-foreground",children:[n.jsx(bb,{className:"size-3 shrink-0"}),u("modules_ui.code_chat_tab")]}),$.map(je=>{const ze=je.path.split("/").pop()??je.path,Ye=G===je.path;return n.jsxs("div",{"data-active":Ye,className:"group flex shrink-0 items-center gap-1 border-r border-border px-2 py-2 text-[11px] text-muted-foreground transition-colors hover:bg-accent/40 data-[active=true]:text-foreground",children:[n.jsx(qe,{content:je.path,children:n.jsx("button",{type:"button",onClick:()=>U(je.path),className:"min-w-0 max-w-[140px] truncate font-mono",children:ze})}),n.jsx(qe,{content:u("code_module.close"),children:n.jsx("button",{type:"button",onClick:()=>Oe(je.path),className:"shrink-0 rounded p-0.5 opacity-60 hover:bg-accent hover:opacity-100",children:n.jsx(gs,{className:"size-2.5"})})})]},je.path)})]}),G==="chat"?n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto","data-testid":"code-transcript",children:c?g.length?n.jsx(tv,{msgs:g,onCopy:Ae}):n.jsx("div",{className:"grid h-full place-items-center p-6",children:n.jsx(ft,{children:u("code_module.empty_chat")})}):n.jsx("div",{className:"grid h-full place-items-center p-6",children:n.jsx(ft,{children:u("code_module.pick_project")})})}),Ce&&ye&&n.jsx(LE,{turnKey:ye.turnKey,questions:ye.questions,onSubmit:Qe,onDismiss:()=>Le(ye.turnKey),disabled:j})]}):n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:(()=>{const je=$.find(ze=>ze.path===G);return je?n.jsx(BU,{path:je.path,content:je.content,loading:je.loading,onSave:je.artifactName?ze=>Ne(je.path,ze):void 0}):null})()}),n.jsx("div",{className:"shrink-0 border-t border-border p-2","data-testid":"code-input",children:n.jsx(SU,{value:b,onValueChange:_,onSubmit:()=>void Re(),onStop:xe,busy:j,disabled:!c,mode:ee,onModeChange:je=>void le({mode:je}),model:F,onModelChange:je=>void le({model:je||null})})})]})}),N&&n.jsxs(n.Fragment,{children:[n.jsx(ax,{}),n.jsx(Eo,{id:"right",defaultSize:"22%",minSize:"15%",children:n.jsx("aside",{className:"flex h-full flex-col",children:n.jsx(PU,{pid:o,turns:Ue,changes:I.data,changesLoading:I.isLoading,onRefreshChanges:()=>void I.mutate(),session:W.data?{title:W.data.title,mode:W.data.mode,createdAt:W.data.createdAt,updatedAt:W.data.updatedAt,agentSlug:W.data.agentSlug??null}:null,onRunInTerminal:V,onEditArtifact:Te})})})]})]})}),S&&o&&n.jsxs(n.Fragment,{children:[n.jsx(UU,{}),n.jsx(Eo,{id:"terminal",defaultSize:"45%",minSize:"10%",maxSize:"80%",children:n.jsx($U,{pid:o,initCmd:A,onClose:Tt,className:"h-full"})})]})]}):n.jsx("div",{className:"grid flex-1 place-items-center",children:n.jsx(ft,{children:u("code_module.no_projects")})})})}function HU({open:e,onClose:t}){const{mutate:a}=fN(),o=Pn(),l=Je(),[c,d]=x.useState(""),[f,m]=x.useState(!1),[g,h]=x.useState(""),[b,_]=x.useState([]),[j,E]=x.useState(null),[y,k]=x.useState(""),[N,w]=x.useState(!1),[S,R]=x.useState(!1),A=async(M,L=!1)=>{w(!0),k("");try{const P=await Nf.dirs(M||"~");h(P.path),d(P.path),E(P.parent),_(P.entries)}catch(P){const B=P.message;k(B),L||l.error(B)}finally{w(!1)}};x.useEffect(()=>{e||(d(""),m(!1),h(""),_([]),E(null),k(""))},[e]);const T=async()=>{w(!0);try{const M=await Nf.pickDir(u("add_project.picker_prompt"));if("cancelled"in M)return;d(M.path);return}catch{m(!0),await A(c||"~")}finally{w(!1)}},z=async()=>{const M=c.trim();if(!M){l.error(u("add_project.path_required"));return}R(!0);try{const L=await Zn.register(M);l.success(u("add_project.registered",{id:L.id})),await a("/projects"),t(),o(`/p/${L.id}`)}catch(L){l.error(L.message)}finally{R(!1)}};return n.jsx(Xt,{open:e,onClose:t,title:u("add_project.title"),description:u("add_project.subtitle"),footer:n.jsxs(n.Fragment,{children:[n.jsx(re,{variant:"ghost",onClick:t,disabled:S,children:u("common.cancel")}),n.jsx(re,{variant:"primary",onClick:z,loading:S,children:u("add_project.register")})]}),children:n.jsxs("div",{className:"space-y-3",children:[n.jsx(ie,{label:u("add_project.path_label"),hint:u("add_project.path_hint"),children:n.jsxs("div",{className:"flex gap-2",children:[n.jsx(Ee,{autoFocus:!0,placeholder:u("add_project.path_placeholder"),value:c,onChange:M=>d(M.target.value),onKeyDown:M=>{M.key==="Enter"&&z()}}),n.jsxs(re,{onClick:T,disabled:N,children:[n.jsx(ql,{size:14})," ",u("add_project.search_btn")]})]})}),f&&n.jsxs("div",{className:"rounded-md border border-border bg-muted/20",children:[n.jsxs("div",{className:"flex items-center justify-between border-b border-border px-3 py-2",children:[n.jsx("span",{className:"truncate font-mono text-xs text-muted-fg",children:g||c||"~"}),n.jsxs("div",{className:"flex gap-1",children:[n.jsx(re,{size:"sm",variant:"ghost",onClick:()=>A("~"),disabled:N,children:n.jsx(eS,{size:13})}),n.jsx(re,{size:"sm",variant:"ghost",onClick:()=>j&&A(j),disabled:!j||N,children:".."}),n.jsx(re,{size:"sm",variant:"ghost",onClick:()=>m(!1),disabled:N,children:n.jsx(gs,{size:13})})]})]}),n.jsxs("div",{className:"max-h-64 overflow-y-auto p-2",children:[N&&n.jsx(st,{}),!N&&y&&n.jsx(ft,{children:u("add_project.browser_unavailable")}),!N&&!y&&b.length===0&&n.jsx(ft,{children:u("add_project.no_folders")}),!N&&!y&&b.map(M=>n.jsxs("button",{type:"button",onClick:()=>A(M),className:"flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-accent",children:[n.jsx(qo,{size:14,className:"text-muted-fg"}),n.jsx("span",{className:"truncate",children:M.split("/").pop()}),n.jsx("span",{className:"ml-auto truncate font-mono text-[10px] text-muted-fg",children:M})]},M))]})]})]})})}function VU({onPaired:e}){const[t,a]=x.useState(""),[o,l]=x.useState(FU()),[c,d]=x.useState(!1),[f,m]=x.useState(null);async function g(){const h=t.trim();if(!h){m(u("pairing.err_required"));return}d(!0),m(null);try{const b=await ri.confirm({pairing_id:h,label:o.trim()||void 0});Ro(b.token);try{localStorage.setItem(On.token,b.token)}catch{}e()}catch(b){m(GU(b)),d(!1)}}return n.jsx("div",{className:"flex min-h-[100dvh] w-full items-center justify-center overflow-y-auto bg-background p-4 text-foreground",children:n.jsxs("div",{className:"my-auto w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-sm",children:[n.jsxs("div",{className:"mb-4 flex items-center gap-3",children:[n.jsx("div",{className:"grid size-10 place-items-center rounded-lg bg-primary/10 text-primary",children:n.jsx(tS,{size:20})}),n.jsxs("div",{children:[n.jsx("h1",{className:"text-base font-semibold",children:u("pairing.title")}),n.jsx("p",{className:"text-xs text-muted-fg",children:u("pairing.subtitle")})]})]}),n.jsxs("ol",{className:"mb-5 space-y-1.5 rounded-lg bg-muted/50 p-3 text-xs text-muted-fg",children:[n.jsx("li",{className:"font-medium text-foreground",children:u("pairing.steps_title")}),n.jsxs("li",{children:["1. ",u("pairing.step_1")]}),n.jsxs("li",{children:["2. ",u("pairing.step_2")]}),n.jsxs("li",{children:["3. ",u("pairing.step_3")]})]}),n.jsxs("form",{className:"space-y-3",onSubmit:h=>{h.preventDefault(),g()},children:[n.jsx(ie,{label:u("pairing.code_label"),children:n.jsx(Ee,{value:t,onChange:h=>a(h.target.value),placeholder:u("pairing.code_ph"),spellCheck:!1,autoComplete:"off"})}),n.jsx(ie,{label:u("pairing.label_label"),hint:u("pairing.revoke_hint"),children:n.jsx(Ee,{value:o,onChange:h=>l(h.target.value),placeholder:u("pairing.label_ph")})}),f&&n.jsx("p",{className:"rounded-md bg-destructive/10 px-3 py-2 text-xs text-destructive",children:f}),n.jsx(re,{type:"submit",variant:"primary",size:"md",loading:c,className:"w-full justify-center",children:u(c?"pairing.linking":"pairing.submit")})]})]})})}function FU(){const e=navigator.userAgent;return/iPhone|iPad/.test(e)?"iPhone":/Android/.test(e)?"Android":/Mac/.test(e)?"Mac":/Windows/.test(e)?"Windows PC":/Linux/.test(e)?"Linux":"browser"}function GU(e){if(e instanceof lu){if(e.status===410)return u("pairing.err_expired");if(e.status===404||e.status===409)return u("pairing.err_unknown")}return u("pairing.err_generic")}function YU({...e}){return n.jsx(SN,{"data-slot":"sheet",...e})}function KU({...e}){return n.jsx(wN,{"data-slot":"sheet-portal",...e})}function XU({className:e,...t}){return n.jsx(vN,{"data-slot":"sheet-overlay",className:St("fixed inset-0 z-50 bg-black/10 transition-opacity duration-150 data-ending-style:opacity-0 data-starting-style:opacity-0 supports-backdrop-filter:backdrop-blur-xs",e),...t})}function QU({className:e,children:t,side:a="right",showCloseButton:o=!0,...l}){return n.jsxs(KU,{children:[n.jsx(XU,{}),n.jsxs(kN,{"data-slot":"sheet-content","data-side":a,className:St("fixed z-50 flex flex-col gap-4 bg-popover bg-clip-padding text-sm text-popover-foreground shadow-lg transition duration-200 ease-in-out data-ending-style:opacity-0 data-starting-style:opacity-0 data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=bottom]:data-ending-style:translate-y-[2.5rem] data-[side=bottom]:data-starting-style:translate-y-[2.5rem] data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=left]:border-r data-[side=left]:data-ending-style:translate-x-[-2.5rem] data-[side=left]:data-starting-style:translate-x-[-2.5rem] data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-3/4 data-[side=right]:border-l data-[side=right]:data-ending-style:translate-x-[2.5rem] data-[side=right]:data-starting-style:translate-x-[2.5rem] data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-[side=top]:data-ending-style:translate-y-[-2.5rem] data-[side=top]:data-starting-style:translate-y-[-2.5rem] data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm",e),...l,children:[t,o&&n.jsxs(wp,{"data-slot":"sheet-close",render:n.jsx(or,{variant:"ghost",className:"absolute top-3 right-3",size:"icon-sm"}),children:[n.jsx(gs,{}),n.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function WU({className:e,...t}){return n.jsx("div",{"data-slot":"sheet-header",className:St("flex flex-col gap-0.5 p-4",e),...t})}function ZU({className:e,...t}){return n.jsx(CN,{"data-slot":"sheet-title",className:St("font-heading text-base font-medium text-foreground",e),...t})}function JU({className:e,...t}){return n.jsx(yN,{"data-slot":"sheet-description",className:St("text-sm text-muted-foreground",e),...t})}function eq({value:e,projectPath:t,onPick:a}){const o=tq(e),l=o?nq(e):"",{data:c}=Be(o?["/skills",t||""]:null,()=>Us.list(t)),d=c?.skills||[],f=x.useMemo(()=>{const m=l.toLowerCase();return m?d.filter(g=>g.slug.toLowerCase().includes(m)).slice(0,8):d.slice(0,8)},[d,l]);return!o||f.length===0?null:n.jsxs("div",{className:"rounded-xl border border-border bg-popover/95 text-sm shadow-md backdrop-blur",children:[n.jsx("ul",{role:"listbox",className:"max-h-64 overflow-y-auto py-1",children:f.map(m=>n.jsx("li",{children:n.jsxs("button",{type:"button",onClick:()=>a(m.slug),className:"flex w-full items-start gap-2 px-3 py-1.5 text-left hover:bg-accent hover:text-accent-foreground",children:[n.jsxs("code",{className:"rounded bg-muted px-1.5 py-0.5 text-[11px]",children:["/",m.slug]}),n.jsx("span",{className:"truncate text-xs text-muted-foreground",children:m.description})]})},m.slug))}),n.jsx("div",{className:"border-t border-border px-3 py-1.5 text-[10px] text-muted-foreground",children:"Type a name to filter · click to insert · the skill body will be loaded for this turn."})]})}function tq(e){return!!e.match(/^\s*\/([A-Za-z0-9_-]*)$/)}function nq(e){const t=e.match(/^\s*\/([A-Za-z0-9_-]*)$/);return t?t[1]:""}function sq(){try{const e=localStorage.getItem(On.robyChat);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(a=>a&&Array.isArray(a.parts)&&!a.pending):[]}catch{return[]}}function aq({open:e,onOpenChange:t}){const a=yp(),o=Je(),[l,c]=x.useState(sq),[d,f]=x.useState(""),[m,g]=x.useState(!1),[h,b]=x.useState(""),_=x.useRef(null);x.useEffect(()=>{const w=l.filter(S=>!S.pending);try{w.length?localStorage.setItem(On.robyChat,JSON.stringify(w)):localStorage.removeItem(On.robyChat)}catch{}},[l]);const j=()=>{if(!m){c([]),f("");try{localStorage.removeItem(On.robyChat)}catch{}}};x.useEffect(()=>()=>_.current?.abort(),[]),x.useEffect(()=>{const w=S=>{const R=S.detail?.prompt;typeof R=="string"&&(t(!0),f(R))};return window.addEventListener("apx:roby-prompt",w),()=>window.removeEventListener("apx:roby-prompt",w)},[t]);const E=()=>{_.current?.abort(),g(!1)},y=w=>c(S=>{const R=[...S],A=R[R.length-1];return A?.role==="assistant"&&(R[R.length-1]=w(A)),R}),k=async()=>{const w=d.trim();if(!w||m)return;const S=new Date().toISOString(),R=l.filter(M=>!M.pending).map(M=>({role:M.role,content:Qx(M)}));c(M=>[...M,{role:"user",parts:[{kind:"text",text:w}],ts:S},{role:"assistant",parts:[],ts:S,pending:!0}]),f(""),g(!0);const A=new AbortController;_.current=A;let T=!1;const z=M=>{if(M?.type==="error"){T=!0,o.error(M.error||"error"),c(L=>{const P=[...L],B=P[P.length-1];return B?.role==="assistant"&&B.pending&&P.pop(),P});return}y(L=>ev(L,M))};try{await mN.stream(0,{prompt:w,previousMessages:R,model:h||void 0,channel:"web_sidebar"},z,A.signal),y(M=>({...M,pending:!1}))}catch(M){A.signal.aborted?y(L=>({...L,pending:!1,parts:[...L.parts,{kind:"text",text:u("project.chat.stopped_marker")}]})):T||(o.error(M.message),c(L=>{const P=[...L],B=P[P.length-1];return B?.role==="assistant"&&B.pending&&P.pop(),P}))}finally{_.current===A&&(_.current=null),g(!1)}},N=async w=>{try{await navigator.clipboard.writeText(w),o.info(u("project.chat.copied"))}catch{}};return n.jsx(YU,{open:e,onOpenChange:t,children:n.jsxs(QU,{side:"right",className:"flex w-full flex-col gap-0 p-0 sm:max-w-xl data-[side=right]:sm:max-w-xl",children:[n.jsxs(WU,{className:"pr-12",children:[n.jsxs(ZU,{className:"flex items-center gap-2",children:[n.jsx(rn,{size:18})," ",u("superagent.title",{persona:a}),n.jsx("span",{className:"text-xs font-normal text-muted-fg",children:u("superagent.badge")})]}),n.jsx(JU,{children:u("superagent.desc")})]}),n.jsx("div",{className:"flex-1 overflow-y-auto",children:l.length===0?n.jsx("p",{className:"mt-6 text-center text-sm text-muted-fg",children:u("superagent.empty",{persona:a})}):n.jsx(tv,{msgs:l,onCopy:N})}),n.jsx(PE,{msgs:l}),n.jsxs("div",{className:"border-t border-border p-3",children:[n.jsx("div",{className:"mb-1.5",children:n.jsx(eq,{value:d,onPick:w=>f(`/${w} `)})}),n.jsx(Z_,{value:d,onValueChange:f,onSubmit:()=>void k(),onStop:E,busy:m,placeholder:u("superagent.placeholder"),footer:n.jsx(J_,{value:h,onChange:b,disabled:m})}),n.jsx("div",{className:"mt-1.5 flex justify-end",children:n.jsxs(or,{size:"xs",variant:"ghost",onClick:j,disabled:m||l.length===0,children:[n.jsx(Dt,{className:"size-3"})," ",u("superagent.new_chat")]})})]})]})})}function rq(){const e=navigator.userAgent;return/iPhone|iPad/.test(e)?"iPhone":/Android/.test(e)?"Android":/Mac/.test(e)?"Mac":/Windows/.test(e)?"Windows PC":/Linux/.test(e)?"Linux":"browser"}function oq(){const[e,t]=x.useState({status:"loading"}),[a,o]=x.useState(0),l=x.useCallback(()=>{t({status:"loading"}),o(c=>c+1)},[]);return x.useEffect(()=>{let c=!1;return(async()=>{try{const h=await fetch("/health");if(!h.ok)throw new Error(`HTTP ${h.status}`)}catch(h){c||t({status:"error",reason:String(h)});return}const d=window.location.hash.replace(/^#/,""),f=new URLSearchParams(d),m=f.get("pair");if(m){history.replaceState(null,"",window.location.pathname+window.location.search);try{const h=await ri.confirm({pairing_id:m,label:rq(),kind:"web"});Ro(h.token);try{localStorage.setItem(On.token,h.token)}catch{}c||t({status:"ok"});return}catch{}}const g=f.get("token");if(g){Ro(g);try{localStorage.setItem(On.token,g)}catch{}history.replaceState(null,"",window.location.pathname+window.location.search)}else try{const h=localStorage.getItem(On.token);h&&Ro(h)}catch{}try{const h=await fetch("/admin/web-token");if(h.ok){const b=await h.json();if(b?.token){Ro(b.token);try{localStorage.setItem(On.token,b.token)}catch{}}}}catch{}if(!R_()){c||t({status:"unpaired"});return}try{await se.get("/projects"),c||t({status:"ok"})}catch(h){if(h instanceof lu&&(h.status===401||h.status===403)){Ro(null);try{localStorage.removeItem(On.token)}catch{}c||t({status:"unpaired"})}else c||t({status:"error",reason:String(h)})}})(),()=>{c=!0}},[a]),{...e,reload:l}}function lq(){const e=oq();return e.status==="loading"?n.jsx(x2,{text:u("daemon.connecting")}):e.status==="error"?n.jsx(x2,{mood:"sad",text:u("daemon.unreachable"),sub:`${u("daemon.unreachable_hint")}
|
|
822
822
|
|
|
823
823
|
${e.reason}`}):e.status==="unpaired"?n.jsx(VU,{onPaired:e.reload}):n.jsx(iL,{children:n.jsx(v6,{delay:0,children:n.jsx(iq,{})})})}function iq(){const e=Pn(),t=ns(),[a,o]=Uo(),{theme:l,toggle:c}=Nb(),d=a.get("action")==="add-project",[f,m]=x.useState(!1),g=()=>{const b=new URLSearchParams(a);b.delete("action"),o(b,{replace:!0})},h=()=>{const b=new URLSearchParams(a);b.set("action","add-project"),o(b)};return n.jsx(pL,{children:n.jsxs("div",{className:"flex h-screen w-screen overflow-hidden bg-background text-foreground","data-testid":"app-shell",children:[n.jsx(yP,{onSelect:b=>e(b),onOpenRoby:()=>m(!0),onOpenAddProject:h}),n.jsxs("main",{className:"m-2 flex min-w-0 flex-1 flex-col overflow-hidden rounded-xl border border-border bg-card shadow-sm",children:[n.jsx(cq,{onToggleTheme:c,isDark:l==="dark",pathname:t.pathname}),n.jsx("div",{className:"flex-1 overflow-y-auto",children:n.jsxs(I2,{children:[n.jsx(Ot,{path:"/",element:n.jsx(fL,{})}),n.jsx(Ot,{path:"/settings/*",element:n.jsx(O$,{})}),n.jsx(Ot,{path:"/m/desktop/*",element:n.jsx(L$,{})}),n.jsx(Ot,{path:"/m/code/*",element:n.jsx(qU,{})}),n.jsx(Ot,{path:"/p/:pid/*",element:n.jsx(Z9,{})}),n.jsx(Ot,{path:"*",element:n.jsx(mq,{})})]})})]}),n.jsx(HU,{open:d,onClose:g}),n.jsx(aq,{open:f,onOpenChange:m})]})})}function cq({onToggleTheme:e,isDark:t,pathname:a}){const{projects:o}=iu(),l=hL(),c=a.split("/").filter(Boolean),d=c[0]==="p"?o.find(E=>String(E.id)===c[1]):void 0,f=c[0]==="settings"?fq(c[1]):c[0]==="p"?pq(c[2]):"",m=c[0]==="p"&&c[1]==="0",g=d?.name||d?.path?.split("/").pop()||u("nav.project"),h=a==="/"?u("topbar.breadcrumb_root"):c[0]==="settings"?[u("topbar.breadcrumb_root"),u("nav.settings"),f].filter(Boolean).join(" › "):c[0]==="m"?[u("topbar.breadcrumb_root"),dq(c[1]),l].filter(Boolean).join(" › "):c[0]==="p"?m?[u("topbar.breadcrumb_root"),u("topbar.breadcrumb_base"),f].filter(Boolean).join(" › "):[u("topbar.breadcrumb_root"),u("topbar.breadcrumb_projects"),g,f].filter(Boolean).join(" › "):u("topbar.breadcrumb_root"),b=a==="/"?"":c[0]==="settings"?u("settings.subtitle"):c[0]==="p"?m?u("base.subtitle"):d?`${hN(d.kind)} · ${d.path}`:"":"",_=mL(),j=bL();return n.jsxs("header",{className:"flex h-10 shrink-0 items-center gap-2 border-b border-border/50 px-3",children:[_&&n.jsx(TD,{collapsed:_.collapsed,onToggle:_.toggle}),n.jsxs("span",{className:"min-w-0 flex-1 truncate text-[11px] tracking-wide text-muted-fg",children:[h,b&&n.jsxs("span",{className:"text-muted-fg/50",children:[" · ",b]})]}),j,n.jsx(uq,{}),n.jsx(qe,{content:u(t?"topbar.light":"topbar.dark"),children:n.jsx("button",{type:"button","data-testid":"theme-toggle",onClick:e,className:"shrink-0 rounded-md p-1.5 text-muted-fg hover:bg-accent hover:text-accent-fg",children:t?n.jsx(bM,{size:14}):n.jsx(rM,{size:14})})})]})}function uq(){const e=S_(),t=a=>{a!==e&&(nN(a),window.location.reload())};return n.jsxs(y_,{children:[n.jsxs(j_,{"data-testid":"lang-menu",title:u("topbar.lang_toggle"),className:"flex shrink-0 items-center gap-1 rounded-md p-1.5 text-muted-fg hover:bg-accent hover:text-accent-fg",children:[n.jsx(WA,{size:14}),n.jsx("span",{className:"text-[11px] font-medium uppercase",children:e})]}),n.jsx(k_,{align:"end",children:n.jsx(jD,{value:e,onValueChange:a=>t(a),children:sN.map(a=>n.jsx(kD,{value:a.value,children:a.label},a.value))})})]})}function dq(e){switch(e){case"desktop":return u("nav.modules.desktop");case"code":return u("nav.modules.code");default:return e||""}}function fq(e){switch(e){case"super-agent":return u("settings.tabs.super_agent");case"engines":return u("settings.tabs.engines");case"telegram":return u("settings.tabs.telegram");case"devices":return u("settings.tabs.devices");case"voice":return u("nav.modules.voice");case"deck":return u("nav.modules.deck");case"desktop":return u("nav.modules.desktop");case"appearance":return u("settings.appearance");case"config":case"advanced":return u("settings.tabs.advanced");case"identity":default:return e||""}}function pq(e){switch(e){case"chat":return u("project.nav.chat");case"telegram":return u("project.nav.telegram");case"agents":return u("project.nav.agents");case"routines":return u("project.nav.routines");case"tasks":return u("project.nav.tasks");case"mcps":return u("project.nav.mcps");case"artifacts":return u("project.nav.artifacts");case"config":return u("project.nav.config");case"workspaces":return u("base.workspaces_title");case"models":return u("settings.tabs.engines");case"agent-defaults":return u("base.defaults_title");case"sessions":return u("base.sessions_title");case"logs":return u("project.nav.logs");case"memories":return u("project.nav.memories");default:return""}}function x2({text:e,sub:t,mood:a="happy"}){return n.jsx("div",{className:"grid h-screen w-screen place-items-center bg-background text-foreground",children:n.jsxs("div",{className:"flex flex-col items-center text-center",children:[n.jsx($N,{mood:a,className:"mb-4 text-xs"}),n.jsx("div",{className:"text-foreground",children:e}),t&&n.jsx("pre",{className:"mt-2 max-w-xl whitespace-pre-wrap text-sm text-muted-fg",children:t})]})})}function mq(){const e=Pn();return n.jsx(UN,{testId:"screen-not-found",mood:"confused",title:u("not_found.title"),titleClassName:"text-7xl",message:u("not_found.message"),action:n.jsx(or,{variant:"outline",onClick:()=>e("/"),children:u("not_found.home")})})}cI();O5.createRoot(document.getElementById("root")).render(n.jsx(Kc.StrictMode,{children:n.jsx(aA,{children:n.jsx(SM,{children:n.jsx(lq,{})})})}));
|
|
824
|
-
//# sourceMappingURL=index-
|
|
824
|
+
//# sourceMappingURL=index-Bjlk9ttU.js.map
|