@khanglvm/llm-router 2.2.4 → 2.2.6

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.
@@ -48,7 +48,7 @@ Error generating stack: `+r.message+`
48
48
  .allow-interactivity-`).concat(e,` {pointer-events: all;}
49
49
  `)},g_=0,cl=[];function kA(e){var t=pt.useRef([]),n=pt.useRef([0,0]),r=pt.useRef(),a=pt.useState(g_++)[0],o=pt.useState(Os)[0],i=pt.useRef(e);pt.useEffect(function(){i.current=e},[e]),pt.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(a));var g=hA([e.lockRef.current],(e.shards||[]).map(_A),!0).filter(Boolean);return g.forEach(function(x){return x.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),g.forEach(function(x){return x.classList.remove("allow-interactivity-".concat(a))})}}},[e.inert,e.lockRef.current,e.shards]);var s=pt.useCallback(function(g,x){if("touches"in g&&g.touches.length===2||g.type==="wheel"&&g.ctrlKey)return!i.current.allowPinchZoom;var y=sd(g),h=n.current,v="deltaX"in g?g.deltaX:h[0]-y[0],S="deltaY"in g?g.deltaY:h[1]-y[1],C,T=g.target,w=Math.abs(v)>Math.abs(S)?"h":"v";if("touches"in g&&w==="h"&&T.type==="range")return!1;var R=window.getSelection(),M=R&&R.anchorNode,k=M?M===T||M.contains(T):!1;if(k)return!1;var I=Eg(w,T);if(!I)return!0;if(I?C=w:(C=w==="v"?"h":"v",I=Eg(w,T)),!I)return!1;if(!r.current&&"changedTouches"in g&&(v||S)&&(r.current=C),!C)return!0;var H=r.current||C;return MA(H,x,g,H==="h"?v:S,!0)},[]),c=pt.useCallback(function(g){var x=g;if(!(!cl.length||cl[cl.length-1]!==o)){var y="deltaY"in x?OA(x):sd(x),h=t.current.filter(function(C){return C.name===x.type&&(C.target===x.target||x.target===C.shadowParent)&&m_(C.delta,y)})[0];if(h&&h.should){x.cancelable&&x.preventDefault();return}if(!h){var v=(i.current.shards||[]).map(_A).filter(Boolean).filter(function(C){return C.contains(x.target)}),S=v.length>0?s(x,v[0]):!i.current.noIsolation;S&&x.cancelable&&x.preventDefault()}}},[]),u=pt.useCallback(function(g,x,y,h){var v={name:g,delta:x,target:y,should:h,shadowParent:h_(y)};t.current.push(v),setTimeout(function(){t.current=t.current.filter(function(S){return S!==v})},1)},[]),f=pt.useCallback(function(g){n.current=sd(g),r.current=void 0},[]),d=pt.useCallback(function(g){u(g.type,OA(g),g.target,s(g,e.lockRef.current))},[]),p=pt.useCallback(function(g){u(g.type,sd(g),g.target,s(g,e.lockRef.current))},[]);pt.useEffect(function(){return cl.push(o),e.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:p}),document.addEventListener("wheel",c,Xo),document.addEventListener("touchmove",c,Xo),document.addEventListener("touchstart",f,Xo),function(){cl=cl.filter(function(g){return g!==o}),document.removeEventListener("wheel",c,Xo),document.removeEventListener("touchmove",c,Xo),document.removeEventListener("touchstart",f,Xo)}},[]);var m=e.removeScrollBar,b=e.inert;return pt.createElement(pt.Fragment,null,b?pt.createElement(o,{styles:p_(a)}):null,m?pt.createElement(Cg,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function h_(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var LA=vg(ld,kA);var DA=cd.forwardRef(function(e,t){return cd.createElement(Ms,An({},e,{ref:t,sideCar:LA}))});DA.classNames=Ms.classNames;var Tg=DA;var pe=K(Be(),1),y_=[" ","Enter","ArrowUp","ArrowDown"],v_=[" ","Enter"],Zo="Select",[dd,fd,b_]=Iu(Zo),[ul,CB]=Jn(Zo,[b_,cg]),md=cg(),[x_,io]=ul(Zo),[S_,w_]=ul(Zo),zA=e=>{let{__scopeSelect:t,children:n,open:r,defaultOpen:a,onOpenChange:o,value:i,defaultValue:s,onValueChange:c,dir:u,name:f,autoComplete:d,disabled:p,required:m,form:b}=e,g=md(t),[x,y]=J.useState(null),[h,v]=J.useState(null),[S,C]=J.useState(!1),T=rl(u),[w,R]=pa({prop:r,defaultProp:a??!1,onChange:o,caller:Zo}),[M,k]=pa({prop:i,defaultProp:s,onChange:c,caller:Zo}),I=J.useRef(null),H=x?b||!!x.closest("form"):!0,[Q,ee]=J.useState(new Set),X=Array.from(Q).map(z=>z.props.value).join(";");return(0,pe.jsx)(iA,{...g,children:(0,pe.jsxs)(x_,{required:m,scope:t,trigger:x,onTriggerChange:y,valueNode:h,onValueNodeChange:v,valueNodeHasChildren:S,onValueNodeHasChildrenChange:C,contentId:no(),value:M,onValueChange:k,open:w,onOpenChange:R,dir:T,triggerPointerDownPosRef:I,disabled:p,children:[(0,pe.jsx)(dd.Provider,{scope:t,children:(0,pe.jsx)(S_,{scope:e.__scopeSelect,onNativeOptionAdd:J.useCallback(z=>{ee(te=>new Set(te).add(z))},[]),onNativeOptionRemove:J.useCallback(z=>{ee(te=>{let Y=new Set(te);return Y.delete(z),Y})},[]),children:n})}),H?(0,pe.jsxs)(r1,{"aria-hidden":!0,required:m,tabIndex:-1,name:f,autoComplete:d,value:M,onChange:z=>k(z.target.value),disabled:p,form:b,children:[M===void 0?(0,pe.jsx)("option",{value:""}):null,Array.from(Q)]},X):null]})})};zA.displayName=Zo;var BA="SelectTrigger",IA=J.forwardRef((e,t)=>{let{__scopeSelect:n,disabled:r=!1,...a}=e,o=md(n),i=io(BA,n),s=i.disabled||r,c=Xe(t,i.onTriggerChange),u=fd(n),f=J.useRef("touch"),[d,p,m]=o1(g=>{let x=u().filter(v=>!v.disabled),y=x.find(v=>v.value===i.value),h=i1(x,g,y);h!==void 0&&i.onValueChange(h.value)}),b=g=>{s||(i.onOpenChange(!0),m()),g&&(i.triggerPointerDownPosRef.current={x:Math.round(g.pageX),y:Math.round(g.pageY)})};return(0,pe.jsx)(lA,{asChild:!0,...o,children:(0,pe.jsx)(Oe.button,{type:"button",role:"combobox","aria-controls":i.contentId,"aria-expanded":i.open,"aria-required":i.required,"aria-autocomplete":"none",dir:i.dir,"data-state":i.open?"open":"closed",disabled:s,"data-disabled":s?"":void 0,"data-placeholder":a1(i.value)?"":void 0,...a,ref:c,onClick:Pe(a.onClick,g=>{g.currentTarget.focus(),f.current!=="mouse"&&b(g)}),onPointerDown:Pe(a.onPointerDown,g=>{f.current=g.pointerType;let x=g.target;x.hasPointerCapture(g.pointerId)&&x.releasePointerCapture(g.pointerId),g.button===0&&g.ctrlKey===!1&&g.pointerType==="mouse"&&(b(g),g.preventDefault())}),onKeyDown:Pe(a.onKeyDown,g=>{let x=d.current!=="";!(g.ctrlKey||g.altKey||g.metaKey)&&g.key.length===1&&p(g.key),!(x&&g.key===" ")&&y_.includes(g.key)&&(b(),g.preventDefault())})})})});IA.displayName=BA;var UA="SelectValue",jA=J.forwardRef((e,t)=>{let{__scopeSelect:n,className:r,style:a,children:o,placeholder:i="",...s}=e,c=io(UA,n),{onValueNodeHasChildrenChange:u}=c,f=o!==void 0,d=Xe(t,c.onValueNodeChange);return xt(()=>{u(f)},[u,f]),(0,pe.jsx)(Oe.span,{...s,ref:d,style:{pointerEvents:"none"},children:a1(c.value)?(0,pe.jsx)(pe.Fragment,{children:i}):o})});jA.displayName=UA;var A_="SelectIcon",PA=J.forwardRef((e,t)=>{let{__scopeSelect:n,children:r,...a}=e;return(0,pe.jsx)(Oe.span,{"aria-hidden":!0,...a,ref:t,children:r||"\u25BC"})});PA.displayName=A_;var C_="SelectPortal",VA=e=>(0,pe.jsx)(dg,{asChild:!0,...e});VA.displayName=C_;var Jo="SelectContent",HA=J.forwardRef((e,t)=>{let n=io(Jo,e.__scopeSelect),[r,a]=J.useState();if(xt(()=>{a(new DocumentFragment)},[]),!n.open){let o=r;return o?Lg.createPortal((0,pe.jsx)(qA,{scope:e.__scopeSelect,children:(0,pe.jsx)(dd.Slot,{scope:e.__scopeSelect,children:(0,pe.jsx)("div",{children:e.children})})}),o):null}return(0,pe.jsx)($A,{...e,ref:t})});HA.displayName=Jo;var yr=10,[qA,lo]=ul(Jo),R_="SelectContentImpl",E_=Po("SelectContent.RemoveScroll"),$A=J.forwardRef((e,t)=>{let{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:a,onEscapeKeyDown:o,onPointerDownOutside:i,side:s,sideOffset:c,align:u,alignOffset:f,arrowPadding:d,collisionBoundary:p,collisionPadding:m,sticky:b,hideWhenDetached:g,avoidCollisions:x,...y}=e,h=io(Jo,n),[v,S]=J.useState(null),[C,T]=J.useState(null),w=Xe(t,U=>S(U)),[R,M]=J.useState(null),[k,I]=J.useState(null),H=fd(n),[Q,ee]=J.useState(!1),X=J.useRef(!1);J.useEffect(()=>{if(v)return gA(v)},[v]),qS();let z=J.useCallback(U=>{let[ne,...ue]=H().map(oe=>oe.ref.current),[me]=ue.slice(-1),re=document.activeElement;for(let oe of U)if(oe===re||(oe?.scrollIntoView({block:"nearest"}),oe===ne&&C&&(C.scrollTop=0),oe===me&&C&&(C.scrollTop=C.scrollHeight),oe?.focus(),document.activeElement!==re))return},[H,C]),te=J.useCallback(()=>z([R,v]),[z,R,v]);J.useEffect(()=>{Q&&te()},[Q,te]);let{onOpenChange:Y,triggerPointerDownPosRef:q}=h;J.useEffect(()=>{if(v){let U={x:0,y:0},ne=me=>{U={x:Math.abs(Math.round(me.pageX)-(q.current?.x??0)),y:Math.abs(Math.round(me.pageY)-(q.current?.y??0))}},ue=me=>{U.x<=10&&U.y<=10?me.preventDefault():v.contains(me.target)||Y(!1),document.removeEventListener("pointermove",ne),q.current=null};return q.current!==null&&(document.addEventListener("pointermove",ne),document.addEventListener("pointerup",ue,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",ne),document.removeEventListener("pointerup",ue,{capture:!0})}}},[v,Y,q]),J.useEffect(()=>{let U=()=>Y(!1);return window.addEventListener("blur",U),window.addEventListener("resize",U),()=>{window.removeEventListener("blur",U),window.removeEventListener("resize",U)}},[Y]);let[V,_e]=o1(U=>{let ne=H().filter(re=>!re.disabled),ue=ne.find(re=>re.ref.current===document.activeElement),me=i1(ne,U,ue);me&&setTimeout(()=>me.ref.current.focus())}),F=J.useCallback((U,ne,ue)=>{let me=!X.current&&!ue;(h.value!==void 0&&h.value===ne||me)&&(M(U),me&&(X.current=!0))},[h.value]),he=J.useCallback(()=>v?.focus(),[v]),Z=J.useCallback((U,ne,ue)=>{let me=!X.current&&!ue;(h.value!==void 0&&h.value===ne||me)&&I(U)},[h.value]),ae=r==="popper"?Ng:KA,Se=ae===Ng?{side:s,sideOffset:c,align:u,alignOffset:f,arrowPadding:d,collisionBoundary:p,collisionPadding:m,sticky:b,hideWhenDetached:g,avoidCollisions:x}:{};return(0,pe.jsx)(qA,{scope:n,content:v,viewport:C,onViewportChange:T,itemRefCallback:F,selectedItem:R,onItemLeave:he,itemTextRefCallback:Z,focusSelectedItem:te,selectedItemText:k,position:r,isPositioned:Q,searchRef:V,children:(0,pe.jsx)(Tg,{as:E_,allowPinchZoom:!0,children:(0,pe.jsx)(Zp,{asChild:!0,trapped:h.open,onMountAutoFocus:U=>{U.preventDefault()},onUnmountAutoFocus:Pe(a,U=>{h.trigger?.focus({preventScroll:!0}),U.preventDefault()}),children:(0,pe.jsx)(Yp,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:U=>U.preventDefault(),onDismiss:()=>h.onOpenChange(!1),children:(0,pe.jsx)(ae,{role:"listbox",id:h.contentId,"data-state":h.open?"open":"closed",dir:h.dir,onContextMenu:U=>U.preventDefault(),...y,...Se,onPlaced:()=>ee(!0),ref:w,style:{display:"flex",flexDirection:"column",outline:"none",...y.style},onKeyDown:Pe(y.onKeyDown,U=>{let ne=U.ctrlKey||U.altKey||U.metaKey;if(U.key==="Tab"&&U.preventDefault(),!ne&&U.key.length===1&&_e(U.key),["ArrowUp","ArrowDown","Home","End"].includes(U.key)){let me=H().filter(re=>!re.disabled).map(re=>re.ref.current);if(["ArrowUp","End"].includes(U.key)&&(me=me.slice().reverse()),["ArrowUp","ArrowDown"].includes(U.key)){let re=U.target,oe=me.indexOf(re);me=me.slice(oe+1)}setTimeout(()=>z(me)),U.preventDefault()}})})})})})})});$A.displayName=R_;var T_="SelectItemAlignedPosition",KA=J.forwardRef((e,t)=>{let{__scopeSelect:n,onPlaced:r,...a}=e,o=io(Jo,n),i=lo(Jo,n),[s,c]=J.useState(null),[u,f]=J.useState(null),d=Xe(t,w=>f(w)),p=fd(n),m=J.useRef(!1),b=J.useRef(!0),{viewport:g,selectedItem:x,selectedItemText:y,focusSelectedItem:h}=i,v=J.useCallback(()=>{if(o.trigger&&o.valueNode&&s&&u&&g&&x&&y){let w=o.trigger.getBoundingClientRect(),R=u.getBoundingClientRect(),M=o.valueNode.getBoundingClientRect(),k=y.getBoundingClientRect();if(o.dir!=="rtl"){let re=k.left-R.left,oe=M.left-re,Ne=w.left-oe,Re=w.width+Ne,Ze=Math.max(Re,R.width),gt=window.innerWidth-yr,Vt=Kp(oe,[yr,Math.max(yr,gt-Ze)]);s.style.minWidth=Re+"px",s.style.left=Vt+"px"}else{let re=R.right-k.right,oe=window.innerWidth-M.right-re,Ne=window.innerWidth-w.right-oe,Re=w.width+Ne,Ze=Math.max(Re,R.width),gt=window.innerWidth-yr,Vt=Kp(oe,[yr,Math.max(yr,gt-Ze)]);s.style.minWidth=Re+"px",s.style.right=Vt+"px"}let I=p(),H=window.innerHeight-yr*2,Q=g.scrollHeight,ee=window.getComputedStyle(u),X=parseInt(ee.borderTopWidth,10),z=parseInt(ee.paddingTop,10),te=parseInt(ee.borderBottomWidth,10),Y=parseInt(ee.paddingBottom,10),q=X+z+Q+Y+te,V=Math.min(x.offsetHeight*5,q),_e=window.getComputedStyle(g),F=parseInt(_e.paddingTop,10),he=parseInt(_e.paddingBottom,10),Z=w.top+w.height/2-yr,ae=H-Z,Se=x.offsetHeight/2,U=x.offsetTop+Se,ne=X+z+U,ue=q-ne;if(ne<=Z){let re=I.length>0&&x===I[I.length-1].ref.current;s.style.bottom="0px";let oe=u.clientHeight-g.offsetTop-g.offsetHeight,Ne=Math.max(ae,Se+(re?he:0)+oe+te),Re=ne+Ne;s.style.height=Re+"px"}else{let re=I.length>0&&x===I[0].ref.current;s.style.top="0px";let Ne=Math.max(Z,X+g.offsetTop+(re?F:0)+Se)+ue;s.style.height=Ne+"px",g.scrollTop=ne-Z+g.offsetTop}s.style.margin=`${yr}px 0`,s.style.minHeight=V+"px",s.style.maxHeight=H+"px",r?.(),requestAnimationFrame(()=>m.current=!0)}},[p,o.trigger,o.valueNode,s,u,g,x,y,o.dir,r]);xt(()=>v(),[v]);let[S,C]=J.useState();xt(()=>{u&&C(window.getComputedStyle(u).zIndex)},[u]);let T=J.useCallback(w=>{w&&b.current===!0&&(v(),h?.(),b.current=!1)},[v,h]);return(0,pe.jsx)(M_,{scope:n,contentWrapper:s,shouldExpandOnScrollRef:m,onScrollButtonChange:T,children:(0,pe.jsx)("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:S},children:(0,pe.jsx)(Oe.div,{...a,ref:d,style:{boxSizing:"border-box",maxHeight:"100%",...a.style}})})})});KA.displayName=T_;var N_="SelectPopperPosition",Ng=J.forwardRef((e,t)=>{let{__scopeSelect:n,align:r="start",collisionPadding:a=yr,...o}=e,i=md(n);return(0,pe.jsx)(sA,{...i,...o,ref:t,align:r,collisionPadding:a,style:{boxSizing:"border-box",...o.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});Ng.displayName=N_;var[M_,Dg]=ul(Jo,{}),Mg="SelectViewport",FA=J.forwardRef((e,t)=>{let{__scopeSelect:n,nonce:r,...a}=e,o=lo(Mg,n),i=Dg(Mg,n),s=Xe(t,o.onViewportChange),c=J.useRef(0);return(0,pe.jsxs)(pe.Fragment,{children:[(0,pe.jsx)("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),(0,pe.jsx)(dd.Slot,{scope:n,children:(0,pe.jsx)(Oe.div,{"data-radix-select-viewport":"",role:"presentation",...a,ref:s,style:{position:"relative",flex:1,overflow:"hidden auto",...a.style},onScroll:Pe(a.onScroll,u=>{let f=u.currentTarget,{contentWrapper:d,shouldExpandOnScrollRef:p}=i;if(p?.current&&d){let m=Math.abs(c.current-f.scrollTop);if(m>0){let b=window.innerHeight-yr*2,g=parseFloat(d.style.minHeight),x=parseFloat(d.style.height),y=Math.max(g,x);if(y<b){let h=y+m,v=Math.min(b,h),S=h-v;d.style.height=v+"px",d.style.bottom==="0px"&&(f.scrollTop=S>0?S:0,d.style.justifyContent="flex-end")}}}c.current=f.scrollTop})})})]})});FA.displayName=Mg;var GA="SelectGroup",[O_,__]=ul(GA),YA=J.forwardRef((e,t)=>{let{__scopeSelect:n,...r}=e,a=no();return(0,pe.jsx)(O_,{scope:n,id:a,children:(0,pe.jsx)(Oe.div,{role:"group","aria-labelledby":a,...r,ref:t})})});YA.displayName=GA;var WA="SelectLabel",QA=J.forwardRef((e,t)=>{let{__scopeSelect:n,...r}=e,a=__(WA,n);return(0,pe.jsx)(Oe.div,{id:a.id,...r,ref:t})});QA.displayName=WA;var ud="SelectItem",[k_,XA]=ul(ud),ZA=J.forwardRef((e,t)=>{let{__scopeSelect:n,value:r,disabled:a=!1,textValue:o,...i}=e,s=io(ud,n),c=lo(ud,n),u=s.value===r,[f,d]=J.useState(o??""),[p,m]=J.useState(!1),b=Xe(t,h=>c.itemRefCallback?.(h,r,a)),g=no(),x=J.useRef("touch"),y=()=>{a||(s.onValueChange(r),s.onOpenChange(!1))};if(r==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return(0,pe.jsx)(k_,{scope:n,value:r,disabled:a,textId:g,isSelected:u,onItemTextChange:J.useCallback(h=>{d(v=>v||(h?.textContent??"").trim())},[]),children:(0,pe.jsx)(dd.ItemSlot,{scope:n,value:r,disabled:a,textValue:f,children:(0,pe.jsx)(Oe.div,{role:"option","aria-labelledby":g,"data-highlighted":p?"":void 0,"aria-selected":u&&p,"data-state":u?"checked":"unchecked","aria-disabled":a||void 0,"data-disabled":a?"":void 0,tabIndex:a?void 0:-1,...i,ref:b,onFocus:Pe(i.onFocus,()=>m(!0)),onBlur:Pe(i.onBlur,()=>m(!1)),onClick:Pe(i.onClick,()=>{x.current!=="mouse"&&y()}),onPointerUp:Pe(i.onPointerUp,()=>{x.current==="mouse"&&y()}),onPointerDown:Pe(i.onPointerDown,h=>{x.current=h.pointerType}),onPointerMove:Pe(i.onPointerMove,h=>{x.current=h.pointerType,a?c.onItemLeave?.():x.current==="mouse"&&h.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Pe(i.onPointerLeave,h=>{h.currentTarget===document.activeElement&&c.onItemLeave?.()}),onKeyDown:Pe(i.onKeyDown,h=>{c.searchRef?.current!==""&&h.key===" "||(v_.includes(h.key)&&y(),h.key===" "&&h.preventDefault())})})})})});ZA.displayName=ud;var ks="SelectItemText",JA=J.forwardRef((e,t)=>{let{__scopeSelect:n,className:r,style:a,...o}=e,i=io(ks,n),s=lo(ks,n),c=XA(ks,n),u=w_(ks,n),[f,d]=J.useState(null),p=Xe(t,y=>d(y),c.onItemTextChange,y=>s.itemTextRefCallback?.(y,c.value,c.disabled)),m=f?.textContent,b=J.useMemo(()=>(0,pe.jsx)("option",{value:c.value,disabled:c.disabled,children:m},c.value),[c.disabled,c.value,m]),{onNativeOptionAdd:g,onNativeOptionRemove:x}=u;return xt(()=>(g(b),()=>x(b)),[g,x,b]),(0,pe.jsxs)(pe.Fragment,{children:[(0,pe.jsx)(Oe.span,{id:c.textId,...o,ref:p}),c.isSelected&&i.valueNode&&!i.valueNodeHasChildren?Lg.createPortal(o.children,i.valueNode):null]})});JA.displayName=ks;var e1="SelectItemIndicator",t1=J.forwardRef((e,t)=>{let{__scopeSelect:n,...r}=e;return XA(e1,n).isSelected?(0,pe.jsx)(Oe.span,{"aria-hidden":!0,...r,ref:t}):null});t1.displayName=e1;var Og="SelectScrollUpButton",L_=J.forwardRef((e,t)=>{let n=lo(Og,e.__scopeSelect),r=Dg(Og,e.__scopeSelect),[a,o]=J.useState(!1),i=Xe(t,r.onScrollButtonChange);return xt(()=>{if(n.viewport&&n.isPositioned){let c=function(){let f=u.scrollTop>0;o(f)};var s=c;let u=n.viewport;return c(),u.addEventListener("scroll",c),()=>u.removeEventListener("scroll",c)}},[n.viewport,n.isPositioned]),a?(0,pe.jsx)(n1,{...e,ref:i,onAutoScroll:()=>{let{viewport:s,selectedItem:c}=n;s&&c&&(s.scrollTop=s.scrollTop-c.offsetHeight)}}):null});L_.displayName=Og;var _g="SelectScrollDownButton",D_=J.forwardRef((e,t)=>{let n=lo(_g,e.__scopeSelect),r=Dg(_g,e.__scopeSelect),[a,o]=J.useState(!1),i=Xe(t,r.onScrollButtonChange);return xt(()=>{if(n.viewport&&n.isPositioned){let c=function(){let f=u.scrollHeight-u.clientHeight,d=Math.ceil(u.scrollTop)<f;o(d)};var s=c;let u=n.viewport;return c(),u.addEventListener("scroll",c),()=>u.removeEventListener("scroll",c)}},[n.viewport,n.isPositioned]),a?(0,pe.jsx)(n1,{...e,ref:i,onAutoScroll:()=>{let{viewport:s,selectedItem:c}=n;s&&c&&(s.scrollTop=s.scrollTop+c.offsetHeight)}}):null});D_.displayName=_g;var n1=J.forwardRef((e,t)=>{let{__scopeSelect:n,onAutoScroll:r,...a}=e,o=lo("SelectScrollButton",n),i=J.useRef(null),s=fd(n),c=J.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return J.useEffect(()=>()=>c(),[c]),xt(()=>{s().find(f=>f.ref.current===document.activeElement)?.ref.current?.scrollIntoView({block:"nearest"})},[s]),(0,pe.jsx)(Oe.div,{"aria-hidden":!0,...a,ref:t,style:{flexShrink:0,...a.style},onPointerDown:Pe(a.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(r,50))}),onPointerMove:Pe(a.onPointerMove,()=>{o.onItemLeave?.(),i.current===null&&(i.current=window.setInterval(r,50))}),onPointerLeave:Pe(a.onPointerLeave,()=>{c()})})}),z_="SelectSeparator",B_=J.forwardRef((e,t)=>{let{__scopeSelect:n,...r}=e;return(0,pe.jsx)(Oe.div,{"aria-hidden":!0,...r,ref:t})});B_.displayName=z_;var kg="SelectArrow",I_=J.forwardRef((e,t)=>{let{__scopeSelect:n,...r}=e,a=md(n),o=io(kg,n),i=lo(kg,n);return o.open&&i.position==="popper"?(0,pe.jsx)(cA,{...a,...r,ref:t}):null});I_.displayName=kg;var U_="SelectBubbleInput",r1=J.forwardRef(({__scopeSelect:e,value:t,...n},r)=>{let a=J.useRef(null),o=Xe(r,a),i=ku(t);return J.useEffect(()=>{let s=a.current;if(!s)return;let c=window.HTMLSelectElement.prototype,f=Object.getOwnPropertyDescriptor(c,"value").set;if(i!==t&&f){let d=new Event("change",{bubbles:!0});f.call(s,t),s.dispatchEvent(d)}},[i,t]),(0,pe.jsx)(Oe.select,{...n,style:{...fg,...n.style},ref:o,defaultValue:t})});r1.displayName=U_;function a1(e){return e===""||e===void 0}function o1(e){let t=bn(e),n=J.useRef(""),r=J.useRef(0),a=J.useCallback(i=>{let s=n.current+i;t(s),(function c(u){n.current=u,window.clearTimeout(r.current),u!==""&&(r.current=window.setTimeout(()=>c(""),1e3))})(s)},[t]),o=J.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return J.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,a,o]}function i1(e,t,n){let a=t.length>1&&Array.from(t).every(u=>u===t[0])?t[0]:t,o=n?e.indexOf(n):-1,i=j_(e,Math.max(o,0));a.length===1&&(i=i.filter(u=>u!==n));let c=i.find(u=>u.textValue.toLowerCase().startsWith(a.toLowerCase()));return c!==n?c:void 0}function j_(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var l1=zA,s1=IA,c1=jA,u1=PA,d1=VA,f1=HA,m1=FA,p1=YA,g1=QA,h1=ZA,y1=JA,v1=t1;function b1(e){return String(e||"").trim().toLowerCase()}function pd(e){return b1(e).length>0}function x1({searchEnabled:e=!0}={}){return!!e}function zg(e){let t=String(e?.key||"");return!t||t.length!==1||e?.ctrlKey||e?.metaKey||e?.altKey?"":t.trim()?t:""}function S1(e={},t=""){let n=b1(t);return n?[e?.label,e?.value,e?.hint,e?.textValue,e?.searchText].map(a=>String(a||"").toLowerCase()).join(" ").includes(n):!0}var gd=K(xe(),1),V_=12;function Bg(e){return/auto|scroll|hidden|clip|overlay/.test(String(e||"").toLowerCase())}function H_(e,t){return{top:Math.max(e.top,t.top),right:Math.min(e.right,t.right),bottom:Math.min(e.bottom,t.bottom),left:Math.max(e.left,t.left)}}function hd(e){if(typeof window>"u")return[];let t=[],n=e?.parentElement||null;for(;n&&n!==document.body&&n!==document.documentElement;){let r=window.getComputedStyle(n);(Bg(r.overflow)||Bg(r.overflowY)||Bg(r.overflowX))&&t.push(n),n=n.parentElement}return t}function q_(e,{viewportPadding:t=V_}={}){if(typeof window>"u")return null;let n={top:t,right:window.innerWidth-t,bottom:window.innerHeight-t,left:t};for(let r of hd(e))n=H_(n,r.getBoundingClientRect());return n}function $_({anchorRect:e,boundaryRect:t,preferredSide:n="bottom",offset:r=4,desiredHeight:a=288}={}){if(!e||!t)return{side:n==="top"?"top":"bottom",maxHeight:a};let o=Math.max(0,e.top-t.top-r),i=Math.max(0,t.bottom-e.bottom-r),c=o===i?n==="top"?"top":"bottom":o>i?"top":"bottom",u=Math.max(0,Math.min(a,c==="top"?o:i));return{side:c,maxHeight:u}}function yd({open:e=!1,anchorRef:t,preferredSide:n="bottom",offset:r=4,desiredHeight:a=288}={}){let[o,i]=(0,gd.useState)(()=>({side:n==="top"?"top":"bottom",maxHeight:a}));return(0,gd.useLayoutEffect)(()=>{if(!e||typeof window>"u")return;let s=t?.current||null;if(!s){i({side:n==="top"?"top":"bottom",maxHeight:a});return}let c=()=>{i($_({anchorRect:s.getBoundingClientRect(),boundaryRect:q_(s),preferredSide:n,offset:r,desiredHeight:a}))};c();let u=hd(s);window.addEventListener("resize",c);for(let d of u)d.addEventListener("scroll",c,{passive:!0});let f=null;if(typeof ResizeObserver=="function"){f=new ResizeObserver(c),f.observe(s);for(let d of u)f.observe(d)}return()=>{window.removeEventListener("resize",c);for(let d of u)d.removeEventListener("scroll",c);f?.disconnect?.()}},[e,t,n,r,a]),o}var Bt=K(Be(),1),bd=(0,Ue.createContext)(null),K_="Enter character to filter",F_=41,G_="data-llm-router-select-search-input";function vd(e){return e==null||typeof e=="boolean"?"":typeof e=="string"||typeof e=="number"?String(e):Array.isArray(e)?e.map(t=>vd(t)).filter(Boolean).join(" "):(0,Ue.isValidElement)(e)?vd(e.props?.children):""}function Ig(e,t="first"){let n=Array.from(e?.querySelectorAll?.("[role='option']")||[]).filter(o=>o.getAttribute("aria-disabled")!=="true");if(n.length===0)return;let r=n.find(o=>o.getAttribute("data-state")==="checked");(t==="last"?n[n.length-1]:r||n[0])?.focus?.()}function Y_(e={}){let t=String(e.textValue||vd(e.children)||"").trim();return{value:String(e.value||""),textValue:t,searchText:String(e.searchText||"")}}function w1(e,t=""){let n=0,r=0;return{children:Ue.Children.map(e,o=>{if(!(0,Ue.isValidElement)(o))return o;if(o.type?.__LLM_ROUTER_SELECT_ITEM===!0){n+=1;let s=S1(Y_(o.props),t);return s&&(r+=1),s?o:null}if(!o.props?.children)return o;let i=w1(o.props.children,t);return n+=i.totalItems,r+=i.matchedItems,o.type?.__LLM_ROUTER_SELECT_GROUP===!0&&i.matchedItems===0?null:(0,Ue.cloneElement)(o,void 0,i.children)}),totalItems:n,matchedItems:r}}function vr({open:e,defaultOpen:t=!1,onOpenChange:n,searchEnabled:r=!0,openSearchRequest:a=0,children:o,...i}){let[s,c]=(0,Ue.useState)(!!t),[u,f]=(0,Ue.useState)(""),[d,p]=(0,Ue.useState)(!1),m=(0,Ue.useRef)(null),b=(0,Ue.useRef)(0),g=e!==void 0?e:s;(0,Ue.useEffect)(()=>{g||(f(""),p(!1))},[g]);function x(h){e===void 0&&c(h),n?.(h),h||(f(""),p(!1))}(0,Ue.useEffect)(()=>{!a||a===b.current||(b.current=a,f(""),r&&p(!0),!g&&(e===void 0&&c(!0),n?.(!0)))},[a,r,g,e,n]);let y={open:g,searchEnabled:r,filterValue:u,setFilterValue:f,searchSessionActive:d,setSearchSessionActive:p,setOpen:x,triggerRef:m,openSearchRequest:a};return(0,Bt.jsx)(bd.Provider,{value:y,children:(0,Bt.jsx)(l1,{...i,open:g,onOpenChange:x,children:o})})}var br=(0,Ue.forwardRef)(function({className:t,children:n,onKeyDown:r,...a},o){let i=(0,Ue.useContext)(bd),s=i?.triggerRef||null,c=(0,Ue.useCallback)(f=>{if(s&&(s.current=f),typeof o=="function"){o(f);return}o&&(o.current=f)},[s,o]);function u(f){if(r?.(f),f.defaultPrevented||!i?.searchEnabled||a.disabled)return;let d=zg(f);d&&(f.preventDefault(),i.setSearchSessionActive?.(!0),i.setOpen(!0),i.setFilterValue(p=>`${p}${d}`))}return(0,Bt.jsxs)(s1,{ref:c,className:W("relative inline-flex h-9 w-full items-center gap-2 rounded-lg border border-input bg-background/80 pl-3 pr-9 text-sm text-foreground shadow-sm outline-none transition focus:border-ring focus:ring-2 focus:ring-ring/40 disabled:cursor-not-allowed disabled:opacity-50",t),onKeyDown:u,...a,children:[(0,Bt.jsx)("span",{className:"min-w-0 flex-1 truncate text-left",children:n}),(0,Bt.jsx)(u1,{className:"pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"\u25BE"})]})});function xr(e){return(0,Bt.jsx)(c1,{...e})}var Sr=(0,Ue.forwardRef)(function({className:t,children:n,position:r="popper",onKeyDownCapture:a,searchPlaceholder:o=K_,emptySearchMessage:i="No matching options.",...s},c){let u=(0,Ue.useContext)(bd),f=(0,Ue.useRef)(null),d=(0,Ue.useRef)(null),p=yd({open:!!u?.open,anchorRef:u?.triggerRef,preferredSide:"bottom",desiredHeight:288,offset:4}),m=x1({searchEnabled:u?.searchEnabled,filterValue:u?.filterValue,sessionActive:u?.searchSessionActive}),b=(0,Ue.useMemo)(()=>pd(u?.filterValue)?w1(n,u?.filterValue):{children:n,totalItems:0,matchedItems:0},[n,u?.filterValue]),g=pd(u?.filterValue)&&b.totalItems>0&&b.matchedItems===0,x=Math.max(0,Math.floor((p.maxHeight||288)-(m?F_:0)));(0,Ue.useEffect)(()=>{if(!u?.open||!m||typeof window>"u")return;let S=window.requestAnimationFrame(()=>{let C=d.current;if(!C)return;C.focus();let T=C.value.length;C.setSelectionRange(T,T)});return()=>window.cancelAnimationFrame(S)},[u?.open,m,u?.openSearchRequest]);let y=(0,Ue.useCallback)(S=>{if(f.current=S,typeof c=="function"){c(S);return}c&&(c.current=S)},[c]);function h(S){if(a?.(S),S.defaultPrevented||S.target===d.current||!u?.searchEnabled)return;let C=zg(S);C&&(S.preventDefault(),S.stopPropagation(),u.setSearchSessionActive?.(!0),u.setFilterValue(T=>`${T}${C}`))}function v(S){let C=S.target.value;u?.setSearchSessionActive?.(!0),u?.setFilterValue(C)}return(0,Bt.jsx)(d1,{children:(0,Bt.jsxs)(f1,{ref:y,position:r,side:r==="popper"?p.side:void 0,className:W("z-50 min-w-[8rem] overflow-hidden rounded-xl border border-border/70 bg-popover text-popover-foreground shadow-lg",r==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=top]:-translate-y-1",t),onKeyDownCapture:h,...s,children:[m?(0,Bt.jsx)("div",{className:"border-b border-border/70 p-1",children:(0,Bt.jsx)(Dt,{ref:d,"data-llm-router-select-search-input":"true",value:u?.filterValue||"",autoComplete:"off",autoCorrect:"off",autoCapitalize:"none",spellCheck:!1,placeholder:o,className:"h-8 border-border/70 bg-background/90",onChange:v,onPointerDown:S=>S.stopPropagation(),onClick:S=>S.stopPropagation(),onKeyDown:S=>{if(S.stopPropagation(),S.key==="ArrowDown"){S.preventDefault(),Ig(f.current,"first");return}if(S.key==="ArrowUp"){S.preventDefault(),Ig(f.current,"last");return}S.key==="Escape"&&(S.preventDefault(),u?.setSearchSessionActive?.(!1),u?.setFilterValue(""),typeof window<"u"&&window.requestAnimationFrame(()=>Ig(f.current)))}})}):null,(0,Bt.jsxs)(m1,{className:"px-1 pb-1",style:{maxHeight:`${x}px`},children:[pd(u?.filterValue)?b.children:n,g?(0,Bt.jsx)("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:i}):null]})]})})}),ar=(0,Ue.forwardRef)(function({className:t,children:n,searchText:r="",textValue:a,onPointerMove:o,...i},s){let c=(0,Ue.useContext)(bd),u=String(a||vd(n)||"").trim();function f(d){if(o?.(d),d.defaultPrevented||!c?.searchEnabled||typeof document>"u")return;let p=document.activeElement;p instanceof HTMLElement&&p.getAttribute(G_)==="true"&&d.preventDefault()}return(0,Bt.jsxs)(h1,{ref:s,className:W("relative flex w-full cursor-default select-none items-center rounded-lg py-2 pl-3 pr-8 text-sm text-foreground outline-none transition-colors hover:bg-accent/60 focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),textValue:u,onPointerMove:f,...i,children:[(0,Bt.jsx)(y1,{children:n}),(0,Bt.jsx)("span",{className:"absolute right-2 inline-flex h-4 w-4 items-center justify-center text-xs text-muted-foreground",children:(0,Bt.jsx)(v1,{children:"\u2713"})})]})});ar.__LLM_ROUTER_SELECT_ITEM=!0;function Ug(e){return(0,Bt.jsx)(p1,{...e})}Ug.__LLM_ROUTER_SELECT_GROUP=!0;var A1=(0,Ue.forwardRef)(function({className:t,children:n,...r},a){return(0,Bt.jsx)(g1,{ref:a,className:W("-mt-1 sticky top-0 z-10 -mx-1 mb-1 block border-b border-border/55 bg-background/96 px-4 py-2 text-xs font-semibold uppercase tracking-[0.18em] text-foreground/80 backdrop-blur-sm",t),...r,children:n})});var or=K(xe(),1);var W_="flex h-9 w-full rounded-lg border border-input bg-background/80 px-3 py-2 text-sm text-foreground shadow-sm outline-none transition placeholder:text-muted-foreground focus:border-ring focus:ring-2 focus:ring-ring/40";function Q_({committedValue:e="",draftValue:t="",isFocused:n=!1,hasLocalDraft:r=!1,previousCommittedValue:a=""}={}){let o=String(e??""),i=String(t??""),s=String(a??"");return n?{draftValue:i,hasLocalDraft:r,previousCommittedValue:o}:!r||o===i?{draftValue:o,hasLocalDraft:!1,previousCommittedValue:o}:o!==s?{draftValue:o,hasLocalDraft:!1,previousCommittedValue:o}:{draftValue:i,hasLocalDraft:!0,previousCommittedValue:o}}function X_({committedValue:e="",draftValue:t="",isFocused:n=!1,hasLocalDraft:r=!1}={}){return String(n||r?t??"":e??"")}function Z_({commitOnBlur:e=!1,draftValue:t="",hasLocalDraft:n=!1}={}){return!e||!n?null:String(t??"")}var jg=(0,or.forwardRef)(function({className:t,commitOnBlur:n=!1,value:r,onValueCommit:a,onValueChange:o,onChange:i,onFocus:s,onBlur:c,...u},f){let d=String(r??""),[p,m]=(0,or.useState)(d),[b,g]=(0,or.useState)(!1),[x,y]=(0,or.useState)(!1),h=(0,or.useRef)(d);return(0,or.useEffect)(()=>{let v=Q_({committedValue:d,draftValue:p,isFocused:b,hasLocalDraft:x,previousCommittedValue:h.current});h.current=v.previousCommittedValue,m(v.draftValue),y(v.hasLocalDraft)},[d,p,x,b]),(0,or.createElement)("input",{...u,ref:f,className:W(W_,t),value:X_({committedValue:d,draftValue:p,isFocused:b,hasLocalDraft:x}),onFocus:v=>{g(!0),s?.(v)},onChange:v=>{let S=v.target.value;m(S),y(!0),o?.(S,v),i?.(v)},onBlur:v=>{g(!1);let S=Z_({commitOnBlur:n,draftValue:p,hasLocalDraft:x});S!==null&&a?.(S,v),c?.(v)}})});var Pg=Object.freeze(["gpt-5.3-codex","gpt-5.2-codex","gpt-5.1-codex-mini"]),Vg=Object.freeze(["claude-sonnet-4-6","claude-opus-4-6","claude-haiku-4-5"]),QB=Object.freeze({authorizeUrl:"https://auth.openai.com/oauth/authorize",tokenUrl:"https://auth.openai.com/oauth/token",deviceCodeUrl:"https://auth.openai.com/oauth/device/code",callbackPort:1455,callbackPath:"/auth/callback",scopes:"openid profile email offline_access",clientId:"app_EMoamEEZ73f0CkXaXp7hrann",authorizeParams:Object.freeze({id_token_add_organizations:"true",codex_cli_simplified_flow:"true",originator:"codex_cli_rs"}),tokenRefreshBufferMs:300*1e3}),XB=Object.freeze({authorizeUrl:"https://claude.ai/oauth/authorize",tokenUrl:"https://platform.claude.com/v1/oauth/token",callbackPort:1456,callbackPath:"/callback",manualRedirectUrl:"https://platform.claude.com/oauth/code/callback",scopes:"user:profile user:inference user:sessions:claude_code user:mcp_servers",clientId:"9d1c250a-e61b-44d9-88ed-5944d1962f5e",authorizeParams:Object.freeze({code:"true"}),oauthBeta:"oauth-2025-04-20",apiBaseUrl:"https://api.anthropic.com",messagesPath:"/v1/messages?beta=true",tokenRefreshBufferMs:300*1e3});var ek="127.0.0.1";var Ls=`http://${ek}:8376`,JB=`${Ls}/openai/v1`,e3=`${Ls}/anthropic`,t3=Object.freeze({enabled:!0});var at="default",tk="AICodeClient",nk="1.0.0",l3=ak();var s3=Object.freeze({CHATGPT_CODEX:"chatgpt-codex",CLAUDE_CODE:"claude-code"});function rk(){if(typeof process>"u"||!process)return{runtime:"runtime/unknown",platform:"unknown",arch:"unknown"};let e=process?.versions?.node?String(process.versions.node):"",t=e?`node/${e}`:"runtime/unknown",n=process?.platform?String(process.platform):"unknown",r=process?.arch?String(process.arch):"unknown";return{runtime:t,platform:n,arch:r}}function ak(){let{runtime:e,platform:t,arch:n}=rk();return`${tk}/${nk} (${t}; ${n}) ${e}`}var c3=Object.freeze(["brave","tavily","exa","searxng"]),u3=Object.freeze({brave:1e3,tavily:1e3,exa:1e3,searxng:0});var xd=Object.freeze([Object.freeze({id:"@anthropic-opus",description:"Anthropic Opus family used by AMP smart-like flows.",match:[{vendor:"anthropic",family:"opus",variantAbsent:!0}],defaultMatch:"claude-opus-{number}"}),Object.freeze({id:"@anthropic-sonnet",description:"Anthropic Sonnet family used by AMP librarian-like flows.",match:[{vendor:"anthropic",family:"sonnet",variantAbsent:!0}],defaultMatch:"claude-sonnet-{number}"}),Object.freeze({id:"@anthropic-haiku-shared",description:"Anthropic Haiku family shared by AMP rush/title-like flows.",match:[{vendor:"anthropic",family:"haiku",variantAbsent:!0}],defaultMatch:"claude-haiku-{number}"}),Object.freeze({id:"@openai-gpt-base",description:"Base GPT family currently observed for AMP Oracle-like flows.",match:[{vendor:"openai",family:"gpt",variantAbsent:!0}],defaultMatch:"gpt-{number}"}),Object.freeze({id:"@openai-gpt-codex",description:"OpenAI GPT Codex family used by AMP deep-like flows.",match:[{vendor:"openai",family:"gpt",variantPrefix:"codex"},"gpt-*-codex*"],defaultMatch:"gpt-*-codex*"}),Object.freeze({id:"@google-gemini-pro",description:"Google Gemini Pro family used by AMP review-like flows.",match:[{vendor:"google",family:"gemini",variant:"pro"},"gemini-*-pro*"],defaultMatch:"gemini-*-pro*"}),Object.freeze({id:"@google-gemini-pro-image",description:"Google Gemini image family used by AMP painter-like flows.",match:["gemini-3-pro-image","gemini-3-pro-image*","gemini-*-image*"],defaultMatch:"gemini-*-image*"}),Object.freeze({id:"@google-gemini-flash-shared",description:"Google Gemini Flash family shared by AMP search/look-at/handoff-like flows.",match:[{vendor:"google",family:"gemini",variantPrefix:"flash"},"gemini-*-flash*"],defaultMatch:"gemini-*-flash*"})]),Ds=Object.freeze([Object.freeze({id:"smart",type:"mode",description:"Unconstrained state-of-the-art model use",signatures:["@anthropic-opus"]}),Object.freeze({id:"rush",type:"mode",description:"Faster and cheaper, for small well-defined tasks",signatures:["@anthropic-haiku-shared"]}),Object.freeze({id:"deep",type:"mode",description:"Deep reasoning with extended thinking",signatures:["@openai-gpt-codex"]}),Object.freeze({id:"review",type:"feature",description:"Bug identification and code review assistance",signatures:["@google-gemini-pro"]}),Object.freeze({id:"search",type:"agent",description:"Fast, accurate codebase retrieval",signatures:["@google-gemini-flash-shared"]}),Object.freeze({id:"oracle",type:"agent",description:"Complex reasoning and planning on code",signatures:["@openai-gpt-base"]}),Object.freeze({id:"librarian",type:"agent",description:"Large-scale retrieval and research on external code",signatures:["@anthropic-sonnet"]}),Object.freeze({id:"look-at",type:"system",description:"Image, PDF, and media file analysis",aliases:["look at","lookat"],signatures:["@google-gemini-flash-shared"]}),Object.freeze({id:"painter",type:"system",description:"Image generation and editing",signatures:["@google-gemini-pro-image"]}),Object.freeze({id:"handoff",type:"system",description:"Fallback context analysis for task continuation",signatures:["@google-gemini-flash-shared"]}),Object.freeze({id:"title",type:"system",description:"Fast title generation for threads",aliases:["titling"],signatures:["@anthropic-haiku-shared"]})]),d3=Object.freeze([Object.freeze({id:"oracle",patterns:["/^gpt-\\d+(?:\\.\\d+)?$/"]}),Object.freeze({id:"librarian",patterns:["/^(?:claude-)?sonnet-\\d+(?:\\.\\d+)?$/"]}),Object.freeze({id:"title",patterns:["/^(?:claude-)?haiku-\\d+(?:\\.\\d+)?$/"]}),Object.freeze({id:"painter",patterns:["gemini-3-pro-image","gemini-3-pro-image*"]}),Object.freeze({id:"search",patterns:["gemini-2.5-flash","gemini-2.5-flash*","gemini-3-flash","gemini-3-flash*"]}),Object.freeze({id:"look-at",patterns:["gemini-2.5-flash","gemini-2.5-flash*","gemini-3-flash","gemini-3-flash*"]}),Object.freeze({id:"handoff",patterns:["gemini-3-flash","gemini-3-flash*"]})]);var Hg=["second","minute","hour","day","week","month"];function Br(e,t=0){let n=Number.parseInt(String(e||""),10);return Number.isFinite(n)&&n>0?n:t}function ei(e,t=""){let n=String(e||"").trim().toLowerCase();return Hg.includes(n)?n:t}function C1(e,t=1){let n=String(e||"").trim().toLowerCase().replace(/s$/,"");return n?Number(t)===1?n:`${n}s`:"windows"}function Ir(e=[]){let t=[],n=new Set;for(let r of Array.isArray(e)?e:[e]){let a=String(r||"").trim();if(a){if(a.toLowerCase()==="all")return["all"];n.has(a)||(n.add(a),t.push(a))}}return t}function zs({requests:e,windowValue:t,windowUnit:n}){let r=Br(e,0),a=Br(t,0),o=ei(n,"");return!r||!a||!o?"":`${r}-req-per-${a}-${C1(o,a)}`}function R1(e={}){let t=Br(e?.requests??e?.limit,0),n=Br(e?.window?.size??e?.window?.value??e?.windowValue,0),r=ei(e?.window?.unit??e?.windowUnit,"");return!t||!n||!r?"Unconfigured":`${t}/${n} ${C1(r,n)}`}function ti(e=[],{knownModelIds:t=[],requireAtLeastOne:n=!0}={}){let r=Array.isArray(e)?e:[];if(n&&r.length===0)return"Add at least one rate-limit entity.";let a=new Set((t||[]).map(i=>String(i||"").trim()).filter(Boolean)),o=new Set;for(let i of r){let s=Ir(i?.models||[]);if(a.size>0&&s.some(p=>p!=="all"&&!a.has(p)))return"Rate-limit model selectors must match the provider model ids.";let c=Br(i?.requests,0);if(!c)return"Rate-limit requests must be a positive integer.";let u=Br(i?.windowValue,0);if(!u)return"Rate-limit window size must be a positive integer.";let f=ei(i?.windowUnit,"");if(!f)return"Rate-limit window unit is invalid.";let d=zs({requests:c,windowValue:u,windowUnit:f});if(o.has(d))return"Duplicate rate-limit entities are not allowed.";o.add(d)}return""}function Bs(e=[],{existingBucketsBySourceId:t=new Map,fallbackRequests:n=60,fallbackWindowValue:r=1,fallbackWindowUnit:a="minute"}={}){return(Array.isArray(e)?e:[]).map((o,i)=>{let s=String(o?.sourceId||"").trim(),c=s&&t instanceof Map&&t.has(s)?structuredClone(t.get(s)):{},u=Br(o?.requests,Br(c?.requests??c?.limit,n)),f=Br(o?.windowValue,Br(c?.window?.size??c?.window?.value,r)),d=ei(o?.windowUnit,ei(c?.window?.unit,a)||a),p=Ir(o?.models||[]),m=p.length>0?p:["all"],b={...c,id:zs({requests:u,windowValue:f,windowUnit:d})||`rate-limit-${i+1}`,models:m,requests:u,window:{...c?.window&&typeof c.window=="object"&&!Array.isArray(c.window)?c.window:{},size:f,unit:d}};return delete b.name,delete b.limit,b.window&&typeof b.window=="object"&&delete b.window.value,b})}function Is(e){return JSON.parse(JSON.stringify(e??{}))}function Sd(e=[]){let t=new Set,n=[];for(let r of e){let a=String(r||"").trim();!a||t.has(a)||(t.add(a),n.push(a))}return n}function T1(e){let t=String(e||"").trim();return t?t.startsWith("alias:")?t.slice(6).trim():t:""}function ok(e={},t={}){let n=t?.[at];if(n&&typeof n=="object"&&!Array.isArray(n))return{...n,id:at,strategy:String(n.strategy||"ordered").trim()||"ordered",targets:Cn(n.targets||[],o=>o),fallbackTargets:Cn(n.fallbackTargets||[],o=>o)};let r=String(e?.defaultModel||"").trim();if(!r||r==="smart")return{id:at,strategy:"ordered",targets:[],fallbackTargets:[]};let a=T1(r);if(a&&t?.[a]){let o=t[a];return{...o,id:at,strategy:String(o.strategy||"ordered").trim()||"ordered",targets:Cn(o.targets||[],i=>i),fallbackTargets:Cn(o.fallbackTargets||[],i=>i)}}return{id:at,strategy:"ordered",targets:r?[{ref:r}]:[],fallbackTargets:[]}}function ik(e={}){return(!e.modelAliases||typeof e.modelAliases!="object"||Array.isArray(e.modelAliases))&&(e.modelAliases={}),e.modelAliases[at]=ok(e,e.modelAliases),e}function lk(e={}){let t=new Set;for(let n of Object.keys(e?.modelAliases||{})){let r=String(n||"").trim();r&&t.add(r)}for(let n of e?.providers||[]){let r=String(n?.id||"").trim();if(r)for(let a of n?.models||[]){let o=String(a?.id||"").trim();o&&t.add(`${r}/${o}`)}}return t}function sk(e={}){let t=Object.keys(e?.modelAliases||{}).map(n=>String(n||"").trim()).filter(Boolean);if(t.includes(at))return at;if(t.length>0)return t[0];for(let n of e?.providers||[]){let r=String(n?.id||"").trim();if(r)for(let a of n?.models||[]){let o=String(a?.id||"").trim();if(o)return`${r}/${o}`}}return""}function wd(e={}){ik(e);let t=lk(e);if(e.defaultModel=at,!e.amp||typeof e.amp!="object"||Array.isArray(e.amp))return e;let n=String(e.amp.defaultRoute||"").trim();if(!n||!t.has(T1(n))){let r=String(e.defaultModel||"").trim()||sk(e);r?e.amp.defaultRoute=r:delete e.amp.defaultRoute}return e}function dl(e,t,n,r){let a=String(e||"").trim();if(!a)return"";let o=`${t}/`;if(!a.startsWith(o))return a;let i=a.slice(o.length),s=n.get(i)||i;return r.has(s)?`${t}/${s}`:""}function fl(e,t,n=""){let r=String(e||"").trim();if(!r)return"";let a=`${t}/`;return r.startsWith(a)?n?`${n}/${r.slice(a.length)}`:"":r}function N1(e=[]){return Sd(Array.isArray(e)?e:[e])}function ck(e={},t={}){let n={...e};if(!Object.prototype.hasOwnProperty.call(t||{},"credentialInput"))return n;let a=String(t?.credentialInput||"").trim();return delete n.apiKey,delete n.apiKeyEnv,delete n.credential,a?/^[A-Z][A-Z0-9_]*$/.test(a)?(n.apiKeyEnv=a,n):(n.apiKey=a,n):n}function uk(e={},t=[]){let n={...e},r=N1(t),a=String(r[0]||"").trim(),o=n.metadata&&typeof n.metadata=="object"&&!Array.isArray(n.metadata)?{...n.metadata}:null,i=r.length>1||!!(o&&Object.prototype.hasOwnProperty.call(o,"endpointCandidates"));if(!a)delete n.baseUrl,delete n.baseUrlByFormat,o&&Object.prototype.hasOwnProperty.call(o,"endpointCandidates")&&delete o.endpointCandidates;else{n.baseUrl=a;let s=n.baseUrlByFormat&&typeof n.baseUrlByFormat=="object"&&!Array.isArray(n.baseUrlByFormat)?n.baseUrlByFormat:null;s&&Object.keys(s).length>0&&(n.baseUrlByFormat=Object.fromEntries(Object.keys(s).map(c=>[c,a]))),i&&(o=o||{},o.endpointCandidates=r)}return o&&Object.keys(o).length>0?n.metadata=o:o&&delete n.metadata,n}function dk(e={}){return e?.rateLimitLimit!==void 0||e?.rateLimitWindowValue!==void 0||e?.rateLimitWindowUnit!==void 0?[{sourceId:String(e?.rateLimitSourceId||"").trim(),models:["all"],requests:e?.rateLimitLimit,windowValue:e?.rateLimitWindowValue,windowUnit:e?.rateLimitWindowUnit}]:[]}function fk(e={},t={},n=""){let r={...e},a=Array.isArray(r.rateLimits)?r.rateLimits.map(d=>d&&typeof d=="object"?Is(d):d).filter(Boolean):[],o=Array.isArray(t?.rateLimitRows)?t.rateLimitRows:dk(t),i=a[0]&&typeof a[0]=="object"?a[0]:null,s=Number(i?.requests??i?.limit)||60,c=Number(i?.window?.size??i?.window?.value)||1,u=String(i?.window?.unit||"minute").trim()||"minute",f=new Map(a.map(d=>[String(d?.id||"").trim(),d]).filter(([d])=>!!d));return r.rateLimits=Bs(o,{existingBucketsBySourceId:f,fallbackRequests:s,fallbackWindowValue:c,fallbackWindowUnit:u}),r}function Ur(e,t,n=""){let r=String(e||"").trim();return r?r===t?n:r===`alias:${t}`?n?`alias:${n}`:"":r:""}function Cn(e=[],t){let n=new Set,r=[];for(let a of Array.isArray(e)?e:[]){let o=String(a?.ref||"").trim();if(!o)continue;let i=String(t(o)||"").trim();!i||n.has(i)||(n.add(i),r.push({...a,ref:i}))}return r}function Us(e={},t){if(!e?.amp||typeof e.amp!="object"||Array.isArray(e.amp))return e;let n=e.amp,r={};for(let[a,o]of Object.entries(n.routes&&typeof n.routes=="object"&&!Array.isArray(n.routes)?n.routes:{})){let i=String(t(o)||"").trim();i&&(r[a]=i)}return n.routes=r,n.rawModelRoutes=(Array.isArray(n.rawModelRoutes)?n.rawModelRoutes:[]).map(a=>{if(!a||typeof a!="object")return null;if(!Object.prototype.hasOwnProperty.call(a,"to"))return{...a};let o=String(t(a.to)||"").trim();return o?{...a,to:o}:null}).filter(Boolean),e}function M1(e={}){let t=e?.modelAliases&&typeof e.modelAliases=="object"&&!Array.isArray(e.modelAliases)?e.modelAliases:{},n={};for(let[r,a]of Object.entries(t)){let o=Cn(a?.targets||[],s=>s),i=Cn(a?.fallbackTargets||[],s=>s);n[r]={...a,targets:o,fallbackTargets:i}}return e.modelAliases=n,Us(e,r=>r),wd(e)}function mk(e=[]){let t=new Set,n=[];for(let r of Array.isArray(e)?e:[]){let a=String(r?.id||"").trim(),o=String(r?.sourceId||r?.originalId||"").trim();if(!a||t.has(a))continue;t.add(a);let i=Number.parseInt(String(r?.contextWindow||"").trim(),10);n.push({id:a,sourceId:o,contextWindow:Number.isFinite(i)&&i>0?i:null})}return n}function E1(e=[]){let t=new Set,n=[];for(let r of Array.isArray(e)?e:[]){let a=String(r?.ref||"").trim(),o=String(r?.sourceRef||r?.originalRef||"").trim(),i=String(r?.weight??"").trim(),s=Math.floor(Number(i));!a||t.has(a)||(t.add(a),n.push({ref:a,sourceRef:o,...i?{weight:Number.isFinite(s)&&s>0?s:1}:{}}))}return n}function qg(e={},t,n=[]){let r=Is(e),a=Array.isArray(r.providers)?r.providers:[],o=a.findIndex(x=>x?.id===t);if(o===-1)return r;let i=a[o],s=Array.isArray(i?.models)?i.models:[],c=new Map(s.map(x=>[String(x?.id||"").trim(),x])),u=mk(n),f=new Set,d=new Map,p=[];for(let x of u){let y=x.sourceId&&c.has(x.sourceId)&&!f.has(x.sourceId)?x.sourceId:"",h=!y&&c.has(x.id)&&!f.has(x.id)?x.id:"",v=y||h;if(v){f.add(v),v!==x.id&&d.set(v,x.id),p.push({...c.get(v),id:x.id,...x.contextWindow?{contextWindow:x.contextWindow}:{}}),x.contextWindow||delete p[p.length-1].contextWindow;continue}p.push({id:x.id,...x.contextWindow?{contextWindow:x.contextWindow}:{}})}let m=new Set(p.map(x=>String(x?.id||"").trim()).filter(Boolean));i.models=p,i.rateLimits=(Array.isArray(i.rateLimits)?i.rateLimits:[]).map(x=>{let y=Array.isArray(x?.models)?x.models:[];return{...x,models:Sd(y.map(h=>{if(String(h||"").trim()==="all")return"all";let v=d.get(String(h||"").trim())||String(h||"").trim();return m.has(v)?v:""}))}}),r.providers=a.map((x,y)=>y===o?i:x).map(x=>({...x,models:(Array.isArray(x?.models)?x.models:[]).map(y=>Array.isArray(y?.fallbackModels)?{...y,fallbackModels:Sd(y.fallbackModels.map(h=>dl(h,t,d,m)))}:y)}));let b=r.modelAliases&&typeof r.modelAliases=="object"&&!Array.isArray(r.modelAliases)?r.modelAliases:{},g={};for(let[x,y]of Object.entries(b)){let h=Cn(y?.targets||[],S=>dl(S,t,d,m)),v=Cn(y?.fallbackTargets||[],S=>dl(S,t,d,m));g[x]={...y,targets:h,fallbackTargets:v}}return r.modelAliases=g,r.defaultModel=dl(r.defaultModel,t,d,m),r?.amp&&typeof r.amp=="object"&&!Array.isArray(r.amp)&&(r.amp.defaultRoute=dl(r.amp.defaultRoute,t,d,m)),Us(r,x=>dl(x,t,d,m)),wd(r)}function $g(e={},t="",n={}){let r=Is(e),a=Array.isArray(r.providers)?r.providers:[],o=a.findIndex(m=>m?.id===t);if(o===-1)return r;let i=a[o]||{},s=String(n?.id||t||"").trim(),c=String(n?.name??i?.name??"").trim(),u=N1(Array.isArray(n?.endpoints)?n.endpoints:[n?.endpoint]),f=i?.type==="subscription",d=s||t,p={...i,id:d,name:c||d};if(f||(p=ck(p,n),p=uk(p,u),p=fk(p,n,d)),a[o]=p,r.providers=a.map(m=>({...m,models:(Array.isArray(m?.models)?m.models:[]).map(b=>Array.isArray(b?.fallbackModels)?{...b,fallbackModels:Sd(b.fallbackModels.map(g=>fl(g,t,d)))}:b)})),d!==t){let m=r.modelAliases&&typeof r.modelAliases=="object"&&!Array.isArray(r.modelAliases)?r.modelAliases:{},b={};for(let[g,x]of Object.entries(m))b[g]={...x,targets:Cn(x?.targets||[],y=>fl(y,t,d)),fallbackTargets:Cn(x?.fallbackTargets||[],y=>fl(y,t,d))};r.modelAliases=b,r.defaultModel=fl(r.defaultModel,t,d),r?.amp&&typeof r.amp=="object"&&!Array.isArray(r.amp)&&(r.amp.defaultRoute=fl(r.amp.defaultRoute,t,d)),Us(r,g=>fl(g,t,d))}return wd(r)}function O1(e={},t="",n={}){let r=Is(e),a=r.modelAliases&&typeof r.modelAliases=="object"&&!Array.isArray(r.modelAliases)?r.modelAliases:{},o=t?a[t]:void 0,i=t===at?at:String(n?.id||t||"").trim();if(!i)return r;let s=new Map((o?.targets||[]).map(m=>[String(m?.ref||"").trim(),m])),c=new Map((o?.fallbackTargets||[]).map(m=>[String(m?.ref||"").trim(),m])),u=new Set,f=E1(n?.targets).map(m=>{let b=m.sourceRef&&s.has(m.sourceRef)&&!u.has(m.sourceRef)?m.sourceRef:s.has(m.ref)&&!u.has(m.ref)?m.ref:"";return b&&u.add(b),{...b?s.get(b):{},ref:m.ref,...m.weight!==void 0?{weight:m.weight}:{}}}),d=new Set,p=E1(n?.fallbackTargets).map(m=>{let b=m.sourceRef&&c.has(m.sourceRef)&&!d.has(m.sourceRef)?m.sourceRef:c.has(m.ref)&&!d.has(m.ref)?m.ref:"";return b&&d.add(b),{...b?c.get(b):{},ref:m.ref,...m.weight!==void 0?{weight:m.weight}:{}}});if(t&&t!==i&&delete a[t],a[i]={...o?.metadata?{metadata:o.metadata}:{},...n?.metadata&&typeof n.metadata=="object"&&!Array.isArray(n.metadata)?{metadata:n.metadata}:{},id:i,strategy:String(n?.strategy||o?.strategy||"ordered").trim()||"ordered",targets:f,fallbackTargets:p},r.modelAliases=a,t&&t!==i){for(let[m,b]of Object.entries(a))m!==i&&(b.targets=Cn(b?.targets||[],g=>Ur(g,t,i)),b.fallbackTargets=Cn(b?.fallbackTargets||[],g=>Ur(g,t,i)));r.defaultModel=Ur(r.defaultModel,t,i),r?.amp&&typeof r.amp=="object"&&!Array.isArray(r.amp)&&(r.amp.defaultRoute=Ur(r.amp.defaultRoute,t,i)),Us(r,m=>Ur(m,t,i))}return M1(r)}function _1(e={},t=""){let n=Is(e),r=String(t||"").trim();if(!r)return n;let a=n.modelAliases&&typeof n.modelAliases=="object"&&!Array.isArray(n.modelAliases)?n.modelAliases:{};if(!Object.prototype.hasOwnProperty.call(a,r))return n;if(r===at)return a[r]={...a[r],id:at,strategy:String(a[r]?.strategy||"ordered").trim()||"ordered",targets:[],fallbackTargets:[]},n.modelAliases=a,wd(n);delete a[r],n.modelAliases=a;for(let o of Object.values(a))o.targets=Cn(o?.targets||[],i=>Ur(i,r)),o.fallbackTargets=Cn(o?.fallbackTargets||[],i=>Ur(i,r));return n.defaultModel=Ur(n.defaultModel,r),n?.amp&&typeof n.amp=="object"&&!Array.isArray(n.amp)&&(n.amp.defaultRoute=Ur(n.amp.defaultRoute,r)),Us(n,o=>Ur(o,r)),M1(n)}function k1(e="",t={}){return{id:String(e||t?.id||"").trim(),strategy:String(t?.strategy||"ordered").trim()||"ordered",targets:(Array.isArray(t?.targets)?t.targets:[]).map((n,r)=>({key:`target-${e||"alias"}-${r}-${String(n?.ref||"").trim()||"empty"}`,ref:String(n?.ref||"").trim(),sourceRef:String(n?.ref||"").trim(),weight:String(Number.isFinite(Number(n?.weight))&&Number(n.weight)>0?Math.floor(Number(n.weight)):1)})),fallbackTargets:(Array.isArray(t?.fallbackTargets)?t.fallbackTargets:[]).map((n,r)=>({key:`fallback-${e||"alias"}-${r}-${String(n?.ref||"").trim()||"empty"}`,ref:String(n?.ref||"").trim(),sourceRef:String(n?.ref||"").trim(),weight:String(Number.isFinite(Number(n?.weight))&&Number(n.weight)>0?Math.floor(Number(n.weight)):1)}))}}function L1(e={}){return(Array.isArray(e?.models)?e.models:[]).map((t,n)=>({key:`model-${e?.id||"provider"}-${n}-${String(t?.id||"").trim()||"empty"}`,id:String(t?.id||"").trim(),sourceId:String(t?.id||"").trim(),contextWindow:Number.isFinite(t?.contextWindow)?String(Math.floor(Number(t.contextWindow))):""}))}var Kg="__codex_cli_inherit__",y3=Object.freeze(["minimal","low","medium","high","xhigh"]),pk=Object.freeze(["low","medium","high","max"]),v3=Object.freeze({low:4096,medium:12e3,high:24e3,max:31999});function Fg(e){return String(e||"").trim()===Kg}function gk(e){let t=String(e||"").trim().toLowerCase();return pk.includes(t)?t:""}var D1=gk;var hk=/^\d*$/;function z1(e){let t=String(e??""),n=hk.test(t);return{accepted:n,draftValue:n?t:"",shouldCommit:n&&t!=="",commitValue:n&&t!==""?t:""}}var l=K(Be(),1),Ct={"content-type":"application/json"},I1={info:"bg-sky-50 text-sky-700 ring-sky-100",success:"bg-emerald-50 text-emerald-700 ring-emerald-100",warn:"bg-amber-50 text-amber-700 ring-amber-100",error:"bg-rose-50 text-rose-700 ring-rose-100"},yk=[{value:"usage",label:"Request / response"},{value:"router",label:"LLM Router"},{value:"all",label:"All categories"}],Ad={usage:{label:"Request / response",badgeVariant:"info",emptyLabel:"request/response"},router:{label:"LLM Router",badgeVariant:"outline",emptyLabel:"LLM Router"}},vk="https://github.com/khanglvm/llm-router",bk="https://github.com/sponsors/khanglvm",ni="AICodeClient/1.0.0",xk=3e3,Gg=4e3,Sk=100,wk=6,Md=/^[a-z][a-z0-9-]*$/,Ak=/^[A-Za-z0-9][A-Za-z0-9._:-]*$/,dC=[{value:"api",label:"API Key",description:"Test endpoint + model candidates with an API key env before saving."},{value:"oauth-gpt",label:"OAuth \xB7 GPT",description:"Use ChatGPT subscription login with GPT models."}],Wg=[{value:"auto",label:"Auto"},{value:"ordered",label:"Ordered"},{value:"round-robin",label:"Round robin"},{value:"weighted-rr",label:"Weighted RR"},{value:"quota-aware-weighted-rr",label:"Quota-aware weighted RR"}],Qg=Object.fromEntries(Wg.map(e=>[e.value,e.label])),Ck=Object.freeze([{value:"minimal",label:"Minimal",hint:"Fastest supported reasoning"},{value:"low",label:"Low",hint:"Lighter reasoning"},{value:"medium",label:"Medium",hint:"Balanced depth"},{value:"high",label:"High",hint:"Deeper reasoning"},{value:"xhigh",label:"XHigh",hint:"Model-dependent extra depth"}]),Rk=Object.freeze([{value:"low",label:"Low",hint:"Sets CLAUDE_CODE_EFFORT_LEVEL=low"},{value:"medium",label:"Medium",hint:"Sets CLAUDE_CODE_EFFORT_LEVEL=medium"},{value:"high",label:"High",hint:"Sets CLAUDE_CODE_EFFORT_LEVEL=high"},{value:"max",label:"Max",hint:"Sets CLAUDE_CODE_EFFORT_LEVEL=max"}]),U1=Hg;var Cd=Object.freeze({api:Object.freeze({openai:Object.freeze(["gpt-4o-mini","gpt-4.1-mini"]),claude:Object.freeze(["claude-3-5-sonnet","claude-3-5-haiku"])}),"oauth-gpt":Pg,"oauth-claude":Vg}),ml=Object.freeze({api:Object.freeze({limit:60,windowValue:1,windowUnit:"minute"}),oauth:Object.freeze({limit:999999,windowValue:1,windowUnit:"month"})}),j1=Object.freeze({api:Object.freeze({providerName:"My Provider",providerId:"my-provider",subscriptionProfile:""}),"oauth-gpt":Object.freeze({providerName:"ChatGPT Subscription",providerId:"chatgpt-sub",subscriptionProfile:""}),"oauth-claude":Object.freeze({providerName:"Claude Subscription",providerId:"claude-sub",subscriptionProfile:""})}),Ek=Object.freeze([{value:"ordered",label:"Ordered"},{value:"quota-balance",label:"Quota balance"}]),oh=Object.freeze([Object.freeze({id:"brave",label:"Brave",credentialField:"apiKey",credentialLabel:"API key",credentialPlaceholder:"brv_...",defaultLimit:1e3}),Object.freeze({id:"tavily",label:"Tavily",credentialField:"apiKey",credentialLabel:"API key",credentialPlaceholder:"tvly-...",defaultLimit:1e3}),Object.freeze({id:"exa",label:"Exa",credentialField:"apiKey",credentialLabel:"API key",credentialPlaceholder:"exa_...",defaultLimit:1e3}),Object.freeze({id:"searxng",label:"SearXNG",credentialField:"url",credentialLabel:"Base URL",credentialPlaceholder:"https://searx.example.com",defaultLimit:0})]),fo=Object.fromEntries(oh.map(e=>[e.id,e])),ri=5,Od=1,_d=20;function Xg(e){return Array.from(new Set(String(e||"").split(/[\s,]+/).map(t=>t.trim()).filter(Boolean)))}function $s(e){let t=String(e||"").trim();if(!t)return!1;try{let n=new URL(t);return n.protocol==="http:"||n.protocol==="https:"}catch{return!1}}function Hr(e=[],t=""){return Array.from(new Set([...(Array.isArray(e)?e:[]).map(n=>String(n||"").trim()).filter(Boolean),...Xg(t)]))}function fC(e=[],t,n){if(!t||!n||t===n)return e;let r=[...e],a=r.findIndex(s=>s?.key===t),o=r.findIndex(s=>s?.key===n);if(a===-1||o===-1)return e;let[i]=r.splice(a,1);return r.splice(o,0,i),r}function ih(e=[],t,n=r=>r?.key){if(!t)return e;let r=e.findIndex(i=>n(i)===t);if(r<=0)return e;let a=[...e],[o]=a.splice(r,1);return a.splice(r-1,0,o),a}function mC(e=[],t,n=r=>r?.key){if(!t)return e;let r=e.findIndex(i=>n(i)===t);if(r===-1||r>=e.length-1)return e;let a=[...e],[o]=a.splice(r,1);return a.splice(r+1,0,o),a}function P1(e,t=[]){let n=e?.getBoundingClientRect?.();return{top:Number.isFinite(n?.top)?Number(n.top):Number.NaN,left:Number.isFinite(n?.left)?Number(n.left):Number.NaN,windowX:typeof window>"u"?0:Number(window.scrollX||window.pageXOffset||0),windowY:typeof window>"u"?0:Number(window.scrollY||window.pageYOffset||0),containers:t.map(r=>({top:Number(r?.scrollTop||0),left:Number(r?.scrollLeft||0)}))}}function Tk(e,t,n=.5){return!e||!t||!Number.isFinite(t.top)||!Number.isFinite(t.left)||Math.abs(t.top-e.top)>n||Math.abs(t.left-e.left)>n||Math.abs(t.windowX-e.windowX)>n||Math.abs(t.windowY-e.windowY)>n||(e.containers?.length||0)!==(t.containers?.length||0)?!1:t.containers.every((r,a)=>{let o=e.containers[a];return o?Math.abs(r.top-o.top)<=n&&Math.abs(r.left-o.left)<=n:!1})}function V1(e){let t=String(e?.category||"").trim().toLowerCase();if(t==="usage"||t==="router")return t;let n=String(e?.source||"").trim().toLowerCase(),r=String(e?.kind||"").trim().toLowerCase();return n==="runtime"||r.startsWith("request")||r.startsWith("fallback")?"usage":"router"}var H1=["border-primary/45","bg-primary/5"];function pl(e,t){if(e?.classList){if(t){e.classList.add(...H1);return}e.classList.remove(...H1)}}function lh(e){return typeof e?.closest=="function"?e.closest("[data-reorder-row='true']"):null}function sh(e=[]){let t=(0,E.useRef)(new Map),n=(0,E.useRef)(new Map),r=(0,E.useRef)(new Map),a=(0,E.useRef)(""),o=JSON.stringify(e);return(0,E.useLayoutEffect)(()=>{let i=new Map;for(let f of e){let d=t.current.get(f);d&&i.set(f,d.getBoundingClientRect())}let s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;if(a.current!==""&&a.current!==o&&!s)for(let f of e){let d=r.current.get(f),p=i.get(f),m=t.current.get(f);if(!d||!p||!m)continue;let b=d.top-p.top;Math.abs(b)<1||typeof m.animate!="function"||m.animate([{transform:`translateY(${b}px)`},{transform:"translateY(0)"}],{duration:220,easing:"cubic-bezier(0.22, 1, 0.36, 1)"})}let u=new Set(e);for(let f of n.current.keys())u.has(f)||n.current.delete(f);r.current=i,a.current=o},[o]),(0,E.useMemo)(()=>i=>(n.current.has(i)||n.current.set(i,s=>{if(s){t.current.set(i,s);return}t.current.delete(i)}),n.current.get(i)),[])}function ch({className:e=""}){return(0,l.jsxs)("svg",{viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",className:e,children:[(0,l.jsx)("circle",{cx:"5",cy:"4",r:"1.25",fill:"currentColor"}),(0,l.jsx)("circle",{cx:"11",cy:"4",r:"1.25",fill:"currentColor"}),(0,l.jsx)("circle",{cx:"5",cy:"8",r:"1.25",fill:"currentColor"}),(0,l.jsx)("circle",{cx:"11",cy:"8",r:"1.25",fill:"currentColor"}),(0,l.jsx)("circle",{cx:"5",cy:"12",r:"1.25",fill:"currentColor"}),(0,l.jsx)("circle",{cx:"11",cy:"12",r:"1.25",fill:"currentColor"})]})}function Nk({className:e=""}){return(0,l.jsxs)("svg",{viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",className:e,children:[(0,l.jsx)("path",{d:"M8 12V4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"}),(0,l.jsx)("path",{d:"M4.75 7.25 8 4l3.25 3.25",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]})}function Mk({className:e=""}){return(0,l.jsxs)("svg",{viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",className:e,children:[(0,l.jsx)("path",{d:"M8 4v8",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"}),(0,l.jsx)("path",{d:"M4.75 8.75 8 12l3.25-3.25",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]})}function pC({className:e=""}){return(0,l.jsxs)("svg",{viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",className:e,children:[(0,l.jsx)("path",{d:"M8 3.5v9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"}),(0,l.jsx)("path",{d:"M3.5 8h9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]})}function Ok({className:e=""}){return(0,l.jsx)("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",className:e,children:(0,l.jsx)("path",{d:"M12 .5C5.65.5.5 5.65.5 12c0 5.08 3.29 9.39 7.86 10.91.58.11.79-.25.79-.56 0-.28-.01-1.2-.02-2.18-3.2.69-3.88-1.36-3.88-1.36-.52-1.33-1.28-1.68-1.28-1.68-1.05-.72.08-.71.08-.71 1.16.08 1.77 1.19 1.77 1.19 1.03 1.76 2.69 1.25 3.35.96.1-.74.4-1.25.72-1.54-2.56-.29-5.25-1.28-5.25-5.71 0-1.26.45-2.28 1.18-3.08-.12-.29-.51-1.46.11-3.05 0 0 .97-.31 3.17 1.18a10.9 10.9 0 0 1 5.77 0c2.2-1.49 3.17-1.18 3.17-1.18.62 1.59.23 2.76.11 3.05.74.8 1.18 1.82 1.18 3.08 0 4.44-2.69 5.41-5.26 5.69.41.35.78 1.05.78 2.11 0 1.52-.01 2.75-.01 3.12 0 .31.21.67.8.56A11.5 11.5 0 0 0 23.5 12C23.5 5.65 18.35.5 12 .5Z"})})}function _k({className:e=""}){return(0,l.jsx)("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",className:e,children:(0,l.jsx)("path",{d:"M12 21.3 10.9 20.3C5.4 15.3 2 12.3 2 8.5 2 5.4 4.4 3 7.5 3c1.8 0 3.5.8 4.5 2.1C13 3.8 14.7 3 16.5 3 19.6 3 22 5.4 22 8.5c0 3.8-3.4 6.8-8.9 11.8L12 21.3Z"})})}function kk({className:e=""}){return(0,l.jsx)("svg",{viewBox:"0 0 20 20",fill:"currentColor","aria-hidden":"true",className:e,children:(0,l.jsx)("path",{d:"M6.25 4.7a.75.75 0 0 1 1.14-.64l8.1 5.05a1.05 1.05 0 0 1 0 1.78l-8.1 5.05a.75.75 0 0 1-1.14-.64V4.7Z"})})}function Lk({className:e=""}){return(0,l.jsx)("svg",{viewBox:"0 0 20 20",fill:"currentColor","aria-hidden":"true",className:e,children:(0,l.jsx)("path",{d:"M6.25 4.5A1.25 1.25 0 0 1 7.5 3.25h.5a1.25 1.25 0 0 1 1.25 1.25v11A1.25 1.25 0 0 1 8 16.75h-.5a1.25 1.25 0 0 1-1.25-1.25v-11Zm4.5 0A1.25 1.25 0 0 1 12 3.25h.5a1.25 1.25 0 0 1 1.25 1.25v11A1.25 1.25 0 0 1 12.5 16.75H12a1.25 1.25 0 0 1-1.25-1.25v-11Z"})})}function Dk({className:e=""}){return(0,l.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:e,children:[(0,l.jsx)("path",{d:"M2.75 6.5A1.75 1.75 0 0 1 4.5 4.75h3L9.4 6.4h6.1a1.75 1.75 0 0 1 1.75 1.75v6.35a1.75 1.75 0 0 1-1.75 1.75h-11A1.75 1.75 0 0 1 2.75 14.5v-8Z"}),(0,l.jsx)("path",{d:"M2.75 8h14.5"})]})}function zk({className:e=""}){return(0,l.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:e,children:[(0,l.jsx)("path",{d:"M10 3.25v5"}),(0,l.jsx)("path",{d:"M6.1 5.15a6.25 6.25 0 1 0 7.8 0"})]})}function Ks({disabled:e=!1,label:t="Move up",onClick:n}){return(0,l.jsx)(ce,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 rounded-full p-0",onMouseDown:r=>r.preventDefault(),onClick:n,disabled:e,"aria-label":t,title:t,children:(0,l.jsx)(Nk,{className:"h-3.5 w-3.5"})})}function kd({disabled:e=!1,label:t="Move down",onClick:n}){return(0,l.jsx)(ce,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 rounded-full p-0",onMouseDown:r=>r.preventDefault(),onClick:n,disabled:e,"aria-label":t,title:t,children:(0,l.jsx)(Mk,{className:"h-3.5 w-3.5"})})}function q1({active:e=!1}){return e?(0,l.jsx)("span",{"aria-hidden":"true",className:"inline-flex h-2.5 w-2.5 rounded-full bg-emerald-500"}):null}var Ld="w-[5.5rem] justify-self-end";function uh(e){let t=String(e||"").trim().toLowerCase();return t==="automatic"||t==="smart"?"auto":t==="rr"?"round-robin":t==="weighted-round-robin"||t==="weighted_rr"?"weighted-rr":t==="quota-aware-weighted-round-robin"?"quota-aware-weighted-rr":Object.prototype.hasOwnProperty.call(Qg,t)?t:"ordered"}function gC(e){let t=uh(e);return Qg[t]||Qg.ordered}function ba(e=[]){return Array.from(new Set((e||[]).map(t=>String(t||"").trim()).filter(Boolean)))}function dh(e=[]){let t=new Set;for(let n of(e||[]).map(r=>String(r||"").trim()).filter(Boolean)){if(t.has(n))return!0;t.add(n)}return!1}function Bk(e=[],t="",n=-1){let r=String(t||"").trim().toLowerCase();return r?(e||[]).some((a,o)=>o!==n&&String(a?.name||"").trim().toLowerCase()===r):!1}function Ik(){return{id:"",strategy:"auto",targets:[{ref:""}],fallbackTargets:[]}}function Uk(e="",t={},{isNew:n=!1}={}){return JSON.stringify({aliasId:n?"":String(e||"").trim(),id:String(t?.id||(n?"":e)||"").trim(),strategy:String(t?.strategy||"ordered").trim()||"ordered",targets:(Array.isArray(t?.targets)?t.targets:[]).map(r=>String(r?.ref||"").trim()),fallbackTargets:(Array.isArray(t?.fallbackTargets)?t.fallbackTargets:[]).map(r=>String(r?.ref||"").trim())})}function Zg(){if(typeof globalThis<"u"&&globalThis.crypto?.getRandomValues){let t=new Uint8Array(18);return globalThis.crypto.getRandomValues(t),`gw_${Array.from(t,n=>n.toString(16).padStart(2,"0")).join("")}`}return`gw_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`}function Dd(e){return/^[A-Z][A-Z0-9_]*$/.test(String(e||"").trim())}function Vr(e){let t=String(e||"").toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").replace(/-{2,}/g,"-");return t?/^[a-z]/.test(t)?t:`provider-${t}`:""}function $1(e,t){let n=Number.parseInt(String(e||""),10);return Number.isFinite(n)&&n>0?n:t}function Rd(e={}){return ba((Array.isArray(e?.models)?e.models:[]).map(t=>t?.id))}function hC(e={},{keyPrefix:t="rate-limit",index:n=0,defaults:r=ml.api,useDefaults:a=!0}={}){let o=String(e?.sourceId||e?.id||"").trim(),i=e?.requests??e?.limit,s=e?.windowValue??e?.window?.size??e?.window?.value,c=e?.windowUnit??e?.window?.unit;return{key:String(e?.key||"").trim()||`${t}-${o||n+1}`,sourceId:o,models:Ir(Array.isArray(e?.models)?e.models:[]),modelsDraft:String(e?.modelsDraft||""),requests:i!==void 0?String(i):a?String(r.limit??""):"",windowValue:s!==void 0?String(s):a?String(r.windowValue??""):"",windowUnit:String(c!==void 0?c:a?r.windowUnit:"minute").trim()||"minute"}}function fh(e=[],{keyPrefix:t="rate-limit",defaults:n=ml.api,includeDefault:r=!0}={}){return(Array.isArray(e)&&e.length>0?e:r?[{models:["all"],requests:n.limit,window:{size:n.windowValue,unit:n.windowUnit}}]:[]).map((o,i)=>hC(o,{keyPrefix:t,index:i,defaults:n,useDefaults:!0}))}function Jg(e={}){return Ir(Hr(e?.models,e?.modelsDraft||"")).length===0&&!String(e?.requests??"").trim()&&!String(e?.windowValue??"").trim()}function xa(e=[]){return(Array.isArray(e)?e:[]).map((t,n)=>({key:String(t?.key||`rate-limit-${n+1}`).trim()||`rate-limit-${n+1}`,sourceId:String(t?.sourceId||"").trim(),models:Ir(Hr(t?.models,t?.modelsDraft||"")),requests:String(t?.requests??"").trim(),windowValue:String(t?.windowValue??"").trim(),windowUnit:ei(t?.windowUnit,"minute")})).filter((t,n)=>!Jg({...e?.[n]||{},...t}))}function K1(e=[]){return xa(e).map(t=>({sourceId:t.sourceId,models:t.models,requests:t.requests,windowValue:t.windowValue,windowUnit:t.windowUnit}))}function jk(e=[]){let t=Array.isArray(e)?e.filter(Boolean):[];return t.length===0?"":t.length===1?R1(t[0]):`${t.length} rate limits`}function gl(e){return JSON.parse(JSON.stringify(e??{}))}function F1(e,t={}){try{let n=JSON.parse(String(e||"{}"));return n&&typeof n=="object"&&!Array.isArray(n)?n:t}catch{return t}}function zd(e=ni){return[{name:"User-Agent",value:String(e||ni)}]}function mh(e=[]){return(Array.isArray(e)?e:[]).map(t=>({name:String(t?.name||""),value:t?.value===void 0||t?.value===null?"":String(t.value)}))}function Pk(e,t=ni){if(!e||typeof e!="object"||Array.isArray(e))return zd(t);let n=Object.entries(e).map(([r,a])=>({name:String(r||""),value:a==null?"":String(a)})).filter(r=>r.name.trim());return n.length>0?n:zd(t)}function ph(e=[]){let t={};for(let n of mh(e)){let r=String(n.name||"").trim();if(!r)continue;let a=r.toLowerCase()==="user-agent",o=String(n.value||"").trim();!o&&!a||(t[r]=o)}return t}function G1(e={}){return JSON.stringify({connectionType:String(e?.connectionType||""),endpoints:Array.isArray(e?.endpoints)?e.endpoints.map(t=>String(t||"").trim()).filter(Boolean):[],apiKeyEnv:String(e?.apiKeyEnv||"").trim(),headers:ph(e?.headerRows||[])})}function hl(e,t){return String(e||"").trim().startsWith(`${t}/`)}function gh(e){let t=Object.keys(e?.modelAliases||{});if(t.includes(at))return at;if(t.length>0)return t[0];let n=(e?.providers||[]).find(r=>(r?.models||[]).length>0);return n?.models?.[0]?.id?`${n.id}/${n.models[0].id}`:void 0}function Vk(e,t={}){try{let n=String(e||"").trim()?JSON.parse(e):{};return!n||typeof n!="object"||Array.isArray(n)?{value:t,parseError:"Config root must be a JSON object."}:{value:n,parseError:""}}catch(n){return{value:t,parseError:n instanceof Error?n.message:String(n)}}}function Y1(e){return String(e||"").split("-").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function W1(e){let t=String(e||"").trim();if(!t)return"";let n=xd.find(o=>o?.id===t);if(n?.defaultMatch)return String(n.defaultMatch).trim();let r=Ds.find(o=>o?.id===t);if(!r)return"";let a=[...new Set((r.signatures||[]).map(o=>xd.find(i=>i?.id===o)?.defaultMatch).map(o=>String(o||"").trim()).filter(Boolean))];return a.length===1?a[0]:a.join(" | ")}function Hk(){return Ls}function qk(e){let t=String(e||"").trim();return t?t.length<=10?`${t.slice(0,2)}\u2026${t.slice(-2)}`:`${t.slice(0,4)}\u2026${t.slice(-4)}`:""}function zn(e={}){let t=gl(e&&typeof e=="object"&&!Array.isArray(e)?e:{});return(!t.amp||typeof t.amp!="object"||Array.isArray(t.amp))&&(t.amp={}),(!t.amp.routes||typeof t.amp.routes!="object"||Array.isArray(t.amp.routes))&&(t.amp.routes={}),Array.isArray(t.amp.rawModelRoutes)||(t.amp.rawModelRoutes=[]),(!t.amp.overrides||typeof t.amp.overrides!="object"||Array.isArray(t.amp.overrides))&&(t.amp.overrides={}),Array.isArray(t.amp.overrides.entities)||(t.amp.overrides.entities=[]),t.amp.restrictManagementToLocalhost===void 0&&(t.amp.restrictManagementToLocalhost=!0),String(t.amp.preset||"").trim()||(t.amp.preset="builtin"),String(t.amp.defaultRoute||"").trim()||(t.amp.defaultRoute=String(t.defaultModel||gh(t)||"").trim()),t}function va(e,t=0,{min:n=0,max:r=Number.MAX_SAFE_INTEGER}={}){let a=Number.parseInt(String(e??""),10);return Number.isFinite(a)?Math.min(r,Math.max(n,a)):t}function ai(e={}){let t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},n=t.amp?.webSearch&&typeof t.amp.webSearch=="object"&&!Array.isArray(t.amp.webSearch)?gl(t.amp.webSearch):null;(!t.webSearch||typeof t.webSearch!="object"||Array.isArray(t.webSearch))&&(t.webSearch=n||{}),t.amp&&typeof t.amp=="object"&&!Array.isArray(t.amp)&&Object.prototype.hasOwnProperty.call(t.amp,"webSearch")&&delete t.amp.webSearch;let r=String(t.webSearch.strategy||"").trim();return t.webSearch.strategy=r==="quota-balance"?"quota-balance":"ordered",t.webSearch.count!==void 0&&t.webSearch.count!==null&&String(t.webSearch.count).trim()!==""?t.webSearch.count=va(t.webSearch.count,ri,{min:Od,max:_d}):delete t.webSearch.count,Array.isArray(t.webSearch.providers)||(t.webSearch.providers=[]),t.webSearch}function yC(e=""){return String(e||"").trim().includes("/")}function en(e=""){let t=String(e||"").trim();return yC(t)?t:t.toLowerCase()}function yl(e="",t=""){let n=String(e||"").trim(),r=String(t||"").trim();return!n||!r?"":`${n}/${r}`}function $k(e={}){return[...new Set([e?.format,...Array.isArray(e?.formats)?e.formats:[]].map(t=>String(t||"").trim().toLowerCase()).filter(t=>t==="openai"||t==="claude"))]}function Kk(e={},t={}){let n=String(t?.id||"").trim(),r=n?String(e?.lastProbe?.modelPreferredFormat?.[n]||"").trim().toLowerCase():"";if(r==="openai"||r==="claude")return[r];let a=n?[...new Set((Array.isArray(e?.lastProbe?.modelSupport?.[n])?e.lastProbe.modelSupport[n]:[]).map(o=>String(o||"").trim().toLowerCase()).filter(o=>o==="openai"||o==="claude"))]:[];return a.length>0?a:[...new Set([t?.format,...Array.isArray(t?.formats)?t.formats:[]].map(o=>String(o||"").trim().toLowerCase()).filter(o=>o==="openai"||o==="claude"))]}function vC(e={}){let t=String(e?.subscriptionType||e?.subscription_type||"").trim().toLowerCase();return String(e?.type||"").trim().toLowerCase()==="subscription"?t==="chatgpt-codex":$k(e).includes("openai")?!!String(e?.baseUrlByFormat?.openai||e?.baseUrl||"").trim():!1}function Fk(e={}){return String(e?.type||"").trim().toLowerCase()==="subscription"?String(e?.subscriptionType||e?.subscription_type||"").trim().toLowerCase()==="chatgpt-codex":String(e?.apiKey||"").trim()||String(e?.apiKeyEnv||"").trim()||String(e?.auth?.type||"").trim().toLowerCase()==="none"?!0:Object.keys(e?.headers&&typeof e.headers=="object"?e.headers:{}).some(t=>{let n=String(t||"").trim().toLowerCase();return n==="authorization"||n==="x-api-key"})}function Gk(e={},t={}){if(!vC(e))return!1;let n=Kk(e,t);return n.length===0||n.includes("openai")}function Pr(e={},t=[]){return!e||typeof e!="object"||Array.isArray(e)?!1:t.some(n=>Object.prototype.hasOwnProperty.call(e,n)&&e[n]!==void 0&&e[n]!==null&&String(e[n]).trim()!=="")}function Vs(e={},t=""){let n=String(t||e?.id||"").trim().toLowerCase(),r=fo[n];if(!r)return null;let a=r.credentialField,o=String(e?.[a]||"").trim(),i=Pr(e,["count","resultCount","result-count","resultsPerCall","results-per-call"]),s=Pr(e,["limit","monthlyLimit","monthly-limit","quota"]),c=Pr(e,["remaining","remainingQuota","remaining-quota","remainingQueries","remaining-queries"]),u=!!o||s||c,f=u&&Number(r.defaultLimit)||0,d=va(e?.count??e?.resultCount??e?.["result-count"]??e?.resultsPerCall??e?.["results-per-call"],ri,{min:Od,max:_d}),p=va(e?.limit,f,{min:0}),m=p>0?p:0,b=va(e?.remaining,m,{min:0});return{kind:"builtin",id:n,[a]:o,...i&&d!==ri?{count:d}:{},...s||u&&p>0?{limit:p}:{},...c||u&&(p>0||b>0)?{remaining:p>0?Math.min(b,p):b}:{}}}function Yk(e={},t=""){let n=String(t||e?.id||yl(e?.providerId??e?.provider,e?.model??e?.modelId)).trim();if(!yC(n))return null;let r=String(e?.providerId??e?.provider??n.slice(0,n.indexOf("/"))).trim(),a=String(e?.model??e?.modelId??n.slice(n.indexOf("/")+1)).trim(),o=yl(r,a);return!o||o!==n?null:{kind:"hosted",id:o,providerId:r,model:a}}function Wk(e={},t=""){return Yk(e,t)||Vs(e,t)}function Qk(e={},t=new Set){return(Array.isArray(e?.providers)?e.providers:[]).map(r=>{let a=String(r?.id||"").trim();if(!a||r?.enabled===!1||!vC(r)||!Fk(r))return null;let o=(Array.isArray(r?.models)?r.models:[]).map(i=>{let s=String(i?.id||"").trim(),c=yl(a,s);return!s||!c||t.has(c)||!Gk(r,i)||!s.toLowerCase().includes("gpt")?null:{value:s,label:s,routeId:c}}).filter(Boolean);return o.length===0?null:{providerId:a,providerLabel:String(r?.name||a).trim()||a,providerHint:String(r?.subscriptionType||"").trim().toLowerCase()==="chatgpt-codex"?"ChatGPT subscription":String(r?.baseUrlByFormat?.openai||r?.baseUrl||"").trim()||"OpenAI-compatible endpoint",models:o}}).filter(Boolean)}function Xk(e={},t=null){let n=zn(e),r=ai(n),a=Array.isArray(r.providers)?r.providers.map(d=>Wk(d,d?.id)).filter(Boolean):[],o=new Set(a.map(d=>en(d.id))),i=[...a,...oh.filter(d=>!o.has(d.id)).map(d=>Vs({id:d.id},d.id)).filter(Boolean)],s=Array.isArray(t?.providers)?t.providers:[],c=new Map(s.map(d=>[en(d?.id),d]).filter(([d])=>!!d)),u=new Map((Array.isArray(e?.providers)?e.providers:[]).map(d=>[String(d?.id||"").trim(),d]).filter(([d])=>!!d)),f=va(r?.count,ri,{min:Od,max:_d});return i.map(d=>{let p=en(d.id),m=c.get(p)||null,b=a.findIndex(T=>en(T.id)===p),g=i.findIndex(T=>en(T.id)===p),x=d.kind==="hosted"?m?.ready!==!1:!!d?.[fo[d.id]?.credentialField||"apiKey"];if(d.kind==="hosted"){let T=u.get(d.providerId)||null;return{id:d.id,key:d.id,kind:"hosted",label:String(T?.name||d.providerId).trim()||d.providerId,providerId:d.providerId,modelId:d.model,routeId:d.id,configured:!0,configuredIndex:b,configuredCount:a.length,displayIndex:g,displayCount:i.length,active:x,runtimeState:m}}let y=fo[d.id],h=y?.credentialField||"apiKey",v=String(d?.[h]||"").trim(),S=Pr(d,["count"]),C=va(d?.count,f,{min:Od,max:_d});return{id:d.id,key:d.id,kind:"builtin",label:y?.label||d.id,credentialField:h,credentialLabel:y?.credentialLabel||"Credential",credentialPlaceholder:y?.credentialPlaceholder||"",credentialValue:v,resultPerCall:C,resultPerCallInput:S?String(C):f!==ri?String(f):"",limit:va(d?.limit,y?.defaultLimit||0,{min:0}),remaining:va(d?.remaining,y?.defaultLimit||0,{min:0}),configured:!!v,configuredIndex:b,configuredCount:a.length,displayIndex:g,displayCount:i.length,active:x,runtimeState:m}})}function Zk(e={},t={}){let n=zn(e),r=ai(n);return t.strategy!==void 0&&(r.strategy=String(t.strategy||"").trim()==="quota-balance"?"quota-balance":"ordered"),t.count!==void 0&&(r.count=va(t.count,r.count,{min:1,max:20})),n}function Jk(e={},t,n={}){let r=String(t||"").trim().toLowerCase();if(!fo[r])return zn(e);let a=zn(e),o=ai(a),i=Array.isArray(o.providers)?o.providers.slice():[],s=i.findIndex(h=>en(h?.id)===r),c=s>=0?i[s]:null,u=Vs(c||{id:r},r)||Vs({id:r},r),d=fo[r].credentialField,p=Vs({...c&&typeof c=="object"&&!Array.isArray(c)?c:{},...u,...n,id:r,[d]:n[d]!==void 0?String(n[d]||"").trim():u?.[d]},r),m=!!String(p?.[d]||"").trim(),b=Pr(n,["count"])?!!String(n?.count||"").trim()&&Number(p?.count)!==ri:Pr(c,["count"])&&Number(p?.count)!==ri,g=m||Pr(n,["limit"])||Pr(c,["limit"]),x=m||Pr(n,["remaining"])||Pr(c,["remaining"]),y={id:r,...m?{[d]:String(p?.[d]||"").trim()}:{},...b?{count:Number(p.count)}:{},...g&&Number(p?.limit)>0?{limit:Number(p.limit)}:{},...x&&(Number(p?.limit)>0||Number(p?.remaining)>0)?{remaining:Number(p.remaining)}:{}};return s>=0?i[s]=y:i.push(y),o.providers=i,a}function e2(e={},t,n){let r=yl(t,n);if(!r)return zn(e);let a=zn(e),o=ai(a),i=Array.isArray(o.providers)?o.providers.slice():[],s=en(r);return i.some(c=>en(c?.id)===s)||(i.push({id:r,providerId:String(t||"").trim(),model:String(n||"").trim()}),o.providers=i),a}function t2(e={},t){let n=en(t),r=zn(e),a=ai(r),o=Array.isArray(a.providers)?a.providers.slice():[],i=o.filter(s=>en(s?.id)!==n);return i.length===o.length||(a.providers=i),r}function n2(e={},t,n="up"){let r=en(t),a=zn(e),o=ai(a),i=Array.isArray(o.providers)?o.providers.slice():[],s=new Map(i.map(g=>[en(g?.id),g]).filter(([g])=>!!g)),c=i.findIndex(g=>en(g?.id)===r);if(c!==-1){let g=n==="down"?c+1:c-1;if(g<0||g>=i.length)return a;let[x]=i.splice(c,1);return i.splice(g,0,x),o.providers=i,a}if(!fo[r])return a;let u=[...i.map(g=>en(g?.id)).filter(Boolean),...oh.map(g=>g.id).filter(g=>!s.has(g))],f=u.indexOf(r);if(f===-1)return a;let d=n==="down"?f+1:f-1;if(d<0||d>=u.length)return a;let p=u.slice(),[m]=p.splice(f,1);p.splice(d,0,m);let b=new Set(s.keys());b.add(r);for(let g of p.slice(0,d+1))fo[g]&&b.add(g);return o.providers=p.filter(g=>b.has(g)).map(g=>s.get(g)||{id:g}),a}function r2(e,t,n){let r=String(e||"").trim().toLowerCase(),a=fo[r];return!a||String(t||"").trim()!==a.credentialField?!1:!String(n||"").trim()}function Q1(e={}){let t=[],n=e?.modelAliases&&typeof e.modelAliases=="object"&&!Array.isArray(e.modelAliases)?e.modelAliases:{};for(let a of Object.keys(n))t.push({value:a,label:a,hint:`Alias \xB7 ${(n[a]?.targets||[]).length||0} target(s)`,kind:"alias",groupKey:"aliases",groupLabel:"Aliases"});for(let a of Array.isArray(e?.providers)?e.providers:[]){let o=String(a?.id||"").trim(),i=String(a?.name||o||"provider").trim()||"provider";for(let s of Array.isArray(a?.models)?a.models:[]){let c=String(s?.id||"").trim();if(!o||!c)continue;let u=Number.isFinite(s?.contextWindow)?Number(s.contextWindow):null;t.push({value:`${o}/${c}`,label:`${o}/${c}`,hint:u?`${i} \xB7 ${Hs(u)}`:i,kind:"model",providerId:o,groupKey:`provider:${o}`,groupLabel:i})}}let r=new Set;return t.filter(a=>!a?.value||r.has(a.value)?!1:(r.add(a.value),!0))}function a2(e=""){let t=String(e||"").trim();if(!t)return{};let n=t.startsWith("alias:")?t.slice(6).trim():t;if(!n.includes("/"))return{kind:"alias",groupKey:"aliases",groupLabel:"Aliases"};let r=n.indexOf("/"),a=n.slice(0,r).trim();return a?{kind:"model",providerId:a,groupKey:`provider:${a}`,groupLabel:a}:{}}function Hs(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)return"Unknown";if(t>=1e3){let n=t/1e3;return`${Number.isInteger(n)?String(n):n.toFixed(1).replace(/\.0$/,"")}K`}return String(t)}function o2(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)return"";let n=[{suffix:"M",divisor:1e3*1e3},{suffix:"K",divisor:1e3}];for(let r of n){if(t<r.divisor)continue;let a=t/r.divisor;return`${a>=10?String(Math.round(a)):a.toFixed(1).replace(/\.0$/,"")}${r.suffix}`}return String(t)}function Ed(e){let t=so(e),n=Number(t);return!Number.isFinite(n)||n<=0?String(e||""):new Intl.NumberFormat().format(n)}function i2(e={}){let t=new Map;for(let n of Array.isArray(e?.providers)?e.providers:[]){let r=String(n?.id||"").trim();if(r)for(let a of Array.isArray(n?.models)?n.models:[]){let o=String(a?.id||"").trim();o&&t.set(`${r}/${o}`,{ref:`${r}/${o}`,providerId:r,providerName:String(n?.name||r).trim()||r,modelId:o,contextWindow:Number.isFinite(a?.contextWindow)?Number(a.contextWindow):null})}}return t}function l2(e="",t={}){let n=t?.modelAliases&&typeof t.modelAliases=="object"&&!Array.isArray(t.modelAliases)?t.modelAliases:{},r=i2(t),a=new Set,o=new Set,i=[],s=[];function c(m){let b=String(m||"").trim();if(!b)return;if(r.has(b)){if(o.has(b))return;o.add(b),i.push(r.get(b));return}let g=b.startsWith("alias:")?b.slice(6).trim():b;if(!g||!Object.prototype.hasOwnProperty.call(n,g)){s.includes(b)||s.push(b);return}if(a.has(g))return;a.add(g);let x=n[g];for(let y of[...x?.targets||[],...x?.fallbackTargets||[]])c(y?.ref)}c(e);let u=i.filter(m=>Number.isFinite(m?.contextWindow)),f=[...new Set(u.map(m=>m.contextWindow))].sort((m,b)=>m-b),d=f[0]??null,p=f[f.length-1]??null;return{aliasId:e,models:i,unknownRefs:s,smallestContextWindow:d,largestContextWindow:p,hasMixedContextWindows:f.length>1}}function s2(e={}){let t=e?.modelAliases&&typeof e.modelAliases=="object"&&!Array.isArray(e.modelAliases)?e.modelAliases:{};return Object.keys(t).map(n=>l2(n,e)).filter(n=>n.hasMixedContextWindows).sort((n,r)=>String(n.aliasId||"").localeCompare(String(r.aliasId||"")))}function Fs(e=[],t=[]){let n=[...Array.isArray(e)?e:[]],r=new Set(n.map(a=>String(a?.value||"").trim()).filter(Boolean));for(let a of(Array.isArray(t)?t:[]).map(o=>String(o||"").trim()).filter(Boolean))r.has(a)||(r.add(a),n.push({value:a,label:a,hint:"Current config",...a2(a)}));return n}function c2(e=[]){let t=[],n=new Map,r=null;for(let a of(Array.isArray(e)?e:[]).filter(Boolean)){let o=String(a?.groupKey||a?.groupLabel||"").trim(),i=String(a?.groupLabel||"").trim();if(!o){r||(r={key:"__ungrouped__",label:"",options:[]},t.push(r)),r.options.push(a);continue}let s=n.get(o);s||(s={key:o,label:i||o,options:[]},n.set(o,s),t.push(s)),s.options.push(a)}return t}function u2(e={},{includeHint:t=!1}={}){let n=String(e?.label||e?.value||"").trim()||String(e?.value||"").trim(),r=String(e?.hint||"").trim();return t&&r?`${n} \xB7 ${r}`:n}function Bd(e=[],{keyPrefix:t="select-option",includeHint:n=!1}={}){return c2(e).map((r,a)=>{let o=r.options.map(i=>(0,l.jsx)(ar,{value:i.value,searchText:`${i.label||""} ${i.value||""} ${i.hint||""} ${r.label||""}`,children:u2(i,{includeHint:n})},`${t}-${i.value}`));return r.label?(0,l.jsxs)(Ug,{children:[(0,l.jsx)(A1,{children:r.label}),o]},`${t}-group-${r.key||a}`):o})}function d2({bindingValue:e="",thinkingLevel:t="",configFilePath:n="",endpointUrl:r=""}={}){let a=String(e||"").trim(),o=String(t||"").trim(),i=String(n||"").trim(),s=String(r||"").trim(),c=Fg(a),u=c?"Mode: Inherit Codex model":a?`Mode: Pinned to ${a}`:"Mode: Choose a route",f=c?{variant:"success",title:"Inherit mode keeps Codex-native model picks intact.",body:(0,l.jsxs)(l.Fragment,{children:["Codex CLI still chooses its own model name. Create a same-name alias in the ",(0,l.jsx)("span",{className:"font-medium",children:"Alias & Fallback"})," tab so LLM Router can resolve that name to the real upstream target you want."]})}:a?{variant:"info",title:"Pinned mode forces one router target.",body:(0,l.jsxs)(l.Fragment,{children:["LLM Router writes ",(0,l.jsxs)("code",{children:["model=",a]})," into Codex CLI config. That is the simplest setup when every Codex session should use one managed route or alias."]})}:{variant:"warning",title:"Choose your model strategy before you connect.",body:(0,l.jsxs)(l.Fragment,{children:["Pick ",(0,l.jsx)("span",{className:"font-medium",children:"Inherit Codex CLI model"})," if Codex should keep using its built-in model names, or pick one managed route/alias if you want a single fixed target."]})};return{title:"Codex CLI guide",description:"Quick setup for routing Codex CLI through LLM Router while keeping model routing easy to inspect and change later.",badges:[{label:u,variant:c?"success":a?"info":"outline"},{label:o?`Thinking: ${o}`:"Thinking: Codex default",variant:"outline"},{label:i?"Config file detected":"User config: ~/.codex/config.toml",variant:"outline"}],callout:f,highlights:[{eyebrow:"1. Connect",title:"Point Codex CLI at LLM Router",body:s?(0,l.jsxs)(l.Fragment,{children:["When connected, Codex sends requests to ",(0,l.jsx)("code",{children:s}),". LLM Router then handles upstream auth, alias resolution, and failover."]}):(0,l.jsxs)(l.Fragment,{children:["Click ",(0,l.jsx)("span",{className:"font-medium",children:"Connect"})," to patch Codex CLI so it talks to LLM Router instead of a provider directly."]})},{eyebrow:"2. Route",title:"Choose between inherit and pinned mode",body:c?(0,l.jsxs)(l.Fragment,{children:["Keep Codex model names such as ",(0,l.jsx)("code",{children:"gpt-5.4"}),", then create matching aliases in LLM Router, for example ",(0,l.jsx)("code",{children:"gpt-5.4"})," -> ",(0,l.jsx)("code",{children:"demo/gpt-4o-mini"}),"."]}):(0,l.jsxs)(l.Fragment,{children:["Select one managed route or alias in ",(0,l.jsx)("span",{className:"font-medium",children:"Default model"})," when you want every Codex request to land on the same router target."]})},{eyebrow:"3. Tune",title:"Optional reasoning control",body:(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("span",{className:"font-medium",children:"Thinking level"})," writes Codex CLI ",(0,l.jsx)("code",{children:"model_reasoning_effort"})," with the official values ",(0,l.jsx)("code",{children:"minimal"}),", ",(0,l.jsx)("code",{children:"low"}),", ",(0,l.jsx)("code",{children:"medium"}),", ",(0,l.jsx)("code",{children:"high"}),", or ",(0,l.jsx)("code",{children:"xhigh"}),"."]})}],sections:[{title:"Quick start",items:[(0,l.jsxs)(l.Fragment,{children:["Set a ",(0,l.jsx)("code",{children:"masterKey"})," in LLM Router first. The ",(0,l.jsx)("span",{className:"font-medium",children:"Connect"})," button stays disabled until gateway auth is ready."]}),(0,l.jsxs)(l.Fragment,{children:["Click ",(0,l.jsx)("span",{className:"font-medium",children:"Connect"})," to patch the Codex CLI config file and router base URL."]}),c?(0,l.jsxs)(l.Fragment,{children:["Leave ",(0,l.jsx)("span",{className:"font-medium",children:"Default model"})," on ",(0,l.jsx)("span",{className:"font-medium",children:"Inherit Codex CLI model"}),", then create aliases that match the Codex model names you actually use."]}):a?(0,l.jsxs)(l.Fragment,{children:["Your current default is pinned to ",(0,l.jsx)("code",{children:a}),". Change it only when you want Codex to use a different managed route or alias."]}):(0,l.jsxs)(l.Fragment,{children:["Choose either ",(0,l.jsx)("span",{className:"font-medium",children:"Inherit Codex CLI model"})," or one managed route/alias in ",(0,l.jsx)("span",{className:"font-medium",children:"Default model"})," before you start using Codex through the router."]}),(0,l.jsxs)(l.Fragment,{children:["Set ",(0,l.jsx)("span",{className:"font-medium",children:"Thinking level"})," only when you want LLM Router to write ",(0,l.jsx)("code",{children:"model_reasoning_effort"}),"; leave it unset to keep Codex CLI defaults."]})]},{title:"Choose the right model strategy",items:[(0,l.jsxs)(l.Fragment,{children:["Use ",(0,l.jsx)("span",{className:"font-medium",children:"Inherit Codex CLI model"})," when you want Codex-native model names and model-specific UI/options to remain visible."]}),(0,l.jsx)(l.Fragment,{children:"Use a fixed route or alias when your team wants one centrally managed target regardless of what Codex would otherwise choose."}),(0,l.jsx)(l.Fragment,{children:"If Codex-specific options disappear after pinning a route, switch back to inherit mode and route those same model names through aliases instead."})]},{title:"Where these settings land",items:[i?(0,l.jsxs)(l.Fragment,{children:["This page is currently managing ",(0,l.jsx)("code",{children:i}),"."]}):(0,l.jsxs)(l.Fragment,{children:["Codex CLI usually stores user settings in ",(0,l.jsx)("code",{children:"~/.codex/config.toml"}),". Trusted projects can also add overrides in ",(0,l.jsx)("code",{children:".codex/config.toml"}),"."]}),(0,l.jsxs)(l.Fragment,{children:["The router-managed bindings in this panel map to Codex CLI ",(0,l.jsx)("code",{children:"model"})," and ",(0,l.jsx)("code",{children:"model_reasoning_effort"}),"."]}),(0,l.jsxs)(l.Fragment,{children:["Use ",(0,l.jsx)("span",{className:"font-medium",children:"Open Codex CLI Config File"})," whenever you want to inspect the exact generated config."]})]},{title:"Quick verify",items:[(0,l.jsx)(l.Fragment,{children:"Open the config file from this page and confirm the values match the mode you intended."}),(0,l.jsx)(l.Fragment,{children:"Start Codex CLI and run a small prompt. If inherit mode is on, make sure the Codex model you selected has a same-name alias in LLM Router."}),(0,l.jsxs)(l.Fragment,{children:["If requests fail after switching models, check the ",(0,l.jsx)("span",{className:"font-medium",children:"Alias & Fallback"})," tab first because the alias behind that model name may be missing or pointed at the wrong target."]})]}]}}function f2({bindings:e={},settingsFilePath:t="",endpointUrl:n=""}={}){let r=String(e?.primaryModel||"").trim(),a=String(e?.defaultOpusModel||"").trim(),o=String(e?.defaultSonnetModel||"").trim(),i=String(e?.defaultHaikuModel||"").trim(),s=String(e?.subagentModel||"").trim(),c=D1(e?.thinkingLevel),u=String(t||"").trim(),f=String(n||"").trim(),d=[r,a,o,i,s,c].filter(Boolean).length,p=r?{variant:"info",title:"Primary model override is active.",body:(0,l.jsxs)(l.Fragment,{children:["LLM Router is currently writing ",(0,l.jsxs)("code",{children:["ANTHROPIC_MODEL=",r]}),". Leave that field blank if you want Claude Code to keep choosing its own primary model."]})}:d>0?{variant:"info",title:"Only filled fields are overridden.",body:(0,l.jsx)(l.Fragment,{children:"Claude Code continues to inherit its normal defaults for every blank field. This is useful when you only want to steer alias models, subagents, or effort level through LLM Router."})}:{variant:"success",title:"Blank fields are a valid setup.",body:(0,l.jsx)(l.Fragment,{children:"You do not need to fill every binding. Leave fields empty unless you want LLM Router to override that specific Claude Code setting."})};return{title:"Claude Code guide",description:"Quick setup for routing Claude Code through LLM Router while keeping only the model and effort level overrides you actually want.",badges:[{label:d>0?`${d} override${d===1?"":"s"} active`:"No router overrides",variant:d>0?"info":"outline"},{label:c?`Effort: ${c}`:"Effort: Claude adaptive default",variant:"outline"},{label:u?"Settings file detected":"Settings scope: local/project/user",variant:"outline"}],callout:p,highlights:[{eyebrow:"1. Connect",title:"Point Claude Code at the router",body:f?(0,l.jsxs)(l.Fragment,{children:["When connected, Claude Code sends requests to ",(0,l.jsx)("code",{children:f}),". LLM Router then handles upstream auth, route selection, and failover."]}):(0,l.jsxs)(l.Fragment,{children:["Click ",(0,l.jsx)("span",{className:"font-medium",children:"Connect"})," to patch Claude Code so it uses the router Anthropic endpoint instead of a provider directly."]})},{eyebrow:"2. Override",title:"Set only the bindings you need",body:(0,l.jsxs)(l.Fragment,{children:["Leave fields blank to inherit Claude Code defaults. Fill ",(0,l.jsx)("code",{children:"ANTHROPIC_MODEL"}),", the Opus/Sonnet/Haiku defaults, or ",(0,l.jsx)("code",{children:"CLAUDE_CODE_SUBAGENT_MODEL"})," only when you want LLM Router to manage those values."]})},{eyebrow:"3. Effort",title:"Set thinking effort level",body:(0,l.jsxs)(l.Fragment,{children:["The ",(0,l.jsx)("span",{className:"font-medium",children:"Effort level"})," dropdown writes ",(0,l.jsx)("code",{children:"CLAUDE_CODE_EFFORT_LEVEL"})," to your shell profile. If the shell profile cannot be updated, ",(0,l.jsx)("code",{children:"effortLevel"})," is set in ",(0,l.jsx)("code",{children:"settings.json"}),' as a fallback (only "high" is supported there).']})}],sections:[{title:"Quick start",items:[(0,l.jsxs)(l.Fragment,{children:["Click ",(0,l.jsx)("span",{className:"font-medium",children:"Connect"})," to patch Claude Code toward the router and keep provider credentials centralized inside LLM Router."]}),(0,l.jsxs)(l.Fragment,{children:["Leave ",(0,l.jsx)("span",{className:"font-medium",children:"Current model override"})," empty unless you explicitly want to replace Claude Code's own main model selection."]}),(0,l.jsxs)(l.Fragment,{children:["Use ",(0,l.jsx)("span",{className:"font-medium",children:"Default Opus"}),", ",(0,l.jsx)("span",{className:"font-medium",children:"Default Sonnet"}),", and ",(0,l.jsx)("span",{className:"font-medium",children:"Default Haiku"})," when you want Claude Code's built-in alias names to resolve to managed routes or aliases."]}),(0,l.jsxs)(l.Fragment,{children:["Use ",(0,l.jsx)("span",{className:"font-medium",children:"Sub-agent model"})," when background workers or helper agents should run on a different route than the main session."]}),(0,l.jsxs)(l.Fragment,{children:["Use ",(0,l.jsx)("span",{className:"font-medium",children:"Effort level"})," to set ",(0,l.jsx)("code",{children:"CLAUDE_CODE_EFFORT_LEVEL"})," in your shell profile; leave it unset to keep Claude Code's adaptive default. The ",(0,l.jsx)("code",{children:"effortLevel"})," key in ",(0,l.jsx)("code",{children:"settings.json"}),' (only "high") acts as a fallback when the shell profile cannot be updated.']})]},{title:"What each binding controls",items:[(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("code",{children:"ANTHROPIC_MODEL"}),": overrides the main model for the active Claude Code session."]}),(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("code",{children:"ANTHROPIC_DEFAULT_OPUS_MODEL"}),", ",(0,l.jsx)("code",{children:"ANTHROPIC_DEFAULT_SONNET_MODEL"}),", and ",(0,l.jsx)("code",{children:"ANTHROPIC_DEFAULT_HAIKU_MODEL"}),": remap Claude Code's built-in alias names to managed routes or aliases."]}),(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("code",{children:"CLAUDE_CODE_SUBAGENT_MODEL"}),": routes subagents and background workers to a specific managed model."]}),c?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("code",{children:"CLAUDE_CODE_EFFORT_LEVEL"}),": currently set to ",(0,l.jsx)("span",{className:"font-medium",children:c})," in your shell profile."]}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("code",{children:"CLAUDE_CODE_EFFORT_LEVEL"}),": stays unset unless you choose an effort level."]})]},{title:"Settings scope and precedence",items:[(0,l.jsxs)(l.Fragment,{children:["Claude Code settings apply in this order: ",(0,l.jsx)("code",{children:"managed-settings.json"}),", CLI arguments, ",(0,l.jsx)("code",{children:".claude/settings.local.json"}),", ",(0,l.jsx)("code",{children:".claude/settings.json"}),", then ",(0,l.jsx)("code",{children:"~/.claude/settings.json"}),"."]}),u?(0,l.jsxs)(l.Fragment,{children:["This page is currently managing ",(0,l.jsx)("code",{children:u}),"."]}):(0,l.jsx)(l.Fragment,{children:"Claude Code can read from project-local, project-shared, or user settings files depending on what exists in your environment."}),(0,l.jsx)(l.Fragment,{children:"If a value seems ignored, check whether a higher-precedence file or command-line flag is overriding it."})]},{title:"Quick verify",items:[(0,l.jsxs)(l.Fragment,{children:["Open the settings file from this page and confirm the ",(0,l.jsx)("code",{children:"env"})," block contains only the overrides you meant to set."]}),(0,l.jsxs)(l.Fragment,{children:["Launch Claude Code and test both the main session and any subagents if you changed ",(0,l.jsx)("code",{children:"CLAUDE_CODE_SUBAGENT_MODEL"}),"."]}),(0,l.jsxs)(l.Fragment,{children:["If thinking behavior is not what you expected, remember this UI writes ",(0,l.jsx)("code",{children:"CLAUDE_CODE_EFFORT_LEVEL"})," to your shell profile; clearing the field returns control to Claude Code's own default behavior."]})]}]}}function m2(){return new Set([...Ds.map(e=>e.id),...xd.map(e=>e.id)].map(e=>String(e||"").trim()).filter(Boolean))}var p2=m2();function Gs(e){return p2.has(String(e||"").trim())}function Id(e){(!e.routes||typeof e.routes!="object"||Array.isArray(e.routes))&&(e.routes={}),Array.isArray(e.rawModelRoutes)||(e.rawModelRoutes=[])}function bC(e={}){return String(e?.sourceRouteKey||"").trim()}function xC(e={}){let n=zn(e).amp;Id(n);let r=new Map,a=[];for(let[s,c]of(n.rawModelRoutes||[]).entries()){let u=bC(c);if(u&&Gs(u)){r.set(u,{mapping:c,index:s});continue}a.push({id:`raw:${s}`,source:"raw",index:s,routeKey:"",inbound:String(c?.from||"").trim(),outbound:String(c?.to||"").trim(),label:"Custom mapping",description:`Wildcard/raw match: ${String(c?.from||"").trim()||"(empty)"}`,defaultMatch:"",isCustom:!0,removable:!0})}let o=Ds.map(s=>{let c=String(s.id||"").trim(),u=W1(c),f=r.get(c)?.mapping||null;return{id:`route:${c}`,source:"route",routeKey:c,inbound:String(f?.from||u||c).trim(),outbound:String(f?.to||n.routes?.[c]||"").trim(),label:Y1(c),description:s.description||"",defaultMatch:u,isCustom:!1,removable:!1}}),i=Object.entries(n.routes||{}).filter(([s])=>!Ds.some(c=>c.id===s)).map(([s,c])=>{let u=String(s||"").trim(),f=W1(u),d=Gs(u);return{id:`route:${u}`,source:"route",routeKey:u,inbound:u,outbound:String(c||"").trim(),label:d?f||u:Y1(u),description:d?`Route key: ${u}`:`Custom route key: ${u}`,defaultMatch:f,isCustom:!0,removable:!0}});return[...o,...i,...a]}function hh(e,t){return xC(e).find(n=>n.id===t)||null}function X1(e={},t,{inbound:n,outbound:r}={}){let a=zn(e),o=a.amp;Id(o);let i=hh(a,t);if(!i)return a;let s=String(n??i.inbound??"").trim(),c=String(r??i.outbound??"").trim(),u=i.source==="route"?String(i.routeKey||"").trim():"",f=u?String(i.defaultMatch||"").trim():"",d=u?o.rawModelRoutes.findIndex(b=>bC(b)===u):-1,p=u&&Gs(u),m=Gs(s)?s:u&&f&&s===f?u:"";if(i.source==="route"&&i.routeKey&&delete o.routes[i.routeKey],i.source==="raw"&&Number.isInteger(i.index)&&o.rawModelRoutes.splice(i.index,1),d>=0&&o.rawModelRoutes.splice(d,1),m)return c&&(o.routes[m]=c),a;if(p){let b=f||u;return c&&(o.routes[u]=c),s&&s!==b&&o.rawModelRoutes.push({from:s,sourceRouteKey:u}),a}return s&&c&&o.rawModelRoutes.push({from:s,to:c}),a}function g2(e={},{inbound:t,outbound:n}={}){let r=zn(e),a=r.amp;Id(a);let o=String(t||"").trim(),i=String(n||"").trim(),s=Gs(o)?o:"";return!o||!i?r:s?(a.routes[s]=i,r):(a.rawModelRoutes.push({from:o,to:i}),r)}function h2(e={},t){let n=zn(e),r=n.amp;Id(r);let a=hh(n,t);return a?.removable&&(a.source==="route"&&a.routeKey&&delete r.routes[a.routeKey],a.source==="raw"&&Number.isInteger(a.index)&&r.rawModelRoutes.splice(a.index,1)),n}function y2(e,t){let n=gl(e&&typeof e=="object"?e:{});n.providers=(Array.isArray(n.providers)?n.providers:[]).filter(i=>i?.id!==t);let r=new Set((n.providers||[]).flatMap(i=>(i.models||[]).map(s=>`${i.id}/${s.id}`))),a=n.modelAliases&&typeof n.modelAliases=="object"?n.modelAliases:{},o={};for(let[i,s]of Object.entries(a)){let c=Array.isArray(s?.targets)?s.targets.filter(f=>!hl(f?.ref,t)):[],u=Array.isArray(s?.fallbackTargets)?s.fallbackTargets.filter(f=>!hl(f?.ref,t)):[];o[i]={...s,...Array.isArray(s?.targets)?{targets:c}:{},...Array.isArray(s?.fallbackTargets)?{fallbackTargets:u}:{}}}return n.modelAliases=o,n.defaultModel&&!n.modelAliases?.[n.defaultModel]&&!r.has(n.defaultModel)&&(n.defaultModel=at),n?.amp?.defaultRoute&&!n.modelAliases?.[n.amp.defaultRoute]&&!r.has(n.amp.defaultRoute)&&(n.amp={...n.amp,defaultRoute:n.defaultModel||gh(n)}),n}function vl(e={}){let t=Array.isArray(e?.metadata?.endpointCandidates)?e.metadata.endpointCandidates:[],n=[e?.baseUrl,...Object.values(e?.baseUrlByFormat||{})];return Array.from(new Set((t.length>0?t:n).map(r=>String(r||"").trim()).filter(Boolean)))}function v2(e={}){let t=String(e?.apiKeyEnv||"").trim();if(t)return{apiKeyEnv:t};let n=String(e?.apiKey||e?.credential||"").trim();return n?{apiKey:n}:{}}function Z1(e={},t={}){if(e&&Object.prototype.hasOwnProperty.call(e,"credentialInput")){let n=String(e?.credentialInput||"").trim();return n?Dd(n)?{apiKeyEnv:n}:{apiKey:n}:{}}return v2(t)}function uo(e={}){return e?.type==="subscription"?e?.subscriptionType==="claude-code"?"oauth-claude":"oauth-gpt":"api"}function b2(e={}){let t=vl(e),n=uo(e),r=Ud(n);return{id:String(e?.id||"").trim(),name:String(e?.name||e?.id||"").trim(),credentialInput:n==="api"?String(e?.apiKeyEnv||e?.apiKey||e?.credential||"").trim():"",endpoints:n==="api"?t:[],endpointDraft:"",rateLimitRows:n==="api"?fh(e?.rateLimits,{keyPrefix:`provider-${e?.id||"new"}-rate-limit`,defaults:r,includeDefault:!0}):[]}}function x2(e){return dC.find(t=>t.value===e)?.label||"API Key"}function SC(e,t="openai"){return e==="api"?[...Cd.api[t]||Cd.api.openai]:[...Cd[e]||Cd["oauth-gpt"]]}function Ud(e){return e==="api"?ml.api:ml.oauth}function S2(e,t,n=[]){let r=new Set((n||[]).map(o=>o?.id).filter(Boolean));if(!r.has(e))return{providerId:e,providerName:t};let a=2;for(;r.has(`${e}-${a}`);)a++;return{providerId:`${e}-${a}`,providerName:`${t} ${a}`}}function Ps(e,t="openai"){let n=j1[e]||j1.api,r=Ud(e);return{providerName:n.providerName,providerId:n.providerId,endpoints:e==="api"?[]:[],apiKeyEnv:"",subscriptionProfile:e==="api"?"":n.subscriptionProfile,modelIds:e==="api"?[]:SC(e,t),rateLimitRows:e==="api"?fh([],{keyPrefix:`quick-start-${e}-rate-limit`,defaults:r,includeDefault:!0}):[]}}function w2(e={},t="",{aliasId:n=""}={}){if(!t)return null;let r=e?.modelAliases&&typeof e.modelAliases=="object"&&!Array.isArray(e.modelAliases)?e.modelAliases:{},a=n?[[n,r[n]]]:Object.entries(r);for(let[o,i]of a){if(!i||typeof i!="object")continue;let s=Array.isArray(i?.targets)?i.targets:[],c=Array.isArray(i?.fallbackTargets)?i.fallbackTargets:[];if([...s,...c].some(u=>hl(u?.ref,t)))return{aliasId:o,alias:i}}return null}function A2(e,t="",n=[]){let r=Array.from(new Set((n||[]).map(s=>String(s||"").trim()).filter(Boolean)));if(!t||!e?.alias)return r;let a=new Set(r),o=Array.isArray(e.alias?.targets)?e.alias.targets:[],i=[];for(let s of o){let c=String(s?.ref||"").trim();if(!hl(c,t))continue;let u=c.slice(t.length+1);!a.has(u)||i.includes(u)||i.push(u)}return i.length>0?i:r}function yh(e=[],t=[]){let n=Array.from(new Set((t||[]).map(o=>String(o||"").trim()).filter(Boolean))),r=new Set(n),a=[];for(let o of(e||[]).map(i=>String(i||"").trim()).filter(Boolean))r.has(o)&&(a.push(o),r.delete(o));return[...a,...n.filter(o=>r.has(o))]}function J1(e,{fromProviderId:t,toProviderId:n,allowedModelIds:r}){if(!e||typeof e!="object")return e;let a=String(e.ref||"").trim();if(!t||!hl(a,t))return e;let o=a.slice(t.length+1);return r.has(o)?{...e,ref:`${n}/${o}`}:null}function C2(e,t){if(!e||typeof e!="object")return e;let n={...e},r=Array.isArray(e.targets),a=Array.isArray(e.fallbackTargets);return r&&(n.targets=e.targets.map(o=>J1(o,t)).filter(Boolean)),a&&(n.fallbackTargets=e.fallbackTargets.map(o=>J1(o,t)).filter(Boolean)),n}function R2(e,{fromProviderId:t,toProviderId:n,allowedModelIds:r}){let a=String(e||"").trim();if(!a||!t||!hl(a,t))return a;let o=a.slice(t.length+1);return r.has(o)?`${n}/${o}`:""}function E2(e=[]){return new Set((e||[]).flatMap(t=>(t?.models||[]).map(n=>`${t.id}/${n.id}`)))}function T2(e={},{seedMode:t="blank",targetProviderId:n="",defaultProviderUserAgent:r=ni}={}){let a=Array.isArray(e?.providers)?e.providers:[],o=n&&a.find(h=>h?.id===n)||null,i=t==="existing"||!!o,s=i?o||a[0]||{}:{},c=i?uo(s):"api",u=s?.format==="claude"?"claude":"openai",f=Ps(c,u),d=Ud(c),p=Array.isArray(s?.models)?s.models.map(h=>h?.id).filter(Boolean):[],m=String(s?.id||f.providerId||Vr(s?.name||f.providerName||"my-provider")||"my-provider"),b=i?w2(e,m,{aliasId:at}):null,g=p.length>0?p:[...f.modelIds],x=Object.fromEntries((Array.isArray(s?.models)?s.models:[]).map(h=>{let v=String(h?.id||"").trim(),S=Number(h?.contextWindow);return!v||!Number.isFinite(S)||S<=0?null:[v,Math.floor(S)]}).filter(Boolean)),y=c==="api"?Pk(s?.headers,r):[];return{connectionType:c,providerName:String(s?.name||f.providerName),providerId:m,endpoints:vl(s).length>0?vl(s):f.endpoints,endpointDraft:"",apiKeyEnv:String(s?.apiKeyEnv||s?.apiKey||f.apiKeyEnv),subscriptionProfile:String(s?.subscriptionProfile||f.subscriptionProfile),modelIds:g,modelContextWindows:x,modelDraft:"",aliasModelIds:A2(b,m,g),headerRows:y,rateLimitRows:c==="api"?fh(s?.rateLimits,{keyPrefix:`quick-start-${m}-rate-limit`,defaults:d,includeDefault:!0}):[],enableAlias:!0,aliasId:at,sourceAliasId:b?.aliasId||"",useAliasAsDefault:i?!!b:!0}}function eC(e,t={},n={}){return(e||[]).map(r=>{let a=t[r],o=Number(n?.[r]);return{id:r,...a?{formats:[a]}:{},...Number.isFinite(o)&&o>0?{contextWindow:Math.floor(o)}:{}}})}function wC(e={}){let t=Vr(e?.providerId||e?.providerName||"")||"";return String(e?.subscriptionProfile||t||"default").trim()||t||"default"}function N2(e={},t,n=null,{targetProviderId:r=""}={}){let a=gl(e&&typeof e=="object"?e:{}),o=Vr(t?.providerId||t?.providerName||"my-provider")||"my-provider",i=String(t?.providerName||o).trim()||o,s=Array.isArray(t?.modelIds)?t.modelIds.map(H=>String(H||"").trim()).filter(Boolean):[],c=yh(t?.aliasModelIds,s),u=Ud(t?.connectionType),f=Array.isArray(t?.rateLimitRows)?t.rateLimitRows:[],d=f.length>0?f:[{models:["all"],requests:u.limit,windowValue:u.windowValue,windowUnit:u.windowUnit}],p=Array.isArray(e?.providers)&&e.providers.length>0,m=String(r||"").trim(),b=String(t?.sourceAliasId||"").trim(),g;if(t?.connectionType==="api"){let H=Array.isArray(t?.endpoints)?t.endpoints.map(he=>String(he||"").trim()).filter(Boolean):[],Q=Array.isArray(n?.workingFormats)?n.workingFormats.filter(Boolean):[],ee=n?.preferredFormat||Q[0]||"openai",X=n?.baseUrlByFormat&&typeof n.baseUrlByFormat=="object"?n.baseUrlByFormat:H[0]?{[ee]:H[0]}:void 0,z=ee&&X?.[ee]||X?.openai||X?.claude||H[0]||"",te=Array.isArray(n?.models)&&n.models.length>0?c.filter(he=>n.models.includes(he)):c,Y=te.length>0?te:c,q=H.length>1?{endpointCandidates:H}:void 0,V=String(t?.apiKeyEnv||"").trim(),_e=Dd(V)?{apiKeyEnv:V}:V?{apiKey:V}:{},F=ph(t?.headerRows||[]);g={id:o,name:i,baseUrl:z,baseUrlByFormat:X,..._e,...Object.keys(F).length>0?{headers:F}:{},format:ee,formats:Q.length>0?Q:[ee],models:eC(Y,n?.modelPreferredFormat||{},t?.modelContextWindows||{}),...q?{metadata:q}:{}}}else{let H=t?.connectionType==="oauth-claude"?"claude-code":"chatgpt-codex",Q=t?.connectionType==="oauth-claude"?"claude":"openai";g={id:o,name:i,type:"subscription",subscriptionType:H,subscriptionProfile:wC(t),format:Q,formats:[Q],models:eC(c,{},t?.modelContextWindows||{})}}g.rateLimits=t?.connectionType==="api"?Bs(d,{fallbackRequests:u.limit,fallbackWindowValue:u.windowValue,fallbackWindowUnit:u.windowUnit}):Bs([{models:["all"],requests:u.limit,windowValue:u.windowValue,windowUnit:u.windowUnit}],{fallbackRequests:u.limit,fallbackWindowValue:u.windowValue,fallbackWindowUnit:u.windowUnit}),String(a.masterKey||"").trim()||(a.masterKey=Zg()),a.version=typeof a.version=="number"?a.version:2;let x=Array.isArray(a.providers)?a.providers:[],y=m?x.findIndex(H=>H?.id===m):-1;y===-1&&(y=x.findIndex(H=>H?.id===o)),a.providers=y===-1?[...x,g]:x.map((H,Q)=>Q===y?g:H);let h=a.modelAliases&&typeof a.modelAliases=="object"&&!Array.isArray(a.modelAliases)?a.modelAliases:{},v=new Set((g.models||[]).map(H=>H.id)),S=!p||t?.useAliasAsDefault===!0,C={};for(let[H,Q]of Object.entries(h)){let ee=m?C2(Q,{fromProviderId:m,toProviderId:o,allowedModelIds:v}):Q;C[H]=ee}let T=g.models?.[0]?.id?`${o}/${g.models[0].id}`:"",w=(c.length>0?c:(g.models||[]).map(H=>H.id)).filter(H=>v.has(H)),R=at,M=C[R]&&typeof C[R]=="object"?C[R]:{id:R,strategy:"ordered",targets:[],fallbackTargets:[]};C[R]=S?{...M,id:R,strategy:"ordered",targets:w.map(H=>({ref:`${o}/${H}`})),fallbackTargets:[]}:{...M,id:R,strategy:String(M.strategy||"ordered").trim()||"ordered",targets:Array.isArray(M.targets)?M.targets:[],fallbackTargets:Array.isArray(M.fallbackTargets)?M.fallbackTargets:[]},a.modelAliases=C;let k=E2(a.providers);a.defaultModel=at,(!a.amp||typeof a.amp!="object"||Array.isArray(a.amp))&&(a.amp={restrictManagementToLocalhost:!0,overrides:{entities:[]}}),a.amp.restrictManagementToLocalhost===void 0&&(a.amp.restrictManagementToLocalhost=!0),(!a.amp.overrides||typeof a.amp.overrides!="object"||Array.isArray(a.amp.overrides))&&(a.amp.overrides={entities:[]}),Array.isArray(a.amp.overrides.entities)||(a.amp.overrides.entities=[]);let I=String(a.amp.defaultRoute||"").trim();return m&&(I=R2(I,{fromProviderId:m,toProviderId:o,allowedModelIds:v})),(S||!I||!a.modelAliases?.[I]&&!k.has(I))&&(I=at),I&&(a.amp.defaultRoute=I),(!a.metadata||typeof a.metadata!="object"||Array.isArray(a.metadata))&&(a.metadata={}),a}function AC(e={}){return(Array.isArray(e?.providers)?e.providers:[]).some(n=>{if(n?.enabled===!1)return!1;let r=Array.isArray(n?.models)?n.models.filter(o=>String(o?.id||"").trim()):[],a=Array.isArray(n?.rateLimits)?n.rateLimits:[];return r.length>0&&a.length>0})}function M2(e,t,n={},{targetProviderId:r=""}={}){let a=Vr(t?.providerId||t?.providerName||""),o=Hr(t?.modelIds,t?.modelDraft),i=yh(t?.aliasModelIds,o),s=xa(t?.rateLimitRows),c=t?.connectionType==="api"?Hr(t?.endpoints,t?.endpointDraft):[],u=Array.isArray(n?.providers)?n.providers:[],f=n?.modelAliases&&typeof n.modelAliases=="object"&&!Array.isArray(n.modelAliases)?n.modelAliases:{};if(e===0){if(!String(t?.providerName||"").trim())return"Add a provider name to continue.";if(!a||!Md.test(a))return"Provider id must start with a letter and use lowercase letters, numbers, or hyphens.";if(u.some(d=>d?.id===a&&d?.id!==r))return"Provider id already exists. Choose another id or edit that provider instead.";if(t?.connectionType==="api"){if(c.length===0)return"Add at least one endpoint to continue.";if(!String(t?.apiKeyEnv||"").trim())return"API key or env is required before testing config."}}if(e===1){if(o.length===0)return"Add at least one model id.";if(t?.connectionType==="api"){let d=ti(s,{knownModelIds:o,requireAtLeastOne:!0});if(d)return d}}return e===2&&t?.useAliasAsDefault&&Object.prototype.hasOwnProperty.call(f,String(t?.aliasId||at).trim())===!1,""}function vh(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"\u2014"}function O2(e){return e?.parseError?"danger":(e?.validationErrors||[]).length>0?"warning":"success"}function eh(e=""){let t=String(e||"Select alias").trim()||"Select alias",n=Math.min(Math.max(Math.ceil(t.length*8.5+62),160),520);if(typeof document>"u")return n;let a=(eh.canvas||(eh.canvas=document.createElement("canvas"))).getContext("2d");return a?(a.font='500 14px "Inter", "SF Pro Display", ui-sans-serif, system-ui, sans-serif',Math.min(Math.max(Math.ceil(a.measureText(t).width+62),160),520)):n}async function js(e){let t=String(e||"");if(!t)return;if(typeof navigator<"u"&&navigator.clipboard?.writeText){await navigator.clipboard.writeText(t);return}if(typeof document>"u")throw new Error("Clipboard is not available in this environment.");let n=document.createElement("textarea");n.value=t,n.setAttribute("readonly",""),n.style.position="absolute",n.style.left="-9999px",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n)}async function Nt(e,t={}){let n=await fetch(e,t),r=await n.json().catch(()=>({}));if(!n.ok){let a=new Error(r?.error||`Request failed (${n.status})`);throw a.statusCode=n.status,a.payload=r,a}return r}async function CC(e,t={},{onMessage:n}={}){let r=await fetch(e,t);if(!r.ok){let u=await r.json().catch(()=>({})),f=new Error(u?.error||`Request failed (${r.status})`);throw f.statusCode=r.status,f.payload=u,f}let a=r.body?.getReader();if(!a)return null;let o=new TextDecoder,i="",s=null;for(;;){let{value:u,done:f}=await a.read();i+=o.decode(u||new Uint8Array,{stream:!f});let d=i.indexOf(`
50
50
  `);for(;d>=0;){let p=i.slice(0,d).trim();if(i=i.slice(d+1),p){let m=JSON.parse(p);if(n?.(m),m?.type==="result"&&(s=m.result),m?.type==="error"){let b=new Error(m.error||"Request failed.");throw b.statusCode=m.statusCode||500,b}}d=i.indexOf(`
51
- `)}if(f)break}let c=i.trim();if(c){let u=JSON.parse(c);if(n?.(u),u?.type==="result"&&(s=u.result),u?.type==="error"){let f=new Error(u.error||"Request failed.");throw f.statusCode=u.statusCode||500,f}}return s}function tC(e={}){return`${String(e?.model||"").trim()}::${String(e?.contextWindow||"").trim()}`}function _2(e){return String(e||"").trim().replace(/[.,\s_'`]/g,"")}function so(e){let t=_2(e);if(!t)return"";let n=Number.parseInt(t,10);return Number.isFinite(n)&&n>0?String(n):t}async function th(e=[]){let t=[...new Set((Array.isArray(e)?e:[]).map(r=>String(r||"").trim()).filter(Boolean))];if(t.length===0)return[];let n=await Nt("/api/config/litellm-context-lookup",{method:"POST",headers:Ct,body:JSON.stringify({models:t,limit:wk})});return Array.isArray(n?.result)?n.result:[]}function nC(e={}){let t=String(e?.model||"").trim(),n=String(e?.provider||"").trim(),r=String(e?.mode||"").trim(),a=Number(e?.contextWindow);return!Number.isFinite(a)||a<=0?null:{model:t,provider:n,mode:r,contextWindow:Math.floor(a)}}function rC(e="",t=""){let n=String(e||"").trim(),r=String(t||"").trim();if(!n||!r)return n;let a=n.toLowerCase(),o=r.toLowerCase(),i=[`${o}/`,`${o}:`];for(let s of i){if(!a.startsWith(s))continue;return n.slice(s.length).trim()||n}return n}function qs(e={},{fallbackQuery:t=""}={}){let n=String(e?.query||t||"").trim(),r=nC(e?.exactMatch),a=(Array.isArray(e?.suggestions)?e.suggestions:[]).map(f=>nC(f)).filter(Boolean),o=Number(e?.medianContextWindow),i=Number.isFinite(o)&&o>0?Math.floor(o):r?.contextWindow||null,s=[],c=new Set;function u(f){!f?.key||c.has(f.key)||(c.add(f.key),s.push(f))}r&&u({key:`exact::${tC(r)}`,label:rC(r.model,r.provider)||"Exact match",detail:r.provider?`Exact \xB7 ${r.provider}`:"Exact",contextWindow:r.contextWindow});for(let f of a)u({key:tC(f),label:rC(f.model,f.provider)||"Suggestion",detail:f.provider||"Known model",contextWindow:f.contextWindow});return{query:n,exactMatch:r,suggestions:a,medianContextWindow:i,options:s,status:s.length>0?"ready":"miss"}}function nh(e={}){let t=qs(e);return t.exactMatch?.contextWindow?String(t.exactMatch.contextWindow):t.medianContextWindow?String(t.medianContextWindow):""}function k2(e=[]){let t=new Map;for(let n of Array.isArray(e)?e:[]){let r=qs(n);r.query&&t.set(r.query,r)}return t}function L2(e=[]){let t={};for(let n of Array.isArray(e)?e:[]){let r=String(n?.query||"").trim(),a=nh(n);!r||!a||(t[r]=Number(a))}return t}function st({label:e,hint:t,className:n,children:r,stacked:a=!1,headerClassName:o,hintClassName:i,headerAction:s=null}){return(0,l.jsxs)("div",{className:W("flex flex-col gap-2 text-sm",n),children:[(0,l.jsxs)("div",{className:W("text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",a?"flex min-h-10 items-start justify-between gap-3":"flex items-center justify-between gap-2",o),children:[(0,l.jsxs)("div",{className:W("min-w-0",a?"flex-1 space-y-1":"flex min-w-0 items-center gap-2"),children:[(0,l.jsx)("span",{children:e}),t?(0,l.jsx)("span",{className:W("block normal-case tracking-normal text-[11px] text-muted-foreground/80",a?"leading-4":null,i),children:t}):null]}),s?(0,l.jsx)("div",{className:"shrink-0",children:s}):null]}),r]})}function Yg({value:e,onValueChange:t,disabled:n=!1,allowEmptyCommit:r=!1,...a}){let o=String(e??""),[i,s]=(0,E.useState)(o);return(0,E.useEffect)(()=>{s(o)},[o]),(0,l.jsx)(Dt,{...a,value:i,inputMode:"numeric",disabled:n,onChange:c=>{let u=z1(c.target.value);u.accepted&&(s(u.draftValue),u.shouldCommit?t(u.commitValue):r&&u.draftValue===""&&t(""))},onBlur:()=>{s(c=>c!==""?c:r?(t(""),""):o)}})}function D2({label:e,hint:t,checked:n=!1,onCheckedChange:r,disabled:a=!1,className:o}){return(0,l.jsxs)("div",{className:W("flex items-center justify-between gap-4 rounded-2xl border border-border/70 bg-background/80 px-4 py-3",o),children:[(0,l.jsxs)("div",{className:"min-w-0",children:[(0,l.jsx)("div",{className:"text-sm font-medium text-foreground",children:e}),t?(0,l.jsx)("div",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:t}):null]}),(0,l.jsx)(fS,{checked:n,onCheckedChange:r,disabled:a,className:"data-[disabled]:cursor-not-allowed data-[disabled]:opacity-60"})]})}function Sa({open:e=!1,title:t="",description:n="",onClose:r=()=>{},children:a,variant:o="dialog",headerActions:i=null,showCloseButton:s=!0,closeDisabled:c=!1,closeOnEscape:u=!0,closeOnBackdrop:f=!0,footer:d=null,contentClassName:p="",bodyClassName:m="",footerClassName:b=""}){if((0,E.useEffect)(()=>{if(!e||typeof window>"u")return;function y(h){h.key==="Escape"&&u&&r()}return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[u,e,r]),!e)return null;let g=o==="page",x=(0,l.jsx)("div",{className:W("fixed inset-0 z-50 bg-slate-950/55 backdrop-blur-sm",g?"p-0":"flex items-center justify-center p-4"),onMouseDown:y=>{y.target===y.currentTarget&&f&&r()},children:(0,l.jsxs)("div",{className:W("overflow-hidden border border-border/70 bg-card/95 shadow-2xl",g?"flex h-full w-full flex-col rounded-none border-x-0 border-y-0 bg-background/98":"flex max-h-[85vh] w-full max-w-3xl flex-col rounded-3xl",p),children:[(0,l.jsxs)("div",{className:W("flex items-start justify-between gap-3 border-b border-border/70",g?"px-5 py-4 sm:px-6":"px-5 py-4"),children:[(0,l.jsxs)("div",{className:"min-w-0",children:[(0,l.jsx)("div",{className:"text-base font-semibold text-foreground",children:t}),n?(0,l.jsx)("div",{className:"mt-1 text-sm leading-6 text-muted-foreground",children:n}):null]}),(0,l.jsxs)("div",{className:"flex shrink-0 items-center gap-2",children:[i,s?(0,l.jsx)(ce,{type:"button",variant:"ghost",size:"sm",onClick:r,disabled:c,children:"Close"}):null]})]}),(0,l.jsx)("div",{className:W("overflow-y-auto",g?"min-h-0 flex-1 px-5 py-4 sm:px-6 sm:py-5":"min-h-0 flex-1 px-5 py-4",m),children:a}),d?(0,l.jsx)("div",{className:W("border-t border-border/70 bg-background/96",g?"px-5 py-4 sm:px-6":"px-5 py-4",b),children:d}):null]})});return typeof document>"u"||!document.body?x:(0,uC.createPortal)(x,document.body)}function RC({open:e=!1,anchorRef:t,preferredSide:n="bottom",desiredHeight:r=288,offset:a=4,className:o="",children:i,...s}){let c=yd({open:e,anchorRef:t,preferredSide:n,desiredHeight:r,offset:a});return e?(0,l.jsx)("div",{className:W("absolute left-0 right-0 z-30 overflow-y-auto rounded-xl border border-border/70 bg-popover shadow-lg",c.side==="top"?"bottom-full mb-1":"top-full mt-1",o),style:{maxHeight:`${Math.max(0,Math.floor(c.maxHeight||r))}px`},...s,children:i}):null}function z2({open:e=!1,onKeepEditing:t=()=>{},onDiscardAndClose:n=()=>{},onSaveAndClose:r=()=>{},saveDisabled:a=!1,dirtyLabels:o=[],details:i=""}){let s=o.length>1?`${o.slice(0,-1).join(", ")} and ${o[o.length-1]}`:o[0]||"this form";return(0,l.jsx)(Sa,{open:e,onClose:t,title:"Unsaved changes",description:`You have unsaved edits in ${s}.`,contentClassName:"max-w-lg rounded-2xl border border-border/70 bg-background/98 shadow-[0_32px_120px_rgba(15,23,42,0.48)]",showCloseButton:!1,footer:(0,l.jsxs)("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[(0,l.jsx)(ce,{type:"button",variant:"ghost",onClick:t,children:"Keep editing"}),(0,l.jsx)(ce,{type:"button",variant:"outline",onClick:n,children:"Cancel + Close"}),(0,l.jsx)(ce,{type:"button",onClick:()=>{r()},disabled:a,children:"Save + Close"})]}),children:(0,l.jsxs)("div",{className:"space-y-3 text-sm leading-6 text-muted-foreground",children:[(0,l.jsx)("div",{children:"Choose whether to save these edits before closing the modal."}),i?(0,l.jsx)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-amber-900",children:i}):null]})})}function B2({open:e=!1,failedModelIds:t=[],onKeepEditing:n=()=>{},onRemoveFailedAndClose:r=()=>{},removeDisabled:a=!1}){let o=t.length>1?`${t.length} failed models`:t[0]||"the failed model";return(0,l.jsx)(Sa,{open:e,onClose:n,title:"Failed model tests",description:`Some new models did not pass validation: ${o}.`,contentClassName:"max-w-lg rounded-2xl border border-border/70 bg-background/98 shadow-[0_32px_120px_rgba(15,23,42,0.48)]",showCloseButton:!1,footer:(0,l.jsxs)("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[(0,l.jsx)(ce,{type:"button",variant:"ghost",onClick:n,children:"Keep editing"}),(0,l.jsx)(ce,{type:"button",variant:"outline",onClick:()=>{r()},disabled:a,children:"Remove failed + close"})]}),children:(0,l.jsxs)("div",{className:"space-y-3 text-sm leading-6 text-muted-foreground",children:[(0,l.jsx)("div",{children:"Successful new models are still kept in the draft. You can continue editing, or remove only the failed rows and close the modal."}),t.length>0?(0,l.jsx)("div",{className:"rounded-xl border border-rose-200 bg-rose-50 px-3 py-2 text-rose-900",children:t.join(", ")}):null]})})}function Nd({className:e=""}){return(0,l.jsxs)("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",className:e,"aria-hidden":"true",children:[(0,l.jsx)("path",{d:"M12 20h9"}),(0,l.jsx)("path",{d:"M16.5 3.5a2.121 2.121 0 1 1 3 3L7 19l-4 1 1-4 12.5-12.5Z"})]})}function I2({className:e=""}){return(0,l.jsx)("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:e,"aria-hidden":"true",children:(0,l.jsx)("path",{d:"m5 12 4.25 4.25L19 6.5"})})}function rh({className:e=""}){return(0,l.jsxs)("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",className:e,"aria-hidden":"true",children:[(0,l.jsx)("path",{d:"M3 6h18"}),(0,l.jsx)("path",{d:"M8 6V4.75A1.75 1.75 0 0 1 9.75 3h4.5A1.75 1.75 0 0 1 16 4.75V6"}),(0,l.jsx)("path",{d:"M18 6v12.25A1.75 1.75 0 0 1 16.25 20h-8.5A1.75 1.75 0 0 1 6 18.25V6"}),(0,l.jsx)("path",{d:"M10 10.5v5"}),(0,l.jsx)("path",{d:"M14 10.5v5"})]})}function U2({className:e=""}){return(0,l.jsxs)("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",className:e,"aria-hidden":"true",children:[(0,l.jsx)("rect",{x:"9",y:"9",width:"11",height:"11",rx:"2"}),(0,l.jsx)("path",{d:"M5 15V6a2 2 0 0 1 2-2h9"})]})}function j2({className:e=""}){return(0,l.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",className:e,"aria-hidden":"true",children:[(0,l.jsx)("path",{d:"M7.25 5.75h-1.5A2.75 2.75 0 0 0 3 8.5v5.75A2.75 2.75 0 0 0 5.75 17h5.75a2.75 2.75 0 0 0 2.75-2.75v-1.5"}),(0,l.jsx)("path",{d:"M10.5 9.5 17 3"}),(0,l.jsx)("path",{d:"M12 3h5v5"})]})}function P2({className:e=""}){return(0,l.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",className:e,"aria-hidden":"true",children:[(0,l.jsx)("circle",{cx:"6.75",cy:"10",r:"3.25"}),(0,l.jsx)("path",{d:"M10 10h6.5"}),(0,l.jsx)("path",{d:"M13.5 10v2.25"}),(0,l.jsx)("path",{d:"M15.75 10v1.5"})]})}function V2({className:e=""}){return(0,l.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",className:e,"aria-hidden":"true",children:[(0,l.jsx)("path",{d:"M16.25 10a6.25 6.25 0 1 1-1.83-4.42"}),(0,l.jsx)("path",{d:"M13.5 3.75h3v3"}),(0,l.jsx)("path",{d:"M16.5 3.75 12.75 7.5"})]})}function H2({className:e=""}){return(0,l.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",className:e,"aria-hidden":"true",children:[(0,l.jsx)("path",{d:"M6 3.5h5.25L15 7.25V16A1.5 1.5 0 0 1 13.5 17.5h-7A1.5 1.5 0 0 1 5 16V5A1.5 1.5 0 0 1 6.5 3.5H6Z"}),(0,l.jsx)("path",{d:"M11 3.5V7.5H15"}),(0,l.jsx)("path",{d:"M7.75 11h4.5"}),(0,l.jsx)("path",{d:"M7.75 14h4.5"})]})}function EC({className:e=""}){return(0,l.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",className:e,"aria-hidden":"true",children:[(0,l.jsx)("path",{d:"M6 3.5h5.25L15 7.25V16A1.5 1.5 0 0 1 13.5 17.5h-7A1.5 1.5 0 0 1 5 16V5A1.5 1.5 0 0 1 6.5 3.5H6Z"}),(0,l.jsx)("path",{d:"M11 3.5V7.5H15"}),(0,l.jsx)("path",{d:"M7 12.25a3 3 0 1 1 2.85 2.99"}),(0,l.jsx)("path",{d:"M8.5 10.25h1.5v1.5"})]})}function q2({className:e=""}){return(0,l.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",className:e,"aria-hidden":"true",children:[(0,l.jsx)("path",{d:"M10 2.75 4.75 5v4.12c0 3.42 2.1 6.58 5.25 7.88 3.15-1.3 5.25-4.46 5.25-7.88V5L10 2.75Z"}),(0,l.jsx)("circle",{cx:"10",cy:"9",r:"1.4"}),(0,l.jsx)("path",{d:"M10 10.4v2.1"})]})}function $2({label:e,value:t,icon:n,disabled:r=!1,onClick:a,actionLabel:o}){return(0,l.jsxs)("button",{type:"button",className:"inline-flex h-9 min-w-0 max-w-full items-center gap-2 rounded-full border border-border/70 bg-background/90 px-3 text-left transition hover:border-accent hover:bg-accent disabled:cursor-not-allowed disabled:opacity-70 sm:max-w-[18rem]",onClick:a,disabled:r,"aria-label":o,title:r?o:t,children:[(0,l.jsx)("span",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-secondary text-muted-foreground",children:n}),(0,l.jsx)("span",{className:"shrink-0 text-[10px] font-semibold uppercase tracking-[0.14em] text-muted-foreground",children:e}),(0,l.jsx)("span",{className:"min-w-0 truncate text-xs font-medium text-foreground",children:t})]})}function K2({value:e,pending:t=!1,disabled:n=!1,rotateDisabled:r=!1,onCopy:a,onRotate:o}){return(0,l.jsxs)("div",{className:"flex h-9 min-w-0 max-w-full items-stretch overflow-hidden rounded-full border border-border/70 bg-background/90 sm:max-w-[18rem]",children:[(0,l.jsxs)("button",{type:"button",className:"inline-flex min-w-0 flex-1 items-center gap-2 rounded-l-full px-3 text-left transition hover:bg-accent disabled:cursor-not-allowed disabled:opacity-70",onClick:a,disabled:n,"aria-label":t?"Gateway key is still generating":"Copy gateway key",title:t?"Gateway key is still generating":"Copy gateway key",children:[(0,l.jsx)("span",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-secondary text-muted-foreground",children:(0,l.jsx)(P2,{className:"h-3.5 w-3.5"})}),(0,l.jsx)("span",{className:"shrink-0 text-[10px] font-semibold uppercase tracking-[0.14em] text-muted-foreground",children:"Gateway key"}),(0,l.jsx)("span",{className:"min-w-0 truncate text-xs font-medium text-foreground",children:e})]}),(0,l.jsx)("button",{type:"button",className:"inline-flex w-9 shrink-0 items-center justify-center rounded-r-full border-l border-border/70 text-muted-foreground transition hover:bg-accent hover:text-foreground disabled:cursor-not-allowed disabled:opacity-70",onClick:o,disabled:r,"aria-label":"Rotate gateway key",title:"Rotate gateway key",children:(0,l.jsx)(V2,{className:"h-3.5 w-3.5"})})]})}function F2({endpointValue:e,endpointDisabled:t=!1,gatewayValue:n,gatewayPending:r=!1,gatewayDisabled:a=!1,rotateDisabled:o=!1,onCopyEndpoint:i,onCopyGatewayKey:s,onRotateKey:c}){return(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-1.5",children:[(0,l.jsx)($2,{label:"Endpoint",value:e,icon:(0,l.jsx)(j2,{className:"h-3.5 w-3.5"}),disabled:t,onClick:i,actionLabel:t?"API endpoint not ready yet":"Copy API endpoint"}),(0,l.jsx)(K2,{value:n,pending:r,disabled:a,rotateDisabled:o,onCopy:s,onRotate:c})]})}function aC({label:e,value:t,icon:n,disabled:r=!1,onClick:a,actionLabel:o="",emptyLabel:i="Not resolved"}){let s=String(t||"").trim()||i;return(0,l.jsxs)("button",{type:"button",className:"inline-flex min-w-0 max-w-full items-start gap-2 rounded-2xl border border-border/70 bg-background/90 px-3 py-2 text-left transition hover:border-accent hover:bg-accent disabled:cursor-not-allowed disabled:opacity-70",onClick:a,disabled:r,"aria-label":o,title:r?o:s,children:[(0,l.jsx)("span",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-secondary text-muted-foreground",children:n}),(0,l.jsxs)("span",{className:"min-w-0",children:[(0,l.jsx)("span",{className:"block text-[9px] font-semibold uppercase tracking-[0.12em] text-muted-foreground",children:e}),(0,l.jsx)("span",{className:"mt-1 block break-all text-[11px] font-medium leading-4 text-foreground",children:s})]})]})}function Td({connected:e=!1,className:t,srLabel:n="Connected",size:r="sm"}){if(!e)return null;let a=r==="md"?"h-3.5 w-3.5":"h-2.5 w-2.5",o=r==="md"?"h-2 w-2":"h-1.5 w-1.5";return(0,l.jsxs)("span",{className:W("relative inline-flex shrink-0 items-center justify-center",a,t),children:[(0,l.jsx)("span",{"aria-hidden":"true",className:"absolute inset-0 rounded-full bg-emerald-400/45 animate-ping motion-reduce:animate-none"}),(0,l.jsx)("span",{"aria-hidden":"true",className:W("relative rounded-full bg-emerald-500 ring-2 ring-emerald-500/15",o)}),(0,l.jsx)("span",{className:"sr-only",children:n})]})}function TC({primaryLabel:e="Config file",primaryValue:t="",primaryIcon:n=(0,l.jsx)(H2,{className:"h-3 w-3"}),onOpenPrimary:r,secondaryLabel:a="Backup file",secondaryValue:o="",secondaryIcon:i=(0,l.jsx)(EC,{className:"h-3 w-3"}),onOpenSecondary:s}){let c=String(t||"").trim(),u=String(o||"").trim();return(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,l.jsx)(aC,{label:e,value:c,icon:n,disabled:!c||typeof r!="function",onClick:r,actionLabel:c?`Open ${e.toLowerCase()}`:`${e} path is not resolved yet`}),(0,l.jsx)(aC,{label:a,value:u,icon:i,disabled:!u||typeof s!="function",onClick:s,actionLabel:u?`Open ${a.toLowerCase()}`:`${a} path is not resolved yet`})]})}function G2(e){return e==="error"?"Error":e==="success"?"Success":"Notice"}function Y2({notice:e,onDismiss:t}){let[n,r]=(0,E.useState)(Gg),[a,o]=(0,E.useState)(Gg),[i,s]=(0,E.useState)(!1),c=(0,E.useRef)(null),u=(0,E.useRef)(0);(0,E.useEffect)(()=>{if(n<=0){t();return}if(i){c.current&&(clearTimeout(c.current),c.current=null);return}return u.current=Date.now(),c.current=setTimeout(()=>{c.current=null,t()},n),()=>{c.current&&(clearTimeout(c.current),c.current=null)}},[t,i,n]),(0,E.useEffect)(()=>{if(i||n<=0){o(n);return}let h=()=>{let S=u.current?Date.now()-u.current:0;o(Math.max(0,n-S))};h();let v=setInterval(h,Sk);return()=>clearInterval(v)},[i,n]);function f(){if(i)return;c.current&&(clearTimeout(c.current),c.current=null);let h=u.current?Date.now()-u.current:0,v=Math.max(0,n-h);r(v),o(v),s(!0)}function d(){s(!1)}let p=e.tone==="error"?"border-rose-200 bg-rose-50 text-rose-800":e.tone==="success"?"border-emerald-200 bg-emerald-50 text-emerald-800":"border-amber-200 bg-amber-50 text-amber-800",m=9,b=2*Math.PI*m,g=Math.max(0,Math.min(1,a/Gg)),x=b*(1-g),y=i?`Auto-dismiss paused with ${Math.max(0,a/1e3).toFixed(1)} seconds remaining`:`Auto-dismiss in ${Math.max(0,a/1e3).toFixed(1)} seconds`;return(0,l.jsx)("div",{className:W("pointer-events-auto rounded-2xl border px-4 py-3 text-sm shadow-lg backdrop-blur",p),onMouseEnter:f,onMouseLeave:d,onFocusCapture:f,onBlurCapture:h=>{h.currentTarget.contains(h.relatedTarget)||d()},role:e.tone==="error"?"alert":"status",children:(0,l.jsxs)("div",{className:"min-w-0",children:[(0,l.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,l.jsx)("div",{className:"text-[11px] font-medium uppercase tracking-[0.16em] opacity-75",children:G2(e.tone)}),(0,l.jsxs)("div",{className:"relative mt-0.5 h-6 w-6 shrink-0 opacity-85","aria-label":y,title:y,children:[(0,l.jsxs)("svg",{viewBox:"0 0 24 24",className:W("h-6 w-6 -rotate-90",i?"opacity-70":"opacity-100"),"aria-hidden":"true",children:[(0,l.jsx)("circle",{cx:"12",cy:"12",r:m,fill:"none",stroke:"currentColor",strokeOpacity:"0.18",strokeWidth:"2"}),(0,l.jsx)("circle",{cx:"12",cy:"12",r:m,fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeDasharray:b,strokeDashoffset:x,className:"transition-[stroke-dashoffset,opacity] duration-100 ease-linear"})]}),(0,l.jsx)("span",{className:W("pointer-events-none absolute inset-0 flex items-center justify-center",i?"gap-[2px]":""),"aria-hidden":"true",children:i?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("span",{className:"h-2.5 w-[2px] rounded-full bg-current/75"}),(0,l.jsx)("span",{className:"h-2.5 w-[2px] rounded-full bg-current/75"})]}):(0,l.jsx)("span",{className:"h-1.5 w-1.5 rounded-full bg-current/75"})})]})]}),(0,l.jsx)("div",{className:"mt-1 leading-6",children:e.message}),(0,l.jsx)("div",{className:"mt-2 flex justify-end",children:(0,l.jsx)("button",{className:"rounded-full border border-current/15 px-2.5 py-1 text-[11px] font-medium uppercase tracking-[0.16em] opacity-85 transition hover:border-current/30 hover:opacity-100",onClick:t,type:"button",children:"Dismiss"})})]})})}function oC({notices:e,onDismiss:t}){return!Array.isArray(e)||e.length===0?null:(0,l.jsx)("div",{className:"pointer-events-none fixed inset-x-4 top-4 z-50 flex flex-col items-end gap-3","aria-live":"polite","aria-relevant":"additions text",children:e.map(n=>(0,l.jsx)("div",{className:"w-full max-w-md",children:(0,l.jsx)(Y2,{notice:n,onDismiss:()=>t(n.id)})},n.id))})}function W2({provider:e,disabled:t=!1,disabledReason:n="",busy:r=!1,onApply:a,framed:o=!0,focusRequest:i=0,onStateChange:s=null,testStateByModel:c={},savePhase:u="",saveMessage:f=""}){let d=(0,E.useMemo)(()=>L1(e),[e]),[p,m]=(0,E.useState)([]),[b,g]=(0,E.useState)(""),[x,y]=(0,E.useState)(!1),[h,v]=(0,E.useState)({}),[S,C]=(0,E.useState)({}),[T,w]=(0,E.useState)(null),[R,M]=(0,E.useState)(""),[k,I]=(0,E.useState)(""),[H,Q]=(0,E.useState)({}),ee=(0,E.useRef)(0),X=(0,E.useRef)([]),z=(0,E.useRef)(new Map),te=(0,E.useRef)(new Map),Y=(0,E.useRef)(""),q=(0,E.useRef)(""),V=(0,E.useRef)(null),_e=(0,E.useRef)(new Map),F=(0,E.useRef)(new Map);function he(A={}){return ee.current+=1,{key:`model-${e.id}-draft-${ee.current}`,id:"",sourceId:"",contextWindow:"",...A}}function Z(A){Y.current=A}function ae(A=[],{preserveFocus:D=!1}={}){let B=[],G=null;for(let $ of Array.isArray(A)?A:[]){let tt=String($?.id||""),He=$?.contextWindow===void 0||$?.contextWindow===null?"":String($.contextWindow);if(String(tt).trim()){B.push({...$,id:tt,contextWindow:He});continue}G||(G={...$,id:"",contextWindow:He})}return G||(G=he(),D&&Z(G.key)),[G,...B]}function Se(A){C(D=>{if(!D[A])return D;let B={...D};return delete B[A],B})}function U(A,D){v(B=>{if(D)return B[A]?B:{...B,[A]:!0};if(!B[A])return B;let G={...B};return delete G[A],G})}function ne(A,D={},{clearLookupState:B=!1,clearStatus:G=!0,closeLookupMenu:$=!1}={}){B&&Se(A),G&&w(null),$&&R===A&&M(""),m(tt=>ae(tt.map(He=>He.key===A?{...He,...D}:He),{preserveFocus:!1}))}(0,E.useEffect)(()=>{X.current=p},[p]),(0,E.useEffect)(()=>{let A=ae(d,{preserveFocus:!0});m(A),X.current=A,_e.current.clear(),F.current.clear(),v({}),C({}),w(null),M(""),I(""),Q({})},[d]),(0,E.useEffect)(()=>{let A=Y.current;if(!A)return;let D=z.current.get(A);if(!D)return;D.scrollIntoView?.({block:"nearest"}),D.focus();let B=D.value?.length||0;D.setSelectionRange?.(B,B),Y.current=""},[p]),(0,E.useEffect)(()=>{i&&m(A=>{let D=ae(A,{preserveFocus:!1}),B=D.find(G=>!String(G?.id||"").trim())||D[D.length-1];return B&&Z(B.key),D})},[i]),(0,E.useEffect)(()=>{R&&(p.some(A=>A.key===R)||M(""))},[p,R]),(0,E.useEffect)(()=>{k&&(p.some(A=>A.key===k)||I(""))},[p,k]),(0,E.useEffect)(()=>{Q(A=>{let D=new Set(p.map($=>$.key)),B=!1,G={};for(let[$,tt]of Object.entries(A)){if(!D.has($)){B=!0;continue}G[$]=tt}return B?G:A})},[p]),(0,E.useEffect)(()=>{if(!R||typeof document>"u")return;function A(D){te.current.get(R)?.contains(D.target)||M("")}return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[R]);let ue=(0,E.useMemo)(()=>p.filter(A=>String(A?.id||"").trim()),[p]),me=(0,E.useMemo)(()=>d.map(A=>({id:String(A?.id||"").trim(),contextWindow:so(A?.contextWindow||"")})).filter(A=>A.id),[d]),re=(0,E.useMemo)(()=>ue.map(A=>({...A,id:String(A?.id||"").trim(),contextWindow:so(A?.contextWindow||"")})),[ue]),oe=re.map(A=>A.id),Ne=me.map(A=>A.id),Re=oe.filter(A=>!Ne.includes(A)),Ze=dh(oe),gt=oe.length>0,Vt=new Set(re.filter(A=>{let D=String(A?.contextWindow||"").trim();if(!D)return!1;let B=Number.parseInt(D,10);return!Number.isFinite(B)||B<=0||String(B)!==D}).map(A=>A.key)),sn=re.filter(A=>!String(A?.contextWindow||"").trim()),ot=JSON.stringify(me)!==JSON.stringify(re.map(A=>({id:A.id,contextWindow:A.contextWindow}))),Ge=t||r||(b!==""||u==="testing"||u==="saving")||x,qr=(0,E.useMemo)(()=>{let A=-1;return p.forEach((D,B)=>{String(D?.id||"").trim()&&(A=B)}),A},[p]),cn=t?n:gt?Ze?"Model ids must be unique for each provider.":Vt.size>0?"Context windows must be positive integers when set.":"":"Keep at least one model id on the provider.",$e=sh(p.map(A=>A.key));(0,E.useEffect)(()=>{s?.({isDirty:ot,issue:cn,locked:Ge,rows:re.map(A=>({...A,contextWindow:so(A.contextWindow)}))})},[s,ot,cn,Ge,re]);function Ee(A){Se(A),U(A,!1),w(null),R===A&&M(""),k===A&&I(""),Q(D=>{if(!Object.prototype.hasOwnProperty.call(D,A))return D;let B={...D};return delete B[A],B}),m(D=>ae(D.filter(B=>B.key!==A)))}function fe(A){m(D=>ae(ih(D,A,B=>B?.key)))}function ge(A){m(D=>ae(mC(D,A,B=>B?.key)))}function P(){q.current="",pl(V.current,!1),V.current=null}async function Ye(A,{force:D=!1}={}){let B=String(A||"").trim();if(!B)return qs({query:B});if(!D&&_e.current.has(B))return _e.current.get(B);if(!D&&F.current.has(B))return F.current.get(B);let G=(async()=>{let $=await th([B]),tt=(Array.isArray($)?$:[]).find(ke=>String(ke?.query||"").trim()===B)||{query:B},He=qs(tt,{fallbackQuery:B});return _e.current.set(B,He),He})();F.current.set(B,G);try{return await G}finally{F.current.delete(B)}}async function Ht(A,{openMenu:D=!1,prefill:B=!1,modelId:G=""}={}){let $=X.current.find(He=>He.key===A),tt=String(G||$?.id||"").trim();if(!tt)return null;D&&M(A),U(A,!0);try{let He=await Ye(tt);if(C(ke=>({...ke,[A]:He})),B){let ke=nh(He);ke&&m(ht=>ae(ht.map(yt=>{if(yt.key!==A)return yt;let Ve=String(yt?.id||"").trim(),de=String(yt?.contextWindow||"").trim();return!Ve||Ve!==tt||de?yt:{...yt,contextWindow:ke}}),{preserveFocus:!1}))}return He}catch(He){let ke=He instanceof Error?He.message:String(He),ht={query:tt,status:"error",error:ke,options:[]};return C(yt=>({...yt,[A]:ht})),ht}finally{U(A,!1)}}async function Gt(A=[]){let D=new Set(Array.isArray(A)?A:[]),B=re.filter(G=>!G.id||String(G?.contextWindow||"").trim()?!1:D.size===0?!0:D.has(G.key)).map(G=>({key:G.key,id:G.id}));if(B.length!==0){y(!0),w(null);try{let G=await th(B.map(Ve=>Ve.id)),$=k2(G),tt=new Map(B.map(Ve=>[Ve.key,Ve]));for(let Ve of $.values())Ve?.query&&_e.current.set(Ve.query,Ve);let He=Array.isArray(X.current)?X.current:[],ke=0,ht=0,yt=He.map(Ve=>{let de=tt.get(Ve.key);if(!de)return Ve;let qe=String(Ve?.id||"").trim(),un=String(Ve?.contextWindow||"").trim();if(!qe||qe!==de.id||un)return Ve;let po=$.get(qe)||qs({query:qe}),Bn=nh(po);return Bn?(ke+=1,{...Ve,contextWindow:Bn}):(ht+=1,Ve)});m(ae(yt,{preserveFocus:!1})),w({tone:ke>0?"success":"warning",message:ke>0?`Filled ${ke} context size${ke===1?"":"s"}${ht>0?`; ${ht} still need a manual value`:""}.`:`Could not fill ${ht} model${ht===1?"":"s"}.`})}catch(G){w({tone:"error",message:G instanceof Error?G.message:String(G)})}finally{y(!1)}}}async function Mt(){if(Ge||cn||!ot)return!1;let A=uo(e)==="api"&&Re.length>0;g(A?"testing":"saving");try{return await a(re.map(D=>({...D,contextWindow:so(D.contextWindow)})))}finally{g("")}}return(0,l.jsxs)("div",{className:W(o?"space-y-3 rounded-2xl border border-border/70 bg-background/60 p-4":"space-y-3"),children:[(0,l.jsx)("div",{className:"rounded-2xl border border-border/70 bg-secondary/35 px-4 py-3 text-sm leading-6 text-muted-foreground",children:"Direct routes follow this top-to-bottom order. Focus a context field to load suggested sizes, or use Fill missing context size to fill each empty row with a median size."}),(0,l.jsx)("div",{className:"space-y-2",children:p.map((A,D)=>{let B=String(A?.id||"").trim(),G=String(A?.contextWindow||"").trim(),$=!!B,tt=$?ue.findIndex(de=>de.key===A.key):-1,He=S[A.key]||null,ke=!!h[A.key],ht=R===A.key&&!!B,yt=Vt.has(A.key),Ve=B&&c?.[B]||"default";return(0,l.jsxs)("div",{ref:$e(A.key),"data-reorder-row":"true",onDragOver:de=>{!Ge&&q.current&&q.current!==A.key&&(de.preventDefault(),de.dataTransfer.dropEffect="move")},onDrop:de=>{if(Ge)return;de.preventDefault();let qe=de.dataTransfer.getData("text/plain")||q.current;P(),m(un=>ae(fC(un,qe,A.key)))},className:W("space-y-2 rounded-xl border border-border/70 bg-card/90 p-3",$?null:"border-dashed bg-background/85",yt?"border-amber-200 bg-amber-50/70":null,!yt&&Ve==="success"?"border-emerald-200 bg-emerald-50/70":null,!yt&&Ve==="error"?"border-rose-200 bg-rose-50/70":null,!yt&&Ve==="pending"?"border-sky-200 bg-sky-50/70":null),children:[(0,l.jsxs)("div",{className:"grid grid-cols-[auto_auto_auto_minmax(0,1fr)_minmax(12rem,14rem)_5.5rem] items-center gap-2",children:[(0,l.jsx)("span",{className:W("flex h-8 w-8 items-center justify-center rounded-full text-muted-foreground",$&&!Ge?"cursor-grab":"opacity-45"),draggable:!Ge&&$,onDragStart:de=>{if(Ge||!$)return;let qe=lh(de.currentTarget);de.dataTransfer.effectAllowed="move",de.dataTransfer.setData("text/plain",A.key),qe&&typeof de.dataTransfer?.setDragImage=="function"&&de.dataTransfer.setDragImage(qe,20,20),P(),q.current=A.key,V.current=qe,pl(qe,!0)},onDragEnd:P,title:$?"Drag to reorder":"New model draft row",children:(0,l.jsx)(ch,{className:"h-4 w-4"})}),(0,l.jsx)(Ks,{disabled:Ge||!$||tt<=0,label:!$||tt<=0?"Already first":`Move ${A.id||`model ${tt+1}`} up`,onClick:()=>fe(A.key)}),(0,l.jsx)(kd,{disabled:Ge||!$||D>=qr,label:!$||D>=qr?"Already last":`Move ${A.id||`model ${tt+1}`} down`,onClick:()=>ge(A.key)}),(0,l.jsx)(Dt,{ref:de=>{de?z.current.set(A.key,de):z.current.delete(A.key)},value:A.id,onChange:de=>ne(A.key,{id:de.target.value},{clearLookupState:!0,closeLookupMenu:!0}),placeholder:$?"Model id":"Add a new model id",disabled:Ge}),(0,l.jsxs)("div",{ref:de=>{de?te.current.set(A.key,de):te.current.delete(A.key)},className:"relative min-w-0",children:[(0,l.jsx)(Dt,{value:k===A.key?H[A.key]??Ed(A.contextWindow):o2(A.contextWindow),onChange:de=>{let qe=de.target.value,un=so(qe);Q(po=>({...po,[A.key]:Ed(un)})),ne(A.key,{contextWindow:un},{clearStatus:!1})},onBlur:de=>{I(qe=>qe===A.key?"":qe),Q(qe=>{if(!Object.prototype.hasOwnProperty.call(qe,A.key))return qe;let un={...qe};return delete un[A.key],un}),ne(A.key,{contextWindow:so(de.target.value)},{clearStatus:!1})},onFocus:()=>{B&&(I(A.key),Q(de=>({...de,[A.key]:Ed(A.contextWindow)})),Ht(A.key,{openMenu:!0}))},onClick:()=>{B&&Ht(A.key,{openMenu:!0})},onKeyDown:de=>{if(de.key==="ArrowDown"&&B){de.preventDefault(),Ht(A.key,{openMenu:!0});return}de.key==="Escape"&&(de.preventDefault(),M(""))},placeholder:"Context window",inputMode:"numeric",disabled:Ge||!B,className:"font-medium tabular-nums","aria-label":B?`Context window for ${B}`:"Context window"}),ht?(0,l.jsx)(RC,{open:ht,anchorRef:{current:te.current.get(A.key)||null},preferredSide:"top",desiredHeight:224,className:"z-20 rounded-lg bg-background/98 p-2",onMouseDown:de=>de.preventDefault(),children:ke?(0,l.jsxs)("div",{className:"inline-flex items-center gap-2 px-1 py-2 text-sm text-muted-foreground",children:[(0,l.jsx)(co,{}),"Fetching size options for ",(0,l.jsx)("code",{children:B}),"."]}):He?.status==="error"?(0,l.jsx)("div",{className:"rounded-lg border border-rose-200 bg-rose-50 px-3 py-2 text-xs text-rose-900",children:He.error||"Could not load suggested sizes."}):He?.options?.length>0?(0,l.jsx)("div",{className:"space-y-1",children:He.options.map(de=>(0,l.jsxs)("button",{type:"button",className:"flex w-full flex-col gap-2 rounded-lg border border-border/70 bg-background px-3 py-2 text-left text-sm text-foreground transition hover:border-accent hover:bg-accent disabled:cursor-not-allowed disabled:opacity-70",disabled:Ge,onMouseDown:qe=>qe.preventDefault(),onClick:()=>{Q(qe=>({...qe,[A.key]:Ed(de.contextWindow)})),ne(A.key,{contextWindow:String(de.contextWindow)},{clearStatus:!1}),M("")},title:`Use ${de.label}`,children:[(0,l.jsxs)("div",{className:"min-w-0 space-y-1",children:[(0,l.jsx)("div",{className:"break-words font-medium leading-5",children:de.label}),(0,l.jsx)("div",{className:"break-words text-xs leading-4 text-muted-foreground",children:de.detail})]}),(0,l.jsxs)("div",{className:"w-full rounded-md border border-border/70 bg-secondary/70 px-3 py-2",children:[(0,l.jsx)("div",{className:"text-[10px] font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Context size"}),(0,l.jsx)("div",{className:"mt-1 text-lg font-semibold leading-none tabular-nums text-foreground",children:Hs(de.contextWindow)})]})]},de.key))}):(0,l.jsxs)("div",{className:"rounded-lg border border-dashed border-border/70 bg-background/80 px-3 py-2 text-xs text-muted-foreground",children:["No suggested size was found for ",(0,l.jsx)("code",{children:He?.query||B}),"."]})}):null]}),$?(0,l.jsx)(ce,{type:"button",variant:"ghost",className:Ld,onMouseDown:de=>de.preventDefault(),onClick:()=>Ee(A.key),disabled:Ge,children:"Remove"}):(0,l.jsx)(ce,{type:"button",variant:"ghost",className:W(Ld,"pointer-events-none invisible"),tabIndex:-1,disabled:!0,"aria-hidden":"true",children:"Remove"})]}),ke?(0,l.jsx)("div",{className:"flex justify-end text-xs",children:(0,l.jsxs)("div",{className:"inline-flex items-center gap-1.5 text-sky-700",children:[(0,l.jsx)(co,{}),"Looking up sizes"]})}):null,yt?(0,l.jsxs)("div",{className:"rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900",children:["Enter a positive integer like ",(0,l.jsx)("code",{children:"128000"}),", or leave the field blank."]}):Ve==="pending"?(0,l.jsx)("div",{className:"rounded-lg border border-sky-200 bg-sky-50 px-3 py-2 text-xs text-sky-900",children:"Testing this model against the provider endpoint now."}):Ve==="success"?(0,l.jsx)("div",{className:"rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-2 text-xs text-emerald-900",children:"Confirmed by the latest live provider test."}):Ve==="error"?(0,l.jsx)("div",{className:"rounded-lg border border-rose-200 bg-rose-50 px-3 py-2 text-xs text-rose-900",children:"This model failed the latest live provider test."}):null]},A.key)})}),cn?(0,l.jsx)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900",children:cn}):null,T?(0,l.jsx)("div",{className:W("rounded-xl px-3 py-2 text-sm",T.tone==="error"?"border border-rose-200 bg-rose-50 text-rose-900":T.tone==="warning"?"border border-amber-200 bg-amber-50 text-amber-900":"border border-emerald-200 bg-emerald-50 text-emerald-900"),children:T.message}):null,(0,l.jsx)("div",{className:W("sticky z-10 border-t border-border/70 bg-background/95 pt-3 backdrop-blur",o?"bottom-0":"bottom-0 -mx-5 rounded-b-[1rem] px-5 pb-4"),children:(0,l.jsxs)("div",{className:"flex min-h-9 items-center justify-between gap-3",children:[(0,l.jsx)("div",{className:W("text-xs",u==="testing"?"text-sky-700":u==="saving"?"text-foreground":"text-muted-foreground"),children:u==="testing"?(0,l.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,l.jsx)(co,{}),f||"Testing new models before save."]}):u==="saving"?(0,l.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,l.jsx)(co,{}),f||"Saving provider models."]}):Re.length>0&&uo(e)==="api"?`${Re.length} new model${Re.length===1?"":"s"} will be tested before save.`:"Existing models keep their current configuration metadata."}),(0,l.jsxs)("div",{className:"flex items-center justify-end gap-2",children:[!t&&!Ge&&sn.length>0?(0,l.jsx)(ce,{type:"button",variant:"outline",onClick:()=>{Gt()},children:x?"Filling\u2026":"Fill missing context size"}):null,!t&&!Ge&&ot?(0,l.jsx)(ce,{type:"button",variant:"ghost",onClick:()=>{v({}),C({}),w(null),M(""),_e.current.clear(),F.current.clear(),m(ae(d,{preserveFocus:!0}))},children:"Reset"}):null,!t&&ot&&!cn?(0,l.jsx)(ce,{type:"button",onClick:()=>{Mt()},disabled:Ge,children:u==="testing"||b==="testing"?"Testing\u2026":u==="saving"||b==="saving"||r?"Saving\u2026":"Save models"}):null]})]})})]})}function Q2({title:e,rows:t,onChange:n,options:r,disabled:a=!1,addLabel:o="Add target",emptyLabel:i="No targets configured.",helperText:s="Drag rows or use the arrow to change routing order.",helperAction:c=null,placeholder:u="provider/model or alias",draftPlaceholder:f="Add a new route",showDraftRow:d=!1,showDraftFocusButton:p=!1,showWeightInput:m=!1,filterOtherSelectedValues:b=!1,excludedValues:g=[]}){let x=(0,E.useRef)(0),y=(0,E.useRef)(""),h=(0,E.useRef)(null),v=(0,E.useRef)(new Map),S=(0,E.useRef)(0),C=(0,E.useRef)(0),[T,w]=(0,E.useState)(0),R=(0,E.useMemo)(()=>String(e||"targets").trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"targets",[e]),M=`${R}-draft-row`,k=(0,E.useMemo)(()=>{let F=(t||[]).filter(he=>String(he?.ref||"").trim());return d?[{key:M,ref:"",sourceRef:""},...F]:F},[t,d,M]),I=sh(k.map(F=>F.key)),H=(0,E.useMemo)(()=>ba(g),[g]),Q=(0,E.useMemo)(()=>Fs(r,[...k.map(F=>F?.ref),...H]),[r,k,H]);(0,E.useEffect)(()=>()=>{typeof window<"u"&&S.current&&window.cancelAnimationFrame(S.current)},[]);function ee(F,he){if(d&&F===M){if(!String(he||"").trim())return;x.current+=1,n([{key:`${R}-draft-${x.current}`,ref:he,sourceRef:"",...m?{weight:"1"}:{}},...(t||[]).filter(Z=>String(Z?.ref||"").trim())]);return}n((t||[]).map(Z=>Z.key===F?{...Z,ref:he}:Z))}function X(F,he){n((t||[]).map(Z=>Z.key===F?{...Z,weight:he}:Z))}function z(F){n((t||[]).filter(he=>he.key!==F))}function te(F){n(ih(t||[],F,he=>he?.key))}function Y(F){n(mC(t||[],F,he=>he?.key))}function q(){y.current="",pl(h.current,!1),h.current=null}function V(){x.current+=1;let F=new Set([...(t||[]).map(Z=>String(Z?.ref||"").trim()).filter(Boolean),...H]),he=Q.find(Z=>!F.has(Z.value))?.value||"";n([...t||[],{key:`${R}-draft-${x.current}`,ref:he,sourceRef:""}])}function _e(){if(!d||a)return;let F=v.current.get(M);if(!F||typeof window>"u"){w(Ne=>Ne+1);return}C.current+=1;let he=C.current;S.current&&(window.cancelAnimationFrame(S.current),S.current=0),F.scrollIntoView({block:"start",behavior:"smooth"});let Z=hd(F),ae=P1(F,Z),Se=0,U=0,ne=90,ue=8,me=6,re=.5,oe=()=>{if(C.current!==he)return;let Ne=v.current.get(M)||F,Re=P1(Ne,Z);if(!Number.isFinite(Re.top)||!Number.isFinite(Re.left)){S.current=0,w(Ze=>Ze+1);return}if(Tk(ae,Re,re)?Se+=1:Se=0,ae=Re,U+=1,U>=ue&&Se>=me||U>=ne){S.current=0,w(Ze=>Ze+1);return}S.current=window.requestAnimationFrame(oe)};S.current=window.requestAnimationFrame(oe)}return(0,l.jsxs)("div",{className:"space-y-2 rounded-2xl border border-border/70 bg-background/55 p-4",children:[(0,l.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[(0,l.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,l.jsx)("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:e}),p&&d?(0,l.jsx)(ce,{type:"button",variant:"ghost",size:"sm",className:"h-6 w-6 rounded-md p-0 text-muted-foreground hover:text-foreground",onMouseDown:F=>F.preventDefault(),onClick:_e,disabled:a,"aria-label":o,title:o,children:(0,l.jsx)(pC,{className:"h-3.5 w-3.5"})}):null]}),(0,l.jsxs)("div",{className:"ml-auto flex max-w-full flex-wrap items-start justify-end gap-x-3 gap-y-2",children:[s?(0,l.jsx)("div",{className:"max-w-[34rem] text-right text-[11px] leading-4 text-muted-foreground",children:s}):null,d?null:(0,l.jsx)(ce,{type:"button",variant:"ghost",onClick:V,disabled:a,children:o})]})]}),k.length>0?(0,l.jsx)("div",{className:"space-y-2",children:k.map((F,he)=>{let Z=d&&F.key===M,ae=Z?-1:(t||[]).findIndex(U=>U?.key===F.key),Se=b?Q.filter(U=>{let ne=String(U?.value||"").trim();return ne?ne===String(F?.ref||"").trim()?!0:H.includes(ne)?!1:!(k||[]).some(ue=>ue?.key!==F.key&&String(ue?.ref||"").trim()===ne):!1}):Q;return(0,l.jsxs)("div",{ref:U=>{if(I(F.key)(U),U){v.current.set(F.key,U);return}v.current.delete(F.key)},"data-reorder-row":"true",onDragOver:U=>{!a&&y.current&&y.current!==F.key&&(U.preventDefault(),U.dataTransfer.dropEffect="move")},onDrop:U=>{if(a)return;U.preventDefault();let ne=U.dataTransfer.getData("text/plain")||y.current;q(),n(fC(t||[],ne,F.key))},className:W(m?"grid grid-cols-[auto_auto_auto_minmax(0,1fr)_10rem_5.5rem] items-center gap-2 rounded-xl border border-border/70 bg-card/90 p-3":"grid grid-cols-[auto_auto_auto_minmax(0,1fr)_5.5rem] items-center gap-2 rounded-xl border border-border/70 bg-card/90 p-3",Z?"border-dashed bg-background/85":null),children:[(0,l.jsx)("span",{className:W("flex h-8 w-8 items-center justify-center rounded-full text-muted-foreground",Z||a?"opacity-45":"cursor-grab"),draggable:!a&&!Z,onDragStart:U=>{if(a||Z)return;let ne=lh(U.currentTarget);U.dataTransfer.effectAllowed="move",U.dataTransfer.setData("text/plain",F.key),ne&&typeof U.dataTransfer?.setDragImage=="function"&&U.dataTransfer.setDragImage(ne,20,20),q(),y.current=F.key,h.current=ne,pl(ne,!0)},onDragEnd:q,title:Z?"New route draft row":"Drag to reorder",children:(0,l.jsx)(ch,{className:"h-4 w-4"})}),(0,l.jsx)(Ks,{disabled:a||Z||ae<=0,label:Z||ae<=0?"Already first":`Move ${F.ref||`target ${ae+1}`} up`,onClick:()=>te(F.key)}),(0,l.jsx)(kd,{disabled:a||Z||ae===-1||ae>=(t||[]).length-1,label:Z||ae===-1||ae>=(t||[]).length-1?"Already last":`Move ${F.ref||`target ${ae+1}`} down`,onClick:()=>Y(F.key)}),(0,l.jsxs)("div",{className:"flex h-9 min-w-0 overflow-hidden rounded-lg border border-input bg-background/80 shadow-sm transition focus-within:border-ring focus-within:ring-2 focus-within:ring-ring/40",children:[(0,l.jsx)("div",{className:"flex shrink-0 items-center border-r border-border/70 bg-secondary/55 px-2.5 text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Model"}),(0,l.jsxs)(vr,{value:F.ref||void 0,onValueChange:U=>ee(F.key,U),disabled:a,openSearchRequest:Z?T:0,children:[(0,l.jsx)(br,{className:"h-full min-w-0 flex-1 rounded-none border-0 bg-transparent px-3 shadow-none focus:border-transparent focus:ring-0",children:(0,l.jsx)(xr,{placeholder:Z?f:u})}),(0,l.jsx)(Sr,{children:Se.length>0?Bd(Se,{keyPrefix:`${e}-row-${F.key}`}):(0,l.jsx)(ar,{value:"__no-route-options",disabled:!0,children:"No routes available"})})]})]}),m?(0,l.jsxs)("div",{className:W("flex h-9 overflow-hidden rounded-lg border border-input bg-background/80 shadow-sm transition focus-within:border-ring focus-within:ring-2 focus-within:ring-ring/40",Z?"opacity-45":null),children:[(0,l.jsx)("div",{className:"flex shrink-0 items-center border-r border-border/70 bg-secondary/55 px-2.5 text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Weight"}),(0,l.jsx)(Dt,{value:Z?"":String(F?.weight||"1"),onChange:U=>X(F.key,U.target.value),inputMode:"numeric",placeholder:"1",disabled:a||Z,className:"h-full min-w-0 rounded-none border-0 bg-transparent px-3 text-center shadow-none focus:border-transparent focus:ring-0","aria-label":Z?"Weight for new target":`Weight for ${F.ref||`target ${he+1}`}`})]}):null,Z?(0,l.jsx)(ce,{type:"button",variant:"ghost",className:W(Ld,"pointer-events-none invisible"),tabIndex:-1,disabled:!0,"aria-hidden":"true",children:"Remove"}):(0,l.jsx)(ce,{type:"button",variant:"ghost",className:Ld,onMouseDown:U=>U.preventDefault(),onClick:()=>z(F.key),disabled:a,children:"Remove"})]},F.key)})}):(0,l.jsx)("div",{className:"rounded-xl border border-dashed border-border px-4 py-5 text-sm text-muted-foreground",children:i}),c?(0,l.jsx)("div",{className:"flex min-h-8 items-center justify-end",children:c}):null]})}function X2(e,t){let n=Math.abs(Number(e)||0),r=Math.abs(Number(t)||0);for(;r!==0;){let a=n%r;n=r,r=a}return n||1}function Z2(e=[]){return!Array.isArray(e)||e.length===0?1:e.reduce((t,n)=>X2(t,n),0)||1}function J2(e,t){let n=String(e||"").trim();if(!n)return"Unconfigured route";let r=t.get(n);if(!r)return n;let a=String(r.label||n).trim()||n,o=String(r.hint||"").trim();return o&&o!==a?`${a} \xB7 ${o}`:a}function eL(e,t,n=[]){let r=new Map((n||[]).map(s=>[String(s?.value||"").trim(),s]).filter(([s])=>!!s)),a=new Map((Array.isArray(t?.targets)?t.targets:[]).map(s=>[String(s?.ref||"").trim(),s]).filter(([s])=>!!s)),o=new Map((Array.isArray(t?.fallbackTargets)?t.fallbackTargets:[]).map(s=>[String(s?.ref||"").trim(),s]).filter(([s])=>!!s));function i(s,c,u){return(s||[]).map((f,d)=>{let p=String(f?.ref||"").trim(),m=String(f?.sourceRef||f?.ref||"").trim(),b=u.get(m)||u.get(p)||{},g=Number(f?.weight??b?.weight),x=Number.isFinite(g)&&g>0?Math.floor(g):1;return{key:`${c}-${p||"empty"}-${d}`,ref:p,label:J2(p,r),bucket:c,weight:x}}).filter(f=>!!f.ref)}return[...i(e?.targets,"primary",a),...i(e?.fallbackTargets,"fallback",o)]}function tL(e=[],t=8){if(!Array.isArray(e)||e.length===0)return[];let n=e.map(s=>Math.max(1,Number(s?.weight)||1)),r=Z2(n),a=n.map(s=>Math.max(1,Math.floor(s/r))),o=a.reduce((s,c)=>s+c,0);if(o>24){let s=o/24;a=a.map(c=>Math.max(1,Math.round(c/s))),o=a.reduce((c,u)=>c+u,0)}let i=[];for(let s=0;s<e.length;s+=1)for(let c=0;c<a[s];c+=1)i.push(e[s]);return Array.from({length:Math.max(e.length,t)},(s,c)=>i[c%i.length])}function nL(e,t=[]){let n=uh(e),r=gC(n),a=Array.isArray(t)?t.filter(Boolean):[],i=a.some(s=>s.bucket==="fallback")?"Runtime builds the candidate pool as all primary targets first, then all fallback targets.":"Runtime builds the candidate pool from the primary target list only.";if(n==="round-robin"){let s=a.length>0?Array.from({length:Math.max(a.length,8)},(c,u)=>a[u%a.length]):[];return{strategyLabel:r,summary:"Each new request starts from the next candidate in the current pool, then wraps around.",poolNote:`${i} Round-robin rotates across that combined eligible list.`,sequenceLabel:"Example starting candidate by request",sequenceEntries:s,footnote:"If a candidate is unhealthy or quota-blocked, it is skipped and the next eligible candidate is chosen."}}if(n==="weighted-rr"||n==="quota-aware-weighted-rr"||n==="auto"){let s=n==="auto",c=tL(a,8);return{strategyLabel:r,summary:s?"`auto` normalizes to quota-aware weighted round-robin in the runtime balancer.":n==="quota-aware-weighted-rr"?"Candidates rotate like weighted round-robin, but low remaining quota or poor health lowers their share.":"Candidates repeat in proportion to their configured weights.",poolNote:`${i} This strategy ranks across the full eligible pool after it is built.`,sequenceLabel:"Example starting candidate by request",sequenceEntries:c,footnote:s||n==="quota-aware-weighted-rr"?"When all quotas and health scores are equal, the rotation looks like the weighted example below. Low remaining capacity or retryable failures push a target later.":"Weights come from the existing alias target metadata when present. Targets without a stored weight behave as weight 1."}}return{strategyLabel:r,summary:"Requests try candidates in the configured list order and only move to later candidates when earlier ones are unavailable or fail.",poolNote:`${i} Ordered keeps that exact sequence.`,sequenceLabel:"Attempt order",sequenceEntries:a,footnote:"This is the most predictable option when you want a strict preference order."}}function rL({open:e=!1,onClose:t=()=>{},onSave:n=()=>{},aliasLabel:r="",initialStrategy:a="auto",entries:o=[],disabled:i=!1}){let s=uh(a),[c,u]=(0,E.useState)(s),[f,d]=(0,E.useState)(!1);(0,E.useEffect)(()=>{e&&(u(s),d(!1))},[e,s,r]);async function p(){if(!(i||f)){d(!0);try{await n(c)!==!1&&t()}finally{d(!1)}}}return(0,l.jsx)(Sa,{open:e,onClose:t,title:r?`Choose strategy \xB7 ${r}`:"Choose strategy",description:"Review each routing strategy in its own tab. Save applies the currently selected tab to this alias.",showCloseButton:!1,footer:(0,l.jsxs)("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[(0,l.jsx)(ce,{type:"button",variant:"ghost",onClick:t,disabled:f,children:"Cancel"}),(0,l.jsx)(ce,{type:"button",onClick:()=>{p()},disabled:i||f,children:f?"Saving\u2026":"Save strategy"})]}),children:(0,l.jsxs)(Vu,{value:c,onValueChange:u,children:[(0,l.jsx)("div",{className:"overflow-x-auto pb-1",children:(0,l.jsx)(Hu,{className:"h-auto min-w-max flex-wrap justify-start gap-2 rounded-2xl bg-secondary/80 p-2",children:Wg.map(m=>(0,l.jsx)(Or,{value:m.value,className:"h-auto min-h-10 rounded-xl px-4 py-2",children:m.label},m.value))})}),Wg.map(m=>{let b=nL(m.value,o),g=(b.sequenceEntries||[]).filter(Boolean);return(0,l.jsx)(_r,{value:m.value,className:"mt-4",children:(0,l.jsxs)("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.15fr)_minmax(320px,0.85fr)]",children:[(0,l.jsxs)("div",{className:"space-y-4",children:[(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/80 p-5",children:[(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,l.jsx)(Tt,{variant:"outline",children:b.strategyLabel}),(0,l.jsxs)(Tt,{variant:"info",children:[o.length," candidate",o.length===1?"":"s"]})]}),(0,l.jsxs)("div",{className:"mt-4 space-y-3 text-sm leading-6 text-foreground",children:[(0,l.jsx)("p",{children:b.summary}),(0,l.jsx)("p",{className:"text-muted-foreground",children:b.poolNote})]})]}),(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/80 p-5",children:[(0,l.jsx)("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:b.sequenceLabel}),g.length>0?(0,l.jsx)("div",{className:"mt-4 flex flex-wrap gap-2",children:g.map((x,y)=>(0,l.jsxs)("div",{className:"rounded-full border border-border/70 bg-card/90 px-3 py-1.5 text-sm text-foreground",children:[(0,l.jsx)("span",{className:"mr-2 text-xs text-muted-foreground",children:y+1}),(0,l.jsx)("span",{children:x.label})]},`${x.key}-sequence-${y}`))}):(0,l.jsx)("div",{className:"mt-4 rounded-xl border border-dashed border-border px-4 py-5 text-sm text-muted-foreground",children:"Add at least one target to preview how this strategy would route requests."}),(0,l.jsx)("div",{className:"mt-4 text-sm leading-6 text-muted-foreground",children:b.footnote})]})]}),(0,l.jsx)("div",{className:"space-y-4",children:(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/80 p-5",children:[(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,l.jsx)("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Current setup"}),r?(0,l.jsx)(Tt,{variant:"outline",children:r}):null]}),o.length>0?(0,l.jsx)("div",{className:"mt-4 space-y-2",children:o.map(x=>(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-2 rounded-xl border border-border/70 bg-card/90 px-3 py-2 text-sm",children:[(0,l.jsx)(Tt,{variant:x.bucket==="primary"?"info":"outline",children:x.bucket}),(0,l.jsx)("span",{className:"font-medium text-foreground",children:x.label}),(0,l.jsxs)("span",{className:"text-xs text-muted-foreground",children:["weight ",x.weight]})]},x.key))}):(0,l.jsx)("div",{className:"mt-4 rounded-xl border border-dashed border-border px-4 py-5 text-sm text-muted-foreground",children:"This alias does not have any targets yet."})]})})]})},m.value)})]})})}function aL({open:e=!1,onClose:t=()=>{},config:n={}}){let r=(0,E.useMemo)(()=>s2(n),[n]);return(0,l.jsx)(Sa,{open:e,onClose:t,title:"Alias guide",description:"Aliases give clients one stable route while letting LLM Router swap, balance, and fail over across provider/model targets behind that route.",contentClassName:"max-h-[92vh] max-w-4xl rounded-2xl border border-border/70 bg-background/98 shadow-[0_32px_120px_rgba(15,23,42,0.48)]",bodyClassName:"max-h-[calc(92vh-5.5rem)]",children:(0,l.jsxs)("div",{className:"space-y-4",children:[(0,l.jsxs)("div",{className:"grid gap-4 md:grid-cols-3",children:[(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/70 p-4",children:[(0,l.jsx)("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Stable route"}),(0,l.jsxs)("div",{className:"mt-2 text-sm leading-6 text-foreground",children:["Expose one alias like ",(0,l.jsx)("code",{children:"coding"})," or ",(0,l.jsx)("code",{children:"gpt-5.4"})," to clients, then retarget the alias later without touching client config."]})]}),(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/70 p-4",children:[(0,l.jsx)("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Selection strategy"}),(0,l.jsx)("div",{className:"mt-2 text-sm leading-6 text-foreground",children:"The alias strategy controls how LLM Router picks from the configured targets. Ordered is strict preference; the other strategies distribute traffic when multiple targets are healthy."})]}),(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/70 p-4",children:[(0,l.jsx)("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Fallback behavior"}),(0,l.jsx)("div",{className:"mt-2 text-sm leading-6 text-foreground",children:"If one target is unavailable or rate limited, LLM Router can continue to later candidates in the same alias instead of failing the whole request immediately."})]})]}),(0,l.jsxs)("div",{className:"rounded-2xl border border-amber-200 bg-amber-50 p-4",children:[(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,l.jsx)(Tt,{variant:"warning",children:"Important"}),(0,l.jsx)("div",{className:"text-sm font-medium text-amber-950",children:"Mixed context windows inside one alias can change behavior."})]}),(0,l.jsxs)("div",{className:"mt-3 text-sm leading-6 text-amber-900",children:["If an alias mixes models with different context windows, requests that fit the larger model may still fail on the smaller model. For example, an alias that includes both a ",(0,l.jsx)("code",{children:"258K"})," model and a ",(0,l.jsx)("code",{children:"128K"})," model can still fail when routing lands on the smaller target. Keep aliases aligned by context size when you expect long histories or large prompts."]})]}),(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/70 p-4",children:[(0,l.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,l.jsxs)("div",{children:[(0,l.jsx)("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Current config check"}),(0,l.jsx)("div",{className:"mt-1 text-sm text-muted-foreground",children:"Aliases below currently mix different configured model context windows."})]}),(0,l.jsx)(Tt,{variant:r.length>0?"warning":"success",children:r.length>0?`${r.length} alias${r.length===1?"":"es"} need review`:"No mixed context windows detected"})]}),r.length>0?(0,l.jsx)("div",{className:"mt-4 space-y-3",children:r.map(a=>(0,l.jsxs)("div",{className:"rounded-2xl border border-amber-200 bg-amber-50/70 p-4",children:[(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,l.jsx)(Tt,{variant:"outline",children:a.aliasId}),(0,l.jsxs)("div",{className:"text-sm font-medium text-amber-950",children:["Smallest target: ",Hs(a.smallestContextWindow),". Largest target: ",Hs(a.largestContextWindow),"."]})]}),(0,l.jsxs)("div",{className:"mt-3 flex flex-wrap gap-2",children:[a.models.map(o=>(0,l.jsxs)("div",{className:"rounded-full border border-amber-200 bg-background/90 px-3 py-1.5 text-sm text-foreground",children:[o.ref," \xB7 ",Hs(o.contextWindow)]},o.ref)),a.unknownRefs.map(o=>(0,l.jsxs)("div",{className:"rounded-full border border-dashed border-amber-300 bg-background/70 px-3 py-1.5 text-sm text-muted-foreground",children:[o," \xB7 context unknown"]},o))]})]},a.aliasId))}):(0,l.jsx)("div",{className:"mt-4 rounded-xl border border-dashed border-border px-4 py-5 text-sm text-muted-foreground",children:"No alias currently mixes known context-window sizes across its configured targets."})]})]})})}function iC({aliasId:e,alias:t,aliasIds:n,routeOptions:r,defaultModel:a,ampDefaultRoute:o,disabled:i=!1,disabledReason:s="",busy:c=!1,onApply:u,onRemove:f,onCopyAliasId:d=()=>{},isNew:p=!1,alwaysShowAliasIdInput:m=!1,showIssueOnSubmitOnly:b=!1,onDiscard:g=()=>{},onOpenStrategyModal:x=()=>{},titleAccessory:y=null,aliasSwitcher:h=null,framed:v=!0}){let S=Uk(e,t,{isNew:p}),C=(0,E.useMemo)(()=>k1(p?"":e,t),[S]),[T,w]=(0,E.useState)(C),[R,M]=(0,E.useState)(p),[k,I]=(0,E.useState)(!1),H=(0,E.useRef)(null);(0,E.useEffect)(()=>{w(C),M(p),I(!1)},[C,p]);let Q=!p&&Array.isArray(h?.entries)&&h.entries.length>1,ee=m||R;(0,E.useEffect)(()=>{if(!ee)return;let P=typeof window<"u"?window.requestAnimationFrame(()=>{H.current?.focus(),H.current?.select?.()}):0;return()=>{typeof window<"u"&&window.cancelAnimationFrame(P)}},[ee]);let X=String(T?.id||"").trim(),z=e===at||X===at,te=(0,E.useMemo)(()=>Fs((r||[]).filter(P=>P.kind!=="alias"&&P.value!==X&&P.value!==`alias:${X}`),(T?.targets||[]).map(P=>P?.ref)),[r,X,T?.targets]),Y=(T?.targets||[]).map(P=>String(P?.ref||"").trim()),q=(T?.targets||[]).some(P=>!String(P?.ref||"").trim()),V=dh(Y),_e=(T?.targets||[]).some(P=>{if(!String(P?.ref||"").trim())return!1;let Ye=Math.floor(Number(P?.weight));return!Number.isFinite(Ye)||Ye<=0}),F=X&&n.some(P=>P!==e&&P===X),he=X&&Y.some(P=>P===X||P===`alias:${X}`),Z=Y.filter(Boolean).length>0,ae=JSON.stringify({id:C.id,strategy:C.strategy,targets:C.targets.map(P=>({ref:P.ref,weight:String(P?.weight||"1")}))}),Se=JSON.stringify({id:X,strategy:T?.strategy,targets:(T?.targets||[]).map(P=>({ref:String(P?.ref||"").trim(),weight:String(P?.weight||"1").trim()}))}),U=ae!==Se,ne=X?Ak.test(X)?F?"Alias id already exists. Choose another id.":q?"Fill or remove blank target rows before applying.":V?"Duplicate targets are not allowed anywhere in this alias.":_e?"Target weights must be positive integers.":he?"An alias cannot target itself.":"":"Alias id must start with a letter or number and use letters, numbers, dots, underscores, colons, or hyphens.":"Alias id is required.",ue=i?s:ne,me=i?s:b&&ne&&!k?"":ne,re=i||c,oe=String(X||e||"").trim(),Ne=oe||"Select alias",Re=re||z||p,Ze=z?"Default alias cannot be removed":`Remove alias ${oe||e}`,gt=(0,E.useMemo)(()=>eh(Ne),[Ne]),Vt=z||a===e||a===X,sn=o===e||o===X,ot=p?"Enter alias name. Example: claude-opus":void 0,mo=(0,E.useMemo)(()=>eL({...T,fallbackTargets:[]},{...t,fallbackTargets:[]},r),[T,t,r]);async function Ge(){if(I(!0),ue)return!1;let P=await u(e,{...T,fallbackTargets:[]});return P&&p&&g(e),P}async function qr(P){let Ye={...T,strategy:P};return await u(e,{...Ye,fallbackTargets:[]})?p?(g(e),!0):(w(Ye),!0):!1}async function cn(){if(I(!0),ue)return!1;let P=await u(e,{...T,fallbackTargets:[]});return P&&(M(!1),I(!1)),P}function $e(){if(m)return;if(!Q){M(!1);return}let P=String(e||"").trim(),Ye=String(T?.id||"").trim();if(!Ye||Ye===P){w(Ht=>({...Ht,id:P})),M(!1),I(!1);return}cn()}function Ee(P){if(P.key==="Escape"){P.preventDefault(),w(Ye=>({...Ye,id:C.id})),M(!1),I(!1);return}!m&&P.key==="Enter"&&(P.preventDefault(),P.currentTarget.blur())}async function fe(){if(ee){let P=String(e||"").trim(),Ye=String(T?.id||"").trim();if(!Ye||Ye===P){w(Ht=>({...Ht,id:P})),M(!1),I(!1);return}await cn();return}M(!0)}let ge=(0,l.jsxs)("div",{className:"space-y-4",children:[(0,l.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[(0,l.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,l.jsx)("div",{className:"flex min-w-0 flex-wrap items-center gap-2",children:Q?(0,l.jsxs)("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-2",children:[(0,l.jsxs)("div",{className:W("flex h-9 min-w-0 max-w-full overflow-hidden rounded-lg border border-input bg-background/80 shadow-sm transition focus-within:border-ring focus-within:ring-2 focus-within:ring-ring/40",ee?"flex-1":"w-fit"),children:[(0,l.jsx)("div",{className:"flex shrink-0 items-center border-r border-border/70 bg-secondary/55 px-2.5 text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Select an alias"}),ee?(0,l.jsx)(Dt,{ref:H,value:T.id,placeholder:ot,onChange:P=>w(Ye=>({...Ye,id:P.target.value})),onBlur:$e,onKeyDown:Ee,disabled:re||z,className:"h-full min-w-[12rem] flex-1 rounded-none border-0 bg-transparent px-3 text-sm font-medium shadow-none focus:border-transparent focus:ring-0"}):(0,l.jsxs)(vr,{value:h.value||void 0,onValueChange:h.onValueChange,children:[(0,l.jsx)(br,{className:"h-full min-w-[10rem] flex-none rounded-none border-0 bg-transparent px-3 pr-[50px] text-left text-sm font-medium shadow-none focus:border-transparent focus:ring-0",style:{width:`${gt}px`,maxWidth:"100%"},children:(0,l.jsx)(xr,{placeholder:"Select alias"})}),(0,l.jsx)(Sr,{children:h.entries.map(([P,Ye])=>(0,l.jsx)(ar,{value:P,searchText:`${P} ${(Ye?.targets||[]).length} ${(Ye?.fallbackTargets||[]).length}`,children:P},P))})]}),ee?null:(0,l.jsx)("button",{type:"button",className:"flex h-full w-10 shrink-0 items-center justify-center border-l border-border/70 text-muted-foreground transition hover:bg-accent/60 hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/60 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{d(oe)},disabled:re||!oe,"aria-label":`Copy alias id ${oe}`,title:oe?`Copy alias id ${oe}`:"Alias id is not ready yet",children:(0,l.jsx)(U2,{className:"h-4 w-4 shrink-0"})})]}),(0,l.jsx)(ce,{type:"button",variant:"outline",size:"sm",className:"h-9 w-9 rounded-lg border-border/70 bg-background/70 p-0 text-muted-foreground shadow-none hover:bg-background/90 hover:text-foreground",onMouseDown:P=>{ee&&P.preventDefault()},onClick:()=>{fe()},disabled:re||z,"aria-label":ee?"Save alias id":z?"Default alias id cannot be edited":"Edit alias id",title:ee?"Save alias id":z?"Default alias id cannot be edited":"Edit alias id",children:ee?(0,l.jsx)(I2,{className:"h-4 w-4 shrink-0"}):(0,l.jsx)(Nd,{className:"h-4 w-4 shrink-0"})}),p?null:(0,l.jsx)(ce,{type:"button",variant:"outline",size:"sm",className:"h-9 w-9 rounded-lg border-border/70 bg-background/70 p-0 text-muted-foreground shadow-none hover:border-destructive hover:bg-background/90 hover:text-destructive",onClick:()=>f(e),disabled:Re,"aria-label":Ze,title:Ze,children:(0,l.jsx)(rh,{className:"h-4 w-4 shrink-0"})})]}):(0,l.jsxs)(l.Fragment,{children:[ee?(0,l.jsx)(Dt,{ref:H,autoFocus:p,value:T.id,placeholder:ot,onChange:P=>w(Ye=>({...Ye,id:P.target.value})),onBlur:$e,onKeyDown:Ee,disabled:re||z&&!p,className:"max-w-[22rem] font-semibold"}):z&&!p?(0,l.jsx)("div",{className:"truncate text-base font-semibold text-foreground",children:e}):(0,l.jsxs)("button",{type:"button",className:"group inline-flex max-w-full items-center gap-2 rounded-lg text-left text-base font-semibold text-foreground transition hover:bg-primary/5 hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/60 focus-visible:ring-offset-2 focus-visible:ring-offset-background",onClick:()=>M(!0),disabled:re,"aria-label":"Edit alias id",title:"Edit alias id",children:[(0,l.jsx)("span",{className:"truncate",children:p?X||"New alias":X||e}),(0,l.jsx)(Nd,{className:"h-4 w-4 shrink-0"})]}),y?(0,l.jsx)("div",{className:"min-w-[11rem] max-w-full",children:y}):null]})}),z?null:(0,l.jsxs)("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[Vt?(0,l.jsx)(Tt,{variant:"success",children:"Default route"}):null,sn?(0,l.jsx)(Tt,{variant:"info",children:"AMP default"}):null]})]}),(0,l.jsxs)("div",{className:"flex items-start gap-2 self-start",children:[(0,l.jsxs)(ce,{type:"button",variant:"outline",size:"default",className:"group h-9 gap-0 overflow-hidden rounded-lg border-border/70 bg-background/70 px-0 text-sm font-medium normal-case tracking-normal shadow-none hover:bg-background/90",onClick:()=>x({aliasLabel:X||(p?"New alias":e),strategy:T?.strategy||"auto",entries:mo,disabled:re||!!ue,onSave:qr}),disabled:re,children:[(0,l.jsx)("span",{className:"flex h-full shrink-0 items-center border-r border-border/70 bg-secondary/55 px-2.5 text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Routing stratergy"}),(0,l.jsxs)("span",{className:"inline-flex min-w-0 items-center gap-2 px-3 text-left",children:[(0,l.jsx)("span",{className:"truncate",children:gC(T.strategy||"auto")}),(0,l.jsx)(Nd,{className:"h-4 w-4 shrink-0"})]})]}),!Q&&!p?(0,l.jsx)(ce,{type:"button",variant:"outline",size:"sm",className:"h-9 w-9 rounded-lg border-border/70 bg-background/70 p-0 text-muted-foreground shadow-none hover:border-destructive hover:bg-background/90 hover:text-destructive",onClick:()=>f(e),disabled:Re,"aria-label":Ze,title:Ze,children:(0,l.jsx)(rh,{className:"h-4 w-4 shrink-0"})}):null]})]}),(0,l.jsx)(Q2,{title:"Manage model in alias",rows:T.targets,onChange:P=>w(Ye=>({...Ye,targets:P})),options:te,disabled:re,addLabel:"Add target",emptyLabel:"No targets yet. This alias can stay empty until you wire routes back in.",helperText:"Drag to reorder targets. Weights and metadata stay with the same ref.",draftPlaceholder:"Add a new target",showDraftRow:!0,showDraftFocusButton:!0,showWeightInput:!0,filterOtherSelectedValues:!0,excludedValues:[]}),me?(0,l.jsx)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900",children:me}):null,!me&&z&&!Z?(0,l.jsxs)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900",children:["The fixed ",(0,l.jsx)("code",{children:"default"})," route is empty. Requests routed to ",(0,l.jsx)("code",{children:"default"})," or ",(0,l.jsx)("code",{children:"smart"})," will return 500 until you add a working target."]}):null,p||U?(0,l.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,l.jsx)("div",{children:p?(0,l.jsx)(ce,{type:"button",variant:"ghost",onClick:()=>g(e),disabled:re,children:"Discard"}):null}),(0,l.jsxs)("div",{className:"flex flex-wrap justify-end gap-2",children:[U?(0,l.jsx)(ce,{type:"button",variant:"ghost",onClick:()=>{w(C),I(!1)},disabled:re,children:"Reset"}):null,p||U&&!ue?(0,l.jsx)(ce,{type:"button",onClick:()=>{Ge()},disabled:re,children:c?"Saving\u2026":p?"Create alias":"Apply alias"}):null]})]}):null]});return v?(0,l.jsx)(Xn,{children:(0,l.jsx)(Zn,{className:"space-y-4 p-5",children:ge})}):ge}function oL({aliases:e,config:t,aliasIds:n,routeOptions:r,defaultModel:a,ampDefaultRoute:o,disabledReason:i="",busy:s=!1,onApplyAlias:c,onRemoveAlias:u,onCopyAliasId:f}){let d=Object.entries(e||{}),p=!!i,[m,b]=(0,E.useState)(""),[g,x]=(0,E.useState)(!1),[y,h]=(0,E.useState)(""),v=(0,E.useMemo)(()=>Ik(),[]),[S,C]=(0,E.useState)({open:!1,aliasLabel:"",strategy:"auto",entries:[],disabled:!1,onSave:null});function T(){p||s||b(`draft-${Date.now()}`)}function w(z){(!z||z===m)&&b("")}function R(){b("")}function M({aliasLabel:z="",strategy:te="auto",entries:Y=[],disabled:q=!1,onSave:V=null}){C({open:!0,aliasLabel:z,strategy:te,entries:Y,disabled:q,onSave:V})}function k(){C(z=>({...z,open:!1}))}async function I(z,te){let Y=await c(z,te);if(Y){let q=String(te?.id||z||"").trim()||z;h(q)}return Y}(0,E.useEffect)(()=>{let z=d.map(([te])=>te);if(z.length===0){y&&h("");return}(!y||!z.includes(y))&&h(z[0])},[d,y]);let H=d.find(([z])=>z===y)||d[0]||null,Q=H?.[0]||"",ee=H?.[1]||null,X=d.length>1?{value:Q,onValueChange:h,entries:d}:null;return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(Xn,{children:[(0,l.jsx)(jo,{children:(0,l.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[(0,l.jsx)("div",{className:"space-y-1",children:(0,l.jsx)(Ss,{children:"Model aliases give clients one stable route across multiple provider/models, so you can swap, balance, and fail over without changing client config."})}),(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,l.jsx)(ce,{type:"button",variant:"outline",size:"sm",onClick:()=>x(!0),children:"Help"}),(0,l.jsx)(ce,{type:"button",size:"sm",onClick:T,disabled:p||s,children:s?"Saving\u2026":"Add alias"})]})]})}),(0,l.jsxs)(Zn,{className:"space-y-4",children:[p?(0,l.jsx)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900",children:i}):null,d.length>0?Q&&ee?(0,l.jsx)(iC,{aliasId:Q,alias:ee,aliasIds:n,routeOptions:r,defaultModel:a,ampDefaultRoute:o,disabled:p,disabledReason:i,busy:s,onApply:I,onRemove:u,onCopyAliasId:f,onOpenStrategyModal:M,aliasSwitcher:X,framed:!1},Q):null:(0,l.jsxs)("div",{className:"rounded-2xl border border-dashed border-border px-4 py-6 text-sm text-muted-foreground",children:["No model aliases yet. Add one to expose stable routes like ",(0,l.jsx)("code",{children:"coding"})," or ",(0,l.jsx)("code",{children:"chat.fast"})," in the Web UI."]})]})]}),(0,l.jsx)(Sa,{open:!!m,onClose:R,title:"Add alias",description:"Set a stable client-facing route, choose its strategy, and order the targets it should use.",showCloseButton:!1,contentClassName:"max-h-[92vh] max-w-5xl rounded-2xl border border-border/70 bg-background/98 shadow-[0_32px_120px_rgba(15,23,42,0.48)]",bodyClassName:"max-h-[calc(92vh-5.5rem)]",children:m?(0,l.jsx)(iC,{aliasId:m,alias:v,aliasIds:n,routeOptions:r,defaultModel:a,ampDefaultRoute:o,disabled:p,disabledReason:i,busy:s,onApply:I,onRemove:u,onCopyAliasId:f,isNew:!0,alwaysShowAliasIdInput:!0,showIssueOnSubmitOnly:!0,onDiscard:w,onOpenStrategyModal:M,framed:!1},m):null}),(0,l.jsx)(rL,{open:S.open,onClose:k,onSave:z=>S.onSave?.(z),aliasLabel:S.aliasLabel,initialStrategy:S.strategy,entries:S.entries,disabled:S.disabled}),(0,l.jsx)(aL,{open:g,onClose:()=>x(!1),config:t})]})}function iL({children:e,onClick:t,disabled:n=!1,title:r="",className:a=""}){return(0,l.jsx)("button",{type:"button",className:W("inline-flex items-center rounded-full border border-border bg-background/70 px-2.5 py-1 text-[11px] font-medium tracking-wide text-muted-foreground transition hover:border-primary/35 hover:bg-primary/5 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/60 focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-50",a),onClick:t,disabled:n,title:r,"aria-label":r||void 0,children:e})}function lL({provider:e,onRemove:t,onCopyModelId:n,onApplyProviderDetails:r,onApplyProviderModels:a,onSaveAndCloseEditor:o,disabledReason:i="",busy:s=!1}){let c=(0,E.useMemo)(()=>b2(e),[e]),[u,f]=(0,E.useState)(c),[d,p]=(0,E.useState)(!1),[m,b]=(0,E.useState)(!1),[g,x]=(0,E.useState)(!1),[y,h]=(0,E.useState)("provider"),[v,S]=(0,E.useState)(""),[C,T]=(0,E.useState)(0),[w,R]=(0,E.useState)({isDirty:!1,issue:"",locked:!1,rows:[]}),[M,k]=(0,E.useState)({phase:"",modelStates:{},failedModelIds:[],message:""}),I=(0,E.useRef)(null),H=(0,E.useRef)(null),Q=(0,E.useRef)(null),ee=(0,E.useRef)(null);(0,E.useEffect)(()=>{f(c)},[c]);let z=uo(e)!=="api",te=(Array.isArray(e?.models)?e.models:[]).map(fe=>String(fe?.id||"").trim()).filter(Boolean),Y=vl(e),q=z?"":jk(e?.rateLimits),V=z?[]:Hr(u?.endpoints,u?.endpointDraft),_e=z?[]:xa(u?.rateLimitRows),F=JSON.stringify({id:String(u?.id||"").trim(),name:String(u?.name||"").trim(),credentialInput:String(u?.credentialInput||"").trim(),endpoints:V,endpointDraft:String(u?.endpointDraft||"").trim(),rateLimitRows:K1(u?.rateLimitRows)}),he=JSON.stringify({id:String(c?.id||"").trim(),name:String(c?.name||"").trim(),credentialInput:String(c?.credentialInput||"").trim(),endpoints:ba(c?.endpoints),endpointDraft:String(c?.endpointDraft||"").trim(),rateLimitRows:K1(c?.rateLimitRows)}),Z=F!==he,ae=!!i||s,Se=new Set((Array.isArray(w.rows)?w.rows:[]).map(fe=>String(fe?.id||"").trim()).filter(Boolean)),U=M.failedModelIds.filter(fe=>Se.has(fe)),ne=ae||M.phase==="testing"||M.phase==="saving",ue=z?"":ti(_e,{knownModelIds:te,requireAtLeastOne:!0}),me=i||(String(u?.id||"").trim()?Md.test(String(u?.id||"").trim())?String(u?.name||"").trim()?!z&&V.length===0?"Add at least one endpoint for API Key providers.":!z&&V.some(fe=>!$s(fe))?"All endpoints must start with http:// or https://.":ue:"Provider name is required.":"Provider id must start with a letter and use lowercase letters, digits, or dashes only.":"Provider id is required."),re=z?u:{...u,endpoints:V,endpointDraft:""},oe=!!w.isDirty,Ne=Z||oe,Re=[Z?"provider settings":"",oe?"model list":""].filter(Boolean),Ze=[Z&&me?`Provider: ${me}`:"",oe&&w.issue?`Models: ${w.issue}`:""].filter(Boolean).join(" "),gt=ae||M.phase==="testing"||M.phase==="saving"||Z&&!!me||oe&&(!!w.issue||w.locked)||typeof o!="function";async function Vt(){let fe=await r(e.id,re);return fe&&Ge(),fe}async function sn(fe){let ge=await a(e.id,fe,{providerDraft:Z?re:null,onModelTestStateChange:P=>{k({phase:String(P?.phase||""),modelStates:P?.modelStates&&typeof P.modelStates=="object"?P.modelStates:{},failedModelIds:Array.isArray(P?.failedModelIds)?P.failedModelIds:[],message:String(P?.message||"")})}});return ge&&Ge(),ge}function ot(){f(c)}function mo(fe){R(fe)}function Ge(){b(!1),x(!1),p(!1),h("provider"),S(""),f(c),R({isDirty:!1,issue:"",locked:!1,rows:[]}),k({phase:"",modelStates:{},failedModelIds:[],message:""})}async function qr(){let fe=(Array.isArray(w.rows)?w.rows:[]).filter(P=>!U.includes(String(P?.id||"").trim()));return fe.length===0&&!Z||await o(e.id,{providerDraft:Z?re:null,modelRows:oe?fe:null,onModelTestStateChange:P=>{k({phase:String(P?.phase||""),modelStates:P?.modelStates&&typeof P.modelStates=="object"?P.modelStates:{},failedModelIds:Array.isArray(P?.failedModelIds)?P.failedModelIds:[],message:String(P?.message||"")})}})?(Ge(),!0):(h("models"),!1)}(0,E.useEffect)(()=>{k({phase:"",modelStates:{},failedModelIds:[],message:""})},[c]),(0,E.useEffect)(()=>{U.length>0||!g||x(!1)},[U,g]),(0,E.useEffect)(()=>{if(!d||y!=="provider"||v!=="endpoint"&&v!=="rate-limit"||typeof window>"u")return;let fe=window.requestAnimationFrame(()=>{let ge=v==="endpoint"?I.current:Q.current,P=v==="endpoint"?H.current:ee.current;ge?.scrollIntoView?.({block:"nearest"}),P?.focus?.(),P?.select?.(),S("")});return()=>window.cancelAnimationFrame(fe)},[d,y,v]);function cn(fe="provider",ge=""){b(!1),x(!1),h(fe),S(ge),fe==="models"&&ge==="models"&&T(P=>P+1),p(!0)}function $e(){if(!ne){if(U.length>0){b(!1),x(!0);return}if(Ne){b(!0);return}Ge()}}async function Ee(){if(gt)return;if(!await o(e.id,{providerDraft:Z?re:null,modelRows:oe?w.rows:null,onModelTestStateChange:ge=>{k({phase:String(ge?.phase||""),modelStates:ge?.modelStates&&typeof ge.modelStates=="object"?ge.modelStates:{},failedModelIds:Array.isArray(ge?.failedModelIds)?ge.failedModelIds:[],message:String(ge?.message||"")})}})){oe&&(b(!1),h("models"));return}Ge()}return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(Xn,{children:(0,l.jsxs)(Zn,{className:"space-y-3 p-5",children:[(0,l.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[(0,l.jsx)("div",{className:"min-w-0 flex-1 px-0.5 py-0.5",children:(0,l.jsxs)("div",{className:"flex flex-wrap items-baseline gap-x-2 gap-y-1",children:[(0,l.jsx)("span",{className:"text-base font-semibold text-foreground",children:e.name||e.id}),(0,l.jsxs)("span",{className:"text-sm text-muted-foreground",children:["(",e.id,")"]})]})}),(0,l.jsxs)("div",{className:"flex items-start gap-2 self-start",children:[(0,l.jsxs)(ce,{type:"button",variant:"outline",size:"sm",className:"gap-1.5 normal-case tracking-normal",onClick:()=>cn("provider"),disabled:ae,"aria-label":`Edit provider ${e.name||e.id}`,title:"Edit provider",children:[(0,l.jsx)(Nd,{className:"h-4 w-4 shrink-0"}),"Edit"]}),(0,l.jsx)(ce,{type:"button",variant:"outline",size:"sm",className:"h-8 w-8 shrink-0 p-0 text-muted-foreground hover:border-destructive/35 hover:bg-destructive/5 hover:text-destructive",onClick:()=>t(e.id),disabled:s,"aria-label":"Remove provider",title:"Remove provider",children:(0,l.jsx)(rh,{className:"h-4 w-4"})})]})]}),te.length>0?(0,l.jsx)("div",{className:"flex flex-wrap gap-2 pt-1",children:te.map(fe=>(0,l.jsx)(iL,{onClick:()=>n?.(fe),title:`Copy model id ${fe}`,className:"max-w-full",children:(0,l.jsx)("span",{className:"truncate",children:fe})},`${e.id}-${fe}`))}):null]})}),(0,l.jsx)(Sa,{open:d,onClose:$e,title:`Edit \xB7 ${e.id}`,description:M.phase==="testing"?M.message||"Testing new models before save.":M.phase==="saving"?M.message||"Saving provider changes.":"Switch between provider settings and model list. Each tab saves independently.",closeDisabled:ne,closeOnBackdrop:!ne,closeOnEscape:!ne,contentClassName:"max-h-[92vh] max-w-5xl rounded-2xl border border-border/70 bg-background/98 shadow-[0_32px_120px_rgba(15,23,42,0.48)]",bodyClassName:"max-h-[calc(92vh-5.5rem)] pb-0",children:(0,l.jsxs)(Vu,{value:y,onValueChange:h,children:[(0,l.jsxs)(Hu,{className:"w-full justify-start",children:[(0,l.jsx)(Or,{value:"provider",children:"Provider"}),(0,l.jsx)(Or,{value:"models",children:"Model list"})]}),(0,l.jsxs)(_r,{forceMount:!0,value:"provider",className:W("space-y-4 pb-4",y!=="provider"?"hidden":null),children:[(0,l.jsx)("div",{className:"rounded-2xl border border-border/70 bg-background/60 p-4",children:(0,l.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,l.jsxs)("div",{children:[(0,l.jsx)("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Provider"}),(0,l.jsx)("div",{className:"mt-1 text-sm text-muted-foreground",children:"Update provider identity and connection settings here."})]}),(0,l.jsx)(Tt,{variant:"outline",children:z?"Subscription":"API Key"})]})}),(0,l.jsxs)("div",{className:W("grid gap-3",z?"md:grid-cols-2":"md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]"),children:[(0,l.jsx)(st,{label:"Provider name",stacked:!0,children:(0,l.jsx)(Dt,{value:u.name,onChange:fe=>f(ge=>({...ge,name:fe.target.value})),disabled:ne})}),(0,l.jsx)(st,{label:"Provider id",hint:"Used in direct routes like provider/model",stacked:!0,children:(0,l.jsx)(Dt,{value:u.id,onChange:fe=>f(ge=>({...ge,id:Vr(fe.target.value)})),disabled:ne})})]}),z?null:(0,l.jsxs)("div",{className:"space-y-3",children:[(0,l.jsx)(st,{label:"API key or env",hint:"Use an env var like OPENAI_API_KEY or paste the direct key.",stacked:!0,children:(0,l.jsx)(Dt,{value:u.credentialInput||"",onChange:fe=>f(ge=>({...ge,credentialInput:fe.target.value})),disabled:ne,placeholder:"Example: OPENAI_API_KEY or sk-..."})}),(0,l.jsx)("div",{ref:I,children:(0,l.jsx)(st,{label:"Endpoints",hint:Y.length>1?"Comma, space, or newline turns into chips. The first endpoint stays active until you re-test this provider.":"Comma, space, or newline turns into chips.",stacked:!0,children:(0,l.jsx)(ah,{values:u.endpoints,onChange:fe=>f(ge=>({...ge,endpoints:fe})),draftValue:u.endpointDraft,onDraftValueChange:fe=>f(ge=>({...ge,endpointDraft:fe})),commitOnBlur:!0,disabled:ne,isValueValid:$s,inputRef:H,inputClassName:"placeholder:text-muted-foreground/55",placeholder:"Click here to type new endpoint",helperText:"Paste one or more endpoints"})})}),(0,l.jsx)("div",{ref:Q,className:"grid gap-3 md:grid-cols-2 xl:grid-cols-[minmax(0,1.35fr)_minmax(0,0.8fr)_minmax(0,0.8fr)_minmax(0,1fr)]",children:(0,l.jsx)("div",{className:"md:col-span-2 xl:col-span-4",children:(0,l.jsx)(st,{label:"Rate limit",stacked:!0,headerAction:(0,l.jsx)(ce,{type:"button",size:"sm",variant:"outline",onClick:()=>f(fe=>({...fe,rateLimitRows:MC(fe.rateLimitRows)})),disabled:ne,children:"Add rate limit"}),children:(0,l.jsx)(OC,{rows:u.rateLimitRows,onChange:fe=>f(ge=>({...ge,rateLimitRows:fe})),availableModelIds:te,disabled:ne,inputRef:ee})})})})]}),me?(0,l.jsx)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900",children:me}):null,(0,l.jsxs)("div",{className:"flex min-h-9 items-center justify-end gap-2",children:[!ne&&Z?(0,l.jsx)(ce,{type:"button",variant:"ghost",onClick:ot,children:"Reset"}):null,Z&&!me?(0,l.jsx)(ce,{type:"button",onClick:()=>{Vt()},disabled:ne,children:M.phase==="saving"||s?"Saving\u2026":"Save provider"}):null]})]}),(0,l.jsx)(_r,{forceMount:!0,value:"models",className:W(y!=="models"?"hidden":null),children:(0,l.jsx)(W2,{provider:e,disabled:!!i,disabledReason:i,busy:s,framed:!1,focusRequest:C,onStateChange:mo,onApply:sn,testStateByModel:M.modelStates,savePhase:M.phase,saveMessage:M.message})})]})}),(0,l.jsx)(z2,{open:m,onKeepEditing:()=>b(!1),onDiscardAndClose:Ge,onSaveAndClose:Ee,saveDisabled:gt,dirtyLabels:Re,details:Ze}),(0,l.jsx)(B2,{open:g,failedModelIds:U,onKeepEditing:()=>x(!1),onRemoveFailedAndClose:qr,removeDisabled:ne||typeof o!="function"})]})}function sL({providers:e,onRemove:t,onCopyModelId:n,onApplyProviderDetails:r,onApplyProviderModels:a,onSaveAndCloseEditor:o,disabledReason:i="",busy:s=!1}){return e.length?(0,l.jsx)("div",{className:"grid gap-4 xl:grid-cols-2",children:e.map(c=>(0,l.jsx)(lL,{provider:c,onRemove:t,onCopyModelId:n,onApplyProviderDetails:r,onApplyProviderModels:a,onSaveAndCloseEditor:o,disabledReason:i,busy:s},c.id))}):(0,l.jsx)(Xn,{children:(0,l.jsx)(Zn,{className:"flex flex-col gap-4 p-5 text-sm text-muted-foreground",children:(0,l.jsx)("div",{children:"No enabled providers are configured yet. Use Add provider to create your first provider, model list, and rate limits."})})})}function cL({providers:e,onAddProvider:t,onRemove:n,onCopyModelId:r,onApplyProviderDetails:a,onApplyProviderModels:o,onSaveAndCloseEditor:i,disabledReason:s="",busy:c=!1}){return(0,l.jsxs)("section",{className:"rounded-2xl border border-border/70 bg-card p-4","aria-label":"Provider models",children:[(0,l.jsxs)("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[(0,l.jsxs)("div",{className:"min-w-0",children:[(0,l.jsx)("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Provider & Models"}),(0,l.jsx)("div",{className:"mt-1 text-sm text-muted-foreground",children:"Manage providers, direct model routes, endpoints, and rate limits in one place."})]}),(0,l.jsx)(ce,{onClick:t,children:"Add provider"})]}),(0,l.jsx)("div",{className:"mt-4",children:(0,l.jsx)(sL,{providers:e,onRemove:n,onCopyModelId:r,onApplyProviderDetails:a,onApplyProviderModels:o,onSaveAndCloseEditor:i,disabledReason:s,busy:c})})]})}function uL({rows:e,routeOptions:t,webSearchSnapshot:n,ampClientUrl:r,ampClientGlobal:a,routingBusy:o,onToggleGlobalRouting:i,onInboundChange:s,onOutboundChange:c,onCreateEntry:u,onRemoveEntry:f,onOpenWebSearchTab:d,onOpenConfigPath:p,onOpenSecretsPath:m,hasMasterKey:b,disabledReason:g,autosaveState:x}){let[y,h]=(0,E.useState)(!1),[v,S]=(0,E.useState)(""),[C,T]=(0,E.useState)(String(t[0]?.value||"").trim()),w=e.some(q=>String(q?.inbound||"").trim()===String(v||"").trim()&&String(v||"").trim()),R=String(v||"").trim()&&String(C||"").trim()&&!w,M=a?.routedViaRouter===!0,k=String(a?.error||"").trim(),I=!!(b&&r&&!g&&!k),H=Number(n?.configuredProviderCount)||0,Q=M&&H===0,ee=g?"warning":x.status==="error"?"danger":x.status==="pending"?"outline":x.status==="saving"?"info":x.savedAt?"success":"outline",X=g?"Needs review":x.status==="error"?"Save failed":x.status==="pending"?"Unsaved":x.status==="saving"?"saving...":x.savedAt?"Saved":"Ready",z=g||(x.status==="error"?x.message:x.status==="pending"?"Unsaved changes queued. Auto-save will run shortly.":x.status==="saving"?"Saving changes...":x.savedAt?`Last saved ${vh(x.savedAt)}.`:"AMP route changes auto-save after valid edits.");async function te(){!R||await u?.({inbound:v,outbound:C})===!1||(h(!1),S(""),T(String(t[0]?.value||"").trim()))}function Y(){h(!0),S(""),T(String(t[0]?.value||"").trim())}return(0,l.jsx)("div",{className:"grid gap-4",children:(0,l.jsxs)(Xn,{children:[(0,l.jsxs)(jo,{className:"flex flex-col gap-3 p-4 pb-0 sm:flex-row sm:items-start sm:justify-between",children:[(0,l.jsxs)("div",{className:"space-y-2",children:[(0,l.jsx)(el,{className:"flex items-center gap-2",children:(0,l.jsx)("span",{children:"Use AMP via LLM Router"})}),(0,l.jsx)(TC,{primaryLabel:"Config file",primaryValue:a?.settingsFilePath||"",onOpenPrimary:p,secondaryLabel:"Secrets file",secondaryValue:a?.secretsFilePath||"",secondaryIcon:(0,l.jsx)(q2,{className:"h-3 w-3"}),onOpenSecondary:m})]}),(0,l.jsx)("div",{className:"flex shrink-0 flex-wrap items-center gap-2",children:(0,l.jsx)(ce,{type:"button",size:"sm",variant:M?"outline":void 0,onClick:i,disabled:o!==""||!M&&!I,children:o==="enable"?"Connecting\u2026":o==="disable"?"Disconnecting\u2026":M?"Disconnect":"Connect"})})]}),(0,l.jsxs)(Zn,{className:"space-y-4 p-4",children:[k?(0,l.jsx)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900",children:k}):null,!M&&!b?(0,l.jsxs)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800",children:["Set ",(0,l.jsx)("code",{children:"masterKey"})," first to connect AMP."]}):null,Q?(0,l.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-3 rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900",children:[(0,l.jsx)("div",{className:"max-w-3xl",children:"AMP is connected, but no alternative web search provider is configured. AMP web search is only available through the shared Web Search tab."}),(0,l.jsx)(ce,{type:"button",size:"sm",variant:"outline",onClick:d,children:"Open Web Search"})]}):null,g?(0,l.jsx)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800",children:g}):(0,l.jsxs)("div",{className:"space-y-3 rounded-2xl border border-border/70 bg-background/60 p-4",children:[(0,l.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,l.jsxs)("div",{children:[(0,l.jsx)("div",{className:"text-sm font-medium text-foreground",children:"Route mapping editor"}),(0,l.jsx)("div",{className:"mt-1 text-xs text-muted-foreground",children:"Map built-in AMP route keys and wildcard model matches to managed routes."})]}),(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,l.jsx)(Tt,{variant:ee,children:X}),(0,l.jsxs)(Tt,{variant:"outline",children:[e.length," routes"]}),(0,l.jsx)(ce,{type:"button",size:"sm",onClick:Y,children:"Add custom mapping"})]})]}),(0,l.jsx)("div",{className:"text-xs text-muted-foreground",children:z}),y?(0,l.jsx)("div",{className:"rounded-2xl border border-dashed border-border bg-background/80 p-3",children:(0,l.jsxs)("div",{className:"grid gap-3 xl:grid-cols-[160px_minmax(0,1fr)_minmax(0,1fr)] xl:items-start",children:[(0,l.jsxs)("div",{className:"space-y-2",children:[(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,l.jsx)("div",{className:"text-sm font-medium text-foreground",children:"Add custom mapping"}),(0,l.jsx)(Tt,{variant:"info",children:"Custom"})]}),(0,l.jsxs)("div",{className:"text-xs leading-5 text-muted-foreground",children:["Match a built-in AMP route key like ",(0,l.jsx)("code",{children:"smart"})," or a wildcard such as ",(0,l.jsx)("code",{children:"gpt-*-codex*"}),", then send it to any managed route."]}),(0,l.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,l.jsx)(ce,{type:"button",size:"sm",onClick:te,disabled:!R,children:"Create mapping"}),(0,l.jsx)(ce,{type:"button",size:"sm",variant:"ghost",onClick:()=>h(!1),children:"Close"})]})]}),(0,l.jsx)(st,{label:"Inbound match",hint:"Built-in route key or AMP model pattern",children:(0,l.jsx)(Dt,{value:v,onChange:q=>S(q.target.value),placeholder:"smart or gpt-*-codex*"})}),(0,l.jsx)(st,{label:"Route target",hint:"Alias or provider/model route in LLM Router",children:(0,l.jsxs)(vr,{value:C||void 0,onValueChange:T,children:[(0,l.jsx)(br,{children:(0,l.jsx)(xr,{placeholder:"Select local route"})}),(0,l.jsx)(Sr,{children:Bd(t,{keyPrefix:"amp-route-create",includeHint:!0})})]})})]})}):null,(0,l.jsx)("div",{className:"space-y-2",children:e.map(q=>(0,l.jsx)("div",{className:"rounded-2xl border border-border/70 bg-background/75 p-3",children:(0,l.jsxs)("div",{className:"grid gap-3 xl:grid-cols-[160px_minmax(0,1fr)_minmax(0,1fr)] xl:items-start",children:[(0,l.jsxs)("div",{className:"space-y-2",children:[(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,l.jsx)("div",{className:"text-sm font-medium text-foreground",children:q.label}),q.isCustom?(0,l.jsx)(Tt,{variant:"info",children:"Custom"}):null]}),(0,l.jsx)("div",{className:"text-xs leading-5 text-muted-foreground",children:q.description}),q.removable?(0,l.jsx)(ce,{type:"button",size:"sm",variant:"ghost",onClick:()=>f(q.id),children:"Remove"}):null]}),(0,l.jsx)(st,{label:"Inbound wildcard",hint:q.defaultMatch?`Default: ${q.defaultMatch}`:"AMP model pattern",children:(0,l.jsx)(jg,{commitOnBlur:!0,value:q.inbound,onValueCommit:V=>s(q.id,V),placeholder:q.defaultMatch||"gpt-*-codex*",onKeyDown:V=>{V.key==="Enter"&&(V.preventDefault(),V.currentTarget.blur())}})}),(0,l.jsx)(st,{label:"Target route",hint:"Alias or provider/model route",children:(0,l.jsxs)(vr,{value:q.outbound||"__default__",onValueChange:V=>c(q.id,V),children:[(0,l.jsx)(br,{children:(0,l.jsx)(xr,{placeholder:q.removable?"Choose target route":"Use default route"})}),(0,l.jsxs)(Sr,{children:[q.removable?null:(0,l.jsx)(ar,{value:"__default__",children:"Use default route"}),Bd(t,{keyPrefix:`amp-route-${q.id}`,includeHint:!0})]})]})})]})},q.id))})]})]})]})})}function dL({open:e=!1,onClose:t=()=>{},candidates:n=[],onTestAndAdd:r=async()=>{},disabledReason:a=""}){let[o,i]=(0,E.useState)(""),[s,c]=(0,E.useState)(""),[u,f]=(0,E.useState)(!1),[d,p]=(0,E.useState)(""),m=Array.isArray(n)?n:[],b=m.find(v=>v.providerId===o)||m[0]||null,g=Array.isArray(b?.models)?b.models:[];(0,E.useEffect)(()=>{if(!e){f(!1),p("");return}let v=m[0]?.providerId||"";i(S=>m.some(T=>T.providerId===S)?S:v)},[e,m]),(0,E.useEffect)(()=>{let v=g[0]?.value||"";c(S=>g.some(T=>T.value===S)?S:v)},[g]);let x=yl(o,s),y=e&&!u&&!a&&o&&s;async function h(){if(y){f(!0),p("");try{await r({providerId:o,modelId:s}),t()}catch(v){p(v instanceof Error?v.message:String(v))}finally{f(!1)}}}return(0,l.jsx)(Sa,{open:e,onClose:()=>{u||t()},title:"Add ChatGPT Search Endpoint",description:"Choose a configured OpenAI-compatible GPT route. Test runs a live Responses API request with the native web search tool, then saves the route on success.",contentClassName:"max-h-[92vh] max-w-3xl rounded-2xl border border-border/70 bg-background/98 shadow-[0_32px_120px_rgba(15,23,42,0.48)]",showCloseButton:!1,footer:(0,l.jsxs)("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[(0,l.jsx)(ce,{type:"button",variant:"ghost",onClick:t,disabled:u,children:"Cancel"}),(0,l.jsx)(ce,{type:"button",onClick:()=>{h()},disabled:!y,children:u?"Testing\u2026":"Test connection"})]}),children:(0,l.jsxs)("div",{className:"space-y-4",children:[a?(0,l.jsx)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900",children:a}):null,!a&&m.length===0?(0,l.jsx)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900",children:"No configured OpenAI-compatible GPT providers are available yet. Add a provider with a GPT model first."}):null,m.length>0?(0,l.jsxs)("div",{className:"grid gap-3 md:grid-cols-2",children:[(0,l.jsx)(st,{label:"Provider",hint:"Configured provider or ChatGPT subscription",stacked:!0,children:(0,l.jsxs)(vr,{value:o||void 0,onValueChange:i,disabled:u||!!a,children:[(0,l.jsx)(br,{children:(0,l.jsx)(xr,{placeholder:"Choose provider"})}),(0,l.jsx)(Sr,{children:m.map(v=>(0,l.jsx)(ar,{value:v.providerId,children:v.providerLabel},v.providerId))})]})}),(0,l.jsx)(st,{label:"GPT model",hint:"Only GPT models on OpenAI-compatible routes are listed",stacked:!0,children:(0,l.jsxs)(vr,{value:s||void 0,onValueChange:c,disabled:u||!!a||g.length===0,children:[(0,l.jsx)(br,{children:(0,l.jsx)(xr,{placeholder:"Choose model"})}),(0,l.jsx)(Sr,{children:g.map(v=>(0,l.jsx)(ar,{value:v.value,children:v.label},v.routeId))})]})})]}):null,x?(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/70 px-4 py-3",children:[(0,l.jsx)("div",{className:"text-[11px] font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Saved route id"}),(0,l.jsx)("div",{className:"mt-1 text-sm font-medium text-foreground",children:x}),(0,l.jsx)("div",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:"This route stores only the provider/model reference. No separate API key or quota is saved here."})]}):null,d?(0,l.jsx)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900",children:d}):null]})})}function fL({webSearchConfig:e,webSearchProviders:t,hostedSearchCandidates:n,onWebSearchStrategyChange:r,onWebSearchProviderChange:a,onWebSearchProviderMove:o,onRemoveWebSearchProvider:i,onAddHostedSearchEndpoint:s,disabledReason:c,autosaveState:u}){let[f,d]=(0,E.useState)(!1),p=String(e?.strategy||"ordered").trim()==="quota-balance"?"quota-balance":"ordered",m=Array.isArray(n)&&n.some(g=>Array.isArray(g?.models)&&g.models.length>0),b=c||(u.status==="error"?u.message:u.status==="pending"?"Unsaved changes queued. Auto-save will run shortly.":u.status==="saving"?"Saving changes...":u.savedAt?`Last saved ${vh(u.savedAt)}.`:"");return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(Xn,{children:[(0,l.jsxs)(jo,{className:"flex flex-col gap-4 p-4 pb-0 xl:flex-row xl:items-start xl:justify-between",children:[(0,l.jsxs)("div",{className:"space-y-1",children:[(0,l.jsx)(el,{children:"Web Search"}),(0,l.jsx)(Ss,{className:"text-xs leading-5",children:"Shared web search routing for AMP and other router-managed tools."}),b?(0,l.jsx)("div",{className:"text-xs text-muted-foreground",children:b}):null]}),(0,l.jsxs)("div",{className:"flex w-full shrink-0 flex-wrap items-end justify-end gap-3 xl:w-auto",children:[(0,l.jsxs)("div",{className:"min-w-[12rem] space-y-1",children:[(0,l.jsx)("div",{className:"text-[11px] font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Routing strategy"}),(0,l.jsxs)(vr,{value:p,onValueChange:r,disabled:!!c,children:[(0,l.jsx)(br,{children:(0,l.jsx)(xr,{placeholder:"Choose strategy"})}),(0,l.jsx)(Sr,{children:Ek.map(g=>(0,l.jsx)(ar,{value:g.value,children:g.label},g.value))})]})]}),(0,l.jsxs)(ce,{type:"button",variant:"outline",className:"gap-2",onClick:()=>d(!0),disabled:!!c||!m,children:[(0,l.jsx)(pC,{className:"h-3.5 w-3.5"}),(0,l.jsx)("span",{children:"Endpoint"})]})]})]}),(0,l.jsx)(Zn,{className:"space-y-4 p-4",children:(0,l.jsx)("div",{className:"space-y-3",children:(t||[]).map(g=>{if(g.kind==="hosted"){let h=g.runtimeState&&g.runtimeState.ready===!1?"This provider/model route is no longer available or is not OpenAI-compatible.":"";return(0,l.jsx)("div",{className:"rounded-2xl border border-border/70 bg-background/80 p-4",children:(0,l.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,l.jsxs)("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-start xl:justify-between",children:[(0,l.jsxs)("div",{className:"min-w-0",children:[(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,l.jsx)(q1,{active:g.active}),(0,l.jsx)("div",{className:"text-sm font-medium text-foreground",children:g.label}),(0,l.jsx)(Tt,{variant:"outline",children:"GPT Search"})]}),(0,l.jsx)("div",{className:"mt-1 text-xs break-all text-muted-foreground",children:g.routeId}),(0,l.jsx)("div",{className:"mt-2 text-xs leading-5 text-muted-foreground",children:"Uses the provider's native OpenAI Responses web search tool. No local API key or quota is stored here."})]}),(0,l.jsxs)("div",{className:"flex items-center gap-2 self-start",children:[(0,l.jsxs)("div",{className:"flex items-center gap-2 rounded-xl border border-border/70 bg-background/70 p-1",children:[(0,l.jsx)(Ks,{disabled:!!c||g.displayIndex<=0,label:`Move ${g.routeId} up`,onClick:()=>o(g.id,"up")}),(0,l.jsx)(kd,{disabled:!!c||g.displayIndex>=g.displayCount-1,label:`Move ${g.routeId} down`,onClick:()=>o(g.id,"down")})]}),(0,l.jsx)(ce,{type:"button",size:"sm",variant:"ghost",onClick:()=>i(g.id),disabled:!!c,children:"Remove"})]})]}),h?(0,l.jsx)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900",children:h}):null]})},g.key)}let x=g.credentialField,y=String(g?.credentialValue||"").trim();return(0,l.jsx)("div",{className:"rounded-2xl border border-border/70 bg-background/80 p-4",children:(0,l.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,l.jsxs)("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-start xl:justify-between",children:[(0,l.jsx)("div",{className:"min-w-0",children:(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,l.jsx)(q1,{active:g.active}),(0,l.jsx)("div",{className:"text-sm font-medium text-foreground",children:g.label})]})}),(0,l.jsxs)("div",{className:"flex items-center gap-2 self-start rounded-xl border border-border/70 bg-background/70 p-1",children:[(0,l.jsx)(Ks,{disabled:!!c||g.displayIndex<=0,label:`Move ${g.label} up`,onClick:()=>o(g.id,"up")}),(0,l.jsx)(kd,{disabled:!!c||g.displayIndex>=g.displayCount-1,label:`Move ${g.label} down`,onClick:()=>o(g.id,"down")})]})]}),(0,l.jsxs)("div",{className:"grid gap-3 lg:grid-cols-[minmax(0,0.9fr)_minmax(0,1.35fr)]",children:[(0,l.jsx)(st,{label:g.credentialLabel,hint:g.credentialField==="url"?"Required to enable this backend.":"Required to enable this backend. Stored in router config.",stacked:!0,className:"gap-1",headerClassName:"min-h-0",hintClassName:"leading-4",children:(0,l.jsx)(jg,{type:g.credentialField==="url"?"text":"password",autoComplete:"off",value:y,placeholder:g.credentialPlaceholder,onValueChange:h=>a(g.id,x,h),disabled:!!c})}),(0,l.jsxs)("div",{className:"grid gap-3 sm:grid-cols-3",children:[(0,l.jsx)(st,{label:"Result per call",hint:"Empty keeps the default of 5.",stacked:!0,className:"gap-1",headerClassName:"min-h-0",hintClassName:"leading-4",children:(0,l.jsx)(Yg,{value:g.resultPerCallInput,placeholder:"Default: 5",allowEmptyCommit:!0,onValueChange:h=>a(g.id,"count",h),disabled:!!c})}),(0,l.jsx)(st,{label:"Monthly limit",hint:"0 keeps quotas self-managed.",stacked:!0,className:"gap-1",headerClassName:"min-h-0",hintClassName:"leading-4",children:(0,l.jsx)(Yg,{value:String(g.limit||0),onValueChange:h=>a(g.id,"limit",h),disabled:!!c})}),(0,l.jsx)(st,{label:"Synced remaining",hint:"Adjust after manual upstream sync.",stacked:!0,className:"gap-1",headerClassName:"min-h-0",hintClassName:"leading-4",children:(0,l.jsx)(Yg,{value:String(g.remaining||0),onValueChange:h=>a(g.id,"remaining",h),disabled:!!c})})]})]})]})},g.key)})})})]}),(0,l.jsx)(dL,{open:f,onClose:()=>d(!1),candidates:n,onTestAndAdd:s,disabledReason:c})]})}function lC({toolName:e,toolState:t,endpointUrl:n,routeOptions:r,connectionBusy:a,bindingBusy:o,onToggleRouting:i,onBindingChange:s,hasMasterKey:c,disabledReason:u,onOpenPrimaryPath:f,onOpenSecondaryPath:d,secondaryPathLabel:p="Backup file",secondaryPathIcon:m=(0,l.jsx)(EC,{className:"h-3 w-3"}),bindingFields:b=[],guideContent:g=null}){let x=t?.routedViaRouter===!0,y=String(t?.error||"").trim(),h=!!(c&&n&&!u&&!y),v=(0,E.useMemo)(()=>{let C=new Set(["__unset__"]);for(let T of b){for(let w of Array.isArray(T?.extraOptions)?T.extraOptions:[]){let R=String(w?.value||"").trim();R&&C.add(R)}for(let w of Array.isArray(T?.options)?T.options:[]){let R=String(w?.value||"").trim();R&&C.add(R)}}return b.filter(T=>T?.usesRouteOptions!==!1).map(T=>String(T?.value||"").trim()).filter(T=>T&&!C.has(T))},[b]),S=Fs(r,v);return(0,l.jsxs)(Xn,{children:[(0,l.jsxs)(jo,{className:"flex flex-col gap-3 p-4 pb-0 sm:flex-row sm:items-start sm:justify-between",children:[(0,l.jsxs)("div",{className:"space-y-2",children:[(0,l.jsx)(el,{className:"flex items-center gap-2",children:(0,l.jsx)("span",{children:`Use ${e} via LLM Router`})}),(0,l.jsx)(TC,{primaryLabel:"Config file",primaryValue:t?.configFilePath||t?.settingsFilePath||"",onOpenPrimary:f,secondaryLabel:p,secondaryValue:t?.backupFilePath||"",secondaryIcon:m,onOpenSecondary:d})]}),(0,l.jsxs)("div",{className:"flex shrink-0 flex-wrap items-center gap-2",children:[g?(0,l.jsx)(pL,{guideContent:g}):null,(0,l.jsx)(ce,{type:"button",size:"sm",variant:x?"outline":void 0,onClick:i,disabled:a!==""||!x&&!h,children:a==="enable"?"Connecting\u2026":a==="disable"?"Disconnecting\u2026":x?"Disconnect":"Connect"})]})]}),(0,l.jsxs)(Zn,{className:"space-y-4 p-4",children:[y?(0,l.jsx)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900",children:y}):null,!x&&!c?(0,l.jsxs)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800",children:["Set ",(0,l.jsx)("code",{children:"masterKey"})," first to connect ",e,"."]}):null,u?(0,l.jsx)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800",children:u}):null,(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/60 p-4",children:[(0,l.jsx)("div",{children:(0,l.jsxs)("div",{children:[(0,l.jsx)("div",{className:"text-sm font-medium text-foreground",children:"Model bindings"}),(0,l.jsx)("div",{className:"mt-1 text-xs text-muted-foreground",children:"Prefer LLM Router aliases here so you can retarget models later from the Alias & Fallback tab."})]})}),b.length===0?(0,l.jsx)("div",{className:"mt-4 rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800",children:"No tool bindings are available yet."}):(0,l.jsx)("div",{className:"mt-4 grid gap-3",children:b.map(C=>(0,l.jsxs)("div",{className:"rounded-xl border border-border/70 bg-background/80 p-3",children:[(0,l.jsxs)("div",{className:"mb-2 flex flex-wrap items-center justify-between gap-2",children:[(0,l.jsx)("div",{className:"text-sm font-medium text-foreground",children:C.label}),(0,l.jsx)(Tt,{variant:"outline",children:C.envKey})]}),(0,l.jsx)("div",{className:"mb-3 text-xs leading-5 text-muted-foreground",children:C.description}),(0,l.jsx)(gL,{field:C,routeOptions:S,disabled:C.standaloneWhenDisconnected?o:!x||o,onValueChange:T=>s(C.id,T==="__unset__"?"":T)})]},C.id))})]})]})]})}function mL(e="outline"){switch(e){case"success":return"border-emerald-200 bg-emerald-50";case"warning":return"border-amber-200 bg-amber-50";case"danger":return"border-rose-200 bg-rose-50";case"info":return"border-sky-200 bg-sky-50";default:return"border-border/70 bg-background/70"}}function sC(e="outline"){switch(e){case"success":return"text-emerald-950";case"warning":return"text-amber-950";case"danger":return"text-rose-950";case"info":return"text-sky-950";default:return"text-foreground"}}function pL({guideContent:e}){let[t,n]=(0,E.useState)(!1),r=String(e?.title||"").trim()||"Guide",a=String(e?.description||"").trim(),o=Array.isArray(e?.badges)?e.badges.filter(Boolean):[],i=Array.isArray(e?.highlights)?e.highlights.filter(Boolean):[],s=Array.isArray(e?.sections)?e.sections.filter(Boolean):[],c=e?.callout&&e.callout.body?e.callout:null,u=c?.variant||"outline";return i.length===0&&s.length===0&&!c?null:(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(ce,{type:"button",size:"sm",variant:"outline","aria-label":r,onClick:()=>n(!0),children:"Guide"}),(0,l.jsx)(Sa,{open:t,onClose:()=>n(!1),title:r,description:a,contentClassName:"max-h-[92vh] max-w-4xl rounded-2xl border border-border/70 bg-background/98 shadow-[0_32px_120px_rgba(15,23,42,0.48)]",bodyClassName:"max-h-[calc(92vh-5.5rem)]",children:(0,l.jsxs)("div",{className:"space-y-4",children:[o.length>0?(0,l.jsx)("div",{className:"flex flex-wrap items-center gap-2",children:o.map((f,d)=>(0,l.jsx)(Tt,{variant:f?.variant||"outline",children:f?.label},`${r}-badge-${d}`))}):null,c?(0,l.jsxs)("div",{className:W("rounded-2xl border p-4",mL(u)),children:[(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,l.jsx)(Tt,{variant:["success","warning","danger","info"].includes(u)?u:"outline",children:u==="success"?"Current best fit":u==="warning"?"Needs attention":u==="info"?"Current behavior":"Guide note"}),(0,l.jsx)("div",{className:W("text-sm font-medium",sC(u)),children:c.title})]}),(0,l.jsx)("div",{className:W("mt-3 text-sm leading-6",sC(u)),children:c.body})]}):null,i.length>0?(0,l.jsx)("div",{className:W("grid gap-4",i.length>2?"md:grid-cols-3":"md:grid-cols-2"),children:i.map((f,d)=>(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/70 p-4",children:[f?.eyebrow?(0,l.jsx)("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:f.eyebrow}):null,(0,l.jsx)("div",{className:"mt-2 text-sm font-medium text-foreground",children:f?.title}),(0,l.jsx)("div",{className:"mt-2 text-sm leading-6 text-muted-foreground",children:f?.body})]},`${r}-highlight-${d}`))}):null,s.map((f,d)=>{let p=Array.isArray(f?.items)?f.items.filter(Boolean):[];return(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/70 p-4",children:[(0,l.jsx)("div",{className:"text-sm font-medium text-foreground",children:f?.title}),f?.description?(0,l.jsx)("div",{className:"mt-2 text-sm leading-6 text-muted-foreground",children:f.description}):null,p.length>0?(0,l.jsx)("div",{className:"mt-3 space-y-3",children:p.map((m,b)=>(0,l.jsxs)("div",{className:"flex gap-3 text-sm leading-6 text-foreground",children:[(0,l.jsx)("span",{className:"mt-2 h-1.5 w-1.5 shrink-0 rounded-full bg-foreground/50"}),(0,l.jsx)("div",{className:"min-w-0",children:m})]},`${r}-section-${d}-item-${b}`))}):null]},`${r}-section-${d}`)})]})})]})}function gL({field:e,routeOptions:t,disabled:n=!1,onValueChange:r}){let a=String(e?.value||"").trim()||(e?.allowUnset?"__unset__":""),o=(0,E.useMemo)(()=>{let i=e?.usesRouteOptions===!1?[]:t,s=Array.isArray(e?.options)?e.options:[],c=Array.isArray(e?.extraOptions)?e.extraOptions:[];return e?.allowUnset?[{value:"__unset__",label:"Inherit tool default",hint:""},...c,...s,...i]:[...c,...s,...i]},[e?.allowUnset,e?.extraOptions,e?.options,e?.usesRouteOptions,t]);return(0,l.jsxs)(vr,{value:a,onValueChange:r,disabled:n||o.length===0,children:[(0,l.jsx)(br,{children:(0,l.jsx)(xr,{placeholder:e.placeholder||"Select a route"})}),(0,l.jsx)(Sr,{children:o.length>0?Bd(o,{keyPrefix:e.id||"binding-option"}):(0,l.jsx)(ar,{value:"__no-route-options",disabled:!0,children:"No routes available"})})]})}function hL({logs:e,activityLogEnabled:t=!0,activityFilter:n="usage",busyAction:r="",onActivityFilterChange:a,onToggleEnabled:o,onClear:i}){let s=Array.isArray(e)?e:[],c=s.filter(f=>n==="all"?!0:V1(f)===n),u=Ad[n]||Ad.usage;return(0,l.jsxs)(Xn,{children:[(0,l.jsx)(jo,{children:(0,l.jsxs)("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[(0,l.jsxs)("div",{className:"space-y-1",children:[(0,l.jsx)(el,{children:"Activity"}),(0,l.jsx)(Ss,{children:t?"Router actions, request fallbacks, and runtime issues stream here.":"Activity logging is paused. Re-enable it to capture router actions, request fallbacks, and runtime issues."})]}),(0,l.jsxs)("div",{className:"flex shrink-0 flex-wrap items-center gap-2",children:[(0,l.jsx)("div",{className:"min-w-[13rem]",children:(0,l.jsxs)(vr,{value:n,onValueChange:a,searchEnabled:!1,children:[(0,l.jsx)(br,{children:(0,l.jsx)(xr,{placeholder:"Filter category"})}),(0,l.jsx)(Sr,{children:yk.map(f=>(0,l.jsx)(ar,{value:f.value,children:f.label},f.value))})]})}),(0,l.jsx)(ce,{type:"button",size:"sm",variant:"outline",onClick:i,disabled:r!==""||!e?.length,children:r==="clear"?"Clearing\u2026":"Clear log"}),(0,l.jsx)(ce,{type:"button",size:"sm",variant:t?"outline":"default",onClick:o,disabled:r!=="",children:r==="toggle"?"Updating\u2026":t?"Disable log":"Enable log"})]})]})}),(0,l.jsx)(Zn,{children:(0,l.jsx)("div",{className:"max-h-[32rem] space-y-3 overflow-auto pr-1",children:c.length?c.map(f=>{let d=V1(f),p=Ad[d]||Ad.usage;return(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/80 px-4 py-3",children:[(0,l.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,l.jsxs)("div",{className:"flex items-center gap-2",children:[(0,l.jsx)("span",{className:W("inline-flex h-2.5 w-2.5 rounded-full ring-4",I1[f.level]||I1.info)}),(0,l.jsx)(Tt,{variant:p.badgeVariant,children:p.label}),(0,l.jsx)("span",{className:"text-sm font-medium text-foreground",children:f.message})]}),(0,l.jsx)("span",{className:"text-xs text-muted-foreground",children:vh(f.time)})]}),f.detail?(0,l.jsx)("div",{className:"mt-2 text-sm leading-6 text-muted-foreground",children:f.detail}):null]},f.id)}):s.length?(0,l.jsxs)("div",{className:"rounded-2xl border border-dashed border-border px-4 py-6 text-sm text-muted-foreground",children:["No ",u.emptyLabel," activity matches the current filter. Switch the dropdown to inspect the hidden categories."]}):(0,l.jsx)("div",{className:"rounded-2xl border border-dashed border-border px-4 py-6 text-sm text-muted-foreground",children:"Activity is quiet. Save config changes or start the router to populate this stream."})})})]})}function ah({values:e,onChange:t,placeholder:n,helperText:r,inputRef:a=null,inputClassName:o="",suggestedValues:i=[],valueStates:s={},draftValue:c="",onDraftValueChange:u=()=>{},commitOnBlur:f=!1,disabled:d=!1,isValueValid:p=m=>!!String(m||"").trim()}){let m=(0,E.useMemo)(()=>ba(e),[e]),[b,g]=(0,E.useState)(""),[x,y]=(0,E.useState)("");function h(w=c,{clearDraft:R=!0}={}){if(d)return!1;let M=Xg(w).filter(I=>p(I));if(M.length===0)return R&&u(""),!1;let k=Array.from(new Set([...m||[],...M]));return JSON.stringify(k)!==JSON.stringify(m||[])&&t(k),R&&u(""),!0}function v(w){d||(t(m.filter(R=>R!==w)),b===w&&(g(""),y("")))}function S(){d||i.length&&(t(Array.from(new Set([...m||[],...i]))),u(""))}function C(w){d||(g(w),y(w))}function T(w=x){if(d)return g(""),y(""),!1;if(!b)return!1;let R=Xg(w).filter(H=>p(H)),M=[],k=!1;for(let H of m||[]){if(H!==b){M.push(H);continue}k||(M.push(...R),k=!0)}let I=Array.from(new Set(M.map(H=>String(H||"").trim()).filter(Boolean)));return JSON.stringify(I)!==JSON.stringify(m||[])&&t(I),g(""),y(""),R.length>0}return(0,E.useEffect)(()=>{!d||!b||(g(""),y(""))},[d,b]),(0,l.jsxs)("div",{className:"space-y-2",children:[(0,l.jsxs)("div",{className:W("flex min-h-11 flex-wrap items-center gap-2 rounded-xl border border-input bg-background/80 px-3 py-2",d?"opacity-80":null),children:[m.map(w=>{let R=s?.[w]||"default",M=R==="success"?"border-emerald-200 bg-emerald-50 text-emerald-900":R==="error"?"border-rose-200 bg-rose-50 text-rose-900":R==="pending"?"border-sky-200 bg-sky-50 text-sky-900":"border-border bg-secondary text-foreground",k=!d&&b===w;return(0,l.jsxs)("span",{className:W("inline-flex max-w-full items-center gap-1 rounded-full border px-2.5 py-1 text-xs",M),children:[k?(0,l.jsx)("input",{autoFocus:!0,className:"min-w-[7rem] bg-transparent text-xs text-foreground outline-none",value:x,onChange:I=>y(I.target.value),onKeyDown:I=>{if(I.key==="Enter"||I.key==="Tab"){I.preventDefault(),T();return}I.key==="Escape"&&(I.preventDefault(),g(""),y(""))},onBlur:()=>{T()}}):(0,l.jsx)("button",{className:"max-w-[16rem] truncate text-left transition hover:text-foreground disabled:cursor-not-allowed disabled:opacity-70",type:"button",onMouseDown:I=>I.preventDefault(),onClick:()=>C(w),disabled:d,title:"Click to edit",children:w}),(0,l.jsx)("button",{className:"text-muted-foreground transition hover:text-foreground disabled:cursor-not-allowed disabled:opacity-60",type:"button",onMouseDown:I=>I.preventDefault(),onClick:()=>v(w),disabled:d,children:"\xD7"})]},w)}),(0,l.jsx)("input",{ref:a,className:W("min-w-[10rem] flex-1 bg-transparent text-sm text-foreground outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-70",o),value:c,disabled:d,onChange:w=>{let R=w.target.value;if(/[\s,]/.test(R)){let M=R.split(/[\s,]+/),k=M.pop()||"";M.length>0&&h(M.join(","),{clearDraft:!1}),u(k);return}u(R)},onKeyDown:w=>{if((w.key===","||w.key===" "||w.key==="Enter"||w.key==="Tab")&&c.trim()){w.preventDefault(),h();return}w.key==="Backspace"&&!c&&m.length>0&&(w.preventDefault(),v(m[m.length-1]))},onPaste:w=>{let R=w.clipboardData?.getData("text")||"";if(/[\s,]/.test(R)){w.preventDefault();let M=R.split(/[\s,]+/).filter(Boolean).filter(k=>p(k));M.length>0&&(t(Array.from(new Set([...m||[],...M]))),u(""));return}w.preventDefault(),u(`${c}${R}`)},onBlur:()=>{if(f&&p(c)){h(c);return}u(c)},placeholder:n}),m.length>0||c?(0,l.jsx)("button",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground transition hover:text-foreground disabled:cursor-not-allowed disabled:opacity-60",type:"button",onMouseDown:w=>w.preventDefault(),onClick:()=>{t([]),u("")},disabled:d,children:"Clear all"}):null]}),(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[r?(0,l.jsx)("span",{children:r}):null,m.length===0&&i.length>0?(0,l.jsx)("button",{className:"font-medium uppercase tracking-[0.16em] text-foreground transition hover:text-primary disabled:cursor-not-allowed disabled:opacity-60",type:"button",onClick:S,disabled:d,children:"Use suggested values"}):null]})]})}function NC(e="rate-limit-draft-row"){return hC({key:e,models:[],requests:"",windowValue:"",windowUnit:ml.api.windowUnit},{keyPrefix:"rate-limit-draft",defaults:ml.api,useDefaults:!1})}function MC(e=[],{keyPrefix:t="rate-limit-draft"}={}){let n=`${t}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;return[...Array.isArray(e)?e:[],NC(n)]}function yL({value:e=[],onChange:t,availableModelIds:n=[],disabled:r=!1}){let a=(0,E.useRef)(null),[o,i]=(0,E.useState)(!1),s=(0,E.useMemo)(()=>Ir(e),[e]),c=s.includes("all"),u=c?[]:s.filter(Boolean),f=c||u.length===0,d=(0,E.useMemo)(()=>ba(n),[n]);(0,E.useEffect)(()=>{if(!o||typeof document>"u")return;function y(h){a.current?.contains(h.target)||i(!1)}return document.addEventListener("mousedown",y),()=>document.removeEventListener("mousedown",y)},[o]);function p(y){t(Ir(y))}function m(y){p(y?["all"]:[])}function b(y,h){let v=h?[...u,y]:u.filter(S=>S!==y);p(v)}function g(y){if(y==="all"){p([]);return}p(u.filter(h=>h!==y))}let x=c?[{key:"all",label:"All model",removable:!0}]:u.length>0?u.map(y=>({key:y,label:y,removable:!0})):[{key:"__implicit-all__",label:"All model",removable:!1,muted:!0}];return(0,l.jsxs)("div",{ref:a,className:"relative space-y-1.5",children:[(0,l.jsxs)("div",{role:"button",tabIndex:r?-1:0,className:W("flex min-h-9 w-full items-center justify-between gap-2 rounded-lg border border-input bg-background/80 px-3 py-1.5 text-left text-sm text-foreground shadow-sm outline-none transition focus:border-ring focus:ring-2 focus:ring-ring/40",r?"cursor-not-allowed opacity-50":"cursor-pointer",o?"border-ring ring-2 ring-ring/40":null),onClick:()=>{r||i(y=>!y)},"aria-expanded":o,"aria-haspopup":"menu",onKeyDown:y=>{if(!r){if(y.key==="Enter"||y.key===" "){y.preventDefault(),i(h=>!h);return}if(y.key==="ArrowDown"){y.preventDefault(),i(!0);return}y.key==="Escape"&&(y.preventDefault(),i(!1))}},children:[(0,l.jsx)("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-1.5",children:x.map(y=>y.removable?(0,l.jsxs)("button",{type:"button",className:"inline-flex max-w-full items-center gap-1 rounded-full border border-border/70 bg-background px-2 py-0.5 text-xs font-medium text-foreground transition hover:border-accent hover:bg-accent",onClick:h=>{h.preventDefault(),h.stopPropagation(),g(y.key)},disabled:r,title:`Remove ${y.label}`,children:[(0,l.jsx)("span",{className:"truncate",children:y.label}),(0,l.jsx)("span",{className:"text-muted-foreground",children:"x"})]},y.key):(0,l.jsx)("span",{className:W("inline-flex max-w-full items-center rounded-full border px-2 py-0.5 text-xs font-medium",y.muted?"border-border/70 bg-secondary/45 text-muted-foreground":"border-border/70 bg-background text-foreground"),children:(0,l.jsx)("span",{className:"truncate",children:y.label})},y.key))}),(0,l.jsx)("span",{className:"text-muted-foreground",children:"\u25BE"})]}),o?(0,l.jsxs)(RC,{open:o,anchorRef:a,preferredSide:"top",desiredHeight:192,className:"p-2",onMouseDown:y=>y.stopPropagation(),onClick:y=>y.stopPropagation(),onKeyDown:y=>{y.key==="Escape"&&(y.preventDefault(),i(!1))},children:[(0,l.jsxs)("label",{className:"flex cursor-pointer items-center gap-2 rounded-lg px-2 py-2 text-sm text-foreground transition hover:bg-secondary/60",children:[(0,l.jsx)("input",{type:"checkbox",className:"h-4 w-4 rounded border-input",checked:c,onChange:y=>m(y.target.checked)}),(0,l.jsx)("span",{children:"All model"})]}),(0,l.jsx)("div",{className:"my-1 border-t border-border/70"}),d.length>0?(0,l.jsx)("div",{children:d.map(y=>(0,l.jsxs)("label",{className:"flex cursor-pointer items-center gap-2 rounded-lg px-2 py-2 text-sm text-foreground transition hover:bg-secondary/60",children:[(0,l.jsx)("input",{type:"checkbox",className:"h-4 w-4 rounded border-input",checked:u.includes(y),onChange:h=>b(y,h.target.checked)}),(0,l.jsx)("span",{className:"truncate",children:y})]},y))}):(0,l.jsx)("div",{className:"px-2 py-2 text-sm text-muted-foreground",children:"No models available yet."})]}):null]})}function OC({rows:e,onChange:t,availableModelIds:n=[],disabled:r=!1,inputRef:a=null,helperText:o="",onValidBlur:i=null}){let s=Array.isArray(e)?e:[],c=(0,E.useRef)(null),u=(0,E.useRef)(s),f=(0,E.useMemo)(()=>ba(n),[n]),d=(0,E.useMemo)(()=>{let h=new Set,v=new Set;for(let S of xa(s)){let C=zs(S);if(C){if(h.has(C)){v.add(C);continue}h.add(C)}}return v},[s]),p=(0,E.useMemo)(()=>s.map(h=>({...NC(h.key),...h,models:Ir(h?.models||[])})),[s]);(0,E.useEffect)(()=>{u.current=s},[s]);function m(h){let v=Array.isArray(h)?h:[];u.current=v,t(v)}function b(h,v){m(s.map(S=>S.key===h?{...S,...v}:S))}function g(h){m(s.filter(v=>v.key!==h))}function x(h){if(Jg(h))return"";let v=Ir(h?.models||[]);if(f.length>0&&v.some(C=>C!=="all"&&!f.includes(C)))return"Use exact provider model ids only.";if($1(h?.requests,0)<=0)return"Requests must be a positive integer.";if($1(h?.windowValue,0)<=0)return"Window size must be a positive integer.";if(!U1.includes(String(h?.windowUnit||"").trim()))return"Window unit is invalid.";let S=zs({requests:h?.requests,windowValue:h?.windowValue,windowUnit:h?.windowUnit});return S&&d.has(S)?"Another row already uses this cap.":""}function y(h){if(!(!i||r)&&!h.currentTarget.contains(h.relatedTarget)){if(typeof window>"u"){let v=xa(u.current);ti(v,{knownModelIds:f,requireAtLeastOne:!0})||i(v);return}window.setTimeout(()=>{if(!c.current||c.current.contains(document.activeElement))return;let v=xa(u.current);ti(v,{knownModelIds:f,requireAtLeastOne:!0})||i(v)},0)}}return(0,l.jsxs)("div",{ref:c,className:"space-y-2.5",onBlurCapture:y,children:[(0,l.jsx)("div",{className:"space-y-2.5",children:p.map((h,v)=>{let S=Jg(h),C=x(h);return(0,l.jsxs)("div",{className:W("rounded-2xl border border-border/70 bg-background/70 p-3",C?"border-amber-200 bg-amber-50/70":null,S?"border-dashed bg-background/80":null),children:[(0,l.jsxs)("div",{className:"grid gap-2.5 xl:grid-cols-[minmax(0,1.5fr)_minmax(0,0.72fr)_minmax(0,0.72fr)_minmax(0,0.86fr)_auto] xl:items-end",children:[(0,l.jsx)(st,{label:"Models",stacked:!0,className:"gap-1",headerClassName:"min-h-0",hintClassName:"leading-4",children:(0,l.jsx)(yL,{value:h.models,onChange:T=>b(h.key,{models:T}),availableModelIds:f,disabled:r})}),(0,l.jsx)(st,{label:"Request",stacked:!0,className:"gap-1",headerClassName:"min-h-0",children:(0,l.jsx)(Dt,{ref:v===0?a:null,value:h.requests,onChange:T=>b(h.key,{requests:T.target.value}),disabled:r,inputMode:"numeric",placeholder:"60"})}),(0,l.jsx)(st,{label:"Window",stacked:!0,className:"gap-1",headerClassName:"min-h-0",children:(0,l.jsx)(Dt,{value:h.windowValue,onChange:T=>b(h.key,{windowValue:T.target.value}),disabled:r,inputMode:"numeric",placeholder:"1"})}),(0,l.jsx)(st,{label:"Unit",stacked:!0,className:"gap-1",headerClassName:"min-h-0",children:(0,l.jsxs)(vr,{value:String(h.windowUnit||"minute"),onValueChange:T=>b(h.key,{windowUnit:T}),disabled:r,children:[(0,l.jsx)(br,{children:(0,l.jsx)(xr,{placeholder:"Window unit"})}),(0,l.jsx)(Sr,{children:U1.map(T=>(0,l.jsx)(ar,{value:T,children:T},`${h.key}-${T}`))})]})}),(0,l.jsx)(ce,{type:"button",variant:"ghost",onClick:()=>g(h.key),disabled:r,className:"xl:self-end",children:"Remove"})]}),C?(0,l.jsx)("div",{className:"mt-2.5 rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900",children:C}):null]},h.key)})}),o?(0,l.jsx)("div",{className:"text-xs leading-5 text-muted-foreground",children:o}):null]})}function vL({rows:e,onChange:t}){let n=mh(e),r=n.length>0?n:[{name:"",value:""}];function a(s,c,u){c==="name"&&Bk(r,u,s)||t(r.map((f,d)=>d===s?{...f,[c]:u}:f))}function o(){t([...r,{name:"",value:""}])}function i(s){let c=r.filter((u,f)=>f!==s);t(c.length>0?c:[{name:"",value:""}])}return(0,l.jsxs)("div",{className:"space-y-2",children:[r.map((s,c)=>(0,l.jsxs)("div",{className:"grid gap-2 md:grid-cols-[minmax(0,0.9fr)_minmax(0,1.3fr)_auto]",children:[(0,l.jsx)(Dt,{value:s.name,onChange:u=>a(c,"name",u.target.value),placeholder:c===0?"User-Agent":"Header name"}),(0,l.jsx)(Dt,{value:s.value,onChange:u=>a(c,"value",u.target.value),placeholder:c===0?ni:"Header value"}),(0,l.jsx)(ce,{type:"button",variant:"ghost",onClick:()=>i(c),children:"Remove"})]},`header-row-${c}`)),(0,l.jsxs)("div",{className:"flex items-center justify-between gap-3 text-xs text-muted-foreground",children:[(0,l.jsx)("span",{children:"User-Agent is included by default. Add more only when a provider needs them."}),(0,l.jsx)(ce,{type:"button",variant:"outline",onClick:o,children:"Add custom header"})]})]})}function co(){return(0,l.jsx)("span",{className:"mr-2 inline-flex h-3.5 w-3.5 animate-spin rounded-full border-2 border-current border-r-transparent align-[-0.125em]"})}function bL({providerId:e,values:t,onChange:n}){let r=(t||[]).map(d=>String(d||"").trim()).filter(Boolean),a=sh(r),o=(0,E.useRef)(""),i=(0,E.useRef)(null);function s(d){n((t||[]).filter(p=>p!==d))}function c(d,p){if(!d||!p||d===p)return;let m=[...t||[]],b=m.indexOf(d),g=m.indexOf(p);if(b===-1||g===-1)return;let[x]=m.splice(b,1);m.splice(g,0,x),n(m)}function u(d){n(ih(t||[],d,p=>String(p||"").trim()))}function f(){o.current="",pl(i.current,!1),i.current=null}return(0,l.jsxs)("div",{className:"space-y-2",children:[(0,l.jsx)("div",{className:"space-y-2 rounded-xl border border-input bg-background/80 px-3 py-3",children:r.length>0?r.map((d,p)=>(0,l.jsxs)("div",{ref:a(d),"data-reorder-row":"true",onDragOver:m=>{o.current&&o.current!==d&&(m.preventDefault(),m.dataTransfer.dropEffect="move")},onDrop:m=>{m.preventDefault();let b=m.dataTransfer.getData("text/plain")||o.current;f(),c(b,d)},className:W("grid grid-cols-[auto_auto_minmax(0,1fr)_auto] items-center gap-2 rounded-xl border border-border/70 bg-card/90 p-3"),children:[(0,l.jsx)("span",{className:"flex h-8 w-8 cursor-grab items-center justify-center rounded-full text-muted-foreground",draggable:!0,onDragStart:m=>{let b=lh(m.currentTarget);m.dataTransfer.effectAllowed="move",m.dataTransfer.setData("text/plain",d),b&&typeof m.dataTransfer?.setDragImage=="function"&&m.dataTransfer.setDragImage(b,20,20),f(),o.current=d,i.current=b,pl(b,!0)},onDragEnd:f,title:"Drag to reorder",children:(0,l.jsx)(ch,{className:"h-4 w-4"})}),(0,l.jsx)(Ks,{disabled:p===0,label:p===0?"Already first":`Move ${e}/${d} up`,onClick:()=>u(d)}),(0,l.jsxs)("span",{className:"truncate text-sm font-medium text-foreground",children:[e,"/",d]}),(0,l.jsx)("button",{className:"text-muted-foreground transition hover:text-foreground",type:"button",onMouseDown:m=>m.preventDefault(),onClick:()=>s(d),children:"\xD7"})]},d)):(0,l.jsxs)("span",{className:"block px-1 text-xs text-muted-foreground",children:["Leave it empty for now, or add models to back the fixed ",(0,l.jsx)("code",{children:"default"})," route. An empty default route returns 500 until you add a working model."]})}),(0,l.jsx)("div",{className:"text-xs text-muted-foreground",children:"Drag rows to change the preferred order, use the arrow to move a model earlier, or remove any models you do not want in this route."})]})}function cC({baseConfig:e,onApplyDraft:t,onValidateDraft:n,onSaveDraft:r,onSaveAndStart:a,seedMode:o="blank",mode:i="add",targetProviderId:s="",defaultProviderUserAgent:c=ni,framed:u=!0,showHeader:f=!0}){let[d,p]=(0,E.useState)(0),[m,b]=(0,E.useState)(""),[g,x]=(0,E.useState)(()=>T2(e,{seedMode:o,targetProviderId:s,defaultProviderUserAgent:c})),[y,h]=(0,E.useState)(null),[v,S]=(0,E.useState)(""),[C,T]=(0,E.useState)({}),[w,R]=(0,E.useState)(null),[M,k]=(0,E.useState)(""),[I,H]=(0,E.useState)(!1),[Q,ee]=(0,E.useState)(""),X=(0,E.useRef)(""),z=i==="edit",te=!z&&o==="blank"&&AC(e),Y=[{title:"Provider",detail:"Choose API Key or OAuth first, then enter the provider details needed for that connection type."},{title:"Models",detail:"Add model ids, then configure one or more rate limits for all models or selected models. API Key providers are tested before continue."},{title:"Default",detail:"Order the models behind the fixed `default` route before you finish."}],q=Hr(g.modelIds,g.modelDraft),V=yh(g.aliasModelIds,q),_e=g.connectionType==="api"?Hr(g.endpoints,g.endpointDraft):[],F=(0,E.useMemo)(()=>({...g,endpoints:_e,modelIds:q,aliasModelIds:V,rateLimitRows:xa(g.rateLimitRows)}),[g,_e,q,V]),he=(0,E.useMemo)(()=>ph(g.headerRows||[]),[g.headerRows]),Z=String(g.apiKeyEnv||"").trim(),ae=(0,E.useMemo)(()=>G1(F),[F]),Se=w?.signature===ae?w.result:null,U=Se?.models?.length>0?Se.models:SC(g.connectionType),ne=Vr(g.providerId||g.providerName||"my-provider")||"my-provider",ue=wC(g),me=JSON.stringify({connectionType:g.connectionType,subscriptionProfile:ue}),re=JSON.stringify({apiConnectionSignature:ae,modelIds:q}),oe=y?.signature===re?y.result:null,Ne=g.connectionType!=="api"||!!oe?.ok,Re=(0,E.useMemo)(()=>N2(e,F,oe,{targetProviderId:s}),[e,F,oe,s]),Ze=(0,E.useMemo)(()=>`${JSON.stringify(Re,null,2)}
51
+ `)}if(f)break}let c=i.trim();if(c){let u=JSON.parse(c);if(n?.(u),u?.type==="result"&&(s=u.result),u?.type==="error"){let f=new Error(u.error||"Request failed.");throw f.statusCode=u.statusCode||500,f}}return s}function tC(e={}){return`${String(e?.model||"").trim()}::${String(e?.contextWindow||"").trim()}`}function _2(e){return String(e||"").trim().replace(/[.,\s_'`]/g,"")}function so(e){let t=_2(e);if(!t)return"";let n=Number.parseInt(t,10);return Number.isFinite(n)&&n>0?String(n):t}async function th(e=[]){let t=[...new Set((Array.isArray(e)?e:[]).map(r=>String(r||"").trim()).filter(Boolean))];if(t.length===0)return[];let n=await Nt("/api/config/litellm-context-lookup",{method:"POST",headers:Ct,body:JSON.stringify({models:t,limit:wk})});return Array.isArray(n?.result)?n.result:[]}function nC(e={}){let t=String(e?.model||"").trim(),n=String(e?.provider||"").trim(),r=String(e?.mode||"").trim(),a=Number(e?.contextWindow);return!Number.isFinite(a)||a<=0?null:{model:t,provider:n,mode:r,contextWindow:Math.floor(a)}}function rC(e="",t=""){let n=String(e||"").trim(),r=String(t||"").trim();if(!n||!r)return n;let a=n.toLowerCase(),o=r.toLowerCase(),i=[`${o}/`,`${o}:`];for(let s of i){if(!a.startsWith(s))continue;return n.slice(s.length).trim()||n}return n}function qs(e={},{fallbackQuery:t=""}={}){let n=String(e?.query||t||"").trim(),r=nC(e?.exactMatch),a=(Array.isArray(e?.suggestions)?e.suggestions:[]).map(f=>nC(f)).filter(Boolean),o=Number(e?.medianContextWindow),i=Number.isFinite(o)&&o>0?Math.floor(o):r?.contextWindow||null,s=[],c=new Set;function u(f){!f?.key||c.has(f.key)||(c.add(f.key),s.push(f))}r&&u({key:`exact::${tC(r)}`,label:rC(r.model,r.provider)||"Exact match",detail:r.provider?`Exact \xB7 ${r.provider}`:"Exact",contextWindow:r.contextWindow});for(let f of a)u({key:tC(f),label:rC(f.model,f.provider)||"Suggestion",detail:f.provider||"Known model",contextWindow:f.contextWindow});return{query:n,exactMatch:r,suggestions:a,medianContextWindow:i,options:s,status:s.length>0?"ready":"miss"}}function nh(e={}){let t=qs(e);return t.exactMatch?.contextWindow?String(t.exactMatch.contextWindow):t.medianContextWindow?String(t.medianContextWindow):""}function k2(e=[]){let t=new Map;for(let n of Array.isArray(e)?e:[]){let r=qs(n);r.query&&t.set(r.query,r)}return t}function L2(e=[]){let t={};for(let n of Array.isArray(e)?e:[]){let r=String(n?.query||"").trim(),a=nh(n);!r||!a||(t[r]=Number(a))}return t}function st({label:e,hint:t,className:n,children:r,stacked:a=!1,headerClassName:o,hintClassName:i,headerAction:s=null}){return(0,l.jsxs)("div",{className:W("flex flex-col gap-2 text-sm",n),children:[(0,l.jsxs)("div",{className:W("text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",a?"flex min-h-10 items-start justify-between gap-3":"flex items-center justify-between gap-2",o),children:[(0,l.jsxs)("div",{className:W("min-w-0",a?"flex-1 space-y-1":"flex min-w-0 items-center gap-2"),children:[(0,l.jsx)("span",{children:e}),t?(0,l.jsx)("span",{className:W("block normal-case tracking-normal text-[11px] text-muted-foreground/80",a?"leading-4":null,i),children:t}):null]}),s?(0,l.jsx)("div",{className:"shrink-0",children:s}):null]}),r]})}function Yg({value:e,onValueChange:t,disabled:n=!1,allowEmptyCommit:r=!1,...a}){let o=String(e??""),[i,s]=(0,E.useState)(o);return(0,E.useEffect)(()=>{s(o)},[o]),(0,l.jsx)(Dt,{...a,value:i,inputMode:"numeric",disabled:n,onChange:c=>{let u=z1(c.target.value);u.accepted&&(s(u.draftValue),u.shouldCommit?t(u.commitValue):r&&u.draftValue===""&&t(""))},onBlur:()=>{s(c=>c!==""?c:r?(t(""),""):o)}})}function D2({label:e,hint:t,checked:n=!1,onCheckedChange:r,disabled:a=!1,className:o}){return(0,l.jsxs)("div",{className:W("flex items-center justify-between gap-4 rounded-2xl border border-border/70 bg-background/80 px-4 py-3",o),children:[(0,l.jsxs)("div",{className:"min-w-0",children:[(0,l.jsx)("div",{className:"text-sm font-medium text-foreground",children:e}),t?(0,l.jsx)("div",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:t}):null]}),(0,l.jsx)(fS,{checked:n,onCheckedChange:r,disabled:a,className:"data-[disabled]:cursor-not-allowed data-[disabled]:opacity-60"})]})}function Sa({open:e=!1,title:t="",description:n="",onClose:r=()=>{},children:a,variant:o="dialog",headerActions:i=null,showCloseButton:s=!0,closeDisabled:c=!1,closeOnEscape:u=!0,closeOnBackdrop:f=!0,footer:d=null,contentClassName:p="",bodyClassName:m="",footerClassName:b=""}){if((0,E.useEffect)(()=>{if(!e||typeof window>"u")return;function y(h){h.key==="Escape"&&u&&r()}return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[u,e,r]),!e)return null;let g=o==="page",x=(0,l.jsx)("div",{className:W("fixed inset-0 z-50 bg-slate-950/55 backdrop-blur-sm",g?"p-0":"flex items-center justify-center p-4"),onMouseDown:y=>{y.target===y.currentTarget&&f&&r()},children:(0,l.jsxs)("div",{className:W("overflow-hidden border border-border/70 bg-card/95 shadow-2xl",g?"flex h-full w-full flex-col rounded-none border-x-0 border-y-0 bg-background/98":"flex max-h-[85vh] w-full max-w-3xl flex-col rounded-3xl",p),children:[(0,l.jsxs)("div",{className:W("flex items-start justify-between gap-3 border-b border-border/70",g?"px-5 py-4 sm:px-6":"px-5 py-4"),children:[(0,l.jsxs)("div",{className:"min-w-0",children:[(0,l.jsx)("div",{className:"text-base font-semibold text-foreground",children:t}),n?(0,l.jsx)("div",{className:"mt-1 text-sm leading-6 text-muted-foreground",children:n}):null]}),(0,l.jsxs)("div",{className:"flex shrink-0 items-center gap-2",children:[i,s?(0,l.jsx)(ce,{type:"button",variant:"ghost",size:"sm",onClick:r,disabled:c,children:"Close"}):null]})]}),(0,l.jsx)("div",{className:W("overflow-y-auto",g?"min-h-0 flex-1 px-5 py-4 sm:px-6 sm:py-5":"min-h-0 flex-1 px-5 py-4",m),children:a}),d?(0,l.jsx)("div",{className:W("border-t border-border/70 bg-background/96",g?"px-5 py-4 sm:px-6":"px-5 py-4",b),children:d}):null]})});return typeof document>"u"||!document.body?x:(0,uC.createPortal)(x,document.body)}function RC({open:e=!1,anchorRef:t,preferredSide:n="bottom",desiredHeight:r=288,offset:a=4,className:o="",children:i,...s}){let c=yd({open:e,anchorRef:t,preferredSide:n,desiredHeight:r,offset:a});return e?(0,l.jsx)("div",{className:W("absolute left-0 right-0 z-30 overflow-y-auto rounded-xl border border-border/70 bg-popover shadow-lg",c.side==="top"?"bottom-full mb-1":"top-full mt-1",o),style:{maxHeight:`${Math.max(0,Math.floor(c.maxHeight||r))}px`},...s,children:i}):null}function z2({open:e=!1,onKeepEditing:t=()=>{},onDiscardAndClose:n=()=>{},onSaveAndClose:r=()=>{},saveDisabled:a=!1,dirtyLabels:o=[],details:i=""}){let s=o.length>1?`${o.slice(0,-1).join(", ")} and ${o[o.length-1]}`:o[0]||"this form";return(0,l.jsx)(Sa,{open:e,onClose:t,title:"Unsaved changes",description:`You have unsaved edits in ${s}.`,contentClassName:"max-w-lg rounded-2xl border border-border/70 bg-background/98 shadow-[0_32px_120px_rgba(15,23,42,0.48)]",showCloseButton:!1,footer:(0,l.jsxs)("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[(0,l.jsx)(ce,{type:"button",variant:"ghost",onClick:t,children:"Keep editing"}),(0,l.jsx)(ce,{type:"button",variant:"outline",onClick:n,children:"Cancel + Close"}),(0,l.jsx)(ce,{type:"button",onClick:()=>{r()},disabled:a,children:"Save + Close"})]}),children:(0,l.jsxs)("div",{className:"space-y-3 text-sm leading-6 text-muted-foreground",children:[(0,l.jsx)("div",{children:"Choose whether to save these edits before closing the modal."}),i?(0,l.jsx)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-amber-900",children:i}):null]})})}function B2({open:e=!1,failedModelIds:t=[],onKeepEditing:n=()=>{},onRemoveFailedAndClose:r=()=>{},removeDisabled:a=!1}){let o=t.length>1?`${t.length} failed models`:t[0]||"the failed model";return(0,l.jsx)(Sa,{open:e,onClose:n,title:"Failed model tests",description:`Some new models did not pass validation: ${o}.`,contentClassName:"max-w-lg rounded-2xl border border-border/70 bg-background/98 shadow-[0_32px_120px_rgba(15,23,42,0.48)]",showCloseButton:!1,footer:(0,l.jsxs)("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[(0,l.jsx)(ce,{type:"button",variant:"ghost",onClick:n,children:"Keep editing"}),(0,l.jsx)(ce,{type:"button",variant:"outline",onClick:()=>{r()},disabled:a,children:"Remove failed + close"})]}),children:(0,l.jsxs)("div",{className:"space-y-3 text-sm leading-6 text-muted-foreground",children:[(0,l.jsx)("div",{children:"Successful new models are still kept in the draft. You can continue editing, or remove only the failed rows and close the modal."}),t.length>0?(0,l.jsx)("div",{className:"rounded-xl border border-rose-200 bg-rose-50 px-3 py-2 text-rose-900",children:t.join(", ")}):null]})})}function Nd({className:e=""}){return(0,l.jsxs)("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",className:e,"aria-hidden":"true",children:[(0,l.jsx)("path",{d:"M12 20h9"}),(0,l.jsx)("path",{d:"M16.5 3.5a2.121 2.121 0 1 1 3 3L7 19l-4 1 1-4 12.5-12.5Z"})]})}function I2({className:e=""}){return(0,l.jsx)("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:e,"aria-hidden":"true",children:(0,l.jsx)("path",{d:"m5 12 4.25 4.25L19 6.5"})})}function rh({className:e=""}){return(0,l.jsxs)("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",className:e,"aria-hidden":"true",children:[(0,l.jsx)("path",{d:"M3 6h18"}),(0,l.jsx)("path",{d:"M8 6V4.75A1.75 1.75 0 0 1 9.75 3h4.5A1.75 1.75 0 0 1 16 4.75V6"}),(0,l.jsx)("path",{d:"M18 6v12.25A1.75 1.75 0 0 1 16.25 20h-8.5A1.75 1.75 0 0 1 6 18.25V6"}),(0,l.jsx)("path",{d:"M10 10.5v5"}),(0,l.jsx)("path",{d:"M14 10.5v5"})]})}function U2({className:e=""}){return(0,l.jsxs)("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",className:e,"aria-hidden":"true",children:[(0,l.jsx)("rect",{x:"9",y:"9",width:"11",height:"11",rx:"2"}),(0,l.jsx)("path",{d:"M5 15V6a2 2 0 0 1 2-2h9"})]})}function j2({className:e=""}){return(0,l.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",className:e,"aria-hidden":"true",children:[(0,l.jsx)("path",{d:"M7.25 5.75h-1.5A2.75 2.75 0 0 0 3 8.5v5.75A2.75 2.75 0 0 0 5.75 17h5.75a2.75 2.75 0 0 0 2.75-2.75v-1.5"}),(0,l.jsx)("path",{d:"M10.5 9.5 17 3"}),(0,l.jsx)("path",{d:"M12 3h5v5"})]})}function P2({className:e=""}){return(0,l.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",className:e,"aria-hidden":"true",children:[(0,l.jsx)("circle",{cx:"6.75",cy:"10",r:"3.25"}),(0,l.jsx)("path",{d:"M10 10h6.5"}),(0,l.jsx)("path",{d:"M13.5 10v2.25"}),(0,l.jsx)("path",{d:"M15.75 10v1.5"})]})}function V2({className:e=""}){return(0,l.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",className:e,"aria-hidden":"true",children:[(0,l.jsx)("path",{d:"M16.25 10a6.25 6.25 0 1 1-1.83-4.42"}),(0,l.jsx)("path",{d:"M13.5 3.75h3v3"}),(0,l.jsx)("path",{d:"M16.5 3.75 12.75 7.5"})]})}function H2({className:e=""}){return(0,l.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",className:e,"aria-hidden":"true",children:[(0,l.jsx)("path",{d:"M6 3.5h5.25L15 7.25V16A1.5 1.5 0 0 1 13.5 17.5h-7A1.5 1.5 0 0 1 5 16V5A1.5 1.5 0 0 1 6.5 3.5H6Z"}),(0,l.jsx)("path",{d:"M11 3.5V7.5H15"}),(0,l.jsx)("path",{d:"M7.75 11h4.5"}),(0,l.jsx)("path",{d:"M7.75 14h4.5"})]})}function EC({className:e=""}){return(0,l.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",className:e,"aria-hidden":"true",children:[(0,l.jsx)("path",{d:"M6 3.5h5.25L15 7.25V16A1.5 1.5 0 0 1 13.5 17.5h-7A1.5 1.5 0 0 1 5 16V5A1.5 1.5 0 0 1 6.5 3.5H6Z"}),(0,l.jsx)("path",{d:"M11 3.5V7.5H15"}),(0,l.jsx)("path",{d:"M7 12.25a3 3 0 1 1 2.85 2.99"}),(0,l.jsx)("path",{d:"M8.5 10.25h1.5v1.5"})]})}function q2({className:e=""}){return(0,l.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",className:e,"aria-hidden":"true",children:[(0,l.jsx)("path",{d:"M10 2.75 4.75 5v4.12c0 3.42 2.1 6.58 5.25 7.88 3.15-1.3 5.25-4.46 5.25-7.88V5L10 2.75Z"}),(0,l.jsx)("circle",{cx:"10",cy:"9",r:"1.4"}),(0,l.jsx)("path",{d:"M10 10.4v2.1"})]})}function $2({label:e,value:t,icon:n,disabled:r=!1,onClick:a,actionLabel:o}){return(0,l.jsxs)("button",{type:"button",className:"inline-flex h-9 min-w-0 max-w-full items-center gap-2 rounded-full border border-border/70 bg-background/90 px-3 text-left transition hover:border-accent hover:bg-accent disabled:cursor-not-allowed disabled:opacity-70 sm:max-w-[18rem]",onClick:a,disabled:r,"aria-label":o,title:r?o:t,children:[(0,l.jsx)("span",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-secondary text-muted-foreground",children:n}),(0,l.jsx)("span",{className:"shrink-0 text-[10px] font-semibold uppercase tracking-[0.14em] text-muted-foreground",children:e}),(0,l.jsx)("span",{className:"min-w-0 truncate text-xs font-medium text-foreground",children:t})]})}function K2({value:e,pending:t=!1,disabled:n=!1,rotateDisabled:r=!1,onCopy:a,onRotate:o}){return(0,l.jsxs)("div",{className:"flex h-9 min-w-0 max-w-full items-stretch overflow-hidden rounded-full border border-border/70 bg-background/90 sm:max-w-[18rem]",children:[(0,l.jsxs)("button",{type:"button",className:"inline-flex min-w-0 flex-1 items-center gap-2 rounded-l-full px-3 text-left transition hover:bg-accent disabled:cursor-not-allowed disabled:opacity-70",onClick:a,disabled:n,"aria-label":t?"Gateway key is still generating":"Copy gateway key",title:t?"Gateway key is still generating":"Copy gateway key",children:[(0,l.jsx)("span",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-secondary text-muted-foreground",children:(0,l.jsx)(P2,{className:"h-3.5 w-3.5"})}),(0,l.jsx)("span",{className:"shrink-0 text-[10px] font-semibold uppercase tracking-[0.14em] text-muted-foreground",children:"Gateway key"}),(0,l.jsx)("span",{className:"min-w-0 truncate text-xs font-medium text-foreground",children:e})]}),(0,l.jsx)("button",{type:"button",className:"inline-flex w-9 shrink-0 items-center justify-center rounded-r-full border-l border-border/70 text-muted-foreground transition hover:bg-accent hover:text-foreground disabled:cursor-not-allowed disabled:opacity-70",onClick:o,disabled:r,"aria-label":"Rotate gateway key",title:"Rotate gateway key",children:(0,l.jsx)(V2,{className:"h-3.5 w-3.5"})})]})}function F2({endpointValue:e,endpointDisabled:t=!1,gatewayValue:n,gatewayPending:r=!1,gatewayDisabled:a=!1,rotateDisabled:o=!1,onCopyEndpoint:i,onCopyGatewayKey:s,onRotateKey:c}){return(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-1.5",children:[(0,l.jsx)($2,{label:"Endpoint",value:e,icon:(0,l.jsx)(j2,{className:"h-3.5 w-3.5"}),disabled:t,onClick:i,actionLabel:t?"API endpoint not ready yet":"Copy API endpoint"}),(0,l.jsx)(K2,{value:n,pending:r,disabled:a,rotateDisabled:o,onCopy:s,onRotate:c})]})}function aC({label:e,value:t,icon:n,disabled:r=!1,onClick:a,actionLabel:o="",emptyLabel:i="Not resolved"}){let s=String(t||"").trim()||i;return(0,l.jsxs)("button",{type:"button",className:"inline-flex min-w-0 max-w-full items-start gap-2 rounded-2xl border border-border/70 bg-background/90 px-3 py-2 text-left transition hover:border-accent hover:bg-accent disabled:cursor-not-allowed disabled:opacity-70",onClick:a,disabled:r,"aria-label":o,title:r?o:s,children:[(0,l.jsx)("span",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-secondary text-muted-foreground",children:n}),(0,l.jsxs)("span",{className:"min-w-0",children:[(0,l.jsx)("span",{className:"block text-[9px] font-semibold uppercase tracking-[0.12em] text-muted-foreground",children:e}),(0,l.jsx)("span",{className:"mt-1 block break-all text-[11px] font-medium leading-4 text-foreground",children:s})]})]})}function Td({connected:e=!1,className:t,srLabel:n="Connected",size:r="sm"}){if(!e)return null;let a=r==="md"?"h-3.5 w-3.5":"h-2.5 w-2.5",o=r==="md"?"h-2 w-2":"h-1.5 w-1.5";return(0,l.jsxs)("span",{className:W("relative inline-flex shrink-0 items-center justify-center",a,t),children:[(0,l.jsx)("span",{"aria-hidden":"true",className:"absolute inset-0 rounded-full bg-emerald-400/45 animate-ping motion-reduce:animate-none"}),(0,l.jsx)("span",{"aria-hidden":"true",className:W("relative rounded-full bg-emerald-500 ring-2 ring-emerald-500/15",o)}),(0,l.jsx)("span",{className:"sr-only",children:n})]})}function TC({primaryLabel:e="Config file",primaryValue:t="",primaryIcon:n=(0,l.jsx)(H2,{className:"h-3 w-3"}),onOpenPrimary:r,secondaryLabel:a="Backup file",secondaryValue:o="",secondaryIcon:i=(0,l.jsx)(EC,{className:"h-3 w-3"}),onOpenSecondary:s}){let c=String(t||"").trim(),u=String(o||"").trim();return(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,l.jsx)(aC,{label:e,value:c,icon:n,disabled:!c||typeof r!="function",onClick:r,actionLabel:c?`Open ${e.toLowerCase()}`:`${e} path is not resolved yet`}),(0,l.jsx)(aC,{label:a,value:u,icon:i,disabled:!u||typeof s!="function",onClick:s,actionLabel:u?`Open ${a.toLowerCase()}`:`${a} path is not resolved yet`})]})}function G2(e){return e==="error"?"Error":e==="success"?"Success":"Notice"}function Y2({notice:e,onDismiss:t}){let[n,r]=(0,E.useState)(Gg),[a,o]=(0,E.useState)(Gg),[i,s]=(0,E.useState)(!1),c=(0,E.useRef)(null),u=(0,E.useRef)(0);(0,E.useEffect)(()=>{if(n<=0){t();return}if(i){c.current&&(clearTimeout(c.current),c.current=null);return}return u.current=Date.now(),c.current=setTimeout(()=>{c.current=null,t()},n),()=>{c.current&&(clearTimeout(c.current),c.current=null)}},[t,i,n]),(0,E.useEffect)(()=>{if(i||n<=0){o(n);return}let h=()=>{let S=u.current?Date.now()-u.current:0;o(Math.max(0,n-S))};h();let v=setInterval(h,Sk);return()=>clearInterval(v)},[i,n]);function f(){if(i)return;c.current&&(clearTimeout(c.current),c.current=null);let h=u.current?Date.now()-u.current:0,v=Math.max(0,n-h);r(v),o(v),s(!0)}function d(){s(!1)}let p=e.tone==="error"?"border-rose-200 bg-rose-50 text-rose-800":e.tone==="success"?"border-emerald-200 bg-emerald-50 text-emerald-800":"border-amber-200 bg-amber-50 text-amber-800",m=9,b=2*Math.PI*m,g=Math.max(0,Math.min(1,a/Gg)),x=b*(1-g),y=i?`Auto-dismiss paused with ${Math.max(0,a/1e3).toFixed(1)} seconds remaining`:`Auto-dismiss in ${Math.max(0,a/1e3).toFixed(1)} seconds`;return(0,l.jsx)("div",{className:W("pointer-events-auto rounded-2xl border px-4 py-3 text-sm shadow-lg backdrop-blur",p),onMouseEnter:f,onMouseLeave:d,onFocusCapture:f,onBlurCapture:h=>{h.currentTarget.contains(h.relatedTarget)||d()},role:e.tone==="error"?"alert":"status",children:(0,l.jsxs)("div",{className:"min-w-0",children:[(0,l.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,l.jsx)("div",{className:"text-[11px] font-medium uppercase tracking-[0.16em] opacity-75",children:G2(e.tone)}),(0,l.jsxs)("div",{className:"relative mt-0.5 h-6 w-6 shrink-0 opacity-85","aria-label":y,title:y,children:[(0,l.jsxs)("svg",{viewBox:"0 0 24 24",className:W("h-6 w-6 -rotate-90",i?"opacity-70":"opacity-100"),"aria-hidden":"true",children:[(0,l.jsx)("circle",{cx:"12",cy:"12",r:m,fill:"none",stroke:"currentColor",strokeOpacity:"0.18",strokeWidth:"2"}),(0,l.jsx)("circle",{cx:"12",cy:"12",r:m,fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeDasharray:b,strokeDashoffset:x,className:"transition-[stroke-dashoffset,opacity] duration-100 ease-linear"})]}),(0,l.jsx)("span",{className:W("pointer-events-none absolute inset-0 flex items-center justify-center",i?"gap-[2px]":""),"aria-hidden":"true",children:i?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("span",{className:"h-2.5 w-[2px] rounded-full bg-current/75"}),(0,l.jsx)("span",{className:"h-2.5 w-[2px] rounded-full bg-current/75"})]}):(0,l.jsx)("span",{className:"h-1.5 w-1.5 rounded-full bg-current/75"})})]})]}),(0,l.jsx)("div",{className:"mt-1 leading-6",children:e.message}),(0,l.jsx)("div",{className:"mt-2 flex justify-end",children:(0,l.jsx)("button",{className:"rounded-full border border-current/15 px-2.5 py-1 text-[11px] font-medium uppercase tracking-[0.16em] opacity-85 transition hover:border-current/30 hover:opacity-100",onClick:t,type:"button",children:"Dismiss"})})]})})}function oC({notices:e,onDismiss:t}){return!Array.isArray(e)||e.length===0?null:(0,l.jsx)("div",{className:"pointer-events-none fixed inset-x-4 top-4 z-50 flex flex-col items-end gap-3","aria-live":"polite","aria-relevant":"additions text",children:e.map(n=>(0,l.jsx)("div",{className:"w-full max-w-md",children:(0,l.jsx)(Y2,{notice:n,onDismiss:()=>t(n.id)})},n.id))})}function W2({provider:e,disabled:t=!1,disabledReason:n="",busy:r=!1,onApply:a,framed:o=!0,focusRequest:i=0,onStateChange:s=null,testStateByModel:c={},savePhase:u="",saveMessage:f=""}){let d=(0,E.useMemo)(()=>L1(e),[e]),[p,m]=(0,E.useState)([]),[b,g]=(0,E.useState)(""),[x,y]=(0,E.useState)(!1),[h,v]=(0,E.useState)({}),[S,C]=(0,E.useState)({}),[T,w]=(0,E.useState)(null),[R,M]=(0,E.useState)(""),[k,I]=(0,E.useState)(""),[H,Q]=(0,E.useState)({}),ee=(0,E.useRef)(0),X=(0,E.useRef)([]),z=(0,E.useRef)(new Map),te=(0,E.useRef)(new Map),Y=(0,E.useRef)(""),q=(0,E.useRef)(""),V=(0,E.useRef)(null),_e=(0,E.useRef)(new Map),F=(0,E.useRef)(new Map);function he(A={}){return ee.current+=1,{key:`model-${e.id}-draft-${ee.current}`,id:"",sourceId:"",contextWindow:"",...A}}function Z(A){Y.current=A}function ae(A=[],{preserveFocus:D=!1}={}){let B=[],G=null;for(let $ of Array.isArray(A)?A:[]){let tt=String($?.id||""),He=$?.contextWindow===void 0||$?.contextWindow===null?"":String($.contextWindow);if(String(tt).trim()){B.push({...$,id:tt,contextWindow:He});continue}G||(G={...$,id:"",contextWindow:He})}return G||(G=he(),D&&Z(G.key)),[G,...B]}function Se(A){C(D=>{if(!D[A])return D;let B={...D};return delete B[A],B})}function U(A,D){v(B=>{if(D)return B[A]?B:{...B,[A]:!0};if(!B[A])return B;let G={...B};return delete G[A],G})}function ne(A,D={},{clearLookupState:B=!1,clearStatus:G=!0,closeLookupMenu:$=!1}={}){B&&Se(A),G&&w(null),$&&R===A&&M(""),m(tt=>ae(tt.map(He=>He.key===A?{...He,...D}:He),{preserveFocus:!1}))}(0,E.useEffect)(()=>{X.current=p},[p]),(0,E.useEffect)(()=>{let A=ae(d,{preserveFocus:!0});m(A),X.current=A,_e.current.clear(),F.current.clear(),v({}),C({}),w(null),M(""),I(""),Q({})},[d]),(0,E.useEffect)(()=>{let A=Y.current;if(!A)return;let D=z.current.get(A);if(!D)return;D.scrollIntoView?.({block:"nearest"}),D.focus();let B=D.value?.length||0;D.setSelectionRange?.(B,B),Y.current=""},[p]),(0,E.useEffect)(()=>{i&&m(A=>{let D=ae(A,{preserveFocus:!1}),B=D.find(G=>!String(G?.id||"").trim())||D[D.length-1];return B&&Z(B.key),D})},[i]),(0,E.useEffect)(()=>{R&&(p.some(A=>A.key===R)||M(""))},[p,R]),(0,E.useEffect)(()=>{k&&(p.some(A=>A.key===k)||I(""))},[p,k]),(0,E.useEffect)(()=>{Q(A=>{let D=new Set(p.map($=>$.key)),B=!1,G={};for(let[$,tt]of Object.entries(A)){if(!D.has($)){B=!0;continue}G[$]=tt}return B?G:A})},[p]),(0,E.useEffect)(()=>{if(!R||typeof document>"u")return;function A(D){te.current.get(R)?.contains(D.target)||M("")}return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[R]);let ue=(0,E.useMemo)(()=>p.filter(A=>String(A?.id||"").trim()),[p]),me=(0,E.useMemo)(()=>d.map(A=>({id:String(A?.id||"").trim(),contextWindow:so(A?.contextWindow||"")})).filter(A=>A.id),[d]),re=(0,E.useMemo)(()=>ue.map(A=>({...A,id:String(A?.id||"").trim(),contextWindow:so(A?.contextWindow||"")})),[ue]),oe=re.map(A=>A.id),Ne=me.map(A=>A.id),Re=oe.filter(A=>!Ne.includes(A)),Ze=dh(oe),gt=oe.length>0,Vt=new Set(re.filter(A=>{let D=String(A?.contextWindow||"").trim();if(!D)return!1;let B=Number.parseInt(D,10);return!Number.isFinite(B)||B<=0||String(B)!==D}).map(A=>A.key)),sn=re.filter(A=>!String(A?.contextWindow||"").trim()),ot=JSON.stringify(me)!==JSON.stringify(re.map(A=>({id:A.id,contextWindow:A.contextWindow}))),Ge=t||r||(b!==""||u==="testing"||u==="saving")||x,qr=(0,E.useMemo)(()=>{let A=-1;return p.forEach((D,B)=>{String(D?.id||"").trim()&&(A=B)}),A},[p]),cn=t?n:gt?Ze?"Model ids must be unique for each provider.":Vt.size>0?"Context windows must be positive integers when set.":"":"Keep at least one model id on the provider.",$e=sh(p.map(A=>A.key));(0,E.useEffect)(()=>{s?.({isDirty:ot,issue:cn,locked:Ge,rows:re.map(A=>({...A,contextWindow:so(A.contextWindow)}))})},[s,ot,cn,Ge,re]);function Ee(A){Se(A),U(A,!1),w(null),R===A&&M(""),k===A&&I(""),Q(D=>{if(!Object.prototype.hasOwnProperty.call(D,A))return D;let B={...D};return delete B[A],B}),m(D=>ae(D.filter(B=>B.key!==A)))}function fe(A){m(D=>ae(ih(D,A,B=>B?.key)))}function ge(A){m(D=>ae(mC(D,A,B=>B?.key)))}function P(){q.current="",pl(V.current,!1),V.current=null}async function Ye(A,{force:D=!1}={}){let B=String(A||"").trim();if(!B)return qs({query:B});if(!D&&_e.current.has(B))return _e.current.get(B);if(!D&&F.current.has(B))return F.current.get(B);let G=(async()=>{let $=await th([B]),tt=(Array.isArray($)?$:[]).find(ke=>String(ke?.query||"").trim()===B)||{query:B},He=qs(tt,{fallbackQuery:B});return _e.current.set(B,He),He})();F.current.set(B,G);try{return await G}finally{F.current.delete(B)}}async function Ht(A,{openMenu:D=!1,prefill:B=!1,modelId:G=""}={}){let $=X.current.find(He=>He.key===A),tt=String(G||$?.id||"").trim();if(!tt)return null;D&&M(A),U(A,!0);try{let He=await Ye(tt);if(C(ke=>({...ke,[A]:He})),B){let ke=nh(He);ke&&m(ht=>ae(ht.map(yt=>{if(yt.key!==A)return yt;let Ve=String(yt?.id||"").trim(),de=String(yt?.contextWindow||"").trim();return!Ve||Ve!==tt||de?yt:{...yt,contextWindow:ke}}),{preserveFocus:!1}))}return He}catch(He){let ke=He instanceof Error?He.message:String(He),ht={query:tt,status:"error",error:ke,options:[]};return C(yt=>({...yt,[A]:ht})),ht}finally{U(A,!1)}}async function Gt(A=[]){let D=new Set(Array.isArray(A)?A:[]),B=re.filter(G=>!G.id||String(G?.contextWindow||"").trim()?!1:D.size===0?!0:D.has(G.key)).map(G=>({key:G.key,id:G.id}));if(B.length!==0){y(!0),w(null);try{let G=await th(B.map(Ve=>Ve.id)),$=k2(G),tt=new Map(B.map(Ve=>[Ve.key,Ve]));for(let Ve of $.values())Ve?.query&&_e.current.set(Ve.query,Ve);let He=Array.isArray(X.current)?X.current:[],ke=0,ht=0,yt=He.map(Ve=>{let de=tt.get(Ve.key);if(!de)return Ve;let qe=String(Ve?.id||"").trim(),un=String(Ve?.contextWindow||"").trim();if(!qe||qe!==de.id||un)return Ve;let po=$.get(qe)||qs({query:qe}),Bn=nh(po);return Bn?(ke+=1,{...Ve,contextWindow:Bn}):(ht+=1,Ve)});m(ae(yt,{preserveFocus:!1})),w({tone:ke>0?"success":"warning",message:ke>0?`Filled ${ke} context size${ke===1?"":"s"}${ht>0?`; ${ht} still need a manual value`:""}.`:`Could not fill ${ht} model${ht===1?"":"s"}.`})}catch(G){w({tone:"error",message:G instanceof Error?G.message:String(G)})}finally{y(!1)}}}async function Mt(){if(Ge||cn||!ot)return!1;let A=uo(e)==="api"&&Re.length>0;g(A?"testing":"saving");try{return await a(re.map(D=>({...D,contextWindow:so(D.contextWindow)})))}finally{g("")}}return(0,l.jsxs)("div",{className:W(o?"space-y-3 rounded-2xl border border-border/70 bg-background/60 p-4":"space-y-3"),children:[(0,l.jsx)("div",{className:"rounded-2xl border border-border/70 bg-secondary/35 px-4 py-3 text-sm leading-6 text-muted-foreground",children:"Direct routes follow this top-to-bottom order. Focus a context field to load suggested sizes, or use Fill missing context size to fill each empty row with a median size."}),(0,l.jsx)("div",{className:"space-y-2",children:p.map((A,D)=>{let B=String(A?.id||"").trim(),G=String(A?.contextWindow||"").trim(),$=!!B,tt=$?ue.findIndex(de=>de.key===A.key):-1,He=S[A.key]||null,ke=!!h[A.key],ht=R===A.key&&!!B,yt=Vt.has(A.key),Ve=B&&c?.[B]||"default";return(0,l.jsxs)("div",{ref:$e(A.key),"data-reorder-row":"true",onDragOver:de=>{!Ge&&q.current&&q.current!==A.key&&(de.preventDefault(),de.dataTransfer.dropEffect="move")},onDrop:de=>{if(Ge)return;de.preventDefault();let qe=de.dataTransfer.getData("text/plain")||q.current;P(),m(un=>ae(fC(un,qe,A.key)))},className:W("space-y-2 rounded-xl border border-border/70 bg-card/90 p-3",$?null:"border-dashed bg-background/85",yt?"border-amber-200 bg-amber-50/70":null,!yt&&Ve==="success"?"border-emerald-200 bg-emerald-50/70":null,!yt&&Ve==="error"?"border-rose-200 bg-rose-50/70":null,!yt&&Ve==="pending"?"border-sky-200 bg-sky-50/70":null),children:[(0,l.jsxs)("div",{className:"grid grid-cols-[auto_auto_auto_minmax(0,1fr)_minmax(12rem,14rem)_5.5rem] items-center gap-2",children:[(0,l.jsx)("span",{className:W("flex h-8 w-8 items-center justify-center rounded-full text-muted-foreground",$&&!Ge?"cursor-grab":"opacity-45"),draggable:!Ge&&$,onDragStart:de=>{if(Ge||!$)return;let qe=lh(de.currentTarget);de.dataTransfer.effectAllowed="move",de.dataTransfer.setData("text/plain",A.key),qe&&typeof de.dataTransfer?.setDragImage=="function"&&de.dataTransfer.setDragImage(qe,20,20),P(),q.current=A.key,V.current=qe,pl(qe,!0)},onDragEnd:P,title:$?"Drag to reorder":"New model draft row",children:(0,l.jsx)(ch,{className:"h-4 w-4"})}),(0,l.jsx)(Ks,{disabled:Ge||!$||tt<=0,label:!$||tt<=0?"Already first":`Move ${A.id||`model ${tt+1}`} up`,onClick:()=>fe(A.key)}),(0,l.jsx)(kd,{disabled:Ge||!$||D>=qr,label:!$||D>=qr?"Already last":`Move ${A.id||`model ${tt+1}`} down`,onClick:()=>ge(A.key)}),(0,l.jsx)(Dt,{ref:de=>{de?z.current.set(A.key,de):z.current.delete(A.key)},value:A.id,onChange:de=>ne(A.key,{id:de.target.value},{clearLookupState:!0,closeLookupMenu:!0}),placeholder:$?"Model id":"Add a new model id",disabled:Ge}),(0,l.jsxs)("div",{ref:de=>{de?te.current.set(A.key,de):te.current.delete(A.key)},className:"relative min-w-0",children:[(0,l.jsx)(Dt,{value:k===A.key?H[A.key]??Ed(A.contextWindow):o2(A.contextWindow),onChange:de=>{let qe=de.target.value,un=so(qe);Q(po=>({...po,[A.key]:Ed(un)})),ne(A.key,{contextWindow:un},{clearStatus:!1})},onBlur:de=>{I(qe=>qe===A.key?"":qe),Q(qe=>{if(!Object.prototype.hasOwnProperty.call(qe,A.key))return qe;let un={...qe};return delete un[A.key],un}),ne(A.key,{contextWindow:so(de.target.value)},{clearStatus:!1})},onFocus:()=>{B&&(I(A.key),Q(de=>({...de,[A.key]:Ed(A.contextWindow)})),Ht(A.key,{openMenu:!0}))},onClick:()=>{B&&Ht(A.key,{openMenu:!0})},onKeyDown:de=>{if(de.key==="ArrowDown"&&B){de.preventDefault(),Ht(A.key,{openMenu:!0});return}de.key==="Escape"&&(de.preventDefault(),M(""))},placeholder:"Context window",inputMode:"numeric",disabled:Ge||!B,className:"font-medium tabular-nums","aria-label":B?`Context window for ${B}`:"Context window"}),ht?(0,l.jsx)(RC,{open:ht,anchorRef:{current:te.current.get(A.key)||null},preferredSide:"top",desiredHeight:224,className:"z-20 rounded-lg bg-background/98 p-2",onMouseDown:de=>de.preventDefault(),children:ke?(0,l.jsxs)("div",{className:"inline-flex items-center gap-2 px-1 py-2 text-sm text-muted-foreground",children:[(0,l.jsx)(co,{}),"Fetching size options for ",(0,l.jsx)("code",{children:B}),"."]}):He?.status==="error"?(0,l.jsx)("div",{className:"rounded-lg border border-rose-200 bg-rose-50 px-3 py-2 text-xs text-rose-900",children:He.error||"Could not load suggested sizes."}):He?.options?.length>0?(0,l.jsx)("div",{className:"space-y-1",children:He.options.map(de=>(0,l.jsxs)("button",{type:"button",className:"flex w-full flex-col gap-2 rounded-lg border border-border/70 bg-background px-3 py-2 text-left text-sm text-foreground transition hover:border-accent hover:bg-accent disabled:cursor-not-allowed disabled:opacity-70",disabled:Ge,onMouseDown:qe=>qe.preventDefault(),onClick:()=>{Q(qe=>({...qe,[A.key]:Ed(de.contextWindow)})),ne(A.key,{contextWindow:String(de.contextWindow)},{clearStatus:!1}),M("")},title:`Use ${de.label}`,children:[(0,l.jsxs)("div",{className:"min-w-0 space-y-1",children:[(0,l.jsx)("div",{className:"break-words font-medium leading-5",children:de.label}),(0,l.jsx)("div",{className:"break-words text-xs leading-4 text-muted-foreground",children:de.detail})]}),(0,l.jsxs)("div",{className:"w-full rounded-md border border-border/70 bg-secondary/70 px-3 py-2",children:[(0,l.jsx)("div",{className:"text-[10px] font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Context size"}),(0,l.jsx)("div",{className:"mt-1 text-lg font-semibold leading-none tabular-nums text-foreground",children:Hs(de.contextWindow)})]})]},de.key))}):(0,l.jsxs)("div",{className:"rounded-lg border border-dashed border-border/70 bg-background/80 px-3 py-2 text-xs text-muted-foreground",children:["No suggested size was found for ",(0,l.jsx)("code",{children:He?.query||B}),"."]})}):null]}),$?(0,l.jsx)(ce,{type:"button",variant:"ghost",className:Ld,onMouseDown:de=>de.preventDefault(),onClick:()=>Ee(A.key),disabled:Ge,children:"Remove"}):(0,l.jsx)(ce,{type:"button",variant:"ghost",className:W(Ld,"pointer-events-none invisible"),tabIndex:-1,disabled:!0,"aria-hidden":"true",children:"Remove"})]}),ke?(0,l.jsx)("div",{className:"flex justify-end text-xs",children:(0,l.jsxs)("div",{className:"inline-flex items-center gap-1.5 text-sky-700",children:[(0,l.jsx)(co,{}),"Looking up sizes"]})}):null,yt?(0,l.jsxs)("div",{className:"rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900",children:["Enter a positive integer like ",(0,l.jsx)("code",{children:"128000"}),", or leave the field blank."]}):Ve==="pending"?(0,l.jsx)("div",{className:"rounded-lg border border-sky-200 bg-sky-50 px-3 py-2 text-xs text-sky-900",children:"Testing this model against the provider endpoint now."}):Ve==="success"?(0,l.jsx)("div",{className:"rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-2 text-xs text-emerald-900",children:"Confirmed by the latest live provider test."}):Ve==="error"?(0,l.jsx)("div",{className:"rounded-lg border border-rose-200 bg-rose-50 px-3 py-2 text-xs text-rose-900",children:"This model failed the latest live provider test."}):null]},A.key)})}),cn?(0,l.jsx)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900",children:cn}):null,T?(0,l.jsx)("div",{className:W("rounded-xl px-3 py-2 text-sm",T.tone==="error"?"border border-rose-200 bg-rose-50 text-rose-900":T.tone==="warning"?"border border-amber-200 bg-amber-50 text-amber-900":"border border-emerald-200 bg-emerald-50 text-emerald-900"),children:T.message}):null,(0,l.jsx)("div",{className:W("sticky z-10 border-t border-border/70 bg-background/95 pt-3 backdrop-blur",o?"bottom-0":"bottom-0 -mx-5 rounded-b-[1rem] px-5 pb-4"),children:(0,l.jsxs)("div",{className:"flex min-h-9 items-center justify-between gap-3",children:[(0,l.jsx)("div",{className:W("text-xs",u==="testing"?"text-sky-700":u==="saving"?"text-foreground":"text-muted-foreground"),children:u==="testing"?(0,l.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,l.jsx)(co,{}),f||"Testing new models before save."]}):u==="saving"?(0,l.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,l.jsx)(co,{}),f||"Saving provider models."]}):Re.length>0&&uo(e)==="api"?`${Re.length} new model${Re.length===1?"":"s"} will be tested before save.`:"Existing models keep their current configuration metadata."}),(0,l.jsxs)("div",{className:"flex items-center justify-end gap-2",children:[!t&&!Ge&&sn.length>0?(0,l.jsx)(ce,{type:"button",variant:"outline",onClick:()=>{Gt()},children:x?"Filling\u2026":"Fill missing context size"}):null,!t&&!Ge&&ot?(0,l.jsx)(ce,{type:"button",variant:"ghost",onClick:()=>{v({}),C({}),w(null),M(""),_e.current.clear(),F.current.clear(),m(ae(d,{preserveFocus:!0}))},children:"Reset"}):null,!t&&ot&&!cn?(0,l.jsx)(ce,{type:"button",onClick:()=>{Mt()},disabled:Ge,children:u==="testing"||b==="testing"?"Testing\u2026":u==="saving"||b==="saving"||r?"Saving\u2026":"Save models"}):null]})]})})]})}function Q2({title:e,rows:t,onChange:n,options:r,disabled:a=!1,addLabel:o="Add target",emptyLabel:i="No targets configured.",helperText:s="Drag rows or use the arrow to change routing order.",helperAction:c=null,placeholder:u="provider/model or alias",draftPlaceholder:f="Add a new route",showDraftRow:d=!1,showDraftFocusButton:p=!1,showWeightInput:m=!1,filterOtherSelectedValues:b=!1,excludedValues:g=[]}){let x=(0,E.useRef)(0),y=(0,E.useRef)(""),h=(0,E.useRef)(null),v=(0,E.useRef)(new Map),S=(0,E.useRef)(0),C=(0,E.useRef)(0),[T,w]=(0,E.useState)(0),R=(0,E.useMemo)(()=>String(e||"targets").trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"targets",[e]),M=`${R}-draft-row`,k=(0,E.useMemo)(()=>{let F=(t||[]).filter(he=>String(he?.ref||"").trim());return d?[{key:M,ref:"",sourceRef:""},...F]:F},[t,d,M]),I=sh(k.map(F=>F.key)),H=(0,E.useMemo)(()=>ba(g),[g]),Q=(0,E.useMemo)(()=>Fs(r,[...k.map(F=>F?.ref),...H]),[r,k,H]);(0,E.useEffect)(()=>()=>{typeof window<"u"&&S.current&&window.cancelAnimationFrame(S.current)},[]);function ee(F,he){if(d&&F===M){if(!String(he||"").trim())return;x.current+=1,n([{key:`${R}-draft-${x.current}`,ref:he,sourceRef:"",...m?{weight:"1"}:{}},...(t||[]).filter(Z=>String(Z?.ref||"").trim())]);return}n((t||[]).map(Z=>Z.key===F?{...Z,ref:he}:Z))}function X(F,he){n((t||[]).map(Z=>Z.key===F?{...Z,weight:he}:Z))}function z(F){n((t||[]).filter(he=>he.key!==F))}function te(F){n(ih(t||[],F,he=>he?.key))}function Y(F){n(mC(t||[],F,he=>he?.key))}function q(){y.current="",pl(h.current,!1),h.current=null}function V(){x.current+=1;let F=new Set([...(t||[]).map(Z=>String(Z?.ref||"").trim()).filter(Boolean),...H]),he=Q.find(Z=>!F.has(Z.value))?.value||"";n([...t||[],{key:`${R}-draft-${x.current}`,ref:he,sourceRef:""}])}function _e(){if(!d||a)return;let F=v.current.get(M);if(!F||typeof window>"u"){w(Ne=>Ne+1);return}C.current+=1;let he=C.current;S.current&&(window.cancelAnimationFrame(S.current),S.current=0),F.scrollIntoView({block:"start",behavior:"smooth"});let Z=hd(F),ae=P1(F,Z),Se=0,U=0,ne=90,ue=8,me=6,re=.5,oe=()=>{if(C.current!==he)return;let Ne=v.current.get(M)||F,Re=P1(Ne,Z);if(!Number.isFinite(Re.top)||!Number.isFinite(Re.left)){S.current=0,w(Ze=>Ze+1);return}if(Tk(ae,Re,re)?Se+=1:Se=0,ae=Re,U+=1,U>=ue&&Se>=me||U>=ne){S.current=0,w(Ze=>Ze+1);return}S.current=window.requestAnimationFrame(oe)};S.current=window.requestAnimationFrame(oe)}return(0,l.jsxs)("div",{className:"space-y-2 rounded-2xl border border-border/70 bg-background/55 p-4",children:[(0,l.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[(0,l.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,l.jsx)("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:e}),p&&d?(0,l.jsx)(ce,{type:"button",variant:"ghost",size:"sm",className:"h-6 w-6 rounded-md p-0 text-muted-foreground hover:text-foreground",onMouseDown:F=>F.preventDefault(),onClick:_e,disabled:a,"aria-label":o,title:o,children:(0,l.jsx)(pC,{className:"h-3.5 w-3.5"})}):null]}),(0,l.jsxs)("div",{className:"ml-auto flex max-w-full flex-wrap items-start justify-end gap-x-3 gap-y-2",children:[s?(0,l.jsx)("div",{className:"max-w-[34rem] text-right text-[11px] leading-4 text-muted-foreground",children:s}):null,d?null:(0,l.jsx)(ce,{type:"button",variant:"ghost",onClick:V,disabled:a,children:o})]})]}),k.length>0?(0,l.jsx)("div",{className:"space-y-2",children:k.map((F,he)=>{let Z=d&&F.key===M,ae=Z?-1:(t||[]).findIndex(U=>U?.key===F.key),Se=b?Q.filter(U=>{let ne=String(U?.value||"").trim();return ne?ne===String(F?.ref||"").trim()?!0:H.includes(ne)?!1:!(k||[]).some(ue=>ue?.key!==F.key&&String(ue?.ref||"").trim()===ne):!1}):Q;return(0,l.jsxs)("div",{ref:U=>{if(I(F.key)(U),U){v.current.set(F.key,U);return}v.current.delete(F.key)},"data-reorder-row":"true",onDragOver:U=>{!a&&y.current&&y.current!==F.key&&(U.preventDefault(),U.dataTransfer.dropEffect="move")},onDrop:U=>{if(a)return;U.preventDefault();let ne=U.dataTransfer.getData("text/plain")||y.current;q(),n(fC(t||[],ne,F.key))},className:W(m?"grid grid-cols-[auto_auto_auto_minmax(0,1fr)_10rem_5.5rem] items-center gap-2 rounded-xl border border-border/70 bg-card/90 p-3":"grid grid-cols-[auto_auto_auto_minmax(0,1fr)_5.5rem] items-center gap-2 rounded-xl border border-border/70 bg-card/90 p-3",Z?"border-dashed bg-background/85":null),children:[(0,l.jsx)("span",{className:W("flex h-8 w-8 items-center justify-center rounded-full text-muted-foreground",Z||a?"opacity-45":"cursor-grab"),draggable:!a&&!Z,onDragStart:U=>{if(a||Z)return;let ne=lh(U.currentTarget);U.dataTransfer.effectAllowed="move",U.dataTransfer.setData("text/plain",F.key),ne&&typeof U.dataTransfer?.setDragImage=="function"&&U.dataTransfer.setDragImage(ne,20,20),q(),y.current=F.key,h.current=ne,pl(ne,!0)},onDragEnd:q,title:Z?"New route draft row":"Drag to reorder",children:(0,l.jsx)(ch,{className:"h-4 w-4"})}),(0,l.jsx)(Ks,{disabled:a||Z||ae<=0,label:Z||ae<=0?"Already first":`Move ${F.ref||`target ${ae+1}`} up`,onClick:()=>te(F.key)}),(0,l.jsx)(kd,{disabled:a||Z||ae===-1||ae>=(t||[]).length-1,label:Z||ae===-1||ae>=(t||[]).length-1?"Already last":`Move ${F.ref||`target ${ae+1}`} down`,onClick:()=>Y(F.key)}),(0,l.jsxs)("div",{className:"flex h-9 min-w-0 overflow-hidden rounded-lg border border-input bg-background/80 shadow-sm transition focus-within:border-ring focus-within:ring-2 focus-within:ring-ring/40",children:[(0,l.jsx)("div",{className:"flex shrink-0 items-center border-r border-border/70 bg-secondary/55 px-2.5 text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Model"}),(0,l.jsxs)(vr,{value:F.ref||void 0,onValueChange:U=>ee(F.key,U),disabled:a,openSearchRequest:Z?T:0,children:[(0,l.jsx)(br,{className:"h-full min-w-0 flex-1 rounded-none border-0 bg-transparent px-3 shadow-none focus:border-transparent focus:ring-0",children:(0,l.jsx)(xr,{placeholder:Z?f:u})}),(0,l.jsx)(Sr,{children:Se.length>0?Bd(Se,{keyPrefix:`${e}-row-${F.key}`}):(0,l.jsx)(ar,{value:"__no-route-options",disabled:!0,children:"No routes available"})})]})]}),m?(0,l.jsxs)("div",{className:W("flex h-9 overflow-hidden rounded-lg border border-input bg-background/80 shadow-sm transition focus-within:border-ring focus-within:ring-2 focus-within:ring-ring/40",Z?"opacity-45":null),children:[(0,l.jsx)("div",{className:"flex shrink-0 items-center border-r border-border/70 bg-secondary/55 px-2.5 text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Weight"}),(0,l.jsx)(Dt,{value:Z?"":String(F?.weight||"1"),onChange:U=>X(F.key,U.target.value),inputMode:"numeric",placeholder:"1",disabled:a||Z,className:"h-full min-w-0 rounded-none border-0 bg-transparent px-3 text-center shadow-none focus:border-transparent focus:ring-0","aria-label":Z?"Weight for new target":`Weight for ${F.ref||`target ${he+1}`}`})]}):null,Z?(0,l.jsx)(ce,{type:"button",variant:"ghost",className:W(Ld,"pointer-events-none invisible"),tabIndex:-1,disabled:!0,"aria-hidden":"true",children:"Remove"}):(0,l.jsx)(ce,{type:"button",variant:"ghost",className:Ld,onMouseDown:U=>U.preventDefault(),onClick:()=>z(F.key),disabled:a,children:"Remove"})]},F.key)})}):(0,l.jsx)("div",{className:"rounded-xl border border-dashed border-border px-4 py-5 text-sm text-muted-foreground",children:i}),c?(0,l.jsx)("div",{className:"flex min-h-8 items-center justify-end",children:c}):null]})}function X2(e,t){let n=Math.abs(Number(e)||0),r=Math.abs(Number(t)||0);for(;r!==0;){let a=n%r;n=r,r=a}return n||1}function Z2(e=[]){return!Array.isArray(e)||e.length===0?1:e.reduce((t,n)=>X2(t,n),0)||1}function J2(e,t){let n=String(e||"").trim();if(!n)return"Unconfigured route";let r=t.get(n);if(!r)return n;let a=String(r.label||n).trim()||n,o=String(r.hint||"").trim();return o&&o!==a?`${a} \xB7 ${o}`:a}function eL(e,t,n=[]){let r=new Map((n||[]).map(s=>[String(s?.value||"").trim(),s]).filter(([s])=>!!s)),a=new Map((Array.isArray(t?.targets)?t.targets:[]).map(s=>[String(s?.ref||"").trim(),s]).filter(([s])=>!!s)),o=new Map((Array.isArray(t?.fallbackTargets)?t.fallbackTargets:[]).map(s=>[String(s?.ref||"").trim(),s]).filter(([s])=>!!s));function i(s,c,u){return(s||[]).map((f,d)=>{let p=String(f?.ref||"").trim(),m=String(f?.sourceRef||f?.ref||"").trim(),b=u.get(m)||u.get(p)||{},g=Number(f?.weight??b?.weight),x=Number.isFinite(g)&&g>0?Math.floor(g):1;return{key:`${c}-${p||"empty"}-${d}`,ref:p,label:J2(p,r),bucket:c,weight:x}}).filter(f=>!!f.ref)}return[...i(e?.targets,"primary",a),...i(e?.fallbackTargets,"fallback",o)]}function tL(e=[],t=8){if(!Array.isArray(e)||e.length===0)return[];let n=e.map(s=>Math.max(1,Number(s?.weight)||1)),r=Z2(n),a=n.map(s=>Math.max(1,Math.floor(s/r))),o=a.reduce((s,c)=>s+c,0);if(o>24){let s=o/24;a=a.map(c=>Math.max(1,Math.round(c/s))),o=a.reduce((c,u)=>c+u,0)}let i=[];for(let s=0;s<e.length;s+=1)for(let c=0;c<a[s];c+=1)i.push(e[s]);return Array.from({length:Math.max(e.length,t)},(s,c)=>i[c%i.length])}function nL(e,t=[]){let n=uh(e),r=gC(n),a=Array.isArray(t)?t.filter(Boolean):[],i=a.some(s=>s.bucket==="fallback")?"Runtime builds the candidate pool as all primary targets first, then all fallback targets.":"Runtime builds the candidate pool from the primary target list only.";if(n==="round-robin"){let s=a.length>0?Array.from({length:Math.max(a.length,8)},(c,u)=>a[u%a.length]):[];return{strategyLabel:r,summary:"Each new request starts from the next candidate in the current pool, then wraps around.",poolNote:`${i} Round-robin rotates across that combined eligible list.`,sequenceLabel:"Example starting candidate by request",sequenceEntries:s,footnote:"If a candidate is unhealthy or quota-blocked, it is skipped and the next eligible candidate is chosen."}}if(n==="weighted-rr"||n==="quota-aware-weighted-rr"||n==="auto"){let s=n==="auto",c=tL(a,8);return{strategyLabel:r,summary:s?"`auto` normalizes to quota-aware weighted round-robin in the runtime balancer.":n==="quota-aware-weighted-rr"?"Candidates rotate like weighted round-robin, but low remaining quota or poor health lowers their share.":"Candidates repeat in proportion to their configured weights.",poolNote:`${i} This strategy ranks across the full eligible pool after it is built.`,sequenceLabel:"Example starting candidate by request",sequenceEntries:c,footnote:s||n==="quota-aware-weighted-rr"?"When all quotas and health scores are equal, the rotation looks like the weighted example below. Low remaining capacity or retryable failures push a target later.":"Weights come from the existing alias target metadata when present. Targets without a stored weight behave as weight 1."}}return{strategyLabel:r,summary:"Requests try candidates in the configured list order and only move to later candidates when earlier ones are unavailable or fail.",poolNote:`${i} Ordered keeps that exact sequence.`,sequenceLabel:"Attempt order",sequenceEntries:a,footnote:"This is the most predictable option when you want a strict preference order."}}function rL({open:e=!1,onClose:t=()=>{},onSave:n=()=>{},aliasLabel:r="",initialStrategy:a="auto",entries:o=[],disabled:i=!1}){let s=uh(a),[c,u]=(0,E.useState)(s),[f,d]=(0,E.useState)(!1);(0,E.useEffect)(()=>{e&&(u(s),d(!1))},[e,s,r]);async function p(){if(!(i||f)){d(!0);try{await n(c)!==!1&&t()}finally{d(!1)}}}return(0,l.jsx)(Sa,{open:e,onClose:t,title:r?`Choose strategy \xB7 ${r}`:"Choose strategy",description:"Review each routing strategy in its own tab. Save applies the currently selected tab to this alias.",showCloseButton:!1,footer:(0,l.jsxs)("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[(0,l.jsx)(ce,{type:"button",variant:"ghost",onClick:t,disabled:f,children:"Cancel"}),(0,l.jsx)(ce,{type:"button",onClick:()=>{p()},disabled:i||f,children:f?"Saving\u2026":"Save strategy"})]}),children:(0,l.jsxs)(Vu,{value:c,onValueChange:u,children:[(0,l.jsx)("div",{className:"overflow-x-auto pb-1",children:(0,l.jsx)(Hu,{className:"h-auto min-w-max flex-wrap justify-start gap-2 rounded-2xl bg-secondary/80 p-2",children:Wg.map(m=>(0,l.jsx)(Or,{value:m.value,className:"h-auto min-h-10 rounded-xl px-4 py-2",children:m.label},m.value))})}),Wg.map(m=>{let b=nL(m.value,o),g=(b.sequenceEntries||[]).filter(Boolean);return(0,l.jsx)(_r,{value:m.value,className:"mt-4",children:(0,l.jsxs)("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.15fr)_minmax(320px,0.85fr)]",children:[(0,l.jsxs)("div",{className:"space-y-4",children:[(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/80 p-5",children:[(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,l.jsx)(Tt,{variant:"outline",children:b.strategyLabel}),(0,l.jsxs)(Tt,{variant:"info",children:[o.length," candidate",o.length===1?"":"s"]})]}),(0,l.jsxs)("div",{className:"mt-4 space-y-3 text-sm leading-6 text-foreground",children:[(0,l.jsx)("p",{children:b.summary}),(0,l.jsx)("p",{className:"text-muted-foreground",children:b.poolNote})]})]}),(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/80 p-5",children:[(0,l.jsx)("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:b.sequenceLabel}),g.length>0?(0,l.jsx)("div",{className:"mt-4 flex flex-wrap gap-2",children:g.map((x,y)=>(0,l.jsxs)("div",{className:"rounded-full border border-border/70 bg-card/90 px-3 py-1.5 text-sm text-foreground",children:[(0,l.jsx)("span",{className:"mr-2 text-xs text-muted-foreground",children:y+1}),(0,l.jsx)("span",{children:x.label})]},`${x.key}-sequence-${y}`))}):(0,l.jsx)("div",{className:"mt-4 rounded-xl border border-dashed border-border px-4 py-5 text-sm text-muted-foreground",children:"Add at least one target to preview how this strategy would route requests."}),(0,l.jsx)("div",{className:"mt-4 text-sm leading-6 text-muted-foreground",children:b.footnote})]})]}),(0,l.jsx)("div",{className:"space-y-4",children:(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/80 p-5",children:[(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,l.jsx)("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Current setup"}),r?(0,l.jsx)(Tt,{variant:"outline",children:r}):null]}),o.length>0?(0,l.jsx)("div",{className:"mt-4 space-y-2",children:o.map(x=>(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-2 rounded-xl border border-border/70 bg-card/90 px-3 py-2 text-sm",children:[(0,l.jsx)(Tt,{variant:x.bucket==="primary"?"info":"outline",children:x.bucket}),(0,l.jsx)("span",{className:"font-medium text-foreground",children:x.label}),(0,l.jsxs)("span",{className:"text-xs text-muted-foreground",children:["weight ",x.weight]})]},x.key))}):(0,l.jsx)("div",{className:"mt-4 rounded-xl border border-dashed border-border px-4 py-5 text-sm text-muted-foreground",children:"This alias does not have any targets yet."})]})})]})},m.value)})]})})}function aL({open:e=!1,onClose:t=()=>{},config:n={}}){let r=(0,E.useMemo)(()=>s2(n),[n]);return(0,l.jsx)(Sa,{open:e,onClose:t,title:"Alias guide",description:"Aliases give clients one stable route while letting LLM Router swap, balance, and fail over across provider/model targets behind that route.",contentClassName:"max-h-[92vh] max-w-4xl rounded-2xl border border-border/70 bg-background/98 shadow-[0_32px_120px_rgba(15,23,42,0.48)]",bodyClassName:"max-h-[calc(92vh-5.5rem)]",children:(0,l.jsxs)("div",{className:"space-y-4",children:[(0,l.jsxs)("div",{className:"grid gap-4 md:grid-cols-3",children:[(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/70 p-4",children:[(0,l.jsx)("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Stable route"}),(0,l.jsxs)("div",{className:"mt-2 text-sm leading-6 text-foreground",children:["Expose one alias like ",(0,l.jsx)("code",{children:"coding"})," or ",(0,l.jsx)("code",{children:"gpt-5.4"})," to clients, then retarget the alias later without touching client config."]})]}),(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/70 p-4",children:[(0,l.jsx)("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Selection strategy"}),(0,l.jsx)("div",{className:"mt-2 text-sm leading-6 text-foreground",children:"The alias strategy controls how LLM Router picks from the configured targets. Ordered is strict preference; the other strategies distribute traffic when multiple targets are healthy."})]}),(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/70 p-4",children:[(0,l.jsx)("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Fallback behavior"}),(0,l.jsx)("div",{className:"mt-2 text-sm leading-6 text-foreground",children:"If one target is unavailable or rate limited, LLM Router can continue to later candidates in the same alias instead of failing the whole request immediately."})]})]}),(0,l.jsxs)("div",{className:"rounded-2xl border border-amber-200 bg-amber-50 p-4",children:[(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,l.jsx)(Tt,{variant:"warning",children:"Important"}),(0,l.jsx)("div",{className:"text-sm font-medium text-amber-950",children:"Mixed context windows inside one alias can change behavior."})]}),(0,l.jsxs)("div",{className:"mt-3 text-sm leading-6 text-amber-900",children:["If an alias mixes models with different context windows, requests that fit the larger model may still fail on the smaller model. For example, an alias that includes both a ",(0,l.jsx)("code",{children:"258K"})," model and a ",(0,l.jsx)("code",{children:"128K"})," model can still fail when routing lands on the smaller target. Keep aliases aligned by context size when you expect long histories or large prompts."]})]}),(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/70 p-4",children:[(0,l.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,l.jsxs)("div",{children:[(0,l.jsx)("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Current config check"}),(0,l.jsx)("div",{className:"mt-1 text-sm text-muted-foreground",children:"Aliases below currently mix different configured model context windows."})]}),(0,l.jsx)(Tt,{variant:r.length>0?"warning":"success",children:r.length>0?`${r.length} alias${r.length===1?"":"es"} need review`:"No mixed context windows detected"})]}),r.length>0?(0,l.jsx)("div",{className:"mt-4 space-y-3",children:r.map(a=>(0,l.jsxs)("div",{className:"rounded-2xl border border-amber-200 bg-amber-50/70 p-4",children:[(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,l.jsx)(Tt,{variant:"outline",children:a.aliasId}),(0,l.jsxs)("div",{className:"text-sm font-medium text-amber-950",children:["Smallest target: ",Hs(a.smallestContextWindow),". Largest target: ",Hs(a.largestContextWindow),"."]})]}),(0,l.jsxs)("div",{className:"mt-3 flex flex-wrap gap-2",children:[a.models.map(o=>(0,l.jsxs)("div",{className:"rounded-full border border-amber-200 bg-background/90 px-3 py-1.5 text-sm text-foreground",children:[o.ref," \xB7 ",Hs(o.contextWindow)]},o.ref)),a.unknownRefs.map(o=>(0,l.jsxs)("div",{className:"rounded-full border border-dashed border-amber-300 bg-background/70 px-3 py-1.5 text-sm text-muted-foreground",children:[o," \xB7 context unknown"]},o))]})]},a.aliasId))}):(0,l.jsx)("div",{className:"mt-4 rounded-xl border border-dashed border-border px-4 py-5 text-sm text-muted-foreground",children:"No alias currently mixes known context-window sizes across its configured targets."})]})]})})}function iC({aliasId:e,alias:t,aliasIds:n,routeOptions:r,defaultModel:a,ampDefaultRoute:o,disabled:i=!1,disabledReason:s="",busy:c=!1,onApply:u,onRemove:f,onCopyAliasId:d=()=>{},isNew:p=!1,alwaysShowAliasIdInput:m=!1,showIssueOnSubmitOnly:b=!1,onDiscard:g=()=>{},onOpenStrategyModal:x=()=>{},titleAccessory:y=null,aliasSwitcher:h=null,framed:v=!0}){let S=Uk(e,t,{isNew:p}),C=(0,E.useMemo)(()=>k1(p?"":e,t),[S]),[T,w]=(0,E.useState)(C),[R,M]=(0,E.useState)(p),[k,I]=(0,E.useState)(!1),H=(0,E.useRef)(null);(0,E.useEffect)(()=>{w(C),M(p),I(!1)},[C,p]);let Q=!p&&Array.isArray(h?.entries)&&h.entries.length>1,ee=m||R;(0,E.useEffect)(()=>{if(!ee)return;let P=typeof window<"u"?window.requestAnimationFrame(()=>{H.current?.focus(),H.current?.select?.()}):0;return()=>{typeof window<"u"&&window.cancelAnimationFrame(P)}},[ee]);let X=String(T?.id||"").trim(),z=e===at||X===at,te=(0,E.useMemo)(()=>Fs((r||[]).filter(P=>P.kind!=="alias"&&P.value!==X&&P.value!==`alias:${X}`),(T?.targets||[]).map(P=>P?.ref)),[r,X,T?.targets]),Y=(T?.targets||[]).map(P=>String(P?.ref||"").trim()),q=(T?.targets||[]).some(P=>!String(P?.ref||"").trim()),V=dh(Y),_e=(T?.targets||[]).some(P=>{if(!String(P?.ref||"").trim())return!1;let Ye=Math.floor(Number(P?.weight));return!Number.isFinite(Ye)||Ye<=0}),F=X&&n.some(P=>P!==e&&P===X),he=X&&Y.some(P=>P===X||P===`alias:${X}`),Z=Y.filter(Boolean).length>0,ae=JSON.stringify({id:C.id,strategy:C.strategy,targets:C.targets.map(P=>({ref:P.ref,weight:String(P?.weight||"1")}))}),Se=JSON.stringify({id:X,strategy:T?.strategy,targets:(T?.targets||[]).map(P=>({ref:String(P?.ref||"").trim(),weight:String(P?.weight||"1").trim()}))}),U=ae!==Se,ne=X?Ak.test(X)?F?"Alias id already exists. Choose another id.":q?"Fill or remove blank target rows before applying.":V?"Duplicate targets are not allowed anywhere in this alias.":_e?"Target weights must be positive integers.":he?"An alias cannot target itself.":"":"Alias id must start with a letter or number and use letters, numbers, dots, underscores, colons, or hyphens.":"Alias id is required.",ue=i?s:ne,me=i?s:b&&ne&&!k?"":ne,re=i||c,oe=String(X||e||"").trim(),Ne=oe||"Select alias",Re=re||z||p,Ze=z?"Default alias cannot be removed":`Remove alias ${oe||e}`,gt=(0,E.useMemo)(()=>eh(Ne),[Ne]),Vt=z||a===e||a===X,sn=o===e||o===X,ot=p?"Enter alias name. Example: claude-opus":void 0,mo=(0,E.useMemo)(()=>eL({...T,fallbackTargets:[]},{...t,fallbackTargets:[]},r),[T,t,r]);async function Ge(){if(I(!0),ue)return!1;let P=await u(e,{...T,fallbackTargets:[]});return P&&p&&g(e),P}async function qr(P){let Ye={...T,strategy:P};return await u(e,{...Ye,fallbackTargets:[]})?p?(g(e),!0):(w(Ye),!0):!1}async function cn(){if(I(!0),ue)return!1;let P=await u(e,{...T,fallbackTargets:[]});return P&&(M(!1),I(!1)),P}function $e(){if(m)return;if(!Q){M(!1);return}let P=String(e||"").trim(),Ye=String(T?.id||"").trim();if(!Ye||Ye===P){w(Ht=>({...Ht,id:P})),M(!1),I(!1);return}cn()}function Ee(P){if(P.key==="Escape"){P.preventDefault(),w(Ye=>({...Ye,id:C.id})),M(!1),I(!1);return}!m&&P.key==="Enter"&&(P.preventDefault(),P.currentTarget.blur())}async function fe(){if(ee){let P=String(e||"").trim(),Ye=String(T?.id||"").trim();if(!Ye||Ye===P){w(Ht=>({...Ht,id:P})),M(!1),I(!1);return}await cn();return}M(!0)}let ge=(0,l.jsxs)("div",{className:"space-y-4",children:[(0,l.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[(0,l.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,l.jsx)("div",{className:"flex min-w-0 flex-wrap items-center gap-2",children:Q?(0,l.jsxs)("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-2",children:[(0,l.jsxs)("div",{className:W("flex h-9 min-w-0 max-w-full overflow-hidden rounded-lg border border-input bg-background/80 shadow-sm transition focus-within:border-ring focus-within:ring-2 focus-within:ring-ring/40",ee?"flex-1":"w-fit"),children:[(0,l.jsx)("div",{className:"flex shrink-0 items-center border-r border-border/70 bg-secondary/55 px-2.5 text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Select an alias"}),ee?(0,l.jsx)(Dt,{ref:H,value:T.id,placeholder:ot,onChange:P=>w(Ye=>({...Ye,id:P.target.value})),onBlur:$e,onKeyDown:Ee,disabled:re||z,className:"h-full min-w-[12rem] flex-1 rounded-none border-0 bg-transparent px-3 text-sm font-medium shadow-none focus:border-transparent focus:ring-0"}):(0,l.jsxs)(vr,{value:h.value||void 0,onValueChange:h.onValueChange,children:[(0,l.jsx)(br,{className:"h-full min-w-[10rem] flex-none rounded-none border-0 bg-transparent px-3 pr-[50px] text-left text-sm font-medium shadow-none focus:border-transparent focus:ring-0",style:{width:`${gt}px`,maxWidth:"100%"},children:(0,l.jsx)(xr,{placeholder:"Select alias"})}),(0,l.jsx)(Sr,{children:h.entries.map(([P,Ye])=>(0,l.jsx)(ar,{value:P,searchText:`${P} ${(Ye?.targets||[]).length} ${(Ye?.fallbackTargets||[]).length}`,children:P},P))})]}),ee?null:(0,l.jsx)("button",{type:"button",className:"flex h-full w-10 shrink-0 items-center justify-center border-l border-border/70 text-muted-foreground transition hover:bg-accent/60 hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/60 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{d(oe)},disabled:re||!oe,"aria-label":`Copy alias id ${oe}`,title:oe?`Copy alias id ${oe}`:"Alias id is not ready yet",children:(0,l.jsx)(U2,{className:"h-4 w-4 shrink-0"})})]}),(0,l.jsx)(ce,{type:"button",variant:"outline",size:"sm",className:"h-9 w-9 rounded-lg border-border/70 bg-background/70 p-0 text-muted-foreground shadow-none hover:bg-background/90 hover:text-foreground",onMouseDown:P=>{ee&&P.preventDefault()},onClick:()=>{fe()},disabled:re||z,"aria-label":ee?"Save alias id":z?"Default alias id cannot be edited":"Edit alias id",title:ee?"Save alias id":z?"Default alias id cannot be edited":"Edit alias id",children:ee?(0,l.jsx)(I2,{className:"h-4 w-4 shrink-0"}):(0,l.jsx)(Nd,{className:"h-4 w-4 shrink-0"})}),p?null:(0,l.jsx)(ce,{type:"button",variant:"outline",size:"sm",className:"h-9 w-9 rounded-lg border-border/70 bg-background/70 p-0 text-muted-foreground shadow-none hover:border-destructive hover:bg-background/90 hover:text-destructive",onClick:()=>f(e),disabled:Re,"aria-label":Ze,title:Ze,children:(0,l.jsx)(rh,{className:"h-4 w-4 shrink-0"})})]}):(0,l.jsxs)(l.Fragment,{children:[ee?(0,l.jsx)(Dt,{ref:H,autoFocus:p,value:T.id,placeholder:ot,onChange:P=>w(Ye=>({...Ye,id:P.target.value})),onBlur:$e,onKeyDown:Ee,disabled:re||z&&!p,className:"max-w-[22rem] font-semibold"}):z&&!p?(0,l.jsx)("div",{className:"truncate text-base font-semibold text-foreground",children:e}):(0,l.jsxs)("button",{type:"button",className:"group inline-flex max-w-full items-center gap-2 rounded-lg text-left text-base font-semibold text-foreground transition hover:bg-primary/5 hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/60 focus-visible:ring-offset-2 focus-visible:ring-offset-background",onClick:()=>M(!0),disabled:re,"aria-label":"Edit alias id",title:"Edit alias id",children:[(0,l.jsx)("span",{className:"truncate",children:p?X||"New alias":X||e}),(0,l.jsx)(Nd,{className:"h-4 w-4 shrink-0"})]}),y?(0,l.jsx)("div",{className:"min-w-[11rem] max-w-full",children:y}):null]})}),z?null:(0,l.jsxs)("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[Vt?(0,l.jsx)(Tt,{variant:"success",children:"Default route"}):null,sn?(0,l.jsx)(Tt,{variant:"info",children:"AMP default"}):null]})]}),(0,l.jsxs)("div",{className:"flex items-start gap-2 self-start",children:[(0,l.jsxs)(ce,{type:"button",variant:"outline",size:"default",className:"group h-9 gap-0 overflow-hidden rounded-lg border-border/70 bg-background/70 px-0 text-sm font-medium normal-case tracking-normal shadow-none hover:bg-background/90",onClick:()=>x({aliasLabel:X||(p?"New alias":e),strategy:T?.strategy||"auto",entries:mo,disabled:re||!!ue,onSave:qr}),disabled:re,children:[(0,l.jsx)("span",{className:"flex h-full shrink-0 items-center border-r border-border/70 bg-secondary/55 px-2.5 text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Routing stratergy"}),(0,l.jsxs)("span",{className:"inline-flex min-w-0 items-center gap-2 px-3 text-left",children:[(0,l.jsx)("span",{className:"truncate",children:gC(T.strategy||"auto")}),(0,l.jsx)(Nd,{className:"h-4 w-4 shrink-0"})]})]}),!Q&&!p?(0,l.jsx)(ce,{type:"button",variant:"outline",size:"sm",className:"h-9 w-9 rounded-lg border-border/70 bg-background/70 p-0 text-muted-foreground shadow-none hover:border-destructive hover:bg-background/90 hover:text-destructive",onClick:()=>f(e),disabled:Re,"aria-label":Ze,title:Ze,children:(0,l.jsx)(rh,{className:"h-4 w-4 shrink-0"})}):null]})]}),(0,l.jsx)(Q2,{title:"Manage model in alias",rows:T.targets,onChange:P=>w(Ye=>({...Ye,targets:P})),options:te,disabled:re,addLabel:"Add target",emptyLabel:"No targets yet. This alias can stay empty until you wire routes back in.",helperText:"Drag to reorder targets. Weights and metadata stay with the same ref.",draftPlaceholder:"Add a new target",showDraftRow:!0,showDraftFocusButton:!0,showWeightInput:!0,filterOtherSelectedValues:!0,excludedValues:[]}),me?(0,l.jsx)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900",children:me}):null,!me&&z&&!Z?(0,l.jsxs)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900",children:["The fixed ",(0,l.jsx)("code",{children:"default"})," route is empty. Requests routed to ",(0,l.jsx)("code",{children:"default"})," or ",(0,l.jsx)("code",{children:"smart"})," will return 500 until you add a working target."]}):null,p||U?(0,l.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,l.jsx)("div",{children:p?(0,l.jsx)(ce,{type:"button",variant:"ghost",onClick:()=>g(e),disabled:re,children:"Discard"}):null}),(0,l.jsxs)("div",{className:"flex flex-wrap justify-end gap-2",children:[U?(0,l.jsx)(ce,{type:"button",variant:"ghost",onClick:()=>{w(C),I(!1)},disabled:re,children:"Reset"}):null,p||U&&!ue?(0,l.jsx)(ce,{type:"button",onClick:()=>{Ge()},disabled:re,children:c?"Saving\u2026":p?"Create alias":"Apply alias"}):null]})]}):null]});return v?(0,l.jsx)(Xn,{children:(0,l.jsx)(Zn,{className:"space-y-4 p-5",children:ge})}):ge}function oL({aliases:e,config:t,aliasIds:n,routeOptions:r,defaultModel:a,ampDefaultRoute:o,disabledReason:i="",busy:s=!1,onApplyAlias:c,onRemoveAlias:u,onCopyAliasId:f}){let d=Object.entries(e||{}),p=!!i,[m,b]=(0,E.useState)(""),[g,x]=(0,E.useState)(!1),[y,h]=(0,E.useState)(""),v=(0,E.useMemo)(()=>Ik(),[]),[S,C]=(0,E.useState)({open:!1,aliasLabel:"",strategy:"auto",entries:[],disabled:!1,onSave:null});function T(){p||s||b(`draft-${Date.now()}`)}function w(z){(!z||z===m)&&b("")}function R(){b("")}function M({aliasLabel:z="",strategy:te="auto",entries:Y=[],disabled:q=!1,onSave:V=null}){C({open:!0,aliasLabel:z,strategy:te,entries:Y,disabled:q,onSave:V})}function k(){C(z=>({...z,open:!1}))}async function I(z,te){let Y=await c(z,te);if(Y){let q=String(te?.id||z||"").trim()||z;h(q)}return Y}(0,E.useEffect)(()=>{let z=d.map(([te])=>te);if(z.length===0){y&&h("");return}(!y||!z.includes(y))&&h(z[0])},[d,y]);let H=d.find(([z])=>z===y)||d[0]||null,Q=H?.[0]||"",ee=H?.[1]||null,X=d.length>1?{value:Q,onValueChange:h,entries:d}:null;return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(Xn,{children:[(0,l.jsx)(jo,{children:(0,l.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[(0,l.jsx)("div",{className:"space-y-1",children:(0,l.jsx)(Ss,{children:"Model aliases give clients one stable route across multiple provider/models, so you can swap, balance, and fail over without changing client config."})}),(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,l.jsx)(ce,{type:"button",variant:"outline",size:"sm",onClick:()=>x(!0),children:"Help"}),(0,l.jsx)(ce,{type:"button",size:"sm",onClick:T,disabled:p||s,children:s?"Saving\u2026":"Add alias"})]})]})}),(0,l.jsxs)(Zn,{className:"space-y-4",children:[p?(0,l.jsx)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900",children:i}):null,d.length>0?Q&&ee?(0,l.jsx)(iC,{aliasId:Q,alias:ee,aliasIds:n,routeOptions:r,defaultModel:a,ampDefaultRoute:o,disabled:p,disabledReason:i,busy:s,onApply:I,onRemove:u,onCopyAliasId:f,onOpenStrategyModal:M,aliasSwitcher:X,framed:!1},Q):null:(0,l.jsxs)("div",{className:"rounded-2xl border border-dashed border-border px-4 py-6 text-sm text-muted-foreground",children:["No model aliases yet. Add one to expose stable routes like ",(0,l.jsx)("code",{children:"coding"})," or ",(0,l.jsx)("code",{children:"chat.fast"})," in the Web UI."]})]})]}),(0,l.jsx)(Sa,{open:!!m,onClose:R,title:"Add alias",description:"Set a stable client-facing route, choose its strategy, and order the targets it should use.",showCloseButton:!1,contentClassName:"max-h-[92vh] max-w-5xl rounded-2xl border border-border/70 bg-background/98 shadow-[0_32px_120px_rgba(15,23,42,0.48)]",bodyClassName:"max-h-[calc(92vh-5.5rem)]",children:m?(0,l.jsx)(iC,{aliasId:m,alias:v,aliasIds:n,routeOptions:r,defaultModel:a,ampDefaultRoute:o,disabled:p,disabledReason:i,busy:s,onApply:I,onRemove:u,onCopyAliasId:f,isNew:!0,alwaysShowAliasIdInput:!0,showIssueOnSubmitOnly:!0,onDiscard:w,onOpenStrategyModal:M,framed:!1},m):null}),(0,l.jsx)(rL,{open:S.open,onClose:k,onSave:z=>S.onSave?.(z),aliasLabel:S.aliasLabel,initialStrategy:S.strategy,entries:S.entries,disabled:S.disabled}),(0,l.jsx)(aL,{open:g,onClose:()=>x(!1),config:t})]})}function iL({children:e,onClick:t,disabled:n=!1,title:r="",className:a=""}){return(0,l.jsx)("button",{type:"button",className:W("inline-flex items-center rounded-full border border-border bg-background/70 px-2.5 py-1 text-[11px] font-medium tracking-wide text-muted-foreground transition hover:border-primary/35 hover:bg-primary/5 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/60 focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-50",a),onClick:t,disabled:n,title:r,"aria-label":r||void 0,children:e})}function lL({provider:e,onRemove:t,onCopyModelId:n,onApplyProviderDetails:r,onApplyProviderModels:a,onSaveAndCloseEditor:o,disabledReason:i="",busy:s=!1}){let c=(0,E.useMemo)(()=>b2(e),[e]),[u,f]=(0,E.useState)(c),[d,p]=(0,E.useState)(!1),[m,b]=(0,E.useState)(!1),[g,x]=(0,E.useState)(!1),[y,h]=(0,E.useState)("provider"),[v,S]=(0,E.useState)(""),[C,T]=(0,E.useState)(0),[w,R]=(0,E.useState)({isDirty:!1,issue:"",locked:!1,rows:[]}),[M,k]=(0,E.useState)({phase:"",modelStates:{},failedModelIds:[],message:""}),I=(0,E.useRef)(null),H=(0,E.useRef)(null),Q=(0,E.useRef)(null),ee=(0,E.useRef)(null);(0,E.useEffect)(()=>{f(c)},[c]);let z=uo(e)!=="api",te=(Array.isArray(e?.models)?e.models:[]).map(fe=>String(fe?.id||"").trim()).filter(Boolean),Y=vl(e),q=z?"":jk(e?.rateLimits),V=z?[]:Hr(u?.endpoints,u?.endpointDraft),_e=z?[]:xa(u?.rateLimitRows),F=JSON.stringify({id:String(u?.id||"").trim(),name:String(u?.name||"").trim(),credentialInput:String(u?.credentialInput||"").trim(),endpoints:V,endpointDraft:String(u?.endpointDraft||"").trim(),rateLimitRows:K1(u?.rateLimitRows)}),he=JSON.stringify({id:String(c?.id||"").trim(),name:String(c?.name||"").trim(),credentialInput:String(c?.credentialInput||"").trim(),endpoints:ba(c?.endpoints),endpointDraft:String(c?.endpointDraft||"").trim(),rateLimitRows:K1(c?.rateLimitRows)}),Z=F!==he,ae=!!i||s,Se=new Set((Array.isArray(w.rows)?w.rows:[]).map(fe=>String(fe?.id||"").trim()).filter(Boolean)),U=M.failedModelIds.filter(fe=>Se.has(fe)),ne=ae||M.phase==="testing"||M.phase==="saving",ue=z?"":ti(_e,{knownModelIds:te,requireAtLeastOne:!0}),me=i||(String(u?.id||"").trim()?Md.test(String(u?.id||"").trim())?String(u?.name||"").trim()?!z&&V.length===0?"Add at least one endpoint for API Key providers.":!z&&V.some(fe=>!$s(fe))?"All endpoints must start with http:// or https://.":ue:"Provider name is required.":"Provider id must start with a letter and use lowercase letters, digits, or dashes only.":"Provider id is required."),re=z?u:{...u,endpoints:V,endpointDraft:""},oe=!!w.isDirty,Ne=Z||oe,Re=[Z?"provider settings":"",oe?"model list":""].filter(Boolean),Ze=[Z&&me?`Provider: ${me}`:"",oe&&w.issue?`Models: ${w.issue}`:""].filter(Boolean).join(" "),gt=ae||M.phase==="testing"||M.phase==="saving"||Z&&!!me||oe&&(!!w.issue||w.locked)||typeof o!="function";async function Vt(){let fe=await r(e.id,re);return fe&&Ge(),fe}async function sn(fe){let ge=await a(e.id,fe,{providerDraft:Z?re:null,onModelTestStateChange:P=>{k({phase:String(P?.phase||""),modelStates:P?.modelStates&&typeof P.modelStates=="object"?P.modelStates:{},failedModelIds:Array.isArray(P?.failedModelIds)?P.failedModelIds:[],message:String(P?.message||"")})}});return ge&&Ge(),ge}function ot(){f(c)}let mo=(0,E.useCallback)(fe=>{R(fe)},[]);function Ge(){b(!1),x(!1),p(!1),h("provider"),S(""),f(c),R({isDirty:!1,issue:"",locked:!1,rows:[]}),k({phase:"",modelStates:{},failedModelIds:[],message:""})}async function qr(){let fe=(Array.isArray(w.rows)?w.rows:[]).filter(P=>!U.includes(String(P?.id||"").trim()));return fe.length===0&&!Z||await o(e.id,{providerDraft:Z?re:null,modelRows:oe?fe:null,onModelTestStateChange:P=>{k({phase:String(P?.phase||""),modelStates:P?.modelStates&&typeof P.modelStates=="object"?P.modelStates:{},failedModelIds:Array.isArray(P?.failedModelIds)?P.failedModelIds:[],message:String(P?.message||"")})}})?(Ge(),!0):(h("models"),!1)}(0,E.useEffect)(()=>{k({phase:"",modelStates:{},failedModelIds:[],message:""})},[c]),(0,E.useEffect)(()=>{U.length>0||!g||x(!1)},[U,g]),(0,E.useEffect)(()=>{if(!d||y!=="provider"||v!=="endpoint"&&v!=="rate-limit"||typeof window>"u")return;let fe=window.requestAnimationFrame(()=>{let ge=v==="endpoint"?I.current:Q.current,P=v==="endpoint"?H.current:ee.current;ge?.scrollIntoView?.({block:"nearest"}),P?.focus?.(),P?.select?.(),S("")});return()=>window.cancelAnimationFrame(fe)},[d,y,v]);function cn(fe="provider",ge=""){b(!1),x(!1),h(fe),S(ge),fe==="models"&&ge==="models"&&T(P=>P+1),p(!0)}function $e(){if(!ne){if(U.length>0){b(!1),x(!0);return}if(Ne){b(!0);return}Ge()}}async function Ee(){if(gt)return;if(!await o(e.id,{providerDraft:Z?re:null,modelRows:oe?w.rows:null,onModelTestStateChange:ge=>{k({phase:String(ge?.phase||""),modelStates:ge?.modelStates&&typeof ge.modelStates=="object"?ge.modelStates:{},failedModelIds:Array.isArray(ge?.failedModelIds)?ge.failedModelIds:[],message:String(ge?.message||"")})}})){oe&&(b(!1),h("models"));return}Ge()}return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(Xn,{children:(0,l.jsxs)(Zn,{className:"space-y-3 p-5",children:[(0,l.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[(0,l.jsx)("div",{className:"min-w-0 flex-1 px-0.5 py-0.5",children:(0,l.jsxs)("div",{className:"flex flex-wrap items-baseline gap-x-2 gap-y-1",children:[(0,l.jsx)("span",{className:"text-base font-semibold text-foreground",children:e.name||e.id}),(0,l.jsxs)("span",{className:"text-sm text-muted-foreground",children:["(",e.id,")"]})]})}),(0,l.jsxs)("div",{className:"flex items-start gap-2 self-start",children:[(0,l.jsxs)(ce,{type:"button",variant:"outline",size:"sm",className:"gap-1.5 normal-case tracking-normal",onClick:()=>cn("provider"),disabled:ae,"aria-label":`Edit provider ${e.name||e.id}`,title:"Edit provider",children:[(0,l.jsx)(Nd,{className:"h-4 w-4 shrink-0"}),"Edit"]}),(0,l.jsx)(ce,{type:"button",variant:"outline",size:"sm",className:"h-8 w-8 shrink-0 p-0 text-muted-foreground hover:border-destructive/35 hover:bg-destructive/5 hover:text-destructive",onClick:()=>t(e.id),disabled:s,"aria-label":"Remove provider",title:"Remove provider",children:(0,l.jsx)(rh,{className:"h-4 w-4"})})]})]}),te.length>0?(0,l.jsx)("div",{className:"flex flex-wrap gap-2 pt-1",children:te.map(fe=>(0,l.jsx)(iL,{onClick:()=>n?.(fe),title:`Copy model id ${fe}`,className:"max-w-full",children:(0,l.jsx)("span",{className:"truncate",children:fe})},`${e.id}-${fe}`))}):null]})}),(0,l.jsx)(Sa,{open:d,onClose:$e,title:`Edit \xB7 ${e.id}`,description:M.phase==="testing"?M.message||"Testing new models before save.":M.phase==="saving"?M.message||"Saving provider changes.":"Switch between provider settings and model list. Each tab saves independently.",closeDisabled:ne,closeOnBackdrop:!ne,closeOnEscape:!ne,contentClassName:"max-h-[92vh] max-w-5xl rounded-2xl border border-border/70 bg-background/98 shadow-[0_32px_120px_rgba(15,23,42,0.48)]",bodyClassName:"max-h-[calc(92vh-5.5rem)] pb-0",children:(0,l.jsxs)(Vu,{value:y,onValueChange:h,children:[(0,l.jsxs)(Hu,{className:"w-full justify-start",children:[(0,l.jsx)(Or,{value:"provider",children:"Provider"}),(0,l.jsx)(Or,{value:"models",children:"Model list"})]}),(0,l.jsxs)(_r,{forceMount:!0,value:"provider",className:W("space-y-4 pb-4",y!=="provider"?"hidden":null),children:[(0,l.jsx)("div",{className:"rounded-2xl border border-border/70 bg-background/60 p-4",children:(0,l.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,l.jsxs)("div",{children:[(0,l.jsx)("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Provider"}),(0,l.jsx)("div",{className:"mt-1 text-sm text-muted-foreground",children:"Update provider identity and connection settings here."})]}),(0,l.jsx)(Tt,{variant:"outline",children:z?"Subscription":"API Key"})]})}),(0,l.jsxs)("div",{className:W("grid gap-3",z?"md:grid-cols-2":"md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]"),children:[(0,l.jsx)(st,{label:"Provider name",stacked:!0,children:(0,l.jsx)(Dt,{value:u.name,onChange:fe=>f(ge=>({...ge,name:fe.target.value})),disabled:ne})}),(0,l.jsx)(st,{label:"Provider id",hint:"Used in direct routes like provider/model",stacked:!0,children:(0,l.jsx)(Dt,{value:u.id,onChange:fe=>f(ge=>({...ge,id:Vr(fe.target.value)})),disabled:ne})})]}),z?null:(0,l.jsxs)("div",{className:"space-y-3",children:[(0,l.jsx)(st,{label:"API key or env",hint:"Use an env var like OPENAI_API_KEY or paste the direct key.",stacked:!0,children:(0,l.jsx)(Dt,{value:u.credentialInput||"",onChange:fe=>f(ge=>({...ge,credentialInput:fe.target.value})),disabled:ne,placeholder:"Example: OPENAI_API_KEY or sk-..."})}),(0,l.jsx)("div",{ref:I,children:(0,l.jsx)(st,{label:"Endpoints",hint:Y.length>1?"Comma, space, or newline turns into chips. The first endpoint stays active until you re-test this provider.":"Comma, space, or newline turns into chips.",stacked:!0,children:(0,l.jsx)(ah,{values:u.endpoints,onChange:fe=>f(ge=>({...ge,endpoints:fe})),draftValue:u.endpointDraft,onDraftValueChange:fe=>f(ge=>({...ge,endpointDraft:fe})),commitOnBlur:!0,disabled:ne,isValueValid:$s,inputRef:H,inputClassName:"placeholder:text-muted-foreground/55",placeholder:"Click here to type new endpoint",helperText:"Paste one or more endpoints"})})}),(0,l.jsx)("div",{ref:Q,className:"grid gap-3 md:grid-cols-2 xl:grid-cols-[minmax(0,1.35fr)_minmax(0,0.8fr)_minmax(0,0.8fr)_minmax(0,1fr)]",children:(0,l.jsx)("div",{className:"md:col-span-2 xl:col-span-4",children:(0,l.jsx)(st,{label:"Rate limit",stacked:!0,headerAction:(0,l.jsx)(ce,{type:"button",size:"sm",variant:"outline",onClick:()=>f(fe=>({...fe,rateLimitRows:MC(fe.rateLimitRows)})),disabled:ne,children:"Add rate limit"}),children:(0,l.jsx)(OC,{rows:u.rateLimitRows,onChange:fe=>f(ge=>({...ge,rateLimitRows:fe})),availableModelIds:te,disabled:ne,inputRef:ee})})})})]}),me?(0,l.jsx)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900",children:me}):null,(0,l.jsxs)("div",{className:"flex min-h-9 items-center justify-end gap-2",children:[!ne&&Z?(0,l.jsx)(ce,{type:"button",variant:"ghost",onClick:ot,children:"Reset"}):null,Z&&!me?(0,l.jsx)(ce,{type:"button",onClick:()=>{Vt()},disabled:ne,children:M.phase==="saving"||s?"Saving\u2026":"Save provider"}):null]})]}),(0,l.jsx)(_r,{forceMount:!0,value:"models",className:W(y!=="models"?"hidden":null),children:(0,l.jsx)(W2,{provider:e,disabled:!!i,disabledReason:i,busy:s,framed:!1,focusRequest:C,onStateChange:mo,onApply:sn,testStateByModel:M.modelStates,savePhase:M.phase,saveMessage:M.message})})]})}),(0,l.jsx)(z2,{open:m,onKeepEditing:()=>b(!1),onDiscardAndClose:Ge,onSaveAndClose:Ee,saveDisabled:gt,dirtyLabels:Re,details:Ze}),(0,l.jsx)(B2,{open:g,failedModelIds:U,onKeepEditing:()=>x(!1),onRemoveFailedAndClose:qr,removeDisabled:ne||typeof o!="function"})]})}function sL({providers:e,onRemove:t,onCopyModelId:n,onApplyProviderDetails:r,onApplyProviderModels:a,onSaveAndCloseEditor:o,disabledReason:i="",busy:s=!1}){return e.length?(0,l.jsx)("div",{className:"grid gap-4 xl:grid-cols-2",children:e.map(c=>(0,l.jsx)(lL,{provider:c,onRemove:t,onCopyModelId:n,onApplyProviderDetails:r,onApplyProviderModels:a,onSaveAndCloseEditor:o,disabledReason:i,busy:s},c.id))}):(0,l.jsx)(Xn,{children:(0,l.jsx)(Zn,{className:"flex flex-col gap-4 p-5 text-sm text-muted-foreground",children:(0,l.jsx)("div",{children:"No enabled providers are configured yet. Use Add provider to create your first provider, model list, and rate limits."})})})}function cL({providers:e,onAddProvider:t,onRemove:n,onCopyModelId:r,onApplyProviderDetails:a,onApplyProviderModels:o,onSaveAndCloseEditor:i,disabledReason:s="",busy:c=!1}){return(0,l.jsxs)("section",{className:"rounded-2xl border border-border/70 bg-card p-4","aria-label":"Provider models",children:[(0,l.jsxs)("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[(0,l.jsxs)("div",{className:"min-w-0",children:[(0,l.jsx)("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Provider & Models"}),(0,l.jsx)("div",{className:"mt-1 text-sm text-muted-foreground",children:"Manage providers, direct model routes, endpoints, and rate limits in one place."})]}),(0,l.jsx)(ce,{onClick:t,children:"Add provider"})]}),(0,l.jsx)("div",{className:"mt-4",children:(0,l.jsx)(sL,{providers:e,onRemove:n,onCopyModelId:r,onApplyProviderDetails:a,onApplyProviderModels:o,onSaveAndCloseEditor:i,disabledReason:s,busy:c})})]})}function uL({rows:e,routeOptions:t,webSearchSnapshot:n,ampClientUrl:r,ampClientGlobal:a,routingBusy:o,onToggleGlobalRouting:i,onInboundChange:s,onOutboundChange:c,onCreateEntry:u,onRemoveEntry:f,onOpenWebSearchTab:d,onOpenConfigPath:p,onOpenSecretsPath:m,hasMasterKey:b,disabledReason:g,autosaveState:x}){let[y,h]=(0,E.useState)(!1),[v,S]=(0,E.useState)(""),[C,T]=(0,E.useState)(String(t[0]?.value||"").trim()),w=e.some(q=>String(q?.inbound||"").trim()===String(v||"").trim()&&String(v||"").trim()),R=String(v||"").trim()&&String(C||"").trim()&&!w,M=a?.routedViaRouter===!0,k=String(a?.error||"").trim(),I=!!(b&&r&&!g&&!k),H=Number(n?.configuredProviderCount)||0,Q=M&&H===0,ee=g?"warning":x.status==="error"?"danger":x.status==="pending"?"outline":x.status==="saving"?"info":x.savedAt?"success":"outline",X=g?"Needs review":x.status==="error"?"Save failed":x.status==="pending"?"Unsaved":x.status==="saving"?"saving...":x.savedAt?"Saved":"Ready",z=g||(x.status==="error"?x.message:x.status==="pending"?"Unsaved changes queued. Auto-save will run shortly.":x.status==="saving"?"Saving changes...":x.savedAt?`Last saved ${vh(x.savedAt)}.`:"AMP route changes auto-save after valid edits.");async function te(){!R||await u?.({inbound:v,outbound:C})===!1||(h(!1),S(""),T(String(t[0]?.value||"").trim()))}function Y(){h(!0),S(""),T(String(t[0]?.value||"").trim())}return(0,l.jsx)("div",{className:"grid gap-4",children:(0,l.jsxs)(Xn,{children:[(0,l.jsxs)(jo,{className:"flex flex-col gap-3 p-4 pb-0 sm:flex-row sm:items-start sm:justify-between",children:[(0,l.jsxs)("div",{className:"space-y-2",children:[(0,l.jsx)(el,{className:"flex items-center gap-2",children:(0,l.jsx)("span",{children:"Use AMP via LLM Router"})}),(0,l.jsx)(TC,{primaryLabel:"Config file",primaryValue:a?.settingsFilePath||"",onOpenPrimary:p,secondaryLabel:"Secrets file",secondaryValue:a?.secretsFilePath||"",secondaryIcon:(0,l.jsx)(q2,{className:"h-3 w-3"}),onOpenSecondary:m})]}),(0,l.jsx)("div",{className:"flex shrink-0 flex-wrap items-center gap-2",children:(0,l.jsx)(ce,{type:"button",size:"sm",variant:M?"outline":void 0,onClick:i,disabled:o!==""||!M&&!I,children:o==="enable"?"Connecting\u2026":o==="disable"?"Disconnecting\u2026":M?"Disconnect":"Connect"})})]}),(0,l.jsxs)(Zn,{className:"space-y-4 p-4",children:[k?(0,l.jsx)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900",children:k}):null,!M&&!b?(0,l.jsxs)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800",children:["Set ",(0,l.jsx)("code",{children:"masterKey"})," first to connect AMP."]}):null,Q?(0,l.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-3 rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900",children:[(0,l.jsx)("div",{className:"max-w-3xl",children:"AMP is connected, but no alternative web search provider is configured. AMP web search is only available through the shared Web Search tab."}),(0,l.jsx)(ce,{type:"button",size:"sm",variant:"outline",onClick:d,children:"Open Web Search"})]}):null,g?(0,l.jsx)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800",children:g}):(0,l.jsxs)("div",{className:"space-y-3 rounded-2xl border border-border/70 bg-background/60 p-4",children:[(0,l.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,l.jsxs)("div",{children:[(0,l.jsx)("div",{className:"text-sm font-medium text-foreground",children:"Route mapping editor"}),(0,l.jsx)("div",{className:"mt-1 text-xs text-muted-foreground",children:"Map built-in AMP route keys and wildcard model matches to managed routes."})]}),(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,l.jsx)(Tt,{variant:ee,children:X}),(0,l.jsxs)(Tt,{variant:"outline",children:[e.length," routes"]}),(0,l.jsx)(ce,{type:"button",size:"sm",onClick:Y,children:"Add custom mapping"})]})]}),(0,l.jsx)("div",{className:"text-xs text-muted-foreground",children:z}),y?(0,l.jsx)("div",{className:"rounded-2xl border border-dashed border-border bg-background/80 p-3",children:(0,l.jsxs)("div",{className:"grid gap-3 xl:grid-cols-[160px_minmax(0,1fr)_minmax(0,1fr)] xl:items-start",children:[(0,l.jsxs)("div",{className:"space-y-2",children:[(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,l.jsx)("div",{className:"text-sm font-medium text-foreground",children:"Add custom mapping"}),(0,l.jsx)(Tt,{variant:"info",children:"Custom"})]}),(0,l.jsxs)("div",{className:"text-xs leading-5 text-muted-foreground",children:["Match a built-in AMP route key like ",(0,l.jsx)("code",{children:"smart"})," or a wildcard such as ",(0,l.jsx)("code",{children:"gpt-*-codex*"}),", then send it to any managed route."]}),(0,l.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,l.jsx)(ce,{type:"button",size:"sm",onClick:te,disabled:!R,children:"Create mapping"}),(0,l.jsx)(ce,{type:"button",size:"sm",variant:"ghost",onClick:()=>h(!1),children:"Close"})]})]}),(0,l.jsx)(st,{label:"Inbound match",hint:"Built-in route key or AMP model pattern",children:(0,l.jsx)(Dt,{value:v,onChange:q=>S(q.target.value),placeholder:"smart or gpt-*-codex*"})}),(0,l.jsx)(st,{label:"Route target",hint:"Alias or provider/model route in LLM Router",children:(0,l.jsxs)(vr,{value:C||void 0,onValueChange:T,children:[(0,l.jsx)(br,{children:(0,l.jsx)(xr,{placeholder:"Select local route"})}),(0,l.jsx)(Sr,{children:Bd(t,{keyPrefix:"amp-route-create",includeHint:!0})})]})})]})}):null,(0,l.jsx)("div",{className:"space-y-2",children:e.map(q=>(0,l.jsx)("div",{className:"rounded-2xl border border-border/70 bg-background/75 p-3",children:(0,l.jsxs)("div",{className:"grid gap-3 xl:grid-cols-[160px_minmax(0,1fr)_minmax(0,1fr)] xl:items-start",children:[(0,l.jsxs)("div",{className:"space-y-2",children:[(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,l.jsx)("div",{className:"text-sm font-medium text-foreground",children:q.label}),q.isCustom?(0,l.jsx)(Tt,{variant:"info",children:"Custom"}):null]}),(0,l.jsx)("div",{className:"text-xs leading-5 text-muted-foreground",children:q.description}),q.removable?(0,l.jsx)(ce,{type:"button",size:"sm",variant:"ghost",onClick:()=>f(q.id),children:"Remove"}):null]}),(0,l.jsx)(st,{label:"Inbound wildcard",hint:q.defaultMatch?`Default: ${q.defaultMatch}`:"AMP model pattern",children:(0,l.jsx)(jg,{commitOnBlur:!0,value:q.inbound,onValueCommit:V=>s(q.id,V),placeholder:q.defaultMatch||"gpt-*-codex*",onKeyDown:V=>{V.key==="Enter"&&(V.preventDefault(),V.currentTarget.blur())}})}),(0,l.jsx)(st,{label:"Target route",hint:"Alias or provider/model route",children:(0,l.jsxs)(vr,{value:q.outbound||"__default__",onValueChange:V=>c(q.id,V),children:[(0,l.jsx)(br,{children:(0,l.jsx)(xr,{placeholder:q.removable?"Choose target route":"Use default route"})}),(0,l.jsxs)(Sr,{children:[q.removable?null:(0,l.jsx)(ar,{value:"__default__",children:"Use default route"}),Bd(t,{keyPrefix:`amp-route-${q.id}`,includeHint:!0})]})]})})]})},q.id))})]})]})]})})}function dL({open:e=!1,onClose:t=()=>{},candidates:n=[],onTestAndAdd:r=async()=>{},disabledReason:a=""}){let[o,i]=(0,E.useState)(""),[s,c]=(0,E.useState)(""),[u,f]=(0,E.useState)(!1),[d,p]=(0,E.useState)(""),m=Array.isArray(n)?n:[],b=m.find(v=>v.providerId===o)||m[0]||null,g=Array.isArray(b?.models)?b.models:[];(0,E.useEffect)(()=>{if(!e){f(!1),p("");return}let v=m[0]?.providerId||"";i(S=>m.some(T=>T.providerId===S)?S:v)},[e,m]),(0,E.useEffect)(()=>{let v=g[0]?.value||"";c(S=>g.some(T=>T.value===S)?S:v)},[g]);let x=yl(o,s),y=e&&!u&&!a&&o&&s;async function h(){if(y){f(!0),p("");try{await r({providerId:o,modelId:s}),t()}catch(v){p(v instanceof Error?v.message:String(v))}finally{f(!1)}}}return(0,l.jsx)(Sa,{open:e,onClose:()=>{u||t()},title:"Add ChatGPT Search Endpoint",description:"Choose a configured OpenAI-compatible GPT route. Test runs a live Responses API request with the native web search tool, then saves the route on success.",contentClassName:"max-h-[92vh] max-w-3xl rounded-2xl border border-border/70 bg-background/98 shadow-[0_32px_120px_rgba(15,23,42,0.48)]",showCloseButton:!1,footer:(0,l.jsxs)("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[(0,l.jsx)(ce,{type:"button",variant:"ghost",onClick:t,disabled:u,children:"Cancel"}),(0,l.jsx)(ce,{type:"button",onClick:()=>{h()},disabled:!y,children:u?"Testing\u2026":"Test connection"})]}),children:(0,l.jsxs)("div",{className:"space-y-4",children:[a?(0,l.jsx)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900",children:a}):null,!a&&m.length===0?(0,l.jsx)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900",children:"No configured OpenAI-compatible GPT providers are available yet. Add a provider with a GPT model first."}):null,m.length>0?(0,l.jsxs)("div",{className:"grid gap-3 md:grid-cols-2",children:[(0,l.jsx)(st,{label:"Provider",hint:"Configured provider or ChatGPT subscription",stacked:!0,children:(0,l.jsxs)(vr,{value:o||void 0,onValueChange:i,disabled:u||!!a,children:[(0,l.jsx)(br,{children:(0,l.jsx)(xr,{placeholder:"Choose provider"})}),(0,l.jsx)(Sr,{children:m.map(v=>(0,l.jsx)(ar,{value:v.providerId,children:v.providerLabel},v.providerId))})]})}),(0,l.jsx)(st,{label:"GPT model",hint:"Only GPT models on OpenAI-compatible routes are listed",stacked:!0,children:(0,l.jsxs)(vr,{value:s||void 0,onValueChange:c,disabled:u||!!a||g.length===0,children:[(0,l.jsx)(br,{children:(0,l.jsx)(xr,{placeholder:"Choose model"})}),(0,l.jsx)(Sr,{children:g.map(v=>(0,l.jsx)(ar,{value:v.value,children:v.label},v.routeId))})]})})]}):null,x?(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/70 px-4 py-3",children:[(0,l.jsx)("div",{className:"text-[11px] font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Saved route id"}),(0,l.jsx)("div",{className:"mt-1 text-sm font-medium text-foreground",children:x}),(0,l.jsx)("div",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:"This route stores only the provider/model reference. No separate API key or quota is saved here."})]}):null,d?(0,l.jsx)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900",children:d}):null]})})}function fL({webSearchConfig:e,webSearchProviders:t,hostedSearchCandidates:n,onWebSearchStrategyChange:r,onWebSearchProviderChange:a,onWebSearchProviderMove:o,onRemoveWebSearchProvider:i,onAddHostedSearchEndpoint:s,disabledReason:c,autosaveState:u}){let[f,d]=(0,E.useState)(!1),p=String(e?.strategy||"ordered").trim()==="quota-balance"?"quota-balance":"ordered",m=Array.isArray(n)&&n.some(g=>Array.isArray(g?.models)&&g.models.length>0),b=c||(u.status==="error"?u.message:u.status==="pending"?"Unsaved changes queued. Auto-save will run shortly.":u.status==="saving"?"Saving changes...":u.savedAt?`Last saved ${vh(u.savedAt)}.`:"");return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(Xn,{children:[(0,l.jsxs)(jo,{className:"flex flex-col gap-4 p-4 pb-0 xl:flex-row xl:items-start xl:justify-between",children:[(0,l.jsxs)("div",{className:"space-y-1",children:[(0,l.jsx)(el,{children:"Web Search"}),(0,l.jsx)(Ss,{className:"text-xs leading-5",children:"Shared web search routing for AMP and other router-managed tools."}),b?(0,l.jsx)("div",{className:"text-xs text-muted-foreground",children:b}):null]}),(0,l.jsxs)("div",{className:"flex w-full shrink-0 flex-wrap items-end justify-end gap-3 xl:w-auto",children:[(0,l.jsxs)("div",{className:"min-w-[12rem] space-y-1",children:[(0,l.jsx)("div",{className:"text-[11px] font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Routing strategy"}),(0,l.jsxs)(vr,{value:p,onValueChange:r,disabled:!!c,children:[(0,l.jsx)(br,{children:(0,l.jsx)(xr,{placeholder:"Choose strategy"})}),(0,l.jsx)(Sr,{children:Ek.map(g=>(0,l.jsx)(ar,{value:g.value,children:g.label},g.value))})]})]}),(0,l.jsxs)(ce,{type:"button",variant:"outline",className:"gap-2",onClick:()=>d(!0),disabled:!!c||!m,children:[(0,l.jsx)(pC,{className:"h-3.5 w-3.5"}),(0,l.jsx)("span",{children:"Endpoint"})]})]})]}),(0,l.jsx)(Zn,{className:"space-y-4 p-4",children:(0,l.jsx)("div",{className:"space-y-3",children:(t||[]).map(g=>{if(g.kind==="hosted"){let h=g.runtimeState&&g.runtimeState.ready===!1?"This provider/model route is no longer available or is not OpenAI-compatible.":"";return(0,l.jsx)("div",{className:"rounded-2xl border border-border/70 bg-background/80 p-4",children:(0,l.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,l.jsxs)("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-start xl:justify-between",children:[(0,l.jsxs)("div",{className:"min-w-0",children:[(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,l.jsx)(q1,{active:g.active}),(0,l.jsx)("div",{className:"text-sm font-medium text-foreground",children:g.label}),(0,l.jsx)(Tt,{variant:"outline",children:"GPT Search"})]}),(0,l.jsx)("div",{className:"mt-1 text-xs break-all text-muted-foreground",children:g.routeId}),(0,l.jsx)("div",{className:"mt-2 text-xs leading-5 text-muted-foreground",children:"Uses the provider's native OpenAI Responses web search tool. No local API key or quota is stored here."})]}),(0,l.jsxs)("div",{className:"flex items-center gap-2 self-start",children:[(0,l.jsxs)("div",{className:"flex items-center gap-2 rounded-xl border border-border/70 bg-background/70 p-1",children:[(0,l.jsx)(Ks,{disabled:!!c||g.displayIndex<=0,label:`Move ${g.routeId} up`,onClick:()=>o(g.id,"up")}),(0,l.jsx)(kd,{disabled:!!c||g.displayIndex>=g.displayCount-1,label:`Move ${g.routeId} down`,onClick:()=>o(g.id,"down")})]}),(0,l.jsx)(ce,{type:"button",size:"sm",variant:"ghost",onClick:()=>i(g.id),disabled:!!c,children:"Remove"})]})]}),h?(0,l.jsx)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900",children:h}):null]})},g.key)}let x=g.credentialField,y=String(g?.credentialValue||"").trim();return(0,l.jsx)("div",{className:"rounded-2xl border border-border/70 bg-background/80 p-4",children:(0,l.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,l.jsxs)("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-start xl:justify-between",children:[(0,l.jsx)("div",{className:"min-w-0",children:(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,l.jsx)(q1,{active:g.active}),(0,l.jsx)("div",{className:"text-sm font-medium text-foreground",children:g.label})]})}),(0,l.jsxs)("div",{className:"flex items-center gap-2 self-start rounded-xl border border-border/70 bg-background/70 p-1",children:[(0,l.jsx)(Ks,{disabled:!!c||g.displayIndex<=0,label:`Move ${g.label} up`,onClick:()=>o(g.id,"up")}),(0,l.jsx)(kd,{disabled:!!c||g.displayIndex>=g.displayCount-1,label:`Move ${g.label} down`,onClick:()=>o(g.id,"down")})]})]}),(0,l.jsxs)("div",{className:"grid gap-3 lg:grid-cols-[minmax(0,0.9fr)_minmax(0,1.35fr)]",children:[(0,l.jsx)(st,{label:g.credentialLabel,hint:g.credentialField==="url"?"Required to enable this backend.":"Required to enable this backend. Stored in router config.",stacked:!0,className:"gap-1",headerClassName:"min-h-0",hintClassName:"leading-4",children:(0,l.jsx)(jg,{type:g.credentialField==="url"?"text":"password",autoComplete:"off",value:y,placeholder:g.credentialPlaceholder,onValueChange:h=>a(g.id,x,h),disabled:!!c})}),(0,l.jsxs)("div",{className:"grid gap-3 sm:grid-cols-3",children:[(0,l.jsx)(st,{label:"Result per call",hint:"Empty keeps the default of 5.",stacked:!0,className:"gap-1",headerClassName:"min-h-0",hintClassName:"leading-4",children:(0,l.jsx)(Yg,{value:g.resultPerCallInput,placeholder:"Default: 5",allowEmptyCommit:!0,onValueChange:h=>a(g.id,"count",h),disabled:!!c})}),(0,l.jsx)(st,{label:"Monthly limit",hint:"0 keeps quotas self-managed.",stacked:!0,className:"gap-1",headerClassName:"min-h-0",hintClassName:"leading-4",children:(0,l.jsx)(Yg,{value:String(g.limit||0),onValueChange:h=>a(g.id,"limit",h),disabled:!!c})}),(0,l.jsx)(st,{label:"Synced remaining",hint:"Adjust after manual upstream sync.",stacked:!0,className:"gap-1",headerClassName:"min-h-0",hintClassName:"leading-4",children:(0,l.jsx)(Yg,{value:String(g.remaining||0),onValueChange:h=>a(g.id,"remaining",h),disabled:!!c})})]})]})]})},g.key)})})})]}),(0,l.jsx)(dL,{open:f,onClose:()=>d(!1),candidates:n,onTestAndAdd:s,disabledReason:c})]})}function lC({toolName:e,toolState:t,endpointUrl:n,routeOptions:r,connectionBusy:a,bindingBusy:o,onToggleRouting:i,onBindingChange:s,hasMasterKey:c,disabledReason:u,onOpenPrimaryPath:f,onOpenSecondaryPath:d,secondaryPathLabel:p="Backup file",secondaryPathIcon:m=(0,l.jsx)(EC,{className:"h-3 w-3"}),bindingFields:b=[],guideContent:g=null}){let x=t?.routedViaRouter===!0,y=String(t?.error||"").trim(),h=!!(c&&n&&!u&&!y),v=(0,E.useMemo)(()=>{let C=new Set(["__unset__"]);for(let T of b){for(let w of Array.isArray(T?.extraOptions)?T.extraOptions:[]){let R=String(w?.value||"").trim();R&&C.add(R)}for(let w of Array.isArray(T?.options)?T.options:[]){let R=String(w?.value||"").trim();R&&C.add(R)}}return b.filter(T=>T?.usesRouteOptions!==!1).map(T=>String(T?.value||"").trim()).filter(T=>T&&!C.has(T))},[b]),S=Fs(r,v);return(0,l.jsxs)(Xn,{children:[(0,l.jsxs)(jo,{className:"flex flex-col gap-3 p-4 pb-0 sm:flex-row sm:items-start sm:justify-between",children:[(0,l.jsxs)("div",{className:"space-y-2",children:[(0,l.jsx)(el,{className:"flex items-center gap-2",children:(0,l.jsx)("span",{children:`Use ${e} via LLM Router`})}),(0,l.jsx)(TC,{primaryLabel:"Config file",primaryValue:t?.configFilePath||t?.settingsFilePath||"",onOpenPrimary:f,secondaryLabel:p,secondaryValue:t?.backupFilePath||"",secondaryIcon:m,onOpenSecondary:d})]}),(0,l.jsxs)("div",{className:"flex shrink-0 flex-wrap items-center gap-2",children:[g?(0,l.jsx)(pL,{guideContent:g}):null,(0,l.jsx)(ce,{type:"button",size:"sm",variant:x?"outline":void 0,onClick:i,disabled:a!==""||!x&&!h,children:a==="enable"?"Connecting\u2026":a==="disable"?"Disconnecting\u2026":x?"Disconnect":"Connect"})]})]}),(0,l.jsxs)(Zn,{className:"space-y-4 p-4",children:[y?(0,l.jsx)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900",children:y}):null,!x&&!c?(0,l.jsxs)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800",children:["Set ",(0,l.jsx)("code",{children:"masterKey"})," first to connect ",e,"."]}):null,u?(0,l.jsx)("div",{className:"rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800",children:u}):null,(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/60 p-4",children:[(0,l.jsx)("div",{children:(0,l.jsxs)("div",{children:[(0,l.jsx)("div",{className:"text-sm font-medium text-foreground",children:"Model bindings"}),(0,l.jsx)("div",{className:"mt-1 text-xs text-muted-foreground",children:"Prefer LLM Router aliases here so you can retarget models later from the Alias & Fallback tab."})]})}),b.length===0?(0,l.jsx)("div",{className:"mt-4 rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800",children:"No tool bindings are available yet."}):(0,l.jsx)("div",{className:"mt-4 grid gap-3",children:b.map(C=>(0,l.jsxs)("div",{className:"rounded-xl border border-border/70 bg-background/80 p-3",children:[(0,l.jsxs)("div",{className:"mb-2 flex flex-wrap items-center justify-between gap-2",children:[(0,l.jsx)("div",{className:"text-sm font-medium text-foreground",children:C.label}),(0,l.jsx)(Tt,{variant:"outline",children:C.envKey})]}),(0,l.jsx)("div",{className:"mb-3 text-xs leading-5 text-muted-foreground",children:C.description}),(0,l.jsx)(gL,{field:C,routeOptions:S,disabled:C.standaloneWhenDisconnected?o:!x||o,onValueChange:T=>s(C.id,T==="__unset__"?"":T)})]},C.id))})]})]})]})}function mL(e="outline"){switch(e){case"success":return"border-emerald-200 bg-emerald-50";case"warning":return"border-amber-200 bg-amber-50";case"danger":return"border-rose-200 bg-rose-50";case"info":return"border-sky-200 bg-sky-50";default:return"border-border/70 bg-background/70"}}function sC(e="outline"){switch(e){case"success":return"text-emerald-950";case"warning":return"text-amber-950";case"danger":return"text-rose-950";case"info":return"text-sky-950";default:return"text-foreground"}}function pL({guideContent:e}){let[t,n]=(0,E.useState)(!1),r=String(e?.title||"").trim()||"Guide",a=String(e?.description||"").trim(),o=Array.isArray(e?.badges)?e.badges.filter(Boolean):[],i=Array.isArray(e?.highlights)?e.highlights.filter(Boolean):[],s=Array.isArray(e?.sections)?e.sections.filter(Boolean):[],c=e?.callout&&e.callout.body?e.callout:null,u=c?.variant||"outline";return i.length===0&&s.length===0&&!c?null:(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(ce,{type:"button",size:"sm",variant:"outline","aria-label":r,onClick:()=>n(!0),children:"Guide"}),(0,l.jsx)(Sa,{open:t,onClose:()=>n(!1),title:r,description:a,contentClassName:"max-h-[92vh] max-w-4xl rounded-2xl border border-border/70 bg-background/98 shadow-[0_32px_120px_rgba(15,23,42,0.48)]",bodyClassName:"max-h-[calc(92vh-5.5rem)]",children:(0,l.jsxs)("div",{className:"space-y-4",children:[o.length>0?(0,l.jsx)("div",{className:"flex flex-wrap items-center gap-2",children:o.map((f,d)=>(0,l.jsx)(Tt,{variant:f?.variant||"outline",children:f?.label},`${r}-badge-${d}`))}):null,c?(0,l.jsxs)("div",{className:W("rounded-2xl border p-4",mL(u)),children:[(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,l.jsx)(Tt,{variant:["success","warning","danger","info"].includes(u)?u:"outline",children:u==="success"?"Current best fit":u==="warning"?"Needs attention":u==="info"?"Current behavior":"Guide note"}),(0,l.jsx)("div",{className:W("text-sm font-medium",sC(u)),children:c.title})]}),(0,l.jsx)("div",{className:W("mt-3 text-sm leading-6",sC(u)),children:c.body})]}):null,i.length>0?(0,l.jsx)("div",{className:W("grid gap-4",i.length>2?"md:grid-cols-3":"md:grid-cols-2"),children:i.map((f,d)=>(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/70 p-4",children:[f?.eyebrow?(0,l.jsx)("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:f.eyebrow}):null,(0,l.jsx)("div",{className:"mt-2 text-sm font-medium text-foreground",children:f?.title}),(0,l.jsx)("div",{className:"mt-2 text-sm leading-6 text-muted-foreground",children:f?.body})]},`${r}-highlight-${d}`))}):null,s.map((f,d)=>{let p=Array.isArray(f?.items)?f.items.filter(Boolean):[];return(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/70 p-4",children:[(0,l.jsx)("div",{className:"text-sm font-medium text-foreground",children:f?.title}),f?.description?(0,l.jsx)("div",{className:"mt-2 text-sm leading-6 text-muted-foreground",children:f.description}):null,p.length>0?(0,l.jsx)("div",{className:"mt-3 space-y-3",children:p.map((m,b)=>(0,l.jsxs)("div",{className:"flex gap-3 text-sm leading-6 text-foreground",children:[(0,l.jsx)("span",{className:"mt-2 h-1.5 w-1.5 shrink-0 rounded-full bg-foreground/50"}),(0,l.jsx)("div",{className:"min-w-0",children:m})]},`${r}-section-${d}-item-${b}`))}):null]},`${r}-section-${d}`)})]})})]})}function gL({field:e,routeOptions:t,disabled:n=!1,onValueChange:r}){let a=String(e?.value||"").trim()||(e?.allowUnset?"__unset__":""),o=(0,E.useMemo)(()=>{let i=e?.usesRouteOptions===!1?[]:t,s=Array.isArray(e?.options)?e.options:[],c=Array.isArray(e?.extraOptions)?e.extraOptions:[];return e?.allowUnset?[{value:"__unset__",label:"Inherit tool default",hint:""},...c,...s,...i]:[...c,...s,...i]},[e?.allowUnset,e?.extraOptions,e?.options,e?.usesRouteOptions,t]);return(0,l.jsxs)(vr,{value:a,onValueChange:r,disabled:n||o.length===0,children:[(0,l.jsx)(br,{children:(0,l.jsx)(xr,{placeholder:e.placeholder||"Select a route"})}),(0,l.jsx)(Sr,{children:o.length>0?Bd(o,{keyPrefix:e.id||"binding-option"}):(0,l.jsx)(ar,{value:"__no-route-options",disabled:!0,children:"No routes available"})})]})}function hL({logs:e,activityLogEnabled:t=!0,activityFilter:n="usage",busyAction:r="",onActivityFilterChange:a,onToggleEnabled:o,onClear:i}){let s=Array.isArray(e)?e:[],c=s.filter(f=>n==="all"?!0:V1(f)===n),u=Ad[n]||Ad.usage;return(0,l.jsxs)(Xn,{children:[(0,l.jsx)(jo,{children:(0,l.jsxs)("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[(0,l.jsxs)("div",{className:"space-y-1",children:[(0,l.jsx)(el,{children:"Activity"}),(0,l.jsx)(Ss,{children:t?"Router actions, request fallbacks, and runtime issues stream here.":"Activity logging is paused. Re-enable it to capture router actions, request fallbacks, and runtime issues."})]}),(0,l.jsxs)("div",{className:"flex shrink-0 flex-wrap items-center gap-2",children:[(0,l.jsx)("div",{className:"min-w-[13rem]",children:(0,l.jsxs)(vr,{value:n,onValueChange:a,searchEnabled:!1,children:[(0,l.jsx)(br,{children:(0,l.jsx)(xr,{placeholder:"Filter category"})}),(0,l.jsx)(Sr,{children:yk.map(f=>(0,l.jsx)(ar,{value:f.value,children:f.label},f.value))})]})}),(0,l.jsx)(ce,{type:"button",size:"sm",variant:"outline",onClick:i,disabled:r!==""||!e?.length,children:r==="clear"?"Clearing\u2026":"Clear log"}),(0,l.jsx)(ce,{type:"button",size:"sm",variant:t?"outline":"default",onClick:o,disabled:r!=="",children:r==="toggle"?"Updating\u2026":t?"Disable log":"Enable log"})]})]})}),(0,l.jsx)(Zn,{children:(0,l.jsx)("div",{className:"max-h-[32rem] space-y-3 overflow-auto pr-1",children:c.length?c.map(f=>{let d=V1(f),p=Ad[d]||Ad.usage;return(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/80 px-4 py-3",children:[(0,l.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,l.jsxs)("div",{className:"flex items-center gap-2",children:[(0,l.jsx)("span",{className:W("inline-flex h-2.5 w-2.5 rounded-full ring-4",I1[f.level]||I1.info)}),(0,l.jsx)(Tt,{variant:p.badgeVariant,children:p.label}),(0,l.jsx)("span",{className:"text-sm font-medium text-foreground",children:f.message})]}),(0,l.jsx)("span",{className:"text-xs text-muted-foreground",children:vh(f.time)})]}),f.detail?(0,l.jsx)("div",{className:"mt-2 text-sm leading-6 text-muted-foreground",children:f.detail}):null]},f.id)}):s.length?(0,l.jsxs)("div",{className:"rounded-2xl border border-dashed border-border px-4 py-6 text-sm text-muted-foreground",children:["No ",u.emptyLabel," activity matches the current filter. Switch the dropdown to inspect the hidden categories."]}):(0,l.jsx)("div",{className:"rounded-2xl border border-dashed border-border px-4 py-6 text-sm text-muted-foreground",children:"Activity is quiet. Save config changes or start the router to populate this stream."})})})]})}function ah({values:e,onChange:t,placeholder:n,helperText:r,inputRef:a=null,inputClassName:o="",suggestedValues:i=[],valueStates:s={},draftValue:c="",onDraftValueChange:u=()=>{},commitOnBlur:f=!1,disabled:d=!1,isValueValid:p=m=>!!String(m||"").trim()}){let m=(0,E.useMemo)(()=>ba(e),[e]),[b,g]=(0,E.useState)(""),[x,y]=(0,E.useState)("");function h(w=c,{clearDraft:R=!0}={}){if(d)return!1;let M=Xg(w).filter(I=>p(I));if(M.length===0)return R&&u(""),!1;let k=Array.from(new Set([...m||[],...M]));return JSON.stringify(k)!==JSON.stringify(m||[])&&t(k),R&&u(""),!0}function v(w){d||(t(m.filter(R=>R!==w)),b===w&&(g(""),y("")))}function S(){d||i.length&&(t(Array.from(new Set([...m||[],...i]))),u(""))}function C(w){d||(g(w),y(w))}function T(w=x){if(d)return g(""),y(""),!1;if(!b)return!1;let R=Xg(w).filter(H=>p(H)),M=[],k=!1;for(let H of m||[]){if(H!==b){M.push(H);continue}k||(M.push(...R),k=!0)}let I=Array.from(new Set(M.map(H=>String(H||"").trim()).filter(Boolean)));return JSON.stringify(I)!==JSON.stringify(m||[])&&t(I),g(""),y(""),R.length>0}return(0,E.useEffect)(()=>{!d||!b||(g(""),y(""))},[d,b]),(0,l.jsxs)("div",{className:"space-y-2",children:[(0,l.jsxs)("div",{className:W("flex min-h-11 flex-wrap items-center gap-2 rounded-xl border border-input bg-background/80 px-3 py-2",d?"opacity-80":null),children:[m.map(w=>{let R=s?.[w]||"default",M=R==="success"?"border-emerald-200 bg-emerald-50 text-emerald-900":R==="error"?"border-rose-200 bg-rose-50 text-rose-900":R==="pending"?"border-sky-200 bg-sky-50 text-sky-900":"border-border bg-secondary text-foreground",k=!d&&b===w;return(0,l.jsxs)("span",{className:W("inline-flex max-w-full items-center gap-1 rounded-full border px-2.5 py-1 text-xs",M),children:[k?(0,l.jsx)("input",{autoFocus:!0,className:"min-w-[7rem] bg-transparent text-xs text-foreground outline-none",value:x,onChange:I=>y(I.target.value),onKeyDown:I=>{if(I.key==="Enter"||I.key==="Tab"){I.preventDefault(),T();return}I.key==="Escape"&&(I.preventDefault(),g(""),y(""))},onBlur:()=>{T()}}):(0,l.jsx)("button",{className:"max-w-[16rem] truncate text-left transition hover:text-foreground disabled:cursor-not-allowed disabled:opacity-70",type:"button",onMouseDown:I=>I.preventDefault(),onClick:()=>C(w),disabled:d,title:"Click to edit",children:w}),(0,l.jsx)("button",{className:"text-muted-foreground transition hover:text-foreground disabled:cursor-not-allowed disabled:opacity-60",type:"button",onMouseDown:I=>I.preventDefault(),onClick:()=>v(w),disabled:d,children:"\xD7"})]},w)}),(0,l.jsx)("input",{ref:a,className:W("min-w-[10rem] flex-1 bg-transparent text-sm text-foreground outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-70",o),value:c,disabled:d,onChange:w=>{let R=w.target.value;if(/[\s,]/.test(R)){let M=R.split(/[\s,]+/),k=M.pop()||"";M.length>0&&h(M.join(","),{clearDraft:!1}),u(k);return}u(R)},onKeyDown:w=>{if((w.key===","||w.key===" "||w.key==="Enter"||w.key==="Tab")&&c.trim()){w.preventDefault(),h();return}w.key==="Backspace"&&!c&&m.length>0&&(w.preventDefault(),v(m[m.length-1]))},onPaste:w=>{let R=w.clipboardData?.getData("text")||"";if(/[\s,]/.test(R)){w.preventDefault();let M=R.split(/[\s,]+/).filter(Boolean).filter(k=>p(k));M.length>0&&(t(Array.from(new Set([...m||[],...M]))),u(""));return}w.preventDefault(),u(`${c}${R}`)},onBlur:()=>{if(f&&p(c)){h(c);return}u(c)},placeholder:n}),m.length>0||c?(0,l.jsx)("button",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground transition hover:text-foreground disabled:cursor-not-allowed disabled:opacity-60",type:"button",onMouseDown:w=>w.preventDefault(),onClick:()=>{t([]),u("")},disabled:d,children:"Clear all"}):null]}),(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[r?(0,l.jsx)("span",{children:r}):null,m.length===0&&i.length>0?(0,l.jsx)("button",{className:"font-medium uppercase tracking-[0.16em] text-foreground transition hover:text-primary disabled:cursor-not-allowed disabled:opacity-60",type:"button",onClick:S,disabled:d,children:"Use suggested values"}):null]})]})}function NC(e="rate-limit-draft-row"){return hC({key:e,models:[],requests:"",windowValue:"",windowUnit:ml.api.windowUnit},{keyPrefix:"rate-limit-draft",defaults:ml.api,useDefaults:!1})}function MC(e=[],{keyPrefix:t="rate-limit-draft"}={}){let n=`${t}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;return[...Array.isArray(e)?e:[],NC(n)]}function yL({value:e=[],onChange:t,availableModelIds:n=[],disabled:r=!1}){let a=(0,E.useRef)(null),[o,i]=(0,E.useState)(!1),s=(0,E.useMemo)(()=>Ir(e),[e]),c=s.includes("all"),u=c?[]:s.filter(Boolean),f=c||u.length===0,d=(0,E.useMemo)(()=>ba(n),[n]);(0,E.useEffect)(()=>{if(!o||typeof document>"u")return;function y(h){a.current?.contains(h.target)||i(!1)}return document.addEventListener("mousedown",y),()=>document.removeEventListener("mousedown",y)},[o]);function p(y){t(Ir(y))}function m(y){p(y?["all"]:[])}function b(y,h){let v=h?[...u,y]:u.filter(S=>S!==y);p(v)}function g(y){if(y==="all"){p([]);return}p(u.filter(h=>h!==y))}let x=c?[{key:"all",label:"All model",removable:!0}]:u.length>0?u.map(y=>({key:y,label:y,removable:!0})):[{key:"__implicit-all__",label:"All model",removable:!1,muted:!0}];return(0,l.jsxs)("div",{ref:a,className:"relative space-y-1.5",children:[(0,l.jsxs)("div",{role:"button",tabIndex:r?-1:0,className:W("flex min-h-9 w-full items-center justify-between gap-2 rounded-lg border border-input bg-background/80 px-3 py-1.5 text-left text-sm text-foreground shadow-sm outline-none transition focus:border-ring focus:ring-2 focus:ring-ring/40",r?"cursor-not-allowed opacity-50":"cursor-pointer",o?"border-ring ring-2 ring-ring/40":null),onClick:()=>{r||i(y=>!y)},"aria-expanded":o,"aria-haspopup":"menu",onKeyDown:y=>{if(!r){if(y.key==="Enter"||y.key===" "){y.preventDefault(),i(h=>!h);return}if(y.key==="ArrowDown"){y.preventDefault(),i(!0);return}y.key==="Escape"&&(y.preventDefault(),i(!1))}},children:[(0,l.jsx)("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-1.5",children:x.map(y=>y.removable?(0,l.jsxs)("button",{type:"button",className:"inline-flex max-w-full items-center gap-1 rounded-full border border-border/70 bg-background px-2 py-0.5 text-xs font-medium text-foreground transition hover:border-accent hover:bg-accent",onClick:h=>{h.preventDefault(),h.stopPropagation(),g(y.key)},disabled:r,title:`Remove ${y.label}`,children:[(0,l.jsx)("span",{className:"truncate",children:y.label}),(0,l.jsx)("span",{className:"text-muted-foreground",children:"x"})]},y.key):(0,l.jsx)("span",{className:W("inline-flex max-w-full items-center rounded-full border px-2 py-0.5 text-xs font-medium",y.muted?"border-border/70 bg-secondary/45 text-muted-foreground":"border-border/70 bg-background text-foreground"),children:(0,l.jsx)("span",{className:"truncate",children:y.label})},y.key))}),(0,l.jsx)("span",{className:"text-muted-foreground",children:"\u25BE"})]}),o?(0,l.jsxs)(RC,{open:o,anchorRef:a,preferredSide:"top",desiredHeight:192,className:"p-2",onMouseDown:y=>y.stopPropagation(),onClick:y=>y.stopPropagation(),onKeyDown:y=>{y.key==="Escape"&&(y.preventDefault(),i(!1))},children:[(0,l.jsxs)("label",{className:"flex cursor-pointer items-center gap-2 rounded-lg px-2 py-2 text-sm text-foreground transition hover:bg-secondary/60",children:[(0,l.jsx)("input",{type:"checkbox",className:"h-4 w-4 rounded border-input",checked:c,onChange:y=>m(y.target.checked)}),(0,l.jsx)("span",{children:"All model"})]}),(0,l.jsx)("div",{className:"my-1 border-t border-border/70"}),d.length>0?(0,l.jsx)("div",{children:d.map(y=>(0,l.jsxs)("label",{className:"flex cursor-pointer items-center gap-2 rounded-lg px-2 py-2 text-sm text-foreground transition hover:bg-secondary/60",children:[(0,l.jsx)("input",{type:"checkbox",className:"h-4 w-4 rounded border-input",checked:u.includes(y),onChange:h=>b(y,h.target.checked)}),(0,l.jsx)("span",{className:"truncate",children:y})]},y))}):(0,l.jsx)("div",{className:"px-2 py-2 text-sm text-muted-foreground",children:"No models available yet."})]}):null]})}function OC({rows:e,onChange:t,availableModelIds:n=[],disabled:r=!1,inputRef:a=null,helperText:o="",onValidBlur:i=null}){let s=Array.isArray(e)?e:[],c=(0,E.useRef)(null),u=(0,E.useRef)(s),f=(0,E.useMemo)(()=>ba(n),[n]),d=(0,E.useMemo)(()=>{let h=new Set,v=new Set;for(let S of xa(s)){let C=zs(S);if(C){if(h.has(C)){v.add(C);continue}h.add(C)}}return v},[s]),p=(0,E.useMemo)(()=>s.map(h=>({...NC(h.key),...h,models:Ir(h?.models||[])})),[s]);(0,E.useEffect)(()=>{u.current=s},[s]);function m(h){let v=Array.isArray(h)?h:[];u.current=v,t(v)}function b(h,v){m(s.map(S=>S.key===h?{...S,...v}:S))}function g(h){m(s.filter(v=>v.key!==h))}function x(h){if(Jg(h))return"";let v=Ir(h?.models||[]);if(f.length>0&&v.some(C=>C!=="all"&&!f.includes(C)))return"Use exact provider model ids only.";if($1(h?.requests,0)<=0)return"Requests must be a positive integer.";if($1(h?.windowValue,0)<=0)return"Window size must be a positive integer.";if(!U1.includes(String(h?.windowUnit||"").trim()))return"Window unit is invalid.";let S=zs({requests:h?.requests,windowValue:h?.windowValue,windowUnit:h?.windowUnit});return S&&d.has(S)?"Another row already uses this cap.":""}function y(h){if(!(!i||r)&&!h.currentTarget.contains(h.relatedTarget)){if(typeof window>"u"){let v=xa(u.current);ti(v,{knownModelIds:f,requireAtLeastOne:!0})||i(v);return}window.setTimeout(()=>{if(!c.current||c.current.contains(document.activeElement))return;let v=xa(u.current);ti(v,{knownModelIds:f,requireAtLeastOne:!0})||i(v)},0)}}return(0,l.jsxs)("div",{ref:c,className:"space-y-2.5",onBlurCapture:y,children:[(0,l.jsx)("div",{className:"space-y-2.5",children:p.map((h,v)=>{let S=Jg(h),C=x(h);return(0,l.jsxs)("div",{className:W("rounded-2xl border border-border/70 bg-background/70 p-3",C?"border-amber-200 bg-amber-50/70":null,S?"border-dashed bg-background/80":null),children:[(0,l.jsxs)("div",{className:"grid gap-2.5 xl:grid-cols-[minmax(0,1.5fr)_minmax(0,0.72fr)_minmax(0,0.72fr)_minmax(0,0.86fr)_auto] xl:items-end",children:[(0,l.jsx)(st,{label:"Models",stacked:!0,className:"gap-1",headerClassName:"min-h-0",hintClassName:"leading-4",children:(0,l.jsx)(yL,{value:h.models,onChange:T=>b(h.key,{models:T}),availableModelIds:f,disabled:r})}),(0,l.jsx)(st,{label:"Request",stacked:!0,className:"gap-1",headerClassName:"min-h-0",children:(0,l.jsx)(Dt,{ref:v===0?a:null,value:h.requests,onChange:T=>b(h.key,{requests:T.target.value}),disabled:r,inputMode:"numeric",placeholder:"60"})}),(0,l.jsx)(st,{label:"Window",stacked:!0,className:"gap-1",headerClassName:"min-h-0",children:(0,l.jsx)(Dt,{value:h.windowValue,onChange:T=>b(h.key,{windowValue:T.target.value}),disabled:r,inputMode:"numeric",placeholder:"1"})}),(0,l.jsx)(st,{label:"Unit",stacked:!0,className:"gap-1",headerClassName:"min-h-0",children:(0,l.jsxs)(vr,{value:String(h.windowUnit||"minute"),onValueChange:T=>b(h.key,{windowUnit:T}),disabled:r,children:[(0,l.jsx)(br,{children:(0,l.jsx)(xr,{placeholder:"Window unit"})}),(0,l.jsx)(Sr,{children:U1.map(T=>(0,l.jsx)(ar,{value:T,children:T},`${h.key}-${T}`))})]})}),(0,l.jsx)(ce,{type:"button",variant:"ghost",onClick:()=>g(h.key),disabled:r,className:"xl:self-end",children:"Remove"})]}),C?(0,l.jsx)("div",{className:"mt-2.5 rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900",children:C}):null]},h.key)})}),o?(0,l.jsx)("div",{className:"text-xs leading-5 text-muted-foreground",children:o}):null]})}function vL({rows:e,onChange:t}){let n=mh(e),r=n.length>0?n:[{name:"",value:""}];function a(s,c,u){c==="name"&&Bk(r,u,s)||t(r.map((f,d)=>d===s?{...f,[c]:u}:f))}function o(){t([...r,{name:"",value:""}])}function i(s){let c=r.filter((u,f)=>f!==s);t(c.length>0?c:[{name:"",value:""}])}return(0,l.jsxs)("div",{className:"space-y-2",children:[r.map((s,c)=>(0,l.jsxs)("div",{className:"grid gap-2 md:grid-cols-[minmax(0,0.9fr)_minmax(0,1.3fr)_auto]",children:[(0,l.jsx)(Dt,{value:s.name,onChange:u=>a(c,"name",u.target.value),placeholder:c===0?"User-Agent":"Header name"}),(0,l.jsx)(Dt,{value:s.value,onChange:u=>a(c,"value",u.target.value),placeholder:c===0?ni:"Header value"}),(0,l.jsx)(ce,{type:"button",variant:"ghost",onClick:()=>i(c),children:"Remove"})]},`header-row-${c}`)),(0,l.jsxs)("div",{className:"flex items-center justify-between gap-3 text-xs text-muted-foreground",children:[(0,l.jsx)("span",{children:"User-Agent is included by default. Add more only when a provider needs them."}),(0,l.jsx)(ce,{type:"button",variant:"outline",onClick:o,children:"Add custom header"})]})]})}function co(){return(0,l.jsx)("span",{className:"mr-2 inline-flex h-3.5 w-3.5 animate-spin rounded-full border-2 border-current border-r-transparent align-[-0.125em]"})}function bL({providerId:e,values:t,onChange:n}){let r=(t||[]).map(d=>String(d||"").trim()).filter(Boolean),a=sh(r),o=(0,E.useRef)(""),i=(0,E.useRef)(null);function s(d){n((t||[]).filter(p=>p!==d))}function c(d,p){if(!d||!p||d===p)return;let m=[...t||[]],b=m.indexOf(d),g=m.indexOf(p);if(b===-1||g===-1)return;let[x]=m.splice(b,1);m.splice(g,0,x),n(m)}function u(d){n(ih(t||[],d,p=>String(p||"").trim()))}function f(){o.current="",pl(i.current,!1),i.current=null}return(0,l.jsxs)("div",{className:"space-y-2",children:[(0,l.jsx)("div",{className:"space-y-2 rounded-xl border border-input bg-background/80 px-3 py-3",children:r.length>0?r.map((d,p)=>(0,l.jsxs)("div",{ref:a(d),"data-reorder-row":"true",onDragOver:m=>{o.current&&o.current!==d&&(m.preventDefault(),m.dataTransfer.dropEffect="move")},onDrop:m=>{m.preventDefault();let b=m.dataTransfer.getData("text/plain")||o.current;f(),c(b,d)},className:W("grid grid-cols-[auto_auto_minmax(0,1fr)_auto] items-center gap-2 rounded-xl border border-border/70 bg-card/90 p-3"),children:[(0,l.jsx)("span",{className:"flex h-8 w-8 cursor-grab items-center justify-center rounded-full text-muted-foreground",draggable:!0,onDragStart:m=>{let b=lh(m.currentTarget);m.dataTransfer.effectAllowed="move",m.dataTransfer.setData("text/plain",d),b&&typeof m.dataTransfer?.setDragImage=="function"&&m.dataTransfer.setDragImage(b,20,20),f(),o.current=d,i.current=b,pl(b,!0)},onDragEnd:f,title:"Drag to reorder",children:(0,l.jsx)(ch,{className:"h-4 w-4"})}),(0,l.jsx)(Ks,{disabled:p===0,label:p===0?"Already first":`Move ${e}/${d} up`,onClick:()=>u(d)}),(0,l.jsxs)("span",{className:"truncate text-sm font-medium text-foreground",children:[e,"/",d]}),(0,l.jsx)("button",{className:"text-muted-foreground transition hover:text-foreground",type:"button",onMouseDown:m=>m.preventDefault(),onClick:()=>s(d),children:"\xD7"})]},d)):(0,l.jsxs)("span",{className:"block px-1 text-xs text-muted-foreground",children:["Leave it empty for now, or add models to back the fixed ",(0,l.jsx)("code",{children:"default"})," route. An empty default route returns 500 until you add a working model."]})}),(0,l.jsx)("div",{className:"text-xs text-muted-foreground",children:"Drag rows to change the preferred order, use the arrow to move a model earlier, or remove any models you do not want in this route."})]})}function cC({baseConfig:e,onApplyDraft:t,onValidateDraft:n,onSaveDraft:r,onSaveAndStart:a,seedMode:o="blank",mode:i="add",targetProviderId:s="",defaultProviderUserAgent:c=ni,framed:u=!0,showHeader:f=!0}){let[d,p]=(0,E.useState)(0),[m,b]=(0,E.useState)(""),[g,x]=(0,E.useState)(()=>T2(e,{seedMode:o,targetProviderId:s,defaultProviderUserAgent:c})),[y,h]=(0,E.useState)(null),[v,S]=(0,E.useState)(""),[C,T]=(0,E.useState)({}),[w,R]=(0,E.useState)(null),[M,k]=(0,E.useState)(""),[I,H]=(0,E.useState)(!1),[Q,ee]=(0,E.useState)(""),X=(0,E.useRef)(""),z=i==="edit",te=!z&&o==="blank"&&AC(e),Y=[{title:"Provider",detail:"Choose API Key or OAuth first, then enter the provider details needed for that connection type."},{title:"Models",detail:"Add model ids, then configure one or more rate limits for all models or selected models. API Key providers are tested before continue."},{title:"Default",detail:"Order the models behind the fixed `default` route before you finish."}],q=Hr(g.modelIds,g.modelDraft),V=yh(g.aliasModelIds,q),_e=g.connectionType==="api"?Hr(g.endpoints,g.endpointDraft):[],F=(0,E.useMemo)(()=>({...g,endpoints:_e,modelIds:q,aliasModelIds:V,rateLimitRows:xa(g.rateLimitRows)}),[g,_e,q,V]),he=(0,E.useMemo)(()=>ph(g.headerRows||[]),[g.headerRows]),Z=String(g.apiKeyEnv||"").trim(),ae=(0,E.useMemo)(()=>G1(F),[F]),Se=w?.signature===ae?w.result:null,U=Se?.models?.length>0?Se.models:SC(g.connectionType),ne=Vr(g.providerId||g.providerName||"my-provider")||"my-provider",ue=wC(g),me=JSON.stringify({connectionType:g.connectionType,subscriptionProfile:ue}),re=JSON.stringify({apiConnectionSignature:ae,modelIds:q}),oe=y?.signature===re?y.result:null,Ne=g.connectionType!=="api"||!!oe?.ok,Re=(0,E.useMemo)(()=>N2(e,F,oe,{targetProviderId:s}),[e,F,oe,s]),Ze=(0,E.useMemo)(()=>`${JSON.stringify(Re,null,2)}
52
52
  `,[Re]),gt=at,Vt=Y[d],sn=M2(d,F,e,{targetProviderId:s});(0,E.useEffect)(()=>{if(X.current!==re&&(X.current=re,Object.keys(C).length>0&&T({})),g.connectionType!=="api"){y!==null&&h(null),v&&S(""),Object.keys(C).length>0&&T({}),w!==null&&R(null),M&&k("");return}y?.signature&&y.signature!==re&&(h(null),S(""),T({})),w?.signature&&w.signature!==ae&&(R(null),k(""))},[g.connectionType,re,y,v,C,w,M,ae]);function ot(A,D){x(B=>({...B,[A]:D}))}function mo(A){x(D=>{let B=Vr(D.providerName||""),G=Vr(A||"")||"my-provider",$=!D.providerId||D.providerId===B;return{...D,providerName:A,providerId:$?G:D.providerId}})}function Ge(A){S(""),h(null),T({}),R(null),k(""),x(D=>{let B=Ps(D.connectionType),G=Ps(A),$=Array.isArray(e?.providers)?e.providers:[],tt=S2(G.providerId,G.providerName,$),He=D.connectionType==="api"?zd(c):[],ke=A==="api"?zd(c):[],ht=mh(D.headerRows||[]),yt=!D.providerId||D.providerId===B.providerId||D.providerId===Vr(D.providerName||""),Ve=!D.providerName||D.providerName===B.providerName,de=!D.apiKeyEnv||D.apiKeyEnv===B.apiKeyEnv,qe=!D.subscriptionProfile||D.subscriptionProfile===B.subscriptionProfile,un=(D.modelIds||[]).length===0||JSON.stringify(D.modelIds||[])===JSON.stringify(B.modelIds||[]),po=JSON.stringify(ht)===JSON.stringify(He);return{...D,connectionType:A,providerName:Ve?tt.providerName:D.providerName,providerId:yt?tt.providerId:D.providerId,endpoints:A==="api"?(D.endpoints||[]).length>0?D.endpoints:G.endpoints:[],endpointDraft:A==="api"?String(D.endpointDraft||""):"",apiKeyEnv:A==="api"?de?G.apiKeyEnv:D.apiKeyEnv:"",subscriptionProfile:A==="api"?"":qe?G.subscriptionProfile:D.subscriptionProfile,modelIds:un?G.modelIds:D.modelIds,modelContextWindows:un?{}:D.modelContextWindows||{},modelDraft:"",rateLimitRows:A==="api"?G.rateLimitRows:[],headerRows:A==="api"?ht.length===0||po?ke:ht:[]}})}async function qr({force:A=!1,silent:D=!1}={}){if(g.connectionType!=="api")return!1;if(_e.length===0||!Z)return D||k("Add endpoints and an API key or env before checking the model list API."),!1;if(!A&&w?.signature===ae)return!!(w?.result?.models||[]).length;H(!0),D||k("");try{let B=await Nt("/api/config/discover-provider-models",{method:"POST",headers:Ct,body:JSON.stringify({endpoints:_e,...Dd(Z)?{apiKeyEnv:Z}:{apiKey:Z},...Object.keys(he).length>0?{headers:he}:{}})}),G=(B.result?.models||[]).map(ke=>String(ke||"").trim()).filter(Boolean),$={};if(G.length>0)try{let ke=await th(G);$=L2(ke)}catch{$={}}let tt={...B.result&&typeof B.result=="object"?B.result:{},modelContextWindows:$};if(R({signature:ae,result:tt}),G.length>0)return x(ke=>{if(G1(ke)!==ae||ke.connectionType!=="api")return ke;let ht=Array.isArray(ke.modelIds)?ke.modelIds:[],yt=A&&ht.length>0?Array.from(new Set([...ht,...G])):ht.length>0?ht:G,Ve={...ke.modelContextWindows&&typeof ke.modelContextWindows=="object"?ke.modelContextWindows:{},...$};return JSON.stringify(yt)===JSON.stringify(ht)&&JSON.stringify(Ve)===JSON.stringify(ke.modelContextWindows||{})?ke:{...ke,modelIds:yt,modelContextWindows:Ve}}),k(""),!0;let He=(B.result?.warnings||[]).join(" ")||"Model list API did not return any models. Add model ids manually if needed.";return k(He),!1}catch(B){let G=B instanceof Error?B.message:String(B);return k(G),!1}finally{H(!1)}}async function cn(){if(g.connectionType!=="api")return!0;b("test"),S(""),T(Object.fromEntries(q.map(A=>[A,"pending"])));try{let A=await CC("/api/config/test-provider-stream",{method:"POST",headers:Ct,body:JSON.stringify({endpoints:_e,models:q,...Dd(Z)?{apiKeyEnv:Z}:{apiKey:Z},...Object.keys(he).length>0?{headers:he}:{}})},{onMessage:D=>{if(D?.type!=="progress")return;let B=D.event||{};B.phase==="model-done"&&T(G=>({...G,[B.model]:B.confirmed?"success":"error"}))}});return h({signature:re,result:A}),T(D=>{let B={...D},G=new Set(Array.isArray(A?.models)?A.models:[]);for(let $ of q)B[$]=G.has($)?"success":"error";return B}),A?.ok?!0:(S((A?.warnings||[]).join(" ")||"Provider test could not confirm a working endpoint/model combination."),!1)}catch(A){return T(D=>{let B={...D};for(let G of q)(!B[G]||B[G]==="pending")&&(B[G]="error");return B}),S(A instanceof Error?A.message:String(A)),!1}finally{b("")}}(0,E.useEffect)(()=>{d!==1||g.connectionType!=="api"||q.length>0||!Z||_e.length===0||I||w?.signature===ae||qr({silent:!0})},[d,g.connectionType,q.length,Z,_e.length,I,w,ae]);async function $e({force:A=!1}={}){if(g.connectionType==="api"||!A&&Q===me)return!0;b("oauth-login"),S("");try{return await Nt("/api/subscription/login",{method:"POST",headers:Ct,body:JSON.stringify({profileId:ue,providerId:ne,subscriptionType:g.connectionType==="oauth-claude"?"claude-code":"chatgpt-codex"})}),ee(me),!0}catch(D){return S(D instanceof Error?D.message:String(D)),!1}finally{b("")}}async function Ee(){d===0&&g.connectionType!=="api"&&!await $e()||d===1&&g.connectionType==="api"&&!Ne&&!await cn()||p(A=>Math.min(A+1,Y.length-1))}async function fe(A){if((A==="save"||A==="save-start")&&g.connectionType==="api"&&!Ne){S("Finish is available after the provider test succeeds.");return}b(A);try{if(A==="apply"){await t(Ze);return}if(A==="validate"){await n(Ze);return}if(A==="save"){await r(Ze);return}A==="save-start"&&await a(Ze)}finally{b("")}}let ge=v||sn||(d===0&&g.connectionType!=="api"&&Q!==me?"Continue opens the browser sign-in flow for this provider.":d===1&&g.connectionType==="api"&&!Ne?"Continue will test this provider against the entered endpoints and model ids using your API key or env.":Y[d].detail),P=g.connectionType==="oauth-claude"?"Examples: claude-opus-4-6 claude-sonnet-4-6 claude-haiku-4-5":g.connectionType==="oauth-gpt"?"Examples: gpt-5.3-codex gpt-5.2-codex gpt-5.1-codex-mini":(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)("span",{children:["Examples: gpt-4o-mini gpt-4.1-mini",Object.keys(Se?.modelContextWindows||{}).length>0?` \xB7 ${Object.keys(Se?.modelContextWindows||{}).length} context size${Object.keys(Se?.modelContextWindows||{}).length===1?"":"s"} ready`:""]}),(0,l.jsx)("span",{className:"ml-2 text-amber-700",children:"Auto-discovered model ids may be incomplete or inaccurate if the provider is misconfigured. Verify the list and add or remove model ids yourself."})]}),Ye=!te,Ht=z?"Edit provider":te?"Add provider":"Quick start wizard",Gt=z?"Update this provider in place. Change endpoints, model ids, rate limits, alias, or provider id, then save the refreshed config.":te?"Add another provider with endpoints, model ids, rate limits, and a stable alias. API Key providers are auto-tested before save.":"Add the first provider, models list, rate limits, stable alias, and then start the router. API Key providers are auto-tested before save.",Mt=(0,l.jsxs)("div",{className:"space-y-5",children:[(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-secondary/25 px-3 py-3",children:[(0,l.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[Ye?(0,l.jsxs)(Tt,{variant:"outline",className:"px-3 py-1 text-[10px] uppercase tracking-[0.16em]",children:["Step ",d+1," of ",Y.length]}):null,Y.map((A,D)=>(0,l.jsxs)("div",{className:W("inline-flex items-center gap-2 rounded-xl px-3 py-2 ring-1",D===d?"bg-background text-foreground shadow-sm ring-border":D<d?"bg-emerald-50 text-emerald-900 ring-emerald-200":"bg-background/70 text-muted-foreground ring-border/60"),children:[(0,l.jsx)("span",{className:W("inline-flex h-5 w-5 items-center justify-center rounded-full text-[11px] font-semibold",D===d?"bg-primary text-primary-foreground":D<d?"bg-emerald-100 text-emerald-700":"bg-secondary text-secondary-foreground"),children:D+1}),(0,l.jsx)("span",{className:"text-sm font-medium",children:A.title})]},A.title))]}),(0,l.jsxs)("div",{className:"mt-3 flex flex-col gap-1 border-t border-border/60 px-1 pt-3 sm:flex-row sm:items-start sm:justify-between sm:gap-4",children:[(0,l.jsx)("div",{className:"text-sm font-medium text-foreground",children:Vt.title}),(0,l.jsx)("div",{className:"max-w-2xl text-xs leading-5 text-muted-foreground",children:Vt.detail})]})]}),d===0?(0,l.jsxs)("div",{className:"space-y-4",children:[(0,l.jsx)("div",{className:"grid gap-3 md:grid-cols-3",children:dC.map(A=>(0,l.jsxs)("button",{type:"button",className:W("rounded-2xl border px-4 py-3 text-left transition",g.connectionType===A.value?"border-ring bg-background shadow-sm":"border-border/70 bg-background/70 hover:border-border"),onClick:()=>Ge(A.value),children:[(0,l.jsx)("div",{className:"text-sm font-medium text-foreground",children:A.label}),(0,l.jsx)("div",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:A.description})]},A.value))}),(0,l.jsxs)("div",{className:"grid gap-3 md:grid-cols-2",children:[(0,l.jsx)(st,{label:"Provider name",children:(0,l.jsx)(Dt,{value:g.providerName,onChange:A=>mo(A.target.value),placeholder:Ps(g.connectionType).providerName})}),(0,l.jsx)(st,{label:"Provider id",hint:"lowercase-hyphenated",children:(0,l.jsx)(Dt,{value:g.providerId,onChange:A=>ot("providerId",A.target.value),onBlur:()=>ot("providerId",Vr(g.providerId||g.providerName||"my-provider")||"my-provider"),placeholder:Ps(g.connectionType).providerId})})]}),g.connectionType==="api"?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(st,{label:"Endpoints",hint:"comma, space, or newline turns into chips",children:(0,l.jsx)(ah,{values:g.endpoints,onChange:A=>ot("endpoints",A),draftValue:g.endpointDraft,onDraftValueChange:A=>ot("endpointDraft",A),commitOnBlur:!0,isValueValid:$s,placeholder:"Example: https://api.openai.com/v1",helperText:"Paste one or more endpoints"})}),(0,l.jsx)(st,{label:"API key or env",children:(0,l.jsx)(Dt,{value:g.apiKeyEnv,onChange:A=>ot("apiKeyEnv",A.target.value),placeholder:"Example: OPENAI_API_KEY or sk-..."})}),(0,l.jsx)(st,{label:"Custom headers",hint:"User-Agent included by default",children:(0,l.jsx)(vL,{rows:g.headerRows,onChange:A=>ot("headerRows",A)})})]}):(0,l.jsxs)("div",{className:"space-y-3",children:[(0,l.jsx)("div",{className:"rounded-2xl border border-border/70 bg-secondary/45 px-4 py-3 text-sm leading-6 text-muted-foreground",children:"Continue opens the ChatGPT sign-in page in your browser and stores the login for this provider automatically."}),(0,l.jsxs)("div",{className:"rounded-2xl border border-amber-300/60 bg-amber-50/80 px-4 py-3 text-xs leading-5 text-amber-800 dark:border-amber-500/30 dark:bg-amber-950/40 dark:text-amber-300",children:[(0,l.jsx)("span",{className:"font-medium",children:"Heads up:"})," ChatGPT subscriptions (Plus / Pro / Team) are separate from the OpenAI API and are intended for use within OpenAI's own apps. Routing requests through your subscription here may violate OpenAI's terms of service and could result in account restrictions."]})]})]}):null,d===1?(0,l.jsxs)("div",{className:"space-y-4",children:[(0,l.jsx)(st,{label:"Models",hint:"comma, space, or newline turns into chips",children:(0,l.jsx)(ah,{values:g.modelIds,onChange:A=>ot("modelIds",A),draftValue:g.modelDraft,onDraftValueChange:A=>ot("modelDraft",A),commitOnBlur:!0,disabled:m==="test",valueStates:g.connectionType==="api"?C:{},placeholder:"Paste model ids",helperText:P,suggestedValues:U})}),g.connectionType==="api"&&I?(0,l.jsxs)("div",{className:"rounded-2xl border border-sky-200 bg-sky-50 px-4 py-3 text-sm text-sky-900",children:[(0,l.jsxs)("div",{className:"flex items-center gap-2 font-medium",children:[(0,l.jsx)(co,{}),"Loading provider models"]}),(0,l.jsx)("div",{className:"mt-1 text-xs leading-5 text-sky-800/90",children:"LLM Router is checking the provider model list and matching context sizes for the discovered models."})]}):null,g.connectionType==="api"?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(st,{label:"Rate limit",stacked:!0,headerAction:(0,l.jsx)(ce,{type:"button",size:"sm",variant:"outline",onClick:()=>ot("rateLimitRows",MC(g.rateLimitRows)),disabled:m==="test",children:"Add rate limit"}),children:(0,l.jsx)(OC,{rows:g.rateLimitRows,onChange:A=>ot("rateLimitRows",A),availableModelIds:q,disabled:m==="test"})}),(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/80 px-4 py-3 text-sm leading-6 text-muted-foreground",children:["The first model becomes the primary direct route. Add caps for ",(0,l.jsx)("code",{children:"all"})," models or target individual model ids when you need a narrower quota bucket."]})]}):null,g.connectionType==="api"?(0,l.jsxs)("div",{className:W("rounded-2xl border px-4 py-3 text-sm leading-6",oe?.ok?"border-emerald-200 bg-emerald-50 text-emerald-900":oe?"border-amber-200 bg-amber-50 text-amber-900":"border-border/70 bg-background/80 text-muted-foreground"),children:[(0,l.jsx)("div",{className:"text-xs font-medium uppercase tracking-[0.16em]",children:"Provider test"}),(0,l.jsx)("div",{className:"mt-2",children:oe?.ok?`Confirmed ${(oe.models||[]).length} model(s) across ${(oe.workingFormats||[]).join(", ")||"detected formats"}.`:oe?(oe.warnings||[]).join(" ")||"Provider test still needs review.":"Run Provider test before continuing so the wizard can auto-detect the working endpoint format(s)."})]}):null]}):null,d===2?(0,l.jsxs)("div",{className:"space-y-4",children:[(0,l.jsx)("div",{className:"grid gap-3 md:grid-cols-2",children:te||z?(0,l.jsx)(D2,{label:"Use this provider order for the default route",hint:"Updates the fixed `default` alias",checked:g.useAliasAsDefault,onCheckedChange:A=>ot("useAliasAsDefault",A)}):(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/80 px-4 py-3 text-sm text-muted-foreground md:col-span-2",children:["The fixed ",(0,l.jsx)("code",{children:"default"})," route is created automatically. Arrange this provider's models in the order you want clients to try first."]})}),(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/80 px-4 py-3",children:[(0,l.jsx)("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Model order"}),(0,l.jsx)("div",{className:"mt-3",children:(0,l.jsx)(bL,{providerId:ne,values:V,onChange:A=>ot("aliasModelIds",A)})})]}),(0,l.jsxs)("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-4",children:[(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/80 px-4 py-3",children:[(0,l.jsx)("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Provider"}),(0,l.jsx)("div",{className:"mt-2 text-sm font-medium text-foreground",children:ne}),(0,l.jsx)("div",{className:"mt-1 text-xs text-muted-foreground",children:g.providerName})]}),(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/80 px-4 py-3",children:[(0,l.jsx)("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Connection"}),(0,l.jsx)("div",{className:"mt-2 text-sm font-medium text-foreground",children:x2(g.connectionType)}),(0,l.jsx)("div",{className:"mt-1 text-xs text-muted-foreground break-all",children:g.connectionType==="api"?`${_e.length} endpoint candidate(s)`:"Browser sign-in flow"})]}),(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/80 px-4 py-3",children:[(0,l.jsx)("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Models"}),(0,l.jsxs)("div",{className:"mt-2 text-sm font-medium text-foreground",children:[q.length," configured"]}),(0,l.jsx)("div",{className:"mt-1 text-xs text-muted-foreground break-all",children:q.join(", ")||"No models yet"})]}),(0,l.jsxs)("div",{className:"rounded-2xl border border-border/70 bg-background/80 px-4 py-3",children:[(0,l.jsx)("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Default route"}),(0,l.jsx)("div",{className:"mt-2 text-sm font-medium text-foreground break-all",children:gt}),(0,l.jsx)("div",{className:"mt-1 text-xs text-muted-foreground",children:g.useAliasAsDefault?"Requests to `default` and `smart` use this ordered list.":"This provider keeps its direct routes only until you opt it into the fixed default route."})]})]}),g.connectionType==="api"?(0,l.jsxs)("div",{className:W("rounded-2xl border px-4 py-3 text-sm leading-6",Ne?"border-emerald-200 bg-emerald-50 text-emerald-900":"border-amber-200 bg-amber-50 text-amber-900"),children:[(0,l.jsx)("div",{className:"text-xs font-medium uppercase tracking-[0.16em]",children:"Provider test"}),(0,l.jsx)("div",{className:"mt-2",children:Ne?`Using ${(oe?.workingFormats||[]).join(", ")||"detected formats"}. The saved provider keeps the tested endpoint selection and confirmed models.`:"Finish is available after the provider test succeeds."})]}):null]}):null,(0,l.jsxs)("div",{className:"flex flex-col gap-3 border-t border-border/70 pt-4 md:flex-row md:items-start md:justify-between md:gap-4",children:[(0,l.jsx)("div",{className:W("min-w-0 flex-1 text-sm md:max-w-2xl",sn||v?"text-amber-700":"text-muted-foreground"),children:ge}),(0,l.jsxs)("div",{className:"flex shrink-0 flex-wrap items-center gap-2 md:justify-end",children:[d>0?(0,l.jsx)(ce,{variant:"ghost",onClick:()=>p(A=>Math.max(A-1,0)),children:"Back"}):null,d<Y.length-1?(0,l.jsx)(ce,{onClick:()=>{Ee()},disabled:!!sn||m!=="",children:m==="oauth-login"?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(co,{}),"Signing in\u2026"]}):m==="test"?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(co,{}),"Testing provider\u2026"]}):"Continue"}):(0,l.jsx)(ce,{onClick:()=>{fe("save-start")},disabled:!!sn||m!==""||g.connectionType==="api"&&!Ne,children:m==="save-start"?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(co,{}),"Finishing\u2026"]}):"Finish"})]})]})]});return u?(0,l.jsxs)(Xn,{className:"border-dashed",children:[f?(0,l.jsxs)(jo,{children:[(0,l.jsx)(el,{children:Ht}),(0,l.jsx)(Ss,{children:Gt})]}):null,(0,l.jsx)(Zn,{className:"space-y-5",children:Mt})]}):(0,l.jsxs)("div",{className:"space-y-5",children:[f?(0,l.jsxs)("div",{children:[(0,l.jsx)("div",{className:"text-base font-semibold text-foreground",children:Ht}),(0,l.jsx)("div",{className:"mt-1 text-sm leading-6 text-muted-foreground",children:Gt})]}):null,Mt]})}function _C(){let[e,t]=(0,E.useState)(null),[n,r]=(0,E.useState)(""),[a,o]=(0,E.useState)(""),[i,s]=(0,E.useState)(null),[c,u]=(0,E.useState)([]),[f,d]=(0,E.useState)(!0),[p,m]=(0,E.useState)(!1),[b,g]=(0,E.useState)(!1),[x,y]=(0,E.useState)(!1),[h,v]=(0,E.useState)(""),[S,C]=(0,E.useState)(""),[T,w]=(0,E.useState)("model-alias"),[R,M]=(0,E.useState)(!1),[k,I]=(0,E.useState)(!1),[H,Q]=(0,E.useState)(0),[ee,X]=(0,E.useState)(""),[z,te]=(0,E.useState)(""),[Y,q]=(0,E.useState)(""),[V,_e]=(0,E.useState)(!1),[F,he]=(0,E.useState)(!1),[Z,ae]=(0,E.useState)(""),[Se,U]=(0,E.useState)("usage"),[ne,ue]=(0,E.useState)(null),[me,re]=(0,E.useState)({status:"idle",message:"",savedAt:""}),oe=(0,E.useRef)(""),Ne=(0,E.useRef)(""),Re=(0,E.useRef)(null),Ze=(0,E.useRef)(null),gt=(0,E.useRef)(null),Vt=(0,E.useRef)(0),sn=(0,E.useRef)(""),ot=(0,E.useRef)(0);(0,E.useEffect)(()=>{oe.current=n},[n]),(0,E.useEffect)(()=>{Ne.current=a},[a]),(0,E.useEffect)(()=>()=>{gt.current&&(clearTimeout(gt.current),gt.current=null)},[]);let mo=n!==a,Ge=e?.config?.document,qr=i?.summary||e?.config||{},cn=i?.validationMessages||e?.config?.validationMessages||[],$e=(0,E.useMemo)(()=>F1(e?.config?.rawText||"{}",e?.config?.document||{}),[e?.config?.rawText,e?.config?.document]),Ee=(0,E.useMemo)(()=>Vk(n,$e),[n,$e]),fe=(0,E.useMemo)(()=>F1(n,$e),[n,$e]),ge=Ee.parseError?$e:Ee.value,P=(0,E.useMemo)(()=>Array.isArray(ge?.providers)?ge.providers:[],[ge]),Ye=(0,E.useMemo)(()=>ge?.modelAliases&&typeof ge.modelAliases=="object"&&!Array.isArray(ge.modelAliases)?ge.modelAliases:{},[ge]),Ht=(0,E.useMemo)(()=>Q1(ge),[ge]),Gt=Ee.parseError?`Fix the raw JSON parse error first: ${Ee.parseError}`:"",Mt=ge,A=(0,E.useMemo)(()=>Hk(),[]),D=e?.ampClient?.global||{},B=e?.webSearch||e?.ampWebSearch||null,G=e?.codingTools?.codexCli||{},$=e?.codingTools?.claudeCode||{},tt=D?.routedViaRouter===!0,He=G?.routedViaRouter===!0,ke=$?.routedViaRouter===!0,yt=(e?.activityLog||{enabled:!0})?.enabled!==!1,Ve=(0,E.useMemo)(()=>Q1(Mt),[Mt]),de=(0,E.useMemo)(()=>xC(Mt),[Mt]),qe=(0,E.useMemo)(()=>ai(zn(Mt)),[Mt]),un=(0,E.useMemo)(()=>Xk(Mt,B),[Mt,B]),po=(0,E.useMemo)(()=>{let O=new Set((Array.isArray(qe?.providers)?qe.providers:[]).map(N=>en(N?.id)).filter(Boolean));return Qk(Mt,O)},[Mt,qe]),Bn=Ee.parseError?`Fix the raw JSON parse error first: ${Ee.parseError}`:Ve.length===0?"Add at least one alias or provider/model route before configuring AMP.":"",ir=Ee.parseError?`Fix the raw JSON parse error first: ${Ee.parseError}`:"",oi=Ee.parseError?`Fix the raw JSON parse error first: ${Ee.parseError}`:Ht.length===0?"Add at least one alias or provider/model route before configuring coding-tool bindings.":"",zC=(0,E.useMemo)(()=>Fs(Ht,Fg(G?.bindings?.defaultModel)?[]:[G?.bindings?.defaultModel]),[Ht,G?.bindings?.defaultModel]),BC=(0,E.useMemo)(()=>Fs(Ht,[$?.bindings?.primaryModel,$?.bindings?.defaultOpusModel,$?.bindings?.defaultSonnetModel,$?.bindings?.defaultHaikuModel,$?.bindings?.subagentModel]),[Ht,$?.bindings?.primaryModel,$?.bindings?.defaultOpusModel,$?.bindings?.defaultSonnetModel,$?.bindings?.defaultHaikuModel,$?.bindings?.subagentModel]),jd=String(Mt?.amp?.defaultRoute||Mt?.defaultModel||gh(Mt)||"").trim(),dn=String(Mt?.masterKey||e?.config?.document?.masterKey||"").trim(),IC=(0,E.useMemo)(()=>qk(dn),[dn]),Pd=P.length>0,UC=Pd&&k,ii=e?.router?.running===!0,bh=e?.startup?.installed===!0,Vd=h==="start"?"Starting\u2026":h==="stop"?"Stopping\u2026":ii?"Stop server":"Start server",Hd=S==="enable"?"Enabling OS startup\u2026":S==="disable"?"Disabling OS startup\u2026":bh?"Disable OS startup":"Enable OS startup",xh=e?.router?.portBusy?e?.router?.portBusyReason||`Port ${8376} is occupied${e?.router?.listenerPids?.length>0?` by PID${e.router.listenerPids.length===1?"":"s"} ${e.router.listenerPids.join(", ")}`:""}.`:String(e?.router?.lastError||"").trim(),jC=!AC(ge),Sh=P.length>0?"existing":"blank",wh=P[0]?.id||"",Ah=e?.defaults?.providerUserAgent||ni;(0,E.useEffect)(()=>{if(f||p||Ee.parseError)return;if(dn){sn.current="";return}let O=String(e?.config?.rawText||a||"__empty__");sn.current!==O&&(sn.current=O,$C({showSuccessNotice:!1}))},[a,dn,f,Ee.parseError,p,e?.config?.rawText]),(0,E.useEffect)(()=>{if(gt.current&&(clearTimeout(gt.current),gt.current=null),!ne)return;let O=ne.immediate===!0?0:450;return gt.current=setTimeout(()=>{gt.current=null;let N=ne.sequence;re(_=>({..._,status:"saving",message:""})),(async()=>{try{let _=await Nt("/api/amp/apply",{method:"POST",headers:Ct,body:JSON.stringify({rawText:ne.rawText,source:"autosave"})});if(N!==Vt.current)return;wa(_),re({status:"saved",message:"",savedAt:new Date().toISOString()})}catch(_){if(N!==Vt.current)return;let se=_ instanceof Error?_.message:String(_);re({status:"error",message:se,savedAt:""}),j("error",se)}})()},O),()=>{gt.current&&(clearTimeout(gt.current),gt.current=null)}},[ne]);function PC(){I(!0),Q(O=>O+1)}function VC(){PC()}function qd(){I(!1)}(0,E.useEffect)(()=>{!Pd&&k&&I(!1)},[Pd,k]);function j(O,N){ot.current+=1,u(_=>[..._,{id:`notice-${ot.current}`,tone:O,message:N}])}function Ch(O){u(N=>N.filter(_=>_.id!==O))}function wa(O,{preserveDraft:N=!1}={}){t(O);let _=String(O?.config?.rawText||"");if(!N||oe.current===Ne.current){r(_),o(_),M(!1),s({rawText:_,summary:O?.config,validationMessages:O?.config?.validationMessages||[]});return}o(_),_!==Ne.current&&M(!0)}async function lr({preserveDraft:O=!1}={}){let N=await Nt("/api/state");wa(N,{preserveDraft:O})}(0,E.useEffect)(()=>{let O=!1;function N(){Re.current&&(Re.current.close(),Re.current=null)}function _(){Ze.current&&(clearTimeout(Ze.current),Ze.current=null)}function se(){O||Ze.current||(Ze.current=setTimeout(()=>{Ze.current=null,ye({isReconnect:!0})},xk))}function ye({isReconnect:Te=!1}={}){if(O)return;_(),N();let we=new EventSource("/api/events");Re.current=we,we.onopen=()=>{O||Re.current!==we||Te&&lr({preserveDraft:oe.current!==Ne.current}).catch(()=>{})},we.addEventListener("state",it=>{if(!(O||Re.current!==we))try{let nt=JSON.parse(it.data);nt?.snapshot&&wa(nt.snapshot,{preserveDraft:!0})}catch(nt){j("error",nt instanceof Error?nt.message:String(nt))}}),we.addEventListener("log",it=>{if(!(O||Re.current!==we))try{let nt=JSON.parse(it.data);t(be=>be&&{...be,logs:[nt,...be.logs||[]].slice(0,150)})}catch{}}),we.addEventListener("logs",it=>{if(!(O||Re.current!==we))try{let nt=JSON.parse(it.data);t(be=>be&&{...be,...nt?.activityLog?{activityLog:nt.activityLog}:{},logs:Array.isArray(nt?.logs)?nt.logs:[]})}catch{}}),we.onerror=()=>{O||Re.current!==we||(N(),se())}}return(async()=>{try{await lr()}catch(Te){O||j("error",Te instanceof Error?Te.message:String(Te))}finally{O||(d(!1),ye())}})(),()=>{O=!0,_(),N()}},[]);async function Rh(O,{silent:N=!1}={}){g(!0);try{let _=await Nt("/api/config/validate",{method:"POST",headers:Ct,body:JSON.stringify({rawText:O})});return s({rawText:O,summary:_.summary,validationMessages:_.validationMessages||[]}),N||j(O2(_.summary)==="success"?"success":"warning",_.summary.validationSummary),_}catch(_){throw N||j("error",_ instanceof Error?_.message:String(_)),_}finally{g(!1)}}async function $d(O,{successMessage:N="Config saved.",showSuccessNotice:_=!0}={}){m(!0);try{let se=await Nt("/api/config/save",{method:"POST",headers:Ct,body:JSON.stringify({rawText:O})});return wa(se),_&&N&&j("success",N),se}catch(se){throw j("error",se instanceof Error?se.message:String(se)),se}finally{m(!1)}}function go(O,{immediate:N=!1}={}){let _=Vt.current+1;Vt.current=_,ue({sequence:_,rawText:O,immediate:N===!0}),re(se=>({status:"pending",message:"",savedAt:se.savedAt}))}function In(O){r(O),s(null)}async function $r(O,N,_={}){let se=`${JSON.stringify(O,null,2)}
53
53
  `;In(se),M(!1),await $d(se,{successMessage:N,..._})}async function Eh({providerId:O,endpoints:N,newModelIds:_,credentialPayload:se,headers:ye,onModelTestStateChange:Te}){if(!Array.isArray(_)||_.length===0)return Te?.({phase:"",modelStates:{},failedModelIds:[],message:""}),{ok:!0};let we=Object.fromEntries(_.map(be=>[be,"pending"])),it=({phase:be="testing",message:Yt="",failedModelIds:Le=[]}={})=>{Te?.({phase:be,modelStates:{...we},failedModelIds:Le,message:Yt})},nt=()=>`Testing ${_.filter(Yt=>we[Yt]==="success"||we[Yt]==="error").length}/${_.length} new model${_.length===1?"":"s"} for ${O}.`;it({phase:"testing",message:nt()});try{let be=await CC("/api/config/test-provider-stream",{method:"POST",headers:Ct,body:JSON.stringify({endpoints:N,models:_,...se,...ye&&typeof ye=="object"&&!Array.isArray(ye)?{headers:ye}:{}})},{onMessage:ct=>{if(ct?.type!=="progress")return;let sr=ct.event||{};if(sr.phase!=="model-done")return;let Kr=String(sr.model||"").trim();!Kr||!Object.prototype.hasOwnProperty.call(we,Kr)||(we[Kr]=sr.confirmed?"success":"error",it({phase:"testing",message:nt()}))}}),Yt=new Set(Array.isArray(be?.models)?be.models:[]),Le=_.filter(ct=>!Yt.has(ct));for(let ct of _)we[ct]=Yt.has(ct)?"success":"error";if(!be?.ok||Le.length>0){let ct=Le.length>0?`New model test failed for ${O}: ${Le.join(", ")}.`:(be?.warnings||[]).join(" ")||`New model test failed for ${O}.`;return it({phase:"",failedModelIds:Le,message:ct}),j("warning",ct),{ok:!1,failedModelIds:Le,result:be}}return it({phase:"saving",message:`Saving ${_.length} confirmed new model${_.length===1?"":"s"} for ${O}.`}),{ok:!0,failedModelIds:[],result:be}}catch(be){for(let ct of _)we[ct]!=="success"&&(we[ct]="error");let Yt=be instanceof Error?be.message:String(be),Le=_.filter(ct=>we[ct]==="error");return it({phase:"",failedModelIds:Le,message:Yt}),j("error",Yt),{ok:!1,failedModelIds:Le}}}async function HC(O,N,{showSuccessNotice:_=!0}={}){if(Gt)return j("warning",Gt),!1;let se=String(N?.id||"").trim(),ye=String(N?.name||"").trim(),Te=Array.isArray(N?.endpoints)?ba(N.endpoints):Hr([],N?.endpoint||""),we=Array.isArray(N?.rateLimitRows)?xa(N.rateLimitRows):[],it=P.find(ct=>ct?.id===O),nt=uo(it)==="api",be=Rd(it);if(!se)return j("warning","Provider id is required."),!1;if(!Md.test(se))return j("warning","Provider id must start with a letter and use lowercase letters, digits, or dashes only."),!1;if(!ye)return j("warning","Provider name is required."),!1;if(se!==O&&P.some(ct=>ct?.id===se))return j("warning",`Provider id "${se}" already exists.`),!1;if(nt&&Te.length===0)return j("warning","API Key providers require at least one valid http(s) endpoint."),!1;if(nt&&Te.some(ct=>!$s(ct)))return j("warning","One or more endpoints are invalid. Use full http:// or https:// URLs."),!1;let Yt=nt?ti(we,{knownModelIds:be,requireAtLeastOne:!0}):"";if(Yt)return j("warning",Yt),!1;let Le=$g(Ee.value||$e,O,{...N,endpoints:Te,rateLimitRows:we});try{return await $r(Le,`Updated provider ${se}.`,{showSuccessNotice:_}),!0}catch{return!1}}async function qC(O,{providerDraft:N=null,modelRows:_=null,showSuccessNotice:se=!0,onModelTestStateChange:ye=null}={}){if(Gt)return j("warning",Gt),!1;let Te=P.find(Un=>Un?.id===O);if(!Te)return j("error",`Provider '${O}' was not found.`),!1;let we=!!(N&&typeof N=="object"),it=Array.isArray(_);if(!we&&!it)return!0;let nt=uo(Te)==="api",be=we?String(N?.id||"").trim():O,Yt=we?String(N?.name||"").trim():String(Te?.name||O).trim(),Le=we?Array.isArray(N?.endpoints)?ba(N.endpoints):Hr([],N?.endpoint||""):vl(Te),ct=we&&Array.isArray(N?.rateLimitRows)?xa(N.rateLimitRows):[],sr=it?_.map(Un=>({...Un,id:String(Un?.id||"").trim(),contextWindow:so(Un?.contextWindow||"")})).filter(Un=>Un.id):[];if(we){let Un=it?sr.map(jn=>jn.id):Rd(Te);if(!be)return j("warning","Provider id is required."),!1;if(!Md.test(be))return j("warning","Provider id must start with a letter and use lowercase letters, digits, or dashes only."),!1;if(!Yt)return j("warning","Provider name is required."),!1;if(be!==O&&P.some(jn=>jn?.id===be))return j("warning",`Provider id "${be}" already exists.`),!1;if(nt&&Le.length===0)return j("warning","API Key providers require at least one valid http(s) endpoint."),!1;if(nt&&Le.some(jn=>!$s(jn)))return j("warning","One or more endpoints are invalid. Use full http:// or https:// URLs."),!1;let Aa=nt?ti(ct,{knownModelIds:Un,requireAtLeastOne:!0}):"";if(Aa)return j("warning",Aa),!1}if(it){if(sr.length===0)return j("warning","Keep at least one model id on the provider."),!1;if(dh(sr.map(cr=>cr.id)))return j("warning","Model ids must be unique for each provider."),!1;if(sr.some(cr=>{let Ys=String(cr?.contextWindow||"").trim();if(!Ys)return!1;let Gd=Number.parseInt(Ys,10);return!Number.isFinite(Gd)||Gd<=0||String(Gd)!==Ys}))return j("warning","Context windows must be positive integers when set."),!1;let Aa=Rd(Te),jn=sr.map(cr=>cr.id).filter(cr=>!Aa.includes(cr));if(nt&&jn.length>0){if(Le.length===0)return j("warning",`Provider '${be}' needs at least one endpoint before testing new models.`),!1;let cr=Z1(N,Te);if(!cr.apiKey&&!cr.apiKeyEnv)return j("warning",`Provider '${be}' needs an API key or env before testing new models.`),!1;if(!(await Eh({providerId:be,endpoints:Le,newModelIds:jn,credentialPayload:cr,headers:Te?.headers,onModelTestStateChange:ye})).ok)return!1}}let Kr=Ee.value||$e;we&&(Kr=$g(Kr,O,{...N,endpoints:Le,rateLimitRows:ct})),it&&(Kr=qg(Kr,we?be:O,sr));let xR=we&&it?`Updated provider ${be} and saved its model list.`:we?`Updated provider ${be}.`:(()=>{let Un=Rd(Te),Aa=sr.map(jn=>jn.id).filter(jn=>!Un.includes(jn));return Aa.length>0?`Tested ${Aa.length} new model${Aa.length===1?"":"s"} and updated ${be}.`:`Updated models for ${be}.`})();try{return await $r(Kr,xR,{showSuccessNotice:se}),ye?.({phase:"",modelStates:{},failedModelIds:[],message:""}),!0}catch{return!1}}async function $C({showSuccessNotice:O=!1}={}){if(Ee.parseError||String((Ee.value||$e||{}).masterKey||"").trim())return!1;let N=gl(Ee.value||$e||{});N.masterKey=Zg();try{return await $r(N,"Gateway key ready.",{showSuccessNotice:O}),!0}catch{return!1}}async function KC(){if(!dn){j("warning","Gateway key is still generating. Try again in a second.");return}try{await js(dn),j("success","Gateway key copied to clipboard.")}catch(O){j("error",O instanceof Error?O.message:String(O))}}async function FC(){if(!A){j("warning","API endpoint is not ready yet.");return}try{await js(A),j("success","API endpoint copied to clipboard.")}catch(O){j("error",O instanceof Error?O.message:String(O))}}async function GC(O){let N=String(O||"").trim();if(!N){j("warning","Alias id is not ready yet.");return}try{await js(N),j("success",`Alias id ${N} copied to clipboard.`)}catch(_){j("error",_ instanceof Error?_.message:String(_))}}async function li(O,N,{ensureMode:_="none",successMessage:se=""}={}){let ye=String(O||"").trim();if(!ye){j("warning",`${N} is not resolved yet.`);return}try{await Nt("/api/file/open",{method:"POST",headers:Ct,body:JSON.stringify({editorId:"default",filePath:ye,ensureMode:_})}),j("success",se||`Opened ${N} in the default app.`)}catch(Te){j("error",Te instanceof Error?Te.message:String(Te))}}async function YC(O){let N=String(O||"").trim();if(!N){j("warning","Model id is not ready yet.");return}try{await js(N),j("success",`Model id ${N} copied to clipboard.`)}catch(_){j("error",_ instanceof Error?_.message:String(_))}}async function WC(){if(!(typeof window>"u"?!0:window.confirm("Rotate the gateway key? Existing clients using the old key will need the new one. Linked tools like AMP, Codex CLI, and Claude Code will auto-update to the new key.")))return;let N=gl(Ee.value||$e||{});N.masterKey=Zg();try{await $r(N,"Rotated gateway key. Linked tools like AMP, Codex CLI, and Claude Code refreshed automatically.")}catch{}}async function QC(O,N,{providerDraft:_=null,onModelTestStateChange:se=null}={}){if(Gt)return j("warning",Gt),!1;let ye=P.find(Le=>Le?.id===O);if(!ye)return j("error",`Provider '${O}' was not found.`),!1;let Te=(Array.isArray(N)?N:[]).map(Le=>({...Le,id:String(Le?.id||"").trim()})).filter(Le=>Le.id),we=_&&String(_?.id||"").trim()||O,it=_?Array.isArray(_?.endpoints)?ba(_.endpoints):Hr([],_?.endpoint||""):vl(ye),nt=(Array.isArray(ye?.models)?ye.models:[]).map(Le=>String(Le?.id||"").trim()).filter(Boolean),be=Te.map(Le=>Le.id).filter(Le=>!nt.includes(Le));if(uo(ye)==="api"&&be.length>0){if(it.length===0)return j("warning",`Provider '${we}' needs at least one endpoint before testing new models.`),!1;let Le=Z1(_,ye);if(!Le.apiKey&&!Le.apiKeyEnv)return j("warning",`Provider '${we}' needs an API key or env before testing new models.`),!1;if(!(await Eh({providerId:we,endpoints:it,newModelIds:be,credentialPayload:Le,headers:ye?.headers,onModelTestStateChange:se})).ok)return!1}let Yt=qg(Ee.value||$e,O,Te);try{let Le=be.length>0?`Tested ${be.length} new model${be.length===1?"":"s"} and updated ${O}.`:`Updated models for ${O}.`;return await $r(Yt,Le),se?.({phase:"",modelStates:{},failedModelIds:[],message:""}),!0}catch{return!1}}async function XC(O,N){if(Gt)return j("warning",Gt),!1;let _=O1(Ee.value||$e,O,N),se=String(N?.id||O||"").trim()||O;try{return await $r(_,`Updated alias ${se}.`),!0}catch{return!1}}async function ZC(O){if(Gt){j("warning",Gt);return}if(!(typeof window>"u"?!0:window.confirm(`Remove alias "${O}" from the config?`)))return;let _=_1(Ee.value||$e,O);try{await $r(_,`Removed alias ${O}.`)}catch{}}async function xL(O){try{await js(O?.url||""),j("success",`${O?.label||"Endpoint"} copied to clipboard.`)}catch(N){j("error",N instanceof Error?N.message:String(N))}}async function JC(){let N=!(D?.routedViaRouter===!0);if(N){if(Bn){j("warning",Bn);return}if(!dn){j("warning","Gateway key is still generating. Try again in a second.");return}if(!A){j("warning","API endpoint is not ready yet.");return}}X(N?"enable":"disable");try{let _=!1,se;try{se=await Nt("/api/amp/global-route",{method:"POST",headers:Ct,body:JSON.stringify({enabled:N,rawText:N?n:void 0,endpointUrl:A})})}catch(Te){if(Te?.statusCode===404&&N)_=!0,se=await Nt("/api/amp/apply",{method:"POST",headers:Ct,body:JSON.stringify({rawText:n,source:"amp-global-route-compat",patchScope:"global",endpointUrl:A})});else throw Te?.statusCode===404?new Error("Restart the web console so the AMP routing endpoint is available."):Te}await lr({preserveDraft:!N});let ye=N?"AMP connected.":"AMP disconnected.";j("success",_?`${ye} Restart the web console if the AMP status does not refresh.`:ye)}catch(_){j("error",_ instanceof Error?_.message:String(_))}finally{X("")}}function eR(O,N){if(Bn){j("warning",Bn);return}let _=String(N||"").trim(),se=de.find(we=>we.id!==O&&String(we?.inbound||"").trim()===_);if(_&&se){j("warning",`AMP inbound match "${_}" already exists.`);return}let ye=X1(Ee.value||$e,O,{inbound:N}),Te=`${JSON.stringify(ye,null,2)}
54
54
  `;In(Te),go(Te)}function tR(O,N){if(Bn){j("warning",Bn);return}let _=X1(Ee.value||$e,O,{outbound:N==="__default__"?"":N}),se=`${JSON.stringify(_,null,2)}