responses-proxy 0.2.0 → 0.2.1
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.
|
@@ -11,4 +11,4 @@ Error generating stack: `+e.message+`
|
|
|
11
11
|
`)>-1?e.split(`
|
|
12
12
|
`):e}function dd(e,t){let{element:n,datasetIndex:r,index:i}=t,a=e.getDatasetMeta(r).controller,{label:o,value:s}=a.getLabelAndValue(i);return{chart:e,label:o,parsed:a.getParsed(i),raw:e.data.datasets[r].data[i],formattedValue:s,dataset:a.getDataset(),dataIndex:i,datasetIndex:r,element:n}}function fd(e,t){let n=e.chart.ctx,{body:r,footer:i,title:a}=e,{boxWidth:o,boxHeight:s}=t,c=Ia(t.bodyFont),l=Ia(t.titleFont),u=Ia(t.footerFont),d=a.length,f=i.length,p=r.length,m=Fa(t.padding),h=m.height,g=0,_=r.reduce((e,t)=>e+t.before.length+t.lines.length+t.after.length,0);if(_+=e.beforeBody.length+e.afterBody.length,d&&(h+=d*l.lineHeight+(d-1)*t.titleSpacing+t.titleMarginBottom),_){let e=t.displayColors?Math.max(s,c.lineHeight):c.lineHeight;h+=p*e+(_-p)*c.lineHeight+(_-1)*t.bodySpacing}f&&(h+=t.footerMarginTop+f*u.lineHeight+(f-1)*t.footerSpacing);let v=0,y=function(e){g=Math.max(g,n.measureText(e).width+v)};return n.save(),n.font=l.string,Ir(e.title,y),n.font=c.string,Ir(e.beforeBody.concat(e.afterBody),y),v=t.displayColors?o+2+t.boxPadding:0,Ir(r,e=>{Ir(e.before,y),Ir(e.lines,y),Ir(e.after,y)}),v=0,n.font=u.string,Ir(e.footer,y),n.restore(),g+=m.width,{width:g,height:h}}function pd(e,t){let{y:n,height:r}=t;return n<r/2?`top`:n>e.height-r/2?`bottom`:`center`}function md(e,t,n,r){let{x:i,width:a}=r,o=n.caretSize+n.caretPadding;if(e===`left`&&i+a+o>t.width||e===`right`&&i-a-o<0)return!0}function hd(e,t,n,r){let{x:i,width:a}=n,{width:o,chartArea:{left:s,right:c}}=e,l=`center`;return r===`center`?l=i<=(s+c)/2?`left`:`right`:i<=a/2?l=`left`:i>=o-a/2&&(l=`right`),md(l,e,t,n)&&(l=`center`),l}function gd(e,t,n){let r=n.yAlign||t.yAlign||pd(e,n);return{xAlign:n.xAlign||t.xAlign||hd(e,t,n,r),yAlign:r}}function _d(e,t){let{x:n,width:r}=e;return t===`right`?n-=r:t===`center`&&(n-=r/2),n}function vd(e,t,n){let{y:r,height:i}=e;return t===`top`?r+=n:t===`bottom`?r-=i+n:r-=i/2,r}function yd(e,t,n,r){let{caretSize:i,caretPadding:a,cornerRadius:o}=e,{xAlign:s,yAlign:c}=n,l=i+a,{topLeft:u,topRight:d,bottomLeft:f,bottomRight:p}=Pa(o),m=_d(t,s),h=vd(t,c,l);return c===`center`?s===`left`?m+=l:s===`right`&&(m-=l):s===`left`?m-=Math.max(u,f)+i:s===`right`&&(m+=Math.max(d,p)+i),{x:wi(m,0,r.width-t.width),y:wi(h,0,r.height-t.height)}}function bd(e,t,n){let r=Fa(n.padding);return t===`center`?e.x+e.width/2:t===`right`?e.x+e.width-r.right:e.x+r.left}function Z(e){return ld([],ud(e))}function xd(e,t,n){return za(e,{tooltip:t,tooltipItems:n,type:`tooltip`})}function Sd(e,t){let n=t&&t.dataset&&t.dataset.tooltip&&t.dataset.tooltip.callbacks;return n?e.override(n):e}var Cd={beforeTitle:Ar,title(e){if(e.length>0){let t=e[0],n=t.chart.data.labels,r=n?n.length:0;if(this&&this.options&&this.options.mode===`dataset`)return t.dataset.label||``;if(t.label)return t.label;if(r>0&&t.dataIndex<r)return n[t.dataIndex]}return``},afterTitle:Ar,beforeBody:Ar,beforeLabel:Ar,label(e){if(this&&this.options&&this.options.mode===`dataset`)return e.label+`: `+e.formattedValue||e.formattedValue;let t=e.dataset.label||``;t&&(t+=`: `);let n=e.formattedValue;return H(n)||(t+=n),t},labelColor(e){let t=e.chart.getDatasetMeta(e.datasetIndex).controller.getStyle(e.dataIndex);return{borderColor:t.borderColor,backgroundColor:t.backgroundColor,borderWidth:t.borderWidth,borderDash:t.borderDash,borderDashOffset:t.borderDashOffset,borderRadius:0}},labelTextColor(){return this.options.bodyColor},labelPointStyle(e){let t=e.chart.getDatasetMeta(e.datasetIndex).controller.getStyle(e.dataIndex);return{pointStyle:t.pointStyle,rotation:t.rotation}},afterLabel:Ar,afterBody:Ar,beforeFooter:Ar,footer:Ar,afterFooter:Ar};function wd(e,t,n,r){let i=e[t].call(n,r);return i===void 0?Cd[t].call(n,r):i}var Td=class extends Vc{static positioners=cd;constructor(e){super(),this.opacity=0,this._active=[],this._eventPosition=void 0,this._size=void 0,this._cachedAnimations=void 0,this._tooltipItems=[],this.$animations=void 0,this.$context=void 0,this.chart=e.chart,this.options=e.options,this.dataPoints=void 0,this.title=void 0,this.beforeBody=void 0,this.body=void 0,this.afterBody=void 0,this.footer=void 0,this.xAlign=void 0,this.yAlign=void 0,this.x=void 0,this.y=void 0,this.height=void 0,this.width=void 0,this.caretX=void 0,this.caretY=void 0,this.labelColors=void 0,this.labelPointStyles=void 0,this.labelTextColors=void 0}initialize(e){this.options=e,this._cachedAnimations=void 0,this.$context=void 0}_resolveAnimations(){let e=this._cachedAnimations;if(e)return e;let t=this.chart,n=this.options.setContext(this.getContext()),r=n.enabled&&t.options.animation&&n.animations,i=new is(this.chart,r);return r._cacheable&&(this._cachedAnimations=Object.freeze(i)),i}getContext(){return this.$context||=xd(this.chart.getContext(),this,this._tooltipItems)}getTitle(e,t){let{callbacks:n}=t,r=wd(n,`beforeTitle`,this,e),i=wd(n,`title`,this,e),a=wd(n,`afterTitle`,this,e),o=[];return o=ld(o,ud(r)),o=ld(o,ud(i)),o=ld(o,ud(a)),o}getBeforeBody(e,t){return Z(wd(t.callbacks,`beforeBody`,this,e))}getBody(e,t){let{callbacks:n}=t,r=[];return Ir(e,e=>{let t={before:[],lines:[],after:[]},i=Sd(n,e);ld(t.before,ud(wd(i,`beforeLabel`,this,e))),ld(t.lines,wd(i,`label`,this,e)),ld(t.after,ud(wd(i,`afterLabel`,this,e))),r.push(t)}),r}getAfterBody(e,t){return Z(wd(t.callbacks,`afterBody`,this,e))}getFooter(e,t){let{callbacks:n}=t,r=wd(n,`beforeFooter`,this,e),i=wd(n,`footer`,this,e),a=wd(n,`afterFooter`,this,e),o=[];return o=ld(o,ud(r)),o=ld(o,ud(i)),o=ld(o,ud(a)),o}_createItems(e){let t=this._active,n=this.chart.data,r=[],i=[],a=[],o=[],s,c;for(s=0,c=t.length;s<c;++s)o.push(dd(this.chart,t[s]));return e.filter&&(o=o.filter((t,r,i)=>e.filter(t,r,i,n))),e.itemSort&&(o=o.sort((t,r)=>e.itemSort(t,r,n))),Ir(o,t=>{let n=Sd(e.callbacks,t);r.push(wd(n,`labelColor`,this,t)),i.push(wd(n,`labelPointStyle`,this,t)),a.push(wd(n,`labelTextColor`,this,t))}),this.labelColors=r,this.labelPointStyles=i,this.labelTextColors=a,this.dataPoints=o,o}update(e,t){let n=this.options.setContext(this.getContext()),r=this._active,i,a=[];if(!r.length)this.opacity!==0&&(i={opacity:0});else{let e=cd[n.position].call(this,r,this._eventPosition);a=this._createItems(n),this.title=this.getTitle(a,n),this.beforeBody=this.getBeforeBody(a,n),this.body=this.getBody(a,n),this.afterBody=this.getAfterBody(a,n),this.footer=this.getFooter(a,n);let t=this._size=fd(this,n),o=Object.assign({},e,t),s=gd(this.chart,n,o),c=yd(n,o,s,this.chart);this.xAlign=s.xAlign,this.yAlign=s.yAlign,i={opacity:1,x:c.x,y:c.y,width:t.width,height:t.height,caretX:e.x,caretY:e.y}}this._tooltipItems=a,this.$context=void 0,i&&this._resolveAnimations().update(this,i),e&&n.external&&n.external.call(this,{chart:this.chart,tooltip:this,replay:t})}drawCaret(e,t,n,r){let i=this.getCaretPosition(e,n,r);t.lineTo(i.x1,i.y1),t.lineTo(i.x2,i.y2),t.lineTo(i.x3,i.y3)}getCaretPosition(e,t,n){let{xAlign:r,yAlign:i}=this,{caretSize:a,cornerRadius:o}=n,{topLeft:s,topRight:c,bottomLeft:l,bottomRight:u}=Pa(o),{x:d,y:f}=e,{width:p,height:m}=t,h,g,_,v,y,b;return i===`center`?(y=f+m/2,r===`left`?(h=d,g=h-a,v=y+a,b=y-a):(h=d+p,g=h+a,v=y-a,b=y+a),_=h):(g=r===`left`?d+Math.max(s,l)+a:r===`right`?d+p-Math.max(c,u)-a:this.caretX,i===`top`?(v=f,y=v-a,h=g-a,_=g+a):(v=f+m,y=v+a,h=g+a,_=g-a),b=v),{x1:h,x2:g,x3:_,y1:v,y2:y,y3:b}}drawTitle(e,t,n){let r=this.title,i=r.length,a,o,s;if(i){let c=Io(n.rtl,this.x,this.width);for(e.x=bd(this,n.titleAlign,n),t.textAlign=c.textAlign(n.titleAlign),t.textBaseline=`middle`,a=Ia(n.titleFont),o=n.titleSpacing,t.fillStyle=n.titleColor,t.font=a.string,s=0;s<i;++s)t.fillText(r[s],c.x(e.x),e.y+a.lineHeight/2),e.y+=a.lineHeight+o,s+1===i&&(e.y+=n.titleMarginBottom-o)}}_drawColorBox(e,t,n,r,i){let a=this.labelColors[n],o=this.labelPointStyles[n],{boxHeight:s,boxWidth:c}=i,l=Ia(i.bodyFont),u=bd(this,`left`,i),d=r.x(u),f=s<l.lineHeight?(l.lineHeight-s)/2:0,p=t.y+f;if(i.usePointStyle){let t={radius:Math.min(c,s)/2,pointStyle:o.pointStyle,rotation:o.rotation,borderWidth:1},n=r.leftForLtr(d,c)+c/2,l=p+s/2;e.strokeStyle=i.multiKeyBackground,e.fillStyle=i.multiKeyBackground,ga(e,t,n,l),e.strokeStyle=a.borderColor,e.fillStyle=a.backgroundColor,ga(e,t,n,l)}else{e.lineWidth=W(a.borderWidth)?Math.max(...Object.values(a.borderWidth)):a.borderWidth||1,e.strokeStyle=a.borderColor,e.setLineDash(a.borderDash||[]),e.lineDashOffset=a.borderDashOffset||0;let t=r.leftForLtr(d,c),n=r.leftForLtr(r.xPlus(d,1),c-2),o=Pa(a.borderRadius);Object.values(o).some(e=>e!==0)?(e.beginPath(),e.fillStyle=i.multiKeyBackground,Da(e,{x:t,y:p,w:c,h:s,radius:o}),e.fill(),e.stroke(),e.fillStyle=a.backgroundColor,e.beginPath(),Da(e,{x:n,y:p+1,w:c-2,h:s-2,radius:o}),e.fill()):(e.fillStyle=i.multiKeyBackground,e.fillRect(t,p,c,s),e.strokeRect(t,p,c,s),e.fillStyle=a.backgroundColor,e.fillRect(n,p+1,c-2,s-2))}e.fillStyle=this.labelTextColors[n]}drawBody(e,t,n){let{body:r}=this,{bodySpacing:i,bodyAlign:a,displayColors:o,boxHeight:s,boxWidth:c,boxPadding:l}=n,u=Ia(n.bodyFont),d=u.lineHeight,f=0,p=Io(n.rtl,this.x,this.width),m=function(n){t.fillText(n,p.x(e.x+f),e.y+d/2),e.y+=d+i},h=p.textAlign(a),g,_,v,y,b,x,S;for(t.textAlign=a,t.textBaseline=`middle`,t.font=u.string,e.x=bd(this,h,n),t.fillStyle=n.bodyColor,Ir(this.beforeBody,m),f=o&&h!==`right`?a===`center`?c/2+l:c+2+l:0,y=0,x=r.length;y<x;++y){for(g=r[y],_=this.labelTextColors[y],t.fillStyle=_,Ir(g.before,m),v=g.lines,o&&v.length&&(this._drawColorBox(t,e,y,p,n),d=Math.max(u.lineHeight,s)),b=0,S=v.length;b<S;++b)m(v[b]),d=u.lineHeight;Ir(g.after,m)}f=0,d=u.lineHeight,Ir(this.afterBody,m),e.y-=i}drawFooter(e,t,n){let r=this.footer,i=r.length,a,o;if(i){let s=Io(n.rtl,this.x,this.width);for(e.x=bd(this,n.footerAlign,n),e.y+=n.footerMarginTop,t.textAlign=s.textAlign(n.footerAlign),t.textBaseline=`middle`,a=Ia(n.footerFont),t.fillStyle=n.footerColor,t.font=a.string,o=0;o<i;++o)t.fillText(r[o],s.x(e.x),e.y+a.lineHeight/2),e.y+=a.lineHeight+n.footerSpacing}}drawBackground(e,t,n,r){let{xAlign:i,yAlign:a}=this,{x:o,y:s}=e,{width:c,height:l}=n,{topLeft:u,topRight:d,bottomLeft:f,bottomRight:p}=Pa(r.cornerRadius);t.fillStyle=r.backgroundColor,t.strokeStyle=r.borderColor,t.lineWidth=r.borderWidth,t.beginPath(),t.moveTo(o+u,s),a===`top`&&this.drawCaret(e,t,n,r),t.lineTo(o+c-d,s),t.quadraticCurveTo(o+c,s,o+c,s+d),a===`center`&&i===`right`&&this.drawCaret(e,t,n,r),t.lineTo(o+c,s+l-p),t.quadraticCurveTo(o+c,s+l,o+c-p,s+l),a===`bottom`&&this.drawCaret(e,t,n,r),t.lineTo(o+f,s+l),t.quadraticCurveTo(o,s+l,o,s+l-f),a===`center`&&i===`left`&&this.drawCaret(e,t,n,r),t.lineTo(o,s+u),t.quadraticCurveTo(o,s,o+u,s),t.closePath(),t.fill(),r.borderWidth>0&&t.stroke()}_updateAnimationTarget(e){let t=this.chart,n=this.$animations,r=n&&n.x,i=n&&n.y;if(r||i){let n=cd[e.position].call(this,this._active,this._eventPosition);if(!n)return;let a=this._size=fd(this,e),o=Object.assign({},n,this._size),s=gd(t,e,o),c=yd(e,o,s,t);(r._to!==c.x||i._to!==c.y)&&(this.xAlign=s.xAlign,this.yAlign=s.yAlign,this.width=a.width,this.height=a.height,this.caretX=n.x,this.caretY=n.y,this._resolveAnimations().update(this,c))}}_willRender(){return!!this.opacity}draw(e){let t=this.options.setContext(this.getContext()),n=this.opacity;if(!n)return;this._updateAnimationTarget(t);let r={width:this.width,height:this.height},i={x:this.x,y:this.y};n=Math.abs(n)<.001?0:n;let a=Fa(t.padding),o=this.title.length||this.beforeBody.length||this.body.length||this.afterBody.length||this.footer.length;t.enabled&&o&&(e.save(),e.globalAlpha=n,this.drawBackground(i,e,r,t),Lo(e,t.textDirection),i.y+=a.top,this.drawTitle(i,e,t),this.drawBody(i,e,t),this.drawFooter(i,e,t),Ro(e,t.textDirection),e.restore())}getActiveElements(){return this._active||[]}setActiveElements(e,t){let n=this._active,r=e.map(({datasetIndex:e,index:t})=>{let n=this.chart.getDatasetMeta(e);if(!n)throw Error(`Cannot find a dataset at index `+e);return{datasetIndex:e,element:n.data[t],index:t}}),i=!Lr(n,r),a=this._positionChanged(r,t);(i||a)&&(this._active=r,this._eventPosition=t,this._ignoreReplayEvents=!0,this.update(!0))}handleEvent(e,t,n=!0){if(t&&this._ignoreReplayEvents)return!1;this._ignoreReplayEvents=!1;let r=this.options,i=this._active||[],a=this._getActiveElements(e,i,t,n),o=this._positionChanged(a,e),s=t||!Lr(a,i)||o;return s&&(this._active=a,(r.enabled||r.external)&&(this._eventPosition={x:e.x,y:e.y},this.update(!0,t))),s}_getActiveElements(e,t,n,r){let i=this.options;if(e.type===`mouseout`)return[];if(!r)return t.filter(e=>this.chart.data.datasets[e.datasetIndex]&&this.chart.getDatasetMeta(e.datasetIndex).controller.getParsed(e.index)!==void 0);let a=this.chart.getElementsAtEventForMode(e,i.mode,i,n);return i.reverse&&a.reverse(),a}_positionChanged(e,t){let{caretX:n,caretY:r,options:i}=this,a=cd[i.position].call(this,e,t);return a!==!1&&(n!==a.x||r!==a.y)}},Ed={id:`tooltip`,_element:Td,positioners:cd,afterInit(e,t,n){n&&(e.tooltip=new Td({chart:e,options:n}))},beforeUpdate(e,t,n){e.tooltip&&e.tooltip.initialize(n)},reset(e,t,n){e.tooltip&&e.tooltip.initialize(n)},afterDraw(e){let t=e.tooltip;if(t&&t._willRender()){let n={tooltip:t};if(e.notifyPlugins(`beforeTooltipDraw`,{...n,cancelable:!0})===!1)return;t.draw(e.ctx),e.notifyPlugins(`afterTooltipDraw`,n)}},afterEvent(e,t){if(e.tooltip){let n=t.replay;e.tooltip.handleEvent(t.event,n,t.inChartArea)&&(t.changed=!0)}},defaults:{enabled:!0,external:null,position:`average`,backgroundColor:`rgba(0,0,0,0.8)`,titleColor:`#fff`,titleFont:{weight:`bold`},titleSpacing:2,titleMarginBottom:6,titleAlign:`left`,bodyColor:`#fff`,bodySpacing:2,bodyFont:{},bodyAlign:`left`,footerColor:`#fff`,footerSpacing:2,footerMarginTop:6,footerFont:{weight:`bold`},footerAlign:`left`,padding:6,caretPadding:2,caretSize:5,cornerRadius:6,boxHeight:(e,t)=>t.bodyFont.size,boxWidth:(e,t)=>t.bodyFont.size,multiKeyBackground:`#fff`,displayColors:!0,boxPadding:0,borderColor:`rgba(0,0,0,0)`,borderWidth:0,animation:{duration:400,easing:`easeOutQuart`},animations:{numbers:{type:`number`,properties:[`x`,`y`,`width`,`height`,`caretX`,`caretY`]},opacity:{easing:`linear`,duration:200}},callbacks:Cd},defaultRoutes:{bodyFont:`font`,footerFont:`font`,titleFont:`font`},descriptors:{_scriptable:e=>e!==`filter`&&e!==`itemSort`&&e!==`external`,_indexable:!1,callbacks:{_scriptable:!1,_indexable:!1},animation:{_fallback:!1},animations:{_fallback:`animation`}},additionalOptionScopes:[`interaction`]},Dd=(e,t,n,r)=>(typeof t==`string`?(n=e.push(t)-1,r.unshift({index:n,label:t})):isNaN(t)&&(n=null),n);function Od(e,t,n,r){let i=e.indexOf(t);return i===-1?Dd(e,t,n,r):i===e.lastIndexOf(t)?i:n}var kd=(e,t)=>e===null?null:wi(Math.round(e),0,t);function Ad(e){let t=this.getLabels();return e>=0&&e<t.length?t[e]:e}var jd=class extends sl{static id=`category`;static defaults={ticks:{callback:Ad}};constructor(e){super(e),this._startValue=void 0,this._valueRange=0,this._addedLabels=[]}init(e){let t=this._addedLabels;if(t.length){let e=this.getLabels();for(let{index:n,label:r}of t)e[n]===r&&e.splice(n,1);this._addedLabels=[]}super.init(e)}parse(e,t){if(H(e))return null;let n=this.getLabels();return t=isFinite(t)&&n[t]===e?t:Od(n,e,G(t,e),this._addedLabels),kd(t,n.length-1)}determineDataLimits(){let{minDefined:e,maxDefined:t}=this.getUserBounds(),{min:n,max:r}=this.getMinMax(!0);this.options.bounds===`ticks`&&(e||(n=0),t||(r=this.getLabels().length-1)),this.min=n,this.max=r}buildTicks(){let e=this.min,t=this.max,n=this.options.offset,r=[],i=this.getLabels();i=e===0&&t===i.length-1?i:i.slice(e,t+1),this._valueRange=Math.max(i.length-+!n,1),this._startValue=this.min-(n?.5:0);for(let n=e;n<=t;n++)r.push({value:n});return r}getLabelForValue(e){return Ad.call(this,e)}configure(){super.configure(),this.isHorizontal()||(this._reversePixels=!this._reversePixels)}getPixelForValue(e){return typeof e!=`number`&&(e=this.parse(e)),e===null?NaN:this.getPixelForDecimal((e-this._startValue)/this._valueRange)}getPixelForTick(e){let t=this.ticks;return e<0||e>t.length-1?null:this.getPixelForValue(t[e].value)}getValueForPixel(e){return Math.round(this._startValue+this.getDecimalForPixel(e)*this._valueRange)}getBasePixel(){return this.bottom}};function Md(e,t){let n=[],{bounds:r,step:i,min:a,max:o,precision:s,count:c,maxTicks:l,maxDigits:u,includeBounds:d}=e,f=i||1,p=l-1,{min:m,max:h}=t,g=!H(a),_=!H(o),v=!H(c),y=(h-m)/(u+1),b=ui((h-m)/p/f)*f,x,S,C,w;if(b<1e-14&&!g&&!_)return[{value:m},{value:h}];w=Math.ceil(h/b)-Math.floor(m/b),w>p&&(b=ui(w*b/p/f)*f),H(s)||(x=10**s,b=Math.ceil(b*x)/x),r===`ticks`?(S=Math.floor(m/b)*b,C=Math.ceil(h/b)*b):(S=m,C=h),g&&_&&i&&mi((o-a)/i,b/1e3)?(w=Math.round(Math.min((o-a)/b,l)),b=(o-a)/w,S=a,C=o):v?(S=g?a:S,C=_?o:C,w=c-1,b=(C-S)/w):(w=(C-S)/b,w=li(w,Math.round(w),b/1e3)?Math.round(w):Math.ceil(w));let T=Math.max(vi(b),vi(S));x=10**(H(s)?T:s),S=Math.round(S*x)/x,C=Math.round(C*x)/x;let E=0;for(g&&(d&&S!==a?(n.push({value:a}),S<a&&E++,li(Math.round((S+E*b)*x)/x,a,Nd(a,y,e))&&E++):S<a&&E++);E<w;++E){let e=Math.round((S+E*b)*x)/x;if(_&&e>o)break;n.push({value:e})}return _&&d&&C!==o?n.length&&li(n[n.length-1].value,o,Nd(o,y,e))?n[n.length-1].value=o:n.push({value:o}):(!_||C===o)&&n.push({value:C}),n}function Nd(e,t,{horizontal:n,minRotation:r}){let i=gi(r),a=(n?Math.sin(i):Math.cos(i))||.001,o=.75*t*(``+e).length;return Math.min(t/a,o)}var Q=class extends sl{constructor(e){super(e),this.start=void 0,this.end=void 0,this._startValue=void 0,this._endValue=void 0,this._valueRange=0}parse(e,t){return H(e)||(typeof e==`number`||e instanceof Number)&&!isFinite(+e)?null:+e}handleTickRangeOptions(){let{beginAtZero:e}=this.options,{minDefined:t,maxDefined:n}=this.getUserBounds(),{min:r,max:i}=this,a=e=>r=t?r:e,o=e=>i=n?i:e;if(e){let e=ci(r),t=ci(i);e<0&&t<0?o(0):e>0&&t>0&&a(0)}if(r===i){let t=i===0?1:Math.abs(i*.05);o(i+t),e||a(r-t)}this.min=r,this.max=i}getTickLimit(){let{maxTicksLimit:e,stepSize:t}=this.options.ticks,n;return t?(n=Math.ceil(this.max/t)-Math.floor(this.min/t)+1,n>1e3&&(console.warn(`scales.${this.id}.ticks.stepSize: ${t} would result generating up to ${n} ticks. Limiting to 1000.`),n=1e3)):(n=this.computeTickLimit(),e||=11),e&&(n=Math.min(e,n)),n}computeTickLimit(){return 1/0}buildTicks(){let e=this.options,t=e.ticks,n=this.getTickLimit();n=Math.max(2,n);let r=Md({maxTicks:n,bounds:e.bounds,min:e.min,max:e.max,precision:t.precision,step:t.stepSize,count:t.count,maxDigits:this._maxDigits(),horizontal:this.isHorizontal(),minRotation:t.minRotation||0,includeBounds:t.includeBounds!==!1},this._range||this);return e.bounds===`ticks`&&hi(r,this,`value`),e.reverse?(r.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),r}configure(){let e=this.ticks,t=this.min,n=this.max;if(super.configure(),this.options.offset&&e.length){let r=(n-t)/Math.max(e.length-1,1)/2;t-=r,n+=r}this._startValue=t,this._endValue=n,this._valueRange=n-t}getLabelForValue(e){return ta(e,this.chart.options.locale,this.options.ticks.format)}},Pd=class extends Q{static id=`linear`;static defaults={ticks:{callback:ia.formatters.numeric}};determineDataLimits(){let{min:e,max:t}=this.getMinMax(!0);this.min=Mr(e)?e:0,this.max=Mr(t)?t:1,this.handleTickRangeOptions()}computeTickLimit(){let e=this.isHorizontal(),t=e?this.width:this.height,n=gi(this.options.ticks.minRotation),r=(e?Math.sin(n):Math.cos(n))||.001,i=this._resolveTickFontOptions(0);return Math.ceil(t/Math.min(40,i.lineHeight/r))}getPixelForValue(e){return e===null?NaN:this.getPixelForDecimal((e-this._startValue)/this._valueRange)}getValueForPixel(e){return this._startValue+this.getDecimalForPixel(e)*this._valueRange}},Fd=e=>Math.floor(si(e)),Id=(e,t)=>10**(Fd(e)+t);function Ld(e){return e/10**Fd(e)==1}function Rd(e,t,n){let r=10**n,i=Math.floor(e/r);return Math.ceil(t/r)-i}function zd(e,t){let n=Fd(t-e);for(;Rd(e,t,n)>10;)n++;for(;Rd(e,t,n)<10;)n--;return Math.min(n,Fd(e))}function Bd(e,{min:t,max:n}){t=Nr(e.min,t);let r=[],i=Fd(t),a=zd(t,n),o=a<0?10**Math.abs(a):1,s=10**a,c=i>a?10**i:0,l=Math.round((t-c)*o)/o,u=Math.floor((t-c)/s/10)*s*10,d=Math.floor((l-u)/10**a),f=Nr(e.min,Math.round((c+u+d*10**a)*o)/o);for(;f<n;)r.push({value:f,major:Ld(f),significand:d}),d>=10?d=d<15?15:20:d++,d>=20&&(a++,d=2,o=a>=0?1:o),f=Math.round((c+u+d*10**a)*o)/o;let p=Nr(e.max,f);return r.push({value:p,major:Ld(p),significand:d}),r}(class extends sl{static id=`logarithmic`;static defaults={ticks:{callback:ia.formatters.logarithmic,major:{enabled:!0}}};constructor(e){super(e),this.start=void 0,this.end=void 0,this._startValue=void 0,this._valueRange=0}parse(e,t){let n=Q.prototype.parse.apply(this,[e,t]);if(n===0){this._zero=!0;return}return Mr(n)&&n>0?n:null}determineDataLimits(){let{min:e,max:t}=this.getMinMax(!0);this.min=Mr(e)?Math.max(0,e):null,this.max=Mr(t)?Math.max(0,t):null,this.options.beginAtZero&&(this._zero=!0),this._zero&&this.min!==this._suggestedMin&&!Mr(this._userMin)&&(this.min=e===Id(this.min,0)?Id(this.min,-1):Id(this.min,0)),this.handleTickRangeOptions()}handleTickRangeOptions(){let{minDefined:e,maxDefined:t}=this.getUserBounds(),n=this.min,r=this.max,i=t=>n=e?n:t,a=e=>r=t?r:e;n===r&&(n<=0?(i(1),a(10)):(i(Id(n,-1)),a(Id(r,1)))),n<=0&&i(Id(r,-1)),r<=0&&a(Id(n,1)),this.min=n,this.max=r}buildTicks(){let e=this.options,t=Bd({min:this._userMin,max:this._userMax},this);return e.bounds===`ticks`&&hi(t,this,`value`),e.reverse?(t.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),t}getLabelForValue(e){return e===void 0?`0`:ta(e,this.chart.options.locale,this.options.ticks.format)}configure(){let e=this.min;super.configure(),this._startValue=si(e),this._valueRange=si(this.max)-si(e)}getPixelForValue(e){return(e===void 0||e===0)&&(e=this.min),e===null||isNaN(e)?NaN:this.getPixelForDecimal(e===this.min?0:(si(e)-this._startValue)/this._valueRange)}getValueForPixel(e){let t=this.getDecimalForPixel(e);return 10**(this._startValue+t*this._valueRange)}});function Vd(e){let t=e.ticks;if(t.display&&e.display){let e=Fa(t.backdropPadding);return G(t.font&&t.font.size,ua.font.size)+e.height}return 0}function Hd(e,t,n){return n=U(n)?n:[n],{w:pa(e,t.string,n),h:n.length*t.lineHeight}}function Ud(e,t,n,r,i){return e===r||e===i?{start:t-n/2,end:t+n/2}:e<r||e>i?{start:t-n,end:t}:{start:t,end:t+n}}function Wd(e){let t={l:e.left+e._padding.left,r:e.right-e._padding.right,t:e.top+e._padding.top,b:e.bottom-e._padding.bottom},n=Object.assign({},t),r=[],i=[],a=e._pointLabels.length,o=e.options.pointLabels,s=o.centerPointLabels?$r/a:0;for(let c=0;c<a;c++){let a=o.setContext(e.getPointLabelContext(c));i[c]=a.padding;let l=e.getPointPosition(c,e.drawingArea+i[c],s),u=Ia(a.font),d=Hd(e.ctx,u,e._pointLabels[c]);r[c]=d;let f=Si(e.getIndexAngle(c)+s),p=Math.round(_i(f));Gd(n,t,f,Ud(p,l.x,d.w,0,180),Ud(p,l.y,d.h,90,270))}e.setCenterPoint(t.l-n.l,n.r-t.r,t.t-n.t,n.b-t.b),e._pointLabelItems=Jd(e,r,i)}function Gd(e,t,n,r,i){let a=Math.abs(Math.sin(n)),o=Math.abs(Math.cos(n)),s=0,c=0;r.start<t.l?(s=(t.l-r.start)/a,e.l=Math.min(e.l,t.l-s)):r.end>t.r&&(s=(r.end-t.r)/a,e.r=Math.max(e.r,t.r+s)),i.start<t.t?(c=(t.t-i.start)/o,e.t=Math.min(e.t,t.t-c)):i.end>t.b&&(c=(i.end-t.b)/o,e.b=Math.max(e.b,t.b+c))}function Kd(e,t,n){let r=e.drawingArea,{extra:i,additionalAngle:a,padding:o,size:s}=n,c=e.getPointPosition(t,r+i+o,a),l=Math.round(_i(Si(c.angle+ii))),u=Zd(c.y,s.h,l),d=Yd(l),f=Xd(c.x,s.w,d);return{visible:!0,x:c.x,y:u,textAlign:d,left:f,top:u,right:f+s.w,bottom:u+s.h}}function qd(e,t){if(!t)return!0;let{left:n,top:r,right:i,bottom:a}=e;return!(va({x:n,y:r},t)||va({x:n,y:a},t)||va({x:i,y:r},t)||va({x:i,y:a},t))}function Jd(e,t,n){let r=[],i=e._pointLabels.length,a=e.options,{centerPointLabels:o,display:s}=a.pointLabels,c={extra:Vd(a)/2,additionalAngle:o?$r/i:0},l;for(let a=0;a<i;a++){c.padding=n[a],c.size=t[a];let i=Kd(e,a,c);r.push(i),s===`auto`&&(i.visible=qd(i,l),i.visible&&(l=i))}return r}function Yd(e){return e===0||e===180?`center`:e<180?`left`:`right`}function Xd(e,t,n){return n===`right`?e-=t:n===`center`&&(e-=t/2),e}function Zd(e,t,n){return n===90||n===270?e-=t/2:(n>270||n<90)&&(e-=t),e}function Qd(e,t,n){let{left:r,top:i,right:a,bottom:o}=n,{backdropColor:s}=t;if(!H(s)){let n=Pa(t.borderRadius),c=Fa(t.backdropPadding);e.fillStyle=s;let l=r-c.left,u=i-c.top,d=a-r+c.width,f=o-i+c.height;Object.values(n).some(e=>e!==0)?(e.beginPath(),Da(e,{x:l,y:u,w:d,h:f,radius:n}),e.fill()):e.fillRect(l,u,d,f)}}function $d(e,t){let{ctx:n,options:{pointLabels:r}}=e;for(let i=t-1;i>=0;i--){let t=e._pointLabelItems[i];if(!t.visible)continue;let a=r.setContext(e.getPointLabelContext(i));Qd(n,a,t);let o=Ia(a.font),{x:s,y:c,textAlign:l}=t;Ea(n,e._pointLabels[i],s,c+o.lineHeight/2,o,{color:a.color,textAlign:l,textBaseline:`middle`})}}function ef(e,t,n,r){let{ctx:i}=e;if(n)i.arc(e.xCenter,e.yCenter,t,0,ei);else{let n=e.getPointPosition(0,t);i.moveTo(n.x,n.y);for(let a=1;a<r;a++)n=e.getPointPosition(a,t),i.lineTo(n.x,n.y)}}function tf(e,t,n,r,i){let a=e.ctx,o=t.circular,{color:s,lineWidth:c}=t;!o&&!r||!s||!c||n<0||(a.save(),a.strokeStyle=s,a.lineWidth=c,a.setLineDash(i.dash||[]),a.lineDashOffset=i.dashOffset,a.beginPath(),ef(e,n,o,r),a.closePath(),a.stroke(),a.restore())}function nf(e,t,n){return za(e,{label:n,index:t,type:`pointLabel`})}(class extends Q{static id=`radialLinear`;static defaults={display:!0,animate:!0,position:`chartArea`,angleLines:{display:!0,lineWidth:1,borderDash:[],borderDashOffset:0},grid:{circular:!1},startAngle:0,ticks:{showLabelBackdrop:!0,callback:ia.formatters.numeric},pointLabels:{backdropColor:void 0,backdropPadding:2,display:!0,font:{size:10},callback(e){return e},padding:5,centerPointLabels:!1}};static defaultRoutes={"angleLines.color":`borderColor`,"pointLabels.color":`color`,"ticks.color":`color`};static descriptors={angleLines:{_fallback:`grid`}};constructor(e){super(e),this.xCenter=void 0,this.yCenter=void 0,this.drawingArea=void 0,this._pointLabels=[],this._pointLabelItems=[]}setDimensions(){let e=this._padding=Fa(Vd(this.options)/2),t=this.width=this.maxWidth-e.width,n=this.height=this.maxHeight-e.height;this.xCenter=Math.floor(this.left+t/2+e.left),this.yCenter=Math.floor(this.top+n/2+e.top),this.drawingArea=Math.floor(Math.min(t,n)/2)}determineDataLimits(){let{min:e,max:t}=this.getMinMax(!1);this.min=Mr(e)&&!isNaN(e)?e:0,this.max=Mr(t)&&!isNaN(t)?t:0,this.handleTickRangeOptions()}computeTickLimit(){return Math.ceil(this.drawingArea/Vd(this.options))}generateTickLabels(e){Q.prototype.generateTickLabels.call(this,e),this._pointLabels=this.getLabels().map((e,t)=>{let n=Fr(this.options.pointLabels.callback,[e,t],this);return n||n===0?n:``}).filter((e,t)=>this.chart.getDataVisibility(t))}fit(){let e=this.options;e.display&&e.pointLabels.display?Wd(this):this.setCenterPoint(0,0,0,0)}setCenterPoint(e,t,n,r){this.xCenter+=Math.floor((e-t)/2),this.yCenter+=Math.floor((n-r)/2),this.drawingArea-=Math.min(this.drawingArea/2,Math.max(e,t,n,r))}getIndexAngle(e){let t=ei/(this._pointLabels.length||1),n=this.options.startAngle||0;return Si(e*t+gi(n))}getDistanceFromCenterForValue(e){if(H(e))return NaN;let t=this.drawingArea/(this.max-this.min);return this.options.reverse?(this.max-e)*t:(e-this.min)*t}getValueForDistanceFromCenter(e){if(H(e))return NaN;let t=e/(this.drawingArea/(this.max-this.min));return this.options.reverse?this.max-t:this.min+t}getPointLabelContext(e){let t=this._pointLabels||[];if(e>=0&&e<t.length){let n=t[e];return nf(this.getContext(),e,n)}}getPointPosition(e,t,n=0){let r=this.getIndexAngle(e)-ii+n;return{x:Math.cos(r)*t+this.xCenter,y:Math.sin(r)*t+this.yCenter,angle:r}}getPointPositionForValue(e,t){return this.getPointPosition(e,this.getDistanceFromCenterForValue(t))}getBasePosition(e){return this.getPointPositionForValue(e||0,this.getBaseValue())}getPointLabelPosition(e){let{left:t,top:n,right:r,bottom:i}=this._pointLabelItems[e];return{left:t,top:n,right:r,bottom:i}}drawBackground(){let{backgroundColor:e,grid:{circular:t}}=this.options;if(e){let n=this.ctx;n.save(),n.beginPath(),ef(this,this.getDistanceFromCenterForValue(this._endValue),t,this._pointLabels.length),n.closePath(),n.fillStyle=e,n.fill(),n.restore()}}drawGrid(){let e=this.ctx,t=this.options,{angleLines:n,grid:r,border:i}=t,a=this._pointLabels.length,o,s,c;if(t.pointLabels.display&&$d(this,a),r.display&&this.ticks.forEach((e,t)=>{if(t!==0||t===0&&this.min<0){s=this.getDistanceFromCenterForValue(e.value);let n=this.getContext(t),o=r.setContext(n),c=i.setContext(n);tf(this,o,s,a,c)}}),n.display){for(e.save(),o=a-1;o>=0;o--){let r=n.setContext(this.getPointLabelContext(o)),{color:i,lineWidth:a}=r;!a||!i||(e.lineWidth=a,e.strokeStyle=i,e.setLineDash(r.borderDash),e.lineDashOffset=r.borderDashOffset,s=this.getDistanceFromCenterForValue(t.reverse?this.min:this.max),c=this.getPointPosition(o,s),e.beginPath(),e.moveTo(this.xCenter,this.yCenter),e.lineTo(c.x,c.y),e.stroke())}e.restore()}}drawBorder(){}drawLabels(){let e=this.ctx,t=this.options,n=t.ticks;if(!n.display)return;let r=this.getIndexAngle(0),i,a;e.save(),e.translate(this.xCenter,this.yCenter),e.rotate(r),e.textAlign=`center`,e.textBaseline=`middle`,this.ticks.forEach((r,o)=>{if(o===0&&this.min>=0&&!t.reverse)return;let s=n.setContext(this.getContext(o)),c=Ia(s.font);if(i=this.getDistanceFromCenterForValue(this.ticks[o].value),s.showLabelBackdrop){e.font=c.string,a=e.measureText(r.label).width,e.fillStyle=s.backdropColor;let t=Fa(s.backdropPadding);e.fillRect(-a/2-t.left,-i-c.size/2-t.top,a+t.width,c.size+t.height)}Ea(e,r.label,0,-i,c,{color:s.color,strokeColor:s.textStrokeColor,strokeWidth:s.textStrokeWidth})}),e.restore()}drawTitle(){}});var rf={millisecond:{common:!0,size:1,steps:1e3},second:{common:!0,size:1e3,steps:60},minute:{common:!0,size:6e4,steps:60},hour:{common:!0,size:36e5,steps:24},day:{common:!0,size:864e5,steps:30},week:{common:!1,size:6048e5,steps:4},month:{common:!0,size:2628e6,steps:12},quarter:{common:!1,size:7884e6,steps:4},year:{common:!0,size:3154e7}},af=Object.keys(rf);function of(e,t){return e-t}function sf(e,t){if(H(t))return null;let n=e._adapter,{parser:r,round:i,isoWeekday:a}=e._parseOpts,o=t;return typeof r==`function`&&(o=r(o)),Mr(o)||(o=typeof r==`string`?n.parse(o,r):n.parse(o)),o===null?null:(i&&(o=i===`week`&&(pi(a)||a===!0)?n.startOf(o,`isoWeek`,a):n.startOf(o,i)),+o)}function cf(e,t,n,r){let i=af.length;for(let a=af.indexOf(e);a<i-1;++a){let e=rf[af[a]],i=e.steps?e.steps:2**53-1;if(e.common&&Math.ceil((n-t)/(i*e.size))<=r)return af[a]}return af[i-1]}function lf(e,t,n,r,i){for(let a=af.length-1;a>=af.indexOf(n);a--){let n=af[a];if(rf[n].common&&e._adapter.diff(i,r,n)>=t-1)return n}return af[n?af.indexOf(n):0]}function uf(e){for(let t=af.indexOf(e)+1,n=af.length;t<n;++t)if(rf[af[t]].common)return af[t]}function df(e,t,n){if(!n)e[t]=!0;else if(n.length){let{lo:r,hi:i}=Di(n,t),a=n[r]>=t?n[r]:n[i];e[a]=!0}}function ff(e,t,n,r){let i=e._adapter,a=+i.startOf(t[0].value,r),o=t[t.length-1].value,s,c;for(s=a;s<=o;s=+i.add(s,1,r))c=n[s],c>=0&&(t[c].major=!0);return t}function pf(e,t,n){let r=[],i={},a=t.length,o,s;for(o=0;o<a;++o)s=t[o],i[s]=o,r.push({value:s,major:!1});return a===0||!n?r:ff(e,r,i,n)}var mf=class extends sl{static id=`time`;static defaults={bounds:`data`,adapters:{},time:{parser:!1,unit:!1,round:!1,isoWeekday:!1,minUnit:`millisecond`,displayFormats:{}},ticks:{source:`auto`,callback:!1,major:{enabled:!1}}};constructor(e){super(e),this._cache={data:[],labels:[],all:[]},this._unit=`day`,this._majorUnit=void 0,this._offsets={},this._normalized=!1,this._parseOpts=void 0}init(e,t={}){let n=e.time||={},r=this._adapter=new Gs._date(e.adapters.date);r.init(t),Hr(n.displayFormats,r.formats()),this._parseOpts={parser:n.parser,round:n.round,isoWeekday:n.isoWeekday},super.init(e),this._normalized=t.normalized}parse(e,t){return e===void 0?null:sf(this,e)}beforeLayout(){super.beforeLayout(),this._cache={data:[],labels:[],all:[]}}determineDataLimits(){let e=this.options,t=this._adapter,n=e.time.unit||`day`,{min:r,max:i,minDefined:a,maxDefined:o}=this.getUserBounds();function s(e){!a&&!isNaN(e.min)&&(r=Math.min(r,e.min)),!o&&!isNaN(e.max)&&(i=Math.max(i,e.max))}(!a||!o)&&(s(this._getLabelBounds()),(e.bounds!==`ticks`||e.ticks.source!==`labels`)&&s(this.getMinMax(!1))),r=Mr(r)&&!isNaN(r)?r:+t.startOf(Date.now(),n),i=Mr(i)&&!isNaN(i)?i:+t.endOf(Date.now(),n)+1,this.min=Math.min(r,i-1),this.max=Math.max(r+1,i)}_getLabelBounds(){let e=this.getLabelTimestamps(),t=1/0,n=-1/0;return e.length&&(t=e[0],n=e[e.length-1]),{min:t,max:n}}buildTicks(){let e=this.options,t=e.time,n=e.ticks,r=n.source===`labels`?this.getLabelTimestamps():this._generate();e.bounds===`ticks`&&r.length&&(this.min=this._userMin||r[0],this.max=this._userMax||r[r.length-1]);let i=this.min,a=this.max,o=ki(r,i,a);return this._unit=t.unit||(n.autoSkip?cf(t.minUnit,this.min,this.max,this._getLabelCapacity(i)):lf(this,o.length,t.minUnit,this.min,this.max)),this._majorUnit=!n.major.enabled||this._unit===`year`?void 0:uf(this._unit),this.initOffsets(r),e.reverse&&o.reverse(),pf(this,o,this._majorUnit)}afterAutoSkip(){this.options.offsetAfterAutoskip&&this.initOffsets(this.ticks.map(e=>+e.value))}initOffsets(e=[]){let t=0,n=0,r,i;this.options.offset&&e.length&&(r=this.getDecimalForValue(e[0]),t=e.length===1?1-r:(this.getDecimalForValue(e[1])-r)/2,i=this.getDecimalForValue(e[e.length-1]),n=e.length===1?i:(i-this.getDecimalForValue(e[e.length-2]))/2);let a=e.length<3?.5:.25;t=wi(t,0,a),n=wi(n,0,a),this._offsets={start:t,end:n,factor:1/(t+1+n)}}_generate(){let e=this._adapter,t=this.min,n=this.max,r=this.options,i=r.time,a=i.unit||cf(i.minUnit,t,n,this._getLabelCapacity(t)),o=G(r.ticks.stepSize,1),s=a===`week`?i.isoWeekday:!1,c=pi(s)||s===!0,l={},u=t,d,f;if(c&&(u=+e.startOf(u,`isoWeek`,s)),u=+e.startOf(u,c?`day`:a),e.diff(n,t,a)>1e5*o)throw Error(t+` and `+n+` are too far apart with stepSize of `+o+` `+a);let p=r.ticks.source===`data`&&this.getDataTimestamps();for(d=u,f=0;d<n;d=+e.add(d,o,a),f++)df(l,d,p);return(d===n||r.bounds===`ticks`||f===1)&&df(l,d,p),Object.keys(l).sort(of).map(e=>+e)}getLabelForValue(e){let t=this._adapter,n=this.options.time;return n.tooltipFormat?t.format(e,n.tooltipFormat):t.format(e,n.displayFormats.datetime)}format(e,t){let n=this.options.time.displayFormats,r=this._unit,i=t||n[r];return this._adapter.format(e,i)}_tickFormatFunction(e,t,n,r){let i=this.options,a=i.ticks.callback;if(a)return Fr(a,[e,t,n],this);let o=i.time.displayFormats,s=this._unit,c=this._majorUnit,l=s&&o[s],u=c&&o[c],d=n[t],f=c&&u&&d&&d.major;return this._adapter.format(e,r||(f?u:l))}generateTickLabels(e){let t,n,r;for(t=0,n=e.length;t<n;++t)r=e[t],r.label=this._tickFormatFunction(r.value,t,e)}getDecimalForValue(e){return e===null?NaN:(e-this.min)/(this.max-this.min)}getPixelForValue(e){let t=this._offsets,n=this.getDecimalForValue(e);return this.getPixelForDecimal((t.start+n)*t.factor)}getValueForPixel(e){let t=this._offsets,n=this.getDecimalForPixel(e)/t.factor-t.end;return this.min+n*(this.max-this.min)}_getLabelSize(e){let t=this.options.ticks,n=this.ctx.measureText(e).width,r=gi(this.isHorizontal()?t.maxRotation:t.minRotation),i=Math.cos(r),a=Math.sin(r),o=this._resolveTickFontOptions(0).size;return{w:n*i+o*a,h:n*a+o*i}}_getLabelCapacity(e){let t=this.options.time,n=t.displayFormats,r=n[t.unit]||n.millisecond,i=this._tickFormatFunction(e,0,pf(this,[e],this._majorUnit),r),a=this._getLabelSize(i),o=Math.floor(this.isHorizontal()?this.width/a.w:this.height/a.h)-1;return o>0?o:1}getDataTimestamps(){let e=this._cache.data||[],t,n;if(e.length)return e;let r=this.getMatchingVisibleMetas();if(this._normalized&&r.length)return this._cache.data=r[0].controller.getAllParsedValues(this);for(t=0,n=r.length;t<n;++t)e=e.concat(r[t].controller.getAllParsedValues(this));return this._cache.data=this.normalize(e)}getLabelTimestamps(){let e=this._cache.labels||[],t,n;if(e.length)return e;let r=this.getLabels();for(t=0,n=r.length;t<n;++t)e.push(sf(this,r[t]));return this._cache.labels=this._normalized?e:this.normalize(e)}normalize(e){return Ni(e.sort(of))}};function hf(e,t,n){let r=0,i=e.length-1,a,o,s,c;n?(t>=e[r].pos&&t<=e[i].pos&&({lo:r,hi:i}=K(e,`pos`,t)),{pos:a,time:s}=e[r],{pos:o,time:c}=e[i]):(t>=e[r].time&&t<=e[i].time&&({lo:r,hi:i}=K(e,`time`,t)),{time:a,pos:s}=e[r],{time:o,pos:c}=e[i]);let l=o-a;return l?s+(c-s)*(t-a)/l:s}(class extends mf{static id=`timeseries`;static defaults=mf.defaults;constructor(e){super(e),this._table=[],this._minPos=void 0,this._tableRange=void 0}initOffsets(){let e=this._getTimestampsForTable(),t=this._table=this.buildLookupTable(e);this._minPos=hf(t,this.min),this._tableRange=hf(t,this.max)-this._minPos,super.initOffsets(e)}buildLookupTable(e){let{min:t,max:n}=this,r=[],i=[],a,o,s,c,l;for(a=0,o=e.length;a<o;++a)c=e[a],c>=t&&c<=n&&r.push(c);if(r.length<2)return[{time:t,pos:0},{time:n,pos:1}];for(a=0,o=r.length;a<o;++a)l=r[a+1],s=r[a-1],c=r[a],Math.round((l+s)/2)!==c&&i.push({time:c,pos:a/(o-1)});return i}_generate(){let e=this.min,t=this.max,n=super.getDataTimestamps();return(!n.includes(e)||!n.length)&&n.splice(0,0,e),(!n.includes(t)||n.length===1)&&n.push(t),n.sort((e,t)=>e-t)}_getTimestampsForTable(){let e=this._cache.all||[];if(e.length)return e;let t=this.getDataTimestamps(),n=this.getLabelTimestamps();return e=t.length&&n.length?this.normalize(t.concat(n)):t.length?t:n,e=this._cache.all=e,e}getDecimalForValue(e){return(hf(this._table,e)-this._minPos)/this._tableRange}getValueForPixel(e){let t=this._offsets,n=this.getDecimalForPixel(e)/t.factor-t.end;return hf(this._table,n*this._tableRange+this._minPos,!0)}});var gf=`label`;function _f(e,t){typeof e==`function`?e(t):e&&(e.current=t)}function vf(e,t){let n=e.options;n&&t&&Object.assign(n,t)}function yf(e,t){e.labels=t}function bf(e,t,n=gf){let r=[];e.datasets=t.map(t=>{let i=e.datasets.find(e=>e[n]===t[n]);return!i||!t.data||r.includes(i)?{...t}:(r.push(i),Object.assign(i,t),i)})}function xf(e,t=gf){let n={labels:[],datasets:[]};return yf(n,e.labels),bf(n,e.datasets,t),n}function Sf(e,t){let{height:n=150,width:r=300,redraw:i=!1,datasetIdKey:a,type:o,data:s,options:c,plugins:l=[],fallbackContent:u,updateMode:d,...f}=e,p=(0,v.useRef)(null),m=(0,v.useRef)(null),h=()=>{p.current&&(m.current=new Kl(p.current,{type:o,data:xf(s,a),options:c&&{...c},plugins:l}),_f(t,m.current))},g=()=>{_f(t,null),m.current&&=(m.current.destroy(),null)};return(0,v.useEffect)(()=>{!i&&m.current&&c&&vf(m.current,c)},[i,c]),(0,v.useEffect)(()=>{!i&&m.current&&yf(m.current.config.data,s.labels)},[i,s.labels]),(0,v.useEffect)(()=>{!i&&m.current&&s.datasets&&bf(m.current.config.data,s.datasets,a)},[i,s.datasets]),(0,v.useEffect)(()=>{m.current&&(i?(g(),setTimeout(h)):m.current.update(d))},[i,c,s.labels,s.datasets,d]),(0,v.useEffect)(()=>{m.current&&(g(),setTimeout(h))},[o]),(0,v.useEffect)(()=>(h(),()=>g()),[]),(0,P.jsx)(`canvas`,{ref:p,role:`img`,height:n,width:r,...f,children:u})}var Cf=(0,v.forwardRef)(Sf);function wf(e,t){return Kl.register(t),(0,v.forwardRef)((t,n)=>(0,P.jsx)(Cf,{...t,ref:n,type:e}))}var Tf=wf(`line`,Us),Ef=wf(`bar`,Hs),Df=365.2425,Of=6048e5,kf=864e5,Af=3600*24;Af*7,Af*Df/12*3;var jf=Symbol.for(`constructDateFrom`);function Mf(e,t){return typeof e==`function`?e(t):e&&typeof e==`object`&&jf in e?e[jf](t):e instanceof Date?new e.constructor(t):new Date(t)}function Nf(e,t){return Mf(t||e,e)}var Pf={};function Ff(){return Pf}function If(e,t){let n=Ff(),r=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??n.weekStartsOn??n.locale?.options?.weekStartsOn??0,i=Nf(e,t?.in),a=i.getDay(),o=(a<r?7:0)+a-r;return i.setDate(i.getDate()-o),i.setHours(0,0,0,0),i}function Lf(e,t){return If(e,{...t,weekStartsOn:1})}function Rf(e,t){let n=Nf(e,t?.in),r=n.getFullYear(),i=Mf(n,0);i.setFullYear(r+1,0,4),i.setHours(0,0,0,0);let a=Lf(i),o=Mf(n,0);o.setFullYear(r,0,4),o.setHours(0,0,0,0);let s=Lf(o);return n.getTime()>=a.getTime()?r+1:n.getTime()>=s.getTime()?r:r-1}function zf(e){let t=Nf(e),n=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return n.setUTCFullYear(t.getFullYear()),e-+n}function Bf(e,...t){let n=Mf.bind(null,e||t.find(e=>typeof e==`object`));return t.map(n)}function Vf(e,t){let n=Nf(e,t?.in);return n.setHours(0,0,0,0),n}function Hf(e,t,n){let[r,i]=Bf(n?.in,e,t),a=Vf(r),o=Vf(i),s=+a-zf(a),c=+o-zf(o);return Math.round((s-c)/kf)}function Uf(e,t){let n=Rf(e,t),r=Mf(t?.in||e,0);return r.setFullYear(n,0,4),r.setHours(0,0,0,0),Lf(r)}function Wf(e){return e instanceof Date||typeof e==`object`&&Object.prototype.toString.call(e)===`[object Date]`}function Gf(e){return!(!Wf(e)&&typeof e!=`number`||isNaN(+Nf(e)))}function Kf(e,t){let n=Nf(e,t?.in);return n.setFullYear(n.getFullYear(),0,1),n.setHours(0,0,0,0),n}var qf={lessThanXSeconds:{one:`less than a second`,other:`less than {{count}} seconds`},xSeconds:{one:`1 second`,other:`{{count}} seconds`},halfAMinute:`half a minute`,lessThanXMinutes:{one:`less than a minute`,other:`less than {{count}} minutes`},xMinutes:{one:`1 minute`,other:`{{count}} minutes`},aboutXHours:{one:`about 1 hour`,other:`about {{count}} hours`},xHours:{one:`1 hour`,other:`{{count}} hours`},xDays:{one:`1 day`,other:`{{count}} days`},aboutXWeeks:{one:`about 1 week`,other:`about {{count}} weeks`},xWeeks:{one:`1 week`,other:`{{count}} weeks`},aboutXMonths:{one:`about 1 month`,other:`about {{count}} months`},xMonths:{one:`1 month`,other:`{{count}} months`},aboutXYears:{one:`about 1 year`,other:`about {{count}} years`},xYears:{one:`1 year`,other:`{{count}} years`},overXYears:{one:`over 1 year`,other:`over {{count}} years`},almostXYears:{one:`almost 1 year`,other:`almost {{count}} years`}},Jf=(e,t,n)=>{let r,i=qf[e];return r=typeof i==`string`?i:t===1?i.one:i.other.replace(`{{count}}`,t.toString()),n?.addSuffix?n.comparison&&n.comparison>0?`in `+r:r+` ago`:r};function Yf(e){return(t={})=>{let n=t.width?String(t.width):e.defaultWidth;return e.formats[n]||e.formats[e.defaultWidth]}}var Xf={date:Yf({formats:{full:`EEEE, MMMM do, y`,long:`MMMM do, y`,medium:`MMM d, y`,short:`MM/dd/yyyy`},defaultWidth:`full`}),time:Yf({formats:{full:`h:mm:ss a zzzz`,long:`h:mm:ss a z`,medium:`h:mm:ss a`,short:`h:mm a`},defaultWidth:`full`}),dateTime:Yf({formats:{full:`{{date}} 'at' {{time}}`,long:`{{date}} 'at' {{time}}`,medium:`{{date}}, {{time}}`,short:`{{date}}, {{time}}`},defaultWidth:`full`})},Zf={lastWeek:`'last' eeee 'at' p`,yesterday:`'yesterday at' p`,today:`'today at' p`,tomorrow:`'tomorrow at' p`,nextWeek:`eeee 'at' p`,other:`P`},Qf=(e,t,n,r)=>Zf[e];function $f(e){return(t,n)=>{let r=n?.context?String(n.context):`standalone`,i;if(r===`formatting`&&e.formattingValues){let t=e.defaultFormattingWidth||e.defaultWidth,r=n?.width?String(n.width):t;i=e.formattingValues[r]||e.formattingValues[t]}else{let t=e.defaultWidth,r=n?.width?String(n.width):e.defaultWidth;i=e.values[r]||e.values[t]}let a=e.argumentCallback?e.argumentCallback(t):t;return i[a]}}var ep={ordinalNumber:(e,t)=>{let n=Number(e),r=n%100;if(r>20||r<10)switch(r%10){case 1:return n+`st`;case 2:return n+`nd`;case 3:return n+`rd`}return n+`th`},era:$f({values:{narrow:[`B`,`A`],abbreviated:[`BC`,`AD`],wide:[`Before Christ`,`Anno Domini`]},defaultWidth:`wide`}),quarter:$f({values:{narrow:[`1`,`2`,`3`,`4`],abbreviated:[`Q1`,`Q2`,`Q3`,`Q4`],wide:[`1st quarter`,`2nd quarter`,`3rd quarter`,`4th quarter`]},defaultWidth:`wide`,argumentCallback:e=>e-1}),month:$f({values:{narrow:[`J`,`F`,`M`,`A`,`M`,`J`,`J`,`A`,`S`,`O`,`N`,`D`],abbreviated:[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],wide:[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`]},defaultWidth:`wide`}),day:$f({values:{narrow:[`S`,`M`,`T`,`W`,`T`,`F`,`S`],short:[`Su`,`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`],abbreviated:[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],wide:[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`]},defaultWidth:`wide`}),dayPeriod:$f({values:{narrow:{am:`a`,pm:`p`,midnight:`mi`,noon:`n`,morning:`morning`,afternoon:`afternoon`,evening:`evening`,night:`night`},abbreviated:{am:`AM`,pm:`PM`,midnight:`midnight`,noon:`noon`,morning:`morning`,afternoon:`afternoon`,evening:`evening`,night:`night`},wide:{am:`a.m.`,pm:`p.m.`,midnight:`midnight`,noon:`noon`,morning:`morning`,afternoon:`afternoon`,evening:`evening`,night:`night`}},defaultWidth:`wide`,formattingValues:{narrow:{am:`a`,pm:`p`,midnight:`mi`,noon:`n`,morning:`in the morning`,afternoon:`in the afternoon`,evening:`in the evening`,night:`at night`},abbreviated:{am:`AM`,pm:`PM`,midnight:`midnight`,noon:`noon`,morning:`in the morning`,afternoon:`in the afternoon`,evening:`in the evening`,night:`at night`},wide:{am:`a.m.`,pm:`p.m.`,midnight:`midnight`,noon:`noon`,morning:`in the morning`,afternoon:`in the afternoon`,evening:`in the evening`,night:`at night`}},defaultFormattingWidth:`wide`})};function tp(e){return(t,n={})=>{let r=n.width,i=r&&e.matchPatterns[r]||e.matchPatterns[e.defaultMatchWidth],a=t.match(i);if(!a)return null;let o=a[0],s=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],c=Array.isArray(s)?rp(s,e=>e.test(o)):np(s,e=>e.test(o)),l;l=e.valueCallback?e.valueCallback(c):c,l=n.valueCallback?n.valueCallback(l):l;let u=t.slice(o.length);return{value:l,rest:u}}}function np(e,t){for(let n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&t(e[n]))return n}function rp(e,t){for(let n=0;n<e.length;n++)if(t(e[n]))return n}function ip(e){return(t,n={})=>{let r=t.match(e.matchPattern);if(!r)return null;let i=r[0],a=t.match(e.parsePattern);if(!a)return null;let o=e.valueCallback?e.valueCallback(a[0]):a[0];o=n.valueCallback?n.valueCallback(o):o;let s=t.slice(i.length);return{value:o,rest:s}}}var ap={code:`en-US`,formatDistance:Jf,formatLong:Xf,formatRelative:Qf,localize:ep,match:{ordinalNumber:ip({matchPattern:/^(\d+)(th|st|nd|rd)?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:tp({matchPatterns:{narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},defaultMatchWidth:`wide`,parsePatterns:{any:[/^b/i,/^(a|c)/i]},defaultParseWidth:`any`}),quarter:tp({matchPatterns:{narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},defaultMatchWidth:`wide`,parsePatterns:{any:[/1/i,/2/i,/3/i,/4/i]},defaultParseWidth:`any`,valueCallback:e=>e+1}),month:tp({matchPatterns:{narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},defaultMatchWidth:`wide`,parsePatterns:{narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},defaultParseWidth:`any`}),day:tp({matchPatterns:{narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},defaultMatchWidth:`wide`,parsePatterns:{narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},defaultParseWidth:`any`}),dayPeriod:tp({matchPatterns:{narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},defaultMatchWidth:`any`,parsePatterns:{any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},defaultParseWidth:`any`})},options:{weekStartsOn:0,firstWeekContainsDate:1}};function op(e,t){let n=Nf(e,t?.in);return Hf(n,Kf(n))+1}function sp(e,t){let n=Nf(e,t?.in),r=Lf(n)-+Uf(n);return Math.round(r/Of)+1}function cp(e,t){let n=Nf(e,t?.in),r=n.getFullYear(),i=Ff(),a=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??i.firstWeekContainsDate??i.locale?.options?.firstWeekContainsDate??1,o=Mf(t?.in||e,0);o.setFullYear(r+1,0,a),o.setHours(0,0,0,0);let s=If(o,t),c=Mf(t?.in||e,0);c.setFullYear(r,0,a),c.setHours(0,0,0,0);let l=If(c,t);return+n>=+s?r+1:+n>=+l?r:r-1}function lp(e,t){let n=Ff(),r=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,i=cp(e,t),a=Mf(t?.in||e,0);return a.setFullYear(i,0,r),a.setHours(0,0,0,0),If(a,t)}function up(e,t){let n=Nf(e,t?.in),r=If(n,t)-+lp(n,t);return Math.round(r/Of)+1}function $(e,t){return(e<0?`-`:``)+Math.abs(e).toString().padStart(t,`0`)}var dp={y(e,t){let n=e.getFullYear(),r=n>0?n:1-n;return $(t===`yy`?r%100:r,t.length)},M(e,t){let n=e.getMonth();return t===`M`?String(n+1):$(n+1,2)},d(e,t){return $(e.getDate(),t.length)},a(e,t){let n=e.getHours()/12>=1?`pm`:`am`;switch(t){case`a`:case`aa`:return n.toUpperCase();case`aaa`:return n;case`aaaaa`:return n[0];default:return n===`am`?`a.m.`:`p.m.`}},h(e,t){return $(e.getHours()%12||12,t.length)},H(e,t){return $(e.getHours(),t.length)},m(e,t){return $(e.getMinutes(),t.length)},s(e,t){return $(e.getSeconds(),t.length)},S(e,t){let n=t.length,r=e.getMilliseconds();return $(Math.trunc(r*10**(n-3)),t.length)}},fp={am:`am`,pm:`pm`,midnight:`midnight`,noon:`noon`,morning:`morning`,afternoon:`afternoon`,evening:`evening`,night:`night`},pp={G:function(e,t,n){let r=+(e.getFullYear()>0);switch(t){case`G`:case`GG`:case`GGG`:return n.era(r,{width:`abbreviated`});case`GGGGG`:return n.era(r,{width:`narrow`});default:return n.era(r,{width:`wide`})}},y:function(e,t,n){if(t===`yo`){let t=e.getFullYear(),r=t>0?t:1-t;return n.ordinalNumber(r,{unit:`year`})}return dp.y(e,t)},Y:function(e,t,n,r){let i=cp(e,r),a=i>0?i:1-i;return t===`YY`?$(a%100,2):t===`Yo`?n.ordinalNumber(a,{unit:`year`}):$(a,t.length)},R:function(e,t){return $(Rf(e),t.length)},u:function(e,t){return $(e.getFullYear(),t.length)},Q:function(e,t,n){let r=Math.ceil((e.getMonth()+1)/3);switch(t){case`Q`:return String(r);case`QQ`:return $(r,2);case`Qo`:return n.ordinalNumber(r,{unit:`quarter`});case`QQQ`:return n.quarter(r,{width:`abbreviated`,context:`formatting`});case`QQQQQ`:return n.quarter(r,{width:`narrow`,context:`formatting`});default:return n.quarter(r,{width:`wide`,context:`formatting`})}},q:function(e,t,n){let r=Math.ceil((e.getMonth()+1)/3);switch(t){case`q`:return String(r);case`qq`:return $(r,2);case`qo`:return n.ordinalNumber(r,{unit:`quarter`});case`qqq`:return n.quarter(r,{width:`abbreviated`,context:`standalone`});case`qqqqq`:return n.quarter(r,{width:`narrow`,context:`standalone`});default:return n.quarter(r,{width:`wide`,context:`standalone`})}},M:function(e,t,n){let r=e.getMonth();switch(t){case`M`:case`MM`:return dp.M(e,t);case`Mo`:return n.ordinalNumber(r+1,{unit:`month`});case`MMM`:return n.month(r,{width:`abbreviated`,context:`formatting`});case`MMMMM`:return n.month(r,{width:`narrow`,context:`formatting`});default:return n.month(r,{width:`wide`,context:`formatting`})}},L:function(e,t,n){let r=e.getMonth();switch(t){case`L`:return String(r+1);case`LL`:return $(r+1,2);case`Lo`:return n.ordinalNumber(r+1,{unit:`month`});case`LLL`:return n.month(r,{width:`abbreviated`,context:`standalone`});case`LLLLL`:return n.month(r,{width:`narrow`,context:`standalone`});default:return n.month(r,{width:`wide`,context:`standalone`})}},w:function(e,t,n,r){let i=up(e,r);return t===`wo`?n.ordinalNumber(i,{unit:`week`}):$(i,t.length)},I:function(e,t,n){let r=sp(e);return t===`Io`?n.ordinalNumber(r,{unit:`week`}):$(r,t.length)},d:function(e,t,n){return t===`do`?n.ordinalNumber(e.getDate(),{unit:`date`}):dp.d(e,t)},D:function(e,t,n){let r=op(e);return t===`Do`?n.ordinalNumber(r,{unit:`dayOfYear`}):$(r,t.length)},E:function(e,t,n){let r=e.getDay();switch(t){case`E`:case`EE`:case`EEE`:return n.day(r,{width:`abbreviated`,context:`formatting`});case`EEEEE`:return n.day(r,{width:`narrow`,context:`formatting`});case`EEEEEE`:return n.day(r,{width:`short`,context:`formatting`});default:return n.day(r,{width:`wide`,context:`formatting`})}},e:function(e,t,n,r){let i=e.getDay(),a=(i-r.weekStartsOn+8)%7||7;switch(t){case`e`:return String(a);case`ee`:return $(a,2);case`eo`:return n.ordinalNumber(a,{unit:`day`});case`eee`:return n.day(i,{width:`abbreviated`,context:`formatting`});case`eeeee`:return n.day(i,{width:`narrow`,context:`formatting`});case`eeeeee`:return n.day(i,{width:`short`,context:`formatting`});default:return n.day(i,{width:`wide`,context:`formatting`})}},c:function(e,t,n,r){let i=e.getDay(),a=(i-r.weekStartsOn+8)%7||7;switch(t){case`c`:return String(a);case`cc`:return $(a,t.length);case`co`:return n.ordinalNumber(a,{unit:`day`});case`ccc`:return n.day(i,{width:`abbreviated`,context:`standalone`});case`ccccc`:return n.day(i,{width:`narrow`,context:`standalone`});case`cccccc`:return n.day(i,{width:`short`,context:`standalone`});default:return n.day(i,{width:`wide`,context:`standalone`})}},i:function(e,t,n){let r=e.getDay(),i=r===0?7:r;switch(t){case`i`:return String(i);case`ii`:return $(i,t.length);case`io`:return n.ordinalNumber(i,{unit:`day`});case`iii`:return n.day(r,{width:`abbreviated`,context:`formatting`});case`iiiii`:return n.day(r,{width:`narrow`,context:`formatting`});case`iiiiii`:return n.day(r,{width:`short`,context:`formatting`});default:return n.day(r,{width:`wide`,context:`formatting`})}},a:function(e,t,n){let r=e.getHours()/12>=1?`pm`:`am`;switch(t){case`a`:case`aa`:return n.dayPeriod(r,{width:`abbreviated`,context:`formatting`});case`aaa`:return n.dayPeriod(r,{width:`abbreviated`,context:`formatting`}).toLowerCase();case`aaaaa`:return n.dayPeriod(r,{width:`narrow`,context:`formatting`});default:return n.dayPeriod(r,{width:`wide`,context:`formatting`})}},b:function(e,t,n){let r=e.getHours(),i;switch(i=r===12?fp.noon:r===0?fp.midnight:r/12>=1?`pm`:`am`,t){case`b`:case`bb`:return n.dayPeriod(i,{width:`abbreviated`,context:`formatting`});case`bbb`:return n.dayPeriod(i,{width:`abbreviated`,context:`formatting`}).toLowerCase();case`bbbbb`:return n.dayPeriod(i,{width:`narrow`,context:`formatting`});default:return n.dayPeriod(i,{width:`wide`,context:`formatting`})}},B:function(e,t,n){let r=e.getHours(),i;switch(i=r>=17?fp.evening:r>=12?fp.afternoon:r>=4?fp.morning:fp.night,t){case`B`:case`BB`:case`BBB`:return n.dayPeriod(i,{width:`abbreviated`,context:`formatting`});case`BBBBB`:return n.dayPeriod(i,{width:`narrow`,context:`formatting`});default:return n.dayPeriod(i,{width:`wide`,context:`formatting`})}},h:function(e,t,n){if(t===`ho`){let t=e.getHours()%12;return t===0&&(t=12),n.ordinalNumber(t,{unit:`hour`})}return dp.h(e,t)},H:function(e,t,n){return t===`Ho`?n.ordinalNumber(e.getHours(),{unit:`hour`}):dp.H(e,t)},K:function(e,t,n){let r=e.getHours()%12;return t===`Ko`?n.ordinalNumber(r,{unit:`hour`}):$(r,t.length)},k:function(e,t,n){let r=e.getHours();return r===0&&(r=24),t===`ko`?n.ordinalNumber(r,{unit:`hour`}):$(r,t.length)},m:function(e,t,n){return t===`mo`?n.ordinalNumber(e.getMinutes(),{unit:`minute`}):dp.m(e,t)},s:function(e,t,n){return t===`so`?n.ordinalNumber(e.getSeconds(),{unit:`second`}):dp.s(e,t)},S:function(e,t){return dp.S(e,t)},X:function(e,t,n){let r=e.getTimezoneOffset();if(r===0)return`Z`;switch(t){case`X`:return hp(r);case`XXXX`:case`XX`:return gp(r);default:return gp(r,`:`)}},x:function(e,t,n){let r=e.getTimezoneOffset();switch(t){case`x`:return hp(r);case`xxxx`:case`xx`:return gp(r);default:return gp(r,`:`)}},O:function(e,t,n){let r=e.getTimezoneOffset();switch(t){case`O`:case`OO`:case`OOO`:return`GMT`+mp(r,`:`);default:return`GMT`+gp(r,`:`)}},z:function(e,t,n){let r=e.getTimezoneOffset();switch(t){case`z`:case`zz`:case`zzz`:return`GMT`+mp(r,`:`);default:return`GMT`+gp(r,`:`)}},t:function(e,t,n){return $(Math.trunc(e/1e3),t.length)},T:function(e,t,n){return $(+e,t.length)}};function mp(e,t=``){let n=e>0?`-`:`+`,r=Math.abs(e),i=Math.trunc(r/60),a=r%60;return a===0?n+String(i):n+String(i)+t+$(a,2)}function hp(e,t){return e%60==0?(e>0?`-`:`+`)+$(Math.abs(e)/60,2):gp(e,t)}function gp(e,t=``){let n=e>0?`-`:`+`,r=Math.abs(e),i=$(Math.trunc(r/60),2),a=$(r%60,2);return n+i+t+a}var _p=(e,t)=>{switch(e){case`P`:return t.date({width:`short`});case`PP`:return t.date({width:`medium`});case`PPP`:return t.date({width:`long`});default:return t.date({width:`full`})}},vp=(e,t)=>{switch(e){case`p`:return t.time({width:`short`});case`pp`:return t.time({width:`medium`});case`ppp`:return t.time({width:`long`});default:return t.time({width:`full`})}},yp={p:vp,P:(e,t)=>{let n=e.match(/(P+)(p+)?/)||[],r=n[1],i=n[2];if(!i)return _p(e,t);let a;switch(r){case`P`:a=t.dateTime({width:`short`});break;case`PP`:a=t.dateTime({width:`medium`});break;case`PPP`:a=t.dateTime({width:`long`});break;default:a=t.dateTime({width:`full`});break}return a.replace(`{{date}}`,_p(r,t)).replace(`{{time}}`,vp(i,t))}},bp=/^D+$/,xp=/^Y+$/,Sp=[`D`,`DD`,`YY`,`YYYY`];function Cp(e){return bp.test(e)}function wp(e){return xp.test(e)}function Tp(e,t,n){let r=Ep(e,t,n);if(console.warn(r),Sp.includes(e))throw RangeError(r)}function Ep(e,t,n){let r=e[0]===`Y`?`years`:`days of the month`;return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${t}\`) for formatting ${r} to the input \`${n}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}var Dp=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Op=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,kp=/^'([^]*?)'?$/,Ap=/''/g,jp=/[a-zA-Z]/;function Mp(e,t,n){let r=Ff(),i=n?.locale??r.locale??ap,a=n?.firstWeekContainsDate??n?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,o=n?.weekStartsOn??n?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,s=Nf(e,n?.in);if(!Gf(s))throw RangeError(`Invalid time value`);let c=t.match(Op).map(e=>{let t=e[0];if(t===`p`||t===`P`){let n=yp[t];return n(e,i.formatLong)}return e}).join(``).match(Dp).map(e=>{if(e===`''`)return{isToken:!1,value:`'`};let t=e[0];if(t===`'`)return{isToken:!1,value:Np(e)};if(pp[t])return{isToken:!0,value:e};if(t.match(jp))throw RangeError("Format string contains an unescaped latin alphabet character `"+t+"`");return{isToken:!1,value:e}});i.localize.preprocessor&&(c=i.localize.preprocessor(s,c));let l={firstWeekContainsDate:a,weekStartsOn:o,locale:i};return c.map(r=>{if(!r.isToken)return r.value;let a=r.value;(!n?.useAdditionalWeekYearTokens&&wp(a)||!n?.useAdditionalDayOfYearTokens&&Cp(a))&&Tp(a,t,String(e));let o=pp[a[0]];return o(s,a,i.localize,l)}).join(``)}function Np(e){let t=e.match(kp);return t?t[1].replace(Ap,`'`):e}Kl.register(jd,Pd,cu,ou,sd,Ed,id,Yu);function Pp({data:e=[],title:t,height:n=300,color:r=`var(--accent)`,fill:i=!1,showGrid:a=!0,timeFormat:o=`HH:mm`,valueFormatter:s=e=>e.toString(),className:c=``}){if(!e||e.length===0)return(0,P.jsx)(`div`,{className:`line-chart ${c}`,style:{height:n},children:(0,P.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`center`,height:`100%`,color:`var(--text-muted)`,fontSize:`var(--text-sm)`},children:`No data available`})});let l={labels:e.map(e=>typeof e.timestamp==`string`?Mp(new Date(e.timestamp),o):Mp(e.timestamp,o)),datasets:[{label:t||`Data`,data:e.map(e=>e.value),borderColor:r,backgroundColor:i?`${r}20`:`transparent`,borderWidth:2,fill:i,tension:.4,pointRadius:3,pointHoverRadius:5,pointBackgroundColor:r,pointBorderColor:`var(--surface-strong)`,pointBorderWidth:2}]},u={responsive:!0,maintainAspectRatio:!1,plugins:{legend:{display:!!t,labels:{color:`var(--text-secondary)`,font:{family:`Inter, system-ui, sans-serif`,size:12}}},tooltip:{backgroundColor:`var(--surface-strong)`,titleColor:`var(--text-primary)`,bodyColor:`var(--text-secondary)`,borderColor:`var(--line)`,borderWidth:1,cornerRadius:8,displayColors:!1,callbacks:{label:e=>{let t=s(e.parsed.y);return`${e.dataset.label}: ${t}`}}}},scales:{x:{grid:{display:a,color:`var(--line)`},ticks:{color:`var(--text-muted)`,font:{family:`Inter, system-ui, sans-serif`,size:11}}},y:{grid:{display:a,color:`var(--line)`},ticks:{color:`var(--text-muted)`,font:{family:`Inter, system-ui, sans-serif`,size:11},callback:e=>s(e)}}},interaction:{intersect:!1,mode:`index`}};return(0,P.jsx)(`div`,{className:`line-chart ${c}`,style:{height:n},children:(0,P.jsx)(Tf,{data:l,options:u})})}Kl.register(jd,Pd,vu,sd,Ed,id);function Fp({data:e=[],title:t,height:n=300,horizontal:r=!1,showGrid:i=!0,valueFormatter:a=e=>e.toString(),className:o=``}){if(!e||e.length===0)return(0,P.jsx)(`div`,{className:`bar-chart ${o}`,style:{height:n},children:(0,P.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`center`,height:`100%`,color:`var(--text-muted)`,fontSize:`var(--text-sm)`},children:`No data available`})});let s={labels:e.map(e=>e.label),datasets:[{label:t||`Data`,data:e.map(e=>e.value),backgroundColor:e.map(e=>e.color?e.color.match(/[a-f0-9]{2}$/i)?e.color:e.color+`20`:`var(--chart-primary)20`),borderColor:e.map(e=>e.color?e.color.replace(/[a-f0-9]{2}$/i,``):`var(--chart-primary)`),borderWidth:1,borderRadius:4,borderSkipped:!1}]},c={responsive:!0,maintainAspectRatio:!1,indexAxis:r?`y`:`x`,plugins:{legend:{display:!!t,labels:{color:`var(--text-secondary)`,font:{family:`Inter, system-ui, sans-serif`,size:12}}},tooltip:{backgroundColor:`var(--surface-strong)`,titleColor:`var(--text-primary)`,bodyColor:`var(--text-secondary)`,borderColor:`var(--line)`,borderWidth:1,cornerRadius:8,displayColors:!1,callbacks:{label:e=>{let t=a(e.parsed[r?`x`:`y`]);return`${e.dataset.label}: ${t}`}}}},scales:{x:{grid:{display:i,color:`var(--line)`},ticks:{color:`var(--text-muted)`,font:{family:`Inter, system-ui, sans-serif`,size:11},callback:r?e=>a(e):void 0}},y:{grid:{display:i,color:`var(--line)`},ticks:{color:`var(--text-muted)`,font:{family:`Inter, system-ui, sans-serif`,size:11},callback:r?void 0:e=>a(e)}}}};return(0,P.jsx)(`div`,{className:`bar-chart ${o}`,style:{height:n},children:(0,P.jsx)(Ef,{data:s,options:c})})}function Ip({title:e,value:t,icon:n,trend:r,sparklineData:i,status:a=`neutral`,description:o,className:s=``}){let c=()=>{switch(r?.direction){case`up`:return`var(--success)`;case`down`:return`var(--danger)`;default:return`var(--text-muted)`}},l=()=>{switch(a){case`healthy`:return`var(--status-healthy)`;case`warning`:return`var(--status-warning)`;case`error`:return`var(--status-error)`;default:return`var(--text-muted)`}};return(0,P.jsxs)(`div`,{className:`metric-card metric-card-${a} ${s}`,children:[(0,P.jsxs)(`div`,{className:`metric-card-header`,children:[(0,P.jsxs)(`div`,{className:`metric-card-title-row`,children:[n&&(0,P.jsx)(`div`,{className:`metric-card-icon`,children:(0,P.jsx)(n,{"aria-hidden":`true`})}),(0,P.jsx)(`h3`,{className:`metric-card-title`,children:e}),a!==`neutral`&&(0,P.jsx)(`div`,{className:`metric-card-status-indicator`,style:{backgroundColor:l()},"aria-label":`Status: ${a}`})]}),o&&(0,P.jsx)(`p`,{className:`metric-card-description`,children:o})]}),(0,P.jsxs)(`div`,{className:`metric-card-content`,children:[(0,P.jsxs)(`div`,{className:`metric-card-value-section`,children:[(0,P.jsx)(`div`,{className:`metric-card-value`,children:t}),r&&(0,P.jsxs)(`div`,{className:`metric-card-trend`,style:{color:c()},children:[(0,P.jsx)(`span`,{className:`trend-arrow trend-${r.direction}`,children:r.direction===`up`?`↗`:r.direction===`down`?`↘`:`→`}),(0,P.jsxs)(`span`,{className:`trend-percentage`,children:[r.percentage>0?`+`:``,r.percentage,`%`]}),r.period&&(0,P.jsx)(`span`,{className:`trend-period`,children:r.period})]})]}),i&&i.length>0&&(0,P.jsx)(`div`,{className:`metric-card-sparkline`,children:(0,P.jsx)(Pp,{data:i,height:60,color:l(),fill:!0,showGrid:!1,valueFormatter:()=>``})})]})]})}function Lp({variant:e=`text`,lines:t=3,height:n,width:r,className:i=``}){return e===`text`?(0,P.jsx)(`div`,{className:`skeleton-container ${i}`,children:Array.from({length:t},(e,n)=>(0,P.jsx)(`div`,{className:`skeleton skeleton-text`,style:{width:n===t-1?`60%`:`100%`}},n))}):e===`card`?(0,P.jsx)(`div`,{className:`skeleton skeleton-card ${i}`,style:{height:n,width:r}}):e===`table-row`?(0,P.jsx)(`div`,{className:`skeleton skeleton-table-row ${i}`,style:{height:n,width:r}}):e===`metric-card`?(0,P.jsxs)(`div`,{className:`skeleton-metric-card ${i}`,children:[(0,P.jsx)(`div`,{className:`skeleton skeleton-text`,style:{width:`40%`,height:`14px`}}),(0,P.jsx)(`div`,{className:`skeleton skeleton-text`,style:{width:`60%`,height:`32px`,marginTop:`8px`}}),(0,P.jsx)(`div`,{className:`skeleton skeleton-text`,style:{width:`30%`,height:`12px`,marginTop:`4px`}})]}):(0,P.jsx)(`div`,{className:`skeleton ${i}`,style:{height:n,width:r}})}function Rp(){let{state:e,retry:t}=Wt((0,v.useCallback)(async()=>{let e=await E(),t=await Promise.allSettled([D(),j(),ce()]),[n,r,i]=t,a=t.filter(e=>e.status===`rejected`).length;return{health:e,providers:n.status===`fulfilled`?n.value:null,usage:r.status===`fulfilled`?r.value:null,cache:i.status===`fulfilled`?i.value:null,telemetryWarning:a>0?`${a} optional telemetry source${a===1?``:`s`} unavailable`:void 0}},[])),n=(0,v.useMemo)(()=>{let e=new Date,t=[];for(let n=23;n>=0;n--){let r=new Date(e.getTime()-n*60*60*1e3),i=75+Math.sin(n*.5)*15,a=(Math.random()-.5)*10;t.push({timestamp:r,value:Math.max(0,Math.min(100,i+a))})}return t},[]),r=(0,v.useMemo)(()=>[{label:`OpenAI`,value:95.2,color:`var(--chart-success)`},{label:`Anthropic`,value:97.8,color:`var(--chart-primary)`},{label:`Kiro`,value:89.1,color:`var(--chart-secondary)`},{label:`Fallback`,value:78.5,color:`var(--chart-warning)`}],[]);if(e.status===`loading`||e.status===`idle`)return(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{eyebrow:`Dashboard`,title:`System Status`,description:`Live service health, provider readiness, cache activity, and request telemetry at a glance.`}),(0,P.jsx)(`div`,{className:`metric-grid`,children:Array.from({length:6},(e,t)=>(0,P.jsx)(Lp,{variant:`metric-card`},t))}),(0,P.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`1fr 1fr`,gap:`var(--space-5)`},children:[(0,P.jsx)(Lp,{variant:`card`,height:`300px`}),(0,P.jsx)(Lp,{variant:`card`,height:`300px`})]})]});if(e.status===`error`)return(0,P.jsx)(Ht,{title:`Dashboard unavailable`,description:e.error.message,onRetry:t});let{health:i,providers:a,usage:o,cache:s,telemetryWarning:c}=e.data,l=o&&Rt(o.stats)?o.stats:{},u=Rt(l.today)?l.today:{},d=Rt(l.month)?l.month:{},f=s?.latest??null,p=a&&Array.isArray(a.clientRoutes)?a.clientRoutes:[],m=a&&Array.isArray(a.providers)?a.providers:[];s&&f&&f.cacheHit;let h=i.ok?`healthy`:`warning`,g=s?f?.cacheHit?`healthy`:`warning`:`error`,_=e=>typeof e!=`number`||isNaN(e)?[]:Array.from({length:12},(t,n)=>({timestamp:new Date(Date.now()-(11-n)*60*60*1e3),value:Math.max(0,e+(Math.random()-.5)*e*.2)}));return(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{eyebrow:`Dashboard`,title:`System Status`,description:`Live service health, provider readiness, cache activity, and request telemetry at a glance.`}),(0,P.jsx)(V,{className:`hero-card`,children:(0,P.jsxs)(`div`,{className:`hero-status`,children:[(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`p`,{className:`eyebrow`,children:`Service Health`}),(0,P.jsx)(`h2`,{children:i.service??`responses-proxy`}),(0,P.jsx)(`p`,{children:i.upstream??`Upstream not reported`})]}),(0,P.jsxs)(`div`,{className:`card-inline-status`,children:[(0,P.jsx)(B,{variant:i.ok?`success`:`warning`,children:i.ok?`Healthy`:`Check status`}),c&&(0,P.jsx)(B,{variant:`warning`,children:c})]})]})}),(0,P.jsxs)(`div`,{className:`metric-grid`,children:[(0,P.jsx)(Ip,{title:`System Health`,value:i.ok?`Healthy`:`Warning`,icon:i.ok?qe:Je,status:h,description:`Overall system status`,sparklineData:_(i.ok?95:75),trend:{direction:i.ok?`up`:`down`,percentage:i.ok?2.1:-1.5,period:`24h`}}),(0,P.jsx)(Ip,{title:`Active Providers`,value:m.length,icon:Ie,status:`healthy`,description:`${R(i.activeProviderId)} currently active`,sparklineData:_(m.length)}),(0,P.jsx)(Ip,{title:`Client Routes`,value:p.length,icon:Re,status:`healthy`,description:`Configured routing endpoints`,sparklineData:_(p.length)}),(0,P.jsx)(Ip,{title:`Cache Hit Rate`,value:o?zt(u.hitRate||0):`N/A`,icon:Ue,status:g,description:s?Bt(f?.timestamp):`Cache unavailable`,sparklineData:o&&typeof u.hitRate==`number`?_(u.hitRate*100):void 0,trend:o&&typeof u.hitRate==`number`?{direction:u.hitRate>.8?`up`:u.hitRate>.6?`neutral`:`down`,percentage:(u.hitRate-.75)*100,period:`today`}:void 0}),(0,P.jsx)(Ip,{title:`Today's Requests`,value:o?L(u.requests||0):`N/A`,icon:Ve,status:o?`healthy`:`error`,description:`API requests processed today`,sparklineData:o&&typeof u.requests==`number`?_(Math.max(1,u.requests/100)):void 0,trend:o?{direction:`up`,percentage:12.5,period:`vs yesterday`}:void 0}),(0,P.jsx)(Ip,{title:`Monthly Savings`,value:o?zt(d.avgCacheSavedPercent||0):`N/A`,icon:He,status:o?`healthy`:`error`,description:`Average cache efficiency this month`,sparklineData:o&&typeof d.avgCacheSavedPercent==`number`?_(d.avgCacheSavedPercent*100):void 0,trend:o?{direction:`up`,percentage:5.2,period:`vs last month`}:void 0})]}),(0,P.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`1fr 1fr`,gap:`var(--space-5)`,marginBottom:`var(--space-6)`},children:[(0,P.jsx)(V,{title:`Cache Hit Rate Trend`,description:`24-hour cache performance overview`,children:(0,P.jsx)(Pp,{data:n,title:`Hit Rate %`,height:250,color:`var(--chart-primary)`,fill:!0,valueFormatter:e=>`${e.toFixed(1)}%`})}),(0,P.jsx)(V,{title:`Provider Performance`,description:`Response time comparison across providers`,children:(0,P.jsx)(Fp,{data:r,title:`Avg Response Time (ms)`,height:250,valueFormatter:e=>`${e.toFixed(1)}ms`})})]}),(0,P.jsx)(V,{title:`System Overview`,description:`Current backend-reported runtime details.`,children:(0,P.jsxs)(`dl`,{className:`detail-list`,children:[(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`dt`,{children:`Upstream Base URL`}),(0,P.jsx)(`dd`,{children:R(i.upstream)})]}),(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`dt`,{children:`Fallback Upstream`}),(0,P.jsx)(`dd`,{children:R(i.fallback)})]}),(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`dt`,{children:`Latest Cache Provider`}),(0,P.jsx)(`dd`,{children:s?R(f?.providerId):`Unavailable`})]}),(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`dt`,{children:`Latest Request ID`}),(0,P.jsx)(`dd`,{children:s?R(f?.requestId):`Unavailable`})]}),(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`dt`,{children:`Latest Cached Tokens`}),(0,P.jsx)(`dd`,{children:s?L(f?.cachedTokens):`Unavailable`})]}),(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`dt`,{children:`Latest Saved Percent`}),(0,P.jsx)(`dd`,{children:s?zt(f?.cacheSavedPercent):`Unavailable`})]})]})})]})}function zp(){let[e,t]=(0,v.useState)([]),[n,r]=(0,v.useState)(!0),[i,a]=(0,v.useState)(!1),[o,s]=(0,v.useState)(``),[c,l]=(0,v.useState)(!1),[u,d]=(0,v.useState)(``),f=(0,v.useCallback)(async()=>{try{r(!0);let e=(await D()).clientRoutes||[],n=[];for(let t of e){let e=Array.isArray(t.apiKeys)?t.apiKeys.filter(Boolean):[];for(let r of e)n.push({routeKey:t.key,apiKey:r,providerId:t.providerId})}t(n)}catch{}finally{r(!1)}},[]);(0,v.useEffect)(()=>{f()},[f]);let p=async()=>{if(!o.trim()){d(`Name is required`);return}l(!0),d(``);try{await ne({client:o.trim()}),s(``),a(!1),await f()}catch(e){d(e.message||`Failed to create`)}finally{l(!1)}},m=async e=>{if(confirm(`Delete route "${e.routeKey}" and its API key?`))try{await ie(e.routeKey),await f()}catch{}};return(0,P.jsxs)(V,{title:`API Keys`,description:`Manage access keys for CLI tools and clients.`,actions:(0,P.jsxs)(`button`,{className:`button-primary`,onClick:()=>a(!0),style:{minHeight:36},children:[(0,P.jsx)(at,{style:{width:14,height:14}}),`New Key`]}),children:[i&&(0,P.jsxs)(`div`,{style:{marginBottom:`var(--space-4)`,padding:`var(--space-3) var(--space-4)`,background:`var(--surface-muted)`,borderRadius:`var(--radius-md)`,border:`1px solid var(--line)`},children:[(0,P.jsxs)(`div`,{style:{display:`flex`,gap:`var(--space-2)`,alignItems:`center`},children:[(0,P.jsx)(`input`,{type:`text`,value:o,onChange:e=>s(e.target.value),onKeyDown:e=>{e.key===`Enter`&&p()},placeholder:`Key name (e.g. my-laptop)`,autoFocus:!0,style:{flex:1,minHeight:36,fontSize:`var(--text-sm)`,padding:`6px 12px`}}),(0,P.jsx)(`button`,{className:`button-primary`,onClick:p,disabled:c||!o.trim(),style:{minHeight:36},children:c?`...`:`Create`}),(0,P.jsx)(`button`,{className:`button-link`,onClick:()=>{a(!1),d(``)},style:{minHeight:36},children:`Cancel`})]}),u&&(0,P.jsx)(`p`,{style:{margin:`var(--space-2) 0 0`,color:`var(--danger)`,fontSize:`var(--text-xs)`},children:u})]}),n?(0,P.jsx)(`p`,{style:{color:`var(--text-muted)`,fontSize:`var(--text-sm)`},children:`Loading...`}):e.length===0?(0,P.jsx)(`p`,{style:{color:`var(--text-muted)`,fontSize:`var(--text-sm)`,textAlign:`center`,padding:`var(--space-4)`},children:`No API keys yet. Create one to connect your CLI tools.`}):(0,P.jsx)(`div`,{style:{display:`grid`,gap:`var(--space-2)`},children:e.map((e,t)=>(0,P.jsx)(Bp,{entry:e,onDelete:()=>m(e)},`${e.routeKey}-${t}`))})]})}function Bp({entry:e,onDelete:t}){let[n,r]=(0,v.useState)(!1),[i,a]=(0,v.useState)(!1),o=()=>{navigator.clipboard.writeText(e.apiKey).catch(()=>{}),r(!0),setTimeout(()=>r(!1),1500)},s=`${e.apiKey.slice(0,8)}${`•`.repeat(12)}${e.apiKey.slice(-4)}`;return(0,P.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`var(--space-3)`,padding:`var(--space-2) var(--space-3)`,background:`var(--surface-muted)`,borderRadius:`var(--radius-sm)`,border:`1px solid var(--line)`},children:[(0,P.jsx)(`span`,{style:{width:8,height:8,borderRadius:`50%`,background:`var(--success)`,boxShadow:`0 0 0 3px var(--success-soft)`,flexShrink:0}}),(0,P.jsx)(`span`,{style:{fontSize:`var(--text-sm)`,fontWeight:600,minWidth:80},children:e.routeKey}),(0,P.jsx)(`code`,{onClick:()=>a(!i),style:{flex:1,fontSize:`var(--text-xs)`,fontFamily:`monospace`,color:`var(--text-secondary)`,cursor:`pointer`,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},title:`Click to reveal/hide`,children:i?e.apiKey:s}),(0,P.jsx)(`button`,{onClick:o,style:{background:`none`,border:`none`,color:`var(--accent)`,cursor:`pointer`,fontSize:`var(--text-xs)`,fontWeight:600,minHeight:`auto`,whiteSpace:`nowrap`},children:n?`✓`:`Copy`}),(0,P.jsx)(`button`,{onClick:t,style:{background:`none`,border:`none`,color:`var(--danger)`,cursor:`pointer`,fontSize:`var(--text-xs)`,fontWeight:600,minHeight:`auto`},children:`Delete`})]})}var Vp={chat:{label:`Chat`,icon:`💬`,description:`Text generation and conversation`},embedding:{label:`Embeddings`,icon:`🔢`,description:`Text embeddings and similarity`},tts:{label:`Text-to-Speech`,icon:`🔊`,description:`Convert text to audio`},stt:{label:`Speech-to-Text`,icon:`🎤`,description:`Convert audio to text`},image:{label:`Image Generation`,icon:`🎨`,description:`Generate images from text`},vision:{label:`Vision`,icon:`👁️`,description:`Analyze and understand images`},video:{label:`Video`,icon:`🎬`,description:`Video generation and analysis`},web_search:{label:`Web Search`,icon:`🔍`,description:`Search the web for information`},web_fetch:{label:`Web Fetch`,icon:`🌐`,description:`Fetch and analyze web content`}},Hp={oauth:{label:`OAuth`,description:`Secure OAuth authentication flow`,complexity:2},api_key:{label:`API Key`,description:`Simple API key authentication`,complexity:1},browser_cookie:{label:`Browser Cookie`,description:`Extract session from browser`,complexity:3},local_cli:{label:`Local CLI`,description:`Use local CLI authentication`,complexity:4},none:{label:`None`,description:`No authentication required`,complexity:0}},Up=[{id:`claude-code`,name:`claude-code`,displayName:`Claude Code`,description:`Anthropic's official CLI for Claude with high quotas`,tier:`subscription`,serviceKinds:[`chat`,`vision`],authTypes:[`oauth`,`api_key`],preferredAuthType:`oauth`,defaultBaseUrl:`https://api.anthropic.com`,signupUrl:`https://claude.ai/code`,docsUrl:`https://docs.anthropic.com/claude/docs/claude-code`,defaultModels:[`claude-3-5-sonnet-20241022`,`claude-3-5-haiku-20241022`],estimatedSetupTime:`2 minutes`,popularity:5},{id:`openai-codex`,name:`openai-codex`,displayName:`OpenAI Codex`,description:`OpenAI's premium API with GPT-4 and advanced models`,tier:`subscription`,serviceKinds:[`chat`,`embedding`,`tts`,`stt`,`image`,`vision`],authTypes:[`api_key`],preferredAuthType:`api_key`,defaultBaseUrl:`https://api.openai.com/v1`,signupUrl:`https://platform.openai.com/signup`,docsUrl:`https://platform.openai.com/docs`,defaultModels:[`gpt-4-turbo`,`gpt-4o`,`gpt-3.5-turbo`],estimatedSetupTime:`3 minutes`,popularity:5},{id:`gemini-pro`,name:`gemini-pro`,displayName:`Gemini Pro`,description:`Google's premium Gemini models with high quotas`,tier:`subscription`,serviceKinds:[`chat`,`vision`,`embedding`],authTypes:[`api_key`],preferredAuthType:`api_key`,defaultBaseUrl:`https://generativelanguage.googleapis.com`,signupUrl:`https://makersuite.google.com/`,docsUrl:`https://ai.google.dev/docs`,defaultModels:[`gemini-1.5-pro`,`gemini-1.5-flash`],estimatedSetupTime:`3 minutes`,popularity:4},{id:`github-copilot`,name:`github-copilot`,displayName:`GitHub Copilot`,description:`GitHub's AI coding assistant with chat capabilities`,tier:`subscription`,serviceKinds:[`chat`],authTypes:[`oauth`,`local_cli`],preferredAuthType:`oauth`,defaultBaseUrl:`https://api.github.com`,signupUrl:`https://github.com/features/copilot`,docsUrl:`https://docs.github.com/en/copilot`,defaultModels:[`gpt-4`,`gpt-3.5-turbo`],estimatedSetupTime:`5 minutes`,popularity:4},{id:`cursor-pro`,name:`cursor-pro`,displayName:`Cursor Pro`,description:`Cursor's premium AI coding models`,tier:`subscription`,serviceKinds:[`chat`],authTypes:[`api_key`,`oauth`],preferredAuthType:`oauth`,defaultBaseUrl:`https://api.cursor.sh`,signupUrl:`https://cursor.sh/`,docsUrl:`https://docs.cursor.sh/`,defaultModels:[`cursor-fast`,`cursor-smart`],estimatedSetupTime:`3 minutes`,popularity:3},{id:`kiro-ide`,name:`kiro-ide`,displayName:`Kiro IDE`,description:`Kiro's integrated development environment AI`,tier:`subscription`,serviceKinds:[`chat`,`vision`],authTypes:[`oauth`],preferredAuthType:`oauth`,defaultBaseUrl:`https://codewhisperer.us-east-1.amazonaws.com`,signupUrl:`https://kiro.ai/`,docsUrl:`https://docs.kiro.ai/`,riskNotice:{level:`medium`,title:`Subscription Usage Notice`,message:`This provider uses a subscription/OAuth session not officially licensed for proxy/router use. Account may be restricted or banned. Use at your own risk.`,learnMoreUrl:`https://docs.kiro.ai/terms`},defaultModels:[`kr/claude-sonnet-4.6`,`kr/claude-opus-4.8`],estimatedSetupTime:`4 minutes`,popularity:3},{id:`glm`,name:`glm`,displayName:`GLM (Zhipu AI)`,description:`Cost-effective Chinese AI models with good performance`,tier:`cheap`,serviceKinds:[`chat`,`embedding`,`image`],authTypes:[`api_key`],preferredAuthType:`api_key`,defaultBaseUrl:`https://open.bigmodel.cn/api/paas/v4`,signupUrl:`https://open.bigmodel.cn/`,docsUrl:`https://open.bigmodel.cn/dev/api`,defaultModels:[`glm-4`,`glm-4v`,`glm-3-turbo`],estimatedSetupTime:`4 minutes`,popularity:4},{id:`minimax`,name:`minimax`,displayName:`MiniMax`,description:`Affordable Chinese AI models with multimodal support`,tier:`cheap`,serviceKinds:[`chat`,`tts`,`image`],authTypes:[`api_key`],preferredAuthType:`api_key`,defaultBaseUrl:`https://api.minimax.chat/v1`,signupUrl:`https://www.minimaxi.com/`,docsUrl:`https://www.minimaxi.com/document/guides/chat-model/pro/api`,defaultModels:[`abab6.5s-chat`,`abab6.5-chat`],estimatedSetupTime:`5 minutes`,popularity:3},{id:`kimi`,name:`kimi`,displayName:`Kimi (Moonshot AI)`,description:`Long-context Chinese AI models at competitive prices`,tier:`cheap`,serviceKinds:[`chat`],authTypes:[`api_key`],preferredAuthType:`api_key`,defaultBaseUrl:`https://api.moonshot.cn/v1`,signupUrl:`https://platform.moonshot.cn/`,docsUrl:`https://platform.moonshot.cn/docs`,defaultModels:[`moonshot-v1-8k`,`moonshot-v1-32k`,`moonshot-v1-128k`],estimatedSetupTime:`4 minutes`,popularity:4},{id:`deepseek`,name:`deepseek`,displayName:`DeepSeek`,description:`High-performance coding and reasoning models at low cost`,tier:`cheap`,serviceKinds:[`chat`],authTypes:[`api_key`],preferredAuthType:`api_key`,defaultBaseUrl:`https://api.deepseek.com`,signupUrl:`https://platform.deepseek.com/`,docsUrl:`https://platform.deepseek.com/api-docs`,defaultModels:[`deepseek-chat`,`deepseek-coder`],estimatedSetupTime:`3 minutes`,popularity:5},{id:`groq`,name:`groq`,displayName:`Groq`,description:`Ultra-fast inference with competitive pricing`,tier:`cheap`,serviceKinds:[`chat`],authTypes:[`api_key`],preferredAuthType:`api_key`,defaultBaseUrl:`https://api.groq.com/openai/v1`,signupUrl:`https://console.groq.com/`,docsUrl:`https://console.groq.com/docs`,defaultModels:[`llama-3.1-70b-versatile`,`llama-3.1-8b-instant`],estimatedSetupTime:`2 minutes`,popularity:4},{id:`xai`,name:`xai`,displayName:`xAI (Grok)`,description:`Elon Musk's xAI with Grok models`,tier:`cheap`,serviceKinds:[`chat`],authTypes:[`api_key`],preferredAuthType:`api_key`,defaultBaseUrl:`https://api.xai.com/v1`,signupUrl:`https://x.ai/`,docsUrl:`https://docs.x.ai/`,defaultModels:[`grok-beta`,`grok-vision-beta`],estimatedSetupTime:`4 minutes`,popularity:3},{id:`mistral`,name:`mistral`,displayName:`Mistral AI`,description:`European AI models with strong performance and fair pricing`,tier:`cheap`,serviceKinds:[`chat`,`embedding`],authTypes:[`api_key`],preferredAuthType:`api_key`,defaultBaseUrl:`https://api.mistral.ai/v1`,signupUrl:`https://console.mistral.ai/`,docsUrl:`https://docs.mistral.ai/`,defaultModels:[`mistral-large-latest`,`mistral-small-latest`],estimatedSetupTime:`3 minutes`,popularity:4},{id:`openrouter`,name:`openrouter`,displayName:`OpenRouter`,description:`Access to multiple AI models through a single API`,tier:`cheap`,serviceKinds:[`chat`,`image`,`vision`],authTypes:[`api_key`],preferredAuthType:`api_key`,defaultBaseUrl:`https://openrouter.ai/api/v1`,signupUrl:`https://openrouter.ai/`,docsUrl:`https://openrouter.ai/docs`,defaultModels:[`anthropic/claude-3.5-sonnet`,`openai/gpt-4-turbo`],estimatedSetupTime:`2 minutes`,popularity:4},{id:`iflow`,name:`iflow`,displayName:`iFlow`,description:`Free AI models with basic quotas for testing`,tier:`free`,serviceKinds:[`chat`],authTypes:[`api_key`,`none`],preferredAuthType:`api_key`,defaultBaseUrl:`https://api.iflow.ai/v1`,signupUrl:`https://iflow.ai/`,docsUrl:`https://docs.iflow.ai/`,defaultModels:[`iflow-chat`,`iflow-fast`],estimatedSetupTime:`2 minutes`,popularity:3},{id:`qwen`,name:`qwen`,displayName:`Qwen (Alibaba)`,description:`Alibaba's free AI models with decent performance`,tier:`free`,serviceKinds:[`chat`,`vision`],authTypes:[`api_key`],preferredAuthType:`api_key`,defaultBaseUrl:`https://dashscope.aliyuncs.com/api/v1`,signupUrl:`https://dashscope.aliyun.com/`,docsUrl:`https://help.aliyun.com/zh/dashscope/`,defaultModels:[`qwen-turbo`,`qwen-plus`],estimatedSetupTime:`5 minutes`,popularity:3},{id:`kiro-free`,name:`kiro-free`,displayName:`Kiro Free`,description:`Free tier of Kiro AI with limited quotas`,tier:`free`,serviceKinds:[`chat`],authTypes:[`oauth`,`browser_cookie`],preferredAuthType:`oauth`,defaultBaseUrl:`https://codewhisperer.us-east-1.amazonaws.com`,signupUrl:`https://kiro.ai/`,docsUrl:`https://docs.kiro.ai/`,riskNotice:{level:`high`,title:`Free Account Usage Notice`,message:`This provider uses a free account not intended for proxy/router use. High risk of account restrictions or bans. Use only for testing.`,learnMoreUrl:`https://docs.kiro.ai/terms`},defaultModels:[`kr/claude-haiku-3.5`,`kr/gpt-3.5-turbo`],estimatedSetupTime:`3 minutes`,popularity:2},{id:`opencode`,name:`opencode`,displayName:`OpenCode`,description:`Free coding-focused AI models`,tier:`free`,serviceKinds:[`chat`],authTypes:[`api_key`,`none`],preferredAuthType:`api_key`,defaultBaseUrl:`https://api.opencode.ai/v1`,signupUrl:`https://opencode.ai/`,docsUrl:`https://docs.opencode.ai/`,defaultModels:[`opencode-chat`,`opencode-instruct`],estimatedSetupTime:`3 minutes`,popularity:2},{id:`gemini-free`,name:`gemini-free`,displayName:`Gemini Free`,description:`Google's free Gemini models with rate limits`,tier:`free`,serviceKinds:[`chat`,`vision`],authTypes:[`api_key`],preferredAuthType:`api_key`,defaultBaseUrl:`https://generativelanguage.googleapis.com`,signupUrl:`https://makersuite.google.com/`,docsUrl:`https://ai.google.dev/docs`,defaultModels:[`gemini-1.5-flash`,`gemini-1.0-pro`],estimatedSetupTime:`3 minutes`,popularity:4},{id:`cloudflare-ai`,name:`cloudflare-ai`,displayName:`Cloudflare AI`,description:`Cloudflare's free AI models on Workers platform`,tier:`free`,serviceKinds:[`chat`,`embedding`,`image`],authTypes:[`api_key`],preferredAuthType:`api_key`,defaultBaseUrl:`https://api.cloudflare.com/client/v4`,signupUrl:`https://dash.cloudflare.com/`,docsUrl:`https://developers.cloudflare.com/workers-ai/`,defaultModels:[`@cf/meta/llama-3.1-8b-instruct`,`@cf/microsoft/phi-2`],estimatedSetupTime:`4 minutes`,popularity:3},{id:`nvidia-nim`,name:`nvidia-nim`,displayName:`NVIDIA NIM`,description:`NVIDIA's free inference microservices`,tier:`free`,serviceKinds:[`chat`,`embedding`],authTypes:[`api_key`],preferredAuthType:`api_key`,defaultBaseUrl:`https://integrate.api.nvidia.com/v1`,signupUrl:`https://build.nvidia.com/`,docsUrl:`https://docs.nvidia.com/nim/`,defaultModels:[`nvidia/llama-3.1-nemotron-70b-instruct`],estimatedSetupTime:`5 minutes`,popularity:3}];function Wp(e){return Up.find(t=>t.id===e)}function Gp(e){let t=e.toLowerCase();return t.includes(`claude-code`)||t.includes(`copilot`)||t.includes(`cursor`)||t.includes(`subscription`)||t.includes(`premium`)||t.includes(`pro`)?`subscription`:t.includes(`free`)||t.includes(`trial`)||t.includes(`demo`)||t.includes(`kiro-free`)||t.includes(`huggingface-free`)?`free`:t.includes(`deepseek`)||t.includes(`groq`)||t.includes(`together`)||t.includes(`cheap`)||t.includes(`budget`)?`cheap`:`custom`}function Kp(e){switch(e){case`api_key`:return[`api_key`];case`chatgpt_oauth`:return[`oauth`];case`kiro`:return[`oauth`];default:return[`api_key`]}}function qp(e,t){let n=e.toLowerCase(),r=[];return r.push(`chat`),(n.includes(`claude`)||n.includes(`gpt-4`)||n.includes(`vision`))&&r.push(`vision`),(n.includes(`dall-e`)||n.includes(`midjourney`)||n.includes(`stable-diffusion`))&&r.push(`image`),(n.includes(`embedding`)||n.includes(`text-embedding`))&&r.push(`embedding`),r}function Jp(e,t){let n=Array.isArray(e.providerApiKeys)&&e.providerApiKeys.length>0,r=e.chatgptAccountId;return n||r?t?.quotaExhausted?`quota_exhausted`:t?.errorMessage?t.errorMessage.includes(`auth`)||t.errorMessage.includes(`unauthorized`)?`auth_expired`:t.errorMessage.includes(`rate`)||t.errorMessage.includes(`limit`)?`rate_limited`:`degraded`:t?.accountsStatus?.some(e=>e.status===`error`||e.status===`expired`)?`auth_expired`:`healthy`:`not_configured`}function Yp(e){return{"claude-code":`Claude Code`,"chatgpt-web":`ChatGPT Web`,deepseek:`DeepSeek`,groq:`Groq`,together:`Together AI`,"kiro-free":`Kiro Free`,anthropic:`Anthropic`,openai:`OpenAI`}[e]||e.split(`-`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}function Xp(e,t){let n=!!Wp(e.id),r=n?Gp(e.name):`custom`,i=Kp(e.authMode),a=qp(e.name,e.capabilities),o=Jp(e,t),s=n?Yp(e.name):e.name,c=n?`${s} provider`:`Custom endpoint: ${e.baseUrl}`,l=[];e.chatgptAccountId&&l.push({id:e.chatgptAccountId,label:`OAuth Account`,authType:`oauth`,status:o===`auth_expired`?`expired`:`connected`,routingMode:`priority`}),Array.isArray(e.providerApiKeys)&&e.providerApiKeys.length>0&&e.providerApiKeys.forEach((e,t)=>{l.push({id:`api-key-${t}`,label:`API Key ${t+1}`,authType:`api_key`,status:`connected`,routingMode:`round_robin`})});let u;return e.capabilities.usageCheckEnabled&&t&&(u={quotaType:`unknown`,usagePercent:t.quotaExhausted?100:void 0,hardLimitReached:t.quotaExhausted}),{id:e.id,name:e.name,displayName:s,description:c,tier:r,serviceKinds:a,authTypes:i,preferredAuthType:i[0],enabled:!0,configured:l.length>0,healthStatus:o,priority:r===`subscription`?1:r===`cheap`?2:r===`free`?3:4,fallbackEligible:o===`healthy`&&l.length>0,accounts:l,quota:u,providerApiKeys:e.providerApiKeys,models:[],createdAt:e.createdAt,updatedAt:e.updatedAt}}async function Zp(){try{let e=(await b(`/api/providers`)).providers||[],t=e.map(async e=>{try{let t=await b(`/api/providers/${e.id}/usage`);return{providerId:e.id,...t}}catch(t){return{providerId:e.id,usageCheckEnabled:e.capabilities.usageCheckEnabled,errorMessage:t instanceof Error?t.message:`Usage check failed`}}}),n=await Promise.all(t),r=new Map(n.map(e=>[e.providerId,e]));return e.map(e=>Xp(e,r.get(e.id)))}catch(e){throw console.error(`Failed to fetch providers:`,e),Error(`Failed to load provider data`)}}async function Qp(e){try{let t=await x(`/api/providers/${e}/test`,`POST`,{});return{success:t.success||!1,message:t.message||`Test completed`,latencyMs:t.latencyMs}}catch(e){return{success:!1,message:e instanceof Error?e.message:`Test failed`}}}async function $p(){try{await x(`/api/providers/refresh-health`,`POST`,{})}catch(e){throw console.error(`Failed to refresh provider health:`,e),Error(`Failed to refresh provider health`)}}var em=new class{ws=null;callbacks=new Set;reconnectAttempts=0;maxReconnectAttempts=5;reconnectDelay=1e3;reconnectTimer=null;isConnecting=!1;constructor(e=`/ws/health`){this.wsUrl=e}connect(){if(!(this.ws&&this.ws.readyState===WebSocket.OPEN)&&!this.isConnecting){this.isConnecting=!0;try{let e=`${window.location.protocol===`https:`?`wss:`:`ws:`}//${window.location.host}${this.wsUrl}`;console.log(`Connecting to health WebSocket:`,e),this.ws=new WebSocket(e),this.ws.onopen=()=>{console.log(`Health WebSocket connected`),this.isConnecting=!1,this.reconnectAttempts=0,this.reconnectDelay=1e3},this.ws.onmessage=e=>{try{let t=JSON.parse(e.data);this.handleMessage(t)}catch(e){console.error(`Failed to parse health WebSocket message:`,e)}},this.ws.onclose=e=>{console.log(`Health WebSocket disconnected:`,e.code,e.reason),this.isConnecting=!1,this.ws=null,e.code!==1e3&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()},this.ws.onerror=e=>{console.error(`Health WebSocket error:`,e),this.isConnecting=!1}}catch(e){console.error(`Failed to create health WebSocket:`,e),this.isConnecting=!1}}}disconnect(){this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null),this.ws&&=(this.ws.close(1e3,`Client disconnect`),null),this.isConnecting=!1,this.reconnectAttempts=0}subscribe(e){return this.callbacks.add(e),this.callbacks.size===1&&this.connect(),()=>{this.callbacks.delete(e),this.callbacks.size===0&&this.disconnect()}}getConnectionStatus(){if(this.isConnecting)return`connecting`;if(!this.ws)return`disconnected`;switch(this.ws.readyState){case WebSocket.CONNECTING:return`connecting`;case WebSocket.OPEN:return`connected`;case WebSocket.CLOSING:case WebSocket.CLOSED:return`disconnected`;default:return`error`}}handleMessage(e){for(let t of this.callbacks)try{t(e)}catch(e){console.error(`Error in health update callback:`,e)}}scheduleReconnect(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectAttempts++;let e=Math.min(this.reconnectDelay*2**(this.reconnectAttempts-1),3e4);console.log(`Scheduling health WebSocket reconnect attempt ${this.reconnectAttempts} in ${e}ms`),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},e)}};function tm(){let[e,t]=(0,v.useState)([]),[n,r]=(0,v.useState)(!0),[i,a]=(0,v.useState)(null),[o,s]=(0,v.useState)(null),[c,l]=(0,v.useState)(new Map),[u,d]=(0,v.useState)(null),f=(0,v.useCallback)(async()=>{try{r(!0),a(null);let e=await Zp(),n=Up.map(t=>{let n=e.find(e=>e.id===t.id||e.name===t.name);return n?{...n,displayName:t.displayName,description:t.description,tier:t.tier,serviceKinds:t.serviceKinds,authTypes:t.authTypes,preferredAuthType:t.preferredAuthType,riskNotice:t.riskNotice}:{id:t.id,name:t.name,displayName:t.displayName,description:t.description,tier:t.tier,serviceKinds:t.serviceKinds,authTypes:t.authTypes,preferredAuthType:t.preferredAuthType,enabled:!0,configured:!1,healthStatus:`not_configured`,priority:t.popularity||3,fallbackEligible:!1,accounts:[],models:[],riskNotice:t.riskNotice}}),i=new Set(Up.map(e=>e.id)),o=e.filter(e=>!i.has(e.id));t([...n,...o]),s(new Date)}catch(e){a(e instanceof Error?e.message:`Failed to load providers`)}finally{r(!1)}},[]),p=(0,v.useCallback)(e=>{if(e.type===`health_update`){let n=e;l(e=>{let t=new Map(e);return t.set(n.providerId,n.metrics),t}),t(e=>e.map(e=>{if(e.id===n.providerId){let t=n.metrics,r=e.healthStatus;return r=t.healthScore>=70?`healthy`:t.healthScore>=40?`degraded`:`unhealthy`,t.quotaStatus.usagePercent>90&&(r=`rate_limited`),t.quotaStatus.usagePercent>=100&&(r=`quota_exhausted`),{...e,healthStatus:r,healthScore:t.healthScore,lastHealthCheck:new Date(t.lastChecked).toISOString()}}return e}))}else e.type===`health_summary`&&d(e.summary)},[]);(0,v.useEffect)(()=>em.subscribe(p),[p]),(0,v.useEffect)(()=>{f()},[f]);let m=(0,v.useCallback)(async()=>{await f()},[f]),h=(0,v.useCallback)(async()=>{try{await $p(),await f()}catch(e){a(e instanceof Error?e.message:`Failed to refresh health`)}},[f]);return{providers:(0,v.useMemo)(()=>e.map(e=>{let t=c.get(e.id);return{...e,healthMetrics:t}}),[e,c]),loading:n,error:i,lastRefresh:o,healthSummary:u,refresh:m,refreshHealth:h}}function nm(e){let[t,n]=(0,v.useState)(null),[r,i]=(0,v.useState)(!1),[a,o]=(0,v.useState)(null);return(0,v.useEffect)(()=>{if(!e){n(null),i(!1),o(null);return}let t=e=>e?{id:e.id,name:e.name,displayName:e.displayName,description:e.description,tier:e.tier,serviceKinds:e.serviceKinds,authTypes:e.authTypes,preferredAuthType:e.preferredAuthType,enabled:!0,configured:!1,healthStatus:`not_configured`,priority:e.popularity||3,fallbackEligible:!1,accounts:[],models:[],riskNotice:e.riskNotice}:null;(async()=>{try{i(!0),o(null);let r=(await Zp()).find(t=>t.id===e||t.name===e);if(r){let t=Wp(e);n({...r,...t?{displayName:t.displayName,description:t.description,tier:t.tier,serviceKinds:t.serviceKinds,authTypes:t.authTypes,preferredAuthType:t.preferredAuthType,riskNotice:t.riskNotice}:{}})}else{let r=t(Wp(e));r?n(r):o(`Provider not found`)}}catch(r){let i=t(Wp(e));i?n(i):o(r instanceof Error?r.message:`Failed to load provider`)}finally{i(!1)}})()},[e]),{provider:t,loading:r,error:a,refresh:(0,v.useCallback)(async()=>{if(!e)return;let t=e=>e?{id:e.id,name:e.name,displayName:e.displayName,description:e.description,tier:e.tier,serviceKinds:e.serviceKinds,authTypes:e.authTypes,preferredAuthType:e.preferredAuthType,enabled:!0,configured:!1,healthStatus:`not_configured`,priority:e.popularity||3,fallbackEligible:!1,accounts:[],models:[],riskNotice:e.riskNotice}:null;try{i(!0),o(null);let r=(await Zp()).find(t=>t.id===e||t.name===e);if(r){let t=Wp(e);n({...r,...t?{displayName:t.displayName,description:t.description,tier:t.tier,serviceKinds:t.serviceKinds,authTypes:t.authTypes,preferredAuthType:t.preferredAuthType,riskNotice:t.riskNotice}:{}})}else{let r=t(Wp(e));r&&n(r)}}catch(r){let i=t(Wp(e));i?n(i):o(r instanceof Error?r.message:`Failed to refresh provider`)}finally{i(!1)}},[e])}}function rm(){let[e,t]=(0,v.useState)(new Map),[n,r]=(0,v.useState)(new Set);return{testProvider:(0,v.useCallback)(async e=>{if(!n.has(e))try{r(t=>new Set(t).add(e));let n=await Qp(e);return t(t=>new Map(t).set(e,n)),n}catch(n){let r={success:!1,message:n instanceof Error?n.message:`Test failed`};return t(t=>new Map(t).set(e,r)),r}finally{r(t=>{let n=new Set(t);return n.delete(e),n})}},[n]),getTestResult:(0,v.useCallback)(t=>e.get(t),[e]),isTestingProvider:(0,v.useCallback)(e=>n.has(e),[n]),clearTestResult:(0,v.useCallback)(e=>{t(t=>{let n=new Map(t);return n.delete(e),n})},[])}}function im(){let[e,t]=(0,v.useState)(`disconnected`),[n,r]=(0,v.useState)(null),[i,a]=(0,v.useState)(new Map),o=(0,v.useCallback)(e=>{if(e.type===`health_update`){let t=e;a(e=>{let n=new Map(e);return n.set(t.providerId,t.metrics),n})}else e.type===`health_summary`&&r(e.summary)},[]);return(0,v.useEffect)(()=>{let e=()=>{t(em.getConnectionStatus())};e();let n=setInterval(e,1e3);return()=>clearInterval(n)},[]),(0,v.useEffect)(()=>em.subscribe(o),[o]),{connectionStatus:e,healthSummary:n,providerHealth:i,connect:(0,v.useCallback)(()=>{em.connect()},[]),disconnect:(0,v.useCallback)(()=>{em.disconnect()},[])}}function am(e=!0){let{connectionStatus:t,healthSummary:n,providerHealth:r}=im();return(0,v.useEffect)(()=>(e&&em.connect(),()=>{e&&em.disconnect()}),[e]),{connectionStatus:t,healthSummary:n,providerHealth:r,isEnabled:e}}function om(e,t){return t===`cursor`?e.split(`
|
|
13
13
|
`).map((e,t)=>{if(e.trim().startsWith(`//`))return(0,P.jsx)(`div`,{className:`terminal-comment`,children:e},t);let n=e.split(`:`);if(n.length>=2){let e=n[0],r=n.slice(1).join(`:`);return(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`span`,{className:`terminal-key`,children:e}),`:`,(0,P.jsx)(`span`,{className:`terminal-value`,children:r})]},t)}return(0,P.jsx)(`div`,{className:`terminal-text`,children:e},t)}):e.split(`
|
|
14
|
-
`).map((e,t)=>{if(e.startsWith(`export `)){let n=e.split(`=`),r=n[0],i=n.slice(1).join(`=`);return(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`span`,{className:`command-highlight`,children:`export`}),` `,(0,P.jsx)(`span`,{className:`variable-highlight`,children:r.replace(`export `,``)}),`=`,(0,P.jsx)(`span`,{className:`terminal-value`,children:i})]},t)}return(0,P.jsx)(`div`,{children:e},t)})}function sm({health:e,loading:t,endpointUrl:n,onRefresh:r}){let i=e?.ok??!1,[a,o]=(0,v.useState)(!1);return(0,P.jsxs)(V,{title:`Server Status`,description:`Local router server health and information`,actions:(0,P.jsx)($t,{onClick:r,isRefreshing:t}),children:[(0,P.jsxs)(`div`,{className:`endpoint-status-grid`,children:[(0,P.jsxs)(`div`,{className:`status-item`,children:[(0,P.jsx)(`div`,{className:`status-indicator`,children:i?(0,P.jsx)(`span`,{className:`status-pulse-dot`}):(0,P.jsx)(Je,{className:`status-icon status-error`})}),(0,P.jsxs)(`div`,{className:`status-details`,children:[(0,P.jsx)(`div`,{className:`status-label`,children:`Server`}),(0,P.jsx)(`div`,{className:`status-value`,children:i?`Running`:`Stopped`})]})]}),(0,P.jsx)(`div`,{className:`status-item`,children:(0,P.jsxs)(`div`,{className:`status-details`,children:[(0,P.jsx)(`div`,{className:`status-label`,children:`Service`}),(0,P.jsx)(`div`,{className:`status-value`,children:e?.service||`responses-proxy`})]})}),(0,P.jsx)(`div`,{className:`status-item`,children:(0,P.jsxs)(`div`,{className:`status-details`,children:[(0,P.jsx)(`div`,{className:`status-label`,children:`Status`}),(0,P.jsx)(`div`,{className:`status-value`,children:i?`Online`:`Offline`})]})}),(0,P.jsx)(`div`,{className:`status-item`,children:(0,P.jsxs)(`div`,{className:`status-details`,children:[(0,P.jsx)(`div`,{className:`status-label`,children:`Port`}),(0,P.jsx)(`div`,{className:`status-value`,children:window.location.port||`8318`})]})})]}),(0,P.jsxs)(`div`,{className:`endpoint-url-section`,children:[(0,P.jsx)(`div`,{className:`endpoint-label`,children:`Local Endpoint`}),(0,P.jsxs)(`div`,{className:`endpoint-url-container`,children:[(0,P.jsx)(`code`,{className:`endpoint-url`,children:n}),(0,P.jsx)(`button`,{className:`copy-button`,onClick:()=>{navigator.clipboard.writeText(n),o(!0),setTimeout(()=>o(!1),2e3)},title:`Copy endpoint URL`,children:a?`Copied!`:`Copy`})]})]})]})}function cm({health:e,providers:t}){let n=e?.activeProviderId,r=t.find(e=>e.id===n),i=r?.displayName||n||`None`,a=r?.tier||`n/a`,o=r?.healthStatus||`unknown`,s=r?.models?.[0]?.id||r?.capabilities?.defaultModels?.[0]||`auto`,{cardClass:c,icon:l}=(()=>{let e=n?.toLowerCase()||``;return e.includes(`claude`)||e.includes(`anthropic`)?{cardClass:`active-provider-card-anthropic`,icon:`🦉`}:e.includes(`openai`)||e.includes(`codex`)||e.includes(`gpt`)?{cardClass:`active-provider-card-openai`,icon:`🧠`}:e.includes(`gemini`)||e.includes(`google`)?{cardClass:`active-provider-card-google`,icon:`✨`}:e.includes(`kiro`)?{cardClass:`active-provider-card-kiro`,icon:`⚡`}:{cardClass:`active-provider-card-default`,icon:`🔌`}})();return(0,P.jsx)(V,{title:`Active Provider`,description:`Currently selected provider for new requests`,className:c,children:(0,P.jsxs)(`div`,{className:`active-provider-info`,children:[(0,P.jsxs)(`div`,{className:`provider-header-row`,children:[(0,P.jsx)(`div`,{className:`provider-vendor-icon`,children:l}),(0,P.jsxs)(`div`,{className:`provider-details-wrapper`,children:[(0,P.jsx)(`div`,{className:`provider-name`,children:i}),(0,P.jsxs)(`div`,{className:`provider-meta-row`,children:[(0,P.jsx)(B,{variant:`accent`,children:a}),(0,P.jsx)(B,{variant:o===`healthy`?`success`:o===`degraded`?`warning`:`danger`,children:o})]})]})]}),(0,P.jsxs)(`div`,{className:`provider-model-wrapper`,children:[(0,P.jsx)(`div`,{className:`model-label`,children:`Active Model`}),(0,P.jsx)(`code`,{className:`model-name`,children:s})]})]})})}function lm({providers:e}){return(0,P.jsx)(V,{title:`Fallback Tiers`,description:`Provider tier health and fallback readiness`,children:(0,P.jsx)(`div`,{className:`fallback-tiers-list`,children:[`subscription`,`cheap`,`free`].map(t=>{let n=e.filter(e=>e.tier===t).filter(e=>e.configured),r=n.filter(e=>e.healthStatus===`healthy`).length,i=`not_configured`;n.length>0&&(i=r>0?`healthy`:`warning`);let a=n.length>0?r/n.length*100:0;return{tier:{subscription:`Subscription`,cheap:`Cheap`,free:`Free`}[t],providers:n.length,healthy:r,status:i,usagePercent:a}}).map(e=>(0,P.jsxs)(`div`,{className:`fallback-tier-item`,children:[(0,P.jsxs)(`div`,{className:`tier-header`,children:[(0,P.jsx)(`div`,{className:`tier-name`,children:e.tier}),(0,P.jsx)(`div`,{className:`tier-stats`,children:e.providers>0?`${e.healthy}/${e.providers} healthy`:`Not configured`})]}),e.providers>0?(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(`div`,{className:`tier-progress-container`,children:(0,P.jsx)(`div`,{className:`tier-progress-fill tier-progress-fill-${e.status}`,style:{width:`${e.usagePercent}%`}})}),(0,P.jsx)(`div`,{className:`tier-footer`,children:(0,P.jsx)(B,{variant:e.status===`healthy`?`success`:`warning`,children:e.status===`healthy`?`Ready`:`Warning`})})]}):(0,P.jsx)(`div`,{className:`tier-footer`,children:(0,P.jsx)(B,{variant:`neutral`,children:`Disabled`})})]},e.tier))})})}function um({health:e,providers:t,endpointUrl:n}){let r=e?.activeProviderId,i=t.find(e=>e.id===r),a=i?.displayName||r||`No Active Upstream`,o=i?.tier?`${i.tier.toUpperCase()} Tier`:`Routing Pipeline`;return(0,P.jsx)(V,{title:`Routing Pipeline`,description:`Request flow through the router system`,children:(0,P.jsx)(`div`,{className:`pipeline-container-premium`,children:[{step:`Client CLI`,description:`Claude Code / Cline Client`,active:!0},{step:`Local Proxy`,description:n.replace(/^https?:\/\//,``),active:!0},{step:`Router Engine`,description:`Failover Strategy Routing`,active:!0},{step:o,description:a,active:i!==void 0},{step:`Response Stream`,description:`Dynamic cache delivery`,active:i!==void 0}].map((e,t)=>(0,P.jsxs)(`div`,{className:`pipeline-step-premium ${e.active?`active`:``}`,children:[(0,P.jsx)(`div`,{className:`step-indicator-premium`,children:t+1}),(0,P.jsxs)(`div`,{className:`pipeline-step-info`,children:[(0,P.jsx)(`div`,{className:`pipeline-step-title`,children:e.step}),(0,P.jsx)(`div`,{className:`pipeline-step-desc`,children:e.description})]}),(0,P.jsx)(`div`,{className:`step-status`,children:(0,P.jsx)(B,{variant:e.active?`success`:`neutral`,children:e.active?`Active`:`Pending`})})]},e.step))})})}function dm({endpointUrl:e}){let[t,n]=(0,v.useState)(`claude`),[r,i]=(0,v.useState)(!1),a={claude:{tool:`Claude Code`,command:`export ANTHROPIC_API_KEY="your-key-here"\nexport ANTHROPIC_BASE_URL="${e}"`},cursor:{tool:`Cursor`,command:`// In Cursor settings:\n{\n "anthropic.baseURL": "${e}",\n "anthropic.apiKey": "your-key-here"\n}`},openai:{tool:`OpenAI CLI`,command:`export OPENAI_API_KEY="your-key-here"\nexport OPENAI_BASE_URL="${e}"`}}[t],o=e=>{navigator.clipboard.writeText(e),i(!0),setTimeout(()=>i(!1),2e3)};return(0,P.jsxs)(V,{title:`Quick Setup`,description:`Copy configuration for popular AI tools`,children:[(0,P.jsxs)(`div`,{className:`setup-tab-bar`,children:[(0,P.jsx)(`button`,{className:`setup-tab-btn ${t===`claude`?`active`:``}`,onClick:()=>n(`claude`),children:`Claude Code`}),(0,P.jsx)(`button`,{className:`setup-tab-btn ${t===`cursor`?`active`:``}`,onClick:()=>n(`cursor`),children:`Cursor`}),(0,P.jsx)(`button`,{className:`setup-tab-btn ${t===`openai`?`active`:``}`,onClick:()=>n(`openai`),children:`OpenAI CLI`})]}),(0,P.jsxs)(`div`,{className:`terminal-wrapper`,children:[(0,P.jsxs)(`div`,{className:`terminal-header`,children:[(0,P.jsxs)(`div`,{className:`terminal-dots`,children:[(0,P.jsx)(`span`,{className:`terminal-dot terminal-dot-red`}),(0,P.jsx)(`span`,{className:`terminal-dot terminal-dot-yellow`}),(0,P.jsx)(`span`,{className:`terminal-dot terminal-dot-green`})]}),(0,P.jsx)(`span`,{className:`terminal-title`,children:t===`cursor`?`JSON`:`BASH`}),(0,P.jsx)(`button`,{className:`copy-command-button`,onClick:()=>o(a.command),children:r?`Copied!`:`Copy`})]}),(0,P.jsx)(`div`,{className:`terminal-body`,children:(0,P.jsx)(`pre`,{children:(0,P.jsx)(`code`,{children:om(a.command,t)})})})]})]})}function fm(){let{providers:e,loading:t,refresh:n}=tm();am(!0);let[r,i]=(0,v.useState)(null),[a,o]=(0,v.useState)(null),[s,c]=(0,v.useState)(!0),[l,u]=(0,v.useState)(null),d=(0,v.useCallback)(async()=>{try{c(!0),u(null);let[e,t]=await Promise.all([E(),j()]);i(e),o(t)}catch(e){console.error(`Failed to load telemetry`,e),u(e instanceof Error?e.message:`Failed to connect to local proxy. Make sure it is running.`)}finally{c(!1)}},[]);(0,v.useEffect)(()=>{d()},[d]);let f=async()=>{await Promise.all([d(),n()])},p=`${window.location.origin}/v1`,m=(a?.stats||{}).today||{},h=m.requests||0,g=(m.totalInputTokens||0)+(m.totalCachedTokens||0),_=m.hitRate||0,y=m.avgCacheSavedPercent||0,b=m.rtkAppliedRequests||0,x=t||s;return(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{icon:Ze,title:`Endpoint`,description:`Local OpenAI-compatible endpoint and router status`,actions:(0,P.jsx)(`div`,{className:`page-actions`,children:(0,P.jsx)($t,{onClick:f,isRefreshing:x})})}),(0,P.jsxs)(`div`,{className:`endpoint-screen-layout`,children:[l&&(0,P.jsxs)(`div`,{className:`error-banner`,style:{background:`var(--danger-soft)`,border:`1px solid var(--danger)`,borderRadius:`var(--radius-md)`,padding:`var(--space-4)`,marginBottom:`var(--space-5)`,display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:`var(--space-4)`},children:[(0,P.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`var(--space-3)`},children:[(0,P.jsx)(Je,{className:`status-icon status-error`,style:{width:`24px`,height:`24px`}}),(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`h3`,{style:{margin:0,color:`var(--danger)`,fontSize:`var(--font-md)`},children:`Connection Offline`}),(0,P.jsxs)(`p`,{style:{margin:`var(--space-1) 0 0 0`,fontSize:`var(--font-sm)`,color:`var(--text-secondary)`},children:[`Failed to connect to local proxy: `,l,`. Check if your service is active.`]})]})]}),(0,P.jsx)(`button`,{className:`button-secondary`,style:{whiteSpace:`nowrap`},onClick:f,children:`Retry Connection`})]}),(0,P.jsxs)(`div`,{className:`endpoint-top-row`,children:[(0,P.jsx)(sm,{health:r,loading:x,endpointUrl:p,onRefresh:f}),(0,P.jsx)(cm,{health:r,providers:e})]}),(0,P.jsxs)(`div`,{className:`endpoint-stats-row`,children:[(0,P.jsx)(z,{label:`Requests Today`,value:L(h),caption:`API requests processed`}),(0,P.jsx)(z,{label:`Tokens Today`,value:L(g),caption:`Input + cached tokens`}),(0,P.jsx)(z,{label:`RTK Applied`,value:L(b),caption:`Reduced context requests`}),(0,P.jsx)(z,{label:`Cache Hit Rate`,value:zt(_),caption:`Prompt cache efficiency`}),(0,P.jsx)(z,{label:`Average Savings`,value:zt(y),caption:`Tokens saved ratio`})]}),(0,P.jsxs)(`div`,{className:`endpoint-bottom-row`,children:[(0,P.jsx)(lm,{providers:e}),(0,P.jsx)(um,{health:r,providers:e,endpointUrl:p})]}),(0,P.jsx)(`div`,{className:`endpoint-setup-row`,children:(0,P.jsx)(dm,{endpointUrl:p})}),(0,P.jsx)(zp,{})]})]})}function pm({onAuthenticated:e}){let[t,n]=(0,v.useState)(`password`),[r,i]=(0,v.useState)(``),[a,o]=(0,v.useState)(!1),[s,c]=(0,v.useState)(``),[l,u]=(0,v.useState)(null),[d,f]=(0,v.useState)(!1),[p,m]=(0,v.useState)(null),[h,g]=(0,v.useState)(`idle`),[_,y]=(0,v.useState)(()=>Date.now()),[b,S]=(0,v.useState)(0);async function T(t){if(t.preventDefault(),!r.trim()){c(`Password is required`);return}o(!0),c(``);try{let t=await x(`/api/dashboard-auth/login`,`POST`,{password:r});t.session&&e(t.session)}catch(e){let t=e.message||`Login failed`;t.includes(`not configured`)?n(`telegram`):c(t)}finally{o(!1)}}(0,v.useEffect)(()=>{if(!l||h!==`pending`)return;let e=window.setInterval(()=>void E(),1500);return()=>window.clearInterval(e)},[l,h]),(0,v.useEffect)(()=>{if(!l)return;let e=window.setInterval(()=>y(Date.now()),1e3);return()=>window.clearInterval(e)},[l]);async function E(){if(l)try{let t=await w(l.challengeId,l.pollToken);if(t.status===`approved`&&t.session){g(`approved`),e(t.session);return}if(t.status===`rejected`||t.status===`expired`){g(t.status),m({variant:`error`,message:t.status===`rejected`?`Admin rejected. Try again.`:`Expired. Request again.`});return}g(`pending`)}catch{g(`idle`),u(null)}}async function D(){f(!0),m(null);try{let e=await C();u({challengeId:e.challengeId,pollToken:e.pollToken,displayCode:e.displayCode,expiresAt:e.expiresAt}),g(`pending`),y(Date.now()),S(Math.max(1,Math.ceil((new Date(e.expiresAt).getTime()-Date.now())/1e3))),m({variant:`success`,message:`Approval sent to Telegram admin.`})}catch(e){m({variant:`error`,message:e.message||`Failed to request approval.`})}finally{f(!1)}}let O=l?Math.max(0,Math.ceil((new Date(l.expiresAt).getTime()-_)/1e3)):0,ee=b>0?Math.min(100,O/b*100):0;return(0,P.jsx)(`div`,{className:`login-page`,children:(0,P.jsxs)(V,{className:`login-card`,children:[(0,P.jsx)(`span`,{className:`login-mark`,"aria-hidden":`true`,children:`RP`}),(0,P.jsx)(`p`,{className:`eyebrow`,children:`Admin dashboard`}),(0,P.jsx)(`h1`,{children:`Sign in`}),t===`password`?(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(`p`,{className:`muted-copy`,children:`Enter your admin password to access the dashboard.`}),s&&(0,P.jsx)(Ut,{variant:`error`,message:s}),(0,P.jsxs)(`form`,{className:`login-form`,onSubmit:T,style:{display:`grid`,gap:`var(--space-3)`},children:[(0,P.jsx)(`input`,{type:`password`,value:r,onChange:e=>i(e.target.value),placeholder:`Admin password`,autoFocus:!0,autoComplete:`current-password`,style:{minHeight:46}}),(0,P.jsx)(`button`,{className:`button-primary`,type:`submit`,disabled:a,children:a?`Signing in…`:`Sign in`})]}),(0,P.jsx)(`button`,{type:`button`,onClick:()=>n(`telegram`),style:{background:`none`,border:`none`,color:`var(--accent)`,cursor:`pointer`,fontSize:`var(--text-xs)`,marginTop:`var(--space-3)`,padding:0},children:`Use Telegram approval instead →`})]}):(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(`p`,{className:`muted-copy`,children:`Request approval from your Telegram admin.`}),p&&(0,P.jsx)(Ut,{variant:p.variant,message:p.message}),(0,P.jsx)(`div`,{className:`login-form`,children:(0,P.jsx)(`button`,{className:`button-primary`,type:`button`,disabled:d,onClick:D,children:d?`Sending…`:l?`Request again`:`Request Telegram approval`})}),l&&(0,P.jsxs)(`div`,{className:`login-form`,style:{marginTop:`var(--space-3)`},children:[(0,P.jsx)(`div`,{className:`login-code-display`,"aria-label":`Approval code`,children:l.displayCode}),(0,P.jsxs)(`div`,{className:`login-countdown`,children:[(0,P.jsx)(`div`,{className:`login-countdown-track`,role:`progressbar`,"aria-valuemin":0,"aria-valuemax":b,"aria-valuenow":O,children:(0,P.jsx)(`div`,{className:`login-countdown-fill`,style:{width:`${ee}%`}})}),(0,P.jsxs)(`div`,{className:`login-status-row`,children:[h===`pending`&&(0,P.jsx)(`span`,{className:`login-spinner`,"aria-hidden":`true`}),(0,P.jsxs)(`span`,{children:[h===`pending`?`Waiting for admin`:`Status: ${h}`,` · `,O,`s`]})]})]})]}),(0,P.jsx)(`button`,{type:`button`,onClick:()=>n(`password`),style:{background:`none`,border:`none`,color:`var(--accent)`,cursor:`pointer`,fontSize:`var(--text-xs)`,marginTop:`var(--space-3)`,padding:0},children:`← Use password instead`})]})]})})}function mm(e){if(!e.enabled)return`disabled`;if(!e.configured)return`not_configured`;if(e.quota?.hardLimitReached)return`quota_exhausted`;let t=e.accounts||[];if(t.filter(e=>e.status===`connected`&&e.routingMode!==`disabled`).length===0&&t.length>0&&t.some(e=>e.status===`expired`||e.status===`needs_reconnect`))return`auth_expired`;let n=e.models?.filter(e=>e.serviceKind===`chat`&&e.enabled)||[];if(e.serviceKinds.includes(`chat`)&&n.length===0)return`not_configured`;if([e.quota?.softLimitReached,e.quota?.usagePercent&&e.quota.usagePercent>85,t.some(e=>e.status===`needs_reconnect`),e.healthMessage&&e.healthMessage.includes(`warning`)].some(e=>e))return`degraded`;if(e.healthStatus&&e.lastHealthCheckAt){let t=new Date(e.lastHealthCheckAt);if((new Date().getTime()-t.getTime())/(1e3*60*60)<1)return e.healthStatus}return`healthy`}function hm(e){if(e.healthStatus===`unknown`||!e.lastHealthCheckAt)return!0;let t=new Date(e.lastHealthCheckAt);return(new Date().getTime()-t.getTime())/(1e3*60*60)>=(e.healthStatus===`healthy`?4:1)}function gm(e){let t=0;switch(e.enabled&&(t+=10),e.configured&&(t+=5),e.fallbackEligible&&(t+=3),e.tier){case`subscription`:t+=8;break;case`cheap`:t+=6;break;case`free`:t+=4;break;case`custom`:t+=2;break}switch(e.healthStatus){case`unknown`:t+=15;break;case`auth_expired`:case`quota_exhausted`:t+=12;break;case`degraded`:case`rate_limited`:t+=8;break;case`not_configured`:t+=5;break}return t}function _m(e){let t=[],n=[],r=`success`;e.status===`failed`?r=`error`:e.status===`partial`&&(r=`warning`),e.authOk||(t.push(`Authentication failed`),n.push(`Reconnect or refresh authentication credentials`),r=`error`),e.quotaOk||(t.push(`Quota limit reached`),n.push(`Wait for quota reset or upgrade plan`),r=`error`),e.modelOk||(t.push(`Model access failed`),n.push(`Check model availability and permissions`),r=`error`),e.routingOk||(t.push(`Routing configuration failed`),n.push(`Verify provider routing settings`),r=`error`),e.latencyMs&&e.latencyMs>5e3&&(t.push(`High latency detected`),n.push(`Check network connection and provider performance`),r===`success`&&(r=`warning`));let i;return i=e.status===`success`?`Health check passed in ${e.latencyMs}ms`:e.status===`partial`?`Health check partially successful with ${t.length} issue(s)`:`Health check failed: ${e.errorMessage||`Unknown error`}`,{summary:i,issues:t,suggestions:n,severity:r}}function vm(e){return e.hardLimitReached?{status:`exhausted`,message:`Quota exhausted`,resetInfo:e.resetAt?`Resets at ${new Date(e.resetAt).toLocaleString()}`:void 0}:e.softLimitReached||e.usagePercent&&e.usagePercent>90?{status:`critical`,message:`Quota usage: ${e.usagePercent?.toFixed(1)}%`,resetInfo:e.resetAt?`Resets at ${new Date(e.resetAt).toLocaleString()}`:void 0}:e.usagePercent&&e.usagePercent>75?{status:`warning`,message:`Quota usage: ${e.usagePercent.toFixed(1)}%`,resetInfo:e.resetAt?`Resets at ${new Date(e.resetAt).toLocaleString()}`:void 0}:{status:`healthy`,message:e.usagePercent?`Quota usage: ${e.usagePercent.toFixed(1)}%`:`Quota available`,resetInfo:e.resetAt?`Resets at ${new Date(e.resetAt).toLocaleString()}`:void 0}}var ym={pollInterval:3e4,maxRetries:3,retryDelay:5e3,batchSize:5,priorityThreshold:50},bm=class{config;isRunning=!1;intervalId=null;subscribers=new Set;statsSubscribers=new Set;providerHealthCache=new Map;stats={totalProviders:0,healthyProviders:0,unhealthyProviders:0,lastUpdateAt:new Date().toISOString(),checksPerformed:0,errorsEncountered:0,averageCheckTime:0};checkTimes=[];constructor(e={}){this.config={...ym,...e}}start(){this.isRunning||(this.isRunning=!0,this.scheduleNextCheck(),console.log(`Provider health monitoring started`))}stop(){this.isRunning&&(this.isRunning=!1,this.intervalId&&=(clearTimeout(this.intervalId),null),console.log(`Provider health monitoring stopped`))}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}subscribeToStats(e){return this.statsSubscribers.add(e),()=>this.statsSubscribers.delete(e)}getProviderHealth(e){return this.providerHealthCache.get(e)||null}getAllProviderHealth(){return new Map(this.providerHealthCache)}getStats(){return{...this.stats}}async checkProviderHealth(e){let t=Date.now();try{let[n,r]=await Promise.all([b(`/api/providers/${e}`),this.fetchProviderUsage(e)]),i=n.provider;if(!i)throw Error(`Provider not found`);let a=this.computeProviderHealthFromData(i,r);this.providerHealthCache.set(e,a),this.notifySubscribers(a);let o=Date.now()-t;return this.updateStats(o,!1),a}catch(n){console.error(`Health check failed for provider ${e}:`,n);let r={providerId:e,healthStatus:`unknown`,healthMessage:n instanceof Error?n.message:`Health check failed`,lastHealthCheckAt:new Date().toISOString(),issues:[`Health check failed`],suggestedFixes:[`Check provider configuration and network connectivity`]};this.providerHealthCache.set(e,r),this.notifySubscribers(r);let i=Date.now()-t;throw this.updateStats(i,!0),n}}async checkMultipleProviders(e){let t=[],n=this.chunkArray(e,this.config.batchSize);for(let e of n){let r=e.map(e=>this.checkProviderHealth(e).catch(t=>(console.error(`Batch health check failed for provider ${e}:`,t),null))),i=await Promise.all(r);t.push(...i.filter(e=>e!==null)),n.length>1&&await this.delay(1e3)}return t}async refreshAllProviders(){try{let e=(await b(`/api/providers`)).providers||[],t=e.filter(e=>this.shouldCheckProvider(e)).sort((e,t)=>{let n=gm(this.mapToProvider(e));return gm(this.mapToProvider(t))-n}).slice(0,20);console.log(`Refreshing health for ${t.length} providers`),await this.checkMultipleProviders(t.map(e=>e.id)),this.updateOverallStats(e)}catch(e){console.error(`Failed to refresh all provider health:`,e)}}scheduleNextCheck(){this.isRunning&&(this.intervalId=setTimeout(async()=>{try{await this.refreshAllProviders()}catch(e){console.error(`Scheduled health check failed:`,e)}finally{this.scheduleNextCheck()}},this.config.pollInterval))}async fetchProviderUsage(e){try{return(await b(`/api/providers/live-usage`)).providers?.find(t=>t.id===e)?.usage||null}catch(t){return console.warn(`Failed to fetch usage for provider ${e}:`,t),null}}computeProviderHealthFromData(e,t){let n=this.mapToProvider(e);t&&n.quota&&(n.quota.used=t.used||n.quota.used,n.quota.limit=t.limit||n.quota.limit,n.quota.remaining=t.remaining,n.quota.used&&n.quota.limit&&(n.quota.usagePercent=n.quota.used/n.quota.limit*100));let r=mm(n);return{providerId:e.id,healthStatus:r.status,healthMessage:r.message,lastHealthCheckAt:new Date().toISOString(),quota:n.quota,issues:r.issues||[],suggestedFixes:r.suggestedFixes||[]}}shouldCheckProvider(e){let t=this.mapToProvider(e);if(!t.enabled)return!1;let n=hm(t),r=gm(t);return n&&r>=this.config.priorityThreshold}mapToProvider(e){return{id:e.id,name:e.name,displayName:e.name,tier:`custom`,serviceKinds:[`chat`],authTypes:[e.authMode||`api_key`],enabled:!0,configured:e.providerApiKeys?.length>0||!!e.chatgptAccountId,healthStatus:`unknown`,priority:1,fallbackEligible:!1,accounts:[],models:[]}}notifySubscribers(e){this.subscribers.forEach(t=>{try{t(e)}catch(e){console.error(`Error in health update subscriber:`,e)}})}notifyStatsSubscribers(){this.statsSubscribers.forEach(e=>{try{e(this.stats)}catch(e){console.error(`Error in stats subscriber:`,e)}})}updateStats(e,t){this.stats.checksPerformed++,t&&this.stats.errorsEncountered++,this.checkTimes.push(e),this.checkTimes.length>100&&this.checkTimes.shift(),this.stats.averageCheckTime=this.checkTimes.reduce((e,t)=>e+t,0)/this.checkTimes.length,this.stats.lastUpdateAt=new Date().toISOString(),this.notifyStatsSubscribers()}updateOverallStats(e){this.stats.totalProviders=e.length;let t=0,n=0;this.providerHealthCache.forEach(e=>{e.healthStatus===`healthy`?t++:e.healthStatus!==`unknown`&&n++}),this.stats.healthyProviders=t,this.stats.unhealthyProviders=n,this.stats.lastUpdateAt=new Date().toISOString(),this.notifyStatsSubscribers()}chunkArray(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}delay(e){return new Promise(t=>setTimeout(t,e))}},xm=null;function Sm(e){return xm||=new bm(e),xm}function Cm(e){let[t,n]=(0,v.useState)(new Map),[r,i]=(0,v.useState)(null),[a,o]=(0,v.useState)(!1),[s,c]=(0,v.useState)(null),l=(0,v.useMemo)(()=>Sm(e),[e]);(0,v.useEffect)(()=>{let e=l.subscribe(e=>{n(t=>new Map(t).set(e.providerId,e)),c(null)}),t=l.subscribeToStats(e=>{i(e)});return n(l.getAllProviderHealth()),i(l.getStats()),()=>{e(),t()}},[l]);let u=(0,v.useCallback)(()=>{try{l.start(),o(!0),c(null)}catch(e){c(e instanceof Error?e.message:`Failed to start monitoring`)}},[l]),d=(0,v.useCallback)(()=>{try{l.stop(),o(!1)}catch(e){c(e instanceof Error?e.message:`Failed to stop monitoring`)}},[l]),f=(0,v.useCallback)(async()=>{try{c(null),await l.refreshAllProviders()}catch(e){c(e instanceof Error?e.message:`Failed to refresh health data`)}},[l]),p=(0,v.useCallback)(async e=>{try{c(null),await l.checkProviderHealth(e)}catch(t){c(t instanceof Error?t.message:`Failed to check health for provider ${e}`)}},[l]);return{healthUpdates:t,stats:r,healthSummary:(0,v.useMemo)(()=>{let e=Array.from(t.values()),n={total:e.length,healthy:0,degraded:0,critical:0,unknown:0,lastUpdateAt:r?.lastUpdateAt||null};return e.forEach(e=>{switch(e.healthStatus){case`healthy`:n.healthy++;break;case`degraded`:case`rate_limited`:n.degraded++;break;case`quota_exhausted`:case`auth_expired`:case`disabled`:case`not_configured`:n.critical++;break;default:n.unknown++}}),n},[t,r]),isMonitoring:a,error:s,startMonitoring:u,stopMonitoring:d,refreshAllHealth:f,checkProviderHealth:p}}function wm(e){let[t,n]=(0,v.useState)(null),[r,i]=(0,v.useState)(!1),[a,o]=(0,v.useState)(null),s=(0,v.useMemo)(()=>Sm(),[]);return(0,v.useEffect)(()=>{if(!e){n(null);return}return n(s.getProviderHealth(e)),s.subscribe(t=>{t.providerId===e&&(n(t),o(null))})},[e,s]),{healthUpdate:t,isChecking:r,error:a,checkHealth:(0,v.useCallback)(async()=>{if(e)try{i(!0),o(null),await s.checkProviderHealth(e)}catch(e){o(e instanceof Error?e.message:`Health check failed`)}finally{i(!1)}},[e,s]),getHealthAge:(0,v.useCallback)(()=>{if(!t?.lastHealthCheckAt)return null;let e=new Date(t.lastHealthCheckAt),n=new Date().getTime()-e.getTime();return{ageMs:n,ageMinutes:Math.floor(n/(1e3*60)),ageHours:Math.floor(n/(1e3*60*60)),isStale:n>14400*1e3}},[t]),hasHealthData:!!t}}function Tm(e){let{healthUpdates:t}=Cm(),n=(0,v.useMemo)(()=>e.map(e=>{let n=t.get(e.id);return{...e,healthStatus:n?.healthStatus||e.healthStatus,healthMessage:n?.healthMessage||e.healthMessage,lastHealthCheckAt:n?.lastHealthCheckAt||e.lastHealthCheckAt,quota:n?.quota||e.quota,realtimeHealth:n}}),[e,t]);return{enhancedProviders:n,sortedByHealth:(0,v.useMemo)(()=>[...n].sort((e,t)=>{let n={healthy:0,degraded:1,rate_limited:2,quota_exhausted:3,auth_expired:4,not_configured:5,disabled:6,unknown:7},r=n[e.healthStatus]??7,i=n[t.healthStatus]??7;if(r!==i)return r-i;let a={subscription:0,cheap:1,free:2,custom:3},o=a[e.tier]??3,s=a[t.tier]??3;return o===s?e.priority-t.priority:o-s}),[n]),filterByHealth:(0,v.useCallback)(e=>n.filter(t=>e.includes(t.healthStatus)),[n]),getProvidersNeedingAttention:(0,v.useCallback)(()=>n.filter(e=>{let n=t.get(e.id);return n&&(n.issues&&n.issues.length>0||[`quota_exhausted`,`auth_expired`,`not_configured`,`disabled`].includes(n.healthStatus))}),[n,t])}}function Em(e=!0,t){let{isMonitoring:n,startMonitoring:r,stopMonitoring:i}=Cm(t);return(0,v.useEffect)(()=>{e&&!n?r():!e&&n&&i()},[e,n,r,i]),(0,v.useEffect)(()=>()=>{n&&i()},[n,i]),{isMonitoring:n}}function Dm(e){let t=e.toLowerCase();return t.includes(`claude`)||t.includes(`anthropic`)?`linear-gradient(135deg, #d97706, #b45309)`:t.includes(`openai`)||t.includes(`codex`)||t.includes(`copilot`)?`linear-gradient(135deg, #1e293b, #0f172a)`:t.includes(`gemini`)||t.includes(`google`)?`linear-gradient(135deg, #2563eb, #7c3aed)`:t.includes(`deepseek`)?`linear-gradient(135deg, #0d9488, #0f766e)`:t.includes(`groq`)?`linear-gradient(135deg, #ea580c, #c2410c)`:t.includes(`mistral`)?`linear-gradient(135deg, #e11d48, #be123c)`:t.includes(`xai`)||t.includes(`grok`)?`linear-gradient(135deg, #000000, #1e293b)`:t.includes(`cursor`)?`linear-gradient(135deg, #4f46e5, #3730a3)`:t.includes(`qwen`)||t.includes(`alibaba`)?`linear-gradient(135deg, #059669, #047857)`:t.includes(`cloudflare`)?`linear-gradient(135deg, #f97316, #ea580c)`:t.includes(`nvidia`)?`linear-gradient(135deg, #16a34a, #15803d)`:`linear-gradient(135deg, #64748b, #475569)`}function Om(e){let t=e.split(` `);return t.length>=2?(t[0][0]+t[1][0]).toUpperCase():e.slice(0,2).toUpperCase()}function km(e){return e.configured?e.healthStatus===`healthy`?{label:`Ready`,dotClass:`healthy`}:e.healthStatus===`degraded`?{label:`Degraded`,dotClass:`degraded`}:e.healthStatus===`quota_exhausted`?{label:`Quota Exhausted`,dotClass:`quota_exhausted`}:{label:`Ready`,dotClass:`healthy`}:{label:`No connection`,dotClass:`not_configured`}}function Am({provider:e,isDisabled:t,onToggle:n,onClick:r}){let i=t?{label:`Disabled`,dotClass:`not_configured`}:km(e),a=Dm(e.id),o=Om(e.displayName);return(0,P.jsxs)(`div`,{className:`provider-small-card`,onClick:r,children:[(0,P.jsx)(`div`,{className:`provider-small-logo-container`,style:{background:a},children:o}),(0,P.jsxs)(`div`,{className:`provider-small-info`,children:[(0,P.jsxs)(`div`,{className:`provider-small-name-row`,style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:`var(--space-2)`},children:[(0,P.jsx)(`h4`,{className:`provider-small-name`,title:e.displayName,children:e.displayName}),(0,P.jsx)(`div`,{className:`custom-switch ${t?`off`:`on`}`,onClick:e=>{e.stopPropagation(),n()},title:t?`Enable Provider`:`Disable Provider`,children:(0,P.jsx)(`span`,{className:`custom-switch-slider`})})]}),(0,P.jsxs)(`div`,{className:`provider-small-status`,children:[(0,P.jsx)(`span`,{className:`provider-small-status-dot ${i.dotClass}`}),(0,P.jsx)(`span`,{children:i.label})]})]})]})}function jm(){let[e,t]=(0,v.useState)(``),[n,r]=(0,v.useState)(null),[i,a]=(0,v.useState)(()=>{try{let e=localStorage.getItem(`disabled_providers`);return e?new Set(JSON.parse(e)):new Set}catch{return new Set}}),o=e=>{a(t=>{let n=new Set(t);n.has(e)?n.delete(e):n.add(e);try{localStorage.setItem(`disabled_providers`,JSON.stringify(Array.from(n)))}catch(e){console.error(`Failed to persist disabled providers:`,e)}return n})};(0,v.useEffect)(()=>{E().then(e=>{e&&e.activeProviderId&&r(e.activeProviderId)}).catch(()=>{})},[]);let{providers:s,loading:c,error:l,refresh:u}=tm(),{testProvider:d}=rm();Em(!0);let{enhancedProviders:f}=Tm(s),p=(0,v.useMemo)(()=>f.filter(t=>{if(e){let n=e.toLowerCase();return t.name.toLowerCase().includes(n)||t.displayName.toLowerCase().includes(n)||t.description?.toLowerCase().includes(n)}return!0}),[f,e]),m=(0,v.useMemo)(()=>p.filter(e=>e.tier===`custom`),[p]),h=(0,v.useMemo)(()=>p.filter(e=>e.tier!==`custom`&&e.authTypes.includes(`oauth`)),[p]),g=(0,v.useMemo)(()=>p.filter(e=>e.tier===`free`&&!e.authTypes.includes(`oauth`)),[p]),_=(0,v.useMemo)(()=>p.filter(e=>e.tier!==`custom`&&!e.authTypes.includes(`oauth`)&&e.tier!==`free`),[p]),y=e=>{window.location.hash=`#/providers/${e}`},b=async e=>{try{await d(e)}catch(t){console.error(`Failed to test provider ${e}:`,t)}},x=()=>{window.location.hash=`#/providers/new`},S=async e=>{let t=e.filter(e=>e.configured);for(let e of t)b(e.id)},C=async()=>{try{await u()}catch(e){console.error(`Failed to refresh providers:`,e)}};return c?(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{icon:Ie,title:`Providers`,description:`Manage AI provider connections and routing configuration`}),(0,P.jsx)(jt,{title:`Loading providers`,description:`Fetching provider data and health status...`,cards:3})]}):l?(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{icon:Ie,title:`Providers`,description:`Manage AI provider connections and routing configuration`}),(0,P.jsx)(At,{title:`Failed to load providers`,description:l,actionLabel:`Retry`,onClick:C})]}):(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{icon:Ie,title:`Providers`,description:`Manage your AI provider connections`,actions:(0,P.jsxs)(`div`,{className:`page-actions`,style:{display:`flex`,alignItems:`center`,gap:`var(--space-3)`},children:[(0,P.jsxs)(`div`,{className:`search-container`,style:{position:`relative`,display:`flex`,alignItems:`center`},children:[(0,P.jsx)(`input`,{type:`text`,className:`search-input`,placeholder:`Search providers...`,value:e,onChange:e=>t(e.target.value),style:{padding:`6px 12px 6px 32px`,fontSize:`var(--font-sm)`,borderRadius:`var(--radius-md)`,border:`1px solid var(--line)`,background:`var(--surface-input)`,color:`var(--text-primary)`,width:`200px`}}),(0,P.jsx)(`span`,{style:{position:`absolute`,left:`10px`,color:`var(--text-secondary)`,fontSize:`var(--font-sm)`,pointerEvents:`none`},children:`🔍`})]}),(0,P.jsx)($t,{onClick:C})]})}),(0,P.jsxs)(`div`,{className:`providers-screen-layout`,children:[(0,P.jsxs)(`div`,{className:`provider-section`,style:{marginBottom:`var(--space-6)`},children:[(0,P.jsxs)(`div`,{className:`provider-section-title-row`,children:[(0,P.jsx)(`h3`,{children:`Custom Providers (OpenAI/Anthropic Compatible)`}),(0,P.jsx)(`div`,{className:`provider-section-actions`,children:(0,P.jsx)(`button`,{className:`button-primary`,onClick:x,children:`+ Add Provider`})})]}),m.length===0?(0,P.jsx)(`div`,{className:`provider-empty-state`,style:{textAlign:`center`,padding:`var(--space-6)`,border:`1px dashed var(--line)`,borderRadius:`var(--radius-md)`,color:`var(--text-secondary)`,fontSize:`var(--font-sm)`},children:`No custom providers — use buttons above to add OpenAI/Anthropic compatible endpoints`}):(0,P.jsx)(`div`,{className:`providers-small-grid`,children:m.map(e=>(0,P.jsx)(Am,{provider:e,isDisabled:i.has(e.id),onToggle:()=>o(e.id),onClick:()=>y(e.id)},e.id))})]}),(0,P.jsxs)(`div`,{className:`provider-section`,style:{marginBottom:`var(--space-6)`},children:[(0,P.jsxs)(`div`,{className:`provider-section-title-row`,children:[(0,P.jsx)(`h3`,{children:`OAuth Providers`}),(0,P.jsx)(`button`,{className:`button-secondary`,style:{fontSize:`var(--font-xs)`,padding:`4px var(--space-2)`},onClick:()=>S(h),disabled:h.filter(e=>e.configured).length===0,children:`▷ Test All`})]}),h.length===0?(0,P.jsx)(`div`,{style:{color:`var(--text-secondary)`,fontSize:`var(--font-sm)`},children:`No OAuth providers found`}):(0,P.jsx)(`div`,{className:`providers-small-grid`,children:h.map(e=>(0,P.jsx)(Am,{provider:e,isDisabled:i.has(e.id),onToggle:()=>o(e.id),onClick:()=>y(e.id)},e.id))})]}),(0,P.jsxs)(`div`,{className:`provider-section`,style:{marginBottom:`var(--space-6)`},children:[(0,P.jsxs)(`div`,{className:`provider-section-title-row`,children:[(0,P.jsx)(`h3`,{children:`Free Tier Providers`}),(0,P.jsx)(`button`,{className:`button-secondary`,style:{fontSize:`var(--font-xs)`,padding:`4px var(--space-2)`},onClick:()=>S(g),disabled:g.filter(e=>e.configured).length===0,children:`▷ Test All`})]}),g.length===0?(0,P.jsx)(`div`,{style:{color:`var(--text-secondary)`,fontSize:`var(--font-sm)`},children:`No Free Tier providers found`}):(0,P.jsx)(`div`,{className:`providers-small-grid`,children:g.map(e=>(0,P.jsx)(Am,{provider:e,isDisabled:i.has(e.id),onToggle:()=>o(e.id),onClick:()=>y(e.id)},e.id))})]}),(0,P.jsxs)(`div`,{className:`provider-section`,style:{marginBottom:`var(--space-6)`},children:[(0,P.jsxs)(`div`,{className:`provider-section-title-row`,children:[(0,P.jsx)(`h3`,{children:`API Key Providers`}),(0,P.jsx)(`button`,{className:`button-secondary`,style:{fontSize:`var(--font-xs)`,padding:`4px var(--space-2)`},onClick:()=>S(_),disabled:_.filter(e=>e.configured).length===0,children:`▷ Test All`})]}),_.length===0?(0,P.jsx)(`div`,{style:{color:`var(--text-secondary)`,fontSize:`var(--font-sm)`},children:`No API Key providers found`}):(0,P.jsx)(`div`,{className:`providers-small-grid`,children:_.map(e=>(0,P.jsx)(Am,{provider:e,isDisabled:i.has(e.id),onToggle:()=>o(e.id),onClick:()=>y(e.id)},e.id))})]})]})]})}function Mm(){return(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{icon:Ie,title:`Media Providers`,description:`Multimodal, voice, image, and video generation upstreams`}),(0,P.jsx)(V,{title:`Feature Coming Soon`,description:`Extended media provider pool`,tone:`info`,children:(0,P.jsxs)(`div`,{style:{padding:`var(--space-6) var(--space-4)`,textAlign:`center`},children:[(0,P.jsx)(`span`,{style:{fontSize:`3rem`},children:`🎨`}),(0,P.jsx)(`h3`,{style:{margin:`var(--space-3) 0 var(--space-2) 0`,fontSize:`var(--font-lg)`},children:`Extended Multimodal Pipeline`}),(0,P.jsx)(`p`,{style:{margin:`0 auto var(--space-4) auto`,color:`var(--text-secondary)`,fontSize:`var(--font-sm)`,maxWidth:`540px`,lineHeight:`1.6`},children:`Media Providers will allow responses-proxy to handle multimodal requests (audio processing, text-to-speech, DALL-E image generation, and video upstreams) with automatic cost routing and fallback policies.`}),(0,P.jsxs)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:`var(--space-2)`,justifyContent:`center`},children:[(0,P.jsx)(B,{variant:`accent`,children:`Image Tiers`}),(0,P.jsx)(B,{variant:`accent`,children:`Audio Failover`}),(0,P.jsx)(B,{variant:`accent`,children:`Video Upstreams`})]})]})})]})}function Nm(){return(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{icon:Ie,title:`Proxy Pools`,description:`Distributed network proxies and rotating IP pools`}),(0,P.jsx)(V,{title:`Feature Coming Soon`,description:`Network proxy list configuration`,tone:`info`,children:(0,P.jsxs)(`div`,{style:{padding:`var(--space-6) var(--space-4)`,textAlign:`center`},children:[(0,P.jsx)(`span`,{style:{fontSize:`3rem`},children:`🌐`}),(0,P.jsx)(`h3`,{style:{margin:`var(--space-3) 0 var(--space-2) 0`,fontSize:`var(--font-lg)`},children:`Rotating Network IP Pools`}),(0,P.jsx)(`p`,{style:{margin:`0 auto var(--space-4) auto`,color:`var(--text-secondary)`,fontSize:`var(--font-sm)`,maxWidth:`540px`,lineHeight:`1.6`},children:`Proxy Pools will enable routing upstream provider requests through a configured list of residential or datacenter web proxies. This prevents rate-limiting and geographical blocks from impacting high-frequency developer workflows.`}),(0,P.jsxs)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:`var(--space-2)`,justifyContent:`center`},children:[(0,P.jsx)(B,{variant:`accent`,children:`Rotating Proxies`}),(0,P.jsx)(B,{variant:`accent`,children:`IP Health Check`}),(0,P.jsx)(B,{variant:`accent`,children:`Geo-Targeting`})]})]})})]})}function Pm({providerId:e,authType:t,connectionFlow:n,connecting:r,error:i,onStartConnection:a,onCompleteConnection:o,onCancel:s,validationResult:c=null,validating:l=!1}){let[u,d]=(0,v.useState)(`start`),[f,p]=(0,v.useState)(``),[m,h]=(0,v.useState)(``),[g,_]=(0,v.useState)(``),[y,b]=(0,v.useState)(!1),[x,S]=(0,v.useState)(null),[C,w]=(0,v.useState)(`picker`),[T,E]=(0,v.useState)(`builder_id`),[D,O]=(0,v.useState)(``),[ee,k]=(0,v.useState)(`us-east-1`),[te,ne]=(0,v.useState)(null),[re,ie]=(0,v.useState)(``),[ae,A]=(0,v.useState)(``),[j,oe]=(0,v.useState)(``),[se,ce]=(0,v.useState)(5),[le,M]=(0,v.useState)(null),N=(0,v.useRef)(null),ue=n?.type===`kiro`;(0,v.useEffect)(()=>{u===`start`&&n&&(ue?(w(`picker`),d(`device_login`)):t===`api_key`&&n.type===`api_key`?d(`callback`):t===`oauth`&&n.type===`oauth`&&d(`authorize`))},[u,n,t,ue]),(0,v.useEffect)(()=>()=>{N.current&&=(clearInterval(N.current),null)},[u]);let de=(0,v.useCallback)(()=>{N.current&&=(clearInterval(N.current),null)},[]),fe=(0,v.useCallback)(async()=>{try{S(null),M(null),b(!0);let e={authMethod:T};T===`idc`&&(e.startUrl=D.trim(),e.region=ee.trim());let t=await Oe(e);ne(t.sessionId),ie(t.userCode),A(t.verificationUri),oe(t.verificationUriComplete),ce(t.interval),w(`waiting`)}catch(e){M(e instanceof Error?e.message:`Failed to start device login`),w(`error`)}finally{b(!1)}},[T,D,ee]);(0,v.useEffect)(()=>{if(u!==`device_login`||C!==`waiting`||!te)return;let e=async()=>{try{let t=await ke(te);t.status===`pending`?t.interval&&t.interval!==se&&(ce(t.interval),de(),N.current=setInterval(e,t.interval*1e3)):t.status===`completed`?(de(),w(`done`),await o({kiroDeviceLogin:!0,accountId:t.account?.id}),d(`complete`)):t.status===`expired`?(de(),M(`Login expired. Please try again.`),w(`error`)):t.status===`error`&&(de(),M(t.error?.message||`Device login failed.`),w(`error`))}catch(e){de(),M(e instanceof Error?e.message:`Polling failed.`),w(`error`)}};return N.current=setInterval(e,se*1e3),()=>{de()}},[u,C,te,se,de,o]);let pe=(0,v.useCallback)(async()=>{try{if(S(null),ue){d(`device_login`),w(`picker`);return}await a(t),t===`oauth`?d(`authorize`):t===`api_key`&&d(`callback`)}catch(e){console.error(`Failed to start connection:`,e),S(e instanceof Error?e.message:`Failed to start connection`)}},[t,ue,a]),me=(0,v.useCallback)(async()=>{if(f.trim())try{b(!0),S(null),await o({callbackUrl:f.trim(),state:n?.state}),d(`complete`)}catch(e){console.error(`Failed to complete OAuth:`,e),S(e instanceof Error?e.message:`Failed to complete OAuth connection`)}finally{b(!1)}},[f,n?.state,o]),he=(0,v.useCallback)(async()=>{if(m.trim())try{b(!0),S(null),await o({apiKey:m.trim(),keyName:g.trim()||`API Key`}),d(`complete`)}catch(e){console.error(`Failed to add API key:`,e),S(e instanceof Error?e.message:`Failed to add API key connection`)}finally{b(!1)}},[m,g,o]),ge=()=>(0,P.jsxs)(`div`,{className:`connection-flow-step`,children:[(0,P.jsxs)(`div`,{className:`step-header`,children:[(0,P.jsx)(`h3`,{children:`Connect New Account`}),(0,P.jsx)(`p`,{children:`Add a new ${t===`oauth`?`OAuth`:`API key`} account to this provider.`})]}),(0,P.jsxs)(`div`,{className:`step-content`,children:[t===`oauth`&&(0,P.jsxs)(`div`,{className:`auth-info`,children:[(0,P.jsx)(`div`,{className:`auth-type-badge`,children:(0,P.jsx)(B,{variant:`accent`,size:`sm`,children:`OAuth`})}),(0,P.jsx)(`p`,{children:`This will start an OAuth flow to connect your account securely.`})]}),t===`api_key`&&(0,P.jsxs)(`div`,{className:`auth-info`,children:[(0,P.jsx)(`div`,{className:`auth-type-badge`,children:(0,P.jsx)(B,{variant:`neutral`,size:`sm`,children:`API Key`})}),(0,P.jsx)(`p`,{children:`Enter your API key to connect this provider.`})]}),(i||x)&&(0,P.jsxs)(`div`,{className:`connection-error`,children:[(0,P.jsx)(Je,{className:`error-icon`}),(0,P.jsx)(`span`,{children:i||x})]})]}),(0,P.jsxs)(`div`,{className:`step-actions`,children:[(0,P.jsx)(`button`,{className:`button-secondary`,onClick:s,disabled:r,children:`Cancel`}),(0,P.jsx)(`button`,{className:`button-primary`,onClick:pe,disabled:r,children:r?`Starting...`:`Start Connection`})]})]}),_e=()=>C===`picker`?(0,P.jsxs)(`div`,{className:`connection-flow-step`,children:[(0,P.jsxs)(`div`,{className:`step-header`,children:[(0,P.jsx)(`h3`,{children:`Sign In with Device Code`}),(0,P.jsx)(`p`,{children:`Choose your authentication method to connect a Kiro account.`})]}),(0,P.jsxs)(`div`,{className:`step-content`,children:[(0,P.jsxs)(`div`,{className:`form-group`,children:[(0,P.jsx)(`label`,{children:`Authentication Method`}),(0,P.jsxs)(`div`,{className:`auth-method-cards`,children:[(0,P.jsxs)(`button`,{type:`button`,className:`auth-method-card ${T===`builder_id`?`selected`:``}`,onClick:()=>E(`builder_id`),children:[(0,P.jsx)(`strong`,{children:`AWS Builder ID`}),(0,P.jsx)(`span`,{children:`Personal account`})]}),(0,P.jsxs)(`button`,{type:`button`,className:`auth-method-card ${T===`idc`?`selected`:``}`,onClick:()=>E(`idc`),children:[(0,P.jsx)(`strong`,{children:`IAM Identity Center`}),(0,P.jsx)(`span`,{children:`Enterprise`})]})]})]}),T===`idc`&&(0,P.jsxs)(P.Fragment,{children:[(0,P.jsxs)(`div`,{className:`form-group`,children:[(0,P.jsx)(`label`,{htmlFor:`deviceStartUrl`,children:`Start URL *`}),(0,P.jsx)(`input`,{id:`deviceStartUrl`,type:`text`,className:`form-input`,placeholder:`https://my-org.awsapps.com/start`,value:D,onChange:e=>O(e.target.value),disabled:y})]}),(0,P.jsxs)(`div`,{className:`form-group`,children:[(0,P.jsx)(`label`,{htmlFor:`deviceRegion`,children:`Region *`}),(0,P.jsx)(`input`,{id:`deviceRegion`,type:`text`,className:`form-input`,placeholder:`us-east-1`,value:ee,onChange:e=>k(e.target.value),disabled:y})]})]}),(le||x)&&(0,P.jsxs)(`div`,{className:`connection-error`,children:[(0,P.jsx)(Je,{className:`error-icon`}),(0,P.jsx)(`span`,{children:le||x})]})]}),(0,P.jsxs)(`div`,{className:`step-actions`,children:[(0,P.jsx)(`button`,{className:`button-secondary`,onClick:()=>d(`start`),disabled:y,children:`Back`}),(0,P.jsx)(`button`,{className:`button-primary`,onClick:fe,disabled:y||T===`idc`&&(!D.trim()||!ee.trim()),children:y?`Starting...`:`Start Device Login`})]})]}):C===`waiting`?(0,P.jsxs)(`div`,{className:`connection-flow-step`,children:[(0,P.jsxs)(`div`,{className:`step-header`,children:[(0,P.jsx)(`h3`,{children:`Enter Code in Browser`}),(0,P.jsx)(`p`,{children:`Enter the code above on the verification page`})]}),(0,P.jsxs)(`div`,{className:`step-content`,children:[(0,P.jsx)(`div`,{className:`device-user-code`,children:re}),(0,P.jsx)(`div`,{className:`auth-url-section`,children:(0,P.jsxs)(`a`,{href:j,target:`_blank`,rel:`noopener noreferrer`,className:`auth-url-link`,children:[(0,P.jsx)(ct,{className:`link-icon`}),`Open verification page`]})}),(0,P.jsxs)(`div`,{className:`connection-validating`,children:[(0,P.jsx)(`span`,{className:`login-spinner`,"aria-hidden":`true`}),(0,P.jsx)(`span`,{children:`Waiting for browser approval...`})]})]}),(0,P.jsx)(`div`,{className:`step-actions`,children:(0,P.jsx)(`button`,{className:`button-secondary`,onClick:()=>{de(),s()},children:`Cancel`})})]}):C===`error`?(0,P.jsxs)(`div`,{className:`connection-flow-step`,children:[(0,P.jsxs)(`div`,{className:`step-header`,children:[(0,P.jsx)(`h3`,{children:`Device Login Failed`}),(0,P.jsx)(`p`,{children:`Something went wrong during the device login flow.`})]}),(0,P.jsx)(`div`,{className:`step-content`,children:(0,P.jsxs)(`div`,{className:`connection-error`,children:[(0,P.jsx)(Je,{className:`error-icon`}),(0,P.jsx)(`span`,{children:le||`An unknown error occurred.`})]})}),(0,P.jsxs)(`div`,{className:`step-actions`,children:[(0,P.jsx)(`button`,{className:`button-secondary`,onClick:s,children:`Cancel`}),(0,P.jsx)(`button`,{className:`button-primary`,onClick:()=>{M(null),w(`picker`)},children:`Try Again`})]})]}):(0,P.jsxs)(`div`,{className:`connection-flow-step`,children:[(0,P.jsxs)(`div`,{className:`step-header`,children:[(0,P.jsx)(qe,{className:`success-icon`}),(0,P.jsx)(`h3`,{children:`Device Login Successful`}),(0,P.jsx)(`p`,{children:`Your Kiro account has been connected.`})]}),(0,P.jsx)(`div`,{className:`step-content`,children:(0,P.jsx)(`div`,{className:`success-message`,children:(0,P.jsx)(`p`,{children:`Account connected successfully via device code flow.`})})}),(0,P.jsx)(`div`,{className:`step-actions`,children:(0,P.jsx)(`button`,{className:`button-primary`,onClick:s,children:`Done`})})]}),ve=()=>(0,P.jsxs)(`div`,{className:`connection-flow-step`,children:[(0,P.jsxs)(`div`,{className:`step-header`,children:[(0,P.jsx)(`h3`,{children:`Authorize Account`}),(0,P.jsx)(`p`,{children:`Click the link below to authorize with the provider.`})]}),(0,P.jsxs)(`div`,{className:`step-content`,children:[n?.authUrl&&(0,P.jsxs)(`div`,{className:`auth-url-section`,children:[(0,P.jsx)(`div`,{className:`auth-url-container`,children:(0,P.jsxs)(`a`,{href:n.authUrl,target:`_blank`,rel:`noopener noreferrer`,className:`auth-url-link`,children:[(0,P.jsx)(ct,{className:`link-icon`}),`Open Authorization Page`]})}),(0,P.jsx)(`p`,{className:`auth-instructions`,children:n.instructions||`Complete the authorization and return here.`})]}),n?.requiresCallback&&(0,P.jsxs)(`div`,{className:`callback-section`,children:[(0,P.jsx)(`p`,{children:`After authorizing, you'll be redirected to a callback URL. Copy and paste that URL below:`}),(0,P.jsx)(`button`,{className:`button-secondary`,onClick:()=>d(`callback`),children:`I've Completed Authorization`})]})]}),(0,P.jsx)(`div`,{className:`step-actions`,children:(0,P.jsx)(`button`,{className:`button-secondary`,onClick:s,children:`Cancel`})})]}),ye=()=>t===`api_key`?(0,P.jsxs)(`div`,{className:`connection-flow-step`,children:[(0,P.jsxs)(`div`,{className:`step-header`,children:[(0,P.jsx)(`h3`,{children:`Enter API Key`}),(0,P.jsx)(`p`,{children:`Provide your API key and an optional name for this connection.`})]}),(0,P.jsxs)(`div`,{className:`step-content`,children:[(0,P.jsxs)(`div`,{className:`form-group`,children:[(0,P.jsx)(`label`,{htmlFor:`apiKey`,children:`API Key *`}),(0,P.jsx)(`input`,{id:`apiKey`,type:`password`,className:`form-input`,placeholder:`Enter your API key...`,value:m,onChange:e=>h(e.target.value),disabled:y})]}),(0,P.jsxs)(`div`,{className:`form-group`,children:[(0,P.jsx)(`label`,{htmlFor:`apiKeyName`,children:`Key Name (Optional)`}),(0,P.jsx)(`input`,{id:`apiKeyName`,type:`text`,className:`form-input`,placeholder:`e.g., Production Key, Development Key`,value:g,onChange:e=>_(e.target.value),disabled:y})]}),(i||x)&&(0,P.jsxs)(`div`,{className:`connection-error`,children:[(0,P.jsx)(Je,{className:`error-icon`}),(0,P.jsx)(`span`,{children:i||x})]})]}),(0,P.jsxs)(`div`,{className:`step-actions`,children:[(0,P.jsx)(`button`,{className:`button-secondary`,onClick:s,disabled:y,children:`Cancel`}),(0,P.jsx)(`button`,{className:`button-primary`,onClick:he,disabled:!m.trim()||y,children:y?`Adding...`:`Add API Key`})]})]}):(0,P.jsxs)(`div`,{className:`connection-flow-step`,children:[(0,P.jsxs)(`div`,{className:`step-header`,children:[(0,P.jsx)(`h3`,{children:`Complete Authorization`}),(0,P.jsx)(`p`,{children:`Paste the callback URL you were redirected to after authorization.`})]}),(0,P.jsxs)(`div`,{className:`step-content`,children:[(0,P.jsxs)(`div`,{className:`form-group`,children:[(0,P.jsx)(`label`,{htmlFor:`callbackUrl`,children:`Callback URL *`}),(0,P.jsx)(`textarea`,{id:`callbackUrl`,className:`form-textarea`,placeholder:`Paste the full callback URL here...`,value:f,onChange:e=>p(e.target.value),disabled:y,rows:3})]}),(0,P.jsxs)(`div`,{className:`callback-help`,children:[(0,P.jsx)(`p`,{children:`The callback URL should look something like:`}),(0,P.jsx)(`code`,{children:`https://chat.openai.com/auth/callback?code=...`})]}),(i||x)&&(0,P.jsxs)(`div`,{className:`connection-error`,children:[(0,P.jsx)(Je,{className:`error-icon`}),(0,P.jsx)(`span`,{children:i||x})]})]}),(0,P.jsxs)(`div`,{className:`step-actions`,children:[(0,P.jsx)(`button`,{className:`button-secondary`,onClick:()=>d(`authorize`),disabled:y,children:`Back`}),(0,P.jsx)(`button`,{className:`button-primary`,onClick:me,disabled:!f.trim()||y,children:y?`Completing...`:`Complete Connection`})]})]}),be=e=>(0,P.jsx)(`ul`,{className:`validation-check-list`,children:[{label:`Authentication`,ok:e.authOk},{label:`Quota`,ok:e.quotaOk},{label:`Model access`,ok:e.modelOk},{label:`Routing`,ok:e.routingOk}].map(e=>(0,P.jsxs)(`li`,{className:e.ok?`check-pass`:`check-fail`,children:[e.ok?(0,P.jsx)(qe,{className:`success-icon`}):(0,P.jsx)(Je,{className:`error-icon`}),(0,P.jsxs)(`span`,{children:[e.label,`: `,e.ok?`Passed`:`Did not pass`]})]},e.label))}),xe=()=>(0,P.jsx)(`div`,{className:`step-actions`,children:(0,P.jsx)(`button`,{className:`button-primary`,onClick:s,children:`Done`})});return r&&!n?(0,P.jsx)(`div`,{className:`connection-flow`,children:(0,P.jsx)(jt,{title:`Starting connection`,description:`Preparing account connection flow...`,cards:1})}):(0,P.jsx)(`div`,{className:`connection-flow`,children:(0,P.jsxs)(`div`,{className:`connection-flow-container`,children:[u===`start`&&ge(),u===`authorize`&&ve(),u===`callback`&&ye(),u===`device_login`&&_e(),u===`complete`&&(()=>{if(l)return(0,P.jsxs)(`div`,{className:`connection-flow-step`,children:[(0,P.jsxs)(`div`,{className:`step-header`,children:[(0,P.jsx)(`h3`,{children:`Verifying connection`}),(0,P.jsx)(`p`,{children:`Running a quick health check against the new account.`})]}),(0,P.jsx)(`div`,{className:`step-content`,children:(0,P.jsxs)(`div`,{className:`connection-validating`,children:[(0,P.jsx)(`span`,{className:`login-spinner`,"aria-hidden":`true`}),(0,P.jsx)(`span`,{children:`Verifying connection...`})]})}),xe()]});if(c){if(c.status===`success`){let e=typeof c.latencyMs==`number`?` (${c.latencyMs}ms)`:``;return(0,P.jsxs)(`div`,{className:`connection-flow-step`,children:[(0,P.jsxs)(`div`,{className:`step-header`,children:[(0,P.jsx)(qe,{className:`success-icon`}),(0,P.jsx)(`h3`,{children:`Connection Verified`}),(0,P.jsx)(`p`,{children:`Connected successfully${e}.`})]}),(0,P.jsx)(`div`,{className:`step-content`,children:(0,P.jsx)(`div`,{className:`success-message`,children:(0,P.jsx)(`p`,{children:`The new account responded to a health check and is ready to use.`})})}),xe()]})}return c.status===`partial`?(0,P.jsxs)(`div`,{className:`connection-flow-step`,children:[(0,P.jsxs)(`div`,{className:`step-header`,children:[(0,P.jsx)(qe,{className:`success-icon`}),(0,P.jsx)(`h3`,{children:`Connection Saved — Partial Check`}),(0,P.jsx)(`p`,{children:`Your account was saved, but some health checks did not pass.`})]}),(0,P.jsx)(`div`,{className:`step-content`,children:(0,P.jsxs)(`div`,{className:`connection-notice`,children:[(0,P.jsx)(`p`,{children:`Health check results:`}),c.checks&&be(c.checks)]})}),xe()]}):c.status===`timeout`?(0,P.jsxs)(`div`,{className:`connection-flow-step`,children:[(0,P.jsxs)(`div`,{className:`step-header`,children:[(0,P.jsx)(Je,{className:`error-icon`}),(0,P.jsx)(`h3`,{children:`Connection Saved — Validation Timed Out`}),(0,P.jsx)(`p`,{children:`Your account was saved, but we couldn't verify it in time.`})]}),(0,P.jsx)(`div`,{className:`step-content`,children:(0,P.jsxs)(`div`,{className:`connection-warning`,children:[(0,P.jsx)(Je,{className:`error-icon`}),(0,P.jsx)(`span`,{children:`Validation timed out. Test manually.`})]})}),xe()]}):(0,P.jsxs)(`div`,{className:`connection-flow-step`,children:[(0,P.jsxs)(`div`,{className:`step-header`,children:[(0,P.jsx)(Je,{className:`error-icon`}),(0,P.jsx)(`h3`,{children:`Connection Saved — Validation Failed`}),(0,P.jsx)(`p`,{children:`Your account was saved, but the health check did not pass.`})]}),(0,P.jsx)(`div`,{className:`step-content`,children:(0,P.jsxs)(`div`,{className:`connection-warning`,children:[(0,P.jsx)(Je,{className:`error-icon`}),(0,P.jsxs)(`div`,{className:`connection-warning-body`,children:[(0,P.jsx)(`span`,{children:c.errorMessage||`Validation failed.`}),c.suggestedFix&&(0,P.jsx)(`span`,{className:`connection-warning-fix`,children:c.suggestedFix})]})]})}),xe()]})}return(0,P.jsxs)(`div`,{className:`connection-flow-step`,children:[(0,P.jsxs)(`div`,{className:`step-header`,children:[(0,P.jsx)(qe,{className:`success-icon`}),(0,P.jsx)(`h3`,{children:`Connection Successful`}),(0,P.jsx)(`p`,{children:`Your account has been connected successfully.`})]}),(0,P.jsx)(`div`,{className:`step-content`,children:(0,P.jsx)(`div`,{className:`success-message`,children:(0,P.jsx)(`p`,{children:`The new account is now available for this provider and will be included in the routing configuration.`})})}),xe()]})})()]})})}async function Fm(e){if(e===`kiro-ide`||e===`kiro-free`||e===`account-kiro`||e.startsWith(`kiro-`))return Im(e);try{let t=(await b(`/api/providers/${e}`)).provider;if(!t)return[];if(t.authMode===`kiro`)return Im(e);let n=[];switch(t.authMode){case`chatgpt_oauth`:let r=await Lm(e,t);n.push(...r);break;case`api_key`:let i=await Rm(e,t);n.push(...i);break;default:console.warn(`Unknown auth mode: ${t.authMode}`)}return n}catch{return[]}}async function Im(e){try{let t=await b(`/api/kiro/accounts`),n=[];return t.accounts?.forEach(t=>{n.push(Bm(e,t))}),n}catch(e){return console.error(`Failed to fetch Kiro accounts:`,e),[]}}async function Lm(e,t){try{let n=await b(`/api/chatgpt-oauth/status`),r=[];if(t.chatgptAccountId){let i=n.accounts?.find(e=>e.accountId===t.chatgptAccountId);i&&r.push(zm(e,i))}else n.accounts?.forEach(t=>{r.push(zm(e,t))});return r}catch(e){return console.error(`Failed to fetch ChatGPT OAuth accounts:`,e),[]}}async function Rm(e,t){let n=[];return t.providerApiKeys?.forEach((t,r)=>{n.push({id:`api-key-${r}`,providerId:e,authType:`api_key`,status:`connected`,label:`API Key ${r+1}`,routingMode:`round_robin`,metadata:{keyPrefix:t.substring(0,8)+`...`,keyName:`Key ${r+1}`,priority:r}})}),n}function zm(e,t){let n=new Date,r=t.expiresAt?new Date(t.expiresAt):null,i=r&&r<n,a=r&&r.getTime()-n.getTime()<10080*60*1e3,o=`connected`,s=`valid`;return t.disabled?o=`disabled`:i?(o=`expired`,s=`expired`):a&&(s=`expiring`),{id:t.accountId||t.id,providerId:e,authType:`oauth`,status:o,label:t.email||`OAuth Account`,email:t.email,routingMode:`priority`,tokenStatus:s,expiresAt:t.expiresAt,refreshable:!0,lastUsedAt:t.lastRefreshAt,metadata:{accountId:t.accountId,idToken:t.idToken?`[REDACTED]`:void 0}}}function Bm(e,t){let n=t.tokenStatus||`unknown`,r=`connected`;return t.isActive?n===`expired`?r=`expired`:n===`missing`&&(r=`invalid`):r=`disabled`,{id:t.id,providerId:e,authType:`oauth`,status:r,label:t.name||`Kiro Account`,routingMode:`round_robin`,tokenStatus:n,expiresAt:t.expiresAt,refreshable:!0,lastUsedAt:t.updatedAt,metadata:{profileArn:t.providerSpecificData?.profileArn,region:t.providerSpecificData?.region,clientId:t.providerSpecificData?.clientId,authMethod:t.providerSpecificData?.authMethod,startUrl:t.providerSpecificData?.startUrl,priority:t.priority,isActive:t.isActive}}}async function Vm(e,t){try{if(e===`kiro-ide`||e===`kiro-free`||e===`account-kiro`||e.startsWith(`kiro-`)){let n=await Um(t);return{providerId:e,accountId:t,status:n.success?`success`:`failed`,testedAt:new Date().toISOString(),latencyMs:n.latencyMs,authOk:n.authOk!==!1,quotaOk:n.quotaOk!==!1,modelOk:n.modelOk!==!1,routingOk:n.routingOk!==!1,testedModel:n.testedModel,errorCode:n.errorCode,errorMessage:n.errorMessage,suggestedFix:n.suggestedFix}}let n=(await b(`/api/providers/${e}`)).provider;if(!n)throw Error(`Provider not found`);let r;switch(n.authMode){case`chatgpt_oauth`:r=await Hm(t);break;case`kiro`:r=await Um(t);break;case`api_key`:r=await Wm(e,t);break;default:throw Error(`Unsupported auth mode: ${n.authMode}`)}return{providerId:e,accountId:t,status:r.success?`success`:`failed`,testedAt:new Date().toISOString(),latencyMs:r.latencyMs,authOk:r.authOk!==!1,quotaOk:r.quotaOk!==!1,modelOk:r.modelOk!==!1,routingOk:r.routingOk!==!1,testedModel:r.testedModel,errorCode:r.errorCode,errorMessage:r.errorMessage,suggestedFix:r.suggestedFix}}catch(n){return{providerId:e,accountId:t,status:`failed`,testedAt:new Date().toISOString(),authOk:!1,quotaOk:!1,modelOk:!1,routingOk:!1,errorMessage:n instanceof Error?n.message:`Test failed`,suggestedFix:`Check account configuration and try again`}}}async function Hm(e){try{return await x(`/api/account-auth/accounts/${e}/test`,`POST`,{})}catch(e){return{success:!1,authOk:!1,errorMessage:e instanceof Error?e.message:`OAuth test failed`,suggestedFix:`Try refreshing the account tokens`}}}async function Um(e){try{let t=Date.now();return await x(`/api/kiro/accounts/${e}/refresh`,`POST`,{}),{success:!0,authOk:!0,quotaOk:!0,modelOk:!0,routingOk:!0,latencyMs:Date.now()-t}}catch(e){return{success:!1,authOk:!1,errorMessage:e instanceof Error?e.message:`Kiro test failed`,suggestedFix:`Check Kiro account configuration and refresh tokens`}}}async function Wm(e,t){try{return await x(`/api/providers/${e}/test`,`POST`,{accountId:t})}catch(e){return{success:!1,authOk:!1,errorMessage:e instanceof Error?e.message:`API key test failed`,suggestedFix:`Verify API key is valid and has necessary permissions`}}}async function Gm(e,t,n){if(e===`kiro-ide`||e===`kiro-free`||e===`account-kiro`||e.startsWith(`kiro-`)){await x(`/api/kiro/accounts/${t}`,`PATCH`,{routingMode:n});return}try{let r=(await b(`/api/providers/${e}`)).provider;if(!r)throw Error(`Provider not found`);switch(r.authMode){case`chatgpt_oauth`:await x(`/api/chatgpt-oauth/settings`,`PATCH`,{rotationMode:Km(n)});break;case`kiro`:await x(`/api/kiro/accounts/${t}`,`PATCH`,{routingMode:n});break;case`api_key`:console.warn(`API key accounts do not support individual routing modes`);break;default:throw Error(`Unsupported auth mode: ${r.authMode}`)}}catch(e){throw console.error(`Failed to update routing mode for account ${t}:`,e),Error(`Failed to update account routing mode`)}}function Km(e){switch(e){case`round_robin`:return`round_robin`;case`priority`:return`first_available`;case`sticky`:return`first_available`;case`failover_only`:return`first_available`;default:return`round_robin`}}async function qm(e,t){if(e===`kiro-ide`||e===`kiro-free`||e===`account-kiro`||e.startsWith(`kiro-`)){await x(`/api/kiro/accounts/${t}/refresh`,`POST`,{});let n=(await Fm(e)).find(e=>e.id===t);if(!n)throw Error(`Account not found after refresh`);return n}try{let n=(await b(`/api/providers/${e}`)).provider;if(!n)throw Error(`Provider not found`);switch(n.authMode){case`chatgpt_oauth`:await x(`/api/account-auth/accounts/${t}/refresh`,`POST`,{});break;case`kiro`:await x(`/api/kiro/accounts/${t}/refresh`,`POST`,{});break;case`api_key`:throw Error(`API key accounts do not support token refresh`);default:throw Error(`Unsupported auth mode: ${n.authMode}`)}let r=(await Fm(e)).find(e=>e.id===t);if(!r)throw Error(`Account not found after refresh`);return r}catch(e){throw console.error(`Failed to refresh account ${t}:`,e),Error(`Failed to refresh account`)}}async function Jm(e,t){if(e===`kiro-ide`||e===`kiro-free`||e===`account-kiro`||e.startsWith(`kiro-`)){await x(`/api/kiro/accounts/${t}`,`DELETE`,{});return}try{let n=(await b(`/api/providers/${e}`)).provider;if(!n)throw Error(`Provider not found`);switch(n.authMode){case`chatgpt_oauth`:await x(`/api/account-auth/accounts/${t}`,`DELETE`,{});break;case`kiro`:await x(`/api/kiro/accounts/${t}`,`DELETE`,{});break;case`api_key`:let r=parseInt(t.replace(`api-key-`,``),10);if(isNaN(r))throw Error(`Invalid account ID for API key: ${t}`);let i=(Array.isArray(n.providerApiKeys)?n.providerApiKeys:[]).filter((e,t)=>t!==r);await x(`/api/providers/${encodeURIComponent(e)}`,`PUT`,{name:n.name,baseUrl:n.baseUrl,authMode:n.authMode,providerApiKeys:i,capabilities:n.capabilities});break;default:throw Error(`Unsupported auth mode: ${n.authMode}`)}}catch(e){throw console.error(`Failed to delete account ${t}:`,e),Error(`Failed to delete account`)}}async function Ym(e,t){try{switch(t){case`oauth`:{let t=null;try{t=(await b(`/api/providers/${e}`)).provider}catch{}let n=Wp(e),r=t?.authMode||n?.preferredAuthType||`api_key`;if(r===`chatgpt_oauth`||e===`openai-codex`||e.includes(`chatgpt`)||e===`account-openai-codex`){let e=await x(`/api/chatgpt-oauth/start`,`POST`,{});return{type:`oauth`,authUrl:e.authUrl,state:e.state,instructions:`Click the link to authorize with ChatGPT, then paste the callback URL below.`,requiresCallback:!0}}else if(r===`kiro`||e.startsWith(`kiro-`))return{type:`kiro`,instructions:`Kiro accounts are imported from a 9router database. The proxy then owns token refresh (write-back) without sharing 9router's live database.`,requiresCallback:!1};throw Error(`OAuth authentication is not supported for this provider on the backend. Please use API Key authentication instead.`)}case`api_key`:return{type:`api_key`,instructions:`Enter your API key below. Make sure it has the necessary permissions for this provider.`,requiresCallback:!1};default:throw Error(`Unsupported auth type: ${t}`)}}catch(e){throw console.error(`Failed to start connection flow for ${t}:`,e),e instanceof Error?e:Error(`Failed to start account connection`)}}function Xm(e){let[t,n]=(0,v.useState)([]),[r,i]=(0,v.useState)(!1),[a,o]=(0,v.useState)(null),[s,c]=(0,v.useState)(null),l=(0,v.useCallback)(async()=>{if(!e){n([]),i(!1),o(null);return}try{i(!0),o(null),n(await Fm(e)),c(new Date)}catch(e){o(e instanceof Error?e.message:`Failed to load accounts`),n([])}finally{i(!1)}},[e]);(0,v.useEffect)(()=>{l()},[l]);let u=(0,v.useCallback)(async()=>{await l()},[l]);return{accounts:t,loading:r,error:a,lastRefresh:s,stats:(0,v.useMemo)(()=>{let e=t.length,n=t.filter(e=>e.status===`connected`).length,r=t.filter(e=>e.status===`expired`).length,i=t.filter(e=>e.tokenStatus===`expiring`).length;return{total:e,connected:n,expired:r,expiring:i,disabled:t.filter(e=>e.status===`disabled`).length,healthy:n,needsAttention:r+i}},[t]),refresh:u}}function Zm(e){let[t,n]=(0,v.useState)(new Map),[r,i]=(0,v.useState)(new Set);return{testAccount:(0,v.useCallback)(async t=>{if(!(!e||r.has(t)))try{i(e=>new Set(e).add(t));let r=await Vm(e,t);return n(e=>new Map(e).set(t,r)),r}catch(r){let i={providerId:e,accountId:t,status:`failed`,testedAt:new Date().toISOString(),authOk:!1,quotaOk:!1,modelOk:!1,routingOk:!1,errorMessage:r instanceof Error?r.message:`Test failed`,suggestedFix:`Check account configuration and try again`};return n(e=>new Map(e).set(t,i)),i}finally{i(e=>{let n=new Set(e);return n.delete(t),n})}},[e,r]),getTestResult:(0,v.useCallback)(e=>t.get(e),[t]),isTestingAccount:(0,v.useCallback)(e=>r.has(e),[r]),clearTestResult:(0,v.useCallback)(e=>{n(t=>{let n=new Map(t);return n.delete(e),n})},[]),clearAllTestResults:(0,v.useCallback)(()=>{n(new Map)},[]),hasTestResults:t.size>0}}function Qm(e){let[t,n]=(0,v.useState)(new Map),[r,i]=(0,v.useState)(null),a=(0,v.useCallback)((e,t)=>{n(n=>new Map(n).set(e,t)),i(null)},[]),o=(0,v.useCallback)(e=>{n(t=>{let n=new Map(t);return n.delete(e),n})},[]);return{updateRoutingMode:(0,v.useCallback)(async(t,n)=>{if(!e)throw Error(`Provider ID is required`);try{a(t,`updating`),await Gm(e,t,n)}catch(e){throw i(e instanceof Error?e.message:`Failed to update routing mode`),e}finally{o(t)}},[e,a,o]),refreshAccount:(0,v.useCallback)(async t=>{if(!e)throw Error(`Provider ID is required`);try{return a(t,`refreshing`),await qm(e,t)}catch(e){throw i(e instanceof Error?e.message:`Failed to refresh account`),e}finally{o(t)}},[e,a,o]),deleteAccount:(0,v.useCallback)(async t=>{if(!e)throw Error(`Provider ID is required`);try{a(t,`deleting`),await Jm(e,t)}catch(e){throw i(e instanceof Error?e.message:`Failed to delete account`),e}finally{o(t)}},[e,a,o]),isAccountLoading:(0,v.useCallback)(e=>t.has(e),[t]),getAccountOperation:(0,v.useCallback)(e=>t.get(e),[t]),operationError:r,clearError:(0,v.useCallback)(()=>{i(null)},[])}}function $m(e){let[t,n]=(0,v.useState)(null),[r,i]=(0,v.useState)(!1),[a,o]=(0,v.useState)(null);return{connectionFlow:t,connecting:r,connectionError:a,startConnection:(0,v.useCallback)(async t=>{if(!e)throw Error(`Provider ID is required`);try{i(!0),o(null);let r=await Ym(e,t);return n(r),r}catch(e){throw o(e instanceof Error?e.message:`Failed to start connection`),e}finally{i(!1)}},[e]),clearConnectionFlow:(0,v.useCallback)(()=>{n(null),o(null)},[]),clearError:(0,v.useCallback)(()=>{o(null)},[])}}function eh(e){let t=(0,v.useMemo)(()=>{let t={healthy:0,warning:0,critical:0,total:e.length};return e.forEach(e=>{switch(e.status){case`connected`:e.tokenStatus===`expiring`?t.warning++:t.healthy++;break;case`expired`:case`invalid`:t.critical++;break;case`disabled`:break;default:t.warning++}}),t},[e]),n=(0,v.useMemo)(()=>e.filter(e=>e.tokenStatus===`expiring`||e.expiresAt&&new Date(e.expiresAt).getTime()-Date.now()<10080*60*1e3),[e]),r=(0,v.useMemo)(()=>e.filter(e=>e.status===`expired`||e.tokenStatus===`expired`),[e]),i=(0,v.useMemo)(()=>e.filter(e=>e.status===`expired`||e.status===`invalid`||e.status===`needs_reconnect`||e.tokenStatus===`expiring`||e.tokenStatus===`expired`),[e]);return{healthSummary:t,expiringAccounts:n,expiredAccounts:r,needsAttentionAccounts:i,hasHealthIssues:i.length>0}}async function th({providerId:e,apiKey:t}){let n=Wp(e);if(!n)throw Error(`Provider ${e} not found in catalog.`);let r={id:e,name:n.name,baseUrl:n.defaultBaseUrl||`https://api.example.com`,authMode:`api_key`,providerApiKeys:[t],capabilities:{transportMode:`chat_completions`}};try{await O(r)}catch(n){let r=n instanceof Error?n.message:String(n);if(r.includes(`already assigned to another provider`))throw Error(`This API key is already registered with a different provider. Remove it from that provider first.`);if(r.includes(`already exists`)){await nh(e,t);return}throw n}}async function nh(e,t){let n=(await b(`/api/providers/${encodeURIComponent(e)}`)).provider;if(!n)throw Error(`Provider ${e} reported as existing but could not be fetched.`);let r=Array.isArray(n.providerApiKeys)?n.providerApiKeys:[];if(!r.includes(t))try{await ee(e,{name:n.name??``,baseUrl:n.baseUrl??``,authMode:n.authMode??`api_key`,providerApiKeys:[...r,t],capabilities:n.capabilities})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to add API key to existing provider: ${t}`)}}var rh=`__TIMEOUT__`,ih=1e4;function ah(e){let t={authOk:e.authOk,quotaOk:e.quotaOk,modelOk:e.modelOk,routingOk:e.routingOk};return e.status===`success`?{status:`success`,latencyMs:e.latencyMs,checks:t}:e.status===`partial`?{status:`partial`,latencyMs:e.latencyMs,checks:t}:{status:`failed`,errorMessage:e.errorMessage,suggestedFix:e.suggestedFix,checks:t}}async function oh(e,t,n=ih){let r,i=Vm(e,t),a=new Promise((e,t)=>{r=setTimeout(()=>t(Error(rh)),n)});try{return ah(await Promise.race([i,a]))}catch(e){return e instanceof Error&&e.message===rh?{status:`timeout`}:{status:`failed`,errorMessage:e instanceof Error?e.message:`Validation failed`,suggestedFix:`Try testing the connection manually from the accounts list.`}}finally{r!==void 0&&clearTimeout(r)}}function sh({providerId:e,providerName:t,supportedAuthTypes:n,accounts:r,isOpen:i,mode:a,editingAccount:o,onClose:s,onAccountsChanged:c}){let[l,u]=(0,v.useState)(n[0]),[d,f]=(0,v.useState)(!1),[p,m]=(0,v.useState)(!1),[h,g]=(0,v.useState)(null),{connectionFlow:_,connecting:y,connectionError:x,startConnection:S,clearConnectionFlow:C,clearError:w}=$m(e),{updateRoutingMode:T,refreshAccount:E,deleteAccount:D,isAccountLoading:O,getAccountOperation:k,operationError:te,clearError:ne}=Qm(e);(0,v.useEffect)(()=>{i&&(C(),w(),ne(),f(!1),m(!1),g(null),o&&u(o.authType))},[i,o,C,w,ne]);let re=(0,v.useCallback)(async e=>{try{await S(e)}catch(e){console.error(`Failed to start connection:`,e)}},[S]),ie=(0,v.useCallback)(async t=>{m(!0),g(null);try{g(await oh(e,t))}finally{m(!1)}},[e]),ae=(0,v.useCallback)(async t=>{try{let n=null;if(t.kiroImport){let e=await Ce(t.sourcePath?{sourcePath:t.sourcePath}:void 0);if(e.imported===0)throw Error(`No Kiro accounts were found in the source database. Sign in through 9router first.`);if(e.imported===1)try{n=(await ye()).accounts?.[0]?.id??null}catch(e){console.warn(`Could not resolve imported Kiro account for validation:`,e)}}else if(t.callbackUrl)n=(await N({redirectUrl:t.callbackUrl})).account?.accountId??null;else if(t.apiKey){let r=t.apiKey,i=null;try{let t=await b(`/api/providers/${encodeURIComponent(e)}`);t.ok&&t.provider&&(i=t.provider)}catch(e){console.log(`Provider does not exist on backend:`,e)}if(!i)await th({providerId:e,apiKey:r}),n=`api-key-0`;else{let t=Array.isArray(i.providerApiKeys)?i.providerApiKeys:[];t.includes(r)?n=`api-key-${t.indexOf(r)}`:(n=`api-key-${t.length}`,await ee(e,{name:i.name??``,baseUrl:i.baseUrl??``,authMode:i.authMode??`api_key`,providerApiKeys:[...t,r],capabilities:i.capabilities}))}}c(),n&&ie(n)}catch(e){throw console.error(`Failed to complete connection:`,e),e}},[e,c,ie]),A=(0,v.useCallback)(async(e,t)=>{try{await T(e,t),c()}catch(e){console.error(`Failed to update routing mode:`,e)}},[T,c]),j=(0,v.useCallback)(async e=>{try{await E(e),c()}catch(e){console.error(`Failed to refresh account:`,e)}},[E,c]),oe=(0,v.useCallback)(async e=>{try{await D(e),c(),f(!1),a===`edit`&&s()}catch(e){console.error(`Failed to delete account:`,e)}},[D,c,a,s]),[se,ce]=(0,v.useState)(``),[le,M]=(0,v.useState)(``),[ue,de]=(0,v.useState)(`idle`),[fe,pe]=(0,v.useState)(!1),[me,he]=(0,v.useState)(null);(0,v.useEffect)(()=>{i&&a===`add`&&(ce(``),M(``),de(`idle`),pe(!1),he(null))},[i,a]);let ge=(0,v.useCallback)(async()=>{if(le.trim()){pe(!0),he(null);try{await ae({apiKey:le.trim(),keyName:se.trim()||`API Key`})}catch(e){he(e instanceof Error?e.message:`Failed to save`)}finally{pe(!1)}}},[le,se,ae]),_e=n.length===1&&n[0]===`api_key`,ve=n.includes(`oauth`)||_?.type===`kiro`,be=(0,v.useRef)(!1);return(0,v.useEffect)(()=>{i&&a===`add`&&ve&&!_&&!be.current&&(be.current=!0,re(n.includes(`oauth`)?`oauth`:n[0])),i||(be.current=!1)},[i,a,ve,n,_,re]),i?(0,P.jsx)(`div`,{className:`modal-backdrop`,onClick:s,children:(0,P.jsxs)(`div`,{className:`modal-card account-management-modal`,onClick:e=>e.stopPropagation(),children:[a===`add`&&(_e?!fe&&!me&&h?(0,P.jsxs)(`div`,{className:`account-modal-content`,children:[(0,P.jsx)(`div`,{className:`modal-header`,children:(0,P.jsx)(`h2`,{children:`Account Added`})}),(0,P.jsx)(`div`,{className:`step-content`,children:(0,P.jsx)(`div`,{className:`add-key-badge ${h.status===`success`?`valid`:`warning`}`,children:h.status===`success`?(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(qe,{className:`success-icon`}),` Connected`,h.latencyMs?` (${h.latencyMs}ms)`:``]}):(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(Je,{className:`error-icon`}),` Saved — `,h.errorMessage||`verify manually`]})})}),(0,P.jsx)(`div`,{className:`modal-actions`,children:(0,P.jsx)(`button`,{className:`button-primary`,onClick:s,children:`Done`})})]}):p?(0,P.jsxs)(`div`,{className:`account-modal-content`,children:[(0,P.jsx)(`div`,{className:`modal-header`,children:(0,P.jsx)(`h2`,{children:`Verifying...`})}),(0,P.jsxs)(`div`,{className:`connection-validating`,style:{padding:`var(--space-4)`,justifyContent:`center`},children:[(0,P.jsx)(`span`,{className:`login-spinner`,"aria-hidden":`true`}),(0,P.jsx)(`span`,{children:`Verifying connection...`})]}),(0,P.jsx)(`div`,{className:`modal-actions`,children:(0,P.jsx)(`button`,{className:`button-secondary`,onClick:s,children:`Done`})})]}):(0,P.jsxs)(`div`,{className:`account-modal-content`,children:[(0,P.jsx)(`div`,{className:`modal-header`,children:(0,P.jsxs)(`h2`,{children:[`Add `,t,` API Key`]})}),(0,P.jsxs)(`div`,{className:`add-key-form`,children:[(0,P.jsxs)(`div`,{className:`form-group`,children:[(0,P.jsx)(`label`,{htmlFor:`add-key-name`,className:`form-label`,children:`Name`}),(0,P.jsx)(`input`,{id:`add-key-name`,type:`text`,className:`form-input`,placeholder:`Production Key`,value:se,onChange:e=>ce(e.target.value),disabled:fe})]}),(0,P.jsxs)(`div`,{className:`form-group`,children:[(0,P.jsx)(`label`,{htmlFor:`add-key-value`,className:`form-label`,children:`API Key`}),(0,P.jsx)(`div`,{className:`form-input-row`,children:(0,P.jsx)(`input`,{id:`add-key-value`,type:`password`,className:`form-input`,placeholder:`sk-...`,value:le,onChange:e=>{M(e.target.value),de(`idle`)},disabled:fe})})]}),ue===`valid`&&(0,P.jsxs)(`div`,{className:`add-key-badge valid`,children:[(0,P.jsx)(qe,{className:`success-icon`}),` Valid`]}),ue===`invalid`&&(0,P.jsxs)(`div`,{className:`add-key-badge invalid`,children:[(0,P.jsx)(Je,{className:`error-icon`}),` Invalid`]}),me&&(0,P.jsxs)(`div`,{className:`connection-error`,children:[(0,P.jsx)(Je,{className:`error-icon`}),(0,P.jsx)(`span`,{children:me})]})]}),(0,P.jsxs)(`div`,{className:`modal-actions`,children:[(0,P.jsx)(`button`,{className:`button-secondary`,onClick:s,disabled:fe,children:`Cancel`}),(0,P.jsx)(`button`,{className:`button-primary`,onClick:ge,disabled:!le.trim()||fe,children:fe?`Saving...`:`Save`})]})]}):_?(0,P.jsx)(`div`,{className:`account-modal-content`,children:(0,P.jsx)(Pm,{providerId:e,authType:l,connectionFlow:_,connecting:y,error:x,onStartConnection:re,onCompleteConnection:ae,onCancel:s,validating:p,validationResult:h})}):n.length>1&&!ve?(0,P.jsxs)(`div`,{className:`account-modal-content`,children:[(0,P.jsxs)(`div`,{className:`modal-header`,children:[(0,P.jsxs)(`h2`,{children:[`Add Account to `,t]}),(0,P.jsx)(`p`,{children:`Choose how to connect.`})]}),(0,P.jsx)(`div`,{className:`auth-type-options`,children:n.map(e=>(0,P.jsx)(`button`,{className:`auth-type-option ${l===e?`selected`:``}`,onClick:()=>u(e),children:(0,P.jsxs)(`div`,{className:`auth-type-info`,children:[(0,P.jsx)(B,{variant:e===`oauth`?`accent`:`neutral`,size:`sm`,children:e===`oauth`?`OAuth`:`API Key`}),(0,P.jsxs)(`div`,{className:`auth-type-description`,children:[e===`oauth`&&`Secure OAuth authentication`,e===`api_key`&&`Direct API key authentication`]})]})},e))}),(0,P.jsxs)(`div`,{className:`modal-actions`,children:[(0,P.jsx)(`button`,{className:`button-secondary`,onClick:s,children:`Cancel`}),(0,P.jsx)(`button`,{className:`button-primary`,onClick:()=>re(l),disabled:y,children:y?`Starting...`:`Continue`})]})]}):(0,P.jsx)(`div`,{className:`account-modal-content`,children:(0,P.jsxs)(`div`,{className:`connection-validating`,style:{padding:`var(--space-6)`,justifyContent:`center`},children:[(0,P.jsx)(`span`,{className:`login-spinner`,"aria-hidden":`true`}),(0,P.jsx)(`span`,{children:`Preparing connection...`})]})})),a===`edit`&&(o?(0,P.jsxs)(`div`,{className:`account-modal-content`,children:[(0,P.jsxs)(`div`,{className:`modal-header`,children:[(0,P.jsx)(`h2`,{children:`Manage Account`}),(0,P.jsxs)(`p`,{children:[`Configure settings for `,o.label]})]}),(0,P.jsxs)(`div`,{className:`account-details`,children:[(0,P.jsxs)(`div`,{className:`account-info-section`,children:[(0,P.jsx)(`h3`,{children:`Account Information`}),(0,P.jsxs)(`div`,{className:`account-info-grid`,children:[(0,P.jsxs)(`div`,{className:`info-item`,children:[(0,P.jsx)(`label`,{children:`Account Name`}),(0,P.jsx)(`span`,{children:o.label})]}),o.email&&(0,P.jsxs)(`div`,{className:`info-item`,children:[(0,P.jsx)(`label`,{children:`Email`}),(0,P.jsx)(`span`,{children:o.email})]}),(0,P.jsxs)(`div`,{className:`info-item`,children:[(0,P.jsx)(`label`,{children:`Authentication`}),(0,P.jsx)(B,{variant:o.authType===`oauth`?`accent`:`neutral`,size:`sm`,children:o.authType===`oauth`?`OAuth`:`API Key`})]}),(0,P.jsxs)(`div`,{className:`info-item`,children:[(0,P.jsx)(`label`,{children:`Status`}),(0,P.jsx)(B,{variant:o.status===`connected`?`success`:o.status===`expired`?`error`:`warning`,size:`sm`,children:o.status})]})]})]}),(0,P.jsxs)(`div`,{className:`routing-config-section`,children:[(0,P.jsx)(`h3`,{children:`Routing Configuration`}),(0,P.jsxs)(`div`,{className:`routing-mode-selector`,children:[(0,P.jsx)(`label`,{htmlFor:`routingMode`,children:`Routing Mode`}),(0,P.jsxs)(`select`,{id:`routingMode`,value:o.routingMode,onChange:e=>A(o.id,e.target.value),disabled:O(o.id),children:[(0,P.jsx)(`option`,{value:`priority`,children:`Priority (Use first)`}),(0,P.jsx)(`option`,{value:`round_robin`,children:`Round Robin`}),(0,P.jsx)(`option`,{value:`sticky`,children:`Sticky (Session-based)`}),(0,P.jsx)(`option`,{value:`failover_only`,children:`Failover Only`}),(0,P.jsx)(`option`,{value:`disabled`,children:`Disabled`})]})]})]}),o.tokenStatus&&(0,P.jsxs)(`div`,{className:`token-status-section`,children:[(0,P.jsx)(`h3`,{children:`Token Status`}),(0,P.jsxs)(`div`,{className:`token-info`,children:[(0,P.jsx)(B,{variant:o.tokenStatus===`valid`?`success`:o.tokenStatus===`expiring`?`warning`:`error`,size:`sm`,children:o.tokenStatus}),o.expiresAt&&(0,P.jsxs)(`span`,{className:`token-expiry`,children:[`Expires: `,new Date(o.expiresAt).toLocaleString()]})]})]}),(x||te)&&(0,P.jsxs)(`div`,{className:`modal-error`,children:[(0,P.jsx)(Je,{className:`error-icon`}),(0,P.jsx)(`span`,{children:x||te})]})]}),(0,P.jsx)(`div`,{className:`account-actions`,children:(0,P.jsxs)(`div`,{className:`account-action-buttons`,children:[o.refreshable&&(0,P.jsxs)(`button`,{className:`button-secondary`,onClick:()=>j(o.id),disabled:O(o.id),children:[(0,P.jsx)(We,{className:`button-icon`}),k(o.id)===`refreshing`?`Refreshing...`:`Refresh Tokens`]}),(0,P.jsxs)(`button`,{className:`button-danger`,onClick:()=>f(!0),disabled:O(o.id),children:[(0,P.jsx)(st,{className:`button-icon`}),`Delete Account`]})]})}),(0,P.jsx)(`div`,{className:`modal-actions`,children:(0,P.jsx)(`button`,{className:`button-secondary`,onClick:s,children:`Close`})}),d&&(0,P.jsx)(`div`,{className:`delete-confirm-overlay`,children:(0,P.jsxs)(`div`,{className:`delete-confirm-dialog`,children:[(0,P.jsx)(`h3`,{children:`Delete Account`}),(0,P.jsxs)(`p`,{children:[`Are you sure you want to delete "`,o.label,`"? This will remove the account from this provider and cannot be undone.`]}),(0,P.jsxs)(`div`,{className:`delete-confirm-actions`,children:[(0,P.jsx)(`button`,{className:`button-secondary`,onClick:()=>f(!1),disabled:O(o.id),children:`Cancel`}),(0,P.jsx)(`button`,{className:`button-danger`,onClick:()=>oe(o.id),disabled:O(o.id),children:k(o.id)===`deleting`?`Deleting...`:`Delete Account`})]})]})})]}):null),a===`manage`&&(0,P.jsxs)(`div`,{className:`account-modal-content`,children:[(0,P.jsxs)(`div`,{className:`modal-header`,children:[(0,P.jsxs)(`h2`,{children:[`Manage Accounts for `,t]}),(0,P.jsx)(`p`,{children:`Configure all accounts connected to this provider.`})]}),(0,P.jsx)(`div`,{className:`accounts-list`,children:r.length===0?(0,P.jsxs)(`div`,{className:`no-accounts`,children:[(0,P.jsx)(`p`,{children:`No accounts connected to this provider.`}),(0,P.jsx)(`button`,{className:`button-primary`,onClick:()=>re(n[0]),children:`Add First Account`})]}):(0,P.jsx)(`div`,{className:`accounts-grid`,children:r.map(e=>(0,P.jsxs)(`div`,{className:`account-summary-card`,children:[(0,P.jsxs)(`div`,{className:`account-summary-header`,children:[(0,P.jsx)(`div`,{className:`account-name`,children:e.label}),(0,P.jsx)(B,{variant:e.status===`connected`?`success`:e.status===`expired`?`error`:`warning`,size:`sm`,children:e.status})]}),(0,P.jsxs)(`div`,{className:`account-summary-details`,children:[e.email&&(0,P.jsx)(`div`,{className:`account-email`,children:e.email}),(0,P.jsxs)(`div`,{className:`account-routing`,children:[`Routing: `,e.routingMode]})]}),(0,P.jsx)(`div`,{className:`account-summary-actions`,children:(0,P.jsx)(`button`,{className:`button-secondary button-sm`,onClick:()=>{},children:`Edit`})})]},e.id))})}),(0,P.jsxs)(`div`,{className:`modal-actions`,children:[(0,P.jsx)(`button`,{className:`button-secondary`,onClick:s,children:`Close`}),r.length>0&&(0,P.jsx)(`button`,{className:`button-primary`,onClick:()=>re(n[0]),children:`Add Another Account`})]})]})]})}):null}var ch={requireEnabled:!0,requireConfigured:!0,requireHealthy:!0,requireQuotaAvailable:!0,requireActiveAccount:!0,requireServiceKinds:[`chat`],allowDegraded:!0,minimumScore:50};function lh(e,t=ch){let n=[],r=[],i=100,a=!0;if(t.requireEnabled&&!e.enabled&&(a=!1,n.push(`Provider is disabled`),i-=50),t.requireConfigured&&!e.configured&&(a=!1,n.push(`Provider is not configured`),i-=40),t.requireHealthy){let o=uh(e.healthStatus);i=Math.min(i,o),e.healthStatus===`not_configured`?(a=!1,n.push(`Provider is not configured`)):e.healthStatus===`disabled`?(a=!1,n.push(`Provider is disabled`)):e.healthStatus===`auth_expired`?(a=!1,n.push(`Authentication has expired`)):e.healthStatus===`quota_exhausted`?t.requireQuotaAvailable?(a=!1,n.push(`Quota is exhausted`)):r.push(`Quota is exhausted but may recover`):e.healthStatus===`rate_limited`?(r.push(`Provider is currently rate limited`),i-=20):e.healthStatus===`degraded`?t.allowDegraded?(r.push(`Provider is degraded but still usable`),i-=15):(a=!1,n.push(`Provider is degraded and strict health is required`)):e.healthStatus===`unknown`&&(r.push(`Provider health status is unknown`),i-=10)}if(t.requireQuotaAvailable&&e.quota&&(e.quota.hardLimitReached?(a=!1,n.push(`Hard quota limit reached`)):e.quota.softLimitReached?(r.push(`Soft quota limit reached`),i-=10):e.quota.usagePercent&&e.quota.usagePercent>90&&(r.push(`Quota usage is very high (>90%)`),i-=5)),t.requireActiveAccount){let t=dh(e.accounts||[]);if(t.length===0)a=!1,n.push(`No active accounts available`);else{let e=fh(t);i=Math.min(i,e),e<50&&r.push(`Account health is poor`)}}if(t.requireServiceKinds&&t.requireServiceKinds.length>0){let r=t.requireServiceKinds.filter(t=>!e.serviceKinds.includes(t));r.length>0&&(a=!1,n.push(`Missing required services: ${r.join(`, `)}`))}return t.requireServiceKinds?.includes(`chat`)&&(e.models?.filter(e=>e.serviceKind===`chat`&&e.enabled)||[]).length===0&&(a=!1,n.push(`No enabled chat models available`)),t.minimumScore&&i<t.minimumScore&&(a=!1,n.push(`Provider score (${i}) below minimum required (${t.minimumScore})`)),e.fallbackEligible||(a=!1,n.push(`Provider is marked as not fallback eligible`)),{eligible:a,reasons:n,warnings:r,score:Math.max(0,i),lastCheckedAt:new Date().toISOString()}}function uh(e){switch(e){case`healthy`:return 100;case`degraded`:return 75;case`rate_limited`:return 60;case`quota_exhausted`:return 40;case`unknown`:return 50;case`auth_expired`:return 20;case`disabled`:return 0;case`not_configured`:return 0;default:return 50}}function dh(e){return e.filter(e=>e.status===`connected`&&e.routingMode!==`disabled`)}function fh(e){if(e.length===0)return 0;let t=e.map(e=>{switch(e.status){case`connected`:return 100;case`needs_reconnect`:return 60;case`expired`:return 30;case`invalid`:return 20;case`disabled`:return 0;case`unknown`:return 50;default:return 50}});return Math.round(t.reduce((e,t)=>e+t,0)/t.length)}function ph(e){return(0,P.jsx)(`svg`,{viewBox:`0 0 16 16`,width:`14`,height:`14`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,className:e.className,children:(0,P.jsx)(`path`,{d:`M4 10l4-4 4 4`})})}function mh(e){return(0,P.jsx)(`svg`,{viewBox:`0 0 16 16`,width:`14`,height:`14`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,className:e.className,children:(0,P.jsx)(`path`,{d:`M4 6l4 4 4-4`})})}function hh(e){return(0,P.jsxs)(`svg`,{viewBox:`0 0 16 16`,width:`15`,height:`15`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.6`,strokeLinecap:`round`,strokeLinejoin:`round`,className:e.className,children:[(0,P.jsx)(`rect`,{x:`3.5`,y:`7`,width:`9`,height:`6.5`,rx:`1.5`}),(0,P.jsx)(`path`,{d:`M5.5 7V5a2.5 2.5 0 0 1 5 0v2`})]})}function gh(e){return(0,P.jsx)(`svg`,{viewBox:`0 0 16 16`,width:`15`,height:`15`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.6`,strokeLinecap:`round`,strokeLinejoin:`round`,className:e.className,children:(0,P.jsx)(`path`,{d:`M11.5 2.5l2 2L6 12l-2.5.5L4 10z`})})}function _h(e){return(0,P.jsxs)(`svg`,{viewBox:`0 0 16 16`,width:`14`,height:`14`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.6`,strokeLinecap:`round`,strokeLinejoin:`round`,className:e.className,children:[(0,P.jsx)(`rect`,{x:`5.5`,y:`5.5`,width:`8`,height:`8`,rx:`1.5`}),(0,P.jsx)(`path`,{d:`M3.5 10.5h-1A1 1 0 0 1 1.5 9.5v-7a1 1 0 0 1 1-1h7a1 1 0 0 1 1 1v1`})]})}function vh({provider:e,onToggleEnabled:t}){let n=Wp(e.id),r=e.accounts?.length||0,i=e.enabled!==!1;return(0,P.jsxs)(`div`,{className:`pd9-header`,children:[(0,P.jsx)(`button`,{className:`pd9-back`,onClick:()=>window.location.hash=`#/providers`,children:`← Back to Providers`}),(0,P.jsxs)(`div`,{className:`pd9-title-row`,children:[(0,P.jsx)(`div`,{className:`pd9-icon-tile`,children:(0,P.jsx)(Ie,{})}),(0,P.jsxs)(`div`,{className:`pd9-title-main`,children:[(0,P.jsxs)(`div`,{className:`pd9-title-line`,children:[(0,P.jsx)(`h1`,{className:`pd9-title`,children:e.displayName}),t&&(0,P.jsx)(`button`,{type:`button`,className:`pd9-switch ${i?`on`:``}`,role:`switch`,"aria-checked":i,onClick:()=>t(!i),title:i?`Disable provider`:`Enable provider`,children:(0,P.jsx)(`span`,{className:`pd9-switch-knob`})}),!i&&(0,P.jsx)(B,{variant:`neutral`,size:`sm`,children:`Disabled`}),n?.signupUrl&&(0,P.jsx)(`a`,{href:n.signupUrl,target:`_blank`,rel:`noopener noreferrer`,className:`pd9-signup-link`,children:`Sign up / Learn more ↗`})]}),(0,P.jsxs)(`div`,{className:`pd9-connection-count`,children:[r,` connection`,r===1?``:`s`]})]})]})]})}function yh({provider:e}){if(!e.riskNotice)return null;let t={none:{bg:`var(--neutral-soft)`,border:`var(--line)`,text:`var(--text-secondary)`},low:{bg:`var(--success-soft)`,border:`var(--success)`,text:`var(--success)`},medium:{bg:`var(--warning-soft)`,border:`var(--warning)`,text:`var(--warning)`},high:{bg:`var(--danger-soft)`,border:`var(--danger)`,text:`var(--danger)`}}[e.riskNotice.level];return(0,P.jsx)(`div`,{className:`provider-risk-banner`,style:{background:t.bg,borderColor:t.border,color:t.text},children:(0,P.jsxs)(`div`,{className:`risk-banner-content`,children:[(0,P.jsx)(Je,{className:`risk-banner-icon`}),(0,P.jsxs)(`div`,{className:`risk-banner-text`,children:[(0,P.jsx)(`div`,{className:`risk-banner-title`,children:e.riskNotice.title}),(0,P.jsx)(`div`,{className:`risk-banner-message`,children:e.riskNotice.message})]}),e.riskNotice.learnMoreUrl&&(0,P.jsx)(`a`,{href:e.riskNotice.learnMoreUrl,target:`_blank`,rel:`noopener noreferrer`,className:`risk-banner-link`,children:`Learn More`})]})})}function bh({provider:e,accounts:t,accountsLoading:n,accountsError:r,onAddAccount:i,onEditAccount:a,onTestAccount:o,onUpdateRoutingMode:s,onReorderAccount:c,onDeleteAccount:l,getTestResult:u,isTestingAccount:d}){let[f,p]=(0,v.useState)(t.some(e=>e.routingMode===`round_robin`)),[m,h]=(0,v.useState)(1);(0,v.useEffect)(()=>{p(t.some(e=>e.routingMode===`round_robin`))},[t]);let g=t.some(e=>d(e.id)),_=async()=>{for(let e of t)o(e.id)},y=()=>{let e=!f;p(e);let n=e?`round_robin`:`sticky`;t.forEach(e=>s(e.id,n))},b=e=>e===`connected`?`active`:e;return(0,P.jsxs)(V,{title:`Connections`,actions:(0,P.jsxs)(`div`,{className:`pd9-conn-controls`,children:[(0,P.jsxs)(`button`,{className:`pd9-test-onebyone`,onClick:_,disabled:g||t.length===0,children:[(0,P.jsx)(ot,{className:`pd9-btn-icon`}),g?`Testing...`:`Test Connection One-by-One`]}),(0,P.jsxs)(`div`,{className:`pd9-rotation-control`,children:[(0,P.jsx)(`span`,{className:`pd9-rotation-label`,children:`Round Robin`}),(0,P.jsx)(`button`,{type:`button`,className:`pd9-switch ${f?`on`:``}`,role:`switch`,"aria-checked":f,onClick:y,disabled:t.length===0,title:`Toggle round-robin rotation across connections`,children:(0,P.jsx)(`span`,{className:`pd9-switch-knob`})})]}),(0,P.jsxs)(`div`,{className:`pd9-sticky-control`,title:`Sticky session count (visual only)`,children:[(0,P.jsx)(`span`,{className:`pd9-rotation-label`,children:`Sticky:`}),(0,P.jsx)(`input`,{type:`number`,min:1,className:`pd9-sticky-input`,value:m,onChange:e=>h(Math.max(1,parseInt(e.target.value,10)||1)),disabled:!f})]})]}),children:[r&&(0,P.jsxs)(`div`,{className:`connections-error`,style:{color:`var(--danger)`,padding:`var(--space-2) 0`},children:[`Error loading accounts: `,r]}),(0,P.jsxs)(`div`,{className:`pd9-conn-list`,children:[t.map((e,n)=>{let r=d(e.id),i=u(e.id),f=e.status!==`disabled`,p=!!c&&t.length>1;return(0,P.jsxs)(`div`,{className:`pd9-conn-row ${f?``:`is-disabled`}`,children:[(0,P.jsxs)(`div`,{className:`pd9-conn-reorder`,children:[(0,P.jsx)(`button`,{className:`pd9-reorder-btn`,"aria-label":`Move up`,disabled:!p||n===0,onClick:()=>c&&c(n,`up`),children:(0,P.jsx)(ph,{})}),(0,P.jsx)(`button`,{className:`pd9-reorder-btn`,"aria-label":`Move down`,disabled:!p||n===t.length-1,onClick:()=>c&&c(n,`down`),children:(0,P.jsx)(mh,{})})]}),(0,P.jsx)(`div`,{className:`pd9-conn-lock`,title:`This connection is managed securely`,children:(0,P.jsx)(hh,{})}),(0,P.jsxs)(`div`,{className:`pd9-conn-main`,children:[(0,P.jsx)(`div`,{className:`pd9-conn-label`,children:e.label}),(0,P.jsxs)(`div`,{className:`pd9-conn-badges`,children:[(0,P.jsx)(`span`,{className:`pd9-status-dot ${e.status===`connected`?`ok`:`bad`}`}),(0,P.jsx)(`span`,{className:`pd9-status-text`,children:b(e.status)}),(0,P.jsx)(`span`,{className:`pd9-conn-chip`,children:Hp[e.authType]?.label||e.authType}),(0,P.jsxs)(`span`,{className:`pd9-conn-index`,children:[`#`,n+1]})]}),i&&(0,P.jsxs)(`div`,{className:`pd9-conn-testresult ${i.status===`success`?`ok`:`bad`}`,children:[i.status===`success`?`✓`:`✕`,` `,_m(i).summary,i.latencyMs?` • ${i.latencyMs}ms`:``]})]}),(0,P.jsxs)(`div`,{className:`pd9-conn-actions`,children:[(0,P.jsx)(`button`,{className:`pd9-icon-btn`,title:`Test connection`,onClick:()=>o(e.id),disabled:r,children:(0,P.jsx)(ot,{className:`pd9-action-icon`})}),(0,P.jsx)(`button`,{className:`pd9-icon-btn`,title:`Edit connection`,onClick:()=>a(e),children:(0,P.jsx)(gh,{})}),(0,P.jsx)(`button`,{className:`pd9-icon-btn danger`,title:`Delete connection`,onClick:()=>{window.confirm(`Are you sure you want to remove account connection "${e.label}"?`)&&l(e.id)},children:(0,P.jsx)(st,{className:`pd9-action-icon`})}),(0,P.jsx)(`button`,{type:`button`,className:`pd9-switch sm ${f?`on`:``}`,role:`switch`,"aria-checked":f,title:f?`Disable connection`:`Enable connection`,onClick:()=>s(e.id,f?`disabled`:`round_robin`),children:(0,P.jsx)(`span`,{className:`pd9-switch-knob`})})]})]},e.id)}),t.length===0&&!n&&(0,P.jsx)(At,{title:`No accounts connected`,description:`Connect an account to start using this provider.`,actionLabel:`Add Account`,onClick:i}),(0,P.jsxs)(`button`,{className:`pd9-add-btn`,onClick:i,children:[(0,P.jsx)(at,{className:`pd9-btn-icon`}),`Add`]})]})]})}function xh({models:e,loading:t,onRefresh:n,isKiro:r}){let i=e.filter(e=>e.enabled),[a,o]=(0,v.useState)(null),[s,c]=(0,v.useState)(!1),[l,u]=(0,v.useState)(``),[d,f]=(0,v.useState)(``),[p,m]=(0,v.useState)(!1),[h,g]=(0,v.useState)(null),[_,y]=(0,v.useState)(null),[b,x]=(0,v.useState)(new Map),S=e=>{navigator.clipboard.writeText(e),o(e),setTimeout(()=>o(null),1500)},C=async e=>{if(!_){y(e);try{let t=await Ee(e);x(n=>new Map(n).set(e,{ok:t.ok,latencyMs:t.latencyMs,error:t.error}))}catch(t){x(n=>new Map(n).set(e,{ok:!1,error:t instanceof Error?t.message:`Test failed`}))}finally{y(null)}}},w=async()=>{if(!(!l.trim()||!d.trim())){m(!0),g(null);try{await we(l.trim(),d.trim()),u(``),f(``),c(!1),n&&n()}catch(e){g(e instanceof Error?e.message:`Failed to add alias`)}finally{m(!1)}}},T=async e=>{if(window.confirm(`Remove model alias "${e}"?`))try{await Te(e),n&&n()}catch(e){console.error(`Failed to delete alias:`,e)}};return(0,P.jsx)(V,{title:`Available Models`,description:t?`Loading models...`:`${i.length} enabled • ${e.length} total`,actions:(0,P.jsx)(`div`,{className:`pd9-models-actions`,children:n&&(0,P.jsx)(`button`,{className:`pd9-test-onebyone`,onClick:n,disabled:t,children:t?`Loading...`:`⟳ Fetch Models`})}),children:t?(0,P.jsx)(`div`,{style:{padding:`var(--space-6)`,textAlign:`center`,color:`var(--text-secondary)`},children:`Loading available models...`}):(0,P.jsxs)(`div`,{className:`pd9-models-grid`,children:[e.map(e=>{let t=b.get(e.id),n=_===e.id,i=t?t.ok?`2px solid var(--success, #22c55e)`:`2px solid var(--danger, #ef4444)`:void 0;return(0,P.jsxs)(`div`,{className:`pd9-model-pill`,title:e.id,style:i?{border:i}:void 0,children:[(0,P.jsx)(`span`,{className:`pd9-model-icon`,children:t?t.ok?`✓`:`✕`:Vp[e.serviceKind]?.icon||`🧠`}),(0,P.jsx)(`span`,{className:`pd9-model-id`,children:e.id}),t?.ok&&t.latencyMs&&(0,P.jsxs)(`span`,{style:{fontSize:`0.65rem`,color:`var(--success, #22c55e)`},children:[t.latencyMs,`ms`]}),t&&!t.ok&&(0,P.jsx)(`span`,{style:{fontSize:`0.65rem`,color:`var(--danger)`},title:t.error,children:`✕`}),r&&(0,P.jsx)(`button`,{className:`pd9-model-copy`,onClick:()=>C(e.id),title:`Test model`,disabled:n,style:n?{animation:`spin 1s linear infinite`}:void 0,children:n?`⏳`:`🧪`}),(0,P.jsx)(`button`,{className:`pd9-model-copy`,onClick:()=>S(e.id),title:`Copy model ID`,children:a===e.id?`✓`:(0,P.jsx)(_h,{})}),r&&(0,P.jsx)(`button`,{className:`pd9-model-copy`,onClick:()=>T(e.id),title:`Remove alias`,style:{color:`var(--danger)`},children:`✕`})]},e.id)}),s?(0,P.jsxs)(`div`,{className:`pd9-add-model-form`,children:[(0,P.jsx)(`input`,{type:`text`,className:`form-input`,placeholder:`Alias (e.g. claude-4)`,value:l,onChange:e=>u(e.target.value),disabled:p}),(0,P.jsx)(`input`,{type:`text`,className:`form-input`,placeholder:`Target (e.g. claude-sonnet-4)`,value:d,onChange:e=>f(e.target.value),disabled:p}),(0,P.jsxs)(`div`,{style:{display:`flex`,gap:`var(--space-2)`},children:[(0,P.jsx)(`button`,{className:`button-primary`,onClick:w,disabled:!l.trim()||!d.trim()||p,children:p?`...`:`Add`}),(0,P.jsx)(`button`,{className:`button-secondary`,onClick:()=>{c(!1),g(null)},children:`Cancel`})]}),h&&(0,P.jsx)(`span`,{style:{color:`var(--danger)`,fontSize:`0.75rem`},children:h})]}):(0,P.jsxs)(`button`,{className:`pd9-add-model`,onClick:()=>c(!0),children:[(0,P.jsx)(at,{className:`pd9-btn-icon`}),`Add Model Alias`]}),e.length===0&&!s&&(0,P.jsx)(`div`,{className:`pd9-models-empty`,children:`No models available yet.`})]})})}function Sh({providerId:e}){let[t,n]=(0,v.useState)(!1),[r,i]=(0,v.useState)(`add`),[a,o]=(0,v.useState)(null),[s,c]=(0,v.useState)(!1);Em(!0);let{provider:l,loading:u,error:d,refresh:f}=nm(e||null),{accounts:p,loading:m,error:h,stats:g,refresh:_}=Xm(e||null),[y,b]=(0,v.useState)([]);(0,v.useEffect)(()=>{b(p)},[p]);let{testAccount:x,getTestResult:S,isTestingAccount:C,clearTestResult:w}=Zm(e||null),{updateRoutingMode:T,refreshAccount:E,deleteAccount:D,isAccountLoading:O,getAccountOperation:ne,operationError:re,clearError:ie}=Qm(e||null),{healthSummary:ae,needsAttentionAccounts:A,hasHealthIssues:j}=eh(p),{healthUpdate:oe,isChecking:se,error:ce,checkHealth:le,getHealthAge:M,hasHealthData:N}=wm(e||null);oe?.healthStatus||l?.healthStatus,oe?.healthMessage||l?.healthMessage;let ue=oe?.quota||l?.quota,[de,fe]=(0,v.useState)(``),[pe,me]=(0,v.useState)(``),[he,ge]=(0,v.useState)(`chat_completions`),[ve,ye]=(0,v.useState)(!1),[be,xe]=(0,v.useState)(null),[Se,Ce]=(0,v.useState)(!1),[we,Te]=(0,v.useState)([]),[Ee,De]=(0,v.useState)(!1);(0,v.useEffect)(()=>{l&&l.tier===`custom`&&(fe(l.displayName||``),me(l.baseUrl||``),ge(l.capabilities?.transportMode===`responses`?`responses`:`chat_completions`))},[l]);let Oe=(0,v.useCallback)(async()=>{if(e)try{De(!0);let t=await _e(e===`kiro-ide`||e===`kiro-free`||e.startsWith(`kiro-`)?`account-kiro`:e);t&&Array.isArray(t.models)?Te(t.models.map(e=>{let t=typeof e==`string`?e:e.id||``;return{id:t,displayName:t.split(`/`).pop()||t,enabled:!0,serviceKind:`chat`,supportsStreaming:!0,supportsTools:!0,supportsVision:t.includes(`vision`)||t.includes(`gpt-4o`),supportsJsonMode:!0}})):Te([])}catch{Te([])}finally{De(!1)}},[e]);(0,v.useEffect)(()=>{e&&Oe()},[e,Oe]),l&&lh(l),ue&&vm(ue);let ke=async e=>{try{await x(e)}catch(t){console.error(`Failed to test account ${e}:`,t)}},Ae=async(e,t)=>{try{await T(e,t),await _()}catch(t){console.error(`Failed to update routing mode for account ${e}:`,t)}},je=async e=>{try{await D(e),await _()}catch(t){console.error(`Failed to delete account ${e}:`,t)}},Me=()=>{i(`add`),o(null),n(!0)},Ne=e=>{i(`edit`),o(e),n(!0)},Pe=()=>{_(),f()},F=(e,t)=>{b(n=>{let r=[...n],i=t===`up`?e-1:e+1;return i<0||i>=r.length?n:([r[e],r[i]]=[r[i],r[e]],r)})},Fe=async t=>{if(t.preventDefault(),e){if(xe(null),Ce(!1),!de.trim()){xe(`Name is required`);return}if(!pe.trim()){xe(`Base URL is required`);return}try{new URL(pe)}catch{xe(`Base URL must be a valid URL`);return}try{ye(!0),await ee(e,{name:de.trim(),baseUrl:pe.trim(),authMode:l?.preferredAuthType||`api_key`,providerApiKeys:l?.providerApiKeys||[],capabilities:{...l?.capabilities,transportMode:he}}),Ce(!0),await f(),setTimeout(()=>Ce(!1),3e3)}catch(e){xe(e instanceof Error?e.message:`Failed to update provider settings`)}finally{ye(!1)}}},Le=async()=>{if(!(!e||!l)&&window.confirm(`Are you sure you want to permanently delete custom provider "${l.displayName}"? This action cannot be undone.`))try{await k(e),window.location.hash=`#/providers`}catch(e){alert(e instanceof Error?e.message:`Failed to delete provider`)}};return u?(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{icon:Ie,title:`Provider Details`,description:`Manage provider connections, models, and configuration`}),(0,P.jsx)(jt,{title:`Loading provider`,description:`Fetching provider details and account information...`,cards:3})]}):d||!l?(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{icon:Ie,title:`Provider Details`,description:`Manage provider connections, models, and configuration`}),(0,P.jsx)(At,{title:`Provider not found`,description:d||`The requested provider could not be found.`,actionLabel:`Back to Providers`,actionHref:`#/providers`})]}):(0,P.jsxs)(`div`,{className:`screen-stack pd9-screen`,children:[(0,P.jsxs)(`div`,{className:`provider-detail-layout pd9-layout`,children:[(0,P.jsx)(vh,{provider:l,onToggleEnabled:async t=>{try{await te(e,t),await f()}catch(e){console.error(`Failed to toggle provider:`,e)}}}),(0,P.jsx)(yh,{provider:l}),(0,P.jsx)(`div`,{className:`provider-detail-grid pd9-grid`,children:(0,P.jsxs)(`div`,{className:`provider-detail-main`,children:[l.tier===`custom`&&(0,P.jsx)(V,{title:`Configuration`,description:`Edit endpoint settings and transport mode for this custom provider`,actions:(0,P.jsx)(`button`,{className:`button-danger`,onClick:Le,style:{fontSize:`var(--font-xs)`,padding:`4px var(--space-3)`},children:`🗑 Delete Provider`}),children:(0,P.jsxs)(`form`,{onSubmit:Fe,className:`custom-provider-config-form`,style:{display:`flex`,flexDirection:`column`,gap:`var(--space-4)`},children:[be&&(0,P.jsxs)(`div`,{className:`modal-error`,style:{color:`var(--danger)`,padding:`var(--space-2) 0`},children:[`⚠️ `,be]}),Se&&(0,P.jsx)(`div`,{className:`modal-success`,style:{color:`var(--success)`,padding:`var(--space-2) 0`,fontWeight:`600`},children:`✓ Configuration updated successfully`}),(0,P.jsxs)(`div`,{className:`form-group`,style:{display:`flex`,flexDirection:`column`,gap:`var(--space-1)`},children:[(0,P.jsx)(`label`,{htmlFor:`custom-name`,style:{fontSize:`var(--font-xs)`,fontWeight:`600`,color:`var(--text-secondary)`},children:`Provider Name`}),(0,P.jsx)(`input`,{id:`custom-name`,type:`text`,className:`search-input`,value:de,onChange:e=>fe(e.target.value),required:!0,style:{padding:`8px 12px`,fontSize:`var(--font-sm)`,borderRadius:`var(--radius-md)`,border:`1px solid var(--line)`,background:`var(--surface-input)`,color:`var(--text-primary)`,width:`100%`}})]}),(0,P.jsxs)(`div`,{className:`form-group`,style:{display:`flex`,flexDirection:`column`,gap:`var(--space-1)`},children:[(0,P.jsx)(`label`,{htmlFor:`custom-url`,style:{fontSize:`var(--font-xs)`,fontWeight:`600`,color:`var(--text-secondary)`},children:`Base URL / Endpoint`}),(0,P.jsx)(`input`,{id:`custom-url`,type:`url`,className:`search-input`,value:pe,onChange:e=>me(e.target.value),placeholder:`https://api.openai.com/v1`,required:!0,style:{padding:`8px 12px`,fontSize:`var(--font-sm)`,borderRadius:`var(--radius-md)`,border:`1px solid var(--line)`,background:`var(--surface-input)`,color:`var(--text-primary)`,width:`100%`}})]}),(0,P.jsxs)(`div`,{className:`form-group`,style:{display:`flex`,flexDirection:`column`,gap:`var(--space-1)`},children:[(0,P.jsx)(`label`,{htmlFor:`custom-transport`,style:{fontSize:`var(--font-xs)`,fontWeight:`600`,color:`var(--text-secondary)`},children:`Transport Mode`}),(0,P.jsxs)(`select`,{id:`custom-transport`,className:`search-input`,value:he,onChange:e=>ge(e.target.value),style:{padding:`8px 12px`,fontSize:`var(--font-sm)`,borderRadius:`var(--radius-md)`,border:`1px solid var(--line)`,background:`var(--surface-input)`,color:`var(--text-primary)`,width:`100%`},children:[(0,P.jsx)(`option`,{value:`responses`,children:`Responses API (/responses)`}),(0,P.jsx)(`option`,{value:`chat_completions`,children:`Chat Completions (/chat/completions)`})]})]}),(0,P.jsx)(`div`,{style:{display:`flex`,justifyContent:`flex-end`,marginTop:`var(--space-2)`},children:(0,P.jsx)(`button`,{type:`submit`,className:`button-primary`,disabled:ve,children:ve?`Saving...`:`Save Configuration`})})]})}),l.tier!==`custom`&&l.configured&&(0,P.jsx)(`div`,{style:{display:`flex`,justifyContent:`flex-end`,marginBottom:`var(--space-3)`},children:(0,P.jsx)(`button`,{className:`button-danger`,onClick:Le,style:{fontSize:`var(--font-xs)`,padding:`4px var(--space-3)`},children:`🗑 Remove Provider`})}),(0,P.jsx)(bh,{provider:l,accounts:y,accountsLoading:m,accountsError:h,onAddAccount:Me,onEditAccount:Ne,onTestAccount:ke,onUpdateRoutingMode:Ae,onReorderAccount:F,onDeleteAccount:je,getTestResult:S,isTestingAccount:C}),(0,P.jsx)(xh,{models:we,loading:Ee,onRefresh:Oe,isKiro:e===`kiro-ide`||e===`kiro-free`||e?.startsWith(`kiro-`)||!1})]})})]}),(0,P.jsx)(sh,{providerId:l.id,providerName:l.displayName,supportedAuthTypes:l.authTypes,accounts:p,isOpen:t,mode:r,editingAccount:a,onClose:()=>n(!1),onAccountsChanged:Pe})]})}function Ch(e){return e.split(/\r?\n|,/).map(e=>e.trim()).filter(Boolean)}function wh({mode:e,initialData:t,onSubmit:n,onCancel:r}){let[i,a]=(0,v.useState)({name:t?.name??``,baseUrl:t?.baseUrl??``,authMode:t?.authMode===`chatgpt_oauth`?`chatgpt_oauth`:`api_key`,chatgptAccountId:t?.chatgptAccountId??``,providerApiKeysText:t?.providerApiKeysText??``,transportMode:t?.transportMode===`chat_completions`?`chat_completions`:`responses`}),[o,s]=(0,v.useState)(null),[c,l]=(0,v.useState)(!1),u=(0,v.useMemo)(()=>e===`edit`?`Leave blank to keep the currently configured keys, or enter new keys to replace them.`:`Optional. Enter one provider API key per line.`,[e]);async function d(t){t.preventDefault(),s(null);let r=i.name.trim(),a=i.baseUrl.trim(),o=i.chatgptAccountId.trim(),c=Ch(i.providerApiKeysText),u=i.providerApiKeysText.trim().length>0;if(!r){s(`Name is required.`);return}if(!a){s(`Base URL is required.`);return}try{new URL(a)}catch{s(`Base URL must be a valid URL.`);return}if(i.authMode===`chatgpt_oauth`&&!o){s(`Account ID is required for ChatGPT OAuth providers.`);return}i.authMode===`api_key`&&e===`create`&&c.length===0&&s(`At least one provider API key is recommended for API key providers.`),l(!0);try{await n({name:r,baseUrl:a,authMode:i.authMode,chatgptAccountId:o||void 0,providerApiKeys:c,replaceKeys:u,transportMode:i.transportMode})}catch(e){s(e instanceof Error?e.message:`Could not save provider.`),l(!1);return}l(!1)}return(0,P.jsxs)(`form`,{className:`provider-form`,onSubmit:d,children:[(0,P.jsx)(`div`,{className:`modal-header`,children:(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`p`,{className:`eyebrow`,children:e===`create`?`Create provider`:`Edit provider`}),(0,P.jsx)(`h2`,{children:e===`create`?`New provider`:`Update provider`})]})}),(0,P.jsx)(`p`,{className:`modal-copy`,children:e===`create`?`Create a runtime provider with routing metadata, auth mode, and upstream credentials.`:`Update provider metadata, account binding, and credentials without exposing existing keys.`}),o?(0,P.jsx)(Ut,{message:o,title:`Could not save provider`,variant:`error`}):null,(0,P.jsxs)(`label`,{className:`form-field`,children:[(0,P.jsx)(`span`,{className:`field-label`,children:`Name`}),(0,P.jsx)(`input`,{className:`search-input`,onChange:e=>a(t=>({...t,name:e.target.value})),required:!0,type:`text`,value:i.name})]}),(0,P.jsxs)(`label`,{className:`form-field`,children:[(0,P.jsx)(`span`,{className:`field-label`,children:`Base URL`}),(0,P.jsx)(`input`,{className:`search-input`,onChange:e=>a(t=>({...t,baseUrl:e.target.value})),placeholder:`https://example.com/v1`,required:!0,type:`url`,value:i.baseUrl})]}),(0,P.jsxs)(`label`,{className:`form-field`,children:[(0,P.jsx)(`span`,{className:`field-label`,children:`Auth mode`}),(0,P.jsxs)(`select`,{className:`search-input`,onChange:e=>a(t=>({...t,authMode:e.target.value===`chatgpt_oauth`?`chatgpt_oauth`:`api_key`})),value:i.authMode,children:[(0,P.jsx)(`option`,{value:`api_key`,children:`API key`}),(0,P.jsx)(`option`,{value:`chatgpt_oauth`,children:`ChatGPT OAuth`})]})]}),i.authMode===`chatgpt_oauth`?(0,P.jsxs)(`label`,{className:`form-field`,children:[(0,P.jsx)(`span`,{className:`field-label`,children:`Account ID`}),(0,P.jsx)(`input`,{className:`search-input`,onChange:e=>a(t=>({...t,chatgptAccountId:e.target.value})),placeholder:`acct_123`,type:`text`,value:i.chatgptAccountId})]}):null,(0,P.jsxs)(`label`,{className:`form-field`,children:[(0,P.jsx)(`span`,{className:`field-label`,children:`Transport mode`}),(0,P.jsxs)(`select`,{className:`search-input`,onChange:e=>a(t=>({...t,transportMode:e.target.value===`chat_completions`?`chat_completions`:`responses`})),value:i.transportMode,children:[(0,P.jsx)(`option`,{value:`responses`,children:`Responses API (/responses)`}),(0,P.jsx)(`option`,{value:`chat_completions`,children:`Chat Completions (/chat/completions)`})]})]}),(0,P.jsxs)(`label`,{className:`form-field`,children:[(0,P.jsx)(`span`,{className:`field-label`,children:e===`create`?`Provider API keys`:`Replace provider API keys`}),(0,P.jsx)(`textarea`,{className:`search-input form-textarea`,onChange:e=>a(t=>({...t,providerApiKeysText:e.target.value})),placeholder:e===`create`?`sk-provider-...`:`Enter new keys only if you want to replace them`,rows:4,value:i.providerApiKeysText}),(0,P.jsx)(`span`,{className:`field-help`,children:u})]}),(0,P.jsxs)(`div`,{className:`modal-actions`,children:[(0,P.jsx)(`button`,{className:`button-link`,disabled:c,onClick:r,type:`button`,children:`Cancel`}),(0,P.jsx)(`button`,{className:`button-link button-primary`,disabled:c,type:`submit`,children:c?e===`create`?`Creating...`:`Saving...`:e===`create`?`Create provider`:`Save changes`})]})]})}var Th={anthropic:{label:`Anthropic Compatible`,description:`Claude-style upstream using the Responses API transport.`,initialData:{name:``,baseUrl:``,authMode:`api_key`,chatgptAccountId:``,providerApiKeysText:``,transportMode:`responses`}},openai:{label:`OpenAI Compatible`,description:`OpenAI-style upstream using the Chat Completions transport.`,initialData:{name:``,baseUrl:``,authMode:`api_key`,chatgptAccountId:``,providerApiKeysText:``,transportMode:`chat_completions`}}};function Eh(){let[e,t]=(0,v.useState)(`openai`),n=(0,v.useMemo)(()=>Th[e].initialData,[e]),r=()=>{window.location.hash=`#/providers`};return(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{icon:Ie,eyebrow:`Providers`,title:`Add Provider`,description:`Connect an OpenAI or Anthropic compatible endpoint`,actions:(0,P.jsx)(`div`,{className:`page-actions`,children:(0,P.jsx)(`button`,{className:`back-button`,onClick:r,type:`button`,children:`← Back to Providers`})})}),(0,P.jsxs)(`div`,{className:`provider-new-layout`,children:[(0,P.jsx)(V,{title:`Provider Type`,description:`Pick the upstream protocol this provider speaks`,children:(0,P.jsx)(`div`,{className:`provider-preset-grid`,children:Object.keys(Th).map(n=>{let r=e===n;return(0,P.jsxs)(`button`,{type:`button`,className:`provider-preset-card${r?` active`:``}`,onClick:()=>t(n),"aria-pressed":r,children:[(0,P.jsx)(`span`,{className:`provider-preset-name`,children:Th[n].label}),(0,P.jsx)(`span`,{className:`provider-preset-desc`,children:Th[n].description})]},n)})})}),(0,P.jsx)(V,{title:`Configuration`,description:`Set the provider name, endpoint, and credentials`,children:(0,P.jsx)(wh,{mode:`create`,initialData:n,onCancel:r,onSubmit:async e=>{await O({name:e.name,baseUrl:e.baseUrl,authMode:e.authMode,chatgptAccountId:e.authMode===`chatgpt_oauth`?e.chatgptAccountId??``:``,providerApiKeys:e.providerApiKeys??[],capabilities:{transportMode:e.transportMode}}),r()}},e)})]})]})}var Dh={enabled:`inherit`,toolOutputEnabled:`inherit`,maxChars:``,maxLines:``,tailLines:``,tailChars:``,detectFormat:`inherit`};function Oh(e){if(!Rt(e))return`Inherit`;let t=[];return typeof e.enabled==`boolean`&&t.push(e.enabled?`enabled`:`disabled`),typeof e.toolOutputEnabled==`boolean`&&t.push(e.toolOutputEnabled?`tool-output:on`:`tool-output:off`),typeof e.maxChars==`number`&&t.push(`chars:${e.maxChars}`),typeof e.maxLines==`number`&&t.push(`lines:${e.maxLines}`),typeof e.tailLines==`number`&&t.push(`tail:${e.tailLines}`),typeof e.tailChars==`number`&&t.push(`tailChars:${e.tailChars}`),typeof e.detectFormat==`string`&&e.detectFormat.trim()&&t.push(`format:${e.detectFormat}`),t.length?t.join(` | `):`Inherit`}function kh(e){return Array.isArray(e.apiKeys)?e.apiKeys.length:0}function Ah(e){return Array.isArray(e.providers)&&e.providers.length?e.providers:Array.isArray(e.providerOptions)?e.providerOptions:[]}function jh(e){return Rt(e)?e:{}}function Mh(e){return typeof e==`boolean`?String(e):`inherit`}function Nh(e){return typeof e==`string`&&e.trim()?e:`inherit`}function Ph(e){return typeof e==`number`&&Number.isFinite(e)?String(e):``}function Fh(e){let t=Rt(e)?e:{};return{enabled:Mh(t.enabled),toolOutputEnabled:Mh(t.toolOutputEnabled),maxChars:Ph(t.maxChars),maxLines:Ph(t.maxLines),tailLines:Ph(t.tailLines),tailChars:Ph(t.tailChars),detectFormat:Nh(t.detectFormat)}}function Ih(e){let t=e.trim();if(!t)return;let n=Number(t);return Number.isInteger(n)&&n>0?n:void 0}function Lh(e){let t=e.trim();if(!t)return;let n=Number(t);return Number.isInteger(n)&&n>=0?n:void 0}function Rh(e){return{...e.enabled===`inherit`?{}:{enabled:e.enabled===`true`},...e.toolOutputEnabled===`inherit`?{}:{toolOutputEnabled:e.toolOutputEnabled===`true`},...Ih(e.maxChars)===void 0?{}:{maxChars:Ih(e.maxChars)},...Ih(e.maxLines)===void 0?{}:{maxLines:Ih(e.maxLines)},...Lh(e.tailLines)===void 0?{}:{tailLines:Lh(e.tailLines)},...Lh(e.tailChars)===void 0?{}:{tailChars:Lh(e.tailChars)},...e.detectFormat===`inherit`?{}:{detectFormat:e.detectFormat}}}function zh(e){return typeof e.enabled==`boolean`||typeof e.toolOutputEnabled==`boolean`||typeof e.maxChars==`number`||typeof e.maxLines==`number`}function Bh(e,t){return typeof t.rtkRequests!=`number`||t.rtkRequests<=0?null:(0,P.jsx)(V,{title:`${e} RTK telemetry`,description:`Observed RTK reductions from recorded requests.`,children:(0,P.jsxs)(`div`,{className:`stat-grid`,children:[(0,P.jsx)(z,{label:`Requests seen`,value:L(t.rtkRequests)}),(0,P.jsx)(z,{label:`Applied requests`,value:L(t.rtkAppliedRequests)}),(0,P.jsx)(z,{label:`Applied rate`,value:zt(t.rtkAppliedRate)}),(0,P.jsx)(z,{label:`Tool outputs reduced`,value:L(t.rtkToolOutputsReduced)}),(0,P.jsx)(z,{label:`Chars before`,value:L(t.rtkCharsBefore)}),(0,P.jsx)(z,{label:`Chars after`,value:L(t.rtkCharsAfter)}),(0,P.jsx)(z,{label:`Chars saved`,value:L(t.rtkCharsSaved)}),(0,P.jsx)(z,{label:`Avg chars saved`,value:L(t.rtkAvgCharsSaved)})]})})}function Vh(){if(window.location.hash.includes(`skills`))return(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{icon:nt,title:`Skills Hub`,description:`Cognitive abilities, tool registries, and agentic workflows`}),(0,P.jsx)(V,{title:`Feature Coming Soon`,description:`Advanced cognitive skills registry`,tone:`info`,children:(0,P.jsxs)(`div`,{style:{padding:`var(--space-6) var(--space-4)`,textAlign:`center`},children:[(0,P.jsx)(`span`,{style:{fontSize:`3rem`},children:`🧠`}),(0,P.jsx)(`h3`,{style:{margin:`var(--space-3) 0 var(--space-2) 0`,fontSize:`var(--font-lg)`},children:`Cognitive & Agentic Skills`}),(0,P.jsx)(`p`,{style:{margin:`0 auto var(--space-4) auto`,color:`var(--text-secondary)`,fontSize:`var(--font-sm)`,maxWidth:`540px`,lineHeight:`1.6`},children:`Skills Hub will enable configuring advanced prompt injections, system instructions, and tool schemas directly inside responses-proxy. Developers can register and deploy cognitive behaviors that are injected dynamically into client sessions based on model compatibility.`}),(0,P.jsxs)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:`var(--space-2)`,justifyContent:`center`},children:[(0,P.jsx)(B,{variant:`accent`,children:`Prompt Injectors`}),(0,P.jsx)(B,{variant:`accent`,children:`Tool Schemas`}),(0,P.jsx)(B,{variant:`accent`,children:`Context Trimming`})]})]})})]});let{state:e,retry:t}=Wt((0,v.useCallback)(async()=>{let[e,t]=await Promise.all([D(),j()]);return{providers:e,usage:t}},[])),[n,r]=(0,v.useState)(null),[i,a]=(0,v.useState)(Dh),[o,s]=(0,v.useState)(!1),[c,l]=(0,v.useState)(null),u=e.status===`success`?Ah(e.data.providers):[],d=e.status===`success`&&Array.isArray(e.data.providers.clientRoutes)?e.data.providers.clientRoutes:[];(0,v.useEffect)(()=>{if(!d.length){n!==null&&r(null);return}n&&d.some(e=>e.key===n)||r((d.find(e=>e.key!==`default`)??d[0]).key)},[d,n]);let f=d.find(e=>e.key===n)??d[0]??null;if((0,v.useEffect)(()=>{if(!f){a(Dh);return}a(Fh(f.rtkPolicy))},[f?.key,f?.rtkPolicy]),e.status===`loading`||e.status===`idle`)return(0,P.jsx)(jt,{title:`Loading RTK overview`,description:`Reading route policies and RTK usage telemetry.`});if(e.status===`error`)return(0,P.jsx)(Ht,{title:`RTK overview unavailable`,description:e.error.message,onRetry:t});let p=Rt(e.data.usage.stats)?e.data.usage.stats:{},m=jh(p.today),h=jh(p.month),g=d.map(e=>({clientRoute:e.key,provider:e.providerName||e.providerId||`Unbound`,modelOverride:e.modelOverride||`Inherited`,apiKeys:kh(e),policySummary:Oh(e.rtkPolicy)})),_=u.map(e=>{let t=Rt(e.capabilities)?e.capabilities:null;return{provider:e.name||e.id,authMode:e.authMode||`Not reported`,defaultPolicy:Oh(t?.rtkPolicy)}}).filter(e=>e.defaultPolicy!==`Inherit`),y=g.filter(e=>e.policySummary!==`Inherit`).length,b=_.length,x=typeof m.rtkRequests==`number`&&m.rtkRequests>0||typeof h.rtkRequests==`number`&&h.rtkRequests>0,S=Rh(i),C=Object.keys(S).length>0&&!zh(S)?`Current backend behavior only persists RTK overrides when at least one of enabled, tool output, max chars, or max lines is set.`:null;async function w(){if(f){s(!0),l(null);try{await se(f.key,S),l({variant:`success`,message:Object.keys(S).length===0?`RTK policy for ${f.key} reset to inherit.`:`RTK policy for ${f.key} saved.`}),t()}catch(e){l({variant:`error`,message:e instanceof Error?e.message:`Could not save RTK policy`})}finally{s(!1)}}}function T(){a(Dh),l(null)}return(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{eyebrow:`RTK`,title:`RTK reduction overview`,description:`Tune route-level RTK policy, review recent savings, and compare live telemetry against your current rules.`,actions:(0,P.jsx)($t,{onClick:t})}),(0,P.jsx)(V,{children:(0,P.jsxs)(`div`,{className:`hero-status`,children:[(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`p`,{className:`eyebrow`,children:`Policy coverage`}),(0,P.jsx)(`h2`,{children:L(y)}),(0,P.jsx)(`p`,{children:y===1?`client route with explicit RTK policy`:`client routes with explicit RTK policy`})]}),(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`p`,{className:`eyebrow`,children:`Provider defaults`}),(0,P.jsx)(`h2`,{children:L(b)}),(0,P.jsx)(`p`,{children:b===1?`provider exposes an RTK default`:`providers expose RTK defaults`})]})]})}),(0,P.jsxs)(`div`,{className:`stat-grid`,children:[(0,P.jsx)(z,{label:`Today RTK requests`,value:L(m.rtkRequests)}),(0,P.jsx)(z,{label:`Today applied rate`,value:zt(m.rtkAppliedRate)}),(0,P.jsx)(z,{label:`Month RTK requests`,value:L(h.rtkRequests)}),(0,P.jsx)(z,{label:`Month chars saved`,value:L(h.rtkCharsSaved)})]}),Bh(`Today`,m),Bh(`This month`,h),x?null:(0,P.jsx)(At,{title:`No RTK telemetry yet`,description:`RTK telemetry will appear here after requests are processed with session logging enabled.`}),(0,P.jsxs)(V,{title:`Edit client route RTK policy`,description:`Save route-level RTK policy changes against the live backend contract used by the proxy.`,children:[c?(0,P.jsx)(Ut,{variant:c.variant,message:c.message,title:c.variant===`error`?`Save failed`:`Saved`}):null,C?(0,P.jsx)(Ut,{variant:`error`,title:`Persistence note`,message:C}):null,f?(0,P.jsxs)(`div`,{className:`surface-card-body`,children:[(0,P.jsxs)(`div`,{className:`client-form-grid rtk-form-grid`,children:[(0,P.jsxs)(`label`,{className:`form-field`,children:[(0,P.jsx)(`span`,{className:`field-label`,children:`Client route`}),(0,P.jsx)(`select`,{className:`search-input`,value:f.key,onChange:e=>{r(e.target.value),l(null)},children:d.map(e=>(0,P.jsx)(`option`,{value:e.key,children:e.key},e.key))})]}),(0,P.jsxs)(`label`,{className:`form-field`,children:[(0,P.jsx)(`span`,{className:`field-label`,children:`Enabled`}),(0,P.jsxs)(`select`,{className:`search-input`,value:i.enabled,onChange:e=>a(t=>({...t,enabled:e.target.value})),children:[(0,P.jsx)(`option`,{value:`inherit`,children:`Inherit`}),(0,P.jsx)(`option`,{value:`true`,children:`Enabled`}),(0,P.jsx)(`option`,{value:`false`,children:`Disabled`})]})]}),(0,P.jsxs)(`label`,{className:`form-field`,children:[(0,P.jsx)(`span`,{className:`field-label`,children:`Tool output reduction`}),(0,P.jsxs)(`select`,{className:`search-input`,value:i.toolOutputEnabled,onChange:e=>a(t=>({...t,toolOutputEnabled:e.target.value})),children:[(0,P.jsx)(`option`,{value:`inherit`,children:`Inherit`}),(0,P.jsx)(`option`,{value:`true`,children:`Enabled`}),(0,P.jsx)(`option`,{value:`false`,children:`Disabled`})]})]}),(0,P.jsxs)(`label`,{className:`form-field`,children:[(0,P.jsx)(`span`,{className:`field-label`,children:`Max chars`}),(0,P.jsx)(`input`,{className:`search-input`,inputMode:`numeric`,placeholder:`e.g. 2800`,value:i.maxChars,onChange:e=>a(t=>({...t,maxChars:e.target.value}))})]}),(0,P.jsxs)(`label`,{className:`form-field`,children:[(0,P.jsx)(`span`,{className:`field-label`,children:`Max lines`}),(0,P.jsx)(`input`,{className:`search-input`,inputMode:`numeric`,placeholder:`e.g. 90`,value:i.maxLines,onChange:e=>a(t=>({...t,maxLines:e.target.value}))})]}),(0,P.jsxs)(`label`,{className:`form-field`,children:[(0,P.jsx)(`span`,{className:`field-label`,children:`Tail lines`}),(0,P.jsx)(`input`,{className:`search-input`,inputMode:`numeric`,placeholder:`e.g. 12`,value:i.tailLines,onChange:e=>a(t=>({...t,tailLines:e.target.value}))})]}),(0,P.jsxs)(`label`,{className:`form-field`,children:[(0,P.jsx)(`span`,{className:`field-label`,children:`Tail chars`}),(0,P.jsx)(`input`,{className:`search-input`,inputMode:`numeric`,placeholder:`e.g. 400`,value:i.tailChars,onChange:e=>a(t=>({...t,tailChars:e.target.value}))})]}),(0,P.jsxs)(`label`,{className:`form-field`,children:[(0,P.jsx)(`span`,{className:`field-label`,children:`Detect format`}),(0,P.jsxs)(`select`,{className:`search-input`,value:i.detectFormat,onChange:e=>a(t=>({...t,detectFormat:e.target.value})),children:[(0,P.jsx)(`option`,{value:`inherit`,children:`Inherit`}),(0,P.jsx)(`option`,{value:`auto`,children:`Auto`}),(0,P.jsx)(`option`,{value:`plain`,children:`Plain`}),(0,P.jsx)(`option`,{value:`json`,children:`JSON`}),(0,P.jsx)(`option`,{value:`stack`,children:`Stack`}),(0,P.jsx)(`option`,{value:`command`,children:`Command`})]})]})]}),(0,P.jsxs)(`div`,{className:`rtk-form-actions`,children:[(0,P.jsx)(`button`,{className:`button-link`,disabled:o,onClick:T,type:`button`,children:`Reset form`}),(0,P.jsx)(`button`,{className:`button-link`,disabled:o,onClick:()=>a(Fh(f.rtkPolicy)),type:`button`,children:`Load saved policy`}),(0,P.jsx)(`button`,{className:`button-primary`,disabled:o,onClick:w,type:`button`,children:o?`Saving...`:`Save RTK policy`})]})]}):(0,P.jsx)(At,{title:`No client routes available`,description:`Create a client route first, then return here to adjust RTK policy.`})]}),(0,P.jsx)(V,{title:`Client route RTK policy`,description:`Route-level RTK settings currently configured in the backend. Inherited means the route follows provider defaults.`,children:(0,P.jsx)(Vt,{columns:[{key:`clientRoute`,label:`Client route`},{key:`provider`,label:`Provider`},{key:`modelOverride`,label:`Model override`},{key:`apiKeys`,label:`API keys`,align:`right`,render:e=>L(e)},{key:`policySummary`,label:`RTK policy`}],rows:g,emptyTitle:`No client routes reported`,emptyDescription:`Route policy details will appear after providers are loaded.`})}),(0,P.jsx)(V,{title:`Provider RTK defaults`,description:`Provider-level defaults used when a client route inherits RTK behavior.`,children:(0,P.jsx)(Vt,{columns:[{key:`provider`,label:`Provider`},{key:`authMode`,label:`Auth`},{key:`defaultPolicy`,label:`Default RTK policy`}],rows:_,emptyTitle:`No provider RTK defaults reported`,emptyDescription:`Providers without explicit RTK defaults will continue to inherit backend behavior.`})}),(0,P.jsx)(V,{title:`Policy notes`,description:`Helpful context for choosing conservative defaults before widening route-level policy.`,children:(0,P.jsxs)(`dl`,{className:`detail-list`,children:[(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`dt`,{children:`Selected route`}),(0,P.jsx)(`dd`,{children:f?f.key:`Not reported`})]}),(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`dt`,{children:`Saved summary`}),(0,P.jsx)(`dd`,{children:f?Oh(f.rtkPolicy):`Not reported`})]}),(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`dt`,{children:`Provider defaults`}),(0,P.jsx)(`dd`,{children:b>0?`${b} provider default${b===1?``:`s`} detected`:`No explicit provider defaults reported`})]}),(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`dt`,{children:`Telemetry fallback`}),(0,P.jsx)(`dd`,{children:x?`Telemetry is flowing and can be compared against policy summaries above.`:`Telemetry is still sparse, so compare recent requests after saving a policy update.`})]}),(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`dt`,{children:`Top-level request reduction`}),(0,P.jsx)(`dd`,{children:typeof h.rtkAppliedRate==`number`?`${zt(h.rtkAppliedRate)} applied this month`:`Not reported yet`})]}),(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`dt`,{children:`Tool-output trimming`}),(0,P.jsx)(`dd`,{children:R(h.rtkToolOutputsReduced)})]})]})})]})}var Hh=[{value:`today`,label:`Today`},{value:`7d`,label:`7D`},{value:`30d`,label:`30D`}],Uh=e=>new Intl.NumberFormat().format(Number(e)||0),Wh=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e||0);function Gh(){let[e,t]=(0,v.useState)(`overview`),[n,r]=(0,v.useState)(`today`),[i,a]=(0,v.useState)(`tokens`),{state:o,retry:s}=Wt((0,v.useCallback)(()=>j(),[])),[c,l]=(0,v.useState)({status:`idle`}),u=(0,v.useCallback)(async()=>{l(e=>({status:`loading`,data:e.data}));try{l({status:`success`,data:await oe()})}catch{l({status:`success`,data:{ok:!0,providers:[]}})}},[]);(0,v.useEffect)(()=>{let e=!0,t=async()=>{l(e=>({status:`loading`,data:e.data}));try{let t=await oe();e&&l({status:`success`,data:t})}catch{e&&l({status:`success`,data:{ok:!0,providers:[]}})}};t();let n=setInterval(()=>void t(),3e4);return()=>{e=!1,clearInterval(n)}},[]);let d=o.status===`success`&&Rt(o.data.stats)?o.data.stats:{},f=Rt(d.today)?d.today:{},p=Rt(d.month)?d.month:{},m=Array.isArray(d.daily)?d.daily:[],h=Array.isArray(d.byProvider)?d.byProvider:[],g=Array.isArray(d.byModel)?d.byModel:[],_=Array.isArray(d.byClientRoute)?d.byClientRoute:[],y=Array.isArray(c.data?.providers)?c.data.providers:[],b=n===`30d`?p:f,x=Number(b.totalInputTokens)||0,S=Number(b.totalCachedTokens)||0,C=Number(b.requests)||0,w=(0,v.useMemo)(()=>m.map(e=>({timestamp:e.date||new Date().toISOString(),value:i===`tokens`?Number(e.totalInputTokens||0)+Number(e.totalCachedTokens||0):Number(e.requests||0)})),[m,i]);return o.status===`loading`||o.status===`idle`?(0,P.jsx)(jt,{title:`Loading usage`,description:`Reading usage data...`}):o.status===`error`?(0,P.jsx)(Ht,{title:`Usage unavailable`,description:o.error.message,onRetry:s}):(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{title:`Usage & Analytics`,description:`Track requests, tokens, cost, and provider utilization.`,actions:(0,P.jsx)($t,{onClick:s})}),(0,P.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:`var(--space-4)`,flexWrap:`wrap`},children:[(0,P.jsx)(qh,{options:[{value:`overview`,label:`Overview`},{value:`details`,label:`Details`}],value:e,onChange:e=>t(e)}),e===`overview`&&(0,P.jsx)(qh,{options:Hh,value:n,onChange:e=>r(e),size:`sm`})]}),e===`overview`&&(0,P.jsxs)(P.Fragment,{children:[(0,P.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`repeat(auto-fit, minmax(180px, 1fr))`,gap:`var(--space-4)`},children:[(0,P.jsx)(Kh,{label:`Total Requests`,value:Uh(C)}),(0,P.jsx)(Kh,{label:`Total Input Tokens`,value:Wh(x),color:`var(--accent)`}),(0,P.jsx)(Kh,{label:`Cached Tokens`,value:Wh(S),color:`var(--success)`}),(0,P.jsx)(Kh,{label:`Cache Hit Rate`,value:zt(b.hitRate),color:`var(--warning)`,subtitle:`Prompt cache efficiency`})]}),w.length>0&&(0,P.jsxs)(V,{children:[(0,P.jsxs)(`div`,{style:{display:`flex`,justifyContent:`space-between`,alignItems:`center`,marginBottom:`var(--space-3)`},children:[(0,P.jsx)(`h3`,{style:{margin:0,fontSize:`var(--text-sm)`,fontWeight:600},children:`Usage Over Time`}),(0,P.jsx)(qh,{options:[{value:`tokens`,label:`Tokens`},{value:`cost`,label:`Requests`}],value:i,onChange:e=>a(e),size:`sm`})]}),(0,P.jsx)(Pp,{data:w,height:200,color:i===`tokens`?`var(--accent)`:`var(--warning)`,fill:!0,valueFormatter:e=>i===`tokens`?Wh(e):Uh(e)})]}),typeof b.rtkRequests==`number`&&b.rtkRequests>0&&(0,P.jsx)(V,{title:`RTK Token Saver`,description:`Tool output compression statistics`,children:(0,P.jsxs)(`div`,{className:`stat-grid`,children:[(0,P.jsx)(z,{label:`RTK Requests`,value:Uh(b.rtkRequests)}),(0,P.jsx)(z,{label:`Applied`,value:Uh(b.rtkAppliedRequests)}),(0,P.jsx)(z,{label:`Apply Rate`,value:zt(b.rtkAppliedRate)}),(0,P.jsx)(z,{label:`Chars Saved`,value:Uh(b.rtkCharsSaved)})]})}),(0,P.jsx)(V,{title:`By Provider`,description:`Request distribution across providers`,children:(0,P.jsx)(Vt,{columns:[{key:`key`,label:`Provider`},{key:`requests`,label:`Requests`,align:`right`,render:e=>Uh(e)},{key:`totalCachedTokens`,label:`Cached Tokens`,align:`right`,render:e=>Uh(e)},{key:`hitRate`,label:`Hit Rate`,align:`right`,render:e=>zt(e)},{key:`rtkCharsSaved`,label:`RTK Saved`,align:`right`,render:e=>Uh(e)}],rows:h,emptyTitle:`No provider data`,emptyDescription:`Usage will appear after requests are processed.`})}),g.length>0&&(0,P.jsx)(V,{title:`By Model`,description:`Token usage per model`,children:(0,P.jsx)(Vt,{columns:[{key:`key`,label:`Model`},{key:`requests`,label:`Requests`,align:`right`,render:e=>Uh(e)},{key:`totalCachedTokens`,label:`Cached`,align:`right`,render:e=>Uh(e)},{key:`avgCacheSavedPercent`,label:`Avg Saved`,align:`right`,render:e=>zt(e)}],rows:g,emptyTitle:`No model data`,emptyDescription:``})}),(0,P.jsx)(V,{title:`By Client Route`,description:`Usage per API key route`,children:(0,P.jsx)(Vt,{columns:[{key:`key`,label:`Route`},{key:`requests`,label:`Requests`,align:`right`,render:e=>Uh(e)},{key:`hitRate`,label:`Hit Rate`,align:`right`,render:e=>zt(e)},{key:`rtkCharsSaved`,label:`RTK Saved`,align:`right`,render:e=>Uh(e)}],rows:_,emptyTitle:`No route data`,emptyDescription:`Client route usage will appear when route-specific logs exist.`})})]}),e===`details`&&(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(V,{title:`Live Provider Status`,description:`Real-time provider availability. Auto-refreshes every 30s.`,actions:(0,P.jsx)($t,{onClick:u,label:`Refresh`}),children:y.length===0?(0,P.jsx)(`p`,{style:{color:`var(--text-muted)`,fontSize:`var(--text-sm)`,textAlign:`center`,padding:`var(--space-4)`},children:`No live data available.`}):(0,P.jsx)(`div`,{style:{display:`grid`,gap:`var(--space-2)`},children:y.map(e=>{let t=Rt(e.usage)?e.usage:{},n=e.ok!==!1&&t.allowed!==!1;return(0,P.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`var(--space-3)`,padding:`var(--space-3) var(--space-4)`,background:`var(--surface-muted)`,borderRadius:`var(--radius-sm)`,border:`1px solid var(--line)`},children:[(0,P.jsx)(`span`,{style:{width:8,height:8,borderRadius:`50%`,flexShrink:0,background:n?`var(--success)`:`var(--danger)`,boxShadow:`0 0 0 3px ${n?`var(--success-soft)`:`var(--danger-soft)`}`}}),(0,P.jsx)(`span`,{style:{flex:1,fontWeight:600,fontSize:`var(--text-sm)`},children:e.providerName||e.providerId}),typeof t.remaining==`number`&&typeof t.limit==`number`&&(0,P.jsxs)(`span`,{style:{fontSize:`var(--text-xs)`,color:`var(--text-secondary)`},children:[Uh(t.remaining),` / `,Uh(t.limit)]}),(0,P.jsx)(B,{status:n?`success`:`danger`,children:n?`Available`:e.error?`Error`:`Exhausted`})]},e.providerId||e.providerName)})})}),(0,P.jsx)(V,{title:`Cache Performance`,description:`Detailed cache statistics`,children:(0,P.jsxs)(`div`,{className:`stat-grid`,children:[(0,P.jsx)(z,{label:`Today Requests`,value:Uh(f.requests)}),(0,P.jsx)(z,{label:`Today Hit Rate`,value:zt(f.hitRate)}),(0,P.jsx)(z,{label:`Today Cached`,value:Uh(f.totalCachedTokens)}),(0,P.jsx)(z,{label:`Today Avg Saved`,value:zt(f.avgCacheSavedPercent)}),(0,P.jsx)(z,{label:`Month Requests`,value:Uh(p.requests)}),(0,P.jsx)(z,{label:`Month Hit Rate`,value:zt(p.hitRate)}),(0,P.jsx)(z,{label:`Month Cached`,value:Uh(p.totalCachedTokens)}),(0,P.jsx)(z,{label:`Month Avg Saved`,value:zt(p.avgCacheSavedPercent)})]})})]})]})}function Kh({label:e,value:t,color:n,subtitle:r}){return(0,P.jsxs)(`section`,{className:`surface-card`,style:{padding:`var(--space-4) var(--space-5)`},children:[(0,P.jsx)(`span`,{style:{fontSize:`var(--text-xs)`,fontWeight:600,textTransform:`uppercase`,letterSpacing:`0.04em`,color:`var(--text-muted)`},children:e}),(0,P.jsx)(`span`,{style:{display:`block`,marginTop:4,fontSize:`var(--text-2xl)`,fontWeight:700,letterSpacing:`-0.04em`,color:n||`var(--text-primary)`,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:t}),r&&(0,P.jsx)(`span`,{style:{fontSize:`0.65rem`,color:`var(--text-muted)`},children:r})]})}function qh({options:e,value:t,onChange:n,size:r}){return(0,P.jsx)(`div`,{style:{display:`inline-flex`,borderRadius:`var(--radius-pill)`,overflow:`hidden`,border:`1px solid var(--line)`,background:`var(--surface-muted)`},children:e.map(e=>(0,P.jsx)(`button`,{onClick:()=>n(e.value),style:{padding:r===`sm`?`var(--space-1) var(--space-3)`:`var(--space-2) var(--space-4)`,fontSize:`var(--text-xs)`,fontWeight:600,cursor:`pointer`,background:t===e.value?`var(--accent)`:`transparent`,color:t===e.value?`#fff`:`var(--text-secondary)`,border:`none`,minHeight:r===`sm`?28:34,transition:`background var(--animation-fast), color var(--animation-fast)`},children:e.label},e.value))})}var Jh=6e4;function Yh(){let[e,t]=(0,v.useState)([]),[n,r]=(0,v.useState)([]),[i,a]=(0,v.useState)(!0),[o,s]=(0,v.useState)(!1),[c,l]=(0,v.useState)(!0),[u,d]=(0,v.useState)(60),[f,p]=(0,v.useState)(null),m=(0,v.useRef)(null),h=(0,v.useRef)(null),g=(0,v.useCallback)(async()=>{try{s(!0);let[e,n]=await Promise.all([D(),oe()]);t(e.providerOptions||e.providers||[]),r(n.providers||[]),p(new Date),d(60)}catch(e){console.error(`Failed to fetch quota data:`,e)}finally{a(!1),s(!1)}},[]);(0,v.useEffect)(()=>{g()},[g]),(0,v.useEffect)(()=>{if(!c){m.current&&clearInterval(m.current),h.current&&clearInterval(h.current);return}return m.current=setInterval(g,Jh),h.current=setInterval(()=>{d(e=>e<=1?60:e-1)},1e3),()=>{m.current&&clearInterval(m.current),h.current&&clearInterval(h.current)}},[c,g]);let _=(0,v.useMemo)(()=>{let t=new Map;for(let e of n)e.providerId&&t.set(e.providerId,e);return e.map(e=>{let n=t.get(e.id),r=n&&Rt(n.usage)?n.usage:null;return{id:e.id,name:e.name,live:n,ok:n?.ok!==!1&&r?.allowed!==!1,allowed:r?.allowed,remaining:typeof r?.remaining==`number`?r.remaining:void 0,limit:typeof r?.limit==`number`?r.limit:void 0,used:typeof r?.used==`number`?r.used:void 0,error:n?.error,hasQuota:n!==void 0}})},[e,n]),y=(0,v.useMemo)(()=>_.filter(e=>e.hasQuota),[_]);return i?(0,P.jsx)(jt,{title:`Loading quotas`,description:`Fetching provider quota status...`,cards:4}):(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{title:`Quota Tracker`,description:`Real-time provider quota limits and usage status.`,actions:(0,P.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`var(--space-2)`},children:[(0,P.jsxs)(`button`,{onClick:()=>l(e=>!e),className:`button-link`,style:{minHeight:36,gap:`var(--space-2)`},title:c?`Disable auto-refresh`:`Enable auto-refresh`,children:[(0,P.jsx)(`span`,{style:{color:c?`var(--accent)`:`var(--text-muted)`},children:c?`⟳`:`⏸`}),(0,P.jsx)(`span`,{children:`Auto`}),c&&(0,P.jsxs)(`span`,{style:{fontSize:`var(--text-xs)`,color:`var(--text-muted)`,fontVariantNumeric:`tabular-nums`},children:[`(`,u,`s)`]})]}),(0,P.jsx)($t,{onClick:g,isRefreshing:o})]})}),f&&(0,P.jsxs)(`p`,{style:{fontSize:`var(--text-xs)`,color:`var(--text-muted)`,margin:0},children:[`Last updated: `,f.toLocaleTimeString()]}),y.length===0?(0,P.jsx)(V,{children:(0,P.jsxs)(`div`,{style:{textAlign:`center`,padding:`var(--space-8)`},children:[(0,P.jsx)(`p`,{style:{fontSize:`var(--text-base)`,fontWeight:600,margin:`0 0 var(--space-2)`},children:`No Quota Data Available`}),(0,P.jsx)(`p`,{style:{fontSize:`var(--text-sm)`,color:`var(--text-secondary)`,margin:0,maxWidth:400,marginInline:`auto`},children:`Connect providers with quota tracking (OAuth subscriptions like Claude Code, Codex) to see quota limits and usage here.`})]})}):(0,P.jsx)(`div`,{style:{display:`grid`,gridTemplateColumns:`repeat(auto-fit, minmax(320px, 1fr))`,gap:`var(--space-4)`},children:y.map(e=>(0,P.jsx)(Xh,{provider:e,onRefresh:g},e.id))})]})}function Xh({provider:e,onRefresh:t}){let n=e.limit&&e.limit>0?Math.round((e.used||0)/e.limit*100):null,r=n===null?null:100-n;return(0,P.jsxs)(`section`,{className:`surface-card`,style:{padding:0,overflow:`hidden`},children:[(0,P.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:`var(--space-3)`,padding:`var(--space-3) var(--space-4)`,borderBottom:`1px solid var(--line)`},children:[(0,P.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`var(--space-3)`,minWidth:0},children:[(0,P.jsx)(`div`,{style:{width:32,height:32,borderRadius:8,background:`var(--accent-soft)`,display:`flex`,alignItems:`center`,justifyContent:`center`,flexShrink:0},children:(0,P.jsx)(`span`,{style:{fontSize:14,fontWeight:700,color:`var(--accent)`},children:e.name.charAt(0).toUpperCase()})}),(0,P.jsx)(`div`,{style:{minWidth:0},children:(0,P.jsx)(`h3`,{style:{margin:0,fontSize:`var(--text-sm)`,fontWeight:600,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:e.name})})]}),(0,P.jsx)(B,{status:e.ok?`success`:`danger`,children:e.ok?`Active`:e.error?`Error`:`Exhausted`})]}),(0,P.jsx)(`div`,{style:{padding:`var(--space-3) var(--space-4)`},children:e.error?(0,P.jsx)(`p`,{style:{margin:0,fontSize:`var(--text-xs)`,color:`var(--danger)`},children:e.error}):e.limit===void 0?(0,P.jsx)(`p`,{style:{margin:0,fontSize:`var(--text-xs)`,color:`var(--text-muted)`,textAlign:`center`,padding:`var(--space-2)`},children:e.ok?`Connected — no quota limits reported`:`Unable to fetch quota`}):(0,P.jsxs)(`div`,{style:{display:`grid`,gap:`var(--space-3)`},children:[(0,P.jsxs)(`div`,{children:[(0,P.jsxs)(`div`,{style:{display:`flex`,justifyContent:`space-between`,marginBottom:4},children:[(0,P.jsxs)(`span`,{style:{fontSize:`var(--text-xs)`,color:`var(--text-muted)`},children:[L(e.remaining),` remaining`]}),(0,P.jsx)(`span`,{style:{fontSize:`var(--text-xs)`,fontWeight:600},children:r===null?`—`:`${r}%`})]}),(0,P.jsx)(`div`,{style:{height:8,borderRadius:`var(--radius-pill)`,background:`var(--neutral-soft)`,overflow:`hidden`},children:(0,P.jsx)(`div`,{style:{height:`100%`,width:`${r??0}%`,borderRadius:`var(--radius-pill)`,background:!e.ok||r!==null&&r<=10?`var(--danger)`:r!==null&&r<=30?`var(--warning)`:`var(--success)`,transition:`width var(--animation-slow) var(--animation-easing)`}})})]}),(0,P.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`1fr 1fr 1fr`,gap:`var(--space-2)`},children:[(0,P.jsxs)(`div`,{style:{textAlign:`center`},children:[(0,P.jsx)(`span`,{style:{display:`block`,fontSize:`var(--text-xs)`,color:`var(--text-muted)`},children:`Used`}),(0,P.jsx)(`span`,{style:{display:`block`,fontSize:`var(--text-sm)`,fontWeight:600},children:L(e.used)})]}),(0,P.jsxs)(`div`,{style:{textAlign:`center`},children:[(0,P.jsx)(`span`,{style:{display:`block`,fontSize:`var(--text-xs)`,color:`var(--text-muted)`},children:`Remaining`}),(0,P.jsx)(`span`,{style:{display:`block`,fontSize:`var(--text-sm)`,fontWeight:600,color:`var(--success)`},children:L(e.remaining)})]}),(0,P.jsxs)(`div`,{style:{textAlign:`center`},children:[(0,P.jsx)(`span`,{style:{display:`block`,fontSize:`var(--text-xs)`,color:`var(--text-muted)`},children:`Limit`}),(0,P.jsx)(`span`,{style:{display:`block`,fontSize:`var(--text-sm)`,fontWeight:600},children:L(e.limit)})]})]})]})})]})}var Zh=[{id:`antigravity`,name:`Antigravity (Google)`,color:`#4285F4`,description:`Google Antigravity IDE — intercepts daily-cloudcode-pa.googleapis.com`,mitmDomain:`daily-cloudcode-pa.googleapis.com`,models:[{id:`gemini-3.5-flash-low`,name:`Gemini 3.5 Flash (Medium)`},{id:`gemini-3-flash-agent`,name:`Gemini 3.5 Flash (High)`},{id:`claude-sonnet-4-6`,name:`Claude Sonnet 4.6 (Thinking)`},{id:`claude-opus-4-6-thinking`,name:`Claude Opus 4.6 (Thinking)`}]},{id:`copilot`,name:`GitHub Copilot`,color:`#1F6FEB`,description:`GitHub Copilot IDE — intercepts api.individual.githubcopilot.com`,mitmDomain:`api.individual.githubcopilot.com`,models:[{id:`gpt-4o`,name:`GPT-4o`},{id:`gpt-4.1`,name:`GPT-4.1`},{id:`claude-haiku-4.5`,name:`Claude Haiku 4.5`}]},{id:`kiro`,name:`Kiro IDE`,color:`#FF6B00`,description:`Kiro IDE — intercepts q.us-east-1.amazonaws.com`,mitmDomain:`q.us-east-1.amazonaws.com`,models:[{id:`claude-sonnet-4.5`,name:`Claude Sonnet 4.5`},{id:`claude-sonnet-4`,name:`Claude Sonnet 4`},{id:`deepseek-3.2`,name:`DeepSeek 3.2`},{id:`minimax-m2.1`,name:`MiniMax M2.1`}]}];function Qh(){let[e,t]=(0,v.useState)(null),[n,r]=(0,v.useState)(!0),[i,a]=(0,v.useState)(null),o=(0,v.useCallback)(async()=>{try{let e=await fetch(`/api/cli-tools/mitm-status`);e.ok?t(await e.json()):t({running:!1,certExists:!1,certTrusted:!1,dnsStatus:{}})}catch{t({running:!1,certExists:!1,certTrusted:!1,dnsStatus:{}})}finally{r(!1)}},[]);if((0,v.useEffect)(()=>{o()},[o]),n)return(0,P.jsx)(jt,{title:`Loading MITM status`,description:`Checking MITM server and certificates...`,cards:3});let s=e?.running||!1;return(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{title:`MITM Proxy`,description:`Intercept IDE HTTPS traffic to route through your providers.`}),(0,P.jsxs)(`div`,{style:{display:`flex`,alignItems:`flex-start`,gap:`var(--space-3)`,padding:`var(--space-3) var(--space-4)`,borderRadius:`var(--radius-md)`,background:`var(--warning-soft)`,border:`1px solid color-mix(in srgb, var(--warning) 30%, transparent)`},children:[(0,P.jsx)(`span`,{style:{color:`var(--warning)`,fontSize:`16px`,marginTop:2,flexShrink:0},children:`⚠️`}),(0,P.jsx)(`p`,{style:{margin:0,fontSize:`var(--text-xs)`,color:`var(--danger)`,lineHeight:1.5},children:`MITM intercepts HTTPS traffic of IDE tools (Antigravity, GitHub Copilot, Kiro) via local CA to redirect requests to your providers. May violate ToS → account ban. Use at your own risk.`})]}),(0,P.jsx)($h,{status:e,isRunning:s,onRefresh:o}),(0,P.jsx)(`div`,{style:{display:`grid`,gap:`var(--space-3)`},children:Zh.map(t=>(0,P.jsx)(eg,{tool:t,isExpanded:i===t.id,onToggle:()=>a(i===t.id?null:t.id),serverRunning:s,dnsActive:e?.dnsStatus?.[t.id]||!1},t.id))})]})}function $h({status:e,isRunning:t,onRefresh:n}){let[r,i]=(0,v.useState)(!1),[a,o]=(0,v.useState)(null);return(0,P.jsx)(`section`,{className:`surface-card surface-card-info`,style:{padding:`var(--space-4) var(--space-5)`},children:(0,P.jsxs)(`div`,{style:{display:`grid`,gap:`var(--space-4)`},children:[(0,P.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,flexWrap:`wrap`,gap:`var(--space-3)`},children:[(0,P.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`var(--space-3)`},children:[(0,P.jsx)(`span`,{style:{fontSize:20,color:`var(--accent)`},children:`🔒`}),(0,P.jsx)(`span`,{style:{fontWeight:600,fontSize:`var(--text-sm)`},children:`MITM Server`}),(0,P.jsx)(B,{status:t?`success`:`neutral`,children:t?`Running`:`Stopped`})]}),(0,P.jsxs)(`div`,{style:{display:`flex`,gap:`var(--space-3)`,fontSize:`var(--text-xs)`,color:`var(--text-muted)`},children:[(0,P.jsx)(tg,{label:`Cert`,ok:e?.certExists}),(0,P.jsx)(tg,{label:`Trusted`,ok:e?.certTrusted}),(0,P.jsx)(tg,{label:`Server`,ok:t})]})]}),(0,P.jsxs)(`div`,{style:{padding:`var(--space-3)`,background:`var(--surface-muted)`,borderRadius:`var(--radius-sm)`,border:`1px solid var(--line)`},children:[(0,P.jsxs)(`p`,{style:{margin:`0 0 4px`,fontSize:`0.68rem`,color:`var(--text-secondary)`},children:[(0,P.jsx)(`strong`,{style:{color:`var(--text-primary)`},children:`Purpose:`}),` Use Antigravity IDE & GitHub Copilot with ANY provider/model from the proxy`]}),(0,P.jsxs)(`p`,{style:{margin:0,fontSize:`0.68rem`,color:`var(--text-secondary)`},children:[(0,P.jsx)(`strong`,{style:{color:`var(--text-primary)`},children:`How it works:`}),` IDE request → DNS redirect to localhost:443 → MITM intercepts → Proxy routes → response to IDE`]})]}),(0,P.jsxs)(`div`,{style:{display:`flex`,gap:`var(--space-2)`,flexWrap:`wrap`,alignItems:`center`},children:[t?(0,P.jsx)(`button`,{className:`button-danger`,onClick:async()=>{i(!0),o(null);try{let e=await fetch(`/api/cli-tools/mitm-stop`,{method:`POST`});e.ok?await n():o((await e.json().catch(()=>({}))).error||`Failed to stop MITM server`)}catch(e){o(e.message||`Network error`)}finally{i(!1)}},disabled:r,style:{minHeight:36},children:r?`Stopping...`:`Stop Server`}):(0,P.jsx)(`button`,{className:`button-primary`,onClick:async()=>{i(!0),o(null);try{let e=await fetch(`/api/cli-tools/mitm-start`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({})});e.ok?await n():o((await e.json().catch(()=>({}))).error||`Failed to start MITM server`)}catch(e){o(e.message||`Network error`)}finally{i(!1)}},disabled:r,style:{minHeight:36},children:r?`Starting...`:`Start Server`}),(0,P.jsx)(`button`,{className:`button-link`,onClick:n,style:{minHeight:36},children:`Refresh Status`}),t&&(0,P.jsx)(`span`,{style:{fontSize:`var(--text-xs)`,color:`var(--text-muted)`},children:`Enable DNS per tool below to activate interception`})]}),a&&(0,P.jsx)(`div`,{style:{padding:`var(--space-2) var(--space-3)`,background:`var(--danger-soft)`,borderRadius:`var(--radius-sm)`,fontSize:`var(--text-xs)`,color:`var(--danger)`},children:a})]})})}function eg({tool:e,isExpanded:t,onToggle:n,serverRunning:r,dnsActive:i}){let[a,o]=(0,v.useState)(!1);return(0,P.jsxs)(`section`,{className:`surface-card`,style:{padding:0,overflow:`hidden`},children:[(0,P.jsxs)(`div`,{onClick:n,style:{display:`flex`,alignItems:`center`,gap:`var(--space-3)`,padding:`var(--space-3) var(--space-4)`,cursor:`pointer`},children:[(0,P.jsx)(`div`,{style:{width:32,height:32,borderRadius:8,flexShrink:0,background:`${e.color}18`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,P.jsx)(`span`,{style:{fontSize:14,fontWeight:700,color:e.color},children:e.name.charAt(0)})}),(0,P.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,P.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`var(--space-2)`},children:[(0,P.jsx)(`h3`,{style:{margin:0,fontSize:`var(--text-sm)`,fontWeight:600},children:e.name}),i&&(0,P.jsx)(B,{status:`success`,children:`Intercepting`})]}),(0,P.jsx)(`p`,{style:{margin:`2px 0 0`,fontSize:`var(--text-xs)`,color:`var(--text-muted)`,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:e.mitmDomain})]}),(0,P.jsx)(`span`,{style:{color:`var(--text-muted)`,transition:`transform var(--animation-normal)`,transform:t?`rotate(180deg)`:`none`},children:`▾`})]}),t&&(0,P.jsxs)(`div`,{style:{borderTop:`1px solid var(--line)`,padding:`var(--space-4)`,display:`grid`,gap:`var(--space-3)`},children:[(0,P.jsx)(`p`,{style:{margin:0,fontSize:`var(--text-xs)`,color:`var(--text-secondary)`},children:e.description}),(0,P.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,padding:`var(--space-2) var(--space-3)`,background:`var(--surface-muted)`,borderRadius:`var(--radius-sm)`,border:`1px solid var(--line)`},children:[(0,P.jsx)(`span`,{style:{fontSize:`var(--text-xs)`,fontWeight:600},children:`DNS Interception`}),(0,P.jsx)(`button`,{onClick:async()=>{o(!0);try{await fetch(`/api/cli-tools/mitm-dns`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({toolId:e.id,enable:!i})})}catch{}finally{o(!1)}},disabled:!r||a,style:{position:`relative`,display:`inline-flex`,width:36,height:20,borderRadius:`var(--radius-pill)`,border:`none`,background:i?`var(--success)`:`var(--neutral-soft)`,cursor:r?`pointer`:`not-allowed`,opacity:r?1:.5,padding:0,transition:`background var(--animation-normal)`},title:r?i?`Disable DNS interception`:`Enable DNS interception`:`Start MITM server first`,children:(0,P.jsx)(`span`,{style:{position:`absolute`,top:2,left:i?18:2,width:16,height:16,borderRadius:`50%`,background:`#fff`,boxShadow:`0 2px 4px rgba(0,0,0,0.2)`,transition:`left var(--animation-normal)`}})})]}),(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`span`,{style:{fontSize:`var(--text-xs)`,fontWeight:600,color:`var(--text-muted)`,display:`block`,marginBottom:`var(--space-2)`},children:`Available Models`}),(0,P.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:4},children:e.models.map(e=>(0,P.jsx)(`code`,{className:`metadata-pill`,style:{fontSize:`0.6rem`,padding:`2px 6px`,minHeight:`auto`},children:e.name},e.id))})]}),(0,P.jsxs)(`div`,{style:{fontSize:`var(--text-xs)`,color:`var(--text-muted)`},children:[(0,P.jsx)(`strong`,{children:`Target domain:`}),` `,(0,P.jsx)(`code`,{style:{fontSize:`0.65rem`},children:e.mitmDomain})]})]})]})}function tg({label:e,ok:t}){return(0,P.jsxs)(`span`,{style:{display:`inline-flex`,alignItems:`center`,gap:3},children:[(0,P.jsx)(`span`,{style:{color:t?`var(--success)`:`var(--text-muted)`,fontSize:`0.7rem`},children:t?`✓`:`✗`}),e]})}var ng=`responses-proxy-theme`,rg=`endpoint`,ig=[...pt,...mt],ag=new Set(ig.map(e=>e.route));Object.keys(ft).forEach(e=>{let t=ht(e);t&&ag.add(t)});function og(e){try{return decodeURIComponent(e)}catch{return e}}function sg(){let e=window.location.hash.replace(/^#\/?/,``).trim().split(`/`).filter(Boolean),t=e[0];if(!t)return{route:rg,baseRoute:rg,params:{},isUnknown:!1};let n=ht(t);if(n&&(t=n),!ag.has(t))return{route:rg,baseRoute:rg,params:{},isUnknown:!0};let r=t,i=e[1]?og(e[1]):``;return r===`providers`?i===`new`?{route:`provider-new`,baseRoute:r,params:{},isUnknown:e.length>2}:{route:i?`provider-detail`:`providers`,baseRoute:r,params:i?{providerId:i}:{},isUnknown:e.length>2}:r===`clients`?{route:i?`client-detail`:`clients`,baseRoute:r,params:i?{clientKey:i}:{},isUnknown:e.length>2}:r===`oauth`?{route:i?`account-detail`:`oauth`,baseRoute:r,params:i?{accountId:i}:{},isUnknown:e.length>2}:r===`kiro`?{route:i?`account-detail`:`oauth`,baseRoute:`oauth`,params:i?{accountId:i}:{},isUnknown:e.length>2}:{route:r,baseRoute:r,params:{},isUnknown:e.length>1}}function cg(){try{let e=window.localStorage.getItem(ng);if(e===`light`||e===`dark`)return e}catch{}return`light`}function lg(e){if(e.isUnknown)return(0,P.jsx)(At,{title:`Route not found`,description:`This dashboard uses the current React route map. Return to Endpoint to continue.`,actionHref:`#/endpoint`,actionLabel:`Go to Endpoint`});switch(e.route){case`endpoint`:return(0,P.jsx)(fm,{});case`combos`:return(0,P.jsx)(Sn,{});case`quota-tracker`:return(0,P.jsx)(Yh,{});case`mitm`:return(0,P.jsx)(Qh,{});case`cli-tools`:return(0,P.jsx)(On,{});case`media-providers`:return(0,P.jsx)(Mm,{});case`proxy-pools`:return(0,P.jsx)(Nm,{});case`skills`:return(0,P.jsx)(Vh,{});case`console-log`:return(0,P.jsx)(on,{});case`settings`:return(0,P.jsx)(rn,{});case`providers`:return(0,P.jsx)(jm,{});case`provider-new`:return(0,P.jsx)(Eh,{});case`provider-detail`:return(0,P.jsx)(Sh,{providerId:e.params.providerId});case`clients`:return(0,P.jsx)(vn,{});case`client-detail`:return(0,P.jsx)(vn,{clientKey:e.params.clientKey});case`oauth`:return(0,P.jsx)(Qt,{initialTab:window.location.hash.includes(`/kiro`)?`kiro`:`oauth`});case`account-detail`:return(0,P.jsx)(Qt,{accountId:e.params.accountId});case`auth-management`:return(0,P.jsx)(rn,{});case`config-helper`:return(0,P.jsx)(Rn,{});case`usage`:return(0,P.jsx)(Gh,{});case`rtk`:return(0,P.jsx)(Vh,{});case`cache`:return(0,P.jsx)(an,{});case`dashboard`:return(0,P.jsx)(Rp,{});default:return(0,P.jsx)(fm,{})}}function ug(){let[e,t]=(0,v.useState)(sg),[n,r]=(0,v.useState)(cg),[i,a]=(0,v.useState)({status:`loading`});(0,v.useEffect)(()=>{document.documentElement.dataset.theme=n,document.documentElement.style.colorScheme=n;try{window.localStorage.setItem(ng,n)}catch{}},[n]),(0,v.useEffect)(()=>{let e=!1;return S().then(t=>{e||a(t.authenticated&&t.session?{status:`authenticated`,session:t.session}:{status:`anonymous`})}).catch(()=>{e||a({status:`anonymous`})}),()=>{e=!0}},[]),(0,v.useEffect)(()=>{window.location.hash||window.history.replaceState(null,``,`#/endpoint`);let e=()=>t(sg());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]);let o=(0,v.useCallback)(()=>{r(e=>e===`dark`?`light`:`dark`)},[]),s=(0,v.useCallback)(async()=>{await T().catch(()=>void 0),a({status:`anonymous`})},[]),c=(0,v.useCallback)(e=>{window.location.hash=`#/${e}`},[]),l=(0,v.useMemo)(()=>lg(e),[e]);return i.status===`loading`?(0,P.jsx)(`div`,{className:`app-page`,children:(0,P.jsx)(`main`,{className:`app-panel`,children:(0,P.jsx)(jt,{title:`Checking dashboard login`,description:`Validating your admin session.`,cards:3})})}):i.status===`anonymous`?(0,P.jsx)(pm,{onAuthenticated:e=>a({status:`authenticated`,session:e})}):(0,P.jsx)(Pt,{children:(0,P.jsx)(kt,{currentRoute:e.baseRoute,theme:n,session:i.session,onToggleTheme:o,onLogout:s,onNavigate:c,children:l})})}(0,y.createRoot)(document.getElementById(`root`)).render((0,P.jsx)(v.StrictMode,{children:(0,P.jsx)(ug,{})}));
|
|
14
|
+
`).map((e,t)=>{if(e.startsWith(`export `)){let n=e.split(`=`),r=n[0],i=n.slice(1).join(`=`);return(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`span`,{className:`command-highlight`,children:`export`}),` `,(0,P.jsx)(`span`,{className:`variable-highlight`,children:r.replace(`export `,``)}),`=`,(0,P.jsx)(`span`,{className:`terminal-value`,children:i})]},t)}return(0,P.jsx)(`div`,{children:e},t)})}function sm({health:e,loading:t,endpointUrl:n,onRefresh:r}){let i=e?.ok??!1,[a,o]=(0,v.useState)(!1);return(0,P.jsxs)(V,{title:`Server Status`,description:`Local router server health and information`,actions:(0,P.jsx)($t,{onClick:r,isRefreshing:t}),children:[(0,P.jsxs)(`div`,{className:`endpoint-status-grid`,children:[(0,P.jsxs)(`div`,{className:`status-item`,children:[(0,P.jsx)(`div`,{className:`status-indicator`,children:i?(0,P.jsx)(`span`,{className:`status-pulse-dot`}):(0,P.jsx)(Je,{className:`status-icon status-error`})}),(0,P.jsxs)(`div`,{className:`status-details`,children:[(0,P.jsx)(`div`,{className:`status-label`,children:`Server`}),(0,P.jsx)(`div`,{className:`status-value`,children:i?`Running`:`Stopped`})]})]}),(0,P.jsx)(`div`,{className:`status-item`,children:(0,P.jsxs)(`div`,{className:`status-details`,children:[(0,P.jsx)(`div`,{className:`status-label`,children:`Service`}),(0,P.jsx)(`div`,{className:`status-value`,children:e?.service||`responses-proxy`})]})}),(0,P.jsx)(`div`,{className:`status-item`,children:(0,P.jsxs)(`div`,{className:`status-details`,children:[(0,P.jsx)(`div`,{className:`status-label`,children:`Status`}),(0,P.jsx)(`div`,{className:`status-value`,children:i?`Online`:`Offline`})]})}),(0,P.jsx)(`div`,{className:`status-item`,children:(0,P.jsxs)(`div`,{className:`status-details`,children:[(0,P.jsx)(`div`,{className:`status-label`,children:`Port`}),(0,P.jsx)(`div`,{className:`status-value`,children:window.location.port||`8318`})]})})]}),(0,P.jsxs)(`div`,{className:`endpoint-url-section`,children:[(0,P.jsx)(`div`,{className:`endpoint-label`,children:`Local Endpoint`}),(0,P.jsxs)(`div`,{className:`endpoint-url-container`,children:[(0,P.jsx)(`code`,{className:`endpoint-url`,children:n}),(0,P.jsx)(`button`,{className:`copy-button`,onClick:()=>{navigator.clipboard.writeText(n),o(!0),setTimeout(()=>o(!1),2e3)},title:`Copy endpoint URL`,children:a?`Copied!`:`Copy`})]})]})]})}function cm({health:e,providers:t}){let n=e?.activeProviderId,r=t.find(e=>e.id===n),i=r?.displayName||n||`None`,a=r?.tier||`n/a`,o=r?.healthStatus||`unknown`,s=r?.models?.[0]?.id||r?.capabilities?.defaultModels?.[0]||`auto`,{cardClass:c,icon:l}=(()=>{let e=n?.toLowerCase()||``;return e.includes(`claude`)||e.includes(`anthropic`)?{cardClass:`active-provider-card-anthropic`,icon:`🦉`}:e.includes(`openai`)||e.includes(`codex`)||e.includes(`gpt`)?{cardClass:`active-provider-card-openai`,icon:`🧠`}:e.includes(`gemini`)||e.includes(`google`)?{cardClass:`active-provider-card-google`,icon:`✨`}:e.includes(`kiro`)?{cardClass:`active-provider-card-kiro`,icon:`⚡`}:{cardClass:`active-provider-card-default`,icon:`🔌`}})();return(0,P.jsx)(V,{title:`Active Provider`,description:`Currently selected provider for new requests`,className:c,children:(0,P.jsxs)(`div`,{className:`active-provider-info`,children:[(0,P.jsxs)(`div`,{className:`provider-header-row`,children:[(0,P.jsx)(`div`,{className:`provider-vendor-icon`,children:l}),(0,P.jsxs)(`div`,{className:`provider-details-wrapper`,children:[(0,P.jsx)(`div`,{className:`provider-name`,children:i}),(0,P.jsxs)(`div`,{className:`provider-meta-row`,children:[(0,P.jsx)(B,{variant:`accent`,children:a}),(0,P.jsx)(B,{variant:o===`healthy`?`success`:o===`degraded`?`warning`:`danger`,children:o})]})]})]}),(0,P.jsxs)(`div`,{className:`provider-model-wrapper`,children:[(0,P.jsx)(`div`,{className:`model-label`,children:`Active Model`}),(0,P.jsx)(`code`,{className:`model-name`,children:s})]})]})})}function lm({providers:e}){return(0,P.jsx)(V,{title:`Fallback Tiers`,description:`Provider tier health and fallback readiness`,children:(0,P.jsx)(`div`,{className:`fallback-tiers-list`,children:[`subscription`,`cheap`,`free`].map(t=>{let n=e.filter(e=>e.tier===t).filter(e=>e.configured),r=n.filter(e=>e.healthStatus===`healthy`).length,i=`not_configured`;n.length>0&&(i=r>0?`healthy`:`warning`);let a=n.length>0?r/n.length*100:0;return{tier:{subscription:`Subscription`,cheap:`Cheap`,free:`Free`}[t],providers:n.length,healthy:r,status:i,usagePercent:a}}).map(e=>(0,P.jsxs)(`div`,{className:`fallback-tier-item`,children:[(0,P.jsxs)(`div`,{className:`tier-header`,children:[(0,P.jsx)(`div`,{className:`tier-name`,children:e.tier}),(0,P.jsx)(`div`,{className:`tier-stats`,children:e.providers>0?`${e.healthy}/${e.providers} healthy`:`Not configured`})]}),e.providers>0?(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(`div`,{className:`tier-progress-container`,children:(0,P.jsx)(`div`,{className:`tier-progress-fill tier-progress-fill-${e.status}`,style:{width:`${e.usagePercent}%`}})}),(0,P.jsx)(`div`,{className:`tier-footer`,children:(0,P.jsx)(B,{variant:e.status===`healthy`?`success`:`warning`,children:e.status===`healthy`?`Ready`:`Warning`})})]}):(0,P.jsx)(`div`,{className:`tier-footer`,children:(0,P.jsx)(B,{variant:`neutral`,children:`Disabled`})})]},e.tier))})})}function um({health:e,providers:t,endpointUrl:n}){let r=e?.activeProviderId,i=t.find(e=>e.id===r),a=i?.displayName||r||`No Active Upstream`,o=i?.tier?`${i.tier.toUpperCase()} Tier`:`Routing Pipeline`;return(0,P.jsx)(V,{title:`Routing Pipeline`,description:`Request flow through the router system`,children:(0,P.jsx)(`div`,{className:`pipeline-container-premium`,children:[{step:`Client CLI`,description:`Claude Code / Cline Client`,active:!0},{step:`Local Proxy`,description:n.replace(/^https?:\/\//,``),active:!0},{step:`Router Engine`,description:`Failover Strategy Routing`,active:!0},{step:o,description:a,active:i!==void 0},{step:`Response Stream`,description:`Dynamic cache delivery`,active:i!==void 0}].map((e,t)=>(0,P.jsxs)(`div`,{className:`pipeline-step-premium ${e.active?`active`:``}`,children:[(0,P.jsx)(`div`,{className:`step-indicator-premium`,children:t+1}),(0,P.jsxs)(`div`,{className:`pipeline-step-info`,children:[(0,P.jsx)(`div`,{className:`pipeline-step-title`,children:e.step}),(0,P.jsx)(`div`,{className:`pipeline-step-desc`,children:e.description})]}),(0,P.jsx)(`div`,{className:`step-status`,children:(0,P.jsx)(B,{variant:e.active?`success`:`neutral`,children:e.active?`Active`:`Pending`})})]},e.step))})})}function dm({endpointUrl:e}){let[t,n]=(0,v.useState)(`claude`),[r,i]=(0,v.useState)(!1),a={claude:{tool:`Claude Code`,command:`export ANTHROPIC_API_KEY="your-key-here"\nexport ANTHROPIC_BASE_URL="${e}"`},cursor:{tool:`Cursor`,command:`// In Cursor settings:\n{\n "anthropic.baseURL": "${e}",\n "anthropic.apiKey": "your-key-here"\n}`},openai:{tool:`OpenAI CLI`,command:`export OPENAI_API_KEY="your-key-here"\nexport OPENAI_BASE_URL="${e}"`}}[t],o=e=>{navigator.clipboard.writeText(e),i(!0),setTimeout(()=>i(!1),2e3)};return(0,P.jsxs)(V,{title:`Quick Setup`,description:`Copy configuration for popular AI tools`,children:[(0,P.jsxs)(`div`,{className:`setup-tab-bar`,children:[(0,P.jsx)(`button`,{className:`setup-tab-btn ${t===`claude`?`active`:``}`,onClick:()=>n(`claude`),children:`Claude Code`}),(0,P.jsx)(`button`,{className:`setup-tab-btn ${t===`cursor`?`active`:``}`,onClick:()=>n(`cursor`),children:`Cursor`}),(0,P.jsx)(`button`,{className:`setup-tab-btn ${t===`openai`?`active`:``}`,onClick:()=>n(`openai`),children:`OpenAI CLI`})]}),(0,P.jsxs)(`div`,{className:`terminal-wrapper`,children:[(0,P.jsxs)(`div`,{className:`terminal-header`,children:[(0,P.jsxs)(`div`,{className:`terminal-dots`,children:[(0,P.jsx)(`span`,{className:`terminal-dot terminal-dot-red`}),(0,P.jsx)(`span`,{className:`terminal-dot terminal-dot-yellow`}),(0,P.jsx)(`span`,{className:`terminal-dot terminal-dot-green`})]}),(0,P.jsx)(`span`,{className:`terminal-title`,children:t===`cursor`?`JSON`:`BASH`}),(0,P.jsx)(`button`,{className:`copy-command-button`,onClick:()=>o(a.command),children:r?`Copied!`:`Copy`})]}),(0,P.jsx)(`div`,{className:`terminal-body`,children:(0,P.jsx)(`pre`,{children:(0,P.jsx)(`code`,{children:om(a.command,t)})})})]})]})}function fm(){let{providers:e,loading:t,refresh:n}=tm();am(!0);let[r,i]=(0,v.useState)(null),[a,o]=(0,v.useState)(null),[s,c]=(0,v.useState)(!0),[l,u]=(0,v.useState)(null),d=(0,v.useCallback)(async()=>{try{c(!0),u(null);let[e,t]=await Promise.all([E(),j()]);i(e),o(t)}catch(e){console.error(`Failed to load telemetry`,e),u(e instanceof Error?e.message:`Failed to connect to local proxy. Make sure it is running.`)}finally{c(!1)}},[]);(0,v.useEffect)(()=>{d()},[d]);let f=async()=>{await Promise.all([d(),n()])},p=`${window.location.origin}/v1`,m=(a?.stats||{}).today||{},h=m.requests||0,g=(m.totalInputTokens||0)+(m.totalCachedTokens||0),_=m.hitRate||0,y=m.avgCacheSavedPercent||0,b=m.rtkAppliedRequests||0,x=t||s;return(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{icon:Ze,title:`Endpoint`,description:`Local OpenAI-compatible endpoint and router status`,actions:(0,P.jsx)(`div`,{className:`page-actions`,children:(0,P.jsx)($t,{onClick:f,isRefreshing:x})})}),(0,P.jsxs)(`div`,{className:`endpoint-screen-layout`,children:[l&&(0,P.jsxs)(`div`,{className:`error-banner`,style:{background:`var(--danger-soft)`,border:`1px solid var(--danger)`,borderRadius:`var(--radius-md)`,padding:`var(--space-4)`,marginBottom:`var(--space-5)`,display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:`var(--space-4)`},children:[(0,P.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`var(--space-3)`},children:[(0,P.jsx)(Je,{className:`status-icon status-error`,style:{width:`24px`,height:`24px`}}),(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`h3`,{style:{margin:0,color:`var(--danger)`,fontSize:`var(--font-md)`},children:`Connection Offline`}),(0,P.jsxs)(`p`,{style:{margin:`var(--space-1) 0 0 0`,fontSize:`var(--font-sm)`,color:`var(--text-secondary)`},children:[`Failed to connect to local proxy: `,l,`. Check if your service is active.`]})]})]}),(0,P.jsx)(`button`,{className:`button-secondary`,style:{whiteSpace:`nowrap`},onClick:f,children:`Retry Connection`})]}),(0,P.jsxs)(`div`,{className:`endpoint-top-row`,children:[(0,P.jsx)(sm,{health:r,loading:x,endpointUrl:p,onRefresh:f}),(0,P.jsx)(cm,{health:r,providers:e})]}),(0,P.jsxs)(`div`,{className:`endpoint-stats-row`,children:[(0,P.jsx)(z,{label:`Requests Today`,value:L(h),caption:`API requests processed`}),(0,P.jsx)(z,{label:`Tokens Today`,value:L(g),caption:`Input + cached tokens`}),(0,P.jsx)(z,{label:`RTK Applied`,value:L(b),caption:`Reduced context requests`}),(0,P.jsx)(z,{label:`Cache Hit Rate`,value:zt(_),caption:`Prompt cache efficiency`}),(0,P.jsx)(z,{label:`Average Savings`,value:zt(y),caption:`Tokens saved ratio`})]}),(0,P.jsxs)(`div`,{className:`endpoint-bottom-row`,children:[(0,P.jsx)(lm,{providers:e}),(0,P.jsx)(um,{health:r,providers:e,endpointUrl:p})]}),(0,P.jsx)(`div`,{className:`endpoint-setup-row`,children:(0,P.jsx)(dm,{endpointUrl:p})}),(0,P.jsx)(zp,{})]})]})}function pm({onAuthenticated:e}){let[t,n]=(0,v.useState)(`password`),[r,i]=(0,v.useState)(``),[a,o]=(0,v.useState)(!1),[s,c]=(0,v.useState)(``),[l,u]=(0,v.useState)(null),[d,f]=(0,v.useState)(!1),[p,m]=(0,v.useState)(null),[h,g]=(0,v.useState)(`idle`),[_,y]=(0,v.useState)(()=>Date.now()),[b,S]=(0,v.useState)(0);async function T(t){if(t.preventDefault(),!r.trim()){c(`Password is required`);return}o(!0),c(``);try{let t=await x(`/api/dashboard-auth/login`,`POST`,{password:r});t.session&&e(t.session)}catch(e){let t=e.message||`Login failed`;t.includes(`not configured`)?n(`telegram`):c(t)}finally{o(!1)}}(0,v.useEffect)(()=>{if(!l||h!==`pending`)return;let e=window.setInterval(()=>void E(),1500);return()=>window.clearInterval(e)},[l,h]),(0,v.useEffect)(()=>{if(!l)return;let e=window.setInterval(()=>y(Date.now()),1e3);return()=>window.clearInterval(e)},[l]);async function E(){if(l)try{let t=await w(l.challengeId,l.pollToken);if(t.status===`approved`&&t.session){g(`approved`),e(t.session);return}if(t.status===`rejected`||t.status===`expired`){g(t.status),m({variant:`error`,message:t.status===`rejected`?`Admin rejected. Try again.`:`Expired. Request again.`});return}g(`pending`)}catch{g(`idle`),u(null)}}async function D(){f(!0),m(null);try{let e=await C();u({challengeId:e.challengeId,pollToken:e.pollToken,displayCode:e.displayCode,expiresAt:e.expiresAt}),g(`pending`),y(Date.now()),S(Math.max(1,Math.ceil((new Date(e.expiresAt).getTime()-Date.now())/1e3))),m({variant:`success`,message:`Approval sent to Telegram admin.`})}catch(e){m({variant:`error`,message:e.message||`Failed to request approval.`})}finally{f(!1)}}let O=l?Math.max(0,Math.ceil((new Date(l.expiresAt).getTime()-_)/1e3)):0,ee=b>0?Math.min(100,O/b*100):0;return(0,P.jsx)(`div`,{className:`login-page`,children:(0,P.jsxs)(V,{className:`login-card`,children:[(0,P.jsx)(`span`,{className:`login-mark`,"aria-hidden":`true`,children:`RP`}),(0,P.jsx)(`p`,{className:`eyebrow`,children:`Admin dashboard`}),(0,P.jsx)(`h1`,{children:`Sign in`}),t===`password`?(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(`p`,{className:`muted-copy`,children:`Enter your admin password to access the dashboard.`}),s&&(0,P.jsx)(Ut,{variant:`error`,message:s}),(0,P.jsxs)(`form`,{className:`login-form`,onSubmit:T,style:{display:`grid`,gap:`var(--space-3)`},children:[(0,P.jsx)(`input`,{type:`password`,value:r,onChange:e=>i(e.target.value),placeholder:`Admin password`,autoFocus:!0,autoComplete:`current-password`,style:{minHeight:46}}),(0,P.jsx)(`button`,{className:`button-primary`,type:`submit`,disabled:a,children:a?`Signing in…`:`Sign in`})]}),(0,P.jsx)(`button`,{type:`button`,onClick:()=>n(`telegram`),style:{background:`none`,border:`none`,color:`var(--accent)`,cursor:`pointer`,fontSize:`var(--text-xs)`,marginTop:`var(--space-3)`,padding:0},children:`Use Telegram approval instead →`})]}):(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(`p`,{className:`muted-copy`,children:`Request approval from your Telegram admin.`}),p&&(0,P.jsx)(Ut,{variant:p.variant,message:p.message}),(0,P.jsx)(`div`,{className:`login-form`,children:(0,P.jsx)(`button`,{className:`button-primary`,type:`button`,disabled:d,onClick:D,children:d?`Sending…`:l?`Request again`:`Request Telegram approval`})}),l&&(0,P.jsxs)(`div`,{className:`login-form`,style:{marginTop:`var(--space-3)`},children:[(0,P.jsx)(`div`,{className:`login-code-display`,"aria-label":`Approval code`,children:l.displayCode}),(0,P.jsxs)(`div`,{className:`login-countdown`,children:[(0,P.jsx)(`div`,{className:`login-countdown-track`,role:`progressbar`,"aria-valuemin":0,"aria-valuemax":b,"aria-valuenow":O,children:(0,P.jsx)(`div`,{className:`login-countdown-fill`,style:{width:`${ee}%`}})}),(0,P.jsxs)(`div`,{className:`login-status-row`,children:[h===`pending`&&(0,P.jsx)(`span`,{className:`login-spinner`,"aria-hidden":`true`}),(0,P.jsxs)(`span`,{children:[h===`pending`?`Waiting for admin`:`Status: ${h}`,` · `,O,`s`]})]})]})]}),(0,P.jsx)(`button`,{type:`button`,onClick:()=>n(`password`),style:{background:`none`,border:`none`,color:`var(--accent)`,cursor:`pointer`,fontSize:`var(--text-xs)`,marginTop:`var(--space-3)`,padding:0},children:`← Use password instead`})]})]})})}function mm(e){if(!e.enabled)return`disabled`;if(!e.configured)return`not_configured`;if(e.quota?.hardLimitReached)return`quota_exhausted`;let t=e.accounts||[];if(t.filter(e=>e.status===`connected`&&e.routingMode!==`disabled`).length===0&&t.length>0&&t.some(e=>e.status===`expired`||e.status===`needs_reconnect`))return`auth_expired`;let n=e.models?.filter(e=>e.serviceKind===`chat`&&e.enabled)||[];if(e.serviceKinds.includes(`chat`)&&n.length===0)return`not_configured`;if([e.quota?.softLimitReached,e.quota?.usagePercent&&e.quota.usagePercent>85,t.some(e=>e.status===`needs_reconnect`),e.healthMessage&&e.healthMessage.includes(`warning`)].some(e=>e))return`degraded`;if(e.healthStatus&&e.lastHealthCheckAt){let t=new Date(e.lastHealthCheckAt);if((new Date().getTime()-t.getTime())/(1e3*60*60)<1)return e.healthStatus}return`healthy`}function hm(e){if(e.healthStatus===`unknown`||!e.lastHealthCheckAt)return!0;let t=new Date(e.lastHealthCheckAt);return(new Date().getTime()-t.getTime())/(1e3*60*60)>=(e.healthStatus===`healthy`?4:1)}function gm(e){let t=0;switch(e.enabled&&(t+=10),e.configured&&(t+=5),e.fallbackEligible&&(t+=3),e.tier){case`subscription`:t+=8;break;case`cheap`:t+=6;break;case`free`:t+=4;break;case`custom`:t+=2;break}switch(e.healthStatus){case`unknown`:t+=15;break;case`auth_expired`:case`quota_exhausted`:t+=12;break;case`degraded`:case`rate_limited`:t+=8;break;case`not_configured`:t+=5;break}return t}function _m(e){let t=[],n=[],r=`success`;e.status===`failed`?r=`error`:e.status===`partial`&&(r=`warning`),e.authOk||(t.push(`Authentication failed`),n.push(`Reconnect or refresh authentication credentials`),r=`error`),e.quotaOk||(t.push(`Quota limit reached`),n.push(`Wait for quota reset or upgrade plan`),r=`error`),e.modelOk||(t.push(`Model access failed`),n.push(`Check model availability and permissions`),r=`error`),e.routingOk||(t.push(`Routing configuration failed`),n.push(`Verify provider routing settings`),r=`error`),e.latencyMs&&e.latencyMs>5e3&&(t.push(`High latency detected`),n.push(`Check network connection and provider performance`),r===`success`&&(r=`warning`));let i;return i=e.status===`success`?`Health check passed in ${e.latencyMs}ms`:e.status===`partial`?`Health check partially successful with ${t.length} issue(s)`:`Health check failed: ${e.errorMessage||`Unknown error`}`,{summary:i,issues:t,suggestions:n,severity:r}}function vm(e){return e.hardLimitReached?{status:`exhausted`,message:`Quota exhausted`,resetInfo:e.resetAt?`Resets at ${new Date(e.resetAt).toLocaleString()}`:void 0}:e.softLimitReached||e.usagePercent&&e.usagePercent>90?{status:`critical`,message:`Quota usage: ${e.usagePercent?.toFixed(1)}%`,resetInfo:e.resetAt?`Resets at ${new Date(e.resetAt).toLocaleString()}`:void 0}:e.usagePercent&&e.usagePercent>75?{status:`warning`,message:`Quota usage: ${e.usagePercent.toFixed(1)}%`,resetInfo:e.resetAt?`Resets at ${new Date(e.resetAt).toLocaleString()}`:void 0}:{status:`healthy`,message:e.usagePercent?`Quota usage: ${e.usagePercent.toFixed(1)}%`:`Quota available`,resetInfo:e.resetAt?`Resets at ${new Date(e.resetAt).toLocaleString()}`:void 0}}var ym={pollInterval:3e4,maxRetries:3,retryDelay:5e3,batchSize:5,priorityThreshold:50},bm=class{config;isRunning=!1;intervalId=null;subscribers=new Set;statsSubscribers=new Set;providerHealthCache=new Map;stats={totalProviders:0,healthyProviders:0,unhealthyProviders:0,lastUpdateAt:new Date().toISOString(),checksPerformed:0,errorsEncountered:0,averageCheckTime:0};checkTimes=[];constructor(e={}){this.config={...ym,...e}}start(){this.isRunning||(this.isRunning=!0,this.scheduleNextCheck(),console.log(`Provider health monitoring started`))}stop(){this.isRunning&&(this.isRunning=!1,this.intervalId&&=(clearTimeout(this.intervalId),null),console.log(`Provider health monitoring stopped`))}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}subscribeToStats(e){return this.statsSubscribers.add(e),()=>this.statsSubscribers.delete(e)}getProviderHealth(e){return this.providerHealthCache.get(e)||null}getAllProviderHealth(){return new Map(this.providerHealthCache)}getStats(){return{...this.stats}}async checkProviderHealth(e){let t=Date.now();try{let[n,r]=await Promise.all([b(`/api/providers/${e}`),this.fetchProviderUsage(e)]),i=n.provider;if(!i)throw Error(`Provider not found`);let a=this.computeProviderHealthFromData(i,r);this.providerHealthCache.set(e,a),this.notifySubscribers(a);let o=Date.now()-t;return this.updateStats(o,!1),a}catch(n){console.error(`Health check failed for provider ${e}:`,n);let r={providerId:e,healthStatus:`unknown`,healthMessage:n instanceof Error?n.message:`Health check failed`,lastHealthCheckAt:new Date().toISOString(),issues:[`Health check failed`],suggestedFixes:[`Check provider configuration and network connectivity`]};this.providerHealthCache.set(e,r),this.notifySubscribers(r);let i=Date.now()-t;throw this.updateStats(i,!0),n}}async checkMultipleProviders(e){let t=[],n=this.chunkArray(e,this.config.batchSize);for(let e of n){let r=e.map(e=>this.checkProviderHealth(e).catch(t=>(console.error(`Batch health check failed for provider ${e}:`,t),null))),i=await Promise.all(r);t.push(...i.filter(e=>e!==null)),n.length>1&&await this.delay(1e3)}return t}async refreshAllProviders(){try{let e=(await b(`/api/providers`)).providers||[],t=e.filter(e=>this.shouldCheckProvider(e)).sort((e,t)=>{let n=gm(this.mapToProvider(e));return gm(this.mapToProvider(t))-n}).slice(0,20);console.log(`Refreshing health for ${t.length} providers`),await this.checkMultipleProviders(t.map(e=>e.id)),this.updateOverallStats(e)}catch(e){console.error(`Failed to refresh all provider health:`,e)}}scheduleNextCheck(){this.isRunning&&(this.intervalId=setTimeout(async()=>{try{await this.refreshAllProviders()}catch(e){console.error(`Scheduled health check failed:`,e)}finally{this.scheduleNextCheck()}},this.config.pollInterval))}async fetchProviderUsage(e){try{return(await b(`/api/providers/live-usage`)).providers?.find(t=>t.id===e)?.usage||null}catch(t){return console.warn(`Failed to fetch usage for provider ${e}:`,t),null}}computeProviderHealthFromData(e,t){let n=this.mapToProvider(e);t&&n.quota&&(n.quota.used=t.used||n.quota.used,n.quota.limit=t.limit||n.quota.limit,n.quota.remaining=t.remaining,n.quota.used&&n.quota.limit&&(n.quota.usagePercent=n.quota.used/n.quota.limit*100));let r=mm(n);return{providerId:e.id,healthStatus:r.status,healthMessage:r.message,lastHealthCheckAt:new Date().toISOString(),quota:n.quota,issues:r.issues||[],suggestedFixes:r.suggestedFixes||[]}}shouldCheckProvider(e){let t=this.mapToProvider(e);if(!t.enabled)return!1;let n=hm(t),r=gm(t);return n&&r>=this.config.priorityThreshold}mapToProvider(e){return{id:e.id,name:e.name,displayName:e.name,tier:`custom`,serviceKinds:[`chat`],authTypes:[e.authMode||`api_key`],enabled:!0,configured:e.providerApiKeys?.length>0||!!e.chatgptAccountId,healthStatus:`unknown`,priority:1,fallbackEligible:!1,accounts:[],models:[]}}notifySubscribers(e){this.subscribers.forEach(t=>{try{t(e)}catch(e){console.error(`Error in health update subscriber:`,e)}})}notifyStatsSubscribers(){this.statsSubscribers.forEach(e=>{try{e(this.stats)}catch(e){console.error(`Error in stats subscriber:`,e)}})}updateStats(e,t){this.stats.checksPerformed++,t&&this.stats.errorsEncountered++,this.checkTimes.push(e),this.checkTimes.length>100&&this.checkTimes.shift(),this.stats.averageCheckTime=this.checkTimes.reduce((e,t)=>e+t,0)/this.checkTimes.length,this.stats.lastUpdateAt=new Date().toISOString(),this.notifyStatsSubscribers()}updateOverallStats(e){this.stats.totalProviders=e.length;let t=0,n=0;this.providerHealthCache.forEach(e=>{e.healthStatus===`healthy`?t++:e.healthStatus!==`unknown`&&n++}),this.stats.healthyProviders=t,this.stats.unhealthyProviders=n,this.stats.lastUpdateAt=new Date().toISOString(),this.notifyStatsSubscribers()}chunkArray(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}delay(e){return new Promise(t=>setTimeout(t,e))}},xm=null;function Sm(e){return xm||=new bm(e),xm}function Cm(e){let[t,n]=(0,v.useState)(new Map),[r,i]=(0,v.useState)(null),[a,o]=(0,v.useState)(!1),[s,c]=(0,v.useState)(null),l=(0,v.useMemo)(()=>Sm(e),[e]);(0,v.useEffect)(()=>{let e=l.subscribe(e=>{n(t=>new Map(t).set(e.providerId,e)),c(null)}),t=l.subscribeToStats(e=>{i(e)});return n(l.getAllProviderHealth()),i(l.getStats()),()=>{e(),t()}},[l]);let u=(0,v.useCallback)(()=>{try{l.start(),o(!0),c(null)}catch(e){c(e instanceof Error?e.message:`Failed to start monitoring`)}},[l]),d=(0,v.useCallback)(()=>{try{l.stop(),o(!1)}catch(e){c(e instanceof Error?e.message:`Failed to stop monitoring`)}},[l]),f=(0,v.useCallback)(async()=>{try{c(null),await l.refreshAllProviders()}catch(e){c(e instanceof Error?e.message:`Failed to refresh health data`)}},[l]),p=(0,v.useCallback)(async e=>{try{c(null),await l.checkProviderHealth(e)}catch(t){c(t instanceof Error?t.message:`Failed to check health for provider ${e}`)}},[l]);return{healthUpdates:t,stats:r,healthSummary:(0,v.useMemo)(()=>{let e=Array.from(t.values()),n={total:e.length,healthy:0,degraded:0,critical:0,unknown:0,lastUpdateAt:r?.lastUpdateAt||null};return e.forEach(e=>{switch(e.healthStatus){case`healthy`:n.healthy++;break;case`degraded`:case`rate_limited`:n.degraded++;break;case`quota_exhausted`:case`auth_expired`:case`disabled`:case`not_configured`:n.critical++;break;default:n.unknown++}}),n},[t,r]),isMonitoring:a,error:s,startMonitoring:u,stopMonitoring:d,refreshAllHealth:f,checkProviderHealth:p}}function wm(e){let[t,n]=(0,v.useState)(null),[r,i]=(0,v.useState)(!1),[a,o]=(0,v.useState)(null),s=(0,v.useMemo)(()=>Sm(),[]);return(0,v.useEffect)(()=>{if(!e){n(null);return}return n(s.getProviderHealth(e)),s.subscribe(t=>{t.providerId===e&&(n(t),o(null))})},[e,s]),{healthUpdate:t,isChecking:r,error:a,checkHealth:(0,v.useCallback)(async()=>{if(e)try{i(!0),o(null),await s.checkProviderHealth(e)}catch(e){o(e instanceof Error?e.message:`Health check failed`)}finally{i(!1)}},[e,s]),getHealthAge:(0,v.useCallback)(()=>{if(!t?.lastHealthCheckAt)return null;let e=new Date(t.lastHealthCheckAt),n=new Date().getTime()-e.getTime();return{ageMs:n,ageMinutes:Math.floor(n/(1e3*60)),ageHours:Math.floor(n/(1e3*60*60)),isStale:n>14400*1e3}},[t]),hasHealthData:!!t}}function Tm(e){let{healthUpdates:t}=Cm(),n=(0,v.useMemo)(()=>e.map(e=>{let n=t.get(e.id);return{...e,healthStatus:n?.healthStatus||e.healthStatus,healthMessage:n?.healthMessage||e.healthMessage,lastHealthCheckAt:n?.lastHealthCheckAt||e.lastHealthCheckAt,quota:n?.quota||e.quota,realtimeHealth:n}}),[e,t]);return{enhancedProviders:n,sortedByHealth:(0,v.useMemo)(()=>[...n].sort((e,t)=>{let n={healthy:0,degraded:1,rate_limited:2,quota_exhausted:3,auth_expired:4,not_configured:5,disabled:6,unknown:7},r=n[e.healthStatus]??7,i=n[t.healthStatus]??7;if(r!==i)return r-i;let a={subscription:0,cheap:1,free:2,custom:3},o=a[e.tier]??3,s=a[t.tier]??3;return o===s?e.priority-t.priority:o-s}),[n]),filterByHealth:(0,v.useCallback)(e=>n.filter(t=>e.includes(t.healthStatus)),[n]),getProvidersNeedingAttention:(0,v.useCallback)(()=>n.filter(e=>{let n=t.get(e.id);return n&&(n.issues&&n.issues.length>0||[`quota_exhausted`,`auth_expired`,`not_configured`,`disabled`].includes(n.healthStatus))}),[n,t])}}function Em(e=!0,t){let{isMonitoring:n,startMonitoring:r,stopMonitoring:i}=Cm(t);return(0,v.useEffect)(()=>{e&&!n?r():!e&&n&&i()},[e,n,r,i]),(0,v.useEffect)(()=>()=>{n&&i()},[n,i]),{isMonitoring:n}}function Dm(e){let t=e.toLowerCase();return t.includes(`claude`)||t.includes(`anthropic`)?`linear-gradient(135deg, #d97706, #b45309)`:t.includes(`openai`)||t.includes(`codex`)||t.includes(`copilot`)?`linear-gradient(135deg, #1e293b, #0f172a)`:t.includes(`gemini`)||t.includes(`google`)?`linear-gradient(135deg, #2563eb, #7c3aed)`:t.includes(`deepseek`)?`linear-gradient(135deg, #0d9488, #0f766e)`:t.includes(`groq`)?`linear-gradient(135deg, #ea580c, #c2410c)`:t.includes(`mistral`)?`linear-gradient(135deg, #e11d48, #be123c)`:t.includes(`xai`)||t.includes(`grok`)?`linear-gradient(135deg, #000000, #1e293b)`:t.includes(`cursor`)?`linear-gradient(135deg, #4f46e5, #3730a3)`:t.includes(`qwen`)||t.includes(`alibaba`)?`linear-gradient(135deg, #059669, #047857)`:t.includes(`cloudflare`)?`linear-gradient(135deg, #f97316, #ea580c)`:t.includes(`nvidia`)?`linear-gradient(135deg, #16a34a, #15803d)`:`linear-gradient(135deg, #64748b, #475569)`}function Om(e){let t=e.split(` `);return t.length>=2?(t[0][0]+t[1][0]).toUpperCase():e.slice(0,2).toUpperCase()}function km(e){return e.configured?e.healthStatus===`healthy`?{label:`Ready`,dotClass:`healthy`}:e.healthStatus===`degraded`?{label:`Degraded`,dotClass:`degraded`}:e.healthStatus===`quota_exhausted`?{label:`Quota Exhausted`,dotClass:`quota_exhausted`}:{label:`Ready`,dotClass:`healthy`}:{label:`No connection`,dotClass:`not_configured`}}function Am({provider:e,isDisabled:t,onToggle:n,onClick:r}){let i=t?{label:`Disabled`,dotClass:`not_configured`}:km(e),a=Dm(e.id),o=Om(e.displayName);return(0,P.jsxs)(`div`,{className:`provider-small-card`,onClick:r,children:[(0,P.jsx)(`div`,{className:`provider-small-logo-container`,style:{background:a},children:o}),(0,P.jsxs)(`div`,{className:`provider-small-info`,children:[(0,P.jsxs)(`div`,{className:`provider-small-name-row`,style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:`var(--space-2)`},children:[(0,P.jsx)(`h4`,{className:`provider-small-name`,title:e.displayName,children:e.displayName}),(0,P.jsx)(`div`,{className:`custom-switch ${t?`off`:`on`}`,onClick:e=>{e.stopPropagation(),n()},title:t?`Enable Provider`:`Disable Provider`,children:(0,P.jsx)(`span`,{className:`custom-switch-slider`})})]}),(0,P.jsxs)(`div`,{className:`provider-small-status`,children:[(0,P.jsx)(`span`,{className:`provider-small-status-dot ${i.dotClass}`}),(0,P.jsx)(`span`,{children:i.label})]})]})]})}function jm(){let[e,t]=(0,v.useState)(``),[n,r]=(0,v.useState)(null),[i,a]=(0,v.useState)(()=>{try{let e=localStorage.getItem(`disabled_providers`);return e?new Set(JSON.parse(e)):new Set}catch{return new Set}}),o=e=>{a(t=>{let n=new Set(t);n.has(e)?n.delete(e):n.add(e);try{localStorage.setItem(`disabled_providers`,JSON.stringify(Array.from(n)))}catch(e){console.error(`Failed to persist disabled providers:`,e)}return n})};(0,v.useEffect)(()=>{E().then(e=>{e&&e.activeProviderId&&r(e.activeProviderId)}).catch(()=>{})},[]);let{providers:s,loading:c,error:l,refresh:u}=tm(),{testProvider:d}=rm();Em(!0);let{enhancedProviders:f}=Tm(s),p=(0,v.useMemo)(()=>f.filter(t=>{if(e){let n=e.toLowerCase();return t.name.toLowerCase().includes(n)||t.displayName.toLowerCase().includes(n)||t.description?.toLowerCase().includes(n)}return!0}),[f,e]),m=(0,v.useMemo)(()=>p.filter(e=>e.tier===`custom`),[p]),h=(0,v.useMemo)(()=>p.filter(e=>e.tier!==`custom`&&e.authTypes.includes(`oauth`)),[p]),g=(0,v.useMemo)(()=>p.filter(e=>e.tier===`free`&&!e.authTypes.includes(`oauth`)),[p]),_=(0,v.useMemo)(()=>p.filter(e=>e.tier!==`custom`&&!e.authTypes.includes(`oauth`)&&e.tier!==`free`),[p]),y=e=>{window.location.hash=`#/providers/${e}`},b=async e=>{try{await d(e)}catch(t){console.error(`Failed to test provider ${e}:`,t)}},x=()=>{window.location.hash=`#/providers/new`},S=async e=>{let t=e.filter(e=>e.configured);for(let e of t)b(e.id)},C=async()=>{try{await u()}catch(e){console.error(`Failed to refresh providers:`,e)}};return c?(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{icon:Ie,title:`Providers`,description:`Manage AI provider connections and routing configuration`}),(0,P.jsx)(jt,{title:`Loading providers`,description:`Fetching provider data and health status...`,cards:3})]}):l?(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{icon:Ie,title:`Providers`,description:`Manage AI provider connections and routing configuration`}),(0,P.jsx)(At,{title:`Failed to load providers`,description:l,actionLabel:`Retry`,onClick:C})]}):(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{icon:Ie,title:`Providers`,description:`Manage your AI provider connections`,actions:(0,P.jsxs)(`div`,{className:`page-actions`,style:{display:`flex`,alignItems:`center`,gap:`var(--space-3)`},children:[(0,P.jsxs)(`div`,{className:`search-container`,style:{position:`relative`,display:`flex`,alignItems:`center`},children:[(0,P.jsx)(`input`,{type:`text`,className:`search-input`,placeholder:`Search providers...`,value:e,onChange:e=>t(e.target.value),style:{padding:`6px 12px 6px 32px`,fontSize:`var(--font-sm)`,borderRadius:`var(--radius-md)`,border:`1px solid var(--line)`,background:`var(--surface-input)`,color:`var(--text-primary)`,width:`200px`}}),(0,P.jsx)(`span`,{style:{position:`absolute`,left:`10px`,color:`var(--text-secondary)`,fontSize:`var(--font-sm)`,pointerEvents:`none`},children:`🔍`})]}),(0,P.jsx)($t,{onClick:C})]})}),(0,P.jsxs)(`div`,{className:`providers-screen-layout`,children:[(0,P.jsxs)(`div`,{className:`provider-section`,style:{marginBottom:`var(--space-6)`},children:[(0,P.jsxs)(`div`,{className:`provider-section-title-row`,children:[(0,P.jsx)(`h3`,{children:`Custom Providers (OpenAI/Anthropic Compatible)`}),(0,P.jsx)(`div`,{className:`provider-section-actions`,children:(0,P.jsx)(`button`,{className:`button-primary`,onClick:x,children:`+ Add Provider`})})]}),m.length===0?(0,P.jsx)(`div`,{className:`provider-empty-state`,style:{textAlign:`center`,padding:`var(--space-6)`,border:`1px dashed var(--line)`,borderRadius:`var(--radius-md)`,color:`var(--text-secondary)`,fontSize:`var(--font-sm)`},children:`No custom providers — use buttons above to add OpenAI/Anthropic compatible endpoints`}):(0,P.jsx)(`div`,{className:`providers-small-grid`,children:m.map(e=>(0,P.jsx)(Am,{provider:e,isDisabled:i.has(e.id),onToggle:()=>o(e.id),onClick:()=>y(e.id)},e.id))})]}),(0,P.jsxs)(`div`,{className:`provider-section`,style:{marginBottom:`var(--space-6)`},children:[(0,P.jsxs)(`div`,{className:`provider-section-title-row`,children:[(0,P.jsx)(`h3`,{children:`OAuth Providers`}),(0,P.jsx)(`button`,{className:`button-secondary`,style:{fontSize:`var(--font-xs)`,padding:`4px var(--space-2)`},onClick:()=>S(h),disabled:h.filter(e=>e.configured).length===0,children:`▷ Test All`})]}),h.length===0?(0,P.jsx)(`div`,{style:{color:`var(--text-secondary)`,fontSize:`var(--font-sm)`},children:`No OAuth providers found`}):(0,P.jsx)(`div`,{className:`providers-small-grid`,children:h.map(e=>(0,P.jsx)(Am,{provider:e,isDisabled:i.has(e.id),onToggle:()=>o(e.id),onClick:()=>y(e.id)},e.id))})]}),(0,P.jsxs)(`div`,{className:`provider-section`,style:{marginBottom:`var(--space-6)`},children:[(0,P.jsxs)(`div`,{className:`provider-section-title-row`,children:[(0,P.jsx)(`h3`,{children:`Free Tier Providers`}),(0,P.jsx)(`button`,{className:`button-secondary`,style:{fontSize:`var(--font-xs)`,padding:`4px var(--space-2)`},onClick:()=>S(g),disabled:g.filter(e=>e.configured).length===0,children:`▷ Test All`})]}),g.length===0?(0,P.jsx)(`div`,{style:{color:`var(--text-secondary)`,fontSize:`var(--font-sm)`},children:`No Free Tier providers found`}):(0,P.jsx)(`div`,{className:`providers-small-grid`,children:g.map(e=>(0,P.jsx)(Am,{provider:e,isDisabled:i.has(e.id),onToggle:()=>o(e.id),onClick:()=>y(e.id)},e.id))})]}),(0,P.jsxs)(`div`,{className:`provider-section`,style:{marginBottom:`var(--space-6)`},children:[(0,P.jsxs)(`div`,{className:`provider-section-title-row`,children:[(0,P.jsx)(`h3`,{children:`API Key Providers`}),(0,P.jsx)(`button`,{className:`button-secondary`,style:{fontSize:`var(--font-xs)`,padding:`4px var(--space-2)`},onClick:()=>S(_),disabled:_.filter(e=>e.configured).length===0,children:`▷ Test All`})]}),_.length===0?(0,P.jsx)(`div`,{style:{color:`var(--text-secondary)`,fontSize:`var(--font-sm)`},children:`No API Key providers found`}):(0,P.jsx)(`div`,{className:`providers-small-grid`,children:_.map(e=>(0,P.jsx)(Am,{provider:e,isDisabled:i.has(e.id),onToggle:()=>o(e.id),onClick:()=>y(e.id)},e.id))})]})]})]})}function Mm(){return(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{icon:Ie,title:`Media Providers`,description:`Multimodal, voice, image, and video generation upstreams`}),(0,P.jsx)(V,{title:`Feature Coming Soon`,description:`Extended media provider pool`,tone:`info`,children:(0,P.jsxs)(`div`,{style:{padding:`var(--space-6) var(--space-4)`,textAlign:`center`},children:[(0,P.jsx)(`span`,{style:{fontSize:`3rem`},children:`🎨`}),(0,P.jsx)(`h3`,{style:{margin:`var(--space-3) 0 var(--space-2) 0`,fontSize:`var(--font-lg)`},children:`Extended Multimodal Pipeline`}),(0,P.jsx)(`p`,{style:{margin:`0 auto var(--space-4) auto`,color:`var(--text-secondary)`,fontSize:`var(--font-sm)`,maxWidth:`540px`,lineHeight:`1.6`},children:`Media Providers will allow responses-proxy to handle multimodal requests (audio processing, text-to-speech, DALL-E image generation, and video upstreams) with automatic cost routing and fallback policies.`}),(0,P.jsxs)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:`var(--space-2)`,justifyContent:`center`},children:[(0,P.jsx)(B,{variant:`accent`,children:`Image Tiers`}),(0,P.jsx)(B,{variant:`accent`,children:`Audio Failover`}),(0,P.jsx)(B,{variant:`accent`,children:`Video Upstreams`})]})]})})]})}function Nm(){return(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{icon:Ie,title:`Proxy Pools`,description:`Distributed network proxies and rotating IP pools`}),(0,P.jsx)(V,{title:`Feature Coming Soon`,description:`Network proxy list configuration`,tone:`info`,children:(0,P.jsxs)(`div`,{style:{padding:`var(--space-6) var(--space-4)`,textAlign:`center`},children:[(0,P.jsx)(`span`,{style:{fontSize:`3rem`},children:`🌐`}),(0,P.jsx)(`h3`,{style:{margin:`var(--space-3) 0 var(--space-2) 0`,fontSize:`var(--font-lg)`},children:`Rotating Network IP Pools`}),(0,P.jsx)(`p`,{style:{margin:`0 auto var(--space-4) auto`,color:`var(--text-secondary)`,fontSize:`var(--font-sm)`,maxWidth:`540px`,lineHeight:`1.6`},children:`Proxy Pools will enable routing upstream provider requests through a configured list of residential or datacenter web proxies. This prevents rate-limiting and geographical blocks from impacting high-frequency developer workflows.`}),(0,P.jsxs)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:`var(--space-2)`,justifyContent:`center`},children:[(0,P.jsx)(B,{variant:`accent`,children:`Rotating Proxies`}),(0,P.jsx)(B,{variant:`accent`,children:`IP Health Check`}),(0,P.jsx)(B,{variant:`accent`,children:`Geo-Targeting`})]})]})})]})}function Pm({providerId:e,authType:t,connectionFlow:n,connecting:r,error:i,onStartConnection:a,onCompleteConnection:o,onCancel:s,validationResult:c=null,validating:l=!1}){let[u,d]=(0,v.useState)(`start`),[f,p]=(0,v.useState)(``),[m,h]=(0,v.useState)(``),[g,_]=(0,v.useState)(``),[y,b]=(0,v.useState)(!1),[x,S]=(0,v.useState)(null),[C,w]=(0,v.useState)(`picker`),[T,E]=(0,v.useState)(`builder_id`),[D,O]=(0,v.useState)(``),[ee,k]=(0,v.useState)(`us-east-1`),[te,ne]=(0,v.useState)(null),[re,ie]=(0,v.useState)(``),[ae,A]=(0,v.useState)(``),[j,oe]=(0,v.useState)(``),[se,ce]=(0,v.useState)(5),[le,M]=(0,v.useState)(null),N=(0,v.useRef)(null),ue=n?.type===`kiro`;(0,v.useEffect)(()=>{u===`start`&&n&&(ue?(w(`picker`),d(`device_login`)):t===`api_key`&&n.type===`api_key`?d(`callback`):t===`oauth`&&n.type===`oauth`&&d(`authorize`))},[u,n,t,ue]),(0,v.useEffect)(()=>()=>{N.current&&=(clearInterval(N.current),null)},[u]);let de=(0,v.useCallback)(()=>{N.current&&=(clearInterval(N.current),null)},[]),fe=(0,v.useCallback)(async()=>{try{S(null),M(null),b(!0);let e={authMethod:T};T===`idc`&&(e.startUrl=D.trim(),e.region=ee.trim());let t=await Oe(e);ne(t.sessionId),ie(t.userCode),A(t.verificationUri),oe(t.verificationUriComplete),ce(t.interval),w(`waiting`)}catch(e){M(e instanceof Error?e.message:`Failed to start device login`),w(`error`)}finally{b(!1)}},[T,D,ee]);(0,v.useEffect)(()=>{if(u!==`device_login`||C!==`waiting`||!te)return;let e=async()=>{try{let t=await ke(te);t.status===`pending`?t.interval&&t.interval!==se&&(ce(t.interval),de(),N.current=setInterval(e,t.interval*1e3)):t.status===`completed`?(de(),w(`done`),await o({kiroDeviceLogin:!0,accountId:t.account?.id}),d(`complete`)):t.status===`expired`?(de(),M(`Login expired. Please try again.`),w(`error`)):t.status===`error`&&(de(),M(t.error?.message||`Device login failed.`),w(`error`))}catch(e){de(),M(e instanceof Error?e.message:`Polling failed.`),w(`error`)}};return N.current=setInterval(e,se*1e3),()=>{de()}},[u,C,te,se,de,o]);let pe=(0,v.useCallback)(async()=>{try{if(S(null),ue){d(`device_login`),w(`picker`);return}await a(t),t===`oauth`?d(`authorize`):t===`api_key`&&d(`callback`)}catch(e){console.error(`Failed to start connection:`,e),S(e instanceof Error?e.message:`Failed to start connection`)}},[t,ue,a]),me=(0,v.useCallback)(async()=>{if(f.trim())try{b(!0),S(null),await o({callbackUrl:f.trim(),state:n?.state}),d(`complete`)}catch(e){console.error(`Failed to complete OAuth:`,e),S(e instanceof Error?e.message:`Failed to complete OAuth connection`)}finally{b(!1)}},[f,n?.state,o]),he=(0,v.useCallback)(async()=>{if(m.trim())try{b(!0),S(null),await o({apiKey:m.trim(),keyName:g.trim()||`API Key`}),d(`complete`)}catch(e){console.error(`Failed to add API key:`,e),S(e instanceof Error?e.message:`Failed to add API key connection`)}finally{b(!1)}},[m,g,o]),ge=()=>(0,P.jsxs)(`div`,{className:`connection-flow-step`,children:[(0,P.jsxs)(`div`,{className:`step-header`,children:[(0,P.jsx)(`h3`,{children:`Connect New Account`}),(0,P.jsx)(`p`,{children:`Add a new ${t===`oauth`?`OAuth`:`API key`} account to this provider.`})]}),(0,P.jsxs)(`div`,{className:`step-content`,children:[t===`oauth`&&(0,P.jsxs)(`div`,{className:`auth-info`,children:[(0,P.jsx)(`div`,{className:`auth-type-badge`,children:(0,P.jsx)(B,{variant:`accent`,size:`sm`,children:`OAuth`})}),(0,P.jsx)(`p`,{children:`This will start an OAuth flow to connect your account securely.`})]}),t===`api_key`&&(0,P.jsxs)(`div`,{className:`auth-info`,children:[(0,P.jsx)(`div`,{className:`auth-type-badge`,children:(0,P.jsx)(B,{variant:`neutral`,size:`sm`,children:`API Key`})}),(0,P.jsx)(`p`,{children:`Enter your API key to connect this provider.`})]}),(i||x)&&(0,P.jsxs)(`div`,{className:`connection-error`,children:[(0,P.jsx)(Je,{className:`error-icon`}),(0,P.jsx)(`span`,{children:i||x})]})]}),(0,P.jsxs)(`div`,{className:`step-actions`,children:[(0,P.jsx)(`button`,{className:`button-secondary`,onClick:s,disabled:r,children:`Cancel`}),(0,P.jsx)(`button`,{className:`button-primary`,onClick:pe,disabled:r,children:r?`Starting...`:`Start Connection`})]})]}),_e=()=>C===`picker`?(0,P.jsxs)(`div`,{className:`connection-flow-step`,children:[(0,P.jsxs)(`div`,{className:`step-header`,children:[(0,P.jsx)(`h3`,{children:`Sign In with Device Code`}),(0,P.jsx)(`p`,{children:`Choose your authentication method to connect a Kiro account.`})]}),(0,P.jsxs)(`div`,{className:`step-content`,children:[(0,P.jsxs)(`div`,{className:`form-group`,children:[(0,P.jsx)(`label`,{children:`Authentication Method`}),(0,P.jsxs)(`div`,{className:`auth-method-cards`,children:[(0,P.jsxs)(`button`,{type:`button`,className:`auth-method-card ${T===`builder_id`?`selected`:``}`,onClick:()=>E(`builder_id`),children:[(0,P.jsx)(`strong`,{children:`AWS Builder ID`}),(0,P.jsx)(`span`,{children:`Personal account`})]}),(0,P.jsxs)(`button`,{type:`button`,className:`auth-method-card ${T===`idc`?`selected`:``}`,onClick:()=>E(`idc`),children:[(0,P.jsx)(`strong`,{children:`IAM Identity Center`}),(0,P.jsx)(`span`,{children:`Enterprise`})]})]})]}),T===`idc`&&(0,P.jsxs)(P.Fragment,{children:[(0,P.jsxs)(`div`,{className:`form-group`,children:[(0,P.jsx)(`label`,{htmlFor:`deviceStartUrl`,children:`Start URL *`}),(0,P.jsx)(`input`,{id:`deviceStartUrl`,type:`text`,className:`form-input`,placeholder:`https://my-org.awsapps.com/start`,value:D,onChange:e=>O(e.target.value),disabled:y})]}),(0,P.jsxs)(`div`,{className:`form-group`,children:[(0,P.jsx)(`label`,{htmlFor:`deviceRegion`,children:`Region *`}),(0,P.jsx)(`input`,{id:`deviceRegion`,type:`text`,className:`form-input`,placeholder:`us-east-1`,value:ee,onChange:e=>k(e.target.value),disabled:y})]})]}),(le||x)&&(0,P.jsxs)(`div`,{className:`connection-error`,children:[(0,P.jsx)(Je,{className:`error-icon`}),(0,P.jsx)(`span`,{children:le||x})]})]}),(0,P.jsxs)(`div`,{className:`step-actions`,children:[(0,P.jsx)(`button`,{className:`button-secondary`,onClick:()=>d(`start`),disabled:y,children:`Back`}),(0,P.jsx)(`button`,{className:`button-primary`,onClick:fe,disabled:y||T===`idc`&&(!D.trim()||!ee.trim()),children:y?`Starting...`:`Start Device Login`})]})]}):C===`waiting`?(0,P.jsxs)(`div`,{className:`connection-flow-step`,children:[(0,P.jsxs)(`div`,{className:`step-header`,children:[(0,P.jsx)(`h3`,{children:`Enter Code in Browser`}),(0,P.jsx)(`p`,{children:`Enter the code above on the verification page`})]}),(0,P.jsxs)(`div`,{className:`step-content`,children:[(0,P.jsx)(`div`,{className:`device-user-code`,children:re}),(0,P.jsx)(`div`,{className:`auth-url-section`,children:(0,P.jsxs)(`a`,{href:j,target:`_blank`,rel:`noopener noreferrer`,className:`auth-url-link`,children:[(0,P.jsx)(ct,{className:`link-icon`}),`Open verification page`]})}),(0,P.jsxs)(`div`,{className:`connection-validating`,children:[(0,P.jsx)(`span`,{className:`login-spinner`,"aria-hidden":`true`}),(0,P.jsx)(`span`,{children:`Waiting for browser approval...`})]})]}),(0,P.jsx)(`div`,{className:`step-actions`,children:(0,P.jsx)(`button`,{className:`button-secondary`,onClick:()=>{de(),s()},children:`Cancel`})})]}):C===`error`?(0,P.jsxs)(`div`,{className:`connection-flow-step`,children:[(0,P.jsxs)(`div`,{className:`step-header`,children:[(0,P.jsx)(`h3`,{children:`Device Login Failed`}),(0,P.jsx)(`p`,{children:`Something went wrong during the device login flow.`})]}),(0,P.jsx)(`div`,{className:`step-content`,children:(0,P.jsxs)(`div`,{className:`connection-error`,children:[(0,P.jsx)(Je,{className:`error-icon`}),(0,P.jsx)(`span`,{children:le||`An unknown error occurred.`})]})}),(0,P.jsxs)(`div`,{className:`step-actions`,children:[(0,P.jsx)(`button`,{className:`button-secondary`,onClick:s,children:`Cancel`}),(0,P.jsx)(`button`,{className:`button-primary`,onClick:()=>{M(null),w(`picker`)},children:`Try Again`})]})]}):(0,P.jsxs)(`div`,{className:`connection-flow-step`,children:[(0,P.jsxs)(`div`,{className:`step-header`,children:[(0,P.jsx)(qe,{className:`success-icon`}),(0,P.jsx)(`h3`,{children:`Device Login Successful`}),(0,P.jsx)(`p`,{children:`Your Kiro account has been connected.`})]}),(0,P.jsx)(`div`,{className:`step-content`,children:(0,P.jsx)(`div`,{className:`success-message`,children:(0,P.jsx)(`p`,{children:`Account connected successfully via device code flow.`})})}),(0,P.jsx)(`div`,{className:`step-actions`,children:(0,P.jsx)(`button`,{className:`button-primary`,onClick:s,children:`Done`})})]}),ve=()=>(0,P.jsxs)(`div`,{className:`connection-flow-step`,children:[(0,P.jsxs)(`div`,{className:`step-header`,children:[(0,P.jsx)(`h3`,{children:`Authorize Account`}),(0,P.jsx)(`p`,{children:`Click the link below to authorize with the provider.`})]}),(0,P.jsxs)(`div`,{className:`step-content`,children:[n?.authUrl&&(0,P.jsxs)(`div`,{className:`auth-url-section`,children:[(0,P.jsx)(`div`,{className:`auth-url-container`,children:(0,P.jsxs)(`a`,{href:n.authUrl,target:`_blank`,rel:`noopener noreferrer`,className:`auth-url-link`,children:[(0,P.jsx)(ct,{className:`link-icon`}),`Open Authorization Page`]})}),(0,P.jsx)(`p`,{className:`auth-instructions`,children:n.instructions||`Complete the authorization and return here.`})]}),n?.requiresCallback&&(0,P.jsxs)(`div`,{className:`callback-section`,children:[(0,P.jsx)(`p`,{children:`After authorizing, you'll be redirected to a callback URL. Copy and paste that URL below:`}),(0,P.jsx)(`button`,{className:`button-secondary`,onClick:()=>d(`callback`),children:`I've Completed Authorization`})]})]}),(0,P.jsx)(`div`,{className:`step-actions`,children:(0,P.jsx)(`button`,{className:`button-secondary`,onClick:s,children:`Cancel`})})]}),ye=()=>t===`api_key`?(0,P.jsxs)(`div`,{className:`connection-flow-step`,children:[(0,P.jsxs)(`div`,{className:`step-header`,children:[(0,P.jsx)(`h3`,{children:`Enter API Key`}),(0,P.jsx)(`p`,{children:`Provide your API key and an optional name for this connection.`})]}),(0,P.jsxs)(`div`,{className:`step-content`,children:[(0,P.jsxs)(`div`,{className:`form-group`,children:[(0,P.jsx)(`label`,{htmlFor:`apiKey`,children:`API Key *`}),(0,P.jsx)(`input`,{id:`apiKey`,type:`password`,className:`form-input`,placeholder:`Enter your API key...`,value:m,onChange:e=>h(e.target.value),disabled:y})]}),(0,P.jsxs)(`div`,{className:`form-group`,children:[(0,P.jsx)(`label`,{htmlFor:`apiKeyName`,children:`Key Name (Optional)`}),(0,P.jsx)(`input`,{id:`apiKeyName`,type:`text`,className:`form-input`,placeholder:`e.g., Production Key, Development Key`,value:g,onChange:e=>_(e.target.value),disabled:y})]}),(i||x)&&(0,P.jsxs)(`div`,{className:`connection-error`,children:[(0,P.jsx)(Je,{className:`error-icon`}),(0,P.jsx)(`span`,{children:i||x})]})]}),(0,P.jsxs)(`div`,{className:`step-actions`,children:[(0,P.jsx)(`button`,{className:`button-secondary`,onClick:s,disabled:y,children:`Cancel`}),(0,P.jsx)(`button`,{className:`button-primary`,onClick:he,disabled:!m.trim()||y,children:y?`Adding...`:`Add API Key`})]})]}):(0,P.jsxs)(`div`,{className:`connection-flow-step`,children:[(0,P.jsxs)(`div`,{className:`step-header`,children:[(0,P.jsx)(`h3`,{children:`Complete Authorization`}),(0,P.jsx)(`p`,{children:`Paste the callback URL you were redirected to after authorization.`})]}),(0,P.jsxs)(`div`,{className:`step-content`,children:[(0,P.jsxs)(`div`,{className:`form-group`,children:[(0,P.jsx)(`label`,{htmlFor:`callbackUrl`,children:`Callback URL *`}),(0,P.jsx)(`textarea`,{id:`callbackUrl`,className:`form-textarea`,placeholder:`Paste the full callback URL here...`,value:f,onChange:e=>p(e.target.value),disabled:y,rows:3})]}),(0,P.jsxs)(`div`,{className:`callback-help`,children:[(0,P.jsx)(`p`,{children:`The callback URL should look something like:`}),(0,P.jsx)(`code`,{children:`https://chat.openai.com/auth/callback?code=...`})]}),(i||x)&&(0,P.jsxs)(`div`,{className:`connection-error`,children:[(0,P.jsx)(Je,{className:`error-icon`}),(0,P.jsx)(`span`,{children:i||x})]})]}),(0,P.jsxs)(`div`,{className:`step-actions`,children:[(0,P.jsx)(`button`,{className:`button-secondary`,onClick:()=>d(`authorize`),disabled:y,children:`Back`}),(0,P.jsx)(`button`,{className:`button-primary`,onClick:me,disabled:!f.trim()||y,children:y?`Completing...`:`Complete Connection`})]})]}),be=e=>(0,P.jsx)(`ul`,{className:`validation-check-list`,children:[{label:`Authentication`,ok:e.authOk},{label:`Quota`,ok:e.quotaOk},{label:`Model access`,ok:e.modelOk},{label:`Routing`,ok:e.routingOk}].map(e=>(0,P.jsxs)(`li`,{className:e.ok?`check-pass`:`check-fail`,children:[e.ok?(0,P.jsx)(qe,{className:`success-icon`}):(0,P.jsx)(Je,{className:`error-icon`}),(0,P.jsxs)(`span`,{children:[e.label,`: `,e.ok?`Passed`:`Did not pass`]})]},e.label))}),xe=()=>(0,P.jsx)(`div`,{className:`step-actions`,children:(0,P.jsx)(`button`,{className:`button-primary`,onClick:s,children:`Done`})});return r&&!n?(0,P.jsx)(`div`,{className:`connection-flow`,children:(0,P.jsx)(jt,{title:`Starting connection`,description:`Preparing account connection flow...`,cards:1})}):(0,P.jsx)(`div`,{className:`connection-flow`,children:(0,P.jsxs)(`div`,{className:`connection-flow-container`,children:[u===`start`&&ge(),u===`authorize`&&ve(),u===`callback`&&ye(),u===`device_login`&&_e(),u===`complete`&&(()=>{if(l)return(0,P.jsxs)(`div`,{className:`connection-flow-step`,children:[(0,P.jsxs)(`div`,{className:`step-header`,children:[(0,P.jsx)(`h3`,{children:`Verifying connection`}),(0,P.jsx)(`p`,{children:`Running a quick health check against the new account.`})]}),(0,P.jsx)(`div`,{className:`step-content`,children:(0,P.jsxs)(`div`,{className:`connection-validating`,children:[(0,P.jsx)(`span`,{className:`login-spinner`,"aria-hidden":`true`}),(0,P.jsx)(`span`,{children:`Verifying connection...`})]})}),xe()]});if(c){if(c.status===`success`){let e=typeof c.latencyMs==`number`?` (${c.latencyMs}ms)`:``;return(0,P.jsxs)(`div`,{className:`connection-flow-step`,children:[(0,P.jsxs)(`div`,{className:`step-header`,children:[(0,P.jsx)(qe,{className:`success-icon`}),(0,P.jsx)(`h3`,{children:`Connection Verified`}),(0,P.jsx)(`p`,{children:`Connected successfully${e}.`})]}),(0,P.jsx)(`div`,{className:`step-content`,children:(0,P.jsx)(`div`,{className:`success-message`,children:(0,P.jsx)(`p`,{children:`The new account responded to a health check and is ready to use.`})})}),xe()]})}return c.status===`partial`?(0,P.jsxs)(`div`,{className:`connection-flow-step`,children:[(0,P.jsxs)(`div`,{className:`step-header`,children:[(0,P.jsx)(qe,{className:`success-icon`}),(0,P.jsx)(`h3`,{children:`Connection Saved — Partial Check`}),(0,P.jsx)(`p`,{children:`Your account was saved, but some health checks did not pass.`})]}),(0,P.jsx)(`div`,{className:`step-content`,children:(0,P.jsxs)(`div`,{className:`connection-notice`,children:[(0,P.jsx)(`p`,{children:`Health check results:`}),c.checks&&be(c.checks)]})}),xe()]}):c.status===`timeout`?(0,P.jsxs)(`div`,{className:`connection-flow-step`,children:[(0,P.jsxs)(`div`,{className:`step-header`,children:[(0,P.jsx)(Je,{className:`error-icon`}),(0,P.jsx)(`h3`,{children:`Connection Saved — Validation Timed Out`}),(0,P.jsx)(`p`,{children:`Your account was saved, but we couldn't verify it in time.`})]}),(0,P.jsx)(`div`,{className:`step-content`,children:(0,P.jsxs)(`div`,{className:`connection-warning`,children:[(0,P.jsx)(Je,{className:`error-icon`}),(0,P.jsx)(`span`,{children:`Validation timed out. Test manually.`})]})}),xe()]}):(0,P.jsxs)(`div`,{className:`connection-flow-step`,children:[(0,P.jsxs)(`div`,{className:`step-header`,children:[(0,P.jsx)(Je,{className:`error-icon`}),(0,P.jsx)(`h3`,{children:`Connection Saved — Validation Failed`}),(0,P.jsx)(`p`,{children:`Your account was saved, but the health check did not pass.`})]}),(0,P.jsx)(`div`,{className:`step-content`,children:(0,P.jsxs)(`div`,{className:`connection-warning`,children:[(0,P.jsx)(Je,{className:`error-icon`}),(0,P.jsxs)(`div`,{className:`connection-warning-body`,children:[(0,P.jsx)(`span`,{children:c.errorMessage||`Validation failed.`}),c.suggestedFix&&(0,P.jsx)(`span`,{className:`connection-warning-fix`,children:c.suggestedFix})]})]})}),xe()]})}return(0,P.jsxs)(`div`,{className:`connection-flow-step`,children:[(0,P.jsxs)(`div`,{className:`step-header`,children:[(0,P.jsx)(qe,{className:`success-icon`}),(0,P.jsx)(`h3`,{children:`Connection Successful`}),(0,P.jsx)(`p`,{children:`Your account has been connected successfully.`})]}),(0,P.jsx)(`div`,{className:`step-content`,children:(0,P.jsx)(`div`,{className:`success-message`,children:(0,P.jsx)(`p`,{children:`The new account is now available for this provider and will be included in the routing configuration.`})})}),xe()]})})()]})})}async function Fm(e){if(e===`kiro-ide`||e===`kiro-free`||e===`account-kiro`||e.startsWith(`kiro-`))return Im(e);try{let t=(await b(`/api/providers/${e}`)).provider;if(!t)return[];if(t.authMode===`kiro`)return Im(e);let n=[];switch(t.authMode){case`chatgpt_oauth`:let r=await Lm(e,t);n.push(...r);break;case`api_key`:let i=await Rm(e,t);n.push(...i);break;default:console.warn(`Unknown auth mode: ${t.authMode}`)}return n}catch{return[]}}async function Im(e){try{let t=await b(`/api/kiro/accounts`),n=[];return t.accounts?.forEach(t=>{n.push(Bm(e,t))}),n}catch(e){return console.error(`Failed to fetch Kiro accounts:`,e),[]}}async function Lm(e,t){try{let n=await b(`/api/chatgpt-oauth/status`),r=[];if(t.chatgptAccountId){let i=n.accounts?.find(e=>e.accountId===t.chatgptAccountId);i&&r.push(zm(e,i))}else n.accounts?.forEach(t=>{r.push(zm(e,t))});return r}catch(e){return console.error(`Failed to fetch ChatGPT OAuth accounts:`,e),[]}}async function Rm(e,t){let n=[];return t.providerApiKeys?.forEach((t,r)=>{n.push({id:`api-key-${r}`,providerId:e,authType:`api_key`,status:`connected`,label:`API Key ${r+1}`,routingMode:`round_robin`,metadata:{keyPrefix:t.substring(0,8)+`...`,keyName:`Key ${r+1}`,priority:r}})}),n}function zm(e,t){let n=new Date,r=t.expiresAt?new Date(t.expiresAt):null,i=r&&r<n,a=r&&r.getTime()-n.getTime()<10080*60*1e3,o=`connected`,s=`valid`;return t.disabled?o=`disabled`:i?(o=`expired`,s=`expired`):a&&(s=`expiring`),{id:t.accountId||t.id,providerId:e,authType:`oauth`,status:o,label:t.email||`OAuth Account`,email:t.email,routingMode:`priority`,tokenStatus:s,expiresAt:t.expiresAt,refreshable:!0,lastUsedAt:t.lastRefreshAt,metadata:{accountId:t.accountId,idToken:t.idToken?`[REDACTED]`:void 0}}}function Bm(e,t){let n=t.tokenStatus||`unknown`,r=`connected`;return t.isActive?n===`expired`?r=`expired`:n===`missing`&&(r=`invalid`):r=`disabled`,{id:t.id,providerId:e,authType:`oauth`,status:r,label:t.name||`Kiro Account`,routingMode:`round_robin`,tokenStatus:n,expiresAt:t.expiresAt,refreshable:!0,lastUsedAt:t.updatedAt,metadata:{profileArn:t.providerSpecificData?.profileArn,region:t.providerSpecificData?.region,clientId:t.providerSpecificData?.clientId,authMethod:t.providerSpecificData?.authMethod,startUrl:t.providerSpecificData?.startUrl,priority:t.priority,isActive:t.isActive}}}async function Vm(e,t){try{if(e===`kiro-ide`||e===`kiro-free`||e===`account-kiro`||e.startsWith(`kiro-`)){let n=await Um(t);return{providerId:e,accountId:t,status:n.success?`success`:`failed`,testedAt:new Date().toISOString(),latencyMs:n.latencyMs,authOk:n.authOk!==!1,quotaOk:n.quotaOk!==!1,modelOk:n.modelOk!==!1,routingOk:n.routingOk!==!1,testedModel:n.testedModel,errorCode:n.errorCode,errorMessage:n.errorMessage,suggestedFix:n.suggestedFix}}let n=(await b(`/api/providers/${e}`)).provider;if(!n)throw Error(`Provider not found`);let r;switch(n.authMode){case`chatgpt_oauth`:r=await Hm(t);break;case`kiro`:r=await Um(t);break;case`api_key`:r=await Wm(e,t);break;default:throw Error(`Unsupported auth mode: ${n.authMode}`)}return{providerId:e,accountId:t,status:r.success?`success`:`failed`,testedAt:new Date().toISOString(),latencyMs:r.latencyMs,authOk:r.authOk!==!1,quotaOk:r.quotaOk!==!1,modelOk:r.modelOk!==!1,routingOk:r.routingOk!==!1,testedModel:r.testedModel,errorCode:r.errorCode,errorMessage:r.errorMessage,suggestedFix:r.suggestedFix}}catch(n){return{providerId:e,accountId:t,status:`failed`,testedAt:new Date().toISOString(),authOk:!1,quotaOk:!1,modelOk:!1,routingOk:!1,errorMessage:n instanceof Error?n.message:`Test failed`,suggestedFix:`Check account configuration and try again`}}}async function Hm(e){try{return await x(`/api/account-auth/accounts/${e}/test`,`POST`,{})}catch(e){return{success:!1,authOk:!1,errorMessage:e instanceof Error?e.message:`OAuth test failed`,suggestedFix:`Try refreshing the account tokens`}}}async function Um(e){try{let t=Date.now();return await x(`/api/kiro/accounts/${e}/refresh`,`POST`,{}),{success:!0,authOk:!0,quotaOk:!0,modelOk:!0,routingOk:!0,latencyMs:Date.now()-t}}catch(e){return{success:!1,authOk:!1,errorMessage:e instanceof Error?e.message:`Kiro test failed`,suggestedFix:`Check Kiro account configuration and refresh tokens`}}}async function Wm(e,t){try{return await x(`/api/providers/${e}/test`,`POST`,{accountId:t})}catch(e){return{success:!1,authOk:!1,errorMessage:e instanceof Error?e.message:`API key test failed`,suggestedFix:`Verify API key is valid and has necessary permissions`}}}async function Gm(e,t,n){if(e===`kiro-ide`||e===`kiro-free`||e===`account-kiro`||e.startsWith(`kiro-`)){await x(`/api/kiro/accounts/${t}`,`PATCH`,{routingMode:n});return}try{let r=(await b(`/api/providers/${e}`)).provider;if(!r)throw Error(`Provider not found`);switch(r.authMode){case`chatgpt_oauth`:await x(`/api/chatgpt-oauth/settings`,`PATCH`,{rotationMode:Km(n)});break;case`kiro`:await x(`/api/kiro/accounts/${t}`,`PATCH`,{routingMode:n});break;case`api_key`:console.warn(`API key accounts do not support individual routing modes`);break;default:throw Error(`Unsupported auth mode: ${r.authMode}`)}}catch(e){throw console.error(`Failed to update routing mode for account ${t}:`,e),Error(`Failed to update account routing mode`)}}function Km(e){switch(e){case`round_robin`:return`round_robin`;case`priority`:return`first_available`;case`sticky`:return`first_available`;case`failover_only`:return`first_available`;default:return`round_robin`}}async function qm(e,t){if(e===`kiro-ide`||e===`kiro-free`||e===`account-kiro`||e.startsWith(`kiro-`)){await x(`/api/kiro/accounts/${t}/refresh`,`POST`,{});let n=(await Fm(e)).find(e=>e.id===t);if(!n)throw Error(`Account not found after refresh`);return n}try{let n=(await b(`/api/providers/${e}`)).provider;if(!n)throw Error(`Provider not found`);switch(n.authMode){case`chatgpt_oauth`:await x(`/api/account-auth/accounts/${t}/refresh`,`POST`,{});break;case`kiro`:await x(`/api/kiro/accounts/${t}/refresh`,`POST`,{});break;case`api_key`:throw Error(`API key accounts do not support token refresh`);default:throw Error(`Unsupported auth mode: ${n.authMode}`)}let r=(await Fm(e)).find(e=>e.id===t);if(!r)throw Error(`Account not found after refresh`);return r}catch(e){throw console.error(`Failed to refresh account ${t}:`,e),Error(`Failed to refresh account`)}}async function Jm(e,t){if(e===`kiro-ide`||e===`kiro-free`||e===`account-kiro`||e.startsWith(`kiro-`)){await x(`/api/kiro/accounts/${t}`,`DELETE`,{});return}try{let n=(await b(`/api/providers/${e}`)).provider;if(!n)throw Error(`Provider not found`);switch(n.authMode){case`chatgpt_oauth`:await x(`/api/account-auth/accounts/${t}`,`DELETE`,{});break;case`kiro`:await x(`/api/kiro/accounts/${t}`,`DELETE`,{});break;case`api_key`:let r=parseInt(t.replace(`api-key-`,``),10);if(isNaN(r))throw Error(`Invalid account ID for API key: ${t}`);let i=(Array.isArray(n.providerApiKeys)?n.providerApiKeys:[]).filter((e,t)=>t!==r);await x(`/api/providers/${encodeURIComponent(e)}`,`PUT`,{name:n.name,baseUrl:n.baseUrl,authMode:n.authMode,providerApiKeys:i,capabilities:n.capabilities});break;default:throw Error(`Unsupported auth mode: ${n.authMode}`)}}catch(e){throw console.error(`Failed to delete account ${t}:`,e),Error(`Failed to delete account`)}}async function Ym(e,t){try{switch(t){case`oauth`:{let t=null;try{t=(await b(`/api/providers/${e}`)).provider}catch{}let n=Wp(e),r=t?.authMode||n?.preferredAuthType||`api_key`;if(r===`chatgpt_oauth`||e===`openai-codex`||e.includes(`chatgpt`)||e===`account-openai-codex`){let e=await x(`/api/chatgpt-oauth/start`,`POST`,{});return{type:`oauth`,authUrl:e.authUrl,state:e.state,instructions:`Click the link to authorize with ChatGPT, then paste the callback URL below.`,requiresCallback:!0}}else if(r===`kiro`||e.startsWith(`kiro-`))return{type:`kiro`,instructions:`Kiro accounts are imported from a 9router database. The proxy then owns token refresh (write-back) without sharing 9router's live database.`,requiresCallback:!1};throw Error(`OAuth authentication is not supported for this provider on the backend. Please use API Key authentication instead.`)}case`api_key`:return{type:`api_key`,instructions:`Enter your API key below. Make sure it has the necessary permissions for this provider.`,requiresCallback:!1};default:throw Error(`Unsupported auth type: ${t}`)}}catch(e){throw console.error(`Failed to start connection flow for ${t}:`,e),e instanceof Error?e:Error(`Failed to start account connection`)}}function Xm(e){let[t,n]=(0,v.useState)([]),[r,i]=(0,v.useState)(!1),[a,o]=(0,v.useState)(null),[s,c]=(0,v.useState)(null),l=(0,v.useCallback)(async()=>{if(!e){n([]),i(!1),o(null);return}try{i(!0),o(null),n(await Fm(e)),c(new Date)}catch(e){o(e instanceof Error?e.message:`Failed to load accounts`),n([])}finally{i(!1)}},[e]);(0,v.useEffect)(()=>{l()},[l]);let u=(0,v.useCallback)(async()=>{await l()},[l]);return{accounts:t,loading:r,error:a,lastRefresh:s,stats:(0,v.useMemo)(()=>{let e=t.length,n=t.filter(e=>e.status===`connected`).length,r=t.filter(e=>e.status===`expired`).length,i=t.filter(e=>e.tokenStatus===`expiring`).length;return{total:e,connected:n,expired:r,expiring:i,disabled:t.filter(e=>e.status===`disabled`).length,healthy:n,needsAttention:r+i}},[t]),refresh:u}}function Zm(e){let[t,n]=(0,v.useState)(new Map),[r,i]=(0,v.useState)(new Set);return{testAccount:(0,v.useCallback)(async t=>{if(!(!e||r.has(t)))try{i(e=>new Set(e).add(t));let r=await Vm(e,t);return n(e=>new Map(e).set(t,r)),r}catch(r){let i={providerId:e,accountId:t,status:`failed`,testedAt:new Date().toISOString(),authOk:!1,quotaOk:!1,modelOk:!1,routingOk:!1,errorMessage:r instanceof Error?r.message:`Test failed`,suggestedFix:`Check account configuration and try again`};return n(e=>new Map(e).set(t,i)),i}finally{i(e=>{let n=new Set(e);return n.delete(t),n})}},[e,r]),getTestResult:(0,v.useCallback)(e=>t.get(e),[t]),isTestingAccount:(0,v.useCallback)(e=>r.has(e),[r]),clearTestResult:(0,v.useCallback)(e=>{n(t=>{let n=new Map(t);return n.delete(e),n})},[]),clearAllTestResults:(0,v.useCallback)(()=>{n(new Map)},[]),hasTestResults:t.size>0}}function Qm(e){let[t,n]=(0,v.useState)(new Map),[r,i]=(0,v.useState)(null),a=(0,v.useCallback)((e,t)=>{n(n=>new Map(n).set(e,t)),i(null)},[]),o=(0,v.useCallback)(e=>{n(t=>{let n=new Map(t);return n.delete(e),n})},[]);return{updateRoutingMode:(0,v.useCallback)(async(t,n)=>{if(!e)throw Error(`Provider ID is required`);try{a(t,`updating`),await Gm(e,t,n)}catch(e){throw i(e instanceof Error?e.message:`Failed to update routing mode`),e}finally{o(t)}},[e,a,o]),refreshAccount:(0,v.useCallback)(async t=>{if(!e)throw Error(`Provider ID is required`);try{return a(t,`refreshing`),await qm(e,t)}catch(e){throw i(e instanceof Error?e.message:`Failed to refresh account`),e}finally{o(t)}},[e,a,o]),deleteAccount:(0,v.useCallback)(async t=>{if(!e)throw Error(`Provider ID is required`);try{a(t,`deleting`),await Jm(e,t)}catch(e){throw i(e instanceof Error?e.message:`Failed to delete account`),e}finally{o(t)}},[e,a,o]),isAccountLoading:(0,v.useCallback)(e=>t.has(e),[t]),getAccountOperation:(0,v.useCallback)(e=>t.get(e),[t]),operationError:r,clearError:(0,v.useCallback)(()=>{i(null)},[])}}function $m(e){let[t,n]=(0,v.useState)(null),[r,i]=(0,v.useState)(!1),[a,o]=(0,v.useState)(null);return{connectionFlow:t,connecting:r,connectionError:a,startConnection:(0,v.useCallback)(async t=>{if(!e)throw Error(`Provider ID is required`);try{i(!0),o(null);let r=await Ym(e,t);return n(r),r}catch(e){throw o(e instanceof Error?e.message:`Failed to start connection`),e}finally{i(!1)}},[e]),clearConnectionFlow:(0,v.useCallback)(()=>{n(null),o(null)},[]),clearError:(0,v.useCallback)(()=>{o(null)},[])}}function eh(e){let t=(0,v.useMemo)(()=>{let t={healthy:0,warning:0,critical:0,total:e.length};return e.forEach(e=>{switch(e.status){case`connected`:e.tokenStatus===`expiring`?t.warning++:t.healthy++;break;case`expired`:case`invalid`:t.critical++;break;case`disabled`:break;default:t.warning++}}),t},[e]),n=(0,v.useMemo)(()=>e.filter(e=>e.tokenStatus===`expiring`||e.expiresAt&&new Date(e.expiresAt).getTime()-Date.now()<10080*60*1e3),[e]),r=(0,v.useMemo)(()=>e.filter(e=>e.status===`expired`||e.tokenStatus===`expired`),[e]),i=(0,v.useMemo)(()=>e.filter(e=>e.status===`expired`||e.status===`invalid`||e.status===`needs_reconnect`||e.tokenStatus===`expiring`||e.tokenStatus===`expired`),[e]);return{healthSummary:t,expiringAccounts:n,expiredAccounts:r,needsAttentionAccounts:i,hasHealthIssues:i.length>0}}async function th({providerId:e,apiKey:t}){let n=Wp(e);if(!n)throw Error(`Provider ${e} not found in catalog.`);let r={id:e,name:n.name,baseUrl:n.defaultBaseUrl||`https://api.example.com`,authMode:`api_key`,providerApiKeys:[t],capabilities:{transportMode:`chat_completions`}};try{await O(r)}catch(n){let r=n instanceof Error?n.message:String(n);if(r.includes(`already assigned to another provider`))throw Error(`This API key is already registered with a different provider. Remove it from that provider first.`);if(r.includes(`already exists`)){await nh(e,t);return}throw n}}async function nh(e,t){let n=(await b(`/api/providers/${encodeURIComponent(e)}`)).provider;if(!n)throw Error(`Provider ${e} reported as existing but could not be fetched.`);let r=Array.isArray(n.providerApiKeys)?n.providerApiKeys:[];if(!r.includes(t))try{await ee(e,{name:n.name??``,baseUrl:n.baseUrl??``,authMode:n.authMode??`api_key`,providerApiKeys:[...r,t],capabilities:n.capabilities})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to add API key to existing provider: ${t}`)}}var rh=`__TIMEOUT__`,ih=1e4;function ah(e){let t={authOk:e.authOk,quotaOk:e.quotaOk,modelOk:e.modelOk,routingOk:e.routingOk};return e.status===`success`?{status:`success`,latencyMs:e.latencyMs,checks:t}:e.status===`partial`?{status:`partial`,latencyMs:e.latencyMs,checks:t}:{status:`failed`,errorMessage:e.errorMessage,suggestedFix:e.suggestedFix,checks:t}}async function oh(e,t,n=ih){let r,i=Vm(e,t),a=new Promise((e,t)=>{r=setTimeout(()=>t(Error(rh)),n)});try{return ah(await Promise.race([i,a]))}catch(e){return e instanceof Error&&e.message===rh?{status:`timeout`}:{status:`failed`,errorMessage:e instanceof Error?e.message:`Validation failed`,suggestedFix:`Try testing the connection manually from the accounts list.`}}finally{r!==void 0&&clearTimeout(r)}}function sh({providerId:e,providerName:t,supportedAuthTypes:n,accounts:r,isOpen:i,mode:a,editingAccount:o,onClose:s,onAccountsChanged:c}){let[l,u]=(0,v.useState)(n[0]),[d,f]=(0,v.useState)(!1),[p,m]=(0,v.useState)(!1),[h,g]=(0,v.useState)(null),{connectionFlow:_,connecting:y,connectionError:x,startConnection:S,clearConnectionFlow:C,clearError:w}=$m(e),{updateRoutingMode:T,refreshAccount:E,deleteAccount:D,isAccountLoading:O,getAccountOperation:k,operationError:te,clearError:ne}=Qm(e);(0,v.useEffect)(()=>{i&&(C(),w(),ne(),f(!1),m(!1),g(null),o&&u(o.authType))},[i,o,C,w,ne]);let re=(0,v.useCallback)(async e=>{try{await S(e)}catch(e){console.error(`Failed to start connection:`,e)}},[S]),ie=(0,v.useCallback)(async t=>{m(!0),g(null);try{g(await oh(e,t))}finally{m(!1)}},[e]),ae=(0,v.useCallback)(async t=>{try{let n=null;if(t.kiroImport){let e=await Ce(t.sourcePath?{sourcePath:t.sourcePath}:void 0);if(e.imported===0)throw Error(`No Kiro accounts were found in the source database. Sign in through 9router first.`);if(e.imported===1)try{n=(await ye()).accounts?.[0]?.id??null}catch(e){console.warn(`Could not resolve imported Kiro account for validation:`,e)}}else if(t.callbackUrl)n=(await N({redirectUrl:t.callbackUrl})).account?.accountId??null;else if(t.apiKey){let r=t.apiKey,i=null;try{let t=await b(`/api/providers/${encodeURIComponent(e)}`);t.ok&&t.provider&&(i=t.provider)}catch(e){console.log(`Provider does not exist on backend:`,e)}if(!i)await th({providerId:e,apiKey:r}),n=`api-key-0`;else{let t=Array.isArray(i.providerApiKeys)?i.providerApiKeys:[];t.includes(r)?n=`api-key-${t.indexOf(r)}`:(n=`api-key-${t.length}`,await ee(e,{name:i.name??``,baseUrl:i.baseUrl??``,authMode:i.authMode??`api_key`,providerApiKeys:[...t,r],capabilities:i.capabilities}))}}c(),n&&ie(n)}catch(e){throw console.error(`Failed to complete connection:`,e),e}},[e,c,ie]),A=(0,v.useCallback)(async(e,t)=>{try{await T(e,t),c()}catch(e){console.error(`Failed to update routing mode:`,e)}},[T,c]),j=(0,v.useCallback)(async e=>{try{await E(e),c()}catch(e){console.error(`Failed to refresh account:`,e)}},[E,c]),oe=(0,v.useCallback)(async e=>{try{await D(e),c(),f(!1),a===`edit`&&s()}catch(e){console.error(`Failed to delete account:`,e)}},[D,c,a,s]),[se,ce]=(0,v.useState)(``),[le,M]=(0,v.useState)(``),[ue,de]=(0,v.useState)(`idle`),[fe,pe]=(0,v.useState)(!1),[me,he]=(0,v.useState)(null);(0,v.useEffect)(()=>{i&&a===`add`&&(ce(``),M(``),de(`idle`),pe(!1),he(null))},[i,a]);let ge=(0,v.useCallback)(async()=>{if(le.trim()){pe(!0),he(null);try{await ae({apiKey:le.trim(),keyName:se.trim()||`API Key`})}catch(e){he(e instanceof Error?e.message:`Failed to save`)}finally{pe(!1)}}},[le,se,ae]),_e=n.length===1&&n[0]===`api_key`,ve=n.includes(`oauth`)||_?.type===`kiro`,be=(0,v.useRef)(!1);return(0,v.useEffect)(()=>{i&&a===`add`&&ve&&!_&&!be.current&&(be.current=!0,re(n.includes(`oauth`)?`oauth`:n[0])),i||(be.current=!1)},[i,a,ve,n,_,re]),i?(0,P.jsx)(`div`,{className:`modal-backdrop`,onClick:s,children:(0,P.jsxs)(`div`,{className:`modal-card account-management-modal`,onClick:e=>e.stopPropagation(),children:[a===`add`&&(_e?!fe&&!me&&h?(0,P.jsxs)(`div`,{className:`account-modal-content`,children:[(0,P.jsx)(`div`,{className:`modal-header`,children:(0,P.jsx)(`h2`,{children:`Account Added`})}),(0,P.jsx)(`div`,{className:`step-content`,children:(0,P.jsx)(`div`,{className:`add-key-badge ${h.status===`success`?`valid`:`warning`}`,children:h.status===`success`?(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(qe,{className:`success-icon`}),` Connected`,h.latencyMs?` (${h.latencyMs}ms)`:``]}):(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(Je,{className:`error-icon`}),` Saved — `,h.errorMessage||`verify manually`]})})}),(0,P.jsx)(`div`,{className:`modal-actions`,children:(0,P.jsx)(`button`,{className:`button-primary`,onClick:s,children:`Done`})})]}):p?(0,P.jsxs)(`div`,{className:`account-modal-content`,children:[(0,P.jsx)(`div`,{className:`modal-header`,children:(0,P.jsx)(`h2`,{children:`Verifying...`})}),(0,P.jsxs)(`div`,{className:`connection-validating`,style:{padding:`var(--space-4)`,justifyContent:`center`},children:[(0,P.jsx)(`span`,{className:`login-spinner`,"aria-hidden":`true`}),(0,P.jsx)(`span`,{children:`Verifying connection...`})]}),(0,P.jsx)(`div`,{className:`modal-actions`,children:(0,P.jsx)(`button`,{className:`button-secondary`,onClick:s,children:`Done`})})]}):(0,P.jsxs)(`div`,{className:`account-modal-content`,children:[(0,P.jsx)(`div`,{className:`modal-header`,children:(0,P.jsxs)(`h2`,{children:[`Add `,t,` API Key`]})}),(0,P.jsxs)(`div`,{className:`add-key-form`,children:[(0,P.jsxs)(`div`,{className:`form-group`,children:[(0,P.jsx)(`label`,{htmlFor:`add-key-name`,className:`form-label`,children:`Name`}),(0,P.jsx)(`input`,{id:`add-key-name`,type:`text`,className:`form-input`,placeholder:`Production Key`,value:se,onChange:e=>ce(e.target.value),disabled:fe})]}),(0,P.jsxs)(`div`,{className:`form-group`,children:[(0,P.jsx)(`label`,{htmlFor:`add-key-value`,className:`form-label`,children:`API Key`}),(0,P.jsx)(`div`,{className:`form-input-row`,children:(0,P.jsx)(`input`,{id:`add-key-value`,type:`password`,className:`form-input`,placeholder:`sk-...`,value:le,onChange:e=>{M(e.target.value),de(`idle`)},disabled:fe})})]}),ue===`valid`&&(0,P.jsxs)(`div`,{className:`add-key-badge valid`,children:[(0,P.jsx)(qe,{className:`success-icon`}),` Valid`]}),ue===`invalid`&&(0,P.jsxs)(`div`,{className:`add-key-badge invalid`,children:[(0,P.jsx)(Je,{className:`error-icon`}),` Invalid`]}),me&&(0,P.jsxs)(`div`,{className:`connection-error`,children:[(0,P.jsx)(Je,{className:`error-icon`}),(0,P.jsx)(`span`,{children:me})]})]}),(0,P.jsxs)(`div`,{className:`modal-actions`,children:[(0,P.jsx)(`button`,{className:`button-secondary`,onClick:s,disabled:fe,children:`Cancel`}),(0,P.jsx)(`button`,{className:`button-primary`,onClick:ge,disabled:!le.trim()||fe,children:fe?`Saving...`:`Save`})]})]}):_?(0,P.jsx)(`div`,{className:`account-modal-content`,children:(0,P.jsx)(Pm,{providerId:e,authType:l,connectionFlow:_,connecting:y,error:x,onStartConnection:re,onCompleteConnection:ae,onCancel:s,validating:p,validationResult:h})}):n.length>1&&!ve?(0,P.jsxs)(`div`,{className:`account-modal-content`,children:[(0,P.jsxs)(`div`,{className:`modal-header`,children:[(0,P.jsxs)(`h2`,{children:[`Add Account to `,t]}),(0,P.jsx)(`p`,{children:`Choose how to connect.`})]}),(0,P.jsx)(`div`,{className:`auth-type-options`,children:n.map(e=>(0,P.jsx)(`button`,{className:`auth-type-option ${l===e?`selected`:``}`,onClick:()=>u(e),children:(0,P.jsxs)(`div`,{className:`auth-type-info`,children:[(0,P.jsx)(B,{variant:e===`oauth`?`accent`:`neutral`,size:`sm`,children:e===`oauth`?`OAuth`:`API Key`}),(0,P.jsxs)(`div`,{className:`auth-type-description`,children:[e===`oauth`&&`Secure OAuth authentication`,e===`api_key`&&`Direct API key authentication`]})]})},e))}),(0,P.jsxs)(`div`,{className:`modal-actions`,children:[(0,P.jsx)(`button`,{className:`button-secondary`,onClick:s,children:`Cancel`}),(0,P.jsx)(`button`,{className:`button-primary`,onClick:()=>re(l),disabled:y,children:y?`Starting...`:`Continue`})]})]}):(0,P.jsx)(`div`,{className:`account-modal-content`,children:(0,P.jsxs)(`div`,{className:`connection-validating`,style:{padding:`var(--space-6)`,justifyContent:`center`},children:[(0,P.jsx)(`span`,{className:`login-spinner`,"aria-hidden":`true`}),(0,P.jsx)(`span`,{children:`Preparing connection...`})]})})),a===`edit`&&(o?(0,P.jsxs)(`div`,{className:`account-modal-content`,children:[(0,P.jsxs)(`div`,{className:`modal-header`,children:[(0,P.jsx)(`h2`,{children:`Manage Account`}),(0,P.jsxs)(`p`,{children:[`Configure settings for `,o.label]})]}),(0,P.jsxs)(`div`,{className:`account-details`,children:[(0,P.jsxs)(`div`,{className:`account-info-section`,children:[(0,P.jsx)(`h3`,{children:`Account Information`}),(0,P.jsxs)(`div`,{className:`account-info-grid`,children:[(0,P.jsxs)(`div`,{className:`info-item`,children:[(0,P.jsx)(`label`,{children:`Account Name`}),(0,P.jsx)(`span`,{children:o.label})]}),o.email&&(0,P.jsxs)(`div`,{className:`info-item`,children:[(0,P.jsx)(`label`,{children:`Email`}),(0,P.jsx)(`span`,{children:o.email})]}),(0,P.jsxs)(`div`,{className:`info-item`,children:[(0,P.jsx)(`label`,{children:`Authentication`}),(0,P.jsx)(B,{variant:o.authType===`oauth`?`accent`:`neutral`,size:`sm`,children:o.authType===`oauth`?`OAuth`:`API Key`})]}),(0,P.jsxs)(`div`,{className:`info-item`,children:[(0,P.jsx)(`label`,{children:`Status`}),(0,P.jsx)(B,{variant:o.status===`connected`?`success`:o.status===`expired`?`error`:`warning`,size:`sm`,children:o.status})]})]})]}),(0,P.jsxs)(`div`,{className:`routing-config-section`,children:[(0,P.jsx)(`h3`,{children:`Routing Configuration`}),(0,P.jsxs)(`div`,{className:`routing-mode-selector`,children:[(0,P.jsx)(`label`,{htmlFor:`routingMode`,children:`Routing Mode`}),(0,P.jsxs)(`select`,{id:`routingMode`,value:o.routingMode,onChange:e=>A(o.id,e.target.value),disabled:O(o.id),children:[(0,P.jsx)(`option`,{value:`priority`,children:`Priority (Use first)`}),(0,P.jsx)(`option`,{value:`round_robin`,children:`Round Robin`}),(0,P.jsx)(`option`,{value:`sticky`,children:`Sticky (Session-based)`}),(0,P.jsx)(`option`,{value:`failover_only`,children:`Failover Only`}),(0,P.jsx)(`option`,{value:`disabled`,children:`Disabled`})]})]})]}),o.tokenStatus&&(0,P.jsxs)(`div`,{className:`token-status-section`,children:[(0,P.jsx)(`h3`,{children:`Token Status`}),(0,P.jsxs)(`div`,{className:`token-info`,children:[(0,P.jsx)(B,{variant:o.tokenStatus===`valid`?`success`:o.tokenStatus===`expiring`?`warning`:`error`,size:`sm`,children:o.tokenStatus}),o.expiresAt&&(0,P.jsxs)(`span`,{className:`token-expiry`,children:[`Expires: `,new Date(o.expiresAt).toLocaleString()]})]})]}),(x||te)&&(0,P.jsxs)(`div`,{className:`modal-error`,children:[(0,P.jsx)(Je,{className:`error-icon`}),(0,P.jsx)(`span`,{children:x||te})]})]}),(0,P.jsx)(`div`,{className:`account-actions`,children:(0,P.jsxs)(`div`,{className:`account-action-buttons`,children:[o.refreshable&&(0,P.jsxs)(`button`,{className:`button-secondary`,onClick:()=>j(o.id),disabled:O(o.id),children:[(0,P.jsx)(We,{className:`button-icon`}),k(o.id)===`refreshing`?`Refreshing...`:`Refresh Tokens`]}),(0,P.jsxs)(`button`,{className:`button-danger`,onClick:()=>f(!0),disabled:O(o.id),children:[(0,P.jsx)(st,{className:`button-icon`}),`Delete Account`]})]})}),(0,P.jsx)(`div`,{className:`modal-actions`,children:(0,P.jsx)(`button`,{className:`button-secondary`,onClick:s,children:`Close`})}),d&&(0,P.jsx)(`div`,{className:`delete-confirm-overlay`,children:(0,P.jsxs)(`div`,{className:`delete-confirm-dialog`,children:[(0,P.jsx)(`h3`,{children:`Delete Account`}),(0,P.jsxs)(`p`,{children:[`Are you sure you want to delete "`,o.label,`"? This will remove the account from this provider and cannot be undone.`]}),(0,P.jsxs)(`div`,{className:`delete-confirm-actions`,children:[(0,P.jsx)(`button`,{className:`button-secondary`,onClick:()=>f(!1),disabled:O(o.id),children:`Cancel`}),(0,P.jsx)(`button`,{className:`button-danger`,onClick:()=>oe(o.id),disabled:O(o.id),children:k(o.id)===`deleting`?`Deleting...`:`Delete Account`})]})]})})]}):null),a===`manage`&&(0,P.jsxs)(`div`,{className:`account-modal-content`,children:[(0,P.jsxs)(`div`,{className:`modal-header`,children:[(0,P.jsxs)(`h2`,{children:[`Manage Accounts for `,t]}),(0,P.jsx)(`p`,{children:`Configure all accounts connected to this provider.`})]}),(0,P.jsx)(`div`,{className:`accounts-list`,children:r.length===0?(0,P.jsxs)(`div`,{className:`no-accounts`,children:[(0,P.jsx)(`p`,{children:`No accounts connected to this provider.`}),(0,P.jsx)(`button`,{className:`button-primary`,onClick:()=>re(n[0]),children:`Add First Account`})]}):(0,P.jsx)(`div`,{className:`accounts-grid`,children:r.map(e=>(0,P.jsxs)(`div`,{className:`account-summary-card`,children:[(0,P.jsxs)(`div`,{className:`account-summary-header`,children:[(0,P.jsx)(`div`,{className:`account-name`,children:e.label}),(0,P.jsx)(B,{variant:e.status===`connected`?`success`:e.status===`expired`?`error`:`warning`,size:`sm`,children:e.status})]}),(0,P.jsxs)(`div`,{className:`account-summary-details`,children:[e.email&&(0,P.jsx)(`div`,{className:`account-email`,children:e.email}),(0,P.jsxs)(`div`,{className:`account-routing`,children:[`Routing: `,e.routingMode]})]}),(0,P.jsx)(`div`,{className:`account-summary-actions`,children:(0,P.jsx)(`button`,{className:`button-secondary button-sm`,onClick:()=>{},children:`Edit`})})]},e.id))})}),(0,P.jsxs)(`div`,{className:`modal-actions`,children:[(0,P.jsx)(`button`,{className:`button-secondary`,onClick:s,children:`Close`}),r.length>0&&(0,P.jsx)(`button`,{className:`button-primary`,onClick:()=>re(n[0]),children:`Add Another Account`})]})]})]})}):null}var ch={requireEnabled:!0,requireConfigured:!0,requireHealthy:!0,requireQuotaAvailable:!0,requireActiveAccount:!0,requireServiceKinds:[`chat`],allowDegraded:!0,minimumScore:50};function lh(e,t=ch){let n=[],r=[],i=100,a=!0;if(t.requireEnabled&&!e.enabled&&(a=!1,n.push(`Provider is disabled`),i-=50),t.requireConfigured&&!e.configured&&(a=!1,n.push(`Provider is not configured`),i-=40),t.requireHealthy){let o=uh(e.healthStatus);i=Math.min(i,o),e.healthStatus===`not_configured`?(a=!1,n.push(`Provider is not configured`)):e.healthStatus===`disabled`?(a=!1,n.push(`Provider is disabled`)):e.healthStatus===`auth_expired`?(a=!1,n.push(`Authentication has expired`)):e.healthStatus===`quota_exhausted`?t.requireQuotaAvailable?(a=!1,n.push(`Quota is exhausted`)):r.push(`Quota is exhausted but may recover`):e.healthStatus===`rate_limited`?(r.push(`Provider is currently rate limited`),i-=20):e.healthStatus===`degraded`?t.allowDegraded?(r.push(`Provider is degraded but still usable`),i-=15):(a=!1,n.push(`Provider is degraded and strict health is required`)):e.healthStatus===`unknown`&&(r.push(`Provider health status is unknown`),i-=10)}if(t.requireQuotaAvailable&&e.quota&&(e.quota.hardLimitReached?(a=!1,n.push(`Hard quota limit reached`)):e.quota.softLimitReached?(r.push(`Soft quota limit reached`),i-=10):e.quota.usagePercent&&e.quota.usagePercent>90&&(r.push(`Quota usage is very high (>90%)`),i-=5)),t.requireActiveAccount){let t=dh(e.accounts||[]);if(t.length===0)a=!1,n.push(`No active accounts available`);else{let e=fh(t);i=Math.min(i,e),e<50&&r.push(`Account health is poor`)}}if(t.requireServiceKinds&&t.requireServiceKinds.length>0){let r=t.requireServiceKinds.filter(t=>!e.serviceKinds.includes(t));r.length>0&&(a=!1,n.push(`Missing required services: ${r.join(`, `)}`))}return t.requireServiceKinds?.includes(`chat`)&&(e.models?.filter(e=>e.serviceKind===`chat`&&e.enabled)||[]).length===0&&(a=!1,n.push(`No enabled chat models available`)),t.minimumScore&&i<t.minimumScore&&(a=!1,n.push(`Provider score (${i}) below minimum required (${t.minimumScore})`)),e.fallbackEligible||(a=!1,n.push(`Provider is marked as not fallback eligible`)),{eligible:a,reasons:n,warnings:r,score:Math.max(0,i),lastCheckedAt:new Date().toISOString()}}function uh(e){switch(e){case`healthy`:return 100;case`degraded`:return 75;case`rate_limited`:return 60;case`quota_exhausted`:return 40;case`unknown`:return 50;case`auth_expired`:return 20;case`disabled`:return 0;case`not_configured`:return 0;default:return 50}}function dh(e){return e.filter(e=>e.status===`connected`&&e.routingMode!==`disabled`)}function fh(e){if(e.length===0)return 0;let t=e.map(e=>{switch(e.status){case`connected`:return 100;case`needs_reconnect`:return 60;case`expired`:return 30;case`invalid`:return 20;case`disabled`:return 0;case`unknown`:return 50;default:return 50}});return Math.round(t.reduce((e,t)=>e+t,0)/t.length)}function ph(e){return(0,P.jsx)(`svg`,{viewBox:`0 0 16 16`,width:`14`,height:`14`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,className:e.className,children:(0,P.jsx)(`path`,{d:`M4 10l4-4 4 4`})})}function mh(e){return(0,P.jsx)(`svg`,{viewBox:`0 0 16 16`,width:`14`,height:`14`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,className:e.className,children:(0,P.jsx)(`path`,{d:`M4 6l4 4 4-4`})})}function hh(e){return(0,P.jsxs)(`svg`,{viewBox:`0 0 16 16`,width:`15`,height:`15`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.6`,strokeLinecap:`round`,strokeLinejoin:`round`,className:e.className,children:[(0,P.jsx)(`rect`,{x:`3.5`,y:`7`,width:`9`,height:`6.5`,rx:`1.5`}),(0,P.jsx)(`path`,{d:`M5.5 7V5a2.5 2.5 0 0 1 5 0v2`})]})}function gh(e){return(0,P.jsx)(`svg`,{viewBox:`0 0 16 16`,width:`15`,height:`15`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.6`,strokeLinecap:`round`,strokeLinejoin:`round`,className:e.className,children:(0,P.jsx)(`path`,{d:`M11.5 2.5l2 2L6 12l-2.5.5L4 10z`})})}function _h(e){return(0,P.jsxs)(`svg`,{viewBox:`0 0 16 16`,width:`14`,height:`14`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.6`,strokeLinecap:`round`,strokeLinejoin:`round`,className:e.className,children:[(0,P.jsx)(`rect`,{x:`5.5`,y:`5.5`,width:`8`,height:`8`,rx:`1.5`}),(0,P.jsx)(`path`,{d:`M3.5 10.5h-1A1 1 0 0 1 1.5 9.5v-7a1 1 0 0 1 1-1h7a1 1 0 0 1 1 1v1`})]})}function vh({provider:e,onToggleEnabled:t}){let n=Wp(e.id),r=e.accounts?.length||0,i=e.enabled!==!1;return(0,P.jsxs)(`div`,{className:`pd9-header`,children:[(0,P.jsx)(`button`,{className:`pd9-back`,onClick:()=>window.location.hash=`#/providers`,children:`← Back to Providers`}),(0,P.jsxs)(`div`,{className:`pd9-title-row`,children:[(0,P.jsx)(`div`,{className:`pd9-icon-tile`,children:(0,P.jsx)(Ie,{})}),(0,P.jsxs)(`div`,{className:`pd9-title-main`,children:[(0,P.jsxs)(`div`,{className:`pd9-title-line`,children:[(0,P.jsx)(`h1`,{className:`pd9-title`,children:e.displayName}),t&&(0,P.jsx)(`button`,{type:`button`,className:`pd9-switch ${i?`on`:``}`,role:`switch`,"aria-checked":i,onClick:()=>t(!i),title:i?`Disable provider`:`Enable provider`,children:(0,P.jsx)(`span`,{className:`pd9-switch-knob`})}),!i&&(0,P.jsx)(B,{variant:`neutral`,size:`sm`,children:`Disabled`}),n?.signupUrl&&(0,P.jsx)(`a`,{href:n.signupUrl,target:`_blank`,rel:`noopener noreferrer`,className:`pd9-signup-link`,children:`Sign up / Learn more ↗`})]}),(0,P.jsxs)(`div`,{className:`pd9-connection-count`,children:[r,` connection`,r===1?``:`s`]})]})]})]})}function yh({provider:e}){if(!e.riskNotice)return null;let t={none:{bg:`var(--neutral-soft)`,border:`var(--line)`,text:`var(--text-secondary)`},low:{bg:`var(--success-soft)`,border:`var(--success)`,text:`var(--success)`},medium:{bg:`var(--warning-soft)`,border:`var(--warning)`,text:`var(--warning)`},high:{bg:`var(--danger-soft)`,border:`var(--danger)`,text:`var(--danger)`}}[e.riskNotice.level];return(0,P.jsx)(`div`,{className:`provider-risk-banner`,style:{background:t.bg,borderColor:t.border,color:t.text},children:(0,P.jsxs)(`div`,{className:`risk-banner-content`,children:[(0,P.jsx)(Je,{className:`risk-banner-icon`}),(0,P.jsxs)(`div`,{className:`risk-banner-text`,children:[(0,P.jsx)(`div`,{className:`risk-banner-title`,children:e.riskNotice.title}),(0,P.jsx)(`div`,{className:`risk-banner-message`,children:e.riskNotice.message})]}),e.riskNotice.learnMoreUrl&&(0,P.jsx)(`a`,{href:e.riskNotice.learnMoreUrl,target:`_blank`,rel:`noopener noreferrer`,className:`risk-banner-link`,children:`Learn More`})]})})}function bh({provider:e,accounts:t,accountsLoading:n,accountsError:r,onAddAccount:i,onEditAccount:a,onTestAccount:o,onUpdateRoutingMode:s,onReorderAccount:c,onDeleteAccount:l,getTestResult:u,isTestingAccount:d}){let[f,p]=(0,v.useState)(t.some(e=>e.routingMode===`round_robin`)),[m,h]=(0,v.useState)(1);(0,v.useEffect)(()=>{p(t.some(e=>e.routingMode===`round_robin`))},[t]);let g=t.some(e=>d(e.id)),_=async()=>{for(let e of t)o(e.id)},y=()=>{let e=!f;p(e);let n=e?`round_robin`:`sticky`;t.forEach(e=>s(e.id,n))},b=e=>e===`connected`?`active`:e;return(0,P.jsxs)(V,{title:`Connections`,actions:(0,P.jsxs)(`div`,{className:`pd9-conn-controls`,children:[(0,P.jsxs)(`button`,{className:`pd9-test-onebyone`,onClick:_,disabled:g||t.length===0,children:[(0,P.jsx)(ot,{className:`pd9-btn-icon`}),g?`Testing...`:`Test Connection One-by-One`]}),(0,P.jsxs)(`div`,{className:`pd9-rotation-control`,children:[(0,P.jsx)(`span`,{className:`pd9-rotation-label`,children:`Round Robin`}),(0,P.jsx)(`button`,{type:`button`,className:`pd9-switch ${f?`on`:``}`,role:`switch`,"aria-checked":f,onClick:y,disabled:t.length===0,title:`Toggle round-robin rotation across connections`,children:(0,P.jsx)(`span`,{className:`pd9-switch-knob`})})]}),(0,P.jsxs)(`div`,{className:`pd9-sticky-control`,title:`Sticky session count (visual only)`,children:[(0,P.jsx)(`span`,{className:`pd9-rotation-label`,children:`Sticky:`}),(0,P.jsx)(`input`,{type:`number`,min:1,className:`pd9-sticky-input`,value:m,onChange:e=>h(Math.max(1,parseInt(e.target.value,10)||1)),disabled:!f})]})]}),children:[r&&(0,P.jsxs)(`div`,{className:`connections-error`,style:{color:`var(--danger)`,padding:`var(--space-2) 0`},children:[`Error loading accounts: `,r]}),(0,P.jsxs)(`div`,{className:`pd9-conn-list`,children:[t.map((e,n)=>{let r=d(e.id),i=u(e.id),f=e.status!==`disabled`,p=!!c&&t.length>1;return(0,P.jsxs)(`div`,{className:`pd9-conn-row ${f?``:`is-disabled`}`,children:[(0,P.jsxs)(`div`,{className:`pd9-conn-reorder`,children:[(0,P.jsx)(`button`,{className:`pd9-reorder-btn`,"aria-label":`Move up`,disabled:!p||n===0,onClick:()=>c&&c(n,`up`),children:(0,P.jsx)(ph,{})}),(0,P.jsx)(`button`,{className:`pd9-reorder-btn`,"aria-label":`Move down`,disabled:!p||n===t.length-1,onClick:()=>c&&c(n,`down`),children:(0,P.jsx)(mh,{})})]}),(0,P.jsx)(`div`,{className:`pd9-conn-lock`,title:`This connection is managed securely`,children:(0,P.jsx)(hh,{})}),(0,P.jsxs)(`div`,{className:`pd9-conn-main`,children:[(0,P.jsx)(`div`,{className:`pd9-conn-label`,children:e.label}),(0,P.jsxs)(`div`,{className:`pd9-conn-badges`,children:[(0,P.jsx)(`span`,{className:`pd9-status-dot ${e.status===`connected`?`ok`:`bad`}`}),(0,P.jsx)(`span`,{className:`pd9-status-text`,children:b(e.status)}),(0,P.jsx)(`span`,{className:`pd9-conn-chip`,children:Hp[e.authType]?.label||e.authType}),(0,P.jsxs)(`span`,{className:`pd9-conn-index`,children:[`#`,n+1]})]}),i&&(0,P.jsxs)(`div`,{className:`pd9-conn-testresult ${i.status===`success`?`ok`:`bad`}`,children:[i.status===`success`?`✓`:`✕`,` `,_m(i).summary,i.latencyMs?` • ${i.latencyMs}ms`:``]})]}),(0,P.jsxs)(`div`,{className:`pd9-conn-actions`,children:[(0,P.jsx)(`button`,{className:`pd9-icon-btn`,title:`Test connection`,onClick:()=>o(e.id),disabled:r,children:(0,P.jsx)(ot,{className:`pd9-action-icon`})}),(0,P.jsx)(`button`,{className:`pd9-icon-btn`,title:`Edit connection`,onClick:()=>a(e),children:(0,P.jsx)(gh,{})}),(0,P.jsx)(`button`,{className:`pd9-icon-btn danger`,title:`Delete connection`,onClick:()=>{window.confirm(`Are you sure you want to remove account connection "${e.label}"?`)&&l(e.id)},children:(0,P.jsx)(st,{className:`pd9-action-icon`})}),(0,P.jsx)(`button`,{type:`button`,className:`pd9-switch sm ${f?`on`:``}`,role:`switch`,"aria-checked":f,title:f?`Disable connection`:`Enable connection`,onClick:()=>s(e.id,f?`disabled`:`round_robin`),children:(0,P.jsx)(`span`,{className:`pd9-switch-knob`})})]})]},e.id)}),t.length===0&&!n&&(0,P.jsx)(At,{title:`No accounts connected`,description:`Connect an account to start using this provider.`,actionLabel:`Add Account`,onClick:i}),(0,P.jsxs)(`button`,{className:`pd9-add-btn`,onClick:i,children:[(0,P.jsx)(at,{className:`pd9-btn-icon`}),`Add`]})]})]})}function xh({models:e,loading:t,onRefresh:n,isKiro:r}){let i=e.filter(e=>e.enabled),[a,o]=(0,v.useState)(null),[s,c]=(0,v.useState)(!1),[l,u]=(0,v.useState)(``),[d,f]=(0,v.useState)(``),[p,m]=(0,v.useState)(!1),[h,g]=(0,v.useState)(null),[_,y]=(0,v.useState)(null),[b,x]=(0,v.useState)(new Map),S=e=>{navigator.clipboard.writeText(e),o(e),setTimeout(()=>o(null),1500)},C=async e=>{if(!_){y(e);try{let t=await Ee(e);x(n=>new Map(n).set(e,{ok:t.ok,latencyMs:t.latencyMs,error:t.error}))}catch(t){x(n=>new Map(n).set(e,{ok:!1,error:t instanceof Error?t.message:`Test failed`}))}finally{y(null)}}},w=async()=>{if(!(!l.trim()||!d.trim())){m(!0),g(null);try{await we(l.trim(),d.trim()),u(``),f(``),c(!1),n&&n()}catch(e){g(e instanceof Error?e.message:`Failed to add alias`)}finally{m(!1)}}},T=async e=>{if(window.confirm(`Remove model alias "${e}"?`))try{await Te(e),n&&n()}catch(e){console.error(`Failed to delete alias:`,e)}};return(0,P.jsx)(V,{title:`Available Models`,description:t?`Loading models...`:`${i.length} enabled • ${e.length} total`,actions:(0,P.jsx)(`div`,{className:`pd9-models-actions`,children:n&&(0,P.jsx)(`button`,{className:`pd9-test-onebyone`,onClick:n,disabled:t,children:t?`Loading...`:`⟳ Fetch Models`})}),children:t?(0,P.jsx)(`div`,{style:{padding:`var(--space-6)`,textAlign:`center`,color:`var(--text-secondary)`},children:`Loading available models...`}):(0,P.jsxs)(`div`,{className:`pd9-models-grid`,children:[e.map(e=>{let t=b.get(e.id),n=_===e.id,i=t?t.ok?`2px solid var(--success, #22c55e)`:`2px solid var(--danger, #ef4444)`:void 0;return(0,P.jsxs)(`div`,{className:`pd9-model-pill`,title:e.id,style:i?{border:i}:void 0,children:[(0,P.jsx)(`span`,{className:`pd9-model-icon`,children:t?t.ok?`✓`:`✕`:Vp[e.serviceKind]?.icon||`🧠`}),(0,P.jsx)(`span`,{className:`pd9-model-id`,children:e.id}),t?.ok&&t.latencyMs&&(0,P.jsxs)(`span`,{style:{fontSize:`0.65rem`,color:`var(--success, #22c55e)`},children:[t.latencyMs,`ms`]}),t&&!t.ok&&(0,P.jsx)(`span`,{style:{fontSize:`0.65rem`,color:`var(--danger)`},title:t.error,children:`✕`}),r&&(0,P.jsx)(`button`,{className:`pd9-model-copy`,onClick:()=>C(e.id),title:`Test model`,disabled:n,style:n?{animation:`spin 1s linear infinite`}:void 0,children:n?`⏳`:`🧪`}),(0,P.jsx)(`button`,{className:`pd9-model-copy`,onClick:()=>S(e.id),title:`Copy model ID`,children:a===e.id?`✓`:(0,P.jsx)(_h,{})}),r&&(0,P.jsx)(`button`,{className:`pd9-model-copy`,onClick:()=>T(e.id),title:`Remove alias`,style:{color:`var(--danger)`},children:`✕`})]},e.id)}),s?(0,P.jsxs)(`div`,{className:`pd9-add-model-form`,children:[(0,P.jsx)(`input`,{type:`text`,className:`form-input`,placeholder:`Alias (e.g. claude-4)`,value:l,onChange:e=>u(e.target.value),disabled:p}),(0,P.jsx)(`input`,{type:`text`,className:`form-input`,placeholder:`Target (e.g. claude-sonnet-4)`,value:d,onChange:e=>f(e.target.value),disabled:p}),(0,P.jsxs)(`div`,{style:{display:`flex`,gap:`var(--space-2)`},children:[(0,P.jsx)(`button`,{className:`button-primary`,onClick:w,disabled:!l.trim()||!d.trim()||p,children:p?`...`:`Add`}),(0,P.jsx)(`button`,{className:`button-secondary`,onClick:()=>{c(!1),g(null)},children:`Cancel`})]}),h&&(0,P.jsx)(`span`,{style:{color:`var(--danger)`,fontSize:`0.75rem`},children:h})]}):(0,P.jsxs)(`button`,{className:`pd9-add-model`,onClick:()=>c(!0),children:[(0,P.jsx)(at,{className:`pd9-btn-icon`}),`Add Model Alias`]}),e.length===0&&!s&&(0,P.jsx)(`div`,{className:`pd9-models-empty`,children:`No models available yet.`})]})})}function Sh({providerId:e}){let[t,n]=(0,v.useState)(!1),[r,i]=(0,v.useState)(`add`),[a,o]=(0,v.useState)(null),[s,c]=(0,v.useState)(!1);Em(!0);let{provider:l,loading:u,error:d,refresh:f}=nm(e||null),{accounts:p,loading:m,error:h,stats:g,refresh:_}=Xm(e||null),[y,b]=(0,v.useState)([]);(0,v.useEffect)(()=>{b(p)},[p]);let{testAccount:x,getTestResult:S,isTestingAccount:C,clearTestResult:w}=Zm(e||null),{updateRoutingMode:T,refreshAccount:E,deleteAccount:D,isAccountLoading:O,getAccountOperation:ne,operationError:re,clearError:ie}=Qm(e||null),{healthSummary:ae,needsAttentionAccounts:A,hasHealthIssues:j}=eh(p),{healthUpdate:oe,isChecking:se,error:ce,checkHealth:le,getHealthAge:M,hasHealthData:N}=wm(e||null);oe?.healthStatus||l?.healthStatus,oe?.healthMessage||l?.healthMessage;let ue=oe?.quota||l?.quota,[de,fe]=(0,v.useState)(``),[pe,me]=(0,v.useState)(``),[he,ge]=(0,v.useState)(`chat_completions`),[ve,ye]=(0,v.useState)(!1),[be,xe]=(0,v.useState)(null),[Se,Ce]=(0,v.useState)(!1),[we,Te]=(0,v.useState)([]),[Ee,De]=(0,v.useState)(!1);(0,v.useEffect)(()=>{l&&l.tier===`custom`&&(fe(l.displayName||``),me(l.baseUrl||``),ge(l.capabilities?.transportMode===`responses`?`responses`:`chat_completions`))},[l]);let Oe=(0,v.useCallback)(async()=>{if(e)try{De(!0);let t=await _e(e===`kiro-ide`||e===`kiro-free`||e.startsWith(`kiro-`)?`account-kiro`:e);t&&Array.isArray(t.models)?Te(t.models.map(e=>{let t=typeof e==`string`?e:e.id||``;return{id:t,displayName:t.split(`/`).pop()||t,enabled:!0,serviceKind:`chat`,supportsStreaming:!0,supportsTools:!0,supportsVision:t.includes(`vision`)||t.includes(`gpt-4o`),supportsJsonMode:!0}})):Te([])}catch{Te([])}finally{De(!1)}},[e]);(0,v.useEffect)(()=>{e&&Oe()},[e,Oe]),l&&lh(l),ue&&vm(ue);let ke=async e=>{try{await x(e)}catch(t){console.error(`Failed to test account ${e}:`,t)}},Ae=async(e,t)=>{try{await T(e,t),await _()}catch(t){console.error(`Failed to update routing mode for account ${e}:`,t)}},je=async e=>{try{await D(e),await _()}catch(t){console.error(`Failed to delete account ${e}:`,t)}},Me=()=>{i(`add`),o(null),n(!0)},Ne=e=>{i(`edit`),o(e),n(!0)},Pe=()=>{_(),f()},F=(e,t)=>{b(n=>{let r=[...n],i=t===`up`?e-1:e+1;return i<0||i>=r.length?n:([r[e],r[i]]=[r[i],r[e]],r)})},Fe=async t=>{if(t.preventDefault(),e){if(xe(null),Ce(!1),!de.trim()){xe(`Name is required`);return}if(!pe.trim()){xe(`Base URL is required`);return}try{new URL(pe)}catch{xe(`Base URL must be a valid URL`);return}try{ye(!0),await ee(e,{name:de.trim(),baseUrl:pe.trim(),authMode:l?.preferredAuthType||`api_key`,providerApiKeys:l?.providerApiKeys||[],capabilities:{...l?.capabilities,transportMode:he}}),Ce(!0),await f(),setTimeout(()=>Ce(!1),3e3)}catch(e){xe(e instanceof Error?e.message:`Failed to update provider settings`)}finally{ye(!1)}}},Le=async()=>{if(!(!e||!l)&&window.confirm(`Are you sure you want to permanently delete custom provider "${l.displayName}"? This action cannot be undone.`))try{await k(e),window.location.hash=`#/providers`}catch(e){alert(e instanceof Error?e.message:`Failed to delete provider`)}};return u?(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{icon:Ie,title:`Provider Details`,description:`Manage provider connections, models, and configuration`}),(0,P.jsx)(jt,{title:`Loading provider`,description:`Fetching provider details and account information...`,cards:3})]}):d||!l?(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{icon:Ie,title:`Provider Details`,description:`Manage provider connections, models, and configuration`}),(0,P.jsx)(At,{title:`Provider not found`,description:d||`The requested provider could not be found.`,actionLabel:`Back to Providers`,actionHref:`#/providers`})]}):(0,P.jsxs)(`div`,{className:`screen-stack pd9-screen`,children:[(0,P.jsxs)(`div`,{className:`provider-detail-layout pd9-layout`,children:[(0,P.jsx)(vh,{provider:l,onToggleEnabled:async t=>{try{await te(e,t),await f()}catch(e){console.error(`Failed to toggle provider:`,e)}}}),(0,P.jsx)(yh,{provider:l}),(0,P.jsx)(`div`,{className:`provider-detail-grid pd9-grid`,children:(0,P.jsxs)(`div`,{className:`provider-detail-main`,children:[l.tier===`custom`&&(0,P.jsx)(V,{title:`Configuration`,description:`Edit endpoint settings and transport mode for this custom provider`,actions:(0,P.jsx)(`button`,{className:`button-danger`,onClick:Le,style:{fontSize:`var(--font-xs)`,padding:`4px var(--space-3)`},children:`🗑 Delete Provider`}),children:(0,P.jsxs)(`form`,{onSubmit:Fe,className:`custom-provider-config-form`,style:{display:`flex`,flexDirection:`column`,gap:`var(--space-4)`},children:[be&&(0,P.jsxs)(`div`,{className:`modal-error`,style:{color:`var(--danger)`,padding:`var(--space-2) 0`},children:[`⚠️ `,be]}),Se&&(0,P.jsx)(`div`,{className:`modal-success`,style:{color:`var(--success)`,padding:`var(--space-2) 0`,fontWeight:`600`},children:`✓ Configuration updated successfully`}),(0,P.jsxs)(`div`,{className:`form-group`,style:{display:`flex`,flexDirection:`column`,gap:`var(--space-1)`},children:[(0,P.jsx)(`label`,{htmlFor:`custom-name`,style:{fontSize:`var(--font-xs)`,fontWeight:`600`,color:`var(--text-secondary)`},children:`Provider Name`}),(0,P.jsx)(`input`,{id:`custom-name`,type:`text`,className:`search-input`,value:de,onChange:e=>fe(e.target.value),required:!0,style:{padding:`8px 12px`,fontSize:`var(--font-sm)`,borderRadius:`var(--radius-md)`,border:`1px solid var(--line)`,background:`var(--surface-input)`,color:`var(--text-primary)`,width:`100%`}})]}),(0,P.jsxs)(`div`,{className:`form-group`,style:{display:`flex`,flexDirection:`column`,gap:`var(--space-1)`},children:[(0,P.jsx)(`label`,{htmlFor:`custom-url`,style:{fontSize:`var(--font-xs)`,fontWeight:`600`,color:`var(--text-secondary)`},children:`Base URL / Endpoint`}),(0,P.jsx)(`input`,{id:`custom-url`,type:`url`,className:`search-input`,value:pe,onChange:e=>me(e.target.value),placeholder:`https://api.openai.com/v1`,required:!0,style:{padding:`8px 12px`,fontSize:`var(--font-sm)`,borderRadius:`var(--radius-md)`,border:`1px solid var(--line)`,background:`var(--surface-input)`,color:`var(--text-primary)`,width:`100%`}})]}),(0,P.jsxs)(`div`,{className:`form-group`,style:{display:`flex`,flexDirection:`column`,gap:`var(--space-1)`},children:[(0,P.jsx)(`label`,{htmlFor:`custom-transport`,style:{fontSize:`var(--font-xs)`,fontWeight:`600`,color:`var(--text-secondary)`},children:`Transport Mode`}),(0,P.jsxs)(`select`,{id:`custom-transport`,className:`search-input`,value:he,onChange:e=>ge(e.target.value),style:{padding:`8px 12px`,fontSize:`var(--font-sm)`,borderRadius:`var(--radius-md)`,border:`1px solid var(--line)`,background:`var(--surface-input)`,color:`var(--text-primary)`,width:`100%`},children:[(0,P.jsx)(`option`,{value:`responses`,children:`Responses API (/responses)`}),(0,P.jsx)(`option`,{value:`chat_completions`,children:`Chat Completions (/chat/completions)`})]})]}),(0,P.jsx)(`div`,{style:{display:`flex`,justifyContent:`flex-end`,marginTop:`var(--space-2)`},children:(0,P.jsx)(`button`,{type:`submit`,className:`button-primary`,disabled:ve,children:ve?`Saving...`:`Save Configuration`})})]})}),l.tier!==`custom`&&l.configured&&(0,P.jsx)(`div`,{style:{display:`flex`,justifyContent:`flex-end`,marginBottom:`var(--space-3)`},children:(0,P.jsx)(`button`,{className:`button-danger`,onClick:Le,style:{fontSize:`var(--font-xs)`,padding:`4px var(--space-3)`},children:`🗑 Remove Provider`})}),(0,P.jsx)(bh,{provider:l,accounts:y,accountsLoading:m,accountsError:h,onAddAccount:Me,onEditAccount:Ne,onTestAccount:ke,onUpdateRoutingMode:Ae,onReorderAccount:F,onDeleteAccount:je,getTestResult:S,isTestingAccount:C}),(0,P.jsx)(xh,{models:we,loading:Ee,onRefresh:Oe,isKiro:e===`kiro-ide`||e===`kiro-free`||e?.startsWith(`kiro-`)||!1})]})})]}),(0,P.jsx)(sh,{providerId:l.id,providerName:l.displayName,supportedAuthTypes:l.authTypes,accounts:p,isOpen:t,mode:r,editingAccount:a,onClose:()=>n(!1),onAccountsChanged:Pe})]})}function Ch(e){return e.split(/\r?\n|,/).map(e=>e.trim()).filter(Boolean)}function wh({mode:e,initialData:t,onSubmit:n,onCancel:r}){let[i,a]=(0,v.useState)({name:t?.name??``,baseUrl:t?.baseUrl??``,authMode:t?.authMode===`chatgpt_oauth`?`chatgpt_oauth`:`api_key`,chatgptAccountId:t?.chatgptAccountId??``,providerApiKeysText:t?.providerApiKeysText??``,transportMode:t?.transportMode===`chat_completions`?`chat_completions`:`responses`}),[o,s]=(0,v.useState)(null),[c,l]=(0,v.useState)(!1),u=(0,v.useMemo)(()=>e===`edit`?`Leave blank to keep the currently configured keys, or enter new keys to replace them.`:`Optional. Enter one provider API key per line.`,[e]);async function d(t){t.preventDefault(),s(null);let r=i.name.trim(),a=i.baseUrl.trim(),o=i.chatgptAccountId.trim(),c=Ch(i.providerApiKeysText),u=i.providerApiKeysText.trim().length>0;if(!r){s(`Name is required.`);return}if(!a){s(`Base URL is required.`);return}try{new URL(a)}catch{s(`Base URL must be a valid URL.`);return}if(i.authMode===`chatgpt_oauth`&&!o){s(`Account ID is required for ChatGPT OAuth providers.`);return}i.authMode===`api_key`&&e===`create`&&c.length===0&&s(`At least one provider API key is recommended for API key providers.`),l(!0);try{await n({name:r,baseUrl:a,authMode:i.authMode,chatgptAccountId:o||void 0,providerApiKeys:c,replaceKeys:u,transportMode:i.transportMode})}catch(e){s(e instanceof Error?e.message:`Could not save provider.`),l(!1);return}l(!1)}return(0,P.jsxs)(`form`,{className:`provider-form`,onSubmit:d,children:[(0,P.jsx)(`div`,{className:`modal-header`,children:(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`p`,{className:`eyebrow`,children:e===`create`?`Create provider`:`Edit provider`}),(0,P.jsx)(`h2`,{children:e===`create`?`New provider`:`Update provider`})]})}),(0,P.jsx)(`p`,{className:`modal-copy`,children:e===`create`?`Create a runtime provider with routing metadata, auth mode, and upstream credentials.`:`Update provider metadata, account binding, and credentials without exposing existing keys.`}),o?(0,P.jsx)(Ut,{message:o,title:`Could not save provider`,variant:`error`}):null,(0,P.jsxs)(`label`,{className:`form-field`,children:[(0,P.jsx)(`span`,{className:`field-label`,children:`Name`}),(0,P.jsx)(`input`,{className:`search-input`,onChange:e=>a(t=>({...t,name:e.target.value})),required:!0,type:`text`,value:i.name})]}),(0,P.jsxs)(`label`,{className:`form-field`,children:[(0,P.jsx)(`span`,{className:`field-label`,children:`Base URL`}),(0,P.jsx)(`input`,{className:`search-input`,onChange:e=>a(t=>({...t,baseUrl:e.target.value})),placeholder:`https://example.com/v1`,required:!0,type:`url`,value:i.baseUrl})]}),(0,P.jsxs)(`label`,{className:`form-field`,children:[(0,P.jsx)(`span`,{className:`field-label`,children:`Auth mode`}),(0,P.jsxs)(`select`,{className:`search-input`,onChange:e=>a(t=>({...t,authMode:e.target.value===`chatgpt_oauth`?`chatgpt_oauth`:`api_key`})),value:i.authMode,children:[(0,P.jsx)(`option`,{value:`api_key`,children:`API key`}),(0,P.jsx)(`option`,{value:`chatgpt_oauth`,children:`ChatGPT OAuth`})]})]}),i.authMode===`chatgpt_oauth`?(0,P.jsxs)(`label`,{className:`form-field`,children:[(0,P.jsx)(`span`,{className:`field-label`,children:`Account ID`}),(0,P.jsx)(`input`,{className:`search-input`,onChange:e=>a(t=>({...t,chatgptAccountId:e.target.value})),placeholder:`acct_123`,type:`text`,value:i.chatgptAccountId})]}):null,(0,P.jsxs)(`label`,{className:`form-field`,children:[(0,P.jsx)(`span`,{className:`field-label`,children:`Transport mode`}),(0,P.jsxs)(`select`,{className:`search-input`,onChange:e=>a(t=>({...t,transportMode:e.target.value===`chat_completions`?`chat_completions`:`responses`})),value:i.transportMode,children:[(0,P.jsx)(`option`,{value:`responses`,children:`Responses API (/responses)`}),(0,P.jsx)(`option`,{value:`chat_completions`,children:`Chat Completions (/chat/completions)`})]})]}),(0,P.jsxs)(`label`,{className:`form-field`,children:[(0,P.jsx)(`span`,{className:`field-label`,children:e===`create`?`Provider API keys`:`Replace provider API keys`}),(0,P.jsx)(`textarea`,{className:`search-input form-textarea`,onChange:e=>a(t=>({...t,providerApiKeysText:e.target.value})),placeholder:e===`create`?`sk-provider-...`:`Enter new keys only if you want to replace them`,rows:4,value:i.providerApiKeysText}),(0,P.jsx)(`span`,{className:`field-help`,children:u})]}),(0,P.jsxs)(`div`,{className:`modal-actions`,children:[(0,P.jsx)(`button`,{className:`button-link`,disabled:c,onClick:r,type:`button`,children:`Cancel`}),(0,P.jsx)(`button`,{className:`button-link button-primary`,disabled:c,type:`submit`,children:c?e===`create`?`Creating...`:`Saving...`:e===`create`?`Create provider`:`Save changes`})]})]})}var Th={anthropic:{label:`Anthropic Compatible`,description:`Claude-style upstream using the Responses API transport.`,initialData:{name:``,baseUrl:``,authMode:`api_key`,chatgptAccountId:``,providerApiKeysText:``,transportMode:`responses`}},openai:{label:`OpenAI Compatible`,description:`OpenAI-style upstream using the Chat Completions transport.`,initialData:{name:``,baseUrl:``,authMode:`api_key`,chatgptAccountId:``,providerApiKeysText:``,transportMode:`chat_completions`}}};function Eh(){let[e,t]=(0,v.useState)(`openai`),n=(0,v.useMemo)(()=>Th[e].initialData,[e]),r=()=>{window.location.hash=`#/providers`};return(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{icon:Ie,eyebrow:`Providers`,title:`Add Provider`,description:`Connect an OpenAI or Anthropic compatible endpoint`,actions:(0,P.jsx)(`div`,{className:`page-actions`,children:(0,P.jsx)(`button`,{className:`back-button`,onClick:r,type:`button`,children:`← Back to Providers`})})}),(0,P.jsxs)(`div`,{className:`provider-new-layout`,children:[(0,P.jsx)(V,{title:`Provider Type`,description:`Pick the upstream protocol this provider speaks`,children:(0,P.jsx)(`div`,{className:`provider-preset-grid`,children:Object.keys(Th).map(n=>{let r=e===n;return(0,P.jsxs)(`button`,{type:`button`,className:`provider-preset-card${r?` active`:``}`,onClick:()=>t(n),"aria-pressed":r,children:[(0,P.jsx)(`span`,{className:`provider-preset-name`,children:Th[n].label}),(0,P.jsx)(`span`,{className:`provider-preset-desc`,children:Th[n].description})]},n)})})}),(0,P.jsx)(V,{title:`Configuration`,description:`Set the provider name, endpoint, and credentials`,children:(0,P.jsx)(wh,{mode:`create`,initialData:n,onCancel:r,onSubmit:async e=>{await O({name:e.name,baseUrl:e.baseUrl,authMode:e.authMode,chatgptAccountId:e.authMode===`chatgpt_oauth`?e.chatgptAccountId??``:``,providerApiKeys:e.providerApiKeys??[],capabilities:{transportMode:e.transportMode}}),r()}},e)})]})]})}var Dh={enabled:`inherit`,toolOutputEnabled:`inherit`,maxChars:``,maxLines:``,tailLines:``,tailChars:``,detectFormat:`inherit`};function Oh(e){if(!Rt(e))return`Inherit`;let t=[];return typeof e.enabled==`boolean`&&t.push(e.enabled?`enabled`:`disabled`),typeof e.toolOutputEnabled==`boolean`&&t.push(e.toolOutputEnabled?`tool-output:on`:`tool-output:off`),typeof e.maxChars==`number`&&t.push(`chars:${e.maxChars}`),typeof e.maxLines==`number`&&t.push(`lines:${e.maxLines}`),typeof e.tailLines==`number`&&t.push(`tail:${e.tailLines}`),typeof e.tailChars==`number`&&t.push(`tailChars:${e.tailChars}`),typeof e.detectFormat==`string`&&e.detectFormat.trim()&&t.push(`format:${e.detectFormat}`),t.length?t.join(` | `):`Inherit`}function kh(e){return Array.isArray(e.apiKeys)?e.apiKeys.length:0}function Ah(e){return Array.isArray(e.providers)&&e.providers.length?e.providers:Array.isArray(e.providerOptions)?e.providerOptions:[]}function jh(e){return Rt(e)?e:{}}function Mh(e){return typeof e==`boolean`?String(e):`inherit`}function Nh(e){return typeof e==`string`&&e.trim()?e:`inherit`}function Ph(e){return typeof e==`number`&&Number.isFinite(e)?String(e):``}function Fh(e){let t=Rt(e)?e:{};return{enabled:Mh(t.enabled),toolOutputEnabled:Mh(t.toolOutputEnabled),maxChars:Ph(t.maxChars),maxLines:Ph(t.maxLines),tailLines:Ph(t.tailLines),tailChars:Ph(t.tailChars),detectFormat:Nh(t.detectFormat)}}function Ih(e){let t=e.trim();if(!t)return;let n=Number(t);return Number.isInteger(n)&&n>0?n:void 0}function Lh(e){let t=e.trim();if(!t)return;let n=Number(t);return Number.isInteger(n)&&n>=0?n:void 0}function Rh(e){return{...e.enabled===`inherit`?{}:{enabled:e.enabled===`true`},...e.toolOutputEnabled===`inherit`?{}:{toolOutputEnabled:e.toolOutputEnabled===`true`},...Ih(e.maxChars)===void 0?{}:{maxChars:Ih(e.maxChars)},...Ih(e.maxLines)===void 0?{}:{maxLines:Ih(e.maxLines)},...Lh(e.tailLines)===void 0?{}:{tailLines:Lh(e.tailLines)},...Lh(e.tailChars)===void 0?{}:{tailChars:Lh(e.tailChars)},...e.detectFormat===`inherit`?{}:{detectFormat:e.detectFormat}}}function zh(e){return typeof e.enabled==`boolean`||typeof e.toolOutputEnabled==`boolean`||typeof e.maxChars==`number`||typeof e.maxLines==`number`}function Bh(e,t){return typeof t.rtkRequests!=`number`||t.rtkRequests<=0?null:(0,P.jsx)(V,{title:`${e} RTK telemetry`,description:`Observed RTK reductions from recorded requests.`,children:(0,P.jsxs)(`div`,{className:`stat-grid`,children:[(0,P.jsx)(z,{label:`Requests seen`,value:L(t.rtkRequests)}),(0,P.jsx)(z,{label:`Applied requests`,value:L(t.rtkAppliedRequests)}),(0,P.jsx)(z,{label:`Applied rate`,value:zt(t.rtkAppliedRate)}),(0,P.jsx)(z,{label:`Tool outputs reduced`,value:L(t.rtkToolOutputsReduced)}),(0,P.jsx)(z,{label:`Chars before`,value:L(t.rtkCharsBefore)}),(0,P.jsx)(z,{label:`Chars after`,value:L(t.rtkCharsAfter)}),(0,P.jsx)(z,{label:`Chars saved`,value:L(t.rtkCharsSaved)}),(0,P.jsx)(z,{label:`Avg chars saved`,value:L(t.rtkAvgCharsSaved)})]})})}function Vh(){if(window.location.hash.includes(`skills`))return(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{icon:nt,title:`Skills Hub`,description:`Cognitive abilities, tool registries, and agentic workflows`}),(0,P.jsx)(V,{title:`Feature Coming Soon`,description:`Advanced cognitive skills registry`,tone:`info`,children:(0,P.jsxs)(`div`,{style:{padding:`var(--space-6) var(--space-4)`,textAlign:`center`},children:[(0,P.jsx)(`span`,{style:{fontSize:`3rem`},children:`🧠`}),(0,P.jsx)(`h3`,{style:{margin:`var(--space-3) 0 var(--space-2) 0`,fontSize:`var(--font-lg)`},children:`Cognitive & Agentic Skills`}),(0,P.jsx)(`p`,{style:{margin:`0 auto var(--space-4) auto`,color:`var(--text-secondary)`,fontSize:`var(--font-sm)`,maxWidth:`540px`,lineHeight:`1.6`},children:`Skills Hub will enable configuring advanced prompt injections, system instructions, and tool schemas directly inside responses-proxy. Developers can register and deploy cognitive behaviors that are injected dynamically into client sessions based on model compatibility.`}),(0,P.jsxs)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:`var(--space-2)`,justifyContent:`center`},children:[(0,P.jsx)(B,{variant:`accent`,children:`Prompt Injectors`}),(0,P.jsx)(B,{variant:`accent`,children:`Tool Schemas`}),(0,P.jsx)(B,{variant:`accent`,children:`Context Trimming`})]})]})})]});let{state:e,retry:t}=Wt((0,v.useCallback)(async()=>{let[e,t]=await Promise.all([D(),j()]);return{providers:e,usage:t}},[])),[n,r]=(0,v.useState)(null),[i,a]=(0,v.useState)(Dh),[o,s]=(0,v.useState)(!1),[c,l]=(0,v.useState)(null),u=e.status===`success`?Ah(e.data.providers):[],d=e.status===`success`&&Array.isArray(e.data.providers.clientRoutes)?e.data.providers.clientRoutes:[];(0,v.useEffect)(()=>{if(!d.length){n!==null&&r(null);return}n&&d.some(e=>e.key===n)||r((d.find(e=>e.key!==`default`)??d[0]).key)},[d,n]);let f=d.find(e=>e.key===n)??d[0]??null;if((0,v.useEffect)(()=>{if(!f){a(Dh);return}a(Fh(f.rtkPolicy))},[f?.key,f?.rtkPolicy]),e.status===`loading`||e.status===`idle`)return(0,P.jsx)(jt,{title:`Loading RTK overview`,description:`Reading route policies and RTK usage telemetry.`});if(e.status===`error`)return(0,P.jsx)(Ht,{title:`RTK overview unavailable`,description:e.error.message,onRetry:t});let p=Rt(e.data.usage.stats)?e.data.usage.stats:{},m=jh(p.today),h=jh(p.month),g=d.map(e=>({clientRoute:e.key,provider:e.providerName||e.providerId||`Unbound`,modelOverride:e.modelOverride||`Inherited`,apiKeys:kh(e),policySummary:Oh(e.rtkPolicy)})),_=u.map(e=>{let t=Rt(e.capabilities)?e.capabilities:null;return{provider:e.name||e.id,authMode:e.authMode||`Not reported`,defaultPolicy:Oh(t?.rtkPolicy)}}).filter(e=>e.defaultPolicy!==`Inherit`),y=g.filter(e=>e.policySummary!==`Inherit`).length,b=_.length,x=typeof m.rtkRequests==`number`&&m.rtkRequests>0||typeof h.rtkRequests==`number`&&h.rtkRequests>0,S=Rh(i),C=Object.keys(S).length>0&&!zh(S)?`Current backend behavior only persists RTK overrides when at least one of enabled, tool output, max chars, or max lines is set.`:null;async function w(){if(f){s(!0),l(null);try{await se(f.key,S),l({variant:`success`,message:Object.keys(S).length===0?`RTK policy for ${f.key} reset to inherit.`:`RTK policy for ${f.key} saved.`}),t()}catch(e){l({variant:`error`,message:e instanceof Error?e.message:`Could not save RTK policy`})}finally{s(!1)}}}function T(){a(Dh),l(null)}return(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{eyebrow:`RTK`,title:`RTK reduction overview`,description:`Tune route-level RTK policy, review recent savings, and compare live telemetry against your current rules.`,actions:(0,P.jsx)($t,{onClick:t})}),(0,P.jsx)(V,{children:(0,P.jsxs)(`div`,{className:`hero-status`,children:[(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`p`,{className:`eyebrow`,children:`Policy coverage`}),(0,P.jsx)(`h2`,{children:L(y)}),(0,P.jsx)(`p`,{children:y===1?`client route with explicit RTK policy`:`client routes with explicit RTK policy`})]}),(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`p`,{className:`eyebrow`,children:`Provider defaults`}),(0,P.jsx)(`h2`,{children:L(b)}),(0,P.jsx)(`p`,{children:b===1?`provider exposes an RTK default`:`providers expose RTK defaults`})]})]})}),(0,P.jsxs)(`div`,{className:`stat-grid`,children:[(0,P.jsx)(z,{label:`Today RTK requests`,value:L(m.rtkRequests)}),(0,P.jsx)(z,{label:`Today applied rate`,value:zt(m.rtkAppliedRate)}),(0,P.jsx)(z,{label:`Month RTK requests`,value:L(h.rtkRequests)}),(0,P.jsx)(z,{label:`Month chars saved`,value:L(h.rtkCharsSaved)})]}),Bh(`Today`,m),Bh(`This month`,h),x?null:(0,P.jsx)(At,{title:`No RTK telemetry yet`,description:`RTK telemetry will appear here after requests are processed with session logging enabled.`}),(0,P.jsxs)(V,{title:`Edit client route RTK policy`,description:`Save route-level RTK policy changes against the live backend contract used by the proxy.`,children:[c?(0,P.jsx)(Ut,{variant:c.variant,message:c.message,title:c.variant===`error`?`Save failed`:`Saved`}):null,C?(0,P.jsx)(Ut,{variant:`error`,title:`Persistence note`,message:C}):null,f?(0,P.jsxs)(`div`,{className:`surface-card-body`,children:[(0,P.jsxs)(`div`,{className:`client-form-grid rtk-form-grid`,children:[(0,P.jsxs)(`label`,{className:`form-field`,children:[(0,P.jsx)(`span`,{className:`field-label`,children:`Client route`}),(0,P.jsx)(`select`,{className:`search-input`,value:f.key,onChange:e=>{r(e.target.value),l(null)},children:d.map(e=>(0,P.jsx)(`option`,{value:e.key,children:e.key},e.key))})]}),(0,P.jsxs)(`label`,{className:`form-field`,children:[(0,P.jsx)(`span`,{className:`field-label`,children:`Enabled`}),(0,P.jsxs)(`select`,{className:`search-input`,value:i.enabled,onChange:e=>a(t=>({...t,enabled:e.target.value})),children:[(0,P.jsx)(`option`,{value:`inherit`,children:`Inherit`}),(0,P.jsx)(`option`,{value:`true`,children:`Enabled`}),(0,P.jsx)(`option`,{value:`false`,children:`Disabled`})]})]}),(0,P.jsxs)(`label`,{className:`form-field`,children:[(0,P.jsx)(`span`,{className:`field-label`,children:`Tool output reduction`}),(0,P.jsxs)(`select`,{className:`search-input`,value:i.toolOutputEnabled,onChange:e=>a(t=>({...t,toolOutputEnabled:e.target.value})),children:[(0,P.jsx)(`option`,{value:`inherit`,children:`Inherit`}),(0,P.jsx)(`option`,{value:`true`,children:`Enabled`}),(0,P.jsx)(`option`,{value:`false`,children:`Disabled`})]})]}),(0,P.jsxs)(`label`,{className:`form-field`,children:[(0,P.jsx)(`span`,{className:`field-label`,children:`Max chars`}),(0,P.jsx)(`input`,{className:`search-input`,inputMode:`numeric`,placeholder:`e.g. 2800`,value:i.maxChars,onChange:e=>a(t=>({...t,maxChars:e.target.value}))})]}),(0,P.jsxs)(`label`,{className:`form-field`,children:[(0,P.jsx)(`span`,{className:`field-label`,children:`Max lines`}),(0,P.jsx)(`input`,{className:`search-input`,inputMode:`numeric`,placeholder:`e.g. 90`,value:i.maxLines,onChange:e=>a(t=>({...t,maxLines:e.target.value}))})]}),(0,P.jsxs)(`label`,{className:`form-field`,children:[(0,P.jsx)(`span`,{className:`field-label`,children:`Tail lines`}),(0,P.jsx)(`input`,{className:`search-input`,inputMode:`numeric`,placeholder:`e.g. 12`,value:i.tailLines,onChange:e=>a(t=>({...t,tailLines:e.target.value}))})]}),(0,P.jsxs)(`label`,{className:`form-field`,children:[(0,P.jsx)(`span`,{className:`field-label`,children:`Tail chars`}),(0,P.jsx)(`input`,{className:`search-input`,inputMode:`numeric`,placeholder:`e.g. 400`,value:i.tailChars,onChange:e=>a(t=>({...t,tailChars:e.target.value}))})]}),(0,P.jsxs)(`label`,{className:`form-field`,children:[(0,P.jsx)(`span`,{className:`field-label`,children:`Detect format`}),(0,P.jsxs)(`select`,{className:`search-input`,value:i.detectFormat,onChange:e=>a(t=>({...t,detectFormat:e.target.value})),children:[(0,P.jsx)(`option`,{value:`inherit`,children:`Inherit`}),(0,P.jsx)(`option`,{value:`auto`,children:`Auto`}),(0,P.jsx)(`option`,{value:`plain`,children:`Plain`}),(0,P.jsx)(`option`,{value:`json`,children:`JSON`}),(0,P.jsx)(`option`,{value:`stack`,children:`Stack`}),(0,P.jsx)(`option`,{value:`command`,children:`Command`})]})]})]}),(0,P.jsxs)(`div`,{className:`rtk-form-actions`,children:[(0,P.jsx)(`button`,{className:`button-link`,disabled:o,onClick:T,type:`button`,children:`Reset form`}),(0,P.jsx)(`button`,{className:`button-link`,disabled:o,onClick:()=>a(Fh(f.rtkPolicy)),type:`button`,children:`Load saved policy`}),(0,P.jsx)(`button`,{className:`button-primary`,disabled:o,onClick:w,type:`button`,children:o?`Saving...`:`Save RTK policy`})]})]}):(0,P.jsx)(At,{title:`No client routes available`,description:`Create a client route first, then return here to adjust RTK policy.`})]}),(0,P.jsx)(V,{title:`Client route RTK policy`,description:`Route-level RTK settings currently configured in the backend. Inherited means the route follows provider defaults.`,children:(0,P.jsx)(Vt,{columns:[{key:`clientRoute`,label:`Client route`},{key:`provider`,label:`Provider`},{key:`modelOverride`,label:`Model override`},{key:`apiKeys`,label:`API keys`,align:`right`,render:e=>L(e)},{key:`policySummary`,label:`RTK policy`}],rows:g,emptyTitle:`No client routes reported`,emptyDescription:`Route policy details will appear after providers are loaded.`})}),(0,P.jsx)(V,{title:`Provider RTK defaults`,description:`Provider-level defaults used when a client route inherits RTK behavior.`,children:(0,P.jsx)(Vt,{columns:[{key:`provider`,label:`Provider`},{key:`authMode`,label:`Auth`},{key:`defaultPolicy`,label:`Default RTK policy`}],rows:_,emptyTitle:`No provider RTK defaults reported`,emptyDescription:`Providers without explicit RTK defaults will continue to inherit backend behavior.`})}),(0,P.jsx)(V,{title:`Policy notes`,description:`Helpful context for choosing conservative defaults before widening route-level policy.`,children:(0,P.jsxs)(`dl`,{className:`detail-list`,children:[(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`dt`,{children:`Selected route`}),(0,P.jsx)(`dd`,{children:f?f.key:`Not reported`})]}),(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`dt`,{children:`Saved summary`}),(0,P.jsx)(`dd`,{children:f?Oh(f.rtkPolicy):`Not reported`})]}),(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`dt`,{children:`Provider defaults`}),(0,P.jsx)(`dd`,{children:b>0?`${b} provider default${b===1?``:`s`} detected`:`No explicit provider defaults reported`})]}),(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`dt`,{children:`Telemetry fallback`}),(0,P.jsx)(`dd`,{children:x?`Telemetry is flowing and can be compared against policy summaries above.`:`Telemetry is still sparse, so compare recent requests after saving a policy update.`})]}),(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`dt`,{children:`Top-level request reduction`}),(0,P.jsx)(`dd`,{children:typeof h.rtkAppliedRate==`number`?`${zt(h.rtkAppliedRate)} applied this month`:`Not reported yet`})]}),(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`dt`,{children:`Tool-output trimming`}),(0,P.jsx)(`dd`,{children:R(h.rtkToolOutputsReduced)})]})]})})]})}var Hh=[{value:`today`,label:`Today`},{value:`7d`,label:`7D`},{value:`30d`,label:`30D`}],Uh=e=>new Intl.NumberFormat().format(Number(e)||0),Wh=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e||0);function Gh(){let[e,t]=(0,v.useState)(`overview`),[n,r]=(0,v.useState)(`today`),[i,a]=(0,v.useState)(`tokens`),{state:o,retry:s}=Wt((0,v.useCallback)(()=>j(),[])),[c,l]=(0,v.useState)({status:`idle`}),u=(0,v.useCallback)(async()=>{l(e=>({status:`loading`,data:e.data}));try{l({status:`success`,data:await oe()})}catch{l({status:`success`,data:{ok:!0,providers:[]}})}},[]);(0,v.useEffect)(()=>{let e=!0,t=async()=>{l(e=>({status:`loading`,data:e.data}));try{let t=await oe();e&&l({status:`success`,data:t})}catch{e&&l({status:`success`,data:{ok:!0,providers:[]}})}};t();let n=setInterval(()=>void t(),3e4);return()=>{e=!1,clearInterval(n)}},[]);let d=o.status===`success`&&Rt(o.data.stats)?o.data.stats:{},f=Rt(d.today)?d.today:{},p=Rt(d.month)?d.month:{},m=Array.isArray(d.daily)?d.daily:[],h=Array.isArray(d.byProvider)?d.byProvider:[],g=Array.isArray(d.byModel)?d.byModel:[],_=Array.isArray(d.byClientRoute)?d.byClientRoute:[],y=Array.isArray(c.data?.providers)?c.data.providers:[],b=n===`30d`?p:f,x=Number(b.totalInputTokens)||0,S=Number(b.totalCachedTokens)||0,C=Number(b.requests)||0,w=(0,v.useMemo)(()=>m.map(e=>({timestamp:e.date||new Date().toISOString(),value:i===`tokens`?Number(e.totalInputTokens||0)+Number(e.totalCachedTokens||0):Number(e.requests||0)})),[m,i]);return o.status===`loading`||o.status===`idle`?(0,P.jsx)(jt,{title:`Loading usage`,description:`Reading usage data...`}):o.status===`error`?(0,P.jsx)(Ht,{title:`Usage unavailable`,description:o.error.message,onRetry:s}):(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{title:`Usage & Analytics`,description:`Track requests, tokens, cost, and provider utilization.`,actions:(0,P.jsx)($t,{onClick:s})}),(0,P.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:`var(--space-4)`,flexWrap:`wrap`},children:[(0,P.jsx)(qh,{options:[{value:`overview`,label:`Overview`},{value:`details`,label:`Details`}],value:e,onChange:e=>t(e)}),e===`overview`&&(0,P.jsx)(qh,{options:Hh,value:n,onChange:e=>r(e),size:`sm`})]}),e===`overview`&&(0,P.jsxs)(P.Fragment,{children:[(0,P.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`repeat(auto-fit, minmax(180px, 1fr))`,gap:`var(--space-4)`},children:[(0,P.jsx)(Kh,{label:`Total Requests`,value:Uh(C)}),(0,P.jsx)(Kh,{label:`Total Input Tokens`,value:Wh(x),color:`var(--accent)`}),(0,P.jsx)(Kh,{label:`Cached Tokens`,value:Wh(S),color:`var(--success)`}),(0,P.jsx)(Kh,{label:`Cache Hit Rate`,value:zt(b.hitRate),color:`var(--warning)`,subtitle:`Prompt cache efficiency`})]}),w.length>0&&(0,P.jsxs)(V,{children:[(0,P.jsxs)(`div`,{style:{display:`flex`,justifyContent:`space-between`,alignItems:`center`,marginBottom:`var(--space-3)`},children:[(0,P.jsx)(`h3`,{style:{margin:0,fontSize:`var(--text-sm)`,fontWeight:600},children:`Usage Over Time`}),(0,P.jsx)(qh,{options:[{value:`tokens`,label:`Tokens`},{value:`cost`,label:`Requests`}],value:i,onChange:e=>a(e),size:`sm`})]}),(0,P.jsx)(Pp,{data:w,height:200,color:i===`tokens`?`var(--accent)`:`var(--warning)`,fill:!0,valueFormatter:e=>i===`tokens`?Wh(e):Uh(e)})]}),typeof b.rtkRequests==`number`&&b.rtkRequests>0&&(0,P.jsx)(V,{title:`RTK Token Saver`,description:`Tool output compression statistics`,children:(0,P.jsxs)(`div`,{className:`stat-grid`,children:[(0,P.jsx)(z,{label:`RTK Requests`,value:Uh(b.rtkRequests)}),(0,P.jsx)(z,{label:`Applied`,value:Uh(b.rtkAppliedRequests)}),(0,P.jsx)(z,{label:`Apply Rate`,value:zt(b.rtkAppliedRate)}),(0,P.jsx)(z,{label:`Chars Saved`,value:Uh(b.rtkCharsSaved)})]})}),(0,P.jsx)(V,{title:`By Provider`,description:`Request distribution across providers`,children:(0,P.jsx)(Vt,{columns:[{key:`key`,label:`Provider`},{key:`requests`,label:`Requests`,align:`right`,render:e=>Uh(e)},{key:`totalCachedTokens`,label:`Cached Tokens`,align:`right`,render:e=>Uh(e)},{key:`hitRate`,label:`Hit Rate`,align:`right`,render:e=>zt(e)},{key:`rtkCharsSaved`,label:`RTK Saved`,align:`right`,render:e=>Uh(e)}],rows:h,emptyTitle:`No provider data`,emptyDescription:`Usage will appear after requests are processed.`})}),g.length>0&&(0,P.jsx)(V,{title:`By Model`,description:`Token usage per model`,children:(0,P.jsx)(Vt,{columns:[{key:`key`,label:`Model`},{key:`requests`,label:`Requests`,align:`right`,render:e=>Uh(e)},{key:`totalCachedTokens`,label:`Cached`,align:`right`,render:e=>Uh(e)},{key:`avgCacheSavedPercent`,label:`Avg Saved`,align:`right`,render:e=>zt(e)}],rows:g,emptyTitle:`No model data`,emptyDescription:``})}),(0,P.jsx)(V,{title:`By Client Route`,description:`Usage per API key route`,children:(0,P.jsx)(Vt,{columns:[{key:`key`,label:`Route`},{key:`requests`,label:`Requests`,align:`right`,render:e=>Uh(e)},{key:`hitRate`,label:`Hit Rate`,align:`right`,render:e=>zt(e)},{key:`rtkCharsSaved`,label:`RTK Saved`,align:`right`,render:e=>Uh(e)}],rows:_,emptyTitle:`No route data`,emptyDescription:`Client route usage will appear when route-specific logs exist.`})})]}),e===`details`&&(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(V,{title:`Live Provider Status`,description:`Real-time provider availability. Auto-refreshes every 30s.`,actions:(0,P.jsx)($t,{onClick:u,label:`Refresh`}),children:y.length===0?(0,P.jsx)(`p`,{style:{color:`var(--text-muted)`,fontSize:`var(--text-sm)`,textAlign:`center`,padding:`var(--space-4)`},children:`No live data available.`}):(0,P.jsx)(`div`,{style:{display:`grid`,gap:`var(--space-2)`},children:y.map(e=>{let t=Rt(e.usage)?e.usage:{},n=e.ok!==!1&&t.allowed!==!1;return(0,P.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`var(--space-3)`,padding:`var(--space-3) var(--space-4)`,background:`var(--surface-muted)`,borderRadius:`var(--radius-sm)`,border:`1px solid var(--line)`},children:[(0,P.jsx)(`span`,{style:{width:8,height:8,borderRadius:`50%`,flexShrink:0,background:n?`var(--success)`:`var(--danger)`,boxShadow:`0 0 0 3px ${n?`var(--success-soft)`:`var(--danger-soft)`}`}}),(0,P.jsx)(`span`,{style:{flex:1,fontWeight:600,fontSize:`var(--text-sm)`},children:e.providerName||e.providerId}),typeof t.remaining==`number`&&typeof t.limit==`number`&&(0,P.jsxs)(`span`,{style:{fontSize:`var(--text-xs)`,color:`var(--text-secondary)`},children:[Uh(t.remaining),` / `,Uh(t.limit)]}),(0,P.jsx)(B,{status:n?`success`:`danger`,children:n?`Available`:e.error?`Error`:`Exhausted`})]},e.providerId||e.providerName)})})}),(0,P.jsx)(V,{title:`Cache Performance`,description:`Detailed cache statistics`,children:(0,P.jsxs)(`div`,{className:`stat-grid`,children:[(0,P.jsx)(z,{label:`Today Requests`,value:Uh(f.requests)}),(0,P.jsx)(z,{label:`Today Hit Rate`,value:zt(f.hitRate)}),(0,P.jsx)(z,{label:`Today Cached`,value:Uh(f.totalCachedTokens)}),(0,P.jsx)(z,{label:`Today Avg Saved`,value:zt(f.avgCacheSavedPercent)}),(0,P.jsx)(z,{label:`Month Requests`,value:Uh(p.requests)}),(0,P.jsx)(z,{label:`Month Hit Rate`,value:zt(p.hitRate)}),(0,P.jsx)(z,{label:`Month Cached`,value:Uh(p.totalCachedTokens)}),(0,P.jsx)(z,{label:`Month Avg Saved`,value:zt(p.avgCacheSavedPercent)})]})})]})]})}function Kh({label:e,value:t,color:n,subtitle:r}){return(0,P.jsxs)(`section`,{className:`surface-card`,style:{padding:`var(--space-4) var(--space-5)`},children:[(0,P.jsx)(`span`,{style:{fontSize:`var(--text-xs)`,fontWeight:600,textTransform:`uppercase`,letterSpacing:`0.04em`,color:`var(--text-muted)`},children:e}),(0,P.jsx)(`span`,{style:{display:`block`,marginTop:4,fontSize:`var(--text-2xl)`,fontWeight:700,letterSpacing:`-0.04em`,color:n||`var(--text-primary)`,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:t}),r&&(0,P.jsx)(`span`,{style:{fontSize:`0.65rem`,color:`var(--text-muted)`},children:r})]})}function qh({options:e,value:t,onChange:n,size:r}){return(0,P.jsx)(`div`,{style:{display:`inline-flex`,borderRadius:`var(--radius-pill)`,overflow:`hidden`,border:`1px solid var(--line)`,background:`var(--surface-muted)`},children:e.map(e=>(0,P.jsx)(`button`,{onClick:()=>n(e.value),style:{padding:r===`sm`?`var(--space-1) var(--space-3)`:`var(--space-2) var(--space-4)`,fontSize:`var(--text-xs)`,fontWeight:600,cursor:`pointer`,background:t===e.value?`var(--accent)`:`transparent`,color:t===e.value?`#fff`:`var(--text-secondary)`,border:`none`,minHeight:r===`sm`?28:34,transition:`background var(--animation-fast), color var(--animation-fast)`},children:e.label},e.value))})}var Jh=6e4;function Yh(){let[e,t]=(0,v.useState)([]),[n,r]=(0,v.useState)([]),[i,a]=(0,v.useState)(!0),[o,s]=(0,v.useState)(!1),[c,l]=(0,v.useState)(!0),[u,d]=(0,v.useState)(60),[f,p]=(0,v.useState)(null),m=(0,v.useRef)(null),h=(0,v.useRef)(null),g=(0,v.useCallback)(async()=>{try{s(!0);let[e,n]=await Promise.all([D(),oe()]);t(e.providerOptions||e.providers||[]),r(n.providers||[]),p(new Date),d(60)}catch(e){console.error(`Failed to fetch quota data:`,e)}finally{a(!1),s(!1)}},[]);(0,v.useEffect)(()=>{g()},[g]),(0,v.useEffect)(()=>{if(!c){m.current&&clearInterval(m.current),h.current&&clearInterval(h.current);return}return m.current=setInterval(g,Jh),h.current=setInterval(()=>{d(e=>e<=1?60:e-1)},1e3),()=>{m.current&&clearInterval(m.current),h.current&&clearInterval(h.current)}},[c,g]);let _=(0,v.useMemo)(()=>{let t=new Map;for(let e of n)e.providerId&&t.set(e.providerId,e);return e.map(e=>{let n=t.get(e.id),r=n&&Rt(n.usage)?n.usage:null;return{id:e.id,name:e.name,live:n,ok:n?.ok!==!1&&r?.allowed!==!1,allowed:r?.allowed,remaining:typeof r?.remaining==`number`?r.remaining:void 0,limit:typeof r?.limit==`number`?r.limit:void 0,used:typeof r?.used==`number`?r.used:void 0,error:n?.error,hasQuota:n!==void 0}})},[e,n]),y=(0,v.useMemo)(()=>_.filter(e=>e.hasQuota),[_]);return i?(0,P.jsx)(jt,{title:`Loading quotas`,description:`Fetching provider quota status...`,cards:4}):(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{title:`Quota Tracker`,description:`Real-time provider quota limits and usage status.`,actions:(0,P.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`var(--space-2)`},children:[(0,P.jsxs)(`button`,{onClick:()=>l(e=>!e),className:`button-link`,style:{minHeight:36,gap:`var(--space-2)`},title:c?`Disable auto-refresh`:`Enable auto-refresh`,children:[(0,P.jsx)(`span`,{style:{color:c?`var(--accent)`:`var(--text-muted)`},children:c?`⟳`:`⏸`}),(0,P.jsx)(`span`,{children:`Auto`}),c&&(0,P.jsxs)(`span`,{style:{fontSize:`var(--text-xs)`,color:`var(--text-muted)`,fontVariantNumeric:`tabular-nums`},children:[`(`,u,`s)`]})]}),(0,P.jsx)($t,{onClick:g,isRefreshing:o})]})}),f&&(0,P.jsxs)(`p`,{style:{fontSize:`var(--text-xs)`,color:`var(--text-muted)`,margin:0},children:[`Last updated: `,f.toLocaleTimeString()]}),y.length===0?(0,P.jsx)(V,{children:(0,P.jsxs)(`div`,{style:{textAlign:`center`,padding:`var(--space-8)`},children:[(0,P.jsx)(`p`,{style:{fontSize:`var(--text-base)`,fontWeight:600,margin:`0 0 var(--space-2)`},children:`No Quota Data Available`}),(0,P.jsx)(`p`,{style:{fontSize:`var(--text-sm)`,color:`var(--text-secondary)`,margin:0,maxWidth:400,marginInline:`auto`},children:`Connect providers with quota tracking (OAuth subscriptions like Claude Code, Codex) to see quota limits and usage here.`})]})}):(0,P.jsx)(`div`,{style:{display:`grid`,gridTemplateColumns:`repeat(auto-fit, minmax(320px, 1fr))`,gap:`var(--space-4)`},children:y.map(e=>(0,P.jsx)(Xh,{provider:e,onRefresh:g},e.id))})]})}function Xh({provider:e,onRefresh:t}){let n=e.limit&&e.limit>0?Math.round((e.used||0)/e.limit*100):null,r=n===null?null:100-n;return(0,P.jsxs)(`section`,{className:`surface-card`,style:{padding:0,overflow:`hidden`},children:[(0,P.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:`var(--space-3)`,padding:`var(--space-3) var(--space-4)`,borderBottom:`1px solid var(--line)`},children:[(0,P.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`var(--space-3)`,minWidth:0},children:[(0,P.jsx)(`div`,{style:{width:32,height:32,borderRadius:8,background:`var(--accent-soft)`,display:`flex`,alignItems:`center`,justifyContent:`center`,flexShrink:0},children:(0,P.jsx)(`span`,{style:{fontSize:14,fontWeight:700,color:`var(--accent)`},children:e.name.charAt(0).toUpperCase()})}),(0,P.jsx)(`div`,{style:{minWidth:0},children:(0,P.jsx)(`h3`,{style:{margin:0,fontSize:`var(--text-sm)`,fontWeight:600,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:e.name})})]}),(0,P.jsx)(B,{status:e.ok?`success`:`danger`,children:e.ok?`Active`:e.error?`Error`:`Exhausted`})]}),(0,P.jsx)(`div`,{style:{padding:`var(--space-3) var(--space-4)`},children:e.error?(0,P.jsx)(`p`,{style:{margin:0,fontSize:`var(--text-xs)`,color:`var(--danger)`},children:e.error}):e.limit===void 0?(0,P.jsx)(`p`,{style:{margin:0,fontSize:`var(--text-xs)`,color:`var(--text-muted)`,textAlign:`center`,padding:`var(--space-2)`},children:e.ok?`Connected — no quota limits reported`:`Unable to fetch quota`}):(0,P.jsxs)(`div`,{style:{display:`grid`,gap:`var(--space-3)`},children:[(0,P.jsxs)(`div`,{children:[(0,P.jsxs)(`div`,{style:{display:`flex`,justifyContent:`space-between`,marginBottom:4},children:[(0,P.jsxs)(`span`,{style:{fontSize:`var(--text-xs)`,color:`var(--text-muted)`},children:[L(e.remaining),` remaining`]}),(0,P.jsx)(`span`,{style:{fontSize:`var(--text-xs)`,fontWeight:600},children:r===null?`—`:`${r}%`})]}),(0,P.jsx)(`div`,{style:{height:8,borderRadius:`var(--radius-pill)`,background:`var(--neutral-soft)`,overflow:`hidden`},children:(0,P.jsx)(`div`,{style:{height:`100%`,width:`${r??0}%`,borderRadius:`var(--radius-pill)`,background:!e.ok||r!==null&&r<=10?`var(--danger)`:r!==null&&r<=30?`var(--warning)`:`var(--success)`,transition:`width var(--animation-slow) var(--animation-easing)`}})})]}),(0,P.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`1fr 1fr 1fr`,gap:`var(--space-2)`},children:[(0,P.jsxs)(`div`,{style:{textAlign:`center`},children:[(0,P.jsx)(`span`,{style:{display:`block`,fontSize:`var(--text-xs)`,color:`var(--text-muted)`},children:`Used`}),(0,P.jsx)(`span`,{style:{display:`block`,fontSize:`var(--text-sm)`,fontWeight:600},children:L(e.used)})]}),(0,P.jsxs)(`div`,{style:{textAlign:`center`},children:[(0,P.jsx)(`span`,{style:{display:`block`,fontSize:`var(--text-xs)`,color:`var(--text-muted)`},children:`Remaining`}),(0,P.jsx)(`span`,{style:{display:`block`,fontSize:`var(--text-sm)`,fontWeight:600,color:`var(--success)`},children:L(e.remaining)})]}),(0,P.jsxs)(`div`,{style:{textAlign:`center`},children:[(0,P.jsx)(`span`,{style:{display:`block`,fontSize:`var(--text-xs)`,color:`var(--text-muted)`},children:`Limit`}),(0,P.jsx)(`span`,{style:{display:`block`,fontSize:`var(--text-sm)`,fontWeight:600},children:L(e.limit)})]})]})]})})]})}var Zh=[{id:`antigravity`,name:`Antigravity (Google)`,color:`#4285F4`,description:`Google Antigravity IDE — intercepts daily-cloudcode-pa.googleapis.com`,mitmDomain:`daily-cloudcode-pa.googleapis.com`,models:[{id:`gemini-3.5-flash-low`,name:`Gemini 3.5 Flash (Medium)`},{id:`gemini-3-flash-agent`,name:`Gemini 3.5 Flash (High)`},{id:`claude-sonnet-4-6`,name:`Claude Sonnet 4.6 (Thinking)`},{id:`claude-opus-4-6-thinking`,name:`Claude Opus 4.6 (Thinking)`}]},{id:`copilot`,name:`GitHub Copilot`,color:`#1F6FEB`,description:`GitHub Copilot IDE — intercepts api.individual.githubcopilot.com`,mitmDomain:`api.individual.githubcopilot.com`,models:[{id:`gpt-4o`,name:`GPT-4o`},{id:`gpt-4.1`,name:`GPT-4.1`},{id:`claude-haiku-4.5`,name:`Claude Haiku 4.5`}]},{id:`kiro`,name:`Kiro IDE`,color:`#FF6B00`,description:`Kiro IDE — intercepts q.us-east-1.amazonaws.com`,mitmDomain:`q.us-east-1.amazonaws.com`,models:[{id:`claude-sonnet-4.5`,name:`Claude Sonnet 4.5`},{id:`claude-sonnet-4`,name:`Claude Sonnet 4`},{id:`deepseek-3.2`,name:`DeepSeek 3.2`},{id:`minimax-m2.1`,name:`MiniMax M2.1`}]}];function Qh(){let[e,t]=(0,v.useState)(null),[n,r]=(0,v.useState)(!0),[i,a]=(0,v.useState)(null),[o,s]=(0,v.useState)(``),[c,l]=(0,v.useState)(!1),[u,d]=(0,v.useState)(null),f=(0,v.useCallback)(async()=>{try{let e=await fetch(`/api/cli-tools/mitm-status`);e.ok?t(await e.json()):t({running:!1,certExists:!1,certTrusted:!1,dnsStatus:{}})}catch{t({running:!1,certExists:!1,certTrusted:!1,dnsStatus:{}})}finally{r(!1)}},[]);(0,v.useEffect)(()=>{f()},[f]);let p=t=>{o||e?.needsSudoPassword===!1?t(o):(d(()=>t),l(!0))},m=()=>{l(!1),u&&(u(o),d(null))};if(n)return(0,P.jsx)(jt,{title:`Loading MITM status`,description:`Checking MITM server and certificates...`,cards:3});let h=e?.running||!1;return(0,P.jsxs)(`div`,{className:`screen-stack`,children:[(0,P.jsx)(I,{title:`MITM Proxy`,description:`Intercept IDE HTTPS traffic to route through your providers.`}),(0,P.jsxs)(`div`,{style:{display:`flex`,alignItems:`flex-start`,gap:`var(--space-3)`,padding:`var(--space-3) var(--space-4)`,borderRadius:`var(--radius-md)`,background:`var(--warning-soft)`,border:`1px solid color-mix(in srgb, var(--warning) 30%, transparent)`},children:[(0,P.jsx)(`span`,{style:{color:`var(--warning)`,fontSize:`16px`,marginTop:2,flexShrink:0},children:`⚠️`}),(0,P.jsx)(`p`,{style:{margin:0,fontSize:`var(--text-xs)`,color:`var(--danger)`,lineHeight:1.5},children:`MITM intercepts HTTPS traffic of IDE tools (Antigravity, GitHub Copilot, Kiro) via local CA to redirect requests to your providers. May violate ToS → account ban. Use at your own risk.`})]}),(0,P.jsx)($h,{status:e,isRunning:h,onRefresh:f,withSudo:p}),(0,P.jsx)(`div`,{style:{display:`grid`,gap:`var(--space-3)`},children:Zh.map(t=>(0,P.jsx)(eg,{tool:t,isExpanded:i===t.id,onToggle:()=>a(i===t.id?null:t.id),serverRunning:h,dnsActive:e?.dnsStatus?.[t.id]||!1,withSudo:p,onDnsChanged:f},t.id))}),c&&(0,P.jsx)(`div`,{className:`modal-backdrop`,role:`presentation`,onClick:()=>l(!1),children:(0,P.jsxs)(`div`,{className:`modal-card`,role:`dialog`,"aria-modal":`true`,onClick:e=>e.stopPropagation(),style:{maxWidth:380},children:[(0,P.jsx)(`div`,{className:`modal-header`,children:(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`p`,{className:`eyebrow`,children:`Sudo Required`}),(0,P.jsx)(`h2`,{children:`Enter Mac Password`})]})}),(0,P.jsxs)(`div`,{style:{padding:`0 var(--space-5) var(--space-4)`},children:[(0,P.jsx)(`p`,{style:{margin:`0 0 var(--space-3)`,fontSize:`var(--text-xs)`,color:`var(--text-secondary)`},children:`Modifying /etc/hosts requires administrator privileges.`}),(0,P.jsx)(`input`,{type:`password`,value:o,onChange:e=>s(e.target.value),onKeyDown:e=>{e.key===`Enter`&&m()},placeholder:`Mac login password`,autoFocus:!0,style:{minHeight:42}})]}),(0,P.jsxs)(`div`,{className:`modal-actions`,style:{padding:`var(--space-3) var(--space-5)`},children:[(0,P.jsx)(`button`,{className:`button-link`,onClick:()=>{l(!1),d(null)},children:`Cancel`}),(0,P.jsx)(`button`,{className:`button-primary`,onClick:m,disabled:!o,children:`Confirm`})]})]})})]})}function $h({status:e,isRunning:t,onRefresh:n,withSudo:r}){let[i,a]=(0,v.useState)(!1),[o,s]=(0,v.useState)(null);return(0,P.jsx)(`section`,{className:`surface-card surface-card-info`,style:{padding:`var(--space-4) var(--space-5)`},children:(0,P.jsxs)(`div`,{style:{display:`grid`,gap:`var(--space-4)`},children:[(0,P.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,flexWrap:`wrap`,gap:`var(--space-3)`},children:[(0,P.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`var(--space-3)`},children:[(0,P.jsx)(`span`,{style:{fontSize:20,color:`var(--accent)`},children:`🔒`}),(0,P.jsx)(`span`,{style:{fontWeight:600,fontSize:`var(--text-sm)`},children:`MITM Server`}),(0,P.jsx)(B,{status:t?`success`:`neutral`,children:t?`Running`:`Stopped`})]}),(0,P.jsxs)(`div`,{style:{display:`flex`,gap:`var(--space-3)`,fontSize:`var(--text-xs)`,color:`var(--text-muted)`},children:[(0,P.jsx)(tg,{label:`Cert`,ok:e?.certExists}),(0,P.jsx)(tg,{label:`Trusted`,ok:e?.certTrusted}),(0,P.jsx)(tg,{label:`Server`,ok:t})]})]}),(0,P.jsxs)(`div`,{style:{padding:`var(--space-3)`,background:`var(--surface-muted)`,borderRadius:`var(--radius-sm)`,border:`1px solid var(--line)`},children:[(0,P.jsxs)(`p`,{style:{margin:`0 0 4px`,fontSize:`0.68rem`,color:`var(--text-secondary)`},children:[(0,P.jsx)(`strong`,{style:{color:`var(--text-primary)`},children:`Purpose:`}),` Use Antigravity IDE & GitHub Copilot with ANY provider/model from the proxy`]}),(0,P.jsxs)(`p`,{style:{margin:0,fontSize:`0.68rem`,color:`var(--text-secondary)`},children:[(0,P.jsx)(`strong`,{style:{color:`var(--text-primary)`},children:`How it works:`}),` IDE request → DNS redirect to localhost:443 → MITM intercepts → Proxy routes → response to IDE`]})]}),(0,P.jsxs)(`div`,{style:{display:`flex`,gap:`var(--space-2)`,flexWrap:`wrap`,alignItems:`center`},children:[t?(0,P.jsx)(`button`,{className:`button-danger`,onClick:()=>{r(async e=>{a(!0),s(null);try{let t=await fetch(`/api/cli-tools/mitm-stop`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({sudoPassword:e})});t.ok?await n():s((await t.json().catch(()=>({}))).error||`Failed to stop MITM server`)}catch(e){s(e.message||`Network error`)}finally{a(!1)}})},disabled:i,style:{minHeight:36},children:i?`Stopping...`:`Stop Server`}):(0,P.jsx)(`button`,{className:`button-primary`,onClick:()=>{r(async e=>{a(!0),s(null);try{let t=await fetch(`/api/cli-tools/mitm-start`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({sudoPassword:e})});t.ok?await n():s((await t.json().catch(()=>({}))).error||`Failed to start MITM server`)}catch(e){s(e.message||`Network error`)}finally{a(!1)}})},disabled:i,style:{minHeight:36},children:i?`Starting...`:`Start Server`}),(0,P.jsx)(`button`,{className:`button-link`,onClick:n,style:{minHeight:36},children:`Refresh Status`}),t&&(0,P.jsx)(`span`,{style:{fontSize:`var(--text-xs)`,color:`var(--text-muted)`},children:`Enable DNS per tool below to activate interception`})]}),o&&(0,P.jsx)(`div`,{style:{padding:`var(--space-2) var(--space-3)`,background:`var(--danger-soft)`,borderRadius:`var(--radius-sm)`,fontSize:`var(--text-xs)`,color:`var(--danger)`},children:o})]})})}function eg({tool:e,isExpanded:t,onToggle:n,serverRunning:r,dnsActive:i,withSudo:a,onDnsChanged:o}){let[s,c]=(0,v.useState)(!1),[l,u]=(0,v.useState)(``);return(0,P.jsxs)(`section`,{className:`surface-card`,style:{padding:0,overflow:`hidden`},children:[(0,P.jsxs)(`div`,{onClick:n,style:{display:`flex`,alignItems:`center`,gap:`var(--space-3)`,padding:`var(--space-3) var(--space-4)`,cursor:`pointer`},children:[(0,P.jsx)(`div`,{style:{width:32,height:32,borderRadius:8,flexShrink:0,background:`${e.color}18`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,P.jsx)(`span`,{style:{fontSize:14,fontWeight:700,color:e.color},children:e.name.charAt(0)})}),(0,P.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,P.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`var(--space-2)`},children:[(0,P.jsx)(`h3`,{style:{margin:0,fontSize:`var(--text-sm)`,fontWeight:600},children:e.name}),i&&(0,P.jsx)(B,{status:`success`,children:`Intercepting`})]}),(0,P.jsx)(`p`,{style:{margin:`2px 0 0`,fontSize:`var(--text-xs)`,color:`var(--text-muted)`,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:e.mitmDomain})]}),(0,P.jsx)(`span`,{style:{color:`var(--text-muted)`,transition:`transform var(--animation-normal)`,transform:t?`rotate(180deg)`:`none`},children:`▾`})]}),t&&(0,P.jsxs)(`div`,{style:{borderTop:`1px solid var(--line)`,padding:`var(--space-4)`,display:`grid`,gap:`var(--space-3)`},children:[(0,P.jsx)(`p`,{style:{margin:0,fontSize:`var(--text-xs)`,color:`var(--text-secondary)`},children:e.description}),(0,P.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,padding:`var(--space-2) var(--space-3)`,background:`var(--surface-muted)`,borderRadius:`var(--radius-sm)`,border:`1px solid var(--line)`},children:[(0,P.jsx)(`span`,{style:{fontSize:`var(--text-xs)`,fontWeight:600},children:`DNS Interception`}),(0,P.jsx)(`button`,{onClick:()=>{a(async t=>{c(!0),u(``);try{let n=await fetch(`/api/cli-tools/mitm-dns`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({toolId:e.id,enable:!i,sudoPassword:t})});n.ok?o():u((await n.json().catch(()=>({}))).error||`Failed to update DNS`)}catch(e){u(e.message||`Network error`)}finally{c(!1)}})},disabled:!r||s,style:{position:`relative`,display:`inline-flex`,width:36,height:20,borderRadius:`var(--radius-pill)`,border:`none`,background:i?`var(--success)`:`var(--neutral-soft)`,cursor:r?`pointer`:`not-allowed`,opacity:r?1:.5,padding:0,transition:`background var(--animation-normal)`},title:r?i?`Disable DNS interception`:`Enable DNS interception`:`Start MITM server first`,children:(0,P.jsx)(`span`,{style:{position:`absolute`,top:2,left:i?18:2,width:16,height:16,borderRadius:`50%`,background:`#fff`,boxShadow:`0 2px 4px rgba(0,0,0,0.2)`,transition:`left var(--animation-normal)`}})})]}),l&&(0,P.jsx)(`div`,{style:{padding:`var(--space-2) var(--space-3)`,background:`var(--danger-soft)`,borderRadius:`var(--radius-sm)`,fontSize:`var(--text-xs)`,color:`var(--danger)`},children:l}),(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`span`,{style:{fontSize:`var(--text-xs)`,fontWeight:600,color:`var(--text-muted)`,display:`block`,marginBottom:`var(--space-2)`},children:`Available Models`}),(0,P.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:4},children:e.models.map(e=>(0,P.jsx)(`code`,{className:`metadata-pill`,style:{fontSize:`0.6rem`,padding:`2px 6px`,minHeight:`auto`},children:e.name},e.id))})]}),(0,P.jsxs)(`div`,{style:{fontSize:`var(--text-xs)`,color:`var(--text-muted)`},children:[(0,P.jsx)(`strong`,{children:`Target domain:`}),` `,(0,P.jsx)(`code`,{style:{fontSize:`0.65rem`},children:e.mitmDomain})]})]})]})}function tg({label:e,ok:t}){return(0,P.jsxs)(`span`,{style:{display:`inline-flex`,alignItems:`center`,gap:3},children:[(0,P.jsx)(`span`,{style:{color:t?`var(--success)`:`var(--text-muted)`,fontSize:`0.7rem`},children:t?`✓`:`✗`}),e]})}var ng=`responses-proxy-theme`,rg=`endpoint`,ig=[...pt,...mt],ag=new Set(ig.map(e=>e.route));Object.keys(ft).forEach(e=>{let t=ht(e);t&&ag.add(t)});function og(e){try{return decodeURIComponent(e)}catch{return e}}function sg(){let e=window.location.hash.replace(/^#\/?/,``).trim().split(`/`).filter(Boolean),t=e[0];if(!t)return{route:rg,baseRoute:rg,params:{},isUnknown:!1};let n=ht(t);if(n&&(t=n),!ag.has(t))return{route:rg,baseRoute:rg,params:{},isUnknown:!0};let r=t,i=e[1]?og(e[1]):``;return r===`providers`?i===`new`?{route:`provider-new`,baseRoute:r,params:{},isUnknown:e.length>2}:{route:i?`provider-detail`:`providers`,baseRoute:r,params:i?{providerId:i}:{},isUnknown:e.length>2}:r===`clients`?{route:i?`client-detail`:`clients`,baseRoute:r,params:i?{clientKey:i}:{},isUnknown:e.length>2}:r===`oauth`?{route:i?`account-detail`:`oauth`,baseRoute:r,params:i?{accountId:i}:{},isUnknown:e.length>2}:r===`kiro`?{route:i?`account-detail`:`oauth`,baseRoute:`oauth`,params:i?{accountId:i}:{},isUnknown:e.length>2}:{route:r,baseRoute:r,params:{},isUnknown:e.length>1}}function cg(){try{let e=window.localStorage.getItem(ng);if(e===`light`||e===`dark`)return e}catch{}return`light`}function lg(e){if(e.isUnknown)return(0,P.jsx)(At,{title:`Route not found`,description:`This dashboard uses the current React route map. Return to Endpoint to continue.`,actionHref:`#/endpoint`,actionLabel:`Go to Endpoint`});switch(e.route){case`endpoint`:return(0,P.jsx)(fm,{});case`combos`:return(0,P.jsx)(Sn,{});case`quota-tracker`:return(0,P.jsx)(Yh,{});case`mitm`:return(0,P.jsx)(Qh,{});case`cli-tools`:return(0,P.jsx)(On,{});case`media-providers`:return(0,P.jsx)(Mm,{});case`proxy-pools`:return(0,P.jsx)(Nm,{});case`skills`:return(0,P.jsx)(Vh,{});case`console-log`:return(0,P.jsx)(on,{});case`settings`:return(0,P.jsx)(rn,{});case`providers`:return(0,P.jsx)(jm,{});case`provider-new`:return(0,P.jsx)(Eh,{});case`provider-detail`:return(0,P.jsx)(Sh,{providerId:e.params.providerId});case`clients`:return(0,P.jsx)(vn,{});case`client-detail`:return(0,P.jsx)(vn,{clientKey:e.params.clientKey});case`oauth`:return(0,P.jsx)(Qt,{initialTab:window.location.hash.includes(`/kiro`)?`kiro`:`oauth`});case`account-detail`:return(0,P.jsx)(Qt,{accountId:e.params.accountId});case`auth-management`:return(0,P.jsx)(rn,{});case`config-helper`:return(0,P.jsx)(Rn,{});case`usage`:return(0,P.jsx)(Gh,{});case`rtk`:return(0,P.jsx)(Vh,{});case`cache`:return(0,P.jsx)(an,{});case`dashboard`:return(0,P.jsx)(Rp,{});default:return(0,P.jsx)(fm,{})}}function ug(){let[e,t]=(0,v.useState)(sg),[n,r]=(0,v.useState)(cg),[i,a]=(0,v.useState)({status:`loading`});(0,v.useEffect)(()=>{document.documentElement.dataset.theme=n,document.documentElement.style.colorScheme=n;try{window.localStorage.setItem(ng,n)}catch{}},[n]),(0,v.useEffect)(()=>{let e=!1;return S().then(t=>{e||a(t.authenticated&&t.session?{status:`authenticated`,session:t.session}:{status:`anonymous`})}).catch(()=>{e||a({status:`anonymous`})}),()=>{e=!0}},[]),(0,v.useEffect)(()=>{window.location.hash||window.history.replaceState(null,``,`#/endpoint`);let e=()=>t(sg());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]);let o=(0,v.useCallback)(()=>{r(e=>e===`dark`?`light`:`dark`)},[]),s=(0,v.useCallback)(async()=>{await T().catch(()=>void 0),a({status:`anonymous`})},[]),c=(0,v.useCallback)(e=>{window.location.hash=`#/${e}`},[]),l=(0,v.useMemo)(()=>lg(e),[e]);return i.status===`loading`?(0,P.jsx)(`div`,{className:`app-page`,children:(0,P.jsx)(`main`,{className:`app-panel`,children:(0,P.jsx)(jt,{title:`Checking dashboard login`,description:`Validating your admin session.`,cards:3})})}):i.status===`anonymous`?(0,P.jsx)(pm,{onAuthenticated:e=>a({status:`authenticated`,session:e})}):(0,P.jsx)(Pt,{children:(0,P.jsx)(kt,{currentRoute:e.baseRoute,theme:n,session:i.session,onToggleTheme:o,onLogout:s,onNavigate:c,children:l})})}(0,y.createRoot)(document.getElementById(`root`)).render((0,P.jsx)(v.StrictMode,{children:(0,P.jsx)(ug,{})}));
|
package/dist/client/index.html
CHANGED
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
margin: 0;
|
|
23
23
|
}
|
|
24
24
|
</style>
|
|
25
|
-
<script type="module" crossorigin src="/assets/index-
|
|
25
|
+
<script type="module" crossorigin src="/assets/index-D4Ktr4qL.js"></script>
|
|
26
26
|
<link rel="stylesheet" crossorigin href="/assets/index-DpqgYK3L.css">
|
|
27
27
|
</head>
|
|
28
28
|
<body>
|
package/dist/package.json
CHANGED